Ejemplo n.º 1
0
    def sbmplot(self, state):

        state.draw(edge_color=gt.prop_to_size(graph.ep.weight,
                                              power=1,
                                              log=True),
                   ecmap=(plt.cm.inferno, .6),
                   eorder=graph.ep.weight,
                   edge_pen_width=gt.prop_to_size(graph.ep.weight,
                                                  1,
                                                  4,
                                                  power=1,
                                                  log=True),
                   edge_gradient=[])
Ejemplo n.º 2
0
def draw_graph(only_classified_users):
    g = create_graph(only_classified_users, False)

    pos = gt.sfdp_layout(
        g,
        vweight=g.degree_property_map('total'),
        eweight=g.ep.weight,
        groups=g.vp.group,
        multilevel=True,
        gamma=1.0,
        mu_p=0.2,
        weighted_coarse=True,
        coarse_method="hybrid",  # mivs hybrid ec
    )
    return gt.graph_draw(
        g,
        pos=pos,
        vertex_fill_color=g.vp.group,
        vertex_size=gt.prop_to_size(g.degree_property_map('total'),
                                    ma=20,
                                    mi=3),
        edge_color='white',
        edge_pen_width=0.1,
        bg_color=[0.0, 0.0, 0.0, 1.0],
        output_size=[800, 600],
        # vertex_text=g.vp.username,
        # vertex_font_size=8,
        display_props=[g.vp.group_name, g.vp.username]
        #   output=pj(RESOURCE_DIR, 'graph.pdf'),
    )
Ejemplo n.º 3
0
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))
Ejemplo n.º 4
0
def update_state():
    global time
    mark.a = False
    visited.a = False
    g.set_vertex_filter(None)

    # visit the nodes in random order
    vs = list(g.vertices())
    shuffle(vs)
    for v in vs:
        if time - 5 < order[v] < time + 5:
            visited[v] = True
            state[v] = past

        elif time == order[v]:
            visited[v] = True
            mark[v] = True
            state[v] = present
        else:
            visited[v] = False
    # Filter out the recovered vertices
    g.set_vertex_filter(visited)
    size = gt.prop_to_size(g.degree_property_map("total"), ma=10)
    for v in vs:
        vsize[v] = size[v]
    #vsize = gt.prop_to_size(deg)
    gt.sfdp_layout(g,
                   pos=pos,
                   eweight=g.ep['weight'],
                   groups=g.vp['comm_infomap'],
                   max_iter=0)
    print(g.num_vertices())

    # The following will force the re-drawing of the graph, and issue a
    # re-drawing of the GTK window.
    win.graph.fit_to_window(g=g)
    win.graph.regenerate_surface(reset=True)
    win.graph.queue_draw()

    # if doing an offscreen animation, dump frame to disk
    time += 1
    if time > max_time:
        sys.exit(0)
    print(time)
    if offscreen:
        pixbuf = win.get_pixbuf()
        strdate = (initial_date + timedelta(days=time)).strftime('%d-%m-%Y')
        pixbuf = put_text(pixbuf, strdate, 0, 10)
        pixbuf.savev(dir + '/news-date_%06d.png' % time, 'png', [], [])

    # We need to return True so that the main loop will call this function more
    # than once.
    print('-' * 80)
    return True
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)
Ejemplo n.º 6
0
 def save_graph(self, graph_path):
     gt.graph_draw(self.graph,
                   vertex_text=self.graph_vertex_label,
                   pos=self.graph_position,
                   vertex_font_size=18,
                   edge_pen_width=gt.prop_to_size(self.graph_penalty,
                                                  mi=0,
                                                  ma=8,
                                                  power=1),
                   vertex_fill_color=self.graph_vertex_color,
                   edge_color=self.graph_edge_color,
                   output_size=(self.w * 50, self.h * 50),
                   output=graph_path)
Ejemplo n.º 7
0
def plot(G_gt, layout_gt, n_range, palette, **kwargs):  # pylint: disable=unused-argument

    v_text = G_gt.vertex_properties['id']
    # v_degrees_p = G_gt.degree_property_map('out')
    # v_degrees_p.a = np.sqrt(v_degrees_p.a)+2
    v_degrees_p = G_gt.vertex_properties['degree']
    v_size_p = gt.prop_to_size(v_degrees_p, n_range[0], n_range[1])
    v_fill_color = G_gt.vertex_properties['fill_color']
    e_weights = G_gt.edge_properties['weight']
    e_size_p = gt.prop_to_size(e_weights, 1.0, 4.0)
    # state = gt.minimize_blockmodel_dl(G_gt)
    # state.draw(
    # c = gt.all.closeness(G_gt)

    v_blocks = gt.minimize_blockmodel_dl(G_gt).get_blocks()
    plot_color = G_gt.new_vertex_property('vector<double>')
    G_gt.vertex_properties['plot_color'] = plot_color

    for v_i, v in enumerate(G_gt.vertices()):
        scolor = palette[v_blocks[v_i]]
        plot_color[v] = tuple(int(scolor[i : i + 2], 16) for i in (1, 3, 5)) + (1,)

    gt_draw.graph_draw(
        G_gt,
        # vorder=c,
        pos=layout_gt,
        output_size=(1000, 1000),
        # vertex_text_offset=[-1,1],
        vertex_text_position=0.0,
        vertex_text=v_text,
        vertex_color=[1, 1, 1, 0],
        vertex_fill_color=v_fill_color,
        vertex_size=v_size_p,
        vertex_font_family='helvetica',
        vertex_text_color='black',
        edge_pen_width=e_size_p,
        inline=True,
    )
def draw_frames(glist):
    stamp = datetime.strftime(datetime.now(), "%d_%h-%H-%M")
    outpath = f"./outputs_{stamp}"
    if not os.path.exists(outpath):
        os.mkdir(outpath)
    for i, gu in enumerate(glist):
        gt.graph_draw(
            gu,
            pos=gu.vp.pos,
            vertex_fill_color=gu.vp.lum,
            edge_pen_width=0.2,
            vertex_size=gt.prop_to_size(gu.vp.mass, mi=2, ma=10, log=False, power=2),
            output=os.path.join(outpath, "frame%06d.png" % i), adjust_aspect=False
        )
Ejemplo n.º 9
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")
'''#seed_number = randint(1, 1000)
# generator = Random(10, 40, directed=True, seed_number=seed_number)
seed_number = 386
generator = Triangulation(50, type="delaunay", directed=True, seed_number=seed_number)
# generator = Wikipedia()
g, source, target = generator.generate()
print("Source: " + str(source) + " target " + str(target))

gt.graph_draw(g, edge_pen_width=gt.prop_to_size(g.ep.cap, mi=1, ma=5, power=1),
              output="cf/cf_capacities.pdf", vertex_text=g.vertex_index, edge_text=g.ep.cap)'''
#seed_number = randint(1, 1000)
seed_number = 14
generator = Triangulation(50, type="delaunay", directed=True, seed_number=seed_number)
g, source, target = generator.generate()

gt.graph_draw(g, edge_pen_width=gt.prop_to_size(g.ep.cap, mi=1, ma=5, power=1),
              output="cf/cf_capacities.pdf", vertex_text=g.vertex_index, edge_text=g.ep.cap)

# source = g.vertex(0)
# target = g.vertex(3)
solver = Goldberg(g)
solution = solver.get_max_flow(source, target)
print("Il max flow trovato da Golberg è:", solution)

labels = g.new_vertex_property("string")
for vertex in g.vertices():
    labels[vertex] = str(g.vertex_index[vertex]) + "(" + str(g.vp.height[vertex]) + "," + str(
        g.vp.excess[vertex]) + ")"

gt.graph_draw(g, edge_pen_width=gt.prop_to_size(g.ep.residual, mi=1, ma=5, power=1),
              output="cf/max-flow-our-solution.pdf", vertex_text=labels, edge_text=g.ep.residual)
Ejemplo n.º 11
0
def run_analysis(netfile, compnet_files):
    '''
    Run the analysis.  
    :param netfile: Filename of the network to analyze
    :param compnet_files: List of filenames of the comparison networks, viz.,
        the high-energy physics networks.  
    '''
    
    # Timestamp
    # --------------------
    print(datetime.now())
    
    # Load the network
    # --------------------
    net, outfile_pre, core_pmap, core_vertices = load_net(netfile + '.graphml', 
                                                             core = True,
                                                             filter = True)
    output_folder = 'output/'
    outfile_pre = output_folder + outfile_pre
     
    # Plotting
    print('Plotting')
    layout = layout_and_plot(net, core_pmap, outfile_pre)
    # Store the layout in the net
    net.vp['layout'] = layout
    # Show only the core vertices    
    net.set_vertex_filter(core_pmap)
    layout_and_plot(net, core_pmap, outfile_pre, filename_mod = '.core.net', 
    				reverse_colors = True)
    net.set_vertex_filter(None)
    
    # Vertex statistics
    # --------------------
    # ECDF for out-degree distribution
    degree_dist(net, core_vertices, outfile = outfile_pre, 
                show_plot = False, save_plot = True)
    # ECDF for eigenvector centrality
    ## Currently this is causing a segmentation fault
#     ev_centrality_dist(net, core_vertices, outfile = outfile_pre, 
#                 show_plot = False, save_plot = True)
    
    # Modularity
    # --------------------
    # Calculate modularity, using the core vertices as the partition
    modularity = gtcomm.modularity(net, core_pmap)
    print('Observed modularity: ' + str(modularity))
    obs_ins = insularity(net, core_pmap)
    print('Observed insularity: ' + str(obs_ins))
   
    # Calculate the number of core vertices
    n_core = len(core_vertices)
    # Construct a sampling distribution for the modularity statistic
    #  And use it to calculate a p-value for the modularity
    print('Random sample modularity')
    modularity_sample_dist(net, n_core, modularity,
                                outfile = outfile_pre + '.mod', 
                                show_plot = False, save_plot = True)
    print('Random sample insularities')
    modularity_sample_dist(net, n_core, obs_ins, 
                                mod_func = insularity, 
                                outfile = outfile_pre + '.ins',
                                show_plot = False, save_plot = True)
    
    # Information-theoretic partitioning
    print('Information-theoretic partitioning')
    # Calculate the partition
    gt.seed_rng(5678)
    np.random.seed(5678)
    part_block = gt.minimize_blockmodel_dl(net, B_min = 2, B_max = 2, 
    										verbose = True, 
    										overlap = False)
    # Extract the block memberships as a pmap
    net.vp['partition'] = part_block.get_blocks()
    # Calculate the modularity
    block_modularity = gtcomm.modularity(net, net.vp['partition'])
    print('Partion modularity: ' + str(block_modularity))
    print('Partition insularities')
    block_insularities = partition_insularity(net, net.vp['partition'])
    for community in block_insularities:
        print('Community ' + str(community) + ': ' + 
                str(block_insularities[community]))
    
    print('Plotting')
    size_pmap = gt.prop_to_size(core_pmap, mi = 10, ma = 20)
    layout_and_plot(net, net.vp['partition'], outfile_pre,
                        size_pmap = size_pmap, filename_mod = '.partition')
    
    # Modularity optimization
    optimal_sample_dist(net, modularity, obs_ins,
                                outfile = outfile_pre, 
                                show_plot = False, save_plot = True)
    

    # Save results
    # --------------------
    # The above covers all of the analysis to be written into the output files,
    #  so we'll go ahead and save things now.  
    print('Saving')
    # Save in graph-tool's binary format
    net.save(outfile_pre + '.out' + '.gt')
    # Replace vector-type properties with strings
    #net.list_properties()
    properties = net.vertex_properties
    for property_key in properties.keys():
        property = properties[property_key]
        if 'vector' in property.value_type():
            properties[property_key] = property.copy(value_type = 'string')
    # Save as graphml
    net.save(outfile_pre + '.out' + '.graphml')


    # Comparison networks
    # --------------------
    for compnet_file in compnet_files:
        # Load the comparison network
        compnet, compnet_outfile = load_net(compnet_file)
        # Set it to the same directedness as the network of interest
        compnet.set_directed(net.is_directed())
        # Size of compnet
        n_compnet = compnet.num_vertices()
        # Num vertices in compnet to use in each random partition
        k_compnet = round(n_core / net.num_vertices() * n_compnet)
        # Sample distribution based on random partition
        print('Random sample modularities')
        print('Observed modularity: ' + str(modularity))
        modularity_sample_dist(compnet, k_compnet, modularity, 
                                outfile = outfile_pre + '.mod.' + compnet_outfile, 
                                show_plot = False, save_plot = True)
        print('Random sample insularities')
        print('Observed insularity: ' + str(obs_ins))
        modularity_sample_dist(compnet, k_compnet, obs_ins, 
                                mod_func = insularity, 
                                outfile = outfile_pre + '.ins.' + compnet_outfile,
                                show_plot = False, save_plot = True)
        # Sample distribution based on optimizing modularity
#         optimal_sample_dist(compnet, modularity, n_samples = 300, 
#                                 outfile = outfile_pre + '.mod.' + compnet_outfile,  
#                                 show_plot = False)


    # Timestamp
    # --------------------
    print(datetime.now())
    # Visually separate analyses
    print('-'*40)
Ejemplo n.º 12
0
def create_graph(filename, author):
    """Get entity graph data from file and create graph with networkx."""
    
    # Get filename (of array) and load
    with open(DIRECTORY+filename,'rb') as f:       
        entity_graph = pickle.load(f, encoding='latin1')

    # Compute entity graph sum to verify graph is not empty.
    eg_sum = np.sum(entity_graph)

    # Discard empty graphs
    if eg_sum==0.0:
        return None
        
    ## Get graphs (add empty vertex)
    entity_graph_zero = np.zeros((entity_graph.shape[0]+1, entity_graph.shape[1]+1))
    entity_graph_zero[:-1,:-1] = entity_graph 
    #adj_matrix = entity_graph_zero
    
    # Get adjacency matrix
    adj_matrix = entity_graph
         
    # Get circular graph pos
    D = nx.from_numpy_matrix(entity_graph_zero)
    pos_x = nx.shell_layout(D)
    
    # Create graph, set nodes, edge type and pos
    g = gt.Graph(directed = True)
    g.add_vertex(adj_matrix.shape[0])
    edge_weights = g.new_edge_property("float")
    pos = g.new_vertex_property("vector<float>")
    v_count = g.new_vertex_property("int")
    
    # Assign pos by network x
    n_vertices = adj_matrix.shape[0]

    for i in range(adj_matrix.shape[0]):
        vert = n_vertices-i
        pos[g.vertex(i)] = pos_x[vert]
        v_count[g.vertex(i)] = i+1
        
    # Fill graph with weights
    for i in range(n_vertices):
        for j in range(n_vertices):            
                if adj_matrix[i,j] != 0.0:
                    e = g.add_edge(i,j)
                    edge_weights[e] = adj_matrix[i,j]
        
    # Prop sizing
    v_size_p = gt.prop_to_size(v_count, 5,10)
    edge_weights_p = gt.prop_to_size(edge_weights, mi=0, ma=10, power=1)

    # Save edge/vertex properties
    g.edge_properties["weights"] = edge_weights
    g.vertex_properties["pos"] = pos
    g.vertex_properties["v_count"] = v_count
    
    # Print graph
    #gt.graph_draw(g, pos=pos,vertex_text=v_count, vertex_fill_color='orange', edge_pen_width=edge_weights_p, output_size=(600, 600))
 
    # Generate Graph
    try:
        new_graph = Graph(g, author, filename, entity_graph)
    except ValueError:
        print("This file didn't work:", filename)
        return
    return new_graph
Ejemplo n.º 13
0
mass -= min(mass)
mass /= max(mass)
##
# applying properties
for i, v in enumerate(g.vertices()):
    g.vp.mass[v] = mass[i]
    g.vp.lum[v] = lum[i]
    g.vp.mag[v] = mag[i]
    g.vp.pos[v] = np.array([mag[i], -lum[i]])

##
gtdraw = gt.graph_draw(
    g,
    pos=g.vp.pos,
    vertex_fill_color=g.vp.lum,
    vertex_size=gt.prop_to_size(g.vp.mass, mi=3, ma=9.5, log=False, power=2),
    output=os.path.join(outpath, "HR_diag.png"),
)
##
posv = g.vp.pos.get_2d_array([0, 1]).T
##
gg, gpos = gt.geometric_graph(posv, ibin)
##
gu = gt.graph_union(gg, g, intersection=g.vertex_index, internal_props=True)
##
gt.graph_draw(
    gu,
    pos=gu.vp.pos,
    vertex_fill_color=gu.vp.lum,
    vertex_size=gt.prop_to_size(gu.vp.mass, mi=2, ma=10, log=False, power=2),
    output=os.path.join(outpath, f"HR_diag_edges_{ibin}.png"),
        log=True,
    )
    plt.xticks(np.linspace(0, 0.6, 13), rotation=45, fontsize=6)
    #plt.title('Histogram of Closeness Centrality\nLargest Component')
    plt.xlabel('Closeness Centrality')
    plt.ylabel('Frequency (log)')
    plt.savefig("closeness_hist_g_friend_LC_ap1.png")
    plt.close()

if descClosePlot_bool == True:

    # Screenshot added to Github (less loading time)
    gt.graph_draw(g_friend_LC,
                  pos=None,
                  vertex_fill_color=vprop_closeness,
                  vertex_size=gt.prop_to_size(vprop_closeness, mi=5, ma=15),
                  vcmap=plt.cm.gist_heat,
                  vorder=vprop_closeness,
                  output="closeness_g_friend_LC_ap1.pdf")

#-- Betweenness Distribution of Largest Component --#

if descBetw_bool == True:

    print("\n\n#-- Betweenness Distribution --#\n")

    vprop_betweenness, eprop_betweenness = gt.betweenness(g_friend_LC)
    g_friend_LC.vp.v_betweenness = vprop_betweenness
    g_friend_LC.ep.e_betweenness = eprop_betweenness

    v_between_array = np.array(vprop_betweenness.a)
Ejemplo n.º 15
0
        state[v] = past

    elif time == order[v]:
        visited[v] = True
        mark[v] = True
        state[v] = present
    else:
        visited[v] = False
# Filter out the recovered vertices
max_time = np.max(list(order))
g.set_vertex_filter(visited)
print('asdasd', g.num_vertices())

vsize = g.new_vertex_property("double")
deg = g.degree_property_map("total")
vsize = gt.prop_to_size(g.degree_property_map("total"))
pos = gt.sfdp_layout(g,
                     eweight=g.ep['weight'],
                     groups=g.vp['comm_infomap'],
                     init_step=0.005,
                     max_iter=1)
if not offscreen:
    win = gt.GraphWindow(g,
                         pos,
                         geometry=(500, 400),
                         edge_color=[0.6, 0.6, 0.6, 1],
                         vorder=visited,
                         vertex_size=vsize,
                         vertex_fill_color=g.vp['comm_infomap'],
                         vertex_halo=mark,
                         vertex_halo_color=[0.8, 0, 0, 0.6])
Ejemplo n.º 16
0
args = argparser.parse_args()

g = gt.load_graph(args.file)
g = gt.GraphView(g, vfilt=gt.label_largest_component(g), directed=False)
g = gt.Graph(g, prune=True)

filename = 'degree'

# chequea que todo sea como "debe ser"
print('chequeando...', args.file)
print('vertices', g.num_vertices())  # numero de vertices
print('edges', g.num_edges())  # numero de links

weight = g.ep['weight']
width = gt.prop_to_size(weight, ma=.5)

# seteo de algunas argumentos de la creacion del grafo

pos = g.vp['pos_sfdp_infomap']

deg = g.degree_property_map("total", weight=weight)
vsize = gt.prop_to_size(deg)
vorder = -vsize.a

df = pd.DataFrame({'node': list(g.vertices()), 'degree': list(deg)})
df.sort_values(by='degree', inplace=True, ascending=False)
print(df.head(15))

print('drawing...')
# dibuja el grafico en el archivo filename.pdf
Ejemplo n.º 17
0
    def draw_graph(self, e_label, output, v_label='idx'):
        """
        Helper for convienient and consistent graph drawing.


        @param output   filepath of desired output file (pdf)
        """

        return

        s = self.simulation
        g = self.graph

        # Update position if the topology changed.
        if self.pos_dirty:
            # Calculate pos once to be used by all other graphs
            #self.pos = gt.sfdp_layout(g, K=100, C=0.1, gamma=10.0, mu=0.0)
            #self.pos = gt.sfdp_layout(g, gamma=10.0)
            #self.pos = gt.sfdp_layout(g, gamma=200.0)
            #self.pos = gt.arf_layout(g, d=5.0, a=10, dt=0.001, epsilon=1e-06, max_iter=1000)
            #self.pos = gt.radial_tree_layout(g, self.driveswitch)
            self.pos = gt.radial_tree_layout(g, self.mainswitch)
            self.pos_dirty = False

        if type(e_label) is str:
            ep = g.ep[e_label]
        else:
            ep = e_label

        # Set node fill color depending on certain criteria: busy
        busy_fill = g.new_vertex_property('vector<double>')
        for v in g.vertices():
            if g.vp['obj'][v].has_capacity():
                busy_fill[v] = [1, 1, 1, 1]
            else:
                busy_fill[v] = [1, 0, 0, 0.5]

        # Prepare label text and ensure all labels are converted to be strings
        edge_label = g.new_edge_property("string")
        gt.map_property_values(ep, edge_label, lambda x: str(x))

        # Adjust vertex label depending on type.
        if v_label != None:
            if v_label == 'idx':
                vertex_label = g.copy_property(g.vp['name'])
                for v in g.vertices():
                    vertex_label[v] = str(int(v)) + "::" + vertex_label[v]
            else:
                # prepare vertex label text
                if type(v_label) is str:
                    vp = g.vp[e_label]
                else:
                    vp = v_label

                vertex_label = g.new_edge_property("string")
                # ensure strings
                gt.map_property_values(vp, vertex_label, lambda x: str(x))
        else:
            vertex_label = g.vp['name']

        pos = self.pos
        gt.graph_draw(
            g,
            pos=pos,
            output_size=(800, 600),
            vertex_text=vertex_label,
            vertex_shape='circle',
            #vertex_shape = 'square',
            #vertex_aspect = 2.0,
            vertex_pen_width=0.5,
            vertex_fill_color=busy_fill,  # TODO
            vertex_color=[0, 0, 0, 1],
            vertex_text_color=[0, 0, 0, 0.8],
            vertex_font_family='sans-serif',
            vertex_font_size=10,
            vertex_font_weight=cairo.FONT_WEIGHT_BOLD,
            edge_pen_width=gt.prop_to_size(ep, mi=1, ma=15, power=1),
            edge_text=edge_label,
            edge_end_marker='bar',
            #edge_marker_size = 4,
            edge_font_family='sans-serif',
            edge_font_size=8,
            edge_color=[0, 0, 0, 0.2],
            output=output)
Ejemplo n.º 18
0
    # plot graph (like plot2Dnet) # pos=g.vp.locs
    #pos = gt.planar_layout(g)  #radial_tree_layout(g, 0) #arf_layout(g) # fruchterman_reingold_layout(g)
    plotGraph = 0
    if plotGraph:
        print('Plotting node and edges graph...')
        gt.graph_draw(g,
                      pos=g.vp.locs,
                      vertex_text=g.vertex_index,
                      vertex_size=5,
                      vertex_fill_color=pop_ids,
                      vcmap=matplotlib.cm.jet,
                      vcnorm=1,
                      edge_color=g.ep.weights,
                      ecmap=(matplotlib.cm.jet, .6),
                      edge_pen_width=gt.prop_to_size(g.ep.weights,
                                                     0.05,
                                                     0.1,
                                                     power=1),
                      vertex_font_size=5,
                      output_size=(100, 1000),
                      output=outputFile + '_graph.pdf')

    # caculate betweeness
    # bv, be = betweenness(g)

    print('  elapsed time: %d s' % (time() - start))

    # --------------------------------------------------------------------------
    # run inference SBM algorithm to extract groupings
    # --------------------------------------------------------------------------
    if loadState:
        print('Loading the nested stochastic block model...')
Ejemplo n.º 19
0
for v in g.vertices():
    state[v] = future
    d, m, y = map(int, g.vp['date'][v].split('-'))
    vdate = date(y, m, d)
    order[v] = (vdate - initial_date).days

# Newly infected nodes will be highlighted in red
mark = g.new_vertex_property("bool")
visited = g.new_vertex_property("bool")
mark.a = False
visited.a = False

# This creates a GTK+ window with the initial graph layout
time = -1
max_time = np.max(list(order))
width = gt.prop_to_size(g.ep['weight'], ma=.1)
if not offscreen:
    win = gt.GraphWindow(g,
                         pos,
                         geometry=(500, 400),
                         edge_color=[0.6, 0.6, 0.6, 1],
                         vorder=visited,
                         vertex_fill_color=state,
                         vertex_halo=mark,
                         vertex_halo_color=[0.8, 0, 0, 0.6])
    print('asdasd', g.num_vertices())
else:
    win = Gtk.OffscreenWindow()
    win.set_default_size(500, 400)
    win.graph = gt.GraphWidget(g,
                               pos,
Ejemplo n.º 20
0
for v in cs.get_vertices():

    cs.vp.name[v] = names[v]
    cs.vp.color[v] = "green" if price_change[v] >= 0 else "red"
    cs.vp.volmcap[v] = volmcap[v]
    cs.vp.pricec[v] = price_change[v]
    cs.vp.mcapc[v] = mcap_change[v]
    cs.vp.mcap[v] = mcap[v]

    print(names[v], volmcap[v], price_change[v])


# %%

cs.vp.name[1]
cs.vp.color[1]
cs.vp.volmcap[1]

# %%
gt.graph_draw(
    cs,
    vertex_text=cs.vp.name,
    vertex_text_position="centered",
    vertex_font_size=8,
    vertex_fill_color=cs.vp.color,
    vertex_size=gt.prop_to_size(cs.vp.mcap, mi=5, ma=15, power=1, log=True),
    output = "market_graph.png",
)

# %%
import numpy as np
import math
from generation.Triangulation import Triangulation

# Number of nodes
N = 5
# Number of edges
M = 10

seed_number = 45
generator = Triangulation(N, directed=False, seed_number=seed_number)
g, src, tgt = generator.generate()

cap = g.ep.cap
gt.graph_draw(g,
              edge_pen_width=gt.prop_to_size(cap, mi=1, ma=1, power=1),
              output="graph_to_solve.pdf",
              vertex_text=g.vertex_index,
              edge_text=g.ep.cap)

# using GraphTool algorithm, find the solution to test and print the resulting graph
res = gt.push_relabel_max_flow(g, src, tgt, cap)
res.a = cap.a - res.a  # the actual flow
max_flow = sum(res[e] for e in tgt.in_edges())
print("Il max flow trovato da GraphTool è:", max_flow)
labels = g.new_edge_property("string")
for edge in g.edges():
    labels[edge] = str(res[edge]) + "/" + str(cap[edge])

gt.graph_draw(g,
              edge_pen_width=gt.prop_to_size(res, mi=1, ma=5, power=1),
Ejemplo n.º 22
0
 def save_graph(self, graph_path):
     gt.graph_draw(self.graph, vertex_text=self.graph_vertex_label, pos=self.graph_position, vertex_font_size=18,
                   edge_pen_width=gt.prop_to_size(self.graph_penalty, mi=0, ma=8, power=1),
                   vertex_fill_color=self.graph_vertex_color, edge_color=self.graph_edge_color,
                   output_size=(self.w * 50, self.h * 50), output=graph_path)
Ejemplo n.º 23
0
import graph_tool.all as gtool

gr = gtool.collection.data["polblogs"]
gr = gtool.GraphView(gr, vfilt=gtool.label_largest_component(gr))

cness = gtool.closeness(gr)

gtool.graph_draw(gr,
                 pos=gr.vp["pos"],
                 vertex_fill_color=cness,
                 vertex_size=gtool.prop_to_size(cness, mi=5, ma=15),
                 vorder=cness,
                 vcmap=matplotlib.cm.gist_heat,
                 output="political_closeness.pdf")
print('start drawing')

pos_fr = gt.fruchterman_reingold_layout(g, n_iter=1000)
g.vertex_properties["pos_fr"] = pos_fr
control = g.new_edge_property("vector<double>")
for e in g.edges():
    d = sqrt(sum((pos_fr[e.source()].a - pos_fr[e.target()].a)**2)) / 5
    control[e] = [0.3, d, 0.7, d]
g.edge_properties["control"] = control

gt.graph_draw(g,
              pos=pos_fr,
              vertex_pen_width=0.6,
              vertex_color=[1, 1, 1, 1],
              vertex_fill_color=color_bytype,
              vertex_size=gt.prop_to_size(degrees, mi=10, ma=20),
              edge_color=edge_color,
              edge_control_points=control,
              edge_pen_width=edge_width,
              output_size=(800, 800),
              output="Graphs/Component2995nodes_fr.svg")

pos_rt = gt.radial_tree_layout(g, g.vertex(0))
for e in g.edges():
    d = sqrt(sum((pos_rt[e.source()].a - pos_rt[e.target()].a)**2)) / 5
    control[e] = [0.3, d, 0.7, d]
gt.graph_draw(g,
              pos=pos_rt,
              vertex_pen_width=0.6,
              vertex_color=[1, 1, 1, 1],
              vertex_fill_color=color_bytype,
Ejemplo n.º 25
0
    def draw_graph(self, e_label, output, v_label='idx'):
        """
        Helper for convienient and consistent graph drawing.


        @param output   filepath of desired output file (pdf)
        """


        return


        s = self.simulation
        g = self.graph

        # Update position if the topology changed.
        if self.pos_dirty:
            # Calculate pos once to be used by all other graphs
            #self.pos = gt.sfdp_layout(g, K=100, C=0.1, gamma=10.0, mu=0.0)
            #self.pos = gt.sfdp_layout(g, gamma=10.0)
            #self.pos = gt.sfdp_layout(g, gamma=200.0)
            #self.pos = gt.arf_layout(g, d=5.0, a=10, dt=0.001, epsilon=1e-06, max_iter=1000)
            #self.pos = gt.radial_tree_layout(g, self.driveswitch)
            self.pos = gt.radial_tree_layout(g, self.mainswitch)
            self.pos_dirty = False


        if type(e_label) is str:
            ep = g.ep[e_label]
        else:
            ep = e_label

        # Set node fill color depending on certain criteria: busy
        busy_fill = g.new_vertex_property('vector<double>')
        for v in g.vertices():
            if g.vp['obj'][v].has_capacity():
                busy_fill[v] = [1,1,1,1]
            else:
                busy_fill[v] = [1,0,0,0.5]

        # Prepare label text and ensure all labels are converted to be strings
        edge_label = g.new_edge_property("string")
        gt.map_property_values(ep, edge_label, lambda x: str(x))

        # Adjust vertex label depending on type.
        if v_label != None:
            if v_label == 'idx':
                vertex_label = g.copy_property(g.vp['name'])
                for v in g.vertices():
                    vertex_label[v] =  str(int(v)) + "::" + vertex_label[v]
            else:
                # prepare vertex label text
                if type(v_label) is str:
                    vp = g.vp[e_label]
                else:
                    vp = v_label

                vertex_label = g.new_edge_property("string")
                # ensure strings
                gt.map_property_values(vp, vertex_label, lambda x: str(x))
        else:
            vertex_label = g.vp['name']


        pos = self.pos
        gt.graph_draw(g, pos=pos,

            output_size=(800, 600),

            vertex_text=vertex_label,
            vertex_shape = 'circle',
            #vertex_shape = 'square',
            #vertex_aspect = 2.0,
            vertex_pen_width = 0.5,
            vertex_fill_color = busy_fill, # TODO
            vertex_color = [0,0,0,1],

            vertex_text_color = [0,0,0,0.8],
            vertex_font_family = 'sans-serif',
            vertex_font_size = 10,
            vertex_font_weight = cairo.FONT_WEIGHT_BOLD,

            edge_pen_width=gt.prop_to_size(ep, mi=1, ma=15, power=1),
            edge_text=edge_label,
            edge_end_marker = 'bar',
            #edge_marker_size = 4,
            edge_font_family = 'sans-serif',
            edge_font_size = 8,
            edge_color = [0,0,0,0.2],


            output=output)
Ejemplo n.º 26
0
##

##
# offscreen = sys.argv[1] == "offscreen" if len(sys.argv) > 1 else False

# This creates a GTK+ window with the initial graph layout
if not offscreen:
    win = gt.GraphWindow(
        ug,
        pos,
        geometry=(800, 800),
        vertex_fill_color=ug.vp.lum,
        vertex_size=gt.prop_to_size(ug.vp.mass,
                                    mi=2,
                                    ma=10,
                                    log=False,
                                    power=2),
    )
else:
    win = Gtk.OffscreenWindow()
    win.set_default_size(800, 800)
    win.graph = gt.GraphWidget(
        ug,
        pos,
        vertex_fill_color=ug.vp.lum,
        vertex_size=gt.prop_to_size(ug.vp.mass,
                                    mi=2,
                                    ma=10,
                                    log=False,
                                    power=2),
company_count  = len(comp_comp_tri)

for i in range(0, company_count):
    v_company[v.next()] = comp_tag_table.index[i]

g.vertex_properties['company'] =  v_company

for i in range(0, len(comp_comp_tri)):
    for j in range (0, len(comp_comp_tri)):
        if i != j and comp_comp_tri [i,j] > 0:
            e = g.add_edge(g.vertex(i), g.vertex(j))
            e_weight[e] = comp_comp_tri[i,j]

g.edge_properties['weight'] = e_weight


# to filter the graph a bit
 v_bet, e_bet = gt.betweenness(g, weight=g.edge_properties['weight'])
 pos, it = gt.graph_draw(g, vertex_fill_color = v_bet, 
    vertex_size = gt.prop_to_size(v_bet, mi=2, ma=15),
    edge_pen_width = gt.prop_to_size(e_bet, mi=0.3, ma = 5))

# could use degree to filter

deg = g.degree_property_map(deg='total', weight = g.edge_properties['weight'])
companies_list = comp_tag_table.index
companies_list[deg.a.argmax()]
v_bet, e_bet = gt.betweenness(g, weight = g.edge_properties['weight'])
companies_list[v_bet.a.argmax()]