Skip to content

Commit 812686b

Browse files
committed
[decorators] finally behaviour
1 parent 6e97964 commit 812686b

11 files changed

+342
-2
lines changed

CHANGELOG.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ Release Notes
33

44
Forthcoming
55
-----------
6-
* ...
6+
* [decorators] a finally-style decorator, `#427 <https://github.com/splintered-reality/py_trees/pull/427>`_
77

88
2.2.3 (2023-02-08)
99
------------------

docs/demos.rst

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,22 @@ py-trees-demo-eternal-guard
147147
:linenos:
148148
:caption: py_trees/demos/eternal_guard.py
149149

150+
.. _py-trees-demo-finally-program:
151+
152+
py-trees-demo-finally
153+
---------------------
154+
155+
.. automodule:: py_trees.demos.decorator_finally
156+
:members:
157+
:special-members:
158+
:show-inheritance:
159+
:synopsis: demo the finally-like decorator
160+
161+
.. literalinclude:: ../py_trees/demos/decorator_finally.py
162+
:language: python
163+
:linenos:
164+
:caption: py_trees/demos/decorator_finally.py
165+
150166
.. _py-trees-demo-logging-program:
151167

152168
py-trees-demo-logging

docs/dot/demo-finally.dot

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
digraph pastafarianism {
2+
ordering=out;
3+
graph [fontname="times-roman"];
4+
node [fontname="times-roman"];
5+
edge [fontname="times-roman"];
6+
root [fillcolor=orange, fontcolor=black, fontsize=9, label="Ⓜ root", shape=box, style=filled];
7+
SetFlagFalse [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagFalse, shape=ellipse, style=filled];
8+
root -> SetFlagFalse;
9+
Parallel [fillcolor=gold, fontcolor=black, fontsize=9, label="Parallel\nSuccessOnOne", shape=parallelogram, style=filled];
10+
root -> Parallel;
11+
Counter [fillcolor=gray, fontcolor=black, fontsize=9, label=Counter, shape=ellipse, style=filled];
12+
Parallel -> Counter;
13+
Finally [fillcolor=ghostwhite, fontcolor=black, fontsize=9, label=Finally, shape=ellipse, style=filled];
14+
Parallel -> Finally;
15+
SetFlagTrue [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagTrue, shape=ellipse, style=filled];
16+
Finally -> SetFlagTrue;
17+
}

docs/images/finally.png

49.6 KB
Loading

py_trees/behaviour.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ def iterate(self, direct_descendants: bool = False) -> typing.Iterator[Behaviour
344344
yield child
345345
yield self
346346

347-
# TODO: better type refinement of 'viso=itor'
347+
# TODO: better type refinement of 'visitor'
348348
def visit(self, visitor: typing.Any) -> None:
349349
"""
350350
Introspect on this behaviour with a visitor.

py_trees/behaviours.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,7 @@ def update(self) -> common.Status:
280280
:data:`~py_trees.common.Status.RUNNING` while not expired, the given completion status otherwise
281281
"""
282282
self.counter += 1
283+
self.feedback_message = f"count: {self.counter}"
283284
if self.counter <= self.duration:
284285
return common.Status.RUNNING
285286
else:

py_trees/decorators.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
* :class:`py_trees.decorators.Condition`
3737
* :class:`py_trees.decorators.Count`
3838
* :class:`py_trees.decorators.EternalGuard`
39+
* :class:`py_trees.decorators.Finally`
3940
* :class:`py_trees.decorators.Inverter`
4041
* :class:`py_trees.decorators.OneShot`
4142
* :class:`py_trees.decorators.Repeat`
@@ -920,3 +921,89 @@ def update(self) -> common.Status:
920921
the behaviour's new status :class:`~py_trees.common.Status`
921922
"""
922923
return self.decorated.status
924+
925+
926+
class Finally(Decorator):
927+
"""
928+
Implement a 'finally'-like pattern with behaviours.
929+
930+
This implements a pattern
931+
Always return :data:`~py_trees.common.Status.RUNNING` and
932+
on :meth:`terminate`, call the child's :meth:`~py_trees.behaviour.Behaviour.update`
933+
method, once. The return status of the child is unused as both decorator
934+
and child will be in the process of terminating with status
935+
:data:`~py_trees.common.Status.INVALID`.
936+
937+
This decorator is usually used underneath a parallel with a sibling
938+
that represents the 'try' part of the behaviour.
939+
940+
.. code-block::
941+
942+
/_/ Parallel
943+
--> Work
944+
-^- Finally (Decorator)
945+
--> Finally (Implementation)
946+
947+
.. seealso:: :ref:`py-trees-demo-finally-program`
948+
949+
NB: If you need to persist the execution of the 'finally'-like block for more
950+
than a single tick, you'll need to build that explicitly into your tree. There
951+
are various ways of doing so (with and without the blackboard). One pattern
952+
that works:
953+
954+
.. code-block::
955+
956+
[o] Selector
957+
{-} Sequence
958+
--> Work
959+
--> Finally (Triggers on Success)
960+
{-} Sequence
961+
--> Finally (Triggers on Failure)
962+
--> Failure
963+
"""
964+
965+
def __init__(self, name: str, child: behaviour.Behaviour):
966+
"""
967+
Initialise with the standard decorator arguments.
968+
969+
Args:
970+
name: the decorator name
971+
child: the child to be decorated
972+
"""
973+
super(Finally, self).__init__(name=name, child=child)
974+
975+
def tick(self) -> typing.Iterator[behaviour.Behaviour]:
976+
"""
977+
Bypass the child when ticking.
978+
979+
Yields:
980+
a reference to itself
981+
"""
982+
self.logger.debug(f"{self.__class__.__name__}.tick()")
983+
self.status = self.update()
984+
yield self
985+
986+
def update(self):
987+
"""
988+
Return with :data:`~py_trees.common.Status.RUNNING`.
989+
990+
Returns:
991+
the behaviour's new status :class:`~py_trees.common.Status`
992+
"""
993+
return common.Status.RUNNING
994+
995+
def terminate(self, new_status: common.Status) -> None:
996+
"""Tick the child behaviour once."""
997+
self.logger.debug(
998+
"{}.terminate({})".format(
999+
self.__class__.__name__,
1000+
"{}->{}".format(self.status, new_status)
1001+
if self.status != new_status
1002+
else f"{new_status}",
1003+
)
1004+
)
1005+
if new_status == common.Status.INVALID:
1006+
self.decorated.tick_once()
1007+
# Do not need to stop the child here - this method
1008+
# is only called by Decorator.stop() which will handle
1009+
# that responsibility immediately after this method returns.

py_trees/demos/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from . import display_modes # usort:skip # noqa: F401
2222
from . import dot_graphs # usort:skip # noqa: F401
2323
from . import either_or # usort:skip # noqa: F401
24+
from . import decorator_finally # usort:skip # noqa: F401
2425
from . import lifecycle # usort:skip # noqa: F401
2526
from . import selector # usort:skip # noqa: F401
2627
from . import sequence # usort:skip # noqa: F401

py_trees/demos/decorator_finally.py

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
#!/usr/bin/env python
2+
#
3+
# License: BSD
4+
# https://raw.githubusercontent.com/splintered-reality/py_trees/devel/LICENSE
5+
#
6+
##############################################################################
7+
# Documentation
8+
##############################################################################
9+
10+
"""
11+
Trigger 'finally'-like behaviour with :class:`~py_trees.decorators.Finally`.
12+
13+
.. argparse::
14+
:module: py_trees.demos.decorator_finally
15+
:func: command_line_argument_parser
16+
:prog: py-trees-demo-finally
17+
18+
.. graphviz:: dot/demo-finally.dot
19+
20+
.. image:: images/finally.png
21+
22+
"""
23+
24+
##############################################################################
25+
# Imports
26+
##############################################################################
27+
28+
import argparse
29+
import sys
30+
import typing
31+
32+
import py_trees
33+
import py_trees.console as console
34+
35+
##############################################################################
36+
# Classes
37+
##############################################################################
38+
39+
40+
def description(root: py_trees.behaviour.Behaviour) -> str:
41+
"""
42+
Print description and usage information about the program.
43+
44+
Returns:
45+
the program description string
46+
"""
47+
content = (
48+
"Trigger python-like 'finally' behaviour with the 'Finally' decorator.\n\n"
49+
)
50+
content += "A blackboard flag is set to false prior to commencing work. \n"
51+
content += "Once the work terminates, the decorator and it's child\n"
52+
content += "child will also terminate and toggle the flag to true.\n"
53+
content += "\n"
54+
content += "The demonstration is run twice - on the first occasion\n"
55+
content += "the work terminates with SUCCESS and on the second, it\n"
56+
content + "terminates with FAILURE\n"
57+
content += "\n"
58+
content += "EVENTS\n"
59+
content += "\n"
60+
content += " - 1 : flag is set to false, worker is running\n"
61+
content += " - 2 : worker completes (with SUCCESS||FAILURE)\n"
62+
content += " - 2 : finally is triggered, flag is set to true\n"
63+
content += "\n"
64+
if py_trees.console.has_colours:
65+
banner_line = console.green + "*" * 79 + "\n" + console.reset
66+
s = banner_line
67+
s += console.bold_white + "Finally".center(79) + "\n" + console.reset
68+
s += banner_line
69+
s += "\n"
70+
s += content
71+
s += "\n"
72+
s += banner_line
73+
else:
74+
s = content
75+
return s
76+
77+
78+
def epilog() -> typing.Optional[str]:
79+
"""
80+
Print a noodly epilog for --help.
81+
82+
Returns:
83+
the noodly message
84+
"""
85+
if py_trees.console.has_colours:
86+
return (
87+
console.cyan
88+
+ "And his noodly appendage reached forth to tickle the blessed...\n"
89+
+ console.reset
90+
)
91+
else:
92+
return None
93+
94+
95+
def command_line_argument_parser() -> argparse.ArgumentParser:
96+
"""
97+
Process command line arguments.
98+
99+
Returns:
100+
the argument parser
101+
"""
102+
parser = argparse.ArgumentParser(
103+
description=description(create_root(py_trees.common.Status.SUCCESS)),
104+
epilog=epilog(),
105+
formatter_class=argparse.RawDescriptionHelpFormatter,
106+
)
107+
group = parser.add_mutually_exclusive_group()
108+
group.add_argument(
109+
"-r", "--render", action="store_true", help="render dot tree to file"
110+
)
111+
return parser
112+
113+
114+
def create_root(
115+
expected_work_termination_result: py_trees.common.Status,
116+
) -> py_trees.behaviour.Behaviour:
117+
"""
118+
Create the root behaviour and it's subtree.
119+
120+
Returns:
121+
the root behaviour
122+
"""
123+
root = py_trees.composites.Sequence(name="root", memory=True)
124+
set_flag_to_false = py_trees.behaviours.SetBlackboardVariable(
125+
name="SetFlagFalse",
126+
variable_name="flag",
127+
variable_value=False,
128+
overwrite=True,
129+
)
130+
set_flag_to_true = py_trees.behaviours.SetBlackboardVariable(
131+
name="SetFlagTrue", variable_name="flag", variable_value=True, overwrite=True
132+
)
133+
parallel = py_trees.composites.Parallel(
134+
name="Parallel",
135+
policy=py_trees.common.ParallelPolicy.SuccessOnOne(),
136+
children=[],
137+
)
138+
worker = py_trees.behaviours.TickCounter(
139+
name="Counter", duration=1, completion_status=expected_work_termination_result
140+
)
141+
well_finally = py_trees.decorators.Finally(name="Finally", child=set_flag_to_true)
142+
parallel.add_children([worker, well_finally])
143+
root.add_children([set_flag_to_false, parallel])
144+
return root
145+
146+
147+
##############################################################################
148+
# Main
149+
##############################################################################
150+
151+
152+
def main() -> None:
153+
"""Entry point for the demo script."""
154+
args = command_line_argument_parser().parse_args()
155+
# py_trees.logging.level = py_trees.logging.Level.DEBUG
156+
print(description(create_root(py_trees.common.Status.SUCCESS)))
157+
158+
####################
159+
# Rendering
160+
####################
161+
if args.render:
162+
py_trees.display.render_dot_tree(create_root(py_trees.common.Status.SUCCESS))
163+
sys.exit()
164+
165+
for status in (py_trees.common.Status.SUCCESS, py_trees.common.Status.FAILURE):
166+
py_trees.blackboard.Blackboard.clear()
167+
console.banner(f"Experiment - Terminate with {status}")
168+
root = create_root(status)
169+
root.tick_once()
170+
print(py_trees.display.unicode_tree(root=root, show_status=True))
171+
print(py_trees.display.unicode_blackboard())
172+
root.tick_once()
173+
print(py_trees.display.unicode_tree(root=root, show_status=True))
174+
print(py_trees.display.unicode_blackboard())
175+
176+
print("\n")

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ py-trees-demo-display-modes = "py_trees.demos.display_modes:main"
6666
py-trees-demo-dot-graphs = "py_trees.demos.dot_graphs:main"
6767
py-trees-demo-either-or = "py_trees.demos.either_or:main"
6868
py-trees-demo-eternal-guard = "py_trees.demos.eternal_guard:main"
69+
py-trees-demo-finally = "py_trees.demos.decorator_finally:main"
6970
py-trees-demo-logging = "py_trees.demos.logging:main"
7071
py-trees-demo-pick-up-where-you-left-off = "py_trees.demos.pick_up_where_you_left_off:main"
7172
py-trees-demo-selector = "py_trees.demos.selector:main"

0 commit comments

Comments
 (0)