GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / ventus-grid-engine / engine

Electrification Model and 1 more file

A JavaScript module in Ventus Grid Engine that works with non negative count (`nonNegativeCount`) and fleet demand (`fleetDemand`).

592 lines of JavaScript from ventus-grid-engine, in 2 files. Topic: Websites and apps. Section 2018 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. Electrification Demand energy-data · ventus-grid-engine / engine/electrification-demand.js lines 1–247
  2. Electrification Model energy-data · ventus-grid-engine / engine/electrification-model.js lines 1–345

Electrification Demand

A JavaScript module in Ventus Grid Engine that averages power GW (`averagePowerGw`) and loads factor peak (`loadFactorFromPeak`).

energy-dataventus-grid-engine / engine/electrification-demand.js · lines 1–247 of 247 · pattern requirePositive (shared by 2 files)

What it does
It calculates its inputs. Defines 8 functions or classes, including requireRatio, requirePositive, describe, averagePowerGw, peakFromLoadFactorGw.
Downstream impact
Used directly by 6 files: Grid Engine — Substation Growth Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060218-substation-growth/); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Electrification Demand Proof (ventus-grid-engine); Grid Engine — Electrification Workbench Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060148-electrification-workbench/); and 2 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
It loads factor peak (`loadFactorFromPeak`) and is built from the require ratio helper (`requireRatio`) and the require positive helper (`requirePositive`). Every function here is arithmetic a grid engineer would do on paper, made exact, named, and given a unit.
Why it matters
Loaded by the Substation Growth page in GlobalGrid2050 at https://globalgrid2050.com/grid_engine/202609060218-substation-growth/ and 3 other pages. Also imported by Build Graph and Electrification Demand Proof.
Application
ventus-grid-engine · engine · JavaScript module
VEDIC
CALCULATE AVERAGE POWER (GG2050-VEDIC-000054): Ventus Grid Engine · Energy and power calculation. annual_energy_twh → average_power_gw_result
VEDIC
ESTIMATE PEAK DEMAND (GG2050-VEDIC-000055): Ventus Grid Engine · Energy and power calculation. average_demand_gw, load_factor_fraction → estimated_peak_demand_gw_result
VEDIC
CALCULATE LOAD FACTOR (GG2050-VEDIC-000056): Ventus Grid Engine · Energy and power calculation. average_demand_gw, peak_demand_gw → dimensionless_load_factor_result
Uses
none found
Used by
linked from Grid Engine — Substation Growth Page (link), named by URL in Build Graph (estate URL), imported by Electrification Demand Proof (import), linked from Grid Engine — Electrification Workbench Page (link), linked from Grid Engine — Data Centre Connection Page (link), linked from Grid Engine — Compute Against Charging Page (link)
Produces
schema, HOURS_PER_YEAR, HOURS_TWH_TO_GW, averagePowerGw, peakFromLoadFactorGw, loadFactorFromPeak, nameplateFromCapacityFactorGw, electricityForDisplacedFuelTwh, NOT_COMPUTED
Defines here
requireRatio, requirePositive, describe, averagePowerGw, peakFromLoadFactorGw, loadFactorFromPeak, nameplateFromCapacityFactorGw, electricityForDisplacedFuelTwh
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/electrification-demand.js:1-247 · blob 864a2ecf5f89315f7017539a5ed796473691167a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: production_core
/**
 * Module: electrification-demand
 *
 * APPLIED ENGINEERING. Every function here is arithmetic a grid engineer
 * would do on paper, made exact, named, and given a unit. Nothing here is a
 * forecast, and nothing here decides anything.
 *
 * WHY THIS MODULE EXISTS.
 * The electrification paper (globalgrid2050.com/papers/202609060203-electrification/)
 * sets out how annual energy, average power, peak demand, capacity factor and
 * displaced fuel relate to one another. Written down, that arithmetic is
 * unambiguous. Repeated from memory into a table, it is where the errors get
 * in: a peak-to-average ratio measured against a rounded reference, a load
 * factor quietly reused across two different systems, a capacity factor
 * applied to peak instead of to energy. This module is the arithmetic, once,
 * with the boundary conditions attached to it.
 *
 * THE FOUR RELATIONS, AND WHAT EACH ONE IS ACTUALLY SAYING.
 *
 * 1. Average power. P_avg (GW) = E (TWh) / 8.76. There are 8,760 hours in a
 *    non-leap year and 1 TWh = 1,000 GWh, so TWh/8.76 gives GW directly. This
 *    is a definition, not a model: it is exact, and it is the only quantity
 *    here that carries no assumption. It is also the least useful number on
 *    its own, because no network is ever sized for its average.
 *
 * 2. Peak from load factor. P_peak = P_avg / LF. The load factor is the
 *    ratio of average to peak over a stated period, so this is the definition
 *    rearranged. The assumption is entirely in the choice of LF, which is why
 *    this function REQUIRES the caller to state it rather than defaulting to
 *    one. GB's present system load factor and a deeply electrified system's
 *    load factor are different numbers, and a system with heat pumps and one
 *    with smart-charged EVs are different again — heat drives a winter peak
 *    upward while managed charging fills a trough. There is no single correct
 *    value, so this module supplies none.
 *
 * 3. Nameplate from capacity factor. C (GW) = E (TWh) / (8.76 x CF). Note
 *    what this is NOT: it is not a statement about meeting peak, about firm
 *    capacity, or about adequacy. It answers exactly one question — how much
 *    nameplate, at a stated annual capacity factor, produces this much annual
 *    energy. A system that satisfies this equation may still fail on a still,
 *    cold evening, which is why adequacy is a chronological study and not a
 *    division.
 *
 * 4. Electricity for displaced fuel.
 *      E_elec = E_fuel x eta_old / eta_new
 *    Burning fuel to make heat or motion wastes most of it; doing the same
 *    work electrically wastes much less, and a heat pump moves more heat than
 *    the energy it consumes. So displaced fuel energy does NOT map one-for-one
 *    onto electricity, and the ratio is not a constant — it is roughly 0.33
 *    for a gas boiler replaced by a COP 3 heat pump, roughly 0.31 for a petrol
 *    car replaced by an EV, and roughly 0.95 for industrial heat where both
 *    routes are already efficient. The single most common error in
 *    electrification arithmetic is skipping this step and treating primary
 *    energy as future electrical load. This function exists to make that
 *    error impossible to make silently.
 *
 * WHAT THIS MODULE REFUSES TO DO, AND WHY THE PROOF CHECKS THE REFUSAL.
 * There is no function here that returns headroom, spare capacity, connection
 * availability, or a per-site uplift. The paper is explicit that a national
 * load factor cannot establish utilisation at any particular transformer, and
 * that scenario arithmetic is not evidence of connection headroom. Those are
 * not gaps to be filled later by a keener version of this file: computing
 * them needs the network operator's model, its running arrangement and its
 * outage plan, none of which are public. The proof asserts these functions are
 * ABSENT, so that their absence is a tested property rather than an oversight
 * somebody helpfully corrects.
 *
 * Depends on: nothing. Pure arithmetic on caller-supplied scalars. No network,
 * no DOM, no data files, no clock.
 *
 * Schema: ventus-grid-engine.electrification-demand.v1
 */

export const schema = 'ventus-grid-engine.electrification-demand.v1';

/* 8,760 hours in a non-leap year, expressed so that TWh / HOURS_TWH_TO_GW is
   GW. Stated as a constant because a magic 8.76 in four functions is four
   chances to type 8.67. A leap year is 8,784 h; the 0.27% difference is far
   below the uncertainty in any scenario this module will be handed, and using
   one figure keeps two calls comparable. Where that 0.27% would matter, the
   quantity being computed is not an annual average. */
export const HOURS_PER_YEAR = 8760;
export const HOURS_TWH_TO_GW = HOURS_PER_YEAR / 1000;

/* A ratio that must be a fraction of one. Load factors, capacity factors,
   coincidence factors and efficiencies all live in (0, 1]; a caller passing
   40 for "40%" is the error this catches, and it catches it loudly rather
   than returning a number 100 times too small. */
function requireRatio(name, value, { allowAboveOne = false } = {}) {
    if (typeof value !== 'number' || !Number.isFinite(value)) {
        throw new TypeError(`${name} must be a finite number, received ${describe(value)}`);
    }
    if (value <= 0) {
        throw new RangeError(`${name} must be greater than zero, received ${value}`);
    }
    if (!allowAboveOne && value > 1) {
        throw new RangeError(
            `${name} must be a fraction in (0, 1], received ${value}. ` +
            `A percentage such as 40 must be passed as 0.4.`
        );
    }
    return value;
}

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

function describe(value) {
    if (value === null) return 'null';
    if (Array.isArray(value)) return 'an array';
    return typeof value;
}

/**
 * Average power over a year, from annual energy.
 *
 * Exact by definition. Returns GW for TWh in.
 */
export function averagePowerGw({ annualTwh }) {
    requirePositive('annualTwh', annualTwh);
    return {
        schema,
        quantity: 'average_power_gw',
        value: annualTwh / HOURS_TWH_TO_GW,
        unit: 'GW',
        from: { annualTwh, hoursPerYear: HOURS_PER_YEAR },
        basis: 'Definition: mean power is annual energy divided by the hours in the year. Exact; carries no assumption.'
    };
}

/**
 * Peak demand implied by an average and a STATED load factor.
 *
 * The load factor is the assumption. It is required, never defaulted, and it
 * is returned alongside the answer so a figure cannot travel without it.
 */
export function peakFromLoadFactorGw({ averageGw, loadFactor }) {
    requirePositive('averageGw', averageGw);
    requireRatio('loadFactor', loadFactor);
    return {
        schema,
        quantity: 'peak_demand_gw',
        value: averageGw / loadFactor,
        unit: 'GW',
        from: { averageGw, loadFactor },
        basis:
            `Definition rearranged: peak = average / load factor, at a load factor of ${loadFactor} ` +
            `supplied by the caller. The load factor is the whole assumption; this figure is only ` +
            `as good as it. It is a sensitivity, not a forecast, and it is not a published peak.`
    };
}

/**
 * The load factor implied by an average and a peak that are both known.
 *
 * The inverse of the above, and the honest direction of travel: where a peak
 * is published, derive the load factor from it rather than assuming one.
 */
export function loadFactorFromPeak({ averageGw, peakGw }) {
    requirePositive('averageGw', averageGw);
    requirePositive('peakGw', peakGw);
    if (peakGw < averageGw) {
        throw new RangeError(
            `peakGw (${peakGw}) is below averageGw (${averageGw}); a peak cannot be lower than the mean it contains.`
        );
    }
    return {
        schema,
        quantity: 'load_factor',
        value: averageGw / peakGw,
        unit: 'dimensionless',
        from: { averageGw, peakGw },
        basis: 'Measured from a published peak rather than assumed. Prefer this direction wherever a peak is published.'
    };
}

/**
 * Nameplate capacity that yields a stated annual energy at a stated annual
 * capacity factor.
 *
 * Answers an energy question only. Says nothing about peak, firm capacity or
 * adequacy — see the header.
 */
export function nameplateFromCapacityFactorGw({ annualTwh, capacityFactor }) {
    requirePositive('annualTwh', annualTwh);
    requireRatio('capacityFactor', capacityFactor);
    return {
        schema,
        quantity: 'nameplate_capacity_gw',
        value: annualTwh / (HOURS_TWH_TO_GW * capacityFactor),
        unit: 'GW',
        from: { annualTwh, capacityFactor },
        basis:
            `Energy equivalence only: the nameplate that produces ${annualTwh} TWh a year at an annual ` +
            `capacity factor of ${capacityFactor}. It does not follow that this capacity meets peak, ` +
            `provides firm capacity, or satisfies adequacy — those are chronological studies.`
    };
}

/**
 * Electricity required to do work presently done by burning fuel.
 *
 *   E_elec = E_fuel x eta_old / eta_new
 *
 * eta_new may exceed 1 for a heat pump, which moves heat rather than making
 * it — a COP of 3 delivers three units of heat per unit of electricity. That
 * is the one ratio here allowed above one, and it is allowed deliberately.
 */
export function electricityForDisplacedFuelTwh({ fuelTwh, oldEfficiency, newPerformance }) {
    requirePositive('fuelTwh', fuelTwh);
    requireRatio('oldEfficiency', oldEfficiency);
    requireRatio('newPerformance', newPerformance, { allowAboveOne: true });
    const usefulTwh = fuelTwh * oldEfficiency;
    return {
        schema,
        quantity: 'electricity_required_twh',
        value: usefulTwh / newPerformance,
        unit: 'TWh',
        from: { fuelTwh, oldEfficiency, newPerformance, usefulOutputTwh: usefulTwh },
        basis:
            `Useful output is conserved, not fuel energy: ${fuelTwh} TWh of fuel at ${oldEfficiency} ` +
            `delivers ${usefulTwh.toFixed(3)} TWh of useful output, which an electrical route of ` +
            `performance ${newPerformance} supplies from the electricity stated. Displaced fuel energy ` +
            `never maps one-for-one onto electricity.`
    };
}

/* The refusals. Named here so a reader looking for them finds the reason
   rather than an empty space, and so the proof can assert that no function of
   these names is exported. */
export const NOT_COMPUTED = Object.freeze({
    headroom:
        'Spare capacity at a site is the network operator\'s figure, from its model, running arrangement and outage plan. None of those are public.',
    connectionAvailability:
        'Whether a connection can be made is answered by an application and an offer, never by scenario arithmetic.',
    perSiteUplift:
        'There is no defensible rule that every site receives the same percentage uplift; national growth does not distribute evenly.',
    adequacy:
        'Security of supply is a chronological study over weather years and outage scenarios. An annual total cannot demonstrate it.'
});

Electrification Model

A JavaScript module in Ventus Grid Engine that works with non negative count (`nonNegativeCount`) and fleet demand (`fleetDemand`).

energy-dataventus-grid-engine / engine/electrification-model.js · lines 1–345 of 345 · Not reached from any entry point (candidate for review) · pattern quantity (shared by 4 files)

What it does
It calculates its inputs. Defines 9 functions or classes, including positive, nonNegativeCount, meaningOf, quantity, electricalInputFromHeat.
Downstream impact
Used directly by 1 file: Electrification Model Proof (ventus-grid-engine).
What it achieves
It is built from the positive step (`positive`), the non negative count helper (`nonNegativeCount`) and the meaning of helper (`meaningOf`). What electrifying a fleet of end uses does to energy demand, and what it does to peak load. Its code works with 3.5 kW, 98 GW and 1.7 kW.
Why it matters
Imported by Electrification Model Proof.
Application
ventus-grid-engine · engine · JavaScript module
VEDIC
ESTIMATE HEATING ELECTRICITY (GG2050-VEDIC-000067): Ventus Grid Engine · Energy and power calculation. typed_delivered_heat, seasonal_performance_factor → typed_electrical_input_in_same_unit
VEDIC
ESTIMATE DELIVERED HEAT (GG2050-VEDIC-000068): Ventus Grid Engine · Energy and power calculation. typed_electrical_input, seasonal_performance_factor → typed_delivered_heat_in_same_unit
VEDIC
ESTIMATE FLEET DEMAND (GG2050-VEDIC-000072): Ventus Grid Engine · Energy and power calculation. units, perUnitNameplate, perUnitAfterDiversity → Labelled simultaneous and diversified quantities.
Uses
none found
Used by
imported by Electrification Model Proof (import)
Produces
schema, MEANING, NOT_COMPUTED, NEVER_ADDED, NOT_A_FORECAST, quantity, electricalInputFromHeat, heatFromElectricalInput, fleetDemand, combinedPeak, primaryEnergyForWork
Defines here
positive, nonNegativeCount, meaningOf, quantity, electricalInputFromHeat, heatFromElectricalInput, fleetDemand, combinedPeak, primaryEnergyForWork
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/electrification-model.js:1-345 · blob 3b4b92399199b8d4915026f912e1c7e8b9a65395 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
/**
 * Module: electrification-model
 *
 * APPLIED ENGINEERING. What electrifying a fleet of end uses does to energy
 * demand, and what it does to peak load. Two different questions with two
 * different answers, kept apart here because conflating them is the mistake
 * this file exists to prevent.
 *
 * WHY THIS FILE EXISTS, AND THE ERROR THAT JUSTIFIES IT.
 * A published UK report on electrification had to be corrected after an early
 * draft conflated the THERMAL OUTPUT of a heat pump with its ELECTRICAL INPUT.
 * A heat pump delivering 12.25 kW of heat draws about 3.5 kW of electricity at
 * a seasonal coefficient of performance of 3.5. Both numbers are written in
 * kilowatts. Both are correct. Interchanging them overstates electrical demand
 * by a factor of three and a half, and no unit check in the world would catch
 * it, because the unit is the same.
 *
 * So this module does not accept a power. It accepts a power WITH A MEANING,
 * and refuses to read one meaning as another. That is the whole design:
 *
 *     THERMAL_OUTPUT     heat delivered to a building
 *     ELECTRICAL_INPUT   electricity drawn from the network
 *     NAMEPLATE          the rating on the appliance, drawn only if it runs flat out
 *     AFTER_DIVERSITY    the contribution one unit makes to a network peak
 *     PRIMARY_ENERGY     energy entering the economy, fuel as burned
 *     FINAL_ENERGY       energy delivered to the end user
 *     USEFUL_WORK        the heat or motion actually obtained
 *
 * Seven meanings, three of them measured in watts, and every published error in
 * this field is a substitution between two of them.
 *
 * THE DIVERSITY POINT, WHICH IS THE ONE PLANNERS CARE ABOUT.
 * Twenty-eight million homes each with a 3.5 kW heat pump is not a 98 GW load,
 * because they do not all run at once. After diversity the maximum demand is
 * about 1.7 kW per home, so the same fleet contributes roughly 48 GW to a
 * network peak. The 98 GW figure is a stress test and must be labelled one.
 * This module returns both and names each, and it will not let a caller add a
 * nameplate sum to an after-diversity sum.
 *
 * WHAT THIS MODULE REFUSES.
 * It will not choose a coefficient of performance, a diversity factor or a
 * charging power: those are properties of a real appliance in a real place and
 * a plausible default would be the most dangerous thing this file could carry.
 * It will not tell you whether a network can take the answer, because that is
 * the rating and it is not here. It will not produce an emissions figure. And
 * it will not sum two quantities of different meaning, at all, ever.
 *
 * Schema: ventus-grid-engine.electrification-model.v1
 */

export const schema = 'ventus-grid-engine.electrification-model.v1';

/** The seven meanings a quantity may carry. A number without one is not an
 *  input to this module. */
export const MEANING = Object.freeze({
    THERMAL_OUTPUT: 'thermal_output',
    ELECTRICAL_INPUT: 'electrical_input',
    NAMEPLATE: 'nameplate',
    AFTER_DIVERSITY: 'after_diversity',
    PRIMARY_ENERGY: 'primary_energy',
    FINAL_ENERGY: 'final_energy',
    USEFUL_WORK: 'useful_work'
});

const POWER_MEANINGS = new Set([
    MEANING.THERMAL_OUTPUT, MEANING.ELECTRICAL_INPUT,
    MEANING.NAMEPLATE, MEANING.AFTER_DIVERSITY
]);

const ENERGY_MEANINGS = new Set([
    MEANING.PRIMARY_ENERGY, MEANING.FINAL_ENERGY, MEANING.USEFUL_WORK
]);

export const NOT_COMPUTED = Object.freeze({
    coefficientOfPerformance:
        'No seasonal coefficient of performance is carried here. It belongs to a '
        + 'specific machine in a specific building at a specific flow temperature, '
        + 'and the published range for heat pumps is roughly 3.5 to 5.',
    diversityFactor:
        'No after-diversity factor is carried here. It is measured, not derived, '
        + 'and it belongs to a particular network with a particular customer mix.',
    networkCapacity:
        'Whether a network can carry the answer is a question about ratings and '
        + 'about what already flows. Neither is in this module.',
    emissions:
        'No carbon intensity is carried here. An energy figure is not an '
        + 'emissions figure until someone states the intensity and its date.',
    timing:
        'This module has no clock. It says how much, never when, so it cannot '
        + 'tell you whether two peaks coincide.'
});

export const NEVER_ADDED =
    'Two quantities of different meaning are never summed. A nameplate total and '
    + 'an after-diversity total are different questions about the same fleet, and '
    + 'adding them answers neither.';

export const NOT_A_FORECAST =
    'A scenario is arithmetic on assumptions the caller supplied. It is not a '
    + 'prediction, and the assumptions travel with the answer so they can be '
    + 'argued with.';

/* ── guards ──────────────────────────────────────────────────────────────── */

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 nonNegativeCount(name, v) {
    if (!Number.isInteger(v) || v < 0) {
        throw new RangeError(`${name} must be a whole number of units, received ${v}`);
    }
    return v;
}

function meaningOf(name, m, allowed) {
    if (typeof m !== 'string' || !Object.values(MEANING).includes(m)) {
        throw new RangeError(`${name} must carry one of the declared meanings, received ${JSON.stringify(m)}`);
    }
    if (allowed && !allowed.has(m)) {
        throw new RangeError(
            `${name} carries the meaning "${m}", which is not one this argument accepts. ` +
            `A kilowatt of heat delivered and a kilowatt of electricity drawn are both kilowatts ` +
            `and they are not the same quantity.`);
    }
    return m;
}

/** A quantity is a number, a unit and a meaning. Nothing in this module accepts
 *  a bare number where a quantity is expected. */
export function quantity(value, unit, meaning) {
    positive('value', value);
    if (typeof unit !== 'string' || !unit) throw new TypeError('unit must be a non-empty string');
    meaningOf('meaning', meaning);
    return Object.freeze({ value, unit, meaning });
}

/* ── the heat pump: the conversion that was got wrong ────────────────────── */

/**
 * Electrical input implied by a thermal output at a stated seasonal
 * coefficient of performance.
 *
 * This is the ONLY route in this module between heat and electricity, and it
 * is explicit in both directions, because the correction that prompted this
 * file was a silent substitution in exactly this place.
 */
export function electricalInputFromHeat({ thermal, scop }) {
    if (!thermal || typeof thermal !== 'object') throw new TypeError('thermal must be a quantity');
    meaningOf('thermal.meaning', thermal.meaning, new Set([MEANING.THERMAL_OUTPUT]));
    positive('thermal.value', thermal.value);
    positive('scop', scop);
    if (scop <= 1) throw new RangeError(
        `scop must be greater than 1; a coefficient of performance of ${scop} would mean the machine `
        + 'delivers no more heat than the electricity it consumes, which is a resistance heater.');

    return {
        schema,
        quantity: 'electrical_input',
        value: thermal.value / scop,
        unit: thermal.unit,
        meaning: MEANING.ELECTRICAL_INPUT,
        from: { thermal: { ...thermal }, scop },
        basis:
            `Electricity drawn = heat delivered / SCOP. ${thermal.value} ${thermal.unit} of heat at a `
            + `seasonal coefficient of performance of ${scop} needs `
            + `${(thermal.value / scop).toFixed(3)} ${thermal.unit} of electricity. The two numbers share `
            + 'a unit and are not interchangeable.',
        not_computed: NOT_COMPUTED.coefficientOfPerformance
    };
}

/** The same conversion the other way, for a caller who knows the electrical
 *  input and wants the heat. Declared separately so neither direction is ever
 *  implied. */
export function heatFromElectricalInput({ electrical, scop }) {
    if (!electrical || typeof electrical !== 'object') throw new TypeError('electrical must be a quantity');
    meaningOf('electrical.meaning', electrical.meaning, new Set([MEANING.ELECTRICAL_INPUT]));
    positive('electrical.value', electrical.value);
    positive('scop', scop);
    return {
        schema,
        quantity: 'thermal_output',
        value: electrical.value * scop,
        unit: electrical.unit,
        meaning: MEANING.THERMAL_OUTPUT,
        from: { electrical: { ...electrical }, scop },
        basis: `Heat delivered = electricity drawn x SCOP.`,
        not_computed: NOT_COMPUTED.coefficientOfPerformance
    };
}

/* ── fleets: the stress test and the planning number, side by side ───────── */

/**
 * What a fleet of identical units contributes to demand, answered twice.
 *
 * `perUnitNameplate` is what one unit draws running flat out.
 * `perUnitAfterDiversity` is what one unit contributes to a network peak, which
 * is a measured property of a population and is always smaller.
 *
 * Both are returned, each labelled, and they are never added. The simultaneous
 * figure is marked as a stress test because that is what it is: nobody expects
 * twenty-eight million heat pumps to start in the same second, and a number
 * that assumes they do should never be quoted as a forecast.
 */
export function fleetDemand({ units, perUnitNameplate, perUnitAfterDiversity = null }) {
    nonNegativeCount('units', units);
    if (!perUnitNameplate || typeof perUnitNameplate !== 'object') {
        throw new TypeError('perUnitNameplate must be a quantity');
    }
    meaningOf('perUnitNameplate.meaning', perUnitNameplate.meaning,
        new Set([MEANING.NAMEPLATE, MEANING.ELECTRICAL_INPUT]));
    positive('perUnitNameplate.value', perUnitNameplate.value);

    const simultaneous = {
        value: units * perUnitNameplate.value,
        unit: perUnitNameplate.unit,
        meaning: MEANING.NAMEPLATE,
        label: 'every unit at once: a stress test, not an expectation'
    };

    let diversified = null;
    if (perUnitAfterDiversity) {
        meaningOf('perUnitAfterDiversity.meaning', perUnitAfterDiversity.meaning,
            new Set([MEANING.AFTER_DIVERSITY]));
        positive('perUnitAfterDiversity.value', perUnitAfterDiversity.value);
        if (perUnitAfterDiversity.unit !== perUnitNameplate.unit) {
            throw new RangeError(
                `after-diversity demand is in ${perUnitAfterDiversity.unit} and nameplate is in `
                + `${perUnitNameplate.unit}; this module does not convert units`);
        }
        if (perUnitAfterDiversity.value > perUnitNameplate.value) {
            throw new RangeError(
                `after-diversity demand (${perUnitAfterDiversity.value}) exceeds nameplate `
                + `(${perUnitNameplate.value}). Diversity can only reduce a contribution to peak; a `
                + 'larger figure means the two have been swapped.');
        }
        diversified = {
            value: units * perUnitAfterDiversity.value,
            unit: perUnitAfterDiversity.unit,
            meaning: MEANING.AFTER_DIVERSITY,
            label: 'contribution to a network peak, after diversity',
            ratio: perUnitAfterDiversity.value / perUnitNameplate.value
        };
    }

    return {
        schema,
        quantity: 'fleet_demand',
        units,
        simultaneous,
        diversified,
        never_added: NEVER_ADDED,
        not_computed: diversified ? NOT_COMPUTED.networkCapacity : NOT_COMPUTED.diversityFactor,
        not_a_forecast: NOT_A_FORECAST,
        basis: diversified
            ? `${units} units. Flat out: ${simultaneous.value} ${simultaneous.unit}. After diversity: `
              + `${diversified.value} ${diversified.unit}, which is `
              + `${(diversified.ratio * 100).toFixed(1)}% of the nameplate sum.`
            : `${units} units at ${perUnitNameplate.value} ${perUnitNameplate.unit} each, flat out. `
              + 'No diversity factor was supplied, so only the stress test is answered.'
    };
}

/** Two fleets contribute to one peak only if their peaks coincide, and this
 *  module has no clock. So it adds the after-diversity contributions and says
 *  plainly what that addition assumes. */
export function combinedPeak({ fleets }) {
    if (!Array.isArray(fleets) || fleets.length === 0) {
        throw new TypeError('fleets must be a non-empty array of fleetDemand results');
    }
    const parts = [];
    let unit = null;
    for (const f of fleets) {
        if (!f || !f.diversified) throw new RangeError(
            'every fleet must carry an after-diversity figure; summing nameplate totals across fleets '
            + 'multiplies one stress test by another and means nothing');
        if (unit === null) unit = f.diversified.unit;
        else if (unit !== f.diversified.unit) throw new RangeError(
            `fleets are in different units (${unit} and ${f.diversified.unit}); this module does not convert`);
        parts.push({ units: f.units, value: f.diversified.value, unit: f.diversified.unit });
    }
    return {
        schema,
        quantity: 'combined_peak',
        value: parts.reduce((a, p) => a + p.value, 0),
        unit,
        meaning: MEANING.AFTER_DIVERSITY,
        parts,
        assumes: 'that every fleet reaches its after-diversity maximum at the same hour. This module has '
               + 'no clock and cannot check that. If the peaks are separated in time the true combined '
               + 'peak is lower, and if a shared driver such as cold weather moves them together it is not.',
        not_computed: NOT_COMPUTED.timing,
        not_a_forecast: NOT_A_FORECAST
    };
}

/* ── the efficiency case for electrification ─────────────────────────────── */

/**
 * The primary energy a use case needs, before and after electrification, for
 * the same useful work.
 *
 * This is the arithmetic behind the claim that electrifying can cut primary
 * energy demand substantially: an internal combustion car turns roughly a
 * quarter of the fuel into motion while an electric one turns most of the
 * electricity into motion, and a gas boiler delivers a little less heat than
 * the gas it burns while a heat pump delivers several times its electricity.
 * The saving is real and it is a ratio of efficiencies, nothing more.
 */
export function primaryEnergyForWork({ usefulWork, incumbentEfficiency, electrifiedEfficiency }) {
    if (!usefulWork || typeof usefulWork !== 'object') throw new TypeError('usefulWork must be a quantity');
    meaningOf('usefulWork.meaning', usefulWork.meaning, new Set([MEANING.USEFUL_WORK]));
    positive('usefulWork.value', usefulWork.value);
    positive('incumbentEfficiency', incumbentEfficiency);
    positive('electrifiedEfficiency', electrifiedEfficiency);

    const before = usefulWork.value / incumbentEfficiency;
    const after = usefulWork.value / electrifiedEfficiency;
    const saved = before - after;

    return {
        schema,
        quantity: 'primary_energy_for_work',
        unit: usefulWork.unit,
        meaning: MEANING.PRIMARY_ENERGY,
        before: { value: before, unit: usefulWork.unit, meaning: MEANING.PRIMARY_ENERGY },
        after: { value: after, unit: usefulWork.unit, meaning: MEANING.PRIMARY_ENERGY },
        saved: { value: saved, unit: usefulWork.unit, meaning: MEANING.PRIMARY_ENERGY },
        reductionRatio: before > 0 ? saved / before : 0,
        from: { usefulWork: { ...usefulWork }, incumbentEfficiency, electrifiedEfficiency },
        basis:
            `Same useful work, two conversion chains. At ${incumbentEfficiency} it needs `
            + `${before.toFixed(3)} ${usefulWork.unit}; at ${electrifiedEfficiency} it needs `
            + `${after.toFixed(3)} ${usefulWork.unit}. The reduction is a ratio of efficiencies and `
            + 'nothing else: no behaviour change, no fabric improvement and no generation mix is in it.',
        not_computed: NOT_COMPUTED.emissions,
        not_a_forecast: NOT_A_FORECAST
    };
}