Skip to content

Commit

Permalink
code satisfies A rules (#518)
Browse files Browse the repository at this point in the history
* 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 A rules

* fix typing

* fix type to format change
  • Loading branch information
samuelduchesne authored Oct 25, 2024
1 parent 9e7400c commit 5803f23
Show file tree
Hide file tree
Showing 15 changed files with 99 additions and 102 deletions.
20 changes: 9 additions & 11 deletions archetypal/dataportal.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,12 +530,11 @@ def nrel_bcl_api_request(data):
return response_json


def stat_can_request(type, lang="E", dguid="2016A000011124", topic=0, notes=0, stat=0):
"""Send a request to the StatCan API via HTTP GET and return the JSON
response.
def stat_can_request(response_format, lang="E", dguid="2016A000011124", topic=0, notes=0, stat=0):
"""Send a request to the StatCan API via HTTP GET and return the JSON response.
Args:
type (str): "json" or "xml". json = json response format and xml = xml
response_format (str): "json" or "xml". json = json response format and xml = xml
response format.
lang (str): "E" or "F". E = English and F = French.
dguid (str): Dissemination Geography Unique Identifier - DGUID. It is an
Expand All @@ -560,7 +559,7 @@ def stat_can_request(type, lang="E", dguid="2016A000011124", topic=0, notes=0, s
"""
prepared_url = (
"https://www12.statcan.gc.ca/rest/census-recensement"
f"/CPR2016.{type}?lang={lang}&dguid={dguid}&topic="
f"/CPR2016.{response_format}?lang={lang}&dguid={dguid}&topic="
f"{topic}&notes={notes}&stat={stat}"
)

Expand Down Expand Up @@ -612,10 +611,11 @@ def stat_can_request(type, lang="E", dguid="2016A000011124", topic=0, notes=0, s
return response_json


def stat_can_geo_request(type="json", lang="E", geos="PR", cpt="00"):
"""
def stat_can_geo_request(response_format="json", lang="E", geos="PR", cpt="00"):
"""Send a request to the StatCan API via HTTP GET and return the JSON response.
Args:
type (str): "json" or "xml". json = json response format and xml = xml
response_format (str): "json" or "xml". json = json response format and xml = xml
response format.
lang (str): "E" or "F". where: E = English F = French.
geos (str): one geographic level code (default = PR). where: CD = Census
Expand All @@ -632,9 +632,7 @@ def stat_can_geo_request(type="json", lang="E", geos="PR", cpt="00"):
35 = Ontario 46 = Manitoba 47 = Saskatchewan 48 = Alberta 59 =
British Columbia 60 = Yukon 61 = Northwest Territories 62 = Nunavut.
"""
prepared_url = (
f"https://www12.statcan.gc.ca/rest/census-recensement/CR2016Geo.{type}?lang={lang}&geos={geos}&cpt={cpt}"
)
prepared_url = f"https://www12.statcan.gc.ca/rest/census-recensement/CR2016Geo.{response_format}?lang={lang}&geos={geos}&cpt={cpt}"

cached_response_json = get_from_cache(prepared_url)

Expand Down
2 changes: 1 addition & 1 deletion archetypal/eplus_interface/energy_plus.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __init__(
annual=False,
convert=False,
design_day=False,
help=False,
help=False, # noqa: A002
idd=None,
epmacro=False,
output_prefix="eplus",
Expand Down
8 changes: 4 additions & 4 deletions archetypal/eplus_interface/transition.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ def copytree(src, dst, symlinks=False, ignore=None):
if self._trans_exec is None:
copytree(self.idf.idfversionupdater_dir, self.running_directory)
self._trans_exec = {
EnergyPlusVersion(re.search(r"to-V(([\d]*?)-([\d]*?)-([\d]))", exec).group(1)): exec
for exec in self.running_directory.files("Transition-V*")
EnergyPlusVersion(re.search(r"to-V(([\d]*?)-([\d]*?)-([\d]))", execution).group(1)): execution
for execution in self.running_directory.files("Transition-V*")
}
return self._trans_exec

Expand Down Expand Up @@ -239,8 +239,8 @@ def stop(self):
def trans_exec(self) -> dict:
"""Return dict of {EnergyPlusVersion, executable} for each transitions."""
return {
EnergyPlusVersion(re.search(r"to-V(([\d]*?)-([\d]*?)-([\d]))", exec).group(1)): exec
for exec in self.idf.idfversionupdater_dir.files("Transition-V*")
EnergyPlusVersion(re.search(r"to-V(([\d]*?)-([\d]*?)-([\d]))", execution).group(1)): execution
for execution in self.idf.idfversionupdater_dir.files("Transition-V*")
}

@property
Expand Down
2 changes: 1 addition & 1 deletion archetypal/eplus_interface/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def current_install_dir(self):
raise EnergyPlusVersionError(f"EnergyPlusVersion {self.dash} is not installed.") from e

@property
def tuple(self) -> tuple:
def tuple(self) -> tuple: # noqa: A003
"""Return the version number as a tuple: (major, minor, micro)."""
return self.major, self.minor, self.micro

Expand Down
9 changes: 6 additions & 3 deletions archetypal/idfclass/outputs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from __future__ import annotations

from collections.abc import Iterable
from typing import Literal

from archetypal.idfclass.end_use_balance import EndUseBalance
from archetypal.idfclass.extensions import get_name_attribute
Expand Down Expand Up @@ -294,7 +297,7 @@ def add_schedules(self):
self._other_outputs.append(output)
return self

def add_meter_variables(self, format="IDF"):
def add_meter_variables(self, key_field: Literal["IDF", "regular"] = "IDF"):
"""Generate .mdd file at end of simulation. This file (from the
Output:VariableDictionary, regular; and Output:VariableDictionary,
IDF; commands) shows all the report meters along with their “availability”
Expand All @@ -304,12 +307,12 @@ def add_meter_variables(self, format="IDF"):
Output Reference) and IDF (ready to be copied and pasted into your Input File).
Args:
format (str): Choices are "IDF" and "regul
key_field (str): Choices are IDF, regular
Returns:
Outputs: self
"""
outputs = [{"key": "Output:VariableDictionary".upper(), "Key_Field": format}]
outputs = [{"key": "Output:VariableDictionary".upper(), "Key_Field": key_field}]
for output in outputs:
self._other_outputs.append(output)
return self
Expand Down
14 changes: 8 additions & 6 deletions archetypal/reportdata.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
""""""

from __future__ import annotations

import functools
import time

Expand Down Expand Up @@ -177,7 +179,7 @@ def filter_report_data(
reportdatadictionaryindex=None,
value=None,
ismeter=None,
type=None,
report_type=None,
indexgroup=None,
timesteptype=None,
keyvalue=None,
Expand All @@ -198,7 +200,7 @@ def filter_report_data(
reportdatadictionaryindex (str or tuple):
value (str or tuple):
ismeter (str or tuple):
type (str or tuple):
report_type (str or tuple):
indexgroup (str or tuple):
timesteptype (str or tuple):
keyvalue (str or tuple):
Expand Down Expand Up @@ -277,11 +279,11 @@ def filter_report_data(
else self[self.ISMETER] == ismeter
)
c_n.append(c_6)
if type:
if report_type:
c_7 = (
conjunction(*[self[self.TYPE] == type for type in type], logical=np.logical_or)
if isinstance(type, tuple)
else self[self.TYPE] == type
conjunction(*[self[self.TYPE] == t for t in report_type], logical=np.logical_or)
if isinstance(report_type, tuple)
else self[self.TYPE] == report_type
)
c_n.append(c_7)
if indexgroup:
Expand Down
4 changes: 2 additions & 2 deletions archetypal/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -1157,12 +1157,12 @@ def all_values(self, value):
self._values = validators.iterable(value, maximum_length=8760)

@property
def max(self):
def max(self): # noqa: A003
"""Get the maximum value of the schedule."""
return max(self.all_values)

@property
def min(self):
def min(self): # noqa: A003
"""Get the minimum value of the schedule."""
return min(self.all_values)

Expand Down
64 changes: 32 additions & 32 deletions archetypal/simple_glazing.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def calc_simple_glazing(shgc, u_factor, visible_transmittance=None):
"various resistances can be negative."
)

dict = {}
glazing = {}

# Step 1. Determine glass-to-glass Resistance.

Expand Down Expand Up @@ -110,41 +110,41 @@ def calc_simple_glazing(shgc, u_factor, visible_transmittance=None):
T_vis -= (T_vis + R_vis_b - 1) * 1.1

# Last Step. Saving results to dict
dict["SolarHeatGainCoefficient"] = shgc
dict["UFactor"] = u_factor
dict["Conductivity"] = Lambda_eff
dict["Thickness"] = Thickness
dict["SolarTransmittance"] = T_sol
dict["SolarReflectanceFront"] = R_s_f
dict["SolarReflectanceBack"] = R_s_b
dict["IRTransmittance"] = 0.0
dict["VisibleTransmittance"] = T_vis
dict["VisibleReflectanceFront"] = R_vis_f
dict["VisibleReflectanceBack"] = R_vis_b
dict["IREmissivityFront"] = 0.84
dict["IREmissivityBack"] = 0.84
dict["DirtFactor"] = 1.0 # Clean glass

dict["Cost"] = 0
dict["Density"] = 2500
dict["EmbodiedCarbon"] = 0
dict["EmbodiedCarbonStdDev"] = 0
dict["EmbodiedEnergy"] = 0
dict["EmbodiedEnergyStdDev"] = 0
dict["Life"] = 1
dict["SubstitutionRatePattern"] = [1.0]
dict["SubstitutionTimestep"] = 0
dict["TransportCarbon"] = 0
dict["TransportDistance"] = 0
dict["TransportEnergy"] = 0
dict["Type"] = "Uncoated" # TODO Further investigation necessary

dict["Comments"] = (
glazing["SolarHeatGainCoefficient"] = shgc
glazing["UFactor"] = u_factor
glazing["Conductivity"] = Lambda_eff
glazing["Thickness"] = Thickness
glazing["SolarTransmittance"] = T_sol
glazing["SolarReflectanceFront"] = R_s_f
glazing["SolarReflectanceBack"] = R_s_b
glazing["IRTransmittance"] = 0.0
glazing["VisibleTransmittance"] = T_vis
glazing["VisibleReflectanceFront"] = R_vis_f
glazing["VisibleReflectanceBack"] = R_vis_b
glazing["IREmissivityFront"] = 0.84
glazing["IREmissivityBack"] = 0.84
glazing["DirtFactor"] = 1.0 # Clean glass

glazing["Cost"] = 0
glazing["Density"] = 2500
glazing["EmbodiedCarbon"] = 0
glazing["EmbodiedCarbonStdDev"] = 0
glazing["EmbodiedEnergy"] = 0
glazing["EmbodiedEnergyStdDev"] = 0
glazing["Life"] = 1
glazing["SubstitutionRatePattern"] = [1.0]
glazing["SubstitutionTimestep"] = 0
glazing["TransportCarbon"] = 0
glazing["TransportDistance"] = 0
glazing["TransportEnergy"] = 0
glazing["Type"] = "Uncoated" # TODO Further investigation necessary

glazing["Comments"] = (
"Properties calculated from Simple Glazing System with "
f"SHGC={shgc:.3f}, UFactor={u_factor:.3f} and Tvis={T_vis:.3f}"
)

return dict
return glazing


# region Step 1. Determine glass-to-glass Resistance
Expand Down
48 changes: 21 additions & 27 deletions archetypal/template/conditioning.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,24 +737,18 @@ def _set_economizer(self, zone: "ZoneDefinition", zone_ep: EpBunch):
controllers_in_idf = zone_ep.theidf.idfobjects["Controller:OutdoorAir".upper()]
self.EconomizerType = EconomizerTypes.NoEconomizer # default value

for object in controllers_in_idf:
if object.Economizer_Control_Type == "NoEconomizer":
for obj in controllers_in_idf:
if obj.Economizer_Control_Type == "NoEconomizer":
self.EconomizerType = EconomizerTypes.NoEconomizer
elif object.Economizer_Control_Type == "DifferentialEnthalphy":
elif obj.Economizer_Control_Type == "DifferentialEnthalphy":
self.EconomizerType = EconomizerTypes.DifferentialEnthalphy
elif (
object.Economizer_Control_Type == "DifferentialDryBulb"
or object.Economizer_Control_Type == "FixedDryBulb"
):
elif obj.Economizer_Control_Type == "DifferentialDryBulb" or obj.Economizer_Control_Type == "FixedDryBulb":
self.EconomizerType = EconomizerTypes.DifferentialDryBulb
elif (
object.Economizer_Control_Type == "FixedEnthalpy"
or object.Economizer_Control_Type == "ElectronicEnthalpy"
):
elif obj.Economizer_Control_Type == "FixedEnthalpy" or obj.Economizer_Control_Type == "ElectronicEnthalpy":
self.EconomizerType = EconomizerTypes.DifferentialEnthalphy
elif object.Economizer_Control_Type == "FixedDewPointAndDryBulb":
elif obj.Economizer_Control_Type == "FixedDewPointAndDryBulb":
self.EconomizerType = EconomizerTypes.DifferentialDryBulb
elif object.Economizer_Control_Type == "DifferentialDryBulbAndEnthalpy":
elif obj.Economizer_Control_Type == "DifferentialDryBulbAndEnthalpy":
self.EconomizerType = EconomizerTypes.DifferentialEnthalphy

def _set_mechanical_ventilation(self, zone: "ZoneDefinition", zone_ep: EpBunch):
Expand Down Expand Up @@ -1149,13 +1143,13 @@ def _set_heat_recovery(self, zone: "ZoneDefinition", zone_ep: EpBunch):
comment = ""

# iterate over those objects. If the list is empty, it will simply pass.
for object in heat_recovery_in_idf:
if object.key.upper() == "HeatExchanger:AirToAir:FlatPlate".upper():
for obj in heat_recovery_in_idf:
if obj.key.upper() == "HeatExchanger:AirToAir:FlatPlate".upper():
# Do HeatExchanger:AirToAir:FlatPlate

nsaot = object.Nominal_Supply_Air_Outlet_Temperature
nsait = object.Nominal_Supply_Air_Inlet_Temperature
n2ait = object.Nominal_Secondary_Air_Inlet_Temperature
nsaot = obj.Nominal_Supply_Air_Outlet_Temperature
nsait = obj.Nominal_Supply_Air_Inlet_Temperature
n2ait = obj.Nominal_Secondary_Air_Inlet_Temperature
HeatRecoveryEfficiencySensible = (nsaot - nsait) / (n2ait - nsait)
# Hypotheses: HeatRecoveryEfficiencySensible - 0.05
HeatRecoveryEfficiencyLatent = HeatRecoveryEfficiencySensible - 0.05
Expand All @@ -1167,25 +1161,25 @@ def _set_heat_recovery(self, zone: "ZoneDefinition", zone_ep: EpBunch):
"Supply Air Inlet T°C)"
)

elif object.key.upper() == "HeatExchanger:AirToAir:SensibleAndLatent".upper():
elif obj.key.upper() == "HeatExchanger:AirToAir:SensibleAndLatent".upper():
# Do HeatExchanger:AirToAir:SensibleAndLatent calculation

HeatRecoveryEfficiencyLatent = object.Latent_Effectiveness_at_100_Heating_Air_Flow
HeatRecoveryEfficiencySensible = object.Sensible_Effectiveness_at_100_Heating_Air_Flow
HeatRecoveryEfficiencyLatent = obj.Latent_Effectiveness_at_100_Heating_Air_Flow
HeatRecoveryEfficiencySensible = obj.Sensible_Effectiveness_at_100_Heating_Air_Flow
HeatRecoveryType = HeatRecoveryTypes.Enthalpy

elif object.key.upper() == "HeatExchanger:Desiccant:BalancedFlow".upper():
elif obj.key.upper() == "HeatExchanger:Desiccant:BalancedFlow".upper():
# Do HeatExchanger:Dessicant:BalancedFlow
# Use default values
HeatRecoveryEfficiencyLatent = 0.65
HeatRecoveryEfficiencySensible = 0.7
HeatRecoveryType = HeatRecoveryTypes.Enthalpy

elif object.key.upper() == "HeatExchanger:Desiccant:BalancedFlow:PerformanceDataType1".upper():
elif obj.key.upper() == "HeatExchanger:Desiccant:BalancedFlow:PerformanceDataType1".upper():
# This is not an actual HeatExchanger, pass
pass
else:
msg = f'Heat exchanger object "{object}" is not ' "implemented"
msg = f'Heat exchanger object "{obj}" is not ' "implemented"
raise NotImplementedError(msg)

self.HeatRecoveryEfficiencyLatent = HeatRecoveryEfficiencyLatent
Expand All @@ -1194,7 +1188,7 @@ def _set_heat_recovery(self, zone: "ZoneDefinition", zone_ep: EpBunch):
self.Comments += comment

@staticmethod
def _get_recoverty_effectiveness(object, zone, zone_ep):
def _get_recoverty_effectiveness(obj, zone, zone_ep):
rd = ReportData.from_sql_dict(zone_ep.theidf.sql())
effectiveness = (
rd.filter_report_data(
Expand All @@ -1208,8 +1202,8 @@ def _get_recoverty_effectiveness(object, zone, zone_ep):
.Value.mean()
.unstack(level=-1)
)
HeatRecoveryEfficiencySensible = effectiveness.loc[object.Name.upper(), "Heat Exchanger Sensible Effectiveness"]
HeatRecoveryEfficiencyLatent = effectiveness.loc[object.Name.upper(), "Heat Exchanger Latent Effectiveness"]
HeatRecoveryEfficiencySensible = effectiveness.loc[obj.Name.upper(), "Heat Exchanger Sensible Effectiveness"]
HeatRecoveryEfficiencyLatent = effectiveness.loc[obj.Name.upper(), "Heat Exchanger Latent Effectiveness"]
return HeatRecoveryEfficiencyLatent, HeatRecoveryEfficiencySensible

@staticmethod
Expand Down
6 changes: 3 additions & 3 deletions archetypal/template/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,13 +268,13 @@ def __repr__(self):
"""Return a representation of self."""
name = self.Name
resample = self.series.resample("D")
min = resample.min().mean()
low = resample.min().mean()
mean = resample.mean().mean()
max = resample.max().mean()
high = resample.max().mean()
return (
name
+ ": "
+ f"mean daily min:{min:.2f} mean:{mean:.2f} max:{max:.2f} "
+ f"mean daily min:{low:.2f} mean:{mean:.2f} max:{high:.2f} "
+ (f"quantity {self.quantity}" if self.quantity is not None else "")
)

Expand Down
Loading

0 comments on commit 5803f23

Please sign in to comment.