text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v2020.1.3),
    on October 22, 2021, at 19:23
If you publish work using this script the most relevant publication is:

    Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv JK. (2019)
        PsychoPy2: Experiments in behavior made easy Behav Res 51: 195.
        https://doi.org/10.3758/s13428-018-01193-y

"""

from __future__ import absolute_import, division

from psychopy import locale_setup
from psychopy import prefs
prefs.hardware['audioLib'] = 'ptb'
from psychopy import sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
                                STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)

import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
                   sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import sys  # to get file system encoding

from psychopy.hardware import keyboard

# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)

# Store info about the experiment session
psychopyVersion = '2020.1.3'
expName = 'Task_1L'  # from the Builder filename that created this script
expInfo = {'participant': '', 'age': '', 'gender': ['m', 'f'], 'Eye Tracker': ''}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
    core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion

# 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'])

# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
    extraInfo=expInfo, runtimeInfo=None,
    originPath='C:\\Users\\presi\\Desktop\\PhD\\Children experiment\\Tasks\\Task1\\Task_1L_lastrun.py',
    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
frameTolerance = 0.001  # how close to onset before 'same' frame

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

# Setup the Window
win = visual.Window(
    size=[1920, 1080], fullscr=True, screen=0,
    winType='pyglet', allowGUI=True, allowStencil=False,
    monitor='PHILIPS', color=[0.506,0.506,0.506], colorSpace='rgb',
    blendMode='avg', useFBO=True,
    units='pix')
# 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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "Welcome_screen"
Welcome_screenClock = core.Clock()
instructions = visual.ImageStim(
    win=win,
    name='instructions',
    image='Stimuli/instruct.png', mask=None,
    ori=0, pos=(0, 0), size=(900, 980),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=0.0)
next = visual.ImageStim(
    win=win,
    name='next',
    image='Stimuli/next1.png', mask=None,
    ori=0, pos=(880, -490), size=(140, 80),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)
#Assign different condition file based on participant number:
if int(expInfo['participant'])%2==0:
    condition='LearningB.xlsx'
else:
    condition='LearningA.xlsx'

#Fixation boundary in pixels
fixation_boundary=60

eyetracker=False
participant=expInfo['participant']
date=expInfo['date']

#Establish connection with Gazepoint EyeTracker:
if expInfo['Eye Tracker']:
    try:
        from opengaze import GazePointTracker
        import os.path
        import time

        # Construct the path to the log file.
        save_path=r'C:\Users\presi\Desktop\PhD\Children experiment\Tasks\Task1\ET_Data'
        file_name = os.path.join(save_path, f'L_{participant}_{date}.tsv')

        # Open the connection to the tracker.
        eyetracker = GazePointTracker(logfile=file_name, debug=False)
        time.sleep(1.0)
    except Exception as e:
       print("!! Error starting Gazepoint: ",e," Exiting...")
       core.quit()

    display_gaze=False
    x,y=0,0

# Initialize components for Routine "calibrate"
calibrateClock = core.Clock()
text_2 = visual.TextStim(win=win, name='text_2',
    text='Περιμέντε όσο η κάμερα μπαίνει σε λειτουργία...',
    font='Arila',
    pos=(0, 0), height=40, wrapWidth=1000, ori=0,
    color='Black', colorSpace='rgb', opacity=1,
    languageStyle='LTR',
    depth=-1.0);

# Initialize components for Routine "start_recording"
start_recordingClock = core.Clock()
text = visual.TextStim(win=win, name='text',
    text='Οι δοκιμές ξεκινάνε σύντομα...',
    font='Arial',
    pos=(0, 0), height=40, wrapWidth=1000, ori=0,
    color='black', colorSpace='rgb', opacity=1,
    languageStyle='LTR',
    depth=0.0);

# Initialize components for Routine "fixation"
fixationClock = core.Clock()
fix_cross = visual.ShapeStim(
    win=win, name='fix_cross', vertices='cross',
    size=(30, 30),
    ori=0, pos=(0, 0),
    lineWidth=2, lineColor=[-1.000,-1.000,-1.000], lineColorSpace='rgb',
    fillColor=[-1.000,-1.000,-1.000], fillColorSpace='rgb',
    opacity=1, depth=0.0, interpolate=True)

# Initialize components for Routine "Practise_trials"
Practise_trialsClock = core.Clock()
mouse = event.Mouse(win=win)
x, y = [None, None]
mouse.mouseClock = core.Clock()
background = visual.ImageStim(
    win=win,
    name='background',
    image='sin', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)
star = visual.ImageStim(
    win=win,
    name='star',
    image='Stimuli/20x20t.png', 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=-2.0)
gaze_cursor = visual.GratingStim(
    win=win, name='gaze_cursor',
    tex='sin', mask=None,
    ori=0, pos=[0,0], size=1.0, sf=None, phase=0.0,
    color=[1.000,1.000,-1.000], colorSpace='rgb', opacity=1.0,blendmode='avg',
    texRes=128, interpolate=True, depth=-3.0)

# Initialize components for Routine "Practise_feedback"
Practise_feedbackClock = core.Clock()

sound_1 = sound.Sound('A', secs=0.7, stereo=True, hamming=False,
    name='sound_1')
sound_1.setVolume(1)

# Initialize components for Routine "Start"
StartClock = core.Clock()
worldmap = visual.ImageStim(
    win=win,
    name='worldmap',
    image='Stimuli/fullmap.png', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=0.0)
plot2 = visual.ImageStim(
    win=win,
    name='plot2',
    image='Stimuli/start.png', mask=None,
    ori=0, pos=(0, 0), size=(1180, 670),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)
next2 = visual.ImageStim(
    win=win,
    name='next2',
    image='Stimuli/next1.png', mask=None,
    ori=0, pos=(880, -490), size=(140, 80),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)

# Initialize components for Routine "fixation"
fixationClock = core.Clock()
fix_cross = visual.ShapeStim(
    win=win, name='fix_cross', vertices='cross',
    size=(30, 30),
    ori=0, pos=(0, 0),
    lineWidth=2, lineColor=[-1.000,-1.000,-1.000], lineColorSpace='rgb',
    fillColor=[-1.000,-1.000,-1.000], fillColorSpace='rgb',
    opacity=1, depth=0.0, interpolate=True)

# Initialize components for Routine "Learning_trials"
Learning_trialsClock = core.Clock()
mouse2 = event.Mouse(win=win)
x, y = [None, None]
mouse2.mouseClock = core.Clock()
background2 = visual.ImageStim(
    win=win,
    name='background2',
    image='sin', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)
Star = visual.ImageStim(
    win=win,
    name='Star',
    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=-2.0)
gaze_Cursor = visual.GratingStim(
    win=win, name='gaze_Cursor',
    tex='sin', mask=None,
    ori=0, pos=[0,0], size=(20, 20), sf=None, phase=0.0,
    color=[-1.000,1.000,-1.000], colorSpace='rgb', opacity=1.0,blendmode='avg',
    texRes=128, interpolate=True, depth=-3.0)

# Initialize components for Routine "Learning_feedback"
Learning_feedbackClock = core.Clock()
my_trial=0
Acc_blocks=0
Acc_trials=0
sound_2 = sound.Sound('A', secs=0.7, stereo=True, hamming=False,
    name='sound_2')
sound_2.setVolume(1)

# Initialize components for Routine "Trial_Break"
Trial_BreakClock = core.Clock()
msg_3=""

break_text = visual.TextStim(win=win, name='break_text',
    text='default text',
    font='Calibri',
    pos=(65, 30), height=60, wrapWidth=1000, ori=0,
    color=[0.192,-0.216,-0.702], colorSpace='rgb', opacity=1,
    languageStyle='LTR',
    depth=-1.0);
next3 = visual.ImageStim(
    win=win,
    name='next3',
    image='Stimuli/next.png', mask=None,
    ori=0, pos=(880, -490), size=(150, 90),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)

# Initialize components for Routine "Block_Break"
Block_BreakClock = core.Clock()
msg_4=""
map=None
block_break_text = visual.TextStim(win=win, name='block_break_text',
    text='default text',
    font='Calibri',
    pos=(105, -45), height=80, wrapWidth=1350, ori=0,
    color=[0.192,-0.216,-0.702], colorSpace='rgb', opacity=1,
    languageStyle='LTR',
    depth=-1.0);
next_5 = visual.ImageStim(
    win=win,
    name='next_5',
    image='Stimuli/next.png', mask=None,
    ori=0, pos=(880,-490), size=(150, 90),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)

# Initialize components for Routine "gap"
gapClock = core.Clock()

# Initialize components for Routine "End"
EndClock = core.Clock()
cloud = visual.ImageStim(
    win=win,
    name='cloud',
    image='Stimuli/kamecloud.png', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=0.0)
family = visual.ImageStim(
    win=win,
    name='family',
    image='Stimuli/kamehouse.jpg', mask=None,
    ori=0, pos=(0, 0), size=(1920, 1080),
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.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

# ------Prepare to start Routine "Welcome_screen"-------
continueRoutine = True
# update component parameters for each repeat
# keep track of which components have finished
Welcome_screenComponents = [instructions, next]
for thisComponent in Welcome_screenComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
Welcome_screenClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "Welcome_screen"-------
while continueRoutine:
    # get current time
    t = Welcome_screenClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=Welcome_screenClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # *instructions* updates
    if instructions.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        instructions.frameNStart = frameN  # exact frame index
        instructions.tStart = t  # local t and not account for scr refresh
        instructions.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(instructions, 'tStartRefresh')  # time at next scr refresh
        instructions.setAutoDraw(True)

    # *next* updates
    if next.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        next.frameNStart = frameN  # exact frame index
        next.tStart = t  # local t and not account for scr refresh
        next.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(next, 'tStartRefresh')  # time at next scr refresh
        next.setAutoDraw(True)
    if mouse.isPressedIn(next, buttons=[0]):
        continueRoutine=False

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

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

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

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

# set up handler to look after randomisation of conditions etc
calibration_loop = data.TrialHandler(nReps=0, method='sequential',
    extraInfo=expInfo, originPath=-1,
    trialList=[None],
    seed=None, name='calibration_loop')
thisExp.addLoop(calibration_loop)  # add the loop to the experiment
thisCalibration_loop = calibration_loop.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisCalibration_loop.rgb)
if thisCalibration_loop != None:
    for paramName in thisCalibration_loop:
        exec('{} = thisCalibration_loop[paramName]'.format(paramName))

for thisCalibration_loop in calibration_loop:
    currentLoop = calibration_loop
    # abbreviate parameter names if possible (e.g. rgb = thisCalibration_loop.rgb)
    if thisCalibration_loop != None:
        for paramName in thisCalibration_loop:
            exec('{} = thisCalibration_loop[paramName]'.format(paramName))

    # ------Prepare to start Routine "calibrate"-------
    continueRoutine = True
    routineTimer.add(35.000000)
    # update component parameters for each repeat
    win.winHandle.minimize()
    win.winHandle.set_fullscreen(False)
    #win.flip()
    # keep track of which components have finished
    calibrateComponents = [text_2]
    for thisComponent in calibrateComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    calibrateClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "calibrate"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = calibrateClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=calibrateClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *text_2* updates
        if text_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            text_2.frameNStart = frameN  # exact frame index
            text_2.tStart = t  # local t and not account for scr refresh
            text_2.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(text_2, 'tStartRefresh')  # time at next scr refresh
            text_2.setAutoDraw(True)
        if text_2.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > text_2.tStartRefresh + 35-frameTolerance:
                # keep track of stop time/frame for later
                text_2.tStop = t  # not accounting for scr refresh
                text_2.frameNStop = frameN  # exact frame index
                win.timeOnFlip(text_2, 'tStopRefresh')  # time at next scr refresh
                text_2.setAutoDraw(False)

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

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

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

    # -------Ending Routine "calibrate"-------
    for thisComponent in calibrateComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    win.winHandle.maximize()
    win.winHandle.set_fullscreen(True)
    win.winHandle.activate()
    win.flip()
    thisExp.nextEntry()

# completed 0 repeats of 'calibration_loop'

# ------Prepare to start Routine "start_recording"-------
continueRoutine = True
routineTimer.add(5.000000)
# update component parameters for each repeat
#Start data stream
eyetracker.start_recording()
# keep track of which components have finished
start_recordingComponents = [text]
for thisComponent in start_recordingComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
start_recordingClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "start_recording"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = start_recordingClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=start_recordingClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # *text* updates
    if text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        text.frameNStart = frameN  # exact frame index
        text.tStart = t  # local t and not account for scr refresh
        text.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(text, 'tStartRefresh')  # time at next scr refresh
        text.setAutoDraw(True)
    if text.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > text.tStartRefresh + 5-frameTolerance:
            # keep track of stop time/frame for later
            text.tStop = t  # not accounting for scr refresh
            text.frameNStop = frameN  # exact frame index
            win.timeOnFlip(text, 'tStopRefresh')  # time at next scr refresh
            text.setAutoDraw(False)

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

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

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

# -------Ending Routine "start_recording"-------
for thisComponent in start_recordingComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)

# set up handler to look after randomisation of conditions etc
Practise_loop = data.TrialHandler(nReps=1, method='random',
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions('Practise.xlsx'),
    seed=None, name='Practise_loop')
thisExp.addLoop(Practise_loop)  # add the loop to the experiment
thisPractise_loop = Practise_loop.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisPractise_loop.rgb)
if thisPractise_loop != None:
    for paramName in thisPractise_loop:
        exec('{} = thisPractise_loop[paramName]'.format(paramName))

for thisPractise_loop in Practise_loop:
    currentLoop = Practise_loop
    # abbreviate parameter names if possible (e.g. rgb = thisPractise_loop.rgb)
    if thisPractise_loop != None:
        for paramName in thisPractise_loop:
            exec('{} = thisPractise_loop[paramName]'.format(paramName))

    # ------Prepare to start Routine "fixation"-------
    continueRoutine = True
    # update component parameters for each repeat
    fixation_started=False
    # keep track of which components have finished
    fixationComponents = [fix_cross]
    for thisComponent in fixationComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    fixationClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "fixation"-------
    while continueRoutine:
        # get current time
        t = fixationClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=fixationClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *fix_cross* updates
        if fix_cross.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            fix_cross.frameNStart = frameN  # exact frame index
            fix_cross.tStart = t  # local t and not account for scr refresh
            fix_cross.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(fix_cross, 'tStartRefresh')  # time at next scr refresh
            fix_cross.setAutoDraw(True)
        if eyetracker:
            gpos=eyetracker.sample()
            if type(gpos) in [list,tuple]:
                x,y=gpos[0],gpos[1]
                distance_from_center=np.sqrt(abs(x-0)**2+abs(y-0)**2)
                if distance_from_center<=80:
                    if not fixation_started:
                        fixation_started=True
                        fixation_start_time=t
                    if fixation_start_time>0.40:
                        continueRoutine=False
                    else:
                        fixation_started=False

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

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

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

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

    # ------Prepare to start Routine "Practise_trials"-------
    continueRoutine = True
    routineTimer.add(30.000000)
    # update component parameters for each repeat
    # setup some python lists for storing info about the mouse
    mouse.x = []
    mouse.y = []
    mouse.leftButton = []
    mouse.midButton = []
    mouse.rightButton = []
    mouse.time = []
    mouse.clicked_name = []
    gotValidClick = False  # until a click is received
    mouse.mouseClock.reset()
    background.setImage(Scenes)
    star.setPos((p_Star_x,p_Star_y))
    mouse.setPos([0,0])
    #eyetracker.user_data("%s_START" %Img)

    # keep track of which components have finished
    Practise_trialsComponents = [mouse, background, star, gaze_cursor]
    for thisComponent in Practise_trialsComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Practise_trialsClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "Practise_trials"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = Practise_trialsClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Practise_trialsClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        # *mouse* updates
        if mouse.status == NOT_STARTED and t >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            mouse.frameNStart = frameN  # exact frame index
            mouse.tStart = t  # local t and not account for scr refresh
            mouse.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(mouse, 'tStartRefresh')  # time at next scr refresh
            mouse.status = STARTED
            prevButtonState = mouse.getPressed()  # if button is down already this ISN'T a new click
        if mouse.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > mouse.tStartRefresh + 30-frameTolerance:
                # keep track of stop time/frame for later
                mouse.tStop = t  # not accounting for scr refresh
                mouse.frameNStop = frameN  # exact frame index
                win.timeOnFlip(mouse, 'tStopRefresh')  # time at next scr refresh
                mouse.status = FINISHED
        if mouse.status == STARTED:  # only update if started and not finished!
            buttons = mouse.getPressed()
            if buttons != prevButtonState:  # button state changed?
                prevButtonState = buttons
                if sum(buttons) > 0:  # state changed to a new click
                    # check if the mouse was inside our 'clickable' objects
                    gotValidClick = False
                    for obj in [star,background]:
                        if obj.contains(mouse):
                            gotValidClick = True
                            mouse.clicked_name.append(obj.name)
                    x, y = mouse.getPos()
                    mouse.x.append(x)
                    mouse.y.append(y)
                    buttons = mouse.getPressed()
                    mouse.leftButton.append(buttons[0])
                    mouse.midButton.append(buttons[1])
                    mouse.rightButton.append(buttons[2])
                    mouse.time.append(mouse.mouseClock.getTime())

        # *background* updates
        if background.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            background.frameNStart = frameN  # exact frame index
            background.tStart = t  # local t and not account for scr refresh
            background.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(background, 'tStartRefresh')  # time at next scr refresh
            background.setAutoDraw(True)
        if background.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > background.tStartRefresh + 30-frameTolerance:
                # keep track of stop time/frame for later
                background.tStop = t  # not accounting for scr refresh
                background.frameNStop = frameN  # exact frame index
                win.timeOnFlip(background, 'tStopRefresh')  # time at next scr refresh
                background.setAutoDraw(False)

        # *star* updates
        if star.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            star.frameNStart = frameN  # exact frame index
            star.tStart = t  # local t and not account for scr refresh
            star.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(star, 'tStartRefresh')  # time at next scr refresh
            star.setAutoDraw(True)
        if star.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > star.tStartRefresh + 30-frameTolerance:
                # keep track of stop time/frame for later
                star.tStop = t  # not accounting for scr refresh
                star.frameNStop = frameN  # exact frame index
                win.timeOnFlip(star, 'tStopRefresh')  # time at next scr refresh
                star.setAutoDraw(False)

        # *gaze_cursor* updates
        if gaze_cursor.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            gaze_cursor.frameNStart = frameN  # exact frame index
            gaze_cursor.tStart = t  # local t and not account for scr refresh
            gaze_cursor.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(gaze_cursor, 'tStartRefresh')  # time at next scr refresh
            gaze_cursor.setAutoDraw(True)
        if gaze_cursor.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > gaze_cursor.tStartRefresh + 30-frameTolerance:
                # keep track of stop time/frame for later
                gaze_cursor.tStop = t  # not accounting for scr refresh
                gaze_cursor.frameNStop = frameN  # exact frame index
                win.timeOnFlip(gaze_cursor, 'tStopRefresh')  # time at next scr refresh
                gaze_cursor.setAutoDraw(False)
        if gaze_cursor.status == STARTED:  # only update if drawing
            gaze_cursor.setOpacity(display_gaze, log=False)
            gaze_cursor.setPos([x,y], log=False)
            gaze_cursor.setSize((20, 20), log=False)
        if eyetracker:
            if event.getKeys(keyList=['g',]):
                display_gaze=not display_gaze
            gpos=eyetracker.sample()
            if type(gpos) in [list,tuple]:
                x,y=gpos[0],gpos[1]
                d=np.sqrt(abs(x-p_Star_x)**2+abs(y-p_Star_y)**2)
                if d<= fixation_boundary and mouse.clicked_name==["star","background"]:
                    continueRoutine=False
                elif mouse.clicked_name==["background"]:
                    continueRoutine=False
                else:
                    continueRoutine=True

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

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

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

    # -------Ending Routine "Practise_trials"-------
    for thisComponent in Practise_trialsComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # store data for Practise_loop (TrialHandler)
    Practise_loop.addData('mouse.x', mouse.x)
    Practise_loop.addData('mouse.y', mouse.y)
    Practise_loop.addData('mouse.leftButton', mouse.leftButton)
    Practise_loop.addData('mouse.midButton', mouse.midButton)
    Practise_loop.addData('mouse.rightButton', mouse.rightButton)
    Practise_loop.addData('mouse.time', mouse.time)
    Practise_loop.addData('mouse.clicked_name', mouse.clicked_name)
    Practise_loop.addData('mouse.started', mouse.tStart)
    Practise_loop.addData('mouse.stopped', mouse.tStop)
    #eyetracker.user_data("%s_END" %Img)
    #time.sleep(0.0066)
    #eyetracker.user_data("0")

    # ------Prepare to start Routine "Practise_feedback"-------
    continueRoutine = True
    routineTimer.add(0.700000)
    # update component parameters for each repeat
    if mouse.clicked_name==["star","background"]:
        sound='Sounds/correct3.wav'
        Practise_loop.addData('Practise_acc', 1)
        Practise_loop.addData('Mouse_click_X', mouse.x[-1])
        Practise_loop.addData('Mouse_click_Y', mouse.y[-1])
        Practise_loop.addData('Reaction_time', mouse.time[-1])
    elif mouse.clicked_name==["background"]:
        sound='Sounds/wrong2.wav'
        Practise_loop.addData('Practise_acc', 0)
        Practise_loop.addData('Mouse_click_X', mouse.x[-1])
        Practise_loop.addData('Mouse_click_Y', mouse.y[-1])
        Practise_loop.addData('Reaction_time', mouse.time[-1])
    else:
        sound='Sounds/cuckoo.wav'
        Practise_loop.addData('Practise_acc', -9)

    sound_1.setSound(sound, secs=0.7, hamming=False)
    sound_1.setVolume(1, log=False)
    # keep track of which components have finished
    Practise_feedbackComponents = [sound_1]
    for thisComponent in Practise_feedbackComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Practise_feedbackClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "Practise_feedback"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = Practise_feedbackClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Practise_feedbackClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        if mouse.clicked_name==["star","background"]:
            v=visual.ImageStim(win=win, image='Stimuli/v.png', pos=(0, 0),size=(150,150))
            v.draw()
        elif mouse.clicked_name==["background"]:
            x=visual.ImageStim(win=win, image='Stimuli/x.png', pos=(0, 0),size=(150,150))
            x.draw()
        else:
            clock=visual.ImageStim(win=win, image='Stimuli/clock_.png', pos=(0, 0))
            clock.draw()
        # start/stop sound_1
        if sound_1.status == NOT_STARTED and t >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            sound_1.frameNStart = frameN  # exact frame index
            sound_1.tStart = t  # local t and not account for scr refresh
            sound_1.tStartRefresh = tThisFlipGlobal  # on global time
            sound_1.play()  # start the sound (it finishes automatically)
        if sound_1.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > sound_1.tStartRefresh + 0.7-frameTolerance:
                # keep track of stop time/frame for later
                sound_1.tStop = t  # not accounting for scr refresh
                sound_1.frameNStop = frameN  # exact frame index
                win.timeOnFlip(sound_1, 'tStopRefresh')  # time at next scr refresh
                sound_1.stop()

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

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

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

    # -------Ending Routine "Practise_feedback"-------
    for thisComponent in Practise_feedbackComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    sound_1.stop()  # ensure sound has stopped at end of routine
    thisExp.nextEntry()

# completed 1 repeats of 'Practise_loop'

# ------Prepare to start Routine "Start"-------
continueRoutine = True
# update component parameters for each repeat
# keep track of which components have finished
StartComponents = [worldmap, plot2, next2]
for thisComponent in StartComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
StartClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "Start"-------
while continueRoutine:
    # get current time
    t = StartClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=StartClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # *worldmap* updates
    if worldmap.status == NOT_STARTED and tThisFlip >= 0-frameTolerance:
        # keep track of start time/frame for later
        worldmap.frameNStart = frameN  # exact frame index
        worldmap.tStart = t  # local t and not account for scr refresh
        worldmap.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(worldmap, 'tStartRefresh')  # time at next scr refresh
        worldmap.setAutoDraw(True)
    if worldmap.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > worldmap.tStartRefresh + 6-frameTolerance:
            # keep track of stop time/frame for later
            worldmap.tStop = t  # not accounting for scr refresh
            worldmap.frameNStop = frameN  # exact frame index
            win.timeOnFlip(worldmap, 'tStopRefresh')  # time at next scr refresh
            worldmap.setAutoDraw(False)

    # *plot2* updates
    if plot2.status == NOT_STARTED and tThisFlip >= 6-frameTolerance:
        # keep track of start time/frame for later
        plot2.frameNStart = frameN  # exact frame index
        plot2.tStart = t  # local t and not account for scr refresh
        plot2.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(plot2, 'tStartRefresh')  # time at next scr refresh
        plot2.setAutoDraw(True)

    # *next2* updates
    if next2.status == NOT_STARTED and tThisFlip >= 6-frameTolerance:
        # keep track of start time/frame for later
        next2.frameNStart = frameN  # exact frame index
        next2.tStart = t  # local t and not account for scr refresh
        next2.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(next2, 'tStartRefresh')  # time at next scr refresh
        next2.setAutoDraw(True)
    if mouse.isPressedIn(next2):
        continueRoutine=False

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

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

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

# -------Ending Routine "Start"-------
for thisComponent in StartComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('worldmap.started', worldmap.tStartRefresh)
thisExp.addData('worldmap.stopped', worldmap.tStopRefresh)
thisExp.addData('plot2.started', plot2.tStartRefresh)
thisExp.addData('plot2.stopped', plot2.tStopRefresh)
thisExp.addData('next2.started', next2.tStartRefresh)
thisExp.addData('next2.stopped', next2.tStopRefresh)
# the Routine "Start" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
Learning_loop = data.TrialHandler(nReps=4, method='random',
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions(condition),
    seed=None, name='Learning_loop')
thisExp.addLoop(Learning_loop)  # add the loop to the experiment
thisLearning_loop = Learning_loop.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisLearning_loop.rgb)
if thisLearning_loop != None:
    for paramName in thisLearning_loop:
        exec('{} = thisLearning_loop[paramName]'.format(paramName))

for thisLearning_loop in Learning_loop:
    currentLoop = Learning_loop
    # abbreviate parameter names if possible (e.g. rgb = thisLearning_loop.rgb)
    if thisLearning_loop != None:
        for paramName in thisLearning_loop:
            exec('{} = thisLearning_loop[paramName]'.format(paramName))

    # ------Prepare to start Routine "fixation"-------
    continueRoutine = True
    # update component parameters for each repeat
    fixation_started=False
    # keep track of which components have finished
    fixationComponents = [fix_cross]
    for thisComponent in fixationComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    fixationClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "fixation"-------
    while continueRoutine:
        # get current time
        t = fixationClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=fixationClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *fix_cross* updates
        if fix_cross.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            fix_cross.frameNStart = frameN  # exact frame index
            fix_cross.tStart = t  # local t and not account for scr refresh
            fix_cross.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(fix_cross, 'tStartRefresh')  # time at next scr refresh
            fix_cross.setAutoDraw(True)
        if eyetracker:
            gpos=eyetracker.sample()
            if type(gpos) in [list,tuple]:
                x,y=gpos[0],gpos[1]
                distance_from_center=np.sqrt(abs(x-0)**2+abs(y-0)**2)
                if distance_from_center<=80:
                    if not fixation_started:
                        fixation_started=True
                        fixation_start_time=t
                    if fixation_start_time>0.40:
                        continueRoutine=False
                    else:
                        fixation_started=False

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

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

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

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

    # ------Prepare to start Routine "Learning_trials"-------
    continueRoutine = True
    # update component parameters for each repeat
    # setup some python lists for storing info about the mouse2
    mouse2.x = []
    mouse2.y = []
    mouse2.leftButton = []
    mouse2.midButton = []
    mouse2.rightButton = []
    mouse2.time = []
    mouse2.clicked_name = []
    gotValidClick = False  # until a click is received
    background2.setImage(List)
    Star.setPos((StarX,StarY))
    Star.setImage('Stimuli/20x20t.png')
    if Learning_loop.thisRepN ==0:
        duration=30
    elif Learning_loop.thisRepN ==1:
        duration=25
    elif Learning_loop.thisRepN ==2:
        duration=20
    else:
        duration=15

    mouse2.setPos([0,0])
    eyetracker.user_data("%s_%s_%s_START" % (Images,Clutter_Level,Learning_loop.thisRepN))
    # keep track of which components have finished
    Learning_trialsComponents = [mouse2, background2, Star, gaze_Cursor]
    for thisComponent in Learning_trialsComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Learning_trialsClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "Learning_trials"-------
    while continueRoutine:
        # get current time
        t = Learning_trialsClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Learning_trialsClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        # *mouse2* updates
        if mouse2.status == NOT_STARTED and t >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            mouse2.frameNStart = frameN  # exact frame index
            mouse2.tStart = t  # local t and not account for scr refresh
            mouse2.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(mouse2, 'tStartRefresh')  # time at next scr refresh
            mouse2.status = STARTED
            mouse2.mouseClock.reset()
            prevButtonState = mouse2.getPressed()  # if button is down already this ISN'T a new click
        if mouse2.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > mouse2.tStartRefresh + duration-frameTolerance:
                # keep track of stop time/frame for later
                mouse2.tStop = t  # not accounting for scr refresh
                mouse2.frameNStop = frameN  # exact frame index
                win.timeOnFlip(mouse2, 'tStopRefresh')  # time at next scr refresh
                mouse2.status = FINISHED
        if mouse2.status == STARTED:  # only update if started and not finished!
            buttons = mouse2.getPressed()
            if buttons != prevButtonState:  # button state changed?
                prevButtonState = buttons
                if sum(buttons) > 0:  # state changed to a new click
                    # check if the mouse was inside our 'clickable' objects
                    gotValidClick = False
                    for obj in [Star,background2]:
                        if obj.contains(mouse2):
                            gotValidClick = True
                            mouse2.clicked_name.append(obj.name)
                    x, y = mouse2.getPos()
                    mouse2.x.append(x)
                    mouse2.y.append(y)
                    buttons = mouse2.getPressed()
                    mouse2.leftButton.append(buttons[0])
                    mouse2.midButton.append(buttons[1])
                    mouse2.rightButton.append(buttons[2])
                    mouse2.time.append(mouse2.mouseClock.getTime())

        # *background2* updates
        if background2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            background2.frameNStart = frameN  # exact frame index
            background2.tStart = t  # local t and not account for scr refresh
            background2.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(background2, 'tStartRefresh')  # time at next scr refresh
            background2.setAutoDraw(True)
        if background2.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > background2.tStartRefresh + duration-frameTolerance:
                # keep track of stop time/frame for later
                background2.tStop = t  # not accounting for scr refresh
                background2.frameNStop = frameN  # exact frame index
                win.timeOnFlip(background2, 'tStopRefresh')  # time at next scr refresh
                background2.setAutoDraw(False)

        # *Star* updates
        if Star.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            Star.frameNStart = frameN  # exact frame index
            Star.tStart = t  # local t and not account for scr refresh
            Star.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(Star, 'tStartRefresh')  # time at next scr refresh
            Star.setAutoDraw(True)
        if Star.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > Star.tStartRefresh + duration-frameTolerance:
                # keep track of stop time/frame for later
                Star.tStop = t  # not accounting for scr refresh
                Star.frameNStop = frameN  # exact frame index
                win.timeOnFlip(Star, 'tStopRefresh')  # time at next scr refresh
                Star.setAutoDraw(False)

        # *gaze_Cursor* updates
        if gaze_Cursor.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            gaze_Cursor.frameNStart = frameN  # exact frame index
            gaze_Cursor.tStart = t  # local t and not account for scr refresh
            gaze_Cursor.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(gaze_Cursor, 'tStartRefresh')  # time at next scr refresh
            gaze_Cursor.setAutoDraw(True)
        if gaze_Cursor.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > gaze_Cursor.tStartRefresh + duration-frameTolerance:
                # keep track of stop time/frame for later
                gaze_Cursor.tStop = t  # not accounting for scr refresh
                gaze_Cursor.frameNStop = frameN  # exact frame index
                win.timeOnFlip(gaze_Cursor, 'tStopRefresh')  # time at next scr refresh
                gaze_Cursor.setAutoDraw(False)
        if gaze_Cursor.status == STARTED:  # only update if drawing
            gaze_Cursor.setOpacity(display_gaze, log=False)
            gaze_Cursor.setPos([x,y], log=False)
        if eyetracker:
            if event.getKeys(keyList=['g',]):
                display_gaze=not display_gaze
            gpos=eyetracker.sample()
            if type(gpos) in [list,tuple]:
                x,y=gpos[0],gpos[1]
                d=np.sqrt(abs(x-StarX)**2+abs(y-StarY)**2)
                rounded_d=np.round(d,0)
                if rounded_d<= fixation_boundary and mouse2.clicked_name==["Star","background2"]:
                    continueRoutine=False
                elif mouse2.clicked_name==["background2"]:
                    continueRoutine=False
                else:
                    continueRoutine=True

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

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

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

    # -------Ending Routine "Learning_trials"-------
    for thisComponent in Learning_trialsComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # store data for Learning_loop (TrialHandler)
    Learning_loop.addData('mouse2.x', mouse2.x)
    Learning_loop.addData('mouse2.y', mouse2.y)
    Learning_loop.addData('mouse2.leftButton', mouse2.leftButton)
    Learning_loop.addData('mouse2.midButton', mouse2.midButton)
    Learning_loop.addData('mouse2.rightButton', mouse2.rightButton)
    Learning_loop.addData('mouse2.time', mouse2.time)
    Learning_loop.addData('mouse2.clicked_name', mouse2.clicked_name)
    Learning_loop.addData('mouse2.started', mouse2.tStart)
    Learning_loop.addData('mouse2.stopped', mouse2.tStop)
    Learning_loop.addData('background2.started', background2.tStartRefresh)
    Learning_loop.addData('background2.stopped', background2.tStopRefresh)
    Learning_loop.addData('Star.started', Star.tStartRefresh)
    Learning_loop.addData('Star.stopped', Star.tStopRefresh)
    Learning_loop.addData('gaze_Cursor.started', gaze_Cursor.tStartRefresh)
    Learning_loop.addData('gaze_Cursor.stopped', gaze_Cursor.tStopRefresh)
    eyetracker.user_data("%s_%s_%s_END" % (Images,Clutter_Level,Learning_loop.thisRepN))
    #time.sleep(0.0066)
    eyetracker.user_data("0")
    # the Routine "Learning_trials" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    # ------Prepare to start Routine "Learning_feedback"-------
    continueRoutine = True
    routineTimer.add(0.700000)
    # update component parameters for each repeat
    my_trial+=1
    if mouse2.clicked_name==["Star","background2"]:
        sound='Sounds/correct3.wav'
        Learning_loop.addData('Practise_acc', 1)
        Learning_loop.addData('Mouse_click_X', mouse2.x[-1])
        Learning_loop.addData('Mouse_click_Y', mouse2.y[-1])
        Learning_loop.addData('Reaction_time', mouse2.time[-1])
        Acc_trials+=1
        Acc_blocks+=1
    elif mouse2.clicked_name==["background2"]:
        sound='Sounds/wrong2.wav'
        Learning_loop.addData('Practise_acc', 0)
        Learning_loop.addData('Mouse_click_X', mouse2.x[-1])
        Learning_loop.addData('Mouse_click_Y', mouse2.y[-1])
        Learning_loop.addData('Reaction_time', mouse2.time[-1])
    else:
        sound='Sounds/cuckoo.wav'
        Learning_loop.addData('Practise_acc', -9)
    sound_2.setSound(sound, secs=0.7, hamming=False)
    sound_2.setVolume(1, log=False)
    # keep track of which components have finished
    Learning_feedbackComponents = [sound_2]
    for thisComponent in Learning_feedbackComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Learning_feedbackClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "Learning_feedback"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = Learning_feedbackClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Learning_feedbackClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        if mouse2.clicked_name==["Star","background2"]:
            v=visual.ImageStim(win=win, image='Stimuli/v.png', pos=(0, 0), size=(150,150))
            v.draw()
        elif mouse2.clicked_name==["background2"]:
            x=visual.ImageStim(win=win, image='Stimuli/x.png', pos=(0, 0), size=(150,150))
            x.draw()
        else:
            clock=visual.ImageStim(win=win, image='Stimuli/clock_.png', pos=(0, 0))
            clock.draw()
        # start/stop sound_2
        if sound_2.status == NOT_STARTED and t >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            sound_2.frameNStart = frameN  # exact frame index
            sound_2.tStart = t  # local t and not account for scr refresh
            sound_2.tStartRefresh = tThisFlipGlobal  # on global time
            sound_2.play()  # start the sound (it finishes automatically)
        if sound_2.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > sound_2.tStartRefresh + 0.7-frameTolerance:
                # keep track of stop time/frame for later
                sound_2.tStop = t  # not accounting for scr refresh
                sound_2.frameNStop = frameN  # exact frame index
                win.timeOnFlip(sound_2, 'tStopRefresh')  # time at next scr refresh
                sound_2.stop()

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

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

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

    # -------Ending Routine "Learning_feedback"-------
    for thisComponent in Learning_feedbackComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    sound_2.stop()  # ensure sound has stopped at end of routine

    # ------Prepare to start Routine "Trial_Break"-------
    continueRoutine = True
    # update component parameters for each repeat
    msg_3=f"{Acc_trials}/14"
    if Learning_loop.thisTrialN not in [13,27,41,69,83,97,125,139,153,181,195,209]:
        continueRoutine=False

    break_text.setText(msg_3)
    # keep track of which components have finished
    Trial_BreakComponents = [break_text, next3]
    for thisComponent in Trial_BreakComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Trial_BreakClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "Trial_Break"-------
    while continueRoutine:
        # get current time
        t = Trial_BreakClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Trial_BreakClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        feedback=visual.ImageStim(win=win, image='Stimuli/trial_feedback.png', pos=(0, 0))
        feedback.draw()
        if mouse2.isPressedIn(next3,buttons=[0]):
            continueRoutine=False

        # *break_text* updates
        if break_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            break_text.frameNStart = frameN  # exact frame index
            break_text.tStart = t  # local t and not account for scr refresh
            break_text.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(break_text, 'tStartRefresh')  # time at next scr refresh
            break_text.setAutoDraw(True)

        # *next3* updates
        if next3.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            next3.frameNStart = frameN  # exact frame index
            next3.tStart = t  # local t and not account for scr refresh
            next3.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(next3, 'tStartRefresh')  # time at next scr refresh
            next3.setAutoDraw(True)

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

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

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

    # -------Ending Routine "Trial_Break"-------
    for thisComponent in Trial_BreakComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    Learning_loop.addData('break_text.started', break_text.tStartRefresh)
    Learning_loop.addData('break_text.stopped', break_text.tStopRefresh)
    Learning_loop.addData('next3.started', next3.tStartRefresh)
    Learning_loop.addData('next3.stopped', next3.tStopRefresh)
    # the Routine "Trial_Break" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    # ------Prepare to start Routine "Block_Break"-------
    continueRoutine = True
    # update component parameters for each repeat
    eyetracker.stop_recording()
    # keep track of which components have finished
    Block_BreakComponents = [block_break_text, next_5]
    for thisComponent in Block_BreakComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    Block_BreakClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "Block_Break"-------
    while continueRoutine:
        # get current time
        t = Block_BreakClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=Block_BreakClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        if Learning_loop.thisN==55 or Learning_loop.thisN==111 or Learning_loop.thisN==167 or Learning_loop.thisN==223:
            continueRoutine=True
            if mouse.isPressedIn(next_5, buttons=[0]):
                continueRoutine=False
        else:
            continueRoutine=False

        if Learning_loop.thisN==55:
            map=visual.ImageStim(win=win, image='Stimuli/block1_feedback.png', pos=(0, 0))
            map.draw()
            msg_4=f"{Acc_blocks}/56"

        elif Learning_loop.thisN==111:
            map=visual.ImageStim(win=win, image='Stimuli/block2_feedback.png', pos=(0, 0))
            map.draw()
            msg_4=f"{Acc_blocks}/56"

        elif Learning_loop.thisN==167:
            map=visual.ImageStim(win=win, image='Stimuli/block3_feedback.png', pos=(0, 0))
            map.draw()
            msg_4=f"{Acc_blocks}/56"

        elif Learning_loop.thisN==223:
            map=visual.ImageStim(win=win, image='Stimuli/block4_feedback.png', pos=(0, 0))
            map.draw()
            msg_4=f"{Acc_blocks}/56"

        # *block_break_text* updates
        if block_break_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            block_break_text.frameNStart = frameN  # exact frame index
            block_break_text.tStart = t  # local t and not account for scr refresh
            block_break_text.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(block_break_text, 'tStartRefresh')  # time at next scr refresh
            block_break_text.setAutoDraw(True)
        if block_break_text.status == STARTED:  # only update if drawing
            block_break_text.setText(msg_4, log=False)

        # *next_5* updates
        if next_5.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            next_5.frameNStart = frameN  # exact frame index
            next_5.tStart = t  # local t and not account for scr refresh
            next_5.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(next_5, 'tStartRefresh')  # time at next scr refresh
            next_5.setAutoDraw(True)

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

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

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

    # -------Ending Routine "Block_Break"-------
    for thisComponent in Block_BreakComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    map=None
    msg=''
    eyetracker.start_recording()
    Learning_loop.addData('block_break_text.started', block_break_text.tStartRefresh)
    Learning_loop.addData('block_break_text.stopped', block_break_text.tStopRefresh)
    Learning_loop.addData('next_5.started', next_5.tStartRefresh)
    Learning_loop.addData('next_5.stopped', next_5.tStopRefresh)
    # the Routine "Block_Break" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    # ------Prepare to start Routine "gap"-------
    continueRoutine = True
    # update component parameters for each repeat
    # keep track of which components have finished
    gapComponents = []
    for thisComponent in gapComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    gapClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "gap"-------
    while continueRoutine:
        # get current time
        t = gapClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=gapClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

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

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

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

    # -------Ending Routine "gap"-------
    for thisComponent in gapComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    if my_trial in [14,28,42,56,70,84,98,112,126,140,154,168,182,196,210,224]:
        Acc_trials=0

    if my_trial in [56,112,168,224]:
        Acc_blocks=0

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

# completed 4 repeats of 'Learning_loop'

# ------Prepare to start Routine "End"-------
continueRoutine = True
routineTimer.add(6.500000)
# update component parameters for each repeat
# keep track of which components have finished
EndComponents = [cloud, family]
for thisComponent in EndComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
EndClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "End"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = EndClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=EndClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # *cloud* updates
    if cloud.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        cloud.frameNStart = frameN  # exact frame index
        cloud.tStart = t  # local t and not account for scr refresh
        cloud.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(cloud, 'tStartRefresh')  # time at next scr refresh
        cloud.setAutoDraw(True)
    if cloud.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > cloud.tStartRefresh + 3-frameTolerance:
            # keep track of stop time/frame for later
            cloud.tStop = t  # not accounting for scr refresh
            cloud.frameNStop = frameN  # exact frame index
            win.timeOnFlip(cloud, 'tStopRefresh')  # time at next scr refresh
            cloud.setAutoDraw(False)

    # *family* updates
    if family.status == NOT_STARTED and tThisFlip >= 3-frameTolerance:
        # keep track of start time/frame for later
        family.frameNStart = frameN  # exact frame index
        family.tStart = t  # local t and not account for scr refresh
        family.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(family, 'tStartRefresh')  # time at next scr refresh
        family.setAutoDraw(True)
    if family.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > family.tStartRefresh + 3.5-frameTolerance:
            # keep track of stop time/frame for later
            family.tStop = t  # not accounting for scr refresh
            family.frameNStop = frameN  # exact frame index
            win.timeOnFlip(family, 'tStopRefresh')  # time at next scr refresh
            family.setAutoDraw(False)

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

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

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

# -------Ending Routine "End"-------
for thisComponent in EndComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('cloud.started', cloud.tStartRefresh)
thisExp.addData('cloud.stopped', cloud.tStopRefresh)
thisExp.addData('family.started', family.tStartRefresh)
thisExp.addData('family.stopped', family.tStopRefresh)
thisExp.addData("condition_file",condition)
eyetracker.stop_recording()
eyetracker.close()

# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()

# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort()  # or data files will save again on exit
win.close()
core.quit()

reason: import numpy,from numpy


text:
"""
The RMAType definition.
"""

__classification__ = "UNCLASSIFIED"
__author__ = "Thomas McCullough"

from typing import Union

import numpy
from numpy.linalg import norm

from sarpy.io.xml.base import Serializable
from sarpy.io.xml.descriptors import StringEnumDescriptor, FloatDescriptor, \
    BooleanDescriptor, SerializableDescriptor

from .base import DEFAULT_STRICT, FLOAT_FORMAT
from .blocks import XYZType, Poly1DType, Poly2DType
from .utils import _get_center_frequency

class RMRefType(Serializable):
    """
    Range migration reference element of RMA type.
    """

    _fields = ('PosRef', 'VelRef', 'DopConeAngRef')
    _required = _fields
    _numeric_format = {'DopConeAngRef': FLOAT_FORMAT, }
    # descriptors
    PosRef = SerializableDescriptor(
        'PosRef', XYZType, _required, strict=DEFAULT_STRICT,
        docstring='Platform reference position in ECF coordinates used to establish '
                  'the reference slant plane.')  # type: XYZType
    VelRef = SerializableDescriptor(
        'VelRef', XYZType, _required, strict=DEFAULT_STRICT,
        docstring='Platform reference velocity vector in ECF coordinates used to establish '
                  'the reference slant plane.')  # type: XYZType
    DopConeAngRef = FloatDescriptor(
        'DopConeAngRef', _required, strict=DEFAULT_STRICT,
        docstring='Reference Doppler Cone Angle in degrees.')  # type: float

    def __init__(self, PosRef=None, VelRef=None, DopConeAngRef=None, **kwargs):
        """

        Parameters
        ----------
        PosRef : XYZType|numpy.ndarray|list|tuple
        VelRef : XYZType|numpy.ndarray|list|tuple
        DopConeAngRef : float
        kwargs
        """

        if '_xml_ns' in kwargs:
            self._xml_ns = kwargs['_xml_ns']
        if '_xml_ns_key' in kwargs:
            self._xml_ns_key = kwargs['_xml_ns_key']
        self.PosRef = PosRef
        self.VelRef = VelRef
        self.DopConeAngRef = DopConeAngRef
        super(RMRefType, self).__init__(**kwargs)

class INCAType(Serializable):
    """Parameters for Imaging Near Closest Approach (INCA) image description."""
    _fields = (
        'TimeCAPoly', 'R_CA_SCP', 'FreqZero', 'DRateSFPoly', 'DopCentroidPoly', 'DopCentroidCOA')
    _required = ('TimeCAPoly', 'R_CA_SCP', 'FreqZero', 'DRateSFPoly')
    _numeric_format = {'R_CA_SCP': '0.17E', 'FreqZero': '0.17E'}
    # descriptors
    TimeCAPoly = SerializableDescriptor(
        'TimeCAPoly', Poly1DType, _required, strict=DEFAULT_STRICT,
        docstring='Polynomial function that yields *Time of Closest Approach* as function of '
                  'image column *(azimuth)* coordinate in meters. Time relative to '
                  'collection start in seconds.')  # type: Poly1DType
    R_CA_SCP = FloatDescriptor(
        'R_CA_SCP', _required, strict=DEFAULT_STRICT,
        docstring='*Range at Closest Approach (R_CA)* for the *Scene Center Point (SCP)* in meters.')  # type: float
    FreqZero = FloatDescriptor(
        'FreqZero', _required, strict=DEFAULT_STRICT,
        docstring=r'*RF frequency* :\math:`(f_0)` in Hz used for computing '
                  r'Doppler Centroid values. Typical :math:`f_0` '
                  r'set equal to center transmit frequency.')  # type: float
    DRateSFPoly = SerializableDescriptor(
        'DRateSFPoly', Poly2DType, _required, strict=DEFAULT_STRICT,
        docstring='Polynomial function that yields *Doppler Rate scale factor (DRSF)* '
                  'as a function of image location. Yields `DRSF` as a function of image '
                  'range coordinate ``(variable 1)`` and azimuth coordinate ``(variable 2)``. '
                  'Used to compute Doppler Rate at closest approach.')  # type: Poly2DType
    DopCentroidPoly = SerializableDescriptor(
        'DopCentroidPoly', Poly2DType, _required, strict=DEFAULT_STRICT,
        docstring='Polynomial function that yields Doppler Centroid value as a '
                  'function of image location *(fdop_DC)*. The *fdop_DC* is the '
                  'Doppler frequency at the peak signal response. The polynomial is a function '
                  'of image range coordinate ``(variable 1)`` and azimuth coordinate ``(variable 2)``. '
                  '*Note: Only used for Stripmap and Dynamic Stripmap collections.*')  # type: Poly2DType
    DopCentroidCOA = BooleanDescriptor(
        'DopCentroidCOA', _required, strict=DEFAULT_STRICT,
        docstring="""Flag indicating that the COA is at the peak signal :math`fdop_COA = fdop_DC`.

        * `True` - if Pixel COA at peak signal for all pixels.

        * `False` otherwise.

        *Note:* Only used for Stripmap and Dynamic Stripmap.""")  # type: bool

    def __init__(self, TimeCAPoly=None, R_CA_SCP=None, FreqZero=None, DRateSFPoly=None,
                 DopCentroidPoly=None, DopCentroidCOA=None, **kwargs):
        """

        Parameters
        ----------
        TimeCAPoly : Poly1DType|numpy.ndarray|list|tuple
        R_CA_SCP : float
        FreqZero : float
        DRateSFPoly : Poly2DType|numpy.ndarray|list|tuple
        DopCentroidPoly : Poly2DType|numpy.ndarray|list|tuple
        DopCentroidCOA : bool
        kwargs : dict
        """

        if '_xml_ns' in kwargs:
            self._xml_ns = kwargs['_xml_ns']
        if '_xml_ns_key' in kwargs:
            self._xml_ns_key = kwargs['_xml_ns_key']
        self.TimeCAPoly = TimeCAPoly
        self.R_CA_SCP = R_CA_SCP
        self.FreqZero = FreqZero
        self.DRateSFPoly = DRateSFPoly
        self.DopCentroidPoly = DopCentroidPoly
        self.DopCentroidCOA = DopCentroidCOA
        super(INCAType, self).__init__(**kwargs)

    def _apply_reference_frequency(self, reference_frequency):
        if self.FreqZero is not None:
            self.FreqZero += reference_frequency

class RMAType(Serializable):
    """Parameters included when the image is formed using the Range Migration Algorithm."""
    _fields = ('RMAlgoType', 'ImageType', 'RMAT', 'RMCR', 'INCA')
    _required = ('RMAlgoType', 'ImageType')
    _choice = ({'required': True, 'collection': ('RMAT', 'RMCR', 'INCA')}, )
    # class variables
    _RM_ALGO_TYPE_VALUES = ('OMEGA_K', 'CSA', 'RG_DOP')
    # descriptors
    RMAlgoType = StringEnumDescriptor(
        'RMAlgoType', _RM_ALGO_TYPE_VALUES, _required, strict=DEFAULT_STRICT,
        docstring=r"""
        Identifies the type of migration algorithm used:

        * `OMEGA_K` - Algorithms that employ Stolt interpolation of the Kxt dimension. :math:`Kx = \sqrt{Kf^2 - Ky^2}`

        * `CSA` - Wave number algorithm that process two-dimensional chirp signals.

        * `RG_DOP` - Range-Doppler algorithms that employ *RCMC* in the compressed range domain.

        """)  # type: str
    RMAT = SerializableDescriptor(
        'RMAT', RMRefType, _required, strict=DEFAULT_STRICT,
        docstring='Parameters for *RMA with Along Track (RMAT)* motion compensation.')  # type: RMRefType
    RMCR = SerializableDescriptor(
        'RMCR', RMRefType, _required, strict=DEFAULT_STRICT,
        docstring='Parameters for *RMA with Cross Range (RMCR)* motion compensation.')  # type: RMRefType
    INCA = SerializableDescriptor(
        'INCA', INCAType, _required, strict=DEFAULT_STRICT,
        docstring='Parameters for *Imaging Near Closest Approach (INCA)* image description.')  # type: INCAType

    def __init__(self, RMAlgoType=None, RMAT=None, RMCR=None, INCA=None, **kwargs):
        """

        Parameters
        ----------
        RMAlgoType : str
        RMAT : RMRefType
        RMCR : RMRefType
        INCA : INCAType
        kwargs : dict
        """

        if '_xml_ns' in kwargs:
            self._xml_ns = kwargs['_xml_ns']
        if '_xml_ns_key' in kwargs:
            self._xml_ns_key = kwargs['_xml_ns_key']
        self.RMAlgoType = RMAlgoType
        self.RMAT = RMAT
        self.RMCR = RMCR
        self.INCA = INCA
        super(RMAType, self).__init__(**kwargs)

    @property
    def ImageType(self):  # type: () -> Union[None, str]
        """
        str: READ ONLY attribute. Identifies the specific RM image type / metadata type supplied. This is determined by
        returning the (first) attribute among `'RMAT', 'RMCR', 'INCA'` which is populated. `None` will be returned if
        none of them are populated.
        """

        for attribute in self._choice[0]['collection']:
            if getattr(self, attribute) is not None:
                return attribute
        return None

    def _derive_parameters(self, SCPCOA, Position, RadarCollection, ImageFormation):
        """
        Expected to be called from SICD parent.

        Parameters
        ----------
        SCPCOA : sarpy.io.complex.sicd_elements.SCPCOA.SCPCOAType
        Position : sarpy.io.complex.sicd_elements.Position.PositionType
        RadarCollection : sarpy.io.complex.sicd_elements.RadarCollection.RadarCollectionType
        ImageFormation : sarpy.io.complex.sicd_elements.ImageFormation.ImageFormationType

        Returns
        -------
        None
        """

        if SCPCOA is None:
            return

        scp = None if SCPCOA.ARPPos is None else SCPCOA.ARPPos.get_array()

        im_type = self.ImageType
        if im_type in ['RMAT', 'RMCR']:
            rm_ref = getattr(self, im_type)  # type: RMRefType
            if rm_ref.PosRef is None and SCPCOA.ARPPos is not None:
                rm_ref.PosRef = SCPCOA.ARPPos.copy()
            if rm_ref.VelRef is None and SCPCOA.ARPVel is not None:
                rm_ref.VelRef = SCPCOA.ARPVel.copy()
            if scp is not None and rm_ref.PosRef is not None and rm_ref.VelRef is not None:
                pos_ref = rm_ref.PosRef.get_array()
                vel_ref = rm_ref.VelRef.get_array()
                uvel_ref = vel_ref/norm(vel_ref)
                ulos = (scp - pos_ref)  # it absolutely could be that scp = pos_ref
                ulos_norm = norm(ulos)
                if ulos_norm > 0:
                    ulos /= ulos_norm
                    if rm_ref.DopConeAngRef is None:
                        rm_ref.DopConeAngRef = numpy.rad2deg(numpy.arccos(numpy.dot(uvel_ref, ulos)))
        elif im_type == 'INCA':
            if scp is not None and self.INCA.TimeCAPoly is not None and \
                    Position is not None and Position.ARPPoly is not None:
                t_zero = self.INCA.TimeCAPoly.Coefs[0]
                ca_pos = Position.ARPPoly(t_zero)
                if self.INCA.R_CA_SCP is None:
                    self.INCA.R_CA_SCP = norm(ca_pos - scp)
            if self.INCA.FreqZero is None:
                self.INCA.FreqZero = _get_center_frequency(RadarCollection, ImageFormation)

    def _apply_reference_frequency(self, reference_frequency):
        """
        If the reference frequency is used, adjust the necessary fields accordingly.
        Expected to be called by SICD parent.

        Parameters
        ----------
        reference_frequency : float
            The reference frequency.

        Returns
        -------
        None
        """

        if self.INCA is not None:
            # noinspection PyProtectedMember
            self.INCA._apply_reference_frequency(reference_frequency)

ext: py

max_stars_repo_name: spacefan/sarpy

max_issues_repo_name: spacefan/sarpy

max_forks_repo_name: spacefan/sarpy


text:
import pyautogui
import time
import numpy as np
import subprocess
import os

# Caution This Vpn Changer is only Written For NORDVPN!!!
class VpnChanger:

    #pause between each action
    def __init__(self,vpnlist):
        self.vpntexts = vpnlist
        self.counter = 0

    def changevpn(self):
        vpnsuc = -1
        for i in range(0,10):
            vpnsuc = self.trychangevpn()
            if vpnsuc==0:
                break
            else:
                self.counter +=1
                if (self.counter==len(self.vpntexts)):
                    break
        if vpnsuc==-1:
            print('Big error in change vpn for some reason')

    def trychangevpn(self):
        try:
            os.popen('"C:/Program Files (x86)/NordVPN/nordvpn" -d')
            time.sleep(10)
            curip = os.popen('nslookup myip.opendns.com resolver1.opendns.com').read()
            pos = curip.find('myip.opendns.com')
            if (pos==-1):
                return -1
            oscommand = '"C:/Program Files (x86)/NordVPN/nordvpn" -c -n ' + '"' +  self.vpntexts[self.counter] + '"'
            os.popen(oscommand)
            time.sleep(45)
            chngip = os.popen('nslookup myip.opendns.com resolver1.opendns.com').read()
            if (chngip.find('myip.opendns.com')!=-1 and chngip!=curip):
                return 0
            else:
                return -1
        except:
            print('Error in trychange vpn')
            return -1

reason: import numpy


text:
#!/usr/bin/env python

"""
Extract a subset of the data for the given speaker.

Author: Herman Kamper
Contact: kamperh@gmail.com
Date: 2015
"""

from os import path
import argparse
import pickle
import numpy as np
import os
import sys

output_dir = "data"

#-----------------------------------------------------------------------------#
#                              UTILITY FUNCTIONS                              #
#-----------------------------------------------------------------------------#

def check_argv():
    """Check the command line arguments."""
    parser = argparse.ArgumentParser(description=__doc__.strip().split("\n")[0], add_help=False)
    parser.add_argument("data_dir", type=str, help="data directory")
    parser.add_argument("speaker", type=str, help="target speaker")
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)
    return parser.parse_args()

def get_data_speaker(speaker, data_dir):

    src_landmarks_dict_fn = path.join(data_dir, "landmarks.pkl")
    src_dense_embeddings_fn = path.join(data_dir, "dense_embeddings.npz")
    src_vec_ids_dict_fn = path.join(data_dir, "vec_ids.pkl")
    src_durations_dict_fn = path.join(data_dir, "durations.pkl")
    src_word_gt_dict_fn = path.join(data_dir, "word_gt.pkl")
    src_phone_gt_dict_fn = path.join(data_dir, "phone_gt.pkl")

    print("Reading:", src_landmarks_dict_fn)
    with open(src_landmarks_dict_fn, "rb") as f:
        src_landmarks_dict = pickle.load(f)
    print("Reading:", src_dense_embeddings_fn)
    src_dense_embeddings = np.load(src_dense_embeddings_fn)
    print("Reading:", src_vec_ids_dict_fn)
    with open(src_vec_ids_dict_fn, "rb") as f:
        src_vec_ids_dict = pickle.load(f)
    print("Reading:", src_durations_dict_fn)
    with open(src_durations_dict_fn, "rb") as f:
        src_durations_dict = pickle.load(f)
    print("Reading:", src_word_gt_dict_fn)
    with open(src_word_gt_dict_fn, "rb") as f:
        src_word_gt_bound_dict = pickle.load(f)
        src_word_gt_label_dict = pickle.load(f)
    print("Reading:", src_phone_gt_dict_fn)
    with open(src_phone_gt_dict_fn, "rb") as f:
        src_phone_gt_bound_dict = pickle.load(f)
        src_phone_gt_label_dict = pickle.load(f)
    print("Total no. of utterances:", len(src_phone_gt_bound_dict))

    print("Speaker:", speaker)
    keys = [
        i for i in src_phone_gt_bound_dict.keys() if i.startswith(speaker) or
        i.startswith("nchlt-tso-" + speaker)
        ]
    print("No. of utterances from speaker:", len(keys))

    print("Filtering")
    landmarks_dict = {}
    dense_embeddings = {}
    vec_ids_dict = {}
    durations_dict = {}
    word_gt_bound_dict = {}
    word_gt_label_dict = {}
    phone_gt_bound_dict = {}
    phone_gt_label_dict = {}
    for key in keys:
        landmarks_dict[key] = src_landmarks_dict[key]
        dense_embeddings[key] = src_dense_embeddings[key]
        vec_ids_dict[key] = src_vec_ids_dict[key]
        durations_dict[key] = src_durations_dict[key]
        word_gt_bound_dict[key] = src_word_gt_bound_dict[key]
        word_gt_label_dict[key] = src_word_gt_label_dict[key]
        phone_gt_bound_dict[key] = src_phone_gt_bound_dict[key]
        phone_gt_label_dict[key] = src_phone_gt_label_dict[key]
    print("No. of utterances:", len(phone_gt_bound_dict))

    data_dir = path.join(data_dir, speaker)
    if not path.isdir(data_dir):
        os.makedirs(data_dir)

    landmarks_dict_fn = path.join(data_dir, "landmarks.pkl")
    dense_embeddings_fn = path.join(data_dir, "dense_embeddings.npz")
    vec_ids_dict_fn = path.join(data_dir, "vec_ids.pkl")
    durations_dict_fn = path.join(data_dir, "durations.pkl")
    word_gt_dict_fn = path.join(data_dir, "word_gt.pkl")
    phone_gt_dict_fn = path.join(data_dir, "phone_gt.pkl")
    print("Writing:", landmarks_dict_fn)
    with open(landmarks_dict_fn, "wb") as f:
        pickle.dump(landmarks_dict, f, -1)
    print("Writing:", dense_embeddings_fn)
    np.savez_compressed(dense_embeddings_fn, **dense_embeddings)
    print("Writing:", vec_ids_dict_fn)
    with open(vec_ids_dict_fn, "wb") as f:
        pickle.dump(vec_ids_dict, f, -1)
    print("Writing:", durations_dict_fn)
    with open(durations_dict_fn, "wb") as f:
        pickle.dump(durations_dict, f, -1)
    print("Writing:", word_gt_dict_fn)
    with open(word_gt_dict_fn, "wb") as f:
        pickle.dump(word_gt_bound_dict, f, -1)
        pickle.dump(word_gt_label_dict, f, -1)
    print("Writing:", phone_gt_dict_fn)
    with open(phone_gt_dict_fn, "wb") as f:
        pickle.dump(phone_gt_bound_dict, f, -1)
        pickle.dump(phone_gt_label_dict, f, -1)

#-----------------------------------------------------------------------------#
#                                MAIN FUNCTION                                #
#-----------------------------------------------------------------------------#

def main():
    args = check_argv()

    data_dir = args.data_dir
    print("Output directory:", data_dir)

    get_data_speaker(args.speaker, data_dir)

if __name__ == "__main__":
    main()


text:
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

"""
Created on Sun Nov 12 08:44:37 2017

@author: Belter
"""

def sampling2pmf(n, dist, m=100000):
    """
    n: sample size for each experiment
    m: how many times do you do experiment, fix in 100000
    dist: frozen distribution
    """
    current_dist = dist
    sum_of_samples = []
    for i in range(m):
        samples = current_dist.rvs(size=n)  # 与每次取一个值，取n次效果相同
        # print(samples)
        sum_of_samples.append(np.sum(samples))
    # 下面计算频率的方式不适合连续型随机变量，因此直接返回随机变量的和
    # val, cnt = np.unique(sum_of_samples, return_counts=True)
    # pmf = cnt / len(sum_of_samples)
    # return val, pmf
    return sum_of_samples

def plot(n, dist, subplot, plt_handle, dist_type):
    """
    :param n: sample size
    :param dist: distribution of each single sample
    :param subplot: location of sub-graph, such as 221, 222, 223, 224
    :param plt_handle: plt object
    :param dist_type: the type of distribution
    :return: plt object
    """
    bins = 20000
    plt = plt_handle
    plt.subplot(subplot)
    mu = n * dist.mean()
    sigma = np.sqrt(n * dist.var())
    samples = sampling2pmf(n=n, dist=dist)
    # print(samples)
    # normed参数可以对直方图进行标准化，从而使纵坐标表示概率而不是次数
    plt.hist(samples, normed=True, bins=50, histtype='stepfilled', alpha=1)
    plt.ylabel('Probability')
    plt.title('Sum of {} dist. (n={})'.format(dist_type, n))
    # normal distribution
    norm_dis = stats.norm(mu, sigma)
    norm_x = np.linspace(mu - 3 * sigma, mu + 3 * sigma, bins)
    pdf1 = norm_dis.pdf(norm_x)
    plt.plot(norm_x, pdf1, 'r--', alpha=0.4)
    return plt

size = [1, 2, 3, 4, 8, 10]

# sum of bernoulli distribution
# dist_type = 'bern'
# bern_para = [0.99]
# single_sample_dist = stats.bernoulli(p=bern_para[0])  # 定义一个伯努利分布

# sum of binomial distribution
# dist_type = 'bino'
# bino_para = [20, 0.4]
# single_sample_dist = stats.binom(n=bino_para[0], p=bino_para[1])  # 定义一个二项分布

# sum of uniform distribution
dist_type = 'uniform'
uniform_para = [3, 2]
single_sample_dist = stats.uniform(loc=uniform_para[0], scale=uniform_para[1])  # 定义一个均匀分布

# 下面是利用matplotlib画图
plt.figure(1)
plt = plot(n=size[0], dist=single_sample_dist, subplot=321, plt_handle=plt, dist_type=dist_type)
plt = plot(n=size[1], dist=single_sample_dist, subplot=322, plt_handle=plt, dist_type=dist_type)
plt = plot(n=size[2], dist=single_sample_dist, subplot=323, plt_handle=plt, dist_type=dist_type)
plt = plot(n=size[3], dist=single_sample_dist, subplot=324, plt_handle=plt, dist_type=dist_type)
plt = plot(n=size[4], dist=single_sample_dist, subplot=325, plt_handle=plt, dist_type=dist_type)
plt = plot(n=size[5], dist=single_sample_dist, subplot=326, plt_handle=plt, dist_type=dist_type)
plt.tight_layout()
plt.savefig('sum_of_{}_dist_2.png'.format(dist_type), dpi=200)

reason: import numpy,from scipy