Utilities & Notebook Helpers

Provides some utilities widely used by other modules

sequence(iterable)[source]

Converts iterable to sequence, if it is not already one.

remove_all(item, seq)[source]

Return a copy of seq (or string) with all occurrences of item removed.

unique(seq)[source]

Remove duplicate elements from seq. Assumes hashable elements.

count(seq)[source]

Count the number of items in sequence that are interpreted as true.

multimap(items)[source]

Given (key, val) pairs, return {key: [val, ….], …}.

multimap_items(mmap)[source]

Yield all (key, val) pairs stored in the multimap.

product(numbers)[source]

Return the product of the numbers, e.g. product([2, 3, 10]) == 60

first(iterable, default=None)[source]

Return the first element of an iterable; or default.

is_in(elt, seq)[source]

Similar to (elt in seq), but compares with ‘is’, not ‘==’.

mode(data)[source]

Return the most common data item. If there are ties, return any one of them.

power_set([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)[source]
extend(s, var, val)[source]

Copy dict s and extend it by setting var to val; return copy.

flatten(seqs)[source]

Flatten a sequence of sequences into a single flat list.

identity(x)
argmin_random_tie(seq, key=<function <lambda>>)[source]

Return a minimum element of seq; break ties at random.

argmax_random_tie(seq, key=<function <lambda>>)[source]

Return an element with highest fn(seq[i]) score; break ties at random.

shuffled(iterable)[source]

Randomly shuffle a copy of iterable.

histogram(values, mode=0, bin_function=None)[source]

Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first.

dot_product(x, y)[source]

Return the sum of the element-wise product of vectors x and y.

element_wise_product(x, y)[source]

Return vector as an element-wise product of vectors x and y.

matrix_multiplication(x, *y)[source]

Return a matrix as a matrix-multiplication of x and arbitrary number of matrices *y.

vector_add(a, b)[source]

Component-wise addition of two vectors.

scalar_vector_product(x, y)[source]

Return vector as a product of a scalar and a vector

probability(p: float) bool[source]

Return true with probability p.

weighted_sample_with_replacement(n, seq, weights)[source]

Pick n samples from seq at random, with replacement, with the probability of each element in proportion to its corresponding weight.

weighted_sampler(seq, weights)[source]

Return a random-sample function that picks from seq weighted by weights.

weighted_choice(choices)[source]

A weighted version of random.choice

rounder(numbers, d=4)[source]

Round a single number, or sequence of numbers, to d decimal places.

num_or_str(x: str) int | float | str[source]

The argument is a string; convert to a number if possible, or strip it.

euclidean_distance(x, y) float[source]

Return the Euclidean (L2) distance between vectors x and y.

manhattan_distance(x, y) float[source]

Return the Manhattan (L1) distance between vectors x and y.

hamming_distance(x, y) int[source]

Return the number of positions at which vectors x and y differ.

cross_entropy_loss(x, y) float[source]

Return the mean binary cross-entropy loss between targets x and predictions y.

mean_squared_error_loss(x, y) float[source]

Return the mean squared error loss between vectors x and y.

rms_error(x, y) float[source]

Return the root-mean-square error between vectors x and y.

ms_error(x, y) float[source]

Return the mean of the squared differences between vectors x and y.

mean_error(x, y) float[source]

Return the mean of the absolute differences between vectors x and y.

mean_boolean_error(x, y) float[source]

Return the fraction of positions at which vectors x and y differ.

normalize(dist)[source]

Multiply each number by a constant such that the sum is 1.0

random_weights(min_value: float, max_value: float, num_weights: int) list[source]

Return a list of num_weights random floats drawn uniformly from [min_value, max_value].

sigmoid(x)[source]

Return activation value of x with sigmoid function.

sigmoid_derivative(value)[source]

Return the derivative of the sigmoid, given its already-computed output value.

elu(x: float, alpha: float = 0.01) float[source]

Return the Exponential Linear Unit activation of x.

elu_derivative(value: float, alpha: float = 0.01) float[source]

Return the derivative of the ELU activation, given its output value.

tanh(x)[source]

Return the hyperbolic tangent activation of x.

tanh_derivative(value)[source]

Return the derivative of tanh, given its already-computed output value.

leaky_relu(x: float, alpha: float = 0.01) float[source]

Return the Leaky ReLU activation of x (slope alpha for negative inputs).

leaky_relu_derivative(value: float, alpha: float = 0.01) float[source]

Return the derivative of the Leaky ReLU activation, given its output value.

relu(x: float) float[source]

Return the Rectified Linear Unit activation of x, i.e. max(0, x).

relu_derivative(value: float) int[source]

Return the derivative of the ReLU activation, given its output value.

step(x: float) int[source]

Return activation value of x with sign function

gaussian(mean: float, st_dev: float, x: float) float[source]

Given the mean and standard deviation of a distribution, it returns the probability of x.

linear_kernel(x, y=None)[source]

Return the linear kernel (dot product) between x and y; defaults y to x.

polynomial_kernel(x, y=None, degree=2.0)[source]

Return the polynomial kernel (1 + x.y)**degree between x and y; defaults y to x.

rbf_kernel(x, y=None, gamma=None)[source]

Radial-basis function kernel (aka squared-exponential kernel).

turn_heading(heading, inc, headings=[(1, 0), (0, 1), (-1, 0), (0, -1)])[source]

Return the heading reached by turning inc steps around the list of headings.

turn_right(heading)[source]

Return the heading obtained by turning right (clockwise) from heading.

turn_left(heading)[source]

Return the heading obtained by turning left (counter-clockwise) from heading.

distance(a, b)[source]

The distance between two (x, y) points.

distance_squared(a, b)[source]

The square of the distance between two (x, y) points.

class injection(**kwds)[source]

Bases: object

Dependency injection of temporary values for global functions/classes/etc. E.g., with injection(DataBase=MockDataBase): …

memoize(fn, slot=None, maxsize=32)[source]

Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, use lru_cache for caching the values.

name(obj)[source]

Try to find some reasonable name for the object.

isnumber(x)[source]

Is x a number?

issequence(x)[source]

Is x a sequence?

print_table(table, header=None, sep='   ', numfmt='{}')[source]

Print a list of lists as a table, so that columns line up nicely. header, if specified, will be printed as the first row. numfmt is the format for all numbers; you might want e.g. ‘{:.2f}’. (If you want different formats in different columns, don’t use print_table.) sep is the separator between columns.

open_data(name, mode='r')[source]

Open and return the file named name from the aima-data directory.

failure_test(algorithm, tests)[source]

Grades the given algorithm based on how many tests it passes. Most algorithms have arbitrary output on correct execution, which is difficult to check for correctness. On the other hand, a lot of algorithms output something particular on fail (for example, False, or None). tests is a list with each element in the form: (values, failure_output).

class Expr(op, *args)[source]

Bases: object

A mathematical expression with an operator and 0 or more arguments. op is a str like ‘+’ or ‘sin’; args are Expressions. Expr(‘x’) or Symbol(‘x’) creates a symbol (a nullary Expr). Expr(‘-’, x) creates a unary; Expr(‘+’, x, 1) creates a binary.

Symbol(name)[source]

A Symbol is just an Expr with no args.

symbols(names)[source]

Return a tuple of Symbols; names is a comma/whitespace delimited str.

subexpressions(x)[source]

Yield the subexpressions of an Expression (including x itself).

arity(expression)[source]

The number of sub-expressions in this expression.

class PartialExpr(op, lhs)[source]

Bases: object

Given ‘P |’==>’| Q, first form PartialExpr(‘==>’, P), then combine with Q.

expr(x)[source]

Shortcut to create an Expression. x is a str in which: - identifiers are automatically defined as Symbols. - ==> is treated as an infix |’==>’|, as are <== and <=>. If x is already an Expression, it is returned unchanged.

expr_handle_infix_ops(x)[source]

Given a str, return a new str with ==> replaced by |’==>’|, etc.

class defaultkeydict[source]

Bases: defaultdict

Like defaultdict, but the default_factory is a function of the key.

class hashabledict[source]

Bases: dict

Allows hashing by representing a dictionary as tuple of key:value pairs. May cause problems as the hash value may change during runtime.

class PriorityQueue(order='min', f=<function PriorityQueue.<lambda>>)[source]

Bases: object

A Queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is ‘min’, the item with minimum f(x) is returned first; if order is ‘max’, then it is the item with maximum f(x). Also supports dict-like lookup.

append(item)[source]

Insert item at its correct position.

extend(items)[source]

Insert each item in items at its correct position.

pop()[source]

Pop and return the item (with min or max f(x) value) depending on the order.

class Bool[source]

Bases: int

Just like bool, except values display as ‘T’ and ‘F’ instead of ‘True’ and ‘False’.

gaussian_kernel(size=3)[source]

Return a length-size 1D Gaussian kernel centred at the middle (fixed st_dev 0.1).

gaussian_kernel_1D(size=3, sigma=0.5)[source]

Return a length-size 1D Gaussian kernel centred at the middle with st_dev sigma.

gaussian_kernel_2D(size=3, sigma=0.5)[source]

Return a size x size 2D Gaussian kernel with st_dev sigma, normalized to sum to 1.

conv1D(x, k)[source]

1D convolution. x: input vector; K: kernel vector.

map_vector(f, x)[source]

Apply function f to iterable x.

class MCT_Node(parent=None, state=None, U=0, N=0)[source]

Bases: object

Node in the Monte Carlo search tree, keeps track of the children states.

ucb(n, C=1.4)[source]

Return the UCB1 score of node n (exploitation plus C-weighted exploration term).

Unvisited nodes (n.N == 0) score infinity so they are selected first; used to guide selection in Monte Carlo tree search.

pseudocode(algorithm)[source]

Print the pseudocode for the given algorithm.

psource(*functions)[source]

Print the source code for the given function(s).

show_iris(i=0, j=1, k=2)[source]

Plots the iris dataset in a 3D plot. The three axes are given by i, j and k, which correspond to three of the four iris features.

load_MNIST(path='aima-data/MNIST/Digits', fashion=False)[source]

Load the MNIST (or Fashion-MNIST when fashion is True) dataset from its IDX files under path. Returns (train_img, train_lbl, test_img, test_lbl) as numpy arrays, with images flattened to one row per sample.

show_MNIST(labels, images, samples=8, fashion=False)[source]

Display a grid of samples random example images for each class of the (Fashion-)MNIST dataset.

show_ave_MNIST(labels, images, fashion=False)[source]

Display the average image of every class in the (Fashion-)MNIST dataset and print how many images each class contains.

make_plot_grid_step_function(columns, rows, U_over_time)[source]

ipywidgets interactive function supports single parameter as input. This function creates and return such a function by taking as input other parameters.

make_visualize(slider)[source]

Takes an input a sliderand returns callback function for timer and animation.

class Canvas(varname, width=800, height=600, cid=None)[source]

Bases: object

Inherit from this class to manage the HTML canvas element in jupyter notebooks. To create an object of this class any_name_xyz = Canvas(“any_name_xyz”) The first argument given must be the name of the object being created. IPython must be able to reference the variable name that is being passed.

mouse_click(x, y)[source]

Override this method to handle mouse click at position (x, y)

mouse_move(x, y)[source]

Override this method to handle mouse move at position (x, y)

execute(exec_str)[source]

Stores the command to be executed to a list which is used later during update()

fill(r, g, b)[source]

Changes the fill color to a color in rgb format

stroke(r, g, b)[source]

Changes the colors of line/strokes to rgb

strokeWidth(w)[source]

Changes the width of lines/strokes to ‘w’ pixels

rect(x, y, w, h)[source]

Draw a rectangle with ‘w’ width, ‘h’ height and (x, y) as the top-left corner

rect_n(xn, yn, wn, hn)[source]

Similar to rect(), but the dimensions are normalized to fall between 0 and 1

line(x1, y1, x2, y2)[source]

Draw a line from (x1, y1) to (x2, y2)

line_n(x1n, y1n, x2n, y2n)[source]

Similar to line(), but the dimensions are normalized to fall between 0 and 1

arc(x, y, r, start, stop)[source]

Draw an arc with (x, y) as centre, ‘r’ as radius from angles ‘start’ to ‘stop’

arc_n(xn, yn, rn, start, stop)[source]

Similar to arc(), but the dimensions are normalized to fall between 0 and 1 The normalizing factor for radius is selected between width and height by seeing which is smaller.

clear()[source]

Clear the HTML canvas

font(font)[source]

Changes the font of text

text(txt, x, y, fill=True)[source]

Display a text at (x, y)

text_n(txt, xn, yn, fill=True)[source]

Similar to text(), but with normalized coordinates

alert(message)[source]

Immediately display an alert

update()[source]

Execute the JS code to execute the commands queued by execute()

display_html(html_string)[source]

Render the given HTML string in the Jupyter notebook output.

class Canvas_TicTacToe(varname, player_1='human', player_2='random', width=300, height=350, cid=None)[source]

Bases: Canvas

Play a 3x3 TicTacToe game on HTML canvas

mouse_click(x, y)[source]

Handle a click at pixel (x, y): make the move for the current human or AI player, or restart the game when it is over, then redraw the board.

draw_board()[source]

Redraw the board: grid lines, the current X/O marks, and the game status (whose turn it is, the winning line, or the restart button).

draw_x(position)[source]

Draw an ‘X’ mark in the cell at the given (column, row) board position.

draw_o(position)[source]

Draw an ‘O’ mark in the cell at the given (column, row) board position.

class Canvas_min_max(varname, util_list, width=800, height=600, cid=None)[source]

Bases: Canvas

MinMax for Fig52Extended on HTML canvas

min_max(node)[source]

Run minimax from the given node, recording the sequence of canvas changes (visited nodes, explored utilities, thick edges) for step-by-step animation. Returns the node’s minimax value.

stack_manager_gen()[source]

Generator that replays the recorded change list, updating the node stack, explored set and thick lines, and yielding once per animation step.

mouse_click(x, y)[source]

Advance the minimax animation by one step on each click, then redraw the graph.

draw_graph()[source]

Draw the game tree: the nodes (highlighting those on the stack and showing the utilities of explored nodes) together with the edges connecting them.

class Canvas_alpha_beta(varname, util_list, width=800, height=600, cid=None)[source]

Bases: Canvas

Alpha-beta pruning for Fig52Extended on HTML canvas

Run alpha-beta pruning from the given node, recording the sequence of canvas changes (visited nodes, alpha/beta bounds, pruned nodes, thick edges) for step-by-step animation. Returns the node’s value.

stack_manager_gen()[source]

Generator that replays the recorded change list, updating the node stack, alpha/beta bounds, explored and pruned sets and thick lines, yielding once per animation step.

mouse_click(x, y)[source]

Advance the alpha-beta animation by one step on each click, then redraw the graph.

draw_graph()[source]

Draw the game tree with nodes (highlighting those on the stack, explored and pruned) and edges, and display the alpha/beta bounds of nodes on the stack.

class Canvas_fol_bc_ask(varname, kb, query, width=800, height=600, cid=None)[source]

Bases: Canvas

fol_bc_ask() on HTML canvas

fol_bc_ask()[source]

Run first-order backward chaining for the stored query against the knowledge base, yielding proof trees together with their substitutions.

make_table(graph)[source]

Lay out the proof tree as a table of node positions and edges (stored on the instance) ready for rendering on the canvas.

mouse_click(x, y)[source]

Select the proof-tree node under the click position and redraw, showing its text.

draw_table()[source]

Draw the proof-tree nodes and edges, plus a text area showing the content of the currently selected node.

show_map(graph_data, node_colors=None)[source]

Draw a networkx graph of the given map data with coloured nodes, edge weight labels and a legend describing the search-state colours.

final_path_colors(initial_node_colors, problem, solution)[source]

Return a node_colors dict of the final path provided the problem and solution.

display_visual(graph_data, user_input, algorithm=None, problem=None)[source]

Build interactive ipywidgets controls to animate a search algorithm on the map. When user_input is True, also let the user choose the algorithm and the start and goal cities; otherwise animate the supplied algorithm.

plot_NQueens(solution)[source]

Draw an N-Queens chessboard with queen images for the given solution, which may be a dict (from NQueensCSP) or a list (from NQueensProblem).

heatmap(grid, cmap='binary', interpolation='nearest')[source]

Display the given 2D grid as a heatmap.

gaussian_kernel(l=5, sig=1.0)[source]

Return an l x l Gaussian kernel with standard deviation sig.

plot_pomdp_utility(utility)[source]

Plot the piecewise-linear utility functions of a POMDP’s actions and mark the belief thresholds between the optimal actions.

plot_model_boundary(dataset, attr1, attr2, model=None)[source]

Plot the decision boundary of a classifier over two attributes of a dataset. Builds a mesh over the attr1/attr2 plane, colours each cell by the model’s prediction, and overlays the training examples.

grid_search_steps(problem, strategy='astar')[source]

Run a search on a GridProblem, recording how it explores.

Returns (explored, path): explored is the list of cells in the order they are expanded (popped from the frontier), and path is the list of cells from start to goal (None if the goal is unreachable). strategy selects the evaluation function – 'astar' (g + h), 'ucs' (g), 'bfs' (depth) or 'greedy' (h) – which is what makes the different exploration patterns.

Visualise a grid search: obstacles, the cells expanded (shaded by when they were expanded), the solution path, and the start/goal. explored and path are as returned by grid_search_steps(). Returns the matplotlib Axes.

class ContinuousWorldView(world, fill='#AAA')[source]

Bases: object

View for continuousworld Implementation in agents.py

object_name()[source]

Return the variable name this view is bound to in the main namespace, matched by its creation timestamp, so the JavaScript canvas can address it.

handle_add_obstacle(vertices)[source]

Vertices must be a nestedtuple. This method is called from kernel.execute on completion of a polygon.

handle_remove_obstacle()[source]

Hook for removing an obstacle from the world; not yet implemented.

get_polygon_obstacles_coordinates()[source]

Return the vertex coordinates of every polygon obstacle in the world.

show()[source]

Render the continuous world (its dimensions and obstacles) as an HTML canvas and display it in the notebook output.

class GridWorldView(world, block_size=30, default_fill='white')[source]

Bases: object

View for grid world. Uses XYEnviornment in agents.py as model. world: an instance of XYEnviornment. block_size: size of individual blocks in pixels. default_fill: color of blocks. A hex value or name should be passed.

object_name()[source]

Return the variable name this view is bound to in the main namespace, matched by its creation timestamp, so the JavaScript canvas can address it.

set_label(coordinates, label)[source]

Add labels to a particular block of grid. coordinates: a tuple of (row, column). rows and columns are 0 indexed.

set_representation(thing, repr_type, source)[source]

Set the representation of different things in the environment. thing: a thing object. repr_type : type of representation can be either “color” or “img” source: Hex value in case of color. Image path in case of image.

handle_click(coordinates)[source]

This method needs to be overridden. Make sure to include a self.show() call at the end.

map_to_render()[source]

Build the grid’s render model and return it as a JSON string: a 2D array of cells annotated with each thing’s class name and any per-location tooltip label.

show()[source]

Render the grid world (its cells, sizes, and representations) as an HTML canvas and display it in the notebook output.