middoe 0.0.9__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.
- middoe/__init__.py +0 -0
- middoe/__init__.pyi +0 -0
- middoe/des_md.py +633 -0
- middoe/des_md.pyi +2 -0
- middoe/des_pp.py +681 -0
- middoe/des_pp.pyi +2 -0
- middoe/des_utils.py +948 -0
- middoe/des_utils.pyi +5 -0
- middoe/iden_parmest.py +845 -0
- middoe/iden_parmest.pyi +3 -0
- middoe/iden_uncert.py +854 -0
- middoe/iden_uncert.pyi +5 -0
- middoe/iden_utils.py +1871 -0
- middoe/iden_utils.pyi +33 -0
- middoe/iden_valida.py +198 -0
- middoe/iden_valida.pyi +2 -0
- middoe/krnl_expera.py +429 -0
- middoe/krnl_expera.pyi +3 -0
- middoe/krnl_models.py +1491 -0
- middoe/krnl_models.pyi +30 -0
- middoe/krnl_simula.py +214 -0
- middoe/krnl_simula.pyi +1 -0
- middoe/log_utils.py +270 -0
- middoe/log_utils.pyi +10 -0
- middoe/sc_estima.py +169 -0
- middoe/sc_estima.pyi +3 -0
- middoe/sc_sensa.py +622 -0
- middoe/sc_sensa.pyi +4 -0
- middoe-0.0.9.dist-info/LICENSE +21 -0
- middoe-0.0.9.dist-info/METADATA +118 -0
- middoe-0.0.9.dist-info/RECORD +32 -0
- middoe-0.0.9.dist-info/WHEEL +4 -0
middoe/__init__.py
ADDED
|
File without changes
|
middoe/__init__.pyi
ADDED
|
File without changes
|
middoe/des_md.py
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
from functools import partial
|
|
2
|
+
from scipy.optimize import differential_evolution, Bounds, minimize
|
|
3
|
+
import os
|
|
4
|
+
from middoe.des_utils import _slicer, _segmenter, _reporter, _par_update, build_var_groups, build_linear_constraints, penalized_objective, constraint_violation
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
import numpy as np
|
|
7
|
+
from middoe.krnl_simula import Simula
|
|
8
|
+
|
|
9
|
+
def MD(design_settings, model_structure, modelling_settings, core_number, framework_settings, round):
|
|
10
|
+
"""
|
|
11
|
+
Perform MBDOE_MD design optimization (either local or global).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
# 1) Extract relevant data
|
|
15
|
+
tf = model_structure['t_s'][1]
|
|
16
|
+
ti = model_structure['t_s'][0]
|
|
17
|
+
|
|
18
|
+
tv_iphi_vars = list(model_structure['tv_iphi'].keys())
|
|
19
|
+
tv_iphi_max = [model_structure['tv_iphi'][var]['max'] for var in tv_iphi_vars]
|
|
20
|
+
tv_iphi_min = [model_structure['tv_iphi'][var]['min'] for var in tv_iphi_vars]
|
|
21
|
+
tv_iphi_seg = [model_structure['tv_iphi'][var]['swp'] for var in tv_iphi_vars]
|
|
22
|
+
tv_iphi_const = [model_structure['tv_iphi'][var]['constraints'] for var in tv_iphi_vars]
|
|
23
|
+
tv_iphi_offsett = [model_structure['tv_iphi'][var]['offsett'] for var in tv_iphi_vars]
|
|
24
|
+
tv_iphi_offsetl = [model_structure['tv_iphi'][var]['offsetl'] for var in tv_iphi_vars]
|
|
25
|
+
tv_iphi_cvp = {var: model_structure['tv_iphi'][var]['design_cvp'] for var in tv_iphi_vars}
|
|
26
|
+
|
|
27
|
+
ti_iphi_vars = list(model_structure['ti_iphi'].keys())
|
|
28
|
+
ti_iphi_max = [model_structure['ti_iphi'][var]['max'] for var in ti_iphi_vars]
|
|
29
|
+
ti_iphi_min = [model_structure['ti_iphi'][var]['min'] for var in ti_iphi_vars]
|
|
30
|
+
|
|
31
|
+
tv_ophi_vars = [
|
|
32
|
+
var for var in model_structure['tv_ophi'].keys()
|
|
33
|
+
if model_structure['tv_ophi'][var].get('measured', True)
|
|
34
|
+
]
|
|
35
|
+
tv_ophi_seg = [model_structure['tv_ophi'][var]['sp'] for var in tv_ophi_vars]
|
|
36
|
+
tv_ophi_offsett = [model_structure['tv_ophi'][var]['offsett'] for var in tv_ophi_vars]
|
|
37
|
+
tv_ophi_matching = [model_structure['tv_ophi'][var]['matching'] for var in tv_ophi_vars]
|
|
38
|
+
|
|
39
|
+
ti_ophi_vars = [
|
|
40
|
+
var for var in model_structure['ti_ophi'].keys()
|
|
41
|
+
if model_structure['ti_ophi'][var].get('measured', True)
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
active_solvers = modelling_settings['active_solvers']
|
|
45
|
+
estimations = modelling_settings['normalized_parameters']
|
|
46
|
+
ref_thetas = modelling_settings['theta_parameters']
|
|
47
|
+
theta_parameters = _par_update(ref_thetas, estimations)
|
|
48
|
+
|
|
49
|
+
design_criteria = design_settings['criteria']['MBDOE_MD_criterion']
|
|
50
|
+
nd = design_settings['iteration_settings']['nd']
|
|
51
|
+
eps = design_settings['eps']
|
|
52
|
+
maxmd = design_settings['iteration_settings']['maxmd']
|
|
53
|
+
tolmd = design_settings['iteration_settings']['tolmd']
|
|
54
|
+
mutation = modelling_settings['mutation']
|
|
55
|
+
|
|
56
|
+
# 2) Decide local vs global
|
|
57
|
+
method_key = design_settings['optimization_methods']['mdopt_method']
|
|
58
|
+
if method_key == 'Local':
|
|
59
|
+
result, index_dict = _optimizel(
|
|
60
|
+
tv_iphi_vars, tv_iphi_seg, tv_iphi_max, tv_iphi_min, tv_iphi_const,
|
|
61
|
+
tv_iphi_offsett, tv_iphi_offsetl, tv_iphi_cvp,
|
|
62
|
+
ti_iphi_vars, ti_iphi_max, ti_iphi_min,
|
|
63
|
+
tv_ophi_vars, tv_ophi_seg, tv_ophi_offsett, tv_ophi_matching,
|
|
64
|
+
ti_ophi_vars,
|
|
65
|
+
tf, ti,
|
|
66
|
+
active_solvers, theta_parameters, nd, eps, maxmd, tolmd,
|
|
67
|
+
mutation, design_criteria, model_structure, modelling_settings
|
|
68
|
+
)
|
|
69
|
+
elif method_key == 'Global':
|
|
70
|
+
result, index_dict = _optimizeg(
|
|
71
|
+
tv_iphi_vars, tv_iphi_seg, tv_iphi_max, tv_iphi_min, tv_iphi_const,
|
|
72
|
+
tv_iphi_offsett, tv_iphi_offsetl, tv_iphi_cvp,
|
|
73
|
+
ti_iphi_vars, ti_iphi_max, ti_iphi_min,
|
|
74
|
+
tv_ophi_vars, tv_ophi_seg, tv_ophi_offsett, tv_ophi_matching,
|
|
75
|
+
ti_ophi_vars,
|
|
76
|
+
tf, ti,
|
|
77
|
+
active_solvers, theta_parameters, nd, eps, maxmd, tolmd,
|
|
78
|
+
mutation, design_criteria, model_structure, modelling_settings
|
|
79
|
+
)
|
|
80
|
+
else:
|
|
81
|
+
raise ValueError(f"Unknown method '{method_key}' for mdopt_method.")
|
|
82
|
+
|
|
83
|
+
# 3) Evaluate again at nd2
|
|
84
|
+
nd = design_settings['iteration_settings']['nd2']
|
|
85
|
+
|
|
86
|
+
# 4) Use the final solution in _runner
|
|
87
|
+
phi, swps, St, sum_sq_diffs, t_vals, tv_ophi_dict, ti_ophi_dict, phit = _runner(
|
|
88
|
+
result.x, nd, tv_iphi_vars, tv_iphi_max, ti_iphi_vars, ti_iphi_max,
|
|
89
|
+
tv_ophi_vars, ti_ophi_vars, active_solvers,
|
|
90
|
+
theta_parameters, tv_iphi_cvp, design_criteria, tf, eps, mutation,
|
|
91
|
+
index_dict, model_structure, modelling_settings
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
# 5) Prepare output
|
|
95
|
+
# You can create plots, save to file, etc.:
|
|
96
|
+
base_path = framework_settings['path']
|
|
97
|
+
modelling_folder = str(framework_settings['case'])
|
|
98
|
+
filename = os.path.join(base_path, modelling_folder)
|
|
99
|
+
os.makedirs(filename, exist_ok=True)
|
|
100
|
+
|
|
101
|
+
# Suppose you call _reporter(...) to finalize
|
|
102
|
+
phi, phit, swps, St = _reporter(
|
|
103
|
+
phi, phit, swps, St,
|
|
104
|
+
sum_sq_diffs, t_vals,
|
|
105
|
+
tv_ophi_dict, ti_ophi_dict,
|
|
106
|
+
tv_iphi_vars, tv_iphi_max,
|
|
107
|
+
ti_iphi_vars, ti_iphi_max,
|
|
108
|
+
tf, filename,
|
|
109
|
+
design_criteria,
|
|
110
|
+
round,
|
|
111
|
+
core_number
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
design_decisions = {
|
|
115
|
+
'phi': phi,
|
|
116
|
+
'phit': phit,
|
|
117
|
+
'swps': swps,
|
|
118
|
+
'St': St,
|
|
119
|
+
't_values': t_vals
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return design_decisions, sum_sq_diffs, swps
|
|
123
|
+
|
|
124
|
+
def _optimizeg(tv_iphi_vars, tv_iphi_seg, tv_iphi_max, tv_iphi_min, tv_iphi_const,
|
|
125
|
+
tv_iphi_offsett, tv_iphi_offsetl, tv_iphi_cvp,
|
|
126
|
+
ti_iphi_vars, ti_iphi_max, ti_iphi_min,
|
|
127
|
+
tv_ophi_vars, tv_ophi_seg, tv_ophi_offsett_ophi, tv_ophi_matching,
|
|
128
|
+
ti_ophi_vars,
|
|
129
|
+
tf, ti,
|
|
130
|
+
active_solvers, theta_parameters, nd, eps, maxmd, tolmd,
|
|
131
|
+
mutation, design_criteria, model_structure, modelling_settings):
|
|
132
|
+
"""
|
|
133
|
+
Global optimization (Differential Evolution) for MBDOE_MD,
|
|
134
|
+
then local refinement (trust-constr).
|
|
135
|
+
Returns (result, index_dict).
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
# 1) var_groups
|
|
139
|
+
var_groups = build_var_groups(
|
|
140
|
+
tv_iphi_vars, tv_iphi_offsetl, tv_iphi_offsett, tv_iphi_const,
|
|
141
|
+
tv_ophi_vars, tv_ophi_offsett_ophi
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
# 2) Segmenter => bounds, x0, index_pairs, index_dict
|
|
145
|
+
bounds_list, x0, index_pairs_levels, index_pairs_times, index_dict = _segmenter(
|
|
146
|
+
tv_iphi_vars, tv_iphi_seg, tv_iphi_max, tv_iphi_min, tv_iphi_const,
|
|
147
|
+
tv_iphi_offsett, tv_iphi_offsetl,
|
|
148
|
+
ti_iphi_vars, ti_iphi_max, ti_iphi_min,
|
|
149
|
+
tv_ophi_vars, tv_ophi_seg, tv_ophi_offsett_ophi, tv_ophi_matching,
|
|
150
|
+
tf, ti
|
|
151
|
+
)
|
|
152
|
+
lower_bounds = [b[0] for b in bounds_list]
|
|
153
|
+
upper_bounds = [b[1] for b in bounds_list]
|
|
154
|
+
x0 = np.clip(x0, lower_bounds, upper_bounds)
|
|
155
|
+
|
|
156
|
+
trust_bounds = Bounds(lower_bounds, upper_bounds)
|
|
157
|
+
|
|
158
|
+
# 3) Build linear constraints
|
|
159
|
+
(A_level, lb_level,
|
|
160
|
+
A_time, lb_time,
|
|
161
|
+
constraints_list) = build_linear_constraints(
|
|
162
|
+
x_len=len(x0),
|
|
163
|
+
index_pairs_levels=index_pairs_levels,
|
|
164
|
+
index_pairs_times=index_pairs_times,
|
|
165
|
+
var_groups=var_groups
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
# 4) Build a partial function for the objective
|
|
169
|
+
local_obj_fun = partial(
|
|
170
|
+
md_objective_function,
|
|
171
|
+
nd=nd,
|
|
172
|
+
tv_iphi_vars=tv_iphi_vars,
|
|
173
|
+
tv_iphi_max=tv_iphi_max,
|
|
174
|
+
ti_iphi_vars=ti_iphi_vars,
|
|
175
|
+
ti_iphi_max=ti_iphi_max,
|
|
176
|
+
tv_ophi_vars=tv_ophi_vars,
|
|
177
|
+
ti_ophi_vars=ti_ophi_vars,
|
|
178
|
+
active_solvers=active_solvers,
|
|
179
|
+
theta_parameters=theta_parameters,
|
|
180
|
+
tv_iphi_cvp=tv_iphi_cvp,
|
|
181
|
+
design_criteria=design_criteria,
|
|
182
|
+
tf=tf,
|
|
183
|
+
eps=eps,
|
|
184
|
+
mutation=mutation,
|
|
185
|
+
index_dict=index_dict,
|
|
186
|
+
model_structure=model_structure,
|
|
187
|
+
modelling_settings=modelling_settings,
|
|
188
|
+
runner_function=_runner
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# 5) For DE, define a penalty-based objective
|
|
192
|
+
# pass references to local_obj_fun plus A_level etc.
|
|
193
|
+
obj_args = {
|
|
194
|
+
'objective_fun': local_obj_fun
|
|
195
|
+
}
|
|
196
|
+
constraint_args = {
|
|
197
|
+
'violation_fun': partial(
|
|
198
|
+
constraint_violation,
|
|
199
|
+
A_level=A_level,
|
|
200
|
+
lb_level=lb_level,
|
|
201
|
+
A_time=A_time,
|
|
202
|
+
lb_time=lb_time
|
|
203
|
+
)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
penalized_de_fun = partial(
|
|
207
|
+
penalized_objective,
|
|
208
|
+
obj_args=obj_args,
|
|
209
|
+
constraint_args=constraint_args,
|
|
210
|
+
penalty_weight=1e4
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
# 6) Differential Evolution
|
|
214
|
+
de_bounds = list(zip(lower_bounds, upper_bounds))
|
|
215
|
+
de_result = differential_evolution(
|
|
216
|
+
penalized_de_fun,
|
|
217
|
+
bounds=de_bounds,
|
|
218
|
+
strategy='best1bin',
|
|
219
|
+
maxiter=50, # or whatever you want
|
|
220
|
+
popsize=15,
|
|
221
|
+
tol=1e-6,
|
|
222
|
+
mutation=(0.5, 1.0),
|
|
223
|
+
recombination=0.7,
|
|
224
|
+
seed=None,
|
|
225
|
+
polish=False, # local refinement ourselves
|
|
226
|
+
workers=-1, # parallel
|
|
227
|
+
updating='deferred',
|
|
228
|
+
disp=True
|
|
229
|
+
)
|
|
230
|
+
x0_de = de_result.x
|
|
231
|
+
|
|
232
|
+
# 7) Local refinement with trust-constr
|
|
233
|
+
result = minimize(
|
|
234
|
+
fun=local_obj_fun,
|
|
235
|
+
x0=x0_de,
|
|
236
|
+
bounds=trust_bounds,
|
|
237
|
+
constraints=constraints_list,
|
|
238
|
+
method='trust-constr',
|
|
239
|
+
options={
|
|
240
|
+
'maxiter': maxmd,
|
|
241
|
+
'verbose': 3,
|
|
242
|
+
'xtol': tolmd,
|
|
243
|
+
'gtol': tolmd,
|
|
244
|
+
'barrier_tol': 1e-8,
|
|
245
|
+
}
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
if not result.success:
|
|
249
|
+
print("Global+Local Optimization (MBDOE_MD) failed or did not converge.")
|
|
250
|
+
else:
|
|
251
|
+
print("Global+Local Optimization (MBDOE_MD) succeeded!")
|
|
252
|
+
|
|
253
|
+
return result, index_dict
|
|
254
|
+
|
|
255
|
+
def _optimizel(tv_iphi_vars, tv_iphi_seg, tv_iphi_max, tv_iphi_min, tv_iphi_const,
|
|
256
|
+
tv_iphi_offsett, tv_iphi_offsetl, tv_iphi_cvp,
|
|
257
|
+
ti_iphi_vars, ti_iphi_max, ti_iphi_min,
|
|
258
|
+
tv_ophi_vars, tv_ophi_seg, tv_ophi_offsett_ophi, tv_ophi_matching,
|
|
259
|
+
ti_ophi_vars,
|
|
260
|
+
tf, ti,
|
|
261
|
+
active_solvers, theta_parameters, nd, eps, maxmd, tolmd,
|
|
262
|
+
mutation, design_criteria, model_structure, modelling_settings):
|
|
263
|
+
"""
|
|
264
|
+
Local optimization for MBDOE_MD (trust-constr).
|
|
265
|
+
Returns (result, index_dict).
|
|
266
|
+
"""
|
|
267
|
+
|
|
268
|
+
# 1) var_groups
|
|
269
|
+
var_groups = build_var_groups(
|
|
270
|
+
tv_iphi_vars, tv_iphi_offsetl, tv_iphi_offsett, tv_iphi_const,
|
|
271
|
+
tv_ophi_vars, tv_ophi_offsett_ophi
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
# 2) Segmenter => bounds, x0, index_pairs, index_dict
|
|
275
|
+
bounds_list, x0, index_pairs_levels, index_pairs_times, index_dict = _segmenter(
|
|
276
|
+
tv_iphi_vars, tv_iphi_seg, tv_iphi_max, tv_iphi_min, tv_iphi_const,
|
|
277
|
+
tv_iphi_offsett, tv_iphi_offsetl,
|
|
278
|
+
ti_iphi_vars, ti_iphi_max, ti_iphi_min,
|
|
279
|
+
tv_ophi_vars, tv_ophi_seg, tv_ophi_offsett_ophi, tv_ophi_matching,
|
|
280
|
+
tf, ti
|
|
281
|
+
)
|
|
282
|
+
lower_bounds = [b[0] for b in bounds_list]
|
|
283
|
+
upper_bounds = [b[1] for b in bounds_list]
|
|
284
|
+
x0 = np.clip(x0, lower_bounds, upper_bounds)
|
|
285
|
+
bounds = Bounds(lower_bounds, upper_bounds)
|
|
286
|
+
|
|
287
|
+
# 3) Build linear constraints
|
|
288
|
+
A_level, lb_level, A_time, lb_time, constraints_list = build_linear_constraints(
|
|
289
|
+
x_len=len(x0),
|
|
290
|
+
index_pairs_levels=index_pairs_levels,
|
|
291
|
+
index_pairs_times=index_pairs_times,
|
|
292
|
+
var_groups=var_groups
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
# 4) Objective function for trust-constr
|
|
296
|
+
def local_objective(x):
|
|
297
|
+
return md_objective_function(
|
|
298
|
+
x,
|
|
299
|
+
nd,
|
|
300
|
+
tv_iphi_vars, tv_iphi_max,
|
|
301
|
+
ti_iphi_vars, ti_iphi_max,
|
|
302
|
+
tv_ophi_vars, ti_ophi_vars,
|
|
303
|
+
active_solvers, theta_parameters,
|
|
304
|
+
tv_iphi_cvp,
|
|
305
|
+
design_criteria,
|
|
306
|
+
tf, eps, mutation,
|
|
307
|
+
index_dict,
|
|
308
|
+
model_structure,
|
|
309
|
+
modelling_settings,
|
|
310
|
+
_runner # pass your actual runner function
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
# 5) Solve with trust-constr
|
|
314
|
+
result = minimize(
|
|
315
|
+
fun=local_objective,
|
|
316
|
+
x0=x0,
|
|
317
|
+
bounds=bounds,
|
|
318
|
+
constraints=constraints_list,
|
|
319
|
+
method='trust-constr',
|
|
320
|
+
options={
|
|
321
|
+
'maxiter': maxmd,
|
|
322
|
+
'verbose': 3,
|
|
323
|
+
'xtol': tolmd,
|
|
324
|
+
'gtol': tolmd,
|
|
325
|
+
'barrier_tol': 1e-8,
|
|
326
|
+
}
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
if not result.success:
|
|
330
|
+
print("Optimization (MBDOE_MD local) failed!")
|
|
331
|
+
else:
|
|
332
|
+
print("Optimization (MBDOE_MD local) succeeded!")
|
|
333
|
+
|
|
334
|
+
return result, index_dict
|
|
335
|
+
|
|
336
|
+
def _runner(
|
|
337
|
+
x, nd,
|
|
338
|
+
tv_iphi_vars, tv_iphi_max,
|
|
339
|
+
ti_iphi_vars, ti_iphi_max,
|
|
340
|
+
tv_ophi_vars, ti_ophi_vars,
|
|
341
|
+
active_solvers, theta_parameters,
|
|
342
|
+
tv_iphi_cvp,
|
|
343
|
+
design_criteria,
|
|
344
|
+
tf, eps, mutation,
|
|
345
|
+
index_dict,
|
|
346
|
+
model_structure,
|
|
347
|
+
modelling_settings
|
|
348
|
+
):
|
|
349
|
+
"""
|
|
350
|
+
Run the optimization process and return the results.
|
|
351
|
+
|
|
352
|
+
Parameters
|
|
353
|
+
----------
|
|
354
|
+
x : list
|
|
355
|
+
Current values of the decision variables.
|
|
356
|
+
nd : int
|
|
357
|
+
Number of time points in the first stage.
|
|
358
|
+
tv_iphi_vars : list
|
|
359
|
+
Time-variant input variables.
|
|
360
|
+
tv_iphi_max : list
|
|
361
|
+
Maximum scaling values for time-variant inputs.
|
|
362
|
+
ti_iphi_vars : list
|
|
363
|
+
Time-invariant input variables.
|
|
364
|
+
ti_iphi_max : list
|
|
365
|
+
Maximum scaling values for time-invariant inputs.
|
|
366
|
+
tv_ophi_vars : list
|
|
367
|
+
Time-variant output variables.
|
|
368
|
+
ti_ophi_vars : list
|
|
369
|
+
Time-invariant output variables.
|
|
370
|
+
active_solvers : list
|
|
371
|
+
List of solver names.
|
|
372
|
+
theta_parameters : dict
|
|
373
|
+
Dictionary of parameter vectors keyed by solver_name.
|
|
374
|
+
tv_iphi_cvp : dict
|
|
375
|
+
Piecewise interpolation or design functions for time-variant inputs.
|
|
376
|
+
design_criteria : str
|
|
377
|
+
The criterion for the design (e.g., 'HR', 'BFF').
|
|
378
|
+
tf : float
|
|
379
|
+
Final time for the experiment.
|
|
380
|
+
eps : float
|
|
381
|
+
Small epsilon for numerical sensitivity.
|
|
382
|
+
mutation : dict
|
|
383
|
+
Dictionary keyed by solver_name → list of booleans (which parameters are free).
|
|
384
|
+
index_dict : dict
|
|
385
|
+
Dictionary of index segments from `_segmenter` / `_slicer`.
|
|
386
|
+
model_structure : dict
|
|
387
|
+
Model structure used by the solver.
|
|
388
|
+
modelling_settings : dict
|
|
389
|
+
Additional settings for the solver or experiment.
|
|
390
|
+
|
|
391
|
+
Returns
|
|
392
|
+
-------
|
|
393
|
+
ti : dict or list
|
|
394
|
+
Time-invariant input data from `_slicer`.
|
|
395
|
+
swps : dict or list
|
|
396
|
+
Switching points from `_slicer`.
|
|
397
|
+
St : dict
|
|
398
|
+
Sampling times, keyed by output variable name → array of times.
|
|
399
|
+
sum_squared_differences : float
|
|
400
|
+
The objective function value.
|
|
401
|
+
t_values : list
|
|
402
|
+
Final time grid used in the simulation (dimensionless from 0..1 plus any St points).
|
|
403
|
+
tv_ophi : dict
|
|
404
|
+
Time-variant outputs from each solver.
|
|
405
|
+
ti_ophi : dict
|
|
406
|
+
Time-invariant outputs from each solver.
|
|
407
|
+
phit_interp : any
|
|
408
|
+
Additional data from the solver (if returned).
|
|
409
|
+
"""
|
|
410
|
+
|
|
411
|
+
# 1) Extract design parameters via _slicer
|
|
412
|
+
x = x.tolist() if not isinstance(x, list) else x
|
|
413
|
+
ti, swps, St = _slicer(x, index_dict)
|
|
414
|
+
|
|
415
|
+
# Convert St to a dict of {var: np.array([...])}
|
|
416
|
+
for var in St:
|
|
417
|
+
if not isinstance(St[var], np.ndarray):
|
|
418
|
+
St[var] = np.array(St[var])
|
|
419
|
+
|
|
420
|
+
# 2) Build the combined time vector: dimensionless 0..1 plus any points from St
|
|
421
|
+
t_values_flat = []
|
|
422
|
+
for var in St:
|
|
423
|
+
t_values_flat.extend(St[var]) # gather all sampling times for all variables
|
|
424
|
+
t_lin = np.linspace(0, 1, nd)
|
|
425
|
+
t_values = np.unique(np.concatenate([t_lin, t_values_flat])).tolist()
|
|
426
|
+
|
|
427
|
+
# 3) Prepare data structures
|
|
428
|
+
LSA = defaultdict(lambda: defaultdict(dict))
|
|
429
|
+
y_values_dict = defaultdict(dict) # For each solver, store {var: array_of_outputs}
|
|
430
|
+
y_i_values_dict = defaultdict(dict) # For partial-derivative modifications
|
|
431
|
+
indices = {} # For each var, a boolean mask in t_values
|
|
432
|
+
for var in tv_ophi_vars:
|
|
433
|
+
if var not in St:
|
|
434
|
+
raise ValueError(f"No time values found for variable '{var}' in St.")
|
|
435
|
+
mask = np.isin(t_values, St[var])
|
|
436
|
+
indices[var] = mask
|
|
437
|
+
|
|
438
|
+
# J_dot: dictionary of solver_name → array of shape (#params, #params)
|
|
439
|
+
J_dot = defaultdict(
|
|
440
|
+
lambda: np.zeros(
|
|
441
|
+
(len(theta_parameters[active_solvers[0]]),
|
|
442
|
+
len(theta_parameters[active_solvers[0]])),
|
|
443
|
+
dtype=float
|
|
444
|
+
)
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
# For storing final solver outputs
|
|
448
|
+
tv_ophi = {}
|
|
449
|
+
ti_ophi = {}
|
|
450
|
+
|
|
451
|
+
# 4) Solve each model + compute partial derivatives
|
|
452
|
+
for solver_name in active_solvers:
|
|
453
|
+
thetac = theta_parameters[solver_name]
|
|
454
|
+
theta = np.array([1.0] * len(thetac), dtype=float) # initial guess or scale factor?
|
|
455
|
+
|
|
456
|
+
# Gather data from slicer
|
|
457
|
+
ti_iphi_data = ti
|
|
458
|
+
swps_data = swps
|
|
459
|
+
|
|
460
|
+
# Build scaling dicts
|
|
461
|
+
phisc = {var: ti_iphi_max[i] for i, var in enumerate(ti_iphi_vars)}
|
|
462
|
+
phitsc = {var: tv_iphi_max[i] for i, var in enumerate(tv_iphi_vars)}
|
|
463
|
+
tsc = tf # pass to solver if the solver does time-scaling internally
|
|
464
|
+
|
|
465
|
+
# 4a) Run solver unperturbed
|
|
466
|
+
tv_ophi[solver_name], ti_ophi[solver_name], phit_interp = Simula(
|
|
467
|
+
t_values,
|
|
468
|
+
swps_data,
|
|
469
|
+
ti_iphi_data,
|
|
470
|
+
phisc,
|
|
471
|
+
phitsc,
|
|
472
|
+
tsc,
|
|
473
|
+
theta,
|
|
474
|
+
thetac,
|
|
475
|
+
tv_iphi_cvp,
|
|
476
|
+
{},
|
|
477
|
+
solver_name,
|
|
478
|
+
model_structure,
|
|
479
|
+
modelling_settings
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
# 4b) Store results in y_values_dict[solver_name][var]
|
|
483
|
+
# So we can easily do y_values_dict[solver_name][var][mask]
|
|
484
|
+
for var in tv_ophi_vars:
|
|
485
|
+
y_values_dict[solver_name][var] = np.array(tv_ophi[solver_name][var])
|
|
486
|
+
for var in ti_ophi_vars:
|
|
487
|
+
y_values_dict[solver_name][var] = np.array(ti_ophi[solver_name][var])
|
|
488
|
+
|
|
489
|
+
# 4c) Prepare for partial derivatives
|
|
490
|
+
free_params_indices = [i for i, is_free in enumerate(mutation[solver_name]) if is_free]
|
|
491
|
+
|
|
492
|
+
# For each free parameter, perturb and re-run
|
|
493
|
+
for para_idx in free_params_indices:
|
|
494
|
+
modified_theta = theta.copy()
|
|
495
|
+
modified_theta[para_idx] += eps
|
|
496
|
+
|
|
497
|
+
# Re-run solver with perturbed parameter
|
|
498
|
+
tv_mod, ti_mod, _ = Simula(
|
|
499
|
+
t_values,
|
|
500
|
+
swps_data,
|
|
501
|
+
ti_iphi_data,
|
|
502
|
+
phisc,
|
|
503
|
+
phitsc,
|
|
504
|
+
tsc,
|
|
505
|
+
modified_theta,
|
|
506
|
+
thetac,
|
|
507
|
+
tv_iphi_cvp,
|
|
508
|
+
{},
|
|
509
|
+
solver_name,
|
|
510
|
+
model_structure,
|
|
511
|
+
modelling_settings
|
|
512
|
+
)
|
|
513
|
+
|
|
514
|
+
# Store these modified solver outputs
|
|
515
|
+
for var in tv_ophi_vars:
|
|
516
|
+
y_i_values_dict[solver_name][var] = np.array(tv_mod[var])
|
|
517
|
+
for var in ti_ophi_vars:
|
|
518
|
+
y_i_values_dict[solver_name][var] = np.array(ti_mod[var])
|
|
519
|
+
|
|
520
|
+
# For each var in indices, compute partial derivative
|
|
521
|
+
for var, mask in indices.items():
|
|
522
|
+
# base_vals = unperturbed solver result
|
|
523
|
+
base_vals = y_values_dict[solver_name][var]
|
|
524
|
+
# pert_vals = perturbed solver result
|
|
525
|
+
pert_vals = y_i_values_dict[solver_name][var]
|
|
526
|
+
# difference
|
|
527
|
+
diff = pert_vals - base_vals
|
|
528
|
+
# partial derivative
|
|
529
|
+
LSA[var][solver_name][para_idx] = diff / eps
|
|
530
|
+
|
|
531
|
+
# 4d) Build solver_LSA by stacking across all `var in indices`
|
|
532
|
+
solver_LSA_list = []
|
|
533
|
+
for var in indices:
|
|
534
|
+
# For each param i in free_params_indices, grab LSA[var][solver_name][i]
|
|
535
|
+
row_for_var = [LSA[var][solver_name][i] for i in free_params_indices]
|
|
536
|
+
# Suppose we take the mean across the time dimension
|
|
537
|
+
row_summed = np.array([arr.mean() for arr in row_for_var])
|
|
538
|
+
solver_LSA_list.append(row_summed)
|
|
539
|
+
|
|
540
|
+
# Convert to array => shape (#vars, #free_params)
|
|
541
|
+
solver_LSA = np.array(solver_LSA_list, dtype=float)
|
|
542
|
+
|
|
543
|
+
# 4e) Compute J^T J
|
|
544
|
+
J_transpose = solver_LSA.T
|
|
545
|
+
J_dot_matrix = np.dot(J_transpose, solver_LSA)
|
|
546
|
+
|
|
547
|
+
# Ensure correct shape
|
|
548
|
+
if J_dot[solver_name].shape != (solver_LSA.shape[1], solver_LSA.shape[1]):
|
|
549
|
+
J_dot[solver_name] = np.zeros((solver_LSA.shape[1], solver_LSA.shape[1]), dtype=float)
|
|
550
|
+
|
|
551
|
+
J_dot[solver_name] += J_dot_matrix
|
|
552
|
+
|
|
553
|
+
# 5) Compute the objective
|
|
554
|
+
sum_squared_differences = 0.0
|
|
555
|
+
|
|
556
|
+
if design_criteria == 'HR':
|
|
557
|
+
# Compare pairwise differences between all solvers
|
|
558
|
+
for i, solver1 in enumerate(active_solvers):
|
|
559
|
+
for solver2 in active_solvers[i+1:]:
|
|
560
|
+
# For each var in tv_ophi_vars (since indices only has those)
|
|
561
|
+
for var, mask in indices.items():
|
|
562
|
+
y1 = y_values_dict[solver1][var]
|
|
563
|
+
y2 = y_values_dict[solver2][var]
|
|
564
|
+
y1_subset = y1[mask]
|
|
565
|
+
y2_subset = y2[mask]
|
|
566
|
+
sum_squared_differences += np.sum((y1_subset - y2_subset)**2)
|
|
567
|
+
|
|
568
|
+
elif design_criteria == 'BFF':
|
|
569
|
+
# For each solver, do quadratic form (diff)^T (J + regI) (diff)
|
|
570
|
+
for solver_name in active_solvers:
|
|
571
|
+
J_reg = J_dot[solver_name] + 1e-10 * np.eye(J_dot[solver_name].shape[0])
|
|
572
|
+
# For each variable in indices, build difference_vector
|
|
573
|
+
for var, mask in indices.items():
|
|
574
|
+
diff_vec = y_values_dict[solver_name][var][mask]
|
|
575
|
+
# Check shape
|
|
576
|
+
if J_reg.shape[0] != diff_vec.shape[0]:
|
|
577
|
+
raise ValueError(
|
|
578
|
+
f"Shape mismatch: J_dot has shape {J_reg.shape}, "
|
|
579
|
+
f"but difference_vector for var '{var}' has shape {diff_vec.shape}."
|
|
580
|
+
)
|
|
581
|
+
sum_squared_differences += diff_vec @ (J_reg @ diff_vec)
|
|
582
|
+
|
|
583
|
+
print(f"\rmbdoe-MD:{design_criteria} is running with {sum_squared_differences}", end='', flush=True)
|
|
584
|
+
|
|
585
|
+
# Return everything needed
|
|
586
|
+
return ti, swps, St, sum_squared_differences, t_values, tv_ophi, ti_ophi, phit_interp
|
|
587
|
+
|
|
588
|
+
def md_objective_function(
|
|
589
|
+
x,
|
|
590
|
+
nd,
|
|
591
|
+
tv_iphi_vars, tv_iphi_max,
|
|
592
|
+
ti_iphi_vars, ti_iphi_max,
|
|
593
|
+
tv_ophi_vars, ti_ophi_vars,
|
|
594
|
+
active_solvers, theta_parameters,
|
|
595
|
+
tv_iphi_cvp,
|
|
596
|
+
design_criteria,
|
|
597
|
+
tf, eps, mutation,
|
|
598
|
+
index_dict,
|
|
599
|
+
model_structure,
|
|
600
|
+
modelling_settings,
|
|
601
|
+
runner_function
|
|
602
|
+
):
|
|
603
|
+
"""
|
|
604
|
+
A top-level objective function that calls your _runner function
|
|
605
|
+
and returns -md_obj (assuming you want to maximize md_obj).
|
|
606
|
+
"""
|
|
607
|
+
try:
|
|
608
|
+
# _runner signature:
|
|
609
|
+
# def _runner(x, nd, tv_iphi_vars, tv_iphi_max, ti_iphi_vars, ti_iphi_max,
|
|
610
|
+
# tv_ophi_vars, ti_ophi_vars, active_solvers, theta_parameters,
|
|
611
|
+
# tv_iphi_cvp, design_criteria, tf, eps, mutation,
|
|
612
|
+
# index_dict, model_structure, modelling_settings)
|
|
613
|
+
_, _, _, md_obj, _, _, _, _ = runner_function(
|
|
614
|
+
x,
|
|
615
|
+
nd,
|
|
616
|
+
tv_iphi_vars, tv_iphi_max,
|
|
617
|
+
ti_iphi_vars, ti_iphi_max,
|
|
618
|
+
tv_ophi_vars, ti_ophi_vars,
|
|
619
|
+
active_solvers, theta_parameters,
|
|
620
|
+
tv_iphi_cvp,
|
|
621
|
+
design_criteria,
|
|
622
|
+
tf, eps, mutation,
|
|
623
|
+
index_dict,
|
|
624
|
+
model_structure,
|
|
625
|
+
modelling_settings
|
|
626
|
+
)
|
|
627
|
+
if np.isnan(md_obj):
|
|
628
|
+
return 1e6 # penalty
|
|
629
|
+
return -md_obj # negative => "maximize" md_obj
|
|
630
|
+
except Exception as e:
|
|
631
|
+
print(f"Exception in md_objective_function: {e}")
|
|
632
|
+
return 1e6 # big penalty on exception
|
|
633
|
+
|
middoe/des_md.pyi
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
def MD(design_settings, model_structure, modelling_settings, core_number, framework_settings, round) -> None: ...
|
|
2
|
+
def md_objective_function(x, nd, tv_iphi_vars, tv_iphi_max, ti_iphi_vars, ti_iphi_max, tv_ophi_vars, ti_ophi_vars, active_solvers, theta_parameters, tv_iphi_cvp, design_criteria, tf, eps, mutation, index_dict, model_structure, modelling_settings, runner_function) -> None: ...
|