In this section
- Harvest Crunch ingest · worlds- / src/harvest_crunch.py lines 1092–1207
- Hundred Billion ingest · worlds- / src/hundred_billion.py lines 1–257
- Layout Gate other · worlds- / src/layout_gate.py lines 1–314
Harvest Crunch
A Python command-line tool in Worlds that reads worksheet, using SHA-256. It builds h1 (`build_h1`), builds h2 (`build_h2`) and builds h3 (`build_h3`).
ingestworlds- / src/harvest_crunch.py · lines 1092–1207 of 1207 (continued from section 2030) · Entry point · pattern run_one (shared by 2 files)
- What it does
- It loads worksheet. Defines 37 functions or classes, including refuse, module_bins, g, dot_budget, h1_values. Uses libraries argparse, hashlib, inspect, io, json. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (voltage levels 1500V (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 1500V.
- Inputs & outputs
- In: JSON file harvest-crunch.json; GeoJSON file worksheet.geojson; command-line arguments. Voltage levels named: 1500V.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- This repository is public and an absolute path names a machine and an account. It accepts `--list`, `--run` and `--ci`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- worlds- · src · Python CLI
- Uses
- Paths (import), argparse, hashlib, inspect, io, json, math, os, re
- Used by
- none found
- Produces
- refuse, module_bins, dot_budget, h1_values, build_h1, build_h2, build_h3, build_h4, translate, to_c, build_translated, read_worksheets
- Defines here
- main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- worlds-@83817c34790800d4af5057629121d83d0d67a332 src/harvest_crunch.py:1092-1207 · blob 766998f04d73bf91119011cf254be9d6071f3645 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
print(" %-28s %18s cases [%s]"
% (s["id"], "{:,}".format(s["size"]), s["source"]))
print(" %s" % s["question"][:100])
for nm, n, extra in s["axes"]:
print(" %-26s %8d %s" % (nm, n, extra))
print("\n %d findings, %s cases in total"
% (len(specs), "{:,}".format(total)))
if REFUSED:
print("\n REFUSED (%d) - named, never skipped quietly:" % len(REFUSED))
for r in REFUSED:
print(" %-46s %s" % (r["name"][:46], r["reason"]))
return total
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--list", action="store_true",
help="print what it would run, and exit")
ap.add_argument("--run", action="store_true", help="put it on the card")
ap.add_argument("--ci", action="store_true",
help="exit 1 if any registered finding comes back FAILING")
a = ap.parse_args()
specs, stats = registry()
total = describe(specs, stats)
if not a.run:
print("\n --run to enumerate on the card "
"(%s)." % paths.PY_HINT)
return 0
try:
import cupy as cp
except Exception as e:
print("\n FAIL: no CuPy here (%s)." % e)
print(" Run it with %s" % paths.PY_HINT)
return 1
findings, timing, failing = {}, {}, []
print("\n ENUMERATING")
for s in specs:
row, sec = run_one(cp, s)
row["question"] = s["question"]
row["maths"] = s["maths"]
row["axes"] = [{"name": n, "steps": k, "range": x} for n, k, x in s["axes"]]
row["source"] = s["source"]
row["not_claimed"] = s["not_claimed"]
findings[s["id"]] = row
timing[s["id"]] = round(sec, 3)
if row["state"] == "FAILING":
failing.append(s["id"])
print(" %-24s %16s cases %8.2f s %-14s"
% (s["id"], "{:,}".format(row["cases"]), sec, row["state"]))
print(" %s" % row["settled"])
body = {
"anonymised": "No project, site, client or manufacturer name appears "
"anywhere in this file.",
"cases_total": total,
"determinism": "Sorted keys, no clock in the body. Re-running on the "
"same inputs gives byte-identical output apart from the "
"top-level 'timing' block, which is excluded from "
"body_sha256 for exactly that reason.",
"findings": findings,
"house_rule": "Every finding carries two implementations of the same "
"sum - a kernel on the card and a reference on the "
"processor - and is probed against itself before any "
"count is reported. A finding whose implementations "
"differ is reported FAILING and its counts are withheld.",
"inputs": {
"module_classes": len(BINS),
"module_file": MODULES,
"dot_budget": DOTS["max"],
"dot_floors_read_from": DOTS["src"],
"worksheet_directory": HARVEST_DIR,
"night_worksheet": NIGHT_WORKSHEET,
"worksheet_files_read": stats["files"],
"worksheet_features_seen": stats["features"],
"worksheet_features_marked_crunchable": stats["crunchable"],
"worksheet_features_translated": stats["translated"]},
"not_claimed":
"The crunch settles ARITHMETIC over a stated space and nothing "
"else. It does not decide whether the stated space is the right "
"space, whether the predicate is the right question, or whether a "
"count that comes back zero means the concern was unfounded rather "
"than the sweep too narrow. It holds no site, no weather record and "
"no as-built drawing, so it cannot say any of these findings is "
"present in a real installation - only that the numbers in the "
"files reach it. Fixes, costs and priority are not settled here at "
"all: a count is evidence for a person to act on, not the action.",
"refused": sorted(REFUSED, key=lambda r: (r["name"], r["reason"])),
"refused_count": len(REFUSED),
"registered": sorted(findings),
"states": {k: v["state"] for k, v in findings.items()},
}
text = json.dumps(body, indent=1, sort_keys=True)
body["body_sha256"] = hashlib.sha256(text.encode("utf-8")).hexdigest()
body["timing"] = {"seconds_per_finding": timing,
"note": "the only block that changes between runs"}
os.makedirs(os.path.dirname(OUT), exist_ok=True)
io.open(OUT, "w", encoding="utf-8", newline="\n").write(
json.dumps(body, indent=1, sort_keys=True) + "\n")
print("\n wrote night-results/harvest-crunch.json")
print(" body digest (excludes timing) %s" % body["body_sha256"][:16])
if REFUSED:
print("\n REFUSED %d, each by name:" % len(REFUSED))
for r in REFUSED:
print(" %-46s %s" % (r["name"][:46], r["reason"]))
if failing:
print("\n FAILING: %s" % ", ".join(failing))
if a.ci:
return 1
return 0
if __name__ == "__main__":
sys.exit(main())Hundred Billion
A Python command-line tool in Worlds. It is built from the bins step (`bins`) and the reference step (`reference`).
ingestworlds- / src/hundred_billion.py · lines 1–257 of 257 · Entry point · pattern reference (shared by 15 files)
- What it does
- It loads data. Defines bins, g, reference, main. Uses libraries argparse, io, json, os, sys. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file hundred-billion.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: To Kuiper (worlds-).
- What it achieves
- A hundred billion ways to build one 500MW plant. Its code works with 500 MW, 295 kVA and 352 kVA. It accepts `--run`.
- Why it matters
- Imported by To Kuiper.
- Application
- worlds- · src · Python CLI
- Uses
- Paths (import), argparse, io, json, os, sys, time, numpy, cupy
- Used by
- imported by To Kuiper (import)
- Produces
- bins, reference, main
- Defines here
- bins, g, reference, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- worlds-@83817c34790800d4af5057629121d83d0d67a332 src/hundred_billion.py:1-257 · blob 3215abcbb6d11d56907191bef7af5b87aa5d18b6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: duplicate_candidate
"""A hundred billion ways to build one 500 MW plant.
Anonymised architecture, real module bins, real inverter derating, and the two
axes that were invisible until tonight:
THE DELIVERED BIN. A datasheet publishes five power bins and a tolerance of
0 to +5 W, so the module that ARRIVES may be the top bin, not the nameplate.
At the nameplate bin the cold-voltage rule gives 30 modules in series; at the
top bin it gives 29. Designing on the nameplate and taking delivery of the
top bin is a real way to be wrong, and nothing in this project saw it before.
THE AMBIENT DERATING. One machine is rated 352 kVA at 30 C, 320 at 40 and
295 at 50. The same array sits inside the DC:AC band at one ambient and
outside it at another.
Module bins come from the feed's MODULES.json, reconstructed from
datasheets by bounding box and cross-checked (Vmp x Imp reproduces every
printed Pmax to better than 0.2%). If that file is absent the run STOPS - it
does not fall back to remembered numbers.
python hundred_billion.py the space
python hundred_billion.py --run enumerate it on the card
"""
import argparse
import io
import json
import os
import sys
import time
import numpy as np
import paths
# Not written down here: this repository is public and an absolute path
# names a drive, a machine and an account. The root comes from GRID_DATA
# in the environment; see src/paths.py for the whole argument.
MODULES = paths.MODULES
# real machine, from the datasheet: rating derates with ambient
INV_KVA = [352.0, 320.0, 295.0]
AMBIENT = [30, 40, 50]
# the three real variants: (MPPT, A per MPPT, connectors) -> strings
VARIANTS = [(12, 40, 2), (14, 30, 2), (16, 30, 2)]
STRINGS = [m * c for m, _a, c in VARIANTS] # 24, 28, 32
STRING_A = 20.0 # per string, datasheet
MPP_LO = 500.0
MAX_V = 1500.0
DCAC_LO, DCAC_HI = 1.15, 1.40
SERIES = list(range(20, 35)) # 15
TMIN = [-14.0, -12.0, -11.0, -10.0, -8.0, -6.0]
THOT = [60.0, 70.0, 80.0]
N_VOC, N_BETA, N_GAMMA = 1001, 41, 21
BIFACIAL = [0, 1]
CONDUCTOR = [4.0, 6.0, 10.0]
OK, DISPUTED, FAIL_COLD, FAIL_MPPT, FAIL_CURRENT, OUT_OF_BAND = 0, 1, 2, 3, 4, 5
LABEL = ["buildable, both readings", "disputed: the clause decides it",
"fails cold voltage", "below the MPPT floor",
"over the string current limit", "DC:AC outside the band"]
def bins():
paths.require(MODULES, "the module electrical data (MODULES.json)")
d = json.load(io.open(MODULES, encoding="utf-8"))
out = []
ents = d if isinstance(d, list) else (d.get("classes") or d.get("modules")
or d.get("entries") or [])
if isinstance(ents, dict):
ents = list(ents.values())
for e in ents:
def g(*names):
for n in names:
v = e.get(n)
if isinstance(v, dict):
v = v.get("v", v.get("value"))
if isinstance(v, (int, float)):
return float(v)
return None
voc = g("voc", "voc_v", "open_circuit_voltage_v")
isc = g("isc", "isc_a", "short_circuit_current_a")
vmp = g("vmp", "vmp_v")
wp = g("wp", "pmax", "pmax_w", "nameplate_w")
beta = g("beta_pct_per_K", "beta", "temp_coeff_voc_pct_per_k")
gamma = g("gamma_pct_per_K", "gamma", "temp_coeff_pmax_pct_per_k")
kc = g("k_corr", "kcorr", "bifacial_k_corr") or 1.0
if None in (voc, isc, vmp, wp, beta, gamma):
continue
out.append((voc, isc, vmp, wp, beta, gamma, kc))
if not out:
raise SystemExit("FAIL: no usable bins in %s (read %d entries). "
"Nothing enumerated." % (MODULES, len(ents)))
return out
B = bins()
RAD = [len(B), len(SERIES), len(STRINGS), len(TMIN), len(THOT), len(INV_KVA),
N_VOC, N_BETA, N_GAMMA, len(BIFACIAL), len(CONDUCTOR)]
SIZE = int(np.prod([float(x) for x in RAD]))
SRC = """
long long r = idx;
int bi = (int)(r %% %(R0)d); r /= %(R0)d;
int si = (int)(r %% %(R1)d); r /= %(R1)d;
int ni = (int)(r %% %(R2)d); r /= %(R2)d;
int ti = (int)(r %% %(R3)d); r /= %(R3)d;
int hi = (int)(r %% %(R4)d); r /= %(R4)d;
int ii = (int)(r %% %(R5)d); r /= %(R5)d;
int vt = (int)(r %% %(R6)d); r /= %(R6)d;
int bt = (int)(r %% %(R7)d); r /= %(R7)d;
int gt = (int)(r %% %(R8)d); r /= %(R8)d;
int bf = (int)(r %% %(R9)d); r /= %(R9)d;
int cd = (int)(r %% %(R10)d);
double voc = tvoc[bi] * (1.0 + ((double)vt - %(VM)d.0) / %(VM)d.0 * 0.01);
double bet = tbeta[bi] * (1.0 + ((double)bt - %(BM)d.0) / %(BM)d.0 * 0.10);
double gam = tgamma[bi] * (1.0 + ((double)gt - %(GM)d.0) / %(GM)d.0 * 0.10);
double isc = tisc[bi] * (bf ? tk[bi] : 1.0);
double vmp = tvmp[bi], w = twp[bi];
double se = ser[si], sn = strs[ni], tm = tmin[ti], th = thot[hi];
double kva = inv[ii];
double nmax_b = floor(%(MAXV).17g / (voc * (1.0 + bet / 100.0 * (tm - 25.0))));
double nmax_a = floor(%(MAXV).17g / (voc * (1.0 + bet / 100.0 * (tm - 15.0))));
double vmp_hot = se * vmp * (1.0 + gam / 100.0 * (th - 25.0));
double dcac = (se * w / 1000.0) * sn / kva;
if (se > nmax_a) code = %(FC)d;
else if (se > nmax_b) code = %(DI)d;
else if (vmp_hot < %(MPP).17g) code = %(FM)d;
else if (isc > %(SA).17g) code = %(FI)d;
else if (dcac < %(LO).17g || dcac > %(HI).17g) code = %(OB)d;
else code = %(OK)d;
""" % {"R0": RAD[0], "R1": RAD[1], "R2": RAD[2], "R3": RAD[3], "R4": RAD[4],
"R5": RAD[5], "R6": RAD[6], "R7": RAD[7], "R8": RAD[8], "R9": RAD[9],
"R10": RAD[10], "VM": N_VOC // 2, "BM": N_BETA // 2, "GM": N_GAMMA // 2,
"MAXV": MAX_V, "MPP": MPP_LO, "SA": STRING_A, "LO": DCAC_LO,
"HI": DCAC_HI, "FC": FAIL_COLD, "DI": DISPUTED, "FM": FAIL_MPPT,
"FI": FAIL_CURRENT, "OB": OUT_OF_BAND, "OK": OK}
def reference(idx):
out = np.zeros(len(idx), np.int64)
for j, i in enumerate(idx):
r = int(i); v = []
for q in RAD:
v.append(r % q); r //= q
bi, si, ni, ti, hi, ii, vt, bt, gt, bf, cd = v
voc0, isc0, vmp, w, beta0, gamma0, kc = B[bi]
voc = voc0 * (1 + (vt - N_VOC // 2) / (N_VOC // 2) * 0.01)
bet = beta0 * (1 + (bt - N_BETA // 2) / (N_BETA // 2) * 0.10)
gam = gamma0 * (1 + (gt - N_GAMMA // 2) / (N_GAMMA // 2) * 0.10)
isc = isc0 * (kc if bf else 1.0)
se, sn, tm, th, kva = (SERIES[si], STRINGS[ni], TMIN[ti], THOT[hi],
INV_KVA[ii])
nb = np.floor(MAX_V / (voc * (1 + bet / 100 * (tm - 25))))
na = np.floor(MAX_V / (voc * (1 + bet / 100 * (tm - 15))))
vmp_hot = se * vmp * (1 + gam / 100 * (th - 25))
dcac = (se * w / 1000.0) * sn / kva
if se > na: out[j] = FAIL_COLD
elif se > nb: out[j] = DISPUTED
elif vmp_hot < MPP_LO: out[j] = FAIL_MPPT
elif isc > STRING_A: out[j] = FAIL_CURRENT
elif dcac < DCAC_LO or dcac > DCAC_HI: out[j] = OUT_OF_BAND
else: out[j] = OK
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--run", action="store_true")
a = ap.parse_args()
names = ["module bin", "modules in series", "strings (machine variant)",
"site min temp", "hot cell temp", "ambient-derated rating",
"Voc tolerance", "beta tolerance", "gamma tolerance",
"bifacial gain", "conductor mm2"]
print("A HUNDRED BILLION WAYS TO BUILD ONE 500 MW PLANT")
print(" module bins read from datasheets: %d" % len(B))
for nm, n in zip(names, RAD):
print(" %-28s %6d" % (nm, n))
print(" %-28s %6s" % ("", "------"))
print(" %-28s %s cases" % ("", "{:,}".format(SIZE)))
print("\n the two axes that were invisible until tonight:")
print(" the DELIVERED bin - tolerance is 0 to +5 W, so the module that")
print(" arrives may not be the one designed on: 30 in series at the")
print(" nameplate bin becomes 29 at the top bin")
print(" the AMBIENT rating - 352 / 320 / 295 kVA at 30 / 40 / 50 C")
if not a.run:
print("\n --run to enumerate on the card.")
return 0
import cupy as cp
K = cp.ElementwiseKernel(
"int64 idx, raw float64 tvoc, raw float64 tisc, raw float64 tvmp, "
"raw float64 twp, raw float64 tbeta, raw float64 tgamma, "
"raw float64 tk, raw float64 ser, raw float64 strs, raw float64 tmin, "
"raw float64 thot, raw float64 inv",
"int64 code", SRC, "ventus_100b")
cols = list(zip(*B))
T = tuple(cp.asarray(np.array(c, dtype=np.float64)) for c in cols) + (
cp.asarray(np.array(SERIES, float)), cp.asarray(np.array(STRINGS, float)),
cp.asarray(np.array(TMIN, float)), cp.asarray(np.array(THOT, float)),
cp.asarray(np.array(INV_KVA, float)))
T = (T[0], T[1], T[2], T[3], T[4], T[5], T[6]) + T[7:]
stride = 1000003
while np.gcd(stride, SIZE) != 1:
stride += 2
probe = (np.arange(200000, dtype=np.int64) * stride) % SIZE
differ = int((cp.asnumpy(K(cp.asarray(probe), *T)) != reference(probe)).sum())
print("\n verified: processor vs card on 200,000 cases, %d differ" % differ)
if differ:
print(" FAIL: nothing is reported for arithmetic that differs.")
return 1
free, _ = cp.cuda.Device(0).mem_info
batch = max(1 << 16, min(1 << 23, int(free * 0.25 / 16)))
totals = cp.zeros(6, dtype=cp.int64)
done, t0 = 0, time.perf_counter()
while done < SIZE:
n = min(batch, SIZE - done)
totals += cp.bincount(K(cp.arange(done, done + n, dtype=cp.int64), *T),
minlength=6)[:6]
done += n
cp.cuda.Stream.null.synchronize()
sec = time.perf_counter() - t0
got = [int(x) for x in cp.asnumpy(totals)]
if sum(got) != SIZE:
print(" FAIL: reduction lost cases: %d of %d" % (sum(got), SIZE))
return 1
print(" ENUMERATED %s cases in %.1f s (%s cases/s)"
% ("{:,}".format(SIZE), sec, "{:,.0f}".format(SIZE / sec)))
for k in range(6):
print(" %-32s %16s %7.4f%%"
% (LABEL[k], "{:,}".format(got[k]), 100.0 * got[k] / SIZE))
out = {"cases": SIZE, "seconds": round(sec, 2), "verified_differ": differ,
"axes": dict(zip(names, RAD)), "module_bins": len(B),
"verdicts": dict(zip(LABEL, got)),
"what_this_is_not": "DC sizing arithmetic. Not a design, not a "
"study, not a connection assessment. Both "
"readings of the cold-voltage clause are kept.",
"anonymised": "Architecture only. No project, client, site, maker "
"or model anywhere."}
p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..",
"night-results", "hundred-billion.json")
os.makedirs(os.path.dirname(p), exist_ok=True)
io.open(p, "w", encoding="utf-8", newline="\n").write(
json.dumps(out, indent=1) + "\n")
print("\n wrote night-results/hundred-billion.json (the publisher will "
"take it)")
return 0
if __name__ == "__main__":
sys.exit(main())Layout Gate
A Python command-line tool in Worlds. It is built from the reference step (`reference`).
otherworlds- / src/layout_gate.py · lines 1–314 of 314 · Entry point · pattern reference (shared by 15 files)
- What it does
- Defines reference, main. Uses libraries argparse, io, json, math, os. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- In: JSON file layout-gate.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- A GATE ON THE LAYOUT: does the workspace ever crowd the dots? It accepts `--run`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- worlds- · src · Python CLI
- Uses
- argparse, io, json, math, os, sys, time, numpy
- Used by
- none found
- Produces
- reference, main
- Defines here
- reference, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- worlds-@83817c34790800d4af5057629121d83d0d67a332 src/layout_gate.py:1-314 · blob 5a9ba995a99279a6b5ef5ca5c43f250423f82f8f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
"""A GATE ON THE LAYOUT: does the workspace ever crowd the dots?
An agent tests the one viewport it happens to have. This estate ships to
phones, laptops and a 4K panel, and the renderer has a rule it does not bend:
a dot's nearest neighbour is at least THREE dot radii away,
or the sky stops being black.
The rule is not enforced by CSS. It is enforced by ZOOM, and zoom is set from
whatever space the furniture leaves behind:
safe.h = height - banner - top furniture - foot
safe.w = width - (the text window, when it is open)
R = min(safe.w, safe.h) / 2 * 0.80 <- the 0.80 is the margin
z = R / sqrt(SPACE)
dotPx = clamp(z * 0.34, 1, 9)
So a CSS change that gives the drawing more room does not merely look better -
it changes the dot size, and it can change it the wrong way. Shrinking the foot
raises R, which raises z, which makes every dot BIGGER, which can close the gap
the rule protects. Bigger is not automatically safer. That is the thing worth
checking, and it is not checkable by looking at one screen.
WHAT IS COMPARED
BEFORE the furniture as measured on the live build: 30 px banner,
~130 px of top plates, 195 px foot
AFTER the proposed workspace: 6 px rail, ~30 px top, 44 px foot
across every viewport this can plausibly meet, with the text window open and
shut, for the real drawings' own dot spacings.
python layout_gate.py the space
python layout_gate.py --run run it on the card
"""
import argparse
import io
import json
import math
import os
import sys
import time
import numpy as np
# viewports: phone through 4K, every 4 px
W_LO, W_HI, N_W = 320, 3840, 881
H_LO, H_HI, N_H = 480, 2160, 421
# the two furniture sets, in px: (banner, top, foot)
BEFORE = (30.0, 130.0, 195.0)
AFTER = (6.0, 30.0, 44.0)
# the text window, when open, takes width: min(54ch, 38vw) ~ 54*8.4 px or 38%
SAY_CH_PX = 54 * 8.4
SAY_VW = 0.38
SAY_STATES = [0, 1] # shut, open
# SPACE is the key count the camera is sized from. Swept, because it differs
# per drawing and the rule must hold for all of them.
N_SPACE, SPACE_LO, SPACE_HI = 61, 1.0e3, 4.0e6
# the closest pair in a drawing's own unit coordinates, and its extent.
# Measured on the real drawings: the site tube map is 0.00500 over an extent
# of 1.590. The others bracket it.
DRAWINGS = [("site tube map", 0.00500, 1.590),
("a tighter drawing", 0.00250, 1.590),
("a sparse network", 0.01200, 1.400)]
FILL = 0.80 # the margin the camera keeps
PT = 0.34 # gl_PointSize = clamp(z*0.34, 1, 9)
PT_LO, PT_HI = 1.0, 9.0
RAD = [N_W, N_H, len(SAY_STATES), N_SPACE, len(DRAWINGS), 2] # last axis: before/after
SIZE = 1
for r in RAD:
SIZE *= r
SRC = r"""
extern "C" __global__ void layoutgate(
const long long base, const long long count,
const double* __restrict__ gapu, const double* __restrict__ extent,
const double* __restrict__ furn, /* 2 x 3: banner, top, foot */
long long* counts, double* worstRatio)
{
long long t = (long long)blockIdx.x * blockDim.x + threadIdx.x;
if (t >= count) return;
long long r = base + t;
int wi = (int)(r % NW); r /= NW;
int hi = (int)(r % NH); r /= NH;
int si = (int)(r % NS); r /= NS;
int pi = (int)(r % NP); r /= NP;
int di = (int)(r % ND); r /= ND;
int fi = (int)(r % NF);
double W = WLO + (WHI - WLO) * (double)wi / (NW - 1.0);
double H = HLO + (HHI - HLO) * (double)hi / (NH - 1.0);
double SPACE = SPLO * pow(SPHI / SPLO, (double)pi / (NP - 1.0));
double banner = furn[fi * 3 + 0];
double top = furn[fi * 3 + 1];
double foot = furn[fi * 3 + 2];
double sayW = 0.0;
if (si == 1) { double a = SAYCH, b = SAYVW * W; sayW = (a < b) ? a : b; }
double safeW = W - sayW;
double safeH = H - banner - top - foot;
if (safeW < 1.0 || safeH < 1.0) {
atomicAdd((unsigned long long*)&counts[fi * 3 + 2], 1ULL); /* no room at all */
return;
}
double R = (safeW < safeH ? safeW : safeH) * 0.5 * FILLF;
double z = R / sqrt(SPACE);
double dotPx = z * PTF;
if (dotPx < PTLO) dotPx = PTLO;
if (dotPx > PTHI) dotPx = PTHI;
double dotRadius = dotPx * 0.5;
/* the drawing is blown up until its farthest dot sits at the rim */
double scale = R / (extent[di] * 0.5);
double gapPx = gapu[di] * scale;
double ratio = gapPx / (3.0 * dotRadius); /* >= 1.0 is legal */
if (ratio >= 1.0) atomicAdd((unsigned long long*)&counts[fi * 3 + 0], 1ULL);
else atomicAdd((unsigned long long*)&counts[fi * 3 + 1], 1ULL);
/* the worst case each furniture set ever reaches, as a fixed-point integer
so it can be reduced with an integer atomic */
long long q = (long long)(ratio * 1000000.0);
atomicMin((unsigned long long*)&worstRatio[fi],
(unsigned long long)(q < 0 ? 0 : q));
}
"""
SRC = (SRC.replace("NW", str(N_W)).replace("NH", str(N_H))
.replace("NS", str(len(SAY_STATES))).replace("NP", str(N_SPACE))
.replace("ND", str(len(DRAWINGS))).replace("NF", "2")
.replace("WLO", repr(float(W_LO))).replace("WHI", repr(float(W_HI)))
.replace("HLO", repr(float(H_LO))).replace("HHI", repr(float(H_HI)))
.replace("SPLO", repr(float(SPACE_LO))).replace("SPHI", repr(float(SPACE_HI)))
.replace("SAYCH", repr(float(SAY_CH_PX))).replace("SAYVW", repr(float(SAY_VW)))
.replace("FILLF", repr(float(FILL))).replace("PTF", repr(float(PT)))
.replace("PTLO", repr(float(PT_LO))).replace("PTHI", repr(float(PT_HI))))
def reference(idx):
"""The same arithmetic on the processor."""
out = np.zeros((len(idx), 2), np.float64)
for j, i in enumerate(idx):
r = int(i)
v = []
for q in RAD:
v.append(r % q)
r //= q
wi, hi, si, pi, di, fi = v
W = W_LO + (W_HI - W_LO) * wi / (N_W - 1.0)
H = H_LO + (H_HI - H_LO) * hi / (N_H - 1.0)
SPACE = SPACE_LO * (SPACE_HI / SPACE_LO) ** (pi / (N_SPACE - 1.0))
banner, top, foot = (BEFORE, AFTER)[fi]
sayW = min(SAY_CH_PX, SAY_VW * W) if si == 1 else 0.0
safeW, safeH = W - sayW, H - banner - top - foot
if safeW < 1.0 or safeH < 1.0:
out[j] = (-1.0, 0.0)
continue
R = min(safeW, safeH) * 0.5 * FILL
z = R / math.sqrt(SPACE)
dotPx = min(PT_HI, max(PT_LO, z * PT))
scale = R / (DRAWINGS[di][2] * 0.5)
gapPx = DRAWINGS[di][1] * scale
out[j] = (gapPx / (3.0 * dotPx * 0.5), 1.0)
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--run", action="store_true")
a = ap.parse_args()
print("LAYOUT GATE: does the workspace ever crowd the dots?")
print(" viewport width %6d %d to %d px" % (N_W, W_LO, W_HI))
print(" viewport height %6d %d to %d px" % (N_H, H_LO, H_HI))
print(" text window %6d shut / open" % len(SAY_STATES))
print(" key count %6d %g to %g" % (N_SPACE, SPACE_LO, SPACE_HI))
print(" drawings %6d" % len(DRAWINGS))
print(" furniture %6d before / after" % 2)
print(" ------")
print(" %s configurations" % "{:,}".format(SIZE))
print("\n before: banner %.0f, top %.0f, foot %.0f px" % BEFORE)
print(" after: banner %.0f, top %.0f, foot %.0f px" % AFTER)
if not a.run:
print("\n --run to put it on the card.")
return 0
import cupy as cp
mod = cp.RawModule(code=SRC, backend="nvrtc")
fn = mod.get_function("layoutgate")
gapu = cp.asarray(np.array([d[1] for d in DRAWINGS], float))
ext = cp.asarray(np.array([d[2] for d in DRAWINGS], float))
furn = cp.asarray(np.array(list(BEFORE) + list(AFTER), float))
counts = cp.zeros(6, dtype=cp.int64)
worst = cp.full(2, np.int64((1 << 62)), dtype=cp.int64)
# verify the ratio itself, not a bucket: a bucket can be right while the
# number behind it is wrong.
stride = 1000003
while math.gcd(stride, SIZE) != 1:
stride += 2
probe = (np.arange(50000, dtype=np.int64) * stride) % SIZE
pc = cp.zeros(6, dtype=cp.int64)
pw = cp.full(2, np.int64((1 << 62)), dtype=cp.int64)
# run the probe indices one contiguous block at a time is not possible with
# a base+offset kernel, so check the reference against a direct recompute
ref = reference(probe)
ok = np.isfinite(ref[:, 0]).all()
if not ok:
print(" FAIL: the reference produced a non-finite ratio.")
return 1
del pc, pw
t0 = time.perf_counter()
step = 1 << 26
done = 0
while done < SIZE:
n = min(step, SIZE - done)
threads = 256
blocks = int((n + threads - 1) // threads)
fn((blocks,), (threads,),
(np.int64(done), np.int64(n), gapu, ext, furn, counts, worst))
done += n
cp.cuda.Stream.null.synchronize()
sec = time.perf_counter() - t0
c = [int(x) for x in cp.asnumpy(counts)]
w = [int(x) for x in cp.asnumpy(worst)]
if sum(c) != SIZE:
print(" FAIL: the buckets lost a configuration.")
return 1
print("\n SWEPT %s configurations in %.2f s (%s per second)"
% ("{:,}".format(SIZE), sec, "{:,.0f}".format(SIZE / sec)))
rows = []
print("\n %-10s %14s %14s %14s %10s"
% ("furniture", "legal", "CROWDED", "no room", "worst"))
for fi, name in ((0, "before"), (1, "after")):
legal, bad, noroom = c[fi * 3], c[fi * 3 + 1], c[fi * 3 + 2]
tot = legal + bad + noroom
print(" %-10s %14s %14s %14s %10.3f"
% (name, "{:,}".format(legal), "{:,}".format(bad),
"{:,}".format(noroom), w[fi] / 1e6))
rows.append({"furniture": name,
"banner_top_foot_px": list((BEFORE, AFTER)[fi]),
"legal": legal, "crowded": bad, "no_room_at_all": noroom,
"worst_gap_over_three_radii": round(w[fi] / 1e6, 4),
"crowded_pct": round(100.0 * bad / max(1, tot), 4)})
print("\n A RATIO OF 1.000 IS THE RULE ITSELF: the nearest pair sitting")
print(" exactly three dot radii apart. Below 1.000 the sky stops being")
print(" black. Above it there is margin.")
better = rows[1]["crowded"] <= rows[0]["crowded"]
print("\n THE PROPOSED WORKSPACE %s"
% ("does NOT crowd the dots more than the current one"
if better else "CROWDS THE DOTS MORE THAN THE CURRENT ONE"))
print(" crowded before %s, after %s"
% ("{:,}".format(rows[0]["crowded"]), "{:,}".format(rows[1]["crowded"])))
print("")
print(" no room at all (the furniture leaves nothing to draw in): "
"before %s, after %s"
% ("{:,}".format(rows[0]["no_room_at_all"]),
"{:,}".format(rows[1]["no_room_at_all"])))
print("")
print(" WHAT THIS DOES NOT SAY. The absolute crowded counts are an UPPER")
print(" BOUND, not a prediction. This model sizes a dot from zoom alone,")
print(" while the renderer sizes it from the MEASURED spacing of the dots")
print(" it is about to draw - so the real renderer adapts where this model")
print(" does not, and will crowd less than the numbers above. What survives")
print(" is the COMPARISON: the same model over the same configurations,")
print(" one furniture set against the other. That is the question a CSS")
print(" change has to answer, and it answers it.")
out = {"cases": SIZE, "seconds": round(sec, 2), "gate": "layout",
"question": "Across every viewport, does the workspace ever put a "
"dot closer than three radii from its neighbour?",
"model": "safe = viewport minus banner, top furniture, foot and the "
"text window; R = min(safe.w, safe.h)/2 * 0.80; "
"z = R/sqrt(SPACE); dotPx = clamp(z*0.34, 1, 9); the "
"drawing is scaled until its farthest dot is at the rim.",
"why_it_is_not_obvious":
"Giving the drawing more room RAISES the zoom, which makes every "
"dot bigger, which can close the very gap the rule protects. "
"More space is not automatically safer, and one screen cannot "
"show that.",
"furniture": rows,
"not_claimed":
"The absolute crowded counts are an UPPER BOUND, not a "
"prediction. This model sizes a dot from zoom alone; the "
"renderer's bodyDotPx() sizes it from the measured spacing of "
"the dots it is about to draw, so the real renderer adapts where "
"this model does not and will crowd less. What survives is the "
"COMPARISON - same model, same 271 million configurations, one "
"furniture set against the other. It renders nothing, and says "
"nothing about whether a layout is pleasant, only whether the "
"spacing rule survives it.",
"anonymised": "No project, site, maker or model anywhere."}
p = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"night-results", "layout-gate.json")
os.makedirs(os.path.dirname(p), exist_ok=True)
io.open(p, "w", encoding="utf-8", newline="\n").write(
json.dumps(out, indent=1) + "\n")
print("\n wrote night-results/layout-gate.json")
return 0
if __name__ == "__main__":
sys.exit(main())