diff --git a/CHANGELOG.md b/CHANGELOG.md index ed70ffa..2161870 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,94 @@ Removed. `scripts/bump_version.py` turns them into a release section. ## [Unreleased] +## [0.2.0] - 2026-11-17 + +### Added + +- Results download includes an annual summary CSV with one row per equipment and emission + scenario combination +- Reset button in the Scale Load Profile and Modify Base Load modals to restore the load + without scaling or base load +- Confirm button in both modals: Apply only updates the values shown in the modal, so several + changes (e.g. heating and cooling) can be made before Confirm uses them in the calculation +- Modify Base Load modal shows peak loads without and with the base load side by side +- Status line in both modals says what is in the table and whether Apply or Confirm is needed + next; Confirm is disabled while an entered value has not been applied or nothing changed +- Equipment Manager page, linked in the sidebar next to the documentation: browse the equipment + library by type, search it, and inspect each item's data, data checks and performance curves + (plot and table, SI/IP) (#171) +- Performance curve plot in the edit equipment scenario window, with the curve at the selected + supply temperature highlighted (#171) +- Equipment validation that reports every problem in an equipment definition (errors and + warnings), groundwork for the Equipment Manager and editable performance curves (#171) +- Optional `source`, `based_on` and `notes` fields on equipment, to tell library equipment from + user-made copies +- Custom equipment in the Equipment Manager: duplicate any library item and edit the copy's + properties (including efficiency of backup heating and chillers), curve points, supply + temperatures and operating limits; save, edit or delete custom items. Library equipment is never + changed, and custom items survive the equipment Reset (#171) +- Scaling of heat pump performance curves by a COP and a capacity percentage; factors are relative + to the unscaled curves and are recorded on the item (#171) +- Import and export of custom equipment in the Equipment Manager: export all custom items as a + JSON file and import them in a later session; import also reads the custom items of a results + settings file. Library equipment is never replaced: an item with a library ID is imported as a + custom copy, and invalid items are rejected with a reason (#171) +- Refrigerant database (`data/input/refrigerants.csv`, IPCC AR4 GWPs) behind the refrigerant input, + which fills in the GWP automatically (#171) +- Optional balancing source/sink for the HR WWHP, with rejection and recovery capacities and a control option for each side (#122) +- Google Analytics (GA4, measurement ID `G-3K9P3CNPWY`) and Siteimprove usage tracking on the + production deployment, enabled with `ENABLE_ANALYTICS=true` (set in the Dockerfile) (#200) + +### Changed + +- I-P conversions use one exact BTU factor (1 W = 3.41214 BTU/h, 1 TR = 3516.85 W) instead of a + mix of 3.412 and 1/0.293, so I-P values shown and entered (BTU, BTU/h, kBTU, TR, lb CO₂e/kBTU) + shift by up to 0.03 %; results in SI are unchanged (#227) +- Performance curve plots restyled: white background with light grid, legend above the plot, + outdoor air temperature labelled under both AWHP panels, unified hover, the part of a curve outside its operating limits drawn dashed, and the original + curves shown in grey behind a custom copy (#171) +- Equipment validation also reports missing (blank) curve values +- Charts use Open Sans, the font of the rest of the interface, instead of Helvetica +- Performance curve tables have grouped, sentence-case headings (a column group per supply + temperature, with units as secondary text) instead of uppercase headings with units in brackets +- The Equipment Manager shows equipment names with their own capitalisation instead of all caps +- Default unit system is IP; SI can still be selected with the unit toggle +- Results download is named after the case (building, location, climate zone, load scaling, + base load, unit system), e.g. `decarb_B3_Denver_CZ5B_scaled-h1.25-c1.25_SI_.zip`, and + unzips into a folder of the same name +- Hourly results CSV starts with readable case columns (equipment scenario number as shown on the + Results page, emission scenario letter, name, year, grid scenario, source, emission type) so + scenario combinations can be filtered directly; rows are grouped per combination and the + remaining columns are ordered by topic. The load-year column was removed (it is in the timestamp) +- Settings summary lists load scaling and base load, and shows emission rates in the selected unit + system +- Values below 1 in the results CSVs keep 4 significant figures instead of 3 decimals, so small + hourly emissions and lb CO₂e/kWh rates no longer round to zero +- Scale Load Profile modal shows the original library values next to the scaled values instead + of overwriting them +- Scaling by peak heating or peak cooling load only scales that load; heating and cooling + factors are kept separately, so both peaks can be matched +- Heating and cooling can each have their own base load (floor or offset); applying a base + load replaces the previous one for that load type instead of stacking, and base loads are + always applied after scaling +- Heat pump curves are now also checked for strictly increasing outdoor temperature or capacity + values, positive COP and capacity, numeric non-duplicate supply temperatures, and ordered + min/max limits before a calculation runs +- Equipment input modal revised to have separate sections for AWHP and HR WWHP inputs + +### Fixed + +- Heat rejection/recovery capacities entered in BTU/h in the Edit Equipment Scenario modal were + stored slightly off (100000 showed as 100028.4) because saving and display used different + BTU/h factors (#227) +- Combined LRMER/SRMER/AER CO₂e rate columns in the results CSV were not converted (and had no + unit) in IP mode +- Applying load scaling repeatedly no longer compounds the scale factor +- Input labels and the base load method description show as soon as the modals open +- The supply temperature reset now picks the lowest supply temperature curve numerically + instead of alphabetically (no effect on the current equipment library) +- The HR WWHP can now run at exactly its minimum turndown + ## [0.1.0] - 2026-10-13 First versioned release of the tool. Earlier deployments were not versioned consistently; diff --git a/Dockerfile b/Dockerfile index 6935eef..517ccfb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,6 +5,8 @@ FROM python:3.12-slim ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ENV PORT=8080 +# Load Google Analytics / Siteimprove tracking (off for local runs) +ENV ENABLE_ANALYTICS=true # Set working directory WORKDIR /app diff --git a/app.py b/app.py index 9bbbd9b..ce8ddaf 100644 --- a/app.py +++ b/app.py @@ -7,6 +7,7 @@ import utils.plotly_theme # noqa: F401 - imports for side effect (sets default Plotly theme) from layout.shell import build_shell +from utils.analytics import GA_MEASUREMENT_ID, add_analytics, analytics_enabled from utils.logging_config import get_logger, setup_logging # Read level from environment variable (or default to INFO) @@ -30,6 +31,9 @@ serve_locally=True, ) +app.index_string = add_analytics(app.index_string, analytics_enabled(), GA_MEASUREMENT_ID) +logger.info("Analytics %s", "enabled" if analytics_enabled() else "disabled (ENABLE_ANALYTICS)") + # Expose Flask server for gunicorn server = app.server diff --git a/assets/css/custom-dash-styles.css b/assets/css/custom-dash-styles.css index 17da3a1..348a5d3 100644 --- a/assets/css/custom-dash-styles.css +++ b/assets/css/custom-dash-styles.css @@ -44,4 +44,19 @@ background-color: rgb(240, 241, 242); /* Bootstrap primary */ color: rgb(0, 0, 0) !important; border-radius: 0.5rem 0.5rem 0.5rem 0.5rem; -} \ No newline at end of file +} + +/* Equipment Manager curve tables: sentence-case headings instead of the theme's uppercase */ +.eqm-table th, +.eqm-table .dash-header { + text-transform: none !important; + letter-spacing: normal !important; + font-weight: 600; + vertical-align: bottom; +} + +.eqm-table .eqm-unit { + display: block; + font-weight: 400; + color: var(--mantine-color-dimmed); +} diff --git a/data/input/equipment_data.JSON b/data/input/equipment_data.JSON index b018880..7e8c4f9 100644 --- a/data/input/equipment_data.JSON +++ b/data/input/equipment_data.JSON @@ -1191,6 +1191,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": null, "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1209,6 +1213,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": null, "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1227,6 +1235,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1245,6 +1257,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1263,6 +1279,10 @@ "hr_wwhp": "hr03", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1281,6 +1301,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "fractional_sizing_peak_load", @@ -1299,6 +1323,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "fractional_sizing_peak_load", @@ -1317,6 +1345,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "fractional_sizing_peak_load", @@ -1335,6 +1367,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "fractional_sizing_peak_load", @@ -1353,6 +1389,10 @@ "hr_wwhp": "hr03", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": null, "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1371,6 +1411,10 @@ "hr_wwhp": "hr03", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": null, "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1389,6 +1433,10 @@ "hr_wwhp": "hr03", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1407,6 +1455,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1425,6 +1477,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_reset", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1443,6 +1499,10 @@ "hr_wwhp": "hr03", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 60, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1460,6 +1520,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": null, "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1478,6 +1542,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1496,6 +1564,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1514,6 +1586,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp04", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1531,6 +1607,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp06", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1548,6 +1628,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp08", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1565,6 +1649,10 @@ "hr_wwhp": "hr06", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 57.2, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1582,6 +1670,10 @@ "hr_wwhp": "hr07", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 57.2, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_sizing_mode": "integer_sizing_peak_load", @@ -1592,6 +1684,50 @@ "awhp_sizing_priority": "heating", "backup_heating": "res02", "chiller": "ch02" + }, + { + "eq_scen_id": "eq_scenario_24", + "eq_scen_name": "HR WWHP+Balancing+100% AWHP (H+C)+Elec Backup", + "hr_wwhp": "hr03", + "hr_wwhp_performance_model": "interpolate_HHWST", + "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 50000, + "hr_eac_recovery_cap_W": 50000, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "min_turndown", + "awhp": "hp01", + "awhp_performance_model": "interpolate_HHWST_fixed", + "awhp_sizing_mode": "integer_sizing_peak_load", + "awhp_sizing_value": 1, + "awhp_redundancy": 1, + "awhp_h_supply_t": 38, + "awhp_use_cooling": true, + "awhp_sizing_priority": "heating", + "backup_heating": "res02", + "fuel_switching": false, + "chiller": "ch02" + }, + { + "eq_scen_id": "eq_scenario_25", + "eq_scen_name": "HR WWHP+Max Recovery Balancing+100% AWHP (H+C)+Elec Backup", + "hr_wwhp": "hr03", + "hr_wwhp_performance_model": "interpolate_HHWST", + "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 50000, + "hr_eac_recovery_cap_W": 50000, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "max_heat_recovery", + "awhp": "hp01", + "awhp_performance_model": "interpolate_HHWST_fixed", + "awhp_sizing_mode": "integer_sizing_peak_load", + "awhp_sizing_value": 1, + "awhp_redundancy": 1, + "awhp_h_supply_t": 38, + "awhp_use_cooling": true, + "awhp_sizing_priority": "heating", + "backup_heating": "res02", + "fuel_switching": false, + "chiller": "ch02" } ], "scenario_groups": [ @@ -1620,6 +1756,11 @@ "group_name": "Dynamic Fuel Switching", "scenario_ids": ["eq_scenario_16", "eq_scenario_17", "eq_scenario_4", "eq_scenario_18"] }, + { + "group_id": "heat_recovery_balancing", + "group_name": "Heat Recovery Balancing Source/Sink", + "scenario_ids": ["eq_scenario_4", "eq_scenario_5", "eq_scenario_24", "eq_scenario_25"] + }, { "group_id": "awhp_refrigerant_types", "group_name": "Varying AWHP Model+Refrigerant", diff --git a/data/input/refrigerants.csv b/data/input/refrigerants.csv new file mode 100644 index 0000000..6476333 --- /dev/null +++ b/data/input/refrigerants.csv @@ -0,0 +1,21 @@ +name,aliases,gwp,type,safety_class,note +R-32,,675,HFC,A2L,IPCC AR4 +R-410A,,2088,HFC blend,A1,IPCC AR4 (R-32/R-125 50/50) +R-454B,,466,HFC/HFO blend,A2L,IPCC AR4 (R-32/R-1234yf 68.9/31.1) +R-452B,,698,HFC/HFO blend,A2L,IPCC AR4 (R-32/R-125/R-1234yf 67/7/26) +R-454C,,148,HFC/HFO blend,A2L,IPCC AR4 (R-32/R-1234yf 21.5/78.5) +R-466A,,733,HFC blend,A1,IPCC AR4 (R-32/R-125/R-13I1 49/11.5/39.5) +R-449A,,1397,HFC/HFO blend,A1,IPCC AR4 (R-32/R-125/R-1234yf/R-134a 24.3/24.7/25.3/25.7) +R-407C,,1774,HFC blend,A1,IPCC AR4 (R-32/R-125/R-134a 23/25/52) +R-404A,,3922,HFC blend,A1,IPCC AR4 (R-125/R-143a/R-134a 44/52/4) +R-134a,,1430,HFC,A1,IPCC AR4 +R-513A,,631,HFC/HFO blend,A1,IPCC AR4 (R-1234yf/R-134a 56/44) +R-515B,,292,HFO/HFC blend,A1,IPCC AR4 (R-1234ze(E)/R-227ea 91.1/8.9) +R-22,,1810,HCFC,A1,IPCC AR4; phased out +R-1234yf,,4,HFO,A2L,IPCC AR4 +R-1234ze(E),R-1234ze,1,HFO,A2L,Not in IPCC AR4; EPA value (IPCC AR5 <1) +R-1233zd(E),R-1233zd,1,HCFO,A1,Not in IPCC AR4; EPA value (IPCC AR5 1) +R-290,Propane,3,Natural (HC),A3,IPCC AR4 +R-600a,Isobutane,3,Natural (HC),A3,IPCC AR4 +R-717,Ammonia,0,Natural,B2L,IPCC AR4 +R-744,CO2,1,Natural,A1,IPCC AR4 (reference gas) diff --git a/docs/documentation/equipment.md b/docs/documentation/equipment.md index 7ac69ba..8dad649 100644 --- a/docs/documentation/equipment.md +++ b/docs/documentation/equipment.md @@ -129,8 +129,23 @@ This scenario group varies the WWHP and AWHP heating hot water supply temperatur This scenario group compares fully gas and fully electric heating plants with a partial AWHP scenario and a fuel switching scenario. +### Equipment Manager + +The Equipment Manager, linked in the sidebar, lists all equipment with its data checks, performance curves and properties. Library equipment is never changed. To customise an item, select it and click **Duplicate to edit**. This creates a custom copy that you can then edit: + +- **Overview**: name, manufacturer, capacities, efficiency (backup heating and chillers), refrigerant, charge, weight, dimensions, electrical data and notes. Pick a refrigerant from the list to fill in its GWP (IPCC AR4, 100-year). For a refrigerant that is not listed, type its name and enter the GWP yourself. +- **Performance** (heat pumps): edit any curve point in the table, add or remove curve points and supply temperatures, and change the outdoor air temperature limits of each curve. **Scale curves** multiplies all COP and/or capacity values of the selected mode by a percentage. The factors are relative to the unscaled curves, so applying 90 % twice still gives 90 %. While you edit, the original curves are shown in grey for comparison. + +Click **Save** to store the copy. Saving is blocked while the data checks report errors; warnings, such as a COP outside 1 to 8, are allowed. Custom equipment appears in the equipment selections of the scenario edit window, marked "custom". It is kept for the browser session, also when the equipment scenarios are reset, and is included in the settings file of the results download. A custom item cannot be deleted while a scenario uses it. + +**Import and export.** Custom equipment is only kept for the browser session. To keep it, click **Export custom**. This downloads all custom items as a JSON file (`decarb_custom_equipment_.json`). Load the file again in a later session with **Import**. Import also accepts the settings file from a results download and takes the custom equipment out of it. When importing: + +- an item that matches one already in the tool is skipped; +- a custom item with the same ID as one in the session replaces it; +- an item with the ID of library equipment is imported as a new custom copy, so library equipment is never replaced; +- items with data errors are not imported, and the message shows why. + ### Future Development -1. Allow users to edit the equipment library and add new equipment models. -2. Display equipment sizing outputs, such as total capacity required, total number of units, and total refrigerant weight. -3. Allow users to edit the HHWST reset bounds. +1. Display equipment sizing outputs, such as total capacity required, total number of units, and total refrigerant weight. +2. Allow users to edit the HHWST reset bounds. diff --git a/layout/equipment_editor.py b/layout/equipment_editor.py new file mode 100644 index 0000000..ab3dbc3 --- /dev/null +++ b/layout/equipment_editor.py @@ -0,0 +1,330 @@ +"""Equipment Manager edit helpers: the overview form and the curve editor tables. + +Values are shown in display units (SI/IP, fixed scale) and converted back to the stored base +units. Kept apart from the page module so the conversions can be unit-tested without the app. +""" + +import dash_mantine_components as dmc +import pandas as pd +from dash.dash_table.Format import Format, Scheme + +from src.equipment import ( + HEAT_PUMP_TYPES, + Equipment, + curve_table, + find_refrigerant, + load_refrigerants, +) +from utils.units import get_converter, get_display_unit, get_inverse_converter + +TYPE_LABELS = { + "hr_heat_pump": "HR water-to-water heat pump", + "heat_pump": "Air-to-water heat pump", + "backup_heating": "Backup heating", + "chiller": "Chiller", +} + +CALC_TYPE_OPTIONS = [ + {"label": "Specific (sized from its capacity)", "value": "specific"}, + {"label": "Generic (unlimited capacity)", "value": "generic"}, +] + + +def edit_unit(category: str, unit_mode: str): + """(base -> display, display -> base, label) for edit inputs, with a fixed scale per unit system.""" + if category == "power" and unit_mode == "IP": + to_btu, from_btu = get_converter("power", "IP"), get_inverse_converter("power", "IP") + return (lambda v: to_btu(v) / 1000), (lambda v: from_btu(v * 1000)), "kBTU/h" + if category == "length": + factor = 1.0 if unit_mode == "SI" else 3.28084 + return (lambda v: v * factor), (lambda v: v / factor), "m" if unit_mode == "SI" else "ft" + return ( + get_converter(category, unit_mode), + get_inverse_converter(category, unit_mode), + get_display_unit(category, unit_mode), + ) + + +# --- Overview form --- +# path in the equipment dict -> (label, kind, unit category, decimals, display factor) +FORM_FIELDS = { + "model": ("Model", "text", None, None, 1), + "eq_manufacturer": ("Manufacturer", "text", None, None, 1), + "eq_subtype": ("Subtype", "text", None, None, 1), + "eq_calc_type": ("Calculation type", "calc_type", None, None, 1), + "nominal_capacity_W": ("Nominal capacity", "number", "power_cooling", 2, 1), + "capacity_W": ("Capacity", "number", "power", 1, 1), + "efficiency": ("Efficiency", "number", None, 2, 1), + "refrigerant": ("Refrigerant", "refrigerant", None, None, 1), + "refrigerant_gwp": ("Refrigerant GWP", "number", "gwp", 0, 1), + "refrigerant_weight_g": ("Refrigerant charge", "number", "mass_g", 2, 1), + "operating_weight_g": ("Operating weight", "number", "mass_g", 0, 1), + "dimensions.length": ("Length", "number", "length", 2, 1), + "dimensions.width": ("Width", "number", "length", 2, 1), + "dimensions.height": ("Height", "number", "length", 2, 1), + "electrical.mca": ("MCA [A]", "number", None, 1, 1), + "electrical.voltage": ("Voltage [V]", "number", None, 0, 1), + "electrical.phase": ("Phase", "number", None, 0, 1), + "max_output_dba": ("Max. sound level [dBA]", "number", None, 0, 1), + "notes": ("Notes", "textarea", None, None, 1), +} + +FORM_SECTIONS = [ + ("General", ["model", "eq_manufacturer", "eq_subtype", "eq_calc_type"]), + ("Capacity and efficiency", ["nominal_capacity_W", "capacity_W", "efficiency"]), + ("Refrigerant", ["refrigerant", "refrigerant_gwp", "refrigerant_weight_g"]), + ( + "Physical and electrical", + [ + "operating_weight_g", + "dimensions.length", + "dimensions.width", + "dimensions.height", + "electrical.mca", + "electrical.voltage", + "electrical.phase", + "max_output_dba", + ], + ), + ("Notes", ["notes"]), +] + + +def form_field_names(eq: dict) -> list[str]: + """The overview fields that apply to this kind of equipment.""" + eq_type = eq.get("eq_type") + names = ["model", "eq_manufacturer", "eq_subtype", "eq_calc_type", "notes"] + if eq_type in (*HEAT_PUMP_TYPES, "chiller"): + names += ["nominal_capacity_W", "refrigerant", "refrigerant_gwp", "refrigerant_weight_g"] + names += [n for n in FORM_FIELDS if n.startswith(("dimensions.", "electrical."))] + names += ["operating_weight_g", "max_output_dba"] + if eq_type in ("backup_heating", "chiller") or ( + eq_type == "heat_pump" and eq.get("capacity_W") + ): + names.append("capacity_W") + if eq_type in ("backup_heating", "chiller"): + names.append("efficiency") + return names + + +def field_meta(name: str, eq: dict, unit_mode: str): + """Label, unit converters and decimals of a form field for this item and unit system.""" + label, kind, category, decimals, factor = FORM_FIELDS[name] + eq_type = eq.get("eq_type") + if name == "capacity_W": + category = "power_cooling" if eq_type == "chiller" else "power" + label = "Fixed unit capacity" if eq_type == "heat_pump" else "Capacity" + if name == "efficiency": + label, factor = ("Efficiency [%]", 100) if eq_type == "backup_heating" else ("COP", 1) + if category: + to_display, to_base, unit = edit_unit(category, unit_mode) + label = f"{label} [{unit}]" + else: + to_display, to_base = (lambda v: v * factor), (lambda v: v / factor) + return label, kind, to_display, to_base, decimals + + +def get_path(eq: dict, name: str): + if name == "efficiency": + perf = next(iter((eq.get("performance") or {}).values()), None) or {} + return perf.get("efficiency") + value = eq + for part in name.split("."): + value = (value or {}).get(part) + return value + + +def set_path(eq: dict, name: str, value): + if name == "efficiency": + mode = next(iter(eq.get("performance") or {}), None) + if mode: + eq["performance"][mode]["efficiency"] = value + return + parts = name.split(".") + target = eq + for part in parts[:-1]: + if target.get(part) is None: + target[part] = {} + target = target[part] + target[parts[-1]] = value + + +def display_value(eq: dict, name: str, unit_mode: str): + """A field's value as shown in the form (converted and rounded).""" + _, kind, to_display, _, decimals = field_meta(name, eq, unit_mode) + value = get_path(eq, name) + if kind in ("text", "textarea", "calc_type", "refrigerant"): + return value or "" + if value is None: + return "" + return round(to_display(value), decimals) + + +def _form_input(name: str, eq: dict, unit_mode: str): + label, kind, _, _, decimals = field_meta(name, eq, unit_mode) + field_id = {"type": "eqm-field", "name": name} + value = display_value(eq, name, unit_mode) + if kind == "text": + return dmc.TextInput(id=field_id, label=label, value=value, size="xs", debounce=400) + if kind == "textarea": + return dmc.Textarea( + id=field_id, label=label, value=value, size="xs", autosize=True, minRows=2, debounce=400 + ) + if kind == "calc_type": + return dmc.Select( + id=field_id, label=label, data=CALC_TYPE_OPTIONS, value=value or None, size="xs" + ) + if kind == "refrigerant": + return dmc.Autocomplete( + id=field_id, + label=label, + data=[r.name for r in load_refrigerants()], + value=value, + size="xs", + placeholder="Pick or type a refrigerant", + debounce=400, + ) + known = name == "refrigerant_gwp" and find_refrigerant(eq.get("refrigerant")) is not None + return dmc.NumberInput( + id=field_id, + label=label, + value=value, + decimalScale=decimals, + size="xs", + debounce=400, + disabled=known, + description="From the refrigerant database" if name == "refrigerant_gwp" else None, + ) + + +def overview_form(eq: dict, unit_mode: str): + names = set(form_field_names(eq)) + sections = [] + for title, fields in FORM_SECTIONS: + inputs = [_form_input(n, eq, unit_mode) for n in fields if n in names] + if not inputs: + continue + sections.append(dmc.Text(title, size="xs", fw=700, c="dimmed", tt="uppercase", mt="xs")) + sections.append( + inputs[0] if title == "Notes" else dmc.SimpleGrid(inputs, cols={"base": 1, "sm": 2}) + ) + header = dmc.Text( + f"{eq['eq_id']} · {TYPE_LABELS.get(eq.get('eq_type'), eq.get('eq_type'))} · " + f"{(eq.get('fuel') or '').replace('_', ' ')}" + + (f" · based on {eq['based_on']}" if eq.get("based_on") else ""), + size="xs", + c="dimmed", + ) + return dmc.Stack([header, *sections], gap="xs") + + +# --- Curve editor tables --- +def _num_col(col_id, name, decimals): + return { + "id": col_id, + "name": name, + "type": "numeric", + "format": Format(precision=decimals, scheme=Scheme.fixed), + } + + +def editor_units(mode: str, unit_mode: str): + temp = edit_unit("temperature", unit_mode) + cap = edit_unit("power_cooling" if mode == "cooling" else "power", unit_mode) + return temp, cap + + +def editor_tables(eq: Equipment, mode: str, unit_mode: str): + """Rows and columns of the curve and supply temperature tables, in display units. + + Curve table: one row per curve point, `cop_i` (and `cap_i` for AWHPs with capacity curves) + per supply temperature i. Supply temperature table: one row per supply temperature i. + """ + df = curve_table(eq, mode) + (t_disp, _, t_unit), (c_disp, _, c_unit) = editor_units(mode, unit_mode) + is_awhp = eq.eq_type == "heat_pump" + lwts = sorted(df["lwt_C"].unique()) + has_cap = is_awhp and df["capacity_W"].notna().any() + + # two header rows (merged by the table): a group per supply temperature, COP/capacity beneath + x_name = ( + ["Outdoor air temperature", f"({t_unit})"] + if is_awhp + else ["Capacity at part load", f"({c_unit})"] + ) + columns = [_num_col("x", x_name, 1 if is_awhp else 2)] + for i, lwt in enumerate(lwts): + group = f"Supply {t_disp(lwt):.1f} {t_unit}" + columns.append(_num_col(f"cop_{i}", [group, "COP"], 2)) + if has_cap: + columns.append(_num_col(f"cap_{i}", [group, f"Capacity ({c_unit})"], 2)) + + rows = [] + for x, d in df.groupby("x", sort=True): + d = d.set_index("lwt_C") + row = {"x": float(t_disp(x) if is_awhp else c_disp(x))} + for i, lwt in enumerate(lwts): + row[f"cop_{i}"] = float(d.loc[lwt, "cop"]) + if has_cap: + row[f"cap_{i}"] = float(c_disp(d.loc[lwt, "capacity_W"])) + rows.append(row) + + lwt_columns = [_num_col("lwt", f"Supply temperature ({t_unit})", 1)] + if is_awhp: + lwt_columns += [ + _num_col("oat_min", f"Lowest outdoor air temperature ({t_unit})", 1), + _num_col("oat_max", f"Highest outdoor air temperature ({t_unit})", 1), + ] + limits = df.groupby("lwt_C")[["oat_min_C", "oat_max_C"]].first() + lwt_rows = [] + for lwt in lwts: + row = {"lwt": float(t_disp(lwt))} + if is_awhp: + row["oat_min"] = _nan_to_none(t_disp(limits.loc[lwt, "oat_min_C"])) + row["oat_max"] = _nan_to_none(t_disp(limits.loc[lwt, "oat_max_C"])) + lwt_rows.append(row) + return rows, columns, lwt_rows, lwt_columns + + +def _nan_to_none(v): + return None if pd.isna(v) else float(v) + + +def to_float(v): + """A table cell as float; blank or invalid cells become NaN and fail validation.""" + try: + return float(v) + except (TypeError, ValueError): + return float("nan") + + +def tables_to_long(eq: Equipment, mode: str, unit_mode: str, rows, lwt_rows) -> pd.DataFrame: + """Curve and supply temperature tables (display units) as a `curve_table` long table (SI).""" + (_, t_base, _), (_, c_base, _) = editor_units(mode, unit_mode) + is_awhp = eq.eq_type == "heat_pump" + records = [] + for i, lwt_row in enumerate(lwt_rows): + lwt = t_base(to_float(lwt_row.get("lwt"))) + for row in rows: + x = to_float(row.get("x")) + cap_key = f"cap_{i}" + records.append( + { + "x": t_base(x) if is_awhp else c_base(x), + "lwt_C": lwt, + "cop": to_float(row.get(f"cop_{i}")), + "capacity_W": ( + c_base(to_float(row.get(cap_key))) + if is_awhp and cap_key in row + else (c_base(x) if not is_awhp else float("nan")) + ), + "oat_min_C": t_base(to_float(lwt_row.get("oat_min"))) if is_awhp else None, + "oat_max_C": t_base(to_float(lwt_row.get("oat_max"))) if is_awhp else None, + } + ) + return pd.DataFrame(records) + + +def scale_values(eq: Equipment, mode: str): + factors = (eq.scaling or {}).get(mode, {}) + return round(factors.get("cop", 1.0) * 100, 1), round(factors.get("capacity", 1.0) * 100, 1) diff --git a/layout/input.py b/layout/input.py index 99d29f4..1662061 100644 --- a/layout/input.py +++ b/layout/input.py @@ -14,7 +14,7 @@ value_deemphasis_style, ) from src import paths -from src.config import LINKS, EmissionTableRows, EquipmentTableRows +from src.config import LINKS, URLS, EmissionTableRows, EquipmentTableRows from utils.tooltips import with_icon_and_tooltip, with_tooltip @@ -38,7 +38,7 @@ def get_emissions_index(): def unit_toggle(): return dmc.SegmentedControl( id="unit-toggle", # keep your existing id if you already use it - value="SI", # or "IP" + value="IP", # default unit system; "SI" or "IP" data=[ {"label": "SI", "value": "SI"}, {"label": "IP", "value": "IP"}, @@ -586,7 +586,7 @@ def build_equipment_table( view_mode: One of "simple", "advanced", or "differences" unit_mode: "SI" or "IP" for unit conversion """ - from utils.units import get_unit_converter, get_unit_label + from utils.units import get_converter, get_display_unit if isinstance(equipment_data, list): equipment_df = pd.DataFrame(equipment_data) @@ -618,8 +618,9 @@ def build_equipment_table( equipment_df = equipment_df[equipment_df["eq_scen_id"].isin(valid_displayed_ids)] equipment_df = equipment_df.set_index("eq_scen_id").loc[valid_displayed_ids].reset_index() - # Get unit label for temperature (dynamic based on unit_mode) - temp_unit = get_unit_label("temperature", unit_mode) + # Get unit label for temperature and HR source/sink capacity (dynamic based on unit_mode) + temp_unit = get_display_unit("temperature", unit_mode) + power_unit = get_display_unit("power", unit_mode) # Rows to display (property name, label) # Note: eq_scen_id and eq_scen_name are excluded as they're shown in the header @@ -627,6 +628,10 @@ def build_equipment_table( ("hr_wwhp", "HR WWHP Model"), ("hr_wwhp_performance_model", "HR WWHP Performance Calculation Model"), ("hr_wwhp_h_supply_t", f"HR WWHP Heating Supply Temp ({temp_unit})"), + ("hr_eac_rejection_cap_W", f"HR Balancing Heat Rejection Capacity ({power_unit})"), + ("hr_eac_rejection_control", "HR Balancing Heat Rejection Control"), + ("hr_eac_recovery_cap_W", f"HR Balancing Heat Recovery Capacity ({power_unit})"), + ("hr_eac_recovery_control", "HR Balancing Heat Recovery Control"), ("awhp", "AWHP Model"), ("awhp_performance_model", "AWHP Performance Calculation Model"), ("awhp_h_supply_t", f"AWHP Heating Supply Temp ({temp_unit})"), @@ -808,9 +813,13 @@ def build_equipment_table( diff_row_style = TABLE_STYLE.diff_row_style # Get converter for temperature values - temp_converter = get_unit_converter("temperature", unit_mode) + temp_converter = get_converter("temperature", unit_mode) temp_fields = {"hr_wwhp_h_supply_t", "awhp_h_supply_t"} + # Get converter for HR source/sink values + power_converter = get_converter("power", unit_mode) + power_fields = {"hr_eac_rejection_cap_W", "hr_eac_recovery_cap_W"} + for field, label in available_rows: is_diff_row = field in diff_fields @@ -824,13 +833,19 @@ def build_equipment_table( for idx, scen_id in enumerate(scen_ids): raw_value = equipment_df.iloc[idx].get(field, "") - # Apply unit conversion for temperature fields + # Apply unit conversion for temperature and HR source/sink fields if field in temp_fields and raw_value is not None: try: converted = temp_converter(float(raw_value)) display_value = f"{converted:.1f}" except (ValueError, TypeError): display_value = format_table_value(raw_value, field_name=field) + elif field in power_fields and raw_value is not None: + try: + converted = power_converter(float(raw_value)) + display_value = f"{converted:.1f}" + except (ValueError, TypeError): + display_value = format_table_value(raw_value, field_name=field) else: display_value = format_table_value(raw_value, field_name=field) @@ -960,19 +975,69 @@ def edit_equipment_modal(): ], grow=True, ), - dmc.Divider(label="Heat pump selection", labelPosition="center"), + dmc.Accordion( + dmc.AccordionItem( + [ + dmc.AccordionControl( + dmc.Text("Performance curves", size="sm", fw=500), + ), + dmc.AccordionPanel( + dmc.Stack( + [ + dmc.Tabs( + [ + dmc.TabsList( + [ + dmc.TabsTab("AWHP", value="awhp"), + dmc.TabsTab( + "HR heat pump", value="hr_wwhp" + ), + ] + ), + dmc.TabsPanel( + dcc.Graph( + id="edit-awhp-curve-graph", + config={"displaylogo": False}, + ), + value="awhp", + ), + dmc.TabsPanel( + dcc.Graph( + id="edit-hr-wwhp-curve-graph", + config={"displaylogo": False}, + ), + value="hr_wwhp", + ), + ], + value="awhp", + ), + dmc.Text( + [ + "Dashed line: curve at the selected supply temperature. ", + dmc.Anchor( + "View all equipment in the Equipment Manager", + href=URLS.EQUIPMENT_MANAGER.value, + size="xs", + ), + ], + size="xs", + c="dimmed", + ), + ], + gap="xs", + ) + ), + ], + value="curves", + ), + variant="contained", + radius="md", + ), + dmc.Divider(label="Air-to-water heat pump", labelPosition="center", size="md"), dmc.SimpleGrid( cols=2, spacing="md", children=[ - dmc.Select( - id="edit-hr-wwhp-select", - label="HR Heat Pump", - placeholder="None", - data=[], # filled by callback - clearable=True, - searchable=True, - ), dmc.Select( id="edit-awhp-select", label="Air-to-water Heat Pump", @@ -981,19 +1046,6 @@ def edit_equipment_modal(): clearable=True, searchable=True, ), - dmc.Select( - id="edit-hr-wwhp-performance-model", - label="HR HP Performance Calculation Model", - placeholder="None", - data=[ # not including fixed_COP and performance_curves atm - { - "label": "Interpolated table (HHWST fixed)", - "value": "interpolate_HHWST", - } - ], - clearable=True, - searchable=True, - ), dmc.Select( id="edit-awhp-performance-model", label="AWHP Performance Calculation Model", @@ -1011,24 +1063,10 @@ def edit_equipment_modal(): clearable=True, searchable=True, ), - dmc.Stack( - gap=4, - children=[ - dmc.Text( - id="edit-hr-wwhp-h-supply-t-label", - children="HR HP Heating supply temp (°C)", - size="sm", - fw=500, - ), - dmc.NumberInput( - id="edit-hr-wwhp-h-supply-t-value", - placeholder="Enter temperature", - min=32.2, # Updated dynamically by callback - max=73.9, # Updated dynamically by callback - step=0.1, - decimalScale=1, - ), - ], + dmc.Switch( + id="edit-awhp-use-cooling", + label="Use AWHP for cooling", + mt="xs", ), dmc.Stack( gap=4, @@ -1051,82 +1089,182 @@ def edit_equipment_modal(): ), ], ), - dmc.Divider(label="Heat pump sizing", labelPosition="center"), - dmc.Stack( - [ - dmc.SegmentedControl( - id="edit-awhp-sizing-mode", + dmc.Divider(label="Air-to-water heat pump sizing", labelPosition="center"), + dmc.SegmentedControl( + id="edit-awhp-sizing-mode", + data=[ + { + "label": "Integer ceiling method", + "value": "integer_sizing_peak_load", + }, + { + "label": "Fractional method", + "value": "fractional_sizing_peak_load", + }, + { + "label": "Specific # of units", + "value": "fixed_num_units", + }, + ], + fullWidth=True, + ), + dmc.SimpleGrid( + cols=3, + spacing="md", + children=[ + dmc.NumberInput( + id="edit-awhp-sizing-value", + label="Sizing value", + min=0, + max=5, + step=0.05, # will be overridden dynamically + style={"flex": 1}, + ), + dmc.NumberInput( + id="edit-awhp-redundancy", + label="Redundant units", + min=0, + max=5, + step=1, + style={"flex": 1}, + ), + dmc.Select( + id="edit-awhp-sizing-priority", + label="Sizing basis", + placeholder="None", data=[ { - "label": "Integer ceiling method", - "value": "integer_sizing_peak_load", + "label": "Heating load", + "value": "heating", }, { - "label": "Fractional method", - "value": "fractional_sizing_peak_load", + "label": "Cooling load", + "value": "cooling", }, { - "label": "Specific # of units", - "value": "fixed_num_units", + "label": "Larger of heating and cooling load", + "value": "larger", }, ], - fullWidth=True, + clearable=True, + searchable=True, ), - dmc.Group( - [ + ], + ), + dmc.Divider( + label="Heat recovery water-to-water heat pump", + labelPosition="center", + size="md", + ), + dmc.SimpleGrid( + cols=2, + spacing="md", + children=[ + dmc.Select( + id="edit-hr-wwhp-select", + label="HR Heat Pump", + placeholder="None", + data=[], # filled by callback + clearable=True, + searchable=True, + ), + dmc.Select( + id="edit-hr-wwhp-performance-model", + label="HR HP Performance Calculation Model", + placeholder="None", + data=[ # not including fixed_COP and performance_curves atm + { + "label": "Interpolated table (HHWST fixed)", + "value": "interpolate_HHWST", + } + ], + clearable=True, + searchable=True, + ), + dmc.Space(), + dmc.Stack( + gap=4, + children=[ + dmc.Text( + id="edit-hr-wwhp-h-supply-t-label", + children="HR HP Heating supply temp (°C)", + size="sm", + fw=500, + ), dmc.NumberInput( - id="edit-awhp-sizing-value", - label="Sizing value", - min=0, - max=5, - step=0.05, # will be overridden dynamically - style={"flex": 1}, + id="edit-hr-wwhp-h-supply-t-value", + placeholder="Enter temperature", + min=32.2, # Updated dynamically by callback + max=73.9, # Updated dynamically by callback + step=0.1, + decimalScale=1, + ), + ], + ), + ], + ), + dmc.Divider(label="Heat recovery balancing source/sink", labelPosition="center"), + dmc.SimpleGrid( + cols=2, + spacing="md", + children=[ + dmc.Stack( + [ + dmc.Text( + id="edit-hr-eac-rejection-cap-label", + children="Heat rejection capacity (kW)", + size="sm", + fw=500, ), dmc.NumberInput( - id="edit-awhp-redundancy", - label="Redundant units", + id="edit-hr-eac-rejection-cap", min=0, - max=5, - step=1, - style={"flex": 1}, + step=10, + decimalScale=1, ), ], - grow=True, + gap=4, ), - dmc.Group( + dmc.Stack( [ - dmc.Switch( - id="edit-awhp-use-cooling", - label="Use AWHP for cooling", - mt="xs", + dmc.Text( + id="edit-hr-eac-recovery-cap-label", + children="Heat recovery capacity (kW)", + size="sm", + fw=500, ), - dmc.Select( - id="edit-awhp-sizing-priority", - label="Sizing basis", - placeholder="None", - data=[ - { - "label": "Heating load", - "value": "heating", - }, - { - "label": "Cooling load", - "value": "cooling", - }, - { - "label": "Larger of heating and cooling load", - "value": "larger", - }, - ], - clearable=True, - searchable=True, + dmc.NumberInput( + id="edit-hr-eac-recovery-cap", + min=0, + step=10, + decimalScale=1, ), ], - grow=True, + gap=4, + ), + dmc.Select( + id="edit-hr-eac-rejection-control", + label="Heat rejection control", + data=[ + {"label": "Min turndown", "value": "min_turndown"}, + {"label": "Max heat rejection", "value": "max_heat_rejection"}, + ], + value="min_turndown", + allowDeselect=False, + ), + dmc.Select( + id="edit-hr-eac-recovery-control", + label="Heat recovery control", + data=[ + {"label": "Min turndown", "value": "min_turndown"}, + {"label": "Max heat recovery", "value": "max_heat_recovery"}, + ], + value="min_turndown", + allowDeselect=False, ), ], ), - dmc.Divider(label="Backup equipment", labelPosition="center"), + dmc.Divider(label="Backup equipment", labelPosition="center", size="md"), dmc.SimpleGrid( cols=2, spacing="md", @@ -1608,6 +1746,30 @@ def build_completeness_modal(): ) +def _load_modification_buttons(prefix): + """Reset (left) and Cancel / Apply / Confirm (right) for the scale and base load modals. + + Apply only updates the modal's draft; Confirm commits it to the load data. + """ + return dmc.Group( + [ + dmc.Button( + "Reset", id=f"{prefix}-reset-btn", variant="outline", color="red", disabled=True + ), + dmc.Group( + [ + dmc.Button("Cancel", id=f"{prefix}-cancel-btn", variant="outline"), + dmc.Button("Apply", id=f"{prefix}-apply-btn", variant="outline"), + dmc.Button("Confirm", id=f"{prefix}-confirm-btn", color="blue"), + ], + gap="sm", + ), + ], + justify="space-between", + mt="md", + ) + + def build_scale_load_modal(): """Modal for scaling/normalizing a library load profile.""" return dmc.Modal( @@ -1619,7 +1781,9 @@ def build_scale_load_modal(): children=[ dmc.Text( "Scale the library load profile to match your building. " - "Every hourly heating and cooling load will be multiplied by the computed scale factor.", + "Scaling by building area multiplies every hourly heating and cooling load by the " + "computed scale factor; scaling by peak heating or peak cooling load only changes " + "that load. Apply updates the table; Confirm uses the result in the calculation.", size="sm", c="dimmed", ), @@ -1649,16 +1813,10 @@ def build_scale_load_modal(): mt=4, ), dmc.Space(h="sm"), - dmc.Text(id="scale-preview-text", c="blue", size="sm", fw=500), - dmc.Text(id="scale-error-text", c="red", size="sm"), - dmc.Group( - [ - dmc.Button("Cancel", id="scale-cancel-btn", variant="outline"), - dmc.Button("Apply", id="scale-apply-btn", color="blue"), - ], - justify="flex-end", - mt="md", - ), + # Status line: always filled so the layout doesn't jump; colour set by callback + dmc.Text("No scaling applied", id="scale-preview-text", c="dimmed", size="sm", fw=500), + _load_modification_buttons("scale"), + dcc.Store(id="scale-draft-store", data=None), ], ) @@ -1674,7 +1832,8 @@ def build_base_load_modal(): children=[ dmc.Text( "Add a minimum floor or a constant offset to model process loads or " - "minimum baseline consumption.", + "minimum baseline consumption. Heating and cooling can each have their own " + "base load. Apply updates the table; Confirm uses the result in the calculation.", size="sm", c="dimmed", ), @@ -1719,16 +1878,12 @@ def build_base_load_modal(): mt=4, ), dmc.Space(h="sm"), - dmc.Text(id="base-load-preview-text", c="blue", size="sm", fw=500), - dmc.Text(id="base-load-error-text", c="red", size="sm"), - dmc.Group( - [ - dmc.Button("Cancel", id="base-load-cancel-btn", variant="outline"), - dmc.Button("Apply", id="base-load-apply-btn", color="blue"), - ], - justify="flex-end", - mt="md", + # Status line: always filled so the layout doesn't jump; colour set by callback + dmc.Text( + "No base load applied", id="base-load-preview-text", c="dimmed", size="sm", fw=500 ), + _load_modification_buttons("base-load"), + dcc.Store(id="base-load-draft-store", data=None), ], ) diff --git a/layout/shell.py b/layout/shell.py index e144251..e61b4cd 100644 --- a/layout/shell.py +++ b/layout/shell.py @@ -11,7 +11,7 @@ from layout.header import shell_header from layout.input import legend_toggle, scenario_legend_accordion, unit_toggle from src import paths -from src.config import DEFAULT_SELECTIONS, LINKS +from src.config import DEFAULT_SELECTIONS, LINKS, URLS from src.equipment import load_library # adjust if path differs from utils.display_registry import ( format_emission_scenario_id_short, @@ -162,8 +162,9 @@ def build_shell(page_content): def build_navbar_content(): + # Workflow steps only; the Equipment Manager is linked next to the documentation instead pages = sorted( - dash.page_registry.values(), + (p for p in dash.page_registry.values() if p["path"] != URLS.EQUIPMENT_MANAGER.value), key=lambda p: p.get("order", 0), ) @@ -182,6 +183,20 @@ def build_navbar_content(): for page in pages ] + equipment_manager_link = dmc.Anchor( + dmc.Group( + [ + DashIconify(icon="material-symbols-light:tune", width=25), + "Equipment Manager", + ], + gap="xs", + align="center", + ), + href=URLS.EQUIPMENT_MANAGER.value, + underline=False, + fz="sm", + ) + docs_link = dmc.Anchor( dmc.Group( [ @@ -235,7 +250,7 @@ def build_navbar_content(): ), dmc.Space(h="2"), dmc.Stack( - [docs_link, repo_link], + [equipment_manager_link, docs_link, repo_link], gap="xs", ), dmc.Divider(), diff --git a/notes/unit-conventions.md b/notes/unit-conventions.md index 94bcbed..994e955 100644 --- a/notes/unit-conventions.md +++ b/notes/unit-conventions.md @@ -212,11 +212,11 @@ UNIT_MAP = { AUTO_SCALE_CONFIG = { "energy": { "SI": [(1e9, "GWh"), (1e6, "MWh"), (1e3, "kWh")], - "IP": [(1e3/3.412, "kBTU")], + "IP": [(1e3 * BTU_to_Wh, "kBTU")], }, "power": { "SI": [(1e6, "MW"), (1e3, "kW")], - "IP": [(1e3/3.412, "kBTU/h")], + "IP": [(1e3 * BTUh_to_W, "kBTU/h")], }, "power_cooling": { "SI": [(1e6, "MW"), (1e3, "kW")], diff --git a/pages/equipment_manager_page.py b/pages/equipment_manager_page.py new file mode 100644 index 0000000..7b349e2 --- /dev/null +++ b/pages/equipment_manager_page.py @@ -0,0 +1,1310 @@ +import base64 +import datetime +import json +import time + +import dash +import dash_mantine_components as dmc +import pandas as pd +from dash import ALL, Input, Output, State, callback, ctx, dash_table, dcc, html, no_update +from dash_iconify import DashIconify + +from layout.equipment_editor import ( + TYPE_LABELS, + display_value, + editor_tables, + editor_units, + field_meta, + overview_form, + scale_values, + set_path, + tables_to_long, + to_float, +) +from src.config import LINKS, URLS +from src.equipment import ( + HEAT_PUMP_TYPES, + Equipment, + apply_curve_table, + curve_table, + delete_custom_equipment, + duplicate_equipment, + export_custom_equipment, + find_refrigerant, + import_custom_equipment, + save_custom_equipment, + scale_performance, + validate_equipment, +) +from src.visuals import empty_figure, plot_performance_curves +from utils.logging_config import get_logger +from utils.tooltips import with_icon_and_tooltip +from utils.units import ( + format_with_auto_scale, + get_auto_scale, + get_converter, + get_display_unit, +) +from utils.version import get_version + +logger = get_logger(__name__) + + +dash.register_page( + __name__, + name="Equipment Manager", + path=URLS.EQUIPMENT_MANAGER.value, + order=99, # not a workflow step; linked separately in the sidebar +) + +TYPE_FILTERS = [ + {"label": "All", "value": "all"}, + {"label": "HR WWHP", "value": "hr_heat_pump"}, + {"label": "AWHP", "value": "heat_pump"}, + {"label": "Backup", "value": "backup_heating"}, + {"label": "Chiller", "value": "chiller"}, +] + +MODE_LABELS = {"heating": "Heating", "cooling": "Cooling"} + +HIDDEN = {"display": "none"} + +TABLE_STYLE = { + "style_table": {"overflowX": "auto"}, + "style_cell": { + "fontFamily": "inherit", + "fontSize": 12, + "padding": "4px 8px", + "border": "1px solid var(--mantine-color-gray-3)", + "minWidth": 70, + }, + "style_header": { + "fontWeight": 600, + "backgroundColor": "var(--mantine-color-gray-0)", + "whiteSpace": "normal", + "height": "auto", + }, +} + + +def _action_button(label, button_id, icon, **kwargs): + return dmc.Button( + label, + id=button_id, + leftSection=DashIconify(icon=icon, width=16), + size="xs", + n_clicks=0, + style=HIDDEN, + **kwargs, + ) + + +def _curve_editor(): + """Scaling panel and editable curve tables, shown while a custom heat pump is edited.""" + return html.Div( + dmc.Stack( + [ + dmc.Paper( + dmc.Stack( + [ + dmc.Text("Scale curves", size="sm", fw=600), + dmc.Group( + [ + dmc.NumberInput( + id="eqm-scale-cop", + label="COP factor", + suffix=" %", + value=100, + min=1, + step=1, + decimalScale=1, + size="xs", + w=120, + ), + dmc.NumberInput( + id="eqm-scale-cap", + label="Capacity factor", + suffix=" %", + value=100, + min=1, + step=1, + decimalScale=1, + size="xs", + w=120, + ), + dmc.Button( + "Apply", id="eqm-scale-apply", size="xs", n_clicks=0 + ), + ], + align="flex-end", + gap="sm", + ), + dmc.Text( + "Factors are relative to the curves before any scaling and apply " + "to every supply temperature of the selected mode. Applying the " + "same factor again changes nothing.", + size="xs", + c="dimmed", + ), + ], + gap=6, + ), + withBorder=True, + radius="sm", + p="sm", + ), + dmc.Text("Curve points", size="sm", fw=600), + html.Div( + dash_table.DataTable( + id="eqm-curve-editor", + data=[], + columns=[], + editable=True, + row_deletable=True, + merge_duplicate_headers=True, + **TABLE_STYLE, + ), + className="eqm-table", + ), + dmc.Group( + dmc.Button( + "Add point", + id="eqm-add-point", + leftSection=DashIconify(icon="tabler:row-insert-bottom", width=16), + size="xs", + variant="light", + n_clicks=0, + ) + ), + dmc.Text("Supply temperatures", size="sm", fw=600, mt="xs"), + html.Div( + dash_table.DataTable( + id="eqm-lwt-editor", + data=[], + columns=[], + editable=True, + **TABLE_STYLE, + ), + className="eqm-table", + ), + dmc.Group( + [ + dmc.NumberInput(id="eqm-new-lwt", placeholder="New", size="xs", w=110), + dmc.Button( + "Add supply temperature", + id="eqm-add-lwt", + size="xs", + variant="light", + n_clicks=0, + ), + dmc.Select(id="eqm-remove-lwt-select", data=[], size="xs", w=110), + dmc.Button( + "Remove", + id="eqm-remove-lwt", + size="xs", + variant="light", + color="red", + n_clicks=0, + ), + ], + gap="xs", + ), + dmc.Text( + "A new supply temperature starts as a copy of the nearest existing curve. " + "The supply temperature limits of the mode follow the range of the curves.", + size="xs", + c="dimmed", + ), + html.Div(id="eqm-curve-editor-msg"), + ], + gap="xs", + ), + id="eqm-curve-editor-wrap", + style=HIDDEN, + ) + + +def layout(): + return dmc.Container( + [ + dcc.Store(id="eqm-selected-store", storage_type="session"), + dcc.Store(id="eqm-draft-store", storage_type="memory", data=None), + dcc.Store(id="eqm-edit-session", storage_type="memory", data=None), + dcc.Store(id="eqm-form-version", storage_type="memory", data=0), + dmc.Stack( + [ + with_icon_and_tooltip( + "Equipment Manager", + "equipment_manager.docs", + order=5, + icon="basil:book-open-outline", + href=LINKS.EQUIPMENT_DOCS_URL.value, + ), + dmc.Text( + "Browse the equipment library and inspect the data behind each item. " + "Duplicate an item to make an editable custom copy; library equipment " + "itself is never changed.", + size="sm", + c="dimmed", + ), + ], + gap=3, + mt="md", + mb="sm", + ), + dmc.Grid( + [ + dmc.GridCol( + dmc.Paper( + dmc.Stack( + [ + dmc.Group( + [ + dcc.Upload( + dmc.Button( + "Import", + leftSection=DashIconify( + icon="tabler:upload", width=16 + ), + size="xs", + variant="light", + ), + id="eqm-import-upload", + accept=".json,application/json", + multiple=False, + ), + dmc.Button( + "Export custom", + id="eqm-export-btn", + leftSection=DashIconify( + icon="tabler:download", width=16 + ), + size="xs", + variant="light", + n_clicks=0, + ), + dcc.Download(id="eqm-download"), + ], + gap="xs", + ), + dmc.SegmentedControl( + id="eqm-type-filter", + data=TYPE_FILTERS, + value="all", + size="xs", + fullWidth=True, + ), + dmc.TextInput( + id="eqm-search", + placeholder="Search model, manufacturer or ID", + leftSection=DashIconify(icon="tabler:search", width=16), + size="sm", + debounce=300, + ), + dmc.ScrollArea( + html.Div(id="eqm-list"), + h=640, + type="hover", + offsetScrollbars=True, + ), + ], + gap="sm", + ), + shadow="xs", + radius="md", + p="md", + ), + span={"base": 12, "md": 4}, + ), + dmc.GridCol( + dmc.Paper( + dmc.Stack( + [ + html.Div(id="eqm-detail-header"), + dmc.Group( + [ + _action_button( + "Duplicate to edit", + "eqm-duplicate-btn", + "tabler:copy", + variant="light", + ), + _action_button("Edit", "eqm-edit-btn", "tabler:pencil"), + _action_button( + "Delete", + "eqm-delete-btn", + "tabler:trash", + variant="subtle", + color="red", + ), + _action_button( + "Save", "eqm-save-btn", "tabler:device-floppy" + ), + _action_button( + "Cancel", + "eqm-cancel-btn", + "tabler:x", + variant="default", + ), + ], + gap="xs", + ), + html.Div(id="eqm-action-msg"), + dmc.Tabs( + [ + dmc.TabsList( + [ + dmc.TabsTab("Performance", value="performance"), + dmc.TabsTab("Overview", value="overview"), + ] + ), + dmc.TabsPanel( + dmc.Stack( + [ + dmc.SegmentedControl( + id="eqm-mode", + data=[], + value=None, + size="xs", + style={"alignSelf": "flex-start"}, + ), + html.Div(id="eqm-issues"), + dcc.Graph( + id="eqm-curve-graph", + figure=empty_figure(""), + config={"displaylogo": False}, + ), + html.Div(id="eqm-curve-table"), + _curve_editor(), + ], + gap="sm", + pt="sm", + ), + value="performance", + ), + dmc.TabsPanel( + html.Div( + id="eqm-overview", style={"paddingTop": 8} + ), + value="overview", + ), + ], + value="performance", + ), + ], + gap="sm", + ), + shadow="xs", + radius="md", + p="md", + ), + span={"base": 12, "md": 8}, + ), + ], + gutter="md", + ), + ], + fluid=True, + ) + + +# ---------------------------------------- Helpers ---------------------------------------- + + +def _resolve_selected_id(equipment_list, selected_id): + """The selected eq_id if it still exists, otherwise the first heat pump in the library.""" + ids = [e.get("eq_id") for e in equipment_list] + if selected_id in ids: + return selected_id + first_hp = next( + (e["eq_id"] for e in equipment_list if e.get("eq_type") in HEAT_PUMP_TYPES), None + ) + return first_hp or (ids[0] if ids else None) + + +def _find_equipment(equipment_data, eq_id) -> Equipment | None: + eq = next( + (e for e in (equipment_data or {}).get("equipment", []) if e.get("eq_id") == eq_id), None + ) + return Equipment(**eq) if eq else None + + +def _editing(session, draft, selected_id) -> bool: + """Whether the selected item is open in the editor.""" + return bool(session and draft and session.get("eq_id") == selected_id) + + +def _capacity_label(eq: Equipment, unit_mode: str) -> str: + """Capacity as shown in the scenario dropdowns (see equipment_page._build_equipment_options).""" + if eq.eq_calc_type != "specific": + return "Infinite capacity" + if eq.eq_type == "backup_heating": + return format_with_auto_scale(eq.capacity_W, "power", unit_mode) + return format_with_auto_scale(eq.nominal_capacity_W, "power_cooling", unit_mode) + + +def _source_badge(eq: Equipment): + if eq.source == "custom": + return dmc.Badge("Custom", color="grape", variant="light", size="sm") + return dmc.Badge("Library", color="gray", variant="light", size="sm") + + +def _scaling_text(eq: Equipment) -> str | None: + if not eq.scaling: + return None + return "; ".join( + f"{MODE_LABELS.get(m, m)}: COP {f.get('cop', 1) * 100:.0f} %, " + f"capacity {f.get('capacity', 1) * 100:.0f} %" + for m, f in eq.scaling.items() + ) + + +def _list_item(eq: Equipment, selected: bool, unit_mode: str): + title = f"{eq.eq_manufacturer} {eq.model}" if eq.eq_manufacturer else eq.model + return dmc.UnstyledButton( + dmc.Paper( + dmc.Group( + [ + dmc.Stack( + [ + dmc.Text(title, size="sm", fw=600), + dmc.Text( + f"{eq.eq_id} · {_capacity_label(eq, unit_mode)}", + size="xs", + c="dimmed", + ), + ], + gap=0, + ), + _source_badge(eq), + ], + justify="space-between", + wrap="nowrap", + ), + p="xs", + radius="sm", + withBorder=True, + style={ + "borderColor": "var(--mantine-color-blue-6)" if selected else None, + "backgroundColor": "var(--mantine-color-blue-0)" if selected else None, + }, + ), + id={"type": "eqm-item", "eq_id": eq.eq_id}, + n_clicks=0, + w="100%", + ) + + +def _overview_table(eq: Equipment, unit_mode: str): + def fmt(value, category=None, decimals=1): + if value is None: + return "—" + if category: + return format_with_auto_scale(value, category, unit_mode, decimals=decimals) + return str(value) + + rows = [ + ("ID", eq.eq_id), + ("Type", TYPE_LABELS.get(eq.eq_type, eq.eq_type)), + ("Subtype", fmt(eq.eq_subtype)), + ("Manufacturer", fmt(eq.eq_manufacturer)), + ("Model", eq.model), + ( + "Source", + "Custom" + (f" (based on {eq.based_on})" if eq.based_on else "") + if eq.source == "custom" + else "Library", + ), + ("Fuel", eq.fuel.replace("_", " ")), + ("Capacity", _capacity_label(eq, unit_mode)), + ] + if eq.eq_type == "heat_pump" and eq.capacity_W: + rows.append(("Fixed unit capacity", fmt(eq.capacity_W, "power"))) + for mode, perf in eq.performance.items(): + if perf.efficiency is not None: + label = "Efficiency" if eq.eq_type == "backup_heating" else "COP" + value = ( + f"{perf.efficiency * 100:.0f} %" + if eq.eq_type == "backup_heating" + else f"{perf.efficiency:.2f}" + ) + rows.append((f"{label} ({mode})", value)) + if eq.scaling: + rows.append(("Curve scaling", _scaling_text(eq))) + if eq.eq_type in HEAT_PUMP_TYPES or eq.refrigerant: + rows += [ + ("Refrigerant", fmt(eq.refrigerant)), + ("Refrigerant GWP", fmt(eq.refrigerant_gwp, "gwp", decimals=0)), + ("Refrigerant charge", fmt(eq.refrigerant_weight_g, "mass_g")), + ("Operating weight", fmt(eq.operating_weight_g, "mass_g", decimals=0)), + ] + if eq.dimensions: + d = eq.dimensions + factor, unit = (1, "m") if unit_mode == "SI" else (3.28084, "ft") + dims = [v for v in (d.length, d.width, d.height) if v is not None] + rows.append( + ("Dimensions (L x W x H)", " x ".join(f"{v * factor:.1f}" for v in dims) + f" {unit}") + ) + if eq.electrical: + e = eq.electrical + rows.append( + ("Electrical", f"MCA {fmt(e.mca)} A · {fmt(e.voltage)} V · {fmt(e.phase)} phase") + ) + if eq.max_output_dba is not None: + rows.append(("Max. sound level", f"{eq.max_output_dba:.0f} dBA")) + if eq.notes: + rows.append(("Notes", eq.notes)) + + # Explicit rows: components inside Table's `data` prop are not rendered by Dash + return dmc.Table( + dmc.TableTbody( + [ + dmc.TableTr( + [ + dmc.TableTd(dmc.Text(k, size="sm", c="dimmed")), + dmc.TableTd(dmc.Text(v, size="sm")), + ] + ) + for k, v in rows + ] + ), + withRowBorders=True, + verticalSpacing=6, + ) + + +def _issues_block(eq: Equipment, mode: str): + issues = validate_equipment(eq, (mode,)) + if not issues: + return dmc.Text( + [ + DashIconify(icon="tabler:circle-check", width=14, style={"verticalAlign": "-2px"}), + " Data checks passed", + ], + size="xs", + c="green", + ) + return dmc.Stack( + [ + dmc.Alert( + i.message, + color="red" if i.severity == "error" else "yellow", + variant="light", + p="xs", + title="Error" if i.severity == "error" else "Warning", + ) + for i in issues + ], + gap=4, + ) + + +def _curve_data_table(eq: Equipment, mode: str, unit_mode: str): + """Wide table: one row per curve point, a COP (and capacity) column per supply temperature.""" + df = curve_table(eq, mode) + if df.empty: + return None + + to_temp = get_converter("temperature", unit_mode) + t_unit = get_display_unit("temperature", unit_mode) + cap_category = "power_cooling" if mode == "cooling" else "power" + is_awhp = df["x_kind"].iloc[0] == "t_out_C" + + # one scale for the whole table, matching the plot axis + cap_scale, cap_unit = get_auto_scale( + df["capacity_W"].dropna().tolist() or [eq.capacity_W or 0], cap_category, unit_mode + ) + + def cap(v): + return "—" if pd.isna(v) else f"{v / cap_scale:,.1f}" + + lwts = sorted(df["lwt_C"].unique()) + x_points = sorted(df["x"].unique()) + has_cap = is_awhp and df["capacity_W"].notna().any() + + def th(text, unit=None, **span): + # html.Th: dmc.TableTh has no rowSpan/colSpan + unit_line = html.Span(unit, className="eqm-unit") if unit else None + return html.Th([text, unit_line], **span) + + # two header rows: a group per supply temperature, with COP (and capacity) beneath + per_lwt = 2 if has_cap else 1 + head = dmc.TableThead( + [ + dmc.TableTr( + [ + th( + "Outdoor air temperature" if is_awhp else "Capacity at part load", + t_unit if is_awhp else cap_unit, + rowSpan=2, + ), + *[ + th( + f"Supply {to_temp(lwt):.1f} {t_unit}", + colSpan=per_lwt, + style={"textAlign": "center"}, + ) + for lwt in lwts + ], + ] + ), + dmc.TableTr( + [ + cell + for _ in lwts + for cell in ([th("COP")] + ([th("Capacity", cap_unit)] if has_cap else [])) + ] + ), + ] + ) + + body = [] + for x in x_points: + row = [f"{to_temp(x):.1f}" if is_awhp else cap(x)] + for lwt in lwts: + point = df[(df["lwt_C"] == lwt) & (df["x"] == x)].iloc[0] + row.append(f"{point['cop']:.2f}") + if has_cap: + row.append(cap(point["capacity_W"])) + body.append(row) + + caption = None + if is_awhp: + limits = df.groupby("lwt_C")[["oat_min_C", "oat_max_C"]].first().sort_index().itertuples() + caption = "Outdoor air temperature limits: " + "; ".join( + f"{to_temp(r.Index):.1f} {t_unit}: {to_temp(r.oat_min_C):.1f} to {to_temp(r.oat_max_C):.1f} {t_unit}" + for r in limits + ) + if not has_cap and eq.capacity_W: + caption += f". Fixed unit capacity: {format_with_auto_scale(eq.capacity_W, cap_category, unit_mode)}" + + return dmc.Stack( + [ + dmc.TableScrollContainer( + dmc.Table( + [ + head, + dmc.TableTbody( + [dmc.TableTr([dmc.TableTd(v) for v in row]) for row in body] + ), + ], + striped=True, + highlightOnHover=True, + withColumnBorders=True, + fz="xs", + verticalSpacing=4, + className="eqm-table", + ), + minWidth=400, + ), + dmc.Text(caption, size="xs", c="dimmed") if caption else None, + ], + gap=4, + ) + + +def _message(text, color="blue"): + return dmc.Alert(text, color=color, variant="light", p="xs", withCloseButton=True) + + +# ---------------------------------------- Callbacks ---------------------------------------- + + +@callback( + Output("eqm-list", "children"), + Input("equipment-store", "data"), + Input("eqm-type-filter", "value"), + Input("eqm-search", "value"), + Input("eqm-selected-store", "data"), + Input("unit-toggle", "value"), +) +def render_equipment_list(equipment_data, type_filter, search, selected_id, unit_mode): + equipment_list = (equipment_data or {}).get("equipment", []) + if not equipment_list: + return dmc.Text("No equipment available.", size="sm", c="dimmed") + + selected_id = _resolve_selected_id(equipment_list, selected_id) + query = (search or "").strip().lower() + + groups = [] + for eq_type, label in TYPE_LABELS.items(): + if type_filter not in (None, "all", eq_type): + continue + items = [] + for e in equipment_list: + if e.get("eq_type") != eq_type: + continue + haystack = " ".join(str(e.get(k) or "") for k in ("eq_id", "model", "eq_manufacturer")) + if query and query not in haystack.lower(): + continue + items.append(_list_item(Equipment(**e), e["eq_id"] == selected_id, unit_mode or "SI")) + if items: + groups.append(dmc.Text(label, size="xs", fw=700, c="dimmed", tt="uppercase", mt="xs")) + groups.extend(items) + + if not groups: + return dmc.Text("No equipment matches the filter.", size="sm", c="dimmed") + return dmc.Stack(groups, gap=6) + + +@callback( + Output("eqm-selected-store", "data"), + Output("eqm-draft-store", "data", allow_duplicate=True), + Output("eqm-edit-session", "data", allow_duplicate=True), + Output("eqm-action-msg", "children", allow_duplicate=True), + Input({"type": "eqm-item", "eq_id": ALL}, "n_clicks"), + State("eqm-edit-session", "data"), + prevent_initial_call=True, +) +def select_equipment(n_clicks, session): + # The list is re-rendered on every selection, which re-fires this with n_clicks=0 + if not ctx.triggered_id or not any(n_clicks or []): + return no_update, no_update, no_update, no_update + eq_id = ctx.triggered_id["eq_id"] + if session and session.get("eq_id") != eq_id: + # selecting another item discards unsaved edits + return eq_id, None, None, None + return eq_id, no_update, no_update, no_update + + +@callback( + Output("eqm-mode", "data"), + Output("eqm-mode", "value"), + Output("eqm-mode", "style"), + Input("eqm-selected-store", "data"), + Input("equipment-store", "data"), + State("eqm-mode", "value"), +) +def update_mode_options(selected_id, equipment_data, current_mode): + equipment_list = (equipment_data or {}).get("equipment", []) + eq = _find_equipment(equipment_data, _resolve_selected_id(equipment_list, selected_id)) + modes = list(eq.performance) if eq else [] + data = [{"label": MODE_LABELS.get(m, m.title()), "value": m} for m in modes] + value = current_mode if current_mode in modes else (modes[0] if modes else None) + style = {"alignSelf": "flex-start", "display": "flex" if len(modes) > 1 else "none"} + return data, value, style + + +@callback( + Output("eqm-duplicate-btn", "style"), + Output("eqm-duplicate-btn", "children"), + Output("eqm-edit-btn", "style"), + Output("eqm-delete-btn", "style"), + Output("eqm-save-btn", "style"), + Output("eqm-cancel-btn", "style"), + Input("eqm-selected-store", "data"), + Input("equipment-store", "data"), + Input("eqm-edit-session", "data"), + Input("eqm-draft-store", "data"), +) +def update_action_buttons(selected_id, equipment_data, session, draft): + show = {} + equipment_list = (equipment_data or {}).get("equipment", []) + selected_id = _resolve_selected_id(equipment_list, selected_id) + eq = _find_equipment(equipment_data, selected_id) + if eq is None: + return HIDDEN, no_update, HIDDEN, HIDDEN, HIDDEN, HIDDEN + if _editing(session, draft, selected_id): + return HIDDEN, no_update, HIDDEN, HIDDEN, show, show + if eq.source == "custom": + return show, "Duplicate", show, show, HIDDEN, HIDDEN + return show, "Duplicate to edit", HIDDEN, HIDDEN, HIDDEN, HIDDEN + + +@callback( + Output("equipment-store", "data", allow_duplicate=True), + Output("eqm-selected-store", "data", allow_duplicate=True), + Output("eqm-draft-store", "data", allow_duplicate=True), + Output("eqm-edit-session", "data", allow_duplicate=True), + Output("eqm-action-msg", "children"), + Input("eqm-duplicate-btn", "n_clicks"), + Input("eqm-edit-btn", "n_clicks"), + Input("eqm-delete-btn", "n_clicks"), + Input("eqm-save-btn", "n_clicks"), + Input("eqm-cancel-btn", "n_clicks"), + State("eqm-selected-store", "data"), + State("equipment-store", "data"), + State("equipment-initial-store", "data"), + State("eqm-draft-store", "data"), + prevent_initial_call=True, +) +def handle_actions( + _dup, _edit, _delete, _save, _cancel, selected_id, equipment_data, initial_data, draft +): + trigger = ctx.triggered_id + if not trigger or not ctx.triggered[0]["value"]: + return (no_update,) * 5 + + equipment_list = (equipment_data or {}).get("equipment", []) + selected_id = _resolve_selected_id(equipment_list, selected_id) + eq = _find_equipment(equipment_data, selected_id) + library_ids = [e["eq_id"] for e in (initial_data or {}).get("equipment", [])] + + if trigger == "eqm-cancel-btn": + return no_update, no_update, None, None, None + + if eq is None: + return (no_update,) * 4 + (_message("No equipment selected.", "red"),) + + if trigger == "eqm-duplicate-btn": + copy = duplicate_equipment(eq, [e["eq_id"] for e in equipment_list]) + updated = save_custom_equipment(equipment_data, copy, library_ids) + logger.info("Created custom equipment '%s' from '%s'", copy.eq_id, eq.eq_id) + return ( + updated, + copy.eq_id, + copy.model_dump(), + {"eq_id": copy.eq_id, "started": time.time()}, + _message(f"Created the custom copy {copy.eq_id}. Edit it below, then Save."), + ) + + if trigger == "eqm-edit-btn": + if eq.source != "custom": + return (no_update,) * 4 + (_message("Library equipment cannot be edited.", "red"),) + return ( + no_update, + no_update, + eq.model_dump(), + {"eq_id": eq.eq_id, "started": time.time()}, + None, + ) + + if trigger == "eqm-delete-btn": + try: + updated = delete_custom_equipment(equipment_data, eq.eq_id) + except ValueError as err: + return (no_update,) * 4 + (_message(str(err), "red"),) + logger.info("Deleted custom equipment '%s'", eq.eq_id) + return updated, eq.based_on, None, None, _message(f"Deleted {eq.eq_id}.") + + # save + if not draft: + return (no_update,) * 5 + edited = Equipment(**draft) + errors = [i for i in validate_equipment(edited) if i.severity == "error"] + if errors: + return (no_update,) * 4 + ( + _message( + [ + dmc.Text("Fix these problems before saving:", size="sm"), + dmc.List([dmc.ListItem(i.message) for i in errors], size="sm"), + ], + "red", + ), + ) + try: + updated = save_custom_equipment(equipment_data, edited, library_ids) + except ValueError as err: + return (no_update,) * 4 + (_message(str(err), "red"),) + logger.info("Saved custom equipment '%s'", edited.eq_id) + return updated, no_update, None, None, _message(f"Saved {edited.eq_id}.", "green") + + +@callback( + Output("eqm-overview", "children"), + Input("eqm-selected-store", "data"), + Input("equipment-store", "data"), + Input("unit-toggle", "value"), + Input("eqm-edit-session", "data"), + Input("eqm-form-version", "data"), + State("eqm-draft-store", "data"), +) +def render_overview(selected_id, equipment_data, unit_mode, session, _version, draft): + # Rendered from the draft only when editing starts or the units change, so that typing + # in the form is not interrupted by re-rendering it + unit_mode = unit_mode or "SI" + equipment_list = (equipment_data or {}).get("equipment", []) + selected_id = _resolve_selected_id(equipment_list, selected_id) + if _editing(session, draft, selected_id): + return overview_form(draft, unit_mode) + eq = _find_equipment(equipment_data, selected_id) + return _overview_table(eq, unit_mode) if eq else None + + +@callback( + Output("eqm-draft-store", "data", allow_duplicate=True), + Input({"type": "eqm-field", "name": ALL}, "value"), + State({"type": "eqm-field", "name": ALL}, "id"), + State("eqm-draft-store", "data"), + State("eqm-edit-session", "data"), + State("unit-toggle", "value"), + prevent_initial_call=True, +) +def update_draft_from_form(values, ids, draft, session, unit_mode): + if not draft or not session or not ids: + return no_update + unit_mode = unit_mode or "SI" + triggered = {t["prop_id"].rsplit(".", 1)[0] for t in ctx.triggered} + changed = False + for field_id, value in zip(ids, values, strict=True): + name = field_id["name"] + if _id_str(field_id) not in triggered: + continue + if value == display_value(draft, name, unit_mode): + continue # keep the stored value instead of its rounded display value + _, kind, _, to_base, _ = field_meta(name, draft, unit_mode) + if kind in ("text", "textarea", "calc_type", "refrigerant"): + new = (value or "").strip() or None + if name == "model" and new is None: + continue # the model name is required + elif value in (None, ""): + new = None + else: + new = to_base(float(value)) + if name in ("nominal_capacity_W", "electrical.phase"): + new = round(new) + set_path(draft, name, new) + if name == "refrigerant" and (match := find_refrigerant(new)) is not None: + draft["refrigerant_gwp"] = match.gwp + changed = True + return draft if changed else no_update + + +def _id_str(field_id: dict) -> str: + """A pattern-matching id as it appears in ctx.triggered prop ids.""" + return json.dumps(field_id, sort_keys=True, separators=(",", ":")) + + +@callback( + Output({"type": "eqm-field", "name": "refrigerant_gwp"}, "value"), + Output({"type": "eqm-field", "name": "refrigerant_gwp"}, "disabled"), + Input({"type": "eqm-field", "name": "refrigerant"}, "value"), + prevent_initial_call=True, +) +def fill_refrigerant_gwp(refrigerant): + match = find_refrigerant(refrigerant) + if match is None: + return no_update, False # unknown refrigerant: enter the GWP manually + return match.gwp, True + + +@callback( + Output("eqm-detail-header", "children"), + Output("eqm-issues", "children"), + Output("eqm-curve-graph", "figure"), + Output("eqm-curve-graph", "style"), + Output("eqm-curve-table", "children"), + Output("eqm-curve-editor-wrap", "style"), + Input("eqm-selected-store", "data"), + Input("eqm-mode", "value"), + Input("equipment-store", "data"), + Input("unit-toggle", "value"), + Input("eqm-draft-store", "data"), + Input("eqm-edit-session", "data"), +) +def render_equipment_detail(selected_id, mode, equipment_data, unit_mode, draft, session): + unit_mode = unit_mode or "SI" + equipment_list = (equipment_data or {}).get("equipment", []) + selected_id = _resolve_selected_id(equipment_list, selected_id) + editing = _editing(session, draft, selected_id) + eq = Equipment(**draft) if editing else _find_equipment(equipment_data, selected_id) + if eq is None: + return None, None, empty_figure("No equipment selected"), HIDDEN, None, HIDDEN + + if mode not in eq.performance: + mode = next(iter(eq.performance), None) + + title = f"{eq.eq_manufacturer} {eq.model}" if eq.eq_manufacturer else eq.model + badges = [_source_badge(eq)] + if editing: + badges.insert(0, dmc.Badge("Editing", color="orange", variant="filled", size="sm")) + header = dmc.Group( + [ + dmc.Stack( + [ + # keep the model's own capitalisation (the theme sets headings in uppercase) + dmc.Title(title, order=4, tt="none", lts="normal"), + dmc.Text( + f"{TYPE_LABELS.get(eq.eq_type, eq.eq_type)} · {eq.eq_id}", + size="sm", + c="dimmed", + ), + ], + gap=0, + ), + dmc.Group(badges, gap=4), + ], + justify="space-between", + ) + + issues = _issues_block(eq, mode) if mode else None + + if eq.eq_type not in HEAT_PUMP_TYPES: + perf = eq.performance.get(mode) if mode else None + if perf and perf.efficiency is not None: + text = ( + f"Constant efficiency of {perf.efficiency * 100:.0f} %." + if eq.eq_type == "backup_heating" + else f"Constant COP of {perf.efficiency:.2f}." + ) + else: + text = "No performance data." + note = f"{text} This equipment has no performance curves." + if editing: + note += " Edit its efficiency in the Overview tab." + return header, issues, empty_figure(""), HIDDEN, dmc.Text(note, size="sm"), HIDDEN + + compare_to = None + if editing or eq.source == "custom": + compare_to = _find_equipment(equipment_data, eq.based_on) if eq.based_on else None + if not editing or _plottable(eq, mode): + fig = plot_performance_curves(eq, mode, unit_mode, compare_to=compare_to) + else: + fig = empty_figure("Fix the errors above to see the curves") + if editing: + return header, issues, fig, {}, None, {} + return header, issues, fig, {}, _curve_data_table(eq, mode, unit_mode), HIDDEN + + +def _plottable(eq: Equipment, mode: str) -> bool: + """Whether a draft's curves can be drawn: errors in limits or values still plot, broken shapes do not.""" + try: + df = curve_table(eq, mode) + except (ValueError, TypeError): + return False + return not df.empty and df["x"].notna().all() + + +@callback( + Output("eqm-draft-store", "data", allow_duplicate=True), + Output("eqm-curve-editor", "data"), + Output("eqm-curve-editor", "columns"), + Output("eqm-lwt-editor", "data"), + Output("eqm-lwt-editor", "columns"), + Output("eqm-remove-lwt-select", "data"), + Output("eqm-remove-lwt-select", "value"), + Output("eqm-scale-cop", "value"), + Output("eqm-scale-cap", "value"), + Output("eqm-curve-editor-msg", "children"), + Output("eqm-form-version", "data"), + Input("eqm-edit-session", "data"), + Input("eqm-mode", "value"), + Input("unit-toggle", "value"), + Input("eqm-curve-editor", "data_timestamp"), + Input("eqm-lwt-editor", "data_timestamp"), + Input("eqm-scale-apply", "n_clicks"), + Input("eqm-add-point", "n_clicks"), + Input("eqm-add-lwt", "n_clicks"), + Input("eqm-remove-lwt", "n_clicks"), + State("eqm-curve-editor", "data"), + State("eqm-lwt-editor", "data"), + State("eqm-draft-store", "data"), + State("eqm-scale-cop", "value"), + State("eqm-scale-cap", "value"), + State("eqm-new-lwt", "value"), + State("eqm-remove-lwt-select", "value"), + State("eqm-form-version", "data"), + prevent_initial_call=True, +) +def edit_curves( + session, + mode, + unit_mode, + _curve_ts, + _lwt_ts, + _scale, + _add_point, + _add_lwt, + _remove_lwt, + rows, + lwt_rows, + draft, + cop_pct, + cap_pct, + new_lwt, + remove_lwt, + form_version, +): + """All edits of the curves of the draft; the tables are re-rendered after structural changes.""" + unit_mode = unit_mode or "SI" + if not session or not draft or draft.get("eq_type") not in HEAT_PUMP_TYPES: + return (no_update,) * 11 + eq = Equipment(**draft) + if mode not in eq.performance: + mode = next(iter(eq.performance), None) + if mode is None: + return (no_update,) * 11 + + trigger = ctx.triggered_id + message = None + rerender_form = False + + def render(eq, new_draft): + tables = editor_tables(eq, mode, unit_mode) + lwt_options = [ + {"label": f"{r['lwt']:.1f}", "value": str(i)} for i, r in enumerate(tables[2]) + ] + cop, cap = scale_values(eq, mode) + return ( + new_draft, + *tables, + lwt_options, + None, + cop, + cap, + message, + form_version + 1 if rerender_form else no_update, + ) + + if trigger in ("eqm-edit-session", "eqm-mode", "unit-toggle"): + return render(eq, no_update) + + try: + if trigger == "eqm-curve-editor": + # plain value edits: update the draft, keep the table as typed + df = tables_to_long(eq, mode, unit_mode, rows or [], lwt_rows or []) + if df.empty: + return (no_update,) * 9 + ( + _message("Keep at least one curve point.", "red"), + no_update, + ) + eq = apply_curve_table(eq, mode, df) + return (eq.model_dump(),) + (no_update,) * 10 + + if trigger == "eqm-lwt-editor": + lwts = [to_float(r.get("lwt")) for r in lwt_rows or []] + if any(pd.isna(t) for t in lwts) or len({round(t, 1) for t in lwts}) < len(lwts): + return (no_update,) * 9 + ( + _message("Each supply temperature needs a value, and no value twice.", "red"), + no_update, + ) + df = tables_to_long(eq, mode, unit_mode, rows or [], lwt_rows or []) + eq = apply_curve_table(eq, mode, df) + + elif trigger == "eqm-scale-apply": + eq = scale_performance(eq, mode, (cop_pct or 100) / 100, (cap_pct or 100) / 100) + rerender_form = True # nominal and fixed capacity are shown in the form + + elif trigger == "eqm-add-point": + rows = [dict(r) for r in rows or []] + if not rows: + return (no_update,) * 11 + xs = [to_float(r.get("x")) for r in rows] + step = xs[-1] - xs[-2] if len(xs) > 1 else 5.0 + rows.append({**rows[-1], "x": xs[-1] + step}) + eq = apply_curve_table(eq, mode, tables_to_long(eq, mode, unit_mode, rows, lwt_rows)) + + elif trigger == "eqm-add-lwt": + if new_lwt in (None, ""): + return (no_update,) * 9 + ( + _message("Enter the new supply temperature.", "red"), + no_update, + ) + (_, t_base, _), _ = editor_units(mode, unit_mode) + lwt_C = t_base(float(new_lwt)) + df = curve_table(eq, mode) + if (df["lwt_C"] - lwt_C).abs().min() < 0.05: + return (no_update,) * 9 + ( + _message("This supply temperature already exists.", "red"), + no_update, + ) + nearest = df.loc[(df["lwt_C"] - lwt_C).abs().idxmin(), "lwt_C"] + new_curve = df[df["lwt_C"] == nearest].assign(lwt_C=lwt_C) + eq = apply_curve_table(eq, mode, pd.concat([df, new_curve], ignore_index=True)) + message = _message( + "Added a copy of the nearest curve. Adjust its values in the table above." + ) + + elif trigger == "eqm-remove-lwt": + df = curve_table(eq, mode) + lwts = sorted(df["lwt_C"].unique()) + if remove_lwt is None: + return (no_update,) * 9 + ( + _message("Pick the supply temperature to remove.", "red"), + no_update, + ) + if len(lwts) < 2: + return (no_update,) * 9 + ( + _message("Keep at least one supply temperature.", "red"), + no_update, + ) + eq = apply_curve_table(eq, mode, df[df["lwt_C"] != lwts[int(remove_lwt)]]) + + else: + return (no_update,) * 11 + except (ValueError, TypeError, KeyError) as err: + return (no_update,) * 9 + (_message(f"Could not apply the change: {err}", "red"), no_update) + + return render(eq, eq.model_dump()) + + +@callback( + Output("eqm-download", "data"), + Output("eqm-action-msg", "children", allow_duplicate=True), + Input("eqm-export-btn", "n_clicks"), + State("equipment-store", "data"), + prevent_initial_call=True, +) +def export_equipment(n_clicks, equipment_data): + if not n_clicks: + return no_update, no_update + payload = export_custom_equipment(equipment_data, get_version()) + if not payload["equipment"]: + return no_update, _message( + "There is no custom equipment to export yet. Duplicate an item to make one.", "yellow" + ) + filename = f"decarb_custom_equipment_{datetime.date.today().isoformat()}.json" + n = len(payload["equipment"]) + return ( + dcc.send_string(json.dumps(payload, indent=2), filename), + _message(f"Exported {n} custom item{'s' if n != 1 else ''} to {filename}.", "green"), + ) + + +@callback( + Output("equipment-store", "data", allow_duplicate=True), + Output("eqm-selected-store", "data", allow_duplicate=True), + Output("eqm-draft-store", "data", allow_duplicate=True), + Output("eqm-edit-session", "data", allow_duplicate=True), + Output("eqm-action-msg", "children", allow_duplicate=True), + Output("eqm-import-upload", "contents"), # reset so the same file can be imported again + Input("eqm-import-upload", "contents"), + State("eqm-import-upload", "filename"), + State("equipment-store", "data"), + State("equipment-initial-store", "data"), + prevent_initial_call=True, +) +def import_equipment(contents, filename, equipment_data, initial_data): + if not contents: + return (no_update,) * 6 + try: + payload = json.loads(base64.b64decode(contents.split(",", 1)[1]).decode("utf-8")) + library_ids = [e["eq_id"] for e in (initial_data or {}).get("equipment", [])] + updated, report = import_custom_equipment(equipment_data, payload, library_ids) + except (ValueError, UnicodeDecodeError, IndexError) as err: + reason = "it is not a JSON file" if isinstance(err, json.JSONDecodeError) else str(err) + return (no_update,) * 4 + (_message(f"Could not import {filename}: {reason}", "red"), None) + + lines = [] + if report.added: + lines.append(f"Added: {', '.join(report.added)}") + if report.updated: + lines.append(f"Replaced the custom items with the same id: {', '.join(report.updated)}") + if report.renamed: + lines.append( + "Imported as custom copies (library equipment is never replaced): " + + ", ".join(f"{old} as {new}" for old, new in report.renamed.items()) + ) + if report.unchanged: + lines.append(f"Already present, unchanged: {', '.join(report.unchanged)}") + if report.rejected: + lines.append("Not imported: " + "; ".join(f"{k}: {v}" for k, v in report.rejected.items())) + if not lines: + lines.append("The file contains no custom equipment.") + color = ( + "red" + if report.rejected and not report.imported + else ("yellow" if report.rejected else "green") + ) + message = _message( + [ + dmc.Text(f"Imported {filename}", size="sm", fw=600), + dmc.List([dmc.ListItem(line) for line in lines], size="sm"), + ], + color, + ) + logger.info("Imported custom equipment from %s: %s", filename, report.model_dump()) + if not report.imported: + return no_update, no_update, no_update, no_update, message, None + # importing ends an edit in progress, its item may just have been replaced + return updated, report.imported[0], None, None, message, None diff --git a/pages/equipment_page.py b/pages/equipment_page.py index 4ab10a6..cc77c38 100644 --- a/pages/equipment_page.py +++ b/pages/equipment_page.py @@ -22,6 +22,8 @@ edit_equipment_modal, ) from src.config import LINKS, MAX_ACTIVE_EQUIPMENT_SCENARIOS, URLS +from src.equipment import Equipment, keep_custom_equipment +from src.visuals import empty_figure, plot_performance_curves from utils.logging_config import get_logger from utils.tooltips import with_icon_and_tooltip, with_tooltip @@ -697,12 +699,13 @@ def remove_scenario(remove_clicks, equipment_data, selected_equipment_ids, displ Output("selected-equipment-store", "data", allow_duplicate=True), Input("button-reset-equipment", "n_clicks"), State("equipment-initial-store", "data"), + State("equipment-store", "data"), prevent_initial_call=True, ) -def reset_equipment(n_clicks, initial_data): +def reset_equipment(n_clicks, initial_data, equipment_data): """ Reset the equipment configuration back to the initial library - and clear any active selections. + and clear any active selections. Custom equipment from the Equipment Manager is kept. """ if not n_clicks: return no_update, no_update @@ -710,7 +713,7 @@ def reset_equipment(n_clicks, initial_data): if not initial_data: return no_update, no_update - return initial_data, [] + return keep_custom_equipment(initial_data, equipment_data), [] @callback( @@ -721,6 +724,10 @@ def reset_equipment(n_clicks, initial_data): Output("edit-hr-wwhp-select", "value"), Output("edit-hr-wwhp-performance-model", "value"), Output("edit-hr-wwhp-h-supply-t-value", "value"), + Output("edit-hr-eac-rejection-cap", "value"), + Output("edit-hr-eac-recovery-cap", "value"), + Output("edit-hr-eac-rejection-control", "value"), + Output("edit-hr-eac-recovery-control", "value"), Output("edit-awhp-select", "data"), Output("edit-awhp-select", "value"), Output("edit-awhp-performance-model", "value"), @@ -747,7 +754,7 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): pre-filling all editable fields. """ if not any(edit_clicks or []): - return (no_update,) * 22 + return (no_update,) * 26 if not equipment_data: return ( @@ -758,6 +765,10 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): None, None, None, + None, + None, + "", + "", [], None, None, @@ -780,7 +791,7 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): triggered = callback_context.triggered if not triggered: - return (no_update,) * 22 + return (no_update,) * 26 prop_id = triggered[0]["prop_id"] id_str = prop_id.split(".")[0] @@ -796,6 +807,10 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): None, None, None, + None, + None, + "", + "", [], None, None, @@ -827,6 +842,10 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): None, None, None, + None, + None, + "", + "", [], None, None, @@ -867,17 +886,19 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): hr_wwhp_performance_model_val = scenario.get("hr_wwhp_performance_model") or "interpolate_HHWST" - # Get temperature values and convert to display units - from utils.units import C_to_F + # Get temperature/power values and convert to display units + from utils.units import get_converter unit_mode = unit_mode or "SI" + temp_converter = get_converter("temperature", unit_mode) + power_converter = get_converter("power", unit_mode) hr_wwhp_h_supply_t_val = scenario.get("hr_wwhp_h_supply_t") if hr_wwhp_h_supply_t_val is not None: try: hr_wwhp_h_supply_t_val = float(hr_wwhp_h_supply_t_val) if unit_mode == "IP": - hr_wwhp_h_supply_t_val = C_to_F(hr_wwhp_h_supply_t_val) + hr_wwhp_h_supply_t_val = temp_converter(hr_wwhp_h_supply_t_val) except (ValueError, TypeError): hr_wwhp_h_supply_t_val = None @@ -892,7 +913,7 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): try: awhp_h_supply_t_val = float(awhp_h_supply_t_val) if unit_mode == "IP": - awhp_h_supply_t_val = C_to_F(awhp_h_supply_t_val) + awhp_h_supply_t_val = temp_converter(awhp_h_supply_t_val) except (ValueError, TypeError): awhp_h_supply_t_val = None @@ -906,6 +927,26 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): backup_heating_val = scenario.get("backup_heating") chiller_val = scenario.get("chiller") + hr_eac_rejection_capacity_val = scenario.get("hr_eac_rejection_cap_W") + if hr_eac_rejection_capacity_val is not None: + try: + hr_eac_rejection_capacity_val = float(hr_eac_rejection_capacity_val) + # have to convert in both unit modes, because SI unit for power is kW not W + hr_eac_rejection_capacity_val = power_converter(hr_eac_rejection_capacity_val) + except (ValueError, TypeError): + hr_eac_rejection_capacity_val = None + + hr_eac_recovery_capacity_val = scenario.get("hr_eac_recovery_cap_W") + if hr_eac_recovery_capacity_val is not None: + try: + hr_eac_recovery_capacity_val = float(hr_eac_recovery_capacity_val) + hr_eac_recovery_capacity_val = power_converter(hr_eac_recovery_capacity_val) + except (ValueError, TypeError): + hr_eac_recovery_capacity_val = None + + hr_eac_rejection_control_val = scenario.get("hr_eac_rejection_control") or "min_turndown" + hr_eac_recovery_control_val = scenario.get("hr_eac_recovery_control") or "min_turndown" + return ( True, # modal open eq_scen_id, # id input @@ -914,6 +955,10 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): hr_wwhp_val, hr_wwhp_performance_model_val, hr_wwhp_h_supply_t_val, + hr_eac_rejection_capacity_val, + hr_eac_recovery_capacity_val, + hr_eac_rejection_control_val, + hr_eac_recovery_control_val, awhp_options, awhp_val, awhp_performance_model_val, @@ -942,6 +987,10 @@ def open_edit_modal(edit_clicks, equipment_data, unit_mode): State("edit-hr-wwhp-select", "value"), State("edit-hr-wwhp-performance-model", "value"), State("edit-hr-wwhp-h-supply-t-value", "value"), + State("edit-hr-eac-rejection-cap", "value"), + State("edit-hr-eac-recovery-cap", "value"), + State("edit-hr-eac-rejection-control", "value"), + State("edit-hr-eac-recovery-control", "value"), State("edit-awhp-select", "value"), State("edit-awhp-performance-model", "value"), State("edit-awhp-h-supply-t-value", "value"), @@ -964,6 +1013,10 @@ def save_edit_scenario( hr_wwhp_val, hr_wwhp_performance_model_val, hr_wwhp_h_supply_t_val, + hr_eac_rejection_cap_W_val, + hr_eac_recovery_cap_W_val, + hr_eac_rejection_control_val, + hr_eac_recovery_control_val, awhp_val, awhp_performance_model_val, awhp_h_supply_t_val, @@ -988,16 +1041,19 @@ def save_edit_scenario( if not new_name: return True, no_update, "Scenario name cannot be empty." - from utils.units import F_to_C + from utils.units import F_to_C, get_inverse_converter unit_mode = unit_mode or "SI" + # exact inverse of the power converter open_edit_modal displays with (kW or BTU/h -> W), + # so a saved value reopens unchanged (#227) + power_to_base = get_inverse_converter("power", unit_mode) if hr_wwhp_val == "None": hr_wwhp_val = None if awhp_val == "None": awhp_val = None - # Convert temperature values from display units back to Celsius (base unit) + # Convert temperature/power values from display units back to base unit if hr_wwhp_h_supply_t_val is not None: try: hr_wwhp_h_supply_t_val = float(hr_wwhp_h_supply_t_val) @@ -1024,6 +1080,18 @@ def save_edit_scenario( except (TypeError, ValueError): redundancy = 1 + if hr_eac_rejection_cap_W_val is not None: + try: + hr_eac_rejection_cap_W_val = power_to_base(float(hr_eac_rejection_cap_W_val)) + except (ValueError, TypeError): + hr_eac_rejection_cap_W_val = None + + if hr_eac_recovery_cap_W_val is not None: + try: + hr_eac_recovery_cap_W_val = power_to_base(float(hr_eac_recovery_cap_W_val)) + except (ValueError, TypeError): + hr_eac_recovery_cap_W_val = None + use_cooling = bool(use_cooling) fuel_switching = bool(fuel_switching) @@ -1038,6 +1106,10 @@ def save_edit_scenario( new_scen["hr_wwhp"] = hr_wwhp_val new_scen["hr_wwhp_performance_model"] = hr_wwhp_performance_model_val new_scen["hr_wwhp_h_supply_t"] = hr_wwhp_h_supply_t_val + new_scen["hr_eac_rejection_cap_W"] = hr_eac_rejection_cap_W_val + new_scen["hr_eac_recovery_cap_W"] = hr_eac_recovery_cap_W_val + new_scen["hr_eac_rejection_control"] = hr_eac_rejection_control_val or "min_turndown" + new_scen["hr_eac_recovery_control"] = hr_eac_recovery_control_val or "min_turndown" new_scen["awhp"] = awhp_val new_scen["awhp_performance_model"] = awhp_performance_model_val new_scen["awhp_h_supply_t"] = awhp_h_supply_t_val @@ -1203,6 +1275,25 @@ def update_temp_labels_on_unit_change(unit_mode): return hr_label, awhp_label +# Update HR source/sink labels when unit mode changes (without resetting values) +@callback( + Output("edit-hr-eac-rejection-cap-label", "children"), + Output("edit-hr-eac-recovery-cap-label", "children"), + Input("unit-toggle", "value"), +) +def update_hr_eac_label(unit_mode): + """Update HR WWHP source/sink capacity label based on unit mode.""" + from utils.units import get_display_unit + + unit_mode = unit_mode or "SI" + power_unit = get_display_unit("power", unit_mode) + + hr_rejection_label = f"Heat rejection capacity ({power_unit})" + hr_recovery_label = f"Heat recovery capacity ({power_unit})" + + return hr_rejection_label, hr_recovery_label + + @callback( Output("edit-hr-wwhp-performance-model", "disabled"), Output("edit-awhp-performance-model", "disabled"), @@ -1220,6 +1311,56 @@ def update_perf_model_on_hp_change(hr_hp_id, awhp_id): return (not hr_selected, not awhp_selected) +@callback( + Output("edit-hr-wwhp-curve-graph", "figure"), + Output("edit-awhp-curve-graph", "figure"), + Input("edit-hr-wwhp-select", "value"), + Input("edit-awhp-select", "value"), + Input("edit-hr-wwhp-h-supply-t-value", "value"), + Input("edit-awhp-h-supply-t-value", "value"), + Input("edit-hr-wwhp-performance-model", "value"), + Input("edit-awhp-performance-model", "value"), + Input("unit-toggle", "value"), + State("equipment-store", "data"), + prevent_initial_call=True, +) +def update_curve_previews( + hr_hp_id, + awhp_id, + hr_supply_t, + awhp_supply_t, + hr_perf_model, + awhp_perf_model, + unit_mode, + equipment_data, +): + """Plot the heating performance curves of the heat pumps selected in the edit modal.""" + from utils.units import F_to_C + + unit_mode = unit_mode or "SI" + equipment_list = (equipment_data or {}).get("equipment", []) + + def figure(eq_id, supply_t, fixed_supply_t): + eq = next((e for e in equipment_list if e.get("eq_id") == eq_id), None) + if not eq: + return empty_figure("No heat pump selected") + # only a fixed supply temperature can be shown as one curve (not a reset schedule) + highlight = None + if fixed_supply_t and supply_t is not None: + with contextlib.suppress(TypeError, ValueError): + highlight = float(supply_t) + if unit_mode == "IP": + highlight = F_to_C(highlight) + return plot_performance_curves( + Equipment(**eq), "heating", unit_mode, highlight_lwt_C=highlight, height=440 + ) + + return ( + figure(hr_hp_id, hr_supply_t, hr_perf_model == "interpolate_HHWST"), + figure(awhp_id, awhp_supply_t, awhp_perf_model == "interpolate_HHWST_fixed"), + ) + + @callback( Output("edit-awhp-sizing-priority", "disabled"), Input("edit-awhp-use-cooling", "checked"), @@ -1261,6 +1402,23 @@ def update_fuel_switching(awhp_id, backup_heating_id, fuel_switching, equipment_ return (disabled, checked) +@callback( + Output("edit-hr-eac-rejection-cap", "disabled"), + Output("edit-hr-eac-recovery-cap", "disabled"), + Output("edit-hr-eac-rejection-control", "disabled"), + Output("edit-hr-eac-recovery-control", "disabled"), + Input("edit-hr-wwhp-select", "value"), + prevent_initial_call=True, +) +def update_eac_inputs_on_wwhp_change(hr_hp_id): + """Enable/disable HR WWHP source/sink capacity inputs when HR selection changes.""" + + # Disable inputs if WWHP is not selected + hr_selected = hr_hp_id and hr_hp_id != "None" + + return (not hr_selected, not hr_selected, not hr_selected, not hr_selected) + + # helper to build equipment options for Selects @@ -1302,6 +1460,8 @@ def _build_equipment_options( label_cap = "Infinite cap." label += f" ({label_cap})" + if eq.get("source") == "custom": + label += " · custom" options.append( { diff --git a/pages/loads_page.py b/pages/loads_page.py index 7e0752f..afb6880 100644 --- a/pages/loads_page.py +++ b/pages/loads_page.py @@ -30,7 +30,7 @@ ) from src import paths from src.config import LINKS, URLS -from src.loads import STANDARD_COLUMNS, StandardLoad, get_load_data +from src.loads import STANDARD_COLUMNS, StandardLoad, apply_load_modifications, get_load_data from src.metadata import LoadData, Metadata from utils.error_handling import create_success_notification from utils.logging_config import get_logger @@ -477,6 +477,41 @@ def _build_summary_payload(load_obj: "StandardLoad") -> dict: return {"monthly_peaks": monthly_summary, "temp_bins": temp_summary} +def _original_load_path(load_data_path) -> Path: + """Path of the unmodified copy of a session load parquet.""" + path = Path(load_data_path) + return path.with_name(f"{path.stem}_original{path.suffix}") + + +def _read_original_load(load_data_path, scale_info=None, base_load_info=None) -> StandardLoad: + """Read the unmodified session load. + + Sessions started before the original copy existed fall back to the current file, + which is only safe while no scaling or base load has been applied to it. + """ + original_path = _original_load_path(load_data_path) + if not original_path.exists(): + if scale_info or base_load_info: + raise FileNotFoundError(f"Original load data not found: {original_path}") + StandardLoad.from_parquet(load_data_path).to_parquet(original_path) + return StandardLoad.from_parquet(original_path) + + +def _rebuild_session_load(load_data_path, scale_info, base_load_info) -> StandardLoad: + """Rebuild the session load from the original: scale first, then base load.""" + original = _read_original_load(load_data_path, scale_info, base_load_info) + scale_info = scale_info or {} + modified_df = apply_load_modifications( + original.df, + heating_factor=scale_info.get("heating_factor", 1.0), + cooling_factor=scale_info.get("cooling_factor", 1.0), + base_load=base_load_info, + ) + modified_load = StandardLoad(modified_df.reset_index()) + modified_load.to_parquet(load_data_path) + return modified_load + + @callback( [ Output("selected-building-store", "data"), @@ -610,8 +645,9 @@ def confirm_selection(n_clicks, current_choice, metadata_data, session_data): fname = f"load_data_building_{metadata.building_id}_{metadata.load_data.load_type}.parquet" path = folder / fname - # 4) save as parquet + # 4) save as parquet, plus an untouched copy that scaling/base load rebuild from load_obj.to_parquet(path) + load_obj.to_parquet(_original_load_path(path)) # 5) store path as string load_data_path = str(path) @@ -1115,7 +1151,7 @@ def update_table( if hhw_range and len(hhw_range) == 2: if unit_mode == "IP": - # kBTU/h → W (1 kBTU/h = 1e3 BTU/h = 1e3/3.412 W) + # kBTU/h → W (1 kBTU/h = 1e3 BTU/h = 1e3 * BTUh_to_W W) w_per_kbtu = 1e3 / W_to_BTUh hhw_range = [h * w_per_kbtu for h in hhw_range] else: @@ -1297,7 +1333,7 @@ def update_slider_units(unit_mode): area_max = int(sqm_to_sqft(area_max_si)) area_step = 5000 - # Convert HHW: W → kBTU/h (1 kBTU/h = 1e3 BTU/h = 1e3/3.412 W) + # Convert HHW: W → kBTU/h (1 kBTU/h = 1e3 BTU/h = 1e3 * BTUh_to_W W) # Using kBTU/h to avoid excessively large numbers kbtu_per_w = W_to_BTUh / 1e3 # W to kBTU/h hhw_min = round(hhw_min_si * kbtu_per_w, 1) @@ -1600,6 +1636,141 @@ def scale_power(w): # Scale loads feature # ------------------------------------------------------------------- +SCALE_METHOD_LABELS = { + "area": "building area", + "peak_heating": "peak heating load", + "peak_cooling": "peak cooling load", +} + + +def _scale_references(metadata, load_data_path, scale_info, base_load_info) -> dict: + """Original (unscaled) area and peak loads that scale factors are computed against.""" + stats = _read_original_load(load_data_path, scale_info, base_load_info).compute_load_stats() + return { + "area_sqm": scale_info["orig_area_sqm"] if scale_info else metadata.area_sqm, + "hhw_max_W": stats["hhw_max_load"], + "chw_max_W": stats["chw_max_load"], + } + + +def _compute_scale_info(method, target_value, unit_mode, refs, prev_scale_info) -> dict: + """Build the new scale-info-store payload for a scaling request. + + Area scales heating and cooling; a peak method only sets the factor of its own load + type and keeps the other factor from the previous scaling. Factors are always relative + to the original data, so applying the same target twice does not compound. + Raises ValueError if the scale factor cannot be computed. + """ + from utils.units import BTUh_to_W, sqft_to_sqm, ton_to_W + + prev = prev_scale_info or {} + scale_info = { + "method": SCALE_METHOD_LABELS[method], + "heating_factor": prev.get("heating_factor", 1.0), + "cooling_factor": prev.get("cooling_factor", 1.0), + "orig_area_sqm": refs["area_sqm"], + "target_area_sqm": prev.get("target_area_sqm"), + } + + if method == "area": + ref_si = refs["area_sqm"] + target_si = sqft_to_sqm(target_value) if unit_mode == "IP" else target_value + elif method == "peak_heating": + ref_si = refs["hhw_max_W"] + target_si = target_value * BTUh_to_W if unit_mode == "IP" else target_value * 1000 + else: # peak_cooling + ref_si = refs["chw_max_W"] + target_si = target_value * ton_to_W if unit_mode == "IP" else target_value * 1000 + + if not ref_si or ref_si <= 0: + raise ValueError(f"Reference value for '{method}' not available in library data.") + + scale_factor = target_si / ref_si + if scale_factor <= 0: + raise ValueError("Scale factor must be positive.") + + if method == "area": + scale_info["heating_factor"] = scale_factor + scale_info["cooling_factor"] = scale_factor + scale_info["target_area_sqm"] = target_si + elif method == "peak_heating": + scale_info["heating_factor"] = scale_factor + else: + scale_info["cooling_factor"] = scale_factor + + return scale_info + + +def _format_scale_value(kind, value, unit_mode): + """Format an area (m²) or peak load (W) for the scale comparison table.""" + from utils.units import W_to_BTUh, W_to_kW, W_to_tons, sqm_to_sqft + + if value is None: + return "—" + if kind == "area": + if unit_mode == "IP": + return f"{sqm_to_sqft(value):,.0f} ft²" + return f"{value:,.0f} m²" + if unit_mode == "IP": + if kind == "cooling": + return f"{W_to_tons(value):,.1f} TR" + return f"{value * W_to_BTUh:,.0f} BTU/h" + return f"{W_to_kW(value):,.1f} kW" + + +def _comparison_table(headers, rows): + """Two-column before/after table for the scale and base load modals. + + rows: (label, before_text, after_text, changed); changed cells are emphasised. + """ + + def _after_cell(text, changed): + # Only pass emphasis props when needed: dmc fails on c=None / fw=None + emphasis = {"fw": 600, "c": "blue"} if changed else {} + return dmc.TableTd(dmc.Text(text, size="sm", **emphasis)) + + return dmc.Table( + [ + dmc.TableThead(dmc.TableTr([dmc.TableTh("")] + [dmc.TableTh(h) for h in headers])), + dmc.TableTbody( + [ + dmc.TableTr( + [ + dmc.TableTd(label), + dmc.TableTd(before), + _after_cell(after, changed), + ] + ) + for label, before, after, changed in rows + ] + ), + ], + fz="sm", + withTableBorder=True, + ) + + +def _commit_load_modifications( + metadata_data, load_data_path, scale_info, base_load_info, orig_area_sqm=None +): + """Rebuild the session load and return (metadata dict, summary payload). + + orig_area_sqm: library area to fall back to when scale_info has no target area; + None leaves the area unchanged. + """ + metadata = Metadata(**metadata_data) + load = _rebuild_session_load(load_data_path, scale_info, base_load_info) + + if orig_area_sqm is not None: + metadata.area_sqm = (scale_info or {}).get("target_area_sqm") or orig_area_sqm + metadata.load_data = LoadData.model_validate( + {**metadata.load_data.model_dump(), **load.compute_load_stats()} + ) + # Without any modification the session file equals the library data again + metadata.session_load_path = load_data_path if (scale_info or base_load_info) else None + + return metadata.model_dump(), _build_summary_payload(load) + @callback( Output("open-scale-load-modal", "disabled"), @@ -1624,74 +1795,134 @@ def update_scale_btn_state(metadata_data, scale_info): ) +@callback( + Output("scale-reset-btn", "disabled"), + Input("scale-draft-store", "data"), +) +def update_scale_reset_btn(draft): + """Reset is only useful while the draft holds a scaling.""" + return not draft + + @callback( Output("scale-load-modal", "opened", allow_duplicate=True), - Output("scale-reference-info", "children"), + Output("scale-draft-store", "data", allow_duplicate=True), Input("open-scale-load-modal", "n_clicks"), Input("scale-cancel-btn", "n_clicks"), State("metadata-store", "data"), - State("unit-toggle", "value"), + State("scale-info-store", "data"), prevent_initial_call=True, ) -def toggle_scale_modal(open_clicks, cancel_clicks, metadata_data, unit_mode): - """Open or close the scale load modal.""" - from utils.units import W_to_BTUh, W_to_kW, W_to_tons, sqm_to_sqft - - if ctx.triggered_id == "scale-cancel-btn": +def toggle_scale_modal(open_clicks, cancel_clicks, metadata_data, scale_info): + """Open the scale modal with a draft of the committed scaling, or close it (Cancel).""" + if ctx.triggered_id == "scale-cancel-btn" or not metadata_data: return False, no_update + return True, scale_info - if not metadata_data: - return False, no_update + +@callback( + Output("scale-reference-info", "children"), + Input("scale-load-modal", "opened"), + Input("scale-draft-store", "data"), + Input("unit-toggle", "value"), + State("metadata-store", "data"), + State("load-data-path-store", "data"), + State("scale-info-store", "data"), + State("base-load-info-store", "data"), +) +def render_scale_comparison( + opened, draft, unit_mode, metadata_data, load_data_path, scale_info, base_load_info +): + """Show original library values next to the scaled values of the draft.""" + if not opened or not metadata_data or not load_data_path: + return no_update unit_mode = unit_mode or "SI" metadata = Metadata(**metadata_data) - ld = metadata.load_data - def _fmt(val, decimals=1): - return f"{val:,.{decimals}f}" if val is not None else "—" + try: + refs = _scale_references(metadata, load_data_path, scale_info, base_load_info) + except Exception as e: + logger.error(f"Could not read original load data: {e}") + return dmc.Text("Original load data not available.", c="red", size="sm") - if unit_mode == "IP": - area_val = sqm_to_sqft(metadata.area_sqm) if metadata.area_sqm else None - area_unit = "ft²" - hhw_val = ld.hhw_max_load * W_to_BTUh if ld.hhw_max_load is not None else None - hhw_unit = "BTU/h" - chw_val = W_to_tons(ld.chw_max_load) if ld.chw_max_load is not None else None - chw_unit = "TR" + originals = { + "area": refs["area_sqm"], + "heating": refs["hhw_max_W"], + "cooling": refs["chw_max_W"], + } + if draft: + target_area = draft.get("target_area_sqm") + # Unchanged values are carried over so both columns are always complete + scaled = { + "area": target_area if target_area is not None else refs["area_sqm"], + "heating": refs["hhw_max_W"] * draft["heating_factor"], + "cooling": refs["chw_max_W"] * draft["cooling_factor"], + } + changed = { + "area": target_area is not None, + "heating": draft["heating_factor"] != 1.0, + "cooling": draft["cooling_factor"] != 1.0, + } else: - area_val = metadata.area_sqm - area_unit = "m²" - hhw_val = W_to_kW(ld.hhw_max_load) if ld.hhw_max_load is not None else None - hhw_unit = "kW" - chw_val = W_to_kW(ld.chw_max_load) if ld.chw_max_load is not None else None - chw_unit = "kW" - - ref_info = dmc.Stack( - gap=4, - children=[ - dmc.Text("Library building reference values:", size="sm", fw=600), - dmc.Text(f"Area: {_fmt(area_val, 0)} {area_unit}", size="sm"), - dmc.Text(f"Peak heating: {_fmt(hhw_val)} {hhw_unit}", size="sm"), - dmc.Text(f"Peak cooling: {_fmt(chw_val)} {chw_unit}", size="sm"), - ], - ) + scaled = {"area": None, "heating": None, "cooling": None} + changed = {"area": False, "heating": False, "cooling": False} + + labels = {"area": "Area", "heating": "Peak heating", "cooling": "Peak cooling"} + rows = [ + ( + label, + _format_scale_value(kind, originals[kind], unit_mode), + _format_scale_value(kind, scaled[kind], unit_mode), + changed[kind], + ) + for kind, label in labels.items() + ] + return _comparison_table(["Library (original)", "Scaled"], rows) - return True, ref_info + +def _scale_summary(scale_info): + """Short description of a scaling for the modal status line.""" + if not scale_info: + return "No scaling applied" + return ( + f"Heating {scale_info['heating_factor']:.3f}x, cooling {scale_info['cooling_factor']:.3f}x" + ) @callback( - Output("scale-preview-text", "children"), Output("scale-target-label", "children"), - Output("scale-error-text", "children"), + Output("scale-preview-text", "children"), + Output("scale-preview-text", "c"), + Output("scale-confirm-btn", "disabled"), + Input("scale-load-modal", "opened"), Input("scale-method-select", "value"), Input("scale-target-value", "value"), + Input("scale-draft-store", "data"), + Input("unit-toggle", "value"), State("metadata-store", "data"), - State("unit-toggle", "value"), + State("load-data-path-store", "data"), + State("scale-info-store", "data"), + State("base-load-info-store", "data"), prevent_initial_call=True, ) -def update_scale_preview(method, target_value, metadata_data, unit_mode): - """Update the input label and live scale-factor preview.""" - from utils.units import BTUh_to_W, ton_to_W +def update_scale_status( + opened, + method, + target_value, + draft, + unit_mode, + metadata_data, + load_data_path, + scale_info, + base_load_info, +): + """Input label, status line, and Confirm state of the scale modal. + The status line is always filled (layout stays put): grey for the scaling in the table, + blue for an entered value that still needs Apply, red for invalid input. Confirm is + disabled while an entered value is not applied yet or when there is nothing to confirm. + """ unit_mode = unit_mode or "SI" labels = { @@ -1700,176 +1931,178 @@ def update_scale_preview(method, target_value, metadata_data, unit_mode): "peak_cooling": f"Your peak cooling load [{'TR' if unit_mode == 'IP' else 'kW'}]", } label = labels.get(method, "Enter value") + nothing_to_confirm = draft == scale_info - try: - target_value = float(target_value) - except (TypeError, ValueError): - return "", label, "" - - if not metadata_data or target_value <= 0: - return "", label, "" + def _status(): + summary = _scale_summary(draft) + if nothing_to_confirm: + return summary + return f"{summary} in the table — click Confirm to use it in the calculation" - metadata = Metadata(**metadata_data) - ld = metadata.load_data + if target_value in (None, ""): + return label, _status(), "dimmed", nothing_to_confirm try: - if method == "area": - ref_si = metadata.area_sqm - target_si = target_value / 10.7639 if unit_mode == "IP" else target_value - elif method == "peak_heating": - ref_si = ld.hhw_max_load - target_si = target_value * BTUh_to_W if unit_mode == "IP" else target_value * 1000 - else: # peak_cooling - ref_si = ld.chw_max_load - target_si = target_value * ton_to_W if unit_mode == "IP" else target_value * 1000 - - if not ref_si or ref_si <= 0: - return ( - "", - label, - f"Reference value for '{method}' not available in library data.", - ) + target_value = float(target_value) + if target_value <= 0: + raise ValueError("Value must be greater than 0.") + refs = _scale_references( + Metadata(**metadata_data), load_data_path, scale_info, base_load_info + ) + new_info = _compute_scale_info(method, target_value, unit_mode, refs, draft) + except Exception as e: + return label, str(e), "red", True - scale_factor = target_si / ref_si - if scale_factor <= 0: - return "", label, "Scale factor must be positive." + if new_info == draft: + # Entered value is already in the table + return label, _status(), "dimmed", nothing_to_confirm - return f"Scale factor: {scale_factor:.3f}x", label, "" + if method == "area": + preview = f"Scale factor: {new_info['heating_factor']:.3f}x (heating and cooling)" + elif method == "peak_heating": + preview = f"Heating scale factor: {new_info['heating_factor']:.3f}x (cooling unchanged)" + else: + preview = f"Cooling scale factor: {new_info['cooling_factor']:.3f}x (heating unchanged)" - except Exception as e: - return "", label, str(e) + return label, f"{preview} — click Apply to add it to the table", "blue", True @callback( - Output("metadata-store", "data", allow_duplicate=True), - Output("load-summary-store", "data", allow_duplicate=True), - Output("scale-load-modal", "opened", allow_duplicate=True), - Output("scale-info-store", "data"), - Output("notification-container", "sendNotifications", allow_duplicate=True), + Output("scale-draft-store", "data", allow_duplicate=True), Input("scale-apply-btn", "n_clicks"), State("scale-method-select", "value"), State("scale-target-value", "value"), State("metadata-store", "data"), State("load-data-path-store", "data"), State("unit-toggle", "value"), + State("scale-draft-store", "data"), + State("scale-info-store", "data"), + State("base-load-info-store", "data"), prevent_initial_call=True, ) -def apply_scale(n_clicks, method, target_value, metadata_data, load_data_path, unit_mode): - """Apply load scaling: multiply every hourly heating_W and cooling_W by scale_factor.""" - from utils.units import BTUh_to_W, W_to_BTUh, W_to_kW, W_to_tons, ton_to_W - - no_change = (no_update, no_update, no_update, no_update, no_update) +def apply_scale( + n_clicks, + method, + target_value, + metadata_data, + load_data_path, + unit_mode, + draft, + scale_info, + base_load_info, +): + """Add a scaling to the draft (table only); Confirm commits it to the load data. - if not n_clicks: + Area scales heating and cooling, a peak method only its own load, so heating and + cooling can be matched one after the other before confirming. + """ + if not n_clicks or not metadata_data or not load_data_path: raise dash.exceptions.PreventUpdate - unit_mode = unit_mode or "SI" - - if not metadata_data or not load_data_path: - return no_change - try: target_value = float(target_value) except (TypeError, ValueError): - return no_change + raise dash.exceptions.PreventUpdate from None if target_value <= 0: - return no_change - - metadata = Metadata(**metadata_data) - ld = metadata.load_data + raise dash.exceptions.PreventUpdate - # Compute scale factor try: - if method == "area": - ref_si = metadata.area_sqm - target_si = target_value / 10.7639 if unit_mode == "IP" else target_value - method_label = "building area" - elif method == "peak_heating": - ref_si = ld.hhw_max_load - target_si = target_value * BTUh_to_W if unit_mode == "IP" else target_value * 1000 - method_label = "peak heating load" - else: # peak_cooling - ref_si = ld.chw_max_load - target_si = target_value * ton_to_W if unit_mode == "IP" else target_value * 1000 - method_label = "peak cooling load" - - if not ref_si or ref_si <= 0: - return no_change - - scale_factor = target_si / ref_si - if scale_factor <= 0: - return no_change - + refs = _scale_references( + Metadata(**metadata_data), load_data_path, scale_info, base_load_info + ) + # Errors are already shown by update_scale_status + return _compute_scale_info(method, target_value, unit_mode or "SI", refs, draft) except Exception as e: - logger.error(f"Scale factor computation failed: {e}") - return no_change + logger.error(f"Error computing load scaling: {e}") + raise dash.exceptions.PreventUpdate from None - # Load, scale, and save parquet - try: - load_obj = StandardLoad.from_parquet(load_data_path) - orig_hhw_max = float(load_obj.df["heating_W"].max()) - orig_chw_max = float(load_obj.df["cooling_W"].max()) +@callback( + Output("scale-draft-store", "data", allow_duplicate=True), + Input("scale-reset-btn", "n_clicks"), + prevent_initial_call=True, +) +def reset_scale(n_clicks): + """Clear the draft scaling; Confirm restores the original library load.""" + if not n_clicks: + raise dash.exceptions.PreventUpdate + return None - scaled_df = load_obj.df.copy() - scaled_df["heating_W"] = scaled_df["heating_W"] * scale_factor - scaled_df["cooling_W"] = scaled_df["cooling_W"] * scale_factor - scaled_load = StandardLoad(scaled_df.reset_index()) - scaled_load.to_parquet(load_data_path) +@callback( + Output("metadata-store", "data", allow_duplicate=True), + Output("load-summary-store", "data", allow_duplicate=True), + Output("scale-load-modal", "opened", allow_duplicate=True), + Output("scale-info-store", "data", allow_duplicate=True), + Output("notification-container", "sendNotifications", allow_duplicate=True), + Input("scale-confirm-btn", "n_clicks"), + State("scale-draft-store", "data"), + State("metadata-store", "data"), + State("load-data-path-store", "data"), + State("scale-info-store", "data"), + State("base-load-info-store", "data"), + prevent_initial_call=True, +) +def confirm_scale(n_clicks, draft, metadata_data, load_data_path, scale_info, base_load_info): + """Commit the draft scaling to the session load data and close the modal.""" + if not n_clicks or not metadata_data or not load_data_path: + raise dash.exceptions.PreventUpdate + + if draft == scale_info: + return no_update, no_update, False, no_update, no_update + + orig_area_sqm = (scale_info or {}).get("orig_area_sqm") or Metadata(**metadata_data).area_sqm + try: + metadata_out, summary_payload = _commit_load_modifications( + metadata_data, load_data_path, draft, base_load_info, orig_area_sqm + ) except Exception as e: logger.error(f"Error scaling load data: {e}") - return no_change - - # Recompute stats and update metadata - new_stats = scaled_load.compute_load_stats() - if method == "area": - metadata.area_sqm = target_si - metadata.load_data = LoadData.model_validate({**ld.model_dump(), **new_stats}) - metadata.session_load_path = load_data_path + return no_update, no_update, no_update, no_update, no_update - # Rebuild summary payload for charts - summary_payload = _build_summary_payload(scaled_load) + if draft: + message = f"Heating {draft['heating_factor']:.3f}x, cooling {draft['cooling_factor']:.3f}x" + notification = create_success_notification( + "Load scaled", message, notification_id="scale-load-notification" + ) + logger.info(f"Applied load scaling ({message}) to {load_data_path}") + else: + notification = create_success_notification( + "Scaling reset", + "Load profile restored to the original library values", + notification_id="scale-load-notification", + ) + logger.info(f"Reset load scaling for {load_data_path}") - # Build confirmation alert - def _display_power(w_val): - if w_val is None: - return "—" - if unit_mode == "IP": - if method == "peak_cooling": - return f"{W_to_tons(w_val):.1f} TR" - return f"{w_val * W_to_BTUh:,.0f} BTU/h" - return f"{W_to_kW(w_val):.1f} kW" + return metadata_out, summary_payload, False, draft, [notification] - new_hhw = new_stats["hhw_max_load"] - new_chw = new_stats["chw_max_load"] - scale_info = { - "method": method_label, - "scale_factor": round(scale_factor, 6), - "orig_hhw_max_W": orig_hhw_max, - "orig_chw_max_W": orig_chw_max, - "new_hhw_max_W": new_hhw, - "new_chw_max_W": new_chw, - } +# ------------------------------------------------------------------- +# Base Load callbacks +# ------------------------------------------------------------------- - notification = create_success_notification( - "Load scaled", - f"Scale factor {scale_factor:.3f}x (based on {method_label})", - notification_id="scale-load-notification", - ) - logger.info( - f"Applied load scale factor {scale_factor:.4f} (method={method_label}) to {load_data_path}" - ) +def _compute_base_load_info(method, apply_to, value, unit_mode, prev_base_load_info) -> dict: + """Build the new base-load-info-store payload: one base load per load type. - return metadata.model_dump(), summary_payload, False, scale_info, [notification] + Applying to heating or cooling keeps the other load type's base load from before. + """ + from utils.units import BTUh_to_W + value_W = value * BTUh_to_W if unit_mode == "IP" else value * 1000 + entry = { + "method": "floor" if method == "floor" else "offset", + "value_W": value_W, + "value_display": f"{value:,.0f} BTU/h" if unit_mode == "IP" else f"{value:.1f} kW", + } -# ------------------------------------------------------------------- -# Base Load callbacks -# ------------------------------------------------------------------- + prev = prev_base_load_info or {} + info = {"heating": prev.get("heating"), "cooling": prev.get("cooling")} + for load_type in ("heating", "cooling"): + if apply_to in (load_type, "both"): + info[load_type] = entry + return info @callback( @@ -1895,71 +2128,121 @@ def update_base_load_btn_state(metadata_data, base_load_info): ) +@callback( + Output("base-load-reset-btn", "disabled"), + Input("base-load-draft-store", "data"), +) +def update_base_load_reset_btn(draft): + """Reset is only useful while the draft holds a base load.""" + return not draft + + @callback( Output("base-load-modal", "opened", allow_duplicate=True), - Output("base-load-current-values", "children"), + Output("base-load-draft-store", "data", allow_duplicate=True), Input("open-base-load-modal", "n_clicks"), Input("base-load-cancel-btn", "n_clicks"), State("metadata-store", "data"), - State("unit-toggle", "value"), + State("base-load-info-store", "data"), prevent_initial_call=True, ) -def toggle_base_load_modal(open_clicks, cancel_clicks, metadata_data, unit_mode): - """Open or close the base load modal, showing current peak values for reference.""" - from utils.units import W_to_BTUh, W_to_kW, W_to_tons - - if ctx.triggered_id == "base-load-cancel-btn": +def toggle_base_load_modal(open_clicks, cancel_clicks, metadata_data, base_load_info): + """Open the base load modal with a draft of the committed base load, or close it (Cancel).""" + if ctx.triggered_id == "base-load-cancel-btn" or not metadata_data: return False, no_update + return True, base_load_info - if not metadata_data: - return False, no_update + +@callback( + Output("base-load-current-values", "children"), + Input("base-load-modal", "opened"), + Input("base-load-draft-store", "data"), + Input("unit-toggle", "value"), + State("load-data-path-store", "data"), + State("scale-info-store", "data"), + State("base-load-info-store", "data"), +) +def render_base_load_comparison( + opened, draft, unit_mode, load_data_path, scale_info, base_load_info +): + """Show peak loads without and with the draft base load (scaling included in both).""" + if not opened or not load_data_path: + return no_update unit_mode = unit_mode or "SI" - metadata = Metadata(**metadata_data) - ld = metadata.load_data + factors = { + "heating_factor": (scale_info or {}).get("heating_factor", 1.0), + "cooling_factor": (scale_info or {}).get("cooling_factor", 1.0), + } - def _fmt(val, decimals=1): - return f"{val:,.{decimals}f}" if val is not None else "—" + try: + original_df = _read_original_load(load_data_path, scale_info, base_load_info).df + except Exception as e: + logger.error(f"Could not read original load data: {e}") + return dmc.Text("Original load data not available.", c="red", size="sm") + + without_df = apply_load_modifications(original_df, **factors) + with_df = apply_load_modifications(original_df, **factors, base_load=draft) if draft else None + + rows = [] + for load_type, col, label in ( + ("heating", "heating_W", "heating"), + ("cooling", "cooling_W", "cooling"), + ): + mod = (draft or {}).get(load_type) + if draft: + setting = f"{mod['method'].capitalize()} {mod['value_display']}" if mod else "None" + peak_after = _format_scale_value(load_type, float(with_df[col].max()), unit_mode) + else: + setting = peak_after = "—" + rows.append((f"{label.capitalize()} base load", "—", setting, bool(mod))) + rows.append( + ( + f"Peak {label}", + _format_scale_value(load_type, float(without_df[col].max()), unit_mode), + peak_after, + bool(mod), + ) + ) + + return _comparison_table(["Without base load", "With base load"], rows) - if unit_mode == "IP": - hhw_val = ld.hhw_max_load * W_to_BTUh if ld.hhw_max_load is not None else None - hhw_unit = "BTU/h" - chw_val = W_to_tons(ld.chw_max_load) if ld.chw_max_load is not None else None - chw_unit = "TR" - else: - hhw_val = W_to_kW(ld.hhw_max_load) if ld.hhw_max_load is not None else None - hhw_unit = "kW" - chw_val = W_to_kW(ld.chw_max_load) if ld.chw_max_load is not None else None - chw_unit = "kW" - - current_values = dmc.Stack( - gap=4, - children=[ - dmc.Text("Current peak loads:", size="sm", fw=600), - dmc.Text(f"Peak heating: {_fmt(hhw_val)} {hhw_unit}", size="sm"), - dmc.Text(f"Peak cooling: {_fmt(chw_val)} {chw_unit}", size="sm"), - ], - ) - return True, current_values +def _base_load_summary(base_load_info): + """Short description of the base loads for the modal status line.""" + if not base_load_info or not any(base_load_info.values()): + return "No base load applied" + parts = [ + f"{load_type.capitalize()} {mod['method']} of {mod['value_display']}" + if mod + else f"No {load_type} base load" + for load_type, mod in base_load_info.items() + ] + return ", ".join(parts) @callback( - Output("base-load-preview-text", "children"), Output("base-load-value-label", "children"), - Output("base-load-error-text", "children"), Output("base-load-method-desc", "children"), + Output("base-load-preview-text", "children"), + Output("base-load-preview-text", "c"), + Output("base-load-confirm-btn", "disabled"), + Input("base-load-modal", "opened"), Input("base-load-method-select", "value"), Input("base-load-apply-select", "value"), Input("base-load-value", "value"), - State("metadata-store", "data"), - State("unit-toggle", "value"), + Input("base-load-draft-store", "data"), + Input("unit-toggle", "value"), + State("base-load-info-store", "data"), prevent_initial_call=True, ) -def update_base_load_preview(method, apply_to, value, metadata_data, unit_mode): - """Update label, method description, and live preview text.""" - from utils.units import BTUh_to_W, W_to_BTUh, W_to_kW +def update_base_load_status(opened, method, apply_to, value, draft, unit_mode, base_load_info): + """Value label, method description, status line, and Confirm state of the base load modal. + Same rules as the scale modal: grey for the base load in the table, blue for an entered + value that still needs Apply, red for invalid input; Confirm is disabled while an entered + value is not applied yet or when there is nothing to confirm. + """ unit_mode = unit_mode or "SI" power_unit = "BTU/h" if unit_mode == "IP" else "kW" @@ -1981,156 +2264,131 @@ def update_base_load_preview(method, apply_to, value, metadata_data, unit_mode): "both": f"Base load [{power_unit}] (applied to heating and cooling)", } label = apply_labels.get(apply_to, f"Value [{power_unit}]") + nothing_to_confirm = draft == base_load_info + + def _status(): + summary = _base_load_summary(draft) + if nothing_to_confirm: + return summary + return f"{summary} in the table — click Confirm to use it in the calculation" + + if value in (None, ""): + return label, method_desc, _status(), "dimmed", nothing_to_confirm try: value = float(value) except (TypeError, ValueError): - return "", label, "", method_desc - - if not metadata_data or value <= 0: - return "", label, "", method_desc - - metadata = Metadata(**metadata_data) - ld = metadata.load_data - - # Convert input to Watts - value_W = value * BTUh_to_W if unit_mode == "IP" else value * 1000 + return label, method_desc, "Enter a number.", "red", True + if value <= 0: + return label, method_desc, "Base load must be greater than 0.", "red", True - def _peak_display(w_val): - if w_val is None: - return "—" - if unit_mode == "IP": - return f"{w_val * W_to_BTUh:,.0f} BTU/h" - return f"{W_to_kW(w_val):.1f} kW" - - lines = [] - applies_to_heating = apply_to in ("heating", "both") - applies_to_cooling = apply_to in ("cooling", "both") - - if method == "floor": - if applies_to_heating and ld.hhw_max_load is not None: - if value_W > ld.hhw_max_load: - lines.append( - f"Heating: floor ({_peak_display(value_W)}) exceeds current peak — all hours will be set to floor" - ) - else: - lines.append(f"Heating peak unchanged at {_peak_display(ld.hhw_max_load)}") - if applies_to_cooling and ld.chw_max_load is not None: - if value_W > ld.chw_max_load: - lines.append( - f"Cooling: floor ({_peak_display(value_W)}) exceeds current peak — all hours will be set to floor" - ) - else: - lines.append(f"Cooling peak unchanged at {_peak_display(ld.chw_max_load)}") - else: # offset - if applies_to_heating and ld.hhw_max_load is not None: - new_hhw = ld.hhw_max_load + value_W - lines.append(f"New peak heating: {_peak_display(new_hhw)} (+{_peak_display(value_W)})") - if applies_to_cooling and ld.chw_max_load is not None: - new_chw = ld.chw_max_load + value_W - lines.append(f"New peak cooling: {_peak_display(new_chw)} (+{_peak_display(value_W)})") + new_info = _compute_base_load_info(method, apply_to, value, unit_mode, draft) + if new_info == draft: + # Entered value is already in the table + return label, method_desc, _status(), "dimmed", nothing_to_confirm - preview = " · ".join(lines) if lines else "" - return preview, label, "", method_desc + target = {"heating": "heating", "cooling": "cooling", "both": "heating and cooling"}[apply_to] + entry = new_info["cooling" if apply_to == "cooling" else "heating"] + preview = f"{entry['method'].capitalize()} of {entry['value_display']} for {target}" + return ( + label, + method_desc, + f"{preview} — click Apply to add it to the table", + "blue", + True, + ) @callback( - Output("metadata-store", "data", allow_duplicate=True), - Output("load-summary-store", "data", allow_duplicate=True), - Output("base-load-modal", "opened", allow_duplicate=True), - Output("base-load-info-store", "data"), - Output("notification-container", "sendNotifications", allow_duplicate=True), + Output("base-load-draft-store", "data", allow_duplicate=True), Input("base-load-apply-btn", "n_clicks"), State("base-load-method-select", "value"), State("base-load-apply-select", "value"), State("base-load-value", "value"), - State("metadata-store", "data"), - State("load-data-path-store", "data"), State("unit-toggle", "value"), + State("base-load-draft-store", "data"), prevent_initial_call=True, ) -def apply_base_load(n_clicks, method, apply_to, value, metadata_data, load_data_path, unit_mode): - """Apply base load modification: floor or offset on heating and/or cooling loads.""" - from utils.units import BTUh_to_W - - no_change = (no_update, no_update, no_update, no_update, no_update) +def apply_base_load(n_clicks, method, apply_to, value, unit_mode, draft): + """Add a floor or offset for heating and/or cooling to the draft (table only). + Confirm commits it; the load is then rebuilt from the original data with the current + scaling applied first. + """ if not n_clicks: raise dash.exceptions.PreventUpdate - unit_mode = unit_mode or "SI" - - if not metadata_data or not load_data_path: - return no_change - try: value = float(value) except (TypeError, ValueError): - return no_change + raise dash.exceptions.PreventUpdate from None if value <= 0: - return no_change + raise dash.exceptions.PreventUpdate - # Convert to Watts - value_W = value * BTUh_to_W if unit_mode == "IP" else value * 1000 + return _compute_base_load_info(method, apply_to, value, unit_mode or "SI", draft) - applies_to_heating = apply_to in ("heating", "both") - applies_to_cooling = apply_to in ("cooling", "both") - try: - load_obj = StandardLoad.from_parquet(load_data_path) - modified_df = load_obj.df.copy() - - if method == "floor": - if applies_to_heating: - modified_df["heating_W"] = modified_df["heating_W"].clip(lower=value_W) - if applies_to_cooling: - modified_df["cooling_W"] = modified_df["cooling_W"].clip(lower=value_W) - else: # offset - if applies_to_heating: - modified_df["heating_W"] = modified_df["heating_W"] + value_W - if applies_to_cooling: - modified_df["cooling_W"] = modified_df["cooling_W"] + value_W - - modified_load = StandardLoad(modified_df.reset_index()) - modified_load.to_parquet(load_data_path) +@callback( + Output("base-load-draft-store", "data", allow_duplicate=True), + Input("base-load-reset-btn", "n_clicks"), + prevent_initial_call=True, +) +def reset_base_load(n_clicks): + """Clear the draft base load; Confirm removes it from the load data.""" + if not n_clicks: + raise dash.exceptions.PreventUpdate + return None - except Exception as e: - logger.error(f"Error applying base load modification: {e}") - return no_change - # Recompute stats and update metadata - metadata = Metadata(**metadata_data) - ld = metadata.load_data - new_stats = modified_load.compute_load_stats() - metadata.load_data = LoadData.model_validate({**ld.model_dump(), **new_stats}) - metadata.session_load_path = load_data_path - - summary_payload = _build_summary_payload(modified_load) - - apply_to_label = { - "heating": "heating", - "cooling": "cooling", - "both": "heating + cooling", - }[apply_to] - method_label = "floor" if method == "floor" else "offset" - value_display = f"{value:,.0f} BTU/h" if unit_mode == "IP" else f"{value:.1f} kW" - - base_load_info = { - "method": method_label, - "apply_to": apply_to, - "value_W": value_W, - "value_display": value_display, - } +@callback( + Output("metadata-store", "data", allow_duplicate=True), + Output("load-summary-store", "data", allow_duplicate=True), + Output("base-load-modal", "opened", allow_duplicate=True), + Output("base-load-info-store", "data", allow_duplicate=True), + Output("notification-container", "sendNotifications", allow_duplicate=True), + Input("base-load-confirm-btn", "n_clicks"), + State("base-load-draft-store", "data"), + State("metadata-store", "data"), + State("load-data-path-store", "data"), + State("scale-info-store", "data"), + State("base-load-info-store", "data"), + prevent_initial_call=True, +) +def confirm_base_load(n_clicks, draft, metadata_data, load_data_path, scale_info, base_load_info): + """Commit the draft base load to the session load data and close the modal.""" + if not n_clicks or not metadata_data or not load_data_path: + raise dash.exceptions.PreventUpdate - notification = create_success_notification( - "Base load applied", - f"{method_label.capitalize()} of {value_display} applied to {apply_to_label}", - notification_id="base-load-notification", - ) + if draft == base_load_info: + return no_update, no_update, False, no_update, no_update - logger.info( - f"Applied base load {method_label} of {value_W:.1f} W to {apply_to} loads in {load_data_path}" - ) + try: + metadata_out, summary_payload = _commit_load_modifications( + metadata_data, load_data_path, scale_info, draft + ) + except Exception as e: + logger.error(f"Error applying base load modification: {e}") + return no_update, no_update, no_update, no_update, no_update + + if draft: + parts = [ + f"{load_type}: {mod['method']} of {mod['value_display']}" + for load_type, mod in draft.items() + if mod + ] + message = ", ".join(parts) + message = message[0].upper() + message[1:] + notification = create_success_notification( + "Base load applied", message, notification_id="base-load-notification" + ) + logger.info(f"Applied base load ({message}) to {load_data_path}") + else: + notification = create_success_notification( + "Base load removed", + "Load profile restored to the values without base load", + notification_id="base-load-notification", + ) + logger.info(f"Removed base load for {load_data_path}") - return metadata.model_dump(), summary_payload, False, base_load_info, [notification] + return metadata_out, summary_payload, False, draft, [notification] diff --git a/pages/results_page.py b/pages/results_page.py index ba3b567..d5d4368 100644 --- a/pages/results_page.py +++ b/pages/results_page.py @@ -1,5 +1,4 @@ import contextlib -import datetime import io import time import zipfile @@ -321,7 +320,7 @@ def show_download_notification(n_clicks, unit_mode): return [notification] -# Download the full results/source energy dataframe as CSV +# Download the results as a zip: hourly CSV, annual summary CSV and the settings @callback( Output("download-data", "data"), Input("download-button", "n_clicks"), @@ -331,6 +330,9 @@ def show_download_notification(n_clicks, unit_mode): State("equipment-store", "data"), State("selected-equipment-store", "data"), State("selected-emissions-store", "data"), + State("displayed-equipment-store", "data"), + State("scale-info-store", "data"), + State("base-load-info-store", "data"), prevent_initial_call=True, ) def download_results( @@ -341,15 +343,16 @@ def download_results( equipment_json, selected_eq_ids, selected_em_ids, + displayed_eq_ids=None, + scale_info=None, + base_load_info=None, ): - """Download the entire results dataframe as a .csv file with unit conversion.""" - import numpy as np - - from utils.units import ( - COLUMN_DISPLAY_NAMES, - convert_dataframe, - get_category, - get_column_label, + """Download the results as a zip named after the case, in the selected unit system.""" + from src.export import ( + build_annual_summary, + build_export_basename, + build_hourly_export, + format_for_csv, ) # Only trigger on actual button click @@ -360,64 +363,51 @@ def download_results( raise dash.exceptions.PreventUpdate df = load_source_energy(session_data) - if df is None: + if df is None or not metadata_json: raise dash.exceptions.PreventUpdate unit_mode = unit_mode or "SI" + metadata = Metadata(**metadata_json) - # Convert values based on unit mode - df = convert_dataframe(df, unit_mode) - - def round_like_python(values, decimals): - """Vectorised round() with the same result as Python's built-in round(). - - Series.round() can differ from round() on values that look like exact - halves in decimal (e.g. 6.825); those few values are rounded one by one. - """ - rounded = values.round(decimals) - scaled = values * 10**decimals - near_half = ((scaled - np.trunc(scaled)).abs() - 0.5).abs() < 1e-6 - if near_half.any(): - rounded[near_half] = values[near_half].map(lambda v: round(v, decimals)) - return rounded - - # Round numeric values: 2 decimals normally, 3 for values < 1 - for col in df.columns: - if df[col].dtype in [np.float64, np.float32, float]: - values = df[col] - small = (values.abs() < 1) & (values != 0) - df[col] = round_like_python(values, 2).where(~small, round_like_python(values, 3)) - - # Rename columns: - # - Columns with a category: use get_column_label (includes unit) - # - Columns without a category but with display name: use display name only - column_renames = {} - for col in df.columns: - if get_category(col) is not None: - # Has unit conversion - include unit in label - column_renames[col] = get_column_label(col, unit_mode) - elif col in COLUMN_DISPLAY_NAMES: - # No unit conversion but has display name - column_renames[col] = COLUMN_DISPLAY_NAMES[col] - # else: keep original column name - df = df.rename(columns=column_renames) - - timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") - csv_string = df.to_csv(index=True) + hourly = build_hourly_export(df, metadata, _equipment_position_map(displayed_eq_ids)) + annual = build_annual_summary(hourly) + base = build_export_basename(metadata, unit_mode, scale_info, base_load_info) buf = io.BytesIO() with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: - zf.writestr(f"results_{timestamp}.csv", csv_string) + zf.writestr( + f"{base}/{base}_hourly.csv", + format_for_csv(hourly, unit_mode).to_csv(index_label="Timestamp"), + ) + zf.writestr( + f"{base}/{base}_annual.csv", format_for_csv(annual, unit_mode).to_csv(index=False) + ) _add_metadata_files( - zf, metadata_json, equipment_json, selected_eq_ids, selected_em_ids, unit_mode + zf, + f"{base}/", + metadata_json, + equipment_json, + selected_eq_ids, + selected_em_ids, + unit_mode, + scale_info, + base_load_info, ) buf.seek(0) - return dcc.send_bytes(buf.getvalue(), f"results_{timestamp}.zip") + return dcc.send_bytes(buf.getvalue(), f"{base}.zip") def _add_metadata_files( - zf, metadata_json, equipment_json, selected_eq_ids, selected_em_ids, unit_mode + zf, + prefix, + metadata_json, + equipment_json, + selected_eq_ids, + selected_em_ids, + unit_mode, + scale_info=None, + base_load_info=None, ): import json as _json @@ -435,12 +425,18 @@ def _add_metadata_files( selected_em = list(selected_em_ids) if selected_em_ids else [] summary = build_metadata_summary( - metadata, equipment_library, selected_eq, selected_em, unit_mode + metadata, + equipment_library, + selected_eq, + selected_em, + unit_mode, + scale_info=scale_info, + base_load_info=base_load_info, ) - zf.writestr("settings_summary.txt", summary) + zf.writestr(f"{prefix}settings_summary.txt", summary) bundle = build_settings_bundle(metadata, equipment_library, selected_eq, selected_em) - zf.writestr("settings.json", _json.dumps(bundle, indent=2, default=str)) + zf.writestr(f"{prefix}settings.json", _json.dumps(bundle, indent=2, default=str)) except Exception: # Never block the CSV download for a metadata-export failure, but do # log it - a silent `pass` here is what let a stale-field regression diff --git a/pyproject.toml b/pyproject.toml index 214e3c2..0f6bc7c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "decarb-tool" -version = "0.1.0" +version = "0.2.0" description = "Building decarbonization planning tool" requires-python = ">=3.12" diff --git a/src/config.py b/src/config.py index c7b659d..5aafb2e 100644 --- a/src/config.py +++ b/src/config.py @@ -6,6 +6,7 @@ class URLS(Enum): EQUIPMENT: str = "/equipment" EMISSIONS: str = "/emissions" RESULTS: str = "/results" + EQUIPMENT_MANAGER: str = "/equipment-manager" class LINKS(Enum): @@ -129,6 +130,8 @@ class Columns(StrEnum): MAX_CAP_H_HR_W = "max_cap_h_hr_W" MIN_CAP_H_HR_W = "min_cap_h_hr_W" SIMULT_H_HR_W = "simult_h_hr_W" + HR_EAC_H_W = "hr_eac_h_W" + HR_EAC_C_W = "hr_eac_c_W" ELEC_HR_WH = "elec_hr_Wh" # --- Air-Water Heat Pump (Heating) --- diff --git a/src/energy.py b/src/energy.py index cd85c28..dae8b4f 100644 --- a/src/energy.py +++ b/src/energy.py @@ -3,7 +3,7 @@ from src.config import Columns as Col from src.emissions import get_emissions_data -from src.equipment import Equipment, EquipmentLibrary, PerformanceCurves +from src.equipment import Equipment, EquipmentLibrary, PerformanceCurves, validate_equipment from src.loads import StandardLoad from src.metadata import Metadata from utils.interp import interp_vector, multi_interp_vector @@ -13,6 +13,13 @@ logger = get_logger(__name__) +def _raise_on_equipment_errors(e: Equipment, modes: tuple[str, ...]): + """Raise a ValueError with the first validation error of `e` for the given modes, if any.""" + errors = [i for i in validate_equipment(e, modes) if i.severity == "error"] + if errors: + raise ValueError(errors[0].message) + + def _equipment_data_validation(library: EquipmentLibrary, scenario_ids: list[str]): """Ensure all equipment in the selected scenarios have complete data for the calculations.""" @@ -22,9 +29,7 @@ def _equipment_data_validation(library: EquipmentLibrary, scenario_ids: list[str # wwhp checks if scen.hr_wwhp: hr_wwhp = library.get_equipment(scen.hr_wwhp) - - if not hr_wwhp.performance_heating: - raise ValueError(f"Equipment '{hr_wwhp.eq_id}' lacks heating performance data.") + _raise_on_equipment_errors(hr_wwhp, ("heating",)) hr_wwhp_supply_t = scen.hr_wwhp_h_supply_t if ( @@ -35,26 +40,6 @@ def _equipment_data_validation(library: EquipmentLibrary, scenario_ids: list[str f"Supply water temperature {hr_wwhp_supply_t} is outside the bounds of the provided performance data for equipment '{hr_wwhp.eq_id}'." ) - if not hr_wwhp.performance_heating.capacity_W: - raise ValueError( - f"Equipment '{hr_wwhp.eq_id}' lacks heating capacity info (capacity_W curve)." - ) - - hr_wwhp_supply_temps_str = list(hr_wwhp.performance_heating.leaving_supply_t.keys()) - - for t in hr_wwhp_supply_temps_str: - if not hr_wwhp.performance_heating.leaving_supply_t[t].cop: - raise ValueError( - f"Equipment '{hr_wwhp.eq_id}' lacks heating capacity info (COP curve for supply temperature {t})." - ) - - if len(hr_wwhp.performance_heating.capacity_W) != len( - hr_wwhp.performance_heating.leaving_supply_t[t].cop - ): - raise ValueError( - f"Equipment '{hr_wwhp.eq_id}' heating COP and capacity curves are of different lengths for supply temperature {t}." - ) - if scen.hr_wwhp_performance_model not in [ "fixed_COP", "interpolate_HHWST", @@ -64,12 +49,33 @@ def _equipment_data_validation(library: EquipmentLibrary, scenario_ids: list[str f"HR WWHP scenario '{scen.eq_scen_id}' has unrecognized performance calculation model: '{scen.hr_wwhp_performance_model}'." ) + if scen.hr_eac_rejection_control not in [ + "max_heat_rejection", + "min_turndown", + ]: + raise ValueError( + f"HR WWHP scenario '{scen.eq_scen_id}' has unrecognized balancing heat rejection control model: '{scen.hr_eac_rejection_controlhr_eac_rejection_control}'." + ) + if scen.hr_eac_recovery_control not in [ + "max_heat_recovery", + "min_turndown", + ]: + raise ValueError( + f"HR WWHP scenario '{scen.eq_scen_id}' has unrecognized balancing heat recovery control model: '{scen.hr_eac_recovery_control}'." + ) + if scen.hr_eac_rejection_cap_W < 0 or scen.hr_eac_recovery_cap_W < 0: + raise ValueError( + f"HR WWHP scenario '{scen.eq_scen_id}' requires " + f"balancing heat recovery and rejection capacity to be non-negative." + ) + if scen.awhp: # awhp heating checks awhp_h = library.get_equipment(scen.awhp) - - if not awhp_h.performance_heating: - raise ValueError(f"Equipment '{awhp_h.eq_id}' lacks heating performance data.") + # cooling curves are only checked when the scenario uses the AWHP for cooling + _raise_on_equipment_errors( + awhp_h, ("heating", "cooling") if scen.awhp_use_cooling else ("heating",) + ) awhp_h_supply_t = scen.awhp_h_supply_t if ( @@ -80,50 +86,6 @@ def _equipment_data_validation(library: EquipmentLibrary, scenario_ids: list[str f"Supply water temperature {awhp_h_supply_t} is outside the bounds of the provided performance data for equipment '{awhp_h.eq_id}'." ) - if not awhp_h.performance_heating.t_out_C: - raise ValueError( - f"Equipment '{awhp_h.eq_id}' lacks heating capacity info (t_out curve)." - ) - - awhp_h_supply_temps_str = list(awhp_h.performance_heating.leaving_supply_t.keys()) - - for t in awhp_h_supply_temps_str: - if not awhp_h.performance_heating.leaving_supply_t[t].capacity_W: - if not awhp_h.capacity_W: - raise ValueError( - f"Equipment '{awhp_h.eq_id}' lacks heating capacity info (fixed value or t_out-based curve for capacity_W at supply temperature {t})." - ) - - else: - if len(awhp_h.performance_heating.t_out_C) != len( - awhp_h.performance_heating.leaving_supply_t[t].capacity_W - ): - raise ValueError( - f"Equipment '{awhp_h.eq_id}' heating capacity_W and t_out curves are of different lengths for supply temperature {t}." - ) - - if not awhp_h.performance_heating.leaving_supply_t[t].cop: - raise ValueError( - f"Equipment '{awhp_h.eq_id}' lacks heating capacity info (COP curve for supply temperature {t})." - ) - - if len(awhp_h.performance_heating.t_out_C) != len( - awhp_h.performance_heating.leaving_supply_t[t].cop - ): - raise ValueError( - f"Equipment '{awhp_h.eq_id}' heating COP and t_out curves are of different lengths for supply temperature {t}." - ) - - if "min_temp_C" not in awhp_h.performance_heating.leaving_supply_t[t].constraints: - raise ValueError( - f"Equipment '{awhp_h.eq_id}' lacks heating capacity info (minimum t_out constraint for supply temperature {t})." - ) - - if "max_temp_C" not in awhp_h.performance_heating.leaving_supply_t[t].constraints: - raise ValueError( - f"Equipment '{awhp_h.eq_id}' lacks heating capacity info (maximum t_out constraint for supply temperature {t})." - ) - if scen.awhp_sizing_mode is None: raise ValueError(f"AWHP scenario '{scen.eq_scen_id}' requires 'awhp_sizing_mode'.") @@ -171,83 +133,16 @@ def _equipment_data_validation(library: EquipmentLibrary, scenario_ids: list[str f"AWHP scenario '{scen.eq_scen_id}' has unrecognized performance calculation model: '{scen.awhp_performance_model}'." ) - # awhp cooling checks - if scen.awhp_use_cooling: - awhp_c = library.get_equipment(scen.awhp) - - if scen.awhp_sizing_priority is None: - raise ValueError( - f"AWHP scenario '{scen.eq_scen_id}' requires 'awhp_sizing_priority'." - ) - - if not awhp_c.performance_cooling: - raise ValueError(f"Equipment '{awhp_c.eq_id}' lacks cooling performance data.") - - if not awhp_c.performance_cooling.t_out_C: - raise ValueError( - f"Equipment '{awhp_c.eq_id}' lacks cooling capacity info (t_out curve)." - ) - - awhp_c_supply_temps_str = list(awhp_c.performance_cooling.leaving_supply_t.keys()) - - for t in awhp_c_supply_temps_str: - if not awhp_c.performance_cooling.leaving_supply_t[t].capacity_W: - if not awhp_c.capacity_W: - raise ValueError( - f"Equipment '{awhp_c.eq_id}' lacks cooling capacity info (fixed value or t_out-based curve for capacity_W at supply temperature {t})." - ) - - else: - if len(awhp_c.performance_cooling.t_out_C) != len( - awhp_c.performance_cooling.leaving_supply_t[t].capacity_W - ): - raise ValueError( - f"Equipment '{awhp_c.eq_id}' cooling capacity_W and t_out curves are of different lengths for supply temperature {t}." - ) - - if not awhp_c.performance_cooling.leaving_supply_t[t].cop: - raise ValueError( - f"Equipment '{awhp_c.eq_id}' lacks cooling capacity info (COP curve for supply temperature {t})." - ) - - if len(awhp_c.performance_cooling.t_out_C) != len( - awhp_c.performance_cooling.leaving_supply_t[t].cop - ): - raise ValueError( - f"Equipment '{awhp_c.eq_id}' cooling COP and t_out curves are of different lengths for supply temperature {t}." - ) - - if ( - "min_temp_C" - not in awhp_c.performance_cooling.leaving_supply_t[t].constraints - ): - raise ValueError( - f"Equipment '{awhp_c.eq_id}' lacks cooling capacity info (minimum t_out constraint for supply temperature {t})." - ) - - if ( - "max_temp_C" - not in awhp_c.performance_cooling.leaving_supply_t[t].constraints - ): - raise ValueError( - f"Equipment '{awhp_c.eq_id}' lacks cooling capacity info (maximum t_out constraint for supply temperature {t})." - ) + # awhp cooling checks (equipment data already checked above) + if scen.awhp_use_cooling and scen.awhp_sizing_priority is None: + raise ValueError( + f"AWHP scenario '{scen.eq_scen_id}' requires 'awhp_sizing_priority'." + ) # boiler checks backup_heating = library.get_equipment(scen.backup_heating) if backup_heating.fuel == "natural_gas": - if not backup_heating.performance_heating: - raise ValueError( - f"Equipment '{backup_heating.eq_id}' lacks heating performance data (efficiency)." - ) - - if ( - backup_heating.performance_heating.efficiency is None - or backup_heating.performance_heating.efficiency <= 0 - ): - raise ValueError( - f"Equipment '{backup_heating.eq_id}' requires a positive 'efficiency'." - ) + _raise_on_equipment_errors(backup_heating, ("heating",)) def _heat_recovery_plr_curve(e: Equipment, performance: PerformanceCurves) -> pd.DataFrame: @@ -274,7 +169,7 @@ def _heating_supply_temp_performance( t_out_lim = [np.nan, 20] # set low limit to the minimum operating OAT at the lowest supply temperature t_out_lim[0] = e.performance_heating.leaving_supply_t[ - min(equip_supply_temps_str) + min(equip_supply_temps_str, key=float) ].constraints["min_temp_C"] logger.debug( f"AWHP heating water supply temperature reset: " @@ -527,6 +422,8 @@ def loads_to_site_energy( Col.HR_HHW_W.value, Col.HR_CHW_W.value, Col.HR_COP_H.value, + Col.HR_EAC_H_W.value, + Col.HR_EAC_C_W.value, Col.ELEC_HR_WH.value, # AWHP Heating Col.AWHP_HHW_W.value, @@ -605,29 +502,94 @@ def loads_to_site_energy( min_cap_h = plr_curve["cap"].min() # min heating capacity allowed by unit # Simultaneous load potential (using least-waste-heat factor) - simult_h = np.minimum( + heating_dominant = ( + df[Col.HHW_REM_W.value].to_numpy() * least_waste_heat["cap_h_to_cap_c"] + >= df[Col.CHW_REM_W.value].to_numpy() + ) # heating dominant if heat rejectable from HHW is greater than CHW + + # simult_base: no exhaust air coil - smaller of HHW and heat recoverable from CHW + simult_base = np.minimum( df[Col.HHW_REM_W.value].to_numpy(), - df[Col.CHW_REM_W.value].to_numpy() - / least_waste_heat[ - "cap_h_to_cap_c" - ], # amount of simultaneous load that the WWHP can actually satisfy + df[Col.CHW_REM_W.value].to_numpy() / least_waste_heat["cap_h_to_cap_c"], + ) + + # Simult_max: exhaust air coil used up to its full capacity + simult_max = np.where( + heating_dominant, + # if heating dominant, simult load = smaller of HHW vs heat recoverable from CHW + EAHR capacity + np.minimum( + df[Col.HHW_REM_W.value].to_numpy(), + (df[Col.CHW_REM_W.value].to_numpy() + scen.hr_eac_recovery_cap_W) + / least_waste_heat["cap_h_to_cap_c"], + ), + # if cooling dominant, simult load = smaller of HHW + EAHR capacity vs heat recoverable from CHW + np.minimum( + df[Col.CHW_REM_W.value].to_numpy() / least_waste_heat["cap_h_to_cap_c"], + df[Col.HHW_REM_W.value].to_numpy() + scen.hr_eac_rejection_cap_W, + ), ) - # Actual heating served (within capacity limits) - hr_hhw = np.where( - np.minimum(max_cap_h, simult_h) > min_cap_h, + # simult_min: exhaust air coil used only to reach the HR WWHP min turndown + simult_min = np.where( + simult_base >= min_cap_h, + simult_base, + np.minimum(simult_max, min_cap_h), + ) + + simult_h = np.where( + heating_dominant, + # Heating dominant hours follow the heat recovery control + simult_max if scen.hr_eac_recovery_control == "max_heat_recovery" else simult_min, + # Cooling dominant hours follow the heat rejection control + simult_max if scen.hr_eac_rejection_control == "max_heat_rejection" else simult_min, + ) + + # Actual HR WWHP heating output (within capacity limits) + hr_out_h = np.where( + np.minimum(max_cap_h, simult_h) >= min_cap_h, np.minimum(max_cap_h, simult_h), 0.0, ) # Interpolate COP at part load - hr_cop_h = interp_vector(plr_curve["cap"], plr_curve["cop"], hr_hhw) + hr_cop_h = interp_vector(plr_curve["cap"], plr_curve["cop"], hr_out_h) # Cooling served derived from heating & COP - hr_chw = np.where(hr_cop_h > 0, hr_hhw * (1 - (1 / hr_cop_h)), 0.0) # same as R + hr_out_c = np.where(hr_cop_h > 0, hr_out_h * (1 - (1 / hr_cop_h)), 0.0) + + # Split total HRC output into building loads and exhaust air coil loads + hr_hhw = np.minimum(hr_out_h, df[Col.HHW_REM_W.value].to_numpy()) + hr_chw = np.minimum(hr_out_c, df[Col.CHW_REM_W.value].to_numpy()) + eac_h = hr_out_h - hr_hhw + eac_c = hr_out_c - hr_chw + + hr_hhw_no_eac = np.minimum(max_cap_h, simult_base) + hr_hhw_no_eac = np.where(hr_hhw_no_eac >= min_cap_h, hr_hhw_no_eac, 0.0) + + eac_h_coverage = ( + 100 * np.nansum(eac_h) / np.nansum(hr_out_h) if np.nansum(hr_out_h) > 0 else 0.0 + ) + eac_c_coverage = ( + 100 * np.nansum(eac_c) / np.nansum(hr_out_c) if np.nansum(hr_out_c) > 0 else 0.0 + ) + + logger.debug( + f"Balancing heat rejection: control={scen.hr_eac_rejection_control}, " + f"capacity={scen.hr_eac_rejection_cap_W:.1f} W, " + f"covers {eac_h_coverage:.1f}% of HR WWHP heating" + ) + logger.debug( + f"Balancing heat recovery: control={scen.hr_eac_recovery_control}, " + f"capacity={scen.hr_eac_recovery_cap_W:.1f} W, " + f"covers {eac_c_coverage:.1f}% of HR WWHP cooling" + ) + logger.debug( + f"EAC effect on HR WWHP heating (no coil -> with coil): " + f"{np.nansum(hr_hhw_no_eac) / 1000:.0f} -> {np.nansum(hr_hhw) / 1000:.0f} kWh" + ) # Electricity use - elec_hr = np.where(hr_cop_h > 0, hr_hhw / hr_cop_h, 0.0) + elec_hr = np.where(hr_cop_h > 0, hr_out_h / hr_cop_h, 0.0) # add refrigerant information hr_wwhp_refrigerant = hr_wwhp.refrigerant if hr_wwhp.refrigerant else "Unknown" @@ -658,6 +620,8 @@ def loads_to_site_energy( df[Col.HR_HHW_W.value] = hr_hhw df[Col.HR_CHW_W.value] = hr_chw df[Col.HR_COP_H.value] = hr_cop_h + df[Col.HR_EAC_H_W] = eac_h + df[Col.HR_EAC_C_W] = eac_c df[Col.ELEC_HR_WH.value] = elec_hr df[Col.ELEC_WH.value] += elec_hr df[Col.HHW_REM_W.value] -= hr_hhw @@ -1087,6 +1051,8 @@ def _finalize_columns(df: pd.DataFrame, detail: bool) -> list[str]: Col.MAX_CAP_H_HR_W.value, Col.MIN_CAP_H_HR_W.value, Col.SIMULT_H_HR_W.value, + Col.HR_EAC_H_W.value, + Col.HR_EAC_C_W.value, Col.ELEC_HR_WH.value, Col.HR_WWHP_REFRIGERANT.value, Col.HR_WWHP_REFRIGERANT_WEIGHT_KG.value, diff --git a/src/equipment.py b/src/equipment.py index 0a4e630..048a630 100644 --- a/src/equipment.py +++ b/src/equipment.py @@ -1,12 +1,20 @@ +import copy import json +import math +from collections.abc import Iterable from functools import lru_cache +from itertools import pairwise from pathlib import Path from typing import Literal +import pandas as pd from pydantic import BaseModel, Field, PrivateAttr from src.mixins import DotAccessMixin +HEAT_PUMP_TYPES = ("heat_pump", "hr_heat_pump") +PLAUSIBLE_COP_RANGE = (1.0, 8.0) # outside this range is flagged as a warning, not an error + # --- Models --- class PerformanceCurves(BaseModel): @@ -71,6 +79,12 @@ class Equipment(BaseModel): max_output_dba: float | None = None performance: dict[str, Performance] = Field(default_factory=dict) emissions: Emissions | None = None #! potentially rename to something more specific + source: Literal["library", "custom"] = "library" + based_on: str | None = None # eq_id of the library item a custom copy was made from + notes: str | None = None + # total factors applied to the curves of a custom copy, e.g. {"heating": {"cop": 0.95, "capacity": 1.1}}; + # informational only, the scaled values are stored in `performance` + scaling: dict[str, dict[str, float]] | None = None @property def performance_heating(self) -> Performance | None: @@ -89,6 +103,10 @@ class EquipmentScenario(DotAccessMixin, BaseModel): Literal["fixed_COP", "interpolate_HHWST", "performance_curves"] | None ) = None hr_wwhp_h_supply_t: float | None = None + hr_eac_rejection_cap_W: float | None = None + hr_eac_recovery_cap_W: float | None = None + hr_eac_rejection_control: Literal["min_turndown", "max_heat_rejection"] | None = None + hr_eac_recovery_control: Literal["min_turndown", "max_heat_recovery"] | None = None awhp: str | None = None awhp_performance_model: ( Literal[ @@ -115,6 +133,489 @@ class ScenarioGroup(BaseModel): scenario_ids: list[str] +# --- Validation --- +class EquipmentIssue(BaseModel): + """A single problem found in an equipment definition. `field` is a dotted path into the model.""" + + severity: Literal["error", "warning"] + field: str + message: str + + +def _curve_x_axis(eq: Equipment, perf: Performance) -> tuple[str, list[float] | None]: + """Name and values of the x-axis the curves are defined over: part-load capacity for HR WWHPs, outdoor air temperature for AWHPs.""" + if eq.eq_type == "hr_heat_pump": + return "capacity_W", perf.capacity_W + return "t_out_C", perf.t_out_C + + +def validate_equipment(eq: Equipment, modes: Iterable[str] | None = None) -> list[EquipmentIssue]: + """Check an equipment definition for completeness and consistency. + + Returns all issues found instead of raising, so callers can either report them + (equipment manager) or raise on the first error (calculation engine). + `modes` limits the checks to e.g. ("heating",); defaults to every mode present. + """ + issues: list[EquipmentIssue] = [] + + def add(severity, field, message): + issues.append( + EquipmentIssue( + severity=severity, field=field, message=f"Equipment '{eq.eq_id}' {message}" + ) + ) + + modes = list(eq.performance) if modes is None else list(modes) + + if eq.eq_type in HEAT_PUMP_TYPES: + if eq.eq_calc_type == "specific" and eq.nominal_capacity_W is None: + add("warning", "nominal_capacity_W", "has no nominal capacity.") + for mode in modes: + _validate_heat_pump_mode(eq, mode, add) + else: + for mode in modes: + perf = eq.performance.get(mode) + if perf is None: + add("error", f"performance.{mode}", f"lacks {mode} performance data.") + elif perf.efficiency is None or perf.efficiency <= 0: + add("error", f"performance.{mode}.efficiency", "requires a positive 'efficiency'.") + + return issues + + +def _validate_constraints(constraints, field, label, add): + if not constraints or "min_temp_C" not in constraints or "max_temp_C" not in constraints: + add("error", field, f"lacks {label} (min_temp_C and max_temp_C).") + elif constraints["min_temp_C"] > constraints["max_temp_C"]: + add("error", field, f"has {label} with min_temp_C above max_temp_C.") + + +def _validate_heat_pump_mode(eq: Equipment, mode: str, add): + prefix = f"performance.{mode}" + perf = eq.performance.get(mode) + if perf is None: + add("error", prefix, f"lacks {mode} performance data.") + return + if not perf.leaving_supply_t: + add("error", f"{prefix}.leaving_supply_t", f"has no {mode} performance curves.") + return + + x_name, x = _curve_x_axis(eq, perf) + if not x: + add("error", f"{prefix}.{x_name}", f"lacks {mode} capacity info ({x_name} curve).") + elif not all(math.isfinite(v) for v in x): + add("error", f"{prefix}.{x_name}", f"has a missing {mode} {x_name} value.") + elif any(b <= a for a, b in pairwise(x)): + add("error", f"{prefix}.{x_name}", f"{mode} {x_name} values must be strictly increasing.") + + _validate_constraints( + perf.constraints, f"{prefix}.constraints", f"{mode} supply temperature limits", add + ) + + supply_temps: dict[float, str] = {} + for key in perf.leaving_supply_t: + try: + t = float(key) + except ValueError: + add( + "error", + f"{prefix}.leaving_supply_t", + f"has a {mode} supply temperature '{key}' that is not a number.", + ) + continue + if t in supply_temps: + add( + "error", + f"{prefix}.leaving_supply_t", + f"lists {mode} supply temperature {key} more than once.", + ) + supply_temps[t] = key + + c = perf.constraints or {} + if ( + supply_temps + and "min_temp_C" in c + and "max_temp_C" in c + and (min(supply_temps) != c["min_temp_C"] or max(supply_temps) != c["max_temp_C"]) + ): + add( + "warning", + f"{prefix}.constraints", + f"{mode} supply temperature limits do not match the range of the curves " + f"({min(supply_temps)} to {max(supply_temps)} °C).", + ) + + for key, curves in perf.leaving_supply_t.items(): + field = f"{prefix}.leaving_supply_t.{key}" + label = f"supply temperature {key}" + + if not curves.cop: + add("error", f"{field}.cop", f"lacks {mode} capacity info (COP curve for {label}).") + elif not all(math.isfinite(v) for v in curves.cop): + add("error", f"{field}.cop", f"has a missing {mode} COP value for {label}.") + else: + if x and len(curves.cop) != len(x): + add( + "error", + f"{field}.cop", + f"{mode} COP and {x_name} curves are of different lengths for {label}.", + ) + if any(v <= 0 for v in curves.cop): + add("error", f"{field}.cop", f"has a non-positive {mode} COP for {label}.") + elif any(not PLAUSIBLE_COP_RANGE[0] <= v <= PLAUSIBLE_COP_RANGE[1] for v in curves.cop): + add( + "warning", + f"{field}.cop", + f"has a {mode} COP outside the typical range " + f"{PLAUSIBLE_COP_RANGE[0]} to {PLAUSIBLE_COP_RANGE[1]} for {label}.", + ) + + if eq.eq_type != "heat_pump": + continue + + # AWHP: capacity per supply temperature, or a fixed capacity for the unit + if curves.capacity_W: + if not all(math.isfinite(v) for v in curves.capacity_W): + add( + "error", + f"{field}.capacity_W", + f"has a missing {mode} capacity value for {label}.", + ) + elif x and len(curves.capacity_W) != len(x): + add( + "error", + f"{field}.capacity_W", + f"{mode} capacity_W and t_out curves are of different lengths for {label}.", + ) + if any(v <= 0 for v in curves.capacity_W): + add( + "error", + f"{field}.capacity_W", + f"has a non-positive {mode} capacity for {label}.", + ) + elif not eq.capacity_W: + add( + "error", + f"{field}.capacity_W", + f"lacks {mode} capacity info (fixed value or t_out-based curve for capacity_W at {label}).", + ) + + _validate_constraints( + curves.constraints, + f"{field}.constraints", + f"{mode} outdoor air temperature limits for {label}", + add, + ) + + +# --- Helpers for user-defined equipment --- +def duplicate_equipment(eq: Equipment, existing_ids: Iterable[str]) -> Equipment: + """Return an editable custom copy of `eq` with an id not in `existing_ids`.""" + existing_ids = set(existing_ids) + base_id = eq.based_on if eq.source == "custom" and eq.based_on else eq.eq_id + n = 1 + while f"custom_{base_id}_{n}" in existing_ids: + n += 1 + return eq.model_copy( + deep=True, + update={ + "eq_id": f"custom_{base_id}_{n}", + "model": f"{eq.model} (copy)", + "source": "custom", + "based_on": base_id, + }, + ) + + +SCENARIO_EQUIPMENT_FIELDS = ("hr_wwhp", "awhp", "backup_heating", "chiller") + + +def scenarios_using(equipment_data: dict, eq_id: str) -> list[str]: + """Names of the equipment scenarios in `equipment_data` that use `eq_id`.""" + return [ + s.get("eq_scen_name") or s.get("eq_scen_id") + for s in (equipment_data or {}).get("equipment_scenarios", []) + if any(s.get(f) == eq_id for f in SCENARIO_EQUIPMENT_FIELDS) + ] + + +def save_custom_equipment(equipment_data: dict, eq: Equipment, library_ids: Iterable[str]) -> dict: + """Return `equipment_data` with the custom item `eq` added or replaced. + + Refuses anything that would overwrite library equipment: `eq` must be a custom item + whose id is not one of `library_ids`. + """ + if eq.source != "custom" or eq.eq_id in set(library_ids): + raise ValueError(f"Equipment '{eq.eq_id}' is library equipment and cannot be overwritten.") + item = eq.model_dump() + equipment = list((equipment_data or {}).get("equipment", [])) + index = next((i for i, e in enumerate(equipment) if e.get("eq_id") == eq.eq_id), None) + if index is None: + equipment.append(item) + else: + equipment[index] = item + return {**(equipment_data or {}), "equipment": equipment} + + +def delete_custom_equipment(equipment_data: dict, eq_id: str) -> dict: + """Return `equipment_data` without the custom item `eq_id`; refuses library items and items in use.""" + equipment = (equipment_data or {}).get("equipment", []) + item = next((e for e in equipment if e.get("eq_id") == eq_id), None) + if item is None or item.get("source") != "custom": + raise ValueError(f"Equipment '{eq_id}' is not custom equipment and cannot be deleted.") + used_by = scenarios_using(equipment_data, eq_id) + if used_by: + raise ValueError( + f"Equipment '{eq_id}' is used by {', '.join(used_by)}. " + "Choose other equipment in these scenarios first." + ) + return {**equipment_data, "equipment": [e for e in equipment if e.get("eq_id") != eq_id]} + + +def keep_custom_equipment(initial_data: dict, current_data: dict | None) -> dict: + """`initial_data` (the library) plus the custom equipment in `current_data`, used when resetting.""" + custom = [e for e in (current_data or {}).get("equipment", []) if e.get("source") == "custom"] + if not custom: + return initial_data + return {**initial_data, "equipment": [*initial_data.get("equipment", []), *custom]} + + +# --- Import / export of custom equipment --- +CUSTOM_EQUIPMENT_FORMAT = "decarb-tool/custom-equipment" +CUSTOM_EQUIPMENT_FORMAT_VERSION = "1.0" + + +def export_custom_equipment(equipment_data: dict, tool_version: str | None = None) -> dict: + """The custom equipment in `equipment_data` as an export file (see `import_custom_equipment`).""" + import datetime + + return { + "format": CUSTOM_EQUIPMENT_FORMAT, + "format_version": CUSTOM_EQUIPMENT_FORMAT_VERSION, + "tool_version": tool_version, + "exported_at": datetime.datetime.now().isoformat(timespec="seconds"), + "equipment": [ + copy.deepcopy(e) + for e in (equipment_data or {}).get("equipment", []) + if e.get("source") == "custom" + ], + } + + +class ImportReport(BaseModel): + """What `import_custom_equipment` did with each item of a file.""" + + added: list[str] = [] + updated: list[str] = [] + renamed: dict[str, str] = {} # id in the file -> new id (the file's id is a library id) + unchanged: list[str] = [] + rejected: dict[str, str] = {} # id (or position) in the file -> reason + + @property + def imported(self) -> list[str]: + return [*self.added, *self.updated, *self.renamed.values()] + + +def _items_in_file(payload) -> list: + """Equipment items of an export file, a results settings file or a bare list.""" + if isinstance(payload, list): + return payload + if not isinstance(payload, dict): + raise ValueError("The file does not contain equipment.") + if isinstance(payload.get("equipment"), list): + return payload["equipment"] + library = payload.get("equipment_library") + if isinstance(library, dict) and isinstance(library.get("equipment"), list): + # results settings file: only the custom items, the library is already in the tool + return [ + e for e in library["equipment"] if isinstance(e, dict) and e.get("source") == "custom" + ] + raise ValueError("The file does not contain equipment.") + + +def import_custom_equipment( + equipment_data: dict, payload, library_ids: Iterable[str] +) -> tuple[dict, ImportReport]: + """Add the equipment of an imported file to `equipment_data` as custom equipment. + + Library equipment is never overwritten: an item with a library id is imported under a new + custom id. An item with the id of a custom item replaces it (or is skipped when identical). + Items that cannot be read or have validation errors are rejected. + """ + library_ids = set(library_ids) + report = ImportReport() + data = equipment_data or {} + + for n, item in enumerate(_items_in_file(payload), start=1): + label = item.get("eq_id") if isinstance(item, dict) and item.get("eq_id") else f"item {n}" + try: + eq = Equipment(**item) + except (TypeError, ValueError) as err: + reason = err.errors()[0]["msg"] if hasattr(err, "errors") else str(err) + report.rejected[label] = f"not a valid equipment definition ({reason})" + continue + stored = _stored_item(data, eq.eq_id) + if stored is not None and eq.model_dump() == stored: + report.unchanged.append( + eq.eq_id + ) # e.g. a library item, or a custom item imported twice + continue + errors = [i.message for i in validate_equipment(eq) if i.severity == "error"] + if errors: + report.rejected[label] = errors[0] + continue + + if eq.eq_id in library_ids: + # a changed library item: keep it as a custom copy, never overwrite the library + existing_ids = [e.get("eq_id") for e in data.get("equipment", [])] + duplicate = duplicate_equipment( + eq.model_copy(update={"source": "library"}), existing_ids + ) + eq = duplicate.model_copy(update={"model": eq.model}) + report.renamed[label] = eq.eq_id + else: + eq = eq.model_copy(update={"source": "custom"}) + (report.updated if stored is not None else report.added).append(eq.eq_id) + data = save_custom_equipment(data, eq, library_ids) + + return data, report + + +def _stored_item(equipment_data: dict, eq_id: str) -> dict | None: + """The stored item with `eq_id`, normalised through the model so it compares with an import.""" + item = next((e for e in equipment_data.get("equipment", []) if e.get("eq_id") == eq_id), None) + return Equipment(**item).model_dump() if item else None + + +CURVE_TABLE_COLUMNS = ["x", "x_kind", "lwt_C", "cop", "capacity_W", "oat_min_C", "oat_max_C"] + + +def curve_table(eq: Equipment, mode: str) -> pd.DataFrame: + """Heat pump performance curves for one mode as a long table, one row per (supply temperature, x) point. + + `x` is outdoor air temperature (AWHP) or part-load capacity (HR WWHP), named in `x_kind`. + Supply temperatures are sorted numerically. `capacity_W` is NaN where an AWHP only has a + fixed unit capacity. Expects equipment without validation errors. + """ + perf = eq.performance.get(mode) + if eq.eq_type not in HEAT_PUMP_TYPES or perf is None or not perf.leaving_supply_t: + return pd.DataFrame(columns=CURVE_TABLE_COLUMNS) + + x_name, x = _curve_x_axis(eq, perf) + frames = [] + for key, curves in sorted(perf.leaving_supply_t.items(), key=lambda item: float(item[0])): + constraints = curves.constraints or {} + # HR WWHP curves are defined over capacity; AWHPs may only have a fixed unit capacity + capacity = x if x_name == "capacity_W" else curves.capacity_W or [float("nan")] * len(x) + frames.append( + pd.DataFrame( + { + "x": x, + "x_kind": x_name, + "lwt_C": float(key), + "cop": curves.cop, + "capacity_W": capacity, + "oat_min_C": constraints.get("min_temp_C", float("nan")), + "oat_max_C": constraints.get("max_temp_C", float("nan")), + } + ) + ) + return pd.concat(frames, ignore_index=True)[CURVE_TABLE_COLUMNS] + + +def apply_curve_table(eq: Equipment, mode: str, df: pd.DataFrame) -> Equipment: + """Return a copy of `eq` with the `mode` curves replaced by a long table in `curve_table` format. + + The inverse of `curve_table`: rows are grouped by `lwt_C` and sorted by `x`. Every supply + temperature must share the same x points. AWHP capacity columns that are all NaN mean the + item uses its fixed unit capacity. The mode's supply temperature limits are set to the + range of the curves. + """ + eq = eq.model_copy(deep=True) + perf = eq.performance.get(mode) or Performance() + x_name = "capacity_W" if eq.eq_type == "hr_heat_pump" else "t_out_C" + df = df.sort_values(["lwt_C", "x"]) + + x_points = None + curves = {} + for lwt, d in df.groupby("lwt_C", sort=True): + x = [float(v) for v in d["x"]] + if x_points is None: + x_points = x + elif x != x_points: + raise ValueError("All supply temperatures need the same curve points.") + cap = d["capacity_W"] + constraints = None + if x_name == "t_out_C" and d[["oat_min_C", "oat_max_C"]].iloc[0].notna().all(): + constraints = { + "min_temp_C": float(d["oat_min_C"].iloc[0]), + "max_temp_C": float(d["oat_max_C"].iloc[0]), + } + curves[_lwt_key(lwt)] = PerformanceCurves( + cop=[float(v) for v in d["cop"]], + capacity_W=( + [float(v) for v in cap] if x_name == "t_out_C" and cap.notna().all() else None + ), + constraints=constraints, + ) + + setattr(perf, x_name, x_points) + perf.leaving_supply_t = curves + if curves: + # supply temperature limits follow the range of the curves + lwts = [float(k) for k in curves] + perf.constraints = { + **(perf.constraints or {}), + "min_temp_C": min(lwts), + "max_temp_C": max(lwts), + } + eq.performance[mode] = perf + return eq + + +def _lwt_key(lwt: float) -> str: + """Supply temperature as a dict key in the library's style: '38', '32.2'.""" + return f"{float(lwt):g}" + + +def scale_performance( + eq: Equipment, mode: str, cop_factor: float = 1.0, capacity_factor: float = 1.0 +) -> Equipment: + """Return a copy of `eq` with the `mode` curves scaled to the given total factors. + + The factors are relative to the unscaled curves: the curves are multiplied by the new + factor divided by the one already applied (`eq.scaling`), so applying 110 % twice stays + at 110 %. Scales COP and capacity (AWHP per supply temperature or fixed unit capacity, + HR WWHP part-load capacity points, and the nominal capacity). + """ + if cop_factor <= 0 or capacity_factor <= 0: + raise ValueError("Scaling factors must be positive.") + eq = eq.model_copy(deep=True) + perf = eq.performance.get(mode) + if perf is None or not perf.leaving_supply_t: + return eq + + previous = (eq.scaling or {}).get(mode, {}) + cop_step = cop_factor / previous.get("cop", 1.0) + cap_step = capacity_factor / previous.get("capacity", 1.0) + + for curves in perf.leaving_supply_t.values(): + curves.cop = [v * cop_step for v in curves.cop or []] + if curves.capacity_W: + curves.capacity_W = [v * cap_step for v in curves.capacity_W] + if eq.eq_type == "hr_heat_pump" and perf.capacity_W: + perf.capacity_W = [v * cap_step for v in perf.capacity_W] + elif eq.eq_type == "heat_pump" and eq.capacity_W: + eq.capacity_W *= cap_step + if eq.nominal_capacity_W: + eq.nominal_capacity_W = round(eq.nominal_capacity_W * cap_step) + + scaling = dict(eq.scaling or {}) + scaling[mode] = {"cop": cop_factor, "capacity": capacity_factor} + eq.scaling = {m: f for m, f in scaling.items() if f != {"cop": 1.0, "capacity": 1.0}} or None + return eq + + # --- Dot-accessible wrapper with dynamic updates --- class DotDict: def __init__(self, items: list[BaseModel], id_attr: str): @@ -173,6 +674,10 @@ def get_equipment(self, eq_id: str) -> Equipment: def get_scenario(self, eq_scen_id: str) -> EquipmentScenario: return self._scenarios[eq_scen_id] + def validation_issues(self) -> dict[str, list[EquipmentIssue]]: + """Validation issues per equipment id (empty list when an item is fine).""" + return {e.eq_id: validate_equipment(e) for e in self.equipment} + # Dynamic updates def add_equipment(self, equipment: Equipment): self.equipment.append(equipment) @@ -229,6 +734,53 @@ def to_json(self, file_path: str | Path, indent: int = 2): json.dump(data, f, indent=indent) +# --- Refrigerants --- +class Refrigerant(BaseModel): + """A refrigerant and its global warming potential (100-year, IPCC AR4 where listed).""" + + name: str + aliases: list[str] = [] + gwp: float + type: str | None = None + safety_class: str | None = None + note: str | None = None + + +def _refrigerant_key(name: str) -> str: + """Name normalised for matching: 'R-134A', 'r134a' and 'R 134a' are the same refrigerant.""" + return "".join(c for c in name.upper() if c.isalnum()) + + +@lru_cache(maxsize=4) +def load_refrigerants(file_path: str | Path | None = None) -> tuple[Refrigerant, ...]: + """Refrigerant database from CSV (columns name, aliases, gwp, type, safety_class, note).""" + from src import paths + + df = pd.read_csv(file_path or paths.REFRIGERANTS_CSV, dtype=str, keep_default_na=False) + return tuple( + Refrigerant( + name=r["name"], + aliases=[a.strip() for a in r["aliases"].split(";") if a.strip()], + gwp=float(r["gwp"]), + type=r["type"] or None, + safety_class=r["safety_class"] or None, + note=r["note"] or None, + ) + for r in df.to_dict("records") + ) + + +def find_refrigerant(name: str | None, refrigerants: Iterable[Refrigerant] | None = None): + """The database entry matching `name` (or one of its aliases), or None.""" + if not name: + return None + key = _refrigerant_key(name) + for r in refrigerants if refrigerants is not None else load_refrigerants(): + if key in {_refrigerant_key(n) for n in (r.name, *r.aliases)}: + return r + return None + + # --- Loader --- @lru_cache(maxsize=4) def load_library(file_path: str | Path) -> EquipmentLibrary: diff --git a/src/export.py b/src/export.py index 6b17cde..ff5ea0e 100644 --- a/src/export.py +++ b/src/export.py @@ -1,8 +1,239 @@ import datetime +import re + +import numpy as np +import pandas as pd from src.equipment import EquipmentLibrary from src.metadata import Metadata -from utils.units import UNIT_MAP +from utils.display_registry import format_emission_scenario_id_short +from utils.units import ( + COLUMN_DISPLAY_NAMES, + UNIT_MAP, + convert_dataframe, + get_category, + get_column_label, +) + +# Columns that identify a case (equipment x emission scenario); first in every results CSV +EXPORT_ID_COLUMNS = [ + "eq_scen_slot", + "eq_scen_name", + "em_scen_letter", + "em_scen_name", + "em_year", + "em_grid_scenario", + "em_elec_source", + "em_emission_type", + "eq_scen_id", + "em_scen_id", +] + +# Hourly results column order after the identifiers; columns not listed here are appended +_HOURLY_COLUMN_ORDER = [ + # conditions + "t_out_C", + "heating_W", + "cooling_W", + # totals + "elec_Wh", + "gas_Wh", + "elec_emissions", + "gas_emissions", + "total_refrig_emissions", + "total_emissions", + # grid emission rates + "elec_emissions_rate_gCO2e_per_kWh", + "lrmer_co2e_c", + "lrmer_co2e_p", + "lrmer_co2e", + "srmer_co2e_c", + "srmer_co2e_p", + "srmer_co2e", + "aer_load_co2e_c", + "aer_load_co2e_p", + "aer_load_co2e", + "shortrun_weighting", + # equipment operation, heating then cooling + "hhw_W", + "chw_W", + "hr_hhw_W", + "hr_chw_W", + "hr_cop_h", + "simult_h_hr_W", + "elec_hr_Wh", + "awhp_hhw_W", + "awhp_cap_h_W", + "awhp_cop_h", + "elec_awhp_h_Wh", + "boiler_hhw_W", + "gas_boiler_Wh", + "res_hhw_W", + "elec_res_Wh", + "awhp_chw_W", + "awhp_num_c", + "awhp_cap_c_W", + "awhp_cop_c", + "elec_awhp_c_Wh", + "chiller_chw_W", + "chiller_cop", + "elec_chiller_Wh", + # equipment properties, constant per equipment scenario + "max_cap_h_hr_W", + "min_cap_h_hr_W", + "awhp_num", + "awhp_num_redundant", + "boiler_num", + "boiler_cap_W", + "boiler_eff", + "hr_wwhp_refrigerant", + "hr_wwhp_refrigerant_weight_kg", + "hr_wwhp_refrigerant_gwp_kgCO2e_per_kgRefrig", + "awhp_refrigerant", + "total_awhp_refrigerant_weight_kg", + "total_awhp_refrigerant_gwp_kgCO2e_per_kgRefrig", + "chiller_refrigerant", + "chiller_refrigerant_weight_kg", + "chiller_refrigerant_gwp_kgCO2e_per_kgRefrig", + "total_refrig_gwp_kg", +] + +# Load year of the timestamp; dropped so it is not mistaken for the emission year +_HOURLY_DROP_COLUMNS = ["year"] + +# Hourly columns summed into the annual summary (hourly data, so W sums to Wh) +_ANNUAL_SUM_COLUMNS = { + "heating_W": "annual_heating_Wh", + "cooling_W": "annual_cooling_Wh", + "elec_Wh": "elec_Wh", + "gas_Wh": "gas_Wh", + "elec_hr_Wh": "elec_hr_Wh", + "elec_awhp_h_Wh": "elec_awhp_h_Wh", + "elec_res_Wh": "elec_res_Wh", + "elec_awhp_c_Wh": "elec_awhp_c_Wh", + "elec_chiller_Wh": "elec_chiller_Wh", + "gas_boiler_Wh": "gas_boiler_Wh", + "elec_emissions": "elec_emissions", + "gas_emissions": "gas_emissions", + "total_refrig_emissions": "total_refrig_emissions", + "total_emissions": "total_emissions", +} + + +def _slug(text, max_len: int = 40) -> str: + """Filename-safe part: letters, digits, '.' and '-' only.""" + slug = re.sub(r"[^A-Za-z0-9.]+", "-", str(text)).strip("-.") + return slug[:max_len].rstrip("-.") + + +def _building_label(metadata: Metadata) -> str: + building_id = _slug(metadata.building_id or "") + if metadata.load_data.load_type == "custom": + if not building_id and metadata.load_data.load_source_ref: + building_id = _slug(metadata.load_data.load_source_ref.rsplit(".", 1)[0]) + return f"custom-{building_id}" if building_id else "custom" + if building_id.isdigit(): + return f"B{building_id}" + return building_id + + +def build_export_basename( + metadata: Metadata, + unit_mode: str = "SI", + scale_info: dict | None = None, + base_load_info: dict | None = None, + now: datetime.datetime | None = None, +) -> str: + """Descriptive name for the results download, e.g. + decarb_B3_Denver_CZ5B_scaled-h1.25-c1.25_SI_20261102-1430 + """ + now = now or datetime.datetime.now() + parts = ["decarb", _building_label(metadata)] + if metadata.location: + parts.append(_slug(metadata.location)) + if metadata.ashrae_climate_zone: + parts.append(f"CZ{_slug(metadata.ashrae_climate_zone)}") + if scale_info: + heating = scale_info.get("heating_factor", 1.0) + cooling = scale_info.get("cooling_factor", 1.0) + parts.append(f"scaled-h{heating:.2f}-c{cooling:.2f}") + if base_load_info and any(base_load_info.get(k) for k in ("heating", "cooling")): + parts.append("baseload") + parts.append(unit_mode or "SI") + parts.append(now.strftime("%Y%m%d-%H%M")) + return "_".join(p for p in parts if p) + + +def _slot_number(eq_scen_id: str, slot_map: dict) -> int | None: + if eq_scen_id in slot_map: + return slot_map[eq_scen_id] + suffix = str(eq_scen_id).removeprefix("eq_scenario_") + return int(suffix) if suffix.isdigit() else None + + +def build_hourly_export( + df: pd.DataFrame, metadata: Metadata, slot_map: dict | None = None +) -> pd.DataFrame: + """Hourly results in export layout (raw column names, base units). + + Adds readable case identifiers (equipment slot, emission letter, emission scenario + settings) as the first columns, orders the remaining columns by topic and sorts the + rows so that each equipment x emission combination is one contiguous block. + + slot_map maps eq_scen_id to its slot on the Equipment page, the number the Results + page shows; without it the number in the scenario id is used. + """ + slot_map = slot_map or {} + em_by_id = {s.em_scen_id: s for s in metadata.emission_settings} + + out = df.drop(columns=[c for c in _HOURLY_DROP_COLUMNS if c in df.columns]) + eq_ids = out["eq_scen_id"] + em_ids = out["em_scen_id"] + + slots = {i: _slot_number(i, slot_map) for i in eq_ids.unique()} + out["eq_scen_slot"] = eq_ids.map(slots).astype("Int64") + out["em_scen_letter"] = em_ids.map(format_emission_scenario_id_short) + + descriptors = { + "em_scen_name": "em_scen_name", + "em_year": "year", + "em_grid_scenario": "grid_scenario", + "em_elec_source": "elec_emission_source", + "em_emission_type": "emission_type", + } + for col, field in descriptors.items(): + values = {i: getattr(s, field) for i, s in em_by_id.items()} + out[col] = em_ids.map(values) + out["em_year"] = out["em_year"].astype("Int64") + + ordered = [c for c in EXPORT_ID_COLUMNS + _HOURLY_COLUMN_ORDER if c in out.columns] + ordered += [c for c in out.columns if c not in ordered] + out = out[ordered] + + index_name = out.index.name or "timestamp" + out = ( + out.rename_axis(index_name) + .reset_index() + .sort_values(["eq_scen_slot", "eq_scen_id", "em_scen_id", index_name], kind="stable") + .set_index(index_name) + ) + return out + + +def build_annual_summary(df_hourly: pd.DataFrame) -> pd.DataFrame: + """Annual totals, one row per equipment x emission combination (base units). + + Takes the output of build_hourly_export. Hourly loads in W sum to annual Wh. + """ + id_cols = [c for c in EXPORT_ID_COLUMNS if c in df_hourly.columns] + sum_cols = [c for c in _ANNUAL_SUM_COLUMNS if c in df_hourly.columns] + annual = ( + df_hourly.groupby(id_cols, dropna=False, sort=False)[sum_cols] + .sum() + .reset_index() + .rename(columns=_ANNUAL_SUM_COLUMNS) + ) + return annual def _perf_model_label(model: str | None) -> str: @@ -51,6 +282,110 @@ def _eq_capacity(eq_id: str | None, library: EquipmentLibrary, unit_mode: str) - return "N/A" +def _round_like_python(values, decimals): + """Vectorised round() with the same result as Python's built-in round(). + + Series.round() can differ from round() on values that look like exact + halves in decimal (e.g. 6.825); those few values are rounded one by one. + Masks and assignments are positional, as the hourly index repeats per case. + """ + rounded = values.round(decimals) + scaled = values * 10**decimals + near_half = (((scaled - np.trunc(scaled)).abs() - 0.5).abs() < 1e-6).to_numpy() + if near_half.any(): + rounded.iloc[near_half] = [round(v, decimals) for v in values.iloc[near_half]] + return rounded + + +def _round_for_csv(values): + """2 decimals for |x| >= 1, 4 significant figures below (at most 8 decimals). + + Significant figures keep small values such as lb CO2e/kWh rates or hourly + emissions from rounding to zero. + """ + rounded = _round_like_python(values, 2) + magnitude = values.abs().to_numpy() + small = (magnitude < 1) & (magnitude > 0) + if small.any(): + decimals = np.zeros(len(values), dtype=int) + decimals[small] = np.minimum(3 - np.floor(np.log10(magnitude[small])), 8) + for d in np.unique(decimals[small]): + mask = small & (decimals == d) + rounded.iloc[mask] = _round_like_python(values.iloc[mask], int(d)).to_numpy() + return rounded + + +def format_for_csv(df, unit_mode): + """Convert to the unit system, round, and label columns with display name and unit.""" + df = convert_dataframe(df, unit_mode) + + for col in df.columns: + if df[col].dtype in [np.float64, np.float32, float]: + df[col] = _round_for_csv(df[col]) + + # Columns with a unit category get "Name [unit]"; others just their display name + column_renames = {} + for col in df.columns: + if get_category(col) is not None: + column_renames[col] = get_column_label(col, unit_mode) + elif col in COLUMN_DISPLAY_NAMES: + column_renames[col] = COLUMN_DISPLAY_NAMES[col] + return df.rename(columns=column_renames) + + +def _format_rate(value: float) -> str: + """1 decimal for g/kWh-sized values, 4 significant figures for lb-sized ones.""" + return f"{value:.1f}" if abs(value) >= 10 else f"{value:.4g}" + + +def _load_modification_lines(scale_info, base_load_info, unit_mode, row) -> list[str]: + area_func = UNIT_MAP["area"][unit_mode]["func"] + area_unit = UNIT_MAP["area"][unit_mode]["unit"] + power_func = UNIT_MAP["power"][unit_mode]["func"] + power_unit = UNIT_MAP["power"][unit_mode]["unit"] + + lines = [] + if scale_info: + lines.append(row("Scaled By:", scale_info.get("method") or "N/A")) + lines.append(row("Heating Scale Factor:", f"{scale_info.get('heating_factor', 1.0):.3f}")) + lines.append(row("Cooling Scale Factor:", f"{scale_info.get('cooling_factor', 1.0):.3f}")) + if scale_info.get("orig_area_sqm") is not None: + lines.append( + row( + f"Original Floor Area [{area_unit}]:", + f"{area_func(scale_info['orig_area_sqm']):,.0f}", + ) + ) + if scale_info.get("target_area_sqm") is not None: + lines.append( + row( + f"Target Floor Area [{area_unit}]:", + f"{area_func(scale_info['target_area_sqm']):,.0f}", + ) + ) + else: + lines.append(row("Scaling:", "None (original load profile)")) + + base_load_info = base_load_info or {} + methods = {"floor": "Floor (minimum)", "offset": "Constant offset"} + for load_type in ("heating", "cooling"): + entry = base_load_info.get(load_type) + label = f"{load_type.capitalize()} Base Load:" + if not entry: + lines.append(row(label, "None")) + continue + # Shown in the export's unit mode, not the one active when it was entered + value = power_func(entry["value_W"]) + lines.append( + row( + label, + f"{methods.get(entry.get('method'), entry.get('method'))}, " + f"{value:,.1f} {power_unit}", + ) + ) + return lines + + def _section(title: str) -> str: bar = "━" * 50 return f"\n{bar}\n {title}\n{bar}\n" @@ -62,6 +397,8 @@ def build_metadata_summary( selected_eq_ids: list[str], selected_em_ids: list[str], unit_mode: str = "SI", + scale_info: dict | None = None, + base_load_info: dict | None = None, ) -> str: unit_mode = unit_mode or "SI" energy_func = UNIT_MAP["energy"][unit_mode]["func"] @@ -72,6 +409,10 @@ def build_metadata_summary( area_unit = UNIT_MAP["area"][unit_mode]["unit"] temp_func = UNIT_MAP["temperature"][unit_mode]["func"] temp_unit = UNIT_MAP["temperature"][unit_mode]["unit"] + rate_func = UNIT_MAP["emissions_rate"][unit_mode]["func"] + rate_unit = UNIT_MAP["emissions_rate"][unit_mode]["unit"] + ng_rate_func = UNIT_MAP["gas_emission_factor"][unit_mode]["func"] + ng_rate_unit = UNIT_MAP["gas_emission_factor"][unit_mode]["unit"] unit_label = "SI (metric)" if unit_mode == "SI" else "IP (imperial)" now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") @@ -122,6 +463,10 @@ def row(label, value): if ld.heat_recovery_heating_fraction is not None: lines.append(row("Heat Recovery Fraction:", f"{ld.heat_recovery_heating_fraction:.2f}")) + # ── Load Modifications ───────────────────────────────── + lines.append(_section("LOAD MODIFICATIONS")) + lines.extend(_load_modification_lines(scale_info, base_load_info, unit_mode, row)) + # ── Equipment Scenarios ──────────────────────────────── lines.append(_section("EQUIPMENT SCENARIOS")) @@ -207,13 +552,15 @@ def row(label, value): ): lines.append( " Elec. Emission Rate: " - f"{scen.elec_avg_emission_rate_gCO2e_per_kWh:.1f} g CO₂e / kWh" + f"{_format_rate(rate_func(scen.elec_avg_emission_rate_gCO2e_per_kWh))}" + f" {rate_unit}" ) lines.append( f" Refrig. Leakage: {scen.annual_refrig_leakage_percent:.2f} % / year" ) lines.append( - f" NG Emission Rate: {scen.ng_emission_rate_gCO2e_per_kWh:.1f} g CO₂e / kWh" + " NG Emission Rate: " + f"{_format_rate(ng_rate_func(scen.ng_emission_rate_gCO2e_per_kWh))} {ng_rate_unit}" ) if i < len(selected_em): diff --git a/src/loads.py b/src/loads.py index 26a68b2..8bbc6c3 100644 --- a/src/loads.py +++ b/src/loads.py @@ -274,6 +274,36 @@ def stats(self) -> pd.DataFrame: return self.df.describe() +def apply_load_modifications( + df: pd.DataFrame, + heating_factor: float = 1.0, + cooling_factor: float = 1.0, + base_load: dict | None = None, +) -> pd.DataFrame: + """Return a copy of df with load scaling and base-load adjustment applied. + + Scaling is applied first, then the base load (floor or offset), so the base load + always stays at the absolute value the user entered. + + base_load: one base load per load type (shape of base-load-info-store), or None: + {"heating": {"method": "floor" | "offset", "value_W": float} | None, "cooling": ... | None} + """ + out = df.copy() + out["heating_W"] = out["heating_W"] * heating_factor + out["cooling_W"] = out["cooling_W"] * cooling_factor + + for load_type, col in (("heating", "heating_W"), ("cooling", "cooling_W")): + mod = (base_load or {}).get(load_type) + if not mod: + continue + if mod["method"] == "floor": + out[col] = out[col].clip(lower=mod["value_W"]) + else: # offset + out[col] = out[col] + mod["value_W"] + + return out + + def get_load_data(metadata: Metadata) -> StandardLoad: """ Load and filter load data based on Metadata settings. diff --git a/src/paths.py b/src/paths.py index babd3c5..476a77f 100644 --- a/src/paths.py +++ b/src/paths.py @@ -11,4 +11,5 @@ LOAD_DATA_PARQUET = DATA_DIR / "load_data_full.parquet" EMISSION_DATA_PARQUET = DATA_DIR / "emission_data.parquet" EQUIPMENT_JSON = DATA_DIR / "equipment_data.JSON" +REFRIGERANTS_CSV = DATA_DIR / "refrigerants.csv" METADATA_INDEX_JSON = DATA_DIR / "metadata_index.json" diff --git a/src/visuals.py b/src/visuals.py index 1b48af1..e6b8c0a 100644 --- a/src/visuals.py +++ b/src/visuals.py @@ -4,14 +4,17 @@ import plotly.graph_objects as go from plotly.subplots import make_subplots +from src.equipment import Equipment, curve_table from utils.display_registry import ( format_emission_scenario_id_short, format_equipment_scenario_id_short, format_meter_name, ) +from utils.interp import interp_vector from utils.units import ( convert_dataframe, get_auto_scale, + get_converter, get_display_unit, # Legacy import for backward compatibility (axis labels with HTML) unit_map, @@ -858,3 +861,308 @@ def plot_scatter_temp_vs_variable( ) return fig + + +CURVE_PALETTES = { + # sequential, light (low supply temperature) to dark (high) + "heating": ("#F6B352", "#8E1B3A"), + "cooling": ("#8EC5EE", "#0B3C78"), +} +CURVE_STYLE = dict( + font=dict(size=12, color="#343a40"), + grid="#e9ecef", + axis="#adb5bd", + original="#adb5bd", + highlight="#212529", +) + + +def _supply_temp_colors(n: int, mode: str) -> list[str]: + """Sequential colours for supply temperature curves: light (low) to dark (high).""" + low, high = ( + px.colors.hex_to_rgb(c) for c in CURVE_PALETTES.get(mode, CURVE_PALETTES["heating"]) + ) + if n == 1: + return [px.colors.label_rgb(px.colors.find_intermediate_color(low, high, 0.6))] + return [ + px.colors.label_rgb(px.colors.find_intermediate_color(low, high, i / (n - 1))) + for i in range(n) + ] + + +def plot_performance_curves( + eq: Equipment, + mode: str, + unit_mode: str = "SI", + highlight_lwt_C: float | None = None, + height: int = 500, + compare_to: Equipment | None = None, +) -> go.Figure: + """Heat pump performance curves, one line per leaving supply water temperature. + + AWHP: COP (top) and capacity (bottom) against outdoor air temperature; the part of a curve + outside its operating limits is drawn dashed and faded. HR WWHP: COP against part-load + capacity. `highlight_lwt_C` adds a dashed curve interpolated at that supply temperature, the + way the calculation interpolates between the tabulated curves. `compare_to` draws the curves + of another item (e.g. the library original of a custom copy) in grey behind. + Every trace's `meta` names its role: curve, outside, fixed, highlight or original. + """ + df = curve_table(eq, mode) + if df.empty: + return empty_figure("No performance curves for this equipment") + + to_temp = get_converter("temperature", unit_mode) + t_unit = get_display_unit("temperature", unit_mode) + cap_category = "power_cooling" if mode == "cooling" else "power" + is_awhp = df["x_kind"].iloc[0] == "t_out_C" + mode_label = "Cooling" if mode == "cooling" else "Heating" + + compare_df = curve_table(compare_to, mode) if compare_to is not None else None + if compare_df is not None and ( + compare_df.empty or compare_df["x_kind"].iloc[0] != df["x_kind"].iloc[0] + ): + compare_df = None + + fixed_capacity = None + if is_awhp and df["capacity_W"].isna().all() and eq.capacity_W: + fixed_capacity = eq.capacity_W + cap_values = df["capacity_W"].dropna().tolist() or [fixed_capacity or 0] + cap_scale, cap_unit = get_auto_scale(cap_values, cap_category, unit_mode) + + lwts = sorted(df["lwt_C"].unique()) + colors = _supply_temp_colors(len(lwts), mode) + + if is_awhp: + fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.24) + x_label = f"Outdoor air temperature [{t_unit}]" + else: + fig = go.Figure() + x_label = f"{mode_label} capacity at part load [{cap_unit}]" + + def x_display(x): + return ( + to_temp(np.asarray(x, dtype=float)) + if is_awhp + else np.asarray(x, dtype=float) / cap_scale + ) + + cop_panel = {"row": 1, "col": 1} if is_awhp else {} + cap_panel = {"row": 2, "col": 1} + + # original curves first, so they sit behind + if compare_df is not None: + for i, (_lwt, d) in enumerate(compare_df.groupby("lwt_C", sort=True)): + line = dict(color=CURVE_STYLE["original"], width=1.5, dash="dot") + common = dict( + mode="lines", + legendgroup="original", + line=line, + hoverinfo="skip", + meta="original", + ) + fig.add_trace( + go.Scatter( + x=x_display(d["x"]), + y=d["cop"], + name=f"Original ({compare_to.eq_id})", + showlegend=i == 0, + **common, + ), + **cop_panel, + ) + if is_awhp and d["capacity_W"].notna().any(): + fig.add_trace( + go.Scatter( + x=x_display(d["x"]), + y=d["capacity_W"] / cap_scale, + name=f"Original ({compare_to.eq_id})", + showlegend=False, + **common, + ), + **cap_panel, + ) + + def add_curve(x, y, in_range, name, color, panel, hover_value, show_legend): + """A curve with its in-range part solid and the part outside the limits dashed.""" + x, y, in_range = np.asarray(x), np.asarray(y, dtype=float), np.asarray(in_range) + fig.add_trace( + go.Scatter( + x=x, + y=np.where(in_range, y, np.nan), + mode="lines+markers", + name=name, + legendgroup=name, + showlegend=show_legend, + line=dict(color=color, width=2.5), + marker=dict(color=color, size=6, symbol="circle"), + hovertemplate=f"{name}: {hover_value}", + meta="curve", + ), + **panel, + ) + if in_range.all(): + return + # extend the outside part by one point so it joins the solid line + outside = ~in_range | np.convolve(~in_range, [1, 1, 1], mode="same").astype(bool) + fig.add_trace( + go.Scatter( + x=x, + y=np.where(outside, y, np.nan), + mode="lines+markers", + name=name, + legendgroup=name, + showlegend=False, + opacity=0.45, + line=dict(color=color, width=1.5, dash="dash"), + marker=dict( + color=color, size=6, symbol=np.where(in_range, "circle", "circle-open") + ), + hovertemplate=f"{name}: {hover_value} (outside operating limits)", + meta="outside", + ), + **panel, + ) + + for lwt, color in zip(lwts, colors, strict=True): + d = df[df["lwt_C"] == lwt] + name = f"{to_temp(lwt):.1f} {t_unit}" + in_range = ( + ((d["x"] >= d["oat_min_C"]) & (d["x"] <= d["oat_max_C"])) | d["oat_min_C"].isna() + if is_awhp + else pd.Series(True, index=d.index) + ) + add_curve( + x_display(d["x"]), d["cop"], in_range, name, color, cop_panel, "COP %{y:.2f}", True + ) + if is_awhp and d["capacity_W"].notna().any(): + add_curve( + x_display(d["x"]), + d["capacity_W"] / cap_scale, + in_range, + name, + color, + cap_panel, + f"%{{y:,.1f}} {cap_unit}", + False, + ) + + if is_awhp and fixed_capacity: + x_range = x_display([df["x"].min(), df["x"].max()]) + fig.add_trace( + go.Scatter( + x=x_range, + y=[fixed_capacity / cap_scale] * 2, + mode="lines", + name="Fixed capacity", + line=dict(color="#868e96", width=2), + hovertemplate=f"Fixed capacity: %{{y:,.1f}} {cap_unit}", + meta="fixed", + ), + **cap_panel, + ) + + if highlight_lwt_C is not None and len(lwts) > 0: + pivot_cop = df.pivot(index="x", columns="lwt_C", values="cop") + x_points = pivot_cop.index.to_numpy() + cop_at = [float(interp_vector(lwts, row, highlight_lwt_C)) for row in pivot_cop.to_numpy()] + name = f"Selected {to_temp(highlight_lwt_C):.1f} {t_unit}" + highlight_line = dict(color=CURVE_STYLE["highlight"], width=2, dash="dash") + fig.add_trace( + go.Scatter( + x=x_display(x_points), + y=cop_at, + mode="lines", + name=name, + legendgroup="highlight", + line=highlight_line, + hovertemplate=f"{name}: COP %{{y:.2f}}", + meta="highlight", + ), + **cop_panel, + ) + fig.add_annotation( + x=x_display(x_points)[-1], + y=cop_at[-1], + text=f"{to_temp(highlight_lwt_C):.1f} {t_unit}", + showarrow=False, + xanchor="left", + xshift=4, + font=dict(size=11, color=CURVE_STYLE["highlight"]), + **({"xref": "x", "yref": "y"} if is_awhp else {}), + ) + if is_awhp and df["capacity_W"].notna().all(): + pivot_cap = df.pivot(index="x", columns="lwt_C", values="capacity_W") + cap_at = [ + float(interp_vector(lwts, row, highlight_lwt_C)) for row in pivot_cap.to_numpy() + ] + fig.add_trace( + go.Scatter( + x=x_display(x_points), + y=np.asarray(cap_at) / cap_scale, + mode="lines", + name=name, + legendgroup="highlight", + showlegend=False, + line=highlight_line, + hovertemplate=f"{name}: %{{y:,.1f}} {cap_unit}", + meta="highlight", + ), + **cap_panel, + ) + + axis_style = dict( + showgrid=True, + gridcolor=CURVE_STYLE["grid"], + zeroline=False, + showline=True, + linecolor=CURVE_STYLE["axis"], + ticks="outside", + tickcolor=CURVE_STYLE["axis"], + ticklen=4, + mirror=False, + title_font=dict(size=12), + tickfont=dict(size=11), + ) + fig.update_xaxes( + **axis_style, + showspikes=True, + spikemode="across", + spikethickness=1, + spikecolor=CURVE_STYLE["axis"], + spikedash="dot", + ) + fig.update_yaxes(**axis_style) + # the unified hover label shows x once, as the axis value + fig.update_xaxes(hoverformat=".1f" if is_awhp else ",.1f") + + if is_awhp: + fig.update_yaxes(title_text="COP", row=1, col=1) + fig.update_yaxes( + title_text=f"{mode_label} capacity [{cap_unit}]", rangemode="tozero", row=2, col=1 + ) + # both panels are plotted against outdoor air temperature: label the x-axis under each + fig.update_xaxes(title_text=x_label, showticklabels=True, row=1, col=1) + fig.update_xaxes(title_text=x_label, row=2, col=1) + else: + fig.update_layout(xaxis_title=x_label, yaxis_title="COP") + + fig.update_layout( + template="decarb-tool-theme", + height=height, + margin=dict(t=56, b=10, l=10, r=40), + font=CURVE_STYLE["font"], + plot_bgcolor="white", + legend=dict( + title_text="Supply water temperature", + orientation="h", + x=0, + xanchor="left", + y=1.04, + yanchor="bottom", + font=dict(size=11), + title_font=dict(size=11), + ), + hovermode="x unified", + hoverlabel=dict(font_size=11), + ) + return fig diff --git a/tests/__snapshots__/test_energy_regression.ambr b/tests/__snapshots__/test_energy_regression.ambr index 8b06bc8..fa3ba89 100644 --- a/tests/__snapshots__/test_energy_regression.ambr +++ b/tests/__snapshots__/test_energy_regression.ambr @@ -151,121 +151,121 @@ # --- # name: test_scenario_output_snapshot[eq_scenario_10] ''' - timestamp,t_out_C,heating_W,cooling_W,elec_Wh,gas_Wh,hhw_W,chw_W,hr_hhw_W,hr_chw_W,hr_cop_h,max_cap_h_hr_W,min_cap_h_hr_W,simult_h_hr_W,elec_hr_Wh,hr_wwhp_refrigerant,hr_wwhp_refrigerant_weight_kg,hr_wwhp_refrigerant_gwp_kgCO2e_per_kgRefrig,awhp_num,awhp_num_redundant,awhp_cap_h_W,awhp_cop_h,awhp_hhw_W,elec_awhp_h_Wh,boiler_num,boiler_eff,boiler_hhw_W,boiler_hhw_W_ng_mode,boiler_eq_calc_type,boiler_cap_W,gas_boiler_Wh,gas_boiler_Wh_ng_mode,fuel_switching,res_hhw_W,elec_res_Wh,awhp_num_c,awhp_cap_c_W,awhp_cop_c,awhp_chw_W,elec_awhp_c_Wh,chiller_cop,chiller_chw_W,elec_chiller_Wh,chiller_refrigerant,chiller_refrigerant_weight_kg,chiller_refrigerant_gwp_kgCO2e_per_kgRefrig,eq_scen_id,eq_scen_name - 2025-01-01 00:00:00,-20.0,450000.0,0.0,0.0,562500.0,450000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,450000.0,,specific,190500.0,562500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 01:00:00,-15.0,400000.0,0.0,0.0,500000.0,400000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,400000.0,,specific,190500.0,500000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 02:00:00,-10.0,350000.0,0.0,0.0,437500.0,350000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,350000.0,,specific,190500.0,437500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 03:00:00,-5.0,300000.0,0.0,0.0,375000.0,300000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,300000.0,,specific,190500.0,375000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 04:00:00,0.0,250000.0,0.0,0.0,312500.0,250000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,250000.0,,specific,190500.0,312500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 05:00:00,4.4,206000.0,0.0,0.0,257500.0,206000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,206000.0,,specific,190500.0,257500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 06:00:00,10.0,150000.0,0.0,0.0,187500.0,150000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,150000.0,,specific,190500.0,187500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 07:00:00,15.0,100000.0,0.0,0.0,125000.0,100000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,100000.0,,specific,190500.0,125000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 08:00:00,20.0,50000.0,40000.0,12500.0,62500.0,50000.0,40000.0,0.0,0.0,4.2,211000.0,70000.0,50000.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,50000.0,,specific,190500.0,62500.0,,False,,,,,,,,3.2,40000.0,12500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 09:00:00,25.0,0.0,80000.0,25000.0,0.0,0.0,80000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,80000.0,25000.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 10:00:00,28.0,0.0,104000.0,32500.0,0.0,0.0,104000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,104000.0,32500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 11:00:00,30.0,0.0,120000.0,37500.0,0.0,0.0,120000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,120000.0,37500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 12:00:00,35.0,0.0,160000.0,50000.0,0.0,0.0,160000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,160000.0,50000.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 13:00:00,36.0,0.0,168000.0,52500.0,0.0,0.0,168000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,168000.0,52500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 14:00:00,40.0,0.0,200000.0,62500.0,0.0,0.0,200000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,200000.0,62500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 15:00:00,45.0,0.0,240000.0,75000.0,0.0,0.0,240000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,240000.0,75000.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 16:00:00,-10.0,350000.0,0.0,0.0,437500.0,350000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,350000.0,,specific,190500.0,437500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 17:00:00,-5.0,300000.0,0.0,0.0,375000.0,300000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,300000.0,,specific,190500.0,375000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 18:00:00,0.0,250000.0,0.0,0.0,312500.0,250000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,250000.0,,specific,190500.0,312500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 19:00:00,5.0,200000.0,0.0,0.0,250000.0,200000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,200000.0,,specific,190500.0,250000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 20:00:00,10.0,150000.0,0.0,0.0,187500.0,150000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,150000.0,,specific,190500.0,187500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 21:00:00,15.0,100000.0,0.0,0.0,125000.0,100000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,100000.0,,specific,190500.0,125000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 22:00:00,20.0,50000.0,40000.0,12500.0,62500.0,50000.0,40000.0,0.0,0.0,4.2,211000.0,70000.0,50000.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,50000.0,,specific,190500.0,62500.0,,False,,,,,,,,3.2,40000.0,12500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller - 2025-01-01 23:00:00,25.0,0.0,80000.0,25000.0,0.0,0.0,80000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,80000.0,25000.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + timestamp,t_out_C,heating_W,cooling_W,elec_Wh,gas_Wh,hhw_W,chw_W,hr_hhw_W,hr_chw_W,hr_cop_h,max_cap_h_hr_W,min_cap_h_hr_W,simult_h_hr_W,hr_eac_h_W,hr_eac_c_W,elec_hr_Wh,hr_wwhp_refrigerant,hr_wwhp_refrigerant_weight_kg,hr_wwhp_refrigerant_gwp_kgCO2e_per_kgRefrig,awhp_num,awhp_num_redundant,awhp_cap_h_W,awhp_cop_h,awhp_hhw_W,elec_awhp_h_Wh,boiler_num,boiler_eff,boiler_hhw_W,boiler_hhw_W_ng_mode,boiler_eq_calc_type,boiler_cap_W,gas_boiler_Wh,gas_boiler_Wh_ng_mode,fuel_switching,res_hhw_W,elec_res_Wh,awhp_num_c,awhp_cap_c_W,awhp_cop_c,awhp_chw_W,elec_awhp_c_Wh,chiller_cop,chiller_chw_W,elec_chiller_Wh,chiller_refrigerant,chiller_refrigerant_weight_kg,chiller_refrigerant_gwp_kgCO2e_per_kgRefrig,eq_scen_id,eq_scen_name + 2025-01-01 00:00:00,-20.0,450000.0,0.0,0.0,562500.0,450000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,450000.0,,specific,190500.0,562500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 01:00:00,-15.0,400000.0,0.0,0.0,500000.0,400000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,400000.0,,specific,190500.0,500000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 02:00:00,-10.0,350000.0,0.0,0.0,437500.0,350000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,350000.0,,specific,190500.0,437500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 03:00:00,-5.0,300000.0,0.0,0.0,375000.0,300000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,300000.0,,specific,190500.0,375000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 04:00:00,0.0,250000.0,0.0,0.0,312500.0,250000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,250000.0,,specific,190500.0,312500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 05:00:00,4.4,206000.0,0.0,0.0,257500.0,206000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,206000.0,,specific,190500.0,257500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 06:00:00,10.0,150000.0,0.0,0.0,187500.0,150000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,150000.0,,specific,190500.0,187500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 07:00:00,15.0,100000.0,0.0,0.0,125000.0,100000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,100000.0,,specific,190500.0,125000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 08:00:00,20.0,50000.0,40000.0,12500.0,62500.0,50000.0,40000.0,0.0,0.0,4.2,211000.0,70000.0,50000.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,50000.0,,specific,190500.0,62500.0,,False,,,,,,,,3.2,40000.0,12500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 09:00:00,25.0,0.0,80000.0,25000.0,0.0,0.0,80000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,80000.0,25000.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 10:00:00,28.0,0.0,104000.0,32500.0,0.0,0.0,104000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,104000.0,32500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 11:00:00,30.0,0.0,120000.0,37500.0,0.0,0.0,120000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,120000.0,37500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 12:00:00,35.0,0.0,160000.0,50000.0,0.0,0.0,160000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,160000.0,50000.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 13:00:00,36.0,0.0,168000.0,52500.0,0.0,0.0,168000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,168000.0,52500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 14:00:00,40.0,0.0,200000.0,62500.0,0.0,0.0,200000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,200000.0,62500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 15:00:00,45.0,0.0,240000.0,75000.0,0.0,0.0,240000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,240000.0,75000.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 16:00:00,-10.0,350000.0,0.0,0.0,437500.0,350000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,350000.0,,specific,190500.0,437500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 17:00:00,-5.0,300000.0,0.0,0.0,375000.0,300000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,300000.0,,specific,190500.0,375000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 18:00:00,0.0,250000.0,0.0,0.0,312500.0,250000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,250000.0,,specific,190500.0,312500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 19:00:00,5.0,200000.0,0.0,0.0,250000.0,200000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,200000.0,,specific,190500.0,250000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 20:00:00,10.0,150000.0,0.0,0.0,187500.0,150000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,150000.0,,specific,190500.0,187500.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 21:00:00,15.0,100000.0,0.0,0.0,125000.0,100000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,100000.0,,specific,190500.0,125000.0,,False,,,,,,,,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 22:00:00,20.0,50000.0,40000.0,12500.0,62500.0,50000.0,40000.0,0.0,0.0,4.2,211000.0,70000.0,50000.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,50000.0,,specific,190500.0,62500.0,,False,,,,,,,,3.2,40000.0,12500.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller + 2025-01-01 23:00:00,25.0,0.0,80000.0,25000.0,0.0,0.0,80000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,,,,,,,,0.8,0.0,,specific,190500.0,0.0,,False,,,,,,,,3.2,80000.0,25000.0,R-134A,11.9167,17040.8333,eq_scenario_10,HR WWHP+Gas Boiler+AC Chiller ''' # --- # name: test_scenario_output_snapshot[eq_scenario_3] ''' - timestamp,t_out_C,heating_W,cooling_W,elec_Wh,gas_Wh,hhw_W,chw_W,hr_hhw_W,hr_chw_W,hr_cop_h,elec_hr_Wh,awhp_num,awhp_num_redundant,awhp_cap_h_W,awhp_cop_h,awhp_hhw_W,elec_awhp_h_Wh,awhp_refrigerant,total_awhp_refrigerant_weight_kg,total_awhp_refrigerant_gwp_kgCO2e_per_kgRefrig,boiler_num,boiler_eff,boiler_hhw_W,boiler_hhw_W_ng_mode,boiler_eq_calc_type,boiler_cap_W,gas_boiler_Wh,gas_boiler_Wh_ng_mode,fuel_switching,res_hhw_W,elec_res_Wh,awhp_num_c,awhp_cap_c_W,awhp_cop_c,awhp_chw_W,elec_awhp_c_Wh,chiller_cop,chiller_chw_W,elec_chiller_Wh,chiller_refrigerant,chiller_refrigerant_weight_kg,chiller_refrigerant_gwp_kgCO2e_per_kgRefrig,eq_scen_id,eq_scen_name - 2025-01-01 00:00:00,-20.0,450000.0,0.0,0.0,562500.0,450000.0,0.0,,,,,1.0,2.0,0.0,2.15,0.0,0.0,R-454B,4.5,2097.0,,0.8,450000.0,,specific,190500.0,562500.0,,False,,,1.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 01:00:00,-15.0,400000.0,0.0,57488.3721,345500.0,400000.0,0.0,,,,,1.0,2.0,123600.0,2.15,123600.0,57488.3721,R-454B,4.5,2097.0,,0.8,276400.0,,specific,190500.0,345500.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 02:00:00,-10.0,350000.0,0.0,62552.4769,251250.0,350000.0,0.0,,,,,1.0,2.0,149000.0,2.382,149000.0,62552.4769,R-454B,4.5,2097.0,,0.8,201000.0,,specific,190500.0,251250.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 03:00:00,-5.0,300000.0,0.0,63118.5149,175401.7857,300000.0,0.0,,,,,1.0,2.0,159678.5714,2.5298,159678.5714,63118.5149,R-454B,4.5,2097.0,,0.8,140321.4286,,specific,190500.0,175401.7857,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 04:00:00,0.0,250000.0,0.0,63823.9538,91350.0,250000.0,0.0,,,,,1.0,2.0,176920.0,2.772,176920.0,63823.9538,R-454B,4.5,2097.0,,0.8,73080.0,,specific,190500.0,91350.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 05:00:00,4.4,206000.0,0.0,64580.6452,7250.0,206000.0,0.0,,,,,1.0,2.0,200200.0,3.1,200200.0,64580.6452,R-454B,4.5,2097.0,,0.8,5800.0,,specific,190500.0,7250.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 06:00:00,10.0,150000.0,0.0,41322.314,0.0,150000.0,0.0,,,,,1.0,2.0,235700.0,3.63,150000.0,41322.314,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 07:00:00,15.0,100000.0,0.0,25906.7358,0.0,100000.0,0.0,,,,,1.0,2.0,243100.0,3.86,100000.0,25906.7358,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.5,125000.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 08:00:00,20.0,50000.0,40000.0,21930.7574,0.0,50000.0,40000.0,,,,,1.0,2.0,257500.0,4.03,50000.0,12406.9479,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.5,117500.0,4.2,40000.0,9523.8095,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 09:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,,,,,1.0,2.0,266150.0,4.125,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,220000.0,4.0,80000.0,20000.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 10:00:00,28.0,0.0,104000.0,28176.6459,0.0,0.0,104000.0,,,,,1.0,2.0,271340.0,4.182,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,214360.0,3.691,104000.0,28176.6459,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 11:00:00,30.0,0.0,120000.0,34433.2855,0.0,0.0,120000.0,,,,,1.0,2.0,274800.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,210600.0,3.485,120000.0,34433.2855,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 12:00:00,35.0,0.0,160000.0,53872.0539,0.0,0.0,160000.0,,,,,1.0,2.0,274800.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,201200.0,2.97,160000.0,53872.0539,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 13:00:00,36.0,0.0,168000.0,57181.7563,0.0,0.0,168000.0,,,,,1.0,2.0,0.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,199380.0,2.938,168000.0,57181.7563,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 14:00:00,40.0,0.0,200000.0,70831.7393,0.0,0.0,200000.0,,,,,1.0,2.0,0.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,192100.0,2.81,192100.0,68362.9893,3.2,7900.0,2468.75,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 15:00:00,45.0,0.0,240000.0,86869.1038,0.0,0.0,240000.0,,,,,1.0,2.0,0.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,183000.0,2.65,183000.0,69056.6038,3.2,57000.0,17812.5,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 16:00:00,-10.0,350000.0,0.0,62552.4769,251250.0,350000.0,0.0,,,,,1.0,2.0,149000.0,2.382,149000.0,62552.4769,R-454B,4.5,2097.0,,0.8,201000.0,,specific,190500.0,251250.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 17:00:00,-5.0,300000.0,0.0,63118.5149,175401.7857,300000.0,0.0,,,,,1.0,2.0,159678.5714,2.5298,159678.5714,63118.5149,R-454B,4.5,2097.0,,0.8,140321.4286,,specific,190500.0,175401.7857,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 18:00:00,0.0,250000.0,0.0,63823.9538,91350.0,250000.0,0.0,,,,,1.0,2.0,176920.0,2.772,176920.0,63823.9538,R-454B,4.5,2097.0,,0.8,73080.0,,specific,190500.0,91350.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 19:00:00,5.0,200000.0,0.0,63355.5832,0.0,200000.0,0.0,,,,,1.0,2.0,204003.5714,3.1568,200000.0,63355.5832,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 20:00:00,10.0,150000.0,0.0,41322.314,0.0,150000.0,0.0,,,,,1.0,2.0,235700.0,3.63,150000.0,41322.314,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 21:00:00,15.0,100000.0,0.0,25906.7358,0.0,100000.0,0.0,,,,,1.0,2.0,243100.0,3.86,100000.0,25906.7358,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.5,125000.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 22:00:00,20.0,50000.0,40000.0,21930.7574,0.0,50000.0,40000.0,,,,,1.0,2.0,257500.0,4.03,50000.0,12406.9479,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.5,117500.0,4.2,40000.0,9523.8095,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup - 2025-01-01 23:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,,,,,1.0,2.0,266150.0,4.125,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,220000.0,4.0,80000.0,20000.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + timestamp,t_out_C,heating_W,cooling_W,elec_Wh,gas_Wh,hhw_W,chw_W,hr_hhw_W,hr_chw_W,hr_cop_h,hr_eac_h_W,hr_eac_c_W,elec_hr_Wh,awhp_num,awhp_num_redundant,awhp_cap_h_W,awhp_cop_h,awhp_hhw_W,elec_awhp_h_Wh,awhp_refrigerant,total_awhp_refrigerant_weight_kg,total_awhp_refrigerant_gwp_kgCO2e_per_kgRefrig,boiler_num,boiler_eff,boiler_hhw_W,boiler_hhw_W_ng_mode,boiler_eq_calc_type,boiler_cap_W,gas_boiler_Wh,gas_boiler_Wh_ng_mode,fuel_switching,res_hhw_W,elec_res_Wh,awhp_num_c,awhp_cap_c_W,awhp_cop_c,awhp_chw_W,elec_awhp_c_Wh,chiller_cop,chiller_chw_W,elec_chiller_Wh,chiller_refrigerant,chiller_refrigerant_weight_kg,chiller_refrigerant_gwp_kgCO2e_per_kgRefrig,eq_scen_id,eq_scen_name + 2025-01-01 00:00:00,-20.0,450000.0,0.0,0.0,562500.0,450000.0,0.0,,,,,,,1.0,2.0,0.0,2.15,0.0,0.0,R-454B,4.5,2097.0,,0.8,450000.0,,specific,190500.0,562500.0,,False,,,1.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 01:00:00,-15.0,400000.0,0.0,57488.3721,345500.0,400000.0,0.0,,,,,,,1.0,2.0,123600.0,2.15,123600.0,57488.3721,R-454B,4.5,2097.0,,0.8,276400.0,,specific,190500.0,345500.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 02:00:00,-10.0,350000.0,0.0,62552.4769,251250.0,350000.0,0.0,,,,,,,1.0,2.0,149000.0,2.382,149000.0,62552.4769,R-454B,4.5,2097.0,,0.8,201000.0,,specific,190500.0,251250.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 03:00:00,-5.0,300000.0,0.0,63118.5149,175401.7857,300000.0,0.0,,,,,,,1.0,2.0,159678.5714,2.5298,159678.5714,63118.5149,R-454B,4.5,2097.0,,0.8,140321.4286,,specific,190500.0,175401.7857,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 04:00:00,0.0,250000.0,0.0,63823.9538,91350.0,250000.0,0.0,,,,,,,1.0,2.0,176920.0,2.772,176920.0,63823.9538,R-454B,4.5,2097.0,,0.8,73080.0,,specific,190500.0,91350.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 05:00:00,4.4,206000.0,0.0,64580.6452,7250.0,206000.0,0.0,,,,,,,1.0,2.0,200200.0,3.1,200200.0,64580.6452,R-454B,4.5,2097.0,,0.8,5800.0,,specific,190500.0,7250.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 06:00:00,10.0,150000.0,0.0,41322.314,0.0,150000.0,0.0,,,,,,,1.0,2.0,235700.0,3.63,150000.0,41322.314,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 07:00:00,15.0,100000.0,0.0,25906.7358,0.0,100000.0,0.0,,,,,,,1.0,2.0,243100.0,3.86,100000.0,25906.7358,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.5,125000.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 08:00:00,20.0,50000.0,40000.0,21930.7574,0.0,50000.0,40000.0,,,,,,,1.0,2.0,257500.0,4.03,50000.0,12406.9479,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.5,117500.0,4.2,40000.0,9523.8095,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 09:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,,,,,,,1.0,2.0,266150.0,4.125,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,220000.0,4.0,80000.0,20000.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 10:00:00,28.0,0.0,104000.0,28176.6459,0.0,0.0,104000.0,,,,,,,1.0,2.0,271340.0,4.182,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,214360.0,3.691,104000.0,28176.6459,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 11:00:00,30.0,0.0,120000.0,34433.2855,0.0,0.0,120000.0,,,,,,,1.0,2.0,274800.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,210600.0,3.485,120000.0,34433.2855,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 12:00:00,35.0,0.0,160000.0,53872.0539,0.0,0.0,160000.0,,,,,,,1.0,2.0,274800.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,201200.0,2.97,160000.0,53872.0539,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 13:00:00,36.0,0.0,168000.0,57181.7563,0.0,0.0,168000.0,,,,,,,1.0,2.0,0.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,199380.0,2.938,168000.0,57181.7563,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 14:00:00,40.0,0.0,200000.0,70831.7393,0.0,0.0,200000.0,,,,,,,1.0,2.0,0.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,192100.0,2.81,192100.0,68362.9893,3.2,7900.0,2468.75,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 15:00:00,45.0,0.0,240000.0,86869.1038,0.0,0.0,240000.0,,,,,,,1.0,2.0,0.0,4.22,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,183000.0,2.65,183000.0,69056.6038,3.2,57000.0,17812.5,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 16:00:00,-10.0,350000.0,0.0,62552.4769,251250.0,350000.0,0.0,,,,,,,1.0,2.0,149000.0,2.382,149000.0,62552.4769,R-454B,4.5,2097.0,,0.8,201000.0,,specific,190500.0,251250.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 17:00:00,-5.0,300000.0,0.0,63118.5149,175401.7857,300000.0,0.0,,,,,,,1.0,2.0,159678.5714,2.5298,159678.5714,63118.5149,R-454B,4.5,2097.0,,0.8,140321.4286,,specific,190500.0,175401.7857,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 18:00:00,0.0,250000.0,0.0,63823.9538,91350.0,250000.0,0.0,,,,,,,1.0,2.0,176920.0,2.772,176920.0,63823.9538,R-454B,4.5,2097.0,,0.8,73080.0,,specific,190500.0,91350.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 19:00:00,5.0,200000.0,0.0,63355.5832,0.0,200000.0,0.0,,,,,,,1.0,2.0,204003.5714,3.1568,200000.0,63355.5832,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 20:00:00,10.0,150000.0,0.0,41322.314,0.0,150000.0,0.0,,,,,,,1.0,2.0,235700.0,3.63,150000.0,41322.314,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.0,0.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 21:00:00,15.0,100000.0,0.0,25906.7358,0.0,100000.0,0.0,,,,,,,1.0,2.0,243100.0,3.86,100000.0,25906.7358,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.5,125000.0,4.4,0.0,0.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 22:00:00,20.0,50000.0,40000.0,21930.7574,0.0,50000.0,40000.0,,,,,,,1.0,2.0,257500.0,4.03,50000.0,12406.9479,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,0.5,117500.0,4.2,40000.0,9523.8095,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup + 2025-01-01 23:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,,,,,,,1.0,2.0,266150.0,4.125,0.0,0.0,R-454B,4.5,2097.0,,0.8,0.0,,specific,190500.0,0.0,,False,,,1.0,220000.0,4.0,80000.0,20000.0,3.2,0.0,0.0,R-134A,11.9167,17040.8333,eq_scenario_3,20% AWHP (H+C)+Gas Backup ''' # --- # name: test_scenario_output_snapshot[eq_scenario_4] ''' - timestamp,t_out_C,heating_W,cooling_W,elec_Wh,gas_Wh,hhw_W,chw_W,hr_hhw_W,hr_chw_W,hr_cop_h,elec_hr_Wh,awhp_num,awhp_num_redundant,awhp_cap_h_W,awhp_cop_h,awhp_hhw_W,elec_awhp_h_Wh,awhp_refrigerant,total_awhp_refrigerant_weight_kg,total_awhp_refrigerant_gwp_kgCO2e_per_kgRefrig,boiler_num,boiler_eff,boiler_hhw_W,boiler_hhw_W_ng_mode,boiler_eq_calc_type,boiler_cap_W,gas_boiler_Wh,gas_boiler_Wh_ng_mode,fuel_switching,res_hhw_W,elec_res_Wh,awhp_num_c,awhp_cap_c_W,awhp_cop_c,awhp_chw_W,elec_awhp_c_Wh,chiller_cop,chiller_chw_W,elec_chiller_Wh,eq_scen_id,eq_scen_name - 2025-01-01 00:00:00,-20.0,450000.0,0.0,450000.0,0.0,450000.0,0.0,,,,,3.0,4.0,0.0,2.15,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,450000.0,450000.0,3.0,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 01:00:00,-15.0,400000.0,0.0,201665.11627906977,0.0,400000.0,0.0,,,,,3.0,4.0,370800.0,2.15,370800.0,172465.11627906977,R-454B,9.0,4194.0,,,,,,,,,False,29200.0,29200.0,0.0,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 02:00:00,-10.0,350000.0,0.0,146935.34844668346,0.0,350000.0,0.0,,,,,3.0,4.0,447000.0,2.382,350000.0,146935.34844668346,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,0.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 03:00:00,-5.0,300000.0,0.0,118585.4450483518,0.0,300000.0,0.0,,,,,3.0,4.0,479035.71428571426,2.5298214285714287,300000.0,118585.4450483518,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.0,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 04:00:00,0.0,250000.0,0.0,90187.59018759019,0.0,250000.0,0.0,,,,,3.0,4.0,530760.0,2.772,250000.0,90187.59018759019,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 05:00:00,4.4,206000.0,0.0,66451.6129032258,0.0,206000.0,0.0,,,,,3.0,4.0,600600.0,3.1,206000.0,66451.6129032258,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 06:00:00,10.0,150000.0,0.0,41322.31404958678,0.0,150000.0,0.0,,,,,3.0,4.0,707100.0,3.63,150000.0,41322.31404958678,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 07:00:00,15.0,100000.0,0.0,25906.73575129534,0.0,100000.0,0.0,,,,,3.0,4.0,729300.0,3.86,100000.0,25906.73575129534,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,625000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 08:00:00,20.0,50000.0,40000.0,21930.75741462838,0.0,50000.0,40000.0,,,,,3.0,4.0,772500.0,4.03,50000.0,12406.947890818858,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,587500.0,4.2,40000.0,9523.809523809523,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 09:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,,,,,3.0,4.0,798450.0,4.125,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,660000.0,4.0,80000.0,20000.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 10:00:00,28.0,0.0,104000.0,28176.645895421298,0.0,0.0,104000.0,,,,,3.0,4.0,814020.0,4.1819999999999995,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,643080.0,3.691,104000.0,28176.645895421298,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 11:00:00,30.0,0.0,120000.0,34433.28550932568,0.0,0.0,120000.0,,,,,3.0,4.0,824400.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,631800.0,3.4850000000000003,120000.0,34433.28550932568,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 12:00:00,35.0,0.0,160000.0,53872.05387205387,0.0,0.0,160000.0,,,,,3.0,4.0,824400.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,603600.0,2.97,160000.0,53872.05387205387,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 13:00:00,36.0,0.0,168000.0,57181.756296800544,0.0,0.0,168000.0,,,,,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,598140.0,2.938,168000.0,57181.756296800544,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 14:00:00,40.0,0.0,200000.0,71174.37722419928,0.0,0.0,200000.0,,,,,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,576300.0,2.81,200000.0,71174.37722419928,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 15:00:00,45.0,0.0,240000.0,90566.03773584907,0.0,0.0,240000.0,,,,,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,549000.0,2.65,240000.0,90566.03773584907,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 16:00:00,-10.0,350000.0,0.0,146935.34844668346,0.0,350000.0,0.0,,,,,3.0,4.0,447000.0,2.382,350000.0,146935.34844668346,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,0.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 17:00:00,-5.0,300000.0,0.0,118585.4450483518,0.0,300000.0,0.0,,,,,3.0,4.0,479035.71428571426,2.5298214285714287,300000.0,118585.4450483518,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.0,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 18:00:00,0.0,250000.0,0.0,90187.59018759019,0.0,250000.0,0.0,,,,,3.0,4.0,530760.0,2.772,250000.0,90187.59018759019,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 19:00:00,5.0,200000.0,0.0,63355.58321077045,0.0,200000.0,0.0,,,,,3.0,4.0,612010.7142857143,3.1567857142857143,200000.0,63355.58321077045,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 20:00:00,10.0,150000.0,0.0,41322.31404958678,0.0,150000.0,0.0,,,,,3.0,4.0,707100.0,3.63,150000.0,41322.31404958678,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 21:00:00,15.0,100000.0,0.0,25906.73575129534,0.0,100000.0,0.0,,,,,3.0,4.0,729300.0,3.86,100000.0,25906.73575129534,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,625000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 22:00:00,20.0,50000.0,40000.0,21930.75741462838,0.0,50000.0,40000.0,,,,,3.0,4.0,772500.0,4.03,50000.0,12406.947890818858,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,587500.0,4.2,40000.0,9523.809523809523,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup - 2025-01-01 23:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,,,,,3.0,4.0,798450.0,4.125,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,660000.0,4.0,80000.0,20000.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + timestamp,t_out_C,heating_W,cooling_W,elec_Wh,gas_Wh,hhw_W,chw_W,hr_hhw_W,hr_chw_W,hr_cop_h,hr_eac_h_W,hr_eac_c_W,elec_hr_Wh,awhp_num,awhp_num_redundant,awhp_cap_h_W,awhp_cop_h,awhp_hhw_W,elec_awhp_h_Wh,awhp_refrigerant,total_awhp_refrigerant_weight_kg,total_awhp_refrigerant_gwp_kgCO2e_per_kgRefrig,boiler_num,boiler_eff,boiler_hhw_W,boiler_hhw_W_ng_mode,boiler_eq_calc_type,boiler_cap_W,gas_boiler_Wh,gas_boiler_Wh_ng_mode,fuel_switching,res_hhw_W,elec_res_Wh,awhp_num_c,awhp_cap_c_W,awhp_cop_c,awhp_chw_W,elec_awhp_c_Wh,chiller_cop,chiller_chw_W,elec_chiller_Wh,eq_scen_id,eq_scen_name + 2025-01-01 00:00:00,-20.0,450000.0,0.0,450000.0,0.0,450000.0,0.0,,,,,,,3.0,4.0,0.0,2.15,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,450000.0,450000.0,3.0,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 01:00:00,-15.0,400000.0,0.0,201665.11627906977,0.0,400000.0,0.0,,,,,,,3.0,4.0,370800.0,2.15,370800.0,172465.11627906977,R-454B,9.0,4194.0,,,,,,,,,False,29200.0,29200.0,0.0,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 02:00:00,-10.0,350000.0,0.0,146935.34844668346,0.0,350000.0,0.0,,,,,,,3.0,4.0,447000.0,2.382,350000.0,146935.34844668346,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,0.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 03:00:00,-5.0,300000.0,0.0,118585.4450483518,0.0,300000.0,0.0,,,,,,,3.0,4.0,479035.71428571426,2.5298214285714287,300000.0,118585.4450483518,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.0,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 04:00:00,0.0,250000.0,0.0,90187.59018759019,0.0,250000.0,0.0,,,,,,,3.0,4.0,530760.0,2.772,250000.0,90187.59018759019,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 05:00:00,4.4,206000.0,0.0,66451.6129032258,0.0,206000.0,0.0,,,,,,,3.0,4.0,600600.0,3.1,206000.0,66451.6129032258,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 06:00:00,10.0,150000.0,0.0,41322.31404958678,0.0,150000.0,0.0,,,,,,,3.0,4.0,707100.0,3.63,150000.0,41322.31404958678,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 07:00:00,15.0,100000.0,0.0,25906.73575129534,0.0,100000.0,0.0,,,,,,,3.0,4.0,729300.0,3.86,100000.0,25906.73575129534,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,625000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 08:00:00,20.0,50000.0,40000.0,21930.75741462838,0.0,50000.0,40000.0,,,,,,,3.0,4.0,772500.0,4.03,50000.0,12406.947890818858,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,587500.0,4.2,40000.0,9523.809523809523,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 09:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,,,,,,,3.0,4.0,798450.0,4.125,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,660000.0,4.0,80000.0,20000.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 10:00:00,28.0,0.0,104000.0,28176.645895421298,0.0,0.0,104000.0,,,,,,,3.0,4.0,814020.0,4.1819999999999995,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,643080.0,3.691,104000.0,28176.645895421298,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 11:00:00,30.0,0.0,120000.0,34433.28550932568,0.0,0.0,120000.0,,,,,,,3.0,4.0,824400.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,631800.0,3.4850000000000003,120000.0,34433.28550932568,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 12:00:00,35.0,0.0,160000.0,53872.05387205387,0.0,0.0,160000.0,,,,,,,3.0,4.0,824400.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,603600.0,2.97,160000.0,53872.05387205387,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 13:00:00,36.0,0.0,168000.0,57181.756296800544,0.0,0.0,168000.0,,,,,,,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,598140.0,2.938,168000.0,57181.756296800544,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 14:00:00,40.0,0.0,200000.0,71174.37722419928,0.0,0.0,200000.0,,,,,,,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,576300.0,2.81,200000.0,71174.37722419928,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 15:00:00,45.0,0.0,240000.0,90566.03773584907,0.0,0.0,240000.0,,,,,,,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,549000.0,2.65,240000.0,90566.03773584907,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 16:00:00,-10.0,350000.0,0.0,146935.34844668346,0.0,350000.0,0.0,,,,,,,3.0,4.0,447000.0,2.382,350000.0,146935.34844668346,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,0.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 17:00:00,-5.0,300000.0,0.0,118585.4450483518,0.0,300000.0,0.0,,,,,,,3.0,4.0,479035.71428571426,2.5298214285714287,300000.0,118585.4450483518,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.0,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 18:00:00,0.0,250000.0,0.0,90187.59018759019,0.0,250000.0,0.0,,,,,,,3.0,4.0,530760.0,2.772,250000.0,90187.59018759019,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 19:00:00,5.0,200000.0,0.0,63355.58321077045,0.0,200000.0,0.0,,,,,,,3.0,4.0,612010.7142857143,3.1567857142857143,200000.0,63355.58321077045,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 20:00:00,10.0,150000.0,0.0,41322.31404958678,0.0,150000.0,0.0,,,,,,,3.0,4.0,707100.0,3.63,150000.0,41322.31404958678,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 21:00:00,15.0,100000.0,0.0,25906.73575129534,0.0,100000.0,0.0,,,,,,,3.0,4.0,729300.0,3.86,100000.0,25906.73575129534,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,625000.0,4.4,0.0,0.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 22:00:00,20.0,50000.0,40000.0,21930.75741462838,0.0,50000.0,40000.0,,,,,,,3.0,4.0,772500.0,4.03,50000.0,12406.947890818858,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,587500.0,4.2,40000.0,9523.809523809523,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup + 2025-01-01 23:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,,,,,,,3.0,4.0,798450.0,4.125,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,660000.0,4.0,80000.0,20000.0,,,,eq_scenario_4,100% AWHP (H+C)+Elec Backup ''' # --- # name: test_scenario_output_snapshot[eq_scenario_5] ''' - timestamp,t_out_C,heating_W,cooling_W,elec_Wh,gas_Wh,hhw_W,chw_W,hr_hhw_W,hr_chw_W,hr_cop_h,max_cap_h_hr_W,min_cap_h_hr_W,simult_h_hr_W,elec_hr_Wh,hr_wwhp_refrigerant,hr_wwhp_refrigerant_weight_kg,hr_wwhp_refrigerant_gwp_kgCO2e_per_kgRefrig,awhp_num,awhp_num_redundant,awhp_cap_h_W,awhp_cop_h,awhp_hhw_W,elec_awhp_h_Wh,awhp_refrigerant,total_awhp_refrigerant_weight_kg,total_awhp_refrigerant_gwp_kgCO2e_per_kgRefrig,boiler_num,boiler_eff,boiler_hhw_W,boiler_hhw_W_ng_mode,boiler_eq_calc_type,boiler_cap_W,gas_boiler_Wh,gas_boiler_Wh_ng_mode,fuel_switching,res_hhw_W,elec_res_Wh,awhp_num_c,awhp_cap_c_W,awhp_cop_c,awhp_chw_W,elec_awhp_c_Wh,chiller_cop,chiller_chw_W,elec_chiller_Wh,eq_scen_id,eq_scen_name - 2025-01-01 00:00:00,-20.0,450000.0,0.0,450000.0,0.0,450000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,0.0,2.15,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,450000.0,450000.0,3.0,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 01:00:00,-15.0,400000.0,0.0,201665.11627906977,0.0,400000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,370800.0,2.15,370800.0,172465.11627906977,R-454B,9.0,4194.0,,,,,,,,,False,29200.0,29200.0,0.0,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 02:00:00,-10.0,350000.0,0.0,146935.34844668346,0.0,350000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,447000.0,2.382,350000.0,146935.34844668346,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,0.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 03:00:00,-5.0,300000.0,0.0,118585.4450483518,0.0,300000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,479035.71428571426,2.5298214285714287,300000.0,118585.4450483518,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.0,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 04:00:00,0.0,250000.0,0.0,90187.59018759019,0.0,250000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,530760.0,2.772,250000.0,90187.59018759019,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 05:00:00,4.4,206000.0,0.0,66451.6129032258,0.0,206000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,600600.0,3.1,206000.0,66451.6129032258,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 06:00:00,10.0,150000.0,0.0,41322.31404958678,0.0,150000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,707100.0,3.63,150000.0,41322.31404958678,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 07:00:00,15.0,100000.0,0.0,25906.73575129534,0.0,100000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,729300.0,3.86,100000.0,25906.73575129534,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,625000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 08:00:00,20.0,50000.0,40000.0,21930.75741462838,0.0,50000.0,40000.0,0.0,0.0,4.2,211000.0,70000.0,50000.0,0.0,R-454B,1.875,873.75,3.0,4.0,772500.0,4.03,50000.0,12406.947890818858,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,587500.0,4.2,40000.0,9523.809523809523,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 09:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,798450.0,4.125,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,660000.0,4.0,80000.0,20000.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 10:00:00,28.0,0.0,104000.0,28176.645895421298,0.0,0.0,104000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,814020.0,4.1819999999999995,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,643080.0,3.691,104000.0,28176.645895421298,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 11:00:00,30.0,0.0,120000.0,34433.28550932568,0.0,0.0,120000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,824400.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,631800.0,3.4850000000000003,120000.0,34433.28550932568,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 12:00:00,35.0,0.0,160000.0,53872.05387205387,0.0,0.0,160000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,824400.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,603600.0,2.97,160000.0,53872.05387205387,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 13:00:00,36.0,0.0,168000.0,57181.756296800544,0.0,0.0,168000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,598140.0,2.938,168000.0,57181.756296800544,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 14:00:00,40.0,0.0,200000.0,71174.37722419928,0.0,0.0,200000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,576300.0,2.81,200000.0,71174.37722419928,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 15:00:00,45.0,0.0,240000.0,90566.03773584907,0.0,0.0,240000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,549000.0,2.65,240000.0,90566.03773584907,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 16:00:00,-10.0,350000.0,0.0,146935.34844668346,0.0,350000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,447000.0,2.382,350000.0,146935.34844668346,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,0.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 17:00:00,-5.0,300000.0,0.0,118585.4450483518,0.0,300000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,479035.71428571426,2.5298214285714287,300000.0,118585.4450483518,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.0,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 18:00:00,0.0,250000.0,0.0,90187.59018759019,0.0,250000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,530760.0,2.772,250000.0,90187.59018759019,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 19:00:00,5.0,200000.0,0.0,63355.58321077045,0.0,200000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,612010.7142857143,3.1567857142857143,200000.0,63355.58321077045,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 20:00:00,10.0,150000.0,0.0,41322.31404958678,0.0,150000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,707100.0,3.63,150000.0,41322.31404958678,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 21:00:00,15.0,100000.0,0.0,25906.73575129534,0.0,100000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,729300.0,3.86,100000.0,25906.73575129534,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,625000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 22:00:00,20.0,50000.0,40000.0,21930.75741462838,0.0,50000.0,40000.0,0.0,0.0,4.2,211000.0,70000.0,50000.0,0.0,R-454B,1.875,873.75,3.0,4.0,772500.0,4.03,50000.0,12406.947890818858,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,587500.0,4.2,40000.0,9523.809523809523,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup - 2025-01-01 23:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,798450.0,4.125,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,660000.0,4.0,80000.0,20000.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + timestamp,t_out_C,heating_W,cooling_W,elec_Wh,gas_Wh,hhw_W,chw_W,hr_hhw_W,hr_chw_W,hr_cop_h,max_cap_h_hr_W,min_cap_h_hr_W,simult_h_hr_W,hr_eac_h_W,hr_eac_c_W,elec_hr_Wh,hr_wwhp_refrigerant,hr_wwhp_refrigerant_weight_kg,hr_wwhp_refrigerant_gwp_kgCO2e_per_kgRefrig,awhp_num,awhp_num_redundant,awhp_cap_h_W,awhp_cop_h,awhp_hhw_W,elec_awhp_h_Wh,awhp_refrigerant,total_awhp_refrigerant_weight_kg,total_awhp_refrigerant_gwp_kgCO2e_per_kgRefrig,boiler_num,boiler_eff,boiler_hhw_W,boiler_hhw_W_ng_mode,boiler_eq_calc_type,boiler_cap_W,gas_boiler_Wh,gas_boiler_Wh_ng_mode,fuel_switching,res_hhw_W,elec_res_Wh,awhp_num_c,awhp_cap_c_W,awhp_cop_c,awhp_chw_W,elec_awhp_c_Wh,chiller_cop,chiller_chw_W,elec_chiller_Wh,eq_scen_id,eq_scen_name + 2025-01-01 00:00:00,-20.0,450000.0,0.0,450000.0,0.0,450000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,0.0,2.15,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,450000.0,450000.0,3.0,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 01:00:00,-15.0,400000.0,0.0,201665.11627906977,0.0,400000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,370800.0,2.15,370800.0,172465.11627906977,R-454B,9.0,4194.0,,,,,,,,,False,29200.0,29200.0,0.0,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 02:00:00,-10.0,350000.0,0.0,146935.34844668346,0.0,350000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,447000.0,2.382,350000.0,146935.34844668346,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,0.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 03:00:00,-5.0,300000.0,0.0,118585.4450483518,0.0,300000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,479035.71428571426,2.5298214285714287,300000.0,118585.4450483518,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.0,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 04:00:00,0.0,250000.0,0.0,90187.59018759019,0.0,250000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,530760.0,2.772,250000.0,90187.59018759019,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 05:00:00,4.4,206000.0,0.0,66451.6129032258,0.0,206000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,600600.0,3.1,206000.0,66451.6129032258,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 06:00:00,10.0,150000.0,0.0,41322.31404958678,0.0,150000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,707100.0,3.63,150000.0,41322.31404958678,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 07:00:00,15.0,100000.0,0.0,25906.73575129534,0.0,100000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,729300.0,3.86,100000.0,25906.73575129534,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,625000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 08:00:00,20.0,50000.0,40000.0,21930.75741462838,0.0,50000.0,40000.0,0.0,0.0,4.2,211000.0,70000.0,50000.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,772500.0,4.03,50000.0,12406.947890818858,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,587500.0,4.2,40000.0,9523.809523809523,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 09:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,798450.0,4.125,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,660000.0,4.0,80000.0,20000.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 10:00:00,28.0,0.0,104000.0,28176.645895421298,0.0,0.0,104000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,814020.0,4.1819999999999995,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,643080.0,3.691,104000.0,28176.645895421298,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 11:00:00,30.0,0.0,120000.0,34433.28550932568,0.0,0.0,120000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,824400.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,631800.0,3.4850000000000003,120000.0,34433.28550932568,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 12:00:00,35.0,0.0,160000.0,53872.05387205387,0.0,0.0,160000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,824400.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,603600.0,2.97,160000.0,53872.05387205387,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 13:00:00,36.0,0.0,168000.0,57181.756296800544,0.0,0.0,168000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,598140.0,2.938,168000.0,57181.756296800544,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 14:00:00,40.0,0.0,200000.0,71174.37722419928,0.0,0.0,200000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,576300.0,2.81,200000.0,71174.37722419928,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 15:00:00,45.0,0.0,240000.0,90566.03773584907,0.0,0.0,240000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,0.0,4.22,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,549000.0,2.65,240000.0,90566.03773584907,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 16:00:00,-10.0,350000.0,0.0,146935.34844668346,0.0,350000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,447000.0,2.382,350000.0,146935.34844668346,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,0.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 17:00:00,-5.0,300000.0,0.0,118585.4450483518,0.0,300000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,479035.71428571426,2.5298214285714287,300000.0,118585.4450483518,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.0,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 18:00:00,0.0,250000.0,0.0,90187.59018759019,0.0,250000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,530760.0,2.772,250000.0,90187.59018759019,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,1.5,0.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 19:00:00,5.0,200000.0,0.0,63355.58321077045,0.0,200000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,612010.7142857143,3.1567857142857143,200000.0,63355.58321077045,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 20:00:00,10.0,150000.0,0.0,41322.31404958678,0.0,150000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,707100.0,3.63,150000.0,41322.31404958678,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.0,500000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 21:00:00,15.0,100000.0,0.0,25906.73575129534,0.0,100000.0,0.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,729300.0,3.86,100000.0,25906.73575129534,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,625000.0,4.4,0.0,0.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 22:00:00,20.0,50000.0,40000.0,21930.75741462838,0.0,50000.0,40000.0,0.0,0.0,4.2,211000.0,70000.0,50000.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,772500.0,4.03,50000.0,12406.947890818858,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,2.5,587500.0,4.2,40000.0,9523.809523809523,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup + 2025-01-01 23:00:00,25.0,0.0,80000.0,20000.0,0.0,0.0,80000.0,0.0,0.0,4.2,211000.0,70000.0,0.0,0.0,0.0,0.0,R-454B,1.875,873.75,3.0,4.0,798450.0,4.125,0.0,0.0,R-454B,9.0,4194.0,,,,,,,,,False,0.0,0.0,3.0,660000.0,4.0,80000.0,20000.0,,,,eq_scenario_5,HR WWHP+100% AWHP (H+C)+Elec Backup ''' # --- diff --git a/tests/app_helpers.py b/tests/app_helpers.py index f44626a..1e49ebf 100644 --- a/tests/app_helpers.py +++ b/tests/app_helpers.py @@ -70,3 +70,28 @@ def callback_component_ids(dependencies: list[dict]) -> set[str]: def figure_has_data(fig) -> bool: fig = json.loads(fig.to_json()) if hasattr(fig, "to_json") else fig return any(trace for trace in fig.get("data", [])) + + +def _contains_component(value) -> bool: + if isinstance(value, Component): + return True + if isinstance(value, dict): + return any(_contains_component(v) for v in value.values()) + if isinstance(value, list | tuple): + return any(_contains_component(v) for v in value) + return False + + +def components_in_dict_props(layout) -> list[str]: + """Components nested inside dict-valued props (e.g. dmc.Table `data`). + + Dash only renders components placed directly in node props; inside a dict they reach + React as plain objects and the page fails with "Objects are not valid as a React child". + """ + found = [] + for comp in walk(layout): + for prop in comp._prop_names: + value = getattr(comp, prop, None) + if isinstance(value, dict) and _contains_component(value): + found.append(f"{type(comp).__name__}(id={getattr(comp, 'id', None)!r}).{prop}") + return found diff --git a/tests/fixtures/spreadsheet_cases.json b/tests/fixtures/spreadsheet_cases.json index 38f39fa..c249ea2 100644 --- a/tests/fixtures/spreadsheet_cases.json +++ b/tests/fixtures/spreadsheet_cases.json @@ -727,6 +727,10 @@ "hr_wwhp": "hr03", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 48.9, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "max_heat_recovery", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_h_supply_t": 38, @@ -1098,6 +1102,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": null, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "max_heat_recovery", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_reset", "awhp_h_supply_t": 38, @@ -1415,6 +1423,10 @@ "hr_wwhp": "hr03", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 52, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "max_heat_recovery", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_h_supply_t": 42, @@ -1789,6 +1801,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": null, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "max_heat_recovery", "awhp": null, "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_h_supply_t": null, @@ -1935,6 +1951,10 @@ "hr_wwhp": "hr03", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 60, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "max_heat_recovery", "awhp": "hp06", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_h_supply_t": 60, @@ -2225,6 +2245,10 @@ "hr_wwhp": "hr01", "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": 40, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "max_heat_recovery", "awhp": "hp01", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_h_supply_t": 38, @@ -2596,6 +2620,10 @@ "hr_wwhp": null, "hr_wwhp_performance_model": "interpolate_HHWST", "hr_wwhp_h_supply_t": null, + "hr_eac_rejection_cap_W": 0, + "hr_eac_recovery_cap_W": 0, + "hr_eac_rejection_control": "min_turndown", + "hr_eac_recovery_control": "max_heat_recovery", "awhp": "hp04", "awhp_performance_model": "interpolate_HHWST_fixed", "awhp_h_supply_t": 45, diff --git a/tests/test_analytics.py b/tests/test_analytics.py new file mode 100644 index 0000000..509c7ea --- /dev/null +++ b/tests/test_analytics.py @@ -0,0 +1,44 @@ +"""Tests for the analytics snippets injected into the Dash index string.""" + +import pytest +from dash import Dash + +from utils.analytics import SITEIMPROVE_SRC, add_analytics + +pytestmark = pytest.mark.unit + +DASH_PLACEHOLDERS = [ + "{%metas%}", + "{%title%}", + "{%favicon%}", + "{%css%}", + "{%app_entry%}", + "{%config%}", + "{%scripts%}", + "{%renderer%}", +] + + +@pytest.fixture(scope="module") +def default_index(): + return Dash(__name__).index_string + + +def test_enabled_with_id_adds_gtag_and_siteimprove(default_index): + html = add_analytics(default_index, enabled=True, ga_id="G-TEST123") + head = html.split("")[0] + assert "googletagmanager.com/gtag/js?id=G-TEST123" in head + assert "gtag('config', 'G-TEST123')" in head + assert SITEIMPROVE_SRC in head + for placeholder in DASH_PLACEHOLDERS: + assert placeholder in html + + +def test_enabled_without_id_adds_only_siteimprove(default_index): + html = add_analytics(default_index, enabled=True, ga_id="") + assert "gtag" not in html + assert SITEIMPROVE_SRC in html + + +def test_disabled_leaves_index_unchanged(default_index): + assert add_analytics(default_index, enabled=False, ga_id="G-TEST123") == default_index diff --git a/tests/test_app_smoke.py b/tests/test_app_smoke.py index fce66b8..0e0051b 100644 --- a/tests/test_app_smoke.py +++ b/tests/test_app_smoke.py @@ -12,7 +12,13 @@ import plotly import pytest -from tests.app_helpers import callback_component_ids, component_ids, ids_declared_in_source +from tests.app_helpers import ( + callback_component_ids, + component_ids, + components_in_dict_props, + ids_declared_in_source, + walk, +) pytestmark = pytest.mark.app @@ -85,3 +91,111 @@ def test_no_output_written_by_two_callbacks_without_allow_duplicate(dependencies continue assert output not in seen, f"{output} written by two callbacks" seen[output] = dep + + +def test_equipment_manager_is_not_a_numbered_workflow_step(app): + from layout.shell import build_navbar_content + from src.config import URLS + + navbar = list(walk(build_navbar_content())) + step_paths = { + c.id["path"] + for c in navbar + if isinstance(getattr(c, "id", None), dict) and c.id.get("type") == "navbar-link" + } + assert "/equipment" in step_paths + assert URLS.EQUIPMENT_MANAGER.value not in step_paths + assert URLS.EQUIPMENT_MANAGER.value in {getattr(c, "href", None) for c in navbar} + + +def test_page_layouts_have_no_components_inside_dict_props(app): + for page in dash.page_registry.values(): + layout = page["layout"]() if callable(page["layout"]) else page["layout"] + assert components_in_dict_props(layout) == [], page["path"] + + +@pytest.mark.parametrize("eq_id", ["hr01", "hp01", "hp02", "bo01", "ch02"]) +@pytest.mark.parametrize("unit_mode", ["SI", "IP"]) +def test_equipment_manager_output_renders_in_browser(app, eq_id, unit_mode): + """Rendered list and detail must serialise and contain no components inside dict props.""" + import pages.equipment_manager_page as eqm + from layout.shell import _get_equipment_library + + library = _get_equipment_library() + _, mode, _ = eqm.update_mode_options(eq_id, library, None) + outputs = [ + eqm.render_equipment_list(library, "all", None, eq_id, unit_mode), + eqm.render_overview(eq_id, library, unit_mode, None, 0, None), + *eqm.render_equipment_detail(eq_id, mode, library, unit_mode, None, None), + ] + for output in outputs: + json.dumps(output, cls=plotly.utils.PlotlyJSONEncoder) + assert components_in_dict_props(output) == [] + + +@pytest.mark.parametrize("eq_id", ["hr01", "hp01", "hp02", "bo01", "ch02"]) +@pytest.mark.parametrize("unit_mode", ["SI", "IP"]) +def test_equipment_manager_edit_mode_renders_in_browser(app, eq_id, unit_mode): + """The overview form and curve editor tables of a custom copy must serialise.""" + import pages.equipment_manager_page as eqm + from layout.shell import _get_equipment_library + from src.equipment import Equipment, duplicate_equipment, save_custom_equipment + + library = _get_equipment_library() + library_ids = [e["eq_id"] for e in library["equipment"]] + source = next(Equipment(**e) for e in library["equipment"] if e["eq_id"] == eq_id) + copy = duplicate_equipment(source, library_ids) + data = save_custom_equipment(library, copy, library_ids) + draft, session = copy.model_dump(), {"eq_id": copy.eq_id, "started": 0} + _, mode, _ = eqm.update_mode_options(copy.eq_id, data, None) + + outputs = [ + eqm.render_overview(copy.eq_id, data, unit_mode, session, 0, draft), + *eqm.render_equipment_detail(copy.eq_id, mode, data, unit_mode, draft, session), + ] + if copy.eq_type in ("heat_pump", "hr_heat_pump"): + from layout.equipment_editor import editor_tables + + outputs += list(editor_tables(copy, mode, unit_mode)) + for output in outputs: + json.dumps(output, cls=plotly.utils.PlotlyJSONEncoder) + assert components_in_dict_props(output) == [] + + +def test_equipment_manager_export_then_import(app): + """Export the custom items of one session and import the file into a fresh one.""" + import base64 + + import pages.equipment_manager_page as eqm + from layout.shell import _get_equipment_library + from src.equipment import Equipment, duplicate_equipment, save_custom_equipment + + library = _get_equipment_library() + library_ids = [e["eq_id"] for e in library["equipment"]] + hp01 = next(Equipment(**e) for e in library["equipment"] if e["eq_id"] == "hp01") + copy = duplicate_equipment(hp01, library_ids) + session = save_custom_equipment(library, copy, library_ids) + + download, _ = eqm.export_equipment(1, session) + assert download["filename"].startswith("decarb_custom_equipment_") + contents = ( + "data:application/json;base64," + base64.b64encode(download["content"].encode()).decode() + ) + + store, selected, draft, edit_session, message, reset = eqm.import_equipment( + contents, download["filename"], library, library + ) + assert selected == copy.eq_id and draft is None and edit_session is None and reset is None + assert store["equipment"][-1]["eq_id"] == copy.eq_id + json.dumps(message, cls=plotly.utils.PlotlyJSONEncoder) + + *_, error, _ = eqm.import_equipment( + "data:text/plain;base64," + base64.b64encode(b"not json").decode(), + "x.json", + library, + library, + ) + assert "not a JSON file" in str(error.children) + + _, empty = eqm.export_equipment(1, library) + assert "no custom equipment" in str(empty.children) diff --git a/tests/test_energy_regression.py b/tests/test_energy_regression.py index a8a3af7..0d4e640 100644 --- a/tests/test_energy_regression.py +++ b/tests/test_energy_regression.py @@ -21,7 +21,13 @@ from src.config import Columns as Col from src.emissions import EmissionScenario from src.energy import loads_to_site_energy, site_to_source -from src.equipment import load_library +from src.equipment import ( + EquipmentLibrary, + EquipmentScenario, + duplicate_equipment, + load_library, + scale_performance, +) from src.loads import StandardLoad from src.metadata import Metadata @@ -164,6 +170,53 @@ def test_no_negative_energy(scenario_id, library, synthetic_load): ).all(), f"[{scenario_id}] Negative gas consumption detected" +@pytest.mark.regression +@pytest.mark.parametrize("recovery_control", ["min_turndown", "max_heat_recovery"]) +@pytest.mark.parametrize("rejection_control", ["min_turndown", "max_heat_rejection"]) +def test_exhaust_air_coil(library, synthetic_load, recovery_control, rejection_control): + """Exhaust air coil stays within capacity and keeps the HR WWHP energy balance.""" + lib = EquipmentLibrary(**library.model_dump()) # copy library + + # new scenario with 10 kW exhaust air coil + scen = lib.get_scenario("eq_scenario_5").model_dump() + scen.update( + eq_scen_id="eac", + hr_eac_rejection_cap_W=1e5, + hr_eac_recovery_cap_W=1e5, + hr_eac_recovery_control=recovery_control, + hr_eac_rejection_control=rejection_control, + ) + lib.add_equipment_scenario(EquipmentScenario(**scen)) + + df = loads_to_site_energy(load=synthetic_load, library=lib, scenario_ids=["eac"]) + eac_h = df[Col.HR_EAC_H_W.value] + eac_c = df[Col.HR_EAC_C_W.value] + + # coil check + assert eac_h.sum() > 0 and eac_c.sum() > 0 + assert eac_h.max() <= 1e5 + 1e-5 and eac_c.max() <= 1e5 + 1e-5 + + # HR WWHP energy balance + assert np.allclose( + df[Col.HR_HHW_W.value] + eac_h, + df[Col.HR_CHW_W.value] + eac_c + df[Col.ELEC_HR_WH.value], + atol=1.0, + ) + + hr_out_h = df[Col.HR_HHW_W.value] + eac_h + min_cap = min(lib.get_equipment(scen["hr_wwhp"]).performance_heating.capacity_W) + + if recovery_control == "min_turndown": + assert np.allclose(hr_out_h[eac_c > 1.0], min_cap) + else: + assert (hr_out_h[eac_c > 1.0] > min_cap).any() + + if rejection_control == "min_turndown": + assert np.allclose(hr_out_h[eac_h > 1.0], min_cap) + else: + assert (hr_out_h[eac_h > 1.0] > min_cap).any() + + # --------------------------------------------------------------------------- # Layer 2b — Snapshot regression # --------------------------------------------------------------------------- @@ -220,3 +273,58 @@ def test_emissions_output_snapshot(snapshot, scenario_id, library, synthetic_loa site = loads_to_site_energy(load=synthetic_load, library=library, scenario_ids=[scenario_id]) out = site_to_source(site, metadata=metadata) assert snapshot == out[EMISSION_COLUMNS].round(4).to_csv() + + +# --------------------------------------------------------------------------- +# Layer 2d — Custom equipment copies +# --------------------------------------------------------------------------- + + +@pytest.mark.regression +@pytest.mark.parametrize("scenario_id", ["eq_scenario_5"]) # HR-WWHP + AWHP + cooling +def test_unmodified_custom_copy_matches_library_equipment(scenario_id, library, synthetic_load): + """A duplicated but unedited AWHP / HR-WWHP must give the same results as the original.""" + custom_library = EquipmentLibrary(**library.model_dump()) + scenario = custom_library.get_scenario(scenario_id) + existing_ids = [e.eq_id for e in custom_library.equipment] + + hr_copy = duplicate_equipment(custom_library.get_equipment(scenario.hr_wwhp), existing_ids) + awhp_copy = duplicate_equipment(custom_library.get_equipment(scenario.awhp), existing_ids) + custom_library.add_equipment(hr_copy) + custom_library.add_equipment(awhp_copy) + custom_library.add_equipment_scenario( + scenario.model_copy(update={"hr_wwhp": hr_copy.eq_id, "awhp": awhp_copy.eq_id}) + ) + + df_original = loads_to_site_energy( + load=synthetic_load, library=library, scenario_ids=[scenario_id] + ) + df_copy = loads_to_site_energy( + load=synthetic_load, library=custom_library, scenario_ids=[scenario_id] + ) + pd.testing.assert_frame_equal(df_original, df_copy) + + +@pytest.mark.regression +def test_halving_awhp_heating_cop_doubles_its_heating_electricity(library, synthetic_load): + """COP-only scaling keeps sizing and delivered heat; heat pump heating electricity is heat / COP.""" + scenario_id = "eq_scenario_4" # AWHP heating + cooling, electric resistance backup + custom_library = EquipmentLibrary(**library.model_dump()) + scenario = custom_library.get_scenario(scenario_id) + existing_ids = [e.eq_id for e in custom_library.equipment] + awhp = duplicate_equipment(custom_library.get_equipment(scenario.awhp), existing_ids) + custom_library.add_equipment(scale_performance(awhp, "heating", cop_factor=0.5)) + custom_library.add_equipment_scenario(scenario.model_copy(update={"awhp": awhp.eq_id})) + + df_original = loads_to_site_energy( + load=synthetic_load, library=library, scenario_ids=[scenario_id] + ) + df_scaled = loads_to_site_energy( + load=synthetic_load, library=custom_library, scenario_ids=[scenario_id] + ) + pd.testing.assert_series_equal( + df_scaled[Col.ELEC_AWHP_H_WH.value], 2 * df_original[Col.ELEC_AWHP_H_WH.value] + ) + pd.testing.assert_series_equal( + df_scaled[Col.ELEC_AWHP_C_WH.value], df_original[Col.ELEC_AWHP_C_WH.value] + ) diff --git a/tests/test_energy_unit.py b/tests/test_energy_unit.py index 0bbcd65..b9b59aa 100644 --- a/tests/test_energy_unit.py +++ b/tests/test_energy_unit.py @@ -11,6 +11,7 @@ _capacity_constraints, _constant_heating_efficiency, _heat_recovery_plr_curve, + _heating_supply_temp_performance, _per_unit_cooling_capacity_W, _per_unit_cooling_cop, _per_unit_heating_capacity_W, @@ -313,3 +314,46 @@ def test_high_efficiency(self): ) result = _constant_heating_efficiency(e) assert result == pytest.approx(0.97) + + +# --------------------------------------------------------------------------- +# _heating_supply_temp_performance +# --------------------------------------------------------------------------- + + +@pytest.mark.unit +class TestHeatingSupplyTempReset: + def test_lowest_supply_temperature_picked_numerically(self): + """Reset starts at the OAT limit of the numerically lowest supply temperature. + + As strings, "100" < "82", which used to pick the wrong curve's limit (-5 °C instead of -20 °C). + """ + e = Equipment( + eq_id="test_awhp_reset", + eq_type="heat_pump", + model="TestAWHPReset", + fuel="electricity", + performance={ + "heating": { + "t_out_C": [-20.0, 20.0], + "leaving_supply_t": { + "100": { + "cop": [2.0, 2.0], + "constraints": {"min_temp_C": -5.0, "max_temp_C": 35.0}, + }, + "82": { + "cop": [3.0, 3.0], + "constraints": {"min_temp_C": -20.0, "max_temp_C": 35.0}, + }, + }, + "constraints": {"min_temp_C": 82.0, "max_temp_C": 100.0}, + } + }, + capacity_W=100_000.0, + ) + perf = _heating_supply_temp_performance( + e, np.array([np.nan]), np.array([-5.0]), "interpolate_HHWST_reset" + ) + # reset from 100 °C at -20 °C OAT to 82 °C at 20 °C OAT -> 93.25 °C at -5 °C OAT + # COP interpolated between the 82 °C (3.0) and 100 °C (2.0) curves + assert perf.cop[0][0] == pytest.approx(3.0 - (93.25 - 82.0) / 18.0) diff --git a/tests/test_equipment.py b/tests/test_equipment.py index a80eb8f..9571564 100644 --- a/tests/test_equipment.py +++ b/tests/test_equipment.py @@ -1,12 +1,30 @@ """Tests for equipment models and library.""" +import json + +import pandas as pd import pytest from layout.shell import _get_initial_equipment_scenario_ids from src import paths from src.equipment import ( + HEAT_PUMP_TYPES, + Equipment, EquipmentLibrary, + apply_curve_table, + curve_table, + delete_custom_equipment, + duplicate_equipment, + export_custom_equipment, + find_refrigerant, + import_custom_equipment, + keep_custom_equipment, load_library, + load_refrigerants, + save_custom_equipment, + scale_performance, + scenarios_using, + validate_equipment, ) pytestmark = pytest.mark.unit @@ -92,3 +110,454 @@ def test_equipment_has_required_fields(self, equipment_library): assert equipment.eq_type is not None assert equipment.model is not None assert equipment.fuel is not None + + +# --------------------------------------------------------------------------- +# validate_equipment +# --------------------------------------------------------------------------- + + +def _awhp_dict(): + """A minimal valid AWHP (heating + cooling) as a plain dict, easy to break per test.""" + return { + "eq_id": "t_awhp", + "eq_type": "heat_pump", + "eq_calc_type": "specific", + "model": "TestAWHP", + "nominal_capacity_W": 100_000, + "fuel": "electricity", + "performance": { + "heating": { + "t_out_C": [-10.0, 0.0, 10.0], + "leaving_supply_t": { + "40": { + "cop": [2.5, 3.0, 3.5], + "capacity_W": [80_000.0, 90_000.0, 100_000.0], + "constraints": {"min_temp_C": -15.0, "max_temp_C": 35.0}, + }, + "55": { + "cop": [2.0, 2.5, 3.0], + "capacity_W": [75_000.0, 85_000.0, 95_000.0], + "constraints": {"min_temp_C": -10.0, "max_temp_C": 35.0}, + }, + }, + "constraints": {"min_temp_C": 40.0, "max_temp_C": 55.0}, + }, + "cooling": { + "t_out_C": [25.0, 35.0], + "leaving_supply_t": { + "7": { + "cop": [4.0, 3.0], + "capacity_W": [100_000.0, 90_000.0], + "constraints": {"min_temp_C": 5.0, "max_temp_C": 45.0}, + } + }, + "constraints": {"min_temp_C": 7.0, "max_temp_C": 7.0}, + }, + }, + } + + +def _errors(eq_dict, modes=None): + issues = validate_equipment(Equipment(**eq_dict), modes) + return [i for i in issues if i.severity == "error"] + + +def _warnings(eq_dict, modes=None): + issues = validate_equipment(Equipment(**eq_dict), modes) + return [i for i in issues if i.severity == "warning"] + + +class TestValidateEquipment: + def test_library_has_no_errors(self, equipment_library): + for eq_id, issues in equipment_library.validation_issues().items(): + errors = [i.message for i in issues if i.severity == "error"] + assert not errors, f"{eq_id}: {errors}" + + def test_valid_awhp_has_no_issues(self): + assert validate_equipment(Equipment(**_awhp_dict())) == [] + + def test_cop_length_mismatch(self): + d = _awhp_dict() + d["performance"]["heating"]["leaving_supply_t"]["40"]["cop"] = [2.5, 3.0] + errors = _errors(d) + assert [e.field for e in errors] == ["performance.heating.leaving_supply_t.40.cop"] + assert "different lengths" in errors[0].message + + def test_capacity_length_mismatch(self): + d = _awhp_dict() + d["performance"]["heating"]["leaving_supply_t"]["55"]["capacity_W"] = [1.0] + assert [e.field for e in _errors(d)] == [ + "performance.heating.leaving_supply_t.55.capacity_W" + ] + + def test_t_out_not_increasing(self): + d = _awhp_dict() + d["performance"]["heating"]["t_out_C"] = [-10.0, 10.0, 0.0] + assert "strictly increasing" in _errors(d)[0].message + + def test_non_positive_cop(self): + d = _awhp_dict() + d["performance"]["heating"]["leaving_supply_t"]["40"]["cop"] = [2.5, 0.0, 3.5] + assert "non-positive" in _errors(d)[0].message + + def test_non_numeric_supply_temperature(self): + d = _awhp_dict() + lst = d["performance"]["heating"]["leaving_supply_t"] + lst["hot"] = lst.pop("55") + assert any("not a number" in e.message for e in _errors(d)) + + def test_missing_cop_value(self): + d = _awhp_dict() + d["performance"]["heating"]["leaving_supply_t"]["40"]["cop"] = [2.5, float("nan"), 3.5] + assert "missing" in _errors(d)[0].message + + def test_missing_curve_point(self): + d = _awhp_dict() + d["performance"]["heating"]["t_out_C"] = [-10.0, float("nan"), 10.0] + assert "missing" in _errors(d)[0].message + + def test_duplicate_supply_temperature(self): + d = _awhp_dict() + lst = d["performance"]["heating"]["leaving_supply_t"] + lst["40.0"] = lst.pop("55") + assert any("more than once" in e.message for e in _errors(d)) + + def test_missing_oat_constraints(self): + d = _awhp_dict() + del d["performance"]["heating"]["leaving_supply_t"]["40"]["constraints"] + assert [e.field for e in _errors(d)] == [ + "performance.heating.leaving_supply_t.40.constraints" + ] + + def test_flipped_supply_temperature_constraints(self): + d = _awhp_dict() + d["performance"]["heating"]["constraints"] = {"min_temp_C": 55.0, "max_temp_C": 40.0} + assert "min_temp_C above max_temp_C" in _errors(d)[0].message + + def test_missing_capacity_without_fixed_capacity(self): + d = _awhp_dict() + del d["performance"]["heating"]["leaving_supply_t"]["40"]["capacity_W"] + assert "lacks heating capacity info" in _errors(d)[0].message + + def test_fixed_unit_capacity_replaces_capacity_curve(self): + d = _awhp_dict() + del d["performance"]["heating"]["leaving_supply_t"]["40"]["capacity_W"] + d["capacity_W"] = 100_000.0 + assert _errors(d) == [] + + def test_implausible_cop_is_warning_only(self): + d = _awhp_dict() + d["performance"]["heating"]["leaving_supply_t"]["40"]["cop"] = [2.5, 3.0, 12.0] + assert _errors(d) == [] + assert "typical range" in _warnings(d)[0].message + + def test_constraints_not_matching_curves_is_warning(self): + d = _awhp_dict() + d["performance"]["heating"]["constraints"] = {"min_temp_C": 35.0, "max_temp_C": 55.0} + assert _errors(d) == [] + assert [w.field for w in _warnings(d)] == ["performance.heating.constraints"] + + def test_modes_limits_checks(self): + d = _awhp_dict() + d["performance"]["cooling"]["leaving_supply_t"]["7"]["cop"] = [4.0] + assert _errors(d, modes=("heating",)) == [] + assert _errors(d, modes=("heating", "cooling")) + + def test_missing_mode_is_error_when_requested(self): + d = _awhp_dict() + del d["performance"]["cooling"] + assert "lacks cooling performance data" in _errors(d, modes=("cooling",))[0].message + + def test_boiler_requires_positive_efficiency(self): + boiler = { + "eq_id": "t_bo", + "eq_type": "backup_heating", + "model": "TestBoiler", + "fuel": "natural_gas", + "performance": {"heating": {"efficiency": 0.0}}, + } + assert "positive 'efficiency'" in _errors(boiler)[0].message + + +# --------------------------------------------------------------------------- +# duplicate_equipment / curve_table +# --------------------------------------------------------------------------- + + +class TestDuplicateEquipment: + def test_copy_gets_new_id_and_custom_source(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + copy = duplicate_equipment(hp01, [e.eq_id for e in equipment_library.equipment]) + assert copy.eq_id == "custom_hp01_1" + assert copy.source == "custom" + assert copy.based_on == "hp01" + assert copy.model == f"{hp01.model} (copy)" + + def test_id_skips_existing_copies(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + assert duplicate_equipment(hp01, ["custom_hp01_1"]).eq_id == "custom_hp01_2" + + def test_copy_of_copy_refers_to_library_item(self, equipment_library): + first = duplicate_equipment(equipment_library.get_equipment("hp01"), []) + second = duplicate_equipment(first, [first.eq_id]) + assert second.eq_id == "custom_hp01_2" + assert second.based_on == "hp01" + + def test_copy_is_deep(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + original_cop = list(hp01.performance_heating.leaving_supply_t["38"].cop) + copy = duplicate_equipment(hp01, []) + copy.performance_heating.leaving_supply_t["38"].cop[0] = 99.0 + assert hp01.performance_heating.leaving_supply_t["38"].cop == original_cop + + +class TestCurveTable: + def test_awhp_rows_and_columns(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + df = curve_table(hp01, "heating") + n_lwt = len(hp01.performance_heating.leaving_supply_t) + assert len(df) == n_lwt * len(hp01.performance_heating.t_out_C) + assert set(df["x_kind"]) == {"t_out_C"} + assert df["capacity_W"].notna().all() + + def test_hr_wwhp_uses_capacity_axis(self, equipment_library): + hr01 = equipment_library.get_equipment("hr01") + df = curve_table(hr01, "heating") + assert len(df) == 2 * len(hr01.performance_heating.capacity_W) + assert set(df["x_kind"]) == {"capacity_W"} + assert (df["x"] == df["capacity_W"]).all() + + def test_supply_temperatures_sorted_numerically(self, equipment_library): + # hp04 stores its supply temperatures as "50", "45", "35" + df = curve_table(equipment_library.get_equipment("hp04"), "heating") + assert list(df["lwt_C"].unique()) == [35.0, 45.0, 50.0] + + def test_fixed_capacity_gives_nan_capacity(self, equipment_library): + df = curve_table(equipment_library.get_equipment("hp02"), "heating") + assert df["capacity_W"].isna().all() + + def test_non_heat_pump_is_empty(self, equipment_library): + assert curve_table(equipment_library.get_equipment("bo01"), "heating").empty + + +class TestApplyCurveTable: + def test_round_trip_is_identity_for_library_heat_pumps(self, equipment_library): + for eq in equipment_library.equipment: + for mode in eq.performance if eq.eq_type in HEAT_PUMP_TYPES else (): + back = apply_curve_table(eq, mode, curve_table(eq, mode)) + assert back.performance[mode] == eq.performance[mode], f"{eq.eq_id} {mode}" + + def test_edited_value_and_new_supply_temperature(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + df = curve_table(hp01, "heating") + df.loc[0, "cop"] = 9.9 + new = df[df["lwt_C"] == 52.0].assign(lwt_C=60.0) + eq = apply_curve_table(hp01, "heating", pd.concat([df, new])) + perf = eq.performance_heating + assert perf.leaving_supply_t["38"].cop[0] == 9.9 + assert list(perf.leaving_supply_t) == ["38", "52", "60"] + assert perf.constraints["max_temp_C"] == 60.0 # limits follow the curves + assert hp01.performance_heating.leaving_supply_t["38"].cop[0] != 9.9 # original untouched + + def test_points_must_match_across_supply_temperatures(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + df = curve_table(hp01, "heating") + with pytest.raises(ValueError, match="same curve points"): + apply_curve_table(hp01, "heating", df.drop(index=0)) + + +class TestScalePerformance: + def test_awhp_cop_and_capacity_scaled(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + eq = scale_performance(hp01, "heating", cop_factor=0.9, capacity_factor=1.1) + for key, curves in eq.performance_heating.leaving_supply_t.items(): + orig = hp01.performance_heating.leaving_supply_t[key] + assert curves.cop == pytest.approx([0.9 * v for v in orig.cop]) + assert curves.capacity_W == pytest.approx([1.1 * v for v in orig.capacity_W]) + assert eq.nominal_capacity_W == round(1.1 * hp01.nominal_capacity_W) + assert eq.performance_heating.t_out_C == hp01.performance_heating.t_out_C + assert eq.scaling == {"heating": {"cop": 0.9, "capacity": 1.1}} + + def test_fixed_unit_capacity_scaled(self, equipment_library): + hp02 = equipment_library.get_equipment("hp02") + eq = scale_performance(hp02, "heating", capacity_factor=1.2) + assert eq.capacity_W == pytest.approx(1.2 * hp02.capacity_W) + + def test_hr_wwhp_capacity_points_scaled(self, equipment_library): + hr01 = equipment_library.get_equipment("hr01") + eq = scale_performance(hr01, "heating", capacity_factor=0.5) + assert eq.performance_heating.capacity_W == pytest.approx( + [0.5 * v for v in hr01.performance_heating.capacity_W] + ) + + def test_reapplying_does_not_compound(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + once = scale_performance(hp01, "heating", 1.1, 1.1) + twice = scale_performance(once, "heating", 1.1, 1.1) + assert twice.performance_heating == once.performance_heating + back = scale_performance(twice, "heating", 1.0, 1.0) + assert back.performance_heating.leaving_supply_t["38"].cop == pytest.approx( + hp01.performance_heating.leaving_supply_t["38"].cop + ) + assert back.scaling is None + + def test_rejects_non_positive_factor(self, equipment_library): + with pytest.raises(ValueError): + scale_performance(equipment_library.get_equipment("hp01"), "heating", 0) + + +class TestCustomEquipmentStore: + def _data(self, equipment_library): + return equipment_library.model_dump() + + def test_save_adds_then_replaces_custom_item(self, equipment_library): + data = self._data(equipment_library) + library_ids = [e["eq_id"] for e in data["equipment"]] + copy = duplicate_equipment(equipment_library.get_equipment("hp01"), library_ids) + added = save_custom_equipment(data, copy, library_ids) + assert len(added["equipment"]) == len(data["equipment"]) + 1 + renamed = copy.model_copy(update={"model": "Renamed"}) + replaced = save_custom_equipment(added, renamed, library_ids) + assert len(replaced["equipment"]) == len(added["equipment"]) + assert replaced["equipment"][-1]["model"] == "Renamed" + assert data["equipment"] == self._data(equipment_library)["equipment"] # input untouched + + def test_save_refuses_to_overwrite_library_items(self, equipment_library): + data = self._data(equipment_library) + library_ids = [e["eq_id"] for e in data["equipment"]] + hp01 = equipment_library.get_equipment("hp01") + with pytest.raises(ValueError, match="library equipment"): + save_custom_equipment(data, hp01.model_copy(update={"model": "x"}), library_ids) + # even when marked custom, a library id is refused + with pytest.raises(ValueError, match="library equipment"): + save_custom_equipment(data, hp01.model_copy(update={"source": "custom"}), library_ids) + + def test_delete_refuses_library_items_and_items_in_use(self, equipment_library): + data = self._data(equipment_library) + library_ids = [e["eq_id"] for e in data["equipment"]] + with pytest.raises(ValueError, match="not custom"): + delete_custom_equipment(data, "hp01") + copy = duplicate_equipment(equipment_library.get_equipment("hp01"), library_ids) + data = save_custom_equipment(data, copy, library_ids) + scenario = {**data["equipment_scenarios"][0], "awhp": copy.eq_id} + in_use = {**data, "equipment_scenarios": [*data["equipment_scenarios"], scenario]} + assert scenarios_using(in_use, copy.eq_id) == [scenario["eq_scen_name"]] + with pytest.raises(ValueError, match="used by"): + delete_custom_equipment(in_use, copy.eq_id) + assert copy.eq_id not in [ + e["eq_id"] for e in delete_custom_equipment(data, copy.eq_id)["equipment"] + ] + + def test_reset_keeps_custom_items(self, equipment_library): + initial = self._data(equipment_library) + library_ids = [e["eq_id"] for e in initial["equipment"]] + copy = duplicate_equipment(equipment_library.get_equipment("hp01"), library_ids) + current = save_custom_equipment(initial, copy, library_ids) + reset = keep_custom_equipment(initial, current) + assert [e["eq_id"] for e in reset["equipment"]] == [*library_ids, copy.eq_id] + assert keep_custom_equipment(initial, initial) is initial + + +class TestRefrigerants: + def test_database_loads_with_unique_names(self): + refrigerants = load_refrigerants() + names = [r.name for r in refrigerants] + assert len(names) == len(set(names)) >= 15 + assert all(r.gwp >= 0 for r in refrigerants) + + def test_library_gwps_match_database(self, equipment_library): + for eq in equipment_library.equipment: + if eq.refrigerant: + match = find_refrigerant(eq.refrigerant) + assert match is not None, f"{eq.eq_id}: {eq.refrigerant} not in database" + assert match.gwp == eq.refrigerant_gwp, eq.eq_id + + def test_lookup_ignores_case_punctuation_and_uses_aliases(self): + assert find_refrigerant("r134A").name == "R-134a" + assert find_refrigerant("R-1234ze").name == "R-1234ze(E)" + assert find_refrigerant("CO2").gwp == 1 + assert find_refrigerant("R-999") is None + assert find_refrigerant(None) is None + + +class TestImportExport: + @pytest.fixture + def setup(self, equipment_library): + data = equipment_library.model_dump() + library_ids = [e["eq_id"] for e in data["equipment"]] + copy = scale_performance( + duplicate_equipment(equipment_library.get_equipment("hp01"), library_ids), + "heating", + cop_factor=0.9, + ) + return data, library_ids, save_custom_equipment(data, copy, library_ids), copy + + def test_export_contains_only_custom_items(self, setup): + _, _, with_custom, copy = setup + payload = export_custom_equipment(with_custom, "0.2.0") + assert payload["format"] == "decarb-tool/custom-equipment" + assert payload["tool_version"] == "0.2.0" + assert [e["eq_id"] for e in payload["equipment"]] == [copy.eq_id] + + def test_round_trip_into_a_fresh_session(self, setup): + data, library_ids, with_custom, copy = setup + payload = json.loads(json.dumps(export_custom_equipment(with_custom))) + imported, report = import_custom_equipment(data, payload, library_ids) + assert report.added == [copy.eq_id] + assert imported["equipment"][-1] == copy.model_dump() + + def test_importing_the_same_file_twice_changes_nothing(self, setup): + _, library_ids, with_custom, copy = setup + payload = export_custom_equipment(with_custom) + again, report = import_custom_equipment(with_custom, payload, library_ids) + assert report.unchanged == [copy.eq_id] and not report.imported + assert again["equipment"] == with_custom["equipment"] + + def test_changed_custom_item_replaces_the_session_copy(self, setup): + _, library_ids, with_custom, copy = setup + payload = export_custom_equipment(with_custom) + payload["equipment"][0]["model"] = "Renamed in the file" + updated, report = import_custom_equipment(with_custom, payload, library_ids) + assert report.updated == [copy.eq_id] + assert len(updated["equipment"]) == len(with_custom["equipment"]) + assert updated["equipment"][-1]["model"] == "Renamed in the file" + + def test_library_items_are_never_overwritten(self, setup, equipment_library): + data, library_ids, _, _ = setup + hp01 = equipment_library.get_equipment("hp01").model_dump() + changed = {**hp01, "model": "Edited outside the tool", "source": "custom"} + imported, report = import_custom_equipment(data, [hp01, changed], library_ids) + assert report.unchanged == ["hp01"] # the unchanged library item itself + new_id = report.renamed["hp01"] + assert new_id.startswith("custom_hp01_") + assert next(e for e in imported["equipment"] if e["eq_id"] == "hp01") == hp01 + new = next(e for e in imported["equipment"] if e["eq_id"] == new_id) + assert (new["model"], new["source"], new["based_on"]) == ( + "Edited outside the tool", + "custom", + "hp01", + ) + + def test_invalid_items_are_rejected_with_a_reason(self, setup, equipment_library): + data, library_ids, _, _ = setup + broken = duplicate_equipment(equipment_library.get_equipment("hp01"), library_ids) + broken = broken.model_dump() + broken["performance"]["heating"]["leaving_supply_t"]["38"]["cop"] = [0.0] * 9 + _, report = import_custom_equipment( + data, [broken, {"eq_id": "x1", "model": "no type"}, "nonsense"], library_ids + ) + assert set(report.rejected) == {broken["eq_id"], "x1", "item 3"} + assert "non-positive" in report.rejected[broken["eq_id"]] + assert not report.imported + + def test_results_settings_file_contributes_its_custom_items(self, setup): + data, library_ids, with_custom, copy = setup + settings = {"format_version": "1.0", "equipment_library": with_custom} + _, report = import_custom_equipment(data, settings, library_ids) + assert report.added == [copy.eq_id] + + def test_file_without_equipment_is_an_error(self, setup): + data, library_ids, _, _ = setup + with pytest.raises(ValueError, match="does not contain equipment"): + import_custom_equipment(data, {"something": "else"}, library_ids) diff --git a/tests/test_equipment_manager.py b/tests/test_equipment_manager.py new file mode 100644 index 0000000..ca78578 --- /dev/null +++ b/tests/test_equipment_manager.py @@ -0,0 +1,61 @@ +"""Unit tests for the Equipment Manager's editor helpers (display units <-> stored curves).""" + +import pytest + +import layout.equipment_editor as eqm +from src.equipment import apply_curve_table + +pytestmark = pytest.mark.unit + + +@pytest.mark.parametrize("eq_id", ["hp01", "hp02", "hp04", "hp08", "hr01"]) +@pytest.mark.parametrize("unit_mode", ["SI", "IP"]) +def test_editor_tables_round_trip(equipment_library, eq_id, unit_mode): + eq = equipment_library.get_equipment(eq_id) + for mode in eq.performance: + rows, _, lwt_rows, _ = eqm.editor_tables(eq, mode, unit_mode) + df = eqm.tables_to_long(eq, mode, unit_mode, rows, lwt_rows) + back = apply_curve_table(eq, mode, df) + before, after = eq.performance[mode], back.performance[mode] + assert set(after.leaving_supply_t) == set(before.leaving_supply_t) + for key, curves in before.leaving_supply_t.items(): + assert after.leaving_supply_t[key].cop == pytest.approx(curves.cop) + if curves.capacity_W: + assert after.leaving_supply_t[key].capacity_W == pytest.approx(curves.capacity_W) + assert ( + after.leaving_supply_t[key].constraints == pytest.approx(curves.constraints or {}) + or curves.constraints is None + ) + + +def test_editor_cell_edit_reaches_the_curve(equipment_library): + hp01 = equipment_library.get_equipment("hp01") + rows, _, lwt_rows, _ = eqm.editor_tables(hp01, "heating", "IP") + rows[0]["cop_1"] = 1.5 # 52 °C curve, first outdoor temperature + lwt_rows[0]["oat_min"] = 0.0 # 0 °F + eq = apply_curve_table( + hp01, "heating", eqm.tables_to_long(hp01, "heating", "IP", rows, lwt_rows) + ) + assert eq.performance_heating.leaving_supply_t["52"].cop[0] == 1.5 + assert eq.performance_heating.leaving_supply_t["38"].constraints["min_temp_C"] == pytest.approx( + -17.78, abs=0.01 + ) + + +@pytest.mark.parametrize("unit_mode", ["SI", "IP"]) +def test_form_display_values_convert_back(equipment_library, unit_mode): + hp01 = equipment_library.get_equipment("hp01").model_dump() + for name in ("nominal_capacity_W", "refrigerant_weight_g", "dimensions.length"): + _, _, _, to_base, _ = eqm.field_meta(name, hp01, unit_mode) + shown = eqm.display_value(hp01, name, unit_mode) + assert to_base(shown) == pytest.approx(eqm.get_path(hp01, name), rel=1e-3) + + +def test_form_fields_follow_equipment_type(equipment_library): + names = { + eq_id: set(eqm.form_field_names(equipment_library.get_equipment(eq_id).model_dump())) + for eq_id in ("hp01", "hp02", "bo01", "ch02") + } + assert "efficiency" in names["bo01"] and "refrigerant" not in names["bo01"] + assert {"efficiency", "refrigerant", "capacity_W"} <= names["ch02"] + assert "capacity_W" in names["hp02"] and "capacity_W" not in names["hp01"] diff --git a/tests/test_export.py b/tests/test_export.py new file mode 100644 index 0000000..7a4d077 --- /dev/null +++ b/tests/test_export.py @@ -0,0 +1,303 @@ +"""Tier 1 unit tests for the results download in src/export.py. + +Synthetic results frames only: names, column order, annual summary, and that the +SI/IP switch converts and labels every exported value. +""" + +import datetime + +import numpy as np +import pandas as pd +import pytest + +from src.emissions import EmissionScenario +from src.equipment import EquipmentLibrary +from src.export import ( + _HOURLY_COLUMN_ORDER, + EXPORT_ID_COLUMNS, + _round_for_csv, + build_annual_summary, + build_export_basename, + build_hourly_export, + build_metadata_summary, + format_for_csv, +) +from src.metadata import LoadData, Metadata +from utils.units import ( + COLUMN_REGISTRY, + UNIT_MAP, + W_to_BTUh, + get_category, + get_column_label, +) + +NOW = datetime.datetime(2026, 11, 2, 14, 30) +HOURS = 3 +EQ_IDS = ["eq_scenario_1", "eq_scenario_2"] +EM_IDS = ["em_scenario_a", "em_scenario_b"] +TEXT_COLUMNS = {"hr_wwhp_refrigerant", "awhp_refrigerant", "chiller_refrigerant"} + +# Numeric export columns without a unit; every other numeric column must have a unit category +UNITLESS_COLUMNS = { + "eq_scen_slot", + "em_year", + "hr_cop_h", + "awhp_cop_h", + "awhp_cop_c", + "chiller_cop", + "boiler_eff", + "awhp_num", + "awhp_num_redundant", + "awhp_num_c", + "boiler_num", + "shortrun_weighting", +} + + +def _emission_scenarios(): + common = dict( + elec_emission_source="Marginal (Cambium, Long-run)", + grid_scenario="MidCase", + emission_type="Includes pre-combustion", + annual_refrig_leakage_percent=1.0, + ng_emission_rate_gCO2e_per_kWh=239.2, + ) + return [ + EmissionScenario(em_scen_id="em_scenario_a", em_scen_name="Mid 2030", year=2030, **common), + EmissionScenario(em_scen_id="em_scenario_b", em_scen_name="Mid 2045", year=2045, **common), + ] + + +def _metadata(**overrides): + fields = dict( + building_id="3", + location="Los Angeles", + ashrae_climate_zone="3C", + load_data=LoadData(load_type="simulated"), + emission_settings=_emission_scenarios(), + ) + return Metadata.create(**{**fields, **overrides}) + + +def _results_frame() -> pd.DataFrame: + """Engine-shaped results: em scenarios outermost, as site_to_source returns them.""" + rng = np.random.default_rng(0) + index = pd.date_range("2001-01-01 01:00", periods=HOURS, freq="h", name="timestamp") + blocks = [] + for em_id in EM_IDS: + for eq_id in EQ_IDS: + block = pd.DataFrame(index=index) + for col in _HOURLY_COLUMN_ORDER: + block[col] = "R-32" if col in TEXT_COLUMNS else rng.uniform(1, 5000, HOURS) + block["eq_scen_id"] = eq_id + block["eq_scen_name"] = f"Name {eq_id}" + block["em_scen_id"] = em_id + block["year"] = 2001 + blocks.append(block) + return pd.concat(blocks) + + +# --------------------------------------------------------------------------- +# File names +# --------------------------------------------------------------------------- + + +@pytest.mark.unit +def test_basename_library_building(): + name = build_export_basename(_metadata(), "SI", now=NOW) + assert name == "decarb_B3_Los-Angeles_CZ3C_SI_20261102-1430" + + +@pytest.mark.unit +def test_basename_scaled_with_base_load_ip(): + scale = {"heating_factor": 1.25, "cooling_factor": 0.8} + base = {"heating": {"method": "floor", "value_W": 5000.0}, "cooling": None} + name = build_export_basename(_metadata(), "IP", scale, base, now=NOW) + assert name == "decarb_B3_Los-Angeles_CZ3C_scaled-h1.25-c0.80_baseload_IP_20261102-1430" + + +@pytest.mark.unit +def test_basename_empty_base_load_is_not_flagged(): + base = {"heating": None, "cooling": None} + assert "baseload" not in build_export_basename(_metadata(), "SI", None, base, now=NOW) + + +@pytest.mark.unit +def test_basename_custom_upload_and_missing_location(): + md = _metadata( + building_id="My Bldg #2", + location=None, + ashrae_climate_zone=None, + load_data=LoadData(load_type="custom", load_source_ref="upload.csv"), + ) + assert build_export_basename(md, "SI", now=NOW) == "decarb_custom-My-Bldg-2_SI_20261102-1430" + + +# --------------------------------------------------------------------------- +# Hourly layout and annual summary +# --------------------------------------------------------------------------- + + +@pytest.mark.unit +def test_hourly_identifiers_first_and_no_column_lost(): + df = _results_frame() + out = build_hourly_export(df, _metadata()) + + assert list(out.columns[: len(EXPORT_ID_COLUMNS)]) == EXPORT_ID_COLUMNS + assert set(df.columns) - {"year"} <= set(out.columns) + assert "year" not in out.columns + assert len(out) == len(df) + + +@pytest.mark.unit +def test_hourly_appends_unknown_columns(): + df = _results_frame() + df["new_engine_col"] = 1.0 + assert build_hourly_export(df, _metadata()).columns[-1] == "new_engine_col" + + +@pytest.mark.unit +def test_hourly_rows_grouped_per_case_and_slot_map_applied(): + # eq_scenario_2 occupies slot 1 on the Equipment page + slot_map = {"eq_scenario_2": 1, "eq_scenario_1": 2} + out = build_hourly_export(_results_frame(), _metadata(), slot_map) + + cases = list(zip(out["eq_scen_slot"], out["em_scen_letter"], strict=True)) + expected = [(s, e) for s in (1, 2) for e in ("A", "B") for _ in range(HOURS)] + assert cases == expected + assert out["eq_scen_id"].iloc[0] == "eq_scenario_2" + assert out.index[:HOURS].is_monotonic_increasing + + +@pytest.mark.unit +def test_hourly_emission_descriptors(): + out = build_hourly_export(_results_frame(), _metadata()) + by_em = out.groupby("em_scen_id")[["em_scen_name", "em_year", "em_grid_scenario"]].first() + assert by_em.loc["em_scenario_a"].tolist() == ["Mid 2030", 2030, "MidCase"] + assert by_em.loc["em_scenario_b"].tolist() == ["Mid 2045", 2045, "MidCase"] + + +@pytest.mark.unit +def test_annual_summary_sums_each_case(): + hourly = build_hourly_export(_results_frame(), _metadata()) + annual = build_annual_summary(hourly) + + assert len(annual) == len(EQ_IDS) * len(EM_IDS) + assert list(annual.columns[: len(EXPORT_ID_COLUMNS)]) == EXPORT_ID_COLUMNS + expected = hourly.groupby(["eq_scen_id", "em_scen_id"])[["total_emissions", "heating_W"]].sum() + got = annual.set_index(["eq_scen_id", "em_scen_id"]) + pd.testing.assert_series_equal( + got["total_emissions"], expected["total_emissions"], check_names=False + ) + pd.testing.assert_series_equal( + got["annual_heating_Wh"], expected["heating_W"], check_names=False + ) + + +# --------------------------------------------------------------------------- +# SI / IP +# --------------------------------------------------------------------------- + + +@pytest.mark.unit +def test_every_numeric_export_column_has_a_unit_or_is_unitless(): + hourly = build_hourly_export(_results_frame(), _metadata()) + annual = build_annual_summary(hourly) + for frame in (hourly, annual): + numeric = frame.select_dtypes("number").columns + missing = [c for c in numeric if c not in COLUMN_REGISTRY and c not in UNITLESS_COLUMNS] + assert not missing, f"no unit category for {missing}" + + +@pytest.mark.unit +@pytest.mark.parametrize("unit_mode", ["SI", "IP"]) +def test_values_and_headers_follow_unit_mode(unit_mode): + hourly = build_hourly_export(_results_frame(), _metadata()) + annual = build_annual_summary(hourly) + + for raw in (hourly, annual): + formatted = format_for_csv(raw, unit_mode) + for col in raw.columns: + category = get_category(col) + if category is None: + continue + label = get_column_label(col, unit_mode) + assert label.endswith(f"[{UNIT_MAP[category][unit_mode]['unit']}]") + expected = UNIT_MAP[category][unit_mode]["func"](raw[col]).to_numpy() + np.testing.assert_allclose(formatted[label].to_numpy(), expected, rtol=1e-3, atol=0.01) + + +@pytest.mark.unit +def test_combined_marginal_rates_convert_in_ip(): + raw = build_hourly_export(_results_frame(), _metadata()) + formatted = format_for_csv(raw, "IP") + for col in ("lrmer_co2e", "srmer_co2e"): + assert f"{col.upper()[:5]} CO₂e [lb CO₂e/kWh]" in formatted.columns + + +@pytest.mark.unit +def test_annual_ip_totals_equal_converted_base_sums(): + hourly = build_hourly_export(_results_frame(), _metadata()) + annual_ip = format_for_csv(build_annual_summary(hourly), "IP") + base = hourly.groupby(["eq_scen_id", "em_scen_id"], sort=False)["total_emissions"].sum() + expected = UNIT_MAP["emissions"]["IP"]["func"](base).to_numpy() + np.testing.assert_allclose(annual_ip["Total Emissions [lb CO₂e]"], expected, rtol=1e-6) + + +@pytest.mark.unit +def test_rounding_keeps_small_values_and_positions(): + # Repeated index labels, as in the hourly export + values = pd.Series( + [1234.5678, 0.123456, 0.000123456, -0.0456789, 0.0, 1e-12, 6.825], + index=[0, 0, 1, 1, 2, 2, 3], + ) + rounded = _round_for_csv(values).tolist() + assert rounded == [1234.57, 0.1235, 0.0001235, -0.04568, 0.0, 0.0, round(6.825, 2)] + + +# --------------------------------------------------------------------------- +# Settings summary +# --------------------------------------------------------------------------- + + +def _summary(unit_mode, scale_info=None, base_load_info=None): + library = EquipmentLibrary(equipment=[], equipment_scenarios=[]) + return build_metadata_summary( + _metadata(), library, [], EM_IDS, unit_mode, scale_info, base_load_info + ) + + +@pytest.mark.unit +def test_summary_rates_follow_unit_mode(): + assert "239.2 g CO₂e/kWh" in _summary("SI") + ip = _summary("IP") + assert "lb CO₂e/kBTU" in ip + assert "g CO₂e" not in ip + + +@pytest.mark.unit +def test_summary_load_modifications_in_export_units(): + scale = { + "method": "building area", + "heating_factor": 1.25, + "cooling_factor": 1.25, + "orig_area_sqm": 1000.0, + "target_area_sqm": 1250.0, + } + base = {"heating": {"method": "floor", "value_W": 10_000.0, "value_display": "10.0 kW"}} + + si = _summary("SI", scale, base) + assert "Heating Scale Factor:" in si and "1.250" in si + assert "Floor (minimum), 10.0 kW" in si + assert "1,250" in si + + ip = _summary("IP", scale, base) + # from value_W, not the value_display stored in the unit it was entered in + assert f"{10_000.0 * W_to_BTUh:,.1f} BTU/h" in ip + assert "13,455" in ip # 1250 m² in ft² + assert "Cooling Base Load:" in ip + + +@pytest.mark.unit +def test_summary_without_modifications(): + assert "None (original load profile)" in _summary("SI") diff --git a/tests/test_loads.py b/tests/test_loads.py index 71e9a71..712db52 100644 --- a/tests/test_loads.py +++ b/tests/test_loads.py @@ -4,7 +4,13 @@ import pandas as pd import pytest -from src.loads import STANDARD_COLUMNS, StandardLoad, ensure_datetime, get_load_data +from src.loads import ( + STANDARD_COLUMNS, + StandardLoad, + apply_load_modifications, + ensure_datetime, + get_load_data, +) from src.metadata import LoadData, Metadata @@ -210,6 +216,56 @@ def _make_annual_load(hours=8760, year=2025, nan_col=None, nan_count=0): ) +@pytest.mark.unit +class TestApplyLoadModifications: + """Scaling and base load are rebuilt from the original: scale first, then base load.""" + + def _df(self): + return pd.DataFrame( + {"t_out_C": [10.0, 20.0], "heating_W": [100.0, 1000.0], "cooling_W": [50.0, 500.0]} + ) + + def test_unit_factors_return_identical_copy(self): + df = self._df() + out = apply_load_modifications(df) + pd.testing.assert_frame_equal(out, df) + assert out is not df + + def test_factors_apply_per_load_type(self): + out = apply_load_modifications(self._df(), heating_factor=2.0) + assert out["heating_W"].tolist() == [200.0, 2000.0] + assert out["cooling_W"].tolist() == [50.0, 500.0] + + out = apply_load_modifications(self._df(), cooling_factor=0.5) + assert out["heating_W"].tolist() == [100.0, 1000.0] + assert out["cooling_W"].tolist() == [25.0, 250.0] + + def test_floor_applied_after_scaling(self): + base_load = {"heating": {"method": "floor", "value_W": 300.0}, "cooling": None} + out = apply_load_modifications(self._df(), heating_factor=2.0, base_load=base_load) + # 100 * 2 = 200 is raised to the floor; the floor itself is not scaled + assert out["heating_W"].tolist() == [300.0, 2000.0] + assert out["cooling_W"].tolist() == [50.0, 500.0] + + def test_offset_applied_after_scaling(self): + offset = {"method": "offset", "value_W": 10.0} + base_load = {"heating": offset, "cooling": offset} + out = apply_load_modifications( + self._df(), heating_factor=2.0, cooling_factor=2.0, base_load=base_load + ) + assert out["heating_W"].tolist() == [210.0, 2010.0] + assert out["cooling_W"].tolist() == [110.0, 1010.0] + + def test_separate_base_load_per_load_type(self): + base_load = { + "heating": {"method": "floor", "value_W": 300.0}, + "cooling": {"method": "offset", "value_W": 10.0}, + } + out = apply_load_modifications(self._df(), base_load=base_load) + assert out["heating_W"].tolist() == [300.0, 1000.0] + assert out["cooling_W"].tolist() == [60.0, 510.0] + + @pytest.mark.unit class TestGetDataSummary: def test_complete_data_flagged_as_complete(self): diff --git a/tests/test_units.py b/tests/test_units.py new file mode 100644 index 0000000..52619c7 --- /dev/null +++ b/tests/test_units.py @@ -0,0 +1,24 @@ +"""Unit tests for utils/units.py conversions.""" + +import pytest + +from utils.units import get_converter, get_inverse_converter + +pytestmark = pytest.mark.unit + + +@pytest.mark.parametrize( + "category", + ["temperature", "power", "power_cooling", "capacity", "mass_g", "gwp", "energy", "area"], +) +@pytest.mark.parametrize("unit_mode", ["SI", "IP"]) +def test_inverse_converter_round_trips(category, unit_mode): + to_display = get_converter(category, unit_mode) + to_base = get_inverse_converter(category, unit_mode) + for value in (-12.5, 0.0, 1.0, 54_000.0): + assert to_base(to_display(value)) == pytest.approx(value) + + +def test_inverse_temperature_is_affine(): + assert get_inverse_converter("temperature", "IP")(32.0) == pytest.approx(0.0) + assert get_inverse_converter("temperature", "IP")(212.0) == pytest.approx(100.0) diff --git a/tests/test_visuals.py b/tests/test_visuals.py new file mode 100644 index 0000000..55a89b0 --- /dev/null +++ b/tests/test_visuals.py @@ -0,0 +1,92 @@ +"""Unit tests for figure builders in src/visuals.py.""" + +import math + +import pytest + +import utils.plotly_theme # noqa: F401 - registers the decarb-tool-theme template +from src.visuals import plot_performance_curves + +pytestmark = pytest.mark.unit + + +def _traces(fig, role): + return [t for t in fig.data if t.meta == role] + + +class TestPlotPerformanceCurves: + def test_awhp_has_cop_and_capacity_trace_per_supply_temperature(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + fig = plot_performance_curves(hp01, "heating") + n_lwt = len(hp01.performance_heating.leaving_supply_t) + assert len(_traces(fig, "curve")) == 2 * n_lwt + assert {t.yaxis for t in fig.data} == {"y", "y2"} + + def test_hr_wwhp_plots_cop_against_capacity(self, equipment_library): + hr01 = equipment_library.get_equipment("hr01") + fig = plot_performance_curves(hr01, "heating") + assert len(_traces(fig, "curve")) == len(hr01.performance_heating.leaving_supply_t) + assert not _traces(fig, "outside") # HR WWHP curves have no outdoor air limits + assert "capacity" in fig.layout.xaxis.title.text.lower() + + def test_awhp_panels_both_labelled_with_outdoor_temperature(self, equipment_library): + fig = plot_performance_curves(equipment_library.get_equipment("hp01"), "heating") + for axis in (fig.layout.xaxis, fig.layout.xaxis2): + assert axis.title.text.startswith("Outdoor air temperature") + assert fig.layout.xaxis.showticklabels + assert fig.layout.yaxis.title.text == "COP" + assert "capacity" in fig.layout.yaxis2.title.text.lower() + + def test_ip_units_on_temperature_axis(self, equipment_library): + fig = plot_performance_curves(equipment_library.get_equipment("hp01"), "heating", "IP") + assert "°F" in fig.layout.xaxis2.title.text + assert fig.data[0].name.endswith("°F") + + def test_highlight_adds_interpolated_curve(self, equipment_library): + hp01 = equipment_library.get_equipment("hp01") + plain = plot_performance_curves(hp01, "heating") + fig = plot_performance_curves(hp01, "heating", highlight_lwt_C=45.0) + assert len(fig.data) == len(plain.data) + 2 # COP and capacity + # halfway between the 38 and 52 °C curves at the first outdoor temperature + cops = [hp01.performance_heating.leaving_supply_t[t].cop[0] for t in ("38", "52")] + assert _traces(fig, "highlight")[0].y[0] == pytest.approx(sum(cops) / 2) + + def test_fixed_capacity_drawn_when_no_capacity_curves(self, equipment_library): + fig = plot_performance_curves(equipment_library.get_equipment("hp02"), "heating") + assert "Fixed capacity" in [t.name for t in fig.data] + + def test_part_outside_operating_limits_is_dashed(self, equipment_library): + # hp01 at 52 °C is limited to -10 °C and above, its curve starts at -15 °C + fig = plot_performance_curves(equipment_library.get_equipment("hp01"), "heating") + solid = next(t for t in _traces(fig, "curve") if t.name.startswith("52")) + dashed = next(t for t in _traces(fig, "outside") if t.name.startswith("52")) + assert math.isnan(solid.y[0]) and not math.isnan(solid.y[-1]) + assert dashed.line.dash == "dash" + assert dashed.marker.symbol[0] == "circle-open" + # the 38 °C curve is within its limits everywhere + assert not [t for t in _traces(fig, "outside") if t.name.startswith("38")] + + def test_compare_to_draws_original_curves_behind(self, equipment_library): + from src.equipment import scale_performance + + hp01 = equipment_library.get_equipment("hp01") + scaled = scale_performance(hp01, "heating", cop_factor=0.9) + fig = plot_performance_curves(scaled, "heating", compare_to=hp01) + original = _traces(fig, "original") + assert len(original) == 2 * len(hp01.performance_heating.leaving_supply_t) + assert fig.data[0].meta == "original" + assert sum(t.showlegend is not False for t in original) == 1 + assert _traces(fig, "curve")[0].y[-1] == pytest.approx(0.9 * original[0].y[-1]) + + def test_compare_to_ignores_equipment_of_another_kind(self, equipment_library): + fig = plot_performance_curves( + equipment_library.get_equipment("hp01"), + "heating", + compare_to=equipment_library.get_equipment("hr01"), + ) + assert not _traces(fig, "original") + + def test_equipment_without_curves_gives_empty_figure(self, equipment_library): + fig = plot_performance_curves(equipment_library.get_equipment("bo01"), "heating") + assert len(fig.data) == 0 + assert fig.layout.annotations diff --git a/tests/test_workflow.py b/tests/test_workflow.py index 9574cff..fdf85e4 100644 --- a/tests/test_workflow.py +++ b/tests/test_workflow.py @@ -161,7 +161,7 @@ def options(component_id): assert figure_has_data(fig), f"scatter empty ({y_var}, {freq}, {unit})" -def _download(results_page, s: Session, unit: str) -> pd.DataFrame: +def _download(results_page, s: Session, unit: str) -> tuple[pd.DataFrame, pd.DataFrame]: payload = results_page.download_results( 1, s.session_data, @@ -170,10 +170,18 @@ def _download(results_page, s: Session, unit: str) -> pd.DataFrame: s.equipment_json, s.scenario_ids, s.emission_ids, + s.scenario_ids, ) + assert payload["filename"].startswith("decarb_") and f"_{unit}_" in payload["filename"] with zipfile.ZipFile(io.BytesIO(base64.b64decode(payload["content"]))) as zf: - csv_name = next(n for n in zf.namelist() if n.startswith("results_")) - return pd.read_csv(zf.open(csv_name), low_memory=False) + names = zf.namelist() + hourly = next(n for n in names if n.endswith("_hourly.csv")) + annual = next(n for n in names if n.endswith("_annual.csv")) + assert any(n.endswith("/settings_summary.txt") for n in names) + return ( + pd.read_csv(zf.open(hourly), low_memory=False), + pd.read_csv(zf.open(annual)), + ) def _run_workflow(results_page, layout, session: Session, exhaustive=False, download_units=()): @@ -183,9 +191,11 @@ def _run_workflow(results_page, layout, session: Session, exhaustive=False, down for ( unit ) in download_units: # the export is the slowest step, so only where it adds coverage - df = _download(results_page, session, unit) - hours = len(df) / len(session.scenario_ids) / len(session.emission_ids) + df, annual = _download(results_page, session, unit) + n_cases = len(session.scenario_ids) * len(session.emission_ids) + hours = len(df) / n_cases assert hours in (8760, 8784), f"download has {len(df)} rows" + assert len(annual) == n_cases, f"annual summary has {len(annual)} rows" finally: shutil.rmtree(session.folder, ignore_errors=True) diff --git a/utils/analytics.py b/utils/analytics.py new file mode 100644 index 0000000..5c47e3e --- /dev/null +++ b/utils/analytics.py @@ -0,0 +1,43 @@ +"""Usage tracking (Google Analytics 4 + UC Berkeley Siteimprove), injected into the page . + +Tracking only loads when ENABLE_ANALYTICS=true (set in the Dockerfile for production), +so local development runs do not show up in the statistics. +""" + +import os + +# GA4 measurement ID of the decarb-tool property; GA_MEASUREMENT_ID overrides it +# (an empty value disables GA and loads only Siteimprove). +GA_MEASUREMENT_ID = os.environ.get("GA_MEASUREMENT_ID", "G-3K9P3CNPWY") + +SITEIMPROVE_SRC = "https://siteimproveanalytics.com/js/siteanalyze_6294756.js" + +GTAG_SNIPPET = """ + + """ + +SITEIMPROVE_SNIPPET = f""" + """ + + +def analytics_enabled() -> bool: + return os.environ.get("ENABLE_ANALYTICS", "false").lower() == "true" + + +def build_analytics_head(ga_id: str | None) -> str: + """HTML for the tracking scripts; the GA block is skipped without a measurement ID.""" + snippets = [GTAG_SNIPPET.replace("__GA_ID__", ga_id)] if ga_id else [] + snippets.append(SITEIMPROVE_SNIPPET) + return "\n ".join(snippets) + + +def add_analytics(index_string: str, enabled: bool, ga_id: str | None) -> str: + """Insert the tracking scripts at the top of in a Dash index string.""" + if not enabled: + return index_string + return index_string.replace("", "\n " + build_analytics_head(ga_id), 1) diff --git a/utils/display_registry.py b/utils/display_registry.py index cc7b05d..20abcb9 100644 --- a/utils/display_registry.py +++ b/utils/display_registry.py @@ -77,9 +77,25 @@ def get_equipment_display_name(eq_id: str) -> str: "performance_curves": "Performance curves", } +# HR balancing source/sink value mappings +HR_WWHP_REJECTION_CONTROL_DISPLAY = { + "min_turndown": "Min turndown", + "max_heat_rejection": "Max heat rejection", +} +HR_WWHP_RECOVERY_CONTROL_DISPLAY = { + "min_turndown": "Min turndown", + "max_heat_recovery": "Max heat recovery", +} + # Fields that have enumerated values needing display mapping ENUM_VALUE_FIELDS = frozenset( - {"awhp_sizing_mode", "awhp_performance_model", "hr_wwhp_performance_model"} + { + "awhp_sizing_mode", + "awhp_performance_model", + "hr_wwhp_performance_model", + "hr_eac_rejection_control", + "hr_eac_recovery_control", + } ) @@ -105,6 +121,12 @@ def format_enum_value(value: str, field_name: str) -> str: if field_name == "hr_wwhp_performance_model": return HR_WWHP_PERFORMANCE_MODEL_DISPLAY.get(value, value) + if field_name == "hr_eac_rejection_control": + return HR_WWHP_REJECTION_CONTROL_DISPLAY.get(value, value) + + if field_name == "hr_eac_recovery_control": + return HR_WWHP_RECOVERY_CONTROL_DISPLAY.get(value, value) + return value diff --git a/utils/plotly_theme.py b/utils/plotly_theme.py index d839a9d..2db7a27 100644 --- a/utils/plotly_theme.py +++ b/utils/plotly_theme.py @@ -31,7 +31,7 @@ layout_colorway=extended_custom_colors, layout_plot_bgcolor="rgba(0,0,0,0)", layout_paper_bgcolor="rgba(0,0,0,0)", - layout_font=dict(family="Helvetica, sans-serif", size=14, color="black"), + layout_font=dict(family="Open Sans, Helvetica, sans-serif", size=14, color="black"), ) pio.templates["decarb-tool-theme"] = custom_template diff --git a/utils/tooltips.py b/utils/tooltips.py index 99919f9..bf43687 100644 --- a/utils/tooltips.py +++ b/utils/tooltips.py @@ -45,6 +45,10 @@ "equipment_docs": "Click to access the documentation on equipment options and scenarios.", "equipment_input_docs": "Click to access the documentation on equipment inputs.", }, + # --- Equipment Manager Page --- + "equipment_manager": { + "docs": "Click to access the documentation on equipment.", + }, # --- Emissions Page --- "emissions": { "emissions_docs": "Click to access the documentation on emissions options and scenarios.", diff --git a/utils/units.py b/utils/units.py index 6a5a30c..51053eb 100644 --- a/utils/units.py +++ b/utils/units.py @@ -1,12 +1,14 @@ # any constants used in the analysis # unit conversions # all are multiplied, right to left -ton_to_W = 12000 * 0.293 # refrigerant-ton to W +BTUh_to_W = ( + 1055.05585262 / 3600 +) # BTU/hr to W (IT BTU, ≈ 0.29307); every BTU factor derives from this +W_to_BTUh = 1 / BTUh_to_W # ≈ 3.41214 +BTU_to_Wh = BTUh_to_W # same factor: BTU to Wh is BTU/h to W +Wh_to_BTU = W_to_BTUh +ton_to_W = 12000 * BTUh_to_W # refrigerant-ton to W (≈ 3516.85) W_to_ton = 1 / ton_to_W -BTUh_to_W = 0.293 # BTU/hr to W -W_to_BTUh = 1 / BTUh_to_W -Wh_to_BTU = 3.412 -BTU_to_Wh = 1 / Wh_to_BTU lbs_to_ton = 0.454 / 1000 # lbs (e.g. of CO2) to metric tons ton_to_lbs = 1 / lbs_to_ton lb_to_kg = 0.454 # lbs (e.g. of CO2) to metric tons @@ -40,8 +42,16 @@ def Wh_to_kWh(Wh): return Wh / 1000 +def kWh_to_Wh(kWh): + return kWh * 1000 + + def Wh_to_BTUh(Wh): - return Wh * 3.412 + return Wh * Wh_to_BTU + + +def BTUh_to_Wh(BTUh): + return BTUh * BTU_to_Wh def kg_to_lbs(kg): @@ -247,6 +257,8 @@ def sqft_to_sqm(sqft): "hhw_W": ("power", "HHW Load"), "hhw_rem_W": ("power", "HHW Remaining"), "hr_hhw_W": ("power", "HR HHW Output"), + "hr_eac_h_W": ("power", "Exhaust Air Coil Heat Rejection"), + "hr_eac_c_W": ("power", "Exhaust Air Coil Heat Recovery"), "awhp_hhw_W": ("power", "AWHP HHW Output"), "boiler_hhw_W": ("power", "Boiler HHW Output"), "res_hhw_W": ("power", "Resistance HHW Output"), @@ -327,15 +339,25 @@ def sqft_to_sqm(sqft): "hr_wwhp_refrigerant": (None, "HR-WWHP Refrigerant"), "awhp_refrigerant": (None, "AWHP Refrigerant"), # === Emission Scenario Parameters === - "lrmer_co2e": (None, "LRMER CO₂e"), - "srmer_co2e": (None, "SRMER CO₂e"), - "aer_load_co2e": (None, "AER Load CO₂e"), + "lrmer_co2e": ("emissions_rate", "LRMER CO₂e"), + "srmer_co2e": ("emissions_rate", "SRMER CO₂e"), + "aer_load_co2e": ("emissions_rate", "AER Load CO₂e"), "shortrun_weighting": (None, "Short-run Weighting"), "year": (None, "Year"), # === Scenario Identifiers === "em_scen_id": (None, "Emission Scenario ID"), "eq_scen_id": (None, "Equipment Scenario ID"), "eq_scen_name": (None, "Equipment Scenario"), + # === Results export only (src/export.py) === + "eq_scen_slot": (None, "Equipment Scen. #"), + "em_scen_letter": (None, "Emission Scen."), + "em_scen_name": (None, "Emission Scenario"), + "em_year": (None, "Emission Year"), + "em_grid_scenario": (None, "Grid Scenario"), + "em_elec_source": (None, "Elec. Emission Source"), + "em_emission_type": (None, "Emission Type"), + "annual_heating_Wh": ("energy", "Annual Heating Load"), + "annual_cooling_Wh": ("energy", "Annual Cooling Load"), } @@ -367,11 +389,10 @@ def sqft_to_sqm(sqft): (1e3, 1e3, "kWh"), # >= 1 kWh (in Wh) → kWh ], "IP": [ - # 1 Wh = 3.412 BTU; kBTU = 1e3 BTU - # Threshold: 1 kBTU = 1e3 BTU = 1e3/3.412 Wh ≈ 293.083 Wh - # Scale: divide Wh by (1e3/3.412) to get kBTU - # (1e3 / 3.412, 1e3 / 3.412, "kBTU"), - (1e3 / 3.412, 1e3 / 3.412, "kBTU"), + # kBTU = 1e3 BTU + # Threshold: 1 kBTU = 1e3 * BTU_to_Wh ≈ 293.07 Wh + # Scale: divide Wh by (1e3 * BTU_to_Wh) to get kBTU + (1e3 * BTU_to_Wh, 1e3 * BTU_to_Wh, "kBTU"), ], }, "energy_electric": { @@ -394,10 +415,9 @@ def sqft_to_sqm(sqft): (1e3, 1e3, "kW"), # >= 1 kW (in W) → kW ], "IP": [ - # 1 W = 3.412 BTU/h; kBTU/h = 1e3 BTU/h - # Threshold: 1 kBTU/h = 1e3/3.412 W ≈ 293.083 W - # (1e3 / 3.412, 1e3 / 3.412, "kBTU/h"), - (1e3 / 3.412, 1e3 / 3.412, "kBTU/h"), + # kBTU/h = 1e3 BTU/h + # Threshold: 1 kBTU/h = 1e3 * BTUh_to_W ≈ 293.07 W + (1e3 * BTUh_to_W, 1e3 * BTUh_to_W, "kBTU/h"), ], }, "power_cooling": { @@ -506,6 +526,17 @@ def get_display_unit(category: str, unit_mode: str) -> str: return UNIT_MAP[category][unit_mode]["unit"] +def get_inverse_converter(category: str, unit_mode: str): + """Conversion function from the display unit back to the base unit (inverse of get_converter). + + Temperature is the only affine conversion; every other category is a plain factor. + """ + if category == "temperature": + return F_to_C if unit_mode == "IP" else (lambda x: x) + factor = get_converter(category, unit_mode)(1.0) + return lambda x: x / factor + + def get_base_unit(category: str) -> str: """Get the base (internal storage) unit for a category.