/
visitor.py
1673 lines (1402 loc) · 57.6 KB
/
visitor.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 (c) 2008-2024
# 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 inspect
import logging
import sys
from copy import deepcopy
from collections import deque
logger = logging.getLogger('pyomo.core')
from pyomo.common.deprecation import deprecated, deprecation_warning
from pyomo.common.errors import DeveloperError, TemplateExpressionError
from pyomo.common.numeric_types import (
nonpyomo_leaf_types,
native_types,
native_numeric_types,
value,
)
import pyomo.core.expr.expr_common as common
from pyomo.core.expr.symbol_map import SymbolMap
try:
# sys._getframe is slightly faster than inspect's currentframe, but
# is not guaranteed to exist everywhere
currentframe = sys._getframe
except AttributeError:
currentframe = inspect.currentframe
def get_stack_depth():
n = -1 # skip *this* frame in the count
f = currentframe()
while f is not None:
n += 1
f = f.f_back
return n
# For efficiency, we want to run recursively, but don't want to hit
# Python's recursion limit (because that would be difficult to recover
# from cleanly). However, there is a non-trivial cost to determine the
# current stack depth - and we don't want to hit that for every call.
# Instead, we will assume that the walker is always called with at
# least RECURSION_LIMIT frames available on the stack. When we hit the
# end of that limit, we will actually check how much space is left on
# the stack and run recursively until only 2*RECURSION_LIMIT frames are
# left. For the vast majority of well-formed expressions this approach
# avoids a somewhat costly call to get_stack_depth, but still catches
# the vast majority of cases that could generate a recursion error.
RECURSION_LIMIT = 50
class RevertToNonrecursive(Exception):
pass
# NOTE: This module also has dependencies on numeric_expr; however, to
# avoid circular dependencies, we will NOT import them here. Instead,
# until we can resolve the circular dependencies, they will be injected
# into this module by the .current module (which must be imported
# *after* numeric_expr, logocal_expr, and this module.
# -------------------------------------------------------
#
# Visitor Logic
#
# -------------------------------------------------------
class StreamBasedExpressionVisitor(object):
"""This class implements a generic stream-based expression walker.
This visitor walks an expression tree using a depth-first strategy
and generates a full event stream similar to other tree visitors
(e.g., the expat XML parser). The following events are triggered
through callback functions as the traversal enters and leaves nodes
in the tree:
::
initializeWalker(expr) -> walk, result
enterNode(N1) -> args, data
{for N2 in args:}
beforeChild(N1, N2) -> descend, child_result
enterNode(N2) -> N2_args, N2_data
[...]
exitNode(N2, n2_data) -> child_result
acceptChildResult(N1, data, child_result) -> data
afterChild(N1, N2) -> None
exitNode(N1, data) -> N1_result
finalizeWalker(result) -> result
Individual event callbacks match the following signatures:
walk, result = initializeWalker(self, expr):
initializeWalker() is called to set the walker up and perform
any preliminary processing on the root node. The method returns
a flag indicating if the tree should be walked and a result. If
`walk` is True, then result is ignored. If `walk` is False,
then `result` is returned as the final result from the walker,
bypassing all other callbacks (including finalizeResult).
args, data = enterNode(self, node):
enterNode() is called when the walker first enters a node (from
above), and is passed the node being entered. It is expected to
return a tuple of child `args` (as either a tuple or list) and a
user-specified data structure for collecting results. If None
is returned for args, the node's args attribute is used for
expression types and the empty tuple for leaf nodes. Returning
None is equivalent to returning (None,None). If the callback is
not defined, the default behavior is equivalent to returning
(None, []).
node_result = exitNode(self, node, data):
exitNode() is called after the node is completely processed (as
the walker returns up the tree to the parent node). It is
passed the node and the results data structure (defined by
enterNode() and possibly further modified by
acceptChildResult()), and is expected to return the "result" for
this node. If not specified, the default action is to return
the data object from enterNode().
descend, child_result = beforeChild(self, node, child, child_idx):
beforeChild() is called by a node for every child before
entering the child node. The node, child node, and child index
(position in the args list from enterNode()) are passed as
arguments. beforeChild should return a tuple (descend,
child_result). If descend is False, the child node will not be
entered and the value returned to child_result will be passed to
the node's acceptChildResult callback. Returning None is
equivalent to (True, None). The default behavior if not
specified is equivalent to (True, None).
data = acceptChildResult(self, node, data, child_result, child_idx):
acceptChildResult() is called for each child result being
returned to a node. This callback is responsible for recording
the result for later processing or passing up the tree. It is
passed the node, result data structure (see enterNode()), child
result, and the child index (position in args from enterNode()).
The data structure (possibly modified or replaced) must be
returned. If acceptChildResult is not specified, it does
nothing if data is None, otherwise it calls data.append(result).
afterChild(self, node, child, child_idx):
afterChild() is called by a node for every child node
immediately after processing the node is complete before control
moves to the next child or up to the parent node. The node,
child node, an child index (position in args from enterNode())
are passed, and nothing is returned. If afterChild is not
specified, no action takes place.
finalizeResult(self, result):
finalizeResult() is called once after the entire expression tree
has been walked. It is passed the result returned by the root
node exitNode() callback. If finalizeResult is not specified,
the walker returns the result obtained from the exitNode
callback on the root node.
Clients interact with this class by either deriving from it and
implementing the necessary callbacks (see above), assigning callable
functions to an instance of this class, or passing the callback
functions as arguments to this class' constructor.
"""
# The list of event methods that can either be implemented by
# derived classes or specified as callback functions to the class
# constructor.
#
# This is a dict mapping the callback name to a single character
# that we can use to classify the set of callbacks used by a
# particular Visitor (we define special-purpose node processors for
# certain common combinations). For example, a 'bex' visitor is one
# that supports beforeChild, enterNode, and exitNode, but NOT
# afterChild or acceptChildResult.
client_methods = {
'enterNode': 'e',
'exitNode': 'x',
'beforeChild': 'b',
'afterChild': 'a',
'acceptChildResult': 'c',
'initializeWalker': '',
'finalizeResult': '',
}
def __init__(self, **kwds):
# This is slightly tricky: We want derived classes to be able to
# override the "None" defaults here, and for keyword arguments
# to override both. The hasattr check prevents the "None"
# defaults from overriding attributes or methods defined on
# derived classes.
for field in self.client_methods:
if field in kwds:
setattr(self, field, kwds.pop(field))
elif not hasattr(self, field):
setattr(self, field, None)
if kwds:
raise RuntimeError("Unrecognized keyword arguments: %s" % (kwds,))
# Handle deprecated APIs
_fcns = (('beforeChild', 2), ('acceptChildResult', 3), ('afterChild', 2))
for name, nargs in _fcns:
fcn = getattr(self, name)
if fcn is None:
continue
_args = inspect.getfullargspec(fcn)
_self_arg = 1 if inspect.ismethod(fcn) else 0
if len(_args.args) == nargs + _self_arg and _args.varargs is None:
deprecation_warning(
"Note that the API for the StreamBasedExpressionVisitor "
"has changed to include the child index for the %s() "
"method. Please update your walker callbacks." % (name,),
version='5.7.0',
)
def wrap(fcn, nargs):
def wrapper(*args):
return fcn(*args[:nargs])
return wrapper
setattr(self, name, wrap(fcn, nargs))
self.recursion_stack = None
# Set up the custom recursive node handler function (customized
# for the specific set of callbacks that are defined for this
# class instance).
recursive_node_handler = '_process_node_' + ''.join(
sorted(
'' if getattr(self, f[0]) is None else f[1]
for f in self.client_methods.items()
)
)
self._process_node = getattr(
self, recursive_node_handler, self._process_node_general
)
def walk_expression(self, expr):
"""Walk an expression, calling registered callbacks.
This is the standard interface for running the visitor. It
defaults to using an efficient recursive implementation of the
visitor, falling back on :py:meth:`walk_expression_nonrecursive`
if the recursion stack gets too deep.
"""
if self.initializeWalker is not None:
walk, root = self.initializeWalker(expr)
if not walk:
return root
elif root is None:
root = expr
else:
root = expr
try:
result = self._process_node(root, RECURSION_LIMIT)
_nonrecursive = None
except RevertToNonrecursive:
ptr = (None,) + self.recursion_stack.pop()
while self.recursion_stack:
ptr = (ptr,) + self.recursion_stack.pop()
self.recursion_stack = None
_nonrecursive = self._nonrecursive_walker_loop, ptr
except RecursionError:
logger.warning(
'Unexpected RecursionError walking an expression tree.',
extra={'id': 'W1003'},
)
_nonrecursive = self.walk_expression_nonrecursive, expr
if _nonrecursive is not None:
return _nonrecursive[0](_nonrecursive[1])
if self.finalizeResult is not None:
return self.finalizeResult(result)
else:
return result
def _compute_actual_recursion_limit(self):
recursion_limit = (
sys.getrecursionlimit() - get_stack_depth() - 2 * RECURSION_LIMIT
)
if recursion_limit <= RECURSION_LIMIT:
self.recursion_stack = []
raise RevertToNonrecursive()
return recursion_limit
def _process_node_general(self, node, recursion_limit):
"""Recursive routine for processing nodes with general callbacks
This is the "general" implementation of the
StreamBasedExpressionVisitor node processor that can handle any
combination of registered callback functions.
"""
if not recursion_limit:
recursion_limit = self._compute_actual_recursion_limit()
else:
recursion_limit -= 1
if self.enterNode is not None:
tmp = self.enterNode(node)
if tmp is None:
args = data = None
else:
args, data = tmp
else:
args = None
data = []
if args is None:
if type(node) in nonpyomo_leaf_types or not node.is_expression_type():
args = ()
else:
args = node.args
# Because we do not require the args to be a context manager, we
# will mock up the "with args" using a try-finally.
context_manager = hasattr(args, '__enter__')
if context_manager:
args.__enter__()
try:
descend = True
child_idx = -1
# Note: this relies on iter(iterator) returning the
# iterator. This seems to hold for all common iterators
# (list, tuple, generator, etc)
arg_iter = iter(args)
for child in arg_iter:
child_idx += 1
if self.beforeChild is not None:
tmp = self.beforeChild(node, child, child_idx)
if tmp is None:
descend = True
else:
descend, child_result = tmp
if descend:
child_result = self._process_node(child, recursion_limit)
if self.acceptChildResult is not None:
data = self.acceptChildResult(node, data, child_result, child_idx)
elif data is not None:
data.append(child_result)
if self.afterChild is not None:
self.afterChild(node, child, child_idx)
except RevertToNonrecursive:
self._recursive_frame_to_nonrecursive_stack(locals())
context_manager = False
raise
finally:
if context_manager:
args.__exit__(None, None, None)
# We are done with this node. Call exitNode to compute
# any result
if self.exitNode is not None:
return self.exitNode(node, data)
else:
return data
def _process_node_bex(self, node, recursion_limit):
"""Recursive routine for processing nodes with only 'bex' callbacks
This is a special-case implementation of the "general"
StreamBasedExpressionVisitor node processor for the case that
only beforeChild, enterNode, and exitNode are defined (see
also the definition of the client_methods dict).
"""
if not recursion_limit:
recursion_limit = self._compute_actual_recursion_limit()
else:
recursion_limit -= 1
tmp = self.enterNode(node)
if tmp is None:
args = data = None
else:
args, data = tmp
if args is None:
if type(node) in nonpyomo_leaf_types or not node.is_expression_type():
args = ()
else:
args = node.args
# Because we do not require the args to be a context manager, we
# will mock up the "with args" using a try-finally.
context_manager = hasattr(args, '__enter__')
if context_manager:
args.__enter__()
try:
child_idx = -1
# Note: this relies on iter(iterator) returning the
# iterator. This seems to hold for all common iterators
# (list, tuple, generator, etc)
arg_iter = iter(args)
for child in arg_iter:
child_idx += 1
tmp = self.beforeChild(node, child, child_idx)
if tmp is None:
descend = True
else:
descend, child_result = tmp
if descend:
data.append(self._process_node(child, recursion_limit))
else:
data.append(child_result)
except RevertToNonrecursive:
self._recursive_frame_to_nonrecursive_stack(locals())
context_manager = False
raise
finally:
if context_manager:
args.__exit__(None, None, None)
# We are done with this node. Call exitNode to compute
# any result
return self.exitNode(node, data)
def _process_node_bx(self, node, recursion_limit):
"""Recursive routine for processing nodes with only 'bx' callbacks
This is a special-case implementation of the "general"
StreamBasedExpressionVisitor node processor for the case that
only beforeChild and exitNode are defined (see also the
definition of the client_methods dict).
"""
if not recursion_limit:
recursion_limit = self._compute_actual_recursion_limit()
else:
recursion_limit -= 1
if type(node) in nonpyomo_leaf_types or not node.is_expression_type():
args = ()
else:
args = node.args
data = []
try:
child_idx = -1
# Note: this relies on iter(iterator) returning the
# iterator. This seems to hold for all common iterators
# (list, tuple, generator, etc)
arg_iter = iter(args)
for child in arg_iter:
child_idx += 1
tmp = self.beforeChild(node, child, child_idx)
if tmp is None:
descend = True
else:
descend, child_result = tmp
if descend:
data.append(self._process_node(child, recursion_limit))
else:
data.append(child_result)
except RevertToNonrecursive:
self._recursive_frame_to_nonrecursive_stack(locals())
raise
finally:
pass
# We are done with this node. Call exitNode to compute
# any result
return self.exitNode(node, data)
def _recursive_frame_to_nonrecursive_stack(self, local):
child_idx = local['child_idx']
_arg_list = [None] * child_idx
_arg_list.append(local['child'])
_arg_list.extend(local['arg_iter'])
if not self.recursion_stack:
# For the deepest stack frame, the recursion limit hit
# as we started to enter the child. As we haven't
# started processing it yet, we need to decrement
# child_idx so that it is revisited
child_idx -= 1
self.recursion_stack.append(
(local['node'], _arg_list, len(_arg_list) - 1, local['data'], child_idx)
)
def walk_expression_nonrecursive(self, expr):
"""Nonrecursively walk an expression, calling registered callbacks.
This routine is safer than the recursive walkers for deep (or
unbalanced) trees. It is, however, slightly slower than the
recursive implementations.
"""
#
# This walker uses a linked list to store the stack (instead of
# an array). The nodes of the linked list are 6-member tuples:
#
# ( pointer to parent,
# expression node,
# tuple/list of child nodes (arguments),
# number of child nodes (arguments),
# data object to aggregate results from child nodes,
# current child node index )
#
# The walker only needs a single pointer to the end of the list
# (ptr). The beginning of the list is indicated by a None
# parent pointer.
#
if self.initializeWalker is not None:
walk, result = self.initializeWalker(expr)
if not walk:
return result
elif result is not None:
expr = result
if self.enterNode is not None:
tmp = self.enterNode(expr)
if tmp is None:
args = data = None
else:
args, data = tmp
else:
args = None
data = []
if args is None:
if type(expr) in nonpyomo_leaf_types or not expr.is_expression_type():
args = ()
else:
args = expr.args
if hasattr(args, '__enter__'):
args.__enter__()
node = expr
# Note that because we increment child_idx just before fetching
# the child node, it must be initialized to -1, and ptr[3] must
# always be *one less than* the number of arguments
return self._nonrecursive_walker_loop(
(None, node, args, len(args) - 1, data, -1)
)
def _nonrecursive_walker_loop(self, ptr):
_, node, args, _, data, child_idx = ptr
try:
while 1:
if child_idx < ptr[3]:
# Increment the child index pointer here for
# consistency. Note that this means that for the bulk
# of the time, 'child_idx' will not match the value of
# ptr[5]. This provides a modest performance
# improvement, as we only have to recreate the ptr tuple
# just before we descend further into the tree (i.e., we
# avoid recreating the tuples for the special case where
# beforeChild indicates that we should not descend
# further).
child_idx += 1
# This node still has children to process
child = ptr[2][child_idx]
# Notify this node that we are about to descend into a
# child.
if self.beforeChild is not None:
tmp = self.beforeChild(node, child, child_idx)
if tmp is None:
descend = True
child_result = None
else:
descend, child_result = tmp
if not descend:
# We are aborting processing of this child node.
# Tell this node to accept the child result and
# we will move along
if self.acceptChildResult is not None:
data = self.acceptChildResult(
node, data, child_result, child_idx
)
elif data is not None:
data.append(child_result)
# And let the node know that we are done with a
# child node
if self.afterChild is not None:
self.afterChild(node, child, child_idx)
# Jump to the top to continue processing the
# next child node
continue
# Update the child argument counter in the stack.
# Because we are using tuples, we need to recreate the
# "ptr" object (linked list node)
ptr = ptr[:4] + (data, child_idx)
# We are now going to actually enter this node. The
# node will tell us the list of its child nodes that we
# need to process
if self.enterNode is not None:
tmp = self.enterNode(child)
if tmp is None:
args = data = None
else:
args, data = tmp
else:
args = None
data = []
if args is None:
if (
type(child) in nonpyomo_leaf_types
or not child.is_expression_type()
):
# Leaves (either non-pyomo types or
# non-Expressions) have no child arguments, so
# are just put on the stack
args = ()
else:
args = child.args
if hasattr(args, '__enter__'):
args.__enter__()
node = child
child_idx = -1
ptr = (ptr, node, args, len(args) - 1, data, child_idx)
else: # child_idx == ptr[3]:
# We are done with this node. Call exitNode to compute
# any result
if hasattr(ptr[2], '__exit__'):
ptr[2].__exit__(None, None, None)
if self.exitNode is not None:
node_result = self.exitNode(node, data)
else:
node_result = data
# Pop the node off the linked list
ptr = ptr[0]
# If we have returned to the beginning, return the final
# answer
if ptr is None:
if self.finalizeResult is not None:
return self.finalizeResult(node_result)
else:
return node_result
# Not done yet, update node to point to the new active
# node
node, child = ptr[1], node
data = ptr[4]
child_idx = ptr[5]
# We need to alert the node to accept the child's result:
if self.acceptChildResult is not None:
data = self.acceptChildResult(
node, data, node_result, child_idx
)
elif data is not None:
data.append(node_result)
# And let the node know that we are done with a child node
if self.afterChild is not None:
self.afterChild(node, child, child_idx)
finally:
while ptr is not None:
if hasattr(ptr[2], '__exit__'):
ptr[2].__exit__(None, None, None)
ptr = ptr[0]
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 nonpyomo_leaf_types
or not c.is_expression_type()
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 (
node.__class__ in nonpyomo_leaf_types
or not node.is_expression_type()
or node.nargs() == 0
):
ans = self.visit(node)
if not ans is None:
yield ans
return
#
# 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 nonpyomo_leaf_types
or not c.is_expression_type()
or c.nargs() == 0
):
ans = self.visit(c)
if not ans is None:
yield ans
else:
dq.append(c)
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): # pragma: no cover
"""
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 self.finalize(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 object
# _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)
def replace_expressions(
expr,
substitution_map,
descend_into_named_expressions=True,
remove_named_expressions=True,
):
"""
Parameters
----------
expr : Pyomo expression
The source expression
substitution_map : dict
A dictionary mapping object ids in the source to the replacement objects.
descend_into_named_expressions : bool
True if replacement should go into named expression objects, False to halt at
a named expression
remove_named_expressions : bool
True if the named expressions should be replaced with a standard expression,
and False if the named expression should be left in place
Returns
-------
Pyomo expression : returns the new expression object
"""
return ExpressionReplacementVisitor(
substitute=substitution_map,
descend_into_named_expressions=descend_into_named_expressions,
remove_named_expressions=remove_named_expressions,
).walk_expression(expr)
class ExpressionReplacementVisitor(StreamBasedExpressionVisitor):
def __init__(
self,
substitute=None,
descend_into_named_expressions=True,
remove_named_expressions=True,
):
if substitute is None:
substitute = {}
# Note: preserving the attribute names from the previous
# implementation of the expression walker.
self.substitute = substitute
self.enter_named_expr = descend_into_named_expressions
self.rm_named_expr = remove_named_expressions
kwds = {}
if hasattr(self, 'visiting_potential_leaf'):
deprecation_warning(
"ExpressionReplacementVisitor: this walker has been ported "
"to derive from StreamBasedExpressionVisitor. "
"visiting_potential_leaf() has been replaced by beforeChild()"
"(note to implementers: the sense of the bool return value "
"has been inverted).",