In this section
- CAD Wireframe render · kuiper-drawing-engine / tools/cad_wireframe.py lines 1–56
- Check Full Plant storage · kuiper-drawing-engine / tools/check_full_plant.py lines 1–50
- Check Public Bundle other · kuiper-drawing-engine / tools/check_public_bundle.py lines 1–25
- Distill Candidates storage · kuiper-drawing-engine / tools/distill_candidates.py lines 1–45
- Electrical Reference Check electrical · kuiper-drawing-engine / tools/electrical_reference_check.py lines 1–74
- Export Geometry Template storage · kuiper-drawing-engine / tools/export_geometry_template.mjs lines 1–8
- Geometry Loop storage · kuiper-drawing-engine / tools/geometry_loop.py lines 1–87
- Height Envelope Check storage · kuiper-drawing-engine / tools/height_envelope_check.py lines 1–38
- Hourly Check storage · kuiper-drawing-engine / tools/hourly_check.py lines 1–29
- Kuiper Drawing Engine — App interaction · kuiper-drawing-engine / web/app.mjs lines 1–37
- Geometry transform · kuiper-drawing-engine / web/geometry.mjs lines 1–47
- Kuiper Drawing Engine — Index Page render · kuiper-drawing-engine / web/index.html lines 1–14
- Site transform · kuiper-drawing-engine / web/site.mjs lines 1–25
- Elements on Wafer ingest · neural-link-between-agents / FIXES/NL-010/tools/evidence/nl010/team-4/elements_on_wafer.py lines 1–24
CAD Wireframe
A Python module in the tools folder of Kuiper Drawing Engine.
renderkuiper-drawing-engine / tools/cad_wireframe.py · lines 1–56 of 56 · Not reached from any entry point (candidate for review)
- What it does
- It draws its content. Uses libraries argparse, json, math, sys, pathlib. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments. Out: SVG drawing.
- What it achieves
- Local STEP edge preview. Source and derived drawings retain source restrictions. It accepts `--runtime`, `--step` and `--out`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- kuiper-drawing-engine · tools · Python module
- Uses
- argparse, json, math, sys, pathlib, OCP.STEPControl, OCP.IFSelect, OCP.TopExp
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 tools/cad_wireframe.py:1-56 · blob 7779635bd518376193de21a44434944edcb30654 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Local STEP edge preview. Source and derived drawings retain source restrictions.
No upload or publication. Requires an isolated OCP runtime supplied by the user.
"""
import argparse
import json
import math
import sys
from pathlib import Path
p = argparse.ArgumentParser()
p.add_argument('--runtime', type=Path, required=True)
p.add_argument('--step', type=Path, required=True)
p.add_argument('--out', type=Path, required=True)
a = p.parse_args()
sys.path.insert(0, str(a.runtime))
from OCP.STEPControl import STEPControl_Reader
from OCP.IFSelect import IFSelect_RetDone
from OCP.TopExp import TopExp_Explorer
from OCP.TopAbs import TopAbs_EDGE
from OCP.TopoDS import TopoDS
from OCP.BRepAdaptor import BRepAdaptor_Curve
reader = STEPControl_Reader()
if reader.ReadFile(str(a.step)) != IFSelect_RetDone:
raise ValueError('STEP could not be read')
reader.TransferRoots()
explorer = TopExp_Explorer(reader.OneShape(), TopAbs_EDGE)
lines = []
while explorer.More():
curve = BRepAdaptor_Curve(TopoDS.Edge_s(explorer.Current()))
first, last = curve.FirstParameter(), curve.LastParameter()
if not math.isfinite(first + last):
raise ValueError('Unbounded edge')
points = []
for i in range(21):
point = curve.Value(first + (last - first) * i / 20)
x, y, z = point.X(), point.Y(), point.Z()
points.append((math.sqrt(3) / 2 * (x - y), (x + y) / 2 - z))
lines.append(points)
if len(lines) > 10000:
raise ValueError('Preview edge budget exceeded')
explorer.Next()
if not lines:
raise ValueError('No edges found')
xs = [p[0] for line in lines for p in line]
ys = [p[1] for line in lines for p in line]
lo = [min(xs), min(ys)]
factor = min(960 / max(max(xs) - lo[0], 1e-9), 660 / max(max(ys) - lo[1], 1e-9))
paths = []
for line in lines:
points = ' '.join(f'{20+(x-lo[0])*factor:.3f},{20+(y-lo[1])*factor:.3f}' for x,y in line)
paths.append(f'<polyline points="{points}"/>')
a.out.write_text('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 700"><title>Local CAD edge preview; uniformly sampled curves; source restrictions apply</title><g fill="none" stroke="#333" stroke-width="0.5">' + ''.join(paths) + '</g></svg>')
print(json.dumps({'status': 'pass', 'edges': len(lines), 'curve_samples': len(lines) * 21,
'bytes': a.out.stat().st_size, 'publication': 'not authorized by this tool'}))Check Full Plant
A Python module in the tools folder of Kuiper Drawing Engine.
storagekuiper-drawing-engine / tools/check_full_plant.py · lines 1–50 of 50 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Uses libraries argparse, json, time, pathlib, numpy. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- Enumerate all virtual-plant module corners in GPU batches; retain only summary. It accepts `--template` and `--out`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- kuiper-drawing-engine · tools · Python module
- Uses
- argparse, json, time, pathlib, numpy, cupy
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 tools/check_full_plant.py:1-50 · blob 90781e3af6ad7fb1b7f28690449980bb1620e1b9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Enumerate all virtual-plant module corners in GPU batches; retain only summary.
Input template is produced by tested JS geometry. CPU checks placement arithmetic
independently; this is not an independent check of the input module template.
"""
import argparse
import json
import time
from pathlib import Path
import numpy as np
import cupy as cp
parser = argparse.ArgumentParser()
parser.add_argument('--template', type=Path, required=True)
parser.add_argument('--out', type=Path, required=True)
args = parser.parse_args()
source = json.loads(args.template.read_text())
site = source['site']
base = np.array(source['corners'], dtype=np.float64)
gpu_base = cp.asarray(base)
lo = np.full(3, np.inf)
hi = -lo
max_error = 0.
start = time.perf_counter()
for begin in range(0, site['modules'], 131072):
stop = min(begin + 131072, site['modules'])
ids = cp.arange(begin, stop, dtype=cp.int64)
table = ids // site['modulesPerTable']
points = gpu_base[ids % site['modulesPerTable']].copy()
points[:, :, 0] += ((table % site['columns']) * site['pitch'][0] - site['min'][0])[:, None]
points[:, :, 1] += ((table // site['columns']) * site['pitch'][1] - site['min'][1])[:, None]
actual = cp.asnumpy(points)
# Host quotient/remainder and offset matrix provide the second placement path.
host = np.arange(begin, stop)
tables, local = np.divmod(host, len(base))
row, column = np.divmod(tables, site['columns'])
offsets = np.column_stack([column * site['pitch'][0], row * site['pitch'][1], np.zeros(len(host))])
expected = base[local] - np.array([*site['min'], 0]) + offsets[:, None, :]
max_error = max(max_error, float(np.max(np.abs(actual - expected))))
if not np.isfinite(actual).all() or max_error > 1e-8:
raise RuntimeError('Full-plant placement mismatch')
lo = np.minimum(lo, actual.min(axis=(0, 1)))
hi = np.maximum(hi, actual.max(axis=(0, 1)))
result = {'status': 'pass', 'modules': site['modules'], 'corners': site['modules'] * 4,
'coordinates': site['modules'] * 12, 'max_cpu_gpu_difference_m': max_error,
'bounds_min_m': lo.tolist(), 'bounds_max_m': hi.tolist(),
'seconds': time.perf_counter() - start,
'scope': 'Every module in synthetic regular placement; no terrain, exclusions, cables or approval. Template geometry checked separately in JS tests.'}
args.out.write_text(json.dumps(result, indent=2))
print(json.dumps({k: result[k] for k in ['status', 'modules', 'coordinates', 'max_cpu_gpu_difference_m', 'seconds']}))Check Public Bundle
A Python command-line tool in the tools folder of Kuiper Drawing Engine that uses SHA-256. It is built from the check step (`check`).
otherkuiper-drawing-engine / tools/check_public_bundle.py · lines 1–25 of 25 · Entry point
- What it does
- Defines check. Uses libraries hashlib, json, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 1 file: Array Pages Workflow (kuiper-drawing-engine).
- What it achieves
- Reject unexpected deployment files. This is a packaging gate, not anonymization.
- Why it matters
- Run by Array Pages Workflow.
- Application
- kuiper-drawing-engine · tools · Python CLI
- Uses
- hashlib, json, pathlib
- Used by
- run by Array Pages Workflow (workflow run)
- Produces
- check
- Defines here
- check
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 tools/check_public_bundle.py:1-25 · blob 6a2654df089fab9b2e9199d50bfcda47df57a234 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Reject unexpected deployment files. This is a packaging gate, not anonymization."""
import hashlib
import json
from pathlib import Path
ALLOWED = {'index.html', 'style.css', 'app.mjs', 'geometry.mjs', 'site.mjs'}
def check(root):
root = Path(root).resolve()
files = list(root.rglob('*'))
if any(p.is_symlink() for p in files):
raise ValueError('Deployment must not contain symbolic links')
actual = {p.relative_to(root).as_posix() for p in files if p.is_file()}
if actual != ALLOWED:
raise ValueError('Deployment file allowlist mismatch')
size = sum((root / name).stat().st_size for name in actual)
if size >= 150000:
raise ValueError('Deployment exceeds size budget')
return {'bytes': size, 'files': {name: hashlib.sha256((root / name).read_bytes()).hexdigest()
for name in sorted(actual)}}
if __name__ == '__main__':
print(json.dumps(check(Path(__file__).resolve().parents[1] / 'web'), indent=2))Distill Candidates
A Python module in the tools folder of Kuiper Drawing Engine that reads drawing diverse shortlist private, drawing shortlist private and distillation summary, using SHA-256.
storagekuiper-drawing-engine / tools/distill_candidates.py · lines 1–45 of 45 · Not reached from any entry point (candidate for review)
- What it does
- It loads drawing diverse shortlist private, drawing shortlist private and distillation summary. Uses libraries argparse, json, time, re, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments. Out: JSON file drawing-diverse-shortlist.private.json; JSON file drawing-shortlist.private.json; JSON file distillation-summary.json.
- What it achieves
- Local GPU similarity graph over lexical code features; not semantic approval. It accepts `--audit`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- kuiper-drawing-engine · tools · Python module
- Uses
- argparse, json, time, re, pathlib, cupy, numpy
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 tools/distill_candidates.py:1-45 · blob 216d8ad01ee03b04c3886204bacba44f87bd213d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Local GPU similarity graph over lexical code features; not semantic approval."""
import argparse,json,time,re
from pathlib import Path
import cupy as cp
import numpy as np
ap=argparse.ArgumentParser();ap.add_argument('--audit',required=True);args=ap.parse_args();root=Path(args.audit)
rows=[json.loads(x) for x in (root/'drawing-candidates.private.jsonl').read_text().splitlines()]
vocabulary=sorted({p for r in rows for p in r['patterns']});lookup={p:i for i,p in enumerate(vocabulary)}
x=np.zeros((len(rows),len(vocabulary)),np.float32)
for i,r in enumerate(rows):
for p in r['patterns']:x[i,lookup[p]]=1
idf=np.log((len(rows)+1)/(x.sum(0)+1))+1;x*=idf;x/=np.maximum(np.linalg.norm(x,axis=1,keepdims=True),1e-12)
gx=cp.asarray(x);indices=[];weights=[];max_error=0.;started=time.perf_counter()
for begin in range(0,len(rows),256):
similarity=gx[begin:begin+256]@gx.T
local=cp.arange(similarity.shape[0]);similarity[local,begin+local]=-1
best=cp.argpartition(similarity,-5,axis=1)[:,-5:];value=cp.take_along_axis(similarity,best,axis=1)
indices.append(best);weights.append(cp.maximum(value,0))
if begin==0:
actual=cp.asnumpy(similarity[:8,:128]);expected=x[:8]@x[:128].T
for i in range(8):expected[i,i]=-1
max_error=float(np.max(np.abs(actual-expected)))
neighbors=cp.concatenate(indices);weight=cp.concatenate(weights);weight/=cp.maximum(weight.sum(1,keepdims=True),1e-12)
seed=np.array([sum(p in r['patterns'] for p in ['modulegeometry','arraygeometry','portrait','azimuth','junction']) for r in rows],np.float32)
seed/=max(float(seed.sum()),1);base=cp.asarray(seed);rank=base.copy()
for _ in range(24):
nxt=.2*base;cp.add.at(nxt,neighbors.ravel(),(.8*rank[:,None]*weight).ravel());rank=nxt
selected=cp.asnumpy(cp.argsort(rank)[-100:][::-1]);scores=cp.asnumpy(rank[selected]);result=[]
for index,score in zip(selected,scores):
row=dict(rows[int(index)]);row['lexical_graph_score']=float(score);result.append(row)
# A second shortlist limits repeated versions from one source directory.
diverse=[];families={};seen=set()
all_indices=cp.asnumpy(cp.argsort(rank)[::-1]);all_scores=cp.asnumpy(rank)
for index in all_indices:
row=dict(rows[int(index)]);fingerprint=row.get('normalized_sha256',row.get('sha256'))
family=(row['repository'],re.sub(r'\d+', '#', str(Path(row['path']).parent)))
if fingerprint in seen or families.get(family,0)>=3:continue
seen.add(fingerprint);families[family]=families.get(family,0)+1
row['lexical_graph_score']=float(all_scores[int(index)]);diverse.append(row)
if len(diverse)>=100:break
(root/'drawing-diverse-shortlist.private.json').write_text(json.dumps({'scope':'Directory-diverse lexical candidates, not semantic admission. Hashes refer to normalized text.', 'items':diverse},indent=2))
(root/'drawing-shortlist.private.json').write_text(json.dumps({'scope':'Lexical feature similarity and bounded propagation. Candidate discovery only; source/licence review still required.','items':result},indent=2))
summary=dict(files=len(rows),edges=len(rows)*5,propagation_steps=24,cpu_gpu_similarity_error=max_error,wall_seconds=time.perf_counter()-started,status='pass' if max_error<1e-5 else 'fail')
(root/'distillation-summary.json').write_text(json.dumps(summary,indent=2));print(json.dumps(summary))
if max_error>=1e-5:raise SystemExit(1)Electrical Reference Check
A Python command-line tool in the tools folder of Kuiper Drawing Engine. It is built from the screen step (`screen`).
electricalkuiper-drawing-engine / tools/electrical_reference_check.py · lines 1–74 of 74 · Entry point · pattern screen (shared by 3 files)
- What it does
- It loads data. Defines screen. Uses libraries argparse, json, pathlib, numpy, cupy. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Local-only reference screening. Inputs/outputs can be confidential: never deploy them. It accepts `--references`, `--profile` and `--out`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- kuiper-drawing-engine · tools · Python CLI
- Uses
- argparse, json, pathlib, numpy, cupy
- Used by
- none found
- Produces
- screen
- Defines here
- screen
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 tools/electrical_reference_check.py:1-74 · blob 87a9b500fc5bcb1199b8bb4d4c06b603521c2f5e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Local-only reference screening. Inputs/outputs can be confidential: never deploy them.
Linear Voc temperature model only; not a complete string-sizing calculation.
Current comparisons use STC values, without bifacial gain or design factors.
"""
import argparse
import json
from pathlib import Path
import numpy as np
import cupy as cp
def screen(ref, profile):
module, inverter = ref['module'], ref['inverter']
temps = np.linspace(module['minimumOperatingC'], module['maximumOperatingC'], 12601)
series = np.arange(1, 61)
voc = np.array([b['voc'] for b in module['bins']])
beta = module['vocCoefficientPerC']
limit = min(module['maximumSystemV'], inverter['maximumDcV'])
# Different algebra on GPU and CPU, double precision on both.
gpu = cp.asarray(series)[None, :, None] * (
cp.asarray(voc)[None, None, :] +
cp.asarray(voc)[None, None, :] * beta * (cp.asarray(temps)[:, None, None] - 25))
cpu = np.multiply.outer(1 + beta * (temps - 25), series)[:, :, None] * voc
observed = cp.asnumpy(gpu)
tolerance = 1e-8
max_error = float(np.max(np.abs(observed - cpu)))
# Boundary band reported separately: do not hide floating-point equality effects.
boundary = np.abs(cpu - limit) <= tolerance
disagreement = int(np.count_nonzero(((observed > limit) != (cpu > limit)) & ~boundary))
if not np.isfinite(observed).all() or max_error > tolerance or disagreement:
raise RuntimeError('Independent reference comparison failed')
chosen = next(b for b in module['bins'] if b['watts'] == profile['moduleW'])
n = profile['series']
crossing = 25 + (limit / (n * chosen['voc']) - 1) / beta if beta else None
variants = []
for variant in inverter['variants']:
parallel = variant['inputsPerMppt']
variants.append({
'mppts': variant['mppts'],
'maximum_input_strings': parallel * variant['mppts'],
'selected_string_count_fits': profile['stringsPerInverter'] <= parallel * variant['mppts'],
'fully_populated_mppt_imp_stc_A': parallel * chosen['imp'],
'operating_limit_exceeded_at_stc': parallel * chosen['imp'] > variant['operatingLimitA'],
'fully_populated_mppt_isc_stc_A': parallel * chosen['isc'],
'short_circuit_limit_exceeded_at_stc': parallel * chosen['isc'] > variant['shortCircuitLimitA'],
})
return {
'status': 'numeric comparison passed; engineering admission unresolved',
'cases': int(cpu.size), 'max_cpu_gpu_error_V': max_error,
'classification_disagreements_outside_boundary_band': disagreement,
'boundary_band_cases': int(boundary.sum()),
'selected_string_voltage_limit_V': limit,
'selected_linear_voc_crossing_cell_temperature_C': crossing,
'selected_voc_at_minimum_module_operating_temperature_V': n * chosen['voc'] * (1 + beta * (temps[0] - 25)),
'variants': variants,
'missing_checks': ['site design cell temperatures', 'voltage tolerances',
'bifacial and irradiance current factors', 'MPPT voltage temperature model',
'installed inverter variant', 'protection coordination', 'cable sizing and routing',
'approved equipment revision and junction geometry'],
'scope': 'Private draft reference screening, not approval or probability of safety',
}
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--references', required=True, type=Path)
parser.add_argument('--profile', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
args = parser.parse_args()
result = screen(json.loads(args.references.read_text(encoding='utf-8-sig')),
json.loads(args.profile.read_text(encoding='utf-8-sig')))
args.out.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
print(json.dumps({k: result[k] for k in ['status', 'cases', 'max_cpu_gpu_error_V']}))Export Geometry Template
A JavaScript module in the tools folder of Kuiper Drawing Engine.
storagekuiper-drawing-engine / tools/export_geometry_template.mjs · lines 1–8 of 8 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Uses libraries node:fs. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- Local numeric interchange only. A private input produces a private output.
- Why it matters
- No other file in the estate was found to import it.
- Application
- kuiper-drawing-engine · tools · JavaScript module
- Uses
- Geometry (import), Site (import), node:fs
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 tools/export_geometry_template.mjs:1-8 · blob 39f294f017516147656c1d6b6a95e97f590f3bde · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// Local numeric interchange only. A private input produces a private output.
import fs from 'node:fs';
import {array,validate} from '../web/geometry.mjs';
import {siteModel} from '../web/site.mjs';
const [input,output]=process.argv.slice(2);
if(!input||!output)throw Error('Usage: node export_geometry_template.mjs settings.json output.json');
const settings=validate(JSON.parse(fs.readFileSync(input,'utf8')));
fs.writeFileSync(output,JSON.stringify({site:siteModel(settings),corners:array(settings).modules.map(m=>m.corners)}));Geometry Loop
A Python command-line tool in the tools folder of Kuiper Drawing Engine that calculates planar distances.
storagekuiper-drawing-engine / tools/geometry_loop.py · lines 1–87 of 87 · Entry point · pattern witness (shared by 3 files)
- What it does
- Defines atomic, witness, batch, temperature, main. Uses libraries argparse, json, math, os, subprocess. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file status.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the atomic step (`atomic`), the witness step (`witness`) and the batch step (`batch`). Bounded synthetic array geometry comparison; compact local outputs only. It accepts `--out`, `--hours` and `--batch`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- kuiper-drawing-engine · tools · Python CLI
- Uses
- argparse, json, math, os, subprocess, time, datetime, pathlib
- Used by
- none found
- Produces
- atomic, witness, batch, temperature, main
- Defines here
- atomic, witness, batch, temperature, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 tools/geometry_loop.py:1-87 · blob 1a37ffcc9d73aecaa4ff9fcbaae862fea92d052c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Bounded synthetic array geometry comparison; compact local outputs only."""
import argparse, json, math, os, subprocess, time
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import cupy as cp
SPACE=720*601*10*60*271*2
KERNEL=cp.RawKernel(r'''
extern "C" __global__ void corners(unsigned long long start,int n,double* out){
int k=blockDim.x*blockIdx.x+threadIdx.x;if(k>=n)return;
unsigned long long i=start+k;int a=i%720;i/=720;int t=i%601;i/=601;
int rows=i%10+1;i/=10;int cols=i%60+1;i/=60;int h=i%271;i/=271;int landscape=i%2;
double az=a*0.5*3.141592653589793/180.,tilt=t*0.1*3.141592653589793/180.;
double length=landscape?1.2:2.4,width=landscape?2.4:1.2;
double run=rows*length+(rows-1)*.02,half=(cols*width+(cols-1)*.02)/2.;
out[3*k]=cos(az)*half-sin(az)*cos(tilt)*run;
out[3*k+1]=-sin(az)*half-cos(az)*cos(tilt)*run;
out[3*k+2]=.3+h*.01+sin(tilt)*run;
}''','corners')
def atomic(path,data):
temp=path.with_suffix('.tmp');temp.write_text(json.dumps(data,indent=2)+'\n',encoding='utf-8');temp.replace(path)
def witness(ids):
results=[]
for value in ids:
i=int(value);a=i%720;i//=720;t=i%601;i//=601;rows=i%10+1;i//=10;cols=i%60+1;i//=60;h=i%271;i//=271;landscape=i%2
az=math.radians(a*.5);tilt=math.radians(t*.1);length,width=(1.2,2.4) if landscape else (2.4,1.2)
run=rows*length+(rows-1)*.02;half=(cols*width+(cols-1)*.02)/2
u=np.array([math.cos(az),-math.sin(az),0.]);v=np.array([-math.sin(az)*math.cos(tilt),-math.cos(az)*math.cos(tilt),math.sin(tilt)])
results.append(u*half+v*run+np.array([0.,0.,.3+h*.01]))
return np.array(results)
def batch(start,n):
i=cp.arange(start,start+n,dtype=cp.uint64);a=i%720;i//=720;t=i%601;i//=601;rows=i%10+1;i//=10;cols=i%60+1;i//=60;h=i%271;i//=271;landscape=i%2
az=a.astype(cp.float64)*(.5*math.pi/180);tilt=t.astype(cp.float64)*(.1*math.pi/180)
run=rows*cp.where(landscape,1.2,2.4)+(rows-1)*.02
half=(cols*cp.where(landscape,2.4,1.2)+(cols-1)*.02)/2
radius=cp.hypot(half,run*cp.cos(tilt));angle=cp.arctan2(-run*cp.cos(tilt),half)-az
other=cp.stack([radius*cp.cos(angle),radius*cp.sin(angle),.3+h*.01+run*cp.cos(math.pi/2-tilt)],axis=1)
actual=cp.empty((n,3),cp.float64);KERNEL(((n+255)//256,),(256,),(np.uint64(start),np.int32(n),actual))
error=float(cp.max(cp.abs(actual-other)).get());invalid=int(cp.count_nonzero(~cp.isfinite(actual)).get())
sample=np.unique(np.linspace(0,n-1,min(n,257),dtype=np.int64));got=cp.asnumpy(actual[cp.asarray(sample)])
cpu_error=float(np.max(np.abs(got-witness(start+sample))))
return dict(max_gpu_difference=error,max_cpu_difference=cpu_error,cpu_witnesses=len(sample),nonfinite=invalid)
def temperature():
try:return float(subprocess.check_output(['nvidia-smi','--query-gpu=temperature.gpu','--format=csv,noheader,nounits'],text=True,timeout=10).splitlines()[0])
except Exception:return None
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--hours',type=float,default=5);ap.add_argument('--batch',type=int,default=1048576);ap.add_argument('--smoke',action='store_true');args=ap.parse_args()
if not 0<args.hours<=5 or not 1<=args.batch<=4194304:raise ValueError('Bound exceeded')
out=Path(args.out);out.mkdir(parents=True,exist_ok=True);lock=out/'running.lock'
fd=os.open(lock,os.O_CREAT|os.O_EXCL|os.O_WRONLY);os.write(fd,str(os.getpid()).encode());os.close(fd)
start_time=time.time();deadline=start_time+args.hours*3600
state=dict(status='starting',pid=os.getpid(),started_at=datetime.now(timezone.utc).isoformat(),deadline_epoch=deadline,
unique_cases=0,space=SPACE,batches=0,cpu_witnesses=0,max_gpu_difference=0.,max_cpu_difference=0.,
scope='Synthetic rectangular-array corner geometry only; not shading, electrical suitability or engineering approval.')
cp.get_default_memory_pool().set_limit(size=2*1024**3)
try:
# Dispersed whole-domain witnesses, not only the first azimuth interval.
for index in [0,719,720,432719,SPACE//2,SPACE-1024]:
test=batch(index,128)
if max(test['max_gpu_difference'],test['max_cpu_difference'])>1e-8 or test['nonfinite']:raise ValueError('Initial reference comparison failed')
while time.time()<deadline and state['unique_cases']<SPACE:
if (out/'STOP').exists():state['status']='stopped';break
temp=temperature();state['temperature_c']=temp;state['heartbeat']=datetime.now(timezone.utc).isoformat()
if temp is None or temp>=80:
state['status']='thermal_pause';atomic(out/'status.json',state);time.sleep(30);continue
n=min(args.batch,SPACE-state['unique_cases']);begin=state['unique_cases'];tick=time.perf_counter();result=batch(begin,n);elapsed=time.perf_counter()-tick
if max(result['max_gpu_difference'],result['max_cpu_difference'])>1e-8 or result['nonfinite']:raise ValueError('Numerical disagreement; results quarantined')
state.update(status='running',unique_cases=begin+n,batches=state['batches']+1,last_batch_seconds=elapsed,
cpu_witnesses=state['cpu_witnesses']+result['cpu_witnesses'],
max_gpu_difference=max(state['max_gpu_difference'],result['max_gpu_difference']),
max_cpu_difference=max(state['max_cpu_difference'],result['max_cpu_difference']))
atomic(out/'status.json',state)
if args.smoke:break
time.sleep(1)
if state['status']=='running':state['status']='smoke_pass' if args.smoke else 'deadline_reached' if time.time()>=deadline else 'domain_complete'
except Exception as exc:
state.update(status='failed',error=type(exc).__name__+': '+str(exc));raise
finally:
state['elapsed_seconds']=time.time()-start_time;atomic(out/'status.json',state);lock.unlink(missing_ok=True)
print(json.dumps({k:state.get(k) for k in ['status','unique_cases','cpu_witnesses','max_gpu_difference','max_cpu_difference']}))
if __name__=='__main__':main()Height Envelope Check
A Python module in the tools folder of Kuiper Drawing Engine.
storagekuiper-drawing-engine / tools/height_envelope_check.py · lines 1–38 of 38 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Uses libraries argparse, json, math, pathlib, numpy. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- Private draft height-envelope sweep. Candidate counts are not probabilities. It accepts `--evidence`, `--profile` and `--out`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- kuiper-drawing-engine · tools · Python module
- Uses
- argparse, json, math, pathlib, numpy, cupy
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 tools/height_envelope_check.py:1-38 · blob 6302aaa5eaa9d8f2294b8c8ccda6e965ddc222ec · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Private draft height-envelope sweep. Candidate counts are not probabilities."""
import argparse
import json
import math
from pathlib import Path
import numpy as np
import cupy as cp
p=argparse.ArgumentParser()
p.add_argument('--evidence',type=Path,required=True)
p.add_argument('--profile',type=Path,required=True)
p.add_argument('--out',type=Path,required=True)
a=p.parse_args()
e=json.loads(a.evidence.read_text());s=json.loads(a.profile.read_text())
facts={row['key']:row for row in e['facts']}
floor=facts['module_lowest_part_height_min']['value']
ceiling=facts['module_highest_part_height_max']['value']
length=s['moduleLength'] if s['orientation']=='portrait' else s['moduleWidth']
run=s['rows']*length+(s['rows']-1)*s['gap']
heights=np.arange(math.ceil(floor*100),math.floor(ceiling*100)+1)/100
tilts=np.arange(6001)/100
gpu=cp.asarray(heights)[:,None]+run*cp.sin(cp.deg2rad(cp.asarray(tilts)))[None,:]
actual=cp.asnumpy(gpu)
cpu=heights[:,None]+run*np.sin(tilts*np.pi/180)[None,:]
error=float(np.max(np.abs(actual-cpu)));band=np.abs(cpu-ceiling)<=1e-9
differences=int(np.count_nonzero(((actual<=ceiling)!=(cpu<=ceiling))&~band))
if error>1e-9 or differences or not np.isfinite(actual).all():raise RuntimeError('Envelope comparison failed')
top=s['height']+run*math.sin(math.radians(s['tilt']))
result={'scope':'Known contract height bounds only; no structural, terrain, shading or as-built admission',
'candidate_cells':int(cpu.size),'feasible_outside_boundary_band':int(((cpu<ceiling)&~band).sum()),
'boundary_band_cells':int(band.sum()),'max_cpu_gpu_error_m':error,
'classification_differences_outside_boundary_band':differences,
'selected_top_height_m':top,'selected_satisfies_known_height_bounds':s['height']>=floor and top<=ceiling,
'source_facts':[facts[k] for k in ['module_lowest_part_height_min','module_highest_part_height_max']],
'unknowns':['approved nominal tilt and mounting geometry','field-specific exceptions','terrain and structural loading'],
'publication':'private only; no probability or engineering approval claim'}
a.out.write_text(json.dumps(result,indent=2))
print(json.dumps({k:result[k] for k in ['candidate_cells','max_cpu_gpu_error_m','classification_differences_outside_boundary_band']}))Hourly Check
A Python module in the tools folder of Kuiper Drawing Engine that reads hourly status.
storagekuiper-drawing-engine / tools/hourly_check.py · lines 1–29 of 29 · Not reached from any entry point (candidate for review)
- What it does
- It loads hourly status. Uses libraries argparse, json, subprocess, time, pathlib. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file status.json; command-line arguments. Out: JSON file hourly-status.json.
- What it achieves
- Local supervisor report. Does not restart failed computations or publish. It accepts `--out` and `--memory-dir`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- kuiper-drawing-engine · tools · Python module
- Uses
- argparse, json, subprocess, time, pathlib, datetime
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 tools/hourly_check.py:1-29 · blob 29ceb73b830191b4699af9b25353c3f508b29fe9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Local supervisor report. Does not restart failed computations or publish."""
import argparse,json,subprocess,time
from pathlib import Path
from datetime import datetime,timezone
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--memory-dir');a=ap.parse_args();root=Path(a.out)
s=json.loads((root/'status.json').read_text());pid=s['pid']
p=subprocess.run(['tasklist','/FI',f'PID eq {pid}','/FO','CSV','/NH'],capture_output=True,text=True)
alive=f'"{pid}"' in p.stdout
r=dict(checked_at=datetime.now(timezone.utc).isoformat(),process_alive=alive,state=s['status'],unique_cases=s['unique_cases'],cpu_witnesses=s['cpu_witnesses'],max_gpu_difference=s['max_gpu_difference'],max_cpu_difference=s['max_cpu_difference'],temperature_c=s.get('temperature_c'),deadline_reached=time.time()>=s['deadline_epoch'])
(root/'hourly-status.json').write_text(json.dumps(r,indent=2)+'\n')
with (root/'hourly-history.jsonl').open('a') as f:f.write(json.dumps(r)+'\n')
if a.memory_dir:
dest=Path(a.memory_dir);dest.mkdir(parents=True,exist_ok=True)
now=datetime.now(timezone.utc);name=now.strftime('%Y%m%d-%H%M%S-array-layout.md')
message='\n'.join(['# Array layout progress', '', 'Checked (UTC): '+r['checked_at'],
'Worker alive: '+str(alive), 'State: '+r['state'],
'Distinct synthetic geometry cases: '+str(r['unique_cases']),
'Independent CPU witnesses: '+str(r['cpu_witnesses']),
'Largest GPU-channel difference: '+str(r['max_gpu_difference']),
'Largest CPU-reference difference: '+str(r['max_cpu_difference']),
'GPU temperature C: '+str(r['temperature_c']),
'', 'Scope: rectangular-array coordinates only. This does not establish electrical, structural or site approval.',
'Private source documents and private equipment parameters stay outside public Git and website assets.',
'Public interface: neutral wireframe array layout; configurable count, orientation, tilt and direction.',
'Next: review current test/CI status and the private requirements admission ledger before release.',
'This note is an automatic local checkpoint, not a claim that a human or AI reviewed this hour.', ''])
(dest/name).write_text(message,encoding='utf-8')
(dest/'LATEST.md').write_text(message,encoding='utf-8')
print(json.dumps(r))Kuiper Drawing Engine — App
A JavaScript module that sets placement (`setPlacement`), calculates planar distances and draws on a canvas. Served with the page at https://ventusltd.github.io/kuiper-drawing-engine/web/.
interactionkuiper-drawing-engine / web/app.mjs · lines 1–37 of 37 · Entry point · pattern fields (shared by 4 files)
- What it does
- It draws its content. Defines 9 functions or classes, including $, money, point3, poly, fields. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file array-settings.json. Out: canvas drawing; SVG drawing.
- Downstream impact
- Used directly by 2 files: Kuiper Drawing Engine — Index Page (kuiper-drawing-engine, https://ventusltd.github.io/kuiper-drawing-engine/web/); Array Pages Workflow (kuiper-drawing-engine). It is itself an entry point, published at https://ventusltd.github.io/kuiper-drawing-engine/web/.
- What it achieves
- It sets placement (`setPlacement`) and is built from the fields step (`fields`) and the height fields helper (`heightFields`). Defines `money`, `point3`, `poly` and 5 more. It responds to input and resize events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/kuiper-drawing-engine/web/. Run by Array Pages Workflow.
- Application
- kuiper-drawing-engine · web · JavaScript module
- Uses
- Site (import), Geometry (import)
- Used by
- loaded by Kuiper Drawing Engine — Index Page (script src), run by Array Pages Workflow (workflow run)
- Produces
- $, money, point3, poly, fields, heightFields, download, siteScale, setPlacement
- Defines here
- $, money, point3, poly, fields, heightFields, download, siteScale, setPlacement
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 web/app.mjs:1-37 · blob 1df6fd0f7b783d5721cd023090274dc1b5473816 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
import {siteModel,tableAt,validatePlacements,overlapsFor} from './site.mjs';
import {defaults,validate,array,plant} from './geometry.mjs';
const $=id=>document.getElementById(id),canvas=$('drawing'),ctx=canvas.getContext('2d');let settings={...defaults},model=array(settings),yaw=-.6,pitch=.65,scale=30,pan=[0,0],projected=[],drag=null,selected=null,view='array',site=siteModel(settings),placements={},selectedTable=0,siteHits=[],moving=false,siteZoom=1,siteFrame=null;
const money=n=>n.toLocaleString('en-GB');
function point3(p){let [x,y,z]=p;const a=x*Math.cos(yaw)-y*Math.sin(yaw),b=x*Math.sin(yaw)+y*Math.cos(yaw);return [innerWidth/2+pan[0]+a*scale,innerHeight/2+pan[1]+(b*Math.sin(pitch)-z*Math.cos(pitch))*scale];}
function poly(points){ctx.beginPath();points.forEach((p,i)=>i?ctx.lineTo(...p):ctx.moveTo(...p));ctx.closePath();ctx.stroke();}
function draw(){const count=tableAt(site,selectedTable,placements).modules;$('summary').textContent=view==='site'?`${money(site.modules)} modules in ${money(site.tables)} arrays`:`${count} modules shown - width ${model.span.toFixed(2)} m - slope ${model.run.toFixed(2)} m - top ${(model.height+model.rise).toFixed(2)} m`;$('arrayIndex').value=selectedTable+1;const d=devicePixelRatio||1;canvas.width= … [line shortened here: 630 characters; full line on GitHub]
for(const m of model.modules.slice(0,tableAt(site,selectedTable,placements).modules)){const pts=m.corners.map(point3);ctx.lineWidth=selected===m.id?2:.7;poly(pts);projected.push({id:m.id,pts});ctx.lineWidth=.8;for(const b of m.boxes){const p=point3(b);ctx.strokeRect(p[0]-2,p[1]-2,4,4);}}
ctx.strokeStyle='#647b91';ctx.lineWidth=.55;for(const member of model.structure){ctx.beginPath();member.points.map(point3).forEach((p,i)=>i?ctx.lineTo(...p):ctx.moveTo(...p));ctx.stroke();}
ctx.fillStyle='#a7bacb';ctx.font='12px Arial';ctx.fillText('N',...point3([0,model.run+2,0]));
}
function fit(){if(view==='site'){pan=[0,0];siteZoom=1;siteFrame=[0,0,site.width,site.height];for(const p of Object.values(placements)){siteFrame[0]=Math.min(siteFrame[0],p.x);siteFrame[1]=Math.min(siteFrame[1],p.y);siteFrame[2]=Math.max(siteFrame[2],p.x+site.size[0]);siteFrame[3]=Math.max(siteFrame[3],p.y+site.size[1]);}draw();return;}pan=[0,0];scale=1;const pts=[...model.modules.flatMap(m=>m.corn … [line shortened here: 770 characters; full line on GitHub]
function apply(next){settings=validate(next);model=array(settings);site=siteModel(settings);siteFrame=null;placements=Object.fromEntries(Object.entries(placements).filter(([i])=>Number(i)<site.tables));selectedTable=Math.min(selectedTable,site.tables-1);selected=null;const p=plant(settings);$('counts').textContent=`${money(p.modules)} modules\n${money(p.strings)} strings\n${money(p.inverters)} inv … [line shortened here: 735 characters; full line on GitHub]
function fields(){for(const el of $('form').elements)if(el.name&&el.name in settings)el.value=settings[el.name];$('direction').value=String(settings.azimuth);heightFields();}
function heightFields(){const form=$('form');form.elements.tilt.disabled=settings.heightMode==='edges';form.elements.upperHeight.disabled=settings.heightMode==='tilt';form.elements.tilt.value=Number(settings.tilt.toFixed(4));form.elements.upperHeight.value=Number(settings.upperHeight.toFixed(4));}
$('raised-preset').onclick=()=>{apply({...settings,heightMode:'edges',height:4,upperHeight:5});fields();fit();};
document.querySelectorAll('[data-preset]').forEach(button=>button.onclick=()=>{const key=button.dataset.preset;apply({...settings,rows:key==='ew'?5:1,orientation:'portrait',layout:key==='ew'?'east-west':'fixed',azimuth:{ew:90,south:180,east:90,west:270}[key]});fields();fit();});
$('form').addEventListener('input',()=>{try{const next={...settings};for(const el of $('form').elements)if(el.name)next[el.name]=el.type==='number'?Number(el.value):el.value;next.azimuth=Number($('direction').value);apply(next);heightFields();fit();}catch(e){$('error').textContent=e.message;}});
$('menu').onclick=()=>{$('settings').hidden=!$('settings').hidden;$('menu').setAttribute('aria-expanded',String(!$('settings').hidden));};$('fit').onclick=fit;$('plan').onclick=()=>{view='array';pitch=Math.PI/2;yaw=0;fit();};$('three').onclick=()=>{view='array';pitch=.65;yaw=-.6;fit();};$('full').onclick=()=>{if(!document.fullscreenElement)document.documentElement.requestFullscreen?.().catch(()=>{ … [line shortened here: 438 characters; full line on GitHub]
function download(name,text,type){const u=URL.createObjectURL(new Blob([text],{type}));const a=document.createElement('a');a.href=u;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(u),1000);}
$('save').onclick=()=>download('array-settings.json',JSON.stringify({schema:'array-layout/1',settings,placements:Object.entries(placements).map(([index,p])=>({index:Number(index),...p}))},null,2),'application/json');
$('load').onchange=async e=>{try{const f=e.target.files[0];if(!f)return;if(f.size>1000000)throw Error('Settings file is too large');const data=JSON.parse(await f.text());if(data.schema==='array-layout/1'){const next=validate(data.settings),moves=validatePlacements(data.placements,siteModel(next));apply(next);placements=moves;}else{apply(data);placements={};}fields();fit();}catch(err){$('error').te … [line shortened here: 443 characters; full line on GitHub]
$('svg').onclick=()=>{const outlines=view==='site'?siteHits.map(h=>({pts:[h.p,[h.p[0]+h.w,h.p[1]],[h.p[0]+h.w,h.p[1]+h.h],[h.p[0],h.p[1]+h.h]]})):projected;const paths=outlines.map(m=>`<polygon points="${m.pts.map(p=>p.map(x=>x.toFixed(3)).join(',')).join(' ')}"/>`).join('');const members=view==='array'?model.structure.map(m=>{const [a,b]=m.points.map(point3);return `<line x1="${a[0]}" y1="${a[1]} … [line shortened here: 796 characters; full line on GitHub]
canvas.oncontextmenu=e=>e.preventDefault();canvas.onpointerdown=e=>{if(view==='site'){if(e.button===2){drag={sitePan:true,x:e.clientX,y:e.clientY};canvas.setPointerCapture(e.pointerId);return;}const hit=[...siteHits].reverse().find(h=>e.clientX>=h.p[0]&&e.clientX<=h.p[0]+h.w&&e.clientY>=h.p[1]&&e.clientY<=h.p[1]+h.h);if(hit){selectedTable=hit.index;$('arrayIndex').value=selectedTable+1;canvas.setP … [line shortened here: 1,332 characters; full line on GitHub]
canvas.onpointerup=e=>{if(view==='site'){drag=null;draw();return;}if(drag&&Math.hypot(e.clientX-drag.startX,e.clientY-drag.startY)<4){let best=Infinity,hit=null;for(const m of projected){const c=m.pts.reduce((a,p)=>[a[0]+p[0]/4,a[1]+p[1]/4],[0,0]);const distance=Math.hypot(c[0]-e.clientX,c[1]-e.clientY);if(distance<best&&distance<40){best=distance;hit=m.id;}}selected=hit;const m=model.modules.find … [line shortened here: 943 characters; full line on GitHub]
// Read-only diagnostic state for automated geometry/browser checks.
window.arrayStudio={get state(){return {settings:{...settings},moduleCount:tableAt(site,selectedTable,placements).modules,plant:plant(settings),view,tableCount:site.tables,selectedTable,movedArrays:Object.keys(placements).length,selectedPosition:{...tableAt(site,selectedTable,placements)},selectedScreen:siteHits.find(h=>h.index===selectedTable),projectedBounds:projected.length?[Math.min(...project … [line shortened here: 607 characters; full line on GitHub]
function siteScale(){const b=siteFrame??[0,0,site.width,site.height];return siteZoom*Math.max(1e-9,Math.min((innerWidth-80)/(b[2]-b[0]),(innerHeight-150)/(b[3]-b[1])));}
function drawSite(){const overlaps=overlapsFor(site,selectedTable,placements);$('selection').textContent='Array '+(selectedTable+1)+' - '+overlaps.length+' overlapping array bounds';const b=siteFrame??[0,0,site.width,site.height],k=siteScale(),left=(innerWidth-(b[2]-b[0])*k)/2+pan[0],top=(innerHeight-(b[3]-b[1])*k)/2+pan[1];siteHits=[];const stride=site.groupSize;const shown=new Set([selectedTable … [line shortened here: 1,068 characters; full line on GitHub]
$('site').onclick=()=>{view='site';fit();};$('move').onclick=()=>{view='site';moving=!moving;$('move').textContent=moving?'Finish move':'Move array';draw();};
$('arrayIndex').onchange=()=>{const n=Number($('arrayIndex').value);if(!Number.isInteger(n)||n<1||n>site.tables){$('error').textContent='Array number must be 1 to '+site.tables;return;}selectedTable=n-1;$('error').textContent='';$('selection').textContent='Array '+n+' - '+tableAt(site,selectedTable,placements).modules+' modules';draw();};
document.querySelectorAll('[data-step]').forEach(button=>button.onclick=()=>{const t=tableAt(site,selectedTable,placements),delta={west:[-1,0],east:[1,0],north:[0,1],south:[0,-1]}[button.dataset.step];setPlacement({x:t.x+delta[0],y:t.y+delta[1]});view='site';draw();});
function setPlacement(p){try{if(!(selectedTable in placements)&&Object.keys(placements).length>=10000)throw Error('Maximum 10000 moved arrays');validatePlacements([{index:selectedTable,...p}],site);placements[selectedTable]=p;$('error').textContent='';}catch(e){$('error').textContent=e.message;}}Geometry
A JavaScript module in Kuiper Drawing Engine. Served with the page at https://ventusltd.github.io/kuiper-drawing-engine/web/. It is built from the point step (`point`), the array step (`array`) and the plant step (`plant`).
transformkuiper-drawing-engine / web/geometry.mjs · lines 1–47 of 47 · pattern plant (shared by 3 files)
- What it does
- It calculates its inputs. Defines 6 functions or classes, including validate, rad, basis, point, array.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 3 files: Export Geometry Template (kuiper-drawing-engine); Kuiper Drawing Engine — App (kuiper-drawing-engine, https://ventusltd.github.io/kuiper-drawing-engine/web/); Site (kuiper-drawing-engine, https://ventusltd.github.io/kuiper-drawing-engine/web/). Reached from 2 other entry points, including Kuiper Drawing Engine — Index Page (kuiper-drawing-engine, https://ventusltd.github.io/kuiper-drawing-engine/web/); Array Pages Workflow (kuiper-drawing-engine).
- What it achieves
- Defines `validate`, `rad`, `basis` and 3 more.
- Why it matters
- Imported by Export Geometry Template, Kuiper Drawing Engine — App and Site.
- Application
- kuiper-drawing-engine · web · JavaScript module
- Uses
- none found
- Used by
- imported by Export Geometry Template (import), imported by Kuiper Drawing Engine — App (import), imported by Site (import)
- Produces
- defaults, validate, basis, point, array, plant
- Defines here
- validate, rad, basis, point, array, plant
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 web/geometry.mjs:1-47 · blob ef31d2999765e56f79424b3ab2cd6564e77ce787 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
// Original geometry. Coordinates: east (x), north (y), up (z); metres.
export const defaults=Object.freeze({rows:5,columns:6,orientation:'portrait',layout:'east-west',azimuth:90,tilt:12,height:1,gap:.02,ridgeGap:.3,moduleLength:2.4,moduleWidth:1.2,moduleW:650,series:30,stringsPerInverter:24,invertersPerBlock:24,targetMW:1000,boxLayout:'unknown',boxU:.5,boxV:.5,heightMode:'tilt',upperHeight:5,supportBays:2,structure:'braced'});
export function validate(input){
if(!input||typeof input!=='object'||Array.isArray(input))throw Error('Expected numeric layout settings');
for(const k of Object.keys(input))if(!Object.hasOwn(defaults,k))throw Error('Unknown setting: '+k);
const s={...defaults,...input};
const limits={rows:[1,10],columns:[1,300],azimuth:[0,360],tilt:[0,60],height:[.1,20],upperHeight:[.1,20],supportBays:[1,20],gap:[0,.2],ridgeGap:[0,3],moduleLength:[.1,4],moduleWidth:[.1,3],moduleW:[1,1500],series:[1,60],stringsPerInverter:[1,100],invertersPerBlock:[1,100],targetMW:[.001,10000],boxU:[0,1],boxV:[0,1]};
for(const[k,[lo,hi]]of Object.entries(limits))if(typeof s[k]!=='number'||!Number.isFinite(s[k])||s[k]<lo||s[k]>hi)throw Error(k+' is outside its supported range');
for(const k of ['supportBays','rows','columns','series','stringsPerInverter','invertersPerBlock'])if(!Number.isInteger(s[k]))throw Error(k+' must be a whole number');
if(!['portrait','landscape'].includes(s.orientation)||!['fixed','east-west'].includes(s.layout)||!['unknown','one','two','three'].includes(s.boxLayout))throw Error('Unknown layout');
if(!['tilt','edges'].includes(s.heightMode)||!['none','posts','braced'].includes(s.structure))throw Error('Unknown height or support mode');
const run=s.rows*(s.orientation==='portrait'?s.moduleLength:s.moduleWidth)+(s.rows-1)*s.gap;
if(s.heightMode==='edges'){const rise=s.upperHeight-s.height;if(rise<0||rise>run*Math.sin(Math.PI/3)+1e-10)throw Error('Upper edge must be above lower edge and reachable with this table at 0?60 degrees');s.tilt=Math.asin(Math.min(1,rise/run))*180/Math.PI;}else s.upperHeight=s.height+run*Math.sin(s.tilt*Math.PI/180);
if(s.upperHeight>20+1e-10)throw Error('Upper edge exceeds 20 m; reduce tilt or lower edge');
return s;
}
const rad=x=>x*Math.PI/180;
export function basis(azimuth,tilt){const a=rad(azimuth),t=rad(tilt);return {u:[Math.cos(a),-Math.sin(a),0],v:[-Math.sin(a)*Math.cos(t),-Math.cos(a)*Math.cos(t),Math.sin(t)],normal:[Math.sin(a)*Math.sin(t),Math.cos(a)*Math.sin(t),Math.cos(t)]};}
export function point(origin,u,v,x,y){return origin.map((p,i)=>p+u[i]*x+v[i]*y);}
export function array(supplied){
const s=validate(supplied),length=s.orientation==='portrait'?s.moduleLength:s.moduleWidth,width=s.orientation==='portrait'?s.moduleWidth:s.moduleLength;
const run=s.rows*length+(s.rows-1)*s.gap,span=s.columns*width+(s.columns-1)*s.gap;
const directions=s.layout==='east-west'?[s.azimuth,(s.azimuth+180)%360]:[s.azimuth];const modules=[],structure=[];
for(const [wing,az]of directions.entries()){
const {u,v,normal}=basis(az,s.tilt),a=rad(az),projected=run*Math.cos(rad(s.tilt));
const origin=s.layout==='east-west'?[Math.sin(a)*(projected+s.ridgeGap/2),Math.cos(a)*(projected+s.ridgeGap/2),s.height]:[0,0,s.height];
if(s.structure!=='none'){
const low=[],high=[],ground=p=>[p[0],p[1],0],add=(kind,a,b)=>structure.push({kind,wing,points:[a,b]});
for(let bay=0;bay<=s.supportBays;bay++){const x=-span/2+bay*span/s.supportBays,l=point(origin,u,v,x,0),h=point(origin,u,v,x,run);low.push(l);high.push(h);add('post',ground(l),l);add('post',ground(h),h);add('rafter',l,h);}
add('rail',low[0],low.at(-1));add('rail',high[0],high.at(-1));
if(s.structure==='braced')for(let bay=0;bay<s.supportBays;bay++)for(const line of [low,high]){add('brace',ground(line[bay]),line[bay+1]);add('brace',ground(line[bay+1]),line[bay]);}
}
for(let row=0;row<s.rows;row++)for(let col=0;col<s.columns;col++){
const x=col*(width+s.gap)-span/2,y=row*(length+s.gap);
const corners=[[0,0],[width,0],[width,length],[0,length]].map(([dx,dy])=>point(origin,u,v,x+dx,y+dy));
const count={unknown:0,one:1,two:2,three:3}[s.boxLayout];
// Normalised box positions are user settings, not manufacturer-approved coordinates.
const boxes=Array.from({length:count},(_,k)=>{const across=count===1?s.boxU:Math.max(0,Math.min(1,s.boxU+(k-(count-1)/2)*.28));const dx=s.orientation==='portrait'?width*across:width*s.boxV,dy=s.orientation==='portrait'?length*s.boxV:length*across;return point(origin,u,v,x+dx,y+dy);});
modules.push({id:modules.length+1,wing,row:row+1,column:col+1,corners,boxes,normal});
}
}
return {modules,structure,span,run,rise:run*Math.sin(rad(s.tilt)),projectedRun:run*Math.cos(rad(s.tilt)),height:s.height,settings:s};
}
export function plant(supplied){
const s=validate(supplied),strings=Math.ceil(s.targetMW*1e6/(s.moduleW*s.series)),modules=strings*s.series,inverters=Math.ceil(strings/s.stringsPerInverter),blocks=Math.ceil(inverters/s.invertersPerBlock);
return {targetDCMW:s.targetMW,actualDCMW:modules*s.moduleW/1e6,modules,strings,inverters,blocks,lastInverterStrings:strings-(inverters-1)*s.stringsPerInverter,lastBlockInverters:inverters-(blocks-1)*s.invertersPerBlock};
}Kuiper Drawing Engine — Index Page
A web page that reads inputs for array index, rows and columns (units: MW). Published at https://ventusltd.github.io/kuiper-drawing-engine/web/.
renderkuiper-drawing-engine / web/index.html · lines 1–14 of 14 · Entry point
- What it does
- It draws its content. Uses libraries style.css. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: user-supplied file (file picker); form fields (user input). Out: web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/kuiper-drawing-engine/web/.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- kuiper-drawing-engine · web · page
- Uses
- Kuiper Drawing Engine — App (script src), style.css
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 web/index.html:1-14 · blob dc0e7d1bac515d123af0daf88004f99d10d132b8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Array layout</title><link rel="icon" href="data:,"><link rel="stylesheet" href="style.css"><script type="module" src="app.mjs"></script></head><body>
<canvas id="drawing" aria-label="Interactive solar array wireframe"></canvas>
<header><button id="menu" aria-expanded="true">Settings</button><strong>Array layout</strong><button id="fit">Fit</button><button id="plan">Plan</button><button id="three">3D</button><button id="site">Plant</button><button id="move">Move array</button><button id="full">Full screen</button><a href="https://globalgrid2050.com/ventus/wiring/inverter-48.html">24-string inverter</a></header>
<aside id="settings"><div class="presets" aria-label="Layout presets"><button data-preset="ew">5 portrait · E/W</button><button data-preset="south">1 portrait · S</button><button data-preset="east">1 portrait · E</button><button data-preset="west">1 portrait · W</button></div><label>Array number <input id="arrayIndex" type="number" value="1" min="1"></label><div class="presets" aria-label="Move se … [line shortened here: 665 characters; full line on GitHub]
<label>Modules up slope <input name="rows" type="number" min="1" max="10" value="5"></label><label>Modules along row <input name="columns" type="number" min="1" max="300" value="6"></label>
<label>Arrangement <select name="layout"><option value="east-west">Opposing faces</option><option value="fixed">Single face</option></select></label>
<label>Orientation <select name="orientation"><option>portrait</option><option>landscape</option></select></label>
<label>Facing <select id="direction"><option value="90">East / West</option><option value="180">South</option><option value="270">West</option><option value="0">North</option></select></label>
<label>Set height by <select name="heightMode"><option value="tilt">Lower edge + tilt</option><option value="edges">Lower + upper edges</option></select></label><label>Upper edge m <input name="upperHeight" type="number" min=".1" max="20" step=".1" value="5"></label><label>Tilt ° <input name="tilt" type="number" min="0" max="60" value="12" step=".5"></label><label>Lower edge m <input name="height" … [line shortened here: 461 characters; full line on GitHub]
<details><summary>Support layout</summary><label>Frame <select name="structure"><option value="braced">Braced</option><option value="posts">Posts and rails</option><option value="none">Hide</option></select></label><label>Bays along table <input name="supportBays" type="number" min="1" max="20" value="2"></label><p>Schematic posts and braces follow the table. Steel sections, foundations and struct … [line shortened here: 1,426 characters; full line on GitHub]
<details><summary>Plant quantities</summary><label>Target MW DC <input name="targetMW" type="number" value="1000"></label><label>Modules per string <input name="series" type="number" value="30"></label><label>Strings per inverter <input name="stringsPerInverter" type="number" value="24"></label><label>Inverters per block <input name="invertersPerBlock" type="number" value="24"></label><output id=" … [line shortened here: 524 characters; full line on GitHub]
</form><div class="actions"><button id="save">Save settings</button><label class="load">Load settings<input id="load" type="file" accept="application/json"></label><button id="svg">Export drawing</button></div><p>Drag to rotate · wheel to zoom · right-drag to pan · click a module to inspect.</p></aside>
<footer><span id="summary"></span><span id="selection">Synthetic geometry · metres · editable assumptions</span><span id="error" role="alert"></span></footer>
</body></html>Site
A JavaScript module in Kuiper Drawing Engine that validates placements (`validatePlacements`). Served with the page at https://ventusltd.github.io/kuiper-drawing-engine/web/.
transformkuiper-drawing-engine / web/site.mjs · lines 1–25 of 25 · pattern siteModel (shared by 2 files)
- What it does
- It calculates its inputs. Defines siteModel, tableAt, validatePlacements, overlapsFor.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 2 files: Export Geometry Template (kuiper-drawing-engine); Kuiper Drawing Engine — App (kuiper-drawing-engine, https://ventusltd.github.io/kuiper-drawing-engine/web/). Reached from 2 other entry points, including Kuiper Drawing Engine — Index Page (kuiper-drawing-engine, https://ventusltd.github.io/kuiper-drawing-engine/web/); Array Pages Workflow (kuiper-drawing-engine).
- What it achieves
- It validates placements (`validatePlacements`) and is built from the site model helper (`siteModel`) and the table at helper (`tableAt`). Defines `siteModel`, `tableAt`, `validatePlacements` and 1 more.
- Why it matters
- Imported by Export Geometry Template and Kuiper Drawing Engine — App.
- Application
- kuiper-drawing-engine · web · JavaScript module
- Uses
- Geometry (import)
- Used by
- imported by Export Geometry Template (import), imported by Kuiper Drawing Engine — App (import)
- Produces
- siteModel, tableAt, validatePlacements, overlapsFor
- Defines here
- siteModel, tableAt, validatePlacements, overlapsFor
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 web/site.mjs:1-25 · blob 3b120fe67787b7182785d0ec4a67cc7a1b2b2b9a · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
import {array,plant,validate} from './geometry.mjs';
export function siteModel(input){
const s=validate(input),a=array(s),p=plant(s),points=a.modules.flatMap(m=>m.corners);
const min=[0,1].map(i=>Math.min(...points.map(p=>p[i]))),max=[0,1].map(i=>Math.max(...points.map(p=>p[i])));
const size=max.map((v,i)=>v-min[i]),tables=Math.ceil(p.modules/a.modules.length),columns=Math.ceil(Math.sqrt(tables)),rows=Math.ceil(tables/columns),pitch=size.map(v=>v+3);
return {tables,columns,rows,pitch,size,min,max,modulesPerTable:a.modules.length,modules:p.modules,width:columns*pitch[0],height:rows*pitch[1],groupSize:Math.max(1,Math.ceil(tables/400))};
}
export function tableAt(site,index,edits={}){
if(!Number.isInteger(index)||index<0||index>=site.tables)throw Error('Array index is outside the plant');
const override=edits[index];const x=override?.x??(index%site.columns)*site.pitch[0],y=override?.y??Math.floor(index/site.columns)*site.pitch[1];
return {index,x,y,modules:Math.min(site.modulesPerTable,site.modules-index*site.modulesPerTable)};
}
export function validatePlacements(raw,site){
if(!Array.isArray(raw)||raw.length>10000)throw Error('Too many moved arrays');const result={};
for(const row of raw){if(!row||Object.keys(row).some(k=>!['index','x','y'].includes(k))||!Number.isInteger(row.index)||row.index<0||row.index>=site.tables||!Number.isFinite(row.x)||!Number.isFinite(row.y)||Math.abs(row.x)>1e6||Math.abs(row.y)>1e6||row.index in result)throw Error('Invalid array position');result[row.index]={x:row.x,y:row.y};}
return result;
}
// Axis-aligned bounding-box overlap screening against the regular grid plus moved arrays.
export function overlapsFor(site,index,edits={}){
const a=tableAt(site,index,edits),candidates=new Set(Object.keys(edits).map(Number));
const c0=Math.max(0,Math.ceil((a.x-site.size[0])/site.pitch[0])),c1=Math.min(site.columns-1,Math.floor((a.x+site.size[0])/site.pitch[0]));
const r0=Math.max(0,Math.ceil((a.y-site.size[1])/site.pitch[1])),r1=Math.min(site.rows-1,Math.floor((a.y+site.size[1])/site.pitch[1]));
for(let r=r0;r<=r1;r++)for(let c=c0;c<=c1;c++){const i=r*site.columns+c;if(i<site.tables)candidates.add(i);}
return [...candidates].filter(i=>{if(i===index)return false;const b=tableAt(site,i,edits);return Math.min(a.x+site.size[0],b.x+site.size[0])-Math.max(a.x,b.x)>1e-9&&Math.min(a.y+site.size[1],b.y+site.size[1])-Math.max(a.y,b.y)>1e-9;});
}Elements on Wafer
A Python module in the evidence folder of Neural Link Between Agents.
ingestneural-link-between-agents / FIXES/NL-010/tools/evidence/nl010/team-4/elements_on_wafer.py · lines 1–24 of 24 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Uses libraries json, collections. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file elements.json.
- What it achieves
- Which catalogued elements can be placed on the live wafer at a key of their own? It reads `/home/user/estate/elements/catalogue/elements.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · FIXES/NL-010/tools/evidence/nl010/team-4 · Python module
- Uses
- json, collections
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-010/tools/evidence/nl010/team-4/elements_on_wafer.py:1-24 · blob 31dfb2dd9f7991256deb7aa4cb38546638e67c86 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Which catalogued elements can be placed on the live wafer at a key of their own?
An element is placeable when at least one of its register files names a commit that is a row of
cosmos/wafer.tsv (sha12 match) in a repository the wafer names. Reads only; prints counts."""
import json, collections
E = json.load(open('/home/user/estate/elements/catalogue/elements.json'))
W = [l.rstrip('\n').split('\t') for l in open('/home/user/estate/kuiper-belt/cosmos/wafer.tsv') if l.strip() and l[0] != '#']
R = {int(p[0]): p[1] for p in (l.rstrip('\n').split('\t') for l in open('/home/user/estate/kuiper-belt/cosmos/repos.tsv') if l.strip() and l[0] != '#')}
sha12 = {w[3]: (R[int(w[2])], int(w[0]), int(w[1])) for w in W}
with_files = [e for e in E if e['files']]
placeable, by_app, commits_used = [], {}, set()
for e in E:
hits = [(f['repo'], f['path'], f['commit']) for f in e['files'] if f['commit'][:12] in sha12]
if hits: placeable.append(e['key']); commits_used.update(h[2][:12] for h in hits)
if e['kind'] == 'app': by_app[e['key']] = (len(e['files']), len(hits), sorted(set(h[2][:7] for h in hits)))
print('elements', len(E), 'with files', len(with_files), 'placeable (a file commit is a wafer row)', len(placeable),
'not placeable', len(E) - len(placeable), 'distinct commits used', len(commits_used))
print('by kind placeable:', collections.Counter(next(x['kind'] for x in E if x['key'] == k) for k in placeable))
print('by kind all:', collections.Counter(e['kind'] for e in E))
print('apps: key -> (files, files on wafer, commits)', by_app)
allc = collections.Counter(f['commit'][:12] in sha12 for e in E for f in e['files'])
print('file rows total/on wafer:', sum(allc.values()), allc[True])
repos_named = collections.Counter(f['repo'].split('/')[-1] for e in E for f in e['files'])
print('repos named by element files:', dict(repos_named))
print('of which not on the wafer:', [r for r in repos_named if r not in set(R.values())])