Skip to content

Commit 7cdba5b

Browse files
committed
Merge remote-tracking branch 'sscini/add-update-model-utility' into sensitivity-initialization
2 parents 0c87484 + 81a595f commit 7cdba5b

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

pyomo/contrib/doe/utils.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,50 @@ def rescale_FIM(FIM, param_vals):
124124
# return param_list
125125

126126

127+
# Adding utility to update parameter values in a model based on the suffix
128+
def update_model_from_suffix(model, suffix_name, values):
129+
"""
130+
Iterate over the components (variables or parameters) referenced by the
131+
given suffix in the model, and assign each a new value from the provided iterable.
132+
133+
Parameters
134+
----------
135+
model : pyomo.environ.ConcreteModel
136+
The Pyomo model containing the suffix and components to update.
137+
suffix_name : str
138+
The name of the Suffix attribute on the model whose items will be updated.
139+
Must be one of: 'experiment_outputs', 'experiment_inputs', 'unknown_parameters', or 'measurement_error'.
140+
values : iterable of numbers
141+
The new values to assign to each component referenced by the suffix. The length of this
142+
iterable must match the number of items in the suffix.
143+
"""
144+
# Allowed suffix names
145+
allowed = {
146+
"experiment_outputs",
147+
"experiment_inputs",
148+
"unknown_parameters",
149+
"measurement_error",
150+
}
151+
# Validate input is an allowed suffix name
152+
if suffix_name not in allowed:
153+
raise ValueError(f"suffix_name must be one of {sorted(allowed)}")
154+
# Check if the model has the specified suffix
155+
suffix_obj = getattr(model, suffix_name, None)
156+
if suffix_obj is None:
157+
raise AttributeError(f"Model has no attribute '{suffix_name}'")
158+
# Check if the suffix is a Suffix object
159+
items = list(suffix_obj.items())
160+
if len(items) != len(values):
161+
raise ValueError("values length does not match suffix length")
162+
# Set the new values for the suffix items
163+
for (comp, _), new_val in zip(items, values):
164+
# Update the variable/parameter itself if it is VarData or ParamData
165+
if isinstance(comp, (VarData, ParamData)):
166+
comp.set_value(new_val)
167+
else:
168+
raise TypeError(f"Unsupported component type: {type(comp)}")
169+
170+
127171
def check_FIM(FIM):
128172
"""
129173
Checks that the FIM is square, positive definite, and symmetric.

0 commit comments

Comments
 (0)