def optimize(self, graph):
        """
        Build a dictionary mapping each pair of nodes to a number (
        the distance between them).

        @type  graph: graph
        @param graph: Graph.
        """
        for start in graph.nodes():
            for end in graph.nodes():
                for each in graph.node_attributes(start):
                    if (each[0] == 'position'):
                        start_attr = each[1]
                        break
                for each in graph.node_attributes(end):
                    if (each[0] == 'position'):
                        end_attr = each[1]
                        break
                dist = 0
                long1 = float(start_attr[0])
                latit1 = float(start_attr[1])
                long2 = float(end_attr[0])
                latit2 = float(end_attr[1])
                dis = haversine(long1, latit1, long2, latit2)

                self.distances[(start, end)] = dist
def pagerank(graph, damping_factor=0.85, max_iterations=100, min_delta=0.00001):
    """
    Compute and return the PageRank in an directed graph.    
    
    @type  graph: digraph
    @param graph: Digraph.
    
    @type  damping_factor: number
    @param damping_factor: PageRank dumping factor.
    
    @type  max_iterations: number 
    @param max_iterations: Maximum number of iterations.
    
    @type  min_delta: number
    @param min_delta: Smallest variation required to have a new iteration.
    
    @rtype:  Dict
    @return: Dict containing all the nodes PageRank.
    """
    
    nodes = graph.nodes()
    graph_size = len(nodes)
    if graph_size == 0:
        graph = gr
        nodes = graph.nodes()
        graph_size = len(nodes)
        # return {}
    min_value = (1.0-damping_factor)/graph_size #value for nodes without inbound links
    
    # itialize the page rank dict with 1/N for all nodes
    pagerank = dict.fromkeys(nodes, 1.0/graph_size)
        
    for i in range(max_iterations):
        diff = 0 #total difference compared to last iteraction
        # computes each node PageRank based on inbound links
        for node in nodes:
            rank = min_value
            for referring_page in graph.incidents(node):
                rank += damping_factor * pagerank[referring_page] / len(graph.neighbors(referring_page))
                
            diff += abs(pagerank[node] - rank)
            pagerank[node] = rank
        
        #stop if PageRank has converged
        if diff < min_delta:
            break
    
    return pagerank
def pagerank(graph,
             damping_factor=0.85,
             max_iterations=100,
             min_delta=0.00001):
    nodes = graph.nodes()
    graph_size = len(nodes)
    if graph_size == 0:
        return {}
    min_value = (1.0 - damping_factor
                 ) / graph_size  #value for nodes without inbound links

    # itialize the page rank dict with 1/N for all nodes
    pagerank = dict.fromkeys("a", 1.0 / graph_size)

    for i in range(max_iterations):
        diff = 0  #total difference compared to last iteraction
        # computes each node PageRank based on inbound links
        for node in nodes:
            rank = min_value
            for referring_page in graph.incidents("a"):
                rank += damping_factor * pagerank[referring_page] / len(
                    graph.neighbors(referring_page))

            diff += abs(pagerank["a"] - rank)
            pagerank["a"] = rank

        #stop if PageRank has converged
        if diff < min_delta:
            break

    return pagerank
示例#4
0
def output_clustered_graph(graph, name, clustering):
    """Will ommit edge labels
    """

    # Create AGraph via networkx
    G = nx.DiGraph()
    G.add_nodes_from(graph.nodes())
    G.add_edges_from(graph.edges())

    A = to_agraph(G)

    tableau20 = [ '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78',
                  '#2ca02c', '#98df8a', '#d62728', '#ff9896',
                  '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
                  '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7',
                  '#bcbd22', '#dbdb8d', '#17becf', '#9edae5' ]
    clist = [ tableau20[i*2] for i in range(0, len(tableau20)/2)]

    i = 0
    for c in clustering:
        A.add_subgraph(c, name='cluster_%d' % i, color=clist[i % len(clist)])
        i += 1

    name = 'graphs/%s.png' % name
    A.write(name + '.dot')
    A.draw(name, prog="dot")
示例#5
0
文件: hyki.py 项目: mmetzmac/hwios
 def format_graph_to_thejit_graph(self,graph):
     thejit_graph = []
     for node in graph.nodes():
         jit_node = graph.node_attr[node][0]
         jit_node['id'] = node
         jit_node['adjacencies'] = graph.node_neighbors[node]
         thejit_graph.append(jit_node)
     return thejit_graph
示例#6
0
 def _format_graph_to_thejit_graph(self,graph):
     """Convert pygraph graph to theJIT compatible graph"""
     thejit_graph = []
     for node in graph.nodes():
         jit_node = graph.node_attr[node][0]
         jit_node['id'] = node
         jit_node['adjacencies'] = graph.node_neighbors[node]
         thejit_graph.append(jit_node)
     return thejit_graph
示例#7
0
def visualize_graph(graph,
                    output_path,
                    coords,
                    colors=None,
                    sizes=None,
                    show=False):
    """Creates an image of a graph and saves it to a file.

    :param graph: The graph you want to visualize.
    :type graph: `pygraph.classes.graph.graph`

    :param output_path: Path to where image should be saved. None if you don't want it to be saved.
    :type output_path: str or NoneType

    :param coords: A function that outputs coordinates of a node.
    :type coords: function that outputs list of 2 float

    :param colors: A function that outputs an rgb code for each node, defaults to None
    :type colors: (function that outputs tuple of 3 float) or NoneType

    :param sizes: A function that outputs the radius for each node.
    :type sizes: (function that outputs float) or NoneType

    :param show: whether or not to show the image once generated.
    :type show: bool
    """
    graph_image = Image.new("RGB", (1000, 1000), "white")
    draw = ImageDraw.Draw(graph_image, "RGB")

    graph_nodes = graph.nodes()
    graph_edges = graph.edges()

    modified_coords = modify_coords([coords(node) for node in graph_nodes],
                                    [1000, 1000])

    if colors is not None:
        node_colors = [colors(node) for node in graph_nodes]
    else:
        node_colors = [(235, 64, 52) for _ in graph_nodes]

    if sizes is not None:
        node_sizes = [sizes(node) for node in graph_nodes]
    else:
        node_sizes = [1 for _ in graph_nodes]

    for edge in graph_edges:

        indices = [graph_nodes.index(v) for v in edge]
        centers = [tuple(modified_coords[i]) for i in indices]

        draw.line(centers, fill=(0, 0, 0), width=1)

    for center, node, color, r in zip(modified_coords, graph_nodes,
                                      node_colors, node_sizes):
        draw.ellipse([(center[0] - r, center[1] - r),
                      (center[0] + r, center[1] + r)],
                     fill=color)

    if output_path is not None:
        graph_image.save(output_path)
    if show:
        graph_image.show()
示例#8
0
文件: hyki.py 项目: mmetzmac/hwios
 def format_graph_to_thejit_tree(self, graph):
     """ If you have a 'disconnected' graph, this will fail """
     thejit_graph = self.make_node(graph, graph.nodes()[0], [])
     return thejit_graph
示例#9
0
 def _format_graph_to_thejit_tree(self, graph):
     """Convert pygraph graph to theJIT compatible tree. This will fail if you have a
     'disconnected' graph"""
     thejit_graph = self._make_node(graph, graph.nodes()[0], [])
     return thejit_graph