In this section
- Measure storage · seed-data / experiments/explain-cable-screen-change/original/measure.mjs lines 1–42
- Reuse ingest · seed-data / experiments/explain-cable-screen-change/original/reuse.mjs lines 1–97
- Standalone ingest · seed-data / experiments/explain-cable-screen-change/original/standalone.mjs lines 1–115
- Sandbox — Cable electrical · testcode / sandbox/202609060432/cable/app.js lines 1–446
Measure
A JavaScript module in the original folder of Seed Data that reads acceptance.
storageseed-data / experiments/explain-cable-screen-change/original/measure.mjs · lines 1–42 of 42 · Not reached from any entry point (candidate for review)
- What it does
- It loads acceptance. Uses libraries node:child_process, node:fs, node:url, node:perf_hooks. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: JSON file acceptance.json; command-line arguments.
- What it achieves
- It reads `acceptance.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- seed-data · experiments/explain-cable-screen-change/original · JavaScript module
- Uses
- node:child_process, node:fs, node:url, node:perf_hooks
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/explain-cable-screen-change/original/measure.mjs:1-42 · blob 87634e6d361194b53d25c1e59fba43880b8bd736 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { performance } from 'node:perf_hooks';
const joint = JSON.parse(readFileSync(new URL('acceptance.json', import.meta.url))).cases.find(row => row.id === 'joint');
const repeats = 8;
const [, , mode, arm] = process.argv;
if (mode === '--worker') {
const start = performance.now();
const { explain } = await import(new URL(arm, import.meta.url));
const initMs = performance.now() - start;
const first = performance.now();
assert.equal(explain(joint.input), joint.expected);
const firstMs = performance.now() - first;
const warm = performance.now();
for (let i = 0; i < repeats; i++) assert.equal(explain(joint.input), joint.expected);
console.log(JSON.stringify({ arm, initMs, firstMs, repeatedMs: performance.now()-warm }));
} else {
assert(mode, 'Pass a new measurement output file');
const samples = [];
const here = fileURLToPath(import.meta.url);
for (let i = 0; i < 5; i++) {
const order = i % 2 ? ['standalone.mjs','reuse.mjs'] : ['reuse.mjs','standalone.mjs'];
for (const name of order) {
const start = performance.now();
const child = execFileSync(process.execPath,[here,'--worker',name],{encoding:'utf8'});
samples.push({ ...JSON.parse(child), workerWallMs: performance.now()-start });
}
}
const medians = {};
for (const name of ['reuse.mjs','standalone.mjs']) {
const rows = samples.filter(row => row.arm === name);
medians[name] = Object.fromEntries(['initMs','firstMs','repeatedMs','workerWallMs'].map(key =>
[key, rows.map(row => row[key]).sort((a,b)=>a-b)[2]]));
}
const report = { repeats, workersPerArm: 5, scenario: joint.id, medians, samples,
scope: 'Fresh Node processes interleaved. Init includes exact pins and Git source checks for reuse. Each reuse call starts one Python adapter and verifies its generated evidence. The repeated interval excludes Node startup and includes the assertion in both arms. Energy unmeasured.' };
writeFileSync(mode, JSON.stringify(report,null,2)+'\n',{flag:'wx'});
console.log(JSON.stringify(medians,null,2));
}
Reuse
A JavaScript module in the original folder of Seed Data that reads cables, using SHA-256.
ingestseed-data / experiments/explain-cable-screen-change/original/reuse.mjs · lines 1–97 of 97 · Not reached from any entry point (candidate for review) · pattern explain (shared by 7 files)
- What it does
- It loads cables. Defines 8 functions or classes, including num, bounds, validate, result, describe. Uses libraries node:crypto, node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): 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.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- It is built from the result step (`result`), the describe step (`describe`) and the exact step (`exact`). Defines `num`, `bounds`, `validate` and 5 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- seed-data · experiments/explain-cable-screen-change/original · JavaScript module
- Uses
- Evidence Adapter (script call), node:crypto, node:fs, node:path, node:url
- Used by
- none found
- Produces
- explain
- Defines here
- num, bounds, validate, result, describe, exact, explain, metres
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/explain-cable-screen-change/original/reuse.mjs:1-97 · blob a60c742f934bc5c0a4cb52837dcd49ee6bc03513 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: none · canonical: duplicate_candidate
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const root = new URL('../reduction-publish/experiments/economical-seeds/next-invention/', import.meta.url);
const pinned = {
'reduction/projected.mjs': 'e3ac6314fcefc1351c6c6b3c569e630bf96f6160d66f8392c7a3f7ad36615c3f',
'cable-screen/route-screen.mjs': '315ab43679156e2ba19516e7d76526bbd305dc78bf2a02ed8094cb760139f7b8',
};
for (const [rel, digest] of Object.entries(pinned)) {
const actual = createHash('sha256').update(readFileSync(new URL(rel, root))).digest('hex');
if (actual !== digest) throw new Error('Screener source differs from pin');
}
const { prepareProjectedScreen } = await import(new URL('reduction/projected.mjs', root));
const screen = await prepareProjectedScreen(process.env.EXPLAIN_ENGINE || 'ventus-grid-engine');
const adapter = fileURLToPath(new URL('./evidence_adapter.py', import.meta.url));
const evidencePath = fileURLToPath(new URL('reduction/sufficiency/identify_missing_evidence.py', root));
const num = v => Number(v.toFixed(6));
const bounds = (n, low, high) => Number.isFinite(n) && n >= low && n <= high;
function validate(input) {
if (!input || typeof input !== 'object' || Object.keys(input).sort().join() !== 'after,before') {
throw new Error('Expected before and after scenarios');
}
for (const side of [input.before, input.after]) {
if (!side || typeof side !== 'object' ||
Object.keys(side).some(key => key !== 'currentA' && key !== 'lengthM') ||
!bounds(side.currentA, 1, 1000) || (Object.hasOwn(side, 'lengthM') && !bounds(side.lengthM, 1000, 10000))) {
throw new Error('Invalid current or declared installed length');
}
}
}
function result(side) {
const route = { id: 'fictional', straightLineKm: 1, crossings: [] };
if (Object.hasOwn(side, 'lengthM')) route.installedLengthM = side.lengthM;
return screen({
electrical: { currentA: side.currentA, nominalVolts: 1000, resistanceOhmPerKm: 0.2,
reactanceOhmPerKm: 0.1, powerFactor: 0.8, phases: 'single' },
options: [route],
}).options[0].electrical;
}
const describe = r => r.status === 'computed' ? num(r.dropV) + ' V and ' + num(r.lossW) + ' W' : 'unavailable';
const exact = (a,b) => a.dropV === b.dropV && a.lossW === b.lossW;
export function explain(input) {
validate(input);
const {before, after} = input, changes = [];
const length = before.lengthM !== after.lengthM, current = before.currentA !== after.currentA;
const metres = v => v === undefined ? 'unknown' : num(v) + ' m';
if (length) changes.push('Installed length ' + metres(before.lengthM) + ' to ' + metres(after.lengthM));
if (current) changes.push((length ? 'current ' : 'Current ') + num(before.currentA) + ' A to ' + num(after.currentA) + ' A');
const coverage = JSON.parse(execFileSync(process.env.EXPLAIN_PYTHON || 'python', [adapter, evidencePath], {
input: JSON.stringify({before_length: Object.hasOwn(before,'lengthM'), after_length: Object.hasOwn(after,'lengthM')}),
encoding: 'utf8', maxBuffer: 16384,
}));
const a = result(before), b = result(after);
if (coverage.before_length !== (a.status === 'computed') || coverage.after_length !== (b.status === 'computed')) {
throw new Error('Evidence and screener disagree');
}
let difference, reason;
if (!coverage.before_length || !coverage.after_length) {
difference = 'Before: ' + describe(a) + '. After: ' + describe(b) + '.';
const missing = !coverage.before_length && !coverage.after_length ? 'Both cases need'
: coverage.before_length ? 'The after case needs' : 'The before case needs';
reason = missing + ' a declared installed length. The change cannot be explained.';
} else {
difference = 'Voltage drop ' + num(a.dropV) + ' V to ' + num(b.dropV)
+ ' V; loss ' + num(a.lossW) + ' W to ' + num(b.lossW) + ' W.';
if (!length && !current) {
if (!exact(a,b)) throw new Error('Identical inputs produced different results');
reason = 'The model returned the same result. There is no change to explain.';
} else if (length && current) {
const l = result({...before, lengthM: after.lengthM}), c = result({...before, currentA: after.currentA});
reason = 'With the before case as the baseline, length alone produced ' + describe(l)
+ '; current alone produced ' + describe(c) + '. These replays do not establish a unique split of the joint change.';
} else {
const replay = result(length ? {...before, lengthM: after.lengthM} : {...before, currentA: after.currentA});
if (!exact(replay,b)) throw new Error('Controlled replay failed to reproduce result');
reason = 'Changing only ' + (length ? 'installed length' : 'current') + ' in the model reproduced the result.';
}
}
return 'Inputs: ' + (changes.length ? changes.join('; ') + '.' : 'No changes.')
+ '\nResult: ' + difference + '\nEvidence: ' + reason;
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
try {
console.log(explain(JSON.parse(readFileSync(process.argv[2], 'utf8'))));
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}
Standalone
A JavaScript module in the original folder of Seed Data that checks object (`checkObject`) (units: Ω). It checks object (`checkObject`) and checks case (`checkCase`).
ingestseed-data / experiments/explain-cable-screen-change/original/standalone.mjs · lines 1–115 of 115 · Not reached from any entry point (candidate for review) · pattern numberInRange (shared by 4 files)
- What it does
- It loads data. Defines 7 functions or classes, including checkObject, numberInRange, checkCase, model, format. Uses libraries node:url. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- Defines `checkObject`, `numberInRange`, `checkCase` and 4 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- seed-data · experiments/explain-cable-screen-change/original · JavaScript module
- Uses
- node:url
- Used by
- none found
- Produces
- explain
- Defines here
- checkObject, numberInRange, checkCase, model, format, amount, explain
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/explain-cable-screen-change/original/standalone.mjs:1-115 · blob a72e2ffe8d37cc3e23205146854bbab6596b8dfd · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
const RESISTANCE_OHM_PER_KM = 0.2;
const REACTANCE_OHM_PER_KM = 0.1;
const POWER_FACTOR = 0.8;
const REACTIVE_FACTOR = Math.sqrt(1 - POWER_FACTOR * POWER_FACTOR);
function checkObject(value, fields) {
if (typeof value !== 'object' || value === null || Array.isArray(value)
|| Reflect.ownKeys(value).some(key => !fields.includes(key))) {
throw new TypeError('Unexpected input fields or shape.');
}
}
function numberInRange(value, lower, upper, field) {
if (!Number.isFinite(value) || value < lower || value > upper) {
throw new RangeError(field + ' must be a finite number in [' + lower + ', ' + upper + '].');
}
}
function checkCase(value) {
checkObject(value, ['currentA', 'lengthM']);
if (!Object.hasOwn(value, 'currentA')) {
throw new TypeError('Each case requires currentA.');
}
numberInRange(value.currentA, 1, 1000, 'Current');
if (!Object.hasOwn(value, 'lengthM')) {
return { currentA: value.currentA };
}
numberInRange(value.lengthM, 1000, 10000, 'Installed length');
return { currentA: value.currentA, lengthM: value.lengthM };
}
function model({ currentA, lengthM }) {
if (lengthM === undefined) {
return undefined;
}
const kilometres = lengthM / 1000;
return {
voltage: 2 * currentA * kilometres
* (RESISTANCE_OHM_PER_KM * POWER_FACTOR + REACTANCE_OHM_PER_KM * REACTIVE_FACTOR),
loss: 2 * currentA * currentA * RESISTANCE_OHM_PER_KM * kilometres,
};
}
function format(value, unit) {
return value === undefined ? 'unknown' : Number(value.toFixed(6)) + ' ' + unit;
}
function amount(result) {
return result ? format(result.voltage, 'V') + ' and ' + format(result.loss, 'W') : 'unavailable';
}
export function explain(input) {
checkObject(input, ['before', 'after']);
if (!Object.hasOwn(input, 'before') || !Object.hasOwn(input, 'after')) {
throw new TypeError('Input requires before and after cases.');
}
const before = checkCase(input.before);
const after = checkCase(input.after);
const lengthChanged = before.lengthM !== after.lengthM;
const currentChanged = before.currentA !== after.currentA;
const changes = [];
if (lengthChanged) {
changes.push('Installed length ' + format(before.lengthM, 'm') + ' to ' + format(after.lengthM, 'm'));
}
if (currentChanged) {
const label = lengthChanged ? 'current' : 'Current';
changes.push(label + ' ' + format(before.currentA, 'A') + ' to ' + format(after.currentA, 'A'));
}
const inputs = 'Inputs: ' + (changes.length ? changes.join('; ') + '.' : 'No changes.');
const original = model(before);
const changed = model(after);
if (!original || !changed) {
const subject = !original && !changed ? 'Both cases need' : (!original
? 'The before case needs' : 'The after case needs');
return [
inputs,
'Result: Before: ' + amount(original) + '. After: ' + amount(changed) + '.',
'Evidence: ' + subject + ' a declared installed length. The change cannot be explained.',
].join('\n');
}
const result = 'Result: Voltage drop ' + format(original.voltage, 'V') + ' to '
+ format(changed.voltage, 'V') + '; loss ' + format(original.loss, 'W') + ' to '
+ format(changed.loss, 'W') + '.';
let evidence;
if (lengthChanged && currentChanged) {
const lengthOnly = model({ ...before, lengthM: after.lengthM });
const currentOnly = model({ ...before, currentA: after.currentA });
evidence = 'With the before case as the baseline, length alone produced ' + amount(lengthOnly)
+ '; current alone produced ' + amount(currentOnly)
+ '. These replays do not establish a unique split of the joint change.';
} else if (lengthChanged || currentChanged) {
const changedInput = lengthChanged ? 'installed length' : 'current';
evidence = 'Changing only ' + changedInput + ' in the model reproduced the result.';
} else {
evidence = 'The model returned the same result. There is no change to explain.';
}
return [inputs, result, 'Evidence: ' + evidence].join('\n');
}
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
try {
if (process.argv.length !== 3) {
throw new TypeError('Provide one JSON input file.');
}
const input = JSON.parse(readFileSync(process.argv[2], 'utf8').replace(/^\uFEFF/, ''));
console.log(explain(input));
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}
Sandbox — Cable
A JavaScript file in Testcode that clamps integer (`clampInteger`), formats mm (`formatMm`), gets min burial depth (`getMinBurialDepth`) and draws on a canvas (units: mm², kV).
electricaltestcode / sandbox/202609060432/cable/app.js · lines 1–446 of 1213 · version 2026-09-06 04:32 · Not reached from any entry point (candidate for review) · pattern normaliseBurialDepthFieldOnBlur (shared by 4 files)
- What it does
- It draws cables. Defines 50 functions or classes, including byId, clampInteger, formatMm, effectiveGap, getMinBurialDepth. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): 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, 1500V.
- Inputs & outputs
- Out: canvas drawing. Voltage levels named: 1500V.
- What it achieves
- It clamps integer (`clampInteger`), formats mm (`formatMm`) and gets min burial depth (`getMinBurialDepth`). Defines `byId`, `clampInteger`, `formatMm` and 47 more. It responds to focus, click and touchend events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/202609060432/cable · script
- Uses
- none found
- Used by
- none found
- Produces
- byId, clampInteger, formatMm, effectiveGap, getMinBurialDepth, getVoltageRuntimeMeta, getSelectedCore, getBurialDepthForComputation, normaliseBurialDepthFieldOnBlur, normaliseIntegerFields, getInputs, populateFormationOptions
- Defines here
- byId, clampInteger, formatMm, effectiveGap, getMinBurialDepth, getVoltageRuntimeMeta, getSelectedCore, getBurialDepthForComputation, normaliseBurialDepthFieldOnBlur, normaliseIntegerFields, getInputs, populateFormationOptions, syncFormationToLookupCore, populateVoltageOptions, getLookupKey, lookupOD, getVoltageDisplayName, getConductorShapeText, populateLookupCSA, applyLookup, updateFromLookup, getGroupGeometry, computeLayout, buildReview
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609060432/cable/app.js:1-446 · blob d23e32effebad9a79a8469ca1792c6b0a06fd3be · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
const OD_CONFIRMED = { ...OD_LV, ...OD_MV_HV, ...OD_SOLAR };
const appState = {
inputs: null,
layout: null,
review: null,
snapshotText: "",
previousSpacing: { h: 150, v: 150 }
};
function byId(id) { return document.getElementById(id); }
function clampInteger(value, fallback, minValue) {
const num = Number(value);
if (!Number.isFinite(num)) return fallback;
return Math.max(Math.round(num), minValue);
}
function formatMm(v) { return `${Math.round(v)} mm`; }
function effectiveGap(basis, spacing, od) {
if (basis === "touching") return 0;
if (basis === "centre_to_centre") return Math.max(spacing - od, 0);
return spacing;
}
function getMinBurialDepth(serviceType) {
if (!MIN_BURIAL_DEPTHS || typeof MIN_BURIAL_DEPTHS !== "object") return 0;
return MIN_BURIAL_DEPTHS[serviceType] || 0;
}
function getVoltageRuntimeMeta(voltageKey) {
const base = VOLTAGE_CLASSES[voltageKey] || {};
const overrides = {
lv_cu_sc: { Uo: 0, mbr_factor: 15 },
lv_cu_3c: { Uo: 0, mbr_factor: 12 },
uk_11kv_sc: { Uo: 6.35, mbr_factor: 15 },
uk_11kv_3c: { Uo: 6.35, mbr_factor: 15 },
uk_33kv_sc: { Uo: 19, mbr_factor: 15 },
uk_33kv_3c: { Uo: 19, mbr_factor: 15 },
iec_110kv_sc: { Uo: 64, mbr_factor: 25 },
pv_string: { Uo: 0, mbr_factor: 4 },
flex_hv_ac: { Uo: 0, mbr_factor: 3 },
flex_hv_dc: { Uo: 0, mbr_factor: 3 },
al_ata_ac: { Uo: 0, mbr_factor: 12 },
al_ata_dc: { Uo: 0, mbr_factor: 12 }
};
return { ...base, ...(overrides[voltageKey] || {}) };
}
function getSelectedCore() {
return byId("lookup_cores").value;
}
function getBurialDepthForComputation() {
const raw = Number(byId("burial_depth").value);
if (!Number.isFinite(raw) || raw <= 0) {
return DEFAULT_BURIAL_DEPTHS[byId("service_type").value] || 900;
}
return Math.max(Math.round(raw), 0);
}
function normaliseBurialDepthFieldOnBlur() {
const burial = byId("burial_depth");
const serviceType = byId("service_type").value;
const minDepth = getMinBurialDepth(serviceType);
const fallback = DEFAULT_BURIAL_DEPTHS[serviceType] || 900;
const normalised = clampInteger(burial.value, fallback, minDepth);
burial.value = String(normalised);
return normalised;
}
function normaliseIntegerFields() {
[
{ id: "circuit_qty", fallback: 1, min: 1 },
{ id: "max_per_row", fallback: 1, min: 1 },
{ id: "section_length", fallback: 0, min: 0 },
{ id: "cable_od", fallback: 45, min: 1 },
{ id: "spacing_h", fallback: appState.previousSpacing.h || 0, min: 0 },
{ id: "spacing_v", fallback: appState.previousSpacing.v || 0, min: 0 },
{ id: "bend_factor", fallback: 15, min: 1 }
].forEach(item => {
const el = byId(item.id);
if (el) el.value = String(clampInteger(el.value, item.fallback, item.min));
});
}
function getInputs() {
return {
route_name: byId("route_name").value.trim() || "Unnamed_Route",
section_length_m: clampInteger(byId("section_length").value, 0, 0),
installation_condition: byId("installation_condition").value,
service_type: byId("service_type").value,
grouping_basis: byId("grouping_basis").value,
burial_depth_mm: getBurialDepthForComputation(),
formation_type: byId("formation_type").value,
circuit_qty: clampInteger(byId("circuit_qty").value, 1, 1),
max_per_row: clampInteger(byId("max_per_row").value, 1, 1),
cable_od_mm: clampInteger(byId("cable_od").value, 45, 1),
spacing_basis: byId("spacing_basis").value,
spacing_h_mm: clampInteger(byId("spacing_h").value, appState.previousSpacing.h || 0, 0),
spacing_v_mm: clampInteger(byId("spacing_v").value, appState.previousSpacing.v || 0, 0),
bend_factor: clampInteger(byId("bend_factor").value, 15, 1)
};
}
function populateFormationOptions(serviceType, preferredValue) {
const sel = byId("formation_type");
const opts = FORMATION_LIBRARY[serviceType] || FORMATION_LIBRARY.lv;
sel.innerHTML = "";
opts.forEach(o => {
const node = document.createElement("option");
node.value = o.value;
node.textContent = o.label;
sel.appendChild(node);
});
sel.value = opts.some(o => o.value === preferredValue) ? preferredValue : opts[0].value;
}
function syncFormationToLookupCore() {
const formation = byId("formation_type").value;
const coreSel = byId("lookup_cores");
const coreMap = {
multicore_3c: "three",
multicore_4c: "four",
multicore_5c: "five",
trefoil_single_row: "single",
flat_single_row: "single",
stacked_two_high: "single",
dc_pair_horizontal: "single",
dc_pair_vertical: "single"
};
const wanted = coreMap[formation];
if (!wanted) return;
if ([...coreSel.options].some(o => o.value === wanted)) {
coreSel.value = wanted;
}
}
function populateVoltageOptions() {
const serviceType = byId("service_type").value;
const sel = byId("lookup_voltage");
const selectedCore = getSelectedCore();
const previousValue = sel.value;
sel.innerHTML = '<option value="">— manual OD entry —</option>';
const groups = VOLTAGE_DROPDOWN_GROUPS[serviceType] || [];
let appendedAny = false;
groups.forEach(group => {
const optgroup = document.createElement("optgroup");
optgroup.label = group.label;
group.options.forEach(optData => {
const runtime = getVoltageRuntimeMeta(optData.value);
const cores = runtime.cores || [];
if (selectedCore !== "any" && cores.length && !cores.includes(selectedCore)) return;
const opt = document.createElement("option");
opt.value = optData.value;
opt.textContent = optData.text;
optgroup.appendChild(opt);
appendedAny = true;
});
if (optgroup.children.length) sel.appendChild(optgroup);
});
if (previousValue && [...sel.options].some(o => o.value === previousValue)) {
sel.value = previousValue;
} else {
sel.selectedIndex = 0;
}
if (!appendedAny) {
sel.innerHTML = '<option value="">— no voltage classes for selected core —</option>';
}
populateLookupCSA();
applyLookup();
}
// ===============================
// 🔧 KEY FIX — CORRECT LOOKUP MAP
// ===============================
function getLookupKey(voltageKey, csaMm2, selectedCore) {
if (!voltageKey || !csaMm2) return null;
const directMap = {
// LV
lv_cu_sc: csa => `sc_cu_lv_${csa}`,
lv_cu_3c: csa => `3c_cu_lv_${csa}`,
// UK MV
uk_11kv_sc: csa => `sc_6.35_${csa}`,
uk_11kv_3c: csa => `3c_6.35_${csa}`,
uk_33kv_sc: csa => `sc_19_${csa}`,
uk_33kv_3c: csa => `3c_cu18_${csa}`,
// HV
iec_110kv_sc: csa => `sc_64_${csa}`,
// Solar / DC
pv_string: csa => `sc_pv_string_${csa}`,
flex_hv_ac: csa => `sc_flex_hv_ac_${csa}`,
flex_hv_dc: csa => `sc_flex_hv_dc_${csa}`,
al_ata_ac: csa => `sc_al_ata_ac_${csa}`,
al_ata_dc: csa => `sc_al_ata_dc_${csa}`
};
if (directMap[voltageKey]) return directMap[voltageKey](csaMm2);
return null;
}
// ===============================
// OD LOOKUP — stored data only, no estimation fallback
// ===============================
function lookupOD(voltageKey, csaMm2, selectedCore) {
if (!voltageKey || !csaMm2) return null;
const runtime = getVoltageRuntimeMeta(voltageKey);
const key = getLookupKey(voltageKey, csaMm2, selectedCore);
if (key && OD_CONFIRMED[key]) {
const entry = OD_CONFIRMED[key];
return {
...entry,
estimated: /Generic|catalogue|model/i.test(entry.src || "")
};
}
return null;
}
function getVoltageDisplayName(voltageKey) {
const runtime = getVoltageRuntimeMeta(voltageKey);
return runtime.display_short || runtime.label || voltageKey;
}
function getConductorShapeText(voltageKey) {
const runtime = getVoltageRuntimeMeta(voltageKey);
return CONDUCTOR_SHAPE_LABELS[runtime.conductor_shape] || "Conductor shape not stated";
}
function populateLookupCSA() {
const vk = byId("lookup_voltage").value;
const selectedCore = getSelectedCore();
const sel = byId("lookup_csa");
const noteEl = byId("lookup_note");
sel.innerHTML = "";
if (!vk) {
sel.innerHTML = '<option value="">— select voltage first —</option>';
noteEl.innerHTML =
"Select voltage class and CSA to auto populate OD and bend radius. " +
"All values are for <strong>fixed installation</strong> only. " +
"Flexible applications, very tight bend radii, cleats and terminations must be verified separately.";
return;
}
const runtime = getVoltageRuntimeMeta(vk);
const allowedCores = runtime.cores || [];
if (selectedCore !== "any" && allowedCores.length && !allowedCores.includes(selectedCore)) {
sel.innerHTML = '<option value="">— no CSA for selected core —</option>';
noteEl.innerHTML =
`<strong>${getVoltageDisplayName(vk)}</strong><br>` +
`This voltage class is not available for the selected core arrangement.`;
return;
}
const csas = CSA_BY_VOLTAGE_KEY[vk] || [];
if (!csas.length) {
sel.innerHTML = '<option value="">— no CSA data —</option>';
noteEl.innerHTML =
`<strong>${getVoltageDisplayName(vk)}</strong><br>` +
`No CSA range is configured for this entry.`;
return;
}
csas.forEach(csa => {
const res = lookupOD(vk, csa, selectedCore);
const opt = document.createElement("option");
opt.value = csa;
opt.textContent = res
? `${csa} mm² — OD ${res.od} mm | MBR ${Math.round(res.mbr)} mm${res.estimated ? " (est.)" : ""}`
: `${csa} mm² — no OD data`;
sel.appendChild(opt);
});
sel.selectedIndex = 0;
sel.disabled = !!runtime.locked_csa;
const shapeText = getConductorShapeText(vk);
const sectorNote = runtime.sectorial
? " Sector conductors are indicated here because they affect OD, termination selection and accessory fit."
: "";
const systemNote = runtime.standard_basis
? ` Standard basis: ${runtime.standard_basis}.`
: runtime.system_type
? ` System basis: ${runtime.system_type}.`
: "";
const lockedNote = runtime.locked_csa
? ` CSA is fixed at ${runtime.locked_csa} mm² for this entry.`
: "";
const screenNote = runtime.metallic_screen
? ` Metallic screen reference: ${runtime.metallic_screen} mm².`
: "";
noteEl.innerHTML =
`<strong>${getVoltageDisplayName(vk)}</strong><br>` +
`${shapeText}.${sectorNote}${systemNote}${lockedNote}${screenNote}`;
}
function applyLookup() {
const vk = byId("lookup_voltage").value;
const csa = byId("lookup_csa").value;
const selectedCore = getSelectedCore();
if (!vk || !csa) return;
const result = lookupOD(vk, parseFloat(csa), selectedCore);
if (!result) return;
const runtime = getVoltageRuntimeMeta(vk);
byId("cable_od").value = String(Math.round(result.od * 10) / 10);
byId("bend_factor").value = String(runtime.mbr_factor || Math.max(1, Math.round(result.mbr / result.od)));
const srcEl = byId("od_source_note");
srcEl.textContent = result.estimated
? `OD from model or generic schedule. Verify before use.`
: `OD from stored dataset.`;
srcEl.style.color = result.estimated ? "var(–warn)" : "var(–ok)";
const noteEl = byId("lookup_note");
const shapeText = getConductorShapeText(vk);
const sectorText = runtime.sectorial ? " Sector conductors affect OD and terminations." : "";
const systemText = runtime.system_type
? ` ${runtime.system_type}.`
: runtime.standard_basis
? ` ${runtime.standard_basis}.`
: "";
noteEl.innerHTML =
`<strong>${getVoltageDisplayName(vk)} — ${csa} mm²</strong><br>` +
`OD = ${result.od} mm. Fixed installation MBR = ${Math.round(result.mbr)} mm.${systemText} ` +
`${shapeText}.${sectorText} ` +
`${result.estimated ? "Estimated value. Verify before design use." : "Stored dataset value."}`;
renderAll();
}
function updateFromLookup() {
const vk = byId("lookup_voltage").value;
const csa = byId("lookup_csa").value;
const selectedCore = getSelectedCore();
const srcEl = byId("od_source_note");
if (vk && csa) {
const res = lookupOD(vk, parseFloat(csa), selectedCore);
if (res) {
srcEl.textContent = res.estimated
? "OD from model or generic schedule. Verify before use."
: "OD from stored dataset.";
srcEl.style.color = res.estimated ? "var(–warn)" : "var(–ok)";
}
}
renderAll();
}
function getGroupGeometry(inputs) {
const d = inputs.cable_od_mm;
const sqrt3 = Math.sqrt(3);
switch (inputs.formation_type) {
case "trefoil_single_row": return { width: d * 2, depth: d * (1 + sqrt3 / 2), drawType: "trefoil", note: "Trefoil 1c groups" };
case "flat_single_row": return { width: d * 3, depth: d, drawType: "flat_3", note: "Flat 1c groups" };
case "stacked_two_high": return { width: d * 3, depth: d * 2, drawType: "stacked_2x3", note: "Stacked 2 high 1c groups" };
case "multicore_3c": return { width: d, depth: d, drawType: "multicore_3c", note: "Three core cable groups" };
case "multicore_4c": return { width: d, depth: d, drawType: "multicore_4c", note: "Four core cable groups" };
case "multicore_5c": return { width: d, depth: d, drawType: "multicore_5c", note: "Five core cable groups" };
case "dc_pair_horizontal": return { width: d * 2, depth: d, drawType: "dc_pair_h", note: "DC horizontal pair" };
case "dc_pair_vertical": return { width: d, depth: d * 2, drawType: "dc_pair_v", note: "DC vertical pair" };
default: return { width: d * 2, depth: d * (1 + sqrt3 / 2), drawType: "trefoil", note: "Trefoil 1c groups" };
}
}
function computeLayout(inputs) {
const gapH = effectiveGap(inputs.spacing_basis, inputs.spacing_h_mm, inputs.cable_od_mm);
const gapV = effectiveGap(inputs.spacing_basis, inputs.spacing_v_mm, inputs.cable_od_mm);
const geom = getGroupGeometry(inputs);
const perRow = Math.max(1, inputs.max_per_row);
const groupCount = Math.max(1, inputs.circuit_qty);
const rows = Math.ceil(groupCount / perRow);
const rowCounts = [];
let remaining = groupCount;
for (let i = 0; i < rows; i++) {
const c = Math.min(perRow, remaining);
rowCounts.push(c);
remaining -= c;
}
const maxRowCount = Math.max(...rowCounts);
const formationWidth = (maxRowCount * geom.width) + (Math.max(maxRowCount - 1, 0) * gapH);
const formationDepth = (rows * geom.depth) + (Math.max(rows - 1, 0) * gapV);
const appliedBendRadius = inputs.cable_od_mm * inputs.bend_factor;
const singleCableOuterSweepRadius = appliedBendRadius + inputs.cable_od_mm / 2;
const approxGroupCtcH = inputs.spacing_basis === "centre_to_centre" ? inputs.spacing_h_mm : geom.width + gapH;
const approxGroupCtcV = inputs.spacing_basis === "centre_to_centre" ? inputs.spacing_v_mm : geom.depth + gapV;
return {
rows,
rowCounts,
groupWidth: geom.width,
groupDepth: geom.depth,
drawType: geom.drawType,
groupNote: geom.note,
gapH,
gapV,
formationWidth,
formationDepth,
appliedBendRadius,
singleCableOuterSweepRadius,
approxGroupCtcH,
approxGroupCtcV,
indicativeTrenchWidth: formationWidth,
indicativeTrenchDepth: inputs.burial_depth_mm + formationDepth,
hasUnevenLastRow: rowCounts.length > 1 && rowCounts[rowCounts.length - 1] !== maxRowCount
};
}
function buildReview(inputs, layout) {
const inputConflicts = [];
const reviewPoints = [];
const standingAssumptions = [
"Within group cable spacing is assumed touching unless separately modelled.",
"Mixed service visual uses one worst case OD for all shown services and is schematic only.",
"Bend model is a single cable body sweep only.",
"Burial depth is recorded as an indicative input only.",
"4 core and 5 core multicore formations are drawn as a single cable OD."