GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / globalgrid2050 / repd_grid_atlasv6/scripts

Fetch Global Hydrocarbons v6 and 5 more files

A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches gem hydrocarbons master from OpenStreetMap (Overpass). It parses gem (`parse_gem_data`), fetches OSM (`fetch_osm_data`) and saves GeoJSON (`save_geojson`).

680 lines of Python from globalgrid2050, in 6 files. Topic: Maps, GIS and field navigation. Section 495 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Fetch Global Hydrocarbons v6 geodesy · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_global_hydrocarbonsv6.py lines 1–215
  2. Fetch Global Ports v6 geodesy · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_global_portsv6.py lines 1–118
  3. Fetch Grid Data v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_grid_datav6.py lines 1–79
  4. Fetch Hs2v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_hs2v6.py lines 1–69
  5. Fetch Industrial Offtakers v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_industrial_offtakersv6.py lines 1–141
  6. Fetch London Underground v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_london_undergroundv6.py lines 1–58

Fetch Global Hydrocarbons v6

A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches gem hydrocarbons master from OpenStreetMap (Overpass). It parses gem (`parse_gem_data`), fetches OSM (`fetch_osm_data`) and saves GeoJSON (`save_geojson`).

geodesyglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_global_hydrocarbonsv6.py · lines 1–215 of 215 · Entry point · pattern haversine_distance (shared by 2 files)

What it does
It fetches gem hydrocarbons master. Defines haversine_distance, parse_gem_data, fetch_osm_data, deduplicate_and_merge, save_geojson. Uses libraries requests, json, math, os, sys. Side effects: reads or writes files; makes network requests; starts processes.
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); CSV file gem_hydrocarbons_master.csv; GeoJSON file global_hydrocarbons.geojson. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Calculate the absolute path of the repository root.
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, os, sys, csv
Used by
none found
Produces
haversine_distance, parse_gem_data, fetch_osm_data, deduplicate_and_merge, save_geojson
Defines here
haversine_distance, parse_gem_data, fetch_osm_data, deduplicate_and_merge, save_geojson
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_global_hydrocarbonsv6.py:1-215 · blob 2498688d03fb79c8e4c2285745a6730bfe2280cb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import math
import os
import sys
import csv

# Calculate the absolute path of the repository root
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, '..'))

OVERPASS_URL = "https://overpass-api.de/api/interpreter"
GEM_CSV_FILENAME = "gem_hydrocarbons_master.csv"  
DEDUPLICATION_RADIUS_M = 3000.0  

OVERPASS_QUERY = """[out:json][timeout:900];
(
  way["man_made"="petroleum_works"];
  relation["man_made"="petroleum_works"];
  way["industrial"="oil_refinery"];
  relation["industrial"="oil_refinery"];
  way["industrial"="oil"];
  relation["industrial"="oil"];
  way["industrial"="gas"];
  relation["industrial"="gas"];
  way["industrial"="lng"];
  relation["industrial"="lng"];
  way["product"="lng"];
  relation["product"="lng"];
  way["industrial"="gas_field"];
  relation["industrial"="gas_field"];
  way["industrial"="oil_field"];
  relation["industrial"="oil_field"];
  node["man_made"="offshore_platform"];
  way["man_made"="offshore_platform"];
  relation["man_made"="offshore_platform"];
);
out center bb;"""

def haversine_distance(lat1, lon1, lat2, lon2):
    R = 6371000
    phi1, phi2 = math.radians(lat1), math.radians(lat2)
    dphi = math.radians(lat2 - lat1)
    dlambda = math.radians(lon2 - lon1)
    a = math.sin(dphi/2)**2 + math.cos(phi1)*math.cos(phi2)*math.sin(dlambda/2)**2
    return 2 * R * math.atan2(math.sqrt(a), math.sqrt(1-a))

def parse_gem_data():
    gem_features = []
    filepath = os.path.join(REPO_ROOT, GEM_CSV_FILENAME)
    
    if not os.path.exists(filepath):
        print(f"WARNING: Gold Standard file '{GEM_CSV_FILENAME}' not found in root. Defaulting strictly to OSM.")
        return gem_features
        
    print(f"Ingesting Gold Standard data from {filepath}...")
    with open(filepath, 'r', encoding='utf-8-sig') as f:
        reader = csv.DictReader(f)
        headers = [h.lower() for h in reader.fieldnames]
        
        lat_col = next((h for h in headers if 'lat' in h), None)
        lon_col = next((h for h in headers if 'lon' in h or 'lng' in h), None)
        name_col = next((h for h in headers if 'name' in h or 'project' in h), None)
        type_col = next((h for h in headers if 'type' in h or 'category' in h), None)
        
        if not lat_col or not lon_col:
            print("CRITICAL: Could not identify Latitude/Longitude columns in GEM CSV.")
            return gem_features

        for row in reader:
            try:
                lat_key = reader.fieldnames[headers.index(lat_col)]
                lon_key = reader.fieldnames[headers.index(lon_col)]
                name_key = reader.fieldnames[headers.index(name_col)] if name_col else None
                type_key = reader.fieldnames[headers.index(type_col)] if type_col else None
                
                lat = float(row[lat_key])
                lon = float(row[lon_key])
                name = row[name_key] if name_key else "GEM Tracked Facility"
                facility_type = row[type_key] if type_key else "Hydrocarbon Asset"
                
                gem_features.append({
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [lon, lat]
                    },
                    "properties": {
                        "name": name,
                        "type": facility_type,
                        "source": "Global Energy Monitor",
                        "area_ha": 30.0
                    }
                })
            except (ValueError, TypeError):
                continue
                
    print(f"SUCCESS: Ingested {len(gem_features)} Gold Standard assets.")
    return gem_features

def fetch_osm_data():
    print("Initiating global Overpass API extraction for secondary infrastructure...")
    
    headers = {
        'User-Agent': 'GlobalGrid2050-Pipeline/5.0 (Automated Spatial Extraction)'
    }
    
    try:
        response = requests.post(OVERPASS_URL, data=OVERPASS_QUERY.encode('utf-8'), headers=headers)
        
        if response.status_code != 200:
            print(f"OVERPASS API ERROR [{response.status_code}]:\n{response.text}")
            
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"CRITICAL: Failed to fetch data: {e}")
        sys.exit(1)

def deduplicate_and_merge(gem_features, osm_raw):
    final_features = list(gem_features)
    if not osm_raw:
        return {"type": "FeatureCollection", "features": final_features}
        
    elements = osm_raw.get('elements', [])
    
    print(f"Cross-referencing {len(elements)} OSM assets against Gold Standard data...")
    
    osm_kept = 0
    osm_dropped = 0
    
    for el in elements:
        lon = el.get('lon') or el.get('center', {}).get('lon')
        lat = el.get('lat') or el.get('center', {}).get('lat')
        
        if not lon or not lat:
            continue

        is_duplicate = False
        for gem in gem_features:
            gem_lon, gem_lat = gem['geometry']['coordinates']
            distance = haversine_distance(lat, lon, gem_lat, gem_lon)
            if distance <= DEDUPLICATION_RADIUS_M:
                is_duplicate = True
                break
                
        if is_duplicate:
            osm_dropped += 1
            continue

        tags = el.get('tags', {})
        is_offshore_platform = tags.get('man_made') == 'offshore_platform'
        is_field = tags.get('industrial') in ['gas_field', 'oil_field']
        is_lng = tags.get('industrial') == 'lng' or tags.get('product') == 'lng'
        
        area_ha = 0.0
        bounds = el.get('bounds')
        
        if bounds:
            minlat, minlon = bounds['minlat'], bounds['minlon']
            maxlat, maxlon = bounds['maxlat'], bounds['maxlon']
            width_m = haversine_distance(lat, minlon, lat, maxlon)
            height_m = haversine_distance(minlat, lon, maxlat, lon)
            area_ha = (width_m * height_m) / 10000.0
            
            if area_ha < 5.0 and not is_field and not is_lng:
                continue
        elif not is_offshore_platform:
            continue

        name = tags.get('name', tags.get('name:en', 'Unnamed Hydrocarbon Facility'))
        
        if is_lng: facility_type = 'LNG Terminal / Plant'
        elif tags.get('industrial') == 'gas_field': facility_type = 'Gas Field'
        elif tags.get('industrial') == 'oil_field': facility_type = 'Oil Field'
        elif is_offshore_platform: facility_type = 'Offshore Platform'
        elif tags.get('industrial') == 'gas': facility_type = 'Gas Processing'
        else: facility_type = 'Oil Refinery'
        
        if is_offshore_platform: area_ha = max(area_ha, 30.0)
        elif is_lng: area_ha = max(area_ha, 10.0)
        
        final_features.append({
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [lon, lat]
            },
            "properties": {
                "name": name,
                "type": facility_type,
                "source": "OSM",
                "area_ha": round(area_ha, 1),
                "osm_id": el['id']
            }
        })
        osm_kept += 1
        
    print(f"Deduplication Complete: Kept {osm_kept} OSM assets, Dropped {osm_dropped} duplicates.")
    return {
        "type": "FeatureCollection",
        "features": final_features
    }

def save_geojson(geojson_data, filename="global_hydrocarbons.geojson"):
    filepath = os.path.join(REPO_ROOT, filename)
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(geojson_data, f, separators=(',', ':'))
    print(f"SUCCESS: Wrote {len(geojson_data['features'])} unified facilities to {filepath}")

if __name__ == "__main__":
    gem_data = parse_gem_data()
    osm_raw = fetch_osm_data()
    final_geojson = deduplicate_and_merge(gem_data, osm_raw)
    save_geojson(final_geojson)

Fetch Global Ports v6

A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass). It fetches ports (`fetch_ports`), converts GeoJSON (`convert_to_geojson`) and saves GeoJSON (`save_geojson`).

geodesyglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_global_portsv6.py · lines 1–118 of 118 · Entry point · pattern haversine_distance (shared by 2 files)

What it does
It fetches data. Defines haversine_distance, fetch_ports, convert_to_geojson, save_geojson. Uses libraries requests, json, math, os, sys. Side effects: reads or writes files; makes network requests; starts processes.
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 global_ports.geojson. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Calculate the absolute path of the repository root.
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, os, sys, time
Used by
none found
Produces
haversine_distance, fetch_ports, convert_to_geojson, save_geojson
Defines here
haversine_distance, fetch_ports, convert_to_geojson, save_geojson
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_global_portsv6.py:1-118 · blob a20b619d5aeac7e52e606565afaa4fadcbaf3c21 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import math
import os
import sys
import time

# Calculate the absolute path of the repository root
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, '..'))

OVERPASS_URL = "https://overpass-api.de/api/interpreter"

# Added [maxsize:2000000000] to explicitly prevent Overpass memory crashes on global bounding boxes
OVERPASS_QUERY = """[out:json][timeout:900][maxsize:2000000000];
(
  nwr["seamark:type"="harbour"];
  nwr["industrial"="port"];
  nwr["amenity"="ferry_terminal"];
);
out center bb;"""

def haversine_distance(lat1, lon1, lat2, lon2):
    R = 6371000
    phi1, phi2 = math.radians(lat1), math.radians(lat2)
    dphi = math.radians(lat2 - lat1)
    dlambda = math.radians(lon2 - lon1)
    a = math.sin(dphi/2)**2 + math.cos(phi1)*math.cos(phi2)*math.sin(dlambda/2)**2
    return 2 * R * math.atan2(math.sqrt(a), math.sqrt(1-a))

def fetch_ports():
    print("Initiating global port & ferry extraction from Overpass API...")
    headers = {'User-Agent': 'GlobalGrid2050-Pipeline/5.1'}
    
    # Built-in resilience: Retry loop for memory drops or rate limits
    for attempt in range(3):
        try:
            # Switched to safe form-data payload, explicitly matching the timeout length
            response = requests.post(OVERPASS_URL, data={'data': OVERPASS_QUERY}, headers=headers, timeout=900)
            
            if response.status_code == 200:
                print("SUCCESS: Data downloaded from Overpass!")
                return response.json()
            elif response.status_code == 429:
                print(f"WARNING: API Rate Limited (429). Retrying in 60s... (Attempt {attempt+1}/3)")
                time.sleep(60)
            else:
                print(f"OVERPASS API ERROR [{response.status_code}]:\n{response.text}")
                sys.exit(1)
                
        except requests.exceptions.RequestException as e:
            print(f"CRITICAL: Failed to fetch data: {e}")
            if attempt == 2:
                sys.exit(1)
            print("Retrying in 30 seconds...")
            time.sleep(30)

def convert_to_geojson(osm_data):
    features = []
    elements = osm_data.get('elements', [])
    print(f"Processing {len(elements)} spatial nodes and calculating physical footprints...")
    
    for el in elements:
        lon = el.get('lon') or el.get('center', {}).get('lon')
        lat = el.get('lat') or el.get('center', {}).get('lat')
        if not lon or not lat: continue
            
        tags = el.get('tags', {})
        name = tags.get('name', tags.get('name:en', 'Unnamed Port / Terminal'))
        
        # Strict logic for Deep Water, Containers, and Ro-Ro Ferries
        is_industrial = tags.get('industrial') == 'port'
        is_ferry_terminal = tags.get('amenity') == 'ferry_terminal'
        
        category = tags.get('seamark:harbour:category', '').lower()
        cargo_tags = ['cargo', 'container', 'industrial', 'ro-ro', 'commercial', 'military', 'ferry', 'passenger', 'cruise', 'deep_water']
        
        is_major = is_industrial or is_ferry_terminal or any(c in category for c in cargo_tags)
        port_class = 'Major Cargo/Container Port' if is_major else 'Minor/Local Harbour'
        
        area_ha = 1.0 
        bounds = el.get('bounds')
        
        if bounds:
            width_m = haversine_distance(lat, bounds['minlon'], lat, bounds['maxlon'])
            height_m = haversine_distance(bounds['minlat'], lon, bounds['maxlat'], lon)
            area_ha = (width_m * height_m) / 10000.0
        
        # If it's a major deep-water/ferry port but only mapped as a point, force a massive 80-hectare fallback
        if is_major and area_ha < 80.0:
            area_ha = 80.0
            
        feature = {
            "type": "Feature",
            "geometry": {"type": "Point", "coordinates": [lon, lat]},
            "properties": {
                "name": name,
                "type": port_class,
                "operator": tags.get('operator', 'Unknown'),
                "area_ha": round(area_ha, 1),
                "osm_id": el['id']
            }
        }
        features.append(feature)
        
    return {"type": "FeatureCollection", "features": features}

def save_geojson(geojson_data, filename="global_ports.geojson"):
    filepath = os.path.join(REPO_ROOT, filename)
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(geojson_data, f, separators=(',', ':'))
    print(f"SUCCESS: Wrote {len(geojson_data['features'])} ports to {filepath}")

if __name__ == "__main__":
    raw_data = fetch_ports()
    if raw_data:
        geojson = convert_to_geojson(raw_data)
        save_geojson(geojson)

Fetch Grid Data v6

A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches grid 400kV, grid 275kV and grid 132kV from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_grid_datav6.py · lines 1–79 of 79 · Entry point

What it does
It fetches grid 400kV, grid 275kV and grid 132kV. Defines fetch_and_convert. Uses libraries requests, json, os, 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. Domain terms in the code: 400kV, 275kV, 132kV.
Inputs & outputs
In: data source: OpenStreetMap (Overpass); GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_132kv.geojson. Out: JSON file. Voltage levels named: 400kV, 275kV, 132kV.
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 grid data. Defines `fetch_and_convert`. Its code works with 132 kV, 275 kV and 400 kV.
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, os, time
Used by
none found
Produces
fetch_and_convert
Defines here
fetch_and_convert
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_grid_datav6.py:1-79 · blob 4daf53221d6246e692ea106ca08f49c8eaea89e2 · 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 os
import time

def fetch_and_convert(voltage, filename, timeout_secs=300):
    print(f"\n--- Fetching {voltage}V data ---")
    
    query = f"""
    [out:json][timeout:{timeout_secs}];
    area(3600062149)->.uk;
    (
      way["power"="line"]["voltage"~"{voltage}"](area.uk);
      way["power"="cable"]["voltage"~"{voltage}"](area.uk);
    );
    out geom;
    """
    
    url = "https://overpass-api.de/api/interpreter"
    
    max_retries = 3
    for attempt in range(max_retries):
        print(f"Attempt {attempt + 1} of {max_retries}...")
        response = requests.post(url, data={'data': query})
        
        if response.status_code == 429:
            print("⚠️ Overpass server is busy (Status 429: Too Many Requests).")
            print("😴 Sleeping for 3 minutes before retrying...")
            time.sleep(180)  # 3 minute nap
            continue
        elif response.status_code != 200:
            print(f"❌ Error (Status {response.status_code}):\n", response.text[:500])
            return
        else:
            print("✅ Data successfully downloaded from server!")
            break  # Success! Break out of the retry loop.
            
    if response.status_code != 200:
        print(f"❌ Giving up on {voltage}V after {max_retries} attempts.")
        return

    try:
        osm_data = response.json()
    except ValueError:
        print(f"❌ Failed to parse JSON for {voltage}V. Server returned:\n", response.text[:500])
        return

    geojson = {"type": "FeatureCollection", "features": []}
    
    for element in osm_data.get('elements', []):
        if element['type'] == 'way' and 'geometry' in element:
            coords = [[node['lon'], node['lat']] for node in element['geometry']]
            feature = {
                "type": "Feature",
                "properties": element.get('tags', {}),
                "geometry": {"type": "LineString", "coordinates": coords}
            }
            geojson['features'].append(feature)
            
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(geojson, f)
        
    print(f"💾 Saved {len(geojson['features'])} power lines to {filename}")

if __name__ == "__main__":
    # 400kV fetch
    fetch_and_convert("400000", "grid_400kv.geojson", 300)
    
    print("⏳ Pausing for 60 seconds...")
    time.sleep(60)
    
    # 275kV fetch
    fetch_and_convert("275000", "grid_275kv.geojson", 300)
    
    print("⏳ Pausing for another 60 seconds...")
    time.sleep(60)
    
    # ⚡ 132kV fetch (15 minute timeout)
    fetch_and_convert("132000", "grid_132kv.geojson", 900)

Fetch Hs2v6

A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_hs2v6.py · lines 1–69 of 69 · Entry point

What it does
It fetches data. Defines fetch_hs2. 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 hs2.geojson; JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Defines `fetch_hs2`. It writes `hs2.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_hs2
Defines here
fetch_hs2
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_hs2v6.py:1-69 · blob 7d593dbfb1f53da3adb07a3f90f717d96414fc89 · 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_hs2():
    print("🚀 Fetching UK HS2 Infrastructure from OpenStreetMap...")
    
    query = """
    [out:json][timeout:180];
    area(3600062149)->.uk;
    (
      node["name"~"HS2"]["railway"](area.uk);
      way["name"~"HS2"]["railway"](area.uk);
      relation["name"~"HS2"]["railway"](area.uk);
      
      node["network"="HS2"](area.uk);
      way["network"="HS2"](area.uk);
      relation["network"="HS2"](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:
            feature = {
                "type": "Feature",
                "properties": {
                    "name": tags.get('name', 'HS2 Infrastructure')
                },
                "geometry": {"type": "Point", "coordinates": [lon, lat]}
            }
            geojson['features'].append(feature)

    with open("hs2.geojson", 'w', encoding='utf-8') as f:
        json.dump(geojson, f)
        
    print(f"🎉 Successfully saved HS2 sites!")

if __name__ == "__main__":
    fetch_hs2()

Fetch Industrial Offtakers v6

A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_industrial_offtakersv6.py · lines 1–141 of 141 · Entry point

What it does
It fetches data. Defines fetch_overpass_data, process_osm_data, fetch_heavy_industry. 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 industrial_offtakers.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 industrial offtakers. Defines `fetch_overpass_data`, `process_osm_data` and `fetch_heavy_industry`. It writes `industrial_offtakers.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_overpass_data, process_osm_data, fetch_heavy_industry
Defines here
fetch_overpass_data, process_osm_data, fetch_heavy_industry
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_industrial_offtakersv6.py:1-141 · blob 64162fd78a6868d235ef5ee3a0edc6136afc67f8 · 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

OVERPASS_URL = "https://overpass-api.de/api/interpreter"

HEAVY_OPERATORS = [
    "tata",
    "british steel",
    "cemex",
    "heidelberg",
    "tarmac",
    "aggregate industries",
    "ineos",
    "shell",
    "bp",
    "total",
    "phillips 66",
    "sabic",
    "dow"
]

def fetch_overpass_data(query, name):
    for attempt in range(3):
        try:
            print(f"  -> Requesting {name} (attempt {attempt + 1})...")
            response = requests.post(
                OVERPASS_URL,
                data={"data": query},
                timeout=120
            )

            if response.status_code == 200:
                print(f"  ✅ {name} downloaded!")
                return response.json()

            if response.status_code == 429:
                print("  ⚠️ Server busy, sleeping 60s...")
                time.sleep(60)
                continue

            print(f"  ⚠️ Error for {name}: {response.status_code}, retrying...")
            time.sleep(10)

        except Exception as e:
            print(f"  ⚠️ Connection error for {name}: {e}, retrying...")
            time.sleep(10)

    print(f"  ❌ Failed to fetch {name}")
    return None

def process_osm_data(osm_data, geojson_features, seen):
    if not osm_data:
        return

    for element in osm_data.get("elements", []):
        tags = element.get("tags", {})

        if "center" not in element:
            continue

        lat = element["center"].get("lat")
        lon = element["center"].get("lon")

        if lat is None or lon is None:
            continue

        name = tags.get("name", "").strip()
        operator = (tags.get("operator", "") or tags.get("brand", "")).strip()

        if not name:
            continue

        searchable_text = f"{name} {operator}".lower()
        if not any(op in searchable_text for op in HEAVY_OPERATORS):
            continue

        key = (round(lat, 4), round(lon, 4), name.lower())
        if key in seen:
            continue
        seen.add(key)

        ind_type = (
            tags.get("industrial")
            or tags.get("man_made")
            or tags.get("landuse")
            or tags.get("power")
            or "Industrial Site"
        ).replace("_", " ").title()

        feature = {
            "type": "Feature",
            "properties": {
                "name": name,
                "operator": operator if operator else "Unknown",
                "type": ind_type
            },
            "geometry": {
                "type": "Point",
                "coordinates": [lon, lat]
            }
        }

        geojson_features.append(feature)

def fetch_heavy_industry():
    print("🚀 Fetching UK heavy industry sites...")

    geojson = {
        "type": "FeatureCollection",
        "features": []
    }

    seen = set()

    query_heavy_industry = """
    [out:json][timeout:180];
    area(3600062149)->.uk;
    (
      way["industrial"~"steel|cement|chemical|oil|refinery|glass"](area.uk);
      relation["industrial"~"steel|cement|chemical|oil|refinery|glass"](area.uk);

      way["man_made"="works"]["product"~"steel|cement|chemical"](area.uk);
      relation["man_made"="works"]["product"~"steel|cement|chemical"](area.uk);

      way["power"="plant"]["plant:source"~"gas|coal|oil"](area.uk);
      relation["power"="plant"]["plant:source"~"gas|coal|oil"](area.uk);
    );
    out center;
    """

    data = fetch_overpass_data(query_heavy_industry, "Heavy Industry")
    process_osm_data(data, geojson["features"], seen)

    with open("industrial_offtakers.geojson", "w", encoding="utf-8") as f:
        json.dump(geojson, f, ensure_ascii=False, indent=2)

    print(f"🎉 Successfully saved {len(geojson['features'])} sites to industrial_offtakers.geojson!")

if __name__ == "__main__":
    fetch_heavy_industry()

Fetch London Underground v6

A Python module in the scripts folder of GlobalGrid2050 that uses ISO3166-1 using data from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_london_undergroundv6.py · lines 1–58 of 58 · Not reached from any entry point (candidate for review)

What it does
It fetches data. 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 london_underground.geojson. Out: JSON file.
What it achieves
Overpass query to find London Underground stations.
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_london_undergroundv6.py:1-58 · blob 761d4dbd1a95af462ab0934a62784d30bee8c2c7 · 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 London Underground stations
query = """
[out:json][timeout:90];
area["ISO3166-1"="GB"]->.uk;
(
  node["railway"="station"]["network"~"London Underground"](area.uk);
  way["railway"="station"]["network"~"London Underground"](area.uk);
  rel["railway"="station"]["network"~"London Underground"](area.uk);
);
out center;
"""

url = "https://overpass-api.de/api/interpreter"
print("Fetching London Underground stations 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', []):
        # Extract coordinates (handles nodes, ways, and relations)
        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')
            
            feature = {
                "type": "Feature",
                "properties": {
                    "name": name,
                    "type": "Tube Station",
                    "operator": "Transport for London"
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [lon, lat]
                }
            }
            features.append(feature)

    geojson = {
        "type": "FeatureCollection",
        "features": features
    }

    output_path = "london_underground.geojson"
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(geojson, f, indent=2)

    print(f"Successfully saved {len(features)} London Underground stations to {output_path}")
else:
    print(f"Error fetching data: {response.status_code}")