| Type: | Package |
| Title: | Agent Based Model Simulation Framework |
| Version: | 0.4.3 |
| Date: | 2025-01-25 |
| Description: | A high-performance, flexible and extensible framework to develop continuous-time agent based models. Its high performance allows it to simulate millions of agents efficiently. Agents are defined by their states (arbitrary R lists). The events are handled in chronological order. This avoids the multi-event interaction problem in a time step of discrete-time simulations, and gives precise outcomes. The states are modified by provided or user-defined events. The framework provides a flexible and customizable implementation of state transitions (either spontaneous or caused by agent interactions), making the framework suitable to apply to epidemiology and ecology, e.g., to model life history stages, competition and cooperation, and disease and information spread. The agent interactions are flexible and extensible. The framework provides random mixing and network interactions, and supports multi-level mixing patterns. It can be easily extended to other interactions such as inter- and intra-households (or workplaces and schools) by subclassing an R6 class. It can be used to study the effect of age-specific, group-specific, and contact- specific intervention strategies, and complex interactions between individual behavior and population dynamics. This modeling concept can also be used in business, economical and political models. As a generic event based framework, it can be applied to many other fields. More information about the implementation and examples can be found athttps://github.com/junlingm/ABM. |
| License: | GPL-2 |GPL-3 [expanded from: GPL (≥ 2)] |
| URL: | https://github.com/junlingm/ABM |
| BugReports: | https://github.com/junlingm/ABM/issues |
| Imports: | R6, Rcpp |
| LinkingTo: | Rcpp |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.2.3 |
| NeedsCompilation: | yes |
| Packaged: | 2025-01-26 00:57:07 UTC; jma |
| Author: | Junling Ma [aut, cre] |
| Maintainer: | Junling Ma <junlingm@uvic.ca> |
| Repository: | CRAN |
| Date/Publication: | 2025-01-26 04:30:02 UTC |
Agent Based Model Simulation Framework
Description
This package provides a framework to simulate agent based models that arebased on states and events.
Details
Agent
The concept of this framework is agent, which is an object of theAgentclass. An agent maintains its own state, which is a named R list storing anyR values in it. (seeState ). The main task of an agent is to manage events(seeEvent), and handle them in chronological order.
Population
An object of thePopulation class manages agents and their contacts. Thecontacts of agents are managed by Contact objects. The main functionality fora contact object is to provide contacts of a given individuals at a giventime. For example,newRandomMixing() returns such an object that finds arandom agent in the population as a contact. the effect of contacts on thestates of agents are defined using a state transition rule. Please seeaddTransition method ofSimulation for more details.
Simulation
TheSimulation class inherits thePopulation class. So a simulationmanages agents and their contacts. Thus, the class also inherits theAgentclass. So a simulation can have its own state, and events attached(scheduled) to it. In addition, it also manages all the transitions, usingitsaddTransition method. At last, it maintains loggers, which record(or count) the state changes, and report their values at specified times.
During a simulation the earliest event in the simulation is picked out,unscheduled (detached), and handled, which potentially causes the statechange of the agent (or another agent in the simulation). The state change isthen logged by loggers (seenewCounter() andnewStateLogger() for more details) that recognize the statechange.
Usage
To use this framework, we start by creating a simulationobject, populate the simulation with agents (either using the argument inthe constructor, or use itsaddAgent method), andinitialize the agents with their initial states using itssetState method.
We then attach (schedule()) events to agents (possibly to the populations orthe simulation object too), so that these events change the agents' state.For models which agents' states are defined by discrete states, such as theSIR epidemic model, the events are managed by the framework through statetransitions, using rules defined by theaddTransition method oftheSimulation class.
At last, we add loggers to the simulation usingtheSimulation class'addLogger method' and eithernewCounter() ornewStateLogger(). At last, run the simulation usingitsrun method, which returns the observations of the loggersat the requested time points as a data.frame object.
For more information and examples, please see theWiki pages on Github.
Author(s)
Maintainer: Junling Majunlingm@uvic.ca
See Also
Useful links:
Examples
# simulate an SIR model using the Gillespie method# the population sizeN = 10000# the initial number of infectious agentsI0 = 10# the transmission ratebeta = 0.4# the recovery rategamma = 0.2# an waiting time egenerator that handles 0 rate properlywait.exp = function(rate) { if (rate == 0) Inf else rexp(1, rate)}# this is a function that rescheduled all the events. When the# state changed, the old events are invalid because they are# calculated from the old state. This is possible because the# waiting times are exponentially distributedreschedule = function(time, agent, state) { clearEvents(agent) t.inf = time + wait.exp(beta*state$I*state$S/N) schedule(agent, newEvent(t.inf, handler.infect)) t.rec = time + wait.exp(gamma*state$I) schedule(agent, newEvent(t.rec, handler.recover))}# The infection event handler# an event handler take 3 arguments# time is the current simulation time# sim is an external pointer to the Simulation object.# agent is the agent that the event is scheduled tohandler.infect = function(time, sim, agent) { x = getState(agent) x$S = x$S - 1 x$I = x$I + 1 setState(agent, x) reschedule(time, agent, x)}# The recovery event handlerhandler.recover = function(time, sim, agent) { x = getState(agent) x$R = x$R + 1 x$I = x$I - 1 setState(agent, x) reschedule(time, agent, x)}# create a new simulation with no agent in it.# note that the simulation object itself is an agentsim = Simulation$new()# the initial statex = list(S=N-I0, I=I0, R=0)sim$state = x# schedule an infection event and a recovery eventreschedule(0, sim$get, sim$state)# add state loggers that saves the S, I, and R statessim$addLogger(newStateLogger("S", NULL, "S"))sim$addLogger(newStateLogger("I", NULL, "I"))sim$addLogger(newStateLogger("R", sim$get, "R"))# now the simulation is setup, and is ready to runresult = sim$run(0:100)# the result is a data.frame objectprint(result)# simulate an agent based SEIR model# specify an exponential waiting time for recoverygamma = newExpWaitingTime(0.2)# specify a tansmission ratebeta = 0.4# specify a exponentially distributed latent periodsigma =newExpWaitingTime(0.5)# the population sizeN = 10000# create a simulation with N agents, initialize the first 5 with a state "I" # and the remaining with "S".sim = Simulation$new(N, function(i) if (i <= 5) "I" else "S")# add event loggers that counts the individuals in each state.# the first variable is the name of the counter, the second is# the state for counting. States should be lists. However, for# simplicity, if the state has a single value, then we # can specify the list as the value, e.g., "S", and the state# is equivalent to list("S")sim$addLogger(newCounter("S", "S"))sim$addLogger(newCounter("E", "E"))sim$addLogger(newCounter("I", "I"))sim$addLogger(newCounter("R", "R"))# create a random mixing contact pattern and attach it to simm = newRandomMixing()sim$addContact(m)# the transition for leaving latent state anbd becoming infectioussim$addTransition("E"->"I", sigma)# the transition for recoverysim$addTransition("I"->"R", gamma)# the transition for tranmission, which is caused by the contact m# also note that the waiting time can be a number, which is the same# as newExpWaitingTime(beta)sim$addTransition("I" + "S" -> "I" + "E" ~ m, beta)# run the simulation, and get a data.frame objectresult = sim$run(0:100)print(result)R6 class that represent an agent
Description
The key task of an agent is to maintain events, and handle them in thechronological order. Agents also maintain their states, which is a list ofvalues. The events, when handled, operate on the state of the agent (or otheragents).
Details
During the simulation the agent with the earliest event in the simulation ispicked out, unscheduled, then its earliest event is handled, whichpotentially causes the state change of the agent (or another agent in thesimulation). The state change is then logged by loggers that recognize thestate change.
An agent itself cannot handle the event. Instead, it has to be added to asimulation (or a population that itself is added to a simulation).
Note that specifying death.time is equivalent to call the$setDeathTime method.Check if the state of the agent matches a given state
At the time of death, the agent is removed from the simulation.Calling it multiple times causes the agent to die at the earliest time.
Active bindings
stateGet/set the state of the agent
idGet the agent ID
getGet the external pointer for the agent
Methods
Public methods
Methodnew()
Usage
Agent$new(agent = NULL, death.time = NA)
Arguments
agentcan be either an external pointer to an agent such as onereturned by newAgent, or a list representing the initial state for creatinga new agent, or NULL (an empty state)
death.timethe time of death for the agent, a numeric value
Methodmatch()
Usage
Agent$match(rule)
Arguments
rulethe state to match, a list
Returns
a logical valueSchedule an event
Methodschedule()
Usage
Agent$schedule(event)
Arguments
eventan object of the R6 class Event, or an external pointerreturned by newEvent
Returns
the agent itself (invisible)Unschedule an event
Methodunschedule()
Usage
Agent$unschedule(event)
Arguments
eventan object of the R6 class Event, or an external pointerreturned by newEvent
Returns
the agent itself (invisible)leave the population that the agent is in
Methodleave()
Usage
Agent$leave()
Returns
the agent itselfset the time of death for the agent
MethodsetDeathTime()
Usage
Agent$setDeathTime(time)
Arguments
timethe time of death, a numeric value
Returns
the agent itself (invisible)
Methodclone()
The objects of this class are cloneable with this method.
Usage
Agent$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
An R6 class that implements a contact pattern in R
Description
An R6 class that implements a contact pattern in R
An R6 class that implements a contact pattern in R
Details
The main task of the class is to return the contacts of a given agent. Eachobject of this class is associated to a population. A population may havemultiple contacts attached, e.g., a random mixing contact pattern and anetwork contact pattern.
This class must be subclassed in order to implement specific functionality.To subclass, we must implement three methods, namely contact, addAgent, andbuild. See more details in the documentation of each method.
. This method should be called from the C++ side. Users should notcall this directly.
When an agent is added to a population, it is added to each of thecontact patterns. When a contact pattern is added to a population, allagents in a population is added to the contact pattern, one by one.
Note that, immediately before the simulation is run, while reportingthe states to the simulation object, the population will call thebuild method for each Contact object. Thus a contact object may chooseto ignore adding agents before build is called, and handle all agentswithin the finalize method. However, the contact object must handleadding an agent after build is called.
When an agent leaves a population, it is removed from each of thecontact patterns.
This method may also be called in event handlers to remove an agent
This method is called immediately before the simulation is run,when the attached population reports the states to the simulation object.
Thus this method can be considered as a callback function to notify thecontact object the population state, such as its agents, states, events,and contact patterns are all initialized, so the contact pattern shouldfinish initialization, for example, building the contact network.
This is needed because some contact patterns, such as a configuration-model contact network, cannot be built while adding agents one by one.It must be generated when all agents are present. This is unlike theAlbert-Barabasi networkm which can be built while adding the agents.
Active bindings
get.The external pointer pointing to the C++ RContact object.
attacheda logical value indicating whether the object has been attachedto a population
Methods
Public methods
Methodnew()
the constructor
Usage
Contact$new()
Methodattach()
attach to a population
Usage
Contact$attach(population)
Arguments
populationthe population to attach to. An external pointer
Methodcontact()
Returns the contacts of the given agent
Usage
Contact$contact(time, agent)
Arguments
timethe current time in the simulation, a number
agentthe agent whose contacts are requested. An external pointer
Returns
a list of external pointers pointing to the contacting agents
MethodaddAgent()
Add an agent to the contact pattern
Usage
Contact$addAgent(agent)
Arguments
agentthe agent to be added. An external pointer
Methodremove()
Remove an agent from the contact pattern
Usage
Contact$remove(agent)
Arguments
agentthe agent to be removed. An external pointer
Methodbuild()
Build the contact pattern
Usage
Contact$build()
Methodclone()
The objects of this class are cloneable with this method.
Usage
Contact$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
R6 class to create and represent an event
Description
R6 class to create and represent an event
R6 class to create and represent an event
Active bindings
timereturns the event time
getreturns the external pointer, which can then be passed tofunctions such as schedule and unschedule.
Methods
Public methods
Methodnew()
Usage
Event$new(time, handler)
Arguments
timethe time that this event will occur. A length-1numeric vector.
handleran R function that handles the event when it occurs.
Details
The R handler function should take exactly 3 arguments
time: the current time in the simulation
sim: the simulation object, an external pointer
agent: the agent to whom this event is attached to.
The return value of the handler function is ignored.
Methodclone()
The objects of this class are cloneable with this method.
Usage
Event$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
# This handler prints increases a counter in the state of the # Simulation object, and schedule another event every 0.1 time unit.handler = function(time, sim, agent) { x = getState(sim) x$counter = x$counter + 1 setState(sim, x) schedule(agent, newEvent(time + 0.1, handler))}# create a new simulation with no agents. but the simulation itself is# an agent. So we can use all the methods of agentsim = Simulation$new()# set the state of the simulation, initialize the countersim$state = list(counter = 0)# schedule a new event at time 0sim$schedule(Event$new(0, handler))# add a logger for the counter. Note that, because sim is an R6 class# to use it in the newStateLogger function, we need to access the # external pointer using its $get methodsim$addLogger(newStateLogger("counter", sim$get, "counter"))# run the simulation for 10 time units.print(sim$run(0:10))# interestingly, the counts are not exactly in 10 event time unit. # Firstly, report always happen before event, so event at time 0 is # not counted in the time interval 0 to 1. Secondly, the event time # is stored as a numeric value with increments of 0.1, which is # subject to rounding errors. So some the the integer tiome events# may be before the reporting and some may be after.R6 class that represents a population
Description
A population is a collection of agents. There are two important tasksfor a population:
to manage the agents in it
to define the contact patterns of the agents
The contact patterns are defined by objects of the Contact class thatare associated with the population. A population may have multipleContact objects, for example, one for random mixing, one for closecontacts represented by a contact network, and another for socialnetwork.
Super class
ABM::R6Agent ->R6Population
Active bindings
sizeThe population size, an integer
Methods
Public methods
Inherited methods
Methodnew()
Usage
Population$new(population = 0, initializer = NULL)
Arguments
populationcan be either an external pointer pointing toa population object returned from newPopulation, or an integerspecifying the population size, or a list.
initializera function or NULL
Details
If population is a number (the population size), then initializercan be a function that take the index of an agent and return its initialstate. If it is a list, the length is the population size, and each elementcorresponds to the initial state of an agent (with the same index).Add an agent
MethodaddAgent()
Usage
Population$addAgent(agent)
Arguments
agenteither an object of the R6 class Agent, or an externalpointer returned from newAgent.
Details
The agent is scheduled in the population. If the populationis already added to a simulation, the agent will report its stateto the simulation.remove an agent
Returns
the population object itself (invisible) for chaining actions
MethodremoveAgent()
Usage
Population$removeAgent(agent)
Arguments
agenteither an object of the R6 class Agent, or an externalpointer returned from newAgent.
Details
The agent is scheduled in the population. If the populationis already added to a simulation, the agent will report its stateto the simulation.Add a contact pattern
Returns
the population object itself (invisible) for chaining actions
MethodaddContact()
Usage
Population$addContact(contact)
Arguments
contactan external pointer pointing to a Contact object,e.g., created from newRandomMixing.
Details
If the contact has already been added, this call does nothing.return a specific agent by index
Methodagent()
Usage
Population$agent(i)
Arguments
ithe index of the agent (starting from 1)
Returns
an external pointer pointing to the agentset the state of a specific agent by index
MethodsetState()
Usage
Population$setState(i, state)
Arguments
ithe index of the agent (starting from 1)
statea list holding the state to set
Returns
the population object itself (invisible) for chaining actionsSet the states for the agents
MethodsetStates()
Usage
Population$setStates(states)
Arguments
stateseither a list holding the states (one for each agent), or afunction
Details
Ifstates is a function then it takes a single argumenti, specifying the index of the agent (starting from 1), and returnsa state.
Returns
the population object itself for chaining actions
Methodclone()
The objects of this class are cloneable with this method.
Usage
Population$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
R6 class Create and represent a Simulation object
Description
TheSimulation class inherits thePopulation class. So a simulationmanages agents and their contact. Thus, the class also inherits theAgent class. So a simulation can have its own state, and events attached(scheduled) to it. In addition, it also manages all the transitions, usingitsaddTransition method. ASt last, it maintains loggers, whichrecord (or count) the state changes, and report their values at specifiedtimes.
Super classes
ABM::R6Agent ->ABM::R6Population ->R6Simulation
Methods
Public methods
Inherited methods
Methodnew()
Usage
Simulation$new(simulation = 0, initializer = NULL)
Arguments
simulationcan be either an external pointer pointing toa population object returned from newSimulation, or an integerspecifying the population size, or a list
initializera function or NULL
Details
If simulation is a number (the population size), then initializercan be a function that take the index of an agent and return its initialstate. If it is a list, the length is the population size, and each elementcorresponds to the initial state of an agent (with the same index).Run the simulation
Methodrun()
Usage
Simulation$run(time)
Arguments
timethe time points to return the logger values.
Details
the returned list can be coerced into a data.frame objectwhich first column is time, and other columns are logger results,each row corresponds to a time point.
The Simulation object first collect and log the states from allagents in the simulation, then set the current time to the time ofthe first event, then call the resume method to actually run it.
Continue running the simulation
Returns
a list of numeric vectors, with time and values reportedby all logger.
Methodresume()
Usage
Simulation$resume(time)
Arguments
timethe time points to return the logger values.
Details
the returned list can be coerced into a data.frame objectwhich first column is time, and other columns are logger results,each row corresponds to a time point.
The Simulation object repetitively handle the events until the thelast time point in "time" is reached. ASt each time point, thelogger states are collected in put in a list to return.Add a logger to the simulation
Returns
a list of numeric vectors, with time and values reportedby all logger.
MethodaddLogger()
Usage
Simulation$addLogger(logger)
Arguments
logger,an external pointer returned by functions likenewCounter or newStateLogger.
Details
without adding a logger, there will be no useful simulationresults returned.Add a transition to the simulation
Returns
the simulation object itself (invisible)
MethodaddTransition()
Usage
Simulation$addTransition( rule, waiting.time, to_change_callback = NULL, changed_callback = NULL)
Arguments
ruleis a formula that gives the transition rule
waiting.timeeither an external pointer to a WaitingTime objectsuch as one returned by newExpWaitingTime or newGammaWaitingTime, ora function (see the details section)
to_change_callbackthe R callback function to determine ifthe change should occur. See the details section.
changed_callbackthe R callback function after the changehappened. See the details section.
Details
If waiting.time is a function then it should take exactly oneargument time, which is a numeric value holding the current value, andreturn a single numeric value for the waiting time (i.e., should not addtime).
Formula can be used to specify either a spontaneoustransition change, or a transition caused by a contact.
A spontaneous transition has the form from -> to, where from andto are state specifications. It is either a variable name holdinga state (R list) or the list itself. The list can also be specifiedby state(...) instead of list(...)
For a spontaneous transition, the callback functions take thefollowing two arguments
time: the current time in the simulation
agent: the agent who initiate the contact, an external pointer
A transition caused by contact, the formula needs to specify thestates of both the agent who initiate the contact and the contactagent. The two states are connected by a + sign, the one before the
sign is the initiator, and the one after the sign is the contact.The transition must be associated with a Contact object, usinga ~ operator. The Contact object must be specified by a variable namethat hold the external pointer to the object (created by e.g.,the newRandomMixing function) For example, suppose S=list("S"),I=list("I"), and m=newRandomMixing(sim), then a possible rulespecifying an infectious agent contacting a susceptible agent causingit to become exposed can bespecified by
I + S -> I + list("E") ~ m
For a transition caused by a contact, the callback functions takethe third argument:3. contact: the contact agent, an external pointer
Returns
the simulation object itself (invisible)
Methodclone()
The objects of this class are cloneable with this method.
Usage
Simulation$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
The state of an agent
Description
In this framework, a state is a list, each named component is called adomain. The value of a domain can be any R value. The list can be at mostone unnamed value, which corresponds to a domain with no name. This isuseful if there is only one domain.
Details
A state can be matched to an R list (called a rule in this case).The state matches the rule if and only if each domain (names of thelist) in rule has the same value as in state. The domains in domains of thestate not listed in rule are not matched. In addition, to match to a rule,the domain values must be either a number or a character. This is usefulfor identifying state changes. SeenewCounter() andtheSimulation class'addTransition method for more details.
add an agent to a population
Description
add an agent to a population
Arguments
population | an external pointer to a population, for example,one returned by |
agent | an external pointer to an agent, returned by |
Details
if the agent is an R6 class, we should useagent$get to getthe external pointer. Similarly, if population is an R6 object, then weshould either usepopulation$addAgent() orpopulation$get.
Unschedule all event from an agent
Description
Unschedule all event from an agent
Arguments
agent | an external pointer returned by newAgent |
Details
If agent is an R6 object, then we should use eitheragent$clearEvents() or clearEvents(agent$get)
Get the agent at an index in the population
Description
Get the agent at an index in the population
Arguments
population | an external pointer to a population, for example,one returned by |
i | the index of the agent, starting from 1. |
Value
the agent at index i in the population.
Get the ID of the agent.
Description
Get the ID of the agent.
Arguments
agent | an external pointer returned by newAgent |
Details
Before an agent is added to a population, its id is 0.After it is added, its id is the index in the population(starting from 1).
If agent is an R6 object, then we should either useagent$id,or usegetID(agent$get)
Value
an integer value
Get the size of a population
Description
Get the size of a population
Arguments
population | an external pointer to a population, for example,one returned by |
Value
the population size, an integer
Get the state of the agent
Description
Get the state of the agent
Arguments
agent | an external pointer returned by newAgent |
Details
If agent is an R6 object, then we should either use agent$schedule,or use schedule(agent$get, event)
Value
a list holding the state
returns the event time
Description
returns the event time
Arguments
event | an external pointer returned by the newEvent function. |
Value
a numeric value
This function avoids the overhead of an R6 class, and is thus faster.This is the recommended method to get event time in an event handler.
Generate a waiting time from an WaitingTime object
Description
Generate a waiting time from an WaitingTime object
Arguments
generator | an external pointer to a WaitingTime object, e.g.,one returned by newExpWaitingTime or newGammaWaitingTime |
time | the current simulation time, a numeric value |
Value
a numeric value
leave the population that the agent is in
Description
leave the population that the agent is in
Arguments
agent | an external pointer returned by newAgent |
Details
If agent is an R6 object, then we should use eitheragent$leave() or leave(agent$get)
Check if the state of an agent matches a given state
Description
Check if the state of an agent matches a given state
Usage
matchState(agent, rule)Arguments
agent | an external pointer returned by newAgent |
rule | a list holding the state to match against |
Details
This function is equivalent tostateMatch(getState(agent), rule)
The state matches the rule if and only if each domain (names of thelist) in rule has the same value as in state. The domains in domains of thestate not listed in rule are not matched
Value
a logical value
Create an agent with a given state
Description
Create an agent with a given state
Arguments
state | a list giving the initial state of the agent, or NULL (an emptylist) |
death_time | the death time for the agent, an optional numeric value. |
Details
Setting death_time is equivalent to calling thesetDeathTime()function.
Value
an external pointer pointing to the agent
Creates a random network using the configuration model
Description
Creates a random network using the configuration model
Arguments
rng | a function that generates random degrees |
Details
The population must be an external pointer, not an R6 objectTo use an R6 object, we should use its pointer representation from its$get method.
The function rng should take exactly one argument n for the number of degreesto generate, and should return an integer vector of length n.
Value
an external pointer.
Examples
# creates a simulation with 100 agentssim = Simulation$new(100)# add a Poisson network with a mean degree 5sim$addContact(newConfigurationModel(function(n) rpois(n, 5)))Create a logger of the Counter class
Description
When state changes occur, it is passed to each logger, which thenchange its value. At the specified time points in a run, thevalues of the logger are reported and recorded in a data.frame object,where the columns represent variables, and rows represent theobservation at each time point given to each run. Each logger has aname, which becomes the the column name in the data.frame.
Arguments
name | the name of the counter, must be a length-1 character vector |
from | a list specifying state of the agent, or a character or numericvalue that is equivalent to list(from). please see the details section |
to | a list (can be NULL) specifying the state of the agent after thestate change, or a character or numeric value that is equivalent tolist(from). please see the details section |
initial | the initial value of the counter. Default to 0. |
Details
if the argument "to" is not NULL, then the counter counts thetransitions from "from" to "to". Otherwise, it counts the number of agentsin a state that matches the "from" argument. Specifically, if the agentjumps to "from", then the count increases by 1. If the agents jumps awayfrom "from", then the count decreases by 1.
Value
an external pointer that can be passed to theSimulation class'$addLogger.
Creates a new event in R
Description
Creates a new event in R
Arguments
time | the time that this event will occur. A length-1numeric vector. |
handler | an R function that handles the event when it occurs. |
Details
The R handler function should take exactly 3 arguments
time: the current time in the simulation
sim: the simulation object, an external pointer
agent: the agent to whom this event is attached to.
The return value of the handler function is ignored.
This function avoids the overhead of an R6 class, and is thus faster.This is the recommended method to create an event in an event handler.
Value
an external pointer, which can then be passed tofunctions such as schedule and unschedule.
Creates an exponentially distributed waiting time
Description
Creates an exponentially distributed waiting time
Arguments
rate | the rate of the exponential distribution |
Details
This function creates an C++ object of type ExpWaitingTime.It can be passed to addTransition or Simulation$addTransition tospecify the waiting time for a transition. As a C++ object, it is fasterthan using an R function to generate waiting times because there isno need to call an R function from C++.
Value
an external pointer
Creates an gamma distributed waiting time
Description
Creates an gamma distributed waiting time
Arguments
shape | the shape parameter of the gamma distribution |
scale | the scale parameter of the gamma distribution, i.e., 1/rate |
Details
This function creates an C++ object of type ExpWaitingTime.It can be passed to addTransition or Simulation$addTransition tospecify the waiting time for a transition. As a C++ object, it is fasterthan using an R function to generate waiting times because there isno need to call an R function from C++.
Value
an external pointer
Create a new population
Description
Create a new population
Arguments
n | an integer specifying the population size. |
Details
The population will be created with "n" individuals in it.These individuals have an empty state upon created. Note thatindividuals can be added later by the "add" method, the initialpopulation size is for convenience, not required
Creates a RandomMixing object
Description
Creates a RandomMixing object
Value
an external pointer.
Examples
# creates a simulation with 100 agentssim = Simulation$new(100)# add a random mixing contact pattern for these agents.sim$addContact(newRandomMixing())Create a logger of the StateLogger class
Description
When state changes occur, it is passed to each logger, which thenchange its value. At the specified time points in a run, thevalues of the logger are reported and recorded in a data.frame object,where the columns represent variables, and rows represent theobservation at each time point given to each run. Each logger has aname, which becomes the the column name in the data.frame.
Arguments
name | the name of the logger. A length-1 character vector |
agent | the agent whose state will be logged. An external pointer |
state.name | the state name of the state of the agent to be logged.A character vector of length 1. |
Details
If a state changed happened to any agent, the specified stateof the agent given by the "agent" argument will be logged. Ifstate.name==NULL then the state of the agent who just changed islogged.
The agent must be an external pointer. To use an R6 object, we needto use its $get method to get the external pointer.
The state to be logged must have a numeric value.
Schedule (attach) an event to an agent
Description
Schedule (attach) an event to an agent
Arguments
agent | an external pointer returned by newAgent |
event | an external pointer returned by newEvent |
Details
If agent is an R6 object, then we should use eitheragent$schedule(event) or schedule(agent$get, event)
Similarly, if event is an R6 object, then we should useschedule(agent, event$get)
set the time of death for an agent
Description
set the time of death for an agent
Arguments
agent | an external pointer returned by |
time | the time of death, a numeric value |
Details
If agent is an R6 object, then we should use eitheragent$leave() or leave(agent$get)
At the time of death, the agent is removed from the simulation. Calling itmultiple times causes the agent to die at the earliest time.
Set the state of the agent
Description
Set the state of the agent
Arguments
agent | an external pointer returned by newAgent |
state | an R list giving the components of the state to beundated. |
Details
In this framework, a state is a list, each namedcomponent is called a domain. This function only updates thevalues of the domain given in the "value" list, while leave theother components not in the "value" list unchanged.
If agent is an R6 object, then we should either use agent$schedule,or use schedule(agent$get, event)
Set the state for each agent in a population
Description
Set the state for each agent in a population
Arguments
population | an external pointer to a population, for example,one returned by |
states | either a list holding the states (one for each agent), or afunction |
Details
Ifstates is a function then it takes a single argumenti, specifying the index of the agent (starting from 1), and returnsa state.
Check if two states match
Description
Check if two states match
Arguments
state | a list holding a state to check |
rule | a list holding the state to match against |
Details
The state matches the rule if and only if each domain (names of thelist) in rule has the same value as in state. The domains in domains of thestate not listed in rule are not matched
Value
a logical value
Unschedule (detach) an event from an agent
Description
Unschedule (detach) an event from an agent
Arguments
agent | an external pointer returned by newAgent |
event | an external pointer returned by newEvent |
Details
If agent is an R6 object, then we should use eitheragent$unschedule(event) or unschedule(agent$get, event)
Similarly, if event is an R6 object, then we should useunschedule(agent, event$get)