示例#1
0
def test_graphtool():
    """Test creating a tree from a suffix tree.
    """
    _num_bases, sequences, _ids = seqan.readFastaDNA(fasta_file('dm01r.fasta'))
    #for s in sequences:
    #    s.remove('T')
    index = seqan.IndexStringDNASetESA(sequences)
    suffix = 'ACGTATGC'
    predicate = seqan.traverse.suffixpredicate(suffix)
    #predicate = seqan.traverse.depthpredicate(4)
    builder = seqan.io.graphtool.Builder(index, predicate=predicate)
    #pos = GT.radial_tree_layout(builder.graph, builder.graph.vertex(0))
    pos = GT.sfdp_layout(builder.graph)
    GT.graph_draw(
        builder.graph,
        pos=pos,
        vertex_size=2,
        vertex_fill_color="lightgrey",
        vertex_text=builder.occurrences,
        vertex_pen_width=seqan.io.graphtool.root_vertex_property(builder),
        edge_text=seqan.io.graphtool.edge_labels_for_output(builder),
        edge_color=seqan.io.graphtool.color_edges_by_first_symbol(builder),
        edge_end_marker="none",
        edge_pen_width=2,
        edge_dash_style=seqan.io.graphtool.dash_non_suffix_edges(
            builder, suffix),
        #edge_pen_width=builder.edge_lengths,
        output="graphtool.png")
    return builder
示例#2
0
def session_draw_bis_melty(sessions_id, weblog, weblog_columns_dict):
    """
    Draw the graph of sessions with sessions_id given in entry
    """
    from graph_tool.all import Graph
    from graph_tool.all import graph_draw
    session = weblog[weblog.session_id == sessions_id]
    session = session.rename(index=str,columns = {weblog_columns_dict['requested_page_column']:'requested_page',\
                                                  weblog_columns_dict['referrer_page_column']:'referrer_page'})
    s_pages = session[['requested_page', 'requested_external']]
    s_pages_ref = session[['referrer_page', 'referrer_external']]
    s_pages_ref = s_pages_ref.rename(index=str,
                                     columns={
                                         'referrer_page': 'requested_page',
                                         'referrer_external':
                                         'requested_external'
                                     })
    s_pages = s_pages.append(s_pages_ref)
    s_pages.drop_duplicates(subset='requested_page', inplace=True)
    g = Graph()
    v = {}
    halo = g.new_vertex_property("bool")
    for row in s_pages.itertuples():
        v[row.requested_page] = g.add_vertex()
        if row.requested_external:
            halo[v[row.requested_page]] = True
        else:
            halo[v[row.requested_page]] = False
    session.apply(
        lambda x: g.add_edge(v[x.referrer_page], v[x.requested_page]), axis=1)
    graph_draw(g,
               vertex_halo=halo,
               output="./_session" + str(sessions_id) + ".png")
    return
示例#3
0
def visualize(pathFinder, source=False, target=False):
    g, weight = buildWeightedGraph(pathFinder)
    ecolor = g.new_edge_property("string")
    ewidth = g.new_edge_property("double")
    ewidth.a = 1
    touch_v = g.new_vertex_property("bool")
    touch_e = g.new_edge_property("bool")
    if not source:
        source = pathFinder.source
    if not target:
        target = pathFinder.target
    dist, pred = gt.astar_search(
        g,
        source,
        weight,
        VisitorExample(touch_v, touch_e, target),
        heuristic=lambda v: pathFinder.jaccard(v, target))
    for e in g.edges():
        ecolor[e] = "blue" if touch_e[e] else "black"
    v = target
    while v != source:
        p = g.vertex(pred[v])
        for e in v.out_edges():
            if e.target() == p:
                ecolor[e] = "#a40000"
                ewidth[e] = 3
        v = p
    gt.graph_draw(g,
                  output_size=(600, 600),
                  vertex_fill_color=touch_v,
                  edge_color=ecolor,
                  edge_pen_width=ewidth,
                  output="astar-demo.pdf")
示例#4
0
def test_graphtool():
    """Test creating a tree from a suffix tree.
    """
    _num_bases, sequences, _ids = seqan.readFastaDNA(fasta_file('dm01r.fasta'))
    #for s in sequences:
    #    s.remove('T')
    index = seqan.IndexStringDNASetESA(sequences)
    suffix = 'ACGTATGC'
    predicate = seqan.traverse.suffixpredicate(suffix)
    #predicate = seqan.traverse.depthpredicate(4)
    builder = seqan.io.graphtool.Builder(index, predicate=predicate)
    #pos = GT.radial_tree_layout(builder.graph, builder.graph.vertex(0))
    pos = GT.sfdp_layout(builder.graph)
    GT.graph_draw(
        builder.graph,
        pos=pos,
        vertex_size=2,
        vertex_fill_color="lightgrey",
        vertex_text=builder.occurrences,
        vertex_pen_width=seqan.io.graphtool.root_vertex_property(builder),
        edge_text=seqan.io.graphtool.edge_labels_for_output(builder),
        edge_color=seqan.io.graphtool.color_edges_by_first_symbol(builder),
        edge_end_marker="none",
        edge_pen_width=2,
        edge_dash_style=seqan.io.graphtool.dash_non_suffix_edges(builder, suffix),
        #edge_pen_width=builder.edge_lengths,
        output="graphtool.png"
    )
    return builder
示例#5
0
def main():

    conn = sqlite3.connect('../../data/testDefinitions.sqlite')
    g = gt.Graph()
    cursor = conn.cursor()
    cursor.execute('select id, testBed from tests;')
    tests = {}
    ids = []
    for entry in cursor.fetchall():
        tests[entry[0]] = g.add_vertex()

    cursor.execute('select id from testBeds;')

    for entry in cursor.fetchall():
        ids.append(entry[0])

    for id in ids:
        cursor.execute("select tests.id from tests where testBed = '{}'".format(id))

        all_items = cursor.fetchall()
        if len(all_items)  > 1:
            for i in range(0, len(all_items)-1):
                for j in range(i +1, len(all_items)):
                    g.add_edge(tests[all_items[i][0]], tests[all_items[j][0]])

    #g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
    kcore = gt.kcore_decomposition(g)
    #gt.graph_draw(g, vertex_fill_color=kcore, vertex_text=kcore, output="test-testBed.pdf")
    gt.graph_draw(g, vertex_font_size=12, output_size=(800, 600), output="test-testBed.png")
示例#6
0
    def paint_graph(self, location, graph, communities):

        sys.stdout.write('Drawing graph ... ')
        sys.stdout.flush()
        network = gt.Graph(graph, directed=False)
        folder = os.path.abspath(self._output_dir)

        r_cols = randomcolor.RandomColor().generate(count=len(communities) + 1)
        colors = [
            list(int(r_col[1:][i:i + 2], 16) for i in (0, 2, 4))
            for r_col in r_cols
        ]

        color = network.new_vertex_property('int')

        base_color = colors.pop()
        for v in network.vertices():
            color[v] = (base_color[0] << 16) + (
                base_color[1] << 8) + base_color[2]
        for community in communities:
            c = colors.pop()
            for v in community:
                color[v] = (c[0] << 16) + (c[1] << 8) + c[2]
        pos = gt.sfdp_layout(network)
        gt.graph_draw(network,
                      pos=pos,
                      vertex_fill_color=color,
                      output=os.path.join(
                          folder,
                          str(len(communities)) + '_' + location +
                          '_graph-communities.svg'))
        sys.stdout.write('Ok!\n')
        sys.stdout.flush()
def main():
    args = parse_arguments()
    n = args.nodes
    m = args.edges
    seed_number = args.seed
    if seed_number is None:
        seed_number = randint(1000)
    directed = args.directed
    generator = get_graph(args.graph, n, m, directed, seed_number)
    g, source, target = generator.generate()

    print("Source " + str(source) + " Target " + str(target))
    gt.graph_draw(g,
                  edge_pen_width=g.ep.cap,
                  output="graph_initial.pdf",
                  vertex_text=g.vertex_index,
                  edge_text=g.ep.cap)

    solver = get_algorithm(args.algorithm, g)
    solution = solver.get_max_flow(source, target)
    print("The maximum flow is " + str(solution))

    if args.compare:
        generator = get_graph(args.graph, n, m, directed, seed_number)
        g, source, target = generator.generate()
        cap = g.ep.cap
        res = gt.push_relabel_max_flow(g, source, target, cap)
        res.a = cap.a - res.a  # the actual flow
        max_flow = sum(res[e] for e in target.in_edges())

        print("The maximum flow of graph-tool is " + str(max_flow))
def main():

    data = load_test_data("../../data/testDefinitions.sqlite")
    lengths = []
    g = gt.Graph(directed=False)
    vertices = {}

    for test in data.tests.values():
        vertices[test.id] = g.add_vertex()

    for equipment in data.test_equipment.values():
        all_items = []
        for test in data.tests.values():
            if equipment in test.testEquipment:
                all_items.append(test)
        if len(all_items) > 0:
            lengths.append(len(all_items))
        if len(all_items) > 1:

            for i in range(0, len(all_items)-1):
                for j in range(i, len(all_items)-1):
                    if i != j:
                        g.add_edge(vertices[all_items[i].id], vertices[all_items[j].id])

    pos = gt.arf_layout(g, max_iter=4)
    deg = g.degree_property_map("total")
    gt.graph_draw(g, pos=pos,  vertex_fill_color=deg, vorder=deg, vertex_text=deg, output_size=(800, 600), output="test-testEquipment.png")
    plt.hist(lengths)
    plt.title("Equipment-Test Histogram")
    plt.xlabel("Equipment required by X tests.")
    plt.ylabel("Frequency")
    plt.show()
示例#9
0
def layout_and_plot(net, color_pmap, outfile_pre, filename_mod = '.net',
                    size_pmap = None, reverse_colors = False):
    '''
    Plot the net, using a predefined layout if it's included as a vector property.
    :param net: The network to plot.
    :param color_pmap: Property map on `net` to color nodes.
    :size_pmap: Property map on `net` to set size of verticies.  
    :param outfile_pre: Prefix for output filename.
    :param filename_mod: Extension to use on the output filename.
    '''
    # Define a default size
    if size_pmap is None:
        size_pmap = net.new_vertex_property('float', val = 20)
    # If a layout isn't included, calculate it
    if 'layout' not in net.vp:
        print('Calculating graph layout')
        #net.vp['layout'] = gt.fruchterman_reingold_layout(net)
        net.vp['layout'] = gt.sfdp_layout(net, verbose = True)
        #net.vp['layout'] = gt.radial_tree_layout(net, 0, r=2)
    # Set the colormap
    if not reverse_colors:
        colormap = bwr
    else:
        colormap = bwr_r
    # Plot the graph
    gt.graph_draw(net, vertex_fill_color = color_pmap, 
                                vcmap = colormap,
                                vertex_size = size_pmap,
                                edge_pen_width = 1,
                                pos = net.vp['layout'], #pin = True,
                                fit_view = 1,
                                output_size = (2000, 2000),
                                output = outfile_pre + filename_mod + '.png')
    return net.vp['layout']
示例#10
0
def visualize(pathFinder, source=False, target=False):
    g, weight = buildWeightedGraph(pathFinder)
    ecolor = g.new_edge_property("string")
    ewidth = g.new_edge_property("double")
    ewidth.a = 1
    touch_v = g.new_vertex_property("bool")
    touch_e = g.new_edge_property("bool")
    if not source:
        source = pathFinder.source
    if not target:
        target = pathFinder.target
    dist, pred = gt.astar_search(g, source, weight,
                                 VisitorExample(touch_v, touch_e, target),       
                                 heuristic=lambda v: pathFinder.jaccard(v, target))
    for e in g.edges():
        ecolor[e] = "blue" if touch_e[e] else "black"
    v = target
    while v != source:
        p = g.vertex(pred[v])
        for e in v.out_edges():
            if e.target() == p:
                ecolor[e] = "#a40000"
                ewidth[e] = 3
        v = p
    gt.graph_draw(g, output_size=(600, 600), vertex_fill_color=touch_v, edge_color=ecolor,
                  edge_pen_width=ewidth, output="astar-demo.pdf")
示例#11
0
 def display(self, save=0, outputsize=(500, 500), filename=None):
     #gt.graph_draw(self.__Graph, pos=self.__pos, vertex_text=self.__Graph.vertex_index, vertex_fill_color=self.__colors, vertex_shape="pentagon", vertex_font_size=12,
     #    output_size=self.__outputsize)
     #gt.graph_draw(self.__Graph, pos=self.__pos, vertex_fill_color=self.__colors, vertex_shape="hexagon", vertex_font_size=12,
     #    output_size=self.__outputsize, output="../20steps.png")
     if filename is None:
         filename = "../contract.png"
     else:
         filename = "../" + filename + ".png"
     if save == 0:
         gt.graph_draw(
             self.__Graph,
             pos=self.__pos,
             vertex_fill_color=self.__vertex_colors,
             edge_color=self.__edge_colors,
             vertex_shape="hexagon",
             vertex_font_size=12,
             output_size=outputsize,
             #vertex_text=self.__Graph.vertex_index
         )
     else:
         gt.graph_draw(
             self.__Graph,
             pos=self.__pos,
             vertex_fill_color=self.__vertex_colors,
             edge_color=self.__edge_colors,
             vertex_shape="hexagon",
             vertex_font_size=12,
             #vertex_text=self.__Graph.vertex_index,
             output_size=outputsize,
             output=filename)
示例#12
0
    def loop(self):
        
        for m in range(1, self.seq_length+1):
            print ("begin step: ", m)
            tree_prop = self.update_edge_weights()
            tree_cost = self.cost_of_tree(tree_prop)
            self.current_tree = gt.GraphView(self.graph, efilt=tree_prop)

            # draw the best spanning tree yet found every 125 iterations
            if m % 125 == 0:
                position = self.graph_class.position
                self.graph_class.draw(self.best_tree, position)
                
            self.prev_degree = self.degree.copy()
            self.degree = self.current_tree.degree_property_map("total")
            vertex_sum = self.sum_of_vertex_weights()
            bound = tree_cost - 2*vertex_sum
            print("current best bound: ", self.bound)

            
            if m != self.seq_length:
                print( "new bound: ", bound)
                if bound > self.bound:
                    self.bound = bound
                    self.best_tree = self.current_tree
                self.step = self.next_step(m)
                self.update_vertex_weights()
            else:
                print self.bound
                gt.graph_draw(gt.GraphView(self.graph, efilt=tree_prop), self.graph_class.position)
示例#13
0
文件: graph.py 项目: gade-upm/kgraph
def paint_graph(path, graph, communities):
    if path:
        sys.stdout.write('Drawing graph ... ')
        sys.stdout.flush()
        network = gt.Graph(graph, directed=False)
        folder = os.path.abspath(path)
        # colors = random.sample(range(100,151), len(communities))
        r_cols = randomcolor.RandomColor().generate(count=len(communities) + 1)
        colors = [
            list(int(r_col[1:][i:i + 2], 16) for i in (0, 2, 4))
            for r_col in r_cols
        ]

        # color = graph.new_vertex_property('vector<float>')
        color = network.new_vertex_property('int')

        base_color = colors.pop()
        for v in network.vertices():
            color[v] = (base_color[0] << 16) + (
                base_color[1] << 8) + base_color[2]
        for community in communities:
            c = colors.pop()
            for v in community:
                color[v] = (c[0] << 16) + (c[1] << 8) + c[2]
        pos = gt.sfdp_layout(network)
        gt.graph_draw(network,
                      pos=pos,
                      vertex_fill_color=color,
                      output=os.path.join(folder, 'graph-communities.svg'))
        sys.stdout.write('Ok!\n')
        sys.stdout.flush()
示例#14
0
def main():

    conn = sqlite3.connect('../../data/testDefinitions.sqlite')
    g = gt.Graph()
    cursor = conn.cursor()
    cursor.execute('select id, testBed from tests;')
    tests = {}
    ids = []
    for entry in cursor.fetchall():
        tests[entry[0]] = g.add_vertex()

    cursor.execute('select id from testBeds;')

    for entry in cursor.fetchall():
        ids.append(entry[0])

    for id in ids:
        cursor.execute(
            "select tests.id from tests where testBed = '{}'".format(id))

        all_items = cursor.fetchall()
        if len(all_items) > 1:
            for i in range(0, len(all_items) - 1):
                for j in range(i + 1, len(all_items)):
                    g.add_edge(tests[all_items[i][0]], tests[all_items[j][0]])

    #g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
    kcore = gt.kcore_decomposition(g)
    #gt.graph_draw(g, vertex_fill_color=kcore, vertex_text=kcore, output="test-testBed.pdf")
    gt.graph_draw(g,
                  vertex_font_size=12,
                  output_size=(800, 600),
                  output="test-testBed.png")
def label_graph(instance, i, use_simplicial):
    edges = np.genfromtxt("res/new_synthetic/" + instance + ".csv",
                          delimiter=",",
                          dtype=np.int)[:, :2]
    n = np.max(edges - 1)
    g = gt.Graph(directed=False)
    g.add_vertex(n)
    g.add_edge_list(edges)

    #print(edges)

    #print(np.sort(g.degree_property_map("total").a))

    A, B = florians_procedure(g, use_simplicial)

    pos = np.where(A)[0]
    pos = g.new_vertex_property("bool", vals=A)

    simplicial_string = "_simplicial_start"
    if not use_simplicial:
        simplicial_string = ""
    file = open(
        "res/new_synthetic/labels/" + instance + "_" + str(i) +
        simplicial_string + "_positive.csv", 'w')
    writer = csv.writer(file)
    writer.writerows(np.where(A)[0].reshape((-1, 1)))
    #print(len(np.where(A)[0])/n)
    gt.graph_draw(g,
                  pos=gt.arf_layout(g, max_iter=0),
                  vertex_fill_color=pos,
                  output="res/new_synthetic/images/" + instance + "_" +
                  str(i) + "_" + simplicial_string + ".svg")
示例#16
0
def plot_graph(graph, path, edge_weights=None, vertex_weights=None):
    graph_draw(graph,
               output_size=(1000, 1000),
               output=path,
               bg_color=[1, 1, 1, 1],
               edge_pen_width=edge_weights,
               vertex_size=vertex_weights)
示例#17
0
 def DrawDependencies(self):
     gt.graph_draw(self.__g,
                   vertex_text=self.__vert_name,
                   vertex_font_size=2,
                   vertex_shape="double_circle",
                   vertex_fill_color="#729fcf",
                   vertex_pen_width=1,
                   output="{0}.pdf".format("dependency_graph"))
示例#18
0
    def worker(Graph,current_count):

        U = gt.GraphView(Graph,vfilt=lambda v: Graph.vertex_properties['alive'][v])

        gt.graph_draw(U, U.vertex_properties['position'],
                 vertex_shape=U.vertex_properties['shape'],
                 vertex_fill_color=U.vertex_properties['fillcolor'],
                 output=frame_path + 'taxi%06d.png'%count,bg_color=(1,1,1,1),output_size=resolution)
示例#19
0
 def vis_prm(self, name="prm"):
     gt.graph_draw(self._g,
                   vertex_text=self._g.vertex_index,
                   vertex_font_size=2,
                   vertex_shape="double_circle",
                   vertex_fill_color="#729fcf",
                   vertex_pen_width=1,
                   output="{0}.pdf".format(name))
示例#20
0
文件: plot.py 项目: johnlees/PopPUNK
def drawMST(mst, outPrefix, isolate_clustering, clustering_name, overwrite):
    """Plot a layout of the minimum spanning tree

    Args:
        mst (graph_tool.Graph)
            A minimum spanning tree
        outPrefix (str)
            Output prefix for save files
        isolate_clustering (dict)
            Dictionary of ID: cluster, used for colouring vertices
        clustering_name (str)
            Name of clustering scheme to be used for colouring
        overwrite (bool)
            Overwrite existing output files
    """
    import graph_tool.all as gt
    graph1_file_name = outPrefix + "/" + os.path.basename(
        outPrefix) + "_mst_stress_plot.png"
    graph2_file_name = outPrefix + "/" + os.path.basename(
        outPrefix) + "_mst_cluster_plot.png"
    if overwrite or not os.path.isfile(graph1_file_name) or not os.path.isfile(
            graph2_file_name):
        sys.stderr.write("Drawing MST\n")
        pos = gt.sfdp_layout(mst)
        if overwrite or not os.path.isfile(graph1_file_name):
            deg = mst.degree_property_map("total")
            deg.a = 4 * (np.sqrt(deg.a) * 0.5 + 0.4)
            ebet = gt.betweenness(mst)[1]
            ebet.a /= ebet.a.max() / 50.
            eorder = ebet.copy()
            eorder.a *= -1
            gt.graph_draw(mst,
                          pos=pos,
                          vertex_size=gt.prop_to_size(deg, mi=20, ma=50),
                          vertex_fill_color=deg,
                          vorder=deg,
                          edge_color=ebet,
                          eorder=eorder,
                          edge_pen_width=ebet,
                          output=graph1_file_name,
                          output_size=(3000, 3000))
        if overwrite or not os.path.isfile(graph2_file_name):
            cluster_fill = {}
            for cluster in set(isolate_clustering[clustering_name].values()):
                cluster_fill[cluster] = list(np.random.rand(3)) + [0.9]
            plot_color = mst.new_vertex_property('vector<double>')
            mst.vertex_properties['plot_color'] = plot_color
            for v in mst.vertices():
                plot_color[v] = cluster_fill[
                    isolate_clustering[clustering_name][mst.vp.id[v]]]

            gt.graph_draw(
                mst,
                pos=pos,
                vertex_fill_color=mst.vertex_properties['plot_color'],
                output=graph2_file_name,
                output_size=(3000, 3000))
示例#21
0
def print_groups(network, groups):
    group_vp = network.new_vertex_property("int")
    for i, group in enumerate(groups):
        for agent in group:
            group_vp[network.vertex_index[agent]] = i      
    network.vp.group = group_vp
    pos = gt.sfdp_layout(network)
    gt.graph_draw(network, pos=pos, vertex_fill_color=group_vp)
    plt.show()
示例#22
0
def influencer_network_anlaysis(year=2020):
    path_2016 = '/home/crossb/packaged_ci/graphs/2016/'
    path_2020 = '/home/crossb/packaged_ci/graphs/2020/'
    top_n_influencers = 30
    biased_graphs = load_graphs_gt(path_2020)
    biased_influencers = top_influencers(top_n_influencers, biased_graphs)
    influencer_network = top_influencer_network(biased_graphs, biased_influencers)
    #influencer_network.save(os.path.join(WORKING_DIR, 'influencer_network.gt'))
    stats = network_characteristics_gt(influencer_network)
    print("Influencer network stats")
    for stat, value in stats.items():
        print("{}: {}".format(stat, value))

    most_infl_influencers = top_influencers(10, {'top': influencer_network})
    print("Most influential:", most_infl_influencers)


    # save influencer network
    gt.save('data/2020/influencer_network.gt')

    # networkit stats
    nk_graph = load_from_graphtool_nk('data/2020/influencer_network.gt')
    characteristics = network_characteristics_nk(nk_graph, 10)

    for stat, value in characteristics.items():
        if "centrality" in stat:
            print("{}: {}".format(
                stat,
                ','.join(['(Node: {}: {})'.format(influencer_network.vp.user_id[n], v) for (n, v) in value])))
        else:
            print("{}: {}".format(stat, value))

    # Draw with the vertices as pie charts
    vprops = {'pie_fractions': influencer_network.vp.pie_fractions,
              'shape': influencer_network.vp.shape,
              'text': influencer_network.vp.text,
              'text_color': influencer_network.vp.text_color,
              'size': influencer_network.vp.size,
              'pie_colors': influencer_network.vp.pie_colors,
              'text_position': 200,
              'font_size': 14,
              'text_offset': [0.0, 1.0]
              }
    eprops = {'color': 'lightgray'}
    # r=1000 leads to cool graph
    #pos = gt.fruchterman_reingold_layout(influencer_network, r=35.0, circular=True, n_iter=2000)
    pos = gt.arf_layout(influencer_network, d=4, max_iter=0)
    gt.graph_draw(influencer_network, pos=pos, vprops=vprops,
                  eprops=eprops, output='top_influencers.svg')
    #with cairo.SVGSurface('top_influencers.svg', 1024, 1280) as surface:
    #    cr = cairo.Context(surface)
    #    gt.cairo_draw(influencer_network, pos, cr, vprops=vprops, eprops=eprops,
    #                  ecmap=(cm.get_cmap(), 0.2),
    #                  output='top_influencers.svg')

    return
示例#23
0
 def draw_graph_label_id(self,dgraph,path):
     dgraph.vertex_properties["show"] = dgraph.new_vertex_property("string")
     for v in dgraph.vertices():
             if v in self.border_node:
                 tmpstr = "o"+str(v)+dgraph.vertex_properties["label"][v]
             else:
                 tmpstr = str(v)+dgraph.vertex_properties["label"][v]
             dgraph.vertex_properties["show"][v] =tmpstr
     gt.graph_draw(dgraph, vertex_text = dgraph.vertex_properties["show"],output_size=(800, 800),output = path)
     del dgraph.vertex_properties["show"]
示例#24
0
文件: graph.py 项目: gade-upm/kgraph
def paint_full_graph(path, graph, name):
    if path:
        sys.stdout.write('Drawing full graph ... ')
        sys.stdout.flush()
        network = gt.Graph(graph, directed=False)
        gt.graph_draw(network,
                      output=os.path.join(os.path.abspath(path),
                                          str(name) + '-graph.svg'))
        sys.stdout.write('Ok!\n')
        sys.stdout.flush()
示例#25
0
def draw_similarity_graph(g):
    state = minimize_blockmodel_dl(g)
    b = state.b
    pos = sfdp_layout(g, eweight=g.edge_properties['sim'])
    graph_draw(g, pos, output_size=(1000, 1000), vertex_color=[1, 1, 1, 0],
               vertex_size=g.vertex_properties['freq'], edge_pen_width=1.2,
               vcmap=matplotlib.cm.gist_heat_r, output="word_similarity.png")

    state = minimize_blockmodel_dl(g)
    graph_draw(g, pos=pos, vertex_fill_color=b, vertex_shape=b, output="blocks_mdl.png")
示例#26
0
 def draw_graph(self):
     g = self.arcgraph
     pos = gt.sfdp_layout(self.arcgraph)
     gt.graph_draw(g,
                   pos,
                   output_size=(10000, 10000),
                   vertex_fill_color=g.vp.color,
                   edge_pen_width=10,
                   output=join('/mnt', 'g', 'LisaDaten', 'Paper2',
                               'figures', 'arcgraph' + self.name + '.pdf'))
def draw_graph(graph,
               value_map=None,
               output=None,
               show_ids=False,
               directed=False,
               position=None):

    gt_graph = gt.Graph(directed=directed)

    node_map = {node: gt_graph.add_vertex() for node in graph}

    if not directed:
        seen_edges = set()

    for node, edges in graph.iteritems():
        i = node_map[node]
        for e in edges:
            j = node_map[e]

            if directed:
                gt_graph.add_edge(i, j)
            else:
                if (j, i) not in seen_edges:
                    gt_graph.add_edge(i, j)
                    seen_edges.add((i, j))

    if position is None:
        position = gt.sfdp_layout(gt_graph)

    node_label = gt_graph.new_vertex_property("string")

    if value_map is not None:
        for id, value in value_map.iteritems():
            node = node_map[id]
            node_label[node] = id

        for id in graph:
            if id not in value_map:
                node = node_map[id]
                node_label[node] = id

    elif show_ids:
        for id in graph:
            node = node_map[id]
            node_label[node] = id

    if show_ids:
        gt.graph_draw(gt_graph,
                      pos=position,
                      vertex_text=node_label,
                      output=output)
    else:
        gt.graph_draw(gt_graph, pos=position, output=output)

    return position
示例#28
0
def main():
    input_fasta = sys.argv[3]
    K = int(sys.argv[1])
    x = float(sys.argv[2])

    ht = khmer.Nodegraph(K, x, 4)

    sparse_graph = gt.Graph()
    hashes = sparse_graph.new_vertex_property("long long")

    for n, record in enumerate(screed.open(input_fasta)):
        if n % 1000 == 0:
            print('...loaded and tagged {} sequences'.format(n),
                  file=sys.stderr)
        name = record.name
        sequence = record.sequence

        ht.consume_sequence_and_tag_with_labels(sequence, n)
        tags = ht.sweep_tag_neighborhood(sequence, 0)
        for i in range(len(tags) - 1):
            src = tags[i]
            dst = tags[i + 1]

            new = False

            srcv = gt.find_vertex(sparse_graph, hashes, src)
            if not srcv:
                srcv = sparse_graph.add_vertex()
                hashes[srcv] = src
                new = True
            else:
                srcv = srcv[0]

            dstv = gt.find_vertex(sparse_graph, hashes, dst)
            if not dstv:
                dstv = sparse_graph.add_vertex()
                hashes[dstv] = dst
                new = True
            else:
                dstv = dstv[0]

            if new:
                e = sparse_graph.add_edge(srcv, dstv)

    print('Sparse graph has {} nodes, {} edges'.format(
        sparse_graph.num_vertices(), sparse_graph.num_edges()))
    comp = gt.label_largest_component(sparse_graph, directed=False)
    #pos = gt.radial_tree_layout(sparse_graph, sparse_graph.vertex(0))
    gt.graph_draw(sparse_graph,
                  output_size=(5000, 5000),
                  output=input_fasta + '_sparse.png')
    sparse_graph.set_vertex_filter(comp)
    gt.graph_draw(sparse_graph,
                  output_size=(5000, 5000),
                  output=input_fasta + '_sparse_comp.png')
示例#29
0
def draw_graph_heatmap(graph, value_map, output, directed=False, palette=sns.cubehelix_palette(10, start=.5, rot=-.75), position=None):

  # for normalize
  values = value_map.values()

  maxv = max(values)
  minv = min(values)

  if len(values) != len(graph):
    # some graph nodes missing from map.
    # make them 0
    minv = min(minv, 0)

  gt_graph = gt.Graph(directed=directed)

  node_map = {node: gt_graph.add_vertex() for node in graph}

  if not directed:
    seen_edges = set()

  for node, edges in graph.iteritems():
    i = node_map[node]
    for e in edges:
      j = node_map[e]

      if directed:
        gt_graph.add_edge(i, j)
      else:
        if (j, i) not in seen_edges:
          gt_graph.add_edge(i, j)
          seen_edges.add((i, j))

  node_intensity = gt_graph.new_vertex_property("vector<float>")
  node_label = gt_graph.new_vertex_property("string")

  for id, value in value_map.iteritems():
    node = node_map[id]
    node_intensity[node] = find_color(value, maxv, minv, palette)
    node_label[node] = id

  for id in graph:
    if id not in value_map:
      node = node_map[id]
      node_intensity[node] = find_color(0, maxv, minv, palette)
      node_label[node] = id

  if position is None:
    position = gt.sfdp_layout(gt_graph)

  gt.graph_draw(gt_graph, pos=position,
                vertex_text=node_label,
                vertex_fill_color=node_intensity,
                output=output)

  return position
示例#30
0
def render(g, eprop, nprop, graph_name, pos):
    gt.graph_draw(
        g,
        # vertex_size=nprop,
        # edge_pen_width=eprop,
        edge_color=eprop,
        vertex_color=nprop,
        bg_color=(1, 1, 1, 1),
        output="{}.png".format(graph_name),
        output_size=(900, 800),
        pos=pos)
示例#31
0
    def plot(self):

        layout = arf_layout(self.view)
        # also arf_layout? not sure how easy is to draw a tree with multiple roots
        # if we want to see features there

        self.ax.set_axis_off()

        graph_draw(self.view, pos=layout, mplfig=self.ax)
        logger.debug("Plot done")
        plt.savefig(self._get_plot_file())
示例#32
0
    def collect_info(self, nType, sbm_graph, highest_l, state, draw=False):
        """
        Retrieve the partitions, number of groups, and entropies for the hyperlink layer 
        of the network.

        Parameters:
        nType: String for type of network (hyperlink, 2-layer-hyperlink-word, 3-layer-hyperlink-word-tag)
        """
        partitions = []
        num_of_groups = []
        entropies = []
        block_SBM_partitions = {
        }  # store dictionary to map nodes to partition.

        # Due to NP-hardness of retrieving optimal partitions, repeat process numerous times.
        for i in range(len(self.seeds)):
            try:
                b = state.project_level(highest_l[i]).get_blocks()
                # Store dictionary of partitions
                if nType == "hSBM":
                    # Only contains hyperlink SBM.
                    for node in sbm_graph.vertices():
                        block_SBM_partitions[sbm_graph.vp.name[node]] = b[node]
                else:
                    # Need to specify to retrieve partitions for document nodes.
                    for node in sbm_graph.vertices():
                        if sbm_graph.vp['kind'][node] == 0:
                            block_SBM_partitions[
                                sbm_graph.vp.name[node]] = b[node]
                # Retrieve the partition from the SBM and store as parameter.
                partition = self.hyperlink_graph.vp[
                    "partition"] = self.hyperlink_graph.new_vp("int")
                # Assign partition label to node properties.
                for v in self.hyperlink_graph.vertices():
                    partition[v] = block_SBM_partitions[
                        self.hyperlink_graph.vp.name[v]]

                # Print output of graph
                if draw:
                    # Visualise graph
                    print(f"{i}: {state}")
                    gt.graph_draw(
                        self.hyperlink_graph,
                        pos=self.hyperlink_graph.vp.pos,
                        vertex_fill_color=self.hyperlink_graph.vp.partition)

                # Add in results.
                partitions.append(list(self.hyperlink_graph.vp.partition))
                num_of_groups.append(len(set(block_SBM_partitions.values())))
                entropies.append(state.entropy())
            except (FileNotFoundError) as e:
                pass

        return (partitions, num_of_groups, entropies)
示例#33
0
    def saveSimulation(self):

        if not os.path.isdir(OUTPUT_DIR):
            os.mkdir(OUTPUT_DIR)
        if not os.path.isdir(SIMULATIONS_DIR):
            os.mkdir(SIMULATIONS_DIR)

        simulation_dir = SIMULATIONS_DIR + "s_" + self.simulation_id + "/"
        os.mkdir(simulation_dir)
        evolution_img_dir = simulation_dir + "evolution_imgs/"
        os.mkdir(evolution_img_dir)

        self.__exportSimulationOutputAsXML(dir=simulation_dir)

        # exports graph structure  in xml: key0 and key1 are respectively opinion property and opinion color property
        self.original_graph.save(simulation_dir + "graph.xml")

        # 0%, 25%, 50%, 75%, 100%
        steps = [0]
        steps.append(int(self.rounds / 100 * 25))
        steps.append(int(self.rounds / 100 * 50))
        steps.append(int(self.rounds / 100 * 75))
        steps.append(self.rounds)

        layout = gt.sfdp_layout(self.original_graph)
        gt.graph_draw(self.original_graph,
                      pos=layout,
                      vertex_text=self.original_graph.vertex_index,
                      vertex_text_color=(1, 1, 1, 1),
                      edge_color=(1, 1, 1, 0.7),
                      output=simulation_dir + "graph.png",
                      output_size=(1600, 1600),
                      adjust_aspect=False,
                      bg_color=(0.09411764705882353, 0.11372549019607843,
                                0.15294117647058825, 1))

        # prints graph evolution in .png
        for step in steps:
            opinion = self.evolutionMap[step][0]
            opinion_color = self.evolutionMap[step][1]
            gt.graph_draw(self.original_graph,
                          pos=layout,
                          vertex_color=(1, 1, 1, 0),
                          vertex_fill_color=opinion_color,
                          vertex_text=opinion,
                          vertex_text_color=(1, 1, 1, 1),
                          edge_color=(1, 1, 1, 0.7),
                          output=evolution_img_dir + "round-" + str(step) +
                          ".png",
                          output_size=(1600, 1600),
                          adjust_aspect=False,
                          bg_color=(0.09411764705882353, 0.11372549019607843,
                                    0.15294117647058825, 1))
示例#34
0
    def worker(Graph, current_count):

        U = gt.GraphView(Graph,
                         vfilt=lambda v: Graph.vertex_properties['alive'][v])

        gt.graph_draw(U,
                      U.vertex_properties['position'],
                      vertex_shape=U.vertex_properties['shape'],
                      vertex_fill_color=U.vertex_properties['fillcolor'],
                      output=frame_path + 'taxi%06d.png' % count,
                      bg_color=(1, 1, 1, 1),
                      output_size=resolution)
示例#35
0
def draw_cluster_save(graph, path=Path.cwd(), resolution=(4000, 4000)):
    pos = gt.sfdp_layout(graph, p=1)
    if path.is_dir(): path = path.joinpath(datetime.now().isoformat() + '.png')
    fill_color = _fill_vertex_color(graph)
    gt.graph_draw(graph,
                  pos=pos,
                  vertex_size=9,
                  vertex_fill_color=fill_color,
                  bg_color=(1, 1, 1, 1),
                  output_size=resolution,
                  output=str(path))
    return
示例#36
0
 def draw(self):
   res = gt.max_independent_vertex_set(self.graph)
   gt.graph_draw(
     self.graph,
     vertex_pen_width=2,
     edge_pen_width=4,
     vertex_fill_color=res,
     vertex_text=self.graph.vp['name'],
     vertex_font_size=10,
     vcmap=matplotlib.cm.plasma,
     output='../graph_named.png'
   )
示例#37
0
 def show_gt(self):
     """
     Display current state of the network without animation.
     """
     self.set_properties()
     vprops = self.vert_prop
     eprops = self.edge_prop
     gt.graph_draw(self.g,
                   pos=self.pos,
                   eprops=eprops,
                   vprops=vprops,
                   output_node=(1000, 500))
示例#38
0
 def initialize_step(self):
     tree_prop = gt.min_spanning_tree(self.graph, weights = self.e_weights)
     tree = gt.GraphView(self.graph, efilt=tree_prop)
     gt.graph_draw(tree, self.graph_class.position)
     self.best_tree = tree
     tree_cost = 0
     
     for e in tree.edges():
         tree_cost += self.e_weights[e]
         
     t = (1/(2.0*self.graph_class.size)) * tree_cost
     return t
示例#39
0
def main():
    input_fasta = sys.argv[3]
    K = int(sys.argv[1])
    x = float(sys.argv[2])
    
    ht = khmer.new_hashbits(K, x, 4)

    sparse_graph = gt.Graph()
    hashes = sparse_graph.new_vertex_property("long long")


    for n, record in enumerate(screed.open(input_fasta)):
        if n % 1000 == 0:
            print >>sys.stderr, '...loaded and tagged {} sequences'.format(n)
        name = record.name
        sequence = record.sequence

        ht.consume_sequence_and_tag_with_labels(sequence, n)
        tags = ht.sweep_tag_neighborhood(sequence, 0)
        for i in xrange(len(tags) - 1):
            src = tags[i]
            dst = tags[i + 1]

            new = False

            srcv = gt.find_vertex(sparse_graph, hashes, src)
            if not srcv:
                srcv = sparse_graph.add_vertex()
                hashes[srcv] = src
                new = True
            else:
                srcv = srcv[0]

            dstv = gt.find_vertex(sparse_graph, hashes, dst)
            if not dstv:
                dstv = sparse_graph.add_vertex()
                hashes[dstv] = dst
                new = True
            else:
                dstv = dstv[0]

            if new:
                e = sparse_graph.add_edge(srcv, dstv)

    print 'Sparse graph has {} nodes, {} edges'.format(sparse_graph.num_vertices(), sparse_graph.num_edges())
    comp = gt.label_largest_component(sparse_graph, directed=False)
    #pos = gt.radial_tree_layout(sparse_graph, sparse_graph.vertex(0))
    gt.graph_draw(sparse_graph, output_size=(
        5000, 5000), output=input_fasta + '_sparse.png')
    sparse_graph.set_vertex_filter(comp)
    gt.graph_draw(sparse_graph, output_size=(
        5000, 5000), output=input_fasta + '_sparse_comp.png')
def show():
	g = gt.load_graph(filename)
	kwargs = {}
	print 'Graph loaded, now drawing to %s' % imagename

	if 'blocks' in g.vp:
		kwargs['vertex_fill_color'] = g.vertex_properties['blocks']
	if 'rank' in g.vp:
		kwargs['vertex_size'] = gt.prop_to_size(g.vp['rank'], mi=5, ma=15)
	if 'pos' in g.vp:
		kwargs['pos'] = g.vp['pos']

	gt.graph_draw(g, vertex_shape=g.vp['rc'], output=imagename, **kwargs)
示例#41
0
def main(text, keyword):
    words, keyword = tokenize(text, keyword)
    print u' | '.join(words)

    mst, root = create_mst(words, keyword)
    weights_str_ep = mst.new_edge_property('string')
    weights_ep = mst.ep['weights']
    for e in mst.edges():
        weights_str_ep[e] = str(weights_ep[e])
    gt.graph_draw(mst,
                  vertex_text=mst.vp['words'],
                  edge_text=weights_str_ep,
                  output_size=(1111, 1111),
                  output='mst.png')
示例#42
0
def draw_graph(graph, value_map=None, output=None, show_ids=False, directed=False, position=None):

  gt_graph = gt.Graph(directed=directed)

  node_map = {node: gt_graph.add_vertex() for node in graph}

  if not directed:
    seen_edges = set()

  for node, edges in graph.iteritems():
    i = node_map[node]
    for e in edges:
      j = node_map[e]

      if directed:
        gt_graph.add_edge(i, j)
      else:
        if (j, i) not in seen_edges:
          gt_graph.add_edge(i, j)
          seen_edges.add((i, j))

  if position is None:
    position = gt.sfdp_layout(gt_graph)

  node_label = gt_graph.new_vertex_property("string")

  if value_map is not None:
    for id, value in value_map.iteritems():
      node = node_map[id]
      node_label[node] = id

    for id in graph:
      if id not in value_map:
        node = node_map[id]
        node_label[node] = id

  elif show_ids:
      for id in graph:
        node = node_map[id]
        node_label[node] = id

  if show_ids:
    gt.graph_draw(gt_graph, pos=position,
                  vertex_text=node_label,
                  output=output)
  else:
    gt.graph_draw(gt_graph, pos=position, output=output)

  return position
示例#43
0
def draw2(g, h, t, output, pos=None):
  g = gt.GraphView(g, efilt=lambda e: h[e] or t[e])
  
  print('{} {}'.format(output, 2*g.num_edges()/g.num_vertices()))

  width = g.new_edge_property('double')
  color = g.new_edge_property('vector<double>')
  
  for e in g.edges():
    width[e] = 1.6 if h[e] else 0.8
    color[e] = (0.1,0.9,0.1,1) if h[e] and t[e] else (0.9,0.1,0.1,1) if t[e] else (0,0,0,1)
  
  gt.graph_draw(g, pos=pos,
    vertex_size=8, vertex_color='black', vertex_fill_color='black',
    edge_pen_width=1.6, edge_color=color,
    output_size=(500, 500), output=output, bg_color=[1,1,1,1])
示例#44
0
    def build_graph(self):
        logging.info('Building graph')
        import graph_tool.all as GT
        graph = GT.Graph(directed=False)
        vertices = dict()
        names = graph.new_vertex_property('string')
        shapes = graph.new_vertex_property('string')
        colours = graph.new_vertex_property('string')

        def get_vertex(name, shape, colour):
            if name in vertices:
                return vertices[name]
            else:
                vertex = graph.add_vertex()
                names[vertex] = name
                shapes[vertex] = shape
                colours[vertex] = colour
                vertices[name] = vertex
                return vertex

        def get_word_vertex(name):
            return get_vertex(name, 'circle', 'blue')

        def get_topic_vertex(name):
            return get_vertex(name, 'square', 'red')

        def get_document_vertex(name):
            return get_vertex(name, 'triangle', 'green')

        for k in range(self.statistics.num_topics_used):
            name = 'TP: %d' % k
            topic_vertex = get_topic_vertex(name)
            for w in self.statistics.words_for_topic(k):
                word_vertex = get_word_vertex('Word: %d' % w)
                graph.add_edge(word_vertex, topic_vertex)
            for d in self.statistics.documents_for_topic(k):
                doc_vertex = get_document_vertex('Doc: %d' % d)
                graph.add_edge(topic_vertex, doc_vertex)

        pos = GT.sfdp_layout(graph)
        GT.graph_draw(
            graph,
            pos=pos,
            vertex_shape=shapes,
            vertex_fill_color=colours)

        return graph, vertices, shapes, colours
def draw_graph_frame((graph, dir_name, number)):
    vertices_filter = graph.new_vertex_property('bool')

    for i in xrange(len(vertices_filter.a)):
        if i < number:
            vertices_filter.a[i] = True
        else:
            vertices_filter.a[i] = False

    graph.set_vertex_filter(vertices_filter)
    graph_draw(
        graph,
        pos=graph.vertex_properties['pos'],
        vertex_fill_color=graph.vertex_properties['pagerank'],
        vertex_size=5,
        output_size=(1024, 1024),
        output=dir_name + str(number) + '.png')
def rysuj_wejscie(input_file, output=None, size=(600, 600)):
    rozszerzenie = input_file.split('.')[1]
    g2 = load_graph(input_file)
    g2.vertex_properties['wyswietlany_tekst'] = g2.new_vertex_property('string')

    if rozszerzenie == 'dot':
        for v in g2.vertices():
            g2.vertex_properties['wyswietlany_tekst'][v] = v.__str__() + ': ' + \
                                                           g2.vertex_properties['liczba_kolorow'][v]
    elif rozszerzenie == 'xml' or 'graphml':
        for v in g2.vertices():
            g2.vertex_properties['wyswietlany_tekst'][v] = v.__str__() + ': ' + \
                                                           str(g2.vertex_properties['liczba_kolorow'][v])

    graph_draw(g2, vertex_text=g2.vertex_properties['wyswietlany_tekst']
               , bg_color=[255., 255., 255., 1]
               , output_size=size
               , output=output
               )
def draw_graph(graph):
    vertices_names = graph.new_vertex_property('string')

    for vertex in graph.vertices():
        vertices_names[vertex] = \
            graph.vertex_properties['actors_on_vertices'][vertex] + \
            ' ' + str(graph.vertex_properties['pagerank'][vertex])

    pos = sfdp_layout(graph, eweight=graph.edge_properties['weights_on_edges'])

    graph_draw(
        graph,
        pos=pos,
        vertex_fill_color=graph.vertex_properties['pagerank'],
        vertex_text=vertices_names,
        vertex_font_size=5,
        output_size=(1024, 1024),
        output='pagerank/' +
        graph.graph_properties['repo_on_graph'].replace('/', '%') + '.pdf')
def rysuj_graf_wejsciowy(g, output=None, size=(600, 600), bez_napisow=False):
    gx = Graph(g)
    gx.vertex_properties['wyswietlany_tekst'] = gx.new_vertex_property('string')

    for v in gx.vertices():
        gx.vertex_properties['wyswietlany_tekst'][v] = v.__str__() + ': ' + \
                                                       str(gx.vertex_properties['liczba_kolorow'][v])
    if bez_napisow:
        graph_draw(gx
                   # , vertex_text=gx.vertex_properties['wyswietlany_tekst']
                   , bg_color=[255., 255., 255., 1]
                   , output_size=size
                   , output=output
                   )
    else:
        graph_draw(gx
                   , vertex_text=gx.vertex_properties['wyswietlany_tekst']
                   , bg_color=[255., 255., 255., 1]
                   , output_size=size
                   , output=output
                   )
示例#49
0
def test1():
    gt.seed_rng(42)
    seed(42)
    NUMBER_OF_NODES = 20
    points = random((NUMBER_OF_NODES, 2))
    points[0] = [0, 0]
    points[1] = [1, 1]
    g, pos = gt.triangulation(points, type="delaunay")
    g.set_directed(True)
    edges = list(g.edges())
    # reciprocate edges
    for e in edges:
       g.add_edge(e.target(), e.source())
    # The capacity will be defined as the inverse euclidean distance
    cap = g.new_edge_property("double")
    for e in g.edges():
        cap[e] = min(1.0 / norm(pos[e.target()].a - pos[e.source()].a), 10)
    g.edge_properties["cap"] = cap
    g.vertex_properties["pos"] = pos
    g.save("flow-example.xml.gz")
    gt.graph_draw(g, pos=pos, edge_pen_width=gt.prop_to_size(cap, mi=0, ma=3, power=1),
                  output="flow-example.pdf")
 def draw_radial_graph(self,
                       output_path,
                       vertex_text=None,
                       vertex_fill_color=[0.640625, 0, 0, 0.9],
                       bg_color=(.75, .75, .75, 1),
                       output_size=(1000, 1000),
                       vcmap=matplotlib.cm.summer,
                       **kwargs):
     """
     Draws the structureGraph as a radial graph to output_path
     :param output_path: path to save the image of the graph to
     :return:
     """
     pos = gt.radial_tree_layout(self.structureGraph, self.structureGraph.vertex(0))
     gt.graph_draw(self.structureGraph,
                   pos=pos,
                   output=output_path,
                   bg_color=bg_color,
                   vertex_text=vertex_text,
                   output_size=output_size,
                   vertex_fill_color=vertex_fill_color,
                   vcmap=vcmap,
                   **kwargs)
示例#51
0
def sfdp_draw(graph, output="lattice_3d.pdf"):
    '''
    Deprecated
    '''
    output = os.path.join('saved_graph/pdf', output)
    sfdp_pos = gt.graph_draw(graph,
                             pos=gt.sfdp_layout(graph,
                                                cooling_step=0.95,
                                                epsilon=1e-3,
                                                multilevel=True),
                             output_size=(300,300),
                             output=output)
    # print 'graph view saved to %s' %output
    return sfdp_pos
示例#52
0
def render(g, file_name, layout):
    # Perform Layout
    pos = get_pos(g, algorithm=layout)

    generate_color_map(g)

    vertex_color = g.new_vertex_property('vector<double>', val=[0, 0, 0, 0])
    vertex_size = g.new_vertex_property('double', val=30)
    vertex_font_size = g.new_vertex_property('int', val=10)
    vertex_font_family = g.new_vertex_property('string', 'helvatica')
    vertex_text_position = g.new_vertex_property('double', val=(math.pi*(2.0/8.0)))
    vertex_text_color = g.new_vertex_property('vector<double>', val=[0.3, 0.3, 0.3, 1.0])

    # Edge properties
    edge_color = g.new_edge_property('vector<double>', val=[0.179, 0.203,
                                                            0.210, 0.9])
    edge_pen_width = g.new_edge_property('double', val=6)
    edge_end_marker = g.new_edge_property('string', val='none')

    gt.graph_draw(g, pos=pos,
                  vertex_color=vertex_color,
                  vertex_fill_color=g.vertex_properties['fill_color'],
                  vertex_shape=g.vertex_properties['shape'],
                  # vertex_text=g.vertex_properties['label'],
                  vertex_font_size=vertex_font_size,
                  vertex_font_family=vertex_font_family,
                  vertex_text_position=vertex_text_position,
                  vertex_text_color=vertex_text_color,
                  vertex_size=vertex_size,

                  edge_color=edge_color,
                  edge_pen_width=edge_pen_width,
                  edge_end_marker=edge_end_marker,
                  output_size=(1600, 1600), output=file_name)

    return file_name
示例#53
0
def pseudo3d_draw(graph, rtz, output="lattice_3d.pdf",
                  z_angle=0.12, theta_rot=0.1,
                  RGB=(0.8, 0.1, 0.), **kwargs):
    '''
    Deprecated
    '''
    rhos, thetas, zeds = rtz
    thetas += theta_rot
    output = os.path.join('saved_graph/pdf', output)
    red, green, blue = RGB

    pseudo_x = graph.new_vertex_property('float')
    pseudo_y = graph.new_vertex_property('float')
    vertex_red = graph.new_vertex_property('float')
    vertex_green = graph.new_vertex_property('float')
    vertex_blue = graph.new_vertex_property('float')
    vertex_alpha = graph.new_vertex_property('float')

    pseudo_x.a = zeds * np.cos(z_angle)\
                 - rhos * np.cos(thetas) * np.sin(z_angle)
    pseudo_y.a = rhos * np.sin(thetas)
    depth = rhos * np.cos(thetas)
    normed_depth = (depth - depth.min()) / (depth.max() - depth.min())
    vertex_alpha.a = normed_depth * 0.7 + 0.3
    vertex_red.a = np.ones(rhos.shape, dtype=np.float) * red
    vertex_green.a = np.ones(rhos.shape, dtype=np.float) * green
    vertex_blue.a = np.ones(rhos.shape, dtype=np.float) * blue
    rgba = [vertex_red, vertex_green, vertex_blue, vertex_alpha]
    pseudo3d_color = gt.group_vector_property(rgba,
                                              value_type='float')

    xy = [pseudo_x, pseudo_y]
    pseudo3d_pos = gt.group_vector_property(xy, value_type='float')
    pmap = gt.graph_draw(graph, pseudo3d_pos,
                         vertex_fill_color=pseudo3d_color,
                         vertex_color=pseudo3d_color,
                         edge_pen_width=2.,
                         output=output, **kwargs)
    del pmap
    return pseudo3d_pos
示例#54
0
        new = False

        srcv = gt.find_vertex(sparse_graph, hashes, src)
        if not srcv:
            srcv = sparse_graph.add_vertex()
            hashes[srcv] = src
            new = True
        else:
            srcv = srcv[0]

        dstv = gt.find_vertex(sparse_graph, hashes, dst)
        if not dstv:
            dstv = sparse_graph.add_vertex()
            hashes[dstv] = dst
            new = True
        else:
            dstv = dstv[0]

        if new:
            e = sparse_graph.add_edge(srcv, dstv)

print 'Sparse graph has {} nodes, {} edges'.format(sparse_graph.num_vertices(), sparse_graph.num_edges())
comp = gt.label_largest_component(sparse_graph, directed=False)
#pos = gt.radial_tree_layout(sparse_graph, sparse_graph.vertex(0))
gt.graph_draw(sparse_graph, output_size=(
    5000, 5000), output=input_fasta + '_sparse.png')
sparse_graph.set_vertex_filter(comp)
gt.graph_draw(sparse_graph, output_size=(
    5000, 5000), output=input_fasta + '_sparse_comp.png')
示例#55
0
def plot_window():
    gt.graph_draw(G, G.vertex_properties['position'],
                  vertex_shape=G.vertex_properties['shape'],
                  vertex_fill_color=G.vertex_properties['fillcolor'],
                  output=base_path + './frames/taxi%06d.png')
示例#56
0
文件: graphGT.py 项目: zutshi/S3CAMR
    def plot(
            self,
            source_list,
            sink_list,
            max_depth,
            max_paths
            ):

        print 'WARNING: This is actually a plotting function!!!'

        num_source_nodes = len(source_list)
        num_sink_nodes = len(sink_list)

        # super_source_vertex = g.add_vertex()
        # super_sink_vertex = g.add_vertex()

        super_source_vertex = 'super_source_vertex'
        super_sink_vertex = 'super_sink_vertex'

        edge_list = zip([super_source_vertex] * num_source_nodes, source_list)
        for e in edge_list:
            self.add_edge(*e)

        edge_list = zip(sink_list, [super_sink_vertex] * num_sink_nodes)
        for e in edge_list:
            self.add_edge(*e)

        g = self.G

        pos = gt.arf_layout(g, max_iter=0)
        gt.graph_draw(g, pos=pos, vertex_text=self.G.vertex_index)
        time.sleep(1000)
        exit()

        gt.graph_draw(self.G, vertex_text=self.G.vertex_index)
        time.sleep(1000)

#        print edge_list

        # Add edges:
        #   \forall sink \in sink_list. sink -> super sink node

        edge_list = zip(sink_list, [dummy_super_sink_node] * num_sink_nodes)
        H.add_edges_from(edge_list)

#        print edge_list

#        print '='*80
        # TODO: WHY?
        # Switching this on with def path_gen(), results in empty path and no further results!!
        # #xplanation required!
#        for path in nx.all_simple_paths(H, dummy_super_source_node, dummy_super_sink_node):
#            print path
#        print '='*80

        # TODO: how to do this with lambda?
        # Also, is this indeed correct?

        def path_gen():
            for i in nx.all_simple_paths(H, dummy_super_source_node,
                    dummy_super_sink_node):

                # Remove the first (super source)
                # and the last element (super sink)

                yield i[1:-1]

        # return lambda: [yield i[1:-1] for i in nx.all_simple_paths(H,
        # dummy_super_source_node, dummy_super_sink_node)]

        return path_gen()
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: lockheed
Information and Electronics Engineering
Huazhong University of science and technology
E-mail:[email protected]
Created on: 3/13/14 9:06 PM

Copyright (C)  lockheedphoenix

"""

import graph_tool.all as gt

"""
20140320 nig
g = gt.load_graph('BA_networks.xml.gz')
pos = gt.arf_layout(g)
g.vertex_properties['pos'] = pos
g.save('BA_networks_2.xml.gz')
"""

g = gt.lattice([40, 40], True)
pos = gt.sfdp_layout(g, cooling_step=0.99, epsilon=1e-3)
g.vertex_properties['pos'] = pos
g.save('3Dlattice.xml.gz')
gt.graph_draw(g, pos)

示例#58
0
文件: __init__.py 项目: wx1988/PMLAB
    def draw(self, filename, engine='graphviz'):
        """Draws the TS. The filename extension determines the format.
        [engine] Rendering engine used to draw the TS. Valid values:
            cairo, graphviz, astg (for draw_astg)
        If [filename] is None and engine is 'cairo', then the interactive 
        window is used"""
        if engine == 'graphviz':
            vprops = {'label':self.vp_state_name}
            eprops = {'label':self.ep_edge_label}
            if 'frequency' in self.g.vertex_properties:
    #            vp_width = self.g.new_vertex_property("float")
                all_traces = self.vp_state_frequency[self.get_state(self.get_initial_state())]
    #            for v in self.g.vertices():
    #                vp_width[v] = 3.0*self.vp_state_frequency[v]/all_traces
    #            vprops['width'] = vp_width
                vsize=(self.vp_state_frequency, 2.0/all_traces)
            else:
                vsize=0.105
            if 'frequency' in self.g.edge_properties:
                all_traces = self.vp_state_frequency[self.get_state(self.get_initial_state())]
                penwidth=(self.ep_edge_frequency, 10.0/all_traces)
            else:
                penwidth=1.0
            print vprops
            if self.g.num_vertices() < 150:
                layout = 'dot'
                overlap = False
            else:
                layout = None
                overlap = 'Prism'
            gt.graphviz_draw(self.g, ratio='auto', vprops=vprops, splines=True,
                            eprops=eprops, sep=1.0, overlap=overlap, vsize=vsize, 
                            penwidth=penwidth, layout=layout, output=filename)
        elif engine=='cairo': #use cairo
            pos = gt.sfdp_layout(self.g)
            vprops = {'text':self.vp_state_name}
            if 'frequency' in self.g.vertex_properties:
                vp_width = self.g.new_vertex_property("float")
                all_traces = self.vp_state_frequency[self.get_state(self.get_initial_state())]
                #use numpy array access 
#                vp_widht.a = int(max(100.0*self.vp_state_frequency.a/all_traces)
                for v in self.g.vertices():
                    vp_width[v] = int(100.0*self.vp_state_frequency[v]/all_traces)
                vprops['size'] = vp_width
            gt.graph_draw(self.g, pos=pos, vprops=vprops, output=filename)
        elif engine=='astg':
            if filename.endswith('.ps'):
                format = '-Fps'
            elif filename.endswith('.gif'):
                format = '-Fgif'
            elif filename.endswith('.dot'):
                format = '-Fdot'
            elif filename.endswith('.png'):
                format = '-Fpng'
            elif filename.endswith('.svg'):
                format = '-Fsvg'
            else:
                raise TypeError, 'Unsupported output for draw_astg'
            #check if file can be forwarded as input_filename 
            if self.filename and not self.modified_since_last_write:
                input_filename = self.filename
            else:
            # or create tmp file with save
                tmpfile = tempfile.NamedTemporaryFile(mode='w', delete=False)
                print "Saving TS to temporary file '{0}'".format( tmpfile.name )
                self.save(tmpfile)
                tmpfile.close()
                input_filename = tmpfile.name
            params = ['draw_astg', '-sg', '-noinfo', format, input_filename]
            output = subprocess.check_output( params )
            with open(filename,'w+b') as f:
                f.write(output)
示例#59
0
# call fastlayout function
start = time.clock()
pos = fl.layout_fr_omp_simd( nodes*dimension, edgelist, max_it, temp )

pos = np.reshape(pos, (nodes, dimension))
pos_prop = g.new_vertex_property('vector<double>')
for v in g.vertices():
    i = g.vertex_index[v]
    pos_prop[v] = pos[i]#[::-1]
    
fastlayout = time.clock()
fastlayout = fastlayout - start
    
# draw the graph in graph_tool
gt.graph_draw(g, pos=pos_prop, output="output/fr-fastlayout.pdf")



# call fastlayout function with new data structure
start = time.clock()
pos = fl.layout_fr_stride_omp_simd( nodes*dimension, edgelist, max_it, temp )

pos = zip(pos[0:nodes], pos[nodes:2*nodes])
pos_prop2 = g.new_vertex_property('vector<double>')
for v in g.vertices():
    i = g.vertex_index[v]
    pos_prop2[v] = pos[i]#[::-1]
    
fastlayout_strided = time.clock()
fastlayout_strided = fastlayout - start
示例#60
0
                grv= self.graph.vertex_properties["rv"][gv]
                given_rvs.append(grv)                
                cpt_dims.append(len(grv.values))
                self.graph.add_edge(gv, v)
            elif node.nodeName == "TABLE":
                cpt_dims.append(len(rv.values))
                table_str= node.childNodes[0].data
                table_vals_str= table_str.split()
                n= len(table_vals_str)
                assert(n == numpy.prod(cpt_dims))
                rv.cpt= numpy.zeros(n)
                for ix in range(n):
                    rv.cpt[ix]= float(table_vals_str[ix])
                rv.cpt.resize(tuple(cpt_dims))
                if (not rv.validateCPT()):
                    raise ValueError('Invalid CPT for' + for_node_name)
                rv.prettyPrintCPT(self.graph)
 
#                       
if __name__== '__main__': 
    """Unit testing
    """
    
    dom = xd.parse("alarm.xmlbif")
    bn= JBN()
    bn.load(dom)
    # visualize the BN graph
    gt.graph_draw(bn.graph, size=(15,15), output="bn.pdf", 
            vprops={"label":bn.graph.vertex_properties["rv"]}, layout="dot", vcolor="white", overlap=False, splines=True,
            ratio="compress", penwidth=2.0)