Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Micro Manager changelog

## Unreleased

- Combined adaptive strategies and model switching so inactive micro-problems are solved using reduced-order models (ROMs) instead of being omitted, with multi-level model selection based on relative similarity distance. [#318](https://github.com/precice/micro-manager/issues/318)

## v0.12.0

- Changed the configuration to conform it to the [preCICE adapter configuration schema](https://github.com/precice/adapter-schema). [#324](https://github.com/precice/micro-manager/pull/324) **Breaking change**
Expand Down
3 changes: 2 additions & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,8 @@ To turn on model switching, set `"model_switching": true` in `simulation_params`

| Parameter | Description |
| --- | --- |
| `switching_function` | Path to the file containing the Python importable switching function. If the file is not in the working directory, give the relative path from the directory where the Micro Manager is executed. |
| `switching_function` | Path to the file containing the Python importable switching function. If the file is not in the working directory, give the relative path from the directory where the Micro Manager is executed. Optional when `adaptivity` is enabled. |
| `levels_thresholds` | (Optional) List of float thresholds for partitioning relative similarity distances across reduced model levels when combined with adaptivity and more than two models. |

Example of model switching configuration is

Expand Down
12 changes: 12 additions & 0 deletions docs/model-switching.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ as long as the `switching_function` contains values other than 0.
Model evaluation - in the call `solve_variant(micro_sims_input, dt)` - is delegated to the regular
(non-model-adaptive) `micro_sim_solve(micro_sims_input, dt)` method.

### Combining Model Switching with Adaptivity

When both `model_switching` and `adaptivity` are enabled, adaptive classification is combined with reduced-order modeling:

- **Active problems** are solved using the high-fidelity Full-Order Model (FOM, Resolution 0).
- **Inactive problems** are not omitted; instead, they are solved using Reduced-Order Models (ROMs, Resolution >= 1).
- When more than two models are loaded ($M > 2$), the ROM level for each inactive problem is determined automatically by its relative similarity distance $d / \epsilon_r \in [0, 1]$ to its active representative:
- Inactive problems close to the activation threshold ($\text{rel\_dist} \approx 1$) receive the finest ROM (Resolution 1).
- Inactive problems very similar to their representative ($\text{rel\_dist} \approx 0$) receive coarser ROMs (up to Resolution $M - 1$).
- Optional custom level boundaries can be defined via `model_switching_levels_thresholds`.
- When adaptivity is enabled, specifying a `switching_function` is optional.

### Interfaces

```python
Expand Down
12 changes: 12 additions & 0 deletions micro_manager/adaptivity/adaptivity_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,18 @@ def get_associated_map(self) -> Dict[int, int]:
"""
...

def get_inactive_relative_distances(self) -> Dict[int, float]:
"""
Get the relative distance of each local inactive simulation to its
associated active simulation, normalized by the refinement tolerance into [0, 1].

Returns
-------
rel_dists : Dict[int, float]
Mapping from local id (lid) to relative distance in [0, 1].
"""
return {}

def check_micro_simulation_initialize(
self, logger: Logger, micro_init_return_value: Optional[Dict[str, Any]]
) -> None:
Expand Down
70 changes: 50 additions & 20 deletions micro_manager/adaptivity/global_adaptivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ def __init__(
mpi,
)

self._is_model_switching_on: bool = config.enable_model_switching()

buffer_size = self._sim_container.global_num_sims**2
array_buffer, mpi_node = self._mpi.create_node_buffer(MPI.FLOAT, buffer_size)
self._mpi_node = mpi_node
Expand Down Expand Up @@ -198,6 +200,33 @@ def get_inactive_gids(self) -> List[int]:

return inactive_gids

def get_inactive_relative_distances(self) -> Dict[int, float]:
"""
Get the relative distance of each local inactive simulation
to its associated active simulation, normalized by the refinement tolerance into [0, 1].

Returns
-------
rel_dists : Dict[int, float]
Mapping from local id (lid) to relative distance in [0, 1].
"""
rel_dists: Dict[int, float] = {}
inactive_lids = self.get_inactive_lids()
if self._ref_tol <= 0.0 or len(self._similarity_dists) == 0:
for lid in inactive_lids:
rel_dists[lid] = 0.0
return rel_dists

for lid in inactive_lids:
gid = self._sim_container.local_gids[lid]
assoc_gid = self._sim_is_associated_to.get(gid)
if assoc_gid is not None and self._ref_tol > 0:
d = float(self._similarity_dists[gid, assoc_gid])
rel_dists[lid] = min(max(d / self._ref_tol, 0.0), 1.0)
else:
rel_dists[lid] = 0.0
return rel_dists

def get_full_field_micro_output(
self,
micro_input: List[Dict[str, Any]],
Expand All @@ -223,7 +252,7 @@ def get_full_field_micro_output(
):
micro_sims_output = deepcopy(micro_output)
num_active = np.sum(self._is_sim_active)
if num_active == self._is_sim_active.shape[0]:
if num_active == self._is_sim_active.shape[0] or self._is_model_switching_on:
return micro_sims_output

self._communicate_micro_output(micro_sims_output)
Expand Down Expand Up @@ -473,26 +502,27 @@ def _update_inactive_sims(self) -> None:
recv_data = self._mpi.exchange(send_map)

# Use received micro sims to activate the required simulations
for state, gid in recv_data:
local_ids = to_be_activated_map[gid]
for lid in local_ids:
# Create the micro simulation object and set its state
self._sim_container[lid] = self._model_manager.get_instance(
self._sim_container.local_gids[lid], self._micro_problem_cls
)
self._sim_container.set_sim_state(lid, state)
if not self._is_model_switching_on:
for state, gid in recv_data:
local_ids = to_be_activated_map[gid]
for lid in local_ids:
# Create the micro simulation object and set its state
self._sim_container[lid] = self._model_manager.get_instance(
self._sim_container.local_gids[lid], self._micro_problem_cls
)
self._sim_container.set_sim_state(lid, state)

# Delete the micro simulation object if it is inactive
for lid, gid in enumerate(self._sim_container.local_gids):
if not self._is_sim_active[gid]:
if self._sim_container[lid] is None:
continue
# Release resources now, especially for remote simulation instance.
# If left to garbage collector this might lead to a race condition.
# Releasing with call to sim.destroy(), afterwards reference in sim
# sim list can be removed.
self._sim_container[lid].destroy()
self._sim_container[lid] = None
# Delete the micro simulation object if it is inactive
for lid, gid in enumerate(self._sim_container.local_gids):
if not self._is_sim_active[gid]:
if self._sim_container[lid] is None:
continue
# Release resources now, especially for remote simulation instance.
# If left to garbage collector this might lead to a race condition.
# Releasing with call to sim.destroy(), afterwards reference in sim
# sim list can be removed.
self._sim_container[lid].destroy()
self._sim_container[lid] = None

self._profiler.end()

Expand Down
71 changes: 53 additions & 18 deletions micro_manager/adaptivity/local_adaptivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ def __init__(
mpi,
)

self._is_model_switching_on: bool = config.enable_model_switching()

# similarity_dists: 2D array having similarity distances between each micro simulation pair
# This matrix is modified in place via the function update_similarity_dists
self._similarity_dists = np.zeros(
Expand Down Expand Up @@ -164,6 +166,32 @@ def get_inactive_gids(self) -> List[int]:

return inactive_gids

def get_inactive_relative_distances(self) -> Dict[int, float]:
"""
Get the relative distance of each local inactive simulation
to its associated active simulation, normalized by the refinement tolerance into [0, 1].

Returns
-------
rel_dists : Dict[int, float]
Mapping from local id (lid) to relative distance in [0, 1].
"""
rel_dists: Dict[int, float] = {}
inactive_lids = self.get_inactive_lids()
if self._ref_tol <= 0.0 or len(self._similarity_dists) == 0:
for lid in inactive_lids:
rel_dists[lid] = 0.0
return rel_dists

for lid in inactive_lids:
assoc_lid = self._sim_is_associated_to.get(lid)
if assoc_lid is not None and self._ref_tol > 0:
d = float(self._similarity_dists[lid, assoc_lid])
rel_dists[lid] = min(max(d / self._ref_tol, 0.0), 1.0)
else:
rel_dists[lid] = 0.0
return rel_dists

def get_full_field_micro_output(
self,
micro_input: List[Dict[str, Any]],
Expand Down Expand Up @@ -191,9 +219,13 @@ def get_full_field_micro_output(
return micro_sims_output

for inactive_lid in inactive_lids:
micro_sims_output[inactive_lid] = deepcopy(
micro_sims_output[self._sim_is_associated_to[inactive_lid]]
)
if micro_sims_output[inactive_lid] is None:
micro_sims_output[inactive_lid] = deepcopy(
micro_sims_output[self._sim_is_associated_to[inactive_lid]]
)

if self._is_model_switching_on:
return micro_sims_output

# Skip interpolation if there are not enough active simulations to build a
# well-posed interpolant (mirrors the check in GlobalAdaptivityCalculator).
Expand Down Expand Up @@ -323,21 +355,24 @@ def _update_inactive_sims(self) -> None:

# Update the set of inactive micro sims
for lid in to_be_activated_lids:
associated_active_id = self._sim_is_associated_to[lid]
self._sim_container[lid] = self._model_manager.get_instance(
lid, self._micro_problem_cls
)
state = self._sim_container.get_sim_state(associated_active_id)
self._sim_container.set_sim_state(lid, state)
if not self._is_model_switching_on:
associated_active_id = self._sim_is_associated_to[lid]
self._sim_container[lid] = self._model_manager.get_instance(
lid, self._micro_problem_cls
)
state = self._sim_container.get_sim_state(associated_active_id)
self._sim_container.set_sim_state(lid, state)
# Active sim cannot have an associated sim
del self._sim_is_associated_to[lid]
if lid in self._sim_is_associated_to:
del self._sim_is_associated_to[lid]

# Delete the inactive micro simulations which have not been activated
for lid in range(self._is_sim_active.size):
if not self._is_sim_active[lid] and self._sim_container[lid] is not None:
# Release resources now, especially for remote simulation instance.
# If left to garbage collector this might lead to a race condition.
# Releasing with call to sim.destroy(), afterwards reference in sim
# sim list can be removed.
self._sim_container[lid].destroy()
self._sim_container[lid] = None
if not self._is_model_switching_on:
for lid in range(self._is_sim_active.size):
if not self._is_sim_active[lid] and self._sim_container[lid] is not None:
# Release resources now, especially for remote simulation instance.
# If left to garbage collector this might lead to a race condition.
# Releasing with call to sim.destroy(), afterwards reference in sim
# sim list can be removed.
self._sim_container[lid].destroy()
self._sim_container[lid] = None
52 changes: 42 additions & 10 deletions micro_manager/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,10 +939,11 @@ def read_json_micro_manager(self):
"model_switching_settings"
].exists()
):
self.enable_model_switching.set = False
self._logger.log_info_rank_zero(
"Model Switching is turned on but no model switching settings are provided."
)
if not self.enable_adaptivity():
self.enable_model_switching.set = False
self._logger.log_info_rank_zero(
"Model Switching is turned on but no model switching settings are provided."
)

if self.enable_model_switching():
if len(self.micro_file_names()) < 2:
Expand All @@ -954,9 +955,28 @@ def read_json_micro_manager(self):
else:
self.write_data_names().append("Model-Resolution")

self.model_switching_function.set = self.json["micro_manager"][
"simulation_params"
]["model_switching_settings"]["switching_function"].get_or_raise()
if self.json["micro_manager"]["simulation_params"][
"model_switching_settings"
].exists():
if self.enable_adaptivity():
self.model_switching_function.set = self.json["micro_manager"][
"simulation_params"
]["model_switching_settings"]["switching_function"].get_with_default(
None
)
else:
self.model_switching_function.set = self.json["micro_manager"][
"simulation_params"
]["model_switching_settings"]["switching_function"].get_or_raise()

self.model_switching_levels_thresholds.set = self.json["micro_manager"][
"simulation_params"
]["model_switching_settings"]["levels_thresholds"].get_with_default(
None
)
else:
self.model_switching_function.set = None
self.model_switching_levels_thresholds.set = None

# ======================================================
# Interpolation and Diagnostics
Expand Down Expand Up @@ -1608,14 +1628,26 @@ def enable_model_switching(self) -> bool:
pass

@config_entry
def model_switching_function(self) -> str:
def model_switching_function(self) -> Optional[str]:
"""
Get path to switching function file

Returns
-------
switching_function : str
String containing the path to the switching function file
switching_function : Optional[str]
String containing the path to the switching function file, or None.
"""
pass

@config_entry
def model_switching_levels_thresholds(self) -> Optional[List[float]]:
"""
Get custom thresholds for multi-level model switching.

Returns
-------
levels_thresholds : Optional[List[float]]
Thresholds for reduced model levels in (0, 1).
"""
pass

Expand Down
Loading