Skip to content

Instantly share code, notes, and snippets.

@willfurnass
Created March 1, 2016 18:36
Show Gist options
  • Save willfurnass/a585dec13e366dea6c7b to your computer and use it in GitHub Desktop.
Save willfurnass/a585dec13e366dea6c7b to your computer and use it in GitHub Desktop.
Convert alphanumeric British National Grid references to/from easting northing integer pairs
import numpy as np
myriad_codes = np.array((
None, None, None, None, "HP", None, None,
None, None, None, "HT", "HU", None, None,
None, "HW", "HX", "HY", "HZ", None, None,
"NA", "NB", "NC", "ND", None, None, None,
"NF", "NG", "NH", "NJ", "NK", None, None,
"NL", "NM", "NN", "NO", None, None, None,
None, "NR", "NS", "NT", "NU", None, None,
None, "NW", "NX", "NY", "NZ", "OV", None,
None, None, "SC", "SD", "SE", "TA", None,
None, None, "SH", "SJ", "SK", "TF", "TG",
None, "SM", "SN", "SO", "SP", "TL", "TM",
None, "SR", "SS", "ST", "SU", "TQ", "TR",
"SV", "SW", "SX", "SY", "SZ", "TV", None))
myriad_codes = np.flipud(myriad_codes.reshape(13, 7))
def myriad_alpha_code_from_x_y(x, y):
"""Given a British National Grid 2-digit myriad x and y e.g. (4,5)
returns the myriad code e.g. 'SE'"""
try:
return myriad_codes[y][x]
except IndexError:
raise IndexError("Invalid British National Grid myriad (single " +
"digit) eastings and northings.")
def myriad_x_y_from_alpha_code(code):
"""Given a British National Grid myriad code e.g. 'SE' returns the
2-digit myriad x and y e.g. (4,5)"""
try:
x = np.where(myriad_codes == code)[1][0]
y = np.where(myriad_codes == code)[0][0]
except IndexError:
raise IndexError("Invalid British National Grid myriad code.")
return (x, y)
def grid_ref_str_to_easting_northing(grid_ref_str):
"""Converts British National Grid ref in form 'SE 12345 12345' to 12-digit
(easting, northing) tuple."""
code, easting, northing = grid_ref_str.split(' ')
easting = myriad_x_y_from_alpha_code(code)[0] * 100000 + float(easting)
northing = myriad_x_y_from_alpha_code(code)[1] * 100000 + float(northing)
return (easting, northing)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment