mesa.visualization package

Subpackages

Submodules

mesa.visualization.ModularVisualization module

ModularServer

A visualization server which renders a model via one or more elements.

The concept for the modular visualization server as follows: A visualization is composed of VisualizationElements, each of which defines how to generate some visualization from a model instance and render it on the client. VisualizationElements may be anything from a simple text display to a multilayered HTML5 canvas.

The actual server is launched with one or more VisualizationElements; it runs the model object through each of them, generating data to be sent to the client. The client page is also generated based on the JavaScript code provided by each element.

This file consists of the following classes:

VisualizationElement: Parent class for all other visualization elements, with

the minimal necessary options.

PageHandler: The handler for the visualization page, generated from a template

and built from the various visualization elements.

SocketHandler: Handles the websocket connection between the client page and

the server.

ModularServer: The overall visualization application class which stores and

controls the model and visualization instance.

ModularServer should not need to be subclassed on a model-by-model basis; it should be primarily a pass-through for VisualizationElement subclasses, which define the actual visualization specifics.

For example, suppose we have created two visualization elements for our model, called canvasvis and graphvis; we would launch a server with:

server = ModularServer(MyModel, [canvasvis, graphvis], name=”My Model”) server.launch()

The client keeps track of what step it is showing. Clicking the Step button in the browser sends a message requesting the viz_state corresponding to the next step position, which is then sent back to the client via the websocket.

The websocket protocol is as follows: Each message is a JSON object, with a “type” property which defines the rest of the structure.

Server -> Client:

Send over the model state to visualize. Model state is a list, with each element corresponding to a div; each div is expected to have a render function associated with it, which knows how to render that particular data. The example below includes two elements: the first is data for a CanvasGrid, the second for a raw text display.

{ “type”: “viz_state”, “data”: [{0:[ {“Shape”: “circle”, “x”: 0, “y”: 0, “r”: 0.5,

“Color”: “#AAAAAA”, “Filled”: “true”, “Layer”: 0, “text”: ‘A’, “text_color”: “white” }]},

“Shape Count: 1”]

}

Informs the client that the model is over. {“type”: “end”}

Informs the client of the current model’s parameters { “type”: “model_params”, “params”: ‘dict’ of model params, (i.e. {arg_1: val_1, …}) }

Client -> Server:

Reset the model. TODO: Allow this to come with parameters { “type”: “reset” }

Get a given state. { “type”: “get_step”, “step:” index of the step to get. }

Submit model parameter updates { “type”: “submit_params”, “param”: name of model parameter “value”: new value for ‘param’ }

Get the model’s parameters { “type”: “get_params” }

is_user_param(val)[source]
class VisualizationElement[source]

Bases: object

Defines an element of the visualization.

Attributes:
package_includes: A list of external JavaScript and CSS files to

include that are part of the Mesa packages.

local_includes: A list of JavaScript and CSS files that are local to

the directory that the server is being run in.

js_code: A JavaScript code string to instantiate the element. local_dir: A full path to the directory containing the local includes.

If a relative path is given, it is relative to the working directory where the server is being run. If an absolute path is given, it is used as-is. Default is the current working directory.

Methods:
render: Takes a model object, and produces JSON data which can be sent

to the client.

package_includes = []
local_includes = []
js_code = ''
render_args = {}
local_dir = ''
render(model)[source]

Build visualization data from a model object.

Args:

model: A model object

Returns:

A JSON-ready object.

class TextElement[source]

Bases: VisualizationElement

Module for drawing live-updating text.

package_includes = ['TextModule.js']
js_code = 'elements.push(new TextModule());'
class PageHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]

Bases: RequestHandler

Handler for the HTML template which holds the visualization.

get()[source]
class SocketHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]

Bases: WebSocketHandler

Handler for websocket.

open()[source]

Invoked when a new WebSocket is opened.

The arguments to open are extracted from the tornado.web.URLSpec regular expression, just like the arguments to tornado.web.RequestHandler.get.

open may be a coroutine. on_message will not be called until open has returned.

Changed in version 5.1: open may be a coroutine.

check_origin(origin)[source]

Override to enable support for allowing alternate origins.

The origin argument is the value of the Origin HTTP header, the url responsible for initiating this request. This method is not called for clients that do not send this header; such requests are always allowed (because all browsers that implement WebSockets support this header, and non-browser clients do not have the same cross-site security concerns).

Should return True to accept the request or False to reject it. By default, rejects all requests with an origin on a host other than this one.

This is a security protection against cross site scripting attacks on browsers, since WebSockets are allowed to bypass the usual same-origin policies and don’t use CORS headers.

Warning

This is an important security measure; don’t disable it without understanding the security implications. In particular, if your authentication is cookie-based, you must either restrict the origins allowed by check_origin() or implement your own XSRF-like protection for websocket connections. See these articles for more.

To accept all cross-origin traffic (which was the default prior to Tornado 4.0), simply override this method to always return True:

def check_origin(self, origin):
    return True

To allow connections from any subdomain of your site, you might do something like:

def check_origin(self, origin):
    parsed_origin = urllib.parse.urlparse(origin)
    return parsed_origin.netloc.endswith(".mydomain.com")

New in version 4.0.

property viz_state_message
on_message(message)[source]

Receiving a message from the websocket, parse, and act accordingly.

class ModularServer(model_cls, visualization_elements, name='Mesa Model', model_params=None, port=None)[source]

Bases: Application

Main visualization application.

Args:

model_cls: Mesa model class visualization_elements: visualisation elements name: A String for the model name port: Port the webserver listens to (int)

Order of configuration: 1. Parameter to ModularServer.launch 2. Parameter to ModularServer() 3. Environment var PORT 4. Default value (8521)

model_params: A dict of model parameters

EXCLUDE_LIST = ('width', 'height')
settings

Create a new visualization server with the given elements.

property user_params
reset_model()[source]

Reinstantiate the model object, using the current parameters.

render_model()[source]

Turn the current state of the model into a dictionary of visualizations

launch(port=None, open_browser=True)[source]

Run the app.

mesa.visualization.TextVisualization module

Text Visualization

Base classes for ASCII-only visualizations of a model. These are useful for quick debugging, and can readily be rendered in an IPython Notebook or via text alone in a browser window.

Classes:

TextVisualization: Class meant to wrap around a Model object and render it in some way using Elements, which are stored in a list and rendered in that order. Each element, in turn, renders a particular piece of information as text.

ASCIIElement: Parent class for all other ASCII elements. render() returns its representative string, which can be printed via the overloaded __str__ method.

TextData: Uses getattr to get the value of a particular property of a model and prints it, along with its name.

TextGrid: Prints a grid, assuming that the value of each cell maps to exactly one ASCII character via a converter method. This (as opposed to a dictionary) is used so as to allow the method to access Agent internals, as well as to potentially render a cell based on several values (e.g. an Agent grid and a Patch value grid).

class TextVisualization(model)[source]

Bases: object

ASCII-Only visualization of a model.

Properties:

model: The underlying model object to be visualized. elements: List of visualization elements, which will be rendered

in the order they are added.

Create a new Text Visualization object.

render()[source]

Render all the text elements, in order.

step()[source]

Advance the model by a step and print the results.

class ASCIIElement[source]

Bases: object

Base class for all TextElements to render.

Methods:

render: ‘Renders’ some data into ASCII and returns. __str__: Displays render() by default.

render()[source]

Render the element as text.

class TextData(model, var_name)[source]

Bases: ASCIIElement

Prints the value of one particular variable from the base model.

Create a new data renderer.

render()[source]

Render the element as text.

class TextGrid(grid, converter)[source]

Bases: ASCIIElement

Class for creating an ASCII visualization of a basic grid object.

By default, assume that each cell is represented by one character, and that empty cells are rendered as ‘ ‘ characters. When printed, the TextGrid results in a width x height grid of ascii characters.

Properties:

grid: The underlying grid object.

Create a new ASCII grid visualization.

Args:

grid: The underlying Grid object. converter: function for converting the content of each cell

to ascii. Takes the contents of a cell, and returns a single character.

grid = None
render()[source]

What to show when printed.

mesa.visualization.UserParam module

class UserSettableParameter(param_type=None, name='', value=None, min_value=None, max_value=None, step=1, choices=None, description=None)[source]

Bases: object

A class for providing options to a visualization for a given parameter.

UserSettableParameter can be used instead of keyword arguments when specifying model parameters in an instance of a ModularServer so that the parameter can be adjusted in the UI without restarting the server.

Validation of correctly-specified params happens on startup of a ModularServer. Each param is handled individually in the UI and sends callback events to the server when an option is updated. That option is then re-validated, in the value.setter property method to ensure input is correct from the UI to reset_model callback.

Parameter types include:
  • ‘number’ - a simple numerical input

  • ‘checkbox’ - boolean checkbox

  • ‘choice’ - String-based dropdown input, for selecting choices within a model

  • ‘slider’ - A number-based slider input with settable increment

  • ‘static_text’ - A non-input textbox for displaying model info.

Examples:

# Simple number input number_option = UserSettableParameter(‘number’, ‘My Number’, value=123)

# Checkbox input boolean_option = UserSettableParameter(‘checkbox’, ‘My Boolean’, value=True)

# Choice input choice_option = UserSettableParameter(‘choice’, ‘My Choice’, value=’Default choice’,

choices=[‘Default Choice’, ‘Alternate Choice’])

# Slider input slider_option = UserSettableParameter(‘slider’, ‘My Slider’, value=123, min_value=10, max_value=200, step=0.1)

# Static text static_text = UserSettableParameter(‘static_text’, value=”This is a descriptive textbox”)

NUMBER = 'number'
CHECKBOX = 'checkbox'
CHOICE = 'choice'
SLIDER = 'slider'
STATIC_TEXT = 'static_text'
TYPES = ('number', 'checkbox', 'choice', 'slider', 'static_text')
property value
property json
class UserParam[source]

Bases: object

property json
maybe_raise_error(valid)[source]
property value
class Slider(name='', value=None, min_value=None, max_value=None, step=1, description=None)[source]

Bases: UserParam

A number-based slider input with settable increment.

Example:

slider_option = Slider(“My Slider”, value=123, min_value=10, max_value=200, step=0.1)

property value
class Checkbox(name='', value=None, description=None)[source]

Bases: UserParam

Boolean checkbox.

Example:

boolean_option = Checkbox(‘My Boolean’, True)

class Choice(name='', value=None, choices=None, description=None)[source]

Bases: UserParam

String-based dropdown input, for selecting choices within a model

Example: choice_option = Choice(

‘My Choice’, value=’Default choice’, choices=[‘Default Choice’, ‘Alternate Choice’]

)

property value
class StaticText(value=None)[source]

Bases: UserParam

A non-input textbox for displaying model info.

Example: static_text = StaticText(“This is a descriptive textbox”)

class NumberInput(name='', value=None, description=None)[source]

Bases: UserParam

a simple numerical input

Example: number_option = NumberInput(“My Number”, value=123)

Module contents

Mesa Visualization Module

TextVisualization: Base class for writing ASCII visualizations of model state.

TextServer: Class which takes a TextVisualization child class as an input, and renders it in-browser, along with an interface.