# ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 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.
# ____________________________________________________________________________________
import pyomo.core.expr as EXPR
from pyomo.core import (
nonpyomo_leaf_types,
TransformationFactory,
IntegerSet,
Integers,
PositiveIntegers,
NonPositiveIntegers,
NegativeIntegers,
NonNegativeIntegers,
Reals,
PositiveReals,
NonNegativeReals,
NegativeReals,
NonPositiveReals,
PercentFraction,
RealSet,
Var,
Set,
value,
Binary,
Constraint,
Objective,
)
from pyomo.core.base.misc import create_name
from pyomo.core.plugins.transform.util import partial
from pyomo.core.plugins.transform.hierarchy import IsomorphicTransformation
from pyomo.core.plugins.transform.util import collectAbstractComponents
import logging
logger = logging.getLogger('pyomo.core')
[docs]
class VarmapVisitor(EXPR.ExpressionReplacementVisitor):
[docs]
def __init__(self, varmap):
super(VarmapVisitor, self).__init__()
self.varmap = varmap
def visiting_potential_leaf(self, node):
if node.__class__ in nonpyomo_leaf_types:
return True, node
#
# Clone leaf nodes in the expression tree
#
if node.is_variable_type():
if node.local_name in self.varmap:
return True, self.varmap[node.local_name]
else:
return True, node
if isinstance(node, EXPR.LinearExpression):
with EXPR.nonlinear_expression() as expr:
for c, v in zip(node.linear_coefs, node.linear_vars):
if hasattr(v, 'local_name'):
expr += c * self.varmap.get(v.local_name)
else:
expr += c * v
return True, expr
return False, None
def _walk_expr(expr, varMap):
"""
Walks an expression tree, making the replacements defined in varMap
"""
visitor = VarmapVisitor(varMap)
return visitor.dfs_postorder_stack(expr)