Ejemplo n.º 1
0
def main():
    pop = []
    for i in range(Config.pop_size):
        pop.append(Grn())

    simulate(pop)

    # print("Population")
    # print(pop[0])
    # print()
    # print(pop[1])
    # print()
    # print(pop[2])
    # print()
    #
    # print("Crossover")
    # print()
    # c1,c2 = std_crossover(pop)
    #
    # print("Children")
    # print(c1)
    # print(c1.initial_proteins)
    # print()
    # print(c2)
    # print(c2.initial_proteins)
    print()
Ejemplo n.º 2
0
 def handle(self):
     # self.request is the TCP socket connected to the client
     self.data = self.request.recv(1024).strip()
     if self.data:
         sim.simulate(self.data)
         
     print self.data
Ejemplo n.º 3
0
def createSimulate(netParams=None, simConfig=None, output=False):
    ''' Sequence of commands create, simulate and analyse network '''
    (pops, cells, conns, stims, simData) = sim.create(netParams,
                                                      simConfig,
                                                      output=True)
    sim.simulate()

    if output: return (pops, cells, conns, stims, simData)
Ejemplo n.º 4
0
def track_ws(ws):
    results = api.rankings("closeness", 4000)
    sim_running = False
    while True:
        message = ws.receive()
        print message
        if message != "" and sim_running == False:
            rocket = getRocketParticle(obj=json.loads(message))
            sim.simulate(rocket, results)
        ws.send(message)
Ejemplo n.º 5
0
def track_ws(ws):
    results = api.rankings("closeness", 4000)
    sim_running = False
    while True:
        message = ws.receive()
        print message
        if message != "" and sim_running == False:
          rocket = getRocketParticle(obj=json.loads(message))
          sim.simulate(rocket, results)
        ws.send(message)
Ejemplo n.º 6
0
def launch():
  try:
    getRocketParticle(args=request.args)

    sim.simulate(rocket, results)

    return json.dumps(sim.convert_to_orbit(rocket))
  except Exception, e:
    resp = jsonify({'error': 'bad request', 'details': str(e)})
    resp.status_code = 500
    return resp
Ejemplo n.º 7
0
def launch():
    try:
        getRocketParticle(args=request.args)

        sim.simulate(rocket, results)

        return json.dumps(sim.convert_to_orbit(rocket))
    except Exception, e:
        resp = jsonify({'error': 'bad request', 'details': str(e)})
        resp.status_code = 500
        return resp
Ejemplo n.º 8
0
def main_prompt(khan):
	while True:
		num = None
		print("\n")
		print("[1] Load infections from file.")
		print("[2] Load users from file.")
		print("[3] Infect a user with a disease (total_infection).")
		print("[4] Infect at most a certain amount of users if possible (limited_infection).")
		print("[5] Infect exactly a certain amount of users if possible (limited_infection_perfect).")
		print("[6] Simulate real-time user-infection interaction.")
		print("[7] Print the infection hierarchy.")
		print("[8] Print the user hierarchy and each user's associated infections.")
		print("[9] Reset all users and infections to defaults.")
		print("[10] Clear all users and infections.")
		print("[11] Exit.")


		try:
			num = int(input("Please select an action to perform: "))
		except:
			pass

		print("")

		if num == 1:
			get_infections(khan)
		elif num == 2:
			get_users(khan)
		elif num == 3:
			total_infection(khan)
		elif num == 4:
			limited_infection(khan)
		elif num == 5:
			limited_infection_perfect(khan)
		elif num == 6:
			sim.simulate(khan)
		elif num == 7:
			print("***** Infections *****")
			khan.print_infections(True)
		elif num == 8:
			print("***** Users *****")
			khan.print_users(print_infections=True)
		elif num == 9:
			reset(khan)
		elif num == 10:
			clear(khan)
		elif num == 11:
			print("Goodbye!")
			return
		else:
			print("Please enter a valid number!")
Ejemplo n.º 9
0
def frac_grey_against_both(num_samples=50, max_moths=30, granularity=0.1):
    probs_white_death = np.arange(0, 1 + granularity, granularity)
    nums_moths = np.arange(1, max_moths + 1)
    results = np.zeros((len(nums_moths), len(probs_white_death)))
    probs_white_death, nums_moths = np.meshgrid(probs_white_death, nums_moths)
    stacked = np.dstack((probs_white_death, nums_moths))
    for i, group in enumerate(stacked):
        for j, pair in enumerate(group):
            prob_white_death, num_moths = pair[0], pair[1]
            results[i][j] = sum(
                simulate({'ww':0, 'wg':num_moths, 'gg':0}, prob_white_death)
                for _ in range(num_samples)) / float(num_samples)

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(probs_white_death, nums_moths, results, rstride=1, 
            cstride=1, cmap=cm.Greys, linewidth=0, antialiased=False)
    ax.set_zlim(0, 1.00)

    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.title('Fraction of Grey Moths')
    ax.set_xlabel('Probability of white moth death')
    ax.set_ylabel('Number of moths')
    ax.set_zlabel('Fraction of grey moths')

    plt.show()
Ejemplo n.º 10
0
def main():
   data, _t = simulate(X0,U)
   theta = data[0]
   theta_dot = data[1]

   #get all of our theta within -pi:pi

   i = len(data[0]) - 1

   while i > -1:
      while not -pi <= data[0][i] <= pi:
         if data[0][i] < -pi:
            data[0][i] = data[0][i] + 2*pi
         else:
            data[0][i] = data[0][i] - 2*pi
      i = i - 1

   #because our version of savetxt doesn't have the header option for some reason
   with open(OUTFILE_NAME, 'w') as f:
      f.write("theta,theta_dot,u\n")
      f.write("float,float,float\n")
      f.write(",,\n")
      trimmed_data = data[:2]
      trimmed_data = numpy.vstack([trimmed_data, U])
      numpy.savetxt(f, numpy.transpose(trimmed_data), delimiter=',', fmt="%.18f")

   plot_traj(data, U, _t)
Ejemplo n.º 11
0
def search(S):
    s = 0
    p = param.Parameters()
    while s < S:
        p.randomize()
        solution = sim.simulate(sat.Satellite(planet.Earth, p))
        print (s+1, ": <eval>\t$", eval.evaluate(solution), "\t", solution.distMin, "\t",
               solution.tMin, "\t", p.velX, "\t", p.velY, "\t", p.friction)
        s += 1
Ejemplo n.º 12
0
def auto_standard(list_lg=None, list_le=None, trials=4, sim_time=6):
    lg, le = list_lg, list_le
    if list_lg is None:
        lg = [x / 100.0 for x in range(20, -2, -2)]
    if list_le is None:
        le = [x / 100.0 for x in range(20, -2, -2)]
    trial_names = string.ascii_letters[:trials]
    for i in lg:
        for j in le:
            dir_string = str(int(i * 100)).zfill(2) + str(int(
                j * 100)).zfill(2)
            mkdir(dir_string)
            for k in trial_names:
                file_name = dir_string + k
                sim.simulate(lg=i,
                             le=j,
                             save_dir=f"{dir_string +'/'+ file_name}",
                             sim_time=sim_time)
Ejemplo n.º 13
0
def search(S):
    s = 0
    p = param.Parameters()
    while s < S:
        p.randomize()
        solution = sim.simulate(sat.Satellite(planet.Earth, p))
        print(s + 1, ": <eval>\t$", eval.evaluate(solution), "\t",
              solution.distMin, "\t", solution.tMin, "\t", p.velX, "\t",
              p.velY, "\t", p.friction)
        s += 1
Ejemplo n.º 14
0
def prob_against_white_death(num_samples=100, num_moths=30, granularity=0.05):
    samples = []
    for prob_white_death in np.arange(0, 1 + granularity, granularity):
        samples.append(sum(
                simulate({'ww':0, 'wg':num_moths, 'gg':0}, prob_white_death)
                for _ in range(num_samples)) / float(num_samples))
    plt.plot(np.arange(0, 1 + granularity, granularity), samples)
    plt.title('Grey Moths Versus Probability of White Death')
    plt.xlabel('Probability of white death')
    plt.ylabel('Fraction of grey moths')
    plt.show()
Ejemplo n.º 15
0
def worker3d(users, events, rounds):
    ''' make rounds of simulation of users '''
    print "{0} users with {1} events started".format(users, events)
    paths = []
    for _ in range(rounds):
        log, attacker_log = sim.simulate(users, messages=events)
        path = sim.match_paths(log, attacker_log)
        paths.append(path)
    # build mean and confidence interval
    mean, conf = sim.mean_confidence_interval(paths)
    print "{0} users with {1} events finished".format(users, events)
    return users, events, mean
Ejemplo n.º 16
0
def prob_all_grey(num_samples=100, max_moths=50, prob_white=0.8):
    samples = []
    for num_moths in range(1, max_moths + 1):
        samples.append(
                sum(simulate({'ww':0, 'wg':num_moths, 'gg':0}, 
                        prob_white, fraction=False)
                for _ in range(num_samples)) / float(num_samples))
    plt.plot(samples)
    plt.title(
        'Probability All Moths Turn Grey (prob_white = {})'.format(prob_white))
    plt.xlabel('Number of moths')
    plt.ylabel('Probability')
    plt.show()
Ejemplo n.º 17
0
def main_loop():

    while True:
        attacking_unit, weapon, n_shots = input_attack(FRIENDLY_ARMY)
        if n_shots is None:
            continue

        abilities_by_target = map_abilities(attacking_unit, weapon, ENEMY_ARMY,
                                            FRIENDLY_ARMY, ENEMY_ARMY)

        all_sim_results = simulate(attacking_unit, weapon, n_shots, ENEMY_ARMY,
                                   abilities_by_target)
        print_sim_results(all_sim_results)
        input('Press any key to continue...')
Ejemplo n.º 18
0
def epsilon_greedy(students, arms, bound, epsilon, log_file):
    """
    arms is a list of configurations, each config can be passed as a
    numpy array.
    bound is the number of arm pulls we will limit ourselves to
    """
    # logging header
    log_file.write("\n--- Epsilon Greedy ---\n")

    # build list of sampleArm objects to track rewards and averages
    s = list()
    for arm in arms:
        s_arm = sim.LineConfig(arm[0], arm[1], arm[2], arm[3], arm[4])
        s_arm.set_config_mu(students)
        s.append(s_arm)

    # find actual max arm, calculate deltas and log
    max_arm = get_actual_max(s)
    calculate_delta(s, max_arm)
    logger.log_arms(log_file, s)

    for i in range(bound):
        # because we are not using a simple numpy.array we will sort
        # the list in place on each interval (ineffeciennnncy)
        # to get the greedy arm
        j = pick_arm(s, epsilon)
        s[j].set_num_pulls(s[j].get_num_pulls() + 1)

        # pull the arm
        reward = sim.simulate(s[j], students, log_file)
        s[j].set_total_reward(
                s[j].get_total_reward() + reward)
        s[j].set_average(
                s[j].get_total_reward() / s[j].get_num_pulls())

        # sort the arms
        current_max = s[0]
        s.sort(key=operator.attrgetter('average'), reverse=True)
        if i != 0 and ((i + 1) % 100) == 0:
            # log current best arm
            logger.log_pulled_arm(log_file, s[0], i+1)

    # log current best arm
    logger.log_best_arm(log_file, s[0], bound)

    for arm in s:
        logger.log_num_pulls(log_file, arm)

    return str(s[0])
Ejemplo n.º 19
0
def lil_ucb(students, arms, delta, epsilon, lambda_p, beta, sigma, log_file, max_pulls):
    # delta == confidence
    #
    time = 0
    n = len(arms)
    mu = numpy.zeros(n) # set of rewards
    T = numpy.zeros(n) # T[i] is the number of times arm i has been pulled
    armList = list()
    timestep = 0

    for arm in arms:
        s_arm = sim.LineConfig(arm[0], arm[1], arm[2], arm[3], arm[4])
        s_arm.set_config_mu(students)
        armList.append(s_arm)

    # actual max used for comparison
    actual_max = get_actual_max(armList)
    # set deltas
    calculate_delta(armList, actual_max)

    #sample each of the n arms once, set T_i(t) = 1, for all i and set t=n
    for i in range(n):
        T[i] = 1
        mu[i] = sim.simulate(armList[i], students, log_file) #pull the arm
        log_file.write("ARM: %s\tCONFIGMU %s\tDELTA: %f\n" %(str(armList[i]), armList[i].get_config_mu(), armList[i].get_delta()))
        timestep += 1

    prevIndex = -1;

    while True:
        done = False
        total_pulls = sum(T)
        timestep += 1
        for i in range(n):
            #check if an arm has been pulled more than all others combined
            print("t[i]: %d >= %d\n" %(T[i], (1 + lambda_p*(total_pulls - T[i]))))
            if T[i] >= 1 + lambda_p*(total_pulls - T[i]):
                done = True
                break

        if done:
            break

        index = 0
        upper_bound_value = 0

        for i in range(n):
            #temp is that magic value used to determine the best, next arm to pull
            temp = math.sqrt((2*sigma**2 * (1 + epsilon) * math.log( math.log((1 + epsilon)* T[i])/delta))/T[i])
            temp = mu[i] + (1 + beta)*(1 + math.sqrt(epsilon))*temp

            if(temp > upper_bound_value):
                upper_bound_value = temp
                index = i


        T[index] += 1
        reward = sim.simulate(armList[index], students, log_file)
        mu[index] = ((T[index]-1)*mu[index] + reward) / T[index] #average the rewards

        if(timestep % 100 == 0):
            #log_file.write("ITERATION: %6d ARM: %s\tCONFIGMU: %f\tDELTA: %f\n" %(timestep, str(armList[index]), armList[index].get_config_mu(), armList[index].get_delta()))
            empercial_best = max(mu)
            best_arm_index = [i for i,j in enumerate(mu) if j == empercial_best]
            best_arm = armList[best_arm_index[0]]
            log_file.write("ITERATION: %6d\tBEST_ARM: %s\tCONFIG_MU: %f\tDELTA: %f\n" %(timestep, str(best_arm), best_arm.get_config_mu(), best_arm.get_delta()))


        #prevIndex = index
        if(timestep == max_pulls):
            break

    arm = armList[T.argmax()]
    log_file.write("\nBEST ARM: %s\tCONFIG_MU: %f\tDELTA: %f\n"
            %(str(arm), arm.get_config_mu(), arm.get_delta()))

    for count,arm in enumerate(armList):
        log_file.write("ARMPULLCOUNT: %s\t%d\n" %(str(arm), T[count]))

    return armList[T.argmax()]
Ejemplo n.º 20
0
from pylab import *
from sim import simulate
from curve import curvature

l = 10

dests = array(curvature(10))

# initial point
initial = [0.0, 0.0]

[x, y, gx, gy, corr, err] = simulate(
    9, l, initial, pi / 2, dests, 1.0, 1.0, 100, c_slip=0.21, c_mag=0.1, c_align=0.1037
)

print err
print corr

plot(x, y, label="Actual path", linewidth=2)
axis([0, l, 0, l])
for i in gx:
    plot([i, i], [0, l], "red")
for i in gy:
    plot([0, l], [i, i], "red")
destx = [initial[0]]
desty = [initial[1]]
for i in dests:
    destx.append(i[0])
    desty.append(i[1])
plot(destx, desty, "g--", label="Desired path", linewidth=2)
# xlabel('x coordinate position, x(m)')
Ejemplo n.º 21
0
        (gait, waypoints_B) = B.get_gait(robot_pos, target, obstacles, 0, ax,
                                         show_sub)
        times_B.append(time.time() - start)
        #if draw:
        #ax.plot([robot_pos[0], target[0]],[robot_pos[1], target[1]], c='black') # straight trajectory line from robot_pos to target

    # Naiv
    if algorithm == 3:
        start = time.time()
        gait = N.compute_gait(robot_pos, target, obstacles)
        times_naiv.append(time.time() - start)

    # simulate the gait
    if not pause and not do_skip_a:
        gait, target, robot_pos, rot, rot_a, actual_path_B, actual_path_LPG, actual_path_naiv, obstacles, LPG_obstacles = sim.simulate(
            gait, target, robot_pos, rot, rot_a, actual_path_B,
            actual_path_LPG, actual_path_naiv, obstacles, orig_obstacles,
            LPG_obstacles, algorithm, sim_obst)
        deadlock = (len(actual_path_naiv) > 200 and algorithm
                    == 3) or (len(actual_path_LPG) > 200
                              and algorithm == 1) or (len(actual_path_B) > 200
                                                      and algorithm == 2)
        if deadlock:
            if algorithm == 1:
                actual_path_LPG = []
                print(" ------------ DEADLOCK LPG ------------")
            elif algorithm == 2:
                print(" ------------ DEADLOCK BISEC ------------")
                actual_path_B = []
            elif algorithm == 3:
                print(" ------------ DEADLOCK NAIV ------------")
                actual_path_naiv = []
def sequential_halving(students, arms, bound, log_file):
    """
    Sequential Halving -- (Fixed Bound)
    Parameters:
    * let arms be an array of vectors, where each vector is a configuration
    * bound is an integer which represents the maximum number of
        arms pulls the algorithm is limited to find optimal arms with
    ** still unsure how we will set up our s, right now it is a list of
        the array arms, which shrinks by half on each iteration
    """
    # logging header
    log_file.write("\n--- Sequential Halving ---\n")

    s = list()
    # add arms with initialized values to the list
    inner_list = list()
    for arm in arms:
        s_arm = sim.LineConfig(arm[0], arm[1], arm[2], arm[3], arm[4])
        s_arm.set_config_mu(students)
        inner_list.append(s_arm)
    s.append(inner_list)

    # get the arm with the highest config_mu for comparison
    actual_max = get_actual_max(s[0])

    # set deltas
    calculate_delta(s[0], actual_max)

    # log all arms
    logger.log_arms(log_file, s[0])

    current_pulls = 0
    # run through iterations of algorithm
    for r in range(int(math.ceil(math.log(len(arms), 2)))):

        # compute the pulls per arm per iteration
        pulls_per_arm = int(
            math.floor(bound /
                       (len(s[r]) * math.ceil(math.log(len(arms), 2)))))
        current_pulls += pulls_per_arm + 1

        # sample each arm pulls_per_arm times and average results
        for i in range(len(s[r])):
            total = 0.0
            for j in range(pulls_per_arm):
                s[r][i].set_num_pulls(s[r][i].get_num_pulls() + 1)
                total += sim.simulate(s[r][i], students, log_file)
            s[r][i].set_average(total / pulls_per_arm)

# sort the remaining arms by average from above sample
        s[r].sort(key=operator.attrgetter('average'), reverse=False)

        # create next iteration which the upper half of the sorted list
        s.append(s[r][int(math.ceil(len(s[r]) / 2)):])

        # log the current empirical best arm
        logger.log_pulled_arm(log_file, s[r][len(s[r]) - 1], current_pulls)

    arm = s[int(math.ceil(math.log(len(arms), 2)))][0]
    logger.log_pulled_arm(log_file, arm, bound)
    logger.log_best_arm(log_file, arm, bound)

    for arm in s[0]:
        logger.log_num_pulls(log_file, arm)

    return arm
Ejemplo n.º 23
0
from pylab import *
from sim import simulate
from curve import curvature
v = []
avg_errors = []
max_errors = []
initial = [0.0,0.0]
l = 10.0
#dests=array(curvature(10))
dests = []
for i in arange(0.1*l, 1.1*l, 0.1*l):
	dests.append([i,i])
dests = array(dests)
for n in arange(1.0, 5.5,0.5):
  errs = []
  for j in range(0,10):
    print n, j
    tmp = simulate(9, l, initial, pi/2, dests, n,1,100)
    errs.append(tmp[-1])
    
  v.append(n)
  avg_errors.append(average(errs))  
  max_errors.append(max(errs))
  
  print n, avg_errors[-1], max_errors[-1]
print v
print avg_errors
print max_errors


Ejemplo n.º 24
0
forceAC = 10**-6
delta0= np.pi/3
q0 = 0
t = np.linspace(0,10,10**6)
counter = 0
freqs = list()
for f in ["series","parallel"]:
    if f == "parallel":
        Ls = [10**-3,10**1]
    else:
        Ls = [10**-15,10**-10]

    for R in Rs:
        for C in Cs:
            for L in Ls:
                delta,successful = simulate(R,L,C,forceDC,forceAC,w,delta0,q0,f)
                i = np.sin(delta)
                if f =="series":
                    freqs.append(nFrequencies(3,phi0/(2*np.pi*Ic*R)*t,i))
                else:
                    freqs.append(nFrequencies(3,R*C*t,i))
                plt.close()
                fig, ax = plt.subplots(figsize=(14,10))
                ax.plot(t,i,'grey')
                ax.set_xlabel(r'$\tau$')
                ax.set_ylabel(r'$I/I_c$')
                ax.set_ylim(-1.05,1.05)
                ax.set_title(f"$R = \\num{{{R:.2e}}}\:\si{{\ohm}},\:L = \\num{{{L:.2e}}}\:\si{{\henry}},$"+"\n"+f"$\:C = \\num{{{C:.2e}}}\:\si{{\\farad}}$",pad=20,multialignment='center')
                plt.tight_layout()
                fig.savefig(f"./figures/manual/{counter}")
                counter +=1
Ejemplo n.º 25
0
#[l/5,l/5],
#[2*l/5,2*l/5],
#[3*l/5,3*l/5],
#[4*l/5,4*l/5],
#[l,l]
#])
dests = []
for i in arange(0.1*l, 1.1*l, 0.1*l):
	dests.append([i,i])
dests = array(dests)
#dests = array(curvature(10))

for b in range(1, 11):
  errs = []
  
  for j in range(0,100):
    print b, j
    tmp = simulate(9, l, initial, pi/2, dests, 1.0,b,100)
    errs.append(tmp[-1])
    
  p.append(b)
  avg_errors.append(average(errs))  
  max_errors.append(max(errs))
  
  print b, avg_errors[-1], max_errors[-1]
print p
print avg_errors
print max_errors


Ejemplo n.º 26
0
def loadSimulateAnalyze(filename, simConfig=None, output=False):
    sim.load(filename, simConfig)
    sim.simulate()
    sim.analyze()
def sequential_halving(students, arms, bound, log_file):
    """
    Sequential Halving -- (Fixed Bound)
    Parameters:
    * let arms be an array of vectors, where each vector is a configuration
    * bound is an integer which represents the maximum number of
        arms pulls the algorithm is limited to find optimal arms with
    ** still unsure how we will set up our s, right now it is a list of
        the array arms, which shrinks by half on each iteration
    """
    # logging header
    log_file.write("\n--- Sequential Halving ---\n")

    s = list()
    # add arms with initialized values to the list
    inner_list = list()
    for arm in arms:
        s_arm = sim.LineConfig(arm[0], arm[1], arm[2], arm[3], arm[4])
        s_arm.set_config_mu(students)
        inner_list.append(s_arm)
    s.append(inner_list)

    # get the arm with the highest config_mu for comparison
    actual_max = get_actual_max(s[0])

    # set deltas
    calculate_delta(s[0], actual_max)

    # log all arms
    logger.log_arms(log_file, s[0])

    current_pulls = 0
    # run through iterations of algorithm
    for r in range(int(math.ceil(math.log(len(arms), 2)))):

        # compute the pulls per arm per iteration
        pulls_per_arm = int(math.floor(bound / (len(s[r])
                * math.ceil(math.log(len(arms), 2)))))
        current_pulls += pulls_per_arm + 1

        # sample each arm pulls_per_arm times and average results
        for i in range(len(s[r])):
            total = 0.0
            for j in range(pulls_per_arm):
                s[r][i].set_num_pulls(s[r][i].get_num_pulls() + 1)
                total += sim.simulate(s[r][i], students, log_file)
            s[r][i].set_average(total/pulls_per_arm)

	# sort the remaining arms by average from above sample
        s[r].sort(key=operator.attrgetter('average'), reverse=False)

        # create next iteration which the upper half of the sorted list
        s.append(s[r][int(math.ceil(len(s[r])/2)):])

        # log the current empirical best arm
        logger.log_pulled_arm(log_file, s[r][len(s[r]) - 1], current_pulls)  

    arm = s[int(math.ceil(math.log(len(arms), 2)))][0]
    logger.log_pulled_arm(log_file, arm, bound)
    logger.log_best_arm(log_file, arm, bound)

    for arm in s[0]:
        logger.log_num_pulls(log_file, arm)
    
    return arm
Ejemplo n.º 28
0
def lil_ucb(students, arms, delta, epsilon, lambda_p, beta, sigma, log_file,
            max_pulls):
    # delta == confidence
    #
    time = 0
    n = len(arms)
    mu = numpy.zeros(n)  # set of rewards
    T = numpy.zeros(n)  # T[i] is the number of times arm i has been pulled
    armList = list()
    timestep = 0

    for arm in arms:
        s_arm = sim.LineConfig(arm[0], arm[1], arm[2], arm[3], arm[4])
        s_arm.set_config_mu(students)
        armList.append(s_arm)

    # actual max used for comparison
    actual_max = get_actual_max(armList)
    # set deltas
    calculate_delta(armList, actual_max)

    #sample each of the n arms once, set T_i(t) = 1, for all i and set t=n
    for i in range(n):
        T[i] = 1
        mu[i] = sim.simulate(armList[i], students, log_file)  #pull the arm
        log_file.write("ARM: %s\tCONFIGMU %s\tDELTA: %f\n" % (str(
            armList[i]), armList[i].get_config_mu(), armList[i].get_delta()))
        timestep += 1

    prevIndex = -1

    while True:
        done = False
        total_pulls = sum(T)
        timestep += 1
        for i in range(n):
            #check if an arm has been pulled more than all others combined
            print("t[i]: %d >= %d\n" % (T[i],
                                        (1 + lambda_p * (total_pulls - T[i]))))
            if T[i] >= 1 + lambda_p * (total_pulls - T[i]):
                done = True
                break

        if done:
            break

        index = 0
        upper_bound_value = 0

        for i in range(n):
            #temp is that magic value used to determine the best, next arm to pull
            temp = math.sqrt((2 * sigma**2 * (1 + epsilon) *
                              math.log(math.log(
                                  (1 + epsilon) * T[i]) / delta)) / T[i])
            temp = mu[i] + (1 + beta) * (1 + math.sqrt(epsilon)) * temp

            if (temp > upper_bound_value):
                upper_bound_value = temp
                index = i

        T[index] += 1
        reward = sim.simulate(armList[index], students, log_file)
        mu[index] = ((T[index] - 1) * mu[index] +
                     reward) / T[index]  #average the rewards

        if (timestep % 100 == 0):
            #log_file.write("ITERATION: %6d ARM: %s\tCONFIGMU: %f\tDELTA: %f\n" %(timestep, str(armList[index]), armList[index].get_config_mu(), armList[index].get_delta()))
            empercial_best = max(mu)
            best_arm_index = [
                i for i, j in enumerate(mu) if j == empercial_best
            ]
            best_arm = armList[best_arm_index[0]]
            log_file.write(
                "ITERATION: %6d\tBEST_ARM: %s\tCONFIG_MU: %f\tDELTA: %f\n" %
                (timestep, str(best_arm), best_arm.get_config_mu(),
                 best_arm.get_delta()))

        #prevIndex = index
        if (timestep == max_pulls):
            break

    arm = armList[T.argmax()]
    log_file.write("\nBEST ARM: %s\tCONFIG_MU: %f\tDELTA: %f\n" %
                   (str(arm), arm.get_config_mu(), arm.get_delta()))

    for count, arm in enumerate(armList):
        log_file.write("ARMPULLCOUNT: %s\t%d\n" % (str(arm), T[count]))

    return armList[T.argmax()]
Ejemplo n.º 29
0
#[2*l/5,2*l/5],
#[3*l/5,3*l/5],
#[4*l/5,4*l/5],
#[l,l]
#])
dests = array(curvature(10))
#dests = []
#for i in arange(0.1*l, 1.1*l, 0.1*l):
#	dests.append([i,i])
#dests = array(dests)
for n in range(0, 10):
 errs = []
 corrs=[]  
 for j in range(0,100):
    print n,j
    tmp = simulate(n, l, initial, pi/2, dests, 1.0,1,100,0.21)
    errs.append(tmp[-1])
 #   corrs.append(tmp[-2])

 p.append(n)
 avg_errors.append(average(errs))  
 max_errors.append(max(errs))
#avg_corrs.append(average(corrs))  
#max_corrs.append(max(corrs))
  
 print n, avg_errors[-1], max_errors[-1]
print p
print avg_errors
print max_errors
#print avg_corrs
#print max_corrs
Ejemplo n.º 30
0
from pylab import *
from sim import simulate
from curve import curvature

l = 10.0

#Destination
dests = array(curvature(10))

#initial point
initial = [0.0, 0.0]

#stud mag without grid
[x, y, gx, gy, corr, err] = simulate(0, l, initial, pi/2, dests, 1.0,1,100, c_mag = 1e-2,c_align=0)
print err
plot(x,y, 'black', label='High-res sensor', linewidth=2)

#stud mag with grid
[x, y, gx, gy, corr, err] = simulate(9, l, initial, pi/2, dests, 1.0,1,100, c_mag = 1e-2,c_align=0)
print err
plot(x,y, 'black', label='High-res sensor with Grid', linestyle='-.', linewidth=3)

#hagga mag without grid
[x, y, gx, gy, corr, err] = simulate(0, l, initial, pi/2, dests, 1.0, 1,100,c_mag = 1.5e-1,c_align=0)
print err
plot(x,y, 'gray', label='Low-res sensor', linewidth=2)

#hagga mag with grid
[x, y, gx, gy, corr, err] = simulate(9, l, initial, pi/2, dests, 1.0, 1,100,c_mag = 1.5e-1,c_align=0)
print err
plot(x,y, 'gray',label='Low-res sensor with Grid', linestyle='-.', linewidth=3)
Ejemplo n.º 31
0
    ])
    start = np.array([0, .5])

    #anca(start, goals)
    #plt.show()

    for thre in [np.pi / 4, np.pi / 4, np.pi / 8]:
        f, (a1, a2) = plt.subplots(1,
                                   2,
                                   sharex=False,
                                   sharey=False,
                                   figsize=(9, 4))
        (t, b, uh, ur) = sim.simulate(start,
                                      goals,
                                      0,
                                      lazy(thre),
                                      shared_sampled(lazylike(thre),
                                                     lazy(thre)),
                                      prior=np.array([0.5, 0.5]))
        print(uh)
        visualize(a1, start, goals, trajectories=[t], u_hs=[uh], c="k")
        (t, b1, uh, ur) = sim.simulate(start,
                                       goals,
                                       0,
                                       lazy(thre),
                                       active(lazylike(thre), lazy(thre), 100),
                                       prior=np.array([0.2, 0.8]))
        print(uh)
        visualize(a2, start, goals, trajectories=[t], u_hs=[uh], c="r")
        f, a = plt.subplots(1)
        compare_beliefs(a, [b, b1], labels=["shared", "active"])
Ejemplo n.º 32
0
 sim.simulate(filepath,
              filedir,
              f,
              write,
              analyze,
              makefig,
              diffuse,
              antibunch,
              pulsed,
              numlines,
              maxlines,
              endtime,
              temp,
              concentration,
              absXsec,
              k_emission,
              emwavelength,
              bfrate,
              r,
              eta,
              n,
              accConc,
              racc,
              crashtransferprob,
              tripem,
              dftime,
              reprate,
              wavelength,
              lp,
              pulselength,
              foclen,
              NA,
              darkcounts,
              sensitivity,
              deadtime,
              afterpulse,
              order,
              mode,
              gnpwr,
              numbins,
              pulsebins,
              channels,
              dopic=0,
              normalize=normalize,
              ac=10**4,
              timestep=timestep,
              units='ns')
Ejemplo n.º 33
0
def plotTraces (include = None, timeRange = None, overlay = False, oneFigPer = 'cell', rerun = False,
    figSize = (10,8), saveData = None, saveFig = None, showFig = True): 
    ''' 
    Plot recorded traces
        - include (['all',|'allCells','allNetStims',|,120,|,'E1'|,('L2', 56)|,('L5',[4,5,6])]): List of cells for which to plot 
            the recorded traces (default: [])
        - timeRange ([start:stop]): Time range of spikes shown; if None shows all (default: None)
        - overlay (True|False): Whether to overlay the data lines or plot in separate subplots (default: False)
        - oneFigPer ('cell'|'trace'): Whether to plot one figure per cell (showing multiple traces) 
            or per trace (showing multiple cells) (default: 'cell')
        - rerun (True|False): rerun simulation so new set of cells gets recorded (default: False)
        - figSize ((width, height)): Size of figure (default: (10,8))
        - saveData (None|True|'fileName'): File name where to save the final data used to generate the figure; 
            if set to True uses filename from simConfig (default: None)
        - saveFig (None|True|'fileName'): File name where to save the figure;
            if set to True uses filename from simConfig (default: None)
        - showFig (True|False): Whether to show the figure or not (default: True)

        - Returns figure handles
    '''

    print('Plotting recorded cell traces ...')

    if include is None: include = [] # If not defined, initialize as empty list

    # rerun simulation so new include cells get recorded from
    if rerun: 
        cellsRecord = [cell.gid for cell in sim.getCellsList(include)]
        for cellRecord in cellsRecord:
            if cellRecord not in sim.cfg.recordCells:
                sim.cfg.recordCells.append(cellRecord)
        sim.setupRecording()
        sim.simulate()


    colorList = [[0.42,0.67,0.84], [0.90,0.76,0.00], [0.42,0.83,0.59], [0.90,0.32,0.00],
                [0.34,0.67,0.67], [0.90,0.59,0.00], [0.42,0.82,0.83], [1.00,0.85,0.00],
                [0.33,0.67,0.47], [1.00,0.38,0.60], [0.57,0.67,0.33], [0.5,0.2,0.0],
                [0.71,0.82,0.41], [0.0,0.2,0.5]] 

    tracesList = sim.cfg.recordTraces.keys()
    tracesList.sort()
    cells, cellGids, _ = getCellsInclude(include)
    gidPops = {cell['gid']: cell['tags']['popLabel'] for cell in cells}

    # time range
    if timeRange is None:
        timeRange = [0,sim.cfg.duration]

    recordStep = sim.cfg.recordStep

    figs = []
    tracesData = []
    # Plot one fig per cell
    if oneFigPer == 'cell':
        for gid in cellGids:
            figs.append(figure()) # Open a new figure
            fontsiz = 12
            for itrace, trace in enumerate(tracesList):
                if 'cell_'+str(gid) in sim.allSimData[trace]:
                    data = sim.allSimData[trace]['cell_'+str(gid)][int(timeRange[0]/recordStep):int(timeRange[1]/recordStep)]
                    t = arange(timeRange[0], timeRange[1]+recordStep, recordStep)
                    tracesData.append({'t': t, 'cell_'+str(gid)+'_'+trace: data})
                    color = colorList[itrace]
                    if not overlay:
                        subplot(len(tracesList),1,itrace+1)
                        color = 'blue'
                    plot(t[:len(data)], data, linewidth=1.5, color=color, label=trace)
                    xlabel('Time (ms)', fontsize=fontsiz)
                    ylabel(trace, fontsize=fontsiz)
                    xlim(timeRange)
                    if itrace==0: title('Cell %d, Pop %s '%(int(gid), gidPops[gid]))
                    if overlay: 
                        maxLabelLen = 10
                        subplots_adjust(right=(0.9-0.012*maxLabelLen))
                        legend(fontsize=fontsiz, bbox_to_anchor=(1.04, 1), loc=2, borderaxespad=0.)


    # Plot one fig per cell
    elif oneFigPer == 'trace':
        for itrace, trace in enumerate(tracesList):
            figs.append(figure()) # Open a new figure
            fontsiz = 12
            for igid, gid in enumerate(cellGids):
                if 'cell_'+str(gid) in sim.allSimData[trace]:
                    data = sim.allSimData[trace]['cell_'+str(gid)][int(timeRange[0]/recordStep):int(timeRange[1]/recordStep)]
                    t = arange(timeRange[0], timeRange[1]+recordStep, recordStep)
                    tracesData.append({'t': t, 'cell_'+str(gid)+'_'+trace: data})
                    color = colorList[igid]
                    if not overlay:
                        subplot(len(cellGids),1,igid+1)
                        color = 'blue'
                        ylabel(trace, fontsize=fontsiz)
                    plot(t[:len(data)], data, linewidth=1.5, color=color, label='Cell %d, Pop %s '%(int(gid), gidPops[gid]))
                    xlabel('Time (ms)', fontsize=fontsiz)
                    xlim(timeRange)
                    title('Cell %d, Pop %s '%(int(gid), gidPops[gid]))
            if overlay:
                maxLabelLen = 10
                subplots_adjust(right=(0.9-0.012*maxLabelLen)) 
                legend(fontsize=fontsiz, bbox_to_anchor=(1.04, 1), loc=2, borderaxespad=0.)

    try:
        tight_layout()
    except:
        pass

    #save figure data
    if saveData:
        figData = {'tracesData': tracesData, 'include': include, 'timeRange': timeRange, 'oneFigPer': oneFigPer,
         'saveData': saveData, 'saveFig': saveFig, 'showFig': showFig}
    
        _saveFigData(figData, saveData, 'traces')
 
    # save figure
    if saveFig: 
        if isinstance(saveFig, str):
            filename = saveFig
        else:
            filename = sim.cfg.filename+'_'+'traces.png'
        savefig(filename)

    # show fig 
    if showFig: _showFigure()

    return figs
Ejemplo n.º 34
0
#dests = array([
#[l/5,l/5],
#[2*l/5,2*l/5],
#[3*l/5,3*l/5],
#[4*l/5,4*l/5],
#[l,l]
#])
#dests = array(curvature(10))
dests = []
for i in arange(0.1*l, 1.1*l, 0.1*l):
	dests.append([i,i])
dests = array(dests)
for b in arange (10,110,10):
  errs = []
  
  for j in range(0,100):
    print b, j
    tmp = simulate(9, l, initial, pi/2, dests, 1.0,1,b)
    errs.append(tmp[-1])
    
  p.append(b)
  avg_errors.append(average(errs))  
  max_errors.append(max(errs))
  
  print b, avg_errors[-1], max_errors[-1]
print p
print avg_errors
print max_errors


Ejemplo n.º 35
0
l = 10.0

#Destination
dests = []
for i in arange(0.1*l, 1.1*l, 0.1*l):
	dests.append([i,i])
dests = array(dests)

#initial point
initial = [0.0, 0.0]
err_range = arange(0, 0.11, 0.01)
print err_range

errs = []
for i in err_range:
  [x, y, gx, gy, corr, err] = sim.simulate(9, l, initial, pi/2, dests, 1.0,1,100, c_slip=i)
  errs.append(err)
print errs

errs = []
for i in err_range:
  [x, y, gx, gy, corr, err] = sim.simulate(9, l, initial, pi/2, dests, 1.0,1,100, c_mag=i)
  errs.append(err)
print errs

mesh = []
errs = []
for i in err_range:
  for j in err_range:
    mesh.append([i, j])
    [x, y, gx, gy, corr, err] = monte.simulate(9, l, initial, pi/2, dests, 1.0,1,100, c_slip=i, c_mag=j)
Ejemplo n.º 36
0
#dests = array([
#[l/5,l/5],
#[2*l/5,2*l/5],
#[3*l/5,3*l/5],
#[4*l/5,4*l/5],
#[l,l]
#])
dests = []
for i in arange(0.1*l, 1.1*l, 0.1*l):
	dests.append([i,i])
dests = array(dests)
#initial point
initial = [0.0, 0.0]

#actual plot1
[x, y, gx, gy, corr, err] = simulate(0, l, initial, pi/2, dests, 1.0, 1, 100)
print err
plot(array(x)*10,array(y)*10, 'black', label='0 correction', linewidth=2)
#actual plot2
[x, y, gx, gy, corr, err] = simulate(1, l, initial, pi/2, dests, 1.0, 1, 100)
print err
plot(array(x)*10,array(y)*10, 'green', label='1 correction', linewidth=2)
#actual plot3
[x, y, gx, gy, corr, err] = simulate(2, l, initial, pi/2, dests, 1.0, 1, 100)
print err
plot(array(x)*10,array(y)*10, 'blue', label='2 corrections', linewidth=2)
legend(loc=2)

l *= 10
dests *= 10
gx *= 10
Ejemplo n.º 37
0
from pylab import *
from sim import simulate

a = []
avg_errors = []
max_errors = []
initial = [0.0, 0.0]
l = 10.0

for n in arange(0, (pi / 2) + 0.05, pi / 20):
    errs = []
    dests = array([[l * cos(n), l * sin(n)]])

    for j in range(0, 10):
        print n, j
        tmp = simulate(10, l, initial, pi / 2, dests, 1.0)
        errs.append(tmp[-1])

    a.append(n)
    avg_errors.append(average(errs))
    max_errors.append(max(errs))

    print n, avg_errors[-1], max_errors[-1]
print a
print avg_errors
print max_errors
Ejemplo n.º 38
0
numbins = 8192
pulsebins = (10**2)-1#should always be an odd number
channels = 2

#Miscellaneous simulation parameters
picyzoom = [-1,-1]
timestep = 1000000 #average number of photons per "round" of calculations

seq = 1
i = 0
f = filenames[0]

sim.simulate(filepath, filedir, f, write, analyze, makefig, diffuse, antibunch,
                                            pulsed, numlines, maxlines, endtime,temp, concentration,
                                            dabsXsec, labsXsec, k_demission, k_sem,
                                            emwavelength, r,eta, n, k_tem, k_fiss, k_trans,
                                            reprate, wavelength, laserpwr, pulselength, foclen,
                                            NA, darkcounts, sensitivity, nligands, deadtime, afterpulse, order,
                                            mode, gnpwr, numbins, pulsebins, channels, seq)

'''
for laserpwr in [0.005,0.0005,0.5]:
    for concentration in [2*10**(-8),2*10**(-6),2*10**(-10)]:
        i = i + 1
        for sensitivity in [0.1,0.5,0.01]:
            for k_demission in [1400000,15]:
                for nligands in [100,1,10000]:
                    for diffuse in range(2):

                        f = filenames[0]
Ejemplo n.º 39
0
def loadSimulate(filename, simConfig=None, output=False):
    import sim
    sim.load(filename, simConfig)
    sim.simulate()