| import json |
| import networkx as nx |
| import matplotlib.pyplot as plt |
|
|
| |
| index_file_path = "graphs/index.json" |
|
|
| |
| def load_index_data(file_path): |
| """Load the index.json file and parse its contents.""" |
| with open(file_path, "r") as file: |
| data = json.load(file) |
| return data |
|
|
| def build_graph(data): |
| """Builds a directed graph based on entities and relationships.""" |
| G = nx.DiGraph() |
|
|
| |
| for entity_id, entity_info in data["entities"].items(): |
| label = entity_info.get("label", entity_id) |
| |
| G.add_node(entity_id, label=label, **{k: v for k, v in entity_info.items() if k != "label"}) |
|
|
| |
| for relationship in data["relationships"]: |
| source = relationship["source"] |
| target = relationship["target"] |
| relationship_label = relationship["attributes"].get("relationship", "related_to") |
| G.add_edge(source, target, label=relationship_label) |
|
|
| return G |
|
|
| |
| def visualize_graph(G, title="340B Program - Inferred Contextual Relationships"): |
| """Visualizes the graph with nodes and relationships.""" |
| pos = nx.spring_layout(G) |
|
|
| |
| plt.figure(figsize=(15, 10)) |
| nx.draw_networkx_nodes(G, pos, node_size=3000, node_color="lightblue", alpha=0.7) |
| nx.draw_networkx_labels(G, pos, font_size=10, font_color="black", font_weight="bold") |
|
|
| |
| nx.draw_networkx_edges(G, pos, arrowstyle="->", arrowsize=20, edge_color="gray", connectionstyle="arc3,rad=0.1") |
| edge_labels = {(u, v): d["label"] for u, v, d in G.edges(data=True)} |
| nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color="red", font_size=9) |
|
|
| |
| plt.title(title) |
| plt.axis("off") |
| plt.show() |
|
|
| |
| if __name__ == "__main__": |
| |
| data = load_index_data(index_file_path) |
|
|
| |
| G = build_graph(data) |
|
|
| |
| visualize_graph(G) |