Skip to content

Search Algorithm Playground is a python package to work with graph related algorithm, mainly dealing with different Artificial Intelligence Search algorithms. 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 wa…

License

Notifications You must be signed in to change notification settings

sritabh/SearchAlgorithmPlayground

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

95 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Search Algorithm Playground

Search Algorithm Playground is a python package to work with graph related algorithm, mainly dealing with different Artificial Intelligence Search algorithms. 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


AStarAlgoResult


License: MPL 2.0 Python 3.6


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.


NodeCreate


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.

EdgeCreate


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

EdgeDelete

To edit an edge weight double click and use keyboard to modify it's value, once done hit ENTER or click anywhere else.

EdgeWeightEdit

To delete a node double click on it and then hit DELETE on keyboard

DeleteNodeWithEdge

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

EditNodeLabel


Move nodes on the playground

Click on the node and drag it on the playground.

NodeDrag


Basic Use:

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

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

World class object on which playground is available

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()

fromfilename(filename:str)

a classmethod which returns PlayGround class object initialised from values given in filename and returns the object
filename: a json file name to which previously a playround is saved into

addUIElement(element)

Adds UI element to the playground
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

removeUIElement(element)

Removes UI element from the playground

onStart(func)

Sets function to be executed when the start button is clicked
func: function which will be executed when start is pressed

delay(millisecond:int)

Delays the program for given milliseconds
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

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 node
node: 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 object
nodeEnd: A Node class object

getAllNodes()->list

Returns all nodes available in the world as a list

getAllEdges()->list

Returns list of all edges available in world

getGoalNode()->Node

Returns Node class object which is currenty set as a goal node for the playground

getSartNode()->Node

Returns Node class object which is currenty set as a start node for the playground

setGoalNode(node:Node)

Sets the given node as goal node for the PlayGround node: A Node class object

setStartNode(node:Node)

Sets the given node as goal node for the PlayGround
node: A Node class object

getScreen()

Returns a pygame window object which is the surface on which the elements are being drawn
Useful in case more extra elements are needed to be drawn on the playground

add_node(node: Node)

Adds node to the world
NOTE: node available in the world will be displayed on the playground screen

add_edge(edge: Edge)

Adds edge to the world
NOTE: edge available in the world will be displayed on the playground screen

remove_edge(edge:Edge)

Removes edge from the world

remove_node(node:Node)

Removed node from the world

saveWork(filename:str=None)

Saves the playground with the given filename. if no filename is provided, then playground will be saved with arbitrary filename

showInfoText(text:str)

To display informational texts on the playground right above the start button
text: text to be displayed on the playground infoText area

to_dict()->dict

Returns Playrgound attributes as dictionary

setTitle(title:str)

Sets the title of the playground window
title: a string value

run()

runs the playground as an active window on which the frames are drawn


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:tuple

blocks_dimension represents number of blocks that will be generated in the world 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

bottom_panel_size:int

height of the bottom panel on which buttons and other UI element will be drawn min allowed 180

grid_width:int

Width of the grids

background_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 10

Methods

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 dictionary
NOTE: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 them

add_node(node:Node)

Adds nodes to the world
NOTE: To make the node visible on playground window it must be include in the world

remove_node(node:Node)

Removes nodes from the world
NOTE: 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 to

getEdges()->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 window
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)

remove_edge(e:Edge)

Removes the edge from the world. The edge removed from the world will no longer be visible on the Playground window

getEdge(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 for

getNodes()->dict

Returns the dictionary of all the nodes available in the world Key of is the id of the node

getNode(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 matrix

get_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 dictionary


Block

Block defines the world tiles. Blocks represents the world in 2-Dimensional array format.

Attribute

x, y, size, id, pgObj

x:int

x coordinate in the window plane of the block

y:int

y coordinate in the window plane of the block

size:int

size of the block, denotes one side of the square block

id:tuple

id represents position in the 2D matrix of the block (x,y) where x is the row and y is the column

pgObj

pygame rect object

Parameters

x, y, size, id, gird_color, grid_width

x:int

x coordinate in the window plane of the block

y:int

y coordinate in the window plane of the block

size:int

size of the block, denotes one side of the square block

id:tuple

id represents position in the 2D matrix of the block (x,y) where x is the row and y is the column

gird_color:tuple

rgb color (r,g,b) value for the block boundary default ((163, 175, 204))

grid_width:int

width of the boundary default 1

Methods

draw_block(), highlight(), pos(), setHasNode(), hasNode(), to_dict()

draw_block(screen)

draws the block on pygame window screen: pygame window

highlight(val:bool)

highlights block with highlist color val:bool - true to enable highlight

pos() -> tuple

returns the coordinate of the centre of the block on the pygame window

setHasNode(val:bool)

sets the value for the flag _hasNode to represent that a block contains a node

hasNode()->bool

returns true if block has node over it

to_dict()->dict

returns the object details with all attribute and values as dictionary


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

block:Block

A Block class object on which the node will be drawn

label:str

Label of the node

colorOutline:tuple

A rgb value of the form (r,g,b) represents outline color of the node

colorNode:tuple

A rgb value of the form (r,g,b) represents color of the node

outlineWidth:int

Width of the outline of the node default 2

specialNodeStatus:bool

sets whether the node is special default is False
NOTE: A special node must be present on playground all time, i.e. delete is not allowed

Attributes

x, y, size, id, pgObj, pos

x:int

x coordinate in the window plane of the block

y:int

y coordinate in the window plane of the block

size:int

size of the block, denotes one side of the square block

id:tuple

id represents position in the 2D matrix of the block (x,y) where x is the row and y is the column

pgObj

pygame rect object

pos:tuple

coordinate in pygame window for center of the node

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()

draw_block(screen)

draws the node on pygame window screen: pygame window

highlight(val:bool)

highlights block with highlist color val:bool - true to enable highlight

pos() -> tuple

returns the coordinate of the centre of the block on the pygame window

setHasNode(val:bool)

sets the value for the flag _hasNode to represent that a block contains a node

hasNode()->bool

returns true if block has node over it

to_dict()->dict

returns the object details with all attribute and values as dictionary

set_label(label:str,screen)

sets the label on the node screen - a pygame window
label:str - a string value that'll be displayed on node

selected(val:bool)

sets isSelected flag value

set_color(color:tuple)

sets the color of the node
color:tuple - A rgb value in the form (r,g,b)

get_label()->str

returns value of label of the node

setLocation(block:Block)

sets the location to the new block block:Block - A Block class object
NOTE: Location for nodes are defined by the block they resides on

handle_event(world:World,event,infoLabel)

Internal method to handle the pygame events

add_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 node
node: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 object

get_neighbour()->list

Returns list of neighbouring nodes(Node class objects) which is sorted in order with their label


Edge

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 edge

nodeEnd:Node

A Node class object which represents the ending node of the edge

isWeighted:bool

Whether the edge drawn between the node has weight or not, default False

weight:int

Wieght of the edge, default 0

edgeColor:tuple

A rgb value of the form (r,g,b) which represents the color of the edge, default value NODE_BORDER_COLOR

edgeWidth:int

Width of the edge, default 3

Attribute

pgObj

pgObj

A pygame rect object

Methods

handle_event(), set_color(), collidePoint(), draw_edge(), getNodes(), get_weight(), to_dict()

handle_event(world:World,event,infoLabel)

Internal method to handle the pygame events

set_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 edge

draw_edge(screen)

Draws edge on the screen screen - A pygame window

getNodes()->tuple

Returns the pair of node which the edge is connecting

get_weight()->int

Returns the weight of the edge

to_dict()->dict

Returns the object details its attributes and value as dictionary


UI Module

Label

Label to add on pygame screens

Methods

draw(), setValue()

draw(screen)

Draws the label on the pygame screen screen: pygame screen

setValue(text:str)

Set the value for label

Parameters

color, size, pos

color:tuple

color of the label in (r,g,b) format

size:int

size of the label

pos:tuple

(x,y) coordinates for the position of label


Button

Button elements for pygame screen

Method

draw_button(), isClicked()

draw_button(screen)

draws button element on pygame screen screen: pygame window

isClicked(pos)

Returns true if pos is a collidePos for the pygame rect element

Parameters

pos, size, bgColor, color, label, labelSize, fill_value,

pos:tuple

(x,y) coordinates for the position of button

size:tuple

(width,height) of the button

bgColor:tuple

background color for the button

color:tuple

color of the button label

label:str

label of the button

labelSize:int

size of the label

fill_value:int

fill value for pygame rect


About

Search Algorithm Playground is a python package to work with graph related algorithm, mainly dealing with different Artificial Intelligence Search algorithms. 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 wa…

Resources

License

Stars

Watchers

Forks

Languages