Reference 〉Class

Helipad( )

The Helipad class is the main way the user creates and interacts with a Helipad model, and groups all of the other classes underneath it. A variety of methods, properties, and hooks can be used to set up the model exactly how you want it with a minimum of boilerplate code. The object takes no arguments at initialization.

Methods

Click a method name for more detailed documentation.

  • addBreed( name, color, prim )

    Registers an agent breed, useful for heterogeneity within agent primitives.

  • addBreedParam( name, title, type, … )

    Adds a parameter to the control panel that takes a separate value for each registered breed. The current value of the parameter for any or all breeds can be retrieved by passing an appropriate parameter identification tuple to model.param().

  • addButton( text, func, desc )

    Adds a button to the control panel, in the shocks section, that runs the func function when pressed. This function is aliased by the @button function decorator, which is simpler to use.

  • addEvent( name, fn, repeat, … )

    Registers an Event. When triggered, an event stores the data output at that time and registers on the visualizer. TimeSeries, for example, draws a vertical line on the plots (see the image to the right), and Charts will flash the background. In the image to the right there are two events, marking the increase and leveling off of population.

    This function is aliased by the @heli.event decorator, which is generally the preferred syntax.

  • addGood( name, color, endowment, … )

    Registers a good that model agents can carry or trade. Agents will keep track of stocks of the good in the agent.stocks dict.

  • addGoodParam( name, title, type, … )

    Adds a parameter to the control panel that takes a separate value for each registered good. The current value of the parameter for any or all goods can be retrieved by passing an appropriate parameter identification tuple to model.param().

  • addHook( place, func, prioritize )

    Inserts a function into designated places in the model's logic. See the Hooks Reference for a complete list of possible hooks and the function signatures necessary to use them.

    This method is aliased by the @model.hook function decorator, which is the preferred way to hook functions.

  • addParameter( name, title, type, … )

    Registers a global parameter to be displayed in the control panel. Depending on the required data, possible parameter types include menus, sliders, checkboxes, checkentries, or checkgrids. The current value of the parameter can be retrieved with model.param().

    Note: model.addBreedParam() and model.addGoodParam() alias model.addParameter() via several undocumented optional parameters. It is recommended to use these two other functions for adding per-breed and per-good parameters, rather than using addParameter() directly.

  • addPrimitive( name, class, plural, … )

    Registers an agent primitive. A primitive, like a breed, is a way of introducing heterogeneity into a model, but there are several differences.

    1. Breeds do not affect the order of stepping. All agents of a primitive are stepped before any agents of another (this order can be changed with the priority argument).
    2. Breed is set as a property of the agent, which can be used with conditional logic in agent hooks. Building a primitive requires building a new agent class, which allows cleaner separation of logic where different types of agents behave in completely different ways.
    3. A use case of breeds would be different types of consumers. A use case of primitives would be consumers versus stores.

  • agent( var, primitive )

    Returns either a single agent object by ID, or a subset of agents by breed. To return all agents, use model.allagents.

  • @button( name, desc )

    A function decorator that adds a button to the control panel, in the shocks section, that runs the function when the button is pressed. This decorator can be used bare (i.e. without parentheses), in which case the button is labelled with the name of the function, or it can take optional arguments as necessary.

    The decorated function should take one argument, the model object.

  • clearEvents( )

    Removes all registered events.

  • clearHooks( place )

    Clears all functions from a given hook or set of hooks.

  • createNetwork( density, kind, prim )

    Creates a random undirected and unweighted network of a certain density among agents.

  • @event( name, repeat, **kwargs )

    A function decorator used to register an Event. When triggered, an event stores the data output at that time and registers on the visualizer. TimeSeries, for example, draws a vertical line on the plots (see the image to the right), and Charts will flash the background. In the image to the right there are two events, marking the increase and leveling off of population.

    This decorator can be used bare (i.e. without parentheses) on a function whose name will be used as the event name. It can also take arguments, which are passed to model.addEvent().

    The decorated function will run at the end of each period, immediately after data collection but before the modelPostStep hook.

  • @hook( place, prioritize )

    A function decorator used to insert a function into designated places in the model’s logic. See the Hooks Reference for a complete list of possible hooks and the function signatures necessary to use them.

    This decorator can be used bare (i.e. without parentheses) on a function whose name corresponds to a hook name. It can also take one argument, the name of the hook, to insert a function with any name into a designated hook. Further keyword arguments (e.g. prioritize) are passed to heli.addHook().

  • launchCpanel( )

    Launches the control panel, either in a Tkinter or a Jupyter environment, as appropriate. Should go at the end of the user's model code.

    Note that launchCpanel() assumes a desire to adjust parameters, so it will interrupt Jupyter's Run All sequence in order to allow the user to adjust parameters before launching the model. If this is not desired, parameters should be set programmatically using model.param(), and model.launchCpanel() should not be called.

  • launchVisual( )

    Launches the visualization window and starts the model.

    This function is not necessary to run from user code when using the Tkinter frontend, as the 'New Model' button will call this function. It can be used following model.launchCpanel() in a Jupyter notebook, however, or to run the model bypassing the control panel.

    This function calls model.setup(), instantiates the class registered in model.useVisual(), populates its plots, and initiates model.start(). This function takes no arguments.

    As of Helipad 1.2, a visualization class must be registered using model.useVisual() before model.launchVisual() can be called.

  • network( kind, prim )

    Exports the model's graph structure to a NetworkX object; useful for further network analysis. Requires that NetworkX be installed.

  • param( param, val )

    Sets or gets a parameter. Note the parameter must have been previously registered with model.addParameter(), model.addBreedParam(), or model.addGoodParameter().

  • paramSweep( param, reporters )

    Repeatedly runs the model while systematically varying one or more parameter values. This function can generate a great deal of data, and is intended to be used without the control panel. ParamSweep, therefore, should be used instead of launching the control panel.

    The possible values to be swept are specified when the parameter is initialized, either with model.addParam(), model.addBreedParam(), or model.addGoodParam(). The values will differ according to their type, even though they will not be displayed in the GUI. A checkbox parameter will run with the parameter set to True and False; a menu parameter will run with all the options specified in the opts parameter, and a slider parameter will run in increments of the step value between the minimum and the maximum. See Param.range.

    The function allows multiple parameters to be swept in an n-dimensional space. This can entail very large numbers of runs. For example, specifying a checkbox and two slider parameters with 50 possible values each will run the model for every combination of the three parameters, or 5,000 times (2×50×50).

    Each run will go until the model time equals the value of model.param('stopafter'), which can either be an integer (in which case each run will be that many periods), or the name of an event in order to stop the model at an open-ended stop condition.

  • removeEvent( name )

    Removes a previously added Event.

  • removeHook( place, fname, removeall )

    Removes one or more previously registered hooks by the function name.

  • removePrimitive( name )

    Removes a previously added primitive. See also model.addPrimitive().

  • @reporter( key, smooth )

    A decorator to register a column in the data to be collected each period. The decorated function should take one argument, the model, and output a recordable value.

    This decorator can be used bare (i.e. without parentheses), in which case the column name takes the name of the decorated function. Further arguments are passed to Data.addReporter().

  • spatial( square, x, y, … )

    Sets up functions, properties, and methods for spatial models. This function should be run before the control panel is drawn.

    The function does several things:

    1. Creates a patch primitive to represent map coordinates. In addition to the usual agent methods, the patch primitive has the following methods and properties:
      • patch.up(), patch.down(), patch.left(), and patch.right() — return the patch one over from the current patch in the specified direction.
      • patch.neighbors() — returns a list of the four (or eight, if diag==True) surrounding patches.
      • patch.agentsOn —  a list of all agents currently on the patch.
    2. Creates a network named 'space' connecting each patch to its neighbors.
    3. Adds a model.patches property, a dict of dicts by coordinates. A patch at coordinates (2,5) can be accessed using model.patches[2][5].
    4. Adds movement methods and properties to agents of all primitives except patches, which cannot move.
      • agent.moveUp(), agent.moveDown(), agent.moveLeft(), and agent.moveRight() — move the agent one patch over starting from the current location.
      • agent.move(x, y) — moves the agent some number of patches over and some number of patches down.
      • agent.moveTo(x, y) or agent.moveTo(patch) — moves the agent to the patch located at (x,y) or the location of the patch.
      • agent.distanceFrom(agent) — calculates the spatial distance between the current agent and another.
      • agent.position — the current coordinates of the agent. Patches also have patch.position, but it cannot be modified. Integer locations correspond to the center of a patch, so the range of the x dimension is -0.5 to model.param('x')-0.5, and mutatis mutandis for y.
      • agent.orientation — the angle in degrees of the agent's current heading.
      • agent.orientTo(agent) — Sets the agent's orientation toward a particular patch or another agent.
      • agent.forward(steps) — Moves the agent some distance in the direction of its current orientation.
      • agent.patch — The patch that the agent is currently on.
    5. Registers the Charts visualizer and a network plot with a patchgrid layout upon it. The plot object has a config() method that allows various aspects of the map to be customized. By default patches are displayed in a grid with colors corresponding to a specified parameter, and agents are displayed as dots of their breed color. The model.visual object can be used to display other chart plots alongside the spatial map. Note that functions calling model.spatial() do not then need to call model.useVisual().
    6. Creates a 'dimension' parameter or 'x' and 'y' parameters for the size of the map, depending on if the map is set to square or not.
    7. Creates an agentPosition hook that takes an agent object and the model object, and returns x,y coordinates. If not specified, agents are randomly positioned when instantiated.
  • start( )

    Starts a model, running model.setup() if model.hasModel is False, and otherwise resuming the existing model. Use model.stop() to pause the model and model.terminate() to end it.

    This function is called by model.launchVisual(), but does not call it. Use that function to start the model instead if output plots are desired.

  • stop( )

    Pauses the model, allowing it to be subsequently resumed. This function takes no arguments.

  • summary( var, prim, breed )

    A function, generally used in the debug console, that prints summary statistics (length, mean, standard deviation, variance, maximum, minimum, and sum) for an agent property.

  • terminate( )

    Terminates the running model and writes the data to disk, if the option was enabled. This function takes no arguments.

    Note: The function signature does take one optional argument in order to serve as a Matplotlib callback when the graph window closes. This argument is not used in the function.

  • useVisual( class )

    Registers a visualization class for live model visualization. Visualization classes can be imported from helipad.visualize, or custom visualization classes can be used if they subclass BaseVisualization and implement a standard set of methods.

    The visualization can then be launched later using model.launchVisual().

  • addItem( obj, name, color, … )

    An internal function aliased by model.addGood() and model.addBreed().

  • doHooks( place, args )

    Executes registered hooks at various places in the model.

  • genDecorator( todo )

    Returns a function which can either serve as a decorator itself or return another decorator function, in order to make it possible to use the various decorators (@heli.hook, @heli.reporter, and @heli.button) either without parentheses or with parameters.

  • nUpdater( val, prim, model, … )

    Creates and/or destroys agents to get a population number. This function is used as a setter function for agent population parameters, and also at the beginning of a model to create the initial agent set.

  • parseParamID( p )

    Takes a parameter identification string or tuple, such as can be passed to model.param(), model.paramSweep(), and Shocks.register(), and returns the corresponding Param object.

  • setup( )

    Gathers the control panel settings and initiates the model. This function runs when the 'New Model' button is pressed, and should not be called by user code. It takes no arguments.

  • step( )

    Steps the model, i.e. runs through the step functions of all the agents and increments the timer by one. The function takes no arguments.

    This function is called automatically while the model is running, and should not generally be called in user code.

Properties

  • name str

    A short name for the model, to be displayed in the title bars of the GUI windows.

    Initial value: ''

  • order str|list[str]

    Determines the order in which agents activate. Possible values are:

    • 'random', which shuffles the list of agents before each stage
    • 'linear', which preserves the order of activation between periods.
    • 'match-n', which steps agents in groups of n and passes them to the match hook. If order=='match' (without the -n), agents will pair off at random (i.e. n==2).
    order can also be set to a list of these values whose length corresponds to the number of stages, in order to use a different ordering in different stages of the model. Use the order hook for more complex ordering. Can be overridden on a per-primitive basis; see model.addPrimitive().

    Initial value: 'linear'

  • stages int

    The number of times the various step functions should be run per period. This parameter can be set from user code.

    Initial value: 1

  • agents dict

    Contains all the agents of all primitives. Keys correspond to registered primitives, and each value is a list of agents of that primitive.

    Initial value: {'agent': []}

  • allagents list[Agent]

    A flat list of all agents of all primitives.

    Initial value: []

  • primitives dict

    Contains information about registered primitives and the breeds associated with them. See model.addPrimitive(), model.addBreed(), and model.addBreedParam().

    Initial value: {'agent': {…}}

  • params dict{str:Param}

    A dict of Param objects that contain information about registered global parameters. See model.addParameter().

    Initial value: {}

  • goods dict{str:Good}

    A dict of Good objects that contain information about registered goods. See model.addGood()

    Initial value: {}

  • goodParams dict{str:Param}

    A dict of Param objects that contains information about registered per-good parameters. See model.addGoodParam().

    Initial value: {}

  • hooks dict{str:list[func]}

    Stores hooked functions. See model.addHook().

    Initial value: {}

  • stage int

    The current stage of the running model. While the current stage is passed to the agentStep hook, this property can be useful for getting the model stage from other hooks where it is not passed.

  • hasModel bool

    Whether a current model has been instantiated. False before a model has been started and after termination, but True while running or paused.

    Initial value: False

  • running bool

    True if the model is currently running, False if it is paused or terminated.

    Initial value: False

  • t int

    The current model time if the model is running.

  • allEdges dict{str: list[Edge]}

    A collection of all active connections in the model, sorted by edge kind. Used to generate model.network().

    Initial value: {}

  • moneyGood str

    The good serving as a numeraire. This property is set by the money parameter of model.addGood(). The value of this property, if set, must correspond to a key of the model.goods property.

    Initial value: None

  • nonMoneyGoods dict

    Equivalent to the model.goods property, but minus the model.moneyGood good.

    Initial value: {}

  • plots dict{str:Plot}

    Contains information about registered plot areas. See model.addPlot() for usage and TimeSeriesPlot for the data structure.

    Initial value: {…}

  • data Data

    The Data class, an interface for the data collected during the model's run.

    Initial value: Data()

  • shocks Shocks

    The Shocks class, an interface for registering and managing automated shocks to parameters or properties.

    Initial value: Shocks()

  • events dict{str: Event}

    The set of Event objects.

    Initial value: {}

  • visual BaseVisualization

    An object subclassed from BaseVisualization to handle drawing live updates.

    Initial value: None

  • timer bool

    If set to True, enables the printing of performance data to the console on each visual update, divided between visualization and model running. For example,

    Period 20 : 21.57 periods/second ( 55.71 % model, 44.29 % visuals)
    Period 40 : 27.84 periods/second ( 74.21 % model, 25.79 % visuals)
    Period 60 : 29.39 periods/second ( 79.79 % model, 20.21 % visuals)

    Initial value: False

Hooks

Click a hook name for more detailed documentation.

  • modelStart( model, hasModel )

    Runs when a model is started, either initialized or resumed. The hasModel argument distinguishes between these two cases, though modelPreSetup or modelPostSetup are preferred for hooking the initialization of a new model.

  • matchSelect( agent, pool, model, … )

    In a matching model, this hook allows random matching to be overridden and matches to be made with custom logic. The function receives one agent, and must then select its partners from a pool.

  • matchAccept( *agents )

    In matching models, Helipad runs all matching groups through matchAccept. Return True to accept the match, and False to reject the match, in which case the matched agents return to the pool.

    WARNING: Be careful that you do not write a situation where all remaining agents have matched and matchAccept returns False for the only remaining pair. The model will hang in this case. To actively select matches rather than reject random ones, use matchSelect.

  • match( agents, primitive, model, … )

    Code to be performed in a matching model, when model.order or the order parameter of the relevant primitive has been set to 'match' or 'match-n'. Helipad steps agents in groups of n and passes them to the match hook. The hook does not run otherwise.

    The match hook will run once per primitive per stage. Corresponding per-primitive hooks are also available on the pattern [primitive]Match, e.g. bankMatch would run only during the matching process of 'bank'-primitive agents. See model.addPrimitive().

  • modelStop( model )

    Runs when the model is paused.

  • terminate( model, data )

    Runs when a model terminates.

  • GUIClose( model )

    Runs when all GUI elements have closed. Note that 'closing' only has a clear meaning in a windowed frontend, so this hook never runs in a Jupyter environment.

  • CpanelPreLaunch( model )

    Runs immediately before the Cpanel object is initialized.

  • decideBreed( id, breeds, model )

    By default, Helipad creates agents with equiproportional breeds, cycling through the list of registered breeds as it creates agents of a specific primitive. decideBreed allows the user to specify a function to determine which breed agents should be assigned when initialized. The hook runs only during the creation of parentless agents, i.e. when agents are initialized at the beginning of the model and when agents are created via the population control panel slider. It does not run when agents reproduce, as the breed is inherited from the primary parent by default.

    The decideBreed hook will run every time a parentless agent of any primitive is created. There are corresponding primitive-specific hooks [primitive]DecideBreed for a more narrow focus, e.g. bankDecideBreed will only run for a bank primitive. See model.addPrimitive().

  • modelStep( model, stage )

    This model runs once per stage in multi-stage models, before any agents have been stepped that stage (but after all agents have been stepped in any previous stage).

  • order( agent, model, stage )

    Helipad allows the order of agent activation to be specified globally as either 'random' or 'linear'. This hook allows more complex ordering to be specified both globally and on a per-primitive basis.

    This hook generates a key function for use in list.sort(). The list of agents will be sorted by the value returned from this function, and activated in that order.

    The order hook will run once per primitive per stage. Corresponding per-primitive hooks are also available on the pattern [primitive]Order, e.g. bankOrder would apply to the ordering of a 'bank' primitive. See model.addPrimitive().

  • modelPostStep( model )

    This model runs once per period, at the end, after all agents have been stepped and data collected.

  • modelPreStep( model )

    This hook runs once per model step, at the beginning, before the model runs any of the agent step functions.

  • modelPostSetup( model )

    Helipad waits to set up a number of variables until a model is actually run. This hook runs after this setup, but immediately before GUI launches the Visualize object.

  • modelPreSetup( model )

    Helipad waits to set up a number of variables until a model is actually run. This hook runs immediately after the user presses the button to create a new model, but before Helipad runs any of its pre-model setup.

Notes and Examples

  1. charwick

    Mar 28, 2020 at 1:52

    model.order=='random' will shuffle agents at the beginning of every stage, not just the beginning of each period. To shuffle agents only at the beginning of each period, only set the first stage to 'random'.

    heli.stages = 3
    heli.order = ['random', 'linear', 'linear']
  2. Contribute a Note

    Your email address will not be published. Required fields are marked *

    You may use limited HTML for formatting. Please embed blocks of code in <pre><code> </code></pre> tags.

History