Skip to content

Floorplan YAML Construction

YAML serialisation of indoor building geometry.

This module provides utilities for converting labelled room polygons into a structured, human-readable YAML representation of a building floorplan. It operates on GeoDataFrame-derived polygon geometries and produces a schema focused on architectural topology rather than geospatial metadata.

Responsibilities of this module include: - Converting polygon exteriors into ordered wall segments. - Mapping labelled polygons and canonical door segments to room definitions. - Assembling building- and floor-level metadata into a serialisable form. - Writing the resulting structure to disk as YAML.

The module assumes: - One polygon corresponds to one room. - Polygon geometries are valid, closed, and planar. - Coordinates exist in a local Cartesian space with no CRS. - Room labels have already been attached upstream.

DXF parsing, spatial joins, and geometry construction are explicitly out of scope and must be handled before using this module.

FlowList

Bases: list

List subtype used to force YAML flow-style serialisation.

Source code in src/floorplan_extractor/yaml_construction.py
42
43
class FlowList(list):
    """List subtype used to force YAML flow-style serialisation."""

apply_door_cardinality_policy(rooms, *, singleton_policy='error')

Validate door attachments and handle doors connected to only one room.

The runtime requires each model door to connect exactly two rooms. A singleton segment can instead be restored to the physical wall geometry when the model intentionally treats the outside as impassable.

Parameters:

Name Type Description Default
rooms list[dict]

Room definitions containing walls and doors segment lists.

required
singleton_policy (error, wall)

Whether a door attached to one room raises an error or is restored as a physical wall segment.

"error"

Returns:

Type Description
list[dict]

Copied room definitions with the selected policy applied.

Raises:

Type Description
InvalidDefinitionError

If singleton_policy is unsupported.

InvalidDoorError

If a door does not connect exactly two rooms and the selected policy cannot resolve it.

Source code in src/floorplan_extractor/yaml_construction.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def apply_door_cardinality_policy(
    rooms: list[dict],
    *,
    singleton_policy: Literal["error", "wall"] = "error",
) -> list[dict]:
    """
    Validate door attachments and handle doors connected to only one room.

    The runtime requires each model door to connect exactly two rooms. A
    singleton segment can instead be restored to the physical wall geometry
    when the model intentionally treats the outside as impassable.

    Parameters
    ----------
    rooms : list[dict]
        Room definitions containing ``walls`` and ``doors`` segment lists.
    singleton_policy : {"error", "wall"}, default="error"
        Whether a door attached to one room raises an error or is restored as a
        physical wall segment.

    Returns
    -------
    list[dict]
        Copied room definitions with the selected policy applied.

    Raises
    ------
    InvalidDefinitionError
        If ``singleton_policy`` is unsupported.
    InvalidDoorError
        If a door does not connect exactly two rooms and the selected policy
        cannot resolve it.

    """
    if singleton_policy not in {"error", "wall"}:
        msg = f"Unsupported singleton door policy: {singleton_policy}"
        raise InvalidDefinitionError(msg)

    copied_rooms = [
        {
            **room,
            "walls": [FlowList(wall) for wall in room.get("walls", [])],
            "doors": [FlowList(door) for door in room.get("doors", [])],
        }
        for room in rooms
    ]
    attachments: dict[tuple[tuple[float, float], ...], set[int]] = {}
    for room_index, room in enumerate(copied_rooms):
        for door in room["doors"]:
            attachments.setdefault(_segment_key(door), set()).add(room_index)

    over_connected = {
        segment: room_indexes
        for segment, room_indexes in attachments.items()
        if len(room_indexes) > 2
    }
    if over_connected:
        segment, room_indexes = next(iter(over_connected.items()))
        msg = f"Door segment {segment} is attached to {len(room_indexes)} rooms"
        raise InvalidDoorError(msg)

    singleton_segments = {
        segment
        for segment, room_indexes in attachments.items()
        if len(room_indexes) == 1
    }
    if singleton_segments and singleton_policy == "error":
        segment = next(iter(singleton_segments))
        room_index = next(iter(attachments[segment]))
        room_name = copied_rooms[room_index]["name"]
        msg = f"Door segment {segment} is attached only to room '{room_name}'"
        raise InvalidDoorError(msg)

    if singleton_policy == "wall":
        for room in copied_rooms:
            retained_doors = []
            wall_segments = {_segment_key(wall) for wall in room["walls"]}
            for door in room["doors"]:
                segment = _segment_key(door)
                if segment not in singleton_segments:
                    retained_doors.append(door)
                    continue
                if segment not in wall_segments:
                    room["walls"].append(FlowList(door))
                    wall_segments.add(segment)
            room["doors"] = retained_doors

    return copied_rooms

build_yaml_structure(*, building_name, building_address, floor_level, rooms, spatial_units)

Construct a YAML-ready building data structure from room definitions.

This function assembles building metadata and a collection of room definitions into a nested dictionary matching the expected output schema. The resulting structure is suitable for serialisation using yaml.safe_dump without further transformation.

The function does not perform validation of room geometry or schema completeness. It assumes that each room dictionary contains, at a minimum, the keys: - "name" - "walls" - "doors"

Parameters:

Name Type Description Default
building_name str

Name of the building.

required
building_address str

Address of the building.

required
floor_level int

Floor identifier to associate with the provided rooms.

required
rooms list[dict]

List of room definitions produced by polygons_to_rooms.

required
spatial_units SpatialUnits

Explicit conversion from source coordinates to canonical metres.

required

Returns:

Type Description
dict

Nested dictionary structured as:

{ "schema_version": 1, "coordinate_unit": "m", "coordinate_provenance": { "source_unit": str, "units_per_metre": float, }, "building": { "name": str, "address": str, "floors": [ { "level": int, "rooms": list[dict], } ], } }

Source code in src/floorplan_extractor/yaml_construction.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def build_yaml_structure(
    *,
    building_name: str,
    building_address: str,
    floor_level: int,
    rooms: list[dict],
    spatial_units: SpatialUnits,
) -> dict:
    """
    Construct a YAML-ready building data structure from room definitions.

    This function assembles building metadata and a collection of room
    definitions into a nested dictionary matching the expected output
    schema. The resulting structure is suitable for serialisation using
    `yaml.safe_dump` without further transformation.

    The function does not perform validation of room geometry or schema
    completeness. It assumes that each room dictionary contains, at a
    minimum, the keys:
        - "name"
        - "walls"
        - "doors"

    Parameters
    ----------
    building_name : str
        Name of the building.
    building_address : str
        Address of the building.
    floor_level : int
        Floor identifier to associate with the provided rooms.
    rooms : list[dict]
        List of room definitions produced by `polygons_to_rooms`.
    spatial_units : floorplan_extractor.spatial_units.SpatialUnits
        Explicit conversion from source coordinates to canonical metres.

    Returns
    -------
    dict
        Nested dictionary structured as:

        {
            "schema_version": 1,
            "coordinate_unit": "m",
            "coordinate_provenance": {
                "source_unit": str,
                "units_per_metre": float,
            },
            "building": {
                "name": str,
                "address": str,
                "floors": [
                    {
                        "level": int,
                        "rooms": list[dict],
                    }
                ],
            }
        }

    """
    canonical_rooms = [_room_to_canonical_metres(room, spatial_units) for room in rooms]
    return {
        "schema_version": SPATIAL_SCHEMA_VERSION,
        "coordinate_unit": CoordinateUnit.METRE.value,
        "coordinate_provenance": {
            "source_unit": spatial_units.source_unit,
            "units_per_metre": spatial_units.units_per_metre,
        },
        "building": {
            "name": building_name,
            "address": building_address,
            "floors": [
                {
                    "level": floor_level,
                    "rooms": canonical_rooms,
                }
            ],
        },
    }

polygons_to_rooms(gdf, room_name_column, door_column=None, opening_column=None, opening_tolerance=1e-06)

Convert labelled polygons into room definitions.

Parameters:

Name Type Description Default
gdf GeoDataFrame

GeoDataFrame containing polygon geometries.

required
room_name_column str

Column containing room names.

required
door_column str or None

Optional column containing lists of canonical door segments represented as [x1, y1, x2, y2]. These spans are emitted as doors and removed from the physical wall list.

None
opening_column str or None

Optional column containing lists of non-operable opening segments. When provided, those segments are emitted as openings and removed from the room's physical wall list.

None
opening_tolerance float

Maximum boundary distance accepted when removing an opening from the physical wall list.

1e-6

Returns:

Type Description
list[dict]

Room definitions containing name, walls, and doors values suitable for YAML serialisation.

Source code in src/floorplan_extractor/yaml_construction.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
def polygons_to_rooms(
    gdf: gpd.GeoDataFrame,
    room_name_column: str,
    door_column: str | None = None,
    opening_column: str | None = None,
    opening_tolerance: float = 1.0e-6,
) -> list[dict]:
    """
    Convert labelled polygons into room definitions.

    Parameters
    ----------
    gdf : geopandas.GeoDataFrame
        GeoDataFrame containing polygon geometries.
    room_name_column : str
        Column containing room names.
    door_column : str or None
        Optional column containing lists of canonical door segments represented
        as ``[x1, y1, x2, y2]``. These spans are emitted as doors and removed
        from the physical wall list.
    opening_column : str or None
        Optional column containing lists of non-operable opening segments. When
        provided, those segments are emitted as ``openings`` and removed from
        the room's physical wall list.
    opening_tolerance : float, default 1e-6
        Maximum boundary distance accepted when removing an opening from the
        physical wall list.

    Returns
    -------
    list[dict]
        Room definitions containing ``name``, ``walls``, and ``doors`` values
        suitable for YAML serialisation.

    """
    rooms = []

    for _, row in gdf.iterrows():
        door_values = []
        if door_column and door_column in row and row[door_column]:
            door_values = [FlowList(d) for d in row[door_column]]

        opening_values = []
        if opening_column and opening_column in row and row[opening_column]:
            opening_values = [FlowList(opening) for opening in row[opening_column]]
        opening_lines = [
            LineString([(opening[0], opening[1]), (opening[2], opening[3])])
            for opening in opening_values
        ]
        door_lines = [
            LineString([(door[0], door[1]), (door[2], door[3])]) for door in door_values
        ]

        d = {
            "name": row[room_name_column],
            "walls": _polygon_to_walls(
                row.geometry,
                [*opening_lines, *door_lines],
                opening_tolerance=opening_tolerance,
            ),
            "doors": door_values,
        }
        if opening_column is not None:
            d["openings"] = opening_values
        rooms.append(d)

    return rooms

register_yaml_representers()

Register custom YAML representers used by the building serialisation module.

This function registers a representer for the FlowList type with PyYAML's SafeDumper, ensuring that wall segment coordinate lists are emitted in flow style (e.g. [x1, y1, x2, y2]) when using yaml.safe_dump.

The registration mutates PyYAML's global dumper state and therefore must be called exactly once, before any YAML serialisation occurs. It is intentionally explicit to avoid hidden import-time side effects.

Returns:

Type Description
None
Source code in src/floorplan_extractor/yaml_construction.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def register_yaml_representers() -> None:
    """
    Register custom YAML representers used by the building serialisation module.

    This function registers a representer for the `FlowList` type with
    PyYAML's `SafeDumper`, ensuring that wall segment coordinate lists are
    emitted in flow style (e.g. `[x1, y1, x2, y2]`) when using
    `yaml.safe_dump`.

    The registration mutates PyYAML's global dumper state and therefore
    must be called exactly once, before any YAML serialisation occurs.
    It is intentionally explicit to avoid hidden import-time side effects.

    Returns
    -------
    None

    """
    yaml.SafeDumper.add_representer(FlowList, _represent_flow_list)