lczlite 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.
lczlite/__init__.py ADDED
@@ -0,0 +1,115 @@
1
+ """lczlite: Local Climate Zone classification from urban canopy parameters.
2
+
3
+ Fuzzy range scoring of sites or grid cells against LCZ property ranges (Stewart & Oke
4
+ 2012) with best class, confidence and mixed-class flags; canopy parameters from building
5
+ footprint grids (surface fractions, aspect ratio, canyon sky view factor, Macdonald et al.
6
+ 1998 roughness, Davenport roughness class); WUDAPT integer codes, colour table, summaries
7
+ and map agreement.
8
+
9
+ The Stewart & Oke (2012) property ranges (Tables 3-4) are bundled as the default range
10
+ table (:func:`stewart_oke_table`); local tables load from CSV or JSON.
11
+ """
12
+
13
+ from ._common import LCZError, write_csv
14
+ from ._version import __version__
15
+ from .classes import (
16
+ LCZ_CLASSES,
17
+ LCZ_KEYS,
18
+ UNCLASSIFIED,
19
+ LCZClass,
20
+ colour_table,
21
+ hex_to_rgb,
22
+ key_from_code,
23
+ lcz_class,
24
+ normalize_key,
25
+ to_rgb,
26
+ write_colour_csv,
27
+ write_qml,
28
+ wudapt_code,
29
+ )
30
+ from .classify import IllustrativeTableWarning, LCZResult, classify, membership
31
+ from .grid import BuildingGrid, GridSpec, buildings_to_grid
32
+ from .io import read_sites_csv, result_rows, write_results_csv
33
+ from .parameters import (
34
+ DAVENPORT_NAMES,
35
+ DAVENPORT_Z0,
36
+ albedo_plan_weighted,
37
+ aspect_ratio,
38
+ canopy_parameters,
39
+ frontal_area_index,
40
+ macdonald,
41
+ roughness_class,
42
+ street_width_regular,
43
+ surface_fractions,
44
+ svf_canyon,
45
+ )
46
+ from .ranges import (
47
+ PARAMETERS,
48
+ Range,
49
+ RangeTable,
50
+ canonical_parameter,
51
+ parse_range,
52
+ read_range_table,
53
+ stewart_oke_table,
54
+ write_template,
55
+ )
56
+ from .summary import class_summary, compare_maps, majority_filter, mixed_pairs
57
+
58
+ __all__ = [
59
+ "__version__",
60
+ "LCZError",
61
+ # classes and colours
62
+ "LCZClass",
63
+ "LCZ_CLASSES",
64
+ "LCZ_KEYS",
65
+ "UNCLASSIFIED",
66
+ "lcz_class",
67
+ "normalize_key",
68
+ "wudapt_code",
69
+ "key_from_code",
70
+ "colour_table",
71
+ "hex_to_rgb",
72
+ "to_rgb",
73
+ "write_qml",
74
+ "write_colour_csv",
75
+ # range tables
76
+ "PARAMETERS",
77
+ "Range",
78
+ "RangeTable",
79
+ "parse_range",
80
+ "canonical_parameter",
81
+ "read_range_table",
82
+ "write_template",
83
+ "stewart_oke_table",
84
+ # parameters
85
+ "DAVENPORT_Z0",
86
+ "DAVENPORT_NAMES",
87
+ "surface_fractions",
88
+ "street_width_regular",
89
+ "aspect_ratio",
90
+ "svf_canyon",
91
+ "frontal_area_index",
92
+ "macdonald",
93
+ "roughness_class",
94
+ "albedo_plan_weighted",
95
+ "canopy_parameters",
96
+ # grid
97
+ "GridSpec",
98
+ "BuildingGrid",
99
+ "buildings_to_grid",
100
+ # classification
101
+ "membership",
102
+ "classify",
103
+ "LCZResult",
104
+ "IllustrativeTableWarning",
105
+ # summaries
106
+ "class_summary",
107
+ "mixed_pairs",
108
+ "compare_maps",
109
+ "majority_filter",
110
+ # I/O
111
+ "read_sites_csv",
112
+ "result_rows",
113
+ "write_results_csv",
114
+ "write_csv",
115
+ ]
lczlite/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """``python -m lczlite``."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ sys.exit(main())
lczlite/_common.py ADDED
@@ -0,0 +1,68 @@
1
+ """Shared errors and helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import math
7
+ from pathlib import Path
8
+ from typing import Any, List, Mapping, Sequence, Union
9
+
10
+ import numpy as np
11
+
12
+ __all__ = ["LCZError", "as_array", "clean_json", "write_csv"]
13
+
14
+
15
+ class LCZError(ValueError):
16
+ """Raised for invalid parameters, range tables or options."""
17
+
18
+
19
+ def as_array(values: Any, name: str, *, allow_inf: bool = False) -> np.ndarray:
20
+ """Float array with a clear error for non-numeric input (NaN allowed = missing)."""
21
+ try:
22
+ arr = np.asarray(values, dtype=float)
23
+ except (TypeError, ValueError):
24
+ raise LCZError(f"{name} must be numeric") from None
25
+ if not allow_inf and np.isinf(arr).any():
26
+ raise LCZError(f"{name} must not contain infinite values")
27
+ return arr
28
+
29
+
30
+ def clean_json(obj: Any) -> Any:
31
+ """JSON-safe copy: NumPy to Python types, NaN/inf to ``None``."""
32
+ if isinstance(obj, dict):
33
+ return {str(k): clean_json(v) for k, v in obj.items()}
34
+ if isinstance(obj, (list, tuple)):
35
+ return [clean_json(v) for v in obj]
36
+ if isinstance(obj, np.ndarray):
37
+ return [clean_json(v) for v in obj.tolist()]
38
+ if isinstance(obj, np.generic):
39
+ obj = obj.item()
40
+ if isinstance(obj, float) and not math.isfinite(obj):
41
+ return None
42
+ return obj
43
+
44
+
45
+ def _cell(v: Any) -> Any:
46
+ if isinstance(v, np.generic):
47
+ v = v.item()
48
+ if isinstance(v, float) and not math.isfinite(v):
49
+ return ""
50
+ return v
51
+
52
+
53
+ def write_csv(rows: Sequence[Mapping[str, Any]], path: Union[str, Path]) -> Path:
54
+ """Write records to CSV (columns in first-seen order; NaN as empty)."""
55
+ if not rows:
56
+ raise LCZError("nothing to write")
57
+ fields: List[str] = []
58
+ for r in rows:
59
+ for k in r:
60
+ if k not in fields:
61
+ fields.append(k)
62
+ p = Path(path)
63
+ with p.open("w", newline="", encoding="utf-8") as fh:
64
+ w = csv.DictWriter(fh, fieldnames=fields)
65
+ w.writeheader()
66
+ for r in rows:
67
+ w.writerow({k: _cell(r.get(k, "")) for k in fields})
68
+ return p
lczlite/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
lczlite/classes.py ADDED
@@ -0,0 +1,208 @@
1
+ """The 17 Local Climate Zones, their WUDAPT integer codes and display colours.
2
+
3
+ Class keys and names follow Stewart & Oke (2012, "Local Climate Zones for urban
4
+ temperature studies", *Bulletin of the American Meteorological Society* 93(12),
5
+ 1879-1900): ten built types ``1``-``10`` and seven land-cover types ``A``-``G``.
6
+
7
+ WUDAPT products and the LCZ Generator (Demuzere, Kittner & Bechtel 2021, "LCZ Generator:
8
+ a web application to create Local Climate Zone maps", *Frontiers in Environmental Science*
9
+ 9, 637455) store the classes as integers 1-17, with ``A``-``G`` mapped to 11-17; 0 is used
10
+ here for "unclassified". The default colours are the palette commonly used for WUDAPT LCZ
11
+ maps; they are display choices and can be replaced with :func:`colour_table`.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
19
+
20
+ import numpy as np
21
+
22
+ from ._common import LCZError
23
+
24
+ __all__ = [
25
+ "LCZClass",
26
+ "LCZ_CLASSES",
27
+ "LCZ_KEYS",
28
+ "UNCLASSIFIED",
29
+ "lcz_class",
30
+ "normalize_key",
31
+ "wudapt_code",
32
+ "key_from_code",
33
+ "colour_table",
34
+ "hex_to_rgb",
35
+ "to_rgb",
36
+ "write_qml",
37
+ "write_colour_csv",
38
+ ]
39
+
40
+ UNCLASSIFIED = 0
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class LCZClass:
45
+ key: str
46
+ code: int
47
+ name: str
48
+ built: bool
49
+ colour: str
50
+
51
+ def to_dict(self) -> Dict[str, Any]:
52
+ return {
53
+ "key": self.key,
54
+ "code": self.code,
55
+ "name": self.name,
56
+ "built": self.built,
57
+ "colour": self.colour,
58
+ }
59
+
60
+
61
+ _DEF: Sequence[Tuple[str, str, str]] = (
62
+ ("1", "Compact high-rise", "#8c0000"),
63
+ ("2", "Compact midrise", "#d10000"),
64
+ ("3", "Compact low-rise", "#ff0000"),
65
+ ("4", "Open high-rise", "#bf4d00"),
66
+ ("5", "Open midrise", "#ff6600"),
67
+ ("6", "Open low-rise", "#ff9955"),
68
+ ("7", "Lightweight low-rise", "#faee05"),
69
+ ("8", "Large low-rise", "#bcbcbc"),
70
+ ("9", "Sparsely built", "#ffccaa"),
71
+ ("10", "Heavy industry", "#555555"),
72
+ ("A", "Dense trees", "#006a00"),
73
+ ("B", "Scattered trees", "#00aa00"),
74
+ ("C", "Bush, scrub", "#648525"),
75
+ ("D", "Low plants", "#b9db79"),
76
+ ("E", "Bare rock or paved", "#000000"),
77
+ ("F", "Bare soil or sand", "#fbf7ae"),
78
+ ("G", "Water", "#6a6aff"),
79
+ )
80
+
81
+ LCZ_CLASSES: Dict[str, LCZClass] = {
82
+ key: LCZClass(key=key, code=i + 1, name=name, built=i < 10, colour=colour)
83
+ for i, (key, name, colour) in enumerate(_DEF)
84
+ }
85
+ LCZ_KEYS: List[str] = list(LCZ_CLASSES)
86
+ _BY_CODE = {c.code: c for c in LCZ_CLASSES.values()}
87
+
88
+
89
+ def normalize_key(key: Any) -> str:
90
+ """Canonical LCZ key from ``1``, ``"LCZ 1"``, ``"lcz_a"``, ``"A"``, ``11`` ... .
91
+
92
+ Integers 11-17 are read as WUDAPT codes for ``A``-``G``.
93
+ """
94
+ if isinstance(key, (int, np.integer)) and not isinstance(key, bool):
95
+ return key_from_code(int(key))
96
+ if isinstance(key, float) and key.is_integer():
97
+ return key_from_code(int(key))
98
+ text = str(key).strip().upper()
99
+ for prefix in ("LCZ_", "LCZ-", "LCZ "):
100
+ if text.startswith(prefix):
101
+ text = text[len(prefix) :]
102
+ if text.startswith("LCZ"):
103
+ text = text[3:]
104
+ text = text.strip()
105
+ if text.isdigit() and 11 <= int(text) <= 17:
106
+ return key_from_code(int(text))
107
+ if text.isdigit():
108
+ text = str(int(text))
109
+ if text not in LCZ_CLASSES:
110
+ raise LCZError(f"not an LCZ class: {key!r}")
111
+ return text
112
+
113
+
114
+ def lcz_class(key: Any) -> LCZClass:
115
+ return LCZ_CLASSES[normalize_key(key)]
116
+
117
+
118
+ def wudapt_code(key: Any) -> int:
119
+ """WUDAPT integer code (1-17) of an LCZ key."""
120
+ return lcz_class(key).code
121
+
122
+
123
+ def key_from_code(code: int) -> str:
124
+ try:
125
+ return _BY_CODE[int(code)].key
126
+ except KeyError:
127
+ raise LCZError(f"not a WUDAPT LCZ code (1-17): {code!r}") from None
128
+
129
+
130
+ def hex_to_rgb(colour: str) -> Tuple[int, int, int]:
131
+ text = colour.strip().lstrip("#")
132
+ if len(text) != 6:
133
+ raise LCZError(f"expected #rrggbb, got {colour!r}")
134
+ try:
135
+ return int(text[0:2], 16), int(text[2:4], 16), int(text[4:6], 16)
136
+ except ValueError:
137
+ raise LCZError(f"expected #rrggbb, got {colour!r}") from None
138
+
139
+
140
+ def colour_table(overrides: Optional[Mapping[Any, str]] = None) -> Dict[int, str]:
141
+ """``{wudapt code: '#rrggbb'}`` with optional per-class overrides."""
142
+ table = {c.code: c.colour for c in LCZ_CLASSES.values()}
143
+ for key, colour in (overrides or {}).items():
144
+ hex_to_rgb(colour)
145
+ table[wudapt_code(key)] = colour.lower()
146
+ return table
147
+
148
+
149
+ def to_rgb(
150
+ codes: Any,
151
+ *,
152
+ colours: Optional[Mapping[int, str]] = None,
153
+ background: str = "#ffffff",
154
+ ) -> np.ndarray:
155
+ """RGB ``uint8`` image ``(..., 3)`` for an array of WUDAPT codes (0 = background)."""
156
+ arr = np.asarray(codes)
157
+ if not np.issubdtype(arr.dtype, np.integer):
158
+ if np.isnan(arr.astype(float)).any():
159
+ arr = np.nan_to_num(arr.astype(float), nan=0.0)
160
+ arr = arr.astype(int)
161
+ table = dict(colour_table()) if colours is None else dict(colours)
162
+ lut = np.zeros((18, 3), dtype=np.uint8)
163
+ lut[:] = hex_to_rgb(background)
164
+ for code, colour in table.items():
165
+ if not 1 <= int(code) <= 17:
166
+ raise LCZError(f"colour table code out of range: {code}")
167
+ lut[int(code)] = hex_to_rgb(colour)
168
+ if arr.size and (arr.min() < 0 or arr.max() > 17):
169
+ raise LCZError("codes must lie in 0-17")
170
+ return lut[arr]
171
+
172
+
173
+ def write_colour_csv(path: Union[str, Path], colours: Optional[Mapping[int, str]] = None) -> Path:
174
+ """CSV with ``code,key,name,colour,r,g,b`` for all 17 classes."""
175
+ table = colour_table() if colours is None else dict(colours)
176
+ p = Path(path)
177
+ lines = ["code,key,name,colour,r,g,b"]
178
+ for c in LCZ_CLASSES.values():
179
+ col = table.get(c.code, c.colour)
180
+ r, g, b = hex_to_rgb(col)
181
+ lines.append(f'{c.code},{c.key},"{c.name}",{col},{r},{g},{b}')
182
+ p.write_text("\n".join(lines) + "\n", encoding="utf-8")
183
+ return p
184
+
185
+
186
+ def write_qml(path: Union[str, Path], colours: Optional[Mapping[int, str]] = None) -> Path:
187
+ """QGIS raster style (paletted renderer) for a WUDAPT-coded LCZ raster."""
188
+ table = colour_table() if colours is None else dict(colours)
189
+ entries = []
190
+ for c in LCZ_CLASSES.values():
191
+ col = table.get(c.code, c.colour)
192
+ label = f"LCZ {c.key} {c.name}".replace("&", "&amp;").replace('"', "&quot;")
193
+ entries.append(
194
+ f' <paletteEntry value="{c.code}" color="{col}" alpha="255" label="{label}"/>'
195
+ )
196
+ text = (
197
+ "<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>\n"
198
+ '<qgis version="3.28" styleCategories="Symbology">\n'
199
+ " <pipe>\n"
200
+ ' <rasterrenderer type="paletted" band="1" opacity="1" nodataColor="">\n'
201
+ " <colorPalette>\n" + "\n".join(entries) + "\n </colorPalette>\n"
202
+ " </rasterrenderer>\n"
203
+ " </pipe>\n"
204
+ "</qgis>\n"
205
+ )
206
+ p = Path(path)
207
+ p.write_text(text, encoding="utf-8")
208
+ return p