jdillard / sphinx-visualized

Visualization generator for Sphinx
https://sphinx-visualized.readthedocs.io/en/latest/
MIT License
5 stars 0 forks source link

Use GraphSON for compatibility with tinkerpop #10

Open jdillard opened 5 hours ago

jdillard commented 5 hours ago

Example code:

Create GraphJSON

from gremlin_python.structure.graph import Graph
from gremlin_python.structure.io.graphson import GraphSONWriter

# Initialize the graph
graph = Graph()

# Add vertices
g = graph.traversal()
alice = g.addV("person").property("name", "Alice").property("age", 29).next()
bob = g.addV("person").property("name", "Bob").property("age", 35).next()
city = g.addV("location").property("name", "New York").next()

# Add edges
g.addE("lives_in").from_(alice).to(city).property("since", 2015).iterate()
g.addE("knows").from_(alice).to(bob).property("since", 2010).iterate()

# Export the graph to visualize or store
writer = GraphSONWriter()
with open("graph.json", "w") as f:
    graphson_data = writer.writeObject(graph)
    f.write(graphson_data)
    print("Graph exported to graph.json")
    print(graphson_data)

Convert GraphJSON to JSON

import json

# Load the GraphSON file
with open("graph.json", "r") as f:
    graphson = json.load(f)

# Simplify the structure
graph = graphson["@value"]

# Process vertices
vertices = []
for vertex in graph["vertices"]:
    simplified_vertex = {
        "id": vertex["id"],
        "label": vertex["label"],
    }
    # Flatten properties
    for key, value in vertex["properties"].items():
        simplified_vertex[key] = value[0]["value"]
    vertices.append(simplified_vertex)

# Process edges
edges = []
for edge in graph["edges"]:
    simplified_edge = {
        "id": edge["id"],
        "label": edge["label"],
        "source": edge["outV"],
        "target": edge["inV"],
    }
    # Add edge properties
    simplified_edge.update(edge.get("properties", {}))
    edges.append(simplified_edge)

# Create simplified JSON structure
simplified_graph = {
    "vertices": vertices,
    "edges": edges
}

# Save to a new JSON file
with open("graph_simplified.json", "w") as f:
    json.dump(simplified_graph, f, indent=4)

print("Simplified graph saved to graph_simplified.json")
jdillard commented 4 hours ago

Possibly use something vs custom d3.js: