In this section
- Fetch Metros Trams v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_metros_tramsv6.py lines 1–70
- Fetch Motorway Services v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_motorway_servicesv6.py lines 1–89
- Fetch Power Plants v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_power_plantsv6.py lines 1–73
- Fetch Railways v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_railwaysv6.py lines 1–70
- Fetch Stadiums v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_stadiumsv6.py lines 1–161
- Fetch Supermarkets v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_supermarketsv6.py lines 1–203
Fetch Metros Trams v6
A Python module in the scripts folder of GlobalGrid2050 that fetches UK metros trams, using ISO3166-1 from OpenStreetMap (Overpass).
storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_metros_tramsv6.py · lines 1–70 of 70 · Not reached from any entry point (candidate for review)
- What it does
- It fetches UK metros trams. Uses libraries requests, json. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: data source: OpenStreetMap (Overpass); GeoJSON file uk_metros_trams.geojson. Out: JSON file.
- What it achieves
- Overpass query to find UK Metros, Trams, and Light Rail (excluding Glasgow Subway).
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · repd_grid_atlasv6/scripts · Python module
- Uses
- requests, json
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_metros_tramsv6.py:1-70 · blob 8ebf84e4167388a1bccaf0254482628598803815 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import requests
import json
# Overpass query to find UK Metros, Trams, and Light Rail (excluding Glasgow Subway)
query = """
[out:json][timeout:90];
area["ISO3166-1"="GB"]->.uk;
(
/* Target specific major networks (omitting Glasgow Subway) */
node["network"~"London Underground|Tyne and Wear Metro|Docklands Light Railway|Manchester Metrolink|Edinburgh Trams|Nottingham Express Transit|Sheffield Supertram|West Midlands Metro|Blackpool Tramway|Tramlink"](area.uk);
way["network"~"London Underground|Tyne and Wear Metro|Docklands Light Railway|Manchester Metrolink|Edinburgh Trams|Nottingham Express Transit|Sheffield Supertram|West Midlands Metro|Blackpool Tramway|Tramlink"](area.uk);
rel["network"~"London Underground|Tyne and Wear Metro|Docklands Light Railway|Manchester Metrolink|Edinburgh Trams|Nottingham Express Transit|Sheffield Supertram|West Midlands Metro|Blackpool Tramway|Tramlink"](area.uk);
/* Catch-all for generic tram stops and light rail, explicitly ensuring Glasgow isn't caught by accident */
node["railway"="tram_stop"]["network"!~"Glasgow Subway"](area.uk);
way["railway"="tram_stop"]["network"!~"Glasgow Subway"](area.uk);
rel["railway"="tram_stop"]["network"!~"Glasgow Subway"](area.uk);
node["railway"="station"]["light_rail"="yes"]["network"!~"Glasgow Subway"](area.uk);
);
out center;
"""
url = "https://overpass-api.de/api/interpreter"
print("Fetching UK Metros and Trams from Overpass API...")
response = requests.post(url, data={'data': query})
if response.status_code == 200:
data = response.json()
features = []
for element in data.get('elements', []):
lat = element.get('lat') or element.get('center', {}).get('lat')
lon = element.get('lon') or element.get('center', {}).get('lon')
if lat and lon:
tags = element.get('tags', {})
name = tags.get('name', 'Unknown Station/Stop')
network = tags.get('network', 'UK Metro/Tram')
# Determine if it's a Metro or a Tram for the popup description
is_metro = any(n in network for n in ["London Underground", "Tyne and Wear Metro", "Docklands Light Railway"])
transit_type = "Metro Station" if is_metro else "Tram / Light Rail"
feature = {
"type": "Feature",
"properties": {
"name": name,
"type": transit_type,
"operator": network
},
"geometry": {
"type": "Point",
"coordinates": [lon, lat]
}
}
features.append(feature)
geojson = {
"type": "FeatureCollection",
"features": features
}
output_path = "uk_metros_trams.geojson"
with open(output_path, "w", encoding="utf-8") as f:
json.dump(geojson, f, indent=2)
print(f"Successfully saved {len(features)} Metro/Tram locations to {output_path}")
else:
print(f"Error fetching data: {response.status_code}")Fetch Motorway Services v6
A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches motorways from OpenStreetMap (Overpass).
storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_motorway_servicesv6.py · lines 1–89 of 89 · Entry point · pattern process_data (shared by 5 files)
- What it does
- It fetches motorways. Defines build_query, process_data, main. Uses libraries requests, json. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: motorways.
- Inputs & outputs
- In: data source: OpenStreetMap (Overpass). Out: GeoJSON file motorway_services.geojson; JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Its name says it fetches motorway services. Defines `build_query` and `process_data`. It writes `motorway_services.geojson`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
- Uses
- requests, json
- Used by
- none found
- Produces
- build_query, process_data, main
- Defines here
- build_query, process_data, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_motorway_servicesv6.py:1-89 · blob 444e32535e2e9882dddc47128d76f768ffd649e7 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
OVERPASS_URL = "https://overpass-api.de/api/interpreter"
# Strict UK Bounding Box to filter out French/Irish services
BBOX = "49.8,-8.5,60.9,1.8"
def build_query() -> str:
# Targets Motorway and major Trunk Road services explicitly
return f"""[out:json][timeout:90];
(
node["highway"="services"]({BBOX});
way["highway"="services"]({BBOX});
relation["highway"="services"]({BBOX});
);
out center tags;
"""
def process_data(data: dict) -> list:
features = []
seen = set()
for el in data.get("elements", []):
el_id = el["id"]
if el_id in seen:
continue
tags = el.get("tags", {})
# Determine coordinates (nodes use lat/lon, ways/relations use center)
lat = el.get("lat")
lon = el.get("lon")
if "center" in el:
lat = el["center"]["lat"]
lon = el["center"]["lon"]
if lat is not None and lon is not None:
seen.add(el_id)
name = tags.get("name", "Motorway Services")
operator = tags.get("operator", tags.get("brand", "Unknown Operator"))
features.append({
"type": "Feature",
"properties": {
"name": name,
"operator": operator,
"osm_id": el_id,
"type": "motorway_services"
},
"geometry": {"type": "Point", "coordinates": [round(lon, 6), round(lat, 6)]}
})
return features
def main():
print("Fetching UK Motorway Service Areas...")
query = build_query()
try:
res = requests.post(OVERPASS_URL, data={"data": query}, timeout=90)
res.raise_for_status()
raw_data = res.json()
except Exception as e:
print(f"Error fetching data: {e}")
return
features = process_data(raw_data)
# Deduplicate overlapping nodes/polygons (within ~150m)
tol = 150.0 / 111320.0
kept = []
for f in features:
lon, lat = f["geometry"]["coordinates"]
dup = False
for k in kept:
klon, klat = k["geometry"]["coordinates"]
if abs(lon - klon) < tol and abs(lat - klat) < tol:
dup = True
break
if not dup: kept.append(f)
geojson = {"type": "FeatureCollection", "features": kept}
with open("motorway_services.geojson", "w", encoding="utf-8") as f:
json.dump(geojson, f, ensure_ascii=False, separators=(",", ":"))
print(f"Saved {len(kept)} Motorway Services to motorway_services.geojson")
if __name__ == "__main__":
main()Fetch Power Plants v6
A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).
storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_power_plantsv6.py · lines 1–73 of 73 · Entry point
- What it does
- It fetches data. Defines fetch_power_plants. Uses libraries requests, json, time. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: data source: OpenStreetMap (Overpass). Out: GeoJSON file power_plants.geojson; JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Its name says it fetches power plants. Defines `fetch_power_plants`. It writes `power_plants.geojson`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
- Uses
- requests, json, time
- Used by
- none found
- Produces
- fetch_power_plants
- Defines here
- fetch_power_plants
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_power_plantsv6.py:1-73 · blob eb58cf8805466665f74e620ff4fdae0a3caddd49 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import time
def fetch_power_plants():
print("🚀 Fetching UK Nuclear & Gas Plants from OpenStreetMap...")
query = """
[out:json][timeout:180];
area(3600062149)->.uk;
(
node["power"="plant"]["plant:source"="nuclear"](area.uk);
way["power"="plant"]["plant:source"="nuclear"](area.uk);
relation["power"="plant"]["plant:source"="nuclear"](area.uk);
node["power"="plant"]["plant:source"="gas"](area.uk);
way["power"="plant"]["plant:source"="gas"](area.uk);
relation["power"="plant"]["plant:source"="gas"](area.uk);
);
out center;
"""
url = "https://overpass-api.de/api/interpreter"
for attempt in range(3):
try:
response = requests.post(url, data={'data': query})
if response.status_code == 200:
print(" ✅ Download successful!")
break
elif response.status_code == 429:
print(" ⚠️ Server busy, sleeping 60s...")
time.sleep(60)
else:
print(f" ❌ Error: {response.status_code}")
return
except Exception as e:
print(f" ❌ Connection Error: {e}")
return
osm_data = response.json()
geojson = {"type": "FeatureCollection", "features": []}
for element in osm_data.get('elements', []):
tags = element.get('tags', {})
if element['type'] == 'node':
lat, lon = element.get('lat'), element.get('lon')
elif 'center' in element:
lat, lon = element['center'].get('lat'), element['center'].get('lon')
else:
continue
if lat and lon:
source = tags.get('plant:source', 'unknown')
feature = {
"type": "Feature",
"properties": {
"name": tags.get('name', f'Unknown {source.title()} Plant'),
"operator": tags.get('operator', 'Unknown Operator'),
"source": source
},
"geometry": {"type": "Point", "coordinates": [lon, lat]}
}
geojson['features'].append(feature)
with open("power_plants.geojson", 'w', encoding='utf-8') as f:
json.dump(geojson, f)
print(f"🎉 Successfully saved {len(geojson['features'])} Power Plants!")
if __name__ == "__main__":
fetch_power_plants()
Fetch Railways v6
A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).
storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_railwaysv6.py · lines 1–70 of 70 · Entry point
- What it does
- It fetches data. Defines fetch_railways. Uses libraries requests, json, time. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: data source: OpenStreetMap (Overpass). Out: GeoJSON file railways.geojson; JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Its name says it fetches railways. Defines `fetch_railways`. It writes `railways.geojson`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
- Uses
- requests, json, time
- Used by
- none found
- Produces
- fetch_railways
- Defines here
- fetch_railways
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_railwaysv6.py:1-70 · blob 45593b916bca5f4c347fe2f65a4f7fe791dbb11c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import time
def fetch_railways():
print("🚀 Fetching UK Railway Stations from OpenStreetMap...")
# Target proper railway stations (ignores minor tram stops/halts)
query = """
[out:json][timeout:180];
area(3600062149)->.uk;
(
node["railway"="station"](area.uk);
way["railway"="station"](area.uk);
relation["railway"="station"](area.uk);
);
out center;
"""
url = "https://overpass-api.de/api/interpreter"
for attempt in range(3):
try:
response = requests.post(url, data={'data': query})
if response.status_code == 200:
print(" ✅ Download successful!")
break
elif response.status_code == 429:
print(" ⚠️ Server busy, sleeping 60s...")
time.sleep(60)
else:
print(f" ❌ Error: {response.status_code}")
return
except Exception as e:
print(f" ❌ Connection Error: {e}")
return
osm_data = response.json()
geojson = {"type": "FeatureCollection", "features": []}
for element in osm_data.get('elements', []):
tags = element.get('tags', {})
if element['type'] == 'node':
lat, lon = element.get('lat'), element.get('lon')
elif 'center' in element:
lat, lon = element['center'].get('lat'), element['center'].get('lon')
else:
continue
if lat and lon:
if 'name' in tags:
feature = {
"type": "Feature",
"properties": {
"name": tags.get('name', 'Unknown Station'),
"network": tags.get('network', 'National Rail / TFL')
},
"geometry": {"type": "Point", "coordinates": [lon, lat]}
}
geojson['features'].append(feature)
with open("railways.geojson", 'w', encoding='utf-8') as f:
json.dump(geojson, f)
print(f"🎉 Successfully saved {len(geojson['features'])} Railway Stations to railways.geojson!")
if __name__ == "__main__":
fetch_railways()
Fetch Stadiums v6
A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).
storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_stadiumsv6.py · lines 1–161 of 161 · Entry point · pattern handle_element (shared by 2 files)
- What it does
- It fetches data. Defines 8 functions or classes, including build_query, is_in_uk_ireland, polygon_area_m2, centroid, way_to_ring. Uses libraries requests, json, math. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: data source: OpenStreetMap (Overpass). Out: GeoJSON file stadiums.geojson; JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It builds query (`build_query`) and is built from the is in UK ireland helper (`is_in_uk_ireland`) and the polygon area m2 helper (`polygon_area_m2`). Use the primary, fast Overpass API endpoint. It writes `stadiums.geojson`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
- Uses
- requests, json, math
- Used by
- none found
- Produces
- build_query, is_in_uk_ireland, polygon_area_m2, centroid, way_to_ring, process_data, main
- Defines here
- build_query, is_in_uk_ireland, polygon_area_m2, centroid, way_to_ring, process_data, handle_element, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_stadiumsv6.py:1-161 · blob 4e05c07a763f6c16b9e7bec666aed3f357734385 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import math
# Use the primary, fast Overpass API endpoint
OVERPASS_URL = "https://overpass-api.de/api/interpreter"
MIN_CAPACITY = 18000 # Target ~20k, but allow a slight buffer for borderline stadiums
MIN_AREA_M2 = 20000 # Fallback: A 20k stadium footprint is typically 25k+ m2
BBOX = "49.5,-10.8,61.0,2.2"
def build_query() -> str:
blocks = (
f'way["leisure"="stadium"]({BBOX});\n'
f'relation["leisure"="stadium"]({BBOX});\n'
)
return f"[out:json][timeout:180];\n(\n{blocks});\nout body;\n>;\nout skel qt;\n"
def is_in_uk_ireland(lon: float, lat: float) -> bool:
if lat < 51.4 and lon > 1.45: return False
if lat < 51.0 and lon > 1.10: return False
if lat < 50.7 and lon > 0.00: return False
if lat < 50.4 and lon > -2.00: return False
if lat < 49.8 and lon > -5.00: return False
return True
def polygon_area_m2(coords: list) -> float:
if not coords or len(coords) < 3: return 0.0
lat_c = sum(c[1] for c in coords) / len(coords)
mlat = 111_320.0
mlon = 111_320.0 * math.cos(math.radians(lat_c))
n = len(coords)
area = 0.0
for i in range(n):
x1 = coords[i][0] * mlon
y1 = coords[i][1] * mlat
x2 = coords[(i + 1) % n][0] * mlon
y2 = coords[(i + 1) % n][1] * mlat
area += x1 * y2 - x2 * y1
return abs(area) / 2.0
def centroid(coords: list) -> tuple:
return (sum(c[0] for c in coords) / len(coords), sum(c[1] for c in coords) / len(coords))
def way_to_ring(way: dict, nodes: dict):
coords = []
for nid in way.get("nodes", []):
if nid in nodes:
node = nodes[nid]
coords.append((node["lon"], node["lat"]))
if len(coords) < 3: return None
if coords[0] != coords[-1]: coords.append(coords[0])
return coords
def process_data(data: dict) -> list:
elements = data.get("elements", [])
nodes = {el["id"]: el for el in elements if el["type"] == "node"}
ways = {el["id"]: el for el in elements if el["type"] == "way" and "tags" in el}
relations = [el for el in elements if el["type"] == "relation" and "tags" in el]
features = []
seen = set()
def handle_element(el_id, tags, coords):
if el_id in seen: return
lon, lat = centroid(coords)
if not is_in_uk_ireland(lon, lat): return
area = polygon_area_m2(coords)
# Check capacity
cap_str = tags.get("capacity", "0")
try:
clean_cap = ''.join(filter(str.isdigit, cap_str))
capacity = int(clean_cap) if clean_cap else 0
except:
capacity = 0
# Drop if it doesn't meet either the capacity or area requirement
if capacity > 0:
if capacity < MIN_CAPACITY: return
else:
if area < MIN_AREA_M2: return
# Validate the sport
sport = tags.get("sport", "").lower()
valid_sports = ["soccer", "rugby_union", "rugby_league", "cricket", "athletics", "rugby", "multi"]
if sport and not any(s in sport for s in valid_sports):
return # Drops unwanted venues like greyhound or horse racing tracks
seen.add(el_id)
features.append({
"type": "Feature",
"properties": {
"name": tags.get("name", "Unnamed Stadium"),
"sport": sport.replace("_", " ").title() if sport else "Multi-Sport",
"club": tags.get("club", tags.get("operator", "")),
"capacity": capacity if capacity > 0 else "Unknown",
"area_m2": round(area),
"osm_id": el_id,
"type": "stadium"
},
"geometry": {"type": "Point", "coordinates": [round(lon, 6), round(lat, 6)]}
})
for way in ways.values():
ring = way_to_ring(way, nodes)
if ring: handle_element(way["id"], way["tags"], ring)
for rel in relations:
outer_coords = []
for member in rel.get("members", []):
if member["type"] == "way" and member.get("role") in ("outer", ""):
w = ways.get(member["ref"])
if w:
ring = way_to_ring(w, nodes)
if ring: outer_coords.extend(ring)
if outer_coords:
handle_element(rel["id"], rel["tags"], outer_coords)
return features
def main():
print("Fetching major UK stadiums...")
query = build_query()
try:
res = requests.post(OVERPASS_URL, data={"data": query}, timeout=180)
res.raise_for_status()
raw_data = res.json()
except Exception as e:
print(f"Error fetching data: {e}")
return
features = process_data(raw_data)
# Deduplicate overlapping ways and relations
tol = 150.0 / 111320.0
kept = []
for f in features:
lon, lat = f["geometry"]["coordinates"]
dup = False
for k in kept:
klon, klat = k["geometry"]["coordinates"]
if abs(lon - klon) < tol and abs(lat - klat) < tol:
if f["properties"]["area_m2"] > k["properties"]["area_m2"]:
kept.remove(k)
else:
dup = True
break
if not dup: kept.append(f)
geojson = {"type": "FeatureCollection", "features": kept}
with open("stadiums.geojson", "w", encoding="utf-8") as f:
json.dump(geojson, f, ensure_ascii=False, separators=(",", ":"))
print(f"Saved {len(kept)} major stadiums to stadiums.geojson")
if __name__ == "__main__":
main()Fetch Supermarkets v6
A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches supermarkets tesco, supermarkets sainsburys, supermarkets asda and supermarkets morrisons from OpenStreetMap (Overpass).
storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_supermarketsv6.py · lines 1–203 of 203 · Entry point · pattern polygon_area_m (shared by 2 files)
- What it does
- It fetches supermarkets tesco, supermarkets sainsburys, supermarkets asda and supermarkets morrisons. Defines 11 functions or classes, including build_bulk_query, fetch_overpass, node_map, polygon_area_m2, centroid. Uses libraries requests, json, math, collections. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: data source: OpenStreetMap (Overpass); GeoJSON file supermarkets_tesco.geojson; GeoJSON file supermarkets_sainsburys.geojson; GeoJSON file supermarkets_asda.geojson; GeoJSON file supermarkets_morrisons.geojson; GeoJSON file supermarkets_aldi.geojson; GeoJSON file supermarkets_lidl.geojson; GeoJSON file supermarkets_waitrose.geojson. Out: JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It builds bulk query (`build_bulk_query`), fetches overpass (`fetch_overpass`) and matches brand (`match_brand`). Use the primary, fast Overpass API endpoint.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
- Uses
- requests, json, math, collections
- Used by
- none found
- Produces
- build_bulk_query, fetch_overpass, node_map, polygon_area_m2, centroid, way_to_ring, match_brand, process_bulk_data, deduplicate, main
- Defines here
- build_bulk_query, fetch_overpass, node_map, polygon_area_m2, centroid, way_to_ring, match_brand, process_bulk_data, _feature, deduplicate, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_supermarketsv6.py:1-203 · blob c1b8a9d50e182ff0d3fb8c99445a059be2765cf4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import math
from collections import defaultdict
# Use the primary, fast Overpass API endpoint
OVERPASS_URL = "https://overpass-api.de/api/interpreter"
MIN_AREA_M2 = 2500
BBOX = "49.5,-10.8,61.0,2.2"
# Added a few aliases to the search logic below to catch messy OSM tags
BRANDS = [
{"name": "Tesco", "canonical": "Tesco", "file": "supermarkets_tesco.geojson", "colour": "#ee1c2e"},
{"name": "Sainsbury's", "canonical": "Sainsbury's", "file": "supermarkets_sainsburys.geojson", "colour": "#ff8200"},
{"name": "Sainsbury", "canonical": "Sainsbury's", "file": "supermarkets_sainsburys.geojson", "colour": "#ff8200"},
{"name": "Asda", "canonical": "Asda", "file": "supermarkets_asda.geojson", "colour": "#78be20"},
{"name": "Morrisons", "canonical": "Morrisons", "file": "supermarkets_morrisons.geojson", "colour": "#ffd700"},
{"name": "Aldi", "canonical": "Aldi", "file": "supermarkets_aldi.geojson", "colour": "#003087"},
{"name": "Lidl", "canonical": "Lidl", "file": "supermarkets_lidl.geojson", "colour": "#0050aa"},
{"name": "Waitrose", "canonical": "Waitrose", "file": "supermarkets_waitrose.geojson", "colour": "#7ab800"},
{"name": "Marks and Spencer", "canonical": "M&S Food", "file": "supermarkets_ms.geojson", "colour": "#009b77"},
{"name": "M&S", "canonical": "M&S Food", "file": "supermarkets_ms.geojson", "colour": "#009b77"},
{"name": "Co-op", "canonical": "Co-op", "file": "supermarkets_coop.geojson", "colour": "#00b1a9"},
{"name": "Coop", "canonical": "Co-op", "file": "supermarkets_coop.geojson", "colour": "#00b1a9"},
{"name": "Iceland", "canonical": "Iceland", "file": "supermarkets_iceland.geojson", "colour": "#c8102e"},
{"name": "Farmfoods", "canonical": "Farmfoods", "file": "supermarkets_farmfoods.geojson", "colour": "#e30613"},
{"name": "Costco", "canonical": "Costco", "file": "supermarkets_costco.geojson", "colour": "#005daa"},
{"name": "Booths", "canonical": "Booths", "file": "supermarkets_booths.geojson", "colour": "#6d2077"},
{"name": "Spar", "canonical": "Spar", "file": "supermarkets_spar.geojson", "colour": "#00a650"},
]
def build_bulk_query() -> str:
# ONE query to pull every supermarket & wholesale store in the UK
blocks = (
f'way["shop"="supermarket"]({BBOX});\n'
f'way["shop"="wholesale"]({BBOX});\n'
f'relation["shop"="supermarket"]({BBOX});\n'
f'relation["shop"="wholesale"]({BBOX});\n'
)
return f"[out:json][timeout:180];\n(\n{blocks});\nout body;\n>;\nout skel qt;\n"
def fetch_overpass(query: str) -> dict:
print("Fetching all supermarkets from Overpass... (This takes ~10 seconds)")
try:
response = requests.post(OVERPASS_URL, data={"data": query}, timeout=180)
response.raise_for_status()
return response.json()
except Exception as e:
print(f"CRITICAL ERROR fetching Overpass data: {e}")
return {}
def node_map(elements: list) -> dict:
return {el["id"]: (el["lon"], el["lat"]) for el in elements if el["type"] == "node"}
def polygon_area_m2(coords: list) -> float:
if not coords or len(coords) < 3: return 0.0
lat_c = sum(c[1] for c in coords) / len(coords)
mlat = 111_320.0
mlon = 111_320.0 * math.cos(math.radians(lat_c))
n = len(coords)
area = 0.0
for i in range(n):
x1 = coords[i][0] * mlon
y1 = coords[i][1] * mlat
x2 = coords[(i + 1) % n][0] * mlon
y2 = coords[(i + 1) % n][1] * mlat
area += x1 * y2 - x2 * y1
return abs(area) / 2.0
def centroid(coords: list) -> tuple:
return (sum(c[0] for c in coords) / len(coords), sum(c[1] for c in coords) / len(coords))
def way_to_ring(way: dict, nodes: dict):
coords = [nodes[nid] for nid in way.get("nodes", []) if nid in nodes]
if len(coords) < 3: return None
if coords[0] != coords[-1]: coords.append(coords[0])
return coords
def match_brand(tags: dict) -> dict:
# Mash relevant tags together to catch messy OpenStreetMap data
search_string = f"{tags.get('brand', '')} {tags.get('name', '')} {tags.get('operator', '')}".lower()
for b in BRANDS:
if b["name"].lower() in search_string:
return b
return None
def process_bulk_data(data: dict) -> dict:
print("Processing geometries and filtering by brand...")
elements = data.get("elements", [])
nodes = node_map(elements)
ways = {el["id"]: el for el in elements if el["type"] == "way" and "tags" in el}
relations = [el for el in elements if el["type"] == "relation" and "tags" in el]
brand_features = defaultdict(list)
seen = set()
# Process Ways
for way in ways.values():
if way["id"] in seen: continue
brand_match = match_brand(way["tags"])
if not brand_match: continue
ring = way_to_ring(way, nodes)
if not ring: continue
area = polygon_area_m2(ring)
if area < MIN_AREA_M2: continue
seen.add(way["id"])
lon, lat = centroid(ring)
feature = _feature(lon, lat, way["tags"], area, way["id"], "way", brand_match)
brand_features[brand_match["canonical"]].append(feature)
# Process Relations
for rel in relations:
if rel["id"] in seen: continue
brand_match = match_brand(rel["tags"])
if not brand_match: continue
outer_coords = []
for member in rel.get("members", []):
if member["type"] == "way" and member.get("role") in ("outer", ""):
way = ways.get(member["ref"])
if way:
ring = way_to_ring(way, nodes)
if ring: outer_coords.extend(ring)
if not outer_coords: continue
area = polygon_area_m2(outer_coords)
if area < MIN_AREA_M2: continue
seen.add(rel["id"])
lon, lat = centroid(outer_coords)
feature = _feature(lon, lat, rel["tags"], area, rel["id"], "relation", brand_match)
brand_features[brand_match["canonical"]].append(feature)
return brand_features
def _feature(lon, lat, tags, area, osm_id, osm_type, brand) -> dict:
return {
"type": "Feature",
"properties": {
"name": tags.get("name", ""),
"brand": brand["canonical"],
"colour": brand["colour"],
"street": tags.get("addr:street", ""),
"city": tags.get("addr:city", ""),
"postcode": tags.get("addr:postcode", ""),
"website": tags.get("website", ""),
"area_m2": round(area),
"osm_id": osm_id,
"osm_type": osm_type,
"type": "supermarket",
},
"geometry": {"type": "Point", "coordinates": [round(lon, 6), round(lat, 6)]}
}
def deduplicate(features: list, tol_m: float = 80.0) -> list:
tol = tol_m / 111_320.0
kept = []
for f in features:
lon, lat = f["geometry"]["coordinates"]
dup = False
for k in kept:
klon, klat = k["geometry"]["coordinates"]
if abs(lon - klon) < tol and abs(lat - klat) < tol:
if f["properties"]["area_m2"] > k["properties"]["area_m2"]:
kept.remove(k)
else:
dup = True
break
if not dup: kept.append(f)
return kept
def main():
query = build_bulk_query()
raw_data = fetch_overpass(query)
if not raw_data:
return
brand_features_map = process_bulk_data(raw_data)
total = 0
# Create an output file based on the unique canon names in our config
unique_brands = {b["canonical"]: b for b in BRANDS}.values()
for brand in unique_brands:
raw_features = brand_features_map.get(brand["canonical"], [])
cleaned_features = deduplicate(raw_features)
geojson = {"type": "FeatureCollection", "features": cleaned_features}
with open(brand["file"], "w", encoding="utf-8") as f:
json.dump(geojson, f, ensure_ascii=False, separators=(",", ":"))
print(f" Saved {len(cleaned_features)} stores to {brand['file']}")
total += len(cleaned_features)
print(f"\nBOOM. Done. {total} total stores generated instantly.")
if __name__ == "__main__":
main()