projectmesa / mesa-viz-tornado

Apache License 2.0
2 stars 8 forks source link

Unable to add Histogram to the visualization! #13

Open PreetamKulkarni opened 1 year ago

PreetamKulkarni commented 1 year ago

I am trying the "MoneyModel" from the tutorial and it demonstrates how to add a "Histogram" to the visualization window. I followed the instructions and I get the following error:

module 'mesa.flat.visualization' has no attribute 'HistogramModule'

I made sure I saved the "HistogramModule.py" and "HistogramModule.js" in the same folder. It still gives me the same error.

rht commented 1 year ago

HistogramModule is a custom class defined in the tutorial, not imported from the mesa library. You should have done either a relative or absolute import from HistogramModule.py instead.

PreetamKulkarni commented 1 year ago

Thank you for the help. I fixed the code and it looks like this:

from money_model import * import mesa from mesa.visualization.ModularVisualization import VisualizationElement, CHART_JS_FILE import numpy as np

class HistogramModule(VisualizationElement): package_includes = [CHART_JS_FILE] local_includes = ["HistogramModule.js"]

def __init__(self, bins, canvas_height, canvas_width):
    self.canvas_height = canvas_height
    self.canvas_width = canvas_width
    self.bins = bins
    new_element = "new HistogramModule({}, {}, {})"
    new_element = new_element.format(bins,
                                     canvas_width,
                                     canvas_height)
    self.js_code = "elements.push(" + new_element + ");"

def render(self, model):
    wealth_vals = [agent.wealth for agent in model.schedule.agents]
    hist = np.histogram(wealth_vals, bins=self.bins)[0]
    return [int(x) for x in hist]

def agent_portrayal(agent): portrayal = {"Shape": "circle", "Filled": "true", "r": 0.5}

if agent.wealth > 0:
    portrayal["Color"] = "red"
    portrayal["Layer"] = 0
else:
    portrayal["Color"] = "grey"
    portrayal["Layer"] = 1
    portrayal["r"] = 0.2
return portrayal

grid = mesa.visualization.CanvasGrid(agent_portrayal, 10, 10, 500, 500)

chart = mesa.visualization.ChartModule([{"Label": "Gini", "Color": "Black"}], data_collector_name='datacollector')

histogram = HistogramModule(list(range(10)), 200, 500)

server = mesa.visualization.ModularServer(MoneyModel, [grid, histogram, chart], "Money Model", {"N":100, "width":10, "height":10})

server.port = 8521 # The default server.launch()

However, I get the following error: RuntimeError: This event loop is already running I do see the histogram on the visualization window but it doesn't update. When I press start, it doesn't advance. When I use step, it does advance but in either case, the chart and the histogram don't update.

I used the following fix on HistogramModule.js as well but it doesn't solve the problem: https://github.com/projectmesa/mesa/issues/609