run_simulation: Run a simulation loop

View source: R/run_simulation.R

run_simulationR Documentation

Run a simulation loop

Description

A generic function to run a simulation loop for a fixed period of time. This function can cope with model step functions that return an updated data frame, or functions that return a list with an end.experiment element and an updated.pop element. If the simulation isn't working you can set debug = TRUE in the arguments, and it will print some (potentially) useful debugging information while it runs. It will also check whether your function has any global variables.

Usage

run_simulation(step_function, initial.pop, end.time, debug = FALSE, ...)

Arguments

step_function

Function to run a timestep (step_function()) which returns a list containing elements updated.pop with the updated population and end.experiment which is TRUE if the experiment has ended (FALSE if not), OR which just returns a data frame with the updated population

initial.pop

Initial population data frame with columns corresponding to function requirements. This *must* include a time column so that run_simple() can check whether the end.time has been reached.

end.time

End time of simulation

debug

(optionally) do you want to print out a limited amount of debugging information about your code? - default FALSE

...

(optionally) any other arguments for step_function(), e.g. parameters or timestep

Value

Data frame containing population history of simulation over time

See Also

run_simple if you want a much simpler but more restrictive version of the simulation code that may be useful for better understanding how the function works.

Examples

growth <- function(latest.df, growth.rate) {
current.count <- latest.df$count
growth.num <- current.count * growth.rate
next.count <- current.count + growth.num
next.time <- latest.df$time + 1
new.df <- data.frame(time=next.time, count=next.count)
finished <- next.count == 0
list(updated.pop=new.df, end.experiment=finished)
}
df <- data.frame(time=0, count=1)
results <- run_simulation(growth, df, 100, growth.rate=0.1, debug=TRUE)
plot_populations(results)


IBAHCM/RPiR documentation built on Jan. 12, 2023, 7:41 p.m.