forked from CCSI-Toolset/fixed_bed_adsorption
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fim_doe.py
2716 lines (2293 loc) · 120 KB
/
fim_doe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#################################################################################################################
# Copyright (c) 2022
# *** Copyright Notice ***
# Pyomo.DOE was produced under the DOE Carbon Capture Simulation Initiative (CCSI), and is
# copyright (c) 2022 by the software owners: TRIAD, LLNS, BERKELEY LAB, PNNL, UT-Battelle, LLC, NOTRE
# DAME, PITT, UT Austin, TOLEDO, WVU, et al. All rights reserved.
#
# NOTICE. This Software was developed under funding from the U.S. Department of Energy and the U.S.
# Government consequently retains certain rights. As such, the U.S. Government has been granted for itself
# and others acting on its behalf a paid-up, nonexclusive, irrevocable, worldwide license in the Software to
# reproduce, distribute copies to the public, prepare derivative works, and perform publicly and display
# publicly, and to permit other to do so.
#
# *** License Agreement ***
#
# Pyomo.DOE Copyright (c) 2022, by the software owners: TRIAD, LLNS, BERKELEY LAB, PNNL, UT-
# Battelle, LLC, NOTRE DAME, PITT, UT Austin, TOLEDO, WVU, et al. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided
# that the following conditions are met:
# (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the
# following disclaimer.
# (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
# the following disclaimer in the documentation and/or other materials provided with the distribution.
# (3) Neither the name of the Carbon Capture Simulation for Industry Impact, TRIAD, LLNS, BERKELEY LAB,
# PNNL, UT-Battelle, LLC, ORNL, NOTRE DAME, PITT, UT Austin, TOLEDO, WVU, U.S. Dept. of Energy nor
# the names of its contributors may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
# THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# You are under no obligation whatsoever to provide any bug fixes, patches, or upgrades to the features,
# functionality or performance of the source code ("Enhancements") to anyone; however, if you choose to
# make your Enhancements available either publicly, or directly to Lawrence Berkeley National Laboratory,
# without imposing a separate written license agreement for such Enhancements, then you hereby grant
# the following license: a non-exclusive, royalty-free perpetual license to install, use, modify, prepare
# derivative works, incorporate into other computer software, distribute, and sublicense such
# enhancements or derivative works thereof, in binary and source code form.
#
# Lead Developers: Jialu Wang and Alexander Dowling, University of Notre Dame
#
#################################################################################################################
import numpy as np
import matplotlib.pyplot as plt
from pyomo.environ import *
from pyomo.dae import *
import pandas as pd
import time
import pickle
from itertools import permutations, product
from pyomo.contrib.sensitivity_toolbox.sens import sipopt, sensitivity_calculation, get_dsdp
class Measurements:
def __init__(self, measurement_index_time, variance=None, ind_string='_index_'):
'''
This class stores measurements' information
Parameters:
----------
measurement_index_time: a dictionary, keys are measurement variable names,
values are a dictionary, keys are its extra index, values are its measuring time points
values are a list of measuring time point if there is no extra index for this measurement
For e.g., for the kinetics illustrative example, it should be {'C':{'CA':[0,1,..], 'CB':[0,2,...]}, 'k':[0,4,..]},
so the measurements are C[scenario, 'CA', 0]..., k[scenario, 0]....
variance: a dictionary, keys are measurement variable names,
values are a dictionary, keys are its extra index, values are its variance (a scalar number)
values are its variance if there is no extra index for this measurement
For e.g., for the kinetics illustrative example, it should be {'C':{'CA': 10, 'CB': 1, 'CC': 2}}
If given None, the default is {'C':{'CA': 1, 'CB': 1, 'CC': 1}}.
'''
self.measurement_all_info = measurement_index_time
self.ind_string = ind_string
# a list of measurement names
self.measurement_name = list(measurement_index_time.keys())
# begin flatten
self.__name_and_index_generator(self.measurement_all_info)
self.__generate_flatten_name(self.name_and_index)
self.__generate_variance(self.flatten_measure_name, variance, self.name_and_index)
self.__generate_flatten_timeset(self.measurement_all_info, self.flatten_measure_name, self.name_and_index)
self.__model_measure_name()
print('All measurements are flattened.')
print('Flatten measurement name:', self.flatten_measure_name)
#print('Flatten measurement timeset:', self.flatten_measure_timeset)
# generate the overall measurement time points set, including the measurement time for all measurements
flatten_timepoint = list(self.flatten_measure_timeset.values())
overall_time = []
for i in flatten_timepoint:
overall_time += i
timepoint_overall_set = list(set(overall_time))
self.timepoint_overall_set = timepoint_overall_set
def __name_and_index_generator(self, all_info):
'''
Generate a dictionary, keys are the variable names, values are the indexes of this variable.
For e.g., name_and_index = {'C': ['CA', 'CB', 'CC']}
Arguments
---------
all_info: a dictionary, keys are measurement variable names,
values are a dictionary, keys are its extra index, values are its measuring time points
values are a list of measuring time point if there is no extra index for this measurement
Note: all_info can be the self.measurement_all_info, but does not have to be it.
'''
measurement_name = list(all_info.keys())
# a list of measurement extra indexes
measurement_extra_index = []
# a list of measurement names with extra indexes
extra_measure_name = []
# check if the measurement has extra indexes
for i in measurement_name:
if type(all_info[i]) is dict:
index_list = list(all_info[i].keys())
extra_measure_name.append(i)
measurement_extra_index.append(index_list)
elif type(all_info[i]) is list:
measurement_extra_index.append(None)
# a dictionary, keys are measurement names, values are a list of extra indexes
name_and_index = {}
for i, iname in enumerate(measurement_name):
name_and_index[iname] = measurement_extra_index[i]
self.name_and_index = name_and_index
def __generate_flatten_name(self, measure_name_and_index):
'''Generate measurement flattened names
Parameters
----------
measure_name_and_index: a dictionary, keys are measurement names, values are lists of extra indexes
Returns
------
jac_involved_name: a list of flattened measurement names
'''
flatten_names = []
for j in list(measure_name_and_index.keys()):
if measure_name_and_index[j] is not None: # if it has extra index
for ind in measure_name_and_index[j]:
flatten_name = j + self.ind_string + str(ind)
flatten_names.append(flatten_name)
else:
flatten_names.append(j)
self.flatten_measure_name = flatten_names
def __generate_variance(self, flatten_measure_name, variance, name_and_index):
'''Generate the variance dictionary
'''
flatten_variance = {}
for i in flatten_measure_name:
if variance is None:
flatten_variance[i] = 1
else:
# split the flattened name if needed
if self.ind_string in i:
measure_name = i.split(self.ind_string)[0]
measure_index = i.split(self.ind_string)[1]
if type(name_and_index[measure_name][0]) is int:
measure_index = int(measure_index)
flatten_variance[i] = variance[measure_name][measure_index]
else:
flatten_variance[i] = variance[i]
self.flatten_variance = flatten_variance
def __generate_flatten_timeset(self, all_info, flatten_measure_name,name_and_index):
'''
Generate flatten variables timeset. Return a dict where keys are the flattened variable names,
values are a list of measurement time.
'''
flatten_measure_timeset = {}
for i in flatten_measure_name:
# split the flattened name if needed
if self.ind_string in i:
measure_name = i.split(self.ind_string)[0]
measure_index = i.split(self.ind_string)[1]
if type(name_and_index[measure_name][0]) is int:
measure_index = int(measure_index)
flatten_measure_timeset[i] = all_info[measure_name][measure_index]
else:
flatten_measure_timeset[i] = all_info[i]
self.flatten_measure_timeset = flatten_measure_timeset
def __model_measure_name(self):
'''Return pyomo string name
'''
# store pyomo string name
measurement_names = []
# loop over measurement name
for mname in self.flatten_measure_name:
# check if there is extra index
if self.ind_string in mname:
measure_name = mname.split(self.ind_string)[0]
measure_index = mname.split(self.ind_string)[1]
for tim in self.flatten_measure_timeset[mname]:
# get the measurement name in the model
measurement_name = measure_name + '[0,' + measure_index + ',' + str(tim) + ']'
measurement_names.append(measurement_name)
else:
for tim in self.flatten_measure_timeset[mname]:
# get the measurement name in the model
measurement_name = mname + '[0,' + str(tim) + ']'
measurement_names.append(measurement_name)
self.model_measure_name = measurement_names
def SP_measure_name(self, j, t,scenario_all=None, p=None, mode=None, legal_t=True):
'''Return pyomo string name for different modes
Arguments
---------
j: flatten measurement name
t: time
scenario_all: all scenario object, only needed for simultaneous finite mode
p: parameter, only needed for simultaneous finite mode
mode: mode name, can be 'simultaneous_finite' or 'sequential_finite'
legal_t: if the time point is legal for this measurement. default is True
Return
------
up_C, lo_C: two measurement pyomo string names for simultaneous mode
legal_t: if the time point is legal for this measurement
string_name: one measurement pyomo string name for sequential
'''
if mode=='simultaneous_finite':
# check extra index
if self.ind_string in j:
measure_name = j.split(self.ind_string)[0]
measure_index = j.split(self.ind_string)[1]
if type(self.name_and_index[measure_name][0]) is str:
measure_index = '"' + measure_index + '"'
if t in self.flatten_measure_timeset[j]:
up_C = 'm.' + measure_name + '[' + str(scenario_all['jac-index'][p][0]) + ',' + measure_index + ',' + str(t) + ']'
lo_C = 'm.' + measure_name + '[' + str(scenario_all['jac-index'][p][1]) + ',' + measure_index + ',' + str(t) + ']'
else:
legal_t = False
else:
up_C = 'm.' + j + '[' + str(scenario_all['jac-index'][p][0]) + ',' + str(t) + ']'
lo_C = 'm.' + j + '[' + str(scenario_all['jac-index'][p][1]) + ',' + str(t) + ']'
return up_C, lo_C, legal_t
elif mode == 'sequential_finite':
if self.ind_string in j:
measure_name = j.split(self.ind_string)[0]
measure_index = j.split(self.ind_string)[1]
if type(self.name_and_index[measure_name][0]) is str:
measure_index = '"' + measure_index + '"'
if t in self.flatten_measure_timeset[j]:
string_name = 'mod.' + measure_name + '[0,' + str((measure_index)) + ',' + str(t) + ']'
else:
string_name = 'mod.' + j + '[0,' + str(t) + ']'
return string_name
def check_subset(self,subset, throw_error=True, valid_subset=True):
'''
Check if the subset is correctly defined with right name, index and time.
subset: measurement name and index involved in jacobian calculation
throw_error: if the given subset is not a subset of the measurement set, throw error message
'''
flatten_subset = subset.flatten_measure_name
flatten_timeset = subset.flatten_measure_timeset
# loop over subset measurement names
for i in flatten_subset:
# check if subset measurement names are in the overall measurement names
if i not in self.flatten_measure_name:
valid_subset = False
if throw_error:
raise ValueError('This is not a legal subset of the measurement overall set!')
else:
# check if subset measurement timepoints are in the overall measurement timepoints
for t in flatten_timeset[i]:
if t not in self.flatten_measure_timeset[i]:
valid_subset = False
if throw_error:
raise ValueError('The time of ', t, ' is not included as measurements before.')
return valid_subset
class DesignOfExperiments:
def __init__(self, param_init, design_variable_timepoints, measurement_object, create_model, solver=None,
prior_FIM=None, discretize_model=None, verbose=True, args=None):
'''
This package enables model-based design of experiments analysis with Pyomo. Both direct optimization and enumeration modes are supported.
NLP sensitivity tools, e.g., sipopt and k_aug, are supported to accelerate analysis via enumeration.
It can be applied to dynamic models, where design variables are controlled throughout the experiment.
Parameters:
-----------
param_init: a dictionary of parameter names and values. If they are an indexed variable, put the variable name and index, such as 'theta["A1"]'. Note: if sIPOPT is used, parameter shouldn't be indexed.
design_variable_timepoints: a dictionary, keys are design variable names, values are its control time points.
if this design var is independent of time (constant), set the time to [0]
measurement_object: the measurement object
create_model: a function that returns the model, where:
- parameter and design variables are defined as variables
- define every state variables dependent on parameters with a scenario index
- take scenarios as the first argument of this function
- define time index as 't'.
- design variables are defined with and only with a time index.
solver: User specified solver, default=None. If not specified, default solver is IPOPT MA57.
prior_FIM: Fisher information matrix (FIM) for prior experiments, default=None
discretize_model: A user-specified function that deiscretizes the model. Only use with Pyomo.DAE, default=None
verbose: if print statements are made
args: Other arguments of the create_model function, in a list
'''
# parameters
self.param_init = param_init
self.param_name = list(param_init.keys())
self.param_value = list(param_init.values())
# design variable name
self.design_timeset = design_variable_timepoints
self.design_name = list(self.design_timeset.keys())
# the control time point for each design variable
self.design_time = list(self.design_timeset.values())
# create_model()
self.create_model = create_model
self.args = args
# create the measurement information object
self.measure = measurement_object
self.flatten_measure_name = self.measure.flatten_measure_name
self.flatten_variance = self.measure.flatten_variance
self.flatten_measure_timeset = self.measure.flatten_measure_timeset
#print('The extra index:', self.measure.measurement_extra_index)
#print('The extra index name:', self.measure.extra_measure_name)
# check if user-defined solver is given
if solver is not None:
self.solver = solver
# if not given, use default solver
else:
self.solver = self.__get_default_ipopt_solver()
# check if discretization is needed
self.discretize_model = discretize_model
# check if there is prior info
self.prior_FIM = prior_FIM
# if print statements
self.verbose = verbose
def __check_inputs(self, check_mode=False):
'''Check if inputs are consistent
Parameters
----------
check_mode: check FIM calculation mode
'''
if self.objective_option not in ['det', 'trace', 'zero']:
raise ValueError('Error: Objective function should be chosen from "det", "zero" and "trace"')
if self.formula not in ['central', 'forward', 'backward', None]:
raise ValueError('Error: Finite difference scheme should be chosen from "central", "forward", "backward" and None.')
if self.prior_FIM is not None:
if not (np.shape(self.prior_FIM)[0] == np.shape(self.prior_FIM)[1]):
raise ValueError('Found wrong prior information matrix shape.')
if self.scale_nominal_param_value:
print('Sensitivity information is scaled by its corresponding parameter nominal value.')
if (self.scale_constant_value != 1):
print('Sensitivity information is scaled by constant ', self.scale_constant_value, ' times itself.')
if check_mode:
if self.mode not in ['simultaneous_finite', 'sequential_finite', 'sequential_sipopt', 'sequential_kaug', 'direct_kaug']:
raise ValueError('Wrong mode. Choose from "simultaneous_finite", "sequential_finite", "0sequential_sipopt", "sequential_kaug"')
def optimize_doe(self, design_values, if_optimize=True, objective_option='det',
jac_involved_measurement=None,
scale_nominal_param_value=False, scale_constant_value=1, optimize_opt=None, if_Cholesky=False, L_LB = 1E-10, L_initial=None,
jac_initial=None, fim_initial=None,
formula='central', step=0.001, check=True):
'''
Optimize DOE problem with design variables being the decisions.
The DOE model is formed invasively and all scenarios are computed simultaneously.
The function will first fun a square problem with design variable being fixed at
the given initial points, and then unfix the design variable and do the
optimization.
Parameters:
-----------
design_values: initial point for optimization, a dict whose keys are design variable names, values are a dict whose keys are time point and values are the design variable value at that time point
if_optimize: if true, continue to do optimization. else, just run square problem with given design variable values
objective_option: supporting maximizing the 'det' determinant or the 'trace' trace of the FIM
jac_involved_measurement: the measurement class involved in calculation. If None, take the overall measurement class
scale_nominal_param_value: if scale Jacobian by the corresponding parameter nominal value
scale_constant_value: how many order of magnitudes the Jacobian value is scaled by. Use when the Jac or FIM value is too small
optimize_opt: A dictionary, keys are design variables, values are True or False deciding if this design variable will be optimized as DOF or not
if_Cholesky: if true, cholesky decomposition is used for Objective function (to optimize determinant).
L_LB: if FIM is P.D., the diagonal element should be positive, so we can set a LB like 1E-10
L_initial: initialize the L
jac_initial: a matrix used to initialize jacobian matrix
fim_initial: a matrix used to initialize FIM matrix
formula: Finite difference formula, choose from 'central', 'forward', 'backward', None
step: Finite difference sensitivity perturbation step size, a fraction between [0,1]. default is 0.001
check: if True check input toggles consistency to be checked multiple times.
Returns:
--------
analysis_square: result summary of the square problem solved at the initial point
analysis_optimize: result summary of the optimization problem solved
Steps:
------
1. Build two-stage stochastic programming optimization model where scenarios correspond to
finite difference approximations for the Jacobian of the response variables with respect to calibrated model parameters
2. Fix the experiment design decisions and solve a square (i.e., zero degrees of freedom) instance of the two-stage DOE problem.
This step is for initialization.
3. Unfix the experiment design decisions and solve the two-stage DOE problem.
'''
time0 = time.time()
# store inputs in object
self.design_values = design_values
self.optimize = if_optimize
self.objective_option = objective_option
self.scale_nominal_param_value = scale_nominal_param_value
self.scale_constant_value = scale_constant_value
self.Cholesky_option = if_Cholesky
self.L_LB = L_LB
self.L_initial = L_initial
self.jac_initial = jac_initial
self.fim_initial = fim_initial
self.formula = formula
self.step = step
self.tee_opt = True
# calculate how much the FIM element is scaled by a constant number
# FIM = Jacobian.T@Jacobian, the FIM is scaled by squared value the Jacobian is scaled
self.fim_scale_constant_value = self.scale_constant_value **2
# identify measurements involved in calculation
if jac_involved_measurement is not None:
self.jac_involved_name = jac_involved_measurement.flatten_measure_name.copy()
self.timepoint_overall_set = jac_involved_measurement.timepoint_overall_set.copy()
else:
self.jac_involved_name = self.flatten_measure_name.copy()
self.timepoint_overall_set = self.measure.timepoint_overall_set.copy()
# check if inputs are valid
# simultaneous mode does not need to check mode and dimension of design variables
if check:
self.__check_inputs(check_mode=False)
# build the large DOE pyomo model
m = self.__create_doe_model()
# solve model, achieve results for square problem, and results for optimization problem
# Solve square problem first
# result_square: solver result
time0_solve = time.time()
result_square = self.__solve_doe(m, fix=True, opt_option=optimize_opt)
time1_solve = time.time()
time_solve1 = time1_solve-time0_solve
# extract Jac
jac_square = self.__extract_jac(m)
# create result object
analysis_square = FIM_result(self.param_name, self.measure, jacobian_info=None, all_jacobian_info=jac_square,
prior_FIM=self.prior_FIM, scale_constant_value=self.scale_constant_value)
# for simultaneous mode, FIM and Jacobian are extracted with extract_FIM()
analysis_square.calculate_FIM(self.design_timeset, result=result_square)
analysis_square.model = m
self.analysis_square = analysis_square
analysis_square.solve_time = time_solve1
if self.optimize:
# solve problem with DOF then
time0_solve2 = time.time()
result_doe = self.__solve_doe(m, fix=False)
time1_solve2 = time.time()
time_solve2 = time1_solve2 - time0_solve2
# extract Jac
jac_optimize = self.__extract_jac(m)
# create result object
analysis_optimize = FIM_result(self.param_name, self.measure, jacobian_info=None, all_jacobian_info=jac_optimize,
prior_FIM=self.prior_FIM)
# for simultaneous mode, FIM and Jacobian are extracted with extract_FIM()
analysis_optimize.calculate_FIM(self.design_timeset, result=result_doe)
analysis_optimize.model = m
time1 = time.time()
# record optimization time
analysis_optimize.solve_time = time_solve2
analysis_optimize.total_time = time1-time0
if self.verbose:
print('Total solve time with simultaneous_finite mode (Wall clock) [s]:', time_solve1 + time_solve2)
print('Total wall clock time [s]:', time1-time0)
return analysis_square, analysis_optimize
else:
analysis_square.model = m
time1 = time.time()
# record square problem time
analysis_square.total_time = time1-time0
if self.verbose:
print('Total solve time with simultaneous_finite mode (Wall clock) [s]:', time_solve1)
print('Total wall clock time [s]:', time1 - time0)
return analysis_square
def compute_FIM(self, design_values, mode='sequential_finite', FIM_store_name=None, specified_prior=None,
tee_opt=True, scale_nominal_param_value=False, scale_constant_value=1,
store_output = None, read_output=None, extract_single_model=None,
formula='central', step=0.001,
objective_option='det',
if_Cholesky=False, L_LB=1E-10, L_initial=None):
'''
This function solves a square Pyomo model with fixed design variables to compute the FIM.
The problem is structured in one of the four following modes:
1. simultaneous_finite: Calculate a multiple scenario model. Sensitivity info estimated by finite difference. This mode is accomplished by optimize_doe().
2. sequential_finite: Calculates a one scenario model multiple times for
multiple scenarios. Sensitivity info estimated by finite difference
3. sequential_sipopt: calculate sensitivity by sIPOPT.
4. sequential_kaug: calculate sensitivity by k_aug
5. direct_kaug: calculate sensitivity by k_aug with direct sensitivity. **In construction**
Parameters:
-----------
design_values: a dict whose keys are design variable names, values are a dict whose keys are time point and values are the design variable value at that time point
mode: use mode='sequential_finite', 'simultaneous_finite', 'sequential_sipopt', 'sequential_kaug'
FIM_store_name: if storing the FIM in a .csv, give the file name here as a string, '**.csv' or '**.txt'.
specified_prior: if user needs a different prior, replace this toggle without creating a new object
tee_opt: if IPOPT console output is printed
scale_nominal_param_value: if True, the parameters are scaled by its own nominal value in param_init
scale_constant_value: how many order of magnitudes the Jacobian value is scaled by. Use when the Jac or FIM value is too small
Only effective when finite=True:
formula: choose from 'central', 'forward', 'backward', None
step: Sensitivity perturbation step size, a fraction between [0,1]. default is 0.001
Cholesky option:
if_Cholesky: if true, Cholesky decomposition is used for Objective function (to optimize determinant).
L_LB: if FIM is positive definite, the diagonal element should be positive, so we can set a LB like 1E-10
L_initial: initialize the L
Return:
-------
FIM_analysis: result summary object of this solve
'''
# save inputs in object
self.design_values = design_values
self.mode = mode
self.scale_nominal_param_value = scale_nominal_param_value
self.scale_constant_value = scale_constant_value
self.formula = formula
self.step = step
# This method only solves square problem
self.optimize = False
# Set the Objective Function to 0 helps solve square problem quickly
self.objective_option = 'zero'
self.tee_opt = tee_opt
self.Cholesky_option = if_Cholesky
self.L_LB = L_LB
self.L_initial = L_initial
# calculate how much the FIM element is scaled by a constant number
# As FIM~Jacobian.T@Jacobian, FIM is scaled twice the number the Q is scaled
self.fim_scale_constant_value = self.scale_constant_value ** 2
# check inputs valid
self.__check_inputs(check_mode=True)
if self.mode=='sequential_finite':
time00 = time.time()
no_para = len(self.param_name)
# if using sequential model
# call generator function to get scenario dictionary
scena_gen = Scenario_generator(self.param_init, formula=self.formula, step=self.step)
scena_gen.generate_sequential_para()
# if measurements are provided
if read_output is not None:
with open(read_output, 'rb') as f:
output_record = pickle.load(f)
f.close()
jac = self.__finite_calculation(output_record, scena_gen)
# if measurements are not provided
else:
# dict for storing model outputs
output_record = {}
# dict for storing Jacobian
models = []
time_allbuild = []
time_allsolve = []
# loop over each scenario
for no_s in (scena_gen.scena_keys):
scenario_iter = scena_gen.next_sequential_scenario(no_s)
print('This scenario:', scenario_iter)
# create the model
# TODO:(long term) add options to create model once and then update. only try this after the
# package is completed and unitest is finished
time0_build = time.time()
mod = self.create_model(scenario_iter, args=self.args)
time1_build = time.time()
time_allbuild.append(time1_build-time0_build)
# discretize if needed
if self.discretize_model is not None:
mod = self.discretize_model(mod)
# extract (discretized) time
time_set = []
for t in mod.t:
time_set.append(value(t))
# solve model
time0_solve = time.time()
square_result = self.__solve_doe(mod, fix=True)
time1_solve = time.time()
time_allsolve.append(time1_solve-time0_solve)
models.append(mod)
if extract_single_model is not None:
mod_name = store_output + str(no_s) + '.csv'
dataframe = extract_single_model(mod, square_result)
dataframe.to_csv(mod_name)
# loop over measurement item and time to store model measurements
output_iter = []
for j in self.flatten_measure_name:
for t in self.flatten_measure_timeset[j]:
measure_string_name = self.measure.SP_measure_name(j,t,mode='sequential_finite')
C_value = value(eval(measure_string_name))
output_iter.append(C_value)
output_record[no_s] = output_iter
print('Output this time: ', output_record[no_s])
output_record['design'] = design_values
if store_output is not None:
f = open(store_output, 'wb')
pickle.dump(output_record, f)
f.close()
# calculate jacobian
jac = self.__finite_calculation(output_record, scena_gen)
time11 = time.time()
if self.verbose:
print('Build time with sequential_finite mode [s]:', sum(time_allbuild))
print('Solve time with sequential_finite mode [s]:', sum(time_allsolve))
print('Total wall clock time [s]:', time11-time00)
# return all models formed
self.models = models
# Assemble and analyze results
if specified_prior is None:
prior_in_use = self.prior_FIM
else:
prior_in_use = specified_prior
#jacobian_split = Jac_splitter(self.param_name, self.measure, jaco_information=jac, prior_FIM=prior_in_use,
# scale_constant_value=self.scale_constant_value)
FIM_analysis = FIM_result(self.param_name, self.measure, jacobian_info=None, all_jacobian_info=jac,
prior_FIM=prior_in_use, store_FIM=FIM_store_name, scale_constant_value=self.scale_constant_value)
# Store the Jacobian information for access by users
self.jac = jac
if read_output is None:
FIM_analysis.build_time = sum(time_allbuild)
FIM_analysis.solve_time = sum(time_allsolve)
return FIM_analysis
elif self.mode in ['sequential_sipopt', 'sequential_kaug']:
time00 = time.time()
# create scenario class for a base case
scena_gen = Scenario_generator(self.param_init, formula=None, step=self.step)
scenario_all = scena_gen.simultaneous_scenario()
# sipopt only uses backward difference scheme
# store measurements for scenarios
all_perturb_measure = []
all_base_measure = []
# store jacobian info
jac={}
# if measurements are provided
# TODO: update this read_output toggle
if read_output is not None:
with open(read_output, 'rb') as f:
output_record = pickle.load(f)
f.close()
jac = self.__finite_calculation(output_record, scena_gen)
else:
# time building time and solving time store list
time_allbuild = []
time_allsolve = []
# loop over parameters
for pa in range(len(self.param_name)):
perturb_mea = []
base_mea = []
# create model
time0_build = time.time()
mod = self.create_model(scenario_all, self.args)
time1_build = time.time()
time_allbuild.append(time1_build - time0_build)
# discretize if needed
if self.discretize_model is not None:
mod = self.discretize_model(mod)
# For sIPOPT, fix model DOF
if self.mode =='sequential_sipopt':
mod = self.__fix_design(mod, self.design_values, fix_opt=True)
# extract (discretized) time
time_set = []
for t in mod.t:
time_set.append(value(t))
# add sIPOPT perturbation parameters
mod = self.__add_parameter(mod, perturb=pa)
# solve the square problem with the original parameters for k_aug mode, since k_aug does not calculate these
if self.mode == 'sequential_kaug':
self.__solve_doe(mod, fix=True)
# parameter name lists for sipopt
list_original = []
list_perturb = []
for ele in self.param_name:
list_original.append(eval('mod.'+ele+'[0]'))
for elem in self.perturb_names:
list_perturb.append(eval('mod.'+elem+'[0]'))
# solve model
if self.mode =='sequential_sipopt':
time0_solve = time.time()
m_sipopt = sensitivity_calculation('sipopt', mod, list_original, list_perturb, tee=self.tee_opt, solver_options='ma57')
else:
time0_solve = time.time()
m_sipopt = sensitivity_calculation('k_aug', mod, list_original, list_perturb, tee=self.tee_opt, solver_options='ma57')
time1_solve = time.time()
time_allsolve.append(time1_solve - time0_solve)
# extract sipopt result
for j in self.flatten_measure_name:
# check if this variable needs split name
if self.measure.ind_string in j:
measure_name = j.split(self.measure.ind_string)[0]
measure_index = j.split(self.measure.ind_string)[1]
# this is needed for using eval(). if the extra index is 'CA', it converts to "'CA'". only for the extra index as a string
if type(measure_index) is str:
measure_index_doublequotes = '"' + measure_index + '"'
for t in self.flatten_measure_timeset[j]:
measure_var = getattr(m_sipopt, measure_name)
# check if this variable is fixed
if (measure_var[0,measure_index,t].fixed == True):
perturb_value = value(measure_var[0,measure_index,t])
else:
# if it is not fixed, record its perturbed value
if self.mode =='sequential_sipopt':
perturb_value = eval('m_sipopt.sens_sol_state_1[m_sipopt.' + measure_name + '[0,'+str(measure_index_doublequotes)+',' + str(t) + ']]')
else:
perturb_value = eval('m_sipopt.' + measure_name + '[0,' +str(measure_index_doublequotes)+',' + str(t) + ']()')
# base case values
if self.mode == 'sequential_sipopt':
base_value = eval('m_sipopt.' + measure_name + '[0,'+str(measure_index_doublequotes)+',' + str(t) + '].value')
else:
base_value = value(eval('mod.' + measure_name + '[0,' +str(measure_index_doublequotes)+','+ str(t) + ']'))
perturb_mea.append(perturb_value)
base_mea.append(base_value)
else:
# fetch the measurement variable
measure_var = getattr(m_sipopt, j)
for t in self.flatten_measure_timeset[j]:
if (measure_var[0,t].fixed == True):
perturb_value = value(measure_var[0, t])
else:
# if it is not fixed, record its perturbed value
if self.mode == 'sequential_sipopt':
perturb_value = eval('m_sipopt.sens_sol_state_1[m_sipopt.' + j + '[0,' + str(t) + ']]')
else:
perturb_value = eval('m_sipopt.' + j + '[0,' + str(t) + ']()')
# base case values
if self.mode == 'sequential_sipopt':
base_value = eval('m_sipopt.' + j + '[0,'+ str(t) + '].value')
else:
base_value = value(eval('mod.' + j + '[0,'+ str(t) + ']'))
perturb_mea.append(perturb_value)
base_mea.append(base_value)
# store extracted measurements
all_perturb_measure.append(perturb_mea)
all_base_measure.append(base_mea)
print(all_perturb_measure)
print(all_base_measure)
# After collecting outputs from all scenarios, calculate sensitivity
for count, para in enumerate(self.param_name):
list_jac = []
for i in range(len(all_perturb_measure[0])):
if self.scale_nominal_param_value:
sensi = -(all_perturb_measure[count][i] - all_base_measure[count][i]) / self.step * self.scale_constant_value
else:
sensi = -(all_perturb_measure[count][i] - all_base_measure[count][i]) / self.step /self.param_init[para] * self.scale_constant_value
list_jac.append(sensi)
# get Jacobian dict, keys are parameter name, values are sensitivity info
jac[para] = list_jac
# check if another prior experiment FIM is provided other than the user-specified one
if specified_prior is None:
prior_in_use = self.prior_FIM
else:
prior_in_use = specified_prior
# Assemble and analyze results
FIM_analysis = FIM_result(self.param_name, self.measure, jacobian_info=None, all_jacobian_info=jac,
prior_FIM=prior_in_use, store_FIM=FIM_store_name, scale_constant_value=self.scale_constant_value)
time11 = time.time()
if self.verbose:
print('Build time with sequential_sipopt or kaug mode [s]:', sum(time_allbuild))
print('Solve time with sequential_sipopt or kaug mode [s]:', sum(time_allsolve))
print('Total wall clock time [s]:', time11-time00)
self.jac = jac
FIM_analysis.build_time = sum(time_allbuild)
FIM_analysis.solve_time = sum(time_allsolve)
return FIM_analysis
elif self.mode =='direct_kaug':
time00 = time.time()
# create scenario class for a base case
scena_gen = Scenario_generator(self.param_init, formula=None, step=self.step)
scenario_all = scena_gen.simultaneous_scenario()
# create model
time0_build = time.time()
mod = self.create_model(scenario_all, args=self.args)
time1_build = time.time()
time_build = time1_build - time0_build
# discretize if needed
if self.discretize_model is not None:
mod = self.discretize_model(mod)
# get all time
t_all = []
for t in mod.t:
t_all.append(t)
# Check if measurement time points are in this time set
# Also correct the measurement time points
# For e.g. if a measurement time point is 0.0 in the model but is given as 0, it is corrected here
measurement_accurate_time = self.flatten_measure_timeset.copy()
for j in self.flatten_measure_name:
for no_t, tt in enumerate(self.flatten_measure_timeset[j]):
if tt not in t_all:
print('A measurement time point not measured by this model: ', tt)
else:
measurement_accurate_time[j][no_t] = t_all[t_all.index(tt)]
print('After practice:', measurement_accurate_time)
# fix model DOF
#mod = self.__fix_design(mod, self.design_values, fix_opt=True)
# set ub and lb to parameters
for par in self.param_name:
component = eval('mod.'+par+'[0]')
component.setlb(self.param_init[par])
component.setub(self.param_init[par])
# generate parameter name list and value dictionary with index
var_name = []
var_dict = {}
for name in self.param_name:
var_name.append(name+'[0]')
var_dict[name+'[0]'] = self.param_init[name]
# call k_aug get_dsdp function
time0_solve = time.time()
square_result = self.__solve_doe(mod, fix=True)
dsdp_re, col = get_dsdp(mod, var_name, var_dict, tee=self.tee_opt)
time1_solve = time.time()
time_solve = time1_solve - time0_solve
# analyze result
dsdp_array = dsdp_re.toarray().T
# here for construction. Remove after finishing.
#dd = pd.DataFrame(dsdp_array)
#print(dd)
#dd.to_csv('test_kaug.csv')
# here for fixed bed
self.dsdp = dsdp_array
self.dsdp = col
# store dsdp returned
dsdp_extract = []
# get right lines from results
measurement_index = []
measurement_names = []
# produce the sensitivity for fixed variables
zero_sens = np.zeros(len(self.param_name))
# loop over measurement variables and their time points
for measurement_name in self.measure.model_measure_name:
# get right line number in kaug results
if self.discretize_model is not None:
# for DAE model, some variables are fixed
try:
kaug_no = col.index(measurement_name)
measurement_index.append(kaug_no)
# get right line of dsdp
dsdp_extract.append(dsdp_array[kaug_no])
except:
if self.verbose:
print('The variable is fixed:', measurement_name)
# for fixed variables, the sensitivity are a zero vector
dsdp_extract.append(zero_sens)
else:
kaug_no = col.index(measurement_name)
measurement_index.append(kaug_no)
# get right line of dsdp
dsdp_extract.append(dsdp_array[kaug_no])
print('dsdp extract is:', dsdp_extract)
# Extract and calculate sensitivity if scaled by constants or parameters.
# Convert sensitivity to a dictionary
jac = {}
for par in self.param_name:
jac[par] = []
for d in range(len(dsdp_extract)):
for p, par in enumerate(self.param_name):
# if scaled by parameter value or constant value
if self.scale_nominal_param_value:
jac[par].append(self.param_init[par]*dsdp_extract[d][p]*self.scale_constant_value)
else:
jac[par].append(dsdp_extract[d][p]*self.scale_constant_value)
time11 = time.time()
if self.verbose:
print('Build time with direct kaug mode [s]:', time_build)
print('Solve time with direct kaug mode [s]:', time_solve)
print('Total wall clock time [s]:', time11-time00)
# check if another prior experiment FIM is provided other than the user-specified one
if specified_prior is None:
prior_in_use = self.prior_FIM
else:
prior_in_use = specified_prior
# Assemble and analyze results
FIM_analysis = FIM_result(self.param_name,self.measure, jacobian_info=None, all_jacobian_info=jac,
prior_FIM=prior_in_use, store_FIM=FIM_store_name,
scale_constant_value=self.scale_constant_value)
self.jac = jac
FIM_analysis.build_time = time_build
FIM_analysis.solve_time = time_solve