|
import igraph as ig |
|
import plotly.graph_objects as go |
|
|
|
import gradio as gr |
|
import plotly.graph_objects as go |
|
import os |
|
from collections import defaultdict |
|
import igraph as ig |
|
|
|
|
|
|
|
|
|
|
|
class binNode(): |
|
def __init__(self, id) -> None: |
|
self.id = id |
|
self.child1 = None |
|
self.child2 = None |
|
|
|
def create_binary_tree_edges(depth): |
|
edges = [] |
|
|
|
|
|
id = 0 |
|
root = binNode(id) |
|
prev = [root] |
|
for _ in range(depth): |
|
new_prev = [] |
|
for node in prev: |
|
id += 1 |
|
node.child1 = binNode(id) |
|
edges.append((node.id, node.child1.id)) |
|
id += 1 |
|
node.child2 = binNode(id) |
|
edges.append((node.id, node.child2.id)) |
|
new_prev += [node.child1, node.child2] |
|
prev = new_prev |
|
|
|
return edges |
|
|
|
|
|
|
|
def plot_tree_using_igraph(): |
|
|
|
|
|
edges = create_binary_tree_edges(8) |
|
|
|
|
|
print(edges) |
|
|
|
|
|
g = ig.Graph(edges, directed=True) |
|
|
|
|
|
if g.vcount() > 0: |
|
root_vertex_id = 0 |
|
else: |
|
print("The graph has no vertices.") |
|
return None |
|
|
|
|
|
try: |
|
layout = g.layout_reingold_tilford(root=None) |
|
except Exception as e: |
|
print(f"Error computing layout: {e}") |
|
return None |
|
|
|
|
|
edge_x = [] |
|
edge_y = [] |
|
for edge in edges: |
|
start_idx, end_idx = edge |
|
x0, y0 = layout.coords[start_idx] |
|
x1, y1 = layout.coords[end_idx] |
|
edge_x.extend([x0, x1, None]) |
|
edge_y.extend([-y0, -y1, None]) |
|
|
|
edge_trace = go.Scatter( |
|
x=edge_x, y=edge_y, |
|
line=dict(width=0.5, color='#888'), |
|
hoverinfo='none', |
|
mode='lines') |
|
|
|
|
|
node_x = [pos[0] for pos in layout.coords] |
|
node_y = [-pos[1] for pos in layout.coords] |
|
|
|
node_trace = go.Scatter( |
|
x=node_x, y=node_y, |
|
text=["Node {}".format(i) for i in range(len(layout.coords))], |
|
mode='markers+text', |
|
hoverinfo='text', |
|
marker=dict( |
|
showscale=False, |
|
size=10, |
|
color='LightSkyBlue' |
|
), |
|
textposition="bottom center" |
|
) |
|
|
|
|
|
fig = go.Figure(data=[edge_trace, node_trace], |
|
layout=go.Layout( |
|
title='<b>Tree Layout with iGraph and Plotly</b>', |
|
titlefont_size=16, |
|
showlegend=False, |
|
hovermode='closest', |
|
margin=dict(b=0, l=0, r=0, t=50), |
|
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), |
|
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False), |
|
|
|
|
|
annotations=[dict( |
|
showarrow=False, |
|
xref="paper", yref="paper", |
|
x=0.005, y=-0.002 )] |
|
)) |
|
|
|
return fig |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with gr.Blocks() as demo: |
|
|
|
gr.Markdown("## Interactive Tree and Image Display") |
|
with gr.Row(): |
|
tree_output = gr.Plot(plot_tree_using_igraph, scale=2) |
|
|
|
|
|
demo.launch() |
|
|