-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCondition.R
More file actions
293 lines (266 loc) · 11.3 KB
/
Condition.R
File metadata and controls
293 lines (266 loc) · 11.3 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
.trigger_to_quosures <- function(trigger) {
if (!is.null(trigger$type)) {
expr <- if (identical(trigger$type, "value")) {
call(trigger$op, call("[[", quote(.data), trigger$col), trigger$rhs)
} else {
call(trigger$op,
call("sum", call("!", call("is.na", call("[[", quote(.data), trigger$col)))),
trigger$rhs)
}
return(list(rlang::new_quosure(expr, env = rlang::current_env())))
}
if (identical(trigger$combinator, "&")) {
return(unlist(lapply(trigger$predicates, .trigger_to_quosures), recursive = FALSE))
}
left_quos <- .trigger_to_quosures(trigger$left)
right_quos <- .trigger_to_quosures(trigger$right)
expr <- call("|", rlang::get_expr(left_quos[[1L]]), rlang::get_expr(right_quos[[1L]]))
list(rlang::new_quosure(expr, env = rlang::current_env()))
}
#' Condition: Stateful trigger and analysis unit
#'
#' @description
#' A `Condition` encapsulates a single trigger rule that is evaluated against
#' a data snapshot at each simulated timepoint. It combines three concerns:
#'
#' \enumerate{
#' \item **Filtering** — a `dplyr::filter()` expression selects the rows
#' relevant to this condition (e.g. "only enrolled subjects in arm A").
#' \item **Analysis** — an optional function transforms the filtered snapshot
#' into a result (e.g. a t-test, a subject count, a Go/No-Go decision).
#' \item **Trigger bookkeeping** — the condition fires only when the
#' filtered data is non-empty, the cooldown period has elapsed since the
#' last trigger, and the maximum trigger count has not been reached.
#' }
#'
#' `Condition` objects are stored in `trial$conditions` and evaluated by
#' [`Trial`]`$run()` at each timepoint.
#'
#' @details
#' **Three-gate logic.** A trigger fires only when all three gates pass:
#' \enumerate{
#' \item The filtered snapshot contains at least one row.
#' \item `current_time - last_trigger_time >= cooldown` (or the condition
#' has never fired before).
#' \item `trigger_count < max_triggers`.
#' }
#' If any gate fails, `check_conditions()` returns an empty list and state
#' is not updated.
#'
#' On a successful trigger, the condition calls
#' `analysis(df, current_time, ...)` and stores the result under
#' `name` (or `1L` when no name is set). Any values in `analysis_args` are
#' appended as additional named arguments. If no analysis function is
#' provided, the filtered data frame is returned as-is with a warning.
#'
#' @section Fields:
#' \describe{
#' \item{\code{where}}{`list` of quosures (from `rlang::quos()`) used as
#' `dplyr::filter()` predicates. Pass `NULL` or an empty list to skip
#' filtering and pass the full snapshot to the analysis.}
#' \item{\code{analysis}}{`function` or `NULL`. Called as
#' `analysis(df, current_time, ...)` on a successful trigger, where `...`
#' are any values from `analysis_args`. Should return a `data.frame` or
#' named list. If `NULL`, the filtered data frame is returned with a warning.}
#' \item{\code{analysis_args}}{`list` or `NULL`. Named list of extra arguments
#' injected into every call to `analysis`.}
#' \item{\code{name}}{`character` or `NULL`. Key used to label the result
#' in the returned list. Falls back to `1L` when `NULL`.}
#' \item{\code{cooldown}}{`numeric`. Minimum time units that must elapse
#' between consecutive triggers. Default `0` (no cooldown).}
#' \item{\code{max_triggers}}{`integer`. Maximum number of times this
#' condition may fire. Use `Inf` for unlimited. Default `1L`.}
#' \item{\code{trigger_count}}{`integer`. Number of successful triggers so
#' far. Initialised to `0L`.}
#' \item{\code{last_trigger_time}}{`numeric`. Calendar time of the most
#' recent successful trigger. Initialised to `NA_real_`.}
#' }
#'
#' @section Methods:
#' \describe{
#' \item{\code{$new(where, analysis, name, cooldown, max_triggers)}}{
#' Construct a new `Condition`. All arguments except `where` are
#' optional. `cooldown` must be a single non-negative number;
#' `max_triggers` must be a single non-negative integer or `Inf`.}
#' \item{\code{$check_conditions(locked_data, current_time)}}{
#' Evaluate the condition against `locked_data` at `current_time`.
#' Returns a named `list` containing the analysis result (or filtered
#' data frame) if the condition fires, or an empty `list` otherwise.
#' On a successful trigger, `trigger_count` is incremented and
#' `last_trigger_time` is updated.}
#' }
#'
#' @seealso
#' \itemize{
#' \item [`Timer`] for managing trial timepoints
#' \item [`Trial`] for running the simulation and iterating over conditions
#' \item [`trigger_by_calendar()`] and [`trigger_by_fraction()`] for
#' convenient `Condition` constructors
#' \item [value_trigger()], [count_trigger()], [enroll_trigger()],
#' [calendar_trigger()] for building safe trigger specifications
#' \item [`dplyr::filter()`] for predicate syntax
#' }
#'
#' @examples
#' # Build a snapshot data frame
#' snapshot <- data.frame(
#' arm = c("A", "A", "A", "B"),
#' status = c("active", "active", "active", "active"),
#' stringsAsFactors = FALSE
#' )
#'
#' # Analysis function: count active subjects per arm
#' count_fn <- function(df, current_time) {
#' data.frame(n_active = nrow(df), fired_at = current_time)
#' }
#'
#' # Condition fires once when arm A has active subjects (max_triggers = 1)
#' cond <- Condition$new(
#' where = rlang::quos(arm == "A", status == "active"),
#' analysis = count_fn,
#' name = "interim_A",
#' cooldown = 0,
#' max_triggers = 1L
#' )
#'
#' # First call: fires and returns analysis result
#' res <- cond$check_conditions(snapshot, current_time = 5)
#' res[["interim_A"]] # data.frame(n_active = 3, fired_at = 5)
#'
#' # Second call: does not fire (max_triggers already reached)
#' res2 <- cond$check_conditions(snapshot, current_time = 6)
#' length(res2) # 0
#'
#' @importFrom dplyr filter
#' @export
Condition <- R6::R6Class(
classname = "Condition",
public = list(
# --- fields ---
#' @field where `list` of quosures (`rlang::quos()`) used as `dplyr::filter()`
#' predicates, or an `rxsim_trigger` (converted automatically). `NULL` or
#' empty list passes the full snapshot.
where = NULL,
#' @field analysis `function` or `NULL`. Called as
#' `analysis(df, current_time, ...)` on a successful trigger, where `...`
#' are any values from `analysis_args`.
analysis = NULL,
#' @field analysis_args `list` or `NULL`. Named list of extra values injected
#' into the analysis function call as additional named arguments.
analysis_args = NULL,
#' @field name `character` or `NULL`. Key labelling the result in the output
#' list. Falls back to `1L` when `NULL`.
name = NULL,
#' @field cooldown `numeric`. Minimum time units between consecutive
#' triggers. Default `0`.
cooldown = 0,
#' @field max_triggers `integer` or `Inf`. Maximum number of times this
#' condition may fire. Default `1L`.
max_triggers = 1L,
#' @field trigger_count `integer`. Number of successful triggers so far.
#' Initialised to `0L`.
trigger_count = 0L,
#' @field last_trigger_time `numeric`. Calendar time of the most recent
#' successful trigger. `NA_real_` until first trigger.
last_trigger_time = NA_real_,
# --- constructor ---
#' @description
#' Create a new `Condition` instance.
#'
#' @param where `rxsim_trigger` (converted automatically to quosures), a
#' `list` of quosures from `rlang::quos()`, or `NULL` to use the full
#' snapshot.
#' @param analysis `function` or `NULL`. Called as
#' `analysis(df, current_time, ...)` on a successful trigger, where `...`
#' are the values from `analysis_args`.
#' @param analysis_args `list` or `NULL`. Named list of extra arguments
#' passed to the analysis function after `df` and `current_time`.
#' @param name `character` or `NULL`. Result key. Defaults to `1L`.
#' @param cooldown `numeric`. Minimum time between triggers. Default `0`.
#' @param max_triggers `integer`. Maximum trigger count. Default `1L`.
#' Use `Inf` for unlimited.
#'
#' @return A new `Condition` instance.
initialize = function(
where = NULL,
analysis = NULL,
analysis_args = NULL,
name = NULL,
cooldown = 0,
max_triggers = 1L
) {
if (inherits(where, "rxsim_trigger")) where <- .trigger_to_quosures(where)
self$where <- where
self$analysis <- analysis
self$analysis_args <- analysis_args
self$name <- name
cooldown <- as.numeric(cooldown)
if (length(cooldown) != 1L || cooldown < 0 || is.na(cooldown)) {
stop("`cooldown` must be a single non-negative number.")
}
if (length(max_triggers) == 1L && is.infinite(max_triggers) && max_triggers > 0) {
# Inf means unlimited — keep as-is
} else {
max_triggers <- as.integer(max_triggers)
if (length(max_triggers) != 1L || is.na(max_triggers) || max_triggers < 0L) {
stop("`max_triggers` must be a non-negative integer (use Inf for unlimited).")
}
}
self$cooldown <- cooldown
self$max_triggers <- max_triggers
},
# --- methods ---
#' @description
#' Evaluate this condition against a data snapshot.
#'
#' Applies the three-gate logic: non-empty filter result, cooldown
#' elapsed, and trigger count below `max_triggers`. Returns the analysis
#' result (or filtered data) on a successful trigger, or an empty list
#' otherwise.
#'
#' @param locked_data `data.frame` The trial snapshot at the current time.
#' @param current_time `numeric` Calendar time of the current timepoint.
#'
#' @return Named `list` with one entry (the analysis result) on success,
#' or an empty `list` if the condition did not fire.
check_conditions = function(locked_data, current_time) {
stopifnot(is.data.frame(locked_data))
results <- list()
key <- if (!is.null(self$name) && nzchar(self$name)) self$name else 1L
# Filter snapshot (dplyr semantics: NA in predicates drops rows)
df_i <- if (!is.null(self$where) && length(self$where) > 0) {
dplyr::filter(locked_data, !!!self$where)
} else {
locked_data
}
# Gate 1: non-empty match
if (nrow(df_i) == 0L) return(results)
# Gate 2: hard cap on number of triggers
if (is.finite(self$max_triggers) && self$trigger_count >= self$max_triggers) {
return(results)
}
# Gate 3: cooldown
if (is.finite(self$last_trigger_time)) {
if ((current_time - self$last_trigger_time) < self$cooldown) {
return(results)
}
}
if (is.function(self$analysis)) {
results[[key]] <- do.call(self$analysis, c(list(df_i, current_time), self$analysis_args))
} else {
results[[key]] <- df_i
warning(
sprintf(
" returning filtered data as is because condition '%s' has no applicable analysis \n",
key
),
call. = FALSE
)
}
# Update trigger state after a successful trigger
self$trigger_count <- self$trigger_count + 1L
self$last_trigger_time <- current_time
results
}
) # end public
) # end class