ZoneMaestro_code / eval /LayoutVLM /test_zones_data.py
kkkkiiii's picture
Add files using upload-large-folder tool
d5f2893 verified
"""
测试 zones_data_mixed.json 中的 test 数据
使用 user_input 作为输入,走完整的 end_to_end_pipeline 流程:
1. 从 user_input 生成房间规格和物体列表 (在主进程使用 Azure OpenAI)
2. 用 OpenShape 从 objaverse_processed 检索 3D 资产 (在主进程使用 CUDA)
3. 用 LayoutVLM 优化布局 (并行,每个 worker 创建新 Azure 客户端)
4. 计算碰撞和出界指标 (使用 voxel, pitch=0.05)
架构说明:
- 第一阶段 (主进程): 对所有样本进行 LLM 调用和 CUDA 资产检索
- 第二阶段 (多进程): 并行运行 LayoutVLM 优化
"""
import os
import json
import argparse
import numpy as np
import collections
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
from tqdm import tqdm
import trimesh
from scipy.spatial import ConvexHull
from shapely.geometry import Polygon, Point
from multiprocessing import current_process
import traceback
# 复用 end_to_end_pipeline.py 的功能
from end_to_end_pipeline import (
setup_azure_client,
generate_room_specification,
generate_object_list,
retrieve_3d_assets,
generate_scene_json,
prepare_task_assets,
load_openclip_model,
load_openshape_embeddings,
)
from src.layoutvlm.layoutvlm import LayoutVLM
from utils.blender_render import render_existing_scene
from utils.blender_utils import reset_blender
# ============================================================================
# 数据加载
# ============================================================================
def load_zones_test_data(data_path: str) -> List[Dict]:
"""加载 zones_data_mixed.json 中的 test 数据"""
print(f"\n📂 加载数据: {data_path}")
with open(data_path, 'r') as f:
data = json.load(f)
# 提取 test split
test_samples = []
for sample in data['data']:
if sample.get('split') == 'test':
test_samples.append({
'id': sample.get('id'),
'scene_path': sample.get('scene_path'),
'granularity': sample.get('granularity'),
'user_input': sample['content'].get('user_input', ''),
})
print(f" 找到 {len(test_samples)} 个测试样本")
return test_samples
# ============================================================================
# 碰撞和出界检测 (使用 voxel, pitch=0.05)
# ============================================================================
@dataclass
class CollisionResult:
total_assets: int
collision_pairs: List[Tuple[str, str]]
collision_count: int
collision_ratio: float
# 碰撞体积指标
collision_volume: float # 总碰撞体积 (立方米)
collision_volume_per_pair: Dict[str, float] # 每对碰撞的体积
# 出界指标
out_of_bounds_assets: List[str]
out_of_bounds_count: int
out_of_bounds_ratio: float
# 出界体积指标
out_of_bounds_volume: float # 总出界体积 (立方米)
out_of_bounds_volume_per_asset: Dict[str, float] # 每个物体的出界体积
# 总体积(用于计算比例)
total_asset_volume: float # 所有资产的总体积
def load_mesh_from_glb(glb_path: str) -> Optional[trimesh.Trimesh]:
"""从 glb 文件加载 mesh"""
if not os.path.exists(glb_path):
return None
try:
mesh = trimesh.load(glb_path)
if isinstance(mesh, trimesh.Scene):
meshes = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)]
if meshes:
mesh = trimesh.util.concatenate(meshes)
else:
return None
return mesh
except Exception as e:
print(f" ⚠️ 加载mesh失败: {e}")
return None
def transform_mesh(mesh: trimesh.Trimesh, position: List[float],
rotation: float, scale: List[float]) -> trimesh.Trimesh:
"""变换 mesh 到世界坐标"""
mesh_copy = mesh.copy()
# 缩放到目标尺寸
current_extents = mesh_copy.bounding_box.extents
if all(e > 0 for e in current_extents):
scale_factors = [s / e for s, e in zip(scale, current_extents)]
mesh_copy.apply_scale(scale_factors)
# 旋转 (绕 Z 轴)
rotation_matrix = trimesh.transformations.rotation_matrix(
np.radians(rotation), [0, 0, 1]
)
mesh_copy.apply_transform(rotation_matrix)
# 平移
mesh_copy.apply_translation(position)
return mesh_copy
def voxelize_mesh(mesh: trimesh.Trimesh, pitch: float = 0.05) -> Optional[set]:
"""将 mesh 体素化,返回体素坐标集合"""
try:
voxels = mesh.voxelized(pitch=pitch)
# 获取填充的体素索引
indices = voxels.sparse_indices
# 转换为世界坐标并量化
world_coords = indices * pitch + voxels.transform[:3, 3]
# 量化为整数索引
quantized = set(map(tuple, np.round(world_coords / pitch).astype(int)))
return quantized
except Exception as e:
return None
def check_voxel_collision(voxels1: set, voxels2: set, voxel_pitch: float = 0.05) -> Tuple[bool, int, float]:
"""检测两个体素集合是否碰撞,返回碰撞体素数和碰撞体积"""
if voxels1 is None or voxels2 is None:
return False, 0, 0.0
overlap = voxels1 & voxels2
overlap_count = len(overlap)
# 每个体素的体积 = pitch^3
overlap_volume = overlap_count * (voxel_pitch ** 3)
return overlap_count > 0, overlap_count, overlap_volume
def check_out_of_bounds_voxel(voxels: set, boundary_polygon: List[List[float]],
height: float, voxel_pitch: float = 0.05) -> Tuple[bool, int, float]:
"""
检测物体体素是否出界,返回出界体素数和出界体积
"""
if voxels is None or len(voxels) == 0:
return False, 0, 0.0
try:
boundary = Polygon([(p[0], p[1]) for p in boundary_polygon])
if not boundary.is_valid:
boundary = boundary.buffer(0)
out_count = 0
for voxel in voxels:
# 转换体素索引回世界坐标
x = voxel[0] * voxel_pitch
y = voxel[1] * voxel_pitch
z = voxel[2] * voxel_pitch if len(voxel) > 2 else 0
# 检查 XY 平面是否在边界内
point = Point(x, y)
if not boundary.contains(point):
out_count += 1
# 检查高度
elif z < 0 or z > height:
out_count += 1
out_volume = out_count * (voxel_pitch ** 3)
return out_count > 0, out_count, out_volume
except Exception as e:
return False, 0, 0.0
def evaluate_layout_collisions(layout: Dict, scene_config: Dict,
voxel_pitch: float = 0.05) -> CollisionResult:
"""
评估布局的碰撞和出界情况,计算碰撞体积和出界体积
"""
print(" 📊 评估碰撞和出界...")
# 获取边界多边形和房间高度
boundary = scene_config.get('boundary', {})
floor_vertices = boundary.get('floor_vertices', [[0,0,0], [5,0,0], [5,5,0], [0,5,0]])
boundary_polygon = [[v[0], v[1]] for v in floor_vertices]
room_height = boundary.get('ceiling_height', 2.7)
# 加载所有资产的 mesh 并体素化
asset_voxels = {}
asset_positions = {}
asset_volumes = {} # 每个资产的体积
for asset_id, asset_info in layout.items():
if asset_id not in scene_config.get('assets', {}):
continue
asset_meta = scene_config['assets'][asset_id]
glb_path = asset_meta.get('path')
position = asset_info.get('position', [0, 0, 0])
if len(position) == 2:
bbox = asset_meta.get('assetMetadata', {}).get('boundingBox', {})
z_height = bbox.get('z', 1.0)
position = [position[0], position[1], z_height / 2]
rotation = asset_info.get('rotation', 0)
if isinstance(rotation, (list, tuple)):
rotation = rotation[2] if len(rotation) > 2 else rotation[0]
scale_factor = asset_info.get('scale', 1.0)
bbox = asset_meta.get('assetMetadata', {}).get('boundingBox', {})
size = [
bbox.get('x', 1.0) * scale_factor,
bbox.get('y', 1.0) * scale_factor,
bbox.get('z', 1.0) * scale_factor
]
asset_positions[asset_id] = {
'position': position,
'rotation': rotation,
'size': size,
}
# 加载并变换 mesh
if glb_path and os.path.exists(glb_path):
mesh = load_mesh_from_glb(glb_path)
if mesh:
transformed = transform_mesh(mesh, position, rotation, size)
voxels = voxelize_mesh(transformed, voxel_pitch)
if voxels:
asset_voxels[asset_id] = voxels
asset_volumes[asset_id] = len(voxels) * (voxel_pitch ** 3)
# 碰撞检测
print(f" 检测碰撞 (voxel pitch={voxel_pitch})...")
collision_pairs = []
collision_volume_per_pair = {}
total_collision_volume = 0.0
asset_ids = list(asset_voxels.keys())
for i in range(len(asset_ids)):
for j in range(i + 1, len(asset_ids)):
id1, id2 = asset_ids[i], asset_ids[j]
is_collision, overlap_count, overlap_volume = check_voxel_collision(
asset_voxels[id1], asset_voxels[id2], voxel_pitch
)
if is_collision:
pair_key = f"{id1}--{id2}"
collision_pairs.append((id1, id2))
collision_volume_per_pair[pair_key] = overlap_volume
total_collision_volume += overlap_volume
# 出界检测
print(" 检测出界...")
out_of_bounds = []
out_of_bounds_volume_per_asset = {}
total_out_of_bounds_volume = 0.0
for asset_id in asset_voxels.keys():
is_out, out_count, out_volume = check_out_of_bounds_voxel(
asset_voxels[asset_id], boundary_polygon, room_height, voxel_pitch
)
if is_out:
out_of_bounds.append(asset_id)
out_of_bounds_volume_per_asset[asset_id] = out_volume
total_out_of_bounds_volume += out_volume
# 计算统计
n = len(asset_positions)
max_pairs = n * (n - 1) // 2 if n > 1 else 1
total_asset_volume = sum(asset_volumes.values())
print(f" 📊 碰撞: {len(collision_pairs)} 对, 碰撞体积: {total_collision_volume:.6f} m³")
print(f" 📊 出界: {len(out_of_bounds)} 个, 出界体积: {total_out_of_bounds_volume:.6f} m³")
print(f" 📊 总资产体积: {total_asset_volume:.6f} m³")
return CollisionResult(
total_assets=n,
collision_pairs=collision_pairs,
collision_count=len(collision_pairs),
collision_ratio=len(collision_pairs) / max_pairs if max_pairs > 0 else 0,
collision_volume=total_collision_volume,
collision_volume_per_pair=collision_volume_per_pair,
out_of_bounds_assets=out_of_bounds,
out_of_bounds_count=len(out_of_bounds),
out_of_bounds_ratio=len(out_of_bounds) / n if n > 0 else 0,
out_of_bounds_volume=total_out_of_bounds_volume,
out_of_bounds_volume_per_asset=out_of_bounds_volume_per_asset,
total_asset_volume=total_asset_volume,
)
# ============================================================================
# 渲染 (使用 blender_render.py,无墙壁天花板)
# ============================================================================
def render_scene(scene_config: Dict, layout: Dict, save_dir: str) -> List[str]:
"""渲染场景 (diagonal + top 视角,无墙壁天花板)"""
print(" 🎨 渲染场景...")
output_dir = os.path.join(save_dir, "renders")
os.makedirs(output_dir, exist_ok=True)
render_paths = []
try:
print(" 渲染 top-down 视角...")
top_images, _ = render_existing_scene(
placed_assets=layout,
task=scene_config,
save_dir=output_dir,
high_res=True,
render_top_down=True,
add_coordinate_mark=False,
annotate_object=False,
annotate_wall=False,
combine_obj_components=True,
fov_multiplier=1.3,
topdown_save_file=os.path.join(output_dir, 'render_top.png'),
sideview_save_file=os.path.join(output_dir, 'render_diagonal.png'),
side_view_indices=[3],
)
reset_blender()
render_paths.extend(top_images)
print(f" ✅ 渲染完成: {len(render_paths)} 张图片")
except Exception as e:
print(f" ❌ 渲染失败: {e}")
traceback.print_exc()
return render_paths
# ============================================================================
# 第一阶段: 主进程预处理 (LLM + CUDA 资产检索)
# ============================================================================
def preprocess_sample(sample: Dict, asset_dir: str, client, use_openshape: bool = True) -> Dict:
"""
在主进程中预处理单个样本:
1. 调用 LLM 生成房间规格和物体列表
2. 使用 CUDA 进行 OpenShape 资产检索
3. 生成 scene_json
返回预处理结果,供后续并行 LayoutVLM 优化使用
"""
sample_id = sample['id']
user_input = sample['user_input']
result = {
'sample_id': sample_id,
'user_input': user_input,
'success': False,
'scene_json': None,
'room_spec': None,
'object_list': None,
'num_assets': 0,
'error': None,
}
try:
# Step 1: 生成房间规格
room_spec = generate_room_specification(client, user_input)
result['room_spec'] = room_spec
# Step 2: 生成物体列表
object_list = generate_object_list(
client,
room_spec['task_description'],
room_spec['layout_criteria'],
room_spec['room_size']
)
result['object_list'] = object_list
# Step 3: 检索 3D 资产 (CUDA 操作)
assets = retrieve_3d_assets(object_list, asset_dir, use_openshape=use_openshape)
result['num_assets'] = len(assets)
if not assets:
raise ValueError("未检索到任何资产")
# Step 4: 生成 scene JSON
scene_json = generate_scene_json(
room_spec['task_description'],
room_spec['layout_criteria'],
room_spec['room_size'],
assets
)
result['scene_json'] = scene_json
result['success'] = True
except Exception as e:
result['error'] = str(e)
print(f" ❌ 预处理失败 [{sample_id}]: {e}")
return result
def preprocess_all_samples(samples: List[Dict], asset_dir: str,
use_openshape: bool = True, save_dir: str = None) -> List[Dict]:
"""
主进程中预处理所有样本 (LLM 调用 + CUDA 资产检索)
"""
print("\n" + "=" * 80)
print("📦 第一阶段: 预处理 (LLM + OpenShape 检索)")
print("=" * 80)
# 预加载 CUDA 模型
if use_openshape:
print("🔄 加载 CLIP 模型和 OpenShape embeddings...")
load_openclip_model()
load_openshape_embeddings()
print("✅ 模型加载完成\n")
# 创建 Azure 客户端
client = setup_azure_client()
preprocessed = []
for i, sample in enumerate(tqdm(samples, desc="预处理进度")):
sample_id = sample['id']
# 检查是否已完成预处理
if save_dir:
sample_save_dir = os.path.join(save_dir, f"sample_{i:04d}")
scene_path = os.path.join(sample_save_dir, 'scene_config.json')
if os.path.exists(scene_path):
# 加载已有的预处理结果
try:
with open(scene_path, 'r') as f:
scene_json = json.load(f)
preprocessed.append({
'sample_id': sample_id,
'user_input': sample['user_input'],
'success': True,
'scene_json': scene_json,
'room_spec': None, # 不需要保存
'object_list': None,
'num_assets': len(scene_json.get('objects', [])),
'error': None,
'skipped': True,
})
print(f" ⏭️ 跳过已预处理: {sample_id}")
continue
except:
pass
# 预处理
result = preprocess_sample(sample, asset_dir, client, use_openshape)
preprocessed.append(result)
# 保存 scene_json
if result['success'] and save_dir:
sample_save_dir = os.path.join(save_dir, f"sample_{i:04d}")
os.makedirs(sample_save_dir, exist_ok=True)
scene_path = os.path.join(sample_save_dir, 'scene_config.json')
with open(scene_path, 'w') as f:
json.dump(result['scene_json'], f, indent=2)
# 统计
success_count = sum(1 for p in preprocessed if p['success'])
print(f"\n📊 预处理完成: {success_count}/{len(samples)} 成功")
return preprocessed
# ============================================================================
# 第二阶段: 并行 LayoutVLM 优化
# ============================================================================
def layoutvlm_worker(args_tuple) -> Dict:
"""
LayoutVLM 优化 worker (单线程模式)
"""
idx, preprocessed, save_dir, asset_dir, do_render = args_tuple
sample_id = preprocessed['sample_id']
sample_save_dir = os.path.join(save_dir, f"sample_{idx:04d}")
proc_name = current_process().name
result = {
'sample_id': sample_id,
'user_input': preprocessed['user_input'],
'success': False,
'room_spec': preprocessed.get('room_spec'),
'object_list': preprocessed.get('object_list'),
'num_assets': preprocessed.get('num_assets', 0),
'collision_result': None,
'render_paths': [],
'error': None,
}
# 检查是否已完成
layout_path = os.path.join(sample_save_dir, 'layout.json')
result_json_path = os.path.join(sample_save_dir, 'result.json')
if os.path.exists(layout_path):
if os.path.exists(result_json_path):
try:
with open(result_json_path, 'r') as f:
cached_result = json.load(f)
print(f"[{proc_name}] ⏭️ 跳过已完成: {sample_id}")
cached_result['skipped'] = True
return cached_result
except:
pass
result['success'] = True
result['skipped'] = True
print(f"[{proc_name}] ⏭️ 跳过已完成: {sample_id}")
return result
# 检查预处理是否成功
if not preprocessed['success']:
result['error'] = preprocessed.get('error', '预处理失败')
print(f"[{proc_name}] ⏭️ 跳过预处理失败: {sample_id}")
return result
try:
print(f"\n[{proc_name}] {'='*50}")
print(f"[{proc_name}] 📋 处理样本: {sample_id}")
scene_json = preprocessed['scene_json']
os.makedirs(sample_save_dir, exist_ok=True)
# 准备资产元数据
scene_config = prepare_task_assets(scene_json, asset_dir)
if not scene_config.get('assets'):
raise ValueError("没有有效的资产")
# LayoutVLM 优化 (会在内部创建新的 Azure 客户端)
print(f"[{proc_name}] LayoutVLM 布局优化...")
layout_solver = LayoutVLM(
mode="one_shot",
save_dir=sample_save_dir,
asset_source="objaverse",
)
layout = layout_solver.solve(scene_config)
# 保存布局
with open(layout_path, 'w') as f:
json.dump(layout, f, indent=2)
# 计算碰撞和出界
print(f"[{proc_name}] 计算碰撞和出界...")
collision_result = evaluate_layout_collisions(
layout, scene_config, voxel_pitch=0.05
)
result['collision_result'] = {
'total_assets': collision_result.total_assets,
'collision_count': collision_result.collision_count,
'collision_ratio': collision_result.collision_ratio,
'collision_volume': collision_result.collision_volume,
'collision_volume_per_pair': collision_result.collision_volume_per_pair,
'out_of_bounds_count': collision_result.out_of_bounds_count,
'out_of_bounds_ratio': collision_result.out_of_bounds_ratio,
'out_of_bounds_volume': collision_result.out_of_bounds_volume,
'out_of_bounds_volume_per_asset': collision_result.out_of_bounds_volume_per_asset,
'total_asset_volume': collision_result.total_asset_volume,
'collision_pairs': collision_result.collision_pairs,
'out_of_bounds_assets': collision_result.out_of_bounds_assets,
}
# 渲染 (可选)
if do_render:
print(f"[{proc_name}] Blender 渲染...")
render_paths = render_scene(scene_config, layout, sample_save_dir)
result['render_paths'] = render_paths
result['success'] = True
print(f"[{proc_name}] ✅ 完成")
except Exception as e:
result['error'] = str(e)
print(f"[{proc_name}] ❌ 失败: {e}")
traceback.print_exc()
# 保存单个样本结果
with open(result_json_path, 'w') as f:
json.dump(result, f, indent=2, default=str)
return result
# ============================================================================
# 主函数
# ============================================================================
def main():
parser = argparse.ArgumentParser(description='测试 zones_data_mixed.json 中的 test 数据')
parser.add_argument('--data_path', type=str,
default='/home/v-meiszhang/amlt-project/group-layout/src/train_sft/data/zones_data_mixed.json',
help='数据文件路径')
parser.add_argument('--save_dir', type=str,
default='./results/zones_test',
help='结果保存目录')
parser.add_argument('--asset_dir', type=str,
default='/home/v-meiszhang/backup/objaverse_processed',
help='Objaverse 资产目录')
parser.add_argument('--num_samples', type=int, default=10,
help='测试样本数量 (0 表示全部)')
parser.add_argument('--start_idx', type=int, default=0,
help='起始索引')
parser.add_argument('--num_workers', type=int, default=4,
help='并行进程数')
parser.add_argument('--random_selection', action='store_true',
help='使用随机选择而非 OpenShape 检索')
parser.add_argument('--skip_render', action='store_true', default=True,
help='跳过渲染 (默认开启)')
parser.add_argument('--enable_render', action='store_true',
help='启用渲染')
args = parser.parse_args()
do_render = args.enable_render
use_openshape = not args.random_selection
print("=" * 80)
print("🧪 Zones Data 测试脚本 (单线程)")
print("=" * 80)
print(f"📁 数据路径: {args.data_path}")
print(f"💾 保存目录: {args.save_dir}")
print(f"📦 资产目录: {args.asset_dir}")
print(f"📊 测试数量: {args.num_samples if args.num_samples > 0 else '全部'}")
print(f"🎨 渲染: {'启用' if do_render else '跳过'}")
print(f"🔍 资产检索: {'OpenShape' if use_openshape else '随机选择'}")
print()
os.makedirs(args.save_dir, exist_ok=True)
# 加载测试数据
test_data = load_zones_test_data(args.data_path)
if args.num_samples > 0:
test_data = test_data[args.start_idx:args.start_idx + args.num_samples]
# ===== 第一阶段: 主进程预处理 (LLM + CUDA) =====
preprocessed = preprocess_all_samples(
test_data,
args.asset_dir,
use_openshape=use_openshape,
save_dir=args.save_dir
)
# ===== 第二阶段: 单线程 LayoutVLM 优化 =====
print("\n" + "=" * 80)
print("🚀 第二阶段: LayoutVLM 优化 (单线程)")
print("=" * 80)
# 准备 worker 参数
worker_args = [
(i, preprocessed[i], args.save_dir, args.asset_dir, do_render)
for i in range(len(preprocessed))
]
all_results = []
for args_tuple in tqdm(worker_args, desc="LayoutVLM 进度"):
result = layoutvlm_worker(args_tuple)
all_results.append(result)
# 每完成10个保存一次中间结果
if len(all_results) % 10 == 0:
results_path = os.path.join(args.save_dir, 'all_results.json')
with open(results_path, 'w') as f:
json.dump(all_results, f, indent=2, default=str)
# ===== 统计结果 =====
summary = {
'total_samples': len(test_data),
'successful': 0,
'failed': 0,
'skipped': 0,
'total_collisions': 0,
'total_out_of_bounds': 0,
'avg_collision_ratio': 0,
'avg_out_of_bounds_ratio': 0,
}
collision_ratios = []
out_of_bounds_ratios = []
collision_volumes = []
out_of_bounds_volumes = []
total_asset_volumes = []
for result in all_results:
if result.get('skipped'):
summary['skipped'] += 1
summary['successful'] += 1
elif result.get('success'):
summary['successful'] += 1
if result.get('collision_result'):
cr = result['collision_result']
summary['total_collisions'] += cr['collision_count']
summary['total_out_of_bounds'] += cr['out_of_bounds_count']
collision_ratios.append(cr['collision_ratio'])
out_of_bounds_ratios.append(cr['out_of_bounds_ratio'])
collision_volumes.append(cr.get('collision_volume', 0))
out_of_bounds_volumes.append(cr.get('out_of_bounds_volume', 0))
total_asset_volumes.append(cr.get('total_asset_volume', 0))
else:
summary['failed'] += 1
if collision_ratios:
summary['avg_collision_ratio'] = sum(collision_ratios) / len(collision_ratios)
if out_of_bounds_ratios:
summary['avg_out_of_bounds_ratio'] = sum(out_of_bounds_ratios) / len(out_of_bounds_ratios)
summary['total_collision_volume'] = sum(collision_volumes)
summary['total_out_of_bounds_volume'] = sum(out_of_bounds_volumes)
summary['total_asset_volume'] = sum(total_asset_volumes)
summary['avg_collision_volume'] = sum(collision_volumes) / len(collision_volumes) if collision_volumes else 0
summary['avg_out_of_bounds_volume'] = sum(out_of_bounds_volumes) / len(out_of_bounds_volumes) if out_of_bounds_volumes else 0
summary['collision_volume_ratio'] = summary['total_collision_volume'] / summary['total_asset_volume'] if summary['total_asset_volume'] > 0 else 0
summary['out_of_bounds_volume_ratio'] = summary['total_out_of_bounds_volume'] / summary['total_asset_volume'] if summary['total_asset_volume'] > 0 else 0
# 保存结果
summary_path = os.path.join(args.save_dir, 'summary.json')
with open(summary_path, 'w') as f:
json.dump(summary, f, indent=2)
results_path = os.path.join(args.save_dir, 'all_results.json')
with open(results_path, 'w') as f:
json.dump(all_results, f, indent=2, default=str)
# 打印总结
print("\n" + "=" * 80)
print("📊 测试总结")
print("=" * 80)
print(f"总样本数: {summary['total_samples']}")
print(f"成功: {summary['successful']}")
print(f"失败: {summary['failed']}")
print(f"跳过: {summary['skipped']}")
print(f"\n--- 碰撞指标 ---")
print(f"总碰撞对数: {summary['total_collisions']}")
print(f"平均碰撞比例: {summary['avg_collision_ratio']:.2%}")
print(f"总碰撞体积: {summary['total_collision_volume']:.6f} m³")
print(f"平均碰撞体积: {summary['avg_collision_volume']:.6f} m³")
print(f"碰撞体积比例: {summary['collision_volume_ratio']:.4%}")
print(f"\n--- 出界指标 ---")
print(f"总出界物体数: {summary['total_out_of_bounds']}")
print(f"平均出界比例: {summary['avg_out_of_bounds_ratio']:.2%}")
print(f"总出界体积: {summary['total_out_of_bounds_volume']:.6f} m³")
print(f"平均出界体积: {summary['avg_out_of_bounds_volume']:.6f} m³")
print(f"出界体积比例: {summary['out_of_bounds_volume_ratio']:.4%}")
print(f"\n--- 资产体积 ---")
print(f"总资产体积: {summary['total_asset_volume']:.6f} m³")
print(f"\n结果保存在: {args.save_dir}")
if __name__ == '__main__':
main()