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), andCharts
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()
andmodel.addGoodParam()
aliasmodel.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 usingaddParameter()
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.
- 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). - 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.
- A use case of breeds would be different types of consumers. A use case of primitives would be consumers versus stores.
- 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
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.
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), 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
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 toheli.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 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.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()
, ormodel.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()
, ormodel.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 toTrue
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.removeEvent( name )
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:
- 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()
, andpatch.right()
— return the patch one over from the current patch in the specified direction.patch.neighbors()
— returns a list of the four (or eight, ifdiag==True
) surrounding patches.patch.agentsOn
— a list of all agents currently on the patch.
- Creates a network named
'space'
connecting each patch to its neighbors. - Adds a
model.patches
property, adict
ofdicts
by coordinates. A patch at coordinates (2,5) can be accessed usingmodel.patches[2][5]
. - 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.location
— the current coordinates of the agent. Patches also havepatch.location
, but it cannot be modified. Integer locations correspond to the center of a patch, so the range of thex
dimension is-0.5
tomodel.param('x')-0.5
, and mutatis mutandis fory
.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.
- Registers the
Charts
visualizer and aspatial
plot upon it. The spatial 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. 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()
. - 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. - 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.
- Creates a
start( )
Starts a model, running
model.setup()
ifmodel.hasModel
is False, 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.
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 subclassBaseVisualization
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()
andmodel.addBreed()
.addPlot( name, label, position, … )
Registers a plot area in the graph to which data series can be added.
This function has been replaced by
TimeSeries.addPlot()
and will be removed in a future update.addSeries( plot, reporter, label, … )
Registers a reporter to be drawn in a particular plot during the model's runtime.
This function is here for compatibility purposes. Use
Plot.addSeries()
instead.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()
, andShocks.register()
, and returns the correspondingParam
object.removePlot( name, reassign )
Removes a plot or plots and optionally reassigns their series to a different plot. This function can only be run prior to
model.launchCpanel()
.Deprecated in Helipad 1.2 in favor of
TimeSeries.removePlot()
.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 ofn
and passes them to thematch
hook. Iforder=='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 theorder
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()
, andmodel.addBreedParam()
.Initial value: {'agent': {…}}
params — dict{str:Param}
A
dict
ofParam
objects that contain information about registered global parameters. Seemodel.addParameter()
.Initial value: {}
goods — dict{str:Good}
A
dict
ofGood
objects that contain information about registered goods. Seemodel.addGood()
Initial value: {}
goodParams — dict{str:Param}
A
dict
ofParam
objects that contains information about registered per-good parameters. Seemodel.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, 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.
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 ofmodel.addGood()
. The value of this property, if set, must correspond to a key of themodel.goods
property.Initial value: None
nonMoneyGoods — dict
Equivalent to the
model.goods
property, but minus themodel.moneyGood
good.Initial value: {}
plots — dict{str:Plot}
Contains information about registered plot areas. See
model.addPlot()
for usage andPlot
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.
charwick
Mar 28, 2020 at 1:52model.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'
.