Advanced Settings with GeneralSettings#
This notebook demonstrates how to use the advanced.GeneralSettings class to modify UCLCHEM parameters instead of using parameter dictionaries. This provides a more object-oriented interface with better autocomplete, type checking, and state management.
# ty: ignore[unresolved-attribute]
import os
import uclchem
from uclchem import advanced
# Ensure output directory exists
if not os.path.exists("output_6"):
os.makedirs("output_6")
Using GeneralSettings Instead of param_dict#
The traditional way to configure UCLCHEM models is with parameter dictionaries that are passed when running the UCLCHEM model. The GeneralSettings class provides an alternative that directly modifies the Fortran module state before running a model. This has the benefit that you can change things globally, and access things that are not exposed through parameter dictionaries.
Key differences:
Direct access to Fortran variables with autocomplete support
Tracks which settings have been modified
Provides context managers for temporary changes
Settings persist across model runs (not reset automatically)
# Create settings interface
settings = advanced.GeneralSettings()
# View current value
print(f"Current initial density: {settings.defaultparameters.initialdens.get()}")
print(f"Current initial temperature: {settings.defaultparameters.initialtemp.get()}")
Current initial density: 100.0
Current initial temperature: 10.0
Setting Parameters Directly#
Instead of creating a param_dict, we can set parameters directly:
# Set model parameters
settings.defaultparameters.initialdens = 1e4 # type: ignore[attr-defined]
settings.defaultparameters.initialtemp = 10.0 # type: ignore[attr-defined]
settings.defaultparameters.finaltime = 1.0e6 # type: ignore[attr-defined]
settings.defaultparameters.rout = 0.1 # type: ignore[attr-defined]
settings.defaultparameters.baseav = 1.0 # type: ignore[attr-defined]
settings.defaultparameters.freefall = False # type: ignore[attr-defined]
settings.defaultparameters.endatfinaldensity = False # type: ignore[attr-defined]
# Verify changes
print(f"New initial density: {settings.defaultparameters.initialdens.get()}")
# ---
# Example: adjust coolant validation tolerances (frequency/population checks)
# These settings are exposed from the Fortran DEFAULTPARAMETERS module and can be
# changed at runtime via GeneralSettings. Set a 10% relative tolerance for frequencies:
try:
settings.defaultparameters.freq_rel_tol = 0.1 # type: ignore[attr-defined]
print(f"Set freq_rel_tol to: {settings.defaultparameters.freq_rel_tol.get()}")
except Exception:
print("Note: freq_rel_tol not available until Fortran modules are rebuilt; see README.")
# ---
New initial density: 10000.0
Set freq_rel_tol to: 0.1
Running a Model with GeneralSettings#
When using GeneralSettings, the Fortran code uses the values we’ve set directly. However, file paths (outputFile, abundSaveFile) should still be set via param_dict since these are handled specially by the model wrapper and file parsers.
# Ensure output directory exists
if not os.path.exists("output_6"):
os.makedirs("output_6")
# Note: Output file paths should be set via param_dict, not GeneralSettings
# This is because file paths are handled specially by the model wrapper
param_dict = {
"outputFile": "output_6/baseline.dat",
}
# Run model with param_dict for file I/O, but using GeneralSettings for other parameters
cloud = uclchem.model.Cloud(param_dict=param_dict)
print("Model completed successfully")
Model completed successfully
Viewing Modified Settings#
You can check which settings have been changed from their defaults:
# Show all modified settings
settings.print_all_edited()
======================================================================
Modified Settings
======================================================================
defaultparameters:
baseav 2.0 → 1.0
finaltime 5000000.0 → 1000000.0
initialdens 100.0 → 10000.0
rout 0.05000000074505806 → 0.1
Using Context Managers for Temporary Changes#
The temporary_changes() context manager is useful for running models with temporary parameter modifications without affecting the global state:
# Set a baseline density
settings.defaultparameters.initialdens = 1e4 # type: ignore[attr-defined]
print(f"Baseline density: {settings.defaultparameters.initialdens.get()}")
# Run model with temporary higher density
with settings.temporary_changes():
settings.defaultparameters.initialdens = 1e5 # type: ignore[attr-defined]
print(f"Inside context: {settings.defaultparameters.initialdens.get()}")
# Use param_dict for file paths
param_dict_high = {"outputFile": "output_6/high_density.dat"}
cloud_high = uclchem.model.Cloud(param_dict=param_dict_high)
print("High density model completed successfully")
# Settings automatically restored
print(f"After context: {settings.defaultparameters.initialdens.get()}")
Baseline density: 10000.0
Inside context: 100000.0
High density model completed successfully
After context: 10000.0
Comparing Results#
Let’s load and compare the two model runs:
result_baseline = uclchem.analysis.read_output_file("output_6/baseline.dat")
result_high_dens = uclchem.analysis.read_output_file("output_6/high_density.dat")
print(f"Baseline final CO abundance: {result_baseline['CO'].iloc[-1]:.2e}")
print(f"High density final CO abundance: {result_high_dens['CO'].iloc[-1]:.2e}")
Baseline final CO abundance: 5.19e-07
High density final CO abundance: 5.19e-07
Resetting Settings#
You can reset individual settings or all settings to defaults:
# Reset a single setting
print(f"Before reset: {settings.defaultparameters.initialdens.get()}")
settings.defaultparameters.initialdens.reset()
print(f"After reset: {settings.defaultparameters.initialdens.get()}")
Before reset: 10000.0
After reset: 100.0
Searching for Settings#
You can search across all modules for settings matching a pattern:
# Search for settings related to "temp"
temp_settings = settings.search("temp")
print(f"Found {len(temp_settings)} settings related to 'temp':")
for name, setting in list(temp_settings.items())[:5]:
print(f" {name}: {setting.get()}")
Found 21 settings related to 'temp':
defaultparameters.heating_temp_abstol: 1.0
defaultparameters.heating_temp_reltol: 0.01
defaultparameters.initialtemp: 10.0
defaultparameters.lower_limit_dusttemp: 10.0
defaultparameters.lower_limit_gastemp: 10.0
Best Practices#
When to use GeneralSettings:
You want to run multiple models with the same base configuration
You need to modify settings that aren’t easily accessible via
param_dictYou want autocomplete support in your IDE
You’re building a GUI or interactive application
When to use param_dict:
One-off model runs
Grid computations where each run has different parameters
File paths (outputFile, abundSaveFile) - always use param_dict for these
You want parameters explicitly documented in the function call
Important Notes:
⚠️ Settings are global and persist across model runs
⚠️ Not thread-safe - don’t use with multiprocessing
⚠️ File I/O paths should always be set via
param_dict, not GeneralSettingsAlways reset or use context managers when running multiple models
Summary#
The GeneralSettings class provides a powerful alternative to parameter dictionaries for configuring UCLCHEM models. Key features:
Direct access to all Fortran module variables
Edit tracking and reset capabilities
Context managers for temporary changes
Search functionality across all settings
Better IDE autocomplete support
See the documentation for more details on the advanced module.