mortie.tools
Encoding, decoding, inspection, and buffering of packed morton words.
Functions for morton indexing.
geo2mort(lats, lons, order=None, points=None)
Compute morton indices from geographic coordinates.
The entire pipeline runs in Rust via the healpix crate — no
Python HEALPix backend is needed.
lat/lon inputs are treated as points by default (indeterminate
resolution, encoded at max precision), so a bare geo2mort(lats, lons)
returns order-29 Kind::Point words. Passing an explicit order asks
for an area cell at that resolution instead (points inferred
False). The two flags resolve as:
order=None, points=None(bare call) -> order-29 point words;- an explicit
orderwithpointsunset -> area cell atorder; points=True-> order-29 point words (order-29-only; an explicitorder != 29raisesValueError, matching :meth:MortonIndexArray.from_latlon);points=False-> area cell atorder(order=None-> 29).
Non-finite lat/lon encode to the reserved empty word 0 (base
cell 0 is the null sentinel) on both the area and point routes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lats
|
array - like
|
Latitude(s) in degrees. |
required |
lons
|
array - like
|
Longitude(s) in degrees. |
required |
order
|
int
|
HEALPix order (0-29). Defaults to 29. An explicit value implies an area
cell unless |
None
|
points
|
bool
|
Encode |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Packed |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in mortie/tools.py
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 | |
mort2geo(morton)
Convert morton index to lat/lon of pixel center.
This is the inverse of geo2mort, returning the center coordinates of the HEALPix cell identified by the morton index.
Mixed-order arrays are supported (issue #116): elements are grouped by
order (:func:orders_of), each group runs the uniform kernel, and the
results scatter back to input positions. Point words (spec §4) are order
29 by definition and group with order 29 — a point's location is exactly
what mort2geo returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton
|
int or array - like
|
Morton index (mixed orders allowed). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
lat |
float or array
|
Latitude in degrees |
lon |
float or array
|
Longitude in degrees |
Source code in mortie/tools.py
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 | |
mort2bbox(morton)
Convert morton index to bounding box of the pixel.
For pixels touching the antimeridian, vertex longitudes at ±180° are normalized to use consistent representation based on hemisphere voting, preventing bbox misinterpretation as spanning the entire globe.
Mixed-order arrays are supported (issue #116): elements are grouped by
order (:func:orders_of), each group runs the uniform kernel, and the
results scatter back to input positions. Point words (spec §4) are order
29 by definition and group with order 29 — a point yields the bounding box
of its containing order-29 cell (the cell that contains the point), which
is exactly the bbox of the order-29 area word at the same location. A
group of points therefore covers a well-defined area, element by element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton
|
int or array - like
|
Morton index (mixed orders allowed). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bbox |
dict or list of dicts
|
Bounding box in format suitable for STAC/CMR: {"west": min_lon, "south": min_lat, "east": max_lon, "north": max_lat} |
Source code in mortie/tools.py
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 | |
mort2polygon(morton, step=1)
Convert morton index to polygon representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton
|
int or array - like
|
Morton index. |
required |
step
|
int
|
Points per side for the cell boundary (default 1 = 4 corners). Use step=32 for 128 boundary points that accurately trace curved cell edges, important for polar cells where 4-corner polygons poorly approximate the true HEALPix boundary. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
polygon |
list or list of lists
|
Polygon coordinates as [[lat, lon], ...] in standard geographic order. The polygon is closed (first point repeated at end). Note: Returns [lat, lon] pairs, NOT [lon, lat]. This is the standard geographic coordinate order used by most spatial analysis libraries. |
Notes
Polygons that touch the antimeridian (±180° longitude) are automatically normalized to use consistent longitude representation (-180 or +180) based on which hemisphere contains the majority of vertices. This prevents spatial libraries from misinterpreting touching polygons as crossing polygons.
Mixed-order arrays are supported (issue #116): elements are grouped by
order (:func:orders_of), each group runs the uniform kernel, and the
results scatter back to input positions (rings are 4step+1 vertices at
every order, so mixed orders do not change the output shape). Point words
(spec §4) are order 29 by definition and group with order 29 — a point
yields the polygon ring of its containing order-29 cell, exactly the ring
of the order-29 area* word at the same location.
Source code in mortie/tools.py
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 | |
mort2healpix(morton)
Convert morton index to HEALPix cell ID and order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton
|
int or array - like
|
Morton index. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
cell_ids |
int or ndarray
|
HEALPix cell ID(s) in NESTED scheme |
order |
int
|
HEALPix order (resolution level) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the words are at mixed orders (propagated from :func: |
Notes
The function converts morton indices to HEALPix NESTED scheme cell IDs. All input morton indices must be at the same order.
Examples:
>>> import mortie
>>> m = mortie.geo2mort(-80.0, 120.0, order=6)[0]
>>> cell_id, order = mortie.mort2healpix(m)
>>> print(f"HEALPix cell {cell_id} at order {order}")
HEALPix cell 37010 at order 6
Source code in mortie/tools.py
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 | |
mort2norm(morton)
Convert morton index back to normalized address and parent cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton
|
int or array - like
|
Packed morton word(s) ( |
required |
Returns:
| Name | Type | Description |
|---|---|---|
normed |
int or array
|
Normalized HEALPix address |
parent |
int or array
|
Parent base cell (0-11) |
order |
int or array
|
HEALPix order inferred from morton index |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the words are at mixed orders — the return contract carries a single
scalar order, so use :func: |
Notes
Empty input returns two empty int64 arrays and order == 0.
Source code in mortie/tools.py
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 | |
norm2mort(normed, parent, order)
Convert a normalized HEALPix address + base cell to a packed morton word.
The exact inverse of :func:mort2norm: mort2norm(norm2mort(n, p, o))
returns (n, p, o). Born order-29-native (issue #48) — there is no order
cap beyond the kernel's MAX_ORDER of 29. The returned uint64 is the
packed decimal_morton word (issue #58; the prefix is base+1, so bit 63
is set — a large unsigned value — for base cells 7-11), not the retired
decimal encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
normed
|
int or array
|
Normalized HEALPix address (the in-base z-order, |
required |
parent
|
int or array
|
Parent base cell (0-11). |
required |
order
|
int
|
HEALPix order (0-29). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
morton |
uint64 or ndarray
|
Packed morton word(s). |
Source code in mortie/tools.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | |
infer_order_from_morton(morton)
Infer the single HEALPix order of packed morton word(s).
Decodes through the packed-u64 kernel (issue #48): the order is carried in
the word's suffix, not in any decimal-digit count. The return is one
scalar order, so array input must be uniform-order; mixed-order input
raises, naming the distinct orders (issue #116 — previously the first
element's order was returned silently). For per-element orders of a mixed
array use :func:orders_of.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton
|
int or array - like
|
Packed morton word(s), all at one order. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The HEALPix order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the words are at mixed orders. |
Source code in mortie/tools.py
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | |
orders_of(morton)
Per-element HEALPix order of packed morton words.
Vectorized numpy decode of the 6-bit suffix (bits 5-0) per the spec page's
suffix table (docs/specification.md §1):
- suffix
0..=27— variable-length area element; the order is the suffix value (0= base-cell-only). - suffix
28..=47— order-28/29 area cells in parent-first preordersuffix = 28 + t28*5 + (t29 present ? t29 + 1 : 0): eacht28owns a 5-block (the order-28 parent, then its four order-29 children), so(suffix - 28) % 5 == 0is order 28 and everything else is order 29. - suffix
48..=63— order-29 point (max-encoded, no area claim — spec §4); points are order 29 by definition.
Pure bit arithmetic — words are not validated (the empty sentinel 0
decodes as order 0; use :func:validate_morton to reject malformed
words). This is the per-element, mixed-order-native counterpart of
:func:infer_order_from_morton.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton
|
int or array - like
|
Packed morton word(s) ( |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Source code in mortie/tools.py
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 | |
orders_of_uniq(uniq)
Per-element HEALPix order decoded from UNIQ cell numbers.
UNIQ is self-describing: uniq = 4 * 4**order + nested with
0 <= nested < 12 * 4**order, so order-k values occupy exactly
[4**(k+1), 4**(k+2)) and consecutive orders tile that line without
gaps. The order is therefore a pure function of the value — no
caller-supplied order is needed and mixed-resolution input decodes element
by element (issue #136).
Implemented as an exact integer bucket search rather than the
log2(uniq / 4) // 2 form this module used previously: the float64
round-trip is not exact above ~2**53, so e.g. 4**30 - 1 (the last
order-28 value) rounds up to 4**30 and mis-decodes as order 29.
The UNIQ counterpart of :func:orders_of, and mirrors its contract:
per-element, mixed-order-native, uint8 out, scalar in -> length-1
ndarray. One deliberate difference: :func:orders_of is pure bit
arithmetic and never validates, because every 6-bit morton suffix decodes
to some order. UNIQ has no such total decode -- a value outside
[4, 4**31) names no cell at any order -- so this raises instead of
inventing an answer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uniq
|
int or array - like
|
UNIQ encoded cell number(s). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If any value lies outside the UNIQ range for orders 0- |
Source code in mortie/tools.py
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 | |
is_point(morton)
Per-element point-kind predicate for packed morton words.
Kind is carried by the encoding itself (spec §4): suffix 0..=47
decodes as an area word, suffix 48..=63 as an order-29 point
(a location with no area claim — docs/specification.md §1 suffix
table). Pure bit arithmetic; words are not validated (see
:func:validate_morton).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton
|
int or array - like
|
Packed morton word(s) ( |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Source code in mortie/tools.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 | |
validate_morton(morton, order=None)
Validate that a packed morton word is well-formed.
The kernel decode rejects the empty sentinel (0) and any word with an
invalid base-cell prefix; this also checks the decoded order matches
order when one is supplied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton
|
int
|
Packed morton word to validate. |
required |
order
|
int
|
Expected HEALPix order. If None, no order check is made. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the word is a valid morton word. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the word does not decode or its order disagrees with |
Source code in mortie/tools.py
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 | |
clip2order(clip_order, midx)
Coarsen packed morton words to a lower resolution.
Degrades each packed word to clip_order by coarsening it through the
kernel (the inverse of refining): the base cell and the first clip_order
tuples are kept, finer detail is dropped, and the suffix is rewritten. Words
already at or below clip_order are returned unchanged.
The print_factor flag was removed for the 1.x freeze (issue #68). It
returned 18 - clip_order, a level count anchored to the retired
decimal encoding's order-18 ceiling, so it went negative for the
order-19..29 words this package now encodes. There is no replacement: the
levels a word actually drops is order - clip_order for its own decoded
order, which :func:orders_of gives directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clip_order
|
int
|
HEALPix order to degrade to. |
required |
midx
|
array-like of int
|
Packed morton words (see :func: |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Coarsened packed words, one per input word. |
Source code in mortie/tools.py
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 | |
generate_morton_children(parent_morton, target_order)
Generate all child morton indices at a target order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent_morton
|
int
|
Parent packed morton word. |
required |
target_order
|
int
|
Target order for children (must be >= parent order). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
children |
ndarray
|
Array of child packed morton words at target_order. If target_order equals parent_order, returns array with parent_morton. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
Children are generated in HEALPix NESTED space — descending level_diff
orders multiplies the cell count by 4**level_diff — then packed back to
morton words via the kernel. If already at target_order, returns the parent
itself.
Source code in mortie/tools.py
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 | |
morton_buffer(morton_indices, k=1)
Compute the k-cell border around a set of morton indices.
Returns only cells NOT in the input set (the expansion ring).
User can union: np.union1d(morton_indices, border)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton_indices
|
array - like
|
Morton indices, all at the same order. |
required |
k
|
int
|
Border width in cells (default 1, 8-connected neighbors). k=1 gives the immediate ring, k=2 gives a 2-cell border, etc. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
border |
ndarray
|
Sorted array of morton indices for the border cells. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If indices have mixed orders or k is out of range. |
Source code in mortie/tools.py
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 | |
morton_buffer_meters(morton_indices, width_m)
Approximate meter-width buffer around a set of morton cells.
This is a convenience wrapper around :func:morton_buffer that picks
k from the cells' HEALPix order so the resulting ring is roughly
width_m meters wide. The input cells are assumed to all be at the same
order.
.. warning::
This is an approximate buffer. The achieved width is rounded
UP to the nearest whole HEALPix cell width — so the result always
covers at least width_m meters, but may cover up to one cell
width more. For order 18 cells (~30 m) the granularity is fine; at
coarser orders it can be substantial. If you need a precise buffer,
pick an order whose cell width is small relative to width_m and
convert your input cells to that order first.
The cell width used for the calculation is the HEALPix angular
resolution sqrt(pi/3) / nside converted to meters via the Earth's
mean radius (6,371,008.77 m).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morton_indices
|
array - like
|
Morton indices, all at the same HEALPix order. |
required |
width_m
|
float
|
Desired buffer width in meters (must be > 0). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
border |
ndarray
|
Sorted array of morton indices for the border cells (NOT including
the input cells). Union with the input if you want the filled ring:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import mortie, numpy as np
>>> cells = mortie.linestring_coverage([10.0, 20.0], [30.0, 40.0], order=10)
>>> border = mortie.morton_buffer_meters(cells, width_m=5000.0)
>>> expanded = np.union1d(cells, border)
Source code in mortie/tools.py
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 | |
order2res(order)
Approximate cell scale (km) at a HEALPix tessellation order.
The exact RMS cell spacing on the mean-radius HEALPix sphere: every
order-k cell has identical area 4*pi*R**2 / (12 * 4**order) (HEALPix is
equal-area), and the cell scale is the square root of that area. Derived
from :data:EARTH_RADIUS_KM so code and the spec page (§3) share one Earth
model (issue #119).
order may be a scalar (returns a float) or an array of orders such
as :func:orders_of yields (returns an ndarray).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
int or array - like
|
HEALPix tessellation order(s). |
required |
Returns:
| Type | Description |
|---|---|
float or ndarray
|
Approximate cell scale in kilometres (scalar in -> |
See Also
res2display : the same ladder as display-ready records, order by order.
Source code in mortie/tools.py
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 | |
res2display(max_order=MAX_ORDER)
Resolution ladder for tessellation orders 0 through max_order.
Returns one record per order rather than printing (issue #68): each
resolution is expressed in the largest sensible unit -- km at coarse
orders, m once it drops below 1 km, cm once it drops below 1 m --
rounded to three decimals within that bracket, so fine orders read
naturally (order 12 -> 1.592 km, order 13 -> 795.852 m) rather
than as tiny km fractions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_order
|
int
|
Highest order to include, inclusive. Must lie in |
MAX_ORDER
|
Returns:
| Type | Description |
|---|---|
list of ResolutionLevel
|
One named tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
See Also
order2res : the raw kilometres for a single order.
Examples:
>>> from mortie import res2display
>>> levels = res2display(max_order=3)
>>> levels[0].order, levels[0].unit
(0, 'km')
>>> for lvl in res2display(max_order=2):
... print(f"{lvl.value} {lvl.unit} at tessellation order {lvl.order}")
...
Source code in mortie/tools.py
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 | |
!!! note "Not yet documented here"
The UNIQ helpers (`geo2uniq`, `norm2uniq`, `uniq2geo`, `unique2parent`) are
omitted while their signatures are in flux — see
[issue #136](https://github.com/espg/mortie/issues/136). `heal_norm` is
omitted because it is being removed under
[PR #130](https://github.com/espg/mortie/pull/130).