Skip to content
Snippets Groups Projects
Commit 982d6aba authored by Balaji D's avatar Balaji D :blush:
Browse files

Main

parents
No related branches found
No related tags found
No related merge requests found
File added
app1.py 0 → 100644
from flask import Flask, send_file, url_for,render_template, flash, request, redirect
from flask import *
import graphs
import os
import time
from mako.template import Template
app = Flask(__name__)
app.secret_key = "abc"
ALLOWED_EXTENSIONS = {'txt'}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods = ['POST','GET'])
def page0():
if request.method == 'POST':
f = request.files['file']
f.save(f.filename)
return render_template('index.html')
@app.route('/processing', methods = ['POST'])
def success():
if request.method == 'POST':
f = request.files['file']
if allowed_file(f.filename):
if(request.files['file']):
f.save(f.filename)
flash("File Uploaded Sucessfully")
return render_template('index2.html')
else:
flash("Problem in File uploading")
return render_template('index.html')
@app.route('/p2', methods = ['POST'])
def v1():
if request.method == 'POST':
n = request.form['nodes']
v = request.form['val']
s = request.form['sourse']
graphs.adjacency(n,v,s)
return render_template('index1.html')
else:
return render_template('index.html')
@app.route('/page2')
def page2():
return send_file('usergraph.png', mimetype='image/png')
@app.route('/image2')
def image2():
return send_file('slowgif.gif', mimetype='image/gif')
@app.route('/page1')
def page1():
graphs.showgraph()
return send_file('graphfinal.png', mimetype='image/png')
@app.route('/image1')
def image1():
graphs.printgraph()
return send_file('slowgif.gif', mimetype='image/gif')
@app.route('/image3')
def image3():
graphs.bfsprintgraph()
return send_file('slowbfs.gif', mimetype='image/gif')
@app.route('/About')
def about():
return render_template('about.html')
@app.route('/table')
def table():
rows=graphs.useradj()
template = """
<table>
% for row in rows:
<tr>
% for cell in row:
<td>${cell}</td>
% endfor
</tr>
% endfor
</table>
"""
x=Template(template).render(rows=rows)
return render_template('table.html',rows=rows)
if __name__ == "__main__":
app.run(debug=True)
bfs.png 0 → 100644
bfs.png

29.6 KiB

graphfinal.png

23.4 KiB

graphs.py 0 → 100644
import networkx as nx
import matplotlib.pyplot as plt
class Graph:
def __init__(self,numvertex):
self.adjMatrix = [[0]*numvertex for x in range(numvertex)]
self.numvertex = numvertex
self.vertices = {}
self.verticeslist =[0]*numvertex
def set_vertex(self,vtx):
id=vtx
if 0<=vtx<=self.numvertex:
self.vertices[id] = vtx
self.verticeslist[vtx] = id
def set_edge(self,frm,to,cost=0):
frm = self.vertices[frm]
to = self.vertices[to]
self.adjMatrix[frm][to] = cost
#for directed graph do not add this
#self.adjMatrix[to][frm] = cost
def get_vertex(self):
return self.verticeslist
def get_edges(self):
edges=[]
for i in range (self.numvertex):
for j in range (self.numvertex):
if (self.adjMatrix[i][j]!=0):
edges.append((self.verticeslist[i],self.verticeslist[j],self.adjMatrix[i][j]))
return edges
def get_matrix(self):
return self.adjMatrix
#utility fucntion used by DFS which does recursive depth first search
def DFSUtil(G, v, visited, sl): #goes to the node and iteratively checks if it is visited or not
visited[v] = True
sl.append(v)
for i in G[v]:
if visited[i] == False:
DFSUtil(G, i, visited, sl)
return sl
#DFS traversal
def DFS(G, source):
visited = [False]*(len(G.nodes()))
sl = [] #a list that stores dfs forest starting with source node
dfs_stk = [] #A nested list that stores all the DFS Forest's
dfs_stk.append(DFSUtil(G, source, visited, sl))
for i in range(len(G.nodes())):
if visited[i] == False:
sl = []
dfs_stk.append(DFSUtil(G, i, visited, sl))
return dfs_stk
#takes input from the file and creates a weighted graph
def CreateGraph():
G = nx.DiGraph()
f = open('input.txt')
n = int(f.readline())
wtMatrix = []
for i in range(n):
list1 = list(map(int, (f.readline()).split()))
wtMatrix.append(list1)
source = int(f.readline()) #source vertex from where DFS has to start
#Adds egdes along with their weights to the graph
for i in range(n):
for j in range(n):
if wtMatrix[i][j] > 0:
G.add_edge(i, j, length = wtMatrix[i][j])
return G,source
imagesbfs=[]
#BFS traversal
def BFS(G, source, pos):
# plt.clf()
imagesbfs.clear()
visited = [False]*(len(G.nodes()))
queue = [] #a queue for BFS traversal
queue.append(source)
visited[source] = True
while queue:
curr_node = queue.pop(0)
for i in G[curr_node]: #iterates through all the possible vertices adjacent to the curr_node
if visited[i] == False:
queue.append(i)
visited[i] = True
nx.draw_networkx_edges(G, pos, edgelist = [(curr_node,i)], width = 2.5, alpha = 0.6, edge_color = 'r')
plt.savefig("bfs.png")
imagesbfs.append(imageio.imread("bfs.png"))
imageio.mimsave("originalbfs.gif",imagesbfs)
gif=imageio.mimread("originalbfs.gif")
imageio.mimsave("slowbfs.gif",gif,fps=1)
return
def DrawGraphbfs(G):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
return pos
def bfsprintgraph():
plt.clf()
G, source = CreateGraph()
pos = DrawGraphbfs(G)
BFS(G, source, pos)
plt.savefig("userbfs.png")
import imageio
images=[]
#marks all edges traversed through DFS with red
def DrawDFSPath(G, dfs_stk):
plt.clf()
images.clear()
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
for i in dfs_stk:
#if there is more than one node in the dfs-forest, then print the corresponding edges
if len(i) > 1:
for j in i[ :(len(i)-1)]:
if i[i.index(j)+1] in G[j]:
nx.draw_networkx_edges(G, pos, edgelist = [(j,i[i.index(j)+1])], width = 2.5, alpha = 0.6, edge_color = 'r')
plt.savefig("orig.png")
images.append(imageio.imread("orig.png"))
else:
#if in case the path was reversed because all the possible neighbours were visited, we need to find the adj node to it.
for k in i[1::-1]:
if k in G[j]:
nx.draw_networkx_edges(G, pos, edgelist = [(j,k)], width = 2.5, alpha = 0.6, edge_color = 'r')
plt.savefig("orig.png")
images.append(imageio.imread("orig.png"))
break
#print([type(i ) for i in images])
imageio.mimsave("originalgif.gif",images)
gif=imageio.mimread("originalgif.gif")
imageio.mimsave("slowgif.gif",gif,fps=1)
# import matplotlib.animation
# ani = matplotlib.animation.FuncAnimation(G, DrawDFSPath, frames=6, interval=1000, repeat=True)
def showgraph():
plt.clf()
G1, source1 = CreateGraph()
nx.draw(G1, with_labels=True, font_weight='bold')
plt.savefig("graphfinal.png")
#main function
def printgraph():
G, source = CreateGraph()
dfs_stk = DFS(G, source)
DrawDFSPath(G, dfs_stk)
plt.savefig("orig.png")
def CreateGraph2(node,finallist):
plt.clf()
G = nx.Graph() #create a graph
for x in range(0,node):
G.add_node(x)
for x in finallist:
print(*x)
G.add_edge(x[0],x[1],length =x[2])
nx.draw(G, with_labels=True, font_weight='bold')
plt.savefig("usergraph.png")
return G
import json
adj=[]
def adjacency(nodeb,edgesb,srcb):
plt.clf()
#node=int(input("No. of nodes"))
node=int(nodeb)
source=int(srcb)
G=Graph(node)
for n in range(0,node):
G.set_vertex(n)
#edgeslist=str(input("enter [[1, 2, 3], [2, 3, 4]] format"))
finallist=json.loads(edgesb)
for x in finallist:
G.set_edge(*x)
usergraph=CreateGraph2(node,finallist)
plt.clf()
dfs_stk = DFS(usergraph, source)
print(dfs_stk)
DrawDFSPath(usergraph, dfs_stk)
plt.savefig("userdfs.png")
print(G.get_matrix())
print(G.get_edges())
print(G.get_vertex())
#bfs
global adj
adj=G.get_matrix()
def useradj():
global adj
return adj
\ No newline at end of file
4
0 5 10 5
0 0 5 0
0 10 0 0
0 0 10 0
0
\ No newline at end of file
orig.png 0 → 100644
orig.png

28.3 KiB

originalbfs.gif

107 KiB

originalgif.gif

97.6 KiB

slowbfs.gif

107 KiB

slowgif.gif

97.6 KiB

{% extends 'base.html' %}
{% block head %}
<title>About</title>
{% endblock %}
{% block body %}
<br>
<h1>About</h1>
<br>
<main role="main">
<div class="jumbotron">
<div class="col-sm-8 mx-auto">
<h1>Work by group 2</h1>
<p>Members include:</p>
<p>&nbsp;--> Akula Sudhamshu</p>
<p>&nbsp;--> Balaji D</p>
<p>&nbsp;--> Cheemalamarri V S Siddhartha</p>
<p>&nbsp;--> Ganapathi Subramanyam Jayam</p>
</div>
</div>
</main>
{% endblock %}/*
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
{% block head %} {% endblock %}
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<a class="navbar-brand" href="/">Graph Visualizer</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample01"
aria-controls="navbarsExample01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExample01">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/posts">Posts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/About">About</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">Contact Us</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a class="dropdown-item" href="https://www.cleverprogrammer.com">Website</a>
<a class="dropdown-item" href="https://www.youtube.com/channel/UCqrILQNl5Ed9Dz6CGMyvMTQ">Youtube</a>
<a class="dropdown-item" href="https://www.facebook.com/CleverProgrammerr/">Facebook</a>
<a class="dropdown-item" href="https://www.instagram.com/cleverqazi/?hl=en">Instagram</a>
</div>
</li>
</ul>
<form class="form-inline my-2 my-md-0">
<input class="form-control" type="text" placeholder="Search" aria-label="Search">
</form>
</div>
</nav>
<div class="container">
{% block body %} {% endblock %}
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
\ No newline at end of file
{% extends 'base.html' %}
{% block head %}
<title>Home</title>
{% endblock %}
{% block body %}
<br>
<h1>Home Page</h1>
<br>
<main role="main">
<div class="jumbotron">
<div class="col-sm-8 mx-auto">
<p>Welcome to our online Graph Visualizar! Here we'll be taking a Graph as an input, in the form of a file or individual nodes , and give you the requered Visualization.</p>
<h4>INPUT FORMAT:</h4>
<p>First line contains the number of nodes,say n.(Nodes are numbered as 0,1,2,...(n-1) ) Followed by n*n weighted matrix. Disconnected egdes are represented by negative weight. Last line contains the source node.(i.e, the node from which the DFS should begin)</p>
<p>File must be named as input.txt and it should be a text file.</p>
<form action = "/processing" method = "post" enctype="multipart/form-data">
<input class="btn btn-primary" style="margin-bottom: 10px" type="file" name="file" />
<input class="btn btn-success" style="margin-bottom: 10px" type = "submit" value="Upload">
</form>
<h4>OR</h4>
<form action = "/p2" method ="post">
<label for="n">No. of Nodes</label> <br>
<input name="nodes" type="text" id="n" /> <br>
<label for="v">Enter value (sourse_node,destination_node,weight):(Eg:[[0,1,10][2,3,20]...])</label> <br>
<textarea name="val"></textarea> <br>
<label for="s">Sourse Node</label> <br>
<input name="sourse" type="text" style="margin-bottom: 10px" id="s"/> <br>
<input class="btn btn-success" style="margin-bottom: 10px" type = "submit" value="Submit">
</form>
</p>
</div>
</div>
</main>
{% endblock %}/*
\ No newline at end of file
{% extends 'base.html' %}
{% block head %}
<title>Home</title>
{% endblock %}
{% block body %}
<br>
<h1>Home Page</h1>
<br>
<main role="main">
<div class="jumbotron">
<div class="col-sm-8 mx-auto">
<h1>Welcome</h1>
{% for message in get_flashed_messages() %}
<p>{{ message }}</p>
{% endfor %}
<p>Welcome to our online Graph Visualizar! Here we'll be taking a Graph as an input, in the form of a file or individual nodes , and give you the requered Visualization.</p>
<p>Input Successful</p>
<a class="btn btn-primary" href="/page2" role="button" style="margin-bottom: 10px">View GRAPH &raquo;</a>
<a class="btn btn-primary" href="/image2" role="button" style="margin-bottom: 10px">View DFS (DEPTH FIRST SEARCH TRAVERSAL) &raquo;</a>
<a class="btn btn-primary" href="/image3" role="button" style="margin-bottom: 10px">View BFS (Breadth FIRST SEARCH TRAVERSAL) &raquo;</a>
<a class="btn btn-primary" href="/table" role="button" style="margin-bottom: 10px">View Adj. represent &raquo;</a>
</p>
</div>
</div>
</main>
{% endblock %}/*
\ No newline at end of file
{% extends 'base.html' %}
{% block head %}
<title>Home</title>
{% endblock %}
{% block body %}
<br>
<h1>Home Page</h1>
<br>
<main role="main">
<div class="jumbotron">
<div class="col-sm-8 mx-auto">
<h1>Welcome</h1>
{% for message in get_flashed_messages() %}
<p>{{ message }}</p>
{% endfor %}
<p>Welcome to our online Graph Visualizar! Here we'll be taking a Graph as an input, in the form of a file or individual nodes , and give you the requered Visualization.</p>
<a class="btn btn-primary" href="/page1" role="button" style="margin-bottom: 10px">View GRAPH &raquo;</a>
<a class="btn btn-primary" href="/image1" role="button" style="margin-bottom: 10px">View DFS (DEPTH FIRST SEARCH TRAVERSAL) &raquo;</a>
<a class="btn btn-primary" href="/image3" role="button" style="margin-bottom: 10px">View BFS (Breadth FIRST SEARCH TRAVERSAL) &raquo;</a>
</p>
</div>
</div>
</main>
{% endblock %}/*
\ No newline at end of file
{% extends 'base.html' %}
{% block head %}
<title>Home</title>
{% endblock %}
{% block body %}
<br>
<h1>Adjacency matrix</h1>
<br>
<main role="main">
<div class="jumbotron">
<div class="col-sm-8 mx-auto">
<table>
{% for row in rows %}
<tr>
{% for cell in row %}
<td>{{cell}}</td>
{% endfor %}
</tr>
{% endfor%}
</table>
</div>
</div>
</main>
{% endblock %}/*
\ No newline at end of file
userbfs.png

29.6 KiB

userdfs.png

17.7 KiB

usergraph.png

23.8 KiB

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment