Skip to content

Commit b716638

Browse files
author
Liam Shaw
committed
changed name of Olival functions script
1 parent 5a0a437 commit b716638

File tree

1 file changed

+296
-0
lines changed

1 file changed

+296
-0
lines changed

scripts/Olival-functions.R

+296
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,296 @@
1+
# This code was originally written by Olival et al. (2017)
2+
# and was adapted (lightly) by Liam Shaw 2019 (liam.philip.shaw at gmail dot com)
3+
# for this project.
4+
5+
# See: https://zenodo.org/record/807517 for the original code repository this code was sourced from
6+
# I am grateful to Olival et al. for making their code available under an MIT License.
7+
# https://opensource.org/licenses/MIT
8+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9+
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11+
12+
fit_all_gams <- function(data_set, outcome_variable, terms) {
13+
14+
fit_gam = function(frm) {
15+
try(gam(formula=as.formula(frm), family="binomial", data_set, select=TRUE), silent=TRUE)
16+
}
17+
18+
terms_grid = do.call(expand.grid, terms)
19+
20+
#Create model forumulas from the grid
21+
formulas = apply(as.matrix(terms_grid), 1, function(row) paste(row, collapse = " + ")) %>%
22+
stri_replace_all_regex("\\s[\\+\\s]+\\s", " + ") %>%
23+
{paste(outcome_variable, "~", .)} %>%
24+
rearrange_formula %>%
25+
unique
26+
27+
models = data_frame(formula = formulas)
28+
29+
n_cores = detectCores()
30+
n_cores_use = round(nrow(models) / ceiling(nrow(models) / (n_cores - 1)))
31+
options(mc.cores = n_cores_use)
32+
message("Using ", n_cores_use, " cores to fit ", nrow(models), " models")
33+
34+
models_vec = mclapply(models$formula, fit_gam)
35+
36+
models = models %>%
37+
mutate(model = models_vec)
38+
#print(models)
39+
40+
# Calculate models
41+
models = models %>%
42+
filter(map_lgl(model, ~ !("try-error" %in% class(.) | is.null(.)))) %>%
43+
mutate(aic = map_dbl(model, MuMIn::AICc),
44+
daic = aic - min(aic),
45+
weight = exp(-daic/2)) %>%
46+
arrange(aic)
47+
#print("Calculated models")
48+
#print(models)
49+
50+
# Remove unused terms from models and reduce to unique ones
51+
models_reduced = models %>%
52+
dplyr::select(model) %>%
53+
mutate(formula = map_chr(model, ~rearrange_formula(rm_low_edf(.)))) %>%
54+
distinct(formula, .keep_all = TRUE)
55+
#print("Remove unused terms")
56+
#print(models)
57+
58+
n_cores_use = round(nrow(models_reduced) / ceiling(nrow(models_reduced) / (n_cores - 1)))
59+
options(mc.cores = n_cores_use)
60+
message("Using ", n_cores_use, " cores to fit ", nrow(models_reduced), " reduced models")
61+
62+
# Reduce the remaining models
63+
models_reduced = models_reduced %>%
64+
mutate(model = mclapply(model, reduce_model))
65+
#print("Reduced remaining models")
66+
#print(models_reduced)
67+
68+
models_reduced = models_reduced %>%
69+
filter(map_lgl(model, ~ !("try-error" %in% class(.) | is.null(.)))) %>%
70+
mutate(aic = map_dbl(model, MuMIn::AICc)) %>%
71+
mutate(formula = map_chr(model, ~rearrange_formula(rm_low_edf(.)))) %>%
72+
distinct(formula, .keep_all=TRUE) %>%
73+
arrange(aic) %>%
74+
mutate(daic = aic - min(aic),
75+
weight = exp(-daic/2),
76+
terms = shortform(map(model, ~ rearrange_formula(.$formula))),
77+
relweight = ifelse(daic > 2, 0, weight/sum(weight[daic < 2])),
78+
relweight_all = weight/sum(weight),
79+
cumweight = cumsum(relweight_all))
80+
#print("Final reduction")
81+
#print(models_reduced)
82+
83+
return(models_reduced)
84+
85+
}
86+
87+
fit_all_gams_poisson <- function(data_set, outcome_variable, terms) {
88+
89+
fit_gam = function(frm) {
90+
try(gam(formula=as.formula(frm), family="poisson", data_set, select=TRUE), silent=TRUE)
91+
}
92+
93+
terms_grid = do.call(expand.grid, terms)
94+
95+
#Create model forumulas from the grid
96+
formulas = apply(as.matrix(terms_grid), 1, function(row) paste(row, collapse = " + ")) %>%
97+
stri_replace_all_regex("\\s[\\+\\s]+\\s", " + ") %>%
98+
{paste(outcome_variable, "~", .)} %>%
99+
rearrange_formula %>%
100+
unique
101+
102+
models = data_frame(formula = formulas)
103+
104+
n_cores = detectCores()
105+
n_cores_use = round(nrow(models) / ceiling(nrow(models) / (n_cores - 1)))
106+
options(mc.cores = n_cores_use)
107+
message("Using ", n_cores_use, " cores to fit ", nrow(models), " models")
108+
109+
models_vec = mclapply(models$formula, fit_gam)
110+
111+
models = models %>%
112+
mutate(model = models_vec)
113+
#print(models)
114+
115+
# Calculate models
116+
models = models %>%
117+
filter(map_lgl(model, ~ !("try-error" %in% class(.) | is.null(.)))) %>%
118+
mutate(aic = map_dbl(model, MuMIn::AICc),
119+
daic = aic - min(aic),
120+
weight = exp(-daic/2)) %>%
121+
arrange(aic)
122+
#print("Calculated models")
123+
#print(models)
124+
125+
# Remove unused terms from models and reduce to unique ones
126+
models_reduced = models %>%
127+
dplyr::select(model) %>%
128+
mutate(formula = map_chr(model, ~rearrange_formula(rm_low_edf(.)))) %>%
129+
distinct(formula, .keep_all = TRUE)
130+
#print("Remove unused terms")
131+
#print(models)
132+
133+
n_cores_use = round(nrow(models_reduced) / ceiling(nrow(models_reduced) / (n_cores - 1)))
134+
options(mc.cores = n_cores_use)
135+
message("Using ", n_cores_use, " cores to fit ", nrow(models_reduced), " reduced models")
136+
137+
# Reduce the remaining models
138+
models_reduced = models_reduced %>%
139+
mutate(model = mclapply(model, reduce_model))
140+
#print("Reduced remaining models")
141+
#print(models_reduced)
142+
143+
models_reduced = models_reduced %>%
144+
filter(map_lgl(model, ~ !("try-error" %in% class(.) | is.null(.)))) %>%
145+
mutate(aic = map_dbl(model, MuMIn::AICc)) %>%
146+
mutate(formula = map_chr(model, ~rearrange_formula(rm_low_edf(.)))) %>%
147+
distinct(formula, .keep_all=TRUE) %>%
148+
arrange(aic) %>%
149+
mutate(daic = aic - min(aic),
150+
weight = exp(-daic/2),
151+
terms = shortform(map(model, ~ rearrange_formula(.$formula))),
152+
relweight = ifelse(daic > 2, 0, weight/sum(weight[daic < 2])),
153+
relweight_all = weight/sum(weight),
154+
cumweight = cumsum(relweight_all))
155+
#print("Final reduction")
156+
#print(models_reduced)
157+
158+
return(models_reduced)
159+
160+
}
161+
162+
163+
# Returns a model formula from a GAM with the low_edf terms removed
164+
rm_low_edf <- function(mod, edf_cutoff = 0.001) {
165+
fr = as.character(formula(mod))
166+
lhs = fr[2]
167+
rhs = fr[3]
168+
edfs = pen.edf(mod)
169+
low_edfs = edfs[edfs < edf_cutoff]
170+
vars_to_remove = stri_replace_all_fixed(unique(stri_extract_first_regex(names(low_edfs), "(?<=s\\()[^\\)]+(?=\\))")), ",",", ")
171+
vars_regex = paste0("(", paste(vars_to_remove, collapse="|"), ")")
172+
new_rhs = stri_replace_all_regex(rhs, paste0("\\s*s\\(", vars_regex, "\\,[^\\)]+\\)\\s*\\+?"), "")
173+
new_rhs= stri_replace_all_fixed(new_rhs, "+, k = 7) ", "")
174+
new_rhs= stri_replace_all_fixed(new_rhs, "+ +s", "+ s")
175+
new_formula = paste(lhs, "~", new_rhs)
176+
new_formula = stri_replace_all_regex(new_formula, "[\\s\\n]+", " ")
177+
new_formula = stri_replace_all_regex(new_formula, "[+\\s]*$", "")
178+
return(new_formula)
179+
}
180+
181+
rm_terms <- function(mod, terms) {
182+
fr = as.character(formula(mod))
183+
lhs = fr[2]
184+
rhs = fr[3]
185+
vars_regex = paste0("(", paste(terms, collapse="|"), ")")
186+
new_rhs = stri_replace_all_regex(rhs, paste0("\\s*s\\(", vars_regex, "\\,[^\\)]+\\)\\s*\\+?"), "")
187+
new_rhs= stri_replace_all_fixed(new_rhs, "+, k = 7) ", "")
188+
new_rhs= stri_replace_all_fixed(new_rhs, "+ +s", "+ s")
189+
new_formula = paste(lhs, "~", new_rhs)
190+
new_formula = stri_replace_all_regex(new_formula, "[\\s\\n]+", " ")
191+
new_formula = stri_replace_all_regex(new_formula, "[+\\s]*$", "")
192+
return(new_formula)
193+
}
194+
195+
#' Alphabetizes the right-hand side of a formula so as to compare formulas across models
196+
rearrange_formula = function(formula) {
197+
if(class(formula) == "formula") {
198+
formula = as.character(formula)
199+
formula = paste(formula[2], "~", formula[3], collapse=" ")
200+
}
201+
lhs = stri_extract_first_regex(formula, "^[^\\s~]+")
202+
rhs = stri_replace_first_regex(formula, "[^~]+~\\s+", "")
203+
terms = stri_split_regex(rhs, "[\\s\\n]+\\+[\\s\\n]+")
204+
terms = lapply(terms, sort)
205+
new_formula = mapply(function(lhs, terms) {paste(lhs, "~", paste(terms, collapse = " + "))}, lhs, terms)
206+
new_formula = stri_replace_all_regex(new_formula, "[\\s\\n]+", " ")
207+
new_formula = stri_replace_all_fixed(new_formula, "+ +s", "+ s")
208+
new_formula = stri_replace_all_fixed(new_formula, "+ +", "+")
209+
names(new_formula) <- NULL
210+
return(stri_trim(new_formula))
211+
}
212+
213+
# Re-fits a gam model, dropping terms that have been selected out
214+
reduce_model <- function(mod, edf_cutoff = 0.001, recursive=TRUE) {
215+
low_edf_vars = any(pen.edf(mod) < edf_cutoff)
216+
if(recursive) {
217+
while(low_edf_vars) {
218+
mod = update(mod, formula = as.formula(rm_low_edf(mod, edf_cutoff)))
219+
low_edf_vars = any(pen.edf(mod) < edf_cutoff)
220+
}
221+
} else {
222+
if(low_edf_vars) {
223+
mod = update(mod, formula = as.formula(rm_low_edf(mod, edf_cutoff)))
224+
}
225+
}
226+
return(mod)
227+
}
228+
229+
# Makes a reduced version of the RHS of a formula
230+
shortform = function(formula) {
231+
rhs = stri_replace_first_regex(formula, "[^~]+~\\s+", "")
232+
rhs = stri_replace_all_regex(rhs, "s\\(([^\\,]+)\\,[^\\)]+\\)", "s($1)")
233+
rhs= stri_replace_all_fixed(rhs, "+ +s", "+ s")
234+
stri_replace_all_fixed(rhs, "(1 + | + 1)", "")
235+
}
236+
237+
check_vals <- function(x) {
238+
w = which(is.nan(x) | is.na(x) | is.infinite(x))
239+
z = x[w]
240+
names(z) = w
241+
return(z)
242+
}
243+
244+
245+
get_relative_contribs <- function(gam_model) {
246+
247+
terms <- attributes(gam_model$terms)
248+
offset <- attributes(gam_model$terms)$offset
249+
250+
formula_chr <- as.character(formula(gam_model))
251+
model_data <- gam_model$model
252+
offset_name = stri_replace_first_regex(names(model_data)[terms$offset], "offset\\(([^\\)]+)\\)", "$1")
253+
names(model_data) <- stri_replace_all_regex(names(model_data), "offset\\(([^\\)]+)\\)", "$1")
254+
gam_model = gam(formula(gam_model), data=model_data, family=gam_model$family, select=FALSE)
255+
256+
y = model_data[,terms$response]
257+
preds = predict(gam_model, type="iterms")
258+
intercept = attributes(preds)$constant
259+
smooth_pars <- gam_model$sp
260+
rhs <- formula_chr[3]
261+
lhs <- formula_chr[2]
262+
devs <- map_dbl(terms$term.labels, function(term) {
263+
# sub_preds <- rowSums(preds[, !stri_detect_fixed(colnames(preds), term), drop=FALSE]) + intercept
264+
# if(length(offset_name) ==1 ) sub_preds = sub_preds + model_data[, offset]
265+
# sub_preds <- gam_model$family$linkinv(sub_preds)
266+
# res <- gam_model$family$dev.resids(y, sub_preds, 1)
267+
# s <- attr(res, "sign")
268+
# if (is.null(s))
269+
# s <- sign(y - sub_preds)
270+
# res <- sqrt(pmax(res, 0, na.rm=TRUE)) * s
271+
# dev <- sum(res^2)
272+
term = c(terms$term.labels[terms$term.labels != term], offset_name)
273+
term_regex= paste0("(", paste(term, collapse="|"), ")")
274+
new_formula <- stri_extract_all_regex(rhs, paste0("(s|offset)\\(", term_regex, "[^\\)]*\\)"))[[1]] %>%
275+
paste(collapse = " + ") %>%
276+
{paste(lhs, "~", .)} %>%
277+
as.formula()
278+
smooth_par <- smooth_pars[stri_detect_regex(names(smooth_pars), term_regex)]
279+
smooth_par <- smooth_par[!stri_detect_regex(names(smooth_par), "\\)[23456789]+$")]
280+
new_model <- gam(formula = new_formula, sp=smooth_par, data=model_data, family=gam_model$family, select=FALSE)
281+
dev = deviance(new_model)
282+
return(dev)
283+
})
284+
null_formula = paste(lhs, "~ 1")
285+
if(length(offset_name) ==1 ) null_formula = paste0(null_formula, "+ offset(", offset_name, ")")
286+
null_model = gam(formula = as.formula(null_formula), data=model_data, family=gam_model$family, select=FALSE)
287+
null_model_dev = deviance(null_model)
288+
orig_dev<- deviance(gam_model)
289+
dev_expl = (devs - orig_dev)
290+
dev_expl = dev_expl/sum(dev_expl)
291+
data_frame(term = terms$term.labels, rel_deviance_explained = dev_expl)
292+
293+
}
294+
295+
296+

0 commit comments

Comments
 (0)