File size: 29,456 Bytes
f88cb90
1ed2aaa
f88cb90
 
1072206
f88cb90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1072206
681eb4b
1ed2aaa
f88cb90
 
 
 
 
 
 
1072206
f88cb90
 
 
 
 
 
 
 
681eb4b
 
 
 
 
 
 
 
f88cb90
 
 
 
 
1072206
f88cb90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
681eb4b
f88cb90
 
 
 
681eb4b
f88cb90
681eb4b
 
f88cb90
 
681eb4b
f88cb90
681eb4b
 
 
1072206
681eb4b
f88cb90
681eb4b
 
f88cb90
 
681eb4b
f88cb90
681eb4b
 
 
 
 
 
 
 
 
 
f88cb90
 
681eb4b
f88cb90
681eb4b
 
 
 
f88cb90
681eb4b
 
 
 
f88cb90
681eb4b
 
 
 
 
 
 
 
 
 
 
f88cb90
 
 
 
 
 
681eb4b
f88cb90
 
 
 
681eb4b
1072206
681eb4b
 
 
 
 
 
 
 
1ed2aaa
 
 
681eb4b
1072206
1ed2aaa
1072206
 
1ed2aaa
681eb4b
 
1ed2aaa
 
 
 
681eb4b
1ed2aaa
681eb4b
 
 
 
1ed2aaa
1072206
 
681eb4b
 
 
1ed2aaa
 
 
 
 
 
 
1072206
 
1ed2aaa
 
 
681eb4b
 
43ed1bc
 
 
 
 
681eb4b
 
43ed1bc
 
681eb4b
 
1ed2aaa
 
 
 
 
 
 
 
 
 
 
 
1072206
681eb4b
 
 
43ed1bc
 
1072206
43ed1bc
681eb4b
 
 
43ed1bc
 
681eb4b
 
 
43ed1bc
 
 
 
 
681eb4b
 
43ed1bc
 
681eb4b
 
1ed2aaa
1072206
 
 
 
 
 
 
 
 
181b06f
 
 
 
 
 
 
 
 
681eb4b
 
 
 
 
 
 
 
7563ab8
f88cb90
681eb4b
 
1072206
 
 
 
 
 
 
 
 
 
 
f88cb90
 
681eb4b
f88cb90
681eb4b
f88cb90
 
1072206
681eb4b
 
1ed2aaa
681eb4b
 
1ed2aaa
 
681eb4b
 
f88cb90
1ed2aaa
 
43ed1bc
 
 
 
 
1072206
f88cb90
 
181b06f
43ed1bc
 
 
1072206
 
 
681eb4b
43ed1bc
1072206
 
 
f88cb90
 
681eb4b
 
 
 
f88cb90
681eb4b
 
f88cb90
681eb4b
 
 
 
 
7563ab8
681eb4b
 
7563ab8
681eb4b
 
 
 
 
1ed2aaa
681eb4b
 
 
1ed2aaa
 
 
 
 
 
 
 
 
681eb4b
 
 
1ed2aaa
681eb4b
 
 
1072206
 
1ed2aaa
 
681eb4b
 
 
1ed2aaa
 
681eb4b
 
 
 
 
 
 
 
 
 
 
1ed2aaa
681eb4b
1ed2aaa
681eb4b
 
1ed2aaa
681eb4b
 
 
 
 
 
 
1ed2aaa
 
681eb4b
 
 
 
 
 
 
 
 
1ed2aaa
681eb4b
 
 
1ed2aaa
681eb4b
1ed2aaa
 
 
 
 
 
 
681eb4b
 
 
1ed2aaa
681eb4b
 
 
1072206
 
1ed2aaa
 
681eb4b
 
 
1ed2aaa
 
681eb4b
 
 
 
 
1ed2aaa
 
681eb4b
 
 
 
1ed2aaa
681eb4b
 
 
 
1ed2aaa
681eb4b
 
 
 
 
 
 
1ed2aaa
 
681eb4b
 
 
 
 
 
 
 
 
1ed2aaa
681eb4b
 
 
1ed2aaa
 
 
681eb4b
 
 
1ed2aaa
681eb4b
 
 
1072206
681eb4b
 
 
1ed2aaa
681eb4b
 
 
 
 
 
1ed2aaa
681eb4b
 
 
 
 
 
 
 
 
1ed2aaa
681eb4b
 
 
 
 
 
f88cb90
 
 
 
 
 
 
 
 
43ed1bc
681eb4b
43ed1bc
 
 
 
 
 
 
 
f88cb90
 
 
 
 
 
 
 
 
 
 
 
43ed1bc
 
 
 
 
 
 
 
 
 
f88cb90
 
 
681eb4b
f88cb90
681eb4b
f88cb90
 
681eb4b
 
f88cb90
681eb4b
f88cb90
681eb4b
f88cb90
1072206
 
681eb4b
 
 
f88cb90
681eb4b
 
 
 
 
f88cb90
681eb4b
f88cb90
1ed2aaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f88cb90
 
 
 
 
 
 
681eb4b
f88cb90
 
 
681eb4b
1072206
1ed2aaa
681eb4b
1072206
1ed2aaa
f88cb90
 
 
681eb4b
1072206
681eb4b
f88cb90
681eb4b
f88cb90
1ed2aaa
 
1072206
681eb4b
1ed2aaa
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
"""
BuildSustain - Building Components Module

This module handles the definition of building envelope components (walls, roofs, floors,
windows, skylights) for the BuildSustain application. It allows users to
assign constructions and fenestrations to specific components, define their areas,
orientations, and other relevant properties.

Developed by: Dr Majed Abuseif, Deakin University
© 2025
"""

import streamlit as st
import pandas as pd
import numpy as np
import json
import logging
import uuid
from typing import Dict, List, Any, Optional, Tuple, Union

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Define constants
COMPONENT_TYPES = ["Walls", "Roofs", "Floors", "Windows", "Skylights"]
ORIENTATION_OPTIONS = ["A (North)", "B (South)", "C (East)", "D (West)", "Custom"]
ORIENTATION_MAP = {'A (North)': 0.0, 'B (South)': 180.0, 'C (East)': 90.0, 'D (West)': 270.0, 'Custom': 0.0}

def display_components_page():
    """
    Display the building components page.
    This is the main function called by main.py when the Building Components page is selected.
    """
    st.title("Building Components")
    st.write("Define walls, roofs, floors, windows, and skylights based on ASHRAE 2005 Handbook of Fundamentals.")
    
    # Display help information in an expandable section
    with st.expander("Help & Information"):
        display_components_help()
    
    # Initialize components in session state if not present
    initialize_components()
    
    # Check if rerun is pending
    if 'components_rerun_pending' not in st.session_state:
        st.session_state.components_rerun_pending = False
    
    if st.session_state.components_rerun_pending:
        st.session_state.components_rerun_pending = False
        st.rerun()
    
    # Create tabs for different component types
    tabs = st.tabs(COMPONENT_TYPES)
    
    for i, component_type in enumerate(COMPONENT_TYPES):
        with tabs[i]:
            display_component_tab(component_type.lower())
    
    # Navigation buttons
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("Back to Construction", key="back_to_construction"):
            st.session_state.current_page = "Construction"
            st.rerun()
    
    with col2:
        if st.button("Continue to Internal Loads", key="continue_to_internal_loads"):
            st.session_state.current_page = "Internal Loads"
            st.rerun()

def initialize_components():
    """Initialize components in session state if not present."""
    if "components" not in st.session_state.project_data:
        st.session_state.project_data["components"] = {
            "walls": [],
            "roofs": [],
            "floors": [],
            "windows": [],
            "skylights": []
        }

def display_component_tab(comp_type: str):
    """
    Display the content for a specific component type tab.
    
    Args:
        comp_type: The type of component (e.g., "walls", "windows")
    """
    # Get singular form for display
    comp_singular = comp_type[:-1].capitalize()
    
    # Get components of this type
    components = st.session_state.project_data["components"].get(comp_type, [])
    
    # Get available items for this component type
    if comp_type in ["walls", "roofs", "floors"]:
        available_items = get_available_constructions()
    else:  # Windows, skylights
        available_items = get_available_fenestrations()
    
    # Split the display into two columns
    col1, col2 = st.columns([3, 2])
    
    with col1:
        st.subheader(f"Saved {comp_type.capitalize()}")
        
        if components:
            # Display components in a table format based on component type
            if comp_type in ["walls", "windows"]:
                display_wall_window_table(comp_type, components)
            elif comp_type in ["roofs", "skylights"]:
                display_roof_skylight_table(comp_type, components)
            elif comp_type == "floors":
                display_floor_table(comp_type, components)
        else:
            st.write(f"No {comp_type} defined.")
    
    with col2:
        st.subheader(f"{comp_singular} Editor/Creator")
        
        # Check if we have an editor state for this component type
        editor_key = f"{comp_type}_editor"
        if editor_key not in st.session_state:
            st.session_state[editor_key] = {}
        
        # Check if we have an action state for this component type
        action_key = f"{comp_type}_action"
        if action_key not in st.session_state:
            st.session_state[action_key] = {"action": None, "id": None}
        
        # Display the editor form
        with st.form(f"{comp_type}_editor_form", clear_on_submit=True):
            editor_state = st.session_state.get(editor_key, {})
            is_edit = editor_state.get("is_edit", False)
            
            # Component name
            name = st.text_input(
                "Name",
                value=editor_state.get("name", ""),
                help="Enter a unique name for this component."
            )
            
            # Area
            area = st.number_input(
                "Area (m²)",
                min_value=0.1,
                max_value=10000.0,
                value=float(editor_state.get("area", 10.0)),
                format="%.2f",
                help="Surface area of the component in square meters."
            )
            
            # Component-specific inputs
            if comp_type in ["walls", "windows", "roofs", "skylights"]:
                # Elevation (orientation)
                elevation = st.selectbox(
                    "Elevation",
                    ORIENTATION_OPTIONS,
                    index=ORIENTATION_OPTIONS.index(editor_state.get("elevation", ORIENTATION_OPTIONS[0])) if editor_state.get("elevation") in ORIENTATION_OPTIONS else 0,
                    help="Orientation of the component relative to the building orientation angle."
                )
                
                # Rotation
                rotation = st.number_input(
                    "Rotation (°)",
                    min_value=0.0,
                    max_value=359.0,
                    value=float(editor_state.get("rotation", 0.0)),
                    step=1.0,
                    format="%.0f",
                    help="Rotation angle in degrees to adjust the elevation (0° = North, 90° = East, 180° = South, 270° = West)."
                )
                
                # Calculate surface azimuth
                elevation_angle = ORIENTATION_MAP[elevation]
                surface_azimuth = (elevation_angle + rotation) % 360.0
                
                # Tilt
                default_tilt = 0.0 if comp_type in ["roofs", "skylights"] else 90.0
                tilt = st.number_input(
                    "Tilt (°)",
                    min_value=0.0,
                    max_value=180.0,
                    value=float(editor_state.get("tilt", default_tilt)),
                    step=1.0,
                    format="%.0f",
                    help="Tilt angle of the component relative to horizontal (0° = horizontal, 90° = vertical)."
                )
            
            elif comp_type == "floors":
                # Contact with ground percentage
                contact_with_ground_percentage = st.number_input(
                    "Contact with Ground (%)",
                    min_value=0.0,
                    max_value=100.0,
                    value=float(editor_state.get("contact_with_ground_percentage", 0.0)),
                    step=1.0,
                    format="%.0f",
                    help="Percentage of the floor in contact with the ground (0% = fully above ground, 100% = fully in contact)."
                )
            
            # Construction or fenestration selection
            if comp_type in ["walls", "roofs", "floors"]:
                construction_options = list(available_items.keys())
                if not construction_options:
                    st.error("No constructions available. Please create constructions first.")
                    construction_options = [""]
                
                construction = st.selectbox(
                    "Construction",
                    construction_options,
                    index=construction_options.index(editor_state.get("construction", "")) if editor_state.get("construction", "") in construction_options else 0,
                    help="Select the construction assembly for this component."
                )
                
                # Extract material properties from the first layer
                absorptivity = 0.7
                emissivity = 0.9
                if construction in available_items and "layers" in available_items[construction]:
                    first_layer = available_items[construction]["layers"][0]
                    if "material" in first_layer:
                        material_data = get_material_data(first_layer["material"])
                        if material_data:
                            absorptivity = material_data.get("absorptivity", 0.7)
                            emissivity = material_data.get("emissivity", 0.9)
            
            else:  # Windows, skylights
                # For fenestrations, we need to select a parent component
                parent_components = get_parent_components(comp_type)
                
                parent_options = list(parent_components.keys())
                if not parent_options:
                    st.error(f"No parent components available. Please create {'walls' if comp_type == 'windows' else 'roofs'} first.")
                    parent_options = [""]
                
                parent_component = st.selectbox(
                    "Parent Component",
                    parent_options,
                    index=parent_options.index(editor_state.get("parent_component", "")) if editor_state.get("parent_component", "") in parent_options else 0,
                    help="Select the wall or roof component this fenestration belongs to."
                )
                
                fenestration_options = list(available_items.keys())
                if not fenestration_options:
                    st.error("No fenestrations available. Please create fenestrations first.")
                    fenestration_options = [""]
                
                fenestration = st.selectbox(
                    "Fenestration",
                    fenestration_options,
                    index=fenestration_options.index(editor_state.get("fenestration", "")) if editor_state.get("fenestration", "") in fenestration_options else 0,
                    help="Select the fenestration type for this component."
                )
                
                # Shading Coefficient
                shading_coefficient = st.number_input(
                    "Shading Coefficient (SC)",
                    min_value=0.0,
                    max_value=1.0,
                    value=float(editor_state.get("shading_coefficient", 1.0)),
                    format="%.2f",
                    help="Shading coefficient for external or internal shading devices (0.0 to 1.0)."
                )
                
                # Function Type (Operable/Fixed)
                function_type_options = ["Operable", "Fixed"]
                function_type = st.selectbox(
                    "Function Type",
                    function_type_options,
                    index=function_type_options.index(editor_state.get("function_type", "Fixed")) if editor_state.get("function_type") in function_type_options else 0,
                    help="Select whether the window or skylight is operable (can be opened) or fixed."
                )
            
            # Submit buttons
            col1, col2 = st.columns(2)
            with col1:
                submit_label = "Update" if is_edit else "Add"
                submit = st.form_submit_button(f"{submit_label} {comp_singular}")
            
            with col2:
                refresh = st.form_submit_button("Refresh")
        
        # Handle form submission
        if submit:
            # Validate name
            if not name or name.strip() == "":
                st.error("Component name is required.")
                return
            
            # Check for unique name
            existing_names = [comp["name"] for comp in components if not (is_edit and comp["name"] == editor_state.get("name"))]
            if name in existing_names:
                st.error("Component name must be unique.")
                return
            
            # Create component data
            component_data = {
                "id": str(uuid.uuid4()),
                "name": name,
                "area": area
            }
            
            if comp_type in ["walls", "windows", "roofs", "skylights"]:
                component_data["elevation"] = elevation
                component_data["rotation"] = rotation
                component_data["surface_azimuth"] = surface_azimuth
                component_data["tilt"] = tilt
            
            if comp_type == "floors":
                component_data["contact_with_ground_percentage"] = contact_with_ground_percentage
            
            if comp_type in ["walls", "roofs", "floors"]:
                component_data["construction"] = construction
                component_data["absorptivity"] = absorptivity
                component_data["emissivity"] = emissivity
                # Get U-value from construction if available
                if construction in available_items:
                    component_data["u_value"] = available_items[construction].get("u_value", 0.0)
                else:
                    component_data["u_value"] = 0.0
            else:  # Windows, skylights
                component_data["fenestration"] = fenestration
                component_data["parent_component"] = parent_component
                component_data["function_type"] = function_type
                # Get U-value and other properties from fenestration if available
                if fenestration in available_items:
                    component_data["u_value"] = available_items[fenestration].get("u_value", 0.0)
                    component_data["shgc"] = available_items[fenestration].get("shgc", 0.7)
                    component_data["visible_transmittance"] = available_items[fenestration].get("visible_transmittance", 0.7)
                    component_data["shading_coefficient"] = shading_coefficient
                else:
                    component_data["u_value"] = 0.0
                    component_data["shgc"] = 0.7
                    component_data["visible_transmittance"] = 0.7
                    component_data["shading_coefficient"] = shading_coefficient
            
            # Handle edit mode
            if is_edit:
                index = editor_state.get("index", 0)
                st.session_state.project_data["components"][comp_type][index] = component_data
                st.success(f"{comp_singular} '{name}' updated!")
            else:
                st.session_state.project_data["components"][comp_type].append(component_data)
                st.success(f"{comp_singular} '{name}' added!")
            
            # Clear editor state
            st.session_state[editor_key] = {}
            st.session_state[action_key] = {"action": "save", "id": str(uuid.uuid4())}
            st.session_state.components_rerun_pending = True
        
        elif refresh:
            # Clear editor state
            st.session_state[editor_key] = {}
            st.session_state[action_key] = {"action": "refresh", "id": str(uuid.uuid4())}
            st.session_state.components_rerun_pending = True

def display_wall_window_table(comp_type: str, components: List[Dict[str, Any]]):
    """Display a table of walls or windows with appropriate columns."""
    # Create column headers
    cols = st.columns([2, 1, 1, 1, 1, 1, 1] if comp_type == "walls" else [2, 1, 1, 1, 1, 1, 1, 1])
    cols[0].write("**Name**")
    cols[1].write("**U-Value**")
    cols[2].write("**Area (m²)**")
    cols[3].write("**Surface Azimuth (°)**")
    cols[4].write("**Tilt (°)**")
    if comp_type == "walls":
        cols[5].write("**Edit**")
        cols[6].write("**Delete**")
    else:  # windows
        cols[5].write("**SC**")
        cols[6].write("**Edit**")
        cols[7].write("**Delete**")
    
    # Display each component
    for idx, comp in enumerate(components):
        cols = st.columns([2, 1, 1, 1, 1, 1, 1] if comp_type == "walls" else [2, 1, 1, 1, 1, 1, 1, 1])
        cols[0].write(comp["name"])
        cols[1].write(f"{comp.get('u_value', 0.0):.3f}")
        cols[2].write(f"{comp['area']:.2f}")
        cols[3].write(f"{comp.get('surface_azimuth', 0.0):.0f}")
        cols[4].write(f"{comp.get('tilt', 90.0):.0f}")
        if comp_type == "windows":
            cols[5].write(f"{comp.get('shading_coefficient', 1.0):.2f}")
        
        # Edit button
        edit_key = f"edit_{comp_type}_{comp['name']}_{idx}"
        edit_col = 5 if comp_type == "walls" else 6
        with cols[edit_col].container():
            if st.button("Edit", key=edit_key):
                editor_data = {
                    "index": idx,
                    "name": comp["name"],
                    "area": comp["area"],
                    "elevation": comp.get("elevation", ORIENTATION_OPTIONS[0]),
                    "rotation": comp.get("rotation", 0.0),
                    "tilt": comp.get("tilt", 90.0),
                    "is_edit": True
                }
                
                if comp_type == "walls":
                    editor_data["construction"] = comp.get("construction", "")
                else:  # windows
                    editor_data["fenestration"] = comp.get("fenestration", "")
                    editor_data["parent_component"] = comp.get("parent_component", "")
                    editor_data["shading_coefficient"] = comp.get("shading_coefficient", 1.0)
                
                st.session_state[f"{comp_type}_editor"] = editor_data
                st.session_state[f"{comp_type}_action"] = {"action": "edit", "id": str(uuid.uuid4())}
                st.session_state.components_rerun_pending = True
        
        # Delete button
        delete_key = f"delete_{comp_type}_{comp['name']}_{idx}"
        delete_col = 6 if comp_type == "walls" else 7
        with cols[delete_col].container():
            if st.button("Delete", key=delete_key):
                st.session_state.project_data["components"][comp_type].pop(idx)
                st.success(f"{comp_type[:-1].capitalize()} '{comp['name']}' deleted!")
                st.session_state[f"{comp_type}_action"] = {"action": "delete", "id": str(uuid.uuid4())}
                st.session_state.components_rerun_pending = True

def display_roof_skylight_table(comp_type: str, components: List[Dict[str, Any]]):
    """Display a table of roofs or skylights with appropriate columns."""
    # Create column headers
    cols = st.columns([2, 1, 1, 1, 1, 1, 1] if comp_type == "roofs" else [2, 1, 1, 1, 1, 1, 1, 1])
    cols[0].write("**Name**")
    cols[1].write("**U-Value**")
    cols[2].write("**Area (m²)**")
    cols[3].write("**Surface Azimuth (°)**")
    cols[4].write("**Tilt (°)**")
    if comp_type == "roofs":
        cols[5].write("**Edit**")
        cols[6].write("**Delete**")
    else:  # skylights
        cols[5].write("**SC**")
        cols[6].write("**Edit**")
        cols[7].write("**Delete**")
    
    # Display each component
    for idx, comp in enumerate(components):
        cols = st.columns([2, 1, 1, 1, 1, 1, 1] if comp_type == "roofs" else [2, 1, 1, 1, 1, 1, 1, 1])
        cols[0].write(comp["name"])
        cols[1].write(f"{comp.get('u_value', 0.0):.3f}")
        cols[2].write(f"{comp['area']:.2f}")
        cols[3].write(f"{comp.get('surface_azimuth', 0.0):.0f}")
        cols[4].write(f"{comp.get('tilt', 0.0):.0f}")
        if comp_type == "skylights":
            cols[5].write(f"{comp.get('shading_coefficient', 1.0):.2f}")
        
        # Edit button
        edit_key = f"edit_{comp_type}_{comp['name']}_{idx}"
        edit_col = 5 if comp_type == "roofs" else 6
        with cols[edit_col].container():
            if st.button("Edit", key=edit_key):
                editor_data = {
                    "index": idx,
                    "name": comp["name"],
                    "area": comp["area"],
                    "elevation": comp.get("elevation", ORIENTATION_OPTIONS[0]),
                    "rotation": comp.get("rotation", 0.0),
                    "tilt": comp.get("tilt", 0.0),
                    "is_edit": True
                }
                
                if comp_type == "roofs":
                    editor_data["construction"] = comp.get("construction", "")
                else:  # skylights
                    editor_data["fenestration"] = comp.get("fenestration", "")
                    editor_data["parent_component"] = comp.get("parent_component", "")
                    editor_data["shading_coefficient"] = comp.get("shading_coefficient", 1.0)
                
                st.session_state[f"{comp_type}_editor"] = editor_data
                st.session_state[f"{comp_type}_action"] = {"action": "edit", "id": str(uuid.uuid4())}
                st.session_state.components_rerun_pending = True
        
        # Delete button
        delete_key = f"delete_{comp_type}_{comp['name']}_{idx}"
        delete_col = 6 if comp_type == "roofs" else 7
        with cols[delete_col].container():
            if st.button("Delete", key=delete_key):
                st.session_state.project_data["components"][comp_type].pop(idx)
                st.success(f"{comp_type[:-1].capitalize()} '{comp['name']}' deleted!")
                st.session_state[f"{comp_type}_action"] = {"action": "delete", "id": str(uuid.uuid4())}
                st.session_state.components_rerun_pending = True

def display_floor_table(comp_type: str, components: List[Dict[str, Any]]):
    """Display a table of floors with appropriate columns."""
    # Create column headers
    cols = st.columns([2, 1, 1, 1, 1, 1])
    cols[0].write("**Name**")
    cols[1].write("**U-Value**")
    cols[2].write("**Area (m²)**")
    cols[3].write("**Contact with Ground (%)**")
    cols[4].write("**Edit**")
    cols[5].write("**Delete**")
    
    # Display each component
    for idx, comp in enumerate(components):
        cols = st.columns([2, 1, 1, 1, 1, 1])
        cols[0].write(comp["name"])
        cols[1].write(f"{comp.get('u_value', 0.0):.3f}")
        cols[2].write(f"{comp['area']:.2f}")
        cols[3].write(f"{comp.get('contact_with_ground_percentage', 0.0):.0f}")
        
        # Edit button
        edit_key = f"edit_{comp_type}_{comp['name']}_{idx}"
        with cols[4].container():
            if st.button("Edit", key=edit_key):
                editor_data = {
                    "index": idx,
                    "name": comp["name"],
                    "area": comp["area"],
                    "construction": comp.get("construction", ""),
                    "contact_with_ground_percentage": comp.get("contact_with_ground_percentage", 0.0),
                    "is_edit": True
                }
                
                st.session_state[f"{comp_type}_editor"] = editor_data
                st.session_state[f"{comp_type}_action"] = {"action": "edit", "id": str(uuid.uuid4())}
                st.session_state.components_rerun_pending = True
        
        # Delete button
        delete_key = f"delete_{comp_type}_{comp['name']}_{idx}"
        with cols[5].container():
            if st.button("Delete", key=delete_key):
                st.session_state.project_data["components"][comp_type].pop(idx)
                st.success(f"{comp_type[:-1].capitalize()} '{comp['name']}' deleted!")
                st.session_state[f"{comp_type}_action"] = {"action": "delete", "id": str(uuid.uuid4())}
                st.session_state.components_rerun_pending = True

def get_available_constructions() -> Dict[str, Any]:
    """
    Get all available constructions from both library and project.
    
    Returns:
        Dict of construction name to construction properties
    """
    available_constructions = {}
    
    # Add library constructions
    if "constructions" in st.session_state.project_data:
        if "library" in st.session_state.project_data["constructions"]:
            for name, construction in st.session_state.project_data["constructions"]["library"].items():
                available_constructions[name] = construction
        
        # Add project constructions
        if "project" in st.session_state.project_data["constructions"]:
            for name, construction in st.session_state.project_data["constructions"]["project"].items():
                available_constructions[name] = construction
    
    return available_constructions

def get_available_fenestrations() -> Dict[str, Any]:
    """
    Get all available fenestrations from both library and project.
    
    Returns:
        Dict of fenestration name to fenestration properties
    """
    available_fenestrations = {}
    
    # Add library fenestrations
    if "fenestrations" in st.session_state.project_data:
        if "library" in st.session_state.project_data["fenestrations"]:
            for name, fenestration in st.session_state.project_data["fenestrations"]["library"].items():
                available_fenestrations[name] = fenestration
        
        # Add project fenestrations
        if "project" in st.session_state.project_data["fenestrations"]:
            for name, fenestration in st.session_state.project_data["fenestrations"]["project"].items():
                available_fenestrations[name] = fenestration
    
    return available_fenestrations

def get_parent_components(comp_type: str) -> Dict[str, Any]:
    """
    Get appropriate parent components for a fenestration type.
    
    Args:
        comp_type: The type of fenestration component
    
    Returns:
        Dict of parent component name to parent component properties
    """
    parent_components = {}
    
    if comp_type == "windows":
        # Windows can only be on walls
        if "walls" in st.session_state.project_data["components"]:
            for wall in st.session_state.project_data["components"]["walls"]:
                parent_components[wall["name"]] = wall
    
    elif comp_type == "skylights":
        # Skylights can only be on roofs
        if "roofs" in st.session_state.project_data["components"]:
            for roof in st.session_state.project_data["components"]["roofs"]:
                parent_components[roof["name"]] = roof
    
    return parent_components

def get_material_data(material_name: str) -> Optional[Dict[str, Any]]:
    """
    Get material data from session state.
    
    Args:
        material_name: Name of the material
    
    Returns:
        Dict of material properties or None if not found
    """
    if "materials" in st.session_state.project_data:
        if "library" in st.session_state.project_data["materials"]:
            if material_name in st.session_state.project_data["materials"]["library"]:
                return st.session_state.project_data["materials"]["library"][material_name]
        if "project" in st.session_state.project_data["materials"]:
            if material_name in st.session_state.project_data["materials"]["project"]:
                return st.session_state.project_data["materials"]["project"][material_name]
    return None

def display_components_help():
    """
    Display help information for the building components page.
    """
    st.markdown("""
    ### Building Components Help
    
    This section allows you to define the building envelope components using the constructions and fenestrations you've created.
    
    **Key Concepts:**
    
    * **Walls, Roofs, Floors**: Opaque components that use constructions from the Construction section.
    * **Windows, Skylights**: Transparent components that use fenestrations from the Material Library section.
    * **Surface Azimuth**: Direction the component faces, calculated as elevation plus rotation (0° = North, 90° = East, 180° = South, 270° = West).
    * **Tilt**: Angle of the component relative to horizontal (0° = horizontal, 90° = vertical).
    * **Parent Component**: The wall or roof that contains a window or skylight.
    * **Shading Coefficient (SC)**: Factor for shading devices on windows/skylights (0.0 to 1.0).
    
    **Workflow:**
    
    1. First define opaque components (walls, roofs, floors) using constructions.
    2. Then define transparent components (windows, skylights) and assign them to parent components.
    3. Ensure all major building envelope components are included for accurate load calculations.
    
    **Tips:**
    
    * Use elevation (A, B, C, D) and rotation to set the surface azimuth.
    * For roofs and skylights, set tilt to 0° for flat surfaces.
    * Ensure the total area of windows doesn't exceed the area of their parent walls.
    * Ensure the total area of skylights doesn't exceed the area of their parent roofs.
    """)