-
Notifications
You must be signed in to change notification settings - Fork 2
/
utilities-sensitivity-Calculation.R
344 lines (314 loc) · 10.4 KB
/
utilities-sensitivity-Calculation.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
# dataframe extraction helpers ------------------------------
#' @title Run batch simulations and extract results in a dataframe
#'
#' @param parameter A single path of the parameter to be varied.
#' @param parameterPath A **single** parameter path.
#' @inheritParams sensitivityCalculation
#'
#' @note Note that the function will work only with a single parameter path.
#'
#' @keywords internal
#' @noRd
.extractSimulationResultsBatch <- function(simulation,
parameterPath,
variationRange) {
# extract `Parameter` object
parameter <- getAllParametersMatching(parameterPath, simulation)
# create simulation batch for efficient calculations
simulationBatch <- createSimulationBatch(simulation, parametersOrPaths = parameter[[1]])
# for each parameter, set the value to `referenceValue * scaleFactor`
# and run simulations with these parameter values
purrr::walk(
.x = c(purrr::pluck(parameter[[1]], "value") * variationRange),
.f = ~ simulationBatch$addRunValues(.x)
)
# use `unlist()` because we only have one `simulationBatch` here
simulationResultsBatch <- unlist(runSimulationBatches(simulationBatch))
# use names for parameter factor
names(simulationResultsBatch) <- variationRange
simulationResultsBatch
}
#' Extract time-series dataframe from a list of `SimulationResults` objects
#'
#' @param simulationResultsBatch A **list** of `SimulationResults` R6 objects.
#' @inheritParams sensitivityCalculation
#'
#' @keywords internal
#' @noRd
.simulationResultsBatchToTimeSeriesDataFrame <- function(simulationResultsBatch,
parameterPaths,
outputPaths) {
purrr::map2_dfr(
.x = simulationResultsBatch,
.y = parameterPaths,
.f = ~ .simulationResultsToTimeSeriesDataFrame(.x, .y, outputPaths = outputPaths)
)
}
#' Extract time-series dataframe from `SimulationResults` object
#'
#' @param simResults A **single** instance of `SimulationResults` R6 object.
#' @inheritParams .extractSimulationResultsBatch
#' @inheritParams sensitivityCalculation
#'
#' @keywords internal
#' @noRd
.simulationResultsToTimeSeriesDataFrame <- function(simulationResults,
parameterPath,
outputPaths) {
purrr::map_dfr(
.x = simulationResults,
.f = ~ simulationResultsToDataFrame(.x, quantitiesOrPaths = outputPaths),
.id = "ParameterFactor"
) %>%
dplyr::rename(
Concentration = simulationValues,
OutputPath = paths,
Dimension = dimension,
Unit = unit
) %>%
.addParameterColumns(simulationResults, parameterPath) %>%
dplyr::select(
"OutputPath",
dplyr::starts_with("Parameter"),
Time, Concentration,
dplyr::everything(),
-c("IndividualId")
) %>%
dplyr::arrange(ParameterPath, ParameterFactor)
}
#' Extract PK parameters dataframe from a list of `SimulationResults` objects
#'
#' @inheritParams .simulationResultsBatchToTimeSeriesDataFrame
#'
#' @keywords internal
#' @noRd
.simulationResultsBatchToPKDataFrame <- function(simulationResultsBatch,
parameterPaths) {
purrr::map2_dfr(
.x = simulationResultsBatch,
.y = parameterPaths,
.f = ~ .simulationResultsToPKDataFrame(.x, .y)
)
}
#' Extract PK parameters dataframe from `Parameter` object
#'
#' @inheritParams .simulationResultsToTimeSeriesDataFrame
#'
#' @keywords internal
#' @noRd
.simulationResultsToPKDataFrame <- function(simulationResults, parameterPath) {
purrr::map_dfr(
.x = simulationResults,
.f = ~ pkAnalysesToDataFrame(calculatePKAnalyses(.x)),
.id = "ParameterFactor"
) %>%
dplyr::rename(
OutputPath = QuantityPath,
PKParameter = Parameter,
PKParameterValue = Value
) %>%
.addParameterColumns(simulationResults, parameterPath) %>%
dplyr::group_by(ParameterPath, PKParameter) %>%
dplyr::group_modify(.f = ~ .computePercentChange(.)) %>%
dplyr::ungroup() %>%
dplyr::select(
"OutputPath",
dplyr::starts_with("Parameter"),
dplyr::starts_with("PK"),
Unit, PercentChangePK,
dplyr::everything(),
-c("IndividualId")
) %>%
dplyr::arrange(ParameterPath, PKParameter, ParameterFactor)
}
# dataframe modification helpers ------------------------------
#' @title Percent change in PK parameters
#'
#' @description Compute %change in PK parameters and their sensitivity
#'
#' @param data A dataframe returned by `pkAnalysesAsDataFrame()` and with
#' columns renamed to follow `UpperCamel` case.
#'
#' @keywords internal
#' @noRd
.computePercentChange <- function(data) {
# baseline values with a scaling of 1, i.e. no scaling
baseDataFrame <- dplyr::filter(data, ParameterFactor == 1.0)
# baseline values for parameters of interest
ParameterBaseValue <- baseDataFrame %>% dplyr::pull(ParameterValue)
PKParameterBaseValue <- baseDataFrame %>% dplyr::pull(PKParameterValue)
# add columns with %change and sensitivity
# reference: https://docs.open-systems-pharmacology.org/shared-tools-and-example-workflows/sensitivity-analysis#mathematical-background
data %>%
dplyr::mutate(
PercentChangePK = ((PKParameterValue - PKParameterBaseValue) / PKParameterBaseValue) * 100,
SensitivityPKParameter =
# delta PK / PK
((PKParameterValue - PKParameterBaseValue) / PKParameterValue) *
# p / delta p
(ParameterValue / (ParameterValue - ParameterBaseValue))
)
}
#' @title Add columns with details about parameter paths
#'
#' @description
#'
#' Adds columns with additional details about parameter paths:
#' - name,
#' - reference values
#' - scaled values
#'
#' @param data A dataframe returned by `pkAnalysesAsDataFrame()` or by
#' `simulationResultsToDataFrame()`.
#' @inheritParams .extractSimulationResultsBatch
#'
#' @note Note that the function will work only with a single parameter path.
#'
#' @keywords internal
#' @noRd
.addParameterColumns <- function(data, simulationResults, parameterPath) {
parameter <- getAllParametersMatching(
parameterPath,
purrr::pluck(simulationResults, 1L, "simulation")
)
data %>%
dplyr::mutate(
ParameterPath = purrr::pluck(parameter[[1]], "path"),
ParameterValue = purrr::pluck(parameter[[1]], "value"),
ParameterFactor = as.numeric(ParameterFactor)
) %>%
dplyr::mutate(ParameterValue = ParameterValue * ParameterFactor)
}
#' @keywords internal
#' @noRd
.convertToWide <- function(data) {
data %>%
tidyr::pivot_wider(
names_from = PKParameter,
values_from = c(PKParameterValue, Unit, PercentChangePK, SensitivityPKParameter),
names_glue = "{PKParameter}_{.value}"
) %>%
dplyr::rename_all(~ stringr::str_remove(.x, "PK$|PKParameter$|_PKParameterValue")) %>%
# all metrics for each parameter should live together
dplyr::select(
dplyr::matches("Output|^Parameter"),
dplyr::matches(names(ospsuite::StandardPKParameter))
)
}
# validation helpers ------------------------------
#' @title Validate variation range
#'
#' @description
#'
#' Checks that the values entered to vary parameter:
#'
#' - are all numeric
#' - are all unique
#' - include base scaling (i.e. a scaling of 1.0)
#'
#' @inheritParams sensitivityCalculation
#'
#' @keywords internal
#' @noRd
.validateVariationRange <- function(variationRange) {
# only numbers allowed
validateIsNumeric(variationRange)
# extract only unique values
variationRange <- unique(variationRange)
# if there is no scaling factor of 1.0 (corresponding to no scaling), add it
if (!any(dplyr::near(1.0, variationRange))) {
variationRange <- c(1.0, variationRange)
}
# return sorted vector of scaling values
sort(variationRange)
}
#' Validate vector arguments of `character` type
#'
#' @param argVector A vector of `character` type.
#'
#' @description
#'
#' If the parameter in your function accepts vectors of `character` type, this
#' can help you validate the following aspects:
#'
#' - the elements are indeed of `character` type
#' - none of the entries are duplicated
#' - there are no empty strings (`""`)
#'
#' @return Error if validation is unsuccessful; otherwise, `NULL`.
#'
#' @examples
#'
#' x <- c("a", "b", "a")
#' # this will produce error
#' # validateCharVectors(x)
#'
#' # this will return `NULL`
#' y <- c("a", "b", "c")
#' validateCharVectors(y)
#'
#' @keywords internal
#' @noRd
.validateCharVectors <- function(argVector) {
argName <- deparse(substitute(argVector))
if (!isOfType(argVector, "character", nullAllowed = TRUE)) {
stop(paste0("Only values of `character` type are allowed in `", argName, "` argument."))
}
if (!hasOnlyDistinctValues(argVector)) {
stop(paste0("Only distinct values are allowed in `", argName, "` argument."))
}
if (any(nchar(argVector) == 0L)) {
stop(paste0("Values in `", argName, "` argument can't be an empty string."))
}
}
#' Inform user if any non-standard PK parameters have been specified
#'
#' @keywords internal
#' @noRd
.validatePKParameters <- function(pkParameters) {
if (!is.null(pkParameters) && !isIncluded(pkParameters, names(ospsuite::StandardPKParameter))) {
nsPKNames <- pkParameters[!pkParameters %in% names(ospsuite::StandardPKParameter)]
message(
cat(
"Following non-standard PK parameters will not be calculated:",
nsPKNames,
sep = "\n"
)
)
}
}
# plotting helpers ------------------------------
#' @name savePlotList
#' @title Save a list of plots
#'
#' @param plotlist A list of plots (ideally form `sensitivityTimeProfiles()` or
#' `sensitivitySpiderPlot()`).
#' @param plot.type A string specifying the prefix for plot filename.
#' @inheritParams sensitivitySpiderPlot
#'
#' @seealso sensitivityTimeProfiles, sensitivitySpiderPlot
#'
#' @examples
#'
#' # first check out examples for `sensitivityTimeProfiles()` and
#' # `sensitivitySpiderPlot()`
#'
#' @keywords internal
#' @noRd
.savePlotList <- function(plotlist,
plot.type,
width = NA,
height = NA,
dpi = 300) {
purrr::walk2(
.x = plotlist,
.y = seq(1:length(plotlist)),
.f = ~ ggsave(
filename = paste0(plot.type, "OutputPath", .y, ".png"),
plot = .x,
height = height,
width = width,
dpi = dpi
)
)
}