Exemplo n.º 1
0
                def candidates():
                    for node in nodes:
#                            print "node is {}\n".format(node)
                            #node, say, ((0, 3),"face")

                            if list(nx.non_neighbors(component, node)) != []:
                             for each_non_neighbor in nx.non_neighbors(component, node):

                                candidate_nodes = [node]
                                



                                if each_non_neighbor[0][0] == node[0][1]:
#                                    print "each_non_neighbor is {}\n".format(each_non_neighbor)
                                #boo is one of the non_neighbors of "face"
                                    candidate_nodes.append(search(component, [each_non_neighbor], each_non_neighbor, flag=''))
                                #booking, no further non_neighbors, so will return a node itself
                                #boo, has two non_neighbors -- "king" and "girl", will return the 
                                yield candidate_nodes
                                #yield (score, [list of nodes])
                            else:
#                                print "NO NEIGHBOR WORD\n"
                                candidate_nodes = [node]
                                yield candidate_nodes
Exemplo n.º 2
0
    def test_non_neighbors(self):
        graph = nx.complete_graph(100)
        pop = random.sample(list(graph), 1)
        nbors = list(nx.non_neighbors(graph, pop[0]))
        # should be all the other vertices in the graph
        assert_equal(len(nbors), 0)

        graph = nx.path_graph(100)
        node = random.sample(list(graph), 1)[0]
        nbors = list(nx.non_neighbors(graph, node))
        # should be all the other vertices in the graph
        if node != 0 and node != 99:
            assert_equal(len(nbors), 97)
        else:
            assert_equal(len(nbors), 98)

        # create a star graph with 99 outer nodes
        graph = nx.star_graph(99)
        nbors = list(nx.non_neighbors(graph, 0))
        assert_equal(len(nbors), 0)

        # disconnected graph
        graph = nx.Graph()
        graph.add_nodes_from(range(10))
        nbors = list(nx.non_neighbors(graph, 0))
        assert_equal(len(nbors), 9)
def nuevo_enlace2(i): #Se selecciona un nodo y se le conecta a otro cercano. Se perturba la posición del primero.
    
    global g, delta_omega, b, delta_c
    
    max_intentos = 1000
    exito = False
    
    n_nodes = len(g.nodes())
    n_enlaces = len(g.edges())
    max_enalces = 0.5 * n_nodes * (n_nodes - 1.0)
    x0=g.node[i]['x']
    y0=g.node[i]['y']    
    
    next_neighbors=[] #J:  primero busco los 2º vecinos
    for ii in nx.neighbors(g,i):
        for nnb in nx.neighbors(g,ii):
            #print('i=',i,'ii=',ii)
            next_neighbors.append(nnb)  #J: Solo consideramos enlaces con los 2º vecinos
            #print('next_neigh=',next_neighbors)
            
    
    if (n_enlaces < max_enalces) and (len(next_neighbors)>0):
        
        #neighbs = nx.neighbors(g,i)
        intentos = 0 
        while (exito != True) and (intentos<max_intentos):
            intentos += 1 #J: Hay que dejar siempre una vía de escape en los while
            #i = rd.choice(g.nodes()) #El agente se elige en el update2()

            #rad = pareto.rvs(b, size=1) #Generate random numbers form a pareto density distribution b/(x^(1+b))
            #rad = rad[0] #El comando anterior genera una lista con 1 elemento, que extraemos aquí
	    rad=rad0 # QUITAMOS vecindad con distribución de Pareto. Ahora es FIJA. JMP 19/01/18

            #candidates0 = [nb for nb in g.nodes() if ( ((g.node[nb]['x']-x0)**2 + (g.node[nb]['y']-y0)**2) < rad**2) and (nb != i) ]
            candidates0 = [nb for nb in next_neighbors if ( ((g.node[nb]['x']-x0)**2 + (g.node[nb]['y']-y0)**2) < rad**2) and (nb != i) ]
            
            candidates = [nb for nb in candidates0 if (nb in nx.non_neighbors(g,i))] #J: antes de elegir vecino comprueba que no tiene enlace
            n_candidates = len(candidates)  #se limita por los de su especie y la otra
            #print('i:',i,'n_candidates= ',n_candidates)

            if n_candidates > 0:

                j=rd.choice(candidates)

                if j in nx.non_neighbors(g,i): #nx.non_neighbors(g,i) proporciona la lista de no-vecinos de i
                    g.add_edge(i, j)
                    exito = True
                    
            #angulo = rd.random()*2*math.pi
            #modulo = rd.random()*delta_c
            #g.node[i]['x'] += modulo*np.cos(angulo)
            #g.node[i]['y'] += modulo*np.sin(angulo)
            
        return i #devuelve el valor del nodo al que se ha conectado el nodo recien creado
                    
    else: #Si el grafo es completo, añadimos un nuevo nodo
        
        #i = rd.choice(g.nodes()) #J: Si no puede añadir enlace VUELVE
        #nuevo_nodo2(i)
        return i
Exemplo n.º 4
0
def populate_query_set(gr,query_nodes): 
  G = gr.get_nx_graph()
  #remove nodes from their own neighbourhood set
  G.remove_edges_from(nx.selfloop_edges(G))

  #code to limit non-edge set to 2-path reachable nodes
  G_adj_mat = nx.to_numpy_matrix(G)
  #A^2+A has non-zero entries for 1-len and 2-len reachable nodes for adjacency matrix A
  G_mod = nx.from_numpy_matrix(G_adj_mat*G_adj_mat + G_adj_mat)

  query_full_set = {}
  for q_node in query_nodes:
    query_full_set[q_node] = {}
    query_full_set[q_node]['Nbr']    = list(nx.neighbors(G,q_node))
    query_full_set[q_node]['NonNbr'] =  list(set(nx.non_neighbors(G,q_node))\
                                             -set(nx.non_neighbors(G_mod,q_node)))

  #assert 'Nbr' and 'NonNbr' for all q_nodes are complements wrt 2-len neighbourhood and neither contain q_node  
  assert( all([ \
            (set(query_full_set[q_node]['Nbr']).intersection(query_full_set[q_node]['NonNbr']) == set() ) \
                and (len(query_full_set[q_node]['Nbr']) + len(query_full_set[q_node]['NonNbr'])==len(list(nx.neighbors(G_mod,q_node)))-1) \
                and (q_node not in set(query_full_set[q_node]['Nbr']).union(query_full_set[q_node]['NonNbr'])) \
                    for q_node in query_nodes]) \
            ==True)
  return query_full_set  
Exemplo n.º 5
0
    def test_non_neighbors(self):
        graph = nx.complete_graph(100)
        pop = random.sample(list(graph), 1)
        nbors = list(nx.non_neighbors(graph, pop[0]))
        # should be all the other vertices in the graph
        assert_equal(len(nbors), 0)

        graph = nx.path_graph(100)
        node = random.sample(list(graph), 1)[0]
        nbors = list(nx.non_neighbors(graph, node))
        # should be all the other vertices in the graph
        if node != 0 and node != 99:
            assert_equal(len(nbors), 97)
        else:
            assert_equal(len(nbors), 98)

        # create a star graph with 99 outer nodes
        graph = nx.star_graph(99)
        nbors = list(nx.non_neighbors(graph, 0))
        assert_equal(len(nbors), 0)

        # disconnected graph
        graph = nx.Graph()
        graph.add_nodes_from(range(10))
        nbors = list(nx.non_neighbors(graph, 0))
        assert_equal(len(nbors), 9)
Exemplo n.º 6
0
                def candidates():
                    for node in nodes:
                        #                        print "working on node: {}".format(node)
                        if list(nx.non_neighbors(component, node)) != []:
                            for each_non_neighbor in nx.non_neighbors(component, node):
                                candidate_nodes = [node]
                                #                                print "candidate_nodes are {}".format(candidate_nodes)
                                #                                print "and the each_non_neighbor is {}".format(each_non_neighbor)
                                if each_non_neighbor[0][0] == node[0][1]:
                                    #                                    print "position adhered each_non_neighbor found: {0} of node {1}\n".format(each_non_neighbor,node)
                                    candidate_nodes.append(
                                        search(
                                            component,
                                            nodes=[each_non_neighbor],  # DP remembers this list
                                            node=each_non_neighbor,
                                            flag="",
                                        )
                                    )

                                yield candidate_nodes

                        else:
                            # NO NEIGHBOR WORD
                            candidate_nodes = [node]
                            yield candidate_nodes
            def search(component, nodes=nodes, node=nodes[0], flag='init'):
                if not nx.non_neighbors(component, node) and flag != 'init':
#                    print "no neighbor found for node: {}".format([node])
                    return node

                elif nx.non_neighbors(component, node) and flag != 'init':
                    #only look at word forwad
                    flag = "HASNOT"
                    for each in nx.non_neighbors(component, node):

                        if each[0][0] > node[0][0]:
                            #if non_neighbor has forward neighbors
                            #keep the flag
                            flag = "HAS"
                            break
                        else:
                            #all non_neighbors are in front of the node
                            pass

                    if flag == "HASNOT":
#                        print "no forward neighbor folloing node: {}".format([node])
                        #means no forward neighbor found
                        return node
                    else:
                        #means it has non_neighbor following it
                        pass

                def candidates():
                    for node in nodes:
#                        print "working on node: {}".format(node)
                        if list(nx.non_neighbors(component, node)) != []:
                            for each_non_neighbor in nx.non_neighbors(component, node):
                                candidate_nodes = [node]
#                                print "candidate_nodes are {}".format(candidate_nodes)
#                                print "and the each_non_neighbor is {}".format(each_non_neighbor)
                                if each_non_neighbor[0][0] == node[0][1]:
#                                    print "position adhered each_non_neighbor found: {0} of node {1}\n".format(each_non_neighbor,node)
                                    candidate_nodes.append(
                                        search(
                                            component, nodes=[each_non_neighbor],    #DP remembers this list
                                            node=each_non_neighbor, flag=''
                                            )
                                        )

                                yield candidate_nodes

                        else:
                            #NO NEIGHBOR WORD
                            candidate_nodes = [node]
                            yield candidate_nodes

                tmp_lst = list(candidates())
                
                s = []
                for i in tmp_lst:
                    if i not in s:
                        s.append(i)

                return s
Exemplo n.º 8
0
            def search(component, nodes=nodes, node=nodes[0], flag='init'):
                if not nx.non_neighbors(component, node) and flag != 'init':
                    print "no neighbor returned: {}".format([node])
                    return node
                elif nx.non_neighbors(component, node) and flag != 'init':
                    #only look at word forwad
                    flag = "HASNOT"
                    for each in nx.non_neighbors(component, node):

                        if each[0][0] > node[0][0]:
                            #if non_neighbor has forward neighbors
                            #keep the flag
                            flag = "HAS"
                            break
                        else:
                            #all non_neighbors are in front of the node
                            pass

                    if flag == "HASNOT":
                        print "no forward neighbor returned: {}".format([node])
                        return node
                    else:
                        #means it has non_neighbor following it
                        pass

                def candidates():
                    for node in nodes:
                        print "node is {}\n".format(node)
                        #node, say, ((0, 3),"face")

                        if list(nx.non_neighbors(component, node)) != []:
                            for each_non_neighbor in nx.non_neighbors(
                                    component, node):
                                candidate_nodes = [node]

                                if each_non_neighbor[0][0] > node[0][0]:
                                    print "each_non_neighbor is {}\n".format(
                                        each_non_neighbor)
                                    #boo is one of the non_neighbors of "face"
                                    candidate_nodes.append(
                                        search(component, [each_non_neighbor],
                                               each_non_neighbor,
                                               flag=''))
                                #booking, no further non_neighbors, so will return a node itself
                                #boo, has two non_neighbors -- "king" and "girl", will return the
                                yield candidate_nodes
                                #yield (score, [list of nodes])
                        else:
                            print "HHHHEEEERRRREEEE\n"
                            candidate_nodes = [node]
                            yield candidate_nodes

                return list(candidates())
Exemplo n.º 9
0
def results():
    sPageTitle = 'Results page - MyWeddingSeatingPlanner.com'
    sDescription = 'Your seating plan for your wedding as generated by us.'
    objMeta = {
        'googlebot': 'index,follow,snippet,archive',
        'description': sDescription,
        'keywords': 'seating plans, wedding, guests, seats',
        'publisher': 'BahamSoft Ltd',
        'og:title': sPageTitle,
        'og:description': sDescription
    }
    # numguests = int(session['config']['numguest'])
    num_tables = int(session['config']['numtables'])
    table_capacity = int(session['config']['numguestspertable'])
    min_known_neighbors = 1
    # min_known_neighbors = int(session['config']['minguestpertable'])
    names = [i['name'] for i in session['guestlist']]

    # ensure that nodes with the same acquintance are connected with weight 1
    # this operation should happen just before passing the graph to the final computation
    acqlookup = {guest['id']: guest['acq'] for guest in session['guestlist']}

    for node in session['graph'].nodes():
        #print('node %s is in the graph acq is %s' % (node, acqlookup[node]))
        for i in nx.non_neighbors(session['graph'], node):
            #print('acq of node %d is %s vs acq of node %d is %s' % (node, acqlookup[node], i, acqlookup[i]))
            if acqlookup[node] and acqlookup[node] == acqlookup[i]:
                session['graph'].add_edge(node, i, weight=1)

    # check the network connectivity, if it equal to 0 it means that the customer didn't specify
    # any guest acquintance, so we randomly connect the nodes for the solver to work correctly
    if session['graph'].number_of_edges() == session['graph'].number_of_nodes():
        # we need to randomly assign weight to nodes
        print('randomly assigning weights as there are not enough edges')
        for node in session['graph'].nodes():
            for i in nx.non_neighbors(session['graph'], node):
                session['graph'].add_edge(node, i, weight=random.choice([0, 1, 50]))

    C = nx.adjacency_matrix(session['graph'],
                            nodelist=range(1, session['graph'].number_of_nodes() + 1)).todense().tolist()
    #print('matrix: ', C)
    solution = WeddingChartPrinter.solve_with_discrete_model(num_tables, table_capacity, min_known_neighbors, C, names)
    solutionrow = SeatingPlan(session['user_id'], solution, session)
    db.session.add(solutionrow)
    db.session.commit()

    # stripe payment data
    stripejs, stripeobj = StripeWrapper.generatePaymentData(session['user_id'], stripekey, request.url_root)
    sol = dict(list(solution.items())[:len(solution)//2])
    return render_template('results.html', meta=objMeta,
                           title=sPageTitle, seating=sol, extrajs=stripejs, stripeobj=stripeobj)
Exemplo n.º 10
0
def ramsey_R2(graph):
    r"""Approximately computes the Ramsey number `R(2;s,t)` for graph.

    Parameters
    ----------
    graph : NetworkX graph
        Undirected graph

    Returns
    -------
    max_pair : (set, set) tuple
        Maximum clique, Maximum independent set.
    """
    if not graph:
        return (set([]), set([]))

    node = next(graph.nodes_iter())
    nbrs = nx.all_neighbors(graph, node)
    nnbrs = nx.non_neighbors(graph, node)
    c_1, i_1 = ramsey_R2(graph.subgraph(nbrs))
    c_2, i_2 = ramsey_R2(graph.subgraph(nnbrs))

    c_1.add(node)
    i_2.add(node)
    return (max([c_1, c_2]), max([i_1, i_2]))
Exemplo n.º 11
0
def ramsey_R2(G):
    r"""Compute the largest clique and largest independent set in `G`.

    This can be used to estimate bounds for the 2-color
    Ramsey number `R(2;s,t)` for `G`.

    This is a recursive implementation which could run into trouble
    for large recursions. Note that self-loop edges are ignored.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    max_pair : (set, set) tuple
        Maximum clique, Maximum independent set.
    """
    if not G:
        return set(), set()

    node = arbitrary_element(G)
    nbrs = (nbr for nbr in nx.all_neighbors(G, node) if nbr != node)
    nnbrs = nx.non_neighbors(G, node)
    c_1, i_1 = ramsey_R2(G.subgraph(nbrs).copy())
    c_2, i_2 = ramsey_R2(G.subgraph(nnbrs).copy())

    c_1.add(node)
    i_2.add(node)
    # Choose the larger of the two cliques and the larger of the two
    # independent sets, according to cardinality.
    return max(c_1, c_2, key=len), max(i_1, i_2, key=len)
Exemplo n.º 12
0
def calculate_probabilities(graph, mode='undirected unweighted') :
	probabilities_to_add_edge = defaultdict(dict)
	number_of_shortest_paths = {}
	if mode == 'directed':
		shortest_path_lengths = dict(nx.all_pairs_shortest_path_length(graph))
		for node in graph.nodes() :
			number_of_shortest_paths[node] = BFS_With_Shortest_Paths(graph, node)[2]
	for node in graph.nodes() :
		for second_node in nx.non_neighbors(graph, node):
			if mode == 'undirected unweighted' :
				coomon_neighbors_size = len(list(nx.common_neighbors(graph, node, second_node)))
				probabilities_to_add_edge[node][second_node] = 1 - pow(float(0.97), coomon_neighbors_size)
			elif mode == 'undirected weighted' :
				m = 0
				n = 0
				for neighbor in nx.common_neighbors(graph, node, second_node) :
					if graph[node][neighbor]['weight'] == 'strong' :
						m += 1
					else:
						n += 1
				probabilities_to_add_edge[node][second_node] = 1 - (pow(float(0.96), m) * pow(float(0.98),n))
			elif mode == 'directed':
				if second_node in shortest_path_lengths[node]:
					L = shortest_path_lengths[node][second_node]
					if L <= 4:
						M = number_of_shortest_paths[node][second_node]
						probabilities_to_add_edge[node][second_node] = min(1, M / (math.pow(5, L)))
	return probabilities_to_add_edge
Exemplo n.º 13
0
def khren(G):

    result_s = []
    result_d = []
    passed_set = []

    list_neighbrs = {}

    for v in G.nodes:
        list_neighbrs.update({v: set(nx.neighbors(G, v))})

    for u in G.nodes:
        passed_set.append(u)
        for v in nx.non_neighbors(G, u):
            if not v in passed_set:
                cmn_nmbr = len(list_neighbrs[u] & list_neighbrs[v])
                # dist = nx.shortest_path_length(G,u,v)
                # if dist == 2:
                # cmn_nmbr = G.distance(u,v)
                if G.nodes[u]["ground_label"] == G.nodes[v]['ground_label']:
                    result_s.append(cmn_nmbr)
                else:
                    result_d.append(cmn_nmbr)

    max_s = max(result_s)
    max_d = max(result_d)

    print(max_s, max_d)

    return (result_s, result_d)
Exemplo n.º 14
0
def ramsey_R2(G):
    r"""Approximately computes the Ramsey number `R(2;s,t)` for graph.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    max_pair : (set, set) tuple
        Maximum clique, Maximum independent set.
    """
    if not G:
        return set(), set()

    node = arbitrary_element(G)
    nbrs = nx.all_neighbors(G, node)
    nnbrs = nx.non_neighbors(G, node)
    c_1, i_1 = ramsey_R2(G.subgraph(nbrs))
    c_2, i_2 = ramsey_R2(G.subgraph(nnbrs))

    c_1.add(node)
    i_2.add(node)
    # Choose the larger of the two cliques and the larger of the two
    # independent sets, according to cardinality.
    return max(c_1, c_2, key=len), max(i_1, i_2, key=len)
Exemplo n.º 15
0
    def has_missing_edges(self, threshold: float = 0.0) -> int:
        """
        Returns the maximal number of missing edges in the model according to the collected interventional
        data. The maximum number is returned because the exact number cannot be determined with an intervention
        on a single variable.

        :param threshold:
        :return:

        Example
        ---------
        Let the ground truth causal model be A -> B -> C and the causal model of the agent A   B -> C (missing
        edge between A and B). This method will return 2. This is because the edge between A and B induces an indirect
        effect of A on C which cannot be distilled from a direct effect that could be present from A to C.

        The collected interventional data with the intervention only on one variable cannot distinguish between
        A -> B -> C and A -> B -> C, hence a maximum of 2 edges are missing.
                        |         ^
                        - - - - - |
        Important: Once there is any path from A to C, no edge is considered to be missing.
        e.g. applied to the model A -> B -> C this method returns 0
        e.g. applied to the model A -> C <- B this method returns 1 as the edge A -> B is missing.

        """
        missing_edges = 0
        # check which causal relationships are missing in the graph
        for n in self.causal_model.nodes:
            # iterate over all nodes that do not already have an edge from n
            for nn in nx.non_neighbors(self.causal_model, n):
                current_edge = (str(n), str(nn))
                if self.edge_is_missing(current_edge, threshold):
                    missing_edges += 1
        
        return missing_edges
Exemplo n.º 16
0
def rewire(M,p):
    R = nx.Graph(M)
    rewireSet = [i for i in nx.edges_iter(R) if random.random() < p]
    R.remove_edges_from(rewireSet)
    for i in rewireSet:
        R.add_edge(i[0],random.sample([k for k in nx.non_neighbors(R,i[0])],1)[0])
    return R
Exemplo n.º 17
0
def ramsey_R2(G):
    r"""Approximately computes the Ramsey number `R(2;s,t)` for graph.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    max_pair : (set, set) tuple
        Maximum clique, Maximum independent set.
    """
    if not G:
        return (set([]), set([]))

    node = next(G.nodes_iter())
    nbrs = nx.all_neighbors(G, node)
    nnbrs = nx.non_neighbors(G, node)
    c_1, i_1 = ramsey_R2(G.subgraph(nbrs))
    c_2, i_2 = ramsey_R2(G.subgraph(nnbrs))

    c_1.add(node)
    i_2.add(node)
    return (max([c_1, c_2]), max([i_1, i_2]))
Exemplo n.º 18
0
    def __genGwMesh(self):
        """Generates the multiple domains GW mesh
        
        :return: networkx instance"""

        # Calc number of mesh links
        gwMesh = nx.cycle_graph(self.__domains)
        _ = self.__getNextIds(self.__domains)
        possibleLinks = itertools.combinations(range(self.__domains), 2)
        possibleLinks = len(list(possibleLinks)) - self.__domains
        numLinks = math.floor(self.__meshDegree * possibleLinks)

        # Add randomly mesh links
        linked, i = 0, 0
        random.seed(datetime.now())
        while linked < numLinks:
            candidates = list(nx.non_neighbors(gwMesh, i))
            if len(candidates) > 0:
                candid = random.randint(0, len(candidates) - 1)
                gwMesh.add_edge(i,
                                candidates[candid],
                                res=self.__genMeshLnkRes(),
                                meshLink='True')
                linked += 1
            i = (i + 1) % self.__domains

        # Add mesh attribute to original cycle edges
        if self.__domains > 1:  # Possible to have only have 1 domain
            for gw in range(self.__domains):
                nextGw = 0 if gw == self.__domains - 1 else gw + 1
                gwMesh[gw][nextGw]['meshLink'] = 'True'
                gwMesh[gw][nextGw]['res'] = self.__genMeshLnkRes()

        return gwMesh
Exemplo n.º 19
0
def connect_leafs(G, leafs):
    """Some graph generators make nodes with no neighbors. This fixes that."""
    random.seed(
        1
    )  # This is a side application, so I'm okay using different seed than generator
    for leaf in leafs:
        G.add_edge(leaf, random.choice(list(nx.non_neighbors(G, leaf))))
Exemplo n.º 20
0
def ramsey_R2(G):
    """Approximately computes the Ramsey number `R(2;s,t)` for graph.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    max_pair : (set, set) tuple
        Maximum clique, Maximum independent set.
    """
    if not G:
        return set(), set()

    node = arbitrary_element(G)
    nbrs = set(nx.all_neighbors(G, node))
    nbrs.discard(node)
    nnbrs = nx.non_neighbors(G, node)
    c_1, i_1 = ramsey_R2(G.subgraph(nbrs).copy())
    c_2, i_2 = ramsey_R2(G.subgraph(nnbrs).copy())

    c_1.add(node)
    i_2.add(node)
    # Choose the larger of the two cliques and the larger of the two
    # independent sets, according to cardinality.
    return max(c_1, c_2, key=len), max(i_1, i_2, key=len)
Exemplo n.º 21
0
def get_balance_coefficient(nx_G, X):
    cos_sims = cosine_similarity(X, X)
    print("Similarity Computing Finished!")
    rate = 0

    isolate_count = 0

    for node in nx_G.nodes():
        neis = list(nx.neighbors(nx_G, node))
        neis_of_neis = []
        for nei in neis:
            neis_of_neis.extend(list(nx.neighbors(nx_G, nei)))
        neis.extend(neis_of_neis)

        neis = list(set(neis))

        neis_sims = cos_sims[node, neis]
        if len(neis_sims) == 0:
            isolate_count = isolate_count + 1
            continue
        avg_of_nei_sims = np.min(neis_sims)
        #avg_of_nei_sims = neis_sims.median()

        non_neis = set(nx.non_neighbors(nx_G, node))
        non_neis = non_neis - set(neis_of_neis)

        non_neis = list(non_neis)
        non_neis_sims = cos_sims[node, non_neis]
        abnormals = np.where(non_neis_sims > avg_of_nei_sims)[0]

        num_of_abnormals = abnormals.shape[0]
        num_of_neis = len(neis)

        rate += num_of_abnormals / len(non_neis)
    return rate / (len(nx_G.nodes()) - isolate_count)
Exemplo n.º 22
0
def gen_test_edge_wrt_changes(graph_t0, graph_t1, seed=None):
    ''' input: two networkx graphs
        generate **changed** testing edges for link prediction task
        currently, we only consider pos_neg_ratio = 1.0
        return: pos_edges_with_label [(node1, node2, 1), (), ...]
                neg_edges_with_label [(node3, node4, 0), (), ...]
    '''
    G0 = graph_t0.copy()
    G1 = graph_t1.copy(
    )  # use copy to avoid problem caused by G1.remove_node(node)
    edge_add = edge_s1_minus_s0(s1=set(G1.edges()), s0=set(G0.edges()))
    edge_del = edge_s1_minus_s0(s1=set(G0.edges()), s0=set(G1.edges()))

    unseen_nodes = set(G1.nodes()) - set(G0.nodes())
    for node in unseen_nodes:  # to avoid unseen nodes while testing
        G1.remove_node(node)

    edge_add_unseen_node = []  # to avoid unseen nodes while testing
    #print('len(edge_add)', len(edge_add))
    for node in unseen_nodes:
        for edge in edge_add:
            if node in edge:
                edge_add_unseen_node.append(edge)
    edge_add = edge_add - set(edge_add_unseen_node)
    #print('len(edge_add)', len(edge_add))

    neg_edges_with_label = [list(item + (0, )) for item in edge_del]
    pos_edges_with_label = [list(item + (1, )) for item in edge_add]

    random.seed(seed)
    all_nodes = list(G0.nodes())

    if len(edge_add) > len(edge_del):
        num = len(edge_add) - len(edge_del)
        start_nodes = np.random.choice(all_nodes, num, replace=True)
        i = 0
        for start_node in start_nodes:
            non_nbrs = list(nx.non_neighbors(G0, start_node))
            non_nbr = random.sample(non_nbrs, 1).pop()
            non_edge = (start_node, non_nbr)
            if non_edge not in edge_del:
                neg_edges_with_label.append(list(non_edge + (0, )))
                i += 1
            if i >= num:
                break
    elif len(edge_add) < len(edge_del):
        num = len(edge_del) - len(edge_add)
        i = 0
        for edge in nx.edges(G1):
            if edge not in edge_add:
                pos_edges_with_label.append(list(edge + (1, )))
                i += 1
            if i >= num:
                break
    else:  # len(edge_add) == len(edge_del)
        pass
    print('---- len(pos_edges_with_label), len(neg_edges_with_label)',
          len(pos_edges_with_label), len(neg_edges_with_label))
    return pos_edges_with_label, neg_edges_with_label
Exemplo n.º 23
0
def add_and_remove_edges(G,
                         p_new_connection,
                         p_remove_connection,
                         num_add=10,
                         num_remove=10):
    '''
    for each node,
      add a new connection to random other node, with prob p_new_connection,
      remove a connection, with prob p_remove_connection

    operates on G in-place
    '''
    new_edges = []
    rem_edges = []
    count_rm = 0
    count_add = 0
    for node in G.nodes():
        # find the other nodes this one is connected to
        # connected = [to for (fr, to) in G.edges(node)]
        connected = G.neighbors(node)
        # and find the remainder of nodes, which are candidates for new edges
        # unconnected = [n for n in G.nodes() if not n in connected]
        unconnected = [n for n in nx.non_neighbors(G, node)]

        # probabilistically add a random edge
        if len(unconnected
               ) and count_add <= num_add:  # only try if new edge is possible
            if random.random() < p_new_connection:
                count_add += 1
                new = random.choice(unconnected)
                G.add_edge(node, new)
                new_edges.append((node, new))
                # book-keeping, in case both add and remove done in same cycle
                # unconnected.remove(new)
                # connected.append(new)
                if count_add % 1000 == 0:
                    print("\t{0}-th new edge:\t {1} -- {2}".format(
                        count_add, node, new))

        # probabilistically remove a random edge
        if len(
                connected
        ) and count_rm <= num_remove:  # only try if an edge exists to remove
            if random.random() < p_remove_connection:
                count_rm += 1
                remove = random.choice(connected)
                G.remove_edge(node, remove)
                rem_edges.append((node, remove))
                # book-keeping, in case lists are important later?
                # connected.remove(remove)
                # unconnected.append(remove)

                if count_rm % 1000 == 0:
                    print("\t{0}-th edge removed:\t {1} -- {2}".format(
                        count_rm, node, remove))

        if count_rm > num_remove and count_add > num_add:
            break
    return rem_edges, new_edges
Exemplo n.º 24
0
def rewire(M, p):
    R = nx.Graph(M)
    rewireSet = [i for i in nx.edges_iter(R) if random.random() < p]
    R.remove_edges_from(rewireSet)
    for i in rewireSet:
        R.add_edge(i[0],
                   random.sample([k for k in nx.non_neighbors(R, i[0])], 1)[0])
    return R
Exemplo n.º 25
0
def scramble(M,p):
    R = nx.Graph(M)
    removeSet = [i for i in nx.edges_iter(R) if random.random() < p]
    R.remove_edges_from(removeSet)
    nodes = R.nodes()
    addFromNodes = [random.sample(nodes,1)[0] for i in removeSet]
    for node in addFromNodes:
        R.add_edge(node,random.sample([k for k in nx.non_neighbors(R,node)],1)[0])
    return R
Exemplo n.º 26
0
def get_set_complementary_neighborhood(G, A):
    compl_neighborhood = []
    for set_node in A:
        compl_neighborhood.append(list(nx.non_neighbors(G, set_node)))
    if not compl_neighborhood:
        return []
    else:
        intersection = set.intersection(*map(set, compl_neighborhood))
        return list(intersection)
Exemplo n.º 27
0
def processGraph(G, nx, num, max_r):
    nnei = []
    nei = []
    for i in nx.non_neighbors(G, 0):
        nnei.append(i)

    tobrk = False
    while nnei:
        for l in range(0, num):
            if tobrk:
                tobrk = False
                break
            nodes = G.nodes(data=True)
            for i in nx.all_neighbors(G, l):
                nei.append(i)  #neighbors of l
            for i in nx.non_neighbors(G, l):
                nnei.append(i)  # non-neighbors of l

            for t in nei:
                for i in nx.all_neighbors(G, t):
                    nei.append(i)
                    nei = list(set(nei))
            nnei = list(set(nnei) - set(nei))  ## these are unconnected
            ##Generate random positions and calculate them again
            for i in nnei:
                for e in G.edges():
                    if i in e:
                        G.remove_edge(*e)
                G.add_node(
                    i,
                    {'pos': [randint(0, max_x * max_r) for l in range(0, 2)]})
                nodes = G.nodes(data=True)
                u, du = nodes[i]
                pu = du['pos']
                for v, dv in nodes:
                    pv = dv['pos']
                    d = sum(
                        ((int(a) - int(b))**2 for a, b in zip(pu, pv)))**(0.5)
                    if int(d) <= int(max_r) and int(
                            d) > 5:  ## to not be on the same position
                        G.add_edge(u, v)
            tobrk = True
            ##should break to the while so it will revise the network
    return G
Exemplo n.º 28
0
def scramble(M, p):
    R = nx.Graph(M)
    removeSet = [i for i in nx.edges_iter(R) if random.random() < p]
    R.remove_edges_from(removeSet)
    nodes = R.nodes()
    addFromNodes = [random.sample(nodes, 1)[0] for i in removeSet]
    for node in addFromNodes:
        R.add_edge(node,
                   random.sample([k for k in nx.non_neighbors(R, node)], 1)[0])
    return R
Exemplo n.º 29
0
def ramsey2(G):

    if len(list(G.nodes())) == 0:
        return (nx.Graph(), nx.Graph())
    else:
        nodes = list(G.nodes())
        v = nodes[random.randint(0, len(nodes) - 1)]

        # all_neighbors = copy.deepcopy(G)
        # non_neighbors = copy.deepcopy(G)

        all_neighbors_list = []
        non_neighbors_list = []

        # for neighbor in nx.all_neighbors(G,v):
        # 	all_neighbors_list.append(neighbor)
        # all_neighbors_list.append(v)

        # for neighbor in nx.non_neighbors(G,v):
        # 	non_neighbors_list.append(neighbor)
        # non_neighbors_list.append(v)

        # Non-neighbor graph
        all_neighbors = G.subgraph(list(nx.all_neighbors(G, v)))
        non_neighbors = G.subgraph(list(nx.non_neighbors(G, v)))

        # print(v)
        # print((list(nx.all_neighbors(G,v)).append(v)))
        # print(all_neighbors.nodes())
        # print(non_neighbors.nodes())
        # print(G.subgraph(list(nx.all_neighbors(G,v))).nodes())
        # print(all_neighbors.nodes())
        # print(list(nx.all_neighbors(G,v)).append(v))
        # Neighbor graph
        # for nonneighbor in nx.non_neighbors(G,v):
        # 	all_neighbors.remove_node(nonneighbor)
        # all_neighbors.remove_node(v)

        c1, i1 = ramsey2(all_neighbors)
        c2, i2 = ramsey2(non_neighbors)

        if len(list(c1.nodes())) + 1 >= len(list(c2.nodes())):
            c1.add_node(v)
            c = copy.deepcopy(c1)
        else:
            c = copy.deepcopy(c2)

        if len(list(i1.nodes())) >= len(list(i2.nodes())) + 1:
            i = copy.deepcopy(i1)
        else:
            i2.add_node(v)
            i = copy.deepcopy(i2)

        return (c, i)
Exemplo n.º 30
0
 def rule_1(self, edge_types):
     any_changed = False
     for x in nx.nodes(self.skeleton):
         for z in nx.non_neighbors(self.skeleton, x):
             for y in nx.common_neighbors(self.skeleton, x, z):
                 if edge_types[(x, y)] != ArrowType.ARROW:
                     continue
                 if edge_types[(z, y)] != ArrowType.CIRCLE:
                     continue
                 edge_types[(z, y)] = ArrowType.NONE
                 edge_types[(y, z)] = ArrowType.ARROW
                 any_changed = True
     return any_changed
Exemplo n.º 31
0
 def pc_rule_1(self, edge_types):
     any_changed = False
     for a in nx.nodes(self.skeleton):
         for c in nx.non_neighbors(self.skeleton, a):
             for b in nx.common_neighbors(self.skeleton, a, c):
                 if edge_types[(a, b)] != ArrowType.ARROW:
                     continue
                 if edge_types[(c, b)] != ArrowType.CIRCLE:
                     continue
                 edge_types[(b, c)] = ArrowType.ARROW
                 edge_types[(c, b)] = ArrowType.NONE
                 any_changed = True
     return any_changed
    def ramsey_R2(graph):
        if not graph:
            return (set([]), set([]))

        node = next(graph.nodes_iter())
        nbrs = nx.all_neighbors(graph, node)
        nnbrs = nx.non_neighbors(graph, node)
        c_1, i_1 = ramsey_R2(graph.subgraph(nbrs))
        c_2, i_2 = ramsey_R2(graph.subgraph(nnbrs))

        c_1.add(node)
        i_2.add(node)
        return (max([c_1, c_2]), max([i_1, i_2]))
 def ramsey_R2(graph):
     if not graph:
         return (set([]), set([]))
 
     node = next(graph.nodes_iter())
     nbrs = nx.all_neighbors(graph, node)
     nnbrs = nx.non_neighbors(graph, node)
     c_1, i_1 = ramsey_R2(graph.subgraph(nbrs))
     c_2, i_2 = ramsey_R2(graph.subgraph(nnbrs))
 
     c_1.add(node)
     i_2.add(node)
     return (max([c_1, c_2]), max([i_1, i_2]))
Exemplo n.º 34
0
def probabilities_for_new_edges(graph) :
	shortest_path_lengths = dict(nx.all_pairs_shortest_path_length(graph))
	number_of_shortest_paths = defaultdict(dict)
	for node in graph.nodes() :
		number_of_shortest_paths[node] = BFS_With_Shortest_Paths(graph, node)[2]
	probabilities_to_add_edge = defaultdict(dict)
	for node in graph.nodes() :
		for second_node in nx.non_neighbors(graph, node):
			if second_node in shortest_path_lengths[node]:
				L = shortest_path_lengths[node][second_node]
				if L <= 4:
					M = number_of_shortest_paths[node][second_node]
					probabilities_to_add_edge[node][second_node] = min(1, (M / (math.pow(10, 1.05 * L))) * get_average_rating_neighbors(graph, node))
	return probabilities_to_add_edge
Exemplo n.º 35
0
                def candidates():
                    for node in nodes:
#                        print "working on node: {}".format(node)
                        if list(nx.non_neighbors(component, node)) != []:
                            for each_non_neighbor in nx.non_neighbors(component, node):
                                candidate_nodes = [node]
#                                print "candidate_nodes are {}".format(candidate_nodes)
#                                print "and the each_non_neighbor is {}".format(each_non_neighbor)
                                if each_non_neighbor[0][0] == node[0][1]:
#                                    print "position adhered each_non_neighbor found: {0} of node {1}\n".format(each_non_neighbor,node)
                                    candidate_nodes.append(
                                        search(
                                            component, nodes=[each_non_neighbor],    #DP remembers this list
                                            node=each_non_neighbor, flag=''
                                            )
                                        )

                                yield candidate_nodes

                        else:
                            #NO NEIGHBOR WORD
                            candidate_nodes = [node]
                            yield candidate_nodes
def ws(n, m, p):
    """
    This function call the ring() function to make a basic ring and then
    rewires each link with  probability p and also prints the total number of
    links and the number of rewired links.
    Note self-loops are not allowed when rewiring (check that you do not rewire
    the end of a link to the node at its other end!)

    Parameters
    ----------
    n : int
      Number of nodes
    m : int
      Number of neighbors to connect left and right
    p : float
        Rewiring probability

    Returns
    -------
    network : graph
        The Watts-Strogatz small-world network

    """
    network = ring(n, m)
    edges = network.edges()
    rewired_num = 0 # tracks the number of rewired links
    total_num = 0 # tracks the total number of links in the network
    for e in edges:
        if np.random.rand() < p:
            i,j = e
            NN=nx.non_neighbors(network,i)
            network.remove_edge(i,j)
            network.add_edge(i,random.choice(list(NN)))
            rewired_num += 1
    total_num = network.number_of_edges()
    # You should rewire each edge if: numpy.random.rand() < p
    # Also, avoid duplicate links (rewiring to a neighbor of the other node)
    # as well as self-links (rewiring one endpoint to the other)
    # You might find these useful: random.choice and nx.non_neighbors
    # The latter yields an iterator: NN=nx.non_neighbors(G,i) lists all nodes
    # that are not connected to i (and are not i)
    # YOUR CODE HERE
    
    #print total number of links in the graph and number of rewired links:
    print("total number of links:")
    print(total_num)
    print("number of rewired links:")
    print(rewired_num)
    return network
Exemplo n.º 37
0
    def ramsey_R2(self, G):
        if not G:
            return set(), set()

        node = self.arbitrary_element(G)
        nbrs = nx.all_neighbors(G, node)
        nnbrs = nx.non_neighbors(G, node)
        c_1, i_1 = self.ramsey_R2(G.subgraph(nbrs).copy())
        c_2, i_2 = self.ramsey_R2(G.subgraph(nnbrs).copy())

        c_1.add(node)
        i_2.add(node)
        # Choose the larger of the two cliques and the larger of the two
        # independent sets, according to cardinality.
        return max(c_1, c_2, key=len), max(i_1, i_2, key=len)
def build_noise_list(agraph):
    """
        Using the adjaceny graph, generate a list of 1000 pairs of non-adjacent images and words.
        This will be added to the learning set to make sure our algorithm can distinguish between
        words and images that should not be close.
    """

    noise_list = []

    for node in nodes(agraph):
        for non_neighbor in nx.non_neighbors(agraph, node):
            if node[type] != non_neight[type]:
                noise_list.append((node, non_neighbor))

            if len(noise_list) >= 1000:
                break

        if len(noise_list) >= 1000:
                break

    return noise_list
Exemplo n.º 39
0
def all_node_cuts(G, k=None, flow_func=None):
    r"""Returns all minimum k cutsets of an undirected graph G. 

    This implementation is based on Kanevsky's algorithm [1]_ for finding all
    minimum-size node cut-sets of an undirected graph G; ie the set (or sets) 
    of nodes of cardinality equal to the node connectivity of G. Thus if 
    removed, would break G into two or more connected components.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    k : Integer
        Node connectivity of the input graph. If k is None, then it is 
        computed. Default value: None.

    flow_func : function
        Function to perform the underlying flow computations. Default value
        edmonds_karp. This function performs better in sparse graphs with
        right tailed degree distributions. shortest_augmenting_path will
        perform better in denser graphs.


    Returns
    -------
    cuts : a generator of node cutsets
        Each node cutset has cardinality equal to the node connectivity of
        the input graph.

    Examples
    --------
    >>> # A two-dimensional grid graph has 4 cutsets of cardinality 2
    >>> G = nx.grid_2d_graph(5, 5)
    >>> cutsets = list(nx.all_node_cuts(G))
    >>> len(cutsets)
    4
    >>> all(2 == len(cutset) for cutset in cutsets)
    True
    >>> nx.node_connectivity(G)
    2

    Notes
    -----
    This implementation is based on the sequential algorithm for finding all
    minimum-size separating vertex sets in a graph [1]_. The main idea is to
    compute minimum cuts using local maximum flow computations among a set 
    of nodes of highest degree and all other non-adjacent nodes in the Graph.
    Once we find a minimum cut, we add an edge between the high degree
    node and the target node of the local maximum flow computation to make 
    sure that we will not find that minimum cut again.

    See also
    --------
    node_connectivity
    edmonds_karp
    shortest_augmenting_path

    References
    ----------
    .. [1]  Kanevsky, A. (1993). Finding all minimum-size separating vertex 
            sets in a graph. Networks 23(6), 533--541.
            http://onlinelibrary.wiley.com/doi/10.1002/net.3230230604/abstract

    """
    if not nx.is_connected(G):
        raise nx.NetworkXError('Input graph is disconnected.')

    # Address some corner cases first.
    # For cycle graphs
    if G.order() == G.size():
        if all(2 == d for n, d in G.degree()):
            seen = set()
            for u in G:
                for v in nx.non_neighbors(G, u):
                    if (u, v) not in seen and (v, u) not in seen:
                        yield {v, u}
                        seen.add((v, u))
            return
    # For complete Graphs
    if nx.density(G) == 1:
        for cut_set in combinations(G, len(G) - 1):
            yield set(cut_set)
        return
    # Initialize data structures.
    # Keep track of the cuts already computed so we do not repeat them.
    seen = []
    # Even-Tarjan reduction is what we call auxiliary digraph
    # for node connectivity.
    H = build_auxiliary_node_connectivity(G)
    mapping = H.graph['mapping']
    R = build_residual_network(H, 'capacity')
    kwargs = dict(capacity='capacity', residual=R)
    # Define default flow function
    if flow_func is None:
        flow_func = default_flow_func
    if flow_func is shortest_augmenting_path:
        kwargs['two_phase'] = True
    # Begin the actual algorithm
    # step 1: Find node connectivity k of G
    if k is None:
        k = nx.node_connectivity(G, flow_func=flow_func)
    # step 2:
    # Find k nodes with top degree, call it X:
    X = {n for n, d in sorted(G.degree(), key=itemgetter(1), reverse=True)[:k]}
    # Check if X is a k-node-cutset
    if _is_separating_set(G, X):
        seen.append(X)
        yield X

    for x in X:
        # step 3: Compute local connectivity flow of x with all other
        # non adjacent nodes in G
        non_adjacent = set(G) - X - set(G[x])
        for v in non_adjacent:
            # step 4: compute maximum flow in an Even-Tarjan reduction H of G
            # and step:5 build the associated residual network R
            R = flow_func(H, '%sB' % mapping[x], '%sA' % mapping[v], **kwargs)
            flow_value = R.graph['flow_value']

            if flow_value == k:
                # Remove saturated edges form the residual network
                saturated_edges = [(u, w, d) for (u, w, d) in
                                   R.edges(data=True)
                                   if d['capacity'] == d['flow']]
                R.remove_edges_from(saturated_edges)
                # step 6: shrink the strongly connected components of
                # residual flow network R and call it L
                L = nx.condensation(R)
                cmap = L.graph['mapping']
                # step 7: Compute antichains of L; they map to closed sets in H
                # Any edge in H that links a closed set is part of a cutset
                for antichain in nx.antichains(L):
                    # Nodes in an antichain of the condensation graph of
                    # the residual network map to a closed set of nodes that
                    # define a node partition of the auxiliary digraph H.
                    S = {n for n, scc in cmap.items() if scc in antichain}
                    # Find the cutset that links the node partition (S,~S) in H
                    cutset = set()
                    for u in S:
                        cutset.update((u, w) for w in H[u] if w not in S)
                    # The edges in H that form the cutset are internal edges
                    # (ie edges that represent a node of the original graph G)
                    node_cut = {H.nodes[n]['id'] for edge in cutset for n in edge}

                    if len(node_cut) == k:
                        if node_cut not in seen:
                            yield node_cut
                            seen.append(node_cut)
                        # Add an edge (x, v) to make sure that we do not
                        # find this cutset again. This is equivalent
                        # of adding the edge in the input graph
                        # G.add_edge(x, v) and then regenerate H and R:
                        # Add edges to the auxiliary digraph.
                        H.add_edge('%sB' % mapping[x], '%sA' % mapping[v],
                                   capacity=1)
                        H.add_edge('%sB' % mapping[v], '%sA' % mapping[x],
                                   capacity=1)
                        # Add edges to the residual network.
                        R.add_edge('%sB' % mapping[x], '%sA' % mapping[v],
                                   capacity=1)
                        R.add_edge('%sA' % mapping[v], '%sB' % mapping[x],
                                   capacity=1)
                        break
                # Add again the saturated edges to reuse the residual network
                R.add_edges_from(saturated_edges)
def coloracion(grafo):
	"""Devuelve la lista minima de colores a usar"""
	nodosSinColorear = grafo.nodes()
	colores = []
	colorActual = (random(), random(), random())	
	coloresAsignados = {}

	for i in nodosSinColorear:
		
		if debug_true:
			print "NodosSinColor[" + str(i) + "]:" + str(nodosSinColorear) 
		
		nodos_adyacentes = nx.all_neighbors(grafo, i)
		nodos_no_adyacentes = nx.non_neighbors(grafo, i)
		colores_adyacentes = []
		colores_no_adyacentes = []
		
		# Almacenamos todos los colores de los nodos adyacentes
		for k in nodos_adyacentes:
			if coloresAsignados.has_key(k):
				colores_adyacentes.append(coloresAsignados[k])
		# Almacenamos todos los colores de los nodos  no adyacentes
		for k in nodos_no_adyacentes:
			if coloresAsignados.has_key(k):
				colores_no_adyacentes.append(coloresAsignados[k])

		# Volvemos a generar los iteradores para nodos adyacentes, ya que
		# al iterar en los bucles de arriba se perdieron
		nodos_adyacentes = nx.all_neighbors(grafo, i)
		nodos_no_adyacentes = nx.non_neighbors(grafo, i)
		
		if debug_true:
			print "colores adyacentes a " + str(i) + str(colores_adyacentes)
			print "colores no adyacentes a " + str(i) + str(colores_no_adyacentes)
			
		aux = False
		for j in nodos_adyacentes:
			if debug_true:
				print "j=" + str(j)
				print "Color Actual=" + str(colorActual)
			if not aux and colorActual not in colores_adyacentes:
				aux = True
				#pass
			else:
				aux = True
				aux2 = False
				# Recorremos los colores no adyacentes y comparamos 
				# el color con el adyacente, usaremos un color existente
				# pero sin que coincida con alguno adyacente
				if colores_no_adyacentes:
					for t in colores_no_adyacentes:
						if debug_true:
							print t not in colores_adyacentes
						if not aux2 and not t in colores_adyacentes:
							aux2 = True
							colorActual = t
				if not aux2:
					if debug_true:
						print "Genero para " + str(i)
					colorActual = (random(), random(), random())

		coloresAsignados[i] = colorActual
		colores.append(colorActual)
		
	if (debug_true):
		pp = pprint.PrettyPrinter(indent=4)
		pp.pprint(coloresAsignados)
		for i in colores:
			print i[0]
	return colores
Exemplo n.º 41
0
import networkx as nx


# 关于图形的方法:
nx.density(G)     #返回图形的密度
nx.degree_histogram(G) #返回列表中每个值的频率
nx.info(G)      #返回图形的摘要信息 :节点数,边数,平均度 etc..
P=nx.create_empty_copy(G)  #返回 移除边的 图形G的 副本
nx.is_directed(DG)       #返回图形是否有向

#关于点的方法
nx.nodes(G)     #以列表的形式返回所有节点
nx.number_of_nodes(G)    #返回节点数
nx.all_neighbors(G,'tank')    #以iterator的形式返回一个节点的所有邻居
nx.non_neighbors(G,'tank')    #以iterator的形式返回一个节点的所有非邻居
nx.common_neighbors(G,'','') #以iterator的形式返回两个节点的公共邻居
nx.nodes_iter(G)              #以iterator的形式返回所有节点
g = nx.compose(G,DG)    #返会合并公共的node???
sorted(G.degree().values())

#关于边的方法
nx.edges(G)     #以列表的形式返回所有的边
nx.number_of_edges(G)   #返回边数
nx.non_edges(G)         #以iterator的形式返回所有不存在的边
nx.edges_iter(G)        #以iterator的形式返回所有边

#关于MultiDiGraph()
G.successors(node)  #返回一个节点的后继
G.predecessor(node) #返回一个节点的前任
G.number_of_edges(node,node)    #返回两个节点间的边数
G.size()    #返回图的边数
Exemplo n.º 42
0
def available_nodes(G, cn, avl):
	for n in nx.non_neighbors(G, cn):
		if G.degree([n]).values()[0] < nodis[n]:
			avl.append(n)
	avl.sort()
	return len(avl)