>>> import pyomo.environ as pyo
>>> from typing import Mapping
>>> from pyomo.contrib.observer.model_observer import (
... AutoUpdateConfig,
... Observer,
... ModelChangeDetector,
... Reason,
... )
>>> from pyomo.core.base import (
... VarData,
... ParamData,
... ConstraintData,
... SOSConstraintData,
... ObjectiveData,
... )
>>> class PrintObserver(Observer):
... def _update_variables(self, vars: Mapping[VarData, Reason]):
... for v, r in vars.items():
... print(f'{v}: {r.name}')
... def _update_parameters(self, params: Mapping[ParamData, Reason]):
... for p, r in params.items():
... print(f'{p}: {r.name}')
... def _update_constraints(self, cons: Mapping[ConstraintData, Reason]):
... for c, r in cons.items():
... print(f'{c}: {r.name}')
... def _update_sos_constraints(self, cons: Mapping[SOSConstraintData, Reason]):
... for c, r in cons.items():
... print(f'{c}: {r.name}')
... def _update_objectives(self, objs: Mapping[ObjectiveData, Reason]):
... for o, r in objs.items():
... print(f'{o}: {r.name}')
>>> m = pyo.ConcreteModel()
>>> obs = PrintObserver()
>>> detector = ModelChangeDetector(m, [obs])
>>> m.x = pyo.Var()
>>> m.y = pyo.Var()
>>> detector.update() # no output because the variables are not used
>>> m.obj = pyo.Objective(expr=m.x**2 + m.y**2)
>>> detector.update()
x: added
y: added
obj: added
>>> del m.obj
>>> detector.update()
obj: removed
x: removed
y: removed
>>> m.px = pyo.Param(mutable=True, initialize=1)
>>> m.py = pyo.Param(mutable=True, initialize=1)
>>> m.obj = pyo.Objective(expr=m.px*m.x + m.py*m.y)
>>> detector.update()
x: added
y: added
px: added
py: added
obj: added
>>> m.px.value = 2
>>> detector.update()
px: value
>>> detector.config.check_for_new_or_removed_constraints = False
>>> detector.config.check_for_new_or_removed_objectives = False
>>> detector.config.update_constraints = False
>>> detector.config.update_vars = False
>>> detector.config.update_parameters = True
>>> detector.config.update_named_expressions = False
>>> detector.config.update_objectives = False
>>> for i in range(10):
... m.py.value = i
... detector.update() # this will be faster because it is only checking for changes to parameters
py: value
py: value
py: value
py: value
py: value
py: value
py: value
py: value
py: value
py: value
>>> m.c = pyo.Constraint(expr=m.y >= pyo.exp(m.x))
>>> detector.update() # no output because we did not check for new constraints
>>> detector.config.check_for_new_or_removed_constraints = True
>>> detector.update()
c: added