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.
Initialization Parameters
locale — str, optional
The code for the language Helipad should launch in. Currently only an English locale exists. Translators may use the string template to contribute a localization.
Default value: 'en'
Methods
Click a method name for more detailed documentation.
addButton( text, func, desc )
Adds a button to the control panel, in the shocks section, that runs the
func
function when pressed. This method is aliased by the@button
function decorator, which is simpler to use.cutStep( )
When called from inside an
agentStep
ormatch
hook, tells Helipad to skip stepping the rest of the agents that stage and proceed to the next (or to the next period in single-stage models). For example, in a model testing if any agent will succeed in a period, there is no need to step through further agents that period once one does, and the rest can be skipped.In multi-stage models,
cutStep
proceeds to the next stage of the period. IfcutStep()
is called in amodelStep
hook, no agents will be stepped that stage. The function has no effect in other hooks.@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), andCharts
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
Events.add()
.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 toHooks.add()
.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 usingmodel.param(),
andmodel.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 inmodel.useVisual()
, populates its plots, and initiatesmodel.start()
. This function takes no arguments.As of Helipad 1.2, a visualization class must be registered using
model.useVisual()
beforemodel.launchVisual()
can be called.param( param, val )
Sets or gets a parameter. Note the parameter must have been previously registered with
Params.add()
.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 registered. 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
andFalse
; a menu parameter will run with all the options specified in theopts
parameter, and a slider parameter will run in increments of the step value between the minimum and the maximum. SeeParam.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.@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( dim, wrap, corners, … )
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:
- Creates a spatially fixed
patch
primitive to represent map coordinates. - Creates a network named
'space'
connecting each patch to its neighbors. - Initializes the
model.patches
property. - Adds movement methods and properties to agents of all primitives except patches, which cannot move.
agent.moveUp()
,agent.moveDown()
,agent.moveLeft()
, andagent.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)
oragent.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 havepatch.position
, but it cannot be modified. Integer locations correspond to the center of a patch, so the range of thex
dimension is-0.5
todim[0]-0.5
, and mutatis mutandis fory
.
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.
- Registers the
Charts
visualizer and anetwork
plot with a spatial layout upon it. The plot object has aconfig()
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. Themodel.visual
object can be used to display other chart plots alongside the spatial map. Note that functions callingmodel.spatial()
do not then need to callmodel.useVisual()
.
By default, agents are randomly positioned on the grid on model launch. The
agentPosition
hook can be used to override this and specify agents' initial positions.- Creates a spatially fixed
start( )
Starts a model, running
model.setup()
ifmodel.hasModel
isFalse
, and otherwise resuming the existing model. Usemodel.stop()
to pause the model andmodel.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.
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 visualization 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 subclassBaseVisualization
and implement a standard set of methods.The visualization can then be launched later using
model.launchVisual()
.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.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.
Object Properties
name — str
A short name for the model, to be displayed in the title bars of the GUI windows.
Initial value: ''
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 — Agents{str:Primitive[Agent]}
The
Agents
container, storing agents by primitive, along with data defining the primitive itself. Keys are primitive names, and values arePrimitive
lists of agents.Initial value: {'agent': []}
patches — list[list]
A list-like property for accessing patches by coordinate in a spatial model (a flat list of patches is still kept in
model.agents['patch']
). Individual patches can be accessed by coordinate withmodel.patches[x,y]
, columns withmodel.patches[x]
, and rows withmodel.patches[None, y]
.
This property will be an empty list until a spatial model is initialized withmodel.spatial()
. Note also thatlen(model.patches)
will return the total number of individual patches, not the number of columns.Initial value: []
params — Params{str:Param}
The
Params
container, an interface for storing, adding, and removingParam
objects with information about model parameters. SeeParams.add()
.Initial value: {}
goods — Goods{str:Good}
The
Goods
container, an interface for storing, adding, and removingGood
objects containing information about registered goods. SeeGoods.add()
Initial value: {}
hooks — Hooks{str:list[func]}
The
Hooks
container, an interface for adding, storing, and removing hooked functions.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, butTrue
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.
data — Data
The
Data
class, an interface for the data collected during the model's run.Initial value: Data()
shocks — Shocks{str:Shock}
The
Shocks
container, an interface for adding, storing, and removing automated shocks to parameters or properties.Initial value: Shocks()
events — Events{str: Event}
The
Events
container, an interface for adding, storing, and removingEvent
objects.Initial value: {}
visual — BaseVisualization
An object subclassed from
BaseVisualization
to handle drawing live updates. This property is instantiated only aftermodel.useVisual()
is called.Initial value: None
cpanel — Cpanel
The
Cpanel
object. This property is instantiated only aftermodel.launchCpanel()
is called.Initial value: None
timer — bool
If set to
True
, prints 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, thoughmodelPreSetup
ormodelPostSetup
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
. ReturnTrue
to accept the match, andFalse
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
returnsFalse
for the only remaining pair. The model will hang in this case. To actively select matches rather than reject random ones, usematchSelect
.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 thematch
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. SeeAgents.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 abank
primitive. SeeAgents.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. SeeAgents.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 instantiate agents and initialize a number of variables until a model is actually run. This hook runs after this setup, but immediately before launching visualizations.
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