API Reference¶
Module contents¶
Algviz is an algorithm visualization tool for your Python code.
Algviz can generate visual animations for vector, table, linked list, tree, and graph data structures. You can bring alive animations in your notebook after inserting a few algviz interfaces into code.
Author: zjl9959@gmail.com
License: GPLv3
- exception algviz.AlgvizFatalError(message)¶
Bases:
Exception
- exception algviz.AlgvizParamError(message)¶
Bases:
Exception
- exception algviz.AlgvizRuntimeError(message)¶
Bases:
Exception
- exception algviz.AlgvizTypeError(obj)¶
Bases:
Exception
- class algviz.BinaryTreeNode(val, left=None, right=None)¶
Bases:
GraphNodeBase
The definition of a binary tree node.
- val¶
The label to be displayed in the binary tree node.
- Type:
printable
- left¶
Point to the left subtree node object.
- Type:
- right¶
Point to the right subtree node object.
- Type:
- class algviz.DoublyLinkedListNode(val, prev=None, next=None)¶
Bases:
GraphNodeBase
The node for doubly linked list.
- val¶
The label to be displayed in the doubly linked list node.
- Type:
printable
- prev¶
Point to the previous DoublyLinkedListNode object.
- Type:
- next¶
Point to the next DoublyLinkedListNode object.
- Type:
- class algviz.ForwardLinkedListNode(val, next=None)¶
Bases:
GraphNodeBase
The node for forward linked list.
- val¶
The label to be displayed in the forward linked list node.
- Type:
printable
- next¶
Point to the next ForwardLinkedListNode object.
- Type:
- class algviz.GraphNode(val)¶
Bases:
GraphNodeBase
This class defined the type of typology graph node.
- val¶
The label to be displayed in the graph node.
- Type:
printable
- add(node, edge=None, index=None)¶
Add a neighbor node for this node.
- Parameters:
node (GraphNode) – The neighbor node object to be added.
edge (printable) – The weight value of the edge between this node and neighbor node.
- Raises:
AlgvizParamError – GraphNode neighbor index should be a positive integer!
- neighborAt(index)¶
Return the neighbor node, edge at the index position of the neighbors list.
- Parameters:
index (int) – The position of the neighbor node.
- Returns:
neighbor node. printable: the edge between this node and the neighbor node.
- Return type:
- Raises:
AlgvizParamError – GraphNode neighbor index type error or out of range.
- neighborCount()¶
Return the neighbors count of this node.
- Returns:
neighbors count.
- Return type:
int
- neighborIndex(node)¶
Return the neighbor node index in the neighbors list.
- Parameters:
node (GraphNode) – The neighbor node object to be located.
- Returns:
the index position of the neighbor node. If node not found, then return -1.
- Return type:
int
- neighbors()¶
Return an iterator to iter over all the neighbor nodes of this node.
- Returns:
Neighbor node iterator.
- Return type:
- remove(node)¶
Remove one neighbor node. Do nothing if node not in neighbors collection.
- Parameters:
node (GraphNode) – The neighbor node to be removed.
- removeAt(index)¶
Remove one neighbor node. Do nothing if node not in neighbors collection.
- Parameters:
index (int) – The neighbor node index to be removed.
- Raises:
AlgvizParamError – GraphNode neighbor index type error or out of range.
- class algviz.RecursiveTree(viz, name='Recursive tree')¶
Bases:
object
Used to trace the recursive process in the recursive algorithm.
- backward(val=None)¶
Backward to the last visited node in the recursive tree. :param val: The update value to be displayed in the recursive tree node. :type val: printable
- forward(val='')¶
Forward to a new depth of this recursive tree. :param val: The label to be displayed in the recursive tree node. :type val: printable
- class algviz.TreeNode(val)¶
Bases:
GraphNodeBase
A tree node has multiply children node.
- val¶
The label to be displayed in the binary tree node.
- Type:
printable
- add(child, index=None)¶
Add a child node for this node.
- Parameters:
child (TreeNode) – The child node object to be added.
index (int) – The position to insert the child node.
- Raises:
AlgvizParamError – TreeNode child index should be a positive integer!
- childAt(index)¶
Return the child node at the index position of the children list.
- Parameters:
index (int) – The position of the child node.
- Returns:
child node.
- Return type:
- Raises:
AlgvizParamError – TreeNode child index type error or out of range.
- childCount()¶
Return the children count of this node.
- Returns:
children count.
- Return type:
int
- childIndex(child)¶
Return the child node index in the children list.
- Parameters:
child (TreeNode) – The child node object to be located.
- Returns:
the index position of the child node. If child not found, then return -1.
- Return type:
int
- children()¶
Return an iterator to iter over all the children nodes of this node.
- Returns:
Children node iterator.
- Return type:
- removeAt(index)¶
Remove the child at the index position.
- Parameters:
index (int) – The child node index to be removed.
- Raises:
AlgvizParamError – TreeNode child index type error or out of range.
- class algviz.Visualizer(delay=2.0, wait=0.5, layout=False)¶
Bases:
object
- createCursor(offset=0, name=None)¶
- Parameters:
offset (int/Cursor) – The cursor’s index position offset.
name (str) – The name of this Cursor object.
- Returns:
Created Cursor object.
- Return type:
- createGraph(data=None, name=None, directed=True)¶
- Parameters:
data (iterable) – The root node(s) to initialize the topology graph.
name (str) – The name of this Vector object.
directed (bool) – Should this graph be directed graph or undirected.
- Returns:
Created SvgGraph object.
- Return type:
- createLogger(buffer_lines=10, name=None, font_size=12, show_line_num=True)¶
- Parameters:
buffer_lines (int) – Maximum buffer line of this logger.
name (str) – The name of this Vector object.
- Returns:
Created Logger object.
- Return type:
- createMap(data=None, name=None)¶
- Parameters:
data (dict) – The initial key and values of this map.
name (str) – The name of this Map object.
- Returns:
Created Map object.
- Return type:
- createTable(row, col, data=None, name=None, cell_size=(40, 40), show_index=True)¶
- Parameters:
row (int) – The number of rows, columns for this table.
col (int) – The number of rows, columns for this table.
data (list(list(printable))) – The initial data for table cells.
name (str) – The name of this table object.
tuple (cell_size) – Table cell size (width, height).
show_index (bool) – Whether to display table row and column labels.
- Returns:
New created Table object.
- Return type:
- createVector(data=None, name=None, cell_size=(40, 40), histogram=False, show_index=True)¶
- Parameters:
data (list(printable)) – The initial data for vector cells.
name (str) – The name of this Vector object.
tuple (cell_size) – Vector cell size (width, height).
histogram (bool) – Display the data in the form of a histogram or not.
show_index (bool) – Whether to display the vector index label.
- Returns:
New created Vector object.
- Return type:
- cursorRange(st, ed, step=1, name=None)¶
- Parameters:
st/ed (int/Cursor) – The start/end of cursor index.
step (int/Cursor) – The change step of this cursor’s index(default->1).
name (str) – The display name of this cursor(default->None).
- Returns:
the iterator of Cursor objects.
- Return type:
_CursorRange
- display(delay=None)¶
Refresh all created display objects.
- Parameters:
delay (float) – Specific the delay time for this animation frame (in seconds).
- layout(max_width=800)¶
Layout all the svg animation pictures. :param max_width: The maximum strip width limit to layouter. :type max_width: int
- Returns:
The final svg string to display.
- Return type:
str
- removeCursor(cursor)¶
- Parameters:
cursor (Cursor) – The cursor object to be removed from this visualizer.
- removeCursors(cursors)¶
- Parameters:
list (cursor) – The list of cursor objects to be removed from this visualizer.
- algviz.generateRandomGraph(nb_nodes, nb_edges, max_degree=None, directed=False)¶
Generate a random graph with the given constraint.
- Parameters:
nb_nodes (int) – the nodes number of this graph, the node id start from 0.
nb_edges (int) – the edges number of this graph.
max_degree (max_degree) – the maximum degree for graph nodes(minimum degree is 1).
directed (boolean) – is this a directed graph or not.
- Returns:
all the nodes in this graph and all the edges in this graph.
- Return type:
nodes (set(printable)), edges (list(tuple(node1, node2, edge)))
- Raises:
AlgvizParamError – generateRandomGraph: input nodes number should be greater than 0.
AlgvizParamError – generateRandomGraph: input edges number should be greater or equal than nodes number.
AlgvizParamError – generateRandomGraph: max_degree is not enough to generate such edges.
AlgvizRuntimeError – generateRandomGraph: can not pick a suitable node.
- algviz.parseBinaryTree(tree_info)¶
Create a new Tree from given node values.
- Parameters:
tree_info (list(printable)) – The label of each node in the tree must be given. Empty node is represented by None. eg:([1, None, 2, None, None, 3, 4])
- Returns:
Root node object of this tree.
- Return type:
- algviz.parseDoublyLinkedList(list_info)¶
Create a new doubly linked list object and return it’s head and tail node.
- Parameters:
list_info (list(printable)) – The labels to display in the doubly linked list’s nodes.
- Returns:
The head and tail node objects for this doubly linked list.
- Return type:
- algviz.parseForwardLinkedList(list_info)¶
Create a new forward linked list object and return it’s head node.
- Parameters:
list_info (list(printable)) – The labels to display in the forward linked list’s nodes.
- Returns:
The head node objet for this forward linked list.
- Return type:
- algviz.parseGraph(nodes, edges, nodes_label=None, directed=True)¶
Create a new graph from edges and nodes information.
All the input edges’s start and edge node should be found in nodes parameter.
Example: parseGraph({0, 1, 2}, [(0, 1), (1, 2), (2, 0)], nodes_label={0:’node_0’})
- Parameters:
nodes (set(printable)) – All the nodes in this graph.
edges (list(tuple(node1, node2, edge))) – All the edges in this graph.
(dict(printable (nodes_label) – printable)): Map the node id into it’s display label.
directed (bool) – Should this graph be directed graph or undirected.
- Returns:
All the graph nodes in this graph. Key is node label in nodes parameter, Value is GraphNode object.
- Return type:
dict(printable)
- Raises:
AlgvizRuntimeError – (paraseGraph) can not find node object for edge xxx.
- algviz.parseTree(tree_info, nodes_label=None)¶
Create a Tree from node_map information and return the root node.
Input tree_info should meet these constraints:
Each node must have one parent node expect for the root node.
2. The node id in tree info should be unique, but you can set the nodes_label to map the unique id into it’s display label text.
- Parameters:
(dict(printable (nodes_label) – list(printable))): Describe the linked information of this tree. Key is the label of root node, Value is the list of it’s children nodes label.
(dict(printable – printable)): Map the node id into it’s display label.
- Returns:
The root node of this tree.
- Return type:
- Raises:
AlgvizParamError – (parseTree) node xxx have more than one parent node!
AlgvizParamError – (parseTree) tree has more than one root node.
- algviz.setUpRandomSeed(sed=None)¶
Set up the random seed when program startup or manually.
- Parameters:
sed (int | float) – the random seed for the random number generator.
algviz.visual module¶
Define visual class in jupyter notebook.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.visual.Visualizer(delay=2.0, wait=0.5, layout=False)¶
Bases:
object
- createCursor(offset=0, name=None)¶
- Parameters:
offset (int/Cursor) – The cursor’s index position offset.
name (str) – The name of this Cursor object.
- Returns:
Created Cursor object.
- Return type:
- createGraph(data=None, name=None, directed=True)¶
- Parameters:
data (iterable) – The root node(s) to initialize the topology graph.
name (str) – The name of this Vector object.
directed (bool) – Should this graph be directed graph or undirected.
- Returns:
Created SvgGraph object.
- Return type:
- createLogger(buffer_lines=10, name=None, font_size=12, show_line_num=True)¶
- Parameters:
buffer_lines (int) – Maximum buffer line of this logger.
name (str) – The name of this Vector object.
- Returns:
Created Logger object.
- Return type:
- createMap(data=None, name=None)¶
- Parameters:
data (dict) – The initial key and values of this map.
name (str) – The name of this Map object.
- Returns:
Created Map object.
- Return type:
- createTable(row, col, data=None, name=None, cell_size=(40, 40), show_index=True)¶
- Parameters:
row (int) – The number of rows, columns for this table.
col (int) – The number of rows, columns for this table.
data (list(list(printable))) – The initial data for table cells.
name (str) – The name of this table object.
tuple (cell_size) – Table cell size (width, height).
show_index (bool) – Whether to display table row and column labels.
- Returns:
New created Table object.
- Return type:
- createVector(data=None, name=None, cell_size=(40, 40), histogram=False, show_index=True)¶
- Parameters:
data (list(printable)) – The initial data for vector cells.
name (str) – The name of this Vector object.
tuple (cell_size) – Vector cell size (width, height).
histogram (bool) – Display the data in the form of a histogram or not.
show_index (bool) – Whether to display the vector index label.
- Returns:
New created Vector object.
- Return type:
- cursorRange(st, ed, step=1, name=None)¶
- Parameters:
st/ed (int/Cursor) – The start/end of cursor index.
step (int/Cursor) – The change step of this cursor’s index(default->1).
name (str) – The display name of this cursor(default->None).
- Returns:
the iterator of Cursor objects.
- Return type:
_CursorRange
- display(delay=None)¶
Refresh all created display objects.
- Parameters:
delay (float) – Specific the delay time for this animation frame (in seconds).
- layout(max_width=800)¶
Layout all the svg animation pictures. :param max_width: The maximum strip width limit to layouter. :type max_width: int
- Returns:
The final svg string to display.
- Return type:
str
- removeCursor(cursor)¶
- Parameters:
cursor (Cursor) – The cursor object to be removed from this visualizer.
- removeCursors(cursors)¶
- Parameters:
list (cursor) – The list of cursor objects to be removed from this visualizer.
algviz.vector module¶
Define the table data structure.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.vector.Vector(data, delay, cell_size, histogram, show_index)¶
Bases:
object
A vector is an expandable list, you can add or remove cell for vector. When the cell position changed, the vector display SVG will show the related animation.
[WARNING] Don’t create this class directly, use algviz.Visualizer.createTable instead.
- append(val)¶
Append a new value into vector’s tail.
- Parameters:
val (printable) – The value to appended into vector’s tail.
- clear()¶
Clear all the values in vector.
- insert(index, val)¶
Insert a new value into vector. If index < 0 or index >= length of Vector, then set index = index % vector length.
- Parameters:
index (int/Cursor) – The subscript index to insert value. (Insert before index)
val (printable) – The value to insert into vector.
- Raises:
RuntimeError – Index:xxx type is not int or Cursor.
RuntimeError – Vector index=xxx out of range!
- mark(color, st, ed=None, hold=False)¶
Emphasize one or more cell(s) in the Vector by mark it’s background color.
- Parameters:
color ((R,G,B)) – The background color for the marked cell. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
st (int/Cursor) – The mark range’s index in Vector.
ed (int/Cursor) – The mark range’s index in Vector.
hold (bool) – Whether to keep the mark color in future animation frames.
- marks(color, ranges, hold=False)¶
Emphasize one or more cell(s) in the Vector by mark it’s background color.
- Parameters:
color ((R,G,B)) – The background color for the marked cell. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
list (ranges) – A list of range’s index in Vector to be marked.
hold (bool) – Whether to keep the mark color in future animation frames.
- pop(index=None)¶
Pop a value from vector. Pop vector’s tail value as default.
- Parameters:
index (int/Cursor) – The index position of value to pop out.
- Returns:
The element at the index position.
- Return type:
printable
- Raises:
RuntimeError – Index:xxx type is not int or Cursor.
RuntimeError – Vector index=xxx out of range!
- removeMark(color)¶
Remove the mark color for cell(s).
- Parameters:
color ((R,G,B)) – R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
- removeMarks(color_list)¶
Remove the mark colors for cell(s).
- Parameters:
color_list ([(R,G,B), ...]) – all the colors to be removed.
- swap(index1, index2)¶
Swap the two cells positon in Vector. :param index1: The two index positions to be swapped. :type index1: int/Cursor :param index2: The two index positions to be swapped. :type index2: int/Cursor
- Raises:
RuntimeError – Index:xxx type is not int or Cursor.
RuntimeError – Vector index=xxx out of range!
algviz.table module¶
Define the table data structure related classes.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.table.Table(row, col, data, cell_size, show_index)¶
Bases:
object
A static table with label text in table cells.
[WARNING] Don’t create this class directly, use algviz.Visualizer.createTable instead.
- getItem(r, c)¶
Get the cell value in the table.
- Parameters:
r (int/Cursor) – Index the cell’s raw, column in the table.
c (int/Cursor) – Index the cell’s raw, column in the table.
- Returns:
The value in the specific cell.
- Return type:
printable
- Raises:
RuntimeError – Index:xx type is not int or Cursor.
RuntimeError – Table index=xxx out of range.
- mark(color, r, c, hold=False, r2=None, c2=None)¶
Emphasize one cell in the table by mark it’s background color.
- Parameters:
color ((R,G,B)) – The background color for the marked cell. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
r (int/Cursor) – Index the cell’s raw, column in the table to be marked.
c (int/Cursor) – Index the cell’s raw, column in the table to be marked.
hold (bool) – Whether to keep the mark color in future animation frames.
r2 (int/Cursor) – If r2, c2 are not None, this will mark cells in the rectange range(r, c, r2, c2).
c2 (int/Cursor) – If r2, c2 are not None, this will mark cells in the rectange range(r, c, r2, c2).
- Raises:
RuntimeError – Index:xx type is not int or Cursor.
RuntimeError – Table index=xxx out of range.
- marks(color, points, hold=False)¶
Emphasize one cell in the table by mark it’s background color.
- Parameters:
color ((R,G,B)) – The background color for the marked cell. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
points – list(((int/Cursor), (int/Cursor))): A list of indexs represent of the cell’s raw, column in the table to be marked.
hold (bool) – Whether to keep the mark color in future animation frames.
- Raises:
RuntimeError – Index:xx type is not int or Cursor.
RuntimeError – Table index=xxx out of range.
- removeMark(color)¶
Remove the mark color for cell(s).
- Parameters:
color ((R,G,B)) – R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
- removeMarks(color_list)¶
Remove the mark colors for cell(s).
- Parameters:
color_list ([(R,G,B), ...]) – all the colors to be removed.
- reshape(row, col)¶
Reshape the row and column size of this table. row, col (int): The new row and column number of the table.
- Raises:
AlgvizParamError – Table row or col number should > 0.
- setItem(r, c, val)¶
Get the cell value in the table.
- Parameters:
r (int/Cursor) – Index the cell’s raw, column in the table to be modified.
c (int/Cursor) – Index the cell’s raw, column in the table to be modified.
val (printable) – New value for the cell.
- Raises:
RuntimeError – Index:xx type is not int or Cursor.
RuntimeError – Table index=xxx out of range.
- shape()¶
- Returns:
Return the rows and columns of this table.
- Return type:
tuple(int, int)
- class algviz.table.TableRowIter(r, tab)¶
Bases:
object
An iterator that iterate on one specifies row in Table object.
- class algviz.table.TableRowOperator(r, tab)¶
Bases:
object
A manipulator to get/set the elements of the specified row in the table.
algviz.linked_list module¶
Define linked list related classes and functions.
Including ForwardLinkedListNode, DoublyLinkedListNode class and parseForwardLinkedList, parseDoublyLinkedList function to parse linked list from string.
Typical usage example:
head = parseForwardLinkedList([1, 2, 3]) # Create a forward linked list: 1->2-3
new_head = ForwardLinkedListNode(0) # Create a forward linked list node: 0
new_head.next = head # Link node into linked list, and get: 0->1->2->3
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.linked_list.DoublyLinkedListNode(val, prev=None, next=None)¶
Bases:
GraphNodeBase
The node for doubly linked list.
- val¶
The label to be displayed in the doubly linked list node.
- Type:
printable
- prev¶
Point to the previous DoublyLinkedListNode object.
- Type:
- next¶
Point to the next DoublyLinkedListNode object.
- Type:
- class algviz.linked_list.ForwardLinkedListNode(val, next=None)¶
Bases:
GraphNodeBase
The node for forward linked list.
- val¶
The label to be displayed in the forward linked list node.
- Type:
printable
- next¶
Point to the next ForwardLinkedListNode object.
- Type:
- algviz.linked_list.parseDoublyLinkedList(list_info)¶
Create a new doubly linked list object and return it’s head and tail node.
- Parameters:
list_info (list(printable)) – The labels to display in the doubly linked list’s nodes.
- Returns:
The head and tail node objects for this doubly linked list.
- Return type:
- algviz.linked_list.parseForwardLinkedList(list_info)¶
Create a new forward linked list object and return it’s head node.
- Parameters:
list_info (list(printable)) – The labels to display in the forward linked list’s nodes.
- Returns:
The head node objet for this forward linked list.
- Return type:
algviz.tree module¶
Define tree related classes and functions.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.tree.BinaryTreeNode(val, left=None, right=None)¶
Bases:
GraphNodeBase
The definition of a binary tree node.
- val¶
The label to be displayed in the binary tree node.
- Type:
printable
- left¶
Point to the left subtree node object.
- Type:
- right¶
Point to the right subtree node object.
- Type:
- class algviz.tree.RecursiveTree(viz, name='Recursive tree')¶
Bases:
object
Used to trace the recursive process in the recursive algorithm.
- backward(val=None)¶
Backward to the last visited node in the recursive tree. :param val: The update value to be displayed in the recursive tree node. :type val: printable
- forward(val='')¶
Forward to a new depth of this recursive tree. :param val: The label to be displayed in the recursive tree node. :type val: printable
- class algviz.tree.TreeChildrenIter(node, children)¶
Bases:
object
Iterator for the children of TreeNode object.
- class algviz.tree.TreeNode(val)¶
Bases:
GraphNodeBase
A tree node has multiply children node.
- val¶
The label to be displayed in the binary tree node.
- Type:
printable
- add(child, index=None)¶
Add a child node for this node.
- Parameters:
child (TreeNode) – The child node object to be added.
index (int) – The position to insert the child node.
- Raises:
AlgvizParamError – TreeNode child index should be a positive integer!
- childAt(index)¶
Return the child node at the index position of the children list.
- Parameters:
index (int) – The position of the child node.
- Returns:
child node.
- Return type:
- Raises:
AlgvizParamError – TreeNode child index type error or out of range.
- childCount()¶
Return the children count of this node.
- Returns:
children count.
- Return type:
int
- childIndex(child)¶
Return the child node index in the children list.
- Parameters:
child (TreeNode) – The child node object to be located.
- Returns:
the index position of the child node. If child not found, then return -1.
- Return type:
int
- children()¶
Return an iterator to iter over all the children nodes of this node.
- Returns:
Children node iterator.
- Return type:
- removeAt(index)¶
Remove the child at the index position.
- Parameters:
index (int) – The child node index to be removed.
- Raises:
AlgvizParamError – TreeNode child index type error or out of range.
- algviz.tree.parseBinaryTree(tree_info)¶
Create a new Tree from given node values.
- Parameters:
tree_info (list(printable)) – The label of each node in the tree must be given. Empty node is represented by None. eg:([1, None, 2, None, None, 3, 4])
- Returns:
Root node object of this tree.
- Return type:
- algviz.tree.parseTree(tree_info, nodes_label=None)¶
Create a Tree from node_map information and return the root node.
Input tree_info should meet these constraints:
Each node must have one parent node expect for the root node.
2. The node id in tree info should be unique, but you can set the nodes_label to map the unique id into it’s display label text.
- Parameters:
(dict(printable (nodes_label) – list(printable))): Describe the linked information of this tree. Key is the label of root node, Value is the list of it’s children nodes label.
(dict(printable – printable)): Map the node id into it’s display label.
- Returns:
The root node of this tree.
- Return type:
- Raises:
AlgvizParamError – (parseTree) node xxx have more than one parent node!
AlgvizParamError – (parseTree) tree has more than one root node.
algviz.graph module¶
Define graph related classes and functions.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.graph.GraphNeighborIter(node, neighbors)¶
Bases:
object
Neighbor nodes iterator for GraphNode class.
- class algviz.graph.GraphNode(val)¶
Bases:
GraphNodeBase
This class defined the type of typology graph node.
- val¶
The label to be displayed in the graph node.
- Type:
printable
- add(node, edge=None, index=None)¶
Add a neighbor node for this node.
- Parameters:
node (GraphNode) – The neighbor node object to be added.
edge (printable) – The weight value of the edge between this node and neighbor node.
- Raises:
AlgvizParamError – GraphNode neighbor index should be a positive integer!
- neighborAt(index)¶
Return the neighbor node, edge at the index position of the neighbors list.
- Parameters:
index (int) – The position of the neighbor node.
- Returns:
neighbor node. printable: the edge between this node and the neighbor node.
- Return type:
- Raises:
AlgvizParamError – GraphNode neighbor index type error or out of range.
- neighborCount()¶
Return the neighbors count of this node.
- Returns:
neighbors count.
- Return type:
int
- neighborIndex(node)¶
Return the neighbor node index in the neighbors list.
- Parameters:
node (GraphNode) – The neighbor node object to be located.
- Returns:
the index position of the neighbor node. If node not found, then return -1.
- Return type:
int
- neighbors()¶
Return an iterator to iter over all the neighbor nodes of this node.
- Returns:
Neighbor node iterator.
- Return type:
- remove(node)¶
Remove one neighbor node. Do nothing if node not in neighbors collection.
- Parameters:
node (GraphNode) – The neighbor node to be removed.
- removeAt(index)¶
Remove one neighbor node. Do nothing if node not in neighbors collection.
- Parameters:
index (int) – The neighbor node index to be removed.
- Raises:
AlgvizParamError – GraphNode neighbor index type error or out of range.
- algviz.graph.generateRandomGraph(nb_nodes, nb_edges, max_degree=None, directed=False)¶
Generate a random graph with the given constraint.
- Parameters:
nb_nodes (int) – the nodes number of this graph, the node id start from 0.
nb_edges (int) – the edges number of this graph.
max_degree (max_degree) – the maximum degree for graph nodes(minimum degree is 1).
directed (boolean) – is this a directed graph or not.
- Returns:
all the nodes in this graph and all the edges in this graph.
- Return type:
nodes (set(printable)), edges (list(tuple(node1, node2, edge)))
- Raises:
AlgvizParamError – generateRandomGraph: input nodes number should be greater than 0.
AlgvizParamError – generateRandomGraph: input edges number should be greater or equal than nodes number.
AlgvizParamError – generateRandomGraph: max_degree is not enough to generate such edges.
AlgvizRuntimeError – generateRandomGraph: can not pick a suitable node.
- algviz.graph.parseGraph(nodes, edges, nodes_label=None, directed=True)¶
Create a new graph from edges and nodes information.
All the input edges’s start and edge node should be found in nodes parameter.
Example: parseGraph({0, 1, 2}, [(0, 1), (1, 2), (2, 0)], nodes_label={0:’node_0’})
- Parameters:
nodes (set(printable)) – All the nodes in this graph.
edges (list(tuple(node1, node2, edge))) – All the edges in this graph.
(dict(printable (nodes_label) – printable)): Map the node id into it’s display label.
directed (bool) – Should this graph be directed graph or undirected.
- Returns:
All the graph nodes in this graph. Key is node label in nodes parameter, Value is GraphNode object.
- Return type:
dict(printable)
- Raises:
AlgvizRuntimeError – (paraseGraph) can not find node object for edge xxx.
algviz.map module¶
Define the map class and related functions.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.map.Map(data, delay)¶
Bases:
object
Map contains keys and values, each key corresponding to a value.
Map is relational container. You can get the value of a given key and update value. You can also add or remove a (key, value) pair and iterate on existing keys, values or items. [WARNING] Don’t create this class directly, use algviz.Visualizer.createMap instead.
- clear()¶
Removes all the elements from the map.
- get(k, default=None)¶
Returns the value of the item with the specified key.
Returns the default value set by default if the key is not in the map.
- Parameters:
k (printable) – the specified key.
default (printable) – the default value.
- Returns:
the value of the item with the specified key
- Return type:
printable
- items()¶
Returns a list containing a tuple for each key value pair.
- Returns:
a list containing a tuple for each key value pair.
- Return type:
iterable((printable, printable))
- keys()¶
Returns a list containing the map’s keys.
- Returns:
a list containing the map’s keys.
- Return type:
iterable(printable)
- mark(color, keys, hold=False)¶
Emphasize the key and value nodes by mark it’s background color.
- Parameters:
color ((R,G,B)) – The background color for the marked node. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
keys (iterable(printable)) – The list of keys to be marked.
hold (bool) – Whether to keep the mark color in future animation frames.
- pop(k, default=None)¶
Removes the element with the specified key.
- Parameters:
k (printable) – the specified key.
default (printable) – the default value.
- Returns:
the value of the item to be removed or the default value.
- Return type:
printable
- removeMark(color)¶
Remove the mark color.
- Parameters:
color ((R,G,B)) – R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
- removeMarks(color_list)¶
Remove the mark colors.
- Parameters:
color_list ([(R,G,B), ...]) – all the colors to be removed.
- values()¶
Returns a list of all the values in the map.
- Returns:
a list of all the values in the map.
- Return type:
iterable(printable)
algviz.logger module¶
Define the Logger related classes.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.logger.Logger(buffer_lines, font_size, show_line_num)¶
Bases:
object
A log class to display strings into the screen.
You can write string into this logger object, it will separate lines by n. And if the buffer lines overflow, the oldest lines in the buffer will be discard.
- clear()¶
Clear all cached log string.
- write(data)¶
Write log data. Use n to split multi-lines.
- Parameters:
data (str) – The log data string.
algviz.cursor module¶
Define the cursor related classes.
A cursor is an arrow shown in Vector or Table’s SVG display. The cursor represents the index of the element in Vector or Table.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.cursor.Cursor(name, index, id)¶
Bases:
object
A cursor is a display object to show the current index of Vector or Table(row/column).
A cursor object should be created from Visualizer.create_cursor or Visualizer.cursorRange interfaces. After that, you can access the element in any Vector/Table object with the created cursor just like an integer index. The index in the cursor should be an integer number.
Assignment operation: <<
- Mathmatics operations:
No side effect, returns a int number: +, -, *, //, %
Changes the cursor’s index and returns itself: +=, -=, *=, //=, %=
Compare operations: >, <, >=, <=, ==, !=
The right-hand value of those operations above can be a cursor or an integer number.
- For example:
i = viz.createCursor(3, ‘i’) # The index in cursor i is 3.
j = viz.createCursor(5, ‘j’) # The index in cursor j is 5.
i += j # The index in cursor i change from 3 into 8(3+5).
j << i - 1 # The index in cursor j change from 5 into 7(8-1).
i > j # True: 8 > 7 is true.
- index()¶
- Returns:
The cursor’s current index value.
- Return type:
int
- name()¶
- Returns:
Cursor display name.
- Return type:
str
algviz.graph_node_base module¶
Define the base class for all the graph nodes.
Do not create GraphNodeBase class directly, create one of it’s subclass instead.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.graph_node_base.GraphNodeBase(val)¶
Bases:
object
Base class for all the graph nodes.
GraphNodeBase’s subclasses contain: GraphNode, BinaryTreeNode, ForwardLinkedListNode and DoublyLinkedListNode. If you want to get/set attribute in subclass, don’t use dot operation like ‘self.attr’. Please use these interfaces instead:
super().__getattribute__(attr)
super().__setattr__(attr, new_value)
- val¶
The label to be displayed in the graph node.
- Type:
printable
algviz.svg_graph module¶
Define low-level SVG animation refresh related classes for graph.
This module was used by linked_list, tree and graph module. You can use the addNode, removeNode, markNode, markEdge and removeMark interfaces to update the graph.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.svg_graph.SvgGraph(data, directed, delay)¶
Bases:
object
A SvgGraph object can record all the nodes in it’s binded graph.
It will relayout the graph and generate animation when add/remove/replace node(s) in graph. It will also show the mark of graph node(s)&edge(s) visit status. Every time __repr_svg__ function is called, SvgGraph object will return the latest svg string for this graph and prepare for a new frame.
- addNode(node)¶
Add a new node and all it’s successor nodes into this graph.
- Parameters:
node (subclass of GraphNodeBase) – The node object to be added. Can be a graph/tree/linked_list node.
- Returns:
The number of node(s) added into graph.
- Return type:
int
- markEdge(color, node1, node2, hold=False)¶
Emphasize one edge by mark it’s stoke color.
- Parameters:
color ((R,G,B)) – The stroke color for the marked edge. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
node1 (subclass of GraphNodeBase) – The begin and end node in the edge to be marked. Can be a graph/tree/linked_list node.
node2 (subclass of GraphNodeBase) – The begin and end node in the edge to be marked. Can be a graph/tree/linked_list node.
hold (bool) – Whether to keep the mark color in future animation frames.
- markEdges(color, edges, hold=False)¶
Emphasize some edges by mark it’s stoke color.
- Parameters:
color ((R,G,B)) – The stroke color for the marked edge. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
list (edges) – The list of edges to be markd. One edge contains the begin and end node in the edge to be marked.
hold (bool) – Whether to keep the mark color in future animation frames.
- markNode(color, node, hold=False)¶
Emphasize one node by mark it’s background color.
- Parameters:
color ((R,G,B)) – The background color for the marked node. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
node (subclass of GraphNodeBase) – The node object to be marked. Can be a graph/tree/linked_list node.
hold (bool) – Whether to keep the mark color in future animation frames.
- markNodes(color, nodes, hold=False)¶
Emphasize some nodes by mark it’s background color.
- Parameters:
color ((R,G,B)) – The background color for the marked node. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
list (nodes) – A list of node objects to be marked. Can be a graph/tree/linked_list node.
hold (bool) – Whether to keep the mark color in future animation frames.
- removeMark(color)¶
Remove the mark color for node(s) and edge(s).
- Parameters:
color ((R,G,B)) – R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
- removeMarks(color_list)¶
Remove the mark colors for node(s) and edge(s).
- Parameters:
color_list ([(R,G,B), ...]) – all the colors to be removed.
- removeNode(node, recursive=False)¶
Remove a node from this graph. Remove this node’s all successor nodes if recursive is True.
If the removed node(s) have input edge(s) from the remains node(s) in this graph, do nothing a return 0.
- Parameters:
node (subclass of GraphNodeBase) – The node object to be removed. Can be a graph/tree/linked_list node.
recursive (bool) – Wheather to remove all the successor nodes of this node.
- Returns:
The number of node(s) removed from graph.
- Return type:
int
algviz.svg_table module¶
Define low-level SVG animation refresh related classes for table.
This module was used by vector and table module. Please don’t use this module unless you want to create new data classes for algviz and knows exactly the meaning of this module.
Author: zjl9959@gmail.com
License: GPLv3
- class algviz.svg_table.SvgTable(width, height)¶
Bases:
object
- add_animate_appear(gid, time, appear=True)¶
Add appear animate for specific element.
- Parameters:
gid (int) – The unique ID of the element to add animation.
time ((begin, end)) – The begin and end time of this animation.
appear (bool) – True for appear animation; False for disappear animation.
- add_animate_move(gid, move, time, bessel=True)¶
Add move animation for specific element.
- Parameters:
gid (int) – The unique ID of the element to add animation.
move (tuple(float, float)) – (delt_x, delt_y) The delt move distance along x axis and y axis for this element.
time (tuple(float, float)) – (begin, end) The begin and end time of this animation.
bessel (bool) – Whether to set the path of this move animation as bezier curve.
- add_cursor_element(cursor, color=(123, 123, 123), name=None, dir='U')¶
Add a cursor into SVG table.
A cursor is an arrow to indicate the current index of rect element. It will be displayed in the SVG and you need to choose the proper position to put it.
- Parameters:
cursor (float, float, float, float, float) – The x, y, offset, width, height of the arrow in cursor. x, y is the arrow’s top point position, relative to the SVG’s top left point. Offset is the x offset of the arrow relative to x position. width, height is the total width and height of cursor, including arrow and name.
color – ((int, int, int)): The (Red, Green, Blue) stroke color of the cursor’s arrow and name.
name (str) – The name to be displayed close to the arrow.
dir (str) – The direction of the arrow (U:up; D:down; L:left; R:right).
- Returns:
Unique ID number for the new added cursor element in this SvgTable.
- Return type:
int
- add_rect_element(rect, text=None, fill=(255, 255, 255), stroke=(123, 123, 123), angle=True)¶
Add a new rectangle element into this SvgTable.
- Parameters:
rect ((x, y, w, h)) – The left bottom corner position(x,y) and width height of this new rectangle. eg:(0.0, 50.0, 100.0, 50.0).
text (str) – The text string to be displayed in this rectangle.
fill ((R,G,B)) – Rectangle’s background color. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
stroke ((R,G,B)) – Rectangle’s stroke color. (R, G, B) type is the same as fill parameter.
angle (bool) – The shape of this new rectangle’s corner. True for round corner; False for sharp corner.
- Returns:
Unique ID number for the new added rect element in this SvgTable.
- Return type:
int
- add_text_element(pos, text, font_size=16, fill=(123, 123, 123))¶
Add a new text element into this SvgTable.
- Parameters:
pos ((x,y)) – The left bottom corner position(x,y), x and y are both float number.
text (str) – The text string.
font_size (int) – Text font size.
fill ((R,G,B)) – Stroke color of this text element. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 0, 0)
- Returns:
Unique ID number for the new added text element in this SvgTable.
- Return type:
int
- clear_animates()¶
Clear all the animations in this SvgTable.
- delete_element(gid)¶
Delete specific element from this SvgTable.
- Parameters:
gid (int) – The unique ID of the element to be deleted.
- update_cursor_element(gid, new_pos)¶
Update the cursor’s position.
- Parameters:
gid (int) – The unique ID of the cursor to be updated.
(delt_x (new_pos) – float, delt_y:float): New position of the cursor’s arrow top, relative to cursor’s old position.
- update_rect_element(gid, rect=None, text=None, fill=None, stroke=None, opacity=None, delay=0)¶
Update the color, text, fill, stroke and opacity attribute of specific rectangle element.
- Parameters:
gid (int) – The unique ID of the rectangle to be updated.
rect ((x, y, w, h) or None) – New position and size for this rectangle. (x, y) is rectangle’s left bottom corner. Keep old position and size if rect is None.
text (str or None) – The text string to be displayed in this rectangle.
fill ((R,G,B) or None) – New background color for this rectangle. Keep old background color if fill is None.
stroke ((R,G,B) or None) – New stroke color for this rectangle. Keep old stroke color if stroke is None.
opacity (float or None) – New opacity arrtibute for this rectangle. Keep old opacity if opacity is None.
delay (float) – The total delay time of text scale animations.
- update_svg_size(width, height)¶
Update the width and height of this svg table.
- Parameters:
width (float) – The width of svg table.
heigt (float) – The height of svg table.
- update_text_element(gid, pos=None, text=None, font_size=None, fill=None)¶
Update the text element’s position and text string/font/color in this SvgTable.
- Parameters:
gid (int) – The unique ID of the rectangle to be updated.
pos ((x,y)) – The left bottom corner position(x,y), x and y are both float number.
text (str) – The text string.
font_size (int) – Text font size.
fill ((R,G,B)) – Stroke color of this text element. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 0, 0)
algviz.utility module¶
Some utility functions and classes used by other modules.
Author: zjl9959@gmail.com
License: GPLv3
- exception algviz.utility.AlgvizFatalError(message)¶
Bases:
Exception
- exception algviz.utility.AlgvizParamError(message)¶
Bases:
Exception
- exception algviz.utility.AlgvizRuntimeError(message)¶
Bases:
Exception
- exception algviz.utility.AlgvizTypeError(obj)¶
Bases:
Exception
- class algviz.utility.ConsecutiveIdMap(offset=0)¶
Bases:
object
Allocate contiguous integer numbers for hashable objects.
- toAttributeId(cons_id)¶
Given a continuous ID, return it’s correspond unordered ID.
- Parameters:
cons_id (int) – Continuous ID value.
- Returns:
Unordered ID object.
- Return type:
hashable
- toConsecutiveId(attr_id)¶
Create or get the continuous ID for an unordered ID.
- Parameters:
attr_id (hashable) – Unordered ID object.
- Returns:
Continuous ID value.
- Return type:
int
- class algviz.utility.TraceColorStack(bgcolor=(255, 255, 255))¶
Bases:
object
Manage multiple colors on an element, perform color fusion operations.
- add(color)¶
Add a new color into TraceColorStack.
- Parameters:
color ((R,G,B)) – R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
- color()¶
Get the merged color in TraceColorStack.
- Returns:
R, G, B stand for color channel for red, green, blue.
- Return type:
color ((R,G,B))
- remove(color)¶
Remove color from TraceColorStack.
- Parameters:
color ((R,G,B)) – R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
- Returns:
Return False if can’t color. Return True if successfully deleted color.
- Return type:
bool
- algviz.utility.add_animate_appear_into_node(g, animate, time, appear=True)¶
g (xmldom.Node): The SVG node to add appear animation into. animate (xmldom.Node): The animate node to be added into node g. time (tuple(float, float)) (begin, end) The begin and end time of this animation. appear (bool): True for appear animation; False for disappear animation.
- algviz.utility.add_animate_move_into_node(g, animate, move, time, bessel)¶
- Parameters:
g (xmldom.Node) – The SVG node to add move animation into.
animate (xmldom.Node) – The animate node to be added into node g.
move (tuple(float, float)) – (delt_x, delt_y) The delt move distance along x axis and y axis for this element.
time (tuple(float, float)) – (begin, end) The begin and end time of this animation.
bessel (bool) – Whether to set the path of this move animation as bezier curve.
- algviz.utility.add_animate_scale_into_text(t, animate, time, font_size, zoom_in=True)¶
t (xmldom.Node): The text node to add scale animation into. animate (xmldom.Node): The animate node to be added into node g. time (tuple(float, float)) (begin, end) The begin and end time of this animation. font_size (float): The text nodes font size. zoome_in (bool): True for zoom out animation; False for zoume in animation.
- algviz.utility.add_default_text_style(dom)¶
Add the default text style into svg.
- Parameters:
dom (xmldom.document) –
- algviz.utility.add_desc_into_svg(dom)¶
Add description meta data into SVG dom tree.
- Parameters:
dom (xmldom.document) –
- algviz.utility.auto_text_color(back_color)¶
Auto pick one text stroke color according to it’s background color.
- Parameters:
back_color ((R,G,B)) – Text background color. R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
- Returns:
- Text stroke color value formatted with hexadecimal number(SVG format).
eg: ‘#FFFFFF’
- Return type:
str
- algviz.utility.clamp(val, min_val, max_val)¶
- Returns:
The clamped value between min_val and max_val.
- algviz.utility.clear_svg_animates(svg)¶
Clear all the animation effects in SVG. :param svg: The SVG object to be cleared. :type svg: xmldom.Node
- algviz.utility.find_tag_by_id(node, tag_name, tag_id)¶
Find the first match node in XML node and its sub nodes. :param node: The XML node object to search. :type node: xmldom.Node :param tag_name: The tag name of the element. :type tag_name: str :param tag_id: :type tag_id: str
- Returns:
Return the XML node object if found it, otherwise return None.
- Return type:
xmldom.Node or None
- algviz.utility.get_text_width(text, font_size)¶
Calculate the total text width of the given text string.
- Parameters:
font_size (int) – The font size of text.
text (str) – The text content (should be unicode format string).
- Returns:
The total width of the text.
- Return type:
float
- algviz.utility.layout_text(text, width, height, font_size)¶
- Layout the text position in the given text box.
Support mult-line text. Just support rectangle text box.
- Parameters:
text (str) – The text content (should be unicode format string).
font_size (int) – The text font size.
width (int) – The width of the text box.
height (int) – The height of the text box.
- Returns:
- (string, x_pos, y_pos)
return the layout text strings and their position information.
- Return type:
list(tuple(str, int, int))
- algviz.utility.rgbcolor2str(color)¶
Convert (R, G, B) formatted color into hexadecimal formatted string.
- Parameters:
color ((R,G,B)) – R, G, B stand for color channel for red, green, blue. R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
- Returns:
Hexadecimal formatted string. (SVG format). eg: ‘#FFFFFF’
- Return type:
str
- algviz.utility.setUpRandomSeed(sed=None)¶
Set up the random seed when program startup or manually.
- Parameters:
sed (int | float) – the random seed for the random number generator.
- algviz.utility.str2rgbcolor(color_str)¶
Convert hexadecimal formatted string into (R, G, B) formatted color.
- Parameters:
color_str (str) – Hexadecimal formatted string. (SVG format). eg: ‘#FFFFFF’
- Returns:
- R, G, B stand for color channel for red, green, blue.
R,G,B should be int value and 0 <= R,G,B <= 255. eg:(0, 255, 0)
- Return type:
(R,G,B)
- algviz.utility.text_char_num(text)¶
Count the number of characters in the text.
- Parameters:
text (str) – The text content (should be unicode format string).
- Returns:
The number of characters in the text.
- Return type:
int
- algviz.utility.text_font_size(text_width, text)¶
Calculate the font size based on the total width of the text and the text content.
- Parameters:
text_width (float) – The total width of the text.
text (str) – The text content (should be unicode format string).
- Returns:
Text font size.
- Return type:
float