diff --git a/EMOD/analyze_sim.py b/EMOD/analyze_sim.py
index b6fba661..4f51b7ee 100644
--- a/EMOD/analyze_sim.py
+++ b/EMOD/analyze_sim.py
@@ -62,7 +62,7 @@ class SurveyAllAgeAnalyzer(IAnalyzer):
Args:
expt_name (str): Name of the experiment.
sweep_variables (list): List of sweep variables. Defaults to None.
- inset_channels (list): List of inset channels. Defaults to None.
+ channels (list): List of inset channels. Defaults to None.
daily (bool): Flag indicating whether the data is daily. Defaults to False.
working_dir (str): Working directory for the analysis. Defaults to "./".
start_year (int): Start year of the simulation. Defaults to 2022.
@@ -482,19 +482,19 @@ class AnnualAgebinAnalyzer(IAnalyzer):
and save a results dataframe for defined age groups over time (years).
Parameters:
- - expt_name (str): Name of the experiment.
- - sweep_variables (list): List of sweep variables. Defaults to None.
- - working_dir (str): Working directory for the analysis. Defaults to './'.
- - start_year (int): Start year of the simulation experiment. Defaults to 1920.
- - end_year (int): End year of the simulation experiment. Defaults to 2020.
- - age_groups_aggregates (list): List of age group aggregates. Defaults to None.
- - burnin (None or int): Number of burn-in iterations. Defaults to None.
+ expt_name (str): Name of the experiment.
+ sweep_variables (list): List of sweep variables. Defaults to None.
+ working_dir (str): Working directory for the analysis. Defaults to './'.
+ start_year (int): Start year of the simulation experiment. Defaults to 1920.
+ end_year (int): End year of the simulation experiment. Defaults to 2020.
+ age_groups_aggregates (list): List of age group aggregates. Defaults to None.
+ burnin (None or int): Number of burn-in iterations. Defaults to None.
Saves:
mmmpy_yr.csv
Returns:
- None
+ None: This method does not return a value.
"""
def __init__(self, expt_name, sweep_variables=None, working_dir='./', start_year=1920,
@@ -806,10 +806,9 @@ class FiveDayAgebinAnalyzer(IAnalyzer):
end_year (int): End year of the simulation experiment. Defaults to 2020.
age_groups_aggregates (list): List of age group aggregates. Defaults to None.
burnin (None or int): Number of burn-in iterations. Defaults to None.
- cc (bool): Flag for change in conditions. Defaults to False.
Saves:
- mmmpy_5day.csv (or mmmpy_ccstep_daily.csv if cc is True)
+ mmmpy_5day.csv
Returns:
None
diff --git a/EMOD/utils.py b/EMOD/utils.py
index 46174f49..a0fd3480 100644
--- a/EMOD/utils.py
+++ b/EMOD/utils.py
@@ -281,15 +281,15 @@ def config_sweep_builder(exp, scen_df):
and configures EMOD simulation parameters related to demographics and mortality.
Args:
- task (EMODTask): The EMOD task object that represents the simulation run. The task will be updated with
- demographic data and the relevant parameters.
- exp (ExperimentConfig): An instance of the `ExperimentConfig` class containing the experiment settings,
- including population size and input file paths. This object is used to update the
- demographics and configuration for the simulation.
+ exp (ExperimentConfig): An instance of the `ExperimentConfig` class that contains all the parameters
+ necessary to configure and run the EMOD simulation. This includes simulation
+ duration, entomology mode, burn-in period, platform configuration, and more.
+ scen_df (pandas.DataFrame): A DataFrame containing the scenario data to be used for the experiment.
+ The dataframe should include the scenario IDs and relevant parameters
+ that define the experiment conditions.
Returns:
- EMODTask: The updated `task` object with demographic and simulation parameters configured.
-
+ list[SimulationBuilder]: A list containing the configured simulation builder with all sweep definitions added.
"""
builder = SimulationBuilder()
nseeds = exp.num_seeds
diff --git a/OpenMalaria/analyze_sim.py b/OpenMalaria/analyze_sim.py
index 65fe49cd..12ba590e 100644
--- a/OpenMalaria/analyze_sim.py
+++ b/OpenMalaria/analyze_sim.py
@@ -17,9 +17,6 @@ def parse_args():
specifically for specifying the job directory and an optional experiment ID.
The job directory is required to locate the `exp.obj` file.
- Args:
- None
-
Returns:
argparse.Namespace: A Namespace object containing the parsed arguments.
The object has the attribute `directory` which corresponds to the user-provided path
@@ -192,11 +189,11 @@ def InputEIRAnalyzer(exp, mm, start_year, survey_step_days=30, compr='infer'):
Run the InputEIRAnalyzer for OpenMalaria experiments.
Args:
- exp: The experiment object.
- mm: The measure map object.
- start_year: The start year of the analysis.
- survey_step_days: The survey step interval in days (default: 30).
- compr: The compression method for saving the output CSV files (default: 'infer').
+ exp (ExperimentConfig): The experiment configuration object.
+ mm (dict): The measure map object.
+ start_year (int): The start year of the analysis.
+ survey_step_days (int): The survey step interval in days. Defaults to 30.
+ compr (str): Compression method for saving output CSV files. Defaults to 'infer'.
Saves:
One or more CSV files based on the `daily` flag:
diff --git a/OpenMalaria/utils.py b/OpenMalaria/utils.py
index 66c8df58..3b38be02 100644
--- a/OpenMalaria/utils.py
+++ b/OpenMalaria/utils.py
@@ -350,6 +350,7 @@ def write_sh_OpenMalaria(exp):
# Construct the content of the shell script
sh_content = f"""#!/bin/bash
+set -e -o pipefail
# Job settings
job_name="run_openmalaria"
@@ -365,11 +366,15 @@ def write_sh_OpenMalaria(exp):
# Navigate to the job directory
cd "$jobdir" || exit 1
+progress_bar="####################"
+printf 'OpenMalaria [%-20s] 0/{exp.nexps} (0%%)' ""
# Run the OpenMalaria simulation for each experiment
for ((i = 1; i <= {exp.nexps}; i++)); do
# Run the OpenMalaria command and log output and errors
- "{exp.OPENMALARIA_venv}/openMalaria" -s "$jobdir/xml/$i.xml" --output "txt/$i.txt" >> "$log_dir/run_openmalaria.log" 2>> "$log_dir/run_openmalaria.err" || true
+ "{exp.OPENMALARIA_venv}/openMalaria" -s "$jobdir/xml/$i.xml" --output "txt/$i.txt" >> "$log_dir/run_openmalaria.log" 2>> "$log_dir/run_openmalaria.err"
+ printf '\\rOpenMalaria [%-20s] %d/{exp.nexps} (%d%%)' "${{progress_bar:0:$((20 * i / {exp.nexps}))}}" "$i" "$((100 * i / {exp.nexps}))"
done
+printf '\\n'
echo "OpenMalaria simulation complete."
"""
diff --git a/dependencies/run_mmmpy_docker.bat b/dependencies/run_mmmpy_docker.bat
index 26e4fbb7..e24c99cb 100644
--- a/dependencies/run_mmmpy_docker.bat
+++ b/dependencies/run_mmmpy_docker.bat
@@ -1,33 +1,40 @@
@echo off
+setlocal
REM Check if Docker is installed
where docker >nul 2>nul
IF %ERRORLEVEL% NEQ 0 (
echo Docker is not installed. Please install Docker first.
pause
- exit /b
+ exit /b 1
)
REM Pull the Docker image
docker pull multimalmodpy/mmmpy_local:rocky8
+if errorlevel 1 (
+ echo Docker image download failed. Check that Docker Desktop is running.
+ pause
+ exit /b 1
+)
REM Ask the user for model names
set /p "MODELS=Enter models to run (e.g. malariasimulation OpenMalaria): "
-REM Get two levels up from current directory
-for %%i in ("%cd%\..\..") do set "REPO_PATH=%%~fi"
+REM Resolve the repository relative to this script.
+for %%i in ("%~dp0..") do set "REPO_PATH=%%~fi"
REM Display what will run
echo Running Docker with models: %MODELS%
-echo Mounting %REPO_PATH% to /mnt/c/projects
+echo Mounting %REPO_PATH% to /mnt/c/projects/MultiMalModPy
REM Escape the MODELS variable for safe injection into bash command
REM We surround %MODELS% with double quotes inside single quotes to preserve spacing
docker run -it --rm ^
- -v "%REPO_PATH%:/mnt/c/projects" ^
+ -v "%REPO_PATH%:/mnt/c/projects/MultiMalModPy" ^
multimalmodpy/mmmpy_local:rocky8 ^
/bin/bash -c "source /opt/envs/mmmpy_local/bin/activate && cd /mnt/c/projects/MultiMalModPy && python launch_sim.py --models %MODELS% --test"
+set "RUN_EXIT_CODE=%ERRORLEVEL%"
echo.
pause
-
+exit /b %RUN_EXIT_CODE%
\ No newline at end of file
diff --git a/docs/getting_started/installation.md b/docs/getting_started/installation.md
index 20fa3ecf..ce813d1b 100644
--- a/docs/getting_started/installation.md
+++ b/docs/getting_started/installation.md
@@ -131,7 +131,8 @@ Activate the Virtual Environment via:
```
.\my_venv\Scripts\activate # Linux/macOS
-source my_venv/bin/activate # Windows
+source my_venv/bin/activate # Windows (CMD)
+.\my_venv\Scripts\Activate.ps1 # Windows (PowerShell)
```
Install Dependencies:
@@ -384,6 +385,8 @@ Update your manifest.py:
r_local = "C:/Program Files/R/R-4.2.3/bin"
```
+Replace the version in this example with your installed R version. This directory must contain `Rscript.exe`, and the packages above must be installed in a library accessible to that R installation. This host setting is not used by the local Docker image.
+
----------------
@@ -401,7 +404,15 @@ See full run instructions: [Example run](../getting_started/example_run.md#usin
### Using Docker (Local)
-Navigate to dependencies and double click on `run_mmmpy_docker.bat`
+Start Docker Desktop and wait for its Linux engine to be running. Then double-click `dependencies/run_mmmpy_docker.bat` and select `OpenMalaria` or `malariasimulation`. The image provides Python, R, and these model dependencies; a host Python or R installation is not required for this route.
+
+In the existing `elif hpc == 'LOCAL':` section of `manifest.py`, ensure the Docker activation setting is:
+
+```python
+EMOD_venv_container = 'source /opt/envs/mmmpy_local/bin/activate'
+```
+
+Docker is detected automatically; no `container_run` setting is required.
Manual Docker setup:
@@ -414,12 +425,12 @@ docker images
```
```
-# Run interactively (optional to test it)
+# Inside a container with the repository mounted at /mnt/c/projects/MultiMalModPy:
source /opt/envs/mmmpy_local/bin/activate
-cd /mnt/c/projects
+cd /mnt/c/projects/MultiMalModPy
python launch_sim.py --models OpenMalaria --test
```
-Note: Inside Docker, you usually don’t need to activate a virtual environment. The Python in the image is ready to use.
+Use the `mmmpy_local` environment inside the container, as the launcher and command below do.
Mount local project to the container to run a test simulation (from host):
diff --git a/docs/getting_started/usage.md b/docs/getting_started/usage.md
index 52cdbcbc..681c2392 100644
--- a/docs/getting_started/usage.md
+++ b/docs/getting_started/usage.md
@@ -14,8 +14,8 @@ _This page provides a concise overview of the main steps to configure, launch, a
❌ If not, revisit the
- ➡️ Installation guide
- ➡️ First-time configuration
+ ➡️ Installation guide
+ ➡️ First-time configuration
diff --git a/malariasimulation/analyze_sim.py b/malariasimulation/analyze_sim.py
index 24b88b6a..54c71b37 100644
--- a/malariasimulation/analyze_sim.py
+++ b/malariasimulation/analyze_sim.py
@@ -19,9 +19,6 @@ def parse_args():
specifically for specifying the job directory and an optional experiment ID.
The job directory is required to locate the `exp.obj` file.
- Args:
- None
-
Returns:
Namespace: A namespace object containing the parsed command-line arguments.
The attributes include:
@@ -49,15 +46,16 @@ def parse_args():
def convert_to_long(output, age_groups):
"""
Convert the dataframe to long form for the desired columns.
-
+ For each specified age group, age-specific population, prevalence,
+ incidence, and mosquito-related outputs are extracted and combined
+ into a single long-format DataFrame.
+
Args:
output (pandas.DataFrame): Input dataframe.
- age_min (list): Minimum age values.
-
- age_max (list): Maximum age values.
+ age_groups (list): List of age groups, where each element contains the lower and upper age bounds in days.
Returns:
- pandas.DataFrame: Long-form output.
+ pandas.DataFrame: Long-format DataFrame with one set of rows per specified age group.
"""
result = []
for pair in age_groups:
@@ -94,8 +92,9 @@ def post_processing(exp, job_directory, pv_suffix=''):
This was previously done in R, but was brought to python to match the two other models.
Args:
- exp: Experiment object.
- job_directory: Directory containing raw simulation output files.
+ exp (ExperimentConfig): The experiment configuration object.
+ job_directory (str): Directory containing raw simulation output files.
+ pv_suffix (str): Suffix for parameter variation files.
Saves:
{i}_daily.csv: for each simulation {i} in an experiment, saves the processed daily output.
diff --git a/malariasimulation/utils.py b/malariasimulation/utils.py
index 99720f2a..54134162 100644
--- a/malariasimulation/utils.py
+++ b/malariasimulation/utils.py
@@ -297,23 +297,42 @@ def write_sh_malariasimulation(exp):
log_dir="$jobdir/log"
# Navigate to the working directory
-cd $work_dir
+cd "$work_dir"
# Create log directory if it doesn't exist
if [ ! -d "$log_dir" ]; then
mkdir -p "$log_dir"
fi
-# Run the OpenMalaria simulation for each experiment
+# Run each simulation in the background and retain its process ID.
+pids=()
for ((i = 1; i <= {nexps}; i++)); do
Rscript "$work_dir/malariasimulation.R" "$work_dir" "$jobdir" $i >> "$log_dir/run_malariasimulation.log" 2>> "$log_dir/run_malariasimulation.err" &
- echo "Simulation $i completed successfully" >> "$log_dir/run_malariasimulation.log"
+ pids+=("$!")
done
-# Wait for all background jobs to finish
-wait
+# Wait for every child and check its own exit status.
+failed=0
+completed=0
+progress_bar="####################"
+printf 'malariasimulation [%-20s] 0/{nexps} (0%%)' ""
+for i in "${{!pids[@]}}"; do
+ if wait "${{pids[$i]}}"; then
+ echo "Simulation $((i + 1)) completed successfully" >> "$log_dir/run_malariasimulation.log"
+ completed=$((completed + 1))
+ printf '\\rmalariasimulation [%-20s] %d/{nexps} (%d%%)' "${{progress_bar:0:$((20 * completed / {nexps}))}}" "$completed" "$((100 * completed / {nexps}))"
+ else
+ printf '\\n'
+ echo "Simulation $((i + 1)) failed. See $log_dir/run_malariasimulation.err" >&2
+ failed=1
+ fi
+done
+printf '\\n'
+if ((failed)); then
+ exit 1
+fi
echo "All simulations completed successfully."
"""
diff --git a/manifest.py b/manifest.py
index ecc61afc..0e8fbca3 100644
--- a/manifest.py
+++ b/manifest.py
@@ -138,7 +138,7 @@
image_path = 'mmmpy_local:rocky8'
image_venv_name = ''
- EMOD_venv_container ='source /opt/envs/mmmpy_container/bin/activate'
+ EMOD_venv_container ='source /opt/envs/mmmpy_local/bin/activate'
bind_path = ROOT_DIR
else:
diff --git a/plotter/plot_agecurves.py b/plotter/plot_agecurves.py
index 1689bf75..9cff29ec 100644
--- a/plotter/plot_agecurves.py
+++ b/plotter/plot_agecurves.py
@@ -50,7 +50,7 @@ def age_curves(fdir, df, channel, sweepvar='models', facet_var='target_output_va
ValueError: If `facet_var` is set to 'ageGroup'.
Returns:
- None: The function saves the generated plot to disk in the specified format.
+ None: The generated plot is saved to disk in the specified format.
"""
if facet_name is None:
diff --git a/plotter/plot_ccstep.py b/plotter/plot_ccstep.py
index 54612251..d9ec8d94 100644
--- a/plotter/plot_ccstep.py
+++ b/plotter/plot_ccstep.py
@@ -24,12 +24,17 @@
def daily_timeseries(fdir, df_all, channel_list, sweepvar='models', facet_var='ageGroup', agegrp='5-10'):
"""
Parameters:
- fdir (str): Directory where the plot will be saved.
- df_all (pandas dataframe): Dataframe that includes combined model results.
- channel (str): Variable representing the y-axis data to be plotted.
- sweepvar (str, optional): Variable to group the data and create multiple lines on the plot. Default is 'models'.
- facet_var (str, optional): Variable used to create subplots based on its unique values. Default is 'ageGroup'. (The default should change)
- agegrp (str, optional): Age group filter for the data. Default is '5-10'.
+ fdir (str): Directory where generated plots are saved.
+ df_all (pandas.DataFrame): Combined model results containing daily
+ simulation outputs and plotting variables.
+ channel_list (list[str]): Variables to plot on the y-axis.
+ sweepvar (str): Variable used to group data into separate lines.
+ Defaults to 'models'.
+ facet_var (str): Variable used to create separate subplot panels.
+ Defaults to 'ageGroup'.
+ agegrp (str or None): Age group used to filter the data when
+ `facet_var` is not 'ageGroup'. If None, data across age groups
+ are combined. Defaults to '5-10'.
Returns:
None (plots are saved to disk).
"""
@@ -43,7 +48,7 @@ def daily_timeseries(fdir, df_all, channel_list, sweepvar='models', facet_var='a
for channel in channel_list:
print(f'#----- Plotting daily timeseries for {channel}-----#')
if channel == 'prevalence_2to10':
- ylab = channel.replace('prevalence_2to10', '$\it{Pf}$PR$_{2-10}$ (%)')
+ ylab = channel.replace('prevalence_2to10', r'$\mathit{Pf}$PR$_{2-10}$ (%)')
else:
ylab = channel.replace('_', ' ')
@@ -105,7 +110,7 @@ def daily_timeseries(fdir, df_all, channel_list, sweepvar='models', facet_var='a
ax.xaxis.set_major_locator(mdates.AutoDateLocator(maxticks=8))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax.set_xlabel('Year')
- ax.set_title('$\it{Pf}$PR$_{2-10}$' + f': {facet}')
+ ax.set_title(r'$\mathit{Pf}$PR$_{2-10}$' + f': {facet}')
fname = f'timeseries_daily_{seasonality}_cm{cm}_{channel}_{agegrp}_by_{sweepvar}'
fig.savefig(os.path.join(fdir, f'{fname}.png'), bbox_extra_artists=(lg,), bbox_inches='tight')
plt.close()
@@ -115,14 +120,19 @@ def daily_timeseries(fdir, df_all, channel_list, sweepvar='models', facet_var='a
def daily_timeseries_by_seed(fdir, df_all, channel_list, sweepvar='models', facet_var='ageGroup', agegrp='0-100'):
"""
Parameters:
- fdir (str): Directory where the plot will be saved.
- df_all (pandas dataframe): Dataframe that includes combined model results.
- channel (str): Variable representing the y-axis data to be plotted.
- sweepvar (str, optional): Variable to group the data and create multiple lines on the plot. Default is 'models'.
- facet_var (str, optional): Variable used to create subplots based on its unique values. Default is 'ageGroup'. (The default should change)
- agegrp (str, optional): Age group filter for the data. Default is '5-10'.
+ fdir (str): Directory where generated plots are saved.
+ df_all (pandas.DataFrame): Combined model results containing daily
+ simulation outputs and plotting variables.
+ channel_list (list[str]): Variables to plot on the y-axis.
+ sweepvar (str): Variable used to group data into separate lines.
+ Defaults to 'models'.
+ facet_var (str): Variable used to create separate subplot panels.
+ Defaults to 'ageGroup'.
+ agegrp (str or None): Age group used to filter the data when
+ `facet_var` is not 'ageGroup'. If None, data across age groups
+ are combined. Defaults to '5-10'.
Returns:
- None (plots are saved to disk).
+ None: (plots are saved to disk).
"""
df_all = df_all[df_all['timestep'] >= 1460] # remove the first 4 years of the 55 year monitoring period
@@ -132,7 +142,7 @@ def daily_timeseries_by_seed(fdir, df_all, channel_list, sweepvar='models', face
for channel in channel_list:
print(f'#----- Plotting daily timeseries for {channel}-----#')
if channel == 'prevalence_2to10':
- ylab = channel.replace('prevalence_2to10', '$\it{Pf}$PR$_{2-10}$ (%)')
+ ylab = channel.replace('prevalence_2to10', r'$\mathit{Pf}$PR$_{2-10}$ (%)')
else:
ylab = channel.replace('_', ' ')
@@ -266,7 +276,7 @@ def daily_vectors(fdir, df_all, channel, sweepvar='models', facet_var='ageGroup'
ax.xaxis.set_major_locator(mdates.AutoDateLocator(maxticks=8))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax.set_xlabel('Year')
- ax.set_title('$\it{Pf}$PR$_{2-10}$' + f': {fi}')
+ ax.set_title(r'$\mathit{Pf}$PR$_{2-10}$' + f': {fi}')
fname = f'timeseries_daily_{channel}_{agegrp}_by_{ii}'
fig.savefig(os.path.join(fdir, f'{fname}.png'), bbox_extra_artists=(lg,), bbox_inches='tight')
diff --git a/plotter/plot_helper.py b/plotter/plot_helper.py
index 2c3163dc..be7ca285 100644
--- a/plotter/plot_helper.py
+++ b/plotter/plot_helper.py
@@ -343,8 +343,8 @@ def get_label(channel):
Args:
channel (str): The name of the channel for which to retrieve the label.
Possible values include (but are not limited to):
- - 'prevalence_2to10': Represents $\it{Pf}$PR$_{2-10}$ (%) prevalence.
- - 'prevalence': Represents $\it{Pf}$PR (%) prevalence.
+ - 'prevalence_2to10': Represents $\mathit{Pf}$PR$_{2-10}$ (%) prevalence.
+ - 'prevalence': Represents $\mathit{Pf}$PR (%) prevalence.
- 'clinical_incidence': Represents clinical incidence (per person per year).
- 'severe_incidence': Represents severe incidence (per person per year).
- 'eir': Represents simulated entomological inoculation rate (EIR).
@@ -412,14 +412,13 @@ def clean_fname(fname, sweepvar=None, unique_groups=None, facet_var=None, unique
Args:
fname (str): The filename to be cleaned and modified.
sweepvar (str, optional): The name of the sweep variable in the filename. Defaults to None.
- unique_groups (list, optional): A list of unique group names (e.g., model names) to replace
- the sweep variable placeholder. Defaults to None.
+ unique_groups (list, optional): A list of unique group names (e.g., model names) to replacethe sweep variable placeholder. Defaults to None.
facet_var (str, optional): The name of the facet variable in the filename. Defaults to None.
unique_facets (list, optional): A list of unique facet names to replace the facet variable
placeholder. Defaults to None.
Returns:
- str: The cleaned and modified filename.
+ str: Cleaned and modified filename.
"""
if unique_facets is not None:
if len(unique_facets) == 1 and not isinstance(unique_facets[0], int):
@@ -457,7 +456,7 @@ def subset_dataframe_for_plot(df, figure_vars, agegrps=None, filter_target=True)
Raises:
ValueError: If 'models' is not included in `figure_vars` and there
- are multiple unique model names in the DataFrame.
+ are multiple unique model names in the DataFrame.
"""
txt = 'Filtered dataset by: '
diff --git a/plotter/plot_relationship.py b/plotter/plot_relationship.py
index b6ada387..e46d1bd9 100644
--- a/plotter/plot_relationship.py
+++ b/plotter/plot_relationship.py
@@ -110,7 +110,7 @@ def prevalence2to10_to_outcome(
ax.set_xlim(0, 1)
ax.set_xticks([0, 0.2, 0.4, 0.6, 0.8, 1])
ax.set_ylabel(get_label(channel))
- ax.set_xlabel('$\it{Pf}$PR$_{2-10}$ (%)')
+ ax.set_xlabel(r'$\mathit{Pf}$PR$_{2-10}$')
if firstPlot:
lg_title = get_legend_title(sweepvar, exp)
lg = ax.legend(loc='upper left', bbox_to_anchor=(0.5, 1.2), title=lg_title)
@@ -229,7 +229,7 @@ def prevalence2to10_to_outcome_by_age_and_model(fdir, df, channel='clinical_inci
ax.set_xlim(0, 1)
ax.set_xticks([0, 0.20, 0.40, 0.60, 0.80, 1])
ax.set_ylabel(f'{ages_labels[a]}\n,{get_label(channel)}')
- ax.set_xlabel('$\it{Pf}$PR$_{2-10}$')
+ ax.set_xlabel(r'$\mathit{Pf}$PR$_{2-10}$')
fname = f'pfpr2to10_to_{channel}_age_model_{season}'
fig.savefig(os.path.join(fdir, f'{fname}.png'), bbox_inches='tight')
diff --git a/utility/helper.py b/utility/helper.py
index 9650de8c..c1341e69 100644
--- a/utility/helper.py
+++ b/utility/helper.py
@@ -22,9 +22,6 @@ def parse_launch_args():
The arguments specify parameters such as the job directory, suite name, experiment name, model to run, user directory,
interventions, run mode, and output type. The parsed arguments are returned as a Namespace object.
- Args:
- None
-
Returns:
argparse.Namespace: An object containing the parsed command-line arguments.
@@ -525,8 +522,8 @@ def create_scenarios_csv(exp, col_list):
Defaults to ['target_output_values', 'case_management', 'seasonality'].
Returns:
- pandas.DataFrame: A DataFrame representing all generated scenarios, including metadata
- and mapped inputs.
+ pandas.DataFrame: DataFrame containing the generated scenarios and
+ associated experiment metadata and input parameters.
"""
if col_list is None:
diff --git a/utility/helper_calibration.py b/utility/helper_calibration.py
index b8a20a6c..dabcfe5a 100644
--- a/utility/helper_calibration.py
+++ b/utility/helper_calibration.py
@@ -94,30 +94,33 @@ def output_target_to_xTemp(df, exp, model):
def output_target_to_eir(df, exp, model):
"""
- Interpolates and adjusts the output target to the expected EIR (Entomological Inoculation Rate) values
- based on input data for different models and experimental conditions.
+ Interpolate target outputs to expected EIR (Entomological Inoculation Rate)
+ values for different models and experimental conditions.
Args:
- df (pd.DataFrame): DataFrame containing simulation job data, where each row represents a specific condition
- (e.g., `target_output_values`, `cm_clinical`, `seasonality`).
- exp (Experiment): Experiment object that contains attributes such as `interp_path`, `target_output_name`, `pop_size`,
- and others required for interpolation.
- model (str): The model name used in the interpolation (e.g., 'malariasimulation', 'OpenMalaria').
+ df (pd.DataFrame): Simulation scenario data, with one row per condition
+ and columns such as `target_output_values`, `cm_clinical`, and
+ `seasonality`.
+ exp (Experiment): Experiment configuration containing interpolation
+ settings, including `interp_path`, `target_output_name`, `pop_size`,
+ and related parameters.
+ model (str): Model used for interpolation, for example
+ 'malariasimulation' or 'OpenMalaria'.
Returns:
- list: A list of interpolated EIR values corresponding to each row of the input DataFrame.
+ list[float]: Interpolated EIR values corresponding to the rows of `df`.
Raises:
- ValueError: If the interpolation file is not found at the specified path.
- ValueError: If the `target_output_name` specified in the experiment object is not valid.
+ ValueError: If the interpolation file cannot be found at `interp_path`.
+ ValueError: If `target_output_name` is not one of the supported output
+ types.
Notes:
- - The function performs interpolation based on the specified output type (`eir`, `prevalence_2to10`, or
- `clinical_incidence_U5`).
- - It applies scaling adjustments for population sizes, ensuring that the values are consistent with the
- `pop_size` defined in the experiment.
- - Warnings are issued if the interpolated values are outside the valid range (`<= 0` or `>= 1000`), with
- adjustments made to these values accordingly.
+ The interpolation depends on the selected target output, such as `eir`,
+ `prevalence_2to10`, or `clinical_incidence_U5`. Population-size scaling
+ may be applied based on `exp.pop_size`. Interpolated values outside the
+ allowed range are adjusted, with warnings issued for values <= 0 or
+ >= 1000.
"""
interp_path = os.path.join(exp.interp_path, model, exp.interp_csv)
if not os.path.exists(interp_path):
diff --git a/utility/helper_local.py b/utility/helper_local.py
index 633e8c35..f64499df 100644
--- a/utility/helper_local.py
+++ b/utility/helper_local.py
@@ -100,7 +100,7 @@ def write_ps1_runmodel(exp, filename, model):
ValueError: If the provided models is empty or if exp.job_directory is not valid.
Returns:
- None: This function does not return a value but writes the PowerShell script to the specified file.
+ None: The PowerShell script is written to `filename`.
"""
# Check for valid models and experiment directory
@@ -120,24 +120,29 @@ def write_ps1_runmodel(exp, filename, model):
# Start the first job
$job1 = Start-Job -ScriptBlock {{
+ $ErrorActionPreference = "Stop"
+ $global:LASTEXITCODE = 0
try {{
# Run the first script: run_{model}.ps1
Write-Host "Running job 1: run_{model}.ps1"
& "{os.path.normpath(exp.job_directory)}\\run_{model}.ps1"
+ if ($LASTEXITCODE -ne 0) {{
+ throw "Simulation exited with code $LASTEXITCODE"
+ }}
}} catch {{
- Write-Error "Job 1 failed: $_"
+ throw "Job 1 failed: $_"
}}
}}
# Wait for the first job to complete
- Receive-Job -Job $job1 -Wait
- if ($job1.State -eq 'Completed') {{
- Write-Host "Job 1 completed successfully."
- }} else {{
- Write-Error "Job 1 did not complete successfully."
- }}
+ Receive-Job -Job $job1 -Wait -ErrorAction Continue
+ $simulationFailed = ($job1.State -ne 'Completed') -or ($job1.ChildJobs[0].Error.Count -gt 0)
$job1 | Remove-Job
Stop-Transcript
+ if ($simulationFailed) {{
+ throw "Simulation failed; analysis was not started. See $LogFile for details."
+ }}
+ Write-Host "Job 1 completed successfully."
# Start the second job (only after the first job completes)
@@ -192,7 +197,7 @@ def submit_runmodel_local(exp, model):
file_name = f'jobs_{model}_simplerun.ps1'
file_path = os.path.join(exp.job_directory, file_name)
write_ps1_runmodel(exp,filename=file_path, model=model)
- cmd_command = f'cmd.exe /c start powershell -ExecutionPolicy Bypass -File "{file_path}"'
+ cmd_command = f'cmd.exe /c start powershell -NoExit -ExecutionPolicy Bypass -File "{file_path}"'
subprocess.Popen(cmd_command, shell=True)
@@ -205,14 +210,18 @@ def create_ps1_script(exp, fname, subdir, job_name, py_command):
4. Pauses the script to keep the console open until the user presses Enter.
Args:
- exp (object): An experiment object containing the 'job_directory' attribute for saving the script.
- fname (str): The name of the PowerShell script file to be created.
- subdir (str): The subdirectory within the working directory where the Python command should be executed.
- job_name (str): The name of the job, used for log file naming and script content.
- pycommand (str): The Python command to be executed within the PowerShell script.
+ exp (object): Experiment object containing the `job_directory`
+ attribute used to save the script and log files.
+ fname (str): Name of the PowerShell script file to create.
+ subdir (str): Subdirectory in which the Python command is executed.
+ job_name (str): Job name used in the script and log file names.
+ py_command (str): Python command to execute within the PowerShell script.
Raises:
- IOError: If there is an issue with writing the PowerShell script to the file.
+ IOError: If the PowerShell script cannot be written to disk.
+
+ Returns:
+ None: The function writes the PowerShell script to disk.
"""
# Construct paths
file_path = os.path.join(exp.job_directory, fname)
@@ -258,13 +267,13 @@ def write_ps1_analyzer(exp, pyscript, model):
"""
job_name = f"analyzer_{model}"
subdir = model
- pycommand = f'python {pyscript} --directory "{exp.job_directory}"\n'
+ pycommand = f'python {pyscript} --directory "{exp.job_directory}"'
if model =='malariasimulation':
if exp.malariasimulation_parameter_variation == "both" :
pycommand = pycommand + f'\npython analyze_sim.py --dir "{exp.job_directory}" --mpv'
if exp.malariasimulation_parameter_variation == "yes" :
- pycommand = pycommand + '--mpv'
+ pycommand = pycommand + ' --mpv'
fname = f'run_analyze_{model}.ps1'
create_ps1_script(exp, fname, subdir, job_name, pycommand )
@@ -314,10 +323,10 @@ def write_bat_submission_plots(exp):
Args:
exp (Experiment): The experiment object containing the necessary directories and model names.
- filename (str): The file path where the batch script will be saved.
Returns:
- None
+ None: The batch submission script is written to the experiment
+ job directory.
"""
# Extract relevant data from the experiment object
wdir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
diff --git a/utility/helper_local_docker.py b/utility/helper_local_docker.py
index 3e9ccb76..56ce06a3 100644
--- a/utility/helper_local_docker.py
+++ b/utility/helper_local_docker.py
@@ -1,5 +1,6 @@
import os
import subprocess
+import shlex
import stat
from datetime import datetime as dt
@@ -7,9 +8,9 @@
#### Running locally from inside docker
def exec(exp, command):
"""
- Executes a shell command in a subprocess, capturing its output and errors.
+ Executes a shell command in a subprocess, showing its output and errors in the terminal.
This function runs the specified command within the given experiment's job directory,
- capturing both standard output and error streams. It also ensures the process runs in a
+ forwarding both standard output and error streams to the terminal. It also ensures the process runs in a
separate session, preventing it from being terminated if the parent process exits.
Args:
@@ -21,26 +22,10 @@ def exec(exp, command):
None
"""
- process = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
- universal_newlines=True, text=True, cwd=exp.job_directory,
- start_new_session=True)
-
- # Capture the output and errors
- stdout, stderr = process.communicate()
-
- # Print output and errors (if any)
- print("=== STDOUT ===")
- print(stdout)
-
- print("=== STDERR ===")
- if stderr:
- print(stderr)
-
- # Check if the process was successful
- if process.returncode != 0:
- print(f" Script failed with exit code {process.returncode}")
- else:
- print("️ Script completed successfully.")
+ # Show progress immediately and propagate a failed command to the launcher.
+ subprocess.run(command, shell=True, cwd=exp.job_directory,
+ start_new_session=True, check=True)
+ print("Script completed successfully.", flush=True)
def write_and_execute_sh_script(script_path: str, content: str, exp=None, execute: bool = False):
@@ -54,7 +39,7 @@ def write_and_execute_sh_script(script_path: str, content: str, exp=None, execut
execute (bool, optional): If True, executes the script after writing it. Default is False.
"""
try:
- with open(script_path, "w", encoding="utf-8") as file:
+ with open(script_path, "w", encoding="utf-8", newline="\n") as file:
file.write(content)
print(f"Shell script written to {script_path}")
except OSError as e:
@@ -68,7 +53,7 @@ def write_and_execute_sh_script(script_path: str, content: str, exp=None, execut
if exp is None:
raise ValueError("Experiment object (exp) is required for script execution.")
try:
- exec(exp, command=f"bash {script_path}")
+ exec(exp, command=f"bash {shlex.quote(str(script_path))}")
except Exception as e:
raise RuntimeError(f"Error executing shell script: {e}")
@@ -115,6 +100,7 @@ def submit_run_pyscript_sh(exp, pyscript='plotter/plot_relationship.py', shname=
# Shell script content
sh_content = f"""#!/bin/bash
+set -e -o pipefail
# Activate virtual environment
{exp.EMOD_venv}
@@ -159,7 +145,7 @@ def submit_run_plotters_sh(exp):
# Determine which plots to run
plots_to_run = [p for p in exp.plots_to_run if not p == 'sampleplots']
- if exp.plots_to_run[0] == 'all':
+ if 'all' in exp.plots_to_run:
plots_to_run = plot_names_all
# Create shell scripts for each plot
@@ -265,7 +251,7 @@ def write_sh_analyzer(exp, pyscript, model):
raise ValueError(f"Invalid job directory: {exp.job_directory}")
# Prepare the shell script content
- sh_content = "#!/bin/bash\n\n"
+ sh_content = "#!/bin/bash\nset -e -o pipefail\n\n"
# Job settings
job_name = f"analyze_{model}"
@@ -283,17 +269,21 @@ def write_sh_analyzer(exp, pyscript, model):
venv_activation = f"{exp.EMOD_venv}\n"
sh_content += f"# Activate virtual environment\n{venv_activation}\n"
- # Set custom arguments and run the Python command
+ # Only malariasimulation supports the parameter-variation analyzer.
py_args = f'--directory "{exp.job_directory}"'
- pycommand = f'python {pyscript} {py_args}\n'
-
- if exp.malariasimulation_parameter_variation:
- py_args_mpv = f'--directory "{exp.job_directory}" --mpv'
- pycommand = pycommand + f'python {pyscript} {py_args_mpv}\n'
-
- # Change to the appropriate directory and run the script
- sh_content += f'cd {os.path.join(exp.ROOT_DIR, model)}\n'
- sh_content += pycommand + '>> "$log_dir/run_analyzer_openmalaria.log" 2>> "$log_dir/run_analyzer_openmalaria.err"\n'
+ flags = ['']
+ if model == 'malariasimulation':
+ variation = exp.malariasimulation_parameter_variation
+ if variation not in ('no', 'yes', 'both'):
+ raise ValueError(f'Invalid parameter variation mode: {variation}')
+ flags = {'no': [''], 'yes': [' --mpv'], 'both': ['', ' --mpv']}[variation]
+
+ sh_content += f'cd "{os.path.join(exp.ROOT_DIR, model)}"\n'
+ for flag in flags:
+ sh_content += (f'echo "Running {model} analyzer{flag}; logs: $log_dir"\n'
+ f'python "{pyscript}" {py_args}{flag} '
+ f'>> "$log_dir/run_analyzer_{model}.log" '
+ f'2>> "$log_dir/run_analyzer_{model}.err"\n')
# Write the shell script to a file
write_and_execute_sh_script(script_path=script_path, content=sh_content, exp=exp, execute=False)
@@ -326,6 +316,7 @@ def write_sh_runmodel(exp, filename, model):
# Define the shell script content
sh_content = f"""#!/bin/bash
+set -e -o pipefail
# Start the first job
echo "Running job 1: run_{model}.sh"
@@ -333,7 +324,7 @@ def write_sh_runmodel(exp, filename, model):
# Run the first script: run_{model}.sh
bash "{os.path.normpath(os.path.join(exp.job_directory, 'run_' + model + '.sh'))}"
}} || {{
- echo "Job 1 failed"
+ echo "Simulation failed; analysis skipped. See {exp.job_directory}/log" >&2
exit 1
}}
@@ -345,7 +336,7 @@ def write_sh_runmodel(exp, filename, model):
# Run the second script: analyze_sim_{model}.sh
bash "{os.path.normpath(os.path.join(exp.job_directory, 'run_analyze_' + model + '.sh'))}"
}} || {{
- echo "Job 2 failed"
+ echo "Analysis failed. See {exp.job_directory}/log/run_analyzer_{model}.err" >&2
exit 1
}}
@@ -364,11 +355,10 @@ def write_sh_runmodel(exp, filename, model):
#echo "Job 3 completed successfully."
echo "All jobs completed."
- read -p "Press Enter to close the terminal"
"""
# Write the shell script to a file
- write_and_execute_sh_script(script_path=filename, content=sh_content, exp=exp, execute=True)
+ write_and_execute_sh_script(script_path=filename, content=sh_content, exp=exp, execute=False)
def submit_runmodel_sh(exp, model):
@@ -392,4 +382,4 @@ def submit_runmodel_sh(exp, model):
write_sh_runmodel(exp, filename=file_path, model=model)
# Execute the generated shell script using subprocess
- exec(exp, command=f"bash {file_path}")
\ No newline at end of file
+ exec(exp, command=f"bash {shlex.quote(file_path)}")
\ No newline at end of file
diff --git a/utility/helper_simulation.py b/utility/helper_simulation.py
index 3ffedb99..e75012b2 100644
--- a/utility/helper_simulation.py
+++ b/utility/helper_simulation.py
@@ -119,17 +119,9 @@ def get_seasonal_eir(exp=None):
exp (Experiment, optional): Experiment object containing experiment specifications.
Returns:
- tuple or Experiment: A tuple containing the daily, monthly, seasonal, and perennial EIR values if exp is None.
- If exp is provided, the Experiment object with updated seasonal EIR attributes is returned.
-
- If exp is None:
- - season_daily (list): Defined seasonal shape of daily EIR values.
- - season_month (list): Monthly EIR values calculated from the seasonal pattern.
- - seasonal (list): Seasonal EIR values rescaled within 0 to 1.
- - perennial (list): Perennial EIR values per month.
-
- If exp is provided:
- - exp (Experiment): Experiment object with updated seasonality attributes.
+ tuple[list, list, list, list] or Experiment:
+ If `exp` is None, returns `(season_daily, season_month, seasonal, perennial)`.
+ If `exp` is provided, returns the updated Experiment object.
"""
seasonal = seasonal_inputs.monthly_seasonal_inputs
eir_sum = sum(seasonal)
@@ -151,13 +143,18 @@ def get_seasonal_eir(exp=None):
def monthly_to_daily_EIR(monthly_EIR):
"""
- Convert monthly EIR values to daily using cubic spline interpolation.
+ Convert monthly EIR values to daily EIR values using linear interpolation.
+
+ Monthly EIR values are interpolated across 365 days and converted to
+ approximate daily rates by dividing by 30. Any negative interpolated
+ values are set to zero.
Args:
- monthly_EIR (list of floats): List of monthly EIRs.
+ monthly_EIR (list[float]): Monthly EIR values for the 12 months
+ of the year.
Returns:
- list of floats: List of daily EIRs.
+ list[float]: Daily EIR values for 365 days.
"""
x_monthly = np.linspace(0, 364, num=12, endpoint=True)
x_daily = np.linspace(0, 364, num=365, endpoint=True)
@@ -172,13 +169,17 @@ def monthly_to_daily_EIR(monthly_EIR):
def submit_run_plotters(exp):
"""
- Submits a plotter job for execution, either locally or via SLURM based on the HPC configuration:
- - If running locally, it generates and submits the plotter job using a local submission script.
- - If using SLURM, it delegates the submission to the SLURM-specific plotter submission function.
+ Submit the plotter job using the configured execution environment.
+
+ If the experiment is configured for local execution, the plotter job is
+ submitted using the local helper function. Otherwise, the job is submitted
+ using the SLURM-specific helper function.
Args:
exp (object): An experiment object containing the necessary attributes, such as 'hpc',
to determine the appropriate submission method.
+ Returns:
+ None: The function submits the plotter job and does not return a value.
"""
if exp.hpc == 'LOCAL':
from utility.helper_local import submit_run_plotters_local