monthly energy balance exporter v1.0

No unittest created yet
This commit is contained in:
Pilar 2022-11-23 16:34:48 -05:00
parent f6e049563f
commit 157f7fa2cb
3 changed files with 256 additions and 0 deletions

76
exports/insel/insel.py Normal file
View File

@ -0,0 +1,76 @@
"""
Insel export models to insel format
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Concordia CERC group
Project Coder Pilar Monsalvete Alvarez de Uribarri pilar.monsalvete@concordia.ca
"""
import os
from pathlib import Path
from abc import ABC
class Insel(ABC):
def __init__(self, path, name, new_content="", mode=1, keep_files=False):
self._path = path
self._name = name
self._full_path = None
self._content = None
self._results = None
self._keep_files = keep_files
self.add_content(new_content, mode)
self.save()
self.run()
def save(self):
with open(self.full_path, 'w') as insel_file:
insel_file.write(self.content)
return
@property
def full_path(self):
if self._full_path is None:
self._full_path = (Path(self._path) / 'tests/tmp' / self._name).resolve()
print(self._full_path)
return self._full_path
@property
def content(self):
if self._content is None:
if os.path.exists(self.full_path):
with open(self.full_path, 'r') as insel_file:
self._content = insel_file.read()
else:
self._content = ''
return self._content
@staticmethod
def add_block(file, block_number, block_type, inputs='', parameters=''):
file += "S " + str(block_number) + " " + block_type + "\n"
for block_input in inputs:
file += block_input + "\n"
if len(parameters) > 0:
file += "P " + str(block_number) + "\n"
for block_parameter in parameters:
file += block_parameter + "\n"
return file
def add_content(self, new_content, mode):
# mode = 1: keep old content
if mode == 1:
self._content = self.content + '\n' + new_content
# mode = 2: over-write
elif mode == 2:
self._content = new_content
else:
raise Exception('Add content mode not supported')
return
def run(self):
finish = os.system('insel ' + str(self.full_path))
os.close(finish)
if not self._keep_files:
os.remove(self.full_path)
def results(self, path):
raise NotImplementedError

View File

@ -0,0 +1,180 @@
import numpy as np
from pathlib import Path
import pandas as pd
import csv
from exports.insel.insel import Insel
from imports.weather.helpers.weather import Weather
import helpers.constants as cte
_CONSTRUCTION_CODE = {
cte.WALL: '1',
cte.GROUND: '2',
cte.ROOF: '3',
cte.INTERIOR_WALL: '5',
cte.GROUND_WALL: '6',
cte.ATTIC_FLOOR: '7',
cte.INTERIOR_SLAB: '8'
}
class MonthlyEnergyBalance(Insel):
def results(self, insel_outputs_path):
heating = []
cooling = []
with open(Path(insel_outputs_path).resolve()) as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
demand = str(line).replace("['", '').replace("']", '').split()
for i in range(0, 2):
if demand[i] != 'NaN':
aux = float(demand[i]) * 1000 # kWh to Wh
demand[i] = str(aux)
heating.append(demand[0])
cooling.append(demand[1])
monthly_heating = pd.DataFrame(heating, columns=['INSEL'])
monthly_cooling = pd.DataFrame(cooling, columns=['INSEL'])
return monthly_heating, monthly_cooling
@staticmethod
def generate_meb_template(building, insel_outputs_path, key):
file = ""
i_block = 1
parameters = ["1", "12", "1"]
file = Insel.add_block(file, i_block, 'DO', parameters=parameters)
i_block = 4
inputs = ["1.1", "20.1", "21.1"]
surfaces = building.surfaces
for i in range(1, len(surfaces) + 1):
inputs.append(f"{str(100 + i)}.1 % Radiation surface {str(i)}")
# BUILDING PARAMETERS
parameters = [f'{0.85 * building.volume} % BP(1) Heated Volume (vBrutto)',
f'{building.average_storey_height} % BP(2) Average storey height / m',
f'{building.storeys_above_ground} % BP(3) Number of storeys above ground',
f'{building.attic_heated} % BP(4) Attic heating type (0=no room, 1=unheated, 2=heated)',
f'{building.basement_heated} % BP(5) Cellar heating type (0=no room, 1=unheated, 2=heated, '
f'99=invalid)']
# todo: this method and the insel model have to be reviewed for more than one internal zone
internal_zone = building.internal_zones[0]
thermal_zone = internal_zone.thermal_zones[0]
parameters.append(f'{thermal_zone.indirectly_heated_area_ratio} % BP(6) Indirectly heated area ratio')
parameters.append(f'{thermal_zone.effective_thermal_capacity} % BP(7) Effective heat capacity')
parameters.append(f'{thermal_zone.additional_thermal_bridge_u_value * thermal_zone.floor_area} '
f'% BP(8) Additional U-value for heat bridge')
parameters.append('0 % BP(9) Usage type (0=standard, 1=IWU)')
# ZONES AND SURFACES
parameters.append(f'{len(internal_zone.usage_zones)} % BP(10) Number $z$ of zones')
for i, usage_zone in enumerate(internal_zone.usage_zones):
percentage_usage = usage_zone.percentage
parameters.append(f'{float(internal_zone.area) * percentage_usage} % BP(11) #1 Area of zone {i + 1} (sqm)')
total_internal_gain = 0
for ig in usage_zone.internal_gains:
total_internal_gain += float(ig.average_internal_gain) * \
(float(ig.convective_fraction) + float(ig.radiative_fraction))
parameters.append(f'{total_internal_gain} % BP(12) #2 Internal gains of zone {i + 1}')
parameters.append(f'{usage_zone.heating_setpoint} % BP(13) #3 Heating setpoint temperature '
f'zone {i + 1} (tSetHeat)')
parameters.append(f'{usage_zone.heating_setback} % BP(14) #4 Heating setback temperature '
f'zone {i + 1} (tSetbackHeat)')
parameters.append(f'{usage_zone.cooling_setpoint} % BP(15) #5 Cooling setpoint temperature '
f'zone {i + 1} (tSetCool)')
parameters.append(f'{usage_zone.hours_day} % BP(16) #6 Usage hours per day zone {i + 1}')
parameters.append(f'{usage_zone.days_year} % BP(17) #7 Usage days per year zone {i + 1}')
parameters.append(f'{usage_zone.mechanical_air_change} % BP(18) #8 Minimum air change rate zone {i + 1} (h^-1)')
parameters.append(f'{len(surfaces)} % Number of surfaces = BP(11+8z) \n'
f'% 1. Surface type (1=wall, 2=ground 3=roof, 4=flat roof)\n'
f'% 2. Areas above ground\n'
f'% 3. Areas below ground\n'
f'% 4. U-value\n'
f'% 5. Window area\n'
f'% 6. Window frame fraction\n'
f'% 7. Window U-value\n'
f'% 8. Window g-value\n'
f'% 9. Short-wave reflectance\n'
f'% #1 #2 #3 #4 #5 #6 #7 #8 #9\n')
for thermal_boundary in thermal_zone.thermal_boundaries:
type_code = _CONSTRUCTION_CODE[thermal_boundary.type]
window_area = thermal_boundary.opaque_area * thermal_boundary.window_ratio / (1 - thermal_boundary.window_ratio)
parameters.append(type_code)
parameters.append(0.85 * thermal_boundary.opaque_area)
parameters.append('0.0')
parameters.append(thermal_boundary.u_value)
parameters.append(0.85 * window_area)
if window_area <= 0.001:
parameters.append(0.0)
parameters.append(0.0)
parameters.append(0.0)
else:
thermal_opening = thermal_boundary.thermal_openings[0]
parameters.append(thermal_opening.frame_ratio)
parameters.append(thermal_opening.overall_u_value)
parameters.append(thermal_opening.g_value)
if thermal_boundary.parent_surface.short_wave_reflectance is not None:
parameters.append(thermal_boundary.shortwave_reflectance)
else:
parameters.append(0.0)
file = Insel.add_block(file, i_block, 'd18599', inputs=inputs, parameters=parameters)
i_block = 20
inputs = ['1']
parameters = ['12 % Monthly ambient temperature']
external_temperature = building.external_temperature[cte.MONTH]
for i in range(0, len(external_temperature)):
parameters.append(f'{i + 1} {external_temperature.at[i, key]}')
file = Insel.add_block(file, i_block, 'polyg', inputs=inputs, parameters=parameters)
i_block = 21
inputs = ['1']
parameters = ['12 % Monthly sky temperature']
sky_temperature = Weather.sky_temperature(external_temperature[[key]].to_numpy().T[0])
for i, temperature in enumerate(sky_temperature):
parameters.append(f'{i + 1} {temperature}')
file = Insel.add_block(file, i_block, 'polyg', inputs=inputs, parameters=parameters)
for i, surface in enumerate(surfaces):
i_block = 101 + i
inputs = ['1 % Monthly surface radiation (W/sqm)']
parameters = [f'12 % Azimuth {np.rad2deg(surface.azimuth)}, inclination {np.rad2deg(surface.inclination)} degrees']
if surface.type != 'Ground':
global_irradiance = surface.global_irradiance[cte.MONTH]
for j in range(0, len(global_irradiance)):
parameters.append(f'{j + 1} {global_irradiance.at[j, "sra"]}')
else:
for j in range(0, 12):
parameters.append(f'{j + 1} 0.0')
file = Insel.add_block(file, i_block, 'polyg', inputs=inputs, parameters=parameters)
i_block = 300
inputs = ['4.1', '4.2']
file = Insel.add_block(file, i_block, 'cum', inputs=inputs)
i_block = 303
inputs = ['300.1', '300.2']
file = Insel.add_block(file, i_block, 'atend', inputs=inputs)
i_block = 310
inputs = ['4.1', '4.2']
parameters = ['1 % Mode',
'0 % Suppress FNQ inputs',
f"'{str(insel_outputs_path)}' % File name",
"'*' % Fortran format"]
file = Insel.add_block(file, i_block, 'WRITE', inputs=inputs, parameters=parameters)
return file

View File