Пример #1
1
def plot_co_x(cox, start, end, size = (20,20), title = '', weighted=False, weight_threshold=10):

        """ Plotting function for keyword graphs

        Parameters
        --------------------
        cox: the coword networkx graph; assumes that nodes have attribute 'topic'
        start: start year
        end: end year
        """

        plt.figure(figsize=size)
        plt.title(title +' %s - %s'%(start,end), fontsize=18)
        if weighted:
            elarge=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] >weight_threshold]
            esmall=[(u,v) for (u,v,d) in cox.edges(data=True) if d['weight'] <=weight_threshold]
            pos=nx.graphviz_layout(cox) # positions for all nodes
            nx.draw_networkx_nodes(cox,pos,
                node_color= [s*4500 for s in nx.eigenvector_centrality(cox).values()],
                node_size = [s*6+20  for s in nx.degree(cox).values()],
                alpha=0.7)
            # edges
            nx.draw_networkx_edges(cox,pos,edgelist=elarge,
                                width=1, alpha=0.5, edge_color='black') #, edge_cmap=plt.cm.Blues
            nx.draw_networkx_edges(cox,pos,edgelist=esmall,
                                width=0.3,alpha=0.5,edge_color='yellow',style='dotted')
            # labels
            nx.draw_networkx_labels(cox,pos,font_size=10,font_family='sans-serif')
            plt.axis('off')
        else:
            nx.draw_graphviz(cox, with_labels=True,
                         alpha = 0.8, width=0.1,
                         fontsize=9,
                         node_color = [s*4 for s in nx.eigenvector_centrality(cox).values()],
                         node_size = [s*6+20 for s in nx.degree(cox).values()])
Пример #2
0
    def createGraph(self):
        # get node
        myNode = self.db.execute("select distinct disverb  from (select distinct last_verb as disverb from verb UNION ALL select distinct post_verb as disverb from verb)")
        # create_node
        for row in myNode:
            g.add_node(row[0])
        
        # create edge
        c = self.db.execute("select * from verb where post_verb <> ''")
        for row in c:
            g.add_edge(row[1], row[2], weight = row[3]/3000)
            #g.add_edge(row[1], row[2], weight = 1)

        estrong = [(u,v) for (u,v,d) in g.edges(data=True) if d["weight"] > 0.001]
        pos=nx.spring_layout(g) # positions for all nodes

        # nodes
        nx.draw_networkx_nodes(g,pos,node_size=500)
        
        # edges
        nx.draw_networkx_edges(g,pos,edgelist=estrong,width=2)
        #nx.draw_networkx_edges(g,pos,edgelist=esmall,width=6,alpha=0.5,edge_color='b',style='dashed')
        
        # labels
        nx.draw_networkx_labels(g,pos,font_size=15,font_family='sans-serif')

        fig=plt.figure(figsize =(10 ,10))
        nx.draw(g)
        plt.axis("tight")
        fig.savefig ("C:/Users/n_shimada/Documents/networkxGraphGal_onlyBuy.pdf")
        plt.show()
Пример #3
0
  def drawFactorGraph(self,var_color='w',factor_color=(.2,.2,.8),**kwargs):
    """Draw a factorgraph using networkx function calls

    Args:
      var_color (str, tuple): networkx color descriptor for drawing variable nodes
      factor_color (str, tuple): networkx color for drawing factor nodes
      var_labels (dict): variable id to label string for variable nodes
      factor_labels (dict): factor id to label string for factor nodes
      ``**kwargs``: remaining keyword arguments passed to networkx.draw()

    Example:
    >>> model.drawFactorGraph( var_labels={0:'0', ... } )    # keyword args passed to networkx.draw()
    """
    # TODO: specify var/factor shape,size, position, etc.; return G? silent mode?
    import networkx as nx
    G = nx.Graph()
    vNodes = [v.label for v in self.X if v.states > 1]   # list only non-trivial variables
    fNodes = [-i-1 for i in range(len(self.factors))]    # use negative IDs for factors
    G.add_nodes_from( vNodes )
    G.add_nodes_from( fNodes )
    for i,f in enumerate(self.factors):
      for v1 in f.vars:
        G.add_edge(v1.label,-i-1)
   
    pos = nx.spring_layout(G)   # so we can use same positions multiple times...
    kwargs['var_labels']  = kwargs.get('var_labels',{n:n for n in vNodes})
    kwargs['labels'] = kwargs.get('var_labels',{})
    nx.draw_networkx(G,pos, nodelist=vNodes,node_color=var_color,**kwargs)
    kwargs['labels'] = kwargs.get('factor_labels',{})    # TODO: need to transform?
    nx.draw_networkx_nodes(G,pos, nodelist=fNodes,node_color=factor_color,node_shape='s',**kwargs)
    nx.draw_networkx_edges(G,pos,**kwargs)
    return G
Пример #4
0
def main():
    G=nx.Graph()

    G.add_edge('a','b',weight=0.6)
    G.add_edge('a','c',weight=0.2)
    G.add_edge('c','d',weight=0.1)
    G.add_edge('c','e',weight=0.7)
    G.add_edge('c','f',weight=0.9)
    G.add_edge('a','d',weight=0.3)

    elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5]
    esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5]

    pos=nx.spring_layout(G) # positions for all nodes

# nodes
    nx.draw_networkx_nodes(G,pos,node_size=700)

# edges
    nx.draw_networkx_edges(G,pos,edgelist=elarge,width=6)
    nx.draw_networkx_edges(G,pos,edgelist=esmall,width=6,alpha=0.5,edge_color='b',style='dashed')

# labels
    nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif')

    plt.axis('off')
#plt.savefig("weighted_graph.png") # save as png
    plt.show() # display
    return
	def plot(self,figure):		
		changed	= False
		for ip in self.stats:
			if ip is not "127.0.0.1" and not self.graph.has_node(ip):
				self.graph.add_node(ip,node_size=4000,node_shape="s")
				self.graph.add_edge(ip,"127.0.0.1",attr_dict={"label":"N/A"})
				changed = True
			for port in self.stats[ip]:
				#pnode = ip + ":" + port
				pnode = port
				if not self.graph.has_node(pnode):
					statName = ip + ":" + port
					self.graph.add_node(pnode,attr_dict={"node_size":700,"node_shape":"o","font_size":8})
					self.graph.add_edge(pnode ,ip, attr_dict={"label":"N/A"})
					changed = True
		if changed:
			figure.clf()
			pos = nx.spring_layout(self.graph, weight=None, iterations=100, scale = 2)
			#draw ip nodes
			ipNodeList = list(self.stats)
			#print(ipNodeList)
			try:
				nx.draw_networkx(self.graph, 
							nodelist = ipNodeList, 
							pos = pos, 
							with_labels = True,
							node_size = 4000 , 
							node_shape = "p", 
							font_size = 8
						)
			except nx.exception.NetworkXError:	# catch some error about a node not having a position yet (we just re-render, that does it)
				pass
			#draw port nodes
			portList = list(self.stats.values())
			portNodesList = [ item for sublist in (list(e) for e in portList) for item in sublist ]
			try:
				nx.draw_networkx_nodes(self.graph, 
							nodelist = portNodesList, 
							pos = pos ,
							with_labels = True,
							node_size = 700 , 
							node_shape = "o", 
							font_size=8
						)
				edges = self.graph.edges(data=True)
				labels = {}
				for (a, b, *c) in edges:
					stats = "N/A"
					if a in self.stats:
						if b in self.stats[a]:
							labels[a,b] = self.stats[a][b]
					else:
						if a in self.stats[b]:
							labels[b,a] = self.stats[b][a]
				nx.draw_networkx_edge_labels(self.graph, pos = pos, edge_labels=labels,ax=None)
			except nx.exception.NetworkXError:	# catch some error about a node not having a position yet (we just re-render, that does it)
				pass
			# draw connStats
			statNodesList = list(self.statNodes)
			figure.canvas.draw()
Пример #6
0
 def test_labels_and_colors(self):
     G = nx.cubical_graph()
     pos = nx.spring_layout(G)  # positions for all nodes
     # nodes
     nx.draw_networkx_nodes(G, pos,
                            nodelist=[0, 1, 2, 3],
                            node_color='r',
                            node_size=500,
                            alpha=0.8)
     nx.draw_networkx_nodes(G, pos,
                            nodelist=[4, 5, 6, 7],
                            node_color='b',
                            node_size=500,
                            alpha=0.8)
     # edges
     nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
     nx.draw_networkx_edges(G, pos,
                            edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
                            width=8, alpha=0.5, edge_color='r')
     nx.draw_networkx_edges(G, pos,
                            edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
                            width=8, alpha=0.5, edge_color='b')
     # some math labels
     labels = {}
     labels[0] = r'$a$'
     labels[1] = r'$b$'
     labels[2] = r'$c$'
     labels[3] = r'$d$'
     labels[4] = r'$\alpha$'
     labels[5] = r'$\beta$'
     labels[6] = r'$\gamma$'
     labels[7] = r'$\delta$'
     nx.draw_networkx_labels(G, pos, labels, font_size=16)
     plt.show()
Пример #7
0
    def draw_network(self, m=2, pos=None):
        edgelist = []
        probdict = {}
        nodesizes = {}
        position = {}
        observations = {}
        for i, node in enumerate(self.nodes[::-1]):
            l, u = node.ppf(.1), node.ppf(.9)
            c, w = .5 * (l + u), .5 * (u - l)
            edgelist += [(node.name, x.name) for x in node.children]
            probdict[node.name] = c
            nodesizes[node.name] = 100 + 5000 * w
            position[node.name] = (i / m, i % m) if pos is None else pos[node.name]
            observations[node.name] = '%.2f+/-%.2f' % (c, w)

        G = nx.DiGraph()
        G.add_edges_from(edgelist)
        values = [probdict.get(node) for node in G.nodes()]
        sizes = [nodesizes.get(node) for node in G.nodes()]

        plt.figure(figsize=(16,8))
        nx.draw_networkx_nodes(G, position, node_size=sizes, cmap=plt.get_cmap('Blues'), node_color=values, vmin=-0.1, vmax=1)
        nx.draw_networkx_labels(G, position, {x: x for x in G.nodes()}, font_size=12, font_color='r')
        nx.draw_networkx_labels(G, {key: (x[0] , x[1]+.3) for key, x in position.iteritems()}, observations,
                                font_size=12, font_color='k')
        nx.draw_networkx_edges(G, position, edgelist=edgelist, edge_color='r', arrows=True, alpha=0.5)
        # plt.xlim((-.15,.9))
        plt.show()
Пример #8
0
    def plot(self):
        """
        Plots an entity relation diagram (ERD) among all nodes that is part
        of the current graph.
        """
        if not self.nodes(): # There is nothing to plot
            logger.warning('Nothing to plot')
            return
        if pygraphviz_layout is None:
            logger.warning('Failed to load Pygraphviz - plotting not supported at this time')
            return

        pos = pygraphviz_layout(self, prog='dot')
        fig = plt.figure(figsize=[10, 7])
        ax = fig.add_subplot(111)
        nx.draw_networkx_nodes(self, pos, node_size=200, node_color='g')
        text_dict = nx.draw_networkx_labels(self, pos, self.node_labels)
        trans = ax.transData + \
            transforms.ScaledTranslation(12/72, 0, fig.dpi_scale_trans)
        for text in text_dict.values():
            text.set_horizontalalignment('left')
            text.set_transform(trans)
        # draw primary key relations
        nx.draw_networkx_edges(self, pos, self.pk_edges, arrows=False)
        # draw non-primary key relations
        nx.draw_networkx_edges(self, pos, self.non_pk_edges, style='dashed', arrows=False)
        apos = np.array(list(pos.values()))
        xmax = apos[:, 0].max() + 200  # TODO: use something more sensible than hard fixed number
        xmin = apos[:, 0].min() - 100
        ax.set_xlim(xmin, xmax)
        ax.axis('off')  # hide axis
Пример #9
0
def plot(CG):
    """
    Plot the call graph using matplotlib
    For larger graphs, this should not be used, as it is very slow
    and probably you can not see anything on it.

    :param CG: A networkx graph to plot
    """
    pos = nx.spring_layout(CG)

    internal = []
    external = []

    for n in CG.node:
        if isinstance(n, ExternalMethod):
            external.append(n)
        else:
            internal.append(n)

    nx.draw_networkx_nodes(CG, pos=pos, node_color='r', nodelist=internal)
    nx.draw_networkx_nodes(CG, pos=pos, node_color='b', nodelist=external)
    nx.draw_networkx_edges(CG, pos, arrow=True)
    nx.draw_networkx_labels(CG, pos=pos, labels={x: "{} {}".format(x.get_class_name(), x.get_name()) for x in CG.edge})
    plt.draw()
    plt.show()
Пример #10
0
def display_retweet_network(network, outfile=None, show=False):
    """
    Take a DiGraph (retweet network?) and display+/save it to file.
    Nodes must have a 'color' property, represented literally and indicating their type
    Edges must have a 'weight' property, represented as edge width
    """
    import networkx as nx
    import matplotlib.pyplot as plt

    # Create a color list corresponding to nodes.
    node_colors = [ n[1]["color"] for n in network.nodes(data=True) ]

    # Get edge weights from graph
    edge_weights = [ e[2]["weight"] for e in network.edges(data=True) ]

    # Build up graph figure
    #pos = nx.random_layout(network)
    pos = nx.spring_layout(network)
    nx.draw_networkx_edges(network, pos, alpha=0.3 , width=edge_weights, edge_color='m')
    nx.draw_networkx_nodes(network, pos, node_size=400, node_color=node_colors, alpha=0.4)
    nx.draw_networkx_labels(network, pos, fontsize=6)

    plt.title("Retweet Network", { 'fontsize': 12 })
    plt.axis('off')

    if outfile:
        print "Saving network to file: {0}".format(outfile)
        plt.savefig(outfile)

    if show:
        print "Displaying graph. Close graph window to resume python execution"
        plt.show()
def drawGraph(space):
    """
    Displays an edge and node graph to represent all of the planets in space 
    and their possible paths
    
    Parameters:
        space: a graph of all planets(nodes) and paths (edges) (digraph)
        
    Returns:
        A figure
    """
    pos = nx.spring_layout(space)
    nx.draw_networkx_nodes(space,pos)
    eone = [(u,v) for (u,v,d) in space.edges(data=True) if d['fuel']==1]
    etwo = [(u,v) for (u,v,d) in space.edges(data=True) if d['fuel']==2]
    ethree = [(u,v) for (u,v,d) in space.edges(data=True) if d['fuel']==3]
    efour = [(u,v) for (u,v,d) in space.edges(data=True) if d['fuel']==4]
    nx.draw_networkx_edges(space,pos,edgelist=eone,width=2,edge_color='green')
    nx.draw_networkx_edges(space,pos,edgelist=etwo,width=3,edge_color='blue')
    nx.draw_networkx_edges(space,pos,edgelist=ethree,width=4,edge_color='orange')
    nx.draw_networkx_edges(space,pos,edgelist=efour,width=5,edge_color='red')
    nx.draw_networkx_labels(space,pos)
    plt.axis("off")

    plt.show()
Пример #12
0
def calcMetrics():
    print('\nTrips:')
    for trip in trips:
        trip.display()
    print('\nPairs:')
    for a, b in itertools.combinations(trips, 2):
        # if isTimeTestFail(): continue
        bestDist = getBestDist(a, b)
        sumDist = a.dist + b.dist
        if bestDist > sumDist: continue
        minDist = min(a.dist, b.dist)
        maxDist = max(a.dist, b.dist)
        delta = sumDist - bestDist
        coPathCoeff = maxDist / bestDist
        effect = delta / bestDist
        weight = effect * coPathCoeff
        G.add_edge(a, b, weight=weight)
        print('edge is added', weight)

    pos = nx.random_layout(G)
    nx.draw_networkx_nodes(G, pos)
    nx.draw_networkx_edges(G, pos, width=weight,)
    plt.axis('off')
    plt.savefig("weighted_graph.png")  # save as png
    plt.show()  # display
Пример #13
0
 def _graph_intelligence_nx(bot, file_path):
     # TODO: Make BehaviorGraph track the launch node and mark it in the graph output
     print("Saving Champion Intelligence Graph...")
     behavior_nodes = bot.behavior.behavior_nodes
     network = nx.DiGraph()
     network.add_nodes_from(behavior_nodes)
     # Add the behavior nodes to the network and link them together
     for node in behavior_nodes:
         if node.node_type == NodeRegister.statement:
             network.add_edge(node, node.next_node, label='')
         elif node.node_type == NodeRegister.conditional:
             network.add_edge(node, node.true_node, label='1')
             network.add_edge(node, node.false_node, label='0')
     # Draw the network
     layout = nx.shell_layout(network, scale=3)
     plt.figure(figsize=(10, 10))
     plt.axis('equal')
     plt.title("%s: Born:%s, Age:%s, Peak Energy:%s, Children:%s" %
               (str(bot), str(bot.birthday), str(bot.age), str(bot.peak_energy), str(bot.number_children)))
     nx.draw_networkx_edges(network, layout, width=0.5, alpha=0.75, edge_color='black', arrows=True)
     statement_color = '#D7E7F7'
     conditional_color = '#F7D7DA'
     colors = [statement_color if node.node_type == NodeRegister.statement else conditional_color
               for node in network.nodes()]
     nx.draw_networkx_nodes(network, layout, node_size=1800, node_color=colors, alpha=1)
     # Reformat node names to make them easier to read
     names = [(node, str(node.function.__name__).replace('_', '\n')) for node in behavior_nodes]
     labels = {key: value for (key, value) in names}
     nx.draw_networkx_labels(network, layout, labels, font_size=10, font_family='sans-serif')
     edge_names = nx.get_edge_attributes(network, 'label')
     nx.draw_networkx_edge_labels(network, layout, edge_labels=edge_names, label_pos=0.7)
     plt.axis('off')
     plt.savefig(file_path + '.png', dpi=80, pad_inches=0.0, bbox_inches='tight')
Пример #14
0
def plotsolution(numnodes,coordinates,routes):
   plt.ion() # interactive mode on
   G=nx.Graph()
   
   nodes = range(1,numnodes+1)
   nodedict = {}
   for i in nodes:
     nodedict[i] = i
   
   nodecolorlist = ['b' for i in nodes]
   nodecolorlist[0] = 'r'
     
   # nodes  
   nx.draw_networkx_nodes(G, coordinates, node_color=nodecolorlist, nodelist=nodes)
   # labels
   nx.draw_networkx_labels(G,coordinates,font_size=9,font_family='sans-serif',labels = nodedict)
   
   edgelist = defaultdict(list)
   
   colors = ['Navy','PaleVioletRed','Yellow','Darkorange','Chartreuse','CadetBlue','Tomato','Turquoise','Teal','Violet','Silver','LightSeaGreen','DeepPink', 'FireBrick','Blue','Green']
   
   for i in (routes):
     edge1 = 1
     for j in routes[i][1:]:
       edge2 = j
       edgelist[i].append((edge1,edge2))
       edge1 = edge2
       nx.draw_networkx_edges(G,coordinates,edgelist=edgelist[i],
                        width=6,alpha=0.5,edge_color=colors[i]) #,style='dashed'
   
   plt.savefig("path.png")

   plt.show()
Пример #15
0
def draw_graphs(G,edge_pro_dict,Gmp,Ggp,Gadr,Gabm):
  plt.figure(1)
  pos=nx.spring_layout(G) # positions for all nodes
  nx.draw_networkx_nodes(G,pos,noG=800)
  nx.draw_networkx_edges(G,pos)
  nx.draw_networkx_labels(G,pos,font_size=10,font_family='sans-serif')
  nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_pro_dict)

  plt.figure(2)
  nx.draw_networkx_nodes(Gmp,pos,noG=800)
  nx.draw_networkx_edges(Gmp,pos)
  nx.draw_networkx_labels(Gmp,pos,font_size=10,font_family='sans-serif')

  plt.figure(3)
  nx.draw_networkx_nodes(Ggp,pos,noG=800)
  nx.draw_networkx_edges(Ggp,pos)
  nx.draw_networkx_labels(Ggp,pos,font_size=10,font_family='sans-serif')

  plt.figure(4)
  nx.draw_networkx_nodes(Gadr,pos,noG=800)
  nx.draw_networkx_edges(Gadr,pos)
  nx.draw_networkx_labels(Gadr,pos,font_size=10,font_family='sans-serif')

  plt.figure(5)
  nx.draw_networkx_nodes(Gabm,pos,noG=800)
  nx.draw_networkx_edges(Gabm,pos)
  nx.draw_networkx_labels(Gabm,pos,font_size=10,font_family='sans-serif')

  plt.show()
Пример #16
0
  def draw(self, layout_type='spring_layout'):
      '''
      Draw the graph
      
      layout_type = The type of layout algorithm (Default = 'spring_layout')
      '''
  
      import matplotlib.pyplot as plt
      
      try:
          pos = getattr(nx, layout_type)(self.G)
      except:
          raise Exception('layout_type of %s is not valid' % layout_type)
 
  
      nx.draw_networkx_nodes(self.G,pos,
                             nodelist=self.species,
                             node_color=self.options['species']['color'],
                             node_size=self.options['species']['size'],
                             alpha=self.options['species']['alpha'])
      nx.draw_networkx_edges(self.G, pos, edgelist=self.product_edges)
      nx.draw_networkx_edges(self.G, pos, edgelist=self.reactant_edges, arrows=False)
      nx.draw_networkx_edges(self.G, pos, edgelist=self.modifier_edges, style='dashed')
      
      labels = {}
      for n in self.G.nodes():
          if n in self.species:
              labels[n] = n
      nx.draw_networkx_labels(self.G,pos,labels,font_size=self.options['species']['label_size'])
      plt.axis('off')
      plt.show()
Пример #17
0
def draw_fault_scenario(title, fault_edge, pp, dp, fwp):
    nx.draw(G, pos, node_size=300, font_size=10, node_color='w', alpha=1, with_labels=True)

    if title is not None:
        plt.text(0.5, 0.5, title, fontsize=12)

    if pp is not None:
        draw_edge_node(pp, 0.8, 'b')
        # Source
        nx.draw_networkx_nodes(G, pos,
                               nodelist=[pp[0]],
                               node_color='black',
                               node_size=500,
                               label='S',
                               font_size=10,
                               node_shape='s',
                               alpha=0.5)
    # Detour path
    if dp is not None:
        draw_edge_node(dp, 0.8, 'g')

    # Fault edge
    if fault_edge is not None:
        nx.draw_networkx_edges(G, pos,
                               edgelist=[fault_edge],
                               width=4, alpha=0.8,
                               edge_color='r')
    # FW Back path
    if fwp is not None:
        draw_edge_node(fwp, 0.8, 'y', 'dashed')
Пример #18
0
def plot_networkx_topology_graph(topology):
    import matplotlib.pyplot as plt
    import networkx as nx

    G = nx.Graph()
    top_graph = topology.get_graph()
    labels = {}
    types = {}
    n_types = 0
    colors = []
    for v in top_graph.get_vertices():
        G.add_node(v.particle_index)
        labels[v.particle_index] = v.label
        if not v.particle_type() in types:
            types[v.particle_type()] = n_types
            n_types += 1
        colors.append(types[v.particle_type()])
    for v in top_graph.get_vertices():
        for vv in v:
            G.add_edge(v.particle_index, vv.get().particle_index)

    pos = nx.spring_layout(G)  # positions for all nodes

    nx.draw_networkx_nodes(G, pos, node_size=700, node_color=colors, cmap=plt.cm.summer)
    nx.draw_networkx_edges(G, pos, width=3)
    nx.draw_networkx_labels(G, pos, font_size=20, labels=labels, font_family='sans-serif')
    plt.show()
Пример #19
0
def run(figures):
    network = dict()
    with open(figures+"TFs.txt") as F:
        for line in F:
            line = line.strip().split()
            TF = line[0]
            weights = line[1].split(',')
            network[TF] = weights[:-1]
    
    cut = 0.00000000000001
    G = nx.Graph()
    for TF in network:
        for i in range(0, (int(len(network[TF])-5)), 6):
            if float(network[TF][i+1]) < cut and float(network[TF][i+2]) < cut and float(network[TF][i+3]) < cut and float(network[TF][i+4]) < cut:
                G.add_edge(TF,network[TF][i],weight=0.1)
        
    
    
    
    edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)] 
    #elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.6]       
    
    pos=nx.spring_layout(G)
    plt.figure()
    plt.subplot(111)
    plt.axis('off')
    nx.draw_networkx_nodes(G, pos)
    nx.draw_networkx_edges(G, pos, edge_color=edgewidth)
    nx.draw_networkx_labels(G,pos,font_size=8,font_family='sans-serif')
    plt.savefig(figures+'network.png')
Пример #20
0
def quickVisual(G, showLabel = False):
    """Just makes a simple _matplotlib_ figure and displays it, with each node coloured by its type. You can add labels with _showLabel_. This looks a bit nicer than the one provided my _networkx_'s defaults.

    # Parameters

    _showLabel_ : `optional [bool]`

    > Default `False`, if `True` labels will be added to the nodes giving their IDs.
    """
    colours = "brcmykwg"
    f = plt.figure(1)
    ax = f.add_subplot(1,1,1)
    ndTypes = []
    ndColours = []
    layout = nx.spring_layout(G, k = 4 / math.sqrt(len(G.nodes())))
    for nd in G.nodes(data = True):
        if 'type' in nd[1]:
            if nd[1]['type'] not in ndTypes:
                ndTypes.append(nd[1]['type'])
            ndColours.append(colours[ndTypes.index(nd[1]['type']) % len(colours)])
        elif len(ndColours) > 1:
            raise RuntimeError("Some nodes do not have a type")
    if len(ndColours) < 1:
        nx.draw_networkx_nodes(G, pos = layout, node_color = colours[0], node_shape = '8', node_size = 100, ax = ax)
    else:
        nx.draw_networkx_nodes(G, pos = layout, node_color = ndColours, node_shape = '8', node_size = 100, ax = ax)
    nx.draw_networkx_edges(G, pos = layout, width = .7, ax = ax)
    if showLabel:
        nx.draw_networkx_labels(G, pos = layout, font_size = 8, ax = ax)
    plt.axis('off')
    f.set_facecolor('w')
Пример #21
0
    def draw_graph(self):
        import matplotlib.pyplot as plt

        elarge = [(u, v) for (u, v, d) in self._graph.edges(data=True)
                  if d['type'] == 'audio_source']
        esmall = [(u, v) for (u, v, d) in self._graph.edges(data=True)
                  if d['type'] == 'data_source']

        pos = nx.shell_layout(self._graph)  # positions for all nodes

        # nodes
        nx.draw_networkx_nodes(self._graph, pos, node_size=700)

        # edges
        nx.draw_networkx_edges(self._graph, pos, edgelist=elarge,
                               arrows=True)
        nx.draw_networkx_edges(self._graph, pos, edgelist=esmall,
                               alpha=0.5, edge_color='b',
                               style='dashed', arrows=True)

        # labels
        labels = {node: repr(self._graph.node[node]['processor']) for node in self._graph.nodes()}
        nx.draw_networkx_labels(self._graph, pos, labels, font_size=20,
                                font_family='sans-serif')

        plt.axis('off')
        plt.show()  # display
def draw_graph(graph2):
    plt.clf()
    nodes = set([n1 for n1, n2 in graph2] + [n2 for n1, n2 in graph2])  # Extract nodes from graph

    G = nx.Graph()   # Graph - No Edges

    for node in nodes:    #Nodes
        G.add_node(node)

    for edge in graph2:    #Edges
        G.add_edge(edge[0], edge[1])

    pos = nx.spring_layout(G)    # Layout settings
    nx.draw_networkx_nodes(G,pos,node_size=1500, node_color='w', font_size=6)
    nx.draw_networkx_edges(G,pos,alpha=0.75,width=3)
    nx.draw_networkx_labels(G,pos, font_color='b')

    plt.title('Twitter Hashtag Graph')
    plt.axis('off')     # Show graph
    plt.savefig(".\\images\\graph.png")
    
    # Calculate average degree
    average_degree = np.mean(nx.degree(G).values())
    ft2 = open(sys.argv[2], 'a')    # Write to ft2.txt
    
    if np.isnan(average_degree): # NaN for no hashtags
        ft2.write('0.00'+'\n')
    else:
        aver_deg = format(average_degree, '.2f')
        ft2.write(str(aver_deg)+'\n')
    ft2.close()
    
    return
Пример #23
0
 def plot_path(self, path):
     if path == None:
         edgelist = []
     else:
         edgelist = zip(path[:-1], path[1:])
     if edgelist == []:
         return
     nodes = nx.draw_networkx_nodes(self,
                                    self.pos,
                                    nodelist=path,
                                    node_size=NODE_SIZE_PATH,
                                    node_color=NODE_COLOR_PATH)
     if nodes != None:
         nodes.set_edgecolor(NODE_BORDER_COLOR_PATH)
     ws = nx.get_node_attributes(self, 'w')
     photo_path_nodes = self.photo_nodes(path)
     if photo_path_nodes != []:
         sizes = [NODE_SIZE_PHOTO_MIN + ws[v]*NODE_SIZE_PHOTO_SCALE
                  for v in photo_path_nodes]
         nodes = nx.draw_networkx_nodes(self,
                                        self.pos,
                                        nodelist=photo_path_nodes,
                                        node_shape=NODE_SHAPE_PHOTO,
                                        node_size=sizes,
                                        node_color=NODE_COLOR_PHOTO_PATH)
     if nodes != None:
         nodes.set_edgecolor(NODE_BORDER_COLOR_PATH)
     nx.draw_networkx_edges(self,
                            self.pos,
                            edgelist=edgelist,
                            width=EDGE_WIDTH_PATH,
                            edge_color=EDGE_COLOR_PATH)
def report_ctg(ctg, filename):
    """
    Reports Clustered Task Graph in the Console and draws CTG in file
    :param ctg: clustered task graph
    :param filename: drawing file name
    :return: None
    """
    print "==========================================="
    print "      REPORTING CLUSTERED TASK GRAPH"
    print "==========================================="
    cluster_task_list_dict = {}
    cluster_weight_dict = {}
    for node in ctg.nodes():
        print ("\tCLUSTER #: "+str(node)+"\tTASKS:"+str(ctg.node[node]['TaskList'])+"\tUTILIZATION: " +
               str(ctg.node[node]['Utilization']))
        cluster_task_list_dict[node] = ctg.node[node]['TaskList']
    for edge in ctg.edges():
        print ("\tEDGE #: "+str(edge)+"\tWEIGHT: "+str(ctg.edge[edge[0]][edge[1]]['Weight']))
        cluster_weight_dict[edge] = ctg.edge[edge[0]][edge[1]]['Weight']
    print ("PREPARING GRAPH DRAWINGS...")
    pos = networkx.shell_layout(ctg)
    networkx.draw_networkx_nodes(ctg, pos, node_size=2200, node_color='#FAA5A5')
    networkx.draw_networkx_edges(ctg, pos)
    networkx.draw_networkx_edge_labels(ctg, pos, edge_labels=cluster_weight_dict)
    networkx.draw_networkx_labels(ctg, pos, labels=cluster_task_list_dict)
    plt.savefig("GraphDrawings/"+filename)
    plt.clf()
    print ("\033[35m* VIZ::\033[0mGRAPH DRAWINGS DONE, CHECK \"GraphDrawings/"+filename+"\"")
    return None
Пример #25
0
def draw_graph(edges, up_words, down_words, node_size, node_color='blue', node_alpha=0.3,
               node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_tickness=2,
               text_font='sans-serif', file_name="graph"):
    plt.clf()
    g = nx.Graph()

    for edge in edges:
        g.add_edge(edge[0], edge[1])

    graph_pos = nx.shell_layout(g)  # layout for the network

    # up_words = map(lambda x: translate_node(x), up_words)
    # down_words = map(lambda x: x + "(" + translate_node(x) + ")", down_words)  # add translated nodes to graph

    try:
        nx.draw_networkx_nodes(g, graph_pos, nodelist=up_words, node_size=node_size,
                               alpha=node_alpha, node_color='red')
        nx.draw_networkx_nodes(g, graph_pos, nodelist=down_words, node_size=node_size,
                               alpha=node_alpha, node_color=node_color)
        nx.draw_networkx_edges(g, graph_pos, width=edge_tickness,
                               alpha=edge_alpha, edge_color=edge_color)
        nx.draw_networkx_labels(g, graph_pos, font_size=node_text_size,
                                font_family=text_font)
    except:
        print 'draw error'

    plt.savefig(result_path + file_name, format="PNG")
Пример #26
0
def draw_graph(G):
	# an example using Graph as a weighted network.
	# __author__ = """Aric Hagberg ([email protected])"""
	try:
	    import matplotlib.pyplot as plt
	except:
	    raise

	elarge = [(u,v) for (u,v,d) in G.edges(data = True) if d['weight'] > 0.5]
	esmall = [(u,v) for (u,v,d) in G.edges(data = True) if d['weight'] <= 0.5]

	pos = nx.spring_layout(G) # positions for all nodes

	# nodes
	nx.draw_networkx_nodes(G, pos, node_size = 200)

	# edges
	nx.draw_networkx_edges(G, pos, edgelist = elarge, width = 0.4)
	nx.draw_networkx_edges(G, pos, edgelist = esmall, width = 0.4, alpha = 0.6, style = 'dashed')

	# labels
	nx.draw_networkx_labels(G, pos, font_size = 6, font_family = 'sans-serif')

	print 'number of cliques/clusters:', nx.graph_number_of_cliques(G)
	print 'time:', time.time() - start
	plt.show()
Пример #27
0
def visualize_rbn(rbn):
    internal_edges = []
    for i, neighbors in enumerate(rbn.connections):
        internal_edges += zip(repeat(i), neighbors)

    input_edges = zip(repeat('input_node'), rbn.input_connections)

    print input_edges
    print internal_edges

    G = nx.MultiGraph()
    pos = nx.spring_layout(G)

    #G.add_edges_from(internal_edges, node_color='r', node_size=10)
    #G.add_edges_from(input_edges, node_color='b', node_size=3)

    nx.draw_networkx_nodes(G, pos,
                           nodelist=range(rbn.n_nodes),
                           node_color='b',
                           node_size=500,
                           alpha=0.8)

    nx.draw_networkx_edges(G, pos,
                           edgelist=internal_edges)
                           #width=3,
                           #edge_color='r')

#nx.draw_networkx_edges(G,pos,
            #edgelist=[(0,1),(1,2),(2,3),(3,0)],
            #width=8,alpha=0.5,edge_color='r')
    #nx.draw(G, pos)

    plt.show()
Пример #28
0
def drawgraph(graph,fixed):
	pos=nx.spring_layout(graph)
	nx.draw_networkx_nodes(graph,pos,with_labels=True,node_size=100)
	nx.draw_networkx_nodes(graph,pos,with_labels=True,nodelist=fixed,node_size=100,node_color="yellow")
	nx.draw_networkx_edges(graph,pos,with_labels=True,width=0.3)
	nx.draw_networkx_labels(graph,pos,fontsize=10)
	plt.show()
Пример #29
0
def draw_graph(username, password, filename='graph.txt', label_flag=True, remove_isolated=True, different_size=True, iso_level=10, node_size=40):
    """Reading data from file and draw the graph.If not exists, create the file and re-scratch data from net"""
    print "Generating graph..."
    try:
        with open(filename, 'r') as f:
            G = p.load(f)
    except:
        G = getgraph(username, password)
        with open(filename, 'w') as f:
            p.dump(G, f)
    #nx.draw(G)
    # Judge whether remove the isolated point from graph
    if remove_isolated is True:
        H = nx.empty_graph()
        for SG in nx.connected_component_subgraphs(G):
            if SG.number_of_nodes() > iso_level:
                H = nx.union(SG, H)
        G = H
    # Ajust graph for better presentation
    if different_size is True:
        L = nx.degree(G)
        G.dot_size = {}
        for k, v in L.items():
            G.dot_size[k] = v
        node_size = [G.dot_size[v] * 10 for v in G]
    pos = nx.spring_layout(G, iterations=50)
    nx.draw_networkx_edges(G, pos, alpha=0.2)
    nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color='r', alpha=0.3)
    # Judge whether shows label
    if label_flag is True:
        nx.draw_networkx_labels(G, pos, alpha=0.5)
    #nx.draw_graphviz(G)
    plt.show()

    return G
Пример #30
0
    def plot(self, show_labels=False):
        nodes = nx.draw_networkx_nodes(self,
                                       self.pos,
                                       node_size=NODE_SIZE_NORMAL,
                                       node_color=NODE_COLOR_NORMAL,
                                       linewidths=NODE_LINEWIDTH_NORMAL,
                                       alpha=NODE_ALPHA_NORMAL)
        if nodes != None:
            nodes.set_edgecolor(NODE_BORDER_COLOR_NORMAL)
        ws = nx.get_node_attributes(self, 'w')
        sizes = [NODE_SIZE_PHOTO_MIN + ws[v]*NODE_SIZE_PHOTO_SCALE
                 for v in self.photo_nodes()]
        nodes = nx.draw_networkx_nodes(self,
                                       self.pos,
                                       nodelist=self.photo_nodes(),
                                       node_shape=NODE_SHAPE_PHOTO,
                                       node_size=sizes,
                                       node_color=NODE_COLOR_PHOTO)

        if nodes != None:
            nodes.set_edgecolor(NODE_BORDER_COLOR_PHOTO)
        if show_labels:
            nx.draw_networkx_labels(self,
                                    self.pos,
                                    font_color=LABEL_COLOR_NORMAL,
                                    font_size=LABEL_FONT_SIZE_NORMAL)
        nx.draw_networkx_edges(self,
                               self.pos,
                               width=EDGE_WIDTH_NORMAL,
                               edge_color=EDGE_COLOR_NORMAL,
                               alpha=EDGE_ALPHA_NORMAL)
Пример #31
0
def Terminal(sponsors):
    bash = ""
    print("Plesae type  \"help\" to see how can you use the system ")
    G = nx.Graph()
    while True:
        try:

            bash = input("command $ ")
            if bash == "":
                continue
# TOPO
            elif bash == "topo":
                if len(sponsors) == 0:
                    print("Nothing to show ! ")
                    continue
                for cur11 in sorted(sponsors):
                    print("||||||||||||||||||| Sponsor \"" + str(cur11.type) +
                          "\" has following things |||||||||||||||||||")
                    apps = sorted(cur11.application_thread_pool)
                    if len(cur11.application_thread_pool) == 0:
                        continue
                    for cur in apps:
                        print("---------------Application \"" + str(cur.ID) +
                              "\" has following things -------------------")
                        for cur2 in sorted(cur.things_thread_pool):
                            print("Thing \"" + str(cur2.ID) + "\"")

                    print(
                        "---------------------------------------------------------------------------"
                    )
                print(
                    "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
                )

# CREATE
            elif bash == "create":
                bash = input(
                    "Which one do you wanna create ? \n1 ) Sponsors \n2 ) Application \n3 ) Things \n? "
                )

                #CREATE THINGS
                if bash == "3":
                    if len(sponsors) < 1:
                        print(
                            "Sorry its supposed to have at least one sponsor")
                        continue

                    print(
                        "------------------- You have following Sponsor(s) ----------------------"
                    )
                    counter = 0
                    for cur in sorted(sponsors):
                        print(str(counter) + " ) " + str(cur.type))
                        counter = counter + 1

                    print(
                        "--------------------------------------------------------------------------"
                    )
                    bash = input("Which sponsor you want to add thing on ? ")

                    try:
                        if bash == "back":
                            continue
                        else:
                            number_tmp4 = int(bash)
                            if not (number_tmp4 < len(sponsors) and
                                    (number_tmp4 > 0 or number_tmp4 == 0)):
                                print(
                                    "The one that you chose is not in the list !"
                                )
                                continue
                            if len(
                                    sorted(sponsors)
                                [number_tmp4].application_thread_pool) < 1:
                                print(
                                    "Sorry its supposed to have at least one application in this sponsor"
                                )
                                continue

                            counter2 = 0
                            print(
                                "------------------- You have following Application(s) ----------------------"
                            )
                            for cur12 in sorted(
                                    sorted(sponsors)
                                [number_tmp4].application_thread_pool):
                                print(str(counter2) + " ) " + str(cur12.ID))
                                counter2 = counter2 + 1

                            print(
                                "--------------------------------------------------------------------------"
                            )

                            bash = input(
                                "Which application you want to add thing on ? "
                            )

                            try:
                                number_tmp2 = int(bash)
                                if not (number_tmp2 < len(
                                        sorted(sponsors)
                                    [number_tmp4].application_thread_pool) and
                                        (number_tmp2 > 0 or number_tmp2 == 0)):
                                    print(
                                        "The one that you chose is not in the list !"
                                    )
                                    continue
                                bash = input(
                                    "How many things do you want to append ? ")
                                number_tmp3 = int(bash)
                                bash = input(
                                    "Percentage of Plugged Devices ? ")
                                plugged_num = int(bash)
                                if (plugged_num > 100 or plugged_num < 0):
                                    print(
                                        "you have to choose between 0 and 100")
                                    continue
                                else:
                                    plugged_num = int(
                                        (plugged_num * number_tmp3) / 100)
                                    counter1 = 0

                                x2 = randrange(0, 500)
                                y2 = randrange(0, 500)

                                for cur4 in range(0, number_tmp3):
                                    x1 = sorted(sponsors)[number_tmp4].center_x
                                    y1 = sorted(sponsors)[number_tmp4].center_y
                                    r1 = sorted(sponsors)[number_tmp4].s_range

                                    x3 = sorted(
                                        sorted(sponsors)[number_tmp4].
                                        application_thread_pool)[number_tmp2].x
                                    y3 = sorted(
                                        sorted(sponsors)[number_tmp4].
                                        application_thread_pool)[number_tmp2].y
                                    r3 = sorted(
                                        sorted(sponsors)
                                        [number_tmp4].application_thread_pool
                                    )[number_tmp2].a_range
                                    while True:
                                        d1 = check_distance(x2, y2, x1, y1)
                                        if (d1 < r1):
                                            d = check_distance(x2, y2, x3, y3)
                                            if (d < r3):
                                                break

                                        x2 = randrange(0, 500)
                                        y2 = randrange(0, 500)
                                    t = Thing(x2, y2)
                                    sorted(
                                        sponsors
                                    )[number_tmp4].things_thread_pool.append(t)
                                    sorted(
                                        sorted(sponsors)
                                        [number_tmp4].application_thread_pool
                                    )[number_tmp2].things_thread_pool.append(t)
                                    things.append(t)
                                    t.distance_from_app = check_distance(
                                        x2, y2, x1, y1)

                                    x2 = randrange(0, 500)
                                    y2 = randrange(0, 500)

                                for cur20 in range(0, plugged_num):
                                    sorted(
                                        sorted(sponsors)
                                        [number_tmp4].application_thread_pool
                                    )[number_tmp2].things_thread_pool[
                                        cur20].EnType = 'plugged'

                            except:
                                #print("Error (5)")
                                #print(sys.exc_info())
                                continue

                    except:
                        print("Error (10)")
                        print(sys.exc_info())
                        continue

        #CREATE APPLICATION
                elif bash == "2":
                    if len(sponsors) < 1:
                        print(
                            "Sorry its supposed to have at least one sponsor")
                        continue

                    print(
                        "------------------- You have following Sponsor(s) ----------------------"
                    )
                    counter = 0
                    for cur in sorted(sponsors):
                        print(str(counter) + " ) " + str(cur.type))
                        counter = counter + 1

                    print(
                        "--------------------------------------------------------------------------"
                    )
                    bash = input(
                        "Which sponsor you want to add application on ? ")

                    try:
                        if bash == "back":
                            continue
                        else:
                            number_tmp2 = int(bash)
                            if not (number_tmp2 < len(sponsors) and
                                    (number_tmp2 > 0 or number_tmp2 == 0)):
                                print(
                                    "The one that you chose is not in the list !"
                                )
                                continue
                            bash = input(
                                "How many application(s) do you want to append ? "
                            )
                            number_tmp3 = int(bash)
                            x2 = randrange(0, 500)
                            y2 = randrange(0, 500)
                            r2 = randrange(150, 200)

                            for cur4 in range(0, number_tmp3):
                                x1 = sorted(sponsors)[number_tmp2].center_x
                                y1 = sorted(sponsors)[number_tmp2].center_y
                                r1 = sorted(sponsors)[number_tmp2].s_range
                                while True:
                                    d2 = check_distance(x2, y2, x1, y1)
                                    if (d2 < r1):
                                        break
                                    else:
                                        x2 = randrange(0, 500)
                                        y2 = randrange(0, 500)

                                t = Application(x2, y2, r2)
                                sorted(
                                    sponsors
                                )[number_tmp2].application_thread_pool.append(
                                    t)

                                x2 = randrange(0, 500)
                                y2 = randrange(0, 500)
                                r2 = randrange(150, 200)

                            print("Done!")
                    except:
                        #print("Error (8)")
                        #print(sys.exc_info())
                        continue

            #CREATE SPONSOR
                elif bash == "1":
                    try:
                        bash = input(
                            "How many sponsor(s) do you want to append ? ")
                        if bash == "back":
                            continue
                        else:
                            number_tmp3 = int(bash)

                    except:
                        print("Wrong command")

                    for cur4 in range(0, number_tmp3):
                        t = Sponsor(randrange(30, 470), randrange(30, 470),
                                    randrange(150, 200))
                        sponsors.append(t)
                    n = 1
                    for cur7 in sorted(sponsors):
                        if n == 1:
                            cur7.type = 'A'
                        if n == 2:
                            cur7.type = 'B'
                        if n == 3:
                            cur7.type = 'C'
                        if n == 4:
                            cur7.type = 'D'
                        if n == 5:
                            cur7.type = 'E'
                        if n == 6:
                            cur7.type = 'F'
                        if n == 7:
                            cur7.type = 'G'
                        n += 1

                    print("Done!")

                elif bash == "back":
                    continue

                else:
                    print("Choose from the list please")
                    continue
                # elif bash.lower() == "load file" :
                # 	bash = input("Enter file path : ")
                # 	file  = open(bash)

# EVALUATE
            elif bash == "evaluate":
                evaluation()
#SHOW DETAILS
            elif bash == "show details":
                for cur11 in sorted(sponsors):
                    apps = sorted(cur11.application_thread_pool)
                    if len(cur11.application_thread_pool) == 0:
                        continue
                    for cur in apps:
                        print("---------------Application \"" + str(cur.ID) +
                              "\" has following things -------------------")
                        for cur2 in sorted(cur.things_thread_pool):
                            print("list of values : " + str(cur2.value))
                            print("distance from app : " +
                                  str(cur2.distance_from_app))
                            print("avg of values : " + str(cur2.avg_of_values))
                        print("for apps :")
                        print("avg of values of apps :" +
                              str(cur.avg_of_values_of_things))
                        print("avg of distances of things :" +
                              str(cur.avg_of_distances_of_things))

# PREF
            elif bash == "pref":
                print(
                    "Do you want to add new attribute for preference function? (y/n)"
                )
                bash = input("$:")

                for cur11 in sorted(sponsors):
                    apps = sorted(cur11.application_thread_pool)
                    if len(cur11.application_thread_pool) == 0:
                        continue
                    for cur in apps:

                        if bash == 'y':
                            alpha = randrange(0, 10) / 10
                            beta = randrange(0, 10) / 10
                            landa = randrange(0, 10) / 10
                            teta = randrange(1, 5) / 10

                            cur.alpha = alpha
                            cur.beta = beta
                            cur.landa = landa
                            cur.teta = teta
                        if bash != 'y' and bash != 'n':
                            print("Wrong command !")
                            continue
                        print("---------------Application \"" + str(cur.ID) +
                              "\" has following things -------------------")

                        print("Alpha = " + str(cur.alpha))
                        print("Beta = " + str(cur.beta))
                        print("Landa = " + str(cur.landa))
                        print("teta = " + str(cur.teta))

                        p = (cur.alpha * int(cur.avg_of_values_of_things * 100)
                             + cur.beta * len(cur.things_thread_pool) * 2 +
                             cur.landa *
                             (int(cur.avg_of_distances_of_things) / 2) +
                             cur.teta * cur.pnum * 2) / 4
                        cur.pref = p

                        print("Preference of this app is :" + str(p))

# SUB
            elif bash == "sub":
                for cur11 in sorted(sponsors):
                    apps = sorted(cur11.application_thread_pool)
                    if len(cur11.application_thread_pool) == 0:
                        continue
                    n = 0
                    for cur in apps:
                        print(
                            "---------------Application \"" + str(cur.ID) +
                            "\" has following available things -------------------"
                        )

                        for cur16 in things:
                            is_in_range = check_distance(
                                cur16.x, cur16.y, cur.x, cur.y)
                            if (is_in_range < cur.a_range):
                                if cur16 not in cur.things_thread_pool:
                                    for cur8 in sorted(sponsors):
                                        if cur16 in cur8.things_thread_pool:
                                            print("thing " + str(cur16.ID) +
                                                  "  from sponsor " +
                                                  str(cur8.type))
                                            n += 1
                        print("number of available things :" + str(n))
                        n = 0

# SUBSETS
            elif bash == "subsets":
                for cur11 in sorted(sponsors):
                    apps = sorted(cur11.application_thread_pool)
                    if len(cur11.application_thread_pool) == 0:
                        continue
                    n = 0
                    for cur in apps:
                        print(
                            "---------------Optimum subsets of application \""
                            + str(cur.ID) + "\"  -------------------")
                        v1 = cur.avg_of_values_of_things
                        v2 = cur.avg_of_distances_of_things
                        for cur16 in things:
                            is_in_range = check_distance(
                                cur16.x, cur16.y, cur.x, cur.y)
                            if (is_in_range < cur.a_range):
                                if cur16 not in cur.things_thread_pool:
                                    #sub_list.append(cur16)
                                    cur.avg_of_values_of_things *= len(
                                        cur.things_thread_pool)
                                    cur.avg_of_values_of_things += sum(
                                        cur16.value)
                                    cur.avg_of_values_of_things /= (
                                        len(cur.things_thread_pool) + 1)

                                    cur.avg_of_distances_of_things *= len(
                                        cur.things_thread_pool)
                                    cur.avg_of_distances_of_things += is_in_range
                                    cur.avg_of_distances_of_things /= (
                                        len(cur.things_thread_pool) + 1)

                                    p = (cur.alpha * int(
                                        cur.avg_of_values_of_things * 100) +
                                         cur.beta *
                                         (len(cur.things_thread_pool) + 1) * 2
                                         + cur.landa *
                                         (int(cur.avg_of_distances_of_things) /
                                          2) + cur.teta * cur.pnum * 2) / 4
                                    q = p - cur.pref
                                    cost = int(q * 20)
                                    print("Adding thing \"" + str(cur16.ID) +
                                          "\" to this application ")
                                    print(
                                        "The new preference of this app is :" +
                                        str(p))
                                    print(
                                        "Difference with previous preference is :"
                                        + str(q))
                                    print("Estimated cost is : " + str(cost) +
                                          "$")
                                    print('')
                                    print('')
                                    cur.avg_of_values_of_things = v1
                                    cur.avg_of_distances_of_things = v2
                                    n += 1
                        n = 0

                print("Do you want to add a thing in any application? (y/n)")
                bash3 = input("$:")
                if bash3 == "y":
                    print("Enter the ID of the thing :")
                    bash = input("$:")

                    for cur16 in things:
                        if cur16.ID == int(bash):
                            print("Enter the ID of the application :")
                            bash2 = input("$:")
                            for cur11 in sorted(sponsors):
                                apps = sorted(cur11.application_thread_pool)
                                if len(cur11.application_thread_pool) == 0:
                                    continue
                                #for cur in apps:
                                #if cur.ID == int(bash2):
                                #print("Done")

                    for cur11 in sorted(sponsors):
                        apps = sorted(cur11.application_thread_pool)
                        if len(cur11.application_thread_pool) == 0:
                            continue
                        n = 0
                        for cur in apps:
                            if cur.ID == int(bash2):
                                for cur16 in things:
                                    if cur16.ID == int(bash):
                                        is_in_range = check_distance(
                                            cur16.x, cur16.y, cur.x, cur.y)
                                        if (is_in_range < cur.a_range):
                                            if cur16 not in cur.things_thread_pool:
                                                cur.things_thread_pool.append(
                                                    cur16)
                                                cur11.things_thread_pool.append(
                                                    cur16)
                                                print("Done")
                    '''
                    for cur11 in sorted(sponsors):
                        apps = sorted(cur11.application_thread_pool)
                        if len(cur11.application_thread_pool) == 0:
                            continue
                        for cur in apps:
                            for cur16 in cur.things_thread_pool:
                                a=cur16.ID
                                if a == int(bash):
                                    #del cur.things_thread_pool[cur16]
                                    #del cur11.things_thread_pool[cur16]
                                    print("yeee")
                    '''

                if bash3 != 'y' and bash3 != 'n':
                    print("Wrong command !")
                    continue

                elif bash3 == "n":
                    continue

# POSITIONS
            elif bash == "positions":
                for cur11 in sorted(sponsors):
                    print("Sponsor  " + str(cur11.type) + ": ")
                    print('')
                    print("x: " + str(cur11.center_x))
                    print("y: " + str(cur11.center_y))
                    print("r: " + str(cur11.s_range))
                    print('')
                    print('')
                    apps = sorted(cur11.application_thread_pool)
                    if len(cur11.application_thread_pool) == 0:
                        continue
                    for cur in apps:
                        print("Application  " + str(cur.ID) + ": ")
                        print('')
                        print("x: " + str(cur.x))
                        print("y: " + str(cur.y))
                        print("r: " + str(cur.a_range))
                        print('')
                        print('')
                        tng = sorted(cur.things_thread_pool)
                        for cur2 in tng:
                            print("Thing  " + str(cur2.ID) + ": ")
                            print('')
                            print("x: " + str(cur2.x))
                            print("y: " + str(cur2.y))
                            print('')
                            print('')

# GRAPHICAL SHOW
            elif bash == "g":
                u = 0
                for cur50 in sorted(sponsors):
                    u += 1
                    G.add_node(cur50.ID)
                    pos = {cur50.ID: (cur50.center_x, cur50.center_y)}
                    if u == 1:
                        nx.draw_networkx_nodes(G,
                                               pos,
                                               node_size=cur50.s_range * 300,
                                               nodelist=[cur50.ID],
                                               node_color='black',
                                               alpha=0.2)
                    if u == 2:
                        nx.draw_networkx_nodes(G,
                                               pos,
                                               node_size=cur50.s_range * 300,
                                               nodelist=[cur50.ID],
                                               node_color='b',
                                               alpha=0.2)
                    if u == 3:
                        nx.draw_networkx_nodes(G,
                                               pos,
                                               node_size=cur50.s_range * 300,
                                               nodelist=[cur50.ID],
                                               node_color='r',
                                               alpha=0.2)
                    if u == 4:
                        nx.draw_networkx_nodes(G,
                                               pos,
                                               node_size=cur50.s_range * 300,
                                               nodelist=[cur50.ID],
                                               node_color='green',
                                               alpha=0.2)
                u = 0
                m = 0
                for cur11 in sorted(sponsors):
                    m += 1
                    apps = sorted(cur11.application_thread_pool)
                    if len(cur11.application_thread_pool) == 0:
                        continue
                    for cur in apps:
                        G.add_node(cur.ID)
                        pos = {cur.ID: (cur.x, cur.y)}
                        if m == 1:

                            nx.draw_networkx_nodes(G,
                                                   pos,
                                                   nodelist=[cur.ID],
                                                   node_color='black',
                                                   alpha=0.3)
                        if m == 2:

                            nx.draw_networkx_nodes(G,
                                                   pos,
                                                   nodelist=[cur.ID],
                                                   node_color='b',
                                                   alpha=0.3)
                        if m == 3:
                            #c = [random()] * 2
                            nx.draw_networkx_nodes(G,
                                                   pos,
                                                   nodelist=[cur.ID],
                                                   node_color='r',
                                                   alpha=0.3)
                        if m == 4:

                            nx.draw_networkx_nodes(G,
                                                   pos,
                                                   nodelist=[cur.ID],
                                                   node_color='green',
                                                   alpha=0.3)
                m = 0

                o = 0
                for cur11 in sorted(sponsors):
                    o += 1
                    apps = sorted(cur11.application_thread_pool)
                    if len(cur11.application_thread_pool) == 0:
                        continue
                    for cur in apps:
                        tng = sorted(cur.things_thread_pool)
                        for cur2 in tng:
                            G.add_node(cur2.ID)
                            pos = {cur2.ID: (cur2.x, cur2.y)}
                            if o == 1:
                                nx.draw_networkx_nodes(G,
                                                       pos,
                                                       nodelist=[cur2.ID],
                                                       node_size=50,
                                                       node_color='black',
                                                       alpha=0.8)
                            if o == 2:
                                nx.draw_networkx_nodes(G,
                                                       pos,
                                                       nodelist=[cur2.ID],
                                                       node_size=50,
                                                       node_color='b',
                                                       alpha=0.8)
                            if o == 3:
                                nx.draw_networkx_nodes(G,
                                                       pos,
                                                       nodelist=[cur2.ID],
                                                       node_size=50,
                                                       node_color='r',
                                                       alpha=0.8)
                            if o == 4:
                                nx.draw_networkx_nodes(G,
                                                       pos,
                                                       nodelist=[cur2.ID],
                                                       node_size=50,
                                                       node_color='green',
                                                       alpha=0.8)
                            #G.add_edge(sorted(sorted(sponsors)[number_tmp4].application_thread_pool)[number_tmp2].ID,t.ID)
                            #pos = {sorted(sorted(sponsors)[number_tmp4].application_thread_pool)[number_tmp2].ID: (sorted(sorted(sponsors)[number_tmp4].application_thread_pool)[number_tmp2].x,sorted(sorted(sponsors)[number_tmp4].application_thread_pool)[number_tmp2].y),t.ID: (t.x, t.y)}
                            #G.draw_networkx_edges(G, pos)
                o = 0

                G.add_node(1)
                G.add_node(2)
                G.add_node(3)
                G.add_node(4)
                pos1 = {1: (0, 0), 2: (0, 500), 3: (500, 500), 4: (500, 0)}
                nx.draw_networkx_nodes(G,
                                       pos=pos1,
                                       node_size=1,
                                       nodelist=[1, 2, 3, 4],
                                       node_color='b',
                                       alpha=0.1)
                plt.show()
# RANDOM
            elif bash == "random":
                rand1 = randrange(1, 4)
                rand2 = randrange(1, 5)
                rand3 = randrange(0, 15)

                number_tmp3 = rand1

                for cur4 in range(0, number_tmp3):
                    t = Sponsor(randrange(30, 470), randrange(30, 470),
                                randrange(150, 200))
                    sponsors.append(t)
                n = 1
                for cur7 in sorted(sponsors):
                    if n == 1:
                        cur7.type = 'A'
                    if n == 2:
                        cur7.type = 'B'
                    if n == 3:
                        cur7.type = 'C'
                    if n == 4:
                        cur7.type = 'D'
                    if n == 5:
                        cur7.type = 'E'
                    if n == 6:
                        cur7.type = 'F'
                    if n == 7:
                        cur7.type = 'G'
                    n += 1

                for cur13 in sorted(sponsors):
                    number_tmp4 = randrange(1, 5)
                    x2 = randrange(0, 500)
                    y2 = randrange(0, 500)
                    r2 = randrange(150, 200)

                    for cur4 in range(0, number_tmp4):
                        x1 = cur13.center_x
                        y1 = cur13.center_y
                        r1 = cur13.s_range
                        while True:
                            d2 = check_distance(x2, y2, x1, y1)
                            if (d2 < r1):
                                break
                            else:
                                x2 = randrange(0, 500)
                                y2 = randrange(0, 500)

                        t = Application(x2, y2, r2)
                        cur13.application_thread_pool.append(t)

                        x2 = randrange(0, 500)
                        y2 = randrange(0, 500)
                        r2 = randrange(150, 200)

                for cur11 in sorted(sponsors):
                    apps = sorted(cur11.application_thread_pool)
                    if len(cur11.application_thread_pool) == 0:
                        continue
                    for cur in apps:
                        number_tmp5 = randrange(0, 15)
                        plugged_num = randrange(0, 100)

                        plugged_num = int((plugged_num * number_tmp5) / 100)
                        counter1 = 0

                        x2 = randrange(0, 100)
                        y2 = randrange(0, 100)

                        for cur4 in range(0, number_tmp5):
                            x1 = cur11.center_x
                            y1 = cur11.center_y
                            r1 = cur11.s_range

                            x3 = cur.x
                            y3 = cur.y
                            r3 = cur.a_range
                            while True:
                                d1 = check_distance(x2, y2, x1, y1)
                                if (d1 < r1):
                                    d = check_distance(x2, y2, x3, y3)
                                    if (d < r3):
                                        break

                                x2 = randrange(0, 500)
                                y2 = randrange(0, 500)
                            t = Thing(x2, y2)
                            cur11.things_thread_pool.append(t)
                            cur.things_thread_pool.append(t)
                            things.append(t)
                            t.distance_from_app = check_distance(
                                x2, y2, x1, y1)

                            x2 = randrange(0, 500)
                            y2 = randrange(0, 500)

                        for cur20 in range(0, plugged_num):
                            cur.things_thread_pool[cur20].EnType = 'plugged'

                print("Done")
                print('')
                for cur11 in sorted(sponsors):
                    print("Sponsor  " + str(cur11.type) + ": ")
                    print("Number of apps :" +
                          str(len(cur11.application_thread_pool)))
                    print("Number of things :" +
                          str(len(cur11.things_thread_pool)))
                    print('')
                    print('')


#HELP
            elif bash == "help":
                print('')
                print(" \"create\" : to create Sponsor/Application/Thing ")
                print('')
                print(" \"topo\" : to view designed system")
                print('')
                print(" \"back\" : go back to the first step")
                print('')
                print(
                    " \"help\" : to show more information about using the system"
                )
                print('')
                print(" \"evaluate\" : to evaluate things in each sponsor")
                print('')
                print(" \"show details\" : to show details of evaluation")
                print('')
                print(" \"pref\" : preferece funtion of each thing")
                print('')
                print(
                    " \"sub\" : show available things in each application range briefly"
                )
                print('')
                print(
                    " \"subsets\" : add available things in choosen application and calculate cost"
                )
                print('')
                print(
                    " \"positions\" : show position of each created Sponsor , Application , Things"
                )
                print('')
                print(" \"g\" : graphical show of scenario")
                print('')
                print(" \"quit\" : to exit from the system")

                # try :
                # 	file = open(bash)
            elif bash.lower() == "quit":
                break
            else:
                print("Wrong command ! ")
                continue
        except KeyboardInterrupt:
            break
    def Crtaj(self, izvor, par=0):
        elarge = [(u, v) for (u, v, d) in self.G.edges(data=True)
                  if d['weight'] > 0 and (u, v) != par]
        esmall = [(u, v) for (u, v, d) in self.G.edges(data=True)
                  if d['weight'] <= 0 and (u, v) != par]

        print(par)
        if self.prviput == True:
            if self._V > 7:
                self.pos = nx.spring_layout(self.G)  # positions for all nodes
            else:
                self.pos = nx.circular_layout(
                    self.G)  # positions for all nodes

        # nodes
        nx.draw_networkx_nodes(self.G,
                               self.pos,
                               node_size=700,
                               node_color='#21BAC9')
        nx.draw_networkx_nodes(self.G,
                               self.pos,
                               nodelist=[izvor],
                               node_size=700,
                               node_color='#01B140')
        # labels
        nx.draw_networkx_labels(self.G,
                                self.pos,
                                font_size=20,
                                font_family='sans-serif')

        # edges
        nx.draw_networkx_edges(self.G,
                               self.pos,
                               edgelist=elarge,
                               width=4,
                               alpha=0.5)
        nx.draw_networkx_edges(self.G,
                               self.pos,
                               edgelist=esmall,
                               width=4,
                               alpha=0.5)
        if par != 0:
            nx.draw_networkx_edges(self.G,
                                   self.pos,
                                   edgelist=[par],
                                   width=4,
                                   alpha=1,
                                   edge_color='#BC1507')
        nx.draw_networkx_edge_labels(self.G,
                                     self.pos,
                                     edge_labels=self.valjda_valja)

        plt.axis('off')

        fig_manager = plt.get_current_fig_manager()
        if self.prviput == True:
            fig_manager.full_screen_toggle()
            self.prviput = False
        plt.show(block=False)
        plt.pause(0.25)  # show it for 0.25s
        plt.cla()

        return
Пример #33
0
def main(argv):

    if len(argv) < 2:
        sys.stderr.write("Usage: %s <input graph>\n" % (argv[0], ))
        return 1

    graph_fn = argv[1]
    G = nx.Graph()  #let's create the graph first
    buildG(G, graph_fn, ' ')

    Nodos = G.nodes()

    n = G.number_of_nodes()  #|V|
    print(n)

    inisi = 0
    while inisi == 0:
        inisi = random.randrange(n)
    print(inisi)
    diffusion = independent_cascade(G, [191], steps=1)
    print(diffusion)

    infectados = []  # cantidad de infectados
    rataRec = 0.2  # tasa de recuperacion

    # creamos un solo paso de infeccion, para empezar a iterar desde un comienzo con una casacada de infectados.
    for i in diffusion:
        for j in i:
            infectados.append(j)

    tasaRec = 1  # indica cuantos agentes se debe recuperar por iteraion.
    diffu = []
    RecSuc = []  #Guarda los recuperados y no deja que se vulevan a infectar
    while (infectados != [] and tasaRec != 0):
        diffu.append(infectados)
        #empezamos a recupear segun tasa
        tasaRec = int(len(infectados) * rataRec)
        suceptibles = [
        ]  # cantidad de recuperados que pueden volver a infectarse
        for i in range(tasaRec):
            suceptibles.append(
                infectados.pop(random.randrange(len(infectados))))
        #controlamos los recuperados
        for i in suceptibles:
            RecSuc.append(i)
        #se vuelve y se coloca los nuevos focos de infeccion a la funcion infeccion.
        diffusion = independent_cascade(G, infectados, steps=1)
        #diffu.append(suceptibles)
        infectados = []
        #algoritmo que exluye de los infectados los nodos recuperados.
        ControlRec = 0
        for i in diffusion:
            for j in i:
                for k in RecSuc:
                    if j == k: ControlRec = 1
                if ControlRec == 0: infectados.append(j)
        Recuperados = []
        for i in RecSuc:
            if i not in Recuperados:
                Recuperados.append(i)
        diffu.append(Recuperados)

    #pos = nx.spectral_layout(G)
    #pos = nx.circular_layout(G)
    #pos = nx.shell_layout(G)
    #pos = nx.random_layout(G,dim=2)
    pos = nx.fruchterman_reingold_layout(G, scale=1000)
    #pos = nx.spring_layout(G, scale=2000)

    cf = plt.figure(2, figsize=(10, 10))
    ax = cf.add_axes((0, 0, 1, 1))

    #fig = plt.gcf()

    labels = {}
    cont = 1
    for i in G.nodes():
        colr = float(cont) / n
        nx.draw_networkx_nodes(G,
                               pos, [i],
                               node_size=100,
                               node_color='w',
                               with_labels=True)
        labels[i] = i
        cont += 1
    nx.draw_networkx_labels(G, pos, labels, font_size=5)
    nx.draw_networkx_edges(G, pos, alpha=0.5)

    plt.ion()
    plt.draw()
    infectados = 0
    suceptil = 0
    recuperados = 0
    sanos = n
    conts = 0
    infect = []
    sucep = []
    Recup = [0]
    tics = []
    infect.append(infectados)
    sucep.append(sanos)
    #Recup.append(suceptil)
    tics.append(conts)
    cont = 2
    for i in diffu:
        if cont % 2 == 0:
            infectados = len(i)  #- suceptil
            #sanos = n - infectados
            #infect.append(infectados)
            #sucep.append(sanos)
            #Recup.append(suceptil)
            #Recup.append(suceptil)
            #conts = conts + 1
            #tics.append(conts)
            #plt.pause(0.001)
            nx.draw_networkx_nodes(G,
                                   pos,
                                   i,
                                   node_size=250,
                                   node_color='r',
                                   with_labels=True)
            plt.pause(0.001)
            plt.draw()
        if cont % 2 != 0:
            suceptil = len(i)
            #Recup.append(suceptil)
            #sucep.append(sanos)
            conts += 1
            tics.append(conts)
            #infectados = infectados - len(i)
            sanos = n - infectados - len(i)
            infect.append(infectados)
            sucep.append(sanos)
            Recup.append(suceptil)
            #plt.pause(0.001)
            nx.draw_networkx_nodes(G,
                                   pos,
                                   i,
                                   node_size=300,
                                   node_color='b',
                                   with_labels=True)
            plt.pause(0.001)
            plt.draw()
        cont += 1

    print 'infectados: ', infectados, ' sanos: ', sanos, " Suceptibles: ", suceptil, ' Etapas: '******'suceptibles')
    plt.xlabel('Tics')
    plt.ylabel('Nodos')
    plt.plot(tics, sucep, 'r')
    plt.subplot(2, 2, 2)
    plt.title('infectados')
    plt.xlabel('Tics')
    plt.ylabel('Nodos')
    plt.plot(tics, infect, 'g')
    plt.subplot(2, 2, 3)
    plt.title('infectados, sanos y Suceptibles')
    plt.xlabel('Tics')
    plt.ylabel('Nodos')
    plt.plot(tics, sucep)
    plt.plot(tics, Recup)
    plt.plot(tics, infect)
    plt.show()
    plt.subplot(2, 2, 4)
    plt.title('recuperados')
    plt.xlabel('Tics')
    plt.ylabel('Nodos')
    plt.plot(tics, Recup, 'b')

    plt.pause(20)
    # Animator call
    #anim = animation.FuncAnimation(fig, animate, frames=20, interval=20, blit=True)
    # Creamos una figura
    blt.plot(infect, tics)
    blt.show()
    print(time.strftime("%I:%M:%S"))
    total_subs = full_df['Total_Submissions'][idx]
    perc_cs_users = (full_df['CS_Users'][idx] /
                     full_df['Distinct_Users'][idx]) * 100
    G.add_node(n, perc_cs=float(perc_cs_users), totalsubs=total_subs)
    G.add_edge('Climate', n, weight=full_df['CO_Users'][idx])

# Create Network Plot
nodes = G.nodes()
colors = [G.node[n]['perc_cs'] for n in nodes]
sizes = [(G.node[n]['totalsubs'] / 50) for n in nodes]

fig = plt.figure()
pos = nx.spring_layout(G)
ec = nx.draw_networkx_edges(G, pos, alpha=0.2)
nc = nx.draw_networkx_nodes(G,
                            pos,
                            nodelist=nodes,
                            node_color=colors,
                            node_size=sizes,
                            with_labels=True,
                            cmap=plt.cm.RdYlGn_r,
                            alpha=0.95)
nx.draw_networkx_labels(G, pos=pos, font_size=10)
cbar = plt.colorbar(nc)
cbar.set_label("% Users from /r/climateskeptics", rotation=90, fontsize=16)
plt.axis('off')
fig.tight_layout()
plt.show()

# Export to GEPHI Format
#nx.write_gexf(G, "test.gexf")
G.add_edge('215', '208', weight=8.5)
G.add_edge('215', '401', weight=0)
G.add_edge('301', 'W-300', weight=11)
G.add_edge('302', 'W-300', weight=11)
G.add_edge('301', '219', weight=85)
G.add_edge('302', '219', weight=85)
G.add_edge('401', '402', weight=10)
G.add_edge('402', 'N-400', weight=17)
G.add_edge('402', 'N-408', weight=16)
G.add_edge('N-408', 'N-407', weight=7)

elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] == 0]

pos = nx.spring_layout(G)  # positions for all nodes

# nodes
nx.draw_networkx_nodes(G, pos, node_size=5)

# edges
nx.draw_networkx_edges(G, pos, edgelist=elarge,
                       width=0.2)
nx.draw_networkx_edges(G, pos, edgelist=esmall,
                       width=0.2, alpha=0.5, edge_color='b', style='dashed')

# labels
nx.draw_networkx_labels(G, pos, font_size=5, font_family='sans-serif')

plt.axis('off')
plt.show()
def net_plot(df = DataFrame([]), layout = 'Spring', label = 'none', column = 0, label_size = 5,diam_nodos = 10, espe_edges = 0.1,
             inter = 10, color_inter_min = 'k',color_inter_max = 'blue',
             edge_alpha_min = 0.3, edge_alpha_max = 0.3, k_num = 3, color_nodo = 'red', node_alpha = 0.7, backg = 'white',
             label_color = 'black'):
    #
    df1 = df[['GO', 'Entry', 'Term', 'Short_Term']].merge(df, on = 'Entry', how = 'left').drop_duplicates()
    df2 = DataFrame(df[['GO', 'Term', 'Short_Term', 'Entry']].drop_duplicates().groupby(['GO','Term', 'Short_Term']).Entry.count()).reset_index()
    #### >>>>>>>>>>>>>>>>
    #### A partir de una matriz de datos extrae valores no redundantes
    matrix = df1.pivot_table(values='Entry',index=['GO_x', 'Term_x', 'Short_Term_x'],aggfunc=len,columns=['GO_y', 'Term_y', 'Short_Term_y'])
    ###
    df_mat = []
    n = -1
    for i in list(matrix.columns.values):
        n += 1
        new = DataFrame(matrix.iloc[n:len(matrix)][i])
        nn = -1
        for index, row in new.iterrows():
            nn += 1
            df_mat.append([index, i, new.iloc[nn][i]])
        nn = 0
    ###
    df_mat = DataFrame(df_mat, columns = ['go0', 'go1', 'val']).dropna()
    ###
    nodos = []
    for index, row in df_mat.iterrows():
        if row.go0 == row.go1:
            #print(row.go0, row.go1)
            continue
        else:
            #print(row.go0, row.go1)
            nodos.append([row.go0, row.go1, row.val])
    nodos = DataFrame(nodos)
    columnas = {0:'GO', 1:'Term', 2:'Short_Term'}
    nodos = DataFrame([[i[column] for i in nodos[0]], [i[column] for i in nodos[1]], nodos[2]]).T
    #### >>>>>>>>>>>>>>>>
    # si interacciona con mas uno, eliminar la redundancia, y si no interacciona con ninguno, dejar el nodo
    # y su valor, este se verá en la red como un nodo aislado
    aislado = [i for i in matrix.columns if len(matrix[[i]].dropna()) == 1]
    aislado = [df_mat[df_mat.go0 == i] for i in aislado]
    if len(aislado) > 0:
        aislado = pd.concat(aislado)
        aislado.columns = [0, 1, 2]
        aislado = DataFrame([[i[column] for i in aislado[0]], [i[column] for i in aislado[1]], aislado[2]]).T
        nodos = pd.concat([nodos, aislado])
    else:
        pass
    ####################
    # https://networkx.github.io/documentation/networkx-2.3/auto_examples/drawing/plot_weighted_graph.html#sphx-glr-auto-examples-drawing-plot-weighted-graph-py
    G=nx.Graph()
    for index, row in nodos.iterrows():
        G.add_edge(row[0], row[1],weight = row[2])
    elarge=[(u,v,d['weight']) for (u,v,d) in G.edges(data=True) if d['weight'] >= inter]
    esmall=[(u,v,d['weight']) for (u,v,d) in G.edges(data=True) if d['weight'] < inter]
    ###
    layouts = {'Circular':nx.circular_layout,
          'Random':nx.random_layout,
          'Shell':nx.shell_layout,
          'Spectral':nx.spectral_layout,
          'Spring':nx.spring_layout,
          'KK':nx.kamada_kawai_layout}
    #circular_layout
    #random_layout
    #shell_layout
    #spring_layout
    #spectral_layout
    #pos=nx.spring_layout(G, k = k_num) # positions for all nodes
    if layouts[layout] == nx.spring_layout:
        pos=layouts[layout](G, k = k_num)
    else:
        pos=layouts[layout](G)
    #pos=layout(G)
    # nodes
    #------------------------------------------------------------------------------
    # ordenar los valores para representarlos en el tama;o del nodo
    order = []
    for index, row in nodos.iterrows():
        order.append(row[0])
        order.append(row[1])
    orden3 = DataFrame(order).drop_duplicates(keep = 'first').reset_index(drop = True)
    orden3.columns = [columnas[column]]
    orden4 = pd.merge(orden3, df2, on = [columnas[column]], how = 'left')
    #------------------------------------------------------------------------------
    # https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.drawing.nx_pylab.draw_networkx_edges.html
    nx.draw_networkx_nodes(G,pos,node_size= np.array(orden4.Entry) * diam_nodos,
                           node_color= color_nodo,alpha= node_alpha)
    # edges
    nx.draw_networkx_edges(G,pos,edgelist=esmall,
                           width = np.array([i[2] for i in esmall]) * espe_edges,
                           alpha= edge_alpha_min,edge_color= color_inter_min,style='-')
    nx.draw_networkx_edges(G,pos, edgelist=elarge,
                           width = np.array([i[2] for i in elarge]) * espe_edges,
                           alpha= edge_alpha_max,edge_color= color_inter_max,style= '-')

    # labels
    posicion = {} ## posicion de las etiquetas, ligeramente arriba
    for key, value in pos.items():
        posicion[key] = value + 0.05
    # arreglo de las posiciones de los nodos en el plano cartesiano
    arr = np.array([[i for i in value] for key, value in pos.items()])
    
    # labels
    if label == 'label':
        nx.draw_networkx_labels(G,posicion,font_size=label_size, font_color=label_color) # ,font_weight='bold'
        if label == 'label':
            plt.axis([arr[:,0].min() - 0.3, arr[:,0].max() + 0.3,
                      arr[:,1].min() - 0.3, arr[:,1].max() + 0.3])
        #plt.axis('off')
        #plt.show() # display
    if label == 'none':
        plt.axis([arr[:,0].min() - 0.2, arr[:,0].max() + 0.2,
                  arr[:,1].min() - 0.2, arr[:,1].max() + 0.2])
        #plt.axis('off')
        #plt.show() # display
    plt.gca().set_facecolor(backg)
    plt.gca().spines['top'].set_visible(False)
    plt.gca().spines['right'].set_visible(False)
    plt.gca().spines['left'].set_visible(False)
    plt.gca().spines['bottom'].set_visible(False)
    plt.gca().axes.get_xaxis().set_visible(False)
    plt.gca().axes.get_yaxis().set_visible(False)   
Пример #37
0
    def visualize_subgraph(self,
                           node_idx,
                           edge_index,
                           edge_mask,
                           y=None,
                           threshold=None,
                           edge_y=None,
                           node_alpha=None,
                           seed=10,
                           **kwargs):
        r"""Visualizes the subgraph given an edge mask
        :attr:`edge_mask`.

        Args:
            node_idx (int): The node id to explain.
                Set to :obj:`-1` to explain graph.
            edge_index (LongTensor): The edge indices.
            edge_mask (Tensor): The edge mask.
            y (Tensor, optional): The ground-truth node-prediction labels used
                as node colorings. All nodes will have the same color
                if :attr:`node_idx` is :obj:`-1`.(default: :obj:`None`).
            threshold (float, optional): Sets a threshold for visualizing
                important edges. If set to :obj:`None`, will visualize all
                edges with transparancy indicating the importance of edges.
                (default: :obj:`None`)
            edge_y (Tensor, optional): The edge labels used as edge colorings.
            node_alpha (Tensor, optional): Tensor of floats (0 - 1) indicating
                transparency of each node.
            seed (int, optional): Random seed of the :obj:`networkx` node
                placement algorithm. (default: :obj:`10`)
            **kwargs (optional): Additional arguments passed to
                :func:`nx.draw`.

        :rtype: :class:`matplotlib.axes.Axes`, :class:`networkx.DiGraph`
        """
        import networkx as nx
        import matplotlib.pyplot as plt

        assert edge_mask.size(0) == edge_index.size(1)

        if node_idx == -1:
            hard_edge_mask = torch.BoolTensor([True] * edge_index.size(1),
                                              device=edge_mask.device)
            subset = torch.arange(edge_index.max().item() + 1,
                                  device=edge_index.device)
            y = None

        else:
            # Only operate on a k-hop subgraph around `node_idx`.
            subset, edge_index, _, hard_edge_mask = k_hop_subgraph(
                node_idx,
                self.num_hops,
                edge_index,
                relabel_nodes=True,
                num_nodes=None,
                flow=self.__flow__())

        edge_mask = edge_mask[hard_edge_mask]

        if threshold is not None:
            edge_mask = (edge_mask >= threshold).to(torch.float)

        if y is None:
            y = torch.zeros(edge_index.max().item() + 1,
                            device=edge_index.device)
        else:
            y = y[subset].to(torch.float) / y.max().item()

        if edge_y is None:
            edge_color = ['black'] * edge_index.size(1)
        else:
            colors = list(plt.rcParams['axes.prop_cycle'])
            edge_color = [
                colors[i % len(colors)]['color']
                for i in edge_y[hard_edge_mask]
            ]

        data = Data(edge_index=edge_index,
                    att=edge_mask,
                    edge_color=edge_color,
                    y=y,
                    num_nodes=y.size(0)).to('cpu')
        G = to_networkx(data,
                        node_attrs=['y'],
                        edge_attrs=['att', 'edge_color'])
        mapping = {k: i for k, i in enumerate(subset.tolist())}
        G = nx.relabel_nodes(G, mapping)

        node_args = set(signature(nx.draw_networkx_nodes).parameters.keys())
        node_kwargs = {k: v for k, v in kwargs.items() if k in node_args}
        node_kwargs['node_size'] = kwargs.get('node_size') or 800
        node_kwargs['cmap'] = kwargs.get('cmap') or 'cool'

        label_args = set(signature(nx.draw_networkx_labels).parameters.keys())
        label_kwargs = {k: v for k, v in kwargs.items() if k in label_args}
        label_kwargs['font_size'] = kwargs.get('font_size') or 10

        pos = nx.spring_layout(G, seed=seed)
        ax = plt.gca()
        for source, target, data in G.edges(data=True):
            ax.annotate('',
                        xy=pos[target],
                        xycoords='data',
                        xytext=pos[source],
                        textcoords='data',
                        arrowprops=dict(
                            arrowstyle="->",
                            alpha=max(data['att'], 0.1),
                            color=data['edge_color'],
                            shrinkA=sqrt(node_kwargs['node_size']) / 2.0,
                            shrinkB=sqrt(node_kwargs['node_size']) / 2.0,
                            connectionstyle="arc3,rad=0.1",
                        ))

        if node_alpha is None:
            nx.draw_networkx_nodes(G,
                                   pos,
                                   node_color=y.tolist(),
                                   **node_kwargs)
        else:
            node_alpha_subset = node_alpha[subset]
            assert ((node_alpha_subset >= 0) & (node_alpha_subset <= 1)).all()
            nx.draw_networkx_nodes(G,
                                   pos,
                                   alpha=node_alpha_subset.tolist(),
                                   node_color=y.tolist(),
                                   **node_kwargs)

        nx.draw_networkx_labels(G, pos, **label_kwargs)

        return ax, G
Пример #38
0
def generateGraph(name, bot):
    edges, nodes = getEdges(name)
    if len(edges) == 0:
        return False

    relations = dict()
    labels = dict()

    G = nx.Graph()
    G.clear()
    for edge in edges:
        G.add_edge(edge.name1.lower(), edge.name2.lower())
        relations[(edge.name1.lower(), edge.name2.lower())] = edge.relationship

    for node in nodes:
        if node[0] == '@' and node[1:].lower() in users:
            userId = users[node[1:].lower()]
            photos = bot.getUserProfilePhotos(userId, limit=1)
            if len(photos.photos) > 0:
                photoId = photos.photos[0][0].file_id
                photoFile = bot.getFile(photoId)
                photoFile.download(node[1:])
                G.node[node.lower()]['image'] = mpimg.imread(node[1:])
                img = mpimg.imread(node[1:])
        else:
            labels[node.lower()] = node

    pos = nx.shell_layout(G)

    plt.cla()

    fig = plt.gcf()
    ax = plt.gca()
    ax.set_aspect('equal')
    plt.axis('off')

    nx.draw_networkx_nodes(G, pos, node_size=1400)
    nx.draw_networkx_edges(G, pos)
    nx.draw_networkx_edge_labels(G, pos, relations)
    nx.draw_networkx_labels(G, pos, labels)

    plt.xlim(-1.5, 1.5)
    plt.ylim(-1.5, 1.5)

    trans = ax.transData.transform
    trans2 = fig.transFigure.inverted().transform

    imgSize = config["imgSize"]
    i2 = imgSize / 2.0
    for n in G:
        if 'image' in G.node[n]:
            xx, yy = ax.transData.transform(pos[n])  # figure coordinates
            xa, ya = fig.transFigure.inverted().transform(
                (xx, yy))  # axes coordinates
            a = plt.axes([xa - i2 / 2.0, ya - i2, imgSize, imgSize])
            a.imshow(G.node[n]['image'])
            a.set_aspect('equal')
            plt.axis('off')
            plt.title(n, y=-0.45)

    plt.savefig(config["graph_file"])

    return True
 def graphCreator():
     A = np.matrix([
         # [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         # [1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         # [0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0],
         # [0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0],
         # [0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0],
         # [0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0],
         # [0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0],
         # [0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0],
         # [0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0],
         # [0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0],
         # [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1]
         [
             -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
             -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
             -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0,
             0, 0, 0
         ],
         [
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0,
             0, 0, 0
         ],
     ])
     G = nx.DiGraph()
     statesArray = []
     for key, val in self.states.items():
         statesArray.append(val)
     for i in range(len(signals)):
         self.table.setColumnWidth(i, 100)
     a = list(signals.keys())
     signalsArray = []
     for key in a:
         signalsArray.append(key)
     it = 0
     for i in range(len(A)):
         for j in range(len(A)):
             for k in range(len(A.transpose())):
                 if A[i, k] == -1 and A[j, k] == 1:
                     G.add_edge(statesArray[i],
                                statesArray[j],
                                weight=signalsArray[it])
                     if it < (len(signalsArray) - 1):
                         it = it + 1
     val_map = {'A': 1.0, 'L': 0.0}
     values = [val_map.get(node, 0.25) for node in G.nodes()]
     red_edges = []
     edge_colours = [
         'black' if not edge in red_edges else 'red'
         for edge in G.edges()
     ]
     black_edges = [edge for edge in G.edges() if edge not in red_edges]
     pos = nx.shell_layout(G)
     nx.draw_networkx_nodes(G,
                            pos,
                            cmap=plt.get_cmap('jet'),
                            node_color='skyblue',
                            node_size=300)
     nx.draw_networkx_labels(G, pos)
     edge_labels = dict([((
         u,
         v,
     ), d['weight']) for u, v, d in G.edges(data=True)])
     nx.draw_networkx_edge_labels(G,
                                  pos,
                                  edge_labels=edge_labels,
                                  color='red')
     nx.draw_networkx_edges(G,
                            pos,
                            edgelist=black_edges,
                            color='red',
                            arrows=True)
     plt.axis('off')
     plt.savefig("graph.png")
def WPGMA(filename):
    start = time.time()
    f = open(filename, "r")
    strmatrix = f.read()
    matrix = []
    matrix.append([])
    index = 0
    alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    edges = []
    for char in range(len(strmatrix)):  #Converts input string to list of lists
        if strmatrix[char] == "-":
            matrix[index].append(strmatrix[char])
        if strmatrix[char] == "\n":
            index = index + 1
            matrix.append([])
        if strmatrix[char] == " ":
            place = char + 1
            while True:
                if place == len(strmatrix) - 1:
                    place = place
                    break
                place = place + 1
                if strmatrix[place] == " ":
                    place = place - 1
                    break
                if strmatrix[place] == "\n":
                    place = place - 1
                    break
            nu = strmatrix[char:place + 1]
            num = nu.replace(" ", "")
            if num not in alph:
                matrix[index].append(int(num))
        if strmatrix[char] in alph:
            matrix[index].append(strmatrix[char])
    for i in range(1, len(matrix)):
        for j in range(1, len(matrix)):
            temp = int(matrix[i][j])
            matrix[i][j] = temp
    while len(
            matrix
    ) > 3:  #Calculates reduced distance matrices and phylogenetic tree structure
        print("Reduced distance matrix:")
        for i in range(len(matrix)):  #Prints reduced distance matrices
            stri = '	'.join(str(e) for e in matrix[i])
            print(stri)
        smallest = int(matrix[1][len(matrix) - 1])
        for i in range(1, len(matrix)):
            for j in range(1, len(matrix)):
                if matrix[i][j] < smallest:
                    if matrix[i][j] != 0:
                        smallest = matrix[i][j]
                        location = [j, i]
        NewName = matrix[0][location[1]] + matrix[location[0]][0]
        edges.append((NewName, matrix[0][location[1]]))
        edges.append((NewName, matrix[location[0]][0]))
        newMatrix = []
        for i in range(len(matrix) - 1):
            newMatrix.append([])
        newMatrix[0].append("-")
        newMatrix[0].append(NewName)
        for i in range(len(matrix)):
            if matrix[0][i] != matrix[0][location[1]]:
                if matrix[0][i] != matrix[0][location[0]]:
                    if i != 0:
                        newMatrix[0].append(matrix[0][i])
        for i in range(1, len(newMatrix)):
            newMatrix[i].append(newMatrix[0][i])
        newMatrix[1].append(0)
        for i in range(2, len(newMatrix)):
            letter = newMatrix[0][i]
            index = matrix[0].index(letter)
            value = (matrix[location[1]][index] +
                     matrix[location[0]][index]) / 2
            newMatrix[1].append(value)
        for i in range(2, len(newMatrix)):
            newMatrix[i].append(newMatrix[1][i])
        for col in range(2, len(newMatrix)):
            for row in range(2, len(newMatrix)):
                if newMatrix[col][0] != NewName:
                    if newMatrix[0][row] != NewName:
                        colletter = newMatrix[col][0]
                        rowletter = newMatrix[0][row]
                        colindex = matrix[0].index(colletter)
                        rowindex = matrix[0].index(rowletter)
                        newMatrix[row].append(matrix[colindex][rowindex])
        matrix = newMatrix
    print("Reduced distance matrix:")
    for i in range(len(matrix)):  #Prints final reduced distance matrix.
        stri = '	'.join(str(e) for e in matrix[i])
        print(stri)
    finalname = matrix[0][1] + matrix[0][2]
    edges.append((finalname, matrix[0][1]))
    edges.append((finalname, matrix[0][2]))
    G = nx.DiGraph()  #Creates graph for phylogenetic tree.
    G.add_edges_from(edges)
    black_edges = [edge for edge in G.edges()]
    pos = nx.circular_layout(G)
    nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), node_size=500)
    nx.draw_networkx_labels(G, pos)
    nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
    plt.savefig("Phylogenetic_Tree.png"
                )  #Saves phylogenetic tree graph to Phylogenetic_Tree.png
    end = time.time()
    print("The program took " + str(end - start) + " to execute.")
Пример #41
0
    G.add_edges_from(edge_)
#for node in G.nodes():
#print(node)
#size_n.append(5)
#n_color.append('blue')
for ind, node in enumerate(G):
    if node in adj:
        #if ind%2==0:
        n_color.append('blue')
    else:
        n_color.append('green')
pos = nx.spring_layout(G, k=2.5)
plt.figure(figsize=(15, 15))
_ = nx.draw_networkx_nodes(G,
                           pos,
                           scale=100,
                           node_size=n_size,
                           node_color=n_color,
                           alpha=0.9)
_ = nx.draw_networkx_edges(G, pos, alpha=0.9, width=weights)
#_=nx.draw_networkx_labels(G,pos,labels,font_size=12)
pos_attrs = {}
for node, coords in pos.items():
    if coords[0] < 0:
        coords[0] = coords[0] - 0.06
        if coords[1] < 0:
            coords[1] = coords[1] - 0.04
        else:
            coords[1] = coords[1] + 0.04
    else:
        coords[0] = coords[0] + 0.06
        if coords[1] < 0:
Пример #42
0
    def _draw_network(self):
        """Draws the NetworkX object representing the underlying graph."""
        plt.clf()

        if self.num_populations == 1:
            node_sizes = 5000
            node_border_width = 1.
        else:
            node_sizes = 15000
            node_border_width = 3.

        vmin, vmax = 0, np.max(self.pi) + 0.1

        nx.draw_networkx_nodes(self.g,
                               self.pos,
                               node_size=node_sizes,
                               node_color=self.node_colors,
                               edgecolors="k",
                               cmap=plt.cm.Blues,
                               vmin=vmin,
                               vmax=vmax,
                               linewidths=node_border_width)

        nx.draw_networkx_edges(self.g,
                               self.pos,
                               node_size=node_sizes,
                               arrowstyle="->",
                               arrowsize=10,
                               edge_color=self.edge_colors,
                               edge_cmap=plt.cm.Blues,
                               width=5)

        nx.draw_networkx_edge_labels(self.g,
                                     self.pos,
                                     edge_labels=self.edge_labels)

        if self.num_populations > 1:
            subnode_separation = 0.1
            subgraph = nx.Graph()
            for i_population in range(self.num_populations):
                subgraph.add_node(i_population)

        for i_strat_profile in self.g:
            x, y = self.pos[i_strat_profile]
            if self.num_populations == 1:
                node_text = "$\\pi_{" + self.state_labels[
                    i_strat_profile] + "}=$"
                node_text += str(np.round(self.pi[i_strat_profile],
                                          decimals=2))
            else:
                node_text = ""  # No text for multi-population case as plot gets messy
            txt = plt.text(x,
                           y,
                           node_text,
                           horizontalalignment="center",
                           verticalalignment="center",
                           fontsize=12)
            txt.set_path_effects(
                [PathEffects.withStroke(linewidth=3, foreground="w")])

            if self.num_populations > 1:
                sub_pos = nx.circular_layout(subgraph)
                subnode_labels = dict()
                strat_profile = utils.get_strat_profile_from_id(
                    self.num_strats_per_population, i_strat_profile)
                for i_population in subgraph.nodes():
                    i_strat = strat_profile[i_population]
                    subnode_labels[i_population] = "$s^{" + str(i_population +
                                                                1) + "}="
                    subnode_labels[i_population] += (
                        self.state_labels[i_population][i_strat] + "$")
                    # Adjust the node positions generated by NetworkX's circular_layout(),
                    # such that the node for the 1st strategy starts on the left.
                    sub_pos[i_population] = (
                        -sub_pos[i_population] * subnode_separation +
                        self.pos[i_strat_profile])
                nx.draw(subgraph,
                        pos=sub_pos,
                        with_labels=True,
                        width=0.,
                        node_color="w",
                        labels=subnode_labels,
                        node_size=2500)
def main():
    print(
        "\nStarting generate graph - {}\nStart step 1 (initialize the nodes)".
        format(out_filename[7:]))

    # initialize the nodes with state and maximum out degree
    random.seed(seed_num)
    print_count = int(num_of_vertices / 100)

    # the first vertex most be out
    v_state = Out
    for v_id in range(num_of_vertices):
        if num_of_vertices > 100:
            if v_id % print_count == 0:
                sys.stdout.write('{} ({}%) \r'.format(
                    v_id, int((v_id / num_of_vertices) * 100)))
                sys.stdout.flush()

        # the last vertex most be in
        if v_id == num_of_vertices - 1:
            v_state = In
        v_degree = random.randint(1, max_degree)
        if debug: print(v_degree)

        v = Vertex(v_id, v_state, v_degree)
        global_vertices.append(v)
        if v_state == In:
            global_in_vertices.append(v_id)
            global_ins_only.append(v_id)
        elif v_state == Both:
            global_in_vertices.append(v_id)
        v_state = random.choices(['In', 'Out', 'Both'], [0.1, 0.1, 0.8])
        if debug: print(v_state)

    print(
        'Finish of step 1...\n\nStart step 2 (make sure graph is connected, associating a father for every in vertex)'
    )
    # visit all the vertices that can get In edge, and associating a father....
    while len(global_ins_only) > 0:
        sys.stdout.write(
            '{} in vertices steel not verified as connected.. \r'.format(
                len(global_ins_only)))
        sys.stdout.flush()
        vertex = random.choice(global_vertices)
        chooseSonFromIns(vertex)

    ins_without_father = 0
    for v_id in global_ins_only:
        if not global_vertices[v_id].has_father:
            ins_without_father += 1
    print('num of in vertices that not has father: {} ({} %)'.format(
        ins_without_father,
        ((ins_without_father / len(global_vertices)) * 100)))

    print(
        "Finish of step 2...\n\nStart step 3 (find a sons for every out node till max degree)"
    )
    for i, vertex in enumerate(global_vertices):
        if num_of_vertices > 100:
            if i % print_count == 0:
                sys.stdout.write('{} ({}%) \r'.format(
                    i, int((i / num_of_vertices) * 100)))
                sys.stdout.flush()

        if vertex.state == Out or vertex.state == Both:
            # means that node have son or more
            chooseSons(vertex)

    print('Finish of step 3...\n\nStart step 4 (save to file)')
    # save in edges.csv file (GraphSim and Neo4j input)
    with open(out_filename, 'w') as outFile:
        if graph_format == 'neptune':
            outFile.write('~id, ~from, ~to, weight:Double\n')

        for i, vertex in enumerate(global_vertices):
            if num_of_vertices > 100:
                if i % print_count == 0:
                    sys.stdout.write('{} ({}%) \r'.format(
                        i, int((i / num_of_vertices) * 100)))
                    sys.stdout.flush()

            ordered_sons = collections.OrderedDict(sorted(vertex.sons.items()))
            for son, weight in ordered_sons.items():
                edge = '{},'.format(
                    vertex.id) + '{},'.format(son) + 'T,{}\n'.format(weight)
                outFile.write(edge)
    outFile.close()
    print('Finish step 4')

    if debug:
        # print the vertices and their in and out degree
        for v in global_vertices:
            print('\n\n\nVertex id: {}'.format(v.id).ljust(20),
                  'state: {}'.format(v.state).ljust(10),
                  'Max degree: {}'.format(v.max_degree).ljust(17),
                  'Out degree: {}'.format(v.out_degree).ljust(17),
                  'In degree: {}'.format(v.in_degree).ljust(15),
                  'has_father'.format(v.has_father))

            print('sons:')
            for k, val in v.sons.items():
                print('(son: {}, weight: {})'.format(k, val), end=', ')

            print('\nfathers:')
            for k, val in v.fathers.items():
                print('(father: {}, weight: {})'.format(k, val), end=', ')
        print()

        # print adjacency matrix
        print('In\Out'.ljust(4), end=' ')
        for i in range(len(global_vertices)):
            print(str(i).ljust(4), end=' ')
        print("\n")

        for vertex in global_vertices:
            print(str(vertex.id).ljust(6), end=' ')
            for _vertex in global_vertices:
                ids = _vertex.sons.keys()
                if _vertex.id in ids:
                    print(str(vertex.sons[ids.index(_vertex.id)]).ljust(4),
                          end=' ')
                else:
                    print(str(0).ljust(4), end=' ')
            print()

    if plot:
        print('\n\nStart step 5 (plotting the graph')

        # plot network graph
        G = nx.Graph().to_directed()
        for i, vertex in enumerate(global_vertices):
            if i % print_count == 0:
                sys.stdout.write('%d \r' % i)
                sys.stdout.flush()

            for s, w in vertex.sons.items():
                G.add_edge(vertex.id, s, weight=w)

        e = [(u, v) for (u, v, d) in G.edges(data=True)]
        pos = nx.layout.spring_layout(G)
        nx.draw(G, pos)
        labels = nx.get_edge_attributes(G, 'weight')
        nx.draw_networkx_nodes(G, pos, node_size=10)
        nx.draw_networkx_edges(G,
                               pos,
                               edgelist=e,
                               width=0.5,
                               arrowstyle='->',
                               arrowsize=4,
                               edge_color='b')
        nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, font_size=10)
        nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif')
        plt.show()
Пример #44
0
    def draw_motif(self, index):
        if VERBOSE:
            print(index)
        if hasattr(index, '__iter__'):
            for idx in index:
                self.draw_motif(idx)
            return

        motif_number = min([
            x for x in self._motif_variations.keys()
            if self._motif_variations[x] == index
        ])
        if VERBOSE:
            print(motif_number)

        bitmask = bin(motif_number)[2:][::-1]
        connection_list = [int(b) for b in bitmask] + [0] * (
            (6 if self._level == 3 else 12) - len(bitmask))

        motif_adg_matrix = []
        for _ in range(self._level):
            motif_adg_matrix.append([0] * self._level)

        pos = 0  # Current position in the connection_list

        if self._directed:
            for i, j in product(range(self._level), repeat=2):
                if VERBOSE:
                    print(pos, ' : ', i, j)
                if i == j:
                    continue
                motif_adg_matrix[i][j] = connection_list[pos]
                pos += 1
        else:
            for i in range(self._level):
                for j in range(i + 1, self._level):
                    if VERBOSE:
                        print(pos, ' : ', i, j)
                    motif_adg_matrix[i][j] = motif_adg_matrix[j][
                        i] = connection_list[pos]
                    pos += 1

        # Build the graph
        if self._directed:
            G = nx.DiGraph()
        else:
            G = nx.Graph()
        G.add_edges_from([(i, j)
                          for i, j in product(range(self._level), repeat=2)
                          if motif_adg_matrix[i][j] != 0])

        # Draw it
        pos = nx.layout.spring_layout(G)
        nx.draw_networkx_nodes(G, pos)
        if self._directed:
            nx.draw_networkx_edges(G, pos, arrowstyle='->', arrowsize=30)
        else:
            nx.draw_networkx_edges(G, pos)

        nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif')

        plt.title('Motif with index {}'.format(index))
        plt.axis('off')
        plt.show()

        pass
commInd_football_lp = [list(x) for x in iter(commIndSet_football)]


# Community detection with the girvan-newman algorithm
commInd_karate_gn = girvan_newman_opt(G_karate)
commInd_football_gn = girvan_newman_opt(G_football)



# drawing the graph (karate network)
plt.figure(figsize=[9,4])

# first, graph without community assignments
plt.subplot(131)
pos = nx.kamada_kawai_layout(G_karate, weight=None) # positions for all nodes
nx.draw_networkx_nodes(G_karate, pos)
nx.draw_networkx_edges(G_karate, pos,
                       edge_color='lightblue')
nx.draw_networkx_labels(G_karate, pos, font_size=10, font_color='DarkGreen')
plt.title('Original karate network')
plt.axis('off')
plt.xlim([-0.6, 0.65])
plt.ylim([-0.85, 1.2])

# next, graph with communities in different colors (label propagation)
plt.subplot(132)
for iComm in range(len(commInd_karate_lp)):
    nx.draw_networkx_nodes(G_karate, pos, nodelist=commInd_karate_lp[iComm],
                           cmap=plt.cm.rainbow,
                           vmin=0, vmax=len(commInd_karate_lp)-1,
                           node_color = [iComm]*len(commInd_karate_lp[iComm]),
Пример #46
0
    #plot delta colors
    delta_colors = {
        'added': '#339966',
        'removed': 'r',
        'modified': '#3366ff',
        '': node_color
    }  # used default color if no delta
    node_deltas = dict((n, d.get("delta")) for n, d in G.nodes(data=True))
    if len(node_deltas):
        # unchanged
        plotted_nodes = nx.draw_networkx_nodes(
            G,
            pos,
            nodelist=[n for n, d in node_deltas.items() if not d],
            node_size=node_size,
            #alpha = 0.8,
            linewidths=(0, 0),
            node_shape='o',
            zorder=delta_zorders[''],
            node_color=node_color)

        # added
        plotted_nodes = nx.draw_networkx_nodes(
            G,
            pos,
            nodelist=[n for n, d in node_deltas.items() if d == "added"],
            node_size=node_size,
            #alpha = 0.8,
            linewidths=(0, 0),
            node_shape='d',
            zorder=delta_zorders['added'],
Пример #47
0
    def draw_rrt(self, int_ax, control_ax=None):
        ax = int_ax

        for thing in self.to_clear:
            if type(thing) in [
                    matplotlib.collections.LineCollection,
                    matplotlib.collections.PatchCollection,
                    matplotlib.collections.Collection
            ]:
                thing.remove()
            if type(thing) == matplotlib.lines.Line2D:
                ax.lines.remove(thing)

        self.to_clear = []

        #ax.cla()
        #ax.set_xlim(-1,1)
        #ax.set_ylim(-1.5,1)

        #for l in ax.lines:
        #    l.remove()
        #for p in ax.patches:
        #    p.remove()

        tree = self.rrt.tree
        rrt = self.rrt

        if (rrt.viz_change):
            viz_x_nearest = rrt.viz_x_nearest
            viz_x_new = rrt.viz_x_new
            viz_x_from = rrt.viz_x_from
        """        
        best_sol = ani_rrt.best_solution(goal) 
        #xpath = np.array([tree.node[i]['state'] for i in best_sol]).T #straight line connection between nodes
        xpath = [tree.node[best_sol[0]]['state']]
        for (node_from,node_to) in zip(best_sol[:-1],best_sol[1:]):
            xpath.extend( lqr_rrt.run_forward(tree.node[node_from]['state'],tree.node[node_to]['action']) )
        
        xpath = np.array(xpath).T
        ani_ax.plot(xpath[plot_dims[0]],xpath[plot_dims[1]],ls='--',lw=10,alpha=.7,color=(.2,.2,.2,1),zorder=20,label='best path so far')


        if control_ax is not None:
            upath = rrt.get_action(best_sol)
            control_ax.cla()
            control_ax.plot(np.squeeze(upath))
        """

        #draw paths that collided
        if (not rrt.viz_collided_paths is None) and (
                not self.run_forward is None):
            if len(rrt.viz_collided_paths) > 100:
                #too many collided paths, don't bother drawing.
                print 'not drawing collided paths. too many ({})'.format(
                    len(rrt.viz_collided_paths))
            else:
                lines = []
                for (node, action) in rrt.viz_collided_paths:
                    x0 = node['state']
                    xs = self.run_forward(x0, action)
                    xs = np.concatenate((x0.reshape((1, -1)), xs))
                    lines.append(xs[:, self.plot_dims])

                collision_collection = mpl.collections.LineCollection(
                    lines, linewidths=1, linestyles='solid')
                collision_collection.set_color('red')
                collision_collection.set_alpha(.5)
                collision_collection.set_zorder(1)
                collision_collection_added = ax.add_collection(
                    collision_collection)
                self.to_clear.append(collision_collection_added)

            rrt.viz_collided_paths = [
            ]  #reset in order to plot only new collided paths

        if (rrt.viz_change):
            #draws a straight edge
            new_ext_x = [
                viz_x_from[self.plot_dims[0]], viz_x_new[self.plot_dims[0]]
            ]
            new_ext_y = [
                viz_x_from[self.plot_dims[1]], viz_x_new[self.plot_dims[1]]
            ]
            ax.plot(new_ext_x,
                    new_ext_y,
                    'y',
                    lw=5,
                    alpha=.7,
                    zorder=3,
                    label='new extension')

        pos = {n: tree.node[n]['state'][self.plot_dims] for n in tree.nodes()}
        col = [tree.node[n]['cost'] for n in tree.nodes()]

        ax.get_figure().sca(
            ax
        )  #set the current axis to the int_ax. there is some bug in networkx/matplotlib
        node_collection = nx.draw_networkx_nodes(
            G=tree,
            pos=pos,
            ax=ax,
            node_size=25,
            node_color=col,
            cmap=mpl.cm.get_cmap(name='copper'),
        )

        if not node_collection is None:
            node_collection.set_zorder(5)
            self.to_clear.append(node_collection)

        if self.run_forward is None:
            #draw straight edges
            edge_collection = nx.draw_networkx_edges(
                G=tree,
                pos=pos,
                ax=ax,
                edge_color='b',
            )
        else:
            #draw dynamical edges
            if not self.__dict__.has_key('edge_cache'):
                'reset edge_cache'
                self.edge_cache = {}

            lines = []
            for i in tree.nodes():
                if self.edge_cache.has_key(i):
                    xs = self.edge_cache[i]
                else:
                    s = tree.predecessors(i)
                    if len(s) == 0:
                        continue
                    assert len(s) == 1  #it's a tree
                    s = s[0]
                    x0 = tree.node[s]['state']
                    xs = self.run_forward(x0, tree.node[i]['action'])
                    xs = np.concatenate((x0.reshape((1, -1)), xs))
                    self.edge_cache[i] = xs

                lines.append(xs[:, self.plot_dims])

            edge_collection = mpl.collections.LineCollection(lines)
            ax.add_collection(edge_collection)

        if not edge_collection is None:
            edge_collection.set_zorder(4)
            self.to_clear.append(node_collection)

        #mfc, mec, mew is marker face color, edge color, edge width
        if (rrt.viz_change):

            #ani_ax.add_patch(mpl.patches.Circle(xy=viz_x_new,radius=ani_rrt.viz_search_radius,
            #                                    alpha=.3,fc='none',ec='b',label='_rewire radius'))

            self.to_clear.extend(
                ax.plot(*rrt.viz_x_rand[self.plot_dims],
                        marker='*',
                        mfc='k',
                        mec='k',
                        ls='None',
                        zorder=6,
                        label='x_rand'))
            self.to_clear.extend(
                ax.plot(*viz_x_nearest[self.plot_dims],
                        marker='p',
                        mfc='c',
                        mec='c',
                        ls='None',
                        zorder=7,
                        ms=5,
                        label='x_nearest'))
            self.to_clear.extend(
                ax.plot(*viz_x_new[self.plot_dims],
                        marker='x',
                        mfc='r',
                        mec='r',
                        ls='None',
                        zorder=8,
                        label='x_new'))
            self.to_clear.extend(
                ax.plot(*viz_x_from[self.plot_dims],
                        marker='o',
                        mfc='g',
                        mec='g',
                        ls='None',
                        alpha=.5,
                        zorder=9,
                        label='x_from'))

            if rrt.viz_x_near is not None and len(rrt.viz_x_near) > 0:
                x_near = np.array(rrt.viz_x_near)
                self.to_clear.extend(
                    ax.plot(x_near[:, self.plot_dims[0]],
                            x_near[:, self.plot_dims[1]],
                            marker='o',
                            mfc='none',
                            mec='r',
                            mew=1,
                            ls='None',
                            alpha=.5,
                            zorder=10,
                            label='X_near'))

        ax.legend(bbox_to_anchor=(1.05, 0.0),
                  loc=3,
                  ncol=1,
                  borderaxespad=0.,
                  fancybox=True,
                  shadow=True,
                  numpoints=1)

        #ani_ax.legend()
        if ax.get_legend() is not None:
            self.to_clear.append(ax.get_legend())
            plt.setp(ax.get_legend().get_texts(), fontsize='small')

        info = ""
        info += "# nodes: %d\n" % (len(tree.nodes()))
        #info += "# edges: %d\n" % (len(tree.edges()))
        info += "cost: %s\n" % (str(rrt.worst_cost)
                                if rrt.found_feasible_solution else "none")

        if self.info_text is None:
            self.info_text = ax.figure.text(.8, .5, info, size='small')
        self.info_text.set_text(info)
def visualizeSingleSystem(subplots, channel_file, power_system_object, pos, G,
                          a):
    node_labels = {i: str(i) for i in range(1, 40)}

    time, frequencies, res = getFrequencyDeviation(channel_file)

    gens = [gen._bus for gen in power_system_object._generators]
    loads = [load._bus for load in power_system_object._loads]
    stubs = list(
        set(range(1, power_system_object._nbus + 1)) - (set(gens + loads)))
    nodelists = [gens, loads, stubs]
    bus_colors = {}
    node_colors = []

    qss = nx.shortest_path_length(G, 10)
    qsna = {key: (12 - qss[key]) * 1.0 / 10 for key in qss}
    qsa = {key: (14 - qss[key]) * 1.0 / 9 for key in qss}
    qsna[10] = 2.4
    qsna[32] = 1.9
    qsna[13] = 1.3
    qsna[12] = 1.1
    qsna[11] = 1.15
    #qs = {10:0.99,32:0.93,13:0.94,12:0.923,11:0.947,14:0.912,15:0.901,6:0.873,31:}

    for nodelist in nodelists:
        #node_colors.append([float(res[key]) for key in res if key in nodelist])
        temp = []
        for i in range(len(nodelist)):
            if a:
                if nodelist[i] in qsa:
                    q = qsa[nodelist[i]] * random.gauss(.7, .08)
                else:
                    q = 0  #random.gauss(.25,.25)
            else:
                if nodelist[i] in qsna:
                    q = qsna[nodelist[i]] * random.gauss(.35, .08)
                else:
                    q = 0  #random.gauss(.25,.25)

            if q < 0:
                q = 0.0
            if q > 1:
                q = 1.0
            bus_colors[nodelist[i]] = q
            temp.append(q)
        node_colors.append(temp)

    shapes = ['s', 'o', 'o']
    node_sizes = [90, 90, 90]
    img = misc.imread('asd.PNG')
    img[:, :, 3] = 190  #set alpha

    plt.subplot(subplots[0])
    plt.imshow(img, zorder=0, extent=[0.0, 1.0, 0.0, 1.0])
    for i in range(3):
        im = nx.draw_networkx_nodes(G,
                                    pos,
                                    nodelist=nodelists[i],
                                    node_color=node_colors[i],
                                    node_shape=shapes[i],
                                    node_size=node_sizes[i],
                                    cmap=plt.cm.get_cmap('RdYlBu_r'),
                                    vmin=0.0,
                                    vmax=1.0)

    #nx.draw_networkx_labels(G,pos,labels=node_labels,font_size=15)

    plt.axis('off')

    nx.draw_networkx_edges(G, pos)

    cmap = plt.cm.get_cmap('RdYlBu_r')
    plt.subplot(subplots[1])
    #bus_colors[bus]
    for bus in sorted(bus_colors):
        #colorVal = plt.cm.get_cmap('RdYlBu_r').to_rgba(res[bus])
        plt.plot(time,
                 frequencies[bus],
                 color=cmap(bus_colors[bus]),
                 alpha=0.7)
        plt.xlim([0.0, 30.0])
        plt.ylim([59.62, 60.38])
        plt.xlabel('Time [s]')
        if a:
            plt.ylabel('Frequency [Hz]')
        plt.xticks([0, 10, 20, 30])
        plt.yticks([59.7, 60, 60.3])
    return im
Пример #49
0
def show_resolutions_graph(as_repo, domain, control_resolutions,
                           dns_resolutions):
    graph = networkx.DiGraph()
    cnames = set()
    ip_nets = set()
    ases = set()
    bad_edges = set()
    bad_nodes = set()
    good_edges = set()
    good_nodes = set()
    edge_countries = defaultdict(set)
    in_control = True
    for resolutions in [control_resolutions or [], dns_resolutions]:
        for resolution in resolutions:
            country = resolution.measurement["probe_cc"]
            last_cname = resolution.cnames[0]
            cnames.add(last_cname)
            for cname in resolution.cnames:
                edge = last_cname, cname
                graph.add_edge(*edge)
                edge_countries[edge].add(country)
                if in_control:
                    good_edges.add(edge)
                    good_nodes.add(cname)
                last_cname = cname
                cnames.add(cname)
            for ip_address in resolution.ips or [None]:
                if ip_address:
                    ip_net = ipaddress.ip_network(ip_address).supernet(
                        new_prefix=22)
                    asys = as_repo.get_as_for_ip(ip_address)
                    as_str = asys.name or str(asys.id)
                    ases.add(as_str)
                    graph.add_edge(ip_net, as_str)
                    if not ip_address.is_global:
                        bad_edges.add((last_cname, ip_net))
                        bad_nodes.add(ip_net)
                else:
                    ip_net = "<empty>"
                ip_nets.add(ip_net)
                edge = last_cname, ip_net
                graph.add_edge(*edge)
                edge_countries[edge].add(country)
                if in_control:
                    good_edges.add(edge)
                    good_nodes.add(ip_net)
        in_control = False

    nodes_pos = networkx.spring_layout(graph)
    min_x = min(x for x, _ in nodes_pos.values())
    max_x = max(x for x, _ in nodes_pos.values())
    range_x = max_x - min_x
    for node, pos in list(nodes_pos.items()):
        if isinstance(node, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
            nodes_pos[node] = (min_x + range_x * 0.5 + (pos[0] - min_x) * 0.3,
                               pos[1])
        else:
            nodes_pos[node] = (min_x + range_x * 0.1 + (pos[0] - min_x) * 0.3,
                               pos[1])
    nodes_pos[domain] = (min_x, nodes_pos[domain][1])
    for asys in ases:
        nodes_pos[asys] = (max_x, nodes_pos[asys][1])
    networkx.draw_networkx_nodes(graph,
                                 nodelist=cnames,
                                 pos=nodes_pos,
                                 node_color="b")
    networkx.draw_networkx_nodes(graph,
                                 nodelist=ip_nets - bad_nodes,
                                 pos=nodes_pos,
                                 node_color="gray")
    networkx.draw_networkx_labels(graph, pos=nodes_pos, font_size=8)
    networkx.draw_networkx_edges(graph, pos=nodes_pos, alpha=0.25)
    edge_labels = dict(
        (key, " ".join(countries) if len(countries) <= 3 else "*")
        for key, countries in edge_countries.items())
    networkx.draw_networkx_edge_labels(graph,
                                       edge_labels=edge_labels,
                                       pos=nodes_pos,
                                       alpha=0.5,
                                       font_size=8,
                                       label_pos=0.2)
    networkx.draw_networkx_edges(graph,
                                 edgelist=good_edges,
                                 pos=nodes_pos,
                                 alpha=0.5,
                                 edge_color="g")
    networkx.draw_networkx_nodes(graph,
                                 nodelist=good_nodes,
                                 pos=nodes_pos,
                                 node_color="g")
    networkx.draw_networkx_edges(graph,
                                 edgelist=bad_edges,
                                 pos=nodes_pos,
                                 alpha=0.5,
                                 edge_color="r")
    networkx.draw_networkx_nodes(graph,
                                 nodelist=bad_nodes,
                                 pos=nodes_pos,
                                 node_color="r")
    pyplot.show()
Пример #50
0
def topo(f, g, pos):
    nx.draw_networkx_nodes(g, pos, alpha=0.09, node_size=500)
    nx.draw_networkx_edges(g, pos, alpha=0.4)
Пример #51
0
    _ics = ic_graph.enumerate_blute(callback=callback, at_most=-1)
    for ic in _ics:
        stats = ic_graph.evaluate_subgraph(ic)
        print(ic)  # ic_graph.decode(ic,1)

    sys.exit()

    # drawing
    rand_colors = generate_random_color_list(len(cliques))
    pos = nx.spring_layout(G)  # positions for all nodes
    node_list = set(G.nodes())
    edge_list = set(G.edges())
    for i in range(len(cliques)):
        H = G.subgraph(cliques[i])
        nx.draw_networkx_nodes(H,
                               pos,
                               nodelist=cliques[i],
                               node_color=rand_colors[i])
        print(H.edges())
        nx.draw_networkx_edges(H,
                               pos,
                               edge_list=H.edges(),
                               edge_color=rand_colors[i],
                               width=4)
        node_list = node_list - set(cliques[i])
        edge_list = edge_list - set(H.edges())

    nx.draw_networkx_nodes(H, pos, nodelist=node_list, node_color="#808080")
    nx.draw_networkx_edges(H, pos, edgelist=edge_list, edge_color="#808080")
    plt.show()
Пример #52
0
    for ii in range(self.ndots):
        G.add_node(ii)

    for ii in range(self.ndots):
        G.add_edge(ii, ii, label='det%d' % ii)

        # G.add_edge('1','2')

    #G.add_node(10, {'name': 'sdfs', 'label': 'hi'})

    plt.figure(10)
    plt.clf()
    plt.axis('off')
    pos = nx.layout.spring_layout(G)
    #nx.draw(G, pos=pos)
    nx.draw_networkx_nodes(G, pos=pos, node_size=4000, node_color="g")
    nx.draw_networkx_edges(G, pos=pos)

    labels = dict([(i, 'node%d' % i) for i in range(3)])
    nx.draw_networkx_labels(G, pos=pos, labels=labels, font_size=16)
    plt.show()

#%% Testing


def testTriple():
    tripledot = TripleDot(name='tripledot')

    tripledot.det1 = 0
    tripledot.det2 = 0
    tripledot.det3 = 0
Пример #53
0
justified = {
    k: v
    for k, v in pos.items() if k in n.justified and k not in n.finalized
}
unjustified = {
    k: v
    for k, v in pos.items() if k not in n.justified and k in n.blocks
}
sigs = {k: v for k, v in pos.items() if k not in n.blocks}

edges = G.edges()
colors = [G[u][v]['color'] for u, v in edges]

nx.draw_networkx_nodes(G,
                       pos,
                       nodelist=sigs.keys(),
                       node_size=5,
                       node_shape='o',
                       node_color='0.75')
nx.draw_networkx_nodes(G,
                       pos,
                       nodelist=unjustified.keys(),
                       node_size=10,
                       node_shape='o',
                       node_color='0.75')
nx.draw_networkx_nodes(G,
                       pos,
                       nodelist=justified.keys(),
                       node_size=16,
                       node_shape='o',
                       node_color='y')
nx.draw_networkx_nodes(G,
Пример #54
0
House With Colors
=================

Draw a graph with matplotlib.
"""
import matplotlib.pyplot as plt
import networkx as nx

G = nx.house_graph()
# explicitly set positions
pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}

# Plot nodes with different properties for the "wall" and "roof" nodes
nx.draw_networkx_nodes(G,
                       pos,
                       node_size=3000,
                       nodelist=[0, 1, 2, 3],
                       node_color="tab:blue")
nx.draw_networkx_nodes(G,
                       pos,
                       node_size=2000,
                       nodelist=[4],
                       node_color="tab:orange")
nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
# Customize axes
ax = plt.gca()
ax.margins(0.11)
plt.tight_layout()
plt.axis("off")
plt.show()
Пример #55
0
def draw_tree(tree, dts, min_size=None, *args, **kwargs):
    """
    Draws a heirarchical tree

    Kwargs:
        font_size:
        node_scale:
        figsize:
    """
    def populate_nx_tree(G, tree):
        for element in tree:
            if isinstance(element,
                          Iterable) and not isinstance(element, (int)):
                G.add_node(
                    element,
                    attr_dict={'size': len(list(flatten_list(element)))})
                for minor_element in element:
                    G.add_edge(element, minor_element)
                populate_nx_tree(G, element)
            else:
                G.add_node(element, attr_dict={'size': 1})

    G = nx.DiGraph()
    populate_nx_tree(G, tree)
    G = nx.convert_node_labels_to_integers(G)

    if min_size is not None:
        remove = [
            node for node, size in nx.get_node_attributes(G, 'size').items()
            if size < min_size
        ]
        G.remove_nodes_from(remove)

    # Defaults
    node_scale = kwargs.get('node_scale', 10)
    font_size = kwargs.get('font_size', 6)
    figsize = kwargs.get('figsize', (30, 10))

    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(111)
    ax.set_axis_off()

    root = [
        ix for ix, val in nx.in_degree_centrality(G).items() if val == 0.0
    ][0]
    remove = [
        ix for ix, length in nx.shortest_path_length(G, root).items()
        if length > len(dts)
    ]
    G.remove_nodes_from(remove)

    dts = sorted(dts)
    dts.append(r'\infty')
    layers = len(dts)
    buffer = 0.2
    spacer = (1 - buffer) / layers
    for ix, dt in enumerate(dts):
        ax.text(0,
                buffer + ix * spacer,
                r"$\Delta t = {}$".format(dt),
                transform=ax.transAxes,
                fontdict={'size': 2 * font_size})

    pos = nx.nx_pydot.graphviz_layout(G, prog='dot')
    sizes = nx.get_node_attributes(G, 'size')

    nx.draw_networkx_labels(G, pos, labels=sizes, font_size=font_size, ax=ax)
    nx.draw_networkx_edges(G, pos, arrows=False)
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=sizes.keys(),
                           node_size=[x * node_scale for x in sizes.values()])

    return None
Пример #56
0
cc = graphsSorted[0]

ego = nx.Graph(nx.ego_graph(cc, 'batsman', radius=2))
d = nx.degree(ego)

elarge = [(u, v) for (u, v, d) in ego.edges(data=True) if d['weight'] > 1]
esmall = [(u, v) for (u, v, d) in ego.edges(data=True) if d['weight'] <= 1]

pos = nx.spring_layout(ego)

nx.draw(ego,
        pos,
        node_size=[v * 10 for v in d.values()],
        with_labels=True,
        font_size=8)

nx.draw_networkx_nodes(ego,
                       pos,
                       nodelist=['batsman'],
                       node_size=300,
                       node_color='g')

nx.draw_networkx_edges(ego, pos, edgelist=elarge, width=3)
nx.draw_networkx_edges(ego,
                       pos,
                       edgelist=esmall,
                       width=1,
                       alpha=0.5,
                       style='dashed',
                       edge_color='g')
Пример #57
0
def draw_graph(graph, embedding, labels, path, s=25):
    assert embedding.shape[1] == 2 

    if isinstance(graph, csr_matrix):
        raise NotImplementedError
        edges = list(zip(*graph.nonzero()))
    else:
        edges = list(graph.edges)

    if labels is not None:
        # filter out noise nodes labelled as -1
        # idx, = np.where(labels[:,0] > -1)
        num_labels = int(max(set(labels[:,0])) + 1)
        # colours = np.random.rand(num_labels, 3)
        colours = np.array([
            [1,0,0],
            [0,1,0],
            [0,0,1],
            [1,1,0],
            [1,0,1],
            [0,1,1],
            [0,0,0],
            [1,1,1]
        ]) 
        # colours = np.array(["r", "g", "b", "y", "m", "c"])
        assert num_labels < len(colours)
    else:
        idx = np.arange(len(embedding))
        colours = None

    if not isinstance(edges, np.ndarray):
        edges = np.array(edges)

    print ("saving two-dimensional poincare plot to {}".format(path))

    fig = plt.figure()
    title = "Two dimensional poincare plot"
    plt.suptitle(title)
    
    ax = fig.add_subplot(111)

    hyperbolic_setup(fig, ax)

    # a = embedding[edges[:,0]]
    # b = embedding[edges[:,1]]
    # c = get_third_point(a, b)
    
    # draw_geodesic(a, b, c, ax)

    # # s = {n: (bc+.05) * 100 for n, bc in nx.betweenness_centrality(graph).items()}
    # # s = [s[n] for n in sorted(graph.nodes)]
    # s = np.array([graph.degree(n, weight="weight") for n in sorted(graph.nodes())])
    # s = s / s.max() * 100
    # ax.scatter(embedding[idx,0], embedding[idx,1], 
    #     c=colours[labels[idx,0]] if labels is not None else None,
    #     s=s, zorder=2)

    pos = {n: emb for n, emb in zip(sorted(graph.nodes()), embedding)}
    node_colours = np.array([colours[labels[n, 0]] for n in graph.nodes()]) if colours is not None else None
    
    # bc  = nx.betweenness_centrality(graph)
    # node_sizes = np.array([(bc[n] + .05) * 50 for n in sorted(graph.nodes())])
    node_sizes = np.array([graph.degree(n, weight="weight") for n in graph.nodes()])
    node_sizes = node_sizes / node_sizes.max() * 250
    nx.draw_networkx_nodes(graph, pos=pos, node_color=node_colours, node_size=node_sizes)
    nx.draw_networkx_edges(graph, pos=pos, width=.05, node_size=node_sizes)
    # nx.draw_networkx_edge_labels(graph, pos=pos, edge_labels=nx.get_edge_attributes(graph, name="weight"))

    plt.savefig(path)
    plt.close()
figure(2)
#draw(g,pos)
# specifiy edge labels explicitly

g = Graph()
g.adj = net.adj

edge_labels = dict([((
    u,
    v,
), d['weight']) for u, v, d in g.edges(data=True)])

pos = spring_layout(net.pos)
pos = net.pos  #Ako pos nije izvuceno iz net.pos rasporede se tako da se bolje vide

draw_networkx_nodes(g, pos=pos, node_size=500)
draw_networkx_edges(g, pos=pos)
draw_networkx_labels(g, pos=pos, labels=net.labels)
draw_networkx_edge_labels(g, pos=pos, edge_labels=edge_labels)
# show graphs
show()

net.algorithms = (MegaMerger, )
write_pickle(net, 'RandomSAlg.tar.gz')

#write_pickle(net, 'WorstCaseSAlg.tar.gz')
##s ovom mrezom pokretati GUI simulator

dobro = True
count = 0
Пример #59
0
def decomposition_democrat(GU, core=False, truss=False):
    # Democrat Graph
    nodes = (
        node
        for node, data in GU.nodes(data=True)
        if data.get("Party") == "Democrat"
    )

    largest_cc = max(nx.connected_components(nx.Graph(GU.subgraph(nodes))), key=len)
    GU_Democrat = GU.subgraph(largest_cc)

    if core:
        nodes = nx.k_core(GU_Democrat, k=12).nodes()
    elif truss:
        nodes = nx.k_truss(GU_Democrat, k=4).nodes()

    node_color = []
    for node in GU_Democrat.nodes():
        if node in nodes:
            node_color.append("yellow")
        else:
            node_color.append("blue")

    d = nx.degree(GU_Democrat)
    sizes = [(d[node] + 1) * 5 for node in GU_Democrat.nodes()]

    # Specify the settings for the Force Atlas 2 algorithm
    forceatlas2 = ForceAtlas2(
        # Behavior alternatives
        outboundAttractionDistribution=True,  # Dissuade hubs
        linLogMode=False,  # NOT IMPLEMENTED
        adjustSizes=False,  # Prevent overlap (NOT IMPLEMENTED)
        edgeWeightInfluence=1.0,

        # Performance
        jitterTolerance=1.0,  # Tolerance
        barnesHutOptimize=True,
        barnesHutTheta=1.2,
        multiThreaded=False,  # NOT IMPLEMENTED

        # Tuning
        scalingRatio=2.0,
        strongGravityMode=False,
        gravity=5.0,

        # Log
        verbose=True)

    positions = forceatlas2.forceatlas2_networkx_layout(GU, pos=None, iterations=2000)

    plt.figure(num=None, figsize=(15, 9), dpi=80, facecolor='w', edgecolor='k')

    sns.set_style('whitegrid')
    sns.set_context('talk')

    # create legend
    plt.scatter([], [], c='yellow', alpha=0.7, s=100, label='Most Influential Democrats')
    plt.legend(scatterpoints=1, frameon=True, labelspacing=1)

    nx.draw_networkx_nodes(GU_Democrat, positions, node_size=sizes, node_color=node_color, alpha=0.7)
    nx.draw_networkx_edges(GU_Democrat, positions, edge_color="grey", alpha=0.08)
    ax = plt.gca()
    ax.collections[0].set_linewidth(0.1)
    ax.set_title('US House Democrat Representatives of 2020 network', fontsize=16);
    plt.axis('off')

    if core:
        plt.savefig("./images/core_democrat.png", format="PNG")
    elif truss:
        plt.savefig("./images/truss_democrat.png", format="PNG")
        return nodes, GU_Democrat
def plotNetwork(net,
                df,
                width_scaling=4000,
                alpha=0.8,
                legend_entries=6,
                legend_decimals=6,
                ccol='blue',
                nccol='red',
                edge_cmap=plt.cm.viridis_r,
                layout=nx.spring_layout,
                seed=9,
                entry_width=0.03 * 0.63,
                left_legend_offset=1.05,
                dpi=50,
                name='',
                save=False):
    #set up plot
    np.random.seed(seed)
    fig, ax = plt.subplots(1, 1, figsize=(20, 15))
    ax.set_axis_off()
    ax.set_title(name)
    nodeidx = {node: i for i, node in enumerate(net.nodes())}
    #color nodes
    nodestatus = getNodeStatus(df)
    cnodes = [n for n in net.nodes() if nodestatus[n] == 'crispr']
    ncnodes = [n for n in net.nodes() if nodestatus[n] == 'non-crispr']
    #color and set edge widths
    edgelist = [(u, v) for u, v in net.edges()]
    edge_color = [net[u][v]['weight'] for (u, v) in edgelist]
    edge_width = [
        net[u][v]['sem_weight'] * width_scaling for (u, v) in edgelist
    ]
    #set node positions
    if layout == nx.shell_layout:
        pos = layout(net, [cnodes, ncnodes])
    else:
        pos = layout(net)
    #Draw graph
    cnd = nx.draw_networkx_nodes(net,
                                 pos,
                                 ax=ax,
                                 nodelist=cnodes,
                                 node_color=ccol,
                                 alpha=alpha)
    ncnd = nx.draw_networkx_nodes(net,
                                  pos,
                                  ax=ax,
                                  nodelist=ncnodes,
                                  node_color=nccol,
                                  alpha=alpha)
    lbls = nx.draw_networkx_labels(net, pos, nodeidx, ax=ax)
    edges = nx.draw_networkx_edges(net,
                                   pos,
                                   ax=ax,
                                   width=edge_width,
                                   edgelist=edgelist,
                                   edge_color=edge_color,
                                   edge_cmap=edge_cmap)
    #create legends
    pltfnc = partial(plt.legend,
                     fancybox=True,
                     loc='upper right',
                     prop={'size': 10})
    fig.colorbar(edges, ax=ax)
    #width legend
    widthlegend = []
    widthticks = np.linspace(min(edge_width), max(edge_width), legend_entries)
    for width in widthticks:
        label = np.around(width / width_scaling, legend_entries)
        widthlegend.append(
            mpl.lines.Line2D([], [],
                             color='black',
                             linewidth=width,
                             label=label))
    bbox2 = (left_legend_offset, 1)
    width_legend = pltfnc(handles=widthlegend,
                          bbox_to_anchor=bbox2,
                          title="$\\bf{Std. Error}$")
    ax = plt.gca().add_artist(width_legend)
    #status legend
    statuslegend = [
        mpl.patches.Patch(color=ccol, label='CRISPR'),
        mpl.patches.Patch(color=nccol, label='Non-CRISPR')
    ]
    height1 = 1 - (len(widthlegend) + 1) * entry_width
    bbox1 = (left_legend_offset, height1)
    status_legend = pltfnc(handles=statuslegend,
                           bbox_to_anchor=bbox1,
                           title="$\\bf{Node Status}$")
    ax = plt.gca().add_artist(status_legend)
    #accession legend
    acclegends = []
    for a, i in nodeidx.items():
        label = '{} = {}'.format(i, a)
        acclegends.append(mpl.lines.Line2D([], [], linewidth=0, label=label))
    height2 = height1 - (len(statuslegend) + 1) * entry_width
    bbox3 = (left_legend_offset, height2)
    pltfnc(handles=acclegends,
           bbox_to_anchor=bbox3,
           title="$\\bf{Accession Numbers}$")
    #savefig
    if type(save) != bool:
        fig.savefig(save, dpi=dpi, format='png', frameon=False)
    plt.show()