"""Build the GeoSQL-Traps database and questions. Reference answers come from pyproj.Geod (WGS84), never from SQL. Every site is fictional; only the regional coordinates are real. Output: data/geosql.duckdb, data/questions.jsonl, data/schema.txt. Usage: python code/build.py """ from __future__ import annotations import json import math import random from pathlib import Path import duckdb from pyproj import Geod, Transformer ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "data" SEED = 20261107 G = Geod(ellps="WGS84") TO_3857 = Transformer.from_crs(4326, 3857, always_xy=True) TO_UTM = Transformer.from_crs(4326, 32632, always_xy=True) CENTRES = {"TRO": (69.65, 18.96), "REK": (64.15, -21.94), "OSL": (59.91, 10.75), "HEL": (60.17, 24.94), "ANC": (61.22, -149.90), "IST": (41.01, 28.98), "NBO": (-1.29, 36.82), "UIO": (-0.18, -78.47), "USH": (-54.80, -68.30), "WLG": (-41.29, 174.78)} ISLANDS = [("Suva", -18.14, 178.44), ("Taveuni", -16.80, -179.97), ("Lautoka", -17.61, 177.45), ("Apia", -13.83, -171.76), ("Attu", 52.90, 173.18), ("Adak", 51.88, -176.65), ("Anadyr", 64.73, 177.51), ("Provideniya", 64.42, -173.23), ("Nukualofa", -21.14, -175.20), ("Funafuti", -8.52, 179.20), ("Chatham", -43.95, -176.56), ("Whangarei", -35.73, 174.32)] CTRL_N = RAD_N = 12 def km(a, b): return G.inv(a[1], a[0], b[1], b[0])[2] / 1000 def wkt_pt(lon, lat): return f"POINT ({lon:.7f} {lat:.7f})" def polygon(rnd, lat, lon, ha): side = math.sqrt(ha * 10000) dlat, dlon = side / 111320, side / (111320 * math.cos(math.radians(lat))) pts = [(lon, lat), (lon + dlon * rnd.uniform(.9, 1.1), lat), (lon + dlon * rnd.uniform(.9, 1.1), lat + dlat * rnd.uniform(.9, 1.1)), (lon + dlon * rnd.uniform(.1, .4), lat + dlat * rnd.uniform(1.0, 1.25)), (lon, lat + dlat * rnd.uniform(.8, 1.0))] return pts + [pts[0]] def main() -> None: rnd = random.Random(SEED) DATA.mkdir(exist_ok=True) db = DATA / "geosql.duckdb" db.unlink(missing_ok=True) con = duckdb.connect(str(db)) con.execute("INSTALL spatial; LOAD spatial;") sites, stations, parcels, pipes, assets = [], [], [], [], [] for code, (lat, lon) in CENTRES.items(): for i in range(14): sites.append((f"S-{code}-{i:02d}", lat + rnd.uniform(-.6, .6), lon + rnd.uniform(-1.2, 1.2))) stations.append((f"T-{code}-{i:02d}", lat + rnd.uniform(-.6, .6), lon + rnd.uniform(-1.2, 1.2))) for i in range(4): la, lo = lat + rnd.uniform(-.4, .4), lon + rnd.uniform(-.8, .8) parcels.append((f"P-{code}-{i}", polygon(rnd, la, lo, rnd.uniform(40, 600)))) line, la2, lo2 = [], lat + rnd.uniform(-.3, .3), lon + rnd.uniform(-.6, .6) for _ in range(rnd.randint(5, 9)): line.append((lo2, la2)) la2 += rnd.uniform(-.04, .05) lo2 += rnd.uniform(.02, .12) pipes.append((f"L-{code}-{i}", line)) for i in range(40): la, lo = 59.91 + rnd.uniform(-.5, .5), 10.75 + rnd.uniform(-1, 1) x, y = TO_UTM.transform(lo, la) assets.append((f"A-{i:02d}", la, lo, x, y)) con.execute("CREATE TABLE sites(name VARCHAR, geom GEOMETRY)") con.execute("CREATE TABLE sites_webmerc(name VARCHAR, geom GEOMETRY)") con.execute("CREATE TABLE stations(name VARCHAR, latitude DOUBLE, longitude DOUBLE)") con.execute("CREATE TABLE parcels(name VARCHAR, geom GEOMETRY)") con.execute("CREATE TABLE parcels_webmerc(name VARCHAR, geom GEOMETRY)") con.execute("CREATE TABLE pipelines(name VARCHAR, geom GEOMETRY)") con.execute("CREATE TABLE assets_utm32n(name VARCHAR, geom GEOMETRY)") con.execute("CREATE TABLE islands(name VARCHAR, latitude DOUBLE, longitude DOUBLE)") for n, la, lo in sites: x, y = TO_3857.transform(lo, la) con.execute("INSERT INTO sites VALUES (?, ST_GeomFromText(?))", [n, wkt_pt(lo, la)]) con.execute("INSERT INTO sites_webmerc VALUES (?, ST_GeomFromText(?))", [n, f"POINT ({x:.3f} {y:.3f})"]) con.executemany("INSERT INTO stations VALUES (?,?,?)", stations) con.executemany("INSERT INTO islands VALUES (?,?,?)", ISLANDS) for n, pts in parcels: con.execute("INSERT INTO parcels VALUES (?, ST_GeomFromText(?))", [n, "POLYGON ((" + ", ".join(f"{a:.7f} {b:.7f}" for a, b in pts) + "))"]) con.execute("INSERT INTO parcels_webmerc VALUES (?, ST_GeomFromText(?))", [n, "POLYGON ((" + ", ".join("{:.3f} {:.3f}".format(*TO_3857.transform(a, b)) for a, b in pts) + "))"]) for n, l in pipes: con.execute("INSERT INTO pipelines VALUES (?, ST_GeomFromText(?))", [n, "LINESTRING (" + ", ".join(f"{a:.7f} {b:.7f}" for a, b in l) + ")"]) for n, _, _, x, y in assets: con.execute("INSERT INTO assets_utm32n VALUES (?, ST_GeomFromText(?))", [n, f"POINT ({x:.3f} {y:.3f})"]) con.close() q = [] def add(family, text, answer, kind, gold, naive=None, tol=None): q.append({"id": f"{family}-{sum(1 for x in q if x['family'] == family):02d}", "family": family, "question": text, "answer": answer, "kind": kind, "tolerance": tol, "gold_sql": gold, "naive_sql": naive}) flip = "{}" high = [s for s in sites if abs(s[1]) > 55] pick = rnd.sample(high, len(high)) # radius count on degree geometry for s in pick: if sum(1 for x in q if x["family"] == "radius_degrees") >= RAD_N: break r = rnd.choice([20, 30, 40, 50]) ref = sum(1 for t in sites if t[0] != s[0] and km(s[1:], t[1:]) <= r) deg = r / 111.32 naive = sum(1 for t in sites if t[0] != s[0] and math.hypot(s[2] - t[2], s[1] - t[1]) <= deg) if ref == naive or ref == 0: continue add("radius_degrees", f"How many other sites are within {r} km of site {s[0]}?", ref, "int", f"SELECT count(*) FROM sites a, sites b WHERE a.name='{s[0]}' AND b.name<>a.name AND ST_Distance_Spheroid({flip.format('a.geom')},{flip.format('b.geom')})<={r*1000}", f"SELECT count(*) FROM sites a, sites b WHERE a.name='{s[0]}' AND b.name<>a.name AND ST_Distance(a.geom,b.geom)<={deg}") # nearest neighbour where planar degrees pick the wrong site for s in pick: if sum(1 for x in q if x["family"] == "nearest_degrees") >= RAD_N: break o = [t for t in sites if t[0] != s[0]] ref = min(o, key=lambda t: km(s[1:], t[1:]))[0] naive = min(o, key=lambda t: math.hypot(s[2] - t[2], s[1] - t[1]))[0] if ref == naive: continue add("nearest_degrees", f"Which other site is nearest to site {s[0]}? Return its name.", ref, "text", f"SELECT b.name FROM sites a, sites b WHERE a.name='{s[0]}' AND b.name<>a.name ORDER BY ST_Distance_Spheroid({flip.format('a.geom')},{flip.format('b.geom')}) LIMIT 1", f"SELECT b.name FROM sites a, sites b WHERE a.name='{s[0]}' AND b.name<>a.name ORDER BY ST_Distance(a.geom,b.geom) LIMIT 1") # distance in web mercator hs = [s for s in pick if abs(s[1]) > 55] for i in range(RAD_N): a = hs[i] b = rnd.choice([t for t in hs if t[0] != a[0] and a[0][:5] == t[0][:5]]) back = "ST_Transform({},'EPSG:3857','EPSG:4326',true)" add("distance_webmerc", f"What is the true ground distance in kilometres between site {a[0]} and site {b[0]} in table sites_webmerc?", km(a[1:], b[1:]), "num", f"SELECT ST_Distance_Spheroid({flip.format(back.format('a.geom'))},{flip.format(back.format('b.geom'))})/1000 FROM sites_webmerc a, sites_webmerc b WHERE a.name='{a[0]}' AND b.name='{b[0]}'", f"SELECT ST_Distance(a.geom,b.geom)/1000 FROM sites_webmerc a, sites_webmerc b WHERE a.name='{a[0]}' AND b.name='{b[0]}'", 0.01) # axis order on plain columns for i in range(RAD_N): a = rnd.choice(stations) b = rnd.choice([t for t in stations if t[0][:5] == a[0][:5] and t[0] != a[0]]) add("axis_order", f"What is the distance in kilometres between stations {a[0]} and {b[0]}?", km(a[1:], b[1:]), "num", f"SELECT ST_Distance_Spheroid(ST_Point(a.longitude,a.latitude),ST_Point(b.longitude,b.latitude))/1000 FROM stations a, stations b WHERE a.name='{a[0]}' AND b.name='{b[0]}'", f"SELECT ST_Distance_Spheroid(ST_Point(a.latitude,a.longitude),ST_Point(b.latitude,b.longitude))/1000 FROM stations a, stations b WHERE a.name='{a[0]}' AND b.name='{b[0]}'", 0.01) # area in degrees and web mercator for i, (n, pts) in enumerate(rnd.sample(parcels, RAD_N)): ref = abs(G.polygon_area_perimeter([p[0] for p in pts[:-1]], [p[1] for p in pts[:-1]])[0]) / 10000 add("area_degrees", f"What is the area of parcel {n} in hectares?", ref, "num", f"SELECT ST_Area_Spheroid({flip.format('geom')})/10000 FROM parcels WHERE name='{n}'", f"SELECT ST_Area(geom)/10000 FROM parcels WHERE name='{n}'", 0.02) hp = [p for p in parcels if abs(p[1][0][1]) > 55] for n, pts in rnd.sample(hp, min(RAD_N, len(hp))): ref = abs(G.polygon_area_perimeter([p[0] for p in pts[:-1]], [p[1] for p in pts[:-1]])[0]) / 10000 add("area_webmerc", f"What is the true ground area of parcel {n} in table parcels_webmerc, in hectares?", ref, "num", f"SELECT ST_Area_Spheroid(ST_Transform(geom,'EPSG:3857','EPSG:4326',true))/10000 FROM parcels_webmerc WHERE name='{n}'", f"SELECT ST_Area(geom)/10000 FROM parcels_webmerc WHERE name='{n}'", 0.02) # line length for n, l in rnd.sample(pipes, RAD_N): add("length_degrees", f"What is the length of pipeline {n} in kilometres?", G.line_length([p[0] for p in l], [p[1] for p in l]) / 1000, "num", f"SELECT ST_Length_Spheroid({flip.format('geom')})/1000 FROM pipelines WHERE name='{n}'", f"SELECT ST_Length(geom)/1000 FROM pipelines WHERE name='{n}'", 0.01) # CRS mismatch between tables oslo = [s for s in sites if s[0].startswith("S-OSL")] for s in rnd.sample(oslo, len(oslo)): if sum(1 for x in q if x["family"] == "crs_join") >= RAD_N: break r = rnd.choice([25, 35, 45, 60]) ref = sum(1 for a in assets if km(s[1:], (a[1], a[2])) <= r) if not ref: continue add("crs_join", f"How many assets are within {r} km of site {s[0]}?", ref, "int", f"SELECT count(*) FROM sites s, assets_utm32n a WHERE s.name='{s[0]}' AND ST_Distance_Spheroid(s.geom,ST_Transform(a.geom,'EPSG:32632','EPSG:4326',true))<={r*1000}", f"SELECT count(*) FROM sites s, assets_utm32n a WHERE s.name='{s[0]}' AND ST_Distance(s.geom,a.geom)<={r*1000}") # antimeridian pairs = [(a, b) for a in ISLANDS for b in ISLANDS if a[0] < b[0] and a[2] * b[2] < 0 and abs(a[2]) > 120 and abs(b[2]) > 120 and km(a[1:], b[1:]) < 3000] for a, b in rnd.sample(pairs, min(RAD_N, len(pairs))): add("antimeridian", f"What is the shortest distance in kilometres between {a[0]} and {b[0]} in table islands?", km(a[1:], b[1:]), "num", f"SELECT ST_Distance_Spheroid(ST_Point(a.longitude,a.latitude),ST_Point(b.longitude,b.latitude))/1000 FROM islands a, islands b WHERE a.name='{a[0]}' AND b.name='{b[0]}'", f"SELECT ST_Distance(ST_Transform(ST_Point(a.longitude,a.latitude),'EPSG:4326','EPSG:3857',true),ST_Transform(ST_Point(b.longitude,b.latitude),'EPSG:4326','EPSG:3857',true))/1000 FROM islands a, islands b WHERE a.name='{a[0]}' AND b.name='{b[0]}'", 0.01) # controls: no spatial trap, general SQL only for i in range(CTRL_N): c = rnd.choice(list(CENTRES)) lim = round(CENTRES[c][0] + rnd.uniform(-.3, .3), 2) ref = sum(1 for s in stations if s[0][2:5] == c and s[1] > lim) add("control", f"How many stations with names starting 'T-{c}' have latitude greater than {lim}?", ref, "int", f"SELECT count(*) FROM stations WHERE name LIKE 'T-{c}%' AND latitude>{lim}") with open(DATA / "questions.jsonl", "w", encoding="utf-8") as f: for x in q: f.write(json.dumps(x) + "\n") (DATA / "schema.txt").write_text( "sites(name VARCHAR, geom GEOMETRY) -- points, EPSG:4326, x=longitude y=latitude\n" "sites_webmerc(name VARCHAR, geom GEOMETRY) -- same sites, EPSG:3857\n" "stations(name VARCHAR, latitude DOUBLE, longitude DOUBLE)\n" "parcels(name VARCHAR, geom GEOMETRY) -- polygons, EPSG:4326, x=longitude y=latitude\n" "parcels_webmerc(name VARCHAR, geom GEOMETRY) -- same parcels, EPSG:3857\n" "pipelines(name VARCHAR, geom GEOMETRY) -- linestrings, EPSG:4326, x=longitude y=latitude\n" "assets_utm32n(name VARCHAR, geom GEOMETRY) -- points, EPSG:32632 (metres)\n" "islands(name VARCHAR, latitude DOUBLE, longitude DOUBLE)\n", encoding="utf-8") print(len(q), {f: sum(1 for x in q if x["family"] == f) for f in sorted({x["family"] for x in q})}) if __name__ == "__main__": main()