Skip to content

Commit f39188c

Browse files
committed
Apply ruff formatting to codebase
- Format all Python files with ruff for consistent code style - Update CI workflow configuration - Maintain all existing functionality (237 tests pass)
1 parent 5afcd2b commit f39188c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+4216
-4062
lines changed

.github/workflows/tests.yml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,8 @@ jobs:
6161
pip install ruff
6262
6363
- name: Run ruff linter
64-
run: ruff check ochre/ --output-format=github
64+
run: ruff check ochre/ test/ --output-format=github
6565
continue-on-error: true
6666

6767
- name: Run ruff formatter check
68-
run: ruff format ochre/ --check --diff
69-
continue-on-error: true
68+
run: ruff format ochre/ test/ --check --diff

ochre/Analysis.py

Lines changed: 26 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,7 @@ def download_resstock_model(
7474
file_names = ["home.xml", "in.schedules.csv"]
7575
missing = [f for f in file_names if not os.path.exists(os.path.join(local_folder, f))]
7676
if missing:
77-
print(
78-
f"WARNING: Couldn't download ResStock files for {building_id}-{upgrade_str}: {missing}"
79-
)
77+
print(f"WARNING: Couldn't download ResStock files for {building_id}-{upgrade_str}: {missing}")
8078

8179

8280
def get_unit(column):
@@ -125,9 +123,7 @@ def load_timeseries_file(file_name, columns=None, resample_res=None, ignore_erro
125123
return df
126124

127125

128-
def load_ochre(
129-
ochre_path, ochre_name, load_main=True, load_hourly=True, combine_schedule=False, remove_tz=True
130-
):
126+
def load_ochre(ochre_path, ochre_name, load_main=True, load_hourly=True, combine_schedule=False, remove_tz=True):
131127
# load metrics file
132128
metrics_file = os.path.join(ochre_path, ochre_name + "_metrics.csv")
133129
if not os.path.exists(metrics_file):
@@ -151,14 +147,10 @@ def find_and_load_file(suffix="", extns=[".csv", ".parquet"]):
151147
# Combine with schedule file if it exists
152148
if schedule is not None:
153149
if main is not None:
154-
schedule = schedule.drop(
155-
columns=[col for col in schedule.columns if col in main.columns]
156-
)
150+
schedule = schedule.drop(columns=[col for col in schedule.columns if col in main.columns])
157151
main = main.join(schedule)
158152
if hourly is not None:
159-
schedule = schedule.drop(
160-
columns=[col for col in schedule.columns if col in hourly.columns]
161-
)
153+
schedule = schedule.drop(columns=[col for col in schedule.columns if col in hourly.columns])
162154
schedule_hourly = schedule.resample(dt.timedelta(hours=1)).mean()
163155
hourly = hourly.join(schedule_hourly)
164156

@@ -182,9 +174,7 @@ def load_eplus_file(
182174
if eplus_format == "BEopt":
183175
# skip header rows, remove "My Design - ", and replace "|"
184176
df = pd.read_csv(file_name, skiprows=[0, 2, 3, 4], low_memory=False)
185-
df.columns = [
186-
" - ".join(col.split(" - ")[1:]) if " - " in col else col for col in df.columns
187-
]
177+
df.columns = [" - ".join(col.split(" - ")[1:]) if " - " in col else col for col in df.columns]
188178
df.columns = [col.replace("|", ":") for col in df.columns]
189179
eplus_format = "OS-HPXML"
190180
elif eplus_format == "ResStock":
@@ -216,9 +206,7 @@ def load_eplus_file(
216206
eplus_list = [eplus_name]
217207

218208
# subtracts columns if '~' is the first character in the column name
219-
eplus_cols = pd.Series(
220-
{col[1:] if col[0] == "~" else col: -1 if col[0] == "~" else 1 for col in eplus_list}
221-
)
209+
eplus_cols = pd.Series({col[1:] if col[0] == "~" else col: -1 if col[0] == "~" else 1 for col in eplus_list})
222210
eplus_cols = eplus_cols.loc[eplus_cols.index.isin(df.columns)]
223211
if len(eplus_cols):
224212
data = (df.loc[:, eplus_cols.index] * eplus_cols).sum(axis=1)
@@ -263,9 +251,7 @@ def replace_nans(s):
263251
)
264252

265253
# add unmet HVAC loads - BEopt only
266-
df["Unmet HVAC Load (C)"] = df["Temperature - Indoor (C)"] - df[
267-
"Temperature - Indoor (C)"
268-
].clip(
254+
df["Unmet HVAC Load (C)"] = df["Temperature - Indoor (C)"] - df["Temperature - Indoor (C)"].clip(
269255
convert(df["Living Space|Heating Setpoint"].values, "degF", "degC"),
270256
convert(df["Living Space|Cooling Setpoint"].values, "degF", "degC"),
271257
)
@@ -294,10 +280,7 @@ def add_eplus_detailed_results(df, df_ochre, ochre_properties):
294280
}
295281
films = pd.DataFrame(index=df.index)
296282
for surface, name_list in surface_names.items():
297-
cols = [
298-
f"{s}:Surface {f} Face Convection Heat Transfer Coefficient [W/m2-K](Hourly)"
299-
for s, f in name_list
300-
]
283+
cols = [f"{s}:Surface {f} Face Convection Heat Transfer Coefficient [W/m2-K](Hourly)" for s, f in name_list]
301284
if all([col in df.columns for col in cols]):
302285
films[f"{surface} Film Coefficient (m^2-K/W)"] = 1 / df.loc[:, cols].mean(axis=1)
303286
df = df.join(films)
@@ -346,9 +329,7 @@ def calculate_metrics(results=None, results_file=None, dwelling=None, metrics_ve
346329
for power_name, energy_name in power_names:
347330
col = "Total " + power_name
348331
if col in results:
349-
metrics[col.replace(power_name, energy_name)] = (
350-
results[col].sum(skipna=False) * hr_per_step
351-
)
332+
metrics[col.replace(power_name, energy_name)] = results[col].sum(skipna=False) * hr_per_step
352333

353334
# Average and peak electrical power
354335
p = results["Total Electric Power (kW)"]
@@ -366,9 +347,7 @@ def calculate_metrics(results=None, results_file=None, dwelling=None, metrics_ve
366347
for end_use in ALL_END_USES:
367348
col = f"{end_use} {power_name}"
368349
if col in results:
369-
metrics[col.replace(power_name, energy_name)] = (
370-
results[col].sum(skipna=False) * hr_per_step
371-
)
350+
metrics[col.replace(power_name, energy_name)] = results[col].sum(skipna=False) * hr_per_step
372351

373352
# Envelope metrics
374353
# Average and std. dev. of zone temperatures
@@ -406,12 +385,8 @@ def calculate_metrics(results=None, results_file=None, dwelling=None, metrics_ve
406385
if metrics_verbosity >= 3:
407386
if "Unmet HVAC Load (C)" in results:
408387
unmet_hvac = results["Unmet HVAC Load (C)"]
409-
metrics["Unmet Heating Load (C-hours)"] = (
410-
-unmet_hvac.clip(upper=0).sum(skipna=False) * hr_per_step
411-
)
412-
metrics["Unmet Cooling Load (C-hours)"] = (
413-
unmet_hvac.clip(lower=0).sum(skipna=False) * hr_per_step
414-
)
388+
metrics["Unmet Heating Load (C-hours)"] = -unmet_hvac.clip(upper=0).sum(skipna=False) * hr_per_step
389+
metrics["Unmet Cooling Load (C-hours)"] = unmet_hvac.clip(lower=0).sum(skipna=False) * hr_per_step
415390

416391
for end_use, hvac_mult in [("HVAC Heating", 1), ("HVAC Cooling", -1)]:
417392
# Delivered heating/cooling
@@ -451,15 +426,11 @@ def calculate_metrics(results=None, results_file=None, dwelling=None, metrics_ve
451426
else:
452427
fan_heat = 0
453428
if sens_capacity_sum != 0:
454-
metrics[f"Average {end_use} Duct Efficiency (-)"] = delivered_sum / (
455-
sens_capacity_sum + fan_heat
456-
)
429+
metrics[f"Average {end_use} Duct Efficiency (-)"] = delivered_sum / (sens_capacity_sum + fan_heat)
457430

458431
# HVAC capacity - only when device is on
459432
if metrics_verbosity >= 7:
460-
metrics["Average {} Capacity (kW)".format(end_use)] = capacity[
461-
capacity > 0
462-
].mean()
433+
metrics["Average {} Capacity (kW)".format(end_use)] = capacity[capacity > 0].mean()
463434

464435
# Water heater and hot water metrics
465436
if metrics_verbosity >= 3 and "Hot Water Unmet Demand (kW)" in results:
@@ -475,9 +446,7 @@ def calculate_metrics(results=None, results_file=None, dwelling=None, metrics_ve
475446
# COP - weighted average only when device is on
476447
if "Water Heating COP (-)" in results and heat.sum(skipna=False) != 0:
477448
cop = results["Water Heating COP (-)"]
478-
metrics["Average Water Heating COP (-)"] = (cop * heat).sum(skipna=False) / heat.sum(
479-
skipna=False
480-
)
449+
metrics["Average Water Heating COP (-)"] = (cop * heat).sum(skipna=False) / heat.sum(skipna=False)
481450

482451
# Hot water delivered
483452
if "Hot Water Delivered (L/min)" in results:
@@ -504,16 +473,10 @@ def calculate_metrics(results=None, results_file=None, dwelling=None, metrics_ve
504473
metrics["Battery Discharging Energy (kWh)"] = -batt_energy.clip(upper=0).sum(skipna=False)
505474
if metrics["Battery Charging Energy (kWh)"] != 0:
506475
metrics["Battery Round-trip Efficiency (-)"] = (
507-
metrics["Battery Discharging Energy (kWh)"]
508-
/ metrics["Battery Charging Energy (kWh)"]
476+
metrics["Battery Discharging Energy (kWh)"] / metrics["Battery Charging Energy (kWh)"]
509477
)
510478

511-
if all(
512-
[
513-
r in results
514-
for r in ["Battery Energy to Discharge (kWh)", "Total Electric Energy (kWh)"]
515-
]
516-
):
479+
if all([r in results for r in ["Battery Energy to Discharge (kWh)", "Total Electric Energy (kWh)"]]):
517480
cumulative_energy = (results["Total Electric Energy (kWh)"] - batt_energy).cumsum()
518481
end_energy = cumulative_energy + results["Battery Energy to Discharge (kWh)"]
519482
islanding_times = []
@@ -528,9 +491,9 @@ def calculate_metrics(results=None, results_file=None, dwelling=None, metrics_ve
528491

529492
# Gas generator metrics
530493
if metrics_verbosity >= 4 and "Gas Generator Electric Energy (kWh)" in metrics:
531-
metrics["Gas Generator Efficiency (-)"] = -metrics[
532-
"Gas Generator Electric Energy (kWh)"
533-
] / convert(metrics["Gas Generator Gas Energy (therms)"], "therm", "kWh")
494+
metrics["Gas Generator Efficiency (-)"] = -metrics["Gas Generator Electric Energy (kWh)"] / convert(
495+
metrics["Gas Generator Gas Energy (therms)"], "therm", "kWh"
496+
)
534497

535498
# Outage metrics
536499
if metrics_verbosity >= 1 and "Grid Voltage (-)" in results:
@@ -542,18 +505,15 @@ def calculate_metrics(results=None, results_file=None, dwelling=None, metrics_ve
542505
outage_ends = np.nonzero(-outage_diff.clip(max=0))[0]
543506
metrics["Number of Outages"] = len(outage_starts)
544507
metrics["Average Outage Duration (hours)"] = outage_sum / len(outage_starts)
545-
metrics["Longest Outage Duration (hours)"] = (
546-
outage_ends - outage_starts
547-
).max() * hr_per_step
508+
metrics["Longest Outage Duration (hours)"] = (outage_ends - outage_starts).max() * hr_per_step
548509

549510
# Equipment power metrics
550511
if metrics_verbosity >= 6:
551512
for power_name, energy_name in power_names:
552513
power_cols = [col for col in results.columns if power_name in col]
553514
metrics.update(
554515
{
555-
col.replace(power_name, energy_name): results[col].sum(skipna=False)
556-
* hr_per_step
516+
col.replace(power_name, energy_name): results[col].sum(skipna=False) * hr_per_step
557517
for col in power_cols
558518
}
559519
)
@@ -597,8 +557,7 @@ def calculate_metrics(results=None, results_file=None, dwelling=None, metrics_ve
597557
for power_name, energy_name in power_names:
598558
metrics.update(
599559
{
600-
col.replace(power_name, energy_name): results[col].sum(skipna=False)
601-
* hr_per_step
560+
col.replace(power_name, energy_name): results[col].sum(skipna=False) * hr_per_step
602561
for col in results.columns
603562
if power_name in col
604563
}
@@ -700,9 +659,7 @@ def find_subfolders(root_folder, includes_file_patterns=None, excludes_file_patt
700659
for root, _, files in os.walk(root_folder):
701660
if any([any([re.match(pattern, f) for f in files]) for pattern in excludes_file_patterns]):
702661
continue
703-
if not all(
704-
[any([re.match(pattern, f) for f in files]) for pattern in includes_file_patterns]
705-
):
662+
if not all([any([re.match(pattern, f) for f in files]) for pattern in includes_file_patterns]):
706663
continue
707664
subfolders.append(root)
708665

@@ -724,16 +681,13 @@ def find_files_from_ending(path, ending, priority_list=None, **kwargs):
724681
# select file match in priority list. If not found, throw an error
725682
matches = [f for f in priority_list if f in matches]
726683
if len(matches) != 1:
727-
raise OCHREException(
728-
f"{len(matches)} files found matching {ending} in {root}: {matches}"
729-
)
684+
raise OCHREException(f"{len(matches)} files found matching {ending} in {root}: {matches}")
730685

731686
file_path = os.path.join(root, matches[0])
732687
run_name = get_parent_folders(file_path, **kwargs)
733688
if run_name in all_files:
734689
raise OCHREException(
735-
f"Multiple files found with same run name ({run_name})."
736-
"Try increasing dirs_to_include. Error from:",
690+
f"Multiple files found with same run name ({run_name}).Try increasing dirs_to_include. Error from:",
737691
file_path,
738692
)
739693

0 commit comments

Comments
 (0)