Skip to content

Commit

Permalink
Support Python 3.12 (#593)
Browse files Browse the repository at this point in the history
* update pre-commit hooks with `pre-commit autoupdate`

* support python 3.12

* update dependencies

* run tests on python 3.12

* tell pypi we support python 3.12

* autopep8

* don't reformat a long line because it makes the quotes weird

* don't reformat another long line because it makes the quotes weird

* point to develop branch of modelica-builder now that 3.12 support has been merged

* update dependencies

* use new release of geojson that supportys python 3.12

* update dependencies with `poetry update`

* update dependencies

* update dependencies

* use newly released version of modelica-builder

* update dependencies

* use a branch of modelica-builder

* update dependencies

* bump versions of actions in pypi_release workflow. inconsequential.

* use new patch version of modelica-builder so models build properly

---------

Co-authored-by: Nicholas Long <nicholas.long@nrel.gov>
  • Loading branch information
vtnate and nllong authored Jan 6, 2024
1 parent c46b33d commit b7f5835
Show file tree
Hide file tree
Showing 12 changed files with 304 additions and 252 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
python-version: ["3.10", "3.11"]
python-version: ["3.10", "3.12"]
test_env: [python, docs, mypy]
mbl_tag: [v9.1.1]
exclude:
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/pypi_release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: 3.12

Expand All @@ -28,7 +28,7 @@ jobs:
run: python3 -m build

- name: Store the distribution packages
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: python-package-distributions
path: dist/
Expand All @@ -47,7 +47,7 @@ jobs:

steps:
- name: Download all the dists
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: python-package-distributions
path: dist/
Expand Down
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ exclude: |
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: check-added-large-files
Expand All @@ -24,7 +24,7 @@ repos:
- id: pretty-format-json
args: ['--autofix', '--no-sort-keys']
- repo: https://github.com/pre-commit/mirrors-autopep8
rev: v2.0.2
rev: v2.0.4
hooks:
- id: autopep8
args:
Expand All @@ -37,7 +37,7 @@ repos:
"--ignore=E501,E402,W503,W504,E731"
]
- repo: https://github.com/PyCQA/autoflake
rev: v2.2.0
rev: v2.2.1
hooks:
- id: autoflake
args:
Expand Down
26 changes: 20 additions & 6 deletions geojson_modelica_translator/model_connectors/plants/borefield.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,19 +109,32 @@ def to_modelica(self, scaffold):

# process g-function file
if Path(template_data["gfunction"]["input_path"]).expanduser().is_absolute():
gfunction = pd.read_csv(Path(template_data["gfunction"]["input_path"]) / template_data["gfunction"]["ghe_id"] / "Gfunction.csv", header=0, usecols=[0, 2])
gfunction = pd.read_csv(
Path(
template_data["gfunction"]["input_path"])
/ template_data["gfunction"]["ghe_id"]
/ "Gfunction.csv",
header=0,
usecols=[
0,
2])
else:
sys_param_dir = Path(self.system_parameters.filename).parent.resolve()
try:
gfunction = pd.read_csv(sys_param_dir / template_data["gfunction"]["input_path"] / template_data["gfunction"]["ghe_id"] / "Gfunction.csv", header=0, usecols=[0, 2])
gfunction = pd.read_csv(sys_param_dir
/ template_data["gfunction"]["input_path"]
/ template_data["gfunction"]["ghe_id"]
/ "Gfunction.csv", header=0, usecols=[0, 2])
except FileNotFoundError:
raise SystemExit(f'When using a relative path to your ghe_dir, your path \'{template_data["gfunction"]["input_path"]}\' must be relative to the dir your sys-param file is in.')
raise SystemExit(f'When using a relative path to your ghe_dir, your path \'{template_data["gfunction"]["input_path"]}\' must be relative to the dir your sys-param file is in.') # noqa: E501
template_data["gfunction"]["gfunction_file_rows"] = gfunction.shape[0] + 1

# convert the values to match Modelica gfunctions
for i in range(len(gfunction)):
gfunction[gfunction.columns[0]].iloc[i] = math.exp(gfunction[gfunction.columns[0]].iloc[i]) * template_data["configuration"]["borehole_height"]**2 / (9 * template_data["soil"]["conductivity"] / template_data["soil"]["volumetric_heat_capacity"])
gfunction[gfunction.columns[1]].iloc[i] = gfunction[gfunction.columns[1]].iloc[i] / (template_data["configuration"]["number_of_boreholes"] * 2 * math.pi * template_data["configuration"]["borehole_height"] * template_data["soil"]["conductivity"])
gfunction[gfunction.columns[0]].iloc[i] = math.exp(gfunction[gfunction.columns[0]].iloc[i]) * template_data["configuration"]["borehole_height"]**2 / (
9 * template_data["soil"]["conductivity"] / template_data["soil"]["volumetric_heat_capacity"])
gfunction[gfunction.columns[1]].iloc[i] = gfunction[gfunction.columns[1]].iloc[i] / \
(template_data["configuration"]["number_of_boreholes"] * 2 * math.pi * template_data["configuration"]["borehole_height"] * template_data["soil"]["conductivity"])

# add zeros to the first row
new_row = pd.Series({gfunction.columns[0]: 0, gfunction.columns[1]: 0})
Expand All @@ -138,7 +151,8 @@ def to_modelica(self, scaffold):

# process nominal mass flow rate
if template_data["configuration"]["flow_type"] == "system":
template_data["configuration"]["nominal_mass_flow_per_borehole"] = template_data["configuration"]["nominal_mass_flow_per_borehole"] / template_data["configuration"]["number_of_boreholes"]
template_data["configuration"]["nominal_mass_flow_per_borehole"] = template_data["configuration"]["nominal_mass_flow_per_borehole"] / \
template_data["configuration"]["number_of_boreholes"]

# process tube thickness
if template_data["tube"]["outer_diameter"] and template_data["tube"]["inner_diameter"]:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ def to_modelica(self, scaffold):
os.path.join(scaffold.plants_path.resources_dir, weather_filepath.name)
)
weather_file_modelica_string = f'modelica://{scaffold.project_name}/' \
f'{scaffold.plants_path.resources_relative_dir}/' \
f'{weather_filepath.name}'
f'{scaffold.plants_path.resources_relative_dir}/' \
f'{weather_filepath.name}'

template_data = {
"nominal_values": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def build_from_template(self, output_dir: Path, project_name: str) -> None:
mos_file.save()

# 4: Add the path to the param data with Modelica friendly path names
rel_path_name = f"{project_name}/{scaffold.districts_path.resources_relative_dir}/{file_to_copy['geojson_id']}/{file_to_copy['save_filename']}"
rel_path_name = f"{project_name}/{scaffold.districts_path.resources_relative_dir}/{file_to_copy['geojson_id']}/{file_to_copy['save_filename']}" # noqa: E501
template_data['building_load_files'].append(f"modelica://{rel_path_name}") # type: ignore

# 5: Calculate the mass flow rates (kg/s) for the heating and cooling networks peak load (in Watts)
Expand Down
3 changes: 2 additions & 1 deletion geojson_modelica_translator/modelica/modelica_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,8 @@ def run_in_docker(self, action: str, model_name: str, file_to_load: Union[str, P
self.move_results(verified_run_path, results_path, model_name)
return (exitcode == 0, results_path)

def run_in_dymola(self, action: str, model_name: str, file_to_load: Union[str, Path], run_path: Union[str, Path], **kwargs) -> tuple[bool, Union[str, Path]]:
def run_in_dymola(self, action: str, model_name: str,
file_to_load: Union[str, Path], run_path: Union[str, Path], **kwargs) -> tuple[bool, Union[str, Path]]:
"""If running on Windows or Linux, you can run Dymola (assuming you have a license),
using the BuildingsPy library. This is not supported on Mac.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,9 @@ def csv_to_sys_param(self,
if (measure_file_path.suffix == '.csv') and ('_export_time_series_modelica' in str(measure_folder_name)):
massflow_rate_df = pd.read_csv(measure_file_path)
try:
building_nominal_massflow_rate = round(massflow_rate_df['massFlowRateHeating'].max(), 3) # round max to 3 decimal places
building_nominal_massflow_rate = round(
massflow_rate_df['massFlowRateHeating'].max(),
3) # round max to 3 decimal places
# Force casting to float even if building_nominal_massflow_rate == 0
# FIXME: This might be related to building_type == `lodging` for non-zero building percentages
building['ets_indirect_parameters']['nominal_mass_flow_building'] = float(building_nominal_massflow_rate)
Expand All @@ -828,7 +830,8 @@ def csv_to_sys_param(self,
district_nominal_massflow_rate += building_nominal_massflow_rate
if measure_file_path.suffix == '.csv' and measure_folder_name.endswith('_export_modelica_loads'):
try:
building_loads = pd.read_csv(measure_file_path, usecols=['ElectricityFacility']) # only use the one column to make the df small
# only use the one column to make the df small
building_loads = pd.read_csv(measure_file_path, usecols=['ElectricityFacility'])
except ValueError: # hack to handle the case where there is no ElectricityFacility column in the csv
continue
max_electricity_load = int(building_loads['ElectricityFacility'].max())
Expand Down Expand Up @@ -884,7 +887,8 @@ def csv_to_sys_param(self,
except KeyError:
pass
if district_system_type == 'Ground Heat Exchanger':
length, width = self.calculate_dimensions(feature['properties']['footprint_area'], feature['properties']['footprint_perimeter'])
length, width = self.calculate_dimensions(
feature['properties']['footprint_area'], feature['properties']['footprint_perimeter'])
ghe_ids.append({'ghe_id': feature['properties']['id'],
'length_of_ghe': length,
'width_of_ghe': width})
Expand Down
3 changes: 2 additions & 1 deletion management/uo_des.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@ def run_model(modelica_project: Path, start_time: int, stop_time: int, step_size
step_size=step_size
)

if (run_path.parent / f'{project_name}/{project_name}.Districts.DistrictEnergySystem_results' / f'{project_name}_Districts_DistrictEnergySystem_res.mat').exists():
if (run_path.parent / f'{project_name}/{project_name}.Districts.DistrictEnergySystem_results'
/ f'{project_name}_Districts_DistrictEnergySystem_res.mat').exists():
print(f"\nModelica model {project_name} ran successfully")
else:
raise SystemExit(f"\n{project_name} failed. Check the error log at {project_name}_results/stdout.log for more info.")
Loading

0 comments on commit b7f5835

Please sign in to comment.