Skip to content
Merged
Show file tree
Hide file tree
Changes from 250 commits
Commits
Show all changes
279 commits
Select commit Hold shift + click to select a range
fc5a81a
adding heatmap plot for sensitivity analysis #632 - precommit fix
crangelsmith Jul 21, 2025
b7e5624
adding heatmap plot for sensitivity analysis #632 - precommit fix
crangelsmith Jul 21, 2025
cbdb39a
formatting fix
radka-j Jul 21, 2025
545caee
updating workflow in notebook
crangelsmith Jul 23, 2025
4ee29be
Merge branch 'main' into naghavi
crangelsmith Jul 23, 2025
a2dcf0e
adding wave workflow in HM
crangelsmith Jul 23, 2025
59ee7d3
adding wave workflow in HM
crangelsmith Jul 23, 2025
562dc9d
Update notebook
crangelsmith Jul 23, 2025
046fafe
fix CI?
crangelsmith Jul 23, 2025
cd9cd9c
move and modify tests for saving models to experimental directory
edwardchalstrey1 Jul 15, 2025
a2f1ecb
update test to use experimental logger
edwardchalstrey1 Jul 15, 2025
fe9f439
restore original test_invalid_file_path
edwardchalstrey1 Jul 15, 2025
8a42fd5
add ModelSerialiser class for saving and loading models
edwardchalstrey1 Jul 15, 2025
6ae88d0
refactor ModelSerialiser to use Emulator model and update method sign…
edwardchalstrey1 Jul 15, 2025
4149ddc
update AutoEmulate docstring to copy v0
edwardchalstrey1 Jul 15, 2025
508f90c
add save method to AutoEmulate
edwardchalstrey1 Jul 15, 2025
6be83b8
initialize ModelSerialiser in AutoEmulate and add load method for mod…
edwardchalstrey1 Jul 15, 2025
cdb568a
add print to save method
edwardchalstrey1 Jul 15, 2025
e1abc10
refactor save method in AutoEmulate to accept model object, result or…
edwardchalstrey1 Jul 15, 2025
4ae14ea
preserve untransformed model name and remove unnecessary logging
edwardchalstrey1 Jul 15, 2025
85d7cd4
refactor _save_model method in ModelSerialiser to accept model_name p…
edwardchalstrey1 Jul 15, 2025
e851f94
add model_name arg and return full path after saving model and update…
edwardchalstrey1 Jul 15, 2025
6d8e35e
refactor save method in AutoEmulate to create unique filenames and up…
edwardchalstrey1 Jul 15, 2025
42903c9
refactor save method in AutoEmulate to include use_timestamp paramete…
edwardchalstrey1 Jul 15, 2025
f0277c8
refactor plot method in AutoEmulate to accept model_obj parameter for…
edwardchalstrey1 Jul 15, 2025
6e143d0
add updated quickstart notebook
edwardchalstrey1 Jul 15, 2025
7525fbb
simplify list_emulators func
edwardchalstrey1 Jul 15, 2025
009022a
add metadata_df method to Result class and corresponding tests
edwardchalstrey1 Jul 16, 2025
e706f5f
implement _save_result method in ModelSerialiser to save both model a…
edwardchalstrey1 Jul 16, 2025
2600c83
refactor _save_result method in ModelSerialiser to return only model …
edwardchalstrey1 Jul 16, 2025
743ab2b
implement load_result method in ModelSerialiser to load model and met…
edwardchalstrey1 Jul 16, 2025
3a13642
refactor test_save_result to combine saving and loading functionality
edwardchalstrey1 Jul 16, 2025
362008d
add test_load_result_no_metadata to verify loading model without meta…
edwardchalstrey1 Jul 16, 2025
7dd00a2
update notebook
edwardchalstrey1 Jul 16, 2025
26cc3d8
fix typehint
edwardchalstrey1 Jul 16, 2025
8bd6ce9
update notebook
edwardchalstrey1 Jul 17, 2025
e867de9
refactor _load_result to improve config parsing error handling
edwardchalstrey1 Jul 17, 2025
6c9510e
enhance config serialization in Result class and update related tests
edwardchalstrey1 Jul 17, 2025
ccd2ff5
fix test for result metadata to match config serialization format
edwardchalstrey1 Jul 17, 2025
f362097
commit notebook after config loading works
edwardchalstrey1 Jul 17, 2025
feb2614
Update autoemulate/experimental/save.py
edwardchalstrey1 Jul 23, 2025
2cb3eef
Update autoemulate/experimental/save.py
edwardchalstrey1 Jul 23, 2025
57ea87e
move details on model selection and logging into collapsible sections…
edwardchalstrey1 Jul 23, 2025
6143481
remove unused import
edwardchalstrey1 Jul 23, 2025
9436500
ensure that _save_result saves the model with joblib extension
edwardchalstrey1 Jul 23, 2025
865e28f
clarify return value description in _save_result docstring
edwardchalstrey1 Jul 23, 2025
77ac15a
finish prev commit
edwardchalstrey1 Jul 23, 2025
cc27a1e
attempted fix for not saving model
edwardchalstrey1 Jul 23, 2025
d5bc4e4
resave notebook
edwardchalstrey1 Jul 23, 2025
a31e8aa
Add dict conversion for transforms
sgreenbury Jul 22, 2025
6fcebfc
Revise serde and add tests
sgreenbury Jul 22, 2025
7ea1c1c
Update AutoEmulate to support str and dict for emulators and transforms
sgreenbury Jul 22, 2025
eeb1b0a
Revise short name, add test for compare
sgreenbury Jul 22, 2025
ae5302a
Fix test
sgreenbury Jul 23, 2025
2884158
add MCMC tutorial
radka-j Jul 21, 2025
c01ad71
update calibration example to use epidemic, update text
radka-j Jul 22, 2025
75c008b
Small formatting revisions and add descriptions for arviz
sgreenbury Jul 23, 2025
9316ba0
Remove dup lower()
sgreenbury Jul 23, 2025
1e2b2b9
fix path not being passed correctly to ae.save in test
edwardchalstrey1 Jul 24, 2025
565cdda
Add all for emulators
sgreenbury Jul 12, 2025
5fc54d4
Update MLP and GP
sgreenbury Jul 12, 2025
2dc8db6
Update GP config, remove assignment
sgreenbury Jul 13, 2025
8dc0826
Update params for GP
sgreenbury Jul 14, 2025
29289da
Add simulator name to base class
sgreenbury Jul 14, 2025
47d54df
Add constants to simulations init
sgreenbury Jul 14, 2025
1901898
Remove method since added to base class
sgreenbury Jul 14, 2025
9285aea
Fix missing model config to pass to cv
sgreenbury Jul 15, 2025
d14867e
Add exception handling in tuner
sgreenbury Jul 22, 2025
30278d5
Rename as simulator registry
sgreenbury Jul 22, 2025
79a794c
Fix arg for cross_validate
sgreenbury Jul 22, 2025
7b16d82
Remove fixed seed for EnsembleMLP
sgreenbury Jul 22, 2025
9bbdc11
Revise MLP learning rate
sgreenbury Jul 22, 2025
2cd6df9
Fix max score calculation
sgreenbury Jul 22, 2025
e549ef2
Revise tuner logging debug msg
sgreenbury Jul 22, 2025
77d1a0b
Revise to use argmax
sgreenbury Jul 22, 2025
bb4f5f9
Add max_retries
sgreenbury Jul 23, 2025
9d6da7c
Add retry logic and exception handling for a given model
sgreenbury Jul 23, 2025
fc57baa
Update MLP tune config
sgreenbury Jul 23, 2025
11880bf
Raise error
sgreenbury Jul 23, 2025
f3695b3
Refactor tuner, add comments, fix type hints
sgreenbury Jul 24, 2025
9b371eb
Remove obsolete method from subclass
sgreenbury Jul 24, 2025
135a27b
Fix docstring
sgreenbury Jul 24, 2025
804f809
Add FlowProblem to experimental simulations
edwardchalstrey1 Jul 22, 2025
a0c29e5
Refactor FlowProblem to return pressure values from the last time step
edwardchalstrey1 Jul 22, 2025
64e5418
try SA with different simulators
edwardchalstrey1 Jul 23, 2025
c8128b1
move emulation sensitivity analysis tutorial notebook
edwardchalstrey1 Jul 24, 2025
943fafa
fp needs right number of output names
edwardchalstrey1 Jul 24, 2025
df0b666
fix: update Callable import and type hint in generate_pulse_function
edwardchalstrey1 Jul 24, 2025
84aeedd
refactor: simplify generate_pulse_function by using a nested function
edwardchalstrey1 Jul 24, 2025
8d61847
refactor: replace lambda with a named function for dfdt_fd_spec for c…
edwardchalstrey1 Jul 24, 2025
e070d22
fix: remove type ignore comments
edwardchalstrey1 Jul 24, 2025
950cc52
refactor: add ncycles and ncomp to initialization of FlowProblem
edwardchalstrey1 Jul 24, 2025
3bd23a9
sa runs for flow problem
edwardchalstrey1 Jul 24, 2025
d154429
show sobol df and plot
edwardchalstrey1 Jul 24, 2025
2c43d84
add morris
edwardchalstrey1 Jul 24, 2025
12dd411
add narrative
edwardchalstrey1 Jul 24, 2025
7f12de9
refactor: replace variable name for tensor conversion in FlowProblem
edwardchalstrey1 Jul 24, 2025
b2fb35c
use peak pressure
edwardchalstrey1 Jul 24, 2025
e498efc
save notebook outputs
edwardchalstrey1 Jul 24, 2025
b03aba5
clear outputs
edwardchalstrey1 Jul 24, 2025
bdf5ece
tidy docstring
edwardchalstrey1 Jul 24, 2025
494c299
refactor: update parameter naming for consistency in FlowProblem and …
edwardchalstrey1 Jul 24, 2025
b14397f
docstring and type annotations
edwardchalstrey1 Jul 24, 2025
facc91e
update docstring
edwardchalstrey1 Jul 24, 2025
88b1496
add option for simulator._forward to return None, handle when simulat…
radka-j Jul 22, 2025
24db686
update handling of failed simulations in HM
radka-j Jul 22, 2025
9727ec5
catch failed simulations in learners
radka-j Jul 22, 2025
31c38b3
update base simulator class to handle failed sims
radka-j Jul 22, 2025
f2186c9
fix handling of failed sims in base Simulator
radka-j Jul 22, 2025
eb6c15e
add test for failed sims
radka-j Jul 22, 2025
df5e9c3
precommit fixes in MCMC tests
radka-j Jul 22, 2025
5cf13e9
pre-commit fixes after simulator update
radka-j Jul 22, 2025
31224aa
add mention of how to handle failed sims in tutorial nb
radka-j Jul 22, 2025
851f163
Simulator.forward_batch can return params for which simulation succeeded
radka-j Jul 23, 2025
fe476b5
Add method for forward batch where simulator can fail
sgreenbury Jul 25, 2025
df09035
updating notebook
crangelsmith Jul 28, 2025
88656aa
Merge remote-tracking branch 'origin/main'
crangelsmith Jul 28, 2025
9aca220
Merge remote-tracking branch 'origin/main' into naghavi
crangelsmith Jul 28, 2025
67eaa12
updating notebook
crangelsmith Jul 28, 2025
105e920
Merge remote-tracking branch 'origin/main' into naghavi
crangelsmith Jul 29, 2025
17e8459
adding paralelism in simulation
crangelsmith Jul 30, 2025
a6fdce4
adding paralelism in simulation
crangelsmith Jul 30, 2025
43f42da
updating text in notebook
crangelsmith Jul 30, 2025
9c37fb7
clear outputs from nb
radka-j Jul 31, 2025
069ffa6
merge main
radka-j Jul 31, 2025
d23b072
update imports in nb after v1 update
radka-j Jul 31, 2025
9fbc423
set model_tuning=False
radka-j Jul 31, 2025
9075d07
update imports in cardiac simulator after v1 release
radka-j Jul 31, 2025
089cadc
further fixes in move to v1
radka-j Jul 31, 2025
6db52a7
fix pre-commit
radka-j Jul 31, 2025
d71da2a
updating notebook
crangelsmith Jul 31, 2025
476ab5c
updating notebook and adding debbuging log for history matching
crangelsmith Aug 1, 2025
48dce8e
Merge branch 'main' into naghavi
crangelsmith Aug 6, 2025
2db371e
rm experimental tests left over after main merge
radka-j Aug 6, 2025
845dc04
update param bound setting in HMW
radka-j Aug 6, 2025
04db678
fix simulator bound setting
radka-j Aug 6, 2025
03b1cb1
updating notebook and workflow fix and Matten GP
crangelsmith Aug 8, 2025
4e2444a
updating notebook with pairplot figures
crangelsmith Aug 11, 2025
db75983
add cloud point sampling to HM, rm reliance on LHS resampling
radka-j Aug 12, 2025
232b596
updating notebook with pairplot figures
crangelsmith Aug 12, 2025
ddcf6b9
updating notebook with pairplot figures
crangelsmith Aug 12, 2025
4ef5931
handle case where have more NROY samples than number that want to gen…
radka-j Aug 12, 2025
6f07342
update HMW tests
radka-j Aug 12, 2025
bc0ce47
fix test
radka-j Aug 12, 2025
0718b1e
update docstring
radka-j Aug 12, 2025
1430ce2
add scaling factor to cloud sampling
radka-j Aug 13, 2025
52c6b87
update docstring
radka-j Aug 13, 2025
fac1c68
Merge branch 'main' into naghavi
radka-j Aug 15, 2025
a9fe520
Merge branch 'naghavi' into update_hm_sampling
radka-j Aug 15, 2025
e9cdfc4
add link to case studies in docs
radka-j Aug 15, 2025
cf7e096
add option to save SA heatmap plot
radka-j Aug 15, 2025
a21e3e0
rename fig vars for consistency
radka-j Aug 15, 2025
3c5be32
Merge branch 'naghavi' into update_hm_sampling
radka-j Aug 15, 2025
3e26a5f
update docstrings
radka-j Aug 15, 2025
e3dbf9e
update how specify GP kernel, add param names to HMW plot
radka-j Aug 15, 2025
7b33d69
Merge branch 'naghavi' into update_hm_sampling
radka-j Aug 15, 2025
ec90ea4
Merge branch 'main' into naghavi
radka-j Aug 15, 2025
7d30a3d
Merge branch 'main' into naghavi
radka-j Aug 15, 2025
b50d1f9
re-initialise emulator before refitting in HMW
radka-j Aug 15, 2025
57a4477
pass result to HMW object in ModularCirc nb
radka-j Aug 15, 2025
29e01cf
Merge branch 'naghavi' into update_hm_sampling
radka-j Aug 15, 2025
3be38d9
ensure cloud sampling stays within NROY bounds
radka-j Aug 18, 2025
603a953
refactor cloud sampling
radka-j Aug 18, 2025
d4894e0
simplify test
radka-j Aug 18, 2025
1e4c50d
Merge pull request #752 from alan-turing-institute/hm_improve_em_fitting
crangelsmith Aug 19, 2025
72ff5e1
Merge branch 'naghavi' into update_hm_sampling
radka-j Aug 19, 2025
ee808ba
fix bug after branch merge
radka-j Aug 19, 2025
e0ba762
Merge pull request #725 from alan-turing-institute/update_hm_sampling
crangelsmith Aug 19, 2025
520bfa1
updating notebook
crangelsmith Aug 19, 2025
1a67071
fix nb
radka-j Aug 19, 2025
5d677ef
update cloud sampling
radka-j Aug 19, 2025
9188a98
merge main
radka-j Aug 19, 2025
b805f7b
update docstrings
radka-j Aug 19, 2025
ef94034
refactor cloud sampling
radka-j Aug 19, 2025
e4ad5b6
rename method
radka-j Aug 19, 2025
3aa7a1d
handle edge case in cloud sampling
radka-j Aug 19, 2025
f6e0f05
fix bug after refactor
radka-j Aug 19, 2025
01b6b78
re-add heatmap plot lost in merge
radka-j Aug 19, 2025
49d1ddc
fix logging messages
radka-j Aug 19, 2025
f493a27
save wave results in hmw object
radka-j Aug 19, 2025
31d6337
refit emulator in run_waves instead of run
radka-j Aug 20, 2025
4122eb3
update history matching tutorial
radka-j Aug 20, 2025
d5272dc
fix bug after refactor
radka-j Aug 20, 2025
cf9438f
pre-commit fix
radka-j Aug 20, 2025
440e611
allow user to choose whether to refit the emulator
radka-j Aug 20, 2025
47be7ba
simplify HMW results plotting in nb
radka-j Aug 20, 2025
26da755
fix param bounds extraction
radka-j Aug 20, 2025
3929967
set axes ranges in hmw pairplot
radka-j Aug 20, 2025
a3dcb61
add observation as reference value to posterior plot
radka-j Aug 20, 2025
fa46ce1
refit emulator only on the latest simulated data
radka-j Aug 20, 2025
5941932
let user decide whether to refit on all data or not
radka-j Aug 21, 2025
23e4e8d
update docs
radka-j Aug 21, 2025
b18fa48
update docstrings, add logging messages
radka-j Aug 21, 2025
471b1af
update log message
radka-j Aug 21, 2025
2d631d1
format log messages
radka-j Aug 21, 2025
c410cdd
make string expr compatible with python < 3.12
radka-j Aug 22, 2025
1c136e2
updating notebook with figures
crangelsmith Aug 22, 2025
98c0633
updating notebook with figures and seed
crangelsmith Aug 22, 2025
7cb9a6e
updating notebook with boox plots
crangelsmith Aug 26, 2025
de50996
HM with only relevant features
crangelsmith Aug 27, 2025
a5a7329
pre-commit
radka-j Aug 27, 2025
72a7ba4
update docstring
radka-j Aug 27, 2025
9713cff
update docstring
radka-j Aug 27, 2025
a408af4
only using relevant parameters in the MCMC calibration
crangelsmith Aug 27, 2025
c643793
updating notebook figures and experiment tracking outputs
crangelsmith Aug 27, 2025
b0459e3
Merge remote-tracking branch 'origin/naghavi' into naghavi
crangelsmith Aug 27, 2025
047202c
fixing broken variable
crangelsmith Aug 27, 2025
10044c7
Merge branch 'main' into naghavi
radka-j Aug 28, 2025
2500680
update docstrings
radka-j Aug 28, 2025
bbb6b82
build docs given autoemuate install from branch not main
radka-j Aug 28, 2025
6aa278d
Merge branch 'main' into naghavi
radka-j Aug 28, 2025
801327a
adding workflow script
crangelsmith Aug 28, 2025
c961a29
Merge remote-tracking branch 'origin/naghavi' into naghavi
crangelsmith Aug 28, 2025
258cc42
Merge branch 'main' into naghavi
radka-j Sep 1, 2025
089d021
rename forward_batch_skip_failures to forward_batch in cardiac simulator
radka-j Sep 1, 2025
3d3f405
pre-commit fix
radka-j Sep 1, 2025
cafb506
use predictive uncertainty in bayesian calibration
radka-j Sep 1, 2025
ed20e0f
revert change to BC, only calibrate top 3 SA params
radka-j Sep 1, 2025
3df05c6
add plot_wave to HMW and use in nb, add text to nb
radka-j Sep 2, 2025
b4cbc57
replace parameter_idx with calibration_params (derive idx internally)
radka-j Sep 2, 2025
1fb2ba1
Merge branch 'main' into naghavi
radka-j Sep 2, 2025
1709378
update nb after main merge
radka-j Sep 2, 2025
be31321
updates to API calls after main merge
radka-j Sep 3, 2025
6ea3a75
fix log message
radka-j Sep 3, 2025
43c58ac
add comments
radka-j Sep 3, 2025
c987f1a
add plot_wave to history matching tutorial, update example
radka-j Sep 3, 2025
8d3e996
change run default to retrain emulator
radka-j Sep 3, 2025
d59642e
add get_wave_results method
radka-j Sep 3, 2025
0151e24
update history matching tutorial
radka-j Sep 3, 2025
be61017
update history matching tutorial
radka-j Sep 3, 2025
4647a6e
update history matching workflow tutorial
radka-j Sep 3, 2025
b7db40c
reduce sim param ranges in tutorial
radka-j Sep 3, 2025
a5b6084
add box plot to HMW
radka-j Sep 3, 2025
f80aa49
add option to keep simulator axis limits on NROY plot
radka-j Sep 3, 2025
7c5e07f
add comments
radka-j Sep 3, 2025
95c4fc0
add text
radka-j Sep 3, 2025
c946666
don't print param ranges pre/post HM, reduction in ranges now shown i…
radka-j Sep 3, 2025
4059b83
clean up print statements
radka-j Sep 3, 2025
530d636
mv param extraction cell to bayes calibration section
radka-j Sep 3, 2025
5377912
updating names and README
crangelsmith Sep 3, 2025
5dd17e9
exclude case_studies from nbstripout
radka-j Sep 3, 2025
2eb481e
fix typos
radka-j Sep 3, 2025
6d0fb7b
fix paths in README
radka-j Sep 3, 2025
253705b
add nb with outputs
radka-j Sep 3, 2025
499bf31
reverting workflow
crangelsmith Sep 3, 2025
74fd510
Merge remote-tracking branch 'origin/naghavi' into naghavi
crangelsmith Sep 3, 2025
0171b78
deleting script workflow from case study
crangelsmith Sep 3, 2025
a20638b
update README
radka-j Sep 3, 2025
2efbbcb
update README
radka-j Sep 3, 2025
40e1406
clarify text in nb
radka-j Sep 3, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ repos:
rev: 0.8.1
hooks:
- id: nbstripout
exclude: ^case_studies/
692 changes: 620 additions & 72 deletions autoemulate/calibration/history_matching.py

Large diffs are not rendered by default.

143 changes: 138 additions & 5 deletions autoemulate/core/sensitivity_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def plot_morris(
@staticmethod
def top_n_sobol_params(
sa_results_df: pd.DataFrame, top_n: int, sa_index: str = "ST"
) -> list:
) -> list[str]:
"""
Return `top_n` most important parameters given Sobol sensitivity analysis.

Expand Down Expand Up @@ -338,14 +338,63 @@ def top_n_sobol_params(

st_results = sa_results_df[sa_results_df["index"] == sa_index]

return (
st_results.groupby("parameter")["value"] # pyright: ignore[reportCallIssue]
# each parameter is evalued against each output
# to rank parameters, average over how sensitive all outputs are to it
# each parameter is evalued against each output
# to rank parameters, average over how sensitive all outputs are to it
top_n = (
st_results.groupby("parameter")["value"] # pyright: ignore[reportCallIssue, reportAssignmentType]
.mean()
.nlargest(top_n)
.index.tolist()
)
assert isinstance(top_n, list)
return top_n

def plot_sa_heatmap(
self,
results: pd.DataFrame,
index: str = "ST",
top_n: int | None = None,
cmap: str = "coolwarm",
normalize: bool = True,
figsize: tuple | None = None,
fname: str | None = None,
):
"""
Plot a normalized Sobol sensitivity analysis heatmap.

Parameters
----------
results: pd.DataFrame
Sensitivity index dataframe with columns ['index', 'parameter',
'output', 'value'].
index: str
The type of sensitivity index to plot (e.g., 'ST').
top_n: int | None
Number of top parameters to include. If None, returns all. Defaults to
None.
cmap: str
Matplotlib colormap. Defaults to 'coolwarm'.
normalize: bool
Wheterto normalize values to [0, 1]. Defaults to True.
figsize: tuple | None
Figure size as (width, height) in inches. Defaults to None.
fname: str | None
If provided, saves the figure to this file path. Defaults to None.
"""
# Determine which parameters to include
parameter_list = self.top_n_sobol_params(
results,
top_n=len(results["parameter"].unique()) if top_n is None else top_n,
)

fig = _plot_sa_heatmap(
results, index, parameter_list, cmap, normalize, fig_size=figsize
)

if fname is None:
return display_figure(fig)
fig.savefig(fname, bbox_inches="tight")
return None


def _sobol_results_to_df(results: dict[str, ResultDict]) -> pd.DataFrame:
Expand Down Expand Up @@ -770,3 +819,87 @@ def _create_morris_plot(
ax.set_ylabel("μ* (Modified Mean)")
ax.set_title(f"Output: {output_name}")
ax.grid(True, alpha=0.3)


def _plot_sa_heatmap(
si_df, index, parameters, cmap="coolwarm", normalize=True, fig_size=None
) -> matplotlib.figure.Figure:
"""
Plot a sensitivity analysis heatmap for a given index.

Parameters
----------
results: pd.DataFrame
Sensitivity index dataframe with columns ['index', 'parameter',
'output', 'value'].
index: str
The type of sensitivity index to plot (e.g., 'ST').
top_n: int | None
Number of top parameters to include. If None, returns all. Defaults to
None.
cmap: str
Matplotlib colormap. Defaults to 'coolwarm'.
normalize: bool
Wheterto normalize values to [0, 1]. Defaults to True.
figsize: tuple | None
Figure size as (width, height) in inches. Defaults to None.

Returns
-------
matplotlib.figure.Figure
The matplotlib figure containing the SA heatmap.
"""
# Filter the dataframe for the specified index
df = si_df[si_df["index"] == index]

# Pivot the dataframe to get a matrix: rows = outputs, cols = parameters
heatmap_df = (
df[df["parameter"].isin(parameters)]
.pivot_table(
index="output", columns="parameter", values="value", fill_value=np.nan
)
.reindex(columns=parameters) # Ensure column order
)

# Normalize if requested
if normalize:
min_value = heatmap_df.min().min()
max_value = heatmap_df.max().max()
value_range = max_value - min_value if max_value != min_value else 1
heatmap_df = (heatmap_df - min_value) / value_range

# Convert to NumPy array
data_np = heatmap_df.to_numpy()

# layout - add space for legend
nrows, ncols = _calculate_layout(data_np.shape[1], data_np.shape[0])
fig_size = fig_size or (4.5 * ncols, 4.5 * nrows + 2) # Extra width for legend

# Plotting
fig, ax = plt.subplots(figsize=fig_size)
cax = ax.imshow(data_np, cmap=cmap, aspect="auto")

# Colorbar
cbar = fig.colorbar(cax, ax=ax)
cbar_label = "Normalized Sensitivity" if normalize else "Sensitivity"
cbar.set_label(cbar_label, rotation=270, labelpad=15)

# Labels and ticks
ax.set_title(f"{index} Sensitivity Analysis Heatmap", fontsize=14, pad=12)
ax.set_xlabel("Parameters", fontsize=12)
ax.set_ylabel("Outputs", fontsize=12)

ax.set_xticks(np.arange(len(parameters)))
ax.set_xticklabels(parameters, rotation=45, ha="right")
ax.set_yticks(np.arange(len(heatmap_df.index)))
ax.set_yticklabels(heatmap_df.index)

# Gridlines
ax.set_xticks(np.arange(-0.5, len(parameters), 1), minor=True)
ax.set_yticks(np.arange(-0.5, len(heatmap_df.index), 1), minor=True)
ax.grid(which="minor", color="w", linestyle="-", linewidth=2)
ax.tick_params(which="minor", bottom=False, left=False)

plt.tight_layout()

return fig
Loading
Loading