| import numpy as np |
| import random |
| import math |
| from shapely.geometry import Polygon, Point |
| from shapely.geometry import Point, LineString, Polygon |
| import re |
| from PIL import Image |
| import math |
|
|
|
|
| def IOU(polygon1, polygon2): |
| """Calculates the IoU of two polygons. |
| |
| Args: |
| polygon1: A Shapely Polygon object. |
| polygon2: A Shapely Polygon object. |
| |
| Returns: |
| The IoU of the two polygons, as a float. |
| """ |
|
|
| intersection = polygon1.intersection(polygon2) |
| union = polygon1.union(polygon2) |
| iou = intersection.area / union.area |
| return iou |
|
|
|
|
| def half_vector_intersects_polygon(start_point, direction, polygon): |
| """ |
| Check if a half vector (ray) intersects with a polygon. |
| |
| Parameters: |
| - start_point: tuple of (x, y), the starting point of the ray. |
| - direction: tuple of (dx, dy), the direction vector of the ray. |
| - polygon: shapely.geometry.Polygon, the polygon to check for intersection. |
| |
| Returns: |
| - bool: True if the ray intersects with the polygon, False otherwise. |
| """ |
| |
| start = Point(start_point) |
| |
| |
| |
| multiplier = 1e6 |
| end_point = (start_point[0] + direction[0] * multiplier, start_point[1] + direction[1] * multiplier) |
| |
| |
| ray = LineString([start_point, end_point]) |
| |
| |
| return ray.intersects(polygon) |
|
|
|
|
| def triangle_area(A, B, C): |
| """Calculate the area of a triangle given by points A, B, and C""" |
| return abs((A[0]*(B[1]-C[1]) + B[0]*(C[1]-A[1]) + C[0]*(A[1]-B[1])) / 2.0) |
|
|
| def random_point_in_triangle(A, B, C): |
| """Generate a random point within the triangle defined by points A, B, and C""" |
| r1, r2 = random.random(), random.random() |
| if r1 + r2 > 1: |
| r1, r2 = 1 - r1, 1 - r2 |
| x = (1 - r1 - r2) * A[0] + r1 * B[0] + r2 * C[0] |
| y = (1 - r1 - r2) * A[1] + r1 * B[1] + r2 * C[1] |
| return (x, y) |
|
|
| def get_random_placement(floor_vertices, add_z=False): |
| if len(floor_vertices[0]) == 2: |
| polygon = Polygon([[x,y] for x,y in floor_vertices]) |
| else: |
| polygon = Polygon([[x,y] for x,y,z in floor_vertices]) |
| minx, miny, maxx, maxy = polygon.bounds |
| while True: |
| random_point = [random.uniform(minx, maxx), random.uniform(miny, maxy)] |
| if polygon.contains(Point(random_point)): |
| if add_z: |
| random_point = [random_point[0], random_point[1], 0] |
| return random_point |
|
|
| |
| def get_bbox_corners(position, rotation, bbox_size): |
| x,y,z = position |
| rotation_deg = rotation[2] |
|
|
| |
| theta = np.radians(-rotation_deg) |
| cos_theta, sin_theta = np.cos(theta), np.sin(theta) |
| dim_x, dim_y, dim_z = bbox_size |
|
|
| epsilon = 0.05 |
| dim_x = max(0, dim_x - epsilon) |
| dim_y = max(0, dim_y - epsilon) |
| dim_z = max(0, dim_z - epsilon) |
|
|
| |
| rotation_matrix = np.array([ |
| [cos_theta, -sin_theta, 0], |
| [sin_theta, cos_theta, 0], |
| [0, 0, 1] |
| ]) |
|
|
| |
| half_dim_x, half_dim_y, half_dim_z = dim_x / 2, dim_y / 2, dim_z / 2 |
| corners = np.array([ |
| [-half_dim_x, -half_dim_y, -half_dim_z], |
| [half_dim_x, -half_dim_y, -half_dim_z], |
| [half_dim_x, half_dim_y, -half_dim_z], |
| [-half_dim_x, half_dim_y, -half_dim_z], |
| [-half_dim_x, -half_dim_y, half_dim_z], |
| [half_dim_x, -half_dim_y, half_dim_z], |
| [half_dim_x, half_dim_y, half_dim_z], |
| [-half_dim_x, half_dim_y, half_dim_z] |
| ]) |
|
|
| |
| rotated_corners = np.dot(corners, rotation_matrix.T) |
| |
| |
| rotated_corners[:, 0] += x |
| rotated_corners[:, 1] += y |
| rotated_corners[:, 2] += z |
| |
| return rotated_corners |
|
|
| def fill_result_with_random_placements(task, layout_result, MAX_RETRIES=10): |
| unplaced_assets = [] |
| for asset_id in task["assets"].keys(): |
| if asset_id not in layout_result.keys(): |
| unplaced_assets.append(asset_id) |
| print("randomly placed assets: ", unplaced_assets) |
| if len(unplaced_assets) == 0: |
| return |
| boundary = Polygon([[x, y] for x, y, z in task["boundary"]["floor_vertices"]]) |
| for asset_id in unplaced_assets: |
| for _ in range(MAX_RETRIES): |
| x, y = get_random_placement(task["boundary"]["floor_vertices"]) |
| z = task["assets"][asset_id]["assetMetadata"]["boundingBox"]["z"]/2 |
| rotation = [0, 0, np.random.randint(0, 360)] |
| layout_result[asset_id] = { |
| "position": [x, y, z], |
| "rotation": rotation |
| } |
| bbox_size = [ |
| task["assets"][asset_id]["assetMetadata"]["boundingBox"]["x"], |
| task["assets"][asset_id]["assetMetadata"]["boundingBox"]["y"], |
| task["assets"][asset_id]["assetMetadata"]["boundingBox"]["z"], |
| ] |
| bbox_corners = get_bbox_corners([x,y,z], rotation, bbox_size) |
| if all(boundary.contains(Point(x,y)) for x,y,z in bbox_corners): |
| break |
|
|
|
|
| def extract_numbers(input_string): |
| |
| float_pattern = r'[-+]?\d*\.\d+|\d+' |
| |
| matches = re.findall(float_pattern, input_string) |
| |
| float_numbers = [float(num) for num in matches] |
| return float_numbers |
|
|
|
|
| def convert_json_format(data, for_gpt4o=False): |
| conversation = [] |
| |
| for conv in data['conversations']: |
| if conv['from'] == 'human': |
| user_content = [ |
| { |
| "type": "text", |
| "text": conv['value'].replace("<image>", "") |
| } |
| ] |
| if for_gpt4o: |
| for i in range(conv['value'].count("<image>")): |
| encoded_image = encode_image(data['image'][i]) |
| user_content.append( |
| { |
| "type": "image_url", |
| "image_url": {"url": f"data:image/jpeg;base64,{encoded_image}"} |
| } |
| ) |
| else: |
| user_content.extend([{"type": "image"} for _ in range(conv['value'].count("<image>"))]) |
| |
| conversation.append({ |
| "role": "user", |
| "content": user_content |
| }) |
| image_list = [Image.open(image_path).convert("RGB") for image_path in data["image"]] |
| return conversation, image_list |
|
|
| def extract_asset_info(code): |
| position = [] |
| rotation = [] |
| constraints = [] |
| |
| |
| position_pattern = re.compile(r"\w+\[\d\]\.position\s*=\s*\[([\d.,\s-]+)\]") |
| rotation_pattern = re.compile(r"\w+\[\d\]\.rotation\s*=\s*\[([\d.,\s-]+)\]") |
| |
| |
| constraint_pattern = re.compile(r"(solver\.\w+\([^)]*\))") |
| |
| |
| for match in position_pattern.findall(code): |
| pos = [float(x) for x in match.split(',')] |
| position.append(pos) |
|
|
| |
| for match in rotation_pattern.findall(code): |
| rot = [float(x) for x in match.split(',')] |
| |
| if len(rot) == 1: |
| rotation.append([0.0, 0.0, rot[0]]) |
| else: |
| rotation.append(rot) |
| |
| |
| constraints = constraint_pattern.findall(code) |
| |
| |
| constraint_str = "\n".join(constraints) |
| |
| return position, rotation, constraint_str |
|
|
| def extract_initialization_from_string(data_str, debug=True): |
| |
| position_pattern = re.compile(r"(\w+\[\d+\])\.position = (\[[-\d., ]+\])") |
| rotation_pattern = re.compile(r"(\w+\[\d+\])\.rotation = (\[[-\d., ]+\])") |
| |
| |
| positions = position_pattern.findall(data_str) |
| rotations = rotation_pattern.findall(data_str) |
|
|
| |
| objects = {} |
|
|
| |
| for obj, pos in positions: |
| pos_list = eval(pos) |
| if obj not in objects: |
| objects[obj] = {'position': pos_list, 'rotation': None} |
|
|
| |
| for obj, rot in rotations: |
| rot_list = eval(rot) |
| if obj in objects: |
| objects[obj]['rotation'] = rot_list |
| |
| return objects |
|
|
|
|
| def replace_z_rot_degree_to_rpy_radians(code): |
| |
| pattern = r'(\w+\[\d+\])\.rotation = \[(-?\d+\.?\d*)\]' |
|
|
| |
| def replace_with_radians(match): |
| obj = match.group(1) |
| degrees = float(match.group(2)) |
| radians = math.radians(degrees) |
| return f'{obj}.rotation = [0, 0, {radians}]' |
|
|
| |
| modified_code = re.sub(pattern, replace_with_radians, code) |
| return modified_code |
|
|
|
|
| if __name__ == '__main__': |
| |
| floor_vertices = [(0, 0, 0), (10, 0, 0), (10, 10, 0), (0, 10, 0)] |
| print(get_random_placement(floor_vertices)) |
|
|