コード例 #1
0
def estimate_edges(G, u, run):
    # Current timestep
    t = 0
    # Current number of returns to start vertex (u)
    k = 0
    # Time of k-th return to start vertex
    Z_total = 0
    # Degree of start vertex
    deg_u = G.degree(u)

    # Build the transition matrix P for the simple random walk
    # w(u,v) <- 1
    P = adjacency_matrix(G)
    P = normalize(P, norm='l1', axis=1)
    eigenvals, eigenvecs = eigs(P, k=2, which='LM')
    lambda_2 = float(sorted(eigenvals)[-2])

    Z_uu = 1.0 / (1.0 - lambda_2)
    pi_u = float(deg_u) / G.number_of_edges()
    ct_factor = (2 * Z_uu + pi_u - 1.0) / (pi_u**2)

    # Estimates of the number of edges, one for each return time
    m_est = []
    # Std. dev estimates using Z_uu
    m_std_Zuu = []
    # Return times
    Tus = []
    # Start vertex
    vertex = u
    while k < 100000:
        # Simple random walk
        i = random.randint(0, len(G.neighbors(vertex)) - 1)
        vertex = G.neighbors(vertex)[i]

        # Check if we have a new return to start vertex
        if vertex == u:
            # Add new return time
            Tus.append(t - Z_total)
            Z_total = t
            k += 1

            # Add new estimate of m (number of edges)
            curr_est = float(Z_total * deg_u) / (2 * k)
            m_est.append(curr_est)
            # Add new std. dev
            curr_std_Zuu = math.sqrt(float(deg_u**2 / (4 * k)) * ct_factor)
            m_std_Zuu.append(curr_std_Zuu)
            if k % 100 == 0:
                print "Estimate of m at", k, ":", curr_est, "std:", curr_std_Zuu

        # Increase timestep
        t += 1

    m_est = np.array(m_est)
    m_std_Zuu = np.array(m_std_Zuu)
    Tus = np.array(Tus)

    m_est.tofile('m_est_' + str(run) + '.npy')
    m_std_Zuu.tofile('m_std_Zuu_' + str(run) + '.npy')
    Tus.tofile('Tus' + str(run) + '.npy')
コード例 #2
0
ファイル: routing_gym.py プロジェクト: jcformanek/routing_gym
 def __init__(self, nx_g, k=4, max_b=200):
     self.k = k
     self.max_bandwidth = max_b
     self.nx_g = nx_g
     self.adjacency_matrix = adjacency_matrix(self.nx_g)
     self.n = self.nx_g.number_of_nodes()
     self.traffic_matrix = None
     self.actions = None
     self.shortest_paths = None
     self.bandwidth = None
     self.done = True
     self.dgl_g = dgl.Graph(self.nx_g)
コード例 #3
0
 def __init__(self, grafo=None, v=0):
     if grafo is not None:
         if type(grafo) == np.ndarray:
             self.adjacencias = grafo
         elif type(grafo) == dict:
             v = len(grafo)
             self.adjacencias = np.zeros((v, v))
             for origem in grafo:
                 for destino, distancia in grafo[origem]:
                     self.adjacencias[origem][destino] = distancia
         elif type(grafo) == StandardProblem:
             self.adjacencias = adjacency_matrix(
                 grafo.get_graph()).toarray()
         else:
             raise Exception(
                 'Tipo de grafo Inválido. O grafo deve ser um array ' +
                 'numpy, um dicionario, um grafo TSPLIB95 ou None')
     else:
         self.adjacencias = np.zeros((v, v))
コード例 #4
0
def graph_stats(G):
    """
    Compute all the graph-related statistics in the features.

    Note that since the graph is always fully connected, all of these are the
    weighted versions. For this reason, many of these functions use the
    implementations in bctpy rather than NetworkX.
    """
    # Local measures
    clustering_dict = clustering(G, weight='weight')
    adjacency = np.array(adjacency_matrix(G).todense())
    betweenness_centrality_dict = betweenness_centrality(G, weight='weight')
    paths = shortest_path_length(G, weight='weight')
    eccentricities = [max(dists.values()) for (source, dists) in sorted(paths)]
    local_measures = np.concatenate(
        [[v for (k, v) in sorted(clustering_dict.items())],
         [v for (k, v) in sorted(betweenness_centrality_dict.items())],
         eccentricities])
    graph_diameter = max(eccentricities)
    graph_radius = min(eccentricities)
    aspl = average_shortest_path_length(G, weight='weight')
    global_measures = np.array([graph_diameter, graph_radius, aspl])
    return np.concatenate([local_measures, global_measures])
コード例 #5
0
nx.draw(G, with_labels=True)

# + [markdown] pycharm={"name": "#%% md\n"}
# It looks like `scipy.sparse.csgraph` has some of the reordering algorithms mentioned in the lecture notes.
# At least:
#
# ### 1. BFS levelset
# _This could also be 2. BFS queue, depending on the actual implementation?_
#
# Note that `i_start` is the index of the adjacency matrix.
# Thus, even though we have indexed our nodes starting at 1, in the adjacency matrix the indices start from 0 (as they always do in Python).

# + pycharm={"name": "#%%\n"}
import scipy.sparse.csgraph as csgraph

csgraph.breadth_first_order(gm.adjacency_matrix(G),
                            i_start=0,
                            return_predecessors=False)

# + [markdown] pycharm={"name": "#%% md\n"}
# ### 4. Reverse Cuthill McKee

# + pycharm={"name": "#%%\n"}
csgraph.reverse_cuthill_mckee(gm.adjacency_matrix(G))

# + [markdown] pycharm={"name": "#%% md\n"}
# # Grids
#
# ## 450. Triangular grid

# + pycharm={"name": "#%%\n"}
コード例 #6
0
# Electron hopping constant - energy parameter of the TB model.
t = 2.0

# Use NetworkX to construct the periodic square lattice (graph)
lat = grid_2d_graph(N, N, periodic=True)

# Create lists of indices for electronic spin-up and spin-down operators.
# lat.nodes() returns a list of N^2 pairs of site indices (x, y).
indices_up = [(x, y, "up") for x, y in lat.nodes()]
indices_dn = [(x, y, "down") for x, y in lat.nodes()]

# A sum of tight-binding Hamiltonians for both spins.
# The hopping matrix passed to tight_binding() is proportional to the
# adjacency matrix of the lattice.
hopping_matrix = -t * adjacency_matrix(lat).todense()
H_e = tight_binding(hopping_matrix, indices=indices_up) \
    + tight_binding(hopping_matrix, indices=indices_dn)

#
# Hamiltonian of phonons localized at lattice sites.
#

# Frequency of the localized phonon.
w0 = 0.5

# A lists of indices for bosonic operators, simply the (x, y) pairs
indices_phonon = lat.nodes()

# All N^2 phonons have the same frequency
phonon_freqs = w0 * np.ones(N ** 2)
コード例 #7
0
def test_tsplib95_G():
    grafo = tsplib95.load('tsp_files/si535.tsp')
    matriz_distancias = adjacency_matrix(grafo.get_graph()).toarray()
    g = G(grafo=grafo)
    assert np.allclose(g.adjacencias, matriz_distancias)
コード例 #8
0
 def _get_adjacency_matrix(self, nodes, weight=None):
     return adjacency_matrix(self.graph, nodelist=nodes, weight=weight)