Exemplo n.º 1
0
def init_server(model_parameters):
    pydemic_canvas = SimpleCanvas(agent_draw, config.canvas_height,
                                  config.canvas_width)
    server = ModularServer(PyDemicModel, [pydemic_canvas],
                           name="PyDemic",
                           model_params=model_parameters)
    server.launch()
Exemplo n.º 2
0
def run(model, parameters, visual, back = False):
	"""
	Execute the simulation with visual representation.
		Args:
			parameters: Parameters associated with the simulation model and others such as grid size.
			model: Model that is simulated.
			visual: JS files with the visualization elements that are included in the JavaScript browser visualization template.
			back: Python file working as backend visualization.
	"""

	backEndVisualization = BackEndVisualization(int(parameters['width']), int(parameters['height']), 500, 500, visual)

	path = os.path.abspath(soba.__file__)
	path = path.rsplit('/', 1)[0]

	local_handler = (r'/local/(.*)', tornado.web.StaticFileHandler,
                     {"path": path})
	external_handler = (r'/external/(.*)', tornado.web.StaticFileHandler,
                     {"path": ""})

	ModularServer.handlers = ModularServer.handlers[:-1]
	ModularServer.handlers = ModularServer.handlers + [local_handler] + [external_handler]
	if back != False:
		server = ModularServer(model, [backEndVisualization, back], name="Simulation", model_params=parameters)
	else:
		server = ModularServer(model, [backEndVisualization], name="Simulation", model_params=parameters)

	server.port = 7777
	server.launch()
Exemplo n.º 3
0
def visualize(args):
    ppd = 8  #pixels per dimension
    width = 150
    height = 140
    countR = int(round(height * width / 25 *
                       3))  # avg 3 Rabits per each 5x5 cells square
    countF = int(round(height * width / 25 *
                       1))  # avg 1 Fox per each 5x5 cells square
    grid = MyCanvasGrid(rabit_portrayal, fox_portrayal, terain_portrayal,
                        width, height, width * ppd, height * ppd)

    FoxesNr = {"Label": "FoxesNr", "Color": "red"}
    RabitsNr = {"Label": "RabitsNr", "Color": "blue"}
    chart_count = ChartModule([FoxesNr, RabitsNr],
                              data_collector_name='datacollector')

    server = ModularServer(
        Field, [grid, chart_count], "Rabit VS Fox Model", {
            "width": width,
            "height": height,
            "num_rabits": countR,
            "num_foxes": countF,
            "mode": Mode.Visualization,
            "seed": 999
        })
    server.port = 8521  # The default
    server.launch()
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
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()
Exemplo n.º 6
0
    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
Exemplo n.º 7
0
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
Exemplo n.º 8
0
def launch_basic():
    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], "Basic Example", num_agents, width, height)
    server.max_steps = 0
    server.port = 8888
    server.launch()
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()
Exemplo n.º 10
0
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(ShapeExample, [grid], "Shape Model Example",
                           {"N": num_agents, "width": width, "height": height})
    server.max_steps = 0
    server.port = 8521
    server.launch()
Exemplo n.º 11
0
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()
Exemplo n.º 12
0
 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
Exemplo n.º 13
0
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 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)
Exemplo n.º 15
0
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()
Exemplo n.º 16
0
def main():
    network = NetworkModule(network_portrayal, 500, 500, library='d3')

    N = 10
    percInfect = 0.5
    percRecover = 0.25

    server = ModularServer(DiseaseModel, [network], "Disease Model", {
        "N": N,
        "percInfect": percInfect,
        "percRecover": percRecover
    })

    server.port = 8521  # The default
    server.launch()
Exemplo n.º 17
0
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()
Exemplo n.º 18
0
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",
                           x_size * y_size, x_size, y_size)
    server.port = 8534  # change this number if address is in use
    server.launch()
Exemplo n.º 19
0
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()
Exemplo n.º 20
0
def launch_server(
    config: ParsedConfig,
    rpcPort: str,
    chainId: int,
    simulationId: str,
    client: TokesimClient,
) -> None:

    model_spec = config.config_class_ref.get_spec(config.model_params)
    ethereum_config = EthereumModelConfig(
        config=config,
        model_spec=model_spec,
        rpcPort=rpcPort,
        chainId=chainId,
        simulationId=simulationId,
    )

    simulation_config = SimulationConfig(
        config=ethereum_config,
        width=100,
        height=100,
        simulationId=simulationId,
        client=client,
    )

    server = ModularServer(
        config.class_ref,
        config.dashboard_class_ref.get_elements(simulation_config),
        "Linear Bonded Token Model: Minority Majority Game",
        {
            "config": simulation_config.config,
            "width": simulation_config.width,
            "height": simulation_config.height,
            "simulationId": simulation_config.simulationId,
            "client": client,
        },
    )
    server.description = """
    This Example Token Contract models a linear token curve where the function mimiced directly tracks
    the token supply by a constant factor of 10000.  price = 10000 * x ; Where X = the total supply of tokens in the market.
    The agents are playing a mixed minority majority game. Where 40% follow the majority when known,
    and 60% follow the minority when known. These types of games have been used to simulate stock market pricing changes
    """

    server.launch()
Exemplo n.º 21
0
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()
Exemplo n.º 22
0
def run(configuration, seed=None):
    """
    Run the mesa server
    :param configuration: configuration used by the model.
    :param seed: random seed. By default None.
    """
    """
    to get results for multiple iterations, run underlying code and add this to default.json in configurations:  
    "inf_threshold": 50,
    "active_threshold_t": 0.5,
    "graph_type": "GraphType.ERDOS_RENYI.name" 
    """

    #batch_run = BatchRunner(CivilViolenceModel, fixed_parameters = config, iterations = 10)
    #batch_run.run_all()
    #data = batch_run.get_model_vars_dataframe()
    #data.head()

    random.seed(seed)

    model_params = get_user_model_parameters()

    # By updating model_params with configuration after getting the user settable parameters,
    # it let us provide fixed values for our model which won't be overwritten by the user choice.
    # Just remove attribute from the configuration file to get user interface back.
    model_params.update(
        configuration
    )  # Overwritten user parameters don't appear in the graphic interface
    model_params.update({'seed': seed})

    server = ModularServer(CivilViolenceModel,
                           get_visualization_elements(model_params,
                                                      show_network=False),
                           name="Civil violence with network model",
                           model_params=model_params)
    print(model_params)

    server.port = 8521
    server.launch()
    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)

server.port = 8521  # default port if unspecified
server.launch()
Exemplo n.º 24
0
    
    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()
Exemplo n.º 25
0
def run_visual():
    def network_portrayal(G):
        portrayal = dict()
        portrayal["nodes"] = []

        for n in G.nodes.data():
            portrayal["nodes"].append({
                "size": node_size_based_on_crowd(n),
                "color": n[1]["color"],
            })

        portrayal["edges"] = []
        for source, target in G.edges:
            portrayal["edges"].append({
                "source": source,
                "target": target,
                "color": "black",
                "width": 1,
            })

        return portrayal

    class Time(TextElement):
        def render(self, model):
            time = model.date
            return str(time)

    network = NetworkModule(network_portrayal, 800, 800, library="d3")
    chart = ChartModule([{
        "Label": "infected",
        "Color": "Green"
    }, {
        "Label": "healthy",
        "Color": "Red"
    }, {
        "Label": "recovered",
        "Color": "Blue"
    }],
                        data_collector_name='datacollector')
    model_params = {
        "p_nodes":
        UserSettableParameter("number", "prob nodes", value=0.04),
        "healthy_N":
        UserSettableParameter("slider", "amount healthy", 95, 1, 500),
        "sick_N":
        UserSettableParameter("slider", "amount sick", 5, 1, 500),
        "altruism":
        UserSettableParameter("slider", "altruism", 10, 1, 100),
        "infect_score_lower":
        UserSettableParameter("slider", "infect_score_lower", -40, -100, 100,
                              10),
        "infect_score_upper":
        UserSettableParameter("slider", "infect_score_upper", -20, -100, 100)
    }

    model_params["network_params"] = [
        (model_params["healthy_N"].value + model_params["sick_N"].value,
         "House", "Grey"), (15, "Work", "yellow"), (5, "School", "green"),
        (3, "Shop", "Brown"), (3, "Bar", "Brown"), (3, "Park", "Brown"),
        (1, "University", "Red")
    ]

    server = ModularServer(BaseModel, [network, Time(), chart],
                           "Infected model", model_params)
    server.port = 8521  # The default
    server.launch()
Exemplo n.º 26
0
}, {
    "Label": "Bin3",
    "Color": "Blue"
}, {
    "Label": "Bin4",
    "Color": "Blue"
}],
                                    scope="model")

model_params = {
    "memory_size":
    UserSettableParameter("slider", "Memory Size", memory_size, 1, 15, 1),
    "number_strategies":
    UserSettableParameter("slider", "Number of Strategies", number_strategies,
                          1, 20, 1),
    "number_persons":
    UserSettableParameter("slider", "Number of Persons", number_persons, 1,
                          200, 1),
    "overcrowding_threshold":
    UserSettableParameter("slider", "Overcrowding Threshold",
                          overcrowding_threshold, 1, 120, 1)
}

server = ModularServer(ElFarolModel, [
    crowded_element, grid, chart, reward_element, hist_agents_reward,
    hist_reward_agents
], "El Farol Model", model_params)

# porta 8521 é a porta default
server.launch(port=8579)
Exemplo n.º 27
0
def create_server(numb_agents,
                  width,
                  height,
                  expose,
                  recover,
                  rate,
                  prop_worker,
                  prop_student,
                  prop_retire,
                  hubs,
                  homes,
                  schools,
                  workplaces,
                  home_capacity,
                  school_capacity,
                  work_capacity,
                  entertain,
                  shops,
                  stationary_agents=[],
                  moving_agents=[],
                  preventative_toggle=False,
                  stage_threshold=[0.2, 0.5, 0.7],
                  vacc_rate=0.5,
                  export_results=False,
                  filename="log.csv",
                  port=0):
    #Colors={"Healthy":"#66cd00","Exposed":"#ffd700","Infected":"#b22222","Recovered":"#9932cc"}
    grid = CanvasGrid(agent_portrayal, width, height, 800, 500)
    chart_element = ChartModule([{
        "Label": label,
        "Color": color
    } for (label, color) in Colors.items()])

    server = ModularServer(
        Model,
        [grid, Legend(), chart_element],
        # [grid],
        "Disease Model",
        {
            "N": numb_agents,
            "width": width,
            "height": height,
            "expose": expose,
            "recover": recover,
            "rate": rate,
            "prop1": prop_worker,
            "prop2": prop_student,
            "prop3": prop_retire,
            "hubs": hubs,
            "homes": homes,
            "schools": schools,
            "workplaces": workplaces,
            "home_max": home_capacity,
            "school_max": school_capacity,
            "work_max": work_capacity,
            "entertain": entertain,
            "shops": shops,
            "infect_agent_station": stationary_agents,
            "infect_agent_move": moving_agents,
            "preventative_measures_active": preventative_toggle,
            "stage_thresholds": stage_threshold,
            "vacc_rate": vacc_rate,
            "export_results": export_results,
            "filename": str(filename) + ".csv"
        })
    server.port = port
    server.launch()
Exemplo n.º 28
0
wiggle_angle = 60
number_particles = 2500
probability_of_sticking = 1
neighbor_influence = False
num_seeds = 1
grid_size = round(2 * round(math.sqrt(number_particles)))

"700 é o tamanho do grid em pixels"
grid = CanvasGrid(agent_portrayal, grid_size, grid_size, 700, 700)

model_params = {
    "wiggle_angle":
    UserSettableParameter("slider", "Wiggle Angle", wiggle_angle, 0, 100, 1),
    "number_particles":
    UserSettableParameter("slider", "Number of Particles", number_particles, 1,
                          5000, 1),
    "probability_of_sticking":
    UserSettableParameter("slider", "Probability of Sticking Probability",
                          probability_of_sticking, 0, 1, 0.05),
    "neighbor_influence":
    UserSettableParameter("checkbox", "Neighbor Influence",
                          neighbor_influence),
    "num_seeds":
    UserSettableParameter("slider", "Number of Seeds", num_seeds, 1, 10, 1)
}

server = ModularServer(DLAModel, [grid], "DLA Model", model_params)

# porta 8521 é a porta default
server.launch(port=8505)
Exemplo n.º 29
0
CANVAS_WIDTH = GRID_COLS * CELL_SIZE


def color_patch_draw(cell):
    '''
    This function is registered with the visualization server to be called
    each tick to indicate how to draw the cell in its current state.

    :param cell:  the cell in the simulation

    :return: the portrayal dictionary.

    '''
    assert cell is not None
    portrayal = {"Shape": "rect", "w": 1, "h": 1, "Filled": "true", "Layer": 0}
    portrayal["x"] = cell.get_col()
    portrayal["y"] = cell.get_row()
    portrayal["Color"] = _COLORS[cell.get_state()]
    return portrayal


CANVAS_ELEMENT = CanvasGrid(color_patch_draw,
                            GRID_COLS, GRID_ROWS,
                            CANVAS_HEIGHT, CANVAS_WIDTH)

SERVER = ModularServer(ColorPatchModel,
                       [CANVAS_ELEMENT], "Color Patches",
                       GRID_ROWS, GRID_COLS)

SERVER.launch()
Exemplo n.º 30
0
    def render(self, model):
        return "Average similarity: " + str(model.similar)
    
class ResidenceElement(TextElement):
    def __init__(self):
        pass

    def render(self, model):
        return "Average residence length: " + str(model.avg_residence)
    
happy_element = HappyElement()
similar_element = SimilarElement()
residence_element = ResidenceElement()
grid = CanvasGrid(agent_portrayal, 50, 50, 400, 400)
happy_chart = ChartModule([{"Label": "Happy", "Color": "Black"}])
similar_chart = ChartModule([{"Label": "Similar", "Color": "Red"}])
residence_chart = ChartModule([{"Label": "Residence", "Color": "Blue"}])

'''
trad_server = ModularServer(TradModel,[grid,  similar_element, similar_chart, happy_element, happy_chart], "Traditional Model", {"width":50, "height":50, "num_agents":2125})
trad_server.verbose = False
trad_server.port = 8889
trad_server.launch()
'''

new_server = ModularServer(NewModel,[grid,  similar_element, similar_chart, happy_element, happy_chart, residence_element, residence_chart], "New Model", {"width":50, "height":50, "num_agents":2125})
new_server.verbose = False
new_server.port = 8889
new_server.launch()
Exemplo n.º 31
0
'''
kapital_households_chart = ChartModule([{
    "Label": "KapitalH",
    "Color": "Blue"
}],
                                       data_collector_name="datacollector")
rate_chart = ChartModule([{
    "Label": "Rate",
    "Color": "Black"
}],
                         data_collector_name="sinu_datacollector")

kapital_households_global_chart = ChartModule(
    [{
        "Label": "KapitalG",
        "Color": "Red"
    }],
    data_collector_name="datacollector")

server2 = ModularServer(
    SinuModel,
    [kapital_households_chart, kapital_households_global_chart, rate_chart],
    "SinuModel", {
        "n_households": 20,
        "df3": 'pfebtc.xlsx',
        "list_kapital_global": btc_model.kapital_global_btcModel
    })

server2.port = 8524  #The default
server2.launch()
Exemplo n.º 32
0
def launch(width, height, port=None):
    model_params = {
        'starting_settlements':
        UserSettableParameter('slider',
                              'starting_settlements',
                              value=14,
                              min_value=5,
                              max_value=20,
                              description='Initial Number of Settlements'),
        'starting_households':
        UserSettableParameter(
            'slider',
            'starting_households',
            value=7,
            min_value=1,
            max_value=10,
            description='Initial Number of Households per Settlement'),
        'starting_household_size':
        UserSettableParameter(
            'slider',
            'starting_household_size',
            value=5,
            min_value=1,
            max_value=10,
            description='Initial Number of Workers in each Household'),
        'starting_grain':
        UserSettableParameter(
            'slider',
            'starting_grain',
            value=3000,
            min_value=100,
            max_value=8000,
            description='Initial Grain Supply of Households'),
        'min_ambition':
        UserSettableParameter('slider',
                              'min_ambition',
                              value=0.1,
                              min_value=0.0,
                              max_value=1.0,
                              step=0.1,
                              description='Minimum Household Ambition'),
        'min_competency':
        UserSettableParameter('slider',
                              'min_competency',
                              value=0.5,
                              min_value=0.0,
                              max_value=1.0,
                              step=0.1,
                              description='Minimum Household Competency'),
        'generational_variation':
        UserSettableParameter(
            'slider',
            'generational_variation',
            value=0.9,
            min_value=0.0,
            max_value=1.0,
            step=0.1,
            description='Generational Variation in Ambition and Competency'),
        'knowledge_radius':
        UserSettableParameter('slider',
                              'knowledge_radius',
                              value=5,
                              min_value=5,
                              max_value=40,
                              description='Household Knowledge Radius'),
        'population_growth_rate':
        UserSettableParameter('slider',
                              'pop_growth_rate',
                              value=0.1,
                              min_value=0.0,
                              max_value=0.5,
                              step=0.01,
                              description='Population Growth Rate'),
        'distance_cost':
        UserSettableParameter('slider',
                              'distance_cost',
                              value=10,
                              min_value=1,
                              max_value=15,
                              step=1,
                              description='Distance Cost'),
        'allow_rental':
        UserSettableParameter('checkbox',
                              'allow_rental',
                              value=False,
                              description='Allow Land Rental'),
        'land_rental_rate':
        UserSettableParameter('slider',
                              'land_rental_rate',
                              value=0.5,
                              min_value=0.3,
                              max_value=0.6,
                              step=0.05,
                              description='Land Rental Rate'),
        'fallow_limit':
        UserSettableParameter('slider',
                              'fallow_limit',
                              value=4,
                              min_value=0,
                              max_value=10,
                              step=1,
                              description='Fallow Limit'),
        'annual_competency_increase':
        UserSettableParameter(
            'slider',
            'annual_competency_increase',
            value=0,
            min_value=0,
            max_value=10,
            step=0.25,
            description='Annual Competency Increase Percentage'),
        'w':
        width,
        'h':
        height
    }

    visualisation_elements = []

    # grid visualisation
    visualisation_elements.append(
        EgyptGrid(__agent_portrayal__, width, height, 500, 500))

    # datacollector graphs
    visualisation_elements.append(
        ChartModule([{
            'Label': 'Gini',
            'Color': 'Black'
        }],
                    data_collector_name='datacollector'))
    visualisation_elements.append(
        ChartModule([{
            'Label': 'Total Wealth',
            'Color': 'Black'
        }],
                    data_collector_name='datacollector'))
    visualisation_elements.append(
        ChartModule([{
            'Label': 'Mean Settlement Wealth',
            'Color': 'Black'
        }],
                    data_collector_name='datacollector'))
    visualisation_elements.append(
        ChartModule([{
            'Label': 'Total Population',
            'Color': 'Black'
        }],
                    data_collector_name='datacollector'))
    visualisation_elements.append(
        ChartModule([{
            'Label': 'Mean Settlement Population',
            'Color': 'Black'
        }],
                    data_collector_name='datacollector'))

    server = ModularServer(EgyptModel, visualisation_elements, 'Egypt Model',
                           model_params)

    server.launch(port)
Exemplo n.º 33
0
CELL_SIZE = 10
CANVAS_HEIGHT = GRID_ROWS * CELL_SIZE
CANVAS_WIDTH = GRID_COLS * CELL_SIZE


def color_patch_draw(cell):
    '''
    This function is registered with the visualization server to be called
    each tick to indicate how to draw the cell in its current state.

    :param cell:  the cell in the simulation

    :return: the portrayal dictionary.

    '''
    assert cell is not None
    portrayal = {"Shape": "rect", "w": 1, "h": 1, "Filled": "true", "Layer": 0}
    portrayal["x"] = cell.get_col()
    portrayal["y"] = cell.get_row()
    portrayal["Color"] = _COLORS[cell.get_state()]
    return portrayal


CANVAS_ELEMENT = CanvasGrid(color_patch_draw, GRID_COLS, GRID_ROWS,
                            CANVAS_HEIGHT, CANVAS_WIDTH)

SERVER = ModularServer(ColorPatchModel, [CANVAS_ELEMENT], "Color Patches",
                       GRID_ROWS, GRID_COLS)

SERVER.launch()
Exemplo n.º 34
0
def launch_city_model():
    city_map = []

    with open("city_map_21x21.txt", "r") as f:
        for line in f:
            l = []
            for cell in line.strip().split('\t'):
                l.append(cell)
            city_map.append(l)

    height = len(city_map)
    width = len(city_map[0])

    num_agents = 6
    pixel_ratio = 5

    city_roads, city_blocks, passenger_blocks, routes = getRoads(
        city_map, height, width)

    n_slider = UserSettableParameter('slider', "Number of Cabs", 5, 1, 10, 1)

    passenger_population = UserSettableParameter('slider',
                                                 "Passenger Population", .1, 0,
                                                 1, .05)

    passenger_pooling = UserSettableParameter('slider', "Passenger Pooling %",
                                              .5, 0, 1, .1)

    # grid = CanvasGrid(agent_draw, width, height,
    #   width * pixel_ratio, height * pixel_ratio)

    grid = CanvasGrid(agent_draw, width, height, 500, 500)

    chart_element = ChartModule([{
        "Label": "Normal Passenger",
        "Color": "#000000"
    }, {
        "Label": "Pooling Passenger",
        "Color": "#0033cc"
    }, {
        "Label": "Average",
        "Color": "#990000"
    }])

    chart_element_cars_carpooling = ChartModule([{
        "Label": "Cars carpooling",
        "Color": "#0033cc"
    }, {
        "Label": "Cars not carpooling",
        "Color": "#000000"
    }, {
        "Label": "Empty cars",
        "Color": "#ffff33"
    }])

    passengers_traveling = ChartModule([{
        "Label": "Passengers Travelling (not pooling)",
        "Color": "#000000"
    }, {
        "Label": "Passengers Travelling (pooling)",
        "Color": "#0033cc"
    }, {
        "Label": "Passengers Travelling",
        "Color": "#19ff00"
    }])

    over_travelled = ChartModule([{
        "Label": "Overtravelled (in percentage)",
        "Color": "#990000"
    }])

    server = ModularServer(
        CityModel, [
            grid, chart_element, chart_element_cars_carpooling,
            passengers_traveling, over_travelled
        ], "SOAS Project - Rafael Bianchi", {
            "N": n_slider,
            "PassengerPopulation": passenger_population,
            "PassengerPooling": passenger_pooling,
            "PassengerBlocks": passenger_blocks,
            "width": width,
            "height": height,
            "city_map": city_map,
            "roads": city_roads,
            "city_blocks": city_blocks,
            "routes": routes
        })
    server.max_steps = 0
    server.port = 8521
    server.launch()
Exemplo n.º 35
0
def run_model(
    input_file,
    output_file,
    n_processors,
    class_id=None,
    all_classes=True,
    webserver=False,
    model_params=None,
    test_mode=False,
    speedup=1,
):
    input_filepath = os.path.join(os.getcwd(), input_file)
    all_data = InputData(input_filepath)

    class_ids = all_data.get_class_ids()
    if webserver:
        if all_classes:
            click.echo("Cannot run over all classes in webserver mode (yet!)")
            sys.exit(2)
    else:
        if not all_classes:
            if class_id not in class_ids:
                click.echo(
                    f"Invalid class ID {class_id}. Valid classes are: {class_ids}"
                )
                sys.exit(1)
            if not webserver:
                class_ids = [class_id]

    output_data_writer = OutputDataWriter(output_file)

    # Get data first to determine grid size
    model_initial_state = ModelState(0, 0, 0, 0, 0)
    logging.info("Running on classes: %s",
                 ", ".join([str(i) for i in class_ids]))

    if not model_params:
        model_params = DEFAULT_MODEL_PARAMS

    if test_mode:
        model_params.maths_ticks_mean = 10
        model_params.maths_ticks_sd = 0.1
        model_params.ticks_per_home_day = 10

    # To ensure each thread in the BatchProcessor gets a different random
    # number generator, we use a seed sequence to generate a new seed for
    # each instance of SimModel (one per class), as they run on parallel
    # processors in batch mode, and we need to ensure they don't all produce
    # the same numbers

    # We use a non-reproducible seed sequence to ensure changes to parameters
    # are not masked by the random numbers generated
    ss = np.random.SeedSequence()

    # If we want the rngs to be reproducible in batch mode, we can use the
    # following to get a SeedSequence (see
    # https://albertcthomas.github.io/good-practices-random-number-generators/)
    # random_number_generator = np.random.default_rng(2021)
    # ss = random_number_generator.bit_generator._seed_seq

    # Create an rng for each class
    rngs = [np.random.default_rng(s) for s in ss.spawn(len(class_ids))]

    if webserver:
        canvas_grid = create_canvas_grid(14, 14)
        css_element = CssElement()
        pupil_element = PupilMonitorElement()
        class_element = ClassMonitorElement()
        max_speedup = round(model_params.maths_ticks_mean / 100) * 100

        summary_filepath = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            "classes_input",
            "sample_class_summaries.csv",
        )
        summary_data = None
        if os.path.isfile(summary_filepath):
            summary_data = pd.read_csv(summary_filepath)

        server = ModularServer(
            SimModel,
            [
                sim_element,
                class_element,
                pupil_element,
                canvas_grid,
                sim_chart,
                css_element,
            ],
            "SimulatED",
            {
                "all_data":
                all_data,
                "model_initial_state":
                model_initial_state,
                "output_data_writer":
                output_data_writer,
                "model_params":
                model_params,
                "summary_data":
                summary_data,
                "canvas_grid":
                canvas_grid,
                "instructions":
                UserSettableParameter(
                    "static_text",
                    value=
                    "<p>Classrooms in school are places when students learn and this model examines how this "
                    "learning in mathematics changes over a year. As time passes students can be attentive (green), "
                    "passive (yellow) or disruptive (red).</p>"
                    "<p>There are some variables related to the classroom which you can change in the model using the "
                    "option on the left. Then click Reset before setting it going. (Setting <em>Frames Per Second</em> "
                    "to 0 runs the model at maximum speed.)</p>"
                    "<p>Whilst the model runs you can watch individual students or the average score for the class."
                    "Try changing the value of the parameters to improve class learning.</p>",
                ),
                "class_id":
                UserSettableParameter("choice",
                                      "Class ID",
                                      value=class_ids[0],
                                      choices=class_ids),
                "teacher_quality_mean":
                UserSettableParameter(
                    "slider",
                    "Teaching quality mean",
                    model_params.teacher_quality_mean,
                    0,
                    5.0,
                    0.1,
                ),
                "teacher_control_mean":
                UserSettableParameter(
                    "slider",
                    "Teaching control mean",
                    model_params.teacher_control_mean,
                    0.00,
                    5.0,
                    0.1,
                ),
                "random_select":
                UserSettableParameter(
                    "slider",
                    "Mean for random number used at each step",
                    model_params.random_select,
                    0.00,
                    10.0,
                    0.1,
                ),
                "group_size":
                UserSettableParameter(
                    "slider",
                    "Size of each group of pupils",
                    model_params.group_size,
                    1,
                    40,
                    1,
                ),
                "group_by_ability":
                UserSettableParameter(
                    "checkbox",
                    "Group pupils by ability (rather than at random)",
                    model_params.group_by_ability,
                ),
                "speedup":
                UserSettableParameter(
                    "slider",
                    "How much to speed up (and approximate) the simulation",
                    1,
                    1,
                    max_speedup,
                ),
            },
        )

        port = int(os.getenv("PORT", 4200))
        server.launch(port=port, open_browser=False)

    else:
        print(f"BatchRunnerMP will use {n_processors} processors")
        batch_run = BatchRunnerMP(
            SimModel,
            variable_parameters={
                "class_id_and_rng": list(zip(class_ids, rngs)),
            },
            fixed_parameters={
                "all_data": all_data,
                "model_initial_state": model_initial_state,
                "output_data_writer": output_data_writer,
                "model_params": model_params,
                "speedup": speedup,
            },
            nr_processes=n_processors,
            iterations=1,
            max_steps=1000000,
        )

        batch_run.run_all()