heattwin3d 0.3.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.
heattwin3d/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """HeatTwin3D - Planning law in 3D.
2
+
3
+ Turns XPlanGML development plans (Bebauungspläne, XPlanung 5.x) into
4
+ auditable OGC 3D Tiles 1.1 "regulatory envelopes" with per-feature
5
+ provenance metadata (EXT_mesh_features + EXT_structural_metadata).
6
+ """
7
+
8
+ __version__ = "0.3.0"
9
+
10
+ #: Default storey height in metres used to convert "Z" (number of full
11
+ #: storeys, Vollgeschosse) into a height and existing heights into storeys.
12
+ DEFAULT_STOREY_HEIGHT_M = 3.0
13
+
14
+ #: Legal reference attached to every zone record.
15
+ LEGAL_REF = "BauGB §9 Abs.1 Nr.1; BauNVO §16-§20"
heattwin3d/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
heattwin3d/citygml.py ADDED
@@ -0,0 +1,244 @@
1
+ """Streaming parser for German AdV LoD2 CityGML (CityGML 1.0 AdV profile; CityGML 2.0 tolerated).
2
+
3
+ Reads ``bldg:Building`` (and nested ``bldg:BuildingPart``) one at a time with
4
+ ``lxml.etree.iterparse`` and clears each object after use, so state-wide tiles
5
+ of several hundred MB stream in constant memory.
6
+
7
+ Geometry source
8
+ ---------------
9
+ AdV LoD2 files carry the real polygons in the thematic boundary surfaces
10
+ (``bldg:boundedBy/bldg:RoofSurface|WallSurface|GroundSurface|ClosureSurface/
11
+ lod2MultiSurface``); ``lod2Solid`` only references them by ``xlink:href``.
12
+ We therefore read the boundary surfaces. Only if a building (part) has *no*
13
+ boundary surface, inline polygons of ``lod2Solid`` / ``lod2MultiSurface`` are
14
+ used as surfaces of kind ``"other"`` (never both, so nothing is counted twice).
15
+
16
+ Security: files are untrusted. The parser resolves no entities, loads no DTD,
17
+ uses no network and keeps lxml's ``huge_tree`` protection on.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+ from typing import Iterator
25
+
26
+ import numpy as np
27
+ from lxml import etree
28
+
29
+ _CITYGML = ("http://www.opengis.net/citygml/1.0", "http://www.opengis.net/citygml/2.0")
30
+ _BLDG = ("http://www.opengis.net/citygml/building/1.0", "http://www.opengis.net/citygml/building/2.0")
31
+ _GEN = ("http://www.opengis.net/citygml/generics/1.0", "http://www.opengis.net/citygml/generics/2.0")
32
+ _GML = "http://www.opengis.net/gml"
33
+ _XAL = "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"
34
+ _GML_ID = f"{{{_GML}}}id"
35
+
36
+ SURFACE_KINDS = {"RoofSurface": "roof", "WallSurface": "wall", "GroundSurface": "ground",
37
+ "ClosureSurface": "closure", "OuterCeilingSurface": "roof", "OuterFloorSurface": "ground"}
38
+
39
+
40
+ @dataclass
41
+ class Surface:
42
+ """One thematic boundary surface; ``polygons`` = list of rings lists [(n,3) exterior, holes...]."""
43
+ kind: str # roof | wall | ground | closure | other
44
+ gml_id: str
45
+ polygons: list[list[np.ndarray]] = field(default_factory=list)
46
+
47
+
48
+ @dataclass
49
+ class BuildingPart:
50
+ gml_id: str
51
+ roof_type: str | None
52
+ measured_height: float | None
53
+ surfaces: list[Surface] = field(default_factory=list)
54
+
55
+
56
+ @dataclass
57
+ class LoD2Building:
58
+ gml_id: str
59
+ function: str | None
60
+ roof_type: str | None
61
+ measured_height: float | None
62
+ generic: dict[str, str]
63
+ address: str
64
+ external_ref: str | None
65
+ parts: list[BuildingPart] # parts[0] is the Building itself (may have no surfaces)
66
+ source_file: str = ""
67
+
68
+ def all_surfaces(self) -> list[Surface]:
69
+ return [s for p in self.parts for s in p.surfaces]
70
+
71
+
72
+ def _ns(el) -> tuple[str, str]:
73
+ q = etree.QName(el)
74
+ return q.namespace or "", q.localname
75
+
76
+
77
+ def _is(el, names: tuple, local: str) -> bool:
78
+ ns, ln = _ns(el)
79
+ return ln == local and ns in names
80
+
81
+
82
+ def _parse_coords(ring_el) -> np.ndarray | None:
83
+ """gml:LinearRing with gml:posList (srsDimension 3) or a sequence of gml:pos."""
84
+ pl = ring_el.find(f"{{{_GML}}}posList")
85
+ if pl is not None and pl.text:
86
+ dim = int(pl.get("srsDimension") or pl.get("dimension") or 3)
87
+ v = np.array(pl.text.split(), dtype=np.float64)
88
+ else:
89
+ pos = ring_el.findall(f"{{{_GML}}}pos")
90
+ if not pos:
91
+ coords = ring_el.find(f"{{{_GML}}}coordinates") # GML 2 style "x,y,z x,y,z"
92
+ if coords is None or not coords.text:
93
+ return None
94
+ v = np.array(coords.text.replace(",", " ").split(), dtype=np.float64)
95
+ dim = 3
96
+ else:
97
+ dim = 3
98
+ v = np.array(" ".join(p.text or "" for p in pos).split(), dtype=np.float64)
99
+ if dim != 3 or len(v) % 3 or len(v) < 9:
100
+ return None
101
+ return v.reshape(-1, 3)
102
+
103
+
104
+ def _polygons(el) -> list[list[np.ndarray]]:
105
+ """All gml:Polygon below ``el`` -> list of [exterior, *interiors] (closing point kept)."""
106
+ out = []
107
+ for poly in el.iter(f"{{{_GML}}}Polygon"):
108
+ rings = []
109
+ ext = poly.find(f"{{{_GML}}}exterior")
110
+ if ext is None:
111
+ continue
112
+ lr = ext.find(f"{{{_GML}}}LinearRing")
113
+ r = _parse_coords(lr) if lr is not None else None
114
+ if r is None:
115
+ continue
116
+ rings.append(r)
117
+ for itr in poly.findall(f"{{{_GML}}}interior"):
118
+ lr = itr.find(f"{{{_GML}}}LinearRing")
119
+ r = _parse_coords(lr) if lr is not None else None
120
+ if r is not None:
121
+ rings.append(r)
122
+ out.append(rings)
123
+ return out
124
+
125
+
126
+ def _float(text) -> float | None:
127
+ try:
128
+ return float(text)
129
+ except (TypeError, ValueError):
130
+ return None
131
+
132
+
133
+ def _direct(el, names: tuple, local: str):
134
+ for c in el:
135
+ if isinstance(c.tag, str) and _is(c, names, local):
136
+ return c
137
+ return None
138
+
139
+
140
+ def _parse_part(el) -> BuildingPart:
141
+ rt = _direct(el, _BLDG, "roofType")
142
+ mh = _direct(el, _BLDG, "measuredHeight")
143
+ part = BuildingPart(el.get(_GML_ID, ""), rt.text.strip() if rt is not None and rt.text else None,
144
+ _float(mh.text) if mh is not None else None)
145
+ for c in el:
146
+ if not isinstance(c.tag, str):
147
+ continue
148
+ ns, ln = _ns(c)
149
+ if ns in _BLDG and ln == "boundedBy":
150
+ for s in c:
151
+ if not isinstance(s.tag, str):
152
+ continue
153
+ sns, sln = _ns(s)
154
+ if sns in _BLDG and sln in SURFACE_KINDS:
155
+ polys = _polygons(s)
156
+ if polys:
157
+ part.surfaces.append(Surface(SURFACE_KINDS[sln], s.get(_GML_ID, ""), polys))
158
+ if not part.surfaces: # fallback: inline geometry without thematic surfaces
159
+ for c in el:
160
+ if not isinstance(c.tag, str):
161
+ continue
162
+ ns, ln = _ns(c)
163
+ if ns in _BLDG and ln in ("lod2Solid", "lod2MultiSurface"):
164
+ polys = _polygons(c)
165
+ if polys:
166
+ part.surfaces.append(Surface("other", part.gml_id + "_" + ln, polys))
167
+ return part
168
+
169
+
170
+ def _address(el) -> str:
171
+ """Street + number, locality from xAL (CityGML core:Address)."""
172
+ out = []
173
+ for adr in el.iter(f"{{{_XAL}}}AddressDetails"):
174
+ street = adr.findtext(f".//{{{_XAL}}}ThoroughfareName") or ""
175
+ num = adr.findtext(f".//{{{_XAL}}}ThoroughfareNumber") or ""
176
+ loc = adr.findtext(f".//{{{_XAL}}}LocalityName") or ""
177
+ s = " ".join(v for v in (street.strip(), num.strip()) if v)
178
+ if loc.strip():
179
+ s = f"{s}, {loc.strip()}" if s else loc.strip()
180
+ if s and s not in out:
181
+ out.append(s)
182
+ return "; ".join(out)
183
+
184
+
185
+ def _parse_building(el, source_file: str) -> LoD2Building:
186
+ fn = _direct(el, _BLDG, "function")
187
+ generic = {}
188
+ for c in el:
189
+ if isinstance(c.tag, str) and _ns(c)[0] in _GEN and _ns(c)[1].endswith("Attribute"):
190
+ v = c.find("{*}value")
191
+ if c.get("name") and v is not None and v.text is not None:
192
+ generic[c.get("name")] = v.text.strip()
193
+ ext = None
194
+ for c in el:
195
+ if isinstance(c.tag, str) and _ns(c)[1] == "externalReference" and _ns(c)[0] in _CITYGML:
196
+ ext = (c.findtext("{*}externalObject/{*}name") or "").strip() or None
197
+ main = _parse_part(el)
198
+ parts = [main]
199
+ # BuildingPart may be nested (consistsOfBuildingPart/BuildingPart), parts of parts included
200
+ for bp in el.iter(*(f"{{{n}}}BuildingPart" for n in _BLDG)):
201
+ parts.append(_parse_part(bp))
202
+ # address: building level only (parts may repeat it)
203
+ adr_el = [c for c in el if isinstance(c.tag, str) and _ns(c)[1] == "address"]
204
+ address = "; ".join(a for a in (_address(a) for a in adr_el) if a)
205
+ rt_parts = [p.roof_type for p in parts if p.roof_type]
206
+ mh_parts = [p.measured_height for p in parts if p.measured_height is not None]
207
+ return LoD2Building(
208
+ gml_id=el.get(_GML_ID, ""), function=fn.text.strip() if fn is not None and fn.text else None,
209
+ roof_type=main.roof_type or (rt_parts[0] if len(set(rt_parts)) == 1 else
210
+ (";".join(dict.fromkeys(rt_parts)) if rt_parts else None)),
211
+ measured_height=main.measured_height if main.measured_height is not None
212
+ else (max(mh_parts) if mh_parts else None),
213
+ generic=generic, address=address, external_ref=ext, parts=parts, source_file=source_file)
214
+
215
+
216
+ def read_srs(path: str | Path) -> str | None:
217
+ """srsName of the first gml:Envelope (or any element with srsName) in the file header."""
218
+ for _, el in etree.iterparse(str(path), events=("start",), resolve_entities=False, no_network=True,
219
+ load_dtd=False, huge_tree=False):
220
+ if el.get("srsName"):
221
+ return el.get("srsName")
222
+ if _ns(el)[1] in ("Building", "cityObjectMember"):
223
+ return None
224
+ return None
225
+
226
+
227
+ def iter_buildings(path: str | Path) -> Iterator[LoD2Building]:
228
+ """Yield every top-level bldg:Building of a CityGML file (streaming)."""
229
+ path = Path(path)
230
+ tags = [f"{{{n}}}Building" for n in _BLDG]
231
+ ctx = etree.iterparse(str(path), events=("end",), tag=tags, resolve_entities=False, no_network=True,
232
+ load_dtd=False, huge_tree=False, remove_comments=True)
233
+ for _, el in ctx:
234
+ parent = el.getparent()
235
+ # top-level only: a Building nested in another Building does not exist in CityGML 1/2,
236
+ # but guard anyway
237
+ if parent is not None and any(_is(a, _BLDG, "Building") for a in el.iterancestors()):
238
+ continue
239
+ yield _parse_building(el, path.name)
240
+ el.clear()
241
+ # free already processed siblings (cityObjectMember wrappers)
242
+ target = parent if parent is not None and _ns(parent)[1] == "cityObjectMember" else el
243
+ while target.getparent() is not None and target.getprevious() is not None:
244
+ del target.getparent()[0]
heattwin3d/cli.py ADDED
@@ -0,0 +1,317 @@
1
+ """Command line interface.
2
+
3
+ python3 -m heattwin3d build --plan plan.gml --buildings buildings.geojson --out out/
4
+ python3 -m heattwin3d lod2 --gml-dir <LoD2 CityGML dir> --out out/lod2 [--heat-gpkg ..] [--buildings-gpkg ..]
5
+ python3 -m heattwin3d heat3d --lod2 out/lod2 --out out/heat3d --drilling .. --heat-areas .. --line-density ..
6
+ python3 -m heattwin3d schema # rewrite schema/xplan_zone.schema.json + schema/lod2_building.schema.json
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import shutil
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ from pyproj import Transformer
19
+ from shapely.geometry import mapping, shape
20
+ import shapely
21
+
22
+ from . import DEFAULT_STOREY_HEIGHT_M, LEGAL_REF, __version__
23
+ from .envelope import compute_plan, load_buildings
24
+ from .geo import LocalFrame
25
+ from .mesh import MeshBuilder
26
+ from .scenario import DEFAULT_SPECIFIC_DEMAND, heat_scenario, parse_buildout
27
+ from .schema import SCHEMA
28
+ from .tiles import check_tileset_contains_content, write_tileset
29
+
30
+ PKG_DIR = Path(__file__).resolve().parent
31
+ REPO_ROOT = PKG_DIR.parent
32
+
33
+
34
+ def _resource_dir(name: str) -> Path:
35
+ """viewer/ or schema/: next to the package (vendored layout) or in the project root."""
36
+ for base in (PKG_DIR, REPO_ROOT):
37
+ if (base / name).is_dir():
38
+ return base / name
39
+ return REPO_ROOT / name
40
+ # Cesium multiplies Cesium3DTileStyle colours with the material base colour, so materials are
41
+ # (near-)white: the viewer style decides the colour. Envelopes stay translucent in clients without styling.
42
+ ENVELOPE_COLOR = (1.0, 1.0, 1.0, 0.6)
43
+ BUILDING_COLOR = (0.9, 0.9, 0.88, 1.0)
44
+
45
+
46
+ def _buildings_geojson_25832(data: dict) -> dict:
47
+ """Return the FeatureCollection in EPSG:25832.
48
+
49
+ Accepts an explicit legacy ``crs`` member naming EPSG:25832, otherwise
50
+ assumes RFC 7946 WGS84 lon/lat if coordinates look geographic.
51
+ """
52
+ crs_name = str(((data.get("crs") or {}).get("properties") or {}).get("name", ""))
53
+ if "25832" in crs_name:
54
+ return data
55
+ feats = [f for f in data.get("features", []) if f.get("geometry")]
56
+ if not feats:
57
+ return data
58
+ x0 = shape(feats[0]["geometry"]).representative_point().x
59
+ if abs(x0) > 180: # already projected, assume EPSG:25832
60
+ return data
61
+ tr = Transformer.from_crs("EPSG:4326", "EPSG:25832", always_xy=True)
62
+ out = dict(data, features=[])
63
+ for f in data["features"]:
64
+ g = f.get("geometry")
65
+ if g:
66
+ f = dict(f, geometry=mapping(shapely.transform(
67
+ shape(g), lambda c: np.column_stack(tr.transform(c[:, 0], c[:, 1])))))
68
+ out["features"].append(f)
69
+ return out
70
+
71
+
72
+ def _is_synthetic(*paths: Path) -> bool:
73
+ """Input files that self-declare as synthetic test data (keyword 'SYNTHETIC')."""
74
+ return any("SYNTHETIC" in p.read_text(encoding="utf-8", errors="ignore").upper() for p in paths if p)
75
+
76
+
77
+ def build(args) -> int:
78
+ if args.source == "pilot":
79
+ from .pilot_build import build_pilot
80
+ return build_pilot(args)
81
+ from .xplan import parse_xplan # lxml only needed for XPlanGML
82
+
83
+ plan_path = Path(args.plan)
84
+ plan = parse_xplan(plan_path)
85
+ if not plan.zones:
86
+ print("error: no BP_BaugebietsTeilFlaeche with polygon geometry found", file=sys.stderr)
87
+ return 2
88
+ if plan.srs_name and "25832" not in plan.srs_name:
89
+ print(f"warning: srsName '{plan.srs_name}' is not EPSG:25832; coordinates are treated as EPSG:25832",
90
+ file=sys.stderr)
91
+
92
+ buildings = []
93
+ bpath = Path(args.buildings) if args.buildings else None
94
+ if bpath:
95
+ data = _buildings_geojson_25832(json.loads(bpath.read_text(encoding="utf-8")))
96
+ buildings = load_buildings(data, bpath.name, default_height=args.default_building_height)
97
+
98
+ results = compute_plan(plan, buildings, storey_height=args.storey_height, ground_nhn=args.ground_nhn)
99
+ records = [r.record() for r in results]
100
+
101
+ # --- local frame at the centre of all geometry, at the base height
102
+ bounds = np.array([r.zone.geometry.bounds for r in results] + [b.footprint.bounds for b in buildings])
103
+ cx = (bounds[:, 0].min() + bounds[:, 2].max()) / 2
104
+ cy = (bounds[:, 1].min() + bounds[:, 3].max()) / 2
105
+ frame = LocalFrame(cx, cy, args.base_height)
106
+
107
+ out = Path(args.out)
108
+ synthetic = _is_synthetic(plan_path, bpath)
109
+ notice = ("SYNTHETIC test data (input files self-declare as synthetic) - not real planning data"
110
+ if synthetic else "")
111
+ extras = {"source_crs": "EPSG:25832", "plan": plan.source_file, "plan_id": plan.gml_id,
112
+ "base_height_m_ellipsoidal": args.base_height, "data_notice": notice}
113
+
114
+ env = MeshBuilder()
115
+ for i, r in enumerate(results):
116
+ env.add_prism(r.footprint, args.base_height, args.base_height + r.height_max_m, frame, i)
117
+ ts_env = write_tileset(out / "envelopes", frame, env, "XPlanZone", records, ENVELOPE_COLOR,
118
+ "envelopes", extras)
119
+
120
+ b_records = [b.record() for b in buildings]
121
+ if buildings:
122
+ bm = MeshBuilder()
123
+ for i, b in enumerate(buildings):
124
+ bm.add_prism(b.footprint, args.base_height, args.base_height + b.height_m, frame, i)
125
+ write_tileset(out / "buildings", frame, bm, "ExistingBuilding", b_records, BUILDING_COLOR,
126
+ "buildings", dict(extras, source=bpath.name))
127
+
128
+ scenario = heat_scenario(records, args.specific_demand, parse_buildout(args.buildout))
129
+ totals = {k: round(sum(r[k] for r in records), 2) for k in
130
+ ("area_m2", "envelope_volume_m3", "existing_volume_m3", "headroom_m3",
131
+ "gfa_allowed_m2", "headroom_gfa_m2")}
132
+ summary = {
133
+ "generator": f"HeatTwin3D {__version__}",
134
+ "data_notice": notice,
135
+ "plan": {"plan_id": plan.gml_id, "name": plan.name, "source": plan.source_file},
136
+ "buildings_source": bpath.name if bpath else None,
137
+ "parameters": {"storey_height_m": args.storey_height, "base_height_m": args.base_height,
138
+ "ground_nhn_m": args.ground_nhn, "legal_ref": LEGAL_REF},
139
+ "georeference": {"origin_lon": frame.lon, "origin_lat": frame.lat, "origin_h": frame.h0,
140
+ "origin_epsg25832": [cx, cy]},
141
+ "totals": totals,
142
+ "zones": records,
143
+ "buildings_count": len(buildings),
144
+ "heat_scenario": scenario,
145
+ }
146
+ (out / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
147
+
148
+ copy_viewer(out, args.no_viewer)
149
+ if not self_check(out):
150
+ return 3
151
+ print(f"zones: {len(records)}, buildings: {len(buildings)} -> {out}")
152
+ for r in records:
153
+ print(f" {r['zone_id']:<12} {r['gebiet_art'][:28]:<28} H={r['height_max_m']:>5} m "
154
+ f"headroom={r['headroom_m3']:>10.0f} m³ GFA reserve={r['headroom_gfa_m2']:>8.0f} m² "
155
+ f"[{r['confidence']}]")
156
+ return 0
157
+
158
+
159
+ def copy_viewer(out: Path, skip: bool) -> None:
160
+ if not skip and _resource_dir("viewer").is_dir():
161
+ shutil.copytree(_resource_dir("viewer"), out / "viewer", dirs_exist_ok=True)
162
+
163
+
164
+ def self_check(out: Path) -> bool:
165
+ """All vertices of each tileset must lie inside its root bounding volume."""
166
+ ok = True
167
+ for sub in ("envelopes", "buildings"):
168
+ p = out / sub / "tileset.json"
169
+ if p.exists():
170
+ chk = check_tileset_contains_content(p)
171
+ size = sum(f.stat().st_size for f in (out / sub).iterdir())
172
+ print(f"{sub}: {chk['vertices']} vertices, {size / 1024:.0f} KiB, "
173
+ f"bounding volume contains geometry: {chk['ok']}")
174
+ ok &= chk["ok"]
175
+ return ok
176
+
177
+
178
+ def write_schema(args) -> int:
179
+ from .schema import LOD2_SCHEMA
180
+
181
+ p = Path(args.out)
182
+ p.parent.mkdir(parents=True, exist_ok=True)
183
+ doc = {"$comment": "HeatTwin3D 'Auditable 3D Tiles' profile: an EXT_structural_metadata schema. "
184
+ "Generated by `python3 -m heattwin3d schema`; embedded verbatim in every GLB.",
185
+ **SCHEMA}
186
+ p.write_text(json.dumps(doc, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
187
+ print(f"wrote {p}")
188
+ p2 = p.parent / "lod2_building.schema.json"
189
+ doc2 = {"$comment": "HeatTwin3D LoD2 heat-planning city model (Deliverable D1): EXT_structural_metadata schema "
190
+ "embedded in every LoD2 GLB. Table 0 = LoD2Building (feature ID set 0, label 'building'), "
191
+ "table 1 = LoD2Surface (feature ID set 1, label 'roof_surface'). "
192
+ "Generated by `python3 -m heattwin3d schema`.",
193
+ **LOD2_SCHEMA}
194
+ p2.write_text(json.dumps(doc2, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
195
+ print(f"wrote {p2}")
196
+ from .heat3d import HEAT3D_SCHEMA, LOD2_PROPS, PLAN_PROPS
197
+
198
+ p3 = p.parent / "heat3d.schema.json"
199
+ doc3 = {"$comment": "HeatTwin3D 3D heat-planning layers (Deliverable D3): EXT_structural_metadata schema embedded in "
200
+ "the subsurface / probes / network GLBs. 'x-lod2Enrichment' and 'x-planEnrichment' list the "
201
+ "properties `heattwin3d heat3d` adds to LoD2Building and PilotPlanEnvelope. "
202
+ "Generated by `python3 -m heattwin3d schema`.",
203
+ **HEAT3D_SCHEMA, "x-lod2Enrichment": LOD2_PROPS, "x-planEnrichment": PLAN_PROPS}
204
+ p3.write_text(json.dumps(doc3, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
205
+ print(f"wrote {p3}")
206
+ return 0
207
+
208
+
209
+ def lod2(args) -> int:
210
+ from .lod2_build import build_lod2, check_lod2_output
211
+
212
+ rc = build_lod2(args)
213
+ if rc == 0:
214
+ chk = check_lod2_output(Path(args.out))
215
+ print(f"lod2 check: {chk['leaves']} leaf contents (both tilesets), all vertices inside leaf/parent/root "
216
+ f"boxes: {chk['ok']}")
217
+ rc = 0 if chk["ok"] else 3
218
+ return rc
219
+
220
+
221
+ def heat3d(args) -> int:
222
+ from .heat3d import build_heat3d, check_heat3d_output
223
+
224
+ rc = build_heat3d(args)
225
+ if rc == 0:
226
+ chk = check_heat3d_output(Path(args.out))
227
+ print(f"heat3d check: {chk['tilesets']} tilesets, {chk['contents']} contents, "
228
+ f"all vertices inside their boxes: {chk['ok']}")
229
+ rc = 0 if chk["ok"] else 3
230
+ return rc
231
+
232
+
233
+ def main(argv=None) -> int:
234
+ ap = argparse.ArgumentParser(prog="heattwin3d", description="Official German planning data -> auditable 3D Tiles 1.1 for heat planning")
235
+ ap.add_argument("--version", action="version", version=__version__)
236
+ sub = ap.add_subparsers(dest="cmd", required=True)
237
+
238
+ b = sub.add_parser("build", help="build envelope + building tilesets and summary.json")
239
+ b.add_argument("--source", choices=["xplan", "pilot"], default="xplan",
240
+ help="xplan: XPlanGML 5.x (default); pilot: Atlas B-Plan pilot JSON (outline + zone list)")
241
+ b.add_argument("--plan", required=True, help="XPlanGML 5.x file (EPSG:25832) or pilot JSON (--source pilot)")
242
+ b.add_argument("--buildings", help="buildings: GeoJSON with 'height_m' (xplan) or GeoPackage with "
243
+ "height_m / heat_demand_cal_kwh_a (pilot)")
244
+ b.add_argument("--buildings-attrs", help="pilot: GeoPackage with GEBID/GEBTYP_GEM/STN/HNR/OTL in the same "
245
+ "row order (verified by geometry equality)")
246
+ b.add_argument("--buffer", type=float, default=120.0,
247
+ help="pilot: context buffer around plan outlines for building selection, m (default 120)")
248
+ b.add_argument("--out", required=True, help="output directory")
249
+ b.add_argument("--storey-height", type=float, default=DEFAULT_STOREY_HEIGHT_M,
250
+ help="storey height in m for Z <-> height (default 3.0)")
251
+ b.add_argument("--base-height", type=float, default=0.0,
252
+ help="ellipsoidal height of the ground in m (default 0 = Cesium ellipsoid terrain)")
253
+ b.add_argument("--ground-nhn", type=float, default=None,
254
+ help="ground height in m NHN, used to convert absolute Hoehenangaben (optional)")
255
+ b.add_argument("--default-building-height", type=float, default=9.0,
256
+ help="height for buildings without height_m (flagged low confidence)")
257
+ b.add_argument("--specific-demand", type=float, default=DEFAULT_SPECIFIC_DEMAND,
258
+ help="ASSUMPTION: specific heat demand of new floor area in kWh/(m²a) (default 40)")
259
+ b.add_argument("--buildout", default=None,
260
+ help="ASSUMPTION: cumulative build-out fraction per year, e.g. '2030:0.2,2035:0.5,2045:1.0'")
261
+ b.add_argument("--no-viewer", action="store_true", help="do not copy the viewer into <out>/viewer")
262
+ b.set_defaults(func=build)
263
+
264
+ from .lod2_build import DEFAULT_GEOID_OFFSET_M
265
+
266
+ l2 = sub.add_parser("lod2", help="AdV LoD2 CityGML -> 3D Tiles 1.1 with heat-planning metadata (D1)")
267
+ l2.add_argument("--gml-dir", required=True, help="directory searched recursively for *.gml (AdV LoD2 tiles)")
268
+ l2.add_argument("--out", required=True, help="output directory (tileset.json, tileset_ellipsoid.json, tiles/)")
269
+ l2.add_argument("--heat-gpkg", help="GeoPackage (EPSG:25832) with heat_demand_cal_kwh_a, heat_demand_kwh_a, "
270
+ "floor_area_m2 per building footprint (Atlas *_heat_demand_cal.gpkg)")
271
+ l2.add_argument("--buildings-gpkg", help="GeoPackage with GEBID, GEBTYP_GEM, GEBALTER_T, STN, HNR, OTL, "
272
+ "ENERGIEF_M in the same row order as --heat-gpkg (verified)")
273
+ l2.add_argument("--geoid-offset", type=float, default=DEFAULT_GEOID_OFFSET_M,
274
+ help=f"metres added to NHN heights to get ellipsoidal heights (default {DEFAULT_GEOID_OFFSET_M}, "
275
+ "approximate for Ehingen; ASSUMPTION)")
276
+ l2.add_argument("--keep-closure", action="store_true", help="also render ClosureSurface polygons")
277
+ l2.add_argument("--keep-ground", action="store_true", help="also render GroundSurface polygons")
278
+ l2.add_argument("--min-footprint", type=float, default=0.0,
279
+ help="drop buildings with a footprint below this area in m² (default 0 = keep all)")
280
+ l2.add_argument("--pv-params", help="PV model parameter JSON (default: heattwin3d/params/pv_params.json)")
281
+ l2.add_argument("--city", default="", help="city label for summary.json")
282
+ l2.add_argument("--view", help="default camera 'lon,lat[,heading,pitch,range]' (degrees, metres)")
283
+ l2.add_argument("--attribution", help="credit text shown by the viewer (default: LGL BW dl-de/by-2-0)")
284
+ l2.add_argument("--lod2-source", help="LoD2 source/licence label used in 'source'")
285
+ l2.add_argument("--heat-source", help="heat-data source label used in 'source'")
286
+ l2.add_argument("--quiet", action="store_true")
287
+ l2.set_defaults(func=lod2)
288
+
289
+ h3 = sub.add_parser("heat3d", help="3D heat-planning layers on the LoD2 model: subsurface, probes, network "
290
+ "scenario, LoD2 enrichment, B-Plan on terrain (D3)")
291
+ h3.add_argument("--lod2", required=True, help="output directory of 'heattwin3d lod2' (enriched in place)")
292
+ h3.add_argument("--out", required=True, help="output directory (subsurface/, probes/, network/, summary.json)")
293
+ h3.add_argument("--drilling", required=True, help="GeoPackage (EPSG:25832): Wasserschutzgebietszonen with "
294
+ "zone_raw, restriction_class, restriction_label")
295
+ h3.add_argument("--heat-areas", required=True, help="GeoPackage: heat-network areas with area_id, name, "
296
+ "category_key (eignung / pruef ...)")
297
+ h3.add_argument("--line-density", required=True, help="GeoPackage: streets with line_density_mwh_m_a, "
298
+ "heat_line_flag, street_name")
299
+ h3.add_argument("--scenario-summary", help="JSON of the heat-planning model (CO2 path per preset), optional")
300
+ h3.add_argument("--bplan-dir", help="output directory of 'heattwin3d build --source pilot' (placed on terrain)")
301
+ h3.add_argument("--bplan-geojson", help="plan outlines (property 'idx' = plan_idx) for the LUBW check")
302
+ h3.add_argument("--parcels", help="GeoPackage: ALKIS / INSPIRE cadastral parcels (probe placement per parcel)")
303
+ h3.add_argument("--waste-heat", help="GeoPackage: reported waste heat (BfEE Plattform für Abwärme) points with "
304
+ "name, menge_mwh_a, leistung_kw, temp_c")
305
+ h3.add_argument("--waste-heat-routes", help="GeoPackage: feeder routes from waste-heat sites to the network")
306
+ h3.add_argument("--wastewater-plants", help="GeoPackage: wastewater treatment plants (in_gemeinde, distances)")
307
+ h3.add_argument("--params", help="ASSUMPTION parameters (default heattwin3d/params/heat3d_params.json)")
308
+ h3.add_argument("--city", default="", help="city label")
309
+ h3.add_argument("--quiet", action="store_true")
310
+ h3.set_defaults(func=heat3d)
311
+
312
+ s = sub.add_parser("schema", help="write the metadata schema JSON")
313
+ s.add_argument("--out", default=str(_resource_dir("schema") / "xplan_zone.schema.json"))
314
+ s.set_defaults(func=write_schema)
315
+
316
+ args = ap.parse_args(argv)
317
+ return args.func(args)