Skip to content

Commit

Permalink
Code satisfies simplify rules (#516)
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 test

don't show plot in pytest

fix union error

mock test

rm test

path
  • Loading branch information
samuelduchesne committed Oct 25, 2024
1 parent 06d25ee commit 898ab75
Show file tree
Hide file tree
Showing 25 changed files with 191 additions and 285 deletions.
5 changes: 1 addition & 4 deletions archetypal/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,10 +292,7 @@ def transition(idf, to_version, cores, yes):
log(
f"executing {len(file_paths)} file(s):\n{file_list}",
)
if not yes:
overwrite = click.confirm("Would you like to overwrite the file(s)?")
else:
overwrite = False
overwrite = click.confirm("Would you like to overwrite the file(s)?") if not yes else False
start_time = time.time()

to_version = to_version.dash
Expand Down
13 changes: 7 additions & 6 deletions archetypal/eplus_interface/basement.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,13 @@ def success_callback(self):
"""Parse surface temperature and append to IDF file."""
for ep_objects in self.run_dir.glob("EPObjects*"):
if ep_objects.exists():
basement_models = self.idf.__class__(
StringIO(open(ep_objects).read()),
file_version=self.idf.file_version,
as_version=self.idf.as_version,
prep_outputs=False,
)
with open(ep_objects) as f:
basement_models = self.idf.__class__(
StringIO(f.read()),
file_version=self.idf.file_version,
as_version=self.idf.as_version,
prep_outputs=False,
)
# Loop on all objects and using self.newidfobject
added_objects = []
for sequence in basement_models.idfobjects.values():
Expand Down
73 changes: 36 additions & 37 deletions archetypal/eplus_interface/energy_plus.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,48 +196,47 @@ def run(self):
if self.p:
self.p.terminate() # terminate process to be sure
return
with logging_redirect_tqdm(loggers=[lg.getLogger("archetypal")]):
with logging_redirect_tqdm(loggers=[lg.getLogger("archetypal")]), tqdm(
unit_scale=False,
total=self.idf.energyplus_its if self.idf.energyplus_its > 0 else None,
miniters=1,
desc=f"{eplus_exe.eplus_exe_path} #{self.idf.position}-{self.idf.name}"
if self.idf.position
else f"{eplus_exe.eplus_exe_path} {self.idf.name}",
position=self.idf.position,
) as progress:
# Start process with tqdm bar
with tqdm(
unit_scale=False,
total=self.idf.energyplus_its if self.idf.energyplus_its > 0 else None,
miniters=1,
desc=f"{eplus_exe.eplus_exe_path} #{self.idf.position}-{self.idf.name}"
if self.idf.position
else f"{eplus_exe.eplus_exe_path} {self.idf.name}",
position=self.idf.position,
) as progress:
self.p = subprocess.Popen(
self.cmd,
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
start_time = time.time()
self.msg_callback("Simulation started")
self.idf._energyplus_its = 0 # reset counter
for line in self.p.stdout:
self.msg_callback(line.decode("utf-8").strip("\n"))
self.idf._energyplus_its += 1
progress.update()
self.p = subprocess.Popen(
self.cmd,
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
start_time = time.time()
self.msg_callback("Simulation started")
self.idf._energyplus_its = 0 # reset counter
for line in self.p.stdout:
self.msg_callback(line.decode("utf-8").strip("\n"))
self.idf._energyplus_its += 1
progress.update()

# We explicitly close stdout
self.p.stdout.close()
# We explicitly close stdout
self.p.stdout.close()

# Wait for process to complete
self.p.wait()
# Wait for process to complete
self.p.wait()

# Communicate callbacks
if self.cancelled:
self.msg_callback("Simulation cancelled")
self.cancelled_callback(self.std_out, self.std_err)
# Communicate callbacks
if self.cancelled:
self.msg_callback("Simulation cancelled")
self.cancelled_callback(self.std_out, self.std_err)
else:
if self.p.returncode == 0:
self.msg_callback(f"EnergyPlus Completed in {time.time() - start_time:,.2f} seconds")
self.success_callback()
else:
if self.p.returncode == 0:
self.msg_callback(f"EnergyPlus Completed in {time.time() - start_time:,.2f} seconds")
self.success_callback()
else:
self.msg_callback("Simulation failed")
self.failure_callback()
self.msg_callback("Simulation failed")
self.failure_callback()

def msg_callback(self, *args, **kwargs):
msg, *_ = args
Expand Down
13 changes: 7 additions & 6 deletions archetypal/eplus_interface/slab.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,13 @@ def success_callback(self):
"""Parse surface temperature and append to IDF file."""
for temp_schedule in self.run_dir.glob("SLABSurfaceTemps*"):
if temp_schedule.exists():
slab_models = self.idf.__class__(
StringIO(open(temp_schedule).read()),
file_version=self.idf.file_version,
as_version=self.idf.as_version,
prep_outputs=False,
)
with open(temp_schedule) as f:
slab_models = self.idf.__class__(
StringIO(f.read()),
file_version=self.idf.file_version,
as_version=self.idf.as_version,
prep_outputs=False,
)
# Loop on all objects and using self.newidfobject
added_objects = []
for sequence in slab_models.idfobjects.values():
Expand Down
9 changes: 1 addition & 8 deletions archetypal/eplus_interface/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,7 @@ def tuple(self) -> tuple:
@property
def valid_versions(self) -> set:
"""List the idd file version found on this machine."""
if not self.valid_idd_paths:
# Little hack in case E+ is not installed
_choices = {
settings.ep_version,
}
else:
_choices = set(self.valid_idd_paths.keys())

_choices = {settings.ep_version} if not self.valid_idd_paths else set(self.valid_idd_paths.keys())
return _choices

@property
Expand Down
2 changes: 1 addition & 1 deletion archetypal/idfclass/end_use_balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ def separate_gains_and_losses(self, component, level="Key_Name") -> EnergyDataFr
Returns:
"""
assert component in self.__dict__.keys(), f"{component} is not a valid attribute of EndUseBalance."
assert component in self.__dict__, f"{component} is not a valid attribute of EndUseBalance."
component_df = getattr(self, component)
assert not component_df.empty, "Expected a component that is not empty."
print(component)
Expand Down
17 changes: 5 additions & 12 deletions archetypal/idfclass/extensions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Eppy extensions module."""

import contextlib
import copy

from eppy.bunch_subclass import BadEPFieldError
Expand Down Expand Up @@ -31,7 +32,7 @@ def nameexists(self: EpBunch):
@extend_class(EpBunch)
def get_default(self: EpBunch, name):
"""Return the default value of a field"""
if "default" in self.getfieldidd(name).keys():
if "default" in self.getfieldidd(name):
_type = _parse_idd_type(self, name)
default_ = next(iter(self.getfieldidd_item(name, "default")), None)
return _type(default_)
Expand Down Expand Up @@ -85,10 +86,8 @@ def makedict(self: Eplusdata, dictfile, fnamefobject):
dt, dtls = self.initdict(dictfile)
fnamefobject.seek(0) # make sure to read from the beginning
astr = fnamefobject.read()
try:
with contextlib.suppress(AttributeError):
astr = astr.decode("ISO-8859-2")
except AttributeError:
pass
nocom = removecomment(astr, "!")
idfst = nocom
# alist = string.split(idfst, ';')
Expand Down Expand Up @@ -131,14 +130,8 @@ def _parse_idd_type(epbunch, name):
- node -> str (name used in connecting HVAC components)
"""
_type = next(iter(epbunch.getfieldidd_item(name, "type")), "").lower()
if _type == "real":
return float
elif _type == "alpha":
return str
elif _type == "integer":
return int
else:
return str
type_mapping = {"real": float, "alpha": str, "integer": int}
return type_mapping.get(_type, str)


# relationship between epbunch output frequency and db.
Expand Down
Loading

0 comments on commit 898ab75

Please sign in to comment.