Example #1
0
def plot(graph, weights, pos, station_values, name):
    palette = sns.color_palette('RdBu', n_colors=256)
    cmap = colors.ListedColormap(palette[::-1])

    weights = weights.copy()
    weights.a -= np.min(weights.a)
    weights.a *= 2 / np.max(weights.a)
    weights.a += 0.2

    gt_draw.graph_draw(graph, pos=pos, vertex_color=[0, 0, 0, 0.5],
                       vertex_fill_color=station_values, vcmap=cmap,
                       vertex_size=5, edge_color=[0, 0, 0, 0.7],
                       edge_pen_width=weights,
                       output=name + '_temp.svg')
    gt_draw.graph_draw(graph, pos=pos, vertex_color=[0, 0, 0, 0.5],
                       vertex_fill_color=station_values, vcmap=cmap,
                       vertex_size=10, edge_color=[0, 0, 0, 0.7],
                       edge_pen_width=weights,
                       output=name + '_temp.png', output_size=(1200, 1200))

    min_val = np.min(station_values.a)
    max_val = np.max(station_values.a)
    step = (max_val - min_val) / 5
    labels = np.array(['{0:.2f}'.format(x)
                       for x in np.arange(min_val, max_val, step)])
    plt.figure()
    utils.plot_colorbar(cmap, labels, name)
Example #2
0
def show_spec_in_graph(graph, vertex, spec, pos, weight, file_name):
    dist = 1.0 - squareform(pdist(spec.T, 'cosine'))

    plt.figure()
    plt.stem(dist[vertex, :], markerfmt=' ')

    rim = graph.new_vertex_property('vector<double>')
    rim.set_2d_array(np.array([0, 0, 0, 1]))
    rim[graph.vertex(vertex)] = [0.8941176471, 0.1019607843, 0.1098039216, 1]
    rim_width = graph.new_vertex_property('float', vals=0.5)
    rim_width.a[vertex] = 2
    shape = graph.new_vertex_property('int', vals=0)
    shape[graph.vertex(vertex)] = 2
    size = graph.new_vertex_property('double', vals=10)
    size.a[vertex] = 15
    correlation = graph.new_vertex_property('double', vals=2)
    correlation.a = dist[vertex, :]
    vorder = graph.new_vertex_property('int', vals=0)
    vorder.a[vertex] = 1

    palette = sns.cubehelix_palette(256)
    cmap = colors.ListedColormap(palette)
    gt_draw.graph_draw(graph, pos=pos, vertex_color=rim, vorder=vorder,
                       vertex_pen_width=rim_width,
                       vertex_shape=shape, vertex_fill_color=correlation,
                       vcmap=cmap, vertex_size=size, edge_color=[0, 0, 0, 0.7],
                       edge_pen_width=weight, output=file_name + '.png',
                       output_size=(1200, 1200))

    plt.figure()
    utils.plot_colorbar(cmap, np.arange(0, 1.01, 0.2), file_name)
Example #3
0
def test_chain():
    periodic = True
    # periodic = False
    graph = gt_gen.lattice([1, 200], periodic=periodic)
    if periodic:
        figure_title = 'line_periodic'
    else:
        figure_title = 'line_non-periodic'

    n = graph.num_vertices()
    location1 = 0.2 * n
    location2 = n - location1
    jump = 1e-3
    weight = graph.new_edge_property('double', vals=1)
    e1 = graph.edge(location1, location1 + 1)
    weight[e1] = jump
    e2 = graph.edge(location2 - 1, location2)
    weight[e2] = jump

    pos_x = np.arange(n)
    pos_y = np.zeros((n,))
    v_pos = graph.new_vertex_property('vector<double>',
                                      vals=np.vstack((pos_x, pos_y)).T)
    v_text = graph.new_vertex_property('string')
    for v in graph.vertices():
        v_text[v] = pos_x[graph.vertex_index[v]]
    palette = sns.color_palette('Set1', n_colors=2)
    cmap = colors.ListedColormap(palette)
    gt_draw.graph_draw(graph, pos=v_pos, edge_color=weight, ecmap=cmap,
                       edge_pen_width=.5, vertex_fill_color='w', vertex_size=2,
                       vertex_text=v_text, vertex_font_size=1,
                       output=figure_title + '_graph.pdf')

    x_signal1 = np.cos(np.linspace(0, 4 * np.pi, location1))
    x_signal2 = np.cos(np.linspace(0, 50 * np.pi, n - 2 * location1))
    x_signal3 = np.cos(np.linspace(0, 8 * np.pi, location1))
    x_signal = np.hstack([x_signal1, x_signal2, x_signal3])

    palette = sns.color_palette('Set1', n_colors=3)
    plt.figure()
    markerline, stemlines, baseline = plt.stem(x_signal, markerfmt=' ')
    plt.setp(stemlines, color=palette[1], linewidth=1.5)
    plt.setp(baseline, color='k')
    plt.savefig(figure_title + '_signal.pdf', dpi=300)

    n_eigs = graph.num_vertices() - 1
    tau = 200
    alpha = -1e-4

    factories = [spec.ConvolutionSGFT(graph, n_eigs, tau, weight=weight),
                 spec.PageRankSGFT(graph, n_eigs, alpha, weight=weight),
                 spec.ConvolutionSGFT(graph, n_eigs, tau, weight=None),
                 spec.PageRankSGFT(graph, n_eigs, alpha, weight=None)]

    sgft.comparison.compare_spectrograms(factories, x_signal, graph, v_pos,
                                         file_name=figure_title)
    sgft.comparison.compare_localization(factories, location1, graph, v_pos,
                                         file_name=figure_title)
Example #4
0
    def draw(self, **kwargs):
        r"""Convenience wrapper to :func:`~graph_tool.draw.graph_draw` that
        draws the state of the graph as colors on the vertices and edges."""

        bv, bc_in, bc_out, bc_total = self.get_overlap_blocks()
        if self.deg_corr:
            pie_fractions = bc_total.copy("vector<double>")
        else:
            pie_fractions = self.base_g.new_vp("vector<double>",
                                               vals=[ones(len(bv[v])) for v
                                                     in self.base_g.vertices()])

        gradient = kwargs.get("edge_gradient",
                              get_block_edge_gradient(self.base_g,
                                                      self.get_edge_blocks(),
                                                      cmap=kwargs.get("ecmap",
                                                                      None)))
        from graph_tool.draw import graph_draw
        return graph_draw(self.base_g,
                          vertex_shape=kwargs.get("vertex_shape", "pie"),
                          vertex_pie_colors=kwargs.get("vertex_pie_colors", bv),
                          vertex_pie_fractions=kwargs.get("vertex_pie_fractions",
                                                          pie_fractions),
                          edge_gradient=gradient,
                          **dmask(kwargs, ["vertex_shape", "vertex_pie_colors",
                                           "vertex_pie_fractions",
                                           "edge_gradient"]))
Example #5
0
    def show_argmax_spectrogram_graph(s, vertex_size=20, amax_file_name=None):
        amax = np.argmax(np.abs(s), axis=0)
        n_values = np.unique(amax).size
        assignment = graph.new_vertex_property('double', vals=amax)

        if weight is None:
            edge_pen_width = 1.0
        else:
            edge_pen_width = weight

        palette = sns.color_palette('BuGn', n_colors=n_values)
        cmap = colors.ListedColormap(palette)
        gt_draw.graph_draw(graph, pos=pos, vertex_color=[0, 0, 0, 0.5],
                           vertex_fill_color=assignment, vcmap=cmap,
                           vertex_size=vertex_size, edge_color=[0, 0, 0, 0.7],
                           edge_pen_width=edge_pen_width, output=amax_file_name,
                           output_size=(1200, 1200))
Example #6
0
def plot_network_random(g, inline=True, filename=None, scale=300.0):
    """
    Display a plot of the network, g, with the vertices placed in an
    unstructured, apparently random layout.  Vertices are the model
    parameters and they are connected by edges whose thickness indicates the
    value of the second order sensitivity.

    Parameters
    -----------
    g        : graph-tool graph
               The graph to plot.
    inline   : bool, optional
               Boolean indicating whether the plot should be shown inline in
               an ipython notebook.  If false the plot is created in its own
               window and is somewhat interactive.
    filename : str, optional
               If you would like to save the plot to a file specify a
               filename (with an extension of pdf or png).
    scale    : float, optional
               If you would like to resize the vertices you can change the
               value of this float.

    Returns
    --------
    graph-tool plot
    """
    for i in range(g.num_vertices()):
        g.vp['sensitivity'][i] = scale * g.vp['sensitivity'][i]

    draw.graph_draw(g,
                    vertex_text=g.vp['param'],
                    vertex_font_size=10,
                    vertex_text_position=-0.1,
                    # vertex_text_color='black',
                    vertex_size=g.vp['sensitivity'],
                    vertex_color='#006600',
                    vertex_fill_color='#006600',
                    vertex_halo=True,
                    vertex_halo_color='#b3c6ff',
                    vertex_halo_size=g.vp['confidence'],
                    edge_color='#002699',
                    edge_pen_width=g.ep['second_sens'],
                    output_size=(600, 600),
                    inline=inline,
                    output=filename
                    )
Example #7
0
def draw_clustering(graph, filename=None, pos=None, vmore=None,
                    emore=None, show_filling=False, curved=False,
                    cluster_index_name='cluster', osize=800):
    # graph.set_edge_filter(graph.ep['fake'], inverted=True)
    pos = pos or gtdraw.sfdp_layout(graph)
    vertex_options = {'pen_width': 0}
    vertex_options.update(add_cluster_name_and_color(graph,
                                                     cluster_index_name))
    name = graph.new_vertex_property('string')
    for i, v in enumerate(graph.vertices()):
        name[v] = str(i)
    if np.unique(graph.vp[cluster_index_name].a).size < 2:
        vertex_options['text'] = name
    if vmore:
        vertex_options.update(vmore)
    # d = count_disagreements(graph, alt_index=cluster_index_name)
    # if not show_filling:
    #     graph.set_edge_filter(graph.ep['fake'], inverted=True)
    # print(str(d.a.sum().ravel()[0]) + ' disagreements')
    if not show_filling:
        edge_options = {'pen_width': 2}
    else:
        edge_width = graph.new_edge_property('float')
        for e in graph.edges():
            if not graph.ep['fake'][e]:
                edge_width[e] = 6
            else:
                edge_width[e] = 3  # if graph.ep['sign'][e] else 1
        edge_options = {'pen_width': edge_width}
    edge_options.update(add_edge_sign_color(graph))
    # edge_options.update(add_edge_disagreement_size(graph, d))
    if emore:
        edge_options.update(emore)
    more_opts = {}
    if curved:
        from math import sqrt
        control = graph.new_edge_property("vector<double>")
        for e in graph.edges():
            d = sqrt(sum((pos[e.source()].a - pos[e.target()].a) ** 2)) / 5
            control[e] = [0.3, d, 0.7, .5*d]
        more_opts['edge_control_points'] = control
    gtdraw.graph_draw(graph, pos=pos, vprops=vertex_options,
                      eprops=edge_options, output=filename, fit_view=True,
                      output_size=(osize, int(0.7*osize)), inline=True,
                      **more_opts)
Example #8
0
def draw_state(n_iter, graph, history, pos):
    """draw one state"""
    edge_tuple = lambda e: (min(map(int, e)), max(map(int, e)))
    n = graph.num_vertices()
    pivot, d_edges = history[n_iter]

    vpen = graph.new_vertex_property('int')
    vpen.a = 4*(np.arange(n) == pivot)
    name = graph.new_vertex_property('string')
    name = graph.new_vertex_property('string')
    for i, v in enumerate(graph.vertices()):
        name[v] = str(i)
    vertex_options = {'size': 26, 'color': 'blue', 'pen_width': vpen,
                      'text': name}

    old_enough = graph.new_edge_property('bool')
    old_enough.a = graph.ep['depth'].a <= n_iter//2

    ecolors = [[.8, .2, .2, .8], [.2, .8, .2, .8]]
    edge_color = graph.new_edge_property('vector<float>')
    edge_width = graph.new_edge_property('int')
    for e in graph.edges():
        if edge_tuple(e) in d_edges:
            edge_width[e] = 5
            old_enough[e] = True
            if n_iter % 2 == 0:
                edge_color[e] = [.6, .6, .6, .8]
            else:
                edge_color[e] = ecolors[graph.ep['sign'][e]]
        else:
            edge_width[e] = 3
            edge_color[e] = ecolors[graph.ep['sign'][e]]

    edge_options = {'pen_width': edge_width, 'color': edge_color}

    graph.set_edge_filter(old_enough)
    gtdraw.graph_draw(graph, pos=pos, vprops=vertex_options,
                      eprops=edge_options, output=None, fit_view=True,
                      output_size=(600, 600))
    graph.set_edge_filter(None)
Example #9
0
def show_window(spectrogram, v, weight=None, pos=None, file_name=None, vertex_size=10):
    window = spectrogram.get_window(v)
    window = spectrogram.graph.new_vertex_property("double", vals=window)

    if weight is None:
        edge_pen_width = 1.0
    else:
        edge_pen_width = weight

    palette = sns.color_palette("YlOrRd", n_colors=256)
    cmap = colors.ListedColormap(palette)
    gt_draw.graph_draw(
        spectrogram.graph,
        pos=pos,
        vertex_color=[0, 0, 0, 0.5],
        vertex_fill_color=window,
        vcmap=cmap,
        vertex_size=vertex_size,
        edge_color=[0, 0, 0, 0.7],
        edge_pen_width=edge_pen_width,
        output=file_name,
        output_size=(1200, 1200),
    )
Example #10
0
def user_network_summary(g):
    span = "{:D MMM YYYY, HH:mm} - {:D MMM YYYY, HH:mm}".format(
        arrow.get(g.edge_properties["created_at"].a.min()),
        arrow.get(g.edge_properties["created_at"].a.max())
    )
    largest_component = label_largest_component(g, directed=False).a.sum()

    display(Markdown("### " + g.graph_properties["track"].replace("#", r"\#")))
    display(Markdown("#### " + span))

    graph_draw(g, inline=True, output_size=[1000, 1000],
               vertex_fill_color=[.2, .3, .9, .7], vertex_size=2)
    stats = pd.DataFrame([
        ["Vertices",
         g.num_vertices()],
        ["Edges",
         g.num_edges()],
        ["Avg. degree",
         float(g.num_edges()) / g.num_vertices()],
        ["Avg. clustering",
         vertex_average(g, local_clustering(g))[0]],
        ["Giant component share",
         "{:.1%}".format(largest_component / g.num_vertices())]
    ], columns=["Metric", "Value"])
    display(stats)

    bins = 20
    counts, _ = vertex_hist(g, "in", range(bins))

    plt.bar(range(1, bins), counts, align="center")

    plt.xticks(range(bins))
    plt.xlim([0.5, bins - 1])
    plt.title("Degree distribution")

    plt.show()
Example #11
0
    def draw(self, **kwargs):
        r"""Convenience wrapper to :func:`~graph_tool.draw.graph_draw` that
        draws the state of the graph as colors on the vertices and edges."""

        b = self.get_MAP()
        bv = self.g.new_vertex_property("vector<int32_t>", val=range(self.B))
        gradient = self.g.new_ep("double")
        gradient = group_vector_property([gradient])
        from graph_tool.draw import graph_draw
        return graph_draw(self.g,
                          vertex_fill_color=kwargs.get("vertex_fill_color", b),
                          vertex_shape=kwargs.get("vertex_shape", "pie"),
                          vertex_pie_colors=kwargs.get("vertex_pie_colors", bv),
                          vertex_pie_fractions=kwargs.get("vertex_pie_fractions",
                                                          self.vm),
                          edge_gradient=kwargs.get("edge_gradient", gradient),
                          **dmask(kwargs, ["vertex_shape", "vertex_pie_colors",
                                           "vertex_pie_fractions",
                                           "vertex_fill_color",
                                           "edge_gradient"]))
Example #12
0
            self.cross_pos_index[cross_pos] = cross_index
            return cross_index

    def add_road_edge(self, s_vertex, e_vertex, road):
        if self.has_edge(s_vertex, e_vertex):
            return self.g.edge(s_vertex, e_vertex)
        else:
            edge = self.g.add_edge(s_vertex, e_vertex)
            self.g.ep.level[edge] = int(road.record[self.PATHCLASS_index])
            self.g.ep.length[edge] = self.road_length(road)
            return edge

    @staticmethod
    def road_length(road):
        length = 0
        for sub_road in zip(road.shape.points[:-1], road.shape.points[1:]):
            length += distance.euclidean(sub_road[0], sub_road[1])
        return length


if __name__ == '__main__':
    shp_file = '/home/elvis/map/map-shp/Beijing2011/bj-road-epsg3785.shp'
    gt_file = '/home/elvis/map/map-shp/Beijing2011/bj-road-epsg3785.gt'
    if os.path.exists(gt_file):
        file = gt_file
    else:
        file = shp_file
    r = RoadMap(file)
    r.load()
    graph_draw(r.g, pos=r.g.vp.pos, output_size=(600, 600), output='/home/elvis/图片/2017-10-12/2.svg')
    # graph_draw(r.g, pos=r.g.vp.pos)
Example #13
0
def visualisation(g, subtree_height=2):
    from cc_pivot import draw_clustering
    import draw_utils as du
    from graph_tool import draw as gdraw
    import graph_tool as gt
    import numpy as np
    import seaborn as sns
    G, E = cexp.redensify.G, cexp.redensify.EDGES_SIGN
    root = 16
    Gbfs, parents, tree = initial_spanning_tree(G, root)
    ecol, esize = du.color_graph(g, tree)
    tmap = du.map_from_list_of_edges(g, tree)
    g.set_edge_filter(tmap)
    tpos = gdraw.sfdp_layout(g)
    g.set_edge_filter(None)
    ecol, esize = du.color_graph(g, tree)
    g_halo = g.new_vertex_property('bool')
    g_halo.a[root] = True
    draw_clustering(g, pos=tpos, vmore={'size': 22, 'halo': g_halo},
                    emore={'pen_width': esize, 'color': ecol, }, osize=900)

    Bparent = deepcopy(parents)
    Bg = deepcopy(Gbfs)
    for u in Bg:
        p = Bparent[u]
        Bg[u].discard(p)

    dtree, height, strees = dfs_of_a_tree(Bg, root, Bparent, subtree_height)

    cols = sns.color_palette('rainbow', len(strees))
    random.shuffle(cols)
    ecol, esize = du.color_graph(g, tree)
    for e in tree:
        ge = g.edge(*e)
        ecol[ge] = du.light_gray  # [.25,.25,.25,.8]
        esize[ge] = 1.5
    for st, c in zip(strees, cols):
        for u, v in ((u, v) for u, v in st.items() if v is not None):
            ge = g.edge(u, v)
            ecol[ge] = c
            esize[ge] = 3
    draw_clustering(g, pos=tpos, vmore={'size': 22},
                    emore={'pen_width': esize, 'color': ecol}, osize=900)

    tree_membership = {u: i for i, st in enumerate(strees) for u in st}
    tree_root = [[k for k, v in t.items() if v is None][0] for t in strees]
    support_tree = []
    for st in strees:
        support_tree.append({(u, v) if u < v else (v, u)
                             for u, v in st.items() if v is not None})
    within_tree, across_trees = bipartition_edges(E, strees, tree_membership, support_tree)
    Gt = {i: set() for i, u in enumerate(strees)}
    Et = {e: random.choice(list(candidates))
          for e, candidates in across_trees.items()}
    for e, n in Et.items():
        add_edge(Gt, *e)

    k = gt.Graph(directed=False)
    k.add_vertex(len(strees))
    names = k.new_vertex_property('string')
    vcols = k.new_vertex_property('vector<double>')
    etext = k.new_edge_property('string')
    prev_pos = tpos.get_2d_array((0, 1))
    new_pos = np.zeros((2, len(strees)))
    stpos = k.new_vertex_property('vector<double>')
    for i, (stree_prt, root) in enumerate(zip(strees, tree_root)):
        v = k.vertex(i)
        members = sorted(stree_prt.keys())
        mpos = prev_pos[:, members]
        new_pos[:, i] = mpos.mean(1)
        stpos[v] = prev_pos[:, root]  # mpos.mean(1)
        names[v] = str(root)
        vcols[v] = list(cols[i]) + [.9, ]
    for e, n in Et.items():
        ke = k.add_edge(*e)
        etext[ke] = str(n)
    gdraw.graph_draw(k, stpos, eprops={'text': etext}, output_size=(800, 800),
                     vprops={'pen_width': 0, 'text': names, 'fill_color': vcols, 'size': 24})

    stars, _, star_membership = extract_stars(Gt)
    within_star, across_stars = bipartition_edges(Et, stars, star_membership)

    scols, ssize = k.new_edge_property('vector<double>'), k.new_edge_property('double')
    cols_s = sns.color_palette('Set1', len(stars))
    star_halo = k.new_vertex_property('bool')
    star_halo.a = np.zeros(k.num_vertices())
    for s in stars:
        star_halo[g.vertex(s.center)] = True
    for e in k.edges():
        u, v = int(e.source()), int(e.target())
        su, sv = star_membership[u], star_membership[v]
        if su == sv and stars[su].center in [u, v]:
            scols[e], ssize[e] = list(cols_s[su]) + [.9, ], 3
        else:
            scols[e], ssize[e] = [.2, .2, .2, .8], 1

    stext = k.new_edge_property('string')
    vs_cols = k.new_vertex_property('vector<double>')
    for u in k.vertices():
        vs_cols[u] = list(cols_s[star_membership[int(u)]]) + [.9]
    for candidates in across_stars.values():
        chosen = sorted(candidates)[0]
        ke = k.edge(*chosen)
        ssize[ke] = 3
        stext[ke] = str(Et[chosen])
        scols[ke] = du.black
    gdraw.graph_draw(k, stpos, vprops={'pen_width': 0, 'text': names, 'fill_color': vs_cols, 'size': 24, 'halo': star_halo},
                     eprops={'pen_width': ssize, 'color': scols, 'text': stext}, output_size=(800, 800))
Example #14
0
def render_graph(g, path='graph/{}.pdf'):

    # the simplest way
    arg_map = dict(
        g = g,
        output = path.format('1-1-random-simplest'),
    )
    graph_draw(**arg_map)

    # use constants
    arg_map.update(dict(
        output = path.format('1-2-random-constant'),
        output_size = (SIZE, SIZE),
        vertex_size = MA_V_SIZE,
        edge_pen_width = MA_E_PWIDTH,
    ))
    graph_draw(**arg_map)

    # use prop_to_size
    v_count_p = g.vp['count']
    e_count_p = g.ep['count']
    v_size_by_count_p = prop_to_size(v_count_p, MI_V_SIZE, MA_V_SIZE)
    e_pwidth_by_count_p = prop_to_size(e_count_p, MI_E_PWIDTH, MA_E_PWIDTH)
    arg_map.update(dict(
        output = path.format('1-3-random-size'),
        vertex_size = v_size_by_count_p,
        edge_pen_width = e_pwidth_by_count_p,
    ))
    graph_draw(**arg_map)

    # use fill_color
    debug('v_count_p.a         : {}', v_count_p.a)
    v_color_by_count_p = prop_to_size(v_count_p, 0, 1)
    debug('v_color_by_count_p.a: {}', v_color_by_count_p.a)
    arg_map.update(dict(
        output = path.format('1-4-random-color'),
        vertex_fill_color = v_color_by_count_p,
    ))
    graph_draw(**arg_map)

    # use closeness
    v_closeness_p = g.vp['closeness']
    v_color_by_closeness_p = prop_to_size(v_closeness_p, 0, 1)
    #closeness_arg_map = arg_map.copy()
    #closeness_arg_map.update(dict(
    #    output = path.format('1-5-random-closeness'),
    #    vertex_fill_color = v_color_by_closeness_p,
    #))
    arg_map.update(dict(
        output = path.format('1-5-random-closeness'),
        vertex_fill_color = v_color_by_closeness_p,
    ))
    graph_draw(**arg_map)

    # sfdp_layout
    arg_map.update(dict(
        output = path.format('2-1-sfdp'),
        pos = sfdp_layout(g),
    ))
    graph_draw(**arg_map)

    # sfdp_layout with only edge's weight
    arg_map.update(dict(
        output = path.format('2-2-sfdp-edge-weight'),
        pos = sfdp_layout(g, eweight=e_count_p),
    ))
    graph_draw(**arg_map)

    # sfdp_layout with both edge and vertex's weight
    arg_map.update(dict(
        output = path.format('2-3-sfdp-both-weight'),
        pos = sfdp_layout(g, eweight=e_count_p, vweight=v_count_p),
    ))
    graph_draw(**arg_map)

    # fruchterman_reingold_layout
    arg_map.update(dict(
        output = path.format('3-1-fr'),
        pos = fruchterman_reingold_layout(g),
    ))
    graph_draw(**arg_map)

    # fruchterman_reingold_layout with edge's weight
    arg_map.update(dict(
        output = path.format('3-2-fp-edge-weight'),
        pos = fruchterman_reingold_layout(g, weight=e_count_p),
    ))
    graph_draw(**arg_map)

    # arf_layout
    arg_map.update(dict(
        output = path.format('4-1-arf'),
        pos = arf_layout(g),
    ))
    graph_draw(**arg_map)

    # arf_layout with edge's weight
    arg_map.update(dict(
        output = path.format('4-2-arf-edge-weight'),
        pos = arf_layout(g, weight=e_count_p),
    ))
    graph_draw(**arg_map)
Example #15
0
             g.v[g.v['layer'] == layer].y.max() + margin,
             layer, fontsize=15)


# We can also plot the supergraph $G^L = (V^L, E^L)$

# In[17]:

# create graph_tool graph of lg
gtg = lg.return_gt_graph(relations=True, node_indices=True, edge_indices=True)

# create plot
gtd.graph_draw(gtg,
               vertex_text=gtg.vp['i'], vertex_text_position=-2,
               vertex_fill_color='w',
               vertex_text_color='k',
               edge_text=gtg.ep['n_edges'],
               inline=True, fit_view=.8,
               output_size=(400,400))


# ### The SuperGraph $G^N = (V^N, E^N)$

# Partitioning by the type of feature ``V_N`` leads to the supergraph $G^{N} = (V^{N}, E^{N})$, where each supernode $V^{N}_{i^N} \in V^{N}$ corresponds to a node of the MLN. Superedges $E^{N}_{i^N j^N} \in E^{N}$ with $i^N = j^N$ correspond to the coupling edges of a MLN.

# In[18]:

# partition by MLN's node indices
nv, ne, gv, ge = g.partition_graph('V_N', return_gve=True)

# for each superedge, get types of edges and their weights
# graph-tool.skewed.de/
from graph_tool import Graph
from graph_tool import draw

g = Graph(directed=True)

for i in range(5):
    g.add_vertex()

v1 = g.add_vertex()
v2 = g.add_vertex()

v3 = g.vertex(2)

e1 = g.add_edge(v1, v2)
g.add_edge(v1, v3)

draw.graph_draw(g)

Example #17
0
def draw_network(network, nsize="total-degree", ncolor="group", nshape="o",
                 nborder_color="k", nborder_width=0.5, esize=1., ecolor="k",
                 spatial=True, size=(600,600), dpi=75):
    '''
    Draw a given graph/network.

    Parameters
    ----------
    network : :class:`~nngt.Graph` or subclass
        The graph/network to plot.
    nsize : float, array of floats or string, optional (default: "total-degree")
        Size of the nodes; if a number, percentage of the canvas length,
        otherwize a string that correlates the size to a node attribute among
        "in/out/total-degree", "betweenness".
    ncolor : float, array of floats or string, optional (default: 0.5)
        Color of the nodes; if a float in [0, 1], position of the color in the
        current palette, otherwise a string that correlates the color to a node
        attribute among "in/out/total-degree", "betweenness" or "group".
    nshape : char or array of chars, optional (default: "o")
        Shape of the nodes (see `Matplotlib markers <http://matplotlib.org/api/markers_api.html?highlight=marker#module-matplotlib.markers>`_).
    nborder_color : char, array of char, float or array of float, optional (default: "k")
        Color of the node's border using predefined `Matplotlib colors <http://matplotlib.org/api/colors_api.html?highlight=color#module-matplotlib.colors>`_).
        or floats in [0, 1] defining the position in the palette.
    nborder_width : float or array of floats, optional (default: 0.5)
        Width of the border in percent of canvas size.
    esize : float or array of floats, optional (default: 0.5)
        Width of the edges in percent of canvas size.
    ecolor : char, array of char, float or array of float, optional (default: "k")
        Edge color.
    spatial : bool, optional (default: True)
        If True, use the neurons' positions to draw them.
    size : tuple of ints, optional (default: (600,600))
        (width, height) tuple for the canvas size (in px).
    dpi : int, optional (default: 75)
        Resolution (dot per inch).
    '''
    pos,layout = None,None
    n = network.node_nb()
    e = network.edge_nb()
    # compute properties
    if issubclass(str,nsize.__class__):
        if e:
            nsize = _node_size(network, nsize)
            nsize.a *= 0.01*size[0]
    elif issubclass(float, nsize.__class__):
        nsize = np.repeat(nsize, n)
    if issubclass(str,esize.__class__):
        if e:
            esize = _edge_size(network, esize)
            esize.a *= 0.01*size[0]
    elif issubclass(float, esize.__class__):
        esize = np.repeat(esize, e)
        esize = network.graph.new_edge_property("double",esize)
    ncolor = _node_color(network, ncolor)        
    if issubclass(float, nborder_color.__class__):
        nborder_color = np.repeat(nborder_color, n)
    if issubclass(float, ecolor.__class__):
        ecolor = np.repeat(ecolor, e)
    # draw
    pos = np.zeros((n,2))
    if not e:
        nsize = 0.02*size[0]
        esize = 0.01*size[0]
        if spatial and network.is_spatial():
            pos = network[POS]
        else:
            pos[:,0] = size[0]*(np.random.uniform(size=n)-0.5)
            pos[:,1] = size[1]*(np.random.uniform(size=n)-0.5)
    elif spatial and network.is_spatial():
        pos = network[POS]
        pos = network.graph.new_vertex_property("vector<double>",pos)
    else:
        ebetw = network.graph.betweenness_list(as_prop=True)[1]
        pos = gplot.sfdp_layout(network.graph, eweight=ebetw)
    if not e:
        size_inches = (size[0]/float(dpi),size[1]/float(dpi))
        fig = plt.figure(facecolor='white', figsize=size_inches, dpi=dpi)
        ax = fig.add_subplot(111, frameon=0, aspect=1)
        fig.facecolor = "white"
        fig.figsize=size
        ax.set_axis_off()
        if hasattr(network, "population"):
            for group in network.population.itervalues():
                idx = group.id_list
                ax.scatter(pos[idx,0], pos[idx,1], s=nsize,
                           color=palette(ncolor[idx[0]]))
        else:
            ax.scatter(pos[:,0], pos[:,1], s=nsize)
        ax.set_xlim([-0.51*size[0],0.51*size[0]])
        ax.set_ylim([-0.51*size[1],0.51*size[1]])
        plt.show()
    elif spatial and network.is_spatial():
        gplot.graph_draw(network.graph, pos=pos, vertex_color=nborder_color,
            vertex_fill_color=ncolor, vertex_size=nsize, edge_color=ecolor,
            edge_pen_width=esize, output_size=size)
    else:
        gplot.graph_draw(network.graph, pos=pos, vertex_color=nborder_color,
            vertex_fill_color=ncolor, vertex_size=nsize, edge_color=ecolor,
            edge_pen_width=esize, output_size=size)