In this section
- Hdd transform · globalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/hdd.mjs lines 1–384
- Land transform · globalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/land.mjs lines 1–298
Hdd
A JavaScript module in the world folder of GlobalGrid2050 that works with cables, 33kV and 132kV, using BS 7870-4.
Set aside from the main view: 96% of its lines are the same as solar-design-studio/202609271552-site-world/world/hdd.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Hdd; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.962 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271552-site-world/world/hdd.mjs:1-384 a3ea813b30351edaf28ace15cc88aacbbae0179d
- sha256 0723b05ef37541f2fa1b6222a668769af938d67ffea09810622c11f049f9c8cc
- target sha256 9cc65f3bd1a36bff6238adffaef83f27990af57b51f0e0ace76dfcd9587bfa53
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformglobalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/hdd.mjs · lines 1–384 of 384 · version 2026-09-27 00:56 · Not reached from any entry point (candidate for review) · pattern cableBendMultiple (shared by 2 files)
- What it does
- It calculates cables, 33kV and 132kV. Defines 16 functions or classes, including cableBendMultiple, ductForCable, clamp, lineOf, side.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 33kV, 132kV.
- Inputs & outputs
- Voltage levels named: 132kV, 33kV.
- Downstream impact
- Used directly by 1 file: Design Earthworks (globalgrid2050).
- What it achieves
- It compares crossing (`compareCrossing`) and is built from the cable bend multiple helper (`cableBendMultiple`) and the duct for cable helper (`ductForCable`). A horizontal directional drill (HDD) crossing under a road, watercourse or hedge. Its code works with 33 kV and 132 kV.
- Why it matters
- Imported by Design Earthworks.
- Application
- globalgrid2050 · solar-design-studio/202609270056-site-world-v3/world · JavaScript module
- Uses
- Trench (import)
- Used by
- imported by Design Earthworks (import), mentioned in Standalone (comment link)
- Produces
- ANGLE_TYPICAL, ANGLE_LIMIT, RADIUS_MULTIPLE, CABLE_BEND, cableBendMultiple, DUCT_SIZES_MM, DUCT_MIN_MM, ductForCable, COVER_ASSUMED, OBSTACLE_DEPTH_ASSUMED, REAM_FACTOR, PIT_ASSUMED
- Defines here
- cableBendMultiple, ductForCable, clamp, lineOf, side, designBore, zAt, pointAt, inRange, pitOf, noLayout, rootOut, h, cablePull, run, compareCrossing
- 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-design-studio/202609270056-site-world-v3/world/hdd.mjs:1-384 · blob 8a6d55dd4c5c344cd2d281d6296e7c94cfad8c8d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// hdd.mjs: a horizontal directional drill (HDD) crossing under a road, watercourse or hedge. Pure: no DOM.
// Local east (x), north (y), up (z), metres. Output lines are gl.LINES pairs: x,y,z, x,y,z per segment.
//
// The plan line is straight, from `from` to `to`. Chainage s is horizontal distance along it from `from`.
// The vertical profile follows the plan line: entry tangent - arc - level straight - arc - exit tangent.
// The level straight sits deep enough for the required cover under the obstacle, and runs at least
// `margin` beyond each side of it before the bore starts to rise.
//
// designBore(opts) -> { entry, exit, depth, segments, boreLength, zAt, pointAt, samples, checks, pits, lines }
// compareCrossing(opts) -> open-cut trench against HDD for the same crossing (lengths, spoil, flags)
//
// EVERY DEFAULT BELOW IS A TYPICAL OR ASSUMED VALUE, NOT A DESIGN. Ground conditions, the asset owner's
// cover rule and the drilling contractor's rig set the real figures.
import { createTrench } from './trench.mjs';
const RAD = Math.PI / 180, G = 9.81;
// Entry and exit angles. ASTM F1962-20 section 7.4.2: entry 8 to 20 degrees, preferably 12 to 15; section 7.4.3:
// exit angles "should be relatively shallow, preferably less than 10°". Outside ANGLE_TYPICAL a warning is given;
// outside ANGLE_LIMIT the check fails (20 degrees exit kept as the hard limit, assumed). See also PRCI "Installation
// of Pipelines by Horizontal Directional Drilling: an Engineering Design Guide" (PR-227-9424, 1995; 2015 update PR-277-144507).
export const ANGLE_TYPICAL = { entry: [8, 20], exit: [5, 10] };
export const ANGLE_LIMIT = { entry: [8, 20], exit: [5, 20] };
// Minimum radius, as multiples of outside diameter:
// - drill pipe (rod): (Rrod)min = 1200 Drod, ASTM F1962-20 section 7.2, Eq. 1 ("100 feet per inch");
// - steel product pipe: 1200 x nominal diameter (PRCI design guide above; typical);
// - polyethylene pipe or duct: ASTM F1962-20 section 8.2.5, Note 7, "approximately 40 or 50 to 1 during pull-back";
// 40, the lower end, is used here;
// - cable in the duct: 20 x cable OD, the verified 33 kV single-core installation rule in data/cables.json (S2/S3).
export const RADIUS_MULTIPLE = { rod: 1200, steel: 1200, pe: 40, cable: 20 };
// Cable installation bend radius by voltage and install method, as multiples of the cable OD (data/cables.json rules):
// - up to 33 kV single core: 20 x OD during installation. Manufacturer UK installation note (2022), BS 7870-4.10/4.11
// dynamic 20 x OD; Northern Powergrid NSP/002 v5.0 (Oct 2021) Table 8 gives about 20 x OD for 33 kV 300-630 mm2.
// - 66 and 132 kV single core with a metallic sheath: NSP/002 v5.0 Table 8, 35 x OD pulled into ducts, 30 x OD laid direct.
// A drilled crossing always pulls into ducts.
export const CABLE_BEND = Object.freeze({
mv: { maxKv: 33, duct: 20, direct: 20, source: 'up to 33 kV: 20 x OD during installation (manufacturer UK note 2022; NSP/002 v5.0 Table 8)' },
hv: { maxKv: 132, duct: 35, direct: 30, source: '66-132 kV: 35 x OD pulled into ducts, 30 x OD laid direct (NSP/002 v5.0 Table 8)' },
});
export function cableBendMultiple(voltageKv = 33, method = 'duct') {
const band = Number(voltageKv) > CABLE_BEND.mv.maxKv ? CABLE_BEND.hv : CABLE_BEND.mv;
return { multiple: method === 'direct' ? band.direct : band.duct, method, source: band.source };
}
// One duct per single-core cable. Size: the smallest stock PE duct whose bore (SDR 11: OD x 9/11) is at least
// 1.5 x the cable OD (ASSUMED pulling clearance), and not below 160 mm, the duct Northern Powergrid NSP/002 Table 5
// gives for 33 kV and 132 kV. The drilling contractor and network operator set the real size.
export const DUCT_SIZES_MM = Object.freeze([110, 125, 160, 180, 200, 225, 250, 280, 315, 355]);
export const DUCT_MIN_MM = 160, DUCT_BORE_RATIO = 1.5, SDR = 11;
export function ductForCable({ odMm, voltageKv = 33, cores = 3, circuits = 1 } = {}) {
const need = DUCT_BORE_RATIO * (Number(odMm) || CABLE_ASSUMED.odMm);
const size = DUCT_SIZES_MM.find(d => d >= DUCT_MIN_MM && d * (1 - 2 / SDR) >= need) ?? DUCT_SIZES_MM[DUCT_SIZES_MM.length - 1];
return { ducts: cores * circuits, odMm: size, voltageKv, basis: `one duct per single-core cable (${cores} x ${circuits} circuit); `
+ `${size} mm SDR ${SDR} PE: bore at least ${DUCT_BORE_RATIO} x cable OD and at least ${DUCT_MIN_MM} mm (assumed; NSP/002 Table 5)` };
}
// Required cover below the bottom of the obstacle to the crown of the product. ASSUMED placeholders: the
// highway authority, the flood risk regulator or the tree adviser sets the real figure for each crossing.
// Watercourse cover allows for bed scour; hedge cover clears the main root zone.
export const COVER_ASSUMED = { road: 1.5, watercourse: 2.0, hedge: 1.5 };
// ASSUMED depth of the obstacle bottom below the ground either side (carriageway build-up, channel bed).
export const OBSTACLE_DEPTH_ASSUMED = { road: 0.6, watercourse: 1.5, hedge: 0 };
// Reamed hole diameter: "typically 50 % greater than the outer diameter", ASTM F1962-20 section 9.3.
export const REAM_FACTOR = 1.5;
// ASSUMED pit size, metres: a small launch / reception pit to hold returned drilling fluid.
export const PIT_ASSUMED = { length: 3, width: 2, depth: 1.2 };
// ASSUMED least ground over the product crown anywhere between the pits (no source): the bore must not daylight.
export const CLEARANCE_ASSUMED = 0.1;
// Step for the cover and clearance checks, metres: much finer than the 1 m LiDAR cells, so a low point between
// samples cannot hide more than a millimetre or so of cover.
const CHECK_STEP = 0.05;
// Cable pull-in, ASSUMED, no public source: duct friction 0.35, and the pulling-eye limit on the conductors of
// 50 N/mm2 for copper and 30 N/mm2 for aluminium. The cable maker's figure for each cable governs over these.
// Per single-core cable, pulled alone into its own duct.
export const CABLE_ASSUMED = { massKgPerM: 2, odMm: 51.5, conductorMm2: 300, material: 'al', friction: 0.35, voltageKv: 33 };
export const PULL_STRESS = { cu: 50, al: 30 }; // N/mm2
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
function lineOf(from, to) {
const L = Math.hypot(to[0] - from[0], to[1] - from[1]);
if (!(L > 0)) throw Error('hdd: the plan line needs two distinct points');
const d = [(to[0] - from[0]) / L, (to[1] - from[1]) / L];
return { L, d, xy: (s) => [from[0] + d[0] * s, from[1] + d[1] * s] };
}
// Horizontal run and slant tangent length to go from ground height zg down to level zb at angle a, radius R.
function side(zg, zb, a, R) {
const drop = zg - zb, arcDrop = R * (1 - Math.cos(a));
const tangent = (drop - arcDrop) / Math.sin(a);
return { tangent, run: tangent * Math.cos(a) + R * Math.sin(a), arcRun: R * Math.sin(a) };
}
/**
* designBore({ from, to, groundAt, obstacle, entryAngleDeg, exitAngleDeg, radius, rodOdMm, product, fit, cable })
* obstacle: { kind: 'road'|'watercourse'|'hedge', from, to (chainages), depth?, cover?, margin? }
* product: { material: 'pe'|'steel', odMm }. radius defaults to the largest required minimum radius.
* fit: true moves entry and exit along the line to the shortest bore that clears the obstacle;
* otherwise entry is at `from` and exit at `to`.
*/
export function designBore(opts) {
const { from, to, groundAt, obstacle } = opts;
if (typeof groundAt !== 'function') throw Error('hdd: groundAt(x, y) is required');
if (!obstacle || !(obstacle.to > obstacle.from)) throw Error('hdd: obstacle needs from < to chainages');
const kind = obstacle.kind || 'road';
if (!(kind in COVER_ASSUMED)) throw Error(`hdd: unknown obstacle kind ${kind}`);
const line = lineOf(from, to), g = (s) => groundAt(...line.xy(s));
const aE = (opts.entryAngleDeg ?? 12) * RAD, aX = (opts.exitAngleDeg ?? 10) * RAD;
if (!(aE > 0 && aE < Math.PI / 2 && aX > 0 && aX < Math.PI / 2)) throw Error('hdd: angles must be between 0 and 90 degrees');
const product = { material: 'pe', odMm: 125, ...(opts.product || {}) };
const rodOdMm = opts.rodOdMm ?? 60.3; // ASSUMED: 2 3/8 inch rod of a small to mid-size rig
const od = product.odMm / 1000;
const minR = {
rod: RADIUS_MULTIPLE.rod * rodOdMm / 1000,
product: (RADIUS_MULTIPLE[product.material] ?? RADIUS_MULTIPLE.pe) * od,
};
const required = Math.max(minR.rod, minR.product);
const R = opts.radius ?? required;
const oDepth = obstacle.depth ?? OBSTACLE_DEPTH_ASSUMED[kind];
const cover = obstacle.cover ?? COVER_ASSUMED[kind];
const margin = obstacle.margin ?? 2; // ASSUMED level run beyond each side
// Level of the straight: the lowest obstacle bottom, less cover, less half the product (cover is to its crown).
let bottom = Infinity;
const nObs = Math.max(4, Math.ceil((obstacle.to - obstacle.from) / CHECK_STEP));
for (let i = 0; i <= nObs; i++) bottom = Math.min(bottom, g(obstacle.from + (obstacle.to - obstacle.from) * i / nObs) - oDepth);
const zb = Math.min(bottom - cover - od / 2, opts.level ?? Infinity);
const base = { kind, depth: { level: zb, obstacleBottom: bottom, cover, obstacleDepth: oDepth, margin }, radius: R, product,
reamedDiameter: REAM_FACTOR * od };
if (!Number.isFinite(zb)) return noLayout(base, 'no ground under the obstacle (off the loaded terrain)');
// Entry and exit chainages: given, or fitted so the straight just spans the obstacle plus margins. Each side is a
// root of f(s) = s +- run(ground(s)) - target, found by scanning out from the obstacle and bisecting, so the root
// taken is the one nearest the obstacle. No root on the drawn line means no valid layout, and it says so.
let sE = 0, sX = line.L, fit = null;
if (opts.fit) {
const a = rootOut((s) => s + side(g(s), zb, aE, R).run - (obstacle.from - margin), obstacle.from - margin, 0,
(s) => side(g(s), zb, aE, R).tangent >= 0);
const b = rootOut((s) => s - side(g(s), zb, aX, R).run - (obstacle.to + margin), obstacle.to + margin, line.L,
(s) => side(g(s), zb, aX, R).tangent >= 0);
if (a.s === null || b.s === null) {
return noLayout(base, `no valid layout on the drawn line: the ${a.s === null ? 'entry' : 'exit'} pit would fall `
+ `${a.nan || b.nan ? 'off the loaded ground' : 'beyond the end of the line'}; draw a longer line or steepen the angles`);
}
sE = a.s; sX = b.s;
fit = { converged: true, residual: Math.max(Math.abs(a.residual), Math.abs(b.residual)) };
}
const zE = g(sE), zX = g(sX), half = PIT_ASSUMED.length / 2;
const pitGround = [sE - half, sE + half, sX - half, sX + half].every((t) => Number.isFinite(g(t)));
if (!Number.isFinite(zE) || !Number.isFinite(zX) || !pitGround) return noLayout(base, 'a pit falls off the loaded ground');
const e = side(zE, zb, aE, R), x = side(zX, zb, aX, R);
// Breakpoints along the chainage.
const s1 = sE + Math.max(0, e.tangent) * Math.cos(aE), s2 = s1 + e.arcRun;
const s4 = sX - Math.max(0, x.tangent) * Math.cos(aX), s3 = s4 - x.arcRun;
const c1 = { s: s2, z: zb + R }, c2 = { s: s3, z: zb + R };
const zAt = (s) => {
const c = clamp(s, sE, sX);
if (c <= s1) return zE - (c - sE) * Math.tan(aE);
if (c <= s2) return c1.z - Math.sqrt(Math.max(0, R * R - (c - c1.s) ** 2));
if (c <= s3) return zb;
if (c <= s4) return c2.z - Math.sqrt(Math.max(0, R * R - (c - c2.s) ** 2));
return zX - (sX - c) * Math.tan(aX);
};
const pointAt = (s) => [...line.xy(s), zAt(s)];
const straight = s3 - s2;
const segments = [
{ kind: 'tangent', s0: sE, s1, length: Math.max(0, e.tangent) },
{ kind: 'arc', s0: s1, s1: s2, length: R * aE },
{ kind: 'straight', s0: s2, s1: s3, length: Math.max(0, straight) },
{ kind: 'arc', s0: s3, s1: s4, length: R * aX },
{ kind: 'tangent', s0: s4, s1: sX, length: Math.max(0, x.tangent) },
];
// When the profile does not fit, the tangents are clamped and the drawn line is not a bore: no length is given.
let boreLength = segments.reduce((t, sg) => t + sg.length, 0);
// Samples along the bore: every 0.5 m and every breakpoint.
const marks = new Set([sE, s1, s2, s3, s4, sX]);
const n = Math.max(2, Math.ceil((sX - sE) / 0.5));
for (let i = 0; i <= n; i++) marks.add(sE + (sX - sE) * i / n);
const ss = [...marks].filter((s) => s >= sE && s <= sX).sort((a, b) => a - b);
const samples = ss.map((s) => ({ s, z: zAt(s), ground: g(s) }));
// ---- checks ---------------------------------------------------------------------------------------------------
const checks = [];
const fits = e.tangent >= -1e-9 && x.tangent >= -1e-9 && straight >= -1e-9;
const spans = s2 <= obstacle.from - margin + 1e-3 && s3 >= obstacle.to + margin - 1e-3; // 1 mm
checks.push({ id: 'profile', ok: fits && spans, value: straight, unit: 'm',
note: !fits ? 'entry and exit too close, too shallow for this angle and radius, or the obstacle too deep: move the pits or change the angles'
: !spans ? `the level straight does not span the obstacle plus ${margin} m each side: move the pits apart or steepen the angles`
: 'tangent-arc-straight-arc-tangent fits, and the level straight spans the obstacle plus margins' });
if (!(fits && spans)) boreLength = null;
let minCover = Infinity, at = null;
const nCov = Math.max(4, Math.ceil((obstacle.to - obstacle.from) / CHECK_STEP));
for (let i = 0; i <= nCov; i++) {
const s = obstacle.from + (obstacle.to - obstacle.from) * i / nCov;
const c = g(s) - oDepth - (zAt(s) + od / 2);
if (c < minCover) { minCover = c; at = pointAt(s); }
}
checks.push({ id: 'cover', ok: minCover >= cover - 1e-6, value: minCover, required: cover, unit: 'm', at,
note: `cover from the obstacle bottom (${oDepth} m below ground, ${obstacle.depth == null ? 'assumed' : 'given'}) `
+ `to the product crown; required ${cover} m is ${obstacle.cover == null ? 'an assumed placeholder' : 'given'}` });
checks.push({ id: 'radius', ok: R >= required - 1e-6, value: R, required, unit: 'm', minR,
note: `rod ${minR.rod.toFixed(1)} m (${RADIUS_MULTIPLE.rod} x ${rodOdMm} mm), product ${minR.product.toFixed(1)} m `
+ `(${RADIUS_MULTIPLE[product.material] ?? RADIUS_MULTIPLE.pe} x ${product.odMm} mm): typical rules, not a rig or pipe maker figure` });
// Clearance: the product crown stays at least CLEARANCE_ASSUMED under the ground everywhere between the pits.
let minClear = Infinity, clearAt = null;
const k0 = Math.min(sE + half, sX), k1 = Math.max(sX - half, k0), nCl = Math.max(1, Math.ceil((k1 - k0) / CHECK_STEP));
for (let i = 0; i <= nCl; i++) {
const s = k0 + (k1 - k0) * i / nCl, c = g(s) - (zAt(s) + od / 2);
if (c < minClear) { minClear = c; clearAt = pointAt(s); }
}
checks.push({ id: 'clearance', ok: minClear >= CLEARANCE_ASSUMED - 1e-9, value: minClear, required: CLEARANCE_ASSUMED, unit: 'm',
at: clearAt, note: minClear < 0 ? `the bore comes out of the ground (${(-minClear).toFixed(2)} m above it) between the pits`
: `least ground over the product crown between the pits; ${CLEARANCE_ASSUMED} m required (assumed, no source)` });
const inRange = (a, [lo, hi]) => a >= lo - 1e-9 && a <= hi + 1e-9;
const eDeg = aE / RAD, xDeg = aX / RAD;
const usual = inRange(eDeg, ANGLE_TYPICAL.entry) && inRange(xDeg, ANGLE_TYPICAL.exit);
checks.push({ id: 'angles', ok: inRange(eDeg, ANGLE_LIMIT.entry) && inRange(xDeg, ANGLE_LIMIT.exit), warn: !usual,
value: [eDeg, xDeg], required: [ANGLE_LIMIT.entry, ANGLE_LIMIT.exit], preferred: [ANGLE_TYPICAL.entry, ANGLE_TYPICAL.exit],
unit: 'degrees', note: usual ? 'entry 8-20 degrees (ASTM F1962-20 7.4.2), exit 10 degrees or less (7.4.3)'
: 'outside the preferred range: ASTM F1962-20 7.4.3 prefers an exit under 10 degrees; entry 8-20 (7.4.2)' });
const pull = cablePull(samples, { ...CABLE_ASSUMED, ...(opts.cable || {}) });
checks.push({ id: 'tension', ok: pull.best <= pull.allowable, value: pull.best, required: pull.allowable, unit: 'N', pull,
note: 'cable pull-in estimate from ASSUMED friction, cable mass and conductor stress limit; '
+ 'the duct pullback itself needs its own calculation (for example ASTM F1962)' });
const bend = cableBendMultiple(opts.cable?.voltageKv ?? CABLE_ASSUMED.voltageKv, 'duct');
const cableOd = opts.cable?.odMm ?? CABLE_ASSUMED.odMm, cableR = bend.multiple * cableOd / 1000;
checks.push({ id: 'cable-bend', ok: R >= cableR, value: R, required: cableR, unit: 'm', multiple: bend.multiple,
note: `bore radius against the cable installation bend radius (${bend.multiple} x ${cableOd} mm OD, pulled into ducts; ${bend.source})` });
// ---- pits and drawing ---------------------------------------------------------------------------------------------
const pitOf = (s, name) => {
const trench = createTrench({ path: [line.xy(s - half), line.xy(s + half)], width: PIT_ASSUMED.width,
depth: PIT_ASSUMED.depth, groundAt });
return { name, at: pointAt(s), trench };
};
const pits = [pitOf(sE, 'entry'), pitOf(sX, 'exit')];
const seg = [];
for (let i = 1; i < samples.length; i++) {
const a = line.xy(samples[i - 1].s), b = line.xy(samples[i].s);
seg.push(a[0], a[1], samples[i - 1].z, b[0], b[1], samples[i].z);
}
for (const p of pits) for (const v of p.trench.wallLines(groundAt)) seg.push(v);
return {
...base, layout: true, fit, entry: { s: sE, point: pointAt(sE), angleDeg: eDeg }, exit: { s: sX, point: pointAt(sX), angleDeg: xDeg },
segments, boreLength, planLength: sX - sE,
zAt, pointAt, samples, checks, ok: checks.every((c) => c.ok), pits, lines: new Float32Array(seg),
};
}
// A crossing with no valid layout: one failing check that says why, nothing to draw and no length.
function noLayout(base, note) {
return { ...base, layout: false, fit: { converged: false, residual: null }, entry: null, exit: null, segments: [],
boreLength: null, planLength: null, samples: [], checks: [{ id: 'layout', ok: false, note }], ok: false, pits: [],
lines: new Float32Array(0) };
}
// Scans from `start` towards `end` in 0.1 m steps for the first sign change of f, then bisects to 1e-9 m.
// f is positive on the obstacle side of the root. A root where valid(s) is false (the ground there is too low for the
// arc, so the tangent would be negative) is passed over. Returns { s, residual }, or { s: null, nan } with no root.
function rootOut(f, start, end, valid = () => true) {
const dir = end < start ? -1 : 1, n = Math.max(1, Math.ceil(Math.abs(end - start) / 0.1));
const h = (s) => dir * -f(s); // entry side: f > 0 at the obstacle; exit side: f < 0 at the obstacle
let a = start, ha = h(a);
if (!Number.isFinite(ha)) return { s: null, nan: true };
if (ha <= 0 && valid(a)) return { s: a, residual: f(a) };
for (let i = 1; i <= n; i++) {
const b = i === n ? end : start + dir * 0.1 * i, hb = h(b);
if (!Number.isFinite(hb)) return { s: null, nan: true };
if (hb <= 0 && ha > 0) {
let lo = a, hi = b;
for (let k = 0; k < 80 && Math.abs(hi - lo) > 1e-9; k++) { const m = (lo + hi) / 2; if (h(m) > 0) lo = m; else hi = m; }
if (valid(hi)) return { s: hi, residual: f(hi) };
}
a = b; ha = hb;
}
return { s: null, nan: false };
}
/**
* cablePull(samples, cable) pulls the cable through the bore polyline both ways. For each step:
* T <- T e^(mu |dtheta|) + w ds (mu cos theta + sin theta), theta the rise in the direction of pull.
* The capstan term is the sidewall friction round the vertical bends. Returns newtons.
*/
export function cablePull(samples, cable = CABLE_ASSUMED) {
const c = { ...CABLE_ASSUMED, ...cable }, mu = c.friction, w = c.massKgPerM * G;
const run = (pts) => {
let T = 0, prev = null;
for (let i = 1; i < pts.length; i++) {
const ds = Math.hypot(pts[i].s - pts[i - 1].s, pts[i].z - pts[i - 1].z);
if (!(ds > 0)) continue;
const th = Math.atan2(pts[i].z - pts[i - 1].z, Math.abs(pts[i].s - pts[i - 1].s));
if (prev !== null) T *= Math.exp(mu * Math.abs(th - prev));
T = Math.max(0, T + w * ds * (mu * Math.cos(th) + Math.sin(th)));
prev = th;
}
return T;
};
const forward = run(samples), backward = run([...samples].reverse());
const allowable = (PULL_STRESS[c.material] ?? PULL_STRESS.al) * c.conductorMm2;
return { forward, backward, best: Math.min(forward, backward),
feedFrom: forward <= backward ? 'entry' : 'exit', allowable, assumed: c };
}
// Disruption flags by obstacle, for each method. Plain statements, advisory only.
const FLAGS = {
road: {
open: ['carriageway closed or narrowed under traffic management', 'road opening notice and reinstatement to the highway specification'],
hdd: ['pits and rig sit off the carriageway', 'ground heave or settlement under the road to be monitored'],
},
watercourse: {
open: ['works in the channel: damming and over-pumping', 'permit for works in or near the watercourse likely',
'silt release and bed and bank reinstatement'],
hdd: ['drilling fluid breakout into the watercourse is the main risk: fluid pressure plan needed', 'permit may still be needed'],
},
hedge: {
open: ['hedge section removed and replanted; hedgerow protection rules may apply', 'nesting season limits the time of year'],
hdd: ['hedge and root zone left intact'],
},
};
const HDD_COMMON = ['specialist rig, fluid handling and working areas at both pits', 'ground investigation needed: rock, gravel or voids can stop a bore'];
/**
* compareCrossing({ from, to, groundAt, obstacle, trench?: { width, depth }, ...designBore options })
* Open cut: a trench over the same plan length as the bore, dug to the normal depth on the approaches and
* to obstacle depth + cover + product OD across the obstacle (plus margins). Spoil from trench.mjs.
* HDD: cuttings from the reamed hole plus the two pits. Returns both and an advisory preference with reasons.
*/
export function compareCrossing(opts) {
const bore = designBore({ fit: true, ...opts });
const advisory = 'a screening comparison on assumed values; not a method statement or a cost estimate';
if (!bore.layout || bore.boreLength === null) {
return { kind: bore.kind, openCut: null, hdd: { boreLength: null, bore, flags: [] }, preferred: 'open-cut', advisory,
reasons: [`HDD has no valid layout: ${bore.checks.find((c) => !c.ok).note}`] };
}
const { groundAt, obstacle } = opts;
const line = lineOf(opts.from, opts.to);
const width = opts.trench?.width ?? 0.6, normal = opts.trench?.depth ?? 1.2; // ASSUMED cable trench
const od = bore.product.odMm / 1000;
const deep = bore.depth.obstacleDepth + bore.depth.cover + od;
const a = obstacle.from - bore.depth.margin, b = obstacle.to + bore.depth.margin;
const parts = [[bore.entry.s, a, normal], [a, b, Math.max(normal, deep)], [b, bore.exit.s, normal]]
.filter(([p, q]) => q - p > 1e-6)
.map(([p, q, depth]) => createTrench({ path: [line.xy(p), line.xy(q)], width, depth, groundAt }));
const openSpoil = parts.reduce((t, tr) => t + tr.spoilVolumeOn(groundAt), 0);
const openLength = parts.reduce((t, tr) => t + tr.length2d, 0);
const cuttings = Math.PI * (bore.reamedDiameter / 2) ** 2 * bore.boreLength;
const pitSpoil = bore.pits.reduce((t, p) => t + p.trench.spoilVolumeOn(groundAt), 0);
const kind = bore.kind, flags = FLAGS[kind];
const reasons = [];
let preferred;
if (!bore.ok) {
preferred = 'open-cut';
reasons.push(`HDD fails: ${bore.checks.filter((c) => !c.ok).map((c) => c.id).join(', ')}`);
} else if (kind === 'hedge' && openLength < 30) {
preferred = 'open-cut';
reasons.push('short hedge crossing: open cut is simpler if the hedge may be cut and replanted');
} else {
preferred = 'hdd';
reasons.push(kind === 'watercourse' ? 'avoids works in the channel' : kind === 'road' ? 'keeps the road open' : 'keeps the hedge intact');
reasons.push(`spoil ${Math.round(cuttings + pitSpoil)} m3 against ${Math.round(openSpoil)} m3 open cut`);
}
return {
kind,
openCut: { length: openLength, spoilM3: openSpoil, trenches: parts, flags: flags.open, deepDepth: deep },
hdd: { boreLength: bore.boreLength, planLength: bore.planLength, spoilM3: cuttings + pitSpoil, cuttingsM3: cuttings,
pitSpoilM3: pitSpoil, flags: [...flags.hdd, ...HDD_COMMON], bore },
preferred, reasons, advisory,
};
}Land
A JavaScript module in the world folder of GlobalGrid2050 that works with solar.
transformglobalgrid2050 / solar-design-studio/202609270056-site-world-v3/world/land.mjs · lines 1–298 of 298 · version 2026-09-27 00:56 · Not reached from any entry point (candidate for review) · pattern intervalsAt (shared by 2 files)
- What it does
- It calculates solar. Defines 19 functions or classes, including isGrade, ringArea, prepare, intervalsAt, intersect.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- What it achieves
- It is built from the is grade helper (`isGrade`), the ring area helper (`ringArea`) and the prepare step (`prepare`). The land-use lens for farmers and planners.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · solar-design-studio/202609270056-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- STEP_M, BMV, UNSPLIT_GRADE_3, isGrade, NOT_GRADED_LABEL, SHEEP, ringArea, prepare, intervalsAt, intersect, subtract, span
- Defines here
- isGrade, ringArea, prepare, intervalsAt, intersect, subtract, span, pointInRings, areaByGrade, planWidth, panelSplit, grazingNote, ewes, cellRing, cropMix, add, landReport, ha, reportLines
- 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-design-studio/202609270056-site-world-v3/world/land.mjs:1-298 · blob 718366918fc8b4d369d8a464608f4a84a932b390 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// land.mjs: the land-use lens for farmers and planners. A cartridge: pure functions, no imports, no DOM.
//
// Input: land.json (world.land.v1, cut by tools/features/cut_land.py) and drawn field polygons or the site
// boundary, in British National Grid metres. Each field is { id?, rings: [[[e, n], ...], ...] }; rings are read
// by the even-odd rule, so holes need no particular orientation.
//
// Output, per field and in total:
// - area by Agricultural Land Classification grade. Post-1988 detailed surveys take precedence where they
// give a grade; the provisional map (about 1:250,000, grade 3 not split) fills the rest.
// - area under panels against area kept open between rows, from the row pitch and the table's plan width.
// - a sheep-grazing capacity note with cited, typical stocking rates, labelled as assumed.
// - the 2024 crop mix from the Crop Map of England, when land.json carries it: each hexagon is clipped to the
// field and to the hexagons before it, so the crop areas never add up to more than the field.
// - land a map marks but does not grade ('Other', non-agricultural, urban) is reported apart, never as a grade.
//
// Areas are integrated by horizontal scanlines: on each line the exact intervals inside each polygon are found,
// intersected, and summed. The error is confined to strips that hold a vertex (step 0.25 m by default).
export const STEP_M = 0.25;
export const BMV = Object.freeze(['Grade 1', 'Grade 2', 'Grade 3a']); // best and most versatile land
export const UNSPLIT_GRADE_3 = 'Grade 3'; // provisional: may be 3a or 3b
const NOT_A_GRADE_DEFAULT = ['', ' ', 'Not Surveyed'];
// An ALC grade proper; anything else a map carries ('Other', 'Non Agricultural', 'Urban') is not graded land.
export const isGrade = g => /^Grade [1-5][ab]?$/.test(String(g));
export const NOT_GRADED_LABEL = 'Not graded / non-agricultural';
// Typical stocking rates. ASSUMED for any given site: the land, sward, breed and season decide the real figure.
export const SHEEP = Object.freeze({
solar: Object.freeze({
low: 4, high: 8, newPasture: Object.freeze([2, 3]),
basis: 'sheep per hectare of solar farm, grazing between about March and November in the south-west and ' +
'May to October in the north-east of England',
source: 'BRE National Solar Centre (2014), Agricultural Good Practice Guidance for Solar Farms, p. 4: ' +
'"Between 4 and 8 sheep/hectare may be achievable (or 2-3 sheep/ha on newly-established pasture), ' +
'similar to stocking rates on conventional grassland"',
url: 'https://files.bregroup.com/solar/NSC_-Guid_Agricultural-good-practice-for-SFs_0914.pdf',
}),
grassland: Object.freeze({
lowlandEweLU: 0.11, lowLU: Object.freeze([1, 1.5]), highLU: Object.freeze([2, 2.5]),
source: 'AHDB Beef & Lamb, Planning grazing strategies for Better Returns (BRM 8), Table 6 and Figure 3: ' +
'lowland ewe 0.11 livestock units (from Defra 2010); low stocking 1-1.5 LU/ha, high 2-2.5 LU/ha in season',
url: 'https://media.ahdb.org.uk/media/Default/Imported%20Publication%20Docs/Planning-grazing-strategies-for-better-returns.pdf',
}),
leadingEdgeM: Object.freeze([0.8, 0.9]), // BRE (2014) p. 4: lower edges of modules "typically about 800-900mm high"
});
// ---------- geometry ----------
export function ringArea(ring) {
let s = 0;
for (let i = 0; i < ring.length; i++) {
const [x0, y0] = ring[i], [x1, y1] = ring[(i + 1) % ring.length];
s += x0 * y1 - x1 * y0;
}
return s / 2;
}
// Edges of a polygon (rings, even-odd), with its bounding box, ready for scanlines.
export function prepare(rings) {
const edges = [];
let y0 = Infinity, y1 = -Infinity, x0 = Infinity, x1 = -Infinity;
for (const ring of rings || []) {
for (let i = 0; i < ring.length; i++) {
const a = ring[i], b = ring[(i + 1) % ring.length];
if (a[1] !== b[1]) edges.push(a[1] < b[1] ? [a[0], a[1], b[0], b[1]] : [b[0], b[1], a[0], a[1]]);
y0 = Math.min(y0, a[1]); y1 = Math.max(y1, a[1]); x0 = Math.min(x0, a[0]); x1 = Math.max(x1, a[0]);
}
}
return { edges, y0, y1, x0, x1 };
}
// Sorted, disjoint intervals [[xa, xb], ...] where the line y = const lies inside the polygon (even-odd).
export function intervalsAt(poly, y) {
if (y < poly.y0 || y >= poly.y1) return [];
const xs = [];
for (const [ax, ay, bx, by] of poly.edges) if (ay <= y && y < by) xs.push(ax + (y - ay) * (bx - ax) / (by - ay));
xs.sort((p, q) => p - q);
const out = [];
for (let i = 0; i + 1 < xs.length; i += 2) if (xs[i + 1] > xs[i]) out.push([xs[i], xs[i + 1]]);
return out;
}
export function intersect(A, B) {
const out = [];
for (let i = 0, j = 0; i < A.length && j < B.length;) {
const lo = Math.max(A[i][0], B[j][0]), hi = Math.min(A[i][1], B[j][1]);
if (hi > lo) out.push([lo, hi]);
if (A[i][1] < B[j][1]) i++; else j++;
}
return out;
}
export function subtract(A, B) {
const out = [];
for (const [a0, a1] of A) {
let s = a0;
for (const [b0, b1] of B) {
if (b1 <= s || b0 >= a1) continue;
if (b0 > s) out.push([s, b0]);
s = Math.max(s, b1);
if (s >= a1) break;
}
if (s < a1) out.push([s, a1]);
}
return out;
}
export const span = I => I.reduce((s, [a, b]) => s + (b - a), 0);
export function pointInRings(rings, x, y) {
let inside = false;
for (const ring of rings) {
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const [xi, yi] = ring[i], [xj, yj] = ring[j];
if ((yi > y) !== (yj > y) && x < xi + (y - yi) * (xj - xi) / (yj - yi)) inside = !inside;
}
}
return inside;
}
// ---------- ALC ----------
// Area (m2) of one field by grade. Returns { grades: {grade: m2}, source: {grade: 'post1988'|'provisional'},
// notGraded: {label: m2}, notGradedM2, fieldM2, unclassifiedM2 } where unclassified is field area outside every
// land.json polygon (e.g. off the box) and notGraded is land a map covers with a label that is not a grade.
export function areaByGrade(fieldRings, land, { step = STEP_M } = {}) {
const field = prepare(fieldRings);
const notGrade = new Set(land.not_a_grade || NOT_A_GRADE_DEFAULT);
const layers = [
['post1988', (land.alc?.post1988 || []).filter(p => !notGrade.has(p.grade))],
['provisional', land.alc?.provisional || []],
].map(([kind, items]) => [kind, items.map(p => ({ grade: p.grade, poly: prepare(p.rings) }))
.filter(p => p.poly.y1 > field.y0 && p.poly.y0 < field.y1 && p.poly.x1 > field.x0 && p.poly.x0 < field.x1)]);
const grades = {}, source = {}, notGraded = {};
let fieldLen = 0, restLen = 0;
if (!(field.y1 > field.y0)) return { grades, source, notGraded, notGradedM2: 0, fieldM2: 0, unclassifiedM2: 0 };
const rows = Math.max(1, Math.ceil((field.y1 - field.y0) / step)), dy = (field.y1 - field.y0) / rows;
for (let k = 0; k < rows; k++) {
const y = field.y0 + (k + 0.5) * dy;
let rest = intervalsAt(field, y);
if (!rest.length) continue;
fieldLen += span(rest);
for (const [kind, items] of layers) {
for (const p of items) {
if (!rest.length) break;
const I = intervalsAt(p.poly, y);
if (!I.length) continue;
const got = span(intersect(rest, I));
if (got > 0 && !isGrade(p.grade)) notGraded[p.grade] = (notGraded[p.grade] || 0) + got * dy;
else if (got > 0) {
grades[p.grade] = (grades[p.grade] || 0) + got * dy;
if (!source[p.grade] || source[p.grade] === kind) source[p.grade] = kind; else source[p.grade] = 'both';
}
rest = subtract(rest, I);
}
}
restLen += span(rest);
}
const notGradedM2 = Object.values(notGraded).reduce((a, b) => a + b, 0);
return { grades, source, notGraded, notGradedM2, fieldM2: fieldLen * dy, unclassifiedM2: restLen * dy };
}
// ---------- panels and grazing ----------
// Plan (horizontal) width of a table from its sloping length across the row and its tilt.
export const planWidth = (slopeLengthM, tiltDeg) => slopeLengthM * Math.cos(tiltDeg * Math.PI / 180);
// Split an area between ground under tables and open ground between rows. pitch: row-to-row spacing (m);
// tableWidth: plan width of one table across the row (m); excludedFraction: tracks, kit and margins taken out
// first (ASSUMED 0 unless given). Assumes rows spread evenly over the area.
export function panelSplit(areaM2, { pitch, tableWidth, excludedFraction = 0 } = {}) {
if (!(pitch > 0) || !(tableWidth > 0)) throw new Error('land: row pitch and table width must be positive');
if (tableWidth > pitch) throw new Error('land: table width cannot exceed the row pitch');
if (!(excludedFraction >= 0 && excludedFraction < 1)) throw new Error('land: excluded fraction must be 0 to <1');
const gcr = tableWidth / pitch, excluded = areaM2 * excludedFraction, arrayM2 = areaM2 - excluded;
return { gcr, excludedM2: excluded, arrayM2, underPanelsM2: arrayM2 * gcr, betweenRowsM2: arrayM2 * (1 - gcr) };
}
// Sheep capacity note for a grazed area. Returns ranges and cited sources; every figure is labelled assumed.
export function grazingNote(grazedM2) {
const ha = grazedM2 / 1e4, s = SHEEP.solar, g = SHEEP.grassland;
const ewes = lu => lu / g.lowlandEweLU;
return {
assumed: true, grazedHa: ha,
solarFarm: { low: Math.floor(ha * s.low), high: Math.floor(ha * s.high), perHa: [s.low, s.high], basis: s.basis },
newPasture: { low: Math.floor(ha * s.newPasture[0]), high: Math.floor(ha * s.newPasture[1]), perHa: [...s.newPasture] },
grasslandCheck: { ewesPerHa: [Math.round(ewes(g.lowLU[0])), Math.round(ewes(g.highLU[1]))], basis: 'in season, open grassland' },
sources: [{ text: s.source, url: s.url }, { text: g.source, url: g.url }],
text: `Assumed: about ${Math.floor(ha * s.low)} to ${Math.floor(ha * s.high)} sheep on ${ha.toFixed(1)} ha of grazed ` +
`solar farm (${s.low} to ${s.high} per ha; ${s.newPasture[0]} to ${s.newPasture[1]} per ha on new pasture), BRE 2014. ` +
'Needs module lower edges clear of the sheep (typically 0.8 to 0.9 m) and a grazing plan; not site-specific.',
};
}
// ---------- crops (CROME 2024) ----------
// One CROME cell's outline: a hexagon of the given side about its centre, flat-topped (vertices east and west:
// columns 1.5 x side apart, as the 2024 cut has them) or pointy; with no side, a square of the given area.
export function cellRing(e, n, { side, area, orientation = 'flat' } = {}) {
if (!(side > 0)) { const h = Math.sqrt(area) / 2; return [[e - h, n - h], [e + h, n - h], [e + h, n + h], [e - h, n + h]]; }
const a0 = orientation === 'pointy' ? 30 : 0;
return Array.from({ length: 6 }, (_, k) => { const a = (a0 + 60 * k) * Math.PI / 180; return [e + side * Math.cos(a), n + side * Math.sin(a)]; });
}
// Crop area by code inside the field. Each cell is clipped to the field and to the cells before it (scanlines, as
// areaByGrade), so the areas add up to at most the field: a hexagon half over the box edge counts half.
export function cropMix(fieldRings, crops, { step = STEP_M } = {}) {
if (!crops || !Array.isArray(crops.cells) || !(crops.hex_area_m2 > 0)) return null;
const f = prepare(fieldRings), byCode = {};
if (!(f.y1 > f.y0)) return [];
const shape = { side: crops.hex_side_m, area: crops.hex_area_m2, orientation: crops.hex_orientation };
const cells = crops.cells.map(([e, n, code, prob], i) => ({ i, code, prob, poly: prepare([cellRing(e, n, shape)]) }))
.filter(c => c.poly.y1 > f.y0 && c.poly.y0 < f.y1 && c.poly.x1 > f.x0 && c.poly.x0 < f.x1)
.sort((a, b) => a.poly.y0 - b.poly.y0 || a.i - b.i);
const areaOf = new Float64Array(crops.cells.length);
const rows = Math.max(1, Math.ceil((f.y1 - f.y0) / step)), dy = (f.y1 - f.y0) / rows;
let next = 0, active = [];
for (let k = 0; k < rows; k++) {
const y = f.y0 + (k + 0.5) * dy;
while (next < cells.length && cells[next].poly.y0 <= y) active.push(cells[next++]);
active = active.filter(c => c.poly.y1 > y);
let rest = intervalsAt(f, y);
if (!rest.length) continue;
for (const c of [...active].sort((a, b) => a.i - b.i)) {
if (!rest.length) break;
const I = intervalsAt(c.poly, y);
if (!I.length) continue;
areaOf[c.i] += span(intersect(rest, I)) * dy;
rest = subtract(rest, I);
}
}
for (const c of cells) {
const a = areaOf[c.i];
if (!(a > 0)) continue;
const o = byCode[c.code] || (byCode[c.code] = { code: c.code, name: crops.codes?.[c.code]?.name || null,
group: crops.codes?.[c.code]?.group || null, cells: 0, areaM2: 0, probArea: 0 });
o.cells++; o.areaM2 += a; o.probArea += (c.prob ?? 0) * a;
}
return Object.values(byCode).map(({ probArea, ...c }) => ({ ...c, meanProb: c.areaM2 ? probArea / c.areaM2 : null }))
.sort((a, b) => b.areaM2 - a.areaM2);
}
// ---------- the report ----------
const add = (into, from) => { for (const [k, v] of Object.entries(from)) into[k] = (into[k] || 0) + v; return into; };
// fields: [{ id?, rings }] in BNG metres. panels: { pitch, tableWidth, excludedFraction? } or null.
export function landReport(fields, land, { panels = null, step = STEP_M } = {}) {
const out = { fields: [], total: { fieldM2: 0, unclassifiedM2: 0, notGradedM2: 0, grades: {}, notGraded: {}, source: {} } };
for (const [i, f] of (fields || []).entries()) {
const r = areaByGrade(f.rings, land, { step });
out.fields.push({ id: f.id ?? `field-${i + 1}`, ...r, crops: cropMix(f.rings, land.crops, { step }) });
out.total.fieldM2 += r.fieldM2; out.total.unclassifiedM2 += r.unclassifiedM2; out.total.notGradedM2 += r.notGradedM2;
add(out.total.grades, r.grades); add(out.total.notGraded, r.notGraded);
for (const [g, s] of Object.entries(r.source)) out.total.source[g] = out.total.source[g] && out.total.source[g] !== s ? 'both' : s;
}
const t = out.total;
t.bmvM2 = BMV.reduce((s, g) => s + (t.grades[g] || 0), 0);
t.possibleBmvM2 = t.grades[UNSPLIT_GRADE_3] || 0; // provisional grade 3: 3a (BMV) or 3b; needs a survey
if (panels) {
const split = panelSplit(t.fieldM2, panels);
const k = split.arrayM2 / (t.fieldM2 || 1);
split.byGrade = Object.fromEntries(Object.entries(t.grades).map(([g, a]) =>
[g, { underPanelsM2: a * k * split.gcr, betweenRowsM2: a * k * (1 - split.gcr) }]));
out.panels = split;
out.grazing = grazingNote(split.arrayM2);
}
out.assumptions = [
'Grades come from Natural England maps: the provisional map is about 1:250,000 and not for field-level decisions; ' +
'a detailed ALC survey decides.',
'Rows are assumed spread evenly across each field, so panel cover falls on every grade in proportion to its area.',
'Stocking rates are typical published figures, labelled assumed; the land, sward, breed and season decide.',
];
out.sources = (land.sources || []).map(s => ({ id: s.id, name: s.name, licence: s.licence, attribution: s.attribution, url: s.url }));
out.attribution = land.attribution || '';
return out;
}
const ha = m2 => `${(m2 / 1e4).toFixed(2)} ha`;
// Plain lines for a panel or the console.
export function reportLines(r) {
const t = r.total, lines = [`Area: ${ha(t.fieldM2)}` + (t.unclassifiedM2 > 1 ? ` (${ha(t.unclassifiedM2)} outside the land data)` : '')];
const from = { post1988: 'post-1988 survey', both: 'survey and provisional', provisional: 'provisional' };
for (const [g, a] of Object.entries(t.grades).sort()) lines.push(` ${g}: ${ha(a)} (${from[t.source[g]] || 'provisional'})`);
lines.push(`Best and most versatile (1, 2, 3a): ${ha(t.bmvM2)}`);
if (t.notGradedM2 > 0) lines.push(`${NOT_GRADED_LABEL}: ${ha(t.notGradedM2)} (no ALC grade; the map marks it ` +
`${Object.keys(t.notGraded).sort().map(k => `"${k}"`).join(', ')})`);
if (t.possibleBmvM2 > 0) lines.push(`Provisional grade 3, not split into 3a/3b: ${ha(t.possibleBmvM2)} (a survey would decide)`);
if (r.panels) {
const p = r.panels;
lines.push(`Under panels: ${ha(p.underPanelsM2)} (ground cover ${(p.gcr * 100).toFixed(0)}%); open between rows: ${ha(p.betweenRowsM2)}` +
(p.excludedM2 > 0 ? `; tracks and kit: ${ha(p.excludedM2)}` : ''));
lines.push(r.grazing.text);
}
lines.push(r.attribution);
return lines;
}