mabuseif commited on
Commit
cc8b950
·
verified ·
1 Parent(s): 65a7d2d

Update utils/solar.py

Browse files
Files changed (1) hide show
  1. utils/solar.py +67 -40
utils/solar.py CHANGED
@@ -4,7 +4,7 @@ import math
4
  from datetime import datetime
5
  from app.materials_library import MaterialLibrary, GlazingMaterial, Material
6
  from utils.ctf_calculations import ComponentType
7
- from app.m_c_data import DEFAULT_WINDOW_PROPERTIES # Import for h_o default
8
  import logging
9
 
10
  # Configure logging
@@ -67,45 +67,73 @@ class SolarCalculations:
67
  logger.info("Initialized SolarCalculations with MaterialLibrary and project-specific libraries.")
68
 
69
  @staticmethod
70
- def day_of_year(month: int, day: int, year: int) -> int:
71
- """Calculate day of the year (n) from month, day, and year, accounting for leap years.
72
 
73
  Args:
74
- month (int): Month of the year (1-12).
75
- day (int): Day of the month (1-31).
76
- year (int): Year.
77
 
78
  Returns:
79
- int: Day of the year (1-365 or 366 for leap years).
80
 
81
  References:
82
- ASHRAE Handbook—Fundamentals, Chapter 18.
83
  """
84
- days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
85
- if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
86
- days_in_month[1] = 29
87
- return sum(days_in_month[:month-1]) + day
88
 
89
  @staticmethod
90
- def equation_of_time(n: int) -> float:
91
- """Calculate Equation of Time (EOT) in minutes using Spencer's formula.
92
 
93
  Args:
94
- n (int): Day of the year (1-365 or 366).
 
95
 
96
  Returns:
97
- float: Equation of Time in minutes.
98
 
99
  References:
100
- ASHRAE Handbook—Fundamentals, Chapter 18.
101
  """
102
- B = (n - 1) * 360 / 365
103
- B_rad = math.radians(B)
104
- EOT = 229.2 * (0.000075 + 0.001868 * math.cos(B_rad) - 0.032077 * math.sin(B_rad) -
105
- 0.014615 * math.cos(2 * B_rad) - 0.04089 * math.sin(2 * B_rad))
106
- return EOT
 
 
 
107
 
108
- def get_surface_parameters(self, component: Any, building_info: Dict) -> Tuple[float, float, float, Optional[float], float]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  """
110
  Determine surface parameters (tilt, azimuth, h_o, emissivity, absorptivity) for a component.
111
  Uses pre-calculated values stored in the component dictionary from components.py.
@@ -113,7 +141,8 @@ class SolarCalculations:
113
  Args:
114
  component: Component dictionary with surface_tilt, surface_azimuth, absorptivity/emissivity or shgc,
115
  component_type, and optionally fenestration.
116
- building_info (Dict): Building information (not used since parameters are pre-calculated).
 
117
 
118
  Returns:
119
  Tuple[float, float, float, Optional[float], float]: Surface tilt (°), surface azimuth (°),
@@ -137,19 +166,18 @@ class SolarCalculations:
137
  }
138
  component_type = type_map.get(component_type, ComponentType.WALL)
139
 
 
 
 
140
  # Default parameters
141
  if component_type == ComponentType.ROOF:
142
  surface_tilt = component.get('surface_tilt', 0.0)
143
- h_o = 23.0
144
  elif component_type == ComponentType.SKYLIGHT:
145
  surface_tilt = component.get('surface_tilt', 0.0)
146
- h_o = component.get('h_o', DEFAULT_WINDOW_PROPERTIES["h_o"])
147
  elif component_type == ComponentType.FLOOR:
148
  surface_tilt = component.get('surface_tilt', 180.0)
149
- h_o = 17.0
150
  else: # WALL, WINDOW
151
  surface_tilt = component.get('surface_tilt', 90.0)
152
- h_o = component.get('h_o', DEFAULT_WINDOW_PROPERTIES["h_o"]) if component_type == ComponentType.WINDOW else 17.0
153
 
154
  surface_azimuth = component.get('surface_azimuth', 0.0)
155
  emissivity = component.get('emissivity', 0.9 if component_type in [ComponentType.WALL, ComponentType.ROOF] else None)
@@ -176,19 +204,15 @@ class SolarCalculations:
176
  # Apply defaults
177
  if component_type == ComponentType.ROOF:
178
  surface_tilt = 0.0
179
- h_o = 23.0
180
  surface_azimuth = 0.0
181
  elif component_type == ComponentType.SKYLIGHT:
182
  surface_tilt = 0.0
183
- h_o = DEFAULT_WINDOW_PROPERTIES["h_o"]
184
  surface_azimuth = 0.0
185
  elif component_type == ComponentType.FLOOR:
186
  surface_tilt = 180.0
187
- h_o = 17.0
188
  surface_azimuth = 0.0
189
  else: # WALL, WINDOW
190
  surface_tilt = 90.0
191
- h_o = DEFAULT_WINDOW_PROPERTIES["h_o"] if component_type == ComponentType.WINDOW else 17.0
192
  surface_azimuth = 0.0
193
 
194
  if component_type in [ComponentType.WALL, ComponentType.ROOF]:
@@ -237,7 +261,7 @@ class SolarCalculations:
237
  """Calculate solar angles, sol-air temperature, and solar heat gain for hourly data with GHI > 0.
238
 
239
  Args:
240
- hourly_data (List[Dict]): Hourly weather data containing month, day, hour, GHI, DNI, DHI, dry_bulb.
241
  latitude (float): Latitude in degrees.
242
  longitude (float): Longitude in degrees.
243
  timezone (float): Timezone offset in hours.
@@ -294,6 +318,9 @@ class SolarCalculations:
294
  dni = record.get("direct_normal_radiation", ghi * 0.7) # Fallback: estimate DNI
295
  dhi = record.get("diffuse_horizontal_radiation", ghi * 0.3) # Fallback: estimate DHI
296
  outdoor_temp = record.get("dry_bulb")
 
 
 
297
 
298
  if None in [month, day, hour, outdoor_temp]:
299
  logger.error(f"Missing required weather data for {month}/{day}/{hour}")
@@ -308,7 +335,8 @@ class SolarCalculations:
308
  continue # Skip hours with no solar radiation
309
 
310
  logger.info(f"Processing solar for {month}/{day}/{hour} with GHI={ghi}, DNI={dni}, DHI={dhi}, "
311
- f"dry_bulb={outdoor_temp}")
 
312
 
313
  # Step 2: Local Solar Time (LST) with Equation of Time
314
  n = self.day_of_year(month, day, year)
@@ -351,7 +379,7 @@ class SolarCalculations:
351
  try:
352
  # Get surface parameters
353
  surface_tilt, surface_azimuth, h_o, emissivity, absorptivity = \
354
- self.get_surface_parameters(comp, building_info)
355
 
356
  # For windows/skylights, get SHGC from component
357
  shgc = comp.get('shgc', 0.7)
@@ -382,11 +410,10 @@ class SolarCalculations:
382
 
383
  # Calculate sol-air temperature for opaque surfaces
384
  if comp.get('type', '').lower() in ['walls', 'roofs']:
385
- delta_R = 63.0 if comp.get('type', '').lower() == 'roofs' else 0.0
386
- sol_air_temp = outdoor_temp + (absorptivity * I_t - (emissivity or 0.9) *
387
- delta_R) / h_o
388
- comp_result["sol_air_temp"] = round(sol_air_temp, 2)
389
- logger.info(f"Sol-air temp for {comp_result['component_id']} at {month}/{day}/{hour}: {sol_air_temp:.2f}°C")
390
 
391
  # Calculate solar heat gain for fenestration
392
  elif comp.get('type', '').lower() in ['windows', 'skylights']:
 
4
  from datetime import datetime
5
  from app.materials_library import MaterialLibrary, GlazingMaterial, Material
6
  from utils.ctf_calculations import ComponentType
7
+ from app.m_c_data import DEFAULT_WINDOW_PROPERTIES
8
  import logging
9
 
10
  # Configure logging
 
67
  logger.info("Initialized SolarCalculations with MaterialLibrary and project-specific libraries.")
68
 
69
  @staticmethod
70
+ def calculate_sky_temperature(T_out: float, dew_point: float, total_sky_cover: float = 0.5) -> float:
71
+ """Calculate sky temperature based on outdoor temperature, dew point, and cloud cover.
72
 
73
  Args:
74
+ T_out: Outdoor dry-bulb temperature (°C).
75
+ dew_point: Dew point temperature (°C).
76
+ total_sky_cover: Cloud cover fraction (0 to 1, default 0.5).
77
 
78
  Returns:
79
+ float: Sky temperature (°C).
80
 
81
  References:
82
+ ASHRAE Handbook—Fundamentals, Chapter 26.
83
  """
84
+ epsilon_sky = 0.9 + 0.04 * total_sky_cover
85
+ T_sky = (epsilon_sky * (T_out + 273.15)**4)**0.25 - 273.15
86
+ return T_sky if dew_point <= T_out else dew_point
 
87
 
88
  @staticmethod
89
+ def calculate_h_o(wind_speed: float, surface_type: ComponentType) -> float:
90
+ """Calculate outdoor convective heat transfer coefficient based on wind speed and surface type.
91
 
92
  Args:
93
+ wind_speed: Wind speed (m/s).
94
+ surface_type: ComponentType enum (WALL, ROOF, FLOOR, WINDOW, SKYLIGHT).
95
 
96
  Returns:
97
+ float: Outdoor heat transfer coefficient (W/m²·K).
98
 
99
  References:
100
+ ASHRAE Handbook—Fundamentals, Chapter 26.
101
  """
102
+ wind_speed = max(min(wind_speed, 20.0), 0.0) # Bound for stability
103
+ if surface_type in [ComponentType.WALL, ComponentType.FLOOR]:
104
+ h_o = 8.3 + 4.0 * (wind_speed ** 0.6) # ASHRAE Ch. 26
105
+ elif surface_type == ComponentType.ROOF:
106
+ h_o = 9.1 + 2.8 * wind_speed # ASHRAE Ch. 26
107
+ else: # WINDOW, SKYLIGHT
108
+ h_o = DEFAULT_WINDOW_PROPERTIES["h_o"]
109
+ return max(h_o, 5.0) # Minimum for stability
110
 
111
+ @staticmethod
112
+ def calculate_sol_air_temperature(T_out: float, I_t: float, absorptivity: float, emissivity: float,
113
+ h_o: float, dew_point: float, total_sky_cover: float = 0.5) -> float:
114
+ """Calculate sol-air temperature for opaque surfaces.
115
+
116
+ Args:
117
+ T_out: Outdoor dry-bulb temperature (°C).
118
+ I_t: Total incident solar radiation (W/m²).
119
+ absorptivity: Surface absorptivity (0 to 1).
120
+ emissivity: Surface emissivity (0 to 1).
121
+ h_o: Outdoor convective heat transfer coefficient (W/m²·K).
122
+ dew_point: Dew point temperature (°C).
123
+ total_sky_cover: Cloud cover fraction (0 to 1, default 0.5).
124
+
125
+ Returns:
126
+ float: Sol-air temperature (°C).
127
+
128
+ References:
129
+ ASHRAE Handbook—Fundamentals, Chapter 26, Eq. 13.
130
+ """
131
+ sigma = 5.67e-8 # Stefan-Boltzmann constant
132
+ T_sky = SolarCalculations.calculate_sky_temperature(T_out, dew_point, total_sky_cover)
133
+ T_sol_air = T_out + (absorptivity * I_t - emissivity * sigma * ((T_out + 273.15)**4 - (T_sky + 273.15)**4)) / h_o
134
+ return T_sol_air
135
+
136
+ def get_surface_parameters(self, component: Any, building_info: Dict, wind_speed: float = 4.0) -> Tuple[float, float, float, Optional[float], float]:
137
  """
138
  Determine surface parameters (tilt, azimuth, h_o, emissivity, absorptivity) for a component.
139
  Uses pre-calculated values stored in the component dictionary from components.py.
 
141
  Args:
142
  component: Component dictionary with surface_tilt, surface_azimuth, absorptivity/emissivity or shgc,
143
  component_type, and optionally fenestration.
144
+ building_info: Building information (not used since parameters are pre-calculated).
145
+ wind_speed: Wind speed (m/s, default 4.0).
146
 
147
  Returns:
148
  Tuple[float, float, float, Optional[float], float]: Surface tilt (°), surface azimuth (°),
 
166
  }
167
  component_type = type_map.get(component_type, ComponentType.WALL)
168
 
169
+ # Calculate h_o dynamically
170
+ h_o = self.calculate_h_o(wind_speed, component_type)
171
+
172
  # Default parameters
173
  if component_type == ComponentType.ROOF:
174
  surface_tilt = component.get('surface_tilt', 0.0)
 
175
  elif component_type == ComponentType.SKYLIGHT:
176
  surface_tilt = component.get('surface_tilt', 0.0)
 
177
  elif component_type == ComponentType.FLOOR:
178
  surface_tilt = component.get('surface_tilt', 180.0)
 
179
  else: # WALL, WINDOW
180
  surface_tilt = component.get('surface_tilt', 90.0)
 
181
 
182
  surface_azimuth = component.get('surface_azimuth', 0.0)
183
  emissivity = component.get('emissivity', 0.9 if component_type in [ComponentType.WALL, ComponentType.ROOF] else None)
 
204
  # Apply defaults
205
  if component_type == ComponentType.ROOF:
206
  surface_tilt = 0.0
 
207
  surface_azimuth = 0.0
208
  elif component_type == ComponentType.SKYLIGHT:
209
  surface_tilt = 0.0
 
210
  surface_azimuth = 0.0
211
  elif component_type == ComponentType.FLOOR:
212
  surface_tilt = 180.0
 
213
  surface_azimuth = 0.0
214
  else: # WALL, WINDOW
215
  surface_tilt = 90.0
 
216
  surface_azimuth = 0.0
217
 
218
  if component_type in [ComponentType.WALL, ComponentType.ROOF]:
 
261
  """Calculate solar angles, sol-air temperature, and solar heat gain for hourly data with GHI > 0.
262
 
263
  Args:
264
+ hourly_data (List[Dict]): Hourly weather data containing month, day, szehour, GHI, DNI, DHI, dry_bulb.
265
  latitude (float): Latitude in degrees.
266
  longitude (float): Longitude in degrees.
267
  timezone (float): Timezone offset in hours.
 
318
  dni = record.get("direct_normal_radiation", ghi * 0.7) # Fallback: estimate DNI
319
  dhi = record.get("diffuse_horizontal_radiation", ghi * 0.3) # Fallback: estimate DHI
320
  outdoor_temp = record.get("dry_bulb")
321
+ dew_point = record.get("dew_point", outdoor_temp - 5.0)
322
+ wind_speed = record.get("wind_speed", 4.0)
323
+ total_sky_cover = record.get("total_sky_cover", 0.5)
324
 
325
  if None in [month, day, hour, outdoor_temp]:
326
  logger.error(f"Missing required weather data for {month}/{day}/{hour}")
 
335
  continue # Skip hours with no solar radiation
336
 
337
  logger.info(f"Processing solar for {month}/{day}/{hour} with GHI={ghi}, DNI={dni}, DHI={dhi}, "
338
+ f"dry_bulb={outdoor_temp}, dew_point={dew_point}, wind_speed={wind_speed}, "
339
+ f"total_sky_cover={total_sky_cover}")
340
 
341
  # Step 2: Local Solar Time (LST) with Equation of Time
342
  n = self.day_of_year(month, day, year)
 
379
  try:
380
  # Get surface parameters
381
  surface_tilt, surface_azimuth, h_o, emissivity, absorptivity = \
382
+ self.get_surface_parameters(comp, building_info, wind_speed)
383
 
384
  # For windows/skylights, get SHGC from component
385
  shgc = comp.get('shgc', 0.7)
 
410
 
411
  # Calculate sol-air temperature for opaque surfaces
412
  if comp.get('type', '').lower() in ['walls', 'roofs']:
413
+ T_sol_air = self.calculate_sol_air_temperature(
414
+ outdoor_temp, I_t, absorptivity, emissivity or 0.9, h_o, dew_point, total_sky_cover)
415
+ comp_result["sol_air_temp"] = round(T_sol_air, 2)
416
+ logger.info(f"Sol-air temp for {comp_result['component_id']} at {month}/{day}/{hour}: {T_sol_air:.2f}°C")
 
417
 
418
  # Calculate solar heat gain for fenestration
419
  elif comp.get('type', '').lower() in ['windows', 'skylights']: