Operacions bàsiques de grafs ============================ Importem la biblioteca :mod:`networkx`. >>> import networkx as nx Creem un graf buit. >>> g = nx.Graph() Consultem els nodes. >>> list(g.nodes) [] Quants nodes té? >>> len(g) 0 >>> g.order() 0 >>> g.number_of_nodes() 0 Consultem les arestes. >>> list(g.edges) [] Quantes arestes té? >>> g.size() 0 >>> g.number_of_edges() 0 Hi afegim un node. >>> g.add_node(10) >>> sorted(g.nodes) [10] >>> g.order(), g.size() (1, 0) Els nodes són un conjunt: només hi apareixen un cop malgrat que els hi afegim més d'un cop. >>> g.add_node(10) >>> sorted(g.nodes) [10] Hi afegim una aresta. >>> g.add_edge(1, 2) Consultem tots els nodes. >>> sorted(g.nodes) [1, 2, 10] Si algun dels nodes incidents a una aresta encara no pertany al graf, s'hi afegeix. Consultem totes les arestes. >>> sorted(g.edges) [(1, 2)] Les arestes són un conjunt: només hi apareixen un cop malgrat que les hi afegim més d'un cop. >>> g.add_edge(1, 2) >>> sorted(g.edges) [(1, 2)] Hi afegim uns quants nodes més a partir d'un iterable. >>> g.add_nodes_from( [3, 4, 5, 11] ) >>> sorted(g.nodes) [1, 2, 3, 4, 5, 10, 11] >>> g.order(), g.size() (7, 1) Hi afegim unes quantes arestes més a partir d'un iterable. >>> g.add_edges_from( [(2,3), (3,4), (4,5), (5,2), (11,10)] ) >>> g.size() 6 Visualitzem el graf utilitzant el mòdul ``matplotlib.pyplot``. >>> import matplotlib.pyplot as plt >>> nx.draw(g, with_labels=True) >>> plt.show() .. figure:: grafs-1.svg Consultem si el graf conté un node. >>> 1 in g True >>> 8 in g False >>> g.has_node(10) True Consultem si el graf conté una aresta. >>> g.has_edge(1, 2) True El graf és simètric: conté les arestes que hi hem afegit i les simètriques. >>> g.has_edge(2, 1) True >>> g.has_edge(3, 5) False Consultem el grau d'un node. >>> g.degree(2) 3 Recorrem els nodes del graf. El graf és iterable, però desconeixem en quin ordre es recorreran els nodes perquè són un conjunt. .. code:: python3 for node in g: print(node) >>> sorted(g) [1, 2, 3, 4, 5, 10, 11] També els podem recórrer mitjançant la vista ``nodes``. .. code:: python3 for node in g.nodes: print(node) >>> sorted(g.nodes) [1, 2, 3, 4, 5, 10, 11] Recorrem les arestes del graf mitjançant la vista ``edges``. Desconeixem en quin ordre es recorreran perquè són un conjunt. .. code:: python3 for edge in g.edges: print(edge) >>> sorted(g.edges) [(1, 2), (2, 3), (2, 5), (3, 4), (4, 5), (10, 11)] Recorrem els veïns d'un node. .. code:: python3 for node in g.neighbors(2): print(node) >>> sorted(g.neighbors(2)) [1, 3, 5] .. code:: python3 for node in g[2]: print(node) >>> sorted(g[2]) [1, 3, 5] Recorrem les arestes incidents a un node. .. code:: python3 for node in g.edges(2): print(node) >>> sorted(g.edges(2)) [(2, 1), (2, 3), (2, 5)] Afegim un camí al graf. >>> nx.add_path(g, [1,2,3,5]) Visualitzem el graf >>> nx.draw(g, with_labels=True) >>> plt.show() .. figure:: grafs-2.svg