def draw_automata(dfaStates, dfaDelta, dfaInitialState, dfaFinalStates, fileName):
    g = ig.Graph(directed=True)

    edgeLabels = []
    g.add_vertices(map(lambda x: x + '*' if x == dfaInitialState else x, dfaStates))
    for node, destinations in dfaDelta.iteritems():
        for weight, destination in dfaDelta[node].iteritems():
            if (node != destination):
                node = node + '*' if node == dfaInitialState else node
                destination = destination + '*' if destination == dfaInitialState else destination
                g.add_edge(node, destination)
                edgeLabels.append(weight)

    layout = g.layout("kk")

    nodeSize = 25 + int(math.log(2, len(dfaFinalStates))) * 30

    plotProperties = {}
    plotProperties["vertex_size"] = nodeSize
    plotProperties["vertex_color"] = map(lambda x: 'lightblue' if x.replace('*', '') in dfaFinalStates else 'pink', g.vs['name'])
    plotProperties["vertex_label"] = g.vs["name"]
    g.es["label"] = edgeLabels
    plotProperties["edge_label_dist"] = 10
    plotProperties["margin"] = nodeSize

    try:
        ig.plot(g, fileName + '_solution.png', layout=layout, **plotProperties)
    except TypeError:
        raise RuntimeError("You need to have pycairo installed in order to show a visual representation of the automata.")
Exemplo n.º 2
0
def generator(N):
    fa=None
    while fa==None:
        net=general(N)
        fa=vizsgalat(net)
    igraph.plot(net)
    return fa
Exemplo n.º 3
0
    def __init__(self, x_range, y_range, max_dist):

        self.x_range = x_range
        self.y_range = y_range
        self.max_dist = max_dist

        # opens the json from divvy.
        f = url.urlopen('http://divvybikes.com/stations/json')
        con = json.loads(f.read())
        slist = con["stationBeanList"]


        # creates the map; we flip the latitude to correct the map.
        # the names argument is the street address for the bikes.
        self.loclist = [(x["longitude"],float(self.y_range - x["latitude"]))  for x in slist]
        self.names = [x["stAddress1"] for x in slist]

        # constructs the graph and adds vertices named 0,1,2,3...
        self.g = ig.Graph()
        self.g.add_vertices(len(self.loclist))

        self.make_edges()
      
        # visual styling for the graph; feel free to tweak these if you'd like.
        visual_style = {}
        visual_style["vertex_size"] = 5
        visual_style["vertex_label_size"] = 8
        visual_style["vertex_label_dist"] = 3
        visual_style["vertex_label"] = self.names
        visual_style["edge_color"] = "gray"
        visual_style["layout"] = self.loclist
        visual_style["bbox"] = (self.x_range, self.y_range)
        visual_style["margin"] = 50        

        ig.plot(self.g, **visual_style)
Exemplo n.º 4
0
def plot_tree(cluster_indices, parent_clusters, output_directory = None):
    """Display a bifurcation tree.
    """

    if igraph not in sys.modules:
        return

    if output_directory is None:
        output_directory = getcwd()
        
    vertex_sizes = np.bincount(cluster_indices)
    N_vertices = vertex_sizes.size
    vertex_sizes = np.divide(vertex_sizes, float(np.sum(vertex_sizes)))
    vertex_sizes *= 100 * N_vertices
    vertex_sizes += 40 + (N_vertices / 3)

    tree = igraph.Graph()
    tree.add_vertices(N_vertices)
    
    cluster_tally = 0
    for k, v in parent_clusters.items():
        if k > 0:
            tree.add_edges(zip(v, xrange(cluster_tally, cluster_tally + len(v))))
        cluster_tally += len(v)
        
    tree.vs['label'] = xrange(N_vertices)
    layout = tree.layout('fr')
    name = path.join(output_directory, 'SCUBA_tree.pdf')
    igraph.plot(tree, name, bbox = (200 * N_vertices, 200 * N_vertices), margin = 250,
                layout = layout, edge_width = [7] * (N_vertices - 1), 
                vertex_label_dist = 0, vertex_label_size = 30, 
                vertex_size = vertex_sizes.tolist())
Exemplo n.º 5
0
    def plot(self, target=None, labels=True, **kwargs):
        """It is almost same az igraph.plot().

        But it has not a graph argument, and left and right margins are wider
        by default, and edges are orange if there are vertex labels.

        Parameter:
            target: string or None
                As in igraph.plot.
            labels: list or boolean
                If it is a list, it will passed to the vs["label"].
                If it is true, and no "label" attribute, but there is
                "name" attribute, the "name" will passed to "label".

        """
        if not kwargs.get("layout"):
            kwargs["layout"] = self.layout_kamada_kawai()
        if kwargs.get("margin") is None:
            kwargs["margin"] = (70, 5) * 2

        attributes = self.vs.attributes()
        if isinstance(labels, list):
            self.vs["label"] = labels
        elif labels and "label" not in attributes and "name" in attributes:
            self.vs["label"] = self.vs["name"]
        igraph.plot(self, target, **kwargs)
Exemplo n.º 6
0
def plotGraph(data):
    #print "Graphing proposed network"
    G=nx.DiGraph()
    G.add_weighted_edges_from(data[0])
    #G.remove_node(16)
    nx.draw_networkx(G, data[2], width = data[1])
    #plt.pyplot.show()
    #plt.pyplot.savefig('flows.png')

    newLinks = []
    for link in data[0]:
        newLinks.append((int(link[0]),int(link[1])))


    IG = ig.Graph(25, newLinks, directed = True)
    IG.es["width"] = data[1]
    IG.vs["label"] = range(data[4])
    sizes = data[5]
    layout = data[3]

    oldMin = np.min(sizes)
    oldMax = np.max(sizes)
    newMin = 12.5
    newMax = 35
    newSizes = (((sizes-oldMin)*(newMax-newMin))/(oldMax-oldMin)) + newMin
    IG.vs["size"] = newSizes
    smallNodes = IG.vs.select(size_lt=20)["label_size"] = 10
    IG.vs.select(label_eq=16)["color"] = "#91CF60"
    IG.vs.select(label_ne=16)["color"] = "#FC8D59"
    ig.plot(IG, layout = layout, weighted =True, edge_arrow_size = .6, vertex_label_angle = 0)


    return G
def disp_tree(tree):

	from igraph import Graph, plot

	g = Graph(directed=True)
	g.add_vertices(len(tree))

	g.vs['label'] = [node.name for node in tree]

	nodes_to_add = set([0])
	while len(nodes_to_add) != 0:

		i_node = nodes_to_add.pop()
		node = tree[i_node]
		g.vs['label'][i_node] = node.name

		left_node = node.left_child
		right_node = node.right_child

		if left_node != None:
			i_left = tree.index(left_node)
			g.add_edges((i_node, i_left))
			nodes_to_add.add(i_left)
		
		if right_node != None:
			i_right = tree.index(right_node)
			g.add_edges((i_node, i_right))
			nodes_to_add.add(i_right)

	layout = g.layout_reingold_tilford(root=0)
	plot(g, layout=layout, bbox=(0, 0, 3000, 1000))
Exemplo n.º 8
0
def DrawSubGraph(graph, threshold, sublist_nodes=None):
    """
    Args:
    	graph
        threshold: all edges under this threshold will be deleted.
        sublist_nodes: names of the nodes that should be kept; default is to 
            keep all nodes
    """
    if sublist_nodes != None:
        graph = db.IsolateSubGraph(graph, sublist_nodes, "term") 

    # Delete edges below threshold.
    index_to_delete = [edge.index for edge in graph.es.select(weight_lt=threshold)] 
    graph.delete_edges(index_to_delete) #deletes selected edges


    np_numberofstudies = np.array(graph.vs['numberofstudies']) 
    nsl = np.log10(np_numberofstudies) #calculates log of number of studies
    log_number_of_studies = nsl*8 #multiplies constant to create attribute "log"
    visual_style = {} #sets method of modifying graph characteristics
    visual_style ["vertex_label"] = graph.vs["term"] # labels the vertices
    visual_style ["vertex_label_dist"] = 2 
    # specifies the distance between the labels and the vertices
    visual_style ["vertex_size"] = log_number_of_studies 
    # specifies size of vertex_size
    visual_style["bbox"] = (700,700) #sets dimensions for the box layout
    visual_style["margin"] = 60
    igraph.plot(graph, **visual_style) # creates the changes
Exemplo n.º 9
0
	def spring_embedding(self, file_name):
		minx = 0
		maxx = self.width
		miny = 0
		maxy = self.height
		area = self.width*self.height	# default is the number of vertices
		maxiter = 500	# number of iterations to perform (default 500)
		maxdelta = self.n	# maximum distance to move a vertex in an iteration (default is the number of vertices)
		coolexp = 1.5	# cooling component of the simulated annealing (default 1.5)
		repulserad = self.n**3.	# radius at which vertex-vertex repulsion cancels out attraction of adjacent vertices (default len(vertices)^3)
		#seed = None 	# if None, uses a random starting layout for the algorithm. If a matrix (list of lists) uses the given matrix as the starting position
		# print self.weights
		# self.graph.layout_fruchterman_reingold(self.weights, maxiter, maxdelta, area, coolexp, repulserad,minx, maxx, miny, maxy, 0, 0, seed, self.dim)
		# self.complex.embed(self.graph)
		s = []
		height = 600
		width = 600
		d_x = (width - 100)/self.l
		pos_x = 50		
		pos_y = 50
		for l in self.cover.coverset:
			if (len(l.clustering.clusters) == 0):
				pos_y = height/2
				s.append([pos_x, height/2])
			else:
				d_y = (height - 100)/len(l.clustering.clusters)
				for c in l.clustering.clusters:
					s.append([pos_x, pos_y])
					pos_y = pos_y + d_y
			pos_x = pos_x + d_x
			pos_y = 50
		layout = self.graph.layout_fruchterman_reingold(seed=s)
		igraph.plot(self.graph, file_name, layout = layout)
		print self.pal.get(0)
		print self.pal.get(self.l-1)
Exemplo n.º 10
0
 def plot(self, margin=50):
     A = self.get_adjacency_matrix_as_list()
     convert_to_igraph = ig.Graph.Adjacency(A)
     g=convert_to_igraph
     for vertex in self.vertices:
         index=self.vertices.index(vertex)
         if vertex.pivot !=None:
              
              if type(vertex.pivot)==set:
                 label_pivot = ' in '+str(list(vertex.pivot))
                 
              else:
                 label_pivot = ' less than '+str(vertex.pivot)
              g.vs[index]['label']=str(vertex.split_attribute)+label_pivot
              g.vs[index]['label_dist']=2
              g.vs[index]['label_color']='red' 
              g.vs[index]['color'] = 'red'
              
         else:
             label=str(vertex.predicted_class)
             g.vs[index]['color']='blue'
             g.vs[index]['label']=label
             
             g.vs[index]['label_dist']=2
             g.vs[index]['label_color']='blue' 
     root_index = self.vertices.index(self.get_root())
     layout = g.layout_reingold_tilford(root=root_index)
     ig.plot(g, layout=layout, margin=margin) 
Exemplo n.º 11
0
def gan_community_detection():
    gan = load_gan()
    graph = ig.Graph(directed=True)
    graph.add_vertices(load_apps())

    elist = []
    for e in gan.edges():
        u, v = e
        w = float(gan[u][v]['weight'])
        elist.append((u, v, w))

    # write networkx to file
    graph = nx.DiGraph()
    graph.add_weighted_edges_from(elist)
    nx.write_graphml(graph, GRAPHML_PATH)

    # read file to construct igraph
    graph = ig.Graph.Read_GraphML(GRAPHML_PATH)
    graph.vs['size'] = [10 for i in xrange(len(graph.vs))]

    clusters = graph.community_spinglass()
    membership = clusters.membership
    vc = ig.VertexClustering(graph, membership)

    result = []
    for c in vc:
        result.append(set([graph.vs[i]['id'] for i in c]))

    ig.plot(vc, bbox=(2400, 1400))
    return result, clusters.modularity
Exemplo n.º 12
0
def main(options, other_args):
    # For local test
    u = re.compile("(.*):(.*)@(.*)/(.*)")
    a = u.match(options.source)
    db_args = a.groups()

    table_info_list, extra = calc_database_table_relations(db_args)
    print("Press [i] to ignore this time, [n] means not an id(key), [e] means an id from an external system.")
    print("")

    try:
        query_uncertain_id_fields(table_info_list, extra)
    except KeyboardInterrupt as e:
        print('Ignore all uncertain foreign keys')

    table_info_list, extra = calc_database_table_relations(db_args)
    if options.graph:
        graph = init_graph_from_relations(table_info_list)
        plot(graph, options.graph)
    
    if options.way:
        begin_point, end_point = options.way.split(',')
        paths = graph.all_paths(begin_point, end_point)
        count = 1
        for path in paths:
            print('-' * 5, "Way %d" % count, '-' * 5)
            graph.prints(path)
            count += 1
def sac_plot_cluster(sac_graph, membership_list, filename):
	red = colour.Color("red")
	blue = colour.Color("blue")
	my_rainbow = list(red.range_to(blue, membership_list.max() + 1))
	color_list = [i.get_hex_l() for i in my_rainbow]
	layout = sac_graph.layout("kk")
	gp.plot(sac_graph, filename, layout=layout, vertex_color=[color_list[x] for x in membership_list])
Exemplo n.º 14
0
def plot_graph(g, layout, filepath, size_tup=(600, 600)):
    # #palettes
    # #  'red-yellow-green','gray','red-purple-blue','rainbow',
    # #  'red-black-green','terrain','red-blue','heat','red-green'
    #palette=colors.palettes["gray"],
    plot(g, filepath, size_tup, layout=layout,  
        vertex_order_by=('size', True), edge_color="white", edge_width=0, edge_arrow_size=0.1, 
        edge_arrow_width=0.1)
Exemplo n.º 15
0
def five_vertices():
    """
    Function for the section 1.
    Reproduce the graph in the subject.
    """
    g = ig.Graph()
    # TODO
    ig.plot(g)
Exemplo n.º 16
0
 def number_of_components_beta(self): #akkor mukodik, ha a grafban nincs fa
     venum = self.vcount() #a vertexek szama
     ncount = 0
     for v in range(0,venum): #vegigmegyek az osszes csucson
         if self.neighborhood_size(v)==2: #ha az adott csucs szomszedsaga==2
             ncount=ncount+1              #tehat maga + egy, akkor a csucs veg vagy kezdo csucs
     print ncount//2
     igraph.plot(self)
def main(graphFileName, featuresFileName, featureListFile, trainingFileName, k):

	# Read ego network
	global graph
	graph = igraph.Graph.Read_Ncol(graphFileName)
	graph.vs["membership"] = 0

	# Read feature names	
	with open(featureListFile, "r") as featureList:
		for line in featureList:
			featureNames.append(line.strip())
			graph.vs[line.strip()] = None
				
	
	# Read feature values of nodes
	with open(featuresFileName, "r") as featuresFile: 
		for line in featuresFile:
			features = line.split(" ")	
			for feature in features[1:-1]:
				try:
					node = graph.vs[int(features[0])]
					node[";".join(feature.split(";")[0:-1])] = feature.split(";")[-1]
				except:
					pass
			
			
	
	# Run K-Means on the graph
	clusters = kmeans(graph, k)
	newClusters = clusters
	
	# Store in each node the cluster it belongs to.
	i = 0
	for membership in clusters.membership:
		graph.vs[i]['membership'] = membership
		i = i + 1
	
	
	# Plot final clusters
	print newClusters
	igraph.plot(newClusters)
	
	# Plot actual clusters from training data
	actualClusters = getTrainingClusters(graphFileName, trainingFileName)
	print actualClusters
	igraph.plot(actualClusters)

	i = 0
	count = 0
	for node1 in graph.vs:
		for node2 in graph.vs:
			if(actualClusters.membership[node1.index] == actualClusters.membership[node2.index] and newClusters.membership[node1.index] == newClusters.membership[node2.index]):
				count = count + 1
			elif(actualClusters.membership[node1.index] != actualClusters.membership[node2.index] and newClusters.membership[node1.index] != newClusters.membership[node2.index]):
				count = count + 1
			i = i + 1
	error = (float(count) / float(i))
	print error
Exemplo n.º 18
0
def showGraph(graph,filename):
	ly=graph.layout('fr')
	visual_style = {}
	visual_style["vertex_size"] = 5
	visual_style['layout']=ly
	#visual_style["vertex_label"] = g.vs["uid"]
	visual_style["vertex_label"] = graph.vs["name"]
	#igraph.plot(graph,"snsPic/{}.png".format(filename),**visual_style)
	igraph.plot(graph,**visual_style)
Exemplo n.º 19
0
 def plot(self):
     cols = ["black","blue","red","green"]
     vertex_color = [cols[s] for s in self.status]
     igraph.plot(
         igraph.Graph.as_undirected(igraph.Graph.Adjacency(
             self.adj.toarray().tolist())),
         vertex_color = vertex_color,
         vertex_label = range(self.numNodes)
         )
def show_hierachy_graph(g):
    visual_style={}
    visual_style['vertex_size']=10
    #visual_style['vertex_label']=g.vs['label_count']
    #visual_style['vertex_label']=g.vs['label_percentage']
    visual_style['margin']=20
    #l=g.layout_reingold_tilford_circular()
    l=g.layout_reingold_tilford()
    igraph.plot(g,layout=l,**visual_style)
Exemplo n.º 21
0
def plotGraph(g, vertexLabel, edgeLabel):
  layout = g.layout_kamada_kawai()
  style = {}
  if vertexLabel:
    style["vertex_label"] = vertexLabel
  if edgeLabel:
    style["edge_label"] = edgeLabel
  style["layout"] = layout
  igraph.plot(g, **style)
Exemplo n.º 22
0
def plotTreeFromString(treeString, colordict, plotFile):
    """
    Plots a tree from the 'brackets tree' format
    :param treeString:
    :param colordict: defines the colors of the nodes by label (e.g. 1 to 5)
    :param plotFile: output file (.png)
    :return:
    """
    g = Graph()
    splitted = treeString.split("(")

    level = -1
    parents = dict()
    parentIds = dict()
    levelCount = dict()
    for part in splitted:
        if len(part)<1:
            continue
        else: #label follows
            level+=1
            count = levelCount.get(level,0)
            levelCount[level] = count+1
            #print "level %d" % level
            label = part[0]
            #print part.split()
            if len(part.split())>1: #leaf node
                label, wordPlusEnding = part.split()
                #print part, "at leaf"
                endings = wordPlusEnding.count(")")
                word = wordPlusEnding.strip(")")
                g.add_vertex(label=word, color=colordict[int(label)])
                #print "added node %d" % (len(g.vs)-1)
                currentNode = len(g.vs)-1
                p = parents[level-1]
                g.add_edge(currentNode,p)#add edge to parent
                #print "added edge %d-%d" % (len(g.vs)-1, parentIds[level-1])
                level-=endings
                #print "word", word
            else:
                g.add_vertex(label=label, color=colordict[int(label)])
                currentNode = g.vs[len(g.vs)-1]
                #print "added node %d" % (len(g.vs)-1)
                if level != 0:
                    p = parents[level-1]
                    g.add_edge(currentNode,p)#add edge to parent
                    #print "added edge %d-%d" % (len(g.vs)-1, parentIds[level-1])

                parent = currentNode
                parentId = len(g.vs)-1
                parents[level] = parent
                parentIds[level] = parentId
                print parentIds

        print g.summary()
        layout = g.layout_reingold_tilford(mode="in", root=0)
        plot(g, plotFile, layout=layout, bbox = (2000, 1000), margin = 100)
Exemplo n.º 23
0
    def drawNetwork(self, **kwargs):
        """
        Read the data stored in self.metrics, using column 0 as
        x axis values. Select the columns specified by *valueCol*,
        *minCol*, *maxCol* as Y values and print a png chart.

        args:
        *matrix*
        (numpy matrix)
        matrix of adjacency    
        -----------------------
        optional args:
        *nodeColor*
        (color)
        color of the nodes. Defaults to "red".
        *lineColor*
        (color)
        The color of the func line (Y values). It defaults to "grey - #787878".
        *oudDir*
        (str)
        output dir. Defaults to `networks'.
        *outFile*
        (str)
        output filename. Defaults to `testNetwork.png'.
	    """
	    # manage args
        matrix = kwargs.get('matrix')
        title = kwargs.get('title', 'test network')
        nodeColor = kwargs.get('nodeColor', 'red')
        lineColor = kwargs.get('lineColor', '#D8D8D8')
        outDir = kwargs.get('outDir', 'networks') 
        outFile = kwargs.get('outFile', 'testNetwork.png')
        if not os.path.exists(outDir):
            os.makedirs(outDir)
        filePath = outDir + '/' + outFile
        g = igraph.Graph.Weighted_Adjacency(list(matrix),mode=igraph.ADJ_MAX)
        visual_style = {}
        visual_style["title"] = title
        visual_style["vertex_size"] = 20
        visual_style["vertex_color"] = nodeColor
        visual_style["vertex_label"] = self.legendfeatures
        visual_style["label_angle"] = 1.57
        visual_style["label_dist"] = 100
        visual_style["edge_width"] = g.es["weight"]
        degrees = g.degree()
        print degrees
        for i in range(len(degrees)):
            degrees[i] = degrees[i] * 5
        visual_style["vertex_size"] = degrees
        visual_style["layout"] = g.layout("circle")
        #bbox = BoundingBox(750, 750, 750, 750)
        #visual_style["bbox"] = bbox       ####FIXME####
        visual_style["margin"] = 20
        #plotting the network
        igraph.plot(g, filePath, bbox = (1200,1200), **visual_style)
Exemplo n.º 24
0
def p(graph):
    #
    #print("pagerank", graph.pagerank())
    ## Looks like per-edge attributes aren't working?
    ig.plot(graph, layout=graph.layout('kk'),
            target='graph.png', vertex_label="",
            edge_width=0.3)
    #ig.plot(graph, layout=graph.layout('grid_fr'),
    #        target='graph.png', vertex_label="", edge_width=0.3)
    #ig.plot(graph, layout=graph.layout('kamada_kawai'), target='graph.png')
    subprocess.Popen(['feh', 'graph.png'])
Exemplo n.º 25
0
def showGraph(graph,filename):
	ly=graph.layout('fr')
	visual_style = {}
	visual_style["vertex_size"] = 5
	visual_style['layout']=ly
	#visual_style["vertex_label"] = g.vs["uid"]
	#visual_style["vertex_label"] = graph.vs["name"]
	if filename is not None:
		igraph.plot(graph,"{}.png".format(filename),**visual_style)
	else:
		igraph.plot(graph,**visual_style)
Exemplo n.º 26
0
def draw_ig_graph(timelines, index_to_title, threshold = 0.9):
    g = igraph.Graph()
    g.add_vertices(len(timelines))
    edges = get_edges(threshold = threshold)
    g.add_edges(edges)

    for i, v in enumerate(g.vs):
        epnum = date_to_epnum[timelines.keys()[i]]
        v['label'] = epnum
        v['color'] = member_to_color[epnum_to_member[epnum]]
    igraph.plot(g, 'graph_kk.png', bbox = (4000, 4000), layout = g.layout('kk'))
Exemplo n.º 27
0
def save_cluster(obj, filename, box=(2000, 2000)):
    p = None
    if isinstance(obj, Graph):
        p = plot(obj, bbox=box)
    elif isinstance(obj, VertexDendrogram) or isinstance(obj, VertexClustering):
        cl = as_clustering_if_not(obj)
        p = plot(cl, bbox=box)
    else:
        return None

    p.save('%s.png' % (filename,))
Exemplo n.º 28
0
def drawGraph(filename):

    if len(filename) > 0:
        visual_style["edge_color"] = [edgeColor for edgeColor in karateClubGraph.es["edge_color"]]
        visual_style["edge_width"] = [edgeWidth for edgeWidth in karateClubGraph.es["edge_width"]]

        layout = karateClubGraph.layout("rt_circular")  # rt, rt_circular
        visual_style["layout"] = layout
        # visual_style["bbox"] = (300, 300)
        visual_style["margin"] = 20
        igraph.plot(karateClubGraph, "./" + folderName + "/" + filename + ".pdf", **visual_style)
Exemplo n.º 29
0
def drawFactionsOriginal(filename):
    if len(filename) > 0:
        color_dict = {1.0: "red", 2.0: "green"}
        visual_style["vertex_color"] = [color_dict[node["Faction"]] for node in karateClubGraph.vs]
        visual_style["edge_color"] = [edgeColor for edgeColor in karateClubGraph.es["edge_color"]]
        visual_style["edge_width"] = [edgeWidth for edgeWidth in karateClubGraph.es["edge_width"]]

        layout = karateClubGraph.layout("rt_circular")  # rt, rt_circular
        visual_style["layout"] = layout
        # visual_style["bbox"] = (300, 300)
        visual_style["margin"] = 20
        igraph.plot(karateClubGraph, "./" + folderName + "/" + filename + ".pdf", **visual_style)
Exemplo n.º 30
0
    def getSimMSTs(self, inverse=True, plotGraph=True, root="UNK"):
        rootId1 = self.emb1.d[root]
        rootId2 = self.emb2.d[root]
        if inverse == True:
            d = -1
        else:
            d = 1
        g1 = minimum_spanning_tree(csr_matrix(d*self.s1))
        g2 = minimum_spanning_tree(csr_matrix(d*self.s2))

        a1 = g1.toarray()
        a2 = g2.toarray()

        if plotGraph==True:
            t1 = Graph()
            t2 = Graph()
            t3 = Graph()
            t1.add_vertices(self.emb1.vocab_size)
            t2.add_vertices(self.emb2.vocab_size)
            t3.add_vertices(self.emb1.vocab_size)
            t1.vs["color"] = "white"
            t2.vs["color"] = "white"
            t3.vs["color"] = "white"
            t1.vs["label"] = [w for w,i in sorted(self.emb1.d.items(), key=itemgetter(1))]
            t2.vs["label"] = [w for w,i in sorted(self.emb2.d.items(), key=itemgetter(1))]
            t3.vs["label"] = t1.vs["label"]
            for i in xrange(a1.shape[0]):
                for j in xrange(a1.shape[1]):
                    if a1[i,j] != 0:
                        t1.add_edge(i,j, weight=a1[i,j], color="blue")
                        t3.add_edge(i,j, weight=a1[i,j], color="blue")
            for i in xrange(a2.shape[0]):
                for j in xrange(a2.shape[1]):
                    if a2[i,j] != 0:
                        t2.add_edge(i,j, weight=a2[i,j], color="red")
                        if t3.are_connected(i,j): #edge in both MSTs
                            t3.es[i,j]["color"] = "black"
                        else:
                            t3.add_edge(i,j, weight=a1[i,j], color="red")
            layout1 = t1.layout_reingold_tilford(mode="in", root=rootId1)
            layout2 = t2.layout_reingold_tilford(mode="in", root=rootId2)
            layout3 = t3.layout_reingold_tilford(mode="in", root=rootId1)
            graphs = [Graph.GRG(10, 0.4) for _ in xrange(5)]
            figure = Plot(bbox=(0,0,2000,1000))
            figure.add(t1, layout=layout1, margin=100, bbox=(0,0,1000,1000))
            figure.add(t2, layout=layout2, margin=100, bbox=(1000,0,2000,1000))
            plotname1 = "plots/"+NAME+".mst_trees.png"
            figure.save(plotname1)
            plotname3 = "plots/"+NAME+".merged_mst.png"
            plot(t3, plotname3 , layout=layout3, bbox=(1000,1000), margin=100)
            print("\tSaved MST plots in '%s', '%s'" % (plotname1, plotname3))

        return t1,t2,t3
from igraph import Graph
from igraph import plot

grafo = Graph(edges=[(0, 1), (2, 3), (0, 2), (0, 3)], directed=True)
grafo.vs['label'] = ['Fernando', 'Pedro', 'Jose', 'Antonio']
grafo.vs['nota'] = [100, 40, 60, 20]
grafo.es['tipoAmizade'] = ['Amigo', 'Inimigo', 'Amigo']
grafo.es['devendo'] = [1, 3, 2, 5]

grafo.vs['color'] = ['red', 'yellow', 'orange', 'green']

plot(grafo,
     bbox=(300, 300),
     vertex_size=grafo.vs['nota'],
     edge_width=grafo.es['devendo'],
     vertex_color=grafo.vs['color'],
     edge_curved=0.4,
     vertex_shape='square')
Exemplo n.º 32
0
    def plot_graph(self):
        self.ig.vs["label"] = [i for i in range(0, self.nodes.shape[0])]

        layout = self.ig.layout("kk")  # Kamada-Kawai layout
        igraph.plot(self.ig, layout=layout)
Exemplo n.º 33
0
    mst = g.spanning_tree(weights=g.es['weight'])
    print('len(mst.es)', len(mst.es))
    assert len(mst.es) == n_samples - 1

    # Plot the graph
    visual_style = {}
    # Scale vertices based on degree
    visual_style["vertex_size"] = [20] * n_samples
    # Don't curve the edges
    visual_style["edge_curved"] = False
    # Set bbox and margin
    visual_style["bbox"] = (800, 800)
    visual_style["margin"] = 100
    visual_style["layout"] = [(X[i, 0], X[i, 1]) for i in xrange(n_samples)]
    ig.plot(
        mst, 'figures/moons/moons_' + add_name + 'mst_n' + str(n_samples) +
        '_m' + str(n_edges) + '.pdf', **visual_style)
    ig.plot(
        g, 'figures/moons/moons_' + add_name + 'graph_n' + str(n_samples) +
        '_m' + str(n_edges) + '.pdf', **visual_style)

    # APPLY KMEANS
    kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
    mst.vs['color'] = [colors[i] for i in list(kmeans.labels_)]
    ig.plot(
        mst, 'figures/moons/moons_' + add_name + 'mst_n' + str(n_samples) +
        '_m' + str(n_edges) + '_Kmeans.pdf', **visual_style)

    # APPLY CLUSTERING DBMSTClu
    index_DBMSTClu, DBMSTClu_cuts, y_pred_ix = DBCVI.DBMSTClu(mst,
                                                              verbose=False)
Exemplo n.º 34
0
def save_plot_graph(gc,
                    graph_name,
                    X,
                    group_masks,
                    group_names,
                    all_feature_names,
                    config,
                    case_name=None,
                    is_plot_graph=True,
                    is_print_name=True,
                    remove_isolated=True):
    fig_graph_path = config.ofname(
        graph_name, ext=".png", include_set=config.params_sets["diff_graph"])
    tsv_graph_path = config.ofname(
        graph_name, ext=".tsv", include_set=config.params_sets["diff_graph"])
    from copy import deepcopy
    export_cpg_path = deepcopy(graph_name)

    def add_graph_name_suffix(graph_name, suffix):
        if type(graph_name) is str:
            graph_name += "_" + suffix
        elif type(graph_name[-1]) is str:
            graph_name[-1] += "_" + suffix
        else:
            graph_name[-1][-1] += "_" + suffix
        return graph_name

    tsv_vertices_path = config.ofname(
        add_graph_name_suffix(graph_name, 'vertices'),
        ext=".tsv",
        include_set=config.params_sets["diff_graph"])
    tsv_list_path = config.ofname(add_graph_name_suffix(graph_name, 'list'),
                                  ext=".tsv",
                                  include_set=config.params_sets["diff_graph"])

    g = gc.copy()
    g.vs["label"] = all_feature_names

    if not case_name is None:
        export_best_cpg_pairs(g, case_name, path=export_cpg_path)

    if remove_isolated:
        g.delete_vertices([v.index for v in g.vs if v.degree() < 1])

    if is_plot_graph:
        layout = g.layout("kk")
        #layout = g.layout("circle")
        #igraph.plot(g, layout = layout)

        visual_style = {}
        visual_style["font_size"] = 5
        visual_style["vertex_label_size"] = 10
        #visual_style["vertex_color"] = [color_dict[gender] for gender in g.vs["gender"]]
        visual_style["vertex_label"] = g.vs["label"]
        #visual_style["edge_width"] = [1 + abs(weight) for weight in g.es["weight"]]
        visual_style["layout"] = layout
        visual_style["bbox"] = (700, 700)
        visual_style["margin"] = 50
        visual_style["vertex_label_dist"] = 1.1
        visual_style["vertex_shape"] = "circle"

        fig_g = igraph.plot(g, **visual_style)

        fig_g.save(fig_graph_path)

    #os.startfile(fig_graph_path)
    name = "cpg" if "num_cpgs" in config.params else "gene"
    df_graph = graph_to_dataframe(g, name)
    #print(df_graph)
    df_graph.to_csv(tsv_graph_path, sep='\t')
    feature_list = list(
        set(df_graph[name + "_1"].values.tolist() +
            df_graph[name + "_2"].values.tolist()))
    _, indices, _ = np.intersect1d(all_feature_names,
                                   feature_list,
                                   return_indices=True)
    feature_list = all_feature_names[indices]

    def add_statistics(d, X, group_masks, group_names):
        _, indices, _ = np.intersect1d(all_feature_names,
                                       d[name],
                                       return_indices=True)
        if len(indices) > 0:
            for group_mask, group_name in zip(group_masks, group_names):
                scur = X[group_mask]
                d[group_name + '_mean'] = scur[:, indices].mean(axis=0)
            for group_mask, group_name in zip(group_masks, group_names):
                scur = X[group_mask]
                d[group_name + '_std'] = scur[:, indices].std(axis=0)
        return d

    d = {name: feature_list}
    d = add_statistics(d, X, group_masks, group_names)
    df_vlist = pd.DataFrame(d)
    df_vlist.to_csv(tsv_list_path, sep='\t')

    d = {name: g.vs["label"]}
    d = add_statistics(d, X, group_masks, group_names)
    df_vertices = pd.DataFrame(d)
    df_vertices.to_csv(tsv_vertices_path, sep='\t')

    if is_print_name:
        print(graph_name)
Exemplo n.º 35
0
print("Cost matrix:\n%s" % cost)

nData = 22
nTasks = 10
edgeProb = 0.2
outgoingEdges = 2
avgDataDep = 3
stddDataDep = 0.5

print("Generating graph...")
#g = gdat.g
# g = gen.generate_barabasi(nData + nTasks, outgoingEdges)
g = gen.generate_realistic(nData, nTasks, avgDataDep, stddDataDep)
# g = ig.Graph.Read_Pickle("data/graph_example")
ig.plot(g)
print("End of generation.")

color_dict_vertex = {0: "blue", 1: "red", 2: "green", 3: "pink", 4: "orange"}
placement = partitionLP(cost, g, tolerance)
partition = []
for vertex in range(len(g.vs)):
    maxProb = 0
    maxPlacement = -1
    for c in range(nClusters):
        if placement[vertex][c] > maxProb:
            maxProb = placement[vertex][c]
            maxPlacement = c
    partition.append(maxPlacement)
print("Placement: %s\n" % placement)
Exemplo n.º 36
0
def build_power_graph(embeddings,
                      avg_embeddings,
                      power=True,
                      filter_articles=None,
                      entity_map=None,
                      graph_name_str="aziz_power_graph",
                      min_count=8,
                      vertex_scalar=1.5):
    if power:
        train = load_power_all(cfg.POWER_AGENCY)
        preds = get_entity_scores(train, None, None,
                                  wgts.power_token_regression, embeddings,
                                  avg_embeddings)
    else:
        train = load_agency_all(cfg.POWER_AGENCY)
        preds = get_entity_scores(train, None, None,
                                  wgts.agency_token_regression, embeddings,
                                  avg_embeddings)

    # we ultimately need to control for number of co-occurences in the same article
    # it's easiest to do this 1 article at a time

    # this is a map from article id to all entites in that article
    article_to_entity_idx = defaultdict(list)
    entity_to_article_count = defaultdict(list)
    edge_tracker = EdgeTracker()

    for e, idxs in embeddings.entity_to_idx.items():
        # this is a verb that has some association with e
        for idx in idxs:
            article_id = os.path.basename(
                embeddings.tupls[idx].filename).split(".")[0]
            if filter_articles is not None and not str(
                    article_id) in filter_articles:
                continue
            article_to_entity_idx[article_id].append((e, idx))

    for a, val in article_to_entity_idx.items():
        per_article_entity_tracker = defaultdict(EntityScoreTracker)
        for e, idx in val:
            if e.lower() in PRONOUNS:
                continue

            if entity_map is not None:
                if not e in entity_map:
                    continue
                e = entity_map[e]

            tupl = embeddings.tupls[idx]

            if tupl.relation == "nsubj":
                per_article_entity_tracker[e].update(preds[idx], 1, False)
            elif tupl.relation in ["nsubjpass", "dobj"]:
                per_article_entity_tracker[e].update(-1 * preds[idx], 1, False)

        keys = list(per_article_entity_tracker.keys())

        # Mark that entities co-occurred in this article
        for i in range(0, len(keys)):
            e1 = keys[i]
            entity_to_article_count[e1].append(a)

            for j in range(i + 1, len(keys)):
                e2 = keys[j]

                edge_tracker.update(e1, e2,
                                    per_article_entity_tracker[e1].score,
                                    per_article_entity_tracker[e2].score,
                                    False)
    # end all articles

    # remove all vertices that didn't appear in at least 8 articles
    to_delete = []
    for v in entity_to_article_count:
        if len(entity_to_article_count[v]) < min_count:
            to_delete.append(v)

    edges, edge_weights, vertex_names, vertex_weights, missing = edge_tracker.get_edge_list(
        to_delete)

    # make vertex weights all positive
    m = min(vertex_weights)
    if m < 0:
        # scale up for better visualization
        vertex_weights = [(v + abs(m)) * vertex_scalar for v in vertex_weights]

    g = igraph.Graph(edges=edges,
                     vertex_attrs={
                         "name": vertex_names,
                         "v_weights": vertex_weights
                     },
                     edge_attrs={"weights": edge_weights},
                     directed=True)

    # edge_colors = ["red" if a else "blue"  for a in missing]
    visual_style = {}
    visual_style["vertex_label"] = g.vs["name"]
    visual_style["vertex_label_size"] = 16
    visual_style["edge_width"] = g.es["weights"]
    visual_style["edge_color"] = 'gray'
    visual_style["vertex_shape"] = 'circular'
    visual_style["vertex_frame_color"] = 'gray'
    visual_style["vertex_size"] = vertex_weights
    visual_style["margin"] = 55
    # visual_style["edge_color"] = edge_colors
    ts = datetime.now().timestamp()
    graph_name = graph_name_str + str(ts) + ".png"
    print("Saving", graph_name)
    igraph.plot(g, graph_name, **visual_style)
Exemplo n.º 37
0
            a2=a2-1
    print a1
    print a2
    similarite= (a1+a2)/2
    return similarite


            
        



def main():
    g1 = igraph.read("/Users/irene/Desktop/pfe/arguments_politique start.gml", format= "gml") 
    g2 = igraph.read("/Users/irene/Desktop/pfe/arguments_politiques_complets.gml", format = "gml")
    g3 = igraph.read("/Users/irene/Desktop/pfe/arguments_politique1.gml", format = "gml")

    
    gcomp1 = get_giant_component(g1)
    gcomp2 = igraph.Graph.induced_subgraph(g2,gcomp1.vs["name"])

    
    print graph_summary(g1)
    print graph_summary(g2)
    
main()

layout = gcomp1.layout("kk")
g.vs["label"] = g.vs["name"]
igraph.plot(gcomp1, layout = layout)
Exemplo n.º 38
0
@author: Giovanni
"""

# Aula 6 - Caminhos e Distâncias com igraph
from igraph import Graph
from igraph import plot

grafo = Graph(edges=[(0, 2), (0, 1), (1, 4), (1, 5), (2, 3), (6, 7), (3, 7),
                     (4, 7), (5, 6)],
              directed=True)
grafo.vs['label'] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
grafo.es['weight'] = [2, 1, 2, 1, 2, 1, 3, 1]

# Colocando em cada aresta o valor da distância:
plot(grafo, bbox=(300, 300), edge_label=grafo.es['weight'])

# Descobrir a menor rota entre A e H:
caminho_vertice = grafo.get_shortest_paths(0, 7, output='vpath')
# índice 0 = A; índice 7 = H
# output = vpath =  cria uma lista com o caminho na saída
# Para visualizar o nome do vértice ao invés do índice:
for n in caminho_vertice[0]:
    #print(n)
    print(grafo.vs[n]['label'])

# com 'epath' retorna as arestas que foram visitadas
caminho_aresta = grafo.get_shortest_paths(0, 7, output='epath')

# Codificação para retornar o valor da distância:
caminho_aresta_id = []
vertexBetweennessList = graph.betweenness(vertices=None, directed=False)
#print vertexBetweennessList
list2 = sorted(range(len(vertexBetweennessList)),
               key=lambda i: vertexBetweennessList[i])[-5:]
print "Five nodes with the highest vertex betweenness are {}, {}, {}, {}, {}".format(
    list2[0], list2[1], list2[2], list2[3], list2[4])

visual_style = {}
visual_style["edge_curved"] = False
visual_style["vertex_color"] = "#95D2CB"
visual_style["vertex_size"] = 15
visual_style["vertex_label_size"] = 12

#igraph.summary(graph)
igraph.plot(graph, "erdosRenyiNetwork.png", **visual_style)

visual_style1 = {}
visual_style1["edge_curved"] = False
visual_style1["vertex_size"] = 15
visual_style1["vertex_label_size"] = 12

#print(communities)
louvainCommunity = graph.community_multilevel()
#print louvainCommunity
print "No of community = {}".format(louvainCommunity.cluster_graph().vcount())
print "Modularity of communities detected by Louvain Algorithm on the Erdos-Renyi graph =  {}".format(
    louvainCommunity.modularity)
igraph.plot(louvainCommunity, "LouvainOnErdosRenyi.png", **visual_style1)

girvanNewmanCommunity = graph.community_edge_betweenness().as_clustering()
Exemplo n.º 40
0
def visualize_gat_properties(model_name=r'gat_PPI_000000.pth',
                             dataset_name=DatasetType.PPI.name,
                             visualization_type=VisualizationType.ATTENTION):
    # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")  # checking whether you have a GPU, I hope so!
    device = torch.device("cpu")
    config = {
        'dataset_name': dataset_name,
        'should_visualize': False,  # don't visualize the dataset
        'batch_size': 2,  # used only for PPI
        'ppi_load_test_only':
        True  # used only for PPI (optimization, we're loading only test graphs)
    }

    # Step1:准备数据
    data_loader_test = load_graph_data(config, device)
    node_features, node_labels, topology = next(iter(data_loader_test))
    node_features = node_features.to(device)
    node_labels = node_labels.to(device)
    topology = topology.to(device)

    # Step2:准备模型
    model_path = os.path.join('models/binaries/', model_name)
    model_state = torch.load(model_path)

    gat = GAT_ppi(num_of_layers=model_state['num_of_layers'],
                  num_heads_per_layer=model_state['num_heads_per_layer'],
                  num_features_per_layer=model_state['num_features_per_layer'],
                  add_skip_connection=model_state['add_skip_connection'],
                  bias=model_state['bias'],
                  dropout=model_state['dropout'],
                  log_attention_weights=True).to(device)

    print_model_metadata(model_state)

    assert model_state['dataset_name'].lower() == dataset_name.lower(), \
        f"The model was trained on {model_state['dataset_name']} but you're calling it on {dataset_name}."

    gat.load_state_dict(model_state["state_dict"], strict=True)
    gat.eval()

    with torch.no_grad():
        all_nodes_unnormalized_scores, _ = gat(
            (node_features, topology))  # shape = (N, num of classes)
        all_nodes_unnormalized_scores = all_nodes_unnormalized_scores.cpu(
        ).numpy()

    if visualization_type == VisualizationType.ATTENTION:
        num_nodes_of_interest = 4  # 选多少个要看的节点
        head_to_visualize = 0  # 要看的head,随便改
        gat_layer_id = 0  # 要看的层

        # assert gat_layer_id == 0, f'Attention visualization for {dataset_name} is only available for the first layer.'

        # 建立完整图
        total_num_of_nodes = len(all_nodes_unnormalized_scores)
        complete_graph = ig.Graph()
        complete_graph.add_vertices(total_num_of_nodes)
        edge_index_tuples = list(zip(topology[0, :], topology[1, :]))
        complete_graph.add_edges(edge_index_tuples)

        nodes_of_interest_ids = np.argpartition(
            complete_graph.degree(),
            -num_nodes_of_interest)[-num_nodes_of_interest:]
        """np.argpartition这个函数是快排的partition操作, kth指定第k大的数字,返回的是下标值,在这里就是找度数最大的num_nodes_of_interest个值的下标"""
        random_node_ids = np.random.randint(low=0,
                                            high=total_num_of_nodes,
                                            size=num_nodes_of_interest)  # 随机取
        nodes_of_interest_ids = np.append(nodes_of_interest_ids,
                                          random_node_ids)
        np.random.shuffle(nodes_of_interest_ids)

        target_node_ids = topology[1]
        source_nodes = topology[0]

        for target_node_id in nodes_of_interest_ids:

            # step1 找邻居
            src_nodes_indices = torch.eq(target_node_ids, target_node_id)
            source_node_ids = source_nodes[src_nodes_indices].cpu().numpy()
            size_of_neighborhood = len(source_node_ids)

            # step2 获得标签
            labels = node_labels[source_node_ids].cpu().numpy()

            # step3 获得aij
            all_attention_weights = gat.gat_net[
                gat_layer_id].attention_weights.squeeze(dim=-1)
            attention_weights = all_attention_weights[
                src_nodes_indices, head_to_visualize].cpu().numpy()
            attention_weights /= np.max(attention_weights)  # 归一化

            # step4 把原邻居id映射到邻居子图上
            id_to_igraph_id = dict(
                zip(source_node_ids, range(len(source_node_ids))))

            # step5 建立子图
            ig_graph = ig.Graph()
            ig_graph.add_vertices(size_of_neighborhood)
            ig_graph.add_edges([(id_to_igraph_id[neighbor],
                                 id_to_igraph_id[target_node_id])
                                for neighbor in source_node_ids])

            visual_style = {
                "edge_width": attention_weights,
                "layout": ig_graph.layout_kamada_kawai()
                # layout_kamada_kawai()  仿真强化
                # layout_reingold_tilford_circular()  树状图
            }
            ig.plot(ig_graph, **visual_style)
            image = ig.plot(ig_graph, **visual_style)
            image.save(
                f'可视化/ppi/node{target_node_id}_layer{gat_layer_id }_head{head_to_visualize}.png'
            )

    elif visualization_type == VisualizationType.ENTROPY:
        num_heads_per_layer = [layer.num_of_heads for layer in gat.gat_net]
        num_layers = len(num_heads_per_layer)
        num_of_nodes = len(node_features)

        target_node_ids = topology[1].cpu().numpy()

        for layer_id in range(num_layers):

            all_attention_weights = gat.gat_net[
                layer_id].attention_weights.squeeze(dim=-1).cpu().numpy()

            if dataset_name == DatasetType.PPI.name and layer_id < 2:
                print(
                    f'Entropy histograms for {dataset_name} are available only for the first,second layer.'
                )
                break

            for head_id in range(num_heads_per_layer[layer_id]):
                uniform_dist_entropy_list = []
                neighborhood_entropy_list = []

                for target_node_id in range(num_of_nodes):
                    neigborhood_attention = all_attention_weights[
                        target_node_ids == target_node_id].flatten()

                    ideal_uniform_attention = np.ones(
                        len(neigborhood_attention)) / len(
                            neigborhood_attention)

                    neighborhood_entropy_list.append(
                        entropy(neigborhood_attention, base=2))
                    uniform_dist_entropy_list.append(
                        entropy(ideal_uniform_attention, base=2))

                title = f'{dataset_name} entropy histogram layer={layer_id}, attention head={head_id}'

                draw_entropy_histogram(uniform_dist_entropy_list,
                                       title,
                                       color='orange',
                                       uniform_distribution=True)
                draw_entropy_histogram(neighborhood_entropy_list,
                                       title,
                                       color='dodgerblue')

                fig = plt.gcf()  # get current figure
                plt.show()
                fig.savefig(f'可视化/ppi/layer_{layer_id}_head_{head_id}.jpg')
                plt.close()
Exemplo n.º 41
0
PlottingTopVorE(mkt_coms, top20_edges, path='F:/BigDataCareer/Python/')

# note: the plot may not properly show the name of nodes in IPython when a single plot is produced(at least, in Spyder), so I save the plot as a png picture in the working directory, then the names of nodes are properly displayed

# community 0
# top 20 nodes with highest degree
# extracting top 20 nodes from the list
top20_v_00 = [i[0] for i in sub00_dict_sorted[:20]]
# getting a subgraph of 20 nodes
sub00_top20_v = mkt_com_ml_sub00.subgraph(top20_v_00)
# plotting
ig.plot(sub00_top20_v,
        layout='circular',
        vertex_label=sub00_top20_v.vs['name'],
        vertex_size=2,
        vertex_label_size=30,
        edge_label=None,
        bbox=(1500, 1500),
        margin=50,
        target='sub00_top20_v.png')

sub00_top20_v.density()
# top 20 edges with highest weight
# extracting top 20 edges from the list
top20_e_00 = [i[0] for i in sub00_e_dict_sorted[:20]]
# getting a subgraph of 20 edges
sub00_top20_e = mkt_com_ml_sub00.subgraph_edges(top20_e_00)
# plotting
ig.plot(sub00_top20_e,
        layout='circular',
        vertex_label=sub00_top20_e.vs['name'],
Exemplo n.º 42
0
        persons_like_mes1.add(data1_mes[k]['likes']['data'][w]['name'])
for l in range(len(data2_mes)):
    for y in range(len(data2_mes[l]['likes']['data'])):
        persons_like_mes2.add(data2_mes[l]['likes']['data'][y]['name'])

g = ig.Graph()

g.add_vertex("MetalGearJp", color="#000", size=150)
g.add_vertex("KonamiJp", color="#FFFFFF", size=150)

#Se itera sobre las ids de las personas que han puesto like
#Esta id se mantiene en vert
#Luego se anyade el vertice usando un color cercano al turquesa 
for vert in (persons_like_mes1 | persons_like_mes2):
    g.add_vertex(vert, color="#00bbff" size=10)

#Se itera sobre las ids de las personas que les gusta la pagina 1
#Se almacena en vert i se añade una linea o arista entre la bola
#de la pagina 1 y vert
for vert in (persons_like_mes1):
    g.add_edge(vert,"MetalGearJp")

#Se itera sobre las ids de las personas que les gusta la pagina 2
#Se almacena en vert i se añade una linea o arista entre la bola
#de la pagina 2 y vert
for vert in (persons_like_mes2):
    g.add_edge(vert,"KonamiJp")
#Se genera una imagen del grafico a un tamaño personalizado y de fondo color plomo     
ig.plot(g, bbox=(1920,1080), background="#171717", layout='lgl')

Exemplo n.º 43
0
from igraph import Graph, plot

g=Graph()
g.add_vertices(3)
g.add_edges([(0,1),(1,2)])
layout = g.layout("rt", 2)
plot(g, layout=layout)
Exemplo n.º 44
0
g = igraph.Graph()

vertex = []
for edge in graph_edges:
    vertex.extend(edge)
graph_vertices = list(set(vertex))
g.add_vertices(graph_vertices)  # add a list of unique vertices to the graph
g.add_edges(graph_edges)  # add the edges to the graph.

print('Communities:')
p = g.community_multilevel()
print(p)
print('Number of communities')
print(len(p))

if print_communities_details:
    show_big_communities(g, p, graph_vertices, authorship)

print_graph_details(g, p)

if print_graph:
    g.vs["label"] = g.vs["name"]
    # layout = g.layout("mds")
    layout = g.layout("graphopt")
    igraph.plot(g,
                layout=layout,
                bbox=(10000, 10000),
                vertex_size=40,
                edge_width=2,
                label_size=10)
Exemplo n.º 45
0
# Set edges attributes
network_i.es['color'] = [
    '#e74c3c' if e['beta'] < 0 else '#2ecc71' for e in network_i.es
]

# Calculate layout
layout = network_i.layout_fruchterman_reingold(maxiter=10000,
                                               area=50 *
                                               (len(network_i.vs)**2))
print '[INFO] Network layout created: ', network_i.summary()

# Export network
igraph.plot(network_i,
            layout=layout,
            bbox=(0, 0, 360, 360),
            vertex_label_size=5,
            vertex_frame_width=0,
            vertex_size=20,
            edge_width=1.,
            target='%s/reports/Figure_4.pdf' % wd)
print '[INFO] Network exported: ', network_i.summary()

# -- Betas heatmap
cmap = sns.diverging_palette(220, 10, n=9, as_cmap=True)

plot_df = lm_betas_kinases.loc[:, [m in met_name for m in lm_betas_kinases]]
plot_df.columns = [met_name[m] for m in plot_df]
plot_df.index = [acc_name[i].split(';')[0] for i in plot_df.index]

sns.set(style='white', palette='pastel')
sns.clustermap(plot_df.T, figsize=(15, 20), cmap=cmap, linewidth=.5)
plt.savefig('%s/reports/Figure_Supp_4_kinases_dynamic_betas.pdf' % wd,
Exemplo n.º 46
0
def plot_graph(graph: int):
    lastname = get_friends(graph, 'last_name')
    vertices = [lastname['items'][i]['first_name']
                + ' ' + lastname['items'][i]['last_name']
                for i in range(lastname['count'])]
    edges = get_network(get_friends_id(graph), False)
    if isinstance(edges, ndarray):
        g = Graph.Adjacency(edges.tolist(), mode='undirected')
        g.vs['label'] = vertices
        g.vs['shape'] = 'triangle'
        g.vs['size'] = 10
    else:
        # Создание графа
        g = Graph(vertex_attrs={"shape": "triangle",
                                "label": vertices,
                                "size": 10},
                  edges=edges, directed=False)

    # Задаем стиль отображения графа
    n = len(vertices)
    visual_style = {"vertex_size": 20,
                    "bbox": (2000, 2000),  # размер поля
                    "margin": 100,  # расстояние от края до вершин
                    "vertex_label_dist": 1.6,  # расстояние между вершинами
                    "edge_color": "gray",
                    "autocurve": True,  # кривизна ребер
                    "layout": g.layout_fruchterman_reingold(
                        # Fruchterman-Reingold force-directed algorithm
                        # алгоритм компоновки
                        maxiter=1000,
                        # the maximum distance to move a vertex in an
                        # iteration. The default is the number of vertices
                        area=n ** 3,
                        # he area of the square on which the vertices will
                        #  be placed. The default is the square of the number
                        # of vertices.
                        repulserad=n ** 3
                        # determines the radius at which vertex-vertex
                        # repulsion cancels out attraction of adjacent
                        # vertices. The default is the number of vertices^3.
                    )}
    g.simplify(multiple=True, loops=True)
    # Отрисовываем граф
    clusters = g.community_multilevel()
    # Finds the community structure of the graph according
    # to the multilevel algorithm of Blondel et al.
    '''
    Это восходящий алгоритм: первоначально каждая вершина принадлежит 
    отдельному сообществу, а вершины перемещаются между сообществами 
    итеративно таким образом, чтобы максимизировать локальный вклад 
    вершин в общий показатель модульности. Когда достигнут консенсус 
    (т. Е. Ни один шаг не увеличит оценку модульности), каждое сообщество 
    исходного графа сократится до одной вершины (при сохранении общего 
    веса краев инцидентов), и процесс продолжит на следующем уровне. 
    Алгоритм останавливается, когда невозможно увеличить модульность 
    после сжатия сообществ до вершин.
    '''
    pal = igraph.drawing.colors.ClusterColoringPalette(len(clusters))
    # A palette suitable for coloring vertices when plotting a clustering.
    g.vs['color'] = pal.get_many(clusters.membership)
    plot(g, **visual_style)
Exemplo n.º 47
0
from igraph import Graph
from igraph import plot

grafo1 = Graph(edges=[(0, 1), (1, 2), (2, 3), (3, 0)], directed=True)
grafo1.vs['label'] = range(grafo1.vcount())
print(grafo1)
plot(grafo1, bbox=(300, 300))

grafo2 = Graph(edges=[(0, 1), (1, 2), (2, 3), (3, 0), (0, 3), (3, 2), (2, 1),
                      (1, 0)],
               directed=True)
grafo2.vs['label'] = range(grafo2.vcount())
plot(grafo2, bbox=(300, 300))

grafo3 = Graph(edges=[(0, 1), (1, 2), (2, 3), (3, 0), (1, 1)], directed=True)
grafo3.vs['label'] = range(grafo3.vcount())
plot(grafo3, bbox=(300, 300))

grafo4 = Graph(edges=[(0, 1), (1, 2), (2, 3), (3, 0), (1, 1)], directed=True)
grafo4.add_vertex(5)
grafo4.vs['label'] = range(grafo4.vcount())
plot(grafo4, bbox=(300, 300))
Exemplo n.º 48
0
def plot_wf(wf, view='combined', labels=False, **kwargs):
    """Plot workflow DAG via igraph.plot.

    Args:
        wf (Workflow)
        view (str): same as in 'to_dot'. Default: 'combined'
        labels (bool): show a FW's name and id as labels in graph

    Other **kwargs can be any igraph plotting style keyword, overrides default.
    See https://igraph.org/python/doc/tutorial/tutorial.html for possible
    keywords. See `plot_wf` code for defaults.

    Returns:
        igraph.drawing.Plot
    """

    dagf = DAGFlow.from_fireworks(wf)
    if labels:
        dagf.add_step_labels()

    # copied from to_dot
    if view == 'controlflow':
        dagf.delete_dataflow_links()
    elif view == 'dataflow':
        dagf.delete_ctrlflow_links()
    elif view == 'combined':
        dlinks = []
        for vertex1, vertex2 in combinations(dagf.vs.indices, 2):
            clinks = list(
                set(dagf.incident(vertex1, mode='ALL'))
                & set(dagf.incident(vertex2, mode='ALL')))
            if len(clinks) > 1:
                for link in clinks:
                    if dagf.es[link]['label'] == ' ':
                        dlinks.append(link)
        dagf.delete_edges(dlinks)

    # remove non-string, non-numeric attributes because write_dot() warns
    for vertex in dagf.vs:
        for key, val in vertex.attributes().items():
            if not isinstance(val, (str, int, float, complex)):
                del vertex[key]
            if isinstance(val, bool):
                del vertex[key]

    # plotting defaults
    visual_style = DEFAULT_IGRAPH_VISUAL_SYTLE.copy()

    # generic plotting defaults
    visual_style["layout"] = dagf.layout_kamada_kawai()

    # vertex defaults
    dagf_roots = dagf._get_roots()
    dagf_leaves = dagf._get_leaves()

    def color_coding(v):
        if v in dagf_roots:
            return DEFAULT_IGRAPH_VERTEX_COLOR_CODING['root']
        elif v in dagf_leaves:
            return DEFAULT_IGRAPH_VERTEX_COLOR_CODING['leaf']
        else:
            return DEFAULT_IGRAPH_VERTEX_COLOR_CODING['other']

    visual_style["vertex_color"] = [
        color_coding(v) for v in range(dagf.vcount())
    ]

    visual_style.update(kwargs)

    # special treatment
    if 'layout' in kwargs and isinstance(kwargs['layout'], str):
        visual_style["layout"] = dagf.layout(kwargs['layout'])

    return igraph.plot(dagf, **visual_style)
Exemplo n.º 49
0
#  initialise edges by value given by vs_dict: input coordinate, ouput val
edges = [(vs_dict[key0], vs_dict[key1]) for key0, key1 in lstrings]
print("{:21}{:4d}".format("Number of edges: ", len(edges)))

G = igraph.Graph()
G.add_vertices(len(vs_dict))
G.add_edges(edges)
visual_style = {}
visual_style["vertex_size"] = 5
visual_style["vertex_shape"] = "circle"
visual_style["layout"] = 'lgl'
visual_style["bbox"] = (1024, 1024)
visual_style["margin"] = 10
layout = G.layout('kk')
fig = igraph.plot(G, layout=layout, vertex_size=3)
fig.show()

#    data.apply(shapely.wkb.loads)
#    data.ST_AsText(SHAPE) = shapely.wkt.loads(data.ST_AsText(SHAPE))
#    query_memphis = ("")

#    lstrings[0].apply
#    print(type(a))
#    print(a)
#    a.append(shapely.geometry.asLineString(lstrings[0]))
#    print(type(lstrings))
#    fig = plt.figure()
#    ax = fig.add_subplot(111)
#    gpd.plotting.plot_linestring_collection(ax, ls, color='blue')
Exemplo n.º 50
0
import re
import igraph
#IN_FILE = "repo-gru.cflow"
IN_FILE = "opencv.cflow"
with open(IN_FILE) as f:
    tree = list(f)

parent = None
graph = igraph.Graph(directed=True)
for line in tree:
    #Check if it's a 0-level function (caller/parent function)
    if line[0] != " ":
        regex = re.match("^(.+)?\(\)", line)
        parent = regex.groups()[0]
        graph.add_vertex(parent)
    else:
        #It is a 1-level function (called by the parent)
        regex = re.match("^\s{4}(.+)?\(\)", line)
        called = regex.groups()[0]
        graph.add_vertex(called)
        graph.add_edge(parent, called)

print("Done generating graph")
print("Starting plotting algorithm")
igraph.plot(graph, "img.png")
#find . -iname "*.c" | xargs cflow -m asdfasdf --depth=2
Exemplo n.º 51
0
import igraph as ig
from util import get_color_arr

N = 13
g = ig.Graph.Tree(N, 3)
layout = g.layout_reingold_tilford(mode="in", root=[0])
g.vs['size'] = ['60']
g.vs['color'] = get_color_arr(N, 3)
g.vs['label'] = [
    '[ ]', '[a]', '[b]', '[c]', '[ad]', '[ae]', '[af]', '[bd]', '[be]', '[bf]',
    '[cd]', '[ce]', '[cf]'
]
g.vs['label_size'] = ['20']

g.write_svg('001.svg', layout=layout, vertex_size=20)
ig.plot(g, layout=layout, bbox=(800, 300), margin=50)
Exemplo n.º 52
0
#!/usr/bin/env python
# coding: utf-8

"""Docstring of the module mmd
"""

from __future__ import division
from __future__ import print_function

# wh for def cl defs ifmain imp fr _ pdb + <Tab>

"""Kiírja a maximális és minimális fokszámot.
"""

import maxmindeg
import igraph

net = maxmindeg.Network.Formula("a-b-c,d-b-e,f-g,h")
for v in net.vs:
    print(v.index, v["name"])
print(net.vs["name"])
print(net.component(0))
# print(net.maxmindegree())
igraph.plot(net)


Exemplo n.º 53
0
import igraph
import price

# Define variables
sv = 3  # starting vertices
at = .8  # attractivity
ns = 20  # network size
""" Create a graph, and print out its properties
"""
p = price.price(sv, at, ns)

# Summary
print()
print("Starting vertices: ", sv)
print("Attractivity: ", at)
print("Network size: ", ns)
print()

print("vcount: ", p.vcount())
print("ecount: ", p.ecount())

print("directed: ", p.is_directed())

print("indegree: ", p.indegree())
print("outdegree:", p.outdegree())

# Plot the graph
p.vs["label"] = range(p.vcount())
p.vs["color"] = "yellow"
igraph.plot(p)
Exemplo n.º 54
0
nodes = pd.read_csv(n)  #names of nodes
n.close()

a_numpy = Adj.as_matrix()
conn_indices = np.where(a_numpy)
# Get the values as np.array, it's more convenenient.
weights = a_numpy[conn_indices]

# a sequence of (i, j) tuples, each corresponding to an edge from i -> j
edges = zip(*conn_indices)

# initialize the graph from the edge sequence

G = igraph.Graph(edges=edges, directed=True)

# assign node names and weights to be attributes of the vertices and edges
# respectively
node_names = nodes['id']
G.es['width'] = weights
G.vs['label'] = node_names
G.es['weight'] = weights

G.es['width'] = weights / 10
# plot the graph
out = igraph.plot(G,
                  '../Results/Netspy.pdf',
                  layout="rt",
                  labels=True,
                  margin=80)
print 'Netspy.pdf saved to Results'
Exemplo n.º 55
0
my_links = []  #备用空列表
for i in df.index:  #外层循环,轮询excel每个列
    for j in df.columns:  #内层循环,轮询excel每一行
        if df[j][i] > 0:  #大于0的值有效
            my_links.append({'source': i, 'target': (j), 'value': df[j][i]})
            g.add_edge(i, j)
            weights.append(df[j][i])
        else:
            pass

if not g.vs[0]['name']:
    g.delete_vertices(0)
result = g.community_multilevel(weights, True)

igraph.plot(result[1],
            mark_groups=True,
            margin=20,
            vertex_label=[str(i) for i in range(len(df.index))])

#colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
colors_list = [
    'yellowgreen', 'gold', 'lightskyblue', 'lightcoral', 'darkslateblue',
    '#ADD8E6', '#DDA0DD', '#FAA460', '#F0E68C', '#8c564b', '#e377c2',
    '#7f7f7f', '#bcbd22', '#17becf'
]
category_dic = {}
for list_data in result[1]:
    for data in list_data:
        category_dic[df.index[data]] = df.index[list_data[0]]

sym_x = []
sym_y = []
Exemplo n.º 56
0
#   col.names=FALSE, file="elist_lazega.ncol")
g = ig.Graph.Read_Ncol("elist_lazega.ncol",
                       weights="if_present",
                       directed=False)

# Created in R via:
#   attrs <- list.vertex.attributes(lazega)
#   cols <- vector("list", length(attrs))
#   for (i in 1:length(cols)) {
#       cols[[i]] <- get.vertex.attribute(lazega,attrs[i])
#   }
#   v.attr.lazega <- data.frame(cols)
#   names(v.attr.lazega) <- list.vertex.attributes(lazega)
# > write.csv(v.attr.lazega,row.names=FALSE,file="v_attr_lazega.csv")
# (Note: in order to work, this very much depends on the vertices appearing
#   in the .ncol file in the same order as they appear in the .csv file!)
v_attr_df = pd.read_csv("v_attr_lazega.csv")
for col in v_attr_df.columns[1:]:
    g.vs[col] = v_attr_df[col]

# Some plotting defaults, to give you the idea. When I run this, I get a file
# called "aplot.pdf" produced with the plot. Yours may auto-appear, not sure.
style = {'margin': 70}
ig.plot(g,
        "aplot.pdf",
        vertex_label=g.vs['name'],
        vertex_size=18,
        vertex_label_dist=2,
        layout=g.layout("kk"),
        **style)
Exemplo n.º 57
0
dim = shape(data_mat)[1]
col_mean = mean(data_mat, axis=0)
data_mat = mat((data_mat - col_mean) / sqrt(diag(cov(data_mat, rowvar=0))))

corr_mat = corrcoef(data_mat, rowvar=0)

# screening the correlation matrix
omega = matrix(zeros(shape=(dim, dim)))
for r in range(0, dim):
    for c in range(0, dim):
        if r == c:
            omega[r, c] = 0
        elif abs(corr_mat[r, c]) < threshold:
            omega[r, c] = 0
        else:
            omega[r, c] = 1

# visualize the graph
import igraph
plot_path = result_dir + "/graph_py.png"
g = igraph.Graph.Adjacency(omega.tolist()).as_undirected()
igraph.plot(g,
            plot_path,
            vertex_size=[24],
            vertex_color=["red"],
            vertex_label=range(1, dim + 1),
            vertex_label_size=[12],
            layout=g.layout_fruchterman_reingold(),
            margin=60,
            bbox=(690, 460))
Exemplo n.º 58
0
g = ig.Graph()
g.add_vertices(12)
g.add_edges([(0, i) for i in [1, 2, 6, 9, 11]])
g.add_edges([(1, i) for i in [2, 3, 4, 9]])
g.add_edges([(2, i) for i in [3, 6]])
g.add_edges([(3, i) for i in [4, 5]])
g.add_edges([(5, i) for i in [6]])
g.add_edges([(6, i) for i in [7, 11]])
g.add_edges([(7, i) for i in [10, 11]])
g.add_edges([(8, i) for i in [9]])
g.add_edges([(9, i) for i in [10]])
# 11, 10 and 4 do not connect to a higher-index vertex

vx = [0.0] * len(g.vs)
vy = [0.0] * len(g.vs)
label = [""] * len(g.vs)
for i, v in enumerate(g.vs):
    ((x, y, z), rot) = listener.lookupTransform('/world', "/Node%d" % v.index,
                                                rospy.Time(0))
    vx[i] = x
    vy[i] = y
    label[i] = "Node%d" % v.index
g.vs["x"] = vx
g.vs["y"] = vy
g.vs["label"] = label

layout = g.layout("auto")
ig.plot(g, 'graph.png', layout=layout, label_dist=[100.] * len(g.vs))
g.write_picklez("graph.picklez")
print "Saved graph"