def test_articulation_points_resnet():
  """Make sure articulation points are found correctly in resnet."""
  tf.reset_default_graph()
  nodes = util.make_resnet(3)
  all_ops = ge.get_forward_walk_ops(seed_ops=nodes[0].op)
  graph = nx.Graph(util.tf_ops_to_graph(all_ops))
  assert util.set_equal(util.format_ops(nx.articulation_points(graph)),
                        ['a01_add'])
  
  tf.reset_default_graph()
  nodes = util.make_resnet(4)
  all_ops = ge.get_forward_walk_ops(seed_ops=nodes[0].op)
  graph = nx.Graph(util.tf_ops_to_graph(all_ops))
  assert util.set_equal(util.format_ops(nx.articulation_points(graph)),
                        ['a01_add', 'a02_add'])
Example #2
0
def test_articulation_points():
    Ggen = _generate_no_biconnected()
    for i in range(5):
        G = next(Ggen)
        cut = nx.minimum_node_cut(G)
        assert_true(len(cut) == 1)
        assert_true(cut.pop() in set(nx.articulation_points(G)))
Example #3
0
def test_articulation_points():
    Ggen = _generate_no_biconnected()
    for i in range(2):
        G = next(Ggen)
        articulation_points = list({a} for a in nx.articulation_points(G))
        for cut in nx.all_node_cuts(G):
            assert_true(cut in articulation_points)
Example #4
0
def get_randomdeletion_graph(network, filename, count):
  while len(network) > count:
    toRemove = numpy.random.choice(network.nodes())
    if toRemove not in nx.articulation_points(network):
      network.remove_node(toRemove)
     
  fh.write_edge_list("%s-RD.txt" % filename, network)      
Example #5
0
def test_articulation_points():
    Ggen = _generate_no_biconnected()
    for i in range(1):  # change 1 to 3 or more for more realizations.
        G = next(Ggen)
        articulation_points = list({a} for a in nx.articulation_points(G))
        for cut in nx.all_node_cuts(G):
            assert_true(cut in articulation_points)
Example #6
0
def block_cutpoint_tree(G, projected=False, verbose=False):
    input_graph = Graph(G)
    top_nodes = []
    bottom_nodes = []
    articulation_points = set(nx.articulation_points(input_graph))
    if verbose:
        print "Articulation points:", articulation_points
    for biconnected_component in nx.biconnected_components(input_graph):
        inter = biconnected_component.intersection(articulation_points)
        if verbose:
            print "Inter:", inter
        top_nodes.extend(
            [json.dumps(sorted(biconnected_component)) for _ in inter]
            )
        #top_nodes.extend([G.subgraph(bcc) for _ in inter])
        bottom_nodes.extend([x for x in inter])
        #bottom_nodes.extend([G.subgraph(x) for x in inter])
    if verbose:
        print "Top nodes:", top_nodes
        print "Bottom nodes:", bottom_nodes
    edges = zip(top_nodes, bottom_nodes)
    if verbose:
        print "Edges:", edges
    bc_tree = Graph()
    bc_tree.add_edges_from(edges)
    if projected:
        return Graph(bipartite.projected_graph(bc_tree, top_nodes))
    else:
        return bc_tree
Example #7
0
 def _singleSegment(self, nodes):
     # disjoint line or a bent line at 45 degrees appearing as dichtonomous tree but an error due to
     # improper binarization, so remove them and do not account for statistics
     listOfPerms = list(itertools.combinations(nodes, 2))
     if type(nodes[0]) == int:
         modulus = [[start - end] for start, end in listOfPerms]
         dists = [abs(i[0]) for i in modulus]
     else:
         dims = len(nodes[0])
         modulus = [[start[dim] - end[dim] for dim in range(0, dims)] for start, end in listOfPerms]
         dists = [sum(modulus[i][dim] * modulus[i][dim] for dim in range(0, dims)) for i in range(0, len(modulus))]
     if len(list(nx.articulation_points(self._subGraphSkeleton))) == 1 and set(dists) != 1:
         # each node is connected to one or two other nodes which are not a distance of 1 implies there is a
         # one branch point with two end points in a single dichotomous tree"""
         for sourceOnTree, item in listOfPerms:
             if nx.has_path(self._subGraphSkeleton, sourceOnTree, item) and sourceOnTree != item:
                 simplePaths = list(nx.all_simple_paths(self._subGraphSkeleton, source=sourceOnTree, target=item))
                 simplePath = simplePaths[0]
                 countBranchNodesOnPath = sum([1 for point in simplePath if point in nodes])
                 if countBranchNodesOnPath == 2:
                     curveLength = self._getLengthAndRemoveTracedPath(simplePath)
                     self.isolatedEdgeInfoDict[sourceOnTree, item] = curveLength
     else:
         # each node is connected to one or two other nodes implies it is a line,
         endPoints = [k for (k, v) in self._nodeDegreeDict.items() if v == 1]
         sourceOnLine = endPoints[0]
         targetOnLine = endPoints[1]
         simplePath = nx.shortest_path(self._subGraphSkeleton, source=sourceOnLine, target=targetOnLine)
         curveLength = self._getLengthAndRemoveTracedPath(simplePath)
         self.isolatedEdgeInfoDict[sourceOnLine, targetOnLine] = curveLength
Example #8
0
def test_articulation_points():
    Ggen = _generate_no_biconnected()
    for flow_func in flow_funcs:
        for i in range(3):
            G = next(Ggen)
            cut = nx.minimum_node_cut(G, flow_func=flow_func)
            assert_true(len(cut) == 1, msg=msg.format(flow_func.__name__))
            assert_true(cut.pop() in set(nx.articulation_points(G)), msg=msg.format(flow_func.__name__))
Example #9
0
	def graph_stats(self, n):
		stats = {}
		stats['Top'] = self.top_nodes(n+1)
		stats['Pagerank'] = nx.pagerank_scipy(self.G)
		stats['Pagerank'] = sorted(stats['Pagerank'].iteritems(), key=itemgetter(1),reverse=True)[0:n+1]
		stats['Articulation Points'] = list(nx.articulation_points(self.G.to_undirected()))
		stats['Histogram'] = self.degree_histogram()[1:26]
		return stats
Example #10
0
def test_biconnected_karate():
    K = nx.karate_club_graph()
    answer = [{0, 1, 2, 3, 7, 8, 9, 12, 13, 14, 15, 17, 18, 19,
               20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33},
              {0, 4, 5, 6, 10, 16},
              {0, 11}]
    bcc = list(nx.biconnected_components(K))
    assert_components_equal(bcc, answer)
    assert_equal(set(nx.articulation_points(K)), {0})
def sorted_articulation_points(targets):
  """Returns list of articulation points (cut vertices) sorted in according
  to the execution order provided by linearize."""
  
  graph, targets = _process_targets(targets)
  sorted_list = list(obtain_linear_order(targets))

  nx_graph = nx.Graph(graph)
  points = _sort(nx.articulation_points(nx_graph),
                 total_order=sorted_list, dedup=True)
  return points
Example #12
0
def articulationpoints(args):
    """Compute articulation points in subgraphs of the graph.

    Parameters
    ----------
    graphname : str
        Refers to pre-computed graphs stored in folder, with the name being the
        first element.
    edgefilter : str (default="families")
        Refers to second component of filename, thus, the component managing
        how edges are created and defined (here: language families as a
        default).
    subgraph : str (default="infomap")
        Determines the name of the subgraph that is used to pre-filter the
        search for articulation points. Defaults to the infomap-algorithms.
    threshold : int (default=1)
        The threshold which was used to calculate the community detection
        analaysis.

    Note
    ----
    Method searches for articulation points inside partitions of the graph,
    usually the partitions as provided by the infomap algorithm. The repository
    stores graph data in different forms, as binary graph and as gml, and the
    paramters are used to identify a given analysis by its filename and make
    sure the correct graph is loaded.
    """
    args.api._log = args.log
    threshold = args.threshold or 1

    graph = args.api.load_graph('infomap', threshold, args.edgefilter)
    coms = defaultdict(list)
    for node, data in graph.nodes(data=True):
        coms[data['infomap']].append(node)
    for com, nodes in sorted(coms.items(), key=lambda x: len(x), reverse=True):
        if len(nodes) > 5:
            subgraph = graph.subgraph(nodes)
            degrees = subgraph.degree(list(subgraph.nodes()))
            cnode = [a for a, b in sorted(degrees, key=lambda x: x[1], reverse=True)][0]
            graph.node[cnode]['DegreeCentrality'] = 1
            for artip in nx.articulation_points(subgraph):
                graph.node[artip]['ArticulationPoint'] = \
                    graph.node[artip].get('ArticulationPoint', 0) + 1
                if bool(args.verbosity):
                    print('{0}\t{1}\t{2}'.format(
                        com, graph.node[cnode]['Gloss'], graph.node[artip]['Gloss']))

    for node, data in graph.nodes(data=True):
        data.setdefault('ArticulationPoint', 0)
        data.setdefault('DegreeCentrality', 0)

    args.api.save_graph(graph, 'articulationpoints', threshold, args.edgefilter)
Example #13
0
def test_biconnected_components1():
    # graph example from
    # http://www.ibluemojo.com/school/articul_algorithm.html
    edges=[
        (0, 1), (0, 5), (0, 6), (0, 14), (1, 5), (1, 6), (1, 14), (2, 4),
        (2, 10), (3, 4), (3, 15), (4, 6), (4, 7), (4, 10), (5, 14), (6, 14),
        (7, 9), (8, 9), (8, 12), (8, 13), (10, 15), (11, 12), (11, 13), (12, 13)
    ]
    G=nx.Graph(edges)
    pts = set(nx.articulation_points(G))
    assert_equal(pts, {4, 6, 7, 8, 9})
    comps = list(nx.biconnected_component_edges(G))
    answer = [
        [(3, 4), (15, 3), (10, 15), (10, 4), (2, 10), (4, 2)],
        [(13, 12), (13, 8), (11, 13), (12, 11), (8, 12)],
        [(9, 8)],
        [(7, 9)],
        [(4, 7)],
        [(6, 4)],
        [(14, 0), (5, 1), (5, 0), (14, 5), (14, 1), (6, 14), (6, 0), (1, 6), (0, 1)],
    ]
    assert_components_edges_equal(comps, answer)
def cut_control(seed_num, graph_json_filename=None, graph_json_str=None):
  """
  Randomly choose 'seed_num' number of cut-vertices from the given graph.
  If there are fewer cut vertices than 'seed_num' then choose the vertices
  adjacent to cut vertices .
  
  Parameters:
    seed_num: Number of nodes to choose.
    graph_json_filename: Filename where the adjacency list lives as JSON.
    graph_json_str: Graph as an adjacency list string in JSON.
    
  Return: List of the chosen nodes.
  """
  
  if graph_json_filename is None and graph_json_str is None:
    return []
  
  G = None
  if graph_json_str is None:
    G = util.load_graph(graph_json_filename=graph_json_filename)
  else:
    G = util.load_graph(graph_json_str=graph_json_str)
  iters_since_change = 0
  cut_vertices = list(set(nx.articulation_points(G)))
  while (len(cut_vertices) < seed_num):
    rand_node = cut_vertices[rand.randint(0, len(cut_vertices) - 1)]
    adj_node_lst = G.neighbors(rand_node)
    rand_adj_node = adj_node_lst[rand.randint(0, len(adj_node_lst) - 1)]
    if (rand_adj_node not in cut_vertices):
      iters_since_change = 0
      cut_vertices.append(rand_adj_node)
    else:
      iters_since_change = iters_since_change + 1
    if (iters_since_change > 10):
      break
  
  return cut_vertices[0:seed_num]
Example #15
0
def spofs(gr):
    """Identifies the SPOF nodes (single points of failure) in a topology, and
    the downstream nodes that will be isolated from the majority of the network
    when any of the SPOFs fail.  Takes a NetworkX Graph or DiGraph as input,
    returns a dictionary of two lists:
    1. a list of SPOF nodes (single points of failure)
    2. a list of downstream nodes that will become isolated when SPOFs fail."""
    if type(gr) != type(nx.Graph()):
        gr = gr.to_undirected(gr)
    # structure:
    #  {'spofs':[node1, node2,...,nodeN], 'isolated':[node1, node2,...,nodeN]}
    impacts = {}
    impacts['spofs'] = list(nx.articulation_points(gr))
    impacts['isolated'] = []
    for spof in impacts['spofs']:
        gr_tmp = gr.copy()
        gr_tmp.remove_node(spof)
        ccomp = nx.connected_components(gr_tmp)
        ccomp.sort(key=len)
        for sublist in range(len(ccomp)-1):
            for node in ccomp[sublist]:
                if not node in impacts['isolated']:
                    impacts['isolated'].append(node)      
    return impacts
Example #16
0
def articulation_points(graph):
    return graph, nx.articulation_points(graph)
Example #17
0
def test_articulation_points_cycle():
    G = nx.cycle_graph(3)
    nx.add_cycle(G, [1, 3, 4])
    pts = set(nx.articulation_points(G))
    assert pts == {1}
Example #18
0
            cpterr+=1
        except ValueError:
            cpterr+=1
    links = []

    # NetworkX graph
    G=nx.Graph()
    for sensor in sensorlist:
        G.add_node(sensor)
    for edge in linklist:
        G.add_edge(edge[0], edge[1], weight=edge[2])

    # We remove articulation points
    if int(MODIF) == -1:
        for H in list(nx.connected_component_subgraphs(G)):
            for sensor in list(nx.articulation_points(H)):
                pos[sensor] = (-1,-1)

        if os.path.isfile(SENSORS_DATA):
            os.remove(SENSORS_DATA)

        det_file = open(SENSORS_DATA, "a+")
        for i in set(pos.keys()):
            posx = float(pos[i][0])
            posy = float(pos[i][1])
            if posx != -1 and posy != -1:
                print >> det_file, str(posx) + ',' + str(posy)
        det_file.close()


    for stridx in strategies:

        start_graph_path = expdir + '/nuc0-' + str(masteridx) + '_' + expname +\
            '/' + str(stridx) + '/olsrd2_vanilla/start_graph.graphml'
        strategy_path = expdir + '/nuc0-' + str(masteridx) + '_' + expname +\
            '/' + str(stridx) + '/prince/strategies'

        deadnode_id = ''
        deadnode_name = ''
        with open(strategy_path, 'r') as df:
            line = df.read()
            deadnode_id = line.split('@')[0]

        sg = nx.read_graphml(start_graph_path)
        ap = [x for x in nx.articulation_points(sg)]
        no_leaves_nodes = nx.k_core(sg, 2).nodes()
        cn = [x for x in sg.nodes() if x not in ap and x in no_leaves_nodes]

        node_ip_to_name = {}
        node_name_to_ip = {}
        for i in range(1, 100):
            node_ip_to_name['10.1.0.' + str(i)] = 'nuc0-' + str(i)
            node_name_to_ip['nuc0-' + str(i)] = '10.1.0.' + str(i)

        deadnode_name = node_ip_to_name[deadnode_id]

        bcn = nx.betweenness_centrality(sg, weight='weight', endpoints=True)
        bcns = [(node_ip_to_name[n], bcn[n]) for (
            n, bcn[n]) in sorted(bcn.items(), key=lambda x: x[1], reverse=True)
                ]
Example #20
0
def topographic_metrics(wn):
    # Get a copy of the graph
    G = wn.get_graph()

    # Print general topographic information
    print(nx.info(G))

    # Plot node and edge attributes.
    junction_attr = wn.query_node_attribute('elevation',
                                            node_type=wntr.network.Junction)
    pipe_attr = wn.query_link_attribute('length', link_type=wntr.network.Pipe)
    wntr.graphics.plot_network(wn,
                               node_attribute=junction_attr,
                               link_attribute=pipe_attr,
                               title='Node elevation and pipe length',
                               node_size=40,
                               link_width=2)

    # Compute link density
    print("Link density: " + str(nx.density(G)))

    # Compute node degree
    node_degree = dict(G.degree())
    wntr.graphics.plot_network(wn,
                               node_attribute=node_degree,
                               title='Node Degree',
                               node_size=40,
                               node_range=[1, 5])

    # Compute number of terminal nodes
    terminal_nodes = G.terminal_nodes()
    wntr.graphics.plot_network(wn,
                               node_attribute=terminal_nodes,
                               title='Terminal nodes',
                               node_size=40,
                               node_range=[0, 1])
    print("Number of terminal nodes: " + str(len(terminal_nodes)))
    print("   " + str(terminal_nodes))

    # Compute pipes with diameter > threshold
    diameter = 0.508  # m (20 inches)
    pipes = wn.query_link_attribute('diameter', np.greater, diameter)
    wntr.graphics.plot_network(wn,
                               link_attribute=list(pipes.keys()),
                               title='Pipes > 20 inches',
                               link_width=2,
                               link_range=[0, 1])
    print("Number of pipes > 20 inches: " + str(len(pipes)))
    print("   " + str(pipes))

    # Compute nodes with elevation <= treshold
    elevation = 1.524  # m (5 feet)
    nodes = wn.query_node_attribute('elevation', np.less_equal, elevation)
    wntr.graphics.plot_network(wn,
                               node_attribute=list(nodes.keys()),
                               title='Nodes <= 5 ft elevation',
                               node_size=40,
                               node_range=[0, 1])
    print("Number of nodes <= 5 ft elevation: " + str(len(nodes)))
    print("   " + str(nodes))

    # Compute eccentricity, diameter, and average shortest path length
    # These all use an undirected graph
    uG = G.to_undirected()  # undirected graph
    if nx.is_connected(uG):
        ecc = nx.eccentricity(uG)
        wntr.graphics.plot_network(wn,
                                   node_attribute=ecc,
                                   title='Eccentricity',
                                   node_size=40,
                                   node_range=[15, 30])

        print("Diameter: " + str(nx.diameter(uG)))

        ASPL = nx.average_shortest_path_length(uG)
        print("Average shortest path length: " + str(ASPL))

    # Compute cluster coefficient
    clust_coefficients = nx.clustering(nx.Graph(G))
    wntr.graphics.plot_network(wn,
                               node_attribute=clust_coefficients,
                               title='Clustering Coefficient',
                               node_size=40)

    # Compute betweenness centrality
    bet_cen = nx.betweenness_centrality(G)
    wntr.graphics.plot_network(wn,
                               node_attribute=bet_cen,
                               title='Betweenness Centrality',
                               node_size=40,
                               node_range=[0, 0.4])
    central_pt_dom = G.central_point_dominance()
    print("Central point dominance: " + str(central_pt_dom))

    # Compute articulation points
    Nap = list(nx.articulation_points(uG))
    Nap = list(set(Nap))  # get the unique nodes in Nap
    Nap_density = float(len(Nap)) / uG.number_of_nodes()
    print("Density of articulation points: " + str(Nap_density))
    wntr.graphics.plot_network(wn,
                               node_attribute=Nap,
                               title='Articulation Point',
                               node_size=40,
                               node_range=[0, 1])

    # Compute bridges
    bridges = G.bridges()
    wntr.graphics.plot_network(wn,
                               link_attribute=bridges,
                               title='Bridges',
                               link_width=2,
                               link_range=[0, 1])
    Nbr_density = float(len(bridges)) / G.number_of_edges()
    print("Density of bridges: " + str(Nbr_density))

    # Compute spectal gap
    spectral_gap = G.spectral_gap()
    print("Spectal gap: " + str(spectral_gap))

    # Compute algebraic connectivity
    alg_con = G.algebraic_connectivity()
    print("Algebraic connectivity: " + str(alg_con))

    # Critical ratio of defragmentation
    fc = G.critical_ratio_defrag()
    print("Critical ratio of defragmentation: " + str(fc))

    # Compute closeness centrality
    clo_cen = nx.closeness_centrality(G)
    wntr.graphics.plot_network(wn,
                               node_attribute=clo_cen,
                               title='Closeness Centrality',
                               node_size=40)
Example #21
0
def test_biconnected_davis():
    D = nx.davis_southern_women_graph()
    bcc = list(nx.biconnected_components(D))[0]
    assert_true(set(D) == bcc) # All nodes in a giant bicomponent
    # So no articulation points
    assert_equal(len(list(nx.articulation_points(D))), 0)
Example #22
0
def articulation_avoidance(segmentation_graph, segment_counts):
    # This implementation of Articulation Avoidance is different from the one proposed in the paper
    # It uses additional heuristics to reduce the number of questions further by ~3%
    # The data provided, however, is for bins generated without using these additional heuristics

    n = segmentation_graph.number_of_nodes()
    m = segmentation_graph.number_of_edges()
    groups = []  # list of all final groups
    count_groups = []
    remaining_nodes = G.nodes()

    H = segmentation_graph.copy()
    cutpoints = list(nx.articulation_points(H))

    # picking group starting nodes in sequence for now
    while len(remaining_nodes) > 0:
        new_center = -1  # first node in new group
        new_group = []

        for i in remaining_nodes:
            if i not in cutpoints:
                new_center = i
                remaining_nodes.remove(i)
                H.remove_node(i)
                cutpoints = list(nx.articulation_points(H))
                break

                # if no remaining non-cutpoints
        if new_center == -1:
            new_center = remaining_nodes.pop()
            H.remove_node(new_center)
            cutpoints = list(nx.articulation_points(H))

            # form new group
        new_group.append(new_center)
        current_size = segment_counts[new_center]

        regular_neighbors = []  # non Articulation Points
        cutpoint_neighbors = []  # Articulation Points

        for node in segmentation_graph.neighbors(new_center):
            if node in remaining_nodes:
                if node in cutpoints:
                    cutpoint_neighbors.append(node)
                else:
                    regular_neighbors.append(node)
        max_segment_size = int(math.floor(WORKER_COUNT_THRESHOLD * 1.0 / max(segment_counts.values()))) * max(
            segment_counts.values()
        )

        while current_size < max_segment_size and len(regular_neighbors) + len(cutpoint_neighbors) > 0:
            if regular_neighbors:
                add_next = regular_neighbors.pop()
            else:
                add_next = cutpoint_neighbors.pop()

            if (add_next in remaining_nodes) and (segment_counts[add_next] + current_size <= max_segment_size):
                H.remove_node(add_next)
                cutpoints = list(nx.articulation_points(H))

                # Recompute cutpoint_neighbors and regular_neighbors
                for vertex in cutpoint_neighbors:
                    if vertex not in cutpoints:
                        cutpoint_neighbors.remove(vertex)
                        regular_neighbors.append(vertex)

                for vertex in regular_neighbors:
                    if vertex in cutpoints:
                        cutpoint_neighbors.append(vertex)
                        regular_neighbors.remove(vertex)

                new_group.append(add_next)
                current_size += segment_counts[add_next]
                remaining_nodes.remove(add_next)
                for node in segmentation_graph.neighbors(add_next):
                    if node in remaining_nodes:
                        if node in cutpoints:
                            cutpoint_neighbors.append(node)
                        else:
                            regular_neighbors.append(node)

        groups.append(new_group)
        count_groups.append(current_size)

    return groups, count_groups
Example #23
0
yfit = lambda x: np.exp(poly(np.log(x)))
plt.loglog(x,yfit(x))
plt.legend(['degree-distribution','Fit-line'])
plt.xlabel('Degree')
plt.ylabel('Number of nodes')
plt.title('deg distribution')
plt.savefig('deg distribution.pdf')
plt.show()
plt.close()

print "Exponents are b", a,"loga",b


#Find the number of bridges in the graph
#print list(nx.articulation_points(G))
nbr = len(list(nx.articulation_points(G)))
print "No of bridges are ",nbr

#Count the number of 3-cycles. In directed graphs, ignore the direction
cycls_3 = [c for c in nx.cycle_basis(G) if len(c)==3]
print "no of 3 cycles are ",len(cycls_3)

#Measure the graph’s diameter. In directed graphs, ignore the direction. 
print "Diameter of graph is",nx.diameter(G)

#Remove x% of edges randomly then:
#Compute the size |S| of the largest connected component
#Do for x from 1 to 100. Plot x versus |S|.
#If you have a directed graph, make it undirected

i=0
Example #24
0
    def GTCannon(self, Graph):
        """Turn graph into canonical form
        Note: Relies on NetworkX articulation_points which is restricted to 
        undirected graphs"""
        
        # Handle case where graph is empty.
        if len(Graph.nodes()) == 0:
            return Graph
        
        lex_labeling = self.utility.lexicographicallyLargestLabeling(Graph)
        Graph = networkx.relabel_nodes(Graph, lex_labeling,copy=True)
        retGraph = Graph.copy()
        last_degree = Graph.degree()
        original_degree = Graph.degree()
        canon_label = {}
        
        label = len(Graph.nodes())
        while len(Graph.nodes()) > 0:
            
            articulations = list(networkx.articulation_points(Graph.to_undirected())) \
                if networkx.is_directed(Graph) else list(networkx.articulation_points(Graph))
            current_degrees = temp_degrees = Graph.degree()
            
            #Remove articulation points from consideration
            for nodes in articulations:
                if nodes in temp_degrees:
                    temp_degrees.pop(nodes)
            
            #Sort by degree       
            sorted_degrees = sorted(temp_degrees.iteritems(), key=itemgetter(1))
            
            #Capture min degree
            candidates = []
            u_min = sorted_degrees.pop(0)
            candidates.append(u_min)
            
            #Collect candidates with same degree
            while len(sorted_degrees) > 0 and sorted_degrees[0][1] == u_min[1]:
                candidates.append(sorted_degrees.pop(0))

            #Are there ties?
            if len(candidates) > 1:
                first_tie_candidates = []
                sorted_last_degrees = []
                for pair in candidates:
                    sorted_last_degrees.append((pair[0],last_degree[pair[0]]))
                sorted_last_degrees = sorted(sorted_last_degrees, key=itemgetter(1))
                u_min = sorted_last_degrees.pop(0)
                first_tie_candidates.append(u_min)
                
                while len(sorted_last_degrees) > 0 and sorted_last_degrees[0][1] == u_min[1]:
                    first_tie_candidates.append(sorted_last_degrees.pop())
                
                #Still ties?
                if len(first_tie_candidates) > 1:
                    sorted_original_degree = []
                    for pair in first_tie_candidates:
                        sorted_original_degree.append((pair[0],original_degree[pair[0]]))
                    sorted_original_degree = sorted(sorted_original_degree, key=itemgetter(1))
                    u_min = sorted_original_degree.pop(0)
            
            Graph.remove_node(u_min[0])                                                                   
            canon_label[u_min[0]] = label
            label -= 1
            
        retGraph = networkx.relabel_nodes(retGraph, canon_label, copy=True)
        return retGraph
def test_null_graph():
    G = nx.Graph()
    assert not nx.is_biconnected(G)
    assert list(nx.biconnected_components(G)) == []
    assert list(nx.biconnected_component_edges(G)) == []
    assert list(nx.articulation_points(G)) == []
def test_biconnected_davis():
    D = nx.davis_southern_women_graph()
    bcc = list(nx.biconnected_components(D))[0]
    assert set(D) == bcc  # All nodes in a giant bicomponent
    # So no articulation points
    assert len(list(nx.articulation_points(D))) == 0
Example #27
0
    def cut_vertices(self):
        """Return list of cut vertices.  Each cut vertex is a node
        that if removed, with its edges, disconnects the graph."""

        return list(nx.articulation_points(self.G))
def compute_2_connected_k_dominating_set(G, DA):

    graphDA = G.subgraph(DA)

    DB = DA

    genB = nx.biconnected_components(graphDA)

    B = []
    for item in genB:
        B.append(list(item))

        # print "B"
        # print B

    art_points = list(nx.articulation_points(graphDA))
    # print "Articulation Points"
    # print art_points

    P = []

    while len(B) > 1:

        for block in B:
            inducedL = list(set(block) - set(art_points))
            L = block

            # print "L"
            # print L
            # print "inducedL"
            # print inducedL

            if inducedL:
                break

        for v in inducedL:
            tempDB = list(DB)
            tempDB.remove(v)

            # Now for nodes in DA, may need DB
            for u in list(set(graphDA.nodes()) - set(L)):
                tempDB.remove(u)

                newG = G.copy()
                newG.remove_nodes_from(tempDB)

                # This part can make the algorithm fail
                if nx.has_path(newG, v, u):
                    tempP = nx.shortest_path(newG, v, u)
                    P.append(tempP)

                    # print "P"
                    # print P

        minPath = min(P, key=len)

        # Keep intermediate nodes of path
        interPath = list(minPath)
        interPath.pop(0)
        interPath.pop(-1)

        for node in interPath:
            DB.append(node)

            # Compute new CDS graph and recalculate B
        tempGraph = G.subgraph(DB)
        B = []
        for item in genB:
            B.append(list(item))

        genB = nx.biconnected_components(tempGraph)

        # print "B"
        # print B

        art_points = list(nx.articulation_points(tempGraph))
        # print "Articulation Points"
        # print art_points

    return DB
Example #29
0
def new_vertex_selector(local_g,
                        v_pol_local,
                        v_pro_local,
                        list_thr,
                        v_s,
                        agg=max):
    # --- Define local subgraph with v_pro removed
    local_vertices = []
    local_vertices = list(local_g.nodes())
    for v_pro in list(v_pro_local.nodes):
        local_vertices.remove(v_pro)

    deleted_subgraph = local_g.subgraph(local_vertices)
    search_subgraph_list = []
    subgraph_list = []
    subgraph_list.extend(list_thr)
    subgraph_list.extend(list(v_pol_local.nodes()))

    # --- Find subgraph for searching use
    for v_thr in list_thr:
        for v_nbr in deleted_subgraph.neighbors(v_thr):
            if v_nbr in subgraph_list:
                continue
            else:
                subgraph_list.append(v_nbr)
                search_subgraph_list.append(v_nbr)

    for rng in range(2):
        search_list_temp = []
        search_list_temp.extend(search_subgraph_list)
        search_subgraph_list = []
        for v_srch in search_list_temp:
            for v_nbr in deleted_subgraph.neighbors(v_srch):
                if v_nbr in subgraph_list:
                    continue
                else:
                    subgraph_list.append(v_nbr)
                    search_subgraph_list.append(v_nbr)

    # find out which vertex will increase the average distance the most
    local_vertices_deleted = []
    local_vertices_deleted.extend(subgraph_list)
    local_vertices_deleted.append(v_s)

    # --- Find Articulation Points that are threatened
    art_pts = [
        x for x in list_thr if x in nx.articulation_points(deleted_subgraph)
    ]

    if len(art_pts) > 0:
        infinity_num_dict = {}
        # --- First pass through articulation points
        for art in art_pts:
            # print('2')
            # Remove articulation point from graph
            local_vertices_deleted.remove(art)
            deleted_subgraph = local_g.subgraph(local_vertices_deleted)

            # Find connected component containing source
            c_gen = deleted_subgraph.subgraph(
                nx.components.node_connected_component(deleted_subgraph, v_s))

            # Store number of isolated nodes
            infinity_num_dict.update(
                {art: (int(deleted_subgraph.order() - c_gen.order()), c_gen)})

            # Return node to local working graph
            local_vertices_deleted.append(art)

        # Filter infinity_num_dict by maximum
        infinity_num_dict = {
            key: item
            for key, item in infinity_num_dict.items()
            if item[0] == max(l[0] for l in infinity_num_dict.values())
        }

        # Find value to return
        if len(infinity_num_dict) > 1:
            # If there are more than one *maximum* cuts, find avg paths
            avg_distance_dict = {
                key: nx.average_shortest_path_length(item[1].copy())
                for key, item in infinity_num_dict.items()
            }

            avg_distance_dict = {
                key: item
                for key, item in avg_distance_dict.items()
                if item == max(avg_distance_dict.values())
            }
            return choice(list(avg_distance_dict.keys()))
        else:
            return choice(list(infinity_num_dict.keys()))

    else:

        avg_distance_list = []
        for l in list_thr:
            local_vertices_deleted.remove(l)
            deleted_subgraph = local_g.subgraph(local_vertices_deleted)
            avg_distance_list.append(
                (l,
                 nx.average_shortest_path_length(
                     deleted_subgraph.subgraph(
                         nx.components.node_connected_component(
                             deleted_subgraph, v_s)).copy())))

            local_vertices_deleted.append(l)
        max_avg_distance = max(l[1] for l in avg_distance_list)
        max_avg_distance_dict = dict(
            filter(lambda l: l[1] == max_avg_distance, avg_distance_list))

        return choice(list(max_avg_distance_dict.keys()))
Example #30
0
def test_articulation_points_cycle():
    G=nx.cycle_graph(3)
    nx.add_cycle(G, [1, 3, 4])
    pts=set(nx.articulation_points(G))
    assert_equal(pts, {1})
Example #31
0
 def get_articulation_points(self, nodes):
     sub_G = self.G.subgraph(nodes)
     points = nx.articulation_points(sub_G)
     return list(points)
def topographic_metrics(wn):
    # Get a copy of the graph 
    G = wn.get_graph_deep_copy()
            
    # Print general topographic information
    print nx.info(G)
    
    # Plot node and edge attributes.
    junction_attr = wn.query_node_attribute('elevation', 
                                          node_type=wntr.network.Junction)
    pipe_attr = wn.query_link_attribute('length', link_type=wntr.network.Pipe)
    wntr.network.draw_graph(wn, node_attribute=junction_attr, 
                               link_attribute=pipe_attr, 
                               title='Node elevation and pipe length', 
                               node_size=40, link_width=2)
    
    # Compute link density
    print "Link density: " + str(nx.density(G))
    
    # Compute node degree
    node_degree = G.degree()
    wntr.network.draw_graph(wn, node_attribute=node_degree,
                          title='Node Degree', node_size=40, node_range=[1,5])
    
    # Compute number of terminal nodes
    terminal_nodes = G.terminal_nodes()
    wntr.network.draw_graph(wn, node_attribute=terminal_nodes,
                          title='Terminal nodes', node_size=40, node_range=[0,1])
    print "Number of terminal nodes: " + str(len(terminal_nodes))
    print "   " + str(terminal_nodes)
    
    # Compute number of non-zero demand (NZD) nodes
    nzd_nodes = wn.query_node_attribute('base_demand', np.greater, 0.0)
    wntr.network.draw_graph(wn, node_attribute=nzd_nodes.keys(),
                          title='NZD nodes', node_size=40, node_range=[0,1])
    print "Number of NZD nodes: " + str(len(nzd_nodes))
    print "   " + str(nzd_nodes.keys())
    
    # Compute pipes with diameter > threshold
    diameter = 0.508 # m (20 inches)
    pipes = wn.query_link_attribute('diameter', np.greater, diameter)
    wntr.network.draw_graph(wn, link_attribute=pipes.keys(), 
                          title='Pipes > 20 inches', link_width=2, 
                          link_range=[0,1])
    print "Number of pipes > 20 inches: " + str(len(pipes))
    print "   " + str(pipes)
    
    # Compute nodes with elevation <= treshold
    elevation = 1.524 # m (5 feet)
    nodes = wn.query_node_attribute('elevation', np.less_equal, elevation)
    wntr.network.draw_graph(wn, node_attribute=nodes.keys(), 
                          title='Nodes <= 5 ft elevation', node_size=40, 
                          node_range=[0,1])
    print "Number of nodes <= 5 ft elevation: " + str(len(nodes))
    print "   " + str(nodes)
    
    # Compute eccentricity, diameter, and average shortest path length
    # These all use an undirected graph
    uG = G.to_undirected() # undirected graph
    if nx.is_connected(uG):
        ecc = nx.eccentricity(uG)
        wntr.network.draw_graph(wn, node_attribute=ecc, title='Eccentricity', 
                              node_size=40, node_range=[15, 30])
    
        print "Diameter: " + str(nx.diameter(uG))
    
        ASPL = nx.average_shortest_path_length(uG)
        print "Average shortest path length: " + str(ASPL)
    
    # Compute cluster coefficient
    clust_coefficients = nx.clustering(nx.Graph(G))
    wntr.network.draw_graph(wn, node_attribute=clust_coefficients,
                          title='Clustering Coefficient', node_size=40)
    
    # Compute meshedness coefficient
    meshedness = float(G.number_of_edges() - G.number_of_nodes() + 1)/(2*G.number_of_nodes()-5)
    print "Meshedness coefficient: " + str(meshedness)
    
    # Compute betweenness centrality
    bet_cen = nx.betweenness_centrality(G)
    wntr.network.draw_graph(wn, node_attribute=bet_cen, 
                          title='Betweenness Centrality', node_size=40, 
                          node_range=[0, 0.4])
    central_pt_dom = G.central_point_dominance()
    print "Central point dominance: " + str(central_pt_dom)
    
    # Compute articulation points
    Nap = list(nx.articulation_points(uG))
    Nap = list(set(Nap)) # get the unique nodes in Nap
    Nap_density = float(len(Nap))/uG.number_of_nodes()
    print "Density of articulation points: " + str(Nap_density)
    wntr.network.draw_graph(wn, node_attribute=Nap, title='Articulation Point', 
                          node_size=40, node_range=[0,1])
    
    # Compute bridges
    bridges = G.bridges()
    wntr.network.draw_graph(wn, link_attribute=bridges, title='Bridges', 
                          link_width=2, link_range=[0,1])
    Nbr_density = float(len(bridges))/G.number_of_edges()
    print "Density of bridges: " + str(Nbr_density)
    
    # Compute spectal gap
    spectral_gap = G.spectral_gap()
    print "Spectal gap: " + str(spectral_gap)
    
    # Compute algebraic connectivity
    alg_con = G.algebraic_connectivity()
    print "Algebraic connectivity: " + str(alg_con)
    
    # Critical ratio of defragmentation
    fc = G.critical_ratio_defrag()
    print "Critical ratio of defragmentation: " + str(fc)
    
    # Compute closeness centrality
    clo_cen = nx.closeness_centrality(G)
    wntr.network.draw_graph(wn, node_attribute=clo_cen,
                          title='Closeness Centrality', node_size=40)
Example #33
0
def test_articulation_points_repetitions():
    G = nx.Graph()
    G.add_edges_from([(0, 1), (1, 2), (1, 3)])
    assert_equal(list(nx.articulation_points(G)), [1])
        #     nodes_color_alpha.append(0.4)
        #     edges_color_alpha.append(0.6)
        #     edge_width_l.append(4.0)
# print str(" ")

# Gcc=sorted(nx.biconnected_connected_component_subgraphs(G), key = len, reverse=True)
# Ggc=Gcc[0]
# graph='Ggc'
# print 'Nodes of giant connected component', graph+':', Ggc.nodes()
# print 'Edges of giant connected component', graph+':', Ggc.edges()
# print str(" ")

print 'The biconnected component edges of G are:', list(nx.biconnected_component_edges(G))
print str(" ")

print 'The articulation points of G are:', set(nx.articulation_points(G))
print str(" ")

print 'Isolated nodes:', nx.isolates(G)
print str(" ")

# n1=list(set(G.nodes()) - set(Ggc.nodes()) - set(nx.isolates(G)))
# print 'Non-isolated nodes outside the giant connected component:', n1

# N1=G.subgraph(n1)
# print 'Edges among non-isolated nodes outside the giant connected component:', N1.edges()


plt.figure()

# plt.title('Biconnected components of an undirected graph')
Example #35
0
def test_null_graph():
    G = nx.Graph()
    assert_false(nx.is_biconnected(G))
    assert_equal(list(nx.biconnected_components(G)), [])
    assert_equal(list(nx.biconnected_component_edges(G)), [])
    assert_equal(list(nx.articulation_points(G)), [])
Example #36
0
def test_articulation_points_repetitions():
    G = nx.Graph()
    G.add_edges_from([(0, 1), (1, 2), (1, 3)])
    assert list(nx.articulation_points(G)) == [1]
Example #37
0
    #g = nx.DiGraph()
    g.add_nodes_from(range(len(lines)))
    for row in range(len(lines)):
        for col in range(len(lines)):
            if int(lines[row][col]) == 1:
                g.add_edge(row,col)
    print "Done reading all the files"  
    graphs[item] = g


for g in graphs.keys():
    try:
        print "====================== " , g, "==========================="
        print "number of isolated nodes",'\t\t\t',nx.isolates(graphs[g])
        print "is graph biconnected?",'\t\t\t',nx.is_biconnected(graphs[g])
        print "cut vertices are: ",'\t\t\t',list(nx.articulation_points(graphs[g]))
        print "number of nodes",'\t\t\t',len(graphs[g].nodes())
        print "number of edges",'\t\t\t',len(graphs[g].edges())
        print "degree",'\t\t\t',get_avg(graphs[g].degree())
        print "diameter",'\t\t\t', nx.diameter(graphs[g])
        print "radius",'\t\t\t', nx.radius(graphs[g])
        print "is_bipartite?",'\t\t', bipartite.is_bipartite(graphs[g])
        print "average_shortest_path_length",'\t\t', nx.average_shortest_path_length(graphs[g])
        print "degree_assortativity_coefficient",'\t\t', nx.degree_assortativity_coefficient(graphs[g])
        print "assortativity.average_degree_connectivity",'\t\t', nx.assortativity.average_degree_connectivity(graphs[g])
        #print "degree_pearson_correlation_coefficient",'\t\t', nx.degree_pearson_correlation_coefficient(graphs[g])
        print "node closeness_centrality",'\t\t\t', get_avg(nx.closeness_centrality(graphs[g]))
        print "clustering",'\t\t\t', get_avg(nx.clustering(graphs[g]))
        print "node betweeness",'\t\t\t', get_avg(nx.betweenness_centrality(graphs[g],normalized=False,endpoints=False))
        print "edge betweeness",'\t\t\t', get_avg(nx.edge_betweenness_centrality(graphs[g],normalized=False))
        #print "spectral_bipartivity",'\t\t', bipartite.spectral_bipartivity(graphs[g])
    def condensate_graph(self):
        graphs = []
        connected_components = list(
            nx.connected_component_subgraphs(self.graph))

        counter = 0
        if not len(connected_components):
            self.condensed_graph = nx.Graph()
            return

        for comp in connected_components:
            if len(comp) == 1:
                g = nx.Graph()
                n = comp.nodes()[0]
                g.add_node(n, {"type": "cutpoint"})
                graphs.append(g)
                continue

            g = nx.Graph()
            if not len(comp):
                pass
            else:
                components = list(nx.biconnected_components(comp))
                max_component_size = max([len(x) for x in components if x])
                component_dict = {}
                cutpoints = set(nx.articulation_points(comp))
                i = 0

                for c in sorted(components, key=lambda x: -len(x)):
                    nodes = set(c) - cutpoints
                    if not nodes:
                        continue
                    node_id = "Block " + str(i)
                    g.add_node(node_id)
                    component_dict[node_id] = nodes
                    i += 1
                    g.node[node_id]["nodes"] = " ".join([x for x in nodes])
                    g.node[node_id]["nodes in block"] = len(nodes)
                    g.node[node_id]["radius"] = max(
                        int(self.max_node_size * float(len(nodes)) /
                            max_component_size), self.min_node_size)
                    g.node[node_id]["type"] = "block"

                for n in cutpoints:
                    temp_g = comp.copy()
                    temp_g.remove_node(n)
                    main_c = sorted(
                        [x for x in nx.connected_components(temp_g)],
                        key=lambda x: len(x))
                    robustness = len(main_c[-1])
                    g.add_node(n)
                    g.node[n]["type"] = "cutpoint"
                    g.node[n]["Potential disconnected nodes"] = len(
                        comp) - robustness - 1
                    for neigh in comp[n].keys():
                        if neigh in cutpoints:
                            g.add_edge(n, neigh, {'weight': 1})  # TODO weight
                        else:
                            for k, v in component_dict.items():
                                if neigh in v:
                                    g.add_edge(n, k,
                                               {'weight': 1})  # TODO weight
                    g.node[n]["robustness"] = 10 - int(
                        10 * float(robustness) / len(comp))
                    g.node[n]["style"] = "cutpoint_" +\
                                          str(10 - int(10*float(robustness) /
                                                       len(comp)))
                    g.node[n]["radius"] = self.cutpoint_size[g.node[n]
                                                             ["robustness"]]

            # let's merge some leaves
            i = 0
            for n, data in g.nodes(data=True):
                tobemerged = []
                mergesize = 0
                if data["type"] == "cutpoint":
                    for (neigh, ndata) in g[n].items():
                        if g.node[neigh]["type"] == "block" and \
                           len(g[neigh]) == 1:
                            tobemerged.append(neigh)
                            mergesize += g.node[neigh]["nodes in block"]
                if len(tobemerged) > 1:
                    nodes = " ".join([g.node[y]["nodes"] for y in tobemerged])
                    g.add_node(
                        i, {
                            "nodes":
                            nodes,
                            "nodes in block":
                            mergesize,
                            "radius":
                            max(
                                int(self.max_node_size *
                                    float(len(tobemerged)) /
                                    max_component_size), self.min_node_size),
                            "type":
                            "block"
                        })
                    g.add_edge(i, n, {"weight": 1})  # TODO need weight here
                    i += 1
                    for n in tobemerged:
                        g.remove_node(n)

        # then relabel all the blocks
            blocks = {}
            for n, data in g.nodes(data=True):
                if data["type"] == "block":
                    blocks[n] = data["nodes in block"]
            labels = {}
            for n in sorted(blocks.items(), key=lambda x: -x[1]):
                labels[n[0]] = "Block %d" % counter
                counter += 1
            r_g = nx.relabel_nodes(g, labels, copy=True)
            graphs.append(r_g)
        self.condensed_graph = nx.union_all(graphs)
a = coeffs[0]
b = coeffs[1]
poly = np.poly1d(coeffs)
yfit = lambda x: np.exp(poly(np.log(x)))
plt.loglog(x,yfit(x))
plt.legend(['degree-distribution','Fit-line'])
plt.xlabel('OutDegree')
plt.ylabel('Count')
plt.title('Out-degree distribution')
plt.savefig('outdegree_distribution.png')
plt.show()
plt.close()
print("Exponents for out-degree distribution are b : %f , log(a) : %f" % (a,b))

# Finding the number of bridges
bridge_node_list=list(nx.articulation_points(h))
bridge_node_set = set(bridge_node_list)
print("Number of Bridges :",len(bridge_node_set))

# Number of 3-cycles
# print("Number of triangles in the Graph is :",len(nx.triangles(h))/3)
cycls_3 = [c for c in nx.cycle_basis(h) if len(c)==3]
print("No of 3 cycles are ",len(cycls_3))

## Point 5

edge_list = list(h.edges())
total_edges = len(edge_list)
#print(total_edges)
print("Total Number of edges: ",len(edge_list))
print("Number of connected components in original graph :",nx.number_connected_components(h))
Example #40
-1
def test_barbell():
    G = nx.barbell_graph(8, 4)
    nx.add_path(G, [7, 20, 21, 22])
    nx.add_cycle(G, [22, 23, 24, 25])
    pts = set(nx.articulation_points(G))
    assert_equal(pts, {7, 8, 9, 10, 11, 12, 20, 21, 22})

    answer = [
        {12, 13, 14, 15, 16, 17, 18, 19},
        {0, 1, 2, 3, 4, 5, 6, 7},
        {22, 23, 24, 25},
        {11, 12},
        {10, 11},
        {9, 10},
        {8, 9},
        {7, 8},
        {21, 22},
        {20, 21},
        {7, 20},
    ]
    assert_components_equal(list(nx.biconnected_components(G)), answer)

    G.add_edge(2,17)
    pts = set(nx.articulation_points(G))
    assert_equal(pts, {7, 20, 21, 22})