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.
Project description
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
Check more implemented examples here.
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
world : World
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).saveToFile : str
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).weighted : bool
whether the edges that will be drawn on playround is weighted or not (default False).startNode : Node
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'NOTE: startNode is a special node which cannot be deleted from the playground(default None)
goalNode : Node
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'NOTE: goalNode is a special node which cannot be deleted from the playground(default None)
blocks_dimension : tuple
blocks_dimension represents number of blocks that will be generated in the world if world object is given as None(default (23,21))e.g (23,21) represents 23 rows and 21 columns
block_size : int
size of each block i.e. one side of the squared block (default 30)Attribute
world: World
World class object on which playground is availableMethods
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()
fromfilename(filename:str)
a classmethod which returns PlayGround class object initialised from values given in filename and returns the objectfilename: a json file name to which previously a playround is saved into
addUIElement(element)
Adds UI element to the playgroundNOTE: any UI element must contain draw() method which takes pygame screen as a parameter, the method will be called each time frame is drawn
removeUIElement(element)
Removes UI element from the playgroundonStart(func)
Sets function to be executed when the start button is clickedfunc: function which will be executed when start is pressed
delay(millisecond:int)
Delays the program for given millisecondsUses 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
MoveGen(node:Node)
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 nodenode: A Node class object
get_edge(nodeStart:Node,nodeEnd:Node)->Edge
Returns an Edge class object between the node nodeStart and nodeEnd, if no edge exists returns None nodeStart: A Node class objectnodeEnd: A Node class object
getAllNodes()->list
Returns all nodes available in the world as a listgetAllEdges()->list
Returns list of all edges available in worldgetGoalNode()->Node
Returns Node class object which is currenty set as a goal node for the playgroundgetSartNode()->Node
Returns Node class object which is currenty set as a start node for the playgroundsetGoalNode(node:Node)
Sets the given node as goal node for the PlayGround node: A Node class objectsetStartNode(node:Node)
Sets the given node as goal node for the PlayGroundnode: A Node class object
getScreen()
Returns a pygame window object which is the surface on which the elements are being drawnUseful in case more extra elements are needed to be drawn on the playground
add_node(node: Node)
Adds node to the worldNOTE: node available in the world will be displayed on the playground screen
add_edge(edge: Edge)
Adds edge to the worldNOTE: edge available in the world will be displayed on the playground screen
remove_edge(edge:Edge)
Removes edge from the worldremove_node(node:Node)
Removed node from the worldsaveWork(filename:str=None)
Saves the playground with the given filename. if no filename is provided, then playground will be saved with arbitrary filenameshowInfoText(text:str)
To display informational texts on the playground right above the start buttontext: text to be displayed on the playground infoText area
to_dict()->dict
Returns Playrgound attributes as dictionarysetTitle(title:str)
Sets the title of the playground windowtitle: a string value
run()
runs the playground as an active window on which the frames are drawnWorld
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:tuple
blocks_dimension represents number of blocks that will be generated in the world e.g (23,21) represents 23 rows and 21 columnsblock_size:int
size of each block i.e. one side of the squared blockbottom_panel_size:int
height of the bottom panel on which buttons and other UI element will be drawn min allowed 180grid_width:int
Width of the gridsbackground_color:tuple
A rgb value type of the form (r,g,b) to set color for the background of the world default (255,255,255)gird_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)margin:int
Margin from the edges of the playground window, minimum value allowed is 10, default 10Methods
fromdict(), create_grids(), add_node(), remove_node(), update_node_loc(), getEdges(), add_edge(), remove_edge(), getNodes(), getNode(), getBlock(), get_dimension(), to_dict()
fromdict(datadict:dict)
A classmethod to create World class object from a dictionaryNOTE:The dictionary must be of the same form returned by to_dict() method of the class
create_grids()
Generates grids if not generated in the world, if the gird is already availbale then it redraws themadd_node(node:Node)
Adds nodes to the worldNOTE: To make the node visible on playground window it must be include in the world
remove_node(node:Node)
Removes nodes from the worldNOTE: If nodes are not available in the world it will no longer visible on playground window
update_node_loc(node:Node,newBlock:Block)
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 togetEdges()->dict
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)NOTE: The id represents position in the 2D matrix of the block
add_edge(e:Edge)
Adds edge to the world, edge added to the world will be visible on Playground windowNOTE: 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)
remove_edge(e:Edge)
Removes the edge from the world. The edge removed from the world will no longer be visible on the Playground windowgetEdge(startNodeID:tuple,endNodeID:tuple)->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 forgetNodes()->dict
Returns the dictionary of all the nodes available in the world Key of is the id of the nodegetNode(key:tuple)->Node
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.getBlock(id)->Block
Returns block at the given id. id:tuple - Index Location in 2D matrixget_dimension()->tuple
Returns dimension of the world as tuple of (rows,col)to_dict()->dict
returns the object details with all attribute and values as dictionaryBlock
Block defines the world tiles. Blocks represents the world in 2-Dimensional array format.
Attribute
x:int
x coordinate in the window plane of the blocky:int
y coordinate in the window plane of the blocksize:int
size of the block, denotes one side of the square blockid:tuple
id represents position in the 2D matrix of the block (x,y) where x is the row and y is the columnpgObj
pygame rect objectParameters
x, y, size, id, gird_color, grid_width
x:int
x coordinate in the window plane of the blocky:int
y coordinate in the window plane of the blocksize:int
size of the block, denotes one side of the square blockid:tuple
id represents position in the 2D matrix of the block (x,y) where x is the row and y is the columngird_color:tuple
rgb color (r,g,b) value for the block boundary default ((163, 175, 204))grid_width:int
width of the boundary default 1Methods
draw_block(), highlight(), pos(), setHasNode(), hasNode(), to_dict()
draw_block(screen)
draws the block on pygame window screen: pygame windowhighlight(val:bool)
highlights block with highlist color val:bool - true to enable highlightpos() -> tuple
returns the coordinate of the centre of the block on the pygame windowsetHasNode(val:bool)
sets the value for the flag _hasNode to represent that a block contains a nodehasNode()->bool
returns true if block has node over itto_dict()->dict
returns the object details with all attribute and values as dictionaryNode
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
block:Block
A Block class object on which the node will be drawnlabel:str
Label of the nodecolorOutline:tuple
A rgb value of the form (r,g,b) represents outline color of the nodecolorNode:tuple
A rgb value of the form (r,g,b) represents color of the nodeoutlineWidth:int
Width of the outline of the node default 2specialNodeStatus:bool
sets whether the node is special default is FalseNOTE: A special node must be present on playground all time, i.e. delete is not allowed
Attributes
x:int
x coordinate in the window plane of the blocky:int
y coordinate in the window plane of the blocksize:int
size of the block, denotes one side of the square blockid:tuple
id represents position in the 2D matrix of the block (x,y) where x is the row and y is the columnpgObj
pygame rect objectpos:tuple
coordinate in pygame window for center of the nodeMethods
draw_block(), highlight(), pos(), setHasNode(), hasNode(), to_dict(), set_label(), selected(), set_color(), get_label(), setLocation(), handle_event(), add_neighbour(), remove_neighbour(), get_neighbours()
draw_block(screen)
draws the node on pygame window screen: pygame windowhighlight(val:bool)
highlights block with highlist color val:bool - true to enable highlightpos() -> tuple
returns the coordinate of the centre of the block on the pygame windowsetHasNode(val:bool)
sets the value for the flag _hasNode to represent that a block contains a nodehasNode()->bool
returns true if block has node over itto_dict()->dict
returns the object details with all attribute and values as dictionaryset_label(label:str,screen)
sets the label on the node screen - a pygame windowlabel:str - a string value that'll be displayed on node
selected(val:bool)
sets isSelected flag valueset_color(color:tuple)
sets the color of the nodecolor:tuple - A rgb value in the form (r,g,b)
get_label()->str
returns value of label of the nodesetLocation(block:Block)
sets the location to the new block block:Block - A Block class objectNOTE: Location for nodes are defined by the block they resides on
handle_event(world:World,event,infoLabel)
Internal method to handle the pygame eventsadd_neighbour(node:Node)
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 nodenode:Node - A Node class object
remove_neighbour(node:Node)
Removes the given node from neighbouring node if it's in neighbouring node node:Node - A Node class objectget_neighbour()->list
Returns list of neighbouring nodes(Node class objects) which is sorted in order with their labelEdge
An edge class represents an edge between 2 nodes
Parameters
nodeStart, nodeEnd, isWeighted, weight, edgeColor, edgeWidth,
nodeStart:Node
A Node class object which represents the starting node of the edgenodeEnd:Node
A Node class object which represents the ending node of the edgeisWeighted:bool
Whether the edge drawn between the node has weight or not, default Falseweight:int
Wieght of the edge, default 0edgeColor:tuple
A rgb value of the form (r,g,b) which represents the color of the edge, default value NODE_BORDER_COLORedgeWidth:int
Width of the edge, default 3Attribute
pgObj
A pygame rect objectMethods
handle_event(), set_color(), collidePoint(), draw_edge(), getNodes(), get_weight(), to_dict()
handle_event(world:World,event,infoLabel)
Internal method to handle the pygame eventsset_color(color:tuple)
Sets color of the edge color:tuple - A rgb value of the form (r,g,b)collidePoint(clickPoint,offeset=5)
Returns true if the given click point is inside the offset value on edgedraw_edge(screen)
Draws edge on the screen screen - A pygame windowgetNodes()->tuple
Returns the pair of node which the edge is connectingget_weight()->int
Returns the weight of the edgeto_dict()->dict
Returns the object details its attributes and value as dictionaryUI Module
Label
Label to add on pygame screens
Methods
draw(screen)
Draws the label on the pygame screen screen: pygame screensetValue(text:str)
Set the value for labelParameters
color:tuple
color of the label in (r,g,b) formatsize:int
size of the labelpos:tuple
(x,y) coordinates for the position of labelButton
Button elements for pygame screen
Method
draw_button(screen)
draws button element on pygame screen screen: pygame windowisClicked(pos)
Returns true if pos is a collidePos for the pygame rect elementParameters
pos, size, bgColor, color, label, labelSize, fill_value,
pos:tuple
(x,y) coordinates for the position of buttonsize:tuple
(width,height) of the buttonbgColor:tuple
background color for the buttoncolor:tuple
color of the button labellabel:str
label of the buttonlabelSize:int
size of the labelfill_value:int
fill value for pygame rectProject details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file SearchAlgoPlayground-1.0.0.tar.gz
.
File metadata
- Download URL: SearchAlgoPlayground-1.0.0.tar.gz
- Upload date:
- Size: 99.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.6.4 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.6.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 23aac5ffc7baf7f041d0b9231763d11c312df51da329c4b7daf08e12e84092e4 |
|
MD5 | cf84afb3802443e571370eaf7c18fdf8 |
|
BLAKE2b-256 | 8a9ea868592cbd409493f7c9247c65484f12f1c7ae24dc746df208168e849a9d |
File details
Details for the file SearchAlgoPlayground-1.0.0-py3-none-any.whl
.
File metadata
- Download URL: SearchAlgoPlayground-1.0.0-py3-none-any.whl
- Upload date:
- Size: 85.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.6.4 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.6.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 189d30cc38d873ac46449541d60f06e12c0f135b5c45748e57e6154151fc5ee6 |
|
MD5 | 1fffc7fd4900b2756785352bbcf3c831 |
|
BLAKE2b-256 | edb657893ba5e30b955c9a0b8657e8f5c4d447dd1e7267e646300c8a2ddca8be |