-
Notifications
You must be signed in to change notification settings - Fork 586
Expand file tree
/
Copy pathparmest.py
More file actions
2700 lines (2307 loc) · 103 KB
/
Copy pathparmest.py
File metadata and controls
2700 lines (2307 loc) · 103 KB
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
# ___________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2025
# National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and
# Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
# rights in this software.
# This software is distributed under the 3-clause BSD License.
# ___________________________________________________________________________
#### Using mpi-sppy instead of PySP; May 2020
#### Adding option for "local" EF starting Sept 2020
#### Wrapping mpi-sppy functionality and local option Jan 2021, Feb 2021
#### Redesign with Experiment class Dec 2023
# TODO: move use_mpisppy to a Pyomo configuration option
# False implies always use the EF that is local to parmest
use_mpisppy = True # Use it if we can but use local if not.
if use_mpisppy:
try:
# MPI-SPPY has an unfortunate side effect of outputting
# "[ 0.00] Initializing mpi-sppy" when it is imported. This can
# cause things like doctests to fail. We will suppress that
# information here.
from pyomo.common.tee import capture_output
with capture_output():
import mpisppy.utils.sputils as sputils
except ImportError:
use_mpisppy = False # we can't use it
if use_mpisppy:
# These things should be outside the try block.
sputils.disable_tictoc_output()
import mpisppy.opt.ef as st
import mpisppy.scenario_tree as scenario_tree
else:
import pyomo.contrib.parmest.utils.create_ef as local_ef
import pyomo.contrib.parmest.utils.scenario_tree as scenario_tree
import re
import importlib as im
import logging
import types
import json
from collections.abc import Callable
from itertools import combinations
from functools import singledispatchmethod
from pyomo.common.dependencies import (
attempt_import,
numpy as np,
numpy_available,
pandas as pd,
pandas_available,
scipy,
scipy_available,
)
import pyomo.environ as pyo
from pyomo.opt import SolverFactory
from pyomo.environ import Block, ComponentUID
import pyomo.contrib.parmest.utils as utils
import pyomo.contrib.parmest.graphics as graphics
from pyomo.dae import ContinuousSet
from pyomo.common.deprecation import deprecated
from pyomo.common.deprecation import deprecation_warning
parmest_available = numpy_available & pandas_available & scipy_available
inverse_reduced_hessian, inverse_reduced_hessian_available = attempt_import(
'pyomo.contrib.interior_point.inverse_reduced_hessian'
)
logger = logging.getLogger(__name__)
def ef_nonants(ef):
# Wrapper to call someone's ef_nonants
# (the function being called is very short, but it might be changed)
if use_mpisppy:
return sputils.ef_nonants(ef)
else:
return local_ef.ef_nonants(ef)
def _experiment_instance_creation_callback(
scenario_name, node_names=None, cb_data=None
):
"""
This is going to be called by mpi-sppy or the local EF and it will call into
the user's model's callback.
Parameters:
-----------
scenario_name: `str` Scenario name should end with a number
node_names: `None` ( Not used here )
cb_data : dict with ["callback"], ["BootList"],
["theta_names"], ["cb_data"], etc.
"cb_data" is passed through to user's callback function
that is the "callback" value.
"BootList" is None or bootstrap experiment number list.
(called cb_data by mpisppy)
Returns:
--------
instance: `ConcreteModel`
instantiated scenario
Note:
----
There is flexibility both in how the function is passed and its signature.
"""
assert cb_data is not None
outer_cb_data = cb_data
scen_num_str = re.compile(r'(\d+)$').search(scenario_name).group(1)
scen_num = int(scen_num_str)
basename = scenario_name[: -len(scen_num_str)] # to reconstruct name
CallbackFunction = outer_cb_data["callback"]
if callable(CallbackFunction):
callback = CallbackFunction
else:
cb_name = CallbackFunction
if "CallbackModule" not in outer_cb_data:
raise RuntimeError(
"Internal Error: need CallbackModule in parmest callback"
)
else:
modname = outer_cb_data["CallbackModule"]
if isinstance(modname, str):
cb_module = im.import_module(modname, package=None)
elif isinstance(modname, types.ModuleType):
cb_module = modname
else:
print("Internal Error: bad CallbackModule")
raise
try:
callback = getattr(cb_module, cb_name)
except:
print("Error getting function=" + cb_name + " from module=" + str(modname))
raise
if "BootList" in outer_cb_data:
bootlist = outer_cb_data["BootList"]
# print("debug in callback: using bootlist=",str(bootlist))
# assuming bootlist itself is zero based
exp_num = bootlist[scen_num]
else:
exp_num = scen_num
scen_name = basename + str(exp_num)
cb_data = outer_cb_data["cb_data"] # cb_data might be None.
# at least three signatures are supported. The first is preferred
try:
instance = callback(experiment_number=exp_num, cb_data=cb_data)
except TypeError:
raise RuntimeError(
"Only one callback signature is supported: "
"callback(experiment_number, cb_data) "
)
"""
try:
instance = callback(scenario_tree_model, scen_name, node_names)
except TypeError: # deprecated signature?
try:
instance = callback(scen_name, node_names)
except:
print("Failed to create instance using callback; TypeError+")
raise
except:
print("Failed to create instance using callback.")
raise
"""
if hasattr(instance, "_mpisppy_node_list"):
raise RuntimeError(f"scenario for experiment {exp_num} has _mpisppy_node_list")
nonant_list = [
instance.find_component(vstr) for vstr in outer_cb_data["theta_names"]
]
if use_mpisppy:
instance._mpisppy_node_list = [
scenario_tree.ScenarioNode(
name="ROOT",
cond_prob=1.0,
stage=1,
cost_expression=instance.FirstStageCost,
nonant_list=nonant_list,
scen_model=instance,
)
]
else:
instance._mpisppy_node_list = [
scenario_tree.ScenarioNode(
name="ROOT",
cond_prob=1.0,
stage=1,
cost_expression=instance.FirstStageCost,
scen_name_list=None,
nonant_list=nonant_list,
scen_model=instance,
)
]
if "ThetaVals" in outer_cb_data:
thetavals = outer_cb_data["ThetaVals"]
# dlw august 2018: see mea code for more general theta
for name, val in thetavals.items():
theta_cuid = ComponentUID(name)
theta_object = theta_cuid.find_component_on(instance)
if val is not None:
# print("Fixing",vstr,"at",str(thetavals[vstr]))
theta_object.fix(val)
else:
# print("Freeing",vstr)
theta_object.unfix()
return instance
def SSE(model):
"""
Sum of squared error between `experiment_output` model and data values
"""
expr = sum((y - y_hat) ** 2 for y, y_hat in model.experiment_outputs.items())
return expr
'''Adding pseudocode for draft implementation of the estimator class,
incorporating multistart.
'''
class Estimator(object):
"""
Parameter estimation class
Parameters
----------
experiment_list: list of Experiments
A list of experiment objects which creates one labeled model for
each experiment
obj_function: string or function (optional)
Built in objective (currently only "SSE") or custom function used to
formulate parameter estimation objective.
If no function is specified, the model is used
"as is" and should be defined with a "FirstStageCost" and
"SecondStageCost" expression that are used to build an objective.
Default is None.
tee: bool, optional
If True, print the solver output to the screen. Default is False.
diagnostic_mode: bool, optional
If True, print diagnostics from the solver. Default is False.
solver_options: dict, optional
Provides options to the solver (also the name of an attribute).
Default is None.
"""
# The singledispatchmethod decorator is used here as a deprecation
# shim to be able to support the now deprecated Estimator interface
# which had a different number of arguments. When the deprecated API
# is removed this decorator and the _deprecated_init method below
# can be removed
@singledispatchmethod
def __init__(
self,
experiment_list,
obj_function=None,
tee=False,
diagnostic_mode=False,
solver_options=None,
# Add the extra arguments needed for running the multistart implement
# _validate_multistart_args:
# if n_restarts > 1 and theta_samplig_method is not None:
n_restarts=20,
multistart_sampling_method="random",
):
'''first theta would be provided by the user in the initialization of
the Estimator class through the unknown parameter variables. Additional
would need to be generated using the sampling method provided by the user.
'''
# check that we have a (non-empty) list of experiments
assert isinstance(experiment_list, list)
self.exp_list = experiment_list
# check that an experiment has experiment_outputs and unknown_parameters
model = self.exp_list[0].get_labeled_model()
try:
outputs = [k.name for k, v in model.experiment_outputs.items()]
except:
RuntimeError(
'Experiment list model does not have suffix ' + '"experiment_outputs".'
)
try:
params = [k.name for k, v in model.unknown_parameters.items()]
except:
RuntimeError(
'Experiment list model does not have suffix ' + '"unknown_parameters".'
)
# populate keyword argument options
self.obj_function = obj_function
self.tee = tee
self.diagnostic_mode = diagnostic_mode
self.solver_options = solver_options
# add the extra multistart arguments to the Estimator class
self.n_restarts = n_restarts
self.multistart_sampling_method = multistart_sampling_method
# TODO: delete this when the deprecated interface is removed
self.pest_deprecated = None
# TODO This might not be needed here.
# We could collect the union (or intersect?) of thetas when the models are built
theta_names = []
for experiment in self.exp_list:
model = experiment.get_labeled_model()
theta_names.extend([k.name for k, v in model.unknown_parameters.items()])
# Utilize list(dict.fromkeys(theta_names)) to preserve parameter
# order compared with list(set(theta_names)), which had
# nondeterministic ordering of parameters
self.estimator_theta_names = list(dict.fromkeys(theta_names))
self._second_stage_cost_exp = "SecondStageCost"
# boolean to indicate if model is initialized using a square solve
self.model_initialized = False
# The deprecated Estimator constructor
# This works by checking the type of the first argument passed to
# the class constructor. If it matches the old interface (i.e. is
# callable) then this _deprecated_init method is called and the
# deprecation warning is displayed.
@__init__.register(Callable)
def _deprecated_init(
self,
model_function,
data,
theta_names,
obj_function=None,
tee=False,
diagnostic_mode=False,
solver_options=None,
):
deprecation_warning(
"You're using the deprecated parmest interface (model_function, "
"data, theta_names). This interface will be removed in a future release, "
"please update to the new parmest interface using experiment lists.",
version='6.7.2',
)
self.pest_deprecated = _DeprecatedEstimator(
model_function,
data,
theta_names,
obj_function,
tee,
diagnostic_mode,
solver_options,
)
def _return_theta_names(self):
"""
Return list of fitted model parameter names
"""
# check for deprecated inputs
if self.pest_deprecated:
# if fitted model parameter names differ from theta_names
# created when Estimator object is created
if hasattr(self, 'theta_names_updated'):
return self.pest_deprecated.theta_names_updated
else:
# default theta_names, created when Estimator object is created
return self.pest_deprecated.theta_names
else:
# if fitted model parameter names differ from theta_names
# created when Estimator object is created
if hasattr(self, 'theta_names_updated'):
return self.theta_names_updated
else:
# default theta_names, created when Estimator object is created
return self.estimator_theta_names
def _expand_indexed_unknowns(self, model_temp):
"""
Expand indexed variables to get full list of thetas
"""
model_theta_list = []
for c in model_temp.unknown_parameters.keys():
if c.is_indexed():
for _, ci in c.items():
model_theta_list.append(ci.name)
else:
model_theta_list.append(c.name)
return model_theta_list
def _create_parmest_model(self, experiment_number):
"""
Modify the Pyomo model for parameter estimation
"""
model = self.exp_list[experiment_number].get_labeled_model()
if len(model.unknown_parameters) == 0:
model.parmest_dummy_var = pyo.Var(initialize=1.0)
# Add objective function (optional)
if self.obj_function:
# Check for component naming conflicts
reserved_names = [
'Total_Cost_Objective',
'FirstStageCost',
'SecondStageCost',
]
for n in reserved_names:
if model.component(n) or hasattr(model, n):
raise RuntimeError(
f"Parmest will not override the existing model component named {n}"
)
# Deactivate any existing objective functions
for obj in model.component_objects(pyo.Objective):
obj.deactivate()
# TODO, this needs to be turned into an enum class of options that still support
# custom functions
if self.obj_function == 'SSE':
second_stage_rule = SSE
else:
# A custom function uses model.experiment_outputs as data
second_stage_rule = self.obj_function
model.FirstStageCost = pyo.Expression(expr=0)
model.SecondStageCost = pyo.Expression(rule=second_stage_rule)
def TotalCost_rule(model):
return model.FirstStageCost + model.SecondStageCost
model.Total_Cost_Objective = pyo.Objective(
rule=TotalCost_rule, sense=pyo.minimize
)
# Convert theta Params to Vars, and unfix theta Vars
theta_names = [k.name for k, v in model.unknown_parameters.items()]
parmest_model = utils.convert_params_to_vars(model, theta_names, fix_vars=False)
return parmest_model
# Make new private method, _generate_initial_theta:
# This method will be used to generate the initial theta values for multistart
# optimization. It will take the theta names and the initial theta values
# and return a dictionary of theta names and their corresponding values.
def _generate_initial_theta(self, parmest_model, seed=None):
if self.n_restarts == 1:
# If only one restart, return an empty list
return print("No multistart optimization needed. Please use normal theta_est()")
# Get the theta names and initial theta values
theta_names = self._return_theta_names()
initial_theta = [parmest_model.find_component(name)() for name in theta_names]
# Get the lower and upper bounds for the theta values
lower_bound = np.array([parmest_model.find_component(name).lb for name in theta_names])
upper_bound = np.array([parmest_model.find_component(name).ub for name in theta_names])
# Check if the lower and upper bounds are defined
if np.any(np.isnan(lower_bound)) or np.any(np.isnan(upper_bound)):
raise ValueError(
"The lower and upper bounds for the theta values must be defined."
)
# Check the length of theta_names and initial_theta, and make sure bounds are defined
if len(theta_names) != len(initial_theta):
raise ValueError(
"The length of theta_names and initial_theta must be the same."
)
if self.method == "random":
np.random.seed(seed)
# Generate random theta values
theta_vals_multistart = np.random.uniform(lower_bound, upper_bound, size=len(theta_names))
# Generate theta values using Latin hypercube sampling or Sobol sampling
return theta_vals_multistart
elif self.method == "latin_hypercube":
# Generate theta values using Latin hypercube sampling
sampler = scipy.stats.qmc.LatinHypercube(d=len(theta_names), seed=seed)
samples = sampler.random(n=self.n_restarts+1)[1:] # Skip the first sample
theta_vals_multistart = np.array([lower_bound + (upper_bound - lower_bound) * theta for theta in samples])
elif self.method == "sobol":
sampler = scipy.stats.qmc.Sobol(d=len(theta_names), seed=seed)
samples = sampler.random(n=self.n_restarts+1)[1:]
theta_vals_multistart = np.array([lower_bound + (upper_bound - lower_bound) * theta for theta in samples])
# elif self.method == "prior":
# # Still working on this
# theta_vals_multistart = np.array([lower_bound + (upper_bound - lower_bound) * theta for theta in initial_theta])
else:
raise ValueError(
"Invalid sampling method. Choose 'random', 'latin_hypercube', 'sobol'." # or 'prior'."
)
# Make an output dataframe with the theta names and their corresponding values for each restart,
# and nan for the output info values
df_multistart = pd.DataFrame(
theta_vals_multistart, columns=theta_names
)
df_multistart["initial objective"] = np.nan
df_multistart["final objective"] = np.nan
df_multistart["solver termination"] = np.nan
df_multistart["solve_time"] = np.nan
# Add the initial theta values to the first row of the dataframe
for i in self.n_restarts:
df_multistart.iloc[i, :] = theta_vals_multistart[i, :]
df_multistart.iloc[0, :] = initial_theta
# # Add the initial objective value to the first row of the dataframe
# df_multistart.iloc[0, -1] = self._Q_at_theta(initial_theta, initialize_parmest_model=True)[0]
# # Add the final objective value to the first row of the dataframe
# df_multistart.iloc[0, -2] = self._Q_at_theta(initial_theta, initialize_parmest_model=True)[0]
# # Add the solver termination value to the first row of the dataframe
# df_multistart.iloc[0, -3] = self._Q_at_theta(initial_theta, initialize_parmest_model=True)[2]
# # Add the solve time to the first row of the dataframe
# df_multistart.iloc[0, -4] = self._Q_at_theta(initial_theta, initialize_parmest_model=True)[3]
return theta_vals_multistart, df_multistart
def _instance_creation_callback(self, experiment_number=None, cb_data=None):
model = self._create_parmest_model(experiment_number)
return model
def _Q_opt(
self,
ThetaVals=None,
solver="ef_ipopt",
return_values=[],
bootlist=None,
calc_cov=False,
cov_n=None,
):
"""
Set up all thetas as first stage Vars, return resulting theta
values as well as the objective function value.
"""
if solver == "k_aug":
raise RuntimeError("k_aug no longer supported.")
# (Bootstrap scenarios will use indirection through the bootlist)
if bootlist is None:
scenario_numbers = list(range(len(self.exp_list)))
scen_names = ["Scenario{}".format(i) for i in scenario_numbers]
else:
scen_names = ["Scenario{}".format(i) for i in range(len(bootlist))]
# tree_model.CallbackModule = None
outer_cb_data = dict()
outer_cb_data["callback"] = self._instance_creation_callback
if ThetaVals is not None:
outer_cb_data["ThetaVals"] = ThetaVals
if bootlist is not None:
outer_cb_data["BootList"] = bootlist
outer_cb_data["cb_data"] = None # None is OK
outer_cb_data["theta_names"] = self.estimator_theta_names
options = {"solver": "ipopt"}
scenario_creator_options = {"cb_data": outer_cb_data}
if use_mpisppy:
ef = sputils.create_EF(
scen_names,
_experiment_instance_creation_callback,
EF_name="_Q_opt",
suppress_warnings=True,
scenario_creator_kwargs=scenario_creator_options,
)
else:
ef = local_ef.create_EF(
scen_names,
_experiment_instance_creation_callback,
EF_name="_Q_opt",
suppress_warnings=True,
scenario_creator_kwargs=scenario_creator_options,
)
self.ef_instance = ef
# Solve the extensive form with ipopt
if solver == "ef_ipopt":
if not calc_cov:
# Do not calculate the reduced hessian
solver = SolverFactory('ipopt')
if self.solver_options is not None:
for key in self.solver_options:
solver.options[key] = self.solver_options[key]
solve_result = solver.solve(self.ef_instance, tee=self.tee)
# The import error will be raised when we attempt to use
# inv_reduced_hessian_barrier below.
#
# elif not asl_available:
# raise ImportError("parmest requires ASL to calculate the "
# "covariance matrix with solver 'ipopt'")
else:
# parmest makes the fitted parameters stage 1 variables
ind_vars = []
for ndname, Var, solval in ef_nonants(ef):
ind_vars.append(Var)
# calculate the reduced hessian
(solve_result, inv_red_hes) = (
inverse_reduced_hessian.inv_reduced_hessian_barrier(
self.ef_instance,
independent_variables=ind_vars,
solver_options=self.solver_options,
tee=self.tee,
)
)
if self.diagnostic_mode:
print(
' Solver termination condition = ',
str(solve_result.solver.termination_condition),
)
# assume all first stage are thetas...
thetavals = {}
for ndname, Var, solval in ef_nonants(ef):
# process the name
# the scenarios are blocks, so strip the scenario name
vname = Var.name[Var.name.find(".") + 1 :]
thetavals[vname] = solval
objval = pyo.value(ef.EF_Obj)
if calc_cov:
# Calculate the covariance matrix
# Number of data points considered
n = cov_n
# Extract number of fitted parameters
l = len(thetavals)
# Assumption: Objective value is sum of squared errors
sse = objval
'''Calculate covariance assuming experimental observation errors are
independent and follow a Gaussian
distribution with constant variance.
The formula used in parmest was verified against equations (7-5-15) and
(7-5-16) in "Nonlinear Parameter Estimation", Y. Bard, 1974.
This formula is also applicable if the objective is scaled by a constant;
the constant cancels out. (was scaled by 1/n because it computes an
expected value.)
'''
cov = 2 * sse / (n - l) * inv_red_hes
cov = pd.DataFrame(
cov, index=thetavals.keys(), columns=thetavals.keys()
)
thetavals = pd.Series(thetavals)
if len(return_values) > 0:
var_values = []
if len(scen_names) > 1: # multiple scenarios
block_objects = self.ef_instance.component_objects(
Block, descend_into=False
)
else: # single scenario
block_objects = [self.ef_instance]
for exp_i in block_objects:
vals = {}
for var in return_values:
exp_i_var = exp_i.find_component(str(var))
if (
exp_i_var is None
): # we might have a block such as _mpisppy_data
continue
# if value to return is ContinuousSet
if type(exp_i_var) == ContinuousSet:
temp = list(exp_i_var)
else:
temp = [pyo.value(_) for _ in exp_i_var.values()]
if len(temp) == 1:
vals[var] = temp[0]
else:
vals[var] = temp
if len(vals) > 0:
var_values.append(vals)
var_values = pd.DataFrame(var_values)
if calc_cov:
return objval, thetavals, var_values, cov
else:
return objval, thetavals, var_values
if calc_cov:
return objval, thetavals, cov
else:
return objval, thetavals
else:
raise RuntimeError("Unknown solver in Q_Opt=" + solver)
def _Q_at_theta(self, thetavals, initialize_parmest_model=False):
"""
Return the objective function value with fixed theta values.
Parameters
----------
thetavals: dict
A dictionary of theta values.
initialize_parmest_model: boolean
If True: Solve square problem instance, build extensive form of the model for
parameter estimation, and set flag model_initialized to True. Default is False.
Returns
-------
objectiveval: float
The objective function value.
thetavals: dict
A dictionary of all values for theta that were input.
solvertermination: Pyomo TerminationCondition
Tries to return the "worst" solver status across the scenarios.
pyo.TerminationCondition.optimal is the best and
pyo.TerminationCondition.infeasible is the worst.
"""
optimizer = pyo.SolverFactory('ipopt')
if len(thetavals) > 0:
dummy_cb = {
"callback": self._instance_creation_callback,
"ThetaVals": thetavals,
"theta_names": self._return_theta_names(),
"cb_data": None,
}
else:
dummy_cb = {
"callback": self._instance_creation_callback,
"theta_names": self._return_theta_names(),
"cb_data": None,
}
if self.diagnostic_mode:
if len(thetavals) > 0:
print(' Compute objective at theta = ', str(thetavals))
else:
print(' Compute objective at initial theta')
# start block of code to deal with models with no constraints
# (ipopt will crash or complain on such problems without special care)
instance = _experiment_instance_creation_callback("FOO0", None, dummy_cb)
try: # deal with special problems so Ipopt will not crash
first = next(instance.component_objects(pyo.Constraint, active=True))
active_constraints = True
except:
active_constraints = False
# end block of code to deal with models with no constraints
WorstStatus = pyo.TerminationCondition.optimal
totobj = 0
scenario_numbers = list(range(len(self.exp_list)))
if initialize_parmest_model:
# create dictionary to store pyomo model instances (scenarios)
scen_dict = dict()
for snum in scenario_numbers:
sname = "scenario_NODE" + str(snum)
instance = _experiment_instance_creation_callback(sname, None, dummy_cb)
model_theta_names = self._expand_indexed_unknowns(instance)
if initialize_parmest_model:
# list to store fitted parameter names that will be unfixed
# after initialization
theta_init_vals = []
# use appropriate theta_names member
theta_ref = model_theta_names
for i, theta in enumerate(theta_ref):
# Use parser in ComponentUID to locate the component
var_cuid = ComponentUID(theta)
var_validate = var_cuid.find_component_on(instance)
if var_validate is None:
logger.warning(
"theta_name %s was not found on the model", (theta)
)
else:
try:
if len(thetavals) == 0:
var_validate.fix()
else:
var_validate.fix(thetavals[theta])
theta_init_vals.append(var_validate)
except:
logger.warning(
'Unable to fix model parameter value for %s (not a Pyomo model Var)',
(theta),
)
if active_constraints:
if self.diagnostic_mode:
print(' Experiment = ', snum)
print(' First solve with special diagnostics wrapper')
(status_obj, solved, iters, time, regu) = (
utils.ipopt_solve_with_stats(
instance, optimizer, max_iter=500, max_cpu_time=120
)
)
print(
" status_obj, solved, iters, time, regularization_stat = ",
str(status_obj),
str(solved),
str(iters),
str(time),
str(regu),
)
results = optimizer.solve(instance)
if self.diagnostic_mode:
print(
'standard solve solver termination condition=',
str(results.solver.termination_condition),
)
if (
results.solver.termination_condition
!= pyo.TerminationCondition.optimal
):
# DLW: Aug2018: not distinguishing "middlish" conditions
if WorstStatus != pyo.TerminationCondition.infeasible:
WorstStatus = results.solver.termination_condition
if initialize_parmest_model:
if self.diagnostic_mode:
print(
"Scenario {:d} infeasible with initialized parameter values".format(
snum
)
)
else:
if initialize_parmest_model:
if self.diagnostic_mode:
print(
"Scenario {:d} initialization successful with initial parameter values".format(
snum
)
)
if initialize_parmest_model:
# unfix parameters after initialization
for theta in theta_init_vals:
theta.unfix()
scen_dict[sname] = instance
else:
if initialize_parmest_model:
# unfix parameters after initialization
for theta in theta_init_vals:
theta.unfix()
scen_dict[sname] = instance
objobject = getattr(instance, self._second_stage_cost_exp)
objval = pyo.value(objobject)
totobj += objval
retval = totobj / len(scenario_numbers) # -1??
if initialize_parmest_model and not hasattr(self, 'ef_instance'):
# create extensive form of the model using scenario dictionary
if len(scen_dict) > 0:
for scen in scen_dict.values():
scen._mpisppy_probability = 1 / len(scen_dict)
if use_mpisppy:
EF_instance = sputils._create_EF_from_scen_dict(
scen_dict,
EF_name="_Q_at_theta",
# suppress_warnings=True
)
else:
EF_instance = local_ef._create_EF_from_scen_dict(
scen_dict, EF_name="_Q_at_theta", nonant_for_fixed_vars=True
)
self.ef_instance = EF_instance
# set self.model_initialized flag to True to skip extensive form model
# creation using theta_est()
self.model_initialized = True
# return initialized theta values
if len(thetavals) == 0:
# use appropriate theta_names member
theta_ref = self._return_theta_names()
for i, theta in enumerate(theta_ref):
thetavals[theta] = theta_init_vals[i]()
return retval, thetavals, WorstStatus
def _get_sample_list(self, samplesize, num_samples, replacement=True):
samplelist = list()
scenario_numbers = list(range(len(self.exp_list)))
if num_samples is None:
# This could get very large
for i, l in enumerate(combinations(scenario_numbers, samplesize)):
samplelist.append((i, np.sort(l)))
else:
for i in range(num_samples):
attempts = 0
unique_samples = 0 # check for duplicates in each sample
duplicate = False # check for duplicates between samples
while (unique_samples <= len(self._return_theta_names())) and (
not duplicate
):
sample = np.random.choice(
scenario_numbers, samplesize, replace=replacement
)
sample = np.sort(sample).tolist()
unique_samples = len(np.unique(sample))
if sample in samplelist:
duplicate = True
attempts += 1
if attempts > num_samples: # arbitrary timeout limit
raise RuntimeError(
"""Internal error: timeout constructing
a sample, the dim of theta may be too
close to the samplesize"""
)
samplelist.append((i, sample))
return samplelist
def theta_est(
self, solver="ef_ipopt", return_values=[], calc_cov=False, cov_n=None
):
"""
Parameter estimation using all scenarios in the data
Parameters
----------
solver: string, optional
Currently only "ef_ipopt" is supported. Default is "ef_ipopt".
return_values: list, optional
List of Variable names, used to return values from the model for data reconciliation
calc_cov: boolean, optional
If True, calculate and return the covariance matrix (only for "ef_ipopt" solver).
Default is False.
cov_n: int, optional
If calc_cov=True, then the user needs to supply the number of datapoints
that are used in the objective function.
Returns
-------
objectiveval: float
The objective function value
thetavals: pd.Series
Estimated values for theta
variable values: pd.DataFrame
Variable values for each variable name in return_values (only for solver='ef_ipopt')
cov: pd.DataFrame
Covariance matrix of the fitted parameters (only for solver='ef_ipopt')
"""
# check if we are using deprecated parmest
if self.pest_deprecated is not None:
return self.pest_deprecated.theta_est(
solver=solver,
return_values=return_values,
calc_cov=calc_cov,
cov_n=cov_n,
)
assert isinstance(solver, str)
assert isinstance(return_values, list)
assert isinstance(calc_cov, bool)
if calc_cov: