使用 Graphviz 生成带箭头的树形图 需要安装: pip install graphviz 系统需要安装 Graphviz: https://graphviz.org/download/
(nodes: Dict[str, NodeInfo], root_id: str, output_file: str = "mcts_tree")
| 309 | |
| 310 | |
| 311 | def print_tree_graphviz(nodes: Dict[str, NodeInfo], root_id: str, output_file: str = "mcts_tree"): |
| 312 | """ |
| 313 | 使用 Graphviz 生成带箭头的树形图 |
| 314 | 需要安装: pip install graphviz |
| 315 | 系统需要安装 Graphviz: https://graphviz.org/download/ |
| 316 | """ |
| 317 | try: |
| 318 | from graphviz import Digraph |
| 319 | except ImportError: |
| 320 | print("Error: graphviz not installed. Install with: pip install graphviz") |
| 321 | print("Also ensure Graphviz executables are installed on your system.") |
| 322 | print(" Ubuntu/Debian: sudo apt-get install graphviz") |
| 323 | print(" macOS: brew install graphviz") |
| 324 | print(" Windows: Download from https://graphviz.org/download/") |
| 325 | return |
| 326 | |
| 327 | # 创建有向图 |
| 328 | g = Digraph( |
| 329 | name='MCTS_Tree', |
| 330 | comment='MCTS Search Tree Visualization', |
| 331 | format='png', # 可以改为 'pdf', 'svg' 等 |
| 332 | graph_attr={ |
| 333 | 'rankdir': 'TB', # Top to Bottom (从上到下) |
| 334 | 'splines': 'ortho', # 正交边 |
| 335 | 'nodesep': '0.5', |
| 336 | 'ranksep': '1.0', |
| 337 | 'bgcolor': '#f5f5f5' |
| 338 | }, |
| 339 | node_attr={ |
| 340 | 'shape': 'box', |
| 341 | 'style': 'rounded,filled', |
| 342 | 'fontsize': '10', |
| 343 | 'fontname': 'Arial' |
| 344 | }, |
| 345 | edge_attr={ |
| 346 | 'arrowhead': 'vee', |
| 347 | 'color': '#666666', |
| 348 | 'penwidth': '1.5' |
| 349 | } |
| 350 | ) |
| 351 | |
| 352 | # 添加节点和边的递归函数 |
| 353 | def add_node_recursive(node_id: str): |
| 354 | if node_id not in nodes: |
| 355 | return |
| 356 | |
| 357 | node = nodes[node_id] |
| 358 | |
| 359 | # 构建节点标签 |
| 360 | status_sym = "✓" if node.run_status == "OK" else "✗" if node.run_status == "FAIL" else "?" |
| 361 | stage_name = {"root": "R", "draft": "D", "improve": "I", "debug": "DB"}.get(node.stage, node.stage[:1].upper()) |
| 362 | |
| 363 | label_lines = [ |
| 364 | f"{status_sym} {stage_name} {node.id[:8]}", |
| 365 | ] |
| 366 | |
| 367 | if node.metric is not None: |
| 368 | label_lines.append(f"metric: {node.metric:.4f}") |
no test coverage detected