sitecontext 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.
@@ -0,0 +1,3 @@
1
+ """sitecontext - 3D site context for building models, from open public data."""
2
+
3
+ __version__ = "0.1.0"
sitecontext/check.py ADDED
@@ -0,0 +1,110 @@
1
+ """Top-down check plot (model frame): the context, every parcel, the lot, and the model's own inputs.
2
+
3
+ Look at it before using a registration: the red dashed property lines must sit on the green lot, the
4
+ model street on the OSM road, and no neighbouring building inside the site.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+ from . import parcels as P
12
+ from .config import Site, SiteError
13
+ from .geo import Frame
14
+ from .gltf import read_glb
15
+
16
+ COLOURS = {
17
+ "terrain": "#e9e4d8",
18
+ "scrub": "#cfd8b8",
19
+ "asphalt": "#555555",
20
+ "paving": "#a5a5a5",
21
+ "dirt": "#b9976b",
22
+ "building": "#8f8f8f",
23
+ "destroyed": "#d9a05b",
24
+ }
25
+ ORDER = ["terrain", "scrub", "dirt", "paving", "asphalt", "destroyed", "building"]
26
+
27
+
28
+ def plot(site: Site, out: str = "check.png", extent_m: float | None = None, title: str | None = None) -> str:
29
+ try:
30
+ import matplotlib
31
+
32
+ matplotlib.use("Agg")
33
+ import matplotlib.pyplot as plt
34
+ from matplotlib.collections import PolyCollection
35
+ except ImportError:
36
+ raise SiteError("check needs matplotlib: pip install 'sitecontext[plot]'") from None
37
+ glb = site.path("context.glb")
38
+ if not glb.exists():
39
+ raise SiteError("context.glb not found - run `sitecontext build` first")
40
+ f = Frame(site.center, site.cfg.get("registration"))
41
+ meshes = read_glb(glb)
42
+ fig, ax = plt.subplots(figsize=(10, 10), dpi=110)
43
+ for mat in ORDER:
44
+ polys = [m.vertices[m.faces][:, :, :2] for m in meshes if m.material == mat]
45
+ if polys:
46
+ tris = np.concatenate(polys)
47
+ if mat in ("building", "destroyed"): # roofs only: keep triangles with a real footprint
48
+ u, v = tris[:, 1] - tris[:, 0], tris[:, 2] - tris[:, 0]
49
+ area = np.abs(u[:, 0] * v[:, 1] - u[:, 1] * v[:, 0])
50
+ tris = tris[area > 1e-6]
51
+ ax.add_collection(
52
+ PolyCollection(
53
+ tris, facecolors=COLOURS[mat], edgecolors="face", linewidths=0.3, zorder=ORDER.index(mat)
54
+ )
55
+ )
56
+ parcels = P.load(site, f)
57
+ for p in parcels:
58
+ for g in getattr(p.polygon, "geoms", [p.polygon]):
59
+ x, y = f.enu_to_model(*np.array(g.exterior.coords).T)
60
+ ax.plot(x, y, color="#6b6b6b", lw=0.4, zorder=10)
61
+ lot = P.lot_polygon(site, parcels)
62
+ if lot is not None:
63
+ for g in getattr(lot, "geoms", [lot]):
64
+ x, y = f.enu_to_model(*np.array(g.exterior.coords).T)
65
+ ax.plot(x, y, color="#1a9850", lw=2.2, zorder=11, label="lot parcel")
66
+ for k, line in enumerate(site.model_lines("property_lines")):
67
+ a = np.array(line)
68
+ ax.plot(
69
+ a[:, 0],
70
+ a[:, 1],
71
+ "--",
72
+ color="#d7301f",
73
+ lw=1.6,
74
+ zorder=12,
75
+ label="model property lines" if k == 0 else None,
76
+ )
77
+ for k, line in enumerate(site.model_lines("cutout")):
78
+ a = np.array([*line, line[0]])
79
+ ax.plot(
80
+ a[:, 0], a[:, 1], color="#7a0177", lw=1.0, zorder=12, label="model cutout" if k == 0 else None
81
+ )
82
+ r = extent_m or site.radius_m
83
+ cx, cy = (float(v) for v in f.enu_to_model(0.0, 0.0)) # the site center
84
+ ax.set_xlim(cx - r, cx + r)
85
+ ax.set_ylim(cy - r, cy + r)
86
+ ax.set_aspect("equal")
87
+ ax.set_facecolor("#f7f5ef")
88
+ frame = "model frame (m)" if f.registered else "east / north (m) about the site center"
89
+ ax.set_title(title or f"{site.cfg.get('address', 'site')} - {frame}", fontsize=10)
90
+ ax.text(
91
+ 0.01, 0.01, "Data: (c) OpenStreetMap contributors (ODbL), USGS 3DEP, county parcels",
92
+ transform=ax.transAxes, fontsize=7, color="#555555",
93
+ ) # fmt: skip
94
+ from matplotlib.patches import Patch
95
+
96
+ handles, labels = ax.get_legend_handles_labels()
97
+ for mat, label in (("building", "building (OSM)"), ("destroyed", "destroyed building (OSM)")):
98
+ if any(m.material == mat for m in meshes):
99
+ handles.append(Patch(facecolor=COLOURS[mat]))
100
+ labels.append(label)
101
+ if handles:
102
+ ax.legend(handles, labels, loc="upper right", fontsize=8)
103
+ # north arrow
104
+ nx, ny = f.xhat[1], f.yhat[1] # true north in model axes
105
+ ax.annotate("N", xy=(0.93 + 0.04 * nx, 0.12 + 0.04 * ny), xytext=(0.93, 0.12), xycoords="axes fraction",
106
+ arrowprops={"arrowstyle": "->", "lw": 1.5}, ha="center", va="center", fontsize=9) # fmt: skip
107
+ path = site.path(out)
108
+ fig.savefig(path, bbox_inches="tight")
109
+ plt.close(fig)
110
+ return str(path)
sitecontext/cli.py ADDED
@@ -0,0 +1,183 @@
1
+ """Command line interface: ``sitecontext <command> [site folder] [options]``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from . import __version__
9
+ from .config import Site, SiteError
10
+
11
+
12
+ def cmd_init(a) -> int:
13
+ cfg = {"address": a.address, "radius_m": a.radius}
14
+ if a.center:
15
+ cfg["center"] = [float(v) for v in a.center.split(",")]
16
+ if a.flat:
17
+ cfg["terrain"] = "flat"
18
+ if a.parcels or a.lot:
19
+ cfg["parcels"] = {"source": a.parcels or "la-county"}
20
+ if a.lot:
21
+ cfg["parcels"]["lot_id"] = a.lot
22
+ Site.create(a.site, **cfg)
23
+ print(f"wrote {a.site}/site.json - next: sitecontext fetch {a.site}")
24
+ return 0
25
+
26
+
27
+ def cmd_fetch(a) -> int:
28
+ from .fetch import fetch
29
+
30
+ fetch(Site.load(a.site), refresh=a.refresh)
31
+ return 0
32
+
33
+
34
+ def cmd_fit(a) -> int:
35
+ from .fit import WARN_RESIDUAL_M, fit, worst_residual
36
+
37
+ reg = fit(Site.load(a.site), hint=a.hint, window=a.window)
38
+ print(f"model +Y bearing {reg['north_bearing_deg']:.3f} deg, anchor {reg['anchor_latlon']}")
39
+ for r in reg["residuals"]:
40
+ print(f" line {r['line']}: median {r['median_m']:.3f} m, max {r['max_m']:.3f} m")
41
+ if reg.get("next_best_bearing_deg") is not None:
42
+ print(
43
+ f" next best bearing {reg['next_best_bearing_deg']} deg (a close score there = ambiguous input)"
44
+ )
45
+ if worst_residual(reg) > WARN_RESIDUAL_M:
46
+ print(
47
+ f"WARNING: a line sits more than {WARN_RESIDUAL_M} m off the parcel - check it before using this fit"
48
+ )
49
+ return 1
50
+ return 0
51
+
52
+
53
+ def cmd_register(a) -> int:
54
+ from .fit import register
55
+
56
+ reg = register(
57
+ Site.load(a.site),
58
+ a.bearing,
59
+ [float(v) for v in a.anchor.split(",")],
60
+ [float(v) for v in a.at.split(",")],
61
+ )
62
+ print(f"registered: model +Y bearing {reg['north_bearing_deg']} deg, anchor {reg['anchor_latlon']}")
63
+ return 0
64
+
65
+
66
+ def cmd_build(a) -> int:
67
+ from .context import build
68
+
69
+ info = build(Site.load(a.site), out=a.output, cut_lot=a.cut_lot)
70
+ g = info["glb"]
71
+ print(
72
+ f"wrote {info['file']}: {info['buildings']} buildings, {info['destroyed_building_pads']} destroyed-building pads, "
73
+ f"{info['roads']} roads, {g['triangles']:,} triangles"
74
+ )
75
+ if not info["registered"]:
76
+ print("note: not registered - the context is in local east/north metres about the site center")
77
+ return 0
78
+
79
+
80
+ def cmd_check(a) -> int:
81
+ from .check import plot
82
+
83
+ print("wrote", plot(Site.load(a.site), out=a.output, extent_m=a.extent))
84
+ return 0
85
+
86
+
87
+ def cmd_earth(a) -> int:
88
+ from .earth import export
89
+
90
+ st = export(
91
+ Site.load(a.site),
92
+ a.model,
93
+ out=a.output,
94
+ with_context=a.with_context,
95
+ nudge=not a.no_nudge,
96
+ name=a.name,
97
+ )
98
+ print(
99
+ f"wrote {st['file']} ({st['MB']} MB): {st['lat']:.7f}, {st['lon']:.7f}, heading {st['heading_deg']} deg, "
100
+ f"altitude {st['altitude_m']} m {st['altitude_mode']}"
101
+ )
102
+ print("open it in Google Earth Pro (File > Open) and untick Layers > 3D Buildings")
103
+ return 0
104
+
105
+
106
+ def build_parser() -> argparse.ArgumentParser:
107
+ p = argparse.ArgumentParser(
108
+ prog="sitecontext",
109
+ description="3D site context for a building model from open data (OSM, county parcels, USGS terrain).",
110
+ )
111
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
112
+ sub = p.add_subparsers(dest="command", metavar="<command>")
113
+
114
+ s = sub.add_parser("init", help="create a site folder with site.json")
115
+ s.add_argument("site", help="site folder to create")
116
+ s.add_argument("--address", help="street address (geocoded with OpenStreetMap Nominatim)")
117
+ s.add_argument("--center", help="lat,lon instead of geocoding")
118
+ s.add_argument("--radius", type=float, default=300.0, help="context radius in metres (default 300)")
119
+ s.add_argument("--flat", action="store_true", help="no terrain download (outside the US)")
120
+ s.add_argument("--parcels", help="parcel source preset (e.g. la-county); other counties: edit site.json")
121
+ s.add_argument("--lot", help="parcel id of the site itself")
122
+ s.set_defaults(func=cmd_init)
123
+
124
+ s = sub.add_parser("fetch", help="download OSM, parcels, terrain and geoid data")
125
+ s.add_argument("site", nargs="?", default=".")
126
+ s.add_argument("--refresh", action="store_true", help="download again even if files exist")
127
+ s.set_defaults(func=cmd_fetch)
128
+
129
+ s = sub.add_parser("fit", help="register the model to the lot parcel from its property lines")
130
+ s.add_argument("site", nargs="?", default=".")
131
+ s.add_argument("--hint", type=float, help="approximate bearing of model +Y (deg), to limit the search")
132
+ s.add_argument("--window", type=float, default=30.0, help="search +/- this around --hint (deg)")
133
+ s.set_defaults(func=cmd_fit)
134
+
135
+ s = sub.add_parser("register", help="register the model by hand (bearing + one known point)")
136
+ s.add_argument("site", nargs="?", default=".")
137
+ s.add_argument("--bearing", type=float, required=True, help="compass bearing of model +Y (deg)")
138
+ s.add_argument("--anchor", required=True, help="x,y of a model point (model.units)")
139
+ s.add_argument("--at", required=True, help="lat,lon of that point")
140
+ s.set_defaults(func=cmd_register)
141
+
142
+ s = sub.add_parser("build", help="build the 3D context (context.glb + context.json)")
143
+ s.add_argument("site", nargs="?", default=".")
144
+ s.add_argument("-o", "--output", help="output file name in the site folder (default context.glb)")
145
+ s.add_argument(
146
+ "--cut-lot", action="store_true", help="leave the lot parcel empty (your model brings its own site)"
147
+ )
148
+ s.set_defaults(func=cmd_build)
149
+
150
+ s = sub.add_parser("check", help="top-down check plot of the context, parcels and model inputs")
151
+ s.add_argument("site", nargs="?", default=".")
152
+ s.add_argument("-o", "--output", default="check.png", help="image file in the site folder")
153
+ s.add_argument("--extent", type=float, help="half-width of the plot in metres (default: the radius)")
154
+ s.set_defaults(func=cmd_check)
155
+
156
+ s = sub.add_parser("earth", help="export the model (and context) as a KMZ for Google Earth Pro")
157
+ s.add_argument("site", nargs="?", default=".")
158
+ s.add_argument("-m", "--model", help="your model as a .glb in the model frame (metres)")
159
+ s.add_argument("-o", "--output", help="output .kmz path (default <site>/site.kmz)")
160
+ s.add_argument("--name", help="document name in Google Earth")
161
+ s.add_argument("--with-context", action="store_true", help="also include context.glb (hidden on open)")
162
+ s.add_argument("--no-nudge", action="store_true", help="place by the parcel fit only, no imagery offset")
163
+ s.set_defaults(func=cmd_earth)
164
+ return p
165
+
166
+
167
+ def main(argv: list[str] | None = None) -> int:
168
+ parser = build_parser()
169
+ args = parser.parse_args(argv)
170
+ if not getattr(args, "command", None):
171
+ parser.print_help()
172
+ return 0
173
+ if args.command == "init" and not (args.address or args.center):
174
+ parser.error("init needs --address or --center")
175
+ try:
176
+ return args.func(args)
177
+ except SiteError as ex:
178
+ print(f"sitecontext: {ex}", file=sys.stderr)
179
+ return 2
180
+
181
+
182
+ if __name__ == "__main__":
183
+ sys.exit(main())
sitecontext/config.py ADDED
@@ -0,0 +1,119 @@
1
+ """The site folder and its ``site.json``.
2
+
3
+ A site folder holds everything for one site::
4
+
5
+ site.json the inputs (address, radius, parcel source, model inputs) and the derived values
6
+ (center, registration, datum, geoid) that later steps write back
7
+ data/ downloaded public data (osm.xml, parcels.json, dem.tif, meta.json)
8
+ context.glb the built context (``sitecontext build``)
9
+
10
+ Model inputs (``model`` block) are given in the model's own plan coordinates, in ``model.units``
11
+ (``m``, ``ft`` or ``in``). Internally everything is metres.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ UNITS = {"m": 1.0, "ft": 0.3048, "in": 0.0254, "mm": 0.001, "cm": 0.01}
22
+
23
+ CONFIG_NAME = "site.json"
24
+ DATA_DIR = "data"
25
+
26
+
27
+ class SiteError(Exception):
28
+ """A user-facing problem with the site inputs or data (printed without a traceback)."""
29
+
30
+
31
+ def unit_scale(units: str) -> float:
32
+ try:
33
+ return UNITS[units]
34
+ except KeyError:
35
+ raise SiteError(f"unknown units {units!r}; use one of {', '.join(UNITS)}") from None
36
+
37
+
38
+ @dataclass
39
+ class Site:
40
+ """A site folder. ``cfg`` is the parsed ``site.json``; call :meth:`save` after changing it."""
41
+
42
+ root: Path
43
+ cfg: dict[str, Any] = field(default_factory=dict)
44
+
45
+ # ------------------------------------------------------------------ files
46
+ @classmethod
47
+ def load(cls, root: str | Path) -> Site:
48
+ root = Path(root)
49
+ p = root / CONFIG_NAME
50
+ if not p.exists():
51
+ raise SiteError(f"{p} not found - create it with `sitecontext init {root} --address ...`")
52
+ return cls(root, json.loads(p.read_text(encoding="utf-8")))
53
+
54
+ @classmethod
55
+ def create(cls, root: str | Path, **cfg: Any) -> Site:
56
+ root = Path(root)
57
+ root.mkdir(parents=True, exist_ok=True)
58
+ if (root / CONFIG_NAME).exists():
59
+ raise SiteError(f"{root / CONFIG_NAME} already exists")
60
+ site = cls(root, {k: v for k, v in cfg.items() if v is not None})
61
+ site.save()
62
+ return site
63
+
64
+ def save(self) -> None:
65
+ (self.root / CONFIG_NAME).write_text(json.dumps(self.cfg, indent=2) + "\n", encoding="utf-8")
66
+
67
+ @property
68
+ def data(self) -> Path:
69
+ d = self.root / DATA_DIR
70
+ d.mkdir(exist_ok=True)
71
+ return d
72
+
73
+ def path(self, name: str) -> Path:
74
+ return self.root / name
75
+
76
+ # ------------------------------------------------------------------ values
77
+ @property
78
+ def center(self) -> tuple[float, float]:
79
+ c = self.cfg.get("center")
80
+ if not c:
81
+ raise SiteError("site.json has no center - run `sitecontext fetch` (it geocodes the address)")
82
+ return float(c[0]), float(c[1])
83
+
84
+ @property
85
+ def radius_m(self) -> float:
86
+ return float(self.cfg.get("radius_m", 300))
87
+
88
+ @property
89
+ def model(self) -> dict[str, Any]:
90
+ return self.cfg.get("model") or {}
91
+
92
+ @property
93
+ def scale(self) -> float:
94
+ """metres per model unit"""
95
+ return unit_scale(self.model.get("units", "m"))
96
+
97
+ def model_lines(self, key: str) -> list[list[tuple[float, float]]]:
98
+ """polylines from the model block (``property_lines``, ``cutout``), converted to metres"""
99
+ s = self.scale
100
+ out = []
101
+ for line in self.model.get(key) or []:
102
+ pts = [(float(p[0]) * s, float(p[1]) * s) for p in line]
103
+ if len(pts) >= 2:
104
+ out.append(pts)
105
+ return out
106
+
107
+ @property
108
+ def lot_parcel_id(self) -> str | None:
109
+ v = (self.cfg.get("parcels") or {}).get("lot_id")
110
+ return None if v in (None, "") else str(v)
111
+
112
+ @property
113
+ def z0_elevation_m(self) -> float:
114
+ """elevation (m, vertical datum of the terrain source) of model z = 0"""
115
+ m = self.model
116
+ if m.get("z0_elevation") is not None:
117
+ return float(m["z0_elevation"]) * self.scale
118
+ d = self.cfg.get("datum") or {}
119
+ return float(d.get("z0_elevation_m", 0.0))