diff --git a/CHANGELOG.md b/CHANGELOG.md index 44876b1..5245092 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,9 +25,38 @@ Removed. `scripts/bump_version.py` turns them into a release section. - 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) ### Changed +- 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 @@ -47,6 +76,9 @@ Removed. `scripts/bump_version.py` turns them into a release section. - 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 ### Fixed @@ -54,6 +86,8 @@ Removed. `scripts/bump_version.py` turns them into a release section. 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) ## [0.1.0] - 2026-10-13 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/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 54b2729..3fe6dd4 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 @@ -1051,6 +1051,64 @@ def edit_equipment_modal(): ), ], ), + 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="Heat pump sizing", labelPosition="center"), dmc.Stack( [ 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/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..7cd769c 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( @@ -1220,6 +1223,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"), @@ -1302,6 +1355,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/src/config.py b/src/config.py index c7b659d..cc43e9b 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): diff --git a/src/energy.py b/src/energy.py index cd85c28..122e212 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", @@ -67,9 +52,10 @@ def _equipment_data_validation(library: EquipmentLibrary, scenario_ids: list[str 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 +66,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 +113,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 +149,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: " diff --git a/src/equipment.py b/src/equipment.py index 0a4e630..744f097 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: @@ -115,6 +129,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 +670,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 +730,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/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/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/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..606fdd0 100644 --- a/tests/test_energy_regression.py +++ b/tests/test_energy_regression.py @@ -21,7 +21,12 @@ 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, + duplicate_equipment, + load_library, + scale_performance, +) from src.loads import StandardLoad from src.metadata import Metadata @@ -220,3 +225,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_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/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 a868812..c044503 100644 --- a/utils/units.py +++ b/utils/units.py @@ -516,6 +516,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.