Esempio n. 1
0
def random_quaternion():
    # based on: https://stackoverflow.com/questions/31600717/how-to-generate-a-random-quaternion-quickly
    while True:
        x = random.uniform(-1, 1)
        y = random.uniform(-1, 1)
        z = x**2 + y**2
        if (z <= 1):
            break
    while True:
        u = random.uniform(-1, 1)
        v = random.uniform(-1, 1)
        w = u**2 + v**2
        if (w <= 1):
            break
    s = np.sqrt((1 - z) / w)
    return [x, y, s * u, s * v]
Esempio n. 2
0
 def converge(self, data_set,  file1):
     #Membership val randomized
     #mu = random((len(data_set), 1))
     #mu = hstack((mu, 1.-mu))
     cluster_num = self.cluster_num
     if cluster_num==1:
         mu = [0.3,0.7]
         mu = [mu]*len(data_set)
     else:    
         mu = []
         for i in range(len(data_set)):
             nums = [random.uniform(0,1) for x in range(0,cluster_num)]
             sum = reduce(lambda x,y: x+y, nums)
             norm = [x/sum for x in nums]
             mu.append(norm)
     #mu = mu*(len(data_set))
     #print mu
     m = 2.0
     fcm = FuzzyCMeans(data_set, mu, m)
     converged = fcm(emax=0)
     mem_vals  = fcm.mu
     for i in range(len(self.overall_data)):
          self.overall_data[i].append(mem_vals[i][0])   
          self.overall_data[i].append(mem_vals[i][1])   
     for i in range(len(mu)):
         self.overall_data[i].append(mu[i])
     self.plot_graph(data_set,converged, file1)
Esempio n. 3
0
File: GA.py Progetto: ywzhang909/tsp
    def getOne(self):
        """选择一个个体"""
        r = random.uniform(0, self.bounds)
        for life in self.lives:
            r -= life.score
            if r <= 0:
                return life

        raise Exception("选择错误", self.bounds)
Esempio n. 4
0
File: GA.py Progetto: ywzhang909/tsp
    def getOne(self):
        """选择一个个体"""
        r = random.uniform(0, self.bounds)
        for life in self.lives:
            r -= life.score
            if r <= 0:
                return life

        raise Exception("选择错误", self.bounds)
Esempio n. 5
0
 def choose(self, choices):
     '''
     Return a random
     :param choices:
     :return:
     '''
     max = sum(choices.values())
     pick = random.uniform(0, max)
     current = 0
     for key, value in choices.items():
         current += value
         if current > pick:
             return key
 def particlefilter(self, sequence, pos, stepsize, n):
     seq = iter(sequence)
     x = np.ones((n, 2), int) * pos #Initial position
     f0 = seq.next()[tuple(pos)] * np.ones(n)   # Target color model
     yield pos, x, np.ones(n) / n 
     for im in seq:
         x += random.uniform(-stepsize, stepsize, x.shape) # Particle motion model: uniform step
         x = x.clip(np.zeros(2), np.array(im.shape) - 1).astype(int) # Clip out-of-bounds particles
         f = im[tuple(x.T)]  # Measure particle colors
         w = 1. / (1. + (f0 - f) ** 2) # Weigght~ inverse quadratic color distance
         w /= sum(w)   # Normalize w
         yield sum(x.T * w, axis=1), x, w   # Return expected position, particles and weights
         if 1. / sum(w ** 2) < n / 2.:
             x = x[self.resample(w), :]  
 def particlefilter(self, sequence, pos, stepsize, n):
     seq = iter(sequence)
     x = np.ones((n, 2), int) * pos  #Initial position
     f0 = seq.next()[tuple(pos)] * np.ones(n)  # Target color model
     yield pos, x, np.ones(n) / n
     for im in seq:
         x += random.uniform(-stepsize, stepsize,
                             x.shape)  # Particle motion model: uniform step
         x = x.clip(np.zeros(2),
                    np.array(im.shape) - 1).astype(
                        int)  # Clip out-of-bounds particles
         f = im[tuple(x.T)]  # Measure particle colors
         w = 1. / (1. +
                   (f0 - f)**2)  # Weigght~ inverse quadratic color distance
         w /= sum(w)  # Normalize w
         yield sum(
             x.T * w, axis=1
         ), x, w  # Return expected position, particles and weights
         if 1. / sum(w**2) < n / 2.:
             x = x[self.resample(w), :]
Esempio n. 8
0
    for thisComponent in BlankWaitComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)

    # ------Prepare to start Routine "Focal"-------
    t = 0
    FocalClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    from psychopy import visual, core
    from PIL import Image
    import numpy as np
    import glob, os, random, copy, time

    randomTime = random.uniform(1, 2)
    f1 = Image.open('./FocalPic.png', 'r')
    visual.ImageStim(win, f1).draw()
    win.flip()
    core.wait(randomTime)
    # keep track of which components have finished
    FocalComponents = []
    for thisComponent in FocalComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    # -------Start Routine "Focal"-------
    while continueRoutine:
        # get current time
        t = FocalClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
Esempio n. 9
0
 def create(input_neuron,output_neuron):
     synapse = Synapse()
     # weight=random.uniform(0.078, 0.78)
     weight=random.uniform(-1, 1)
     synapse.add_connection(input_neuron,weight,output_neuron)
     return synapse
Esempio n. 10
0
 def create_bias(bias,neuron):
     synapse = Synapse()
     weight=random.uniform(-0.5,0.5)
     synapse.add_connection(bias,weight,neuron)
     return synapse
Esempio n. 11
0
 currentLoop = trials
 # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
 if thisTrial != None:
     for paramName in thisTrial.keys():
         exec(paramName + '= thisTrial.' + paramName)
 
 #------Prepare to start Routine "select"-------
 t = 0
 selectClock.reset()  # clock 
 frameN = -1
 # update component parameters for each repeat
 import random
 from threading import Timer
 repsLeft = 0
 repsRight = 0
 preTargetDuration = random.uniform(0.5, 3)
 
 if random.randint(0, 1) == 0:
     repsLeft = 1
     repsRight = 0
 else:
     repsLeft = 0
     repsRight = 1
 
 #side = 'left' if repsLeft else 'right'
 
 #def send():
 #    sendEvent('attention', side)
 
 #Timer(2, send).start()
 # keep track of which components have finished
def createFractals(experimentStructure, outcomeStructure, stimuliStructure,
                   redFractal, targetPatch, corrAns, trials, outcomes,
                   feedbackText, misses, missCounter, myCount, routineTimer,
                   globalClock, nTrials):
    """ This function creates the fractals
    
    Input: 
        experimentStructure: all general experimental properties 
        outcomeStructure: all general outcome properties 
        stimuliStructure: all general stimulus properties
        redFractal: position of red fractal (from xls block files)
        targetPatch: position of the patch that should be identified (from xls block files)
        corrAns: indicates which button should be pressed (up vs. down)
        trials: trial handler Psychopy object instance
        outcome: outcome if anwer is correct (from xls block files)
        feedbackText: feedback text object instance
        misses: temporarily saves information about trials that have been missed to repeat these trials
        missCounter: counter for number of misses
        myCount: counter for total number of completed trials (if missed trials exist, can be larger than nTrials)
        routineTimer: timer to control presentation times
        globalClock: clock to control timing during fMRI
        nTrials: number of trials
    
    Return:
        decision2: decision2 object instance
        trials: trial handler Psychopy object instance
        misses: temporarily saves information about trials that have been missed to repeat these trials
        missCounter: counter for number of misses
        routineTimer: timer to control presentation times
        globalClock: clock to control timing during fMRI
        decision2.timestamp: indicates decision2 onset
        fixCrossTiming: actual presentation time of fixation cross during fractal phase
        feedbackTimestamp: indicates feedback onset
        fixCrossTiming_feedback: actual presentation time of fixation cross during feedback
        missIndex: indicates if current trial was missed
    """

    # Create some shortnames
    NOT_STARTED = experimentStructure['NOT_STARTED']
    STARTED = experimentStructure['STARTED']
    FINISHED = experimentStructure['FINISHED']
    STOPPED = experimentStructure['STOPPED']
    endExpNow = experimentStructure['endExpNow']
    event = experimentStructure['event']
    win = experimentStructure['win']
    whichVersion = experimentStructure['whichVersion']
    winFeedback = outcomeStructure['winFeedback']
    neutralFeedback = outcomeStructure['neutralFeedback']
    reward = outcomeStructure['reward']
    noReward = outcomeStructure['noReward']
    fractalClock = stimuliStructure['fractalClock']
    fractal1 = stimuliStructure['fractal1']
    fractal2 = stimuliStructure['fractal2']
    fixationCross = stimuliStructure['fixationCross']
    fixCrossTiming = stimuliStructure['fixCrossTiming']
    jitter = stimuliStructure['jitter']
    stimulusTiming = stimuliStructure['stimulusTiming']
    feedbackClock = stimuliStructure['feedbackClock']

    #------Prepare to start Routine "decision2"-------
    t = 0
    fractalClock.reset()
    frameN = -1
    currentJitter = random.uniform(0, jitter)
    fixCrossTiming = fixCrossTiming + currentJitter
    routineTimer.add(fixCrossTiming + stimulusTiming)

    # Compute position of fractals
    if redFractal == 'up':
        fractal1.setPos([0, -4])
        fractal2.setPos([0, 4])
    elif redFractal == 'down':
        fractal1.setPos([0, 4])
        fractal2.setPos([0, -4])

    # Get correct keys
    if whichVersion == 1:
        if redFractal == 'up':
            redFractalKey = 'up'
            blueFractalKey = 'down'
        elif redFractal == 'down':
            redFractalKey = 'down'
            blueFractalKey = 'up'
    elif whichVersion == 2:
        if redFractal == 'up':
            redFractalKey = '4'
            blueFractalKey = '2'
        elif redFractal == 'down':
            redFractalKey = '2'
            blueFractalKey = '4'

    if whichVersion == 1:
        corrAnsKey = corrAns
    elif whichVersion == 2:
        if corrAns == 'up':
            corrAnsKey = '4'
        elif corrAns == 'down':
            corrAnsKey = '2'

    decision2 = event.BuilderKeyResponse(
    )  # create an object of type KeyResponse
    decision2.status = NOT_STARTED

    # Keep track of which components have finished
    decision2Components = []
    decision2Components.append(fixationCross)
    decision2Components.append(fractal1)
    decision2Components.append(fractal2)
    decision2Components.append(decision2)
    for thisComponent in decision2Components:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    #-------Start Routine "decision2"-------
    decision2.timestamp = globalClock.getTime()

    missIndex = 0
    continueRoutine = True
    while continueRoutine and routineTimer.getTime() > 0:

        # Get current time
        t = fractalClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)

        # *fixationCross* updates
        if t >= 0.0 and fixationCross.status == NOT_STARTED:
            # keep track of start time/frame for later
            fixationCross.tStart = t  # underestimates by a little under one frame
            fixationCross.frameNStart = frameN  # exact frame index
            fixationCross.setAutoDraw(True)
        if fixationCross.status == STARTED and t >= (
                0.0 +
            (fixCrossTiming + stimulusTiming -
             win.monitorFramePeriod * 0.75)):  #most of one frame period left
            fixationCross.setAutoDraw(False)

        # *fractal1* updates
        if t >= fixCrossTiming and fractal1.status == NOT_STARTED:
            # keep track of start time/frame for later
            fractal1.tStart = t  # underestimates by a little under one frame
            fractal1.frameNStart = frameN  # exact frame index
            fractal1.setAutoDraw(True)
        if fractal1.status == STARTED and t >= (
                fixCrossTiming +
            (stimulusTiming -
             win.monitorFramePeriod * 0.75)):  #most of one frame period left
            fractal1.setAutoDraw(False)

        # *fractal2* updates
        if t >= fixCrossTiming and fractal2.status == NOT_STARTED:
            # keep track of start time/frame for later
            fractal2.tStart = t  # underestimates by a little under one frame
            fractal2.frameNStart = frameN  # exact frame index
            fractal2.setAutoDraw(True)
        if fractal2.status == STARTED and t >= (
                fixCrossTiming +
            (stimulusTiming -
             win.monitorFramePeriod * 0.75)):  #most of one frame period left
            fractal2.setAutoDraw(False)

        # *decision2* updates
        if t >= fixCrossTiming and decision2.status == NOT_STARTED:
            # keep track of start time/frame for later
            decision2.tStart = t  # underestimates by a little under one frame
            decision2.frameNStart = frameN  # exact frame index
            decision2.status = STARTED
            # keyboard checking is just starting
            decision2.clock.reset()  # now t=0
            event.clearEvents(eventType='keyboard')
        if decision2.status == STARTED and t >= (
                fixCrossTiming +
            (stimulusTiming -
             win.monitorFramePeriod * 0.75)):  #most of one frame period left
            decision2.status = STOPPED
        if decision2.status == STARTED:
            if whichVersion == 1:
                theseKeys = event.getKeys(keyList=['up', 'down'])
            elif whichVersion == 2:
                theseKeys = event.getKeys(keyList=['4', '2'])

            # Check for quit:
            if "escape" in theseKeys:
                endExpNow = True
            if len(theseKeys) > 0:  # at least one key was pressed
                decision2.keys = theseKeys[-1]  # just the last key pressed
                decision2.rt = decision2.clock.getTime()

                # Which response?
                if (decision2.keys
                        == str(redFractalKey)) or (decision2.keys
                                                   == redFractalKey):
                    decision2.color = 1
                else:
                    decision2.color = 2

                # Was the answer correct?
                if (decision2.keys == str(corrAnsKey)) or (decision2.keys
                                                           == corrAnsKey):
                    decision2.corr = 1
                else:
                    decision2.corr = 0

            for thisComponent in decision2Components:
                if hasattr(thisComponent,
                           "status") and thisComponent.status != FINISHED:
                    continueRoutine = True
                    break  # at least one component has not yet finished
                else:
                    continueRoutine = False

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

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

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

    # Check responses
    # ---------------
    if decision2.keys in ['', [], None]:
        decision2.keys = None
        decision2.color = float('nan')
        if str(corrAns).lower() == 'none':
            decision2.corr = float('nan')
            decision2.rt = float('nan')
        else:
            decision2.corr = float('nan')
            decision2.rt = float('nan')

    if (decision2.keys is None):
        decision2.reward = noReward
        msg = "Zu langsam!"

        if myCount < nTrials:
            misses.append(myCount)
            missCounter = missCounter + 1
            missIndex = 1

    elif (decision2.corr == 1):

        if float(outcomes) == 1:
            decision2.reward = reward
            msg = winFeedback
        else:
            decision2.reward = noReward
            msg = neutralFeedback
    elif (decision2.corr == 0):

        if float(outcomes) == 1:
            decision2.reward = noReward
            msg = neutralFeedback
        else:
            decision2.reward = reward
            msg = winFeedback

    # Store data for trials (TrialHandler)
    trials.addData('decision2.rt', decision2.rt)
    trials.addData('decision2.keys', decision2.keys)
    trials.addData('decision2.corr', decision2.corr)
    trials.addData('decision2.color', decision2.color)
    trials.addData('decision2.reward', decision2.reward)
    accPerf = trials.data['decision2.reward'].sum()
    trials.addData('decision2.accPerf', accPerf)

    # Give feedback
    (routineTimer, globalClock, feedbackTimestamp,
     fixCrossTiming_feedback) = giveFeedback(experimentStructure,
                                             stimuliStructure, feedbackText,
                                             msg, routineTimer, globalClock,
                                             missIndex)

    return (decision2, trials, misses, missCounter, routineTimer, globalClock,
            decision2.timestamp, fixCrossTiming, feedbackTimestamp,
            fixCrossTiming_feedback, missIndex)
Esempio n. 13
0
def selectJrand(i,m):
    j=i
    while (j == i):
        j = int(random.uniform(0,m))
    return j
Esempio n. 14
0
    trial_loop.addData('trial_txt.started', trial_txt.tStartRefresh)
    trial_loop.addData('trial_txt.stopped', trial_txt.tStopRefresh)
    # check responses
    if trial_resp.keys in ['', [], None]:  # No response was made
        trial_resp.keys = None
    trial_loop.addData('trial_resp.keys', trial_resp.keys)
    if trial_resp.keys != None:  # we had a response
        trial_loop.addData('trial_resp.rt', trial_resp.rt)
    trial_loop.addData('trial_resp.started', trial_resp.tStartRefresh)
    trial_loop.addData('trial_resp.stopped', trial_resp.tStopRefresh)

    # ------Prepare to start Routine "isi"-------
    continueRoutine = True
    # update component parameters for each repeat
    import random
    t_isi = random.uniform(0, 1)
    # keep track of which components have finished
    isiComponents = [fix_dot]
    for thisComponent in isiComponents:
        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")
    isiClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
Esempio n. 15
0
        #GENERATE RANDOM ANGLE ORDER
        shuffle(angles)

        for angle in angles:
            angleNum = (int(angle / 5) - 1)
            #PICK RANDOM POSITION, CENTER OR RANDOM PERIPHERY
            thisPos = random.choice(positions)
            thisLetter = random.choice(letters)

            eccentricity = 0

            if thisPos > 0:
                eccentricity = angle

            #RANDOM STIMULUS ONSET TIME
            delayTime = random.uniform(1, 5)

            #SET ANGLE, DISPLAY COORDINATES

            thisXPos = (0 + ((positionXMult[thisPos]) * angleSpacer[angleNum]))
            thisYPos = (0 + ((positionYMult[thisPos]) * angleSpacer[angleNum]))

            #PICK RANDOM LETTER, SET CORRECT KEY

            correctKeyPress = thisLetter.lower()

            #SET UP DISPLAY TEXT
            displayText = visual.TextStim(win=win,
                                          name='displayText',
                                          text=thisLetter,
                                          font='Arial',