Pometry / Raphtory

Scalable graph analytics database powered by a multithreaded, vectorized temporal engine, written in Rust
https://raphtory.com
GNU General Public License v3.0
335 stars 54 forks source link

Add graph.adjacency_matrix function #1296

Open Haaroon opened 1 year ago

Haaroon commented 1 year ago

allows user to convert the graph into an adjacency matrix

With an extra todense() function

D4rkisek commented 4 months ago

This is how I turned the Raphtory graph into adjacency matrices in Python:

import numpy as np

def transform_into_adjacency_matrix(graph, node_index):
    """Generates an adjacency matrix for the graph using a global node index."""
    adjacency_matrix = np.zeros((len(node_index), len(node_index)), dtype=int)
    for edge in graph.edges:
        src_index = node_index[edge.src.name]
        dst_index = node_index[edge.dst.name]
        adjacency_matrix[src_index, dst_index] = 1
    return adjacency_matrix

# Step 1: Identify all unique vertices
all_vertices = set()
for windowed_graph in graph.rolling(window=60000): # 1 minute
    for vertex in windowed_graph.vertices:
        all_vertices.add(vertex.name)

# Create a global index for all vertices
node_index = {node_name: i for i, node_name in enumerate(list(all_vertices))}

# Step 2: Generate adjacency matrices with consistent dimensions
A_dict = {}
i = 0
for windowed_graph in graph.rolling(window=60000): # 1 minute
    i += 1
    adjacency_matrix = transform_into_adjacency_matrix(windowed_graph, node_index)
    A_dict[i] = adjacency_matrix

print(A_dict)

{1: array([[1, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]]), 2: array([[1, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]]), 3: array([[1, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]]), 4: array([[1, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]]), 5: array([[1, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]]), 6: array([[1, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]])}

I believe this may not be the most optimal solution, however, this can be used as a starting point.

miratepuffin commented 3 weeks ago

Hi @D4rkisek thanks for this! It is something we are going to be looking at soon and this shall be a great help :)