File size: 14,314 Bytes
525a6df e438efd 525a6df 9a99cab 129ce22 171b613 525a6df 01c40ff 525a6df 8254f87 525a6df d50a100 525a6df 6cb6d95 b4194f8 6cb6d95 b4194f8 6cb6d95 35d3b6b 88ac4c8 6cb6d95 b4194f8 6cb6d95 88ac4c8 81983b3 88ac4c8 6cb6d95 18f229b 6cb6d95 35d3b6b d2a3523 35d3b6b d2a3523 35d3b6b 88ac4c8 81983b3 f1853ff 81983b3 c0facca b4194f8 8f216a7 b4194f8 5c71bdb 1a731a9 b4194f8 c0facca bc335c9 1a731a9 9603556 1eaab3f b4194f8 b63e42a b4194f8 1a731a9 b4194f8 b63e42a b4194f8 b63e42a b4194f8 545563d b4194f8 525a6df b63e42a b4194f8 a023ee5 9493629 b4194f8 b63e42a b4194f8 b63e42a b4194f8 b63e42a b4194f8 b63e42a b4194f8 b63e42a 525a6df 171b613 525a6df 171b613 4541211 525a6df 28e2fd0 ab80c92 545563d ab80c92 8591eb2 a332c13 171b613 525a6df 171b613 525a6df 171b613 525a6df 6d6aff3 525a6df 171b613 525a6df 6d6aff3 fd02170 f03bb31 2fe430a a332c13 171b613 51be45a 525a6df |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
import gradio as gr
import plotly.graph_objects as go
import os
from collections import defaultdict
import igraph as ig
# print(os.pwd())
species_to_imgpath = {'bird': './descendent_specific_topk_heatmap_withbb_ep=last_024+051',
'fish': './descendent_specific_topk_heatmap_withbb_ep=last_024+051',
'butterfly': './descendent_specific_topk_heatmap_withbb_ep=last_024+051',
}
# this has to be there for each species
imgname_to_filepath = {} # this ignores the extension such as .png
nodename_to_protoIDs = defaultdict(list)
for species, imgpath in species_to_imgpath.items():
for foldername in os.listdir(imgpath):
if os.path.isdir(os.path.join(imgpath, foldername)):
folderpath = os.path.join(imgpath, foldername)
for filename in os.listdir(folderpath):
if filename.endswith('png') or filename.endswith('jpg'):
filepath = os.path.join(folderpath, filename)
imgname_to_filepath[filename] = filepath
nodename = filename.split('.')[0].split('-')[0]
protoID = filename.split('.')[0].split('-')[1]
nodename_to_protoIDs[nodename].append(protoID)
class Node():
id = 0
def __init__(self, name):
self.id = Node.id
Node.id += 1
self.name = name
self.parent = None
self.children = [] # list of type Node
def add_child(child):
self.children.append(child)
name_to_node = {}
id_to_node = {}
def get_root(node):
root = node
while node:
root = node
node = node.parent
return root
def get_tree(imgpath):
for foldername in os.listdir(imgpath):
if os.path.isdir(os.path.join(imgpath, foldername)):
folderpath = os.path.join(imgpath, foldername)
node_name = foldername
child_names = list(set([filename.split('.')[0].split('-')[0] for filename in os.listdir(folderpath)]))
if node_name in name_to_node:
node = name_to_node[node_name]
else:
node = Node(node_name)
name_to_node[node_name] = node
id_to_node[node.id] = node
child_nodes = []
for child_name in child_names:
if child_name in name_to_node:
child_node = name_to_node[child_name]
else:
child_node = Node(child_name)
name_to_node[child_name] = child_node
id_to_node[child_node.id] = child_node
child_node.parent = node
child_nodes.append(child_node)
node.children = child_nodes
# To be finished
return get_root(node)
ROOT = None
def create_binary_tree_edges(root):
edges = []
prev = [root]
while len(prev) > 0:
new_prev = []
for node in prev:
# print(node.children, '\n')
edges = edges + [(node.id, child.id) for child in node.children]
new_prev = new_prev + [child for child in node.children if (len(child.children) > 0)]
prev = new_prev
# print(edges)
# print('-*'*20, '\n')
return edges
def plot_tree_using_igraph():
# Define the edges in a tree structure
# edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]
root = ROOT
edges = create_binary_tree_edges(root)
# edges = [(str(n1), str(n2)) for (n1, n2) in edges]
# print(edges)
# Create an igraph Graph from the edge list
g = ig.Graph(edges, directed=True)
# Validate the root index
if g.vcount() > 0: # Check if the graph has any vertices
root_vertex_id = 0 # This assumes that vertex '0' is the root
else:
print("The graph has no vertices.")
return None
# Use the Reingold-Tilford layout to position the nodes
try:
layout = g.layout_reingold_tilford(root=None) # Correct root specification
except Exception as e:
print(f"Error computing layout: {e}")
return None
# Edge traces
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]) # y values are inverted to make the tree top-down
edge_trace = go.Scatter(
x=edge_x, y=edge_y,
line=dict(width=0.5, color='#888'),
hoverinfo='none',
mode='lines')
# Node traces
node_x = [pos[0] for pos in layout.coords]
node_y = [-pos[1] for pos in layout.coords] # y values are inverted
node_trace = go.Scatter(
x=node_x, y=node_y,
text=[id_to_node[i].name for i in range(len(layout.coords))],
# 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"
)
# Create a Plotly figure
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),
# height=600,
# width=600,
annotations=[dict(
showarrow=False,
xref="paper", yref="paper",
x=0.005, y=-0.002 )]
))
return fig
def plot_tree_from_species(species_name):
# Define the edges in a tree structure
# edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)]
imgpath = species_to_imgpath[species_name]
print(imgpath)
root = get_tree(imgpath)
# root = ROOT
edges = create_binary_tree_edges(root)
# edges = [(str(n1), str(n2)) for (n1, n2) in edges]
# print(edges)
# Create an igraph Graph from the edge list
g = ig.Graph(edges, directed=True)
# Validate the root index
if g.vcount() > 0: # Check if the graph has any vertices
root_vertex_id = 0 # This assumes that vertex '0' is the root
else:
print("The graph has no vertices.")
return None
# Use the Reingold-Tilford layout to position the nodes
try:
layout = g.layout_reingold_tilford(root=None) # Correct root specification
except Exception as e:
print(f"Error computing layout: {e}")
return None
# Edge traces
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]) # y values are inverted to make the tree top-down
edge_trace = go.Scatter(
x=edge_x, y=edge_y,
line=dict(width=0.5, color='#888'),
hoverinfo='none',
mode='lines')
# Node traces
node_x = [pos[0] for pos in layout.coords]
node_y = [-pos[1] for pos in layout.coords] # y values are inverted
node_trace = go.Scatter(
x=node_x, y=node_y,
text=[id_to_node[i].name for i in range(len(layout.coords))],
# 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"
)
# Create a Plotly figure
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),
# height=600,
# width=600,
annotations=[dict(
showarrow=False,
xref="paper", yref="paper",
x=0.005, y=-0.002 )]
))
return gr.Plot(fig)
def set_nodename_to_protoIDs(species_name):
global nodename_to_protoIDs
imgpath = species_to_imgpath[species_name]
for foldername in os.listdir(imgpath):
if os.path.isdir(os.path.join(imgpath, foldername)):
folderpath = os.path.join(imgpath, foldername)
for filename in os.listdir(folderpath):
if filename.endswith('png') or filename.endswith('jpg'):
filepath = os.path.join(folderpath, filename)
imgname_to_filepath[filename] = filepath
nodename = filename.split('.')[0].split('-')[0]
protoID = filename.split('.')[0].split('-')[1]
nodename_to_protoIDs[nodename].append(protoID)
def get_protoIDs(nodename):
return gr.Dropdown(choices=nodename_to_protoIDs[nodename], interactive=True)
def get_nodenames(species_name):
return gr.Dropdown(choices=list(nodename_to_protoIDs.keys()), interactive=True)
def get_image(nodename, protoID):
imgname = '-'.join([nodename, protoID]) + '.png'
filepath = imgname_to_filepath[imgname]
return gr.Image(filepath)
with gr.Blocks() as demo:
imgpath = species_to_imgpath['bird']
print(imgpath)
ROOT = get_tree(imgpath)
print(ROOT.name)
gr.Markdown("## Interactive Tree and Image Display")
# with gr.Row():
# tree_output = gr.Plot(plot_tree_using_igraph) # Connect the function directly
# with gr.Row():
# with gr.Column():
# dropdown_1_nodename = gr.Dropdown(label="Select a node name", choices=list(nodename_to_protoIDs.keys()))
# dropdown_1_protos = gr.Dropdown(label="Select a prototype ID", choices=[], allow_custom_value=True)
# image_output_1 = gr.Image()
# with gr.Column():
# dropdown_2_nodename = gr.Dropdown(label="Select a node name", choices=list(nodename_to_protoIDs.keys()))
# dropdown_2_protos = gr.Dropdown(label="Select a prototype ID", choices=[], allow_custom_value=True)
# image_output_2 = gr.Image()
# dropdown_1_nodename.change(get_protoIDs, dropdown_1_nodename, dropdown_1_protos)
# dropdown_1_protos.change(get_image, [dropdown_1_nodename, dropdown_1_protos], image_output_1)
# dropdown_2_nodename.change(get_protoIDs, dropdown_2_nodename, dropdown_2_protos)
# dropdown_2_protos.change(get_image, [dropdown_2_nodename, dropdown_2_protos], image_output_2)
with gr.Row():
dropdown_species = gr.Dropdown(label="Select a species", choices=list(species_to_imgpath.keys()))
with gr.Row():
tree_output = gr.Plot() # Connect the function directly
with gr.Row():
with gr.Column():
dropdown_1_nodename = gr.Dropdown(label="Select a node name", choices=[])
dropdown_1_protos = gr.Dropdown(label="Select a prototype ID", choices=[], allow_custom_value=True)
image_output_1 = gr.Image()
with gr.Column():
dropdown_2_nodename = gr.Dropdown(label="Select a node name", choices=[])
dropdown_2_protos = gr.Dropdown(label="Select a prototype ID", choices=[], allow_custom_value=True)
image_output_2 = gr.Image()
dropdown_species.change(plot_tree_from_species, dropdown_species, tree_output)
# dropdown_species.change(set_nodename_to_protoIDs)
dropdown_species.change(get_nodenames, dropdown_species, dropdown_1_nodename)
dropdown_species.change(get_nodenames, dropdown_species, dropdown_2_nodename)
dropdown_1_nodename.change(get_protoIDs, dropdown_1_nodename, dropdown_1_protos)
dropdown_1_protos.change(get_image, [dropdown_1_nodename, dropdown_1_protos], image_output_1)
dropdown_2_nodename.change(get_protoIDs, dropdown_2_nodename, dropdown_2_protos)
dropdown_2_protos.change(get_image, [dropdown_2_nodename, dropdown_2_protos], image_output_2)
# imgpath = species_to_imgpath['bird']
# print(imgpath)
# ROOT = get_tree(imgpath)
# print(ROOT.name)
# gr.Markdown("## Interactive Tree and Image Display")
# with gr.Row():
# tree_output = gr.Plot(plot_tree_using_igraph) # Connect the function directly
# with gr.Row():
# with gr.Column():
# dropdown_3_nodename = gr.Dropdown(label="Select a node name", choices=list(nodename_to_protoIDs.keys()))
# dropdown_3_protos = gr.Dropdown(label="Select a prototype ID", choices=[], allow_custom_value=True)
# image_output_3 = gr.Image()
# with gr.Column():
# dropdown_4_nodename = gr.Dropdown(label="Select a node name", choices=list(nodename_to_protoIDs.keys()))
# dropdown_4_protos = gr.Dropdown(label="Select a prototype ID", choices=[], allow_custom_value=True)
# image_output_4 = gr.Image()
# dropdown_3_nodename.change(get_protoIDs, dropdown_3_nodename, dropdown_3_protos)
# dropdown_3_protos.change(get_image, [dropdown_3_nodename, dropdown_3_protos], image_output_3)
# dropdown_4_nodename.change(get_protoIDs, dropdown_4_nodename, dropdown_4_protos)
# dropdown_4_protos.change(get_image, [dropdown_4_nodename, dropdown_4_protos], image_output_4)
# Initialize with placeholder images
# image_output_1.update(display_image_based_on_dropdown_1)
# image_output_2.update(display_image_based_on_dropdown_2)
demo.launch()
|