Пример #1
0
    def labeling_to_root(self, graph, vertex):
        labeled_graph = nx.Graph(graph)
        source_path_lengths = nx.single_source_dijkstra_path_length(
            graph, vertex)
        nx.set_node_attributes(labeled_graph, source_path_lengths, 'labeling')

        return labeled_graph
Пример #2
0
def create_graph_rendrer(threshold, df, graph_df):
    plot_new = Plot(plot_width=1100,
                    plot_height=800,
                    x_range=Range1d(-1.1, 1.1),
                    y_range=Range1d(-1.1, 1.1))
    plot_new.title.text = "Dash-Graph"

    color_dict = {}

    for i in range(1, df['UserID'].max() + 1):
        color_dict[i] = df.groupby('UserID').groups[i].size * 1.9

    pal_hex_lst = bokeh.palettes.viridis(21)
    mapper = LinearColorMapper(palette=pal_hex_lst, low=0, high=21)

    G = create_graph(graph_df, threshold, True)

    # add graph's attributes
    node_size = {k: ((5 * v) + 5) for k, v in G.degree()}
    nx.set_node_attributes(G, color_dict, 'node_color')
    nx.set_node_attributes(G, node_size, 'node_size')
    graph_renderer = from_networkx(G, nx.spring_layout)
    graph_renderer.node_renderer.glyph = Circle(size='node_size',
                                                fill_color={
                                                    'field': 'node_color',
                                                    'transform': mapper
                                                })
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="black",
                                                   line_alpha=0.8,
                                                   line_width=0.5)
    graph_renderer.selection_policy = NodesAndLinkedEdges()

    plot.renderers.append(graph_renderer)
Пример #3
0
    def canonicalizes(self, subgraph):

        st = time.time()

        #wl_subgraph_normalized=self.wl_normalization(subgraph)['labeled_graph']
        #g_relabel=convert_node_labels_to_integers(wl_subgraph_normalized)

        g_relabel = convert_node_labels_to_integers(subgraph)
        labeled_graph = nx.Graph(g_relabel)

        nauty_graph = Graph(len(g_relabel.nodes()), directed=False)
        nauty_graph.set_adjacency_dict(
            {n: list(nbrdict)
             for n, nbrdict in g_relabel.adjacency()})

        labels_dict = nx.get_node_attributes(g_relabel, 'labeling')
        canonical_labeling_dict = {
            k: canonical_labeling(nauty_graph)[k]
            for k in range(len(g_relabel.nodes()))
        }

        new_ordered_dict = self.rank_label_wrt_dict(g_relabel, labels_dict,
                                                    canonical_labeling_dict)

        nx.set_node_attributes(labeled_graph, new_ordered_dict, 'labeling')

        ed = time.time()
        self.all_times['canonicalizes'].append(ed - st)

        return labeled_graph
Пример #4
0
    def zeroReceptiveField(self):
        graph = nx.star_graph(self.k - 1)  #random graph peu importe sa tete
        nx.set_node_attributes(graph, self.dummy_value, 'attr_name')
        nx.set_node_attributes(graph,
                               {k: k
                                for k, v in dict(graph.nodes()).items()},
                               'labeling')

        return graph
Пример #5
0
    def __init__(self,
                 nx_graph,
                 w,
                 s=1,
                 k=10,
                 labeling_procedure_name='betweeness',
                 use_node_deg=False,
                 one_hot=False,
                 dummy_value=-1):
        self.nx_graph = nx_graph
        self.use_node_deg = use_node_deg
        if self.use_node_deg:
            node_degree_dict = dict(self.nx_graph.degree())
            normalized_node_degree_dict = {
                k: v / len(self.nx_graph.nodes())
                for k, v in node_degree_dict.items()
            }
            nx.set_node_attributes(self.nx_graph, normalized_node_degree_dict,
                                   'attr_name')
        self.all_times = {}
        self.all_times['neigh_assembly'] = []
        self.all_times['normalized_subgraph'] = []
        self.all_times['canonicalizes'] = []
        self.all_times['compute_subgraph_ranking'] = []
        self.all_times['labeling_procedure'] = []
        self.all_times['first_labeling_procedure'] = []
        self.w = w
        self.s = s
        self.k = k
        self.dummy_value = dummy_value
        self.exists_dummies = False
        self.one_hot = one_hot
        self.labeling_procedure_name = labeling_procedure_name

        if self.labeling_procedure_name == 'approx_betweeness':
            st = time.time()
            self.dict_first_labeling = self.betweenness_centrality_labeling(
                self.nx_graph, approx=int(len(self.nx_graph.nodes()) / 5) + 1)
            self.labeling_procedure_name = 'betweeness'
            end = time.time()
            self.all_times['first_labeling_procedure'].append(end - st)
        elif self.labeling_procedure_name == 'betweeness':
            st = time.time()
            self.dict_first_labeling = self.betweenness_centrality_labeling(
                self.nx_graph)
            end = time.time()
            self.all_times['first_labeling_procedure'].append(end - st)
        else:
            st = time.time()
            self.dict_first_labeling = self.labeling_procedure(self.nx_graph)
            end = time.time()
            self.all_times['first_labeling_procedure'].append(end - st)

        self.original_labeled_graph = self.dict_first_labeling['labeled_graph']
Пример #6
0
    def create_empty_receptive_field(self):
        """
        Method that creates a dummy receptive field for padding purposes

        :return: a receptive field of dummy nodes
        """

        graph = nx.star_graph(self.rf_size - 1)
        nx.set_node_attributes(graph, self.dummy_value, 'attr_name')
        nx.set_node_attributes(graph, {element: element for element, v in dict(graph.nodes()).items()}, 'labeling')

        return graph
Пример #7
0
    def compute_subgraph_ranking(self,subgraph,vertex,original_order_to_respect):
        
        st=time.time()

        labeled_graph=nx.Graph(subgraph)
        ordered_subgraph_from_centrality=self.labeling_to_root(subgraph,vertex)

        all_labels_in_subgraph_dict=nx.get_node_attributes(ordered_subgraph_from_centrality,'labeling')

        new_ordered_dict=self.rank_label_wrt_dict(ordered_subgraph_from_centrality,all_labels_in_subgraph_dict,original_order_to_respect)

        nx.set_node_attributes(labeled_graph,new_ordered_dict,'labeling') 
        ed=time.time()
        self.all_times['compute_subgraph_ranking'].append(ed-st)
        return labeled_graph
Пример #8
0
 def betweenness_centrality_labeling(self,graph,approx=None):
     result={}
     labeled_graph=nx.Graph(graph)
     if approx is None:
         centrality=list(nx.betweenness_centrality(graph).items())
     else:
         centrality=list(nx.betweenness_centrality(graph,k=approx).items())
     sorted_centrality=sorted(centrality,key=lambda n:n[1],reverse=True)
     dict_={}
     label=0
     for t in sorted_centrality:
         dict_[t[0]]=label
         label+=1
     nx.set_node_attributes(labeled_graph,dict_,'labeling')
     ordered_nodes=list(zip(*sorted_centrality))[0]
     
     result['labeled_graph']=labeled_graph
     result['sorted_centrality']=sorted_centrality
     result['ordered_nodes']=ordered_nodes
     return result
Пример #9
0
    def compute_graph_ranking(graph: nx.Graph,
                              vertex: int,
                              original_node_order: dict):
        """
        Method that relabels a graph w.r.t. nodes distances to given root

        :param graph: subgraph to rank
        :param vertex: landmark vertex for the ranking
        :param original_node_order: original ranking
        :return: graph labeled by the new ranking
        """

        labeled_graph = nx.Graph(graph)
        ordered_graph = compute_ranking_distance(graph, vertex)
        labels = nx.get_node_attributes(ordered_graph, 'labeling')

        new_order = relabel_graph(graph=ordered_graph,
                                  original_labeling=labels,
                                  new_labeling=original_node_order)

        nx.set_node_attributes(labeled_graph, new_order, 'labeling')

        return labeled_graph
Пример #10
0
    def nauty_graph_automorphism(graph: nx.Graph):
        """
        Graph canonicalization funtion, meant to break timebreakers of the non-injective ranking function

        :param graph: subgraph to be canonicalized
        :return: canonicalized subgraph
        """

        # convert labels to integers to give nauty the node partitions required
        graph_int_labeled = convert_node_labels_to_integers(graph)
        canonicalized_graph = nx.Graph(graph_int_labeled)

        # get canonicalized graph using nauty
        nauty = Graph(len(graph_int_labeled.nodes()), directed=False)
        nauty.set_adjacency_dict({node: list(nbr) for node, nbr in graph_int_labeled.adjacency()})

        labels_dict = nx.get_node_attributes(graph_int_labeled, 'labeling')
        canonical_labeling_order = {k: canonical_labeling(nauty)[k] for k in
                                    range(len(graph_int_labeled.nodes()))}

        canonical_order = relabel_graph(graph_int_labeled, labels_dict, canonical_labeling_order)
        nx.set_node_attributes(canonicalized_graph, canonical_order, 'labeling')

        return canonicalized_graph
Пример #11
0
def activate_nodes(fileN, p, beginRange, endRange, outFileName):
	# READ GRAPH FROM FILE
	g = nx.read_edgelist(fileN)
	#g = nx.read_weighted_edgelist(fileN)

	# SORT BY DEGREE
	sorted(g.degree, key=lambda x: x[1], reverse=True)

	# SET ATTRIBUTE 0 TO ALL NODES 
	attr = 0
	nx.set_node_attributes(g, attr, 'attr')
	
	att = nx.get_node_attributes(g, 'attr')
	#print att
	
	numNodes = 0
	
	for k, v in att.items():
		numNodes = numNodes + 1
		#print("Key : {0}, Value : {1}".format(k, v))
		
	#numNodes = number_of_nodes(g)
	
	
	if (p == 0.3):
		# RANGE ADJUST
		a = 100 - beginRange
		b = 100 - endRange
	
		beginAtt = (a * numNodes) / 100
		endAtt = (b * numNodes) / 100

		# FINAL POSITIONS OF RANGE ON DICTIONARY
		beginAtt = numNodes - beginAtt
		endAtt = numNodes - endAtt
	
		while (beginAtt <= endAtt):
			att[att.keys()[beginAtt]] = 1
			beginAtt = beginAtt + 1
		
		#for k, v in att.items():
			#print("Key : {0}, Value : {1}".format(k, v))

	if (p == 0.2):
		# RANGE ADJUST
		a = 100 - beginRange
		b = 100 - (endRange - 10)
	
		beginAtt = (a * numNodes) / 100
		endAtt = (b * numNodes) / 100

		# FINAL POSITIONS OF RANGE ON DICTIONARY
		beginAtt = numNodes - beginAtt
		endAtt = numNodes - endAtt
	
		while (beginAtt <= endAtt):
			att[att.keys()[beginAtt]] = 1
			beginAtt = beginAtt + 1
		
		#for k, v in att.items():
			#print("Key : {0}, Value : {1}".format(k, v))


	if (p == 0.1):
		# RANGE ADJUST
		a = 100 - beginRange
		b = 100 - (endRange - 20)
	
		beginAtt = (a * numNodes) / 100
		endAtt = (b * numNodes) / 100

		# FINAL POSITIONS OF RANGE ON DICTIONARY
		beginAtt = numNodes - beginAtt
		endAtt = numNodes - endAtt
	
		while (beginAtt <= endAtt):
			att[att.keys()[beginAtt]] = 1
			beginAtt = beginAtt + 1
		
		#for k, v in att.items():
			#print("Key : {0}, Value : {1}".format(k, v))



	if (p == 0.05):
		# RANGE ADJUST
		a = 100 - beginRange
		b = 100 - (endRange - 25)
	
		beginAtt = (a * numNodes) / 100
		endAtt = (b * numNodes) / 100

		# FINAL POSITIONS OF RANGE ON DICTIONARY
		beginAtt = numNodes - beginAtt
		endAtt = numNodes - endAtt
	
		while (beginAtt <= endAtt):
			att[att.keys()[beginAtt]] = 1
			beginAtt = beginAtt + 1
		
		#for k, v in att.items():
			#print("Key : {0}, Value : {1}".format(k, v))

	
	nx.set_node_attributes(g, att, 'attr')
	nx.write_edgelist(g, outFileName+".elist.txt", data=['attr'])
	
	
	#att = nx.get_node_attributes(g, 'attr')
	#for k, v in att.items():
	#	print("Key : {0}, Value : {1}".format(k, v))	
	
	measure_MI(g)
Пример #12
0
    def wl_normalization(self, graph):

        result = {}

        labeled_graph = nx.Graph(graph)

        relabel_dict_ = {}
        graph_node_list = list(graph.nodes())
        for i in range(len(graph_node_list)):
            relabel_dict_[graph_node_list[i]] = i
            i += 1

        inv_relabel_dict_ = {v: k for k, v in relabel_dict_.items()}

        graph_relabel = nx.relabel_nodes(graph, relabel_dict_)

        label_lookup = {}
        label_counter = 0

        l_aux = list(
            nx.get_node_attributes(graph_relabel, 'attr_name').values())
        labels = np.zeros(len(l_aux), dtype=np.int32)
        adjency_list = list([
            list(x[1].keys()) for x in graph_relabel.adjacency()
        ])  #adjency list à l'ancienne comme version 1.0 de networkx

        for j in range(len(l_aux)):
            if not (l_aux[j] in label_lookup):
                label_lookup[l_aux[j]] = label_counter
                labels[j] = label_counter
                label_counter += 1
            else:
                labels[j] = label_lookup[l_aux[j]]
            # labels are associated to a natural number
            # starting with 0.

        new_labels = copy.deepcopy(labels)

        # create an empty lookup table
        label_lookup = {}
        label_counter = 0

        for v in range(len(adjency_list)):
            # form a multiset label of the node v of the i'th graph
            # and convert it to a string

            long_label = np.concatenate(
                (np.array([labels[v]]), np.sort(labels[adjency_list[v]])))
            long_label_string = str(long_label)
            # if the multiset label has not yet occurred, add it to the
            # lookup table and assign a number to it
            if not (long_label_string in label_lookup):
                label_lookup[long_label_string] = label_counter
                new_labels[v] = label_counter
                label_counter += 1
            else:
                new_labels[v] = label_lookup[long_label_string]
        # fill the column for i'th graph in phi
        labels = copy.deepcopy(new_labels)

        dict_ = {inv_relabel_dict_[i]: labels[i] for i in range(len(labels))}

        nx.set_node_attributes(labeled_graph, dict_, 'labeling')

        result['labeled_graph'] = labeled_graph
        result['ordered_nodes'] = [
            x[0] for x in sorted(dict_.items(), key=lambda x: x[1])
        ]

        return result