Skip to content

Commit

Permalink
Merge branch 'main' into Documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
anitaapplegarth authored Jan 22, 2025
2 parents 0b87191 + dc7935e commit 2208d1f
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 43 deletions.
53 changes: 33 additions & 20 deletions R/simulation_flow_check.R
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
#
# Example simulation script with data output
#

# Import dependencies
source("R/zzz.R")
initialize_python_env()
check_python_env()

library(reticulate)
#library(rEpiabm)
library(here)
library(tidyr)

Expand All @@ -24,7 +24,7 @@ base_dir <- here()
pe$Parameters$set_file(here("data", "simple_parameters.json"))

# Method to set the seed at the start of the simulation, for reproducibility
pe$routine$Simulation$set_random_seed(seed=as.integer(42))
pe$routine$Simulation$set_random_seed(seed = as.integer(42))

# Pop_params are used to configure the population structure being used in this
# simulation.
Expand All @@ -37,7 +37,7 @@ pop_params <- list(
)

# Create a population based on the parameters given.
population = pe$routine$ToyPopulationFactory()$make_pop(pop_params)
population <- pe$routine$ToyPopulationFactory()$make_pop(pop_params)

# sim_params
sim_params <- list(
Expand Down Expand Up @@ -101,35 +101,48 @@ df <- read.csv(filename)
library(ggplot2)

# Reshape the data from wide to long format using base R
status_columns <- c("InfectionStatus.Susceptible",
"InfectionStatus.InfectMild",
"InfectionStatus.Recovered",
"InfectionStatus.Dead")
status_columns <- c(
"InfectionStatus.Susceptible",
"InfectionStatus.InfectMild",
"InfectionStatus.Recovered",
"InfectionStatus.Dead"
)

df_long <- pivot_longer(
df,
cols = all_of(status_columns),
names_to = "Status",
values_to = "Count"
)
df_long$Status <- factor(df_long$Status,
levels = status_columns,
labels = c("Susceptible", "Infected", "Recovered", "Dead"))

df_long$Status <- factor(
df_long$Status,
levels = status_columns,
labels = c("Susceptible", "Infected", "Recovered", "Dead")
)

# Create the plot
p <- ggplot(df_long, aes(x = time, y = Count, color = Status)) +
geom_line() +
scale_color_manual(values = c("Susceptible" = "blue",
"Infected" = "red",
"Recovered" = "green",
"Dead" = "black")) +
scale_color_manual(
values = c(
"Susceptible" = "blue",
"Infected" = "red",
"Recovered" = "green",
"Dead" = "black"
)
) +
theme_minimal() +
labs(title = "SIR Model Flow",
x = "Time",
y = "Count") +
theme(legend.position = "right",
plot.title = element_text(hjust = 0.5),
panel.grid.minor = element_blank())
labs(
title = "SIR Model Flow",
x = "Time",
y = "Count"
) +
theme(
legend.position = "right",
plot.title = element_text(hjust = 0.5),
panel.grid.minor = element_blank()
)

# Display the plot
print(p)
Expand Down
48 changes: 25 additions & 23 deletions R/zzz.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ local <- new.env()
#' @param python_version Character. Python version to use (e.g., "3.8")
#' @return Logical indicating success
#' @keywords internal
create_python_env <- function(env_name = "r-reticulate", python_version = "3.9") {
create_python_env <- function(
env_name = "r-reticulate",
python_version = "3.9") {
tryCatch({
# Check if virtualenv package is available
if (!reticulate::virtualenv_exists(env_name)) {
message(sprintf("Creating new Python virtual environment: %s", env_name))

# Create virtual environment with system site packages to help with SSL
reticulate::virtualenv_create(
envname = env_name,
Expand All @@ -20,37 +21,37 @@ create_python_env <- function(env_name = "r-reticulate", python_version = "3.9")
system_site_packages = TRUE
)
}

# Activate the environment
reticulate::use_virtualenv(env_name, required = TRUE)
return(TRUE)
}, error = function(e) {
warning(sprintf("Failed to create/activate Python environment: %s", e$message))
warning(sprintf("Failed to create/activate Python environment: %s",
e$message))
return(FALSE)
})
}

.onLoad <- function(libname, pkgname) {
# Create and activate Python environment
env_success <- create_python_env()

if (!env_success) {
warning("Failed to set up Python environment. Some functionality may be limited.")
warning("Failed to set up Python environment.
Some functionality may be limited.")
return()
}

# Configure reticulate to use the package's environment
reticulate::configure_environment(pkgname)

# Install required packages if not present
ensure_python_dependencies()

# Import dependencies with error handling
tryCatch({
load_python_modules()
}, error = function(e) {
warning(sprintf("Error loading Python dependencies:
%s\nPlease run check_python_env() to diagnose issues.", e$message))
warning(sprintf(
"Error loading Python dependencies: %s\nPlease
run check_python_env() to diagnose issues.",
e$message
))
})
}

Expand All @@ -61,8 +62,8 @@ ensure_python_dependencies <- function() {
reticulate::py_run_string("
import sys
import subprocess
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'--upgrade', 'pip'])
subprocess.check_call([sys.executable
, '-m', 'pip', 'install', '--upgrade', 'pip'])
")
# Install required packages
reticulate::py_run_string("
Expand All @@ -72,9 +73,8 @@ import subprocess
# Install basic packages
packages = ['numpy', 'pandas', 'matplotlib']
for package in packages:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'--upgrade', package])
subprocess.check_call([sys.executable, '-m', 'pip',
'install', '--upgrade', package])
# Install pyEpiabm from GitHub
subprocess.check_call([
sys.executable, '-m', 'pip', 'install', '--upgrade',
Expand All @@ -94,9 +94,9 @@ for package in packages:
print('Missing packages:', missing if missing else 'None')
")
if (length(result$missing) > 0){
stop("Failed to install required packages: ", paste(result$missing,
collapse = ", "))
if (length(result$missing) > 0) {
stop("Failed to install required packages: ",
paste(result$missing, collapse = ", "))
}
message("All required packages installed successfully")
}
Expand Down Expand Up @@ -132,8 +132,9 @@ check_python_env <- function() {
# Print Python information
cat(sprintf("Python version: %s\n", reticulate::py_version()))
cat(sprintf("Python path: %s\n", python_config$python))
cat(sprintf("virtualenv: %s\n", if (is.null(python_config$virtualenv))
"None" else python_config$virtualenv))
cat(sprintf("virtualenv: %s\n",
if (is.null(python_config$virtualenv)) "None"
else python_config$virtualenv))
# Check required packages
required_packages <- c("numpy", "pandas", "matplotlib", "pyEpiabm")
cat("\nPackage Status:\n")
Expand All @@ -142,8 +143,9 @@ check_python_env <- function() {
if (reticulate::py_module_available(pkg)) {
# Try to get version information
tryCatch({
version <- reticulate::py_eval(sprintf("__import__('%s').__version__",
pkg))
version <- reticulate::py_eval(
sprintf("__import__('%s').__version__", pkg)
)
cat(sprintf("✓ %s (version %s)\n", pkg, version))
pkg_status[[pkg]] <- TRUE
}, error = function(e) {
Expand Down

0 comments on commit 2208d1f

Please sign in to comment.