Ejemplo n.º 1
0
def hamiltonian_mcmc_mass_matrix(x0,M_inv,M_sqrt,findE,gradE,epsilon,Tau,N):
    d=len(x0)
    xs = np.zeros((N,d))
    g = gradE(x0); x = x0; E = findE(x0)
    accept = 0

    for t in range(N):                            # loop N times
        xs[t,] = x
        q = np.random.normal(size=d)                  # q ~ N(0,1)
        p = np.dot(M_sqrt,q)                          # p ~ N(0,M)
        H = 0.5*np.sum(p*np.dot(M_inv,p)) + E         # evaluate H(x,p)

        xnew = x; gnew = g
        for tau in range(Tau):                        # make Tau leapfrog steps
            p = p - 0.5*epsilon*gnew                     # make half step in p
            xnew = xnew + epsilon*np.dot(M_inv,p)        # make step in x
            gnew = gradE(xnew)                           # find new gradient
            p = p - 0.5*epsilon*gnew                     # make half step in p
        
        Enew = findE(xnew)
        Hnew = 0.5*np.sum(p*np.dot(M_inv,p)) + Enew   # find new value of H
        dH = Hnew - H                                 # acceptance ratio is exp(-dH)

        if runif()<np.exp(-dH):                       # accept
            accept += 1
            g = gnew; x = xnew; E = Enew
        
    freq = 100*accept/float(N)
    print "acceptance freq of {}%".format(freq)
    return xs
Ejemplo n.º 2
0
 def guess_3(self, c1, c2):
     if self.__skill == -1:
         return True if (runif() > 0.5) else False
     (lo, hi) = (c1, c2) if (c1 < c2) else (c2, c1)
     seen_between = sum(self.__snums[lo.num():hi.num()-1])
     nbetween = max(0, 4 * (hi.num() - lo.num() - 1) - seen_between)
     seen_outside = (sum(self.__snums[:lo.num()-1]) +
                     sum(self.__snums[hi.num():]))
     noutside = 4 * ((lo.num() - 1) + (13 - hi.num())) - seen_outside
     return (nbetween >= noutside)
def MC_phantoms(I,lim):
    Ny, Nu = I.shape
    
    phantoms =[]
    for y in range(Ny):
        u=0
        fired=False
        while ((u<Nu) and not(fired)):
            r=runif()
            p = I[y,u]*lim['du']*lim['dy']
            if (r < p):
                phantoms += [(lim['y'][y],lim['u'][u])]
                fired = True
            u +=1
            
    phantoms = np.array(phantoms, dtype=[('y',float),('u',float)])    
    return phantoms
Ejemplo n.º 4
0
def metropolis_mcmc(x0,findE,epsilon,N): 
    d=len(x0)
    x = x0
    xs = np.zeros((N,d))
    accept = 0

    for t in range(N):     # loop N times
        xs[t,] = x         # store all x's
        xnew = x + np.random.normal(scale=epsilon,size=d)
        dE = findE(xnew) - findE(x)
        a = np.exp(-dE)    # acceptance ratio
        if runif()<a:      # accept 
            x = xnew
            accept += 1
    
    freq = 100*accept/float(N)
    print "acceptance freq of {}%".format(freq)
    return xs
Ejemplo n.º 5
0
def exchange(loc, grid_old, live_nbrs_old):
    exchangee = grid_old[loc]

    conspecific_nbrs = [
        n for n in live_nbrs_old[loc] if grid_old[n].parent == exchangee.parent
    ]
    conspecific = (len(conspecific_nbrs) > 0)
    if conspecific:
        exchanger_stasis = grid_old[random.choice(conspecific_nbrs)].stasis
    else:
        exchanger_stasis = grid_old[random.choice(live_nbrs_old[loc])].stasis

    p1, p2 = s_set[exchangee.stasis], s_set[exchanger_stasis]
    if p1 == p2:
        return mutate(exchangee), conspecific

    new_stasis = p1.intersection(p2)
    for s in p1.symmetric_difference(p2):
        if runif() < 0.5:
            new_stasis.add(s)
    exchangee_new = exchangee.child(set_to_stasis(new_stasis))
    return mutate(exchangee_new), conspecific
Ejemplo n.º 6
0
 def sees(self, card):
     if runif() <= self.__skill:
         self.__snums[card.num()-1] += 1
         self.__ssuits[card.suit()] += 1
Ejemplo n.º 7
0
def step(grid_old, grid_new, live_nbrs_old, live_nbrs_new, live_nbrs_num_old,
         live_nbrs_num_new):
    # Determine active gain of habitability mechanism
    if params['goh_m'] == 'max':

        def goh(cell):
            return empty[s_lose_max[cell.stasis]]
    elif params['goh_m'] == 'min':

        def goh(cell):
            return empty[s_lose_min[cell.stasis]]
    elif params['goh_m'] == 'random':

        def goh(cell):
            pick = random.choice(s_list[cell.stasis])
            return empty[s_lose[cell.stasis][pick]]

    # Precompute cost function for settlement
    cost_func = {}
    f = params['fit_cost']
    for s in range(10):
        cost_func[s] = exp(-f * s)

    events = {}
    for loc in grid_old:
        cell = grid_old[loc]

        # Stasis
        if cell.stasis[live_nbrs_num_old[loc]]:
            if not cell.alive:
                if runif() < params['goh_r']:
                    grid_new[loc] = goh(cell)
                else:
                    grid_new[loc] = cell
            else:
                if (live_nbrs_num_old[loc] > 0
                        and runif() < params['exchange_r']):
                    new, conspecific = exchange(loc, grid_old, live_nbrs_old)
                    grid_new[loc] = new
                    if conspecific:
                        events[loc] = 'exchange conspecific'
                    else:
                        events[loc] = 'exchange interspecific'
                else:
                    grid_new[loc] = cell
        else:
            # Gain
            if not cell.alive:
                if live_nbrs_num_old[loc] == 0:
                    grid_new[loc] = Alive()
                    for n in neighborhood[loc]:
                        live_nbrs_new[n].append(loc)
                        live_nbrs_num_new[n] += 1
                else:
                    grid_new[loc] = settlement(loc, grid_old, live_nbrs_old,
                                               cost_func)
                    for n in neighborhood[loc]:
                        live_nbrs_new[n].append(loc)
                        live_nbrs_num_new[n] += 1
                    events[loc] = 'settlement'
            else:
                # Loss
                grid_new[loc] = empty_init
                for n in neighborhood[loc]:
                    live_nbrs_new[n].remove(loc)
                    live_nbrs_num_new[n] -= 1

    return events
Ejemplo n.º 8
0
def weighted_choice(weights):
    rnd = runif() * sum(weights)
    for i, w in enumerate(weights):
        rnd -= w
        if rnd < 0:
            return i
Ejemplo n.º 9
0
def iid_set(p):
    return {s for s in range(9) if runif() < p}