In this section
- Reconcile Offshore Coordinates geodesy · gridatlas / tools/offshore/reconcile_offshore_coordinates.py lines 701–759
- Build storage · gridatlas / tools/offtakers/build.mjs lines 1–77
- Ot Filter geodesy · gridatlas / tools/offtakers/filter/ot_filter.py lines 1–564
Reconcile Offshore Coordinates
A Python command-line tool in the tools folder of GridAtlas that fetches Renewable Energy Planning Database (REPD) browser registry and crown estate wind sites, using EPSG:4326 and Helmert from postcodes.io.
geodesygridatlas / tools/offshore/reconcile_offshore_coordinates.py · lines 701–759 of 759 (continued from section 638) · Entry point · pattern load_registry (shared by 3 files)
- What it does
- It fetches REPD browser registry, crown estate wind sites, crown estate scotland wind sites and the REPD register. Defines 11 functions or classes, including point_on_surface, shoelace, osgb36_en_to_wgs84, haversine_km, fetch_layer. Uses libraries __future__, argparse, datetime, json, math. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): 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. README: "Offshore coordinates are reconciled by `tools/offshore/reconcile_offshore_coordinates.py`, run annually and on demand by `.github/workflows/offshore-coordinate-reconcile.yml`, writing `atlas/data/offshore-coordinates.json`."
- Inputs & outputs
- In: data source: postcodes.io; JSON file repd_browser_registry_202608290716.json; JSON file offshore-coordinates.json; GeoJSON file crown-estate-wind-sites.geojson; GeoJSON file crown-estate-scotland-wind-sites.geojson; command-line arguments. 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 fetches layer (`fetch_layer`) and loads registry (`load_registry`). Give every unlocated REPD row a coordinate, or say plainly why it has none. Its code works with 2907 MW, 1008 MW and 1000 MW. It accepts `--out`, `--offline` and `--check`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · tools/offshore · Python CLI
- Uses
- __future__, argparse, datetime, json, math, sys, urllib.request, pathlib
- Used by
- none found
- Produces
- point_on_surface, osgb36_en_to_wgs84, haversine_km, fetch_layer, repair, load_registry, unlocated, build, sanity, main
- Defines here
- main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/offshore/reconcile_offshore_coordinates.py:701-759 · blob 9f640176af0a3779d37f181562b481a9a30ce260 · 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
problems.append(f"{ref}: {lon},{lat} is outside the UK/CI envelope {GB_BOUNDS}")
if not entry.get("method") or not (entry.get("source_url") or entry.get("source_file")):
problems.append(f"{ref}: no method or no source")
if ref in seen:
problems.append(f"{ref}: duplicated")
seen.add(ref)
return problems
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out", default=str(DEFAULT_OUT))
parser.add_argument("--offline", action="store_true", help="use the cached lease layers only")
parser.add_argument("--check", action="store_true", help="run the checks, write nothing")
args = parser.parse_args()
report = build(args.offline)
print(f" registry {report['register']['rows']} rows, "
f"{report['register']['placeholder_rows']} carrying the placeholder")
print(f" RESOLVED {report['resolved']}")
print(f" unresolved {report['unresolved_count']}")
for entry in report["coordinates"]:
precision = f" ±{entry['precision_km']}km" if entry.get("precision_km") else ""
print(f" {entry['repd_ref']:<8}{entry['site_name'][:36]:<38}"
f"{entry['longitude']:>11.6f},{entry['latitude']:>10.6f} {entry['method']}{precision}")
for entry in report["unresolved"]:
print(f" {entry['repd_ref']:<8}{entry['site_name'][:36]:<38}omitted")
problems = sanity(report)
if problems:
print("\n SANITY FAILURES", file=sys.stderr)
for problem in problems:
print(f" {problem}", file=sys.stderr)
return 1
print(f"\n sanity {report['resolved']} coordinates, no failures")
if args.check:
out_path = Path(args.out)
if not out_path.exists():
print(f" {out_path} does not exist yet", file=sys.stderr)
return 1
previous = json.loads(out_path.read_text(encoding="utf-8"))
before = len([c for c in previous.get("coordinates", []) if c.get("longitude") is not None])
if report["resolved"] < before:
print(f" REGRESSED: {report['resolved']} against {before} committed", file=sys.stderr)
return 1
print(f" no regression ({report['resolved']} >= {before})")
return 0
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(report, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(f" written {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())Build
A JavaScript module in the offtakers folder of GridAtlas that reads generations and vicinity delta, using SHA-256.
storagegridatlas / tools/offtakers/build.mjs · lines 1–77 of 77 · Entry point · pattern modulePath (shared by 2 files)
- What it does
- It loads generations and vicinity delta. Defines sha256, modulePath, build, check. Uses libraries node:fs, node:path, node:crypto, node:url. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): 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: JSON file generations.json; JSON file 202611222000-vicinity-delta.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: CI PR Gate (gridatlas); Offtakers Cartridge (gridatlas). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Map Promotion Rehearsal (gridatlas).
- What it achieves
- It is built from the sha256 step (`sha256`), the module path helper (`modulePath`) and the build step (`build`). Build the potential-offtakers overlay module (`atlas/modules/` `-uk-offtakers-overlay.js`) from its readable source in `tools/offtakers/src/`, with the same deterministic text transform as the lightning overlay (`tools/lightning/build.mjs` `assemble`: files concatenated in name order, `///` source-only lines dropped, `///` line continuations joined, `@@GEN@@` stamped).
- Why it matters
- Imported by Offtakers Cartridge. Run by CI PR Gate.
- Application
- gridatlas · tools/offtakers · JavaScript module
- Uses
- Build (import), node:fs, node:path, node:crypto, node:url
- Used by
- run by CI PR Gate (script call), imported by Offtakers Cartridge (dynamic import)
- Produces
- SRC_DIR, GENERATIONS, modulePath, build, check
- Defines here
- sha256, modulePath, build, check
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/offtakers/build.mjs:1-77 · blob e60de754627a09fd01901bf0bbc4978e45d4fc85 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/**
* Build the potential-offtakers overlay module (atlas/modules/<GEN>-uk-offtakers-overlay.js) from its readable source in
* tools/offtakers/src/, with the same deterministic text transform as the lightning overlay (tools/lightning/build.mjs
* assemble(): files concatenated in name order, `///` source-only lines dropped, `///` line continuations joined,
* `@@GEN@@` stamped). One variant, "base". docs/OFFTAKERS-SOURCE.md.
*
* node tools/offtakers/build.mjs --gen <GEN> [--out <file>] # build; print size + sha256
* node tools/offtakers/build.mjs --check # the CI check (tools/ci/pr-gate.mjs, "offtakers-source")
*
* --check: the newest atlas/modules/*-uk-offtakers-overlay.js must be listed in tools/offtakers/generations.json, and every
* listed generation must rebuild from src/ byte for byte, except one marked {"historical": "<commit that cut it>"}: its source
* is that commit (it is kept in the registry as a record, and its module must still exist). With no offtakers module and an
* empty list it passes.
*/
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { assemble } from '../lightning/build.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
export const SRC_DIR = path.join(HERE, 'src');
export const GENERATIONS = path.join(HERE, 'generations.json');
const MODULE_RE = /^(\d{12})-uk-offtakers-overlay\.js$/, VARIANTS = ['base'];
const sha256 = b => createHash('sha256').update(b).digest('hex');
export const modulePath = gen => path.join(ROOT, 'atlas', 'modules', `${gen}-uk-offtakers-overlay.js`);
export const build = gen => {
if (gen !== '202611222000') return assemble({ variant: 'base', gen, variants: VARIANTS, srcDir: SRC_DIR });
// V9.194 is a bounded, explicit change set against the exact source-built
// V9.189 offtakers cartridge. Never rebuild an already published edition.
const patch = JSON.parse(fs.readFileSync(path.join(HERE, '202611222000-vicinity-delta.json'), 'utf8'));
if (patch.schema !== 'gridatlas.offtakers.source-delta.v1' || patch.generation !== gen
|| patch.source_generation !== '202611132345') throw new Error('V9.194 source recipe not pinned');
const lines = assemble({ variant: 'base', gen: patch.source_generation, variants: VARIANTS, srcDir: SRC_DIR }).split('\n');
for (const edit of patch.edits.slice().reverse()) {
const old = lines.slice(edit.index, edit.index + edit.old.length);
if (JSON.stringify(old) !== JSON.stringify(edit.old)) throw new Error('V9.194 predecessor/source delta mismatch at '+edit.index);
lines.splice(edit.index, edit.old.length, ...edit.next);
}
return lines.join('\n');
};
export function check() {
const lines = [], bad = [];
const reg = JSON.parse(fs.readFileSync(GENERATIONS, 'utf8')), listed = Object.keys(reg.generations || {}).sort();
const gens = fs.readdirSync(path.join(ROOT, 'atlas', 'modules')).map(n => (MODULE_RE.exec(n) || [])[1]).filter(Boolean).sort(), newest = gens.at(-1);
if (newest && reg.generations?.[newest]?.historical) bad.push(`the newest offtakers generation ${newest} is marked historical; it must rebuild from the current source`);
if (newest && !listed.includes(newest)) bad.push(`the newest offtakers generation ${newest} is not listed in tools/offtakers/generations.json`);
for (const g of listed) {
const file = modulePath(g);
if (!fs.existsSync(file)) { bad.push(`${g}: ${path.relative(ROOT, file)} missing`); continue; }
if (reg.generations[g].historical) { lines.push(`hist ${g}: historical, built from ${reg.generations[g].historical}; not rebuilt from the current source`); continue; }
const want = fs.readFileSync(file); let got;
try { got = Buffer.from(build(g), 'utf8'); } catch (e) { bad.push(`${g}: source does not assemble: ${e.message}`); continue; }
if (got.equals(want)) lines.push(`ok ${g}: ${want.length} B sha256 ${sha256(want)} rebuilt byte for byte`);
else { let i = 0; while (i < got.length && i < want.length && got[i] === want[i]) i++; bad.push(`${g}: rebuild differs from the committed module at byte ${i}`); }
}
if (!listed.length && !newest) lines.push('ok no offtakers generation yet');
for (const b of bad) lines.push(`FAIL ${b}`);
return { ok: !bad.length, lines };
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const a = process.argv.slice(2), opt = {};
for (let i = 0; i < a.length; i++) {
if (a[i] === '--check') opt.check = true;
else if (/^--(gen|out)$/.test(a[i]) && a[i + 1] !== undefined) opt[a[i].slice(2)] = a[++i];
else { console.error(`build.mjs: bad argument ${a[i]}`); process.exit(2); }
}
if (opt.check) { const r = check(); for (const l of r.lines) console.log(l); process.exit(r.ok ? 0 : 1); }
if (!opt.gen) { console.error('build.mjs: --gen <YYYYMMDDHHMM> or --check is required'); process.exit(2); }
const buf = Buffer.from(build(opt.gen), 'utf8');
if (opt.out) fs.writeFileSync(opt.out, buf);
console.log(JSON.stringify({ gen: opt.gen, bytes: buf.length, sha256: sha256(buf), out: opt.out || null }));
}Ot Filter
A Python command-line tool in the offtakers folder of GridAtlas that reads heavy emitters UK, industrial offtakers, datacentres and power plants, using SHA-256 from the GlobalGrid2050 repository.
geodesygridatlas / tools/offtakers/filter/ot_filter.py · lines 1–564 of 693 · Entry point · pattern load_status (shared by 2 files)
- What it does
- It loads heavy emitters UK, industrial offtakers, datacentres and power plants. Defines 26 functions or classes, including sha256, hav_km, in_bbox, norm, tokens. Uses libraries argparse, csv, hashlib, json, math. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): 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: globalgrid2050 data; JSON file heavy_emitters_uk.json; JSON file manifest_heavy_emitters.json; GeoJSON file industrial_offtakers.geojson; GeoJSON file datacentres.geojson; GeoJSON file power_plants.geojson; CSV file gppd.csv; CSV file status_curated.csv. Out: JSON file excluded_counts.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It loads NAEI (`load_naei`), loads GeoJSON (`load_geojson`) and loads gppd (`load_gppd`). Potential-offtakers filter (lane OT-filter), 29 Oct 2026. It accepts `--data`, `--out` and `--dukes`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · tools/offtakers/filter · Python CLI
- Uses
- argparse, csv, hashlib, json, math, os, re, sys
- Used by
- none found
- Produces
- sha256, hav_km, in_bbox, norm, tokens, unknown, band, power_subclass, load_naei, load_geojson, load_gppd, load_status
- Defines here
- sha256, hav_km, in_bbox, norm, tokens, unknown, band, power_subclass, load_naei, load_geojson, load_gppd, load_status, load_dukes, load_tec, classify_naei, btm_flag, nation, main, L, status_of, opkey, sitetok, merge_into_B
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/offtakers/filter/ot_filter.py:1-564 · blob 0661ed9018bd2e900e4126bf6d10e2bc58ca78b2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
Potential-offtakers filter (lane OT-filter), 29 Oct 2026.
Deterministic. Standard library only. Run with: python3 -I ot_filter.py --data data --out out
Inputs (data/):
heavy_emitters_uk.json NAEI 2023 point sources (globalgrid2050 @ 4f0f3a9b), OGL v3
manifest_heavy_emitters.json NAEI manifest (source URL, year, formula)
industrial_offtakers.geojson OSM industrial (ODbL)
datacentres.geojson OSM data centres (ODbL)
power_plants.geojson OSM power=plant gas+nuclear (ODbL)
gppd/gppd.csv WRI Global Power Plant Database v1.3.0 (CC BY 4.0); GBR rows only
status_curated.csv curated power-station status overrides, each with a source URL
Optional (not fetchable in this session; loaders are header-driven and skipped when absent):
dukes_5_11.xlsx DUKES 5.11 power stations (OGL v3) --dukes <path> (needs openpyxl)
tec_register.csv NESO TEC register (NESO Open Licence) --tec <path>
Outputs (out/): offtakers_filtered.geojson, excluded_counts.json, top20_per_class.md, counts.md, run_log.txt
"""
import argparse, csv, hashlib, json, math, os, re, sys
from collections import Counter, defaultdict, OrderedDict
GENERATION = "OT-filter-2026-10-29+R-otdata"
NAEI_URL = "https://naei.energysecurity.gov.uk/data/maps/emissions-point-sources"
NAEI_LIC = "OGL v3.0 (NAEI site: 'published by Defra, DESNZ and the Devolved Governments under the Open Government Licence')"
OSM_LIC = "ODbL 1.0, (c) OpenStreetMap contributors (open, attribution + share-alike; not in the owner's OGL/CC-BY/CC0 list: owner to confirm)"
GPPD_URL = "https://github.com/wri/global-power-plant-database"
GPPD_LIC = "CC BY 4.0 (WRI Global Power Plant Database v1.3.0)"
GG_RAW = "https://raw.githubusercontent.com/Ventusltd/globalgrid2050/4f0f3a9bf9fcd9560adf6ce2058adab4936fbe9f/"
WATER_TYPES = {"Wastewater Plant", "Water Works", "Water Treatment", "Sewage Plant", "Water", "Sewage"}
BBOX = (-11.0, 49.5, 3.0, 61.5)
# ---------- helpers ----------
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def hav_km(a, b):
lon1, lat1 = map(math.radians, a); lon2, lat2 = map(math.radians, b)
d = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
return 2 * 6371.0088 * math.asin(math.sqrt(d))
def in_bbox(c):
return isinstance(c, (list, tuple)) and len(c) == 2 and all(isinstance(v, (int, float)) for v in c) \
and BBOX[0] <= c[0] <= BBOX[2] and BBOX[1] <= c[1] <= BBOX[3]
def norm(s):
s = (s or "").lower()
s = re.sub(r"\b(ltd|limited|plc|llp|co|company|uk|the|power|station|generation|energy|centre|center|ccgt|chp|site|works|plant)\b", " ", s)
s = re.sub(r"[^a-z0-9 ]", " ", s)
return " ".join(s.split())
def tokens(s):
return set(t for t in norm(s).split() if len(t) > 2)
def unknown(s):
return (not s) or s.strip().lower().startswith("unknown") or s.strip().lower() in ("unnamed", "nan", "none")
def band(t):
"""Emission band from the NAEI-derived figure. Shown as a band, never as a number."""
if t is None: return None
if t >= 100000: return ">=100 kt"
if t >= 25000: return "25-100 kt"
if t >= 10000: return "10-25 kt"
if t >= 1000: return "1-10 kt"
return "<1 kt"
BAND_RANK = {None: -1, "<1 kt": 0, "1-10 kt": 1, "10-25 kt": 2, "25-100 kt": 3, ">=100 kt": 4}
# ---------- taxonomy ----------
# (A) energy-intensive industry subclass from NAEI sector, refined by name/operator keywords
MINERAL_KW = [
("glass", r"glass|pilkington|guardian industries|\bo-i\b|rockware|ardagh|encirc|quinn glass|beatson clark|stolzle"),
("bricks_clay", r"brick|ibstock|forterra|wienerberger|hanson building|clay|\btile|marley|plasmor|naylor|redland"),
("gypsum_board", r"gypsum|plasterboard|\bbpb\b|knauf|british gypsum|saint-gobain"),
("insulation", r"rockwool|knauf insulation|superglass|isover|armstrong world"),
("ceramics", r"ceramic|pottery|sanitary|wedgwood|churchill|steelite|norcros|imerys|prince minerals|unifrax"),
("aggregates_asphalt", r"quarry|asphalt|aggregate|tarmac|cemex|lafarge|hanson|breedon|roadstone|eurovia|civil and marine|mine\b|potash"),
]
SECTOR_MAP = {
"Cement": ("A", "cement"),
"Lime": ("A", "lime"),
"Iron & steel industries": ("A", "steel"),
"Non-ferrous metal industries": ("A", "metals_nonferrous"),
"Paper, printing & publishing industries": ("A", "paper_pulp"),
"Chemical industry": ("A", "chemicals"),
"Processing & distribution of petroleum products": ("A", "refining_petroleum"),
"Food, drink & tobacco industry": ("A", "food_drink"),
"Other industries": ("A", "other_manufacturing"),
"Vehicles": ("A", "other_manufacturing"),
"Electrical engineering": ("A", "other_manufacturing"),
"Mechanical engineering": ("A", "other_manufacturing"),
"Textiles, clothing, leather & footwear": ("A", "other_manufacturing"),
"Other fuel production": ("A", "other_manufacturing"),
"Oil & gas exploration and production": ("A", "oil_gas_terminal"),
"Processing & distribution of natural gas": ("A", "gas_processing_terminal"),
"Other mineral industries": ("A", "minerals_other"),
"Water & sewerage": ("D", "water_wastewater"),
"Major power producers": ("B", None),
"Minor power producers": ("B", None),
"Waste collection, treatment & disposal": ("WASTE", None),
"Public administration": ("E", "public_campus"),
"Commercial": ("E", "commercial"),
"Agriculture, forestry & fishing": ("X", "agriculture"),
"Construction": ("X", "construction"),
"Miscellaneous": ("X", "misc"),
}
EFW_KW = r"efw|energy from waste|energy recovery|\berf\b|resource recovery|incinerat|generating station|\bchp\b|power|energy works|waste to energy|recycling & energy|energy centre"
DC_KW = r"data ?cent(re|er)"
CAMPUS_KW = r"airport|naval base|port of|dockyard|university|hospital|infirmary|medical centre|nhs|awe\b|aldermaston|research|institute"
def power_subclass(name, operator, t):
s = f"{name} {operator}".lower()
if re.search(r"nuclear|hinkley|heysham|hartlepool|torness|sizewell|dungeness|hunterston|wylfa|oldbury-on-severn|british energy|nnb generation|edf energy nuclear", s) \
and not re.search(r"\bchp\b|standby|\bstor\b", s): # R-otdata: Fellside CHP (Sellafield) and Oldbury (W. Midlands) standby are not nuclear
return "nuclear"
if re.search(r"biomass|renewable energy plant|steven's croft|markinch|lynemouth|drax|wood|pellet", s):
return "biomass"
if re.search(r"landfill|biogas|anaerobic|sewage gas", s):
return "landfill_biogas"
if re.search(r"efw|energy from waste|energy recovery|\berf\b|incinerat|waste|multifuel|\bmf[12]\b|\bmfe\b", s): # R-otdata: Ferrybridge MF1/MF2 are multifuel EfW
return "energy_from_waste"
if re.search(r"\bchp\b|cogeneration|energy centre|heat (&|and) power|district|heat network|hospital|university|infirmary", s):
return "chp_energy_centre"
if re.search(r"peaking|reserve|\bstor\b|standby|velox|conrad|mercia power|rolls.royce power|plutus|statera|generation ltd|generation limited|flexible|ocgt|gas engine", s):
return "peaking_reserve"
if re.search(r"coal", s):
return "coal"
if t is not None and t >= 100000:
return "gas_ccgt_large"
return "thermal_unspecified"
# ---------- loaders ----------
def load_naei(path):
d = json.load(open(path, encoding="utf-8"))
out = []
for f in d["features"]:
p = f["properties"]; c = f["geometry"]["coordinates"]
out.append(dict(src="naei", id=p["id"], name=p["name"].strip(), operator=p["operator"].strip(),
sector=p["sector"], country=p["country"], datatype=p["datatype"],
t=float(p["emission_tco2e"]), lon=c[0], lat=c[1]))
return out
def load_geojson(path, src):
d = json.load(open(path, encoding="utf-8"))
out = []
for i, f in enumerate(d["features"]):
p = f.get("properties") or {}; g = f.get("geometry") or {}
c = g.get("coordinates")
if g.get("type") != "Point" or not in_bbox(c): continue
out.append(dict(src=src, id=f"{src}-{i}", name=(p.get("name") or "").strip(), operator=(p.get("operator") or "").strip(),
type=p.get("type") or p.get("source") or "", lon=c[0], lat=c[1]))
return out
def load_gppd(path):
out = []
with open(path, encoding="utf-8", newline="") as fh:
for r in csv.DictReader(fh):
if r["country"] != "GBR": continue
if r["primary_fuel"] not in ("Coal", "Gas", "Oil", "Nuclear", "Cogeneration"): continue
try: mw = float(r["capacity_mw"])
except ValueError: mw = None
out.append(dict(src="gppd", id=r["gppd_idnr"], name=r["name"].strip(), operator=r["owner"].strip(),
fuel=r["primary_fuel"], mw=mw, lon=float(r["longitude"]), lat=float(r["latitude"]),
year=r["commissioning_year"], gppd_source=r["source"], cap_year=r["year_of_capacity_data"]))
return out
def load_status(path):
rows = []
with open(path, encoding="utf-8", newline="") as fh:
for line in fh:
if line.startswith("#") or not line.strip(): continue
rows.append(line)
rd = csv.DictReader(rows)
return [dict(rx=re.compile(r["match_regex"], re.I), status=r["status"], date=r["status_date"] or None,
note=r["fuel_note"], url=r["source_url"], verified=r["verified_in_session"]) for r in rd]
def load_dukes(path):
"""DUKES 5.11 (OGL). Header-driven: finds the sheet with 'Station Name' and 'Installed Capacity'."""
if not path or not os.path.exists(path): return []
try: import openpyxl
except ImportError:
print("openpyxl missing: DUKES skipped", file=sys.stderr); return []
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
out = []
for ws in wb.worksheets:
hdr = None
for row in ws.iter_rows(values_only=True):
vals = [str(v).strip() if v is not None else "" for v in row]
if hdr is None:
if any("station name" in v.lower() for v in vals) and any("capacity" in v.lower() for v in vals):
hdr = [v.lower() for v in vals]
continue
rec = dict(zip(hdr, vals))
name = next((rec[k] for k in hdr if "station name" in k), "")
if not name: continue
cap = next((rec[k] for k in hdr if "capacity" in k), "")
out.append(dict(src="dukes", name=name, company=next((rec[k] for k in hdr if "company" in k), ""),
fuel=next((rec[k] for k in hdr if k.startswith("fuel") or "type" in k), ""),
mw=float(re.sub(r"[^0-9.]", "", cap) or 0) or None,
year=next((rec[k] for k in hdr if "year" in k), ""),
location=next((rec[k] for k in hdr if "location" in k or "region" in k), "")))
return out
def load_tec(path):
if not path or not os.path.exists(path): return []
with open(path, encoding="utf-8-sig", newline="") as fh:
rows = list(csv.DictReader(fh))
out = []
for r in rows:
k = {kk.lower().strip(): (vv or "").strip() for kk, vv in r.items()}
name = k.get("project name") or k.get("project_name") or ""
if not name: continue
out.append(dict(name=name, customer=k.get("customer name", ""), site=k.get("connection site", ""),
mw=k.get("mw connected", ""), status=k.get("project status", ""), plant_type=k.get("plant type", ""),
host=k.get("host to", "")))
return out
# ---------- classification ----------
def classify_naei(r):
"""Returns (cls, subclass, reason) for one NAEI row, or ('X', sub, reason) when excluded."""
if r["country"] == "Offshore":
return "X", "offshore", "Offshore country: not a land site"
cls, sub = SECTOR_MAP.get(r["sector"], ("X", "unmapped_sector"))
s = f"{r['name']} {r['operator']}".lower()
t = r["t"]
if cls == "A" and sub == "minerals_other":
for k, pat in MINERAL_KW:
if re.search(pat, s): sub = k; break
if cls == "A" and sub == "refining_petroleum" and re.search(r"refiner|stanlow|fawley|pembroke|grangemouth|humber|lindsey", s):
sub = "refinery"
if cls == "B":
return "B", power_subclass(r["name"], r["operator"], t), "NAEI power-producer sector"
if cls == "WASTE":
if re.search(EFW_KW, s) and t >= 10000:
return "B", "energy_from_waste", "NAEI waste sector, EfW/ERF keyword and >=10 kt"
return "X", "waste_landfill_other", "waste sector without generator keyword or <10 kt"
if cls == "E":
if re.search(DC_KW, s):
return "C", "data_centre", "NAEI commercial sector, data-centre keyword"
if t >= 10000 and (re.search(CAMPUS_KW, s) or re.search(r"\bchp\b|energy centre", s)):
return "E", sub, "NAEI public/commercial, >=10 kt, campus or CHP keyword"
return "X", f"small_{sub}", "public/commercial <10 kt or no campus keyword"
if cls == "D":
if t >= 1000:
return "D", "water_wastewater_large", "NAEI water & sewerage point source, band >=1 kt (large works)"
return "D", "water_wastewater_listed_small", "NAEI water & sewerage point source <1 kt (listed, usually a sewage-gas CHP; off by default)"
if cls == "X":
return "X", sub, "sector outside taxonomy"
return cls, sub, "NAEI sector map"
def btm_flag(cls, sub, s_lower, t, sources):
"""Honest on-site-combustion indicator. Values: evidence strings, never a claim of capacity."""
if cls == "B": return "generator site (listed as power producer)"
if re.search(r"\bchp\b|cogeneration|energy centre|heat (&|and) power|combined heat", s_lower):
return "CHP/energy centre named in record"
if "naei" in sources and t is not None and t >= 10000:
if sub in ("cement", "lime", "glass", "bricks_clay", "ceramics", "steel", "gypsum_board", "aggregates_asphalt", "minerals_other"):
return "CO2 reported to NAEI (combustion and/or process emissions, not distinguished)"
return "CO2 reported to NAEI >=10 kt (fuel combustion on site is the usual source; not distinguished)"
if "naei" in sources: return "CO2 reported to NAEI (<10 kt)"
return "unknown (no open site-level register found)"
def nation(country, lon, lat):
if country in ("England", "Scotland", "Wales", "Northern Ireland"): return country
# OSM/GPPD rows carry no nation: coarse geometric fallback, flagged as approximate
if lon < -5.3 and lat > 53.9 and lat < 55.4: return "Northern Ireland (approx)"
if lat > 55.0 and not (lon > -2.5 and lat < 55.82): return "Scotland (approx)"
if lon < -2.65 and 51.35 < lat < 53.45 and not (lon < -4.6 and lat < 51.75): return "Wales (approx)"
return "England (approx)"
# ---------- main ----------
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", default="data"); ap.add_argument("--out", default="out")
ap.add_argument("--dukes", default=None); ap.add_argument("--tec", default=None)
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
log = []
def L(*x): s = " ".join(str(v) for v in x); log.append(s); print(s)
inputs = {}
for fn in ["heavy_emitters_uk.json", "manifest_heavy_emitters.json", "industrial_offtakers.geojson", "datacentres.geojson",
"power_plants.geojson", "gppd/gppd.csv", "status_curated.csv"]:
p = os.path.join(a.data, fn); inputs[fn] = sha256(p); L("input", fn, inputs[fn][:16])
manifest = json.load(open(os.path.join(a.data, "manifest_heavy_emitters.json")))
naei = load_naei(os.path.join(a.data, "heavy_emitters_uk.json"))
osm_ind = load_geojson(os.path.join(a.data, "industrial_offtakers.geojson"), "osm_ind")
osm_dc = load_geojson(os.path.join(a.data, "datacentres.geojson"), "osm_dc")
osm_pp = load_geojson(os.path.join(a.data, "power_plants.geojson"), "osm_pp")
gppd = load_gppd(os.path.join(a.data, "gppd", "gppd.csv"))
status_rows = load_status(os.path.join(a.data, "status_curated.csv"))
dukes = load_dukes(a.dukes); tec = load_tec(a.tec)
L("rows naei", len(naei), "osm_ind", len(osm_ind), "osm_dc", len(osm_dc), "osm_pp", len(osm_pp), "gppd GBR thermal", len(gppd),
"dukes", len(dukes), "tec", len(tec))
def status_of(name):
for st in status_rows:
if st["rx"].search(name): return st["status"] + (st["date"] or "")
return None
excluded = Counter(); reasons = defaultdict(Counter)
sites = [] # merged site dicts
# 1. NAEI rows: classify, then group rows within 100 m of same class (same operator or either unknown)
kept = []
for r in sorted(naei, key=lambda r: (int(r["id"]))):
cls, sub, why = classify_naei(r)
if cls == "X":
excluded[f"naei:{sub}"] += 1; reasons["naei"][why] += 1; continue
kept.append((cls, sub, why, r))
L("naei kept", len(kept), "excluded", sum(v for k, v in excluded.items() if k.startswith("naei:")))
for cls, sub, why, r in kept:
merged = None
for s in sites:
if s["class"] != cls or s["_primary"] != "naei": continue
if hav_km((s["lon"], s["lat"]), (r["lon"], r["lat"])) <= 0.1 and (
norm(s["operator"]) == norm(r["operator"]) or tokens(s["name"]) & tokens(r["name"])):
if cls == "B" and status_of(s["name"]) != status_of(r["name"]): continue
merged = s; break
if merged:
merged["records"].append(dict(source="NAEI", id=r["id"], name=r["name"], operator=r["operator"], sector=r["sector"],
lon=round(r["lon"], 6), lat=round(r["lat"], 6), band=band(r["t"])))
merged["t"] = (merged["t"] or 0) + r["t"]
if BAND_RANK[band(r["t"])] > BAND_RANK[band(merged["_t_lead"])]: merged["_t_lead"] = r["t"]
continue
sites.append(dict(_primary="naei", class_=None, **{"class": cls}, subclass=sub, name=r["name"], operator=r["operator"],
lon=r["lon"], lat=r["lat"], country=r["country"], t=r["t"], _t_lead=r["t"], mw=None, fuel=None,
records=[dict(source="NAEI", id=r["id"], name=r["name"], operator=r["operator"], sector=r["sector"],
lon=round(r["lon"], 6), lat=round(r["lat"], 6), band=band(r["t"]))],
sources={"naei"}, why=why, osm_corroboration=[]))
L("naei sites after 100 m grouping", len(sites))
# 1b. R-otdata site-level merge (class A only). Integrated works are reported to NAEI as one point per process unit
# (Port Talbot: blast furnaces, sinter, coke ovens, BOS, rolling mills, power station, flaring). Rule: two class-A NAEI
# sites join when (i) same normalised operator after OPERATOR_ALIASES, (ii) they share a site-name token that is not
# a process/generic word, and (iii) some record of one lies within SITE_LINK_M of some record of the other (single
# linkage). Same subclass is not required inside one operator's works, but class must match. Every NAEI record is
# kept in records[] with its own coordinates and band; the point is the record with the largest NAEI figure.
SITE_LINK_M = 1500
PROCESS_WORDS = {"blast", "furnaces", "furnace", "sinter", "coke", "ovens", "oxygen", "rolling", "mill", "flaring", "bfg", "cog",
"integrated", "iron", "steel", "steelworks", "morfa", "appleby", "boiler", "house", "road", "park", "industrial",
"estate", "lane", "north", "south", "east", "west", "new", "old", "unit", "units", "terminal", "terminals", "refinery", "complex",
"brickworks", "factory", "quarry", "manufacturing", "processes", "sections", "package", "boilers", "pharmaceutical",
"cement", "oil", "gas", "sodium", "carbonate", "lime", "kiln", "kilns", "glassworks", "papermill", "mills"}
OPERATOR_ALIASES = {"corus": "tata steel"} # Tata Steel acquired Corus in 2007; NAEI still carries one Port Talbot row as Corus UK Ltd
def opkey(o): k = norm(o); return OPERATOR_ALIASES.get(k, k)
def sitetok(n): return tokens(n) - PROCESS_WORDS
for s in sites:
s["_pts"] = [(s["lon"], s["lat"])]
merged_any = True; n_site_merges = 0
while merged_any:
merged_any = False
A = [s for s in sites if s["class"] == "A" and s["_primary"] == "naei" and not unknown(s["operator"])]
for i, sa in enumerate(A):
for sb in A[i + 1:]:
if opkey(sa["operator"]) != opkey(sb["operator"]): continue
if not (set().union(*(sitetok(r["name"]) for r in sa["records"])) & set().union(*(sitetok(r["name"]) for r in sb["records"]))): continue
if min(hav_km(p, q) for p in sa["_pts"] for q in sb["_pts"]) * 1000 > SITE_LINK_M: continue
keep, drop = (sa, sb) if (sa["_t_lead"] or 0) >= (sb["_t_lead"] or 0) else (sb, sa)
keep["records"].extend(drop["records"]); keep["_pts"].extend(drop["_pts"])
keep["t"] = (keep["t"] or 0) + (drop["t"] or 0)
keep["osm_corroboration"].extend(drop["osm_corroboration"])
keep.setdefault("_merged_names", [keep["name"]]).extend(drop.get("_merged_names", [drop["name"]]))
sites.remove(drop); merged_any = True; n_site_merges += 1
break
if merged_any: break
for s in sites:
if len(s.get("_merged_names", [])) > 1:
# site name: the record names if they are all the same, else their longest common leading words (e.g. "Port
# Talbot"), else the anchor's name; then "(site: N NAEI points)" so the card says it is a merge
nms = [r["name"] for r in s["records"]]
if len(set(nms)) == 1: s["name"] = nms[0]
else:
ws = [n.replace(",", " ").split() for n in nms]; pre = []
for col in zip(*ws):
if len({w.lower() for w in col}) == 1: pre.append(col[0])
else: break
s["name"] = f"{' '.join(pre) if pre else s['name']} (site: {len(nms)} NAEI points)"
s["operator"] = next((r["operator"] for r in s["records"] if opkey(r["operator"]) == opkey(s["operator"]) and norm(r["operator"]) not in OPERATOR_ALIASES), s["operator"])
s["site_merge"] = dict(rule=f"R-otdata site merge: same operator (aliases {OPERATOR_ALIASES}), shared site-name token, "
f"records linked within {SITE_LINK_M} m; point = record with the largest NAEI figure",
n_records=len(s["records"]),
max_spread_m=round(max(hav_km(p, q) for p in s["_pts"] for q in s["_pts"]) * 1000))
L("R-otdata site-level merges (class A)", n_site_merges, "-> naei sites", len(sites))
# 2. Power stations from GPPD (CC BY) and OSM power=plant (ODbL): merge into NAEI B sites within 1 km with a shared name token,
# otherwise add as new B sites.
def merge_into_B(rec, src_label, dist_km=2.5):
"""Merge a GPPD/OSM power-plant record into an existing B site when: within dist_km, a shared name token
(or the record is unnamed and within 0.5 km), and the curated status table gives the same answer for both
names (so a closed coal station is never folded into the CCGT next door). Best match = most shared tokens, then nearest."""
best = None
for s in sites:
if s["class"] != "B": continue
d = hav_km((s["lon"], s["lat"]), (rec["lon"], rec["lat"]))
shared = tokens(s["name"]) & tokens(rec["name"])
if not ((d <= dist_km and shared) or (unknown(rec["name"]) and d <= 0.5)): continue
if status_of(s["name"]) != status_of(rec["name"]): continue
score = (len(shared), -d)
if best is None or score > best[0]: best = (score, s)
GENERIC = {"landfill", "road", "park", "industrial", "estate", "farm", "lane", "street", "stor", "reserve", "standby", "gas",
"biogas", "solar", "wind", "battery", "storage", "north", "south", "east", "west", "new", "ocgt", "peaking"}
if not best and rec["src"] == "gppd" and not unknown(rec["name"]):
# R-otdata: GPPD coordinates (GEODB/CARMA) can be 2.5-5 km off (Kilroot, Spalding, Burghfield, Chickerell, Slough,
# Baglan Bay OCGT). Accept a farther match only when it is unambiguous: exactly one B site within OFFSET_KM shares a
# name token, and the curated status agrees. The record keeps its own coordinates in records[].
OFFSET_KM = 5.0
cand = [s for s in sites if s["class"] == "B" and (tokens(s["name"]) & tokens(rec["name"])) - GENERIC
and hav_km((s["lon"], s["lat"]), (rec["lon"], rec["lat"])) <= OFFSET_KM]
if len(cand) == 1 and status_of(cand[0]["name"]) == status_of(rec["name"]):
best = ((0, 0), cand[0]); rec = dict(rec, merge_note=f"R-otdata offset merge, {hav_km((cand[0]['lon'], cand[0]['lat']), (rec['lon'], rec['lat'])):.2f} km")
if not best and rec["src"] == "osm_pp" and status_of(rec["name"]) is None:
# R-otdata: an OSM power=plant point with no curated status of its own (e.g. "Heysham Nuclear Power Station", which
# covers Heysham 1 and 2) next to a curated site is corroboration, not a new site with "status unknown".
near = [s for s in sites if s["class"] == "B" and (tokens(s["name"]) & tokens(rec["name"])) - GENERIC
and status_of(s["name"]) is not None and hav_km((s["lon"], s["lat"]), (rec["lon"], rec["lat"])) <= 0.5]
if near:
s = min(near, key=lambda s: hav_km((s["lon"], s["lat"]), (rec["lon"], rec["lat"])))
s["osm_corroboration"].append(dict(source="OSM power=plant", id=rec["id"], name=rec["name"], operator=rec["operator"],
note="R-otdata: corroboration only; no curated status of its own"))
s["sources"].add("osm_pp"); return True
if best:
s = best[1]; s["records"].append(dict(source=src_label, **{k: rec.get(k) for k in ("id", "name", "operator", "fuel", "mw", "year")},
lon=round(rec["lon"], 6), lat=round(rec["lat"], 6), **({"merge_note": rec["merge_note"]} if rec.get("merge_note") else {})))
s["sources"].add(rec["src"])
if rec.get("mw") and not s["mw"]: s["mw"] = rec["mw"]; s["fuel"] = rec.get("fuel")
fuel_sub = {"Coal": "coal", "Nuclear": "nuclear", "Oil": "oil"}.get(rec.get("fuel"))
if fuel_sub and s["subclass"] in ("thermal_unspecified", "gas_ccgt_large", "gas_other"): s["subclass"] = fuel_sub
return True
return False
# R-otdata: GPPD rows whose coordinates are wrong beyond any distance rule. Each is folded, as a record, into the named
# NAEI site; the reason is kept in the record. Found by evidence/R-otdata/qa_points.py (Natural Earth 10 m land test).
GPPD_RECORD_FIX = {
"GBR1000412": ("Bowmore", "GPPD point 56.1833,-2.5667 lies 7 km out in the North Sea off Fife; Bowmore (Islay) is the NAEI site"),
}
for g in list(gppd):
fx = GPPD_RECORD_FIX.get(g["id"])
if not fx: continue
tgt = [s for s in sites if s["class"] == "B" and norm(s["name"]) == norm(fx[0]) and "naei" in s["sources"]]
if len(tgt) == 1:
tgt[0]["records"].append(dict(source="GPPD", id=g["id"], name=g["name"], operator=g["operator"], fuel=g["fuel"], mw=g["mw"],
year=g["year"], lon=g["lon"], lat=g["lat"], merge_note="R-otdata: " + fx[1]))
tgt[0]["sources"].add("gppd")
if g["mw"] and not tgt[0]["mw"]: tgt[0]["mw"] = g["mw"]; tgt[0]["fuel"] = g["fuel"]
fuel_sub = {"Coal": "coal", "Nuclear": "nuclear", "Oil": "oil"}.get(g["fuel"])
if fuel_sub and tgt[0]["subclass"] in ("thermal_unspecified", "gas_ccgt_large", "gas_other"): tgt[0]["subclass"] = fuel_sub
gppd.remove(g); excluded["gppd:bad_coordinates_folded_into_naei"] += 1
for g in sorted(gppd, key=lambda g: g["id"]):
if merge_into_B(g, "GPPD"): continue
sub = {"Nuclear": "nuclear", "Coal": "coal", "Oil": "oil", "Cogeneration": "chp_energy_centre"}.get(g["fuel"])
if not sub: sub = power_subclass(g["name"], g["operator"], None); sub = "gas_ccgt_large" if (sub == "thermal_unspecified" and (g["mw"] or 0) >= 300) else ("gas_other" if sub == "thermal_unspecified" else sub)
sites.append(dict(_primary="gppd", **{"class": "B"}, subclass=sub, name=g["name"], operator=g["operator"], lon=g["lon"], lat=g["lat"],
country=None, t=None, _t_lead=None, mw=g["mw"], fuel=g["fuel"],
records=[dict(source="GPPD", id=g["id"], name=g["name"], operator=g["operator"], fuel=g["fuel"], mw=g["mw"], year=g["year"], gppd_source=g["gppd_source"])],
sources={"gppd"}, why="GPPD GBR thermal plant (DUKES-derived), not in NAEI 2023", osm_corroboration=[]))
# 2b. R-otdata: point corrections (before OSM power=plant matching, so OSM points meet the corrected point) where the NAEI coordinate is demonstrably off and an open (CC BY) coordinate of the same
# plant is in records[]. The original point stays in records[] (lon/lat) for provenance.
POINT_FROM_RECORD = {
"8981": ("GBR1000002", "NAEI Kilroot point is 3.5 km SW of the plant, at the shore of Belfast Lough; GPPD GBR1000002 "
"(54.7255,-5.7653) agrees with OSM and the published station location to about 0.1 km"),
}
for s in sites:
ids = {str(r.get("id")) for r in s["records"]}
for naei_id, (rec_id, why_pt) in POINT_FROM_RECORD.items():
if naei_id in ids and rec_id in ids:
r = next(r for r in s["records"] if r.get("id") == rec_id)
s["point_note"] = f"R-otdata: point taken from {r['source']} {rec_id}; {why_pt}"
s["lon"], s["lat"] = r["lon"], r["lat"]
for o in sorted(osm_pp, key=lambda o: o["id"]):
if merge_into_B(o, "OSM power=plant"): continue
if unknown(o["name"]):
excluded["osm_pp:unnamed_unmatched"] += 1; continue
sub = "nuclear" if o["type"] == "nuclear" else power_subclass(o["name"], o["operator"], None)
if sub == "thermal_unspecified": sub = "gas_other"
sites.append(dict(_primary="osm_pp", **{"class": "B"}, subclass=sub, name=o["name"], operator=o["operator"], lon=o["lon"], lat=o["lat"],
country=None, t=None, _t_lead=None, mw=None, fuel=o["type"],
records=[dict(source="OSM power=plant", id=o["id"], name=o["name"], operator=o["operator"], fuel=o["type"])],
sources={"osm_pp"}, why="OSM power=plant (gas/nuclear), not matched to NAEI or GPPD", osm_corroboration=[]))
L("B sites after GPPD+OSM", sum(1 for s in sites if s["class"] == "B"))
# 3. OSM industrial: keep strong-keyword sites; corroborate NAEI sites within 500 m; drop the rest.
STRONG = r"refiner|steelworks|steel works|paper mill|papermill|glass works|glassworks|cement|chemical works|chemical plant|smelter"
seen = set()
for o in sorted(osm_ind, key=lambda o: o["id"]):
key = (o["name"], round(o["lon"], 4), round(o["lat"], 4))
if key in seen: excluded["osm_ind:exact_duplicate"] += 1; continue
seen.add(key)
is_water = o["type"] in WATER_TYPES
near = None
for s in sites:
if s["_primary"] != "naei": continue
if (s["class"] == "D") != is_water: continue
pts = s.get("_pts") or [(s["lon"], s["lat"])]
dmin = min(hav_km(p, (o["lon"], o["lat"])) for p in pts)
# R-otdata: a strong-keyword OSM works polygon point inside a merged NAEI works (site_merge) corroborates it up to 2 km
if dmin <= 0.5 or (s.get("site_merge") and dmin <= 2.0 and re.search(STRONG, f"{o['name']} {o['type']}".lower())
and tokens(o["name"]) & set().union(*(tokens(r["name"]) for r in s["records"]))): near = s; break
if near:
near["osm_corroboration"].append(dict(source="OSM", id=o["id"], name=o["name"], type=o["type"], operator=o["operator"]))
near["sources"].add("osm_ind"); excluded[f"osm_ind:{'water' if is_water else 'industrial'}_merged_into_naei"] += 1; continue
if is_water:
excluded["osm_ind:water_not_large"] += 1; continue
s_l = f"{o['name']} {o['type']}".lower()
if re.search(STRONG, s_l):
sub = ("refinery" if "refiner" in s_l else "steel" if "steel" in s_l else "paper_pulp" if "paper" in s_l else
"glass" if "glass" in s_l else "cement" if "cement" in s_l else "chemicals" if "chemical" in s_l else "metals_nonferrous")
sites.append(dict(_primary="osm_ind", **{"class": "A"}, subclass=sub, name=o["name"], operator=o["operator"], lon=o["lon"], lat=o["lat"],
country=None, t=None, _t_lead=None, mw=None, fuel=None,
records=[dict(source="OSM", id=o["id"], name=o["name"], operator=o["operator"], type=o["type"])],
sources={"osm_ind"}, why="OSM industrial with strong keyword, no NAEI site within 500 m", osm_corroboration=[]))
elif o["type"] in ("Oil", "Oil Storage", "Oil Field"):
excluded["osm_ind:fuel_storage_depot_or_well"] += 1
else:
excluded["osm_ind:minor_industrial"] += 1
# 4. OSM data centres: group within 250 m; corroborate NAEI C sites within 500 m.
dc_groups = []
for o in sorted(osm_dc, key=lambda o: o["id"]):
if re.search(r"cable landing|landing station", o["name"], re.I):
# R-otdata: submarine-cable landing stations are tagged telecom=data_center in OSM but are small repeater buildings
excluded["osm_dc:cable_landing_station"] += 1; continue
near = None
for s in sites:
if s["class"] == "C" and s["_primary"] == "naei" and hav_km((s["lon"], s["lat"]), (o["lon"], o["lat"])) <= 0.5: near = s; break
if near:
near["osm_corroboration"].append(dict(source="OSM", id=o["id"], name=o["name"], operator=o["operator"])); near["sources"].add("osm_dc")
excluded["osm_dc:merged_into_naei"] += 1; continue
g = None
for gg in dc_groups:
if hav_km((gg["lon"], gg["lat"]), (o["lon"], o["lat"])) <= 0.25 and (
unknown(gg["operator"]) or unknown(o["operator"]) or norm(gg["operator"]) == norm(o["operator"])): g = gg; break
if g:
g["records"].append(dict(source="OSM", id=o["id"], name=o["name"], operator=o["operator"]))
if unknown(g["name"]) and not unknown(o["name"]): g["name"] = o["name"]
if unknown(g["operator"]) and not unknown(o["operator"]): g["operator"] = o["operator"]
else:
dc_groups.append(dict(_primary="osm_dc", **{"class": "C"}, subclass="data_centre", name=o["name"], operator=o["operator"], lon=o["lon"], lat=o["lat"],
country=None, t=None, _t_lead=None, mw=None, fuel=None,
records=[dict(source="OSM", id=o["id"], name=o["name"], operator=o["operator"])], sources={"osm_dc"},
why="OSM data centre (telecom/building=data_center)", osm_corroboration=[]))
for g in dc_groups:
g["subclass"] = "data_centre_campus" if len(g["records"]) >= 2 else "data_centre"
sites.extend(dc_groups)
# 4b. R-otdata: one site listed twice under two classes (identical coordinates, same normalised operator), e.g. Queens
# Medical Centre CHP (NAEI "Processing & distribution of natural gas" <1 kt and "Public administration" 10-25 kt).
# The row with the larger NAEI figure keeps its class; the other becomes a record of it.
by_pt = defaultdict(list)
for s in sites: by_pt[(round(s["lon"], 6), round(s["lat"], 6))].append(s)
for grp in by_pt.values():
for sa in list(grp):
for sb in list(grp):
if sa is sb or sa not in sites or sb not in sites or sa["class"] == sb["class"]: continue
if unknown(sa["operator"]) or norm(sa["operator"]) != norm(sb["operator"]): continue
keep, drop = (sa, sb) if (sa["_t_lead"] or 0) >= (sb["_t_lead"] or 0) else (sb, sa)