Exemple #1
0
from __future__ import print_function
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from pattern.graph import Graph, CENTRALITY

# A graph is a network of nodes (or concepts)
# connected to each other with edges (or links).

g = Graph()
for n in ("tree", "nest", "bird", "fly", "insect", "ant"):
    g.add_node(n)

g.add_edge("tree", "nest")  # Trees have bird nests.
g.add_edge("nest", "bird")  # Birds live in nests.
g.add_edge("bird", "fly")   # Birds eat flies.
g.add_edge("ant", "bird")   # Birds eat ants.
g.add_edge("fly", "insect")  # Flies are insects.
g.add_edge("insect", "ant")  # Ants are insects.
g.add_edge("ant", "tree")   # Ants crawl on trees.

# From tree => fly: tree => ant => bird => fly
print(g.shortest_path(g.node("tree"), g.node("fly")))
print(g.shortest_path(g.node("nest"), g.node("ant")))
print()

# Which nodes get the most traffic?
for n in sorted(g.nodes, key=lambda n: n.centrality, reverse=True):
    print('%.2f' % n.centrality, n)
Exemple #2
0
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from pattern.graph import Graph, CENTRALITY

# A graph is a network of nodes (or concepts)
# connected to each other with edges (or links).

g = Graph()
for n in ("tree", "nest", "bird", "fly", "insect", "ant"):
    g.add_node(n)

g.add_edge("tree", "nest")  # Trees have bird nests.
g.add_edge("nest", "bird")  # Birds live in nests.
g.add_edge("bird", "fly")   # Birds eat flies.
g.add_edge("ant", "bird")   # Birds eat ants.
g.add_edge("fly", "insect") # Flies are insects.
g.add_edge("insect", "ant") # Ants are insects.
g.add_edge("ant", "tree")   # Ants crawl on trees.

# From tree => fly: tree => ant => bird => fly
print(g.shortest_path(g.node("tree"), g.node("fly")))
print(g.shortest_path(g.node("nest"), g.node("ant")))
print()

# Which nodes get the most traffic?
for n in sorted(g.nodes, key=lambda n: n.centrality, reverse=True):
    print('%.2f' % n.centrality, n)
Exemple #3
0
from pattern.graph import Graph

g = Graph()
for movie, tropes in movies.items():
    g.add_node(movie)
    for trope in tropes:
        g.add_node(trope)
        g.add_edge(movie, trope)  # connection between movie <=> trope

# What nodes directly connect to a given trope?
for node in g["Teach Him Anger"].links:
    print node

# What is the shortest path between two nodes in the network?
print
print g.shortest_path("Cinderella", "Alien")

# Cinderella => Race Against the Clock => The X-Files => Absurdly Spacious Sewer => Alien

# Could we transform this into a tweet? For example:
# "I just watched Alien vs. Cinderella...
#  a mind-blowing race against the clock in an absurdly spacious sewer!"

# The network is too large visualize as a whole
# (using only Pattern tools).
# But we can visualize sub-networks:
# http://www.clips.ua.ac.be/pages/pattern-graph#canvas

node = g["Lassie"]
halo = node.flatten(depth=2)