if (FALSE) {
# Setup: Create graph with mesh and add point pattern data
graph <- metric_graph$new()
graph$build_mesh(h = 0.1)
# Add point pattern data with covariates
point_data <- data.frame(
y = 1, # All observed locations have y = 1
edge_number = c(1, 2, 3, 1, 2),
distance_on_edge = c(0.1, 0.3, 0.8, 0.9, 0.2),
elevation = c(100, 150, 200, 120, 180),
temperature = c(15, 12, 8, 14, 10)
)
graph$add_observations(point_data, normalized = TRUE)
# Create SPDE model
spde_model <- graph_spde(graph, alpha = 1)
# Precompute for multiple model fitting scenarios
precomputed_data <- precompute_lgcp_graph(
graph = graph,
resp_variable_name = "y",
model_name = "field",
spde_model = spde_model,
covariates = c("elevation", "temperature"),
use_current_mesh = TRUE
)
# Now fit multiple models efficiently
# Model selection: compare different covariate combinations
fit1 <- lgcp_graph(y ~ elevation + f(field, model = spde_model),
graph = graph, precomputed_data = precomputed_data)
fit2 <- lgcp_graph(y ~ temperature + f(field, model = spde_model),
graph = graph, precomputed_data = precomputed_data)
fit3 <- lgcp_graph(y ~ elevation + temperature + f(field, model = spde_model),
graph = graph, precomputed_data = precomputed_data)
# Compare models using log marginal likelihood
c(fit1$mlik[1], fit2$mlik[1], fit3$mlik[1])
# Using manual covariates (exact values at mesh nodes)
manual_covs <- data.frame(
elevation = graph$mesh$VtE[,1] * 50 + 100, # Synthetic elevation
temperature = 20 - graph$mesh$VtE[,1] * 10, # Synthetic temperature
.group = 1
)
precomputed_manual <- precompute_lgcp_graph(
graph = graph,
resp_variable_name = "y",
model_name = "field",
spde_model = spde_model,
covariates = c("elevation", "temperature"),
manual_covariates = manual_covs,
interpolate = FALSE
)
# For maximum performance (modifies original graph)
precomputed_fast <- precompute_lgcp_graph(
graph = graph,
resp_variable_name = "y",
model_name = "field",
spde_model = spde_model,
covariates = c("elevation", "temperature"),
clone_graph = FALSE
)
# Example with replicates
replicate_data <- data.frame(
y = 1,
edge_number = c(1, 2, 1, 3, 2, 3),
distance_on_edge = c(0.2, 0.4, 0.7, 0.1, 0.8, 0.6),
elevation = c(110, 160, 130, 190, 170, 210),
replicate_id = c(1, 1, 1, 2, 2, 2)
)
graph$clear_observations()
graph$add_observations(replicate_data, normalized = TRUE, group = "replicate_id")
precomputed_reps <- precompute_lgcp_graph(
graph = graph,
resp_variable_name = "y",
model_name = "field",
spde_model = spde_model,
covariates = "elevation",
repl = ".all",
repl_col = "replicate_id"
)
fit_reps <- lgcp_graph(y ~ elevation + f(field, model = spde_model,
replicate = field.repl),
graph = graph, precomputed_data = precomputed_reps)
}
Run the code above in your browser using DataLab