forked from ghurault/EczemaPredPOSCORAD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
04a_run_validation.R
217 lines (171 loc) · 6.38 KB
/
04a_run_validation.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
# Notes -------------------------------------------------------------------
# Run validation for severity items and score predictions
# Initialisation ----------------------------------------------------------
rm(list = ls()) # Clear Workspace (better to restart the session)
set.seed(1744834965) # Reproducibility (Stan use a different seed)
source(here::here("analysis", "00_init.R"))
library(foreach)
library(doParallel)
#### OPTIONS
mdl_name <- "BinMC"
score <- "extent"
dataset <- "PFDC"
run <- FALSE
t_horizon <- 4
n_chains <- 4
n_it <- 2000
n_cluster <- 2
####
item_dict <- detail_POSCORAD()
score <- match.arg(score, item_dict[["Name"]])
dataset <- match.arg(dataset, c("Derexyl", "PFDC", "Fake"))
mdl_name <- match.arg(mdl_name, c("uniform", "historical", available_models(score)$Model))
stopifnot(is_scalar_logical(run),
is_scalar_wholenumber(n_chains),
n_chains > 0,
is_scalar_wholenumber(n_it),
n_it > 0,
is_scalar_wholenumber(t_horizon),
t_horizon > 0,
is_scalar_wholenumber(n_cluster),
between(n_cluster, 1, floor((parallel::detectCores() - 2) / n_chains)))
is_continuous <- (score %in% c("SCORAD", "oSCORAD"))
is_stanmodel <- !(mdl_name %in% c("uniform", "historical"))
item_dict <- item_dict %>% filter(Name == score)
item_lbl <- as.character(item_dict[["Label"]])
max_score <- item_dict[["Maximum"]]
reso <- case_when(is_continuous ~ 1,
TRUE ~ item_dict[["Resolution"]])
M <- round(max_score / reso)
file_dict <- get_results_files(outcome = score,
model = mdl_name,
dataset = dataset,
val_horizon = t_horizon,
root_dir = here())
if (is_continuous) {
param <- c("lpd", "y_pred")
} else {
param <- c("lpd", "cum_err", "y_pred")
}
# Data ---------------------------------------------------------------------
POSCORAD <- load_dataset(dataset)
# Subset dataset
df <- POSCORAD %>%
# filter(Patient %in% 1:30) %>%
rename(Time = Day, Score = all_of(item_lbl)) %>%
select(Patient, Time, Score) %>%
drop_na()
pt <- unique(df[["Patient"]])
# Forward chaining --------------------------------------------------------
df <- df %>% mutate(Iteration = get_fc_iteration(Time, t_horizon))
train_it <- get_fc_training_iteration(df[["Iteration"]])
if (run) {
cl <- makeCluster(n_cluster, outfile = "")
registerDoParallel(cl)
dir.create(file_dict$ValDir)
out <- foreach(i = rev(seq_along(train_it))) %dopar% {
it <- train_it[i]
# Need to reload functions and libraries
source(here::here("analysis", "00_init.R"))
duration <- Sys.time()
cat(glue::glue("Starting iteration {it}"), sep = "\n")
####
split <- split_fc_dataset(df, it)
train <- split$Training
test <- split$Testing
if (mdl_name != "MC") {
# Scale by reso for fitting (not saving)
if (is_continuous) {
train_tmp <- train
test_tmp <- test
} else {
train_tmp <- mutate(train, Score = round(Score / reso))
test_tmp <- mutate(test, Score = round(Score / reso))
}
}
# Uniform forecast
if (mdl_name == "uniform") {
perf <- test_tmp %>%
add_uniform_pred(test = .,
max_score = M,
discrete = !is_continuous,
include_samples = is_continuous,
n_samples = 2 * M) %>%
mutate(Score = Score * reso)
}
# Historical forecast
if (mdl_name == "historical") {
perf <- test_tmp %>%
add_historical_pred(test = .,
train = train_tmp,
max_score = M,
discrete = !is_continuous,
add_uniform = TRUE,
include_samples = is_continuous) %>%
mutate(Score = Score * reso)
}
# Markov Chain
if (mdl_name == "MC") {
train_MC <- train %>%
rename(y0 = Score) %>%
group_by(Patient) %>%
mutate(y0 = y0 + 1, y1 = lead(y0), dt = lead(Time) - Time) %>%
ungroup() %>%
select(y0, y1, dt) %>%
drop_na()
test_MC <- test %>%
rename(y0 = LastScore, y1 = Score, dt = Horizon) %>%
mutate(y0 = y0 + 1, y1 = y1 + 1) %>%
select(y0, y1, dt)
model <- EczemaModel("MC", K = max_score + 1)
fit <- EczemaFit(model,
train = train_MC,
test = test_MC,
iter = n_it,
chains = n_chains,
init = 0,
pars = c("lpd", "cum_err", "y_pred"),
refresh = 0)
perf <- test %>%
add_predictions(fit = fit, discrete = TRUE, include_samples = TRUE) %>%
mutate(Samples = map(Samples, ~(.x - 1))) # -1 to be between 0 and max_score
}
# Other time-series model (parametrised similarly)
if (is_stanmodel && mdl_name != "MC") {
model <- EczemaModel(mdl_name, max_score = M, discrete = !is_continuous)
fit <- EczemaFit(model,
train = train_tmp,
test = test_tmp,
iter = n_it,
chains = n_chains,
# control = list(adapt_delta = 0.9),
pars = param,
refresh = 0)
perf <- test %>%
add_predictions(fit = fit, discrete = !is_continuous, include_samples = TRUE) %>%
mutate(Samples = map(Samples, ~(.x * reso)))
}
perf <- perf %>%
select(-LastTime, -LastScore)
# Save results (better to save in the loop in case something breaks)
saveRDS(perf, file = here(file_dict$ValDir, paste0("val_", it, ".rds")))
####
duration <- Sys.time() - duration
cat(glue::glue("Ending iteration {it} after {round(duration, 1)} {units(duration)}"), sep = "\n")
# Return
NULL
}
stopCluster(cl)
# Recombine results
files <- list.files(file_dict$ValDir, full.names = TRUE)
if (length(files) < length(train_it)) {
warning(glue::glue("Number of files (={length(files)}) less than the number of unique iterations (={length(train_it)}).
Some runs may have failed."))
}
res <- lapply(files,
function(f) {
readRDS(here(f))
}) %>%
bind_rows()
saveRDS(res, file = file_dict$Val)
}