GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / ventus-grid-engine / engine

Network Topology and 1 more file (part 2)

A JavaScript module in Ventus Grid Engine that works with physical units (`physicalUnits`) (units: kV, MVA), covering transformers.

536 lines of JavaScript from ventus-grid-engine, in 2 files. Topic: Grid network and substations. Section 462 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. Network Topology render · ventus-grid-engine / engine/network-topology.js lines 1–319
  2. Voltage Drop electrical · ventus-grid-engine / engine/voltage-drop.js lines 1–217

Network Topology

A JavaScript module in Ventus Grid Engine that works with physical units (`physicalUnits`) (units: kV, MVA), covering transformers.

renderventus-grid-engine / engine/network-topology.js · lines 1–319 of 319 · Entry point · pattern physicalUnits (shared by 11 files)

What it does
It lists and searches transformers. Defines 11 functions or classes, including voltageOf, bandKey, ratingsOf, physicalUnits, parametersOf. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'topology'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: transformers.
Downstream impact
Used directly by 5 files: Network Topology Proof (ventus-grid-engine); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Electrical Distance Proof (ventus-grid-engine); Rating Envelope Proof (ventus-grid-engine); and 1 more. Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
What it achieves
It is built from the voltage of helper (`voltageOf`), the band key helper (`bandKey`) and the ratings of helper (`ratingsOf`). PROMOTED from `sources/v9-extracts/network-topology.mjs` (itself extracted verbatim from the LATER of two committed GridAtlas versions, `atlas/modules/202609012245-network-topology.js`, 384 lines — a strict superset of -network-topology.js, 279 lines. Its code works with 100 MVA.
Why it matters
Loaded by the Genome page at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by 4 files, including Network Topology Proof, Build Graph and Electrical Distance Proof.
Application
ventus-grid-engine · engine · JavaScript module
Uses
none found
Used by
imported by Network Topology Proof (import), named by URL in Build Graph (estate URL), imported by Electrical Distance Proof (import), imported by Rating Envelope Proof (import), named by URL in Ventus Grid Engine — Genome Page (estate URL), mentioned in Standalone (comment link)
Produces
ACCEPTS, NOT_AN_ASSESSMENT, IMPEDANCE_BASIS, UNDECLARED, ratingsOf, physicalUnits, parametersOf, index, schema
Defines here
voltageOf, bandKey, ratingsOf, physicalUnits, parametersOf, index, land, siteOf, graph, resolve, at
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 engine/network-topology.js:1-319 · blob 819b0b27c2cb890cb48cda96558cad14647082ab · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
/**
 * Module: network-topology
 *
 * PROMOTED from sources/v9-extracts/network-topology.mjs (itself extracted
 * verbatim from the LATER of two committed gridatlas versions,
 * atlas/modules/202609012245-network-topology.js, 384 lines — a strict
 * superset of 202609012145-network-topology.js, 279 lines: at() is
 * byte-identical between the two; 202609012245 adds physicalUnits() and
 * graph() so electrical-distance.js and rating-envelope.js (both of which
 * require 'gridatlas.module.network-topology.graph.v1') have something to
 * consume). Not one of the six named extraction targets, but promoted
 * because both electrical-distance and rating-envelope are inert without it.
 *
 * What the network operator publishes about ONE site: its nodes, the
 * circuits that land on them, the transformers between them, the changes
 * it has published for future years, and which other sites those circuits
 * reach. Appendix B of the Electricity Ten Year Statement, read as a
 * node/branch model and reported as facts.
 *
 * Depends on: nothing. Topology is not geometry — this module never
 * measures a distance and never touches a coordinate.
 *
 * CHANGED FROM THE SOURCE: the IIFE and `window.__GRIDATLAS_MODULES__`
 * registration are removed. `index()` and its helpers are otherwise
 * unchanged — verified verbatim against
 * gridatlas/atlas/modules/202609012245-network-topology.js at HEAD
 * 64268fd06a0da54ddffbcdaaaee382e314e829f7 (see sources/provenance.json).
 */

export const ACCEPTS = 'data-grid-gb.transmission-network.v1';

export const NOT_AN_ASSESSMENT =
  'Counts, lengths, ratings and impedances are what the network operator '
  + 'publishes about this site. None of them states whether any project can '
  + 'connect here, which depends on queue position, committed connections, '
  + 'consent and commercial terms that no published appendix contains.';

export const IMPEDANCE_BASIS =
  'R, X and B are percentages on a 100 MVA base, as published. They are '
  + 'network parameters, not a solved power flow.';

export const UNDECLARED = 'undeclared';

/* A node's voltage is trusted only where the product says the site
   declares it. Everything else is undeclared — never inferred from the
   digit in the node code, which is a derived convention the product
   itself marks as undocumented. */
function voltageOf(node) {
  if (!node) return null;
  if (node.voltage_consistent_with_site !== true) return null;
  return Number.isFinite(node.voltage_kv) ? node.voltage_kv : null;
}

const bandKey = (kv) => (kv == null ? UNDECLARED : String(kv));

export function ratingsOf(row) {
  const seasons = { winter: row.winter_mva, spring: row.spring_mva,
    summer: row.summer_mva, autumn: row.autumn_mva };
  const published = {};
  for (const [season, value] of Object.entries(seasons)) {
    if (Number.isFinite(value)) published[season] = value;
  }
  return Object.keys(published).length ? published : null;
}

/* A published branch is seen once from EACH of its ends, so a site that
   owns both ends of a branch publishes it twice. See source comment
   (network-topology.js:96-124) for the Cowley 5-vs-10 case that motivated
   this. Pairs are keyed by the two node names so a branch seen from both
   directions is counted once, and one seen from only one direction (what
   a voltage-filtered query sees of an internal machine) is also counted
   once. */
export function physicalUnits(records) {
  const pairs = new Map();
  for (const record of records) {
    const near = String(record.from_node);
    const far = String(record.to_node);
    const forward = near < far;
    const key = forward ? near + ' ' + far : far + ' ' + near;
    if (!pairs.has(key)) pairs.set(key, { forward: 0, reverse: 0 });
    const seen = pairs.get(key);
    if (forward) seen.forward += 1; else seen.reverse += 1;
  }
  let units = 0;
  for (const seen of pairs.values()) {
    units += (seen.forward && seen.reverse)
      ? Math.max(seen.forward, seen.reverse)
      : seen.forward + seen.reverse;
  }
  return units;
}

export function parametersOf(row) {
  const published = {};
  for (const [key, field] of [['r_pct', 'r_pct_100mva'], ['x_pct', 'x_pct_100mva'],
    ['b_pct', 'b_pct_100mva']]) {
    if (Number.isFinite(row[field])) published[key] = row[field];
  }
  return Object.keys(published).length ? published : null;
}

/**
 * @param product  the parsed data-grid-gb transmission-network payload
 * @returns an index, or null if the schema is not the one this reads
 */
export function index(product) {
  if (!product || product.schema !== ACCEPTS) return null;

  const nodes = new Map();
  for (const node of product.nodes || []) {
    if (node && node.node) nodes.set(node.node, node);
  }

  const sitesByCode = new Map();
  const sitesByName = new Map();
  for (const site of product.sites || []) {
    if (!site || !site.code) continue;
    sitesByCode.set(String(site.code).toUpperCase(), site);
    if (site.name) sitesByName.set(String(site.name).toUpperCase().trim(), site);
  }

  /* Branches are indexed by the node they land on, both ends, because a
     circuit is a fact about both of its sites. */
  const byNode = new Map();
  function land(nodeName, entry) {
    if (!nodeName) return;
    if (!byNode.has(nodeName)) byNode.set(nodeName, []);
    byNode.get(nodeName).push(entry);
  }
  for (const [kind, rows] of [['circuit', product.circuits],
    ['transformer', product.transformers], ['planned_change', product.planned_changes]]) {
    for (const row of rows || []) {
      if (!row) continue;
      land(row.node_1, { kind, row, near: 'node_1', far: 'node_2' });
      land(row.node_2, { kind, row, near: 'node_2', far: 'node_1' });
    }
  }

  function siteOf(nodeName) {
    const node = nodes.get(nodeName);
    return node ? node.site_code : null;
  }

  /* The adjacency, handed out rather than rebuilt. Every accessor here is
     a READ of the structures at() already uses, so a traversal cannot
     disagree with a one-hop view about which nodes exist, which site a
     node belongs to, or whether a node's voltage is trustworthy.
     planned_change rows are excluded from edges: a change published for
     2029 is not a path a current can take today. They remain available
     through at(). */
  function graph() {
    return {
      schema: 'gridatlas.module.network-topology.graph.v1',
      has: (name) => nodes.has(name),
      nodeVoltageKv: (name) => voltageOf(nodes.get(name)),
      nodeSiteCode: (name) => {
        const node = nodes.get(name);
        return node ? node.site_code : null;
      },
      /* circuits and transformers only — see above */
      edgesAt: (name) => (byNode.get(name) || [])
        .filter((entry) => entry.kind !== 'planned_change'),
      nodesOfSite: (code) => {
        const wanted = String(code || '').toUpperCase();
        const out = [];
        for (const node of nodes.values()) {
          if (String(node.site_code || '').toUpperCase() === wanted) out.push(node.node);
        }
        return out.sort();
      },
      siteByCode: (code) => sitesByCode.get(String(code || '').toUpperCase()) || null,
      ratingsOf,
      parametersOf
    };
  }

  function resolve(key) {
    if (!key) return null;
    const wanted = String(key).toUpperCase().trim();
    return sitesByCode.get(wanted) || sitesByName.get(wanted) || null;
  }

  /**
   * Everything published about one site, grouped by the voltage of the
   * node each branch lands on. Never a site-wide range.
   *
   * @param key          site code or exact site name
   * @param options      { voltageKv } to restrict to one voltage
   */
  function at(key, options) {
    const site = resolve(key);
    if (!site) return null;
    const wantedKv = options && Number.isFinite(options.voltageKv)
      ? options.voltageKv : null;

    const siteNodes = [];
    for (const node of nodes.values()) {
      if (node.site_code !== site.code) continue;
      const kv = voltageOf(node);
      if (wantedKv != null && kv !== wantedKv) continue;
      siteNodes.push({ node: node.node, voltage_kv: kv });
    }
    siteNodes.sort((a, b) => a.node.localeCompare(b.node));

    const byVoltage = new Map();
    const neighbours = new Map();

    for (const entry of siteNodes) {
      for (const landing of byNode.get(entry.node) || []) {
        const farNode = landing.row[landing.far];
        const farSiteCode = siteOf(farNode);
        const farSite = farSiteCode ? sitesByCode.get(farSiteCode) : null;
        const internal = farSiteCode === site.code;

        const key2 = bandKey(entry.voltage_kv);
        if (!byVoltage.has(key2)) {
          byVoltage.set(key2, { voltage_kv: entry.voltage_kv,
            circuits: [], transformers: [], planned_changes: [] });
        }
        const band = byVoltage.get(key2);

        const published = {
          from_node: entry.node,
          to_node: farNode,
          to_site_code: farSiteCode,
          to_site_name: farSite ? farSite.name : null,
          within_this_site: internal,
          transmission_owner: landing.row.transmission_owner || null,
          parameters_pct_100mva: parametersOf(landing.row),
          ratings_mva: ratingsOf(landing.row)
        };

        if (landing.kind === 'circuit') {
          published.circuit_type = landing.row.circuit_type || null;
          if (Number.isFinite(landing.row.ohl_km)) published.ohl_km = landing.row.ohl_km;
          if (Number.isFinite(landing.row.cable_km)) published.cable_km = landing.row.cable_km;
          band.circuits.push(published);
        } else if (landing.kind === 'transformer') {
          if (Number.isFinite(landing.row.rating_mva)) published.rating_mva = landing.row.rating_mva;
          delete published.ratings_mva;
          band.transformers.push(published);
        } else {
          published.year = landing.row.year || null;
          published.status = landing.row.status || null;
          published.asset = landing.row.asset || null;
          band.planned_changes.push(published);
        }

        /* A neighbour is another SITE this site's circuits reach. An
           internal branch is not a neighbour, and a planned change is
           not a neighbour either — it has not been built. */
        if (landing.kind === 'circuit' && !internal && farSiteCode) {
          if (!neighbours.has(farSiteCode)) {
            neighbours.set(farSiteCode, {
              site_code: farSiteCode,
              site_name: farSite ? farSite.name : null,
              circuits: 0
            });
          }
          neighbours.get(farSiteCode).circuits += 1;
        }
      }
    }

    const voltages = [...byVoltage.entries()]
      .sort((a, b) => {
        if (a[0] === UNDECLARED) return 1;
        if (b[0] === UNDECLARED) return -1;
        return Number(b[0]) - Number(a[0]);
      })
      .map(([, band]) => band);

    return {
      schema: 'gridatlas.module.network-topology.v1',
      source: ACCEPTS,
      site: {
        code: site.code,
        name: site.name,
        transmission_owner: site.transmission_owner || null,
        voltages_kv: Array.isArray(site.voltages_kv) ? site.voltages_kv.slice() : []
      },
      requested_voltage_kv: wantedKv,
      nodes: siteNodes,
      by_voltage: voltages,
      neighbours: [...neighbours.values()].sort((a, b) => b.circuits - a.circuits),
      counts: {
        nodes: siteNodes.length,
        circuits: physicalUnits(voltages.flatMap(band => band.circuits)),
        transformers: physicalUnits(voltages.flatMap(band => band.transformers)),
        planned_changes: physicalUnits(voltages.flatMap(band => band.planned_changes)),
        circuit_landings: voltages.reduce((sum, band) => sum + band.circuits.length, 0),
        transformer_landings: voltages.reduce((sum, band) => sum + band.transformers.length, 0),
        planned_change_landings: voltages.reduce((sum, band) => sum + band.planned_changes.length, 0),
        neighbour_sites: neighbours.size
      },
      counts_are_units: 'A site holds both ends of a transformer and of any '
        + 'internal circuit, so the same branch lands twice. The counts above '
        + 'are physical units; the landing tallies beside them are what the '
        + 'per-voltage lists contain.',
      impedance_basis: IMPEDANCE_BASIS,
      not_an_assessment: NOT_AN_ASSESSMENT
    };
  }

  return {
    schema: 'gridatlas.module.network-topology.v1',
    source: ACCEPTS,
    counts: {
      sites: sitesByCode.size,
      nodes: nodes.size,
      branch_landings: byNode.size
    },
    site: resolve,
    at,
    graph
  };
}

export const schema = 'gridatlas.module.network-topology.v1';

Voltage Drop

A JavaScript module in Ventus Grid Engine that works with cables. It is built from the positive step (`positive`), the non negative helper (`nonNegative`) and the ratio step (`ratio`).

electricalventus-grid-engine / engine/voltage-drop.js · lines 1–217 of 217 · pattern voltageDropVolts (shared by 2 files)

What it does
It calculates cables. Defines 8 functions or classes, including positive, nonNegative, ratio, phasesOf, voltageDropVolts.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'grid-network'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: cables.
Downstream impact
Used directly by 5 files: Grid Engine — Solar Farm Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060318-solar-farm/); Grid Engine — Voltage Drop Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060313-voltage-drop/); Voltage Drop Proof (ventus-grid-engine); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); and 1 more. Reached from 4 other entry points, including Homepage V090 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v090.html); Homepage V091 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v091.html); Homepage V093 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v093.html).
What it achieves
What a cable run costs in volts and in watts.
Why it matters
Loaded by the Solar Farm page in GlobalGrid2050 at https://globalgrid2050.com/grid_engine/202609060318-solar-farm/ and 1 other page. Also imported by Voltage Drop Proof, Build Graph and Current from Power Proof.
Application
ventus-grid-engine · engine · JavaScript module
VEDIC
DROP (GG2050-VEDIC-000024): Ventus Grid Engine / voltage-drop · Electrical engineering / Applied mathematics. current_a, length_m, resistance_ohm_per_km, reactance_ohm_per_km, power_factor, phases → voltage_drop_record
VEDIC
PERCENT (GG2050-VEDIC-000025): Ventus Grid Engine / voltage-drop · Electrical engineering / Applied mathematics. drop_volts, nominal_volts → drop_percent
VEDIC
LOSS (GG2050-VEDIC-000026): Ventus Grid Engine / voltage-drop · Electrical engineering / Applied mathematics. current_a, length_m, resistance_ohm_per_km, phases → losses_watts
Uses
none found
Used by
linked from Grid Engine — Solar Farm Page (link), linked from Grid Engine — Voltage Drop Page (link), imported by Voltage Drop Proof (import), named by URL in Build Graph (estate URL), imported by Current from Power Proof (import)
Produces
schema, PHASE_FACTOR, voltageDropVolts, dropPercent, lossesWatts, annualLossKwh, NOT_COMPUTED
Defines here
positive, nonNegative, ratio, phasesOf, voltageDropVolts, dropPercent, lossesWatts, annualLossKwh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 engine/voltage-drop.js:1-217 · blob 85f48ecf7effabb47973b0a056f90e82b8196ef2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
 * Module: voltage-drop
 *
 * APPLIED ENGINEERING. What a cable run costs in volts and in watts.
 *
 * WHY THIS DECIDES CABLE SIZE MORE OFTEN THAN CURRENT DOES.
 * A cable is chosen for three things: it must carry the current without
 * overheating, it must clear a fault, and it must deliver the voltage at the
 * far end. On a long run — a solar farm's internal collection, a depot's
 * feeders, anything measured in hundreds of metres — the third constraint bites
 * first. A conductor perfectly happy on ampacity can still be the wrong size,
 * because by the time the current reaches the far inverter the voltage has
 * fallen further than the equipment will accept.
 *
 * THE ARITHMETIC.
 * A cable has resistance and reactance per unit length. The load draws current
 * at some power factor, and the drop along the run is the component of the
 * impedance voltage in phase with the supply:
 *
 *     three phase:   Vdrop = sqrt(3) x I x L x (R cos(phi) + X sin(phi))
 *     single phase:  Vdrop = 2      x I x L x (R cos(phi) + X sin(phi))
 *
 * The factor differs because a single-phase circuit's current returns down a
 * second conductor and drops volts in both, while a balanced three-phase
 * circuit's return currents cancel. Getting that factor wrong is a 15% error
 * in the same direction every time.
 *
 * Note the power factor term. At unity the reactance contributes nothing and
 * only R matters; at 0.8 the reactance contributes 60% of its value, and on a
 * large cable — where X approaches and can exceed R — ignoring it under-states
 * the drop badly. Motors, and any poorly corrected industrial load, are exactly
 * where that error lands.
 *
 * LOSSES ARE A SEPARATE QUESTION AND ARE ANSWERED SEPARATELY.
 * Heat is I squared R, and only R: reactance stores and returns energy rather
 * than dissipating it. So a run can have an acceptable voltage drop and
 * expensive losses, or the reverse, and the two are computed here as two
 * different numbers rather than one conflated one.
 *
 * WHAT THIS MODULE REFUSES.
 * It will not choose a cable. Selection needs the installation method, the
 * grouping, the ambient and ground temperature, the soil thermal resistivity,
 * the depth of burial, the protective device and the fault clearance time —
 * and it needs the manufacturer's tables for the actual product. Every one of
 * those is absent here. It also carries no R and X values of its own: those
 * belong to a specific conductor in a specific arrangement, and a plausible
 * default would be the most dangerous thing this file could contain.
 *
 * Schema: ventus-grid-engine.voltage-drop.v1
 */

export const schema = 'ventus-grid-engine.voltage-drop.v1';

export const PHASE_FACTOR = Object.freeze({
    three: Math.sqrt(3),
    single: 2
});

function positive(name, v) {
    if (typeof v !== 'number' || !Number.isFinite(v)) {
        throw new TypeError(`${name} must be a finite number, received ${v === null ? 'null' : typeof v}`);
    }
    if (v <= 0) throw new RangeError(`${name} must be greater than zero, received ${v}`);
    return v;
}

function nonNegative(name, v) {
    if (typeof v !== 'number' || !Number.isFinite(v)) {
        throw new TypeError(`${name} must be a finite number, received ${v === null ? 'null' : typeof v}`);
    }
    if (v < 0) throw new RangeError(`${name} must not be negative, received ${v}`);
    return v;
}

function ratio(name, v) {
    positive(name, v);
    if (v > 1) throw new RangeError(
        `${name} must be a fraction in (0, 1], received ${v}. A power factor of 90% must be passed as 0.9.`);
    return v;
}

function phasesOf(phases) {
    if (phases !== 'three' && phases !== 'single') {
        throw new RangeError(`phases must be "three" or "single", received ${JSON.stringify(phases)}`);
    }
    return phases;
}

/**
 * Volts lost along a run.
 *
 * R and X are per kilometre and belong to the conductor you are actually
 * using. There is no default: see the header.
 */
export function voltageDropVolts({
    currentA, lengthM, resistanceOhmPerKm, reactanceOhmPerKm = 0, powerFactor, phases = 'three'
}) {
    positive('currentA', currentA);
    positive('lengthM', lengthM);
    positive('resistanceOhmPerKm', resistanceOhmPerKm);
    nonNegative('reactanceOhmPerKm', reactanceOhmPerKm);
    ratio('powerFactor', powerFactor);
    phasesOf(phases);

    const km = lengthM / 1000;
    const sinPhi = Math.sqrt(1 - powerFactor * powerFactor);
    const zEffective = resistanceOhmPerKm * powerFactor + reactanceOhmPerKm * sinPhi;
    const factor = PHASE_FACTOR[phases];
    const drop = factor * currentA * km * zEffective;

    const resistivePart = factor * currentA * km * resistanceOhmPerKm * powerFactor;
    return {
        schema,
        quantity: 'voltage_drop_volts',
        value: drop,
        unit: 'V',
        resistiveVolts: resistivePart,
        reactiveVolts: drop - resistivePart,
        from: { currentA, lengthM, resistanceOhmPerKm, reactanceOhmPerKm, powerFactor, phases },
        basis:
            `${currentA} A over ${lengthM} m of conductor at ${resistanceOhmPerKm} ohm/km resistance and ` +
            `${reactanceOhmPerKm} ohm/km reactance, at a power factor of ${powerFactor}, ` +
            `${phases}-phase (factor ${factor.toFixed(4)}). Of ${drop.toFixed(2)} V lost, ` +
            `${resistivePart.toFixed(2)} V is resistive and ${(drop - resistivePart).toFixed(2)} V is ` +
            `reactive. At unity power factor the reactance would contribute nothing; the lower the ` +
            `power factor the more of X appears in the answer, which is why ignoring X on a large ` +
            `cable feeding a poorly corrected load under-states the drop.`
    };
}

/**
 * The drop as a percentage of a nominal voltage, which is how every limit is
 * written.
 */
export function dropPercent({ dropVolts, nominalVolts }) {
    positive('dropVolts', dropVolts);
    positive('nominalVolts', nominalVolts);
    return {
        schema,
        quantity: 'voltage_drop_percent',
        value: (dropVolts / nominalVolts) * 100,
        unit: '%',
        from: { dropVolts, nominalVolts },
        basis:
            `${dropVolts.toFixed(2)} V on a ${nominalVolts} V nominal system is ` +
            `${((dropVolts / nominalVolts) * 100).toFixed(3)}%. What limit applies is a design and ` +
            `compliance question — it depends on the installation, on what is at the far end, and on ` +
            `how much of the allowance the rest of the system has already spent. No limit is asserted here.`
    };
}

/**
 * Heat: I squared R, and only R.
 *
 * Reactance stores and returns energy; it does not dissipate it. A run can have
 * an acceptable drop and expensive losses, or the reverse.
 */
export function lossesWatts({ currentA, lengthM, resistanceOhmPerKm, phases = 'three' }) {
    positive('currentA', currentA);
    positive('lengthM', lengthM);
    positive('resistanceOhmPerKm', resistanceOhmPerKm);
    phasesOf(phases);
    const km = lengthM / 1000;
    /* Three phase: three conductors each carrying I. Single phase: two
       conductors, both carrying the full current. */
    const conductors = phases === 'three' ? 3 : 2;
    const watts = conductors * currentA * currentA * resistanceOhmPerKm * km;
    return {
        schema,
        quantity: 'losses_watts',
        value: watts,
        unit: 'W',
        conductors,
        from: { currentA, lengthM, resistanceOhmPerKm, phases },
        basis:
            `${conductors} conductors carrying ${currentA} A through ` +
            `${(resistanceOhmPerKm * km).toFixed(4)} ohm each dissipate ${watts.toFixed(1)} W as heat. ` +
            `Only resistance appears: reactance stores and returns energy rather than dissipating it, ` +
            `so a run may have an acceptable voltage drop and expensive losses, or the reverse.`
    };
}

/**
 * Annual energy lost, at a stated loss load factor.
 *
 * Losses vary with the SQUARE of current, so they cannot be scaled by the
 * ordinary load factor. The loss load factor is a different quantity and it is
 * required rather than derived.
 */
export function annualLossKwh({ peakLossWatts, lossLoadFactor, hours = 8760 }) {
    positive('peakLossWatts', peakLossWatts);
    ratio('lossLoadFactor', lossLoadFactor);
    positive('hours', hours);
    return {
        schema,
        quantity: 'annual_loss_kwh',
        value: (peakLossWatts * lossLoadFactor * hours) / 1000,
        unit: 'kWh',
        from: { peakLossWatts, lossLoadFactor, hours },
        basis:
            `${peakLossWatts.toFixed(1)} W at peak, held for the equivalent of ${lossLoadFactor} of ` +
            `${hours} hours. The LOSS load factor is not the load factor: losses follow the square of ` +
            `current, so a site with a load factor of 0.5 typically has a loss load factor well below ` +
            `it. Using the load factor here over-states annual losses, sometimes badly.`
    };
}

export const NOT_COMPUTED = Object.freeze({
    cableSelection:
        'This will not choose a cable. Selection needs the installation method, grouping, ambient and ground temperature, soil thermal resistivity, depth of burial, the protective device and the fault clearance time, plus the manufacturer\'s tables for the actual product. None of that is here.',
    conductorParameters:
        'No R or X values are carried. They belong to a specific conductor in a specific arrangement, and a plausible-looking default would be the most dangerous thing this file could contain.',
    permittedDrop:
        'What drop is permitted depends on the installation, on what sits at the far end, and on how much of the allowance the rest of the system has already spent. No limit is asserted.',
    faultWithstand:
        'Whether a conductor survives a fault until the protection clears is a separate calculation needing the prospective fault current and the device characteristic. A cable adequate for volts and amps can still be inadequate for a fault.'
});