-
Notifications
You must be signed in to change notification settings - Fork 2
/
utilities-scenarios.R
295 lines (273 loc) · 11 KB
/
utilities-scenarios.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
#' Run a set of scenarios.
#'
#' @param scenarioConfigurations List of `ScenarioConfiguration` objects to be
#' simulated.
#' @param simulationRunOptions Object of type `SimulationRunOptions` that will be passed
#' to simulation runs. If `NULL`, default options are used.
#'
#' @return A named list, where the names are scenario names, and the values are
#' lists with the entries `simulation` being the initialized `Simulation` object with applied parameters,
#' `results` being `SimulatioResults` object produced by running the simulation,
#' `outputValues` the output values of the `SimulationResults`, and `population`
#' the `Population` object if the scenario is a population simulation.
#' @details
#' If simulation of a scenario fails, a warning is produced, and the `outputValues`
#' for this scenario is `NULL`.
#'
#' @import ospsuite.parameteridentification
#' @export
runScenarios <- function(scenarios, simulationRunOptions = NULL) {
# List of individiaul simulations
individualSimulations <- list()
# List of population scenarios
populationScenarios <- list()
# List of simulation with steady-state
steadyStateSimulations <- list()
# Have to store steady-state times separately, because they are not part of the simulation object
steadyStateTimes <- list()
for (scenario in scenarios) {
if (scenario$scenarioType == "Individual") {
individualSimulations <- c(individualSimulations, scenario$simulation)
} else {
populationScenarios <- c(populationScenarios, scenario)
}
if (scenario$scenarioConfiguration$simulateSteadyState) {
steadyStateSimulations <- c(steadyStateSimulations, scenario$simulation)
steadyStateTimes <- c(steadyStateTimes, scenario$scenarioConfiguration$steadyStateTime)
}
}
# Simulate steady-state concurrently
if (length(steadyStateSimulations) > 0) {
initialValues <- ospsuite::getSteadyState(
simulations = steadyStateSimulations,
steadyStateTime = steadyStateTimes,
ignoreIfFormula = TRUE,
simulationRunOptions = simulationRunOptions
)
}
# Set initial values for steady-state simulations
for (simulation in steadyStateSimulations) {
ospsuite::setQuantityValuesByPath(
quantityPaths = initialValues[[simulation$id]]$paths,
values = initialValues[[simulation$id]]$values, simulation = simulation
)
}
# Run invidual simulations
simulationResults <- runSimulations(
simulations = individualSimulations,
simulationRunOptions = simulationRunOptions
)
# Run population simulations sequentially and add the to the list of simulation results
for (scenario in populationScenarios) {
populationResults <- runSimulations(
simulations = scenario$simulation,
population = scenario$population,
simulationRunOptions = simulationRunOptions
)
simulationResults <- c(simulationResults, populationResults)
}
# Create output list with simulation results, simulation objects, and population objects
returnList <- vector("list", length(simulationResults))
for (idx in seq_along(scenarios)) {
scenario <- scenarios[[idx]]
scenarioName <- scenario$scenarioConfiguration$scenarioName
simulation <- scenario$simulation
id <- simulation$id
results <- simulationResults[[id]]
population <- scenario$population
# Retrieving quantities from paths to support pattern matching with '*'
outputQuantities <- NULL
if (!is.null(scenario$scenarioConfiguration$outputPaths)) {
outputQuantities <- getAllQuantitiesMatching(
scenario$scenarioConfiguration$outputPaths,
simulation
)
}
# If results could not be calculated, show a warning and return NULL
if (is.null(results)) {
warning(messages$missingResultsForScenario(scenarioName))
outputValues <- NULL
} else {
outputValues <- getOutputValues(results,
quantitiesOrPaths = outputQuantities
)
}
returnList[[idx]] <- list(
simulation = simulation, results = results,
outputValues = outputValues,
population = population
)
names(returnList)[[idx]] <- scenarioName
}
# Call gc() on .NET
ospsuite::clearMemory()
return(returnList)
}
#' Create `Scenario` objects from `ScenarioConfiguration` objects
#'
#' @description
#' Load simulation.
#' Apply parameters from global XLS.
#' Apply individual physiology.
#' Apply individual model parameters.
#' Set simulation outputs.
#' Set simulation time.
#' initializeSimulation().
#' Create population
#'
#' @param scenarioConfigurations List of `ScenarioConfiguration` objects to be
#' simulated.
#' @param customParams A list containing vectors 'paths' with the full paths to the
#' parameters, 'values' the values of the parameters, and 'units' with the
#' units the values are in. The values to be applied to the model.
#' @param stopIfParameterNotFound Boolean. If `TRUE` (default) and a custom parameter is not found, an error is thrown. If `FALSE`, non-existing parameters
#' are ignored.
#'
#' @return Named list of `Scenario` objects.
#' @export
createScenarios <- function(scenarioConfigurations, customParams = NULL, stopIfParameterNotFound = TRUE) {
.validateScenarioConfigurations(scenarioConfigurations)
.validateParametersStructure(
parameterStructure = customParams,
argumentName = "customParams",
nullAllowed = TRUE
)
scenarios <- purrr::map(scenarioConfigurations, ~ Scenario$new(.x, customParams = customParams, stopIfParameterNotFound = stopIfParameterNotFound)) %>%
purrr::set_names(purrr::map(scenarioConfigurations, ~ .x$scenarioName))
return(scenarios)
}
#' Save results of scenario simulations to csv.
#'
#' @param simulatedScenariosResults Named list with `simulation`, `results`, `outputValues`,
#' and `population` as produced by `runScenarios()`.
#' @param projectConfiguration An instance of `ProjectConfiguration`
#' @param outputFolder Optional - path to the folder where the results will be
#' stored. If `NULL` (default), a sub-folder in
#' `ProjectConfiguration$outputFolder/SimulationResults/<DateSuffix>`.
#' @param saveSimulationsToPKML If `TRUE` (default), simulations corresponding to
#' the results are saved to PKML along with the results.
#'
#' @details For each scenario, a separate csv file will be created. If the scenario
#' is a population simulation, a population is stored along with the results with
#' the file name suffix `_population`. Results can be read with the `loadScenarioResults()` function.
#'
#' @export
#'
#' @examples \dontrun{
#' projectConfiguration <- esqlabsR::createDefaultProjectConfiguration()
#' scenarioConfigurations <- readScenarioConfigurationFromExcel(
#' projectConfiguration = projectConfiguration
#' )
#' scenarios <- createScenarios(scenarioConfigurations = scenarioConfigurations)
#' simulatedScenariosResults <- runScenarios(
#' scenarios = scenarios
#' )
#' saveScenarioResults(simulatedScenariosResults, projectConfiguration)
#' }
saveScenarioResults <- function(
simulatedScenariosResults,
projectConfiguration,
outputFolder = NULL,
saveSimulationsToPKML = TRUE) {
validateIsLogical(saveSimulationsToPKML)
outputFolder <- outputFolder %||% file.path(
projectConfiguration$outputFolder,
"SimulationResults",
format(Sys.time(), "%F %H-%M")
)
for (i in seq_along(simulatedScenariosResults)) {
results <- simulatedScenariosResults[[i]]$results
scenarioName <- names(simulatedScenariosResults)[[i]]
# Replace "\" and "/" by "_" so the file name does not result in folders
scenarioName <- gsub("[\\\\/]", "_", scenarioName)
outputPath <- file.path(outputFolder, paste0(scenarioName, ".csv"))
tryCatch(
{
# Create a new folder if it does not exist
if (!dir.exists(paths = outputFolder)) {
dir.create(path = outputFolder, recursive = TRUE)
}
# Save results
ospsuite::exportResultsToCSV(results = results, filePath = outputPath)
# Save simulations
if (saveSimulationsToPKML) {
outputPathSim <- file.path(outputFolder, paste0(scenarioName, ".pkml"))
ospsuite::saveSimulation(
simulation = simulatedScenariosResults[[i]]$simulation,
filePath = outputPathSim
)
}
# Save population
if (isOfType(simulatedScenariosResults[[i]]$population, "Population")) {
ospsuite::exportPopulationToCSV(simulatedScenariosResults[[i]]$population,
filePath = file.path(outputFolder, paste0(scenarioName, "_population.csv"))
)
}
},
error = function(cond) {
warning(paste0("Cannot save to path '", outputFolder, "'"))
message("Original error message:")
message(cond)
},
warning = function(cond) {
warning(cond)
}
)
}
}
#' Load simulated scenarios from csv and pkml.
#'
#' @param scenarioNames Names of simulated scenarios
#' @param resultsFolder Path to the folder where simulation results as scv and
#' the corresponding simulations as pkml are located.
#'
#' @details This function requires simulation results AND the corresponding
#' simulation files being located in the same folder (`resultsFolder`) and have
#' the names of the scenarios.
#'
#' @return A named list, where the names are scenario names, and the values are
#' lists with the entries `simulation` being the initialized `Simulation` object with applied parameters,
#' `results` being `SimulatioResults` object produced by running the simulation,
#' and `outputValues` the output values of the `SimulationResults`.
#'
#' @export
#'
#' @examples \dontrun{
#' # First simulate scenarios and save the results
#' projectConfiguration <- esqlabsR::createDefaultProjectConfiguration()
#' scenarioConfigurations <- readScenarioConfigurationFromExcel(
#' projectConfiguration = projectConfiguration
#' )
#' scenarios <- createScenarios(scenarioConfigurations = scenarioConfigurations)
#' simulatedScenariosResults <- runScenarios(
#' scenarios = scenarios
#' )
#' saveResults(simulatedScenariosResults, projectConfiguration)
#'
#' # Now load the results
#' scnarioNames <- names(scenarios)
#' simulatedScenariosResults <- loadScenarioResults(
#' scnarioNames = scnarioNames,
#' resultsFolder = pathToTheFolder
#' )
#' }
loadScenarioResults <- function(scenarioNames, resultsFolder) {
simulatedScenariosResults <- list()
for (i in seq_along(scenarioNames)) {
scenarioName <- scenarioNames[[i]]
# Replace "\" and "/" by "_" so the file name does not result in folders.
# Used only for loading the results, the name of the scenario is not changed.
scenarioNameForPath <- gsub("[\\\\/]", "_", scenarioName)
simulation <- loadSimulation(paste0(resultsFolder, "/", scenarioNameForPath, ".pkml"))
results <- importResultsFromCSV(
simulation = simulation,
filePaths = paste0(resultsFolder, "/", scenarioNameForPath, ".csv")
)
outputValues <- getOutputValues(results,
quantitiesOrPaths = results$allQuantityPaths
)
simulatedScenariosResults[[scenarioNames[[i]]]] <-
list(simulation = simulation, results = results, outputValues = outputValues)
}
return(simulatedScenariosResults)
}