GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / wire-frame-scanner / scanner

Fictional and 4 more files

A Python module in Wire Frame Scanner that works with solar block (`solar_block`) and solar block heights (`solar_block_heights`) and calculates planar distances and angles (units: MW).

594 lines of Python from wire-frame-scanner, in 5 files. Topic: Websites and apps. Section 2026 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. Wire Frame Scanner — Scanner transform · wire-frame-scanner / scanner/core.py lines 1–105
  2. Fictional transform · wire-frame-scanner / scanner/fictional.py lines 1–159
  3. Pylon transform · wire-frame-scanner / scanner/pylon.py lines 1–148
  4. Structures render · wire-frame-scanner / scanner/structures.py lines 1–122
  5. Vlidar transform · wire-frame-scanner / scanner/vlidar.py lines 1–60

Wire Frame Scanner — Scanner

A Python module that labels blocks (`label_blocks`) and calculates angles. It is built from the panel mask helper (`panel_mask`), the row normal helper (`row_normal`) and the row pitch helper (`row_pitch`).

transformwire-frame-scanner / scanner/core.py · lines 1–105 of 105

What it does
It calculates its inputs. Defines 6 functions or classes, including panel_mask, label_blocks, row_normal, row_pitch, row_lines. Uses libraries math.
Why it exists in the grid workflow
README: "scanner/core.py: deterministic rules R1–R4, which run on the GPU (CuPy) or the CPU (NumPy)."
Downstream impact
Used directly by 3 files: Test Fictional Loop (wire-frame-scanner); Test Known Answer (wire-frame-scanner); Test Vlidar Loop (wire-frame-scanner).
What it achieves
Wire Frame Scanner core: measured, deterministic maths that runs on the GPU (CuPy) and the CPU (NumPy) alike.
Why it matters
Checked by 3 tests, including Test Fictional Loop.
Application
wire-frame-scanner · scanner · Python module
Uses
math
Used by
imported by Test Fictional Loop (import), imported by Test Known Answer (import), imported by Test Vlidar Loop (import)
Produces
panel_mask, label_blocks, row_normal, row_pitch, row_lines, refine_normal
Defines here
panel_mask, label_blocks, row_normal, row_pitch, row_lines, refine_normal
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee scanner/core.py:1-105 · blob b63a0b8d5f16e4afd4690af5453793bfa3c9ec80 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Wire Frame Scanner core: measured, deterministic maths that runs on the GPU (CuPy) and the CPU (NumPy) alike.

Every function takes the array module `xp` (cupy or numpy), so the same code is its own witness: run it twice
and the answers must agree. Units: pixels in, metres out once `mpp` (metres per pixel) is given.

  panel_mask(xp, rgb)                 dark, not green: where panels are in satellite imagery
  label_blocks(xp, mask)              connected regions (R1), labels with areas
  row_normal(xp, block)               R2: the direction across the rows, from the row EDGES (structure tensor),
                                      not from the block's outline
  row_pitch(xp, block, theta, mpp)    R3: the fundamental spacing across the rows, limited to 4-15 m, with the phase
  row_lines(xp, block, theta, pitch, phase)  R4: one segment per row, clipped to the block
"""
import math

PITCH_MIN_M, PITCH_MAX_M = 4.0, 15.0


def panel_mask(xp, rgb):
    r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
    return (0.3 * r + 0.59 * g + 0.11 * b < 75) & (g < r + 12) & (b > g - 18)


def label_blocks(xp, mask, ndimage, min_px=400):
    lab, n = ndimage.label(mask)
    areas = ndimage.sum(mask, lab, xp.arange(1, n + 1)) if n else xp.zeros(0)
    keep = [int(i) + 1 for i in range(n) if float(areas[i]) >= min_px]
    return lab, keep


def row_normal(xp, block):
    """Angle (radians, image x right / y down) of the normal to the rows, from the structure tensor of the mask edges.
    Rows are long thin stripes: their edges' gradients point across the rows, so the dominant gradient orientation
    is the row normal. The block's outline contributes little, because the rows' edges vastly outnumber it."""
    B = block.astype(xp.float32)
    gy, gx = xp.gradient(B)
    jxx, jyy, jxy = float((gx * gx).sum()), float((gy * gy).sum()), float((gx * gy).sum())
    return 0.5 * math.atan2(2 * jxy, jxx - jyy)


def row_pitch(xp, block, theta, mpp):
    """(pitch_px, phase_px, profile_origin) from the 1D profile of the block across the rows. The pitch is the
    FUNDAMENTAL inside 4-15 m: the lowest-frequency peak holding at least half the strongest peak's power in range."""
    Y, X = xp.nonzero(block)
    nx, ny = math.cos(theta), math.sin(theta)
    proj = X.astype(xp.float32) * nx + Y.astype(xp.float32) * ny
    lo = float(proj.min()); L = int(float(proj.max()) - lo) + 2
    prof = xp.bincount((proj - lo).astype(xp.int32), minlength=L).astype(xp.float32)
    n = 1 << max(10, (L * 4 - 1).bit_length())                       # zero-padded for a fine frequency grid
    G = xp.abs(xp.fft.rfft(prof - prof.mean(), n=n))
    f = xp.arange(G.size, dtype=xp.float32) / n                       # cycles per pixel
    fmin, fmax = mpp / PITCH_MAX_M, mpp / PITCH_MIN_M
    inr = (f >= fmin) & (f <= fmax)
    if not bool(inr.any()):
        return None
    Gi = xp.where(inr, G, 0)
    peak = float(Gi.max())
    # local maxima in range with at least half the strongest power: take the lowest frequency (the fundamental)
    loc = (Gi[1:-1] > Gi[:-2]) & (Gi[1:-1] >= Gi[2:]) & (Gi[1:-1] >= 0.5 * peak)
    idx = xp.nonzero(loc)[0]
    k = int(idx[0]) + 1 if idx.size else int(Gi.argmax())
    pitch = 1.0 / float(f[k])
    # phase: where the stripes sit, from the profile's projection onto the fundamental
    t = xp.arange(L, dtype=xp.float32)
    c, s = float((prof * xp.cos(2 * math.pi * t / pitch)).sum()), float((prof * xp.sin(2 * math.pi * t / pitch)).sum())
    phase = (math.atan2(s, c) / (2 * math.pi)) * pitch % pitch
    return pitch, phase, lo


def row_lines(xp, block, theta, pitch, phase, lo, min_px=6):
    """One segment per row: the extent of block pixels within 1 px of each row centre line (pixel coordinates)."""
    Y, X = xp.nonzero(block)
    nx, ny = math.cos(theta), math.sin(theta); tx, ty = -ny, nx
    off = X.astype(xp.float32) * nx + Y.astype(xp.float32) * ny - lo
    along = X.astype(xp.float32) * tx + Y.astype(xp.float32) * ty
    segs, d, top = [], phase, float(off.max())
    while d <= top:
        on = xp.abs(off - d) < 1.0
        if int(on.sum()) >= min_px:
            a0, a1 = float(along[on].min()), float(along[on].max())
            base = lo + d
            segs.append((base * nx + a0 * tx, base * ny + a0 * ty, base * nx + a1 * tx, base * ny + a1 * ty))
        d += pitch
    return segs


def refine_normal(xp, block, theta0, mpp, span_deg=8.0, step_deg=0.1):
    """Brute force: sweep the row normal +/- span around theta0 and keep the angle whose cross-row profile has the
    sharpest in-range spectral peak. Rows seen exactly edge-on give the tallest, narrowest peak. Deterministic."""
    Y, X = xp.nonzero(block)
    Xf, Yf = X.astype(xp.float32), Y.astype(xp.float32)
    best, best_t = -1.0, theta0
    k = int(round(span_deg / step_deg))
    for i in range(-k, k + 1):
        t = theta0 + math.radians(i * step_deg)
        proj = Xf * math.cos(t) + Yf * math.sin(t)
        lo = float(proj.min()); L = int(float(proj.max()) - lo) + 2
        prof = xp.bincount((proj - lo).astype(xp.int32), minlength=L).astype(xp.float32)
        n = 1 << max(10, (L * 4 - 1).bit_length())
        G = xp.abs(xp.fft.rfft(prof - prof.mean(), n=n))
        f = xp.arange(G.size, dtype=xp.float32) / n
        G = xp.where((f >= mpp / PITCH_MAX_M) & (f <= mpp / PITCH_MIN_M), G, 0)
        v = float(G.max())
        if v > best:
            best, best_t = v, t
    return best_t

Fictional

A Python module in Wire Frame Scanner that works with solar block (`solar_block`) and solar block heights (`solar_block_heights`) and calculates planar distances and angles (units: MW).

transformwire-frame-scanner / scanner/fictional.py · lines 1–159 of 159

What it does
It calculates its inputs. Defines 9 functions or classes, including val, _dir, box, solar_block, pt. Uses libraries math, numpy.
Downstream impact
Used directly by 2 files: Test Fictional (wire-frame-scanner); Test Fictional Loop (wire-frame-scanner).
What it achieves
It is built from the val step (`val`), the box step (`box`) and the fenced compound helper (`fenced_compound`). Fictional parametric design proposals: deterministic site models built from stated parameters only.
Why it matters
Checked by 2 tests, including Test Fictional.
Application
wire-frame-scanner · scanner · Python module
Uses
math, numpy
Used by
imported by Test Fictional (import), imported by Test Fictional Loop (import)
Produces
val, box, solar_block, solar_block_heights, fenced_compound, cable_route, pylon_row
Defines here
val, _dir, box, solar_block, pt, solar_block_heights, fenced_compound, cable_route, pylon_row
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee scanner/fictional.py:1-159 · blob a41825bbb718ac9267e2784ab53830022c7de50a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Fictional parametric design proposals: deterministic site models built from stated parameters only.

Nothing here is measured, derived from imagery or estimated from a rule. Every numeric value is wrapped as
{'value': v, 'unit': u, 'provenance': 'assumed (design proposal)'} (see docs-SCANNER.md, provenance rule, and
docs/SITEMODEL-SCHEMA.md). Each builder returns (model, segments): a plain dict model and a list of 3D line
segments ((x, y, z), (x, y, z)) in local metres (x east, y north, z up from local ground at 0).
Bearings and azimuths are compass degrees: 0 = north, 90 = east.
"""
import math
import numpy as np

PROV = 'assumed (design proposal)'


def val(v, unit):
    """Tag one numeric value with its unit and provenance."""
    return {'value': v, 'unit': unit, 'provenance': PROV}


def _dir(bearing_deg):
    b = math.radians(bearing_deg)
    return (math.sin(b), math.cos(b))


def box(w, d, h, origin=(0.0, 0.0, 0.0)):
    """Rectangular box w (x) by d (y) by h (z), corner at origin. 12 edges."""
    ox, oy, oz = origin
    c = [(ox + i * w, oy + j * d, oz + k * h) for k in (0, 1) for j in (0, 1) for i in (0, 1)]
    idx = [(0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7)]
    segs = [(c[a], c[b]) for a, b in idx]
    model = {'type': 'box', 'origin': [val(v, 'm') for v in origin],
             'width': val(w, 'm'), 'depth': val(d, 'm'), 'height': val(h, 'm')}
    return model, segs


def solar_block(mw, module_w_wp, module_len_m, module_wid_m, modules_per_table, pitch_m, tilt_deg, azimuth_deg,
                table_rows=2, tables_per_row=None, table_gap_m=0.5, front_h_m=0.8, origin=(0.0, 0.0)):
    """Solar block of fixed-tilt tables. Modules are portrait: table_rows modules up the slope, the rest side by side.
    Tables face azimuth_deg; rows run at azimuth_deg + 90. Row r's front edge lies r * pitch_m behind row 0's
    (measured horizontally along the facing direction), so row spacing equals the pitch exactly."""
    if modules_per_table % table_rows:
        raise ValueError('modules_per_table must be a multiple of table_rows')
    modules_needed = math.ceil(mw * 1e6 / module_w_wp)
    tables = math.ceil(modules_needed / modules_per_table)
    if tables_per_row is None:
        tables_per_row = math.ceil(math.sqrt(tables))
    rows = math.ceil(tables / tables_per_row)
    t_len = (modules_per_table // table_rows) * module_wid_m            # along the row
    slope = table_rows * module_len_m                                     # up the slope
    tilt = math.radians(tilt_deg)
    depth_h = slope * math.cos(tilt)                                      # horizontal footprint depth
    back_h = front_h_m + slope * math.sin(tilt)
    fx, fy = _dir(azimuth_deg)                                            # facing (front) direction
    ax, ay = _dir(azimuth_deg + 90.0)                                     # along-row direction
    ox, oy = origin
    rects, segs = [], []
    for k in range(tables):
        r, i = divmod(k, tables_per_row)
        s = i * (t_len + table_gap_m)
        b = -r * pitch_m                                                  # rows step back from the front
        def pt(u, v, z):  # u along row, v across (positive = toward front), from origin
            return (ox + u * ax + v * fx, oy + u * ay + v * fy, z)
        c = [pt(s, b, front_h_m), pt(s + t_len, b, front_h_m),
             pt(s + t_len, b - depth_h, back_h), pt(s, b - depth_h, back_h)]
        rects.append({'row': val(r, 'index'), 'index': val(i, 'index'), 'corners': [[val(q, 'm') for q in p] for p in c],
                      'front_height': val(front_h_m, 'm'), 'back_height': val(back_h, 'm'),
                      'tilt': val(tilt_deg, 'deg'), 'azimuth': val(azimuth_deg, 'deg')})
        segs += [(c[j], c[(j + 1) % 4]) for j in range(4)]
    model = {'type': 'solar_block', 'target_capacity': val(mw, 'MW'), 'module_rating': val(module_w_wp, 'Wp'),
             'module_length': val(module_len_m, 'm'), 'module_width': val(module_wid_m, 'm'),
             'modules_per_table': val(modules_per_table, 'count'), 'table_rows': val(table_rows, 'count'),
             'pitch': val(pitch_m, 'm'), 'tilt': val(tilt_deg, 'deg'), 'azimuth': val(azimuth_deg, 'deg'),
             'table_gap': val(table_gap_m, 'm'), 'front_height': val(front_h_m, 'm'),
             'origin': [val(v, 'm') for v in origin],
             'table_length': val(t_len, 'm'), 'table_slope_length': val(slope, 'm'),
             'table_depth_horizontal': val(depth_h, 'm'), 'back_height': val(back_h, 'm'),
             'tables': val(tables, 'count'), 'tables_per_row': val(tables_per_row, 'count'),
             'rows': val(rows, 'count'), 'modules': val(tables * modules_per_table, 'count'),
             'capacity': val(tables * modules_per_table * module_w_wp / 1e6, 'MW'),
             'table_rects': rects}
    return model, segs


def solar_block_heights(model, extent, cell):
    """Rasterise a solar_block model to a height-above-ground grid (a DSM minus DTM) for the virtual LiDAR loop.
    extent: a number E (grid covers [0, E] in x and y) or (xmin, ymin, xmax, ymax). Cell centres are sampled.
    Returns (heights[ny, nx], xs, ys); row 0 is ymin (y grows with row index, as in vlidar.rasterise)."""
    if np.isscalar(extent):
        extent = (0.0, 0.0, float(extent), float(extent))
    x0, y0, x1, y1 = extent
    xs = x0 + cell / 2 + cell * np.arange(int(round((x1 - x0) / cell)))
    ys = y0 + cell / 2 + cell * np.arange(int(round((y1 - y0) / cell)))
    X, Y = np.meshgrid(xs, ys)
    H = np.zeros_like(X)
    for t in model['table_rects']:
        c = np.array([[q['value'] for q in p] for p in t['corners']])
        a = c[1, :2] - c[0, :2]; L = np.hypot(*a); a /= L
        e = c[3, :2] - c[0, :2]; D = np.hypot(*e); e /= D
        u = (X - c[0, 0]) * a[0] + (Y - c[0, 1]) * a[1]
        v = (X - c[0, 0]) * e[0] + (Y - c[0, 1]) * e[1]
        on = (u >= 0) & (u <= L) & (v >= 0) & (v <= D)
        h = c[0, 2] + (c[3, 2] - c[0, 2]) * (v / D)
        H = np.where(on, np.maximum(H, h), H)
    return H, xs, ys


def fenced_compound(w, d, fence_h, post_spacing, origin=(0.0, 0.0)):
    """Rectangular fence w by d with posts every post_spacing along the perimeter (corners always posted)."""
    ox, oy = origin
    c = [(ox, oy), (ox + w, oy), (ox + w, oy + d), (ox, oy + d)]
    segs, posts = [], []
    for j in range(4):
        (xa, ya), (xb, yb) = c[j], c[(j + 1) % 4]
        segs.append(((xa, ya, 0.0), (xb, yb, 0.0)))
        segs.append(((xa, ya, fence_h), (xb, yb, fence_h)))
        side = math.hypot(xb - xa, yb - ya)
        n = math.ceil(side / post_spacing - 1e-9)
        for k in range(n):
            f = k / n
            posts.append((xa + f * (xb - xa), ya + f * (yb - ya)))
    segs += [((px, py, 0.0), (px, py, fence_h)) for px, py in posts]
    model = {'type': 'fenced_compound', 'width': val(w, 'm'), 'depth': val(d, 'm'),
             'fence_height': val(fence_h, 'm'), 'post_spacing': val(post_spacing, 'm'),
             'origin': [val(v, 'm') for v in origin],
             'perimeter': val(2 * (w + d), 'm'), 'area': val(w * d, 'm2'), 'posts': val(len(posts), 'count')}
    return model, segs


def cable_route(start, end, trench_depth_m, trench_width_m):
    """Straight cable route start->end (x, y) with a rectangular trench; cross-section drawn at both ends."""
    (xa, ya), (xb, yb) = start, end
    L = math.hypot(xb - xa, yb - ya)
    ux, uy = (xb - xa) / L, (yb - ya) / L
    nx, ny = -uy * trench_width_m / 2, ux * trench_width_m / 2
    segs = [((xa, ya, -trench_depth_m), (xb, yb, -trench_depth_m))]
    for (px, py) in (start, end):
        q = [(px + nx, py + ny, 0.0), (px + nx, py + ny, -trench_depth_m),
             (px - nx, py - ny, -trench_depth_m), (px - nx, py - ny, 0.0)]
        segs += [(q[0], q[1]), (q[1], q[2]), (q[2], q[3])]
    for s in (1, -1):
        segs.append(((xa + s * nx, ya + s * ny, 0.0), (xb + s * nx, yb + s * ny, 0.0)))
    model = {'type': 'cable_route', 'start': [val(v, 'm') for v in start], 'end': [val(v, 'm') for v in end],
             'trench_depth': val(trench_depth_m, 'm'), 'trench_width': val(trench_width_m, 'm'),
             'length': val(L, 'm'), 'bearing': val(math.degrees(math.atan2(ux, uy)) % 360, 'deg'),
             'trench_volume': val(L * trench_depth_m * trench_width_m, 'm3')}
    return model, segs


def pylon_row(start, bearing, span_m, count, height_m=50.0):
    """count pylons from start along bearing, span_m apart; masts plus one conductor between tops."""
    bx, by = _dir(bearing)
    pts = [(start[0] + k * span_m * bx, start[1] + k * span_m * by) for k in range(count)]
    segs = [((x, y, 0.0), (x, y, height_m)) for x, y in pts]
    segs += [((pts[k][0], pts[k][1], height_m), (pts[k + 1][0], pts[k + 1][1], height_m)) for k in range(count - 1)]
    model = {'type': 'pylon_row', 'start': [val(v, 'm') for v in start], 'bearing': val(bearing, 'deg'),
             'span': val(span_m, 'm'), 'count': val(count, 'count'), 'height': val(height_m, 'm'),
             'positions': [[val(x, 'm'), val(y, 'm')] for x, y in pts],
             'route_length': val(span_m * (count - 1), 'm')}
    return model, segs

Pylon

A Python module in Wire Frame Scanner that works with overhead lines (OHL), using BS EN 50341.

transformwire-frame-scanner / scanner/pylon.py · lines 1–148 of 148 · Not reached from any entry point (candidate for review) · pattern leg_point (shared by 3 files)

What it does
It calculates overhead lines (OHL). Defines 6 functions or classes, including half_width, leg_point, panel_levels, arm_levels, lattice_pylon.
Why it exists in the grid workflow
Domain terms in the code: overhead lines (OHL), 400kV, 132kV, 1kV.
Inputs & outputs
Voltage levels named: 400kV, 132kV, 1kV.
Downstream impact
Used directly by 1 file: Test Pylon (wire-frame-scanner).
What it achieves
It is built from the half width helper (`half_width`), the leg point helper (`leg_point`) and the panel levels helper (`panel_levels`). Deterministic lattice-pylon wireframe skeleton (procedural fill, not a measurement). Its code works with 1 kV, 132 kV and 400 kV.
Why it matters
Checked by Test Pylon.
Application
wire-frame-scanner · scanner · Python module
Uses
none found
Used by
imported by Test Pylon (import)
Produces
half_width, leg_point, panel_levels, arm_levels, lattice_pylon
Defines here
half_width, leg_point, panel_levels, arm_levels, lattice_pylon, f
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee scanner/pylon.py:1-148 · blob d42e01d7bd6469149968a037823d7660f5eee65b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
"""Deterministic lattice-pylon wireframe skeleton (procedural fill, not a measurement).

lattice_pylon(voltage_class, bracing='K'|'X', ...) returns (lines, model):
  lines: list of ((x, y, z), (x, y, z)) segments in metres, tower centre at origin, z up, arms along +/-x.
  model: dict of every dimension, each as {'value', 'tag', 'source'} per the provenance rule in docs-SCANNER.md,
         plus counts and the insulator drop points.

Geometry:
  - 4 legs taper linearly from a square base (half-width b at z=0) to a square waist (half-width w at z=h_waist),
    then run vertical at half-width w up to the top (z=h_top). Body: n_body panels below the waist, n_top above.
  - Each panel has 4 leg segments, 4 horizontals at its top level, and on each of the 4 faces 2 bracing members:
      X: both diagonals of the face.
      K: from the midpoint of one leg to the bottom and top of the opposite leg (the letter K: two arms meeting
         on the stroke). Every bracing endpoint lies on a leg.
  - Base: 4 horizontals at z=0.
  - Cross-arms: n_arms_per_side levels on each side (3 per side = double circuit), attached to leg nodes on the
    vertical top section. Each arm: 2 upper chords + 2 lower chords to a tip on the x axis, plus 1 insulator drop.
  Line count = panels * (4 + 4 + 8) + 4 + 2 * n_arms_per_side * 5.

PROVENANCE: every height/width below is ASSUMED (illustrative, not from a published table; to be replaced by cited
values). No internet was available when this was written and no table was consulted. Sources the local team should
cite when replacing these values (to be checked, not quoted here):
  - The network operator's tower-type design schedules for the relevant suite (e.g. the L-series lattice suites used
    on the GB 275/400 kV system and the standard 132 kV suites), with issue/revision.
  - BS EN 50341 (overhead lines exceeding AC 1 kV) and its GB National Normative Aspects, for clearances.
  - ENA Technical Specification 43-8 (overhead line clearances) for ground and phase clearances.
  - Measured data (LiDAR heights, survey drawings) for the specific tower, which override any type value.
"""

ASSUMED = 'assumed'
ASSUMED_SRC = 'assumed (illustrative, not from a published table; to be replaced by cited values)'

# Illustrative only. Keys: h_top, h_waist, base_half, waist_half, arm_len (list, bottom->top), arm_depth,
# insulator_len, n_body, n_top. Metres.
_ASSUMED_DIMS = {
    132: dict(h_top=27.0, h_waist=14.0, base_half=2.6, waist_half=0.9, arm_len=[3.4, 3.8, 3.4],
              arm_depth=1.2, insulator_len=1.8, n_body=4, n_top=4),
    275: dict(h_top=42.0, h_waist=22.0, base_half=4.0, waist_half=1.3, arm_len=[5.4, 6.0, 5.4],
              arm_depth=1.8, insulator_len=3.2, n_body=5, n_top=5),
    400: dict(h_top=50.0, h_waist=26.0, base_half=4.8, waist_half=1.5, arm_len=[6.3, 7.0, 6.3],
              arm_depth=2.1, insulator_len=4.0, n_body=6, n_top=6),
}

CORNERS = [(1, 1), (-1, 1), (-1, -1), (1, -1)]      # leg order, counter-clockwise
FACES = [(0, 1), (1, 2), (2, 3), (3, 0)]            # each face spans two adjacent legs


def half_width(z, d):
    """Leg half-width at height z (linear taper to waist, then vertical)."""
    if z >= d['h_waist']:
        return d['waist_half']
    t = z / d['h_waist']
    return d['base_half'] + t * (d['waist_half'] - d['base_half'])


def leg_point(i, z, d):
    sx, sy = CORNERS[i]
    h = half_width(z, d)
    return (sx * h, sy * h, z)


def panel_levels(d):
    zb = [d['h_waist'] * k / d['n_body'] for k in range(d['n_body'] + 1)]
    zt = [d['h_waist'] + (d['h_top'] - d['h_waist']) * k / d['n_top'] for k in range(1, d['n_top'] + 1)]
    return zb + zt


def arm_levels(d, n):
    """Arm heights: on the upper panel nodes of the vertical top section, skipping the topmost (earthwire peak)."""
    zl = panel_levels(d)[d['n_body'] + 1:-1]         # nodes strictly above waist, below top
    step = max(1, len(zl) // n)
    zs = zl[-n * step::step][:n] if len(zl) >= n else zl
    if len(zs) != n:
        raise ValueError('not enough top-section panels for the requested arms')
    return zs


def lattice_pylon(voltage_class, bracing='K', n_arms_per_side=3, dims=None):
    if bracing not in ('K', 'X'):
        raise ValueError("bracing must be 'K' or 'X'")
    if dims is None:
        if voltage_class not in _ASSUMED_DIMS:
            raise ValueError(f'no assumed dimensions for {voltage_class} kV; supply dims=')
        d = dict(_ASSUMED_DIMS[voltage_class])
        src_tag, src = ASSUMED, ASSUMED_SRC
    else:
        d = dict(dims)
        src_tag, src = d.pop('tag', ASSUMED), d.pop('source', ASSUMED_SRC)
    arm_len = list(d['arm_len'])
    if len(arm_len) != n_arms_per_side:
        arm_len = [arm_len[min(k, len(arm_len) - 1)] for k in range(n_arms_per_side)]

    lines = []
    zs = panel_levels(d)
    for i, j in FACES:                                       # base horizontals
        lines.append((leg_point(i, 0.0, d), leg_point(j, 0.0, d)))
    for z0, z1 in zip(zs[:-1], zs[1:]):
        zm = 0.5 * (z0 + z1)
        for i in range(4):                                   # leg segments
            lines.append((leg_point(i, z0, d), leg_point(i, z1, d)))
        for i, j in FACES:                                   # horizontals at panel top
            lines.append((leg_point(i, z1, d), leg_point(j, z1, d)))
        for i, j in FACES:                                   # face bracing, 2 per face
            if bracing == 'X':
                lines.append((leg_point(i, z0, d), leg_point(j, z1, d)))
                lines.append((leg_point(j, z0, d), leg_point(i, z1, d)))
            else:
                lines.append((leg_point(i, zm, d), leg_point(j, z0, d)))
                lines.append((leg_point(i, zm, d), leg_point(j, z1, d)))

    w, depth = d['waist_half'], d['arm_depth']
    za = arm_levels(d, n_arms_per_side)
    drops = []
    for side in (1, -1):
        for k, z in enumerate(za):
            tip = (side * (w + arm_len[k]), 0.0, z)
            for sy in (1, -1):
                lines.append(((side * w, sy * w, z), tip))           # upper chord (leg node)
                lines.append(((side * w, sy * w, z - depth), tip))   # lower chord (on vertical leg)
            drop = (tip[0], 0.0, z - d['insulator_len'])
            lines.append((tip, drop))
            drops.append({'side': side, 'level': k, 'tip': tip, 'drop': drop})

    n_panels = d['n_body'] + d['n_top']
    expected = n_panels * 16 + 4 + 2 * n_arms_per_side * 5
    assert len(lines) == expected

    def f(v):
        return {'value': v, 'tag': src_tag, 'source': src}

    model = {
        'type': 'lattice_pylon',
        'voltage_kv': {'value': voltage_class, 'tag': 'assumed', 'source': 'caller-supplied class'},
        'bracing': {'value': bracing, 'tag': 'assumed', 'source': 'caller choice'},
        'height_top_m': f(d['h_top']), 'height_waist_m': f(d['h_waist']),
        'base_width_m': f(2 * d['base_half']), 'waist_width_m': f(2 * d['waist_half']),
        'arm_lengths_m': f(arm_len), 'arm_depth_m': f(depth), 'insulator_length_m': f(d['insulator_len']),
        'n_body_panels': f(d['n_body']), 'n_top_panels': f(d['n_top']),
        'n_panels': {'value': n_panels, 'tag': 'derived', 'source': 'n_body + n_top'},
        'arm_heights_m': {'value': za, 'tag': 'derived', 'source': 'top-section panel nodes'},
        'n_lines': {'value': len(lines), 'tag': 'derived',
                    'source': 'panels*16 + 4 + 2*arms_per_side*5'},
        'insulator_drops': {'value': drops, 'tag': 'derived', 'source': 'arm tip minus insulator length'},
        'n_circuits': {'value': 2 if n_arms_per_side == 3 else None, 'tag': 'assumed',
                       'source': '3 arms per side read as double circuit'},
        'procedural': True,
    }
    return lines, model

Structures

A Python module in Wire Frame Scanner that renders png (`render_png`).

renderwire-frame-scanner / scanner/structures.py · lines 1–122 of 122 · pattern line_count (shared by 4 files)

What it does
It lists and searches its content. Defines 6 functions or classes, including pchip_slopes, pchip_eval, ring_heights, line_count, tower_skeleton. Uses libraries math, numpy, matplotlib, matplotlib.pyplot.
Inputs & outputs
Out: figure image.
Downstream impact
Used directly by 1 file: Test Structures (wire-frame-scanner).
What it achieves
It is built from the pchip slopes helper (`pchip_slopes`), the pchip eval helper (`pchip_eval`) and the ring heights helper (`ring_heights`). Tower skeleton from a few measured pins, rule-shaped between them.
Why it matters
Checked by Test Structures.
Application
wire-frame-scanner · scanner · Python module
Uses
math, numpy, matplotlib, matplotlib.pyplot
Used by
imported by Test Structures (import)
Produces
pchip_slopes, pchip_eval, ring_heights, line_count, tower_skeleton, render_png
Defines here
pchip_slopes, pchip_eval, ring_heights, line_count, tower_skeleton, render_png
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee scanner/structures.py:1-122 · blob 40db98da8139f61a073f04beafb3c69e4689755a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Tower skeleton from a few measured pins, rule-shaped between them.

Pins are measured points on the radius profile r(z): base radius at z=0, widest radius and its height, and the
total height with its top radius. Each pin carries provenance "measured" and a `source` citation field.
Between pins the profile is a Fritsch-Carlson monotone piecewise cubic (PCHIP), tagged "rule-shaped between pins":
it passes exactly through every pin and never overshoots between them.

Skeleton: floor rings at fixed spacing (circles as n_diagrid segments) and two opposing helical diagrid families
whose nodes are the ring vertices. Lines: rings R*n + diagrid 2*n*(R-1) = n*(3R-2), R = number of rings.
"""
import math
import numpy as np

PIN_TAG = 'measured'
FILL_TAG = 'rule-shaped between pins'


def pchip_slopes(x, y):
    """Fritsch-Carlson derivatives at the knots (monotone-preserving)."""
    x = np.asarray(x, float); y = np.asarray(y, float)
    n = x.size
    h = np.diff(x); d = np.diff(y) / h
    m = np.zeros(n)
    if n == 2:
        m[:] = d[0]; return m
    for k in range(1, n - 1):
        if d[k - 1] * d[k] <= 0:
            m[k] = 0.0
        else:  # weighted harmonic mean (Fritsch-Butland form used by PCHIP)
            w1 = 2 * h[k] + h[k - 1]; w2 = h[k] + 2 * h[k - 1]
            m[k] = (w1 + w2) / (w1 / d[k - 1] + w2 / d[k])
    # three-point end slopes, limited to keep monotonicity
    for k, (h0, h1, d0, d1) in ((0, (h[0], h[1], d[0], d[1])), (n - 1, (h[-1], h[-2], d[-1], d[-2]))):
        s = ((2 * h0 + h1) * d0 - h0 * d1) / (h0 + h1)
        if s * d0 <= 0:
            s = 0.0
        elif d0 * d1 <= 0 and abs(s) > abs(3 * d0):
            s = 3 * d0
        m[k] = s
    return m


def pchip_eval(x, y, m, z):
    x = np.asarray(x, float); y = np.asarray(y, float)
    z = np.atleast_1d(np.asarray(z, float))
    i = np.clip(np.searchsorted(x, z, side='right') - 1, 0, x.size - 2)
    h = x[i + 1] - x[i]; t = (z - x[i]) / h
    h00 = (1 + 2 * t) * (1 - t) ** 2; h10 = t * (1 - t) ** 2
    h01 = t * t * (3 - 2 * t); h11 = t * t * (t - 1)
    return h00 * y[i] + h10 * h * m[i] + h01 * y[i + 1] + h11 * h * m[i + 1]


def ring_heights(total_h, spacing):
    k = int(math.floor(total_h / spacing + 1e-9))
    zs = [j * spacing for j in range(k + 1)]
    if total_h - zs[-1] > 1e-9:
        zs.append(total_h)
    return zs


def line_count(n_rings, n_diagrid):
    return n_diagrid * n_rings + 2 * n_diagrid * (n_rings - 1)


def tower_skeleton(pins, ring_spacing_m, n_diagrid):
    """pins: list of dicts {z, r, label, source}. Returns (lines, model). Each line is ((x,y,z),(x,y,z), kind)."""
    pins = sorted(pins, key=lambda p: p['z'])
    zp = np.array([p['z'] for p in pins], float); rp = np.array([p['r'] for p in pins], float)
    if zp[0] != 0.0 or np.any(np.diff(zp) <= 0) or len(pins) < 2:
        raise ValueError('pins need z=0 base and strictly increasing heights')
    m = pchip_slopes(zp, rp)
    profile = lambda z: pchip_eval(zp, rp, m, z)
    zs = ring_heights(zp[-1], ring_spacing_m)
    rs = [float(profile(z)[0]) for z in zs]
    n = int(n_diagrid)
    ang = [2 * math.pi * j / n for j in range(n)]
    node = lambda k, j: (rs[k] * math.cos(ang[j % n]), rs[k] * math.sin(ang[j % n]), zs[k])
    lines = []
    for k in range(len(zs)):
        for j in range(n):
            lines.append((node(k, j), node(k, j + 1), 'ring'))
    for k in range(len(zs) - 1):
        for j in range(n):
            lines.append((node(k, j), node(k + 1, j + 1), 'diagrid+'))
            lines.append((node(k, j), node(k + 1, j - 1), 'diagrid-'))
    model = {
        'pins': [dict(p, provenance=PIN_TAG) for p in pins],
        'profile': {'method': 'Fritsch-Carlson monotone piecewise cubic (PCHIP)', 'provenance': FILL_TAG,
                    'knots_z': zp.tolist(), 'knots_r': rp.tolist(), 'slopes': m.tolist()},
        'rings': [{'z': z, 'r': r, 'provenance': FILL_TAG} for z, r in zip(zs, rs)],
        'ring_spacing_m': ring_spacing_m, 'n_diagrid': n,
        'n_lines': len(lines), 'n_lines_formula': line_count(len(zs), n),
        'label': 'measured at these points, rule-shaped between',
        'profile_fn': profile,
    }
    return lines, model


# Illustrative example only: a generic 100 m tower, not any real building. Sources are placeholders.
EXAMPLE_PINS = [
    {'z': 0.0, 'r': 20.0, 'label': 'base radius', 'source': 'measured (cite source)'},
    {'z': 45.0, 'r': 24.0, 'label': 'widest radius', 'source': 'measured (cite source)'},
    {'z': 100.0, 'r': 6.0, 'label': 'total height, top radius', 'source': 'measured (cite source)'},
]


def render_png(lines, model, path):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    fig = plt.figure(figsize=(7, 8))
    ax = fig.add_subplot(111, projection='3d')
    col = {'ring': '#1f5fa8', 'diagrid+': '#c0392b', 'diagrid-': '#8e44ad'}
    for a, b, kind in lines:
        ax.plot([a[0], b[0]], [a[1], b[1]], [a[2], b[2]], color=col[kind], lw=0.6)
    for p in model['pins']:
        ax.scatter([p['r']], [0], [p['z']], color='k', s=25)
    ax.set_xlabel('x (m)'); ax.set_ylabel('y (m)'); ax.set_zlabel('z (m)')
    ax.set_box_aspect((1, 1, 2))
    ax.set_title('Illustrative example: generic 100 m tower\nmeasured at pins (black), rule-shaped between', fontsize=10)
    fig.savefig(path, dpi=120); plt.close(fig)
    return path

Vlidar

A Python module in Wire Frame Scanner that works with tables height (`tables_height`). It is built from the survey step (`survey`) and the rasterise step (`rasterise`).

transformwire-frame-scanner / scanner/vlidar.py · lines 1–60 of 60 · pattern survey (shared by 9 files)

What it does
It calculates its inputs. Defines tables_height, survey, rasterise. Uses libraries math, numpy, cupyx.
Downstream impact
Used directly by 2 files: Test Fictional Loop (wire-frame-scanner); Test Vlidar Loop (wire-frame-scanner).
What it achieves
Virtual LiDAR: simulate an airborne laser survey of a wireframe site model, on the GPU (CuPy) or the CPU (NumPy).
Why it matters
Checked by 2 tests, including Test Fictional Loop.
Application
wire-frame-scanner · scanner · Python module
Uses
math, numpy, cupyx
Used by
imported by Test Fictional Loop (import), imported by Test Vlidar Loop (import)
Produces
tables_height, survey, rasterise
Defines here
tables_height, survey, rasterise
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee scanner/vlidar.py:1-60 · blob b5fe8c9724f11a9c70d2bce7ad4c93600e2f839b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Virtual LiDAR: simulate an airborne laser survey of a wireframe site model, on the GPU (CuPy) or the CPU (NumPy).

A site model gives surfaces: the ground (a height function) and solid objects (here, tilted solar tables as planes
between a front edge height and a back edge height). The simulator fires pulses on a regular scan pattern with
jitter (points per square metre is a parameter), finds each pulse's first return (the highest surface hit) and last
return (the ground), adds range noise, and rasterises a DSM (first return) and DTM (last return), like the EA's.
Deterministic: the jitter comes from a seeded generator, so the same model and seed give the same cloud.

This is the scanner run in reverse. scanner(vlidar(model)) must give back the model's rows: a closed loop.
"""
import math
import numpy as np


def tables_height(xp, x, y, rows_bearing_deg, pitch_m, depth_m, front_m=0.8, back_m=2.4, mask=None):
    """Height of tilted tables at points (x, y) in metres (0 where there is no table). Rows run along the bearing;
    across the row, the table rises from front_m to back_m over depth_m, then there is a gap to the next row."""
    th = math.radians(rows_bearing_deg) + math.pi / 2
    u = (x * math.cos(th) + y * math.sin(th)) % pitch_m                # position across the row cycle
    on = u < depth_m
    h = xp.where(on, front_m + (back_m - front_m) * (u / depth_m), 0.0)
    if mask is not None:
        h = xp.where(mask, h, 0.0)
    return h


def survey(xp, extent_m, ground_fn, object_fn, ppsm=8.0, noise_m=0.05, seed=1):
    """Simulate pulses over a square extent (metres). Returns x, y, first-return z, last-return z (arrays)."""
    n = int(extent_m * extent_m * ppsm)
    side = int(math.sqrt(n))
    g = np.linspace(0, extent_m, side, endpoint=False, dtype=np.float32)
    gx, gy = np.meshgrid(g, g)
    rng = np.random.default_rng(seed)
    jx = rng.uniform(-0.5, 0.5, gx.shape).astype(np.float32) * (extent_m / side)
    jy = rng.uniform(-0.5, 0.5, gy.shape).astype(np.float32) * (extent_m / side)
    nz = rng.normal(0, noise_m, gx.shape).astype(np.float32)
    x, y = xp.asarray((gx + jx).ravel()), xp.asarray((gy + jy).ravel())
    ground = ground_fn(xp, x, y)
    first = ground + object_fn(xp, x, y) + xp.asarray(nz.ravel())
    last = ground + xp.asarray(nz.ravel())
    return x, y, first, last


def rasterise(xp, x, y, z, extent_m, cell_m=0.5, how='max'):
    """Grid points into a raster (the highest point per cell for a DSM). Empty cells are filled from the left."""
    n = int(extent_m / cell_m)
    ix = xp.clip((x / cell_m).astype(xp.int32), 0, n - 1); iy = xp.clip((y / cell_m).astype(xp.int32), 0, n - 1)
    flat = iy * n + ix
    out = xp.full(n * n, -1e9, dtype=xp.float32)
    if xp is np:
        np.maximum.at(out, flat, z)
    else:
        import cupyx
        cupyx.scatter_max(out, flat, z)
    out = out.reshape(n, n)
    empty = out < -1e8
    if bool(empty.any()):
        out = xp.where(empty, xp.roll(out, 1, axis=1), out)
        out = xp.where(out < -1e8, 0.0, out)
    return out