Commit 4c97471f by serfrape

Initial commit

parents
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
charset = utf-8
end_of_line = lf
[*.bat]
indent_style = tab
end_of_line = crlf
[LICENSE]
insert_final_newline = false
[Makefile]
indent_style = tab
* Spade-BDI version:
* Python version:
* Operating System:
### Description
Describe what you were trying to get done.
Tell us what happened, what went wrong, and what you expected to happen.
### What I Did
```
Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.
```
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# dotenv
.env
# virtualenv
.venv
venv/
ENV/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
# Config file for automatic testing at travis-ci.org
language: python
python:
- 3.6
- 3.5
- 3.4
- 2.7
# Command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors
install: pip install -U tox-travis
# Command to run tests, e.g. python setup.py test
script: tox
# Assuming you have installed the travis-ci CLI tool, after you
# create the Github repo and add it to Travis, run the
# following command to finish PyPI deployment setup:
# $ travis encrypt --add deploy.password
deploy:
provider: pypi
distributions: sdist bdist_wheel
user: sfp932705
password:
secure: PLEASE_REPLACE_ME
on:
tags: true
repo: sfp932705/spade_bdi
python: 3.6
=======
Credits
=======
Development Lead
----------------
* Sergio Frayle Pérez <sfp932705@gmail.com>
Contributors
------------
None yet. Why not be the first?
.. highlight:: shell
============
Contributing
============
Contributions are welcome, and they are greatly appreciated! Every little bit
helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions
----------------------
Report Bugs
~~~~~~~~~~~
Report bugs at https://github.com/sfp932705/spade_bdi/issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
Fix Bugs
~~~~~~~~
Look through the GitHub issues for bugs. Anything tagged with "bug" and "help
wanted" is open to whoever wants to implement it.
Implement Features
~~~~~~~~~~~~~~~~~~
Look through the GitHub issues for features. Anything tagged with "enhancement"
and "help wanted" is open to whoever wants to implement it.
Write Documentation
~~~~~~~~~~~~~~~~~~~
Spade-BDI could always use more documentation, whether as part of the
official Spade-BDI docs, in docstrings, or even on the web in blog posts,
articles, and such.
Submit Feedback
~~~~~~~~~~~~~~~
The best way to send feedback is to file an issue at https://github.com/sfp932705/spade_bdi/issues.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
Get Started!
------------
Ready to contribute? Here's how to set up `spade_bdi` for local development.
1. Fork the `spade_bdi` repo on GitHub.
2. Clone your fork locally::
$ git clone git@github.com:your_name_here/spade_bdi.git
3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development::
$ mkvirtualenv spade_bdi
$ cd spade_bdi/
$ python setup.py develop
4. Create a branch for local development::
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
5. When you're done making changes, check that your changes pass flake8 and the
tests, including testing other Python versions with tox::
$ flake8 spade_bdi tests
$ python setup.py test or py.test
$ tox
To get flake8 and tox, just pip install them into your virtualenv.
6. Commit your changes and push your branch to GitHub::
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
7. Submit a pull request through the GitHub website.
Pull Request Guidelines
-----------------------
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put
your new functionality into a function with a docstring, and add the
feature to the list in README.rst.
3. The pull request should work for Python 2.7, 3.4, 3.5 and 3.6, and for PyPy. Check
https://travis-ci.org/sfp932705/spade_bdi/pull_requests
and make sure that the tests pass for all supported Python versions.
Tips
----
To run a subset of tests::
$ py.test tests.test_spade_bdi
Deploying
---------
A reminder for the maintainers on how to deploy.
Make sure all your changes are committed (including an entry in HISTORY.rst).
Then run::
$ bumpversion patch # possible: major / minor / patch
$ git push
$ git push --tags
Travis will then deploy to PyPI if tests pass.
=======
History
=======
0.1.0 (2019-03-09)
------------------
* First release on PyPI.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Implement BDI Agents based on the SPADE MAS Platform
Copyright (C) 2019 Sergio Frayle Pérez
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
include AUTHORS.rst
include CONTRIBUTING.rst
include HISTORY.rst
include LICENSE
include README.rst
recursive-include tests *
recursive-exclude * __pycache__
recursive-exclude * *.py[co]
recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif
.PHONY: clean clean-test clean-pyc clean-build docs help
.DEFAULT_GOAL := help
define BROWSER_PYSCRIPT
import os, webbrowser, sys
try:
from urllib import pathname2url
except:
from urllib.request import pathname2url
webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1])))
endef
export BROWSER_PYSCRIPT
define PRINT_HELP_PYSCRIPT
import re, sys
for line in sys.stdin:
match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
if match:
target, help = match.groups()
print("%-20s %s" % (target, help))
endef
export PRINT_HELP_PYSCRIPT
BROWSER := python -c "$$BROWSER_PYSCRIPT"
help:
@python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)
clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts
clean-build: ## remove build artifacts
rm -fr build/
rm -fr dist/
rm -fr .eggs/
find . -name '*.egg-info' -exec rm -fr {} +
find . -name '*.egg' -exec rm -f {} +
clean-pyc: ## remove Python file artifacts
find . -name '*.pyc' -exec rm -f {} +
find . -name '*.pyo' -exec rm -f {} +
find . -name '*~' -exec rm -f {} +
find . -name '__pycache__' -exec rm -fr {} +
clean-test: ## remove test and coverage artifacts
rm -fr .tox/
rm -f .coverage
rm -fr htmlcov/
rm -fr .pytest_cache
lint: ## check style with flake8
flake8 spade_bdi tests
test: ## run tests quickly with the default Python
py.test
test-all: ## run tests on every Python version with tox
tox
coverage: ## check code coverage quickly with the default Python
coverage run --source spade_bdi -m pytest
coverage report -m
coverage html
$(BROWSER) htmlcov/index.html
docs: ## generate Sphinx HTML documentation, including API docs
rm -f docs/spade_bdi.rst
rm -f docs/modules.rst
sphinx-apidoc -o docs/ spade_bdi
$(MAKE) -C docs clean
$(MAKE) -C docs html
$(BROWSER) docs/_build/html/index.html
servedocs: docs ## compile the docs watching for changes
watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D .
release: dist ## package and upload a release
twine upload dist/*
dist: clean ## builds source and wheel package
python setup.py sdist
python setup.py bdist_wheel
ls -l dist
install: clean ## install the package to the active Python's site-packages
python setup.py install
=========
Spade-BDI
=========
.. image:: https://img.shields.io/pypi/v/spade_bdi.svg
:target: https://pypi.python.org/pypi/spade_bdi
.. image:: https://img.shields.io/travis/sfp932705/spade_bdi.svg
:target: https://travis-ci.org/sfp932705/spade_bdi
.. image:: https://readthedocs.org/projects/spade-bdi/badge/?version=latest
:target: https://spade-bdi.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
.. image:: https://pyup.io/repos/github/sfp932705/spade_bdi/shield.svg
:target: https://pyup.io/repos/github/sfp932705/spade_bdi/
:alt: Updates
Implement BDI Agents based on the SPADE MAS Platform
* Free software: GNU General Public License v3
* Documentation: https://spade-bdi.readthedocs.io.
Features
--------
* TODO
Credits
-------
This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.
.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = python -msphinx
SPHINXPROJ = spade_bdi
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.. include:: ../AUTHORS.rst
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# spade_bdi documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import spade_bdi
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Spade-BDI'
copyright = u"2019, Sergio Frayle Pérez"
author = u"Sergio Frayle Pérez"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = spade_bdi.__version__
# The full version, including alpha/beta/rc tags.
release = spade_bdi.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ---------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'spade_bdidoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto, manual, or own class]).
latex_documents = [
(master_doc, 'spade_bdi.tex',
u'Spade-BDI Documentation',
u'Sergio Frayle Pérez', 'manual'),
]
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'spade_bdi',
u'Spade-BDI Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'spade_bdi',
u'Spade-BDI Documentation',
author,
'spade_bdi',
'One line description of project.',
'Miscellaneous'),
]
.. include:: ../CONTRIBUTING.rst
.. include:: ../HISTORY.rst
Welcome to Spade-BDI's documentation!
======================================
.. toctree::
:maxdepth: 2
:caption: Contents:
readme
installation
usage
modules
contributing
authors
history
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. highlight:: shell
============
Installation
============
Stable release
--------------
To install Spade-BDI, run this command in your terminal:
.. code-block:: console
$ pip install spade_bdi
This is the preferred method to install Spade-BDI, as it will always install the most recent stable release.
If you don't have `pip`_ installed, this `Python installation guide`_ can guide
you through the process.
.. _pip: https://pip.pypa.io
.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/
From sources
------------
The sources for Spade-BDI can be downloaded from the `Github repo`_.
You can either clone the public repository:
.. code-block:: console
$ git clone git://github.com/sfp932705/spade_bdi
Or download the `tarball`_:
.. code-block:: console
$ curl -OL https://github.com/sfp932705/spade_bdi/tarball/master
Once you have a copy of the source, you can install it with:
.. code-block:: console
$ python setup.py install
.. _Github repo: https://github.com/sfp932705/spade_bdi
.. _tarball: https://github.com/sfp932705/spade_bdi/tarball/master
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=python -msphinx
)
set SOURCEDIR=.
set BUILDDIR=_build
set SPHINXPROJ=spade_bdi
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The Sphinx module was not found. Make sure you have Sphinx installed,
echo.then set the SPHINXBUILD environment variable to point to the full
echo.path of the 'sphinx-build' executable. Alternatively you may add the
echo.Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
:end
popd
.. include:: ../README.rst
=====
Usage
=====
To use Spade-BDI in a project::
import spade_bdi
from spade_bdi.bdi import BDIAgent
a = BDIAgent("BDIAgent@localhost", "bditest", "plan.asl")
a.start()
import time
time.sleep(1)
a.bdi.set_belief("car", "azul", "big")
a.bdi.print_beliefs()
print("GETTING FIRST CAR BELIEF")
print(a.bdi.get_belief("car"))
a.bdi.print_beliefs()
a.bdi.remove_belief("car", 'azul', "big")
a.bdi.print_beliefs()
print(a.bdi.get_beliefs())
a.bdi.set_belief("car", 'amarillo')
!start.
+!start <-
+car(rojo);
.a_function(3,W);
.print("w =", W);
literal_function(rojo,Y);
.print("Y =", Y);
.custom_action(8);
.print("sending individual message ...");
.send("BDIAgent@localhost", achieve, hello(15));
.print("sent a message").
+truck(azul).
+car(amarillo)
<- .print("El carro es amarillo.").
+!hello(Msg)[source(Sender)] <-
.print("got a message from", Sender, "saying", Msg).
\ No newline at end of file
from spade_bdi.bdi import BDIAgent
a = BDIAgent("BDIAgent@localhost", "bditest", "plan.asl")
a.start()
import time
time.sleep(1)
a.bdi.set_belief("car", "azul", "big")
a.bdi.print_beliefs()
print("GETTING FIRST CAR BELIEF")
print(a.bdi.get_belief("car"))
a.bdi.print_beliefs()
a.bdi.remove_belief("car", 'azul', "big")
a.bdi.print_beliefs()
print(a.bdi.get_beliefs())
a.bdi.set_belief("car", 'amarillo')
!start.
+!start <-
+car(rojo);
.a_function(3,W);
.print("w =", W);
literal_function(rojo,Y);
.print("Y =", Y);
.custom_action(8);
.print("sending individual message ...");
.send("BDIAgent@localhost", achieve, hello(15));
.print("sent a message").
+truck(azul).
+car(amarillo)
<- .print("El carro es amarillo.").
+!hello(Msg)[source(Sender)] <-
.print("got a message from", Sender, "saying", Msg).
\ No newline at end of file
pip==18.1
bumpversion==0.5.3
wheel==0.32.1
watchdog==0.9.0
flake8==3.5.0
tox==3.5.2
coverage==4.5.1
Sphinx==1.8.1
twine==1.12.1
pytest==3.8.2
pytest-runner==4.2
[bumpversion]
current_version = 0.1.0
commit = True
tag = True
[bumpversion:file:setup.py]
search = version='{current_version}'
replace = version='{new_version}'
[bumpversion:file:spade_bdi/__init__.py]
search = __version__ = '{current_version}'
replace = __version__ = '{new_version}'
[bdist_wheel]
universal = 1
[flake8]
exclude = docs
[aliases]
# Define setup.py command aliases here
test = pytest
[tool:pytest]
collect_ignore = ['setup.py']
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = ['Click>=6.0', ]
setup_requirements = ['pytest-runner', ]
test_requirements = ['pytest', ]
setup(
author="Sergio Frayle Pérez",
author_email='sfp932705@gmail.com',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
description="Implement BDI Agents based on the SPADE MAS Platform",
entry_points={
'console_scripts': [
'spade_bdi=spade_bdi.cli:main',
],
},
install_requires=requirements,
license="GNU General Public License v3",
long_description=readme + '\n\n' + history,
include_package_data=True,
keywords='spade_bdi',
name='spade_bdi',
packages=find_packages(include=['spade_bdi']),
setup_requires=setup_requirements,
test_suite='tests',
tests_require=test_requirements,
url='https://github.com/sfp932705/spade_bdi',
version='0.1.0',
zip_safe=False,
)
# -*- coding: utf-8 -*-
from . import bdi
"""Top-level package for Spade-BDI."""
__author__ = """Sergio Frayle Pérez"""
__email__ = 'sfp932705@gmail.com'
__version__ = '0.1.0'
__all__ = ["bdi"]
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
from spade.behaviour import CyclicBehaviour
import pyson
import pyson.runtime
import pyson.stdlib
import os
import asyncio
from spade.agent import Agent
from spade.template import Template
from spade.message import Message
import json
PERCEPT_TAG = frozenset(
[pyson.Literal("source", (pyson.Literal("percept"), ))])
class BDIAgent(Agent):
def setup(self):
template = Template(metadata={"performative": "BDI"})
self.add_behaviour(self.BDIBehaviour(), template)
def add_behaviour(self, behaviour, template=None):
# print("OVERRIDEN")
self.bdi = behaviour
super().add_behaviour(behaviour, template)
def __init__(self, jid, password, asl, *args, **kwargs):
self.asl_file = asl
super().__init__(jid, password, *args, **kwargs)
class BDIBehaviour(CyclicBehaviour, metaclass=ABCMeta):
def add_actions(self):
@self.actions.add(".send", 3)
def _send(agent, term, intention):
receiver = pyson.grounded(term.args[0], intention.scope)
ilf = pyson.grounded(term.args[1], intention.scope)
if not pyson.is_atom(ilf):
return
ilf_type = ilf.functor
mdata = {"performative": "BDI",
"ilf_type": ilf_type,
"message": term.args[2]}
# Optional body
body = json.dumps({})
msg = Message(to=receiver, body=body, metadata=mdata)
self.agent.submit(self.send(msg))
print("SENT!!!")
yield
@self.actions.add(".custom_action", 1)
def _custom_action(agent, term, intention):
arg_0 = pyson.grounded(term.args[0], intention.scope)
print(arg_0)
yield
@self.actions.add_function(".a_function", (int,))
def _a_function(x):
return x**4
@self.actions.add_function("literal_function", (pyson.Literal,))
def _literal_function(x):
return x
# def set_belief(self, agent, term, intention):
def set_belief(self, name, *args):
"""Set an agent's belief. If it already exists, updates it."""
new_args = ()
for x in args:
new_args += (pyson.Literal(x),)
term = pyson.Literal(name, tuple(new_args), PERCEPT_TAG)
found = False
for belief in list(self.bdi_agent.beliefs[term.literal_group()]):
if pyson.unifies(term, belief):
found = True
else:
self.bdi_agent.call(pyson.Trigger.removal, pyson.GoalType.belief, belief,
pyson.runtime.Intention())
if not found:
self.bdi_agent.call(pyson.Trigger.addition, pyson.GoalType.belief, term,
pyson.runtime.Intention())
def remove_belief(self, name, *args):
"""Remove an existing agent's belief."""
new_args = ()
for x in args:
new_args += (pyson.Literal(x),)
term = pyson.Literal(name, tuple(new_args), PERCEPT_TAG)
self.bdi_agent.call(pyson.Trigger.removal, pyson.GoalType.belief, term,
pyson.runtime.Intention())
def get_belief(self, key):
"""Get an existing agent's belief. The first belief matching
<key> is returned """
key = str(key)
for beliefs in self.bdi_agent.beliefs:
if beliefs[0] == key:
raw_belief = (
str(list(self.bdi_agent.beliefs[beliefs])[0]))
if '")[source' in raw_belief:
raw_belief = raw_belief.split('[')[0].replace('"', '')
belief = raw_belief
break
return belief
def get_beliefs(self):
"""Get agent's beliefs."""
belief_list = []
for beliefs in self.bdi_agent.beliefs:
try:
raw_belief = (
str(list(self.bdi_agent.beliefs[beliefs])[0]))
if ')[source(' in raw_belief:
raw_belief = raw_belief.split('[')[0].replace('"', '')
belief_list.append(raw_belief)
except IndexError:
pass
return belief_list
def print_beliefs(self):
print("PRINTING BELIEFS")
for beliefs in self.bdi_agent.beliefs.values():
for belief in beliefs:
if ')[source(' in str(belief):
belief = str(belief).split('[')[0].replace('"', '')
print(belief)
async def on_start(self):
"""
Coroutine called before the behaviour is started.
"""
self.env = pyson.runtime.Environment()
self.actions = pyson.Actions(pyson.stdlib.actions)
self.add_actions()
with open(self.agent.asl_file) as source:
self.bdi_agent = self.env.build_agent(
source, self.actions)
async def run(self):
"""
Coroutine run cyclic.
"""
msg = await self.receive(timeout=0.1)
if msg:
received = json.loads(msg.body)
mdata = msg.metadata
ilf_type = mdata["ilf_type"]
if ilf_type == "tell":
goal_type = pyson.GoalType.belief
trigger = pyson.Trigger.addition
elif ilf_type == "untell":
goal_type = pyson.GoalType.belief
trigger = pyson.Trigger.removal
elif ilf_type == "achieve":
goal_type = pyson.GoalType.achievement
trigger = pyson.Trigger.addition
else:
raise pyson.PysonError(
"unknown illocutionary force: %s" % ilf_type)
intention = pyson.runtime.Intention()
message = pyson.freeze(mdata["message"], intention.scope, {})
tagged_message = message.with_annotation(
pyson.Literal("source", (pyson.Literal(self.bdi_agent.name), )))
self.bdi_agent.call(trigger, goal_type,
tagged_message, intention)
# print("RECEIVED\n", received)
self.bdi_agent.step()
async def on_end(self):
"""
Coroutine called after the behaviour is done or killed.
"""
pass
# -*- coding: utf-8 -*-
"""Console script for spade_bdi."""
import sys
import click
@click.command()
def main(args=None):
"""Console script for spade_bdi."""
click.echo("Replace this message by putting your code into "
"spade_bdi.cli.main")
click.echo("See click documentation at http://click.pocoo.org/")
return 0
if __name__ == "__main__":
sys.exit(main()) # pragma: no cover
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `spade_bdi` package."""
import pytest
from click.testing import CliRunner
from spade_bdi import spade_bdi
from spade_bdi import cli
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audreyr/cookiecutter-pypackage')
def test_content(response):
"""Sample pytest test function with the pytest fixture as an argument."""
# from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
def test_command_line_interface():
"""Test the CLI."""
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert 'spade_bdi.cli.main' in result.output
help_result = runner.invoke(cli.main, ['--help'])
assert help_result.exit_code == 0
assert '--help Show this message and exit.' in help_result.output
[tox]
envlist = py27, py34, py35, py36, flake8
[travis]
python =
3.6: py36
3.5: py35
3.4: py34
2.7: py27
[testenv:flake8]
basepython = python
deps = flake8
commands = flake8 spade_bdi
[testenv]
setenv =
PYTHONPATH = {toxinidir}
deps =
-r{toxinidir}/requirements_dev.txt
; If you want to make tox run the tests with the same versions, create a
; requirements.txt with the pinned versions and uncomment the following line:
; -r{toxinidir}/requirements.txt
commands =
pip install -U pip
py.test --basetemp={envtmpdir}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment