Skip to content

Commit

Permalink
bump more dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
nllong committed Jan 11, 2025
1 parent 82de8e9 commit f6a157c
Show file tree
Hide file tree
Showing 13 changed files with 91 additions and 68 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ repos:
pass_filenames: false
# https://docs.astral.sh/ruff/integrations/#pre-commit
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
# Run the linter
- id: ruff
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,7 @@ def post_process(self, scaffold, keep_original_models=False):
"Boolean",
"use_moisture_balance",
assigned_value=use_moisture_balance,
string_comment="If true, input connector QLat_flow is enabled and room air computes"
" moisture balance.",
string_comment="If true, input connector QLat_flow is enabled and room air computes moisture balance.",
)
# create a integer parameter to evaluate number of connected ports.
mofile.add_parameter(
Expand Down Expand Up @@ -476,7 +475,7 @@ def post_process(self, scaffold, keep_original_models=False):

# Save as the new filename (without building ID)
new_filename = os.path.join(
scaffold.loads_path.files_dir, f'{self.building_name}/{os.path.basename(f).split("_")[1]}'
scaffold.loads_path.files_dir, f"{self.building_name}/{os.path.basename(f).split('_')[1]}"
)
mofile.save_as(new_filename)
os.remove(f)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ def to_modelica(self, scaffold):
except FileNotFoundError:
raise SystemExit(
f"Can't find g-function file for ghe with ID: {template_data['gfunction']['ghe_id']}.\n"
'If using a relative path to your ghe_dir, your path '
f' \'{template_data["gfunction"]["input_path"]}\' must be relative to the dir your '
'sys-param file is in.'
"If using a relative path to your ghe_dir, your path "
f" '{template_data['gfunction']['input_path']}' must be relative to the dir your "
"sys-param file is in."
)
template_data["gfunction"]["gfunction_file_rows"] = gfunction.shape[0] + 1

Expand Down
2 changes: 1 addition & 1 deletion geojson_modelica_translator/modelica/csv_modelica.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def timeseries_to_modelica_data(
line2 = f"{data_type} {output_modelica_file_name}({size[0]}, {size[1]})"
line3 = "#Nominal heating water mass flow rate=" + str(self.nominal_heating_mass_flow_rate.loc[0, "#value"])
line4 = "#Nominal chilled water mass flow rate=" + str(self.nominal_cooling_mass_flow_rate.loc[0, "#value"])
f.write(f"{line1}\n" f"{line2}\n" f"{line3}\n" f"{line4}\n")
f.write(f"{line1}\n{line2}\n{line3}\n{line4}\n")
if "SecondsFromStart" in self.timeseries_output.columns:
self.timeseries_output.to_csv(f, header=True, index=False)
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def download_weatherfile(self, filename, save_directory: str) -> Union[str, Path
f"Returned non 200 status code trying to download weather file: {weatherfile_data.status_code}"
)
except requests.exceptions.RequestException as e:
raise requests.exceptions.RequestException(f"Could not download weather file: {weatherfile_url}" f"\n{e}")
raise requests.exceptions.RequestException(f"Could not download weather file: {weatherfile_url}\n{e}")

if not outputname.exists():
raise FileNotFoundError(f"Could not find or download weather file for {p_download!s}")
Expand Down
6 changes: 3 additions & 3 deletions management/check_sys_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,11 +240,11 @@ def check_sys_params(v, vv, output_file, log_file):
for idx, param in enumerate(params):
print(delimiter, file=output_file_handle)
if param["skip"]:
print(f'{param["path"]} Skipped (duplicate)', file=output_file_handle)
print(f"{param['path']} Skipped (duplicate)", file=output_file_handle)
continue

if param["type"] == "string":
print(f'{param["path"]} Skipped (string)', file=output_file_handle)
print(f"{param['path']} Skipped (string)", file=output_file_handle)
continue

jsonpath = parse(param["path"])
Expand All @@ -269,7 +269,7 @@ def check_sys_params(v, vv, output_file, log_file):
test_sys_params_path = fp.name
create_package(test_package_path, baseline_geojson_path, test_sys_params_path)

print(f'{param["path"]} Testing Original: {original_value}; New: {value}', file=output_file_handle)
print(f"{param['path']} Testing Original: {original_value}; New: {value}", file=output_file_handle)

# compare the package to baseline (find diffs)
print_diffs(baseline_package_path, test_package_path, output_file_handle)
Expand Down
62 changes: 40 additions & 22 deletions management/format_modelica_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,19 @@
import os
import re
import subprocess
import sys
from pathlib import Path
from tempfile import mkstemp

import click

SKIP_FILES = ["DistrictEnergySystem.mot", "DistrictEnergySystem5G.mot"]
TEMPLATE_FILES = Path("geojson_modelica_translator/model_connectors").glob("**/templates/*")
project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
sys.path.append(project_root)


@click.command()
@click.argument("mofile", required=False)
def fmt_modelica_files(mofile):
if mofile is not None:
files = [mofile]
else:
files = TEMPLATE_FILES

for filepath in files:
if os.path.basename(filepath) in SKIP_FILES:
continue
try:
if filepath.suffix == ".mot":
preprocess_and_format(str(filepath))
elif filepath.suffix == ".mo":
apply_formatter(str(filepath))
except FormattingError as e:
click.echo(f"Error processing file {filepath}:\n {e}", err=True)
SKIP_FILES = ["DistrictEnergySystem.mot", "DistrictEnergySystem5G.mot"]
TEMPLATE_FILES = Path("geojson_modelica_translator/model_connectors").glob("**/templates/*")


class FormattingError(Exception):
Expand Down Expand Up @@ -97,7 +83,7 @@ def sub_generic(text, sub_map):
matches = reversed([m.span() for m in GENERIC_CONTROL_REGEX.finditer(text)])
for span in matches:
sub_id = sub_map.add_sub(text[span[0] : span[1]])
text = f"{text[:span[0]]}/*{sub_id}*/{text[span[1]:]}"
text = f"{text[: span[0]]}/*{sub_id}*/{text[span[1] :]}"

return text

Expand All @@ -115,7 +101,7 @@ def sub_expression(text, sub_map):
matches = reversed([m.span() for m in EXPRESSION_REGEX.finditer(text)])
for span in matches:
sub_id = sub_map.add_sub(text[span[0] : span[1]])
text = f"{text[:span[0]]}{sub_id}{text[span[1]:]}"
text = f"{text[: span[0]]}{sub_id}{text[span[1] :]}"

return text

Expand Down Expand Up @@ -201,3 +187,35 @@ def preprocess_and_format(filename, outfilename=None):
f.write(formatted_result)
finally:
os.remove(tmp_filepath)


@click.command()
@click.argument("mofile", required=False)
@click.argument("debug", required=False)
def format_modelica_files(mofile=None, debug=False):
if mofile is not None:
files = [mofile]
else:
files = TEMPLATE_FILES

for filepath in files:
if os.path.basename(filepath) in SKIP_FILES:
continue
try:
print(f"Formatting mo/mot file: {filepath}")
# Can't format mopt yet.
if filepath.suffix == ".mot":
if debug:
print(f"Formatting mot file: {filepath}")
preprocess_and_format(str(filepath))
elif filepath.suffix == ".mo":
if debug:
print(f"Formatting mo file: {filepath}")
apply_formatter(str(filepath))
except FormattingError as e:
click.echo(f"Error processing file {filepath}:\n {e}", err=True)


if __name__ == "__main__":
"""Method to call this python script manually to format files"""
format_modelica_files(mofile=None, debug=True)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ build-backend = "poetry.core.masonry.api"

[tool.poetry.scripts]
uo_des = 'management.uo_des:cli'
format_modelica_files = 'management.format_modelica_files:fmt_modelica_files'
format_modelica_files = "management.format_modelica_files:format_modelica_files"
check_sys_params = 'management.check_sys_params:check_sys_params'

[tool.pytest.ini_options]
Expand Down
24 changes: 12 additions & 12 deletions tests/geojson_modelica_translator/test_results_ghp.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ def test_result(self):

assert "Datetime" in csv_data.columns, "The 'Datetime' column is missing from the CSV file."

assert (
"heating_electric_power_d55aa383" in csv_data.columns
), "The heating_electric_power column is missing from the CSV file."
assert "heating_electric_power_d55aa383" in csv_data.columns, (
"The heating_electric_power column is missing from the CSV file."
)

assert "pump_power_3da62a1d" in csv_data.columns, "The pump_power column is missing from the CSV file."

assert (
"electrical_power_consumed" in csv_data.columns
), "The electrical_power_consumed column is missing from the CSV file."
assert "electrical_power_consumed" in csv_data.columns, (
"The electrical_power_consumed column is missing from the CSV file."
)

def test_result_multiple_ghp(self):
# Construct the path to the Modelica project directory
Expand Down Expand Up @@ -83,9 +83,9 @@ def test_result_multiple_ghp(self):

assert heating_electric_power, "No columns with 'heating_electric_power' found in the CSV file."

assert (
len(heating_electric_power) == 13
), f"Expected 13 columns with 'heating_electric_power_' but found {len(heating_electric_power)}."
assert len(heating_electric_power) == 13, (
f"Expected 13 columns with 'heating_electric_power_' but found {len(heating_electric_power)}."
)

pump_power = [col for col in csv_data_multiple.columns if "pump_power_" in col]

Expand All @@ -94,6 +94,6 @@ def test_result_multiple_ghp(self):

assert len(pump_power) == 26, f"Expected 26 columns with 'pump_power' but found {len(pump_power)}."

assert (
"electrical_power_consumed" in csv_data_multiple.columns
), "The electrical_power_consumed column is missing from the CSV file."
assert "electrical_power_consumed" in csv_data_multiple.columns, (
"The electrical_power_consumed column is missing from the CSV file."
)
6 changes: 3 additions & 3 deletions tests/management/test_format_modelica_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ def test_no_meaningful_diff_when_formatting_mot_files(self):
with open(file_) as orig, open(outfilepath) as new:
orig_stripped = re.sub(r"\s", "", orig.read())
new_stripped = re.sub(r"\s", "", new.read())
assert (
orig_stripped == new_stripped
), f"Original and formatted files for {file_} should have the same content"
assert orig_stripped == new_stripped, (
f"Original and formatted files for {file_} should have the same content"
)
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,15 @@ def test_simulate_district_heating_and_cooling_systems(self):
(_, cool_m_flow_nominal) = mat_results.values(f"{load.id}.mChiWat_flow_nominal")
cool_m_flow_nominal = cool_m_flow_nominal[0]

assert (
heat_m_flow <= pytest.approx(heat_m_flow_nominal, rel=m_flow_nominal_tolerance).all()
), f"Heating mass flow rate must be less than nominal mass flow rate ({heat_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)" # noqa: E501
assert heat_m_flow <= pytest.approx(heat_m_flow_nominal, rel=m_flow_nominal_tolerance).all(), (
f"Heating mass flow rate must be less than nominal "
f"mass flow rate ({heat_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)"
)

assert (
cool_m_flow <= pytest.approx(cool_m_flow_nominal, rel=m_flow_nominal_tolerance).all()
), f"Cooling mass flow rate must be less than nominal mass flow rate ({cool_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)" # noqa: E501
assert cool_m_flow <= pytest.approx(cool_m_flow_nominal, rel=m_flow_nominal_tolerance).all(), (
"Cooling mass flow rate must be less than nominal "
f"mass flow rate ({cool_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)"
)

# check the thermal load
(_, load_q_req_hea_flow) = mat_results.values(f"{load.id}.QReqHea_flow")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,12 @@ def test_simulate_spawn_district_heating_and_cooling_systems(self):
(_, cool_m_flow_nominal) = mat_results.values(f"{load.id}.mLoaCoo_flow_nominal[1]")
cool_m_flow_nominal = cool_m_flow_nominal[0]

assert (
heat_m_flow <= pytest.approx(heat_m_flow_nominal, rel=m_flow_nominal_tolerance).all()
), f"Heating mass flow rate must be less than nominal mass flow rate ({heat_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)" # noqa: E501
assert heat_m_flow <= pytest.approx(heat_m_flow_nominal, rel=m_flow_nominal_tolerance).all(), (
"Heating mass flow rate must be less than nominal "
f"mass flow rate ({heat_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)"
)

assert (
cool_m_flow <= pytest.approx(cool_m_flow_nominal, rel=m_flow_nominal_tolerance).all()
), f"Cooling mass flow rate must be less than nominal mass flow rate ({cool_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)" # noqa: E501
assert cool_m_flow <= pytest.approx(cool_m_flow_nominal, rel=m_flow_nominal_tolerance).all(), (
"Cooling mass flow rate must be less than nominal "
f"mass flow rate ({cool_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)"
)
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,11 @@ def test_teaser_district_heating_and_cooling_systems(self):
(_, cool_m_flow_nominal) = mat_results.values(f"{load.id}.terUni[1].mLoaCoo_flow_nominal")
cool_m_flow_nominal = cool_m_flow_nominal[0]

assert (
heat_m_flow <= pytest.approx(heat_m_flow_nominal, rel=m_flow_nominal_tolerance).all()
), f"Heating mass flow rate must be less than nominal mass flow rate ({heat_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)" # noqa: E501
assert (
cool_m_flow <= pytest.approx(cool_m_flow_nominal, rel=m_flow_nominal_tolerance).all()
), f"Cooling mass flow rate must be less than nominal mass flow rate ({cool_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)" # noqa: E501
assert heat_m_flow <= pytest.approx(heat_m_flow_nominal, rel=m_flow_nominal_tolerance).all(), (
"Heating mass flow rate must be less than nominal "
f"mass flow rate ({heat_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)"
)
assert cool_m_flow <= pytest.approx(cool_m_flow_nominal, rel=m_flow_nominal_tolerance).all(), (
"Cooling mass flow rate must be less than nominal "
f"mass flow rate ({cool_m_flow_nominal}) plus a tolerance ({m_flow_nominal_tolerance * 100}%)"
)

0 comments on commit f6a157c

Please sign in to comment.