Exemplo n.º 1
0
def main():
    print("Welcome to simone Jimmy")
    print("warming up engines")
    #relayTest()
    print("relay Test Complete")
    print("Starting switches")
    switches()
    print("Switches up booi lets party")
    print("3")
    print("2")
    print("1")
    state()
Exemplo n.º 2
0
def momentum_state(p, n=default_n):
    r"""Momentum eigenstates of a harmonic oscillator.

    Returns the n-dimensional approximation of the eigenstate :math:`|p\rangle`
    of the dimensionless momentum operator P in the number basis.

    See :func:`position`, :func:`momentum`.

    Difference equation:

    .. math::

       r_1 &= i \sqrt{2} p r_0,\\
       \sqrt{k+1} r_{k+1} &= i \sqrt{2} p r_k +\sqrt{k} r_{k-1}, \qquad \text{when} \quad k >= 1.
    """
    # Ville Bergholm 2010

    ket = empty(n, dtype=complex)
    temp = 1j * sqrt(2) * p
    ket[0] = 1  # arbitrary nonzero initial value r_0
    ket[1] = temp * ket[0]
    for k in range(2, n):
        ket[k] = temp/sqrt(k) * ket[k - 1] +sqrt((k-1) / k) * ket[k - 2]
    ket /= norm(ket)  # normalize
    return state(ket, n)
Exemplo n.º 3
0
def test():
    """Testing script for the harmonic oscillator module."""
    from numpy.random import randn
    from utils import assert_o

    def randc():
        """Random complex number."""
        return randn() + 1j*randn()

    a = mat(boson_ladder(default_n))

    alpha = randc()
    s = coherent_state(alpha)
    s0 = state(0, default_n)
    D = displace(alpha)
    
    assert_o((s - s0.u_propagate(D)).norm(), 0, tol)  # displacement

    z = randc()
    S = squeeze(z)

    Q = position(); P = momentum()
    q = randn(); p = randn()
    sq = position_state(q)
    sp = momentum_state(p)

    temp = 1e-1 # the truncation accuracy is not amazing here
    assert_o(sq.ev(Q), q, temp)  # Q, P eigenstates
    assert_o(sp.ev(P), p, temp)

    temp = ones(default_n);  temp[-1] = -default_n+1 # truncation...
    assert_o(norm(comm(Q,P) - 1j * diag(temp)), 0, tol) # [Q, P] = i

    assert_o(norm(mat(P)**2 +mat(Q)**2 - 2 * a.H * a -diag(temp)), 0, tol)  # P^2 +Q^2 = 2a^\dagger * a + 1
Exemplo n.º 4
0
 def state_matrix (self):
     mat = []
     for i in range(0, 18):
         x = []
         for j in range(0, 18):
             x += [state(i, j)]
         mat += [x]
     for i in range(0, 18):
         mat[0][i].c = mat[i][0].c = mat[17][i].c = mat[i][17].c = OBSTACLE
     return mat
Exemplo n.º 5
0
def do_cv():
    # Load the user vectors.
    data = utility.load_vectors()
    outfile_string = "baseline_slice" + str(config.num_slices) \
                     + "_rec" + str(config.tuning_param['num_recs']) + ".txt"
    rates = list()
    st = state('Item Based', rates, outfile_string, "INFO", config.num_slices, config.tuning_param['num_recs'])
    for i in xrange(st.num_slices):
        st.cur_slice += 1
        train, test = utility.get_data_split(data, i)
        success = do_most_popular(train, test)
        st.rates = (success, len(test))
    return st
Exemplo n.º 6
0
 def get_state(self):
     self.core_list = filter(lambda x: "core" in x, os.listdir('.'))
     # print self.core_list
     if len(self.core_list) == 0:
         if self.crash is '':
             log.info('No Crash')
         else:
             log.info('Crash can\'t be used!')
         return None
     s = state(self.binary, self.crash)
     s.get_register_info()
     self.info = s.get_segment_data()
     return self.info
def Construct(n,starting,ending,bool):
    L=[x for x in range(n)]
    for i in range(n):
        for j in range(n):
            reward=[]
            for k in range(4):
                reward.append(np.random.normal(-10,1.5))
            if(bool):
                Q=[0,0,0,0]
                Q2=[0,0,0,0]
                s=state(Q,Q2,reward,i,j)
                state.Array_States[(i,j)]=s
            else:
                state.Array_States[(i, j)].reward=reward
Exemplo n.º 8
0
def main():
    #get our maze from the image
    build_maze( pixel_values, pixels )
    #print( "Maze" )
    #print_maze( pixels )

    #find the entry on the first line
    entry = find_door( pixels[0] )
    #print( "Maze entrence is at 0," + str(entry) )

    #find the exit on the last line
    exit = find_door( pixels[-1] )
    #print( "Maze exit is at " + str(len(pixels)) + "," + str(exit) )

    #begin state
    begin= state( None, 0, entry)
Exemplo n.º 9
0
def do_cv():
    # Load the user vectors.
    data = utility.load_vectors()
    outfile_string = "user_slice" + str(config.num_slices) + "_rec" \
        + str(config.tuning_param['num_recs']) + "_users" + str(config.tuning_param['num_sims']) + ".txt"
    rates = list()
    st = state('User Based', rates, outfile_string, "INFO",
               config.num_slices, config.tuning_param['num_recs'], config.tuning_param['num_sims'])
    # Storage for the success rate.
    for i in range(st.num_slices):
        print "current slice: ", st.cur_slice
        st.cur_slice += 1
        train, test = utility.get_data_split(data, i)
        success = do_user_cf(train, test)
        st.rates = (success, len(test))
    return st
Exemplo n.º 10
0
def coherent_state(alpha, n=default_n):
    r"""Coherent states of a harmonic oscillator.

    Returns the n-dimensional approximation to the
    coherent state :math:`|\alpha\rangle`,

    .. math::

       |\alpha\rangle := D(\alpha) |0\rangle
       = e^{-\frac{|\alpha|^2}{2}} \sum_{k=0}^\infty \frac{\alpha^k}{\sqrt{k!}} |k\rangle,

    in the number basis. :math:`a|\alpha\rangle = \alpha |\alpha\rangle`.
    """
    # Ville Bergholm 2010

    k = arange(n)
    ket = (alpha ** k) / sqrt(factorial(k))
    return state(ket, n).normalize()
Exemplo n.º 11
0
def husimi(s, alpha=None, z=0, res=(40, 40), lim=(-2, 2, -2, 2)):
    r"""Husimi probability distribution.
    ::

      H       = husimi(s, alpha[, z=])
      H, a, b = husimi(s, res=xxx, lim=yyy[, z=])

    Returns the Husimi probability distribution
    :math:`H(\mathrm{Im} \alpha, \mathrm{Re} \alpha)` corresponding to the harmonic
    oscillator state s given in the number basis:

    .. math::

       H(s, \alpha, z) = \frac{1}{\pi} \langle\alpha, z| \rho_s |\alpha, z\rangle

    z is the optional squeezing parameter for the reference state:
    :math:`|\alpha, z\rangle := D(\alpha) S(z) |0\rangle`.
    The integral of H is normalized to unity.
    """
    # Ville Bergholm 2010

    if alpha == None:
        # return a 2D grid of W values
        a = linspace(lim[0], lim[1], res[0])
        b = linspace(lim[2], lim[3], res[1])
        #a, b = ogrid[lim[0]:lim[1]:1j*res[0], lim[2]:lim[3]:1j*res[1]]
        alpha = a + 1j*b[:, newaxis]
        return_ab = True
    else:
        return_ab = False

    # reference state
    n = prod(s.dims())
    ref = state(0, n).u_propagate(squeeze(z, n))
    ref /= sqrt(pi) # normalization included for convenience

    H = empty(alpha.shape)
    for k, c in enumerate(alpha.flat):
        temp = ref.u_propagate(displace(c, n))
        H.flat[k] = s.fidelity(temp) ** 2

    if return_ab:
        H = (H, a, b)
    return H
Exemplo n.º 12
0
def PSOv2(model, retries, changes, graph=False, goal = 0.01, pat = 100, \
era = 100, np=30, phi_1=3.8, phi_2=2.2, personalListSize=5, out='out.txt'):
    #g = grapher(model, int(retries), 1, changes, "PSOv2" + str(changes))
    emin = 0
    phi_tot = phi_1 + phi_2
    k = (2.0 /
         math.fabs((2.0 - phi_tot) - math.sqrt(phi_tot**2.0 - 4.0 * phi_tot)))
    #k = 0.25
    print k
    vmax = max([
        (x[1] - x[0])
        for x in [model.getBounds(i) for i in range(model.numOfDecisions())]
    ])
    baseRadius = vmax / float(model.numOfDecisions())

    s = gens(model, np, personalListSize)

    st = state(model.name, 'PSOv2', s, 0, retries, changes, era)

    st.sb = st.s[0].pos
    bestcan = st.s[0]
    tot_deaths = 0
    model.initializeObjectiveMaxMin(st.sb)
    for c in st.s:
        model.updateObjectiveMaxMin(c.pos)
    frontier = runDom(st, model, list())
    # basic idea is this is a list of positions that
    # persist between retries.
    global_frontier = list()
    #retry loop
    while st.t:
        print "."
        # model.initializeObjectiveMaxMin(st.sb)
        # for c in st.s:
        #     model.updateObjectiveMaxMin(c.pos)
        st.k = changes
        #iterative loop
        while st.k:
            if st.k % 100 == 0:
                print "=" * 29
                print "k ", st.k
                print "tot_deaths ", tot_deaths
            num_deaths = 0
            uniqTracker = list()
            for can in st.s:
                can.vel =  [k * (vel + (phi_1 * random.uniform(0,1) * (best - pos)) + \
                 (phi_2 * random.uniform(0,1) * (gbest - pos))) \
                    for vel, pos, best, gbest in zip(can.vel, can.pos, can.pbest[0], frontier[0])]
                # print 'can.vel ', can.vel
                can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]
                #V2 logic here
                #tracks to make sure we are not doubling up
                uniqTracker.append(can.uniq)
                for c in st.s:
                    if c.uniq in uniqTracker:
                        continue
                    else:
                        radius = distance(c.pos, can.pos)
                        #stop crowding my space
                        if (radius < baseRadius):
                            newRadius = (c.radius + can.radius)**(0.5)
                            #print(newRadius)
                            c.radius = newRadius
                            can.radius = newRadius

                        #always repulse for a little jitter
                        repulsedVelocity = repulsion(c, can, radius)
                        #print("repulsed force=" + str(repulsedVelocity))
                        can.vel = [
                            repulsedVelocity * vmax + vel for vel in can.vel
                        ]
                        can.pos = [
                            pos + vel for pos, vel in zip(can.pos, can.vel)
                        ]
                        #instead of resetting wiggle
                        #each index until bounds and constraints
                        #are met
                        for i in xrange(len(can.pos)):
                            can.pos = model.singleRetry(can.pos, i)

                        #other particle will repulse the opposite direction
                        c.vel = [
                            -repulsedVelocity * vmax + vel for vel in c.vel
                        ]
                        c.pos = [pos + vel for pos, vel in zip(c.pos, c.vel)]
                        for i in xrange(len(c.pos)):
                            c.pos = model.singleRetry(can.pos, i)

                if not model.checkBounds(
                        can.pos) or not model.checkConstraints(can.pos):
                    can.pos = model.retry()
                    can.vel = [0.1 for x in can.pos]
                    num_deaths += 1
                model.updateObjectiveMaxMin(can.pos)
            tot_deaths += num_deaths
            #g.trackParticle(st.s[0].pos, 0, st.k)
            # for v in st.s:
            #     g.addVector(v.pos, v.uniq)
            runDom(st, model, frontier)
            st.k -= 1

        for can in st.s:
            print(
                str(can.uniq) + " radius = " + str(can.radius) + " energy = " +
                str(model.energy(can.pbest[0])))
        st.s = gens(model, np, personalListSize)
        st.sb = st.s[0].pbest
        bestcan = st.s[0]
        st.t -= 1
        # print 'final front ', [model.cal_objs_2(f) for f in frontier]
        for f in frontier:
            global_frontier.append(f)
            # g.addVector(f, int(st.t))
        frontier = runDom(st, model, list())
        # for v in st.s:
        #     g.addVector(v.pbest[0], v.uniq)
    for f in global_frontier:
        st.reg_front.append(model.cal_objs_2(f))
        st.norm_front.append(model.cal_objs(f))
    # g.graph()
    # g.graphEnergy()
    # g.graphTrackedParticle()
    st.termPSO()
Exemplo n.º 13
0
def mws(model, retries, changes, goal=0.01, pat=100, era=100):
    emin = 0
    s = model.retry()
    model.initializeObjectiveMaxMin(s)
    # prime the maxs and mins with values, avoids divide by 0
    for i in xrange(1000):
        model.updateObjectiveMaxMin(model.retry())
    st = state(model.name, 'MWS', s, model.energy(s), retries, changes, era)
    while st.t:
        st.k = changes
        patience = pat
        while st.k:
            # 1st possible stopping condition
            # close to the minimum
            if st.eb - emin <= goal:
                st.sbo = st.sb
                st.ebo = model.energy(st.sbo)
                st.term()
                return
            # 2nd stopping condition
            # We've had the same best for
            # a long while.
            if st.eb == st.eblast:
                if patience == 0:
                    st.bored()
                    st.k = 0
                    break
                else:
                    patience -= 1
            else:
                patience = pat
                st.eblast = st.eb
            c = randint(0, model.numOfVars - 1)
            if (random() >= 0.5):
                st.sn = model.mutate(st.s, c)
                if (model.updateObjectiveMaxMin(st.sn)):
                    st.e = model.energy(
                        st.s)  # update all energies if new normal
                    st.eb = model.energy(st.sb)
                    st.ebo = model.energy(st.sbo)
            else:
                tempS = list(st.sn)
                tempE = model.energy(st.sn)
                for index in range(1, 10):
                    tempS[c] = (model.bounds[c][1] -
                                model.bounds[c][0]) * (index / 10.0)
                    if (model.checkConstraints(tempS)):
                        if (model.updateObjectiveMaxMin(tempS)):
                            # update all energies if new normal
                            st.e = model.energy(st.s)
                            st.eb = model.energy(st.sb)
                            st.ebo = model.energy(st.sbo)
                            st.en = model.energy(st.sn)
                            tempE = model.energy(tempS)
                        if (model.energy(tempS) < tempE):
                            st.sn = list(tempS)
                            tempE = model.energy(tempS)
            st.en = model.energy(st.sn)
            if st.en < st.eb:
                st.sb = list(st.sn)
                st.eb = st.en
                st.app_out('!')
            if st.en < st.e:
                st.app_out('+')
            else:
                st.app_out('.')
            # Always promote the last solution
            st.s = list(st.sn)
            st.e = st.en
            st.k -= 1
        # First check if the sb for that set of changes was better
        # Than any of our other retries
        if (st.eb < st.ebo):
            st.sbo = list(st.sb)
            st.ebo = st.eb
            st.app_out('^')
            # Then retry with a brand new set of values
        st.s = model.retry()
        st.e = model.energy(st.s)
        st.sn = list(st.s)
        st.en = st.e
        st.sb = list(st.sn)
        st.eb = st.en
        st.t -= 1
    st.term()
def classicalGlobalPSO(model, retries, changes, graph=False, goal = 0.01, pat = 100, era = 100, np=30, phi_1=2.8, phi_2=1.3, inertia=0.8):
    emin = 0

    #setting vmax to full search range for an particle (from lit)
    # val bounds = [model.getBounds(i) for i in range(model.numOfDecisions())][0]
    # val difference
    vmax = max([(x[1] - x[0]) for x in [model.getBounds(i) for i in range(model.numOfDecisions())]])

    print(vmax)

    s = gens(model, np)
    #initialize grapher
    if graph:
        g = grapher(model, np)
        for can in s:
            g.addVector(can.pos, can.uniq)
    # Energy here is set to zero since we're not actively using it for now.
    st = state(model.name, 'classicalGlobalPSO', s, 0, retries, changes, era)
    # print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
    # print 'Model Name: ', model.name, '\nOptimizer: Classical Global PSO, K: ', changes
    # Set an initial value for the global best
    # The downside to setting pbest equal to the current
    # particle position is that if there is a high phi_1 value
    # the particle will stay still until something happens globally
    # that pushes it away.
    st.sb = st.s[0].pbest
    st.sblast = st.s[0].pos
    bestcan = st.s[0]
    #Initialize objective mins and maxs
    model.initializeObjectiveMaxMin(st.sb)
    #we whould do this just in case
    for c in st.s:
        model.updateObjectiveMaxMin(c.pos)
    tot_deaths = 0
    frontier = list()
    while st.t:
        st.k = changes
        while st.k:
            if st.sb == st.sblast:
                pat -= 1
                if pat == 0:
                    st.bored()
                    break
            num_deaths = 0
            for can in st.s:
                can.vel =  [inertia * vel + (phi_1 * random.uniform(0,1) * (best - pos)) + (phi_2 * random.uniform(0,1) * (gbest - pos)) \
                    for vel, pos, best, gbest in zip(can.vel, can.pos, can.pbest, st.sb)]
                #checking if velocity is at max
                can.vel = [vmax if vel > vmax else vel for vel in can.vel]
                can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]

                # Currently doing the same thing for particles that are
                # out of bounds and out of constraints, simply killing them
                # definitely some other options with this.  If they get to
                # bounds can set vector to boundary, and vel ot zero, then
                # just let them be pulled back into the space.
                if not model.checkBounds(can.pos) or not model.checkConstraints(can.pos):
                    can.pos = model.retry()
                    can.vel = [0.0 for x in can.pos]
                    # Should a killed candidate maintain it's phantom memory?
                    # Uncomment this to wipe its memory.
                    # can.pbest = list(can.pos)
                    num_deaths += 1
                #Update objective maxs and mins
                if graph:
                    g.addVector(can.pos, can.uniq)
                model.updateObjectiveMaxMin(can.pos)
            tot_deaths += num_deaths
            #if you want to see step by step particle movement uncomment below
            #warning you will end up having to terminate this manually
            #g.graph()
            best = st.s[0]
            best_list = []
            low_diff = []
            for i in xrange(len(st.s) - 1):
                pbret = model.cdom(st.s[i].pos, st.s[i].pbest, st.s[i], st.s[i])
                if pbret == 0 or pbret == -1:
                    st.s[i].pbest = list(st.s[i].pos)
                ret_val = model.cdom(st.sb, st.s[i+1].pos, bestcan, st.s[i+1])
                if ret_val == 0:
                    st.sb = st.s[i+1].pos
                    st.sblast = st.s[i+1].pos
                    bestcan = st.s[i+1]
                elif ret_val == -1:
                    addToFront(model, frontier, st.s[i+1].pos)
            if not st.sb in frontier:
                addToFront(model, frontier, st.sb)
            st.k -= 1
        # We need a clean slate here.
        # print '++++++++++++++++++++++++++++++++++++++++++++++++++++'
        # print 'Global best: ', st.sb, '\nGlobal best energy: ', st.eb
        # print 'Num deaths: ', tot_deaths
        # print 'Total number of particles ', changes*np
        # print "Attrition %0.2f percent" % (100.0 * (tot_deaths/(changes*np)))
        for can in st.s:
            addToFront(model, frontier, can.pbest)
        f = [model.cal_objs(pos) for pos in frontier]
        st.addFrontier(f)
        st.s = gens(model, np)
        st.sb = st.s[0].pbest
        st.sblast = st.s[0].pbest
        bestcan = st.s[0]
        st.t -= 1
    if graph:
        g.graph()
        g.graphEnergy()
    st.termPSO()
Exemplo n.º 15
0
def PSOProbs(model, retries, changes, graph=False, goal = 0.01, pat = 100, \
era = 100, np=60, phi_1=3.8, phi_2=2.2, personalListSize=5, out='out.txt'):
    g = grapher(model, int(retries), 1, changes, "60NP_PSOProbsK" + str(changes))
    probTracker = [Probs(np) for i in xrange(np)]
    emin = 0
    phi_tot = phi_1 + phi_2
    k = (2.0/math.fabs(2.0 - (phi_tot) - math.sqrt(phi_tot**2.0 - 4.0*phi_tot)))
    # print "constriction factor ", k
    s = gens(model, np, personalListSize)
    st = state(model.name, '60NP_PSOProbs', s, 0, retries, changes, era, out=out)
    st.sb = st.s[0].pos
    bestcan = st.s[0]
    tot_deaths = 0
    model.initializeObjectiveMaxMin(st.sb)
    for c in st.s:
        model.updateObjectiveMaxMin(c.pos)
    frontier = runDom(st, model, list())
    # basic idea is this is a list of positions that
    # persist between retries.
    global_frontier = list()
    #retry loop
    while st.t:
        print "."
        # model.initializeObjectiveMaxMin(st.sb)
        # for c in st.s:
        #     model.updateObjectiveMaxMin(c.pos)
        st.k = changes
        #iterative loop
        while st.k:
            if st.k % 100 == 0:
                print "="*29
                print "k ", st.k
                print "tot_deaths ", tot_deaths
            num_deaths = 0
            for can in st.s:
                previousEnergy = model.energy(can.pos) #we could also use domination instead against the pbest list
                currentParticle = probTracker[can.uniq].getParticle()
                pbest = [x for x in st.s if x.uniq == currentParticle][0].pos
                can.vel =  [k * (vel + (phi_1 * random.uniform(0,1) * (best - pos)) + \
                 (phi_2 * random.uniform(0,1) * (gbest - pos))) \
                    for vel, pos, best, gbest in zip(can.vel, can.pos, pbest, frontier[0])]
                # print 'can.vel ', can.vel
                can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]
                if not model.checkBounds(can.pos) or not model.checkConstraints(can.pos):
                    can.pos = model.retry()
                    can.vel = [0.1 for x in can.pos]
                    num_deaths += 1
                model.updateObjectiveMaxMin(can.pos)
                if(model.energy(can.pos) < previousEnergy): #could use dom against pbest list
                    probTracker[can.uniq].increaseProb(currentParticle)
                else:
                    probTracker[can.uniq].decreaseProb(currentParticle)
            #probTracker[0].printProbs()
            tot_deaths += num_deaths
            #g.trackParticle(st.s[0].pos, 0, st.k)
            # for v in st.s:
            #     g.addVector(v.pos, v.uniq)
            runDom(st, model, frontier)
            st.k -= 1
        st.s = gens(model, np, personalListSize)
        st.sb = st.s[0].pbest
        bestcan = st.s[0]
        for f in frontier:
            st.app_out(str(model.cal_objs_2(f)) + '\n')
            global_frontier.append(f)
            g.addVector(f, int(st.t))
        frontier = runDom(st,model,list())
        st.t -= 1
        # for v in st.s:
        #     g.addVector(v.pbest[0], v.uniq)
    for f in global_frontier:
        st.reg_front.append(model.cal_objs_2(f))
        st.norm_front.append(model.cal_objs(f))
    g.graph()
    g.graphEnergy()
    #g.graphTrackedParticle()
    st.termPSO()
Exemplo n.º 16
0
def sac(model, retries, changes, goal=0.01, pat=100, era=100):
    emin = 0
    s = model.retry()
    model.initializeObjectiveMaxMin(s)
    for i in xrange(1000):
        # prime the maxs and mins with second values, avoids divide by 0
        model.updateObjectiveMaxMin(model.retry())
    st = state(model.name, 'SAC', s, model.energy(s), retries, changes, era)
    print 'model name ', model.name
    #changes is some static value passed by the caller
    #st changes is actually a counter
    while st.t:
        st.k = changes
        patience = pat
        while st.k:
            # An Energy based stopping condition
            # doesn't make sense here.
            # 1st possible stopping condition
            # close to the minimum
            # if st.eb - emin <= goal:
            #     st.sbo = st.sb
            #     st.eb = model.energy(st.sb)
            #     st.ebo = model.energy(st.sbo)
            #     st.term()
            #     return
            # 2nd stopping condition
            # We've had the same best for
            # a long while.
            # This still makes sense since we can just
            # check if the vector is the same, if it is
            # it hasn't been dominated in quite awhile.
            if st.sb == st.sblast:
                if patience == 0:
                    st.bored()
                    st.k = 0
                    break
                else:
                    patience -= 1
            else:
                patience = pat
                st.sblast = list(st.sb)
            c = randint(0, model.numOfVars - 1)
            st.sn = neighbor(model, c, st.s, st.k / changes)
            if (model.updateObjectiveMaxMin(
                    st.sn)):  # check if new objective bounds
                st.e = model.energy(st.s)  # adjust accordingly
                st.eb = model.energy(st.sb)
                st.ebo = model.energy(st.sbo)
            best = cdom(model, st.sn, st.sb)
            better = cdom(model, st.sn, st.s)
            st.en = model.energy(st.sn)
            if (best):
                st.app_out('!')
                st.sb = list(st.sn)
                st.eb = st.en
            if (better):
                st.app_out('+')
                st.s = list(st.sn)
                st.e = st.en
            # This is just pegged so that the old is better than the new
            # I'm using pretty small values here.  The actual aggregated values
            # are much larger, so obviously this isn't going to work exactly right
            # the whole point though is just to test out cdom.
            elif (prob(st.e, st.en,
                       ((changes - st.k) / changes), st.t) < random()):
                st.app_out('?')
                st.s = st.sn
                st.e = st.en
            else:
                st.app_out('.')
            st.k -= 1
        # First check if the sb for that set of changes was better
        # Than any of our other retries
        ultimate = cdom(model, st.sb, st.sbo)
        if (ultimate):
            st.app_out(' ^')
            st.sbo = list(st.sb)
            st.ebo = st.eb
        # Then retry with a brand new set of values
        st.s = model.retry()
        st.sn = list(st.s)
        st.sb = list(st.sn)
        st.e = model.energy(st.s)
        st.en = st.e
        st.eb = st.en
        st.t -= 1
    st.term()
def classicalGlobalPSO(model,
                       retries,
                       changes,
                       graph=False,
                       goal=0.01,
                       pat=100,
                       era=100,
                       np=30,
                       phi_1=2.8,
                       phi_2=1.3,
                       inertia=0.8):
    emin = 0

    #setting vmax to full search range for an particle (from lit)
    # val bounds = [model.getBounds(i) for i in range(model.numOfDecisions())][0]
    # val difference
    vmax = max([
        (x[1] - x[0])
        for x in [model.getBounds(i) for i in range(model.numOfDecisions())]
    ])

    print(vmax)

    s = gens(model, np)
    #initialize grapher
    if graph:
        g = grapher(model, np)
        for can in s:
            g.addVector(can.pos, can.uniq)
    # Energy here is set to zero since we're not actively using it for now.
    st = state(model.name, 'classicalGlobalPSO', s, 0, retries, changes, era)
    # print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
    # print 'Model Name: ', model.name, '\nOptimizer: Classical Global PSO, K: ', changes
    # Set an initial value for the global best
    # The downside to setting pbest equal to the current
    # particle position is that if there is a high phi_1 value
    # the particle will stay still until something happens globally
    # that pushes it away.
    st.sb = st.s[0].pbest
    st.sblast = st.s[0].pos
    bestcan = st.s[0]
    #Initialize objective mins and maxs
    model.initializeObjectiveMaxMin(st.sb)
    #we whould do this just in case
    for c in st.s:
        model.updateObjectiveMaxMin(c.pos)
    tot_deaths = 0
    frontier = list()
    while st.t:
        st.k = changes
        while st.k:
            if st.sb == st.sblast:
                pat -= 1
                if pat == 0:
                    st.bored()
                    break
            num_deaths = 0
            for can in st.s:
                can.vel =  [inertia * vel + (phi_1 * random.uniform(0,1) * (best - pos)) + (phi_2 * random.uniform(0,1) * (gbest - pos)) \
                    for vel, pos, best, gbest in zip(can.vel, can.pos, can.pbest, st.sb)]
                #checking if velocity is at max
                can.vel = [vmax if vel > vmax else vel for vel in can.vel]
                can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]

                # Currently doing the same thing for particles that are
                # out of bounds and out of constraints, simply killing them
                # definitely some other options with this.  If they get to
                # bounds can set vector to boundary, and vel ot zero, then
                # just let them be pulled back into the space.
                if not model.checkBounds(
                        can.pos) or not model.checkConstraints(can.pos):
                    can.pos = model.retry()
                    can.vel = [0.0 for x in can.pos]
                    # Should a killed candidate maintain it's phantom memory?
                    # Uncomment this to wipe its memory.
                    # can.pbest = list(can.pos)
                    num_deaths += 1
                #Update objective maxs and mins
                if graph:
                    g.addVector(can.pos, can.uniq)
                model.updateObjectiveMaxMin(can.pos)
            tot_deaths += num_deaths
            #if you want to see step by step particle movement uncomment below
            #warning you will end up having to terminate this manually
            #g.graph()
            best = st.s[0]
            best_list = []
            low_diff = []
            for i in xrange(len(st.s) - 1):
                pbret = model.cdom(st.s[i].pos, st.s[i].pbest, st.s[i],
                                   st.s[i])
                if pbret == 0 or pbret == -1:
                    st.s[i].pbest = list(st.s[i].pos)
                ret_val = model.cdom(st.sb, st.s[i + 1].pos, bestcan,
                                     st.s[i + 1])
                if ret_val == 0:
                    st.sb = st.s[i + 1].pos
                    st.sblast = st.s[i + 1].pos
                    bestcan = st.s[i + 1]
                elif ret_val == -1:
                    addToFront(model, frontier, st.s[i + 1].pos)
            if not st.sb in frontier:
                addToFront(model, frontier, st.sb)
            st.k -= 1
        # We need a clean slate here.
        # print '++++++++++++++++++++++++++++++++++++++++++++++++++++'
        # print 'Global best: ', st.sb, '\nGlobal best energy: ', st.eb
        # print 'Num deaths: ', tot_deaths
        # print 'Total number of particles ', changes*np
        # print "Attrition %0.2f percent" % (100.0 * (tot_deaths/(changes*np)))
        for can in st.s:
            addToFront(model, frontier, can.pbest)
        f = [model.cal_objs(pos) for pos in frontier]
        st.addFrontier(f)
        st.s = gens(model, np)
        st.sb = st.s[0].pbest
        st.sblast = st.s[0].pbest
        bestcan = st.s[0]
        st.t -= 1
    if graph:
        g.graph()
        g.graphEnergy()
    st.termPSO()
Exemplo n.º 18
0
    def check_state(self): #Pin durum kontrol ve pine gore checkbox checked durumu

        if state(2) == '0':
            self.chkbxs_02.setChecked(False)
        elif state(2) == '1':
            self.chkbxs_02.setChecked(True)
        else:
            pass

        if state(3) == '0':
            self.chkbxs_03.setChecked(False)
        elif state(3) == '1':
            self.chkbxs_03.setChecked(True)
        else:
            pass

        if state(4) == '0':
            self.chkbxs_04.setChecked(False)
        elif state(4) == '1':
            self.chkbxs_04.setChecked(True)
        else:
            pass

        if state(17) == '0':
            self.chkbxs_17.setChecked(False)
        elif state(17) == '1':
            self.chkbxs_17.setChecked(True)
        else:
            pass

        if state(27) == '0':
            self.chkbxs_27.setChecked(False)
        elif state(27) == '1':
            self.chkbxs_27.setChecked(True)
        else:
            pass

        if state(22) == '0':
            self.chkbxs_22.setChecked(False)
        elif state(22) == '1':
            self.chkbxs_22.setChecked(True)
        else:
            pass

        if state(10) == '0':
            self.chkbxs_10.setChecked(False)
        elif state(10) == '1':
            self.chkbxs_10.setChecked(True)
        else:
            pass

        if state(9) == '0':
            self.chkbxs_09.setChecked(False)
        elif state(9) == '1':
            self.chkbxs_09.setChecked(True)
        else:
            pass

        if state(11) == '0':
            self.chkbxs_11.setChecked(False)
        elif state(11) == '1':
            self.chkbxs_11.setChecked(True)
        else:
            pass

        if state(5) == '0':
            self.chkbxs_05.setChecked(False)
        elif state(5) == '1':
            self.chkbxs_05.setChecked(True)
        else:
            pass

        if state(6) == '0':
            self.chkbxs_06.setChecked(False)
        elif state(6) == '1':
            self.chkbxs_06.setChecked(True)
        else:
            pass

        if state(13) == '0':
            self.chkbxs_13.setChecked(False)
        elif state(13) == '1':
            self.chkbxs_13.setChecked(True)
        else:
            pass

        if state(19) == '0':
            self.chkbxs_19.setChecked(False)
        elif state(19) == '1':
            self.chkbxs_19.setChecked(True)
        else:
            pass

        if state(26) == '0':
            self.chkbxs_26.setChecked(False)
        elif state(26) == '1':
            self.chkbxs_26.setChecked(True)
        else:
            pass

        if state(14) == '0':
            self.chkbxa_14.setChecked(False)
        elif state(14) == '1':
            self.chkbxa_14.setChecked(True)
        else:
            pass

        if state(15) == '0':
            self.chkbxa_15.setChecked(False)
        elif state(15) == '1':
            self.chkbxa_15.setChecked(True)
        else:
            pass

        if state(18) == '0':
            self.chkbxa_18.setChecked(False)
        elif state(18) == '1':
            self.chkbxa_18.setChecked(True)
        else:
            pass

        if state(23) == '0':
            self.chkbxa_23.setChecked(False)
        elif state(23) == '1':
            self.chkbxa_23.setChecked(True)
        else:
            pass

        if state(24) == '0':
            self.chkbxa_24.setChecked(False)
        elif state(24) == '1':
            self.chkbxa_24.setChecked(True)
        else:
            pass

        if state(25) == '0':
            self.chkbxa_25.setChecked(False)
        elif state(25) == '1':
            self.chkbxa_25.setChecked(True)
        else:
            pass

        if state(8) == '0':
            self.chkbxa_08.setChecked(False)
        elif state(8) == '1':
            self.chkbxa_08.setChecked(True)
        else:
            pass

        if state(7) == '0':
            self.chkbxa_07.setChecked(False)
        elif state(7) == '1':
            self.chkbxa_07.setChecked(True)
        else:
            pass

        if state(12) == '0':
            self.chkbxa_12.setChecked(False)
        elif state(12) == '1':
            self.chkbxa_12.setChecked(True)
        else:
            pass
        """
        if state(16) == '0':
            self.chkbxa_16.setChecked(False)
        elif state(16) == '1':
            self.chkbxa_16.setChecked(True)
        else:
            pass
        """
        if state(20) == '0':
            self.chkbxa_20.setChecked(False)
        elif state(20) == '1':
            self.chkbxa_20.setChecked(True)
        else:
            pass

        if state(21) == '0':
            self.chkbxa_21.setChecked(False)
        elif state(21) == '1':
            self.chkbxa_21.setChecked(True)
        else:
            pass
Exemplo n.º 19
0
def PSO(model, retries, changes, graph=False, goal = 0.01, pat = 100, \
era = 100, np=30, phi_1=3.8, phi_2=2.2, personalListSize=5):
    g = grapher(model, int(retries), 1, changes, "PSO" + str(changes))
    emin = 0
    phi_tot = phi_1 + phi_2
    k = (2.0 / math.fabs(2.0 -
                         (phi_tot) - math.sqrt(phi_tot**2.0 - 4.0 * phi_tot)))
    s = gens(model, np, personalListSize)
    st = state(model.name, 'adaptiveGlobalPSO', s, 0, retries, changes, era)
    st.sb = st.s[0].pos
    bestcan = st.s[0]
    tot_deaths = 0
    model.initializeObjectiveMaxMin(st.sb)
    for c in st.s:
        model.updateObjectiveMaxMin(c.pos)
    frontier = runDom(st, model, list())
    # basic idea is this is a list of positions that
    # persist between retries.
    global_frontier = list()
    #retry loop
    while st.t:
        print "."
        st.k = changes
        #iterative loop
        while st.k:
            if st.k % 100 == 0:
                print "=" * 29
                print "k ", st.k
                print "tot_deaths ", tot_deaths
            num_deaths = 0
            for can in st.s:
                can.vel =  [k * (vel + (phi_1 * random.uniform(0,1) * (best - pos)) + \
                 (phi_2 * random.uniform(0,1) * (gbest - pos))) \
                    for vel, pos, best, gbest in zip(can.vel, can.pos, can.pbest[0], frontier[0])]
                # print 'can.vel ', can.vel
                can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]
                if not model.checkBounds(
                        can.pos) or not model.checkConstraints(can.pos):
                    can.pos = model.retry()
                    can.vel = [0.1 for x in can.pos]
                    num_deaths += 1
                model.updateObjectiveMaxMin(can.pos)
            tot_deaths += num_deaths
            g.trackParticle(st.s[0].pos, 0, st.k)
            # for v in st.s:
            #     g.addVector(v.pos, v.uniq)
            runDom(st, model, frontier)
            st.k -= 1
        st.s = gens(model, np, personalListSize)
        st.sb = st.s[0].pbest
        bestcan = st.s[0]
        st.t -= 1
        for f in frontier:
            global_frontier.append(f)
            g.addVector(f, int(st.t))
        frontier = runDom(st, model, list())
        # for v in st.s:
        #     g.addVector(v.pbest[0], v.uniq)
    for f in global_frontier:
        st.reg_front.append(model.cal_objs_2(f))
        st.norm_front.append(model.cal_objs(f))
    g.graph()
    g.graphEnergy()
    g.graphTrackedParticle()
    st.termPSO()
Exemplo n.º 20
0
def mws(model, retries, changes, goal = 0.01, pat = 100, era = 100):
    emin = 0
    s = model.retry()
    model.initializeObjectiveMaxMin(s)
    # prime the maxs and mins with values, avoids divide by 0
    for i in xrange(1000):
        model.updateObjectiveMaxMin(model.retry())
    st = state(model.name, 'MWS', s, model.energy(s), retries, changes, era)
    while st.t:
        st.k = changes
        patience = pat
        while st.k:
            # 1st possible stopping condition
            # close to the minimum
            if st.eb - emin <= goal:
                st.sbo = st.sb
                st.ebo = model.energy(st.sbo)
                st.term()
                return
            # 2nd stopping condition
            # We've had the same best for
            # a long while.
            if st.eb == st.eblast:
                if patience == 0:
                    st.bored()
                    st.k = 0
                    break
                else:
                    patience -= 1
            else:
                patience = pat
                st.eblast = st.eb
            c = randint(0, model.numOfVars - 1)
            if(random() >= 0.5):
                st.sn = model.mutate(st.s, c)
                if(model.updateObjectiveMaxMin(st.sn)):
                    st.e = model.energy(st.s)  # update all energies if new normal
                    st.eb = model.energy(st.sb)
                    st.ebo = model.energy(st.sbo)
            else:
                tempS = list(st.sn)
                tempE = model.energy(st.sn)
                for index in range(1, 10):
                    tempS[c] = (model.bounds[c][1] -
                                model.bounds[c][0]) * (index / 10.0)
                    if(model.checkConstraints(tempS)):
                        if(model.updateObjectiveMaxMin(tempS)):
                            # update all energies if new normal
                            st.e = model.energy(st.s)
                            st.eb = model.energy(st.sb)
                            st.ebo = model.energy(st.sbo)
                            st.en = model.energy(st.sn)
                            tempE = model.energy(tempS)
                        if(model.energy(tempS) < tempE):
                            st.sn = list(tempS)
                            tempE = model.energy(tempS)
            st.en = model.energy(st.sn)
            if st.en < st.eb:
                st.sb = list(st.sn)
                st.eb = st.en
                st.app_out('!')
            if st.en < st.e:
                st.app_out('+')
            else:
                st.app_out('.')
            # Always promote the last solution
            st.s = list(st.sn)
            st.e = st.en
            st.k -= 1
        # First check if the sb for that set of changes was better
        # Than any of our other retries
        if(st.eb < st.ebo):
            st.sbo = list(st.sb)
            st.ebo = st.eb
            st.app_out('^')
            # Then retry with a brand new set of values
        st.s = model.retry()
        st.e = model.energy(st.s)
        st.sn = list(st.s)
        st.en = st.e
        st.sb = list(st.sn)
        st.eb = st.en
        st.t -= 1
    st.term()
def classicalGlobalPSOV2(model, retries, changes, goal = 0.01, pat = 100, era = 100, np=30, phi_1=2.8, phi_2=1.3, inertia=0.8):
    emin = 0

    #setting vmax to full search range for an particle (from lit)
    # val bounds = [model.getBounds(i) for i in range(model.numOfDecisions())][0]
    # val difference 
    vmax = max([(x[1] - x[0]) for x in [model.getBounds(i) for i in range(model.numOfDecisions())]]) / 10.0

    radius = vmax * 0.20;
    
    s = gens(model, np, radius)
    #initialize grapher
    g = grapher(model, np)
    for can in s:
        g.addVector(can.pos, can.uniq)
    # Energy here is set to zero since we're not actively using it for now.
    st = state(model.name, 'classicalGlobalPSOV2', s, 0, retries, changes, era)
    print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++'
    print 'Model Name: ', model.name, '\nOptimizer: Classical Global PSO V2, K: ', changes
    # Set an initial value for the global best
    # The downside to setting pbest equal to the current
    # particle position is that if there is a high phi_1 value
    # the particle will stay still until something happens globally
    # that pushes it away.
    st.sb = st.s[0].pbest
    #Initialize objective mins and maxs
    model.initializeObjectiveMaxMin(st.sb)
    #we whould do this just in case
    for c in st.s:
        model.updateObjectiveMaxMin(c.pos)
    tot_deaths = 0
    while st.t:
        st.k = changes
        patience = pat
        while st.k:
            num_deaths = 0
            for can in st.s:
                can.vel =  [inertia * vel + (phi_1 * random.uniform(0,1) * (best - pos)) + (phi_2 * random.uniform(0,1) * (gbest - pos)) \
                    for vel, pos, best, gbest in zip(can.vel, can.pos, can.pbest, st.sb)]
                #checking if velocity is at max
                can.vel = [vmax if vel > vmax else vel for vel in can.vel]
                can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]
                
                # Currently doing the same thing for particles that are
                # out of bounds and out of constraints, simply killing them
                # definitely some other options with this.  If they get to
                # bounds can set vector to boundary, and vel ot zero, then
                # just let them be pulled back into the space.
                if not model.checkBounds(can.pos):
                    can.pos = model.retry()
                    can.vel = [0.0 for x in can.pos]
                    # Should a killed candidate maintain it's phantom memory?
                    # Uncomment this to wipe its memory.
                    # can.pbest = list(can.pos)
                    num_deaths += 1
                if not model.checkConstraints(can.pos):
                    can.pos = model.retry()
                    can.vel = [0.0 for x in can.pos]
                    # Should a killed candidate maintain it's phantom memory?
                    # Uncomment this to wipe its memory.
                    # can.pbest = list(can.pos)
                    num_deaths += 1
                #Update objective maxs and mins
                g.addVector(can.pos, can.uniq)
                model.updateObjectiveMaxMin(can.pos)

            #logic for dealing with collision and combining
            #particles
            for c in st.s:
                for can in st.s:
                    if c == can:
                        continue
                    else:
                        radius = distance(c.pos, can.pos)
                        #if we are within the particles gravitational pull
                        #combine into one particle
                        if radius < max(c.radius, can.radius):
                            #the particle with better energy 
                            #becomes the final particle
                            #we delete the particle with worse energy
                            print("particle " + str(c.uniq) + " combined")
                            if model.energy(c.pos) < model.energy(can.pos):
                                c.weight = c.weight + can.weight
                                c.radius = c.radius + can.radius
                                can.pos = model.retry()
                                can.vel = [0.0 for x in can.pos]
                            else:
                                can.weight = can.weight + c.weight
                                c.radius = c.radius + can.radius
                                c.pos = model.retry()
                                c.vel = [0.0 for x in c.pos]
                        else:
                            #here we repulse if we are outside
                            #the radius of gravitation for the
                            #particles
                            repulsedVelocity = repulsion(c, can, radius)
                            print(repulsedVelocity)
                            can.vel = [repulsedVelocity * vel for vel in can.vel]
                            can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]
                            #instead of resetting wiggle 
                            #each index until bounds and constraints
                            #are met
                            for i in xrange(len(can.pos)):
                                can.pos = model.singleRetry(can.pos, i)

                            #other particle will repulse the opposite direction    
                            c.vel = [-repulsedVelocity * vel for vel in c.vel]
                            c.pos = [pos + vel for pos, vel in zip(c.pos, c.vel)]
                            for i in xrange(len(c.pos)):
                                c.pos = model.singleRetry(can.pos, i)

            tot_deaths += num_deaths
            #if you want to see step by step particle movement uncomment below
            #warning you will end up having to terminate this manually
            #g.graph()
            # print "======================="
            # print "BEGIN DOM PROC K: ", st.k
            # print "======================="
            best = st.s[0]
            best_list = []
            low_diff = []
            for c in st.s:
                best = c
                # print 'c is ', c.uniq
                # We first check the can's personal best
                # and update it if its current position
                # dominates.
                if model.cdom(c.pos, c.pbest, c):
                    c.pbest = list(c.pos)
                for can in st.s:
                    if c == can:
                        continue
                    elif c.pos == can.pos:
                        # print "PARTICLES IN SAME POSITION"
                        continue
                    # If we're at this point then the particles
                    # aren't exactly equal in position, and also
                    # aren't the same particle.
                    diff = sum([math.fabs(x-y) for x,y in zip(c.pos, can.pos)])
                    # if diff < 1:
                    #     # print 'diff: ', diff, ' particle ids: ', c.uniq, can.uniq
                    #     low_diff.append((c.uniq, can.uniq))
                    if model.cdom(can.pos, best.pos, can, best):
                        #If we're here then we've been
                        #bettered by the next can, so we
                        #just set it to be our cursor
                        best = can
                # Once we make it out here we should have the
                # global best candidate.
                if(not best.uniq in best_list):
                    best_list.append(best.uniq)
                # print 'best id after run ', best.uniq
            st.sb = best.pos
            st.eb = model.energy(st.sb)
            # print 'low diff list ', low_diff
            # print 'best_list ', best_list
            st.k -= 1
        # We need a clean slate here.
        # print '++++++++++++++++++++++++++++++++++++++++++++++++++++'
        # print 'Global best: ', st.sb, '\nGlobal best energy: ', st.eb
        # print 'Num deaths: ', tot_deaths
        # print 'Total number of particles ', changes*np
        # print "Attrition %0.2f percent" % (100.0 * (tot_deaths/(changes*np)))
        #st.s = gens(model, np)
        st.sb = st.s[0].pbest
        st.t -= 1
    g.graph()
    g.graphEnergy()
    st.term()
Exemplo n.º 22
0
def sa(model, retries, changes, goal = 0.01, pat = 100, era = 100):
    emin = 0
    s = model.retry()
    model.initializeObjectiveMaxMin(s)
    for i in xrange(1000):
        # prime the maxs and mins with second values, avoids divide by 0
        model.updateObjectiveMaxMin(model.retry())
    st = state(model.name, 'SA', s, model.energy(s), retries, changes, era)
    print 'model name ', model.name
    #changes is some static value passed by the caller
    #st changes is actually a counter
    while st.t:
        st.k = changes
        patience = pat
        while st.k:
            # 1st possible stopping condition
            # close to the minimum
            if st.eb - emin <= goal:
                st.sbo = st.sb
                st.eb = model.energy(st.sb)
                st.ebo = model.energy(st.sbo)
                st.term()
                return
            # 2nd stopping condition
            # We've had the same best for
            # a long while.
            if st.eb == st.eblast:
                if patience == 0:
                    st.bored()
                    st.k = 0
                    break
                else:
                    patience -= 1
            else:
                patience = pat
                st.eblast = st.eb
            c = randint(0, model.numOfVars - 1)
            st.sn = neighbor(model, c, st.s, st.k / changes)
            if(model.updateObjectiveMaxMin(st.sn)):  # check if new objective bounds
                st.e = model.energy(st.s)  # adjust accordingly
                st.eb = model.energy(st.sb)
                st.ebo = model.energy(st.sbo)
            st.en = model.energy(st.sn)
            if(st.en < st.eb):
                st.app_out('!')
                st.sb = st.sn
                st.eb = st.en
            if((st.en < st.e)):
                st.app_out('+')
                st.s = st.sn
                st.e = st.en
            elif(st.en == st.e):
                st.app_out('=')
                # print 's ', st.s
                # print 'sn ', st.sn
            elif(prob(st.e, st.en, ((changes - st.k)/changes), st.t) < random()):
                st.app_out('?')
                st.s = st.sn
                st.e = st.en
            else:
                st.app_out('.')
            st.k -= 1
        # First check if the sb for that set of changes was better
        # Than any of our other retries
        if(st.eb < st.ebo):
            st.app_out(' ^')
            st.sbo = list(st.sb)
            st.ebo = st.eb
        # Then retry with a brand new set of values
        st.s = model.retry()
        st.e = model.energy(st.s)
        st.sn = list(st.s)
        st.en = st.e
        st.sb = list(st.sn)
        st.eb = st.en
        st.t -= 1
    st.term()
Exemplo n.º 23
0
def PSOv2(model, retries, changes, graph=False, goal = 0.01, pat = 100, \
era = 100, np=30, phi_1=3.8, phi_2=2.2, personalListSize=5, out='out.txt'):
    #g = grapher(model, int(retries), 1, changes, "PSOv2" + str(changes))
    emin = 0
    phi_tot = phi_1 + phi_2
    k = (2.0/math.fabs((2.0 - phi_tot) - math.sqrt(phi_tot**2.0 - 4.0*phi_tot)))
    #k = 0.25
    print k
    vmax = max([(x[1] - x[0]) for x in [model.getBounds(i) for i in range(model.numOfDecisions())]])
    baseRadius = vmax/float(model.numOfDecisions())

    s = gens(model, np, personalListSize)

    st = state(model.name, 'PSOv2', s, 0, retries, changes, era)

    st.sb = st.s[0].pos
    bestcan = st.s[0]
    tot_deaths = 0
    model.initializeObjectiveMaxMin(st.sb)
    for c in st.s:
        model.updateObjectiveMaxMin(c.pos)
    frontier = runDom(st, model, list())
    # basic idea is this is a list of positions that
    # persist between retries.
    global_frontier = list()
    #retry loop
    while st.t:
        print "."
        # model.initializeObjectiveMaxMin(st.sb)
        # for c in st.s:
        #     model.updateObjectiveMaxMin(c.pos)
        st.k = changes
        #iterative loop
        while st.k:
            if st.k % 100 == 0:
                print "="*29
                print "k ", st.k
                print "tot_deaths ", tot_deaths
            num_deaths = 0
            uniqTracker = list()
            for can in st.s:
                can.vel =  [k * (vel + (phi_1 * random.uniform(0,1) * (best - pos)) + \
                 (phi_2 * random.uniform(0,1) * (gbest - pos))) \
                    for vel, pos, best, gbest in zip(can.vel, can.pos, can.pbest[0], frontier[0])]
                # print 'can.vel ', can.vel
                can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]
                #V2 logic here
                #tracks to make sure we are not doubling up
                uniqTracker.append(can.uniq)
                for c in st.s:
                    if c.uniq in uniqTracker:
                        continue
                    else:
                        radius = distance(c.pos, can.pos)
                        #stop crowding my space
                        if(radius < baseRadius):
                            newRadius = (c.radius + can.radius)**(0.5)
                            #print(newRadius)
                            c.radius = newRadius
                            can.radius = newRadius

                        #always repulse for a little jitter
                        repulsedVelocity = repulsion(c, can, radius)
                        #print("repulsed force=" + str(repulsedVelocity))
                        can.vel = [repulsedVelocity * vmax + vel for vel in can.vel]
                        can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]
                        #instead of resetting wiggle
                        #each index until bounds and constraints
                        #are met
                        for i in xrange(len(can.pos)):
                            can.pos = model.singleRetry(can.pos, i)

                        #other particle will repulse the opposite direction    
                        c.vel = [-repulsedVelocity * vmax + vel for vel in c.vel]
                        c.pos = [pos + vel for pos, vel in zip(c.pos, c.vel)]
                        for i in xrange(len(c.pos)):
                            c.pos = model.singleRetry(can.pos, i)

                if not model.checkBounds(can.pos) or not model.checkConstraints(can.pos):
                    can.pos = model.retry()
                    can.vel = [0.1 for x in can.pos]
                    num_deaths += 1
                model.updateObjectiveMaxMin(can.pos)
            tot_deaths += num_deaths
            #g.trackParticle(st.s[0].pos, 0, st.k)
            # for v in st.s:
            #     g.addVector(v.pos, v.uniq)
            runDom(st, model, frontier)
            st.k -= 1

        for can in st.s:
            print(str(can.uniq)+ " radius = " + str(can.radius) + " energy = " + str(model.energy(can.pbest[0])))
        st.s = gens(model, np, personalListSize)
        st.sb = st.s[0].pbest
        bestcan = st.s[0]
        st.t -= 1
        # print 'final front ', [model.cal_objs_2(f) for f in frontier]
        for f in frontier:
            global_frontier.append(f)
            # g.addVector(f, int(st.t))
        frontier = runDom(st,model,list())
        # for v in st.s:
        #     g.addVector(v.pbest[0], v.uniq)
    for f in global_frontier:
        st.reg_front.append(model.cal_objs_2(f))
        st.norm_front.append(model.cal_objs(f))
    # g.graph()
    # g.graphEnergy()
    # g.graphTrackedParticle()
    st.termPSO()
Exemplo n.º 24
0

def random_dir():
    dir = ""
    x = random.randint(1, 5)
    if x == 1:
        dir = "up"
    elif x == 2:
        dir = "right"
    elif x == 3:
        dir = "down"
    elif x == 4:
        dir = "left"
    return dir


# begin state
grid = Board()
grid.bord[10, 10] = 100
print(grid)

# muis aanmaken op start
mouse = mouse(1, 1)
start = state(mouse, grid)

# 1 keer random alles proberen tot dat je in einde komt

while not start.mouse.end:

    start.mouse.end = True
Exemplo n.º 25
0
def sac(model, retries, changes, goal = 0.01, pat = 100, era = 100):
    emin = 0
    s = model.retry()
    model.initializeObjectiveMaxMin(s)
    for i in xrange(1000):
        # prime the maxs and mins with second values, avoids divide by 0
        model.updateObjectiveMaxMin(model.retry())
    st = state(model.name, 'SAC', s, model.energy(s), retries, changes, era)
    print 'model name ', model.name
    #changes is some static value passed by the caller
    #st changes is actually a counter
    while st.t:
        st.k = changes
        patience = pat
        while st.k:
            # An Energy based stopping condition
            # doesn't make sense here.
            # 1st possible stopping condition
            # close to the minimum
            # if st.eb - emin <= goal:
            #     st.sbo = st.sb
            #     st.eb = model.energy(st.sb)
            #     st.ebo = model.energy(st.sbo)
            #     st.term()
            #     return
            # 2nd stopping condition
            # We've had the same best for
            # a long while.
            # This still makes sense since we can just
            # check if the vector is the same, if it is
            # it hasn't been dominated in quite awhile.
            if st.sb == st.sblast:
                if patience == 0:
                    st.bored()
                    st.k = 0
                    break
                else:
                    patience -= 1
            else:
                patience = pat
                st.sblast = list(st.sb)
            c = randint(0, model.numOfVars - 1)
            st.sn = neighbor(model, c, st.s, st.k / changes)
            if(model.updateObjectiveMaxMin(st.sn)):  # check if new objective bounds
                st.e = model.energy(st.s)  # adjust accordingly
                st.eb = model.energy(st.sb)
                st.ebo = model.energy(st.sbo)
            best = cdom(model, st.sn, st.sb)
            better = cdom(model, st.sn, st.s)
            st.en = model.energy(st.sn)
            if(best):
                st.app_out('!')
                st.sb = list(st.sn)
                st.eb = st.en
            if(better):
                st.app_out('+')
                st.s = list(st.sn)
                st.e = st.en
            # This is just pegged so that the old is better than the new
            # I'm using pretty small values here.  The actual aggregated values
            # are much larger, so obviously this isn't going to work exactly right
            # the whole point though is just to test out cdom.
            elif(prob(st.e, st.en,((changes - st.k)/changes), st.t) < random()):
                st.app_out('?')
                st.s = st.sn
                st.e = st.en
            else:
                st.app_out('.')
            st.k -= 1
        # First check if the sb for that set of changes was better
        # Than any of our other retries
        ultimate = cdom(model, st.sb, st.sbo)
        if(ultimate):
            st.app_out(' ^')
            st.sbo = list(st.sb)
            st.ebo = st.eb
        # Then retry with a brand new set of values
        st.s = model.retry()
        st.sn = list(st.s)
        st.sb = list(st.sn)
        st.e = model.energy(st.s)
        st.en = st.e
        st.eb = st.en
        st.t -= 1
    st.term()
Exemplo n.º 26
0
def PSO(model, retries, changes, graph=False, goal = 0.01, pat = 100, \
era = 100, np=30, phi_1=3.8, phi_2=2.2, personalListSize=5):
    g = grapher(model, int(retries), 1, changes, "PSO" + str(changes))
    emin = 0
    phi_tot = phi_1 + phi_2
    k = (2.0/math.fabs(2.0 - (phi_tot) - math.sqrt(phi_tot**2.0 - 4.0*phi_tot)))
    s = gens(model, np, personalListSize)
    st = state(model.name, 'adaptiveGlobalPSO', s, 0, retries, changes, era)
    st.sb = st.s[0].pos
    bestcan = st.s[0]
    tot_deaths = 0
    model.initializeObjectiveMaxMin(st.sb)
    for c in st.s:
        model.updateObjectiveMaxMin(c.pos)
    frontier = runDom(st, model, list())
    # basic idea is this is a list of positions that
    # persist between retries.
    global_frontier = list()
    #retry loop
    while st.t:
        print "."
        st.k = changes
        #iterative loop
        while st.k:
            if st.k % 100 == 0:
                print "="*29
                print "k ", st.k
                print "tot_deaths ", tot_deaths
            num_deaths = 0
            for can in st.s:
                can.vel =  [k * (vel + (phi_1 * random.uniform(0,1) * (best - pos)) + \
                 (phi_2 * random.uniform(0,1) * (gbest - pos))) \
                    for vel, pos, best, gbest in zip(can.vel, can.pos, can.pbest[0], frontier[0])]
                # print 'can.vel ', can.vel
                can.pos = [pos + vel for pos, vel in zip(can.pos, can.vel)]
                if not model.checkBounds(can.pos) or not model.checkConstraints(can.pos):
                    can.pos = model.retry()
                    can.vel = [0.1 for x in can.pos]
                    num_deaths += 1
                model.updateObjectiveMaxMin(can.pos)
            tot_deaths += num_deaths
            g.trackParticle(st.s[0].pos, 0, st.k)
            # for v in st.s:
            #     g.addVector(v.pos, v.uniq)
            runDom(st, model, frontier)
            st.k -= 1
        st.s = gens(model, np, personalListSize)
        st.sb = st.s[0].pbest
        bestcan = st.s[0]
        st.t -= 1
        for f in frontier:
            global_frontier.append(f)
            g.addVector(f, int(st.t))
        frontier = runDom(st,model,list())
        # for v in st.s:
        #     g.addVector(v.pbest[0], v.uniq)
    for f in global_frontier:
        st.reg_front.append(model.cal_objs_2(f))
        st.norm_front.append(model.cal_objs(f))
    g.graph()
    g.graphEnergy()
    g.graphTrackedParticle()
    st.termPSO()
Exemplo n.º 27
0
from state import *

import os

s = state()

s.acquireGPS()
s.measure()
s.Y = s.X
t = s.gps.timestamp
s.time = self.gps.timestamp[0] * 3600 + self.gps.timestamp[
    1] * 60 + self.gps.timestamp[2]
d = s.gps.date
flightID = '{}{}{}{}{}{}.csv'.format(d[0], d[1], d[2], t[0], t[1], t[2])
directory = 'flightData{}'.format(flightID)
initFiles(directory)
os.mkdir(directory)

while True:
    if s.burst == False:
        s.ascentLoop(directory)
    if s.burst == True:
        s.descentLoop(directory)
        s.logError('{}/error.csv'.format(directory, flightID))
Exemplo n.º 28
0
import socket
import threading
import time
from commands import *
from state import *
from hardware_listener import *

state = state()

def telnet_command(line):
    words = line.split()
    if not words:
        return ""
    command = words[0]
    params = words[1:]

    commands = {
        "help" : cmd_help,
        "alarm" : cmd_alarm,
        "sensor" : cmd_sensor,
        "fifo" : cmd_fifo,
        "action" : cmd_action,
        "chain" : cmd_chain,
        "rule" : cmd_rule,
        "ls" : cmd_ls
            }

    if command in commands:
        return commands.get(command)(state, params)
    return "command not found\n"