In this section
- Indexforgis Single-Line Diagram (SLD) electrical · globalgrid2050 / solar-bess-topology/indexforgis-sld.html lines 429–1128
Indexforgis Single-Line Diagram (SLD)
A map page in the solar BESS topology folder of GlobalGrid2050 that maps grid substations, sat s and l sat, and uses data from OpenStreetMap Nominatim. Published at https://globalgrid2050.com/solar-bess-topology/indexforgis-sld.html.
electricalglobalgrid2050 / solar-bess-topology/indexforgis-sld.html · lines 429–1128 of 1454 (continued from section 117) · Entry point · pattern triggerDownload (shared by 3 files)
- What it does
- It maps grid substations, sat s, l sat and l subs. Defines 47 functions or classes, including $, num, intVal, checked, setText. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'bess'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 33kV.
- Inputs & outputs
- In: data source: OpenStreetMap Nominatim; GeoJSON file grid_substations.geojson; JSON file style.json; form fields (user input). Out: web page; interactive map. Voltage levels named: 33kV.
- Downstream impact
- It is itself an entry point, published at https://globalgrid2050.com/solar-bess-topology/indexforgis-sld.html.
- What it achieves
- It sets text (`setText`), sets class (`setClass`) and picks prop (`pickProp`). GIS-SLD and Financial Sandbox. Its code works with 33 kV. It responds to click, keydown and change events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · solar-bess-topology · page
- Uses
- https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.css, https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.js, https://cdn.jsdelivr.net/npm/@turf/turf@6/turf.min.js
- Used by
- none found
- Produces
- $, num, intVal, checked, setText, setClass, money, debounce, isValidLngLat, pickProp, setFetchStatus, initMap
- Defines here
- $, num, intVal, checked, setText, setClass, money, debounce, isValidLngLat, pickProp, setFetchStatus, initMap, onMapLoad, showPopup, normaliseSubstations, loadSubstations, onSubstationClick, onInverterClick, onPoiClick, readPhysicalInputs, zeroStats, buildStats, computeStringStats, computeCentralStats, computeStats, computeFinance, renderFinance, renderFinanceWarnings, renderTechSummary, renderBenchmark
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-bess-topology/indexforgis-sld.html:429-1128 · blob 727275a46deedb86e05835eaaee57a25219a78b6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
activeTab: "string",
currentGeoJSON: { type: "FeatureCollection", features: [] },
activeDrawCenter: null,
selectedSubstation: null,
subsVisible: true,
satActive: false,
activePopup: null,
lastStats: null,
lastFinance: { fin_string: null, fin_central: null }
};
// ============================================================
// SMALL UTILITIES
// ============================================================
const $ = (id) => document.getElementById(id);
const num = (id) => { const el = $(id); return el ? (parseFloat(el.value) || 0) : 0; };
const intVal = (id, fallback = 0) => { const el = $(id); return el ? (parseInt(el.value, 10) || fallback) : fallback; };
const checked = (id) => { const el = $(id); return el ? !!el.checked : false; };
const setText = (id, val) => { const el = $(id); if (el) el.textContent = val; };
const setClass = (id, cls) => { const el = $(id); if (el) el.className = cls; };
function money(v) {
const rounded = Math.round(v);
if (rounded < 0) return "-£" + Math.abs(rounded).toLocaleString();
return "£" + rounded.toLocaleString();
}
function debounce(fn, ms) {
let t = null;
return function(...args) {
clearTimeout(t);
t = setTimeout(() => fn.apply(this, args), ms);
};
}
function isValidLngLat(c) {
return Array.isArray(c) && c.length >= 2
&& Number.isFinite(+c[0]) && Number.isFinite(+c[1])
&& +c[0] >= -180 && +c[0] <= 180 && +c[1] >= -90 && +c[1] <= 90;
}
function pickProp(obj, keys, fallback = null) {
for (const k of keys) {
if (obj && obj[k] !== undefined && obj[k] !== null && obj[k] !== "") return obj[k];
}
return fallback;
}
function setFetchStatus(msg, isError) {
const el = $("fetch_status");
if (!el) return;
if (!msg) { el.style.display = "none"; el.textContent = ""; el.classList.remove("error"); return; }
el.textContent = msg;
el.style.display = "block";
el.classList.toggle("error", !!isError);
}
// ============================================================
// MAP
// ============================================================
let map = null;
function initMap() {
if (typeof maplibregl === "undefined") {
setFetchStatus("MapLibre failed to load. Check network.", true);
console.error("maplibregl is undefined");
return;
}
if (typeof turf === "undefined") {
setFetchStatus("Turf failed to load. Check network.", true);
console.error("turf is undefined");
return;
}
map = new maplibregl.Map({
container: "map",
style: "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",
center: CONSTANTS.DEFAULT_CENTER,
zoom: CONSTANTS.DEFAULT_ZOOM
});
map.on("error", (e) => console.error("MapLibre error:", e && e.error ? e.error : e));
map.on("load", onMapLoad);
}
function onMapLoad() {
map.addSource("sat-s", {
type: "raster",
tiles: ["https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"],
tileSize: 256
});
map.addLayer({ id: "l-sat", type: "raster", source: "sat-s", layout: { visibility: "none" } });
map.addSource("src-subs", { type: "geojson", data: { type: "FeatureCollection", features: [] } });
map.addLayer({
id: "l-subs", type: "circle", source: "src-subs",
paint: {
"circle-color": "#ffffff",
"circle-radius": ["interpolate", ["linear"], ["zoom"], 5, 3, 10, 5, 14, 10, 18, 22],
"circle-stroke-width": 1, "circle-stroke-color": "#ff3333", "circle-opacity": 0.8
}
});
map.addSource("topology", { type: "geojson", data: state.currentGeoJSON });
map.addLayer({
id: "overall_boundary_fill", type: "fill", source: "topology",
filter: ["==", "type", "array_boundary"],
paint: { "fill-color": "#0066ff", "fill-opacity": 0.25 }
});
map.addLayer({
id: "overall_boundary_line", type: "line", source: "topology",
filter: ["==", "type", "array_boundary"],
paint: { "line-color": "#0066ff", "line-width": 2, "line-dasharray": [4, 4] }
});
map.addLayer({
id: "footprints", type: "fill", source: "topology",
filter: ["in", ["get", "type"], ["literal", ["skid_footprint", "central_footprint", "bess_footprint"]]],
paint: {
"fill-color": ["match", ["get", "type"],
"skid_footprint", "#00ffff", "central_footprint", "#ff9900", "bess_footprint", "#ff00aa", "#000"],
"fill-opacity": 0.15
}
});
map.addLayer({
id: "footprints_outline", type: "line", source: "topology",
filter: ["in", ["get", "type"], ["literal", ["skid_footprint", "central_footprint", "bess_footprint"]]],
paint: {
"line-color": ["match", ["get", "type"],
"skid_footprint", "#00ffff", "central_footprint", "#ff9900", "bess_footprint", "#ff00aa", "#000"],
"line-width": 1
}
});
map.addLayer({
id: "export_cable", type: "line", source: "topology",
filter: ["==", "type", "export_cable"],
paint: { "line-color": "#ff3333", "line-width": 2, "line-dasharray": [4, 4] }
});
map.addLayer({
id: "radial_spine", type: "line", source: "topology",
filter: ["==", "type", "33kv_radial"],
paint: { "line-color": "#00ffff", "line-width": 2 }
});
map.addLayer({
id: "inverters", type: "circle", source: "topology",
filter: ["in", ["get", "type"], ["literal", ["string_substation", "central_inverter", "mv_station", "bess_compound"]]],
paint: {
"circle-color": ["match", ["get", "type"],
"string_substation", "#ffff00", "central_inverter", "#ff9900",
"mv_station", "#6633ff", "bess_compound", "#ff00aa", "#fff"],
"circle-radius": ["match", ["get", "type"],
"string_substation", 4, "central_inverter", 6, "mv_station", 4, "bess_compound", 6, 3],
"circle-stroke-color": "#000", "circle-stroke-width": 1
}
});
map.addLayer({
id: "substation", type: "circle", source: "topology",
filter: ["in", ["get", "type"], ["literal", ["poi", "private_sub"]]],
paint: {
"circle-color": ["match", ["get", "type"], "poi", "#ff3333", "private_sub", "#00ff88", "#fff"],
"circle-radius": 8, "circle-stroke-color": "#fff", "circle-stroke-width": 2
}
});
// Map clicks
map.on("click", "l-subs", onSubstationClick);
map.on("mouseenter", "l-subs", () => map.getCanvas().style.cursor = "pointer");
map.on("mouseleave", "l-subs", () => map.getCanvas().style.cursor = "");
map.on("click", "inverters", onInverterClick);
map.on("mouseenter", "inverters", () => map.getCanvas().style.cursor = "pointer");
map.on("mouseleave", "inverters", () => map.getCanvas().style.cursor = "");
map.on("click", "substation", onPoiClick);
map.on("mouseenter", "substation", () => map.getCanvas().style.cursor = "pointer");
map.on("mouseleave", "substation", () => map.getCanvas().style.cursor = "");
loadSubstations();
updateLegend();
recalcAll();
}
function showPopup(coords, html) {
if (state.activePopup) state.activePopup.remove();
state.activePopup = new maplibregl.Popup().setLngLat(coords).setHTML(html).addTo(map);
state.activePopup.on("close", () => { state.activePopup = null; });
}
// ============================================================
// SUBSTATION DATA LOAD
// ============================================================
function normaliseSubstations(raw) {
if (!raw) throw new Error("Empty dataset");
let features = [];
if (raw.type === "FeatureCollection" && Array.isArray(raw.features)) {
features = raw.features;
} else if (Array.isArray(raw)) {
features = raw.map(item => ({
type: "Feature",
geometry: item.geometry || { type: "Point", coordinates: [
item.lon ?? item.lng ?? item.longitude ?? item.Longitude ?? item.X,
item.lat ?? item.latitude ?? item.Latitude ?? item.Y
]},
properties: item.properties || item
}));
} else {
throw new Error("Not a FeatureCollection or array");
}
const cleaned = features
.filter(f => f && f.geometry && f.geometry.type === "Point")
.map(f => {
const c = f.geometry.coordinates.map(Number);
if (!isValidLngLat(c)) return null;
const p = f.properties || {};
return {
type: "Feature",
geometry: { type: "Point", coordinates: [c[0], c[1]] },
properties: {
...p,
name_clean: pickProp(p, ["name","Name","site_name","SiteName","Site Name","substation","Substation","substation_name","Substation Name"], "Substation"),
voltage_clean: pickProp(p, ["voltage","Voltage","kv","kV","KV","voltage_kv","Voltage kV"], "Unknown")
}
};
})
.filter(Boolean);
return { type: "FeatureCollection", features: cleaned };
}
async function loadSubstations() {
setFetchStatus("Loading substations…", false);
try {
const url = SUBSTATIONS_URL + (SUBSTATIONS_URL.includes("?") ? "&" : "?") + "v=" + Date.now();
const res = await fetch(url);
if (!res.ok) throw new Error("HTTP " + res.status);
const raw = await res.json();
const cleaned = normaliseSubstations(raw);
const src = map.getSource("src-subs");
if (src) src.setData(cleaned);
console.log("Substations loaded:", cleaned.features.length);
setFetchStatus(`${cleaned.features.length.toLocaleString()} substations loaded`, false);
setTimeout(() => setFetchStatus("", false), 2500);
} catch (err) {
console.error("Substation load failed:", err);
setFetchStatus(`Substations unavailable: ${err.message}. Check SUBSTATIONS_URL.`, true);
}
}
// ============================================================
// MAP CLICK HANDLERS
// ============================================================
function onSubstationClick(e) {
const f = e.features && e.features[0];
if (!f || !f.geometry) return;
const coords = f.geometry.coordinates.slice();
const p = f.properties || {};
state.selectedSubstation = {
name: p.name_clean || pickProp(p, ["name","Name","SiteName","Site Name","substation","Substation"], "Selected Substation"),
voltage: p.voltage_clean || pickProp(p, ["voltage","Voltage","kv","kV","KV"], "Unknown"),
properties: p,
coordinates: coords
};
state.activeDrawCenter = coords;
updateSelectedSubstationDisplay();
computeAndDraw();
showPopup(coords, `
<div style="margin-bottom:5px;color:#ff3333;font-weight:bold;font-size:13px;text-transform:uppercase;">Grid Node</div>
<div class="popup-row"><span>Name:</span><span class="popup-val" style="color:#fff;">${state.selectedSubstation.name}</span></div>
<div class="popup-row"><span>Voltage:</span><span class="popup-val" style="color:#fff;">${state.selectedSubstation.voltage}</span></div>
<div class="popup-row"><span>Lon:</span><span class="popup-val" style="color:#fff;">${Number(coords[0]).toFixed(6)}</span></div>
<div class="popup-row"><span>Lat:</span><span class="popup-val" style="color:#fff;">${Number(coords[1]).toFixed(6)}</span></div>
`);
}
function onInverterClick(e) {
const prop = e.features[0].properties;
const coords = e.features[0].geometry.coordinates.slice();
const colourMap = {
central_inverter: "#ff9900", string_substation: "#ffff00",
bess_compound: "#ff00aa", mv_station: "#6633ff"
};
const colour = colourMap[prop.type] || "#00ffff";
let html = `<div style="margin-bottom:5px;color:${colour};font-weight:bold;font-size:13px;text-transform:uppercase;">Block Info</div>
<div class="popup-row"><span>Type:</span><span class="popup-val" style="color:#fff;">${prop.type}</span></div>`;
if (prop.type === "bess_compound" && prop.mwh !== undefined) {
html += `<div class="popup-row"><span>Capacity:</span><span class="popup-val" style="color:#fff;">${prop.mwh} MWh</span></div>`;
}
showPopup(coords, html);
}
function onPoiClick(e) {
const prop = e.features[0].properties;
const coords = e.features[0].geometry.coordinates.slice();
const title = prop.type === "poi" ? "Point of Interconnection" : "Customer Substation";
const colour = prop.type === "poi" ? "#ff3333" : "#00ff88";
let html = `<div style="margin-bottom:5px;color:${colour};font-weight:bold;font-size:13px;text-transform:uppercase;">${title}</div>`;
if (prop.selected_substation_name) html += `<div class="popup-row"><span>Name:</span><span class="popup-val" style="color:#fff;">${prop.selected_substation_name}</span></div>`;
if (prop.selected_substation_voltage) html += `<div class="popup-row"><span>Voltage:</span><span class="popup-val" style="color:#fff;">${prop.selected_substation_voltage}</span></div>`;
showPopup(coords, html);
}
// ============================================================
// AGGREGATE STATS (single unified function)
// ============================================================
function readPhysicalInputs(suffix) {
return {
mod_wp: num("mod_wp" + suffix),
mod_l: num("mod_l" + suffix),
mod_w: num("mod_w" + suffix),
gcr: parseFloat($("mounting_type" + suffix)?.value) || (suffix === "_c" ? 0.45 : 0.75),
gross_factor: num("gross_factor" + suffix) || 1.35,
mods_pallet: intVal("mods_pallet" + suffix, 1),
mods_container: intVal("mods_container" + suffix, 1),
spare_pct: num("spare_pct" + suffix)
};
}
function zeroStats(dc_ac_ratio, mods_pallet, mods_container) {
return {
total_blocks: 0, block_ground_area_m2: 0, dc_mwp: 0, ac_mw: 0, module_count: 0,
net_mod_area_m2: 0, net_array_area_m2: 0, gross_site_area_m2: 0,
dc_ac_ratio, pallets: 0, containers: 0, spares_pct: 0,
modules_inc_spares: 0, pallets_inc_spares: 0, containers_inc_spares: 0,
mods_pallet, mods_container,
combiner_boxes_per_inverter: 0, total_combiner_boxes: 0
};
}
function buildStats(opts) {
const { total_blocks, module_count, ac_mw_direct, dc_ac_ratio, physical, combiner_boxes_per_inverter, total_combiner_boxes } = opts;
const { mod_wp, mod_l, mod_w, gcr, gross_factor, mods_pallet, mods_container, spare_pct } = physical;
const dc_mwp = (module_count * mod_wp) / 1_000_000;
const ac_mw = ac_mw_direct != null ? ac_mw_direct : (dc_ac_ratio > 0 ? dc_mwp / dc_ac_ratio : 0);
const net_mod_area_m2 = module_count * mod_l * mod_w;
const net_array_area_m2 = gcr > 0 ? net_mod_area_m2 / gcr : 0;
const gross_site_area_m2 = net_array_area_m2 * gross_factor;
const block_ground_area_m2 = total_blocks > 0 ? net_array_area_m2 / total_blocks : 0;
const pallets = Math.ceil(module_count / mods_pallet);
const containers = Math.ceil(module_count / mods_container);
const modules_inc_spares = Math.ceil(module_count * (1 + spare_pct / 100));
const pallets_inc_spares = Math.ceil(modules_inc_spares / mods_pallet);
const containers_inc_spares = Math.ceil(modules_inc_spares / mods_container);
return {
total_blocks, block_ground_area_m2, dc_mwp, ac_mw, module_count,
net_mod_area_m2, net_array_area_m2, gross_site_area_m2, dc_ac_ratio,
pallets, containers, spares_pct: spare_pct,
modules_inc_spares, pallets_inc_spares, containers_inc_spares,
mods_pallet, mods_container,
combiner_boxes_per_inverter: combiner_boxes_per_inverter || 0,
total_combiner_boxes: total_combiner_boxes || 0
};
}
function computeStringStats() {
const physical = readPhysicalInputs("");
const x = intVal("x_mods"), z = intVal("z_strings"), y = intVal("y_invs"), s = intVal("s_subs"), rings = intVal("b_cols");
const dc_ac_ratio = num("dc_ac_ratio") || 1.2;
if (physical.mod_wp <= 0 || physical.mod_l <= 0 || physical.mod_w <= 0 || x <= 0) {
return zeroStats(dc_ac_ratio, physical.mods_pallet, physical.mods_container);
}
const total_blocks = rings * s;
const module_count = total_blocks * y * z * x;
return buildStats({ total_blocks, module_count, dc_ac_ratio, physical });
}
function computeCentralStats() {
const physical = readPhysicalInputs("_c");
const x_mods = intVal("x_mods_c");
const inv_ac_mw = num("inv_ac_mw_c");
const dc_ac_ratio = num("dc_ac_ratio_c") || 1.2;
const str_per_cb = intVal("str_per_cb_c", 1);
const inv_per_mv = intVal("inv_per_mv_c");
const mv_per_ring = intVal("mv_per_ring_c");
const rings = intVal("rings_c");
if (physical.mod_wp <= 0 || physical.mod_l <= 0 || physical.mod_w <= 0 || x_mods <= 0) {
return zeroStats(dc_ac_ratio, physical.mods_pallet, physical.mods_container);
}
const str_dc_kwp = (x_mods * physical.mod_wp) / 1000;
const inv_dc_mwp = inv_ac_mw * dc_ac_ratio;
const req_strings = str_dc_kwp > 0 ? Math.ceil((inv_dc_mwp * 1000) / str_dc_kwp) : 0;
const combiner_boxes_per_inverter = Math.ceil(req_strings / str_per_cb);
const total_blocks = inv_per_mv * mv_per_ring * rings;
const total_combiner_boxes = combiner_boxes_per_inverter * total_blocks;
const module_count = req_strings * x_mods * total_blocks;
const ac_mw_direct = total_blocks * inv_ac_mw;
return buildStats({
total_blocks, module_count, ac_mw_direct, dc_ac_ratio, physical,
combiner_boxes_per_inverter, total_combiner_boxes
});
}
function computeStats() {
return state.activeTab === "string" ? computeStringStats() : computeCentralStats();
}
// ============================================================
// FINANCIALS
// ============================================================
function computeFinance(prefix, stats) {
const dc_mwp = stats.dc_mwp, ac_mw = stats.ac_mw;
const price = num(prefix + "_price");
const other = num(prefix + "_other");
const yieldVal = num(prefix + "_yield");
const bifacial = num(prefix + "_bifacial");
const baseLoss = num(prefix + "_losses");
const deg = num(prefix + "_deg");
const opexRate = num(prefix + "_opex");
const epcEx = num(prefix + "_epc_ex");
const floodAdder = checked(prefix + "_flood") ? num(prefix + "_flood_rate") : 0;
const modules = num(prefix + "_modules");
const otherCapex = num(prefix + "_other_capex");
const fixedCapex = num(prefix + "_fixed_capex");
const cont = num(prefix + "_cont");
const lossExtras = num(prefix + "_loss_dc_string") + num(prefix + "_loss_lv_dc") +
num(prefix + "_loss_lv_ac") + num(prefix + "_loss_tx") + num(prefix + "_loss_other");
const totalLoss = baseLoss + lossExtras;
const bessMw = num(prefix + "_bess_mw");
const bessMwh = num(prefix + "_bess_mwh");
const bessCapexRate = num(prefix + "_bess_capex");
const bessCycles = num(prefix + "_bess_cycles");
const bessSpread = num(prefix + "_bess_spread");
const bessEff = num(prefix + "_bess_eff") / 100;
const safeLoss = Math.min(Math.max(totalLoss, 0), 100);
const safeBessEff = Math.min(Math.max(bessEff, 0), 1);
const effectiveYield = yieldVal * (1 + bifacial / 100);
const year1Gen = dc_mwp * effectiveYield * (1 - safeLoss / 100);
// Cumulative generation
let gen25 = 0, gen35 = 0;
for (let y = 1; y <= 35; y++) {
const yr = year1Gen * Math.pow(1 - deg / 100, y - 1);
if (y <= 25) gen25 += yr;
gen35 += yr;
}
const annualSolarRevenue = year1Gen * (price + other);
const bessAnnualValue = bessMwh * bessCycles * bessSpread * safeBessEff;
const annualRevenue = annualSolarRevenue + bessAnnualValue;
const revenue25 = gen25 * (price + other) + bessAnnualValue * 25;
const revenue35 = gen35 * (price + other) + bessAnnualValue * 35;
const annualOpex = ac_mw * opexRate;
const baseCapexWp = epcEx + modules + otherCapex + floodAdder;
const baseCapex = dc_mwp * 1_000_000 * baseCapexWp;
const contingency = baseCapex * (cont / 100);
const bessCapex = bessMwh * bessCapexRate;
const totalCapex = baseCapex + contingency + fixedCapex + bessCapex;
const capexPerWp = dc_mwp > 0 ? totalCapex / (dc_mwp * 1_000_000) : 0;
const surplus25 = revenue25 - annualOpex * 25 - totalCapex;
const surplus35 = revenue35 - annualOpex * 35 - totalCapex;
return {
annualRevenue, revenue25, revenue35, totalCapex, capexPerWp, surplus25, surplus35,
// raw inputs for export
price, other, yieldVal, bifacial, baseLoss, deg, opexRate,
epcEx, floodActive: checked(prefix + "_flood"), floodRate: num(prefix + "_flood_rate"),
modules, otherCapex, fixedCapex, cont, totalLoss,
bessMw, bessMwh, bessCapexRate, bessCycles, bessSpread, bessEff: num(prefix + "_bess_eff"),
// for warnings
epcIncModules: epcEx + modules
};
}
function renderFinance(prefix, fin) {
setText(prefix + "_annual_rev", money(fin.annualRevenue));
setText(prefix + "_25_rev", money(fin.revenue25));
setText(prefix + "_35_rev", money(fin.revenue35));
setText(prefix + "_capex", money(fin.totalCapex));
setText(prefix + "_capex_wp", "£" + fin.capexPerWp.toFixed(2) + "/Wp");
setText(prefix + "_surplus_25", money(fin.surplus25));
setText(prefix + "_surplus_35", money(fin.surplus35));
}
function renderFinanceWarnings(prefix, fin, stats) {
const w = [];
if (fin.price < 0) w.push("Energy price cannot be negative.");
if (fin.opexRate < 0) w.push("OPEX cannot be negative.");
if (fin.totalLoss < 0) w.push("Losses cannot be negative.");
if (fin.epcIncModules < 0) w.push("EPC cannot be negative.");
if (fin.capexPerWp < 0) w.push("CAPEX cannot be negative.");
if (fin.bessMwh < 0 || fin.bessMw < 0) w.push("BESS size cannot be negative.");
if (fin.bessMwh > 0 && fin.bessEff / 100 <= 0) w.push("BESS efficiency missing.");
if (fin.bessEff / 100 > 1) w.push("BESS efficiency above 100 percent.");
if (fin.price < 50) w.push("Low energy price case.");
if (fin.price > 85) w.push("High energy price case.");
if (fin.epcIncModules < 0.42) w.push("Aggressive EPC pricing.");
if (fin.capexPerWp > 1.00) w.push("Full project cost territory.");
if (fin.capexPerWp > 1.25) w.push("Complex project or asset value territory.");
if (fin.opexRate < 10000 && fin.opexRate >= 0) w.push("OPEX may be unrealistically low.");
if (fin.totalLoss > 6) w.push("High loss assumption.");
if (fin.bifacial > 12) w.push("Aggressive bifacial gain assumption.");
if (fin.bessMwh > 0 && fin.bessMw <= 0) w.push("BESS MW missing.");
if (fin.bessMw > 0 && fin.bessMwh / fin.bessMw > 8) w.push("Unusually long BESS duration.");
if (fin.bessCycles > 365) w.push("Aggressive storage cycling assumption.");
const elecZero = num(prefix + "_loss_dc_string") + num(prefix + "_loss_lv_dc") +
num(prefix + "_loss_lv_ac") + num(prefix + "_loss_tx") + num(prefix + "_loss_other");
if (elecZero === 0) w.push("Specialist electrical loss fields are blank or zero. Revenue may be overstated until verified.");
const gf = state.activeTab === "string" ? num("gross_factor") : num("gross_factor_c");
if (gf < 1.15) w.push("Gross site factor may be too low for roads, buffers, substations, drainage and ecology.");
if (stats.mods_pallet <= 0 || stats.mods_container <= 0) w.push("Module logistics assumptions are missing.");
const el = $(prefix + "_warnings");
if (el) el.innerHTML = w.join("<br>");
}
// ============================================================
// RENDER TECHNICAL SUMMARY
// ============================================================
function renderTechSummary(stats) {
setText("out_module_count", stats.module_count.toLocaleString());
setText("out_dc_capacity", stats.dc_mwp.toFixed(2) + " MWp");
setText("out_ac_capacity", stats.ac_mw.toFixed(2) + " MWac");
setText("out_actual_dcac", stats.dc_ac_ratio.toFixed(2));
setText("out_cb_per_inv", stats.combiner_boxes_per_inverter.toLocaleString());
setText("out_total_cb", stats.total_combiner_boxes.toLocaleString());
setText("out_net_mod_area", (stats.net_mod_area_m2 / CONSTANTS.M2_PER_ACRE).toFixed(0) + " Acres");
setText("out_net_array_area", (stats.net_array_area_m2 / CONSTANTS.M2_PER_ACRE).toFixed(0) + " Acres");
setText("out_gross_area", (stats.gross_site_area_m2 / CONSTANTS.M2_PER_ACRE).toFixed(0) + " Acres");
setText("out_mod_per_pallet", stats.mods_pallet);
setText("out_pallets", stats.pallets.toLocaleString());
setText("out_mod_per_cont", stats.mods_container);
setText("out_containers", stats.containers.toLocaleString());
setText("out_spare_pct", stats.spares_pct.toFixed(1) + "%");
setText("out_containers_spares", stats.containers_inc_spares.toLocaleString());
const tabClass = state.activeTab === "central" ? "stat-val orange" : "stat-val cyan";
setClass("out_dc_capacity", tabClass);
setClass("out_containers_spares", tabClass);
const cpm = stats.dc_mwp > 0 ? stats.containers_inc_spares / stats.dc_mwp : 0;
setText("out_cont_per_mwp", cpm.toFixed(2));
setClass("out_cont_per_mwp", tabClass);
}
function renderBenchmark() {
const mw = num("ref_mw"), mods = num("ref_modules");
const implied = mw > 0 ? mods / mw : 0;
setText("out_ref_implied", `~ ${Math.round(implied).toLocaleString()} modules/MW`);
}
function updateSelectedSubstationDisplay() {
const s = state.selectedSubstation;
if (!s) {
setText("out_selected_sub_name", "None selected");
setText("out_selected_sub_voltage", "Unknown");
setText("out_selected_sub_lon", "n/a");
setText("out_selected_sub_lat", "n/a");
return;
}
setText("out_selected_sub_name", s.name || "Selected Substation");
setText("out_selected_sub_voltage", s.voltage || "Unknown");
setText("out_selected_sub_lon", s.coordinates ? Number(s.coordinates[0]).toFixed(6) : "n/a");
setText("out_selected_sub_lat", s.coordinates ? Number(s.coordinates[1]).toFixed(6) : "n/a");
}
// ============================================================
// MAIN RECALC
// ============================================================
function recalcAll() {
const stats = computeStats();
state.lastStats = stats;
renderTechSummary(stats);
const prefix = state.activeTab === "string" ? "fin_string" : "fin_central";
const fin = computeFinance(prefix, stats);
state.lastFinance[prefix] = fin;
renderFinance(prefix, fin);
renderFinanceWarnings(prefix, fin, stats);
renderBenchmark();
updateSelectedSubstationDisplay();
}
const recalcDebounced = debounce(recalcAll, CONSTANTS.RECALC_DEBOUNCE_MS);
// ============================================================
// LEGEND
// ============================================================
function updateLegend() {
const legend = $("map_legend");
if (!legend) return;
let html = `
<div class="legend-item"><div class="swatch" style="background:#ffffff; border-color:#ff3333;"></div> Atlas Substation Dataset</div>
<div class="legend-item"><div class="swatch" style="background:var(--substation);"></div> Point of Interconnection</div>
<div class="legend-item"><div class="swatch" style="background:transparent; border-bottom: 2px dashed var(--substation);"></div> Export Cable</div>
<div class="legend-item"><div class="swatch" style="background:var(--private-sub);"></div> Customer Substation</div>
<div class="legend-item"><div class="swatch" style="background:var(--bess);"></div> BESS Compound</div>
<div class="legend-item"><div class="swatch" style="background:var(--array-blue); opacity: 0.3; border-style: dashed;"></div> Total Array Boundary</div>`;
if (state.activeTab === "string") {
html += `<div class="legend-item"><div class="swatch" style="background:var(--inverter);"></div> String Substation Block</div>
<div class="legend-item"><div class="swatch" style="background:transparent; border-bottom: 2px solid var(--accent);"></div> Radial 33kV Spine</div>`;
} else {
html += `<div class="legend-item"><div class="swatch" style="background:var(--accent-alt);"></div> Central Inverter Block</div>
<div class="legend-item"><div class="swatch" style="background:transparent; border-bottom: 2px solid var(--accent);"></div> Radial 33kV Spine</div>`;
}
legend.innerHTML = html;
}
// ============================================================
// DRAWING
// ============================================================
function getRectPolygon(centerCoord, width_km, length_km, propType) {
const pt = turf.point(centerCoord);
const ptN = turf.destination(pt, length_km / 2, 0, { units: "kilometers" }).geometry.coordinates;
const ptS = turf.destination(pt, length_km / 2, 180, { units: "kilometers" }).geometry.coordinates;
const nw = turf.destination(turf.point(ptN), width_km / 2, -90, { units: "kilometers" }).geometry.coordinates;
const ne = turf.destination(turf.point(ptN), width_km / 2, 90, { units: "kilometers" }).geometry.coordinates;
const se = turf.destination(turf.point(ptS), width_km / 2, 90, { units: "kilometers" }).geometry.coordinates;
const sw = turf.destination(turf.point(ptS), width_km / 2, -90, { units: "kilometers" }).geometry.coordinates;
return turf.polygon([[nw, ne, se, sw, nw]], { type: propType });
}
function getBlockAspect() {
const mountingVal = state.activeTab === "string" ? $("mounting_type").value : $("mounting_type_c").value;
if (mountingVal === "0.45") return 1 / 1.4;
if (mountingVal === "0.75") return 1.0;
return 1.4;
}
function computeAndDraw() {
if (!state.activeDrawCenter || !map) return;
const stats = computeStats();
state.lastStats = stats;
if (stats.total_blocks === 0) {
recalcAll();
return;
}
const N = stats.total_blocks;
const cols = Math.ceil(Math.sqrt(N));
const rows = Math.ceil(N / cols);
const block_area_km2 = stats.block_ground_area_m2 / 1_000_000;
const aspect = getBlockAspect();
const block_w = Math.sqrt(block_area_km2 / aspect);
const block_l = block_w * aspect;
const spacing = CONSTANTS.BLOCK_SPACING_KM;
const grid_w = cols * block_w + (cols - 1) * spacing;
const grid_l = rows * block_l + (rows - 1) * spacing;
const features = [];
const publicSubCoord = state.activeDrawCenter;
const arrayOffsetKm = grid_l / 2 + CONSTANTS.ARRAY_OFFSET_KM;
const gridCenter = turf.destination(turf.point(publicSubCoord), arrayOffsetKm, 0, { units: "kilometers" }).geometry.coordinates;
const privateSubCoord = turf.destination(turf.point(gridCenter), grid_l / 2, 180, { units: "kilometers" }).geometry.coordinates;
features.push(turf.point(publicSubCoord, {
type: "poi",
selected_substation_name: state.selectedSubstation?.name || "Local Grid Node",
selected_substation_voltage: state.selectedSubstation?.voltage || "Unknown"
}));
features.push(turf.point(privateSubCoord, {
type: "private_sub",
selected_substation_name: "Customer Substation",
selected_substation_voltage: "Local Voltage"
}));
features.push(turf.lineString([privateSubCoord, publicSubCoord], { type: "export_cable" }));
features.push(getRectPolygon(gridCenter, grid_w + CONSTANTS.BOUNDARY_BUFFER_KM, grid_l + CONSTANTS.BOUNDARY_BUFFER_KM, "array_boundary"));
const ptN = turf.destination(turf.point(gridCenter), grid_l / 2, 0, { units: "kilometers" }).geometry.coordinates;
const ptNW = turf.destination(turf.point(ptN), grid_w / 2, -90, { units: "kilometers" }).geometry.coordinates;
const inverters = [];
let count = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (count >= N) break;
const posE = turf.destination(turf.point(ptNW), c * block_w + c * spacing + block_w / 2, 90, { units: "kilometers" }).geometry.coordinates;
const finalPos = turf.destination(turf.point(posE), r * block_l + r * spacing + block_l / 2, 180, { units: "kilometers" }).geometry.coordinates;
const nodeType = state.activeTab === "string" ? "string_substation" : "central_inverter";
const footType = state.activeTab === "string" ? "skid_footprint" : "central_footprint";
features.push(getRectPolygon(finalPos, block_w, block_l, footType));
inverters.push({ coords: finalPos, type: nodeType });
features.push(turf.point(finalPos, { type: nodeType }));
count++;