Repository navigation
Expand file tree
/
Copy pathbuilding_model.py
More file actions
1296 lines (1119 loc) · 55.7 KB
/
Copy pathbuilding_model.py
File metadata and controls
1296 lines (1119 loc) · 55.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
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
331
332
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Canonical building model: the cross-discipline linking layer.
Problem: every discipline draws the same building in its own coordinate
system with its own symbols, and nothing carries a shared ID except the
room number. This module defines the ONE canonical model everything
registers into:
* The ARCHITECTURAL FLOOR PLAN is the reference frame. Rooms (name +
number) are the primary key: ``Space.id = "{level}-{number}"``.
* Lighting plans, mechanical plans, and elevations are parsed into
sheet-local models, REGISTERED into arch-plan coordinates
(registration.py), then linked: fixtures/sensors/diffusers land in
spaces by point-in-polygon; elevation windows land on rooms via
facade wall-run correspondence; duct-tracing zones attach by diffuser
positions (no fragile cross-sheet id matching).
* Zones are MANY-TO-MANY with spaces (an open office can span two
zones). There is no zone tree.
Provenance: EVERY derived fact carries a Provenance record (sheet id,
sheet revision, extraction method, confidence, source bbox). Facts from a
newer revision of the same sheet SUPERSEDE older facts -- they are kept
in ``history``, never silently overwritten.
Coordinate frame (canonical): meters, y growing DOWNWARD (drawing frame,
matches every synth layout and sheet raster). BEM export flips y to
north-up; see bem_export.model_from_takeoff.
JSON: BuildingModel.to_json() / from_json() round-trip the whole model
(model_version included) so the canonical model is a versioned artifact
that diffs cleanly across drawing revisions.
"""
from __future__ import annotations
import json
import types
from dataclasses import dataclass, field, fields, is_dataclass
from typing import Any, Dict, List, Literal, Optional, Union, get_args, get_origin, get_type_hints
from datasets_adapter import ScheduleEntry
MODEL_VERSION = "1.3"
# 1.0 -> 1.1: SpaceOpening gained ``source_provenance`` (1-2 per-sheet records,
# issue #663). 1.0 payloads are migrated on load by _migrate_model_dict.
# 1.1 -> 1.2: SpaceOpening gained ``adjacent_space_id`` (the space on the far
# side of an interior wall opening, issue #666). Older payloads load with it
# None, which is what the default already gives.
# Links below this confidence are flagged for human review, not silently
# accepted (review queue, not dropped).
REVIEW_CONFIDENCE = 0.80
# Auto-triage via the local review_classifier TypedDecider is ON by default.
# Low-confidence results are automatically routed to the review queue.
ENABLE_AUTO_TRIAGE = True
# ---------------------------------------------------------------------------
# Provenance + revisions
# ---------------------------------------------------------------------------
@dataclass
class Provenance:
"""Where one fact came from. Attached to EVERY derived fact."""
sheet_id: str # e.g. "arch_A101", "elev_A201"
revision: int # sheet revision this fact was extracted from
method: str # e.g. "grid_registration", "geometric_fallback",
# "point_in_polygon", "duct_tracing", "schedule_join"
confidence: float # 0..1
bbox: Optional[list] = None # [xtl,ytl,xbr,ybr] in sheet px, if applicable
note: str = ""
@dataclass
class SymbolLinkage:
"""Explicit link between a symbol instance and its schedule row.
Represents a resolved or unresolved link from a symbol detection
(e.g. window tag) to a schedule entry. The linkage graph is
queryable: callers can traverse from symbol → schedule row to
get dimensions, type, and other metadata for takeoffs.
Attributes:
symbol_id: Unique identifier for this symbol instance (detection).
symbol_tag: The tag label from the symbol (e.g. "W1", "D1").
category: Symbol category (e.g. "window", "door").
schedule_entry: The matched schedule entry, or None if unlinked.
confidence: Confidence score for the match (0..1).
provenance: Provenance information (sheet, revision, method).
"""
symbol_id: str
symbol_tag: str
category: str
schedule_entry: "ScheduleEntry | None" = None
confidence: float = 0.0
provenance: Provenance = field(default_factory=lambda: Provenance("", 0, "", 0.0))
@dataclass
class RevisionEvent:
"""One entry in the model's revision log."""
seq: int
sheet_id: str
revision: int
action: str # "ingest" | "relink" | "supersede"
note: str = ""
# ---------------------------------------------------------------------------
# Component references (sheet-detected equipment, registered to canonical m)
# ---------------------------------------------------------------------------
@dataclass
class ComponentRef:
"""One detected equipment instance, in canonical meters."""
id: str # stable within its sheet, e.g. "VAV-1", "D3", "A-12"
type: str # "vav" | "ahu" | "diffuser" | "grille" | "sensor" |
# "fixture" | "window"
x_m: float
y_m: float
tag: str = "" # schedule tag, e.g. "A", "VAV-1"
provenance: Provenance | None = None
history: List[Provenance] = field(default_factory=list)
# ---------------------------------------------------------------------------
# Space sub-records
# ---------------------------------------------------------------------------
@dataclass
class SpaceOpening:
"""One window/door on this space's walls (from an elevation), or a skylight on its roof."""
id: str
tag: str
category: str # "window" | "door" | "skylight"
width_m: float
height_m: float
sill_m: Optional[float] = None
head_m: Optional[float] = None # sill + height; drives daylighting
host_facade: str = "" # e.g. "south"
host_interval_m: Optional[list] = None # [s0, s1] along facade (IFC: along host wall), m
s_center_m: Optional[float] = None # exact along-wall position
area_m2: Optional[float] = None
provenance: Provenance | None = None
needs_review: bool = True
history: List[Provenance] = field(default_factory=list)
# Roof glazing (roadmap item 3). A skylight is category="skylight" with
# host_facade="roof"; sill/head/host_interval do not apply. Tilt is from
# horizontal (0 = flat roof, the current convention), azimuth is the
# outward normal's compass bearing (degrees clockwise from north). Both are
# None for wall openings and for skylights whose roof plane is unknown.
tilt_deg: Optional[float] = None
azimuth_deg: Optional[float] = None
# Skylights only: plan centre [x, y] in the space polygon's frame (y-down
# metres); width_m runs along x, height_m along y. None when the position
# is unknown (drawing takeoff lines carry a count, not a position).
plan_center_m: Optional[list] = None
# Per-sheet observations of this ONE logical opening (issue #663). A
# window that spans two levels is seen on two adjacent elevation sheets;
# cross-level dedup (#664) collapses them into one SpaceOpening and keeps
# both records here. 1 record for a single-sheet opening, at most 2.
# ``provenance`` stays the primary record (== source_provenance[0] when
# populated) so every existing reader keeps working unchanged.
source_provenance: List[Provenance] = field(default_factory=list)
# Interior wall openings only (#666): the space on the far side of the
# wall. The opening is stored once, on the lower-id space, so a door is
# never counted twice; None for exterior openings and skylights.
adjacent_space_id: Optional[str] = None
# The assembly this opening is built from (a key into
# BuildingModel.constructions, #747). Empty means not yet known.
construction_id: str = ""
def add_source_provenance(self, prov: Provenance) -> None:
"""Record one more source sheet for this opening (max 2, distinct sheets).
The first record also becomes ``provenance`` when none is set.
Raises ValueError on a third record or a repeated (sheet, revision).
"""
if self.provenance is not None and not self.source_provenance:
self.source_provenance.append(self.provenance)
key = (prov.sheet_id, prov.revision)
if any((p.sheet_id, p.revision) == key for p in self.source_provenance):
raise ValueError(
f"opening {self.id}: sheet {prov.sheet_id} rev {prov.revision} already recorded"
)
if len(self.source_provenance) >= MAX_OPENING_SOURCES:
raise ValueError(
f"opening {self.id}: at most {MAX_OPENING_SOURCES} source provenance records"
)
self.source_provenance.append(prov)
if self.provenance is None:
self.provenance = prov
@property
def source_sheet_ids(self) -> List[str]:
"""Sheet ids this opening was observed on (primary first)."""
if self.source_provenance:
return [p.sheet_id for p in self.source_provenance]
return [self.provenance.sheet_id] if self.provenance is not None else []
# A logical opening is observed on at most two adjacent elevation sheets.
MAX_OPENING_SOURCES = 2
@dataclass
class FixtureInstance:
"""One light fixture assigned to this space."""
id: str
tag: str
fixture_class: str
x_m: float
y_m: float
watts: Optional[float] = None
provenance: Provenance | None = None
@dataclass
class SpaceLighting:
fixtures: List[FixtureInstance] = field(default_factory=list)
total_w: float = 0.0
lpd_w_m2: Optional[float] = None
lpd_w_ft2: Optional[float] = None
provenance: Provenance | None = None
unmatched_tags: List[str] = field(default_factory=list)
@dataclass
class SpaceUse:
"""Occupant, plug-load and schedule inputs for one space (#685).
Filled from the drawings when they carry a value; otherwise
``space_use_defaults.apply_space_use_defaults`` fills the gaps from the
DOE Commercial Prototype Building Models (ASHRAE 90.1-2019) and records
that in ``provenance`` (method ``"doe_prototype_default"``).
``space_type`` is the key into ``space_use_defaults_data.SPACE_USE_DEFAULTS``.
Schedule fields name a schedule in ``space_use_defaults_data.SCHEDULES``.
"""
space_type: str = ""
people_per_m2: Optional[float] = None
equipment_w_m2: Optional[float] = None
lighting_schedule: str = ""
occupancy_schedule: str = ""
equipment_schedule: str = ""
# total heat per occupant (W/person) from the prototype activity
# schedule (#693); None when neither drawings nor prototype give one
activity_w_per_person: Optional[float] = None
provenance: Provenance | None = None
@dataclass
class SpaceHVAC:
zone_ids: List[str] = field(default_factory=list) # many-to-many
diffusers: List[ComponentRef] = field(default_factory=list)
sensors: List[ComponentRef] = field(default_factory=list)
terminal_units: List[ComponentRef] = field(default_factory=list)
provenance: Provenance | None = None
# ---------------------------------------------------------------------------
# Daylighting: sidelighted zones per ASHRAE 90.1 (from exact window placement)
# ---------------------------------------------------------------------------
@dataclass
class DaylitZone:
"""One sidelighted area polygon inside a space, per ASHRAE 90.1.
Geometry: from the host window's head height H and wall interval,
primary extends inward by ~1xH, secondary by ~1xH..2xH, laterally
window width + ~1xH each side, all clipped to the room polygon.
Exact factors live in DaylightParams (elevation_windows.py); they
vary by 90.1 version, so the standard + factors are recorded here.
"""
id: str
zone_class: str # "primary" | "secondary" | "under_skylight"
window_id: str # the SpaceOpening this derives from
polygon_m: List[list] = field(default_factory=list)
area_m2: float = 0.0
head_height_m: Optional[float] = None
provenance: Provenance | None = None
@dataclass
class SpaceDaylight:
primary: List[DaylitZone] = field(default_factory=list)
secondary: List[DaylitZone] = field(default_factory=list)
params_note: str = "" # e.g. "90.1-2019 approx: P=1.0xH, S=2.0xH"
provenance: Provenance | None = None
# Daylight area under skylights (roadmap item 3, toplighting). One zone
# per placed skylight; toplit_m2 is the area of their union within the
# space, so overlapping zones are not double counted. Skylights with no
# known plan position are named in unplaced_skylights, never guessed.
toplit: List[DaylitZone] = field(default_factory=list)
toplit_m2: float = 0.0
unplaced_skylights: List[str] = field(default_factory=list)
@property
def primary_m2(self) -> float:
return sum(z.area_m2 for z in self.primary)
@property
def secondary_m2(self) -> float:
return sum(z.area_m2 for z in self.secondary)
# ---------------------------------------------------------------------------
# Space: the primary key of the whole model
# ---------------------------------------------------------------------------
@dataclass
class Space:
id: str # "{level}-{number}" or "{level}-UNLABELED-{k}"
level_id: str
name: str = "" # human label, e.g. "OPEN OFFICE"
number: str = "" # room number, e.g. "101"
polygon_m: List[list] = field(default_factory=list) # [[x,y],...] y-down
area_m2: Optional[float] = None
volume_m3: Optional[float] = None
openings: List[SpaceOpening] = field(default_factory=list)
lighting: SpaceLighting = field(default_factory=SpaceLighting)
hvac: SpaceHVAC = field(default_factory=SpaceHVAC)
use: SpaceUse = field(default_factory=SpaceUse) # #685 loads + schedules
daylight: "SpaceDaylight" = field(default_factory=lambda: SpaceDaylight())
core_provenance: Provenance | None = None # polygon + name/number source
label_confidence: float = 0.0
poly_type: str = "room" # "room" | "shaft" | "closet" | "elevator_core" | "unassigned"
# polygon_classify confidence for poly_type; None when the space was not
# classified (e.g. IFC import, where IfcSpace says what it is)
poly_type_confidence: Optional[float] = None
# Alex's vestibule rule (#747, 2026-10-11): True when the space meets his
# rule - exterior door, small floor area, connects to a lobby or main
# entrance. Detection never reclassifies the space; conditioning still
# comes from the HVAC capacity rules alone.
is_vestibule: bool = False
# roadmap item 6: area-weighted exterior wall U-value over this space's
# envelope segments, sum(U_i * A_i) / sum(A_i), written by
# constructions.apply_wall_u_rollup. None until the rollup runs or when
# no segment of the space has a construction with a known U-value.
wall_u_value_w_m2k: Optional[float] = None
# Ids of closets/shafts folded into this space by space_merge (the user's
# rule, 2026-10-04). Empty for a space that absorbed nothing.
# finish floors laid on this space's structural slab (#584):
# [{"global_id": str, "thickness_m": float}]; never floor area or a BEM surface
floor_finishes: List[dict] = field(default_factory=list)
# ceiling from IfcCovering CEILING (#583): underside above the floor, and
# covering top to the underside of the slab above; None when not known
ceiling_height_m: Optional[float] = None
plenum_depth_m: Optional[float] = None
# full floor-to-top height of the space as the source states it (IFC space
# body extrusion or Qto_SpaceBaseQuantities.Height); a height past the next
# storey marks an atrium (#640). None when not stated.
height_m: Optional[float] = None
merged_from: List[str] = field(default_factory=list)
# ASHRAE 90.1-2019 Section 3.2 category from the heating/cooling output of
# the zones serving it, per floor area (#747): {"category": "conditioned" |
# "semiheated" | "unconditioned" | "review", "reasons", "derived", Btu/h
# and Btu/h-ft2 values, "zones", "sources", "review"}. None when no zone
# with a terminal unit was found for the space (never defaulted).
conditioning: Optional[dict] = None
history: List[Provenance] = field(default_factory=list)
@property
def window_area_m2(self) -> float:
return sum(o.area_m2 or 0.0 for o in self.openings if o.category == "window")
@property
def label(self) -> str:
return f"{self.name} {self.number}".strip() or "(unlabeled)"
@dataclass
class Zone:
"""One HVAC zone. MANY-TO-MANY with spaces: zone.space_ids and
Space.hvac.zone_ids are both lists; neither is a tree."""
id: str
level_id: str
space_ids: List[str] = field(default_factory=list)
terminal_unit: Optional[ComponentRef] = None
diffusers: List[ComponentRef] = field(default_factory=list)
sensors: List[ComponentRef] = field(default_factory=list)
duct_length_m: Optional[float] = None
# design supply airflow of the zone's terminal unit from its schedule row
# (#746), m3/s; None when the schedule gives no airflow or no units
design_airflow_max_m3s: Optional[float] = None
design_airflow_min_m3s: Optional[float] = None
# tag of the scheduled central air handler (AHU/RTU) feeding this zone's
# terminal unit (#746), from the box-to-unit link on the schedules; ""
# when not known
air_loop: str = ""
provenance: Provenance | None = None
history: List[Provenance] = field(default_factory=list)
@dataclass
class AirLoop:
"""One scheduled central air handler (AHU/RTU) and the HVAC zones on it
(#746, option 3). Written to gbXML as an ``AirLoop``; each thermal zone
it serves references it. Capacities are as scheduled, in Btu/h; None when
the schedule row doesn't give one with units. ``box_airflow_sum_m3s`` is
the summed max airflow of its boxes (None unless every box has one): it
may exceed the supply fan airflow because of diversity, which is normal.
"""
tag: str
sheet: str = ""
supply_airflow_m3s: Optional[float] = None
cooling_total_btuh: Optional[float] = None
cooling_sensible_btuh: Optional[float] = None
heating_btuh: Optional[float] = None
sources: List[str] = field(default_factory=list)
box_tags: List[str] = field(default_factory=list)
zone_ids: List[str] = field(default_factory=list)
box_airflow_sum_m3s: Optional[float] = None
provenance: Provenance | None = None
@dataclass
class ServingRef:
"""One resolved serving relationship (#1237): the equipment carries it,
the HVAC zone it names is served by this piece of equipment, and
``source`` says where the relationship was read:
* ``plan_terminal_tag``: the zone's terminal unit on the plan carries
this equipment's schedule tag.
* ``schedule_box_link``: the zone's terminal box names this unit in a
schedule column (#747's box-to-unit link).
* ``plan_tag_placement``: the schedule tag is placed on the plan in a
space the zone serves (``mech_tags`` placement).
``note`` carries the human-readable chain ("via box VAV-1"). Zones that
resolve to no unit, or to more than one, get no ref and a review item.
"""
zone_id: str
source: str
confidence: float
note: str = ""
@dataclass
class Equipment:
"""One piece of scheduled mechanical equipment (#1237), the unified
model the writers consume.
Built from the mechanical-schedule rows plus the plan geometry matchline
already extracts: tag and type from the schedule row, capacities and
airflow as the schedule states them (Btu/h and m3/s, None when the row
gives no value with units), ``served_by`` naming the central unit that
feeds a terminal box ("" when the schedules name none), ``serves``
listing the HVAC zones the piece serves each with its source, and
``plan_locs`` the tag placements read off the plans. Export-agnostic:
the gbXML writer builds AirLoops from the central units, the BuildingSync
writer maps the objects directly.
``id`` is an XML-safe identifier (``eq-`` plus the normalized tag).
"""
id: str
tag: str
kind: str
sheet: str = ""
airflow_m3s: Optional[float] = None
cooling_total_btuh: Optional[float] = None
cooling_sensible_btuh: Optional[float] = None
heating_btuh: Optional[float] = None
served_by: str = ""
serves: List[ServingRef] = field(default_factory=list)
plan_locs: List[dict] = field(default_factory=list)
sources: List[str] = field(default_factory=list)
provenance: Provenance | None = None
@dataclass
class OpeningAttachmentSummary:
"""Counts of openings left unattached, broken down by failure reason.
Produced during Tier 1 geometric opening attachment
(ifc_import._attach_openings_to_spaces).
"""
no_envelope_edge: int = 0 # no envelope edge endpoint matched wall placement
ambiguous_tie: int = 0 # multiple same-length edges tied for wall position
no_ref_direction: int = 0 # envelope and entity RefDirection both unavailable
# wall direction known, but neither side of the opening lies in a space on
# the wall's level (#666)
outside_spaces: int = 0
# NOT unattached: openings attached using the host wall's own RefDirection
# because no envelope edge settled its direction (#666, confidence 0.85)
ref_direction_fallback: int = 0
# NOT unattached: openings attached by their centre whose edges reach
# another room, flagged ``adjacency_ambiguous`` for review (#681)
adjacency_ambiguous: int = 0
@property
def total(self) -> int:
return (
self.no_envelope_edge + self.ambiguous_tie + self.no_ref_direction + self.outside_spaces
)
def is_empty(self) -> bool:
return self.total == 0
def summary_line(self) -> str:
"""Human-readable one-line summary for import logs."""
notes = []
if self.ref_direction_fallback:
notes.append(f"{self.ref_direction_fallback} attached via RefDirection")
if self.adjacency_ambiguous:
notes.append(f"{self.adjacency_ambiguous} spanning a room boundary")
fb = f" ({'; '.join(notes)})" if notes else ""
if self.is_empty():
return f"0 openings unattached{fb}"
parts = []
if self.no_envelope_edge:
parts.append(f"{self.no_envelope_edge} no envelope edge")
if self.ambiguous_tie:
parts.append(f"{self.ambiguous_tie} ambiguous tie")
if self.no_ref_direction:
parts.append(f"{self.no_ref_direction} no RefDirection")
if self.outside_spaces:
parts.append(f"{self.outside_spaces} outside every space")
return f"{self.total} opening(s) unattached: {', '.join(parts)}{fb}"
@dataclass
class ShadingSurface:
"""One exterior projection that shades the envelope (roadmap item 5).
Overhangs, fins and balconies matter to BEM as shading, not as envelope:
they live here, outside ``BuildingModel.envelope``, so the envelope area
budget and closure checks never count them.
Placement is relative to the host wall segment, in its own frame:
``along_m`` runs from the segment's ``from_m`` end toward ``to_m``,
``z_m`` is height above the host level's floor, and ``depth_m`` is the
projection outward from the exterior wall face, which sits ``offset_m``
outside the segment's line. An overhang or balcony
is horizontal (``width_m`` along the wall at height ``z_m``); a fin is
vertical (at ``along_m``, from ``z_m`` up ``height_m``).
"""
id: str
kind: str # "overhang" | "fin" | "balcony" | "other"
host_wall_id: str = "" # EnvelopeWall.id; empty = no host (suspicious)
host_opening_id: str = "" # SpaceOpening.id it shades, if any
along_m: Optional[float] = None
width_m: Optional[float] = None # extent along the wall (overhang/balcony)
z_m: Optional[float] = None
depth_m: Optional[float] = None # projection from the wall face
height_m: Optional[float] = None # vertical extent (fin)
# gap from the host segment's line out to the plate's inner edge: half
# the wall thickness when the segment is a wall centreline (IFC #579),
# 0 when the segment is drawn on the exterior face
offset_m: float = 0.0
provenance: Provenance | None = None
@dataclass
class Construction:
"""One exterior wall assembly (roadmap item 6).
Drawings rarely carry assembly data, so ``u_value_w_m2k`` is often
unknown; a construction without one still identifies the wall type, and
the rollup leaves its segments out of the weighted U rather than
guessing a value.
"""
id: str # e.g. "W-1", as tagged on the wall-type legend
name: str = ""
u_value_w_m2k: Optional[float] = None # assembly U-value, SI
provenance: Provenance | None = None
# glazing only (#747): solar heat gain coefficient and visible
# transmittance, fractions
shgc: Optional[float] = None
vt: Optional[float] = None
@dataclass
class EnvelopeWall:
"""One exterior wall run (per facade segment). The detailed
area-budgeted simplification lives in geometry_simplify.py; this is
the canonical record it feeds."""
id: str
facade: str # "south" | "north" | "east" | "west"
from_m: List[float] = field(default_factory=list) # [x, y] canonical m
to_m: List[float] = field(default_factory=list)
length_m: Optional[float] = None
height_m: Optional[float] = None
area_m2: Optional[float] = None
provenance: Provenance | None = None
# roadmap item 6: the assembly this segment is built from (a key into
# BuildingModel.constructions) and the space it encloses. Empty means
# not yet known; validation names such segments rather than guessing.
construction_id: str = ""
space_id: str = ""
@dataclass
class BimOpening:
"""One window/door hosted in a BIM element (IFC Tier 0).
Tier 0 recovers the opening, its dimensions, and its host wall WITHOUT
IfcRelSpaceBoundary -- so openings are NOT attached to spaces yet.
Space attachment is Tier 1 (geometric adjacency inference).
"""
id: str # GlobalId of the IfcOpeningElement
category: str # "window" | "door" | "skylight" | "unknown"
tag: str = ""
width_m: Optional[float] = None # skylight: plan extent along x
height_m: Optional[float] = None # skylight: plan extent along y
sill_m: Optional[float] = None # above host wall base
s_center_m: Optional[float] = None # along host wall from wall start
host_global_id: str = "" # the IfcWall / IfcSlab / host element
fill_global_id: str = "" # the IfcWindow / IfcDoor
provenance: Provenance | None = None
# Skylights only (roof-hosted): plan centre [x, y] in the canonical
# y-down frame, used to attach the skylight to the space under it.
plan_center_m: Optional[list] = None
# Skylights only (#614): tilt/azimuth of the roof plane above the plan
# centre, same convention as SpaceOpening; None when no plane is known.
tilt_deg: Optional[float] = None
azimuth_deg: Optional[float] = None
# Doors only (#573): IfcDoor.OperationType as written (IFC4 occurrence or
# its type; IFC2X3 IfcDoorStyle), and what it says without guessing.
operation_type: Optional[str] = None
leaf_count: Optional[int] = None # 1 | 2; None for revolving/rolling/undefined
hinge_side: Optional[str] = None # "left" | "right" for swing doors only
# Pset_DoorCommon.GlazingAreaFraction (0..1) and the glazed area it gives.
glazing_area_fraction: Optional[float] = None
glazed_area_m2: Optional[float] = None
# Stated thermal values on the fill (#787): Pset_WindowCommon or
# Pset_DoorCommon ThermalTransmittance (W/m2K) and, for glazing,
# Pset_DoorWindowGlazingType SolarHeatGainTransmittance and
# VisibleLightTransmittance. None when the file does not state them.
u_value_w_m2k: Optional[float] = None
shgc: Optional[float] = None
vt: Optional[float] = None
thermal_reference: str = "" # the common pset's Reference, kept for traceability
@dataclass
class BimElement:
"""Raw BIM element inventory (IFC Tier 0).
Walls are ALSO mirrored into ``BuildingModel.envelope`` for the BEM
path; everything else lives here until Tier 1 assigns it a role.
"""
global_id: str
ifc_class: str # "IfcWall", "IfcSlab", ...
name: str = ""
level_id: str = ""
length_m: Optional[float] = None
width_m: Optional[float] = None
height_m: Optional[float] = None
thickness_m: Optional[float] = None # geometry or material layers
area_m2: Optional[float] = None
volume_m3: Optional[float] = None
material_layers: List[dict] = field(default_factory=list)
# [{"material": str, "thickness_m": float}] -- the analytical
# wall-thickness answer (roadmap item 1 on the BIM path)
placement_m: Optional[list] = None # [x, y, z], canonical frame
openings: List["BimOpening"] = field(default_factory=list)
provenance: Provenance | None = None
# "" for an ordinary element; "lining" for an IfcWall that only lines or
# hides inside another wall and was kept out of the envelope (#577)
role: str = ""
# "" when the file contains the element in its storey; "elevation" when
# it had no storey containment and exactly one storey fitted its
# placement height (#585)
storey_method: str = ""
@dataclass
class Level:
id: str # "L1"
name: str = ""
elevation_z_m: float = 0.0
wall_height_m: float = 3.0
# #634: True/False only when a source states it (IFC
# Pset_BuildingStoreyCommon.AboveGround); None = not stated, never guessed
above_ground: Optional[bool] = None
above_ground_source: str = ""
# ---------------------------------------------------------------------------
# Review queue: low-confidence links flagged for humans, never silently
# accepted (and never silently dropped).
# ---------------------------------------------------------------------------
@dataclass
class ReviewItem:
"""Low-confidence link flagged for human review.
A ReviewItem is created when the pipeline produces a result with
confidence below the auto-accept threshold, or when an invariant
violation is detected that requires human judgment to resolve.
Items are never silently dropped or silently accepted — every
item enters the review queue and awaits explicit confirmation or
rejection.
Attributes:
id: Unique identifier for this review item.
kind: Category of the review item (e.g. ``"window_room_link"``,
``"fixture_assignment"``). Controls routing and triage logic.
description: Human-readable description of the issue or anomaly.
confidence: Extraction confidence of the underlying fact (0.0–1.0).
Values >= 1.0 are reserved for fully confirmed facts and
cannot be combined with ``needs_review=False``.
provenance: Provenance record carrying sheet ID, revision, method,
and source bounding box of the extracted fact.
status: Current workflow status: ``"open"`` (default), ``"confirmed"``,
or ``"rejected"``.
needs_human: Estimated probability that human judgment is required
to resolve this item (0.0–1.0). Set by the triage classifier.
urgency: Urgency tier in the range 0–3. Higher values indicate
items that should be resolved before export.
auto_resolved: True when the item was resolved automatically by
the pipeline without human input (e.g. disambiguation guardrails).
resolution: Triage outcome: ``"accept"``, ``"drop"``, or ``"reassign"``.
Empty string when no resolution has been set.
needs_review: True when the item is awaiting human review.
False when the item has been reviewed and closed.
acknowledged: True when a human has explicitly acknowledged this item
(distinct from resolution — acknowledgment indicates the human
has seen the item even if no action was taken).
target: The entity the item is about (#796): ``kind`` (``"opening"``,
``"space"``, ``"wall"``, ``"fixture"``, ...), ``id``, and for an
item a review edit can apply to, the model ``field`` it corrects.
``original`` is filled in the first time a review edit changes the
field, so revert restores it. Empty for items flagged before #796.
Raises:
ValueError: If ``needs_review`` is False but ``confidence >= 1.0``.
A reviewed item cannot carry a fully-confirmed confidence score.
"""
id: str
kind: Literal[
"fixture_assignment",
"fixture_schedule",
"diffuser_assignment",
"sensor_assignment",
"window_room_link",
"space_no_geometry",
"elevation_conflict",
"window_reconciliation",
"gd_complex_row",
"lighting_extraction",
"hvac_extraction",
"room_label_extraction",
"window_extraction",
"elevation_extraction",
"facade_takeoff",
"opening_attachment",
"adjacency_ambiguous",
"facade_unclear",
"space_merge",
"unclaimed_wall_loop",
"ceiling",
"lining_u",
"matchline_identity",
"roof_plane",
"interstory",
"below_grade",
"zone_airflow",
"air_loop",
"mech_schedule",
# #1236: a stated schedule value the reader refuses to map
# (ambiguous family/unit), routed to review instead of fabricated.
"mech_schedule_value",
# A correction a reviewer drew in the viewer (#1002): the item exists
# to carry the decided state and the correction history entry.
"viewer_correction",
# revision-to-revision takeoff changes (#1048): items a takeoff-diff
# report feeds into the queue, worst-first via review_report
"revision_room_removed",
"revision_room_added",
"revision_opening_count",
"revision_symbol_count",
]
description: str
confidence: float
provenance: Provenance | None = None
status: str = "open" # "open" | "confirmed" | "rejected"
needs_human: float = 1.0 # P(needs human) — set by triage
urgency: int = 1 # 0-3; set by triage
auto_resolved: bool = False # True if auto-resolved per guardrails
resolution: str = "" # "accept" | "drop" | "reassign" — set by triage
needs_review: bool = True # True = awaiting human review; False = reviewed
acknowledged: bool = False # True = human explicitly acknowledged this item
target: Dict[str, Any] = field(default_factory=dict) # #796: entity the item is about
def __post_init__(self):
if not self.needs_review and self.confidence >= 1.0:
raise ValueError(
f"ReviewItem '{self.id}' has confidence={self.confidence} but is marked "
f"needs_review=False. A reviewed item cannot carry confidence=1.0 "
f"(fully confirmed). Use confidence < 1.0 for known limitations."
)
# ---------------------------------------------------------------------------
# BuildingModel
# ---------------------------------------------------------------------------
@dataclass
class SpaceAdjacency:
"""Two spaces sharing a border with no wall on it (#582).
``from_m``/``to_m`` run along the midline of the shared border in the
canonical frame. A virtual border carries no wall area and no U-value.
"""
space_a: str
space_b: str
level_id: str
from_m: List[float] = field(default_factory=list)
to_m: List[float] = field(default_factory=list)
length_m: float = 0.0
boundary: str = "virtual"
virtual_element_id: str = "" # IfcVirtualElement GlobalId when the file models it
provenance: Provenance | None = None
@dataclass
class RoofPlane:
"""One planar roof facet (roadmap item 2, #613).
``vertices_m`` are [x, y, z] corners in the canonical frame: plan x east,
plan y down the sheet (south), z metres up from the host level's floor.
``tilt_deg`` is from horizontal (0 = flat). ``azimuth_deg`` is the
outward (upward-facing) normal's compass bearing, degrees clockwise from
north, the same convention as skylights; None for a flat facet, where it
has no meaning. ``area_m2`` is the true sloped area, not the plan area.
``BuildingModel.roof_planes`` empty means the flat roof at wall height that
every export assumed before this existed.
"""
id: str
level_id: str = ""
vertices_m: List[List[float]] = field(default_factory=list)
tilt_deg: Optional[float] = None
azimuth_deg: Optional[float] = None
area_m2: Optional[float] = None
host_global_id: str = "" # IfcRoof / IfcSlab it came from, if any
provenance: Provenance | None = None
@dataclass
class BuildingModel:
"""Canonical building model: cross-discipline linking layer.
The BuildingModel is the single source of truth for all extracted,
linked, and reconciled building data. It is the ONE model that
everything registers into. Disciplines (architectural floor plan,
lighting, mechanical, elevations) are parsed into sheet-local models,
registered into arch-plan coordinates, then linked via the
registration layer. The canonical model is what is validated,
exported, and reviewed.
The architectural floor plan is the reference frame. Rooms
(name + number) are the primary key: ``Space.id = "{level}-{number}"``.
Zones are many-to-many with spaces (an open office can span two zones).
Provenance is tracked on every derived fact. Facts from a newer
revision of the same sheet supersede older facts — they are kept in
``history``, never silently overwritten.
Coordinate frame (canonical): metres, y growing downward (drawing frame).
BEM export flips y to north-up.
Attributes:
name: Display name of the building or project.
model_version: Schema version string for this model.
auto_triage: Whether to run automatic triage on the review queue.
None means triage has not been run yet.
levels: All building levels (floors) in the model.
spaces: All spaces (rooms) keyed by ``Space.id``.
zones: All thermal zones keyed by zone ID.
envelope: All envelope wall segments (walls, windows, doors).
constructions: Exterior wall assemblies keyed by ``Construction.id``;
``EnvelopeWall.construction_id`` points here.
roof_construction_id: ``Construction.id`` of the roof assembly, or
"" when unknown (exports then use the generic roof).
slab_construction_id: ``Construction.id`` of the ground slab, or ""
when unknown (exports then use the generic slab on grade).
shading: Exterior shading projections hosted on envelope walls;
kept out of ``envelope`` so they never enter the area budget.
roof_planes: Planar roof facets with tilt and azimuth (#613); empty
means the flat roof at wall height.
site_latitude_deg: Site latitude (deg, north positive) or None
when unknown; never defaulted (#615).
bim_elements: All BIM elements from IFC import.
schedules: Lighting and other schedules as plain dicts, keyed by
schedule tag. Revived from plain dict on model load.
revision_log: Ordered log of all revisions applied to this model,
including supersession events.
review_queue: List of low-confidence items awaiting human review.
symbol_linkages: Explicit symbol-to-schedule linkage graph. Each entry
links a symbol instance (detection) to its schedule row, or marks
it as unlinked. Takeoffs derive from this graph rather than
parallel symbol and schedule lists.
_rev_seq: Internal revision sequence counter.
Args:
name: Display name of the building or project.
model_version: Schema version string for this model.
auto_triage: Whether to run automatic triage on the review queue.
levels: All building levels (floors) in the model.
spaces: All spaces (rooms) keyed by ``Space.id``.
zones: All thermal zones keyed by zone ID.
envelope: All envelope wall segments (walls, windows, doors).
bim_elements: All BIM elements from IFC import.
schedules: Lighting and other schedules as plain dicts, keyed by
schedule tag.
revision_log: Ordered log of all revisions applied to this model.
review_queue: List of low-confidence items awaiting human review.
"""
name: str = ""
model_version: str = MODEL_VERSION
auto_triage: Optional[bool] = None
levels: List[Level] = field(default_factory=list)
spaces: Dict[str, Space] = field(default_factory=dict)
zones: Dict[str, Zone] = field(default_factory=dict)
# scheduled central air handlers (#746); empty -> no AirLoop written
air_loops: List[AirLoop] = field(default_factory=list)
# every scheduled equipment piece with its zone-serving relationships
# (#1237); empty -> no scheduled equipment read
equipment: List[Equipment] = field(default_factory=list)
envelope: List[EnvelopeWall] = field(default_factory=list)
constructions: Dict[str, Construction] = field(default_factory=dict)
# Construction.id of the roof assembly, when known (IFC import reads it
# from the roof's ThermalTransmittance); "" -> generic roof on export
roof_construction_id: str = ""
# Construction.id of the ground slab (IFC import reads a BASESLAB's stated
# ThermalTransmittance); "" -> generic slab on grade on export
slab_construction_id: str = ""
# Why the ground slab counts as heated (90.1 "heated slab": heating
# elements, hydronic tubing or hot air in, on or under the slab), e.g. a
# radiant floor row on a mechanical schedule (#747); "" -> no evidence,
# and an unset slab gets the unheated-slab F-factor
slab_heated_by: str = ""
# Space ids the heated-slab rows say they serve (#747), when every row
# names its rooms and each resolves to a ground-level space; empty with
# ``slab_heated_by`` set means the whole slab is treated as heated
slab_heated_spaces: List[str] = field(default_factory=list)
# ASHRAE climate zone (e.g. "4A") and 90.1 building category, as given by
# the user (--climate-zone / --building-category, #747/#763); "" means not
# given, and nothing downstream assumes one
climate_zone: str = ""
building_category: str = ""
shading: List[ShadingSurface] = field(default_factory=list)
space_adjacencies: List[SpaceAdjacency] = field(default_factory=list)
# Semi-exterior envelope between spaces (#747): conditioned against
# semiheated or unconditioned, per ASHRAE 90.1-2019 Section 3.2 and
# Figure 5.5.2, from Space.conditioning. One dict per space pair
# (semi_exterior.semi_exterior_boundaries); "kind" is "semi_exterior" or
# "review" when an unsettled side decides it. Wall records carry
# "plane": "wall" with "length_m"/"segments"; floor/ceiling records
# between adjacent levels (#900) carry "plane": "floor" with "area_m2".
# Only wall records take a construction; exports don't read the field.
semi_exterior: List[dict] = field(default_factory=list)
# sloped roof facets (roadmap item 2, #613); empty -> flat roof at wall height
roof_planes: List[RoofPlane] = field(default_factory=list)
# roof planes as they were before simplification (#617); empty when the
# roof was never simplified
source_roof_planes: List[RoofPlane] = field(default_factory=list)
# site latitude in decimal degrees, north positive (IfcSite RefLatitude, #615)
site_latitude_deg: Optional[float] = None
# ground surface triangles [[x, y, z] x 3], canonical frame, from the IFC
# site terrain (#641); empty when the source has none (never a default grade)
terrain: List[list] = field(default_factory=list)
# overhangs, fins, balconies (roadmap item 5); never part of envelope
# exterior wall assemblies keyed by Construction.id (roadmap item 6)
bim_elements: List[BimElement] = field(default_factory=list)
# raw BIM element inventory (IFC frontend, Tier 0+)
schedules: Dict[str, dict] = field(default_factory=dict)
# schedules: tag -> ScheduleEntry as plain dict (revived on load)
revision_log: List[RevisionEvent] = field(default_factory=list)