コード例 #1
0
def reShuffleList(trialList):

    # We need to CONSTRAIN HERE, the list so that no 2 oddballs are for example right after each other 
    # i.e. we could "freeze" certain elements of the list, specified in the input .csv -file
    # e.g. http://stackoverflow.com/questions/12238005/python-shuffling-list-but-keeping-some-elements-frozen
    
    # a bit non-elegant way to extract to the flags for the freeze from the csv-file
    '''
    for index, item in enumerate(irregularTargets.trialList):        
        print "index = ", index
        freezeBooleanFlag = item.freeze        
        print "freeze = ", freezeBooleanFlag    
    '''
     
    # memorize position of fixed elements   
    fixed = [(pos, item) for (pos,item) in enumerate(trialList) if item.freeze]
    # print " "
    # print "FIXED: \n", fixed
    # print " "
    
    # shuffle list
    random.shuffle(trialList)
    # print "Shuffle, 1st Pass: \n", trialList
    # print " "
    
    # swap fixed elements back to their original position
    for pos, item in fixed:        
        index = trialList.index(item)
        trialList[pos], trialList[index] = trialList[index], trialList[pos]
    
    # print "Shuffled List \n", trialList # print shuffled irregularTargets
    # print " "
    return trialList
コード例 #2
0
ファイル: Application.py プロジェクト: Ducuvlad/Knight-s-tour
def main(size, popsize):
    """
    Make a horse happy by guiding it to a path on the chessboard in such a way that it
    moves to every single square once and only once. The little horsie can jump obviously
    only in the classic L shape (the chess’ horse move).

    Generate random permutations of chess board squares
    Find best individual
    Show statistics

    :param size: Size of the chess board
    :param popsize: Size of population
    """
    print("Running")
    tuples = []
    popl = []
    for i in range(size):
        for j in range(size):
            tuples.append((i, j))
    for i in range(popsize):
        random.shuffle(tuples)
        individ = Individual(size, deepcopy(tuples))
        popl.append(deepcopy(individ))
    finpop = population(popsize, popl, size)
    algo = Algorithm(size, finpop)

    evaluation, fitness, iter = algo.run()
    #statistics
    plt.plot(range(iter), fitness, label='BestFitness vs iteration')

    plt.xlabel('Iteration')
    plt.ylabel('BestFitness')
    plt.title("BestFitness evolution")
    plt.legend()
    plt.show()
コード例 #3
0
ファイル: GA.py プロジェクト: ywzhang909/tsp
 def initPopulation(self):
     """初始化种群"""
     self.lives = []
     for i in range(self.lifeCount):
         gene = range(self.geneLenght)
         random.shuffle(gene)
         life = Life(gene)
         self.lives.append(life)
コード例 #4
0
ファイル: GA.py プロジェクト: ywzhang909/tsp
 def initPopulation(self):
     """初始化种群"""
     self.lives = []
     for i in range(self.lifeCount):
         gene = range(self.geneLenght)
         random.shuffle(gene)
         life = Life(gene)
         self.lives.append(life)
コード例 #5
0
ファイル: MAFE4ImagesEEG.py プロジェクト: risoms/mdl-R56
def choose_female_images():
    my_faces = []
    my_faces.extend(np.random.choice(sad_female_images, 2, False))
    my_faces.extend(np.random.choice(neutral_female_images, 2, False))
    random.shuffle(my_faces)
    for i in range(len(my_faces)):
        my_faces[i].setPos(newPos=locations[i])
        thisExp.addData("Image" + str(i) + " _Position", my_faces[i].name)
    return my_faces
コード例 #6
0
def generate_trials(trial_type_column, multiplier):
    """Generate a shuffled list of stimuli exemplars from a column in an excel stimuli file""" 
    a = dict()  # declare a dict to be populated
    for i in range(len(exemplars)):
        a[i] = [exemplars[i][trial_type_column]] * multiplier  # populate the dict from vertical reads of the conditions
    a = a.values()  # extract only values (and not keys) from the list of dicts
    a = list(itertools.chain(*a))  # flatten the list of dicts into a list
    random.shuffle(a)  # shuffle this list, so that it can be drawn from by the trials
    return a
コード例 #7
0
def generate_trials(trial_type_column, multiplier):
    """Generate a shuffled list of stimuli exemplars from a column in an excel stimuli file"""
    a = dict()  # declare a dict to be populated
    for i in range(len(exemplars)):
        a[i] = [
            exemplars[i][trial_type_column]
        ] * multiplier  # populate the dict from vertical reads of the conditions
    a = a.values()  # extract only values (and not keys) from the list of dicts
    a = list(itertools.chain(*a))  # flatten the list of dicts into a list
    random.shuffle(
        a)  # shuffle this list, so that it can be drawn from by the trials
    return a
コード例 #8
0
ファイル: BPR.py プロジェクト: RecSys-Group/Recommender
 def generate_samples(self,dataModel,max_samples=None):
     self.init(dataModel, max_samples)
     idxs = range(self.dataModel.getData().nnz)
     random.shuffle(idxs)
     self.users, self.items = self.dataModel.getData().nonzero()
     self.users = self.users[idxs]
     self.items = self.items[idxs]
     self.idx = 0
     for _ in xrange(self.num_samples(self.dataModel.getData().nnz)):
         u = self.users[self.idx]
         i = self.items[self.idx]
         j = self.sample_negative_item(self.dataModel.getItemIDsFromUid(u))
         self.idx += 1
         yield u, i, j
コード例 #9
0
 def generate_samples(self, dataModel, max_samples=None):
     self.init(dataModel, max_samples)
     idxs = range(self.dataModel.getData().nnz)
     random.shuffle(idxs)
     self.users, self.items = self.dataModel.getData().nonzero()
     self.users = self.users[idxs]
     self.items = self.items[idxs]
     self.idx = 0
     for _ in xrange(self.num_samples(self.dataModel.getData().nnz)):
         u = self.users[self.idx]
         i = self.items[self.idx]
         j = self.sample_negative_item(self.dataModel.getItemIDsFromUid(u))
         self.idx += 1
         yield u, i, j
コード例 #10
0
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
コード例 #11
0
def batch_generator_train(files,
                          train_csv_table,
                          batch_size,
                          npy=False,
                          cv3D_size=512,
                          from_gray_to_rgb=False):
    number_of_batches = np.ceil(len(files) / batch_size)
    counter = 0
    random.shuffle(files)
    next_files = copy.deepcopy(files)
    failed = 0

    while True:
        # batch_files = files[batch_size*counter+failed:batch_size*(counter+1)+failed]
        image_list = []
        mask_list = []
        success = 0
        problem_files = []

        # for f in files[batch_size*counter+failed:]:
        for f in files[batch_size * counter:batch_size * (counter + 1)]:
            # if success==batch_size:
            #     break
            if npy:
                try:
                    image = load_and_normalize_dicom(f, cv3D_size, cv3D_size,
                                                     npy, cv3D_size)
                    success += 1
                except:
                    # print('Problem with:', f)
                    failed += 1
                    try:
                        next_files.remove(f)
                    except:
                        pass
                    problem_files.append(f)
                    batch_files = files[batch_size * counter +
                                        failed:batch_size * (counter + 1) +
                                        failed]

                    continue
                    # img = np.load(f)
                    # print(img.shape)
                # print(image.shape)
                patient_id = os.path.basename(f.replace('.npy', ''))
            else:
                image = load_and_normalize_dicom(f, cv3D_size, cv3D_size)

                patient_id = os.path.basename(os.path.dirname(f))
                success += 1
            try:
                is_cancer = train_csv_table.loc[train_csv_table['id'] ==
                                                patient_id]['cancer'].values[0]

                if is_cancer == 0:
                    mask = [1, 0]
                    # mask = [1]
                else:
                    mask = [0, 1]
                    # mask = [0]
            except:
                # print('Problem with %s' % patient_id)
                mask = [0.5, 0.5]
            if npy:
                if from_gray_to_rgb:
                    image_list.append(np.repeat(image, 3, axis=0))
                else:
                    image_list.append(image)
            else:
                if from_gray_to_rgb:
                    image_list.append([image] * 3)
                else:
                    image_list.append([image])
            mask_list.append(mask)
        # print(Counter([image[0].shape for image in image_list]))
        counter += 1
        if npy:
            npy_image_list = np.zeros(
                (batch_size, 1, cv3D_size, cv3D_size, cv3D_size))
            for i, image in enumerate(image_list):
                len_image = min(len(image), 512)
                # print(len_image)
                # image = np.expand_dims(np.expand_dims(image[:512], 1),0)
                # print(image.shape)
                # print(len_image)

                npy_image_list[i, 0, :len_image, :, :] = image[:512]

            image_list = npy_image_list
        else:
            image_list = np.array(image_list)
        # print(image_list.shape)
        # print(image_list[0].shape)
        mask_list = np.array(mask_list)
        # print(image_list.shape)
        # print(image_list.shape)
        # print(mask_list.shape)
        if len(mask_list) > 0:
            # image_list = np.swapaxes(image_list,1,2)
            image_list.astype(np.int32)
            # print(image_list.shape)

            # print(image_list.nbytes)
            yield image_list, mask_list
        else:
            # print(image_list)
            print(mask_list)
            print(patient_id)
            # print(image_list.shape)
            failed += 1
            try:
                next_files.remove(f)
            except:
                pass

            yield np.zeros((batch_size, 1, cv3D_size, cv3D_size,
                            cv3D_size)), np.array([[0]])

        if counter == number_of_batches:
            # print('Reported %s problems with files this epoch' % (len(files)-len(next_files)))
            # files = next_files
            # next_files = copy.deepcopy(files)
            # print('length of new file list: %s' % len(files))

            random.shuffle(files)
            counter = 0
            failed = 0
コード例 #12
0
# Initialize components for Routine "Initialize"
InitializeClock = core.Clock()
# In this script I use a csv file to define my variables as opposed to explicity defining them in my code. 
# I then use the participant's number and the session number to create personalized order files, in case that would be helpful

import csv
import random 

with open("RunC_Jitter.csv") as f:
    reader = csv.DictReader(f)
    jitters = [row["ISI_duration"] for row in reader]

participant_id = expInfo["participant"]
session_id = expInfo["session"]

random.shuffle(jitters)

# get image names and expressions
condition_input_file = "RunC_ConditionsInputFile.csv"
with open(condition_input_file) as f:
    reader = csv.DictReader(f)
    input_rows = [row["ImageFile"] for row in reader]

output_rows = [(input_row, jitter) for input_row, jitter in zip(input_rows, jitters)]

# write image names, expressions, and jitters
condition_output_file = "RunC_ConditionsFile.csv"
with open(condition_output_file, "w") as f:
    writer = csv.DictWriter(f, ["ImageFile", "jitter"])
    writer.writeheader()
    writer.writerows([{"ImageFile": output_row[0], "jitter": output_row[1]} for output_row in output_rows])
コード例 #13
0
ファイル: Brainlock.py プロジェクト: NeuroTechX/Brainlock
if live == 1:
    inlet= lslstream()

else:
    inlet= datastream()
    
#####



acrLknown.extend(acrlunknown)
acrL=acrLknown
print acrL

random.shuffle(acrL)

#if lSize is not 0:
#    acrL=acrL[:lSize]
######/end Acronym List ##############



#INTRO SCREEN
win = visual.Window(size=(1366, 768), fullscr=True, screen=0, allowGUI=False, allowStencil=False,
    monitor='testMonitor', color=[-1,-1,-1], colorSpace='rgb',
    blendMode='avg', useFBO=True,
    )

#CREATE NONTEXT OBJECTS 
コード例 #14
0
ファイル: visual_fmri_run1.py プロジェクト: sbasils/qlab
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)

# Initialize components for Routine "blank_block_trial"
blank_block_trialClock = core.Clock()
blank_block_trial_image = visual.ImageStim(win=win, name='blank_block_trial_image',
    image='sin', mask=None,
    ori=0, pos=[0, 0], size=None,
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=0.0)


blockList = ['1','2','3','4','5','6']
random.shuffle(blockList)


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


#------Prepare to start Routine "start"-------
t = 0
startClock.reset()  # clock 
frameN = -1
# update component parameters for each repeat
start_key_resp = event.BuilderKeyResponse()  # create an object of type KeyResponse
start_key_resp.status = NOT_STARTED
# keep track of which components have finished
コード例 #15
0
def run2_func(expInfo):
    # main function
    # Ensure that relative paths start from the same directory as this script
    _thisDir = os.path.dirname(os.path.abspath(__file__)).decode(
        sys.getfilesystemencoding())
    os.chdir(_thisDir)

    # Store info about the experiment session
    expName = u'tnac_exp'  # from the Builder filename that created this script
    expInfo['expName'] = expName

    # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
    filename = _thisDir + os.sep + u'data/%s_%s_%s' % (
        expInfo['participant'], expName, expInfo['date'])

    trg_dict = {
        "music": 1,
        "voice": 2,
        "song": 3,
        "sound_off": 100,
        "pause_block": 200,
        "stop_run": 300,
        "start_run": 400,
        "start_block": 500,
    }

    #define path to csvs
    run_var = _thisDir + '/run2.csv'
    # 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
    logFile = logging.LogFile(filename + '.log', level=logging.EXP)
    logging.console.setLevel(
        logging.WARNING)  # this outputs to the screen, not a file

    endExpNow = False  # flag for 'escape' or other condition => quit the exp

    # Start Code - component code to be run before the window creation

    # Setup the Window
    ## TODO: set window to fullscreen
    win = visual.Window(size=[1366, 768],
                        fullscr=True,
                        screen=0,
                        allowGUI=True,
                        allowStencil=False,
                        monitor='testMonitor',
                        color=[0, 0, 0],
                        colorSpace='rgb',
                        blendMode='avg',
                        useFBO=True)
    # store frame rate of monitor if we can measure it
    expInfo['frameRate'] = win.getActualFrameRate()
    if expInfo['frameRate'] != None:
        frameDur = 1.0 / round(expInfo['frameRate'])
    else:
        frameDur = 1.0 / 60.0  # could not measure, so guess

    # Initialize components for Routine "trial"
    trialClock = core.Clock()
    stim_1 = sound.Sound('A', secs=-1)
    stim_1.setVolume(1)
    fix_1 = visual.TextStim(win=win,
                            name='fix_1',
                            text='+',
                            font='Arial',
                            pos=(0, 0),
                            height=0.1,
                            wrapWidth=None,
                            ori=0,
                            color='white',
                            colorSpace='rgb',
                            opacity=1,
                            depth=-1.0)

    # Initialize components for Routine "run_start"
    run_startClock = core.Clock()
    run_start_msg_screen = visual.TextStim(win=win,
                                           name='run_start_msg_screen',
                                           text=u'Kurze Pause.',
                                           font='Arial',
                                           units='norm',
                                           pos=[0, 0],
                                           height=0.12,
                                           wrapWidth=2,
                                           ori=0,
                                           color='white',
                                           colorSpace='rgb',
                                           opacity=1,
                                           depth=0.0)

    # Initialize components for Routine "run_trigger_sync"
    StartClock = core.Clock()
    run_trigger_syncClock = core.Clock()
    run_start_msg = visual.TextStim(win=win,
                                    name='run_start_msg',
                                    text='Durchgang beginnt!',
                                    font='Arial',
                                    units='norm',
                                    pos=[0, 0],
                                    height=0.15,
                                    wrapWidth=2,
                                    ori=0,
                                    color='white',
                                    colorSpace='rgb',
                                    opacity=1,
                                    depth=-1.0)
    movie = visual.MovieStim3(
        win=win,
        name='movie',
        units='pix',
        noAudio=True,
        # rename path
        filename='C:\Paradigmen\AG_Brain\Peer\TNAC\movies\mov2.mkv',
        ori=0,
        pos=(0, 0),
        opacity=1,
        depth=0.0,
    )

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

    block_delay = [4, 5, 6] * 12
    random.shuffle(block_delay)
    #print(block_delay)
    # ------Prepare to start Routine "run_start"-------
    t = 0
    run_startClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    run_start_trigger_key = event.BuilderKeyResponse()
    # keep track of which components have finished
    run_startComponents = [run_start_msg_screen, run_start_trigger_key]
    for thisComponent in run_startComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    # -------Start Routine "run_start"-------
    while continueRoutine:
        # get current time
        t = run_startClock.getTime()
        thisExp.addData('start_run', globalClock.getTime())
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *run_start_msg_screen* updates
        if t >= 0.0 and run_start_msg_screen.status == NOT_STARTED:
            # keep track of start time/frame for later
            run_start_msg_screen.tStart = t
            run_start_msg_screen.frameNStart = frameN  # exact frame index
            run_start_msg_screen.setAutoDraw(True)

        # *run_start_trigger_key* updates
        if t >= 0.0 and run_start_trigger_key.status == NOT_STARTED:
            # keep track of start time/frame for later
            run_start_trigger_key.tStart = t
            run_start_trigger_key.frameNStart = frameN  # exact frame index
            run_start_trigger_key.status = STARTED
            # keyboard checking is just starting
            event.clearEvents(eventType='keyboard')
        if run_start_trigger_key.status == STARTED:
            theseKeys = event.getKeys(keyList=['s'])

            # check for quit:
            if "escape" in theseKeys:
                endExpNow = True
            if len(theseKeys) > 0:  # at least one key was pressed
                # a response ends the routine
                continueRoutine = 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 run_startComponents:
            if hasattr(thisComponent,
                       "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the Esc key)
        if endExpNow or event.getKeys(keyList=["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    # -------Ending Routine "run_start"-------
    for thisComponent in run_startComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # the Routine "run_start" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    # ------Prepare to start Routine "run_trigger_sync"-------
    t = 0
    run_trigger_syncClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    run_trigger_sync_ = event.BuilderKeyResponse()

    # keep track of which components have finished
    run_trigger_syncComponents = [run_trigger_sync_, run_start_msg]
    for thisComponent in run_trigger_syncComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    # -------Start Routine "run_trigger_sync"-------
    while continueRoutine:
        # get current time
        print('waiting for scanner trigger....')
        t = run_trigger_syncClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *run_trigger_sync_* updates
        if t >= 0.0 and run_trigger_sync_.status == NOT_STARTED:
            # keep track of start time/frame for later
            run_trigger_sync_.tStart = t
            run_trigger_sync_.frameNStart = frameN  # exact frame index
            run_trigger_sync_.status = STARTED
            # keyboard checking is just starting
            win.callOnFlip(
                run_trigger_sync_.clock.reset)  # t=0 on next screen flip
            event.clearEvents(eventType='keyboard')
        if run_trigger_sync_.status == STARTED:
            theseKeys = event.getKeys(keyList=['t'])

            # check for quit:
            if "escape" in theseKeys:
                endExpNow = True
            if len(theseKeys) > 0:  # at least one key was pressed
                run_trigger_sync_.keys = theseKeys[
                    -1]  # just the last key pressed
                run_trigger_sync_.rt = run_trigger_sync_.clock.getTime()
                # a response ends the routine
                continueRoutine = False

        # *run_start_msg* updates
        if t >= 0.0 and run_start_msg.status == NOT_STARTED:
            # keep track of start time/frame for later
            run_start_msg.tStart = t
            run_start_msg.frameNStart = frameN  # exact frame index
            run_start_msg.setAutoDraw(True)
        frameRemains = 0.0 + 5 - win.monitorFramePeriod * 0.75  # most of one frame period left
        if run_start_msg.status == STARTED and t >= frameRemains:
            run_start_msg.setAutoDraw(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 run_trigger_syncComponents:
            if hasattr(thisComponent,
                       "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the Esc key)
        if endExpNow or event.getKeys(keyList=["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    # -------Ending Routine "run_trigger_sync"-------
    for thisComponent in run_trigger_syncComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # check responses
    if run_trigger_sync_.keys in ['', [], None]:  # No response was made
        run_trigger_sync_.keys = None
    thisExp.addData('run_trigger_sync_.keys', run_trigger_sync_.keys)
    if run_trigger_sync_.keys != None:  # we had a response
        thisExp.addData('run_trigger_sync_.rt', run_trigger_sync_.rt)
    run_start_timestamp = StartClock.getTime()

    send_trigger(400)
    # the Routine "run_trigger_sync" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    start_delay = False
    delay_counter = 0
    #print(block_delay)
    #print(delay_counter)
    # start movie for whole run (loop over trials)
    mov = 'movies/mov2.mkv'
    #print(mov)
    movie.setMovie(mov)
    if t >= 0.0 and movie.status == NOT_STARTED:
        # keep track of start time/frame for later
        movie.tStart = t
        movie.frameNStart = frameN  # exact frame index
        movie.setAutoDraw(True)
        frameRemains = 0.0 + 2 - win.monitorFramePeriod * 0.75  # most of one frame period left

        # set up handler to look after randomisation of conditions etc
        trials = data.TrialHandler(nReps=1,
                                   method='sequential',
                                   extraInfo=expInfo,
                                   originPath=-1,
                                   trialList=data.importConditions(run_var),
                                   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.keys():
                exec(paramName + '= thisTrial.' + paramName)
        stimuli_played = 0

        for thisTrial in trials:
            currentLoop = trials
            # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
            if thisTrial != None:
                for paramName in thisTrial.keys():
                    exec(paramName + '= thisTrial.' + paramName)

            # ------Prepare to start Routine "trial"-------
            t = 0
            trialClock.reset()  # clock
            frameN = -1
            continueRoutine = True

            routineTimer.add(2.000000)
            # update component parameters for each repeat
            stim_1.setSound(stimuli, secs=2)
            #read stimuli into dict and set port value
            abc = stimuli.split('/')[0]
            trg = trg_dict.get(abc, 100)
            # keep track of which components have finished
            trialComponents = [stim_1, fix_1]
            for thisComponent in trialComponents:
                if hasattr(thisComponent, 'status'):
                    thisComponent.status = NOT_STARTED

            # -------Start Routine "trial"-------
            while continueRoutine and routineTimer.getTime() > 0:

                # get current time
                t = trialClock.getTime()
                frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
                # update/draw components on each frame
                # start/stop stim_1
                if t >= 0.0 and stim_1.status == NOT_STARTED:
                    # keep track of start time/frame for later
                    stim_1.tStart = t
                    stim_1.frameNStart = frameN  # exact frame index

                    ## TODO reinstate: send_trigger(abc)
                    #print(abc)
                    stim_1.play(
                    )  # start the sound (it finishes automatically)
                    send_trigger(trg)  # send block specific trigger
                    # get time for stimuls start
                    thisExp.addData('stimulus_start_global',
                                    globalClock.getTime())
                    thisExp.addData('stimulus_start_routineTimer',
                                    routineTimer.getTime())
                    thisExp.addData('stimulus_start_', frameN)
                    print(stim_1)
                    stimuli_played += 1
                    if stimuli_played % 5 == 0:
                        start_delay = True
                    print('stimuli_nr:' + str(stimuli_played))

                frameRemains = 0.0 + 1.5 - win.monitorFramePeriod * 0.75  # most of one frame period left
                #frameRemainsdelay = 0.0 + 1.5- win.monitorFramePeriod * 0.75  # most of one frame period left
                if stim_1.status == STARTED and t >= frameRemains:
                    stim_1.stop()  # stop the sound (if longer than duration)
                    send_trigger(100)  # send sound off trigger
                    # get info on stim end
                thisExp.addData('stimulus_end_global', globalClock.getTime())
                thisExp.addData('stimulus_end_routineTimer',
                                routineTimer.getTime())

                # add delay intervall after 5 stimuli
                if stimuli_played % 5 == 0 and start_delay and delay_counter != 35:
                    send_trigger(200)
                    delay = block_delay[delay_counter]
                    routineTimer.add(block_delay[delay_counter])
                    #frameRemainsdelay = 0.0 + 1.5 + delay - win.monitorFramePeriod * 0.75  # most of one frame period left
                    #print('delay='+str(delay_counter))
                    delay_counter += 1
                    thisExp.addData('delay_counter',
                                    block_delay[delay_counter])
                    thisExp.addData('block_end_global', globalClock.getTime())
                    start_delay = False

                if stim_1.status == STARTED and t >= frameRemains:
                    stim_1.stop()  # stop the sound (if longer than duration)
                    send_trigger(100)  # send sound off trigger
                    # get info on stim end
                thisExp.addData('stimulus_end_global', globalClock.getTime())
                thisExp.addData('stimulus_end_routineTimer',
                                routineTimer.getTime())

                # 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 trialComponents:
                    if hasattr(thisComponent,
                               "status") and thisComponent.status != FINISHED:
                        continueRoutine = True
                        break  # at least one component has not yet finished

                # check for quit (the Esc key)
                if endExpNow or event.getKeys(keyList=["escape"]):
                    core.quit()

                # refresh the screen
                if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
                    win.flip()

            stim_1.stop()  # ensure sound has stopped at end of routine
            thisExp.nextEntry()

            # completed 1 repeats of 'trials'

        thisExp.nextEntry()

        # completed 1 repeats of 'block'

    if stimuli_played == 180:
        movie.setAutoDraw(False)
        send_trigger(300)  # END RUN
        thisExp.saveAsWideText(filename + 'run2' + '.csv')
        thisExp.saveAsPickle(filename + 'run2')
        logging.flush()
        # make sure everything is closed down
        thisExp.abort()  # or data files will save again on exit
        win.close()
コード例 #16
0
ファイル: Brainlock.py プロジェクト: irfanmustafas/Brainlock
usern = raw_input("Enter your username:"******"Enter 1 for streaming, 2 for data stream"))

if live == 1:
    inlet = lslstream()

else:
    inlet = datastream()

#####

acrLknown.extend(acrlunknown)
acrL = acrLknown
print acrL

random.shuffle(acrL)

#if lSize is not 0:
#    acrL=acrL[:lSize]
######/end Acronym List ##############

#INTRO SCREEN
win = visual.Window(
    size=(1366, 768),
    fullscr=True,
    screen=0,
    allowGUI=False,
    allowStencil=False,
    monitor='testMonitor',
    color=[-1, -1, -1],
    colorSpace='rgb',
コード例 #17
0
    'NEUTRAL1.bmp', 'NEUTRAL2.bmp', 'NEUTRAL3.bmp', 'NEUTRAL4.bmp',
    'NEUTRAL5.bmp', 'NEUTRAL6.bmp', 'NEUTRAL7.bmp', 'NEUTRAL8.bmp',
    'NEUTRAL1.bmp', 'NEUTRAL2.bmp', 'NEUTRAL3.bmp', 'NEUTRAL4.bmp',
    'NEUTRAL5.bmp', 'NEUTRAL6.bmp', 'NEUTRAL7.bmp', 'NEUTRAL8.bmp'
]

#NUMBER OF DISTRACTOR IMAGES AND PRESENTATION

distractor_presentations = 16

FearLeft_marker = 0
FearRight_marker = 0
NeutralLeft_marker = 0
NeutralRight_marker = 0

random.shuffle(FearLeft_trials)
random.shuffle(FearRight_trials)
random.shuffle(NeutralLeft_trials)
random.shuffle(NeutralRight_trials)

fixation = visual.TextStim(win=win,
                           name='fixation',
                           text='+',
                           font='Arial',
                           pos=(0, 0),
                           height=20,
                           wrapWidth=None,
                           ori=0,
                           color='black',
                           colorSpace='rgb',
                           opacity=1,
コード例 #18
0
    F1XPOS = basePos(0, height, XR, XL)[1]
    F2XPOS = basePos(0, height, XR, XL)[2]
    Fixation = fixationr.pos
elif key[0] == 'r':
    base_positions_image = basePos(height, 0, XL, XR)[0]
    F1XPOS = basePos(height, 0, XL, XR)[1]
    F2XPOS = basePos(height, 0, XL, XR)[2]
    Fixation = fixationl.pos

#show wait screen
waitScreen()

#START OF REAL EXPERIMENT WITH 3 BLOCKS#
for k in range(3):
    #randomize the list of images before each of the three blocks
    random.shuffle(STIMULI)
    #randomize the list of positions before each of the three blocks
    random.shuffle(base_positions_image)
    #the next loop follows the same structure as the practice loop
    for t in range(48):
        endTRIAL = False
        opas = 0
        ran_time = random.randint(0, 4)
        STIMULI[t]['stimulus'].pos = base_positions_image[t]
        stopwatch.reset()

        while not endTRIAL:
            if stopwatch.getTime() > RAN[ran_time]:
                if opas < 0.99:
                    opas += 0.015
                else:
コード例 #19
0
        if thisTrial != None:
            for paramName in thisTrial.keys():
                exec(paramName + '= thisTrial.' + paramName)

        # ------Prepare to start Routine "trial"-------
        t = 0
        trialClock.reset()  # clock
        frameN = -1
        continueRoutine = True
        routineTimer.add(TotalTrialTime)
        # update component parameters for each repeat
        # Generate a random set of locations
        # Create the list of possible locations
        Locations = (np.arange(0, GridCount**2, 1))
        # shuffle the list
        random.shuffle(Locations)
        # pick out some
        Locations = Locations[0:Load]

        resp = event.BuilderKeyResponse()
        # keep track of which components have finished
        trialComponents = [circle, textDelay, textITI, resp]

        for thisComponent in trialComponents:
            if hasattr(thisComponent, 'status'):
                thisComponent.status = NOT_STARTED

        # -------Start Routine "trial"-------
        while continueRoutine and routineTimer.getTime() > 0:
            # get current time
            t = trialClock.getTime()
コード例 #20
0
for r in runs:
    expInfo['run'] = r
    #conditionFile='face_matching_stimuli_'+r+'.csv'###CHANGED CONDITION FILE
    #Write condition file (randomize block file sequence)
    if expInfo['runMode'] == 'Scanner':
        conditionFile = output + '/FaceMatching_all_blocks_list_3x' + r + '.csv'
        block_names = [
            'block_A_happy_1.csv', 'block_A_fear_1.csv',
            'block_A_neutral_1.csv', 'block_A_objects_1.csv'
        ]
        with open(conditionFile, 'wb') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=["trial_blocks"])
            writer.writeheader()
            blocks = []
            for i in range(1, 4):
                random.shuffle(block_names)
                blocks.append('block_fixation.csv')
                blocks = blocks + [
                    x.replace('1', str(i)).replace('A', r) for x in block_names
                ]

            for i in blocks:
                print >> csvfile, i

    thisExp.nextEntry()
    # the Routine "instructions" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    #------Prepare to start Routine "trigger"-------

    msgExpter = visual.TextStim(win,
コード例 #21
0
        exec('{} = thisTrial_2[paramName]'.format(paramName))

for thisTrial_2 in trials_2:
    currentLoop = trials_2
    # abbreviate parameter names if possible (e.g. rgb = thisTrial_2.rgb)
    if thisTrial_2 != None:
        for paramName in thisTrial_2:
            exec('{} = thisTrial_2[paramName]'.format(paramName))
    
    # ------Prepare to start Routine "RandomiseStim"-------
    t = 0
    RandomiseStimClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    random.shuffle(FEAR)
    random.shuffle(NEUTRAL)
    
    FearLoop = 0
    NeutralLoop = 0
    
    D_L = "FEAR1.bmp"
    D_R = "FEAR1.bmp"
    # keep track of which components have finished
    RandomiseStimComponents = []
    for thisComponent in RandomiseStimComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    
    # -------Start Routine "RandomiseStim"-------
    while continueRoutine:
コード例 #22
0
ファイル: ExperimentCode_CCL_CL.py プロジェクト: zz112duke/CL
##########Trial Sequence##########
trials = 240
duration = 3.0
ITI_min = 800.0
ITI_max = 2000.0
stim_image = []
corrAns = []
ITI = []



# index the images for high, medium and low frequencies for later selection
#indices_all = (np.random.choice(len(Imagelist), 104, replace=False)).tolist()
indices_all = list(range(104))

random.shuffle(Imagelist)
print (Imagelist)
indices_low = indices_all[:80]
indices_medium = indices_all[80:96]
indices_high = indices_all[96:104]

# select corresponding images
stim_image_high = [Imagelist[i] for i in indices_high]*10
stim_image_medium = [Imagelist[i] for i in indices_medium]*5
stim_image_low = [Imagelist[i] for i in indices_low]
stim_image = stim_image_high +stim_image_medium + stim_image_low

# frequency
frequency = ['high']*80 + ['medium']*80 + ['low']*80

# corrAns
コード例 #23
0
##--------------Read the Experimental Matrix---------------##
expmatrix = pd.read_csv('expmatrix.csv', index_col = [0])

##--------------Post Forced Choice Matrix---------------##
# Generate a matrix with F1 vs. F2, where F1 column has 40 'Low' and F2 has 20 'Medium' and 20 'High'. 
# F1_path & F2_path: 20 Low from Set1 and 20 from Set2; 10 medium from Set1 and 10 from Set2; 10 High from Set1 and 10 from Set2
# Task_1 & Task_2, where each has 20 columns saying 'con' & 'non'
# Question: 20 says 'higher' and 20 says 'lower'.
# Correct response
#left vs. right?

F1 = ['Low'] *40
F2 = ['Medium'] * 10 + ['High'] * 10 + ['Medium'] * 10 + ['High'] * 10
Question = ['higher'] * 20 + ['lower'] * 20
random.shuffle(Question)
Position = ['L'] * 20 + ['R'] * 20
random.shuffle(Position)

low_non = expmatrix.loc[(expmatrix.Congruency == 'None') & (expmatrix.Frequency == 'low')].sample(n=20)[['stim_image','Congruency']]
low_con = expmatrix.loc[(expmatrix.Congruency != 'None') & (expmatrix.Frequency == 'low')].sample(n=20)[['stim_image','Congruency']]

medium_non = expmatrix.loc[(expmatrix.Congruency == 'None') & (expmatrix.Frequency == 'medium')].sample(n=10)[['stim_image','Congruency']]
medium_con = expmatrix.loc[(expmatrix.Congruency != 'None') & (expmatrix.Frequency == 'medium')].sample(n=10)[['stim_image','Congruency']]

high_non = expmatrix.loc[(expmatrix.Congruency == 'None') & (expmatrix.Frequency == 'high')].sample(n=10)[['stim_image','Congruency']]
high_con = expmatrix.loc[(expmatrix.Congruency != 'None') & (expmatrix.Frequency == 'high')].sample(n=10)[['stim_image','Congruency']]

F1_path = pd.concat([low_non,low_con],ignore_index=True)
F2_path = pd.concat([medium_non, high_non, medium_con, high_con],ignore_index=True)
corrAns = ['N/A']*40
コード例 #24
0
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
コード例 #25
0
def batch_generator_npz(files,
                        train_csv_table,
                        batch_size,
                        pad=600,
                        print_padded=False,
                        number=1):
    print('new generator created')
    number_of_batches = np.ceil(len(files) / batch_size)
    counter = 0
    random.shuffle(files)
    # next_files = copy.deepcopy(files)
    # failed = 0

    while True:
        # batch_files = files[batch_size*counter+failed:batch_size*(counter+1)+failed]
        image_list = []
        mask_list = []
        success = 0
        problem_files = []
        batch_files = files[batch_size * counter:batch_size * (counter + 1)]
        # for f in files[batch_size*counter+failed:]:
        for f in batch_files:
            if print_padded:
                print(f, number)
                print(files[batch_size * counter:batch_size * (counter + 1)])
            # if success==batch_size:
            #     break
            # try:
            if print_padded:
                print("loading")
            image = np.load(f, mmap_mode='r')
            if print_padded:
                print(type(image))
                print(sys.getsizeof(image))
                # print(image.shape)
                print(image.files)
            image = image['arr_0'][:pad]
            if print_padded:
                print(type(image))
                print(len(image))
                print(sys.getsizeof(image))
                print(image.shape)
            # except:
            #     print("couldn't load")
            if print_padded:
                print('loaded %s %s' % (f, number))
            padded_image = np.zeros((pad, 512, 32, 32))
            len_image = min(len(image), pad)
            # print(len_image)
            # image = np.expand_dims(np.expand_dims(image[:512], 1),0)
            # print(image.shape)
            # print(len_image)

            padded_image[:len_image, :, :, :] = image[:pad]
            if print_padded:
                print('padded %s %s' % (f, number))
            image_list.append(padded_image)
            patient_id = os.path.basename(os.path.dirname(f))
            success += 1
            try:
                is_cancer = train_csv_table.loc[train_csv_table['id'] ==
                                                patient_id]['cancer'].values[0]

                if is_cancer == 0:
                    mask = [1, 0]
                    # mask = [1]
                else:
                    mask = [0, 1]
                    # mask = [0]
            except:
                # print('Problem with %s' % patient_id)
                mask = [0.5, 0.5]
            mask_list.append(mask)
        counter += 1
        mask_list = np.array(mask_list)
        image_list = np.array(image_list)
        del padded_image, image
        if print_padded:
            print(len(image_list))
            print(image_list[0].shape)
        yield image_list, mask_list
        del image_list, mask_list

        if counter == number_of_batches:
            random.shuffle(files)
            counter = 0
            failed = 0
コード例 #26
0
        exec('{} = thisTrial[paramName]'.format(paramName))

for thisTrial in trials:
    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 "trial"-------
    t = 0
    trialClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    random.shuffle(Letters)
    random.shuffle(Tpos)

    if Tpos[0] == 8:
        P1.setText(Letters[0])
        P2.setText(Letters[1])
        P3.setText(Letters[2])
        P4.setText(Letters[3])
        P5.setText(Letters[4])
        P6.setText(Letters[5])
        P7.setText(Letters[6])
        P8.setText(Target)
        P9.setText(Letters[7])
        P10.setText(Letters[8])
        P11.setText(Letters[9])
        P12.setText(Letters[10])
コード例 #27
0
 idxFirst4 = int(idx4[0])
 idxLast4 = int(idx4[1])
 
 imMale=MaleImages[idxFirst1:idxLast1]
 imFemale=FemaleImages[idxFirst2:idxLast2]
 imIndoor=IndoorImages[idxFirst3:idxLast3]
 imOutdoor=OutdoorImages[idxFirst4:idxLast4]
 
 
 Range1 = list(range(idxLast1))
 Range2 = list(range(idxLast2))
 Range3 = list(range(idxLast3))
 Range4 = list(range(idxLast4))
 
 #Shuffling
 random.shuffle(Range1) 
 random.shuffle(Range2) 
 random.shuffle(Range3) 
 random.shuffle(Range4) 
 
 
 #Select images
 numType1=int(num_trials/2)
 numType2=num_trials-numType1
 list1 = Range1[0:(numType1+1)]
 selectedImages1 = [imMale[i] for i in list1]
 list2 = Range2[0:(numType2+1)]
 selectedImages2 = [imFemale[i] for i in list2]
 list3 = Range3[0:(numType1+1)]
 selectedImages3 = [imIndoor[i] for i in list3]
 list4 = Range4[0:(numType2+1)]
コード例 #28
0
    text='Incorrect',font=u'Arial',
    pos=(0, -0.75), height=0.2, wrapWidth=None, ori=0, 
    color=u'red', colorSpace='rgb', opacity=1,
    depth=0)


###Indexing Image###
# index the images for high, medium and low frequencies for later selection
#indices_all = (np.random.choice(len(Imagelist), 104, replace=False)).tolist()
indices_all = list(range(104))
indices_low = indices_all[:80]
indices_medium = indices_all[80:96]
indices_high = indices_all[96:104]

# select corresponding images
random.shuffle(Imagelist1)
stim_image_high1 = [Imagelist1[i] for i in indices_high]*10
stim_image_medium1 = [Imagelist1[i] for i in indices_medium]*5
stim_image_low1 = [Imagelist1[i] for i in indices_low]
stim_image1 = Practicelist*3 + stim_image_high1 +stim_image_medium1 + stim_image_low1
print(stim_image1)

random.shuffle(Imagelist2)
stim_image_high2 = [Imagelist2[i] for i in indices_high]*10
stim_image_medium2 = [Imagelist2[i] for i in indices_medium]*5
stim_image_low2 = [Imagelist2[i] for i in indices_low]
stim_image2 = Practicelist*3 + stim_image_high2 +stim_image_medium2 + stim_image_low2
print (stim_image2)

##########Timing##########
trials = 240
コード例 #29
0
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# Initialize components for Routine "set_trial_blocks"
set_trial_blocksClock = core.Clock()
import random
import pandas as pd
block_ranges = pd.read_csv('choose_blocks.csv')

# Prepare experiment blocks
block_ranges_exp = list(block_ranges.choose_blocks_exp)
random.shuffle(block_ranges_exp)

# Initialize components for Routine "instructPractice"
instructPracticeClock = core.Clock()
instr_practice = visual.TextStim(
    win=win,
    name='instr_practice',
    text=
    'Recuerda, ignora la palabra.\n\nPresiona:\nf para letras rojas\nj para letras verdes\n"espacio" para letras azules\n\nVamos a comenzar con unos ejercicios de práctica\n\nPresiona cualquier tecla para comenzar',
    font='Arial',
    pos=[0, 0],
    height=0.07,
    wrapWidth=None,
    ori=0,
    color='white',
    colorSpace='rgb',
コード例 #30
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))]
    Trial_times = [4 for i in xrange(len(temporal_combi_list))]

    Instructions = visual.TextStim(
コード例 #31
0
if __name__ == '__main__':
    # begin the unittest.main()
    unittest.main()


#%%
import random
import nltk
from nltk.corpus import movie_reviews
print(nltk.pos_tag(nltk.word_tokenize('Albert Einstein was born in Ulm, Germany in 1879.')))
print(movie_reviews.categories(), len(movie_reviews.fileids()), len(movie_reviews.words()))
documents = [(list(movie_reviews.words(fileid)), category)
              for category in movie_reviews.categories()
              for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())
word_features = list(all_words)[:2000]

def document_features(document): 
    document_words = set(document) 
    features = {}
    for word in word_features:
        features['contains({})'.format(word)] = (word in document_words)
    return features
print(document_features(movie_reviews.words('pos/cv957_8737.txt'))) 
#{'contains(waste)': False, 'contains(lot)': False, ...}
featuresets = [(document_features(d), c) for (d,c) in documents]
train_set, test_set = featuresets[100:], featuresets[:100]
classifier = nltk.NaiveBayesClassifier.train(train_set)
print(nltk.classify.accuracy(classifier, test_set))
コード例 #32
0
    color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
    depth=-1.0) for x in range (30)]

# the random order is printed in order to trace back the order trials were presented in
# N.B  change program to save this order in a file instead of printing
print randomori

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

# create Expnr a shuffled list of nrs 0 to 30 in order to be able to call trials in a random
# order. Changing the seed allows you to generate a new random order for each participant
random.seed(int(expInfo['session']))
x= [[i] for i in range (30)]
random.shuffle(x)
Expnr=[x[i][0] for i in range (30)]


for z in range (30):
    #------Prepare to start Routine "Target"-------
    t = 0
    TargetClock.reset()  # clock 
    frameN = -1
    routineTimer.add(5.000000)
    # update component parameters for each repeat
    # keep track of which components have finished
    TargetComponents = []
    TargetComponents.append(text)
    TargetComponents.append(targetstim[Expnr[z]])
    for thisComponent in TargetComponents:
コード例 #33
0
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# Initialize components for Routine "set_trial_blocks"
set_trial_blocksClock = core.Clock()
import random
import pandas as pd
block_ranges = pd.read_csv('choose_blocks.csv')

# Prepare practice blocks
block_ranges_practice = list(block_ranges.choose_blocks_practice)
print(block_ranges_practice)
random.shuffle(block_ranges_practice)

# Prepare experiment blocks
block_ranges_exp = list(block_ranges.choose_blocks_exp)
random.shuffle(block_ranges_exp)
print (2, block_ranges_exp)

# Initialize components for Routine "instructPractice"
instructPracticeClock = core.Clock()
instr1 = visual.TextStim(win=win, name='instr1',
    text=u'Recuerda, ignora la palabra.\n\nPresiona:\nIzquierda para letras rojas\nAbajo para letras verdes\nDerecha para letras azules\n\nVamos a comenzar con unos ejercicios de pr\xe1ctica\n\nPresiona cualquier tecla para comenzar',
    font='Arial',
    pos=[0, 0], height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1,
    depth=0.0);
コード例 #34
0
        # ------Prepare to start Routine "trial"-------
        continueRoutine = True
        # update component parameters for each repeat
        import random

        # Shuffle answers to appear at random positions each time
        # Uncomment if needed
        #ansList = [ans1, ans2, ans3, ans4]
        #random.shuffle(ansList)
        #ans4 = ansList.pop(-1)
        #ans3 = ansList.pop(-1)
        #ans2 = ansList.pop(-1)
        #ans1 = ansList.pop(-1)

        colorList = ['red', 'green', 'blue', (255, 255, 0)]
        random.shuffle(colorList)
        c1 = colorList[0]
        c2 = colorList[1]
        c3 = colorList[2]
        c4 = colorList[3]
        text.setText(textStim)
        q.setText(question)
        a1.setColor(c1, colorSpace='rgb')
        a1.setText(ans1)
        a2.setColor(c2, colorSpace='rgb')
        a2.setText(ans2)
        a3.setColor(c3, colorSpace='rgb')
        a3.setText(ans3)
        a4.setColor(c4, colorSpace='rgb')
        a4.setText(ans4)
        # setup some python lists for storing info about the resp