diff --git a/.gitignore b/.gitignore index f649448cd..c8d8fdd25 100644 --- a/.gitignore +++ b/.gitignore @@ -83,3 +83,5 @@ target/ lite/_output/ lite/.jupyterlite.doit.db lite/aima-*.whl +lite/pypi/ +lite/_screenshots/ diff --git a/aima/search.py b/aima/search.py index f379f6d77..f40d38e99 100644 --- a/aima/search.py +++ b/aima/search.py @@ -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, diff --git a/aima/widgets.py b/aima/widgets.py new file mode 100644 index 000000000..93c405584 --- /dev/null +++ b/aima/widgets.py @@ -0,0 +1,450 @@ +""" +Interactive views of the algorithms, built on ipywidgets alone. + +The views are drawn as SVG inside ipywidgets.HTML, and the animations are timed +by ipywidgets.Play in the browser, so they run in classic Jupyter, in JupyterLab +and in JupyterLite (Pyodide), with no server and no other widget library. + +A Player replays a list of frames, recorded beforehand; the search functions are +recorded with RecordingProblem (in aima.search), which wraps a problem and leaves +the functions themselves unchanged. The ready-made players are: + + graph_search_player a search on a graph with locations, e.g. the Romania map + eight_puzzle_player the solution path of a search on the 8-puzzle + n_queens_player a search on NQueensProblem, one board per expansion + +and EightPuzzleGame lets the user solve an 8-puzzle by clicking the tiles. +""" + +import itertools +import random +from html import escape + +import ipywidgets + +from aima.search import (EightPuzzle, Node, RecordingProblem, astar_search) + +# colors of the views (state of a node of the search, and the board squares) +COLORS = dict(unreached='#ffffff', frontier='#f6c453', explored='#a9c4e8', + current='#d9534f', path='#2a9d8f', edge='#b8b8b8', text='#222222', + light='#f0d9b5', dark='#b58863', tile='#e8eef7', attacked='#d9534f') + +_ids = itertools.count() + + +def svg_page(body, width, height, max_width): + """Wrap SVG elements in an scaled to the output width (up to max_width + pixels), on a white background so that it reads in dark themes too.""" + return (f'' + f'{body}') + + +# ______________________________________________________________________________ +# Step-through player + + +class Player(ipywidgets.VBox): + """Replay a list of frames with Play/Pause, Step, Reset, a slider over the + frames and a speed control. render(player, i) returns the HTML of frame + player.frames[i] (player.shown is the index on show before it, or None); the + default speed is one frame per second.""" + + def __init__(self, frames, render, speed=1.0): + self.frames = frames + self.render = render + last = max(len(frames) - 1, 0) + self.timer = ipywidgets.Play(min=0, max=last, interval=int(1000 / speed), + show_repeat=False, layout=ipywidgets.Layout(display='none')) + self.slider = ipywidgets.IntSlider(min=0, max=last, description='Step', + continuous_update=True, + layout=ipywidgets.Layout(width='360px')) + ipywidgets.jslink((self.timer, 'value'), (self.slider, 'value')) + self.play_button = ipywidgets.ToggleButton(description='Play', icon='play', + layout=ipywidgets.Layout(width='90px')) + ipywidgets.jslink((self.play_button, 'value'), (self.timer, 'playing')) + self.step_button = ipywidgets.Button(description='Step', icon='step-forward', + layout=ipywidgets.Layout(width='90px')) + self.reset_button = ipywidgets.Button(description='Reset', icon='undo', + layout=ipywidgets.Layout(width='90px')) + self.speed = ipywidgets.FloatSlider(value=speed, min=0.25, max=4, step=0.25, + description='Steps/s', readout_format='.2f', + layout=ipywidgets.Layout(width='280px')) + self.view = ipywidgets.HTML() + self.shown = None + self.slider.observe(lambda change: self.show(change['new']), 'value') + self.play_button.observe(self.on_play, 'value') + self.step_button.on_click(lambda button: self.step()) + self.reset_button.on_click(lambda button: self.reset()) + self.speed.observe(self.on_speed, 'value') + controls = ipywidgets.HBox([self.play_button, self.step_button, self.reset_button, + self.slider, self.speed, self.timer], + layout=ipywidgets.Layout(flex_flow='row wrap')) + super().__init__([controls, self.view]) + self.add_class('aima-player') + self.show(0) + + @property + def value(self): + """The index of the frame on show.""" + return self.slider.value + + def show(self, i): + """Draw frame i.""" + self.view.value = self.render(self, i) + self.shown = i + if i == len(self.frames) - 1: + self.play_button.value = False + + def on_speed(self, change): + """Set the time between frames from the speed, in frames per second.""" + self.timer.interval = int(1000 / change['new']) + + def on_play(self, change): + """Restart from the first frame when Play is pressed on the last one.""" + self.play_button.description = 'Pause' if change['new'] else 'Play' + self.play_button.icon = 'pause' if change['new'] else 'play' + if change['new'] and self.slider.value == self.slider.max: + self.slider.value = 0 + + def step(self): + """Pause and move one frame forward.""" + self.play_button.value = False + if self.slider.value < self.slider.max: + self.slider.value += 1 + + def reset(self): + """Pause and go back to the first frame.""" + self.play_button.value = False + self.slider.value = 0 + + +# ______________________________________________________________________________ +# Search on a graph with locations (the Romania map) + + +def graph_search_svg(graph, step, initial, goal): + """Draw a graph whose nodes have graph.locations, colored by a step of + RecordingProblem.steps(): frontier, explored, the node being expanded and, in + the last step, the path found. Return the SVG as a string.""" + xs = [x for x, y in graph.locations.values()] + ys = [y for x, y in graph.locations.values()] + left, top, scale, pad = min(xs), max(ys), 1.0, 40 + width, height = int(max(xs) - left) + 2 * pad + 60, int(top - min(ys)) + 2 * pad + + def at(node): + x, y = graph.locations[node] + return (x - left) * scale + pad, (top - y) * scale + pad + + path = step.get('path') or [] + on_path = set(zip(path, path[1:])) | set(zip(path[1:], path)) + body = [] + drawn = set() + for a in graph.nodes(): + for b, d in graph.get(a).items(): + if (b, a) in drawn: + continue + drawn.add((a, b)) + (x1, y1), (x2, y2) = at(a), at(b) + color, width_ = (COLORS['path'], 6) if (a, b) in on_path else (COLORS['edge'], 2) + body.append(f'') + body.append(f'{d}') + for node in graph.nodes(): + x, y = at(node) + if node == step['current']: + fill = COLORS['current'] + elif node in step['explored']: + fill = COLORS['explored'] + elif node in step['frontier']: + fill = COLORS['frontier'] + else: + fill = COLORS['unreached'] + ring, ring_width = (COLORS['path'], 3) if node in path else ('#555555', 1.5) + body.append(f'') + weight = 'bold' if node in (initial, goal) else 'normal' + body.append(f'{escape(str(node))}') + legend = [('frontier', 'frontier'), ('explored', 'explored'), ('current', 'expanding'), + ('unreached', 'not reached')] + for i, (key, label) in enumerate(legend): + x = pad + 110 * i + body.append(f'{label}') + return svg_page(''.join(body), width, height, 680) + + +def graph_search_caption(steps, i, goal): + """Describe step i of a recorded graph search in one or two lines of HTML.""" + step = steps[i] + if 'path' in step: + path = ' → '.join(escape(str(state)) for state in step['path']) + return (f'Goal reached after {len(step["explored"])} expansions: {path} ' + f'(cost {step["cost"]}).') + frontier = escape(', '.join(sorted(map(str, step['frontier']))) or 'empty') + if step['current'] is None: + return f'Step 0 of {len(steps) - 1}: the frontier holds the initial state {frontier}.' + text = (f'Step {i} of {len(steps) - 1}: expand {escape(str(step["current"]))}. ' + f'Frontier: {frontier}. Explored: {len(step["explored"])} states.') + if i == len(steps) - 1 and goal is None: + text += ' No solution.' + return text + + +def graph_search_player(search, problem, *args, speed=1.0, **kwargs): + """Run ``search(problem, *args, **kwargs)`` on a GraphProblem whose graph has + locations (e.g. romania_map) and return a Player that replays it, one + expansion per step, ending with the path found and its cost.""" + recorder = RecordingProblem(problem) + goal = search(recorder, *args, **kwargs) + steps = recorder.steps(goal) + + def render(player, i): + svg = graph_search_svg(problem.graph, steps[i], problem.initial, problem.goal) + return f'{svg}
{graph_search_caption(steps, i, goal)}
' + + return Player(steps, render, speed) + + +# ______________________________________________________________________________ +# 8-puzzle + + +def eight_puzzle_svg(state, previous=None, duration=0.4, size=3): + """Draw a sliding-tile board (0 is the blank). If the previous state is given + and differs by one move, the moved tile slides from its old square.""" + cell, gap = 70, 4 + side = size * cell + gap + key = f'aima-slide-{next(_ids)}' + moved, style = None, '' + if previous is not None and previous != state: + blank, old_blank = state.index(0), previous.index(0) + moved = old_blank # the moved tile now sits where the blank was + dx = (blank % size - old_blank % size) * cell + dy = (blank // size - old_blank // size) * cell + style = (f'') + body = [style, f''] + for i, tile in enumerate(state): + if tile == 0: + continue + x, y, w = (i % size) * cell + gap, (i // size) * cell + gap, cell - gap + body.append(f'' + f'{tile}') + return svg_page(''.join(body), side, side, side) + + +def eight_puzzle_player(search, problem, *args, speed=1.0, **kwargs): + """Run ``search(problem, *args, **kwargs)`` on an EightPuzzle and return a Player + that replays the solution found, one move per step, with the tiles sliding.""" + recorder = RecordingProblem(problem) + goal = search(recorder, *args, **kwargs) + states = goal.path_states() if goal else [problem.initial] + + def render(player, i): + # slide the tile only between consecutive moves, not on a jump of the slider + previous = None + if player.shown is not None and abs(player.shown - i) == 1: + previous = states[player.shown] + if goal is None: + caption = f'No solution found ({recorder.succs} nodes expanded).' + else: + caption = (f'Move {i} of {len(states) - 1}; the search expanded {recorder.succs} nodes ' + f'to find this solution.') + svg = eight_puzzle_svg(states[i], previous, duration=min(0.4, 0.6 / player.speed.value)) + return f'{svg}
{caption}
' + + return Player(states, render, speed) + + +def manhattan(node, goal=(1, 2, 3, 4, 5, 6, 7, 8, 0), size=3): + """Sum of the distances of the tiles from their goal squares (an admissible + heuristic for the sliding-tile puzzles).""" + state = node.state if isinstance(node, Node) else node + where = {tile: i for i, tile in enumerate(goal)} + return sum(abs(i // size - where[t] // size) + abs(i % size - where[t] % size) + for i, t in enumerate(state) if t != 0) + + +def scrambled_eight_puzzle(moves=20, goal=(1, 2, 3, 4, 5, 6, 7, 8, 0), seed=None): + """Return a state reached from the goal by random moves of the blank (so it is + always solvable), never undoing the previous move.""" + rng = random.Random(seed) + problem = EightPuzzle(goal, goal) + opposite = dict(UP='DOWN', DOWN='UP', LEFT='RIGHT', RIGHT='LEFT') + state, last = goal, None + for _ in range(moves): + action = rng.choice([a for a in problem.actions(state) if a != opposite.get(last)]) + state, last = problem.result(state, action), action + return state + + +def moves(n): + """'1 move', '2 moves', ...""" + return f'{n} move{"" if n == 1 else "s"}' + + +# the tiles that can move are outlined on hover; the style is scoped to the game +_GAME_STYLE = ( + '') + + +class EightPuzzleGame(ipywidgets.VBox): + """An 8-puzzle the user solves by clicking a tile next to the blank. Any other + click is refused with a message; when the puzzle is solved the number of + moves is compared with the optimum found by A* (Manhattan heuristic).""" + + def __init__(self, initial=None, scramble=16, seed=None): + self.goal = (1, 2, 3, 4, 5, 6, 7, 8, 0) + self.scramble, self.rng = scramble, random.Random(seed) + self.buttons = [ipywidgets.Button(layout=ipywidgets.Layout(width='80px', height='80px')) + for _ in range(9)] + for i, button in enumerate(self.buttons): + button.add_class('aima-tile') + button.on_click(lambda b, i=i: self.click(i)) + board = ipywidgets.GridBox(self.buttons, layout=ipywidgets.Layout( + grid_template_columns='repeat(3, 80px)', grid_gap='4px', width='252px', + padding='4px', border='1px solid #d0d0d0')) + self.message = ipywidgets.HTML() + new_button = ipywidgets.Button(description='New puzzle', icon='random', + layout=ipywidgets.Layout(width='124px')) + new_button.on_click(lambda b: self.new()) + restart_button = ipywidgets.Button(description='Restart', icon='undo', + layout=ipywidgets.Layout(width='124px')) + restart_button.on_click(lambda b: self.start(self.initial)) + super().__init__([ipywidgets.HTML(_GAME_STYLE), board, + ipywidgets.HBox([new_button, restart_button]), self.message]) + self.add_class('aima-eight-puzzle-game') + self.start(initial or scrambled_eight_puzzle(scramble, self.goal, self.rng.random())) + + def new(self): + """Start a new random puzzle.""" + self.start(scrambled_eight_puzzle(self.scramble, self.goal, self.rng.random())) + + def start(self, state): + """Start (or restart) the game from the given state.""" + self.initial, self.state, self.moves, self.solved = tuple(state), tuple(state), 0, False + self.draw('click a tile next to the blank') + + def movable(self, i): + """Is the tile in square i next to the blank?""" + blank = self.state.index(0) + return abs(i // 3 - blank // 3) + abs(i % 3 - blank % 3) == 1 + + def draw(self, text): + """Show the current state and a one-line status.""" + for i, (button, tile) in enumerate(zip(self.buttons, self.state)): + button.description = str(tile) if tile else '\u00a0' # a blank label may not refresh + button.style.button_color = '#fafafa' if tile == 0 else COLORS['tile'] + for name, on in (('aima-blank', tile == 0), + ('aima-movable', tile != 0 and not self.solved and self.movable(i))): + if on: + button.add_class(name) + else: + button.remove_class(name) + self.message.value = f'Moves: {self.moves} · {text}' + + def click(self, i): + """Slide tile i into the blank if they are adjacent, else refuse.""" + if self.solved: + self.draw('solved, press New puzzle to play again') + return + if self.state[i] == 0: + self.draw('that is the blank, click a tile next to it') + return + if not self.movable(i): + self.draw(f'tile {self.state[i]} is not next to the blank, so it cannot move') + return + blank = self.state.index(0) + state = list(self.state) + state[blank], state[i] = state[i], 0 + self.state, self.moves = tuple(state), self.moves + 1 + if self.state == self.goal: + self.solved = True + optimum = len(astar_search(EightPuzzle(self.initial, self.goal), + lambda n: manhattan(n, self.goal)).solution()) + verdict = 'optimal' + if self.moves > optimum: + verdict = f'{moves(self.moves - optimum)} longer than the optimum' + self.draw(f'solved, A* needs {moves(optimum)}, so yours is {verdict}') + else: + self.draw('click a tile next to the blank') + + +# ______________________________________________________________________________ +# N-queens + + +def n_queens_svg(state, n=None, column=None): + """Draw an n-queens board. The state is a tuple whose c-th entry is the row of + the queen in column c, or -1 if the column is empty (as in NQueensProblem), or + a dict {column: row} (as a CSP assignment). Queens attacked by another queen + are drawn in red; column, if given, is highlighted.""" + if isinstance(state, dict): + n = n or len(state) + queens = dict(state) + else: + n = n or len(state) + queens = {c: r for c, r in enumerate(state) if r != -1} + cell = 40 + body = [] + for r in range(n): + for c in range(n): + square = COLORS['light'] if (r + c) % 2 == 0 else COLORS['dark'] + body.append(f'') + if column is not None: + body.append(f'') + for c, r in queens.items(): + attacked = any(r == r2 or abs(r - r2) == abs(c - c2) + for c2, r2 in queens.items() if c2 != c) + x, y = c * cell + cell / 2, r * cell + cell / 2 + fill = COLORS['attacked'] if attacked else '#333333' + body.append(f'' + f'Q') + return svg_page(''.join(body), n * cell, n * cell, max(n * cell, 240)) + + +def n_queens_player(search, problem, *args, speed=1.0, **kwargs): + """Run ``search(problem, *args, **kwargs)`` on an NQueensProblem and return a + Player that shows the board of each expanded state, then the solution.""" + recorder = RecordingProblem(problem) + goal = search(recorder, *args, **kwargs) + steps = recorder.steps(goal) + + def render(player, i): + state = steps[i]['current'] + if state is None: + state = problem.initial + caption = f'Step 0 of {len(steps) - 1}: the search starts from the empty board.' + elif 'path' in steps[i]: + caption = f'Solution found after {len(steps[i]["explored"])} expansions.' + else: + placed = sum(r != -1 for r in state) + caption = f'Step {i} of {len(steps) - 1}: expand a board with {placed} queens.' + if goal is None and i == len(steps) - 1: + caption += ' No solution.' + column = None if -1 not in state else state.index(-1) + return n_queens_svg(state, problem.N, column) + f'
{caption}
' + + return Player(steps, render, speed) diff --git a/docs/utils.rst b/docs/utils.rst index 7a4974639..e0a7c5c64 100644 --- a/docs/utils.rst +++ b/docs/utils.rst @@ -17,3 +17,8 @@ Utilities & Notebook Helpers :show-inheritance: + +.. automodule:: aima.widgets + :members: + :undoc-members: + :show-inheritance: diff --git a/lite/README.md b/lite/README.md index 4186f3319..d8ef91bff 100644 --- a/lite/README.md +++ b/lite/README.md @@ -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`). @@ -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` @@ -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 diff --git a/lite/build.sh b/lite/build.sh index 092c33b9f..434819d6c 100755 --- a/lite/build.sh +++ b/lite/build.sh @@ -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" diff --git a/lite/content/search.ipynb b/lite/content/search.ipynb index 80c5d4f21..f6d453118 100644 --- a/lite/content/search.ipynb +++ b/lite/content/search.ipynb @@ -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": { diff --git a/lite/requirements-lite.txt b/lite/requirements-lite.txt index a68f4b9b7..3cf3f87b5 100644 --- a/lite/requirements-lite.txt +++ b/lite/requirements-lite.txt @@ -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 diff --git a/lite/verify_browser.py b/lite/verify_browser.py index 31b6c4921..0550f2cde 100644 --- a/lite/verify_browser.py +++ b/lite/verify_browser.py @@ -10,13 +10,20 @@ (the `piplite` install cell included, via a micropip-backed shim). `ipython` is loaded to mirror the JupyterLite kernel, which always provides it. +With --lab NAME [NAME ...] it also opens those notebooks in the JupyterLite +app itself, runs all their cells in the real kernel, checks that no cell fails +and that every widget renders, presses Play and Step on the step-through players +and clicks the tiles of the 8-puzzle game (see aima/widgets.py), and saves a +screenshot of each widget in lite/_screenshots. + Setup (one-off): pip install playwright nbformat python -m playwright install chromium Usage: - cd lite && ./build.sh && python verify_browser.py + cd lite && ./build.sh && python verify_browser.py [--lab search] """ +import argparse import asyncio import functools import glob @@ -31,6 +38,7 @@ HERE = pathlib.Path(__file__).resolve().parent SITE = HERE / "_output" CONTENT = HERE / "content" +SHOTS = HERE / "_screenshots" PORT = 8765 PYODIDE = "https://cdn.jsdelivr.net/pyodide/v0.27.2/full/pyodide.js" @@ -97,13 +105,74 @@ async def run_cell(page, code): }""", code) +async def check_lab(browser, name): + """Run a notebook in the JupyterLite app, exercise its widgets and save + screenshots of them. Return a list of problems (empty if all went well).""" + problems = [] + page = await browser.new_page(viewport={"width": 1280, "height": 1000}) + await page.goto(f"http://127.0.0.1:{PORT}/lab/index.html?path={name}.ipynb") + await page.wait_for_selector(".jp-Notebook .jp-CodeCell", timeout=120000) + await page.wait_for_timeout(3000) + await page.locator(".lm-MenuBar-itemLabel", has_text="Run").first.click() + await page.locator(".lm-Menu-itemLabel", has_text="Run All Cells").first.click() + # wait until every code cell has an execution count, i.e. "[n]:" and not "[*]:" + await page.wait_for_function( + """() => { const p = [...document.querySelectorAll('.jp-CodeCell .jp-InputArea-prompt')]; + return p.length > 0 && p.every(e => /\\[\\d+\\]/.test(e.textContent)); }""", + timeout=600000, polling=1000) + await page.wait_for_timeout(3000) + errors = await page.evaluate( + """() => [...document.querySelectorAll('.jp-OutputArea-output')].map(e => e.innerText) + .filter(t => /Traceback|Error displaying widget|\\w+Error:/.test(t))""") + problems += [f"cell output: {e.strip()[-300:]}" for e in errors] + + SHOTS.mkdir(exist_ok=True) + players = page.locator(".aima-player") + for i in range(await players.count()): + player = players.nth(i) + await player.scroll_into_view_if_needed() + await player.get_by_role("button", name="Step").click() + await page.wait_for_timeout(1500) + stepped = int(await player.locator(".widget-readout").first.inner_text()) + await player.get_by_role("button", name="Play").click() + await page.wait_for_timeout(3500) # about 3 steps at the default 1 step per second + played = int(await player.locator(".widget-readout").first.inner_text()) + if stepped != 1 or played < 3: + problems.append(f"player {i}: Step went to {stepped}, Play reached {played}") + await player.screenshot(path=str(SHOTS / f"{name}-player-{i}.png")) + games = page.locator(".aima-eight-puzzle-game") + for i in range(await games.count()): + game = games.nth(i) + await game.scroll_into_view_if_needed() + tiles = game.locator(".widget-gridbox button") + labels = [(await tiles.nth(j).inner_text()).strip() for j in range(9)] + blank = labels.index("") + far = next(j for j in range(9) if abs(j // 3 - blank // 3) + abs(j % 3 - blank % 3) > 1) + near = next(j for j in range(9) if abs(j // 3 - blank // 3) + abs(j % 3 - blank % 3) == 1) + message = game.locator(".widget-html").last + await tiles.nth(far).click() + await page.wait_for_timeout(1500) + refused = await message.inner_text() + await tiles.nth(near).click() + await page.wait_for_timeout(1500) + moved = await message.inner_text() + after = [(await tiles.nth(j).inner_text()).strip() for j in range(9)] + if ("cannot move" not in refused or not moved.startswith("Moves: 1") + or after[near] != "" or after[blank] != labels[near]): + problems.append(f"8-puzzle game {i}: {refused!r}, then {moved!r} with tiles {after}") + await game.screenshot(path=str(SHOTS / f"{name}-game-{i}.png")) + await page.screenshot(path=str(SHOTS / f"{name}-page.png"), full_page=True) + await page.close() + return problems + + def notebook_order(): names = [p.stem for p in CONTENT.glob("*.ipynb")] ordered = [n for n in PREFERRED if n in names] return ordered + sorted(n for n in names if n not in PREFERRED) -async def main(): +async def main(lab=()): if not SITE.exists(): raise SystemExit("lite/_output not found — run ./build.sh first") wheels = glob.glob(str(SITE / "pypi" / "aima-*.whl")) @@ -144,12 +213,22 @@ async def main(): print(f" {'PASS' if ok else 'FAIL'} {name}") if not ok: print("\n".join(" " + l for l in out.strip().splitlines()[-8:])) + + for name in lab: + problems = await check_lab(browser, name) + results[f"{name} (JupyterLite)"] = not problems + print(f" {'PASS' if not problems else 'FAIL'} {name} in the JupyterLite app") + for problem in problems: + print(" " + problem) await browser.close() passed = sum(results.values()) - print(f"\n{passed}/{len(results)} notebooks ran successfully in a real browser") + print(f"\n{passed}/{len(results)} notebook runs succeeded in a real browser") raise SystemExit(0 if passed == len(results) else 1) if __name__ == "__main__": - asyncio.run(main()) + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--lab", nargs="+", default=[], metavar="NAME", + help="also run these notebooks in the JupyterLite app and check their widgets") + asyncio.run(main(parser.parse_args().lab)) diff --git a/tests/test_search.py b/tests/test_search.py index 4139873f4..96bdda315 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -536,5 +536,29 @@ def test_node_path_states(): assert len(node.solution()) == len(states) - 1 # actions are the path's edges +def test_recording_problem(): + # the wrapper records the run without changing what the search returns + for search in (breadth_first_graph_search, uniform_cost_search, astar_search, + depth_first_graph_search): + recorder = RecordingProblem(GraphProblem('Arad', 'Bucharest', romania_map)) + goal = search(recorder) + plain = search(GraphProblem('Arad', 'Bucharest', romania_map)) + assert goal.path_states() == plain.path_states() + steps = recorder.steps(goal) + assert steps[0] == dict(current=None, frontier={'Arad'}, explored=set()) + assert steps[1]['current'] == 'Arad' and steps[1]['frontier'] == {'Sibiu', 'Timisoara', 'Zerind'} + assert steps[-1]['path'] == plain.path_states() and steps[-1]['cost'] == plain.path_cost + assert len(steps) == recorder.succs + 2 # initial step + one per expansion + goal step + for step in steps[1:-1]: + assert step['current'] in step['explored'] + assert not step['frontier'] & step['explored'] + recorder = RecordingProblem(GraphProblem('Arad', 'Bucharest', romania_map)) + astar_search(recorder) + assert [step['current'] for step in recorder.steps()] == [None, 'Arad', 'Sibiu', 'Fagaras', 'Rimnicu', + 'Pitesti'] + recorder = RecordingProblem(NQueensProblem(4)) + assert depth_first_tree_search(recorder).state == depth_first_tree_search(NQueensProblem(4)).state + + if __name__ == '__main__': pytest.main() diff --git a/tests/test_widgets.py b/tests/test_widgets.py new file mode 100644 index 000000000..2482af3c8 --- /dev/null +++ b/tests/test_widgets.py @@ -0,0 +1,59 @@ +import pytest + +from aima.search import * +from aima.widgets import * + + +def test_graph_search_player(): + player = graph_search_player(astar_search, GraphProblem('Arad', 'Bucharest', romania_map)) + assert player.value == 0 and 'Step 0 of' in player.view.value + player.step() + assert player.value == 1 and 'expand Arad' in player.view.value + player.slider.value = player.slider.max + assert 'Goal reached' in player.view.value and '(cost 418)' in player.view.value + player.reset() + assert player.value == 0 and not player.play_button.value + player.speed.value = 2 + assert player.timer.interval == 500 + + +def test_eight_puzzle_player(): + player = eight_puzzle_player(astar_search, EightPuzzle((1, 2, 3, 4, 0, 6, 7, 5, 8))) + assert player.frames == [(1, 2, 3, 4, 0, 6, 7, 5, 8), (1, 2, 3, 4, 5, 6, 7, 0, 8), + (1, 2, 3, 4, 5, 6, 7, 8, 0)] + assert '@keyframes' not in player.view.value + player.step() # one move: the tile slides + assert '@keyframes' in player.view.value + player.slider.value = 0 + player.slider.value = 2 # a jump: no slide + assert '@keyframes' not in player.view.value + + +def test_n_queens_player(): + player = n_queens_player(depth_first_tree_search, NQueensProblem(4)) + player.slider.value = player.slider.max + assert 'Solution found' in player.view.value + assert n_queens_svg((1, 3, 0, 2)).count('#d9534f') == 0 # a solution: no queen attacked + assert n_queens_svg({0: 0, 1: 1}).count('#d9534f') == 2 # same diagonal + + +def test_eight_puzzle_game(): + assert scrambled_eight_puzzle(30, seed=1) == scrambled_eight_puzzle(30, seed=1) + assert EightPuzzle(scrambled_eight_puzzle(30, seed=2)).check_solvability(scrambled_eight_puzzle(30, seed=2)) + game = EightPuzzleGame(initial=(1, 2, 3, 4, 5, 6, 0, 7, 8)) + assert 'aima-movable' in game.buttons[7]._dom_classes and 'aima-movable' not in game.buttons[0]._dom_classes + game.click(0) + assert game.moves == 0 and 'cannot move' in game.message.value + game.click(7) + game.click(8) + assert game.solved and game.moves == 2 + assert 'Moves: 2' in game.message.value and 'yours is optimal' in game.message.value + game.start((1, 2, 3, 4, 5, 6, 7, 0, 8)) + game.click(6) # a legal but useless move, then back and forward + game.click(7) + game.click(8) + assert game.solved and '2 moves longer than the optimum' in game.message.value + + +if __name__ == '__main__': + pytest.main()