Spaces:
Running
Running
File size: 22,369 Bytes
9ee6f68 | 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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 | # utils/visualization_tools.py
"""
Visualization tools for scene graph trees and tasks
"""
import os
import json
from src.core.gen_scene_graph import EIGHT_DIRECTIONS
import graphviz
from typing import Dict, Any, List, Optional, Union
from pathlib import Path
import glog
class SceneGraphVisualizer:
"""Scene graph tree visualization tool"""
def __init__(self, output_dir: str = "visualizations"):
"""
Initialize the visualizer
Args:
output_dir: Directory to save visualization files
"""
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
def export_tree_to_json(self, tree_root, output_file: str = "scene_graph") -> str:
"""
Export scene graph tree to JSON format
Args:
tree_root: Root node of the tree (should have 'to_dict' method)
output_file: Output file name
Returns:
Path to generated file
"""
tree_dict = {"name": tree_root.name, "depth": tree_root.depth, "children": []}
output_path = self.output_dir / output_file
def add_node_recursive(node):
"""Recursively convert nodes to dict"""
node_dict = {
"name": getattr(node, "name", str(node)),
"depth": getattr(node, "depth", None),
"children": [],
"neighbors": [],
"refined_receptacles": [],
"raw_receptacles": [],
"heading": [],
}
if hasattr(node, "children"):
for child in node.children:
node_dict["children"].append(add_node_recursive(child))
# EIGHT_DIRECTIONS = [
# 'rear',
# 'rear-left',
# 'left',
# 'front-left',
# 'front',
# 'front-right',
# 'right','rear-right'
# ]
if hasattr(node, "free_space"):
for dir in range(len(EIGHT_DIRECTIONS)):
if (
node.free_space
and node.free_space[dir]
and "Objects" in node.free_space[dir]
):
neighbor_names = [
getattr(obj, "name", str(obj))
for obj in node.free_space[dir]["Objects"]
]
if len(neighbor_names) > 0:
if node.name != tree_root.name:
node_dict["neighbors"].append(
{EIGHT_DIRECTIONS[dir]: neighbor_names}
)
node_dict["refined_receptacles"].append(
{
EIGHT_DIRECTIONS[dir]: [
point.tolist()
for point in node.free_space[dir][
"Critical_space"
]
]
}
)
node_dict["raw_receptacles"].append(
{
EIGHT_DIRECTIONS[dir]: [
point.tolist()
for point in node.free_space[dir][
"Available_space"
]
]
}
)
node_dict["heading"] = {EIGHT_DIRECTIONS[dir]: node.heading}
return node_dict
tree_dict = add_node_recursive(tree_root)
with open(f"{output_path}.json", "w", encoding="utf-8") as f:
json.dump(tree_dict, f, indent=2, ensure_ascii=False)
return str(output_path)
def export_tree_to_dot(
self,
tree_root,
output_file: str = "scene_graph",
format: str = "png",
include_properties: bool = True,
max_depth: Optional[int] = None,
) -> str:
"""
Export scene graph tree to DOT format and render
Args:
tree_root: Root node of the tree (should have 'children' attribute)
output_file: Output file name (without extension)
format: Output format ('png', 'pdf', 'svg', etc.)
include_properties: Whether to include node properties in visualization
max_depth: Maximum depth to visualize (None for all)
Returns:
Path to generated file
"""
dot = graphviz.Digraph(comment="Scene Graph Tree")
dot.attr(rankdir="TB") # Top to bottom layout
dot.attr("node", shape="box", style="rounded,filled", fontname="Arial")
dot.attr("edge", fontname="Arial")
# Color scheme for different node types/depths
colors = [
"lightblue",
"lightgreen",
"lightcoral",
"lightyellow",
"lightpink",
"lightgray",
"lightcyan",
"lavender",
]
def add_node_recursive(node, depth: int = 0, parent_id: str = None):
"""Recursively add nodes to the graph"""
if max_depth is not None and depth > max_depth:
return
# Generate unique node ID
node_id = f"node_{id(node)}"
# Prepare node label
node_name = getattr(node, "name", str(node))
label_parts = [node_name]
if include_properties:
# Add node properties to label
properties = []
# Check for common attributes
if hasattr(node, "depth"):
properties.append(f"Depth: {node.depth}")
if hasattr(node, "entity_config") and node.entity_config:
if "motion_type" in node.entity_config:
properties.append(
f"Motion: {node.entity_config['motion_type']}"
)
if hasattr(node, "bbox") and node.bbox:
bbox_str = f"BBox: {node.bbox.get('x_length', 0):.2f}×{node.bbox.get('y_length', 0):.2f}×{node.bbox.get('z_length', 0):.2f}"
properties.append(bbox_str)
if hasattr(node, "own_platform") and node.own_platform:
properties.append(f"Platforms: {len(node.own_platform)}")
if properties:
label_parts.extend(properties)
label = "\\n".join(label_parts)
# Choose color based on depth or node type
color = colors[depth % len(colors)]
# Special coloring for specific node types
if hasattr(node, "removed") and node.removed:
color = "lightgray"
elif hasattr(node, "depth"):
if node.depth == 0:
color = "gold" # Root node
elif node.depth == 1:
color = "lightblue" # Ground objects
else:
color = "lightgreen" # Higher level objects
# Add node to graph
dot.node(node_id, label, fillcolor=color)
# Add edge from parent
if parent_id:
dot.edge(parent_id, node_id)
# Process children
if hasattr(node, "children"):
for child in node.children:
add_node_recursive(child, depth + 1, node_id)
elif hasattr(node, "all_children"):
for child in node.all_children:
add_node_recursive(child, depth + 1, node_id)
# Start recursive traversal
add_node_recursive(tree_root)
# Save and render
output_path = self.output_dir / output_file
dot.render(str(output_path), format=format, cleanup=True)
# Also save the DOT source
dot_file = output_path.with_suffix(".dot")
with open(dot_file, "w") as f:
f.write(dot.source)
glog.info(f"Scene graph visualization saved to: {output_path}.{format}")
return str(output_path.with_suffix(f".{format}"))
def export_full_tree(
self, scene_graph, output_file: str = "full_scene_graph"
) -> str:
"""
Export the complete scene graph tree
Args:
scene_graph: Scene graph tree object with nodes dictionary
output_file: Output file name
Returns:
Path to generated file
"""
if not hasattr(scene_graph, "nodes"):
raise ValueError("Scene graph tree must have 'nodes' attribute")
dot = graphviz.Digraph(comment="Complete Scene Graph")
dot.attr(rankdir="TB")
dot.attr("node", shape="box", style="rounded,filled", fontname="Arial")
dot.attr("edge", fontname="Arial")
# Add all nodes
for node_name, node in scene_graph.nodes.items():
# Prepare node label
label_parts = [node_name]
# Add properties
properties = []
if hasattr(node, "depth"):
properties.append(f"D:{node.depth}")
if hasattr(node, "removed") and node.removed:
properties.append("REMOVED")
if hasattr(node, "own_platform") and node.own_platform:
properties.append(f"P:{len(node.own_platform)}")
if properties:
label_parts.append(" | ".join(properties))
label = "\\n".join(label_parts)
# Color based on depth and status
if hasattr(node, "removed") and node.removed:
color = "lightgray"
elif hasattr(node, "depth"):
if node.depth == 0:
color = "gold"
elif node.depth == 1:
color = "lightblue"
else:
color = "lightgreen"
else:
color = "white"
dot.node(node_name, label, fillcolor=color)
# Add edges based on parent-child relationships
for node_name, node in scene_graph.nodes.items():
if hasattr(node, "parent") and node.parent:
dot.edge(node.parent.name, node_name)
# Render
output_path = self.output_dir / output_file
dot.render(str(output_path), format="png", cleanup=True)
# Save DOT source
dot_file = output_path.with_suffix(".dot")
with open(dot_file, "w") as f:
f.write(dot.source)
glog.info(f"Complete scene graph saved to: {output_path}.png")
return str(output_path.with_suffix(".png"))
class TaskVisualizer:
"""Task visualization and analysis tool"""
def __init__(self, output_dir: str = "visualizations/tasks"):
"""
Initialize the task visualizer
Args:
output_dir: Directory to save task analysis files
"""
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
def export_task_info(
self, task, task_id: int, scene_graph=None, output_file: str = None
) -> str:
"""
Export detailed task information
Args:
task: Task object
task_id: Task identifier
scene_graph: Scene graph tree for context
output_file: Output file name (auto-generated if None)
Returns:
Path to generated file
"""
if output_file is None:
output_file = f"task_{task_id}_info.txt"
output_path = self.output_dir / output_file
with open(output_path, "w", encoding="utf-8") as f:
f.write(f"=== TASK {task_id} INFORMATION ===\n\n")
# Basic task information
f.write("1. TASK DESCRIPTION:\n")
if hasattr(task, "__repr_rough__"):
f.write(f" {task.__repr_rough__()}\n\n")
elif hasattr(task, "__str__"):
f.write(f" {str(task)}\n\n")
else:
f.write(f" {repr(task)}\n\n")
# Task type and properties
f.write("2. TASK PROPERTIES:\n")
if hasattr(task, "type"):
f.write(f" Type: {task.type}\n")
if hasattr(task, "item") and task.item:
f.write(f" Item: {getattr(task.item, 'name', str(task.item))}\n")
if hasattr(task, "destination") and task.destination:
f.write(
f" Destination: {getattr(task.destination, 'name', str(task.destination))}\n"
)
if hasattr(task, "reference_objects") and task.reference_objects:
ref_names = [
getattr(obj, "name", str(obj)) for obj in task.reference_objects
]
f.write(f" Reference Objects: {', '.join(ref_names)}\n")
# Ambiguity check
if scene_graph and hasattr(task, "is_ambiguous"):
is_ambiguous = task.is_ambiguous(scene_graph)
f.write(f" Is Ambiguous: {is_ambiguous}\n")
task_level = 2 if is_ambiguous else 1
f.write(f" Task Level: Level {task_level}\n")
f.write("\n")
# Primitive information
f.write("3. TASK PRIMITIVES:\n")
if hasattr(task, "primitive"):
primitive = task.primitive
if isinstance(primitive, dict):
for key, value in primitive.items():
f.write(f" {key}: {value}\n")
else:
f.write(f" {primitive}\n")
else:
f.write(" No primitive information available\n")
f.write("\n")
# Additional task details
f.write("4. DETAILED ANALYSIS:\n")
# Object positions and properties
if hasattr(task, "item") and task.item:
f.write(f" Item Details:\n")
item = task.item
if hasattr(item, "entity_config") and item.entity_config:
config = item.entity_config
if "centroid_translation" in config:
pos = config["centroid_translation"]
f.write(
f" Position: ({pos['x']:.2f}, {pos['y']:.2f}, {pos['z']:.2f})\n"
)
if "bbox" in config and config["bbox"] != "deprecated":
bbox = config["bbox"]
if isinstance(bbox, dict):
f.write(
f" BBox: {bbox.get('x_length', 0):.2f}×{bbox.get('y_length', 0):.2f}×{bbox.get('z_length', 0):.2f}\n"
)
if "motion_type" in config:
f.write(f" Motion Type: {config['motion_type']}\n")
if hasattr(task, "destination") and task.destination:
f.write(f" Destination Details:\n")
dest = task.destination
if hasattr(dest, "entity_config") and dest.entity_config:
config = dest.entity_config
if "centroid_translation" in config:
pos = config["centroid_translation"]
f.write(
f" Position: ({pos['x']:.2f}, {pos['y']:.2f}, {pos['z']:.2f})\n"
)
# Free space analysis
if hasattr(task, "item") and task.item and hasattr(task.item, "free_space"):
f.write(" Free Space Analysis:\n")
for direction, space_info in enumerate(task.item.free_space):
if space_info and "Objects" in space_info:
objects = space_info["Objects"]
if objects:
obj_names = [
getattr(obj, "name", str(obj)) for obj in objects
]
f.write(
f" Direction {direction}: {', '.join(obj_names)}\n"
)
glog.info(f"Task {task_id} information saved to: {output_path}")
return str(output_path)
def export_task_batch_summary(
self,
tasks: List,
scene_graph=None,
output_file: str = "task_batch_summary.json",
) -> str:
"""
Export summary of multiple tasks
Args:
tasks: List of task objects
scene_graph: Scene graph tree for context analysis
output_file: Output file name
Returns:
Path to generated file
"""
output_path = self.output_dir / output_file
summary = {
"total_tasks": len(tasks),
"task_types": {},
"ambiguity_stats": {"level_1": 0, "level_2": 0},
"tasks": [],
}
for i, task in enumerate(tasks):
task_info = {
"id": i,
"description": getattr(task, "__repr_rough__", lambda: str(task))(),
"type": str(getattr(task, "type", "Unknown")),
"item": getattr(getattr(task, "item", None), "name", "Unknown"),
"destination": getattr(
getattr(task, "destination", None), "name", "Unknown"
),
}
# Type statistics
task_type = task_info["type"]
summary["task_types"][task_type] = (
summary["task_types"].get(task_type, 0) + 1
)
# Ambiguity analysis
if scene_graph and hasattr(task, "is_ambiguous"):
is_ambiguous = task.is_ambiguous(scene_graph)
task_info["is_ambiguous"] = is_ambiguous
task_info["level"] = 2 if is_ambiguous else 1
if is_ambiguous:
summary["ambiguity_stats"]["level_2"] += 1
else:
summary["ambiguity_stats"]["level_1"] += 1
# Primitive information
if hasattr(task, "primitive"):
task_info["primitive"] = task.primitive
summary["tasks"].append(task_info)
# Save summary
with open(output_path, "w", encoding="utf-8") as f:
json.dump(summary, f, indent=2, ensure_ascii=False)
glog.info(f"Task batch summary saved to: {output_path}")
return str(output_path)
class VisualizationManager:
"""Main visualization manager that combines all visualization tools"""
def __init__(self, base_output_dir: str = "visualizations"):
"""
Initialize the visualization manager
Args:
base_output_dir: Base directory for all visualizations
"""
self.base_dir = Path(base_output_dir)
self.base_dir.mkdir(parents=True, exist_ok=True)
self.scene_visualizer = SceneGraphVisualizer(
str(self.base_dir / "scene_graphs")
)
self.task_visualizer = TaskVisualizer(str(self.base_dir / "tasks"))
def visualize_scene_and_tasks(
self, scene_graph, tasks: List, session_name: str = "session"
) -> Dict[str, str]:
"""
Complete visualization of scene graph and tasks
Args:
scene_graph: Scene graph tree object
tasks: List of tasks
session_name: Name for this visualization session
Returns:
Dictionary with paths to generated files
"""
results = {}
# Create session directory
session_dir = self.base_dir / session_name
session_dir.mkdir(exist_ok=True)
# Visualize scene graph
try:
scene_file = self.scene_visualizer.export_full_tree(
scene_graph, f"{session_name}_scene_graph"
)
results["scene_graph"] = scene_file
except Exception as e:
glog.error(f"Failed to visualize scene graph: {e}")
# Export task summary
try:
task_summary = self.task_visualizer.export_task_batch_summary(
tasks, scene_graph, f"{session_name}_task_summary.json"
)
results["task_summary"] = task_summary
except Exception as e:
glog.error(f"Failed to export task summary: {e}")
# Export individual task details (for first 10 tasks as example)
task_files = []
for i, task in enumerate(tasks[:10]):
try:
task_file = self.task_visualizer.export_task_info(
task, i, scene_graph, f"{session_name}_task_{i}.txt"
)
task_files.append(task_file)
except Exception as e:
glog.error(f"Failed to export task {i}: {e}")
results["sample_tasks"] = task_files
glog.info(f"Visualization completed for session: {session_name}")
return results
# Convenience functions for easy usage
def quick_visualize_scene(scene_graph, output_name: str = "quick_scene"):
"""Quick scene graph visualization"""
visualizer = SceneGraphVisualizer()
return visualizer.export_full_tree(scene_graph, output_name)
def quick_visualize_task(task, task_id: int, scene_graph=None):
"""Quick task visualization"""
visualizer = TaskVisualizer()
return visualizer.export_task_info(task, task_id, scene_graph)
def quick_visualize_all(scene_graph, tasks: List, session_name: str = "quick_session"):
"""Quick complete visualization"""
manager = VisualizationManager()
return manager.visualize_scene_and_tasks(scene_graph, tasks, session_name)
if __name__ == "__main__":
# Example usage
print("Visualization tools loaded successfully!")
print("Usage examples:")
print("1. quick_visualize_scene(scene_graph)")
print("2. quick_visualize_task(task, task_id, scene_graph)")
print("3. quick_visualize_all(scene_graph, tasks)")
|