Simple graph functionality for Python.
Project description
PGraph: simple graphs for Python
- GitHub repository: https://github.com/petercorke/pgraph-python
- Documentation: https://petercorke.github.io/pgraph-python
- Dependencies:
numpy
This Python package allows the manipulation of directed and non-directed graphs. Also supports embedded graphs.
from pgraph import *
# load places and routes
with open('places.json', 'r') as f:
places = json.loads(f.read())
with open('routes.json', 'r') as f:
routes = json.loads(f.read())
# build the graph
g = UGraph()
for name, info in places.items():
g.add_vertex(name=name, coord=info["utm"])
for route in routes:
g.add_edge(route[0], route[1], cost=route[2])
# plan a path from Hughenden to Brisbane
p = g.path_Astar('Hughenden', 'Brisbane')
g.plot(block=False) # plot it
g.highlight_path(p) # overlay the path
Properties and methods of the graph
Graphs belong to the class UGraph
or DGraph
for undirected or directed graphs respectively
g.add_vertex()
add a vertexg.add_edge()
connect two verticesg.n
the number of vertices- supports iteration:
for vertex in graph:
g.edges()
all edges in the graphg[i]
reference a vertex by its index or nameg.nc
the number of graph components, 1 if fully connectedg.component(v)
the component that vertexv
belongs tog.plot()
plots the vertices and edgesg.path_BFS()
breadth-first searchg.path_Astar()
A* searchg.adjacency()
adjacency matrixg.Laplacian()
Laplacian matrixg.incidence()
incidence matrix
Properties and methods of a vertex
Vertices belong to the class UVertex
or DVertex
for undirected or directed graphs respectively
v.coord
the coordinate vector for embedded graphv.name
the name of the vertex- access the neighbours of a vertex by
v.neighbours()
.
We can name the vertices and reference them by name
Properties and methods of an edge
e.cost
cost of edge for planning methodse.next(v)
vertex on edgee
that is notv
e.v1
,e.v2
the two vertices that define the edgee
Modifying a graph
g.remove(v)
remove vertexv
e.remove()
remove edgee
Inheritance
Consider a user class Foo
that we would like to represent vertices in a graph.
- Have it subclass either
DVertex
orUVertex
- Then place instances of
Foo
into the graph usingadd_vertex
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
pgraph-python-0.5.tar.gz
(12.1 kB
view hashes)