def get_topological_features(G, nodes=None):
    N_ = len(G.nodes)
    if nodes is None:
        nodes = G.nodes
    # Degree centrality
    d_c = get_features(degree_centrality(G).values())
    # Betweeness centrality
    b_c = get_features(betweenness_centrality(G).values())
    # Close ness centrality
    c_c = get_features(closeness_centrality(G).values())
    # Clustering
    c = get_features(clustering(G).values())

    d = diameter(G)
    r = radius(G)

    s_p_average = []
    for s in shortest_path_length(G):
        dic = s[1]
        lengths = dic.values()
        s_p_average += [sum(lengths) / float(N_)]

    s_p_average = get_features(s_p_average)

    features = np.concatenate((d_c, b_c, c_c, c, s_p_average, [d], [r]),
                              axis=0)

    return features
Exemple #2
0
def runWith(fname) :
  print(fname)
  gm=dr.GraphMaker()
  gm.load(fname)
  # dpr=gm.pagerank()
  dg=gm.graph()
  #for x in dg: print('VERT::', x)

  print('nodes:', dg.number_of_nodes())
  print('edges:', dg.number_of_edges())

  comps=nx.strongly_connected_components(dg)

  print('strongly connected components:',len(list(comps)))

  c = max(nx.strongly_connected_components(dg), key=len)
  mg=dg.subgraph(c)

  print('attracting components:', co.number_attracting_components(dg))
  print('number_weakly_connected_components:',co.number_weakly_connected_components(dg))

  print('Transitivity:',cl.transitivity(dg))

  return

  e=dm.eccentricity(mg)

  dprint('ecc:', e)

  cent=dm.center(mg,e=e)
  print('CENTER',cent)

  p=dm.periphery(mg,e=e)

  print('perif:', len(list(e)))

  #dprint('perif:', e)

  print('diameter:', dm.diameter(nx.Graph(mg)))
  print('radius:', dm.radius(nx.Graph(mg)))

  g = nx.Graph(dg)
  print('omega:', omega(g))
  print('sigma:', sigma(g))
    def print_Measures(self,
                       G,
                       blnCalculateDimater=False,
                       blnCalculateRadius=False,
                       blnCalculateExtremaBounding=False,
                       blnCalculateCenterNodes=False,
                       fileName_to_print=None):

        #verify if graph is connected or not
        try:
            blnGraphConnected = is_connected(G)
        except:
            blnGraphConnected = False

        no_nodes = str(len(G.nodes()))
        no_edges = str(len(G.edges()))
        print("# Nodes: " + no_nodes)
        print("# Edges: " + no_edges)

        #Calculate and print Diameter
        if blnCalculateDimater == True:
            if blnGraphConnected == True:
                diameter_value = str(distance_measures.diameter(G))
                print("Diameter: " + diameter_value)
            else:
                diameter_value = "Not possible to calculate diameter. Graph must be connected"
                print(diameter_value)

        #Calculate and print Radius
        if blnCalculateRadius == True:
            if blnGraphConnected == True:
                radius_value = str(distance_measures.radius(G))
                print("Radius: " + radius_value)
            else:
                radius_value = "Not possible to calculate radius. Graph must be connected"
                print(radius_value)

        #Calculate and print Extrema bounding
        if blnCalculateExtremaBounding == True:
            if blnGraphConnected == True:
                extrema_bounding_value = str(
                    distance_measures.extrema_bounding(G))
                print("Extrema bounding: " + extrema_bounding_value)
            else:
                extrema_bounding_value = "Not possible to calculate Extrema bounding. Graph must be connected"
                print(extrema_bounding_value)

        #Calculate and print Centers
        if blnCalculateCenterNodes == True:
            str_centers_nodes = ""
            if blnGraphConnected == True:
                centers_nodes = distance_measures.center(G)
                str_centers_nodes = str(
                    sorted(G.degree(centers_nodes),
                           key=lambda x: x[1],
                           reverse=True))
                print("Centers with their degree: " + str_centers_nodes)
            else:
                centers_nodes = "Not possible to calculate Centers. Graph must be connected"
                print(centers_nodes)

        # if file name is passed in the parameters, we save the measures into a file
        if fileName_to_print != None:
            #creates path if does not exists

            if not os.path.exists(os.path.dirname(fileName_to_print)):
                os.makedirs(os.path.dirname(fileName_to_print))

            f = open(fileName_to_print, "w")
            f.write("# Nodes: " + no_nodes + "\n")
            f.write("# Edges: " + no_edges + "\n")

            if blnCalculateDimater == True:
                f.write("Diameter: " + diameter_value + "\n")
            if blnCalculateRadius == True:
                f.write("Radius: " + radius_value + "\n")
            #if blnCalculateBaryCenter == True:
            #    f.write("Bary Center: " + barycenter_node + "\n")
            if blnCalculateExtremaBounding == True:
                f.write("Extrema bounding: " + extrema_bounding_value + "\n")
            if blnCalculateCenterNodes == True:
                f.write("Centers with their degree: " + str_centers_nodes +
                        "\n")

            f.close()
Exemple #4
0
 def getRadius(
     self
 ) -> Union[int, list[Unknown], dict[Unknown, Any], float, Any, None]:
     """
     """
     return radius(self.graph)
Exemple #5
0
    def reassignLandowners(self, graph):
        for node in graph.nodes():
            graph.node[node]["coordinates"] = self.nodeCoordinates[str(node)]
            
        '''
        if self.numLandowners == 3:
            centers = [129, 145, 487]
        if self.numLandowners == 4:
            centers = [130, 143, 455, 468]
        if self.numLandowners == 5:
            centers = [78, 96, 312, 528, 546]
        if self.numLandowners == 6:
            centers = [129, 137, 145, 479, 487, 495]
        if self.numLandowners == 7:
            centers = [77, 97, 162, 312, 487, 527, 547]
        if self.numLandowners == 8:
            centers = [153, 159, 165, 171, 453, 459, 465, 471]
        if self.numLandowners == 9:
            centers = [84, 90, 101, 123, 312, 501, 523, 534, 540]
        if self.numLandowners == 10:
            centers = [127, 132, 137, 142, 147, 477, 482, 487, 492, 497]
        '''
        
        centerNode = center(graph)[0]
        graphRadius = radius(graph)
        xCenter = graph.node[centerNode]["coordinates"]["x"]
        yCenter = graph.node[centerNode]["coordinates"]["y"]
        
        landCenters = []
        landArea = 2*math.pi/self.numLandowners
        for piece in range(self.numLandowners):
            angle = landArea*piece
            landAreaX = math.floor(xCenter + graphRadius*math.cos(angle))
            landAreaY = math.floor(yCenter + graphRadius*math.sin(angle))
            nodeNum = landAreaX*25 + landAreaY
            landCenters.append(nodeNum)

        owner = 0
        for landCenter in landCenters:
            graph.node[landCenter]["owner"] = owner
            owner = owner + 1

        for node in graph.nodes():
            distList = []
            for landCenter in landCenters:
                distance = ((graph.node[landCenter]["coordinates"]["x"] - graph.node[node]["coordinates"]["x"])**2 + (graph.node[landCenter]["coordinates"]["y"] - graph.node[node]["coordinates"]["y"])**2)**0.5
                distList.append(distance)
            graph.node[node]["owner"] = distList.index(min(distList))

        '''    
        for node in graph.nodes():
            distList = []
            for center in centers:
                distance = nx.shortest_path_length(graph, source=node, target=center)
                distList.append(distance)
            graph.node[node]["owner"] = distList.index(min(distList))
        '''

        nodeList = {}
        for owner in range(self.numLandowners):
            nodeList[owner] = []
            for node in graph.nodes():
                if graph.node[node]["owner"] == owner:
                    nodeList[owner].append(node)
        
        AreaBelongsToLandowners = []
        for owner in nodeList:
            AreaBelongsToLandowners.append(self.Cell_area*len(nodeList[owner]))
        
        return graph, nodeList, AreaBelongsToLandowners              
        data = []
        data.append(fname)
        data.append(G.number_of_nodes())
        data.append(G.number_of_edges())
        data.append(density(G))
        deg_centrality = degree_centrality(G)
        data.extend(properties_of_array(deg_centrality))
        cln_centrality = closeness_centrality(G)
        data.extend(properties_of_array(cln_centrality))
        btn_centrality = betweenness_centrality(G)
        data.extend(properties_of_array(btn_centrality))
        st_path = shortest_path(G)
        deg = [len(val) for key, val in st_path.items()]
        d = np.array(deg)
        data.extend(
            [np.min(d),
             np.max(d),
             np.median(d),
             np.mean(d),
             np.std(d)])
        try:
            data.append(diameter(G.to_undirected()))
        except:
            data.append(0)
        try:
            data.append(radius(G.to_undirected()))
        except:
            data.append(0)
        csvwriter.writerow(data)
    csvfile.close()
Exemple #7
0
def ver_medidas(G):
    print(function.info(G))
    """
    Numero minimo de nodos que deben ser removidos para desconectar G
    """
    print("Numero minimo de nodos que deben ser removidos para desconectar G :"+str(approximation.node_connectivity(G)))

    """
    average clustering coefficient of G.
    """
    print("average clustering coefficient of G: "+str(approximation.average_clustering(G)))

    """
    Densidad de un Grafo
    """
    print("Densidad de G: "+str(function.density(G)))

    """
    Assortativity measures the similarity of connections in
    the graph with respect to the node degree.
    Valores positivos de r indican que existe una correlacion entre nodos 
    con grado similar, mientras que un valor negativo indica
    correlaciones entre nodos de diferente grado
    """

    print("degree assortativity:"+str(assortativity.degree_assortativity_coefficient(G)))

    """
    Assortativity measures the similarity of connections
    in the graph with respect to the given attribute.
    """

    print("assortativity for node attributes: "+str(assortativity.attribute_assortativity_coefficient(G,"crime")))

    """
    Grado promedio vecindad
    """
    plt.plot(assortativity.average_neighbor_degree(G).values())
    plt.title("Grado promedio vecindad")
    plt.xlabel("Nodo")
    plt.ylabel("Grado")
    plt.show();

    """
    Grado de Centralidad de cada nodo
    """

    plt.plot(centrality.degree_centrality(G).values())
    plt.title("Grado de centralidad")
    plt.xlabel("Nodo")
    plt.ylabel("Centralidad")
    plt.show();


    """
    Calcular el coeficiente de agrupamiento para nodos
    """

    plt.plot(cluster.clustering(G).values())
    plt.title("coeficiente de agrupamiento")
    plt.xlabel("Nodo")
    plt.show();

    """
    Media coeficiente de Agrupamiento
    """
    print("Coeficiente de agrupamiento de G:"+str(cluster.average_clustering(G)))

    """
    Centro del grafo
    El centro de un grafo G es el subgrafo inducido por el 
    conjunto de vertices de excentricidad minima.

     La  excentricidad  de  v  in  V  se  define  como  la
     distancia maxima desde v a cualquier otro vertice del 
     grafo G siguiendo caminos de longitud minima.
    """

    print("Centro de G:"+ str(distance_measures.center(G)))

    """
    Diametro de un grafo
    The diameter is the maximum eccentricity.
    """
    print("Diametro de G:"+str(distance_measures.diameter(G)))


    """
    Excentricidad de cada Nodo
    The eccentricity of a node v is the maximum distance
    from v to all other nodes in G.
    """
    plt.plot(distance_measures.eccentricity(G).values())
    plt.title("Excentricidad de cada Nodo")
    plt.xlabel("Nodo")
    plt.show();

    """
    Periferia 
    The periphery is the set of nodes with eccentricity equal to the diameter.
    """
    print("Periferia de G:")
    print(distance_measures.periphery(G))

    """
    Radio
    The radius is the minimum eccentricity.

    """

    print("Radio de G:"+str(distance_measures.radius(G)))

    """
    PageRank calcula una clasificacion de los nodos
    en el grafico G en funcion de la estructura de 
    los enlaces entrantes. Originalmente fue disenado
    como un algoritmo para clasificar paginas web.
    """

    plt.plot(link_analysis.pagerank_alg.pagerank(G).values())
    plt.title("Puntaje de cada Nodo")
    plt.xlabel("Nodo")
    plt.show();

    """
    Coeficiente de Small World.
    A graph is commonly classified as small-world if sigma>1.

    """

    print("Coeficiente de Small World: " + str(smallworld.sigma(G)))

    """
    The small-world coefficient (omega) ranges between -1 and 1.
    Values close to 0 means the G features small-world characteristics.
    Values close to -1 means G has a lattice shape whereas values close
    to 1 means G is a random graph.
    """
    print("Omega coeficiente: "+str(smallworld.omega(G)))