File size: 10,312 Bytes
e95f494
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Sanity-check the coordinates and CRS of georeferenced LAS/LAZ point clouds.

Role in the pipeline:
    A verification utility that confirms the HoliCity (London) tiles have been
    georeferenced correctly before tiling. It inspects each LAS/LAZ file's header
    and bounding box, reprojects the bbox center to WGS84, and checks whether that
    center falls within an approximate London bounding box.

Behavior:
    - Recursively scans a directory for .las/.laz files.
    - Reads header stats (EPSG, bbox, point count, point format, scale, offset)
      and detects degenerate "near (0,0)" coordinates.
    - If the file has an EPSG, reprojects its center to WGS84 and flags whether it
      lies in the London region.
    - If no EPSG is present, tries a list of candidate CRSs (BNG / UTM 30N / Web
      Mercator / WGS84) and reports the first one whose center lands in London.
    - Emits a per-file status (OK / WARN / BAD / ERR) plus a hint, printed as a
      table and optionally exported to CSV.

Inputs:  directory of .las/.laz files (CLI: -d/--dir), optional CSV path (-o/--output).
Outputs: a console report table and an optional CSV file. No files are modified.
External tools: laspy, numpy, pyproj.
"""

import os
import sys
import csv
import math
import argparse
from pathlib import Path

import laspy
import numpy as np
from pyproj import CRS, Transformer

# ----------- Tunable parameters -----------
# London region (WGS84)
LON_MIN, LON_MAX = -0.6, 0.4
LAT_MIN, LAT_MAX = 51.2, 51.8

# Common candidate CRSs (used to guess when no EPSG is present)
CANDIDATE_EPSGS = [
    27700,   # OSGB36 / British National Grid
    32630,   # WGS84 / UTM zone 30N
    3857,    # Web Mercator
    4326,    # WGS84 (lat/lon)
]

# Rough "plausible ranges" for the UK / London (quick sanity check; approximate only)
RANGE_HINTS = {
    27700: {"E": (0, 700000), "N": (0, 1300000), "name": "OSGB36 / BNG"},
    32630: {"E": (160000, 840000), "N": (5550000, 5900000), "name": "UTM 30N"},
    3857: {"X": (-500000, 500000), "Y": (6200000, 7300000), "name": "WebMerc"},
    4326: {"Lon": (-10, 10), "Lat": (45, 60), "name": "WGS84 deg"},
}
# Approximate reference for the center of London (used only for printed hints)
LONDON_WGS84 = (-0.1, 51.51)

# --------------------------------

def in_london(lon, lat):
    return (LON_MIN <= lon <= LON_MAX) and (LAT_MIN <= lat <= LAT_MAX)

def safe_epsg_str(epsg):
    try:
        return f"EPSG:{int(epsg)}"
    except Exception:
        return "None"

def read_stats(path: Path, sample_n: int = 200000):
    """Read the bbox and center point; for large clouds only the header bbox is read; sample some points for QC if needed."""
    with laspy.open(str(path)) as f:
        hdr = f.header
        mins = np.array(getattr(hdr, "mins", getattr(hdr, "min", (0, 0, 0))), dtype=float)
        maxs = np.array(getattr(hdr, "maxs", getattr(hdr, "max", (0, 0, 0))), dtype=float)
        epsg = None
        try:
            epsg = hdr.epsg
        except Exception:
            pass

        # Center point (the bbox midpoint is sufficient)
        cx = (mins[0] + maxs[0]) * 0.5
        cy = (mins[1] + maxs[1]) * 0.5
        cz = (mins[2] + maxs[2]) * 0.5

        # Check whether everything sits near (0,0)
        zeroish = (abs(cx) < 1e-6 and abs(cy) < 1e-6) or \
                  (abs(mins[0]) < 1e-6 and abs(maxs[0]) < 1e-6 and
                   abs(mins[1]) < 1e-6 and abs(maxs[1]) < 1e-6)

        return {
            "epsg": epsg,
            "mins": mins, "maxs": maxs,
            "center": (cx, cy, cz),
            "zeroish": zeroish,
            "point_count": int(getattr(hdr, "point_count", 0)),
            "point_format": str(getattr(hdr.point_format, "id", hdr.point_format)),
            "scale": tuple(hdr.scales),
            "offset": tuple(hdr.offsets),
        }

def transform_to_wgs84(x, y, epsg):
    """Reproject (x,y) from the given EPSG to WGS84 lon/lat. Return None on failure."""
    try:
        src = CRS.from_epsg(int(epsg))
        dst = CRS.from_epsg(4326)
        tr = Transformer.from_crs(src, dst, always_xy=True)
        lon, lat = tr.transform(x, y)
        return lon, lat
    except Exception:
        return None

def guess_and_transform_to_wgs84(x, y, candidates=CANDIDATE_EPSGS):
    """When no EPSG is set, try each candidate CRS in turn; return the first projection that falls within the London region, along with its epsg."""
    tried = []
    for epsg in candidates:
        res = transform_to_wgs84(x, y, epsg)
        if res is None: 
            tried.append((epsg, None))
            continue
        lon, lat = res
        tried.append((epsg, (lon, lat)))
        if in_london(lon, lat):
            return (lon, lat), epsg, tried
    return None, None, tried

def range_hint_text(epsg, mins, maxs):
    h = RANGE_HINTS.get(int(epsg)) if epsg is not None else None
    if not h:
        return ""
    if epsg in (27700, 32630):
        E = (mins[0], maxs[0]); N = (mins[1], maxs[1])
        return f"RangeHint {h['name']}: E∈{h['E']} vs {E}, N∈{h['N']} vs {N}"
    elif epsg == 3857:
        X = (mins[0], maxs[0]); Y = (mins[1], maxs[1])
        return f"RangeHint {h['name']}: X∈{h['X']} vs {X}, Y∈{h['Y']} vs {Y}"
    elif epsg == 4326:
        Lon = (mins[0], maxs[0]); Lat = (mins[1], maxs[1])
        return f"RangeHint {h['name']}: Lon∈{h['Lon']} vs {Lon}, Lat∈{h['Lat']} vs {Lat}"
    return ""

def analyze_file(path: Path):
    size_mb = path.stat().st_size / (1024 * 1024)
    stats = read_stats(path)
    epsg = stats["epsg"]
    cx, cy, cz = stats["center"]
    mins, maxs = stats["mins"], stats["maxs"]

    result = {
        "file": str(path.name),
        "size_mb": f"{size_mb:.2f}",
        "epsg": safe_epsg_str(epsg),
        "pt_fmt": stats["point_format"],
        "pts": stats["point_count"],
        "scale": stats["scale"],
        "offset": stats["offset"],
        "center_xy": (cx, cy),
        "center_wgs84": None,
        "in_london": False,
        "status": "",
        "hint": "",
    }

    # 0) All-zero / near-zero
    if stats["zeroish"]:
        result["status"] = "BAD"
        result["hint"] = "Coordinates near (0,0); likely unassigned or wrong projection. Check the coordinate transform and EPSG write."
        return result

    # 1) Has EPSG: project and check directly
    if epsg is not None:
        wgs = transform_to_wgs84(cx, cy, int(epsg))
        if wgs is None:
            result["status"] = "WARN"
            result["hint"] = f"Could not project the center from {safe_epsg_str(epsg)} to WGS84; the EPSG may be invalid."
            return result
        lon, lat = wgs
        result["center_wgs84"] = (round(lon, 6), round(lat, 6))
        result["in_london"] = in_london(lon, lat)
        if result["in_london"]:
            result["status"] = "OK"
            result["hint"] = f"Center is within the London region; {range_hint_text(int(epsg), mins, maxs)}"
        else:
            result["status"] = "WARN"
            result["hint"] = f"Center is outside the London region ({lon:.5f},{lat:.5f}); if it should be in London, the EPSG or translation may be wrong. {range_hint_text(int(epsg), mins, maxs)}"
        return result

    # 2) No EPSG: try to guess and check whether it lands in London
    guessed, gepsg, tried = guess_and_transform_to_wgs84(cx, cy)
    if guessed is not None:
        lon, lat = guessed
        result["center_wgs84"] = (round(lon, 6), round(lat, 6))
        result["in_london"] = True
        result["status"] = "WARN"
        result["hint"] = (f"No EPSG written, but {safe_epsg_str(gepsg)} is inferred to fall in the London region. "
                          f"Suggest writing {safe_epsg_str(gepsg)} and retrying.")
    else:
        result["status"] = "BAD"
        tried_text = "; ".join(
            f"EPSG:{e} -> {('None' if v is None else f'({v[0]:.5f},{v[1]:.5f})')}" for e, v in tried
        )
        result["hint"] = ("No EPSG written, and none of the common candidate CRSs project the center into the London region. "
                          "Check whether a wrong translation/rotation/unit was used, or whether a different EPSG is needed. "
                          f"Attempts: {tried_text}")
    return result

def print_table(rows):
    headers = ["file","size_mb","epsg","pt_fmt","pts","center_xy","center_wgs84","in_london","status","hint"]
    colw = {h: max(len(h), max((len(str(r[h])) for r in rows), default=0)) for h in headers}
    sep = " | "
    print(sep.join(h.ljust(colw[h]) for h in headers))
    print("-" * (sum(colw.values()) + len(sep)*(len(headers)-1)))
    for r in rows:
        print(sep.join(str(r[h]).ljust(colw[h]) for h in headers))

def main():
    ap = argparse.ArgumentParser(description="Check whether LAS/LAZ files have correct coordinates and CRS, and whether they fall within the London region.")
    ap.add_argument("-d","--dir", default=".", help="Directory to scan (default: current directory)")
    ap.add_argument("-o","--output", default=None, help="CSV export path (optional)")
    args = ap.parse_args()

    root = Path(args.dir).resolve()
    if not root.exists():
        print(f"Directory does not exist: {root}", file=sys.stderr); sys.exit(1)

    files = []
    for p in root.rglob("*"):
        if p.is_file() and p.suffix.lower() in (".las",".laz"):
            files.append(p)

    if not files:
        print("No .las/.laz files found"); return

    rows = []
    for p in sorted(files):
        try:
            rows.append(analyze_file(p))
        except Exception as e:
            rows.append({
                "file": p.name, "size_mb":"?", "epsg":"?", "pt_fmt":"?", "pts":"?",
                "center_xy":"?", "center_wgs84":"?", "in_london":"?", "status":"ERR",
                "hint": f"Parse failed: {e}"
            })

    print(f"Scan directory: {root}\n")
    print_table(rows)

    if args.output:
        out = Path(args.output).resolve()
        out.parent.mkdir(parents=True, exist_ok=True)
        with out.open("w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
            writer.writeheader()
            writer.writerows(rows)
        print(f"\nCSV written: {out}")

if __name__ == "__main__":
    main()