Skip to content

Add UTM and MGRS coordinate functions - #108939

Merged
alexey-milovidov merged 9 commits into
masterfrom
utm-mgrs-functions
Jul 6, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
utm-mgrs-functions

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

Description

Add four geographic coordinate-conversion functions for the UTM (Universal Transverse Mercator) and MGRS (Military Grid Reference System) coordinate systems:

  • geoToUTM(longitude, latitude[, zone]) — converts WGS84 coordinates to UTM, returning a named tuple (easting, northing, zone, band).
  • UTMToGeo(easting, northing, zone, is_north) — the inverse of geoToUTM.
  • geoToMGRS(longitude, latitude[, precision]) — encodes a point as an MGRS string such as 31UDQ4825111935.
  • MGRSToGeo(mgrs) — decodes an MGRS string to the centre of the referenced grid square.

Motivation. UTM and MGRS are widely used in surveying, GIS, GPS and mapping to work with planar coordinates in metres. ClickHouse already has geohashEncode/geohashDecode, H3, S2 and great-circle distance, but no projected-coordinate conversion, so users currently round-trip through external tools.

Implementation. The conversion uses the truncated transverse Mercator series on the WGS84 ellipsoid with no new external dependency, applying the standard Norway and Svalbard zone exceptions. The shared math lives in UTMCoordinates; the zone is auto-selected from the longitude unless an explicit zone is given. MGRSToGeo returns the centre of the grid square (consistent with geohashDecode and stable for round-tripping).

The results were validated against the independent Python utm and mgrs libraries across both hemispheres, the equator, and the Norway/Svalbard zones: easting and northing agree to sub-millimetre, and all zone numbers, latitude bands and MGRS strings match.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Added functions geoToUTM, UTMToGeo, geoToMGRS and MGRSToGeo for converting between WGS84 geographic coordinates and the UTM and MGRS coordinate systems.

Documentation entry for user-facing changes

  • Documentation added in docs/en/sql-reference/functions/geo/coordinates.md.

Add four geographic coordinate-conversion functions:

- `geoToUTM(longitude, latitude[, zone])` converts WGS84 coordinates to
  Universal Transverse Mercator, returning a named tuple
  `(easting, northing, zone, band)`.
- `utmToGeo(easting, northing, zone, is_north)` is the inverse.
- `geoToMGRS(longitude, latitude[, precision])` encodes a point as a
  Military Grid Reference System string such as `31UDQ4825111935`.
- `mgrsToGeo(mgrs)` decodes an MGRS string to the centre of the referenced
  grid square (consistent with `geohashDecode`, and stable for round-tripping).

The conversion uses the truncated transverse Mercator series on the WGS84
ellipsoid with no external dependency, applying the standard Norway and
Svalbard zone exceptions. The shared math lives in `UTMCoordinates`.

Validated against the independent Python `utm` and `mgrs` libraries across
both hemispheres, the equator, and the Norway/Svalbard zones: easting and
northing agree to sub-millimetre, and all zone numbers, latitude bands and
MGRS strings match.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [27734f5]

Summary: ✅


AI Review

Summary

This PR adds geoToUTM, UTMToGeo, geoToMGRS, and MGRSToGeo for WGS84/UTM/MGRS conversion. The code-level validation issues from earlier bot threads are addressed in the current head, but the PR metadata still advertises the old lowercase reverse function names, which would publish incorrect user-facing names.

PR Metadata
  • Changelog category: New Feature is appropriate.
  • Changelog entry: required, but the current entry still says utmToGeo and mgrsToGeo after the implementation was renamed to case-sensitive UTMToGeo and MGRSToGeo.
  • Suggested replacement:
Added functions `geoToUTM`, `UTMToGeo`, `geoToMGRS` and `MGRSToGeo` for converting between WGS84 geographic coordinates and the UTM and MGRS coordinate systems.
Missing context / blind spots
  • ⚠️ I could not run the stateless test locally because this checkout has no build directory. The Praktika PR report linked by the robot comment returned a PR summary with 0 test entries; a passing CI report or local run of 04489_geo_utm_mgrs would close this gap.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: update the PR description and changelog entry to use UTMToGeo and MGRSToGeo (or add lowercase aliases if those names are intended to be valid).

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 30, 2026
```

```text
┌─coord──────────────────────────────────┐

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Misaligned.

The `arm_tidy` build flagged `cppcoreguidelines-init-variables` and
`readability-use-std-min-max` in `UTMCoordinates.cpp`: initialize `zone`,
and replace the manual clamps with `std::clamp` and `std::min`.
No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Functions/UTMCoordinates.cpp Resolved
Comment thread src/Functions/mgrsToGeo.cpp Resolved
- `mgrsToGeo`: reject MGRS strings with more than five digits per
  coordinate (previously `per` was unbounded, so an over-long string such
  as `31UDQ482511193512` decoded to a sub-metre cell the encoder can never
  produce). Now throws `BAD_ARGUMENTS`, with a regression query.
- Fix the stale "south-west corner" wording in the `mgrsToGeo`
  `FunctionDocumentation` and the `mgrsDecode` declaration comment in
  `UTMCoordinates.h` to say "centre", matching the actual behaviour and the
  documentation page.
- Docs: named tuples now render as multi-line JSON in pretty formats, so
  show the tuple results inline instead of in misaligned boxes.
Comment thread src/Functions/UTMCoordinates.cpp Resolved
Comment thread src/Functions/UTMCoordinates.cpp Resolved
Comment thread src/Functions/geoToMGRS.cpp Resolved
Comment thread src/Functions/geoToMGRS.cpp Resolved
Comment thread src/Functions/UTMCoordinates.cpp Resolved
alexey-milovidov and others added 2 commits June 30, 2026 15:17
Address a second round of review comments:

- `mgrsToGeo`: reject 100km square column letters beyond the eight valid
  columns for the zone (e.g. `31UQD...`), which previously decoded to an
  easting far outside the zone and a longitude outside `[-180, 180]`.
- `mgrsToGeo`: reject the even zones `32`, `34`, `36` in the `X` band, which
  do not exist there (e.g. `32XAA`), matching the reference implementations.
- `geoToUTM`: make the Svalbard exception upper bound inclusive so that
  `geoToUTM(6, 84)` returns zone 31, consistent with the documented latitude
  domain `[-80, 84]`.
- `geoToMGRS`: throw `ARGUMENT_OUT_OF_BOUND` for `precision` outside `[0, 5]`
  instead of silently clamping, following the avoid-fallback principle and
  symmetric with the `mgrsToGeo` digit-count check.

Verified the new rejections and the latitude-84 zone against the Python
`utm` and `mgrs` libraries; added regression queries for each case.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `SELECT '-- error handling';` label statement produces output when the
test harness runs the full file, but the earlier reference was generated by
stripping everything from that line onward, so the harness reported a diff.
Regenerate the reference keeping the label and dropping only the
`serverError`-annotated queries (which produce no output).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Functions/UTMCoordinates.cpp Resolved
From review:

- `mgrsToGeo`: reject squares whose decoded latitude does not fall within the
  declared latitude band. A row letter that does not occur in the band (e.g.
  `1LAB`) previously decoded, after the northing roll-over, to a point a full
  ~2000km cycle away in another band. The 1 degree tolerance admits cells that
  straddle a band boundary (a 100km cell reaches at most ~0.5 degrees past it),
  which a 200k-point encode/decode sweep confirmed never over-rejects.
- Tests: the Norway and Svalbard zone-exception checks used points that the
  normal 6 degree formula already maps to the same zone, so they did not
  exercise the exceptions. Use `geoToUTM(4, 60)` (normal 31 -> 32) and
  `geoToUTM(20, 78)` (normal 34 -> 33), and add a `1LAB` regression.

Behaviour verified against the Python `mgrs` library, which rejects `1LAB`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Functions/mgrsToGeo.cpp Resolved
`mgrsToGeo` advertises `FixedString` input, but `FixedString(N)` null-pads
values shorter than `N`, and those trailing `\0` bytes reached `mgrsDecode`
and failed as odd/non-digit location data. For example
`mgrsToGeo(toFixedString('31UDQ4825111935', 20))` threw instead of decoding.

Trim the trailing `\0` padding for the `ColumnFixedString` specialization
(via `if constexpr`) before decoding; `String` input is unaffected. Added a
regression query comparing the `FixedString` and `String` decodes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Functions/utmToGeo.cpp Resolved
Comment thread src/Functions/UTMCoordinates.cpp Resolved
alexey-milovidov and others added 2 commits June 30, 2026 17:21
From review:

- `mgrsToGeo`: bound the zone designator to one or two digits. The parser
  previously consumed an unbounded digit prefix, so `031UDQ...` was accepted
  as zone 31 and a very long prefix could overflow `std::stoi`.
- `utmToGeo`: reject `is_north` values other than `0` or `1` instead of
  treating every nonzero value as north, matching the documented contract and
  the strict validation used elsewhere in these functions.

Added regression queries for both.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Keep the acronym capitalisation consistent between the forward and reverse
functions: the reverse functions now spell the acronym in upper case
(`UTMToGeo`, `MGRSToGeo`) to match `geoToUTM` and `geoToMGRS`. Updates the
function names, syntax strings, documentation and tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Functions/utmToGeo.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Reviewed and synced the PR after the utmToGeo/mgrsToGeo → UTMToGeo/MGRSToGeo rename (commit 27734f5):

  • PR body updated to use the new function names UTMToGeo/MGRSToGeo (description + changelog entry); no stale references to the old names remain anywhere in src/, tests/, or docs/.
  • Resolved the two remaining clickhouse-gh threads, both already fixed in code with regression coverage:
    • is_north must be 0 or 1 — UTMToGeo throws BAD_ARGUMENTS otherwise (utmToGeo.cpp:79-83); covered by SELECT UTMToGeo(448251.6, 5411935.13, 31, 2).
    • Zone designator capped at two digits before std::stoi (UTMCoordinates.cpp:383-389); covered by SELECT MGRSToGeo('031UDQ4825111935').
  • The only open thread left is your own outdated "Misaligned." note on coordinates.md; the doc now renders aligned, so it looks already addressed — leaving it for you to resolve.

CI is still scheduling (Fast test / builds in progress, no failures so far). No code changes were needed.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr pass):

The latest AI Review "⚠️ Request changes" verdict is stale — its sole required action (sync the PR description/changelog from utmToGeo/mgrsToGeo to UTMToGeo/MGRSToGeo) was already done in the prior pass. The verdict was generated at 17:31:22Z, ~40s before the body edit landed at 17:32:05Z, so it read the pre-edit metadata.

Verified now:

  • PR body + changelog entry use UTMToGeo/MGRSToGeo only; zero lowercase utmToGeo/mgrsToGeo references remain in src/, tests/, docs/, or the changelog entry (grep-confirmed).
  • Registered names match: geoToUTM, UTMToGeo, geoToMGRS, MGRSToGeo. The mixed-case reverse names are the intended case-sensitive names mirroring the forward functions — no lowercase aliases wanted.
  • Test 04489_geo_utm_mgrs.{sql,reference} is tracked and uses the new names.

Replied to and resolved the new clickhouse-gh metadata thread accordingly. No code changes were needed; the verdict should re-flip to approved on the next CI run.

CI: no failures (75 green, 74 still in progress). MERGEABLE, merge-base ~17h old (<1d), no conflicts — no re-merge needed. The only remaining open thread is your own outdated "Misaligned." note on coordinates.md (doc now renders aligned), left for you to resolve.

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.70% 92.60% -0.10%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 440/506 (86.96%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr pass):

The sole CI red is Upgrade check (amd_release) → Error message in clickhouse-server.log, which is a known master-wide flake unrelated to this PR (this PR adds only the geo functions and touches no PostgreSQL code):

Reran the failed job (the flake is timing-dependent — it only fires when the reconnect task happens to log during the upgrade-check window), so the rerun may go green on its own.

The AI Review ⚠️ Request changes verdict remains stale: its only required action (sync the description/changelog away from utmToGeo/mgrsToGeo) was already done — the registered names (geoToUTM, UTMToGeo, geoToMGRS, MGRSToGeo), the PR body, and the test all use the case-sensitive names; zero lowercase references remain.

No code changes and no re-merge needed (merge-base ~today, MERGEABLE, no conflicts). The only open thread is your own outdated "Misaligned." note on coordinates.md; the geoToMGRS output box now renders aligned (all box rows are a consistent 33 columns wide), so it is already addressed.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr pass):

CI is now fully green. The Upgrade check (amd_release) → Error message in clickhouse-server.log flake noted in the previous pass has cleared on rerun — the latest report for the current head 27734f50 shows 0 failures (150 passed, 20 skipped), and every status context (PR, Style check, Mergeable Check, CH Inc sync) is SUCCESS. MERGEABLE, no conflicts, merge-base ~1 day old — no re-merge needed.

Independently re-verified the two remaining loose ends:

  • The "Misaligned." self-note on coordinates.md is addressed. Measured the display width of every box-drawing block in the file: all six tables render at a consistent per-line width (geoToUTM/UTMToGeo/MGRSToGeo outputs are now plain text; the geoToMGRS two-column box is a uniform 33 columns across header/data/footer). Left the thread for you to resolve since it is your own.
  • The AI Review ⚠️ Request changes verdict is stale. Its sole required action (sync the description/changelog from utmToGeo/mgrsToGeo to the case-sensitive UTMToGeo/MGRSToGeo) is already done: the PR body and changelog entry use the new names, the registered function names are geoToUTM/UTMToGeo/geoToMGRS/MGRSToGeo, and a grep finds zero lowercase references in src/, docs/, or tests/.

No code changes needed. The PR is effectively ready — only a human approval is outstanding.

yonas pushed a commit to yonasBSD/ClickHouse that referenced this pull request Jul 1, 2026
…e check

The upgrade check (`tests/docker_scripts/upgrade_runner.sh`) scans the
post-upgrade server log for `<Error>` lines and fails on anything not in its
allow-list. It intermittently fails with:

    <Error> PostgreSQLConnectionPool: Connection error: connection to server at "192.0.2.1", port 5432 failed: timeout expired
    <Error> void DB::DatabasePostgreSQL::removeOutdatedTables(): Code: 614. DB::Exception: Try 2. Connection to `192.0.2.1:5432` failed ...

These come from a leftover `DatabasePostgreSQL` engine created by
`04210_show_remote_databases_in_system_tables`, which points at the RFC 5737
documentation IP `192.0.2.1` (intentionally unreachable). The stress phase runs
the stateless tests under a global time limit and can interrupt that test
between its `CREATE DATABASE ... ENGINE = PostgreSQL('192.0.2.1:5432', ...)` and
the final `DROP DATABASE`, leaving the database in metadata. After the upgrade
restart, `DatabasePostgreSQL::startup` unconditionally activates the
`PostgreSQLCleanerTask`, whose `removeOutdatedTables` tries to connect and the
connection pool logs `<Error>` for each retry.

This is the same class of benign background-reconnection-after-restart noise
already allow-listed for Kafka (`rdk:FAIL`/`StorageKafka2`), Azure DNS, and
NuRaft. Add two regex filters in the secondary pipe that require the PostgreSQL
connection-pool / cleaner-task context together with the connection-failure
symptom, so real PostgreSQL regressions (auth, protocol, query errors) are not
masked.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108939&sha=27734f50667a6b77ca59b768e605b4d843acde3c&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
Related: ClickHouse#108939

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@mneedham

mneedham commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

I tried out the functions with some examples - the usability seems good to me

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 6, 2026
Merged via the queue into master with commit b156ede Jul 6, 2026
343 of 344 checks passed
@alexey-milovidov
alexey-milovidov deleted the utm-mgrs-functions branch July 6, 2026 18:42
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 6, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…e check

The upgrade check (`tests/docker_scripts/upgrade_runner.sh`) scans the
post-upgrade server log for `<Error>` lines and fails on anything not in its
allow-list. It intermittently fails with:

    <Error> PostgreSQLConnectionPool: Connection error: connection to server at "192.0.2.1", port 5432 failed: timeout expired
    <Error> void DB::DatabasePostgreSQL::removeOutdatedTables(): Code: 614. DB::Exception: Try 2. Connection to `192.0.2.1:5432` failed ...

These come from a leftover `DatabasePostgreSQL` engine created by
`04210_show_remote_databases_in_system_tables`, which points at the RFC 5737
documentation IP `192.0.2.1` (intentionally unreachable). The stress phase runs
the stateless tests under a global time limit and can interrupt that test
between its `CREATE DATABASE ... ENGINE = PostgreSQL('192.0.2.1:5432', ...)` and
the final `DROP DATABASE`, leaving the database in metadata. After the upgrade
restart, `DatabasePostgreSQL::startup` unconditionally activates the
`PostgreSQLCleanerTask`, whose `removeOutdatedTables` tries to connect and the
connection pool logs `<Error>` for each retry.

This is the same class of benign background-reconnection-after-restart noise
already allow-listed for Kafka (`rdk:FAIL`/`StorageKafka2`), Azure DNS, and
NuRaft. Add two regex filters in the secondary pipe that require the PostgreSQL
connection-pool / cleaner-task context together with the connection-failure
symptom, so real PostgreSQL regressions (auth, protocol, query errors) are not
masked.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108939&sha=27734f50667a6b77ca59b768e605b4d843acde3c&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
Related: ClickHouse#108939

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants