Search Algorithm Playground
Search Algorithm Playground is a python package to work with graph related algorithm, mainly dealing with different Artificial Intelligence Search alorithms. The tool provides an user interface to work with the graphs and visualise the effect of algorithm on the graph while giving the freedom to programmer to make adjustments in the way they wants. It also provides a way to save the graph in json format hence enabling the programmers to share the files and use different algorithm on same graph with ease.
The package is made using pygame module.
Currently supports only undirected graphs
Table of Contents
Installation
Install from pip
pip install SearchAlgoPlayground
Manually install it
Copy the repository in your system then do
python setup.py install
You can also copy/paste the SearchAlgoPlayground folder into your project
Controls
Creating a node
Double click on any empty block will create a node on it.
NOTE: Single click highlights the selected block and info label area will display it's location in 2D Matrix.
Creating an edge between two nodes
Clicking on a node single time selects the node for creating an edge with that.
Select one node, once selected select another node to create an edge between them.
Modify element mode
Double click on any element makes it go in modify mode which allows the element to be deleted or edited.
To delete an edge double click on it and then press DELETE
To edit an edge weight double click and use keyboard to modify it's value, once done hit ENTER or click anywhere else.
To delete a node double click on it and then hit DELETE on keyboard
To edit node label double click on a node and use keyboard to modify the label, once done hit ENTER or click anywhere else.
NOTE: Label of a node must be unique
Move nodes on the playground
Click on the node and drag it on the playground.
Basic Use:
- simple PlayGround
- Loading graph from file
- Set filename to save your work into
- PlayGround with weighted edge
- Setting up dimension for the world in playground
- Setting onStart event
- Changing configuration for playground
- Working with neighbouring nodes
simple PlayGround:
Creates PlayGround object with default values
from SearchAlgoPlayground import PlayGround
pg = PlayGround() #Creating a playground object
pg.run() #run the playground
Loading graph from file:
Method Used: fromfilename()
NOTE: The graph file here in below example Graph.json must have been saved by the playground, i.e. saved by clicking Save Work button.
from SearchAlgoPlayground import PlayGround
pg = PlayGround.fromfilename("Graph.json") #loading a playground from a file
pg.run() #run the playground
Set filename to save your work into:
Parameter used: saveToFile
from SearchAlgoPlayground import PlayGround
pg = PlayGround(saveToFile = "MyWork.json") #Creating a playground object with name of the file provided where the work will be saved
pg.run() #run the playground
PlayGround with weighted edge:
Parameter used: weighted
from SearchAlgoPlayground import PlayGround
pg = PlayGround(weighted=True) #Weighted playground
pg.run() #run the playground
Setting up dimension for the world in playground:
Parameter used: saveToFile, weighted, block_dimensions
from SearchAlgoPlayground import PlayGround
#A weighted playground with a name of the file where work need to be saved given as MyWork.json
#block_dimension is dimension of 2D matrix (rows,cols) here both are 20
pg = PlayGround(saveToFile = "MyWork.json",weighted=True,blocks_dimension=(20,20))
pg.run() #run the playground
Setting onStart event:
Method set as onStart will be executed once the Start button is clicked shown on playground.
Parameter used: saveToFile, weighted, block_dimensions
Method used: onStart()
from SearchAlgoPlayground import PlayGround
#A weighted playground with a name of the file where work need to be saved given as MyWork.json
#block_dimension is dimension of 2D matrix (rows,cols) here both are 20
pg = PlayGround(saveToFile = "MyWork.json",weighted=True,blocks_dimension=(20,20))
##Sample function to be put as start for playground
def sayHello():
print("Hello From Playground!")
pg.onStart(sayHello) #Setting method for on start click
pg.run() #run the playground
Changing configuration for playground:
Changing values in configuration can modify the default values for PlayGround and world related to it.
from SearchAlgoPlayground import PlayGround
from SearchAlgoPlayground import config
from SearchAlgoPlayground.config import YELLOW,PURPLE
config["BACKGROUND_COLOR"] = YELLOW #set background color as yellow
config["NODE_COLOR"] = PURPLE #set node color as purple
#A weighted playground with a name of the file where work need to be saved given as MyWork.json
#block_dimension is dimension of 2D matrix (rows,cols) here both are 20
pg = PlayGround(saveToFile = "MyWork.json",weighted=True,blocks_dimension=(20,20))
pg.run() #run the playground
Below are the given default values, or look into the file config.py
config = {
"TITLE":"Algo PlayGround", #Title of the playground window
"BLOCKS_DIMENSION":(21,23), #ROWS,COLUMNS
"BLOCK_SIZE":30, #Size of each block i.e. sides
"BOTTOM_PANEL_HEIGHT":200, #Size of bottom panel for control
"MARGIN":15, #Margin between sides and the grid
"GRID_WIDTH":1, #Width of the boundary of the block
"BACKGROUND_COLOR":WHITE, #Color of the background of the world
"GRID_COLOR":GRAY, #Block boundary color
"HIGHLIGHT_COLOR":DARK_GRAY, #Highlighting color
"BUTTON_COLOR_PRIMARY":BROWN, #Color for the button larger
"BUTTON_COLOR_SECONDARY": PURPLE, #color for the smaller button
"INFO_LABEL_COLOR":DARK_GRAY, #color for the info text
"NODE_COLOR":GRAY, #color of the node
"NODE_BORDER_COLOR":BLACK, #color of the border of node
"SPECIAL_NODE_BORDER_COLOR": DARK_PURPLE,#Special node border color
"SPECIAL_NODE_COLOR":GREEN, #special node color
"SELECTED_NODE_COLOR" : RED, #color of the node selected
"ELEMENT_ACTIVE_COLOR":BLUE, #Element selected by user is considered as active to the playground
"MY_WORK_DIR": "MyGraph/" #Directory in which the work is saved
}
Working with neighbouring nodes:
Parameter used: saveToFile, weighted, block_dimensions
Method used: onStart(), getStartNode(), MoveGen(), get_edge(),get_weight(), get_label()
from SearchAlgoPlayground import PlayGround
#A weighted playground with a name of the file where work need to be saved given as MyWork.json
#block_dimension is dimension of 2D matrix (rows,cols) here both are 20
pg = PlayGround(saveToFile = "MyWork.json",weighted=True,blocks_dimension=(20,20))
#Function prints all the neighbouring nodes of the start node in the playground and the weight of the edge connecteding them
def printNeighbours():
S = pg.getStartNode() #get start node from playground
#MoveGen method returns the neighbouring nodes
neighbours = pg.MoveGen(S) #Generating the neighbouring nodes
#print details of the node
for node in neighbours:
#get weight of the edge between S and node
edge = pg.get_edge(S,node) #method will return Edge class object
weight = edge.get_weight() #method in Edge class will return weight of the edge
#Display the details
print("Edge: {} - {}, Weight: {}".format(S.get_label(),node.get_label(),weight))
pg.onStart(printNeighbours) #Setting method for on start click
pg.run() #run the playground
Above prints value for the following graph
Edge: S - A, Weight: 17
Edge: S - B, Weight: 34
Edge: S - C, Weight: 10
here.
Check more implemented examples
Documentation
Classes
PlayGround
PlayGround class represents the ground which which consists of the world of blocks on which the graph is displayed or modified. PlayGround class provide controls on the elements in the world like Edge and Nodes.
Parameters
world, saveToFile, weighted, startNode, goalNode, block_dimensions, block_size
A World class object on which the nodes/edges are drawn The screen size of the world determines the screensize of the playground window (default None). world : World
name of the file with which the world(or graph) will be saved(file will be saved in json format) when the 'Save Work' button is pressed (default None). saveToFile : str
whether the edges that will be drawn on playround is weighted or not (default False). weighted : bool
a node object of Node class which will be set as start node for the graph. if no value is provided then top left block contains the start node 'S' startNode : Node
NOTE: startNode is a special node which cannot be deleted from the playground(default None)
a node object of Node class which will be set as start node for the graph. if no value is provided then bottom right block contains the goal node 'G' goalNode : Node
NOTE: goalNode is a special node which cannot be deleted from the playground(default None)
blocks_dimension represents number of blocks that will be generated in the world if world object is given as None(default (23,21)) blocks_dimension : tuple
e.g (23,21) represents 23 rows and 21 columns
size of each block i.e. one side of the squared block (default 30) block_size : int
Attribute
World class object on which playground is available world: World
Methods
fromfilename(), addUIElement(), removeUIElement(), onStart(), delay(),getAllNodes(),getAllEges(), MoveGen(), get_edge(), getGoalNode(), getStartNode(), setGoalNode(), setStartNode(), getScreen(), add_node(), add_edge(), remove_edge(), remove_node(), saveWork(), showInfoText(),get_dimension(), to_dict()
a classmethod which returns PlayGround class object initialised from values given in filename and returns the object fromfilename(filename:str)
filename: a json file name to which previously a playround is saved into
Adds UI element to the playground addUIElement(element)
NOTE: any UI element must contain draw() method which takes pygame screen as a parameter, the method will be called each time frame is drawn
Removes UI element from the playground removeUIElement(element)
Sets function to be executed when the start button is clicked onStart(func)
func: function which will be executed when start is pressed
Delays the program for given milliseconds delay(millisecond:int)
Uses pygame.time.delay method
Once the controls are taken away no other control would work on playground except exit
NOTE: Using this delay function would allow to reflect changes on playground in delay mode better than instantaneous
Returns all the neighbours(in sorted order according to the label) of a node i.e. all the nodes which has edge between the given node MoveGen(node:Node)
node: A Node class object
Returns an Edge class object between the node nodeStart and nodeEnd, if no edge exists returns None nodeStart: A Node class object get_edge(nodeStart:Node,nodeEnd:Node)->Edge
nodeEnd: A Node class object
Returns all nodes available in the world as a list getAllNodes()->list
Returns list of all edges available in world getAllEdges()->list
Returns Node class object which is currenty set as a goal node for the playground getGoalNode()->Node
Returns Node class object which is currenty set as a start node for the playground getSartNode()->Node
Sets the given node as goal node for the PlayGround node: A Node class object setGoalNode(node:Node)
Sets the given node as goal node for the PlayGround setStartNode(node:Node)
node: A Node class object
Returns a pygame window object which is the surface on which the elements are being drawn getScreen()
Useful in case more extra elements are needed to be drawn on the playground
Adds node to the world add_node(node: Node)
NOTE: node available in the world will be displayed on the playground screen
Adds edge to the world add_edge(edge: Edge)
NOTE: edge available in the world will be displayed on the playground screen
Removes edge from the world remove_edge(edge:Edge)
Removed node from the world remove_node(node:Node)
Saves the playground with the given filename. if no filename is provided, then playground will be saved with arbitrary filename saveWork(filename:str=None)
To display informational texts on the playground right above the start button showInfoText(text:str)
text: text to be displayed on the playground infoText area
Returns Playrgound attributes as dictionary to_dict()->dict
Sets the title of the playground window setTitle(title:str)
title: a string value
runs the playground as an active window on which the frames are drawn run()
World
A World class represents the world for the playground which is responsible for Maintaining Node,Edge and Block of the playground
Parameters
blocks_dimension, block_size, bottom_panel_size, grid_width, background_color, gird_color, margin
blocks_dimension represents number of blocks that will be generated in the world e.g (23,21) represents 23 rows and 21 columns blocks_dimension:tuple
size of each block i.e. one side of the squared block block_size:int
height of the bottom panel on which buttons and other UI element will be drawn min allowed 180 bottom_panel_size:int
Width of the grids grid_width:int
A rgb value type of the form (r,g,b) to set color for the background of the world default (255,255,255) background_color:tuple
A rgb value type of the form (r,g,b) to set color for the blocks border of the world default (232, 232, 232) gird_color:tuple
Margin from the edges of the playground window, minimum value allowed is 10, default 10 margin:int
Methods
fromdict(), create_grids(), add_node(), remove_node(), update_node_loc(), getEdges(), add_edge(), remove_edge(), getNodes(), getNode(), getBlock(), get_dimension(), to_dict()
A classmethod to create World class object from a dictionary fromdict(datadict:dict)
NOTE:The dictionary must be of the same form returned by to_dict() method of the class
Generates grids if not generated in the world, if the gird is already availbale then it redraws them create_grids()
Adds nodes to the world add_node(node:Node)
NOTE: To make the node visible on playground window it must be include in the world
Removes nodes from the world remove_node(node:Node)
NOTE: If nodes are not available in the world it will no longer visible on playground window
Updates the location of the node to newBlock location and removes it from previous block. node:Node - A Node class object which needs to be updated newBlock:Block - A Block class object to which the node is require to move to update_node_loc(node:Node,newBlock:Block)
Returns all the available edges in the world as dictionary with key as the node pairs ids e.g ((1,1),(1,5)) is the key for an edge between the node with id (1,1) and (1,5) getEdges()->dict
NOTE: The id represents position in the 2D matrix of the block
Adds edge to the world, edge added to the world will be visible on Playground window add_edge(e:Edge)
NOTE: Edges are added with the key of the end node ids e.g. ((1,1),(1,5)) is the key for an edge between the node with id (1,1) and (1,5)
Removes the edge from the world. The edge removed from the world will no longer be visible on the Playground window remove_edge(e:Edge)
Returns edge between startNodeID and endNodeID if there exists an edge else returns None startNodeID:tuple - id of the node which has edge with the other node we're looking for endNodeID:tuple - id of the node which has edge with the other node we're looking for getEdge(startNodeID:tuple,endNodeID:tuple)->Edge
Returns the dictionary of all the nodes available in the world Key of is the id of the node getNodes()->dict
Returns node with given key, returns None if the node doesn't exists _key:tuple _- id of the node we are looking for, location in the grid or 2D array. getNode(key:tuple)->Node
Returns block at the given id. id:tuple - Index Location in 2D matrix getBlock(id)->Block
Returns dimension of the world as tuple of (rows,col) get_dimension()->tuple
returns the object details with all attribute and values as dictionary to_dict()->dict
Block
Block defines the world tiles. Blocks represents the world in 2-Dimensional array format.
Attribute
x coordinate in the window plane of the block x:int
y coordinate in the window plane of the block y:int
size of the block, denotes one side of the square block size:int
id represents position in the 2D matrix of the block (x,y) where x is the row and y is the column id:tuple
pygame rect object pgObj
Parameters
x, y, size, id, gird_color, grid_width
x coordinate in the window plane of the block x:int
y coordinate in the window plane of the block y:int
size of the block, denotes one side of the square block size:int
id represents position in the 2D matrix of the block (x,y) where x is the row and y is the column id:tuple
rgb color (r,g,b) value for the block boundary default ((163, 175, 204)) gird_color:tuple
width of the boundary default 1 grid_width:int
Methods
draw_block(), highlight(), pos(), setHasNode(), hasNode(), to_dict()
draws the block on pygame window screen: pygame window draw_block(screen)
highlights block with highlist color val:bool - true to enable highlight highlight(val:bool)
returns the coordinate of the centre of the block on the pygame window pos() -> tuple
sets the value for the flag _hasNode to represent that a block contains a node setHasNode(val:bool)
returns true if block has node over it hasNode()->bool
returns the object details with all attribute and values as dictionary to_dict()->dict
Node
A node is a type of block that is important to the world Node class inherits the Block class.
Parameters
block, label, colorOutline, colorNode, outlineWidth, specialNodeStatus
A Block class object on which the node will be drawn block:Block
Label of the node label:str
A rgb value of the form (r,g,b) represents outline color of the node colorOutline:tuple
A rgb value of the form (r,g,b) represents color of the node colorNode:tuple
Width of the outline of the node default 2 outlineWidth:int
sets whether the node is special default is False specialNodeStatus:bool
NOTE: A special node must be present on playground all time, i.e. delete is not allowed
Attributes
x coordinate in the window plane of the block x:int
y coordinate in the window plane of the block y:int
size of the block, denotes one side of the square block size:int
id represents position in the 2D matrix of the block (x,y) where x is the row and y is the column id:tuple
pygame rect object pgObj
coordinate in pygame window for center of the node pos:tuple
Methods
draw_block(), highlight(), pos(), setHasNode(), hasNode(), to_dict(), set_label(), selected(), set_color(), get_label(), setLocation(), handle_event(), add_neighbour(), remove_neighbour(), get_neighbours()
draws the node on pygame window screen: pygame window draw_block(screen)
highlights block with highlist color val:bool - true to enable highlight highlight(val:bool)
returns the coordinate of the centre of the block on the pygame window pos() -> tuple
sets the value for the flag _hasNode to represent that a block contains a node setHasNode(val:bool)
returns true if block has node over it hasNode()->bool
returns the object details with all attribute and values as dictionary to_dict()->dict
sets the label on the node screen - a pygame window set_label(label:str,screen)
label:str - a string value that'll be displayed on node
sets isSelected flag value selected(val:bool)
sets the color of the node set_color(color:tuple)
color:tuple - A rgb value in the form (r,g,b)
returns value of label of the node get_label()->str
sets the location to the new block block:Block - A Block class object setLocation(block:Block)
NOTE: Location for nodes are defined by the block they resides on
Internal method to handle the pygame events handle_event(world:World,event,infoLabel)
Adds the given node as neighbouring node if it's not already a neighbouring node, should be used when it has an edge with the given node add_neighbour(node:Node)
node:Node - A Node class object
Removes the given node from neighbouring node if it's in neighbouring node node:Node - A Node class object remove_neighbour(node:Node)
Returns list of neighbouring nodes(Node class objects) which is sorted in order with their label get_neighbour()->list
Edge
An edge class represents an edge between 2 nodes
Parameters
nodeStart, nodeEnd, isWeighted, weight, edgeColor, edgeWidth,
A Node class object which represents the starting node of the edge nodeStart:Node
A Node class object which represents the ending node of the edge nodeEnd:Node
Whether the edge drawn between the node has weight or not, default False isWeighted:bool
Wieght of the edge, default 0 weight:int
A rgb value of the form (r,g,b) which represents the color of the edge, default value NODE_BORDER_COLOR edgeColor:tuple
Width of the edge, default 3 edgeWidth:int
Attribute
A pygame rect object pgObj
Methods
handle_event(), set_color(), collidePoint(), draw_edge(), getNodes(), get_weight(), to_dict()
Internal method to handle the pygame events handle_event(world:World,event,infoLabel)
Sets color of the edge color:tuple - A rgb value of the form (r,g,b) set_color(color:tuple)
Returns true if the given click point is inside the offset value on edge collidePoint(clickPoint,offeset=5)
Draws edge on the screen screen - A pygame window draw_edge(screen)
Returns the pair of node which the edge is connecting getNodes()->tuple
Returns the weight of the edge get_weight()->int
Returns the object details its attributes and value as dictionary to_dict()->dict
UI Module
Label
Label to add on pygame screens
Methods
Draws the label on the pygame screen screen: pygame screen draw(screen)
Set the value for label setValue(text:str)
Parameters
color of the label in (r,g,b) format color:tuple
size of the label size:int
(x,y) coordinates for the position of label pos:tuple
Button
Button elements for pygame screen
Method
draws button element on pygame screen screen: pygame window draw_button(screen)
Returns true if pos is a collidePos for the pygame rect element isClicked(pos)
Parameters
pos, size, bgColor, color, label, labelSize, fill_value,
(x,y) coordinates for the position of button pos:tuple
(width,height) of the button size:tuple
background color for the button bgColor:tuple
color of the button label color:tuple
label of the button label:str
size of the label labelSize:int