GLOBALGRID2050 / EXPLORE CODE

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

Renewable Energy Planning Database (REPD) Updater v6 and 3 more files

A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches REPD master, the REPD register, solar and wind.

655 lines of Python from globalgrid2050, in 4 files. Topic: Maps, GIS and field navigation. Section 497 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. Generate Deep Subsea v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/generate_deep_subseav6.py lines 1–81
  2. Generate Unification Estimates v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/generate_unification_estimatesv6.py lines 1–44
  3. Renewable Energy Planning Database (REPD) Updater v6 energy-data · globalgrid2050 / repd_grid_atlasv6/scripts/repd_updaterv6.py lines 1–318
  4. Update Metal Trends v6 interaction · globalgrid2050 / repd_grid_atlasv6/scripts/update_metal_trendsv6.py lines 1–212

Generate Deep Subsea v6

A Python command-line tool in the scripts folder of GlobalGrid2050 that reads deep subsea illustrative.

storageglobalgrid2050 / repd_grid_atlasv6/scripts/generate_deep_subseav6.py · lines 1–81 of 81 · Entry point

What it does
It loads deep subsea illustrative. Defines generate_deep_subsea_routes. Uses libraries json. Side effects: reads or writes files.
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
Out: 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 generates deep subsea. Defines `generate_deep_subsea_routes`. It writes `deep_subsea_illustrative.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
json
Used by
none found
Produces
generate_deep_subsea_routes
Defines here
generate_deep_subsea_routes
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/generate_deep_subseav6.py:1-81 · blob 37aff478f99e82d888a46dc29d2f7878ff85ca9a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import json

def generate_deep_subsea_routes():
    # Multi-point waypoints for deep ocean crossings
    # Coordinates are [Longitude, Latitude]
    corridors = [
        {
            "name": "Trans-Pacific Deep Subsea (Illustrative)",
            "operator": "Strategic Corridor",
            "waypoints": [
                [151.20, -33.86],  # Sydney, Australia
                [174.76, -36.84],  # Auckland, NZ
                [-157.85, 21.30],  # Honolulu, Hawaii
                [-118.24, 34.05]   # Los Angeles, US
            ]
        },
        {
            "name": "Oceania-Asia Deep Subsea (Illustrative)",
            "operator": "Strategic Corridor",
            "waypoints": [
                [115.86, -31.95],  # Perth, Australia
                [106.84, -6.20],   # Jakarta, Indonesia
                [103.81, 1.35],    # Singapore
                [114.16, 22.28]    # Hong Kong
            ]
        },
        {
            "name": "Africa-Europe-Asia Deep Subsea (Illustrative)",
            "operator": "Strategic Corridor",
            "waypoints": [
                [5.36, 43.29],     # Marseille, France
                [32.30, 31.20],    # Port Said, Egypt
                [39.19, 21.48],    # Jeddah, Saudi Arabia
                [43.33, 11.58],    # Djibouti
                [39.66, -4.04],    # Mombasa, Kenya
                [32.58, -25.96],   # Maputo, Mozambique
                [18.42, -33.92],   # Cape Town, South Africa
                [13.23, -8.83],    # Luanda, Angola
                [3.37, 6.52],      # Lagos, Nigeria
                [-17.46, 14.71],   # Dakar, Senegal
                [-9.13, 38.72]     # Lisbon, Portugal
            ]
        },
        {
            "name": "South Atlantic Deep Subsea (Illustrative)",
            "operator": "Strategic Corridor",
            "waypoints": [
                [13.23, -8.83],    # Luanda, Angola
                [-38.52, -3.73],   # Fortaleza, Brazil
                [-80.19, 25.76]    # Miami, US
            ]
        }
    ]

    features = []
    for route in corridors:
        features.append({
            "type": "Feature",
            "properties": {
                "name": route["name"],
                "operator": route["operator"],
                "type": "deep_subsea_illustrative",
                "source": "Ventus Deep Subsea (Illustrative)"
            },
            "geometry": {
                "type": "LineString",
                "coordinates": route["waypoints"]
            }
        })

    geojson = {"type": "FeatureCollection", "features": features}
    
    # Save with the new naming convention
    with open("deep_subsea_illustrative.geojson", "w", encoding="utf-8") as f:
        json.dump(geojson, f, ensure_ascii=False, indent=2)
        
    print(f"Successfully generated {len(corridors)} routes to deep_subsea_illustrative.geojson")

if __name__ == "__main__":
    print("Initiating standalone Deep Subsea Illustrative generation...")
    generate_deep_subsea_routes()

Generate Unification Estimates v6

A Python command-line tool in the scripts folder of GlobalGrid2050 that reads unification deep subsea estimates.

storageglobalgrid2050 / repd_grid_atlasv6/scripts/generate_unification_estimatesv6.py · lines 1–44 of 44 · Entry point

What it does
It loads unification deep subsea estimates. Defines generate_unification_routes. Uses libraries json. Side effects: reads or writes files.
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
Out: 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 generates unification estimates. Defines `generate_unification_routes`. It writes `unification_deep_subsea_estimates.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
json
Used by
none found
Produces
generate_unification_routes
Defines here
generate_unification_routes
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/generate_unification_estimatesv6.py:1-44 · blob a2538611a3ba6b7cdfa285d0cce66c259d98d833 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import json

def generate_unification_routes():
    # The 12 massive global macro-corridors
    corridors = [
        {"name": "Trans-Atlantic North (US-UK/EU)", "waypoints": [[-74.00, 40.71], [-5.54, 50.11]]},
        {"name": "Trans-Atlantic South (US-EU)", "waypoints": [[-75.97, 36.85], [-3.01, 43.36]]},
        {"name": "Trans-Pacific North (US-Japan)", "waypoints": [[-123.98, 45.92], [-165.00, 45.00], [140.40, 36.30]]},
        {"name": "Trans-Pacific South (US-Oceania)", "waypoints": [[-118.24, 34.05], [-157.85, 21.30], [144.75, 13.44], [151.20, -33.86], [174.76, -36.84]]},
        {"name": "Intra-Asia Backbone", "waypoints": [[140.40, 36.30], [121.56, 25.03], [114.16, 22.28], [103.81, 1.35]]},
        {"name": "Europe-Middle East-India-Asia", "waypoints": [[5.36, 43.29], [32.30, 31.20], [32.55, 29.96], [39.19, 21.48], [43.33, 11.58], [58.38, 23.58], [72.82, 18.97], [80.27, 13.08], [103.81, 1.35]]},
        {"name": "Africa West Coast Ring", "waypoints": [[-9.13, 38.72], [-17.46, 14.71], [3.37, 6.52], [13.23, -8.83], [18.42, -33.92]]},
        {"name": "Africa East Coast Ring", "waypoints": [[18.42, -33.92], [32.58, -25.96], [39.66, -4.04], [43.33, 11.58]]},
        {"name": "South America East Coast", "waypoints": [[-80.19, 25.76], [-38.52, -3.73], [-43.17, -22.90], [-56.71, -36.53]]},
        {"name": "South America West Coast", "waypoints": [[-118.24, 34.05], [-79.51, 8.98], [-77.04, -12.04], [-71.61, -33.04]]},
        {"name": "South Atlantic Crossing", "waypoints": [[-38.52, -3.73], [-8.86, 37.95]]},
        {"name": "Indian Ocean Crossing", "waypoints": [[115.86, -31.95], [106.84, -6.20], [103.81, 1.35]]}
    ]

    features = []
    for route in corridors:
        features.append({
            "type": "Feature",
            "properties": {
                "name": route["name"],
                "operator": "Unification Estimates",
                "type": "unification_estimates",
                "source": "Ventus Strategic Unification"
            },
            "geometry": {
                "type": "LineString",
                "coordinates": route["waypoints"]
            }
        })

    geojson = {"type": "FeatureCollection", "features": features}
    
    with open("unification_deep_subsea_estimates.geojson", "w", encoding="utf-8") as f:
        json.dump(geojson, f, ensure_ascii=False, indent=2)
        
    print(f"Successfully generated {len(corridors)} routes to unification_deep_subsea_estimates.geojson")

if __name__ == "__main__":
    generate_unification_routes()

Renewable Energy Planning Database (REPD) Updater v6

A Python command-line tool in the scripts folder of GlobalGrid2050 that fetches REPD master, the REPD register, solar and wind.

energy-dataglobalgrid2050 / repd_grid_atlasv6/scripts/repd_updaterv6.py · lines 1–318 of 318 · Entry point · pattern discover_latest_url (shared by 2 files)

What it does
It fetches REPD master, the REPD register, solar and wind. Defines 9 functions or classes, including REPDUpdater, __init__, validate_schema, discover_latest_url, already_current. Uses libraries pandas, json, yaml, os, requests. 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: the REPD register, solar, wind.
Inputs & outputs
In: JSON file manifest_v4.json; CSV file latest_repd.csv; JSON file repd_master.json. Out: JSON file manifest_v4.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It classifies tech (`classify_tech`) and is built from the REPD updater class (`REPDUpdater`) and the already current helper (`already_current`). Defines `REPDUpdater`, `validate_schema`, `discover_latest_url` and 5 more.
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
pandas, json, yaml, os, requests, datetime, math, pyproj
Used by
none found
Produces
REPDUpdater
Defines here
REPDUpdater, __init__, validate_schema, discover_latest_url, already_current, fetch_data, classify_tech, refine_dataset, execute
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/repd_updaterv6.py:1-318 · blob eddb7af0316cd9b7dfbe2569e5574a26822796cd · 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 pandas as pd
import json
import yaml
import os
import requests
from datetime import datetime
from math import isfinite
from pyproj import Transformer
from bs4 import BeautifulSoup

class REPDUpdater:
    """
    VENTUS REPD UPDATER v5.10 | MASTER UNIFIED GEOJSON
    Fixed: substring matching for all tech types — no encoding collisions.
    """

    REPD_PAGE = "https://www.gov.uk/government/publications/renewable-energy-planning-database-monthly-extract"

    UK_LON_MIN, UK_LON_MAX = -9.0,  2.5
    UK_LAT_MIN, UK_LAT_MAX = 49.0, 61.0

    VIABLE_STATUSES = {
        'operational',
        'under construction',
        'awaiting construction',
        'consented',
        'planning permission granted',
        'planning approved',
        'application submitted',
        'pre-construction'
    }

    REQUIRED_COLUMNS = [
        'Site Name',
        'Technology Type',
        'Development Status (short)',
        'Installed Capacity (MWelec)',
        'X-coordinate',
        'Y-coordinate',
        'Operator (or Applicant)'
    ]

    OPTIONAL_COLUMNS = [
        'Mounting Type for Solar'
    ]

    def __init__(self, registry_path="config/registry.yaml"):
        print("📡 VENTUS REPD UPDATER v5.10 | BOOTING SYSTEM...")
        try:
            with open(registry_path, 'r') as f:
                self.config = yaml.safe_load(f)
        except FileNotFoundError:
            print(f"❌ ERROR: {registry_path} not found.")
            exit(1)
        self.output_dir   = "dist"
        self.raw_data_dir = "data"
        os.makedirs(self.output_dir,   exist_ok=True)
        os.makedirs(self.raw_data_dir, exist_ok=True)
        self.transformer = Transformer.from_crs("epsg:27700", "epsg:4326", always_xy=True)

    def validate_schema(self, df):
        cols = set(df.columns)
        missing_required = [c for c in self.REQUIRED_COLUMNS if c not in cols]
        missing_optional = [c for c in self.OPTIONAL_COLUMNS if c not in cols]
        if missing_required:
            print(f"❌ SCHEMA ERROR — missing required columns: {missing_required}")
            print(f"   Available columns: {sorted(cols)}")
            exit(1)
        if missing_optional:
            print(f"⚠️  Missing optional columns (degraded output): {missing_optional}")
        else:
            print(f"✅ Schema valid — all required and optional columns present")

    def discover_latest_url(self):
        print("🔍 Discovering latest REPD URL from Gov.uk...")
        try:
            r = requests.get(self.REPD_PAGE, timeout=30)
            r.raise_for_status()
            soup = BeautifulSoup(r.text, 'html.parser')
            for a in soup.find_all('a', href=True):
                href = a['href']
                if href.endswith('.csv') and 'repd' in href.lower():
                    url = href if href.startswith('http') else f"https://www.gov.uk{href}"
                    print(f"✅ Latest REPD URL: {url}")
                    return url
            print("⚠️ Could not find CSV link — falling back to registry URL")
            return None
        except Exception as e:
            print(f"⚠️ Discovery failed: {e} — falling back to registry URL")
            return None

    def already_current(self, url):
        manifest_path = f"{self.output_dir}/manifest_v4.json"
        if not os.path.exists(manifest_path):
            return False
        try:
            with open(manifest_path) as f:
                manifest = json.load(f)
            if manifest.get('source_url') == url:
                print("✅ REPD unchanged since last sync — skipping pipeline.")
                return True
        except Exception:
            pass
        return False

    def fetch_data(self, url):
        print(f"📥 FETCHING: {url}")
        try:
            r = requests.get(url, timeout=60)
            r.raise_for_status()
            path = f"{self.raw_data_dir}/latest_repd.csv"
            with open(path, 'wb') as f:
                f.write(r.content)
            return path
        except Exception as e:
            print(f"⚠️ FETCH FAILED: {e}")
            return None

    def classify_tech(self, tech_raw, mounting):
        """
        Substring matching throughout — immune to encoding artifacts.
        Hydrogen checked before hydro — no collision possible.
        """
        t  = tech_raw.strip()
        tl = t.lower()

        # --- Solar — mounting drives rooftop split ---
        if 'solar photovoltaic' in tl or 'solar pv' in tl:
            return 'solar_roof' if mounting == 'roof' else 'solar'

        # --- Wind ---
        if 'wind onshore' in tl or 'wind offshore' in tl or tl == 'wind':
            return 'wind'

        # --- Hydrogen — MUST be before hydro ---
        if tl == 'hydrogen' or 'fuel cell (hydrogen)' in tl:
            return 'hydrogen'

        # --- Hydro ---
        if 'large hydro' in tl or 'small hydro' in tl or 'pumped storage hydro' in tl:
            return 'hydro'

        # --- Compressed / Liquid Air Energy Storage ---
        if 'compressed air energy storage' in tl or 'liquid air energy storage' in tl:
            return 'caes'

        # --- Battery ---
        if tl == 'battery' or tl == 'battery storage':
            return 'bess'

        # --- Biomass family ---
        if any(x in tl for x in [
            'biomass', 'efw incineration', 'anaerobic digestion',
            'landfill gas', 'sewage sludge', 'co-firing',
            'energy from waste', 'incineration'
        ]):
            return 'biomass'

        # --- Advanced Conversion Technologies ---
        if 'advanced conversion' in tl or 'gasification' in tl or 'pyrolysis' in tl:
            return 'act'

        # --- Geothermal ---
        if 'geothermal' in tl or 'hot dry rocks' in tl:
            return 'geothermal'

        # --- Tidal / Wave ---
        if 'tidal' in tl or 'shoreline wave' in tl:
            return 'tidal'

        # --- Flywheel ---
        if 'flywheel' in tl:
            return 'flywheel'

        # --- Generic storage fallback ---
        if 'storage' in tl or 'battery' in tl:
            return 'bess'

        # --- Generic wind fallback ---
        if 'wind' in tl:
            return 'wind'

        return 'other'

    def refine_dataset(self, csv_path):
        print("🧪 REFINING MASTER DATASET...")
        df = pd.read_csv(csv_path, encoding='unicode_escape', on_bad_lines='skip', engine='python')
        df.columns = [c.strip() for c in df.columns]

        self.validate_schema(df)

        if 'Mounting Type for Solar' in df.columns:
            mounting_col = 'Mounting Type for Solar'
        elif 'Mounting Type' in df.columns:
            mounting_col = 'Mounting Type'
        else:
            mounting_col = None
            print("⚠️ No mounting type column found — all solar mapped to 'solar'")

        print(f"🔍 Mounting column: '{mounting_col}'")
        if mounting_col:
            print(f"🔍 Mounting values: {df[mounting_col].dropna().unique()}")
        print(f"🔍 Tech Types (all): {sorted(df['Technology Type'].dropna().unique())}")

        df['Development Status (short)'] = (
            df['Development Status (short)']
            .astype(str).str.strip().str.lower()
        )
        df = df[df['Development Status (short)'].isin(self.VIABLE_STATUSES)]
        print(f"🔍 Rows after status filter: {len(df)}")

        features = []
        skipped  = 0

        for _, row in df.iterrows():
            try:
                e = float(row['X-coordinate'])
                n = float(row['Y-coordinate'])
                if not e or not n or e == 0 or n == 0:
                    skipped += 1
                    continue

                lon, lat = self.transformer.transform(e, n)
                if not (isfinite(lon) and isfinite(lat)):
                    skipped += 1
                    continue

                if not (self.UK_LON_MIN < lon < self.UK_LON_MAX and
                        self.UK_LAT_MIN < lat < self.UK_LAT_MAX):
                    skipped += 1
                    continue

                tech_raw = str(row.get('Technology Type', '')).strip()
                mounting = ''
                if mounting_col:
                    mounting = str(row.get(mounting_col, '')).strip().lower()

                tech_map = self.classify_tech(tech_raw, mounting)

                try:
                    capacity = float(row.get('Installed Capacity (MWelec)', 0))
                    if not isfinite(capacity):
                        capacity = 0.0
                    if tech_map == 'solar_roof' and capacity > 50:
                        capacity = round(capacity / 1000, 4)
                    if tech_map == 'biomass' and capacity > 100:
                        capacity = round(capacity / 1000, 4)
                except (ValueError, TypeError):
                    capacity = 0.0

                features.append({
                    "type": "Feature",
                    "properties": {
                        "name":     str(row.get('Site Name', 'Unknown')),
                        "operator": str(row.get('Operator (or Applicant)', 'Unknown')).upper(),
                        "capacity": capacity,
                        "status":   str(row.get('Development Status (short)', '')).strip(),
                        "tech":     tech_map,
                        "raw_tech": tech_raw,
                        "mounting": mounting
                    },
                    "geometry": {
                        "type": "Point",
                        "coordinates": [round(lon, 6), round(lat, 6)]
                    }
                })

            except (ValueError, TypeError):
                skipped += 1
                continue

        print(f"⚠️  Skipped: {skipped}")
        tech_counts = {}
        for f in features:
            t = f['properties']['tech']
            tech_counts[t] = tech_counts.get(t, 0) + 1
        print(f"📊 Tech distribution: {tech_counts}")

        other_count = tech_counts.get('other', 0)
        if other_count > 0:
            other_techs = set(
                f['properties']['raw_tech'] for f in features
                if f['properties']['tech'] == 'other'
            )
            print(f"⚠️  {other_count} unmapped — raw tech values: {other_techs}")

        return {"type": "FeatureCollection", "features": features}

    def execute(self):
        for layer in self.config['layers']:
            if layer['id'] == 'repd' or layer['type'] == 'csv':

                url = self.discover_latest_url() or layer['url']

                if self.already_current(url):
                    return

                local_csv = self.fetch_data(url)
                if not local_csv:
                    return

                geojson = self.refine_dataset(local_csv)
                output = f"{self.output_dir}/repd_master.json"
                with open(output, 'w') as f:
                    json.dump(geojson, f)
                print(f"✅ MASTER SYNC: {len(geojson['features'])} assets.")

                manifest = {
                    "system":     "VENTUS_CORE",
                    "last_sync":  datetime.now().isoformat(),
                    "source_url": url,
                    "status":     "OPERATIONAL"
                }
                with open(f"{self.output_dir}/manifest_v4.json", 'w') as f:
                    json.dump(manifest, f, indent=2)

if __name__ == "__main__":
    REPDUpdater().execute()

Update Metal Trends v6

A Python command-line tool in the scripts folder of GlobalGrid2050 using data from open.er-api.com and query1.finance.yahoo.com. It gets market (`get_market_data`).

interactionglobalgrid2050 / repd_grid_atlasv6/scripts/update_metal_trendsv6.py · lines 1–212 of 212 · Entry point · pattern get_market_data (shared by 3 files)

What it does
It fetches data. Defines get_market_data, main. Uses libraries requests, os, pathlib, datetime. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'metal'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: data source: open.er-api.com; data source: query1.finance.yahoo.com.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
From `/scripts/` up to Root, targeting the file directly.
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, os, pathlib, datetime
Used by
none found
Produces
get_market_data, main
Defines here
get_market_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/update_metal_trendsv6.py:1-212 · blob 4c431f16232ea335e7e96dee26952782101fdea2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: hv_procurement · users: IPP_developer, EPC_contractor, procurement_buyer · canonical: production_core
import requests
import os
from pathlib import Path
from datetime import datetime, timezone

# From /scripts/ up to Root, targeting the file directly
FILE = Path(__file__).parent.parent / "copper_and_aluminium_prices_historic_trends.md"

def get_market_data():
    data = {
        "gbp_usd": 1.3339,
        "gbp_eur": 1.1510,
        "cu_usd": 12850.0,
        "al_usd": 3520.0,
        "used_fallback": False
    }

    # Fetch FX Rates
    try:
        fx = requests.get("https://open.er-api.com/v6/latest/GBP", timeout=15).json()
        data["gbp_usd"] = fx["rates"]["USD"]
        data["gbp_eur"] = fx["rates"]["EUR"]
    except Exception as e:
        print(f"::warning::FX fetch failed, using fallback rates: {e}")
        data["used_fallback"] = True

    # Fetch Copper (HG=F is per pound, multiply by 2204.62 for tonne)
    try:
        r = requests.get(
            "https://query1.finance.yahoo.com/v8/finance/chart/HG=F",
            timeout=10,
            headers={"User-Agent": "Mozilla/5.0"}
        )
        cu_lb = r.json()["chart"]["result"][0]["meta"]["regularMarketPrice"]
        data["cu_usd"] = cu_lb * 2204.62
    except Exception as e:
        print(f"::warning::Copper fetch failed, using fallback: {e}")
        data["used_fallback"] = True

    # Fetch Aluminium (ALI=F is per tonne)
    try:
        r = requests.get(
            "https://query1.finance.yahoo.com/v8/finance/chart/ALI=F",
            timeout=10,
            headers={"User-Agent": "Mozilla/5.0"}
        )
        data["al_usd"] = r.json()["chart"]["result"][0]["meta"]["regularMarketPrice"]
    except Exception as e:
        print(f"::warning::Aluminium fetch failed, using fallback: {e}")
        data["used_fallback"] = True

    return data


def main():
    d = get_market_data()
    ts_obj = datetime.now(timezone.utc)
    ts = ts_obj.strftime("%A %d %B %Y %H:%M UTC")

    if d["used_fallback"]:
        print("::warning::One or more prices are fallback values - verify API sources")

    # Calculate Currency Conversions
    usd_to_gbp = 1 / d["gbp_usd"]
    usd_to_eur = d["gbp_eur"] / d["gbp_usd"]

    cu_gbp = d["cu_usd"] * usd_to_gbp
    cu_eur = d["cu_usd"] * usd_to_eur

    al_gbp = d["al_usd"] * usd_to_gbp
    al_eur = d["al_usd"] * usd_to_eur

    # ---------------------------------------------------------
    # PART 1: The Static Top Section (Includes Plotly JS)
    # ---------------------------------------------------------
    PART_1 = """---
layout: page
title: Copper and Aluminium Historic Prices & Trends
permalink: /copper_and_aluminium_prices_historic_trends/
---

# Copper and Aluminium Historic Prices in Euro and USD per tonne and Trend Graphs

### Indicative annual price ranges in EUR per tonne (1000 kg)  
### For commercial budgeting, trend analysis and metal risk awareness

---

## Historic Price Trends (Interactive)

<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>

<div id="chartUSD" style="width: 100%; height: 450px; background-color: #1a1a1a; border-radius: 8px; margin-bottom: 30px; border: 1px solid #333;"></div>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const years = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025];

    const cuAvg = [2200, 2100, 2000, 2200, 3100, 3900, 6600, 6000, 5500, 6000, 6000, 7500, 6800, 6000, 5700, 5500, 4700, 5700, 6400, 6300, 6000, 9000, 9200, 8500, 9600, 11500];
    const cuLow = [1900, 1800, 1700, 1800, 2200, 2800, 3900, 5000, 3300, 4400, 5000, 6500, 6000, 5500, 5300, 5000, 4200, 5000, 5500, 5700, 4900, 7100, 7600, 7800, 8200, 9600];
    const cuHigh = [2800, 2500, 2400, 2800, 4200, 5500, 9900, 8300, 8800, 7100, 8300, 10500, 8800, 8100, 7600, 6600, 5500, 6800, 7800, 7100, 7600, 10600, 11400, 9600, 11100, 13200];
    
    const alAvg = [1700, 1400, 1300, 1400, 1700, 1900, 2400, 2500, 2000, 1500, 1800, 2100, 1800, 1500, 1500, 1700, 1500, 1900, 2000, 1700, 1700, 2300, 2800, 2300, 2400, 2900];
    const alLow = [1400, 1300, 1200, 1200, 1300, 1600, 2000, 2200, 1400, 1300, 1600, 2000, 1700, 1400, 1400, 1500, 1400, 1800, 1900, 1600, 1400, 2100, 2400, 2100, 2200, 2500];
    const alHigh = [2000, 1800, 1700, 1800, 2100, 2400, 3000, 3100, 3300, 2000, 2600, 3100, 2300, 2100, 2100, 2000, 1900, 2200, 2400, 2100, 2000, 3100, 4100, 2600, 2900, 3700];

    const traces = [
      { x: years, y: cuHigh, type: 'scatter', mode: 'lines', line: {width: 0}, hoverinfo: 'skip', showlegend: false },
      { x: years, y: cuLow, type: 'scatter', mode: 'lines', fill: 'tonexty', fillcolor: 'rgba(255, 0, 127, 0.15)', line: {width: 0}, name: 'Copper Range' },
      { x: years, y: cuAvg, type: 'scatter', mode: 'lines+markers', line: {color: '#FF007F', width: 2.5}, marker: {size: 6}, name: 'Copper Avg' },
      
      { x: years, y: alHigh, type: 'scatter', mode: 'lines', line: {width: 0}, hoverinfo: 'skip', showlegend: false },
      { x: years, y: alLow, type: 'scatter', mode: 'lines', fill: 'tonexty', fillcolor: 'rgba(0, 255, 255, 0.15)', line: {width: 0}, name: 'Aluminium Range' },
      { x: years, y: alAvg, type: 'scatter', mode: 'lines+markers', line: {color: '#00FFFF', width: 2.5}, marker: {size: 6}, name: 'Aluminium Avg' }
    ];

    const layout = {
      title: 'Historic Metal Prices (USD per tonne)',
      hovermode: 'x unified',
      paper_bgcolor: '#1a1a1a', 
      plot_bgcolor: '#121212',  
      font: { color: '#e0e0e0' }, 
      xaxis: { gridcolor: '#333', fixedrange: true }, 
      yaxis: { gridcolor: '#333', fixedrange: true },
      showlegend: true,
      legend: { x: 0.015, y: 0.98, xanchor: 'left', yanchor: 'top', bgcolor: 'rgba(26, 26, 26, 0.8)' }
    };

    Plotly.newPlot('chartUSD', traces, layout, { responsive: true, displayModeBar: false });
  });
</script>

---

## Market Context

2026 represents a historic high pricing regime for base metals, with copper exceeding €11,000 per tonne in sustained trading and reaching above €12,000 per tonne equivalent at peak levels, based on London Metal Exchange pricing.

Aluminium has also approached multi year highs, trading in the range of €2,600 to €3,000 per tonne with spikes above €3,000 during supply disruptions.

---

### Live LME Market Prices
For up-to-the-minute pricing, please refer to the official London Metal Exchange (LME) live data:
* **[Live LME Copper Prices](https://www.lme.com/metals/non-ferrous/lme-copper#Overview)**
* **[Live LME Aluminium Prices](https://www.lme.com/metals/non-ferrous/lme-aluminium#Overview)**

---
"""

    # ---------------------------------------------------------
    # PART 2: The Dynamic API Injection
    # ---------------------------------------------------------
    PART_2 = f"""
### Live Daily Market Prices (API Sync)
*Last Sync: {ts}*

| Metal | Live USD per tonne | Live EUR per tonne | Live GBP per tonne |
|:---|---:|---:|---:|
| **Copper** | ${d['cu_usd']:,.0f} | €{cu_eur:,.0f} | £{cu_gbp:,.0f} |
| **Aluminium** | ${d['al_usd']:,.0f} | €{al_eur:,.0f} | £{al_gbp:,.0f} |

---
"""

    # ---------------------------------------------------------
    # PART 3: The Static Historic Bottom Table
    # ---------------------------------------------------------
    PART_3 = """
## Historic Metal Prices with Risk Range (USD per tonne)

| Year | Cu Low | Cu Avg | Cu High | Al Low | Al Avg | Al High |
|:---|---:|---:|---:|---:|---:|---:|
| 2025 | 9,600 | 11,500 | 13,200 | 2,500 | 2,900 | 3,700 |
| 2024 | 8,200 | 9,600 | 11,100 | 2,200 | 2,400 | 2,900 |
| 2023 | 7,800 | 8,500 | 9,600 | 2,100 | 2,300 | 2,600 |
| 2022 | 7,600 | 9,200 | 11,400 | 2,400 | 2,800 | 4,100 |
| 2021 | 7,100 | 9,000 | 10,600 | 2,100 | 2,300 | 3,100 |
| 2020 | 4,900 | 6,000 | 7,600 | 1,400 | 1,700 | 2,000 |
| 2019 | 5,700 | 6,300 | 7,100 | 1,600 | 1,700 | 2,100 |
| 2018 | 5,500 | 6,400 | 7,800 | 1,900 | 2,000 | 2,400 |
| 2017 | 5,000 | 5,700 | 6,800 | 1,800 | 1,900 | 2,200 |
| 2016 | 4,200 | 4,700 | 5,500 | 1,400 | 1,500 | 1900 |
| 2015 | 5,000 | 5,500 | 6,600 | 1,500 | 1,700 | 2,000 |
| 2014 | 5,300 | 5,700 | 7,600 | 1,400 | 1,500 | 2,100 |
| 2013 | 5,500 | 6,000 | 8,100 | 1,400 | 1,500 | 2,100 |
| 2012 | 6,000 | 6,800 | 8,800 | 1,700 | 1,800 | 2,300 |
| 2011 | 6,500 | 7,500 | 10,500 | 2,000 | 2,100 | 3,100 |
| 2010 | 5,000 | 6,000 | 8,300 | 1,600 | 1,800 | 2,600 |
| 2009 | 4,400 | 6,000 | 7,100 | 1,300 | 1,500 | 2,000 |
| 2008 | 3,300 | 5,500 | 8,800 | 1,400 | 2,000 | 3,300 |
| 2007 | 5,000 | 6,000 | 8,300 | 2,200 | 2,500 | 3,100 |
| 2006 | 3,900 | 6,600 | 9,900 | 2,000 | 2,400 | 3,000 |
| 2005 | 2,800 | 3,900 | 5,500 | 1,600 | 1,900 | 2,400 |
| 2004 | 2,200 | 3,100 | 4,200 | 1,300 | 1,700 | 2,100 |
| 2003 | 1,800 | 2200 | 2,800 | 1,200 | 1,400 | 1,800 |
| 2002 | 1,700 | 2,000 | 2,400 | 1,200 | 1,300 | 1,700 |
| 2001 | 1,800 | 2,100 | 2,500 | 1,300 | 1,400 | 1,800 |
| 2000 | 1,900 | 2,200 | 2,800 | 1,400 | 1,700 | 2,000 |
"""

    # Assemble and write the file
    full_md = PART_1 + PART_2 + PART_3

    with open(FILE, "w", encoding="utf-8") as f:
        f.write(full_md)
        
    print(f"✅ Successfully updated Historic Copper/Aluminium Trends at: {FILE}")

if __name__ == "__main__":
    main()