|
| 1 | +""" |
| 2 | +Reverse the SWEREF conversion that was applied to Norway ("Banenor") kmm2 files. |
| 3 | +
|
| 4 | +The files in ``banenor-wire-positions-20260720`` that carry a |
| 5 | +``VER\\tNorKmmToKmm...`` header were originally delivered in the Norway format |
| 6 | +(WGS84 lat/lon, comma decimals, integer fields, 21 columns) but had their |
| 7 | +coordinate columns rewritten to SWEREF99 TM northing/easting (period decimals, |
| 8 | +float fields, 24 columns) so the old library could parse them. |
| 9 | +
|
| 10 | +This script converts those files back to their original Norway format and |
| 11 | +writes them to ``banenor-wire-positions-20260720-converted-to-original``. |
| 12 | +Files without the Norway header are left untouched (not copied). |
| 13 | +""" |
| 14 | + |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +from sweref99 import projections |
| 18 | +from tqdm import tqdm |
| 19 | + |
| 20 | +tm = projections.make_transverse_mercator("SWEREF_99_TM") |
| 21 | + |
| 22 | +input_dir = Path("/home/felix/data/banenor-wire-positions-20260720") |
| 23 | +output_dir = Path( |
| 24 | + "/home/felix/data/banenor-wire-positions-20260720-converted-to-original" |
| 25 | +) |
| 26 | + |
| 27 | +NORWAY_TOKEN = "NorKmmToKmm" |
| 28 | + |
| 29 | +# Column layout of a converted file (kmm.positions.read_kmm2.expected_columns). |
| 30 | +# The original Norway format only keeps the first 21 columns. |
| 31 | +NORTHING = 10 |
| 32 | +EASTING = 11 |
| 33 | +N_ORIGINAL_COLUMNS = 21 |
| 34 | +# Fields that are integers in the original Norway format but were written as |
| 35 | +# floats (e.g. "3.0") or zero-padded strings (e.g. "0010") after conversion. |
| 36 | +INT_COLUMNS = {1, 2, 3, 4, 6, 7, 8, 9, 12, 20} |
| 37 | + |
| 38 | + |
| 39 | +def revert_int(value): |
| 40 | + value = value.strip() |
| 41 | + if value == "": |
| 42 | + return value |
| 43 | + try: |
| 44 | + return str(int(float(value))) |
| 45 | + except ValueError: |
| 46 | + # Some fields (e.g. alphanumeric track sections like "2d") are not |
| 47 | + # numeric; leave them untouched. |
| 48 | + return value |
| 49 | + |
| 50 | + |
| 51 | +def revert_coordinate(value): |
| 52 | + # WGS84 with comma decimals, mirroring the original delivered precision. |
| 53 | + return repr(float(value)).replace(".", ",") |
| 54 | + |
| 55 | + |
| 56 | +def revert_line(line): |
| 57 | + if not line.startswith("POS"): |
| 58 | + return line |
| 59 | + fields = line.split("\t") |
| 60 | + |
| 61 | + northing = float(fields[NORTHING]) |
| 62 | + easting = float(fields[EASTING]) |
| 63 | + latitude, longitude = tm.grid_to_geodetic(northing, easting) |
| 64 | + fields[NORTHING] = revert_coordinate(latitude) |
| 65 | + fields[EASTING] = revert_coordinate(longitude) |
| 66 | + |
| 67 | + for index in INT_COLUMNS: |
| 68 | + if index < len(fields): |
| 69 | + fields[index] = revert_int(fields[index]) |
| 70 | + |
| 71 | + return "\t".join(fields[:N_ORIGINAL_COLUMNS]) |
| 72 | + |
| 73 | + |
| 74 | +def revert_file(path): |
| 75 | + # latin1 + CRLF, matching the original delivery. |
| 76 | + text = path.read_text(encoding="latin1") |
| 77 | + lines = text.split("\n") |
| 78 | + out_lines = [revert_line(line.rstrip("\r")) for line in lines if line != ""] |
| 79 | + return "\r\n".join(out_lines) + "\r\n" |
| 80 | + |
| 81 | + |
| 82 | +def classify(path): |
| 83 | + """ |
| 84 | + Categorise a kmm2 file: |
| 85 | + - "non-norway": missing the NorKmmToKmm header (leave as is). |
| 86 | + - "sweref": norway header, coordinate columns hold SWEREF99 TM |
| 87 | + northing/easting (converted) -> reverse to lat/lon. |
| 88 | + - "latlon": norway header, coordinate columns already hold WGS84 |
| 89 | + lat/lon (never converted) -> no reversion needed. |
| 90 | + - "unknown": norway header but no parseable/degenerate coordinates. |
| 91 | + """ |
| 92 | + with open(path, "r", encoding="latin1") as f: |
| 93 | + first_line = f.readline() |
| 94 | + if not (first_line.startswith("VER") and NORWAY_TOKEN in first_line): |
| 95 | + return "non-norway" |
| 96 | + for line in f: |
| 97 | + if line.startswith("POS"): |
| 98 | + fields = line.rstrip("\r\n").split("\t") |
| 99 | + try: |
| 100 | + northing = float(fields[NORTHING].replace(",", ".")) |
| 101 | + except (ValueError, IndexError): |
| 102 | + return "unknown" |
| 103 | + if abs(northing) > 100_000: |
| 104 | + return "sweref" |
| 105 | + if 3 < abs(northing) < 100: |
| 106 | + return "latlon" |
| 107 | + return "unknown" |
| 108 | + return "unknown" |
| 109 | + |
| 110 | + |
| 111 | +def main(): |
| 112 | + output_dir.mkdir(exist_ok=True) |
| 113 | + paths = sorted(input_dir.glob("*.kmm2")) |
| 114 | + |
| 115 | + categories = {"non-norway": [], "sweref": [], "latlon": [], "unknown": []} |
| 116 | + for path in tqdm(paths): |
| 117 | + kind = classify(path) |
| 118 | + categories[kind].append(path.name) |
| 119 | + if kind == "sweref": |
| 120 | + (output_dir / path.name).write_text(revert_file(path), encoding="latin1") |
| 121 | + |
| 122 | + print(f"reverse-converted (sweref -> original latlon): {len(categories['sweref'])}") |
| 123 | + print(f"non-norway (left as is): {len(categories['non-norway'])}") |
| 124 | + print(f"already original latlon (left as is): {len(categories['latlon'])}") |
| 125 | + for name in categories["latlon"]: |
| 126 | + print(f" {name}") |
| 127 | + print(f"unknown/degenerate (left as is): {len(categories['unknown'])}") |
| 128 | + for name in categories["unknown"]: |
| 129 | + print(f" {name}") |
| 130 | + |
| 131 | + |
| 132 | +if __name__ == "__main__": |
| 133 | + main() |
0 commit comments