Clean up:

Some old not implemented classes have been removed
Some pep8 improvements done too
This commit is contained in:
Guille Gutierrez 2023-01-26 07:41:56 -05:00
parent 4e0b17d7ee
commit 1b47ea64b5
40 changed files with 67 additions and 696 deletions

View File

@ -6,8 +6,6 @@ Project Coder Sanam Dabirian sanam.dabirian@mail.concordia.ca
Code contributors: Pilar Monsalvete Alvarez de Uribarri pilar.monsalvete@concordia.ca Code contributors: Pilar Monsalvete Alvarez de Uribarri pilar.monsalvete@concordia.ca
""" """
import calendar as cal
class Occupant: class Occupant:
""" """

View File

@ -26,6 +26,7 @@ class ThermalZone:
""" """
ThermalZone class ThermalZone class
""" """
def __init__(self, thermal_boundaries, parent_internal_zone, volume, footprint_area, usage_name=None): def __init__(self, thermal_boundaries, parent_internal_zone, volume, footprint_area, usage_name=None):
self._id = None self._id = None
self._parent_internal_zone = parent_internal_zone self._parent_internal_zone = parent_internal_zone

View File

@ -26,7 +26,6 @@ class UsageZone:
self._internal_gains = None self._internal_gains = None
self._hours_day = None self._hours_day = None
self._days_year = None self._days_year = None
# self._electrical_app_average_consumption_sqm_year = None
self._mechanical_air_change = None self._mechanical_air_change = None
self._occupancy = None self._occupancy = None
self._lighting = None self._lighting = None

View File

@ -17,8 +17,8 @@ class BusSystem(CityObject):
""" """
BusSystem(CityObject) class BusSystem(CityObject) class
""" """
def __init__(self, name, surfaces, city_lower_corner): def __init__(self, name, surfaces):
super().__init__(name, surfaces, city_lower_corner) super().__init__(name, surfaces)
self._bus_routes = None self._bus_routes = None
self._bus_network = None self._bus_network = None
self._buses = None self._buses = None

View File

@ -224,5 +224,3 @@ class CityObject:
:param value: [Sensor] :param value: [Sensor]
""" """
self._sensors = value self._sensors = value

View File

@ -43,4 +43,3 @@ class Fuel:
:return: str :return: str
""" """
return self._unit return self._unit

View File

@ -26,7 +26,7 @@ class Station:
return self._id return self._id
@property @property
def _mobile(self): def mobile(self):
""" """
Get if the station is mobile or not Get if the station is mobile or not
:return: bool :return: bool

View File

@ -1,21 +0,0 @@
"""
LifeCycleAssessment retrieve the specific Life Cycle Assessment module for the given region
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Concordia CERC group
Project Coder Atiya atiya.atiya@mail.concordia.ca
"""
from hub.city_model_structure.machine import Machine
class LcaCalculations:
"""
LCA Calculations class
"""
def emission_disposal_machines(self, ):
return Machine.work_efficiency * Machine.energy_consumption_rate * Machine.carbon_emission_factor
def emission_transportation(self, weight, distance ):
return weight * distance * Machine.energy_consumption_rate * Machine.carbon_emission_factor

View File

@ -11,8 +11,8 @@ class Machine:
Machine class Machine class
""" """
def __init__(self, machine_id, name, work_efficiency, work_efficiency_unit, energy_consumption_rate, energy_consumption_unit, def __init__(self, machine_id, name, work_efficiency, work_efficiency_unit, energy_consumption_rate,
carbon_emission_factor, carbon_emission_unit): energy_consumption_unit, carbon_emission_factor, carbon_emission_unit):
self._machine_id = machine_id self._machine_id = machine_id
self._name = name self._name = name
self._work_efficiency = work_efficiency self._work_efficiency = work_efficiency
@ -85,4 +85,3 @@ class Machine:
:return: str :return: str
""" """
return self._carbon_emission_unit return self._carbon_emission_unit

View File

@ -18,7 +18,7 @@ class Network(CityObject):
Generic network class to be used as base for the network models Generic network class to be used as base for the network models
""" """
def __init__(self, name, edges=None, nodes=None): def __init__(self, name, edges=None, nodes=None):
super().__init__(name, 0, [], None) super().__init__(name, 0)
if nodes is None: if nodes is None:
nodes = [] nodes = []
if edges is None: if edges is None:

View File

@ -12,7 +12,7 @@ class SubwayEntrance(CityObject):
SubwayEntrance(CityObject) class SubwayEntrance(CityObject) class
""" """
def __init__(self, name, latitude, longitude): def __init__(self, name, latitude, longitude):
super().__init__(name, 0, []) super().__init__(name, 0)
self._name = name self._name = name
self._latitude = latitude self._latitude = latitude
self._longitude = longitude self._longitude = longitude

View File

@ -10,7 +10,8 @@ class Vehicle:
Vehicle class Vehicle class
""" """
def __init__(self, vehicle_id, name, fuel_consumption_rate, fuel_consumption_unit, carbon_emission_factor, carbon_emission_factor_unit): def __init__(self, vehicle_id, name, fuel_consumption_rate, fuel_consumption_unit, carbon_emission_factor,
carbon_emission_factor_unit):
self._vehicle_id = vehicle_id self._vehicle_id = vehicle_id
self._name = name self._name = name
self._fuel_consumption_rate = fuel_consumption_rate self._fuel_consumption_rate = fuel_consumption_rate
@ -59,10 +60,9 @@ class Vehicle:
return self._carbon_emission_factor return self._carbon_emission_factor
@property @property
def carbon_emission_unit(self) -> str: def carbon_emission_factor_unit(self) -> str:
""" """
Get carbon emission units Get carbon emission units
:return: str :return: str
""" """
return self._carbon_emission_unit return self._carbon_emission_factor_unit

View File

@ -313,7 +313,8 @@ class EnergyAde:
thermal_zones.append(thermal_zone_dic) thermal_zones.append(thermal_zone_dic)
return thermal_zones return thermal_zones
def _thermal_boundaries(self, city, thermal_zone): @staticmethod
def _thermal_boundaries(city, thermal_zone):
thermal_boundaries = [] thermal_boundaries = []
for thermal_boundary in thermal_zone.thermal_boundaries: for thermal_boundary in thermal_zone.thermal_boundaries:
thermal_boundary_dic = { thermal_boundary_dic = {
@ -364,7 +365,7 @@ class EnergyAde:
'@xlink:href': f'#GML_{construction[0]}' '@xlink:href': f'#GML_{construction[0]}'
} }
if thermal_boundary.thermal_openings is not None: if thermal_boundary.thermal_openings is not None:
for opening in thermal_boundary.thermal_openings: for _ in thermal_boundary.thermal_openings:
opening_construction.append(uuid.uuid4()) opening_construction.append(uuid.uuid4())
thermal_boundary_dic['energy:contains'] = { thermal_boundary_dic['energy:contains'] = {
'energy:ThermalOpening': { 'energy:ThermalOpening': {

View File

@ -252,5 +252,3 @@ class HeatPumpExport:
s = pd.Series(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec", "Total"]) s = pd.Series(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec", "Total"])
df = df.set_index([s]) df = df.set_index([s])
df.to_csv(self._output_path) df.to_csv(self._output_path)

View File

@ -27,4 +27,3 @@ class Insel(ABC):
def _export(self): def _export(self):
raise NotImplementedError raise NotImplementedError

View File

@ -26,7 +26,8 @@ class Obj(Triangular):
file_name_out = self._city.name + '_ground.' + self._triangular_format file_name_out = self._city.name + '_ground.' + self._triangular_format
file_path_in = (Path(self._path).resolve() / file_name_in).resolve() file_path_in = (Path(self._path).resolve() / file_name_in).resolve()
file_path_out = (Path(self._path).resolve() / file_name_out).resolve() file_path_out = (Path(self._path).resolve() / file_name_out).resolve()
scene = GeometryFactory('obj', path=file_path_in).scene obj = GeometryFactory('obj', path=file_path_in)
scene = obj.scene
scene.rezero() scene.rezero()
obj_file = trimesh.exchange.obj.export_obj(scene) obj_file = trimesh.exchange.obj.export_obj(scene)
with open(file_path_out, 'w') as file: with open(file_path_out, 'w') as file:

View File

@ -2,7 +2,8 @@
AirSourceHeatPumpParameters import the heat pump information AirSourceHeatPumpParameters import the heat pump information
SPDX - License - Identifier: LGPL - 3.0 - or -later SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Concordia CERC group Copyright © 2022 Concordia CERC group
Project Coder Peter Yefi peteryefi@gmail.comCode contributor Pilar Monsalvete Alvarez de Uribarri pilar.monsalvete@concordia.ca Project Coder Peter Yefi peteryefi@gmail.comCode
contributor Pilar Monsalvete Alvarez de Uribarri pilar.monsalvete@concordia.ca
""" """
import pandas as pd import pandas as pd
@ -69,8 +70,7 @@ class AirSourceHeatPumpParameters:
Enriches the city with information from file Enriches the city with information from file
""" """
heat_pump_data = self._read_file() heat_pump_data = self._read_file()
for (k_cool, v_cool), (k_heat, v_heat) in \ for (k_cool, v_cool), (k_heat, v_heat) in zip(heat_pump_data["cooling"].items(), heat_pump_data["heating"].items()):
zip(heat_pump_data["cooling"].items(), heat_pump_data["heating"].items()):
heat_pump = AirSourceHP() heat_pump = AirSourceHP()
heat_pump.model = k_cool heat_pump.model = k_cool
h_data = self._extract_heat_pump_data(v_heat) h_data = self._extract_heat_pump_data(v_heat)
@ -87,7 +87,8 @@ class AirSourceHeatPumpParameters:
self._city.add_city_object(energy_system) self._city.add_city_object(energy_system)
return self._city return self._city
def _extract_heat_pump_data(self, heat_pump_capacity_data: Dict) -> [List, List]: @staticmethod
def _extract_heat_pump_data(heat_pump_capacity_data: Dict) -> [List, List]:
""" """
Fetches a list of metric based data for heat pump for various temperature, Fetches a list of metric based data for heat pump for various temperature,
eg. cooling capacity data for 12 capacity heat pump eg. cooling capacity data for 12 capacity heat pump
@ -131,7 +132,8 @@ class AirSourceHeatPumpParameters:
popt, _ = curve_fit(self._objective_function, [x_values, out_temp], hp_data) popt, _ = curve_fit(self._objective_function, [x_values, out_temp], hp_data)
return popt.tolist() return popt.tolist()
def _objective_function(self, xdata: List, a1: float, a2: float, a3: float, a4: float, a5: float, a6: float) -> float: @staticmethod
def _objective_function(xdata: List, a1: float, a2: float, a3: float, a4: float, a5: float, a6: float) -> float:
""" """
Objective function for computing coefficients Objective function for computing coefficients
:param xdata: :param xdata:

View File

@ -71,7 +71,8 @@ class WaterToWaterHPParameters:
# range values for extracting data # range values for extracting data
return data return data
def _extract_hp_data(self, df, columns, ranges): @staticmethod
def _extract_hp_data(df, columns, ranges):
""" """
Extract variable specific (LWT, PD or TC) data from water to water hp Extract variable specific (LWT, PD or TC) data from water to water hp
:param df: the dataframe :param df: the dataframe
@ -88,7 +89,8 @@ class WaterToWaterHPParameters:
return data.dropna().values.tolist() return data.dropna().values.tolist()
def _extract_flow_and_ewt(self, df, ranges, columns, flow_rates): @staticmethod
def _extract_flow_and_ewt(df, ranges, columns, flow_rates):
""" """
Create the flow and ewt data based on the length of the various Create the flow and ewt data based on the length of the various
columns for the variables being extracted columns for the variables being extracted
@ -148,7 +150,8 @@ class WaterToWaterHPParameters:
demand) demand)
return popt.tolist() return popt.tolist()
def _objective_function(self, xdata: List, a1: float, a2: float, a3: float, a4: float, a5: float, a6: float, @staticmethod
def _objective_function(xdata: List, a1: float, a2: float, a3: float, a4: float, a5: float, a6: float,
a7: float, a8: float, a9: float, a10: float, a11: float) -> float: a7: float, a8: float, a9: float, a10: float, a11: float) -> float:
""" """
Objective function for computing coefficients Objective function for computing coefficients
@ -169,4 +172,3 @@ class WaterToWaterHPParameters:
x, y, t = xdata x, y, t = xdata
return (a1 * x ** 2) + (a2 * x) + (a3 * y ** 2) + (a4 * y) + (a5 * t ** 2) + (a6 * t) + (a7 * x * y) + ( return (a1 * x ** 2) + (a2 * x) + (a3 * y ** 2) + (a4 * y) + (a5 * t ** 2) + (a6 * t) + (a7 * x * y) + (
a8 * x * t) + (a9 * y * t) + (a10 * x * y * t) + a11 a8 * x * t) + (a9 * y * t) + (a10 * x * y * t) + a11

View File

@ -7,12 +7,12 @@ Project Coder Guille Gutierrez guillermo.gutierrezmorote@concordia.ca
import numpy as np import numpy as np
import xmltodict import xmltodict
from hub.city_model_structure.city import City
from hub.city_model_structure.building import Building from hub.city_model_structure.building import Building
from hub.city_model_structure.city import City
from hub.city_model_structure.parts_consisting_building import PartsConsistingBuilding from hub.city_model_structure.parts_consisting_building import PartsConsistingBuilding
from hub.helpers.geometry_helper import GeometryHelper
from hub.imports.geometry.citygml_classes.citygml_lod2 import CityGmlLod2
from hub.imports.geometry.citygml_classes.citygml_lod1 import CityGmlLod1 from hub.imports.geometry.citygml_classes.citygml_lod1 import CityGmlLod1
from hub.imports.geometry.citygml_classes.citygml_lod2 import CityGmlLod2
class CityGml: class CityGml:
@ -26,7 +26,7 @@ class CityGml:
self._lod2_tags = ['lod2Solid', 'lod2MultiSurface', 'lod2MultiCurve'] self._lod2_tags = ['lod2Solid', 'lod2MultiSurface', 'lod2MultiCurve']
self._extrusion_height_field = extrusion_height_field self._extrusion_height_field = extrusion_height_field
self._year_of_construction_field = year_of_construction_field self._year_of_construction_field = year_of_construction_field
if function_field == None: if function_field is None:
function_field = 'function' function_field = 'function'
self._function_field = function_field self._function_field = function_field

View File

@ -57,6 +57,7 @@ class GPandas:
""" """
if self._city is None: if self._city is None:
self._city = City(self._lower_corner, self._upper_corner, self._srs_name) self._city = City(self._lower_corner, self._upper_corner, self._srs_name)
lod = 0
for scene_index, bldg in self._scene.iterrows(): for scene_index, bldg in self._scene.iterrows():
polygon = bldg.geometry polygon = bldg.geometry
height = float(bldg['height']) height = float(bldg['height'])

View File

@ -51,6 +51,7 @@ class Obj:
""" """
Get city out of an obj file Get city out of an obj file
""" """
lod = 0
if self._city is None: if self._city is None:
# todo: refactor this method to clearly choose the obj type # todo: refactor this method to clearly choose the obj type
# todo: where do we get this information from? # todo: where do we get this information from?

View File

@ -8,6 +8,7 @@ import xmltodict
from pathlib import Path from pathlib import Path
from hub.city_model_structure.machine import Machine from hub.city_model_structure.machine import Machine
class LcaMachine: class LcaMachine:
def __init__(self, city, base_path): def __init__(self, city, base_path):
self._city = city self._city = city
@ -22,6 +23,8 @@ class LcaMachine:
self._lca = xmltodict.parse(xml.read()) self._lca = xmltodict.parse(xml.read())
for machine in self._lca["library"]["machines"]['machine']: for machine in self._lca["library"]["machines"]['machine']:
self._city.machines.append(Machine(machine['@id'], machine['@name'], machine['work_efficiency']['#text'], self._city.machines.append(Machine(machine['@id'], machine['@name'], machine['work_efficiency']['#text'],
machine['work_efficiency']['@unit'], machine['energy_consumption_rate']['#text'], machine['work_efficiency']['@unit'],
machine['energy_consumption_rate']['@unit'], machine['carbon_emission_factor']['#text'], machine['energy_consumption_rate']['#text'],
machine['energy_consumption_rate']['@unit'],
machine['carbon_emission_factor']['#text'],
machine['carbon_emission_factor']['@unit'])) machine['carbon_emission_factor']['@unit']))

View File

@ -8,6 +8,7 @@ import xmltodict
from pathlib import Path from pathlib import Path
from hub.city_model_structure.lca_material import LcaMaterial as LMaterial from hub.city_model_structure.lca_material import LcaMaterial as LMaterial
class LcaMaterial: class LcaMaterial:
def __init__(self, city, base_path): def __init__(self, city, base_path):
self._city = city self._city = city

View File

@ -26,4 +26,3 @@ class LcaVehicle:
vehicle['fuel_consumption_rate']['@unit'], vehicle['fuel_consumption_rate']['@unit'],
vehicle['carbon_emission_factor']['#text'], vehicle['carbon_emission_factor']['#text'],
vehicle['carbon_emission_factor']['@unit'])) vehicle['carbon_emission_factor']['@unit']))

View File

@ -16,7 +16,7 @@ from hub.hub_logger import logger
class LifeCycleAssessment: class LifeCycleAssessment:
""" """
Life cicle analize factory class Life cycle assessment factory class
""" """
def __init__(self, handler, city, base_path=None): def __init__(self, handler, city, base_path=None):
if base_path is None: if base_path is None:

View File

@ -1,37 +0,0 @@
"""
Concordia gas flow
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 pandas as pd
from hub.imports.sensors.concordia_file_report import ConcordiaFileReport
from city_model_structure.iot.concordia_gas_flow_sensor import ConcordiaGasFlowSensor
class ConcordiaGasFlow(ConcordiaFileReport):
"""
Concordia gas flow sensor class
"""
def __init__(self, city, end_point, base_path):
super().__init__(city, end_point, base_path, 'concordia_gas_flow_db.json')
for city_object in city.city_objects:
self._assign_sensor_to_object(city_object)
def _assign_sensor_to_object(self, obj):
for i in range(len(self._city_object)):
if self._city_object[i] == obj.name and self._sensors[i] in self._sensor_point:
building_measures = [self._measures["Date time"], self._measures[self._sensor_point[self._sensors[i]]]]
building_headers = ["Date time", "Gas Flow Cumulative Monthly"]
building_energy_consumption = pd.concat(building_measures, keys=building_headers, axis=1)
sensor = ConcordiaGasFlowSensor(self._sensors[i])
sensor_exist = False
for j in range(len(obj.sensors)):
if obj.sensors[j].name is sensor.name:
obj.sensors[j].add_period(building_energy_consumption)
sensor_exist = True
break
if not sensor_exist:
sensor.add_period(building_energy_consumption)
obj.sensors.append(sensor)

View File

@ -1,36 +0,0 @@
"""
Concordia temperature
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 pandas as pd
from hub.imports.sensors.concordia_file_report import ConcordiaFileReport
from city_model_structure.iot.concordia_temperature_sensor import ConcordiaTemperatureSensor
class ConcordiaTemperature(ConcordiaFileReport):
"""
Concordia temperature sensor class
"""
def __init__(self, city, end_point, base_path):
super().__init__(city, end_point, base_path, 'concordia_temperature_db.json')
for city_object in city.city_objects:
self._assign_sensor_to_object(city_object)
def _assign_sensor_to_object(self, obj):
for i in range(len(self._city_object)):
if self._city_object[i] == obj.name and self._sensors[i] in self._sensor_point:
building_measures = [self._measures["Date time"], self._measures[self._sensor_point[self._sensors[i]]]]
building_headers = ["Date time", "Temperature"]
building_energy_consumption = pd.concat(building_measures, keys=building_headers, axis=1)
sensor = ConcordiaTemperatureSensor(self._sensors[i])
sensor_exist = False
for j in range(len(obj.sensors)):
if obj.sensors[j].name is sensor.name:
obj.sensors[j].add_period(building_energy_consumption)
sensor_exist = True
break
if not sensor_exist:
sensor.add_period(building_energy_consumption)
obj.sensors.append(sensor)

View File

@ -1,40 +0,0 @@
"""
CaUsageParameters model the usage properties
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 sys
from hub.imports.geometry.helpers.geometry_helper import GeometryHelper
from hub.imports.usage.hft_usage_interface import HftUsageInterface
class HftUsageParameters(HftUsageInterface):
"""
CaUsageParameters class
"""
def __init__(self, city, base_path):
super().__init__(base_path, 'ca_archetypes_reduced.xml')
self._city = city
def enrich_buildings(self):
"""
Returns the city with the usage parameters assigned to the buildings
:return:
"""
city = self._city
for building in city.buildings:
usage = GeometryHelper().libs_usage_from_libs_function(building.function)
try:
archetype = self._search_archetype(usage)
except KeyError:
sys.stderr.write(f'Building {building.name} has unknown archetype for building function:'
f' {building.function}, that assigns building usage as '
f'{GeometryHelper().libs_usage_from_libs_function(building.function)}\n')
return
for internal_zone in building.internal_zones:
usage_zone = self._assign_values(building.function, archetype)
usage_zone.percentage = 1
internal_zone.usage_zones = [usage_zone]

View File

@ -1,67 +0,0 @@
"""
HftInternalGainsArchetype stores internal gains information, complementing the HftUsageZoneArchetype class
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Concordia CERC group
Project Coder Pilar Monsalvete Alvarez de Uribarri pilar.monsalvete@concordia.ca
"""
class HftInternalGainsArchetype:
"""
HftInternalGainsArchetype class
"""
def __init__(self, internal_gains_type=None, average_internal_gain=None, convective_fraction=None, \
radiative_fraction=None, latent_fraction=None):
self._type = internal_gains_type
self._average_internal_gain = average_internal_gain
self._convective_fraction = convective_fraction
self._radiative_fraction = radiative_fraction
self._latent_fraction = latent_fraction
@property
def type(self):
"""
Get internal gains type
:return: string
"""
return self._type
@type.setter
def type(self, value):
"""
Set internal gains type
:param value: string
"""
self._type = value
@property
def average_internal_gain(self):
"""
Get internal gains average internal gain in W/m2
:return: float
"""
return self._average_internal_gain
@property
def convective_fraction(self):
"""
Get internal gains convective fraction
:return: float
"""
return self._convective_fraction
@property
def radiative_fraction(self):
"""
Get internal gains radiative fraction
:return: float
"""
return self._radiative_fraction
@property
def latent_fraction(self):
"""
Get internal gains latent fraction
:return: float
"""
return self._latent_fraction

View File

@ -1,99 +0,0 @@
"""
UsageZoneArchetype stores usage information by usage type
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Concordia CERC group
Project Coder Pilar Monsalvete Alvarez de Uribarri pilar.monsalvete@concordia.ca
"""
from typing import List
from hub.imports.usage.data_classes.hft_internal_gains_archetype import HftInternalGainsArchetype
class UsageZoneArchetype:
"""
UsageZoneArchetype class
"""
def __init__(self, usage=None, internal_gains=None, hours_day=None, days_year=None,
electrical_app_average_consumption_sqm_year=None, mechanical_air_change=None, occupancy=None,
lighting=None, appliances=None):
self._usage = usage
self._internal_gains = internal_gains
self._hours_day = hours_day
self._days_year = days_year
self._electrical_app_average_consumption_sqm_year = electrical_app_average_consumption_sqm_year
self._mechanical_air_change = mechanical_air_change
self._occupancy = occupancy
self._lighting = lighting
self._appliances = appliances
@property
def internal_gains(self) -> List[HftInternalGainsArchetype]:
"""
Get usage zone internal gains from not detailed heating source in W/m2
:return: [InternalGain]
"""
return self._internal_gains
@property
def hours_day(self):
"""
Get usage zone usage hours per day
:return: float
"""
return self._hours_day
@property
def days_year(self):
"""
Get usage zone usage days per year
:return: float
"""
return self._days_year
@property
def mechanical_air_change(self):
"""
Set usage zone mechanical air change in air change per hour (ACH)
:return: float
"""
return self._mechanical_air_change
@property
def usage(self):
"""
Get usage zone usage
:return: str
"""
return self._usage
@property
def electrical_app_average_consumption_sqm_year(self):
"""
Get average consumption of electrical appliances in Joules per m2 and year (J/m2yr)
:return: float
"""
return self._electrical_app_average_consumption_sqm_year
@property
def occupancy(self):
"""
Get occupancy data
:return: Occupancy
"""
return self._occupancy
@property
def lighting(self):
"""
Get lighting data
:return: Lighting
"""
return self._lighting
@property
def appliances(self):
"""
Get appliances data
:return: Appliances
"""
return self._appliances

View File

@ -1,280 +0,0 @@
"""
Hft-based interface, it reads format defined within the CERC team (based on that one used in SimStadt and developed by
the IAF team at hft-Stuttgart)
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 xmltodict
import copy
from hub.city_model_structure.building_demand.usage_zone import UsageZone
from hub.city_model_structure.building_demand.internal_gain import InternalGain
from hub.city_model_structure.building_demand.occupancy import Occupancy
from hub.city_model_structure.building_demand.appliances import Appliances
from hub.city_model_structure.building_demand.thermal_control import ThermalControl
from hub.city_model_structure.attributes.schedule import Schedule
import hub.helpers.constants as cte
from hub.imports.usage.helpers.usage_helper import UsageHelper
class HftUsageInterface:
"""
HftUsageInterface abstract class
"""
def __init__(self, base_path, usage_file='ca_library_reduced.xml'):
path = str(base_path / usage_file)
self._usage_archetypes = []
with open(path) as xml:
self._archetypes = xmltodict.parse(xml.read(), force_list=('zoneUsageVariant', 'zoneUsageType'))
for zone_usage_type in self._archetypes['buildingUsageLibrary']['zoneUsageType']:
usage = zone_usage_type['id']
usage_archetype = self._parse_zone_usage_type(usage, zone_usage_type)
self._usage_archetypes.append(usage_archetype)
if 'zoneUsageVariant' in zone_usage_type:
for usage_zone_variant in zone_usage_type['zoneUsageVariant']:
usage = usage_zone_variant['id']
usage_archetype_variant = self._parse_zone_usage_variant(usage, usage_archetype, usage_zone_variant)
self._usage_archetypes.append(usage_archetype_variant)
@staticmethod
def _parse_zone_usage_type(usage, zone_usage_type):
usage_zone_archetype = UsageZone()
usage_zone_archetype.usage = usage
if 'occupancy' in zone_usage_type:
_occupancy = Occupancy()
_occupancy.occupancy_density = zone_usage_type['occupancy']['occupancyDensity'] #todo: check units
if 'internGains' in zone_usage_type['occupancy']:
_internal_gain = InternalGain()
_internal_gain.latent_fraction = zone_usage_type['occupancy']['internGains']['latentFraction']
_internal_gain.convective_fraction = zone_usage_type['occupancy']['internGains']['convectiveFraction']
_internal_gain.average_internal_gain = zone_usage_type['occupancy']['internGains']['averageInternGainPerSqm']
_internal_gain.radiative_fraction = zone_usage_type['occupancy']['internGains']['radiantFraction']
if 'load' in zone_usage_type['occupancy']['internGains']:
_schedule = Schedule()
_schedule.type = 'internal gains load'
_schedule.time_range = cte.DAY
_schedule.time_step = cte.HOUR
_schedule.data_type = cte.ANY_NUMBER
_schedule.day_types = [cte.MONDAY, cte.TUESDAY, cte.WEDNESDAY, cte.THURSDAY, cte.FRIDAY, cte.SATURDAY,
cte.SUNDAY]
_values = zone_usage_type['occupancy']['internGains']['load']['weekDayProfile']['values']
while ' ' in _values:
_values = _values.replace(' ', ' ')
_values = _values.split()
_values_float = []
for _value in _values:
_values_float.append(float(_value))
_schedule.values = _values_float
_internal_gain.schedules = [_schedule]
usage_zone_archetype.internal_gains = [_internal_gain]
usage_zone_archetype.hours_day = zone_usage_type['occupancy']['usageHoursPerDay']
usage_zone_archetype.days_year = zone_usage_type['occupancy']['usageDaysPerYear']
usage_zone_archetype.occupancy = _occupancy
if 'endUses' in zone_usage_type:
_thermal_control = ThermalControl()
if 'space_heating' in zone_usage_type['endUses']:
_thermal_control.mean_heating_set_point = \
zone_usage_type['endUses']['space_heating']['heatingSetPointTemperature']
_thermal_control.heating_set_back = zone_usage_type['endUses']['space_heating']['heatingSetBackTemperature']
if 'schedule' in zone_usage_type['endUses']['space_heating']:
_schedule = Schedule()
_schedule.type = 'heating temperature'
_schedule.time_range = cte.DAY
_schedule.time_step = cte.HOUR
_schedule.data_type = cte.ANY_NUMBER
_schedule.day_types = [cte.MONDAY, cte.TUESDAY, cte.WEDNESDAY, cte.THURSDAY, cte.FRIDAY, cte.SATURDAY,
cte.SUNDAY]
_values = zone_usage_type['endUses']['space_heating']['schedule']['weekDayProfile']['values']
while ' ' in _values:
_values = _values.replace(' ', ' ')
_values = _values.split()
_values_float = []
for _value in _values:
_values_float.append(float(_value))
_schedule.values = _values_float
_thermal_control.heating_set_point_schedules = [_schedule]
if 'space_cooling' in zone_usage_type['endUses']:
_thermal_control.mean_cooling_set_point = \
zone_usage_type['endUses']['space_cooling']['coolingSetPointTemperature']
if 'schedule' in zone_usage_type['endUses']['space_cooling']:
_schedule = Schedule()
_schedule.type = 'cooling temperature'
_schedule.time_range = cte.DAY
_schedule.time_step = cte.HOUR
_schedule.data_type = cte.ANY_NUMBER
_schedule.day_types = [cte.MONDAY, cte.TUESDAY, cte.WEDNESDAY, cte.THURSDAY, cte.FRIDAY, cte.SATURDAY,
cte.SUNDAY]
_values = zone_usage_type['endUses']['space_cooling']['schedule']['weekDayProfile']['values']
while ' ' in _values:
_values = _values.replace(' ', ' ')
_values = _values.split()
_values_float = []
for _value in _values:
_values_float.append(float(_value))
_schedule.values = _values_float
_thermal_control.cooling_set_point_schedules = [_schedule]
usage_zone_archetype.thermal_control = _thermal_control
if 'ventilation' in zone_usage_type['endUses'] and zone_usage_type['endUses']['ventilation'] is not None:
usage_zone_archetype.mechanical_air_change = \
zone_usage_type['endUses']['ventilation']['mechanicalAirChangeRate']
# todo: not used or assigned anywhere
if 'domestic_hot_water' in zone_usage_type['endUses']:
# liters to cubic meters
dhw_average_volume_pers_day = float(
zone_usage_type['endUses']['domestic_hot_water']['averageVolumePerPersAndDay']) / 1000
dhw_preparation_temperature = zone_usage_type['endUses']['domestic_hot_water']['preparationTemperature']
if 'all_electrical_appliances' in zone_usage_type['endUses']:
if 'averageConsumptionPerSqmAndYear' in zone_usage_type['endUses']['all_electrical_appliances']:
# kWh to J
usage_zone_archetype.electrical_app_average_consumption_sqm_year = \
float(zone_usage_type['endUses']['all_electrical_appliances']['averageConsumptionPerSqmAndYear']) \
* cte.KILO_WATTS_HOUR_TO_JULES
if 'appliance' in zone_usage_type:
_appliances = Appliances()
_appliances.density = zone_usage_type['appliance']['#text'] #todo: check units
usage_zone_archetype.appliances = _appliances
return usage_zone_archetype
@staticmethod
def _parse_zone_usage_variant(usage, usage_zone, usage_zone_variant):
# the variants mimic the inheritance concept from OOP
usage_zone_archetype = copy.deepcopy(usage_zone)
usage_zone_archetype.usage = usage
if 'occupancy' in usage_zone_variant:
_occupancy = Occupancy()
if 'occupancyDensity' in usage_zone_variant['occupancy']:
_occupancy.occupancy_density = usage_zone_variant['occupancy']['occupancyDensity'] # todo: check units
if 'usageHoursPerDay' in usage_zone_variant['occupancy']:
usage_zone_archetype.hours_day = usage_zone_variant['occupancy']['usageHoursPerDay']
if 'usageDaysPerYear' in usage_zone_variant['occupancy']:
usage_zone_archetype.days_year = usage_zone_variant['occupancy']['usageDaysPerYear']
usage_zone_archetype.occupancy = _occupancy
if 'internGains' in usage_zone_variant['occupancy']:
_internal_gain = InternalGain()
if 'latentFraction' in usage_zone_variant['occupancy']['internGains']:
_internal_gain.latent_fraction = usage_zone_variant['occupancy']['internGains']['latentFraction']
if 'convectiveFraction' in usage_zone_variant['occupancy']['internGains']:
_internal_gain.convective_fraction = usage_zone_variant['occupancy']['internGains']['convectiveFraction']
if 'averageInternGainPerSqm' in usage_zone_variant['occupancy']['internGains']:
_internal_gain.average_internal_gain = \
usage_zone_variant['occupancy']['internGains']['averageInternGainPerSqm']
if 'radiantFraction' in usage_zone_variant['occupancy']['internGains']:
_internal_gain.radiative_fraction = usage_zone_variant['occupancy']['internGains']['radiantFraction']
if 'load' in usage_zone_variant['occupancy']['internGains']:
_schedule = Schedule()
_schedule.type = 'internal gains load'
_schedule.time_range = cte.DAY
_schedule.time_step = cte.HOUR
_schedule.data_type = cte.ANY_NUMBER
_schedule.day_types = [cte.MONDAY, cte.TUESDAY, cte.WEDNESDAY, cte.THURSDAY, cte.FRIDAY, cte.SATURDAY,
cte.SUNDAY]
_values = usage_zone_variant['occupancy']['internGains']['load']['weekDayProfile']['values']
while ' ' in _values:
_values = _values.replace(' ', ' ')
_values = _values.split()
_values_float = []
for _value in _values:
_values_float.append(float(_value))
_schedule.values = _values_float
_internal_gain.schedules = [_schedule]
usage_zone_archetype.internal_gains = [_internal_gain]
if 'endUses' in usage_zone_variant:
_thermal_control = ThermalControl()
if 'space_heating' in usage_zone_variant['endUses']:
if 'heatingSetPointTemperature' in usage_zone_variant['endUses']['space_heating']:
_thermal_control.mean_heating_set_point = \
usage_zone_variant['endUses']['space_heating']['heatingSetPointTemperature']
if 'heatingSetBackTemperature' in usage_zone_variant['endUses']['space_heating']:
_thermal_control.heating_set_back = usage_zone_variant['endUses']['space_heating']['heatingSetBackTemperature']
if 'schedule' in usage_zone_variant['endUses']['space_heating']:
_schedule = Schedule()
_schedule.type = 'heating temperature'
_schedule.time_range = cte.DAY
_schedule.time_step = cte.HOUR
_schedule.data_type = cte.ANY_NUMBER
_schedule.day_types = [cte.MONDAY, cte.TUESDAY, cte.WEDNESDAY, cte.THURSDAY, cte.FRIDAY, cte.SATURDAY,
cte.SUNDAY]
_values = usage_zone_variant['endUses']['space_heating']['schedule']['weekDayProfile']['values']
while ' ' in _values:
_values = _values.replace(' ', ' ')
_values = _values.split()
_values_float = []
for _value in _values:
_values_float.append(float(_value))
_schedule.values = _values_float
_thermal_control.heating_set_point_schedules = [_schedule]
if 'space_cooling' in usage_zone_variant['endUses'] and \
usage_zone_variant['endUses']['space_cooling'] is not None:
if 'coolingSetPointTemperature' in usage_zone_variant['endUses']['space_cooling']:
_thermal_control.mean_cooling_set_point = \
usage_zone_variant['endUses']['space_cooling']['coolingSetPointTemperature']
if 'schedule' in usage_zone_variant['endUses']['space_cooling']:
_schedule = Schedule()
_schedule.type = 'cooling temperature'
_schedule.time_range = cte.DAY
_schedule.time_step = cte.HOUR
_schedule.data_type = cte.ANY_NUMBER
_schedule.day_types = [cte.MONDAY, cte.TUESDAY, cte.WEDNESDAY, cte.THURSDAY, cte.FRIDAY, cte.SATURDAY,
cte.SUNDAY]
_values = usage_zone_variant['endUses']['space_cooling']['schedule']['weekDayProfile']['values']
while ' ' in _values:
_values = _values.replace(' ', ' ')
_values = _values.split()
_values_float = []
for _value in _values:
_values_float.append(float(_value))
_schedule.values = _values_float
_thermal_control.cooling_set_point_schedules = [_schedule]
usage_zone_archetype.thermal_control = _thermal_control
if 'ventilation' in usage_zone_variant['endUses'] and usage_zone_variant['endUses']['ventilation'] is not None:
usage_zone_archetype.mechanical_air_change = \
usage_zone_variant['endUses']['ventilation']['mechanicalAirChangeRate']
if 'appliance' in usage_zone_variant:
_appliances = Appliances()
_appliances.density = usage_zone_variant['appliance']['#text'] # todo: check units
usage_zone_archetype.appliances = _appliances
return usage_zone_archetype
def _search_archetype(self, libs_usage):
building_usage = UsageHelper().hft_from_libs_usage(libs_usage)
for building_archetype in self._usage_archetypes:
if building_archetype.usage == building_usage:
return building_archetype
return None
@staticmethod
def _assign_values(usage, archetype):
usage_zone = UsageZone()
usage_zone.usage = usage
usage_zone.internal_gains = copy.deepcopy(archetype.internal_gains)
usage_zone.mechanical_air_change = archetype.mechanical_air_change
usage_zone.occupancy = copy.deepcopy(archetype.occupancy)
usage_zone.appliances = copy.deepcopy(archetype.appliances)
usage_zone.thermal_control = copy.deepcopy(archetype.thermal_control)
usage_zone.days_year = archetype.days_year
usage_zone.hours_day = archetype.hours_day
return usage_zone

View File

@ -1,42 +0,0 @@
"""
HftUsageParameters model the usage properties
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 sys
from hub.imports.geometry.helpers.geometry_helper import GeometryHelper
from hub.imports.usage.hft_usage_interface import HftUsageInterface
from hub.imports.usage.helpers.usage_helper import UsageHelper
class HftUsageParameters(HftUsageInterface):
"""
HftUsageParameters class
"""
def __init__(self, city, base_path):
super().__init__(base_path, 'de_library.xml')
self._city = city
def enrich_buildings(self):
"""
Returns the city with the usage parameters assigned to the buildings
:return:
"""
city = self._city
for building in city.buildings:
usage = GeometryHelper().libs_usage_from_libs_function(building.function)
try:
archetype = self._search_archetype(usage)
except KeyError:
sys.stderr.write(f'Building {building.name} has unknown archetype for building function:'
f' {building.function}, that assigns building usage as '
f'{GeometryHelper().libs_usage_from_libs_function(building.function)}\n')
return
for internal_zone in building.internal_zones:
libs_usage = GeometryHelper().libs_usage_from_libs_function(building.function)
usage_zone = self._assign_values(UsageHelper().hft_from_libs_usage(libs_usage), archetype)
usage_zone.percentage = 1
internal_zone.usage_zones = [usage_zone]

View File

@ -28,7 +28,7 @@ class EpwWeatherParameters:
city.longitude = line[7] city.longitude = line[7]
city.time_zone = line[8] city.time_zone = line[8]
for i in range(0, 2): for i in range(0, 2):
line = file.readline().split(',') _ = file.readline().split(',')
line = file.readline().split(',') line = file.readline().split(',')
number_records = int(line[1]) number_records = int(line[1])
depth_measurement_ground_temperature = [] depth_measurement_ground_temperature = []

View File

@ -19,9 +19,3 @@ class BaseRepo:
self.session = Session(self.engine) self.session = Session(self.engine)
except ValueError as err: except ValueError as err:
print(f'Missing value for credentials: {err}') print(f'Missing value for credentials: {err}')

View File

@ -23,7 +23,8 @@ class DBSetup:
self._user_repo = UserRepo(db_name=db_name, app_env=app_env, dotenv_path=dotenv_path) self._user_repo = UserRepo(db_name=db_name, app_env=app_env, dotenv_path=dotenv_path)
self._create_admin_user(self._user_repo) self._create_admin_user(self._user_repo)
def _create_admin_user(self, user_repo): @staticmethod
def _create_admin_user(user_repo):
email = 'admin@hub.com' email = 'admin@hub.com'
password = 'HubAdmin#!98' password = 'HubAdmin#!98'
print('Creating default admin user...') print('Creating default admin user...')

View File

@ -46,5 +46,3 @@ class City(Base):
u_corner = u_corner.tolist() if type(u_corner) == np.ndarray else u_corner u_corner = u_corner.tolist() if type(u_corner) == np.ndarray else u_corner
self.lower_corner = l_corner self.lower_corner = l_corner
self.upper_corner = u_corner self.upper_corner = u_corner

View File

@ -81,6 +81,3 @@ class HeatPumpSimulation(Base):
self.monthly_electricity_demand = monthly_elec_demand self.monthly_electricity_demand = monthly_elec_demand
self.daily_fossil_fuel_consumption = daily_fossil self.daily_fossil_fuel_consumption = daily_fossil
self.monthly_fossil_fuel_consumption = monthly_fossil self.monthly_fossil_fuel_consumption = monthly_fossil

View File

@ -41,7 +41,7 @@ class UserRepo(BaseRepo):
self.session.commit() self.session.commit()
return user return user
except SQLAlchemyError as err: except SQLAlchemyError as err:
logger.error(f'An error occured while creating user: {err}') logger.error(f'An error occurred while creating user: {err}')
else: else:
return {'message': f'user with {email} email already exists'} return {'message': f'user with {email} email already exists'}
@ -63,7 +63,7 @@ class UserRepo(BaseRepo):
self.session.commit() self.session.commit()
except SQLAlchemyError as err: except SQLAlchemyError as err:
logger.error(f'Error while updating user: {err}') logger.error(f'Error while updating user: {err}')
return {'err_msg': 'Error occured while updated user'} return {'err_msg': 'Error occurred while updated user'}
def get_by_email(self, email: str) -> [User]: def get_by_email(self, email: str) -> [User]:
""" """

View File

@ -22,3 +22,4 @@ bcrypt==4.0.1
shapely shapely
geopandas geopandas
triangle triangle