From 9e7400c7a61971ea64eec4a65be12bd712e42276 Mon Sep 17 00:00:00 2001 From: Samuel Letellier-Duchesne Date: Fri, 25 Oct 2024 15:26:41 -0400 Subject: [PATCH] code satisfies C4 rules (#517) * fir TRY rules * allow pytest as function in tox * fixes an issue where p is not initialized * fix tests * fix UP rules * fix typing union on py39 * fix E rules * fix * fix SIM rules * fix C4 rules * fix types * fix typing --- archetypal/__init__.py | 72 ++++++------ archetypal/cli.py | 22 ++-- archetypal/idfclass/extensions.py | 2 +- archetypal/idfclass/idf.py | 14 +-- archetypal/idfclass/outputs.py | 22 ++-- archetypal/schedule.py | 4 +- archetypal/template/building_template.py | 38 +++---- archetypal/template/conditioning.py | 104 +++++++++--------- .../constructions/opaque_construction.py | 28 ++--- .../constructions/window_construction.py | 24 ++-- archetypal/template/dhw.py | 22 ++-- archetypal/template/load.py | 60 +++++----- archetypal/template/materials/gas_layer.py | 2 +- archetypal/template/materials/gas_material.py | 34 +++--- .../template/materials/glazing_material.py | 54 ++++----- .../template/materials/material_layer.py | 2 +- .../template/materials/nomass_material.py | 40 +++---- .../template/materials/opaque_material.py | 44 ++++---- archetypal/template/schedule.py | 78 ++++++------- archetypal/template/structure.py | 34 +++--- archetypal/template/umi_base.py | 18 +-- archetypal/template/ventilation.py | 42 +++---- archetypal/template/window_setting.py | 82 +++++++------- archetypal/template/zone_construction_set.py | 32 +++--- archetypal/template/zonedefinition.py | 72 ++++++------ archetypal/umi_template.py | 7 +- docs/examples/parallel_process.py | 16 +-- pyproject.toml | 2 +- tests/test_dataportals.py | 8 +- 29 files changed, 491 insertions(+), 488 deletions(-) diff --git a/archetypal/__init__.py b/archetypal/__init__.py index dcdb2f33..cc17c730 100644 --- a/archetypal/__init__.py +++ b/archetypal/__init__.py @@ -89,78 +89,78 @@ class Settings(BaseSettings, arbitrary_types_allowed=True, validate_assignment=T # Ref: https://bigladdersoftware.com/epx/docs/8-3/output-details-and-examples # /eplusout.sql.html#schedules-table - available_sqlite_tables: ClassVar[dict] = dict( - ComponentSizes={"PrimaryKey": ["ComponentSizesIndex"], "ParseDates": []}, - ConstructionLayers={"PrimaryKey": ["ConstructionIndex"], "ParseDates": []}, - Constructions={"PrimaryKey": ["ConstructionIndex"], "ParseDates": []}, - Materials={"PrimaryKey": ["MaterialIndex"], "ParseDates": []}, - NominalBaseboardHeaters={ + available_sqlite_tables: ClassVar[dict] = { + "ComponentSizes": {"PrimaryKey": ["ComponentSizesIndex"], "ParseDates": []}, + "ConstructionLayers": {"PrimaryKey": ["ConstructionIndex"], "ParseDates": []}, + "Constructions": {"PrimaryKey": ["ConstructionIndex"], "ParseDates": []}, + "Materials": {"PrimaryKey": ["MaterialIndex"], "ParseDates": []}, + "NominalBaseboardHeaters": { "PrimaryKey": ["NominalBaseboardHeaterIndex"], "ParseDates": [], }, - NominalElectricEquipment={ + "NominalElectricEquipment": { "PrimaryKey": ["NominalElectricEquipmentIndex"], "ParseDates": [], }, - NominalGasEquipment={ + "NominalGasEquipment": { "PrimaryKey": ["NominalGasEquipmentIndex"], "ParseDates": [], }, - NominalHotWaterEquipment={ + "NominalHotWaterEquipment": { "PrimaryKey": ["NominalHotWaterEquipmentIndex"], "ParseDates": [], }, - NominalInfiltration={ + "NominalInfiltration": { "PrimaryKey": ["NominalInfiltrationIndex"], "ParseDates": [], }, - NominalLighting={"PrimaryKey": ["NominalLightingIndex"], "ParseDates": []}, - NominalOtherEquipment={ + "NominalLighting": {"PrimaryKey": ["NominalLightingIndex"], "ParseDates": []}, + "NominalOtherEquipment": { "PrimaryKey": ["NominalOtherEquipmentIndex"], "ParseDates": [], }, - NominalPeople={"PrimaryKey": ["NominalPeopleIndex"], "ParseDates": []}, - NominalSteamEquipment={ + "NominalPeople": {"PrimaryKey": ["NominalPeopleIndex"], "ParseDates": []}, + "NominalSteamEquipment": { "PrimaryKey": ["NominalSteamEquipmentIndex"], "ParseDates": [], }, - NominalVentilation={ + "NominalVentilation": { "PrimaryKey": ["NominalVentilationIndex"], "ParseDates": [], }, - ReportData={"PrimaryKey": ["ReportDataIndex"], "ParseDates": []}, - ReportDataDictionary={ + "ReportData": {"PrimaryKey": ["ReportDataIndex"], "ParseDates": []}, + "ReportDataDictionary": { "PrimaryKey": ["ReportDataDictionaryIndex"], "ParseDates": [], }, - ReportExtendedData={ + "ReportExtendedData": { "PrimaryKey": ["ReportExtendedDataIndex"], "ParseDates": [], }, - RoomAirModels={"PrimaryKey": ["ZoneIndex"], "ParseDates": []}, - Schedules={"PrimaryKey": ["ScheduleIndex"], "ParseDates": []}, - Surfaces={"PrimaryKey": ["SurfaceIndex"], "ParseDates": []}, - SystemSizes={ + "RoomAirModels": {"PrimaryKey": ["ZoneIndex"], "ParseDates": []}, + "Schedules": {"PrimaryKey": ["ScheduleIndex"], "ParseDates": []}, + "Surfaces": {"PrimaryKey": ["SurfaceIndex"], "ParseDates": []}, + "SystemSizes": { "PrimaryKey": ["SystemSizesIndex"], "ParseDates": {"PeakHrMin": "%m/%d %H:%M:%S"}, }, - Time={"PrimaryKey": ["TimeIndex"], "ParseDates": []}, - ZoneGroups={"PrimaryKey": ["ZoneGroupIndex"], "ParseDates": []}, - Zones={"PrimaryKey": ["ZoneIndex"], "ParseDates": []}, - ZoneLists={"PrimaryKey": ["ZoneListIndex"], "ParseDates": []}, - ZoneSizes={"PrimaryKey": ["ZoneSizesIndex"], "ParseDates": []}, - ZoneInfoZoneLists={"PrimaryKey": ["ZoneListIndex"], "ParseDates": []}, - Simulations={ + "Time": {"PrimaryKey": ["TimeIndex"], "ParseDates": []}, + "ZoneGroups": {"PrimaryKey": ["ZoneGroupIndex"], "ParseDates": []}, + "Zones": {"PrimaryKey": ["ZoneIndex"], "ParseDates": []}, + "ZoneLists": {"PrimaryKey": ["ZoneListIndex"], "ParseDates": []}, + "ZoneSizes": {"PrimaryKey": ["ZoneSizesIndex"], "ParseDates": []}, + "ZoneInfoZoneLists": {"PrimaryKey": ["ZoneListIndex"], "ParseDates": []}, + "Simulations": { "PrimaryKey": ["SimulationIndex"], "ParseDates": {"TimeStamp": {"format": "YMD=%Y.%m.%d %H:%M"}}, }, - EnvironmentPeriods={"PrimaryKey": ["EnvironmentPeriodIndex"], "ParseDates": []}, - TabularData={"PrimaryKey": ["TabularDataIndex"], "ParseDates": []}, - Strings={"PrimaryKey": ["StringIndex"], "ParseDates": []}, - StringTypes={"PrimaryKey": ["StringTypeIndex"], "ParseDates": []}, - TabularDataWithStrings={"PrimaryKey": ["TabularDataIndex"], "ParseDates": []}, - Errors={"PrimaryKey": ["ErrorIndex"], "ParseDates": []}, - ) + "EnvironmentPeriods": {"PrimaryKey": ["EnvironmentPeriodIndex"], "ParseDates": []}, + "TabularData": {"PrimaryKey": ["TabularDataIndex"], "ParseDates": []}, + "Strings": {"PrimaryKey": ["StringIndex"], "ParseDates": []}, + "StringTypes": {"PrimaryKey": ["StringTypeIndex"], "ParseDates": []}, + "TabularDataWithStrings": {"PrimaryKey": ["TabularDataIndex"], "ParseDates": []}, + "Errors": {"PrimaryKey": ["ErrorIndex"], "ParseDates": []}, + } zone_weight: ZoneWeight = ZoneWeight(n=0) diff --git a/archetypal/cli.py b/archetypal/cli.py index 0a01eff5..96e2a145 100644 --- a/archetypal/cli.py +++ b/archetypal/cli.py @@ -18,7 +18,7 @@ from .eplus_interface.exceptions import EnergyPlusVersionError from .eplus_interface.version import EnergyPlusVersion -CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]) +CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]} class CliConfig: @@ -297,14 +297,14 @@ def transition(idf, to_version, cores, yes): to_version = to_version.dash rundict = { - file: dict( - idfname=file, - as_version=to_version, - check_required=False, - check_length=False, - overwrite=overwrite, - prep_outputs=False, - ) + file: { + "idfname": file, + "as_version": to_version, + "check_required": False, + "check_length": False, + "overwrite": overwrite, + "prep_outputs": False, + } for i, file in enumerate(file_paths) } results = parallel_process( @@ -352,7 +352,7 @@ def set_filepaths(idf): file_paths = () # Placeholder for tuple of paths for file_or_path in idf: if file_or_path.isfile(): # if a file, concatenate into file_paths - file_paths += tuple([file_or_path]) + file_paths += (file_or_path,) elif file_or_path.isdir(): # if a directory, walkdir (recursive) and get *.idf file_paths += tuple(file_or_path.walkfiles("*.idf")) else: @@ -368,7 +368,7 @@ def set_filepaths(idf): pattern = file_or_path.basename() file_paths += tuple(Path(root).files(pattern)) - file_paths = set([f.relpath().expand() for f in file_paths]) # Only keep unique + file_paths = {f.relpath().expand() for f in file_paths} # Only keep unique # values if file_paths: return file_paths diff --git a/archetypal/idfclass/extensions.py b/archetypal/idfclass/extensions.py index 169c2596..7ad3510e 100644 --- a/archetypal/idfclass/extensions.py +++ b/archetypal/idfclass/extensions.py @@ -43,7 +43,7 @@ def get_default(self: EpBunch, name): @extend_class(EpBunch) def to_dict(self: EpBunch): """Get the dict representation of the EpBunch.""" - return {k: v for k, v in zip(self.fieldnames, self.fieldvalues)} + return dict(zip(self.fieldnames, self.fieldvalues)) @extend_class(EpBunch) diff --git a/archetypal/idfclass/idf.py b/archetypal/idfclass/idf.py index 736b26f7..58f9560e 100644 --- a/archetypal/idfclass/idf.py +++ b/archetypal/idfclass/idf.py @@ -408,7 +408,7 @@ def from_example_files(cls, example_name, epw=None, **kwargs): try: file = next(iter(Pathlib(example_files_dir).rglob(f"{example_name.stem}.idf"))) except StopIteration as e: - full_list = list(map(lambda x: str(x.name), example_files_dir.files("*.idf"))) + full_list = [str(x.name) for x in example_files_dir.files("*.idf")] raise ValueError(f"Choose from: {sorted(full_list)}") from e if epw is not None: epw = Path(epw) @@ -418,7 +418,7 @@ def from_example_files(cls, example_name, epw=None, **kwargs): try: epw = next(iter(Pathlib(dir_weather_data_).rglob(f"{epw.stem}.epw"))) except StopIteration as e: - full_list = list(map(lambda x: str(x.name), dir_weather_data_.files("*.epw"))) + full_list = [str(x.name) for x in dir_weather_data_.files("*.epw")] raise ValueError(f"Choose EPW from: {sorted(full_list)}") from e return cls(file, epw=epw, **kwargs) @@ -1542,9 +1542,7 @@ def saveas(self, filename, lineendings="default", encoding="latin-1", inplace=Fa import inspect sig = inspect.signature(IDF.__init__) - kwargs = { - key: getattr(self, key) for key in [a for a in sig.parameters] if key not in ["self", "idfname", "kwargs"] - } + kwargs = {key: getattr(self, key) for key in list(sig.parameters) if key not in ["self", "idfname", "kwargs"]} as_idf = IDF(filename, **kwargs) # copy simulation_dir over to new location @@ -2375,7 +2373,7 @@ def to_world(self): if "world" in [o.Coordinate_System.lower() for o in self.idfobjects["GLOBALGEOMETRYRULES"]] or self.translated: log("Model already set as World coordinates", level=lg.WARNING) return - zone_angles = set(z.Direction_of_Relative_North or 0 for z in self.idfobjects["ZONE"]) + zone_angles = {z.Direction_of_Relative_North or 0 for z in self.idfobjects["ZONE"]} # If Zones have Direction_of_Relative_North != 0, model needs to be rotated # before translation. if all(angle != 0 for angle in zone_angles): @@ -2397,7 +2395,7 @@ def to_world(self): } surfaces = {s.Name.upper(): s for s in self.getsurfaces()} subsurfaces = self.getsubsurfaces() - daylighting_refpoints = [p for p in self.idfobjects["DAYLIGHTING:REFERENCEPOINT"]] + daylighting_refpoints = list(self.idfobjects["DAYLIGHTING:REFERENCEPOINT"]) attached_shading_surf_names = [] for g in self.idd_index["ref2names"]["AttachedShadingSurfNames"]: for item in self.idfobjects[g]: @@ -2501,7 +2499,7 @@ def rotate(self, angle: float | None = None, anchor: tuple[float, float, float] if not angle: bldg_angle = self.idfobjects["BUILDING"][0].North_Axis or 0 log(f"Building North Axis = {bldg_angle}", level=lg.DEBUG) - zone_angles = set(z.Direction_of_Relative_North for z in self.idfobjects["ZONE"]) + zone_angles = {z.Direction_of_Relative_North for z in self.idfobjects["ZONE"]} assert len(zone_angles) == 1, "Not all zone have the same Direction_of_Relative_North" zone_angle, *_ = zone_angles zone_angle = zone_angle or 0 diff --git a/archetypal/idfclass/outputs.py b/archetypal/idfclass/outputs.py index 55e545b7..5d44435c 100644 --- a/archetypal/idfclass/outputs.py +++ b/archetypal/idfclass/outputs.py @@ -115,10 +115,10 @@ def __init__( """ self.idf = idf self.reporting_frequency = reporting_frequency - self.output_variables = set(a.Variable_Name for a in idf.idfobjects["Output:Variable".upper()]) - self.output_meters = set( + self.output_variables = {a.Variable_Name for a in idf.idfobjects["Output:Variable".upper()]} + self.output_meters = { (get_name_attribute(a), a.Reporting_Frequency) for a in idf.idfobjects["Output:Meter".upper()] - ) + } self.other_outputs = outputs self.output_variables += tuple((v, reporting_frequency) for v in variables) @@ -289,7 +289,7 @@ def add_basics(self): def add_schedules(self): """Adds Schedules object""" - outputs = [{"key": "Output:Schedules".upper(), **dict(Key_Field="Hourly")}] + outputs = [{"key": "Output:Schedules".upper(), **{"Key_Field": "Hourly"}}] for output in outputs: self._other_outputs.append(output) return self @@ -309,7 +309,7 @@ def add_meter_variables(self, format="IDF"): Returns: Outputs: self """ - outputs = [dict(key="Output:VariableDictionary".upper(), Key_Field=format)] + outputs = [{"key": "Output:VariableDictionary".upper(), "Key_Field": format}] for output in outputs: self._other_outputs.append(output) return self @@ -338,7 +338,7 @@ def add_summary_report(self, summary="AllSummary"): outputs = [ { "key": "Output:Table:SummaryReports".upper(), - **dict(Report_1_Name=summary), + **{"Report_1_Name": summary}, } ] for output in outputs: @@ -361,7 +361,7 @@ def add_sql(self, sql_output_style="SimpleAndTabular"): Returns: Outputs: self """ - outputs = [{"key": "Output:SQLite".upper(), **dict(Option_Type=sql_output_style)}] + outputs = [{"key": "Output:SQLite".upper(), **{"Option_Type": sql_output_style}}] for output in outputs: self._other_outputs.append(output) @@ -390,7 +390,7 @@ def add_output_control(self, output_control_table_style="CommaAndHTML"): outputs = [ { "key": "OutputControl:Table:Style".upper(), - **dict(Column_Separator=output_control_table_style), + **{"Column_Separator": output_control_table_style}, } ] @@ -452,7 +452,7 @@ def add_dxf(self): outputs = [ { "key": "Output:Surfaces:Drawing".upper(), - **dict(Report_Type="DXF", Report_Specifications_1="ThickPolyline"), + **{"Report_Type": "DXF", "Report_Specifications_1": "ThickPolyline"}, } ] for output in outputs: @@ -704,12 +704,12 @@ def apply(self): for variable, reporting_frequency in self.output_variables: self.idf.newidfobject( key="Output:Variable".upper(), - **dict(Variable_Name=variable, Reporting_Frequency=reporting_frequency), + **{"Variable_Name": variable, "Reporting_Frequency": reporting_frequency}, ) for meter, reporting_frequency in self.output_meters: self.idf.newidfobject( key="Output:Meter".upper(), - **dict(Key_Name=meter, Reporting_Frequency=reporting_frequency), + **{"Key_Name": meter, "Reporting_Frequency": reporting_frequency}, ) for output in self.other_outputs: key = output.pop("key", None) diff --git a/archetypal/schedule.py b/archetypal/schedule.py index a9c3fee8..36b3db56 100644 --- a/archetypal/schedule.py +++ b/archetypal/schedule.py @@ -423,7 +423,7 @@ def get_compact_ep_schedule_values(epbunch, start_date, strict) -> np.ndarray: from_time = "00:00" how_interpolate = None for field in fields: - if any([spe in field.lower() for spe in field_sets]): + if any(spe in field.lower() for spe in field_sets): f_set, hour, minute, value = _ScheduleParser._field_interpreter(field, epbunch.Name) if f_set.lower() == "through": @@ -1367,7 +1367,7 @@ def to_year_week_day(self): blocks = {} from_date = datetime(self.year, 1, 1) bincount = [sum(1 for _ in group) for key, group in groupby(nws + 1) if key] - week_order = {i: v for i, v in enumerate(np.array([key for key, group in groupby(nws + 1) if key]) - 1)} + week_order = dict(enumerate(np.array([key for key, group in groupby(nws + 1) if key]) - 1)) for i, (week_n, count) in enumerate(zip(week_order, bincount)): week_id = list(dict_week)[week_order[i]] to_date = from_date + timedelta(days=int(count * 7), hours=-1) diff --git a/archetypal/template/building_template.py b/archetypal/template/building_template.py index 0dbd927a..73f25a10 100644 --- a/archetypal/template/building_template.py +++ b/archetypal/template/building_template.py @@ -560,25 +560,25 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Core=self.Core, - Lifespan=self.Lifespan, - PartitionRatio=self.PartitionRatio, - Perimeter=self.Perimeter, - Structure=self.Structure, - Windows=self.Windows, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - YearFrom=self.YearFrom, - YearTo=self.YearTo, - Country=self.Country, - ClimateZone=self.ClimateZone, - Authors=self.Authors, - AuthorEmails=self.AuthorEmails, - Version=self.Version, - ) + return { + "Core": self.Core, + "Lifespan": self.Lifespan, + "PartitionRatio": self.PartitionRatio, + "Perimeter": self.Perimeter, + "Structure": self.Structure, + "Windows": self.Windows, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + "YearFrom": self.YearFrom, + "YearTo": self.YearTo, + "Country": self.Country, + "ClimateZone": self.ClimateZone, + "Authors": self.Authors, + "AuthorEmails": self.AuthorEmails, + "Version": self.Version, + } def get_ref(self, ref): """Get item matching reference id. diff --git a/archetypal/template/conditioning.py b/archetypal/template/conditioning.py index a35c9ba8..9b8b7db5 100644 --- a/archetypal/template/conditioning.py +++ b/archetypal/template/conditioning.py @@ -1268,31 +1268,33 @@ def combine(self, other, weights=None): if not weights: weights = [self.area, other.area] - new_attr = dict( - CoolingCoeffOfPerf=UmiBase.float_mean(self, other, "CoolingCoeffOfPerf", weights), - CoolingLimitType=max(self.CoolingLimitType, other.CoolingLimitType), - CoolingSetpoint=UmiBase.float_mean(self, other, "CoolingSetpoint", weights), - EconomizerType=max(self.EconomizerType, other.EconomizerType), - HeatRecoveryEfficiencyLatent=UmiBase.float_mean(self, other, "HeatRecoveryEfficiencyLatent", weights), - HeatRecoveryEfficiencySensible=UmiBase.float_mean(self, other, "HeatRecoveryEfficiencySensible", weights), - HeatRecoveryType=max(self.HeatRecoveryType, other.HeatRecoveryType), - HeatingCoeffOfPerf=UmiBase.float_mean(self, other, "HeatingCoeffOfPerf", weights), - HeatingLimitType=max(self.HeatingLimitType, other.HeatingLimitType), - HeatingSetpoint=UmiBase.float_mean(self, other, "HeatingSetpoint", weights), - IsCoolingOn=any((self.IsCoolingOn, other.IsCoolingOn)), - IsHeatingOn=any((self.IsHeatingOn, other.IsHeatingOn)), - IsMechVentOn=any((self.IsMechVentOn, other.IsMechVentOn)), - MaxCoolFlow=UmiBase.float_mean(self, other, "MaxCoolFlow", weights), - MaxCoolingCapacity=UmiBase.float_mean(self, other, "MaxCoolingCapacity", weights), - MaxHeatFlow=UmiBase.float_mean(self, other, "MaxHeatFlow", weights), - MaxHeatingCapacity=UmiBase.float_mean(self, other, "MaxHeatingCapacity", weights), - MinFreshAirPerArea=UmiBase.float_mean(self, other, "MinFreshAirPerArea", weights), - MinFreshAirPerPerson=UmiBase.float_mean(self, other, "MinFreshAirPerPerson", weights), - HeatingSchedule=UmiSchedule.combine(self.HeatingSchedule, other.HeatingSchedule, weights), - CoolingSchedule=UmiSchedule.combine(self.CoolingSchedule, other.CoolingSchedule, weights), - MechVentSchedule=UmiSchedule.combine(self.MechVentSchedule, other.MechVentSchedule, weights), - area=1 if self.area + other.area == 2 else self.area + other.area, - ) + new_attr = { + "CoolingCoeffOfPerf": UmiBase.float_mean(self, other, "CoolingCoeffOfPerf", weights), + "CoolingLimitType": max(self.CoolingLimitType, other.CoolingLimitType), + "CoolingSetpoint": UmiBase.float_mean(self, other, "CoolingSetpoint", weights), + "EconomizerType": max(self.EconomizerType, other.EconomizerType), + "HeatRecoveryEfficiencyLatent": UmiBase.float_mean(self, other, "HeatRecoveryEfficiencyLatent", weights), + "HeatRecoveryEfficiencySensible": UmiBase.float_mean( + self, other, "HeatRecoveryEfficiencySensible", weights + ), + "HeatRecoveryType": max(self.HeatRecoveryType, other.HeatRecoveryType), + "HeatingCoeffOfPerf": UmiBase.float_mean(self, other, "HeatingCoeffOfPerf", weights), + "HeatingLimitType": max(self.HeatingLimitType, other.HeatingLimitType), + "HeatingSetpoint": UmiBase.float_mean(self, other, "HeatingSetpoint", weights), + "IsCoolingOn": any((self.IsCoolingOn, other.IsCoolingOn)), + "IsHeatingOn": any((self.IsHeatingOn, other.IsHeatingOn)), + "IsMechVentOn": any((self.IsMechVentOn, other.IsMechVentOn)), + "MaxCoolFlow": UmiBase.float_mean(self, other, "MaxCoolFlow", weights), + "MaxCoolingCapacity": UmiBase.float_mean(self, other, "MaxCoolingCapacity", weights), + "MaxHeatFlow": UmiBase.float_mean(self, other, "MaxHeatFlow", weights), + "MaxHeatingCapacity": UmiBase.float_mean(self, other, "MaxHeatingCapacity", weights), + "MinFreshAirPerArea": UmiBase.float_mean(self, other, "MinFreshAirPerArea", weights), + "MinFreshAirPerPerson": UmiBase.float_mean(self, other, "MinFreshAirPerPerson", weights), + "HeatingSchedule": UmiSchedule.combine(self.HeatingSchedule, other.HeatingSchedule, weights), + "CoolingSchedule": UmiSchedule.combine(self.CoolingSchedule, other.CoolingSchedule, weights), + "MechVentSchedule": UmiSchedule.combine(self.MechVentSchedule, other.MechVentSchedule, weights), + "area": 1 if self.area + other.area == 2 else self.area + other.area, + } # create a new object with the previous attributes new_obj = self.__class__(**meta, **new_attr, allow_duplicates=self.allow_duplicates) new_obj.predecessors.update(self.predecessors + other.predecessors) @@ -1324,32 +1326,32 @@ def mapping(self, validate=False): self.validate() base = super().mapping(validate=validate) - data = dict( - CoolingSchedule=self.CoolingSchedule, - CoolingCoeffOfPerf=self.CoolingCoeffOfPerf, - CoolingSetpoint=self.CoolingSetpoint, - CoolingLimitType=self.CoolingLimitType, - CoolingFuelType=self.CoolingFuelType, - EconomizerType=self.EconomizerType, - HeatingCoeffOfPerf=self.HeatingCoeffOfPerf, - HeatingLimitType=self.HeatingLimitType, - HeatingFuelType=self.HeatingFuelType, - HeatingSchedule=self.HeatingSchedule, - HeatingSetpoint=self.HeatingSetpoint, - HeatRecoveryEfficiencyLatent=self.HeatRecoveryEfficiencyLatent, - HeatRecoveryEfficiencySensible=self.HeatRecoveryEfficiencySensible, - HeatRecoveryType=self.HeatRecoveryType, - IsCoolingOn=self.IsCoolingOn, - IsHeatingOn=self.IsHeatingOn, - IsMechVentOn=self.IsMechVentOn, - MaxCoolFlow=self.MaxCoolFlow, - MaxCoolingCapacity=self.MaxCoolingCapacity, - MaxHeatFlow=self.MaxHeatFlow, - MaxHeatingCapacity=self.MaxHeatingCapacity, - MechVentSchedule=self.MechVentSchedule, - MinFreshAirPerArea=self.MinFreshAirPerArea, - MinFreshAirPerPerson=self.MinFreshAirPerPerson, - ) + data = { + "CoolingSchedule": self.CoolingSchedule, + "CoolingCoeffOfPerf": self.CoolingCoeffOfPerf, + "CoolingSetpoint": self.CoolingSetpoint, + "CoolingLimitType": self.CoolingLimitType, + "CoolingFuelType": self.CoolingFuelType, + "EconomizerType": self.EconomizerType, + "HeatingCoeffOfPerf": self.HeatingCoeffOfPerf, + "HeatingLimitType": self.HeatingLimitType, + "HeatingFuelType": self.HeatingFuelType, + "HeatingSchedule": self.HeatingSchedule, + "HeatingSetpoint": self.HeatingSetpoint, + "HeatRecoveryEfficiencyLatent": self.HeatRecoveryEfficiencyLatent, + "HeatRecoveryEfficiencySensible": self.HeatRecoveryEfficiencySensible, + "HeatRecoveryType": self.HeatRecoveryType, + "IsCoolingOn": self.IsCoolingOn, + "IsHeatingOn": self.IsHeatingOn, + "IsMechVentOn": self.IsMechVentOn, + "MaxCoolFlow": self.MaxCoolFlow, + "MaxCoolingCapacity": self.MaxCoolingCapacity, + "MaxHeatFlow": self.MaxHeatFlow, + "MaxHeatingCapacity": self.MaxHeatingCapacity, + "MechVentSchedule": self.MechVentSchedule, + "MinFreshAirPerArea": self.MinFreshAirPerArea, + "MinFreshAirPerPerson": self.MinFreshAirPerPerson, + } data.update(base) return data diff --git a/archetypal/template/constructions/opaque_construction.py b/archetypal/template/constructions/opaque_construction.py index 9fdcd661..9a4912d6 100644 --- a/archetypal/template/constructions/opaque_construction.py +++ b/archetypal/template/constructions/opaque_construction.py @@ -64,7 +64,7 @@ def r_value(self): def r_value(self, value): # First, find the insulation layer i = self.infer_insulation_layer() - all_layers_except_insulation_layer = [a for a in self.Layers] + all_layers_except_insulation_layer = list(self.Layers) all_layers_except_insulation_layer.pop(i) insulation_layer: MaterialLayer = self.Layers[i] @@ -464,18 +464,18 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Layers=self.Layers, - AssemblyCarbon=self.AssemblyCarbon, - AssemblyCost=self.AssemblyCost, - AssemblyEnergy=self.AssemblyEnergy, - DisassemblyCarbon=self.DisassemblyCarbon, - DisassemblyEnergy=self.DisassemblyEnergy, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "Layers": self.Layers, + "AssemblyCarbon": self.AssemblyCarbon, + "AssemblyCost": self.AssemblyCost, + "AssemblyEnergy": self.AssemblyEnergy, + "DisassemblyCarbon": self.DisassemblyCarbon, + "DisassemblyEnergy": self.DisassemblyEnergy, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } @classmethod def generic(cls, **kwargs): @@ -512,7 +512,7 @@ def __eq__(self, other): def __copy__(self): """Create a copy of self.""" - new_con = self.__class__(Name=self.Name, Layers=[a for a in self.Layers]) + new_con = self.__class__(Name=self.Name, Layers=list(self.Layers)) return new_con def to_epbunch(self, idf): diff --git a/archetypal/template/constructions/window_construction.py b/archetypal/template/constructions/window_construction.py index 02aec455..d5467612 100644 --- a/archetypal/template/constructions/window_construction.py +++ b/archetypal/template/constructions/window_construction.py @@ -339,18 +339,18 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Layers=self.Layers, - AssemblyCarbon=self.AssemblyCarbon, - AssemblyCost=self.AssemblyCost, - AssemblyEnergy=self.AssemblyEnergy, - DisassemblyCarbon=self.DisassemblyCarbon, - DisassemblyEnergy=self.DisassemblyEnergy, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "Layers": self.Layers, + "AssemblyCarbon": self.AssemblyCarbon, + "AssemblyCost": self.AssemblyCost, + "AssemblyEnergy": self.AssemblyEnergy, + "DisassemblyCarbon": self.DisassemblyCarbon, + "DisassemblyEnergy": self.DisassemblyEnergy, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def combine(self, other, weights=None): """Append other to self. Return self + other as a new object. diff --git a/archetypal/template/dhw.py b/archetypal/template/dhw.py index 5a7c323f..0d123132 100644 --- a/archetypal/template/dhw.py +++ b/archetypal/template/dhw.py @@ -453,17 +453,17 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - FlowRatePerFloorArea=self.FlowRatePerFloorArea, - IsOn=self.IsOn, - WaterSchedule=self.WaterSchedule, - WaterSupplyTemperature=self.WaterSupplyTemperature, - WaterTemperatureInlet=self.WaterTemperatureInlet, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "FlowRatePerFloorArea": self.FlowRatePerFloorArea, + "IsOn": self.IsOn, + "WaterSchedule": self.WaterSchedule, + "WaterSupplyTemperature": self.WaterSupplyTemperature, + "WaterTemperatureInlet": self.WaterTemperatureInlet, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def duplicate(self): """Get copy of self.""" diff --git a/archetypal/template/load.py b/archetypal/template/load.py index 29ba57a1..ab2f8766 100644 --- a/archetypal/template/load.py +++ b/archetypal/template/load.py @@ -531,34 +531,34 @@ def combine(self, other, weights=None): ) ) - new_attr = dict( - DimmingType=max(self.DimmingType, other.DimmingType), - EquipmentAvailabilitySchedule=UmiSchedule.combine( + new_attr = { + "DimmingType": max(self.DimmingType, other.DimmingType), + "EquipmentAvailabilitySchedule": UmiSchedule.combine( self.EquipmentAvailabilitySchedule, other.EquipmentAvailabilitySchedule, weights=[self.area, other.area], quantity=True, ), - EquipmentPowerDensity=self.float_mean(other, "EquipmentPowerDensity", weights), - IlluminanceTarget=self.float_mean(other, "IlluminanceTarget", weights), - LightingPowerDensity=self.float_mean(other, "LightingPowerDensity", weights), - LightsAvailabilitySchedule=UmiSchedule.combine( + "EquipmentPowerDensity": self.float_mean(other, "EquipmentPowerDensity", weights), + "IlluminanceTarget": self.float_mean(other, "IlluminanceTarget", weights), + "LightingPowerDensity": self.float_mean(other, "LightingPowerDensity", weights), + "LightsAvailabilitySchedule": UmiSchedule.combine( self.LightsAvailabilitySchedule, other.LightsAvailabilitySchedule, weights=[self.area, other.area], quantity=True, ), - OccupancySchedule=UmiSchedule.combine( + "OccupancySchedule": UmiSchedule.combine( self.OccupancySchedule, other.OccupancySchedule, weights=[self.area, other.area], quantity=True, ), - IsEquipmentOn=any([self.IsEquipmentOn, other.IsEquipmentOn]), - IsLightingOn=any([self.IsLightingOn, other.IsLightingOn]), - IsPeopleOn=any([self.IsPeopleOn, other.IsPeopleOn]), - PeopleDensity=self.float_mean(other, "PeopleDensity", weights), - ) + "IsEquipmentOn": any([self.IsEquipmentOn, other.IsEquipmentOn]), + "IsLightingOn": any([self.IsLightingOn, other.IsLightingOn]), + "IsPeopleOn": any([self.IsPeopleOn, other.IsPeopleOn]), + "PeopleDensity": self.float_mean(other, "PeopleDensity", weights), + } new_obj = self.__class__(**meta, **new_attr, allow_duplicates=self.allow_duplicates) new_obj.area = self.area + other.area @@ -602,23 +602,23 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - DimmingType=self.DimmingType, - EquipmentAvailabilitySchedule=self.EquipmentAvailabilitySchedule, - EquipmentPowerDensity=self.EquipmentPowerDensity, - IlluminanceTarget=self.IlluminanceTarget, - LightingPowerDensity=self.LightingPowerDensity, - LightsAvailabilitySchedule=self.LightsAvailabilitySchedule, - OccupancySchedule=self.OccupancySchedule, - IsEquipmentOn=self.IsEquipmentOn, - IsLightingOn=self.IsLightingOn, - IsPeopleOn=self.IsPeopleOn, - PeopleDensity=self.PeopleDensity, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "DimmingType": self.DimmingType, + "EquipmentAvailabilitySchedule": self.EquipmentAvailabilitySchedule, + "EquipmentPowerDensity": self.EquipmentPowerDensity, + "IlluminanceTarget": self.IlluminanceTarget, + "LightingPowerDensity": self.LightingPowerDensity, + "LightsAvailabilitySchedule": self.LightsAvailabilitySchedule, + "OccupancySchedule": self.OccupancySchedule, + "IsEquipmentOn": self.IsEquipmentOn, + "IsLightingOn": self.IsLightingOn, + "IsPeopleOn": self.IsPeopleOn, + "PeopleDensity": self.PeopleDensity, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def to_dict(self): """Return ZoneLoad dictionary representation.""" diff --git a/archetypal/template/materials/gas_layer.py b/archetypal/template/materials/gas_layer.py index a7c166ef..09fc591d 100644 --- a/archetypal/template/materials/gas_layer.py +++ b/archetypal/template/materials/gas_layer.py @@ -331,7 +331,7 @@ def to_epbunch(self, idf): def mapping(self): """Get a dict based on the object properties, useful for dict repr.""" - return dict(Material=self.Material, Thickness=self.Thickness) + return {"Material": self.Material, "Thickness": self.Thickness} def get_unique(self): """Return the first of all the created objects that is equivalent to self.""" diff --git a/archetypal/template/materials/gas_material.py b/archetypal/template/materials/gas_material.py index d393b8d8..0c420a25 100644 --- a/archetypal/template/materials/gas_material.py +++ b/archetypal/template/materials/gas_material.py @@ -188,23 +188,23 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Category=self.Category, - Type=self.Type, - Conductivity=self.Conductivity, - Cost=self.Cost, - Density=self.Density, - EmbodiedCarbon=self.EmbodiedCarbon, - EmbodiedEnergy=self.EmbodiedEnergy, - SubstitutionRatePattern=self.SubstitutionRatePattern, - SubstitutionTimestep=self.SubstitutionTimestep, - TransportCarbon=self.TransportCarbon, - TransportDistance=self.TransportDistance, - TransportEnergy=self.TransportEnergy, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "Category": self.Category, + "Type": self.Type, + "Conductivity": self.Conductivity, + "Cost": self.Cost, + "Density": self.Density, + "EmbodiedCarbon": self.EmbodiedCarbon, + "EmbodiedEnergy": self.EmbodiedEnergy, + "SubstitutionRatePattern": self.SubstitutionRatePattern, + "SubstitutionTimestep": self.SubstitutionTimestep, + "TransportCarbon": self.TransportCarbon, + "TransportDistance": self.TransportDistance, + "TransportEnergy": self.TransportEnergy, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def density_at_temperature(self, t_kelvin, pressure=101325): """Get the density of the gas [kg/m3] at a given temperature and pressure. diff --git a/archetypal/template/materials/glazing_material.py b/archetypal/template/materials/glazing_material.py index d3521a2c..9c8f92e9 100644 --- a/archetypal/template/materials/glazing_material.py +++ b/archetypal/template/materials/glazing_material.py @@ -254,7 +254,7 @@ def combine(self, other, weights=None, allow_duplicates=False): new_attr = {} for attr, value in self.mapping().items(): if attr not in ["Comments", "DataSource"]: - if isinstance(value, (int, float)) or isinstance(other, (int, float)): + if isinstance(value, int | float) or isinstance(other, int | float): new_attr[attr] = UmiBase.float_mean(self, other, attr=attr, weights=weights) elif isinstance(value, str) or isinstance(other, str): new_attr[attr] = UmiBase._str_mean(self, other, attr=attr, append=False) @@ -363,32 +363,32 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - DirtFactor=self.DirtFactor, - IREmissivityBack=self.IREmissivityBack, - IREmissivityFront=self.IREmissivityFront, - IRTransmittance=self.IRTransmittance, - SolarReflectanceBack=self.SolarReflectanceBack, - SolarReflectanceFront=self.SolarReflectanceFront, - SolarTransmittance=self.SolarTransmittance, - VisibleReflectanceBack=self.VisibleReflectanceBack, - VisibleReflectanceFront=self.VisibleReflectanceFront, - VisibleTransmittance=self.VisibleTransmittance, - Conductivity=self.Conductivity, - Cost=self.Cost, - Density=self.Density, - EmbodiedCarbon=self.EmbodiedCarbon, - EmbodiedEnergy=self.EmbodiedEnergy, - SubstitutionRatePattern=self.SubstitutionRatePattern, - SubstitutionTimestep=self.SubstitutionTimestep, - TransportCarbon=self.TransportCarbon, - TransportDistance=self.TransportDistance, - TransportEnergy=self.TransportEnergy, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "DirtFactor": self.DirtFactor, + "IREmissivityBack": self.IREmissivityBack, + "IREmissivityFront": self.IREmissivityFront, + "IRTransmittance": self.IRTransmittance, + "SolarReflectanceBack": self.SolarReflectanceBack, + "SolarReflectanceFront": self.SolarReflectanceFront, + "SolarTransmittance": self.SolarTransmittance, + "VisibleReflectanceBack": self.VisibleReflectanceBack, + "VisibleReflectanceFront": self.VisibleReflectanceFront, + "VisibleTransmittance": self.VisibleTransmittance, + "Conductivity": self.Conductivity, + "Cost": self.Cost, + "Density": self.Density, + "EmbodiedCarbon": self.EmbodiedCarbon, + "EmbodiedEnergy": self.EmbodiedEnergy, + "SubstitutionRatePattern": self.SubstitutionRatePattern, + "SubstitutionTimestep": self.SubstitutionTimestep, + "TransportCarbon": self.TransportCarbon, + "TransportDistance": self.TransportDistance, + "TransportEnergy": self.TransportEnergy, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } @classmethod def from_dict(cls, data, **kwargs): diff --git a/archetypal/template/materials/material_layer.py b/archetypal/template/materials/material_layer.py index d8e115eb..4f89e013 100644 --- a/archetypal/template/materials/material_layer.py +++ b/archetypal/template/materials/material_layer.py @@ -127,7 +127,7 @@ def to_epbunch(self, idf): def mapping(self): """Get a dict based on the object properties, useful for dict repr.""" - return dict(Material=self.Material, Thickness=self.Thickness) + return {"Material": self.Material, "Thickness": self.Thickness} def get_unique(self): """Return the first of all the created objects that is equivalent to self.""" diff --git a/archetypal/template/materials/nomass_material.py b/archetypal/template/materials/nomass_material.py index d402f0dc..4c535674 100644 --- a/archetypal/template/materials/nomass_material.py +++ b/archetypal/template/materials/nomass_material.py @@ -381,26 +381,26 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - RValue=self.r_value, - MoistureDiffusionResistance=self.MoistureDiffusionResistance, - Roughness=self.Roughness, - SolarAbsorptance=self.SolarAbsorptance, - ThermalEmittance=self.ThermalEmittance, - VisibleAbsorptance=self.VisibleAbsorptance, - Cost=self.Cost, - EmbodiedCarbon=self.EmbodiedCarbon, - EmbodiedEnergy=self.EmbodiedEnergy, - SubstitutionRatePattern=self.SubstitutionRatePattern, - SubstitutionTimestep=self.SubstitutionTimestep, - TransportCarbon=self.TransportCarbon, - TransportDistance=self.TransportDistance, - TransportEnergy=self.TransportEnergy, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "RValue": self.r_value, + "MoistureDiffusionResistance": self.MoistureDiffusionResistance, + "Roughness": self.Roughness, + "SolarAbsorptance": self.SolarAbsorptance, + "ThermalEmittance": self.ThermalEmittance, + "VisibleAbsorptance": self.VisibleAbsorptance, + "Cost": self.Cost, + "EmbodiedCarbon": self.EmbodiedCarbon, + "EmbodiedEnergy": self.EmbodiedEnergy, + "SubstitutionRatePattern": self.SubstitutionRatePattern, + "SubstitutionTimestep": self.SubstitutionTimestep, + "TransportCarbon": self.TransportCarbon, + "TransportDistance": self.TransportDistance, + "TransportEnergy": self.TransportEnergy, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def duplicate(self): """Get copy of self.""" diff --git a/archetypal/template/materials/opaque_material.py b/archetypal/template/materials/opaque_material.py index 54b73fe8..9581a671 100644 --- a/archetypal/template/materials/opaque_material.py +++ b/archetypal/template/materials/opaque_material.py @@ -524,28 +524,28 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - MoistureDiffusionResistance=self.MoistureDiffusionResistance, - Roughness=self.Roughness, - SolarAbsorptance=self.SolarAbsorptance, - SpecificHeat=self.SpecificHeat, - ThermalEmittance=self.ThermalEmittance, - VisibleAbsorptance=self.VisibleAbsorptance, - Conductivity=self.Conductivity, - Cost=self.Cost, - Density=self.Density, - EmbodiedCarbon=self.EmbodiedCarbon, - EmbodiedEnergy=self.EmbodiedEnergy, - SubstitutionRatePattern=self.SubstitutionRatePattern, - SubstitutionTimestep=self.SubstitutionTimestep, - TransportCarbon=self.TransportCarbon, - TransportDistance=self.TransportDistance, - TransportEnergy=self.TransportEnergy, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "MoistureDiffusionResistance": self.MoistureDiffusionResistance, + "Roughness": self.Roughness, + "SolarAbsorptance": self.SolarAbsorptance, + "SpecificHeat": self.SpecificHeat, + "ThermalEmittance": self.ThermalEmittance, + "VisibleAbsorptance": self.VisibleAbsorptance, + "Conductivity": self.Conductivity, + "Cost": self.Cost, + "Density": self.Density, + "EmbodiedCarbon": self.EmbodiedCarbon, + "EmbodiedEnergy": self.EmbodiedEnergy, + "SubstitutionRatePattern": self.SubstitutionRatePattern, + "SubstitutionTimestep": self.SubstitutionTimestep, + "TransportCarbon": self.TransportCarbon, + "TransportDistance": self.TransportDistance, + "TransportEnergy": self.TransportEnergy, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def duplicate(self): """Get copy of self.""" diff --git a/archetypal/template/schedule.py b/archetypal/template/schedule.py index bc664d7a..7c392c0a 100644 --- a/archetypal/template/schedule.py +++ b/archetypal/template/schedule.py @@ -237,13 +237,13 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Category=self.Category, - Type=self.Type, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "Category": self.Category, + "Type": self.Type, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def get_ref(self, ref): """Get item matching reference id. @@ -437,13 +437,13 @@ def __repr__(self): def mapping(self): """Get a dict based on the object properties, useful for dict repr.""" - return dict( - FromDay=self.FromDay, - FromMonth=self.FromMonth, - ToDay=self.ToDay, - ToMonth=self.ToMonth, - Schedule=self.Schedule, - ) + return { + "FromDay": self.FromDay, + "FromMonth": self.FromMonth, + "ToDay": self.ToDay, + "ToMonth": self.ToMonth, + "Schedule": self.Schedule, + } def get_unique(self): """Return the first of all the created objects that is equivalent to self.""" @@ -599,14 +599,14 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Category=self.Category, - Type=self.Type, - Values=self.all_values.round(3).tolist(), - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "Category": self.Category, + "Type": self.Type, + "Values": self.all_values.round(3).tolist(), + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def to_ref(self): """Return a ref pointer to self.""" @@ -778,14 +778,14 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Category=self.Category, - Days=self.Days, - Type=self.Type, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "Category": self.Category, + "Days": self.Days, + "Type": self.Type, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } @classmethod def get_days(cls, epbunch, **kwargs): @@ -973,7 +973,7 @@ def to_epbunch(self, idf): Returns: EpBunch: The EpBunch object added to the idf model. """ - new_dict = dict(Name=self.Name, Schedule_Type_Limits_Name=self.Type.to_epbunch(idf).Name) + new_dict = {"Name": self.Name, "Schedule_Type_Limits_Name": self.Type.to_epbunch(idf).Name} for i, part in enumerate(self.Parts): new_dict.update( { @@ -997,14 +997,14 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Category=self.Category, - Parts=self.Parts, - Type=self.Type, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "Category": self.Category, + "Parts": self.Parts, + "Type": self.Type, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def _get_parts(self, epbunch): parts = [] diff --git a/archetypal/template/structure.py b/archetypal/template/structure.py index 99aaea11..727fd359 100644 --- a/archetypal/template/structure.py +++ b/archetypal/template/structure.py @@ -87,11 +87,11 @@ def to_dict(self): def mapping(self): """Get a dict based on the object properties, useful for dict repr.""" - return dict( - HighLoadRatio=self.HighLoadRatio, - Material=self.Material, - NormalRatio=self.NormalRatio, - ) + return { + "HighLoadRatio": self.HighLoadRatio, + "Material": self.Material, + "NormalRatio": self.NormalRatio, + } def get_unique(self): """Return the first of all the created objects that is equivalent to self.""" @@ -220,18 +220,18 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - MassRatios=self.MassRatios, - AssemblyCarbon=self.AssemblyCarbon, - AssemblyCost=self.AssemblyCost, - AssemblyEnergy=self.AssemblyEnergy, - DisassemblyCarbon=self.DisassemblyCarbon, - DisassemblyEnergy=self.DisassemblyEnergy, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "MassRatios": self.MassRatios, + "AssemblyCarbon": self.AssemblyCarbon, + "AssemblyCost": self.AssemblyCost, + "AssemblyEnergy": self.AssemblyEnergy, + "DisassemblyCarbon": self.DisassemblyCarbon, + "DisassemblyEnergy": self.DisassemblyEnergy, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def duplicate(self): """Get copy of self.""" diff --git a/archetypal/template/umi_base.py b/archetypal/template/umi_base.py index e5f6092c..7f9ca090 100644 --- a/archetypal/template/umi_base.py +++ b/archetypal/template/umi_base.py @@ -20,7 +20,7 @@ def _resolve_combined_names(predecessors): """ # all_names = [obj.Name for obj in predecessors] - class_ = next(iter(set(obj.__class__.__name__ for obj in predecessors))) + class_ = next(iter({obj.__class__.__name__ for obj in predecessors})) return "Combined_{}_{}".format( class_, @@ -201,7 +201,7 @@ def combine_meta(self, predecessors): "Name": _resolve_combined_names(predecessors), "Comments": ( "Object composed of a combination of these objects:\n{}".format( - "\n- ".join(set(obj.Name for obj in predecessors)) + "\n- ".join({obj.Name for obj in predecessors}) ) ), "Category": ", ".join(set(itertools.chain(*[obj.Category.split(", ") for obj in predecessors]))), @@ -374,13 +374,13 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( + return { # id=self.id, - Name=self.Name, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - ) + "Name": self.Name, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + } def get_unique(self): """Return first object matching equality in the list of instantiated objects.""" @@ -466,7 +466,7 @@ def Name(self): @property def comments(self): """Get object comments.""" - return f"Object composed of a combination of these objects:\n{set(obj.Name for obj in self)}" + return f"Object composed of a combination of these objects:\n{ {obj.Name for obj in self} }" class UniqueName(str): diff --git a/archetypal/template/ventilation.py b/archetypal/template/ventilation.py index 2ea303c6..9f3a81d9 100644 --- a/archetypal/template/ventilation.py +++ b/archetypal/template/ventilation.py @@ -657,27 +657,27 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Afn=self.Afn, - IsBuoyancyOn=self.IsBuoyancyOn, - Infiltration=self.Infiltration, - IsInfiltrationOn=self.IsInfiltrationOn, - IsNatVentOn=self.IsNatVentOn, - IsScheduledVentilationOn=self.IsScheduledVentilationOn, - NatVentMaxRelHumidity=self.NatVentMaxRelHumidity, - NatVentMaxOutdoorAirTemp=self.NatVentMaxOutdoorAirTemp, - NatVentMinOutdoorAirTemp=self.NatVentMinOutdoorAirTemp, - NatVentSchedule=self.NatVentSchedule, - NatVentZoneTempSetpoint=self.NatVentZoneTempSetpoint, - ScheduledVentilationAch=self.ScheduledVentilationAch, - ScheduledVentilationSchedule=self.ScheduledVentilationSchedule, - ScheduledVentilationSetpoint=self.ScheduledVentilationSetpoint, - IsWindOn=self.IsWindOn, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "Afn": self.Afn, + "IsBuoyancyOn": self.IsBuoyancyOn, + "Infiltration": self.Infiltration, + "IsInfiltrationOn": self.IsInfiltrationOn, + "IsNatVentOn": self.IsNatVentOn, + "IsScheduledVentilationOn": self.IsScheduledVentilationOn, + "NatVentMaxRelHumidity": self.NatVentMaxRelHumidity, + "NatVentMaxOutdoorAirTemp": self.NatVentMaxOutdoorAirTemp, + "NatVentMinOutdoorAirTemp": self.NatVentMinOutdoorAirTemp, + "NatVentSchedule": self.NatVentSchedule, + "NatVentZoneTempSetpoint": self.NatVentZoneTempSetpoint, + "ScheduledVentilationAch": self.ScheduledVentilationAch, + "ScheduledVentilationSchedule": self.ScheduledVentilationSchedule, + "ScheduledVentilationSetpoint": self.ScheduledVentilationSetpoint, + "IsWindOn": self.IsWindOn, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def duplicate(self): """Get copy of self.""" diff --git a/archetypal/template/window_setting.py b/archetypal/template/window_setting.py index 02c7d36d..70536982 100644 --- a/archetypal/template/window_setting.py +++ b/archetypal/template/window_setting.py @@ -669,32 +669,34 @@ def combine(self, other, weights=None, allow_duplicates=False): log(f'using 1 as weighting factor in "{self.__class__.__name__}" ' "combine.") weights = [1.0, 1.0] meta = self._get_predecessors_meta(other) - new_attr = dict( - Construction=WindowConstruction.combine(self.Construction, other.Construction, weights), - AfnDischargeC=self.float_mean(other, "AfnDischargeC", weights), - AfnTempSetpoint=self.float_mean(other, "AfnTempSetpoint", weights), - AfnWindowAvailability=UmiSchedule.combine(self.AfnWindowAvailability, other.AfnWindowAvailability, weights), - IsShadingSystemOn=any([self.IsShadingSystemOn, other.IsShadingSystemOn]), - IsVirtualPartition=any([self.IsVirtualPartition, other.IsVirtualPartition]), - IsZoneMixingOn=any([self.IsZoneMixingOn, other.IsZoneMixingOn]), - OperableArea=self.float_mean(other, "OperableArea", weights), - ShadingSystemSetpoint=self.float_mean(other, "ShadingSystemSetpoint", weights), - ShadingSystemTransmittance=self.float_mean(other, "ShadingSystemTransmittance", weights), - ShadingSystemType=max(self.ShadingSystemType, other.ShadingSystemType), - ZoneMixingDeltaTemperature=self.float_mean(other, "ZoneMixingDeltaTemperature", weights), - ZoneMixingFlowRate=self.float_mean(other, "ZoneMixingFlowRate", weights), - ZoneMixingAvailabilitySchedule=UmiSchedule.combine( + new_attr = { + "Construction": WindowConstruction.combine(self.Construction, other.Construction, weights), + "AfnDischargeC": self.float_mean(other, "AfnDischargeC", weights), + "AfnTempSetpoint": self.float_mean(other, "AfnTempSetpoint", weights), + "AfnWindowAvailability": UmiSchedule.combine( + self.AfnWindowAvailability, other.AfnWindowAvailability, weights + ), + "IsShadingSystemOn": any([self.IsShadingSystemOn, other.IsShadingSystemOn]), + "IsVirtualPartition": any([self.IsVirtualPartition, other.IsVirtualPartition]), + "IsZoneMixingOn": any([self.IsZoneMixingOn, other.IsZoneMixingOn]), + "OperableArea": self.float_mean(other, "OperableArea", weights), + "ShadingSystemSetpoint": self.float_mean(other, "ShadingSystemSetpoint", weights), + "ShadingSystemTransmittance": self.float_mean(other, "ShadingSystemTransmittance", weights), + "ShadingSystemType": max(self.ShadingSystemType, other.ShadingSystemType), + "ZoneMixingDeltaTemperature": self.float_mean(other, "ZoneMixingDeltaTemperature", weights), + "ZoneMixingFlowRate": self.float_mean(other, "ZoneMixingFlowRate", weights), + "ZoneMixingAvailabilitySchedule": UmiSchedule.combine( self.ZoneMixingAvailabilitySchedule, other.ZoneMixingAvailabilitySchedule, weights, ), - ShadingSystemAvailabilitySchedule=UmiSchedule.combine( + "ShadingSystemAvailabilitySchedule": UmiSchedule.combine( self.ShadingSystemAvailabilitySchedule, other.ShadingSystemAvailabilitySchedule, weights, ), - Type=max(self.Type, other.Type), - ) + "Type": max(self.Type, other.Type), + } new_obj = WindowSetting(**meta, **new_attr) new_obj.predecessors.update(self.predecessors + other.predecessors) return new_obj @@ -805,28 +807,28 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - AfnDischargeC=self.AfnDischargeC, - AfnTempSetpoint=self.AfnTempSetpoint, - AfnWindowAvailability=self.AfnWindowAvailability, - Construction=self.Construction, - IsShadingSystemOn=self.IsShadingSystemOn, - IsVirtualPartition=self.IsVirtualPartition, - IsZoneMixingOn=self.IsZoneMixingOn, - OperableArea=self.OperableArea, - ShadingSystemAvailabilitySchedule=self.ShadingSystemAvailabilitySchedule, - ShadingSystemSetpoint=self.ShadingSystemSetpoint, - ShadingSystemTransmittance=self.ShadingSystemTransmittance, - ShadingSystemType=self.ShadingSystemType, - Type=self.Type, - ZoneMixingAvailabilitySchedule=self.ZoneMixingAvailabilitySchedule, - ZoneMixingDeltaTemperature=self.ZoneMixingDeltaTemperature, - ZoneMixingFlowRate=self.ZoneMixingFlowRate, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "AfnDischargeC": self.AfnDischargeC, + "AfnTempSetpoint": self.AfnTempSetpoint, + "AfnWindowAvailability": self.AfnWindowAvailability, + "Construction": self.Construction, + "IsShadingSystemOn": self.IsShadingSystemOn, + "IsVirtualPartition": self.IsVirtualPartition, + "IsZoneMixingOn": self.IsZoneMixingOn, + "OperableArea": self.OperableArea, + "ShadingSystemAvailabilitySchedule": self.ShadingSystemAvailabilitySchedule, + "ShadingSystemSetpoint": self.ShadingSystemSetpoint, + "ShadingSystemTransmittance": self.ShadingSystemTransmittance, + "ShadingSystemType": self.ShadingSystemType, + "Type": self.Type, + "ZoneMixingAvailabilitySchedule": self.ZoneMixingAvailabilitySchedule, + "ZoneMixingDeltaTemperature": self.ZoneMixingDeltaTemperature, + "ZoneMixingFlowRate": self.ZoneMixingFlowRate, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } @property def children(self): diff --git a/archetypal/template/zone_construction_set.py b/archetypal/template/zone_construction_set.py index 100f5f50..054d6d1f 100644 --- a/archetypal/template/zone_construction_set.py +++ b/archetypal/template/zone_construction_set.py @@ -457,22 +457,22 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Facade=self.Facade, - Ground=self.Ground, - Partition=self.Partition, - Roof=self.Roof, - Slab=self.Slab, - IsFacadeAdiabatic=self.IsFacadeAdiabatic, - IsGroundAdiabatic=self.IsGroundAdiabatic, - IsPartitionAdiabatic=self.IsPartitionAdiabatic, - IsRoofAdiabatic=self.IsRoofAdiabatic, - IsSlabAdiabatic=self.IsSlabAdiabatic, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - ) + return { + "Facade": self.Facade, + "Ground": self.Ground, + "Partition": self.Partition, + "Roof": self.Roof, + "Slab": self.Slab, + "IsFacadeAdiabatic": self.IsFacadeAdiabatic, + "IsGroundAdiabatic": self.IsGroundAdiabatic, + "IsPartitionAdiabatic": self.IsPartitionAdiabatic, + "IsRoofAdiabatic": self.IsRoofAdiabatic, + "IsSlabAdiabatic": self.IsSlabAdiabatic, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + } def duplicate(self): """Get copy of self.""" diff --git a/archetypal/template/zonedefinition.py b/archetypal/template/zonedefinition.py index 45f221f3..7827d374 100644 --- a/archetypal/template/zonedefinition.py +++ b/archetypal/template/zonedefinition.py @@ -605,20 +605,20 @@ def combine(self, other, weights=None, allow_duplicates=False): ) ) - new_attr = dict( - Conditioning=ZoneConditioning.combine(self.Conditioning, other.Conditioning, weights), - Constructions=ZoneConstructionSet.combine(self.Constructions, other.Constructions, weights), - Ventilation=VentilationSetting.combine(self.Ventilation, other.Ventilation), - Windows=WindowSetting.combine(self.Windows, other.Windows, weights), - DaylightMeshResolution=self.float_mean(other, "DaylightMeshResolution", weights=weights), - DaylightWorkplaneHeight=self.float_mean(other, "DaylightWorkplaneHeight", weights), - DomesticHotWater=DomesticHotWaterSetting.combine(self.DomesticHotWater, other.DomesticHotWater), - InternalMassConstruction=OpaqueConstruction.combine( + new_attr = { + "Conditioning": ZoneConditioning.combine(self.Conditioning, other.Conditioning, weights), + "Constructions": ZoneConstructionSet.combine(self.Constructions, other.Constructions, weights), + "Ventilation": VentilationSetting.combine(self.Ventilation, other.Ventilation), + "Windows": WindowSetting.combine(self.Windows, other.Windows, weights), + "DaylightMeshResolution": self.float_mean(other, "DaylightMeshResolution", weights=weights), + "DaylightWorkplaneHeight": self.float_mean(other, "DaylightWorkplaneHeight", weights), + "DomesticHotWater": DomesticHotWaterSetting.combine(self.DomesticHotWater, other.DomesticHotWater), + "InternalMassConstruction": OpaqueConstruction.combine( self.InternalMassConstruction, other.InternalMassConstruction ), - InternalMassExposedPerFloorArea=self.float_mean(other, "InternalMassExposedPerFloorArea", weights), - Loads=ZoneLoad.combine(self.Loads, other.Loads, weights), - ) + "InternalMassExposedPerFloorArea": self.float_mean(other, "InternalMassExposedPerFloorArea", weights), + "Loads": ZoneLoad.combine(self.Loads, other.Loads, weights), + } new_obj = ZoneDefinition(**meta, **new_attr) # transfer aggregated values [volume, area, occupants] to new combined zone @@ -661,30 +661,30 @@ def mapping(self, validate=False): if validate: self.validate() - return dict( - Conditioning=self.Conditioning, - Constructions=self.Constructions, - DaylightMeshResolution=self.DaylightMeshResolution, - DaylightWorkplaneHeight=self.DaylightWorkplaneHeight, - DomesticHotWater=self.DomesticHotWater, - InternalMassConstruction=self.InternalMassConstruction, - InternalMassExposedPerFloorArea=self.InternalMassExposedPerFloorArea, - Windows=self.Windows, - Loads=self.Loads, - Ventilation=self.Ventilation, - Category=self.Category, - Comments=self.Comments, - DataSource=self.DataSource, - Name=self.Name, - area=self.area, - volume=self.volume, - occupants=self.occupants, - is_part_of_conditioned_floor_area=self.is_part_of_conditioned_floor_area, - is_part_of_total_floor_area=self.is_part_of_total_floor_area, - multiplier=self.multiplier, - zone_surfaces=self.zone_surfaces, - is_core=self.is_core, - ) + return { + "Conditioning": self.Conditioning, + "Constructions": self.Constructions, + "DaylightMeshResolution": self.DaylightMeshResolution, + "DaylightWorkplaneHeight": self.DaylightWorkplaneHeight, + "DomesticHotWater": self.DomesticHotWater, + "InternalMassConstruction": self.InternalMassConstruction, + "InternalMassExposedPerFloorArea": self.InternalMassExposedPerFloorArea, + "Windows": self.Windows, + "Loads": self.Loads, + "Ventilation": self.Ventilation, + "Category": self.Category, + "Comments": self.Comments, + "DataSource": self.DataSource, + "Name": self.Name, + "area": self.area, + "volume": self.volume, + "occupants": self.occupants, + "is_part_of_conditioned_floor_area": self.is_part_of_conditioned_floor_area, + "is_part_of_total_floor_area": self.is_part_of_total_floor_area, + "multiplier": self.multiplier, + "zone_surfaces": self.zone_surfaces, + "is_core": self.is_core, + } def __add__(self, other): """Return a combination of self and other.""" diff --git a/archetypal/umi_template.py b/archetypal/umi_template.py index 19ef44a8..cb58edef 100644 --- a/archetypal/umi_template.py +++ b/archetypal/umi_template.py @@ -276,7 +276,7 @@ def from_idf_files( umi_template.BuildingTemplates = [res for res in results.values() if not isinstance(res, Exception)] if keep_all_zones: - _zones = set(obj.get_unique() for obj in ZoneDefinition._CREATED_OBJECTS) + _zones = {obj.get_unique() for obj in ZoneDefinition._CREATED_OBJECTS} for zone in _zones: umi_template.ZoneDefinitions.append(zone) exceptions = [ZoneDefinition.__name__] @@ -739,14 +739,15 @@ def to_graph(self, include_orphans=False): def no_duplicates(file: Union[str, dict], attribute="Name"): - """Assert whether dict has duplicated Names.""" + """Assert whether or not dict has duplicated Names.""" + if isinstance(file, str): with open(file) as f: data = json.loads(f.read()) else: data = file - ids = defaultdict(lambda: defaultdict(int)) + for key, value in data.items(): for component in value: _id = component.get(attribute) diff --git a/docs/examples/parallel_process.py b/docs/examples/parallel_process.py index 2a8080fe..105e325e 100644 --- a/docs/examples/parallel_process.py +++ b/docs/examples/parallel_process.py @@ -17,14 +17,14 @@ def main(): # setup the runner. We'll use the DataFrame index as keys (k). rundict = { - k: dict( - eplus_file=str(file), - prep_outputs=True, - epw=str(epw), - expandobjects=False, - verbose="v", - design_day=True, - ) + k: { + "eplus_file": str(file), + "prep_outputs": True, + "epw": str(epw), + "expandobjects": False, + "verbose": "v", + "design_day": True, + } for k, file in idfs.file.to_dict().items() } diff --git a/pyproject.toml b/pyproject.toml index 7767f5a0..5ce1862c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -100,7 +100,7 @@ select = [ # flake8-builtins # "A", # flake8-comprehensions - # "C4", + "C4", # flake8-debugger "T10", # flake8-simplify diff --git a/tests/test_dataportals.py b/tests/test_dataportals.py index 614ed2dd..3549b2db 100644 --- a/tests/test_dataportals.py +++ b/tests/test_dataportals.py @@ -220,7 +220,7 @@ def test_download_and_load_bld_window(config): def test_statcan(config): - data = dict(type="json", lang="E", dguid="2016A000011124", topic=5, notes=0) + data = {"type": "json", "lang": "E", "dguid": "2016A000011124", "topic": 5, "notes": 0} response = dataportal.stat_can_request(**data) print(response) @@ -230,7 +230,7 @@ def test_statcan(config): def test_statcan_error(config): # Tests statcan with error in inputs - data = dict(type="json", lang="E", dguid="wrong_string", topic=5, notes=0) + data = {"type": "json", "lang": "E", "dguid": "wrong_string", "topic": 5, "notes": 0} response = dataportal.stat_can_request(**data) print(response) @@ -239,7 +239,7 @@ def test_statcan_error(config): def test_statcan_geo(config): - data = dict(type="json", lang="E", geos="PR", cpt="00") + data = {"type": "json", "lang": "E", "geos": "PR", "cpt": "00"} response = dataportal.stat_can_geo_request(**data) print(response) @@ -249,7 +249,7 @@ def test_statcan_geo(config): def test_statcan_geo_error(config): # Tests statcan_geo with error in inputs - data = dict(type="json", lang="E", geos="wrong_string", cpt="00") + data = {"type": "json", "lang": "E", "geos": "wrong_string", "cpt": "00"} response = dataportal.stat_can_geo_request(**data) print(response)