| 1 | import numpy as np |
| 2 | from scipy.spatial.transform import Rotation as R |
| 3 | from spatiallm.layout.entity import Wall, Door, Window, Bbox, NORMALIZATION_PRESET |
| 4 | |
| 5 | |
| 6 | class Layout: |
| 7 | def __init__(self, s: str = None): |
| 8 | self.walls = [] |
| 9 | self.doors = [] |
| 10 | self.windows = [] |
| 11 | self.bboxes = [] |
| 12 | |
| 13 | if s: |
| 14 | self.from_str(s) |
| 15 | |
| 16 | @staticmethod |
| 17 | def get_grid_size(num_bins): |
| 18 | world_min, world_max = NORMALIZATION_PRESET["world"] |
| 19 | return (world_max - world_min) / num_bins |
| 20 | |
| 21 | def from_str(self, s: str): |
| 22 | s = s.lstrip("\n") |
| 23 | lines = s.split("\n") |
| 24 | # wall lookup table |
| 25 | existing_walls = [] |
| 26 | for line in lines: |
| 27 | try: |
| 28 | label = line.split("=")[0] |
| 29 | entity_id = int(label.split("_")[1]) |
| 30 | entity_label = label.split("_")[0] |
| 31 | |
| 32 | # extract params |
| 33 | start_pos = line.find("(") |
| 34 | end_pos = line.find(")") |
| 35 | params = line[start_pos + 1 : end_pos].split(",") |
| 36 | |
| 37 | if entity_label == Wall.entity_label: |
| 38 | wall_args = [ |
| 39 | "ax", |
| 40 | "ay", |
| 41 | "az", |
| 42 | "bx", |
| 43 | "by", |
| 44 | "bz", |
| 45 | "height", |
| 46 | "thickness", |
| 47 | ] |
| 48 | wall_params = dict(zip(wall_args, params[0:8])) |
| 49 | entity = Wall(id=entity_id, **wall_params) |
| 50 | existing_walls.append(entity_id) |
| 51 | self.walls.append(entity) |
| 52 | elif entity_label == Door.entity_label: |
| 53 | wall_id = int(params[0].split("_")[1]) |
| 54 | if wall_id not in existing_walls: |
| 55 | continue |
| 56 | |
| 57 | door_args = [ |
| 58 | "position_x", |
| 59 | "position_y", |
| 60 | "position_z", |
| 61 | "width", |
| 62 | "height", |
| 63 | ] |
| 64 | door_params = dict(zip(door_args, params[1:6])) |
| 65 | entity = Door( |
| 66 | id=entity_id, |
| 67 | wall_id=wall_id, |
| 68 | **door_params, |
| 69 | ) |
| 70 | self.doors.append(entity) |
| 71 | elif entity_label == Window.entity_label: |
| 72 | wall_id = int(params[0].split("_")[1]) |
| 73 | if wall_id not in existing_walls: |
| 74 | continue |
| 75 | |
| 76 | window_args = [ |
| 77 | "position_x", |
| 78 | "position_y", |
| 79 | "position_z", |
| 80 | "width", |
| 81 | "height", |
| 82 | ] |
| 83 | window_params = dict(zip(window_args, params[1:6])) |
| 84 | entity = Window( |
| 85 | id=entity_id, |
| 86 | wall_id=wall_id, |
| 87 | **window_params, |
| 88 | ) |
| 89 | self.windows.append(entity) |
| 90 | elif entity_label == Bbox.entity_label: |
| 91 | class_name = params[0] |
| 92 | bbox_args = [ |
| 93 | "position_x", |
| 94 | "position_y", |
| 95 | "position_z", |
| 96 | "angle_z", |
| 97 | "scale_x", |
| 98 | "scale_y", |
| 99 | "scale_z", |
| 100 | ] |
| 101 | bbox_params = dict(zip(bbox_args, params[1:8])) |
| 102 | entity = Bbox( |
| 103 | id=entity_id, |
| 104 | class_name=class_name, |
| 105 | **bbox_params, |
| 106 | ) |
| 107 | self.bboxes.append(entity) |
| 108 | except Exception as e: |
| 109 | continue |
| 110 | |
| 111 | def to_boxes(self): |
| 112 | boxes = [] |
| 113 | lookup = {} |
| 114 | for wall in self.walls: |
| 115 | # assume the walls has a thickness of 0.0 for now |
| 116 | thickness = 0.0 |
| 117 | corner_a = np.array([wall.ax, wall.ay, wall.az]) |
| 118 | corner_b = np.array([wall.bx, wall.by, wall.bz]) |
| 119 | length = np.linalg.norm(corner_a - corner_b) |
| 120 | direction = corner_b - corner_a |
| 121 | angle = np.arctan2(direction[1], direction[0]) |
| 122 | lookup[wall.id] = {"wall": wall, "angle": angle} |
| 123 | |
| 124 | center = (corner_a + corner_b) * 0.5 + np.array([0, 0, 0.5 * wall.height]) |
| 125 | scale = np.array([length, thickness, wall.height]) |
| 126 | rotation = R.from_rotvec([0, 0, angle]).as_matrix() |
| 127 | box = { |
| 128 | "id": wall.id, |
| 129 | "class": Wall.entity_label, |
| 130 | "label": Wall.entity_label, |
| 131 | "center": center, |
| 132 | "rotation": rotation, |
| 133 | "scale": scale, |
| 134 | } |
| 135 | boxes.append(box) |
| 136 | |
| 137 | for fixture in self.doors + self.windows: |
| 138 | wall_id = fixture.wall_id |
| 139 | wall_info = lookup.get(wall_id, None) |
| 140 | if wall_info is None: |
| 141 | continue |
| 142 | |
| 143 | wall = wall_info["wall"] |
| 144 | angle = wall_info["angle"] |
| 145 | thickness = wall.thickness |
| 146 | |
| 147 | center = np.array( |
| 148 | [fixture.position_x, fixture.position_y, fixture.position_z] |
| 149 | ) |
| 150 | scale = np.array([fixture.width, thickness, fixture.height]) |
| 151 | rotation = R.from_rotvec([0, 0, angle]).as_matrix() |
| 152 | class_prefix = 1000 if fixture.entity_label == Door.entity_label else 2000 |
| 153 | box = { |
| 154 | "id": fixture.id + class_prefix, |
| 155 | "class": fixture.entity_label, |
| 156 | "label": fixture.entity_label, |
| 157 | "center": center, |
| 158 | "rotation": rotation, |
| 159 | "scale": scale, |
| 160 | } |
| 161 | boxes.append(box) |
| 162 | |
| 163 | for bbox in self.bboxes: |
| 164 | center = np.array([bbox.position_x, bbox.position_y, bbox.position_z]) |
| 165 | scale = np.array([bbox.scale_x, bbox.scale_y, bbox.scale_z]) |
| 166 | rotation = R.from_rotvec([0, 0, bbox.angle_z]).as_matrix() |
| 167 | class_name = bbox.class_name |
| 168 | box = { |
| 169 | "id": bbox.id + 3000, |
| 170 | "class": Bbox.entity_label, |
| 171 | "label": class_name, |
| 172 | "center": center, |
| 173 | "rotation": rotation, |
| 174 | "scale": scale, |
| 175 | } |
| 176 | boxes.append(box) |
| 177 | |
| 178 | return boxes |
| 179 | |
| 180 | def get_entities(self): |
| 181 | return self.walls + self.doors + self.windows + self.bboxes |
| 182 | |
| 183 | def normalize_and_discretize(self, num_bins): |
| 184 | for entity in self.get_entities(): |
| 185 | entity.normalize_and_discretize(num_bins) |
| 186 | |
| 187 | def undiscretize_and_unnormalize(self, num_bins): |
| 188 | for entity in self.get_entities(): |
| 189 | entity.undiscretize_and_unnormalize(num_bins) |
| 190 | |
| 191 | def translate(self, translation: np.ndarray): |
| 192 | for entity in self.get_entities(): |
| 193 | entity.translate(translation) |
| 194 | |
| 195 | def rotate(self, angle: float): |
| 196 | for entity in self.get_entities(): |
| 197 | entity.rotate(angle) |
| 198 | |
| 199 | def scale(self, scale: float): |
| 200 | for entity in self.get_entities(): |
| 201 | entity.scale(scale) |
| 202 | |
| 203 | def to_language_string(self): |
| 204 | entity_strings = [] |
| 205 | for entity in self.get_entities(): |
| 206 | entity_strings.append(entity.to_language_string()) |
| 207 | return "\n".join(entity_strings) |
| 208 | |
| 209 | def filter_empty_bboxes(self, points, num_points=100, margin=0.15): |
| 210 | filtered_bboxes = [] |
| 211 | for bbox in self.bboxes: |
| 212 | box_center = np.array([bbox.position_x, bbox.position_y, bbox.position_z]) |
| 213 | box_size = np.array([bbox.scale_x, bbox.scale_y, bbox.scale_z]) |
| 214 | rot_mat = R.from_rotvec(np.array([0, 0, bbox.angle_z])).as_matrix() |
| 215 | |
| 216 | translated_points = points - np.array(box_center) |
| 217 | rotated_points = translated_points @ rot_mat.T |
| 218 | box_min = -box_size / 2 - margin |
| 219 | box_max = box_size / 2 + margin |
| 220 | points_mask = np.all(rotated_points >= box_min, axis=1) & np.all( |
| 221 | rotated_points <= box_max, axis=1 |
| 222 | ) |
| 223 | if np.sum(points_mask) > num_points: |
| 224 | filtered_bboxes.append(bbox) |
| 225 | |
| 226 | self.bboxes = filtered_bboxes |
| 227 | return filtered_bboxes |
| 228 | |
| 229 | @staticmethod |
| 230 | def sort_entities(entities, wall_lookup=None): |
| 231 | if not entities: |
| 232 | return [] |
| 233 | sort_keys = [entity.sort_key() for entity in entities] |
| 234 | sorted_idx = np.lexsort(np.stack(sort_keys).T) |
| 235 | sorted_entities = [entities[i] for i in sorted_idx] |
| 236 | for i, entity in enumerate(sorted_entities): |
| 237 | entity.id = i |
| 238 | if wall_lookup is not None and hasattr(entity, "wall_id"): |
| 239 | entity.wall_id = wall_lookup[entity.wall_id] |
| 240 | return sorted_entities |
| 241 | |
| 242 | def reorder_entities( |
| 243 | self, |
| 244 | filter_small_objects=True, |
| 245 | filter_unknown=True, |
| 246 | size_threshold=0.15, |
| 247 | ): |
| 248 | bboxes = [] |
| 249 | # filter invalid bboxes |
| 250 | for bbox in self.bboxes: |
| 251 | if filter_small_objects and ( |
| 252 | bbox.scale_x < size_threshold |
| 253 | and bbox.scale_y < size_threshold |
| 254 | and bbox.scale_z < size_threshold |
| 255 | ): |
| 256 | continue |
| 257 | if filter_unknown and (not bbox.class_name or bbox.class_name == "unknown"): |
| 258 | continue |
| 259 | bboxes.append(bbox) |
| 260 | |
| 261 | wall_lookup = {} |
| 262 | sorted_walls = [] |
| 263 | if len(self.walls) > 0: |
| 264 | sort_keys = [] |
| 265 | for wi, wall in enumerate(self.walls): |
| 266 | sort_keys.append(wall.sort_key()) |
| 267 | sorted_idx = np.lexsort(np.stack(sort_keys).T) |
| 268 | sorted_walls = [self.walls[i] for i in sorted_idx] |
| 269 | for wi, wall in enumerate(sorted_walls): |
| 270 | wall_lookup[wall.id] = wi |
| 271 | wall.id = wi |
| 272 | |
| 273 | sorted_doors = self.sort_entities(self.doors, wall_lookup) |
| 274 | sorted_windows = self.sort_entities(self.windows, wall_lookup) |
| 275 | sorted_bboxes = self.sort_entities(bboxes) |
| 276 | |
| 277 | self.walls = sorted_walls |
| 278 | self.doors = sorted_doors |
| 279 | self.windows = sorted_windows |
| 280 | self.bboxes = sorted_bboxes |