|
| 1 | +"""Check every mapping locality's lat,lon against GeoNames: a populated place with the locality's name (or one of |
| 2 | +locality_aka) must exist in that country near the coordinates. |
| 3 | +
|
| 4 | + python -m tools.coords_check [OUT.csv] # default _output/checks/coords_check.csv |
| 5 | +
|
| 6 | +GeoNames files in ~/geonames (GEONAMES_DIR to change): countryInfo.txt and admin1CodesASCII.txt, and populated.txt |
| 7 | +(the populated places, feature class P, of allCountries.txt: 5.2M) or else cities500.txt (places of 500+ people): |
| 8 | + cd ~/geonames && curl -sSfLO https://download.geonames.org/export/dump/allCountries.zip && |
| 9 | + unzip -p allCountries.zip allCountries.txt | awk -F'\\t' '$7=="P"' > populated.txt && rm allCountries.zip |
| 10 | +Takes about 2 min and 2 GB of memory with populated.txt. |
| 11 | +
|
| 12 | +Issue per row (most serious first): |
| 13 | + other_country the coordinates are nearer to places of another country and >5 km from any place of its own country |
| 14 | + wrong_state the place of this name in the row's state is far away, and the coordinates lie in another state |
| 15 | + far places with this name exist (in the row's state, when it has one), but the nearest is farther than |
| 16 | + the radius (10 km, 20 km for 100k+ people, 35 km for 1M+) |
| 17 | + no_name no place of this name in the country in GeoNames (very small place, spelling or a typo), or, for a |
| 18 | + row with a state, only in other states: it is never matched to a place in another state |
| 19 | + ok a place with this name within the radius |
| 20 | +""" |
| 21 | +import csv |
| 22 | +import os |
| 23 | +import re |
| 24 | +import sys |
| 25 | +import unicodedata |
| 26 | +from collections import defaultdict |
| 27 | + |
| 28 | +import numpy as np |
| 29 | +from scipy.spatial import cKDTree |
| 30 | + |
| 31 | +GEONAMES = os.environ.get('GEONAMES_DIR', os.path.expanduser('~/geonames')) |
| 32 | +R_EARTH = 6371.0 |
| 33 | +ISSUES = ['other_country', 'wrong_state', 'far', 'no_name', 'ok'] |
| 34 | +CA_PROV = {'AB': 'Alberta', 'BC': 'British Columbia', 'MB': 'Manitoba', 'NB': 'New Brunswick', |
| 35 | + 'NL': 'Newfoundland and Labrador', 'NS': 'Nova Scotia', 'NT': 'Northwest Territories', 'NU': 'Nunavut', |
| 36 | + 'ON': 'Ontario', 'PE': 'Prince Edward Island', 'QC': 'Quebec', 'SK': 'Saskatchewan', 'YT': 'Yukon'} |
| 37 | +ABBREV = {'st': 'saint', 'ste': 'sainte', 'mt': 'mount', 'ft': 'fort'} |
| 38 | +SUFFIX = r' (oblast|krai|republic|province|prefecture|state|region|county|division|district|governorate)$' |
| 39 | + |
| 40 | + |
| 41 | +def norm(s): |
| 42 | + """Name for matching: no accents, case or punctuation.""" |
| 43 | + s = unicodedata.normalize('NFKD', s) |
| 44 | + s = ''.join(c for c in s if not unicodedata.combining(c)).casefold() |
| 45 | + for a, b in (('ß', 'ss'), ('ı', 'i'), ('ø', 'o'), ('ł', 'l'), ('đ', 'd'), ('æ', 'ae')): |
| 46 | + s = s.replace(a, b) |
| 47 | + s = re.sub(r"[\-'’`.,()/]", ' ', s) |
| 48 | + s = re.sub(r'^(city of|municipality of|town of) ', '', s.strip()) |
| 49 | + # abbreviated words as GeoNames writes them out (St Paul / Saint Paul; Pavlo, 2026-10-25); both sides go through |
| 50 | + # this, so St. Gallen still meets GeoNames' alternate name St. Gallen of Sankt Gallen |
| 51 | + s = re.sub(r'\b(st|ste|mt|ft)\b', lambda m: ABBREV[m.group(1)], s) |
| 52 | + return re.sub(r'\s+', ' ', s).strip() |
| 53 | + |
| 54 | + |
| 55 | +def fits(state, cc, adm): |
| 56 | + """Whether the mapping's state can be this GeoNames admin1 name (None when either is missing): the same name, a |
| 57 | + Canadian province code, or an abbreviation whose letters appear in order in the name from its first letter |
| 58 | + (QLD, CHIH, NSW; the US codes are GeoNames' own).""" |
| 59 | + if not state or not adm: |
| 60 | + return None |
| 61 | + if cc == 'CA' and state.upper() in CA_PROV: |
| 62 | + return norm(CA_PROV[state.upper()]) == norm(adm) |
| 63 | + st = re.sub(SUFFIX, '', norm(state)).replace('republic of ', '') |
| 64 | + an = re.sub(SUFFIX, '', norm(adm)).replace('republic of ', '') |
| 65 | + if st == an or (len(st) > 3 and (st in an or an in st)): |
| 66 | + return True |
| 67 | + if state.isupper() and 2 <= len(state) <= 5: |
| 68 | + letters = an.replace(' ', '') |
| 69 | + if not letters.startswith(st[0]): |
| 70 | + return False |
| 71 | + pos = 0 |
| 72 | + for ch in st: |
| 73 | + pos = letters.find(ch, pos) |
| 74 | + if pos < 0: |
| 75 | + return False |
| 76 | + pos += 1 |
| 77 | + return True |
| 78 | + return False |
| 79 | + |
| 80 | + |
| 81 | +def radius(pop): |
| 82 | + return 35.0 if pop >= 1_000_000 else 20.0 if pop >= 100_000 else 10.0 |
| 83 | + |
| 84 | + |
| 85 | +def _xyz(lat, lon): |
| 86 | + lat, lon = np.radians(lat), np.radians(lon) |
| 87 | + return np.stack([np.cos(lat) * np.cos(lon), np.cos(lat) * np.sin(lon), np.sin(lat)], -1) |
| 88 | + |
| 89 | + |
| 90 | +def _km(chord): |
| 91 | + return 2 * R_EARTH * np.arcsin(np.clip(chord / 2, 0, 1)) |
| 92 | + |
| 93 | + |
| 94 | +def aka(cell): |
| 95 | + return [a.strip() for a in (cell or '').strip('[]').split(',') if a.strip()] |
| 96 | + |
| 97 | + |
| 98 | +def check(rows, gdir=GEONAMES): |
| 99 | + """One result dict per mapping row (dicts of mapping.csv), with 'issue' and the GeoNames place it was matched to |
| 100 | + (match_*), up to 3 other places of the name (alternatives: [name, admin1, lat, lon, km]) and the nearest place.""" |
| 101 | + iso3_to2 = {} |
| 102 | + for line in open(os.path.join(gdir, 'countryInfo.txt'), encoding='utf-8'): |
| 103 | + if line.startswith('#') or not line.strip(): |
| 104 | + continue |
| 105 | + p = line.rstrip('\n').split('\t') |
| 106 | + iso3_to2[p[1]] = p[0] |
| 107 | + iso3_to2.setdefault('XKX', 'XK') # Kosovo |
| 108 | + admin1 = {} |
| 109 | + regions = defaultdict(list) # country -> its first-level regions |
| 110 | + for line in open(os.path.join(gdir, 'admin1CodesASCII.txt'), encoding='utf-8'): |
| 111 | + p = line.rstrip('\n').split('\t') |
| 112 | + admin1[p[0]] = p[1] |
| 113 | + regions[p[0].split('.')[0]].append(p[1]) |
| 114 | + wanted = {norm(n) for r in rows for n in [r['locality'], *aka(r['locality_aka'])] if n.strip()} |
| 115 | + countries = {iso3_to2.get(r['iso3'], '') for r in rows} |
| 116 | + names = defaultdict(list) # (country, normalised name) -> places, only for names the mapping uses |
| 117 | + plat, plon, pcc, pname, ppop, padm = [], [], [], [], [], [] |
| 118 | + src = 'populated.txt' if os.path.exists(os.path.join(gdir, 'populated.txt')) else 'cities500.txt' |
| 119 | + for line in open(os.path.join(gdir, src), encoding='utf-8'): |
| 120 | + p = line.rstrip('\n').split('\t') |
| 121 | + if p[8] not in countries: |
| 122 | + continue |
| 123 | + i = len(plat) |
| 124 | + plat.append(float(p[4])) |
| 125 | + plon.append(float(p[5])) |
| 126 | + pcc.append(p[8]) |
| 127 | + pname.append(p[1]) |
| 128 | + ppop.append(int(p[14] or 0)) |
| 129 | + padm.append(admin1.get(f'{p[8]}.{p[10]}', p[10])) |
| 130 | + for n in {p[1], p[2], *p[3].split(',')}: |
| 131 | + k = norm(n) if n else '' |
| 132 | + if k in wanted: |
| 133 | + names[(p[8], k)].append(i) |
| 134 | + plat, plon, ppop = np.array(plat), np.array(plon), np.array(ppop) |
| 135 | + pts = _xyz(plat, plon) |
| 136 | + tree_all = cKDTree(pts) |
| 137 | + by_cc = defaultdict(list) |
| 138 | + for i, c in enumerate(pcc): |
| 139 | + by_cc[c].append(i) |
| 140 | + trees = {c: (cKDTree(pts[ix]), np.array(ix)) for c, ix in by_cc.items()} |
| 141 | + out = [] |
| 142 | + for r in rows: |
| 143 | + lat, lon = float(r['lat']), float(r['lon']) |
| 144 | + cc, state = iso3_to2.get(r['iso3'], ''), r['state'].strip() |
| 145 | + q = _xyz(np.array([lat]), np.array([lon]))[0] |
| 146 | + res = dict(id=r['id'], locality=r['locality'], locality_aka=r['locality_aka'], state=state, |
| 147 | + country=r['country'], iso3=r['iso3'], population=r['population_locality'], lat=lat, lon=lon) |
| 148 | + d_any, i_any = tree_all.query(q) |
| 149 | + res.update(nearest_place=pname[i_any], nearest_country=pcc[i_any], nearest_km=round(float(_km(d_any)), 1)) |
| 150 | + own = trees.get(cc) |
| 151 | + i_own, d_own = None, float('inf') |
| 152 | + if own: |
| 153 | + d, j = own[0].query(q) |
| 154 | + i_own, d_own = int(own[1][j]), float(_km(d)) |
| 155 | + res.update(coord_admin1=padm[i_own], nearest_own=pname[i_own], nearest_own_km=round(d_own, 1)) |
| 156 | + cand = sorted({i for n in [r['locality'], *aka(r['locality_aka'])] for i in names.get((cc, norm(n)), [])}) |
| 157 | + issue = 'no_name' |
| 158 | + in_state = [] |
| 159 | + if cand: |
| 160 | + in_state = [i for i in cand if fits(state, cc, padm[i])] |
| 161 | + pool = np.array(in_state or cand) |
| 162 | + d = _km(np.linalg.norm(pts[pool] - q, axis=1)) |
| 163 | + order = np.argsort(d) |
| 164 | + b = int(pool[order[0]]) |
| 165 | + res.update(match=pname[b], match_admin1=padm[b], match_pop=int(ppop[b]), match_lat=float(plat[b]), |
| 166 | + match_lon=float(plon[b]), match_km=round(float(d[order[0]]), 1), same_name_places=len(cand), |
| 167 | + alternatives=[[pname[int(pool[k])], padm[int(pool[k])], float(plat[int(pool[k])]), |
| 168 | + float(plon[int(pool[k])]), round(float(d[k]), 1)] for k in order[1:4]]) |
| 169 | + pop = max(int(ppop[b]), int(float(r['population_locality'] or 0))) |
| 170 | + issue = 'ok' if d[order[0]] <= radius(pop) else 'far' |
| 171 | + if issue == 'far' and state and i_own is not None and padm[i_own] != padm[b]: |
| 172 | + fm, fc = fits(state, cc, padm[b]), fits(state, cc, padm[i_own]) |
| 173 | + if fm and not fc: |
| 174 | + issue = 'wrong_state' # the state is the named place's; the coordinates lie in another one |
| 175 | + elif fc and not fm: |
| 176 | + issue = 'no_name' # the only same-name places are in other states: this one is not in GeoNames |
| 177 | + if issue in ('far', 'no_name') and cand and state and not in_state and \ |
| 178 | + any(fits(state, cc, a) for a in regions.get(cc, ())): |
| 179 | + # the row's state is a real region of the country, and the places of this name are all in other states and |
| 180 | + # far away (St Paul, OR is not the one in Minnesota): no match, so no move to offer (Pavlo, 2026-10-25) |
| 181 | + for k in ('match', 'match_admin1', 'match_pop', 'match_lat', 'match_lon', 'match_km'): |
| 182 | + res.pop(k, None) |
| 183 | + res.update(alternatives=[], other_states=sorted({padm[i] for i in cand})[:5]) |
| 184 | + issue = 'no_name' |
| 185 | + if pcc[i_any] != cc and d_own > 5: |
| 186 | + issue = 'other_country' |
| 187 | + res['issue'] = issue |
| 188 | + out.append(res) |
| 189 | + return out |
| 190 | + |
| 191 | + |
| 192 | +KEYS = ['issue', 'id', 'locality', 'state', 'country', 'iso3', 'population', 'lat', 'lon', 'match', 'match_admin1', |
| 193 | + 'match_pop', 'match_lat', 'match_lon', 'match_km', 'coord_admin1', 'same_name_places', 'nearest_own', |
| 194 | + 'nearest_own_km', 'nearest_place', 'nearest_country', 'nearest_km'] |
| 195 | + |
| 196 | + |
| 197 | +def _check(): |
| 198 | + assert fits('QLD', 'AU', 'Queensland') and fits('CHIH', 'MX', 'Chihuahua') and fits('NSW', 'AU', 'New South Wales') |
| 199 | + assert fits('YT', 'CA', 'Yukon') and not fits('BC', 'CA', 'Yukon') |
| 200 | + assert fits('OR', 'US', 'Oregon') and not fits('OR', 'US', 'Massachusetts') |
| 201 | + assert fits('Lviv oblast', 'UA', 'Lviv') and fits('Anambra', 'NG', 'Anambra') |
| 202 | + assert not fits('Anambra', 'NG', 'Enugu State') |
| 203 | + assert fits('', 'US', 'Texas') is None |
| 204 | + assert fits('OR', 'US', 'Minnesota') is False # St Paul, OR: the Minnesota one is never its match |
| 205 | + assert norm('Saarbrücken') == norm('Saarbrucken') == 'saarbrucken' and norm('Ivano-Frankivsk') == 'ivano frankivsk' |
| 206 | + assert norm('St Paul') == norm('St. Paul') == norm('Saint Paul') and norm('Ste-Agathe') == norm('Sainte Agathe') |
| 207 | + assert norm('Mt Vernon') == norm('Mount Vernon') and norm('Ft. Worth') == norm('Fort Worth') |
| 208 | + assert norm('Stuttgart') == 'stuttgart' and norm('Westmount') == 'westmount' # only whole words |
| 209 | + |
| 210 | + |
| 211 | +if __name__ == '__main__': |
| 212 | + _check() |
| 213 | + os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # top folder: mapping.csv |
| 214 | + path = sys.argv[1] if len(sys.argv) > 1 else '_output/checks/coords_check.csv' |
| 215 | + with open('mapping.csv', encoding='utf-8') as f: |
| 216 | + result = check(list(csv.DictReader(f))) |
| 217 | + result.sort(key=lambda x: (ISSUES.index(x['issue']), -float(x.get('match_km') or 0))) |
| 218 | + os.makedirs(os.path.dirname(path), exist_ok=True) |
| 219 | + with open(path, 'w', newline='', encoding='utf-8') as f: |
| 220 | + w = csv.DictWriter(f, KEYS, extrasaction='ignore') |
| 221 | + w.writeheader() |
| 222 | + w.writerows(result) |
| 223 | + counts = {k: sum(x['issue'] == k for x in result) for k in ISSUES} |
| 224 | + print(counts, '->', path) |
0 commit comments