File size: 36,153 Bytes
845939b
02ba5be
845939b
 
02ba5be
 
 
 
 
 
 
 
845939b
 
 
 
 
 
 
 
 
07f89c5
 
 
845939b
 
 
 
 
 
 
 
 
0b114ac
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
 
 
 
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
 
 
 
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
 
 
845939b
02ba5be
 
 
 
 
 
 
 
 
 
 
845939b
 
 
 
 
 
 
 
1489bc9
845939b
 
 
1489bc9
845939b
 
 
 
1489bc9
 
845939b
 
 
 
 
 
1489bc9
 
02ba5be
1489bc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
 
1489bc9
02ba5be
 
 
 
 
 
 
 
 
 
 
 
1489bc9
 
02ba5be
1489bc9
 
02ba5be
1489bc9
 
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
 
 
 
 
 
 
 
 
52b868e
02ba5be
 
 
 
f5a007f
02ba5be
 
 
f5a007f
02ba5be
 
 
 
f5a007f
 
02ba5be
 
 
 
 
 
f5a007f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b114ac
f5a007f
 
 
 
 
 
 
 
 
 
 
02ba5be
f5a007f
02ba5be
 
f5a007f
 
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
 
 
 
 
 
 
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
845939b
 
 
 
 
 
02ba5be
 
845939b
 
02ba5be
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
845939b
 
 
 
 
02ba5be
 
845939b
 
 
 
 
 
 
 
 
 
02ba5be
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
 
 
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
 
 
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
845939b
 
 
 
 
 
02ba5be
 
 
 
 
 
 
 
845939b
 
 
 
02ba5be
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
845939b
 
 
 
 
 
 
 
 
 
 
02ba5be
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
845939b
 
 
 
 
 
 
 
 
02ba5be
 
 
 
845939b
 
 
 
 
 
 
 
 
02ba5be
845939b
 
 
 
 
 
 
 
 
 
 
 
 
 
02ba5be
 
845939b
 
 
 
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
"""
Enhanced heating load calculation module for HVAC Load Calculator.
Implements ASHRAE steady-state methods with simplified thermal lag for compatibility.
Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Section 18.4.

ENHANCEMENTS:
- Added support for equipment and internal loads as heating sources
- Added support for custom U-values for materials
- Improved integration with enhanced component selection features (crack dimensions, drapery inputs)
- Ensured compatibility with winter design parameters from enhanced climate data
- Added support for skylights in heating load calculations
- Improved infiltration calculations using crack dimensions
"""

from typing import Dict, List, Any, Optional, Tuple
import math
import numpy as np
import logging
from enum import Enum
from dataclasses import dataclass

# Debug print to confirm file version
print("Loading heating_load.py with data.building_components import")

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Import utility modules
from utils.psychrometrics import Psychrometrics
from utils.heat_transfer import HeatTransferCalculations

# Import data modules
from data.building_components import Wall, Roof, Floor, Window, Door, Orientation, ComponentType, Skylight


class HeatingLoadCalculator:
    """Class for heating load calculations based on ASHRAE steady-state methods."""
    
    def __init__(self, debug_mode: bool = False):
        """
        Initialize heating load calculator with psychrometric and heat transfer calculations.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Section 18.4.
        
        Args:
            debug_mode: Enable debug logging if True
        """
        self.psychrometrics = Psychrometrics()
        self.heat_transfer = HeatTransferCalculations()
        self.safety_factor = 1.15  # 15% safety factor for design loads
        self.debug_mode = debug_mode
        if debug_mode:
            logger.setLevel(logging.DEBUG)
    
    def validate_inputs(self, components: Dict[str, List[Any]], outdoor_temp: float, indoor_temp: float) -> None:
        """
        Validate input parameters for heating load calculations.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Section 18.4.
        
        Args:
            components: Dictionary of building components
            outdoor_temp: Outdoor design temperature in °C
            indoor_temp: Indoor design temperature in °C
            
        Raises:
            ValueError: If inputs are invalid
        """
        if not components:
            raise ValueError("Building components dictionary cannot be empty")
        for component_type, comp_list in components.items():
            if not isinstance(comp_list, list):
                raise ValueError(f"Components for {component_type} must be a list")
            for comp in comp_list:
                if not hasattr(comp, 'area') or comp.area <= 0:
                    raise ValueError(f"Invalid area for {component_type}: {comp.name}")
                if not hasattr(comp, 'u_value') or comp.u_value <= 0:
                    raise ValueError(f"Invalid U-value for {component_type}: {comp.name}")
        if not -50 <= outdoor_temp <= 60 or not -50 <= indoor_temp <= 60:
            raise ValueError("Temperatures must be between -50°C and 60°C")
        if indoor_temp - outdoor_temp < 1:
            raise ValueError("Indoor temperature must be at least 1°C above outdoor temperature for heating")

    def calculate_wall_heating_load(self, wall: Wall, outdoor_temp: float, indoor_temp: float) -> float:
        """
        Calculate heating load for a wall, with simplified thermal lag.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Equation 18.1.
        
        Args:
            wall: Wall component
            outdoor_temp: Outdoor temperature in °C
            indoor_temp: Indoor temperature in °C
            
        Returns:
            Heating load in W
        """
        delta_t = indoor_temp - outdoor_temp
        if delta_t <= 1:
            return 0.0  # Skip calculation for small temperature differences
        
        # Use default lag factor (no thermal mass adjustment)
        lag_factor = 1.0
        adjusted_delta_t = delta_t * lag_factor
        
        load = self.heat_transfer.conduction_heat_transfer(wall.u_value, wall.area, adjusted_delta_t)
        
        # ENHANCEMENT: Log detailed information in debug mode
        if self.debug_mode:
            logger.debug(f"Wall {wall.name} heating load: u_value={wall.u_value}, area={wall.area}, delta_t={adjusted_delta_t}, load={load:.2f} W")
        
        return max(0, load)

    def calculate_roof_heating_load(self, roof: Roof, outdoor_temp: float, indoor_temp: float) -> float:
        """
        Calculate heating load for a roof, with simplified thermal lag.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Equation 18.1.
        
        Args:
            roof: Roof component
            outdoor_temp: Outdoor temperature in °C
            indoor_temp: Indoor temperature in °C
            
        Returns:
            Heating load in W
        """
        delta_t = indoor_temp - outdoor_temp
        if delta_t <= 1:
            return 0.0
        
        lag_factor = 1.0
        adjusted_delta_t = delta_t * lag_factor
        
        load = self.heat_transfer.conduction_heat_transfer(roof.u_value, roof.area, adjusted_delta_t)
        
        # ENHANCEMENT: Log detailed information in debug mode
        if self.debug_mode:
            logger.debug(f"Roof {roof.name} heating load: u_value={roof.u_value}, area={roof.area}, delta_t={adjusted_delta_t}, load={load:.2f} W")
        
        return max(0, load)

    def calculate_floor_heating_load(self, floor: Floor, ground_temp: float, indoor_temp: float) -> float:
        """
        Calculate heating load for a floor, using dynamic F-factor for ground contact.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Section 18.4.3.
        
        Args:
            floor: Floor component
            ground_temp: Ground temperature in °C
            indoor_temp: Indoor temperature in °C
            
        Returns:
            Heating load in W
        """
        delta_t = indoor_temp - ground_temp
        if delta_t <= 1:
            return 0.0
        
        # ENHANCEMENT: Check if floor has ground_contact attribute
        is_ground_contact = floor.ground_contact if hasattr(floor, 'ground_contact') else False
        
        if is_ground_contact:
            # Dynamic F-factor based on insulation
            # ENHANCEMENT: Check if floor has insulated attribute
            is_insulated = floor.insulated if hasattr(floor, 'insulated') else False
            f_factor = 0.3 if is_insulated else 0.73  # W/m·K
            
            # ENHANCEMENT: Check if floor has perimeter attribute
            perimeter = floor.perimeter if hasattr(floor, 'perimeter') else (
                floor.perimeter_length if hasattr(floor, 'perimeter_length') else 
                math.sqrt(4 * floor.area)  # Estimate perimeter if not provided
            )
            
            load = f_factor * perimeter * delta_t
        else:
            load = self.heat_transfer.conduction_heat_transfer(floor.u_value, floor.area, delta_t)
        
        if self.debug_mode:
            logger.debug(f"Floor {floor.name} load: {load:.2f} W, Delta T: {delta_t:.2f}°C")
        
        return max(0, load)

    def calculate_window_heating_load(self, window: Window, outdoor_temp: float, indoor_temp: float, frame_type: Optional[str] = None) -> float:
        """
        Calculate heating load for a window.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Equation 18.1.
    
        Args:
            window: Window component
            outdoor_temp: Outdoor temperature in °C
            indoor_temp: Indoor temperature in °C
            frame_type: Type of window frame (optional, e.g., 'Aluminum without Thermal Break')
        
        Returns:
            Heating load in W
        """
        delta_t = indoor_temp - outdoor_temp
        if delta_t <= 1:
            return 0.0
    
        # Initialize adjusted U-value
        adjusted_u_value = window.u_value
    
        # Adjust U-value based on frame_type if provided
        frame_adjustments = {
            'Aluminum without Thermal Break': 1.0,
            'Aluminum with Thermal Break': 0.8,
            'Vinyl/Fiberglass': 0.6,
            'Wood/Vinyl-Clad Wood': 0.5,
            'Insulated': 0.4
        }
        if frame_type:
            adjustment = frame_adjustments.get(frame_type, 1.0)
            adjusted_u_value *= adjustment
        elif hasattr(window, 'frame_type') and window.frame_type:
            # Fallback to window.frame_type if frame_type not provided
            adjustment = frame_adjustments.get(window.frame_type, 1.0)
            adjusted_u_value *= adjustment
    
        # Adjust U-value if window has drapery
        if hasattr(window, 'has_drapery') and window.has_drapery:
            # Simple U-value adjustment for drapery (typically reduces U-value by 10-20%)
            drapery_reduction = 0.15  # 15% reduction as a default
        
            # More detailed adjustment if drapery properties are available
            if hasattr(window, 'drapery_type'):
                drapery_reductions = {
                    'None': 0.0,
                    'Sheer': 0.05,
                    'Light': 0.10,
                    'Medium': 0.15,
                    'Heavy': 0.20,
                    'Blackout': 0.25
                }
                drapery_reduction = drapery_reductions.get(window.drapery_type, 0.15)
        
            adjusted_u_value *= (1 - drapery_reduction)
    
        load = self.heat_transfer.conduction_heat_transfer(adjusted_u_value, window.area, delta_t)
    
        # Log detailed information in debug mode
        if self.debug_mode:
            logger.debug(f"Window {window.name} heating load: u_value={adjusted_u_value}, area={window.area}, delta_t={delta_t}, frame_type={frame_type or window.frame_type}, load={load:.2f} W")
    
        return max(0, load)

    def calculate_door_heating_load(self, door: Door, outdoor_temp: float, indoor_temp: float) -> float:
        """
        Calculate heating load for a door.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Equation 18.1.
        
        Args:
            door: Door component
            outdoor_temp: Outdoor temperature in °C
            indoor_temp: Indoor temperature in °C
            
        Returns:
            Heating load in W
        """
        delta_t = indoor_temp - outdoor_temp
        if delta_t <= 1:
            return 0.0
        
        # ENHANCEMENT: Adjust U-value if door has weatherstripping
        adjusted_u_value = door.u_value
        if hasattr(door, 'has_weatherstripping') and door.has_weatherstripping:
            # Simple U-value adjustment for weatherstripping (typically reduces U-value by 5-10%)
            adjusted_u_value = door.u_value * 0.95  # 5% reduction
        
        load = self.heat_transfer.conduction_heat_transfer(adjusted_u_value, door.area, delta_t)
        
        # ENHANCEMENT: Log detailed information in debug mode
        if self.debug_mode:
            logger.debug(f"Door {door.name} heating load: u_value={adjusted_u_value}, area={door.area}, delta_t={delta_t}, load={load:.2f} W")
        
        return max(0, load)
    
    # ENHANCEMENT: Added skylight heating load calculation
    def calculate_skylight_heating_load(self, skylight: Skylight, outdoor_temp: float, indoor_temp: float, frame_type: Optional[str] = None) -> float:
        """
        Calculate heating load for a skylight.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Equation 18.1.
    
        Args:
            skylight: Skylight component
            outdoor_temp: Outdoor temperature in °C
            indoor_temp: Indoor temperature in °C
            frame_type: Type of skylight frame (optional, e.g., 'Aluminum without Thermal Break')
        
        Returns:
            Heating load in W
        """
        delta_t = indoor_temp - outdoor_temp
        if delta_t <= 1:
            return 0.0
    
        # Initialize adjusted U-value
        adjusted_u_value = skylight.u_value
    
        # Adjust U-value based on frame_type if provided
        frame_adjustments = {
            'Aluminum without Thermal Break': 1.0,
            'Aluminum with Thermal Break': 0.8,
            'Vinyl/Fiberglass': 0.6,
            'Wood/Vinyl-Clad Wood': 0.5,
            'Insulated': 0.4
        }
        if frame_type:
            adjustment = frame_adjustments.get(frame_type, 1.0)
            adjusted_u_value *= adjustment
        elif hasattr(skylight, 'frame_type') and skylight.frame_type:
            # Fallback to skylight.frame_type if frame_type not provided
            adjustment = frame_adjustments.get(skylight.frame_type, 1.0)
            adjusted_u_value *= adjustment
    
        # Adjust U-value for drapery based on drapery_openness
        if hasattr(skylight, 'drapery_openness') and skylight.drapery_openness != 'Open':
            drapery_reduction = {
                'Closed': 0.20,
                'Semi-Open': 0.10,
                'Open': 0.0
            }.get(skylight.drapery_openness, 0.15)
            adjusted_u_value *= (1 - drapery_reduction)
    
        load = self.heat_transfer.conduction_heat_transfer(adjusted_u_value, skylight.area, delta_t)
    
        # Log detailed information in debug mode
        if self.debug_mode:
            logger.debug(f"Skylight {skylight.name} heating load: u_value={adjusted_u_value}, area={skylight.area}, delta_t={delta_t}, frame_type={frame_type or skylight.frame_type}, load={load:.2f} W")
    
        return max(0, load)

    def calculate_infiltration_heating_load(self, indoor_conditions: Dict[str, float], 
                                          outdoor_conditions: Dict[str, float], 
                                          infiltration: Dict[str, float], 
                                          building_height: float,
                                          p_atm: float = 101325) -> Tuple[float, float]:
        """
        Calculate sensible and latent heating loads due to infiltration.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Equations 18.5-18.6.
        
        Args:
            indoor_conditions: Indoor conditions (temperature, relative_humidity)
            outdoor_conditions: Outdoor conditions (design_temperature, design_relative_humidity, wind_speed)
            infiltration: Infiltration parameters (flow_rate, crack_length, height)
            building_height: Building height in m
            p_atm: Atmospheric pressure in Pa (default: 101325 Pa)
            
        Returns:
            Tuple of sensible and latent loads in W
        """
        delta_t = indoor_conditions['temperature'] - outdoor_conditions['design_temperature']
        if delta_t <= 1:
            return 0.0, 0.0
        
        # Calculate pressure differences
        wind_pd = self.heat_transfer.wind_pressure_difference(outdoor_conditions['wind_speed'])
        stack_pd = self.heat_transfer.stack_pressure_difference(
            building_height, 
            indoor_conditions['temperature'] + 273.15, 
            outdoor_conditions['design_temperature'] + 273.15
        )
        total_pd = self.heat_transfer.combined_pressure_difference(wind_pd, stack_pd)
        
        # ENHANCEMENT: Use crack dimensions if available for more accurate infiltration calculation
        if 'crack_length' in infiltration and 'crack_width' in infiltration:
            crack_length = infiltration['crack_length']
            crack_width = infiltration['crack_width'] / 1000.0  # Convert from mm to m
            flow_rate = self.heat_transfer.crack_method_infiltration(crack_length, crack_width, total_pd)
        else:
            # Use provided flow rate or default
            flow_rate = infiltration.get('flow_rate', 0.05)  # m³/s
        
        # Calculate humidity ratio difference
        w_indoor = self.psychrometrics.humidity_ratio(
            indoor_conditions['temperature'], 
            indoor_conditions['relative_humidity'],
            p_atm
        )
        w_outdoor = self.psychrometrics.humidity_ratio(
            outdoor_conditions['design_temperature'], 
            outdoor_conditions['design_relative_humidity'],
            p_atm
        )
        delta_w = max(0, w_indoor - w_outdoor)
        
        # Calculate sensible and latent loads using indoor conditions for air properties
        sensible_load = self.heat_transfer.infiltration_heat_transfer(
            flow_rate, delta_t, 
            indoor_conditions['temperature'], 
            indoor_conditions['relative_humidity'],
            p_atm
        )
        latent_load = self.heat_transfer.infiltration_latent_heat_transfer(
            flow_rate, delta_w, 
            indoor_conditions['temperature'], 
            indoor_conditions['relative_humidity'],
            p_atm
        )
        
        if self.debug_mode:
            logger.debug(f"Infiltration flow rate: {flow_rate:.6f} m³/s, Sensible load: {sensible_load:.2f} W, Latent load: {latent_load:.2f} W")
        
        return max(0, sensible_load), max(0, latent_load)

    def calculate_ventilation_heating_load(self, ventilation: Dict[str, float], 
                                         indoor_conditions: Dict[str, float], 
                                         outdoor_conditions: Dict[str, float],
                                         p_atm: float = 101325) -> Tuple[float, float]:
        """
        Calculate sensible and latent heating loads due to ventilation.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Equations 18.5-18.6.
        
        Args:
            ventilation: Ventilation parameters (flow_rate)
            indoor_conditions: Indoor conditions (temperature, relative_humidity)
            outdoor_conditions: Outdoor conditions (design_temperature, design_relative_humidity)
            p_atm: Atmospheric pressure in Pa (default: 101325 Pa)
            
        Returns:
            Tuple of sensible and latent loads in W
        """
        delta_t = indoor_conditions['temperature'] - outdoor_conditions['design_temperature']
        if delta_t <= 1:
            return 0.0, 0.0
        
        flow_rate = ventilation['flow_rate']
        
        w_indoor = self.psychrometrics.humidity_ratio(
            indoor_conditions['temperature'], 
            indoor_conditions['relative_humidity'],
            p_atm
        )
        w_outdoor = self.psychrometrics.humidity_ratio(
            outdoor_conditions['design_temperature'], 
            outdoor_conditions['design_relative_humidity'],
            p_atm
        )
        delta_w = max(0, w_indoor - w_outdoor)
        
        # Calculate sensible and latent loads using indoor conditions for air properties
        sensible_load = self.heat_transfer.infiltration_heat_transfer(
            flow_rate, delta_t,
            indoor_conditions['temperature'],
            indoor_conditions['relative_humidity'],
            p_atm
        )
        latent_load = self.heat_transfer.infiltration_latent_heat_transfer(
            flow_rate, delta_w,
            indoor_conditions['temperature'],
            indoor_conditions['relative_humidity'],
            p_atm
        )
        
        if self.debug_mode:
            logger.debug(f"Ventilation flow rate: {flow_rate:.6f} m³/s, Sensible load: {sensible_load:.2f} W, Latent load: {latent_load:.2f} W")
        
        return max(0, sensible_load), max(0, latent_load)

    # ENHANCEMENT: Modified to include equipment and internal loads as heating sources
    def calculate_internal_gains(self, internal_loads: Dict[str, Any], include_as_heating_source: bool = True) -> float:
        """
        Calculate internal heat gains from people, lighting, and equipment.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Section 18.4.4.
        
        Args:
            internal_loads: Internal loads (people, lights, equipment)
            include_as_heating_source: Whether to include internal gains as heating sources (positive value)
                                      or as load reductions (negative value)
            
        Returns:
            Total internal gains in W (positive if heating source, negative if load reduction)
        """
        total_gains = 0.0
        
        # People gains
        people = internal_loads.get('people', {})
        if people.get('number', 0) > 0:
            sensible_gain = people.get('sensible_gain', 70.0)
            total_gains += people['number'] * sensible_gain
        
        # Lighting gains
        lights = internal_loads.get('lights', {})
        if lights.get('power', 0) > 0:
            total_gains += lights['power'] * lights.get('use_factor', 0.8)
        
        # Equipment gains
        equipment = internal_loads.get('equipment', {})
        if equipment.get('power', 0) > 0:
            total_gains += equipment['power'] * equipment.get('use_factor', 0.7)
        
        # ENHANCEMENT: Return positive value if including as heating source, negative if reducing load
        return total_gains if include_as_heating_source else -total_gains

    def calculate_design_heating_load(self, building_components: Dict[str, List[Any]], 
                                    outdoor_conditions: Dict[str, float], 
                                    indoor_conditions: Dict[str, float], 
                                    internal_loads: Dict[str, Any],
                                    p_atm: float = 101325,
                                    include_internal_gains_as_heating_source: bool = False) -> Dict[str, float]:
        """
        Calculate design heating loads for all components.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Section 18.4.
        
        Args:
            building_components: Dictionary of building components
            outdoor_conditions: Outdoor conditions (design_temperature, design_relative_humidity, ground_temperature, wind_speed)
            indoor_conditions: Indoor conditions (temperature, relative_humidity)
            internal_loads: Internal loads (people, lights, equipment, infiltration, ventilation)
            p_atm: Atmospheric pressure in Pa (default: 101325 Pa)
            include_internal_gains_as_heating_source: Whether to include internal gains as heating sources
            
        Returns:
            Dictionary of design loads in W
        """
        try:
            self.validate_inputs(building_components, outdoor_conditions['design_temperature'], indoor_conditions['temperature'])
        except ValueError as e:
            raise ValueError(f"Input validation failed: {str(e)}")
        
        loads = {
            'walls': 0.0,
            'roofs': 0.0,
            'floors': 0.0,
            'windows': 0.0,
            'doors': 0.0,
            'skylights': 0.0,  # ENHANCEMENT: Added skylights
            'infiltration_sensible': 0.0,
            'infiltration_latent': 0.0,
            'ventilation_sensible': 0.0,
            'ventilation_latent': 0.0,
            'internal_gains': 0.0
        }
        
        # Calculate envelope loads
        for wall in building_components.get('walls', []):
            loads['walls'] += self.calculate_wall_heating_load(wall, outdoor_conditions['design_temperature'], indoor_conditions['temperature'])
        
        for roof in building_components.get('roofs', []):
            loads['roofs'] += self.calculate_roof_heating_load(roof, outdoor_conditions['design_temperature'], indoor_conditions['temperature'])
        
        for floor in building_components.get('floors', []):
            loads['floors'] += self.calculate_floor_heating_load(floor, outdoor_conditions['ground_temperature'], indoor_conditions['temperature'])
        
        for window in building_components.get('windows', []):
            loads['windows'] += self.calculate_window_heating_load(window, outdoor_conditions['design_temperature'], indoor_conditions['temperature'])
        
        for door in building_components.get('doors', []):
            loads['doors'] += self.calculate_door_heating_load(door, outdoor_conditions['design_temperature'], indoor_conditions['temperature'])
        
        # ENHANCEMENT: Added skylights
        for skylight in building_components.get('skylights', []):
            loads['skylights'] += self.calculate_skylight_heating_load(skylight, outdoor_conditions['design_temperature'], indoor_conditions['temperature'])
        
        # Calculate infiltration and ventilation loads
        building_height = internal_loads.get('infiltration', {}).get('height', 3.0)
        infiltration_sensible, infiltration_latent = self.calculate_infiltration_heating_load(
            indoor_conditions, outdoor_conditions, internal_loads.get('infiltration', {}), building_height, p_atm
        )
        loads['infiltration_sensible'] = infiltration_sensible
        loads['infiltration_latent'] = infiltration_latent
        
        ventilation_sensible, ventilation_latent = self.calculate_ventilation_heating_load(
            internal_loads.get('ventilation', {}), indoor_conditions, outdoor_conditions, p_atm
        )
        loads['ventilation_sensible'] = ventilation_sensible
        loads['ventilation_latent'] = ventilation_latent
        
        # ENHANCEMENT: Calculate internal gains (positive or negative based on parameter)
        loads['internal_gains'] = self.calculate_internal_gains(
            internal_loads, include_as_heating_source=include_internal_gains_as_heating_source
        )
        
        return loads

    def calculate_heating_load_summary(self, design_loads: Dict[str, float]) -> Dict[str, float]:
        """
        Summarize heating loads with safety factor.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Section 18.4.
        
        Args:
            design_loads: Dictionary of design loads in W
            
        Returns:
            Summary dictionary with total, subtotal, and safety factor
        """
        # ENHANCEMENT: Include skylights in subtotal
        subtotal = sum(
            load for key, load in design_loads.items()
            if key not in ['internal_gains'] and load > 0
        )
        internal_gains = design_loads.get('internal_gains', 0)
        
        # ENHANCEMENT: If internal gains are positive (heating source), add them to subtotal
        # If negative (load reduction), subtract them from subtotal
        if internal_gains >= 0:
            adjusted_subtotal = subtotal + internal_gains
        else:
            adjusted_subtotal = subtotal + internal_gains  # internal_gains is negative, so this is subtraction
        
        total = max(0, adjusted_subtotal) * self.safety_factor
        
        return {
            'subtotal': subtotal,
            'internal_gains': internal_gains,
            'adjusted_subtotal': adjusted_subtotal,
            'total': total,
            'safety_factor': self.safety_factor
        }

    def calculate_heating_degree_days(self, base_temp: float, monthly_temps: Dict[str, float]) -> float:
        """
        Calculate heating degree days for a year.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 14, Section 14.3.
        
        Args:
            base_temp: Base temperature for HDD calculation in °C
            monthly_temps: Dictionary of monthly average temperatures
            
        Returns:
            Total heating degree days
        """
        hdd = 0.0
        days_per_month = {
            'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30,
            'Jul': 31, 'Aug': 31, 'Sep': 30, 'Oct': 31, 'Nov': 30, 'Dec': 31
        }
        
        for month, temp in monthly_temps.items():
            if temp < base_temp:
                hdd += (base_temp - temp) * days_per_month[month]
        
        return hdd

    def calculate_annual_heating_energy(self, design_loads: Dict[str, float], 
                                      monthly_temps: Dict[str, float], 
                                      indoor_temp: float, 
                                      operating_hours: str) -> float:
        """
        Calculate annual heating energy consumption.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 14, Section 14.3.
        
        Args:
            design_loads: Dictionary of design loads in W
            monthly_temps: Dictionary of monthly average temperatures
            indoor_temp: Indoor design temperature in °C
            operating_hours: Operating hours (e.g., '8:00-18:00')
            
        Returns:
            Annual heating energy in kWh
        """
        base_temp = indoor_temp
        hdd = self.calculate_heating_degree_days(base_temp, monthly_temps)
        
        # Parse operating hours
        start_hour, end_hour = map(lambda x: int(x.split(':')[0]), operating_hours.split('-'))
        daily_hours = end_hour - start_hour
        
        # Calculate design condition degree days
        design_temp = min(monthly_temps.values())
        design_delta_t = indoor_temp - design_temp
        if design_delta_t <= 1:
            return 0.0
        
        total_load = self.calculate_heating_load_summary(design_loads)['total']
        
        # Scale load by HDD and operating hours
        annual_energy = (total_load / design_delta_t) * hdd * (daily_hours / 24) / 1000  # kWh
        
        return max(0, annual_energy)

    def calculate_monthly_heating_loads(self, building_components: Dict[str, List[Any]], 
                                      outdoor_conditions: Dict[str, float], 
                                      indoor_conditions: Dict[str, float], 
                                      internal_loads: Dict[str, Any], 
                                      monthly_temps: Dict[str, float],
                                      p_atm: float = 101325,
                                      include_internal_gains_as_heating_source: bool = False) -> Dict[str, float]:
        """
        Calculate monthly heating loads.
        Reference: ASHRAE Handbook—Fundamentals (2017), Chapter 18, Section 18.4.
        
        Args:
            building_components: Dictionary of building components
            outdoor_conditions: Outdoor conditions
            indoor_conditions: Indoor conditions
            internal_loads: Internal loads
            monthly_temps: Dictionary of monthly average temperatures
            p_atm: Atmospheric pressure in Pa (default: 101325 Pa)
            include_internal_gains_as_heating_source: Whether to include internal gains as heating sources
            
        Returns:
            Dictionary of monthly heating loads in kW
        """
        monthly_loads = {}
        days_per_month = {
            'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30,
            'Jul': 31, 'Aug': 31, 'Sep': 30, 'Oct': 31, 'Nov': 30, 'Dec': 31
        }
        
        for month, temp in monthly_temps.items():
            modified_outdoor = outdoor_conditions.copy()
            modified_outdoor['design_temperature'] = temp
            modified_outdoor['ground_temperature'] = temp
            
            try:
                design_loads = self.calculate_design_heating_load(
                    building_components, modified_outdoor, indoor_conditions, internal_loads, p_atm,
                    include_internal_gains_as_heating_source
                )
                summary = self.calculate_heating_load_summary(design_loads)
                monthly_loads[month] = summary['total'] / 1000  # kW
            except ValueError:
                monthly_loads[month] = 0.0  # Skip invalid months
        
        return monthly_loads

# Example usage
if __name__ == "__main__":
    calculator = HeatingLoadCalculator(debug_mode=True)
    
    # Example building components
    components = {
        'walls': [Wall(id="w1", name="North Wall", area=20.0, u_value=0.5, orientation=Orientation.NORTH)],
        'roofs': [Roof(id="r1", name="Main Roof", area=100.0, u_value=0.3, orientation=Orientation.HORIZONTAL)],
        'floors': [Floor(id="f1", name="Ground Floor", area=100.0, u_value=0.4, perimeter_length=40.0, 
                        is_ground_contact=True, insulated=True, ground_temperature_c=10.0)],
        'windows': [Window(id="win1", name="South Window", area=10.0, u_value=2.8, orientation=Orientation.SOUTH, 
                          shgc=0.7, shading_coefficient=0.8)],
        'doors': [Door(id="d1", name="Main Door", area=2.0, u_value=2.0, orientation=Orientation.NORTH)],
        'skylights': [Skylight(id="s1", name="Main Skylight", area=5.0, u_value=3.0, orientation=Orientation.HORIZONTAL)]
    }
    
    outdoor_conditions = {
        'design_temperature': -5.0,
        'design_relative_humidity': 80.0,
        'ground_temperature': 10.0,
        'wind_speed': 4.0
    }
    indoor_conditions = {
        'temperature': 21.0,
        'relative_humidity': 40.0
    }
    internal_loads = {
        'people': {'number': 10, 'sensible_gain': 70.0, 'operating_hours': '8:00-18:00'},
        'lights': {'power': 1000.0, 'use_factor': 0.8, 'hours_operation': '8h'},
        'equipment': {'power': 500.0, 'use_factor': 0.7, 'hours_operation': '8h'},
        'infiltration': {'flow_rate': 0.05, 'height': 3.0, 'crack_length': 20.0, 'crack_width': 2.0},
        'ventilation': {'flow_rate': 0.1},
        'operating_hours': '8:00-18:00'
    }
    monthly_temps = {
        'Jan': -5.0, 'Feb': -3.0, 'Mar': 2.0, 'Apr': 8.0, 'May': 14.0, 'Jun': 19.0,
        'Jul': 22.0, 'Aug': 21.0, 'Sep': 16.0, 'Oct': 10.0, 'Nov': 4.0, 'Dec': -2.0
    }
    
    # Calculate design loads
    design_loads = calculator.calculate_design_heating_load(
        components, outdoor_conditions, indoor_conditions, internal_loads,
        include_internal_gains_as_heating_source=True  # ENHANCEMENT: Include internal gains as heating sources
    )
    summary = calculator.calculate_heating_load_summary(design_loads)
    
    # Log results
    logger.info(f"Total Heating Load: {summary['total']:.2f} W")
    logger.info(f"Wall Load: {design_loads['walls']:.2f} W")
    logger.info(f"Roof Load: {design_loads['roofs']:.2f} W")
    logger.info(f"Floor Load: {design_loads['floors']:.2f} W")
    logger.info(f"Window Load: {design_loads['windows']:.2f} W")
    logger.info(f"Door Load: {design_loads['doors']:.2f} W")
    logger.info(f"Skylight Load: {design_loads['skylights']:.2f} W")  # ENHANCEMENT: Added skylight load
    logger.info(f"Infiltration Sensible Load: {design_loads['infiltration_sensible']:.2f} W")
    logger.info(f"Infiltration Latent Load: {design_loads['infiltration_latent']:.2f} W")
    logger.info(f"Ventilation Sensible Load: {design_loads['ventilation_sensible']:.2f} W")
    logger.info(f"Ventilation Latent Load: {design_loads['ventilation_latent']:.2f} W")
    logger.info(f"Internal Gains: {design_loads['internal_gains']:.2f} W")
    
    # Calculate annual energy
    annual_energy = calculator.calculate_annual_heating_energy(
        design_loads, monthly_temps, indoor_conditions['temperature'], internal_loads['operating_hours']
    )
    logger.info(f"Annual Heating Energy: {annual_energy:.2f} kWh")
    
    # Calculate monthly loads
    monthly_loads = calculator.calculate_monthly_heating_loads(
        components, outdoor_conditions, indoor_conditions, internal_loads, monthly_temps,
        include_internal_gains_as_heating_source=True  # ENHANCEMENT: Include internal gains as heating sources
    )
    logger.info("Monthly Heating Loads (kW):")
    for month, load in monthly_loads.items():
        logger.info(f"{month}: {load:.2f} kW")