/
expr_pyomo5.py
3197 lines (2655 loc) · 107 KB
/
expr_pyomo5.py
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 2017 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.
# ___________________________________________________________________________
from __future__ import division
#
# These symbols are part of pyomo.core.expr
#
__public__ = ['linear_expression', 'nonlinear_expression']
#
# These symbols are part of pyomo.core.expr.current
#
__all__ = (
'linear_expression',
'nonlinear_expression',
'mutable_sum_context',
'mutable_linear_context',
'decompose_term',
'clone_counter',
'clone_counter_context',
'clone_expression',
'evaluate_expression',
'identify_components',
'identify_variables',
'expression_to_string',
'chainedInequalityErrorMessage',
'ExpressionBase',
'EqualityExpression',
'InequalityExpression',
'ProductExpression',
'PowExpression',
'ExternalFunctionExpression',
'NPV_ExternalFunctionExpression',
'GetItemExpression',
'Expr_if',
'LinearExpression',
'ReciprocalExpression',
'NegationExpression',
'ViewSumExpression',
'UnaryFunctionExpression',
'AbsExpression',
'compress_expression',
'NPV_NegationExpression',
'NPV_ExternalFunctionExpression',
'NPV_PowExpression',
'NPV_ProductExpression',
'NPV_ReciprocalExpression',
'NPV_SumExpression',
'NPV_UnaryFunctionExpression',
'NPV_AbsExpression',
'SimpleExpressionVisitor',
'ExpressionValueVisitor',
'ExpressionReplacementVisitor',
'pyomo5_variable_types',
'_SumExpression', # This should not be referenced, except perhaps while testing code
'_MutableViewSumExpression', # This should not be referenced, except perhaps while testing code
'_MutableLinearExpression', # This should not be referenced, except perhaps while testing code
'_generate_sum_expression', # Only used within pyomo.core.expr
'_generate_mul_expression', # Only used within pyomo.core.expr
'_generate_other_expression', # Only used within pyomo.core.expr
'_generate_intrinsic_function_expression', # Only used within pyomo.core.expr
'_generate_relational_expression', # Only used within pyomo.core.expr
)
import math
import logging
import sys
import traceback
from copy import deepcopy
from collections import deque
from itertools import islice
from six import next, string_types, itervalues
from six.moves import xrange, builtins
from weakref import ref
logger = logging.getLogger('pyomo.core')
from pyutilib.misc.visitor import SimpleVisitor, ValueVisitor
from pyutilib.math.util import isclose
from pyomo.core.expr.symbol_map import SymbolMap
from pyomo.core.expr.numvalue import \
(NumericValue,
NumericConstant,
native_types,
native_numeric_types,
as_numeric,
value)
from pyomo.core.expr.expr_common import \
(_add, _sub, _mul, _div,
_pow, _neg, _abs, _inplace,
_unary, _radd, _rsub, _rmul,
_rdiv, _rpow, _iadd, _isub,
_imul, _idiv, _ipow, _lt, _le,
_eq)
from pyomo.core.expr import expr_common as common
def chainedInequalityErrorMessage(msg=None):
if msg is None:
msg = "Relational expression used in an unexpected Boolean context."
val = InequalityExpression.chainedInequality.to_string()
# We are about to raise an exception, so it's OK to reset chainedInequality
info = InequalityExpression.call_info
InequalityExpression.chainedInequality = None
InequalityExpression.call_info = None
args = ( str(msg).strip(), val.strip(), info[0], info[1],
':\n %s' % info[3] if info[3] is not None else '.' )
return """%s
The inequality expression:
%s
contains non-constant terms (variables) that were evaluated in an
unexpected Boolean context at
File '%s', line %s%s
Evaluating Pyomo variables in a Boolean context, e.g.
if expression <= 5:
is generally invalid. If you want to obtain the Boolean value of the
expression based on the current variable values, explicitly evaluate the
expression using the value() function:
if value(expression) <= 5:
or
if value(expression <= 5):
""" % args
_ParamData = None
SimpleParam = None
TemplateExpressionError = None
def initialize_expression_data():
"""
A function used to initialize expression global data.
This function is necessary to avoid global imports. It is executed
when ``pyomo.environ`` is imported.
"""
global pyomo5_variable_types
from pyomo.core.base import _VarData, _GeneralVarData, SimpleVar
from pyomo.core.kernel.component_variable import IVariable, variable
pyomo5_variable_types.update([_VarData, _GeneralVarData, IVariable, variable, SimpleVar])
_MutableLinearExpression.vtypes = pyomo5_variable_types
#
global _ParamData
global SimpleParam
global TemplateExpressionError
from pyomo.core.base.param import _ParamData, SimpleParam
from pyomo.core.base.template_expr import TemplateExpressionError
#
global pyomo5_named_expression_types
from pyomo.core.base.expression import _GeneralExpressionData, SimpleExpression
from pyomo.core.base.objective import _GeneralObjectiveData, SimpleObjective
pyomo5_expression_types.update([_GeneralExpressionData, SimpleExpression, _GeneralObjectiveData, SimpleObjective])
pyomo5_named_expression_types.update([_GeneralExpressionData, SimpleExpression, _GeneralObjectiveData, SimpleObjective])
#
# [functionality] chainedInequality allows us to generate symbolic
# expressions of the type "a < b < c". This provides a buffer to hold
# the first inequality so the second inequality can access it later.
#
InequalityExpression.chainedInequality = None
InequalityExpression.call_info = None
def compress_expression(expr):
"""
Deprecated function that was used to compress deep Pyomo5
expression trees.
"""
return expr
class clone_counter_context(object):
""" Context manager for counting cloning events.
This context manager counts the number of times that the
:func:`clone_expression <pyomo.core.expr.current.clone_expression>`
function is executed.
"""
_count = 0
def __enter__(self):
return self
def __exit__(self, *args):
pass
@property
def count(self):
"""A property that returns the clone count value.
"""
return clone_counter_context._count
#: A clone counter context manager object that simplifies the
#: use of this context manager. Specifically, different
#: instances of this context manger are not necessary.
clone_counter = clone_counter_context()
class mutable_sum_context(object):
""" Context manager for mutable sums.
This context manager is used to compute a sum while
treating the summation as a mutable object.
"""
def __enter__(self):
self.e = _MutableViewSumExpression([])
return self.e
def __exit__(self, *args):
pass
if self.e.__class__ == _MutableViewSumExpression:
self.e.__class__ = ViewSumExpression
#: A context manager object for nonlinear expressions.
#: This is an instance of the :class:`mutable_sum_contex <pyomo.core.expr.current.mutable_sum_context>` context manager.
#: Different instances of this context manger are not necessary.
nonlinear_expression = mutable_sum_context()
class mutable_linear_context(object):
""" Context manager for mutable linear sums.
This context manager is used to compute a linear sum while
treating the summation as a mutable object.
"""
def __enter__(self):
"""
The :class:`_MutableLinearExpression <pyomo.core.expr.current._MutableLinearExpression>`
class is the context that is used to to
hold the mutable linear sum.
"""
self.e = _MutableLinearExpression()
return self.e
def __exit__(self, *args):
"""
The context is changed to the
:class:`LinearExpression <pyomo.core.expr.current.LinearExpression>`
class to transform the context into a nonmutable
form.
"""
if self.e.__class__ == _MutableLinearExpression:
self.e.__class__ = LinearExpression
#: A context manager object for linear expressions.
#: This is an instance of the :class:`mutable_linear_contex <pyomo.core.expr.current.mutable_lienar_context>` context manager.
#: Different instances of this context manger are not necessary.
linear_expression = mutable_linear_context()
#-------------------------------------------------------
#
# Visitor Logic
#
#-------------------------------------------------------
class SimpleExpressionVisitor(object):
"""
Note:
This class is a customization of the PyUtilib :class:`SimpleVisitor
<pyutilib.misc.visitor.SimpleVisitor>` class that is tailored
to efficiently walk Pyomo expression trees. However, this class
is not a subclass of the PyUtilib :class:`SimpleVisitor
<pyutilib.misc.visitor.SimpleVisitor>` class because all key methods
are reimplemented.
"""
def visit(self, node): #pragma: no cover
"""
Visit a node in an expression tree and perform some operation on
it.
This method should be over-written by a user
that is creating a sub-class.
Args:
node: a node in an expression tree
Returns:
nothing
"""
pass
def finalize(self): #pragma: no cover
"""
Return the "final value" of the search.
The default implementation returns :const:`None`, because
the traditional visitor pattern does not return a value.
Returns:
The final value after the search. Default is :const:`None`.
"""
pass
def xbfs(self, node):
"""
Breadth-first search of an expression tree,
except that leaf nodes are immediately visited.
Note:
This method has the same functionality as the
PyUtilib :class:`SimpleVisitor.xbfs <pyutilib.misc.visitor.SimpleVisitor.xbfs>`
method. The difference is that this method
is tailored to efficiently walk Pyomo expression trees.
Args:
node: The root node of the expression tree that is searched.
Returns:
The return value is determined by the :func:`finalize` function,
which may be defined by the user. Defaults to :const:`None`.
"""
dq = deque([node])
while dq:
current = dq.popleft()
self.visit(current)
#for c in self.children(current):
for c in current.args:
#if self.is_leaf(c):
if c.__class__ in native_numeric_types or not c.is_expression() or c.nargs() == 0:
self.visit(c)
else:
dq.append(c)
return self.finalize()
def xbfs_yield_leaves(self, node):
"""
Breadth-first search of an expression tree, except that
leaf nodes are immediately visited.
Note:
This method has the same functionality as the
PyUtilib :class:`SimpleVisitor.xbfs_yield_leaves <pyutilib.misc.visitor.SimpleVisitor.xbfs_yield_leaves>`
method. The difference is that this method
is tailored to efficiently walk Pyomo expression trees.
Args:
node: The root node of the expression tree
that is searched.
Returns:
The return value is determined by the :func:`finalize` function,
which may be defined by the user. Defaults to :const:`None`.
"""
#
# If we start with a leaf, then yield it and stop iteration
#
if not node.__class__ in pyomo5_expression_types or node.nargs() == 0:
ans = self.visit(node)
if not ans is None:
yield ans
raise StopIteration
#
# Iterate through the tree.
#
dq = deque([node])
while dq:
current = dq.popleft()
#self.visit(current)
#for c in self.children(current):
for c in current.args:
#if self.is_leaf(c):
if c.__class__ in pyomo5_expression_types and c.nargs() > 0:
dq.append(c)
else:
ans = self.visit(c)
if not ans is None:
yield ans
class ExpressionValueVisitor(object):
"""
Note:
This class is a customization of the PyUtilib :class:`ValueVisitor
<pyutilib.misc.visitor.ValueVisitor>` class that is tailored
to efficiently walk Pyomo expression trees. However, this class
is not a subclass of the PyUtilib :class:`ValueVisitor
<pyutilib.misc.visitor.ValueVisitor>` class because all key methods
are reimplemented.
"""
def visit(self, node, values): #pragma: no cover
"""
Visit a node in a tree and compute its value using
the values of its children.
This method should be over-written by a user
that is creating a sub-class.
Args:
node: a node in a tree
values: a list of values of this node's children
Returns:
The *value* for this node, which is computed using :attr:`values`
"""
pass
def visiting_potential_leaf(self, node):
"""
Visit a node and return its value if it is a leaf.
Note:
This method needs to be over-written for a specific
visitor application.
Args:
node: a node in a tree
Returns:
A tuple: ``(flag, value)``. If ``flag`` is False,
then the node is not a leaf and ``value`` is :const:`None`.
Otherwise, ``value`` is the computed value for this node.
"""
raise RuntimeError("The visiting_potential_leaf method needs to be defined.")
def finalize(self, ans): #pragma: no cover
"""
This method defines the return value for the search methods
in this class.
The default implementation returns the value of the
initial node (aka the root node), because
this visitor pattern computes and returns value for each
node to enable the computation of this value.
Args:
ans: The final value computed by the search method.
Returns:
The final value after the search. Defaults to simply
returning :attr:`ans`.
"""
return ans
def dfs_postorder_stack(self, node):
"""
Perform a depth-first search in postorder using a stack
implementation.
Note:
This method has the same functionality as the
PyUtilib :class:`ValueVisitor.dfs_postorder_stack <pyutilib.misc.visitor.ValueVisitor.dfs_postorder_stack>`
method. The difference is that this method
is tailored to efficiently walk Pyomo expression trees.
Args:
node: The root node of the expression tree
that is searched.
Returns:
The return value is determined by the :func:`finalize` function,
which may be defined by the user.
"""
flag, value = self.visiting_potential_leaf(node)
if flag:
return value
#_stack = [ (node, self.children(node), 0, len(self.children(node)), [])]
_stack = [ (node, node._args_, 0, node.nargs(), [])]
#
# Iterate until the stack is empty
#
# Note: 1 is faster than True for Python 2.x
#
while 1:
#
# Get the top of the stack
# _obj Current expression object
# _argList The arguments for this expression objet
# _idx The current argument being considered
# _len The number of arguments
# _result The return values
#
_obj, _argList, _idx, _len, _result = _stack.pop()
#
# Iterate through the arguments
#
while _idx < _len:
_sub = _argList[_idx]
_idx += 1
flag, value = self.visiting_potential_leaf(_sub)
if flag:
_result.append( value )
else:
#
# Push an expression onto the stack
#
_stack.append( (_obj, _argList, _idx, _len, _result) )
_obj = _sub
#_argList = self.children(_sub)
_argList = _sub._args_
_idx = 0
_len = _sub.nargs()
_result = []
#
# Process the current node
#
ans = self.visit(_obj, _result)
if _stack:
#
# "return" the recursion by putting the return value on the end of the results stack
#
_stack[-1][-1].append( ans )
else:
return self.finalize(ans)
class ExpressionReplacementVisitor(object):
"""
Note:
This class is a customization of the PyUtilib :class:`ValueVisitor
<pyutilib.misc.visitor.ValueVisitor>` class that is tailored
to support replacement of sub-trees in a Pyomo expression
tree. However, this class is not a subclass of the PyUtilib
:class:`ValueVisitor <pyutilib.misc.visitor.ValueVisitor>`
class because all key methods are reimplemented.
"""
def __init__(self, memo=None):
"""
Contruct a visitor that is tailored to support the
replacement of sub-trees in a pyomo expression tree.
Args:
memo (dict): A dictionary mapping object ids to
objects. This dictionary has the same semantics as
the memo object used with ``copy.deepcopy``. Defaults
to None, which indicates that no user-defined
dictionary is used.
"""
if memo is None:
self.memo = {'__block_scope__': { id(None): False }}
else:
self.memo = memo
def visit(self, node, values):
"""
Visit and clone nodes that have been expanded.
Note:
This method normally does not need to be re-defined
by a user.
Args:
node: The node that will be cloned.
values (list): The list of child nodes that have been
cloned. These values are used to define the
cloned node.
Returns:
The cloned node. Default is to simply return the node.
"""
return node
def visiting_potential_leaf(self, node):
"""
Visit a node and return a cloned node if it is a leaf.
Note:
This method needs to be over-written for a specific
visitor application.
Args:
node: a node in a tree
Returns:
A tuple: ``(flag, value)``. If ``flag`` is False,
then the node is not a leaf and ``value`` is :const:`None`.
Otherwise, ``value`` is a cloned node.
"""
raise RuntimeError("The visiting_potential_leaf method needs to be defined.")
def finalize(self, ans):
"""
This method defines the return value for the search methods
in this class.
The default implementation returns the value of the
initial node (aka the root node), because
this visitor pattern computes and returns value for each
node to enable the computation of this value.
Args:
ans: The final value computed by the search method.
Returns:
The final value after the search. Defaults to simply
returning :attr:`ans`.
"""
return ans
def construct_node(self, node, values):
"""
Call the expression construct_node() method.
"""
return node.construct_node( tuple(values), self.memo )
def dfs_postorder_stack(self, node):
"""
Perform a depth-first search in postorder using a stack
implementation.
This method replaces subtrees. This method detects if the
:func:`visit` method returns a different object. If so, then
the node has been replaced and search process is adapted
to replace all subsequent parent nodes in the tree.
Note:
This method has the same functionality as the
PyUtilib :class:`ValueVisitor.dfs_postorder_stack <pyutilib.misc.visitor.ValueVisitor.dfs_postorder_stack>`
method that is tailored to support the
replacement of sub-trees in a Pyomo expression tree.
Args:
node: The root node of the expression tree
that is searched.
Returns:
The return value is determined by the :func:`finalize` function,
which may be defined by the user.
"""
flag, value = self.visiting_potential_leaf(node)
if flag:
return value
#_stack = [ (node, self.children(node), 0, len(self.children(node)), [])]
_stack = [ (node, node._args_, 0, node.nargs(), [False])]
#
# Iterate until the stack is empty
#
# Note: 1 is faster than True for Python 2.x
#
while 1:
#
# Get the top of the stack
# _obj Current expression object
# _argList The arguments for this expression objet
# _idx The current argument being considered
# _len The number of arguments
# _result The 'dirty' flag followed by return values
#
_obj, _argList, _idx, _len, _result = _stack.pop()
#
# Iterate through the arguments
#
while _idx < _len:
_sub = _argList[_idx]
_idx += 1
flag, value = self.visiting_potential_leaf(_sub)
if flag:
if id(value) != id(_sub):
_result[0] = True
_result.append( value )
else:
#
# Push an expression onto the stack
#
_stack.append( (_obj, _argList, _idx, _len, _result) )
_obj = _sub
#_argList = self.children(_sub)
_argList = _sub._args_
_idx = 0
_len = _sub.nargs()
_result = [False]
#
# Process the current node
#
# If the user has defined a visit() function in a
# subclass, then call that function. But if the user
# hasn't created a new class and we need to, then
# call the ExpressionReplacementVisitor.visit() function.
#
ans = self.visit(_obj, _result[1:])
if _result[0] and id(ans) == id(_obj):
ans = self.construct_node(_obj, _result[1:])
if _stack:
if _result[0]:
_stack[-1][-1][0] = True
#
# "return" the recursion by putting the return value on the end of the results stack
#
_stack[-1][-1].append( ans )
else:
return self.finalize(ans)
#-------------------------------------------------------
#
# Functions used to process expression trees
#
#-------------------------------------------------------
# =====================================================
# clone_expression
# =====================================================
class _CloneVisitor(ExpressionValueVisitor):
def __init__(self, clone_leaves=False, memo=None):
self.clone_leaves = clone_leaves
self.memo = memo
def visit(self, node, values):
""" Visit nodes that have been expanded """
return node.construct_node( tuple(values), self.memo )
def visiting_potential_leaf(self, node):
"""
Visiting a potential leaf.
Return True if the node is not expanded.
"""
if node.__class__ in native_numeric_types:
#
# Store a native or numeric object
#
return True, deepcopy(node, self.memo)
if node.__class__ not in pyomo5_expression_types:
#
# Store a kernel object that is cloned
#
if self.clone_leaves:
return True, deepcopy(node, self.memo)
else:
return True, node
if not self.clone_leaves and node.__class__ in pyomo5_named_expression_types:
#
# If we are not cloning leaves, then
# we don't copy the expression tree for a
# named expression.
#
return True, node
return False, None
def clone_expression(expr, memo=None, clone_leaves=True):
"""Function used to clone an expression.
Cloning is roughly equivalent to calling ``copy.deepcopy``.
However, the :attr:`clone_leaves` argument can be used to
clone only interior (i.e. non-leaf) nodes in the expression
tree. Note that named expression objects are treated as
leaves when :attr:`clone_leaves` is :const:`True`, and hence
those subexpressions are not cloned.
This function uses a non-recursive
logic, which makes it more scalable than the logic in
``copy.deepcopy``.
Args:
expr: The expression that will be cloned.
memo (dict): A dictionary mapping object ids to
objects. This dictionary has the same semantics as
the memo object used with ``copy.deepcopy``. Defaults
to None, which indicates that no user-defined
dictionary is used.
clone_leaves (bool): If True, then leaves are
cloned along with the rest of the expression.
Defaults to :const:`True`.
Returns:
The cloned expression.
"""
clone_counter_context._count += 1
if not memo:
memo = {'__block_scope__': { id(None): False }}
#
visitor = _CloneVisitor(clone_leaves=clone_leaves, memo=memo)
return visitor.dfs_postorder_stack(expr)
# =====================================================
# _sizeof_expression
# =====================================================
class _SizeVisitor(SimpleExpressionVisitor):
def __init__(self):
self.counter = 0
def visit(self, node):
self.counter += 1
def finalize(self):
return self.counter
def _sizeof_expression(expr):
"""
Return the number of nodes in the expression tree.
Args:
expr: The root node of an expression tree.
Returns:
A non-negative integer that is the number of
interior and leaf nodes in the expression tree.
"""
visitor = _SizeVisitor()
return visitor.xbfs(expr)
# =====================================================
# evaluate_expression
# =====================================================
class _EvaluationVisitor(ExpressionValueVisitor):
def visit(self, node, values):
""" Visit nodes that have been expanded """
return node._apply_operation(values)
def visiting_potential_leaf(self, node):
"""
Visiting a potential leaf.
Return True if the node is not expanded.
"""
if node.__class__ in native_numeric_types:
return True, node
if node.__class__ in pyomo5_variable_types:
return True, value(node)
if not node.is_expression():
return True, value(node)
return False, None
def evaluate_expression(exp, exception=True):
"""
Evaluate the value of the expression.
Args:
expr: The root node of an expression tree.
exception (bool): A flag that indicates whether
exceptions are raised. If this flag is
:const:`False`, then an exception that
occurs while evaluating the expression
is caught and the return value is :const:`None`.
Default is :const:`True`.
Returns:
A floating point value if the expression evaluates
normally, or :const:`None` if an exception occurs
and is caught.
"""
try:
visitor = _EvaluationVisitor()
return visitor.dfs_postorder_stack(exp)
except TemplateExpressionError:
if exception:
raise
return None
except ValueError:
if exception:
raise
return None
# =====================================================
# identify_variables
# =====================================================
class _VariableVisitor(SimpleExpressionVisitor):
def __init__(self, types):
self.seen = set()
if types.__class__ is set:
self.types = types
else:
self.types = set(types)
def visit(self, node):
if node.__class__ in self.types:
if id(node) in self.seen:
return
self.seen.add(id(node))
return node
def identify_components(expr, component_types):
"""
A generator that yields a sequence of nodes
in an expression tree that belong to a specified set.
Args:
expr: The root node of an expression tree.
component_types (set or list): A set of class
types that will be matched during the search.
Yields:
Each node that is found.
"""
#
# OPTIONS:
# component_types - set (or list) if class types to find
# in the expression.
#
visitor = _VariableVisitor(component_types)
for v in visitor.xbfs_yield_leaves(expr):
yield v
def identify_variables(expr, include_fixed=True):
"""
A generator that yields a sequence of variables
in an expression tree.
Args:
expr: The root node of an expression tree.
include_fixed (bool): If :const:`True`, then
this generator will yield variables whose
value is fixed. Defaults to :const:`True`.
Yields:
Each variable that is found.
"""
#
# OPTIONS:
# include_fixed - list includes fixed variables
#
visitor = _VariableVisitor(pyomo5_variable_types)
if include_fixed:
for v in visitor.xbfs_yield_leaves(expr):
yield v
else:
for v in visitor.xbfs_yield_leaves(expr):
if not v.is_fixed():
yield v
# =====================================================
# _polynomial_degree
# =====================================================
class _PolyDegreeVisitor(ExpressionValueVisitor):
def visit(self, node, values):
""" Visit nodes that have been expanded """
return node._compute_polynomial_degree(values)
def visiting_potential_leaf(self, node):
"""
Visiting a potential leaf.
Return True if the node is not expanded.
"""
if node.__class__ in native_types or not node.is_potentially_variable():
return True, 0
if not node.is_expression():
return True, 0 if node.is_fixed() else 1
return False, None
def _polynomial_degree(node):
"""
Return the polynomial degree of the expression.
Args:
node: The root node of an expression tree.
Returns:
A non-negative integer that is the polynomial
degree if the expression is polynomial, or :const:`None` otherwise.
"""
visitor = _PolyDegreeVisitor()
return visitor.dfs_postorder_stack(node)
# =====================================================
# _expression_is_fixed
# =====================================================
class _IsFixedVisitor(ExpressionValueVisitor):
"""
NOTE: This doesn't check if combiner logic is
all or any and short-circuit the test. It's
not clear that that is an important optimization.
"""