buildingcalibration 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. buildingcalibration/__init__.py +63 -0
  2. buildingcalibration/_logging.py +72 -0
  3. buildingcalibration/calibration/__init__.py +79 -0
  4. buildingcalibration/calibration/building_loader.py +305 -0
  5. buildingcalibration/calibration/calibration.py +110 -0
  6. buildingcalibration/calibration/constants.py +44 -0
  7. buildingcalibration/calibration/district_list.py +282 -0
  8. buildingcalibration/calibration/parameters.py +211 -0
  9. buildingcalibration/calibration/processing.py +509 -0
  10. buildingcalibration/calibration/results.py +131 -0
  11. buildingcalibration/calibration/simulation.py +322 -0
  12. buildingcalibration/clustering/__init__.py +61 -0
  13. buildingcalibration/clustering/clustering.py +460 -0
  14. buildingcalibration/clustering/unreliable_districts.py +342 -0
  15. buildingcalibration/plots/__init__.py +51 -0
  16. buildingcalibration/plots/_saving.py +47 -0
  17. buildingcalibration/plots/static_calibration.py +268 -0
  18. buildingcalibration/plots/validation.py +1542 -0
  19. buildingcalibration/seeding.py +108 -0
  20. buildingcalibration/validation/__init__.py +202 -0
  21. buildingcalibration/validation/aggregation.py +511 -0
  22. buildingcalibration/validation/config.py +371 -0
  23. buildingcalibration/validation/constants.py +112 -0
  24. buildingcalibration/validation/metrics.py +455 -0
  25. buildingcalibration/validation/simulation_io.py +453 -0
  26. buildingcalibration/validation/validator.py +533 -0
  27. buildingcalibration-0.1.0.dist-info/METADATA +231 -0
  28. buildingcalibration-0.1.0.dist-info/RECORD +31 -0
  29. buildingcalibration-0.1.0.dist-info/WHEEL +5 -0
  30. buildingcalibration-0.1.0.dist-info/licenses/LICENSE +27 -0
  31. buildingcalibration-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,63 @@
1
+ """District-scale static calibration, validation and clustering.
2
+
3
+ This package holds the *annual/static* half of the building-energy model
4
+ family: calibrating a building stock against measured consumption, decomposing
5
+ the residual error, and reducing a national stock to representative districts.
6
+ The hourly dynamic simulation lives in ``building_eload``; there is no import
7
+ relationship in either direction — the two are coupled only through parquet
8
+ data contracts on disk.
9
+
10
+ Subpackages
11
+ -----------
12
+ ``buildingcalibration.calibration``
13
+ Annual static calibration of the building stock over ``buildingmodel``
14
+ (:class:`~buildingcalibration.calibration.StaticSimulation`), plus building
15
+ footprint loading and representative-district selection.
16
+ ``buildingcalibration.validation``
17
+ Eq. 5 error decomposition against measured ORE / Enedis consumption
18
+ (:class:`~buildingcalibration.validation.Validation`).
19
+ ``buildingcalibration.clustering``
20
+ Representative-district clustering
21
+ (:func:`~buildingcalibration.clustering.cluster_districts`) and
22
+ unreliable-district screening.
23
+ ``buildingcalibration.plots``
24
+ Figures for the calibration and validation stages (imported explicitly, so
25
+ ``matplotlib`` is only loaded when you ask for it).
26
+
27
+ Doctrine
28
+ --------
29
+ **No path registry, frames first.** Nothing here resolves a filesystem path at
30
+ import time. Pipeline intermediates (dynamic-simulation results, clustering
31
+ tables, the unreliable-district list) are passed in as in-memory frames or as
32
+ explicit paths, with no default; external open data (BDTOPO, IRIS districts,
33
+ ORE annual consumption, Enedis measured load curves) is fetched through
34
+ ``buildingdata`` getters, which own the download, cache and vintage. A clean
35
+ checkout therefore needs no ``data/`` tree.
36
+
37
+ Examples
38
+ --------
39
+ >>> from buildingcalibration import StaticParameters, StaticSimulation # doctest: +SKIP
40
+ >>> results = StaticSimulation("751010101", StaticParameters(n_inference=5)).run() # doctest: +SKIP
41
+ """
42
+
43
+ from buildingcalibration.calibration import (
44
+ BuildingLoader,
45
+ StaticParameters,
46
+ StaticResults,
47
+ StaticSimulation,
48
+ )
49
+ from buildingcalibration.clustering import ClusteringResult, cluster_districts
50
+ from buildingcalibration.validation import Validation
51
+
52
+ __version__ = "0.1.0"
53
+
54
+ __all__ = [
55
+ "StaticSimulation",
56
+ "StaticParameters",
57
+ "StaticResults",
58
+ "BuildingLoader",
59
+ "Validation",
60
+ "cluster_districts",
61
+ "ClusteringResult",
62
+ "__version__",
63
+ ]
@@ -0,0 +1,72 @@
1
+ """Console logging setup for the package's own logger tree.
2
+
3
+ Copied verbatim (bar the logger name) from the shared logging helper of the
4
+ model family's original single-package layout, when the calibration modules
5
+ were extracted from ``building_eload``'s core in 0.1.0. The two packages have
6
+ no import relationship, so the helper is duplicated rather than shared: it is
7
+ ~30 lines of handler wiring, and a dependency edge between the dynamic and
8
+ static halves would exist for nothing else.
9
+ """
10
+
11
+ import logging
12
+ import sys
13
+
14
+ import colorlog
15
+
16
+
17
+ def setup_logger(level=logging.INFO, capture_buildingmodel=False):
18
+ """Attach a colourised console handler to the ``buildingcalibration`` logger.
19
+
20
+ Args:
21
+ level: logging level for both the logger and its console handler.
22
+ capture_buildingmodel: also route the ``buildingmodel`` logger through
23
+ the same handler (its static-inference messages then interleave
24
+ with the calibration loop's own).
25
+ """
26
+ logger_name = "buildingcalibration"
27
+
28
+ # --- Main application logger ---
29
+ logger = logging.getLogger(logger_name)
30
+
31
+ # Remove existing handlers to avoid duplicates
32
+ for handler in logger.handlers[:]:
33
+ logger.removeHandler(handler)
34
+
35
+ logger.setLevel(level)
36
+ logger.propagate = False # Prevent propagation to the root logger
37
+
38
+ # --- Colored formatter configuration ---
39
+ log_colors_config = {
40
+ "DEBUG": "cyan",
41
+ "INFO": "green",
42
+ "WARNING": "yellow",
43
+ "ERROR": "red",
44
+ "CRITICAL": "bold_red",
45
+ }
46
+
47
+ formatter = colorlog.ColoredFormatter(
48
+ "%(asctime)s | %(name)-20s | %(log_color)s%(levelname)-8s%(reset)s | %(message)s",
49
+ datefmt="%Y-%m-%d %H:%M:%S",
50
+ log_colors=log_colors_config,
51
+ )
52
+
53
+ # Create console handler
54
+ console_handler = logging.StreamHandler(sys.stdout)
55
+ console_handler.setFormatter(formatter)
56
+ console_handler.setLevel(level)
57
+
58
+ logger.addHandler(console_handler)
59
+
60
+ # --- Optional: capture logs from 'buildingmodel' package ---
61
+ if capture_buildingmodel:
62
+ bm_logger = logging.getLogger("buildingmodel")
63
+
64
+ # Remove existing handlers to prevent duplicate logs
65
+ for handler in bm_logger.handlers[:]:
66
+ bm_logger.removeHandler(handler)
67
+
68
+ bm_logger.setLevel(level)
69
+ bm_logger.addHandler(console_handler)
70
+
71
+ # Disable propagation to avoid double logging via root
72
+ bm_logger.propagate = False
@@ -0,0 +1,79 @@
1
+ """Annual static calibration of a building stock over ``buildingmodel``.
2
+
3
+ Façade for the calibration package: the calibration loop itself (a single
4
+ 1035-line ``core/static_simulation.py`` in the model family's original
5
+ single-package layout, since split into cohesive sub-modules) plus the two
6
+ stock-selection helpers it needs. Extracted from ``building_eload``'s core in
7
+ 0.1.0; every name the original façade exported is exported here unchanged.
8
+
9
+ ====================================== =====================================
10
+ Sub-module Responsibility
11
+ ====================================== =====================================
12
+ :mod:`~.constants` Usage vocabulary, unit conversions
13
+ :mod:`~.parameters` :class:`StaticParameters` run configuration
14
+ :mod:`~.results` :class:`StaticResults`, :class:`BuildingModelResults`, parquet I/O
15
+ :mod:`~.simulation` :class:`StaticSimulation` orchestrator
16
+ :mod:`~.processing` :class:`StaticProcessor` calibration + non-residential
17
+ :mod:`~.calibration` Paper Eq. 4 gap expressions (standalone)
18
+ :mod:`~.building_loader` :class:`BuildingLoader` -- district footprints via ``buildingdata``
19
+ :mod:`~.district_list` Medoid (representative) district selection
20
+ ====================================== =====================================
21
+
22
+ No module here evaluates a filesystem path at import time: pipeline
23
+ intermediates are passed in as frames or explicit paths, and external open data
24
+ (BDTOPO footprints, IRIS districts, the ORE annual district consumption) comes
25
+ from ``buildingdata`` getters.
26
+
27
+ Examples
28
+ --------
29
+ >>> from buildingcalibration.calibration import ( # doctest: +SKIP
30
+ ... StaticParameters, StaticSimulation
31
+ ... )
32
+ >>> results = StaticSimulation("751010101", StaticParameters(n_inference=5)).run() # doctest: +SKIP
33
+ """
34
+
35
+ from buildingcalibration.calibration.building_loader import BuildingLoader
36
+ from buildingcalibration.calibration.calibration import (
37
+ corrected_gap_expression,
38
+ relative_gap_expression,
39
+ )
40
+ from buildingcalibration.calibration.constants import (
41
+ KWH_TO_MWH_CONVERSION,
42
+ NON_RESIDENTIAL_USAGE,
43
+ USAGE_DICT,
44
+ USAGE_OPEN_DATA_MAPPING,
45
+ )
46
+ from buildingcalibration.calibration.district_list import (
47
+ get_national_representative_districts,
48
+ get_regional_representative_districts,
49
+ get_representative_districts,
50
+ get_representative_feeders_districts,
51
+ )
52
+ from buildingcalibration.calibration.parameters import StaticParameters
53
+ from buildingcalibration.calibration.processing import StaticProcessor
54
+ from buildingcalibration.calibration.results import BuildingModelResults, StaticResults
55
+ from buildingcalibration.calibration.simulation import StaticSimulation
56
+
57
+ __all__ = [
58
+ # Public API (README + workflow repo + contract tests)
59
+ "StaticParameters",
60
+ "StaticSimulation",
61
+ "StaticResults",
62
+ "BuildingModelResults",
63
+ "StaticProcessor",
64
+ # Building stock loading
65
+ "BuildingLoader",
66
+ # Representative-district selection (clustering output consumers)
67
+ "get_representative_districts",
68
+ "get_representative_feeders_districts",
69
+ "get_national_representative_districts",
70
+ "get_regional_representative_districts",
71
+ # Calibration gap (paper Eq. 4)
72
+ "corrected_gap_expression",
73
+ "relative_gap_expression",
74
+ # Constants (historically module-level in core/static_simulation.py)
75
+ "KWH_TO_MWH_CONVERSION",
76
+ "NON_RESIDENTIAL_USAGE",
77
+ "USAGE_DICT",
78
+ "USAGE_OPEN_DATA_MAPPING",
79
+ ]
@@ -0,0 +1,305 @@
1
+ # building_loader.py
2
+
3
+ """Loading the building footprints of one IRIS district.
4
+
5
+ Both reference datasets -- the IRIS district layer and the BDTOPO ``batiment``
6
+ footprints -- are **external open data**, so they are obtained through
7
+ ``buildingdata`` (:func:`buildingdata.get_districts`,
8
+ :func:`buildingdata.get_bdtopo`), which owns the download, the cache and the
9
+ vintage.
10
+
11
+ .. note::
12
+ There is no ``DEFAULT_BUILDING_FOOTPRINT_FOLDER``; the original
13
+ single-package layout had one (``data_path["bdtopo"]``, evaluated at import
14
+ time) and it was removed before the extraction. A local BDTOPO mirror
15
+ is still supported, but only when the caller points at it explicitly with
16
+ ``building_footprint_folder``; with nothing passed the footprints come from
17
+ ``buildingdata``.
18
+ """
19
+
20
+ import logging
21
+ import warnings
22
+ from pathlib import Path
23
+ from typing import Optional
24
+
25
+ import geopandas as gpd
26
+ from shapely import geometry
27
+
28
+ import buildingdata
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ # -------------------------------------------------------
34
+ # buildingdata consumption-boundary contracts (fast-fail)
35
+ # -------------------------------------------------------
36
+ #
37
+ # The loader reads two reference datasets through ``buildingdata`` (or a local
38
+ # mirror): the IRIS district layer and the BDTOPO ``batiment`` footprints. Both
39
+ # are indexed *by name* here and downstream, so an upstream schema/unit revision
40
+ # (renamed join key, CRS switched to degrees) would otherwise surface as a deep
41
+ # KeyError or a silently wrong intersection area. These constants + the
42
+ # ``_validate_*`` helpers assert the documented contract at the load boundary.
43
+
44
+ # IRIS district reference frame -- ``buildingdata.get_districts()`` (or a local
45
+ # districts parquet). Contract (buildingdata 0.2.0): EPSG:2154 GeoDataFrame with
46
+ # columns district, city, city_name, city_group, department, region,
47
+ # has_network_city_level, has_network_grdf_data, geometry. The loader is
48
+ # load-bearing on ``district`` (the join key), ``region`` (selects the regional
49
+ # ``BDTOPO_R<region>.gpkg`` file, must be int-castable) and ``geometry``.
50
+ _REQUIRED_DISTRICT_COLUMNS = ("district", "region", "geometry")
51
+
52
+ # BDTOPO_V3 ``batiment`` footprints -- ``buildingdata.get_bdtopo(district_id)``
53
+ # (live IGN Géoplateforme WFS, no fixed vintage) or a local ``BDTOPO_R*.gpkg``
54
+ # mirror. Raw French attribute names are preserved. Load-bearing subset the
55
+ # eload pipeline consumes downstream: ``geometry`` (footprint area + the
56
+ # intersection filter), ``hauteur`` (m; buildingmodel renames -> height),
57
+ # ``nombre_de_logements`` (dwelling count; -> dwelling_count),
58
+ # ``nombre_d_etages`` (floor count), ``usage_1``/``usage_2`` (BDTOPO usage
59
+ # labels) and ``cleabs`` (the stable building id used as ``name``). Note
60
+ # ``get_bdtopo`` only validates geometry/hauteur/nombre_de_logements/usage_1 at
61
+ # fetch; the local-gpkg path is unvalidated upstream, so this boundary checks
62
+ # the full downstream-required set for *both* sources.
63
+ _REQUIRED_BUILDING_COLUMNS = (
64
+ "geometry",
65
+ "cleabs",
66
+ "hauteur",
67
+ "nombre_de_logements",
68
+ "nombre_d_etages",
69
+ "usage_1",
70
+ "usage_2",
71
+ )
72
+
73
+ # BDTOPO / IRIS geometries are published in RGF93 / Lambert-93 (EPSG:2154), a
74
+ # projected CRS in **metres**. ``_filter_buildings_on_bounds`` computes
75
+ # intersection *area* ratios and downstream derives footprint area in m^2, both
76
+ # of which assume planar metres; a degrees CRS (EPSG:4326) would silently yield
77
+ # meaningless areas rather than crash.
78
+ _EXPECTED_CRS_EPSG = 2154
79
+
80
+
81
+ def _validate_schema(frame, required, dataset, accessor):
82
+ """Raise ``ValueError`` if ``frame`` is missing any required column."""
83
+ columns = list(frame.columns)
84
+ missing = [c for c in required if c not in columns]
85
+ if missing:
86
+ raise ValueError(
87
+ f"{dataset}: missing required column(s) {missing}. "
88
+ f"Got columns {columns}. The upstream schema may have changed "
89
+ f"(renamed/dropped column) or the wrong vintage was fetched; "
90
+ f"check {accessor}."
91
+ )
92
+
93
+
94
+ def _validate_crs(frame, dataset, accessor):
95
+ """Raise ``ValueError`` if the frame carries a CRS other than EPSG:2154.
96
+
97
+ A ``None`` CRS is left to pass (synthetic frames / mirrors that drop CRS
98
+ metadata cannot be judged); only a *set* CRS that is not the expected
99
+ projected metres system is a hard error, because it silently corrupts every
100
+ area-based computation.
101
+ """
102
+ crs = getattr(frame, "crs", None)
103
+ if crs is None:
104
+ return
105
+ epsg = crs.to_epsg()
106
+ if epsg is not None and epsg != _EXPECTED_CRS_EPSG:
107
+ raise ValueError(
108
+ f"{dataset}: geometry CRS is EPSG:{epsg}, expected "
109
+ f"EPSG:{_EXPECTED_CRS_EPSG} (RGF93 / Lambert-93, metres). "
110
+ f"Intersection-share and footprint-area computations assume planar "
111
+ f"metres; a degrees CRS would silently corrupt them. Check "
112
+ f"{accessor}."
113
+ )
114
+
115
+
116
+ def _validate_districts(districts, accessor):
117
+ """Fast-fail on the IRIS district reference contract (schema + CRS + region).
118
+
119
+ ``region`` must be int-castable because ``_get_building_path`` does
120
+ ``int(district_data['region'].iloc[0])`` to pick the regional gpkg file.
121
+ """
122
+ dataset = "IRIS districts"
123
+ _validate_schema(districts, _REQUIRED_DISTRICT_COLUMNS, dataset, accessor)
124
+ _validate_crs(districts, dataset, accessor)
125
+ region = districts["region"].dropna()
126
+ if len(region) > 0:
127
+ try:
128
+ region.astype("int64")
129
+ except (ValueError, TypeError) as exc:
130
+ raise ValueError(
131
+ f"{dataset}: column 'region' is not integer-castable "
132
+ f"(dtype {districts['region'].dtype}); it selects the "
133
+ f"BDTOPO_R<region>.gpkg mirror file. Check {accessor}."
134
+ ) from exc
135
+
136
+
137
+ def _validate_buildings(buildings, accessor):
138
+ """Fast-fail on the BDTOPO ``batiment`` footprint contract (schema + CRS)."""
139
+ dataset = "BDTOPO batiment footprints"
140
+ _validate_schema(buildings, _REQUIRED_BUILDING_COLUMNS, dataset, accessor)
141
+ _validate_crs(buildings, dataset, accessor)
142
+
143
+
144
+ class BuildingLoader:
145
+ """Load buildings from a district and filter them based on intersection with the district geometry."""
146
+
147
+ INTERSECTION_THRESHOLD = 0.5
148
+ BUILDING_LAYER_NAME = "batiment"
149
+ GIS_ENGINE = "pyogrio"
150
+ BUILDING_FILE_PREFIX = "BDTOPO_R"
151
+ BUILDING_FILE_SUFFIX = ".gpkg"
152
+ DEFAULT_DISTRICT_DATA_FILE = None
153
+
154
+ def __init__(
155
+ self,
156
+ district_id: str,
157
+ district_data_file: str | Path | None = None,
158
+ building_footprint_folder: str | Path | None = None,
159
+ ):
160
+ """Configure the loader for one district.
161
+
162
+ Parameters
163
+ ----------
164
+ district_id:
165
+ IRIS code of the district whose buildings are loaded.
166
+ district_data_file:
167
+ Optional path to a districts GeoParquet mirror. Unset (default) ->
168
+ :func:`buildingdata.get_districts`.
169
+ building_footprint_folder:
170
+ Optional path to a local BDTOPO mirror holding
171
+ ``BDTOPO_R<region>.gpkg`` files. Unset (default) ->
172
+ :func:`buildingdata.get_bdtopo`. When set but the region's file is
173
+ absent, the loader still falls back to ``buildingdata``.
174
+ """
175
+
176
+ self.district_id = str(district_id)
177
+ self.district_data_file = (
178
+ Path(district_data_file)
179
+ if district_data_file is not None
180
+ else self.DEFAULT_DISTRICT_DATA_FILE
181
+ )
182
+ self.building_footprint_folder = (
183
+ Path(building_footprint_folder) if building_footprint_folder is not None else None
184
+ )
185
+ logger.debug(f"{self.logger_header} District data file: {self.district_data_file}.")
186
+ logger.debug(
187
+ f"{self.logger_header} Building footprint folder: {self.building_footprint_folder}."
188
+ )
189
+
190
+ @property
191
+ def logger_header(self):
192
+ if self.district_id is None:
193
+ return "[BuildingLoader]"
194
+ return f"[District {self.district_id}]"
195
+
196
+ # -------------------------------------------------------
197
+ # Main function
198
+ # -------------------------------------------------------
199
+
200
+ def load_buildings(self) -> Optional[gpd.GeoDataFrame]:
201
+ """Load buildings for a specific district."""
202
+ logger.info(f"{self.logger_header} Loading buildings.")
203
+
204
+ district_data = self._load_district(self.district_id)
205
+ if district_data.empty:
206
+ logger.warning(
207
+ f"{self.logger_header} District {self.district_id} not found in district file."
208
+ )
209
+ return None
210
+ district_geometry = self._get_district_geometry(district_data)
211
+ buildings = self._load_buildings_in_district_bounds(district_geometry, district_data)
212
+ _validate_buildings(buildings, self._buildings_accessor)
213
+ filtered_buildings = self._filter_buildings_on_bounds(buildings, district_geometry)
214
+ filtered_buildings["district"] = self.district_id
215
+
216
+ logger.info(f"{self.logger_header} Loaded {len(filtered_buildings)} buildings.")
217
+
218
+ return filtered_buildings
219
+
220
+ # -------------------------------------------------------
221
+ # Utilis
222
+ # -------------------------------------------------------
223
+
224
+ @property
225
+ def _districts_accessor(self) -> str:
226
+ if self.district_data_file is not None:
227
+ return f"the districts parquet {self.district_data_file}"
228
+ return "buildingdata.get_districts()"
229
+
230
+ @property
231
+ def _buildings_accessor(self) -> str:
232
+ if self.building_footprint_folder is None:
233
+ return f"buildingdata.get_bdtopo({self.district_id!r})"
234
+ return (
235
+ f"buildingdata.get_bdtopo({self.district_id!r}) or the local "
236
+ f"BDTOPO_R*.gpkg mirror under {self.building_footprint_folder}"
237
+ )
238
+
239
+ def _load_district(self, district_id: str) -> gpd.GeoDataFrame:
240
+ district_id = str(district_id)
241
+ if self.district_data_file is not None:
242
+ districts = gpd.read_parquet(self.district_data_file)
243
+ else:
244
+ districts = buildingdata.get_districts()
245
+
246
+ _validate_districts(districts, self._districts_accessor)
247
+
248
+ district_codes = districts["district"].astype(str).str.zfill(len(district_id))
249
+ return districts[district_codes == district_id]
250
+
251
+ @staticmethod
252
+ def _get_district_geometry(district_data: gpd.GeoDataFrame) -> geometry.Polygon:
253
+ return district_data["geometry"].iloc[0]
254
+
255
+ def _load_buildings_in_district_bounds(
256
+ self, district_geometry: geometry.Polygon, district_data: gpd.GeoDataFrame
257
+ ) -> gpd.GeoDataFrame:
258
+ bounds = district_geometry.convex_hull.bounds
259
+ building_path = self._get_building_path(district_data)
260
+
261
+ if building_path is None:
262
+ logger.debug(
263
+ f"{self.logger_header} No local BDTOPO mirror configured; "
264
+ "loading buildings through buildingdata."
265
+ )
266
+ return buildingdata.get_bdtopo(self.district_id)
267
+
268
+ if not building_path.exists():
269
+ logger.debug(
270
+ f"{self.logger_header} Local BDTOPO file {building_path} not found; "
271
+ "loading buildings through buildingdata."
272
+ )
273
+ return buildingdata.get_bdtopo(self.district_id)
274
+
275
+ with warnings.catch_warnings():
276
+ warnings.filterwarnings("ignore")
277
+ logger.debug(f"{self.logger_header} Loading buildings from {building_path}.")
278
+ return gpd.read_file(
279
+ building_path,
280
+ layer=self.BUILDING_LAYER_NAME,
281
+ engine=self.GIS_ENGINE,
282
+ bbox=bounds,
283
+ )
284
+
285
+ def _filter_buildings_on_bounds(
286
+ self, buildings: gpd.GeoDataFrame, district_geometry: geometry.Polygon
287
+ ) -> gpd.GeoDataFrame:
288
+ buildings["intersection_share"] = (
289
+ buildings["geometry"].intersection(district_geometry).area / buildings["geometry"].area
290
+ )
291
+ filtered_buildings = buildings.loc[
292
+ buildings.intersection_share >= self.INTERSECTION_THRESHOLD
293
+ ].copy()
294
+ filtered_buildings.drop(columns=["intersection_share"], inplace=True)
295
+ return filtered_buildings
296
+
297
+ def _get_building_path(self, district_data: gpd.GeoDataFrame) -> Optional[Path]:
298
+ """Return the mirror's regional gpkg path, or ``None`` when unconfigured."""
299
+ if self.building_footprint_folder is None:
300
+ return None
301
+ region_id = int(district_data["region"].iloc[0])
302
+ return (
303
+ self.building_footprint_folder
304
+ / f"{self.BUILDING_FILE_PREFIX}{region_id}{self.BUILDING_FILE_SUFFIX}"
305
+ )
@@ -0,0 +1,110 @@
1
+ """District calibration gap (paper **Eq. 4**) as standalone expressions.
2
+
3
+ The static stage runs the district several times ("iterations") with different
4
+ heating setpoints and picks the iteration whose simulated annual electricity
5
+ consumption best matches the measured open-data total, with a small quadratic
6
+ penalty pulling the choice toward the national reference setpoint.
7
+
8
+ Extracted from ``StaticProcessor._calibrate_results`` (task D2) so the two
9
+ halves of Eq. 4 are directly testable without a ``StaticProcessor``,
10
+ calibration file or BuildingModel run.
11
+
12
+ Reference
13
+ ---------
14
+ Chiche, Abdelouadoud, Cocchi, Girard, "A scalable activity-based and
15
+ physics-informed bottom-up model for residential electricity demand using open
16
+ data", *Energy and Buildings* (2026), Section 4.1, Eq. (4) -- **as corrected by
17
+ ``doc/erratum_eq4.md``**: the printed equation shows the penalty multiplied
18
+ into the raw gap, whereas the procedure that produced the published results
19
+ (R^2 = 0.944 over 200 districts) *adds* it. The additive form is what is
20
+ implemented here.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import polars as pl
26
+
27
+
28
+ def relative_gap_expression(
29
+ simulated_column: str = "annual_electricity_consumption",
30
+ measured_column: str = "open_data_consumption",
31
+ ) -> pl.Expr:
32
+ """Return the ``GAP_raw`` expression of **Eq. 4**.
33
+
34
+ .. math::
35
+
36
+ GAP_{raw} = \\frac{|E_{sim} - E_{meas}|}{E_{sim}}
37
+
38
+ Note the normalisation is by the **simulated** consumption, not the
39
+ measured one (clarified in ``doc/erratum_eq4.md`` §2).
40
+
41
+ Degenerate cases, in evaluation order:
42
+
43
+ * both zero -> ``0.0`` (nothing to fit),
44
+ * measured zero only -> ``1.0`` (a full relative gap, not infinity),
45
+ * simulated zero only -> ``0.0`` (the gap is not evaluated as infinite).
46
+
47
+ Parameters
48
+ ----------
49
+ simulated_column:
50
+ Column holding the district's simulated annual electricity consumption
51
+ for that iteration (``E_sim``).
52
+ measured_column:
53
+ Column holding the measured open-data annual consumption (``E_meas``).
54
+
55
+ Returns
56
+ -------
57
+ pl.Expr
58
+ Unaliased expression; callers alias it (historically ``relative_gap``).
59
+ """
60
+ return (
61
+ pl.when((pl.col(simulated_column) == 0.0) & (pl.col(measured_column) == 0.0))
62
+ .then(0.0)
63
+ .when(pl.col(measured_column) == 0.0)
64
+ .then(1.0)
65
+ .when(pl.col(simulated_column) == 0.0)
66
+ .then(0.0)
67
+ .otherwise(
68
+ abs(pl.col(simulated_column) - pl.col(measured_column)) / pl.col(simulated_column)
69
+ )
70
+ )
71
+
72
+
73
+ def corrected_gap_expression(
74
+ calibration_coefficient: float,
75
+ optimal_heating_setpoint: float,
76
+ relative_gap_column: str = "relative_gap",
77
+ setpoint_column: str = "actual_heating_set_point",
78
+ ) -> pl.Expr:
79
+ """Return the penalised gap ``GAP`` of **Eq. 4** (corrected, additive form).
80
+
81
+ .. math::
82
+
83
+ GAP = GAP_{raw} + C_{factor}\\,(T_{ref} - T_{setpoint})^2
84
+
85
+ with ``C_factor = 0.02`` and ``T_ref = 19 °C`` by default (see
86
+ :class:`~buildingcalibration.calibration.StaticParameters`). The
87
+ quadratic term is a regularisation: when two iterations fit the measured
88
+ consumption similarly well it prefers the one closer to the national
89
+ average setpoint, without overriding a materially better fit elsewhere.
90
+
91
+ Parameters
92
+ ----------
93
+ calibration_coefficient:
94
+ ``C_factor``, the weight of the setpoint penalty.
95
+ optimal_heating_setpoint:
96
+ ``T_ref``, the national reference heating setpoint in °C.
97
+ relative_gap_column:
98
+ Column holding ``GAP_raw`` (see :func:`relative_gap_expression`).
99
+ setpoint_column:
100
+ Column holding the iteration's actual heating setpoint ``T_setpoint``.
101
+
102
+ Returns
103
+ -------
104
+ pl.Expr
105
+ Unaliased expression; the smallest value across iterations wins.
106
+ """
107
+ return (
108
+ pl.col(relative_gap_column)
109
+ + calibration_coefficient * (optimal_heating_setpoint - pl.col(setpoint_column)) ** 2
110
+ )
@@ -0,0 +1,44 @@
1
+ """Usage vocabulary and unit conversions for the static simulation.
2
+
3
+ These names were module-level constants of the monolithic
4
+ ``core/static_simulation.py`` of the model family's original single-package
5
+ layout (extracted from ``building_eload``'s core in 0.1.0); they are
6
+ re-exported unchanged by :mod:`buildingcalibration.calibration`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ KWH_TO_MWH_CONVERSION = 1e3
12
+
13
+ #: BDTOPO French usage label -> internal usage key.
14
+ USAGE_DICT = {
15
+ "Résidentiel": "residential",
16
+ "Agricole": "agriculture",
17
+ "Annexe": "annex",
18
+ "Commercial et services": "commercial",
19
+ "Indifférencié": "unknown",
20
+ "Industriel": "industrial",
21
+ "Religieux": "religious",
22
+ "Sportif": "sport",
23
+ }
24
+
25
+ #: BDTOPO usage labels treated as non-residential.
26
+ NON_RESIDENTIAL_USAGE = [
27
+ "Agricole",
28
+ "Commercial et services",
29
+ "Industriel",
30
+ "Religieux",
31
+ "Sportif",
32
+ ]
33
+
34
+ #: Internal usage key -> ORE/Enedis open-data sector (``code_grand_secteur``).
35
+ USAGE_OPEN_DATA_MAPPING = {
36
+ "residential": "RESIDENTIEL",
37
+ "agriculture": "AGRICULTURE",
38
+ "commercial": "TERTIAIRE",
39
+ "religious": "TERTIAIRE",
40
+ "sport": "TERTIAIRE",
41
+ "industrial": "INDUSTRIE",
42
+ "annex": "TERTIAIRE",
43
+ "unknown": "INCONNU",
44
+ }