Showing preview only (7,033K chars total). Download the full file or copy to clipboard to get everything.
Repository: aimacode/aima-python
Branch: master
Commit: 61d695b37c68
Files: 129
Total size: 6.7 MB
Directory structure:
gitextract_5odqtdr9/
├── .coveragerc
├── .flake8
├── .gitignore
├── .gitmodules
├── .travis.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SUBMODULE.md
├── agents.ipynb
├── agents.py
├── agents4e.py
├── arc_consistency_heuristics.ipynb
├── classical_planning_approaches.ipynb
├── csp.ipynb
├── csp.py
├── deep_learning4e.py
├── games.ipynb
├── games.py
├── games4e.ipynb
├── games4e.py
├── gui/
│ ├── eight_puzzle.py
│ ├── genetic_algorithm_example.py
│ ├── grid_mdp.py
│ ├── romania_problem.py
│ ├── tic-tac-toe.py
│ ├── tsp.py
│ ├── vacuum_agent.py
│ └── xy_vacuum_environment.py
├── images/
│ ├── IMAGE-CREDITS
│ └── makefile
├── improving_sat_algorithms.ipynb
├── index.ipynb
├── intro.ipynb
├── ipyviews.py
├── js/
│ ├── canvas.js
│ ├── continuousworld.js
│ └── gridworld.js
├── knowledge.py
├── knowledge_FOIL.ipynb
├── knowledge_current_best.ipynb
├── knowledge_version_space.ipynb
├── learning.ipynb
├── learning.py
├── learning4e.py
├── learning_apps.ipynb
├── logic.ipynb
├── logic.py
├── logic4e.py
├── making_simple_decision4e.py
├── mdp.ipynb
├── mdp.py
├── mdp4e.py
├── mdp_apps.ipynb
├── neural_nets.ipynb
├── nlp.ipynb
├── nlp.py
├── nlp4e.py
├── nlp_apps.ipynb
├── notebook.py
├── notebook4e.py
├── notebooks/
│ ├── chapter19/
│ │ ├── Learners.ipynb
│ │ ├── Loss Functions and Layers.ipynb
│ │ ├── Optimizer and Backpropagation.ipynb
│ │ └── RNN.ipynb
│ ├── chapter21/
│ │ ├── Active Reinforcement Learning.ipynb
│ │ └── Passive Reinforcement Learning.ipynb
│ ├── chapter22/
│ │ ├── Grammar.ipynb
│ │ ├── Introduction.ipynb
│ │ ├── Parsing.ipynb
│ │ └── nlp_apps.ipynb
│ └── chapter24/
│ ├── Image Edge Detection.ipynb
│ ├── Image Segmentation.ipynb
│ └── Objects in Images.ipynb
├── obsolete_search4e.ipynb
├── perception4e.py
├── planning.ipynb
├── planning.py
├── planning_angelic_search.ipynb
├── planning_graphPlan.ipynb
├── planning_hierarchical_search.ipynb
├── planning_partial_order_planner.ipynb
├── planning_total_order_planner.ipynb
├── probabilistic_learning.py
├── probability.ipynb
├── probability.py
├── probability4e.ipynb
├── probability4e.py
├── pytest.ini
├── reinforcement_learning.ipynb
├── reinforcement_learning.py
├── reinforcement_learning4e.py
├── requirements.txt
├── search.ipynb
├── search.py
├── search4e.ipynb
├── tests/
│ ├── __init__.py
│ ├── pytest.ini
│ ├── test_agents.py
│ ├── test_agents4e.py
│ ├── test_csp.py
│ ├── test_deep_learning4e.py
│ ├── test_games.py
│ ├── test_games4e.py
│ ├── test_knowledge.py
│ ├── test_learning.py
│ ├── test_learning4e.py
│ ├── test_logic.py
│ ├── test_logic4e.py
│ ├── test_mdp.py
│ ├── test_mdp4e.py
│ ├── test_nlp.py
│ ├── test_nlp4e.py
│ ├── test_perception4e.py
│ ├── test_planning.py
│ ├── test_probabilistic_learning.py
│ ├── test_probability.py
│ ├── test_probability4e.py
│ ├── test_reinforcement_learning.py
│ ├── test_reinforcement_learning4e.py
│ ├── test_search.py
│ ├── test_text.py
│ └── test_utils.py
├── text.ipynb
├── text.py
├── utils.py
├── utils4e.py
├── vacuum_world.ipynb
└── viterbi_algorithm.ipynb
================================================
FILE CONTENTS
================================================
================================================
FILE: .coveragerc
================================================
[report]
omit =
tests/*
================================================
FILE: .flake8
================================================
[flake8]
max-line-length = 100
ignore = E121,E123,E126,E221,E222,E225,E226,E242,E701,E702,E704,E731,W503,F405,F841
exclude = tests
================================================
FILE: .gitignore
================================================
# 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/
*.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 instance folder
instance/
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# dotenv
.env
.idea
# for macOS
.DS_Store
._.DS_Store
================================================
FILE: .gitmodules
================================================
[submodule "aima-data"]
path = aima-data
url = https://github.com/aimacode/aima-data.git
================================================
FILE: .travis.yml
================================================
language: python
python:
- 3.5
- 3.6
- 3.7
- 3.8
before_install:
- git submodule update --remote
install:
- pip install --upgrade -r requirements.txt
script:
- py.test --cov=./
- python -m doctest -v *.py
after_success:
- flake8 --max-line-length 100 --ignore=E121,E123,E126,E221,E222,E225,E226,E242,E701,E702,E704,E731,W503 .
notifications:
email: false
================================================
FILE: CONTRIBUTING.md
================================================
How to Contribute to aima-python
==========================
Thanks for considering contributing to `aima-python`! Whether you are an aspiring [Google Summer of Code](https://summerofcode.withgoogle.com/organizations/5431334980288512/) student, or an independent contributor, here is a guide on how you can help.
First of all, you can read these write-ups from past GSoC students to get an idea about what you can do for the project. [Chipe1](https://github.com/aimacode/aima-python/issues/641) - [MrDupin](https://github.com/aimacode/aima-python/issues/632)
In general, the main ways you can contribute to the repository are the following:
1. Implement algorithms from the [list of algorithms](https://github.com/aimacode/aima-python/blob/master/README.md#index-of-algorithms).
1. Add tests for algorithms.
1. Take care of [issues](https://github.com/aimacode/aima-python/issues).
1. Write on the notebooks (`.ipynb` files).
1. Add and edit documentation (the docstrings in `.py` files).
In more detail:
## Read the Code and Start on an Issue
- First, read and understand the code to get a feel for the extent and the style.
- Look at the [issues](https://github.com/aimacode/aima-python/issues) and pick one to work on.
- One of the issues is that some algorithms are missing from the [list of algorithms](https://github.com/aimacode/aima-python/blob/master/README.md#index-of-algorithms) and that some don't have tests.
## Port to Python 3; Pythonic Idioms
- Check for common problems in [porting to Python 3](http://python3porting.com/problems.html), such as: `print` is now a function; `range` and `map` and other functions no longer produce `list`; objects of different types can no longer be compared with `<`; strings are now Unicode; it would be nice to move `%` string formatting to `.format`; there is a new `next` function for generators; integer division now returns a float; we can now use set literals.
- Replace old Lisp-based idioms with proper Python idioms. For example, we have many functions that were taken directly from Common Lisp, such as the `every` function: `every(callable, items)` returns true if every element of `items` is callable. This is good Lisp style, but good Python style would be to use `all` and a generator expression: `all(callable(f) for f in items)`. Eventually, fix all calls to these legacy Lisp functions and then remove the functions.
## New and Improved Algorithms
- Implement functions that were in the third edition of the book but were not yet implemented in the code. Check the [list of pseudocode algorithms (pdf)](https://github.com/aimacode/pseudocode/blob/master/aima3e-algorithms.pdf) to see what's missing.
- As we finish chapters for the new fourth edition, we will share the new pseudocode in the [`aima-pseudocode`](https://github.com/aimacode/aima-pseudocode) repository, and describe what changes are necessary.
We hope to have an `algorithm-name.md` file for each algorithm, eventually; it would be great if contributors could add some for the existing algorithms.
## Jupyter Notebooks
In this project we use Jupyter/IPython Notebooks to showcase the algorithms in the book. They serve as short tutorials on what the algorithms do, how they are implemented and how one can use them. To install Jupyter, you can follow the instructions [here](https://jupyter.org/install.html). These are some ways you can contribute to the notebooks:
- Proofread the notebooks for grammar mistakes, typos, or general errors.
- Move visualization and unrelated to the algorithm code from notebooks to `notebook.py` (a file used to store code for the notebooks, like visualization and other miscellaneous stuff). Make sure the notebooks still work and have their outputs showing!
- Replace the `%psource` magic notebook command with the function `psource` from `notebook.py` where needed. Examples where this is useful are a) when we want to show code for algorithm implementation and b) when we have consecutive cells with the magic keyword (in this case, if the code is large, it's best to leave the output hidden).
- Add the function `pseudocode(algorithm_name)` in algorithm sections. The function prints the pseudocode of the algorithm. You can see some example usage in [`knowledge.ipynb`](https://github.com/aimacode/aima-python/blob/master/knowledge.ipynb).
- Edit existing sections for algorithms to add more information and/or examples.
- Add visualizations for algorithms. The visualization code should go in `notebook.py` to keep things clean.
- Add new sections for algorithms not yet covered. The general format we use in the notebooks is the following: First start with an overview of the algorithm, printing the pseudocode and explaining how it works. Then, add some implementation details, including showing the code (using `psource`). Finally, add examples for the implementations, showing how the algorithms work. Don't fret with adding complex, real-world examples; the project is meant for educational purposes. You can of course choose another format if something better suits an algorithm.
Apart from the notebooks explaining how the algorithms work, we also have notebooks showcasing some indicative applications of the algorithms. These notebooks are in the `*_apps.ipynb` format. We aim to have an `apps` notebook for each module, so if you don't see one for the module you would like to contribute to, feel free to create it from scratch! In these notebooks we are looking for applications showing what the algorithms can do. The general format of these sections is this: Add a description of the problem you are trying to solve, then explain how you are going to solve it and finally provide your solution with examples. Note that any code you write should not require any external libraries apart from the ones already provided (like `matplotlib`).
# Style Guide
There are a few style rules that are unique to this project:
- The first rule is that the code should correspond directly to the pseudocode in the book. When possible this will be almost one-to-one, just allowing for the syntactic differences between Python and pseudocode, and for different library functions.
- Don't make a function more complicated than the pseudocode in the book, even if the complication would add a nice feature, or give an efficiency gain. Instead, remain faithful to the pseudocode, and if you must, add a new function (not in the book) with the added feature.
- I use functional programming (functions with no side effects) in many cases, but not exclusively (sometimes classes and/or functions with side effects are used). Let the book's pseudocode be the guide.
Beyond the above rules, we use [Pep 8](https://www.python.org/dev/peps/pep-0008), with a few minor exceptions:
- I have set `--max-line-length 100`, not 79.
- You don't need two spaces after a sentence-ending period.
- Strunk and White is [not a good guide for English](http://chronicle.com/article/50-Years-of-Stupid-Grammar/25497).
- I prefer more concise docstrings; I don't follow [Pep 257](https://www.python.org/dev/peps/pep-0257/). In most cases,
a one-line docstring suffices. It is rarely necessary to list what each argument does; the name of the argument usually is enough.
- Not all constants have to be UPPERCASE.
- At some point I may add [Pep 484](https://www.python.org/dev/peps/pep-0484/) type annotations, but I think I'll hold off for now;
I want to get more experience with them, and some people may still be in Python 3.4.
Reporting Issues
================
- Under which versions of Python does this happen?
- Provide an example of the issue occurring.
- Is anybody working on this?
Patch Rules
===========
- Ensure that the patch is Python 3.4 compliant.
- Include tests if your patch is supposed to solve a bug, and explain
clearly under which circumstances the bug happens. Make sure the test fails
without your patch.
- Follow the style guidelines described above.
- Refer the issue you have fixed.
- Explain in brief what changes you have made with affected files name.
# Choice of Programming Languages
Are we right to concentrate on Java and Python versions of the code? I think so; both languages are popular; Java is
fast enough for our purposes, and has reasonable type declarations (but can be verbose); Python is popular and has a very direct mapping to the pseudocode in the book (but lacks type declarations and can be slow). The [TIOBE Index](http://www.tiobe.com/tiobe_index) says the top seven most popular languages, in order, are:
Java, C, C++, C#, Python, PHP, Javascript
So it might be reasonable to also support C++/C# at some point in the future. It might also be reasonable to support a language that combines the terse readability of Python with the type safety and speed of Java; perhaps Go or Julia. I see no reason to support PHP. Javascript is the language of the browser; it would be nice to have code that runs in the browser without need for any downloads; this would be in Javascript or a variant such as Typescript.
There is also a `aima-lisp` project; in 1995 when we wrote the first edition of the book, Lisp was the right choice, but today it is less popular (currently #31 on the TIOBE index).
What languages are instructors recommending for their AI class? To get an approximate idea, I gave the query <tt>[\[norvig russell "Modern Approach"\]](https://www.google.com/webhp#q=russell%20norvig%20%22modern%20approach%22%20java)</tt> along with the names of various languages and looked at the estimated counts of results on
various dates. However, I don't have much confidence in these figures...
|Language |2004 |2005 |2007 |2010 |2016 |
|-------- |----: |----: |----: |----: |----: |
|[none](http://www.google.com/search?q=norvig+russell+%22Modern+Approach%22)|8,080|20,100|75,200|150,000|132,000|
|[java](http://www.google.com/search?q=java+norvig+russell+%22Modern+Approach%22)|1,990|4,930|44,200|37,000|50,000|
|[c++](http://www.google.com/search?q=c%2B%2B+norvig+russell+%22Modern+Approach%22)|875|1,820|35,300|105,000|35,000|
|[lisp](http://www.google.com/search?q=lisp+norvig+russell+%22Modern+Approach%22)|844|974|30,100|19,000|14,000|
|[prolog](http://www.google.com/search?q=prolog+norvig+russell+%22Modern+Approach%22)|789|2,010|23,200|17,000|16,000|
|[python](http://www.google.com/search?q=python+norvig+russell+%22Modern+Approach%22)|785|1,240|18,400|11,000|12,000|
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2016 aima-python contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
# `aima-python` [](https://travis-ci.org/aimacode/aima-python) [](http://mybinder.org/repo/aimacode/aima-python)
Python code for the book *[Artificial Intelligence: A Modern Approach](http://aima.cs.berkeley.edu).* You can use this in conjunction with a course on AI, or for study on your own. We're looking for [solid contributors](https://github.com/aimacode/aima-python/blob/master/CONTRIBUTING.md) to help.
# Updates for 4th Edition
The 4th edition of the book as out now in 2020, and thus we are updating the code. All code here will reflect the 4th edition. Changes include:
- Move from Python 3.5 to 3.7.
- More emphasis on Jupyter (Ipython) notebooks.
- More projects using external packages (tensorflow, etc.).
# Structure of the Project
When complete, this project will have Python implementations for all the pseudocode algorithms in the book, as well as tests and examples of use. For each major topic, such as `search`, we provide the following files:
- `search.ipynb` and `search.py`: Implementations of all the pseudocode algorithms, and necessary support functions/classes/data. The `.py` file is generated automatically from the `.ipynb` file; the idea is that it is easier to read the documentation in the `.ipynb` file.
- `search_XX.ipynb`: Notebooks that show how to use the code, broken out into various topics (the `XX`).
- `tests/test_search.py`: A lightweight test suite, using `assert` statements, designed for use with [`py.test`](http://pytest.org/latest/), but also usable on their own.
# Python 3.7 and up
The code for the 3rd edition was in Python 3.5; the current 4th edition code is in Python 3.7. It should also run in later versions, but does not run in Python 2. You can [install Python](https://www.python.org/downloads) or use a browser-based Python interpreter such as [repl.it](https://repl.it/languages/python3).
You can run the code in an IDE, or from the command line with `python -i filename.py` where the `-i` option puts you in an interactive loop where you can run Python functions. All notebooks are available in a [binder environment](http://mybinder.org/repo/aimacode/aima-python). Alternatively, visit [jupyter.org](http://jupyter.org/) for instructions on setting up your own Jupyter notebook environment.
Features from Python 3.6 and 3.7 that we will be using for this version of the code:
- [f-strings](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep498): all string formatting should be done with `f'var = {var}'`, not with `'var = {}'.format(var)` nor `'var = %s' % var`.
- [`typing` module](https://docs.python.org/3.7/library/typing.html): declare functions with type hints: `def successors(state) -> List[State]:`; that is, give type declarations, but omit them when it is obvious. I don't need to say `state: State`, but in another context it would make sense to say `s: State`.
- Underscores in numerics: write a million as `1_000_000` not as `1000000`.
- [`dataclasses` module](https://docs.python.org/3.7/library/dataclasses.html#module-dataclasses): replace `namedtuple` with `dataclass`.
[//]: # (There is a sibling [aima-docker]https://github.com/rajatjain1997/aima-docker project that shows you how to use docker containers to run more complex problems in more complex software environments.)
## Installation Guide
To download the repository:
`git clone https://github.com/aimacode/aima-python.git`
Then you need to install the basic dependencies to run the project on your system:
```
cd aima-python
pip install -r requirements.txt
```
You also need to fetch the datasets from the [`aima-data`](https://github.com/aimacode/aima-data) repository:
```
git submodule init
git submodule update
```
Wait for the datasets to download, it may take a while. Once they are downloaded, you need to install `pytest`, so that you can run the test suite:
`pip install pytest`
Then to run the tests:
`py.test`
And you are good to go!
# Index of Algorithms
Here is a table of algorithms, the figure, name of the algorithm in the book and in the repository, and the file where they are implemented in the repository. This chart was made for the third edition of the book and is being updated for the upcoming fourth edition. Empty implementations are a good place for contributors to look for an issue. The [aima-pseudocode](https://github.com/aimacode/aima-pseudocode) project describes all the algorithms from the book. An asterisk next to the file name denotes the algorithm is not fully implemented. Another great place for contributors to start is by adding tests and writing on the notebooks. You can see which algorithms have tests and notebook sections below. If the algorithm you want to work on is covered, don't worry! You can still add more tests and provide some examples of use in the notebook!
| **Figure** | **Name (in 3<sup>rd</sup> edition)** | **Name (in repository)** | **File** | **Tests** | **Notebook**
|:-------|:----------------------------------|:------------------------------|:--------------------------------|:-----|:---------|
| 2 | Random-Vacuum-Agent | `RandomVacuumAgent` | [`agents.py`][agents] | Done | Included |
| 2 | Model-Based-Vacuum-Agent | `ModelBasedVacuumAgent` | [`agents.py`][agents] | Done | Included |
| 2.1 | Environment | `Environment` | [`agents.py`][agents] | Done | Included |
| 2.1 | Agent | `Agent` | [`agents.py`][agents] | Done | Included |
| 2.3 | Table-Driven-Vacuum-Agent | `TableDrivenVacuumAgent` | [`agents.py`][agents] | Done | Included |
| 2.7 | Table-Driven-Agent | `TableDrivenAgent` | [`agents.py`][agents] | Done | Included |
| 2.8 | Reflex-Vacuum-Agent | `ReflexVacuumAgent` | [`agents.py`][agents] | Done | Included |
| 2.10 | Simple-Reflex-Agent | `SimpleReflexAgent` | [`agents.py`][agents] | Done | Included |
| 2.12 | Model-Based-Reflex-Agent | `ReflexAgentWithState` | [`agents.py`][agents] | Done | Included |
| 3 | Problem | `Problem` | [`search.py`][search] | Done | Included |
| 3 | Node | `Node` | [`search.py`][search] | Done | Included |
| 3 | Queue | `Queue` | [`utils.py`][utils] | Done | No Need |
| 3.1 | Simple-Problem-Solving-Agent | `SimpleProblemSolvingAgent` | [`search.py`][search] | Done | Included |
| 3.2 | Romania | `romania` | [`search.py`][search] | Done | Included |
| 3.7 | Tree-Search | `depth/breadth_first_tree_search` | [`search.py`][search] | Done | Included |
| 3.7 | Graph-Search | `depth/breadth_first_graph_search` | [`search.py`][search] | Done | Included |
| 3.11 | Breadth-First-Search | `breadth_first_graph_search` | [`search.py`][search] | Done | Included |
| 3.14 | Uniform-Cost-Search | `uniform_cost_search` | [`search.py`][search] | Done | Included |
| 3.17 | Depth-Limited-Search | `depth_limited_search` | [`search.py`][search] | Done | Included |
| 3.18 | Iterative-Deepening-Search | `iterative_deepening_search` | [`search.py`][search] | Done | Included |
| 3.22 | Best-First-Search | `best_first_graph_search` | [`search.py`][search] | Done | Included |
| 3.24 | A\*-Search | `astar_search` | [`search.py`][search] | Done | Included |
| 3.26 | Recursive-Best-First-Search | `recursive_best_first_search` | [`search.py`][search] | Done | Included |
| 4.2 | Hill-Climbing | `hill_climbing` | [`search.py`][search] | Done | Included |
| 4.5 | Simulated-Annealing | `simulated_annealing` | [`search.py`][search] | Done | Included |
| 4.8 | Genetic-Algorithm | `genetic_algorithm` | [`search.py`][search] | Done | Included |
| 4.11 | And-Or-Graph-Search | `and_or_graph_search` | [`search.py`][search] | Done | Included |
| 4.21 | Online-DFS-Agent | `online_dfs_agent` | [`search.py`][search] | Done | Included |
| 4.24 | LRTA\*-Agent | `LRTAStarAgent` | [`search.py`][search] | Done | Included |
| 5.3 | Minimax-Decision | `minimax_decision` | [`games.py`][games] | Done | Included |
| 5.7 | Alpha-Beta-Search | `alphabeta_search` | [`games.py`][games] | Done | Included |
| 6 | CSP | `CSP` | [`csp.py`][csp] | Done | Included |
| 6.3 | AC-3 | `AC3` | [`csp.py`][csp] | Done | Included |
| 6.5 | Backtracking-Search | `backtracking_search` | [`csp.py`][csp] | Done | Included |
| 6.8 | Min-Conflicts | `min_conflicts` | [`csp.py`][csp] | Done | Included |
| 6.11 | Tree-CSP-Solver | `tree_csp_solver` | [`csp.py`][csp] | Done | Included |
| 7 | KB | `KB` | [`logic.py`][logic] | Done | Included |
| 7.1 | KB-Agent | `KB_AgentProgram` | [`logic.py`][logic] | Done | Included |
| 7.7 | Propositional Logic Sentence | `Expr` | [`utils.py`][utils] | Done | Included |
| 7.10 | TT-Entails | `tt_entails` | [`logic.py`][logic] | Done | Included |
| 7.12 | PL-Resolution | `pl_resolution` | [`logic.py`][logic] | Done | Included |
| 7.14 | Convert to CNF | `to_cnf` | [`logic.py`][logic] | Done | Included |
| 7.15 | PL-FC-Entails? | `pl_fc_entails` | [`logic.py`][logic] | Done | Included |
| 7.17 | DPLL-Satisfiable? | `dpll_satisfiable` | [`logic.py`][logic] | Done | Included |
| 7.18 | WalkSAT | `WalkSAT` | [`logic.py`][logic] | Done | Included |
| 7.20 | Hybrid-Wumpus-Agent | `HybridWumpusAgent` | | | |
| 7.22 | SATPlan | `SAT_plan` | [`logic.py`][logic] | Done | Included |
| 9 | Subst | `subst` | [`logic.py`][logic] | Done | Included |
| 9.1 | Unify | `unify` | [`logic.py`][logic] | Done | Included |
| 9.3 | FOL-FC-Ask | `fol_fc_ask` | [`logic.py`][logic] | Done | Included |
| 9.6 | FOL-BC-Ask | `fol_bc_ask` | [`logic.py`][logic] | Done | Included |
| 10.1 | Air-Cargo-problem | `air_cargo` | [`planning.py`][planning] | Done | Included |
| 10.2 | Spare-Tire-Problem | `spare_tire` | [`planning.py`][planning] | Done | Included |
| 10.3 | Three-Block-Tower | `three_block_tower` | [`planning.py`][planning] | Done | Included |
| 10.7 | Cake-Problem | `have_cake_and_eat_cake_too` | [`planning.py`][planning] | Done | Included |
| 10.9 | Graphplan | `GraphPlan` | [`planning.py`][planning] | Done | Included |
| 10.13 | Partial-Order-Planner | `PartialOrderPlanner` | [`planning.py`][planning] | Done | Included |
| 11.1 | Job-Shop-Problem-With-Resources | `job_shop_problem` | [`planning.py`][planning] | Done | Included |
| 11.5 | Hierarchical-Search | `hierarchical_search` | [`planning.py`][planning] | Done | Included |
| 11.8 | Angelic-Search | `angelic_search` | [`planning.py`][planning] | Done | Included |
| 11.10 | Doubles-tennis | `double_tennis_problem` | [`planning.py`][planning] | Done | Included |
| 13 | Discrete Probability Distribution | `ProbDist` | [`probability.py`][probability] | Done | Included |
| 13.1 | DT-Agent | `DTAgent` | [`probability.py`][probability] | Done | Included |
| 14.9 | Enumeration-Ask | `enumeration_ask` | [`probability.py`][probability] | Done | Included |
| 14.11 | Elimination-Ask | `elimination_ask` | [`probability.py`][probability] | Done | Included |
| 14.13 | Prior-Sample | `prior_sample` | [`probability.py`][probability] | Done | Included |
| 14.14 | Rejection-Sampling | `rejection_sampling` | [`probability.py`][probability] | Done | Included |
| 14.15 | Likelihood-Weighting | `likelihood_weighting` | [`probability.py`][probability] | Done | Included |
| 14.16 | Gibbs-Ask | `gibbs_ask` | [`probability.py`][probability] | Done | Included |
| 15.4 | Forward-Backward | `forward_backward` | [`probability.py`][probability] | Done | Included |
| 15.6 | Fixed-Lag-Smoothing | `fixed_lag_smoothing` | [`probability.py`][probability] | Done | Included |
| 15.17 | Particle-Filtering | `particle_filtering` | [`probability.py`][probability] | Done | Included |
| 16.9 | Information-Gathering-Agent | `InformationGatheringAgent` | [`probability.py`][probability] | Done | Included |
| 17.4 | Value-Iteration | `value_iteration` | [`mdp.py`][mdp] | Done | Included |
| 17.7 | Policy-Iteration | `policy_iteration` | [`mdp.py`][mdp] | Done | Included |
| 17.9 | POMDP-Value-Iteration | `pomdp_value_iteration` | [`mdp.py`][mdp] | Done | Included |
| 18.5 | Decision-Tree-Learning | `DecisionTreeLearner` | [`learning.py`][learning] | Done | Included |
| 18.8 | Cross-Validation | `cross_validation` | [`learning.py`][learning]\* | | |
| 18.11 | Decision-List-Learning | `DecisionListLearner` | [`learning.py`][learning]\* | | |
| 18.24 | Back-Prop-Learning | `BackPropagationLearner` | [`learning.py`][learning] | Done | Included |
| 18.34 | AdaBoost | `AdaBoost` | [`learning.py`][learning] | Done | Included |
| 19.2 | Current-Best-Learning | `current_best_learning` | [`knowledge.py`](knowledge.py) | Done | Included |
| 19.3 | Version-Space-Learning | `version_space_learning` | [`knowledge.py`](knowledge.py) | Done | Included |
| 19.8 | Minimal-Consistent-Det | `minimal_consistent_det` | [`knowledge.py`](knowledge.py) | Done | Included |
| 19.12 | FOIL | `FOIL_container` | [`knowledge.py`](knowledge.py) | Done | Included |
| 21.2 | Passive-ADP-Agent | `PassiveADPAgent` | [`rl.py`][rl] | Done | Included |
| 21.4 | Passive-TD-Agent | `PassiveTDAgent` | [`rl.py`][rl] | Done | Included |
| 21.8 | Q-Learning-Agent | `QLearningAgent` | [`rl.py`][rl] | Done | Included |
| 22.1 | HITS | `HITS` | [`nlp.py`][nlp] | Done | Included |
| 23 | Chart-Parse | `Chart` | [`nlp.py`][nlp] | Done | Included |
| 23.5 | CYK-Parse | `CYK_parse` | [`nlp.py`][nlp] | Done | Included |
| 25.9 | Monte-Carlo-Localization | `monte_carlo_localization` | [`probability.py`][probability] | Done | Included |
# Index of data structures
Here is a table of the implemented data structures, the figure, name of the implementation in the repository, and the file where they are implemented.
| **Figure** | **Name (in repository)** | **File** |
|:-------|:--------------------------------|:--------------------------|
| 3.2 | romania_map | [`search.py`][search] |
| 4.9 | vacumm_world | [`search.py`][search] |
| 4.23 | one_dim_state_space | [`search.py`][search] |
| 6.1 | australia_map | [`search.py`][search] |
| 7.13 | wumpus_world_inference | [`logic.py`][logic] |
| 7.16 | horn_clauses_KB | [`logic.py`][logic] |
| 17.1 | sequential_decision_environment | [`mdp.py`][mdp] |
| 18.2 | waiting_decision_tree | [`learning.py`][learning] |
# Acknowledgements
Many thanks for contributions over the years. I got bug reports, corrected code, and other support from Darius Bacon, Phil Ruggera, Peng Shao, Amit Patil, Ted Nienstedt, Jim Martin, Ben Catanzariti, and others. Now that the project is on GitHub, you can see the [contributors](https://github.com/aimacode/aima-python/graphs/contributors) who are doing a great job of actively improving the project. Many thanks to all contributors, especially [@darius](https://github.com/darius), [@SnShine](https://github.com/SnShine), [@reachtarunhere](https://github.com/reachtarunhere), [@antmarakis](https://github.com/antmarakis), [@Chipe1](https://github.com/Chipe1), [@ad71](https://github.com/ad71) and [@MariannaSpyrakou](https://github.com/MariannaSpyrakou).
<!---Reference Links-->
[agents]:../master/agents.py
[csp]:../master/csp.py
[games]:../master/games.py
[grid]:../master/grid.py
[knowledge]:../master/knowledge.py
[learning]:../master/learning.py
[logic]:../master/logic.py
[mdp]:../master/mdp.py
[nlp]:../master/nlp.py
[planning]:../master/planning.py
[probability]:../master/probability.py
[rl]:../master/rl.py
[search]:../master/search.py
[utils]:../master/utils.py
[text]:../master/text.py
================================================
FILE: SUBMODULE.md
================================================
This is a guide on how to update the `aima-data` submodule to the latest version. This needs to be done every time something changes in the [aima-data](https://github.com/aimacode/aima-data) repository. All the below commands should be executed from the local directory of the `aima-python` repository, using `git`.
```
git submodule deinit aima-data
git rm aima-data
git submodule add https://github.com/aimacode/aima-data.git aima-data
git commit
git push origin
```
Then you need to pull request the changes (unless you are a collaborator, in which case you can commit directly to the master).
================================================
FILE: agents.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Intelligent Agents #\n",
"\n",
"This notebook serves as supporting material for topics covered in **Chapter 2 - Intelligent Agents** from the book *Artificial Intelligence: A Modern Approach.* This notebook uses implementations from [agents.py](https://github.com/aimacode/aima-python/blob/master/agents.py) module. Let's start by importing everything from agents module."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from agents import *\n",
"from notebook import psource"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CONTENTS\n",
"\n",
"* Overview\n",
"* Agent\n",
"* Environment\n",
"* Simple Agent and Environment\n",
"* Agents in a 2-D Environment\n",
"* Wumpus Environment\n",
"\n",
"## OVERVIEW\n",
"\n",
"An agent, as defined in 2.1, is anything that can perceive its <b>environment</b> through sensors, and act upon that environment through actuators based on its <b>agent program</b>. This can be a dog, a robot, or even you. As long as you can perceive the environment and act on it, you are an agent. This notebook will explain how to implement a simple agent, create an environment, and implement a program that helps the agent act on the environment based on its percepts.\n",
"\n",
"## AGENT\n",
"\n",
"Let us now see how we define an agent. Run the next cell to see how `Agent` is defined in agents module."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"psource(Agent)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `Agent` has two methods.\n",
"* `__init__(self, program=None)`: The constructor defines various attributes of the Agent. These include\n",
"\n",
" * `alive`: which keeps track of whether the agent is alive or not \n",
" \n",
" * `bump`: which tracks if the agent collides with an edge of the environment (for eg, a wall in a park)\n",
" \n",
" * `holding`: which is a list containing the `Things` an agent is holding, \n",
" \n",
" * `performance`: which evaluates the performance metrics of the agent \n",
" \n",
" * `program`: which is the agent program and maps an agent's percepts to actions in the environment. If no implementation is provided, it defaults to asking the user to provide actions for each percept.\n",
" \n",
"* `can_grab(self, thing)`: Is used when an environment contains things that an agent can grab and carry. By default, an agent can carry nothing.\n",
"\n",
"## ENVIRONMENT\n",
"Now, let us see how environments are defined. Running the next cell will display an implementation of the abstract `Environment` class."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"psource(Environment)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`Environment` class has lot of methods! But most of them are incredibly simple, so let's see the ones we'll be using in this notebook.\n",
"\n",
"* `thing_classes(self)`: Returns a static array of `Thing` sub-classes that determine what things are allowed in the environment and what aren't\n",
"\n",
"* `add_thing(self, thing, location=None)`: Adds a thing to the environment at location\n",
"\n",
"* `run(self, steps)`: Runs an environment with the agent in it for a given number of steps.\n",
"\n",
"* `is_done(self)`: Returns true if the objective of the agent and the environment has been completed\n",
"\n",
"The next two functions must be implemented by each subclasses of `Environment` for the agent to recieve percepts and execute actions \n",
"\n",
"* `percept(self, agent)`: Given an agent, this method returns a list of percepts that the agent sees at the current time\n",
"\n",
"* `execute_action(self, agent, action)`: The environment reacts to an action performed by a given agent. The changes may result in agent experiencing new percepts or other elements reacting to agent input."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## SIMPLE AGENT AND ENVIRONMENT\n",
"\n",
"Let's begin by using the `Agent` class to creating our first agent - a blind dog."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class BlindDog(Agent):\n",
" def eat(self, thing):\n",
" print(\"Dog: Ate food at {}.\".format(self.location))\n",
" \n",
" def drink(self, thing):\n",
" print(\"Dog: Drank water at {}.\".format( self.location))\n",
"\n",
"dog = BlindDog()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What we have just done is create a dog who can only feel what's in his location (since he's blind), and can eat or drink. Let's see if he's alive..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(dog.alive)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"This is our dog. How cool is he? Well, he's hungry and needs to go search for food. For him to do this, we need to give him a program. But before that, let's create a park for our dog to play in."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### ENVIRONMENT - Park\n",
"\n",
"A park is an example of an environment because our dog can perceive and act upon it. The <b>Environment</b> class is an abstract class, so we will have to create our own subclass from it before we can use it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Food(Thing):\n",
" pass\n",
"\n",
"class Water(Thing):\n",
" pass\n",
"\n",
"class Park(Environment):\n",
" def percept(self, agent):\n",
" '''return a list of things that are in our agent's location'''\n",
" things = self.list_things_at(agent.location)\n",
" return things\n",
" \n",
" def execute_action(self, agent, action):\n",
" '''changes the state of the environment based on what the agent does.'''\n",
" if action == \"move down\":\n",
" print('{} decided to {} at location: {}'.format(str(agent)[1:-1], action, agent.location))\n",
" agent.movedown()\n",
" elif action == \"eat\":\n",
" items = self.list_things_at(agent.location, tclass=Food)\n",
" if len(items) != 0:\n",
" if agent.eat(items[0]): #Have the dog eat the first item\n",
" print('{} ate {} at location: {}'\n",
" .format(str(agent)[1:-1], str(items[0])[1:-1], agent.location))\n",
" self.delete_thing(items[0]) #Delete it from the Park after.\n",
" elif action == \"drink\":\n",
" items = self.list_things_at(agent.location, tclass=Water)\n",
" if len(items) != 0:\n",
" if agent.drink(items[0]): #Have the dog drink the first item\n",
" print('{} drank {} at location: {}'\n",
" .format(str(agent)[1:-1], str(items[0])[1:-1], agent.location))\n",
" self.delete_thing(items[0]) #Delete it from the Park after.\n",
"\n",
" def is_done(self):\n",
" '''By default, we're done when we can't find a live agent, \n",
" but to prevent killing our cute dog, we will stop before itself - when there is no more food or water'''\n",
" no_edibles = not any(isinstance(thing, Food) or isinstance(thing, Water) for thing in self.things)\n",
" dead_agents = not any(agent.is_alive() for agent in self.agents)\n",
" return dead_agents or no_edibles\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### PROGRAM - BlindDog\n",
"Now that we have a <b>Park</b> Class, we re-implement our <b>BlindDog</b> to be able to move down and eat food or drink water only if it is present.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class BlindDog(Agent):\n",
" location = 1\n",
" \n",
" def movedown(self):\n",
" self.location += 1\n",
" \n",
" def eat(self, thing):\n",
" '''returns True upon success or False otherwise'''\n",
" if isinstance(thing, Food):\n",
" return True\n",
" return False\n",
" \n",
" def drink(self, thing):\n",
" ''' returns True upon success or False otherwise'''\n",
" if isinstance(thing, Water):\n",
" return True\n",
" return False"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now its time to implement a <b>program</b> module for our dog. A program controls how the dog acts upon its environment. Our program will be very simple, and is shown in the table below.\n",
"<table>\n",
" <tr>\n",
" <td><b>Percept:</b> </td>\n",
" <td>Feel Food </td>\n",
" <td>Feel Water</td>\n",
" <td>Feel Nothing</td>\n",
" </tr>\n",
" <tr>\n",
" <td><b>Action:</b> </td>\n",
" <td>eat</td>\n",
" <td>drink</td>\n",
" <td>move down</td>\n",
" </tr>\n",
" \n",
"</table>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def program(percepts):\n",
" '''Returns an action based on the dog's percepts'''\n",
" for p in percepts:\n",
" if isinstance(p, Food):\n",
" return 'eat'\n",
" elif isinstance(p, Water):\n",
" return 'drink'\n",
" return 'move down'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's now run our simulation by creating a park with some food, water, and our dog."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"park = Park()\n",
"dog = BlindDog(program)\n",
"dogfood = Food()\n",
"water = Water()\n",
"park.add_thing(dog, 1)\n",
"park.add_thing(dogfood, 5)\n",
"park.add_thing(water, 7)\n",
"\n",
"park.run(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that the dog moved from location 1 to 4, over 4 steps, and ate food at location 5 in the 5th step.\n",
"\n",
"Let's continue this simulation for 5 more steps."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"park.run(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Perfect! Note how the simulation stopped after the dog drank the water - exhausting all the food and water ends our simulation, as we had defined before. Let's add some more water and see if our dog can reach it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"park.add_thing(water, 15)\n",
"park.run(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Above, we learnt to implement an agent, its program, and an environment on which it acts. However, this was a very simple case. Let's try to add complexity to it by creating a 2-Dimensional environment!\n",
"\n",
"\n",
"## AGENTS IN A 2D ENVIRONMENT\n",
"\n",
"For us to not read so many logs of what our dog did, we add a bit of graphics while making our Park 2D. To do so, we will need to make it a subclass of <b>GraphicEnvironment</b> instead of Environment. Parks implemented by subclassing <b>GraphicEnvironment</b> class adds these extra properties to it:\n",
"\n",
" - Our park is indexed in the 4th quadrant of the X-Y plane.\n",
" - Every time we create a park subclassing <b>GraphicEnvironment</b>, we need to define the colors of all the things we plan to put into the park. The colors are defined in typical [<b>RGB digital 8-bit format</b>](https://en.wikipedia.org/wiki/RGB_color_model#Numeric_representations), common across the web.\n",
" - Fences are added automatically to all parks so that our dog does not go outside the park's boundary - it just isn't safe for blind dogs to be outside the park by themselves! <b>GraphicEnvironment</b> provides `is_inbounds` function to check if our dog tries to leave the park.\n",
" \n",
"First let us try to upgrade our 1-dimensional `Park` environment by just replacing its superclass by `GraphicEnvironment`. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Park2D(GraphicEnvironment):\n",
" def percept(self, agent):\n",
" '''return a list of things that are in our agent's location'''\n",
" things = self.list_things_at(agent.location)\n",
" return things\n",
" \n",
" def execute_action(self, agent, action):\n",
" '''changes the state of the environment based on what the agent does.'''\n",
" if action == \"move down\":\n",
" print('{} decided to {} at location: {}'.format(str(agent)[1:-1], action, agent.location))\n",
" agent.movedown()\n",
" elif action == \"eat\":\n",
" items = self.list_things_at(agent.location, tclass=Food)\n",
" if len(items) != 0:\n",
" if agent.eat(items[0]): #Have the dog eat the first item\n",
" print('{} ate {} at location: {}'\n",
" .format(str(agent)[1:-1], str(items[0])[1:-1], agent.location))\n",
" self.delete_thing(items[0]) #Delete it from the Park after.\n",
" elif action == \"drink\":\n",
" items = self.list_things_at(agent.location, tclass=Water)\n",
" if len(items) != 0:\n",
" if agent.drink(items[0]): #Have the dog drink the first item\n",
" print('{} drank {} at location: {}'\n",
" .format(str(agent)[1:-1], str(items[0])[1:-1], agent.location))\n",
" self.delete_thing(items[0]) #Delete it from the Park after.\n",
" \n",
" def is_done(self):\n",
" '''By default, we're done when we can't find a live agent, \n",
" but to prevent killing our cute dog, we will stop before itself - when there is no more food or water'''\n",
" no_edibles = not any(isinstance(thing, Food) or isinstance(thing, Water) for thing in self.things)\n",
" dead_agents = not any(agent.is_alive() for agent in self.agents)\n",
" return dead_agents or no_edibles\n",
"\n",
"class BlindDog(Agent):\n",
" location = [0,1] # change location to a 2d value\n",
" direction = Direction(\"down\") # variable to store the direction our dog is facing\n",
" \n",
" def movedown(self):\n",
" self.location[1] += 1\n",
" \n",
" def eat(self, thing):\n",
" '''returns True upon success or False otherwise'''\n",
" if isinstance(thing, Food):\n",
" return True\n",
" return False\n",
" \n",
" def drink(self, thing):\n",
" ''' returns True upon success or False otherwise'''\n",
" if isinstance(thing, Water):\n",
" return True\n",
" return False"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's test this new park with our same dog, food and water. We color our dog with a nice red and mark food and water with orange and blue respectively."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"park = Park2D(5,20, color={'BlindDog': (200,0,0), 'Water': (0, 200, 200), 'Food': (230, 115, 40)}) # park width is set to 5, and height to 20\n",
"dog = BlindDog(program)\n",
"dogfood = Food()\n",
"water = Water()\n",
"park.add_thing(dog, [0,1])\n",
"park.add_thing(dogfood, [0,5])\n",
"park.add_thing(water, [0,7])\n",
"morewater = Water()\n",
"park.add_thing(morewater, [0,15])\n",
"print(\"BlindDog starts at (1,1) facing downwards, lets see if he can find any food!\")\n",
"park.run(20)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Adding some graphics was a good idea! We immediately see that the code works, but our blind dog doesn't make any use of the 2 dimensional space available to him. Let's make our dog more energetic so that he turns and moves forward, instead of always moving down. In doing so, we'll also need to make some changes to our environment to be able to handle this extra motion.\n",
"\n",
"### PROGRAM - EnergeticBlindDog\n",
"\n",
"Let's make our dog turn or move forwards at random - except when he's at the edge of our park - in which case we make him change his direction explicitly by turning to avoid trying to leave the park. However, our dog is blind so he wouldn't know which way to turn - he'd just have to try arbitrarily.\n",
"\n",
"<table>\n",
" <tr>\n",
" <td><b>Percept:</b> </td>\n",
" <td>Feel Food </td>\n",
" <td>Feel Water</td>\n",
" <td>Feel Nothing</td>\n",
" </tr>\n",
" <tr>\n",
" <td><b>Action:</b> </td>\n",
" <td>eat</td>\n",
" <td>drink</td>\n",
" <td>\n",
" <table>\n",
" <tr>\n",
" <td><b>Remember being at Edge : </b></td>\n",
" <td>At Edge</td>\n",
" <td>Not at Edge</td>\n",
" </tr>\n",
" <tr>\n",
" <td><b>Action : </b></td>\n",
" <td>Turn Left / Turn Right <br> ( 50% - 50% chance )</td>\n",
" <td>Turn Left / Turn Right / Move Forward <br> ( 25% - 25% - 50% chance )</td>\n",
" </tr>\n",
" </table>\n",
" </td>\n",
" </tr>\n",
" \n",
"</table>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from random import choice\n",
"\n",
"class EnergeticBlindDog(Agent):\n",
" location = [0,1]\n",
" direction = Direction(\"down\")\n",
" \n",
" def moveforward(self, success=True):\n",
" '''moveforward possible only if success (i.e. valid destination location)'''\n",
" if not success:\n",
" return\n",
" if self.direction.direction == Direction.R:\n",
" self.location[0] += 1\n",
" elif self.direction.direction == Direction.L:\n",
" self.location[0] -= 1\n",
" elif self.direction.direction == Direction.D:\n",
" self.location[1] += 1\n",
" elif self.direction.direction == Direction.U:\n",
" self.location[1] -= 1\n",
" \n",
" def turn(self, d):\n",
" self.direction = self.direction + d\n",
" \n",
" def eat(self, thing):\n",
" '''returns True upon success or False otherwise'''\n",
" if isinstance(thing, Food):\n",
" return True\n",
" return False\n",
" \n",
" def drink(self, thing):\n",
" ''' returns True upon success or False otherwise'''\n",
" if isinstance(thing, Water):\n",
" return True\n",
" return False\n",
" \n",
"def program(percepts):\n",
" '''Returns an action based on it's percepts'''\n",
" \n",
" for p in percepts: # first eat or drink - you're a dog!\n",
" if isinstance(p, Food):\n",
" return 'eat'\n",
" elif isinstance(p, Water):\n",
" return 'drink'\n",
" if isinstance(p,Bump): # then check if you are at an edge and have to turn\n",
" turn = False\n",
" choice = random.choice((1,2));\n",
" else:\n",
" choice = random.choice((1,2,3,4)) # 1-right, 2-left, others-forward\n",
" if choice == 1:\n",
" return 'turnright'\n",
" elif choice == 2:\n",
" return 'turnleft'\n",
" else:\n",
" return 'moveforward'\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### ENVIRONMENT - Park2D\n",
"\n",
"We also need to modify our park accordingly, in order to be able to handle all the new actions our dog wishes to execute. Additionally, we'll need to prevent our dog from moving to locations beyond our park boundary - it just isn't safe for blind dogs to be outside the park by themselves."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class Park2D(GraphicEnvironment):\n",
" def percept(self, agent):\n",
" '''return a list of things that are in our agent's location'''\n",
" things = self.list_things_at(agent.location)\n",
" loc = copy.deepcopy(agent.location) # find out the target location\n",
" #Check if agent is about to bump into a wall\n",
" if agent.direction.direction == Direction.R:\n",
" loc[0] += 1\n",
" elif agent.direction.direction == Direction.L:\n",
" loc[0] -= 1\n",
" elif agent.direction.direction == Direction.D:\n",
" loc[1] += 1\n",
" elif agent.direction.direction == Direction.U:\n",
" loc[1] -= 1\n",
" if not self.is_inbounds(loc):\n",
" things.append(Bump())\n",
" return things\n",
" \n",
" def execute_action(self, agent, action):\n",
" '''changes the state of the environment based on what the agent does.'''\n",
" if action == 'turnright':\n",
" print('{} decided to {} at location: {}'.format(str(agent)[1:-1], action, agent.location))\n",
" agent.turn(Direction.R)\n",
" elif action == 'turnleft':\n",
" print('{} decided to {} at location: {}'.format(str(agent)[1:-1], action, agent.location))\n",
" agent.turn(Direction.L)\n",
" elif action == 'moveforward':\n",
" print('{} decided to move {}wards at location: {}'.format(str(agent)[1:-1], agent.direction.direction, agent.location))\n",
" agent.moveforward()\n",
" elif action == \"eat\":\n",
" items = self.list_things_at(agent.location, tclass=Food)\n",
" if len(items) != 0:\n",
" if agent.eat(items[0]):\n",
" print('{} ate {} at location: {}'\n",
" .format(str(agent)[1:-1], str(items[0])[1:-1], agent.location))\n",
" self.delete_thing(items[0])\n",
" elif action == \"drink\":\n",
" items = self.list_things_at(agent.location, tclass=Water)\n",
" if len(items) != 0:\n",
" if agent.drink(items[0]):\n",
" print('{} drank {} at location: {}'\n",
" .format(str(agent)[1:-1], str(items[0])[1:-1], agent.location))\n",
" self.delete_thing(items[0])\n",
" \n",
" def is_done(self):\n",
" '''By default, we're done when we can't find a live agent, \n",
" but to prevent killing our cute dog, we will stop before itself - when there is no more food or water'''\n",
" no_edibles = not any(isinstance(thing, Food) or isinstance(thing, Water) for thing in self.things)\n",
" dead_agents = not any(agent.is_alive() for agent in self.agents)\n",
" return dead_agents or no_edibles\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that our park is ready for the 2D motion of our energetic dog, lets test it!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"park = Park2D(5,5, color={'EnergeticBlindDog': (200,0,0), 'Water': (0, 200, 200), 'Food': (230, 115, 40)})\n",
"dog = EnergeticBlindDog(program)\n",
"dogfood = Food()\n",
"water = Water()\n",
"park.add_thing(dog, [0,0])\n",
"park.add_thing(dogfood, [1,2])\n",
"park.add_thing(water, [0,1])\n",
"morewater = Water()\n",
"morefood = Food()\n",
"park.add_thing(morewater, [2,4])\n",
"park.add_thing(morefood, [4,3])\n",
"print(\"dog started at [0,0], facing down. Let's see if he found any food or water!\")\n",
"park.run(20)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Wumpus Environment"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from ipythonblocks import BlockGrid\n",
"from agents import *\n",
"\n",
"color = {\"Breeze\": (225, 225, 225),\n",
" \"Pit\": (0,0,0),\n",
" \"Gold\": (253, 208, 23),\n",
" \"Glitter\": (253, 208, 23),\n",
" \"Wumpus\": (43, 27, 23),\n",
" \"Stench\": (128, 128, 128),\n",
" \"Explorer\": (0, 0, 255),\n",
" \"Wall\": (44, 53, 57)\n",
" }\n",
"\n",
"def program(percepts):\n",
" '''Returns an action based on it's percepts'''\n",
" print(percepts)\n",
" return input()\n",
"\n",
"w = WumpusEnvironment(program, 7, 7) \n",
"grid = BlockGrid(w.width, w.height, fill=(123, 234, 123))\n",
"\n",
"def draw_grid(world):\n",
" global grid\n",
" grid[:] = (123, 234, 123)\n",
" for x in range(0, len(world)):\n",
" for y in range(0, len(world[x])):\n",
" if len(world[x][y]):\n",
" grid[y, x] = color[world[x][y][-1].__class__.__name__]\n",
"\n",
"def step():\n",
" global grid, w\n",
" draw_grid(w.get_world())\n",
" grid.show()\n",
" w.step()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"step()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
================================================
FILE: agents.py
================================================
"""
Implement Agents and Environments. (Chapters 1-2)
The class hierarchies are as follows:
Thing ## A physical object that can exist in an environment
Agent
Wumpus
Dirt
Wall
...
Environment ## An environment holds objects, runs simulations
XYEnvironment
VacuumEnvironment
WumpusEnvironment
An agent program is a callable instance, taking percepts and choosing actions
SimpleReflexAgentProgram
...
EnvGUI ## A window with a graphical representation of the Environment
EnvToolbar ## contains buttons for controlling EnvGUI
EnvCanvas ## Canvas to display the environment of an EnvGUI
"""
# TODO
# Speed control in GUI does not have any effect -- fix it.
from utils import distance_squared, turn_heading
from statistics import mean
from ipythonblocks import BlockGrid
from IPython.display import HTML, display, clear_output
from time import sleep
import random
import copy
import collections
import numbers
# ______________________________________________________________________________
class Thing:
"""This represents any physical object that can appear in an Environment.
You subclass Thing to get the things you want. Each thing can have a
.__name__ slot (used for output only)."""
def __repr__(self):
return '<{}>'.format(getattr(self, '__name__', self.__class__.__name__))
def is_alive(self):
"""Things that are 'alive' should return true."""
return hasattr(self, 'alive') and self.alive
def show_state(self):
"""Display the agent's internal state. Subclasses should override."""
print("I don't know how to show_state.")
def display(self, canvas, x, y, width, height):
"""Display an image of this Thing on the canvas."""
# Do we need this?
pass
class Agent(Thing):
"""An Agent is a subclass of Thing with one required instance attribute
(aka slot), .program, which should hold a function that takes one argument,
the percept, and returns an action. (What counts as a percept or action
will depend on the specific environment in which the agent exists.)
Note that 'program' is a slot, not a method. If it were a method, then the
program could 'cheat' and look at aspects of the agent. It's not supposed
to do that: the program can only look at the percepts. An agent program
that needs a model of the world (and of the agent itself) will have to
build and maintain its own model. There is an optional slot, .performance,
which is a number giving the performance measure of the agent in its
environment."""
def __init__(self, program=None):
self.alive = True
self.bump = False
self.holding = []
self.performance = 0
if program is None or not isinstance(program, collections.abc.Callable):
print("Can't find a valid program for {}, falling back to default.".format(self.__class__.__name__))
def program(percept):
return eval(input('Percept={}; action? '.format(percept)))
self.program = program
def can_grab(self, thing):
"""Return True if this agent can grab this thing.
Override for appropriate subclasses of Agent and Thing."""
return False
def TraceAgent(agent):
"""Wrap the agent's program to print its input and output. This will let
you see what the agent is doing in the environment."""
old_program = agent.program
def new_program(percept):
action = old_program(percept)
print('{} perceives {} and does {}'.format(agent, percept, action))
return action
agent.program = new_program
return agent
# ______________________________________________________________________________
def TableDrivenAgentProgram(table):
"""
[Figure 2.7]
This agent selects an action based on the percept sequence.
It is practical only for tiny domains.
To customize it, provide as table a dictionary of all
{percept_sequence:action} pairs.
"""
percepts = []
def program(percept):
percepts.append(percept)
action = table.get(tuple(percepts))
return action
return program
def RandomAgentProgram(actions):
"""An agent that chooses an action at random, ignoring all percepts.
>>> list = ['Right', 'Left', 'Suck', 'NoOp']
>>> program = RandomAgentProgram(list)
>>> agent = Agent(program)
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1, 0): 'Clean' , (0, 0): 'Clean'}
True
"""
return lambda percept: random.choice(actions)
# ______________________________________________________________________________
def SimpleReflexAgentProgram(rules, interpret_input):
"""
[Figure 2.10]
This agent takes action based solely on the percept.
"""
def program(percept):
state = interpret_input(percept)
rule = rule_match(state, rules)
action = rule.action
return action
return program
def ModelBasedReflexAgentProgram(rules, update_state, model):
"""
[Figure 2.12]
This agent takes action based on the percept and state.
"""
def program(percept):
program.state = update_state(program.state, program.action, percept, model)
rule = rule_match(program.state, rules)
action = rule.action
return action
program.state = program.action = None
return program
def rule_match(state, rules):
"""Find the first rule that matches state."""
for rule in rules:
if rule.matches(state):
return rule
# ______________________________________________________________________________
loc_A, loc_B = (0, 0), (1, 0) # The two locations for the Vacuum world
def RandomVacuumAgent():
"""Randomly choose one of the actions from the vacuum environment.
>>> agent = RandomVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
return Agent(RandomAgentProgram(['Right', 'Left', 'Suck', 'NoOp']))
def TableDrivenVacuumAgent():
"""Tabular approach towards vacuum world as mentioned in [Figure 2.3]
>>> agent = TableDrivenVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
table = {((loc_A, 'Clean'),): 'Right',
((loc_A, 'Dirty'),): 'Suck',
((loc_B, 'Clean'),): 'Left',
((loc_B, 'Dirty'),): 'Suck',
((loc_A, 'Dirty'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_B, 'Dirty')): 'Suck',
((loc_B, 'Clean'), (loc_A, 'Dirty')): 'Suck',
((loc_B, 'Dirty'), (loc_B, 'Clean')): 'Left',
((loc_A, 'Dirty'), (loc_A, 'Clean'), (loc_B, 'Dirty')): 'Suck',
((loc_B, 'Dirty'), (loc_B, 'Clean'), (loc_A, 'Dirty')): 'Suck'}
return Agent(TableDrivenAgentProgram(table))
def ReflexVacuumAgent():
"""
[Figure 2.8]
A reflex agent for the two-state vacuum environment.
>>> agent = ReflexVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
def program(percept):
location, status = percept
if status == 'Dirty':
return 'Suck'
elif location == loc_A:
return 'Right'
elif location == loc_B:
return 'Left'
return Agent(program)
def ModelBasedVacuumAgent():
"""An agent that keeps track of what locations are clean or dirty.
>>> agent = ModelBasedVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
model = {loc_A: None, loc_B: None}
def program(percept):
"""Same as ReflexVacuumAgent, except if everything is clean, do NoOp."""
location, status = percept
model[location] = status # Update the model here
if model[loc_A] == model[loc_B] == 'Clean':
return 'NoOp'
elif status == 'Dirty':
return 'Suck'
elif location == loc_A:
return 'Right'
elif location == loc_B:
return 'Left'
return Agent(program)
# ______________________________________________________________________________
class Environment:
"""Abstract class representing an Environment. 'Real' Environment classes
inherit from this. Your Environment will typically need to implement:
percept: Define the percept that an agent sees.
execute_action: Define the effects of executing an action.
Also update the agent.performance slot.
The environment keeps a list of .things and .agents (which is a subset
of .things). Each agent has a .performance slot, initialized to 0.
Each thing has a .location slot, even though some environments may not
need this."""
def __init__(self):
self.things = []
self.agents = []
def thing_classes(self):
return [] # List of classes that can go into environment
def percept(self, agent):
"""Return the percept that the agent sees at this point. (Implement this.)"""
raise NotImplementedError
def execute_action(self, agent, action):
"""Change the world to reflect this action. (Implement this.)"""
raise NotImplementedError
def default_location(self, thing):
"""Default location to place a new thing with unspecified location."""
return None
def exogenous_change(self):
"""If there is spontaneous change in the world, override this."""
pass
def is_done(self):
"""By default, we're done when we can't find a live agent."""
return not any(agent.is_alive() for agent in self.agents)
def step(self):
"""Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method."""
if not self.is_done():
actions = []
for agent in self.agents:
if agent.alive:
actions.append(agent.program(self.percept(agent)))
else:
actions.append("")
for (agent, action) in zip(self.agents, actions):
self.execute_action(agent, action)
self.exogenous_change()
def run(self, steps=1000):
"""Run the Environment for given number of time steps."""
for step in range(steps):
if self.is_done():
return
self.step()
def list_things_at(self, location, tclass=Thing):
"""Return all things exactly at a given location."""
if isinstance(location, numbers.Number):
return [thing for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
return [thing for thing in self.things
if all(x == y for x, y in zip(thing.location, location)) and isinstance(thing, tclass)]
def some_things_at(self, location, tclass=Thing):
"""Return true if at least one of the things at location
is an instance of class tclass (or a subclass)."""
return self.list_things_at(location, tclass) != []
def add_thing(self, thing, location=None):
"""Add a thing to the environment, setting its location. For
convenience, if thing is an agent program we make a new agent
for it. (Shouldn't need to override this.)"""
if not isinstance(thing, Thing):
thing = Agent(thing)
if thing in self.things:
print("Can't add the same thing twice")
else:
thing.location = location if location is not None else self.default_location(thing)
self.things.append(thing)
if isinstance(thing, Agent):
thing.performance = 0
self.agents.append(thing)
def delete_thing(self, thing):
"""Remove a thing from the environment."""
try:
self.things.remove(thing)
except ValueError as e:
print(e)
print(" in Environment delete_thing")
print(" Thing to be removed: {} at {}".format(thing, thing.location))
print(" from list: {}".format([(thing, thing.location) for thing in self.things]))
if thing in self.agents:
self.agents.remove(thing)
class Direction:
"""A direction class for agents that want to move in a 2D plane
Usage:
d = Direction("down")
To change directions:
d = d + "right" or d = d + Direction.R #Both do the same thing
Note that the argument to __add__ must be a string and not a Direction object.
Also, it (the argument) can only be right or left."""
R = "right"
L = "left"
U = "up"
D = "down"
def __init__(self, direction):
self.direction = direction
def __add__(self, heading):
"""
>>> d = Direction('right')
>>> l1 = d.__add__(Direction.L)
>>> l2 = d.__add__(Direction.R)
>>> l1.direction
'up'
>>> l2.direction
'down'
>>> d = Direction('down')
>>> l1 = d.__add__('right')
>>> l2 = d.__add__('left')
>>> l1.direction == Direction.L
True
>>> l2.direction == Direction.R
True
"""
if self.direction == self.R:
return {
self.R: Direction(self.D),
self.L: Direction(self.U),
}.get(heading, None)
elif self.direction == self.L:
return {
self.R: Direction(self.U),
self.L: Direction(self.D),
}.get(heading, None)
elif self.direction == self.U:
return {
self.R: Direction(self.R),
self.L: Direction(self.L),
}.get(heading, None)
elif self.direction == self.D:
return {
self.R: Direction(self.L),
self.L: Direction(self.R),
}.get(heading, None)
def move_forward(self, from_location):
"""
>>> d = Direction('up')
>>> l1 = d.move_forward((0, 0))
>>> l1
(0, -1)
>>> d = Direction(Direction.R)
>>> l1 = d.move_forward((0, 0))
>>> l1
(1, 0)
"""
# get the iterable class to return
iclass = from_location.__class__
x, y = from_location
if self.direction == self.R:
return iclass((x + 1, y))
elif self.direction == self.L:
return iclass((x - 1, y))
elif self.direction == self.U:
return iclass((x, y - 1))
elif self.direction == self.D:
return iclass((x, y + 1))
class XYEnvironment(Environment):
"""This class is for environments on a 2D plane, with locations
labelled by (x, y) points, either discrete or continuous.
Agents perceive things within a radius. Each agent in the
environment has a .location slot which should be a location such
as (0, 1), and a .holding slot, which should be a list of things
that are held."""
def __init__(self, width=10, height=10):
super().__init__()
self.width = width
self.height = height
self.observers = []
# Sets iteration start and end (no walls).
self.x_start, self.y_start = (0, 0)
self.x_end, self.y_end = (self.width, self.height)
perceptible_distance = 1
def things_near(self, location, radius=None):
"""Return all things within radius of location."""
if radius is None:
radius = self.perceptible_distance
radius2 = radius * radius
return [(thing, radius2 - distance_squared(location, thing.location))
for thing in self.things if distance_squared(
location, thing.location) <= radius2]
def percept(self, agent):
"""By default, agent perceives things within a default radius."""
return self.things_near(agent.location)
def execute_action(self, agent, action):
agent.bump = False
if action == 'TurnRight':
agent.direction += Direction.R
elif action == 'TurnLeft':
agent.direction += Direction.L
elif action == 'Forward':
agent.bump = self.move_to(agent, agent.direction.move_forward(agent.location))
elif action == 'Grab':
things = [thing for thing in self.list_things_at(agent.location) if agent.can_grab(thing)]
if things:
agent.holding.append(things[0])
print("Grabbing ", things[0].__class__.__name__)
self.delete_thing(things[0])
elif action == 'Release':
if agent.holding:
dropped = agent.holding.pop()
print("Dropping ", dropped.__class__.__name__)
self.add_thing(dropped, location=agent.location)
def default_location(self, thing):
location = self.random_location_inbounds()
while self.some_things_at(location, Obstacle):
# we will find a random location with no obstacles
location = self.random_location_inbounds()
return location
def move_to(self, thing, destination):
"""Move a thing to a new location. Returns True on success or False if there is an Obstacle.
If thing is holding anything, they move with him."""
thing.bump = self.some_things_at(destination, Obstacle)
if not thing.bump:
thing.location = destination
for o in self.observers:
o.thing_moved(thing)
for t in thing.holding:
self.delete_thing(t)
self.add_thing(t, destination)
t.location = destination
return thing.bump
def add_thing(self, thing, location=None, exclude_duplicate_class_items=False):
"""Add things to the world. If (exclude_duplicate_class_items) then the item won't be
added if the location has at least one item of the same class."""
if location is None:
super().add_thing(thing)
elif self.is_inbounds(location):
if (exclude_duplicate_class_items and
any(isinstance(t, thing.__class__) for t in self.list_things_at(location))):
return
super().add_thing(thing, location)
def is_inbounds(self, location):
"""Checks to make sure that the location is inbounds (within walls if we have walls)"""
x, y = location
return not (x < self.x_start or x > self.x_end or y < self.y_start or y > self.y_end)
def random_location_inbounds(self, exclude=None):
"""Returns a random location that is inbounds (within walls if we have walls)"""
location = (random.randint(self.x_start, self.x_end),
random.randint(self.y_start, self.y_end))
if exclude is not None:
while location == exclude:
location = (random.randint(self.x_start, self.x_end),
random.randint(self.y_start, self.y_end))
return location
def delete_thing(self, thing):
"""Deletes thing, and everything it is holding (if thing is an agent)"""
if isinstance(thing, Agent):
del thing.holding
super().delete_thing(thing)
for obs in self.observers:
obs.thing_deleted(thing)
def add_walls(self):
"""Put walls around the entire perimeter of the grid."""
for x in range(self.width):
self.add_thing(Wall(), (x, 0))
self.add_thing(Wall(), (x, self.height - 1))
for y in range(1, self.height - 1):
self.add_thing(Wall(), (0, y))
self.add_thing(Wall(), (self.width - 1, y))
# Updates iteration start and end (with walls).
self.x_start, self.y_start = (1, 1)
self.x_end, self.y_end = (self.width - 1, self.height - 1)
def add_observer(self, observer):
"""Adds an observer to the list of observers.
An observer is typically an EnvGUI.
Each observer is notified of changes in move_to and add_thing,
by calling the observer's methods thing_moved(thing)
and thing_added(thing, loc)."""
self.observers.append(observer)
def turn_heading(self, heading, inc):
"""Return the heading to the left (inc=+1) or right (inc=-1) of heading."""
return turn_heading(heading, inc)
class Obstacle(Thing):
"""Something that can cause a bump, preventing an agent from
moving into the same square it's in."""
pass
class Wall(Obstacle):
pass
# ______________________________________________________________________________
class GraphicEnvironment(XYEnvironment):
def __init__(self, width=10, height=10, boundary=True, color={}, display=False):
"""Define all the usual XYEnvironment characteristics,
but initialise a BlockGrid for GUI too."""
super().__init__(width, height)
self.grid = BlockGrid(width, height, fill=(200, 200, 200))
if display:
self.grid.show()
self.visible = True
else:
self.visible = False
self.bounded = boundary
self.colors = color
def get_world(self):
"""Returns all the items in the world in a format
understandable by the ipythonblocks BlockGrid."""
result = []
x_start, y_start = (0, 0)
x_end, y_end = self.width, self.height
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x, y)))
result.append(row)
return result
"""
def run(self, steps=1000, delay=1):
"" "Run the Environment for given number of time steps,
but update the GUI too." ""
for step in range(steps):
sleep(delay)
if self.visible:
self.reveal()
if self.is_done():
if self.visible:
self.reveal()
return
self.step()
if self.visible:
self.reveal()
"""
def run(self, steps=1000, delay=1):
"""Run the Environment for given number of time steps,
but update the GUI too."""
for step in range(steps):
self.update(delay)
if self.is_done():
break
self.step()
self.update(delay)
def update(self, delay=1):
sleep(delay)
self.reveal()
def reveal(self):
"""Display the BlockGrid for this world - the last thing to be added
at a location defines the location color."""
self.draw_world()
# wait for the world to update and
# apply changes to the same grid instead
# of making a new one.
clear_output(1)
self.grid.show()
self.visible = True
def draw_world(self):
self.grid[:] = (200, 200, 200)
world = self.get_world()
for x in range(0, len(world)):
for y in range(0, len(world[x])):
if len(world[x][y]):
self.grid[y, x] = self.colors[world[x][y][-1].__class__.__name__]
def conceal(self):
"""Hide the BlockGrid for this world"""
self.visible = False
display(HTML(''))
# ______________________________________________________________________________
# Continuous environment
class ContinuousWorld(Environment):
"""Model for Continuous World"""
def __init__(self, width=10, height=10):
super().__init__()
self.width = width
self.height = height
def add_obstacle(self, coordinates):
self.things.append(PolygonObstacle(coordinates))
class PolygonObstacle(Obstacle):
def __init__(self, coordinates):
"""Coordinates is a list of tuples."""
super().__init__()
self.coordinates = coordinates
# ______________________________________________________________________________
# Vacuum environment
class Dirt(Thing):
pass
class VacuumEnvironment(XYEnvironment):
"""The environment of [Ex. 2.12]. Agent perceives dirty or clean,
and bump (into obstacle) or not; 2D discrete world of unknown size;
performance measure is 100 for each dirt cleaned, and -1 for
each turn taken."""
def __init__(self, width=10, height=10):
super().__init__(width, height)
self.add_walls()
def thing_classes(self):
return [Wall, Dirt, ReflexVacuumAgent, RandomVacuumAgent,
TableDrivenVacuumAgent, ModelBasedVacuumAgent]
def percept(self, agent):
"""The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None').
Unlike the TrivialVacuumEnvironment, location is NOT perceived."""
status = ('Dirty' if self.some_things_at(
agent.location, Dirt) else 'Clean')
bump = ('Bump' if agent.bump else 'None')
return status, bump
def execute_action(self, agent, action):
agent.bump = False
if action == 'Suck':
dirt_list = self.list_things_at(agent.location, Dirt)
if dirt_list != []:
dirt = dirt_list[0]
agent.performance += 100
self.delete_thing(dirt)
else:
super().execute_action(agent, action)
if action != 'NoOp':
agent.performance -= 1
class TrivialVacuumEnvironment(Environment):
"""This environment has two locations, A and B. Each can be Dirty
or Clean. The agent perceives its location and the location's
status. This serves as an example of how to implement a simple
Environment."""
def __init__(self):
super().__init__()
self.status = {loc_A: random.choice(['Clean', 'Dirty']),
loc_B: random.choice(['Clean', 'Dirty'])}
def thing_classes(self):
return [Wall, Dirt, ReflexVacuumAgent, RandomVacuumAgent, TableDrivenVacuumAgent, ModelBasedVacuumAgent]
def percept(self, agent):
"""Returns the agent's location, and the location status (Dirty/Clean)."""
return agent.location, self.status[agent.location]
def execute_action(self, agent, action):
"""Change agent's location and/or location's status; track performance.
Score 10 for each dirt cleaned; -1 for each move."""
if action == 'Right':
agent.location = loc_B
agent.performance -= 1
elif action == 'Left':
agent.location = loc_A
agent.performance -= 1
elif action == 'Suck':
if self.status[agent.location] == 'Dirty':
agent.performance += 10
self.status[agent.location] = 'Clean'
def default_location(self, thing):
"""Agents start in either location at random."""
return random.choice([loc_A, loc_B])
# ______________________________________________________________________________
# The Wumpus World
class Gold(Thing):
def __eq__(self, rhs):
"""All Gold are equal"""
return rhs.__class__ == Gold
pass
class Bump(Thing):
pass
class Glitter(Thing):
pass
class Pit(Thing):
pass
class Breeze(Thing):
pass
class Arrow(Thing):
pass
class Scream(Thing):
pass
class Wumpus(Agent):
screamed = False
pass
class Stench(Thing):
pass
class Explorer(Agent):
holding = []
has_arrow = True
killed_by = ""
direction = Direction("right")
def can_grab(self, thing):
"""Explorer can only grab gold"""
return thing.__class__ == Gold
class WumpusEnvironment(XYEnvironment):
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
# Room should be 4x4 grid of rooms. The extra 2 for walls
def __init__(self, agent_program, width=6, height=6):
super().__init__(width, height)
self.init_world(agent_program)
def init_world(self, program):
"""Spawn items in the world based on probabilities from the book"""
"WALLS"
self.add_walls()
"PITS"
for x in range(self.x_start, self.x_end):
for y in range(self.y_start, self.y_end):
if random.random() < self.pit_probability:
self.add_thing(Pit(), (x, y), True)
self.add_thing(Breeze(), (x - 1, y), True)
self.add_thing(Breeze(), (x, y - 1), True)
self.add_thing(Breeze(), (x + 1, y), True)
self.add_thing(Breeze(), (x, y + 1), True)
"WUMPUS"
w_x, w_y = self.random_location_inbounds(exclude=(1, 1))
self.add_thing(Wumpus(lambda x: ""), (w_x, w_y), True)
self.add_thing(Stench(), (w_x - 1, w_y), True)
self.add_thing(Stench(), (w_x + 1, w_y), True)
self.add_thing(Stench(), (w_x, w_y - 1), True)
self.add_thing(Stench(), (w_x, w_y + 1), True)
"GOLD"
self.add_thing(Gold(), self.random_location_inbounds(exclude=(1, 1)), True)
"AGENT"
self.add_thing(Explorer(program), (1, 1), True)
def get_world(self, show_walls=True):
"""Return the items in the world"""
result = []
x_start, y_start = (0, 0) if show_walls else (1, 1)
if show_walls:
x_end, y_end = self.width, self.height
else:
x_end, y_end = self.width - 1, self.height - 1
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x, y)))
result.append(row)
return result
def percepts_from(self, agent, location, tclass=Thing):
"""Return percepts from a given location,
and replaces some items with percepts from chapter 7."""
thing_percepts = {
Gold: Glitter(),
Wall: Bump(),
Wumpus: Stench(),
Pit: Breeze()}
"""Agents don't need to get their percepts"""
thing_percepts[agent.__class__] = None
"""Gold only glitters in its cell"""
if location != agent.location:
thing_percepts[Gold] = None
result = [thing_percepts.get(thing.__class__, thing) for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
return result if len(result) else [None]
def percept(self, agent):
"""Return things in adjacent (not diagonal) cells of the agent.
Result format: [Left, Right, Up, Down, Center / Current location]"""
x, y = agent.location
result = []
result.append(self.percepts_from(agent, (x - 1, y)))
result.append(self.percepts_from(agent, (x + 1, y)))
result.append(self.percepts_from(agent, (x, y - 1)))
result.append(self.percepts_from(agent, (x, y + 1)))
result.append(self.percepts_from(agent, (x, y)))
"""The wumpus gives out a loud scream once it's killed."""
wumpus = [thing for thing in self.things if isinstance(thing, Wumpus)]
if len(wumpus) and not wumpus[0].alive and not wumpus[0].screamed:
result[-1].append(Scream())
wumpus[0].screamed = True
return result
def execute_action(self, agent, action):
"""Modify the state of the environment based on the agent's actions.
Performance score taken directly out of the book."""
if isinstance(agent, Explorer) and self.in_danger(agent):
return
agent.bump = False
if action in ['TurnRight', 'TurnLeft', 'Forward', 'Grab']:
super().execute_action(agent, action)
agent.performance -= 1
elif action == 'Climb':
if agent.location == (1, 1): # Agent can only climb out of (1,1)
agent.performance += 1000 if Gold() in agent.holding else 0
self.delete_thing(agent)
elif action == 'Shoot':
"""The arrow travels straight down the path the agent is facing"""
if agent.has_arrow:
arrow_travel = agent.direction.move_forward(agent.location)
while self.is_inbounds(arrow_travel):
wumpus = [thing for thing in self.list_things_at(arrow_travel)
if isinstance(thing, Wumpus)]
if len(wumpus):
wumpus[0].alive = False
break
arrow_travel = agent.direction.move_forward(agent.location)
agent.has_arrow = False
def in_danger(self, agent):
"""Check if Explorer is in danger (Pit or Wumpus), if he is, kill him"""
for thing in self.list_things_at(agent.location):
if isinstance(thing, Pit) or (isinstance(thing, Wumpus) and thing.alive):
agent.alive = False
agent.performance -= 1000
agent.killed_by = thing.__class__.__name__
return True
return False
def is_done(self):
"""The game is over when the Explorer is killed
or if he climbs out of the cave only at (1,1)."""
explorer = [agent for agent in self.agents if isinstance(agent, Explorer)]
if len(explorer):
if explorer[0].alive:
return False
else:
print("Death by {} [-1000].".format(explorer[0].killed_by))
else:
print("Explorer climbed out {}."
.format("with Gold [+1000]!" if Gold() not in self.things else "without Gold [+0]"))
return True
# TODO: Arrow needs to be implemented
# ______________________________________________________________________________
def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
"""See how well each of several agents do in n instances of an environment.
Pass in a factory (constructor) for environments, and several for agents.
Create n instances of the environment, and run each agent in copies of
each one for steps. Return a list of (agent, average-score) tuples.
>>> environment = TrivialVacuumEnvironment
>>> agents = [ModelBasedVacuumAgent, ReflexVacuumAgent]
>>> result = compare_agents(environment, agents)
>>> performance_ModelBasedVacuumAgent = result[0][1]
>>> performance_ReflexVacuumAgent = result[1][1]
>>> performance_ReflexVacuumAgent <= performance_ModelBasedVacuumAgent
True
"""
envs = [EnvFactory() for i in range(n)]
return [(A, test_agent(A, steps, copy.deepcopy(envs)))
for A in AgentFactories]
def test_agent(AgentFactory, steps, envs):
"""Return the mean score of running an agent in each of the envs, for steps
>>> def constant_prog(percept):
... return percept
...
>>> agent = Agent(constant_prog)
>>> result = agent.program(5)
>>> result == 5
True
"""
def score(env):
agent = AgentFactory()
env.add_thing(agent)
env.run(steps)
return agent.performance
return mean(map(score, envs))
# _________________________________________________________________________
__doc__ += """
>>> a = ReflexVacuumAgent()
>>> a.program((loc_A, 'Clean'))
'Right'
>>> a.program((loc_B, 'Clean'))
'Left'
>>> a.program((loc_A, 'Dirty'))
'Suck'
>>> a.program((loc_A, 'Dirty'))
'Suck'
>>> e = TrivialVacuumEnvironment()
>>> e.add_thing(ModelBasedVacuumAgent())
>>> e.run(5)
"""
================================================
FILE: agents4e.py
================================================
"""
Implement Agents and Environments. (Chapters 1-2)
The class hierarchies are as follows:
Thing ## A physical object that can exist in an environment
Agent
Wumpus
Dirt
Wall
...
Environment ## An environment holds objects, runs simulations
XYEnvironment
VacuumEnvironment
WumpusEnvironment
An agent program is a callable instance, taking percepts and choosing actions
SimpleReflexAgentProgram
...
EnvGUI ## A window with a graphical representation of the Environment
EnvToolbar ## contains buttons for controlling EnvGUI
EnvCanvas ## Canvas to display the environment of an EnvGUI
"""
# TODO
# Implement grabbing correctly.
# When an object is grabbed, does it still have a location?
# What if it is released?
# What if the grabbed or the grabber is deleted?
# What if the grabber moves?
# Speed control in GUI does not have any effect -- fix it.
from utils4e import distance_squared, turn_heading
from statistics import mean
from ipythonblocks import BlockGrid
from IPython.display import HTML, display, clear_output
from time import sleep
import random
import copy
import collections
import numbers
# ______________________________________________________________________________
class Thing:
"""This represents any physical object that can appear in an Environment.
You subclass Thing to get the things you want. Each thing can have a
.__name__ slot (used for output only)."""
def __repr__(self):
return '<{}>'.format(getattr(self, '__name__', self.__class__.__name__))
def is_alive(self):
"""Things that are 'alive' should return true."""
return hasattr(self, 'alive') and self.alive
def show_state(self):
"""Display the agent's internal state. Subclasses should override."""
print("I don't know how to show_state.")
def display(self, canvas, x, y, width, height):
"""Display an image of this Thing on the canvas."""
# Do we need this?
pass
class Agent(Thing):
"""An Agent is a subclass of Thing with one required slot,
.program, which should hold a function that takes one argument, the
percept, and returns an action. (What counts as a percept or action
will depend on the specific environment in which the agent exists.)
Note that 'program' is a slot, not a method. If it were a method,
then the program could 'cheat' and look at aspects of the agent.
It's not supposed to do that: the program can only look at the
percepts. An agent program that needs a model of the world (and of
the agent itself) will have to build and maintain its own model.
There is an optional slot, .performance, which is a number giving
the performance measure of the agent in its environment."""
def __init__(self, program=None):
self.alive = True
self.bump = False
self.holding = []
self.performance = 0
if program is None or not isinstance(program, collections.abc.Callable):
print("Can't find a valid program for {}, falling back to default.".format(self.__class__.__name__))
def program(percept):
return eval(input('Percept={}; action? '.format(percept)))
self.program = program
def can_grab(self, thing):
"""Return True if this agent can grab this thing.
Override for appropriate subclasses of Agent and Thing."""
return False
def TraceAgent(agent):
"""Wrap the agent's program to print its input and output. This will let
you see what the agent is doing in the environment."""
old_program = agent.program
def new_program(percept):
action = old_program(percept)
print('{} perceives {} and does {}'.format(agent, percept, action))
return action
agent.program = new_program
return agent
# ______________________________________________________________________________
def TableDrivenAgentProgram(table):
"""
[Figure 2.7]
This agent selects an action based on the percept sequence.
It is practical only for tiny domains.
To customize it, provide as table a dictionary of all
{percept_sequence:action} pairs.
"""
percepts = []
def program(percept):
percepts.append(percept)
action = table.get(tuple(percepts))
return action
return program
def RandomAgentProgram(actions):
"""An agent that chooses an action at random, ignoring all percepts.
>>> list = ['Right', 'Left', 'Suck', 'NoOp']
>>> program = RandomAgentProgram(list)
>>> agent = Agent(program)
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1, 0): 'Clean' , (0, 0): 'Clean'}
True
"""
return lambda percept: random.choice(actions)
# ______________________________________________________________________________
def SimpleReflexAgentProgram(rules, interpret_input):
"""
[Figure 2.10]
This agent takes action based solely on the percept.
"""
def program(percept):
state = interpret_input(percept)
rule = rule_match(state, rules)
action = rule.action
return action
return program
def ModelBasedReflexAgentProgram(rules, update_state, transition_model, sensor_model):
"""
[Figure 2.12]
This agent takes action based on the percept and state.
"""
def program(percept):
program.state = update_state(program.state, program.action, percept, transition_model, sensor_model)
rule = rule_match(program.state, rules)
action = rule.action
return action
program.state = program.action = None
return program
def rule_match(state, rules):
"""Find the first rule that matches state."""
for rule in rules:
if rule.matches(state):
return rule
# ______________________________________________________________________________
loc_A, loc_B = (0, 0), (1, 0) # The two locations for the Vacuum world
def RandomVacuumAgent():
"""Randomly choose one of the actions from the vacuum environment.
>>> agent = RandomVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
return Agent(RandomAgentProgram(['Right', 'Left', 'Suck', 'NoOp']))
def TableDrivenVacuumAgent():
"""Tabular approach towards vacuum world as mentioned in [Figure 2.3]
>>> agent = TableDrivenVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
table = {((loc_A, 'Clean'),): 'Right',
((loc_A, 'Dirty'),): 'Suck',
((loc_B, 'Clean'),): 'Left',
((loc_B, 'Dirty'),): 'Suck',
((loc_A, 'Dirty'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_B, 'Dirty')): 'Suck',
((loc_B, 'Clean'), (loc_A, 'Dirty')): 'Suck',
((loc_B, 'Dirty'), (loc_B, 'Clean')): 'Left',
((loc_A, 'Dirty'), (loc_A, 'Clean'), (loc_B, 'Dirty')): 'Suck',
((loc_B, 'Dirty'), (loc_B, 'Clean'), (loc_A, 'Dirty')): 'Suck'}
return Agent(TableDrivenAgentProgram(table))
def ReflexVacuumAgent():
"""
[Figure 2.8]
A reflex agent for the two-state vacuum environment.
>>> agent = ReflexVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
def program(percept):
location, status = percept
if status == 'Dirty':
return 'Suck'
elif location == loc_A:
return 'Right'
elif location == loc_B:
return 'Left'
return Agent(program)
def ModelBasedVacuumAgent():
"""An agent that keeps track of what locations are clean or dirty.
>>> agent = ModelBasedVacuumAgent()
>>> environment = TrivialVacuumEnvironment()
>>> environment.add_thing(agent)
>>> environment.run()
>>> environment.status == {(1,0):'Clean' , (0,0) : 'Clean'}
True
"""
model = {loc_A: None, loc_B: None}
def program(percept):
"""Same as ReflexVacuumAgent, except if everything is clean, do NoOp."""
location, status = percept
model[location] = status # Update the model here
if model[loc_A] == model[loc_B] == 'Clean':
return 'NoOp'
elif status == 'Dirty':
return 'Suck'
elif location == loc_A:
return 'Right'
elif location == loc_B:
return 'Left'
return Agent(program)
# ______________________________________________________________________________
class Environment:
"""Abstract class representing an Environment. 'Real' Environment classes
inherit from this. Your Environment will typically need to implement:
percept: Define the percept that an agent sees.
execute_action: Define the effects of executing an action.
Also update the agent.performance slot.
The environment keeps a list of .things and .agents (which is a subset
of .things). Each agent has a .performance slot, initialized to 0.
Each thing has a .location slot, even though some environments may not
need this."""
def __init__(self):
self.things = []
self.agents = []
def thing_classes(self):
return [] # List of classes that can go into environment
def percept(self, agent):
"""Return the percept that the agent sees at this point. (Implement this.)"""
raise NotImplementedError
def execute_action(self, agent, action):
"""Change the world to reflect this action. (Implement this.)"""
raise NotImplementedError
def default_location(self, thing):
"""Default location to place a new thing with unspecified location."""
return None
def exogenous_change(self):
"""If there is spontaneous change in the world, override this."""
pass
def is_done(self):
"""By default, we're done when we can't find a live agent."""
return not any(agent.is_alive() for agent in self.agents)
def step(self):
"""Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method."""
if not self.is_done():
actions = []
for agent in self.agents:
if agent.alive:
actions.append(agent.program(self.percept(agent)))
else:
actions.append("")
for (agent, action) in zip(self.agents, actions):
self.execute_action(agent, action)
self.exogenous_change()
def run(self, steps=1000):
"""Run the Environment for given number of time steps."""
for step in range(steps):
if self.is_done():
return
self.step()
def list_things_at(self, location, tclass=Thing):
"""Return all things exactly at a given location."""
if isinstance(location, numbers.Number):
return [thing for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
return [thing for thing in self.things
if all(x == y for x, y in zip(thing.location, location)) and isinstance(thing, tclass)]
def some_things_at(self, location, tclass=Thing):
"""Return true if at least one of the things at location
is an instance of class tclass (or a subclass)."""
return self.list_things_at(location, tclass) != []
def add_thing(self, thing, location=None):
"""Add a thing to the environment, setting its location. For
convenience, if thing is an agent program we make a new agent
for it. (Shouldn't need to override this.)"""
if not isinstance(thing, Thing):
thing = Agent(thing)
if thing in self.things:
print("Can't add the same thing twice")
else:
thing.location = location if location is not None else self.default_location(thing)
self.things.append(thing)
if isinstance(thing, Agent):
thing.performance = 0
self.agents.append(thing)
def delete_thing(self, thing):
"""Remove a thing from the environment."""
try:
self.things.remove(thing)
except ValueError as e:
print(e)
print(" in Environment delete_thing")
print(" Thing to be removed: {} at {}".format(thing, thing.location))
print(" from list: {}".format([(thing, thing.location) for thing in self.things]))
if thing in self.agents:
self.agents.remove(thing)
class Direction:
"""A direction class for agents that want to move in a 2D plane
Usage:
d = Direction("down")
To change directions:
d = d + "right" or d = d + Direction.R #Both do the same thing
Note that the argument to __add__ must be a string and not a Direction object.
Also, it (the argument) can only be right or left."""
R = "right"
L = "left"
U = "up"
D = "down"
def __init__(self, direction):
self.direction = direction
def __add__(self, heading):
"""
>>> d = Direction('right')
>>> l1 = d.__add__(Direction.L)
>>> l2 = d.__add__(Direction.R)
>>> l1.direction
'up'
>>> l2.direction
'down'
>>> d = Direction('down')
>>> l1 = d.__add__('right')
>>> l2 = d.__add__('left')
>>> l1.direction == Direction.L
True
>>> l2.direction == Direction.R
True
"""
if self.direction == self.R:
return {
self.R: Direction(self.D),
self.L: Direction(self.U),
}.get(heading, None)
elif self.direction == self.L:
return {
self.R: Direction(self.U),
self.L: Direction(self.D),
}.get(heading, None)
elif self.direction == self.U:
return {
self.R: Direction(self.R),
self.L: Direction(self.L),
}.get(heading, None)
elif self.direction == self.D:
return {
self.R: Direction(self.L),
self.L: Direction(self.R),
}.get(heading, None)
def move_forward(self, from_location):
"""
>>> d = Direction('up')
>>> l1 = d.move_forward((0, 0))
>>> l1
(0, -1)
>>> d = Direction(Direction.R)
>>> l1 = d.move_forward((0, 0))
>>> l1
(1, 0)
"""
# get the iterable class to return
iclass = from_location.__class__
x, y = from_location
if self.direction == self.R:
return iclass((x + 1, y))
elif self.direction == self.L:
return iclass((x - 1, y))
elif self.direction == self.U:
return iclass((x, y - 1))
elif self.direction == self.D:
return iclass((x, y + 1))
class XYEnvironment(Environment):
"""This class is for environments on a 2D plane, with locations
labelled by (x, y) points, either discrete or continuous.
Agents perceive things within a radius. Each agent in the
environment has a .location slot which should be a location such
as (0, 1), and a .holding slot, which should be a list of things
that are held."""
def __init__(self, width=10, height=10):
super().__init__()
self.width = width
self.height = height
self.observers = []
# Sets iteration start and end (no walls).
self.x_start, self.y_start = (0, 0)
self.x_end, self.y_end = (self.width, self.height)
perceptible_distance = 1
def things_near(self, location, radius=None):
"""Return all things within radius of location."""
if radius is None:
radius = self.perceptible_distance
radius2 = radius * radius
return [(thing, radius2 - distance_squared(location, thing.location))
for thing in self.things if distance_squared(
location, thing.location) <= radius2]
def percept(self, agent):
"""By default, agent perceives things within a default radius."""
return self.things_near(agent.location)
def execute_action(self, agent, action):
agent.bump = False
if action == 'TurnRight':
agent.direction += Direction.R
elif action == 'TurnLeft':
agent.direction += Direction.L
elif action == 'Forward':
agent.bump = self.move_to(agent, agent.direction.move_forward(agent.location))
# elif action == 'Grab':
# things = [thing for thing in self.list_things_at(agent.location)
# if agent.can_grab(thing)]
# if things:
# agent.holding.append(things[0])
elif action == 'Release':
if agent.holding:
agent.holding.pop()
def default_location(self, thing):
location = self.random_location_inbounds()
while self.some_things_at(location, Obstacle):
# we will find a random location with no obstacles
location = self.random_location_inbounds()
return location
def move_to(self, thing, destination):
"""Move a thing to a new location. Returns True on success or False if there is an Obstacle.
If thing is holding anything, they move with him."""
thing.bump = self.some_things_at(destination, Obstacle)
if not thing.bump:
thing.location = destination
for o in self.observers:
o.thing_moved(thing)
for t in thing.holding:
self.delete_thing(t)
self.add_thing(t, destination)
t.location = destination
return thing.bump
def add_thing(self, thing, location=None, exclude_duplicate_class_items=False):
"""Add things to the world. If (exclude_duplicate_class_items) then the item won't be
added if the location has at least one item of the same class."""
if location is None:
super().add_thing(thing)
elif self.is_inbounds(location):
if (exclude_duplicate_class_items and
any(isinstance(t, thing.__class__) for t in self.list_things_at(location))):
return
super().add_thing(thing, location)
def is_inbounds(self, location):
"""Checks to make sure that the location is inbounds (within walls if we have walls)"""
x, y = location
return not (x < self.x_start or x > self.x_end or y < self.y_start or y > self.y_end)
def random_location_inbounds(self, exclude=None):
"""Returns a random location that is inbounds (within walls if we have walls)"""
location = (random.randint(self.x_start, self.x_end),
random.randint(self.y_start, self.y_end))
if exclude is not None:
while location == exclude:
location = (random.randint(self.x_start, self.x_end),
random.randint(self.y_start, self.y_end))
return location
def delete_thing(self, thing):
"""Deletes thing, and everything it is holding (if thing is an agent)"""
if isinstance(thing, Agent):
for obj in thing.holding:
super().delete_thing(obj)
for obs in self.observers:
obs.thing_deleted(obj)
super().delete_thing(thing)
for obs in self.observers:
obs.thing_deleted(thing)
def add_walls(self):
"""Put walls around the entire perimeter of the grid."""
for x in range(self.width):
self.add_thing(Wall(), (x, 0))
self.add_thing(Wall(), (x, self.height - 1))
for y in range(1, self.height - 1):
self.add_thing(Wall(), (0, y))
self.add_thing(Wall(), (self.width - 1, y))
# Updates iteration start and end (with walls).
self.x_start, self.y_start = (1, 1)
self.x_end, self.y_end = (self.width - 1, self.height - 1)
def add_observer(self, observer):
"""Adds an observer to the list of observers.
An observer is typically an EnvGUI.
Each observer is notified of changes in move_to and add_thing,
by calling the observer's methods thing_moved(thing)
and thing_added(thing, loc)."""
self.observers.append(observer)
def turn_heading(self, heading, inc):
"""Return the heading to the left (inc=+1) or right (inc=-1) of heading."""
return turn_heading(heading, inc)
class Obstacle(Thing):
"""Something that can cause a bump, preventing an agent from
moving into the same square it's in."""
pass
class Wall(Obstacle):
pass
# ______________________________________________________________________________
class GraphicEnvironment(XYEnvironment):
def __init__(self, width=10, height=10, boundary=True, color={}, display=False):
"""Define all the usual XYEnvironment characteristics,
but initialise a BlockGrid for GUI too."""
super().__init__(width, height)
self.grid = BlockGrid(width, height, fill=(200, 200, 200))
if display:
self.grid.show()
self.visible = True
else:
self.visible = False
self.bounded = boundary
self.colors = color
def get_world(self):
"""Returns all the items in the world in a format
understandable by the ipythonblocks BlockGrid."""
result = []
x_start, y_start = (0, 0)
x_end, y_end = self.width, self.height
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x, y)))
result.append(row)
return result
"""
def run(self, steps=1000, delay=1):
"" "Run the Environment for given number of time steps,
but update the GUI too." ""
for step in range(steps):
sleep(delay)
if self.visible:
self.reveal()
if self.is_done():
if self.visible:
self.reveal()
return
self.step()
if self.visible:
self.reveal()
"""
def run(self, steps=1000, delay=1):
"""Run the Environment for given number of time steps,
but update the GUI too."""
for step in range(steps):
self.update(delay)
if self.is_done():
break
self.step()
self.update(delay)
def update(self, delay=1):
sleep(delay)
self.reveal()
def reveal(self):
"""Display the BlockGrid for this world - the last thing to be added
at a location defines the location color."""
self.draw_world()
# wait for the world to update and
# apply changes to the same grid instead
# of making a new one.
clear_output(1)
self.grid.show()
self.visible = True
def draw_world(self):
self.grid[:] = (200, 200, 200)
world = self.get_world()
for x in range(0, len(world)):
for y in range(0, len(world[x])):
if len(world[x][y]):
self.grid[y, x] = self.colors[world[x][y][-1].__class__.__name__]
def conceal(self):
"""Hide the BlockGrid for this world"""
self.visible = False
display(HTML(''))
# ______________________________________________________________________________
# Continuous environment
class ContinuousWorld(Environment):
"""Model for Continuous World"""
def __init__(self, width=10, height=10):
super().__init__()
self.width = width
self.height = height
def add_obstacle(self, coordinates):
self.things.append(PolygonObstacle(coordinates))
class PolygonObstacle(Obstacle):
def __init__(self, coordinates):
"""Coordinates is a list of tuples."""
super().__init__()
self.coordinates = coordinates
# ______________________________________________________________________________
# Vacuum environment
class Dirt(Thing):
pass
class VacuumEnvironment(XYEnvironment):
"""The environment of [Ex. 2.12]. Agent perceives dirty or clean,
and bump (into obstacle) or not; 2D discrete world of unknown size;
performance measure is 100 for each dirt cleaned, and -1 for
each turn taken."""
def __init__(self, width=10, height=10):
super().__init__(width, height)
self.add_walls()
def thing_classes(self):
return [Wall, Dirt, ReflexVacuumAgent, RandomVacuumAgent,
TableDrivenVacuumAgent, ModelBasedVacuumAgent]
def percept(self, agent):
"""The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None').
Unlike the TrivialVacuumEnvironment, location is NOT perceived."""
status = ('Dirty' if self.some_things_at(
agent.location, Dirt) else 'Clean')
bump = ('Bump' if agent.bump else 'None')
return status, bump
def execute_action(self, agent, action):
agent.bump = False
if action == 'Suck':
dirt_list = self.list_things_at(agent.location, Dirt)
if dirt_list != []:
dirt = dirt_list[0]
agent.performance += 100
self.delete_thing(dirt)
else:
super().execute_action(agent, action)
if action != 'NoOp':
agent.performance -= 1
class TrivialVacuumEnvironment(Environment):
"""This environment has two locations, A and B. Each can be Dirty
or Clean. The agent perceives its location and the location's
status. This serves as an example of how to implement a simple
Environment."""
def __init__(self):
super().__init__()
self.status = {loc_A: random.choice(['Clean', 'Dirty']),
loc_B: random.choice(['Clean', 'Dirty'])}
def thing_classes(self):
return [Wall, Dirt, ReflexVacuumAgent, RandomVacuumAgent, TableDrivenVacuumAgent, ModelBasedVacuumAgent]
def percept(self, agent):
"""Returns the agent's location, and the location status (Dirty/Clean)."""
return agent.location, self.status[agent.location]
def execute_action(self, agent, action):
"""Change agent's location and/or location's status; track performance.
Score 10 for each dirt cleaned; -1 for each move."""
if action == 'Right':
agent.location = loc_B
agent.performance -= 1
elif action == 'Left':
agent.location = loc_A
agent.performance -= 1
elif action == 'Suck':
if self.status[agent.location] == 'Dirty':
agent.performance += 10
self.status[agent.location] = 'Clean'
def default_location(self, thing):
"""Agents start in either location at random."""
return random.choice([loc_A, loc_B])
# ______________________________________________________________________________
# The Wumpus World
class Gold(Thing):
def __eq__(self, rhs):
"""All Gold are equal"""
return rhs.__class__ == Gold
pass
class Bump(Thing):
pass
class Glitter(Thing):
pass
class Pit(Thing):
pass
class Breeze(Thing):
pass
class Arrow(Thing):
pass
class Scream(Thing):
pass
class Wumpus(Agent):
screamed = False
pass
class Stench(Thing):
pass
class Explorer(Agent):
holding = []
has_arrow = True
killed_by = ""
direction = Direction("right")
def can_grab(self, thing):
"""Explorer can only grab gold"""
return thing.__class__ == Gold
class WumpusEnvironment(XYEnvironment):
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
# Room should be 4x4 grid of rooms. The extra 2 for walls
def __init__(self, agent_program, width=6, height=6):
super().__init__(width, height)
self.init_world(agent_program)
def init_world(self, program):
"""Spawn items in the world based on probabilities from the book"""
"WALLS"
self.add_walls()
"PITS"
for x in range(self.x_start, self.x_end):
for y in range(self.y_start, self.y_end):
if random.random() < self.pit_probability:
self.add_thing(Pit(), (x, y), True)
self.add_thing(Breeze(), (x - 1, y), True)
self.add_thing(Breeze(), (x, y - 1), True)
self.add_thing(Breeze(), (x + 1, y), True)
self.add_thing(Breeze(), (x, y + 1), True)
"WUMPUS"
w_x, w_y = self.random_location_inbounds(exclude=(1, 1))
self.add_thing(Wumpus(lambda x: ""), (w_x, w_y), True)
self.add_thing(Stench(), (w_x - 1, w_y), True)
self.add_thing(Stench(), (w_x + 1, w_y), True)
self.add_thing(Stench(), (w_x, w_y - 1), True)
self.add_thing(Stench(), (w_x, w_y + 1), True)
"GOLD"
self.add_thing(Gold(), self.random_location_inbounds(exclude=(1, 1)), True)
"AGENT"
self.add_thing(Explorer(program), (1, 1), True)
def get_world(self, show_walls=True):
"""Return the items in the world"""
result = []
x_start, y_start = (0, 0) if show_walls else (1, 1)
if show_walls:
x_end, y_end = self.width, self.height
else:
x_end, y_end = self.width - 1, self.height - 1
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x, y)))
result.append(row)
return result
def percepts_from(self, agent, location, tclass=Thing):
"""Return percepts from a given location,
and replaces some items with percepts from chapter 7."""
thing_percepts = {
Gold: Glitter(),
Wall: Bump(),
Wumpus: Stench(),
Pit: Breeze()}
"""Agents don't need to get their percepts"""
thing_percepts[agent.__class__] = None
"""Gold only glitters in its cell"""
if location != agent.location:
thing_percepts[Gold] = None
result = [thing_percepts.get(thing.__class__, thing) for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
return result if len(result) else [None]
def percept(self, agent):
"""Return things in adjacent (not diagonal) cells of the agent.
Result format: [Left, Right, Up, Down, Center / Current location]"""
x, y = agent.location
result = []
result.append(self.percepts_from(agent, (x - 1, y)))
result.append(self.percepts_from(agent, (x + 1, y)))
result.append(self.percepts_from(agent, (x, y - 1)))
result.append(self.percepts_from(agent, (x, y + 1)))
result.append(self.percepts_from(agent, (x, y)))
"""The wumpus gives out a loud scream once it's killed."""
wumpus = [thing for thing in self.things if isinstance(thing, Wumpus)]
if len(wumpus) and not wumpus[0].alive and not wumpus[0].screamed:
result[-1].append(Scream())
wumpus[0].screamed = True
return result
def execute_action(self, agent, action):
"""Modify the state of the environment based on the agent's actions.
Performance score taken directly out of the book."""
if isinstance(agent, Explorer) and self.in_danger(agent):
return
agent.bump = False
if action == 'TurnRight':
agent.direction += Direction.R
agent.performance -= 1
elif action == 'TurnLeft':
agent.direction += Direction.L
agent.performance -= 1
elif action == 'Forward':
agent.bump = self.move_to(agent, agent.direction.move_forward(agent.location))
agent.performance -= 1
elif action == 'Grab':
things = [thing for thing in self.list_things_at(agent.location)
if agent.can_grab(thing)]
if len(things):
print("Grabbing", things[0].__class__.__name__)
if len(things):
agent.holding.append(things[0])
agent.performance -= 1
elif action == 'Climb':
if agent.location == (1, 1): # Agent can only climb out of (1,1)
agent.performance += 1000 if Gold() in agent.holding else 0
self.delete_thing(agent)
elif action == 'Shoot':
"""The arrow travels straight down the path the agent is facing"""
if agent.has_arrow:
arrow_travel = agent.direction.move_forward(agent.location)
while self.is_inbounds(arrow_travel):
wumpus = [thing for thing in self.list_things_at(arrow_travel)
if isinstance(thing, Wumpus)]
if len(wumpus):
wumpus[0].alive = False
break
arrow_travel = agent.direction.move_forward(agent.location)
agent.has_arrow = False
def in_danger(self, agent):
"""Check if Explorer is in danger (Pit or Wumpus), if he is, kill him"""
for thing in self.list_things_at(agent.location):
if isinstance(thing, Pit) or (isinstance(thing, Wumpus) and thing.alive):
agent.alive = False
agent.performance -= 1000
agent.killed_by = thing.__class__.__name__
return True
return False
def is_done(self):
"""The game is over when the Explorer is killed
or if he climbs out of the cave only at (1,1)."""
explorer = [agent for agent in self.agents if isinstance(agent, Explorer)]
if len(explorer):
if explorer[0].alive:
return False
else:
print("Death by {} [-1000].".format(explorer[0].killed_by))
else:
print("Explorer climbed out {}."
.format("with Gold [+1000]!" if Gold() not in self.things else "without Gold [+0]"))
return True
# TODO: Arrow needs to be implemented
# ______________________________________________________________________________
def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
"""See how well each of several agents do in n instances of an environment.
Pass in a factory (constructor) for environments, and several for agents.
Create n instances of the environment, and run each agent in copies of
each one for steps. Return a list of (agent, average-score) tuples.
>>> environment = TrivialVacuumEnvironment
>>> agents = [ModelBasedVacuumAgent, ReflexVacuumAgent]
>>> result = compare_agents(environment, agents)
>>> performance_ModelBasedVacuumAgent = result[0][1]
>>> performance_ReflexVacuumAgent = result[1][1]
>>> performance_ReflexVacuumAgent <= performance_ModelBasedVacuumAgent
True
"""
envs = [EnvFactory() for i in range(n)]
return [(A, test_agent(A, steps, copy.deepcopy(envs)))
for A in AgentFactories]
def test_agent(AgentFactory, steps, envs):
"""Return the mean score of running an agent in each of the envs, for steps
>>> def constant_prog(percept):
... return percept
...
>>> agent = Agent(constant_prog)
>>> result = agent.program(5)
>>> result == 5
True
"""
def score(env):
agent = AgentFactory()
env.add_thing(agent)
env.run(steps)
return agent.performance
return mean(map(score, envs))
# _________________________________________________________________________
__doc__ += """
>>> a = ReflexVacuumAgent()
>>> a.program((loc_A, 'Clean'))
'Right'
>>> a.program((loc_B, 'Clean'))
'Left'
>>> a.program((loc_A, 'Dirty'))
'Suck'
>>> a.program((loc_A, 'Dirty'))
'Suck'
>>> e = TrivialVacuumEnvironment()
>>> e.add_thing(ModelBasedVacuumAgent())
>>> e.run(5)
"""
================================================
FILE: arc_consistency_heuristics.ipynb
================================================
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"# Constraint Satisfaction Problems\n",
"---\n",
"# Heuristics for Arc-Consistency Algorithms\n",
"\n",
"## Introduction\n",
"A ***Constraint Satisfaction Problem*** is a triple $(X,D,C)$ where: \n",
"- $X$ is a set of variables $X_1, …, X_n$;\n",
"- $D$ is a set of domains $D_1, …, D_n$, one for each variable and each of which consists of a set of allowable values $v_1, ..., v_k$;\n",
"- $C$ is a set of constraints that specify allowable combinations of values.\n",
"\n",
"A CSP is called *arc-consistent* if every value in the domain of every variable is supported by all the neighbors of the variable while, is called *inconsistent*, if it has no solutions. <br>\n",
"***Arc-consistency algorithms*** remove all unsupported values from the domains of variables making the CSP *arc-consistent* or decide that a CSP is *inconsistent* by finding that some variable has no supported values in its domain. <br> \n",
"Heuristics significantly enhance the efficiency of the *arc-consistency algorithms* improving their average performance in terms of *consistency-checks* which can be considered a standard measure of goodness for such algorithms. *Arc-heuristic* operate at arc-level and selects the constraint that will be used for the next check, while *domain-heuristics* operate at domain-level and selects which values will be used for the next support-check."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from csp import *"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Domain-Heuristics for Arc-Consistency Algorithms\n",
"In <a name=\"ref-1\"/>[[1]](#cite-van2002domain) are investigated the effects of a *domain-heuristic* based on the notion of a *double-support check* by studying its average time-complexity.\n",
"\n",
"The objective of *arc-consistency algorithms* is to resolve some uncertainty; it has to be know, for each $v_i \\in D_i$ and for each $v_j \\in D_j$, whether it is supported.\n",
"\n",
"A *single-support check*, $(v_i, v_j) \\in C_{ij}$, is one in which, before the check is done, it is already known that either $v_i$ or $v_j$ are supported. \n",
"\n",
"A *double-support check* $(v_i, v_j) \\in C_{ij}$, is one in which there is still, before the check, uncertainty about the support-status of both $v_i$ and $v_j$. \n",
"\n",
"If a *double-support check* is successful, two uncertainties are resolved. If a *single-support check* is successful, only one uncertainty is resolved. A good *arc-consistency algorithm*, therefore, would always choose to do a *double-support check* in preference of a *single-support check*, because the cormer offers the potential higher payback.\n",
"\n",
"The improvement with *double-support check* is that, where possible, *consistency-checks* are used to find supports for two values, one value in the domain of each variable, which were previously known to be unsupported. It is motivated by the insight that *in order to minimize the number of consistency-checks it is necessary to maximize the number of uncertainties which are resolved per check*."
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"### AC-3b: an improved version of AC-3 with Double-Support Checks"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As shown in <a name=\"ref-2\"/>[[2]](#cite-van2000improving) the idea is to use *double-support checks* to improve the average performance of `AC3` which does not exploit the fact that relations are bidirectional and results in a new general purpose *arc-consistency algorithm* called `AC3b`."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[0;32mdef\u001b[0m \u001b[0mAC3\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0marc_heuristic\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mdom_j_up\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;34m\"\"\"[Figure 6.3]\"\"\"\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mqueue\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXk\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvariables\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mneighbors\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msupport_pruning\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0marc_heuristic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mwhile\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mrevise\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mrevised\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;31m# CSP is inconsistent\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mneighbors\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mXk\u001b[0m \u001b[0;34m!=\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;31m# CSP is satisfiable\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%psource AC3"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[0;32mdef\u001b[0m \u001b[0mrevise\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;34m\"\"\"Return true if we remove a value.\"\"\"\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# if all(not csp.constraints(Xi, x, Xj, y) for y in csp.curr_domains[Xj]):\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mconflict\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0my\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mconstraints\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mconflict\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mconflict\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mbreak\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mconflict\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprune\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mrevised\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%psource revise"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"At any stage in the process of making 2-variable CSP *arc-consistent* in `AC3b`:\n",
"- there is a set $S_i^+ \\subseteq D_i$ whose values are all known to be supported by $X_j$;\n",
"- there is a set $S_i^? = D_i \\setminus S_i^+$ whose values are unknown, as yet, to be supported by $X_j$.\n",
"\n",
"The same holds if the roles for $X_i$ and $X_j$ are exchanged.\n",
"\n",
"In order to establish support for a value $v_i^? \\in S_i^?$ it seems better to try to find a support among the values in $S_j^?$ first, because for each $v_j^? \\in S_j^?$ the check $(v_i^?,v_j^?) \\in C_{ij}$ is a *double-support check* and it is just as likely that any $v_j^? \\in S_j^?$ supports $v_i^?$ than it is that any $v_j^+ \\in S_j^+$ does. Only if no support can be found among the elements in $S_j^?$, should the elements $v_j^+$ in $S_j^+$ be used for *single-support checks* $(v_i^?,v_j^+) \\in C_{ij}$. After it has been decided for each value in $D_i$ whether it is supported or not, either $S_x^+ = \\emptyset$ and the 2-variable CSP is *inconsistent*, or $S_x^+ \\neq \\emptyset$ and the CSP is *satisfiable*. In the latter case, the elements from $D_i$ which are supported by $j$ are given by $S_x^+$. The elements in $D_j$ which are supported by $x$ are given by the union of $S_j^+$ with the set of those elements of $S_j^?$ which further processing will show to be supported by some $v_i^+ \\in S_x^+$."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[0;32mdef\u001b[0m \u001b[0mAC3b\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0marc_heuristic\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mdom_j_up\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mqueue\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXk\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvariables\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mneighbors\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msupport_pruning\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0marc_heuristic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mwhile\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# Si_p values are all known to be supported by Xj\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# Sj_p values are all known to be supported by Xi\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# Dj - Sj_p = Sj_u values are unknown, as yet, to be supported by Xi\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mSi_p\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mSj_p\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mSj_u\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpartition\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mSi_p\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;31m# CSP is inconsistent\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mSi_p\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprune\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mrevised\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mneighbors\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mXk\u001b[0m \u001b[0;34m!=\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0misinstance\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mqueue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mset\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# or queue -= {(Xj, Xi)} or queue.remove((Xj, Xi))\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdifference_update\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m{\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdifference_update\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# the elements in D_j which are supported by Xi are given by the union of Sj_p with the set of those\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# elements of Sj_u which further processing will show to be supported by some vi_p in Si_p\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mvj_p\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mSj_u\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mvi_p\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mSi_p\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mconflict\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mconstraints\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvj_p\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvi_p\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mconflict\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mSj_p\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvj_p\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mconflict\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mbreak\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mSj_p\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprune\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mrevised\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mneighbors\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mXk\u001b[0m \u001b[0;34m!=\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;31m# CSP is satisfiable\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%psource AC3b"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[0;32mdef\u001b[0m \u001b[0mpartition\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mSi_p\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mSj_p\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mSj_u\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mvi_u\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mconflict\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# now, in order to establish support for a value vi_u in Di it seems better to try to find a support among\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# the values in Sj_u first, because for each vj_u in Sj_u the check (vi_u, vj_u) is a double-support check\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# and it is just as likely that any vj_u in Sj_u supports vi_u than it is that any vj_p in Sj_p does...\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mvj_u\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mSj_u\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mSj_p\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# double-support check\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mconstraints\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvi_u\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvj_u\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mconflict\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mSi_p\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvi_u\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mSj_p\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvj_u\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mconflict\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mbreak\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# ... and only if no support can be found among the elements in Sj_u, should the elements vj_p in Sj_p be used\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# for single-support checks (vi_u, vj_p)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mconflict\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mvj_p\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mSj_p\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# single-support check\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mconstraints\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvi_u\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvj_p\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mconflict\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mSi_p\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvi_u\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mconflict\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mbreak\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mSi_p\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mSj_p\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mSj_u\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mSj_p\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%psource partition"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"`AC3b` is a refinement of the `AC3` algorithm which consists of the fact that if, when arc $(i,j)$ is being processed and the reverse arc $(j,i)$ is also in the queue, then consistency-checks can be saved because only support for the elements in $S_j^?$ has to be found (as opposed to support for all the elements in $D_j$ in the\n",
"`AC3` algorithm). <br>\n",
"`AC3b` inherits all its properties like $\\mathcal{O}(ed^3)$ time-complexity and $\\mathcal{O}(e + nd)$ space-complexity fron `AC3` and where $n$ denotes the number of variables in the CSP, $e$ denotes the number of binary constraints and $d$ denotes the maximum domain-size of the variables."
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"## Arc-Heuristics for Arc-Consistency Algorithms"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"Many *arc-heuristics* can be devised, based on three major features of CSPs:\n",
"- the number of acceptable pairs in each constraint (the *constraint size* or *satisfiability*);\n",
"- the *domain size*;\n",
"- the number of binary constraints that each variable participates in, equal to the *degree* of the node of that variable in the constraint graph. \n",
"\n",
"Simple examples of heuristics that might be expected to improve the efficiency of relaxation are:\n",
"- ordering the list of variable pairs by *increasing* relative *satisfiability*;\n",
"- ordering by *increasing size of the domain* of the variable $v_j$ relaxed against $v_i$;\n",
"- ordering by *descending degree* of node of the variable relaxed.\n",
"\n",
"In <a name=\"ref-3\"/>[[3]](#cite-wallace1992ordering) are investigated the effects of these *arc-heuristics* in an empirical way, experimenting the effects of them on random CSPs. Their results demonstrate that the first two, later called `sat up` and `dom j up` for n-ary and binary CSPs respectively, significantly reduce the number of *consistency-checks*."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[0;32mdef\u001b[0m \u001b[0mdom_j_up\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mSortedSet\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mqueue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkey\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mlambda\u001b[0m \u001b[0mt\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mneg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%psource dom_j_up"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[0;32mdef\u001b[0m \u001b[0msat_up\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mto_do\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mSortedSet\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mto_do\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkey\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mlambda\u001b[0m \u001b[0mt\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;36m1\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mvar\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mvar\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mt\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscope\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%psource sat_up"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"## Experimental Results"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"For the experiments below on binary CSPs, in addition to the two *arc-consistency algorithms* already cited above, `AC3` and `AC3b`, the `AC4` algorithm was used. <br>\n",
"The `AC4` algorithm runs in $\\mathcal{O}(ed^2)$ worst-case time but can be slower than `AC3` on average cases."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[0;32mdef\u001b[0m \u001b[0mAC4\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0marc_heuristic\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mdom_j_up\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mqueue\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXk\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvariables\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mneighbors\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msupport_pruning\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mqueue\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0marc_heuristic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcsp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0msupport_counter\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mCounter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mvariable_value_pairs_supported\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdefaultdict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mset\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0munsupported_variable_value_pairs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# construction and initialization of support sets\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mwhile\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mqueue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0my\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mconstraints\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0msupport_counter\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mvariable_value_pairs_supported\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0msupport_counter\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprune\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0munsupported_variable_value_pairs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mrevised\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;31m# CSP is inconsistent\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;31m# propagation of removed values\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mwhile\u001b[0m \u001b[0munsupported_variable_value_pairs\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0munsupported_variable_value_pairs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mvariable_value_pairs_supported\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0msupport_counter\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m-=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0msupport_counter\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mXj\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprune\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremovals\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mrevised\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0munsupported_variable_value_pairs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mrevised\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mcsp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurr_domains\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mXi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;31m# CSP is inconsistent\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mchecks\u001b[0m \u001b[0;31m# CSP is satisfiable\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%psource AC4"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Sudoku"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"#### Easy Sudoku"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
". . 3 | . 2 . | 6 . .\n",
"9 . . | 3 . 5 | . . 1\n",
". . 1 | 8 . 6 | 4 . .\n",
"------+-------+------\n",
". . 8 | 1 . 2 | 9 . .\n",
"7 . . | . . . | . . 8\n",
". . 6 | 7 . 8 | 2 . .\n",
"------+-------+------\n",
". . 2 | 6 . 9 | 5 . .\n",
"8 . . | 2 . 3 | . . 9\n",
". . 5 | . 1 . | 3 . .\n"
]
}
],
"source": [
"sudoku = Sudoku(easy1)\n",
"sudoku.display(sudoku.infer_assignment())"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 23.6 ms, sys: 0 ns, total: 23.6 ms\n",
"Wall time: 22.4 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3 needs 11322 consistency-checks'"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"%time _, checks = AC3(sudoku, arc_heuristic=no_arc_heuristic)\n",
"f'AC3 needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 7.43 ms, sys: 3.68 ms, total: 11.1 ms\n",
"Wall time: 10.7 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3b needs 8345 consistency-checks'"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(easy1)\n",
"%time _, checks = AC3b(sudoku, arc_heuristic=no_arc_heuristic)\n",
"f'AC3b needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 56.3 ms, sys: 0 ns, total: 56.3 ms\n",
"Wall time: 55.4 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC4 needs 27718 consistency-checks'"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(easy1)\n",
"%time _, checks = AC4(sudoku, arc_heuristic=no_arc_heuristic)\n",
"f'AC4 needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 17.2 ms, sys: 0 ns, total: 17.2 ms\n",
"Wall time: 16.9 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3 with DOM J UP arc heuristic needs 6925 consistency-checks'"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(easy1)\n",
"%time _, checks = AC3(sudoku, arc_heuristic=dom_j_up)\n",
"f'AC3 with DOM J UP arc heuristic needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 40.9 ms, sys: 2.47 ms, total: 43.4 ms\n",
"Wall time: 41.7 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3b with DOM J UP arc heuristic needs 6278 consistency-checks'"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(easy1)\n",
"%time _, checks = AC3b(sudoku, arc_heuristic=dom_j_up)\n",
"f'AC3b with DOM J UP arc heuristic needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 38.9 ms, sys: 1.96 ms, total: 40.9 ms\n",
"Wall time: 40.7 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC4 with DOM J UP arc heuristic needs 9393 consistency-checks'"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(easy1)\n",
"%time _, checks = AC4(sudoku, arc_heuristic=dom_j_up)\n",
"f'AC4 with DOM J UP arc heuristic needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4 8 3 | 9 2 1 | 6 5 7\n",
"9 6 7 | 3 4 5 | 8 2 1\n",
"2 5 1 | 8 7 6 | 4 9 3\n",
"------+-------+------\n",
"5 4 8 | 1 3 2 | 9 7 6\n",
"7 2 9 | 5 6 4 | 1 3 8\n",
"1 3 6 | 7 9 8 | 2 4 5\n",
"------+-------+------\n",
"3 7 2 | 6 8 9 | 5 1 4\n",
"8 1 4 | 2 5 3 | 7 6 9\n",
"6 9 5 | 4 1 7 | 3 8 2\n"
]
}
],
"source": [
"backtracking_search(sudoku, select_unassigned_variable=mrv, inference=forward_checking)\n",
"sudoku.display(sudoku.infer_assignment())"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"#### Harder Sudoku"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4 1 7 | 3 6 9 | 8 . 5\n",
". 3 . | . . . | . . .\n",
". . . | 7 . . | . . .\n",
"------+-------+------\n",
". 2 . | . . . | . 6 .\n",
". . . | . 8 . | 4 . .\n",
". . . | . 1 . | . . .\n",
"------+-------+------\n",
". . . | 6 . 3 | . 7 .\n",
"5 . . | 2 . . | . . .\n",
"1 . 4 | . . . | . . .\n"
]
}
],
"source": [
"sudoku = Sudoku(harder1)\n",
"sudoku.display(sudoku.infer_assignment())"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 17.7 ms, sys: 481 µs, total: 18.2 ms\n",
"Wall time: 17.2 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3 needs 12837 consistency-checks'"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"%time _, checks = AC3(sudoku, arc_heuristic=no_arc_heuristic)\n",
"f'AC3 needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 24.1 ms, sys: 2.6 ms, total: 26.7 ms\n",
"Wall time: 25.1 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3b needs 8864 consistency-checks'"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(harder1)\n",
"%time _, checks = AC3b(sudoku, arc_heuristic=no_arc_heuristic)\n",
"f'AC3b needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 63.4 ms, sys: 3.48 ms, total: 66.9 ms\n",
"Wall time: 65.5 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC4 needs 44213 consistency-checks'"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(harder1)\n",
"%time _, checks = AC4(sudoku, arc_heuristic=no_arc_heuristic)\n",
"f'AC4 needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 9.96 ms, sys: 570 µs, total: 10.5 ms\n",
"Wall time: 10.3 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3 with DOM J UP arc heuristic needs 7045 consistency-checks'"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(harder1)\n",
"%time _, checks = AC3(sudoku, arc_heuristic=dom_j_up)\n",
"f'AC3 with DOM J UP arc heuristic needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 36.1 ms, sys: 0 ns, total: 36.1 ms\n",
"Wall time: 35.5 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3b with DOM J UP arc heuristic needs 6994 consistency-checks'"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(harder1)\n",
"%time _, checks = AC3b(sudoku, arc_heuristic=dom_j_up)\n",
"f'AC3b with DOM J UP arc heuristic needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 40.3 ms, sys: 0 ns, total: 40.3 ms\n",
"Wall time: 39.7 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC4 with DOM J UP arc heuristic needs 19210 consistency-checks'"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sudoku = Sudoku(harder1)\n",
"%time _, checks = AC4(sudoku, arc_heuristic=dom_j_up)\n",
"f'AC4 with DOM J UP arc heuristic needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4 1 7 | 3 6 9 | 8 2 5\n",
"6 3 2 | 1 5 8 | 9 4 7\n",
"9 5 8 | 7 2 4 | 3 1 6\n",
"------+-------+------\n",
"8 2 5 | 4 3 7 | 1 6 9\n",
"7 9 1 | 5 8 6 | 4 3 2\n",
"3 4 6 | 9 1 2 | 7 5 8\n",
"------+-------+------\n",
"2 8 9 | 6 4 3 | 5 7 1\n",
"5 7 3 | 2 9 1 | 6 8 4\n",
"1 6 4 | 8 7 5 | 2 9 3\n"
]
}
],
"source": [
"backtracking_search(sudoku, select_unassigned_variable=mrv, inference=forward_checking)\n",
"sudoku.display(sudoku.infer_assignment())"
]
},
{
"cell_type": "markdown",
"metadata": {
"pycharm": {}
},
"source": [
"### 8 Queens"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
". - . - . - . - 0 0 0 0 0 0 0 0 \n",
"- . - . - . - . 0 0 0 0 0 0 0 0 \n",
". - . - . - . - 0 0 0 0 0 0 0 0 \n",
"- . - . - . - . 0 0 0 0 0 0 0 0 \n",
". - . - . - . - 0 0 0 0 0 0 0 0 \n",
"- . - . - . - . 0 0 0 0 0 0 0 0 \n",
". - . - . - . - 0 0 0 0 0 0 0 0 \n",
"- . - . - . - . 0 0 0 0 0 0 0 0 \n"
]
}
],
"source": [
"chess = NQueensCSP(8)\n",
"chess.display(chess.infer_assignment())"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 689 µs, sys: 193 µs, total: 882 µs\n",
"Wall time: 892 µs\n"
]
},
{
"data": {
"text/plain": [
"'AC3 needs 666 consistency-checks'"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"%time _, checks = AC3(chess, arc_heuristic=no_arc_heuristic)\n",
"f'AC3 needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 451 µs, sys: 127 µs, total: 578 µs\n",
"Wall time: 584 µs\n"
]
},
{
"data": {
"text/plain": [
"'AC3b needs 428 consistency-checks'"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chess = NQueensCSP(8)\n",
"%time _, checks = AC3b(chess, arc_heuristic=no_arc_heuristic)\n",
"f'AC3b needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 8.53 ms, sys: 109 µs, total: 8.64 ms\n",
"Wall time: 8.48 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC4 needs 4096 consistency-checks'"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chess = NQueensCSP(8)\n",
"%time _, checks = AC4(chess, arc_heuristic=no_arc_heuristic)\n",
"f'AC4 needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 1.88 ms, sys: 0 ns, total: 1.88 ms\n",
"Wall time: 1.88 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3 with DOM J UP arc heuristic needs 666 consistency-checks'"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chess = NQueensCSP(8)\n",
"%time _, checks = AC3(chess, arc_heuristic=dom_j_up)\n",
"f'AC3 with DOM J UP arc heuristic needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 1.21 ms, sys: 326 µs, total: 1.53 ms\n",
"Wall time: 1.54 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC3b with DOM J UP arc heuristic needs 792 consistency-checks'"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chess = NQueensCSP(8)\n",
"%time _, checks = AC3b(chess, arc_heuristic=dom_j_up)\n",
"f'AC3b with DOM J UP arc heuristic needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 4.71 ms, sys: 0 ns, total: 4.71 ms\n",
"Wall time: 4.65 ms\n"
]
},
{
"data": {
"text/plain": [
"'AC4 with DOM J UP arc heuristic needs 4096 consistency-checks'"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chess = NQueensCSP(8)\n",
"%time _, checks = AC4(chess, arc_heuristic=dom_j_up)\n",
"f'AC4 with DOM J UP arc heuristic needs {checks} consistency-checks'"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"pycharm": {}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
". - . - Q - . - 2 2 3 3 0* 1 1 2 \n",
"- Q - . - . - . 1 0* 3 3 2 2 2 2 \n",
". - . - . Q . - 3 2 3 2 2 0* 3 2 \n",
"Q . - . - . - . 0* 3 1 2 3 3 3 3 \n",
". - . - . - Q - 2 2 2 2 3 3 0* 2 \n",
"- . - Q - . - . 2 1 3 0* 2 3 2 2 \n",
". - . - . - . Q 1 3 2 3 3 1 2 0* \n",
"- . Q . - . - . 2 2 0* 2 2 2 2 2 \n"
]
}
],
"source": [
"backtracking_search(chess, select_unas
gitextract_5odqtdr9/ ├── .coveragerc ├── .flake8 ├── .gitignore ├── .gitmodules ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SUBMODULE.md ├── agents.ipynb ├── agents.py ├── agents4e.py ├── arc_consistency_heuristics.ipynb ├── classical_planning_approaches.ipynb ├── csp.ipynb ├── csp.py ├── deep_learning4e.py ├── games.ipynb ├── games.py ├── games4e.ipynb ├── games4e.py ├── gui/ │ ├── eight_puzzle.py │ ├── genetic_algorithm_example.py │ ├── grid_mdp.py │ ├── romania_problem.py │ ├── tic-tac-toe.py │ ├── tsp.py │ ├── vacuum_agent.py │ └── xy_vacuum_environment.py ├── images/ │ ├── IMAGE-CREDITS │ └── makefile ├── improving_sat_algorithms.ipynb ├── index.ipynb ├── intro.ipynb ├── ipyviews.py ├── js/ │ ├── canvas.js │ ├── continuousworld.js │ └── gridworld.js ├── knowledge.py ├── knowledge_FOIL.ipynb ├── knowledge_current_best.ipynb ├── knowledge_version_space.ipynb ├── learning.ipynb ├── learning.py ├── learning4e.py ├── learning_apps.ipynb ├── logic.ipynb ├── logic.py ├── logic4e.py ├── making_simple_decision4e.py ├── mdp.ipynb ├── mdp.py ├── mdp4e.py ├── mdp_apps.ipynb ├── neural_nets.ipynb ├── nlp.ipynb ├── nlp.py ├── nlp4e.py ├── nlp_apps.ipynb ├── notebook.py ├── notebook4e.py ├── notebooks/ │ ├── chapter19/ │ │ ├── Learners.ipynb │ │ ├── Loss Functions and Layers.ipynb │ │ ├── Optimizer and Backpropagation.ipynb │ │ └── RNN.ipynb │ ├── chapter21/ │ │ ├── Active Reinforcement Learning.ipynb │ │ └── Passive Reinforcement Learning.ipynb │ ├── chapter22/ │ │ ├── Grammar.ipynb │ │ ├── Introduction.ipynb │ │ ├── Parsing.ipynb │ │ └── nlp_apps.ipynb │ └── chapter24/ │ ├── Image Edge Detection.ipynb │ ├── Image Segmentation.ipynb │ └── Objects in Images.ipynb ├── obsolete_search4e.ipynb ├── perception4e.py ├── planning.ipynb ├── planning.py ├── planning_angelic_search.ipynb ├── planning_graphPlan.ipynb ├── planning_hierarchical_search.ipynb ├── planning_partial_order_planner.ipynb ├── planning_total_order_planner.ipynb ├── probabilistic_learning.py ├── probability.ipynb ├── probability.py ├── probability4e.ipynb ├── probability4e.py ├── pytest.ini ├── reinforcement_learning.ipynb ├── reinforcement_learning.py ├── reinforcement_learning4e.py ├── requirements.txt ├── search.ipynb ├── search.py ├── search4e.ipynb ├── tests/ │ ├── __init__.py │ ├── pytest.ini │ ├── test_agents.py │ ├── test_agents4e.py │ ├── test_csp.py │ ├── test_deep_learning4e.py │ ├── test_games.py │ ├── test_games4e.py │ ├── test_knowledge.py │ ├── test_learning.py │ ├── test_learning4e.py │ ├── test_logic.py │ ├── test_logic4e.py │ ├── test_mdp.py │ ├── test_mdp4e.py │ ├── test_nlp.py │ ├── test_nlp4e.py │ ├── test_perception4e.py │ ├── test_planning.py │ ├── test_probabilistic_learning.py │ ├── test_probability.py │ ├── test_probability4e.py │ ├── test_reinforcement_learning.py │ ├── test_reinforcement_learning4e.py │ ├── test_search.py │ ├── test_text.py │ └── test_utils.py ├── text.ipynb ├── text.py ├── utils.py ├── utils4e.py ├── vacuum_world.ipynb └── viterbi_algorithm.ipynb
SYMBOL INDEX (2621 symbols across 66 files)
FILE: agents.py
class Thing (line 47) | class Thing:
method __repr__ (line 52) | def __repr__(self):
method is_alive (line 55) | def is_alive(self):
method show_state (line 59) | def show_state(self):
method display (line 63) | def display(self, canvas, x, y, width, height):
class Agent (line 69) | class Agent(Thing):
method __init__ (line 82) | def __init__(self, program=None):
method can_grab (line 95) | def can_grab(self, thing):
function TraceAgent (line 101) | def TraceAgent(agent):
function TableDrivenAgentProgram (line 118) | def TableDrivenAgentProgram(table):
function RandomAgentProgram (line 136) | def RandomAgentProgram(actions):
function SimpleReflexAgentProgram (line 153) | def SimpleReflexAgentProgram(rules, interpret_input):
function ModelBasedReflexAgentProgram (line 168) | def ModelBasedReflexAgentProgram(rules, update_state, model):
function rule_match (line 184) | def rule_match(state, rules):
function RandomVacuumAgent (line 197) | def RandomVacuumAgent():
function TableDrivenVacuumAgent (line 209) | def TableDrivenVacuumAgent():
function ReflexVacuumAgent (line 231) | def ReflexVacuumAgent():
function ModelBasedVacuumAgent (line 255) | def ModelBasedVacuumAgent():
class Environment (line 285) | class Environment:
method __init__ (line 296) | def __init__(self):
method thing_classes (line 300) | def thing_classes(self):
method percept (line 303) | def percept(self, agent):
method execute_action (line 307) | def execute_action(self, agent, action):
method default_location (line 311) | def default_location(self, thing):
method exogenous_change (line 315) | def exogenous_change(self):
method is_done (line 319) | def is_done(self):
method step (line 323) | def step(self):
method run (line 339) | def run(self, steps=1000):
method list_things_at (line 346) | def list_things_at(self, location, tclass=Thing):
method some_things_at (line 354) | def some_things_at(self, location, tclass=Thing):
method add_thing (line 359) | def add_thing(self, thing, location=None):
method delete_thing (line 374) | def delete_thing(self, thing):
class Direction (line 387) | class Direction:
method __init__ (line 401) | def __init__(self, direction):
method __add__ (line 404) | def __add__(self, heading):
method move_forward (line 442) | def move_forward(self, from_location):
class XYEnvironment (line 466) | class XYEnvironment(Environment):
method __init__ (line 475) | def __init__(self, width=10, height=10):
method things_near (line 487) | def things_near(self, location, radius=None):
method percept (line 496) | def percept(self, agent):
method execute_action (line 500) | def execute_action(self, agent, action):
method default_location (line 520) | def default_location(self, thing):
method move_to (line 527) | def move_to(self, thing, destination):
method add_thing (line 541) | def add_thing(self, thing, location=None, exclude_duplicate_class_item...
method is_inbounds (line 552) | def is_inbounds(self, location):
method random_location_inbounds (line 557) | def random_location_inbounds(self, exclude=None):
method delete_thing (line 567) | def delete_thing(self, thing):
method add_walls (line 576) | def add_walls(self):
method add_observer (line 589) | def add_observer(self, observer):
method turn_heading (line 598) | def turn_heading(self, heading, inc):
class Obstacle (line 603) | class Obstacle(Thing):
class Wall (line 609) | class Wall(Obstacle):
class GraphicEnvironment (line 616) | class GraphicEnvironment(XYEnvironment):
method __init__ (line 617) | def __init__(self, width=10, height=10, boundary=True, color={}, displ...
method get_world (line 630) | def get_world(self):
method run (line 660) | def run(self, steps=1000, delay=1):
method update (line 670) | def update(self, delay=1):
method reveal (line 674) | def reveal(self):
method draw_world (line 685) | def draw_world(self):
method conceal (line 693) | def conceal(self):
class ContinuousWorld (line 702) | class ContinuousWorld(Environment):
method __init__ (line 705) | def __init__(self, width=10, height=10):
method add_obstacle (line 710) | def add_obstacle(self, coordinates):
class PolygonObstacle (line 714) | class PolygonObstacle(Obstacle):
method __init__ (line 716) | def __init__(self, coordinates):
class Dirt (line 726) | class Dirt(Thing):
class VacuumEnvironment (line 730) | class VacuumEnvironment(XYEnvironment):
method __init__ (line 736) | def __init__(self, width=10, height=10):
method thing_classes (line 740) | def thing_classes(self):
method percept (line 744) | def percept(self, agent):
method execute_action (line 752) | def execute_action(self, agent, action):
class TrivialVacuumEnvironment (line 767) | class TrivialVacuumEnvironment(Environment):
method __init__ (line 773) | def __init__(self):
method thing_classes (line 778) | def thing_classes(self):
method percept (line 781) | def percept(self, agent):
method execute_action (line 785) | def execute_action(self, agent, action):
method default_location (line 799) | def default_location(self, thing):
class Gold (line 808) | class Gold(Thing):
method __eq__ (line 810) | def __eq__(self, rhs):
class Bump (line 817) | class Bump(Thing):
class Glitter (line 821) | class Glitter(Thing):
class Pit (line 825) | class Pit(Thing):
class Breeze (line 829) | class Breeze(Thing):
class Arrow (line 833) | class Arrow(Thing):
class Scream (line 837) | class Scream(Thing):
class Wumpus (line 841) | class Wumpus(Agent):
class Stench (line 846) | class Stench(Thing):
class Explorer (line 850) | class Explorer(Agent):
method can_grab (line 856) | def can_grab(self, thing):
class WumpusEnvironment (line 861) | class WumpusEnvironment(XYEnvironment):
method __init__ (line 866) | def __init__(self, agent_program, width=6, height=6):
method init_world (line 870) | def init_world(self, program):
method get_world (line 900) | def get_world(self, show_walls=True):
method percepts_from (line 917) | def percepts_from(self, agent, location, tclass=Thing):
method percept (line 937) | def percept(self, agent):
method execute_action (line 956) | def execute_action(self, agent, action):
method in_danger (line 984) | def in_danger(self, agent):
method is_done (line 994) | def is_done(self):
function compare_agents (line 1014) | def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
function test_agent (line 1032) | def test_agent(AgentFactory, steps, envs):
FILE: agents4e.py
class Thing (line 52) | class Thing:
method __repr__ (line 57) | def __repr__(self):
method is_alive (line 60) | def is_alive(self):
method show_state (line 64) | def show_state(self):
method display (line 68) | def display(self, canvas, x, y, width, height):
class Agent (line 74) | class Agent(Thing):
method __init__ (line 87) | def __init__(self, program=None):
method can_grab (line 100) | def can_grab(self, thing):
function TraceAgent (line 106) | def TraceAgent(agent):
function TableDrivenAgentProgram (line 123) | def TableDrivenAgentProgram(table):
function RandomAgentProgram (line 141) | def RandomAgentProgram(actions):
function SimpleReflexAgentProgram (line 158) | def SimpleReflexAgentProgram(rules, interpret_input):
function ModelBasedReflexAgentProgram (line 173) | def ModelBasedReflexAgentProgram(rules, update_state, transition_model, ...
function rule_match (line 189) | def rule_match(state, rules):
function RandomVacuumAgent (line 202) | def RandomVacuumAgent():
function TableDrivenVacuumAgent (line 214) | def TableDrivenVacuumAgent():
function ReflexVacuumAgent (line 236) | def ReflexVacuumAgent():
function ModelBasedVacuumAgent (line 260) | def ModelBasedVacuumAgent():
class Environment (line 290) | class Environment:
method __init__ (line 301) | def __init__(self):
method thing_classes (line 305) | def thing_classes(self):
method percept (line 308) | def percept(self, agent):
method execute_action (line 312) | def execute_action(self, agent, action):
method default_location (line 316) | def default_location(self, thing):
method exogenous_change (line 320) | def exogenous_change(self):
method is_done (line 324) | def is_done(self):
method step (line 328) | def step(self):
method run (line 344) | def run(self, steps=1000):
method list_things_at (line 351) | def list_things_at(self, location, tclass=Thing):
method some_things_at (line 359) | def some_things_at(self, location, tclass=Thing):
method add_thing (line 364) | def add_thing(self, thing, location=None):
method delete_thing (line 379) | def delete_thing(self, thing):
class Direction (line 392) | class Direction:
method __init__ (line 406) | def __init__(self, direction):
method __add__ (line 409) | def __add__(self, heading):
method move_forward (line 447) | def move_forward(self, from_location):
class XYEnvironment (line 471) | class XYEnvironment(Environment):
method __init__ (line 480) | def __init__(self, width=10, height=10):
method things_near (line 492) | def things_near(self, location, radius=None):
method percept (line 501) | def percept(self, agent):
method execute_action (line 505) | def execute_action(self, agent, action):
method default_location (line 522) | def default_location(self, thing):
method move_to (line 529) | def move_to(self, thing, destination):
method add_thing (line 543) | def add_thing(self, thing, location=None, exclude_duplicate_class_item...
method is_inbounds (line 554) | def is_inbounds(self, location):
method random_location_inbounds (line 559) | def random_location_inbounds(self, exclude=None):
method delete_thing (line 569) | def delete_thing(self, thing):
method add_walls (line 581) | def add_walls(self):
method add_observer (line 594) | def add_observer(self, observer):
method turn_heading (line 603) | def turn_heading(self, heading, inc):
class Obstacle (line 608) | class Obstacle(Thing):
class Wall (line 614) | class Wall(Obstacle):
class GraphicEnvironment (line 621) | class GraphicEnvironment(XYEnvironment):
method __init__ (line 622) | def __init__(self, width=10, height=10, boundary=True, color={}, displ...
method get_world (line 635) | def get_world(self):
method run (line 665) | def run(self, steps=1000, delay=1):
method update (line 675) | def update(self, delay=1):
method reveal (line 679) | def reveal(self):
method draw_world (line 690) | def draw_world(self):
method conceal (line 698) | def conceal(self):
class ContinuousWorld (line 707) | class ContinuousWorld(Environment):
method __init__ (line 710) | def __init__(self, width=10, height=10):
method add_obstacle (line 715) | def add_obstacle(self, coordinates):
class PolygonObstacle (line 719) | class PolygonObstacle(Obstacle):
method __init__ (line 721) | def __init__(self, coordinates):
class Dirt (line 731) | class Dirt(Thing):
class VacuumEnvironment (line 735) | class VacuumEnvironment(XYEnvironment):
method __init__ (line 741) | def __init__(self, width=10, height=10):
method thing_classes (line 745) | def thing_classes(self):
method percept (line 749) | def percept(self, agent):
method execute_action (line 757) | def execute_action(self, agent, action):
class TrivialVacuumEnvironment (line 772) | class TrivialVacuumEnvironment(Environment):
method __init__ (line 778) | def __init__(self):
method thing_classes (line 783) | def thing_classes(self):
method percept (line 786) | def percept(self, agent):
method execute_action (line 790) | def execute_action(self, agent, action):
method default_location (line 804) | def default_location(self, thing):
class Gold (line 813) | class Gold(Thing):
method __eq__ (line 815) | def __eq__(self, rhs):
class Bump (line 822) | class Bump(Thing):
class Glitter (line 826) | class Glitter(Thing):
class Pit (line 830) | class Pit(Thing):
class Breeze (line 834) | class Breeze(Thing):
class Arrow (line 838) | class Arrow(Thing):
class Scream (line 842) | class Scream(Thing):
class Wumpus (line 846) | class Wumpus(Agent):
class Stench (line 851) | class Stench(Thing):
class Explorer (line 855) | class Explorer(Agent):
method can_grab (line 861) | def can_grab(self, thing):
class WumpusEnvironment (line 866) | class WumpusEnvironment(XYEnvironment):
method __init__ (line 871) | def __init__(self, agent_program, width=6, height=6):
method init_world (line 875) | def init_world(self, program):
method get_world (line 905) | def get_world(self, show_walls=True):
method percepts_from (line 922) | def percepts_from(self, agent, location, tclass=Thing):
method percept (line 942) | def percept(self, agent):
method execute_action (line 961) | def execute_action(self, agent, action):
method in_danger (line 1003) | def in_danger(self, agent):
method is_done (line 1013) | def is_done(self):
function compare_agents (line 1033) | def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
function test_agent (line 1051) | def test_agent(AgentFactory, steps, envs):
FILE: csp.py
class CSP (line 17) | class CSP(search.Problem):
method __init__ (line 54) | def __init__(self, variables, domains, neighbors, constraints):
method assign (line 65) | def assign(self, var, val, assignment):
method unassign (line 70) | def unassign(self, var, assignment):
method nconflicts (line 77) | def nconflicts(self, var, val, assignment):
method display (line 86) | def display(self, assignment):
method actions (line 93) | def actions(self, state):
method result (line 104) | def result(self, state, action):
method goal_test (line 109) | def goal_test(self, state):
method support_pruning (line 118) | def support_pruning(self):
method suppose (line 124) | def suppose(self, var, value):
method prune (line 131) | def prune(self, var, value, removals):
method choices (line 137) | def choices(self, var):
method infer_assignment (line 141) | def infer_assignment(self):
method restore (line 147) | def restore(self, removals):
method conflicted_vars (line 154) | def conflicted_vars(self, current):
function no_arc_heuristic (line 164) | def no_arc_heuristic(csp, queue):
function dom_j_up (line 168) | def dom_j_up(csp, queue):
function AC3 (line 172) | def AC3(csp, queue=None, removals=None, arc_heuristic=dom_j_up):
function revise (line 191) | def revise(csp, Xi, Xj, removals, checks=0):
function AC3b (line 213) | def AC3b(csp, queue=None, removals=None, arc_heuristic=dom_j_up):
function partition (line 263) | def partition(csp, Xi, Xj, checks=0):
function AC4 (line 297) | def AC4(csp, queue=None, removals=None, arc_heuristic=dom_j_up):
function first_unassigned_variable (line 346) | def first_unassigned_variable(assignment, csp):
function mrv (line 351) | def mrv(assignment, csp):
function num_legal_values (line 357) | def num_legal_values(csp, var, assignment):
function unordered_domain_values (line 367) | def unordered_domain_values(var, assignment, csp):
function lcv (line 372) | def lcv(var, assignment, csp):
function no_inference (line 380) | def no_inference(csp, var, value, assignment, removals):
function forward_checking (line 384) | def forward_checking(csp, var, value, assignment, removals):
function mac (line 397) | def mac(csp, var, value, assignment, removals, constraint_propagation=AC...
function backtracking_search (line 405) | def backtracking_search(csp, select_unassigned_variable=first_unassigned...
function min_conflicts (line 434) | def min_conflicts(csp, max_steps=100000):
function min_conflicts_value (line 452) | def min_conflicts_value(csp, var, current):
function tree_csp_solver (line 461) | def tree_csp_solver(csp):
function topological_sort (line 480) | def topological_sort(X, root):
function build_topological (line 507) | def build_topological(node, parent, neighbors, visited, stack, parents):
function make_arc_consistent (line 519) | def make_arc_consistent(Xj, Xk, csp):
function assign_value (line 538) | def assign_value(Xj, Xk, csp, assignment):
class UniversalDict (line 554) | class UniversalDict:
method __init__ (line 562) | def __init__(self, value): self.value = value
method __getitem__ (line 564) | def __getitem__(self, key): return self.value
method __repr__ (line 566) | def __repr__(self): return '{{Any: {0!r}}}'.format(self.value)
function different_values_constraint (line 569) | def different_values_constraint(A, a, B, b):
function MapColoringCSP (line 574) | def MapColoringCSP(colors, neighbors):
function parse_neighbors (line 584) | def parse_neighbors(neighbors):
function queen_constraint (line 628) | def queen_constraint(A, a, B, b):
class NQueensCSP (line 634) | class NQueensCSP(CSP):
method __init__ (line 655) | def __init__(self, n):
method nconflicts (line 664) | def nconflicts(self, var, val, assignment):
method assign (line 674) | def assign(self, var, val, assignment):
method unassign (line 683) | def unassign(self, var, assignment):
method record_conflict (line 689) | def record_conflict(self, assignment, var, val, delta):
method display (line 696) | def display(self, assignment):
function flatten (line 722) | def flatten(seqs):
class Sudoku (line 742) | class Sudoku(CSP):
method __init__ (line 788) | def __init__(self, grid):
method display (line 799) | def display(self, assignment):
function Zebra (line 816) | def Zebra():
function solve_zebra (line 883) | def solve_zebra(algorithm=min_conflicts, **args):
class NaryCSP (line 898) | class NaryCSP:
method __init__ (line 907) | def __init__(self, domains, constraints):
method __str__ (line 919) | def __str__(self):
method display (line 923) | def display(self, assignment=None):
method consistent (line 929) | def consistent(self, assignment):
class Constraint (line 939) | class Constraint:
method __init__ (line 947) | def __init__(self, scope, condition):
method __repr__ (line 951) | def __repr__(self):
method holds (line 954) | def holds(self, assignment):
function all_diff_constraint (line 962) | def all_diff_constraint(*values):
function is_word_constraint (line 967) | def is_word_constraint(words):
function meet_at_constraint (line 976) | def meet_at_constraint(p1, p2):
function adjacent_constraint (line 986) | def adjacent_constraint(x, y):
function sum_constraint (line 991) | def sum_constraint(n):
function is_constraint (line 1001) | def is_constraint(val):
function ne_constraint (line 1011) | def ne_constraint(val):
function no_heuristic (line 1021) | def no_heuristic(to_do):
function sat_up (line 1025) | def sat_up(to_do):
class ACSolver (line 1029) | class ACSolver:
method __init__ (line 1032) | def __init__(self, csp):
method GAC (line 1038) | def GAC(self, orig_domains=None, to_do=None, arc_heuristic=sat_up):
method new_to_do (line 1091) | def new_to_do(self, var, const):
method any_holds (line 1101) | def any_holds(self, domains, const, env, other_vars, ind=0, checks=0):
method domain_splitting (line 1120) | def domain_splitting(self, domains=None, to_do=None, arc_heuristic=sat...
function partition_domain (line 1143) | def partition_domain(dom):
class ACSearchSolver (line 1151) | class ACSearchSolver(search.Problem):
method __init__ (line 1155) | def __init__(self, csp, arc_heuristic=sat_up):
method goal_test (line 1163) | def goal_test(self, node):
method actions (line 1167) | def actions(self, state):
method result (line 1180) | def result(self, state, action):
function ac_solver (line 1184) | def ac_solver(csp, arc_heuristic=sat_up):
function ac_search_solver (line 1189) | def ac_search_solver(csp, arc_heuristic=sat_up):
class Crossword (line 1227) | class Crossword(NaryCSP):
method __init__ (line 1229) | def __init__(self, puzzle, words):
method display (line 1260) | def display(self, assignment=None):
class Kakuro (line 1327) | class Kakuro(NaryCSP):
method __init__ (line 1329) | def __init__(self, puzzle):
method display (line 1382) | def display(self, assignment=None):
FILE: deep_learning4e.py
class Node (line 15) | class Node:
method __init__ (line 22) | def __init__(self, weights=None, value=None):
class Layer (line 27) | class Layer:
method __init__ (line 33) | def __init__(self, size):
method forward (line 36) | def forward(self, inputs):
class Activation (line 41) | class Activation:
method function (line 43) | def function(self, x):
method derivative (line 46) | def derivative(self, x):
method __call__ (line 49) | def __call__(self, x):
class Sigmoid (line 53) | class Sigmoid(Activation):
method function (line 55) | def function(self, x):
method derivative (line 58) | def derivative(self, value):
class ReLU (line 62) | class ReLU(Activation):
method function (line 64) | def function(self, x):
method derivative (line 67) | def derivative(self, value):
class ELU (line 71) | class ELU(Activation):
method __init__ (line 73) | def __init__(self, alpha=0.01):
method function (line 76) | def function(self, x):
method derivative (line 79) | def derivative(self, value):
class LeakyReLU (line 83) | class LeakyReLU(Activation):
method __init__ (line 85) | def __init__(self, alpha=0.01):
method function (line 88) | def function(self, x):
method derivative (line 91) | def derivative(self, value):
class Tanh (line 95) | class Tanh(Activation):
method function (line 97) | def function(self, x):
method derivative (line 100) | def derivative(self, value):
class SoftMax (line 104) | class SoftMax(Activation):
method function (line 106) | def function(self, x):
method derivative (line 109) | def derivative(self, x):
class SoftPlus (line 113) | class SoftPlus(Activation):
method function (line 115) | def function(self, x):
method derivative (line 118) | def derivative(self, x):
class Linear (line 122) | class Linear(Activation):
method function (line 124) | def function(self, x):
method derivative (line 127) | def derivative(self, x):
class InputLayer (line 131) | class InputLayer(Layer):
method __init__ (line 134) | def __init__(self, size=3):
method forward (line 137) | def forward(self, inputs):
class OutputLayer (line 145) | class OutputLayer(Layer):
method __init__ (line 148) | def __init__(self, size=3):
method forward (line 151) | def forward(self, inputs, activation=SoftMax):
class DenseLayer (line 159) | class DenseLayer(Layer):
method __init__ (line 167) | def __init__(self, in_size=3, out_size=3, activation=Sigmoid):
method forward (line 176) | def forward(self, inputs):
class ConvLayer1D (line 187) | class ConvLayer1D(Layer):
method __init__ (line 193) | def __init__(self, size=3, kernel_size=3):
method forward (line 199) | def forward(self, features):
class MaxPoolingLayer1D (line 211) | class MaxPoolingLayer1D(Layer):
method __init__ (line 217) | def __init__(self, size=3, kernel_size=3):
method forward (line 222) | def forward(self, features):
class BatchNormalizationLayer (line 237) | class BatchNormalizationLayer(Layer):
method __init__ (line 240) | def __init__(self, size, eps=0.001):
method forward (line 247) | def forward(self, inputs):
function init_examples (line 262) | def init_examples(examples, idx_i, idx_t, o_units):
function stochastic_gradient_descent (line 282) | def stochastic_gradient_descent(dataset, net, loss, epochs=1000, l_rate=...
function adam (line 314) | def adam(dataset, net, loss, epochs=1000, rho=(0.9, 0.999), delta=1 / 10...
function BackPropagation (line 371) | def BackPropagation(inputs, targets, theta, net, loss):
function get_batch (line 425) | def get_batch(examples, batch_size=1):
class NeuralNetworkLearner (line 431) | class NeuralNetworkLearner:
method __init__ (line 437) | def __init__(self, dataset, hidden_layer_sizes, l_rate=0.01, epochs=10...
method fit (line 461) | def fit(self, X, y):
method predict (line 466) | def predict(self, example):
class PerceptronLearner (line 480) | class PerceptronLearner:
method __init__ (line 485) | def __init__(self, dataset, l_rate=0.01, epochs=1000, batch_size=10, o...
method fit (line 502) | def fit(self, X, y):
method predict (line 507) | def predict(self, example):
function keras_dataset_loader (line 512) | def keras_dataset_loader(dataset, max_length=500):
function SimpleRNNLearner (line 526) | def SimpleRNNLearner(train_data, val_data, epochs=2, verbose=False):
function AutoencoderLearner (line 558) | def AutoencoderLearner(inputs, encoding_size, epochs=200, verbose=False):
FILE: games.py
function minmax_decision (line 20) | def minmax_decision(state, game):
function expect_minmax (line 49) | def expect_minmax(state, game):
function alpha_beta_search (line 89) | def alpha_beta_search(state, game):
function alpha_beta_cutoff_search (line 130) | def alpha_beta_cutoff_search(state, game, d=4, cutoff_test=None, eval_fn...
function query_player (line 178) | def query_player(game, state):
function random_player (line 196) | def random_player(game, state):
function alpha_beta_player (line 201) | def alpha_beta_player(game, state):
function minmax_player (line 205) | def minmax_player(game,state):
function expect_minmax_player (line 209) | def expect_minmax_player(game, state):
class Game (line 217) | class Game:
method actions (line 226) | def actions(self, state):
method result (line 230) | def result(self, state, move):
method utility (line 234) | def utility(self, state, player):
method terminal_test (line 238) | def terminal_test(self, state):
method to_move (line 242) | def to_move(self, state):
method display (line 246) | def display(self, state):
method __repr__ (line 250) | def __repr__(self):
method play_game (line 253) | def play_game(self, *players):
class StochasticGame (line 265) | class StochasticGame(Game):
method chances (line 271) | def chances(self, state):
method outcome (line 275) | def outcome(self, state, chance):
method probability (line 279) | def probability(self, chance):
method play_game (line 283) | def play_game(self, *players):
class Fig52Game (line 297) | class Fig52Game(Game):
method actions (line 307) | def actions(self, state):
method result (line 310) | def result(self, state, move):
method utility (line 313) | def utility(self, state, player):
method terminal_test (line 319) | def terminal_test(self, state):
method to_move (line 322) | def to_move(self, state):
class Fig52Extended (line 326) | class Fig52Extended(Game):
method actions (line 332) | def actions(self, state):
method result (line 335) | def result(self, state, move):
method utility (line 338) | def utility(self, state, player):
method terminal_test (line 344) | def terminal_test(self, state):
method to_move (line 347) | def to_move(self, state):
class TicTacToe (line 351) | class TicTacToe(Game):
method __init__ (line 357) | def __init__(self, h=3, v=3, k=3):
method actions (line 365) | def actions(self, state):
method result (line 369) | def result(self, state, move):
method utility (line 380) | def utility(self, state, player):
method terminal_test (line 384) | def terminal_test(self, state):
method display (line 388) | def display(self, state):
method compute_utility (line 395) | def compute_utility(self, board, move, player):
method k_in_row (line 405) | def k_in_row(self, board, move, player, delta_x_y):
class ConnectFour (line 421) | class ConnectFour(TicTacToe):
method __init__ (line 426) | def __init__(self, h=7, v=6, k=4):
method actions (line 429) | def actions(self, state):
class Gomoku (line 433) | class Gomoku(TicTacToe):
method __init__ (line 436) | def __init__(self, h=15, v=16, k=5):
class Backgammon (line 440) | class Backgammon(StochasticGame):
method __init__ (line 445) | def __init__(self):
method actions (line 460) | def actions(self, state):
method result (line 473) | def result(self, state, move):
method utility (line 485) | def utility(self, state, player):
method terminal_test (line 489) | def terminal_test(self, state):
method get_all_moves (line 493) | def get_all_moves(self, board, player):
method display (line 507) | def display(self, state):
method compute_utility (line 516) | def compute_utility(self, board, move, player):
method checkers_at_home (line 524) | def checkers_at_home(self, board, player):
method is_legal_move (line 532) | def is_legal_move(self, board, start, steps, player):
method move_checker (line 558) | def move_checker(self, board, start, steps, player):
method is_point_open (line 568) | def is_point_open(self, player, point):
method chances (line 575) | def chances(self, state):
method outcome (line 580) | def outcome(self, state, chance):
method probability (line 588) | def probability(self, chance):
FILE: games4e.py
function minmax_decision (line 20) | def minmax_decision(state, game):
function expect_minmax (line 49) | def expect_minmax(state, game):
function alpha_beta_search (line 89) | def alpha_beta_search(state, game):
function alpha_beta_cutoff_search (line 130) | def alpha_beta_cutoff_search(state, game, d=4, cutoff_test=None, eval_fn...
function monte_carlo_tree_search (line 178) | def monte_carlo_tree_search(state, game, N=1000):
function query_player (line 229) | def query_player(game, state):
function random_player (line 247) | def random_player(game, state):
function alpha_beta_player (line 252) | def alpha_beta_player(game, state):
function expect_min_max_player (line 256) | def expect_min_max_player(game, state):
function mcts_player (line 260) | def mcts_player(game, state):
class Game (line 268) | class Game:
method actions (line 277) | def actions(self, state):
method result (line 281) | def result(self, state, move):
method utility (line 285) | def utility(self, state, player):
method terminal_test (line 289) | def terminal_test(self, state):
method to_move (line 293) | def to_move(self, state):
method display (line 297) | def display(self, state):
method __repr__ (line 301) | def __repr__(self):
method play_game (line 304) | def play_game(self, *players):
class StochasticGame (line 316) | class StochasticGame(Game):
method chances (line 322) | def chances(self, state):
method outcome (line 326) | def outcome(self, state, chance):
method probability (line 330) | def probability(self, chance):
method play_game (line 334) | def play_game(self, *players):
class Fig52Game (line 348) | class Fig52Game(Game):
method actions (line 358) | def actions(self, state):
method result (line 361) | def result(self, state, move):
method utility (line 364) | def utility(self, state, player):
method terminal_test (line 370) | def terminal_test(self, state):
method to_move (line 373) | def to_move(self, state):
class Fig52Extended (line 377) | class Fig52Extended(Game):
method actions (line 383) | def actions(self, state):
method result (line 386) | def result(self, state, move):
method utility (line 389) | def utility(self, state, player):
method terminal_test (line 395) | def terminal_test(self, state):
method to_move (line 398) | def to_move(self, state):
class TicTacToe (line 402) | class TicTacToe(Game):
method __init__ (line 408) | def __init__(self, h=3, v=3, k=3):
method actions (line 416) | def actions(self, state):
method result (line 420) | def result(self, state, move):
method utility (line 431) | def utility(self, state, player):
method terminal_test (line 435) | def terminal_test(self, state):
method display (line 439) | def display(self, state):
method compute_utility (line 446) | def compute_utility(self, board, move, player):
method k_in_row (line 456) | def k_in_row(self, board, move, player, delta_x_y):
class ConnectFour (line 472) | class ConnectFour(TicTacToe):
method __init__ (line 477) | def __init__(self, h=7, v=6, k=4):
method actions (line 480) | def actions(self, state):
class Backgammon (line 485) | class Backgammon(StochasticGame):
method __init__ (line 490) | def __init__(self):
method actions (line 505) | def actions(self, state):
method result (line 518) | def result(self, state, move):
method utility (line 530) | def utility(self, state, player):
method terminal_test (line 534) | def terminal_test(self, state):
method get_all_moves (line 538) | def get_all_moves(self, board, player):
method display (line 552) | def display(self, state):
method compute_utility (line 561) | def compute_utility(self, board, move, player):
method checkers_at_home (line 569) | def checkers_at_home(self, board, player):
method is_legal_move (line 577) | def is_legal_move(self, board, start, steps, player):
method move_checker (line 603) | def move_checker(self, board, start, steps, player):
method is_point_open (line 613) | def is_point_open(self, player, point):
method chances (line 620) | def chances(self, state):
method outcome (line 625) | def outcome(self, state, chance):
method probability (line 633) | def probability(self, chance):
FILE: gui/eight_puzzle.py
function scramble (line 22) | def scramble():
function solve (line 39) | def solve():
function solve_steps (line 45) | def solve_steps():
function exchange (line 61) | def exchange(index):
function create_buttons (line 97) | def create_buttons():
function create_static_buttons (line 130) | def create_static_buttons():
function init (line 139) | def init():
FILE: gui/genetic_algorithm_example.py
function update_max_population (line 55) | def update_max_population(slider_value):
function update_mutation_rate (line 60) | def update_mutation_rate(slider_value):
function update_f_thres (line 65) | def update_f_thres(slider_value):
function update_ngen (line 70) | def update_ngen(slider_value):
function fitness_fn (line 76) | def fitness_fn(_list):
function raise_frame (line 88) | def raise_frame(frame, init=False, update_target=False, target_entry=Non...
function genetic_algorithm_stepwise (line 145) | def genetic_algorithm_stepwise(population):
FILE: gui/grid_mdp.py
function extents (line 43) | def extents(f):
function display (line 50) | def display(gridmdp, _height, _width):
function display_best_policy (line 67) | def display_best_policy(_best_policy, _height, _width):
function initialize_dialogbox (line 83) | def initialize_dialogbox(_width, _height, gridmdp, terminals, buttons):
function update_table (line 132) | def update_table(i, j, gridmdp, terminals, buttons, reward, term, wall, ...
function initialize_update_table (line 166) | def initialize_update_table(_width, _height, gridmdp, terminals, buttons...
function reset_all (line 176) | def reset_all(_height, i, j, gridmdp, terminals, buttons, reward, term, ...
function initialize_reset_all (line 197) | def initialize_reset_all(_width, _height, gridmdp, terminals, buttons, r...
function external_reset (line 207) | def external_reset(_width, _height, gridmdp, terminals, buttons):
function widget_disability_checks (line 216) | def widget_disability_checks(i, j, gridmdp, terminals, label_reward, ent...
function flatten_list (line 231) | def flatten_list(_list):
function initialize_widget_disability_checks (line 236) | def initialize_widget_disability_checks(_width, _height, gridmdp, termin...
function dialogbox (line 268) | def dialogbox(i, j, gridmdp, terminals, buttons, _height):
class MDPapp (line 320) | class MDPapp(tk.Tk):
method __init__ (line 322) | def __init__(self, *args, **kwargs):
method placeholder_function (line 365) | def placeholder_function(self):
method exit (line 370) | def exit(self):
method new (line 375) | def new(self):
method get_page (line 385) | def get_page(self, page_class):
method view_matrix (line 389) | def view_matrix(self):
method view_terminals (line 398) | def view_terminals(self):
method initialize (line 403) | def initialize(self):
method master_reset (line 409) | def master_reset(self):
method build (line 414) | def build(self):
method show_frame (line 429) | def show_frame(self, controller, cb=False):
class HomePage (line 438) | class HomePage(tk.Frame):
method __init__ (line 440) | def __init__(self, parent, controller):
class BuildMDP (line 505) | class BuildMDP(tk.Frame):
method __init__ (line 507) | def __init__(self, parent, controller):
method create_buttons (line 516) | def create_buttons(self):
method initialize (line 543) | def initialize(self):
method master_reset (line 550) | def master_reset(self):
class SolveMDP (line 558) | class SolveMDP(tk.Frame):
method __init__ (line 560) | def __init__(self, parent, controller):
method process_data (line 573) | def process_data(self, terminals, _height, _width, gridmdp):
method create_graph (line 595) | def create_graph(self, gridmdp, terminals, _height, _width):
method animate_graph (line 612) | def animate_graph(self, i):
method initialize_value_iteration_parameters (line 651) | def initialize_value_iteration_parameters(self, mdp):
method value_iteration_metastep (line 656) | def value_iteration_metastep(self, mdp, iterations=20):
FILE: gui/romania_problem.py
function create_map (line 24) | def create_map(root):
function make_line (line 256) | def make_line(map, x0, y0, x1, y1, distance):
function make_rectangle (line 262) | def make_rectangle(map, x0, y0, margin, city_name):
function make_legend (line 287) | def make_legend(map):
function tree_search (line 304) | def tree_search(problem):
function graph_search (line 332) | def graph_search(problem):
function display_frontier (line 363) | def display_frontier(queue):
function display_current (line 374) | def display_current(node):
function display_explored (line 381) | def display_explored(node):
function display_final (line 388) | def display_final(cities):
function breadth_first_tree_search (line 395) | def breadth_first_tree_search(problem):
function depth_first_tree_search (line 420) | def depth_first_tree_search(problem):
function breadth_first_graph_search (line 446) | def breadth_first_graph_search(problem):
function depth_first_graph_search (line 475) | def depth_first_graph_search(problem):
function best_first_graph_search (line 503) | def best_first_graph_search(problem, f):
function uniform_cost_search (line 543) | def uniform_cost_search(problem):
function astar_search (line 548) | def astar_search(problem, h=None):
function on_click (line 559) | def on_click():
function reset_map (line 615) | def reset_map():
FILE: gui/tic-tac-toe.py
function create_frames (line 22) | def create_frames(root):
function create_buttons (line 55) | def create_buttons(frame):
function on_click (line 71) | def on_click(button):
function check_victory (line 127) | def check_victory(button):
function get_coordinates (line 165) | def get_coordinates(button):
function get_button (line 176) | def get_button(x, y):
function reset_game (line 184) | def reset_game():
function disable_game (line 199) | def disable_game():
function exit_game (line 209) | def exit_game(root):
FILE: gui/tsp.py
class TSProblem (line 12) | class TSProblem(Problem):
method two_opt (line 15) | def two_opt(self, state):
method actions (line 25) | def actions(self, state):
method result (line 29) | def result(self, state, action):
method path_cost (line 33) | def path_cost(self, c, state1, action, state2):
method value (line 41) | def value(self, state):
class TSPGui (line 46) | class TSPGui():
method __init__ (line 52) | def __init__(self, root, all_cities):
method create_checkboxes (line 67) | def create_checkboxes(self, side=LEFT, anchor=W):
method create_buttons (line 85) | def create_buttons(self):
method create_dropdown_menu (line 93) | def create_dropdown_menu(self):
method run_traveling_salesman (line 102) | def run_traveling_salesman(self):
method calculate_canvas_size (line 114) | def calculate_canvas_size(self):
method create_canvas (line 137) | def create_canvas(self, problem):
method exp_schedule (line 189) | def exp_schedule(k=100, lam=0.03, limit=1000):
method simulated_annealing_with_tunable_T (line 194) | def simulated_annealing_with_tunable_T(self, problem, map_canvas, sche...
method genetic_algorithm (line 221) | def genetic_algorithm(self, problem, map_canvas):
method hill_climbing (line 281) | def hill_climbing(self, problem, map_canvas):
method on_closing (line 315) | def on_closing(self):
FILE: gui/vacuum_agent.py
class Gui (line 11) | class Gui(Environment):
method __init__ (line 16) | def __init__(self, root, height=300, width=380):
method thing_classes (line 28) | def thing_classes(self):
method percept (line 33) | def percept(self, agent):
method execute_action (line 37) | def execute_action(self, agent, action):
method default_location (line 55) | def default_location(self, thing):
method create_canvas (line 59) | def create_canvas(self):
method create_buttons (line 68) | def create_buttons(self):
method dirt_switch (line 79) | def dirt_switch(self, button):
method read_env (line 87) | def read_env(self):
method update_env (line 101) | def update_env(self, agent):
function create_agent (line 112) | def create_agent(env, agent):
function move_agent (line 124) | def move_agent(env, agent, before_step):
FILE: gui/xy_vacuum_environment.py
class Gui (line 9) | class Gui(VacuumEnvironment):
method __init__ (line 16) | def __init__(self, root, width=7, height=7, elements=None):
method create_frames (line 26) | def create_frames(self):
method create_buttons (line 34) | def create_buttons(self):
method create_walls (line 47) | def create_walls(self):
method display_element (line 63) | def display_element(self, button):
method execute_action (line 74) | def execute_action(self, agent, action):
method read_env (line 105) | def read_env(self):
method update_env (line 119) | def update_env(self):
method reset_env (line 128) | def reset_env(self, agt):
function XYReflexAgentProgram (line 143) | def XYReflexAgentProgram(percept):
class XYReflexAgent (line 162) | class XYReflexAgent(Agent):
method __init__ (line 165) | def __init__(self, program=None):
FILE: ipyviews.py
class ContinuousWorldView (line 28) | class ContinuousWorldView:
method __init__ (line 31) | def __init__(self, world, fill="#AAA"):
method object_name (line 37) | def object_name(self):
method handle_add_obstacle (line 44) | def handle_add_obstacle(self, vertices):
method handle_remove_obstacle (line 51) | def handle_remove_obstacle(self):
method get_polygon_obstacles_coordinates (line 54) | def get_polygon_obstacles_coordinates(self):
method show (line 61) | def show(self):
class GridWorldView (line 89) | class GridWorldView:
method __init__ (line 96) | def __init__(self, world, block_size=30, default_fill="white"):
method object_name (line 103) | def object_name(self):
method set_label (line 110) | def set_label(self, coordinates, label):
method set_representation (line 117) | def set_representation(self, thing, repr_type, source):
method handle_click (line 129) | def handle_click(self, coordinates):
method map_to_render (line 134) | def map_to_render(self):
method show (line 152) | def show(self):
FILE: js/canvas.js
function output_callback (line 9) | function output_callback(out, block){
function click_callback (line 23) | function click_callback(element, event, varname){
function rgbToHex (line 33) | function rgbToHex(r,g,b){
function toRad (line 40) | function toRad(x){
function Canvas (line 45) | function Canvas(id){
FILE: js/continuousworld.js
function handle_output (line 2) | function handle_output(out, block){
function polygon_complete (line 6) | function polygon_complete(canvas, vertices){
function drawPolygon (line 16) | function drawPolygon(array) {
function getPosition (line 28) | function getPosition(obj,event) {
function drawPoint (line 55) | function drawPoint(x, y) {
function initalizeObstacles (line 62) | function initalizeObstacles(objects) {
FILE: js/gridworld.js
function handle_output (line 3) | function handle_output(out, block){
function handle_click (line 8) | function handle_click(canvas,coord) {
function generateGridWorld (line 21) | function generateGridWorld(state,size,elements)
FILE: knowledge.py
function current_best_learning (line 15) | def current_best_learning(examples, h, examples_so_far=None):
function specializations (line 43) | def specializations(examples_so_far, h):
function generalizations (line 64) | def generalizations(examples_so_far, h):
function add_or (line 102) | def add_or(examples_so_far, h):
function version_space_learning (line 127) | def version_space_learning(examples):
function version_space_update (line 141) | def version_space_update(V, e):
function all_hypotheses (line 145) | def all_hypotheses(examples):
function values_table (line 158) | def values_table(examples):
function build_attr_combinations (line 179) | def build_attr_combinations(s, values):
function build_h_combinations (line 203) | def build_h_combinations(hypotheses):
function minimal_consistent_det (line 221) | def minimal_consistent_det(E, A):
function consistent_det (line 231) | def consistent_det(A, E):
class FOILContainer (line 247) | class FOILContainer(FolKB):
method __init__ (line 250) | def __init__(self, clauses=None):
method tell (line 255) | def tell(self, sentence):
method foil (line 263) | def foil(self, examples, target):
method new_clause (line 280) | def new_clause(self, examples, target):
method extend_example (line 295) | def extend_example(self, example, literal):
method new_literals (line 302) | def new_literals(self, clause):
method choose_literal (line 316) | def choose_literal(self, literals, examples):
method gain (line 320) | def gain(self, l, examples):
method update_examples (line 352) | def update_examples(self, target, examples, extended_examples):
function check_all_consistency (line 369) | def check_all_consistency(examples, h):
function check_negative_consistency (line 378) | def check_negative_consistency(examples, h):
function disjunction_value (line 390) | def disjunction_value(e, d):
function guess_value (line 404) | def guess_value(e, h):
function is_consistent (line 413) | def is_consistent(e, h):
function false_positive (line 417) | def false_positive(e, h):
function false_negative (line 421) | def false_negative(e, h):
FILE: learning.py
class DataSet (line 13) | class DataSet:
method __init__ (line 40) | def __init__(self, examples=None, attrs=None, attr_names=None, target=...
method set_problem (line 76) | def set_problem(self, target, inputs=None, exclude=()):
method check_me (line 94) | def check_me(self):
method add_example (line 104) | def add_example(self, example):
method check_example (line 109) | def check_example(self, example):
method attr_num (line 117) | def attr_num(self, attr):
method update_values (line 126) | def update_values(self):
method sanitize (line 129) | def sanitize(self, example):
method classes_to_numbers (line 133) | def classes_to_numbers(self, classes=None):
method remove_examples (line 141) | def remove_examples(self, value=''):
method split_values_by_classes (line 146) | def split_values_by_classes(self):
method find_means_and_deviations (line 157) | def find_means_and_deviations(self):
method __repr__ (line 187) | def __repr__(self):
function parse_csv (line 191) | def parse_csv(input, delim=','):
function err_ratio (line 204) | def err_ratio(predict, dataset, examples=None):
function grade_learner (line 221) | def grade_learner(predict, tests):
function train_test_split (line 229) | def train_test_split(dataset, start=None, end=None, test_split=None):
function cross_validation_wrapper (line 252) | def cross_validation_wrapper(learner, dataset, k=10, trials=1):
function cross_validation (line 278) | def cross_validation(learner, dataset, size=None, k=10, trials=1):
function leave_one_out (line 311) | def leave_one_out(learner, dataset, size=None):
function learning_curve (line 316) | def learning_curve(learner, dataset, trials=10, sizes=None):
function PluralityLearner (line 327) | def PluralityLearner(dataset):
class DecisionFork (line 341) | class DecisionFork:
method __init__ (line 347) | def __init__(self, attr, attr_name=None, default_child=None, branches=...
method __call__ (line 354) | def __call__(self, example):
method add (line 363) | def add(self, val, subtree):
method display (line 367) | def display(self, indent=0):
method __repr__ (line 374) | def __repr__(self):
class DecisionLeaf (line 378) | class DecisionLeaf:
method __init__ (line 381) | def __init__(self, result):
method __call__ (line 384) | def __call__(self, example):
method display (line 387) | def display(self):
method __repr__ (line 390) | def __repr__(self):
function DecisionTreeLearner (line 394) | def DecisionTreeLearner(dataset):
function information_content (line 451) | def information_content(values):
function DecisionListLearner (line 457) | def DecisionListLearner(dataset):
function NearestNeighborLearner (line 493) | def NearestNeighborLearner(dataset, k=1):
function LinearLearner (line 504) | def LinearLearner(dataset, learning_rate=0.01, epochs=100):
function LogisticLinearLeaner (line 545) | def LogisticLinearLeaner(dataset, learning_rate=0.01, epochs=100):
function NeuralNetLearner (line 589) | def NeuralNetLearner(dataset, hidden_layer_sizes=None, learning_rate=0.0...
function BackPropagationLearner (line 629) | def BackPropagationLearner(dataset, net, learning_rate, epochs, activati...
function PerceptronLearner (line 731) | def PerceptronLearner(dataset, learning_rate=0.01, epochs=100):
class NNUnit (line 753) | class NNUnit:
method __init__ (line 760) | def __init__(self, activation=sigmoid, weights=None, inputs=None):
function network (line 767) | def network(input_units, hidden_layer_sizes, output_units, activation=si...
function init_examples (line 787) | def init_examples(examples, idx_i, idx_t, o_units):
function find_max_node (line 806) | def find_max_node(nodes):
class SVC (line 810) | class SVC:
method __init__ (line 812) | def __init__(self, kernel=linear_kernel, C=1.0, verbose=False):
method fit (line 821) | def fit(self, X, y):
method solve_qp (line 842) | def solve_qp(self, X, y):
method predict_score (line 860) | def predict_score(self, X):
method predict (line 868) | def predict(self, X):
class SVR (line 875) | class SVR:
method __init__ (line 877) | def __init__(self, kernel=linear_kernel, C=1.0, epsilon=0.1, verbose=F...
method fit (line 887) | def fit(self, X, y):
method solve_qp (line 912) | def solve_qp(self, X, y):
method predict (line 934) | def predict(self, X):
class MultiClassLearner (line 940) | class MultiClassLearner:
method __init__ (line 942) | def __init__(self, clf, decision_function='ovr'):
method fit (line 947) | def fit(self, X, y):
method predict (line 978) | def predict(self, X):
function EnsembleLearner (line 1005) | def EnsembleLearner(learners):
function ada_boost (line 1019) | def ada_boost(dataset, L, K):
function weighted_majority (line 1041) | def weighted_majority(predictors, weights):
function weighted_mode (line 1050) | def weighted_mode(values, weights):
function RandomForest (line 1062) | def RandomForest(dataset, n=5):
function WeightedLearner (line 1086) | def WeightedLearner(unweighted_learner):
function replicated_dataset (line 1099) | def replicated_dataset(dataset, weights, n=None):
function weighted_replicate (line 1107) | def weighted_replicate(seq, weights, n):
function accuracy_score (line 1125) | def accuracy_score(y_pred, y_true):
function r2_score (line 1130) | def r2_score(y_pred, y_true):
function RestaurantDataSet (line 1147) | def RestaurantDataSet(examples=None):
function T (line 1159) | def T(attr_name, branches):
function SyntheticRestaurant (line 1189) | def SyntheticRestaurant(n=20):
function Majority (line 1200) | def Majority(k, n):
function Parity (line 1213) | def Parity(k, n, name='parity'):
function Xor (line 1226) | def Xor(n):
function ContinuousXor (line 1231) | def ContinuousXor(n):
function compare (line 1240) | def compare(algorithms=None, datasets=None, k=10, trials=1):
FILE: learning4e.py
class DataSet (line 14) | class DataSet:
method __init__ (line 41) | def __init__(self, examples=None, attrs=None, attr_names=None, target=...
method set_problem (line 77) | def set_problem(self, target, inputs=None, exclude=()):
method check_me (line 95) | def check_me(self):
method add_example (line 105) | def add_example(self, example):
method check_example (line 110) | def check_example(self, example):
method attr_num (line 118) | def attr_num(self, attr):
method update_values (line 127) | def update_values(self):
method sanitize (line 130) | def sanitize(self, example):
method classes_to_numbers (line 134) | def classes_to_numbers(self, classes=None):
method remove_examples (line 142) | def remove_examples(self, value=''):
method split_values_by_classes (line 147) | def split_values_by_classes(self):
method find_means_and_deviations (line 158) | def find_means_and_deviations(self):
method __repr__ (line 188) | def __repr__(self):
function parse_csv (line 192) | def parse_csv(input, delim=','):
function err_ratio (line 205) | def err_ratio(learner, dataset, examples=None):
function grade_learner (line 222) | def grade_learner(learner, tests):
function train_test_split (line 230) | def train_test_split(dataset, start=None, end=None, test_split=None):
function model_selection (line 253) | def model_selection(learner, dataset, k=10, trials=1):
function cross_validation (line 278) | def cross_validation(learner, dataset, size=None, k=10, trials=1):
function leave_one_out (line 307) | def leave_one_out(learner, dataset, size=None):
function learning_curve (line 312) | def learning_curve(learner, dataset, trials=10, sizes=None):
class PluralityLearner (line 323) | class PluralityLearner:
method __init__ (line 329) | def __init__(self, dataset):
method predict (line 332) | def predict(self, example):
class DecisionFork (line 337) | class DecisionFork:
method __init__ (line 343) | def __init__(self, attr, attr_name=None, default_child=None, branches=...
method __call__ (line 350) | def __call__(self, example):
method add (line 359) | def add(self, val, subtree):
method display (line 363) | def display(self, indent=0):
method __repr__ (line 370) | def __repr__(self):
class DecisionLeaf (line 374) | class DecisionLeaf:
method __init__ (line 377) | def __init__(self, result):
method __call__ (line 380) | def __call__(self, example):
method display (line 383) | def display(self):
method __repr__ (line 386) | def __repr__(self):
class DecisionTreeLearner (line 390) | class DecisionTreeLearner:
method __init__ (line 393) | def __init__(self, dataset):
method decision_tree_learning (line 397) | def decision_tree_learning(self, examples, attrs, parent_examples=()):
method plurality_value (line 411) | def plurality_value(self, examples):
method count (line 420) | def count(self, attr, val, examples):
method all_same_class (line 424) | def all_same_class(self, examples):
method choose_attribute (line 429) | def choose_attribute(self, attrs, examples):
method information_gain (line 433) | def information_gain(self, attr, examples):
method split_by (line 445) | def split_by(self, attr, examples):
method predict (line 449) | def predict(self, x):
function information_content (line 453) | def information_content(values):
class DecisionListLearner (line 459) | class DecisionListLearner:
method __init__ (line 465) | def __init__(self, dataset):
method decision_list_learning (line 468) | def decision_list_learning(self, examples):
method find_examples (line 476) | def find_examples(self, examples):
method passes (line 483) | def passes(self, example, test):
method predict (line 487) | def predict(self, example):
class NearestNeighborLearner (line 494) | class NearestNeighborLearner:
method __init__ (line 497) | def __init__(self, dataset, k=1):
method predict (line 501) | def predict(self, example):
class SVC (line 507) | class SVC:
method __init__ (line 509) | def __init__(self, kernel=linear_kernel, C=1.0, verbose=False):
method fit (line 518) | def fit(self, X, y):
method solve_qp (line 539) | def solve_qp(self, X, y):
method predict_score (line 557) | def predict_score(self, X):
method predict (line 565) | def predict(self, X):
class SVR (line 572) | class SVR:
method __init__ (line 574) | def __init__(self, kernel=linear_kernel, C=1.0, epsilon=0.1, verbose=F...
method fit (line 584) | def fit(self, X, y):
method solve_qp (line 609) | def solve_qp(self, X, y):
method predict (line 630) | def predict(self, X):
class MultiClassLearner (line 636) | class MultiClassLearner:
method __init__ (line 638) | def __init__(self, clf, decision_function='ovr'):
method fit (line 643) | def fit(self, X, y):
method predict (line 674) | def predict(self, X):
function LinearLearner (line 701) | def LinearLearner(dataset, learning_rate=0.01, epochs=100):
function LogisticLinearLeaner (line 742) | def LogisticLinearLeaner(dataset, learning_rate=0.01, epochs=100):
class EnsembleLearner (line 786) | class EnsembleLearner:
method __init__ (line 789) | def __init__(self, learners):
method train (line 792) | def train(self, dataset):
method predict (line 795) | def predict(self, example):
function ada_boost (line 799) | def ada_boost(dataset, L, K):
class weighted_majority (line 821) | class weighted_majority:
method __init__ (line 824) | def __init__(self, predictors, weights):
method predict (line 828) | def predict(self, example):
function weighted_mode (line 832) | def weighted_mode(values, weights):
class RandomForest (line 844) | class RandomForest:
method __init__ (line 847) | def __init__(self, dataset, n=5):
method data_bagging (line 854) | def data_bagging(self, m=0):
method feature_bagging (line 859) | def feature_bagging(self, p=0.7):
method predict (line 864) | def predict(self, example):
function WeightedLearner (line 868) | def WeightedLearner(unweighted_learner):
function replicated_dataset (line 885) | def replicated_dataset(dataset, weights, n=None):
function weighted_replicate (line 893) | def weighted_replicate(seq, weights, n):
function accuracy_score (line 911) | def accuracy_score(y_pred, y_true):
function r2_score (line 916) | def r2_score(y_pred, y_true):
function RestaurantDataSet (line 933) | def RestaurantDataSet(examples=None):
function T (line 945) | def T(attr_name, branches):
function SyntheticRestaurant (line 975) | def SyntheticRestaurant(n=20):
function Majority (line 986) | def Majority(k, n):
function Parity (line 999) | def Parity(k, n, name='parity'):
function Xor (line 1012) | def Xor(n):
function ContinuousXor (line 1017) | def ContinuousXor(n):
function compare (line 1026) | def compare(algorithms=None, datasets=None, k=10, trials=1):
FILE: logic.py
class KB (line 48) | class KB:
method __init__ (line 59) | def __init__(self, sentence=None):
method tell (line 63) | def tell(self, sentence):
method ask (line 67) | def ask(self, query):
method ask_generator (line 71) | def ask_generator(self, query):
method retract (line 75) | def retract(self, sentence):
class PropKB (line 80) | class PropKB(KB):
method __init__ (line 83) | def __init__(self, sentence=None):
method tell (line 87) | def tell(self, sentence):
method ask_generator (line 91) | def ask_generator(self, query):
method ask_if_true (line 96) | def ask_if_true(self, query):
method retract (line 102) | def retract(self, sentence):
function KBAgentProgram (line 112) | def KBAgentProgram(kb):
function is_symbol (line 138) | def is_symbol(s):
function is_var_symbol (line 146) | def is_var_symbol(s):
function is_prop_symbol (line 154) | def is_prop_symbol(s):
function variables (line 162) | def variables(s):
function is_definite_clause (line 170) | def is_definite_clause(s):
function parse_definite_clause (line 186) | def parse_definite_clause(s):
function tt_entails (line 203) | def tt_entails(kb, alpha):
function tt_check_all (line 217) | def tt_check_all(kb, alpha, symbols, model):
function prop_symbols (line 232) | def prop_symbols(x):
function constant_symbols (line 242) | def constant_symbols(x):
function predicate_symbols (line 252) | def predicate_symbols(x):
function tt_true (line 262) | def tt_true(s):
function pl_true (line 271) | def pl_true(exp, model={}):
function to_cnf (line 332) | def to_cnf(s):
function eliminate_implications (line 348) | def eliminate_implications(s):
function move_not_inwards (line 369) | def move_not_inwards(s):
function distribute_and_over_or (line 393) | def distribute_and_over_or(s):
function associate (line 421) | def associate(op, args):
function dissociate (line 442) | def dissociate(op, args):
function conjuncts (line 461) | def conjuncts(s):
function disjuncts (line 471) | def disjuncts(s):
function pl_resolution (line 484) | def pl_resolution(kb, alpha):
function pl_resolve (line 509) | def pl_resolve(ci, cj):
class PropDefiniteKB (line 522) | class PropDefiniteKB(PropKB):
method tell (line 525) | def tell(self, sentence):
method ask_generator (line 530) | def ask_generator(self, query):
method retract (line 535) | def retract(self, sentence):
method clauses_with_premise (line 538) | def clauses_with_premise(self, p):
function pl_fc_entails (line 544) | def pl_fc_entails(kb, q):
function no_branching_heuristic (line 604) | def no_branching_heuristic(symbols, clauses):
function min_clauses (line 608) | def min_clauses(clauses):
function moms (line 613) | def moms(symbols, clauses):
function momsf (line 622) | def momsf(symbols, clauses, k=0):
function posit (line 635) | def posit(symbols, clauses):
function zm (line 646) | def zm(symbols, clauses):
function dlis (line 655) | def dlis(symbols, clauses):
function dlcs (line 666) | def dlcs(symbols, clauses):
function jw (line 679) | def jw(symbols, clauses):
function jw2 (line 692) | def jw2(symbols, clauses):
function dpll_satisfiable (line 710) | def dpll_satisfiable(s, branching_heuristic=no_branching_heuristic):
function dpll (line 722) | def dpll(clauses, symbols, model, branching_heuristic=no_branching_heuri...
function find_pure_symbol (line 744) | def find_pure_symbol(symbols, clauses):
function find_unit_clause (line 762) | def find_unit_clause(clauses, model):
function unit_clause_assign (line 775) | def unit_clause_assign(clause, model):
function inspect_literal (line 798) | def inspect_literal(literal):
function no_restart (line 817) | def no_restart(conflicts, restarts, queue_lbd, sum_lbd):
function luby (line 821) | def luby(conflicts, restarts, queue_lbd, sum_lbd, unit=512):
function glucose (line 835) | def glucose(conflicts, restarts, queue_lbd, sum_lbd, x=100, k=0.7):
function cdcl_satisfiable (line 842) | def cdcl_satisfiable(s, vsids_decay=0.95, restart_strategy=no_restart):
function assign_decision_literal (line 882) | def assign_decision_literal(symbols, model, scores, G, dl):
function unit_propagation (line 890) | def unit_propagation(clauses, symbols, model, G, dl):
function conflict_analysis (line 950) | def conflict_analysis(G, dl):
function pl_binary_resolution (line 967) | def pl_binary_resolution(ci, cj):
function backjump (line 976) | def backjump(symbols, model, G, dl=0):
class TwoWLClauseDatabase (line 984) | class TwoWLClauseDatabase:
method __init__ (line 986) | def __init__(self, clauses):
method get_clauses (line 992) | def get_clauses(self):
method set_first_watched (line 995) | def set_first_watched(self, clause, new_watching):
method set_second_watched (line 999) | def set_second_watched(self, clause, new_watching):
method get_first_watched (line 1003) | def get_first_watched(self, clause):
method get_second_watched (line 1010) | def get_second_watched(self, clause):
method get_pos_watched (line 1017) | def get_pos_watched(self, l):
method get_neg_watched (line 1020) | def get_neg_watched(self, l):
method add (line 1023) | def add(self, clause, model):
method remove (line 1031) | def remove(self, clause):
method update_first_watched (line 1039) | def update_first_watched(self, clause, model):
method update_second_watched (line 1050) | def update_second_watched(self, clause, model):
method __find_new_watching_literal (line 1061) | def __find_new_watching_literal(self, clause, other_watched, model):
method __assign_watching_literals (line 1070) | def __assign_watching_literals(self, clause, model=None):
function WalkSAT (line 1083) | def WalkSAT(clauses, p=0.5, max_flips=10000):
function MapColoringSAT (line 1120) | def MapColoringSAT(colors, neighbors):
function facing_east (line 1170) | def facing_east(time):
function facing_west (line 1174) | def facing_west(time):
function facing_north (line 1178) | def facing_north(time):
function facing_south (line 1182) | def facing_south(time):
function wumpus (line 1186) | def wumpus(x, y):
function pit (line 1190) | def pit(x, y):
function breeze (line 1194) | def breeze(x, y):
function stench (line 1198) | def stench(x, y):
function wumpus_alive (line 1202) | def wumpus_alive(time):
function have_arrow (line 1206) | def have_arrow(time):
function percept_stench (line 1210) | def percept_stench(time):
function percept_breeze (line 1214) | def percept_breeze(time):
function percept_glitter (line 1218) | def percept_glitter(time):
function percept_bump (line 1222) | def percept_bump(time):
function percept_scream (line 1226) | def percept_scream(time):
function move_forward (line 1230) | def move_forward(time):
function shoot (line 1234) | def shoot(time):
function turn_left (line 1238) | def turn_left(time):
function turn_right (line 1242) | def turn_right(time):
function ok_to_move (line 1246) | def ok_to_move(x, y, time):
function location (line 1250) | def location(x, y, time=None):
function implies (line 1259) | def implies(lhs, rhs):
function equiv (line 1263) | def equiv(lhs, rhs):
function new_disjunction (line 1269) | def new_disjunction(sentences):
class WumpusKB (line 1279) | class WumpusKB(PropKB):
method __init__ (line 1284) | def __init__(self, dimrow):
method make_action_sentence (line 1347) | def make_action_sentence(self, action, time):
method make_percept_sentence (line 1356) | def make_percept_sentence(self, percept, time):
method add_temporal_sentences (line 1391) | def add_temporal_sentences(self, time):
method ask_if_true (line 1453) | def ask_if_true(self, query):
class WumpusPosition (line 1460) | class WumpusPosition:
method __init__ (line 1461) | def __init__(self, x, y, orientation):
method get_location (line 1466) | def get_location(self):
method set_location (line 1469) | def set_location(self, x, y):
method get_orientation (line 1473) | def get_orientation(self):
method set_orientation (line 1476) | def set_orientation(self, orientation):
method __eq__ (line 1479) | def __eq__(self, other):
class HybridWumpusAgent (line 1489) | class HybridWumpusAgent(Agent):
method __init__ (line 1495) | def __init__(self, dimentions):
method execute (line 1503) | def execute(self, percept):
method plan_route (line 1587) | def plan_route(self, current, goals, allowed):
method plan_shot (line 1591) | def plan_shot(self, current, goals, allowed):
function SAT_plan (line 1622) | def SAT_plan(init, transition, goal, t_max, SAT_solver=cdcl_satisfiable):
function unify (line 1711) | def unify(x, y, s={}):
function is_variable (line 1740) | def is_variable(x):
function unify_var (line 1745) | def unify_var(var, x, s):
function occur_check (line 1758) | def occur_check(var, x, s):
function subst (line 1774) | def subst(s, x):
function cascade_substitution (line 1791) | def cascade_substitution(s):
function unify_mm (line 1810) | def unify_mm(x, y, s={}):
function term_reduction (line 1861) | def term_reduction(x, y, s):
function vars_elimination (line 1873) | def vars_elimination(x, s):
function standardize_variables (line 1884) | def standardize_variables(sentence, dic=None):
function parse_clauses_from_dimacs (line 1907) | def parse_clauses_from_dimacs(dimacs_cnf):
class FolKB (line 1920) | class FolKB(KB):
method __init__ (line 1932) | def __init__(self, clauses=None):
method tell (line 1939) | def tell(self, sentence):
method ask_generator (line 1945) | def ask_generator(self, query):
method retract (line 1948) | def retract(self, sentence):
method fetch_rules_for_goal (line 1951) | def fetch_rules_for_goal(self, goal):
function fol_fc_ask (line 1955) | def fol_fc_ask(kb, alpha):
function fol_bc_ask (line 1994) | def fol_bc_ask(kb, query):
function fol_bc_or (line 2003) | def fol_bc_or(kb, goal, theta):
function fol_bc_and (line 2010) | def fol_bc_and(kb, goals, theta):
function diff (line 2063) | def diff(y, x):
function simp (line 2096) | def simp(x):
function d (line 2159) | def d(y, x):
FILE: logic4e.py
class KB (line 47) | class KB:
method __init__ (line 59) | def __init__(self, sentence=None):
method tell (line 62) | def tell(self, sentence):
method ask (line 66) | def ask(self, query):
method ask_generator (line 70) | def ask_generator(self, query):
method retract (line 74) | def retract(self, sentence):
class PropKB (line 79) | class PropKB(KB):
method __init__ (line 82) | def __init__(self, sentence=None):
method tell (line 87) | def tell(self, sentence):
method ask_generator (line 91) | def ask_generator(self, query):
method ask_if_true (line 96) | def ask_if_true(self, query):
method retract (line 102) | def retract(self, sentence):
function KB_AgentProgram (line 109) | def KB_AgentProgram(KB):
function facing_east (line 139) | def facing_east(time):
function facing_west (line 143) | def facing_west(time):
function facing_north (line 147) | def facing_north(time):
function facing_south (line 151) | def facing_south(time):
function wumpus (line 155) | def wumpus(x, y):
function pit (line 159) | def pit(x, y):
function breeze (line 163) | def breeze(x, y):
function stench (line 167) | def stench(x, y):
function wumpus_alive (line 171) | def wumpus_alive(time):
function have_arrow (line 175) | def have_arrow(time):
function percept_stench (line 179) | def percept_stench(time):
function percept_breeze (line 183) | def percept_breeze(time):
function percept_glitter (line 187) | def percept_glitter(time):
function percept_bump (line 191) | def percept_bump(time):
function percept_scream (line 195) | def percept_scream(time):
function move_forward (line 199) | def move_forward(time):
function shoot (line 203) | def shoot(time):
function turn_left (line 207) | def turn_left(time):
function turn_right (line 211) | def turn_right(time):
function ok_to_move (line 215) | def ok_to_move(x, y, time):
function location (line 219) | def location(x, y, time=None):
function implies (line 229) | def implies(lhs, rhs):
function equiv (line 233) | def equiv(lhs, rhs):
function new_disjunction (line 240) | def new_disjunction(sentences):
function is_symbol (line 251) | def is_symbol(s):
function is_var_symbol (line 259) | def is_var_symbol(s):
function is_prop_symbol (line 267) | def is_prop_symbol(s):
function variables (line 275) | def variables(s):
function is_definite_clause (line 283) | def is_definite_clause(s):
function parse_definite_clause (line 301) | def parse_definite_clause(s):
function tt_entails (line 319) | def tt_entails(kb, alpha):
function tt_check_all (line 332) | def tt_check_all(kb, alpha, symbols, model):
function prop_symbols (line 347) | def prop_symbols(x):
function constant_symbols (line 357) | def constant_symbols(x):
function predicate_symbols (line 367) | def predicate_symbols(x):
function tt_true (line 379) | def tt_true(s):
function pl_true (line 388) | def pl_true(exp, model={}):
function to_cnf (line 449) | def to_cnf(s):
function eliminate_implications (line 463) | def eliminate_implications(s):
function move_not_inwards (line 484) | def move_not_inwards(s):
function distribute_and_over_or (line 508) | def distribute_and_over_or(s):
function associate (line 536) | def associate(op, args):
function dissociate (line 557) | def dissociate(op, args):
function conjuncts (line 576) | def conjuncts(s):
function disjuncts (line 586) | def disjuncts(s):
function pl_resolution (line 599) | def pl_resolution(KB, alpha):
function pl_resolve (line 623) | def pl_resolve(ci, cj):
class PropDefiniteKB (line 639) | class PropDefiniteKB(PropKB):
method tell (line 642) | def tell(self, sentence):
method ask_generator (line 647) | def ask_generator(self, query):
method retract (line 652) | def retract(self, sentence):
method clauses_with_premise (line 655) | def clauses_with_premise(self, p):
function pl_fc_entails (line 662) | def pl_fc_entails(KB, q):
function dpll_satisfiable (line 712) | def dpll_satisfiable(s):
function dpll (line 726) | def dpll(clauses, symbols, model):
function find_pure_symbol (line 750) | def find_pure_symbol(symbols, clauses):
function find_unit_clause (line 769) | def find_unit_clause(clauses, model):
function unit_clause_assign (line 783) | def unit_clause_assign(clause, model):
function inspect_literal (line 806) | def inspect_literal(literal):
function WalkSAT (line 825) | def WalkSAT(clauses, p=0.5, max_flips=10000):
class WumpusKB (line 864) | class WumpusKB(PropKB):
method __init__ (line 869) | def __init__(self, dimrow):
method make_action_sentence (line 932) | def make_action_sentence(self, action, time):
method make_percept_sentence (line 941) | def make_percept_sentence(self, percept, time):
method add_temporal_sentences (line 976) | def add_temporal_sentences(self, time):
method ask_if_true (line 1048) | def ask_if_true(self, query):
class WumpusPosition (line 1055) | class WumpusPosition:
method __init__ (line 1056) | def __init__(self, x, y, orientation):
method get_location (line 1061) | def get_location(self):
method set_location (line 1064) | def set_location(self, x, y):
method get_orientation (line 1068) | def get_orientation(self):
method set_orientation (line 1071) | def set_orientation(self, orientation):
method __eq__ (line 1074) | def __eq__(self, other):
class HybridWumpusAgent (line 1086) | class HybridWumpusAgent(Agent):
method __init__ (line 1089) | def __init__(self, dimentions):
method execute (line 1097) | def execute(self, percept):
method plan_route (line 1181) | def plan_route(self, current, goals, allowed):
method plan_shot (line 1185) | def plan_shot(self, current, goals, allowed):
function SAT_plan (line 1217) | def SAT_plan(init, transition, goal, t_max, SAT_solver=dpll_satisfiable):
function unify (line 1307) | def unify(x, y, s={}):
function is_variable (line 1334) | def is_variable(x):
function unify_var (line 1339) | def unify_var(var, x, s):
function occur_check (line 1350) | def occur_check(var, x, s):
function extend (line 1366) | def extend(s, var, val):
class FolKB (line 1379) | class FolKB(KB):
method __init__ (line 1391) | def __init__(self, initial_clauses=None):
method tell (line 1397) | def tell(self, sentence):
method ask_generator (line 1403) | def ask_generator(self, query):
method retract (line 1406) | def retract(self, sentence):
method fetch_rules_for_goal (line 1409) | def fetch_rules_for_goal(self, goal):
function fol_fc_ask (line 1418) | def fol_fc_ask(KB, alpha):
function subst (line 1453) | def subst(s, x):
function standardize_variables (line 1470) | def standardize_variables(sentence, dic=None):
function fol_bc_ask (line 1495) | def fol_bc_ask(KB, query):
function fol_bc_or (line 1501) | def fol_bc_or(KB, goal, theta):
function fol_bc_and (line 1508) | def fol_bc_and(KB, goals, theta):
function diff (line 1564) | def diff(y, x):
function simp (line 1597) | def simp(x):
function d (line 1660) | def d(y, x):
FILE: making_simple_decision4e.py
class DecisionNetwork (line 10) | class DecisionNetwork(BayesNet):
method __init__ (line 15) | def __init__(self, action, infer):
method best_action (line 22) | def best_action(self):
method get_utility (line 26) | def get_utility(self, action, state):
method get_expected_utility (line 30) | def get_expected_utility(self, action, evidence):
class InformationGatheringAgent (line 40) | class InformationGatheringAgent(Agent):
method __init__ (line 45) | def __init__(self, decnet, infer, initial_evidence=None):
method integrate_percept (line 55) | def integrate_percept(self, percept):
method execute (line 59) | def execute(self, percept):
method request (line 71) | def request(self, variable):
method cost (line 75) | def cost(self, var):
method vpi_cost_ratio (line 79) | def vpi_cost_ratio(self, variables):
method vpi (line 86) | def vpi(self, variable):
class MCLmap (line 106) | class MCLmap:
method __init__ (line 110) | def __init__(self, m):
method sample (line 117) | def sample(self):
method ray_cast (line 125) | def ray_cast(self, sensor_num, kin_state):
function monte_carlo_localization (line 144) | def monte_carlo_localization(a, z, N, P_motion_sample, P_sensor, m, S=No...
FILE: mdp.py
class MDP (line 19) | class MDP:
method __init__ (line 28) | def __init__(self, init, actlist, terminals, transitions=None, reward=...
method R (line 56) | def R(self, state):
method T (line 61) | def T(self, state, action):
method actions (line 70) | def actions(self, state):
method get_states_from_transitions (line 80) | def get_states_from_transitions(self, transitions):
method check_consistency (line 91) | def check_consistency(self):
class MDP2 (line 114) | class MDP2(MDP):
method __init__ (line 119) | def __init__(self, init, actlist, terminals, transitions, reward=None,...
method T (line 122) | def T(self, state, action):
class GridMDP (line 129) | class GridMDP(MDP):
method __init__ (line 135) | def __init__(self, grid, terminals, init=(0, 0), gamma=.9):
method calculate_T (line 158) | def calculate_T(self, state, action):
method T (line 166) | def T(self, state, action):
method go (line 169) | def go(self, state, direction):
method to_grid (line 175) | def to_grid(self, mapping):
method to_arrows (line 182) | def to_arrows(self, policy):
function value_iteration (line 203) | def value_iteration(mdp, epsilon=0.001):
function best_policy (line 219) | def best_policy(mdp, U):
function expected_utility (line 229) | def expected_utility(a, s, U, mdp):
function policy_iteration (line 238) | def policy_iteration(mdp):
function policy_evaluation (line 255) | def policy_evaluation(pi, U, mdp, k=20):
class POMDP (line 266) | class POMDP(MDP):
method __init__ (line 274) | def __init__(self, actions, transitions=None, evidences=None, rewards=...
method remove_dominated_plans (line 296) | def remove_dominated_plans(self, input_values):
method remove_dominated_plans_fast (line 327) | def remove_dominated_plans_fast(self, input_values):
method generate_mapping (line 354) | def generate_mapping(self, best, input_values):
method max_difference (line 365) | def max_difference(self, U1, U2):
class Matrix (line 378) | class Matrix:
method add (line 382) | def add(A, B):
method scalar_multiply (line 394) | def scalar_multiply(a, B):
method multiply (line 403) | def multiply(A, B):
method matmul (line 416) | def matmul(A, B):
method transpose (line 422) | def transpose(A):
function pomdp_value_iteration (line 428) | def pomdp_value_iteration(pomdp, epsilon=0.1):
FILE: mdp4e.py
class MDP (line 19) | class MDP:
method __init__ (line 28) | def __init__(self, init, actlist, terminals, transitions=None, reward=...
method R (line 56) | def R(self, state):
method T (line 61) | def T(self, state, action):
method actions (line 70) | def actions(self, state):
method get_states_from_transitions (line 80) | def get_states_from_transitions(self, transitions):
method check_consistency (line 91) | def check_consistency(self):
class MDP2 (line 114) | class MDP2(MDP):
method __init__ (line 119) | def __init__(self, init, actlist, terminals, transitions, reward=None,...
method T (line 122) | def T(self, state, action):
class GridMDP (line 129) | class GridMDP(MDP):
method __init__ (line 135) | def __init__(self, grid, terminals, init=(0, 0), gamma=.9):
method calculate_T (line 158) | def calculate_T(self, state, action):
method T (line 166) | def T(self, state, action):
method go (line 169) | def go(self, state, direction):
method to_grid (line 175) | def to_grid(self, mapping):
method to_arrows (line 182) | def to_arrows(self, policy):
function q_value (line 204) | def q_value(mdp, s, a, U):
function value_iteration (line 220) | def value_iteration(mdp, epsilon=0.001):
function best_policy (line 241) | def best_policy(mdp, U):
function expected_utility (line 251) | def expected_utility(a, s, U, mdp):
function policy_iteration (line 257) | def policy_iteration(mdp):
function policy_evaluation (line 275) | def policy_evaluation(pi, U, mdp, k=20):
class POMDP (line 290) | class POMDP(MDP):
method __init__ (line 298) | def __init__(self, actions, transitions=None, evidences=None, rewards=...
method remove_dominated_plans (line 320) | def remove_dominated_plans(self, input_values):
method remove_dominated_plans_fast (line 351) | def remove_dominated_plans_fast(self, input_values):
method generate_mapping (line 378) | def generate_mapping(self, best, input_values):
method max_difference (line 389) | def max_difference(self, U1, U2):
class Matrix (line 402) | class Matrix:
method add (line 406) | def add(A, B):
method scalar_multiply (line 418) | def scalar_multiply(a, B):
method multiply (line 427) | def multiply(A, B):
method matmul (line 440) | def matmul(A, B):
method transpose (line 446) | def transpose(A):
function pomdp_value_iteration (line 452) | def pomdp_value_iteration(pomdp, epsilon=0.1):
FILE: nlp.py
function Rules (line 13) | def Rules(**rules):
function Lexicon (line 23) | def Lexicon(**rules):
class Grammar (line 33) | class Grammar:
method __init__ (line 35) | def __init__(self, name, rules, lexicon):
method rewrites_for (line 45) | def rewrites_for(self, cat):
method isa (line 49) | def isa(self, word, cat):
method cnf_rules (line 53) | def cnf_rules(self):
method generate_random (line 63) | def generate_random(self, S='S'):
method __repr__ (line 79) | def __repr__(self):
function ProbRules (line 83) | def ProbRules(**rules):
function ProbLexicon (line 100) | def ProbLexicon(**rules):
class ProbGrammar (line 118) | class ProbGrammar:
method __init__ (line 120) | def __init__(self, name, rules, lexicon):
method rewrites_for (line 132) | def rewrites_for(self, cat):
method isa (line 136) | def isa(self, word, cat):
method cnf_rules (line 140) | def cnf_rules(self):
method generate_random (line 150) | def generate_random(self, S='S'):
method __repr__ (line 172) | def __repr__(self):
class Chart (line 283) | class Chart:
method __init__ (line 290) | def __init__(self, grammar, trace=False):
method parses (line 297) | def parses(self, words, S='S'):
method parse (line 309) | def parse(self, words, S='S'):
method add_edge (line 318) | def add_edge(self, edge):
method scanner (line 330) | def scanner(self, j, word):
method predictor (line 336) | def predictor(self, edge):
method extender (line 344) | def extender(self, edge):
function CYK_parse (line 355) | def CYK_parse(words, grammar):
function loadPageHTML (line 395) | def loadPageHTML(addressList):
function initPages (line 407) | def initPages(addressList):
function stripRawHTML (line 415) | def stripRawHTML(raw_html):
function determineInlinks (line 422) | def determineInlinks(page):
function findOutlinks (line 434) | def findOutlinks(page, handleURLs=None):
function onlyWikipediaURLS (line 442) | def onlyWikipediaURLS(urls):
function expand_pages (line 452) | def expand_pages(pages):
function relevant_pages (line 468) | def relevant_pages(query):
function normalize (line 482) | def normalize(pages):
class ConvergenceDetector (line 493) | class ConvergenceDetector(object):
method __init__ (line 498) | def __init__(self):
method __call__ (line 502) | def __call__(self):
method detect (line 505) | def detect(self):
function getInLinks (line 525) | def getInLinks(page):
function getOutLinks (line 531) | def getOutLinks(page):
class Page (line 540) | class Page(object):
method __init__ (line 541) | def __init__(self, address, inLinks=None, outLinks=None, hub=0, author...
function HITS (line 554) | def HITS(query):
FILE: nlp4e.py
function Rules (line 15) | def Rules(**rules):
function Lexicon (line 25) | def Lexicon(**rules):
class Grammar (line 35) | class Grammar:
method __init__ (line 37) | def __init__(self, name, rules, lexicon):
method rewrites_for (line 47) | def rewrites_for(self, cat):
method isa (line 51) | def isa(self, word, cat):
method cnf_rules (line 55) | def cnf_rules(self):
method generate_random (line 65) | def generate_random(self, S='S'):
method __repr__ (line 81) | def __repr__(self):
function ProbRules (line 85) | def ProbRules(**rules):
function ProbLexicon (line 102) | def ProbLexicon(**rules):
class ProbGrammar (line 120) | class ProbGrammar:
method __init__ (line 122) | def __init__(self, name, rules, lexicon):
method rewrites_for (line 134) | def rewrites_for(self, cat):
method isa (line 138) | def isa(self, word, cat):
method cnf_rules (line 142) | def cnf_rules(self):
method generate_random (line 152) | def generate_random(self, S='S'):
method __repr__ (line 173) | def __repr__(self):
class Chart (line 284) | class Chart:
method __init__ (line 291) | def __init__(self, grammar, trace=False):
method parses (line 298) | def parses(self, words, S='S'):
method parse (line 310) | def parse(self, words, S='S'):
method add_edge (line 319) | def add_edge(self, edge):
method scanner (line 331) | def scanner(self, j, word):
method predictor (line 337) | def predictor(self, edge):
method extender (line 345) | def extender(self, edge):
class Tree (line 357) | class Tree:
method __init__ (line 358) | def __init__(self, root, *args):
function CYK_parse (line 363) | def CYK_parse(words, grammar):
function subspan (line 386) | def subspan(N):
class TextParsingProblem (line 398) | class TextParsingProblem(Problem):
method __init__ (line 399) | def __init__(self, initial, grammar, goal='S'):
method actions (line 413) | def actions(self, state):
method result (line 434) | def result(self, state, action):
method h (line 437) | def h(self, state):
function astar_search_parsing (line 442) | def astar_search_parsing(words, gramma):
function beam_search_parsing (line 465) | def beam_search_parsing(words, gramma, b=3):
FILE: notebook.py
function pseudocode (line 24) | def pseudocode(algorithm):
function psource (line 38) | def psource(*functions):
function show_iris (line 56) | def show_iris(i=0, j=1, k=2):
function load_MNIST (line 100) | def load_MNIST(path="aima-data/MNIST/Digits", fashion=False):
function show_MNIST (line 155) | def show_MNIST(labels, images, samples=8, fashion=False):
function show_ave_MNIST (line 177) | def show_ave_MNIST(labels, images, fashion=False):
function make_plot_grid_step_function (line 206) | def make_plot_grid_step_function(columns, rows, U_over_time):
function make_visualize (line 237) | def make_visualize(slider):
class Canvas (line 263) | class Canvas:
method __init__ (line 269) | def __init__(self, varname, width=800, height=600, cid=None):
method mouse_click (line 278) | def mouse_click(self, x, y):
method mouse_move (line 282) | def mouse_move(self, x, y):
method execute (line 285) | def execute(self, exec_str):
method fill (line 293) | def fill(self, r, g, b):
method stroke (line 297) | def stroke(self, r, g, b):
method strokeWidth (line 301) | def strokeWidth(self, w):
method rect (line 305) | def rect(self, x, y, w, h):
method rect_n (line 309) | def rect_n(self, xn, yn, wn, hn):
method line (line 317) | def line(self, x1, y1, x2, y2):
method line_n (line 321) | def line_n(self, x1n, y1n, x2n, y2n):
method arc (line 329) | def arc(self, x, y, r, start, stop):
method arc_n (line 333) | def arc_n(self, xn, yn, rn, start, stop):
method clear (line 342) | def clear(self):
method font (line 346) | def font(self, font):
method text (line 350) | def text(self, txt, x, y, fill=True):
method text_n (line 357) | def text_n(self, txt, xn, yn, fill=True):
method alert (line 363) | def alert(self, message):
method update (line 367) | def update(self):
function display_html (line 374) | def display_html(html_string):
class Canvas_TicTacToe (line 381) | class Canvas_TicTacToe(Canvas):
method __init__ (line 384) | def __init__(self, varname, player_1='human', player_2='random',
method mouse_click (line 398) | def mouse_click(self, x, y):
method draw_board (line 421) | def draw_board(self):
method draw_x (line 469) | def draw_x(self, position):
method draw_o (line 476) | def draw_o(self, position):
class Canvas_min_max (line 482) | class Canvas_min_max(Canvas):
method __init__ (line 485) | def __init__(self, varname, util_list, width=800, height=600, cid=None):
method min_max (line 507) | def min_max(self, node):
method stack_manager_gen (line 545) | def stack_manager_gen(self):
method mouse_click (line 559) | def mouse_click(self, x, y):
method draw_graph (line 566) | def draw_graph(self):
class Canvas_alpha_beta (line 607) | class Canvas_alpha_beta(Canvas):
method __init__ (line 610) | def __init__(self, varname, util_list, width=800, height=600, cid=None):
method alpha_beta_search (line 634) | def alpha_beta_search(self, node):
method stack_manager_gen (line 699) | def stack_manager_gen(self):
method mouse_click (line 715) | def mouse_click(self, x, y):
method draw_graph (line 722) | def draw_graph(self):
class Canvas_fol_bc_ask (line 777) | class Canvas_fol_bc_ask(Canvas):
method __init__ (line 780) | def __init__(self, varname, kb, query, width=800, height=600, cid=None):
method fol_bc_ask (line 802) | def fol_bc_ask(self):
method make_table (line 825) | def make_table(self, graph):
method mouse_click (line 856) | def mouse_click(self, x, y):
method draw_table (line 866) | def draw_table(self):
function show_map (line 908) | def show_map(graph_data, node_colors=None):
function final_path_colors (line 946) | def final_path_colors(initial_node_colors, problem, solution):
function display_visual (line 958) | def display_visual(graph_data, user_input, algorithm=None, problem=None):
function plot_NQueens (line 1059) | def plot_NQueens(solution):
function heatmap (line 1086) | def heatmap(grid, cmap='binary', interpolation='nearest'):
function gaussian_kernel (line 1096) | def gaussian_kernel(l=5, sig=1.0):
function plot_pomdp_utility (line 1104) | def plot_pomdp_utility(utility):
FILE: notebook4e.py
function pseudocode (line 25) | def pseudocode(algorithm):
function psource (line 39) | def psource(*functions):
function plot_model_boundary (line 53) | def plot_model_boundary(dataset, attr1, attr2, model=None):
function show_iris (line 92) | def show_iris(i=0, j=1, k=2):
function load_MNIST (line 136) | def load_MNIST(path="aima-data/MNIST/Digits", fashion=False):
function show_MNIST (line 191) | def show_MNIST(labels, images, samples=8, fashion=False):
function show_ave_MNIST (line 213) | def show_ave_MNIST(labels, images, fashion=False):
function make_plot_grid_step_function (line 242) | def make_plot_grid_step_function(columns, rows, U_over_time):
function make_visualize (line 273) | def make_visualize(slider):
class Canvas (line 299) | class Canvas:
method __init__ (line 305) | def __init__(self, varname, width=800, height=600, cid=None):
method mouse_click (line 314) | def mouse_click(self, x, y):
method mouse_move (line 318) | def mouse_move(self, x, y):
method execute (line 321) | def execute(self, exec_str):
method fill (line 329) | def fill(self, r, g, b):
method stroke (line 333) | def stroke(self, r, g, b):
method strokeWidth (line 337) | def strokeWidth(self, w):
method rect (line 341) | def rect(self, x, y, w, h):
method rect_n (line 345) | def rect_n(self, xn, yn, wn, hn):
method line (line 353) | def line(self, x1, y1, x2, y2):
method line_n (line 357) | def line_n(self, x1n, y1n, x2n, y2n):
method arc (line 365) | def arc(self, x, y, r, start, stop):
method arc_n (line 369) | def arc_n(self, xn, yn, rn, start, stop):
method clear (line 378) | def clear(self):
method font (line 382) | def font(self, font):
method text (line 386) | def text(self, txt, x, y, fill=True):
method text_n (line 393) | def text_n(self, txt, xn, yn, fill=True):
method alert (line 399) | def alert(self, message):
method update (line 403) | def update(self):
function display_html (line 410) | def display_html(html_string):
class Canvas_TicTacToe (line 417) | class Canvas_TicTacToe(Canvas):
method __init__ (line 420) | def __init__(self, varname, player_1='human', player_2='random',
method mouse_click (line 434) | def mouse_click(self, x, y):
method draw_board (line 457) | def draw_board(self):
method draw_x (line 505) | def draw_x(self, position):
method draw_o (line 512) | def draw_o(self, position):
class Canvas_min_max (line 518) | class Canvas_min_max(Canvas):
method __init__ (line 521) | def __init__(self, varname, util_list, width=800, height=600, cid=None):
method min_max (line 543) | def min_max(self, node):
method stack_manager_gen (line 581) | def stack_manager_gen(self):
method mouse_click (line 595) | def mouse_click(self, x, y):
method draw_graph (line 602) | def draw_graph(self):
class Canvas_alpha_beta (line 643) | class Canvas_alpha_beta(Canvas):
method __init__ (line 646) | def __init__(self, varname, util_list, width=800, height=600, cid=None):
method alpha_beta_search (line 670) | def alpha_beta_search(self, node):
method stack_manager_gen (line 735) | def stack_manager_gen(self):
method mouse_click (line 751) | def mouse_click(self, x, y):
method draw_graph (line 758) | def draw_graph(self):
class Canvas_fol_bc_ask (line 813) | class Canvas_fol_bc_ask(Canvas):
method __init__ (line 816) | def __init__(self, varname, kb, query, width=800, height=600, cid=None):
method fol_bc_ask (line 838) | def fol_bc_ask(self):
method make_table (line 861) | def make_table(self, graph):
method mouse_click (line 892) | def mouse_click(self, x, y):
method draw_table (line 902) | def draw_table(self):
function show_map (line 944) | def show_map(graph_data, node_colors=None):
function final_path_colors (line 982) | def final_path_colors(initial_node_colors, problem, solution):
function display_visual (line 994) | def display_visual(graph_data, user_input, algorithm=None, problem=None):
function plot_NQueens (line 1095) | def plot_NQueens(solution):
function heatmap (line 1122) | def heatmap(grid, cmap='binary', interpolation='nearest'):
function gaussian_kernel (line 1132) | def gaussian_kernel(l=5, sig=1.0):
function plot_pomdp_utility (line 1140) | def plot_pomdp_utility(utility):
FILE: perception4e.py
function array_normalization (line 20) | def array_normalization(array, range_min, range_max):
function gradient_edge_detector (line 29) | def gradient_edge_detector(image):
function gaussian_derivative_edge_detector (line 46) | def gaussian_derivative_edge_detector(image):
function laplacian_edge_detector (line 61) | def laplacian_edge_detector(image):
function show_edges (line 73) | def show_edges(edges):
function sum_squared_difference (line 84) | def sum_squared_difference(pic1, pic2):
function gen_gray_scale_picture (line 109) | def gen_gray_scale_picture(size, level=3):
function probability_contour_detection (line 132) | def probability_contour_detection(image, discs, threshold=0):
function group_contour_detection (line 158) | def group_contour_detection(image, cluster_num=2):
function image_to_graph (line 180) | def image_to_graph(image):
function generate_edge_weight (line 192) | def generate_edge_weight(image, v1, v2):
class Graph (line 202) | class Graph:
method __init__ (line 205) | def __init__(self, image):
method bfs (line 221) | def bfs(self, s, t, parent):
method min_cut (line 238) | def min_cut(self, source, sink):
function gen_discs (line 265) | def gen_discs(init_scale, scales=1):
function load_MINST (line 300) | def load_MINST(train_size, val_size, test_size):
function simple_convnet (line 319) | def simple_convnet(size=3, num_classes=10):
function train_model (line 346) | def train_model(model):
function selective_search (line 360) | def selective_search(image):
function pool_rois (line 391) | def pool_rois(feature_map, rois, pooled_height, pooled_width):
function pool_roi (line 408) | def pool_roi(feature_map, roi, pooled_height, pooled_width):
FILE: planning.py
class PlanningProblem (line 17) | class PlanningProblem:
method __init__ (line 24) | def __init__(self, initial, goals, actions, domain=None):
method convert (line 30) | def convert(self, clauses):
method expand_fluents (line 50) | def expand_fluents(self, name=None):
method expand_actions (line 83) | def expand_actions(self, name=None):
method is_strips (line 142) | def is_strips(self):
method goal_test (line 149) | def goal_test(self):
method act (line 153) | def act(self, action):
class Action (line 168) | class Action:
method __init__ (line 181) | def __init__(self, action, precond, effect, domain=None):
method __call__ (line 190) | def __call__(self, kb, args):
method __repr__ (line 193) | def __repr__(self):
method convert (line 196) | def convert(self, clauses):
method relaxed (line 216) | def relaxed(self):
method substitute (line 223) | def substitute(self, e, args):
method check_precond (line 233) | def check_precond(self, kb, args):
method act (line 243) | def act(self, kb, args):
function goal_test (line 267) | def goal_test(goals, state):
function air_cargo (line 277) | def air_cargo():
function spare_tire (line 319) | def spare_tire():
function three_block_tower (line 358) | def three_block_tower():
function simple_blocks_world (line 392) | def simple_blocks_world():
function have_cake_and_eat_cake_too (line 423) | def have_cake_and_eat_cake_too():
function shopping_problem (line 455) | def shopping_problem():
function socks_and_shoes (line 492) | def socks_and_shoes():
function double_tennis_problem (line 530) | def double_tennis_problem():
class ForwardPlan (line 563) | class ForwardPlan(search.Problem):
method __init__ (line 569) | def __init__(self, planning_problem):
method actions (line 574) | def actions(self, state):
method result (line 577) | def result(self, state, action):
method goal_test (line 580) | def goal_test(self, state):
method h (line 583) | def h(self, state):
class BackwardPlan (line 599) | class BackwardPlan(search.Problem):
method __init__ (line 605) | def __init__(self, planning_problem):
method actions (line 610) | def actions(self, subgoal):
method result (line 629) | def result(self, subgoal, action):
method goal_test (line 633) | def goal_test(self, subgoal):
method h (line 636) | def h(self, subgoal):
function CSPlan (line 652) | def CSPlan(planning_problem, solution_length, CSP_solver=ac_search_solve...
function SATPlan (line 726) | def SATPlan(planning_problem, solution_length, SAT_solver=cdcl_satisfiab...
class Level (line 752) | class Level:
method __init__ (line 759) | def __init__(self, kb):
method __call__ (line 776) | def __call__(self, actions, objects):
method separate (line 780) | def separate(self, e):
method find_mutex (line 792) | def find_mutex(self):
method build (line 833) | def build(self, actions, objects):
method perform_actions (line 876) | def perform_actions(self):
class Graph (line 883) | class Graph:
method __init__ (line 889) | def __init__(self, planning_problem):
method __call__ (line 895) | def __call__(self):
method expand_graph (line 898) | def expand_graph(self):
method non_mutex_goals (line 905) | def non_mutex_goals(self, goals, index):
class GraphPlan (line 915) | class GraphPlan:
method __init__ (line 922) | def __init__(self, planning_problem):
method check_leveloff (line 927) | def check_leveloff(self):
method extract_solution (line 935) | def extract_solution(self, goals, index):
method goal_test (line 994) | def goal_test(self, kb):
method execute (line 997) | def execute(self):
class Linearize (line 1012) | class Linearize:
method __init__ (line 1014) | def __init__(self, planning_problem):
method filter (line 1017) | def filter(self, solution):
method orderlevel (line 1029) | def orderlevel(self, level, planning_problem):
method execute (line 1047) | def execute(self):
function linearize (line 1062) | def linearize(solution):
class PartialOrderPlanner (line 1074) | class PartialOrderPlanner:
method __init__ (line 1097) | def __init__(self, planning_problem):
method find_open_precondition (line 1113) | def find_open_precondition(self):
method find_action_for_precondition (line 1148) | def find_action_for_precondition(self, oprec):
method generate_expr (line 1168) | def generate_expr(self, clause, bindings):
method generate_action_object (line 1183) | def generate_action_object(self, action, bindings):
method cyclic (line 1203) | def cyclic(self, graph):
method add_const (line 1226) | def add_const(self, constraint, constraints):
method is_a_threat (line 1239) | def is_a_threat(self, precondition, effect):
method protect (line 1247) | def protect(self, causal_link, action, constraints):
method convert (line 1274) | def convert(self, constraints):
method toposort (line 1286) | def toposort(self, graph):
method display_plan (line 1311) | def display_plan(self):
method execute (line 1325) | def execute(self, display=True):
function spare_tire_graphPlan (line 1383) | def spare_tire_graphPlan():
function three_block_tower_graphPlan (line 1388) | def three_block_tower_graphPlan():
function air_cargo_graphPlan (line 1393) | def air_cargo_graphPlan():
function have_cake_and_eat_cake_too_graphPlan (line 1398) | def have_cake_and_eat_cake_too_graphPlan():
function shopping_graphPlan (line 1403) | def shopping_graphPlan():
function socks_and_shoes_graphPlan (line 1408) | def socks_and_shoes_graphPlan():
function simple_blocks_world_graphPlan (line 1413) | def simple_blocks_world_graphPlan():
class HLA (line 1418) | class HLA(Action):
method __init__ (line 1425) | def __init__(self, action, precond=None, effect=None, duration=0, cons...
method do_action (line 1442) | def do_action(self, job_order, available_resources, kb, args):
method has_consumable_resource (line 1460) | def has_consumable_resource(self, available_resources):
method has_usable_resource (line 1471) | def has_usable_resource(self, available_resources):
method inorder (line 1482) | def inorder(self, job_order):
class RealWorldPlanningProblem (line 1497) | class RealWorldPlanningProblem(PlanningProblem):
method __init__ (line 1506) | def __init__(self, initial, goals, actions, jobs=None, resources=None):
method act (line 1511) | def act(self, action):
method refinements (line 1526) | def refinements(self, library): # refinements may be (multiple) HLA t...
method hierarchical_search (line 1572) | def hierarchical_search(self, hierarchy):
method result (line 1600) | def result(state, actions):
method angelic_search (line 1607) | def angelic_search(self, hierarchy, initial_plan):
method intersects_goal (line 1648) | def intersects_goal(self, reachable_set):
method is_primitive (line 1656) | def is_primitive(plan, library):
method reach_opt (line 1667) | def reach_opt(init, plan):
method reach_pes (line 1675) | def reach_pes(init, plan):
method find_reachable_set (line 1683) | def find_reachable_set(reachable_set, action_description):
method find_hla (line 1703) | def find_hla(plan, hierarchy):
method making_progress (line 1717) | def making_progress(plan, initial_plan):
method decompose (line 1730) | def decompose(hierarchy, plan, s_f, reachable_set):
method find_previous_state (line 1750) | def find_previous_state(s_f, reachable_set, i, action):
function job_shop_problem (line 1764) | def job_shop_problem():
function go_to_sfo (line 1813) | def go_to_sfo():
class AngelicHLA (line 1858) | class AngelicHLA(HLA):
method __init__ (line 1863) | def __init__(self, action, precond, effect, duration=0, consume=None, ...
method convert (line 1866) | def convert(self, clauses):
method angelic_action (line 1902) | def angelic_action(self):
method compute_parameters (line 1971) | def compute_parameters(clause):
class AngelicNode (line 2001) | class AngelicNode(Node):
method __init__ (line 2008) | def __init__(self, state, parent=None, action_opt=None, action_pes=Non...
FILE: probabilistic_learning.py
class CountingProbDist (line 8) | class CountingProbDist:
method __init__ (line 18) | def __init__(self, observations=None, default=0):
method add (line 34) | def add(self, o):
method smooth_for (line 41) | def smooth_for(self, o):
method __getitem__ (line 51) | def __getitem__(self, item):
method top (line 58) | def top(self, n):
method sample (line 62) | def sample(self):
function NaiveBayesLearner (line 69) | def NaiveBayesLearner(dataset, continuous=True, simple=False):
function NaiveBayesSimple (line 78) | def NaiveBayesSimple(distribution):
function NaiveBayesDiscrete (line 101) | def NaiveBayesDiscrete(dataset):
function NaiveBayesContinuous (line 132) | def NaiveBayesContinuous(dataset):
FILE: probability.py
function DTAgentProgram (line 10) | def DTAgentProgram(belief_state):
class ProbDist (line 28) | class ProbDist:
method __init__ (line 38) | def __init__(self, var_name='?', freq=None):
method __getitem__ (line 49) | def __getitem__(self, val):
method __setitem__ (line 56) | def __setitem__(self, val, p):
method normalize (line 62) | def normalize(self):
method show_approx (line 72) | def show_approx(self, numfmt='{:.3g}'):
method __repr__ (line 77) | def __repr__(self):
class JointProbDist (line 81) | class JointProbDist(ProbDist):
method __init__ (line 90) | def __init__(self, variables):
method __getitem__ (line 95) | def __getitem__(self, values):
method __setitem__ (line 100) | def __setitem__(self, values, p):
method values (line 110) | def values(self, var):
method __repr__ (line 114) | def __repr__(self):
function event_values (line 118) | def event_values(event, variables):
function enumerate_joint_ask (line 134) | def enumerate_joint_ask(X, e, P):
function enumerate_joint (line 152) | def enumerate_joint(variables, e, P):
class BayesNet (line 164) | class BayesNet:
method __init__ (line 167) | def __init__(self, node_specs=None):
method add (line 175) | def add(self, node_spec):
method variable_node (line 186) | def variable_node(self, var):
method variable_values (line 195) | def variable_values(self, var):
method __repr__ (line 199) | def __repr__(self):
class DecisionNetwork (line 203) | class DecisionNetwork(BayesNet):
method __init__ (line 208) | def __init__(self, action, infer):
method best_action (line 215) | def best_action(self):
method get_utility (line 219) | def get_utility(self, action, state):
method get_expected_utility (line 223) | def get_expected_utility(self, action, evidence):
class InformationGatheringAgent (line 233) | class InformationGatheringAgent(Agent):
method __init__ (line 240) | def __init__(self, decnet, infer, initial_evidence=None):
method integrate_percept (line 249) | def integrate_percept(self, percept):
method execute (line 253) | def execute(self, percept):
method request (line 265) | def request(self, variable):
method cost (line 269) | def cost(self, var):
method vpi_cost_ratio (line 273) | def vpi_cost_ratio(self, variables):
method vpi (line 280) | def vpi(self, variable):
class BayesNode (line 295) | class BayesNode:
method __init__ (line 299) | def __init__(self, X, parents, cpt):
method p (line 345) | def p(self, value, event):
method sample (line 357) | def sample(self, event):
method __repr__ (line 364) | def __repr__(self):
function enumeration_ask (line 383) | def enumeration_ask(X, e, bn):
function enumerate_all (line 398) | def enumerate_all(variables, e, bn):
function elimination_ask (line 417) | def elimination_ask(X, e, bn):
function is_hidden (line 433) | def is_hidden(var, X, e):
function make_factor (line 438) | def make_factor(var, e, bn):
function pointwise_product (line 449) | def pointwise_product(factors, bn):
function sum_out (line 453) | def sum_out(var, factors, bn):
class Factor (line 462) | class Factor:
method __init__ (line 465) | def __init__(self, variables, cpt):
method pointwise_product (line 469) | def pointwise_product(self, other, bn):
method sum_out (line 475) | def sum_out(self, var, bn):
method normalize (line 482) | def normalize(self):
method p (line 487) | def p(self, e):
function all_events (line 492) | def all_events(variables, bn, e):
function prior_sample (line 518) | def prior_sample(bn):
function rejection_sampling (line 533) | def rejection_sampling(X, e, bn, N=10000):
function consistent_with (line 553) | def consistent_with(event, evidence):
function likelihood_weighting (line 561) | def likelihood_weighting(X, e, bn, N=10000):
function weighted_sample (line 578) | def weighted_sample(bn, e):
function gibbs_ask (line 598) | def gibbs_ask(X, e, bn, N=1000):
function markov_blanket_sample (line 613) | def markov_blanket_sample(X, e, bn):
class HiddenMarkovModel (line 631) | class HiddenMarkovModel:
method __init__ (line 634) | def __init__(self, transition_model, sensor_model, prior=None):
method sensor_dist (line 639) | def sensor_dist(self, ev):
function forward (line 646) | def forward(HMM, fv, ev):
function backward (line 654) | def backward(HMM, b, ev):
function forward_backward (line 662) | def forward_backward(HMM, ev):
function viterbi (line 688) | def viterbi(HMM, ev):
function fixed_lag_smoothing (line 733) | def fixed_lag_smoothing(e_t, HMM, d, ev, t):
function particle_filtering (line 765) | def particle_filtering(e, N, HMM):
class MCLmap (line 806) | class MCLmap:
method __init__ (line 810) | def __init__(self, m):
method sample (line 817) | def sample(self):
method ray_cast (line 825) | def ray_cast(self, sensor_num, kin_state):
function monte_carlo_localization (line 844) | def monte_carlo_localization(a, z, N, P_motion_sample, P_sensor, m, S=No...
FILE: probability4e.py
function DTAgentProgram (line 18) | def DTAgentProgram(belief_state):
class ProbDist (line 34) | class ProbDist:
method __init__ (line 44) | def __init__(self, varname='?', freqs=None):
method __getitem__ (line 55) | def __getitem__(self, val):
method __setitem__ (line 62) | def __setitem__(self, val, p):
method normalize (line 68) | def normalize(self):
method show_approx (line 78) | def show_approx(self, numfmt='{:.3g}'):
method __repr__ (line 84) | def __repr__(self):
class JointProbDist (line 92) | class JointProbDist(ProbDist):
method __init__ (line 101) | def __init__(self, variables):
method __getitem__ (line 106) | def __getitem__(self, values):
method __setitem__ (line 111) | def __setitem__(self, values, p):
method values (line 121) | def values(self, var):
method __repr__ (line 125) | def __repr__(self):
function event_values (line 129) | def event_values(event, variables):
function enumerate_joint_ask (line 142) | def enumerate_joint_ask(X, e, P):
function enumerate_joint (line 158) | def enumerate_joint(variables, e, P):
function is_independent (line 172) | def is_independent(variables, P):
function gen_possible_events (line 194) | def gen_possible_events(vars, P):
class BayesNet (line 216) | class BayesNet:
method __init__ (line 219) | def __init__(self, node_specs=None):
method add (line 232) | def add(self, node_spec):
method variable_node (line 249) | def variable_node(self, var):
method variable_values (line 260) | def variable_values(self, var):
method __repr__ (line 264) | def __repr__(self):
class BayesNode (line 268) | class BayesNode:
method __init__ (line 274) | def __init__(self, X, parents, cpt):
method p (line 321) | def p(self, value, event):
method sample (line 335) | def sample(self, event):
method __repr__ (line 344) | def __repr__(self):
function gaussian_probability (line 368) | def gaussian_probability(param, event, value):
function logistic_probability (line 393) | def logistic_probability(param, event, value):
class ContinuousBayesNode (line 411) | class ContinuousBayesNode:
method __init__ (line 414) | def __init__(self, name, d_parents, c_parents, parameters, type):
method continuous_p (line 431) | def continuous_p(self, value, c_event, d_event):
function enumeration_ask (line 468) | def enumeration_ask(X, e, bn):
function enumerate_all (line 484) | def enumerate_all(variables, e, bn):
function elimination_ask (line 507) | def elimination_ask(X, e, bn):
function is_hidden (line 523) | def is_hidden(var, X, e):
function make_factor (line 528) | def make_factor(var, e, bn):
function pointwise_product (line 541) | def pointwise_product(factors, bn):
function sum_out (line 545) | def sum_out(var, factors, bn):
class Factor (line 554) | class Factor:
method __init__ (line 557) | def __init__(self, variables, cpt):
method pointwise_product (line 561) | def pointwise_product(self, other, bn):
method sum_out (line 568) | def sum_out(self, var, bn):
method normalize (line 576) | def normalize(self):
method p (line 582) | def p(self, e):
function all_events (line 587) | def all_events(variables, bn, e):
function prior_sample (line 616) | def prior_sample(bn):
function rejection_sampling (line 630) | def rejection_sampling(X, e, bn, N=10000):
function consistent_with (line 650) | def consistent_with(event, evidence):
function likelihood_weighting (line 659) | def likelihood_weighting(X, e, bn, N=10000):
function weighted_sample (line 677) | def weighted_sample(bn, e):
function gibbs_ask (line 699) | def gibbs_ask(X, e, bn, N=1000):
function markov_blanket_sample (line 714) | def markov_blanket_sample(X, e, bn):
class complied_burglary (line 736) | class complied_burglary:
method Burglary (line 739) | def Burglary(self, sample):
method Earthquake (line 751) | def Earthquake(self, sample):
method MaryCalls (line 763) | def MaryCalls(self, sample):
method JongCalls (line 769) | def JongCalls(self, sample):
method Alarm (line 775) | def Alarm(self, sample):
FILE: reinforcement_learning.py
class PassiveDUEAgent (line 9) | class PassiveDUEAgent:
method __init__ (line 30) | def __init__(self, pi, mdp):
method __call__ (line 40) | def __call__(self, percept):
method estimate_U (line 52) | def estimate_U(self):
method update_state (line 74) | def update_state(self, percept):
class PassiveADPAgent (line 80) | class PassiveADPAgent:
class ModelMDP (line 104) | class ModelMDP(MDP):
method __init__ (line 108) | def __init__(self, init, actlist, terminals, gamma, states):
method T (line 114) | def T(self, s, a):
method __init__ (line 119) | def __init__(self, pi, mdp):
method __call__ (line 130) | def __call__(self, percept):
method update_state (line 157) | def update_state(self, percept):
class PassiveTDAgent (line 163) | class PassiveTDAgent:
method __init__ (line 189) | def __init__(self, pi, mdp, alpha=None):
method __call__ (line 205) | def __call__(self, percept):
method update_state (line 220) | def update_state(self, percept):
class QLearningAgent (line 226) | class QLearningAgent:
method __init__ (line 251) | def __init__(self, mdp, Ne, Rplus, alpha=None):
method f (line 269) | def f(self, u, n):
method actions_in_state (line 278) | def actions_in_state(self, state):
method __call__ (line 286) | def __call__(self, percept):
method update_state (line 305) | def update_state(self, percept):
function run_single_trial (line 311) | def run_single_trial(agent_program, mdp):
FILE: reinforcement_learning4e.py
class PassiveDUEAgent (line 14) | class PassiveDUEAgent:
method __init__ (line 35) | def __init__(self, pi, mdp):
method __call__ (line 45) | def __call__(self, percept):
method estimate_U (line 57) | def estimate_U(self):
method update_state (line 79) | def update_state(self, percept):
class PassiveADPAgent (line 88) | class PassiveADPAgent:
class ModelMDP (line 112) | class ModelMDP(MDP):
method __init__ (line 116) | def __init__(self, init, actlist, terminals, gamma, states):
method T (line 122) | def T(self, s, a):
method __init__ (line 127) | def __init__(self, pi, mdp):
method __call__ (line 138) | def __call__(self, percept):
method update_state (line 165) | def update_state(self, percept):
class PassiveTDAgent (line 174) | class PassiveTDAgent:
method __init__ (line 200) | def __init__(self, pi, mdp, alpha=None):
method __call__ (line 216) | def __call__(self, percept):
method update_state (line 231) | def update_state(self, percept):
class QLearningAgent (line 242) | class QLearningAgent:
method __init__ (line 267) | def __init__(self, mdp, Ne, Rplus, alpha=None):
method f (line 285) | def f(self, u, n):
method actions_in_state (line 294) | def actions_in_state(self, state):
method __call__ (line 302) | def __call__(self, percept):
method update_state (line 321) | def update_state(self, percept):
function run_single_trial (line 327) | def run_single_trial(agent_program, mdp):
FILE: search.py
class Problem (line 15) | class Problem:
method __init__ (line 21) | def __init__(self, initial, goal=None):
method actions (line 28) | def actions(self, state):
method result (line 35) | def result(self, state, action):
method goal_test (line 41) | def goal_test(self, state):
method path_cost (line 51) | def path_cost(self, c, state1, action, state2):
method value (line 59) | def value(self, state):
class Node (line 68) | class Node:
method __init__ (line 78) | def __init__(self, state, parent=None, action=None, path_cost=0):
method __repr__ (line 88) | def __repr__(self):
method __lt__ (line 91) | def __lt__(self, node):
method expand (line 94) | def expand(self, problem):
method child_node (line 99) | def child_node(self, problem, action):
method solution (line 105) | def solution(self):
method path (line 109) | def path(self):
method __eq__ (line 122) | def __eq__(self, other):
method __hash__ (line 125) | def __hash__(self):
class SimpleProblemSolvingAgentProgram (line 136) | class SimpleProblemSolvingAgentProgram:
method __init__ (line 142) | def __init__(self, initial_state=None):
method __call__ (line 149) | def __call__(self, percept):
method update_state (line 161) | def update_state(self, state, percept):
method formulate_goal (line 164) | def formulate_goal(self, state):
method formulate_problem (line 167) | def formulate_problem(self, state, goal):
method search (line 170) | def search(self, problem):
function breadth_first_tree_search (line 178) | def breadth_first_tree_search(problem):
function depth_first_tree_search (line 197) | def depth_first_tree_search(problem):
function depth_first_graph_search (line 216) | def depth_first_graph_search(problem):
function breadth_first_graph_search (line 238) | def breadth_first_graph_search(problem):
function best_first_graph_search (line 260) | def best_first_graph_search(problem, f, display=False):
function uniform_cost_search (line 290) | def uniform_cost_search(problem, display=False):
function depth_limited_search (line 295) | def depth_limited_search(problem, limit=50):
function iterative_deepening_search (line 317) | def iterative_deepening_search(problem):
function bidirectional_search (line 329) | def bidirectional_search(problem):
function astar_search (line 415) | def astar_search(problem, h=None, display=False):
class EightPuzzle (line 426) | class EightPuzzle(Problem):
method __init__ (line 431) | def __init__(self, initial, goal=(1, 2, 3, 4, 5, 6, 7, 8, 0)):
method find_blank_square (line 435) | def find_blank_square(self, state):
method actions (line 440) | def actions(self, state):
method result (line 459) | def result(self, state, action):
method goal_test (line 473) | def goal_test(self, state):
method check_solvability (line 478) | def check_solvability(self, state):
method h (line 489) | def h(self, node):
class PlanRoute (line 499) | class PlanRoute(Problem):
method __init__ (line 502) | def __init__(self, initial, goal, allowed, dimrow):
method actions (line 509) | def actions(self, state):
method result (line 534) | def result(self, state, action):
method goal_test (line 584) | def goal_test(self, state):
method h (line 589) | def h(self, node):
function recursive_best_first_search (line 603) | def recursive_best_first_search(problem, h=None):
function hill_climbing (line 635) | def hill_climbing(problem):
function exp_schedule (line 653) | def exp_schedule(k=20, lam=0.005, limit=100):
function simulated_annealing (line 658) | def simulated_annealing(problem, schedule=exp_schedule()):
function simulated_annealing_full (line 675) | def simulated_annealing_full(problem, schedule=exp_schedule()):
function and_or_graph_search (line 694) | def and_or_graph_search(problem):
class PeakFindingProblem (line 736) | class PeakFindingProblem(Problem):
method __init__ (line 739) | def __init__(self, initial, grid, defined_actions=directions4):
method actions (line 749) | def actions(self, state):
method result (line 759) | def result(self, state, action):
method value (line 763) | def value(self, state):
class OnlineDFSAgent (line 771) | class OnlineDFSAgent:
method __init__ (line 780) | def __init__(self, problem):
method __call__ (line 788) | def __call__(self, percept):
method update_state (line 814) | def update_state(self, percept):
class OnlineSearchProblem (line 823) | class OnlineSearchProblem(Problem):
method __init__ (line 829) | def __init__(self, initial, goal, graph):
method actions (line 833) | def actions(self, state):
method output (line 836) | def output(self, state, action):
method h (line 839) | def h(self, state):
method c (line 843) | def c(self, s, a, s1):
method update_state (line 847) | def update_state(self, percept):
method goal_test (line 850) | def goal_test(self, state):
class LRTAStarAgent (line 856) | class LRTAStarAgent:
method __init__ (line 864) | def __init__(self, problem):
method __call__ (line 871) | def __call__(self, s1): # as of now s1 is a state rather than a percept
method LRTA_cost (line 892) | def LRTA_cost(self, s, a, s1, H):
function genetic_search (line 911) | def genetic_search(problem, ngen=1000, pmut=0.1, n=20):
function genetic_algorithm (line 925) | def genetic_algorithm(population, fitness_fn, gene_pool=[0, 1], f_thres=...
function fitness_threshold (line 938) | def fitness_threshold(fitness_fn, f_thres, population):
function init_population (line 949) | def init_population(pop_number, gene_pool, state_length):
function select (line 963) | def select(r, population, fitness_fn):
function recombine (line 969) | def recombine(x, y):
function recombine_uniform (line 975) | def recombine_uniform(x, y):
function mutate (line 986) | def mutate(x, gene_pool, pmut):
class Graph (line 1006) | class Graph:
method __init__ (line 1020) | def __init__(self, graph_dict=None, directed=True):
method make_undirected (line 1026) | def make_undirected(self):
method connect (line 1032) | def connect(self, A, B, distance=1):
method connect1 (line 1039) | def connect1(self, A, B, distance):
method get (line 1043) | def get(self, a, b=None):
method nodes (line 1053) | def nodes(self):
function UndirectedGraph (line 1061) | def UndirectedGraph(graph_dict=None):
function RandomGraph (line 1066) | def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300,
class GraphProblem (line 1179) | class GraphProblem(Problem):
method __init__ (line 1182) | def __init__(self, initial, goal, graph):
method actions (line 1186) | def actions(self, A):
method result (line 1190) | def result(self, state, action):
method path_cost (line 1194) | def path_cost(self, cost_so_far, A, action, B):
method find_min_edge (line 1197) | def find_min_edge(self):
method h (line 1206) | def h(self, node):
class GraphProblemStochastic (line 1218) | class GraphProblemStochastic(GraphProblem):
method result (line 1227) | def result(self, state, action):
method path_cost (line 1230) | def path_cost(self):
class NQueensProblem (line 1237) | class NQueensProblem(Problem):
method __init__ (line 1247) | def __init__(self, N):
method actions (line 1251) | def actions(self, state):
method result (line 1260) | def result(self, state, row):
method conflicted (line 1267) | def conflicted(self, state, row, col):
method conflict (line 1272) | def conflict(self, row1, col1, row2, col2):
method goal_test (line 1279) | def goal_test(self, state):
method h (line 1286) | def h(self, node):
function random_boggle (line 1310) | def random_boggle(n=4):
function print_boggle (line 1325) | def print_boggle(board):
function boggle_neighbors (line 1340) | def boggle_neighbors(n2, cache={}):
function exact_sqrt (line 1373) | def exact_sqrt(n2):
class Wordlist (line 1383) | class Wordlist:
method __init__ (line 1388) | def __init__(self, file, min_len=3):
method lookup (line 1398) | def lookup(self, prefix, lo=0, hi=None):
method __contains__ (line 1412) | def __contains__(self, word):
method __len__ (line 1415) | def __len__(self):
class BoggleFinder (line 1422) | class BoggleFinder:
method __init__ (line 1427) | def __init__(self, board=None):
method set_board (line 1434) | def set_board(self, board=None):
method find (line 1446) | def find(self, lo, hi, i, visited, prefix):
method words (line 1465) | def words(self):
method score (line 1471) | def score(self):
method __len__ (line 1475) | def __len__(self):
function boggle_hill_climbing (line 1483) | def boggle_hill_climbing(board=None, ntimes=100, verbose=True):
function mutate_boggle (line 1504) | def mutate_boggle(board):
class InstrumentedProblem (line 1517) | class InstrumentedProblem(Problem):
method __init__ (line 1520) | def __init__(self, problem):
method actions (line 1525) | def actions(self, state):
method result (line 1529) | def result(self, state, action):
method goal_test (line 1533) | def goal_test(self, state):
method path_cost (line 1540) | def path_cost(self, c, state1, action, state2):
method value (line 1543) | def value(self, state):
method __getattr__ (line 1546) | def __getattr__(self, attr):
method __repr__ (line 1549) | def __repr__(self):
function compare_searchers (line 1554) | def compare_searchers(problems, header,
function compare_graph_searchers (line 1570) | def compare_graph_searchers():
FILE: tests/test_agents.py
function test_move_forward (line 18) | def test_move_forward():
function test_add (line 39) | def test_add():
function test_RandomAgentProgram (line 65) | def test_RandomAgentProgram():
function test_RandomVacuumAgent (line 82) | def test_RandomVacuumAgent():
function test_TableDrivenAgent (line 95) | def test_TableDrivenAgent():
function test_ReflexVacuumAgent (line 131) | def test_ReflexVacuumAgent():
function test_SimpleReflexAgentProgram (line 144) | def test_SimpleReflexAgentProgram():
function test_ModelBasedReflexAgentProgram (line 177) | def test_ModelBasedReflexAgentProgram():
function test_ModelBasedVacuumAgent (line 210) | def test_ModelBasedVacuumAgent():
function test_TableDrivenVacuumAgent (line 223) | def test_TableDrivenVacuumAgent():
function test_compare_agents (line 236) | def test_compare_agents():
function test_TableDrivenAgentProgram (line 253) | def test_TableDrivenAgentProgram():
function test_Agent (line 266) | def test_Agent():
function test_VacuumEnvironment (line 275) | def test_VacuumEnvironment():
function test_WumpusEnvironment (line 302) | def test_WumpusEnvironment():
function test_WumpusEnvironmentActions (line 354) | def test_WumpusEnvironmentActions():
FILE: tests/test_agents4e.py
function test_move_forward (line 18) | def test_move_forward():
function test_add (line 39) | def test_add():
function test_RandomAgentProgram (line 65) | def test_RandomAgentProgram():
function test_RandomVacuumAgent (line 82) | def test_RandomVacuumAgent():
function test_TableDrivenAgent (line 95) | def test_TableDrivenAgent():
function test_ReflexVacuumAgent (line 130) | def test_ReflexVacuumAgent():
function test_SimpleReflexAgentProgram (line 143) | def test_SimpleReflexAgentProgram():
function test_ModelBasedReflexAgentProgram (line 176) | def test_ModelBasedReflexAgentProgram():
function test_ModelBasedVacuumAgent (line 209) | def test_ModelBasedVacuumAgent():
function test_TableDrivenVacuumAgent (line 222) | def test_TableDrivenVacuumAgent():
function test_compare_agents (line 235) | def test_compare_agents():
function test_TableDrivenAgentProgram (line 252) | def test_TableDrivenAgentProgram():
function test_Agent (line 265) | def test_Agent():
function test_VacuumEnvironment (line 274) | def test_VacuumEnvironment():
function test_WumpusEnvironment (line 301) | def test_WumpusEnvironment():
function test_WumpusEnvironmentActions (line 353) | def test_WumpusEnvironmentActions():
FILE: tests/test_csp.py
function test_csp_assign (line 9) | def test_csp_assign():
function test_csp_unassign (line 19) | def test_csp_unassign():
function test_csp_nconflicts (line 27) | def test_csp_nconflicts():
function test_csp_actions (line 38) | def test_csp_actions():
function test_csp_result (line 58) | def test_csp_result():
function test_csp_goal_test (line 67) | def test_csp_goal_test():
function test_csp_support_pruning (line 76) | def test_csp_support_pruning():
function test_csp_suppose (line 82) | def test_csp_suppose():
function test_csp_prune (line 93) | def test_csp_prune():
function test_csp_choices (line 112) | def test_csp_choices():
function test_csp_infer_assignment (line 124) | def test_csp_infer_assignment():
function test_csp_restore (line 137) | def test_csp_restore():
function test_csp_conflicted_vars (line 147) | def test_csp_conflicted_vars():
function test_revise (line 168) | def test_revise():
function test_AC3 (line 191) | def test_AC3():
function test_AC3b (line 218) | def test_AC3b():
function test_AC4 (line 245) | def test_AC4():
function test_first_unassigned_variable (line 272) | def test_first_unassigned_variable():
function test_num_legal_values (line 282) | def test_num_legal_values():
function test_mrv (line 297) | def test_mrv():
function test_unordered_domain_values (line 319) | def test_unordered_domain_values():
function test_lcv (line 325) | def test_lcv():
function test_forward_checking (line 343) | def test_forward_checking():
function test_backtracking_search (line 382) | def test_backtracking_search():
function test_min_conflicts (line 392) | def test_min_conflicts():
function test_nqueens_csp (line 405) | def test_nqueens_csp():
function test_universal_dict (line 457) | def test_universal_dict():
function test_parse_neighbours (line 462) | def test_parse_neighbours():
function test_topological_sort (line 466) | def test_topological_sort():
function test_tree_csp_solver (line 479) | def test_tree_csp_solver():
function test_ac_solver (line 486) | def test_ac_solver():
function test_ac_search_solver (line 502) | def test_ac_search_solver():
function test_different_values_constraint (line 519) | def test_different_values_constraint():
function test_flatten (line 524) | def test_flatten():
function test_sudoku (line 529) | def test_sudoku():
function test_make_arc_consistent (line 536) | def test_make_arc_consistent():
function test_assign_value (line 565) | def test_assign_value():
function test_no_inference (line 589) | def test_no_inference():
function test_mac (line 601) | def test_mac():
function test_queen_constraint (line 629) | def test_queen_constraint():
function test_zebra (line 635) | def test_zebra():
FILE: tests/test_deep_learning4e.py
function test_neural_net (line 20) | def test_neural_net():
function test_perceptron (line 38) | def test_perceptron():
function test_rnn (line 56) | def test_rnn():
function test_autoencoder (line 68) | def test_autoencoder():
FILE: tests/test_games.py
function gen_state (line 12) | def gen_state(to_move='X', x_positions=[], o_positions=[], h=3, v=3):
function test_minmax_decision (line 28) | def test_minmax_decision():
function test_alpha_beta_search (line 35) | def test_alpha_beta_search():
function test_random_tests (line 58) | def test_random_tests():
FILE: tests/test_games4e.py
function gen_state (line 13) | def gen_state(to_move='X', x_positions=[], o_positions=[], h=3, v=3):
function test_minmax_decision (line 29) | def test_minmax_decision():
function test_alpha_beta_search (line 36) | def test_alpha_beta_search():
function test_monte_carlo_tree_search (line 59) | def test_monte_carlo_tree_search():
function test_random_tests (line 85) | def test_random_tests():
FILE: tests/test_knowledge.py
function r_example (line 35) | def r_example(Alt, Bar, Fri, Hun, Pat, Price, Rain, Res, Type, Est, GOAL):
function test_current_best_learning (line 55) | def test_current_best_learning():
function test_version_space_learning (line 78) | def test_version_space_learning():
function test_minimal_consistent_det (line 94) | def test_minimal_consistent_det():
function test_tell (line 162) | def test_tell():
function test_extend_example (line 174) | def test_extend_example():
function test_new_literals (line 185) | def test_new_literals():
function test_new_clause (line 190) | def test_new_clause():
function test_choose_literal (line 198) | def test_choose_literal():
function test_gain (line 212) | def test_gain():
function test_update_examples (line 222) | def test_update_examples():
function test_foil (line 236) | def test_foil():
FILE: tests/test_learning.py
function test_exclude (line 8) | def test_exclude():
function test_parse_csv (line 13) | def test_parse_csv():
function test_weighted_mode (line 18) | def test_weighted_mode():
function test_weighted_replicate (line 22) | def test_weighted_replicate():
function test_means_and_deviation (line 26) | def test_means_and_deviation():
function test_plurality_learner (line 37) | def test_plurality_learner():
function test_k_nearest_neighbors (line 43) | def test_k_nearest_neighbors():
function test_decision_tree_learner (line 51) | def test_decision_tree_learner():
function test_svc (line 59) | def test_svc():
function test_information_content (line 78) | def test_information_content():
function test_random_forest (line 87) | def test_random_forest():
function test_neural_network_learner (line 99) | def test_neural_network_learner():
function test_perceptron (line 117) | def test_perceptron():
function test_random_weights (line 131) | def test_random_weights():
function test_ada_boost (line 141) | def test_ada_boost():
FILE: tests/test_learning4e.py
function test_exclude (line 9) | def test_exclude():
function test_parse_csv (line 14) | def test_parse_csv():
function test_weighted_mode (line 19) | def test_weighted_mode():
function test_weighted_replicate (line 23) | def test_weighted_replicate():
function test_means_and_deviation (line 27) | def test_means_and_deviation():
function test_plurality_learner (line 38) | def test_plurality_learner():
function test_k_nearest_neighbors (line 44) | def test_k_nearest_neighbors():
function test_decision_tree_learner (line 52) | def test_decision_tree_learner():
function test_svc (line 60) | def test_svc():
function test_information_content (line 79) | def test_information_content():
function test_random_forest (line 88) | def test_random_forest():
function test_random_weights (line 100) | def test_random_weights():
function test_ada_boost (line 110) | def test_ada_boost():
FILE: tests/test_logic.py
function test_is_symbol (line 19) | def test_is_symbol():
function test_is_var_symbol (line 28) | def test_is_var_symbol():
function test_is_prop_symbol (line 35) | def test_is_prop_symbol():
function test_variables (line 42) | def test_variables():
function test_expr (line 47) | def test_expr():
function test_extend (line 53) | def test_extend():
function test_subst (line 57) | def test_subst():
function test_PropKB (line 61) | def test_PropKB():
function test_wumpus_kb (line 73) | def test_wumpus_kb():
function test_is_definite_clause (line 93) | def test_is_definite_clause():
function test_parse_definite_clause (line 102) | def test_parse_definite_clause():
function test_pl_true (line 109) | def test_pl_true():
function test_tt_true (line 120) | def test_tt_true():
function test_dpll_satisfiable (line 139) | def test_dpll_satisfiable():
function test_cdcl_satisfiable (line 150) | def test_cdcl_satisfiable():
function test_find_pure_symbol (line 161) | def test_find_pure_symbol():
function test_unit_clause_assign (line 167) | def test_unit_clause_assign():
function test_find_unit_clause (line 173) | def test_find_unit_clause():
function test_unify (line 177) | def test_unify():
function test_unify_mm (line 192) | def test_unify_mm():
function test_pl_fc_entails (line 207) | def test_pl_fc_entails():
function test_tt_entails (line 216) | def test_tt_entails():
function test_prop_symbols (line 225) | def test_prop_symbols():
function test_constant_symbols (line 230) | def test_constant_symbols():
function test_predicate_symbols (line 235) | def test_predicate_symbols():
function test_eliminate_implications (line 250) | def test_eliminate_implications():
function test_dissociate (line 256) | def test_dissociate():
function test_associate (line 262) | def test_associate():
function test_move_not_inwards (line 267) | def test_move_not_inwards():
function test_distribute_and_over_or (line 273) | def test_distribute_and_over_or():
function test_to_cnf (line 287) | def test_to_cnf():
function test_pl_resolution (line 301) | def test_pl_resolution():
function test_standardize_variables (line 311) | def test_standardize_variables():
function test_fol_bc_ask (line 317) | def test_fol_bc_ask():
function test_fol_fc_ask (line 330) | def test_fol_fc_ask():
function test_d (line 344) | def test_d():
function test_WalkSAT (line 348) | def test_WalkSAT():
function test_SAT_plan (line 373) | def test_SAT_plan():
FILE: tests/test_logic4e.py
function test_is_symbol (line 17) | def test_is_symbol():
function test_is_var_symbol (line 26) | def test_is_var_symbol():
function test_is_prop_symbol (line 33) | def test_is_prop_symbol():
function test_variables (line 40) | def test_variables():
function test_expr (line 45) | def test_expr():
function test_extend (line 51) | def test_extend():
function test_subst (line 55) | def test_subst():
function test_PropKB (line 59) | def test_PropKB():
function test_wumpus_kb (line 71) | def test_wumpus_kb():
function test_is_definite_clause (line 91) | def test_is_definite_clause():
function test_parse_definite_clause (line 100) | def test_parse_definite_clause():
function test_pl_true (line 107) | def test_pl_true():
function test_tt_true (line 118) | def test_tt_true():
function test_dpll (line 137) | def test_dpll():
function test_find_pure_symbol (line 148) | def test_find_pure_symbol():
function test_unit_clause_assign (line 154) | def test_unit_clause_assign():
function test_find_unit_clause (line 160) | def test_find_unit_clause():
function test_unify (line 164) | def test_unify():
function test_pl_fc_entails (line 172) | def test_pl_fc_entails():
function test_tt_entails (line 181) | def test_tt_entails():
function test_prop_symbols (line 190) | def test_prop_symbols():
function test_constant_symbols (line 195) | def test_constant_symbols():
function test_predicate_symbols (line 200) | def test_predicate_symbols():
function test_eliminate_implications (line 215) | def test_eliminate_implications():
function test_dissociate (line 221) | def test_dissociate():
function test_associate (line 227) | def test_associate():
function test_move_not_inwards (line 234) | def test_move_not_inwards():
function test_distribute_and_over_or (line 240) | def test_distribute_and_over_or():
function test_to_cnf (line 254) | def test_to_cnf():
function test_pl_resolution (line 268) | def test_pl_resolution():
function test_standardize_variables (line 278) | def test_standardize_variables():
function test_fol_bc_ask (line 285) | def test_fol_bc_ask():
function test_fol_fc_ask (line 300) | def test_fol_fc_ask():
function test_d (line 316) | def test_d():
function test_WalkSAT (line 320) | def test_WalkSAT():
function test_SAT_plan (line 343) | def test_SAT_plan():
FILE: tests/test_mdp.py
function test_value_iteration (line 25) | def test_value_iteration():
function test_policy_iteration (line 61) | def test_policy_iteration():
function test_best_policy (line 81) | def test_best_policy():
function test_transition_model (line 105) | def test_transition_model():
function test_pomdp_value_iteration (line 127) | def test_pomdp_value_iteration():
function test_pomdp_value_iteration2 (line 147) | def test_pomdp_value_iteration2():
FILE: tests/test_mdp4e.py
function test_value_iteration (line 25) | def test_value_iteration():
function test_policy_iteration (line 65) | def test_policy_iteration():
function test_best_policy (line 85) | def test_best_policy():
function test_transition_model (line 113) | def test_transition_model():
function test_pomdp_value_iteration (line 135) | def test_pomdp_value_iteration():
function test_pomdp_value_iteration2 (line 155) | def test_pomdp_value_iteration2():
FILE: tests/test_nlp.py
function test_rules (line 20) | def test_rules():
function test_lexicon (line 25) | def test_lexicon():
function test_grammar (line 31) | def test_grammar():
function test_generation (line 44) | def test_generation():
function test_prob_rules (line 64) | def test_prob_rules():
function test_prob_lexicon (line 71) | def test_prob_lexicon():
function test_prob_grammar (line 79) | def test_prob_grammar():
function test_prob_generation (line 93) | def test_prob_generation():
function test_chart_parsing (line 108) | def test_chart_parsing():
function test_CYK_parse (line 114) | def test_CYK_parse():
function test_stripRawHTML (line 177) | def test_stripRawHTML(html_mock):
function test_determineInlinks (line 186) | def test_determineInlinks():
function test_findOutlinks_wiki (line 192) | def test_findOutlinks_wiki():
function test_expand_pages (line 204) | def test_expand_pages():
function test_relevant_pages (line 215) | def test_relevant_pages():
function test_normalize (line 225) | def test_normalize():
function test_detectConvergence (line 236) | def test_detectConvergence():
function test_getInlinks (line 254) | def test_getInlinks():
function test_getOutlinks (line 259) | def test_getOutlinks():
function test_HITS (line 264) | def test_HITS():
FILE: tests/test_nlp4e.py
function test_rules (line 15) | def test_rules():
function test_lexicon (line 20) | def test_lexicon():
function test_grammar (line 26) | def test_grammar():
function test_generation (line 39) | def test_generation():
function test_prob_rules (line 59) | def test_prob_rules():
function test_prob_lexicon (line 66) | def test_prob_lexicon():
function test_prob_grammar (line 74) | def test_prob_grammar():
function test_prob_generation (line 88) | def test_prob_generation():
function test_chart_parsing (line 102) | def test_chart_parsing():
function test_CYK_parse (line 108) | def test_CYK_parse():
function test_subspan (line 120) | def test_subspan():
function test_text_parsing (line 128) | def test_text_parsing():
FILE: tests/test_perception4e.py
function test_array_normalization (line 13) | def test_array_normalization():
function test_sum_squared_difference (line 18) | def test_sum_squared_difference():
function test_gen_gray_scale_picture (line 28) | def test_gen_gray_scale_picture():
function test_generate_edge_weight (line 36) | def test_generate_edge_weight():
function test_graph_bfs (line 41) | def test_graph_bfs():
function test_graph_min_cut (line 49) | def test_graph_min_cut():
function test_gen_discs (line 58) | def test_gen_discs():
function test_simple_convnet (line 64) | def test_simple_convnet():
function test_ROIPoolingLayer (line 72) | def test_ROIPoolingLayer():
FILE: tests/test_planning.py
function test_action (line 13) | def test_action():
function test_air_cargo_1 (line 29) | def test_air_cargo_1():
function test_air_cargo_2 (line 45) | def test_air_cargo_2():
function test_air_cargo_3 (line 61) | def test_air_cargo_3():
function test_air_cargo_4 (line 77) | def test_air_cargo_4():
function test_spare_tire_1 (line 93) | def test_spare_tire_1():
function test_spare_tire_2 (line 106) | def test_spare_tire_2():
function test_three_block_tower (line 119) | def test_three_block_tower():
function test_simple_blocks_world (line 132) | def test_simple_blocks_world():
function test_have_cake_and_eat_cake_too (line 145) | def test_have_cake_and_eat_cake_too():
function test_shopping_problem_1 (line 157) | def test_shopping_problem_1():
function test_shopping_problem_2 (line 172) | def test_shopping_problem_2():
function test_graph_call (line 187) | def test_graph_call():
function test_graphPlan (line 197) | def test_graphPlan():
function test_forwardPlan (line 239) | def test_forwardPlan():
function test_backwardPlan (line 281) | def test_backwardPlan():
function test_CSPlan (line 332) | def test_CSPlan():
function test_SATPlan (line 377) | def test_SATPlan():
function test_linearize_class (line 398) | def test_linearize_class():
function test_expand_actions (line 442) | def test_expand_actions():
function test_expand_feats_values (line 452) | def test_expand_feats_values():
function test_find_open_precondition (line 462) | def test_find_open_precondition():
function test_cyclic (line 484) | def test_cyclic():
function test_partial_order_planner (line 500) | def test_partial_order_planner():
function test_double_tennis (line 513) | def test_double_tennis():
function test_job_shop_problem (line 527) | def test_job_shop_problem():
function test_refinements (line 588) | def test_refinements():
function test_hierarchical_search (line 607) | def test_hierarchical_search():
function test_convert_angelic_HLA (line 633) | def test_convert_angelic_HLA():
function test_is_primitive (line 652) | def test_is_primitive():
function test_angelic_action (line 661) | def test_angelic_action():
function test_optimistic_reachable_set (line 685) | def test_optimistic_reachable_set():
function test_pessimistic_reachable_set (line 700) | def test_pessimistic_reachable_set():
function test_find_reachable_set (line 715) | def test_find_reachable_set():
function test_intersects_goal (line 726) | def test_intersects_goal():
function test_making_progress (line 736) | def test_making_progress():
function test_angelic_search (line 746) | def test_angelic_search():
FILE: tests/test_probabilistic_learning.py
function test_naive_bayes (line 11) | def test_naive_bayes():
FILE: tests/test_probability.py
function tests (line 9) | def tests():
function test_probdist_basic (line 32) | def test_probdist_basic():
function test_probdist_frequency (line 47) | def test_probdist_frequency():
function test_probdist_normalize (line 56) | def test_probdist_normalize():
function test_jointprob (line 69) | def test_jointprob():
function test_event_values (line 77) | def test_event_values():
function test_enumerate_joint (line 82) | def test_enumerate_joint():
function test_enumerate_joint_ask (line 106) | def test_enumerate_joint_ask():
function test_bayesnode_p (line 115) | def test_bayesnode_p():
function test_bayesnode_sample (line 122) | def test_bayesnode_sample():
function test_enumeration_ask (line 130) | def test_enumeration_ask():
function test_elimination_ask (line 148) | def test_elimination_ask():
function test_prior_sample (line 166) | def test_prior_sample():
function test_prior_sample2 (line 179) | def test_prior_sample2():
function test_rejection_sampling (line 192) | def test_rejection_sampling():
function test_rejection_sampling2 (line 211) | def test_rejection_sampling2():
function test_likelihood_weighting (line 230) | def test_likelihood_weighting():
function test_likelihood_weighting2 (line 252) | def test_likelihood_weighting2():
function test_forward_backward (line 271) | def test_forward_backward():
function test_viterbi (line 285) | def test_viterbi():
function test_fixed_lag_smoothing (line 299) | def test_fixed_lag_smoothing():
function test_particle_filtering (line 320) | def test_particle_filtering():
function test_monte_carlo_localization (line 332) | def test_monte_carlo_localization():
function test_gibbs_ask (line 394) | def test_gibbs_ask():
FILE: tests/test_probability4e.py
function tests (line 8) | def tests():
function test_probdist_basic (line 34) | def test_probdist_basic():
function test_probdist_frequency (line 49) | def test_probdist_frequency():
function test_probdist_normalize (line 58) | def test_probdist_normalize():
function test_jointprob (line 74) | def test_jointprob():
function test_event_values (line 82) | def test_event_values():
function test_enumerate_joint (line 87) | def test_enumerate_joint():
function test_enumerate_joint_ask (line 111) | def test_enumerate_joint_ask():
function test_is_independent (line 120) | def test_is_independent():
function test_bayesnode_p (line 131) | def test_bayesnode_p():
function test_bayesnode_sample (line 138) | def test_bayesnode_sample():
function test_gaussian_probability (line 149) | def test_gaussian_probability():
function test_logistic_probability (line 155) | def test_logistic_probability():
function test_enumeration_ask (line 162) | def test_enumeration_ask():
function test_elimination_ask (line 180) | def test_elimination_ask():
function test_prior_sample (line 201) | def test_prior_sample():
function test_prior_sample2 (line 214) | def test_prior_sample2():
function test_rejection_sampling (line 227) | def test_rejection_sampling():
function test_rejection_sampling2 (line 246) | def test_rejection_sampling2():
function test_likelihood_weighting (line 265) | def test_likelihood_weighting():
function test_likelihood_weighting2 (line 287) | def test_likelihood_weighting2():
function test_gibbs_ask (line 306) | def test_gibbs_ask():
FILE: tests/test_reinforcement_learning.py
function test_PassiveDUEAgent (line 20) | def test_PassiveDUEAgent():
function test_PassiveADPAgent (line 33) | def test_PassiveADPAgent():
function test_PassiveTDAgent (line 46) | def test_PassiveTDAgent():
function test_QLearning (line 58) | def test_QLearning():
FILE: tests/test_reinforcement_learning4e.py
function test_PassiveDUEAgent (line 18) | def test_PassiveDUEAgent():
function test_PassiveADPAgent (line 31) | def test_PassiveADPAgent():
function test_PassiveTDAgent (line 44) | def test_PassiveTDAgent():
function test_QLearning (line 56) | def test_QLearning():
FILE: tests/test_search.py
function test_find_min_edge (line 14) | def test_find_min_edge():
function test_breadth_first_tree_search (line 18) | def test_breadth_first_tree_search():
function test_breadth_first_graph_search (line 24) | def test_breadth_first_graph_search():
function test_best_first_graph_search (line 28) | def test_best_first_graph_search():
function test_uniform_cost_search (line 44) | def test_uniform_cost_search():
function test_depth_first_tree_search (line 50) | def test_depth_first_tree_search():
function test_depth_first_graph_search (line 54) | def test_depth_first_graph_search():
function test_iterative_deepening_search (line 59) | def test_iterative_deepening_search():
function test_depth_limited_search (line 64) | def test_depth_limited_search():
function test_bidirectional_search (line 72) | def test_bidirectional_search():
function test_astar_search (line 78) | def test_astar_search():
function test_find_blank_square (line 86) | def test_find_blank_square():
function test_actions (line 96) | def test_actions():
function test_result (line 106) | def test_result():
function test_goal_test (line 117) | def test_goal_test():
function test_check_solvability (line 132) | def test_check_solvability():
function test_conflict (line 145) | def test_conflict():
function test_recursive_best_first_search (line 156) | def test_recursive_best_first_search():
function test_hill_climbing (line 185) | def test_hill_climbing():
function test_simulated_annealing (line 199) | def test_simulated_annealing():
function test_BoggleFinder (line 211) | def test_BoggleFinder():
function test_and_or_graph_search (line 223) | def test_and_or_graph_search():
function test_online_dfs_agent (line 236) | def test_online_dfs_agent():
function test_LRTAStarAgent (line 244) | def test_LRTAStarAgent():
function test_genetic_algorithm (line 259) | def test_genetic_algorithm():
function GA_GraphColoringChars (line 300) | def GA_GraphColoringChars(edges, fitness):
function GA_GraphColoringBools (line 307) | def GA_GraphColoringBools(edges, fitness):
function GA_GraphColoringInts (line 314) | def GA_GraphColoringInts(edges, fitness):
function test_simpleProblemSolvingAgent (line 320) | def test_simpleProblemSolvingAgent():
FILE: tests/test_text.py
function test_text_models (line 12) | def test_text_models():
function test_char_models (line 61) | def test_char_models():
function test_samples (line 126) | def test_samples():
function test_viterbi_segmentation (line 143) | def test_viterbi_segmentation():
function test_shift_encoding (line 154) | def test_shift_encoding():
function test_shift_decoding (line 160) | def test_shift_decoding():
function test_permutation_decoder (line 168) | def test_permutation_decoder():
function test_rot13_encoding (line 180) | def test_rot13_encoding():
function test_rot13_decoding (line 186) | def test_rot13_decoding():
function test_counting_probability_distribution (line 194) | def test_counting_probability_distribution():
function test_ir_system (line 205) | def test_ir_system():
function test_words (line 272) | def test_words():
function test_canonicalize (line 276) | def test_canonicalize():
function test_translate (line 280) | def test_translate():
function test_bigrams (line 287) | def test_bigrams():
FILE: tests/test_utils.py
function test_sequence (line 8) | def test_sequence():
function test_remove_all_list (line 18) | def test_remove_all_list():
function test_remove_all_string (line 25) | def test_remove_all_string():
function test_unique (line 31) | def test_unique():
function test_count (line 37) | def test_count():
function test_multimap (line 45) | def test_multimap():
function test_product (line 52) | def test_product():
function test_first (line 57) | def test_first():
function test_is_in (line 72) | def test_is_in():
function test_mode (line 78) | def test_mode():
function test_power_set (line 84) | def test_power_set():
function test_histogram (line 88) | def test_histogram():
function test_euclidean (line 95) | def test_euclidean():
function test_cross_entropy (line 106) | def test_cross_entropy():
function test_rms_error (line 117) | def test_rms_error():
function test_manhattan_distance (line 125) | def test_manhattan_distance():
function test_mean_boolean_error (line 133) | def test_mean_boolean_error():
function test_mean_error (line 141) | def test_mean_error():
function test_dot_product (line 149) | def test_dot_product():
function test_vector_add (line 154) | def test_vector_add():
function test_rounder (line 159) | def test_rounder():
function test_num_or_str (line 167) | def test_num_or_str():
function test_normalize (line 172) | def test_normalize():
function test_gaussian (line 176) | def test_gaussian():
function test_weighted_choice (line 182) | def test_weighted_choice():
function compare_list (line 188) | def compare_list(x, y):
function test_distance (line 192) | def test_distance():
function test_distance_squared (line 196) | def test_distance_squared():
function test_turn_heading (line 200) | def test_turn_heading():
function test_turn_left (line 211) | def test_turn_left():
function test_turn_right (line 215) | def test_turn_right():
function test_step (line 219) | def test_step():
function test_Expr (line 225) | def test_Expr():
function test_expr (line 248) | def test_expr():
function test_min_priority_queue (line 260) | def test_min_priority_queue():
function test_max_priority_queue (line 276) | def test_max_priority_queue():
function test_priority_queue_with_objects (line 284) | def test_priority_queue_with_objects():
FILE: text.py
class UnigramWordModel (line 22) | class UnigramWordModel(CountingProbDist):
method __init__ (line 27) | def __init__(self, observations, default=0):
method samples (line 32) | def samples(self, n):
class NgramWordModel (line 37) | class NgramWordModel(CountingProbDist):
method __init__ (line 42) | def __init__(self, n, observation_sequence=None, default=0):
method add_cond_prob (line 53) | def add_cond_prob(self, ngram):
method add_sequence (line 59) | def add_sequence(self, words):
method samples (line 68) | def samples(self, nwords):
class NgramCharModel (line 85) | class NgramCharModel(NgramWordModel):
method add_sequence (line 86) | def add_sequence(self, words):
class UnigramCharModel (line 92) | class UnigramCharModel(NgramCharModel):
method __init__ (line 93) | def __init__(self, observation_sequence=None, default=0):
method add_sequence (line 99) | def add_sequence(self, words):
function viterbi_segment (line 108) | def viterbi_segment(text, P):
class IRSystem (line 138) | class IRSystem:
method __init__ (line 147) | def __init__(self, stopwords='the a of'):
method index_collection (line 155) | def index_collection(self, filenames):
method index_document (line 161) | def index_document(self, text, url):
method query (line 172) | def query(self, query_text, n=10):
method score (line 185) | def score(self, word, docid):
method total_score (line 190) | def total_score(self, words, docid):
method present (line 194) | def present(self, results):
method present_results (line 200) | def present_results(self, query_text, n=10):
class UnixConsultant (line 205) | class UnixConsultant(IRSystem):
method __init__ (line 208) | def __init__(self):
class Document (line 219) | class Document:
method __init__ (line 222) | def __init__(self, title, url, nwords):
function words (line 228) | def words(text, reg=re.compile('[a-z0-9]+')):
function canonicalize (line 237) | def canonicalize(text):
function shift_encode (line 258) | def shift_encode(plaintext, n):
function rot13 (line 266) | def rot13(plaintext):
function translate (line 276) | def translate(plaintext, function):
function maketrans (line 284) | def maketrans(from_, to_):
function encode (line 293) | def encode(plaintext, code):
function bigrams (line 300) | def bigrams(text):
class ShiftDecoder (line 313) | class ShiftDecoder:
method __init__ (line 318) | def __init__(self, training_text):
method score (line 322) | def score(self, plaintext):
method decode (line 331) | def decode(self, ciphertext):
function all_shifts (line 337) | def all_shifts(text):
class PermutationDecoder (line 346) | class PermutationDecoder:
method __init__ (line 360) | def __init__(self, training_text, ciphertext=None):
method decode (line 365) | def decode(self, ciphertext):
method score (line 377) | def score(self, code):
class PermutationDecoderProblem (line 395) | class PermutationDecoderProblem(search.Problem):
method __init__ (line 397) | def __init__(self, initial=None, goal=None, decoder=None):
method actions (line 401) | def actions(self, state):
method result (line 409) | def result(self, state, action):
method goal_test (line 414) | def goal_test(self, state):
FILE: utils.py
function sequence (line 21) | def sequence(iterable):
function remove_all (line 26) | def remove_all(item, seq):
function unique (line 38) | def unique(seq):
function count (line 43) | def count(seq):
function multimap (line 48) | def multimap(items):
function multimap_items (line 56) | def multimap_items(mmap):
function product (line 63) | def product(numbers):
function first (line 71) | def first(iterable, default=None):
function is_in (line 76) | def is_in(elt, seq):
function mode (line 81) | def mode(data):
function power_set (line 87) | def power_set(iterable):
function extend (line 93) | def extend(s, var, val):
function flatten (line 98) | def flatten(seqs):
function argmin_random_tie (line 108) | def argmin_random_tie(seq, key=identity):
function argmax_random_tie (line 113) | def argmax_random_tie(seq, key=identity):
function shuffled (line 118) | def shuffled(iterable):
function histogram (line 129) | def histogram(values, mode=0, bin_function=None):
function dot_product (line 146) | def dot_product(x, y):
function element_wise_product (line 151) | def element_wise_product(x, y):
function matrix_multiplication (line 157) | def matrix_multiplication(x, *y):
function vector_add (line 167) | def vector_add(a, b):
function scalar_vector_product (line 172) | def scalar_vector_product(x, y):
function probability (line 177) | def probability(p):
function weighted_sample_with_replacement (line 182) | def weighted_sample_with_replacement(n, seq, weights):
function weighted_sampler (line 190) | def weighted_sampler(seq, weights):
function weighted_choice (line 198) | def weighted_choice(choices):
function rounder (line 211) | def rounder(numbers, d=4):
function num_or_str (line 220) | def num_or_str(x): # TODO: rename as `atom`
function euclidean_distance (line 231) | def euclidean_distance(x, y):
function manhattan_distance (line 235) | def manhattan_distance(x, y):
function hamming_distance (line 239) | def hamming_distance(x, y):
function cross_entropy_loss (line 243) | def cross_entropy_loss(x, y):
function mean_squared_error_loss (line 247) | def mean_squared_error_loss(x, y):
function rms_error (line 251) | def rms_error(x, y):
function ms_error (line 255) | def ms_error(x, y):
function mean_error (line 259) | def mean_error(x, y):
function mean_boolean_error (line 263) | def mean_boolean_error(x, y):
function normalize (line 267) | def normalize(dist):
function random_weights (line 279) | def random_weights(min_value, max_value, num_weights):
function sigmoid (line 283) | def sigmoid(x):
function sigmoid_derivative (line 288) | def sigmoid_derivative(value):
function elu (line 292) | def elu(x, alpha=0.01):
function elu_derivative (line 296) | def elu_derivative(value, alpha=0.01):
function tanh (line 300) | def tanh(x):
function tanh_derivative (line 304) | def tanh_derivative(value):
function leaky_relu (line 308) | def leaky_relu(x, alpha=0.01):
function leaky_relu_derivative (line 312) | def leaky_relu_derivative(value, alpha=0.01):
function relu (line 316) | def relu(x):
function relu_derivative (line 320) | def relu_derivative(value):
function step (line 324) | def step(x):
function gaussian (line 329) | def gaussian(mean, st_dev, x):
function linear_kernel (line 334) | def linear_kernel(x, y=None):
function polynomial_kernel (line 340) | def polynomial_kernel(x, y=None, degree=2.0):
function rbf_kernel (line 346) | def rbf_kernel(x, y=None, gamma=None):
function turn_heading (line 364) | def turn_heading(heading, inc, headings=orientations):
function turn_right (line 368) | def turn_right(heading):
function turn_left (line 372) | def turn_left(heading):
function distance (line 376) | def distance(a, b):
function distance_squared (line 383) | def distance_squared(a, b):
class injection (line 393) | class injection:
method __init__ (line 397) | def __init__(self, **kwds):
method __enter__ (line 400) | def __enter__(self):
method __exit__ (line 404) | def __exit__(self, type, value, traceback):
function memoize (line 408) | def memoize(fn, slot=None, maxsize=32):
function name (line 428) | def name(obj):
function isnumber (line 435) | def isnumber(x):
function issequence (line 440) | def issequence(x):
function print_table (line 445) | def print_table(table, header=None, sep=' ', numfmt='{}'):
function open_data (line 465) | def open_data(name, mode='r'):
function failure_test (line 472) | def failure_test(algorithm, tests):
class Expr (line 487) | class Expr:
method __init__ (line 493) | def __init__(self, op, *args):
method __neg__ (line 498) | def __neg__(self):
method __pos__ (line 501) | def __pos__(self):
method __invert__ (line 504) | def __invert__(self):
method __add__ (line 507) | def __add__(self, rhs):
method __sub__ (line 510) | def __sub__(self, rhs):
method __mul__ (line 513) | def __mul__(self, rhs):
method __pow__ (line 516) | def __pow__(self, rhs):
method __mod__ (line 519) | def __mod__(self, rhs):
method __and__ (line 522) | def __and__(self, rhs):
method __xor__ (line 525) | def __xor__(self, rhs):
method __rshift__ (line 528) | def __rshift__(self, rhs):
method __lshift__ (line 531) | def __lshift__(self, rhs):
method __truediv__ (line 534) | def __truediv__(self, rhs):
method __floordiv__ (line 537) | def __floordiv__(self, rhs):
method __matmul__ (line 540) | def __matmul__(self, rhs):
method __or__ (line 543) | def __or__(self, rhs):
method __radd__ (line 551) | def __radd__(self, lhs):
method __rsub__ (line 554) | def __rsub__(self, lhs):
method __rmul__ (line 557) | def __rmul__(self, lhs):
method __rdiv__ (line 560) | def __rdiv__(self, lhs):
method __rpow__ (line 563) | def __rpow__(self, lhs):
method __rmod__ (line 566) | def __rmod__(self, lhs):
method __rand__ (line 569) | def __rand__(self, lhs):
method __rxor__ (line 572) | def __rxor__(self, lhs):
method __ror__ (line 575) | def __ror__(self, lhs):
method __rrshift__ (line 578) | def __rrshift__(self, lhs):
method __rlshift__ (line 581) | def __rlshift__(self, lhs):
method __rtruediv__ (line 584) | def __rtruediv__(self, lhs):
method __rfloordiv__ (line 587) | def __rfloordiv__(self, lhs):
method __rmatmul__ (line 590) | def __rmatmul__(self, lhs):
method __call__ (line 593) | def __call__(self, *args):
method __eq__ (line 601) | def __eq__(self, other):
method __lt__ (line 605) | def __lt__(self, other):
method __hash__ (line 608) | def __hash__(self):
method __repr__ (line 611) | def __repr__(self):
function Symbol (line 631) | def Symbol(name):
function symbols (line 636) | def symbols(names):
function subexpressions (line 641) | def subexpressions(x):
function arity (line 649) | def arity(expression):
class PartialExpr (line 660) | class PartialExpr:
method __init__ (line 663) | def __init__(self, op, lhs):
method __or__ (line 666) | def __or__(self, rhs):
method __repr__ (line 669) | def __repr__(self):
function expr (line 673) | def expr(x):
function expr_handle_infix_ops (line 687) | def expr_handle_infix_ops(x):
class defaultkeydict (line 697) | class defaultkeydict(collections.defaultdict):
method __missing__ (line 703) | def __missing__(self, key):
class hashabledict (line 708) | class hashabledict(dict):
method __hash__ (line 712) | def __hash__(self):
class PriorityQueue (line 722) | class PriorityQueue:
method __init__ (line 729) | def __init__(self, order='min', f=lambda x: x):
method append (line 738) | def append(self, item):
method extend (line 742) | def extend(self, items):
method pop (line 747) | def pop(self):
method __len__ (line 755) | def __len__(self):
method __contains__ (line 759) | def __contains__(self, key):
method __getitem__ (line 763) | def __getitem__(self, key):
method __delitem__ (line 771) | def __delitem__(self, key):
class Bool (line 784) | class Bool(int):
FILE: utils4e.py
class PriorityQueue (line 23) | class PriorityQueue:
method __init__ (line 29) | def __init__(self, order='min', f=lambda x: x):
method append (line 39) | def append(self, item):
method extend (line 43) | def extend(self, items):
method pop (line 48) | def pop(self):
method __len__ (line 56) | def __len__(self):
method __contains__ (line 60) | def __contains__(self, key):
method __getitem__ (line 64) | def __getitem__(self, key):
method __delitem__ (line 72) | def __delitem__(self, key):
function sequence (line 85) | def sequence(iterable):
function remove_all (line 91) | def remove_all(item, seq):
function unique (line 103) | def unique(seq):
function count (line 108) | def count(seq):
function multimap (line 113) | def multimap(items):
function multimap_items (line 121) | def multimap_items(mmap):
function product (line 128) | def product(numbers):
function first (line 136) | def first(iterable, default=None):
function is_in (line 141) | def is_in(elt, seq):
function mode (line 146) | def mode(data):
function power_set (line 152) | def power_set(iterable):
function extend (line 158) | def extend(s, var, val):
function flatten (line 163) | def flatten(seqs):
function argmin_random_tie (line 174) | def argmin_random_tie(seq, key=identity):
function argmax_random_tie (line 179) | def argmax_random_tie(seq, key=identity):
function shuffled (line 184) | def shuffled(iterable):
function histogram (line 195) | def histogram(values, mode=0, bin_function=None):
function element_wise_product (line 212) | def element_wise_product(x, y):
function vector_add (line 222) | def vector_add(a, b):
function scalar_vector_product (line 236) | def scalar_vector_product(x, y):
function map_vector (line 241) | def map_vector(f, x):
function probability (line 246) | def probability(p):
function weighted_sample_with_replacement (line 251) | def weighted_sample_with_replacement(n, seq, weights):
function weighted_sampler (line 260) | def weighted_sampler(seq, weights):
function weighted_choice (line 269) | def weighted_choice(choices):
function rounder (line 282) | def rounder(numbers, d=4):
function num_or_str (line 291) | def num_or_str(x): # TODO: rename as `atom`
function euclidean_distance (line 303) | def euclidean_distance(x, y):
function manhattan_distance (line 307) | def manhattan_distance(x, y):
function hamming_distance (line 311) | def hamming_distance(x, y):
function rms_error (line 315) | def rms_error(x, y):
function ms_error (line 319) | def ms_error(x, y):
function mean_error (line 323) | def mean_error(x, y):
function mean_boolean_error (line 327) | def mean_boolean_error(x, y):
function cross_entropy_loss (line 335) | def cross_entropy_loss(x, y):
function mean_squared_error_loss (line 340) | def mean_squared_error_loss(x, y):
function normalize (line 345) | def normalize(dist):
function random_weights (line 357) | def random_weights(min_value, max_value, num_weights):
function conv1D (line 361) | def conv1D(x, k):
function gaussian_kernel (line 366) | def gaussian_kernel(size=3):
function gaussian_kernel_1D (line 370) | def gaussian_kernel_1D(size=3, sigma=0.5):
function gaussian_kernel_2D (line 374) | def gaussian_kernel_2D(size=3, sigma=0.5):
function step (line 380) | def step(x):
function gaussian (line 385) | def gaussian(mean, st_dev, x):
function linear_kernel (line 390) | def linear_kernel(x, y=None):
function polynomial_kernel (line 396) | def polynomial_kernel(x, y=None, degree=2.0):
function rbf_kernel (line 402) | def rbf_kernel(x, y=None, gamma=None):
function turn_heading (line 421) | def turn_heading(heading, inc, headings=orientations):
function turn_right (line 425) | def turn_right(heading):
function turn_left (line 429) | def turn_left(heading):
function distance (line 433) | def distance(a, b):
function distance_squared (line 440) | def distance_squared(a, b):
class injection (line 451) | class injection:
method __init__ (line 455) | def __init__(self, **kwds):
method __enter__ (line 458) | def __enter__(self):
method __exit__ (line 462) | def __exit__(self, type, value, traceback):
function memoize (line 466) | def memoize(fn, slot=None, maxsize=32):
function name (line 486) | def name(obj):
function isnumber (line 493) | def isnumber(x):
function issequence (line 498) | def issequence(x):
function print_table (line 503) | def print_table(table, header=None, sep=' ', numfmt='{}'):
function open_data (line 525) | def open_data(name, mode='r'):
function failure_test (line 532) | def failure_test(algorithm, tests):
class Expr (line 548) | class Expr:
method __init__ (line 554) | def __init__(self, op, *args):
method __neg__ (line 559) | def __neg__(self):
method __pos__ (line 562) | def __pos__(self):
method __invert__ (line 565) | def __invert__(self):
method __add__ (line 568) | def __add__(self, rhs):
method __sub__ (line 571) | def __sub__(self, rhs):
method __mul__ (line 574) | def __mul__(self, rhs):
method __pow__ (line 577) | def __pow__(self, rhs):
method __mod__ (line 580) | def __mod__(self, rhs):
method __and__ (line 583) | def __and__(self, rhs):
method __xor__ (line 586) | def __xor__(self, rhs):
method __rshift__ (line 589) | def __rshift__(self, rhs):
method __lshift__ (line 592) | def __lshift__(self, rhs):
method __truediv__ (line 595) | def __truediv__(self, rhs):
method __floordiv__ (line 598) | def __floordiv__(self, rhs):
method __matmul__ (line 601) | def __matmul__(self, rhs):
method __or__ (line 604) | def __or__(self, rhs):
method __radd__ (line 612) | def __radd__(self, lhs):
method __rsub__ (line 615) | def __rsub__(self, lhs):
method __rmul__ (line 618) | def __rmul__(self, lhs):
method __rdiv__ (line 621) | def __rdiv__(self, lhs):
method __rpow__ (line 624) | def __rpow__(self, lhs):
method __rmod__ (line 627) | def __rmod__(self, lhs):
method __rand__ (line 630) | def __rand__(self, lhs):
method __rxor__ (line 633) | def __rxor__(self, lhs):
method __ror__ (line 636) | def __ror__(self, lhs):
method __rrshift__ (line 639) | def __rrshift__(self, lhs):
method __rlshift__ (line 642) | def __rlshift__(self, lhs):
method __rtruediv__ (line 645) | def __rtruediv__(self, lhs):
method __rfloordiv__ (line 648) | def __rfloordiv__(self, lhs):
method __rmatmul__ (line 651) | def __rmatmul__(self, lhs):
method __call__ (line 654) | def __call__(self, *args):
method __eq__ (line 662) | def __eq__(self, other):
method __lt__ (line 666) | def __lt__(self, other):
method __hash__ (line 669) | def __hash__(self):
method __repr__ (line 672) | def __repr__(self):
function Symbol (line 692) | def Symbol(name):
function symbols (line 697) | def symbols(names):
function subexpressions (line 702) | def subexpressions(x):
function arity (line 710) | def arity(expression):
class PartialExpr (line 721) | class PartialExpr:
method __init__ (line 724) | def __init__(self, op, lhs):
method __or__ (line 727) | def __or__(self, rhs):
method __repr__ (line 730) | def __repr__(self):
function expr (line 734) | def expr(x):
function expr_handle_infix_ops (line 751) | def expr_handle_infix_ops(x):
class defaultkeydict (line 761) | class defaultkeydict(collections.defaultdict):
method __missing__ (line 767) | def __missing__(self, key):
class hashabledict (line 772) | class hashabledict(dict):
method __hash__ (line 776) | def __hash__(self):
class MCT_Node (line 784) | class MCT_Node:
method __init__ (line 787) | def __init__(self, parent=None, state=None, U=0, N=0):
function ucb (line 793) | def ucb(n, C=1.4):
class Bool (line 801) | class Bool(int):
Condensed preview — 129 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (7,425K chars).
[
{
"path": ".coveragerc",
"chars": 28,
"preview": "[report]\nomit = \n tests/*"
},
{
"path": ".flake8",
"chars": 131,
"preview": "[flake8]\nmax-line-length = 100\nignore = E121,E123,E126,E221,E222,E225,E226,E242,E701,E702,E704,E731,W503,F405,F841\nexclu"
},
{
"path": ".gitignore",
"chars": 914,
"preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
},
{
"path": ".gitmodules",
"chars": 91,
"preview": "[submodule \"aima-data\"]\n\tpath = aima-data\n\turl = https://github.com/aimacode/aima-data.git\n"
},
{
"path": ".travis.yml",
"chars": 381,
"preview": "language: python\n\npython:\n - 3.5\n - 3.6\n - 3.7\n - 3.8\n\nbefore_install:\n - git submodule update --remote\n\ninstall:\n "
},
{
"path": "CONTRIBUTING.md",
"chars": 10425,
"preview": "How to Contribute to aima-python\n==========================\n\nThanks for considering contributing to `aima-python`! Wheth"
},
{
"path": "LICENSE",
"chars": 1091,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2016 aima-python contributors\n\nPermission is hereby granted, free of charge, to any"
},
{
"path": "README.md",
"chars": 19377,
"preview": "\n\n# `aima-python` [](https://travis-ci.org/"
},
{
"path": "SUBMODULE.md",
"chars": 599,
"preview": "This is a guide on how to update the `aima-data` submodule to the latest version. This needs to be done every time somet"
},
{
"path": "agents.ipynb",
"chars": 27933,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Intelligent Agents #\\n\",\n \"\\n\""
},
{
"path": "agents.py",
"chars": 36213,
"preview": "\"\"\"\nImplement Agents and Environments. (Chapters 1-2)\n\nThe class hierarchies are as follows:\n\nThing ## A physical object"
},
{
"path": "agents4e.py",
"chars": 36976,
"preview": "\"\"\"\nImplement Agents and Environments. (Chapters 1-2)\n\nThe class hierarchies are as follows:\n\nThing ## A physical object"
},
{
"path": "arc_consistency_heuristics.ipynb",
"chars": 94184,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"pycharm\": {}\n },\n \"source\": [\n \"# Constraint "
},
{
"path": "classical_planning_approaches.ipynb",
"chars": 184851,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Classical Planning\\n\",\n \"---\\n"
},
{
"path": "csp.ipynb",
"chars": 231721,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# CONSTRAINT SATISFACTION PROBLEMS\\"
},
{
"path": "csp.py",
"chars": 55386,
"preview": "\"\"\"CSP (Constraint Satisfaction Problems) problems and solvers. (Chapter 6)\"\"\"\n\nimport itertools\nimport random\nimport re"
},
{
"path": "deep_learning4e.py",
"chars": 18651,
"preview": "\"\"\"Deep learning. (Chapters 20)\"\"\"\n\nimport random\nimport statistics\n\nimport numpy as np\nfrom keras import Sequential, op"
},
{
"path": "games.ipynb",
"chars": 64030,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# GAMES OR ADVERSARIAL SEARCH\\n\",\n "
},
{
"path": "games.py",
"chars": 20998,
"preview": "\"\"\"Games or Adversarial Search (Chapter 5)\"\"\"\n\nimport copy\nimport itertools\nimport random\nfrom collections import namedt"
},
{
"path": "games4e.ipynb",
"chars": 47639,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Game Tree Search\\n\",\n \"\\n\",\n "
},
{
"path": "games4e.py",
"chars": 22458,
"preview": "\"\"\"Games or Adversarial Search (Chapter 5)\"\"\"\n\nimport copy\nimport itertools\nimport random\nfrom collections import namedt"
},
{
"path": "gui/eight_puzzle.py",
"chars": 5091,
"preview": "import os.path\nimport random\nimport time\nfrom functools import partial\nfrom tkinter import *\n\nfrom search import astar_s"
},
{
"path": "gui/genetic_algorithm_example.py",
"chars": 7497,
"preview": "# A simple program that implements the solution to the phrase generation problem using\n# genetic algorithms as given in "
},
{
"path": "gui/grid_mdp.py",
"chars": 26624,
"preview": "import os.path\nimport sys\nimport tkinter as tk\nimport tkinter.messagebox\nfrom functools import partial\nfrom tkinter impo"
},
{
"path": "gui/romania_problem.py",
"chars": 21295,
"preview": "from copy import deepcopy\nfrom tkinter import *\n\nfrom search import *\nfrom utils import PriorityQueue\n\nsys.path.append(o"
},
{
"path": "gui/tic-tac-toe.py",
"chars": 6762,
"preview": "import os.path\nfrom tkinter import *\n\nfrom games import minmax_decision, alpha_beta_player, random_player, TicTacToe\n# \""
},
{
"path": "gui/tsp.py",
"chars": 14696,
"preview": "from tkinter import *\nfrom tkinter import messagebox\n\nimport utils\nfrom search import *\n\nsys.path.append(os.path.join(os"
},
{
"path": "gui/vacuum_agent.py",
"chars": 5939,
"preview": "import os.path\nfrom tkinter import *\n\nfrom agents import *\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'"
},
{
"path": "gui/xy_vacuum_environment.py",
"chars": 7186,
"preview": "import os.path\nfrom tkinter import *\n\nfrom agents import *\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'"
},
{
"path": "images/IMAGE-CREDITS",
"chars": 377,
"preview": "PHOTO CREDITS\n\nImage After http://www.imageafter.com/\n\n b15woods003.jpg \n (Cropped to 764x764 and scaled to 50x50 t"
},
{
"path": "images/makefile",
"chars": 562,
"preview": "# makefile for images\n\nSources = dirt.svg vacuum.svg\n\nTargets = $(Sources:.svg=.png)\n\nImageScale = 50x50\n\nTemporary = tm"
},
{
"path": "improving_sat_algorithms.ipynb",
"chars": 151376,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"pycharm\": {}\n },\n \"source\": [\n \"# Proposition"
},
{
"path": "index.ipynb",
"chars": 2348,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# AIMA Python Binder Index\\n\",\n "
},
{
"path": "intro.ipynb",
"chars": 6408,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# An Introduction To `aima-python` "
},
{
"path": "ipyviews.py",
"chars": 5574,
"preview": "from IPython.display import HTML, display, clear_output\nfrom collections import defaultdict\nfrom agents import PolygonOb"
},
{
"path": "js/canvas.js",
"chars": 3656,
"preview": "/*\n JavaScript functions that are executed by running the corresponding methods of a Canvas object\n Donot use these fu"
},
{
"path": "js/continuousworld.js",
"chars": 2107,
"preview": "var latest_output_area =\"NONE\"; // Jquery object for the DOM element of output area which was used most recently\nfunctio"
},
{
"path": "js/gridworld.js",
"chars": 4053,
"preview": "var latest_output_area =\"NONE\"; // Jquery object for the DOM element of output area which was used most recently\n\nfuncti"
},
{
"path": "knowledge.py",
"chars": 13291,
"preview": "\"\"\"Knowledge in learning (Chapter 19)\"\"\"\n\nfrom collections import defaultdict\nfrom functools import partial\nfrom itertoo"
},
{
"path": "knowledge_FOIL.ipynb",
"chars": 47713,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# KNOWLEDGE\\n\",\n \"\\n\",\n \"The "
},
{
"path": "knowledge_current_best.ipynb",
"chars": 37682,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# KNOWLEDGE\\n\",\n \"\\n\",\n \"The "
},
{
"path": "knowledge_version_space.ipynb",
"chars": 59689,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# KNOWLEDGE\\n\",\n \"\\n\",\n \"The "
},
{
"path": "learning.ipynb",
"chars": 663971,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# LEARNING\\n\",\n \"\\n\",\n \"This "
},
{
"path": "learning.py",
"chars": 45678,
"preview": "\"\"\"Learning from examples (Chapters 18)\"\"\"\n\nimport copy\nfrom collections import defaultdict\nfrom statistics import stdev"
},
{
"path": "learning4e.py",
"chars": 38738,
"preview": "\"\"\"Learning from examples (Chapters 18)\"\"\"\n\nimport copy\nfrom collections import defaultdict\nfrom statistics import stdev"
},
{
"path": "learning_apps.ipynb",
"chars": 553967,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# LEARNING APPLICATIONS\\n\",\n \"\\n"
},
{
"path": "logic.ipynb",
"chars": 265780,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"collapsed\": true\n },\n \"source\": [\n \"# Logic\"\n"
},
{
"path": "logic.py",
"chars": 74057,
"preview": "\"\"\"\nRepresentations and Inference for Logic. (Chapters 7-9, 12)\n\nCovers both Propositional and First-Order Logic. First "
},
{
"path": "logic4e.py",
"chars": 52096,
"preview": "\"\"\"Representations and Inference for Logic (Chapters 7-10)\n\nCovers both Propositional and First-Order Logic. First we ha"
},
{
"path": "making_simple_decision4e.py",
"chars": 5869,
"preview": "\"\"\"Making Simple Decisions (Chapter 15)\"\"\"\n\nimport random\n\nfrom agents import Agent\nfrom probability import BayesNet\nfro"
},
{
"path": "mdp.ipynb",
"chars": 280438,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Making Complex Decisions\\n\",\n "
},
{
"path": "mdp.py",
"chars": 16758,
"preview": "\"\"\"\nMarkov Decision Processes (Chapter 17)\n\nFirst we define an MDP, and the special case of a GridMDP, in which\nstates a"
},
{
"path": "mdp4e.py",
"chars": 17475,
"preview": "\"\"\"\nMarkov Decision Processes (Chapter 16)\n\nFirst we define an MDP, and the special case of a GridMDP, in which\nstates a"
},
{
"path": "mdp_apps.ipynb",
"chars": 84500,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# APPLICATIONS OF MARKOV DECISION P"
},
{
"path": "neural_nets.ipynb",
"chars": 47268,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# NEURAL NETWORKS\\n\",\n \"\\n\",\n "
},
{
"path": "nlp.ipynb",
"chars": 47274,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# NATURAL LANGUAGE PROCESSING\\n\",\n "
},
{
"path": "nlp.py",
"chars": 22011,
"preview": "\"\"\"Natural Language Processing; Chart Parsing and PageRanking (Chapter 22-23)\"\"\"\n\nfrom collections import defaultdict\nfr"
},
{
"path": "nlp4e.py",
"chars": 20036,
"preview": "\"\"\"Natural Language Processing (Chapter 22)\"\"\"\n\nfrom collections import defaultdict\nfrom utils4e import weighted_choice\n"
},
{
"path": "nlp_apps.ipynb",
"chars": 39580,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# NATURAL LANGUAGE PROCESSING APPLI"
},
{
"path": "notebook.py",
"chars": 43285,
"preview": "import time\nfrom collections import defaultdict\nfrom inspect import getsource\n\nimport ipywidgets as widgets\nimport matpl"
},
{
"path": "notebook4e.py",
"chars": 44488,
"preview": "import time\nfrom collections import defaultdict\nfrom inspect import getsource\n\nimport ipywidgets as widgets\nimport matpl"
},
{
"path": "notebooks/chapter19/Learners.ipynb",
"chars": 16227,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Learners\\n\",\n \"\\n\",\n \"In th"
},
{
"path": "notebooks/chapter19/Loss Functions and Layers.ipynb",
"chars": 12778,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Loss Function\\n\",\n \"\\n\",\n \""
},
{
"path": "notebooks/chapter19/Optimizer and Backpropagation.ipynb",
"chars": 19451,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Optimization Algorithms\\n\",\n \""
},
{
"path": "notebooks/chapter19/RNN.ipynb",
"chars": 29332,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# RNN\\n\",\n \"\\n\",\n \"## Overvie"
},
{
"path": "notebooks/chapter21/Active Reinforcement Learning.ipynb",
"chars": 6862,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# ACTIVE REINFORCEMENT LEARNING\\n\","
},
{
"path": "notebooks/chapter21/Passive Reinforcement Learning.ipynb",
"chars": 15583,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Introduction to Reinforcement Lea"
},
{
"path": "notebooks/chapter22/Grammar.ipynb",
"chars": 22302,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Grammar\\n\",\n \"\\n\",\n \"Langua"
},
{
"path": "notebooks/chapter22/Introduction.ipynb",
"chars": 2925,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# NATURAL LANGUAGE PROCESSING\\n\",\n "
},
{
"path": "notebooks/chapter22/Parsing.ipynb",
"chars": 19298,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Parsing\\n\",\n \"\\n\",\n \"## Ove"
},
{
"path": "notebooks/chapter22/nlp_apps.ipynb",
"chars": 39580,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# NATURAL LANGUAGE PROCESSING APPLI"
},
{
"path": "notebooks/chapter24/Image Edge Detection.ipynb",
"chars": 219430,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Edge Detection\\n\",\n \"\\n\",\n "
},
{
"path": "notebooks/chapter24/Image Segmentation.ipynb",
"chars": 33574,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Segmentation\\n\",\n \"\\n\",\n \"I"
},
{
"path": "notebooks/chapter24/Objects in Images.ipynb",
"chars": 19381,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Objects in Images\\n\",\n \"\\n\",\n "
},
{
"path": "obsolete_search4e.ipynb",
"chars": 264276,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"button\": false,\n \"new_sheet\": false,\n \"run_con"
},
{
"path": "perception4e.py",
"chars": 16421,
"preview": "\"\"\"Perception (Chapter 24)\"\"\"\n\nimport cv2\nimport keras\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.s"
},
{
"path": "planning.ipynb",
"chars": 249051,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"collapsed\": true\n },\n \"source\": [\n \"# Plannin"
},
{
"path": "planning.py",
"chars": 81002,
"preview": "\"\"\"Planning (Chapters 10-11)\"\"\"\n\nimport copy\nimport itertools\nfrom collections import deque, defaultdict\nfrom functools "
},
{
"path": "planning_angelic_search.ipynb",
"chars": 38218,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Angelic Search \\n\",\n \"\\n\",\n "
},
{
"path": "planning_graphPlan.ipynb",
"chars": 84141,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"## SOLVING PLANNING PROBLEMS\\n\",\n "
},
{
"path": "planning_hierarchical_search.ipynb",
"chars": 34358,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Hierarchical Search \\n\",\n \"\\n\""
},
{
"path": "planning_partial_order_planner.ipynb",
"chars": 85543,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"### PARTIAL ORDER PLANNER\\n\",\n "
},
{
"path": "planning_total_order_planner.ipynb",
"chars": 18251,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"### TOTAL ORDER PLANNER\\n\",\n \"\\n"
},
{
"path": "probabilistic_learning.py",
"chars": 5334,
"preview": "\"\"\"Learning probabilistic models. (Chapters 20)\"\"\"\n\nimport heapq\n\nfrom utils import weighted_sampler, product, gaussian\n"
},
{
"path": "probability.ipynb",
"chars": 407012,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Probability \\n\",\n \"\\n\",\n \"T"
},
{
"path": "probability.py",
"chars": 29608,
"preview": "\"\"\"Probability models (Chapter 13-15)\"\"\"\n\nfrom collections import defaultdict\nfrom functools import reduce\n\nfrom agents "
},
{
"path": "probability4e.ipynb",
"chars": 40193,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"button\": false,\n \"deletable\": true,\n \"new_shee"
},
{
"path": "probability4e.py",
"chars": 26117,
"preview": "\"\"\"Probability models (Chapter 12-13)\"\"\"\n\nimport copy\nimport random\nfrom collections import defaultdict\nfrom functools i"
},
{
"path": "pytest.ini",
"chars": 108,
"preview": "[pytest]\nfilterwarnings =\n ignore::DeprecationWarning\n ignore::UserWarning\n ignore::RuntimeWarning\n"
},
{
"path": "reinforcement_learning.ipynb",
"chars": 21836,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Reinforcement Learning\\n\",\n \"\\"
},
{
"path": "reinforcement_learning.py",
"chars": 11380,
"preview": "\"\"\"Reinforcement Learning (Chapter 21)\"\"\"\n\nimport random\nfrom collections import defaultdict\n\nfrom mdp import MDP, polic"
},
{
"path": "reinforcement_learning4e.py",
"chars": 11698,
"preview": "\"\"\"Reinforcement Learning (Chapter 21)\"\"\"\n\nimport random\nfrom collections import defaultdict\n\nfrom mdp4e import MDP, pol"
},
{
"path": "requirements.txt",
"chars": 168,
"preview": "cvxopt\nimage\nipython\nipythonblocks\nipywidgets\njupyter\nkeras\nmatplotlib\nnetworkx\nnumpy\nopencv-python\npandas\npillow\npytest"
},
{
"path": "search.ipynb",
"chars": 675281,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {\n \"collapsed\": true\n },\n \"source\": [\n \"# Solving"
},
{
"path": "search.py",
"chars": 55316,
"preview": "\"\"\"\nSearch (Chapters 3-4)\n\nThe way to use this code is to subclass Problem to create a class of problems,\nthen create pr"
},
{
"path": "search4e.ipynb",
"chars": 331100,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Search for AIMA 4th edition\\n\",\n "
},
{
"path": "tests/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "tests/pytest.ini",
"chars": 53,
"preview": "[pytest]\nfilterwarnings =\n ignore::ResourceWarning"
},
{
"path": "tests/test_agents.py",
"chars": 12936,
"preview": "import random\n\nimport pytest\n\nfrom agents import (ReflexVacuumAgent, ModelBasedVacuumAgent, TrivialVacuumEnvironment, co"
},
{
"path": "tests/test_agents4e.py",
"chars": 13008,
"preview": "import random\n\nimport pytest\n\nfrom agents4e import (ReflexVacuumAgent, ModelBasedVacuumAgent, TrivialVacuumEnvironment, "
},
{
"path": "tests/test_csp.py",
"chars": 24289,
"preview": "import pytest\nfrom utils import failure_test\nfrom csp import *\nimport random\n\nrandom.seed(\"aima-python\")\n\n\ndef test_csp_"
},
{
"path": "tests/test_deep_learning4e.py",
"chars": 2653,
"preview": "import pytest\nfrom keras.datasets import imdb\n\nfrom deep_learning4e import *\nfrom learning4e import DataSet, grade_learn"
},
{
"path": "tests/test_games.py",
"chars": 2306,
"preview": "import pytest\n\nfrom games import *\n\n# Creating the game instances\nf52 = Fig52Game()\nttt = TicTacToe()\n\nrandom.seed(\"aima"
},
{
"path": "tests/test_games4e.py",
"chars": 3436,
"preview": "import pytest\n\nfrom games4e import *\n\n# Creating the game instances\nf52 = Fig52Game()\nttt = TicTacToe()\ncon4 = ConnectFo"
},
{
"path": "tests/test_knowledge.py",
"chars": 13157,
"preview": "import pytest\n\nfrom knowledge import *\nfrom utils import expr\nimport random\n\nrandom.seed(\"aima-python\")\n\nparty = [\n {"
},
{
"path": "tests/test_learning.py",
"chars": 5018,
"preview": "import pytest\n\nfrom learning import *\n\nrandom.seed(\"aima-python\")\n\n\ndef test_exclude():\n iris = DataSet(name='iris', "
},
{
"path": "tests/test_learning4e.py",
"chars": 4131,
"preview": "import pytest\n\nfrom deep_learning4e import PerceptronLearner\nfrom learning4e import *\n\nrandom.seed(\"aima-python\")\n\n\ndef "
},
{
"path": "tests/test_logic.py",
"chars": 15258,
"preview": "import pytest\n\nfrom logic import *\nfrom utils import expr_handle_infix_ops, count\n\nrandom.seed(\"aima-python\")\n\ndefinite_"
},
{
"path": "tests/test_logic4e.py",
"chars": 13406,
"preview": "import pytest\n\nfrom logic4e import *\nfrom utils4e import expr_handle_infix_ops, count\n\ndefinite_clauses_KB = PropDefinit"
},
{
"path": "tests/test_mdp.py",
"chars": 8327,
"preview": "import pytest\n\nfrom mdp import *\n\nrandom.seed(\"aima-python\")\n\nsequential_decision_environment_1 = GridMDP([[-0.1, -0.1, "
},
{
"path": "tests/test_mdp4e.py",
"chars": 8626,
"preview": "import pytest\n\nfrom mdp4e import *\n\nrandom.seed(\"aima-python\")\n\nsequential_decision_environment_1 = GridMDP([[-0.1, -0.1"
},
{
"path": "tests/test_nlp.py",
"chars": 9369,
"preview": "import random\n\nimport pytest\nimport nlp\n\nfrom nlp import loadPageHTML, stripRawHTML, findOutlinks, onlyWikipediaURLS\nfro"
},
{
"path": "tests/test_nlp4e.py",
"chars": 4257,
"preview": "import random\n\nimport pytest\nimport nlp\n\nfrom nlp4e import Rules, Lexicon, Grammar, ProbRules, ProbLexicon, ProbGrammar,"
},
{
"path": "tests/test_perception4e.py",
"chars": 3041,
"preview": "import random\n\nimport pytest\n\nfrom perception4e import *\nfrom PIL import Image\nimport numpy as np\nimport os\n\nrandom.seed"
},
{
"path": "tests/test_planning.py",
"chars": 33935,
"preview": "import random\n\nimport pytest\n\nfrom planning import *\nfrom search import astar_search\nfrom utils import expr\nfrom logic i"
},
{
"path": "tests/test_probabilistic_learning.py",
"chars": 1122,
"preview": "import random\n\nimport pytest\n\nfrom learning import DataSet\nfrom probabilistic_learning import *\n\nrandom.seed(\"aima-pytho"
},
{
"path": "tests/test_probability.py",
"chars": 16281,
"preview": "import pytest\n\nfrom probability import *\nfrom utils import rounder\n\nrandom.seed(\"aima-python\")\n\n\ndef tests():\n cpt = "
},
{
"path": "tests/test_probability4e.py",
"chars": 12355,
"preview": "import pytest\n\nfrom probability4e import *\n\nrandom.seed(\"aima-python\")\n\n\ndef tests():\n cpt = burglary.variable_node('"
},
{
"path": "tests/test_reinforcement_learning.py",
"chars": 2426,
"preview": "import pytest\n\nfrom reinforcement_learning import *\nfrom mdp import sequential_decision_environment\n\nrandom.seed(\"aima-p"
},
{
"path": "tests/test_reinforcement_learning4e.py",
"chars": 2435,
"preview": "import pytest\n\nfrom mdp4e import sequential_decision_environment\nfrom reinforcement_learning4e import *\n\nrandom.seed(\"ai"
},
{
"path": "tests/test_search.py",
"chars": 16228,
"preview": "import pytest\nfrom search import *\n\nrandom.seed(\"aima-python\")\n\nromania_problem = GraphProblem('Arad', 'Bucharest', roma"
},
{
"path": "tests/test_text.py",
"chars": 9387,
"preview": "import random\n\nimport numpy as np\nimport pytest\n\nfrom text import *\nfrom utils import open_data\n\nrandom.seed(\"aima-pytho"
},
{
"path": "tests/test_utils.py",
"chars": 9227,
"preview": "import pytest\nfrom utils import *\nimport random\n\nrandom.seed(\"aima-python\")\n\n\ndef test_sequence():\n assert sequence(1"
},
{
"path": "text.ipynb",
"chars": 36649,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# TEXT\\n\",\n \"\\n\",\n \"This note"
},
{
"path": "text.py",
"chars": 15207,
"preview": "\"\"\"\nStatistical Language Processing tools (Chapter 22)\n\nWe define Unigram and Ngram text models, use them to generate ra"
},
{
"path": "utils.py",
"chars": 21937,
"preview": "\"\"\"Provides some utilities widely used by other modules\"\"\"\n\nimport bisect\nimport collections\nimport collections.abc\nimpo"
},
{
"path": "utils4e.py",
"chars": 23044,
"preview": "\"\"\"Provides some utilities widely used by other modules\"\"\"\n\nimport bisect\nimport collections\nimport collections.abc\nimpo"
},
{
"path": "vacuum_world.ipynb",
"chars": 29877,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# THE VACUUM WORLD \\n\",\n \"\\n\","
},
{
"path": "viterbi_algorithm.ipynb",
"chars": 29109,
"preview": "{\n \"cells\": [\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"# Probabilistic Reasoning over Time"
}
]
About this extraction
This page contains the full source code of the aimacode/aima-python GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 129 files (6.7 MB), approximately 1.8M tokens, and a symbol index with 2621 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.