micro-manager-precice 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ import argparse
2
+ import os
3
+
4
+ from .config import Config
5
+ from .micro_manager import MicroManagerCoupling
6
+
7
+ try:
8
+ from .snapshot.snapshot import MicroManagerSnapshot
9
+
10
+ is_snapshot_possible = True
11
+ except ImportError:
12
+ is_snapshot_possible = False
13
+
14
+
15
+ def main():
16
+
17
+ parser = argparse.ArgumentParser(description=".")
18
+ parser.add_argument(
19
+ "config_file", type=str, help="Path to the JSON config file of the manager."
20
+ )
21
+ parser.add_argument(
22
+ "--snapshot", action="store_true", help="compute offline snapshot database"
23
+ )
24
+
25
+ args = parser.parse_args()
26
+ config_file_path = args.config_file
27
+ if not os.path.isabs(config_file_path):
28
+ config_file_path = os.getcwd() + "/" + config_file_path
29
+
30
+ if not args.snapshot:
31
+ manager = MicroManagerCoupling(config_file_path)
32
+ else:
33
+ if is_snapshot_possible:
34
+ manager = MicroManagerSnapshot(config_file_path)
35
+ else:
36
+ raise ImportError(
37
+ "The Micro Manager snapshot computation requires the h5py package."
38
+ )
39
+
40
+ manager.initialize()
41
+
42
+ manager.solve()
@@ -0,0 +1,3 @@
1
+ from micro_manager import main
2
+
3
+ main()
File without changes
@@ -0,0 +1,328 @@
1
+ """
2
+ Functionality for adaptive initialization and control of micro simulations
3
+ """
4
+ import sys
5
+ from math import exp
6
+ from typing import Callable
7
+ from warnings import warn
8
+
9
+ import numpy as np
10
+
11
+
12
+ class AdaptivityCalculator:
13
+ def __init__(self, configurator, logger) -> None:
14
+ """
15
+ Class constructor.
16
+
17
+ Parameters
18
+ ----------
19
+ configurator : object of class Config
20
+ Object which has getter functions to get parameters defined in the configuration file.
21
+ logger : Logger defined from the standard package logging
22
+ """
23
+ self._refine_const = configurator.get_adaptivity_refining_const()
24
+ self._coarse_const = configurator.get_adaptivity_coarsening_const()
25
+ self._hist_param = configurator.get_adaptivity_hist_param()
26
+ self._adaptivity_data_names = configurator.get_data_for_adaptivity()
27
+ self._adaptivity_type = configurator.get_adaptivity_type()
28
+
29
+ self._logger = logger
30
+
31
+ self._coarse_tol = 0.0
32
+ self._ref_tol = 0.0
33
+
34
+ self._similarity_measure = self._get_similarity_measure(
35
+ configurator.get_adaptivity_similarity_measure()
36
+ )
37
+
38
+ def _get_similarity_dists(
39
+ self, dt: float, similarity_dists: np.ndarray, data: dict
40
+ ) -> np.ndarray:
41
+ """
42
+ Calculate metric which determines if two micro simulations are similar enough to have one of them deactivated.
43
+
44
+ Parameters
45
+ ----------
46
+ dt : float
47
+ Current time step
48
+ similarity_dists : numpy array
49
+ 2D array having similarity distances between each micro simulation pair
50
+ data : dict
51
+ Data to be used in similarity distance calculation
52
+
53
+ Returns
54
+ -------
55
+ similarity_dists : numpy array
56
+ Updated 2D array having similarity distances between each micro simulation pair
57
+ """
58
+ _similarity_dists = np.copy(similarity_dists)
59
+
60
+ data_diff = np.zeros_like(_similarity_dists)
61
+ for name in data.keys():
62
+ data_vals = data[name]
63
+ if data_vals.ndim == 1:
64
+ # If the adaptivity data is a scalar for each simulation,
65
+ # expand the dimension to make it a 2D array to unify the calculation.
66
+ # The axis is later reduced with a norm.
67
+ data_vals = np.expand_dims(data_vals, axis=1)
68
+
69
+ data_diff += self._similarity_measure(data_vals)
70
+
71
+ return exp(-self._hist_param * dt) * _similarity_dists + dt * data_diff
72
+
73
+ def _update_active_sims(
74
+ self, similarity_dists: np.ndarray, is_sim_active: np.ndarray
75
+ ) -> np.ndarray:
76
+ """
77
+ Update set of active micro simulations. Active micro simulations are compared to each other
78
+ and if found similar, one of them is deactivated.
79
+
80
+ Parameters
81
+ ----------
82
+ similarity_dists : numpy array
83
+ 2D array having similarity distances between each micro simulation pair
84
+ is_sim_active : numpy array
85
+ 1D array having state (active or inactive) of each micro simulation
86
+
87
+ Returns
88
+ -------
89
+ _is_sim_active : numpy array
90
+ Updated 1D array having state (active or inactive) of each micro simulation
91
+ """
92
+ max_similarity_dist = np.amax(similarity_dists)
93
+
94
+ if max_similarity_dist == 0.0:
95
+ warn(
96
+ "All similarity distances are zero, probably because all the data for adaptivity is the same. Coarsening tolerance will be manually set to minimum float number."
97
+ )
98
+ self._coarse_tol = sys.float_info.min
99
+ else:
100
+ self._coarse_tol = (
101
+ self._coarse_const * self._refine_const * max_similarity_dist
102
+ )
103
+
104
+ _is_sim_active = np.copy(
105
+ is_sim_active
106
+ ) # Input is_sim_active is not longer used after this point
107
+
108
+ # Update the set of active micro sims
109
+ for i in range(_is_sim_active.size):
110
+ if _is_sim_active[i]: # if sim is active
111
+ if self._check_for_deactivation(i, similarity_dists, _is_sim_active):
112
+ _is_sim_active[i] = False
113
+
114
+ return _is_sim_active
115
+
116
+ def _associate_inactive_to_active(
117
+ self,
118
+ similarity_dists: np.ndarray,
119
+ is_sim_active: np.ndarray,
120
+ sim_is_associated_to: np.ndarray,
121
+ ) -> np.ndarray:
122
+ """
123
+ Associate inactive micro simulations to most similar active micro simulation.
124
+
125
+ Parameters
126
+ ----------
127
+ similarity_dists : numpy array
128
+ 2D array having similarity distances between each micro simulation pair
129
+ is_sim_active : numpy array
130
+ 1D array having state (active or inactive) of each micro simulation
131
+ sim_is_associated_to : numpy array
132
+ 1D array with values of associated simulations of inactive simulations. Active simulations have None
133
+
134
+ Returns
135
+ -------
136
+ _sim_is_associated_to : numpy array
137
+ 1D array with values of associated simulations of inactive simulations. Active simulations have None
138
+ """
139
+ active_ids = np.where(is_sim_active)[0]
140
+ inactive_ids = np.where(is_sim_active == False)[0]
141
+
142
+ _sim_is_associated_to = np.copy(sim_is_associated_to)
143
+
144
+ # Associate inactive micro sims to active micro sims
145
+ for inactive_id in inactive_ids:
146
+ dist_min = sys.float_info.max
147
+ for active_id in active_ids:
148
+ # Find most similar active sim for every inactive sim
149
+ if similarity_dists[inactive_id, active_id] < dist_min:
150
+ associated_active_id = active_id
151
+ dist_min = similarity_dists[inactive_id, active_id]
152
+
153
+ _sim_is_associated_to[inactive_id] = associated_active_id
154
+
155
+ return _sim_is_associated_to
156
+
157
+ def _check_for_activation(
158
+ self, inactive_id: int, similarity_dists: np.ndarray, is_sim_active: np.ndarray
159
+ ) -> bool:
160
+ """
161
+ Check if an inactive simulation needs to be activated.
162
+
163
+ Parameters
164
+ ----------
165
+ inactive_id : int
166
+ ID of inactive simulation which is checked for activation.
167
+ similarity_dists : numpy array
168
+ 2D array having similarity distances between each micro simulation pair.
169
+ is_sim_active : numpy array
170
+ 1D array having state (active or inactive) of each micro simulation.
171
+
172
+ Return
173
+ ------
174
+ tag : bool
175
+ True if the inactive simulation needs to be activated, False otherwise.
176
+ """
177
+ active_sim_ids = np.where(is_sim_active)[0]
178
+
179
+ dists = similarity_dists[inactive_id, active_sim_ids]
180
+
181
+ # If inactive sim is not similar to any active sim, activate it
182
+ return min(dists) > self._ref_tol
183
+
184
+ def _check_for_deactivation(
185
+ self, active_id: int, similarity_dists: np.ndarray, is_sim_active: np.ndarray
186
+ ) -> bool:
187
+ """
188
+ Check if an active simulation needs to be deactivated.
189
+
190
+ Parameters
191
+ ----------
192
+ active_id : int
193
+ ID of active simulation which is checked for deactivation.
194
+ similarity_dists : numpy array
195
+ 2D array having similarity distances between each micro simulation pair.
196
+ is_sim_active : numpy array
197
+ 1D array having state (active or inactive) of each micro simulation.
198
+
199
+ Return
200
+ ------
201
+ tag : bool
202
+ True if the active simulation needs to be deactivated, False otherwise.
203
+ """
204
+ active_sim_ids = np.where(is_sim_active)[0]
205
+
206
+ for active_id_2 in active_sim_ids:
207
+ if active_id != active_id_2: # don't compare active sim to itself
208
+ # If active sim is similar to another active sim, deactivate it
209
+ if similarity_dists[active_id, active_id_2] < self._coarse_tol:
210
+ return True
211
+ return False
212
+
213
+ def _get_similarity_measure(
214
+ self, similarity_measure: str
215
+ ) -> Callable[[np.ndarray], np.ndarray]:
216
+ """
217
+ Get similarity measure to be used for similarity calculation
218
+
219
+ Parameters
220
+ ----------
221
+ similarity_measure : str
222
+ String specifying the similarity measure to be used
223
+
224
+ Returns
225
+ -------
226
+ similarity_measure : function
227
+ Function to be used for similarity calculation. Takes data as input and returns similarity measure
228
+ """
229
+ if similarity_measure == "L1":
230
+ return self._l1
231
+ elif similarity_measure == "L2":
232
+ return self._l2
233
+ elif similarity_measure == "L1rel":
234
+ return self._l1rel
235
+ elif similarity_measure == "L2rel":
236
+ return self._l2rel
237
+ else:
238
+ raise ValueError(
239
+ 'Similarity measure not supported. Currently supported similarity measures are "L1", "L2", "L1rel", "L2rel".'
240
+ )
241
+
242
+ def _l1(self, data: np.ndarray) -> np.ndarray:
243
+ """
244
+ Calculate L1 norm of data
245
+
246
+ Parameters
247
+ ----------
248
+ data : numpy array
249
+ Data to be used in similarity distance calculation
250
+
251
+ Returns
252
+ -------
253
+ similarity_dists : numpy array
254
+ Updated 2D array having similarity distances between each micro simulation pair
255
+ """
256
+ return np.linalg.norm(data[np.newaxis, :] - data[:, np.newaxis], ord=1, axis=-1)
257
+
258
+ def _l2(self, data: np.ndarray) -> np.ndarray:
259
+ """
260
+ Calculate L2 norm of data
261
+
262
+ Parameters
263
+ ----------
264
+ data : numpy array
265
+ Data to be used in similarity distance calculation
266
+
267
+ Returns
268
+ -------
269
+ similarity_dists : numpy array
270
+ Updated 2D array having similarity distances between each micro simulation pair
271
+ """
272
+ return np.linalg.norm(data[np.newaxis, :] - data[:, np.newaxis], ord=2, axis=-1)
273
+
274
+ def _l1rel(self, data: np.ndarray) -> np.ndarray:
275
+ """
276
+ Calculate L1 norm of relative difference of data.
277
+ The relative difference is calculated by dividing the difference of two data points by the maximum of the absolute value of the two data points.
278
+
279
+ Parameters
280
+ ----------
281
+ data : numpy array
282
+ Data to be used in similarity distance calculation
283
+
284
+ Returns
285
+ -------
286
+ similarity_dists : numpy array
287
+ Updated 2D array having similarity distances between each micro simulation pair
288
+ """
289
+ pointwise_diff = data[np.newaxis, :] - data[:, np.newaxis]
290
+ # divide by data to get relative difference
291
+ # divide i,j by max(abs(data[i]),abs(data[j])) to get relative difference
292
+ relative = np.nan_to_num(
293
+ (
294
+ pointwise_diff
295
+ / np.maximum(
296
+ np.absolute(data[np.newaxis, :]), np.absolute(data[:, np.newaxis])
297
+ )
298
+ )
299
+ )
300
+ return np.linalg.norm(relative, ord=1, axis=-1)
301
+
302
+ def _l2rel(self, data: np.ndarray) -> np.ndarray:
303
+ """
304
+ Calculate L2 norm of relative difference of data.
305
+ The relative difference is calculated by dividing the difference of two data points by the maximum of the absolute value of the two data points.
306
+
307
+ Parameters
308
+ ----------
309
+ data : numpy array
310
+ Data to be used in similarity distance calculation
311
+
312
+ Returns
313
+ -------
314
+ similarity_dists : numpy array
315
+ Updated 2D array having similarity distances between each micro simulation pair
316
+ """
317
+ pointwise_diff = data[np.newaxis, :] - data[:, np.newaxis]
318
+ # divide by data to get relative difference
319
+ # divide i,j by max(abs(data[i]),abs(data[j])) to get relative difference
320
+ relative = np.nan_to_num(
321
+ (
322
+ pointwise_diff
323
+ / np.maximum(
324
+ np.absolute(data[np.newaxis, :]), np.absolute(data[:, np.newaxis])
325
+ )
326
+ )
327
+ )
328
+ return np.linalg.norm(relative, ord=2, axis=-1)