Skip to content

Commit

Permalink
fix(formatting): minor modifications
Browse files Browse the repository at this point in the history
- Update formatting and typing on modules
- Add new tests
- fix bug in site with legacy HBJSON deserialization
  • Loading branch information
ed-p-may committed May 6, 2023
1 parent 4e2e495 commit 389e7b0
Show file tree
Hide file tree
Showing 12 changed files with 200 additions and 92 deletions.
24 changes: 11 additions & 13 deletions honeybee_energy_ph/properties/hvac/allair.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
class AllAirSystemPhProperties_FromDictError(Exception):
def __init__(self, _expected_types, _input_type):
self.msg = 'Error: Expected type of "{}". Got: {}'.format(
_expected_types, _input_type)
_expected_types, _input_type
)
super(AllAirSystemPhProperties_FromDictError, self).__init__(self.msg)


Expand All @@ -31,28 +32,25 @@ def to_dict(self, abridged=False):
# type: (bool) -> dict[str, dict]
d = {}
if abridged:
d['type'] = 'AllAirSystemPhPropertiesAbridged'
d["type"] = "AllAirSystemPhPropertiesAbridged"
else:
d['type'] = 'AllAirSystemPhProperties'
d["type"] = "AllAirSystemPhProperties"

d['id_num'] = self.id_num
return {'ph': d}
d["id_num"] = self.id_num
return {"ph": d}

@classmethod
def from_dict(cls, _input_dict, host):
# type: (dict, Any) -> AllAirSystemPhProperties
valid_types = ('AllAirSystemPhProperties',
'AllAirSystemPhPropertiesAbridged')
if _input_dict['type'] not in valid_types:
raise AllAirSystemPhProperties_FromDictError(
valid_types, _input_dict['type'])
valid_types = ("AllAirSystemPhProperties", "AllAirSystemPhPropertiesAbridged")
if _input_dict["type"] not in valid_types:
raise AllAirSystemPhProperties_FromDictError(valid_types, _input_dict["type"])

new_prop = cls(host)
new_prop.id_num = _input_dict['id_num']
new_prop.id_num = _input_dict["id_num"]
return new_prop

def apply_properties_from_dict(self, abridged_data):

return

def ToString(self):
Expand All @@ -61,4 +59,4 @@ def ToString(self):

def __repr__(self):
"""Properties representation."""
return '{}'.format(self.__class__.__name__)
return "{}".format(self.__class__.__name__)
10 changes: 9 additions & 1 deletion honeybee_energy_ph/properties/hvac/idealair.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@
except:
pass # IronPython

from honeybee_energy_ph.hvac import ventilation, heating, cooling
try:
from honeybee_energy_ph.hvac import ventilation, heating, cooling
except ImportError as e:
raise ImportError("\nFailed to import honeybee_energy_ph:\n\t{}".format(e))

try:
from ladybug_geometry.geometry3d.pointvector import Point3D
except ImportError as e:
raise ImportError("\nFailed to import ladybug_geometry:\n\t{}".format(e))


class IdealAirSystemPhProperties_FromDictError(Exception):
Expand Down
94 changes: 55 additions & 39 deletions honeybee_ph/properties/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,27 @@
except ImportError:
pass # Python3

try:
from ladybug_geometry.geometry3d.pointvector import Point3D
except ImportError as e:
raise ImportError("\nFailed to import ladybug_geometry:\n\t{}".format(e))

try:
from honeybee import extensionutil
except ImportError as e:
raise ImportError('\nFailed to import honeybee:\n\t{}'.format(e))
raise ImportError("\nFailed to import honeybee:\n\t{}".format(e))
try:
from honeybee import extensionutil
except ImportError as e:
raise ImportError("\nFailed to import honeybee:\n\t{}".format(e))

try:
from honeybee_ph import bldg_segment
except ImportError as e:
raise ImportError('\nFailed to import honeybee_ph:\n\t{}'.format(e))
raise ImportError("\nFailed to import honeybee_ph:\n\t{}".format(e))


class ModelPhProperties(object):

def __init__(self, _host):
self._host = _host
self.id_num = 0
Expand Down Expand Up @@ -53,7 +61,7 @@ def ToString(self):

def _get_bldg_segment_dicts(self):
# type: () -> list[dict[str, Any]]
"""Return a list of all the bldg_segments found on the model's rooms as dicts.
"""Return a list of all the bldg_segments found on the model's rooms as dicts.
This is used when writing an 'Abridged' HBJSON file.
Arguments:
Expand All @@ -62,37 +70,40 @@ def _get_bldg_segment_dicts(self):
Returns:
--------
* list[dict[str, Any]]: A list of all the bldg_segments found on the model's
* list[dict[str, Any]]: A list of all the bldg_segments found on the model's
rooms as dicts.
"""
# -- Collect all the unique BldgSegments in the Model's Rooms
ph_bldg_segments = {rm.properties.ph.ph_bldg_segment.identifier:
rm.properties.ph.ph_bldg_segment for rm in self.host.rooms}
ph_bldg_segments = {
rm.properties.ph.ph_bldg_segment.identifier: rm.properties.ph.ph_bldg_segment
for rm in self.host.rooms
}
return [seg.to_dict() for seg in ph_bldg_segments.values()]

def to_dict(self, abridged=False):
# type: (bool) -> dict[str, dict]

d = {}
if abridged == False:
d['type'] = 'ModelPhPropertiesAbridged'
d['id_num'] = self.id_num
d['bldg_segments'] = self._get_bldg_segment_dicts()
d["type"] = "ModelPhPropertiesAbridged"
d["id_num"] = self.id_num
d["bldg_segments"] = self._get_bldg_segment_dicts()
else:
d['type'] = 'ModelPHProperties'
d['id_num'] = self.id_num
d['bldg_segments'] = []
d["type"] = "ModelPHProperties"
d["id_num"] = self.id_num
d["bldg_segments"] = []

return {'ph': d}
return {"ph": d}

@classmethod
def from_dict(cls, _dict, host):
# type: (dict[str, Any], Any) -> ModelPhProperties
assert _dict['type'] == 'ModelPhProperties', \
'Expected ModelPhProperties. Got {}.'.format(_dict['type'])
assert (
_dict["type"] == "ModelPhProperties"
), "Expected ModelPhProperties. Got {}.".format(_dict["type"])

new_prop = cls(host)
new_prop.id_num = _dict.get('id_num', 0)
new_prop.id_num = _dict.get("id_num", 0)

return new_prop

Expand All @@ -103,72 +114,77 @@ def load_properties_from_dict(data):
Loaded objects include: BldgSegment.......
The function is called when re-serializing an HB-Model object from a
The function is called when re-serializing an HB-Model object from a
dictionary. It will load honeybee_ph entities as Python objects and returns
a tuple of dictionaries with all the de-serialized Honeybee-PH objects.
Arguments:
----------
data: A dictionary representation of an entire honeybee-core Model.
Note that this dictionary must have ModelPhProperties
Note that this dictionary must have ModelPhProperties
in order for this method to successfully apply the .ph properties.
Note: data is an HB-Model dict and .keys() will include:
Note: data is an HB-Model dict and .keys() will include:
[
'display_name', 'identifier', 'tolerance',
'angle_tolerance', 'rooms', 'type', 'version',
'display_name', 'identifier', 'tolerance',
'angle_tolerance', 'rooms', 'type', 'version',
'units', 'orphaned_shades', 'properties'
]
Returns:
--------
* tuple[dict, dict]: A tuple of dictionaries with all the Honeybee-PH objects.
"""
assert 'ph' in data['properties'], \
'HB-Model Dictionary possesses no ModelPhProperties?'
assert (
"ph" in data["properties"]
), "HB-Model Dictionary possesses no ModelPhProperties?"

bldg_segments = {}
for seg in data['properties']['ph']['bldg_segments']:
bldg_segments[seg['identifier']] = bldg_segment.BldgSegment.from_dict(seg)
for seg in data["properties"]["ph"]["bldg_segments"]:
bldg_segments[seg["identifier"]] = bldg_segment.BldgSegment.from_dict(seg)

return bldg_segments

def apply_properties_from_dict(self, data):
# type: (dict[str, Any]) -> None
"""Apply the .ph properties of a dictionary to the host Model of this object.
This method is called when the HB-Model is de-serialized from a dict back into
a Python object. In an 'Abridged' HBJSON file, all the property information
is stored at the model level, not at the sub-model object level. In that case,
this method is used to apply the right property data back onto all the sub-model
This method is called when the HB-Model is de-serialized from a dict back into
a Python object. In an 'Abridged' HBJSON file, all the property information
is stored at the model level, not at the sub-model object level. In that case,
this method is used to apply the right property data back onto all the sub-model
objects (faces, rooms, apertures, etc).
Arguments:
----------
* data (dict[str, Any]): A dictionary representation of an entire honeybee-core
Model. Note that this dictionary must have ModelPhProperties
Model. Note that this dictionary must have ModelPhProperties
in order for this method to successfully apply the .ph properties.
Note: data is an HB-Model dict and .keys() will include:
Note: data is an HB-Model dict and .keys() will include:
[
'display_name', 'identifier', 'tolerance',
'angle_tolerance', 'rooms', 'type', 'version',
'display_name', 'identifier', 'tolerance',
'angle_tolerance', 'rooms', 'type', 'version',
'units', 'orphaned_shades', 'properties'
]
Returns:
--------
* None
"""
assert 'ph' in data['properties'], \
'Dictionary possesses no ModelPhProperties?'
assert "ph" in data["properties"], "Dictionary possesses no ModelPhProperties?"

# re-build all of the .ph property objects from the HB-Model dict as python objects
bldg_segments = self.load_properties_from_dict(data)

# collect lists of .ph property dictionaries at the sub-model level (room, face, etc)
room_ph_dicts, face_ph_dicts, shd_ph_dicts, ap_ph_dicts, dr_ph_dicts = \
extensionutil.model_extension_dicts(data, 'ph', [], [], [], [], [])
(
room_ph_dicts,
face_ph_dicts,
shd_ph_dicts,
ap_ph_dicts,
dr_ph_dicts,
) = extensionutil.model_extension_dicts(data, "ph", [], [], [], [], [])

# apply the .ph properties to all the sub-model objects in the HB-Model
for room, room_dict in zip(self.host.rooms, room_ph_dicts):
Expand All @@ -188,4 +204,4 @@ def apply_properties_from_dict(self, data):
face.properties.ph.apply_properties_from_dict(face_dict)

for aperture, ap_dict in zip(apertures, ap_ph_dicts):
aperture.properties.ph.apply_properties_from_dict(ap_dict)
aperture.properties.ph.apply_properties_from_dict(ap_dict)
24 changes: 17 additions & 7 deletions honeybee_ph/properties/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __init__(self, _host):
self.id_num = 0
self._spaces = list()
self.ph_bldg_segment = BldgSegment()
self._ph_foundations = {} # type: Dict[str, PhFoundation]
self._ph_foundations = {} # type: Dict[str, PhFoundation]
self.specific_heat_capacity = PhSpecificHeatCapacity("1-LIGHTWEIGHT")

@property
Expand Down Expand Up @@ -78,14 +78,16 @@ def duplicate(self, new_host=None, include_spaces=True):
_host = new_host or self._host
new_obj = RoomPhProperties(_host)
new_obj.id_num = self.id_num
new_obj.specific_heat_capacity = PhSpecificHeatCapacity(self.specific_heat_capacity.value)
new_obj.specific_heat_capacity = PhSpecificHeatCapacity(
self.specific_heat_capacity.value
)

if include_spaces:
for sp in self._spaces:
new_obj._spaces.append(sp.duplicate(_host))

new_obj.ph_bldg_segment = self.ph_bldg_segment.duplicate()

for f in self.ph_foundations:
new_obj.add_foundation(f.duplicate())

Expand Down Expand Up @@ -125,7 +127,11 @@ def from_dict(cls, _input_dict, host):

new_prop = cls(host)
new_prop.id_num = _input_dict.get("id_num", 0)
new_prop.specific_heat_capacity = PhSpecificHeatCapacity(_input_dict["specific_heat_capacity"])
new_prop.specific_heat_capacity = PhSpecificHeatCapacity(
_input_dict.get(
"specific_heat_capacity", new_prop.specific_heat_capacity.value
)
)

if "ph_bldg_segment" in _input_dict.keys():
new_prop.ph_bldg_segment = BldgSegment.from_dict(
Expand Down Expand Up @@ -161,7 +167,11 @@ def apply_properties_from_dict(self, room_prop_dict, bldg_segments):
* None
"""

self.specific_heat_capacity = PhSpecificHeatCapacity(room_prop_dict["specific_heat_capacity"])
self.specific_heat_capacity = PhSpecificHeatCapacity(
room_prop_dict.get(
"specific_heat_capacity", self.specific_heat_capacity.value
)
)

# -- Set the bldg-segment attributes from the values stored at the 'Model' level
room_ph_bldg_segment_id = room_prop_dict.get("ph_bldg_segment_id", None)
Expand All @@ -170,7 +180,7 @@ def apply_properties_from_dict(self, room_prop_dict, bldg_segments):

# -- Rebuild the Spaces hosted on the room
space_dicts = room_prop_dict.get("spaces", [])

for space_dict in space_dicts:
self.add_new_space(space.Space.from_dict(space_dict, self.host))

Expand Down Expand Up @@ -219,4 +229,4 @@ def scale(self, factor, origin=None):
"""

for space in self.spaces:
space.scale(factor, origin=None)
space.scale(factor, origin=None)
Loading

0 comments on commit 389e7b0

Please sign in to comment.