diff --git a/.pylint/pylintrc b/.pylint/pylintrc index bdd4722ac5..109efd7c3d 100644 --- a/.pylint/pylintrc +++ b/.pylint/pylintrc @@ -19,7 +19,7 @@ disable=no-self-argument, arguments-differ, abstract-method, arguments-renamed, - unused-argument, # w have cases where a general high level method passes arguments that simpler methods do not need + unused-argument, # we have cases where a general high level method passes arguments that simpler methods do not need redefined-outer-name, anomalous-backslash-in-string, unspecified-encoding, @@ -29,6 +29,7 @@ disable=no-self-argument, too-many-lines, use-implicit-booleaness-not-comparison, # implicit booleaness can be hard to follow consider-using-f-string, # should fix, but a lot of effort + no-member, # Triggers many false positives from Pyomo due to diamond structure [IMPORTS] ignored-modules=cvalsim,almsim diff --git a/docs/reference_guides/core/var_like_expr.rst b/docs/reference_guides/core/var_like_expr.rst index d2d4b54bd0..0fc300d0b5 100644 --- a/docs/reference_guides/core/var_like_expr.rst +++ b/docs/reference_guides/core/var_like_expr.rst @@ -20,6 +20,6 @@ In these cases, it is possible that a user might mistake the `Expression` for a .. autoclass:: IndexedVarLikeExpression :members: -.. autoclass:: _GeneralVarLikeExpressionData +.. autoclass:: VarLikeExpressionData :members: diff --git a/idaes/apps/caprese/common/config.py b/idaes/apps/caprese/common/config.py index d289f2ad2e..560d537945 100644 --- a/idaes/apps/caprese/common/config.py +++ b/idaes/apps/caprese/common/config.py @@ -16,7 +16,7 @@ """ import enum from pyomo.environ import SolverFactory -from pyomo.core.base.var import _GeneralVarData +from pyomo.core.base.var import VarData class ControlInitOption(enum.Enum): @@ -94,7 +94,7 @@ def validate_list_of_vardata(varlist): if not isinstance(varlist, list): raise TypeError("Not a list of VarData") for var in varlist: - if not isinstance(var, _GeneralVarData): + if not isinstance(var, VarData): raise TypeError("Not a list of VarData") return varlist @@ -107,7 +107,7 @@ def validate_list_of_vardata_value_tuples(varvaluelist): raise TypeError("Item in list is not a tuple") if not len(item) == 2: raise ValueError("Tuple in list does not have correct length") - if not isinstance(item[0], _GeneralVarData): + if not isinstance(item[0], VarData): raise TypeError("First entry is not a VarData") item = (item[0], float(item[1])) return varvaluelist diff --git a/idaes/apps/caprese/controller.py b/idaes/apps/caprese/controller.py index f48d5f3f1e..aa08897117 100644 --- a/idaes/apps/caprese/controller.py +++ b/idaes/apps/caprese/controller.py @@ -14,18 +14,12 @@ """ Block-like object meant for controller models. """ -import idaes.logger as idaeslog -from idaes.apps.caprese.util import initialize_by_element_in_range from idaes.apps.caprese.common.config import ( ControlPenaltyType, ) from idaes.apps.caprese.common.config import VariableCategory as VC -from idaes.apps.caprese.categorize import ( - categorize_dae_variables, - CATEGORY_TYPE_MAP, -) + from idaes.apps.caprese.nmpc_var import ( - NmpcVar, DiffVar, AlgVar, InputVar, @@ -35,10 +29,8 @@ ) from idaes.apps.caprese.dynamic_block import ( _DynamicBlockData, - IndexedDynamicBlock, DynamicBlock, ) -from idaes.core.util.model_statistics import degrees_of_freedom from pyomo.environ import ( Objective, @@ -46,11 +38,8 @@ Constraint, Block, ) -from pyomo.core.base.block import _BlockData from pyomo.common.collections import ComponentMap -from pyomo.core.base.range import remainder from pyomo.dae.set_utils import deactivate_model_at -from pyomo.dae.flatten import flatten_dae_components from pyomo.core.base.indexed_component import UnindexedComponent_set diff --git a/idaes/apps/caprese/dynamic_block.py b/idaes/apps/caprese/dynamic_block.py index 281bb7665f..07ffb4120a 100644 --- a/idaes/apps/caprese/dynamic_block.py +++ b/idaes/apps/caprese/dynamic_block.py @@ -49,16 +49,15 @@ Suffix, ) from pyomo.core.base.initializer import Initializer -from pyomo.core.base.block import _BlockData, SubclassOf +from pyomo.core.base.block import BlockData, SubclassOf from pyomo.core.base.indexed_component import UnindexedComponent_set from pyomo.common.collections import ComponentMap from pyomo.common.config import ConfigDict, ConfigValue from pyomo.core.base.range import remainder -from pyomo.dae.set_utils import deactivate_model_at from pyomo.dae.flatten import flatten_dae_components -class _DynamicBlockData(_BlockData): +class _DynamicBlockData(BlockData): """This class adds methods and data structures that are useful for working with dynamic models. These include methods for initialization and references to time-indexed variables. @@ -290,7 +289,7 @@ def _add_category_references(self): # to add time in a rule without a long messy line of super().__setattr__. def add_time(self): # Do this because I can't add a reference to a set - super(_BlockData, self).__setattr__("time", self.time) + super(BlockData, self).__setattr__("time", self.time) def set_sample_time(self, sample_time, tolerance=1e-8): """Validates and sets sample time""" @@ -802,7 +801,7 @@ def _getitem_when_not_present(self, idx): block.mod = self._init_model(parent, idx) if self._init_time is not None: - super(_BlockData, block).__setattr__("time", self._init_time(parent, idx)) + super(BlockData, block).__setattr__("time", self._init_time(parent, idx)) if self._init_inputs is not None: block._inputs = self._init_inputs(parent, idx) diff --git a/idaes/apps/caprese/tests/test_dynamic_block.py b/idaes/apps/caprese/tests/test_dynamic_block.py index 22e6e0edac..227f6bfdf9 100644 --- a/idaes/apps/caprese/tests/test_dynamic_block.py +++ b/idaes/apps/caprese/tests/test_dynamic_block.py @@ -14,27 +14,11 @@ """ import pyomo.environ as pyo -import pyomo.dae as dae -import pyomo.network as pyn from pyomo.common.collections import ComponentSet from pyomo.core.expr.visitor import identify_variables -from pyomo.util.calc_var_value import calculate_variable_from_constraint -from pyomo.core.base.block import _BlockData, SubclassOf +from pyomo.core.base.block import BlockData, SubclassOf from pyomo.dae.flatten import flatten_dae_components -from idaes.core import ( - FlowsheetBlock, - MaterialBalanceType, - EnergyBalanceType, - MomentumBalanceType, -) -from idaes.core.util.model_statistics import ( - degrees_of_freedom, - activated_equalities_generator, - unfixed_variables_generator, -) -from idaes.core.util.initialization import initialize_by_time_element -from idaes.core.util.exceptions import ConfigurationError from idaes.apps.caprese.tests.test_simple_model import ( make_model, make_small_model, @@ -62,10 +46,7 @@ AlgVar, InputVar, FixedVar, - MeasuredVar, ) -import idaes.logger as idaeslog -import random import pytest __author__ = "Robert Parker" @@ -234,7 +215,7 @@ def dynamic_block_rule(b, i): # Won't be obvious that these attrs need to be set if # constructing from a rule b.mod = model - super(_BlockData, b).__setattr__("time", time) + super(BlockData, b).__setattr__("time", time) b._inputs = inputs b._measurements = measurements diff --git a/idaes/apps/caprese/util.py b/idaes/apps/caprese/util.py index d9bd95eed7..cd991139ac 100644 --- a/idaes/apps/caprese/util.py +++ b/idaes/apps/caprese/util.py @@ -25,8 +25,8 @@ from pyomo.dae.flatten import flatten_dae_components from pyomo.dae.set_utils import is_in_block_indexed_by from pyomo.core.expr.visitor import identify_variables -from pyomo.core.base.constraint import _ConstraintData -from pyomo.core.base.block import _BlockData +from pyomo.core.base.constraint import ConstraintData +from pyomo.core.base.block import BlockData from idaes.core.util.model_statistics import degrees_of_freedom from idaes.core.util.dyn_utils import ( @@ -187,9 +187,9 @@ def initialize_by_element_in_range( if was_originally_active[id(comp)]: comp.activate() if not time_linking_vars: - if isinstance(comp, _ConstraintData): + if isinstance(comp, ConstraintData): con_list.append(comp) - elif isinstance(comp, _BlockData): + elif isinstance(comp, BlockData): # Active here should be independent of whether block # was active con_list.extend( diff --git a/idaes/apps/matopt/opt/pyomo_modeling.py b/idaes/apps/matopt/opt/pyomo_modeling.py index 0e9eda2754..effedf0a54 100644 --- a/idaes/apps/matopt/opt/pyomo_modeling.py +++ b/idaes/apps/matopt/opt/pyomo_modeling.py @@ -15,7 +15,7 @@ logging = getModelLogger("MatOptModel") from pyomo.environ import * -from pyomo.core.base.var import _GeneralVarData +from pyomo.core.base.var import VarData from pyomo.core.expr.numeric_expr import ( MonomialTermExpression, SumExpression, @@ -43,13 +43,13 @@ def getLB(e): """ # Future work: use Pyomo function to achieve this functionality # return compute_bounds_on_expr(e)[0] - if isinstance(e, _GeneralVarData): + if isinstance(e, VarData): if e.is_fixed(): return value(e) else: return e.lb elif isinstance(e, MonomialTermExpression): - assert isinstance(e.args[1], pyomo.core.base.var._GeneralVarData), ( + assert isinstance(e.args[1], pyomo.core.base.var.VarData), ( "This code relies on the assumption that the only variable " "in a monomial expression is the second argument" ) @@ -93,13 +93,13 @@ def getUB(e): """ # Future work: use Pyomo function to achieve this functionality # return compute_bounds_on_expr(e)[1] - if isinstance(e, _GeneralVarData): + if isinstance(e, VarData): if e.is_fixed(): return value(e) else: return e.ub elif isinstance(e, MonomialTermExpression): - assert isinstance(e.args[1], pyomo.core.base.var._GeneralVarData), ( + assert isinstance(e.args[1], pyomo.core.base.var.VarData), ( "This code relies on the assumption that the only variable " "in a monomial expression is the second argument" ) diff --git a/idaes/core/base/process_base.py b/idaes/core/base/process_base.py index b0ff0be520..f403dcb38f 100644 --- a/idaes/core/base/process_base.py +++ b/idaes/core/base/process_base.py @@ -26,7 +26,7 @@ from pandas import DataFrame -from pyomo.core.base.block import _BlockData +from pyomo.core.base.block import BlockData from pyomo.common.formatting import tabular_writer from pyomo.environ import Block from pyomo.gdp import Disjunct @@ -75,7 +75,7 @@ class MaterialFlowBasis(Enum): @declare_process_block_class("ProcessBaseBlock") -class ProcessBlockData(_BlockData): +class ProcessBlockData(BlockData): """ Base class for most IDAES process models and classes. @@ -97,7 +97,7 @@ def __init__(self, component): Initialize a ProcessBlockData object. Args: - component(Block): container Block instance to which this _BlockData + component(Block): container Block instance to which this BlockData belongs. Returns: diff --git a/idaes/core/base/property_base.py b/idaes/core/base/property_base.py index 4ee235ea0f..b82e2b0a2c 100644 --- a/idaes/core/base/property_base.py +++ b/idaes/core/base/property_base.py @@ -20,8 +20,8 @@ # Import Pyomo libraries from pyomo.environ import Set, value, Var, Expression, Constraint, Reference -from pyomo.core.base.var import _VarData -from pyomo.core.base.expression import _ExpressionData +from pyomo.core.base.var import VarData +from pyomo.core.base.expression import ExpressionData from pyomo.common.config import ConfigBlock, ConfigValue, Bool from pyomo.common.formatting import tabular_writer from pyomo.network import Port @@ -399,7 +399,7 @@ def report(self, index=(0), true_state=False, dof=False, ostream=None, prefix="" ostream.write("\n" + "-" * max_str_length + "\n") ostream.write(f"{prefix}{tab}State Report") - if any(isinstance(v, _VarData) for k, v in stream_attributes.items()): + if any(isinstance(v, VarData) for k, v in stream_attributes.items()): ostream.write("\n" * 2) ostream.write(f"{prefix}{tab}Variables: \n\n") tabular_writer( @@ -408,13 +408,13 @@ def report(self, index=(0), true_state=False, dof=False, ostream=None, prefix="" ( (k, v) for k, v in stream_attributes.items() - if isinstance(v, _VarData) + if isinstance(v, VarData) ), ("Value", "Fixed", "Bounds"), lambda k, v: ["{:#.5g}".format(value(v)), v.fixed, v.bounds], ) - if any(isinstance(v, _ExpressionData) for k, v in stream_attributes.items()): + if any(isinstance(v, ExpressionData) for k, v in stream_attributes.items()): ostream.write("\n" * 2) ostream.write(f"{prefix}{tab}Expressions: \n\n") tabular_writer( @@ -423,7 +423,7 @@ def report(self, index=(0), true_state=False, dof=False, ostream=None, prefix="" ( (k, v) for k, v in stream_attributes.items() - if isinstance(v, _ExpressionData) + if isinstance(v, ExpressionData) ), ("Value",), lambda k, v: ["{:#.5g}".format(value(v))], diff --git a/idaes/core/base/tests/test_control_volume_1d.py b/idaes/core/base/tests/test_control_volume_1d.py index 62580d2811..f24cf529a0 100644 --- a/idaes/core/base/tests/test_control_volume_1d.py +++ b/idaes/core/base/tests/test_control_volume_1d.py @@ -31,7 +31,7 @@ from pyomo.util.check_units import assert_units_consistent, assert_units_equivalent from pyomo.dae import ContinuousSet, DerivativeVar from pyomo.common.config import ConfigBlock -from pyomo.core.base.constraint import _GeneralConstraintData +from pyomo.core.base.constraint import ConstraintData from idaes.core import ( ControlVolume1DBlock, FlowsheetBlockData, @@ -1127,7 +1127,7 @@ def test_add_material_balances_default(): for j in m.fs.pp.component_list: with pytest.raises(KeyError): assert m.fs.cv.material_balances[0, 0, p, j] - assert type(m.fs.cv.material_balances[0, 1, p, j]) is _GeneralConstraintData + assert type(m.fs.cv.material_balances[0, 1, p, j]) is ConstraintData assert_units_consistent(m) @@ -1312,7 +1312,7 @@ def test_add_phase_component_balances_default(): for j in m.fs.pp.component_list: with pytest.raises(KeyError): assert m.fs.cv.material_balances[0, 0, p, j] - assert type(m.fs.cv.material_balances[0, 1, p, j]) is _GeneralConstraintData + assert type(m.fs.cv.material_balances[0, 1, p, j]) is ConstraintData assert_units_consistent(m) @@ -1344,7 +1344,7 @@ def test_add_phase_component_balances_default_FFD(): for j in m.fs.pp.component_list: with pytest.raises(KeyError): assert m.fs.cv.material_balances[0, 1, p, j] - assert type(m.fs.cv.material_balances[0, 0, p, j]) is _GeneralConstraintData + assert type(m.fs.cv.material_balances[0, 0, p, j]) is ConstraintData assert_units_consistent(m) @@ -1990,7 +1990,7 @@ def test_add_total_component_balances_default(): for j in m.fs.pp.component_list: with pytest.raises(KeyError): assert m.fs.cv.material_balances[0, 0, j] - assert type(m.fs.cv.material_balances[0, 1, j]) is _GeneralConstraintData + assert type(m.fs.cv.material_balances[0, 1, j]) is ConstraintData assert_units_consistent(m) @@ -2022,7 +2022,7 @@ def test_add_total_component_balances_default_FFD(): for j in m.fs.pp.component_list: with pytest.raises(KeyError): assert m.fs.cv.material_balances[0, 1, j] - assert type(m.fs.cv.material_balances[0, 0, j]) is _GeneralConstraintData + assert type(m.fs.cv.material_balances[0, 0, j]) is ConstraintData assert_units_consistent(m) @@ -2662,7 +2662,7 @@ def test_add_total_element_balances_default(): for j in m.fs.pp.element_list: with pytest.raises(KeyError): assert m.fs.cv.element_balances[0, 0, j] - assert type(m.fs.cv.element_balances[0, 1, j]) is _GeneralConstraintData + assert type(m.fs.cv.element_balances[0, 1, j]) is ConstraintData assert_units_consistent(m) @@ -2694,7 +2694,7 @@ def test_add_total_element_balances_default_FFD(): for j in m.fs.pp.element_list: with pytest.raises(KeyError): assert m.fs.cv.element_balances[0, 1, j] - assert type(m.fs.cv.element_balances[0, 0, j]) is _GeneralConstraintData + assert type(m.fs.cv.element_balances[0, 0, j]) is ConstraintData assert_units_consistent(m) @@ -3040,7 +3040,7 @@ def test_add_energy_balances_default(): with pytest.raises(KeyError): assert m.fs.cv.enthalpy_balances[0, 0] - assert type(m.fs.cv.enthalpy_balances[0, 1]) is _GeneralConstraintData + assert type(m.fs.cv.enthalpy_balances[0, 1]) is ConstraintData assert_units_consistent(m) @@ -3076,7 +3076,7 @@ def test_add_total_enthalpy_balances_default(): with pytest.raises(KeyError): assert m.fs.cv.enthalpy_balances[0, 0] - assert type(m.fs.cv.enthalpy_balances[0, 1]) is _GeneralConstraintData + assert type(m.fs.cv.enthalpy_balances[0, 1]) is ConstraintData assert_units_consistent(m) @@ -3110,7 +3110,7 @@ def test_add_total_enthalpy_balances_default_FFD(): with pytest.raises(KeyError): assert m.fs.cv.enthalpy_balances[0, 1] - assert type(m.fs.cv.enthalpy_balances[0, 0]) is _GeneralConstraintData + assert type(m.fs.cv.enthalpy_balances[0, 0]) is ConstraintData assert_units_consistent(m) @@ -3472,7 +3472,7 @@ def test_add_total_pressure_balances_default(): with pytest.raises(KeyError): assert m.fs.cv.pressure_balance[0, 0] - assert type(m.fs.cv.pressure_balance[0, 1]) is _GeneralConstraintData + assert type(m.fs.cv.pressure_balance[0, 1]) is ConstraintData assert_units_consistent(m) @@ -3505,7 +3505,7 @@ def test_add_total_pressure_balances_default_FFD(): with pytest.raises(KeyError): assert m.fs.cv.pressure_balance[0, 1] - assert type(m.fs.cv.pressure_balance[0, 0]) is _GeneralConstraintData + assert type(m.fs.cv.pressure_balance[0, 0]) is ConstraintData assert_units_consistent(m) diff --git a/idaes/core/base/var_like_expression.py b/idaes/core/base/var_like_expression.py index fcf99ac7ca..681d7f4924 100644 --- a/idaes/core/base/var_like_expression.py +++ b/idaes/core/base/var_like_expression.py @@ -19,7 +19,7 @@ # pylint: disable=missing-function-docstring import pyomo.environ as pyo -from pyomo.core.base.expression import _GeneralExpressionData +from pyomo.core.base.expression import ExpressionData from pyomo.core.base.component import ModelComponentFactory from pyomo.core.base.indexed_component import ( UnindexedComponent_set, @@ -28,9 +28,9 @@ # Author: Andrew Lee -class _GeneralVarLikeExpressionData(_GeneralExpressionData): +class VarLikeExpressionData(ExpressionData): """ - An object derived from _GeneralExpressionData which implements methods for + An object derived from ExpressionData which implements methods for common APIs on Vars. Constructor Arguments: @@ -125,7 +125,7 @@ class VarLikeExpression(pyo.Expression): rule: A rule function used to initialize this object. """ - _ComponentDataClass = _GeneralVarLikeExpressionData + _ComponentDataClass = VarLikeExpressionData NoConstraint = (1000,) Skip = (1000,) @@ -140,9 +140,9 @@ def __new__(cls, *args, **kwds): return super(VarLikeExpression, cls).__new__(IndexedVarLikeExpression) -class SimpleVarLikeExpression(_GeneralVarLikeExpressionData, VarLikeExpression): +class SimpleVarLikeExpression(VarLikeExpressionData, VarLikeExpression): def __init__(self, *args, **kwds): - _GeneralVarLikeExpressionData.__init__(self, expr=None, component=self) + VarLikeExpressionData.__init__(self, expr=None, component=self) VarLikeExpression.__init__(self, *args, **kwds) # @@ -184,7 +184,7 @@ def add(self, index, expr): """Add an expression with a given index.""" if isinstance(expr, tuple) and expr == pyo.Expression.Skip: return None - cdata = _GeneralVarLikeExpressionData(expr, component=self) + cdata = VarLikeExpressionData(expr, component=self) self._data[index] = cdata return cdata diff --git a/idaes/core/initialization/initializer_base.py b/idaes/core/initialization/initializer_base.py index 83acf81e80..27f4de040e 100644 --- a/idaes/core/initialization/initializer_base.py +++ b/idaes/core/initialization/initializer_base.py @@ -22,7 +22,7 @@ Constraint, Var, ) -from pyomo.core.base.var import _VarData +from pyomo.core.base.var import VarData from pyomo.common.config import ConfigDict, ConfigValue, String_ConfigFormatter from idaes.core.util.model_serializer import to_json, from_json, StoreSpec, _only_fixed @@ -492,7 +492,7 @@ def _load_values_from_dict(self, model, initial_guesses, exception_on_fixed=True if component is None: raise ValueError(f"Could not find a component with name {c}.") - elif not isinstance(component, (Var, _VarData)): + elif not isinstance(component, (Var, VarData)): self._update_summary(model, "status", InitializationStatus.Error) raise TypeError( f"Component {c} is not a Var. Initial guesses should only contain values for variables." diff --git a/idaes/core/plugins/variable_replace.py b/idaes/core/plugins/variable_replace.py index 883876ddc9..77f656dac9 100644 --- a/idaes/core/plugins/variable_replace.py +++ b/idaes/core/plugins/variable_replace.py @@ -22,7 +22,7 @@ ConfigValue, document_kwargs_from_configdict, ) -from pyomo.core.base.var import _GeneralVarData, Var +from pyomo.core.base.var import VarData, Var from pyomo.core.base.constraint import Constraint from pyomo.core.base.expression import Expression from pyomo.core.base.objective import Objective @@ -32,7 +32,7 @@ def _is_var(v): - return isinstance(v, (_GeneralVarData, Var)) + return isinstance(v, (VarData, Var)) @TransformationFactory.register( @@ -110,7 +110,7 @@ def _apply_to(self, instance, **kwds): instance: A block or model to apply the transformation to substitute: A list-like of two-element list-likes. Each two element list-like specifies a replacement of the first variable by the - second. SimpleVar, IndexedVar, _GeneralVarData, and Reference are + second. SimpleVar, IndexedVar, VarData, and Reference are all accepted types. Returns: diff --git a/idaes/core/solvers/homotopy.py b/idaes/core/solvers/homotopy.py index 6574acee99..0b653d6f10 100644 --- a/idaes/core/solvers/homotopy.py +++ b/idaes/core/solvers/homotopy.py @@ -19,7 +19,7 @@ import logging from pyomo.environ import Block, SolverFactory, TerminationCondition -from pyomo.core.base.var import _VarData +from pyomo.core.base.var import VarData from pyomo.contrib.parmest.utils.ipopt_solver_wrapper import ipopt_solve_with_stats from idaes.core.util.model_serializer import to_json, from_json @@ -103,7 +103,7 @@ def homotopy( for i, v in enumerate(variables): t = targets[i] - if not isinstance(v, _VarData): + if not isinstance(v, VarData): raise TypeError( "Variable provided ({}) was not a valid Pyomo Var " "component.".format(v) diff --git a/idaes/core/surrogate/pysmo_surrogate.py b/idaes/core/surrogate/pysmo_surrogate.py index 9329469fa9..a66e98eeca 100644 --- a/idaes/core/surrogate/pysmo_surrogate.py +++ b/idaes/core/surrogate/pysmo_surrogate.py @@ -674,7 +674,7 @@ def is_pyomo_value(v): return isinstance( v, ( - pc.base.param._ParamData, + pc.base.param.ParamData, pc.base.param.Param, pc.expr.numeric_expr.NPV_ProductExpression, pc.expr.numeric_expr.NPV_DivisionExpression, diff --git a/idaes/core/surrogate/surrogate_block.py b/idaes/core/surrogate/surrogate_block.py index 3ee333c755..456fd59ecd 100644 --- a/idaes/core/surrogate/surrogate_block.py +++ b/idaes/core/surrogate/surrogate_block.py @@ -16,7 +16,7 @@ import collections -from pyomo.core.base.block import declare_custom_block, _BlockData +from pyomo.core.base.block import declare_custom_block, BlockData from pyomo.environ import Var, Set import idaes.logger as idaeslog @@ -26,7 +26,7 @@ @declare_custom_block(name="SurrogateBlock") -class SurrogateBlockData(_BlockData): +class SurrogateBlockData(BlockData): # pylint: disable=W0235 def __init__(self, component): """ diff --git a/idaes/core/util/expr_doc.py b/idaes/core/util/expr_doc.py index a968ac7cae..de70828d2e 100644 --- a/idaes/core/util/expr_doc.py +++ b/idaes/core/util/expr_doc.py @@ -23,9 +23,9 @@ _configure_sympy, ) from pyomo.environ import ExternalFunction, Var, Expression, value, units as pu -from pyomo.core.base.constraint import _ConstraintData, Constraint -from pyomo.core.base.expression import _ExpressionData -from pyomo.core.base.block import _BlockData +from pyomo.core.base.constraint import ConstraintData, Constraint +from pyomo.core.base.expression import ExpressionData +from pyomo.core.base.block import BlockData from pyomo.core.expr.visitor import StreamBasedExpressionVisitor from pyomo.core.expr.numeric_expr import ExternalFunctionExpression from pyomo.core import expr as EXPR, native_types @@ -307,8 +307,8 @@ def document_constraints( assuming the $$latex math$$ and $latex math$ syntax is supported. Args: - comp: A Pyomo component to document in {_ConstraintData, _ExpressionData, - _BlockData}. + comp: A Pyomo component to document in {ConstraintData, ExpressionData, + BlockData}. doc: True adds a documentation table for each constraint or expression. Due to the way symbols are semi-automatiaclly generated, the exact symbol definitions may be unique to each constraint or @@ -322,7 +322,7 @@ def document_constraints( if to_doc is None: to_doc = [] s = None - if isinstance(comp, _ExpressionData): + if isinstance(comp, ExpressionData): d = to_latex(comp) to_doc.append(d["object_map"]) try: @@ -343,7 +343,7 @@ def document_constraints( s = "$${}$$\n{}".format(d["latex_expr"], d["where"]) else: s = "$${}$$".format(d["latex_expr"]) - elif isinstance(comp, _ConstraintData): + elif isinstance(comp, ConstraintData): d = to_latex(comp.body) to_doc.append(d["object_map"]) try: @@ -357,7 +357,7 @@ def document_constraints( s = rf"$${comp.lower} \le {latex_expr} \le {comp.upper}$$" if doc: s += f"\n{d['where']}" - elif isinstance(comp, _BlockData): + elif isinstance(comp, BlockData): cs = [] for c in comp.component_data_objects(Constraint, descend_into=descend_into): if not c.active: diff --git a/idaes/core/util/model_diagnostics.py b/idaes/core/util/model_diagnostics.py index 6ff4ee4def..7fb08393c0 100644 --- a/idaes/core/util/model_diagnostics.py +++ b/idaes/core/util/model_diagnostics.py @@ -54,9 +54,9 @@ NPV_UnaryFunctionExpression, NumericExpression, ) -from pyomo.core.base.block import _BlockData -from pyomo.core.base.var import _GeneralVarData, _VarData -from pyomo.core.base.constraint import _ConstraintData +from pyomo.core.base.block import BlockData +from pyomo.core.base.var import VarData +from pyomo.core.base.constraint import ConstraintData from pyomo.repn.standard_repn import ( # pylint: disable=no-name-in-module generate_standard_repn, ) @@ -427,10 +427,10 @@ class DiagnosticsToolbox: """ - def __init__(self, model: _BlockData, **kwargs): + def __init__(self, model: BlockData, **kwargs): # TODO: In future may want to generalise this to accept indexed blocks # However, for now some of the tools do not support indexed blocks - if not isinstance(model, _BlockData): + if not isinstance(model, BlockData): raise TypeError( "model argument must be an instance of a Pyomo BlockData object " "(either a scalar Block or an element of an indexed Block)." @@ -1563,10 +1563,10 @@ class SVDToolbox: """ - def __init__(self, model: _BlockData, **kwargs): + def __init__(self, model: BlockData, **kwargs): # TODO: In future may want to generalise this to accept indexed blocks # However, for now some of the tools do not support indexed blocks - if not isinstance(model, _BlockData): + if not isinstance(model, BlockData): raise TypeError( "model argument must be an instance of a Pyomo BlockData object " "(either a scalar Block or an element of an indexed Block)." @@ -1748,9 +1748,9 @@ def display_constraints_including_variable(self, variable, stream=None): stream = sys.stdout # Validate variable argument - if not isinstance(variable, _VarData): + if not isinstance(variable, VarData): raise TypeError( - f"variable argument must be an instance of a Pyomo _VarData " + f"variable argument must be an instance of a Pyomo VarData " f"object (got {variable})." ) @@ -1795,9 +1795,9 @@ def display_variables_in_constraint(self, constraint, stream=None): stream = sys.stdout # Validate variable argument - if not isinstance(constraint, _ConstraintData): + if not isinstance(constraint, ConstraintData): raise TypeError( - f"constraint argument must be an instance of a Pyomo _ConstraintData " + f"constraint argument must be an instance of a Pyomo ConstraintData " f"object (got {constraint})." ) @@ -1857,7 +1857,7 @@ def _check_eval_error_pow( integer_exponent = False # if the exponent is an integer, there should not be any evaluation errors - if isinstance(arg2, _GeneralVarData) and arg2.domain in integer_domains: + if isinstance(arg2, VarData) and arg2.domain in integer_domains: # The exponent is an integer variable # check if the base can be zero integer_exponent = True @@ -2008,7 +2008,7 @@ class DegeneracyHunter2: def __init__(self, model, **kwargs): # TODO: In future may want to generalise this to accept indexed blocks # However, for now some of the tools do not support indexed blocks - if not isinstance(model, _BlockData): + if not isinstance(model, BlockData): raise TypeError( "model argument must be an instance of a Pyomo BlockData object " "(either a scalar Block or an element of an indexed Block)." @@ -3108,7 +3108,7 @@ class IpoptConvergenceAnalysis: def __init__(self, model, **kwargs): # TODO: In future may want to generalise this to accept indexed blocks # However, for now some of the tools do not support indexed blocks - if not isinstance(model, _BlockData): + if not isinstance(model, BlockData): raise TypeError( "model argument must be an instance of a Pyomo BlockData object " "(either a scalar Block or an element of an indexed Block)." @@ -3557,7 +3557,7 @@ def set_bounds_from_valid_range(component, descend_into=True): if component.is_indexed(): for k in component: set_bounds_from_valid_range(component[k]) - elif isinstance(component, _BlockData): + elif isinstance(component, BlockData): for i in component.component_data_objects( ctype=[Var, Param], descend_into=descend_into ): @@ -3598,7 +3598,7 @@ def list_components_with_values_outside_valid_range(component, descend_into=True comp_list.extend( list_components_with_values_outside_valid_range(component[k]) ) - elif isinstance(component, _BlockData): + elif isinstance(component, BlockData): for i in component.component_data_objects( ctype=[Var, Param], descend_into=descend_into ): diff --git a/idaes/core/util/model_serializer.py b/idaes/core/util/model_serializer.py index 79b9193bdf..e3eff66db7 100644 --- a/idaes/core/util/model_serializer.py +++ b/idaes/core/util/model_serializer.py @@ -35,7 +35,7 @@ Suffix, value, ) -from pyomo.core.base.param import _ParamData +from pyomo.core.base.param import ParamData from pyomo.core.base.component import ComponentData _log = logging.getLogger(__name__) @@ -256,7 +256,7 @@ def __init__( None, ), BooleanVar._ComponentDataClass: (("fixed", "stale", "value"), None), - _ParamData: (("value",), None), + ParamData: (("value",), None), int: (("value",), None), float: (("value",), None), str: (("value",), None), @@ -472,7 +472,7 @@ def value_isfixed_isactive(cls, only_fixed): data_classes={ Var._ComponentDataClass: (("value", "fixed"), _only_fixed), BooleanVar._ComponentDataClass: (("value", "fixed"), _only_fixed), - _ParamData: (("value",), None), + ParamData: (("value",), None), Constraint._ComponentDataClass: (("active",), None), Block._ComponentDataClass: (("active",), None), }, @@ -489,7 +489,7 @@ def value_isfixed_isactive(cls, only_fixed): data_classes={ Var._ComponentDataClass: (("value", "fixed"), None), BooleanVar._ComponentDataClass: (("value", "fixed"), None), - _ParamData: (("value",), None), + ParamData: (("value",), None), Constraint._ComponentDataClass: (("active",), None), Block._ComponentDataClass: (("active",), None), }, diff --git a/idaes/core/util/scaling.py b/idaes/core/util/scaling.py index 0c1b889058..5396f48610 100644 --- a/idaes/core/util/scaling.py +++ b/idaes/core/util/scaling.py @@ -34,14 +34,14 @@ import scipy.linalg as la import pyomo.environ as pyo -from pyomo.core.base.var import _VarData -from pyomo.core.base.param import _ParamData +from pyomo.core.base.var import VarData +from pyomo.core.base.param import ParamData from pyomo.core.expr.visitor import identify_variables from pyomo.network import Arc from pyomo.contrib.pynumero.interfaces.pyomo_nlp import PyomoNLP from pyomo.contrib.pynumero.asl import AmplInterface from pyomo.common.modeling import unique_component_name -from pyomo.core.base.constraint import _ConstraintData +from pyomo.core.base.constraint import ConstraintData from pyomo.common.collections import ComponentMap, ComponentSet from pyomo.dae import DerivativeVar from pyomo.dae.flatten import slice_component_along_sets @@ -276,7 +276,7 @@ def get_scaling_factor(c, default=None, warning=False, exception=False, hint=Non try: sf = c.parent_block().scaling_factor[c] except (AttributeError, KeyError): - if not isinstance(c, (pyo.Param, _ParamData)): + if not isinstance(c, (pyo.Param, ParamData)): if hint is None: h = "" else: @@ -458,7 +458,7 @@ def constraint_scaling_transform(c, s, overwrite=True): """ # Want to clear away any units that may have incidentally become attached to s s = pyo.value(s) - if not isinstance(c, _ConstraintData): + if not isinstance(c, ConstraintData): raise TypeError(f"{c} is not a constraint or is an indexed constraint") st = get_constraint_transform_applied_scaling_factor(c, default=None) @@ -484,7 +484,7 @@ def constraint_scaling_transform_undo(c): Returns: None """ - if not isinstance(c, _ConstraintData): + if not isinstance(c, ConstraintData): raise TypeError(f"{c} is not a constraint or is an indexed constraint") v = get_constraint_transform_applied_scaling_factor(c) if v is None: @@ -1224,7 +1224,7 @@ def set_variable_scaling_from_current_value( elif component.is_indexed(): for k in component.values(): set_variable_scaling_from_current_value(k, overwrite=overwrite) - elif not isinstance(component, _VarData): + elif not isinstance(component, VarData): raise TypeError( f"Invalid component type {component.name} (type:{type(component)}). " "component argument to set_variable_scaling_from_current_value must be " diff --git a/idaes/core/util/tables.py b/idaes/core/util/tables.py index 6fec166af1..4e88567fec 100644 --- a/idaes/core/util/tables.py +++ b/idaes/core/util/tables.py @@ -20,7 +20,7 @@ from pyomo.environ import value from pyomo.network import Arc, Port -from pyomo.core.base.var import _GeneralVarData, Var +from pyomo.core.base.var import VarData, Var from pyomo.core.base.param import Param from pyomo.core.base.expression import Expression @@ -245,7 +245,7 @@ class VariableTypes: # Identifying value's variable type var_type = None - if isinstance(disp_dict[k][i], (_GeneralVarData, Var)): + if isinstance(disp_dict[k][i], (VarData, Var)): if disp_dict[k][i].fixed: var_type = VariableTypes.FIXED else: diff --git a/idaes/core/util/tests/test_model_diagnostics.py b/idaes/core/util/tests/test_model_diagnostics.py index f21cc5194d..3b1312521a 100644 --- a/idaes/core/util/tests/test_model_diagnostics.py +++ b/idaes/core/util/tests/test_model_diagnostics.py @@ -1846,7 +1846,7 @@ def test_display_constraints_including_variable_invalid(self): with pytest.raises( TypeError, match=re.escape( - "variable argument must be an instance of a Pyomo _VarData " + "variable argument must be an instance of a Pyomo VarData " "object (got foo)." ), ): @@ -1913,7 +1913,7 @@ def test_display_variables_in_constraint_invalid(self): with pytest.raises( TypeError, match=re.escape( - "constraint argument must be an instance of a Pyomo _ConstraintData " + "constraint argument must be an instance of a Pyomo ConstraintData " "object (got foo)." ), ): diff --git a/idaes/core/util/tests/test_model_serializer.py b/idaes/core/util/tests/test_model_serializer.py index 58089dbdd8..2b833e2986 100644 --- a/idaes/core/util/tests/test_model_serializer.py +++ b/idaes/core/util/tests/test_model_serializer.py @@ -362,7 +362,7 @@ def test04b(self): data_classes=( (Var._ComponentDataClass, ("value", "fixed"), _only_fixed), (BooleanVar._ComponentDataClass, ("value", "fixed"), _only_fixed), - (pyomo.core.base.param._ParamData, ("value",), None), + (pyomo.core.base.param.ParamData, ("value",), None), (Constraint._ComponentDataClass, ("active",), None), (Block._ComponentDataClass, ("active",), None), ), diff --git a/idaes/models/properties/tests/test_harness.py b/idaes/models/properties/tests/test_harness.py index 3b642e608f..481a02a01d 100644 --- a/idaes/models/properties/tests/test_harness.py +++ b/idaes/models/properties/tests/test_harness.py @@ -30,14 +30,14 @@ from idaes.core.util.exceptions import InitializationError -from pyomo.core.base.var import _VarData -from pyomo.core.base.param import _ParamData -from pyomo.core.base.expression import _ExpressionData +from pyomo.core.base.var import VarData +from pyomo.core.base.param import ParamData +from pyomo.core.base.expression import ExpressionData from idaes.core.initialization.initializer_base import ( InitializationStatus, ) -_scalable = (_VarData, _ParamData, _ExpressionData) +_scalable = (VarData, ParamData, ExpressionData) # ----------------------------------------------------------------------------- # Get default solver for testing diff --git a/idaes/models/unit_models/separator.py b/idaes/models/unit_models/separator.py index 8ad00589d0..a2a273957a 100644 --- a/idaes/models/unit_models/separator.py +++ b/idaes/models/unit_models/separator.py @@ -1839,9 +1839,9 @@ def calculate_scaling_factors(self): def _get_performance_contents(self, time_point=0): if hasattr(self, "split_fraction"): var_dict = {} - for k in self.split_fraction.keys(): + for k, v in self.split_fraction.items(): if k[0] == time_point: - var_dict[f"Split Fraction [{str(k[1:])}]"] = self.split_fraction[k] + var_dict[f"Split Fraction [{str(k[1:])}]"] = v return {"vars": var_dict} else: return None diff --git a/idaes/models_extra/power_generation/costing/power_plant_capcost.py b/idaes/models_extra/power_generation/costing/power_plant_capcost.py index d394bf0dd2..deacf2bc4f 100644 --- a/idaes/models_extra/power_generation/costing/power_plant_capcost.py +++ b/idaes/models_extra/power_generation/costing/power_plant_capcost.py @@ -1977,17 +1977,17 @@ def initialize_variable_OM_costs(b): # b is the flowsheet-level costing block # initialization for power generation costs if hasattr(b, "variable_operating_costs"): - for i in b.variable_operating_costs.keys(): + for k, v in b.variable_operating_costs.items(): if hasattr(b, "variable_cost_rule_power"): calculate_variable_from_constraint( - b.variable_operating_costs[i], - b.variable_cost_rule_power[i], + v, + b.variable_cost_rule_power[k], ) - for i in b.total_variable_OM_cost.keys(): + for k, v in b.total_variable_OM_cost.items(): calculate_variable_from_constraint( - b.total_variable_OM_cost[i], - b.total_variable_cost_rule_power[i], + v, + b.total_variable_cost_rule_power[k], ) # ----------------------------------------------------------------------------- diff --git a/setup.py b/setup.py index 902cf7a3df..0bd138331e 100644 --- a/setup.py +++ b/setup.py @@ -132,7 +132,7 @@ def __getitem__(self, key): # Put abstract (non-versioned) deps here. # Concrete dependencies go in requirements[-dev].txt install_requires=[ - "pyomo >= 6.7.1", + "pyomo @ https://github.com/IDAES/pyomo/archive/6.7.2.idaes.2024.05.07.zip", "pint", # required to use Pyomo units "networkx", # required to use Pyomo network "numpy<2",