Repository navigation
Expand file tree
/
Copy pathconstruction_library.py
More file actions
1174 lines (1062 loc) · 46.8 KB
/
Copy pathconstruction_library.py
File metadata and controls
1174 lines (1062 loc) · 46.8 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
"""Cited construction library for envelope U-values (#747).
Drawings rarely state U-values, so a wall-type tag such as ``W-1 8" CMU`` or a
roof note such as ``rigid insulation above deck`` is resolved to the ASHRAE
90.1-2019 Table 5.5 maximum assembly value for that construction class and
climate zone (``construction_library_data.py``, generated from the same
openstudio-standards tag as the space-use defaults, #685).
Rules, same as the DOE prototype defaults:
* A stated value (drawing, schedule, IFC ThermalTransmittance) is never
overwritten; only constructions whose ``u_value_w_m2k`` is unset are filled.
* Nothing is guessed. A construction resolves only when its tag or
description names exactly one construction class; no match, two classes, or
no climate zone leaves it unset and reported.
* Every filled value carries Provenance method ``construction_default`` whose
note names the source, edition, table, climate zone, row and the words that
matched. The value is the code maximum, not the drawn assembly, so the
confidence stays below the review threshold's comfortable range.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
from building_model import Provenance
from construction_library_data import (
CONSTRUCTION_LIBRARY,
EDITION,
SOURCE,
SOURCE_VERSION,
)
from construction_library_prm_data import PRM_LIBRARY
from construction_library_prm_data import SOURCE as PRM_SOURCE
from construction_library_prm_data import SOURCE_VERSION as PRM_SOURCE_VERSION
METHOD = "construction_default"
CONFIDENCE = 0.6 # a code-maximum baseline, not the assembly on the drawings
CATEGORIES = ("Nonresidential", "Residential", "Semiheated")
# Order matters: framing governs over cladding ("brick veneer on steel studs"
# is a steel-framed wall), so framing classes are tested before Mass. Two
# framing classes in one description is ambiguous and resolves to nothing.
_WALL_FRAMING: List[Tuple[str, re.Pattern]] = [
(
"Metal Building",
re.compile(r"metal\s+building|pre-?engineered|insulated\s+metal\s+panel|\bimp\b"),
),
(
"SteelFramed",
re.compile(r"(steel|metal|mtl\.?|light[- ]gau?ge|cold[- ]formed)\s+(stud|framing|framed)"),
),
("WoodFramed", re.compile(r"wood\s+(stud|framing|framed)|\b2\s*x\s*[468]\s+stud")),
]
_WALL_MASS = re.compile(
r"\bcmu\b|concrete|masonry|\bbrick\b|\bblock\b|tilt[- ]?up|precast|\bmass\s+wall"
)
_ROOF: List[Tuple[str, re.Pattern]] = [
(
"IEAD",
re.compile(
r"\biead\b|(insulation|insul\.?)\s+(entirely\s+)?above\s+(the\s+)?deck"
r"|rigid\s+(roof\s+)?insulation\s+(on|over)\s+(metal|steel|concrete)\s+deck"
),
),
("Metal Building", re.compile(r"metal\s+building|standing\s+seam")),
("Attic and Other", re.compile(r"\battic\b|wood\s+(joist|truss)")),
]
def climate_zone_number(cz: str) -> str:
"""'5A' -> '5', '7' -> '7'. Table 5.5 is split by zone number only."""
m = re.fullmatch(r"\s*(?:cz\s*)?([0-8])\s*([abc])?\s*", (cz or "").lower())
if not m:
raise ValueError(f"not an ASHRAE climate zone: {cz!r} (expected 0-8 with A/B/C)")
return m.group(1)
def classify(text: str, surface: str) -> Tuple[Optional[str], str]:
"""Construction class named by ``text`` for ``surface``, plus the reason.
Returns ``(None, reason)`` when nothing or more than one class matches.
"""
t = (text or "").lower()
if surface == "ExteriorWall":
hits = [(c, m.group(0)) for c, rx in _WALL_FRAMING if (m := rx.search(t))]
if len(hits) > 1:
return None, "ambiguous: " + ", ".join(f"{c} ({w!r})" for c, w in hits)
if hits:
return hits[0][0], f"matched {hits[0][1]!r}"
m = _WALL_MASS.search(t)
if m:
return "Mass", f"matched {m.group(0)!r}"
return None, "no wall construction class named"
if surface == "ExteriorRoof":
hits = [(c, m.group(0)) for c, rx in _ROOF if (m := rx.search(t))]
if len(hits) > 1:
return None, "ambiguous: " + ", ".join(f"{c} ({w!r})" for c, w in hits)
if hits:
return hits[0][0], f"matched {hits[0][1]!r}"
return None, "no roof construction class named"
return None, f"surface {surface} not resolved by this library yet"
@dataclass
class LibraryRow:
category: str
climate_zone: str
surface: str
construction_type: str
source_construction: str
u_ip: Optional[float]
u_si: Optional[float]
f_ip: Optional[float] = None # slab F-factor, Btu/h-ft-F (GroundContactFloor rows)
shgc: Optional[float] = None # glazing rows only
min_vt_shgc: Optional[float] = None # vertical glazing rows only
@property
def table(self) -> str:
return f"Table 5.5-{self.climate_zone}"
def lookup(
surface: str, construction_type: str, climate_zone: str, category: str = "Nonresidential"
) -> Optional[LibraryRow]:
cz = climate_zone_number(climate_zone)
row = CONSTRUCTION_LIBRARY.get((category, cz, surface, construction_type))
if row is None:
return None
return LibraryRow(
category,
cz,
surface,
construction_type,
row["source_construction"],
row["u_ip"],
row["u_si"],
row.get("f_ip"),
row.get("shgc"),
row.get("min_vt_shgc"),
)
@dataclass
class LibrarySummary:
climate_zone: str = ""
category: str = ""
resolved: Dict[str, dict] = field(default_factory=dict) # construction id -> row info
kept: List[str] = field(default_factory=list) # ids with a stated U, untouched
unmatched: Dict[str, str] = field(default_factory=dict) # id -> reason
not_run: str = "" # why the library did not run at all
# Appendix G baseline defaults (#768): construction id -> row info, for
# walls/roof the drawings name no assembly for at all
defaulted: Dict[str, dict] = field(default_factory=dict)
# Appendix G baseline envelope (#781): Table G3.4 (PRM 2019) values for
# the baseline model; recorded only, the exported proposed model is not
# changed by it
baseline: Dict[str, object] = field(default_factory=dict)
def to_dict(self) -> dict:
return {
"source": f"{SOURCE} ({SOURCE_VERSION})",
"climate_zone": self.climate_zone,
"building_category": self.category,
"not_run": self.not_run,
"resolved": self.resolved,
"kept_stated_values": sorted(self.kept),
"unmatched": self.unmatched,
"defaulted": self.defaulted,
"baseline": self.baseline,
}
def _prov(row: LibraryRow, cid: str, why: str, given_cz: str) -> Provenance:
return Provenance(
sheet_id="",
revision=0,
method=METHOD,
confidence=CONFIDENCE,
note=(
f"{SOURCE}, {EDITION} {row.table} ({SOURCE_VERSION}); {row.category} "
f"{row.surface} {row.construction_type}, climate zone {given_cz}; "
f"U {row.u_ip} Btu/h-ft2-F; {cid}: {why}; code maximum, not the drawn assembly"
),
)
def apply_construction_library(
model, climate_zone: str = "", category: str = "Nonresidential"
) -> LibrarySummary:
"""Fill unset construction U-values from Table 5.5; never overwrite.
With no climate zone the library does not run (a zone is never assumed)
and every unset construction is reported. Space wall U-values are rolled
up again afterwards so the exports see the filled values.
"""
from constructions import apply_wall_u_rollup
if category not in CATEGORIES:
raise ValueError(f"building category must be one of {CATEGORIES}, got {category!r}")
s = LibrarySummary(climate_zone=climate_zone or "", category=category)
if climate_zone:
climate_zone_number(climate_zone) # validate early
model.climate_zone = climate_zone
model.building_category = category
else:
s.not_run = "no climate zone given"
roof_id = getattr(model, "roof_construction_id", "") or ""
slab_id = getattr(model, "slab_construction_id", "") or ""
for cid, c in sorted((getattr(model, "constructions", None) or {}).items()):
if c.u_value_w_m2k is not None and c.u_value_w_m2k > 0:
s.kept.append(cid)
continue
if cid == slab_id:
s.unmatched[cid] = "slab: Table 5.5 gives an F-factor, not resolved yet"
continue
if not climate_zone:
s.unmatched[cid] = "no climate zone given"
continue
surface = "ExteriorRoof" if cid == roof_id else "ExteriorWall"
ctype, why = classify(f"{cid} {c.name}", surface)
if ctype is None:
s.unmatched[cid] = why
continue
row = lookup(surface, ctype, climate_zone, category)
if row is None or row.u_si is None:
s.unmatched[cid] = f"no Table 5.5 U-value for {category} {surface} {ctype}"
continue
c.u_value_w_m2k = row.u_si
c.provenance = _prov(row, cid, why, climate_zone)
s.resolved[cid] = {
"surface": surface,
"construction_type": ctype,
"table": row.table,
"u_ip": row.u_ip,
"u_si": row.u_si,
"why": why,
}
if climate_zone:
# before the unlabeled-envelope defaults: a vestibule's exterior
# walls take the Semiheated column, not the building category's
# (#747, 5.5.2 vestibule sentence)
_default_vestibule_envelope(model, s, climate_zone)
_apply_baseline_defaults(model, s, climate_zone, category)
_default_semi_exterior(model, s, climate_zone)
_default_semi_exterior_floor(model, s, climate_zone)
s.baseline = baseline_envelope(model, climate_zone, category)
if s.resolved or s.defaulted:
apply_wall_u_rollup(model)
return s
# Unlabeled envelope (#781, Alex's order: drawings first, Table 5.5 for
# anything the drawings leave unlabeled, Table G3.4 for the Appendix G
# baseline). Walls with no construction and an unset roof or slab get the
# Table 5.5 code maximum. Table 5.5 needs a construction class and the
# drawings name none, so the class is the one Appendix G uses for its
# baseline (G3.1-5(b): steel-framed walls, insulation entirely above deck).
DEFAULT_WALL_ID = "t55-wall"
DEFAULT_ROOF_ID = "t55-roof"
DEFAULT_SLAB_ID = "t55-slab"
_BASELINE = {
DEFAULT_WALL_ID: (
"ExteriorWall",
"SteelFramed",
"Exterior wall, Table 5.5 code maximum (unlabeled)",
),
DEFAULT_ROOF_ID: ("ExteriorRoof", "IEAD", "Roof, Table 5.5 code maximum (unlabeled)"),
}
_UNLABELED_WHY = "no assembly stated on the drawings; Table 5.5 code maximum, class {ctype}"
def _apply_baseline_defaults(model, s: "LibrarySummary", climate_zone: str, category: str):
"""Default walls with no construction and an unset roof to Table 5.5 (#768, #781).
A segment that already points at a construction (resolved or not) and a
stated roof are left alone. An unset slab gets the unheated-slab F-factor
as an effective U (``_default_slab``).
"""
from building_model import Construction
walls = [w for w in model.envelope if not (getattr(w, "construction_id", "") or "")]
targets = []
if walls:
targets.append(DEFAULT_WALL_ID)
if not (getattr(model, "roof_construction_id", "") or ""):
targets.append(DEFAULT_ROOF_ID)
for cid in targets:
surface, ctype, name = _BASELINE[cid]
row = lookup(surface, ctype, climate_zone, category)
if row is None or row.u_si is None:
s.unmatched[cid] = f"no Table 5.5 U-value for {category} {surface} {ctype}"
continue
why = _UNLABELED_WHY.format(ctype=ctype)
model.constructions[cid] = Construction(
id=cid, name=name, u_value_w_m2k=row.u_si, provenance=_prov(row, cid, why, climate_zone)
)
info = {
"surface": surface,
"construction_type": ctype,
"table": row.table,
"u_ip": row.u_ip,
"u_si": row.u_si,
"why": why,
}
if cid == DEFAULT_WALL_ID:
for w in walls:
w.construction_id = cid
info["segments"] = sorted(w.id for w in walls)
else:
model.roof_construction_id = cid
s.defaulted[cid] = info
if not (getattr(model, "slab_construction_id", "") or ""):
_default_slab(model, s, climate_zone, category)
_default_openings(model, s, climate_zone, category)
# Semi-exterior envelope (#747 slice 6). ASHRAE 90.1-2019 5.5.2: "If a
# building contains any semiheated space or unconditioned space then the
# semiexterior building envelope shall comply with the requirements for
# semiheated space in Tables 5.5-0 through 5.5-8 for the appropriate
# climate" (Alex, 747#issuecomment-6101561224). So a settled semi-exterior
# boundary (``model.semi_exterior`` kind "semi_exterior") takes the
# Semiheated column's wall row whatever the building category, in the same
# class the unlabeled exterior walls use (steel framed, G3.1-5(b)). A
# boundary still "review" keeps the partition and its review item.
DEFAULT_SEMIEXT_WALL_ID = "t55-semiext-wall"
SEMIEXT_CATEGORY = "Semiheated"
SEMIEXT_CLASS = "SteelFramed" # the class Table G3.4 baselines use for floors too
_SEMIEXT_WHY = (
"semi-exterior wall (ASHRAE 90.1-2019 5.5.2: semiexterior envelope meets the "
"semiheated requirements of Table 5.5); no assembly stated, class {ctype}"
)
def _default_semi_exterior(model, s: "LibrarySummary", climate_zone: str) -> None:
"""Give settled semi-exterior boundaries the Table 5.5 Semiheated wall (#747).
A record that already names a construction, a stated construction under
the same id, and boundaries still to review are left alone.
"""
from building_model import Construction
recs = [
r
for r in (getattr(model, "semi_exterior", None) or [])
if (
r.get("kind") == "semi_exterior"
and not r.get("construction_id")
and r.get("plane", "wall") == "wall"
)
]
if not recs:
return
cid = DEFAULT_SEMIEXT_WALL_ID
cons = model.constructions
have = cons.get(cid)
if have is None or not (have.u_value_w_m2k and have.u_value_w_m2k > 0):
row = lookup("ExteriorWall", SEMIEXT_CLASS, climate_zone, SEMIEXT_CATEGORY)
if row is None or row.u_si is None:
s.unmatched[cid] = (
f"no Table 5.5 U-value for {SEMIEXT_CATEGORY} ExteriorWall {SEMIEXT_CLASS}"
)
return
why = _SEMIEXT_WHY.format(ctype=SEMIEXT_CLASS)
cons[cid] = Construction(
id=cid,
name="Semi-exterior wall, Table 5.5 Semiheated code maximum",
u_value_w_m2k=row.u_si,
provenance=_prov(row, cid, why, climate_zone),
)
s.defaulted[cid] = {
"surface": "ExteriorWall",
"construction_type": SEMIEXT_CLASS,
"category": SEMIEXT_CATEGORY,
"table": row.table,
"u_ip": row.u_ip,
"u_si": row.u_si,
"why": why,
}
for r in recs:
r["construction_id"] = cid
if cid in s.defaulted:
s.defaulted[cid]["space_pairs"] = sorted(list(r["spaces"]) for r in recs)
# Floor/ceiling boundaries between a conditioned space and a semiheated or
# unconditioned one (#900) are semi-exterior envelope too. Same rule as the
# walls: the Semiheated column's ExteriorFloor row (Table 5.5 "Floors"), in
# the class the Table G3.4 baseline uses for floors (steel framed).
DEFAULT_SEMIEXT_FLOOR_ID = "t55-semiext-floor"
_SEMIEXT_FLOOR_WHY = (
"semi-exterior floor/ceiling (ASHRAE 90.1-2019 5.5.2: semiexterior envelope "
"meets the semiheated requirements of Table 5.5); no assembly stated, class {ctype}"
)
def _default_semi_exterior_floor(model, s: "LibrarySummary", climate_zone: str) -> None:
"""Give settled semi-exterior floor/ceiling records the Table 5.5 Semiheated floor (#900).
Same rules as the walls: a record that already names a construction, a
stated construction under the same id, and boundaries still to review
are left alone.
"""
from building_model import Construction
recs = [
r
for r in (getattr(model, "semi_exterior", None) or [])
if (
r.get("kind") == "semi_exterior"
and not r.get("construction_id")
and r.get("plane") == "floor"
)
]
if not recs:
return
cid = DEFAULT_SEMIEXT_FLOOR_ID
cons = model.constructions
have = cons.get(cid)
if have is None or not (have.u_value_w_m2k and have.u_value_w_m2k > 0):
row = lookup("ExteriorFloor", SEMIEXT_CLASS, climate_zone, SEMIEXT_CATEGORY)
if row is None or row.u_si is None:
s.unmatched[cid] = (
f"no Table 5.5 U-value for {SEMIEXT_CATEGORY} ExteriorFloor {SEMIEXT_CLASS}"
)
return
why = _SEMIEXT_FLOOR_WHY.format(ctype=SEMIEXT_CLASS)
cons[cid] = Construction(
id=cid,
name="Semi-exterior floor/ceiling, Table 5.5 Semiheated code maximum",
u_value_w_m2k=row.u_si,
provenance=_prov(row, cid, why, climate_zone),
)
s.defaulted[cid] = {
"surface": "ExteriorFloor",
"construction_type": SEMIEXT_CLASS,
"category": SEMIEXT_CATEGORY,
"table": row.table,
"u_ip": row.u_ip,
"u_si": row.u_si,
"why": why,
}
for r in recs:
r["construction_id"] = cid
if cid in s.defaulted:
s.defaulted[cid]["space_pairs"] = sorted(list(r["spaces"]) for r in recs)
DEFAULT_WINDOW_ID = "t55-window"
DEFAULT_DOOR_ID = "t55-door"
DEFAULT_SKYLIGHT_ID = "t55-skylight"
# category -> (construction id, Table 5.5 surface, class, name, why the class).
# Drawings rarely say whether a window opens or whether a door is glazed, so
# each gets one class and says which: fixed windows (the more common class in
# nonresidential glazing), opaque swinging doors, and curbed glass skylights
# (all three skylight classes carry the same values in 90.1-2019).
# Table 5.5 sets no VT for skylights. The 90.1 PRM 2019 data in
# openstudio-standards v0.8.6 (ashrae_90_1_prm_2019.construction_properties.json)
# gives every glazing row VT = round(1.10 x SHGC, 2): all 132 ExteriorWindow,
# 132 GlassDoor and 66 Skylight rows. Skylights use that ratio rather than
# openstudio-standards' name-parsing fallback of VT 0.81, which is a placeholder
# (VT/SHGC 2.0 against a 0.40 SHGC) and not tied to any table (#784).
SKYLIGHT_VT_SHGC = 1.10
SKYLIGHT_VT_SHGC_SOURCE = (
"VT/SHGC 1.10 as in openstudio-standards v0.8.6 "
"ashrae_90_1_prm_2019.construction_properties.json skylight rows"
)
_OPENING_DEFAULTS = {
"window": (
DEFAULT_WINDOW_ID,
"ExteriorWindow",
"Fixed",
"Window, Table 5.5 code maximum (unlabeled)",
"fixed vs operable not stated; fixed class used",
),
"door": (
DEFAULT_DOOR_ID,
"ExteriorDoor",
"Swinging",
"Exterior door, Table 5.5 code maximum (unlabeled)",
"door type not stated; opaque swinging class used",
),
"skylight": (
DEFAULT_SKYLIGHT_ID,
"Skylight",
"Glass with Curb",
"Skylight, Table 5.5 code maximum (unlabeled)",
"skylight type not stated; all Table 5.5 skylight classes share these values",
),
}
def _default_openings(model, s: "LibrarySummary", climate_zone: str, category: str):
"""Give exterior windows, doors and skylights with no assembly Table 5.5 values (#747).
Interior openings (an ``adjacent_space_id``) and openings that already
point at a construction are left alone. Windows and skylights carry the
row's SHGC as well as its U.
"""
from building_model import Construction
by_cat: Dict[str, list] = {}
for sp in (model.spaces or {}).values():
for op in getattr(sp, "openings", None) or []:
if getattr(op, "adjacent_space_id", None) or (getattr(op, "construction_id", "") or ""):
continue
if op.category in _OPENING_DEFAULTS:
by_cat.setdefault(op.category, []).append(op)
for cat, ops in sorted(by_cat.items()):
cid, surface, ctype, name, why_class = _OPENING_DEFAULTS[cat]
row = lookup(surface, ctype, climate_zone, category)
if row is None or row.u_si is None:
s.unmatched[cid] = f"no Table 5.5 U-value for {category} {surface} {ctype}"
continue
why = f"no assembly stated on the drawings; Table 5.5 code maximum, {why_class}"
# Table 5.5 caps SHGC and sets a minimum VT/SHGC for vertical glazing;
# VT is taken at that minimum. Skylight rows carry no VT figure, so
# skylights take the same 1.10 ratio the 90.1 PRM 2019 data applies to
# every glazing row, skylights included (#784).
vt = None
if row.shgc is not None and row.min_vt_shgc is not None:
vt = round(row.shgc * row.min_vt_shgc, 4)
why += f"; VT {vt} = minimum VT/SHGC {row.min_vt_shgc} x SHGC {row.shgc}"
elif row.shgc is not None and surface == "Skylight":
vt = round(row.shgc * SKYLIGHT_VT_SHGC, 4)
why += f"; VT {vt} = {SKYLIGHT_VT_SHGC} x SHGC {row.shgc} ({SKYLIGHT_VT_SHGC_SOURCE})"
model.constructions[cid] = Construction(
id=cid,
name=name,
u_value_w_m2k=row.u_si,
provenance=_prov(row, cid, why, climate_zone),
shgc=row.shgc,
vt=vt,
)
for op in ops:
op.construction_id = cid
s.defaulted[cid] = {
"surface": surface,
"construction_type": ctype,
"table": row.table,
"u_ip": row.u_ip,
"u_si": row.u_si,
"shgc": row.shgc,
"vt": vt,
"why": why,
"openings": sorted(op.id for op in ops),
}
# 1 Btu/h-ft-F = 1.730735 W/m-K (F-factor, heat loss per length of exposed slab edge)
F_IP_TO_SI = 1.730735
# Slab parts smaller than this are drawing noise (slivers between rooms), not a
# wing on grade; they are listed in the report, not counted.
MIN_SLAB_PART_M2 = 1.0
# A hole in the ground footprint is an open-air courtyard when exterior walls
# run along at least this share of its edge (#747). Otherwise it is an
# unmodelled room or shaft: still slab, and its edge is not exposed.
COURTYARD_WALL_SHARE = 0.5
# exterior wall centreline within this distance of the hole edge (m), and
# within this angle of it (degrees), counts as running along it
_COURTYARD_TOL_M = 0.6
_COURTYARD_ANGLE_DEG = 10.0
# a courtyard is open to the sky: spaces on higher levels may cover at most
# this share of it (balconies, a bridge); more means floor above a missing room
COURTYARD_MAX_COVERED_ABOVE = 0.10
def _slab_level_walls(model, level_ids: set) -> list:
"""Exterior wall centrelines ``[(p0, p1)]`` on the slab's level.
IFC and drawing-set envelope ids are level-prefixed (``<level>-EW1``,
``<level>-E1``); when any wall carries a known level prefix, only walls on
``level_ids`` count, so an upper-floor wall over a ground-floor hole edge
is not evidence. Unprefixed envelopes (a single-level model) use every
wall.
"""
known = {lv.id for lv in (getattr(model, "levels", None) or [])}
rows = [
w
for w in (getattr(model, "envelope", None) or [])
if len(w.from_m or []) >= 2 and len(w.to_m or []) >= 2 and w.from_m[:2] != w.to_m[:2]
]
def level_of(w):
for lid in known:
if str(w.id).startswith(f"{lid}-"):
return lid
return None
if any(level_of(w) for w in rows):
rows = [w for w in rows if level_of(w) in level_ids]
return [(tuple(w.from_m[:2]), tuple(w.to_m[:2])) for w in rows]
def _wall_cover(ring, walls) -> float:
"""Length of ``ring`` (a closed shapely ring) that exterior walls run along.
A wall runs along an edge when its centreline is within
``_COURTYARD_TOL_M`` of the edge and within ``_COURTYARD_ANGLE_DEG`` of
parallel; only the stretch of the edge the wall projects onto counts, and
overlapping walls are counted once.
"""
import math
from shapely.geometry import LineString, Point
total = 0.0
coords = list(ring.coords)
for a, b in zip(coords, coords[1:]):
edge = LineString([a, b])
if edge.length <= 0:
continue
ea = math.atan2(b[1] - a[1], b[0] - a[0])
spans = []
for p0, p1 in walls:
wa = math.atan2(p1[1] - p0[1], p1[0] - p0[0])
d = abs((wa - ea + math.pi / 2) % math.pi - math.pi / 2)
if math.degrees(d) > _COURTYARD_ANGLE_DEG:
continue
if LineString([p0, p1]).distance(edge) > _COURTYARD_TOL_M:
continue
s0, s1 = sorted((edge.project(Point(p0)), edge.project(Point(p1))))
if s1 > s0:
spans.append((s0, s1))
spans.sort()
cur0 = cur1 = None
for s0, s1 in spans:
if cur1 is None or s0 > cur1:
if cur1 is not None:
total += cur1 - cur0
cur0, cur1 = s0, s1
else:
cur1 = max(cur1, s1)
if cur1 is not None:
total += cur1 - cur0
return total
def _slab_geometry(model, lowest: bool = True):
"""Slab on grade geometry of the ground (or, ``lowest=False``, top) level.
Returns ``(area_m2, exposed_perimeter_m, level_id, detail)`` or None when
the model has no space polygons. The slab is the union of the level's
space polygons, every part of it (#747): a separate wing is slab on grade
too, so its area and its whole edge count; parts under
``MIN_SLAB_PART_M2`` are slivers and are only listed. A hole in the union
is an open-air courtyard when exterior walls on this level run along at
least ``COURTYARD_WALL_SHARE`` of its edge and spaces on higher levels
cover at most ``COURTYARD_MAX_COVERED_ABOVE`` of it (open to the sky):
its edge is exposed and its area is not slab. Any other hole (an
unmodelled room or shaft) stays slab and its edge is not exposed, which is
what the exported footprint (holes dropped) already assumes. ``detail``
lists wings, courtyards and holes for the report; its private ``_edges``
(exposed edge rings) and ``_spaces`` (slab-level spaces by id) are for
``_heated_part`` only and are not JSON, so never copy ``detail`` whole.
"""
from shapely.geometry import Polygon
from shapely.ops import unary_union
spaces = [sp for sp in (model.spaces or {}).values() if len(sp.polygon_m or []) >= 3]
if not spaces:
return None
elev = {lv.id: lv.elevation_z_m for lv in (getattr(model, "levels", None) or [])}
pick = min if lowest else max
low = pick(elev.get(sp.level_id, 0.0) for sp in spaces)
ground = [sp for sp in spaces if abs(elev.get(sp.level_id, 0.0) - low) < 1e-6]
polys = []
for sp in ground:
g = Polygon([tuple(v[:2]) for v in sp.polygon_m])
if not g.is_valid:
g = g.buffer(0)
if not g.is_empty and g.area > 0:
polys.append(g)
if not polys:
return None
merged = unary_union(polys)
parts = list(merged.geoms) if hasattr(merged, "geoms") else [merged]
parts = [g for g in parts if g.geom_type == "Polygon" and g.area > 0]
walls = _slab_level_walls(model, {sp.level_id for sp in ground})
# spaces on higher levels: a courtyard is open to the sky, so a hole with
# floor above it is a missing room, not a courtyard
above = []
for sp in spaces:
if elev.get(sp.level_id, 0.0) > low + 1e-6:
g = Polygon([tuple(v[:2]) for v in sp.polygon_m])
if not g.is_valid:
g = g.buffer(0)
if not g.is_empty and g.area > 0:
above.append(g)
above_union = unary_union(above) if above else None
detail = {"wings": 0, "slivers": [], "courtyards": [], "holes_not_exposed": []}
edges = [] # exposed slab edges, for splitting the perimeter (heated part)
area = perim = 0.0
for g in sorted(parts, key=lambda q: -q.area):
if g.area < MIN_SLAB_PART_M2:
detail["slivers"].append(round(g.area, 4))
continue
detail["wings"] += 1
area += Polygon(g.exterior).area
perim += g.exterior.length
edges.append(g.exterior)
for hole in g.interiors:
h_area = Polygon(hole).area
h_len = hole.length
cover = _wall_cover(hole, walls) if walls else 0.0
covered_above = 0.0
if above_union is not None and h_area > 0:
covered_above = Polygon(hole).intersection(above_union).area / h_area
rec = {
"area_m2": round(h_area, 4),
"perimeter_m": round(h_len, 4),
"wall_cover_m": round(cover, 4),
}
if covered_above > 0:
rec["covered_above_share"] = round(covered_above, 4)
if (
h_len > 0
and cover / h_len >= COURTYARD_WALL_SHARE
and covered_above <= COURTYARD_MAX_COVERED_ABOVE
):
area -= h_area
perim += h_len
edges.append(hole)
detail["courtyards"].append(rec)
else:
detail["holes_not_exposed"].append(rec)
if area <= 0 or perim <= 0:
return None
detail["_edges"] = edges
detail["_spaces"] = {sp.id: sp for sp in ground}
return area, perim, ground[0].level_id, detail
# a heated space's edge counts as heated slab edge within this distance of the
# slab's exposed edge (space polygons share the slab outline up to rounding)
HEATED_EDGE_TOL_M = 0.05
def _heated_part(detail, space_ids):
"""(heated slab area m2, heated exposed perimeter m, ids used) for the
ground-level spaces in ``space_ids`` (#747). Spaces not on the slab level
are ignored; None when none of them is."""
from shapely.geometry import MultiLineString, Polygon
from shapely.ops import unary_union
on = [detail["_spaces"][i] for i in space_ids if i in detail["_spaces"]]
polys = []
for sp in on:
g = Polygon([tuple(v[:2]) for v in sp.polygon_m])
polys.append(g if g.is_valid else g.buffer(0))
if not polys:
return None
heated = unary_union(polys)
rest = []
for i, sp in detail["_spaces"].items():
if i in space_ids:
continue
g = Polygon([tuple(v[:2]) for v in sp.polygon_m])
rest.append(g if g.is_valid else g.buffer(0))
edge = MultiLineString([list(r.coords) for r in detail["_edges"]])
perim = edge.length
tol = HEATED_EDGE_TOL_M
# the tolerance band overshoots by ``tol`` along the edge wherever a heated
# room meets an unheated one; measuring both sides the same way and
# splitting the difference cancels that overshoot
h = edge.intersection(heated.buffer(tol)).length
u = edge.intersection(unary_union(rest).buffer(tol)).length if rest else 0.0
p_h = max(0.0, min(perim, (h - u + perim) / 2.0)) if rest else min(h, perim)
return heated.area, p_h, sorted(sp.id for sp in on)
# 90.1-2019 Section 3.2, heated slab: "slab-on-grade floor construction in
# which the heating elements, hydronic tubing, or hot-air distribution system
# is in contact with, or placed within or under, the slab." On a drawing set
# that shows up as a radiant floor / in-slab heating row on a mechanical
# schedule. Snow-melt and sidewalk heating are outdoors, and radiant ceiling
# panels heat the room, not the slab, so neither counts.
HEATED_SLAB_RX = re.compile(
r"\bRADIANT\s+(FLOOR|SLAB)|\bIN[- ]?(FLOOR|SLAB)\s+(RADIANT|HEAT)"
r"|\bHEATED\s+(SLAB|FLOOR)|\b(UNDER)?FLOOR\s+HEATING\b|\bSLAB\s+HEATING\b"
)
NOT_HEATED_SLAB_RX = re.compile(r"\bSNOW\s*-?\s*MELT|\bSIDEWALK|\bDRIVEWAY|\bCEILING")
# a radiant slab that only cools is not a heated slab
_COOLING_RX = re.compile(r"\bCOOLING\b")
_HEAT_RX = re.compile(r"\bHEAT")
def heated_slab_evidence(equipment) -> str:
"""Scheduled equipment that heats the slab -> one line naming it, or "".
``equipment`` is the mechanical-schedule record list from a drawing-set
run (``tag``, ``description``, ``schedule``, ``sheet``, ``values``). A
row counts when its description, schedule title or any cell names
radiant floor / in-slab heating and nothing on it says snow melt,
sidewalk, driveway or ceiling. A row that says cooling and never heat
is a radiant cooling slab, not a heated one.
"""
hits = []
for e in equipment or []:
if not _is_heated_slab_row(e):
continue
where = f" on {e['sheet']}" if e.get("sheet") else ""
hits.append(f"{e.get('tag', '?')}{where}")
if not hits:
return ""
return "radiant floor / in-slab heating scheduled: " + ", ".join(sorted(set(hits)))
# a schedule column naming the rooms a row serves ("SERVES", "AREA SERVED",
# "ROOMS SERVED", "ROOM"); not "AREA" alone, which is usually a floor area
_SERVES_COL_RX = re.compile(r"SERV|\bROOMS?\b|\bRM\b")
_ROOM_NO_RX = re.compile(r"\b[A-Z]?\d{2,4}[A-Z]?\b")
def _is_heated_slab_row(e) -> bool:
text = " ".join(
[str(e.get("description") or ""), str(e.get("schedule") or "")]
+ [str(v) for v in (e.get("values") or {}).values()]
).upper()
if not HEATED_SLAB_RX.search(text) or NOT_HEATED_SLAB_RX.search(text):
return False
return not (_COOLING_RX.search(text) and not _HEAT_RX.search(text))
def heated_slab_rooms(equipment):
"""Room numbers the heated-slab rows serve (#747), or None.
Read from a serves / room column on each row ``heated_slab_evidence``
counts. None unless every such row names at least one room number, since a
row without one may heat any part of the slab.
"""
rows = [e for e in equipment or [] if _is_heated_slab_row(e)]
if not rows:
return None
rooms = set()
for e in rows:
found = set()
for k, v in (e.get("values") or {}).items():
if _SERVES_COL_RX.search(str(k).upper()):
found |= set(_ROOM_NO_RX.findall(str(v).upper()))
if not found:
return None
rooms |= found
return sorted(rooms)
def _default_slab(model, s: "LibrarySummary", climate_zone: str, category: str):
"""Unset slab -> Table 5.5 slab F-factor as an effective U (#747, #781).
The slab is Unheated unless ``model.slab_heated_by`` says what heats it,
then the Table 5.5 Heated row is used. When ``model.slab_heated_spaces``
names the rooms the heating serves, only their exposed edge gets the
heated F-factor and the rest the unheated one; otherwise the whole slab is
Heated, which can only raise the loss, and the drawing set run sends that
to review.
gbXML carries a U-value, not
an F-factor, so the slab gets the U that loses the same heat:
U = F x exposed perimeter / slab area (F-factor definition, heat loss per
unit length of exposed edge per degree indoor-outdoor). Perimeter and area
are the whole ground slab: every wing, open-air courtyard edges included
(``_slab_geometry``).
"""
from building_model import Construction
cid = DEFAULT_SLAB_ID
heated_by = (getattr(model, "slab_heated_by", "") or "").strip()
ctype = "Heated" if heated_by else "Unheated"
label = ctype.lower()
row = lookup("GroundContactFloor", ctype, climate_zone, category)
if row is None or row.f_ip is None:
s.unmatched[cid] = f"no Table 5.5 F-factor for {category} {label} slab"
return
geo = _slab_geometry(model)
if geo is None:
s.unmatched[cid] = "slab: no ground-floor space polygons for perimeter and area"
return
area, perim, level_id, detail = geo
f_si = row.f_ip * F_IP_TO_SI
u = round(f_si * perim / area, 6)
part = None
served = list(getattr(model, "slab_heated_spaces", None) or [])
unheated = lookup("GroundContactFloor", "Unheated", climate_zone, category)
if heated_by and served and unheated is not None and unheated.f_ip is not None:
part = _heated_part(detail, served)
if part is not None:
# only the served rooms are heated slab: the slab loses F_heated over
# the exposed edge of those rooms and F_unheated over the rest
# (F-factor is heat loss per length of exposed edge), so one U for the
# whole slab = (F_h x P_h + F_u x P_u) / area
a_h, p_h, used = part
p_h = min(p_h, perim)
fu_si = unheated.f_ip * F_IP_TO_SI
u = round((f_si * p_h + fu_si * (perim - p_h)) / area, 6)
f_text = (
f"Table 5.5 heated slab F-factor {row.f_ip} Btu/h-ft-F = {f_si:.4f} W/m-K over "
f"the {p_h:.2f} m of exposed edge of the heated rooms ({', '.join(used)}, "
f"{a_h:.2f} m2), unheated {unheated.f_ip} = {fu_si:.4f} W/m-K over the other "
f"{perim - p_h:.2f} m; effective U = sum(F x edge) / slab area {area:.2f} m2"
)
else:
f_text = (
f"Table 5.5 {label} slab F-factor "
f"{row.f_ip} Btu/h-ft-F = {f_si:.4f} W/m-K; effective U = F x exposed perimeter "
f"{perim:.2f} m / slab area {area:.2f} m2"
)
why = (
"no slab assembly stated on the drawings; "
+ (f"heated slab ({heated_by}); " if heated_by else "")
+ f_text
+ f" (ground slab of level {level_id}: "
f"{detail['wings']} wing(s), {len(detail['courtyards'])} courtyard(s))"
)
prov = Provenance(
sheet_id="",
revision=0,
method=METHOD,
confidence=CONFIDENCE,
note=(
f"{SOURCE}, {EDITION} {row.table} ({SOURCE_VERSION}); {row.category} "
f"GroundContactFloor {ctype}, climate zone {climate_zone}; {cid}: {why}; "
"code maximum, not the drawn assembly"
),
)
model.constructions[cid] = Construction(
id=cid,
name=(
"Heated slab on grade, Table 5.5 code maximum (unlabeled)"
if heated_by
else "Slab on grade, Table 5.5 code maximum (unlabeled)"
),
u_value_w_m2k=u,
provenance=prov,
)
model.slab_construction_id = cid
s.defaulted[cid] = {
"surface": "GroundContactFloor",
"construction_type": ctype,
"table": row.table,
"f_ip": row.f_ip,
"f_si": round(f_si, 6),
"exposed_perimeter_m": round(perim, 4),
"area_m2": round(area, 4),
"u_si": u,
"why": why,
"wings": detail["wings"],
"courtyards": detail["courtyards"],
"holes_not_exposed": detail["holes_not_exposed"],
"slivers_m2": detail["slivers"],
}
if heated_by:
s.defaulted[cid]["heated_by"] = heated_by
if part is not None:
s.defaulted[cid].update(
heated_spaces=part[2],
heated_area_m2=round(part[0], 4),
heated_perimeter_m=round(min(part[1], perim), 4),
f_ip_unheated=unheated.f_ip,
)
# Appendix G baseline envelope (#781): 90.1-2019 Table G3.4 (PRM 2019).
# Name -> (surface, construction type) as the PRM table keys them.
_PRM_SURFACES = (
("wall", "ExteriorWall", "SteelFramed"),
("roof", "ExteriorRoof", "IEAD"),
("slab", "GroundContactFloor", "Unheated"),
("exterior_floor", "ExteriorFloor", "SteelFramed"),
("door_swinging", "ExteriorDoor", "Swinging"),
("door_nonswinging", "ExteriorDoor", "NonSwinging"),
("vertical_glazing", "ExteriorWindow", "Any Vertical Glazing"),
("glass_door", "GlassDoor", "Any Vertical Glazing"),
("skylight", "Skylight", "Any Skylight"),
)
def prm_rows(surface: str, construction_type: str, climate_zone: str, category: str):
"""(rows, zone key) from Table G3.4; zone 3 is split 3A/3B/3C there."""
z = (climate_zone or "").strip().upper().removeprefix("CZ").strip()
num = climate_zone_number(climate_zone)
for zk in (z, num):
rows = PRM_LIBRARY.get((category, zk, surface, construction_type))
if rows:
return rows, zk
return None, None
def _pick_band(rows: list, pct: Optional[float]):
"""(row, note) for a percent of surface; above the top band uses the top
band (G3.1-5(c) caps the baseline window-to-wall ratio at 40%)."""
if len(rows) == 1 and rows[0]["pct_min"] is None:
return rows[0], ""
if pct is None: