/
simulation-methods.R
356 lines (297 loc) · 11.1 KB
/
simulation-methods.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
#######################################################################
### Modified from Matloff (2009): ###
### - uses S4 classes for the sim objects ###
### - uses `data.table` instead of `data.frame` ###
### - implemented in a more modular fashion so it's easier ###
### to add submodules to the simulation ###
#######################################################################
###
### SimList and SimData methods
###
# initialize methods
setMethod("initialize",
signature = "SimList",
definition = function(.Object) {
sim.events(.Object) = as.data.table(NULL)
sim.time(.Object) = 0.0
sim.debug(.Object) = FALSE
return(.Object)
})
setMethod("initialize",
signature = "SimData",
definition = function(.Object) {
return(.Object)
})
### show is already defined in the methods package
#' @title Show an Object
#' @name show
#' @rdname show-methods
#' @aliases show,SimList
#' @importMethodsFrom methods show
#' @export
#'
setMethod("show",
signature = "SimList",
definition = function(object) {
show = list()
# show[["Modules Required:"]] = as.character(sim.modules(object))
# show[["Modules Loaded:"]] = as.character(sim.loaded(object))
# show[["Simulation Parameters:"]] = as.data.frame(sim.params(object))
# show[["Current Simulation Time:"]] = sim.time(object)
# show[["Next 5 Scheduled Events:"]] = head(sim.events(object), 5)
# show[["Debugging Mode:"]] = sim.debug(object)
show[["Modules Required:"]] = as.character(slot(object, "modules"))
show[["Modules Loaded:"]] = as.character(slot(object, ".loaded"))
show[["Simulation Parameters:"]] = as.data.frame(slot(object, "params"))
show[["Current Simulation Time:"]] = slot(object, "simtime")
show[["Next 5 Scheduled Events:"]] = head(slot(object, "events"), 5)
show[["Debugging Mode:"]] = slot(object, "debug")
print(show)
})
#' @rdname show-methods
#' @aliases show,SimData
#' @importMethodsFrom methods show
#' @export
setMethod("show",
signature = "SimData",
definition = function(object) {
show = list()
show[["Agents:"]] = slot(object, "agents")
show[["Maps:"]] = slot(object, "maps")
show[["Stats:"]] = slot(object, "stats")
print(show)
})
### get slot values using `slot(object, "slotname")`
### set slot values using `slot(object, "slotname") <- value`
# accessor methods for SimList slots
setGeneric("sim.modules", function(object) {
standardGeneric("sim.modules")
})
setMethod("sim.modules",
signature = "SimList",
definition = function(object) {
return(object@modules)
})
setGeneric("sim.modules<-",
function(object, value) {
standardGeneric("sim.modules<-")
})
setReplaceMethod("sim.modules",
signature="SimList",
function(object, value) {
object@modules <- value
validObject(object)
return(object)
})
setGeneric("sim.loaded", function(object) {
standardGeneric("sim.loaded")
})
setMethod("sim.loaded",
signature = "SimList",
definition = function(object) {
return(object@.loaded)
})
setGeneric("sim.loaded<-",
function(object, value) {
standardGeneric("sim.loaded<-")
})
setReplaceMethod("sim.loaded",
signature="SimList",
function(object, value) {
object@.loaded <- value
validObject(object)
return(object)
})
setGeneric("sim.params", function(object) {
standardGeneric("sim.params")
})
setMethod("sim.params",
signature = "SimList",
definition = function(object) {
return(object@params)
})
setGeneric("sim.params<-",
function(object, value) {
standardGeneric("sim.params<-")
})
setReplaceMethod("sim.params",
signature="SimList",
function(object, value) {
object@params <- value
validObject(object)
return(object)
})
setGeneric("sim.time", function(object) {
standardGeneric("sim.time")
})
setMethod("sim.time",
signature = "SimList",
definition = function(object) {
return(object@simtime)
})
setGeneric("sim.time<-",
function(object, value) {
standardGeneric("sim.time<-")
})
setReplaceMethod("sim.time",
signature="SimList",
function(object, value) {
object@simtime <- value
validObject(object)
return(object)
})
setGeneric("sim.events", function(object) {
standardGeneric("sim.events")
})
setMethod("sim.events",
signature = "SimList",
definition = function(object) {
return(object@events)
})
setGeneric("sim.events<-",
function(object, value) {
standardGeneric("sim.events<-")
})
setReplaceMethod("sim.events",
signature="SimList",
function(object, value) {
object@events <- value
validObject(object)
return(object)
})
setGeneric("sim.debug", function(object) {
standardGeneric("sim.debug")
})
setMethod("sim.debug",
signature = "SimList",
definition = function(object) {
return(object@debug)
})
setGeneric("sim.debug<-",
function(object, value) {
standardGeneric("sim.debug<-")
})
setReplaceMethod("sim.debug",
signature="SimList",
function(object, value) {
object@debug <- value
validObject(object)
return(object)
})
check.path = function(path) {
if (is.character(path)) {
if (file.exists(path)) {
# basically, do nothing if it exists
exists = TRUE
} else {
# warn the user before creating the directory
print("Warning: the path you specified doesn't exist.")
print(paste("Creating directory structure:", path))
dir.create(file.path(path), recursive=TRUE, showWarnings=FALSE)
}
} else {
stop("Error: `path` should be specified as a character string.")
}
# check to make sure path has a trailing slash
# if not, add one
strlets <- strsplit(path, "")[[1]]
strlen <- length(strlets)
if (strlets[strlen]!="/") path <- paste(path, "/", sep="")
return(path)
}
###
### initializes simulation variables
###
sim.init <- function(params, modules, path) {
path <- check.path(path)
sim <<- new("SimList")
# load simulation parameters and modules
sim.params(sim) <<- params
sim.modules(sim) <<- modules # this should be a list of module names that will be loaded
for (m in modules) {
source(paste(path, m, ".R", sep="")) # source each module from file
}
# set up first event(s): all first events should be initialization events e.g. from modules
# schedule.event(EVENT.TIME, "MODULE.NAME", "EVENT.TYPE", list(OPTIONAL.ITEMS))
for (m in modules) {
schedule.event(0.00, m, "init")
}
}
# print results of simulation
print.results <- function(modules, debug) {
# THIS NEEDS ATTENTION!!
# it should print all global and module-specific stats.
# it should print these to file unless in debug mode
print("Hi there, I don't do anything yet. Sorry!")
###
### the way this is set up currently likely will (should) change:
### - outputs are schedules events;
### - all module outputs should be scheduled in the modules;
### - need method defs for `print()` of class `SimData`.
###
}
# event processing function called by dosim() below
do.event <- function(head) {
# instead of having a massive list of ifelse cases for each event type,
# we should have the cases processed by the submodule;
# this makes things more modular, since we can add/remove modules without
# having to worry about updating this (hardcoded) list.
module.call <- paste("do.event", head$module.name, sep=".")
# check.validity(module.call) # do it here, otherwise user must do it
# per module in the do.event function?
get(module.call)(head$event.time, head$event.type)
# e.g., this would produce the following call to the fire module:
# do.event.fire(TIME, "TYPE")
}
# insert event with time `time.event` and type `type.event` into event list;
# other.info is an optional set of application-specific traits of this event,
# specified in the form a list with named components
schedule.event <- function(event.time, module.name, event.type) {
new.event <- as.data.table(list(event.time=event.time,
module.name=module.name,
event.type=event.type))
# if the event list is empty, set it to consist of evnt and return
if (length(sim.events(sim))==0) {
sim.events(sim) <<- new.event
return()
}
# otherwise, "insert" by reconstructing the data frame;
# find what portion of the current matrix should come before the new event,
# and what portion should come after it, then bind everything together.
before <- sim.events(sim)[event.time<=new.event$event.time[1]]
after <- sim.events(sim)[event.time>new.event$event.time[1]]
revised.list <- rbindlist(list(before,new.event,after))
sim.events(sim) <<- setkey(revised.list, event.time)
}
# start to process next event;
# second half done by application programmer via call to `do.event()`
get.next.event <- function() {
head <- sim.events(sim)[1,]
# delete head
sim.events(sim) <<- sim.events(sim)[-1,]
return(head)
}
#####################################################################################
# simulation body, takes the following arguments:
# params: list of application-specific parameters.
# modules: list of module names used in the simulation.
# maxsimtime: simulation will be run until this simulated time.
# debug: logical flag determines whether sim debug info will be printed.
dosim <- function(maxsimtime, params=list(), modules=list(), path="./", debug=FALSE) {
# initialize the simulation
sim.init(params, modules, path=path)
# run the discrete event simulation
while(sim.time(sim) < maxsimtime) {
head <- get.next.event()
sim.time(sim) <<- head$event.time # update current simulated time
do.event(head) # process this event
# print debugging info
# this can, and should, be more sophisticated;
# i.e., don't simply print the entire object
if (debug) {
print(sim)
}
}
# print simulation results
print.results(modules, debug)
}