async_btree


Nameasync_btree JSON
Version 1.3.0 PyPI version JSON
download
home_pagehttps://pypi.org/project/async_btree
SummaryAsync behavior tree
upload_time2023-10-07 09:22:10
maintainer
docs_urlNone
authorJerome Guibert
requires_python>=3.8,<3.12
licenseMIT
keywords behavior-tree asyncio
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Async Behaviour Tree for Python


[![Unix Build Status](https://img.shields.io/travis/geronimo-iia/async-btree/master.svg?label=unix)](https://travis-ci.com/geronimo-iia/async-btree)
[![Coverage Status](https://img.shields.io/coveralls/geronimo-iia/async-btree/master.svg)](https://coveralls.io/r/geronimo-iia/async-btree)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/fe669a02b4aa46b5b1faf619ba2bf382)](https://www.codacy.com/app/geronimo-iia/async-btree?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=geronimo-iia/async-btree&amp;utm_campaign=Badge_Grade)
[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/geronimo-iia/async-btree.svg)](https://scrutinizer-ci.com/g/geronimo-iia/async-btree/?branch=master)
[![PyPI Version](https://img.shields.io/pypi/v/async-btree.svg)](https://pypi.org/project/async-btree)
[![PyPI License](https://img.shields.io/pypi/l/async-btree.svg)](https://pypi.org/project/async-btree)

Versions following [Semantic Versioning](https://semver.org/)

See [documentation](https://geronimo-iia.github.io/async-btree).


## Overview


### What's a behavior tree ?

> Unlike a Finite State Machine, a Behaviour Tree is a tree of hierarchical nodes that controls the flow of decision and the execution of "tasks" or, as we will call them further, "Actions".
> -- <cite>[behaviortree](https://www.behaviortree.dev/bt_basics/)</cite>

If your new (or not) about behavior tree, you could spend some time on this few links:

- [Behavior trees for AI: How they work](https://www.gamasutra.com/blogs/ChrisSimpson/20140717/221339/Behavior_trees_for_AI_How_they_work.php) by Chris Simpson
- [Introduction to BTs](https://www.behaviortree.dev/bt_basics/)

Few implementation libraries:

- [task_behavior_engine](https://github.com/ToyotaResearchInstitute/task_behavior_engine) A behavior tree based task engine written in Python
- [pi_trees](https://github.com/pirobot/pi_trees/) a Python/ROS library for implementing Behavior Trees
- [pr_behavior_tree](https://github.com/personalrobotics/pr_behavior_tree) A simple python behavior tree library based on coroutines
- [btsk](https://github.com/aigamedev/btsk) Behavior Tree Starter Kit
- [behave](https://github.com/fuchen/behave) A behavior tree implementation in Python


### Why another library so ?

__SIMPLICITY__

When you study behavior tree implementation, reactive node, dynamic change, runtime execution, etc ...
At a moment you're build more or less something that mimic an evaluator 'eval/apply' or a compilator, with a complex hierachical set of class.

All complexity came with internal state management, using tree of blackboard to avoid global variable, multithreading issue, maybe few callback etc ...

This break the simplicity and beauty of your initial design.

What I find usefull with behavior tree:

- clarity of expression
- node tree representation
- possibility to reuse behavior
- add external measure to dynamicaly change a behavior, a first step on observable pattern...

As I've used OOP for years (very long time), I will try to avoid class tree and prefer using the power of functionnal programming to obtain what I want: add metadata on a sematic construction, deal with closure, use function in parameters or in return value...

And a last reason, more personal, it that i would explore python expressivity.

__SO HOW ?__

In this module, I purpose you to use the concept of coroutines, and their mecanisms to manage the execution flow.
By this way:

- we reuse simple language idiom to manage state, parameter, etc
- no design constraint on action implementation
- most of language build block could be reused

You could build expression like this:

```python

async def a_func():
    """A great function"""
    return "a"

async def b_decorator(child_value, other=""):
    """A great decorator..."""
    return f"b{child_value}{other}"

assert run(decorate(a_func, b_decorator)) == "ba"

```
This expression apply ```b_decorator``` on function ```a_func```. 
Note that ```decorate(a_func, b_decorator)``` is not an async function, only action, or condition are async function.


Few guidelines of this implementation:

- In order to mimic all NodeStatus (success, failure, running), I replace this by truthy/falsy meaning of evaluation value.
  A special dedicated exception decorate standard exception in order to give them a Falsy meaning (`ControlFlowException`).
  By default, exception are raised like happen usually until you catch them.
- Blackboard pattern, act as a manager of context variable for behavior tree.
  With python 3, please... simply use [contextvars](https://docs.python.org/3/library/contextvars.html) !
- In order to be able to build a sematic tree, I've introduce a metadata tuple added on function implementation.

The rest is just implementation details..



A little note:

> You should not use this until you're ready to think about what you're doing :)


### Note about 'async' framework

As we use async function as underlaying mechanism to manage the execution flow, the standard library asyncio is pretty fine.
But, (always a but somewhere isn't it...), you should read this [amazing blog post](https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/) by Nathaniel J. Smith.
And next study [curio](https://github.com/dabeaz/curio) framework in deep.

As curio say:
> Don't Use Curio if You're Allergic to Curio

Personaly, after few time of testing and reading curio code, I'm pretty addict.

If `curio` is not present, we default to `asyncio`.

## Installation

Install this library directly into an activated virtual environment with pip or [Poetry](https://poetry.eustace.io/) :

 - `python -m pip install async-btree` or '`poetry add async-btree`
 - with with curio extention: `python -m pip install async-btree[curio]` or '`poetry add async-btree[curio]`


## Usage

After installation, the package can imported:

```text
$ python
>>> import async_btree
>>> async_btree.__version__
```

See [API Reference documentation](https://geronimo-iia.github.io/async-btree).


With this framework, you didn't find any configuration file, no Xml, no json, no yaml.

The main reason (oriented and personal point of view) is that you did not need to introduce an extra level of abtraction 
to declare a composition of functions. I think it's true for most of main use case (except using an editor to wrote behaviour tree for example).

So "If you wrote your function with python, wrote composition in python"... 
_(remember that you did not need XML to do SQL, just write good sql...)_


So, the goal is to:
 - define your business function wich implements actions or conditions, with all test case that you wish/need
 - compose them using those provided by this framework like ```sequence```, ```selector```, ...
 - use them as it is or create a well define python module to reuse them


Wanna style have an abtract tree of our behaviour tree ?

Functions from async-btree build an abstract tree for you. 
If you lookup in code, you should see an annotation "node_metadata" on internal implementation. 
This decorator add basic information like function name, parameters, and children relation ship.

This abstract tree can be retreived and stringified with ```analyze``` and ```stringify_analyze```.
Here the profile:

```python
  def analyze(target: CallableFunction) -> Node: # here we have our "abtract tree code"
    ...
```

For example:

```python

# your behaviour tree, or a sub tree:
my_func = alias(child=repeat_until(child=action(hello), condition=success_until_zero), name="btree_1")

# retrieve meta information and build a Node tree
abstract_tree_tree_1 = analyze(my_func) 

# output the tree:
print(stringify_analyze(abstract_tree_tree_1))
```

This should print:

```text
 --> btree_1:
     --(child)--> repeat_until:
         --(condition)--> success_until_zero:
         --(child)--> action:
                      target: hello
```


Note about action and condition method:

 - you could use sync or async function
 - you could specify a return value with SUCCESS or FAILURE
 - function with no return value will be evaluated as FAILURE until you decorate them with a `always_success`or `always_failure`

See this [example/tutorial_1.py](https://raw.githubusercontent.com/geronimo-iia/async-btree/master/examples/tutorial_1.py) for more information.
            

Raw data

            {
    "_id": null,
    "home_page": "https://pypi.org/project/async_btree",
    "name": "async_btree",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<3.12",
    "maintainer_email": "",
    "keywords": "behavior-tree,asyncio",
    "author": "Jerome Guibert",
    "author_email": "jguibert@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/79/51/85a06129a0f09ce5212801fa94d0a0cbd4ab93b856c1b4b0ecdcab68ccb5/async_btree-1.3.0.tar.gz",
    "platform": null,
    "description": "# Async Behaviour Tree for Python\n\n\n[![Unix Build Status](https://img.shields.io/travis/geronimo-iia/async-btree/master.svg?label=unix)](https://travis-ci.com/geronimo-iia/async-btree)\n[![Coverage Status](https://img.shields.io/coveralls/geronimo-iia/async-btree/master.svg)](https://coveralls.io/r/geronimo-iia/async-btree)\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/fe669a02b4aa46b5b1faf619ba2bf382)](https://www.codacy.com/app/geronimo-iia/async-btree?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=geronimo-iia/async-btree&amp;utm_campaign=Badge_Grade)\n[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/geronimo-iia/async-btree.svg)](https://scrutinizer-ci.com/g/geronimo-iia/async-btree/?branch=master)\n[![PyPI Version](https://img.shields.io/pypi/v/async-btree.svg)](https://pypi.org/project/async-btree)\n[![PyPI License](https://img.shields.io/pypi/l/async-btree.svg)](https://pypi.org/project/async-btree)\n\nVersions following [Semantic Versioning](https://semver.org/)\n\nSee [documentation](https://geronimo-iia.github.io/async-btree).\n\n\n## Overview\n\n\n### What's a behavior tree ?\n\n> Unlike a Finite State Machine, a Behaviour Tree is a tree of hierarchical nodes that controls the flow of decision and the execution of \"tasks\" or, as we will call them further, \"Actions\".\n> -- <cite>[behaviortree](https://www.behaviortree.dev/bt_basics/)</cite>\n\nIf your new (or not) about behavior tree, you could spend some time on this few links:\n\n- [Behavior trees for AI: How they work](https://www.gamasutra.com/blogs/ChrisSimpson/20140717/221339/Behavior_trees_for_AI_How_they_work.php) by Chris Simpson\n- [Introduction to BTs](https://www.behaviortree.dev/bt_basics/)\n\nFew implementation libraries:\n\n- [task_behavior_engine](https://github.com/ToyotaResearchInstitute/task_behavior_engine) A behavior tree based task engine written in Python\n- [pi_trees](https://github.com/pirobot/pi_trees/) a Python/ROS library for implementing Behavior Trees\n- [pr_behavior_tree](https://github.com/personalrobotics/pr_behavior_tree) A simple python behavior tree library based on coroutines\n- [btsk](https://github.com/aigamedev/btsk) Behavior Tree Starter Kit\n- [behave](https://github.com/fuchen/behave) A behavior tree implementation in Python\n\n\n### Why another library so ?\n\n__SIMPLICITY__\n\nWhen you study behavior tree implementation, reactive node, dynamic change, runtime execution, etc ...\nAt a moment you're build more or less something that mimic an evaluator 'eval/apply' or a compilator, with a complex hierachical set of class.\n\nAll complexity came with internal state management, using tree of blackboard to avoid global variable, multithreading issue, maybe few callback etc ...\n\nThis break the simplicity and beauty of your initial design.\n\nWhat I find usefull with behavior tree:\n\n- clarity of expression\n- node tree representation\n- possibility to reuse behavior\n- add external measure to dynamicaly change a behavior, a first step on observable pattern...\n\nAs I've used OOP for years (very long time), I will try to avoid class tree and prefer using the power of functionnal programming to obtain what I want: add metadata on a sematic construction, deal with closure, use function in parameters or in return value...\n\nAnd a last reason, more personal, it that i would explore python expressivity.\n\n__SO HOW ?__\n\nIn this module, I purpose you to use the concept of coroutines, and their mecanisms to manage the execution flow.\nBy this way:\n\n- we reuse simple language idiom to manage state, parameter, etc\n- no design constraint on action implementation\n- most of language build block could be reused\n\nYou could build expression like this:\n\n```python\n\nasync def a_func():\n    \"\"\"A great function\"\"\"\n    return \"a\"\n\nasync def b_decorator(child_value, other=\"\"):\n    \"\"\"A great decorator...\"\"\"\n    return f\"b{child_value}{other}\"\n\nassert run(decorate(a_func, b_decorator)) == \"ba\"\n\n```\nThis expression apply ```b_decorator``` on function ```a_func```. \nNote that ```decorate(a_func, b_decorator)``` is not an async function, only action, or condition are async function.\n\n\nFew guidelines of this implementation:\n\n- In order to mimic all NodeStatus (success, failure, running), I replace this by truthy/falsy meaning of evaluation value.\n  A special dedicated exception decorate standard exception in order to give them a Falsy meaning (`ControlFlowException`).\n  By default, exception are raised like happen usually until you catch them.\n- Blackboard pattern, act as a manager of context variable for behavior tree.\n  With python 3, please... simply use [contextvars](https://docs.python.org/3/library/contextvars.html) !\n- In order to be able to build a sematic tree, I've introduce a metadata tuple added on function implementation.\n\nThe rest is just implementation details..\n\n\n\nA little note:\n\n> You should not use this until you're ready to think about what you're doing :)\n\n\n### Note about 'async' framework\n\nAs we use async function as underlaying mechanism to manage the execution flow, the standard library asyncio is pretty fine.\nBut, (always a but somewhere isn't it...), you should read this [amazing blog post](https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/) by Nathaniel J. Smith.\nAnd next study [curio](https://github.com/dabeaz/curio) framework in deep.\n\nAs curio say:\n> Don't Use Curio if You're Allergic to Curio\n\nPersonaly, after few time of testing and reading curio code, I'm pretty addict.\n\nIf `curio` is not present, we default to `asyncio`.\n\n## Installation\n\nInstall this library directly into an activated virtual environment with pip or [Poetry](https://poetry.eustace.io/) :\n\n - `python -m pip install async-btree` or '`poetry add async-btree`\n - with with curio extention: `python -m pip install async-btree[curio]` or '`poetry add async-btree[curio]`\n\n\n## Usage\n\nAfter installation, the package can imported:\n\n```text\n$ python\n>>> import async_btree\n>>> async_btree.__version__\n```\n\nSee [API Reference documentation](https://geronimo-iia.github.io/async-btree).\n\n\nWith this framework, you didn't find any configuration file, no Xml, no json, no yaml.\n\nThe main reason (oriented and personal point of view) is that you did not need to introduce an extra level of abtraction \nto declare a composition of functions. I think it's true for most of main use case (except using an editor to wrote behaviour tree for example).\n\nSo \"If you wrote your function with python, wrote composition in python\"... \n_(remember that you did not need XML to do SQL, just write good sql...)_\n\n\nSo, the goal is to:\n - define your business function wich implements actions or conditions, with all test case that you wish/need\n - compose them using those provided by this framework like ```sequence```, ```selector```, ...\n - use them as it is or create a well define python module to reuse them\n\n\nWanna style have an abtract tree of our behaviour tree ?\n\nFunctions from async-btree build an abstract tree for you. \nIf you lookup in code, you should see an annotation \"node_metadata\" on internal implementation. \nThis decorator add basic information like function name, parameters, and children relation ship.\n\nThis abstract tree can be retreived and stringified with ```analyze``` and ```stringify_analyze```.\nHere the profile:\n\n```python\n  def analyze(target: CallableFunction) -> Node: # here we have our \"abtract tree code\"\n    ...\n```\n\nFor example:\n\n```python\n\n# your behaviour tree, or a sub tree:\nmy_func = alias(child=repeat_until(child=action(hello), condition=success_until_zero), name=\"btree_1\")\n\n# retrieve meta information and build a Node tree\nabstract_tree_tree_1 = analyze(my_func) \n\n# output the tree:\nprint(stringify_analyze(abstract_tree_tree_1))\n```\n\nThis should print:\n\n```text\n --> btree_1:\n     --(child)--> repeat_until:\n         --(condition)--> success_until_zero:\n         --(child)--> action:\n                      target: hello\n```\n\n\nNote about action and condition method:\n\n - you could use sync or async function\n - you could specify a return value with SUCCESS or FAILURE\n - function with no return value will be evaluated as FAILURE until you decorate them with a `always_success`or `always_failure`\n\nSee this [example/tutorial_1.py](https://raw.githubusercontent.com/geronimo-iia/async-btree/master/examples/tutorial_1.py) for more information.",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Async behavior tree",
    "version": "1.3.0",
    "project_urls": {
        "Documentation": "https://geronimo-iia.github.io/async-btree/",
        "Homepage": "https://pypi.org/project/async_btree",
        "Repository": "https://github.com/geronimo-iia/async-btree"
    },
    "split_keywords": [
        "behavior-tree",
        "asyncio"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "739ce3e591d38801c47c2f5f76f36cd872d0efd1f062cdaa33ab322f0943c75e",
                "md5": "71eb9bcf676941713b000c80c35dceda",
                "sha256": "a7bde2d45290aa588fb1b67e3a484af655aae16fc16354d07b13b847cccc123e"
            },
            "downloads": -1,
            "filename": "async_btree-1.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "71eb9bcf676941713b000c80c35dceda",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<3.12",
            "size": 17524,
            "upload_time": "2023-10-07T09:22:09",
            "upload_time_iso_8601": "2023-10-07T09:22:09.264599Z",
            "url": "https://files.pythonhosted.org/packages/73/9c/e3e591d38801c47c2f5f76f36cd872d0efd1f062cdaa33ab322f0943c75e/async_btree-1.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "795185a06129a0f09ce5212801fa94d0a0cbd4ab93b856c1b4b0ecdcab68ccb5",
                "md5": "bf3462746b811553e35a63b853d7a2fd",
                "sha256": "40879372fa83fbf3311157b8a09f8238372736f8882248c49cc7eb0e223f6de4"
            },
            "downloads": -1,
            "filename": "async_btree-1.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "bf3462746b811553e35a63b853d7a2fd",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<3.12",
            "size": 17998,
            "upload_time": "2023-10-07T09:22:10",
            "upload_time_iso_8601": "2023-10-07T09:22:10.937058Z",
            "url": "https://files.pythonhosted.org/packages/79/51/85a06129a0f09ce5212801fa94d0a0cbd4ab93b856c1b4b0ecdcab68ccb5/async_btree-1.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-07 09:22:10",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "geronimo-iia",
    "github_project": "async-btree",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "async_btree"
}
        
Elapsed time: 0.97394s