| |
| """ |
| 检测layout中的出界(OOB)和碰撞情况 |
| 使用简单的bbox检测 |
| """ |
|
|
| import json |
| import numpy as np |
| from pathlib import Path |
| from typing import List, Dict, Tuple, Any |
| from shapely.geometry import Polygon, Point, box |
| from shapely.affinity import rotate as shapely_rotate |
| import argparse |
|
|
|
|
| def get_boundary_polygon(layout: dict) -> Polygon: |
| """从layout获取边界多边形""" |
| arch = layout.get('architecture', {}) |
| boundary = arch.get('boundary_polygon', []) |
| if not boundary: |
| |
| boundary = layout.get('boundary', []) |
| |
| if not boundary: |
| raise ValueError("No boundary found in layout") |
| |
| |
| boundary_2d = [(p[0], p[1]) for p in boundary] |
| return Polygon(boundary_2d) |
|
|
|
|
| def get_all_assets(layout: dict) -> List[Dict]: |
| """获取所有assets,添加zone信息""" |
| assets = [] |
| |
| |
| zones = layout.get('functional_zones', []) |
| if isinstance(zones, list): |
| for zone in zones: |
| zone_id = zone.get('id', 'unknown') |
| for asset in zone.get('assets', []): |
| asset_copy = asset.copy() |
| asset_copy['zone_id'] = zone_id |
| assets.append(asset_copy) |
| |
| |
| for inst in layout.get('instances', []): |
| assets.append(inst) |
| |
| return assets |
|
|
|
|
| def get_asset_bbox_2d(asset: dict) -> Tuple[Polygon, dict]: |
| """ |
| 获取asset的2D bbox (在XY平面上) |
| 返回: (shapely Polygon, info dict) |
| """ |
| import math |
| |
| |
| pos = asset.get('pos', asset.get('position', [0, 0, 0])) |
| if len(pos) == 2: |
| pos = [pos[0], pos[1], 0] |
| |
| |
| |
| size = asset.get('retrieved_size', asset.get('size', [1, 1, 1])) |
| if len(size) == 2: |
| size = [size[0], size[1], 1] |
| |
| |
| rot = asset.get('rot', asset.get('rotation', [0, 0, 0])) |
| if isinstance(rot, (int, float)): |
| rot_z_deg = math.degrees(rot) |
| elif len(rot) >= 3: |
| rot_z_deg = math.degrees(rot[2]) |
| else: |
| rot_z_deg = 0 |
| |
| |
| |
| half_w = size[0] / 2 |
| half_d = size[1] / 2 |
| |
| |
| bbox = box(pos[0] - half_w, pos[1] - half_d, |
| pos[0] + half_w, pos[1] + half_d) |
| |
| |
| if abs(rot_z_deg) > 0.1: |
| bbox = shapely_rotate(bbox, rot_z_deg, origin=(pos[0], pos[1])) |
| |
| info = { |
| 'category': asset.get('category', 'unknown'), |
| 'zone_id': asset.get('zone_id', 'unknown'), |
| 'pos': pos, |
| 'size': size, |
| 'rot_z_deg': rot_z_deg, |
| 'model_uid': asset.get('model_uid', '') |
| } |
| |
| return bbox, info |
|
|
|
|
| def check_oob(assets: List[Dict], boundary: Polygon, top_k: int = 10) -> List[Dict]: |
| """ |
| 检测出界的assets |
| 返回: 出界比例最大的top_k个assets |
| """ |
| oob_list = [] |
| |
| for i, asset in enumerate(assets): |
| bbox, info = get_asset_bbox_2d(asset) |
| |
| |
| if not boundary.contains(bbox): |
| intersection = boundary.intersection(bbox) |
| inside_area = intersection.area if not intersection.is_empty else 0 |
| total_area = bbox.area |
| |
| if total_area > 0: |
| oob_ratio = 1.0 - (inside_area / total_area) |
| if oob_ratio > 0.01: |
| oob_list.append({ |
| 'index': i, |
| 'category': info['category'], |
| 'zone_id': info['zone_id'], |
| 'pos': info['pos'], |
| 'size': info['size'], |
| 'oob_ratio': oob_ratio, |
| 'model_uid': info['model_uid'] |
| }) |
| |
| |
| oob_list.sort(key=lambda x: x['oob_ratio'], reverse=True) |
| return oob_list[:top_k] |
|
|
|
|
| def check_collision(assets: List[Dict], top_k: int = 10) -> List[Dict]: |
| """ |
| 检测碰撞的asset对 |
| 返回: 碰撞最严重的top_k对 |
| """ |
| collision_list = [] |
| n = len(assets) |
| |
| |
| bboxes = [] |
| infos = [] |
| for asset in assets: |
| bbox, info = get_asset_bbox_2d(asset) |
| bboxes.append(bbox) |
| infos.append(info) |
| |
| |
| for i in range(n): |
| for j in range(i + 1, n): |
| intersection = bboxes[i].intersection(bboxes[j]) |
| if not intersection.is_empty and intersection.area > 0.001: |
| |
| min_area = min(bboxes[i].area, bboxes[j].area) |
| collision_ratio = intersection.area / min_area if min_area > 0 else 0 |
| |
| if collision_ratio > 0.01: |
| collision_list.append({ |
| 'index_pair': (i, j), |
| 'asset1': { |
| 'category': infos[i]['category'], |
| 'zone_id': infos[i]['zone_id'], |
| 'pos': infos[i]['pos'][:2], |
| }, |
| 'asset2': { |
| 'category': infos[j]['category'], |
| 'zone_id': infos[j]['zone_id'], |
| 'pos': infos[j]['pos'][:2], |
| }, |
| 'collision_ratio': collision_ratio, |
| 'intersection_area': intersection.area |
| }) |
| |
| |
| collision_list.sort(key=lambda x: x['collision_ratio'], reverse=True) |
| return collision_list[:top_k] |
|
|
|
|
| def analyze_layout(layout_path: str, top_k: int = 10) -> Dict: |
| """分析layout的出界和碰撞情况""" |
| with open(layout_path) as f: |
| layout = json.load(f) |
| |
| |
| boundary = get_boundary_polygon(layout) |
| assets = get_all_assets(layout) |
| |
| print(f"Boundary area: {boundary.area:.2f} m²") |
| print(f"Total assets: {len(assets)}") |
| print() |
| |
| |
| oob_results = check_oob(assets, boundary, top_k) |
| print(f"=== Out-of-Bounds (Top {len(oob_results)}) ===") |
| for i, item in enumerate(oob_results): |
| print(f"{i+1}. [{item['zone_id']}] {item['category']}") |
| print(f" pos: ({item['pos'][0]:.2f}, {item['pos'][1]:.2f})") |
| print(f" size: ({item['size'][0]:.2f}, {item['size'][1]:.2f})") |
| print(f" OOB ratio: {item['oob_ratio']*100:.1f}%") |
| |
| print() |
| |
| |
| collision_results = check_collision(assets, top_k) |
| print(f"=== Collisions (Top {len(collision_results)}) ===") |
| for i, item in enumerate(collision_results): |
| a1, a2 = item['asset1'], item['asset2'] |
| print(f"{i+1}. [{a1['zone_id']}]{a1['category']} <-> [{a2['zone_id']}]{a2['category']}") |
| print(f" pos1: ({a1['pos'][0]:.2f}, {a1['pos'][1]:.2f})") |
| print(f" pos2: ({a2['pos'][0]:.2f}, {a2['pos'][1]:.2f})") |
| print(f" Collision ratio: {item['collision_ratio']*100:.1f}%") |
| print(f" Intersection area: {item['intersection_area']:.3f} m²") |
| |
| return { |
| 'oob': oob_results, |
| 'collisions': collision_results |
| } |
|
|
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser(description="Check collision and OOB in layout") |
| parser.add_argument("layout_path", help="Path to layout JSON file") |
| parser.add_argument("--top-k", type=int, default=10, help="Number of top results to show") |
| args = parser.parse_args() |
| |
| analyze_layout(args.layout_path, args.top_k) |
|
|