├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── build.yml │ ├── format.yml │ └── tests.yml ├── .gitignore ├── .gitmodules ├── .mergify.yml ├── LICENSE ├── README.md ├── codecov.yml ├── docs ├── CODE_OF_CONDUCT.md └── CONTRIBUTING.md ├── jupyddl ├── __init__.py ├── a_star.py ├── automated_planner.py ├── bfs.py ├── data_analyst.py ├── dfs.py ├── dijkstra.py ├── greedy_best_first.py ├── heuristics.py ├── metrics.py └── node.py ├── logs └── .gitkeep ├── renovate.json ├── requirements.txt ├── scripts └── ipc.py ├── setup.py └── tests ├── test_automated_planner.py ├── test_basic_astar.py ├── test_basic_search.py ├── test_data_analyst.py ├── test_greedy_best_first.py ├── test_heuristics.py ├── test_hsp_astar.py ├── test_metrics.py └── test_node.py /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: 'bug' 6 | assignees: 'guilyx,sampreets3' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Additional context** 32 | Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: 'feature' 6 | assignees: 'guilyx' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | os: [ubuntu-latest, macos-latest] 11 | python-version: [3.6, 3.7, 3.8] 12 | exclude: 13 | - os: macos-latest 14 | python-version: 3.8 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up Python 3.7 19 | uses: actions/setup-python@v3 20 | with: 21 | python-version: 3.7 22 | - uses: actions/checkout@v2.4.0 23 | - uses: julia-actions/setup-julia@v1 24 | with: 25 | version: '1.4.1' 26 | - name: Install Julia dependencies 27 | run: | 28 | julia --color=yes -e 'using Pkg; Pkg.add(Pkg.PackageSpec(path="https://github.com/APLA-Toolbox/PDDL.jl"))' 29 | julia --color=yes -e 'using Pkg; Pkg.add(Pkg.PackageSpec(path="https://github.com/JuliaPy/PyCall.jl"))' 30 | - name: Install Python dependencies 31 | run: | 32 | python -m pip install --upgrade pip 33 | python -m pip install -r requirements.txt 34 | - name: Lint with flake8 35 | run: | 36 | python -m pip install flake8 37 | # stop the build if there are Python syntax errors or undefined names 38 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 39 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 40 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 41 | - name: Checkout reposistory 42 | uses: actions/checkout@master 43 | - name: Checkout submodules 44 | uses: snickerbockers/submodules-init@v4 45 | 46 | -------------------------------------------------------------------------------- /.github/workflows/format.yml: -------------------------------------------------------------------------------- 1 | name: format 2 | on: 3 | push: 4 | branches: [main] 5 | jobs: 6 | format: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | with: 11 | ref: ${{ github.head_ref }} 12 | - uses: actions/checkout@v2 13 | - name: Set up Python 3.7 14 | uses: actions/setup-python@v3 15 | with: 16 | python-version: 3.7 17 | - name: Install formatter dependencies 18 | run: | 19 | python -m pip install --upgrade pip 20 | python -m pip install black 21 | - name: Format with black 22 | run: | 23 | black . 24 | - name: Commit changes 25 | uses: stefanzweifel/git-auto-commit-action@v4.14.0 26 | with: 27 | commit_message: Apply formatting changes 28 | branch: main 29 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | os: [ubuntu-latest, macos-latest] 11 | python-version: [3.6, 3.7, 3.8] 12 | exclude: 13 | - os: macos-latest 14 | python-version: 3.8 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up Python 3.7 19 | uses: actions/setup-python@v3 20 | with: 21 | python-version: 3.7 22 | - uses: actions/checkout@v2.4.0 23 | - uses: julia-actions/setup-julia@v1 24 | with: 25 | version: '1.4.1' 26 | - name: Install Julia dependencies 27 | run: | 28 | julia --color=yes -e 'using Pkg; Pkg.add(Pkg.PackageSpec(path="https://github.com/APLA-Toolbox/PDDL.jl"))' 29 | julia --color=yes -e 'using Pkg; Pkg.add(Pkg.PackageSpec(path="https://github.com/JuliaPy/PyCall.jl"))' 30 | - name: Install Python dependencies 31 | run: | 32 | python -m pip install --upgrade pip 33 | python -m pip install julia 34 | python -m pip install pycall 35 | - name: Lint with flake8 36 | run: | 37 | python -m pip install flake8 38 | # stop the build if there are Python syntax errors or undefined names 39 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 40 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 41 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 42 | - name: Checkout reposistory 43 | uses: actions/checkout@master 44 | - name: Checkout submodules 45 | uses: snickerbockers/submodules-init@v4 46 | 47 | test: 48 | runs-on: ${{ matrix.os }} 49 | strategy: 50 | matrix: 51 | os: [ubuntu-latest, macos-latest] 52 | python-version: [3.6, 3.7, 3.8] 53 | exclude: 54 | - os: macos-latest 55 | python-version: 3.8 56 | steps: 57 | - uses: actions/checkout@v2 58 | - name: Set up Python 3.7 59 | uses: actions/setup-python@v3 60 | with: 61 | python-version: 3.7 62 | - uses: actions/checkout@v2.4.0 63 | - uses: julia-actions/setup-julia@v1 64 | with: 65 | version: '1.4.1' 66 | - name: Install Julia dependencies 67 | run: | 68 | julia --color=yes -e 'using Pkg; Pkg.add(Pkg.PackageSpec(path="https://github.com/JuliaPy/PyCall.jl"))' 69 | julia --color=yes -e 'using Pkg; Pkg.add(Pkg.PackageSpec(path="https://github.com/APLA-Toolbox/PDDL.jl"))' 70 | - name: Install Python dependencies 71 | run: | 72 | python -m pip install --upgrade pip 73 | python -m pip install -r requirements.txt 74 | - name: Lint with flake8 75 | run: | 76 | python -m pip install flake8 77 | # stop the build if there are Python syntax errors or undefined names 78 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 79 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 80 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 81 | - name: Checkout reposistory 82 | uses: actions/checkout@master 83 | - name: Checkout submodules 84 | uses: snickerbockers/submodules-init@v4 85 | - name: Test with pytest 86 | run: | 87 | pip install pytest 88 | pip install pytest-cov 89 | pytest --cov=./ 90 | - name: Upload coverage to Codecov 91 | uses: codecov/codecov-action@v2 92 | with: 93 | name: codecov-umbrella 94 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | .vscode/* 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | pip-wheel-metadata/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | .python-version 87 | 88 | # pipenv 89 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 90 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 91 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 92 | # install all needed dependencies. 93 | #Pipfile.lock 94 | 95 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 96 | __pypackages__/ 97 | 98 | # Celery stuff 99 | celerybeat-schedule 100 | celerybeat.pid 101 | 102 | # SageMath parsed files 103 | *.sage.py 104 | 105 | # Environments 106 | .env 107 | .venv 108 | env/ 109 | venv/ 110 | ENV/ 111 | env.bak/ 112 | venv.bak/ 113 | 114 | # Spyder project settings 115 | .spyderproject 116 | .spyproject 117 | 118 | # Rope project settings 119 | .ropeproject 120 | 121 | # mkdocs documentation 122 | /site 123 | 124 | # mypy 125 | .mypy_cache/ 126 | .dmypy.json 127 | dmypy.json 128 | 129 | # Pyre type checker 130 | .pyre/ 131 | 132 | # Logs 133 | logs/* 134 | !logs/.gitkeep 135 | data.json 136 | pddl-examples/* 137 | data/* 138 | scripts/* 139 | *.txt 140 | !scripts/ipc.py 141 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "pddl-examples"] 2 | path = pddl-examples 3 | url = https://github.com/APLA-Toolbox/pddl-examples 4 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | pull_request_rules: 2 | - name: Assign the main reviewers 3 | conditions: 4 | - check-success=build 5 | - check-success=CodeFactor 6 | actions: 7 | request_reviews: 8 | users: 9 | - guilyx 10 | - sampreets3 11 | - name: Automatic merge on approval 12 | conditions: 13 | - "#approved-reviews-by>=1" 14 | - check-success=tests 15 | - check-success=build 16 | - check-success=CodeFactor 17 | actions: 18 | merge: 19 | method: merge 20 | - name: Delete head branch after merge 21 | conditions: 22 | - merged 23 | actions: 24 | delete_head_branch: {} 25 | - name: Ask to resolve conflict 26 | conditions: 27 | - conflict 28 | actions: 29 | comment: 30 | message: This pull request is now in conflicts. Could you fix it @{{author}}? 🙏 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | Logo 4 | 5 |
6 | 7 |
8 | 9 | # Python PDDL 10 | 11 | ✨ A Python wrapper using JuliaPy for the PDDL.jl parser package and implementing its own planners. ✨ 12 | 13 |
14 | 15 |
16 | 17 | ![tests](https://github.com/APLA-Toolbox/PythonPDDL/workflows/tests/badge.svg?branch=main) 18 | ![build](https://github.com/APLA-Toolbox/PythonPDDL/workflows/build/badge.svg?branch=main) 19 | [![codecov](https://codecov.io/gh/APLA-Toolbox/PythonPDDL/branch/main/graph/badge.svg?token=63GHA9JUND)](https://codecov.io/gh/APLA-Toolbox/PythonPDDL) 20 | [![CodeFactor](https://www.codefactor.io/repository/github/apla-toolbox/pythonpddl/badge)](https://www.codefactor.io/repository/github/apla-toolbox/pythonpddl) 21 | [![Percentage of issues still open](http://isitmaintained.com/badge/open/APLA-Toolbox/PythonPDDL.svg)](http://isitmaintained.com/project/APLA-Toolbox/PythonPDDL "Percentage of issues still open") 22 | [![GitHub license](https://img.shields.io/github/license/Apla-Toolbox/PythonPDDL.svg)](https://github.com/Apla-Toolbox/PythonPDDL/blob/master/LICENSE) 23 | [![GitHub contributors](https://img.shields.io/github/contributors/Apla-Toolbox/PythonPDDL.svg)](https://GitHub.com/Apla-Toolbox/PythonPDDL/graphs/contributors/) 24 | ![PipPerMonths](https://img.shields.io/pypi/dm/jupyddl.svg) 25 | [![Pip version fury.io](https://badge.fury.io/py/jupyddl.svg)](https://pypi.python.org/pypi/jupyddl/) 26 | 27 |
28 | 29 |
30 | 31 | [Report Bug](https://github.com/APLA-Toolbox/PythonPDDL/issues) · [Request Feature](https://github.com/APLA-Toolbox/PythonPDDL/issues) 32 | 33 | Loved the project? Please consider [donating](https://www.buymeacoffee.com/dq01aOE) to help it improve! 34 | 35 |
36 | 37 | ## Features 🌱 38 | 39 | - ✨ Built to be expanded: easy to add new planners 40 | - 🖥️ Supported on MacOS and Ubuntu 41 | - 🎌 Built with Julia and Python 42 | - 🔎 Uninformed Planners (DFS, BFS) 43 | - 🧭 Informed Planners (Dijkstra, A*, Greedy Best First) 44 | - 📊 Several general purpose heuristics (Goal Count, Delete Relaxation [Hmax, Hadd], Critical Path [H1, H2, H3], Relaxed Critical Path [H1, H2, H3]) 45 | - 🍻 Maintained (Incoming: Landmarks Heuristics...) 46 | 47 | ## Docker 🐋 48 | 49 | You can also use the project in a docker container using [docker-pythonpddl](https://github.com/APLA-Toolbox/docker-pythonpddl) 50 | 51 | ## Install 💾 52 | 53 | - Install Python (3.7.5 is the tested version) 54 | 55 | - Install Julia 56 | 57 | ```bash 58 | $ wget https://julialang-s3.julialang.org/bin/linux/x64/1.5/julia-1.5.2-linux-x86_64.tar.gz 59 | $ tar -xvzf julia-1.5.2-linux-x86_64.tar.gz 60 | $ sudo cp -r julia-1.5.2 /opt/ 61 | $ sudo ln -s /opt/julia-1.5.2/bin/julia /usr/local/bin/julia 62 | ``` 63 | 64 | - Install Julia dependencies 65 | 66 | ```bash 67 | $ julia --color=yes -e 'using Pkg; Pkg.add(Pkg.PackageSpec(path="https://github.com/APLA-Toolbox/PDDL.jl"))' 68 | $ julia --color=yes -e 'using Pkg; Pkg.add(Pkg.PackageSpec(path="https://github.com/JuliaPy/PyCall.jl"))' 69 | ``` 70 | 71 | - Package installation (only if used as library, not needed to run the scripts) 72 | 73 | ```bash 74 | $ python3 -m pip install --upgrade pip 75 | $ python3 -m pip install jupyddl 76 | ``` 77 | 78 | ## IPC Script ⚔️ 79 | 80 | - Clone the project : 81 | ```shell 82 | $ git clone https://github.com/APLA-Toolbox/PythonPDDL 83 | $ cd PythonPDDL 84 | $ python3 -m pip install -r requirements.txt 85 | $ git submodule update --init // Only if you need PDDL files for testing 86 | ``` 87 | 88 | - Run the script : 89 | ```shell 90 | $ cd scripts/ 91 | $ python ipc.py "path_to_domain.pddl" "path_to_problem.pddl" "path_to_desired_output_file" 92 | ``` 93 | 94 | The output file will show the path with a list of state, the path with a list of action and the metrics proposed by IPC2018. 95 | 96 | ## Basic Usage 📑 97 | 98 | If using the jupyddl pip package: 99 | 100 | - If you want to use the data analysis tool, create a pddl-examples folder with pddl instances subfolders containing "problem.pddl" and "domain.pddl". (refer to APLA-Toolbox/pddl-examples) 101 | 102 | If you want to use it by cloning the project: 103 | 104 | ```shell 105 | $ git clone https://github.com/APLA-Toolbox/PythonPDDL 106 | $ cd PythonPDDL 107 | $ python3 -m pip install -r requirements.txt 108 | $ git submodule update --init 109 | ``` 110 | 111 | You should have a `pddl-examples` folder containing PDDL instances. 112 | 113 | ### AutomatedPlanner Class 🗺️ 114 | 115 | ```python 116 | from jupyddl import AutomatedPlanner # takes some time because it has to instantiate the Julia interface 117 | apl = AutomatedPlanner("pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl) 118 | 119 | apl.available_heuristics 120 | ["basic/zero", "basic/goal_count", "delete_relaxation/h_max", "delete_relaxation/h_add"] 121 | 122 | apl.initial_state 123 | 124 | 125 | actions = apl.available_actions(apl.initial_state) 126 | [, , , , , ] 127 | 128 | apl.satisfies(apl.problem.goal, apl.initial_state) 129 | False 130 | 131 | apl.transition(apl.initial_state, actions[0]) 132 | 133 | 134 | path = apl.breadth_first_search() # computes path ([]State) with BFS 135 | 136 | print(apl.get_state_def_from_path(path)) 137 | [, , ] 138 | 139 | print(apl.get_actions_from_path(path)) 140 | [, , ] 141 | ``` 142 | 143 | ### DataAnalyst (more like Viz) Class 📈 144 | 145 | Make sure you have a pddl-examples folder where you run your environment that contains independent folders with "domain.pddl" and "problem.pddl" files, with those standard names. ( if you didn't generate with git submodule update ) 146 | 147 | ```python 148 | from jupyddl import DataAnalyst 149 | 150 | da = DataAnalyst() 151 | da.plot_astar() # plots complexity statistics for all the problem.pddl/domain.pddl couples in the pddl-examples/ folder 152 | 153 | da.plot_astar(problem="pddl-examples/dinner/problem.pddl", domain="pddl-examples/dinner/domain.pddl") # scatter complexity statistics for the provided pddl 154 | 155 | da.plot_astar(heuristic_key="basic/zero") # use h=0 instead of goal_count for your computation 156 | 157 | da.plot_dfs() # same as astar 158 | 159 | da.comparative_data_plot() # Run all planners on the pddl-examples folder and plots them on the same figure, data is stored in a data.json file 160 | 161 | da.comparative_data_plot(astar=False) # Exclude astar from the comparative plot 162 | 163 | da.comparative_data_plot(heuristic_key="basic/zero") # use zero heuristic for h based planners 164 | 165 | da.comparative_data_plot(collect_new_data=False) # uses data.json to plot the data 166 | 167 | da.comparative_astar_heuristic_plot() # compare results of astar with all available heuristics 168 | ``` 169 | 170 | ## Cite 📰 171 | 172 | If you use the project in your work, please consider citing it with: 173 | ``` 174 | @misc{https://doi.org/10.13140/rg.2.2.22418.89282, 175 | doi = {10.13140/RG.2.2.22418.89282}, 176 | url = {http://rgdoi.net/10.13140/RG.2.2.22418.89282}, 177 | author = {Erwin Lejeune}, 178 | language = {en}, 179 | title = {Jupyddl, an extensible python library for PDDL planning and parsing}, 180 | publisher = {Unpublished}, 181 | year = {2021} 182 | } 183 | ``` 184 | 185 | List of publications & preprints using `jupyddl` (please open a pull request to add missing entries): 186 | 187 | * [name](link) (month year) 188 | 189 | ## Contribute 🆘 190 | 191 | Please see `docs/CONTRIBUTING.md` for more details on contributing! 192 | 193 | ## Maintainers Ⓜ️ 194 | 195 | - Erwin Lejeune 196 | - Sampreet Sarkar 197 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | require_ci_to_pass: yes 3 | 4 | coverage: 5 | precision: 2 6 | round: down 7 | range: "70...100" 8 | 9 | parsers: 10 | gcov: 11 | branch_detection: 12 | conditional: yes 13 | loop: yes 14 | method: no 15 | macro: no 16 | ignore: 17 | - "setup.py" 18 | - "scripts/*" 19 | comment: 20 | layout: "reach,diff,flags,files,footer" 21 | behavior: default 22 | require_changes: no 23 | -------------------------------------------------------------------------------- /docs/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at erwin.lejeune15@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /docs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to PythonPDDL 2 | We love your input! We want to make contributing to this project as easy and transparent as possible, whether it's: 3 | 4 | - Reporting a bug 5 | - Discussing the current state of the code 6 | - Submitting a fix 7 | - Proposing new features 8 | - Becoming a maintainer 9 | 10 | ## We Develop with Github 11 | We use github to host code, to track issues and feature requests, as well as accept pull requests. 12 | 13 | ## We Use [Github Flow](https://guides.github.com/introduction/flow/index.html), So All Code Changes Happen Through Pull Requests 14 | Pull requests are the best way to propose changes to the codebase (we use [Github Flow](https://guides.github.com/introduction/flow/index.html)). We actively welcome your pull requests: 15 | 16 | 1. Fork the repo and create your branch from `master`. 17 | 2. If you've added code that should be tested, add tests. 18 | 3. If you've changed APIs, update the documentation. 19 | 4. Ensure the test suite passes. 20 | 5. Make sure your code lints. 21 | 6. Issue that pull request! 22 | 23 | ## Any contributions you make will be under the Apache 2.0 Software License 24 | In short, when you submit code changes, your submissions are understood to be under the same [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) that covers the project. Feel free to contact the maintainers if that's a concern. 25 | 26 | ## Report bugs using Github's [issues](https://github.com/briandk/transcriptase-atom/issues) 27 | We use GitHub issues to track public bugs. Report a bug by [opening a new issue](); it's that easy! 28 | 29 | ## Write bug reports with detail, background, and sample code 30 | [This is an example](http://stackoverflow.com/q/12488905/180626) of a bug report I wrote, and I think it's not a bad model. Here's [another example from Craig Hockenberry](http://www.openradar.me/11905408), an app developer whom I greatly respect. 31 | 32 | **Great Bug Reports** tend to have: 33 | 34 | - A quick summary and/or background 35 | - Steps to reproduce 36 | - Be specific! 37 | - Give sample code if you can. [My stackoverflow question](http://stackoverflow.com/q/12488905/180626) includes sample code that *anyone* with a base R setup can run to reproduce what I was seeing 38 | - What you expected would happen 39 | - What actually happens 40 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 41 | 42 | People *love* thorough bug reports. I'm not even kidding. 43 | 44 | ## Use a Consistent Coding Style 45 | We use black to format automatically your PR to master. Please ensure PEP8 and PEP20 are respected. 46 | 47 | ## License 48 | By contributing, you agree that your contributions will be licensed under its MIT License. 49 | 50 | ## References 51 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md) 52 | -------------------------------------------------------------------------------- /jupyddl/__init__.py: -------------------------------------------------------------------------------- 1 | from .automated_planner import AutomatedPlanner 2 | from .data_analyst import DataAnalyst 3 | -------------------------------------------------------------------------------- /jupyddl/a_star.py: -------------------------------------------------------------------------------- 1 | from .node import Node 2 | import logging 3 | import math 4 | from time import time as now 5 | from datetime import datetime as timestamp 6 | from .metrics import Metrics 7 | 8 | 9 | class AStarBestFirstSearch: 10 | def __init__(self, automated_planner, heuristic_function): 11 | self.time_start = now() 12 | self.automated_planner = automated_planner 13 | self.metrics = Metrics() 14 | self.init = Node( 15 | self.automated_planner.initial_state, 16 | automated_planner, 17 | is_closed=False, 18 | is_open=True, 19 | heuristic=heuristic_function, 20 | heuristic_based=True, 21 | metric=self.metrics, 22 | ) 23 | self.heuristic_function = heuristic_function 24 | self.open_nodes_n = 1 25 | self.nodes = dict() 26 | self.nodes[self.__hash(self.init)] = self.init 27 | 28 | def __hash(self, node): 29 | sep = ", Dict{Symbol,Any}" 30 | string = str(node.state) 31 | return string.split(sep, 1)[0] + ")" 32 | 33 | def search(self, node_bound=float("inf")): 34 | self.automated_planner.logger.debug( 35 | "Search started at: " + str(timestamp.now()) 36 | ) 37 | while self.open_nodes_n > 0: 38 | current_key = min( 39 | [n for n in self.nodes if self.nodes[n].is_open], 40 | key=(lambda k: self.nodes[k].f_cost), 41 | ) 42 | current_node = self.nodes[current_key] 43 | 44 | self.metrics.n_evaluated += 1 45 | if self.automated_planner.satisfies( 46 | self.automated_planner.problem.goal, current_node.state 47 | ): 48 | self.metrics.runtime = now() - self.time_start 49 | self.automated_planner.logger.debug( 50 | "Search finished at: " + str(timestamp.now()) 51 | ) 52 | return current_node, self.metrics 53 | 54 | current_node.is_closed = True 55 | current_node.is_open = False 56 | self.open_nodes_n -= 1 57 | 58 | if self.metrics.n_opened > node_bound: 59 | break 60 | 61 | actions = self.automated_planner.available_actions(current_node.state) 62 | if actions: 63 | self.metrics.n_expended += 1 64 | else: 65 | self.metrics.deadend_states += 1 66 | for act in actions: 67 | child = Node( 68 | state=self.automated_planner.transition(current_node.state, act), 69 | automated_planner=self.automated_planner, 70 | parent_action=act, 71 | parent=current_node, 72 | heuristic=self.heuristic_function, 73 | is_closed=False, 74 | is_open=True, 75 | heuristic_based=True, 76 | metric=self.metrics, 77 | ) 78 | self.metrics.n_generated += 1 79 | child_hash = self.__hash(child) 80 | if child_hash in self.nodes: 81 | if self.nodes[child_hash].is_closed: 82 | continue 83 | if not self.nodes[child_hash].is_open: 84 | self.nodes[child_hash] = child 85 | self.open_nodes_n += 1 86 | self.metrics.n_opened += 1 87 | else: 88 | if child.g_cost < self.nodes[child_hash].g_cost: 89 | self.nodes[child_hash] = child 90 | self.open_nodes_n += 1 91 | self.metrics.n_opened += 1 92 | self.metrics.n_reopened += 1 93 | 94 | else: 95 | self.nodes[child_hash] = child 96 | self.open_nodes_n += 1 97 | self.metrics.n_opened += 1 98 | self.metrics.runtime = now() - self.time_start 99 | self.automated_planner.logger.warning("!!! No path found !!!") 100 | return None, self.metrics 101 | -------------------------------------------------------------------------------- /jupyddl/automated_planner.py: -------------------------------------------------------------------------------- 1 | from .bfs import BreadthFirstSearch 2 | from .dfs import DepthFirstSearch 3 | from .dijkstra import DijkstraBestFirstSearch 4 | from .a_star import AStarBestFirstSearch 5 | from .greedy_best_first import GreedyBestFirstSearch 6 | from .metrics import Metrics 7 | from .heuristics import ( 8 | BasicHeuristic, 9 | DeleteRelaxationHeuristic, 10 | RelaxedCriticalPathHeuristic, 11 | CriticalPathHeuristic, 12 | ) 13 | import coloredlogs 14 | import logging 15 | import julia 16 | 17 | _ = julia.Julia(compiled_modules=False, debug=False) 18 | from julia import PDDL 19 | from time import time as now 20 | 21 | logging.getLogger("julia").setLevel(logging.WARNING) 22 | 23 | 24 | class AutomatedPlanner: 25 | def __init__(self, domain_path, problem_path, log_level="DEBUG"): 26 | # Planning Tool 27 | self.pddl = PDDL 28 | self.domain_path = domain_path 29 | self.problem_path = problem_path 30 | self.domain = self.pddl.load_domain(domain_path) 31 | self.problem = self.pddl.load_problem(problem_path) 32 | self.initial_state = self.pddl.initialize(self.problem) 33 | self.goals = self.__flatten_goal() 34 | self.available_heuristics = [ 35 | "basic/zero", 36 | "basic/goal_count", 37 | "delete_relaxation/h_add", 38 | "delete_relaxation/h_max", 39 | "relaxed_critical_path/1", 40 | "relaxed_critical_path/2", 41 | "relaxed_critical_path/3", 42 | "critical_path/1", 43 | "critical_path/2", 44 | "critical_path/3", 45 | ] 46 | 47 | # Logger 48 | self.__init_logger(log_level) 49 | self.logger = logging.getLogger("automated_planning") 50 | coloredlogs.install(level=log_level) 51 | 52 | # Running external Julia functions once to create the routes 53 | self.__run_julia_once() 54 | 55 | def __run_julia_once(self): 56 | self.satisfies(self.problem.goal, self.initial_state) 57 | self.state_has_term(self.initial_state, self.goals[0]) 58 | actions = self.available_actions(self.initial_state) 59 | if actions: 60 | self.transition(self.initial_state, actions[0]) 61 | return 62 | logging.warning( 63 | "No actions from initial state, a path probably (definitely) won't be found" 64 | ) 65 | 66 | def __init_logger(self, log_level): 67 | import os 68 | 69 | if not os.path.exists("logs"): 70 | os.makedirs("logs") 71 | logging.basicConfig( 72 | filename="logs/main.log", 73 | format="%(levelname)s:%(message)s", 74 | filemode="w", 75 | level=log_level, 76 | ) 77 | 78 | def display_available_heuristics(self): 79 | print(self.available_heuristics) 80 | 81 | def transition(self, state, action): 82 | return self.pddl.transition(self.domain, state, action, check=False) 83 | 84 | def available_actions(self, state): 85 | try: 86 | return self.pddl.available(state, self.domain) 87 | except (RuntimeError, TypeError, NameError): 88 | self.logger.warning( 89 | "Runtime, Type or Name error occured when fetching available action from state" 90 | + str(state) 91 | ) 92 | return [] 93 | 94 | def satisfies(self, asserted_state, state): 95 | return self.pddl.satisfy(asserted_state, state, self.domain)[0] 96 | 97 | def state_has_term(self, state, term): 98 | if self.pddl.has_term_in_state(self.domain, state, term): 99 | return True 100 | return False 101 | 102 | def __flatten_goal(self): 103 | return self.pddl.flatten_goal(self.problem) 104 | 105 | def __retrace_path(self, node): 106 | if not node: 107 | return [] 108 | path = [] 109 | while node.parent: 110 | path.append(node) 111 | node = node.parent 112 | path.reverse() 113 | return path 114 | 115 | def get_actions_from_path(self, path): 116 | if not path: 117 | self.logger.warning("Path is empty, can't operate...") 118 | return [] 119 | actions = [] 120 | for node in path: 121 | if not node.parent_action: 122 | break 123 | act = str(node.parent_action).replace("', "total-cost =" 135 | ) 136 | state_str = state_str.replace("))>", "") 137 | return state_str 138 | 139 | def get_state_def_from_path(self, path): 140 | if not path: 141 | self.logger.warning("Path is empty, can't operate...") 142 | return [] 143 | trimmed_path = [] 144 | for node in path: 145 | state = self.__stringify_state(node.state) 146 | trimmed_path.append(state) 147 | return trimmed_path 148 | 149 | def breadth_first_search(self, node_bound=float("inf")): 150 | bfs = BreadthFirstSearch(self) 151 | last_node, metrics = bfs.search(node_bound=node_bound) 152 | path = self.__retrace_path(last_node) 153 | 154 | return path, metrics 155 | 156 | def depth_first_search(self, node_bound=float("inf")): 157 | dfs = DepthFirstSearch(self) 158 | last_node, metrics = dfs.search(node_bound=node_bound) 159 | path = self.__retrace_path(last_node) 160 | 161 | return path, metrics 162 | 163 | def dijktra_best_first_search(self, node_bound=float("inf")): 164 | dijkstra = DijkstraBestFirstSearch(self) 165 | last_node, metrics = dijkstra.search(node_bound=node_bound) 166 | path = self.__retrace_path(last_node) 167 | 168 | return path, metrics 169 | 170 | def astar_best_first_search( 171 | self, node_bound=float("inf"), heuristic_key="basic/goal_count" 172 | ): 173 | if "basic" in heuristic_key: 174 | heuristic = BasicHeuristic(self, heuristic_key) 175 | elif "delete_relaxation" in heuristic_key: 176 | heuristic = DeleteRelaxationHeuristic(self, heuristic_key) 177 | elif "relaxed_critical_path" in heuristic_key: 178 | heuristic = RelaxedCriticalPathHeuristic(self, int(heuristic_key[-1])) 179 | elif "critical_path" in heuristic_key: 180 | heuristic = CriticalPathHeuristic(self, int(heuristic_key[-1])) 181 | else: 182 | logging.fatal("Not yet implemented") 183 | return [], Metrics() 184 | astar = AStarBestFirstSearch(self, heuristic.compute) 185 | last_node, metrics = astar.search(node_bound=node_bound) 186 | path = self.__retrace_path(last_node) 187 | 188 | return path, metrics 189 | 190 | def greedy_best_first_search( 191 | self, node_bound=float("inf"), heuristic_key="basic/goal_count" 192 | ): 193 | if "basic" in heuristic_key: 194 | if "zero" in heuristic_key: 195 | self.logger.warning( 196 | "Forced heuristic to goal_count. Zero isn't a proper heuristic for Greedy Best First." 197 | ) 198 | heuristic = BasicHeuristic(self, "basic/goal_count") 199 | elif "delete_relaxation" in heuristic_key: 200 | heuristic = DeleteRelaxationHeuristic(self, heuristic_key) 201 | elif "relaxed_critical_path" in heuristic_key: 202 | logging.warning("Relaxed Critical Path is deficient for H^2 and H^3") 203 | heuristic = RelaxedCriticalPathHeuristic(self, int(heuristic_key[-1])) 204 | elif "critical_path" in heuristic_key: 205 | heuristic = CriticalPathHeuristic(self, int(heuristic_key[-1])) 206 | else: 207 | logging.fatal("Not yet implemented") 208 | return [], Metrics() 209 | greedy = GreedyBestFirstSearch(self, heuristic.compute) 210 | last_node, metrics = greedy.search(node_bound=node_bound) 211 | path = self.__retrace_path(last_node) 212 | 213 | return path, metrics 214 | -------------------------------------------------------------------------------- /jupyddl/bfs.py: -------------------------------------------------------------------------------- 1 | from .node import Node 2 | from datetime import datetime as timestamp 3 | from time import time as now 4 | from .metrics import Metrics 5 | 6 | 7 | class BreadthFirstSearch: 8 | def __init__(self, automated_planner): 9 | self.time_start = now() 10 | self.visited = [] 11 | self.automated_planner = automated_planner 12 | self.init = Node(self.automated_planner.initial_state, automated_planner) 13 | self.queue = [self.init] 14 | self.metrics = Metrics() 15 | 16 | def search(self, node_bound=float("inf")): 17 | self.automated_planner.logger.debug( 18 | "Search started at: " + str(timestamp.now()) 19 | ) 20 | while self.queue: 21 | current_node = self.queue.pop(0) 22 | if current_node not in self.visited: 23 | self.visited.append(current_node) 24 | self.metrics.n_evaluated += 1 25 | if self.automated_planner.satisfies( 26 | self.automated_planner.problem.goal, current_node.state 27 | ): 28 | self.metrics.runtime = now() - self.time_start 29 | self.automated_planner.logger.debug( 30 | "Search finished at: " + str(timestamp.now()) 31 | ) 32 | self.metrics.total_cost = current_node.g_cost 33 | return current_node, self.metrics 34 | 35 | if self.metrics.n_opened > node_bound: 36 | break 37 | 38 | actions = self.automated_planner.available_actions(current_node.state) 39 | if not actions: 40 | self.metrics.deadend_states += 1 41 | else: 42 | self.metrics.n_expended += 1 43 | for act in actions: 44 | child = Node( 45 | state=self.automated_planner.transition( 46 | current_node.state, act 47 | ), 48 | automated_planner=self.automated_planner, 49 | parent_action=act, 50 | parent=current_node, 51 | ) 52 | self.metrics.n_generated += 1 53 | if child in self.visited: 54 | continue 55 | self.metrics.n_opened += 1 56 | self.queue.append(child) 57 | self.metrics.runtime = now() - self.time_start 58 | self.automated_planner.logger.warning("!!! No path found !!!") 59 | return None, self.metrics 60 | -------------------------------------------------------------------------------- /jupyddl/data_analyst.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | import matplotlib as mpl 4 | import logging 5 | 6 | if "DISPLAY" not in os.environ: 7 | mpl.use("agg") 8 | else: 9 | mpl.use("TkAgg") 10 | mpl.set_loglevel("WARNING") 11 | import matplotlib.pyplot as plt 12 | 13 | plt.style.use("ggplot") 14 | from .automated_planner import AutomatedPlanner 15 | from os import path 16 | import json 17 | 18 | 19 | class DataAnalyst: 20 | def __init__(self): 21 | logging.info("Instantiating data analyst...") 22 | self.available_heuristics = [ 23 | "basic/goal_count", 24 | "basic/zero", 25 | "delete_relaxation/h_add", 26 | "delete_relaxation/h_max", 27 | ] 28 | 29 | def __get_all_pddl_from_data(self, max_pddl_instances=-1): 30 | tested_files = [] 31 | domains_problems = [] 32 | i = 0 33 | if "DISPLAY" in os.environ: 34 | for root, _, files in os.walk("pddl-examples/", topdown=False): 35 | for name in files: 36 | # if "README" in name: 37 | # continue 38 | # if "LICENSE" in name: 39 | # continue 40 | # if ".gitignore" in name: 41 | # continue 42 | tested_files.append(os.getcwd() + "/" + os.path.join(root, name)) 43 | if i % 2 != 0: 44 | domains_problems.append((tested_files[i - 1], tested_files[i])) 45 | i += 1 46 | if max_pddl_instances != -1 and i >= max_pddl_instances * 2: 47 | return domains_problems 48 | return domains_problems 49 | return [ 50 | ("pddl-examples/dinner/problem.pddl", "pddl-examples/dinner/domain.pddl"), 51 | ("pddl-examples/dinner/problem.pddl", "pddl-examples/dinner/domain.pddl"), 52 | ] 53 | 54 | def __plot_data(self, times, total_nodes, plot_title): 55 | data = dict() 56 | for i, val in enumerate(total_nodes): 57 | data[val] = times[i] 58 | nodes_sorted = sorted(list(data.keys())) 59 | times_y = [] 60 | for node_opened in nodes_sorted: 61 | times_y.append(data[node_opened]) 62 | plt.plot(nodes_sorted, times_y, "r:o") 63 | plt.xlabel("Number of opened nodes") 64 | plt.ylabel("Planning computation time (s)") 65 | plt.xscale("symlog") 66 | plt.title(plot_title) 67 | plt.grid(True) 68 | plt.show(block=False) 69 | 70 | def __plot_data_generic(self, data, name): 71 | _, ax = plt.subplots() 72 | plt.xlabel("Domain") 73 | plt.ylabel(name) 74 | for key, val in data.items(): 75 | ax.plot(val[name], "-o", label=key) 76 | 77 | plt.title("Planners metric comparison") 78 | plt.legend(loc="upper left") 79 | plt.grid(True) 80 | plt.show(block=False) 81 | 82 | def __scatter_data(self, times, total_nodes, plot_title): 83 | plt.scatter(total_nodes, times) 84 | plt.xlabel("Number of opened nodes") 85 | plt.ylabel("Planning computation time (s)") 86 | plt.xscale("symlog") 87 | plt.title(plot_title) 88 | plt.grid(True) 89 | plt.show(block=False) 90 | 91 | def __gather_data_astar( 92 | self, 93 | domain_path="", 94 | problem_path="", 95 | heuristic_key="basic/goal_count", 96 | max_pddl_instances=-1, 97 | ): 98 | has_multiple_files_tested = True 99 | if not domain_path or not problem_path: 100 | metrics = dict() 101 | costs = [] 102 | for problem, domain in self.__get_all_pddl_from_data( 103 | max_pddl_instances=max_pddl_instances 104 | ): 105 | logging.debug( 106 | "Loading new PDDL instance planned with A* [ " 107 | + heuristic_key 108 | + " ]" 109 | ) 110 | logging.debug("Domain: " + domain) 111 | logging.debug("Problem: " + problem) 112 | apla = AutomatedPlanner(domain, problem) 113 | if heuristic_key in apla.available_heuristics: 114 | path, metrics_obj = apla.astar_best_first_search( 115 | heuristic_key=heuristic_key 116 | ) 117 | else: 118 | logging.critical( 119 | "Heuristic is not implemented! (Key not found in registered heuristics dict)" 120 | ) 121 | return [0], [0], [0], has_multiple_files_tested 122 | if path: 123 | metrics[metrics_obj.runtime] = metrics_obj.n_opened 124 | costs.append(path[-1].g_cost) 125 | else: 126 | metrics[0] = 0 127 | costs.append(0) 128 | 129 | total_nodes = list(metrics.values()) 130 | times = list(metrics.keys()) 131 | return costs, times, total_nodes, has_multiple_files_tested 132 | has_multiple_files_tested = False 133 | logging.debug("Loading new PDDL instance...") 134 | logging.debug("Domain: " + domain_path) 135 | logging.debug("Problem: " + problem_path) 136 | apla = AutomatedPlanner(domain_path, problem_path) 137 | if heuristic_key in apla.available_heuristics: 138 | path, metrics_obj = apla.astar_best_first_search( 139 | heuristic_key=heuristic_key 140 | ) 141 | else: 142 | logging.critical( 143 | "Heuristic is not implemented! (Key not found in registered heuristics dict)" 144 | ) 145 | return [0], [0], [0], has_multiple_files_tested 146 | if path: 147 | return ( 148 | [path[-1].g_cost], 149 | [metrics_obj.runtime], 150 | [metrics_obj.n_opened], 151 | has_multiple_files_tested, 152 | ) 153 | return [0], [0], [0], has_multiple_files_tested 154 | 155 | def plot_astar( 156 | self, 157 | heuristic_key="basic/goal_count", 158 | domain="", 159 | problem="", 160 | max_pddl_instances=-1, 161 | ): 162 | if bool(not problem) != bool(not domain): 163 | logging.warning( 164 | "Either problem or domain wasn't provided, testing all files in data folder" 165 | ) 166 | problem = domain = "" 167 | _, times, total_nodes, has_multiple_files_tested = self.__gather_data_astar( 168 | heuristic_key=heuristic_key, 169 | problem_path=problem, 170 | domain_path=domain, 171 | max_pddl_instances=max_pddl_instances, 172 | ) 173 | title = "A* Statistics" + "[Heuristic: " + heuristic_key + "]" 174 | if has_multiple_files_tested: 175 | self.__plot_data(times, total_nodes, title) 176 | else: 177 | self.__scatter_data(times, total_nodes, title) 178 | 179 | def __gather_data_greedy_bfs( 180 | self, 181 | domain_path="", 182 | problem_path="", 183 | heuristic_key="basic/goal_count", 184 | max_pddl_instances=-1, 185 | ): 186 | has_multiple_files_tested = True 187 | if not domain_path or not problem_path: 188 | metrics = dict() 189 | costs = [] 190 | for problem, domain in self.__get_all_pddl_from_data( 191 | max_pddl_instances=max_pddl_instances 192 | ): 193 | logging.debug( 194 | "Loading new PDDL instance planned with A* [ " 195 | + heuristic_key 196 | + " ]" 197 | ) 198 | logging.debug("Domain: " + domain) 199 | logging.debug("Problem: " + problem) 200 | apla = AutomatedPlanner(domain, problem) 201 | if heuristic_key in apla.available_heuristics: 202 | path, metrics_obj = apla.greedy_best_first_search( 203 | heuristic_key=heuristic_key 204 | ) 205 | else: 206 | logging.critical( 207 | "Heuristic is not implemented! (Key not found in registered heuristics dict)" 208 | ) 209 | return [0], [0], [0], has_multiple_files_tested 210 | if path: 211 | metrics[metrics_obj.runtime] = metrics_obj.n_opened 212 | costs.append(path[-1].g_cost) 213 | else: 214 | metrics[0] = 0 215 | costs.append(0) 216 | 217 | total_nodes = list(metrics.values()) 218 | times = list(metrics.keys()) 219 | return costs, times, total_nodes, has_multiple_files_tested 220 | has_multiple_files_tested = False 221 | logging.debug("Loading new PDDL instance...") 222 | logging.debug("Domain: " + domain_path) 223 | logging.debug("Problem: " + problem_path) 224 | apla = AutomatedPlanner(domain_path, problem_path) 225 | if heuristic_key in apla.available_heuristics: 226 | path, metrics_obj = apla.greedy_best_first_search( 227 | heuristic_key=heuristic_key 228 | ) 229 | else: 230 | logging.critical( 231 | "Heuristic is not implemented! (Key not found in registered heuristics dict)" 232 | ) 233 | return [0], [0], [0], has_multiple_files_tested 234 | if path: 235 | return ( 236 | [path[-1].g_cost], 237 | [metrics_obj.runtime], 238 | [metrics_obj.n_opened], 239 | has_multiple_files_tested, 240 | ) 241 | return [0], [0], [0], has_multiple_files_tested 242 | 243 | def plot_greedy_bfs( 244 | self, 245 | heuristic_key="basic/goal_count", 246 | domain="", 247 | problem="", 248 | max_pddl_instances=-1, 249 | ): 250 | if bool(not problem) != bool(not domain): 251 | logging.warning( 252 | "Either problem or domain wasn't provided, testing all files in data folder" 253 | ) 254 | problem = domain = "" 255 | ( 256 | _, 257 | times, 258 | total_nodes, 259 | has_multiple_files_tested, 260 | ) = self.__gather_data_greedy_bfs( 261 | heuristic_key=heuristic_key, 262 | problem_path=problem, 263 | domain_path=domain, 264 | max_pddl_instances=max_pddl_instances, 265 | ) 266 | title = ( 267 | "Greedy Best First Search Statistics" + "[Heuristic: " + heuristic_key + "]" 268 | ) 269 | if has_multiple_files_tested: 270 | self.__plot_data(times, total_nodes, title) 271 | else: 272 | self.__scatter_data(times, total_nodes, title) 273 | 274 | def __gather_data_bfs(self, domain_path="", problem_path="", max_pddl_instances=-1): 275 | has_multiple_files_tested = True 276 | if not domain_path or not problem_path: 277 | metrics = dict() 278 | costs = [] 279 | for problem, domain in self.__get_all_pddl_from_data( 280 | max_pddl_instances=max_pddl_instances 281 | ): 282 | logging.debug("Loading new PDDL instance planned with BFS...") 283 | logging.debug("Domain: " + domain) 284 | logging.debug("Problem: " + problem) 285 | apla = AutomatedPlanner(domain, problem) 286 | path, metrics_obj = apla.breadth_first_search() 287 | if path: 288 | metrics[metrics_obj.runtime] = metrics_obj.n_opened 289 | costs.append(path[-1].g_cost) 290 | else: 291 | metrics[0] = 0 292 | costs.append(0) 293 | 294 | total_nodes = list(metrics.values()) 295 | times = list(metrics.keys()) 296 | return costs, times, total_nodes, has_multiple_files_tested 297 | has_multiple_files_tested = False 298 | logging.debug("Loading new PDDL instance...") 299 | logging.debug("Domain: " + domain_path) 300 | logging.debug("Problem: " + problem_path) 301 | apla = AutomatedPlanner(domain_path, problem_path) 302 | path, metrics_obj = apla.breadth_first_search() 303 | if path: 304 | return ( 305 | [path[-1].g_cost], 306 | [metrics_obj.runtime], 307 | [metrics_obj.n_opened], 308 | has_multiple_files_tested, 309 | ) 310 | return [0], [0], [0], has_multiple_files_tested 311 | 312 | def plot_bfs(self, domain="", problem="", max_pddl_instances=-1): 313 | title = "BFS Statistics" 314 | if bool(not problem) != bool(not domain): 315 | logging.warning( 316 | "Either problem or domain wasn't provided, testing all files in data folder" 317 | ) 318 | problem = domain = "" 319 | _, times, total_nodes, has_multiple_files_tested = self.__gather_data_bfs( 320 | problem_path=problem, 321 | domain_path=domain, 322 | max_pddl_instances=max_pddl_instances, 323 | ) 324 | if has_multiple_files_tested: 325 | self.__plot_data(times, total_nodes, title) 326 | else: 327 | self.__scatter_data(times, total_nodes, title) 328 | 329 | def __gather_data_dfs(self, domain_path="", problem_path="", max_pddl_instances=-1): 330 | has_multiple_files_tested = True 331 | if not domain_path or not problem_path: 332 | metrics = dict() 333 | costs = [] 334 | for problem, domain in self.__get_all_pddl_from_data( 335 | max_pddl_instances=max_pddl_instances 336 | ): 337 | logging.debug("Loading new PDDL instance planned with DFS...") 338 | logging.debug("Domain: " + domain) 339 | logging.debug("Problem: " + problem) 340 | apla = AutomatedPlanner(domain, problem) 341 | path, metrics_obj = apla.depth_first_search() 342 | if path: 343 | metrics[metrics_obj.runtime] = metrics_obj.n_opened 344 | costs.append(path[-1].g_cost) 345 | else: 346 | metrics[0] = 0 347 | costs.append(0) 348 | 349 | total_nodes = list(metrics.values()) 350 | times = list(metrics.keys()) 351 | return costs, times, total_nodes, has_multiple_files_tested 352 | has_multiple_files_tested = False 353 | logging.debug("Loading new PDDL instance...") 354 | logging.debug("Domain: " + domain_path) 355 | logging.debug("Problem: " + problem_path) 356 | apla = AutomatedPlanner(domain_path, problem_path) 357 | path, metrics_obj = apla.depth_first_search() 358 | if path: 359 | return ( 360 | [path[-1].g_cost], 361 | [metrics_obj.runtime], 362 | [metrics_obj.n_opened], 363 | has_multiple_files_tested, 364 | ) 365 | return [0], [0], [0], has_multiple_files_tested 366 | 367 | def plot_dfs(self, problem="", domain="", max_pddl_instances=-1): 368 | title = "DFS Statistics" 369 | if bool(not problem) != bool(not domain): 370 | logging.warning( 371 | "Either problem or domain wasn't provided, testing all files in data folder" 372 | ) 373 | problem = domain = "" 374 | _, times, total_nodes, has_multiple_files_tested = self.__gather_data_dfs( 375 | problem_path=problem, 376 | domain_path=domain, 377 | max_pddl_instances=max_pddl_instances, 378 | ) 379 | if has_multiple_files_tested: 380 | self.__plot_data(times, total_nodes, title) 381 | else: 382 | self.__scatter_data(times, total_nodes, title) 383 | 384 | def __gather_data_dijkstra( 385 | self, domain_path="", problem_path="", max_pddl_instances=-1 386 | ): 387 | has_multiple_files_tested = True 388 | if not domain_path or not problem_path: 389 | metrics = dict() 390 | costs = [] 391 | for problem, domain in self.__get_all_pddl_from_data( 392 | max_pddl_instances=max_pddl_instances 393 | ): 394 | logging.debug("Loading new PDDL instance planned with Dijkstra...") 395 | logging.debug("Domain: " + domain) 396 | logging.debug("Problem: " + problem) 397 | apla = AutomatedPlanner(domain, problem) 398 | path, metrics_obj = apla.dijktra_best_first_search() 399 | if path: 400 | metrics[metrics_obj.runtime] = metrics_obj.n_opened 401 | costs.append(path[-1].g_cost) 402 | else: 403 | metrics[0] = 0 404 | costs.append(0) 405 | 406 | total_nodes = list(metrics.values()) 407 | times = list(metrics.keys()) 408 | return costs, times, total_nodes, has_multiple_files_tested 409 | has_multiple_files_tested = False 410 | logging.debug("Loading new PDDL instance...") 411 | logging.debug("Domain: " + domain_path) 412 | logging.debug("Problem: " + problem_path) 413 | apla = AutomatedPlanner(domain_path, problem_path) 414 | path, metrics_obj = apla.dijktra_best_first_search() 415 | if path: 416 | return ( 417 | [path[-1].g_cost], 418 | [metrics_obj.runtime], 419 | [metrics_obj.n_opened], 420 | has_multiple_files_tested, 421 | ) 422 | return [0], [0], [0], has_multiple_files_tested 423 | 424 | def plot_dijkstra(self, problem="", domain="", max_pddl_instances=-1): 425 | title = "Dijkstra Statistics" 426 | if bool(not problem) != bool(not domain): 427 | logging.warning( 428 | "Either problem or domain wasn't provided, testing all files in data folder" 429 | ) 430 | problem = domain = "" 431 | _, times, total_nodes, has_multiple_files_tested = self.__gather_data_dijkstra( 432 | problem_path=problem, 433 | domain_path=domain, 434 | max_pddl_instances=max_pddl_instances, 435 | ) 436 | if has_multiple_files_tested: 437 | self.__plot_data(times, total_nodes, title) 438 | else: 439 | self.__scatter_data(times, total_nodes, title) 440 | 441 | def __gather_data( 442 | self, 443 | heuristic_key="basic/goal_count", 444 | astar=True, 445 | bfs=True, 446 | dfs=True, 447 | dijkstra=True, 448 | greedy_bfs=False, 449 | domain="", 450 | problem="", 451 | max_pddl_instances=-1, 452 | ): 453 | gatherers = [] 454 | xdata = dict() 455 | ydata = dict() 456 | 457 | if bfs: 458 | gatherers.append(("BFS", self.__gather_data_bfs)) 459 | if dfs: 460 | gatherers.append(("DFS", self.__gather_data_dfs)) 461 | if dijkstra: 462 | gatherers.append(("Dijkstra", self.__gather_data_dijkstra)) 463 | if astar: 464 | gatherers.append(("A*", self.__gather_data_astar)) 465 | if greedy_bfs: 466 | gatherers.append(("Greedy Best First", self.__gather_data_greedy_bfs)) 467 | 468 | _, _, _, _ = self.__gather_data_bfs( 469 | domain_path=domain, problem_path=problem 470 | ) # Dummy line to do first parsing and get rid of static loading 471 | for name, g in gatherers: 472 | if g == self.__gather_data_astar or g == self.__gather_data_greedy_bfs: 473 | _, times, nodes, _ = g( 474 | domain_path=domain, 475 | problem_path=problem, 476 | heuristic_key=heuristic_key, 477 | max_pddl_instances=max_pddl_instances, 478 | ) 479 | else: 480 | _, times, nodes, _ = g( 481 | domain_path=domain, 482 | problem_path=problem, 483 | max_pddl_instances=max_pddl_instances, 484 | ) 485 | ydata[name] = times 486 | xdata[name] = nodes 487 | return xdata, ydata 488 | 489 | def comparative_astar_heuristic_plot( 490 | self, domain="", problem="", max_pddl_instances=-1 491 | ): 492 | _, ax = plt.subplots() 493 | plt.xlabel("Number of opened nodes") 494 | plt.ylabel("Planning computation time (s)") 495 | 496 | for h in self.available_heuristics: 497 | _, times, nodes, _ = self.__gather_data_astar( 498 | domain_path=domain, 499 | problem_path=problem, 500 | heuristic_key=h, 501 | max_pddl_instances=max_pddl_instances, 502 | ) 503 | data = dict() 504 | for i, val in enumerate(nodes): 505 | data[val] = times[i] 506 | nodes_sorted = sorted(list(data.keys())) 507 | times_y = [] 508 | for node_opened in nodes_sorted: 509 | times_y.append(data[node_opened]) 510 | 511 | ax.plot( 512 | nodes_sorted, 513 | times_y, 514 | "-o", 515 | label=h, 516 | ) 517 | 518 | plt.title("A* heuristics complexity comparison") 519 | plt.legend(loc="upper left") 520 | plt.xscale("symlog") 521 | plt.grid(True) 522 | plt.show(block=False) 523 | 524 | def comparative_greedy_bfs_heuristic_plot( 525 | self, domain="", problem="", max_pddl_instances=-1 526 | ): 527 | _, ax = plt.subplots() 528 | plt.xlabel("Number of opened nodes") 529 | plt.ylabel("Planning computation time (s)") 530 | 531 | for h in self.available_heuristics: 532 | _, times, nodes, _ = self.__gather_data_greedy_bfs( 533 | domain_path=domain, 534 | problem_path=problem, 535 | heuristic_key=h, 536 | max_pddl_instances=max_pddl_instances, 537 | ) 538 | data = dict() 539 | for i, val in enumerate(nodes): 540 | data[val] = times[i] 541 | nodes_sorted = sorted(list(data.keys())) 542 | times_y = [] 543 | for node_opened in nodes_sorted: 544 | times_y.append(data[node_opened]) 545 | 546 | ax.plot( 547 | nodes_sorted, 548 | times_y, 549 | "-o", 550 | label=h, 551 | ) 552 | 553 | plt.title("Greedy Best First heuristics complexity comparison") 554 | plt.legend(loc="upper left") 555 | plt.xscale("symlog") 556 | plt.grid(True) 557 | plt.show(block=False) 558 | 559 | def comparative_data_plot( 560 | self, 561 | astar=True, 562 | bfs=True, 563 | dfs=True, 564 | dijkstra=True, 565 | greedy_bfs=False, 566 | domain="", 567 | problem="", 568 | heuristic_key="basic/goal_count", 569 | collect_new_data=True, 570 | max_pddl_instances=-1, 571 | ): 572 | json_dict = {} 573 | if collect_new_data: 574 | xdata, ydata = self.__gather_data( 575 | heuristic_key=heuristic_key, 576 | astar=astar, 577 | dfs=dfs, 578 | bfs=bfs, 579 | dijkstra=dijkstra, 580 | greedy_bfs=greedy_bfs, 581 | domain=domain, 582 | problem=problem, 583 | max_pddl_instances=max_pddl_instances, 584 | ) 585 | json_dict["xdata"] = xdata 586 | json_dict["ydata"] = ydata 587 | with open("data.json", "w") as fp: 588 | json.dump(json_dict, fp) 589 | else: 590 | if not path.exists("data.json"): 591 | logging.warning( 592 | "Input says not to generate new data but no data was found. Generating new data..." 593 | ) 594 | xdata, ydata = self.__gather_data( 595 | heuristic_key=heuristic_key, 596 | astar=astar, 597 | dfs=dfs, 598 | bfs=bfs, 599 | greedy_bfs=greedy_bfs, 600 | dijkstra=dijkstra, 601 | domain=domain, 602 | problem=problem, 603 | max_pddl_instances=max_pddl_instances, 604 | ) 605 | json_dict["xdata"] = xdata 606 | json_dict["ydata"] = ydata 607 | with open("data.json", "w") as fp: 608 | json.dump(json_dict, fp) 609 | else: 610 | with open("data.json") as fp: 611 | json_dict = json.load(fp) 612 | 613 | _, ax = plt.subplots() 614 | plt.xlabel("Number of opened nodes") 615 | plt.ylabel("Planning computation time (s)") 616 | for planner in json_dict["xdata"].keys(): 617 | data = dict() 618 | for i, val in enumerate(json_dict["xdata"][planner]): 619 | data[val] = json_dict["ydata"][planner][i] 620 | nodes_sorted = sorted(list(data.keys())) 621 | times_y = [] 622 | for node_opened in nodes_sorted: 623 | times_y.append(data[node_opened]) 624 | ax.plot( 625 | nodes_sorted, 626 | times_y, 627 | "-o", 628 | label=planner, 629 | ) 630 | plt.title("Planners complexity comparison") 631 | plt.legend(loc="upper left") 632 | plt.xscale("symlog") 633 | plt.yscale("log") 634 | plt.grid(True) 635 | plt.show(block=False) 636 | 637 | def plot_metrics(self): 638 | metrics_dict = dict() 639 | metrics_dict["A* [Zero]"] = [] 640 | metrics_dict["DFS"] = [] 641 | metrics_dict["BFS"] = [] 642 | metrics_dict["A* [Goal_Count]"] = [] 643 | metrics_dict["A* [H_Add]"] = [] 644 | metrics_dict["A* [H_Max]"] = [] 645 | metrics_dict["A* [Critical_Path (H2)]"] = [] 646 | metrics_dict["A* [Critical_Path (H3)]"] = [] 647 | logging.debug("Computation of all metrics for all domains registered...") 648 | for problem, domain in self.__get_all_pddl_from_data(): 649 | logging.debug("Loading new PDDL instance planned with Dijkstra...") 650 | logging.debug("Domain: " + domain) 651 | logging.debug("Problem: " + problem) 652 | apla = AutomatedPlanner(domain, problem) 653 | _, metrics_bfs = apla.breadth_first_search() 654 | _, metrics_agc = apla.astar_best_first_search() 655 | _, metrics_ahadd = apla.astar_best_first_search( 656 | heuristic_key="delete_relaxation/h_add" 657 | ) 658 | _, metrics_ahmax = apla.astar_best_first_search( 659 | heuristic_key="delete_relaxation/h_max" 660 | ) 661 | _, metrics_dij = apla.astar_best_first_search(heuristic_key="basic/zero") 662 | _, metrics_dfs = apla.depth_first_search( 663 | node_bound=metrics_bfs.n_opened * 2 664 | ) 665 | _, metrics_cp2 = apla.astar_best_first_search( 666 | heuristic_key="critical_path/2" 667 | ) 668 | _, metrics_cp3 = apla.astar_best_first_search( 669 | heuristic_key="critical_path/3" 670 | ) 671 | metrics_dict["A* [Zero]"].append(metrics_dij) 672 | metrics_dict["DFS"].append(metrics_dfs) 673 | metrics_dict["BFS"].append(metrics_bfs) 674 | metrics_dict["A* [Goal_Count]"].append(metrics_agc) 675 | metrics_dict["A* [H_Add]"].append(metrics_ahadd) 676 | metrics_dict["A* [H_Max]"].append(metrics_ahmax) 677 | metrics_dict["A* [Critical_Path (H2)]"].append(metrics_cp2) 678 | metrics_dict["A* [Critical_Path (H3)]"].append(metrics_cp3) 679 | 680 | plot_dict = dict() 681 | 682 | for key, val in metrics_dict.items(): 683 | plot_dict[key] = dict() 684 | plot_dict[key]["Search Runtime (s)"] = [m.runtime for m in val] 685 | plot_dict[key]["Total Heuristics Runtime (s)"] = [ 686 | sum(m.heuristic_runtimes) for m in val 687 | ] 688 | plot_dict[key]["Number of Expanded Nodes"] = [m.n_expended for m in val] 689 | plot_dict[key]["Number of Opened Nodes"] = [m.n_opened for m in val] 690 | plot_dict[key]["Number of Reopened Nodes"] = [m.n_reopened for m in val] 691 | plot_dict[key]["Number of Evaluated Nodes"] = [m.n_evaluated for m in val] 692 | plot_dict[key]["Number of Generated Nodes"] = [m.n_generated for m in val] 693 | plot_dict[key]["Number of Deadend States (No Actions from State)"] = [ 694 | m.deadend_states for m in val 695 | ] 696 | 697 | metrics_keys = list(plot_dict["DFS"].keys()) 698 | 699 | for key in metrics_keys: 700 | self.__plot_data_generic(plot_dict, key) 701 | 702 | def compute_planners_efficiency(self): 703 | costs = dict() 704 | costs["A* [Goal_Count]"], _, n_goal_count, _ = self.__gather_data_astar() 705 | costs["A* [H_Max]"], _, n_hmax, _ = self.__gather_data_astar( 706 | heuristic_key="delete_relaxation/h_max" 707 | ) 708 | costs["A* [H_Add]"], _, n_hadd, _ = self.__gather_data_astar( 709 | heuristic_key="delete_relaxation/h_add" 710 | ) 711 | ( 712 | costs["Greedy Best First [Goal_Count]"], 713 | _, 714 | n_greed_goal_count, 715 | _, 716 | ) = self.__gather_data_greedy_bfs(heuristic_key="basic/goal_count") 717 | ( 718 | costs["Greedy Best First [H_Max]"], 719 | _, 720 | n_greed_hmax, 721 | _, 722 | ) = self.__gather_data_greedy_bfs(heuristic_key="delete_relaxation/h_max") 723 | ( 724 | costs["Greedy Best First [H_Add]"], 725 | _, 726 | n_greed_hadd, 727 | _, 728 | ) = self.__gather_data_greedy_bfs(heuristic_key="delete_relaxation/h_add") 729 | costs["DFS"], _, n_dfs, _ = self.__gather_data_dfs() 730 | costs["BFS"], _, n_bfs, _ = self.__gather_data_bfs() 731 | costs["Dijkstra"], _, n_dij, _ = self.__gather_data_dijkstra() 732 | 733 | p_gc = (len(n_goal_count) - n_goal_count.count(0)) / len(n_goal_count) * 100 734 | p_hmax = (len(n_hmax) - n_hmax.count(0)) / len(n_hmax) * 100 735 | p_hadd = (len(n_hadd) - n_hadd.count(0)) / len(n_hadd) * 100 736 | p_greedy_gc = ( 737 | (len(n_greed_goal_count) - n_greed_goal_count.count(0)) 738 | / len(n_greed_goal_count) 739 | * 100 740 | ) 741 | p_greedy_hmax = ( 742 | (len(n_greed_hmax) - n_greed_hmax.count(0)) / len(n_greed_hmax) * 100 743 | ) 744 | p_greedy_hadd = ( 745 | (len(n_greed_hadd) - n_greed_hadd.count(0)) / len(n_greed_hadd) * 100 746 | ) 747 | p_dfs = (len(n_dfs) - n_dfs.count(0)) / len(n_dfs) * 100 748 | p_bfs = (len(n_bfs) - n_bfs.count(0)) / len(n_bfs) * 100 749 | p_dij = (len(n_dij) - n_dij.count(0)) / len(n_dij) * 100 750 | 751 | _, ax = plt.subplots() 752 | plt.xlabel("Domain evaluated") 753 | plt.ylabel("Cost to goal") 754 | for key, val in costs.items(): 755 | ax.plot( 756 | val, 757 | "-o", 758 | label=key, 759 | ) 760 | costs[key] = [i for i in costs[key] if i != 0] 761 | plt.title("Planners efficiency (costs)") 762 | plt.legend(loc="upper left") 763 | plt.grid(True) 764 | plt.show(block=False) 765 | 766 | logging.info( 767 | "DFS succeeded to build a plan with a %.2f%% rate and a %.2f cost average" 768 | % (p_dfs, sum(costs["DFS"]) / len(costs["DFS"])) 769 | ) 770 | logging.info( 771 | "BFS succeeded to build a plan with a %.2f%% rate and a %.2f cost average" 772 | % (p_bfs, sum(costs["BFS"]) / len(costs["BFS"])) 773 | ) 774 | logging.info( 775 | "Dijkstra succeeded to build a plan with a %.2f%% rate and a %.2f cost average" 776 | % (p_dij, sum(costs["Dijkstra"]) / len(costs["Dijkstra"])) 777 | ) 778 | logging.info( 779 | "A* [Goal_Count] succeeded to build a plan with a %.2f%% rate and a %.2f cost average" 780 | % (p_gc, sum(costs["A* [Goal_Count]"]) / len(costs["A* [Goal_Count]"])) 781 | ) 782 | logging.info( 783 | "A* [H_Max] succeeded to build a plan with a %.2f%% rate and a %.2f cost average" 784 | % (p_hmax, sum(costs["A* [H_Max]"]) / len(costs["A* [H_Max]"])) 785 | ) 786 | logging.info( 787 | "A* [H_Add] succeeded to build a plan with a %.2f%% rate and a %.2f cost average" 788 | % (p_hadd, sum(costs["A* [H_Add]"]) / len(costs["A* [H_Add]"])) 789 | ) 790 | logging.info( 791 | "Greedy Best First [Goal_Count] succeeded to build a plan with a %.2f%% rate and a %.2f cost average" 792 | % ( 793 | p_greedy_gc, 794 | sum(costs["Greedy Best First [Goal_Count]"]) 795 | / len(costs["Greedy Best First [Goal_Count]"]), 796 | ) 797 | ) 798 | logging.info( 799 | "Greedy Best First [H_Max] succeeded to build a plan with a %.2f%% rate and a %.2f cost average" 800 | % ( 801 | p_greedy_hmax, 802 | sum(costs["Greedy Best First [H_Max]"]) 803 | / len(costs["Greedy Best First [H_Max]"]), 804 | ) 805 | ) 806 | logging.info( 807 | "Greedy Best First [H_Add] succeeded to build a plan with a %.2f%% rate and a %.2f cost average" 808 | % ( 809 | p_greedy_hadd, 810 | sum(costs["Greedy Best First [H_Add]"]) 811 | / len(costs["Greedy Best First [H_Add]"]), 812 | ) 813 | ) 814 | -------------------------------------------------------------------------------- /jupyddl/dfs.py: -------------------------------------------------------------------------------- 1 | from .node import Node 2 | from datetime import datetime as timestamp 3 | from time import time as now 4 | from .metrics import Metrics 5 | 6 | 7 | class DepthFirstSearch: 8 | def __init__(self, automated_planner): 9 | self.time_start = now() 10 | self.visited = [] 11 | self.automated_planner = automated_planner 12 | self.init = Node(self.automated_planner.initial_state, automated_planner) 13 | self.stack = [self.init] 14 | self.metrics = Metrics() 15 | 16 | def search(self, node_bound=float("inf")): 17 | self.automated_planner.logger.debug( 18 | "Search started at: " + str(timestamp.now()) 19 | ) 20 | while self.stack: 21 | current_node = self.stack.pop() 22 | if current_node not in self.visited: 23 | self.visited.append(current_node) 24 | self.metrics.n_evaluated += 1 25 | if self.automated_planner.satisfies( 26 | self.automated_planner.problem.goal, current_node.state 27 | ): 28 | self.metrics.runtime = now() - self.time_start 29 | self.automated_planner.logger.debug( 30 | "Search finished at: " + str(timestamp.now()) 31 | ) 32 | self.metrics.total_cost = current_node.g_cost 33 | return current_node, self.metrics 34 | 35 | if self.metrics.n_opened > node_bound: 36 | break 37 | 38 | actions = self.automated_planner.available_actions(current_node.state) 39 | if not actions: 40 | self.metrics.deadend_states += 1 41 | else: 42 | self.metrics.n_expended += 1 43 | for act in actions: 44 | child = Node( 45 | state=self.automated_planner.transition( 46 | current_node.state, act 47 | ), 48 | automated_planner=self.automated_planner, 49 | parent_action=act, 50 | parent=current_node, 51 | ) 52 | self.metrics.n_generated += 1 53 | if child in self.visited: 54 | continue 55 | self.metrics.n_opened += 1 56 | self.stack.append(child) 57 | self.metrics.runtime = now() - self.time_start 58 | self.automated_planner.logger.warning("!!! No path found !!!") 59 | return None, self.metrics 60 | -------------------------------------------------------------------------------- /jupyddl/dijkstra.py: -------------------------------------------------------------------------------- 1 | from .node import Node 2 | import logging 3 | import math 4 | from datetime import datetime as timestamp 5 | from time import time as now 6 | from .metrics import Metrics 7 | 8 | 9 | def zero_heuristic(): 10 | return 0 11 | 12 | 13 | class DijkstraBestFirstSearch: 14 | def __init__(self, automated_planner): 15 | self.time_start = now() 16 | self.automated_planner = automated_planner 17 | self.metrics = Metrics() 18 | self.init = Node( 19 | self.automated_planner.initial_state, 20 | automated_planner, 21 | is_closed=False, 22 | is_open=True, 23 | heuristic=zero_heuristic, 24 | metric=self.metrics, 25 | ) 26 | self.open_nodes_n = 1 27 | self.nodes = dict() 28 | self.nodes[self.__hash(self.init)] = self.init 29 | 30 | def __hash(self, node): 31 | sep = ", Dict{Symbol,Any}" 32 | string = str(node.state) 33 | return string.split(sep, 1)[0] + ")" 34 | 35 | def search(self, node_bound=float("inf")): 36 | self.automated_planner.logger.debug( 37 | "Search started at: " + str(timestamp.now()) 38 | ) 39 | while self.open_nodes_n > 0: 40 | current_key = min( 41 | [n for n in self.nodes if self.nodes[n].is_open], 42 | key=(lambda k: self.nodes[k].f_cost), 43 | ) 44 | current_node = self.nodes[current_key] 45 | self.metrics.n_evaluated += 1 46 | if self.automated_planner.satisfies( 47 | self.automated_planner.problem.goal, current_node.state 48 | ): 49 | self.metrics.runtime = now() - self.time_start 50 | self.automated_planner.logger.debug( 51 | "Search finished at: " + str(timestamp.now()) 52 | ) 53 | self.metrics.total_cost = current_node.g_cost 54 | return current_node, self.metrics 55 | 56 | current_node.is_closed = True 57 | current_node.is_open = False 58 | self.open_nodes_n -= 1 59 | 60 | if self.metrics.n_opened > node_bound: 61 | break 62 | 63 | actions = self.automated_planner.available_actions(current_node.state) 64 | if not actions: 65 | self.metrics.deadend_states += 1 66 | else: 67 | self.metrics.n_expended += 1 68 | for act in actions: 69 | child = Node( 70 | state=self.automated_planner.transition(current_node.state, act), 71 | automated_planner=self.automated_planner, 72 | parent_action=act, 73 | parent=current_node, 74 | heuristic=zero_heuristic, 75 | is_closed=False, 76 | is_open=True, 77 | metric=self.metrics, 78 | ) 79 | self.metrics.n_generated += 1 80 | child_hash = self.__hash(child) 81 | if child_hash in self.nodes: 82 | if self.nodes[child_hash].is_closed: 83 | continue 84 | if not self.nodes[child_hash].is_open: 85 | self.nodes[child_hash] = child 86 | self.open_nodes_n += 1 87 | self.metrics.n_opened += 1 88 | else: 89 | if child.g_cost < self.nodes[child_hash].g_cost: 90 | self.nodes[child_hash] = child 91 | self.open_nodes_n += 1 92 | self.metrics.n_opened += 1 93 | self.metrics.n_reopened += 1 94 | 95 | else: 96 | self.nodes[child_hash] = child 97 | self.metrics.n_opened += 1 98 | self.open_nodes_n += 1 99 | self.metrics.runtime = now() - self.time_start 100 | self.automated_planner.logger.warning("!!! No path found !!!") 101 | return None, self.metrics 102 | -------------------------------------------------------------------------------- /jupyddl/greedy_best_first.py: -------------------------------------------------------------------------------- 1 | from .node import Node 2 | import logging 3 | import math 4 | from time import time as now 5 | from datetime import datetime as timestamp 6 | from .metrics import Metrics 7 | 8 | 9 | class GreedyBestFirstSearch: 10 | def __init__(self, automated_planner, heuristic_function): 11 | self.time_start = now() 12 | self.automated_planner = automated_planner 13 | self.metrics = Metrics() 14 | self.init = Node( 15 | self.automated_planner.initial_state, 16 | automated_planner, 17 | is_closed=False, 18 | is_open=True, 19 | heuristic=heuristic_function, 20 | heuristic_based=True, 21 | metric=self.metrics, 22 | ) 23 | self.heuristic_function = heuristic_function 24 | self.open_nodes_n = 1 25 | self.nodes = dict() 26 | self.nodes[self.__hash(self.init)] = self.init 27 | 28 | def __hash(self, node): 29 | sep = ", Dict{Symbol,Any}" 30 | string = str(node.state) 31 | return string.split(sep, 1)[0] + ")" 32 | 33 | def search(self, node_bound=float("inf")): 34 | self.automated_planner.logger.debug( 35 | "Search started at: " + str(timestamp.now()) 36 | ) 37 | while self.open_nodes_n > 0: 38 | current_key = min( 39 | [n for n in self.nodes if self.nodes[n].is_open], 40 | key=(lambda k: self.nodes[k].h_cost), 41 | ) 42 | current_node = self.nodes[current_key] 43 | 44 | self.metrics.n_evaluated += 1 45 | if self.automated_planner.satisfies( 46 | self.automated_planner.problem.goal, current_node.state 47 | ): 48 | self.metrics.runtime = now() - self.time_start 49 | self.automated_planner.logger.debug( 50 | "Search finished at: " + str(timestamp.now()) 51 | ) 52 | self.metrics.total_cost = current_node.g_cost 53 | return current_node, self.metrics 54 | 55 | current_node.is_closed = True 56 | current_node.is_open = False 57 | self.open_nodes_n -= 1 58 | 59 | if self.metrics.n_opened > node_bound: 60 | break 61 | 62 | actions = self.automated_planner.available_actions(current_node.state) 63 | if actions: 64 | self.metrics.n_expended += 1 65 | else: 66 | self.metrics.deadend_states += 1 67 | for act in actions: 68 | child = Node( 69 | state=self.automated_planner.transition(current_node.state, act), 70 | automated_planner=self.automated_planner, 71 | parent_action=act, 72 | parent=current_node, 73 | heuristic=self.heuristic_function, 74 | is_closed=False, 75 | is_open=True, 76 | heuristic_based=True, 77 | metric=self.metrics, 78 | ) 79 | self.metrics.n_generated += 1 80 | child_hash = self.__hash(child) 81 | if child_hash in self.nodes: 82 | if self.nodes[child_hash].is_closed: 83 | continue 84 | if not self.nodes[child_hash].is_open: 85 | self.nodes[child_hash] = child 86 | self.open_nodes_n += 1 87 | self.metrics.n_opened += 1 88 | else: 89 | if child.g_cost < self.nodes[child_hash].g_cost: 90 | self.nodes[child_hash] = child 91 | self.open_nodes_n += 1 92 | self.metrics.n_opened += 1 93 | self.metrics.n_reopened += 1 94 | 95 | else: 96 | self.nodes[child_hash] = child 97 | self.open_nodes_n += 1 98 | self.metrics.n_opened += 1 99 | self.metrics.runtime = now() - self.time_start 100 | self.automated_planner.logger.warning("!!! No path found !!!") 101 | return None, self.metrics 102 | -------------------------------------------------------------------------------- /jupyddl/heuristics.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from .node import Node 3 | 4 | 5 | class BasicHeuristic: 6 | def __init__(self, automated_planner, heuristic_key): 7 | self.automated_planner = automated_planner 8 | self.heuristic_keys = { 9 | "basic/zero": self.__zero_heuristic, 10 | "basic/goal_count": self.__goal_count_heuristic, 11 | } 12 | if heuristic_key not in list(self.heuristic_keys.keys()): 13 | logging.warning( 14 | "Heuristic key isn't registered, forcing it to [basic/goal_count]" 15 | ) 16 | heuristic_key = "basic/goal_count" 17 | 18 | self.current_h = heuristic_key 19 | 20 | def compute(self, state): 21 | return self.heuristic_keys[self.current_h](state) 22 | 23 | def __zero_heuristic(self, state): 24 | return 0 25 | 26 | def __goal_count_heuristic(self, state): 27 | count = 0 28 | for goal in self.automated_planner.goals: 29 | if not self.automated_planner.state_has_term(state, goal): 30 | count += 1 31 | return count 32 | 33 | 34 | class DeleteRelaxationHeuristic: 35 | def __init__(self, automated_planner, heuristic_key): 36 | class DRHCache: 37 | def __init__(self, domain=None, axioms=None, preconds=None, additions=None): 38 | self.domain = domain 39 | self.axioms = axioms 40 | self.preconds = preconds 41 | self.additions = additions 42 | 43 | self.automated_planner = automated_planner 44 | self.cache = DRHCache() 45 | self.heuristic_keys = { 46 | "delete_relaxation/h_add": self.__h_add, 47 | "delete_relaxation/h_max": self.__h_max, 48 | } 49 | if heuristic_key not in list(self.heuristic_keys.keys()): 50 | logging.warning( 51 | "Heuristic key isn't registered, forcing it to [delete_relaxation/h_add]" 52 | ) 53 | heuristic_key = "delete_relaxation/h_add" 54 | 55 | self.current_h = heuristic_key 56 | self.has_been_precomputed = False 57 | self.__pre_compute() 58 | # return self.heuristic_keys[self.current_h](state) 59 | 60 | def compute(self, state): 61 | if not self.has_been_precomputed: 62 | self.__pre_compute() 63 | domain = self.cache.domain 64 | goals = self.automated_planner.goals 65 | types = state.types 66 | facts = state.facts 67 | fact_costs = self.automated_planner.pddl.init_facts_costs(facts) 68 | while True: 69 | facts, state = self.automated_planner.pddl.get_facts_and_state( 70 | fact_costs, types 71 | ) 72 | if self.automated_planner.satisfies(goals, state): 73 | costs = [] 74 | fact_costs_str = dict([(str(k), val) for k, val in fact_costs.items()]) 75 | for g in goals: 76 | if str(g) in fact_costs_str: 77 | costs.append(fact_costs_str[str(g)]) 78 | costs.insert(0, 0) 79 | return self.heuristic_keys[self.current_h](costs) 80 | 81 | for ax in self.cache.axioms: 82 | fact_costs = ( 83 | self.automated_planner.pddl.compute_costs_one_step_derivation( 84 | facts, fact_costs, ax, self.current_h 85 | ) 86 | ) 87 | 88 | actions = self.automated_planner.available_actions(state) 89 | for act in actions: 90 | fact_costs = self.automated_planner.pddl.compute_cost_action_effect( 91 | fact_costs, act, domain, self.cache.additions, self.current_h 92 | ) 93 | 94 | if len(fact_costs) == self.automated_planner.pddl.length( 95 | facts 96 | ) and self.__facts_eq(fact_costs, facts): 97 | break 98 | 99 | return float("inf") 100 | 101 | def __pre_compute(self): 102 | if self.has_been_precomputed: 103 | return 104 | domain = self.automated_planner.domain 105 | domain, axioms = self.automated_planner.pddl.compute_hsp_axioms(domain) 106 | # preconditions = dict() 107 | additions = dict() 108 | self.automated_planner.pddl.cache_global_preconditions(domain) 109 | for name, definition in domain.actions.items(): 110 | additions[name] = self.automated_planner.pddl.effect_diff( 111 | definition.effect 112 | ).add 113 | self.cache.additions = additions 114 | self.cache.preconds = self.automated_planner.pddl.g_preconditions 115 | self.cache.domain = domain 116 | self.cache.axioms = axioms 117 | self.has_been_precomputed = True 118 | 119 | def __h_add(self, costs): 120 | return sum(costs) 121 | 122 | def __h_max(self, costs): 123 | return max(costs) 124 | 125 | def __facts_eq(self, facts_dict, facts_set): 126 | fact_costs_str = dict([(str(k), val) for k, val in facts_dict.items()]) 127 | for f in facts_set: 128 | if not (str(f) in fact_costs_str.keys()): 129 | return False 130 | return True 131 | 132 | 133 | class RelaxedCriticalPathHeuristic: 134 | def __init__(self, automated_planner, critical_path_level=1): 135 | class RCPCache: 136 | def __init__(self, domain=None, axioms=None, preconds=None, additions=None): 137 | self.domain = domain 138 | self.axioms = axioms 139 | self.preconds = preconds 140 | self.additions = additions 141 | 142 | self.automated_planner = automated_planner 143 | self.cache = RCPCache() 144 | if critical_path_level > 3: 145 | logging.warning( 146 | "Critical Path level is only implemented until 3, forcing it to 3." 147 | ) 148 | self.critical_path_level = 3 149 | if critical_path_level < 1: 150 | logging.warning( 151 | "Critical Path level has to be at least 1, forcing it to 1." 152 | ) 153 | self.critical_path_level = 1 154 | else: 155 | self.critical_path_level = critical_path_level 156 | self.has_been_precomputed = False 157 | self.__pre_compute() 158 | # return self.heuristic_keys[self.current_h](state) 159 | 160 | def compute(self, state): 161 | if not self.has_been_precomputed: 162 | self.__pre_compute() 163 | domain = self.cache.domain 164 | goals = self.automated_planner.goals 165 | types = state.types 166 | facts = state.facts 167 | fact_costs = self.automated_planner.pddl.init_facts_costs(facts) 168 | while True: 169 | facts, state = self.automated_planner.pddl.get_facts_and_state( 170 | fact_costs, types 171 | ) 172 | if self.automated_planner.satisfies(goals, state): 173 | costs = [] 174 | fact_costs_str = dict([(str(k), val) for k, val in fact_costs.items()]) 175 | print(fact_costs_str) 176 | if self.critical_path_level == 1: 177 | for g in goals: 178 | if str(g) in fact_costs_str: 179 | costs.append(fact_costs_str[str(g)]) 180 | if self.critical_path_level == 2: 181 | pairs_of_goals = [ 182 | (g1, g2) for g1 in goals for g2 in goals if g1 != g2 183 | ] 184 | for gs in pairs_of_goals: 185 | if ( 186 | str(gs[0]) in fact_costs_str 187 | and str(gs[1]) in fact_costs_str 188 | ): 189 | costs.append( 190 | fact_costs_str[str(gs[0])] + fact_costs_str[str(gs[1])] 191 | ) 192 | if self.critical_path_level == 3: 193 | triplets_of_goals = [ 194 | (g1, g2, g3) 195 | for g1 in goals 196 | for g2 in goals 197 | for g3 in goals 198 | if g1 != g2 and g1 != g3 and g2 != g3 199 | ] 200 | for gs in triplets_of_goals: 201 | if ( 202 | str(gs[0]) in fact_costs_str 203 | and str(gs[1]) in fact_costs_str 204 | and str(gs[2]) in fact_costs_str 205 | ): 206 | costs.append( 207 | fact_costs_str[str(gs[0])] 208 | + fact_costs_str[str(gs[1])] 209 | + fact_costs_str[str(gs[2])] 210 | ) 211 | costs.insert(0, 0) 212 | return max(costs) 213 | 214 | for ax in self.cache.axioms: 215 | fact_costs = ( 216 | self.automated_planner.pddl.compute_costs_one_step_derivation( 217 | facts, fact_costs, ax, "max" 218 | ) 219 | ) 220 | 221 | actions = self.automated_planner.available_actions(state) 222 | for act in actions: 223 | fact_costs = self.automated_planner.pddl.compute_cost_action_effect( 224 | fact_costs, act, domain, self.cache.additions, "max" 225 | ) 226 | 227 | if len(fact_costs) == self.automated_planner.pddl.length( 228 | facts 229 | ) and self.__facts_eq(fact_costs, facts): 230 | break 231 | 232 | return float("inf") 233 | 234 | def __pre_compute(self): 235 | if self.has_been_precomputed: 236 | return 237 | domain = self.automated_planner.domain 238 | domain, axioms = self.automated_planner.pddl.compute_hsp_axioms(domain) 239 | # preconditions = dict() 240 | additions = dict() 241 | self.automated_planner.pddl.cache_global_preconditions(domain) 242 | for name, definition in domain.actions.items(): 243 | additions[name] = self.automated_planner.pddl.effect_diff( 244 | definition.effect 245 | ).add 246 | self.cache.additions = additions 247 | self.cache.preconds = self.automated_planner.pddl.g_preconditions 248 | self.cache.domain = domain 249 | self.cache.axioms = axioms 250 | self.has_been_precomputed = True 251 | 252 | def __h_add(self, costs): 253 | return sum(costs) 254 | 255 | def __h_max(self, costs): 256 | return max(costs) 257 | 258 | def __facts_eq(self, facts_dict, facts_set): 259 | fact_costs_str = dict([(str(k), val) for k, val in facts_dict.items()]) 260 | for f in facts_set: 261 | if not (str(f) in fact_costs_str.keys()): 262 | return False 263 | return True 264 | 265 | 266 | class CriticalPathHeuristic: 267 | def __init__(self, automated_planner, critical_path_level=1): 268 | self.automated_planner = automated_planner 269 | 270 | if critical_path_level > 3: 271 | logging.warning( 272 | "Critical Path level is only implemented until 3, forcing it to 3." 273 | ) 274 | self.critical_path_level = 3 275 | if critical_path_level < 1: 276 | logging.warning( 277 | "Critical Path level has to be at least 1, forcing it to 1." 278 | ) 279 | self.critical_path_level = 1 280 | else: 281 | self.critical_path_level = critical_path_level 282 | 283 | self.goals = [] 284 | 285 | if self.critical_path_level == 1: 286 | self.goals = self.automated_planner.goals 287 | 288 | if self.critical_path_level == 2: 289 | if len(self.automated_planner.goals) < 2: 290 | logging.warning("Only 1 goal predicate, forcing H2 to H1") 291 | self.goals = self.automated_planner.goals 292 | else: 293 | self.goals = [ 294 | [g1, g2] 295 | for g1 in self.automated_planner.goals 296 | for g2 in self.automated_planner.goals 297 | if g1 != g2 298 | ] 299 | 300 | if self.critical_path_level == 3: 301 | if len(self.automated_planner.goals) < 2: 302 | logging.warning("Only 1 goal predicate, forcing H3 to H1") 303 | self.goals = self.automated_planner.goals 304 | elif len(self.automated_planner.goals) < 3: 305 | logging.warning("Only 2 goal predicate, forcing H3 to H2") 306 | self.goals = [ 307 | [g1, g2] 308 | for g1 in self.automated_planner.goals 309 | for g2 in self.automated_planner.goals 310 | if g1 != g2 311 | ] 312 | else: 313 | self.goals = [ 314 | [g1, g2, g3] 315 | for g1 in self.automated_planner.goals 316 | for g2 in self.automated_planner.goals 317 | for g3 in self.automated_planner.goals 318 | if g1 != g2 and g1 != g3 and g2 != g3 319 | ] 320 | 321 | def __h_max(self, costs): 322 | return max(costs) 323 | 324 | def compute(self, state): 325 | costs = [] 326 | 327 | for subgoal in self.goals: 328 | costs.append(self.__dijkstra_search(state, subgoal)) 329 | 330 | return self.__h_max(costs) 331 | 332 | def __hash(self, node): 333 | sep = ", Dict{Symbol,Any}" 334 | string = str(node.state) 335 | return string.split(sep, 1)[0] + ")" 336 | 337 | def __dijkstra_search(self, state, goal): 338 | def zero_heuristic(): 339 | return 0 340 | 341 | init = Node( 342 | state, 343 | self.automated_planner, 344 | is_closed=False, 345 | is_open=True, 346 | heuristic=zero_heuristic, 347 | ) 348 | 349 | open_nodes_n = 1 350 | nodes = dict() 351 | nodes[self.__hash(init)] = init 352 | 353 | while open_nodes_n > 0: 354 | current_key = min( 355 | [n for n in nodes if nodes[n].is_open], 356 | key=(lambda k: nodes[k].f_cost), 357 | ) 358 | current_node = nodes[current_key] 359 | 360 | if self.automated_planner.satisfies(goal, current_node.state): 361 | return current_node.g_cost 362 | 363 | current_node.is_closed = True 364 | current_node.is_open = False 365 | open_nodes_n -= 1 366 | 367 | actions = self.automated_planner.available_actions(current_node.state) 368 | 369 | for act in actions: 370 | child = Node( 371 | state=self.automated_planner.transition(current_node.state, act), 372 | automated_planner=self.automated_planner, 373 | parent_action=act, 374 | parent=current_node, 375 | heuristic=zero_heuristic, 376 | is_closed=False, 377 | is_open=True, 378 | ) 379 | 380 | child_hash = self.__hash(child) 381 | 382 | if child_hash in nodes: 383 | if nodes[child_hash].is_closed: 384 | continue 385 | 386 | if not nodes[child_hash].is_open: 387 | nodes[child_hash] = child 388 | open_nodes_n += 1 389 | 390 | else: 391 | if child.g_cost < nodes[child_hash].g_cost: 392 | nodes[child_hash] = child 393 | open_nodes_n += 1 394 | 395 | else: 396 | nodes[child_hash] = child 397 | open_nodes_n += 1 398 | return float("inf") 399 | -------------------------------------------------------------------------------- /jupyddl/metrics.py: -------------------------------------------------------------------------------- 1 | class Metrics: 2 | def __init__(self): 3 | self.runtime = 0 4 | self.heuristic_runtimes = [] 5 | self.n_expended = 0 6 | self.n_reopened = 0 7 | self.n_evaluated = 0 8 | self.n_opened = 1 9 | self.n_generated = 1 10 | self.deadend_states = 0 11 | self.total_cost = 0 12 | 13 | def get_average_heuristic_runtime(self): 14 | if self.heuristic_runtimes: 15 | return sum(self.heuristic_runtimes) / len(self.heuristic_runtimes) 16 | return 0 17 | 18 | def __str__(self): 19 | if self.heuristic_runtimes: 20 | av = sum(self.heuristic_runtimes) 21 | w = sum(self.heuristic_runtimes) / self.runtime * 100 22 | else: 23 | av = 0 24 | w = 0 25 | return ( 26 | "Expanded %d state(s).\nOpened %d state(s).\nReopened %d state(s).\nEvaluated %d state(s).\nGenerated %d state(s).\nDead ends: %d state(s).\nRuntime: %.2fs.\nTotal heuristic runtime: %.2fs\nComputational weight of heuristic in the search: %.2f%%" 27 | % ( 28 | self.n_expended, 29 | self.n_opened, 30 | self.n_reopened, 31 | self.n_evaluated, 32 | self.n_generated, 33 | self.deadend_states, 34 | self.runtime, 35 | av, 36 | w, 37 | ) 38 | ) 39 | -------------------------------------------------------------------------------- /jupyddl/node.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import time 3 | 4 | 5 | class Node: 6 | def __init__( 7 | self, 8 | state, 9 | automated_planner, 10 | is_closed=None, 11 | is_open=None, 12 | parent_action=None, 13 | parent=None, 14 | g_cost=0, 15 | heuristic=None, 16 | heuristic_based=False, 17 | metric=None, 18 | ): 19 | self.state = state 20 | self.parent_action = parent_action 21 | self.parent = parent 22 | self.automated_planner = automated_planner 23 | temp_cost = automated_planner.pddl.get_value(state, "total-cost") 24 | if temp_cost: 25 | self.g_cost = temp_cost 26 | if heuristic_based: 27 | if heuristic: 28 | clock = time.time() 29 | self.h_cost = heuristic(state) 30 | if metric: 31 | metric.heuristic_runtimes.append(time.time() - clock) 32 | else: 33 | automated_planner.logger.warning( 34 | "Heuristic function wasn't found, forcing it to return zero [Best practice: use the zero_heuristic function]" 35 | ) 36 | self.h_cost = 0 37 | else: 38 | self.h_cost = 0 39 | self.f_cost = self.g_cost + self.h_cost 40 | else: 41 | if parent: 42 | self.g_cost = 1 + parent.g_cost 43 | else: 44 | self.g_cost = g_cost 45 | if heuristic_based: 46 | if heuristic: 47 | clock = time.time() 48 | self.h_cost = heuristic(state) 49 | if metric: 50 | metric.heuristic_runtimes.append(time.time() - clock) 51 | else: 52 | automated_planner.logger.warning( 53 | "Heuristic function wasn't found, forcing it to return zero [Best practice: use the zero_heuristic function]" 54 | ) 55 | self.h_cost = 0 56 | else: 57 | self.h_cost = 0 58 | self.f_cost = self.g_cost + self.h_cost 59 | 60 | self.is_closed = is_closed 61 | self.is_open = is_open 62 | 63 | def __stringify_state(self, state): 64 | state_str = str(state).replace("', "total-cost =" 69 | ) 70 | state_str = state_str.replace("Dict{Symbol,Any}(", "") 71 | state_str = state_str.replace(" , ", "") 72 | state_str = state_str.replace("))>", "") 73 | return state_str 74 | 75 | def __lt__(self, other): 76 | return self.f_cost <= other.f_cost 77 | 78 | def __str__(self): 79 | state = self.__stringify_state(self.state) 80 | return "Node { %s | g = %.2f | h = %.2f | open = %s | closed = %s }" % ( 81 | state, 82 | self.g_cost, 83 | self.h_cost, 84 | self.is_open, 85 | self.is_closed, 86 | ) 87 | 88 | 89 | class Path: 90 | def __init__(self, nodes): 91 | self.nodes = nodes 92 | 93 | def __str__(self): 94 | return str([str(n) for n in self.nodes]) 95 | -------------------------------------------------------------------------------- /logs/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/APLA-Toolbox/PythonPDDL/589a476f3186cee90ec867921588940cfaf6091c/logs/.gitkeep -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | julia==0.5.7 2 | coloredlogs==15.0.1 3 | matplotlib==3.5.1 4 | -------------------------------------------------------------------------------- /scripts/ipc.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import logging 3 | import coloredlogs 4 | from os import path 5 | 6 | sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 7 | from jupyddl.automated_planner import AutomatedPlanner 8 | from jupyddl.node import Path 9 | 10 | coloredlogs.install(level="WARNING") 11 | 12 | for a in sys.argv: 13 | if "ipc.py" in a: 14 | sys.argv.remove(a) 15 | break 16 | 17 | if len(sys.argv) != 3: 18 | logging.fatal("Binary should be ran with 3 arguments") 19 | exit() 20 | 21 | domain = sys.argv[0] 22 | problem = sys.argv[1] 23 | output = sys.argv[2] 24 | 25 | apla = AutomatedPlanner(domain, problem, log_level="WARNING") 26 | 27 | logging.debug("Running Critical Path with H1") 28 | path, metrics = apla.astar_best_first_search(heuristic_key="critical_path/1") 29 | actions = apla.get_actions_from_path(path) 30 | path = Path(path) 31 | 32 | logging.debug("Running Critical Path with H2") 33 | path2, metrics2 = apla.astar_best_first_search(heuristic_key="critical_path/2") 34 | actions2 = apla.get_actions_from_path(path2) 35 | path2 = Path(path2) 36 | 37 | logging.debug("Running Critical Path with H3") 38 | path3, metrics3 = apla.astar_best_first_search(heuristic_key="critical_path/3") 39 | actions3 = apla.get_actions_from_path(path3) 40 | path3 = Path(path3) 41 | 42 | logging.debug("Running Relaxed Critical Path with H1") 43 | path4, metrics4 = apla.astar_best_first_search(heuristic_key="relaxed_critical_path/1") 44 | actions4 = apla.get_actions_from_path(path4) 45 | path4 = Path(path4) 46 | 47 | logging.debug("Running Relaxed Critical Path with H2") 48 | path5, metrics5 = apla.astar_best_first_search(heuristic_key="relaxed_critical_path/2") 49 | actions5 = apla.get_actions_from_path(path5) 50 | path5 = Path(path5) 51 | 52 | logging.debug("Running Relaxed Critical Path with H3") 53 | path6, metrics6 = apla.astar_best_first_search(heuristic_key="relaxed_critical_path/3") 54 | actions6 = apla.get_actions_from_path(path6) 55 | path6 = Path(path6) 56 | 57 | logging.debug("Running Delete Relaxation (HMax)") 58 | path7, metrics7 = apla.astar_best_first_search(heuristic_key="delete_relaxation/h_max") 59 | actions7 = apla.get_actions_from_path(path7) 60 | path7 = Path(path7) 61 | 62 | logging.debug("Running Delete Relaxation (HAdd)") 63 | path8, metrics8 = apla.astar_best_first_search(heuristic_key="delete_relaxation/h_add") 64 | actions8 = apla.get_actions_from_path(path8) 65 | path8 = Path(path8) 66 | 67 | 68 | actions_str = "" 69 | for a in actions: 70 | actions_str += str(a) + "\n" 71 | 72 | actions_str2 = "" 73 | for a in actions2: 74 | actions_str2 += str(a) + "\n" 75 | 76 | actions_str3 = "" 77 | for a in actions3: 78 | actions_str3 += str(a) + "\n" 79 | 80 | actions_str4 = "" 81 | for a in actions4: 82 | actions_str4 += str(a) + "\n" 83 | 84 | actions_str5 = "" 85 | for a in actions5: 86 | actions_str5 += str(a) + "\n" 87 | 88 | actions_str6 = "" 89 | for a in actions6: 90 | actions_str6 += str(a) + "\n" 91 | 92 | actions_str7 = "" 93 | for a in actions7: 94 | actions_str7 += str(a) + "\n" 95 | 96 | actions_str8 = "" 97 | for a in actions8: 98 | actions_str8 += str(a) + "\n" 99 | 100 | dump = ( 101 | "A* - Critical Path - H1\n ======PLAN (Nodes)=======\n%s\n" 102 | "======PLAN (Actions)=======\n%s\n" 103 | "======METRICS=======\n%s\n\n" 104 | "A* - Critical Path - H2\n" 105 | "======PLAN (Nodes)=======\n%s\n" 106 | "======PLAN (Actions)=======\n%s\n" 107 | "======METRICS=======\n%s\n\n" 108 | "A* - Critical Path - H3\n" 109 | "======PLAN (Nodes)=======\n%s\n" 110 | "======PLAN (Actions)=======\n%s\n" 111 | "======METRICS=======\n%s\n\n" 112 | "A* - Relaxed Critical Path - H1\n" 113 | "======PLAN (Nodes)=======\n%s\n" 114 | "======PLAN (Actions)=======\n%s\n" 115 | "======METRICS=======\n%s\n\n" 116 | "A* - Relaxed Critical Path - H2\n" 117 | "======PLAN (Nodes)=======\n%s\n" 118 | "======PLAN (Actions)=======\n%s\n" 119 | "======METRICS=======\n%s\n\n" 120 | "A* - Relaxed Citical Path - H3\n" 121 | "======PLAN (Nodes)=======\n%s\n" 122 | "======PLAN (Actions)=======\n%s\n" 123 | "======METRICS=======\n%s\n\n" 124 | "A* - Delete Relaxation - H_Max\n" 125 | "======PLAN (Nodes)=======\n%s\n" 126 | "======PLAN (Actions)=======\n%s\n" 127 | "======METRICS=======\n%s\n\n" 128 | "A* - Delete Relaxation - H_Add\n" 129 | "======PLAN (Nodes)=======\n%s\n" 130 | "======PLAN (Actions)=======\n%s\n" 131 | "======METRICS=======\n%s\n\n" 132 | % ( 133 | str(path), 134 | actions_str, 135 | str(metrics), 136 | str(path2), 137 | actions_str2, 138 | str(metrics2), 139 | str(path3), 140 | actions_str3, 141 | str(metrics3), 142 | str(path4), 143 | actions_str4, 144 | str(metrics4), 145 | str(path5), 146 | actions_str5, 147 | str(metrics5), 148 | str(path6), 149 | actions_str6, 150 | str(metrics6), 151 | str(path7), 152 | actions_str7, 153 | str(metrics7), 154 | str(path8), 155 | actions_str8, 156 | str(metrics8), 157 | ) 158 | ) 159 | 160 | f = open(output, "w") 161 | f.write(dump) 162 | f.close() 163 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("requirements.txt") as f: 4 | required = f.read().splitlines() 5 | 6 | with open("README.md", "r", encoding="utf-8") as fh: 7 | long_description = fh.read() 8 | 9 | 10 | setuptools.setup( 11 | name="jupyddl", # Replace with your own username 12 | version="0.4.1", 13 | author="Erwin Lejeune", 14 | author_email="erwinlejeune.pro@gmail.com", 15 | description="Jupyddl is a PDDL planner built on top of a Julia parser", 16 | long_description=long_description, 17 | long_description_content_type="text/markdown", 18 | url="https://github.com/apla-toolbox/pythonpddl", 19 | packages=setuptools.find_packages(), 20 | install_requires=required, 21 | classifiers=[ 22 | "Programming Language :: Python :: 3 :: Only", 23 | "Programming Language :: Python :: 3.6", 24 | "Programming Language :: Python :: 3.7", 25 | "Programming Language :: Python :: 3.8", 26 | "Programming Language :: Python :: 3", 27 | "License :: OSI Approved :: Apache Software License", 28 | "Operating System :: Unix", 29 | "Operating System :: MacOS", 30 | "Framework :: Pytest", 31 | ], 32 | python_requires=">=3.6", 33 | ) 34 | -------------------------------------------------------------------------------- /tests/test_automated_planner.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | from os import path 5 | 6 | sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 7 | from jupyddl.automated_planner import AutomatedPlanner 8 | 9 | 10 | def test_parsing(): 11 | apla = AutomatedPlanner( 12 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 13 | ) 14 | assert str(apla.problem) != "" and str(apla.domain) != "" 15 | 16 | 17 | def test_available_actions(): 18 | apla = AutomatedPlanner( 19 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 20 | ) 21 | actions = apla.available_actions(apla.initial_state) 22 | assert len(actions) > 0 23 | 24 | 25 | def test_execute_action(): 26 | apla = AutomatedPlanner( 27 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 28 | ) 29 | actions = apla.available_actions(apla.initial_state) 30 | new_state = apla.transition(apla.initial_state, actions[0]) 31 | assert str(new_state) != str(apla.initial_state) 32 | 33 | 34 | def test_state_has_term(): 35 | apla = AutomatedPlanner( 36 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 37 | ) 38 | is_goal = apla.state_has_term(apla.initial_state, apla.goals[0]) 39 | assert not is_goal 40 | 41 | 42 | def test_state_assertion(): 43 | apla = AutomatedPlanner( 44 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 45 | ) 46 | assert not apla.satisfies(apla.problem.goal, apla.initial_state) 47 | 48 | 49 | def test_bfs(): 50 | apla = AutomatedPlanner( 51 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 52 | ) 53 | path, metrics = apla.breadth_first_search() 54 | plan = apla.get_actions_from_path(path) 55 | plan_state = apla.get_state_def_from_path(path) 56 | assert plan and plan_state and metrics.n_opened > 0 57 | 58 | 59 | def test_dfs(): 60 | apla = AutomatedPlanner( 61 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 62 | ) 63 | path, metrics = apla.depth_first_search() 64 | plan = apla.get_actions_from_path(path) 65 | plan_state = apla.get_state_def_from_path(path) 66 | assert plan and plan_state and metrics.n_opened > 0 67 | 68 | 69 | def test_dij(): 70 | apla = AutomatedPlanner( 71 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 72 | ) 73 | path, metrics = apla.dijktra_best_first_search() 74 | plan = apla.get_actions_from_path(path) 75 | plan_state = apla.get_state_def_from_path(path) 76 | assert plan and plan_state and metrics.n_opened > 0 77 | 78 | 79 | def test_astar(): 80 | apla = AutomatedPlanner( 81 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 82 | ) 83 | path, metrics = apla.astar_best_first_search() 84 | plan = apla.get_actions_from_path(path) 85 | plan_state = apla.get_state_def_from_path(path) 86 | assert plan and plan_state and metrics.n_opened > 0 87 | -------------------------------------------------------------------------------- /tests/test_basic_astar.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | from os import path 5 | 6 | sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 7 | from jupyddl.automated_planner import AutomatedPlanner 8 | from jupyddl.a_star import AStarBestFirstSearch 9 | from jupyddl.heuristics import BasicHeuristic 10 | 11 | 12 | def test_astar_basic(): 13 | apla = AutomatedPlanner( 14 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 15 | ) 16 | heuristic = BasicHeuristic(apla, "basic/goal_count") 17 | astar = AStarBestFirstSearch(apla, heuristic.compute) 18 | assert astar.init.h_cost == heuristic.compute(apla.initial_state) 19 | 20 | 21 | def test_astar_goal(): 22 | apla = AutomatedPlanner( 23 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 24 | ) 25 | heuristic = BasicHeuristic(apla, "basic/goal_count") 26 | astar = AStarBestFirstSearch(apla, heuristic.compute) 27 | lastnode, metrics = astar.search() 28 | assert lastnode and lastnode.parent and metrics.n_evaluated > 0 29 | 30 | 31 | def test_astar_path_length(): 32 | apla = AutomatedPlanner( 33 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 34 | ) 35 | path, _ = apla.astar_best_first_search() 36 | assert len(path) > 0 37 | 38 | 39 | def test_astar_path_no_path(): 40 | apla = AutomatedPlanner( 41 | "pddl-examples/vehicle/domain.pddl", "pddl-examples/vehicle/problem.pddl" 42 | ) 43 | path, _ = apla.astar_best_first_search() 44 | assert len(path) == 0 45 | 46 | 47 | def test_astar_path_no_heuristic(): 48 | apla = AutomatedPlanner( 49 | "pddl-examples/flip/domain.pddl", "pddl-examples/flip/problem.pddl" 50 | ) 51 | p, _ = apla.astar_best_first_search(heuristic_key="idontexist") 52 | assert not p 53 | 54 | 55 | def test_astar_path_bounded(): 56 | apla = AutomatedPlanner( 57 | "pddl-examples/flip/domain.pddl", "pddl-examples/flip/problem.pddl" 58 | ) 59 | p, _ = apla.astar_best_first_search(heuristic_key="idontexist", node_bound=1) 60 | assert not p 61 | -------------------------------------------------------------------------------- /tests/test_basic_search.py: -------------------------------------------------------------------------------- 1 | from jupyddl.automated_planner import AutomatedPlanner 2 | from jupyddl.dijkstra import DijkstraBestFirstSearch, zero_heuristic 3 | from jupyddl.a_star import AStarBestFirstSearch 4 | from jupyddl.bfs import BreadthFirstSearch 5 | from jupyddl.heuristics import BasicHeuristic, DeleteRelaxationHeuristic 6 | from jupyddl.dfs import DepthFirstSearch 7 | from os import path 8 | import coloredlogs 9 | import sys 10 | 11 | 12 | def test_search_dfs(): 13 | apla = AutomatedPlanner( 14 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 15 | ) 16 | dfs = DepthFirstSearch(apla) 17 | path, metrics = dfs.search() 18 | assert path and metrics.n_evaluated > 0 19 | 20 | 21 | def test_search_dfs_bounded(): 22 | apla = AutomatedPlanner( 23 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 24 | ) 25 | dfs = DepthFirstSearch(apla) 26 | path, _ = dfs.search(node_bound=1) 27 | assert not path 28 | 29 | 30 | def test_search_bfs(): 31 | apla = AutomatedPlanner( 32 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 33 | ) 34 | bfs = BreadthFirstSearch(apla) 35 | path, metrics = bfs.search() # Path, computation time, opened nodes 36 | assert path and metrics.n_evaluated > 0 37 | 38 | 39 | def test_search_bfs_bounded(): 40 | apla = AutomatedPlanner( 41 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 42 | ) 43 | bfs = BreadthFirstSearch(apla) 44 | path, _ = bfs.search(node_bound=1) # Path, computation time, opened nodes 45 | assert not path 46 | 47 | 48 | def test_search_dijkstra(): 49 | apla = AutomatedPlanner( 50 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 51 | ) 52 | dijk = DijkstraBestFirstSearch(apla) 53 | path, metrics = dijk.search() # Goal, computation_time, opened_nodes(in this order) 54 | assert path and metrics.n_evaluated > 0 # Assert that it took some time to compute 55 | 56 | 57 | def test_search_dijkstra_bounded(): 58 | apla = AutomatedPlanner( 59 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 60 | ) 61 | dijk = DijkstraBestFirstSearch(apla) 62 | path, _ = dijk.search( 63 | node_bound=1 64 | ) # Goal, computation_time, opened_nodes(in this order) 65 | assert not path 66 | 67 | 68 | def test_search_dijkstra_no_path(): 69 | apla = AutomatedPlanner( 70 | "pddl-examples/vehicle/domain.pddl", "pddl-examples/vehicle/problem.pddl" 71 | ) 72 | dijk = DijkstraBestFirstSearch(apla) 73 | path, metrics = dijk.search() # Goal, computation_time, opened_nodes(in this order) 74 | assert not path and metrics.n_evaluated > 0 75 | 76 | 77 | def test_search_dfs_no_path(): 78 | apla = AutomatedPlanner( 79 | "pddl-examples/vehicle/domain.pddl", "pddl-examples/vehicle/problem.pddl" 80 | ) 81 | dfs = DepthFirstSearch(apla) 82 | path, metrics = dfs.search() # Goal, computation_time, opened_nodes(in this order) 83 | assert not path and metrics.n_evaluated > 0 84 | 85 | 86 | def test_search_bfs_no_path(): 87 | apla = AutomatedPlanner( 88 | "pddl-examples/vehicle/domain.pddl", "pddl-examples/vehicle/problem.pddl" 89 | ) 90 | bfs = BreadthFirstSearch(apla) 91 | path, metrics = bfs.search() # Goal, computation_time, opened_nodes(in this order) 92 | assert not path and metrics.n_evaluated > 0 93 | 94 | 95 | def test_search_astar_basic(): 96 | apla = AutomatedPlanner( 97 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 98 | ) 99 | heuristic = BasicHeuristic(apla, "basic/goal_count") 100 | astar = AStarBestFirstSearch(apla, heuristic.compute) 101 | ( 102 | path, 103 | metrics, 104 | ) = astar.search() # Goal, computation_time, opened_nodes(in this order) 105 | assert path and metrics.n_evaluated > 0 106 | 107 | 108 | def test_search_astar_basic_no_path(): 109 | apla = AutomatedPlanner( 110 | "pddl-examples/vehicle/domain.pddl", "pddl-examples/vehicle/problem.pddl" 111 | ) 112 | heuristic = BasicHeuristic(apla, "basic/goal_count") 113 | astar = AStarBestFirstSearch(apla, heuristic.compute) 114 | ( 115 | path, 116 | metrics, 117 | ) = astar.search() # Goal, computation_time, opened_nodes(in this order) 118 | assert not path and metrics.n_evaluated > 0 119 | 120 | 121 | def test_zero_heuristic(): 122 | assert zero_heuristic() == 0 123 | -------------------------------------------------------------------------------- /tests/test_data_analyst.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | from os import path 5 | 6 | sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 7 | from jupyddl.data_analyst import DataAnalyst 8 | 9 | 10 | def test_data_analyst_constructor(): 11 | _ = DataAnalyst() 12 | assert True 13 | 14 | 15 | def test_heuristics_comparer(): 16 | da = DataAnalyst() 17 | da.comparative_astar_heuristic_plot() 18 | 19 | 20 | def test_heuristics_comparer_single(): 21 | da = DataAnalyst() 22 | da.comparative_astar_heuristic_plot( 23 | domain="pddl-examples/dinner/domain.pddl", 24 | problem="pddl-examples/dinner/problem.pddl", 25 | ) 26 | 27 | 28 | def test_data_analyst_plot_dfs_one_pddl(): 29 | da = DataAnalyst() 30 | da.plot_dfs( 31 | domain="pddl-examples/dinner/domain.pddl", 32 | problem="pddl-examples/dinner/problem.pddl", 33 | ) 34 | assert True 35 | 36 | 37 | def test_data_analyst_plot_bfs_one_pddl(): 38 | da = DataAnalyst() 39 | da.plot_bfs( 40 | domain="pddl-examples/dinner/domain.pddl", 41 | problem="pddl-examples/dinner/problem.pddl", 42 | ) 43 | assert True 44 | 45 | 46 | def test_data_analyst_plot_dijkstra_one_pddl(): 47 | da = DataAnalyst() 48 | da.plot_dijkstra( 49 | domain="pddl-examples/dinner/domain.pddl", 50 | problem="pddl-examples/dinner/problem.pddl", 51 | ) 52 | assert True 53 | 54 | 55 | def test_data_analyst_plot_astar_h_goal_count_one_pddl(): 56 | da = DataAnalyst() 57 | da.plot_astar( 58 | domain="pddl-examples/dinner/domain.pddl", 59 | problem="pddl-examples/dinner/problem.pddl", 60 | ) 61 | assert True 62 | 63 | 64 | def test_data_analyst_plot_dfs(): 65 | da = DataAnalyst() 66 | da.plot_dfs() 67 | assert True 68 | 69 | 70 | def test_data_analyst_plot_bfs(): 71 | da = DataAnalyst() 72 | da.plot_bfs() 73 | assert True 74 | 75 | 76 | def test_data_analyst_plot_dijkstra(): 77 | da = DataAnalyst() 78 | da.plot_dijkstra() 79 | assert True 80 | 81 | 82 | def test_data_analyst_plot_astar_h_goal_count(): 83 | da = DataAnalyst() 84 | da.plot_astar() 85 | assert True 86 | 87 | 88 | def test_data_analyst_plot_dfs_restricted(): 89 | da = DataAnalyst() 90 | da.plot_dfs(max_pddl_instances=2) 91 | assert True 92 | 93 | 94 | def test_data_analyst_plot_bfs_restricted(): 95 | da = DataAnalyst() 96 | da.plot_bfs(max_pddl_instances=2) 97 | assert True 98 | 99 | 100 | def test_data_analyst_plot_dijkstra_restricted(): 101 | da = DataAnalyst() 102 | da.plot_dijkstra(max_pddl_instances=2) 103 | assert True 104 | 105 | 106 | def test_data_analyst_plot_astar_h_goal_count_restricted(): 107 | da = DataAnalyst() 108 | da.plot_astar(max_pddl_instances=2) 109 | assert True 110 | 111 | 112 | def test_data_analyst_plot_astar_h_max(): 113 | da = DataAnalyst() 114 | da.plot_astar(heuristic_key="delete_relaxation/h_max") 115 | assert True 116 | 117 | 118 | def test_data_analyst_plot_greedy_h_goal_count_restricted(): 119 | da = DataAnalyst() 120 | da.plot_greedy_bfs(max_pddl_instances=2) 121 | assert True 122 | 123 | 124 | def test_data_analyst_plot_greedy_hmax(): 125 | da = DataAnalyst() 126 | da.plot_greedy_bfs(heuristic_key="delete_relaxation/h_max") 127 | assert True 128 | 129 | 130 | def test_comparative_no_restrictions(): 131 | da = DataAnalyst() 132 | da.comparative_data_plot() 133 | assert True 134 | 135 | 136 | def test_comparative_no_astar(): 137 | da = DataAnalyst() 138 | da.comparative_data_plot(astar=False) 139 | assert True 140 | 141 | 142 | def test_comparative_no_bfs(): 143 | da = DataAnalyst() 144 | da.comparative_data_plot(bfs=False) 145 | assert True 146 | 147 | 148 | def test_comparative_no_dijkstra(): 149 | da = DataAnalyst() 150 | da.comparative_data_plot(dijkstra=False) 151 | assert True 152 | 153 | 154 | def test_comparative_no_dfs(): 155 | da = DataAnalyst() 156 | da.comparative_data_plot(dfs=False) 157 | assert True 158 | 159 | 160 | def test_comparative_one_pddl(): 161 | da = DataAnalyst() 162 | da.comparative_data_plot( 163 | dfs=False, 164 | bfs=False, 165 | greedy_bfs=True, 166 | domain="pddl-examples/dinner/domain.pddl", 167 | problem="pddl-examples/dinner/problem.pddl", 168 | ) 169 | assert True 170 | 171 | 172 | def test_comparative_use_data_json(): 173 | da = DataAnalyst() 174 | da.comparative_data_plot( 175 | domain="pddl-examples/dinner/domain.pddl", 176 | problem="pddl-examples/dinner/problem.pddl", 177 | greedy_bfs=True, 178 | collect_new_data=False, 179 | ) 180 | assert True 181 | 182 | 183 | def test_comparative_zero_h(): 184 | da = DataAnalyst() 185 | da.comparative_data_plot( 186 | domain="pddl-examples/dinner/domain.pddl", 187 | problem="pddl-examples/dinner/problem.pddl", 188 | greedy_bfs=True, 189 | heuristic_key="zero", 190 | ) 191 | assert True 192 | 193 | 194 | def test_success_rate(): 195 | da = DataAnalyst() 196 | da.compute_planners_efficiency() 197 | assert True 198 | 199 | 200 | def test_metrics(): 201 | da = DataAnalyst() 202 | da.plot_metrics() 203 | assert True 204 | -------------------------------------------------------------------------------- /tests/test_greedy_best_first.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | from os import path 5 | 6 | sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 7 | from jupyddl.automated_planner import AutomatedPlanner 8 | from jupyddl.greedy_best_first import GreedyBestFirstSearch 9 | from jupyddl.heuristics import BasicHeuristic, DeleteRelaxationHeuristic 10 | 11 | 12 | def test_greedy_best_first_basic(): 13 | apla = AutomatedPlanner( 14 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 15 | ) 16 | heuristic = BasicHeuristic(apla, "basic/goal_count") 17 | gbfs = GreedyBestFirstSearch(apla, heuristic.compute) 18 | assert gbfs.init.h_cost == heuristic.compute(apla.initial_state) 19 | 20 | 21 | def test_greedy_best_first_goal(): 22 | apla = AutomatedPlanner( 23 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 24 | ) 25 | heuristic = BasicHeuristic(apla, "basic/goal_count") 26 | gbfs = GreedyBestFirstSearch(apla, heuristic.compute) 27 | lastnode, _ = gbfs.search() 28 | assert lastnode and lastnode.parent 29 | 30 | 31 | def test_greedy_best_first_path_length(): 32 | apla = AutomatedPlanner( 33 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 34 | ) 35 | path, _ = apla.greedy_best_first_search() 36 | assert len(path) > 0 37 | 38 | 39 | def test_greedy_best_first_bounded(): 40 | apla = AutomatedPlanner( 41 | "pddl-examples/tsp/domain.pddl", "pddl-examples/tsp/problem.pddl" 42 | ) 43 | path, _ = apla.greedy_best_first_search(node_bound=1) 44 | assert not path 45 | 46 | 47 | def test_greedy_best_first_path_no_path(): 48 | apla = AutomatedPlanner( 49 | "pddl-examples/vehicle/domain.pddl", "pddl-examples/vehicle/problem.pddl" 50 | ) 51 | path, metrics = apla.greedy_best_first_search() 52 | assert not path and metrics.n_evaluated > 0 53 | 54 | 55 | def test_greedy_best_first_path_no_heuristic(): 56 | apla = AutomatedPlanner( 57 | "pddl-examples/flip/domain.pddl", "pddl-examples/flip/problem.pddl" 58 | ) 59 | p, _ = apla.greedy_best_first_search(heuristic_key="idontexist") 60 | assert not p 61 | 62 | 63 | def test_greedy_best_first_hmax(): 64 | apla = AutomatedPlanner( 65 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 66 | ) 67 | heuristic = DeleteRelaxationHeuristic(apla, "delete_relaxation/h_max") 68 | astar = GreedyBestFirstSearch(apla, heuristic.compute) 69 | assert astar.init.h_cost == heuristic.compute(apla.initial_state) 70 | 71 | 72 | def test_greedy_best_first_hadd(): 73 | apla = AutomatedPlanner( 74 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 75 | ) 76 | heuristic = DeleteRelaxationHeuristic(apla, "delete_relaxation/h_max") 77 | astar = GreedyBestFirstSearch(apla, heuristic.compute) 78 | assert astar.init.h_cost == heuristic.compute(apla.initial_state) 79 | 80 | 81 | def test_greedy_best_first_hmax_sensible_domain(): 82 | apla = AutomatedPlanner( 83 | "pddl-examples/grid/domain.pddl", "pddl-examples/grid/problem.pddl" 84 | ) 85 | heuristic = DeleteRelaxationHeuristic(apla, "delete_relaxation/h_max") 86 | astar = GreedyBestFirstSearch(apla, heuristic.compute) 87 | assert astar.init.h_cost == heuristic.compute(apla.initial_state) 88 | 89 | 90 | def test_greedy_best_first_hadd_sensible_domain(): 91 | apla = AutomatedPlanner( 92 | "pddl-examples/grid/domain.pddl", "pddl-examples/grid/problem.pddl" 93 | ) 94 | heuristic = DeleteRelaxationHeuristic(apla, "delete_relaxation/h_max") 95 | astar = GreedyBestFirstSearch(apla, heuristic.compute) 96 | assert astar.init.h_cost == heuristic.compute(apla.initial_state) 97 | -------------------------------------------------------------------------------- /tests/test_heuristics.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | from os import path 5 | 6 | sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 7 | from jupyddl.automated_planner import AutomatedPlanner 8 | import jupyddl.heuristics as hs 9 | 10 | """ 11 | Testing the heuristics in different situations 12 | To do: 13 | - Run search algorithms and test value of h when at goal 14 | """ 15 | 16 | 17 | def test_zero_heuristic(): 18 | apla = AutomatedPlanner( 19 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 20 | ) 21 | apla.display_available_heuristics() 22 | heuristic = hs.BasicHeuristic(apla, "basic/zero") 23 | h = heuristic.compute(apla.initial_state) 24 | assert h == 0 25 | 26 | 27 | def test_goal_count_heuristic(): 28 | apla = AutomatedPlanner( 29 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 30 | ) 31 | apla.display_available_heuristics() 32 | heuristic = hs.BasicHeuristic(apla, "basic/goal_count") 33 | h = heuristic.compute(apla.initial_state) 34 | assert h != 0 35 | 36 | 37 | def test_delete_relaxation_add_heuristic(): 38 | apla = AutomatedPlanner( 39 | "pddl-examples/tsp/domain.pddl", "pddl-examples/tsp/problem.pddl" 40 | ) 41 | apla.display_available_heuristics() 42 | heuristic = hs.DeleteRelaxationHeuristic(apla, "delete_relaxation/h_max") 43 | h = heuristic.compute(apla.initial_state) 44 | assert h != 0 45 | -------------------------------------------------------------------------------- /tests/test_hsp_astar.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | from os import path 5 | 6 | sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 7 | from jupyddl.automated_planner import AutomatedPlanner 8 | from jupyddl.a_star import AStarBestFirstSearch 9 | from jupyddl.heuristics import DeleteRelaxationHeuristic 10 | 11 | 12 | def test_astar_hmax(): 13 | apla = AutomatedPlanner( 14 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 15 | ) 16 | heuristic = DeleteRelaxationHeuristic(apla, "delete_relaxation/h_max") 17 | astar = AStarBestFirstSearch(apla, heuristic.compute) 18 | assert astar.init.h_cost == heuristic.compute(apla.initial_state) 19 | 20 | 21 | def test_astar_hadd(): 22 | apla = AutomatedPlanner( 23 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 24 | ) 25 | heuristic = DeleteRelaxationHeuristic(apla, "delete_relaxation/h_max") 26 | astar = AStarBestFirstSearch(apla, heuristic.compute) 27 | assert astar.init.h_cost == heuristic.compute(apla.initial_state) 28 | 29 | 30 | def test_astar_hmax_sensible_domain(): 31 | apla = AutomatedPlanner( 32 | "pddl-examples/grid/domain.pddl", "pddl-examples/grid/problem.pddl" 33 | ) 34 | heuristic = DeleteRelaxationHeuristic(apla, "delete_relaxation/h_max") 35 | astar = AStarBestFirstSearch(apla, heuristic.compute) 36 | assert astar.init.h_cost == heuristic.compute(apla.initial_state) 37 | 38 | 39 | def test_astar_hadd_sensible_domain(): 40 | apla = AutomatedPlanner( 41 | "pddl-examples/grid/domain.pddl", "pddl-examples/grid/problem.pddl" 42 | ) 43 | heuristic = DeleteRelaxationHeuristic(apla, "delete_relaxation/h_max") 44 | astar = AStarBestFirstSearch(apla, heuristic.compute) 45 | assert astar.init.h_cost == heuristic.compute(apla.initial_state) 46 | -------------------------------------------------------------------------------- /tests/test_metrics.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | from os import path 5 | 6 | sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 7 | from jupyddl.metrics import Metrics 8 | 9 | 10 | def test_metrics(): 11 | m = Metrics() 12 | assert m.n_opened == 1 and m.n_generated and m.get_average_heuristic_runtime() == 0 13 | -------------------------------------------------------------------------------- /tests/test_node.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | from os import path 5 | 6 | sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) 7 | from jupyddl.automated_planner import AutomatedPlanner 8 | from jupyddl.node import Node, Path 9 | 10 | 11 | def test_node_equality_cost(): 12 | apla = AutomatedPlanner( 13 | "pddl-examples/tsp/domain.pddl", "pddl-examples/tsp/problem.pddl" 14 | ) 15 | actions = apla.available_actions(apla.initial_state) 16 | next_state = apla.transition(apla.initial_state, actions[0]) 17 | next_node = Node(next_state, apla, heuristic_based=True) 18 | next_node_v2 = Node(next_state, apla) 19 | 20 | assertion = next_node_v2 < next_node 21 | assertion2 = next_node < next_node_v2 22 | 23 | assert assertion and assertion2 24 | 25 | 26 | def test_node_equality_no_cost(): 27 | apla = AutomatedPlanner( 28 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 29 | ) 30 | actions = apla.available_actions(apla.initial_state) 31 | next_state = apla.transition(apla.initial_state, actions[0]) 32 | next_node = Node(next_state, apla, heuristic_based=True) 33 | next_node_v2 = Node(next_state, apla) 34 | 35 | assertion = next_node_v2 < next_node 36 | assertion2 = next_node < next_node_v2 37 | 38 | assert assertion and assertion2 39 | 40 | 41 | def test_stringified_node(): 42 | apla = AutomatedPlanner( 43 | "pddl-examples/dinner/domain.pddl", "pddl-examples/dinner/problem.pddl" 44 | ) 45 | actions = apla.available_actions(apla.initial_state) 46 | for act in actions: 47 | next_state = apla.transition(apla.initial_state, act) 48 | next_node = Node(next_state, apla, heuristic_based=True) 49 | assert "