Skip to content

Instantly share code, notes, and snippets.

@lf-araujo
Created January 17, 2025 15:07
Show Gist options
  • Save lf-araujo/c2ece84e94a98bcfac304a72765ddff4 to your computer and use it in GitHub Desktop.
Save lf-araujo/c2ece84e94a98bcfac304a72765ddff4 to your computer and use it in GitHub Desktop.
Future map with OpenMx in simulations
library(purrr)
library(dplyr)
library(future)
library(progress)
# Set up parallel processing
plan(multicore, workers = 23)
# Define the parameters
params <- list(
g1 = c(sqrt(0.02), sqrt(0.03), sqrt(0.04)),
g2 = c(sqrt(0.02), sqrt(0.03), sqrt(0.04)),
b3 = c(sqrt(0.025), sqrt(0.04)),
b1 = c(sqrt(0.025), sqrt(0.04)),
b2 = c(sqrt(0.025), sqrt(0.04)),
ax = c(0.3, 0.4, 0.5),
ay = c(0.3, 0.4, 0.5),
cx = c(0.1, 0.2, 0.3),
cy = c(0.1, 0.2, 0.3),
covA = c(0.1, 0.2),
covE = c(0.1, 0.2),
covC = c(0.1, 0.2),
rf = c(0.5, 0.1, 0.2),
reliability = c(FALSE, TRUE)
)
# Create a data frame of combinations
combinations <- expand.grid(params)
# Initialize the progress bar
pb <- progress_bar$new(
total = nrow(combinations),
format = " [:bar] :percent in :elapsed",
clear = FALSE,
width = 60
)
# Define the simulation function that writes the result directly to a file
sim_function <- function(g1, g2, b1, b2, b3, covC, covA, covE, rf, ax, ay, cx, cy, reliability) {
# Run the simulation
myDF <- sim(
g1 = g1,
g2 = g2,
b1 = b1,
b2 = b2,
b3 = b3,
covC = covC,
covA = covA,
covE = covE,
rf = rf,
ax = ax,
ay = ay,
cx = cx,
cy = cy,
reliability = reliability,
doPow = TRUE
)
# Append the output to file
file <- "25-1-16-relal.csv"
write.table(myDF, file, sep = ",", row.names = FALSE, col.names = !file.exists(file), append = TRUE)
# Update the progress bar
pb$tick()
}
# Use pmap to apply the simulation function to each row of combinations
pmap(combinations, sim_function)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment