We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
When server is launched, browser window should open automagically 
When guest lecturing at GMU, I observed that users did not read the instructions to visit 127.0.0.1... in their browser. I think jupyter spoiled them ;-). We should add functionality to have the browser auto launch when someone kicks off a model.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mesa/visualization/ModularVisualization.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """
3 ModularServer
4 =============
5 
6 A visualization server which renders a model via one or more elements.
7 
8 The concept for the modular visualization server as follows:
9 A visualization is composed of VisualizationElements, each of which defines how
10 to generate some visualization from a model instance and render it on the
11 client. VisualizationElements may be anything from a simple text display to
12 a multilayered HTML5 canvas.
13 
14 The actual server is launched with one or more VisualizationElements;
15 it runs the model object through each of them, generating data to be sent to
16 the client. The client page is also generated based on the JavaScript code
17 provided by each element.
18 
19 This file consists of the following classes:
20 
21 VisualizationElement: Parent class for all other visualization elements, with
22                       the minimal necessary options.
23 PageHandler: The handler for the visualization page, generated from a template
24              and built from the various visualization elements.
25 SocketHandler: Handles the websocket connection between the client page and
26                 the server.
27 ModularServer: The overall visualization application class which stores and
28                controls the model and visualization instance.
29 
30 
31 ModularServer should *not* need to be subclassed on a model-by-model basis; it
32 should be primarily a pass-through for VisualizationElement subclasses, which
33 define the actual visualization specifics.
34 
35 For example, suppose we have created two visualization elements for our model,
36 called canvasvis and graphvis; we would launch a server with:
37 
38     server = ModularServer(MyModel, [canvasvis, graphvis], name="My Model")
39     server.launch()
40 
41 The client keeps track of what step it is showing. Clicking the Step button in
42 the browser sends a message requesting the viz_state corresponding to the next
43 step position, which is then sent back to the client via the websocket.
44 
45 The websocket protocol is as follows:
46 Each message is a JSON object, with a "type" property which defines the rest of
47 the structure.
48 
49 Server -> Client:
50     Send over the model state to visualize.
51     Model state is a list, with each element corresponding to a div; each div
52     is expected to have a render function associated with it, which knows how
53     to render that particular data. The example below includes two elements:
54     the first is data for a CanvasGrid, the second for a raw text display.
55 
56     {
57     "type": "viz_state",
58     "data": [{0:[ {"Shape": "circle", "x": 0, "y": 0, "r": 0.5,
59                 "Color": "#AAAAAA", "Filled": "true", "Layer": 0,
60                 "text": 'A', "text_color": "white" }]},
61             "Shape Count: 1"]
62     }
63 
64     Informs the client that the model is over.
65     {"type": "end"}
66 
67 Client -> Server:
68     Reset the model.
69     TODO: Allow this to come with parameters
70     {
71     "type": "reset"
72     }
73 
74     Get a given state.
75     {
76     "type": "get_step",
77     "step:" index of the step to get.
78     }
79 
80 """
81 import os
82 
83 import tornado.ioloop
84 import tornado.template
85 import tornado.web
86 import tornado.websocket
87 import tornado.escape
88 import tornado.gen
89 
90 # Suppress several pylint warnings for this file.
91 # Attributes being defined outside of init is a Tornado feature.
92 # pylint: disable=attribute-defined-outside-init
93 
94 
95 class VisualizationElement:
96     """
97     Defines an element of the visualization.
98 
99     Attributes:
100         package_includes: A list of external JavaScript files to include that
101                           are part of the Mesa packages.
102         local_includes: A list of JavaScript files that are local to the
103                         directory that the server is being run in.
104         js_code: A JavaScript code string to instantiate the element.
105 
106     Methods:
107         render: Takes a model object, and produces JSON data which can be sent
108                 to the client.
109 
110     """
111 
112     package_includes = []
113     local_includes = []
114     js_code = ''
115     render_args = {}
116 
117     def __init__(self):
118         pass
119 
120     def render(self, model):
121         """ Build visualization data from a model object.
122 
123         Args:
124             model: A model object
125 
126         Returns:
127             A JSON-ready object.
128 
129         """
130         return "<b>VisualizationElement goes here</b>."
131 
132 # =============================================================================
133 # Actual Tornado code starts here:
134 
135 
136 class PageHandler(tornado.web.RequestHandler):
137     """ Handler for the HTML template which holds the visualization. """
138 
139     def get(self):
140         elements = self.application.visualization_elements
141         for i, element in enumerate(elements):
142             element.index = i
143         self.render("modular_template.html", port=self.application.port,
144                     model_name=self.application.model_name,
145                     package_includes=self.application.package_includes,
146                     local_includes=self.application.local_includes,
147                     scripts=self.application.js_code)
148 
149 
150 class SocketHandler(tornado.websocket.WebSocketHandler):
151     """ Handler for websocket. """
152     def open(self):
153         if self.application.verbose:
154             print("Socket opened!")
155 
156     def check_origin(self, origin):
157         return True
158 
159     def on_message(self, message):
160         """ Receiving a message from the websocket, parse, and act accordingly.
161 
162         """
163         if self.application.verbose:
164             print(message)
165         msg = tornado.escape.json_decode(message)
166 
167         if msg["type"] == "get_step":
168             self.application.model.step()
169             self.write_message({"type": "viz_state",
170                     "data": self.application.render_model()})
171 
172         elif msg["type"] == "reset":
173             self.application.reset_model()
174             self.write_message({"type": "viz_state",
175                     "data": self.application.render_model()})
176 
177         else:
178             if self.application.verbose:
179                 print("Unexpected message!")
180 
181 
182 class ModularServer(tornado.web.Application):
183     """ Main visualization application. """
184     verbose = True
185 
186     model_name = "Mesa Model"
187     model_cls = None  # A model class
188     portrayal_method = None
189     port = 8888  # Default port to listen on
190     canvas_width = 500
191     canvas_height = 500
192     grid_height = 0
193     grid_width = 0
194 
195     max_steps = 100000
196 
197     model_args = ()
198     model_kwargs = {}
199 
200     # Handlers and other globals:
201     page_handler = (r'/', PageHandler)
202     socket_handler = (r'/ws', SocketHandler)
203     static_handler = (r'/static/(.*)', tornado.web.StaticFileHandler,
204                       {"path": os.path.dirname(__file__) + "/templates"})
205     local_handler = (r'/local/(.*)', tornado.web.StaticFileHandler,
206                      {"path": ''})
207 
208     handlers = [page_handler, socket_handler, static_handler, local_handler]
209 
210     settings = {"debug": True,
211                 "template_path": os.path.dirname(__file__) + "/templates"}
212 
213     def __init__(self, model_cls, visualization_elements, name="Mesa Model",
214                  *args, **kwargs):
215         """ Create a new visualization server with the given elements. """
216         # Prep visualization elements:
217         self.visualization_elements = visualization_elements
218         self.package_includes = set()
219         self.local_includes = set()
220         self.js_code = []
221         for element in self.visualization_elements:
222             for include_file in element.package_includes:
223                 self.package_includes.add(include_file)
224             for include_file in element.local_includes:
225                 self.local_includes.add(include_file)
226             self.js_code.append(element.js_code)
227 
228         # Initializing the model
229         self.model_name = name
230         self.model_cls = model_cls
231 
232         self.model_args = args
233         self.model_kwargs = kwargs
234         self.reset_model()
235 
236         # Initializing the application itself:
237         super().__init__(self.handlers, **self.settings)
238 
239     def reset_model(self):
240         """ Reinstantiate the model object, using the current parameters. """
241         self.model = self.model_cls(*self.model_args, **self.model_kwargs)
242 
243     def render_model(self):
244         """ Turn the current state of the model into a dictionary of
245         visualizations
246 
247         """
248         visualization_state = []
249         for element in self.visualization_elements:
250             element_state = element.render(self.model)
251             visualization_state.append(element_state)
252         return visualization_state
253 
254     def launch(self, port=None):
255         """ Run the app. """
256         if port is not None:
257             self.port = port
258         print('Interface starting at http://127.0.0.1:{PORT}'.format(PORT=self.port))
259         self.listen(self.port)
260         tornado.ioloop.IOLoop.instance().start()
261
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mesa/visualization/ModularVisualization.py b/mesa/visualization/ModularVisualization.py
--- a/mesa/visualization/ModularVisualization.py
+++ b/mesa/visualization/ModularVisualization.py
@@ -81,12 +81,13 @@
 import os
 
 import tornado.ioloop
-import tornado.template
 import tornado.web
 import tornado.websocket
 import tornado.escape
 import tornado.gen
 
+import webbrowser
+
 # Suppress several pylint warnings for this file.
 # Attributes being defined outside of init is a Tornado feature.
 # pylint: disable=attribute-defined-outside-init
@@ -255,6 +256,8 @@
         """ Run the app. """
         if port is not None:
             self.port = port
-        print('Interface starting at http://127.0.0.1:{PORT}'.format(PORT=self.port))
+        url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)
+        print('Interface starting at {url}'.format(url=url))
         self.listen(self.port)
+        webbrowser.open(url)
         tornado.ioloop.IOLoop.instance().start()

{"golden_diff": "diff --git a/mesa/visualization/ModularVisualization.py b/mesa/visualization/ModularVisualization.py\n--- a/mesa/visualization/ModularVisualization.py\n+++ b/mesa/visualization/ModularVisualization.py\n@@ -81,12 +81,13 @@\n import os\n \n import tornado.ioloop\n-import tornado.template\n import tornado.web\n import tornado.websocket\n import tornado.escape\n import tornado.gen\n \n+import webbrowser\n+\n # Suppress several pylint warnings for this file.\n # Attributes being defined outside of init is a Tornado feature.\n # pylint: disable=attribute-defined-outside-init\n@@ -255,6 +256,8 @@\n         \"\"\" Run the app. \"\"\"\n         if port is not None:\n             self.port = port\n-        print('Interface starting at http://127.0.0.1:{PORT}'.format(PORT=self.port))\n+        url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)\n+        print('Interface starting at {url}'.format(url=url))\n         self.listen(self.port)\n+        webbrowser.open(url)\n         tornado.ioloop.IOLoop.instance().start()\n", "issue": "When server is launched, browser window should open automagically \nWhen guest lecturing at GMU, I observed that users did not read the instructions to visit 127.0.0.1... in their browser. I think jupyter spoiled them ;-). We should add functionality to have the browser auto launch when someone kicks off a model.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"\nModularServer\n=============\n\nA visualization server which renders a model via one or more elements.\n\nThe concept for the modular visualization server as follows:\nA visualization is composed of VisualizationElements, each of which defines how\nto generate some visualization from a model instance and render it on the\nclient. VisualizationElements may be anything from a simple text display to\na multilayered HTML5 canvas.\n\nThe actual server is launched with one or more VisualizationElements;\nit runs the model object through each of them, generating data to be sent to\nthe client. The client page is also generated based on the JavaScript code\nprovided by each element.\n\nThis file consists of the following classes:\n\nVisualizationElement: Parent class for all other visualization elements, with\n                      the minimal necessary options.\nPageHandler: The handler for the visualization page, generated from a template\n             and built from the various visualization elements.\nSocketHandler: Handles the websocket connection between the client page and\n                the server.\nModularServer: The overall visualization application class which stores and\n               controls the model and visualization instance.\n\n\nModularServer should *not* need to be subclassed on a model-by-model basis; it\nshould be primarily a pass-through for VisualizationElement subclasses, which\ndefine the actual visualization specifics.\n\nFor example, suppose we have created two visualization elements for our model,\ncalled canvasvis and graphvis; we would launch a server with:\n\n    server = ModularServer(MyModel, [canvasvis, graphvis], name=\"My Model\")\n    server.launch()\n\nThe client keeps track of what step it is showing. Clicking the Step button in\nthe browser sends a message requesting the viz_state corresponding to the next\nstep position, which is then sent back to the client via the websocket.\n\nThe websocket protocol is as follows:\nEach message is a JSON object, with a \"type\" property which defines the rest of\nthe structure.\n\nServer -> Client:\n    Send over the model state to visualize.\n    Model state is a list, with each element corresponding to a div; each div\n    is expected to have a render function associated with it, which knows how\n    to render that particular data. The example below includes two elements:\n    the first is data for a CanvasGrid, the second for a raw text display.\n\n    {\n    \"type\": \"viz_state\",\n    \"data\": [{0:[ {\"Shape\": \"circle\", \"x\": 0, \"y\": 0, \"r\": 0.5,\n                \"Color\": \"#AAAAAA\", \"Filled\": \"true\", \"Layer\": 0,\n                \"text\": 'A', \"text_color\": \"white\" }]},\n            \"Shape Count: 1\"]\n    }\n\n    Informs the client that the model is over.\n    {\"type\": \"end\"}\n\nClient -> Server:\n    Reset the model.\n    TODO: Allow this to come with parameters\n    {\n    \"type\": \"reset\"\n    }\n\n    Get a given state.\n    {\n    \"type\": \"get_step\",\n    \"step:\" index of the step to get.\n    }\n\n\"\"\"\nimport os\n\nimport tornado.ioloop\nimport tornado.template\nimport tornado.web\nimport tornado.websocket\nimport tornado.escape\nimport tornado.gen\n\n# Suppress several pylint warnings for this file.\n# Attributes being defined outside of init is a Tornado feature.\n# pylint: disable=attribute-defined-outside-init\n\n\nclass VisualizationElement:\n    \"\"\"\n    Defines an element of the visualization.\n\n    Attributes:\n        package_includes: A list of external JavaScript files to include that\n                          are part of the Mesa packages.\n        local_includes: A list of JavaScript files that are local to the\n                        directory that the server is being run in.\n        js_code: A JavaScript code string to instantiate the element.\n\n    Methods:\n        render: Takes a model object, and produces JSON data which can be sent\n                to the client.\n\n    \"\"\"\n\n    package_includes = []\n    local_includes = []\n    js_code = ''\n    render_args = {}\n\n    def __init__(self):\n        pass\n\n    def render(self, model):\n        \"\"\" Build visualization data from a model object.\n\n        Args:\n            model: A model object\n\n        Returns:\n            A JSON-ready object.\n\n        \"\"\"\n        return \"<b>VisualizationElement goes here</b>.\"\n\n# =============================================================================\n# Actual Tornado code starts here:\n\n\nclass PageHandler(tornado.web.RequestHandler):\n    \"\"\" Handler for the HTML template which holds the visualization. \"\"\"\n\n    def get(self):\n        elements = self.application.visualization_elements\n        for i, element in enumerate(elements):\n            element.index = i\n        self.render(\"modular_template.html\", port=self.application.port,\n                    model_name=self.application.model_name,\n                    package_includes=self.application.package_includes,\n                    local_includes=self.application.local_includes,\n                    scripts=self.application.js_code)\n\n\nclass SocketHandler(tornado.websocket.WebSocketHandler):\n    \"\"\" Handler for websocket. \"\"\"\n    def open(self):\n        if self.application.verbose:\n            print(\"Socket opened!\")\n\n    def check_origin(self, origin):\n        return True\n\n    def on_message(self, message):\n        \"\"\" Receiving a message from the websocket, parse, and act accordingly.\n\n        \"\"\"\n        if self.application.verbose:\n            print(message)\n        msg = tornado.escape.json_decode(message)\n\n        if msg[\"type\"] == \"get_step\":\n            self.application.model.step()\n            self.write_message({\"type\": \"viz_state\",\n                    \"data\": self.application.render_model()})\n\n        elif msg[\"type\"] == \"reset\":\n            self.application.reset_model()\n            self.write_message({\"type\": \"viz_state\",\n                    \"data\": self.application.render_model()})\n\n        else:\n            if self.application.verbose:\n                print(\"Unexpected message!\")\n\n\nclass ModularServer(tornado.web.Application):\n    \"\"\" Main visualization application. \"\"\"\n    verbose = True\n\n    model_name = \"Mesa Model\"\n    model_cls = None  # A model class\n    portrayal_method = None\n    port = 8888  # Default port to listen on\n    canvas_width = 500\n    canvas_height = 500\n    grid_height = 0\n    grid_width = 0\n\n    max_steps = 100000\n\n    model_args = ()\n    model_kwargs = {}\n\n    # Handlers and other globals:\n    page_handler = (r'/', PageHandler)\n    socket_handler = (r'/ws', SocketHandler)\n    static_handler = (r'/static/(.*)', tornado.web.StaticFileHandler,\n                      {\"path\": os.path.dirname(__file__) + \"/templates\"})\n    local_handler = (r'/local/(.*)', tornado.web.StaticFileHandler,\n                     {\"path\": ''})\n\n    handlers = [page_handler, socket_handler, static_handler, local_handler]\n\n    settings = {\"debug\": True,\n                \"template_path\": os.path.dirname(__file__) + \"/templates\"}\n\n    def __init__(self, model_cls, visualization_elements, name=\"Mesa Model\",\n                 *args, **kwargs):\n        \"\"\" Create a new visualization server with the given elements. \"\"\"\n        # Prep visualization elements:\n        self.visualization_elements = visualization_elements\n        self.package_includes = set()\n        self.local_includes = set()\n        self.js_code = []\n        for element in self.visualization_elements:\n            for include_file in element.package_includes:\n                self.package_includes.add(include_file)\n            for include_file in element.local_includes:\n                self.local_includes.add(include_file)\n            self.js_code.append(element.js_code)\n\n        # Initializing the model\n        self.model_name = name\n        self.model_cls = model_cls\n\n        self.model_args = args\n        self.model_kwargs = kwargs\n        self.reset_model()\n\n        # Initializing the application itself:\n        super().__init__(self.handlers, **self.settings)\n\n    def reset_model(self):\n        \"\"\" Reinstantiate the model object, using the current parameters. \"\"\"\n        self.model = self.model_cls(*self.model_args, **self.model_kwargs)\n\n    def render_model(self):\n        \"\"\" Turn the current state of the model into a dictionary of\n        visualizations\n\n        \"\"\"\n        visualization_state = []\n        for element in self.visualization_elements:\n            element_state = element.render(self.model)\n            visualization_state.append(element_state)\n        return visualization_state\n\n    def launch(self, port=None):\n        \"\"\" Run the app. \"\"\"\n        if port is not None:\n            self.port = port\n        print('Interface starting at http://127.0.0.1:{PORT}'.format(PORT=self.port))\n        self.listen(self.port)\n        tornado.ioloop.IOLoop.instance().start()\n", "path": "mesa/visualization/ModularVisualization.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"\nModularServer\n=============\n\nA visualization server which renders a model via one or more elements.\n\nThe concept for the modular visualization server as follows:\nA visualization is composed of VisualizationElements, each of which defines how\nto generate some visualization from a model instance and render it on the\nclient. VisualizationElements may be anything from a simple text display to\na multilayered HTML5 canvas.\n\nThe actual server is launched with one or more VisualizationElements;\nit runs the model object through each of them, generating data to be sent to\nthe client. The client page is also generated based on the JavaScript code\nprovided by each element.\n\nThis file consists of the following classes:\n\nVisualizationElement: Parent class for all other visualization elements, with\n                      the minimal necessary options.\nPageHandler: The handler for the visualization page, generated from a template\n             and built from the various visualization elements.\nSocketHandler: Handles the websocket connection between the client page and\n                the server.\nModularServer: The overall visualization application class which stores and\n               controls the model and visualization instance.\n\n\nModularServer should *not* need to be subclassed on a model-by-model basis; it\nshould be primarily a pass-through for VisualizationElement subclasses, which\ndefine the actual visualization specifics.\n\nFor example, suppose we have created two visualization elements for our model,\ncalled canvasvis and graphvis; we would launch a server with:\n\n    server = ModularServer(MyModel, [canvasvis, graphvis], name=\"My Model\")\n    server.launch()\n\nThe client keeps track of what step it is showing. Clicking the Step button in\nthe browser sends a message requesting the viz_state corresponding to the next\nstep position, which is then sent back to the client via the websocket.\n\nThe websocket protocol is as follows:\nEach message is a JSON object, with a \"type\" property which defines the rest of\nthe structure.\n\nServer -> Client:\n    Send over the model state to visualize.\n    Model state is a list, with each element corresponding to a div; each div\n    is expected to have a render function associated with it, which knows how\n    to render that particular data. The example below includes two elements:\n    the first is data for a CanvasGrid, the second for a raw text display.\n\n    {\n    \"type\": \"viz_state\",\n    \"data\": [{0:[ {\"Shape\": \"circle\", \"x\": 0, \"y\": 0, \"r\": 0.5,\n                \"Color\": \"#AAAAAA\", \"Filled\": \"true\", \"Layer\": 0,\n                \"text\": 'A', \"text_color\": \"white\" }]},\n            \"Shape Count: 1\"]\n    }\n\n    Informs the client that the model is over.\n    {\"type\": \"end\"}\n\nClient -> Server:\n    Reset the model.\n    TODO: Allow this to come with parameters\n    {\n    \"type\": \"reset\"\n    }\n\n    Get a given state.\n    {\n    \"type\": \"get_step\",\n    \"step:\" index of the step to get.\n    }\n\n\"\"\"\nimport os\n\nimport tornado.ioloop\nimport tornado.web\nimport tornado.websocket\nimport tornado.escape\nimport tornado.gen\n\nimport webbrowser\n\n# Suppress several pylint warnings for this file.\n# Attributes being defined outside of init is a Tornado feature.\n# pylint: disable=attribute-defined-outside-init\n\n\nclass VisualizationElement:\n    \"\"\"\n    Defines an element of the visualization.\n\n    Attributes:\n        package_includes: A list of external JavaScript files to include that\n                          are part of the Mesa packages.\n        local_includes: A list of JavaScript files that are local to the\n                        directory that the server is being run in.\n        js_code: A JavaScript code string to instantiate the element.\n\n    Methods:\n        render: Takes a model object, and produces JSON data which can be sent\n                to the client.\n\n    \"\"\"\n\n    package_includes = []\n    local_includes = []\n    js_code = ''\n    render_args = {}\n\n    def __init__(self):\n        pass\n\n    def render(self, model):\n        \"\"\" Build visualization data from a model object.\n\n        Args:\n            model: A model object\n\n        Returns:\n            A JSON-ready object.\n\n        \"\"\"\n        return \"<b>VisualizationElement goes here</b>.\"\n\n# =============================================================================\n# Actual Tornado code starts here:\n\n\nclass PageHandler(tornado.web.RequestHandler):\n    \"\"\" Handler for the HTML template which holds the visualization. \"\"\"\n\n    def get(self):\n        elements = self.application.visualization_elements\n        for i, element in enumerate(elements):\n            element.index = i\n        self.render(\"modular_template.html\", port=self.application.port,\n                    model_name=self.application.model_name,\n                    package_includes=self.application.package_includes,\n                    local_includes=self.application.local_includes,\n                    scripts=self.application.js_code)\n\n\nclass SocketHandler(tornado.websocket.WebSocketHandler):\n    \"\"\" Handler for websocket. \"\"\"\n    def open(self):\n        if self.application.verbose:\n            print(\"Socket opened!\")\n\n    def check_origin(self, origin):\n        return True\n\n    def on_message(self, message):\n        \"\"\" Receiving a message from the websocket, parse, and act accordingly.\n\n        \"\"\"\n        if self.application.verbose:\n            print(message)\n        msg = tornado.escape.json_decode(message)\n\n        if msg[\"type\"] == \"get_step\":\n            self.application.model.step()\n            self.write_message({\"type\": \"viz_state\",\n                    \"data\": self.application.render_model()})\n\n        elif msg[\"type\"] == \"reset\":\n            self.application.reset_model()\n            self.write_message({\"type\": \"viz_state\",\n                    \"data\": self.application.render_model()})\n\n        else:\n            if self.application.verbose:\n                print(\"Unexpected message!\")\n\n\nclass ModularServer(tornado.web.Application):\n    \"\"\" Main visualization application. \"\"\"\n    verbose = True\n\n    model_name = \"Mesa Model\"\n    model_cls = None  # A model class\n    portrayal_method = None\n    port = 8888  # Default port to listen on\n    canvas_width = 500\n    canvas_height = 500\n    grid_height = 0\n    grid_width = 0\n\n    max_steps = 100000\n\n    model_args = ()\n    model_kwargs = {}\n\n    # Handlers and other globals:\n    page_handler = (r'/', PageHandler)\n    socket_handler = (r'/ws', SocketHandler)\n    static_handler = (r'/static/(.*)', tornado.web.StaticFileHandler,\n                      {\"path\": os.path.dirname(__file__) + \"/templates\"})\n    local_handler = (r'/local/(.*)', tornado.web.StaticFileHandler,\n                     {\"path\": ''})\n\n    handlers = [page_handler, socket_handler, static_handler, local_handler]\n\n    settings = {\"debug\": True,\n                \"template_path\": os.path.dirname(__file__) + \"/templates\"}\n\n    def __init__(self, model_cls, visualization_elements, name=\"Mesa Model\",\n                 *args, **kwargs):\n        \"\"\" Create a new visualization server with the given elements. \"\"\"\n        # Prep visualization elements:\n        self.visualization_elements = visualization_elements\n        self.package_includes = set()\n        self.local_includes = set()\n        self.js_code = []\n        for element in self.visualization_elements:\n            for include_file in element.package_includes:\n                self.package_includes.add(include_file)\n            for include_file in element.local_includes:\n                self.local_includes.add(include_file)\n            self.js_code.append(element.js_code)\n\n        # Initializing the model\n        self.model_name = name\n        self.model_cls = model_cls\n\n        self.model_args = args\n        self.model_kwargs = kwargs\n        self.reset_model()\n\n        # Initializing the application itself:\n        super().__init__(self.handlers, **self.settings)\n\n    def reset_model(self):\n        \"\"\" Reinstantiate the model object, using the current parameters. \"\"\"\n        self.model = self.model_cls(*self.model_args, **self.model_kwargs)\n\n    def render_model(self):\n        \"\"\" Turn the current state of the model into a dictionary of\n        visualizations\n\n        \"\"\"\n        visualization_state = []\n        for element in self.visualization_elements:\n            element_state = element.render(self.model)\n            visualization_state.append(element_state)\n        return visualization_state\n\n    def launch(self, port=None):\n        \"\"\" Run the app. \"\"\"\n        if port is not None:\n            self.port = port\n        url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)\n        print('Interface starting at {url}'.format(url=url))\n        self.listen(self.port)\n        webbrowser.open(url)\n        tornado.ioloop.IOLoop.instance().start()\n", "path": "mesa/visualization/ModularVisualization.py"}]}