[PYTHON] Create a Connecting Nearest Neighbor with NetworkX

I want to create a network with the connecting Nearest Neighbor algorithm a while ago! When I was consulted, I remember that I couldn't find an example of trying using Python and a package such as NetworkX even if I looked around, so I will post it. I didn't create it by myself, but I made various changes to make it easier to understand (I think). If you have any improvements, please let me know.

environment

What is NetworkX

Official page

I don't talk much because my seniors have written a lot of useful things.

I studied while referring to.

What is Connecting Nearest Neighbor

A model of network generation proposed by Vazquez. The original is Growing network with local rules: Preferential attachment, clustering hierarchy, and degree correlations

I'm not familiar with network-related research, so I'm sorry. In rewriting this time

I was allowed to refer to.

algorithm

  1. Determine the parameter u
  2. Repeat the following until you reach the required number of nodes
  3. Create a new node with a probability of 1-u. Randomly select one existing node and connect a new node with a real link. A potential link is established between all the nodes connected to the selected node by the actual link and the new node.
  4. With a probability of u, randomly select a potential link and change it to a real link

program

CNN class


import networkx as nx
import random
import matplotlib.pyplot as plt


class CNN:
    def __init__(self, node_num, u, seed = 0):
        self.graph = nx.Graph()
        self.node_num = node_num
        self.u = u
        random.seed(seed)
        self.make_cnn()
        
    def make_cnn(self):
        self.graph.add_node(0)
        while len(list(self.graph.nodes)) < self.node_num:
            #Add a new node with probability u
            if random.random() < 1 - self.u:
                new_node = len(list(self.graph.nodes))
                self.graph.add_node(new_node)
                #Randomly select nodes that already exist in the network
                node_list = list(self.graph.nodes)
                node_list.remove(new_node)
                selected_node = random.choice(node_list)
                # selected_new to all adjacent nodes of node_Connect the potential edge with node
                neighbor_nodes = self.get_neighbors(selected_node)
                for nn in neighbor_nodes:
                    self.graph.add_edge(nn, new_node, attribute="potential")
                #Connect the real edge
                self.graph.add_edge(selected_node, new_node, attribute="real")
            #Probability 1-Randomly select a potential link with u and convert it to a real edge
            else:
                potential_edge_list = self.get_attribute_edgelist("potential")
                if len(potential_edge_list) > 0:
                    node_a, node_b = random.choice(potential_edge_list)
                    self.graph.edges[node_a, node_b]["attribute"] = "real"
                    

    def get_attribute_edgelist(self, attr):
        '''
The value of the edge is attr(potenntial or real)Returns a list of edges
        '''
        # {(node, node):attribute}Get the dict
        edge_dict = nx.get_edge_attributes(self.graph, "attribute")
        attr_edgelist = []
        for edge, attribute in edge_dict.items():
            if attribute == attr:
                attr_edgelist.append(edge)
        return attr_edgelist
                
    def get_neighbors(self, node):
        '''
node and real_Returns a list of nodes connected by edge
        '''
        edgelist = self.get_attribute_edgelist("real")
        nodelist = []
        for node_a, node_b in edgelist:
            if node_a == node:
                nodelist.append(node_b)
            elif node_b == node:
                nodelist.append(node_a)
        return nodelist
    
    def plot_graph(self):
        plt.figure(figsize=(15, 10), facecolor="w")
        pos = nx.spring_layout(self.graph, k=1.0)
        real_edge_list = self.get_attribute_edgelist("real")
        nx.draw_networkx_nodes(self.graph,
                               pos,
                               node_color="r")
        nx.draw_networkx_edges(self.graph, pos, edgelist=real_edge_list)
        nx.draw_networkx_labels(self.graph, pos, font_size=10)
        
        plt.axis("off")
        plt.show()

Run


cnn = CNN(node_num=100, u=0.9)
cnn.make_cnn()
cnn.plot_graph()

Then you will get this figure.

u=0.1 u=0.1.png

u=0.5 u=0.5.png

u=0.9 u=0.9.png

Recommended Posts

Create a Connecting Nearest Neighbor with NetworkX
Draw a graph with NetworkX
Create a homepage with django
Create a directory with python
Draw a graph with networkx
Create a virtual environment with Python!
Create a poisson stepper with numpy.random
Create a file uploader with Django
Create a Python function decorator with Class
Build a blockchain with Python ① Create a class
Create a dummy image with Python + PIL.
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Create a large text file with shellscript
Create a star system with Blender 2.80 script
Create a virtual environment with Python_Mac version
Create a VM with a YAML file (KVM)
Create a simple web app with flask
Create a word frequency counter with Python 3.4
Create a web service with Docker + Flask
Create a private repository with AWS CodeArtifact
Create a car meter with raspberry pi
Create a devilish picture with Blender scripts
Create a matrix with PythonGUI (text box)
Create a graph with borders removed with matplotlib
Create a Python3 environment with pyenv on Mac and display a NetworkX graph
Create a GUI executable file created with tkinter
Create a LINE BOT with Minette for Python
Create a game UI from scratch with pygame2!
Create a PDF file with a random page size
Create a page that loads infinitely with python
[Note] Create a one-line timezone class with python
You can easily create a GUI with Python
Create a python3 build environment with Sublime Text3
Create a bulletin board with Heroku, Flask, SQLAlchemy
Create a dashboard for Network devices with Django!
Create a matrix with PythonGUI (tkinter combo box)
Create a color bar with Python + Qt (PySide)
Steps to create a Twitter bot with python
Create a decision tree from 0 with Python (1. Overview)
Create a new page in confluence with Python
Create a color-specified widget with Python + Qt (PySide)
How to create a multi-platform app with kivy
Create a one-file hello world application with django
Create a Photoshop format file (.psd) with python
Create a Python console application easily with Click
Create a cylinder with open3d + STL file output
Create a "Hello World" (HTTP) server with Tornado
Create a translation tool with the Translate Toolkit
Create a table of contents with IPython notebook
[Python] Draw a Qiita tag relationship diagram with NetworkX
Create a Todo app with Django REST Framework + Angular
I tried to create a table only with Django
Create a native GUI app with Py2app and Tkinter
How to create a submenu with the [Blender] plugin
Try to dynamically create a Checkbutton with Python's Tkinter
Create a virtual environment with Anaconda installed via Pyenv
[Python] Create a ValueObject with a complete constructor using dataclasses
Create a Todo app with the Django REST framework
Why not create a stylish table easily with Python?
Create a python development environment with vagrant + ansible + fabric