GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / data_uk_dno_and_tso / scripts/lib

Plant Feeders and 8 more files

A JavaScript module in the engine folder of Energy Transition Simulator that works with cables, 33kV and A roads, using IEC 60287.

613 lines of JavaScript and Python from data_uk_dno_and_tso, energy-transition-simulator, in 9 files. Topic: Grid network and substations. Section 319 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. CKAN ingest · data_uk_dno_and_tso / scripts/lib/ckan.py lines 1–43
  2. Hashing other · data_uk_dno_and_tso / scripts/lib/hashing.py lines 1–13
  3. Opendatasoft ingest · data_uk_dno_and_tso / scripts/lib/opendatasoft.py lines 1–56
  4. Validate Declared other · data_uk_dno_and_tso / scripts/validate_declared.py lines 1–39
  5. Validate Schema Drift ingest · data_uk_dno_and_tso / scripts/validate_schema_drift.py lines 1–41
  6. MV Network ingest · energy-transition-simulator / prototype/mod/engine/mv-network.mjs lines 1–127
  7. Plant Feeders transform · energy-transition-simulator / prototype/mod/engine/plant-feeders.mjs lines 1–142
  8. Single-Line Diagram (SLD) Connect electrical · energy-transition-simulator / prototype/mod/engine/sld-connect.mjs lines 1–57
  9. Single-Line Diagram (SLD) Rules electrical · energy-transition-simulator / prototype/mod/engine/sld-rules.mjs lines 1–95

CKAN

A Python module in the scripts folder of Data UK DNO And TSO that gets action (`get_action`). It is built from the CKAN portal class (`CKANPortal`).

ingestdata_uk_dno_and_tso / scripts/lib/ckan.py · lines 1–43 of 43 · pattern _headers (shared by 2 files)

What it does
It fetches data. Defines CKANPortal, action_base, _headers, action_url, get_action. Uses libraries __future__, json, os, time, urllib.parse. Side effects: makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'dno'): 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.
Downstream impact
Used directly by 1 file: Fetch CKAN Catalogue (data_uk_dno_and_tso).
What it achieves
Defines `CKANPortal`, `action_base`, `action_url` and 1 more.
Why it matters
Imported by Fetch CKAN Catalogue.
Application
data_uk_dno_and_tso · scripts/lib · Python module
Uses
__future__, json, os, time, urllib.parse, urllib.request, dataclasses, typing
Used by
imported by Fetch CKAN Catalogue (import)
Produces
CKANPortal, action_url, get_action
Defines here
CKANPortal, action_base, _headers, action_url, get_action
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/lib/ckan.py:1-43 · blob 713474d7e24244aa26afa893630e1a70806b7455 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations

import json
import os
import time
import urllib.parse
import urllib.request
from dataclasses import dataclass
from typing import Any


@dataclass(frozen=True)
class CKANPortal:
    base_url: str
    api_key_env: str | None = None
    min_delay_seconds: float = 1.0

    @property
    def action_base(self) -> str:
        return self.base_url.rstrip("/") + "/api/3/action"


def _headers(api_key_env: str | None) -> dict[str, str]:
    headers = {"User-Agent": "globalgrid2050-data-fetcher/0.1"}
    if api_key_env:
        api_key = os.environ.get(api_key_env)
        if api_key:
            headers["Authorization"] = api_key
    return headers


def action_url(portal: CKANPortal, action: str, **params: str) -> str:
    query = urllib.parse.urlencode(params)
    return f"{portal.action_base}/{action}" + (f"?{query}" if query else "")


def get_action(portal: CKANPortal, action: str, **params: str) -> dict[str, Any]:
    url = action_url(portal, action, **params)
    req = urllib.request.Request(url, headers=_headers(portal.api_key_env))
    time.sleep(portal.min_delay_seconds)
    with urllib.request.urlopen(req, timeout=60) as response:
        body = response.read().decode("utf-8")
    return json.loads(body)

Hashing

A Python module in the scripts folder of Data UK DNO And TSO that works with sha256 file (`sha256_file`), using SHA-256.

otherdata_uk_dno_and_tso / scripts/lib/hashing.py · lines 1–13 of 13 · pattern sha256_file (shared by 32 files)

What it does
Defines sha256_file. Uses libraries __future__, hashlib, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'dno'): 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.
Downstream impact
Used directly by 3 files: Build Declared (data_uk_dno_and_tso); Fetch CKAN Catalogue (data_uk_dno_and_tso); Fetch Ods Catalogue (data_uk_dno_and_tso). Reached from 1 other entry point, including Audit Workflow (data_uk_dno_and_tso).
What it achieves
Defines `sha256_file`.
Why it matters
Imported by Build Declared, Fetch CKAN Catalogue and Fetch Ods Catalogue.
Application
data_uk_dno_and_tso · scripts/lib · Python module
Uses
__future__, hashlib, pathlib
Used by
imported by Build Declared (import), imported by Fetch CKAN Catalogue (import), imported by Fetch Ods Catalogue (import)
Produces
sha256_file
Defines here
sha256_file
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/lib/hashing.py:1-13 · blob f02860b15ab73e2472cb64287140a66de8e6817b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations

import hashlib
from pathlib import Path


def sha256_file(path: str | Path) -> str:
    file_path = Path(path)
    h = hashlib.sha256()
    with file_path.open("rb") as fh:
        for chunk in iter(lambda: fh.read(1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()

Opendatasoft

A Python module in the scripts folder of Data UK DNO And TSO that lists datasets (`list_datasets`) and exports URL (`export_url`).

ingestdata_uk_dno_and_tso / scripts/lib/opendatasoft.py · lines 1–56 of 56 · pattern _headers (shared by 2 files)

What it does
It fetches data. Defines 7 functions or classes, including ODSPortal, api_base, _headers, get_json, list_datasets. Uses libraries __future__, json, os, urllib.parse, urllib.request. Side effects: makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'dno'): 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.
Downstream impact
Used directly by 1 file: Fetch Ods Catalogue (data_uk_dno_and_tso).
What it achieves
It is built from the ods portal class (`ODSPortal`) and the records URL helper (`records_url`). Defines `ODSPortal`, `api_base`, `get_json` and 3 more.
Why it matters
Imported by Fetch Ods Catalogue.
Application
data_uk_dno_and_tso · scripts/lib · Python module
Uses
__future__, json, os, urllib.parse, urllib.request, dataclasses, typing
Used by
imported by Fetch Ods Catalogue (import)
Produces
ODSPortal, get_json, list_datasets, records_url, export_url
Defines here
ODSPortal, api_base, _headers, get_json, list_datasets, records_url, export_url
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/lib/opendatasoft.py:1-56 · blob 4a4e7ca3abea7ff16a7ef26dde4535b2e1febe38 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations

import json
import os
import urllib.parse
import urllib.request
from dataclasses import dataclass
from typing import Any


@dataclass(frozen=True)
class ODSPortal:
    base_url: str
    api_key_env: str | None = None

    @property
    def api_base(self) -> str:
        return self.base_url.rstrip("/") + "/api/explore/v2.1"


def _headers(api_key_env: str | None) -> dict[str, str]:
    headers = {"User-Agent": "globalgrid2050-data-fetcher/0.1"}
    if api_key_env:
        api_key = os.environ.get(api_key_env)
        if api_key:
            headers["Authorization"] = f"Apikey {api_key}"
    return headers


def get_json(url: str, headers: dict[str, str]) -> dict[str, Any]:
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req, timeout=60) as response:
        body = response.read().decode("utf-8")
    return json.loads(body)


def list_datasets(portal: ODSPortal, limit: int = 100) -> dict[str, Any]:
    query = urllib.parse.urlencode({"limit": str(limit)})
    url = f"{portal.api_base}/catalog/datasets?{query}"
    return get_json(url, _headers(portal.api_key_env))


def records_url(portal: ODSPortal, dataset_id: str, *, limit: int = 10, offset: int = 0) -> str:
    if limit > 100:
        raise ValueError("OpenDataSoft records endpoint limit must not exceed 100")
    if offset + limit >= 10000:
        raise ValueError("OpenDataSoft records endpoint offset + limit must remain below 10000; use exports for bulk pulls")
    query = urllib.parse.urlencode({"limit": str(limit), "offset": str(offset)})
    return f"{portal.api_base}/catalog/datasets/{dataset_id}/records?{query}"


def export_url(portal: ODSPortal, dataset_id: str, fmt: str = "json") -> str:
    safe_fmt = fmt.lower().strip()
    if safe_fmt not in {"csv", "json", "geojson", "parquet", "xlsx"}:
        raise ValueError(f"Unsupported export format: {fmt}")
    return f"{portal.api_base}/catalog/datasets/{dataset_id}/exports/{safe_fmt}"

Validate Declared

A Python command-line tool in the scripts folder of Data UK DNO And TSO that validates CSV (`validate_csv`).

otherdata_uk_dno_and_tso / scripts/validate_declared.py · lines 1–39 of 39 · Entry point

What it does
Defines validate_csv, main. Uses libraries __future__, csv, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'dno'): 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.
Downstream impact
Used directly by 1 file: Audit Workflow (data_uk_dno_and_tso).
What it achieves
Its name says it validates declared. Defines `validate_csv`.
Why it matters
Run by Audit Workflow.
Application
data_uk_dno_and_tso · scripts · Python CLI
Uses
__future__, csv, pathlib
Used by
run by Audit Workflow (workflow run)
Produces
validate_csv, main
Defines here
validate_csv, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/validate_declared.py:1-39 · blob 9adb6d54c282a6e9090c1d8d27362b4488abc734 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations

import csv
from pathlib import Path

REQUIRED_PROVENANCE = {"schemaVersion", "methodState", "source", "provenance"}
DECLARED_DIR = Path("data/declared")


def validate_csv(path: Path) -> list[str]:
    errors: list[str] = []
    with path.open("r", encoding="utf-8", newline="") as fh:
        reader = csv.DictReader(fh)
        fields = set(reader.fieldnames or [])
        missing = REQUIRED_PROVENANCE - fields
        if missing:
            errors.append(f"{path}: missing columns {sorted(missing)}")
        for idx, row in enumerate(reader, start=2):
            for col in REQUIRED_PROVENANCE:
                if not (row.get(col) or "").strip():
                    errors.append(f"{path}:{idx}: empty {col}")
    return errors


def main() -> int:
    errors: list[str] = []
    for path in sorted(DECLARED_DIR.glob("*.csv")):
        errors.extend(validate_csv(path))
    if errors:
        print("Declared data validation failed:")
        for err in errors:
            print(f"- {err}")
        return 1
    print("Declared data validation passed")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Validate Schema Drift

A Python command-line tool in the scripts folder of Data UK DNO And TSO that works with required columns (`required_columns`) and header columns (`header_columns`).

ingestdata_uk_dno_and_tso / scripts/validate_schema_drift.py · lines 1–41 of 41 · Entry point

What it does
It loads data. Defines required_columns, header_columns, main. Uses libraries __future__, argparse, csv, json, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'dno'): 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: command-line arguments.
Downstream impact
Used directly by 1 file: Audit Workflow (data_uk_dno_and_tso).
What it achieves
Its name says it validates schema drift. Defines `required_columns` and `header_columns`.
Why it matters
Run by Audit Workflow.
Application
data_uk_dno_and_tso · scripts · Python CLI
Uses
__future__, argparse, csv, json, pathlib
Used by
run by Audit Workflow (workflow run)
Produces
required_columns, header_columns, main
Defines here
required_columns, header_columns, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data_uk_dno_and_tso@0f012179c2271a7d3bbb06a91af915d23bd9396b scripts/validate_schema_drift.py:1-41 · blob 0f73b288f50ee2dee362966ccf1f0e1f3bd3a620 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
from __future__ import annotations

import argparse
import csv
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def required_columns(schema_path: Path) -> set[str]:
    data = json.loads(schema_path.read_text(encoding="utf-8"))
    return set(data.get("required", []))


def header_columns(csv_path: Path) -> set[str]:
    with csv_path.open("r", encoding="utf-8", newline="") as fh:
        reader = csv.reader(fh)
        return set(next(reader, []))


def main() -> int:
    parser = argparse.ArgumentParser(description="Validate a CSV header against a JSON schema required list.")
    parser.add_argument("schema")
    parser.add_argument("csv_file")
    args = parser.parse_args()

    required = required_columns(ROOT / args.schema)
    columns = header_columns(ROOT / args.csv_file)
    missing = sorted(required - columns)
    if missing:
        print("Schema validation failed")
        for col in missing:
            print(f"- {col}")
        return 1
    print("Schema validation passed")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

MV Network

A JavaScript module in the engine folder of Energy Transition Simulator that reads routes (`readRoutes`) (units: kV, MVA), covering cables and transformers. It reads routes (`readRoutes`) and places network (`placeNetwork`).

Set aside from the main view: 98% of its lines are the same as energy-transition-simulator/202609280014/mod/engine/mv-network.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with MV Network; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9792 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/mv-network.mjs:1-127 e9f525f9bb51d517a255234dec1d9233f900b117
  • sha256 ce8964464b7440f21f46276e9845fb38d0265e68bfc16d0dfaffef292416db48
  • target sha256 498ed85b4f48de07de1a77aaf147082813f17aa4a6a6c35874c59c47228fec4a
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

ingestenergy-transition-simulator / prototype/mod/engine/mv-network.mjs · lines 1–127 of 127 · Not reached from any entry point (candidate for review) · pattern drawingToGround (shared by 3 files)

What it does
Defines 9 functions or classes, including equipmentSolids, box, solidLines, readRoutes, pt.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, transformers.
Downstream impact
Used directly by 1 file: Block Build (energy-transition-simulator).
What it achieves
The medium-voltage network from the stations to the grid, as equipment outlines with solids and cable routes, placed on the ground by the user.
Why it matters
Imported by Block Build.
Application
energy-transition-simulator · prototype/mod/engine · JavaScript module
Uses
Station (import), Plant Template (import)
Used by
imported by Block Build (import), mentioned in Standalone (comment link)
Produces
ROUTES_SCHEMA, EQUIPMENT, equipmentSolids, solidLines, readRoutes, drawingToGround, placeNetwork, cableLines
Defines here
equipmentSolids, box, solidLines, readRoutes, pt, drawingToGround, placeNetwork, kindOf, cableLines
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/mv-network.mjs:1-127 · blob f7a4e67e34739bb8375d8168d9dd58edac9e4fb4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/mv-network.mjs) at v12 commit 3adcee9 (file last changed 2c38e15). Modular star family: public #146440 equipmentSolids.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// mv-network.mjs: the medium-voltage network from the stations to the grid, as equipment outlines with solids
// and cable routes, placed on the ground by the user.
//
// Input is a block diagram (plant-template.mjs: nodes and links) and, optionally, a route file in DRAWING
// coordinates (schema mv-routes.v1: node positions and cable polylines in the units of some drawing). This module
// never knows where a real site is: the user places the drawing with a transform (a point on the ground, metres
// per drawing unit, a rotation). Without a route file the diagram is laid out on a plain grid instead.
//
// Equipment sizes are generic and rounded (ring main unit, station skid, switchroom, grid transformer in its bund,
// cable sealing-end structure at the connection); they are outlines for scale, not any maker's product.
// Pure: no DOM. Imports only the placement helper.

import { placer } from './station.mjs';
import { layoutDiagram } from './plant-template.mjs';

export const ROUTES_SCHEMA = 'mv-routes.v1';

// Footprint w (across) x d (along) and height h, metres.
export const EQUIPMENT = Object.freeze({
  rmu: { w: 1.6, d: 0.9, h: 1.8, label: 'ring main unit' },
  station: { w: 6.1, d: 2.5, h: 2.9, label: 'station skid: transformer, LV and MV switchgear' },
  switchboard: { w: 20, d: 8, h: 4.5, label: 'MV switchroom' },
  'grid-transformer': { w: 10, d: 6, h: 7, label: 'grid transformer', bund: { w: 16, d: 12, h: 0.6 } },
  poc: { w: 4, d: 4, h: 9, label: 'connection structure (cable sealing ends)' }
});

/** Solids for one item: the body, plus a bund wall ring where the kind has one. */
export function equipmentSolids(kind, at = [0, 0, 0], heading = 0, id = kind) {
  const e = EQUIPMENT[kind];
  if (!e) throw new Error(`mv-network: unknown equipment kind ${kind}`);
  const P = placer(at, heading), out = [];
  const box = (part, min, max) => out.push(P.box({ kind, part, id, min, max }));
  box('body', [-e.w / 2, -e.d / 2, 0], [e.w / 2, e.d / 2, e.h]);
  if (e.bund) {                                        // four low walls round the transformer, 0.25 m thick
    const { w, d, h } = e.bund, t = 0.25, x = w / 2, y = d / 2;
    box('bund', [-x, -y, 0], [x, -y + t, h]); box('bund', [-x, y - t, 0], [x, y, h]);
    box('bund', [-x, -y, 0], [-x + t, y, h]); box('bund', [x - t, -y, 0], [x, y, h]);
  }
  return out;
}

/** Edge lines (x, y, z pairs) of placed solids: the rotated footprint at the base and the top, and the uprights. */
export function solidLines(solids) {
  const v = [];
  for (const s of solids) {
    const q = s.quad, z0 = s.min[2], z1 = s.max[2];
    for (let i = 0; i < 4; i++) {
      const a = q[i], b = q[(i + 1) % 4];
      v.push(a[0], a[1], z0, b[0], b[1], z0, a[0], a[1], z1, b[0], b[1], z1, a[0], a[1], z0, a[0], a[1], z1);
    }
  }
  return new Float32Array(v);
}

/** Validate a route file. Returns { units, nodes: Map(id -> [x, y]), links: [{ from, to, points }] } or throws. */
export function readRoutes(json) {
  if (!json || json.schema !== ROUTES_SCHEMA) throw new Error(`mv-network: route file schema must be "${ROUTES_SCHEMA}"`);
  const pt = p => Array.isArray(p) && p.length >= 2 && p.every(Number.isFinite);
  const nodes = new Map();
  for (const [id, p] of Object.entries(json.nodes || {})) { if (!pt(p)) throw new Error(`mv-network: node ${id} needs [x, y]`); nodes.set(id, [p[0], p[1]]); }
  const links = (json.links || []).map((l, i) => {
    if (!l || typeof l.from !== 'string' || typeof l.to !== 'string') throw new Error(`mv-network: link ${i + 1} needs from and to`);
    const points = l.points || [];
    if (!points.every(pt)) throw new Error(`mv-network: link ${i + 1} has a bad point`);
    return { from: l.from, to: l.to, points: points.map(p => [p[0], p[1]]) };
  });
  return { units: String(json.units || 'drawing'), yDown: json.y_down === true, nodes, links };
}

/**
 * drawingToGround({ at, metresPerUnit, heading, yDown }) -> (x, y) -> [east, north] local metres.
 * The drawing's first axis runs along the heading's right-hand side; y down (as in PDF sheets) is flipped.
 */
export function drawingToGround({ at = [0, 0], metresPerUnit = 1, heading = 0, yDown = false } = {}) {
  const c = Math.cos(heading), s = Math.sin(heading);
  return (x, y) => {
    const u = x * metresPerUnit, v = (yDown ? -y : y) * metresPerUnit;
    return [at[0] + u * c + v * s, at[1] - u * s + v * c];
  };
}

/**
 * placeNetwork(diagram, { routes, at, heading, metresPerUnit, spacing, groundAt })
 * -> { equipment: [{ id, kind, label, solids }], cables: [{ from, to, kv, mva, normallyOpen, points: [[x, y, z]] }], missing }
 * With routes: node positions and polylines from the file. Without: layoutDiagram on a `spacing` metre grid.
 */
export function placeNetwork(diagram, { routes = null, at = [0, 0], heading = 0, metresPerUnit = 1, spacing = 40, groundAt = () => 0 } = {}) {
  const map = routes
    ? drawingToGround({ at, metresPerUnit, heading, yDown: routes.yDown })
    : drawingToGround({ at, metresPerUnit: spacing, heading, yDown: true });
  const where = new Map(), missing = [];
  if (routes) for (const [id, p] of routes.nodes) where.set(id, map(p[0], p[1]));
  else for (const n of layoutDiagram(diagram)) where.set(n.id, map(n.x, n.y));
  const kindOf = n => (n.kind in EQUIPMENT ? n.kind : null);
  const equipment = [];
  for (const n of diagram.nodes) {
    const k = kindOf(n), p = where.get(n.id);
    if (!k) continue;
    if (!p) { missing.push(n.id); continue; }
    equipment.push({ id: n.id, kind: k, label: n.label, solids: equipmentSolids(k, [p[0], p[1], groundAt(p[0], p[1])], heading, n.id) });
  }
  const drawn = new Map();
  if (routes) for (const l of routes.links) drawn.set(`${l.from}>${l.to}`, l.points);
  const cables = [];
  for (const l of diagram.links) {
    const a = where.get(l.from), b = where.get(l.to);
    if (!a || !b) continue;
    const path = drawn.get(`${l.from}>${l.to}`) || [...(drawn.get(`${l.to}>${l.from}`) || [])].reverse();
    const plan = path.length ? path.map(p => map(p[0], p[1])) : [a, b];
    const depth = l.kv >= 100 ? 1.2 : 0.9;
    cables.push({ from: l.from, to: l.to, kind: l.kind, kv: l.kv, mva: l.mva, normallyOpen: !!l.normallyOpen,
      points: plan.map(([x, y]) => [x, y, groundAt(x, y) - (l.kind === 'mv-bus' || l.kind === 'station-tee' ? 0 : depth)]) });
  }
  return { equipment, cables, missing };
}

/** Line pairs for the cables of a placed network (optionally only one kind). */
export function cableLines(cables, kind = null) {
  const v = [];
  for (const c of cables) {
    if (kind && c.kind !== kind) continue;
    for (let i = 1; i < c.points.length; i++) v.push(...c.points[i - 1], ...c.points[i]);
  }
  return new Float32Array(v);
}

Plant Feeders

A JavaScript module in the engine folder of Energy Transition Simulator that works with cables, 33kV and A roads, using IEC 60287.

Set aside from the main view: 98% of its lines are the same as solar-design-studio/202609271740-site-world/world/plant-feeders.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Plant Feeders; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9826 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/plant-feeders.mjs:1-140 41af101dc03f6e5bf650be8182a15e0a326dd9a2
  • sha256 bf3536f2f13c61316ddf5962349b9f4a5856296ea4501eb29fbbdc4bf7f46b34
  • target sha256 59e090e3caac223ce64f9879162cf7dce312fb3ea05eea32390e7951c1fcdbd0
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformenergy-transition-simulator / prototype/mod/engine/plant-feeders.mjs · lines 1–142 of 142 · Not reached from any entry point (candidate for review) · pattern routeFeeders (shared by 4 files)

What it does
It calculates cables, 33kV and A roads. Defines 11 functions or classes, including toSpine, roadPath, side, coverage, trenchFor.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, 33kV, A roads.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 3 files: Block MV (energy-transition-simulator); Cmd Model (energy-transition-simulator); Plant Layout (energy-transition-simulator).
What it achieves
It routes feeders (`routeFeeders`) and is built from the to spine helper (`toSpine`) and the road path helper (`roadPath`). The 33kV feeders of a laid-out plant, routed along its roads, with their trenches and cables. Its code works with 33 kV.
Why it matters
Imported by Block MV, Cmd Model and Plant Layout.
Application
energy-transition-simulator · prototype/mod/engine · JavaScript module
Uses
Cable Rating (import), Trench Plan (import)
Used by
imported by Block MV (import), imported by Cmd Model (import), imported by Plant Layout (import), mentioned in Standalone (comment link)
Produces
SECTION_FOR, CABLE_ALLOW, roadPath, coverage, trenchFor, routeFeeders, SECTION_WORDS, trenchRows
Defines here
toSpine, roadPath, side, coverage, trenchFor, routeFeeders, onRoad, add, dropOf, trenchRows, k
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/plant-feeders.mjs:1-142 · blob 2840ad84883288ff0fe1d474c61e2ab2bc4459c7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/plant-feeders.mjs) at v12 commit 3adcee9 (file last changed 604729d). Modular star family: public #146457 roadPath.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// plant-feeders.mjs: the 33 kV feeders of a laid-out plant, routed along its roads, with their trenches and cables.
//
// Each feeder of the plant template runs from its board in the substation compound along the access road, the
// spine and the branch tracks to its first station, then station to station. Routes stay on the road network
// (a comb: one spine, tracks off it), so every route is a set of intervals on a few straight lines. Where several
// circuits share a stretch they share a trench: one circuit in a single trefoil trench, two in a two-circuit
// trench, more in parallel trenches. Where a circuit turns across a road it goes in ducts.
// Cable lengths: route plus 3 % for snaking and 5 m at each end for terminations, three single cores a circuit.
// Voltage drop is worked out on the routed lengths (cable-rating.mjs), replacing the template's placeholder lengths;
// where it passes the limit, the segment that saves most drop per step is upsized, as the template does.
// Trench section ids are those of data/trench-sections.json: farmland cover (0.91 m) for the runs, ducts at crossings.
// The busiest hop's cable is checked by rating (trench-plan.mjs) alone and two circuits side by side as the section
// draws them. Pure: imports only the rating cartridges.

import { dropPercent, SIZES, build } from './cable-rating.mjs';
import { checkAsDrawn } from './trench-plan.mjs';

export const SECTION_FOR = Object.freeze({ one: '33kv-1-agri', two: '33kv-2-agri', crossing: '33kv-1-ducted' });
export const CABLE_ALLOW = Object.freeze({ slack: 0.03, tailM: 5, cores: 3 });

// A point on the road network: on a track (k, u), on the access road (u), or on the spine (v).
function toSpine(pt, net) {
  if (pt.line === 'track') return { parts: [{ key: 't' + pt.k, a: pt.u, b: net.us }], v: net.tracks[pt.k] };
  if (pt.line === 'access') return { parts: [{ key: 'a', a: pt.u, b: net.us }], v: net.cv };
  return { parts: [], v: pt.v };
}

/** Intervals from A to B along the roads, and how many times the route turns across a road. */
export function roadPath(A, B, net) {
  const side = pt => Math.sign(pt.u - net.us);
  if (A.line === 'track' && B.line === 'track' && A.k === B.k && side(A) === side(B)) return { parts: [{ key: 't' + A.k, a: A.u, b: B.u }], turns: 0 };
  const a = toSpine(A, net), b = toSpine(B, net);
  const parts = [...a.parts, ...(a.v !== b.v ? [{ key: 's', a: a.v, b: b.v }] : []), ...b.parts];
  return { parts: parts.filter(q => q.a !== q.b), turns: (a.parts.length ? 1 : 0) + (b.parts.length ? 1 : 0) };
}

/** Sweep a line's intervals into stretches with a constant circuit count: [{ a, b, c }]. */
export function coverage(intervals) {
  const ev = [];
  for (const { a, b } of intervals) { ev.push([Math.min(a, b), 1], [Math.max(a, b), -1]); }
  ev.sort((x, y) => x[0] - y[0] || x[1] - y[1]);
  const out = [];
  let c = 0, last = null;
  for (const [x, d] of ev) {
    if (c > 0 && last !== null && x > last) {
      const prev = out[out.length - 1];
      if (prev && prev.c === c && Math.abs(prev.b - last) < 1e-9) prev.b = x; else out.push({ a: last, b: x, c });
    }
    c += d; last = x;
  }
  return out;
}

/** Trench metres by section for a stretch of length L carrying c circuits. */
export function trenchFor(c, L, into) {
  const two = Math.floor(c / 2), one = c % 2;
  if (two) into[SECTION_FOR.two] = (into[SECTION_FOR.two] || 0) + two * L;
  if (one) into[SECTION_FOR.one] = (into[SECTION_FOR.one] || 0) + L;
  return into;
}

/**
 * routeFeeders(template, net, p) -> { feeders, pieces, trenchByType, trenchM, cableBySize, cableM, worstDropPct, crossings }
 * net: { us, cv, spine, access, tracks, stations: [{ id, u, v, k, track }] } in the layout frame.
 */
export function routeFeeders(tpl, net, p) {
  const at = new Map(net.stations.map(s => [s.id, s]));
  const board = net.access ? { line: 'access', u: net.access.u0 } : { line: 'spine', v: net.cv };
  const onRoad = s => ({ line: 'track', k: s.k, u: s.u });
  const byKey = new Map(), stubs = new Map();
  const add = (key, a, b) => { if (!byKey.has(key)) byKey.set(key, []); byKey.get(key).push({ a, b }); };
  const opts = { pf: tpl.params.powerFactor, soilKmW: tpl.params.soilKmW, kv: 33 };
  const cableBySize = {}, trenchByType = {};
  let crossings = 0, cableM = 0, worst = 0, upsized = 0;
  const dropOf = hops => hops.reduce((t, h) => t + dropPercent(h.areaMm2, h.lengthM, h.loadMVA, opts), 0);
  const feeders = tpl.feeders.map((f, fi) => {
    let from = board, fromStub = 0, fromId = null;
    const hops = f.chain.map((st, k) => {
      const s = at.get(st.id), to = onRoad(s), path = roadPath(from, to, net), stub = Math.abs(s.v - s.track);
      for (const q of path.parts) add(q.key, q.a, q.b);
      stubs.set(s.id, (stubs.get(s.id) || 0) + 1);
      if (fromId) stubs.set(fromId, stubs.get(fromId) + 1);
      crossings += path.turns;
      const road = path.parts.reduce((t, q) => t + Math.abs(q.b - q.a), 0), seg = f.segments[k];
      const hop = { from: fromId || f.board, to: s.id, areaMm2: seg.area, loadMVA: seg.loadMVA, lengthM: road + stub + fromStub, parts: path.parts };
      from = to; fromStub = stub; fromId = s.id;
      return hop;
    });
    for (let guard = 0; dropOf(hops) > tpl.params.vdropLimitPct && guard < 60; guard++) {
      const can = hops.filter(h => h.areaMm2 < SIZES.at(-1)).sort((a, b) => b.loadMVA * b.lengthM - a.loadMVA * a.lengthM)[0];
      if (!can) break;
      can.areaMm2 = SIZES[SIZES.indexOf(can.areaMm2) + 1]; upsized++;
    }
    for (const h of hops) {
      const cable = CABLE_ALLOW.cores * (h.lengthM * (1 + CABLE_ALLOW.slack) + 2 * CABLE_ALLOW.tailM);
      cableBySize[h.areaMm2] = (cableBySize[h.areaMm2] || 0) + cable; cableM += cable;
    }
    const drop = dropOf(hops);
    worst = Math.max(worst, drop);
    return { id: `F${fi + 1}`, board: f.board, hops, dropPct: drop, stations: f.chain.map(s => s.id) };
  });

  // Shared stretches: one trench per stretch, sized by the circuits in it.
  const pieces = [];
  let trenchM = 0;
  for (const [key, list] of byKey) for (const { a, b, c } of coverage(list)) {
    pieces.push({ key, a, b, c }); trenchFor(c, b - a, trenchByType); trenchM += b - a;
  }
  for (const [id, c] of stubs) {
    const s = at.get(id), L = Math.abs(s.v - s.track);
    if (L > 0) { pieces.push({ key: 'stub:' + id, a: s.track, b: s.v, c, u: s.u }); trenchFor(c, L, trenchByType); trenchM += L; }
  }
  const crossM = crossings * (p.spineWidthM + 2);
  if (crossM) { trenchByType[SECTION_FOR.crossing] = (trenchByType[SECTION_FOR.crossing] || 0) + crossM; trenchM += crossM; }
  // Rating of the shared trenches: the busiest hop's cable alone, and two such circuits at 450 mm centres.
  const busy = feeders.flatMap(f => f.hops).sort((a, b) => b.loadMVA - a.loadMVA)[0];
  let trenchRating = null;
  if (busy) {
    const spec = { loadA: busy.loadMVA * 1e6 / (Math.sqrt(3) * 33000), areaMm2: busy.areaMm2, odMm: build(busy.areaMm2).od };
    const env = { soilKmW: tpl.params.soilKmW || 1.2 }, one = checkAsDrawn('mv', 1, spec, 0.45, env), two = checkAsDrawn('mv', 2, spec, 0.45, env);
    trenchRating = { hop: `${busy.from} to ${busy.to}`, loadA: Math.round(spec.loadA), areaMm2: busy.areaMm2, one: one.utilisation, two: two.utilisation,
      ok: two.utilisation <= 1, basis: 'IEC 60287 method (own code), 0.91 m cover; indicative' };
  }
  return { feeders, pieces, trenchByType, trenchM, cableBySize, cableM, worstDropPct: worst, crossings, upsized, trenchRating,
    dropOk: worst <= tpl.params.vdropLimitPct + 1e-9 };
}

// Readout rows for the MV trenches and cables that add up, in words (user test H3). Each trench is counted: where more
// than two circuits share a stretch the trenches run side by side, so trench-km can exceed the route. Cable is single
// core (three per circuit, with slack and tails); circuit-km is a third of it.
export const SECTION_WORDS = Object.freeze({ [SECTION_FOR.one]: 'one 33 kV circuit, farmland (0.91 m cover)',
  [SECTION_FOR.two]: 'two 33 kV circuits', [SECTION_FOR.crossing]: 'road crossings, ducted' });
export function trenchRows(e, fmt = v => v.toFixed(2)) {
  const k = m => fmt(m / 1000), types = Object.entries(e.trenchByType || {}).filter(([, m]) => m > 0), total = types.reduce((t, [, m]) => t + m, 0);
  const rows = [['MV trenches', `${k(total)} trench-km, along ${k(e.trenchM)} km of route`]];
  for (const [id, m] of types) rows.push(['', `${SECTION_WORDS[id] || 'other trench'}: ${k(m)} trench-km`]);
  rows.push(['MV cable', `${k(e.cableM / CABLE_ALLOW.cores)} circuit-km (${k(e.cableM)} km of single-core cable)`]);
  for (const [a, m] of Object.entries(e.cableBySize || {}).sort((x, y) => x[0] - y[0])) rows.push(['', `${a} mm² aluminium: ${k(m / CABLE_ALLOW.cores)} circuit-km`]);
  return { rows, trenchKm: total / 1000 };
}

Single-Line Diagram (SLD) Connect

A JavaScript module in the engine folder of Energy Transition Simulator that works with cables, substations, overhead lines (OHL) and 132kV.

Set aside from the main view: 96% of its lines are the same as solar-design-studio/202609271552-site-world/world/sld-connect.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Single-Line Diagram (SLD) Connect; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9565 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271552-site-world/world/sld-connect.mjs:1-55 6c117c539568a4cdba17bdd8f65174c16f6068a5
  • sha256 b6ea8fa994884566f914a4ccb9dc51eea2b53fdff6d43960c7a6addce4981c7a
  • target sha256 d74272f971286be44fdf1d40a767244e53425440c25d75a13e3f7721b27ea4f9
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

electricalenergy-transition-simulator / prototype/mod/engine/sld-connect.mjs · lines 1–57 of 57 · Not reached from any entry point (candidate for review) · pattern chooseConnection (shared by 3 files)

What it does
It calculates cables, substations, overhead lines (OHL) and 132kV. Defines nearest, km, kvForMW, chooseConnection.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, substations, overhead lines (OHL), 132kV, 400kV, 275kV.
Inputs & outputs
Voltage levels named: 400kV, 275kV, 132kV, 33kV.
Downstream impact
Used directly by 2 files: Cmd Trench (energy-transition-simulator); Connect Here (energy-transition-simulator).
What it achieves
It is built from the nearest step (`nearest`), the kV for MW helper (`kvForMW`) and the choose connection helper (`chooseConnection`). Which grid connection a plant gets, from its size and what is near it. Its code works with 132 kV, 400 kV and 275 kV.
Why it matters
Imported by Cmd Trench and Connect Here.
Application
energy-transition-simulator · prototype/mod/engine · JavaScript module
Uses
none found
Used by
imported by Cmd Trench (import), imported by Connect Here (import)
Produces
CONNECT_RULES, CONNECT_LABEL, kvForMW, chooseConnection
Defines here
nearest, km, kvForMW, chooseConnection
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/sld-connect.mjs:1-57 · blob 62459c44b146aef67bc45301848e150a1a5e640f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/sld-connect.mjs) at v12 commit 3adcee9 (file last changed 219d82e). Modular star family: public #148022 kvForMW.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// sld-connect.mjs: which grid connection a plant gets, from its size and what is near it. Editable, illustrative rules;
// the network operator decides the real connection. One connection object serves the solar block, the single-line
// diagram and Follow (user test H4).
//   The voltage follows the plant's size: up to smallMaxMW at 33 kV, up to dnoMaxMW at 132 kV, up to midMaxMW at 275 kV,
//   above that 400 kV (a block with its own grid transformer connects at 132 kV at least).
//   275 and 400 kV: only through a bay at a substation of that voltage (within transSearchM), by fully ducted, unjointed
//   HV cable; never a tee into a transmission line.
//   132 kV and below: a cable to the nearest network operator substation of that voltage (within dnoSearchM); else a
//   tee into a line of that voltage within teeM (teeMaxKv at most); else no nearby connection (an assumed landing that
//   says so).
// Pure.

export const CONNECT_RULES = Object.freeze({ smallMaxMW: 30, dnoMaxMW: 150, midMaxMW: 400, teeM: 3000, teeMaxKv: 132, dnoSearchM: 30000,
  transSearchM: 40000 });
export const CONNECT_LABEL = 'Connection chosen by illustrative rules (size and distance); the network operator decides the real one.';

const nearest = (list, at, ok) => list.filter(x => ok(x) && Number.isFinite(x.e) && Number.isFinite(x.n))
  .map(x => ({ ...x, d: Math.hypot(x.e - at[0], x.n - at[1]) })).sort((a, b) => a.d - b.d)[0] || null;
const km = m => `${(m / 1000).toFixed(1)} km`;

/** The connection voltage for a plant of mw: 33, 132, 275 or 400 kV; minKv raises it (132 for a block with its own grid transformer). */
export function kvForMW(mw, { minKv = 0, rules = {} } = {}) {
  const R = { ...CONNECT_RULES, ...rules };
  const kv = mw <= R.smallMaxMW ? 33 : mw <= R.dnoMaxMW ? 132 : mw <= R.midMaxMW ? 275 : 400;
  return [33, 132, 275, 400].find(v => v >= Math.max(kv, minKv)) || 400;
}

/**
 * chooseConnection({ mw, at: [e, n], subs: [{ e, n, kv }], towers: [{ e, n, kv }], kv?, minKv?, rules }) ->
 *   { rule, text, kv, connection: 'cable' | 'ohl-tee' | 'none', route: 'cable' | 'overhead line' | null,
 *     landing: { e, n, kv, real, kind: 'gis-bay' | 'dno-sub' | 'tower' } | null }
 * kv: the voltage already fixed (the placed block's grid transformer); else by size.
 */
export function chooseConnection({ mw, at, subs = [], towers = [], kv: fixed = null, minKv = 0, rules = {} }) {
  const R = { ...CONNECT_RULES, ...rules }, kv = fixed || kvForMW(mw, { minKv, rules });
  const size = `${Math.round(mw)} MW`;
  if (kv >= 275) {
    const s = nearest(subs, at, x => x.kv === kv);
    if (s && s.d <= R.transSearchM) return { rule: `bay-${kv}`, kv, connection: 'cable', route: 'cable',
      text: `${size} at ${kv} kV: ducted, unjointed HV cable to a bay at the ${kv} kV substation ${km(s.d)} away (no tee at transmission voltage)`,
      landing: { e: s.e, n: s.n, kv, real: true, kind: 'gis-bay' } };
    return { rule: 'none', kv, connection: 'none', route: null, landing: null,
      text: `${size} at ${kv} kV: no ${kv} kV substation within ${km(R.transSearchM)}; the landing shown is an assumed point, not a substation` };
  }
  const s = nearest(subs, at, x => x.kv === kv);
  if (s && s.d <= R.dnoSearchM) return { rule: `dno-${kv}`, kv, connection: 'cable', route: 'cable',
    text: `${size} at ${kv} kV: cable to the nearest ${kv} kV network operator substation, ${km(s.d)} away`,
    landing: { e: s.e, n: s.n, kv, real: true, kind: 'dno-sub' } };
  const t = kv <= R.teeMaxKv ? nearest(towers, at, x => x.kv === kv) : null;
  if (t && t.d <= R.teeM) return { rule: `tee-${kv}`, kv, connection: 'ohl-tee', route: 'overhead line',
    text: `${size} at ${kv} kV: no ${kv} kV substation within ${km(R.dnoSearchM)}; overhead tee into the ${kv} kV line ${km(t.d)} away (illustrative)`,
    landing: { e: t.e, n: t.n, kv, real: true, kind: 'tower' } };
  return { rule: 'none', kv, connection: 'none', route: null, landing: null,
    text: `${size} at ${kv} kV: no nearby connection at ${kv} kV; the landing shown is an assumed point, not a substation` };
}

Single-Line Diagram (SLD) Rules

A JavaScript module in the engine folder of Energy Transition Simulator that works with cables, transformers and battery storage (BESS), using IEC 60502-2 and BS 7671.

Set aside from the main view: 97% of its lines are the same as solar-design-studio/202609271853-site-world/world/sld-rules.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Single-Line Diagram (SLD) Rules; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9733 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/sld-rules.mjs:1-93 b27d1862239e37c3517715c170d703a643f6ca81
  • sha256 a7b3a742bf99063a303006631ea50140959aa8d1c3aec3551ef675137179a326
  • target sha256 cea903f4aaf404e1a5163ed5b860b79459f01e6d731e1bf3f183a59390943703
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

electricalenergy-transition-simulator / prototype/mod/engine/sld-rules.mjs · lines 1–95 of 95 · Not reached from any entry point (candidate for review) · pattern isolationChecks (shared by 3 files)

What it does
It calculates cables, transformers and battery storage (BESS). Defines groupFactor, economicSize, cost, isolationChecks, zOf.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, transformers, battery storage (BESS), 33kV.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Block MV (energy-transition-simulator).
What it achieves
It groups factor (`groupFactor`) and is built from the economic size helper (`economicSize`) and the cost step (`cost`). The generic electrical rules the single-line diagram generator shares (`sld-plant.mjs`, `block-mv.mjs`, `sld-graph.mjs`): group factors for circuits sharing a trench, an economic step on top of the technical cable size, the switching and protection devices of each functional way. Its code works with 33 kV.
Why it matters
Imported by Block MV.
Application
energy-transition-simulator · prototype/mod/engine · JavaScript module
Uses
Cable Rating (import), Elec Style (import), Measure Format (import)
Used by
imported by Block MV (import)
Produces
SLD_LABEL, groupFactor, ECONOMIC, PALETTE, economicSize, DEVICES, INVERTER_ISOLATION, isolationChecks, SLD_DEFAULTS, C, zOf
Defines here
groupFactor, economicSize, cost, isolationChecks, zOf
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/sld-rules.mjs:1-95 · blob d12a0697978ff6133cdb3acb912363afdeac3789 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/sld-rules.mjs) at v12 commit 3adcee9 (file last changed 9b1ffad). Modular star family: public #148057 economicSize.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// sld-rules.mjs: the generic electrical rules the single-line diagram generator shares (sld-plant.mjs, block-mv.mjs,
// sld-graph.mjs): group factors for circuits sharing a trench, an economic step on top of the technical cable size,
// the switching and protection devices of each functional way, and the assumed impedances and source.
// Every value here is generic practice or a public standard, or is marked assumed. Illustrative, not a design for any
// site. Pure: imports only the cable rating.

import { rating, SIZES } from './cable-rating.mjs';

export const SLD_LABEL = 'Illustrative, not a design for any site.';

// Group factors for 33 kV trefoil circuits laid direct side by side, about 0.4-0.45 m apart: approximate values in the
// style of the IEC 60502-2 annex tables (a rating study replaces them). Index = circuits in the trench.
const GROUP = [1, 1, 0.87, 0.78, 0.73, 0.69, 0.66, 0.64, 0.62];
export const groupFactor = n => GROUP[Math.max(1, Math.min(GROUP.length - 1, Math.round(n) || 1))];

// Economic step (assumed unit costs, not any supplier's): capitalised I2R loss against a cable cost that grows with the
// conductor area. Loss hours and the present-worth factor are generic solar figures; money is in plain cost units.
export const ECONOMIC = Object.freeze({ lossHours: 1100, pricePerMWh: 60, years: 25, rate: 0.06, costPerM: 30, costPerMm2M: 0.09 });
export const PALETTE = Object.freeze([120, 185, 300, 500, 630, 800, 1000]); // a small stock of sizes, not the full series

/**
 * economicSize(technicalArea, mva, lengthM, opts) -> the palette size, at or above the technical size, whose cable cost
 * plus capitalised losses is least. opts: cable-rating options plus { economic }.
 */
export function economicSize(area, mva, lengthM, opts = {}) {
  const e = { ...ECONOMIC, ...(opts.economic || {}) }, kv = opts.kv || 33, I = mva * 1e6 / (Math.sqrt(3) * kv * 1000);
  const pw = (1 - (1 + e.rate) ** -e.years) / e.rate;
  const cost = a => {
    const R = rating(a, opts).R;                               // ohm per metre at the rated temperature (conservative)
    return lengthM * (e.costPerM + e.costPerMm2M * a * 3) + 3 * I * I * R * lengthM * e.lossHours / 1e6 * e.pricePerMWh * pw;
  };
  const list = PALETTE.filter(a => a >= area && SIZES.includes(a));
  if (!list.length) return area;
  return list.reduce((best, a) => (cost(a) < cost(best) - 1e-9 ? a : best), list[0]);
}

// Devices of each functional way, as the diagram draws them (state: closed unless marked open).
export const DEVICES = Object.freeze({
  'rmu-in': ['switch-disconnector', 'earth-switch'],
  'rmu-out': ['switch-disconnector', 'earth-switch'],
  'rmu-tx': ['circuit-breaker', 'protection 50/51 50N/51N', 'earth-switch'],
  'lv-main': ['main breaker', 'insulation monitor', 'surge protection', 'meter'],
  'lv-way': ['breaker'],                                       // one per inverter; no local isolator at the inverter end
  'mv-way': ['vacuum circuit breaker', 'protection 50/51 50N/51N', 'earth-switch'],
  'mv-incomer': ['vacuum circuit breaker', 'protection 51 87T'],
  'bus-tie': ['vacuum circuit breaker (normally open)'],
  'hv-bay': ['disconnector', 'earth switch', 'surge arresters', 'current and voltage transformers'],
  'gis-bay': ['gas-insulated circuit breaker', 'disconnector', 'earth switch'],
  'earthing': ['earthing transformer (zigzag)', 'neutral earthing resistor']
});

// Isolation at the inverter from every source that feeds it (BS 7671 537 and 712.537; IEC 62548-1 isolation clauses):
// each source present needs a named means of isolation at the inverter. Defaults as the diagram draws them: the PV side's
// DC switch-disconnector is taken from the inverter's datasheet (assumed); the AC side has only the board breaker, no
// local isolator at the inverter end; no BESS. A plain check with editable inputs, not a design.
export const INVERTER_ISOLATION = Object.freeze({ pv: 'DC switch-disconnector in the inverter (datasheet, assumed)', grid: null, bess: undefined });
export function isolationChecks(at = INVERTER_ISOLATION) {
  const WORDS = { pv: 'PV (DC)', grid: 'grid (AC)', bess: 'battery (BESS)' };
  return Object.entries(WORDS).filter(([k]) => at[k] !== undefined).map(([k, w]) => ({ source: w, ok: !!at[k], device: at[k] || 'none at the inverter' }));
}

// Assumed impedances and the grid source. Transformer impedances sit inside the usual ranges (station 6-10 %).
export const SLD_DEFAULTS = Object.freeze({
  sBaseMVA: 100, c: 1.1,                       // IEC 60909 voltage factor for maximum fault current
  sourceKA: null, sourceXR: 14,                // grid fault level at the landing: set, or by voltage below (assumed)
  sourceKAByKv: { 400: 40, 275: 40, 132: 25, 33: 12.5 },
  stZPct: 7, stXR: 10, stVector: 'Dy11y11',    // station transformer, one unit with a list of LV windings
  gtZPct: 14, gtXR: 40, gtVector: 'YNd11', gtHvNeutral: 'solid', gtTwoLvFromMVA: 120,
  tapRange: 0.10, tapStep: 0.0125, tapTarget: 1.0,  // grid transformer on-load tap changer (illustrative, editable)
  hvCableOhmKm: [0.012, 0.19],                 // single-core HV cable, large copper (assumed)
  ohlOhmKm: [0.03, 0.3],                       // overhead line option (assumed)
  lvXOhmKm: 0.08,                              // single-core LV cable reactance (assumed)
  busPu: [1e-6, 1e-5],                         // busbars and closed switching devices
  nerA: 1000, powerFactor: 0.95,               // NER limit (assumed); export at 0.95 for the drop (reactive duty)
  module: { w: 660, vmp: 38.6, imp: 17.1, voc: 45.9 }, dcAreaMm2: 6, dcOhmKm20: 3.08, dcTempC: 70
});

/** Complex numbers as [re, im]: the few operations the solvers need. */
export const C = Object.freeze({
  add: (a, b) => [a[0] + b[0], a[1] + b[1]], sub: (a, b) => [a[0] - b[0], a[1] - b[1]],
  mul: (a, b) => [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]],
  div: (a, b) => { const d = b[0] * b[0] + b[1] * b[1]; return [(a[0] * b[0] + a[1] * b[1]) / d, (a[1] * b[0] - a[0] * b[1]) / d]; },
  conj: a => [a[0], -a[1]], abs: a => Math.hypot(a[0], a[1])
});

/** An impedance of |z| per unit at ratio X/R, as [r, x]. */
export const zOf = (mag, xr) => { const r = mag / Math.sqrt(1 + xr * xr); return [r, r * xr]; };

// Every electrical readout ends with this line (earthing, the single-line diagram, Follow, the check HUD's working).
export { ELEC_FOOTER } from './elec-style.mjs';   // one source for the words

// Quantities by the one number rule (measure-format.mjs): significant figures, one dash for none.
export { fmtQ } from './measure-format.mjs';