def run(): global gui import pycxsimulator pSetters = [ Initial_commensals, Initial_spores, Nutrient_replenish_rate, Antiobiotic_kill_rate ] gui = pycxsimulator.GUI(parameterSetters=pSetters, stepSize=5) gui.start(func=[init, draw, step])
def initialize(): global config, nextconfig, p config = zeros([n, n]) for x in range(n): for y in range(n): config[x, y] = 1 if random() < p else 0 nextconfig = zeros([n, n]) def observe(): global config, nextconfig, p cla() imshow(config, vmin=0, vmax=1, cmap=cm.binary) def update(): global config, nextconfig, p for x in range(n): for y in range(n): count = 0 for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: count += config[(x + dx) % n, (y + dy) % n] nextconfig[x, y] = 1 if count >= 4 else 0 config, nextconfig = nextconfig, config import pycxsimulator pycxsimulator.GUI(parameterSetters=[interactive_p]).start( func=[initialize, observe, update])
ylist = [y] def update(): global xlist, ylist, x, y nextx = x + y nexty = x x, y = nextx, nexty xlist.append(x) ylist.append(y) def observe(): global xlist, ylist pylab.show() def iterate(): global t0 t0 += 3 for x in np.arange(-2, 2, 0.4): for y in np.arange(-2, 2, 0.4): init(x, y) for t in range(t0 + 1): update() pylab.plot(xlist, ylist, "b") import pycxsimulator pycxsimulator.GUI().start(func=[initialise, iterate, observe])
subplot(1,2,2) plt.ylim((-1, 1)) plt.title('average magnetization') plt.xlabel('step') plot(range(len(avg_magns)), avg_magns) def update(): global config, t, step x = randint(0, n - 1) y = randint(0, n - 1) energy = 0 for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: # check for von-Neumann neighborhood: if abs(dx) * abs(dy) == 0: energy += config[(x + dx) % n, (y + dy) % n] energy *= -config[x, y] # product with central cell if random() < min(1, e**(2*energy / t)): config[x, y] = -config[x, y] avg_magns.append(calc_avg_magn(config)) import pycxsimulator pycxsimulator.GUI(parameterSetters=[temp_setter]).start(func=[initialize, observe, update]) # notes # energy fluctuates with higher amplitude as temperature is increased # average magnetization drops with higher temperature
def step(): global time, config, nextConfig time += 1 for x in range(width): for y in range(height): state = config[y, x] if state == 0: num = 0 for dx in range(-1, 2): for dy in range(-1, 2): if config[(y + dy) % height, (x + dx) % width] == maxState: num += 1 if RD.random() * 3 < num: state = maxState else: state = 0 else: state -= 1 nextConfig[y, x] = state config, nextConfig = nextConfig, config import pycxsimulator pycxsimulator.GUI().start(func=[init, draw, step])
uC, uR, uL, uU, uD = u[x, y], u[(x + 1) % n, y], u[(x - 1) % n, y], u[x, (y + 1) % n], u[x, (y - 1) % n] vC, vR, vL, vU, vD = v[x, y], v[(x + 1) % n, y], v[(x - 1) % n, y], v[x, (y + 1) % n], v[x, (y - 1) % n] uLap = (uR + uL + uU + uD - 4 * uC) / (Dh)**2 vLap = (vR + vL + vU + vD - 4 * vC) / (Dh)**2 nextu[x, y] = uC + (a * (uC - h) + b * (vC - k) + Du * uLap) * Dt nextv[x, y] = vC + (c * (uC - h) + d * (vC - k) + Dv * vLap) * Dt u, v, nextu, nextv = nextu, nextv, u, v def observe(): global u, v pylab.subplot(1, 2, 1) pylab.cla() pylab.imshow(u, vmin=0, vmax=2, cmap=pylab.cm.binary) pylab.title('u') pylab.subplot(1, 2, 2) pylab.cla() pylab.imshow(v, vmin=0, vmax=2, cmap=pylab.cm.binary) pylab.title('v') import pycxsimulator pycxsimulator.GUI(stepSize=50).start(func=[init, observe, update])
with open(f, "rb") as fp: H = pickle.load(fp) susceptible = [i + s for i, s in zip(H.n_infections, H.n_susceptible)] removed = [r + s for r, s in zip(H.n_removed, susceptible)] def draw(): global H, susceptible, removed, step_ cla() plot(range(H.iter + 1), H.n_infections, "r-", label="Infections") plot(range(H.iter + 1), removed, "g-", label="Rmoved") plot(range(H.iter + 1), susceptible, "y-", label="Susceptible") fill_between(range(H.iter + 1), H.n_infections, color="r") fill_between(range(H.iter + 1), susceptible, H.n_infections, color="y") fill_between(range(H.iter + 1), removed, susceptible, color="g") legend(loc="lower right") xlabel("Runs/Days") ylabel("Cases") title("Covid-19 Simulation Results") show() f = "H.pkl" update = partial(update, f=f) pycx.GUI().start(func=[init, draw, update])
marker="s", color="white" if int(self.current_state[0][pos]) == -1 else "black") elif self.lane == 2: plt.hlines([-1, 0, 1], xmin=0, xmax=self.length, color="black") for lane in range(self.lane): for pos in range(self.length): plt.scatter( pos, 0.5 if lane == 0 else -0.5, s=2, marker="s", color="white" if int( self.current_state[lane][pos]) == -1 else "black") else: print("Lanes more than 2 unavailable.") Simulator1 = TrafficSimulation(length=100, density=0.13, maxvelocity=5, probslow=0.5, steps=50, times=20, lane=2) #Simulator1.simulate() import pycxsimulator pycxsimulator.GUI().start( func=[Simulator1.initialize, Simulator1.draw, Simulator1.update])
def draw(): PL.clf() PL.subplot(1, 3, 1) PL.imshow(env.state, interpolation='nearest') PL.subplot(1, 3, 2) PL.plot(env.stats_avgrep) PL.plot(env.stats_maxrep) PL.plot(env.stats_minrep) PL.subplot(1, 3, 3) PL.hist(env.stats_eats_data) def step(): global env env.step() ##===================================== ## Section 4: [Optional] Create Setter/Getter Functions for Model Parameters ##===================================== ##===================================== ## Section 5: Import and Run GUI ##===================================== import pycxsimulator pycxsimulator.GUI(title='My Simulator', interval=0, parameterSetters=[]).start(func=[init, draw, step]) # 'title', 'interval' and 'parameterSetters' are optional
def step(): global time, config, nextConfig, initProb, infectionRate, regrowthRate, d_h, d_i for x in range(width): for y in range(height): state = config[y, x] if state == 0: for dx in range(-1, 2): for dy in range(-1, 2): if config[(y + dy) % height, (x + dx) % width] == 1: if RD.random() < regrowthRate: state = 1 elif state == 1: for dx in range(-1, 2): for dy in range(-1, 2): if config[(y + dy) % height, (x + dx) % width] == 2: if RD.random() < infectionRate: state = 2 else: state = 0 nextConfig[y, x] = state config, nextConfig = nextConfig, config import pycxsimulator pycxsimulator.GUI(parameterSetters=[ interactive_init_p, interactive_inf_p, interactive_grow_p ]).start(func=[init, draw, step])
def run(self): pycxsimulator.GUI().start( func=[self.initialize, self.observe, self.update])
Whether the world wraps. Input is 0 = False, 1 = True The parameter shouldn't be changed in a running model. """ global wraps wraps = bool(val) return val def startF(val=start): """ What time step to start the model visualization at. This can only be changed for a new model." """ global start start = int(val) return val def gridsizeF(val=gridsize): """ Gridsize of the world. Min 10. This can only be changed for a new model. """ global gridsize gridsize = int(val) return val import pycxsimulator pycxsimulator.GUI(parameterSetters=[wrapsF, startF, gridsizeF]).start( func=[initialize, observe, update])
# self.controller.add_property('C', neta.Model.TYPE_AVG_CLUSTERING_COEFFICIENT) # at least some points for the lines self.model.update() self.model.update() self.model.update() # while actual_time <= 7.5: # actual_time = self.model.update(only_graph_modification=False) def observe(self): """Observe the model and update the GUI""" self.controller.plot() def update(self): """Keep everything moving""" self.model.update() def output_data(self): self.controller.output_data() import pycxsimulator starter = Main() pycxsimulator.GUI( title='Control View', parameterSetters=starter.parameter_setters, outputFunction=starter.output_data).start( func=[starter.initialize, starter.observe, starter.update])
def update_nodes_positions(network): positions = dict() for i in network.nodes(): x = int(round((network.node[i]['lng'] + lng_max) / (lng_max * 2) * img_width)) y = int(round((network.node[i]['lat'] + lat_max) / (lat_max * 2) * img_height)) y = img_height - y pos = dict() pos['x'] = x pos['y'] = y network.node[i]['position'] = pos return network def draw(): if network is not None: draw_botnet_status_map(network) def step(): return 0 if __name__ == '__main__': global simulations global final_steps img_width, img_height = Image.open(world_image_path).size interface = pycxsimulator.GUI() interface.start(func=[init,draw,step])
def update(): global time, cars, roads, envir, total_traffic # Gitt av vi har en list over alle veiene for road in roads: popped_cars_list = road.trim_lane_ends() for popped_car in popped_cars_list: cars.remove(popped_car) new_car = road.spawn_car_cond() if new_car != False: # Hvis bil faktisk ble spawnet cars.append(new_car) for car in cars: car.update() IDIOT_IM.update(time) IDIOT_IM2.update(time) time += 1 total_traffic += len(cars) pycxsimulator.GUI().start(func=[initialize_elgeseter, observe, update]) #PROBLEM I KODEN!: ''' ser ut til at når man nå kjører koden, fungerer det meste bra, MEN Etterhvert er det kun en og en (eller liten gruppe) bil som kan bevege seg, altså ikke alle '''
if nb.type != ag.type and (ag.x - nb.x)**2 + (ag.y - nb.y)**2 < cdsq ] if ag.type == 'r': if len(neighbors) > 0: # if there are foxes nearby if random() < dr: agents.remove(ag) return if random() < rr * (1 - sum(1 for x in agents if x.type == 'r') / nr): agents.append(cp.copy(ag)) else: if len(neighbors) == 0: # if there are no rabbits nearby if random() < df: agents.remove(ag) return else: # if there are rabbits nearby if random() < rf: agents.append(cp.copy(ag)) def update_one_unit_time(): global agents t = 0. while t < 1. and len(agents) > 0: t += 1. / len(agents) update() import pycxsimulator pycxsimulator.GUI().start(func=[initialize, observe, update_one_unit_time])
neighbourhood = [ nb for nb in agents if (nb.x - ag.x)**2 + (nb.y - ag.y)**2 < r**2 and nb != ag ] num_similar = 0 for j in neighbourhood: if j.color == ag.color: num_similar += 1 if len(neighbourhood) > 0: ratio = num_similar / float(len(neighbourhood)) if ratio < th: ag.x = pylab.random() ag.y = pylab.random() def observe(): global agents pylab.cla() white = [nb for nb in agents if nb.color == 0] black = [nb for nb in agents if nb.color == 1] pylab.plot([nb.x for nb in white], [nb.y for nb in white], "go") pylab.plot([nb.x for nb in black], [nb.y for nb in black], "ko") pylab.axis("image") pylab.axis([0, 1, 0, 1]) pylab.show() import pycxsimulator pycxsimulator.GUI(parameterSetters=[n_setter, r_setter]).start( func=[init, observe, update])
def main(): # global args pycxsimulator.GUI(title='SocialNetwork', interval=0, parameterSetters=[]).start(func=[init, draw, step])
def visual(): pSetters = [rowF, colF, lengthF, widthF] pycxsimulator.GUI(parameterSetters=pSetters).start( func=[init, draw, update])
for dy in range(-1, 2): if config[(y + dy) % height, (x + dx) % width] == 2: if RD.random() < infectionRate: state = 2 else: state = 0 nextConfig[y, x] = state healthy_individuals = NP.count_nonzero(config.ravel() == 1) sick_individuals = NP.count_nonzero(config.ravel() == 2) healthy_density.append(healthy_individuals / sim_size) sick_density.append(sick_individuals / sim_size) config, nextConfig = nextConfig, config import pycxsimulator pycxsimulator.GUI( parameterSetters=[param_init, param_infection, param_growth]).start( func=[init, draw, step]) def f(x): return 28 * x**9 - 224 * x**8 + 700 * x**7 - 1120 * x**6 + 980 * x**5 - 448 * x**4 + 84 * x**3 x = NP.linspace(0, 1, 100) y = [f(x) for x in x] PL.plot(x, y, 'b-', x, x, 'r-') PL.show()
user_input = str(val) if '.' in user_input: user_input = user_input[ : user_input.index('.')] if user_input == '-1': result[index] = False else: if str(num) in user_input: result[index] = True else: result[index] = False return result global simulations global final_steps global show_plot show_plot = False final_steps = 5 args = ['-p2p', '-limit', '300', '-all', '-legend'] params = [simulation00, simulation10, simulation20, simulation30, simulation40] if len(sys.argv) > 1: args = sys.argv simulations = get_simulations(args) interface = pycxsimulator.GUI(parameterSetters=params) interface.start(func=[init,draw,step])
continue similar = 0 total = 0 for dx in range(-1, 2): for dy in range(-1, 2): if not ((dx == 0) and (dy == 0)): v = config[(y + dy)%height, (x+dx)%width] if (v != 0): total += 1 if (v == state): similar += 1 if (total == 0): percent_similar += 1 else: percent_similar += similar / (1.0*total) if (similar < threshold * total): percent_unhappy += 1 newpos = RD.randrange(len(empty)) new_y, new_x = empty[newpos] config[new_y, new_x] = state agents[i] = empty[newpos] config[y, x] = 0 empty[newpos] = agent percent_unhappy /= (1.0*len(agents)) percent_similar /= (1.0*len(agents)) import pycxsimulator pSetters = [densityF,thresholdF,widthF,heightF] sim = [init,draw,step] pycxsimulator.GUI(parameterSetters=pSetters,interval=50,stepSize=5).start(func=sim)
'#FFFF00', '#ea2ec4', '#ea2e40', '#cdcdcd', '#577a4d', '#2e46c0', '#f59422', '#219774', '#8086d9' ] mycmap = matplotlib.colors.ListedColormap(cpool[0:nTags + 1], 'index') matplotlib.cm.register_cmap(cmap=mycmap) def main(): global time init() populate() while time < maxtime: imp_model() #leave draw commented out because draw() still needs work # draw() # run simulation either with or without GUI if GUI: #go to the pycxsimulator code and find start func #the four args below are passed into pycxsimulator which uses Tkinter to make the GUI pycxsimulator.GUI().start(func=[init, populate, draw, imp_model]) else: #it is advised to add print statements throughout the model in order to track agent movements if running #main without a GUI main()
li.append(n) # Create list of random neighbors rn=[] random_node=random.choice(li) print('Random node: ', random_node, 'with state: ', g.nodes[random_node]['state']) p=random.uniform(0, 1) # Node is susceptible if g.nodes[random_node]['state']==0: for i in g.neighbors(random_node): rn.append(i) # Choose randomly one of its neighbors random_neighbor=random.choice(rn) print('Random_neighbor: ', random_neighbor, 'with state: ', g.nodes[random_neighbor]['state']) # Neighbor is infected # Sever the edge to the infected node with ps if g.nodes[random_neighbor]['state']==1 and p>ps: edge=[] edge=[random_node,random_neighbor] g.remove_edge(edge[0],edge[1]) # Node is infected else: # Simulate the recovery using pr if p>pr: g.nodes[random_node]['state']=0 # update system states for one discrete time step import pycxsimulator pycxsimulator.GUI().start(func=[initialize,draw,update])
cmap = matplotlib.cm.Spectral cmap.set_under() PL.pcolor(config, vmin=1, vmax=width + height, cmap=cmap) PL.axis('image') PL.title('t = ' + str(time)) def step(): global time, config, nextConfig if time < 50: time += 1 height, width = config.shape tmp = config.copy() if 10 < time < 50: for x in range(width): for y in range(height): if config[y, x] > 0: dx = RD.randint(-1, 1) dy = RD.randint(-1, 1) if tmp[(y + dy) % height, (x + dx) % width] == 0: tmp[(y + dy) % height, (x + dx) % width] = time config = tmp # time += 1 import pycxsimulator pSetters = [widthF, heightF] pycxsimulator.GUI(parameterSetters=pSetters).start(func=[init, draw, step])
def observar(): global config, nextconfig cla() #necesario para la utilizacion de imshow() imshow( config, vmin=0, vmax=1, cmap=cm.binary ) # cmap en imshow es para especificar el esquema de color utilizado en la trama """ Se utiliza la funcion de transicion para contar el numero de individuos con panico y aplica las reglas del modelo """ def actualizar(): global config, nextconfig for x in range(n): for y in range(n): count = 0 for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: count += config[ (x + dx) % n, (y + dy) % n] #dx & dy coordenadas relativas alrededor de x & y (de -1 a +1) para hallar el valor de las celulas vecinas #La expresión (...) % n significa que el valor dentro del paréntesis está contenido dentro del rango [0,n - 1] por el operador de modulación (%). Se trata de una técnica de codificación útil para aplicar condiciones límite periódicas de manera muy sencilla. nextconfig[x, y] = 1 if count >= 4 else 0 #Aplicando reglas config, nextconfig = nextconfig, config pycxsimulator.GUI().start(func=[inicializar, observar, actualizar])
update_removed(g, T, p_qt) update_statistics(g, H) #gnext = g.edge_subgraph(list(g.edges)[:int(p_sd*g.number_of_edges())]) with open("H_enron.pkl", "wb") as fp: pickle.dump(H, fp) def visual(): global g, H cla() ax = subplot() pos = nx.spring_layout(g) nx.draw(g, pos, node_color=get_colors(g), node_size=10, width=0.1, ax=ax) r = ((H.n_infections[H.iter] - H.n_infections[H.iter - 1]) / H.n_infections[H.iter - 1] ) * 100 if H.iter > 0 and H.n_infections[H.iter - 1] != 0 else 0 ax.set_title("Covid-19 Simulation Using Enron Network, Run: " + str(H.iter) + ", Population: " + str(g.number_of_nodes()) + ", Cases: " + str(H.n_infections[H.iter]) + ", Difference: " + str(round(r, 2)) + "%.") draw() p_sd, p_init, p, T, p_qt = 0.15, 0.01, 0.2, 14, 0.0 init = partial(init, p_sd, p_init) update = partial(update, p, T, p_qt) pycx.GUI().start(func=[init, visual, update])
def observe(): global xlist, ylist cla() plot(xlist, ylist, '.') def update(): global xlist, ylist for i in xrange(n): xlist[i] += rd.gauss(0, sd) ylist[i] += rd.gauss(0, sd) def num_particles(val=n): ''' Number of particles. Make sure you change this parameter while the simulation is not running, and reset the simulation before running it. Otherwise it causes an error! ''' global n n = int(val) return val import pycxsimulator pycxsimulator.GUI(parameterSetters=[num_particles]).start( func=[initialize, observe, update])
def update(): likematrix() global agents global like global count global indv global grp global time count += 1 ag = agents[randint(n)] neighbors = [ nb for nb in agents if (ag.x - nb.x)**2 + (ag.y - nb.y)**2 < r**2 and nb != ag ] grp_pol_leader(ag, neighbors) movement(grp) if count == 1000: for id in grp_num: ldr = grp['grp' + str(id)][1] print(ldr.leader) print(len(indv)) if len(grp) != 0: for k in grp_num: size = growth['grp' + str(k)] size.append(len(grp['grp' + str(k)])) time['grp' + str(k)].append(count) import pycxsimulator pycxsimulator.GUI().start(func=[initialize, observe, update])
def run(): pSetters = EXP.setters simfuncs = [init, draw, step, stop] sim.GUI(parameterSetters=pSetters, interval=1, stepSize=1).start(func=simfuncs)