Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,5 @@ target/
lite/_output/
lite/.jupyterlite.doit.db
lite/aima-*.whl
lite/pypi/
lite/_screenshots/
55 changes: 55 additions & 0 deletions aima/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2039,6 +2039,61 @@ def __repr__(self):
self.states, str(self.found)[:4])


class RecordingProblem(InstrumentedProblem):
"""Delegates to a problem, like InstrumentedProblem, and also records the
order in which states are expanded and generated, so that a run of any
search function can be replayed step by step. The search function is called
unchanged, with this wrapper in place of the problem:
>>> problem = RecordingProblem(GraphProblem('Arad', 'Bucharest', romania_map))
>>> goal = astar_search(problem)
>>> [step['current'] for step in problem.steps()][:4]
[None, 'Arad', 'Sibiu', 'Fagaras']
"""

def __init__(self, problem):
super().__init__(problem)
self.events = []

def actions(self, state):
"""A search function asks for the actions of a state when it expands it."""
self.events.append(('expand', state))
return super().actions(state)

def result(self, state, action):
"""Delegate to the wrapped problem, recording the generated state."""
child = super().result(state, action)
self.events.append(('generate', child))
return child

def steps(self, goal=None):
"""Return the recorded run as a list of steps, one per expansion. Each step
is a dict with the state being expanded ('current'), the states expanded
so far ('explored') and the states generated but not yet expanded
('frontier'). The first step shows the initial state alone in the frontier;
if the goal node returned by the search is given, a last step adds its
'path' (a list of states) and its 'cost'. The frontier is a set of states,
which is exact for graph search; tree search may hold the same state in
several nodes."""
reached, explored = {self.problem.initial}, set()
steps = [dict(current=None, frontier=set(reached), explored=set())]
current = None
for kind, state in self.events:
if kind == 'expand':
if current is not None:
steps.append(dict(current=current, frontier=reached - explored,
explored=set(explored)))
current = state
explored.add(state)
else:
reached.add(state)
if current is not None:
steps.append(dict(current=current, frontier=reached - explored, explored=set(explored)))
if goal is not None:
steps.append(dict(current=goal.state, frontier=reached - explored - {goal.state},
explored=set(explored), path=goal.path_states(), cost=goal.path_cost))
return steps


def compare_searchers(problems, header,
searchers=[breadth_first_tree_search,
breadth_first_graph_search,
Expand Down
450 changes: 450 additions & 0 deletions aima/widgets.py

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions docs/utils.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,8 @@ Utilities & Notebook Helpers
:show-inheritance:



.. automodule:: aima.widgets
:members:
:undoc-members:
:show-inheritance:
23 changes: 20 additions & 3 deletions lite/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ packages.
The companion ships a notebook per Pyodide-compatible module:

- `content/agents.ipynb` — reflex vs. model-based agents in the vacuum world (`aima.agents`).
- `content/search.ipynb` — BFS / A* on the Romania map (`aima.search`).
- `content/search.ipynb` — BFS / A* on the Romania map, with step-through players for the search, the 8-puzzle and n-queens, and an 8-puzzle to solve by hand (`aima.search`, `aima.widgets`).
- `content/games.ipynb` — minimax / alpha-beta on Tic-Tac-Toe (`aima.games`).
- `content/csp.ipynb` — map colouring (AC-3 / backtracking) and N-queens (min-conflicts) (`aima.csp`).
- `content/logic.ipynb` — propositional model checking / DPLL and first-order forward chaining (`aima.logic`).
Expand All @@ -40,6 +40,20 @@ The companion ships a notebook per Pyodide-compatible module:

`content/Welcome.ipynb` shows the one-cell install pattern used by every notebook.

## Widgets

The interactive views in `aima/widgets.py` use only [ipywidgets](https://ipywidgets.readthedocs.io):
the pictures are SVG inside an `HTML` widget and the animation is timed by a `Play`
widget in the browser, so they need no other widget library and work in Jupyter,
JupyterLab and JupyterLite alike. `requirements-lite.txt` puts the ipywidgets
frontend in the site, and `build.sh` bundles the matching `ipywidgets`,
`jupyterlab_widgets` and `comm` wheels, so `piplite.install("ipywidgets")` works
offline once the site has loaded.

Of the other libraries tried in this build, ipycanvas and bqplot work,
`%matplotlib inline` gives static images, and ipympl (`%matplotlib widget`) fails
in the Pyodide kernel; none of them is needed for these views.

Most modules need only numpy; `aima.logic`/`aima.planning` need `networkx`,
`aima.csp`/`aima.planning` need `sortedcontainers` (both pure-Python and shipped
with Pyodide — preloaded for the kernel in `jupyter-lite.json`). `game_theory.ipynb`
Expand Down Expand Up @@ -78,10 +92,13 @@ real code cells:
```bash
pip install playwright nbformat
python -m playwright install chromium
cd lite && ./build.sh && python verify_browser.py
cd lite && ./build.sh && python verify_browser.py --lab search
```

It exits non-zero if any notebook errors. All 15 notebooks currently pass.
It exits non-zero if any notebook errors. With `--lab search` it also runs the
search notebook in the JupyterLite app itself, presses Play and Step on each
player, clicks the tiles of the 8-puzzle game, and saves screenshots of the
widgets in `lite/_screenshots`.

## Status / next steps

Expand Down
9 changes: 8 additions & 1 deletion lite/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,14 @@ OUTPUT_DIR="$(cd "$OUTPUT_DIR" && pwd)"
rm -f "$HERE"/aima-*.whl
python -m build --wheel --outdir "$HERE" "$ROOT"

# 2. Build the static JupyterLite site.
# 2. Bundle the ipywidgets wheels, the same versions as the widget labextension
# installed here by requirements-lite.txt, so that the notebooks with widgets
# work offline once the site has loaded (piplite indexes the wheels in pypi/).
rm -rf "$HERE/pypi"
python -m pip download --quiet --no-deps --only-binary=:all: --dest "$HERE/pypi" \
$(python -m pip list --format=freeze | grep -iE '^(ipywidgets|jupyterlab[-_]widgets|comm)==')

# 3. Build the static JupyterLite site.
cd "$HERE"
jupyter lite build --output-dir "$OUTPUT_DIR"

Expand Down
142 changes: 142 additions & 0 deletions lite/content/search.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,148 @@
"A* finds the optimal route Arad → Sibiu → Rimnicu → Pitesti → Bucharest\n",
"(cost 418), while breadth-first returns a shorter-in-hops but costlier path."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Watching the search\n",
"\n",
"The players below replay a run of the same search functions, one expansion per\n",
"step: press Play or Step, or drag the slider. Yellow cities are in the frontier,\n",
"blue ones are explored and the red one is being expanded; the last step draws the\n",
"path found and its cost."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"await piplite.install(\"ipywidgets\")\n",
"from aima.widgets import graph_search_player\n",
"\n",
"graph_search_player(astar_search, problem)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Breadth-first search ignores the road lengths: it reaches Bucharest in fewer\n",
"steps, by a longer road."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"graph_search_player(breadth_first_graph_search, problem)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Uniform-cost search expands the cities in order of their distance from Arad, so\n",
"it expands 12 cities before it finds the route that A* finds after 5."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"graph_search_player(uniform_cost_search, problem)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The players are built on `RecordingProblem`, which wraps a problem and records\n",
"what the search asks of it; the search function is unchanged and returns the same\n",
"node."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from aima.search import RecordingProblem\n",
"\n",
"recorder = RecordingProblem(problem)\n",
"goal = astar_search(recorder)\n",
"[step[\"current\"] for step in recorder.steps(goal)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The 8-puzzle\n",
"\n",
"A* with the misplaced-tiles heuristic (`EightPuzzle.h`) solves this puzzle; the\n",
"player shows the moves of the solution it finds."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from aima.search import EightPuzzle\n",
"from aima.widgets import eight_puzzle_player, EightPuzzleGame\n",
"\n",
"eight_puzzle_player(astar_search, EightPuzzle((1, 2, 0, 6, 8, 3, 5, 4, 7)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Your turn: click a tile next to the blank to slide it. When the puzzle is solved,\n",
"your number of moves is compared with the optimum that A* finds."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"EightPuzzleGame()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The n-queens problem\n",
"\n",
"`NQueensProblem` fills the columns from left to right and places a queen only\n",
"where no other queen attacks it. Depth-first search backtracks when a column has no\n",
"safe square; the highlighted column is the next one to fill."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from aima.search import NQueensProblem, depth_first_tree_search\n",
"from aima.widgets import n_queens_player\n",
"\n",
"n_queens_player(depth_first_tree_search, NQueensProblem(6))"
]
}
],
"metadata": {
Expand Down
3 changes: 3 additions & 0 deletions lite/requirements-lite.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@
jupyterlite-core==0.8.7
jupyterlite-pyodide-kernel==0.8.6
jupyterlite==0.8.7
# the ipywidgets frontend, built into the site (build.sh bundles the matching wheels)
ipywidgets==8.1.9
jupyterlab_widgets==3.0.17
jupyter-server
build
Loading
Loading