-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimer.R
More file actions
341 lines (319 loc) · 10.9 KB
/
Copy pathTimer.R
File metadata and controls
341 lines (319 loc) · 10.9 KB
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
#' Timer: Track timed events and apply condition-triggered analyses
#'
#' @description
#' A class to collect and query _timepoints_, time-based events, across arms.
#' Timer class also supports conditions that filter data using [dplyr::filter()]
#' and apply custom analyses.
#'
#' Use `add_timepoint()` to append timepoints, `get_timepoint()` for a lookup,
#' and `check_conditions()` to filter a data frame based on a trigger condition
#' and return either analysis results or the filtered data.
#'
#' @details
#' Helper functions [trigger_by_calendar()] and [trigger_by_fraction()] provide
#' convenient shortcuts for common trigger patterns.
#'
#' @seealso [Trial] to coordinate simulations with populations, [add_timepoints()]
#' to attach multiple timepoints, [dplyr::filter()] for condition syntax.
#'
#' @examples
#' # Basic construction
#' t <- Timer$new(name = "Timer")
#'
#' # Add timepoints
#' t$add_timepoint(time = 1, arm = "A", dropper = 2L, enroller = 10L)
#' t$add_timepoint(time = 2, arm = "A", dropper = 1L, enroller = 12L)
#' t$add_timepoint(time = 1, arm = "B", dropper = 0L, enroller = 8L)
#'
#' # Query
#' t$get_end_timepoint() # max time => 2
#' t$get_n_arms() # unique arms => 2
#' t$get_unique_times() # unique times => c(1, 2)
#' t$get_timepoint("A", 1) # returns a single timepoint
#'
#' # Add conditions using trigger helpers or dplyr style
#' # Suppose you have a data.frame:
#' df <- data.frame(
#' id = 1:6,
#' arm = c("A", "A", "B", "B", "A", "B"),
#' status = c("active", "inactive", "active", "active", "inactive", "active"),
#' visit = c(1, 2, 1, 3, 3, 2)
#' )
#'
#' # Analysis function: count rows at/after a given visit, per arm
#' my_analysis <- function(dat, current_time) {
#' out <- aggregate(id ~ arm, dat, length)
#' out$current_time <- current_time
#' out
#' }
#'
#' # Or add conditions manually with dplyr style
#' # Condition: arm A, visit >= 2, no analysis -> returns filtered df
#' t$add_condition(
#' arm == "A", visit >= 2,
#' name = "armA_visit2plus"
#' )
#'
#' # Run checks
#' res <- t$check_conditions(locked_data = df, current_time = 3)
#' names(res)
#'
#' @importFrom rlang enquos
#' @importFrom dplyr filter
#' @export
Timer <- R6::R6Class(
classname = "Timer",
public = list(
# --- fields ---
#' @field name `character` Unique identifier for the `Timer` instance.
name = NULL,
#' @field timelist `list` A list of timepoints. Each timepoint is a list with keys:
#' - `time` `numeric` Calendar time
#' - `arm` `character` Unique identifier of the arm
#' - `dropper` `integer` # of subjects dropper at `time`
#' - `enroller` `integer` # of subjects enrolled at `time`
timelist = NULL,
#' @field conditions `list` A list of condition entries. Each entry is a list with keys:
#' - `where` `expr` filter conditions in [dplyr::filter()] style
#' - `analysis` `function` or `NULL` analysis applied to filtered data
#' - `name` `character` or `NULL` unique key for the condition
conditions = NULL,
# --- constructor ---
#' @description
#' Create a new `Timer` instance.
#'
#' @param name `character` Unique identifier.
#' @param timelist `list` Optional list of timepoints.
#' @param conditions `list` Optional list of condition entries.
#'
#' @return A new `Timer` instance.
#'
#' @examples
#' t <- Timer$new(name = "Timer")
initialize = function(
name,
timelist = NULL,
conditions = NULL
) {
stopifnot(is.character(name))
self$name <- name
self$timelist <- if (is.null(timelist)) list() else timelist
self$conditions <- if (is.null(conditions)) list() else conditions
},
# --- methods ---
#' @description
#' Add a timepoint to a timer.
#'
#' @param time `numeric` Calendar time.
#' @param arm `character` Arm identifier.
#' @param dropper `integer` Count of subjects to drop.
#' @param enroller `integer` Count of subjects to enroll.
#'
#' @examples
#' t <- Timer$new(name = "Timer")
#' t$add_timepoint(
#' time = 1,
#' arm = "A",
#' dropper = 1L,
#' enroller = 3L
#' )
add_timepoint = function(time, arm, dropper, enroller) {
stopifnot(is.integer(dropper), is.integer(enroller))
tp <- list(time = time, arm = arm, dropper = dropper, enroller = enroller)
self$timelist <- append(self$timelist, list(tp))
invisible(self)
},
#' @description
#' Add a trigger condition to a timer.
#'
#' @param ... `expression` Boolean expression(s) for `dplyr::filter()`.
#' @param analysis `function` or `NULL` Optional function to apply.
#' @param name `character` Unique condition identifier.
#'
#' @examples
#' #' t <- Timer$new(name = "Timer")
#'
#' # Add timepoints
#' t$add_timepoint(time = 1, arm = "A", dropper = 2L, enroller = 10L)
#'
#' # Add conditions using `dplyr` style
#' # Suppose you have a data.frame:
#' df <- data.frame(
#' id = 1:6,
#' arm = c("A","A","B","B","A","B"),
#' status = c("active","inactive","active","active","inactive","active"),
#' visit = c(1,2,1,3,3,2)
#' )
#'
#' # Analysis function: count rows at/after a given visit, per arm
#' my_analysis <- function(dat, current_time) {
#' out <- aggregate(id ~ arm, dat, length)
#' out$current_time <- current_time
#' out
#' }
#'
#' # Condition 1: active only
#' t$add_condition(
#' status == "active",
#' analysis = my_analysis,
#' name = "active_only"
#' )
add_condition = function(
...,
analysis = NULL,
name = NULL
) {
# Capture filter predicates as quosures (with caller env)
where_quos <- rlang::enquos(..., .named = FALSE)
cond <- list(
where = where_quos,
analysis = analysis,
name = name
)
self$conditions <- append(self$conditions, list(cond))
invisible(self)
},
#' @description
#' Determine the last timepoint for a given instance of `Timer` class.
#'
#' @examples
#' t <- Timer$new(name = "Timer")
#' t$add_timepoint(time = 3.14, arm = "A", dropper = 7L, enroller = 22L)
#' t$get_end_timepoint()
get_end_timepoint = function() {
max(sapply(self$timelist, function(x) {
x$time
}))
},
#' @description
#' Get number of unique arms.
#'
#' @return `integer` Number of unique arms.
#'
#' @examples
#' t <- Timer$new(name = "Timer")
#' t$add_timepoint(time = 3.14, arm = "A", dropper = 7L, enroller = 22L)
#' t$add_timepoint(time = 3.28, arm = "B", dropper = 6L, enroller = 23L)
#' t$get_n_arms()
get_n_arms = function() length(unique(sapply(self$timelist, function(x) x$arm))),
#' @description
#' Get unique timepoints.
#'
#' @return `numeric` vector of unique times.
#'
#' @examples
#' t <- Timer$new(name = "Timer")
#' t$add_timepoint(time = 3.14, arm = "A", dropper = 7L, enroller = 22L)
#' t$add_timepoint(time = 3.28, arm = "B", dropper = 6L, enroller = 23L)
#' t$get_unique_times()
get_unique_times = function() unique(sapply(self$timelist, function(x) x$time)),
#' @description
#' Get a timepoint by arm and index.
#'
#' @param arm `character` Arm identifier.
#' @param i `integer` Timepoint index.
#'
#' @return `list` timepoint or `NULL` if not found.
#'
#' @examples
#' t <- Timer$new(name = "Timer")
#' t$add_timepoint(time = 3.14, arm = "A", dropper = 7L, enroller = 22L)
#' t$add_timepoint(time = 3.28, arm = "B", dropper = 6L, enroller = 23L)
#'
#' t$get_timepoint("A", 1)
get_timepoint = function(arm, i) {
# Basic validation
if (missing(arm)) stop("`arm` is required.")
if (missing(i)) stop("`i` is required.")
# Extract columns from list with type safety
times <- vapply(self$timelist, function(x) x$time, FUN.VALUE = numeric(1))
arms <- vapply(self$timelist, function(x) x$arm, FUN.VALUE = character(1))
# Find matching indices
idx <- which(times == i & arms == arm)
# Handle match outcomes
if (length(idx) == 0L) {
return(NULL)
}
if (length(idx) > 1L) {
stop(sprintf("Multiple timepoints found for arm = %s and time = %s.", arm, as.character(i)))
}
self$timelist[[idx]]
},
#' @description
#' Check conditions and return filtered data or analysis results.
#'
#' @param locked_data `data.frame` Trial data.
#' @param current_time `numeric` Calendar time.
#'
#' @return `list` of filtered data or analysis results per condition.
#'
#' @examples
#' #' t <- Timer$new(name = "Timer")
#'
#' # Add timepoints
#' t$add_timepoint(time = 1, arm = "A", dropper = 2L, enroller = 10L)
#' t$add_timepoint(time = 2, arm = "A", dropper = 1L, enroller = 12L)
#' t$add_timepoint(time = 1, arm = "B", dropper = 0L, enroller = 8L)
#'
#' # Query
#' t$get_end_timepoint() # max time => 2
#' t$get_n_arms() # unique arms => 2
#' t$get_unique_times() # unique times => c(1, 2)
#' t$get_timepoint("A", 1) # returns a single timepoint
#'
#' # Add conditions using dplyr style
#' # Suppose you have a data.frame:
#' df <- data.frame(
#' id = 1:6,
#' arm = c("A","A","B","B","A","B"),
#' status = c("active", "inactive", "active", "active", "inactive", "active"),
#' visit = c(1,2,1,3,3,2)
#' )
#'
#' # Analysis function: count rows at/after a given visit, per arm
#' my_analysis <- function(dat, current_time) {
#' out <- aggregate(id ~ arm, dat, length)
#' out$current_time <- current_time
#' out
#' }
#'
#' # Condition: active only
#' t$add_condition(
#' status == "active",
#' analysis = my_analysis,
#' name = "active_only"
#' )
check_conditions = function(
locked_data,
current_time
) {
stopifnot(is.data.frame(locked_data))
results <- list()
for (i in seq_along(self$conditions)) {
cond <- self$conditions[[i]]
key <- ifelse(
!is.null(cond$name) && nzchar(cond$name),
cond$name,
i
)
# Per-reader filtering (dplyr semantics: NA in predicates drops rows)
df_i <- if (!is.null(cond$where) && length(cond$where) > 0) {
dplyr::filter(locked_data, !!!cond$where)
} else {
locked_data
}
if (nrow(df_i) == 0L) {
#warning(sprintf("Skipping condition '%s' at time %s: filtered data is empty", key, as.character(current_time)), call. = FALSE)
next
}
if (is.function(cond$analysis)) {
results[[key]] <- cond$analysis(df_i, current_time)
} else {
results[[key]] <- df_i
warning(sprintf(" returning filtered data as is because condition '%s' has no applicable analysis \n", key), call. = FALSE)
}
}
results
}
) # end public
) # end class