def StartSimulation(fieldSize): grid = CanvasGrid(agent_portrayal, fieldSize, fieldSize, 500, 500) chart = ChartModule([{ "Label": "Suma przeżytych rund każdej jednostki do kosztu całej armii - czerwoni", "Color": "Red" }, { "Label": "Suma przeżytych rund każdej jednostki do kosztu całej armii - niebiescy", "Color": "Blue" }], data_collector_name='datacollector') chart_hp = ChartModule([{ "Label": "Punkty życia armii czerwonej", "Color": "Red" }, { "Label": "Punkty życia armii niebieskiej", "Color": "Blue" }], data_collector_name='datacollector_health') server = ModularServer(Battlefield, [grid, chart, chart_hp], "Draw Model", { "width": fieldSize, "height": fieldSize }) server.port = 8521 # The default server.launch()
def visualization_grid(width, height, highS, middleS, lowS, edu_setting=False, cureProb=0.1, cureProbFac=2/1440, mutateProb=0.0050, diseaseRate=0.2): """ Launch grid visualization on server. width: Width of the grid. height: Height of the grid. highS: Number of agents with high sociability. middleS: Number of agents with middle sociability. lowS: Number of agents with low sociability. edu_setting: If true, agents will follow a schedule and sit in classrooms, else they will move freely through an open grid. cureProb: Probability of agent getting better. cureProbFac: Factor of cureProb getting higher. mutateProb: Probability of a disease mutating. diseaseRate: Rate at which the disease spreads """ grid = CanvasGrid(agent_portrayal, width, height, width*10, height*10) server = ModularServer(DiseaseModel, [grid], "Disease Model", {"highS": highS, "middleS": middleS, "lowS": lowS, "width": width, "height": height, "edu_setting": edu_setting, "cureProb": cureProb, "cureProbFac": cureProbFac, "mutateProb": mutateProb, "diseaseRate": diseaseRate}) server.port = 8521 # The default server.launch()
def __init__(self, model): #super().__init__(model=model) self.model = model grid = CanvasGrid(self.agent_portrayal, 50, 50, 500, 500) chart = ChartModule([{ "Label": "Emergence", "Color": "Black" }], data_collector_name='datacollector') server = ModularServer(ComplexClusteringModel, visualization_elements=[grid, chart], name="Ant Model", model_params={ "mid": model.middel, "num_ants": model.num_ants, "density_of_particels": model.density_of_particels, "step_size": model.step_size, "jumping_distance": model.jumping_distance, "perceptionRadius": model.perceptionRadius, "particleThreshhold": model.particleThreshhold, "kPlus": model.kPlus, "kMinus": model.kMinus }) server.port = 8525 # The default server.launch() pass
def main(): """ The main running function. :return: 0 on success """ ln_slider = UserSettableParameter('slider', "Number of L. Niger Agents", NUM_LNIGER, 0, 300, 1) fj_slider = UserSettableParameter('slider', "Number of F. Japonica Agents", NUM_FJAPON, 0, 300, 1) mk_slider = UserSettableParameter('slider', "Number of M. Kuricola Colonies", NUM_MK_COL, 0, 100, 1) ft_slider = UserSettableParameter('slider', "Number of F. Tropicalis Colonies", NUM_FT_COL, 0, 100, 1) # Instantiate the grid the agents will be moving on grid = CanvasGrid(agent_portrayal, GRID_WIDTH, GRID_HEIGHT, 500, 500) if VISUALIZE_MODEL: # Open the visualization server server = ModularServer( AntModel, [grid], "L. Niger Model", { "num_ln": ln_slider, "num_fj": fj_slider, "num_mk_col": mk_slider, "num_ft_col": ft_slider, "width": GRID_WIDTH, "height": GRID_HEIGHT }) server.port = 8521 server.launch() else: for j in range(NUM_SIMS): sim_time_sum = 0 print("Model Initialization #", str(j)) s = time() model = AntModel(NUM_LNIGER, NUM_FJAPON, NUM_MK_COL, NUM_FT_COL, GRID_WIDTH, GRID_HEIGHT) e = time() sim_time_sum += e - s print(e - s) for i in range(STEP_COUNT): if i % 10 == 0: print(j, "Step", i) s = time() model.step() e = time() sim_time_sum += e - s if i % 10 == 0: print(e - s) print("Model #", str(j), "complete. Total time", str(sim_time_sum)) df = model.data_collector.get_agent_vars_dataframe() df = df.dropna(axis=0) df.to_csv(path_or_buf="raw_new/out" + str(j) + ".csv") return 0
def get_server(play_guessing, random_behaviour, env_name): env_cls = get_env_cls(env_name) grid = CanvasGrid(agent_portrayal, env_cls.width, env_cls.height, 20 * env_cls.width, 20 * env_cls.height) server = ModularServer(CoopaModel, [grid], "Coopa Model", {"play_guessing": play_guessing, "random_behaviour": random_behaviour, "env_name": env_name}) return server
def reset_model(self, **kwargs): newEnvironment = kwargs.get("newEnvironment", "None") suppressLog = kwargs.get("suppressLog", False) # Copy previous model parameters model_params = {} for key, val in self.model_kwargs.items(): if isinstance(val, UserSettableParameter): if (val.param_type == "static_text" ): # static_text is never used for setting params continue model_params[key] = val.value else: model_params[key] = val # If new environment specified, use it if newEnvironment != "None": gridWidth = envList[newEnvironment]["gridWidth"] gridHeight = envList[newEnvironment]["gridHeight"] visualPlan = CanvasGrid(portrayal, gridWidth, gridHeight, gridWidth * CELL_SIZE, gridHeight * CELL_SIZE) self.visualization_elements = [visualPlan] model_params["envName"] = newEnvironment # If no new environment specified, check if there was previously selected environment else: try: newEnvironment = self.model.envName gridWidth = envList[newEnvironment]["gridWidth"] gridHeight = envList[newEnvironment]["gridHeight"] visualPlan = CanvasGrid(portrayal, gridWidth, gridHeight, gridWidth * CELL_SIZE, gridHeight * CELL_SIZE) self.visualization_elements = [visualPlan] model_params["envName"] = newEnvironment except: pass # Suppress logging of simulation setup if requested model_params["suppress"] = suppressLog # Restart the simulation self.model = self.model_cls(**model_params)
def dynamic_run(params: dict): if params['show_grid']: # visual grid on which agents move grid = CanvasGrid(agent_portrayal, params['grid_width'], params['grid_height'], 500, 500) visualization_elements.insert(0, grid) server = ModularServer(InfectionModel, visualization_elements, "Infection Model", {"params": params}) server.port = 8521 server.launch()
def launch_shape_model(): width = 15 height = 10 num_agents = 2 pixel_ratio = 50 grid = CanvasGrid(agent_draw, width, height, width * pixel_ratio, height * pixel_ratio) server = ModularServer(ShapesModel, [grid], "Shape Model Example", num_agents, width, height) server.max_steps = 0 server.port = 8521 server.launch()
def simulate_scenario(world, tsp_seqs, last_sim_step): model_params = { "world": world, "tsp_seqs": tsp_seqs, "last_sim_step": last_sim_step } task_element = TaskElement() canvas_element = CanvasGrid(warehouse_draw, world.width, world.height, 700, 420) server = ModularServer(Warehouse, [canvas_element, task_element], "MAPD simulation", model_params) server.launch()
def __init__(self, model): # super().__init__(model=model) grid = CanvasGrid(self.agent_portrayal, 50, 50, 500, 500) server = ModularServer(SimpleClusteringModel, visualization_elements=[grid], name="Ant Model", model_params={"mid": model.middel, "num_ants": model.num_ants, "density_of_particels": model.density_of_particels, "step_size": model.step_size, "jumping_distance": model.jumping_distance}) server.port = 8525 # The default server.launch() pass
def start_server(): grid = CanvasGrid( agent_portrayal, 30, # amount of horizontal cells 30, # amount of vertical cells 500, # canvas width 500) # canvas height chart_infections = ChartModule([{ "Label": "current infections", "Color": "Red" }, { "Label": "current cured", "Color": "Green" }], data_collector_name="data_collector") chart_total = ChartModule([{ "Label": "total infections", "Color": "Red" }, { "Label": "total deaths", "Color": "Black" }, { "Label": "total cured", "Color": "Green" }], data_collector_name="data_collector") chart_current = ChartModule([{ "Label": "new infections", "Color": "Red" }, { "Label": "current cured", "Color": "Green" }], data_collector_name="data_collector") chart_deaths = ChartModule([{ "Label": "total deaths", "Color": "Black" }], data_collector_name="data_collector") server = ModularServer( EpidemicModel, [grid, chart_current, chart_infections, chart_total, chart_deaths], "Epidemic simulation") server.launch(8521, True)
def viz_run(width, height, elev_cells, veg_cells, tracking_type): grid = CanvasGrid(agent_portrayal, width, height, 1200, 900) chart = ChartModule([{"Label": "Pack Health", "Color": "Black"}], canvas_height=200, canvas_width=500, data_collector_name='datacollector') chart2 = ChartModule([{"Label": "Pack Average Track Error", "Color": "Black"}], canvas_height=200, canvas_width=500, data_collector_name='datacollector') server = ModularServer(WolfModel, [grid, chart, chart2], "WolfSim", {"N": 25, "width": width, "height": height, "elev": elev_cells, "veg": veg_cells, "tracking_type": tracking_type}) server.port = 8520 # The defaul server.launch()
def main(x_size, y_size): """ This function sets up a canvas to graphically represent the model 'MoneyModel' and a chart, than it runs the server and runs the model in model.py in the browser """ grid = CanvasGrid(agent_portrayal, x_size, y_size, 500, 500) chart = ChartModule([{"Label": "Gini", "Color": "Black"}], data_collector_name='datacollector') # the simulation uses a class DataCollector, that collects the data and # relays it from self.datacollector to the webpage server = ModularServer(MoneyModel, [grid, chart], "abcEconomics and MESA integrated", {'num_agents': 1000, 'x_size': x_size, 'y_size': y_size}) server.port = 8534 # change this number if address is in use server.launch()
def create_vizualization_model(): """Creates the vizualization model""" # Creates grid to be displayed grid = CanvasGrid(agent_portrayal, 150, 1, 900, 100) # Values for vizualisation model_par_dict = { "car_count": UserSettableParameter("number", "Car count", 25), "width": 150, "acceleration": UserSettableParameter("number", "acceleration", 1), "vision_range": UserSettableParameter("number", "vision_range", 100), "speed_limit": UserSettableParameter("number", "max speed", 10), "randomization": UserSettableParameter("number", "randomization", 0.05) } server = ModularServer(CarModel, [grid], "Car Model", model_par_dict) return server
def launch_shape_model(): width = 50 height = 17 num_agents = 2 pixel_ratio = 10 grid = CanvasGrid(agent_draw, width, height, width * pixel_ratio, height * pixel_ratio) server = ModularServer(ShapesModel, [grid], "Shape Model Example", model_params={ 'N': num_agents, 'width': width, 'height': height }) server.max_steps = 0 server.port = 8888 server.launch()
def run_interactive_visualization(model, model_params, agent_portrayal, grid_width, grid_height, pixel_width=500, pixel_height=500, additional_modules=[], port=8531, title="SynBioSoc ABM"): grid = CanvasGrid(agent_portrayal, grid_width, grid_height, canvas_width=pixel_width, canvas_height=pixel_height) modules = [grid] modules.extend(additional_modules) server = ModularServer(model, modules, title, model_params) server.port = port server.launch()
def setUp(self): self.user_params = { "width": 1, "height": 1, "key1": UserSettableParameter("number", "Test Parameter", 101), "key2": UserSettableParameter("slider", "Test Parameter", 200, 0, 300, 10), } self.viz_elements = [ CanvasGrid(self.portrayal, 10, 10, 20, 20), TextElement(), # ChartModule([{"Label": "Wolves", "Color": "#AA0000"}, # Todo - test chart module # {"Label": "Sheep", "Color": "#666666"}]) ] self.server = ModularServer(MockModel, self.viz_elements, "Test Model", model_params=self.user_params)
return portrayal = { "Shape": "rect", "w": 1, "h": 1, "Filled": "true", "Layer": 0, "x": cell.x, "y": cell.y } portrayal["Color"] = COLORS[cell.state] return portrayal # Make a world that is 100x100, on a 500x500 display. canvas_element = CanvasGrid(portrayCell, 100, 100, 500, 500) cell_chart = ChartModule([{ "Label": "Infectious", "Color": 'Red' }, { "Label": "Removed", "Color": 'Blue' }], canvas_height=500, canvas_width=1000) model_params = { "height": 100, "width": 100,
'Color': ['#00FF00', '#99FF99))'], 'stroke_color': '#666666', 'Filled': 'ture', 'heading_x': agent.heading[0], 'heading_y': agent.heading[1], 'text': agent.unique_id, 'text_color': 'white', 'scale': 0.8, } return portrayal width = 15 height = 10 num_agents = 2 pixel_ratio = 50 grid = CanvasGrid(agent_draw, width, height, width * pixel_ratio, height * pixel_ratio) server = ModularServer( ShapeExample, [grid], 'Shape Model Example', { 'N': num_agents, 'width': width, 'height': height }, ) server.max_steps = 0 server.port = 8521
AGENT_REBEL_COLOR color = JAIL_COLOR if agent.jail_sentence else color portrayal["Color"] = color portrayal["r"] = 0.8 portrayal["Layer"] = 0 elif type(agent) is Cop: portrayal["Color"] = COP_COLOR portrayal["w"] = 0.5 portrayal["h"] = 0.5 portrayal["Layer"] = 1 portrayal["Shape"] = "rect" return portrayal canvas_element = CanvasGrid(citizen_cop_portrayal, 40, 40, 500, 500) active_chart = ChartModule([{ "Label": "Active", "Color": "Red" }, { "Label": "Jailed", "Color": "Black" }, { "Label": "Quiescent", "Color": "Orange" }], data_collector_name="dc") leg_slider = UserSettableParameter('slider', "legitimacy", 0.8, 0., 1., 0.001) cit_vis_slider = UserSettableParameter('slider', "Citizen vision", 3, 1, 10, 1) cop_vis_slider = UserSettableParameter('slider', "Cop vision", 2, 1, 10, 1) act_slider = UserSettableParameter('slider', "Active treshold", 0.1, 0., .5,
UserSettableParameter("slider", 'Categories', 1, 1, 10, description="Number of Movie Categories"), } # add ratings matrix here def viewer_portrayal(viewer): portrayal = { "Shape": "circle", "Filled": "true", "Layer": 0, "Color": "red", "r": 0.5 } return portrayal grid = CanvasGrid(viewer_portrayal, 10, model_params['N'], 500, 500) # create instance of ModularServer server = ModularServer( RatingModel, [grid], 'Movie Rating Model', model_params=model_params, )
if agent.immune: portrayal["Color"] = "green" portrayal["Layer"] = 0 else: portrayal["Color"] = "blue" portrayal["Layer"] = 0 if not agent.alive: portrayal["Color"] = "black" portrayal["Layer"] = 0 return portrayal grid = CanvasGrid(agent_portrayal, sim_params.get('grid_x'), sim_params.get('grid_y'), sim_params.get('grid_x') * 4, sim_params.get('grid_y') * 4) chart = ChartModule([{ "Label": "Infected", "Color": "Red" }, { "Label": "Immune", "Color": "Green" }, { "Label": "Deaths", "Color": "Black" }], data_collector_name='datacollector') server = ModularServer(Simulation, [grid, chart], "COVID-19 Model", {"params": sim_params}) server.port = 8521 # The default
portrayal = {'Shape': 'circle', 'Layer': 0, 'r': 1, 'Color': 'lightblue'} # (Un)masked agents show up as (non-)filled circles if agent.masked == True: portrayal['Filled'] = 'true' if agent.infected == True: portrayal['Color'] = 'red' if agent.immune == True: portrayal['Color'] = 'green' return portrayal grid = CanvasGrid(agent_portrayal, 50, 50, 500, 500) line_charts = ChartModule([{ 'Label': 'Susceptible', 'Color': 'lightblue' }, { 'Label': 'Infected', 'Color': 'red' }, { 'Label': 'Recovered & Immune', 'Color': 'green' }]) server = ModularServer(CovidModel, [grid, line_charts], 'COVID Simulation Model', model_params)
if type(agent) is Bean: portrayal["Color"] = "cornflowerblue" elif type(agent) is Corn: portrayal["Color"] = "blueviolet" elif type(agent) is Soy: portrayal["Color"] = "forestgreen" elif type(agent) is Bug: portrayal["Shape"] = "circle" portrayal["Color"] = "tomato" portrayal["r"] = 1 portrayal["Layer"] = 1 return portrayal bean = {"Label": "Bean", "Color": "cornflowerblue"} corn = {"Label": "Corn", "Color": "blueviolet"} soy = {"Label": "Soy", "Color": "forestgreen"} bug = {"Label": "Bug", "Color": "tomato"} canvas = CanvasGrid(food_portrayal, width, height) chart_count = ChartModule([bean, corn, soy, bug]) model_params = {"strategy": "stick"} server = ModularServer(Foraging, [canvas, chart_count], name="Foraging", model_params) server.launch()
portrayal["Layer"] = 1 portrayal["w"] = 1 portrayal["h"] = 1 elif type(agent) is CyanObstacle: portrayal["Color"] = ["#00FFFF"] portrayal["Shape"] = "rect" portrayal["Filled"] = "true" portrayal["Layer"] = 1 portrayal["w"] = 1 portrayal["h"] = 1 return portrayal canvas_element = CanvasGrid(walker_portrayal, 30, 30, 500, 500) chart_element = ChartModule([{ "Label": "Average Finished Cyan Walkers", "Color": "#00FFFF" }, { "Label": "Average Finished Red Walkers", "Color": "#AA0000" }]) model_params = { "initial_cyan_walkers": UserSettableParameter("slider", "Initial cyan walkers", 50, 1, 50), "initial_red_walkers": UserSettableParameter("slider", "Initial red walkers", 50, 1, 50), "cyan_noise": UserSettableParameter("slider", "Cyan walker noise", 0, 0, 100),
portrayal['Layer'] = 0 elif agent.status == 0: portrayal['Color'] = 'orange' portrayal['Layer'] = 1 elif agent.status == 3: portrayal['Color'] = 'green' portrayal['Layer'] = 2 else: portrayal['Color'] = 'grey' portrayal['Layer'] = 3 return portrayal # Creates a grid grid = CanvasGrid(agent_portrayal, WIDTH, HEIGHT, 1000, 1000) # Creates a chart using data collector data chart = ChartModule([{ "Label": "Infected", "Color": "red" }, { "Label": "Susceptible", "Color": "orange" }, { "Label": "Recovered", "Color": "green" }, { "Label": "Dead", "Color": "black" }],
''' if agent is None: return portrayal = {"Shape": "circle", "r": 0.5, "Filled": "true", "Layer": 0} if agent.type == 0: portrayal["Color"] = ["#FF0000", "#FF9999"] portrayal["stroke_color"] = "#00FF00" else: portrayal["Color"] = ["#0000FF", "#9999FF"] portrayal["stroke_color"] = "#000000" return portrayal happy_element = HappyElement() canvas_element = CanvasGrid(schelling_draw, 20, 20, 500, 500) happy_chart = ChartModule([{"Label": "happy", "Color": "Black"}]) model_params = { "height": 20, "width": 20, "density": UserSettableParameter("slider", "Agent density", 0.8, 0.1, 1.0, 0.1), "minority_pc": UserSettableParameter("slider", "Fraction minority", 0.2, 0.00, 1.0, 0.05), "homophily": UserSettableParameter("slider", "Homophily", 3, 0, 8, 1) }
20, description="Upper End of Random Initial Wallet Amount", ), "reserve_percent": UserSettableParameter( "slider", "Reserves", 50, 1, 100, description="Percent of deposits the bank has to hold in reserve", ), } # set the portrayal function and size of the canvas for visualization canvas_element = CanvasGrid(person_portrayal, 20, 20, 500, 500) # map data to chart in the ChartModule line_chart = ChartModule([ { "Label": "Rich", "Color": RICH_COLOR }, { "Label": "Poor", "Color": POOR_COLOR }, { "Label": "Middle Class", "Color": MID_COLOR },
elif type(agent) is disneyplus: portrayal["Shape"] = "market/resources/disneyplus.png" portrayal["scale"] = 0.9 portrayal["Layer"] = 2 portrayal["text_color"] = "White" # elif type(agent) is appletv: # portrayal["Shape"] = "market/resources/appletv.png" # portrayal["scale"] = 0.9 # portrayal["Layer"] = 2 # portrayal["text_color"] = "White" return portrayal canvas_element = CanvasGrid(corona_portrayal, 30, 30, 500, 500) chart_element = ChartModule([{ "Label": "amazonprime", "Color": "#0000FF" }, { "Label": "netflix", "Color": "#FF0000" }, { "Label": "disneyplus", "Color": "#00FF00" } #{"Label": "appletv", "Color": "#000000"} ]) model_params = { "quality_amazonprime":
portrayal["Color"] = "grey" portrayal["Layer"] = 0 elif agent.kind == "E": portrayal["Color"] = "blue" portrayal["Layer"] = 0 elif agent.kind == "I": portrayal["Color"] = "red" portrayal["Layer"] = 0 elif agent.kind == "R": portrayal["Color"] = "green" portrayal["Layer"] = 0 return portrayal canvas_element = CanvasGrid(agent_portrayal, 40, 40, 800, 800) if CALIB: chart = ChartModule([{"Label": "NumberOfneighbors", "Color": "#666666"}]) else: chart = ChartModule([{ "Label": 'NumberOfInfected', "Color": "#AA0000" }, { "Label": 'NumberOfSusceptible', "Color": " #AA5500" }, { "Label": 'NumberOfRecovered', "Color": "#00AA00" }, { "Label": 'NumberOfExposed', "Color": "#0000AA"