hcraft


Namehcraft JSON
Version 2.0.0 PyPI version JSON
download
home_pageNone
SummaryLightweight environments to study hierarchical reasoning
upload_time2025-01-25 15:13:59
maintainerNone
docs_urlNone
authorMathïs Fédérico
requires_python>=3.8
licenseGNU General Public License v3 or later (GPLv3+)
keywords gym hcraft minecraft hierachical reinforcement learning
VCS
bugtrack_url
requirements numpy networkx matplotlib seaborn hebg
Travis-CI No Travis.
coveralls test coverage
            # **HierarchyCraft - Environements builder for hierarchical reasoning research**

[![Fury - PyPi stable version](https://badge.fury.io/py/hcraft.svg)](https://badge.fury.io/py/hcraft)
[![PePy - Downloads](https://static.pepy.tech/badge/hcraft)](https://pepy.tech/project/hcraft)
[![PePy - Downloads per week](https://static.pepy.tech/badge/hcraft/week)](https://pepy.tech/project/hcraft)
[![Licence - GPLv3](https://img.shields.io/github/license/IRLL/HierarchyCraft?style=plastic)](https://www.gnu.org/licenses/)

[![Codacy - grade](https://app.codacy.com/project/badge/Grade/b5010ccc46274c0eb1e3ae563934efdd)](https://www.codacy.com/gh/IRLL/HierarchyCraft/dashboard?utm_source=github.com&utm_medium=referral&utm_content=IRLL/HierarchyCraft&utm_campaign=Badge_Grade)
[![Codacy - coverage](https://app.codacy.com/project/badge/Coverage/b5010ccc46274c0eb1e3ae563934efdd)](https://www.codacy.com/gh/IRLL/HierarchyCraft/dashboard?utm_source=github.com&utm_medium=referral&utm_content=IRLL/HierarchyCraft&utm_campaign=Badge_Coverage)
[![CodeStyle - Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![CodeStyle - Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v1.json)](https://github.com/charliermarsh/ruff)


# HierarchyCraft

HierarchyCraft (hcraft for short) is a Python library designed to create arbitrary hierarchical environments that are compatible with both the [OpenAI Gym Reinforcement Learning Framework](https://github.com/openai/gym) and [AIPlan4EU Unified Planning Framework](https://github.com/aiplan4eu/unified-planning). This library enables users to easily create complex hierarchical structures that can be used to test and develop various reinforcement learning or planning algorithms.

In environments built with HierarchyCraft the agent (player) has an inventory and can navigate into abstract zones that themselves have inventories.

The action space of HierarchyCraft environments consists of sub-tasks, referred to as *Transformations*, as opposed to detailed movements and controls. But each *Transformations* has specific requirements to be valid (eg. have enought of an item, be in the right place), and these requirements may necessitate the execution of other *Transformations* first, inherently creating a hierarchical structure in HierarchyCraft environments.

This concept is visually represented by the *Requirements graph* depicting the hierarchical relationships within each HierarchyCraft environment.
The *Requirements graph* is directly constructed from the list of *Transformations* composing the environement.

![](docs/images/TransformationToRequirements.png)

More details about requirements graph can be found in the documentation at [`hcraft.requirements`](https://irll.github.io/HierarchyCraft/hcraft/requirements.html) and example of requirements graph for some HierarchyCraft environements can be found in [`hcraft.examples`](https://irll.github.io/HierarchyCraft/hcraft/examples.html).

## No feature extraction for fast research even with low compute

HierarchyCraft returns vectorized state information, which plainly and directly describes the player's inventory, current positions, and the inventory of the current zone. Compared to benchmarks that return grids, pixel arrays, text or sound, we directly return a low-dimensional latent representation that doesn't need to be learned.
Therefore saving compute time and allowing researchers to focus only the the hierarchical reasoning part.

![](docs/images/hcraft_observation.png)

See [`hcraft.state`](https://irll.github.io/HierarchyCraft/hcraft/state.html) for more details.

## Create your own tailored HierarchyCraft environments

You can use HierarchyCraft to create various custom hierarchical environments from a list of customized *Transformations*.

See [`hcraft.env`](https://irll.github.io/HierarchyCraft/hcraft/env.html) for a complete tutorial on creating custom environments.


# Installation

## Using pip

Without optional dependencies:

```bash
pip install hcraft
```

All hcraft environments can use a common graphical user interface that can be used with gui requirements:

```bash
pip install hcraft[gui]
```

Gym environment can be obtained with gym requirements:

```bash
pip install hcraft[gym]
```

Planning problems can be obtained throught the upf interface with planning requirements:

```bash
pip install hcraft[planning]
```

Some complex graph can be represented in html interactive visualisation:

```bash
pip install hcraft[htmlvis]
```

# Quickstart

## Play yourself!

![A player knowing Minecraft will find MineHcraft easy.](./docs/images/minehcraft_human_demo.gif)

Install the graphical user interface optional dependencies:
```bash
pip install hcraft[gui]
```

### Using the command line interface

You can directly try to play yourself with the GUI available for any HierarchyCraft environments, for example:
```bash
hcraft minecraft
```

For more examples:
```bash
hcraft --help
```
###  Using the programmatic interface:

```python
from hcraft import get_human_action
from hcraft.examples import MineHcraftEnv

env = MineHcraftEnv()
# or env: MineHcraftEnv = gym.make("MineHcraft-NoReward-v1")
n_episodes = 2
for _ in range(n_episodes):
    env.reset()
    done = False
    total_reward = 0
    while not done:
        env.render()
        action = get_human_action(env)
        print(f"Human pressed: {env.world.transformations[action]}")

        _observation, reward, done, _info = env.step(action)
        total_reward += reward

    print(f"SCORE: {total_reward}")
```

## As a Gym RL environment

Using the programmatic interface, any HierarchyCraft environment can easily be interfaced with classic reinforcement learning agents.

```python
import numpy as np
from hcraft.examples import MineHcraftEnv

def random_legal_agent(observation, action_is_legal):
    action = np.random.choice(np.nonzero(action_is_legal)[0])
    return int(action)

env = MineHcraftEnv(max_step=10)
done = False
observation, _info = env.reset()
while not done:
    action_is_legal = env.action_masks()
    action = random_legal_agent(observation, action_is_legal)
    _observation, _reward, terminated, truncated, _info = env.step(action)
```


```python
# Other examples of HierarchyCraft environments
from hcraft.examples import  TowerHcraftEnv, RecursiveHcraftEnv, RandomHcraftEnv

tower_env = TowerHcraftEnv(height=3, width=2)
# or tower_env = gym.make("TowerHcraft-v1", height=3, width=2)
recursive_env = RecursiveHcraftEnv(n_items=6)
# or recursive_env = gym.make("RecursiveHcraft-v1", n_items=6)
random_env = RandomHcraftEnv(n_items_per_n_inputs={0:2, 1:5, 2:10}, seed=42)
# or random_env = gym.make("RandomHcraft-v1", n_items_per_n_inputs={0:2, 1:5, 2:10}, seed=42)
```
<!-- Run MineHcraft with MaskablePPO from sb3 agent [code] -->

See [`hcraft.env`](https://irll.github.io/HierarchyCraft/hcraft/env.html) for a more complete description.

## As a UPF problem for planning

HierarchyCraft environments can be converted to planning problem in one line
thanks to the Unified Planning Framework (UPF):

```python
# Example env
env = TowerHcraftEnv(height=3, width=2)

# Make it into a unified planning problem
planning_problem = env.planning_problem()
print(planning_problem.upf_problem)
```

Then they can be solved with any compatible planner for UPF:

```python
# Solve the planning problem and show the plan
planning_problem.solve()
print(planning_problem.plan)
```

The planning_problem can also give actions to do in the environment, triggering replaning if necessary:

```python
done = False
_observation, _info = env.reset()
while not done:
    # Automatically replan at the end of each plan until env termination

    # Observations are not used when blindly following a current plan
    # But the state in required in order to replan if there is no plan left
    action = planning_problem.action_from_plan(env.state)
    if action is None:
        # Plan is existing but empty, thus nothing to do, thus terminates
        done = True
        continue
    _observation, _reward, terminated, truncated, _info = env.step(action)
    done = terminated or truncated

if terminated:
    print("Success ! The plan worked in the actual environment !")
else:
    print("Failed ... Something went wrong with the plan or the episode was truncated.")

```

See [`hcraft.planning`](https://irll.github.io/HierarchyCraft/hcraft/planning.html) for a more complete description.


# More about HierarchyCraft

## Online documentation

Learn more in the [DOCUMENTATION](https://irll.github.io/HierarchyCraft/hcraft.html)

## Contributing

You want to contribute to HierarchyCraft ? See our [contributions guidelines](CONTRIBUTING.md) and join us !

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "hcraft",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "gym, hcraft, minecraft, hierachical, reinforcement, learning",
    "author": "Math\u00efs F\u00e9d\u00e9rico",
    "author_email": "Math\u00efs F\u00e9d\u00e9rico <mathfederico@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/4a/34/15ac6a533d49f7fbfac0170ea342e9bb68e0205bdc361fe9482c54eaa158/hcraft-2.0.0.tar.gz",
    "platform": null,
    "description": "# **HierarchyCraft - Environements builder for hierarchical reasoning research**\n\n[![Fury - PyPi stable version](https://badge.fury.io/py/hcraft.svg)](https://badge.fury.io/py/hcraft)\n[![PePy - Downloads](https://static.pepy.tech/badge/hcraft)](https://pepy.tech/project/hcraft)\n[![PePy - Downloads per week](https://static.pepy.tech/badge/hcraft/week)](https://pepy.tech/project/hcraft)\n[![Licence - GPLv3](https://img.shields.io/github/license/IRLL/HierarchyCraft?style=plastic)](https://www.gnu.org/licenses/)\n\n[![Codacy - grade](https://app.codacy.com/project/badge/Grade/b5010ccc46274c0eb1e3ae563934efdd)](https://www.codacy.com/gh/IRLL/HierarchyCraft/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=IRLL/HierarchyCraft&amp;utm_campaign=Badge_Grade)\n[![Codacy - coverage](https://app.codacy.com/project/badge/Coverage/b5010ccc46274c0eb1e3ae563934efdd)](https://www.codacy.com/gh/IRLL/HierarchyCraft/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=IRLL/HierarchyCraft&amp;utm_campaign=Badge_Coverage)\n[![CodeStyle - Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![CodeStyle - Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v1.json)](https://github.com/charliermarsh/ruff)\n\n\n# HierarchyCraft\n\nHierarchyCraft (hcraft for short) is a Python library designed to create arbitrary hierarchical environments that are compatible with both the [OpenAI Gym Reinforcement Learning Framework](https://github.com/openai/gym) and [AIPlan4EU Unified Planning Framework](https://github.com/aiplan4eu/unified-planning). This library enables users to easily create complex hierarchical structures that can be used to test and develop various reinforcement learning or planning algorithms.\n\nIn environments built with HierarchyCraft the agent (player) has an inventory and can navigate into abstract zones that themselves have inventories.\n\nThe action space of HierarchyCraft environments consists of sub-tasks, referred to as *Transformations*, as opposed to detailed movements and controls. But each *Transformations* has specific requirements to be valid (eg. have enought of an item, be in the right place), and these requirements may necessitate the execution of other *Transformations* first, inherently creating a hierarchical structure in HierarchyCraft environments.\n\nThis concept is visually represented by the *Requirements graph* depicting the hierarchical relationships within each HierarchyCraft environment.\nThe *Requirements graph* is directly constructed from the list of *Transformations* composing the environement.\n\n![](docs/images/TransformationToRequirements.png)\n\nMore details about requirements graph can be found in the documentation at [`hcraft.requirements`](https://irll.github.io/HierarchyCraft/hcraft/requirements.html) and example of requirements graph for some HierarchyCraft environements can be found in [`hcraft.examples`](https://irll.github.io/HierarchyCraft/hcraft/examples.html).\n\n## No feature extraction for fast research even with low compute\n\nHierarchyCraft returns vectorized state information, which plainly and directly describes the player's inventory, current positions, and the inventory of the current zone. Compared to benchmarks that return grids, pixel arrays, text or sound, we directly return a low-dimensional latent representation that doesn't need to be learned.\nTherefore saving compute time and allowing researchers to focus only the the hierarchical reasoning part.\n\n![](docs/images/hcraft_observation.png)\n\nSee [`hcraft.state`](https://irll.github.io/HierarchyCraft/hcraft/state.html) for more details.\n\n## Create your own tailored HierarchyCraft environments\n\nYou can use HierarchyCraft to create various custom hierarchical environments from a list of customized *Transformations*.\n\nSee [`hcraft.env`](https://irll.github.io/HierarchyCraft/hcraft/env.html) for a complete tutorial on creating custom environments.\n\n\n# Installation\n\n## Using pip\n\nWithout optional dependencies:\n\n```bash\npip install hcraft\n```\n\nAll hcraft environments can use a common graphical user interface that can be used with gui requirements:\n\n```bash\npip install hcraft[gui]\n```\n\nGym environment can be obtained with gym requirements:\n\n```bash\npip install hcraft[gym]\n```\n\nPlanning problems can be obtained throught the upf interface with planning requirements:\n\n```bash\npip install hcraft[planning]\n```\n\nSome complex graph can be represented in html interactive visualisation:\n\n```bash\npip install hcraft[htmlvis]\n```\n\n# Quickstart\n\n## Play yourself!\n\n![A player knowing Minecraft will find MineHcraft easy.](./docs/images/minehcraft_human_demo.gif)\n\nInstall the graphical user interface optional dependencies:\n```bash\npip install hcraft[gui]\n```\n\n### Using the command line interface\n\nYou can directly try to play yourself with the GUI available for any HierarchyCraft environments, for example:\n```bash\nhcraft minecraft\n```\n\nFor more examples:\n```bash\nhcraft --help\n```\n###  Using the programmatic interface:\n\n```python\nfrom hcraft import get_human_action\nfrom hcraft.examples import MineHcraftEnv\n\nenv = MineHcraftEnv()\n# or env: MineHcraftEnv = gym.make(\"MineHcraft-NoReward-v1\")\nn_episodes = 2\nfor _ in range(n_episodes):\n    env.reset()\n    done = False\n    total_reward = 0\n    while not done:\n        env.render()\n        action = get_human_action(env)\n        print(f\"Human pressed: {env.world.transformations[action]}\")\n\n        _observation, reward, done, _info = env.step(action)\n        total_reward += reward\n\n    print(f\"SCORE: {total_reward}\")\n```\n\n## As a Gym RL environment\n\nUsing the programmatic interface, any HierarchyCraft environment can easily be interfaced with classic reinforcement learning agents.\n\n```python\nimport numpy as np\nfrom hcraft.examples import MineHcraftEnv\n\ndef random_legal_agent(observation, action_is_legal):\n    action = np.random.choice(np.nonzero(action_is_legal)[0])\n    return int(action)\n\nenv = MineHcraftEnv(max_step=10)\ndone = False\nobservation, _info = env.reset()\nwhile not done:\n    action_is_legal = env.action_masks()\n    action = random_legal_agent(observation, action_is_legal)\n    _observation, _reward, terminated, truncated, _info = env.step(action)\n```\n\n\n```python\n# Other examples of HierarchyCraft environments\nfrom hcraft.examples import  TowerHcraftEnv, RecursiveHcraftEnv, RandomHcraftEnv\n\ntower_env = TowerHcraftEnv(height=3, width=2)\n# or tower_env = gym.make(\"TowerHcraft-v1\", height=3, width=2)\nrecursive_env = RecursiveHcraftEnv(n_items=6)\n# or recursive_env = gym.make(\"RecursiveHcraft-v1\", n_items=6)\nrandom_env = RandomHcraftEnv(n_items_per_n_inputs={0:2, 1:5, 2:10}, seed=42)\n# or random_env = gym.make(\"RandomHcraft-v1\", n_items_per_n_inputs={0:2, 1:5, 2:10}, seed=42)\n```\n<!-- Run MineHcraft with MaskablePPO from sb3 agent [code] -->\n\nSee [`hcraft.env`](https://irll.github.io/HierarchyCraft/hcraft/env.html) for a more complete description.\n\n## As a UPF problem for planning\n\nHierarchyCraft environments can be converted to planning problem in one line\nthanks to the Unified Planning Framework (UPF):\n\n```python\n# Example env\nenv = TowerHcraftEnv(height=3, width=2)\n\n# Make it into a unified planning problem\nplanning_problem = env.planning_problem()\nprint(planning_problem.upf_problem)\n```\n\nThen they can be solved with any compatible planner for UPF:\n\n```python\n# Solve the planning problem and show the plan\nplanning_problem.solve()\nprint(planning_problem.plan)\n```\n\nThe planning_problem can also give actions to do in the environment, triggering replaning if necessary:\n\n```python\ndone = False\n_observation, _info = env.reset()\nwhile not done:\n    # Automatically replan at the end of each plan until env termination\n\n    # Observations are not used when blindly following a current plan\n    # But the state in required in order to replan if there is no plan left\n    action = planning_problem.action_from_plan(env.state)\n    if action is None:\n        # Plan is existing but empty, thus nothing to do, thus terminates\n        done = True\n        continue\n    _observation, _reward, terminated, truncated, _info = env.step(action)\n    done = terminated or truncated\n\nif terminated:\n    print(\"Success ! The plan worked in the actual environment !\")\nelse:\n    print(\"Failed ... Something went wrong with the plan or the episode was truncated.\")\n\n```\n\nSee [`hcraft.planning`](https://irll.github.io/HierarchyCraft/hcraft/planning.html) for a more complete description.\n\n\n# More about HierarchyCraft\n\n## Online documentation\n\nLearn more in the [DOCUMENTATION](https://irll.github.io/HierarchyCraft/hcraft.html)\n\n## Contributing\n\nYou want to contribute to HierarchyCraft ? See our [contributions guidelines](CONTRIBUTING.md) and join us !\n",
    "bugtrack_url": null,
    "license": "GNU General Public License v3 or later (GPLv3+)",
    "summary": "Lightweight environments to study hierarchical reasoning",
    "version": "2.0.0",
    "project_urls": {
        "Source": "https://github.com/IRLL/HierarchyCraft"
    },
    "split_keywords": [
        "gym",
        " hcraft",
        " minecraft",
        " hierachical",
        " reinforcement",
        " learning"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "efbbd6cac3df410e1854058c60157b75f3321a3ec590eb02c96c13c490fc00ae",
                "md5": "c42a31dccc0e89ccf69701417104353a",
                "sha256": "05b89d3ee58d96c91d7bdb68f8db3d3939c8aea0ccb8c6b375dc23081a015252"
            },
            "downloads": -1,
            "filename": "hcraft-2.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c42a31dccc0e89ccf69701417104353a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 3857864,
            "upload_time": "2025-01-25T15:13:56",
            "upload_time_iso_8601": "2025-01-25T15:13:56.724365Z",
            "url": "https://files.pythonhosted.org/packages/ef/bb/d6cac3df410e1854058c60157b75f3321a3ec590eb02c96c13c490fc00ae/hcraft-2.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "4a3415ac6a533d49f7fbfac0170ea342e9bb68e0205bdc361fe9482c54eaa158",
                "md5": "df03893a6410eea730eeac8f7bb97f18",
                "sha256": "f8b1703c0c6718840c641f7fc3a6238529e91a99c6840d44564c66d20efa8f96"
            },
            "downloads": -1,
            "filename": "hcraft-2.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "df03893a6410eea730eeac8f7bb97f18",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 12966852,
            "upload_time": "2025-01-25T15:13:59",
            "upload_time_iso_8601": "2025-01-25T15:13:59.658124Z",
            "url": "https://files.pythonhosted.org/packages/4a/34/15ac6a533d49f7fbfac0170ea342e9bb68e0205bdc361fe9482c54eaa158/hcraft-2.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-25 15:13:59",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "IRLL",
    "github_project": "HierarchyCraft",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [
        {
            "name": "numpy",
            "specs": []
        },
        {
            "name": "networkx",
            "specs": [
                [
                    ">=",
                    "2.5.1"
                ]
            ]
        },
        {
            "name": "matplotlib",
            "specs": []
        },
        {
            "name": "seaborn",
            "specs": []
        },
        {
            "name": "hebg",
            "specs": [
                [
                    ">=",
                    "0.2.3"
                ]
            ]
        }
    ],
    "lcname": "hcraft"
}
        
Elapsed time: 5.92331s