In this section
- Web storage · grid / tools/web.py lines 1–188
- Build Dictionary Workflow automation · grid-dictionary / .github/workflows/build-dictionary.yml lines 1–27
- Build Dictionary storage · grid-dictionary / tools/build_dictionary.py lines 1–170
- Parity Driver test · grid-distance-maths / test/parity_driver.mjs lines 1–69
- Verify test · grid-distance-maths / test/verify.mjs lines 1–200
Web
A Python command-line tool in the tools folder of Grid that reads web meta.
storagegrid / tools/web.py · lines 1–188 of 188 · Entry point · pattern git_blobs (shared by 3 files)
- What it does
- It loads web meta. Defines git_blobs, public_set, main, klass. Uses libraries argparse, json, os, subprocess, sys. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- README: "Measured 2026-09-19 by `tools/web.py`, in 3.4 seconds:"
- Inputs & outputs
- In: JSON file web-meta.json; command-line arguments. Out: JSON file.
- 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 git blobs helper (`git_blobs`), the public set helper (`public_set`) and the klass step (`klass`). The estate's actual mesh, measured. It accepts `--roots`, `--org` and `--out`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- grid · tools · Python CLI
- Uses
- argparse, json, os, subprocess, sys, time, datetime, itertools
- Used by
- none found
- Produces
- git_blobs, public_set, main
- Defines here
- git_blobs, public_set, main, klass
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- grid@fb48dbb8f2bca346c7637996afca2f907cfa069e tools/web.py:1-188 · blob 26bd31cfba3042b1ce31aa6fd939112653f73a6c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""tools/web.py - the estate's actual mesh, measured.
A GRID IS THE MESH YOU DO NOT HAVE TO STORE. Its connectivity is implicit in the index: neighbours
are found by arithmetic. A general mesh has to carry its connectivity, because nothing generated
it from a rule.
The real universe is the second kind. Its large scale structure is the cosmic web, and it grew
from a Gaussian random field of primordial density fluctuations, so no rule produces it and no
index gives its filaments. Connectivity there is history, not law, and history has to be measured.
The estate is the same. Its repositories are not adjacent because a law put them next to each
other; they are adjacent when they actually SHARE CONTENT. Git already decides this and cannot be
argued with: a blob SHA is the hash of the content, so two repositories holding the same SHA hold
byte identical content. That is an exact adjacency with a cryptographic key behind it.
edge(A, B) = the blobs whose SHA appears in both A and B
This measures every blob in every repository's history, intersects them, and writes the graph.
Nothing is inferred, nothing is weighted by guesswork, and a pair with nothing in common gets no
edge at all, which is how the voids appear.
Writes:
web/nodes.tsv repo blobs bytes degree shared_blobs class
web/edges.tsv a b shared_blobs shared_bytes
web-meta.json the totals and the checks
Repositories that are not confirmed public are given one of our own words and a number. The counts
are the point; the name is somebody else's business.
"""
import argparse
import json
import os
import subprocess
import sys
import time
from datetime import datetime, timezone
from itertools import combinations
def git_blobs(d):
"""Every blob in every reachable and unreachable object of this repository, with its size."""
p = subprocess.run(['git', 'cat-file', '--batch-all-objects',
'--batch-check=%(objectname) %(objecttype) %(objectsize)'],
cwd=d, capture_output=True, text=True, encoding='utf-8', errors='replace')
out = {}
for line in p.stdout.splitlines():
f = line.split()
if len(f) == 3 and f[1] == 'blob':
out[f[0]] = int(f[2])
return out
def public_set(org):
try:
r = subprocess.run(['gh', 'repo', 'list', org, '--limit', '300',
'--json', 'name,visibility', '--jq',
'.[] | select(.visibility=="PUBLIC") | .name'],
capture_output=True, text=True)
s = {n.strip().lower() for n in r.stdout.split() if n.strip()}
return s or None
except Exception:
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--roots', default='C:/Users/vikra/Documents/GitHub')
ap.add_argument('--org', default='Ventusltd')
ap.add_argument('--out', default='.')
a = ap.parse_args()
repos = []
for root in a.roots.split(','):
if not os.path.isdir(root):
continue
for n in sorted(os.listdir(root)):
d = os.path.join(root, n)
if os.path.isdir(os.path.join(d, '.git')):
repos.append((n, d))
if not repos:
print('FAIL: zero repositories. A check that examines nothing refuses.')
return 1
t0 = time.time()
names = [n for n, _ in repos]
blobs = []
size = {}
for i, (n, d) in enumerate(repos):
b = git_blobs(d)
size.update(b)
blobs.append(set(b))
print(' %-36s %8s blobs %6.1f s' % (n, format(len(b), ','), time.time() - t0),
file=sys.stderr, flush=True)
# where each blob lives. A blob in one repository only is that repository's own; a blob in
# several is an edge, and the more repositories it is in the more of a knot it makes.
where = {}
for i, s in enumerate(blobs):
for sha in s:
where.setdefault(sha, []).append(i)
edge = {}
for sha, rs in where.items():
if len(rs) < 2:
continue
for x, y in combinations(sorted(rs), 2):
e = edge.setdefault((x, y), [0, 0])
e[0] += 1
e[1] += size.get(sha, 0)
deg = [0] * len(repos)
shared = [0] * len(repos)
for (x, y), (nb, by) in edge.items():
deg[x] += 1
deg[y] += 1
shared[x] += nb
shared[y] += nb
# THE CLASSIFICATION IS BY DEGREE, AND IT IS AN ANALOGUE, NOT THE REAL THING. Cosmology
# classifies the web by counting how many eigenvalues of the deformation tensor exceed a
# threshold, which needs a continuous density field. A graph has no such field, so this counts
# neighbours instead and says so, rather than borrowing a method it is not entitled to.
def klass(k):
if k == 0: return 'void' # shares nothing with anything: an island
if k == 1: return 'leaf'
if k == 2: return 'filament'
return 'knot'
pub = public_set(a.org)
label = list(names)
redacted = 0
if pub:
k = 0
for i, n in enumerate(names):
if n.lower() not in pub:
k += 1
label[i] = 'unnamed-%02d' % k
redacted = k
else:
print(' WARNING: could not confirm which repositories are public. Names left as they '
'are; do not publish this without checking.', file=sys.stderr)
os.makedirs(os.path.join(a.out, 'web'), exist_ok=True)
with open(os.path.join(a.out, 'web', 'nodes.tsv'), 'w', encoding='utf-8', newline='\n') as f:
f.write('# repo\tblobs\tbytes\tdegree\tshared_blobs\tclass\n')
for i, n in enumerate(label):
by = sum(size.get(s, 0) for s in blobs[i])
f.write('%s\t%d\t%d\t%d\t%d\t%s\n'
% (n, len(blobs[i]), by, deg[i], shared[i], klass(deg[i])))
with open(os.path.join(a.out, 'web', 'edges.tsv'), 'w', encoding='utf-8', newline='\n') as f:
f.write('# a\tb\tshared_blobs\tshared_bytes\n')
for (x, y), (nb, by) in sorted(edge.items(), key=lambda kv: -kv[1][0]):
f.write('%s\t%s\t%d\t%d\n' % (label[x], label[y], nb, by))
distinct = len(where)
n = len(repos)
meta = {
'asof': datetime.now(timezone.utc).astimezone().isoformat(timespec='seconds'),
'command': 'python tools/web.py ' + ' '.join(sys.argv[1:]),
'repositories': n,
'distinct_blobs': distinct,
'blobs_in_one_repository_only': sum(1 for v in where.values() if len(v) == 1),
'blobs_shared': sum(1 for v in where.values() if len(v) > 1),
'edges': len(edge),
'possible_edges': n * (n - 1) // 2,
'density': round(len(edge) / max(1, n * (n - 1) // 2), 4),
'voids': sum(1 for d_ in deg if d_ == 0),
'leaves': sum(1 for d_ in deg if d_ == 1),
'filaments': sum(1 for d_ in deg if d_ == 2),
'knots': sum(1 for d_ in deg if d_ >= 3),
'largest_degree': max(deg) if deg else 0,
'redacted_repositories': redacted,
'seconds': round(time.time() - t0, 1),
'method': 'a blob SHA is the hash of its content, so a SHA present in two repositories '
'means byte identical content in both. The adjacency cannot be wrong.',
'not_measured': 'imports, forks, references and citations are also real edges and none of '
'them are here. This graph is shared content and nothing else.'
}
with open(os.path.join(a.out, 'web-meta.json'), 'w', encoding='utf-8', newline='\n') as f:
json.dump(meta, f, indent=1, sort_keys=True)
print(json.dumps(meta, indent=1, sort_keys=True))
return 0
if __name__ == '__main__':
raise SystemExit(main())Build Dictionary Workflow
A GitHub Actions workflow in Grid Dictionary. Runs on push, on a schedule and by hand.
automationgrid-dictionary / .github/workflows/build-dictionary.yml · lines 1–27 of 27 · Entry point
- What it does
- It runs automated jobs on GitHub Actions. Side effects: starts processes.
- Inputs & outputs
- Out: commits pushed to the repository.
- Downstream impact
- It is itself an entry point (workflow); no other file was found loading it.
- What it achieves
- Named “Build grid dictionary (monthly)”; runs Build Dictionary (`tools/build_dictionary.py`).
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- grid-dictionary · .github/workflows · workflow
- Uses
- Build Dictionary (workflow run)
- Used by
- none found
- Produces
- none declared
- Defines here
- Build grid dictionary (monthly)
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- grid-dictionary@21b73d7cd5a6171245e0b3d1b69b0ce4d6322a63 .github/workflows/build-dictionary.yml:1-27 · blob f56965a77f08fd573126b947fccdeed9c40ea48e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: Build grid dictionary (monthly)
on:
schedule:
- cron: '23 5 1 * *' # 05:23 UTC on the 1st of each month
workflow_dispatch:
push:
paths: [ 'seed/definitions.yaml', 'tools/build_dictionary.py' ]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: pip install pyyaml
- name: Build the dictionary from the seed and the wandering-star code history
run: python tools/build_dictionary.py
- name: Commit if changed
run: |
git config user.name "grid-dictionary"
git config user.email "noreply@ventusltd.com"
git add data DICTIONARY.md
git diff --cached --quiet || git commit -m "dictionary: rebuild from seed + code history ($(date -u +%Y-%m-%dT%H:%M:%SZ))"
git pushBuild Dictionary
A Python command-line tool in the tools folder of Grid Dictionary that fetches maya cards, blocks and maya links from the stars and spiders repositories.
storagegrid-dictionary / tools/build_dictionary.py · lines 1–170 of 170 · Entry point
- What it does
- It fetches maya cards, blocks and maya links. Defines path, get, load_yaml, main, strong_aliases. Uses libraries json, re, os, sys, urllib.request. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- README: "`tools/build_dictionary.py` reads `seed/definitions.yaml` (the curated authoritative terms), the wandering-star code index (`stars/code/index.json` + `code/f/*.json`), `stars/blocks/blocks.json`, and the Maya cards, then writes:"
- Inputs & outputs
- In: data source: stars data; data source: spiders data; JSON file maya-cards.json; JSON file keys.json; JSON file index.json; JSON file blocks.json. Out: JSON file keys.json; JSON file dictionary.json; JSON file maya-links.json.
- Downstream impact
- Used directly by 1 file: Build Dictionary Workflow (grid-dictionary).
- What it achieves
- It loads yaml (`load_yaml`) and is built from the path step (`path`) and the get step (`get`). Build the grid dictionary and tie it to the estate's unique code history and the Maya cards.
- Why it matters
- Run by Build Dictionary Workflow.
- Application
- grid-dictionary · tools · Python CLI
- Uses
- Stars — Index Page (estate URL), json, re, os, sys, urllib.request, datetime, yaml
- Used by
- run by Build Dictionary Workflow (workflow run)
- Produces
- path, get, load_yaml, main
- Defines here
- path, get, load_yaml, main, strong_aliases
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- grid-dictionary@21b73d7cd5a6171245e0b3d1b69b0ce4d6322a63 tools/build_dictionary.py:1-170 · blob 0a29b4a737a0d0cd23b1389cb8d9ba63a00569ef · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""
build_dictionary.py — build the grid dictionary and tie it to the estate's unique code history and the Maya cards.
Reads:
seed/definitions.yaml the curated authoritative terms (permanent keys)
the wandering star's code index https://ventusltd.github.io/stars/code/index.json + code/f/<bucket>.json
the blocks https://ventusltd.github.io/stars/blocks/blocks.json
the Maya cards the dead-end cards (maya-cards.json), if reachable
Writes:
data/keys.json append-only ledger: term key -> permanent GD number
data/dictionary.json every term, its definition, sources, related terms, and the code families that use it
data/maya-links.json per Maya card: a primary definition key and secondary keys (one-to-many)
DICTIONARY.md the alphabetical human-readable page
Continuous learning protocol: the Spider apps read data/dictionary.json + data/maya-links.json so a reader learns the
grid as they browse. Run monthly (see .github/workflows/build-dictionary.yml); the wandering star walks new commits,
the dictionary follows.
"""
import json, re, os, sys, urllib.request, datetime
STARS = "https://ventusltd.github.io/stars/"
MAYA_URL = "https://ventusltd.github.io/spiders/tools/maya-hunt/data/maya-cards.json"
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def path(*p): return os.path.join(HERE, *p)
def get(url):
with urllib.request.urlopen(url, timeout=60) as r: return json.loads(r.read().decode("utf-8"))
def load_yaml(p):
# tiny YAML reader for our own seed shape (list of flat mappings under `definitions:`), no external deps
import yaml # PyYAML is available on GitHub Actions ubuntu images
with open(p, encoding="utf-8") as f: return yaml.safe_load(f)
def main():
seed = load_yaml(path("seed", "definitions.yaml"))
defs = seed["definitions"]
cats = seed.get("meta", {}).get("categories", {})
# 1) permanent keys ledger (append-only)
os.makedirs(path("data"), exist_ok=True)
ledger = {}
if os.path.exists(path("data", "keys.json")):
ledger = json.load(open(path("data", "keys.json"), encoding="utf-8"))
nxt = (max(ledger.values()) if ledger else 0) + 1
for d in defs:
if d["key"] not in ledger:
ledger[d["key"]] = nxt; nxt += 1
json.dump(ledger, open(path("data", "keys.json"), "w", encoding="utf-8"), indent=1, sort_keys=True)
gd = lambda k: "GD-%04d" % ledger[k]
# 2) the wandering star's code history: family names, and block titles
fam_names = {} # family number -> name
try:
idx = get(STARS + "code/index.json"); bs = idx.get("bucket_size", 500)
buckets = idx.get("buckets", [])
for b in buckets:
try:
data = get(STARS + "code/f/%s.json" % b)
for fnum, rec in data.items():
nm = (rec.get("names") or [rec.get("name")] or [""])[0] if isinstance(rec, dict) else ""
if nm: fam_names[int(fnum)] = nm
except Exception:
continue
except Exception as e:
print("code index unavailable:", e, file=sys.stderr)
blocks = {}
try:
for b in get(STARS + "blocks/blocks.json")["blocks"]:
blocks[b["symbol"]] = b
except Exception as e:
print("blocks unavailable:", e, file=sys.stderr)
# 3) tie each definition to code families whose NAME contains a strong alias (word-boundary, length>=4)
def strong_aliases(d):
al = set([d["term"]] + (d.get("aliases") or []))
# split multiword terms into their significant words too
out = set()
for a in al:
a = str(a)
if len(a) >= 4 and not a.isupper() or len(a) >= 3 and a.isupper():
out.add(a)
return out
# precompute lowercase family names
fam_lc = {n: v.lower() for n, v in fam_names.items()}
for d in defs:
pats = []
for a in strong_aliases(d):
token = re.escape(a.lower())
pats.append(re.compile(r"(?:^|[^a-z0-9])" + token + r"(?:$|[^a-z0-9])"))
fams = []
if pats:
for num, nm in fam_lc.items():
if any(p.search(nm) for p in pats):
fams.append(num)
if len(fams) >= 60: break
d["_families"] = sorted(fams)[:60]
# blocks whose title/description mention the term
d["_blocks"] = [b["symbol"] for b in blocks.values()
if any(a.lower() in (b.get("title", "") + " " + b.get("description", "")).lower()
for a in strong_aliases(d))][:20]
# 4) assemble dictionary.json
by_key = {d["key"]: d for d in defs}
now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
dictionary = {"generated_utc": now, "source": "build_dictionary.py",
"note": "Authoritative grid terms with permanent keys, tied to the estate's unique code history "
"(wandering-star family numbers) and to the Maya cards. Read by the Spider apps.",
"categories": cats, "count": len(defs), "terms": []}
for d in sorted(defs, key=lambda x: x["term"].lower()):
dictionary["terms"].append({
"key": gd(d["key"]), "slug": d["key"], "term": d["term"], "aliases": d.get("aliases", []),
"category": d.get("category", ""), "definition": " ".join(str(d.get("definition", "")).split()),
"source": d.get("source", ""),
"related": [{"key": gd(r), "term": by_key[r]["term"]} for r in d.get("related", []) if r in by_key],
"estate": d.get("estate", ""),
"code_families": d["_families"], "blocks": d["_blocks"]})
json.dump(dictionary, open(path("data", "dictionary.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False)
# 5) tie to Maya cards: primary + secondary definition keys per dead-end card (one-to-many)
maya_links = {"generated_utc": now, "note": "For each Maya card (dead end), a primary grid definition and secondary "
"definitions, so the card offers 'Learn about the grid' links. Keyed by graph then card label.",
"links": {}}
try:
maya = get(MAYA_URL)
# build a matcher: alias -> def key, longest alias first
alias_key = []
for d in defs:
for a in [d["term"]] + (d.get("aliases") or []):
alias_key.append((str(a).lower(), d["key"]))
alias_key.sort(key=lambda x: -len(x[0]))
for gid, cards in (maya.get("cards") or {}).items():
gl = {}
for label, card in cards.items():
text = (label + " " + (card.get("function", "") or "") + " " + (card.get("reason", "") or "")).lower()
hits = []
for a, k in alias_key:
if len(a) >= 4 and re.search(r"(?:^|[^a-z0-9])" + re.escape(a) + r"(?:$|[^a-z0-9])", text):
if k not in hits: hits.append(k)
if hits:
gl[label] = {"primary": gd(hits[0]), "primary_term": by_key[hits[0]]["term"],
"secondary": [{"key": gd(h), "term": by_key[h]["term"]} for h in hits[1:6]]}
if gl: maya_links["links"][gid] = gl
except Exception as e:
print("maya cards unavailable:", e, file=sys.stderr)
json.dump(maya_links, open(path("data", "maya-links.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False)
# 6) DICTIONARY.md (alphabetical)
md = ["# Grid dictionary", "", "Generated %s. %d terms, tied to the estate's unique code history and the Maya "
"cards. Sources: NESO, the transmission owners (NGET, National Grid, TenneT), the DNOs (UK Power Networks and "
"others), Ofgem, UK Government (DESNZ) and Elexon. Terms are standard sourced meaning; anything estate-specific "
"or unverified says so and names the body that publishes it." % (now, len(defs)), ""]
for d in sorted(defs, key=lambda x: x["term"].lower()):
md.append("### %s `%s`" % (d["term"], gd(d["key"])))
md.append("*%s* " % cats.get(d.get("category", ""), d.get("category", "")))
md.append(" ".join(str(d.get("definition", "")).split()))
md.append("")
md.append("- Source: %s" % d.get("source", ""))
if d.get("related"): md.append("- Related: " + ", ".join(by_key[r]["term"] for r in d["related"] if r in by_key))
if d.get("estate"): md.append("- In our code: %s" % d["estate"])
if d["_families"]: md.append("- Unique code families that use it: %d (via the wandering star)" % len(d["_families"]))
md.append("")
open(path("DICTIONARY.md"), "w", encoding="utf-8").write("\n".join(md))
tot_fam = sum(len(d["_families"]) for d in defs)
print("DONE: %d terms; %d code-family ties; maya links for %d graphs." %
(len(defs), tot_fam, len(maya_links["links"])))
if __name__ == "__main__":
main()Parity Driver
A JavaScript module in the test folder of Grid Distance Maths that reads a JSON case list on stdin, answer with the JavaScript result for each case on stdout.
testgrid-distance-maths / test/parity_driver.mjs · lines 1–69 of 69
- What it does
- It tests its inputs.
- Downstream impact
- Used directly by 1 file: Verify Parity (grid-distance-maths).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Checked by Verify Parity.
- Application
- grid-distance-maths · test · JavaScript module
- Uses
- Geodesy (import)
- Used by
- run by Verify Parity (script call)
- 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
- grid-distance-maths@8e91b07d8312acca5bcaef43e839f06a3b1d642a test/parity_driver.mjs:1-69 · blob 638288dad6e3feede9d597c5d8afc212a584ed95 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: unknown
/**
* Parity driver: read a JSON case list on stdin, answer with the JavaScript
* result for each case on stdout.
*
* It exists so verify_parity.py can compare the two implementations on
* identical inputs without either side knowing the other's expected answers.
* Nothing here computes anything itself — every case dispatches straight into
* src/geodesy.mjs, so a divergence is a real divergence.
*/
import {
R_ATLAS, R_MEAN, R_UK,
curvatureKm, localScaleKm,
distanceKm, distanceEllipsoidalKm, pathLengthKm,
initialBearingDeg, destinationPoint,
distanceToSegmentKm, distanceToLineKm,
geodesicCircle, circleApproximationError,
polygonAreaKm2, areaUnits,
SpatialIndex, STRAIGHT_LINE_CAVEAT,
} from "../src/geodesy.mjs";
const OPS = {
constants: () => ({ R_ATLAS, R_MEAN, R_UK }),
curvature: (a) => curvatureKm(a.lat),
localScale: (a) => localScaleKm(a.lat),
distance: (a) => distanceKm(a.lon1, a.lat1, a.lon2, a.lat2, a.radius ?? R_ATLAS),
ellipsoidal: (a) => {
const v = distanceEllipsoidalKm(a.lon1, a.lat1, a.lon2, a.lat2);
return Number.isNaN(v) ? null : v;
},
pathLength: (a) => pathLengthKm(a.coords, a.radius ?? R_ATLAS),
bearing: (a) => initialBearingDeg(a.lon1, a.lat1, a.lon2, a.lat2),
destination: (a) => destinationPoint(a.lon, a.lat, a.km, a.bearing, a.radius ?? R_ATLAS),
segment: (a) => {
const r = distanceToSegmentKm(a.lon, a.lat, a.aLon, a.aLat, a.bLon, a.bLat, a.radius ?? R_ATLAS);
return { km: r.km, foot: r.foot, t: r.t };
},
line: (a) => {
const r = distanceToLineKm(a.lon, a.lat, a.coords, a.radius ?? R_ATLAS);
return { km: r.km, foot: r.foot, t: r.t, segmentIndex: r.segmentIndex };
},
circle: (a) => geodesicCircle(a.lon, a.lat, a.radiusKm, a.vertices, a.radius ?? R_ATLAS),
circleError: (a) => circleApproximationError(a.vertices),
polygon: (a) => polygonAreaKm2(a.coords, a.radius ?? R_ATLAS),
areaUnits: (a) => areaUnits(a.areaKm2),
caveat: () => STRAIGHT_LINE_CAVEAT,
nearest: (a) => {
const index = new SpatialIndex(a.cell ?? 0.1);
a.features.forEach((f, i) => index.addSegment(i, f[0], f[1], f[2], f[3]));
const hit = index.nearest(a.lon, a.lat, (i) => {
const f = a.features[i];
return distanceToSegmentKm(a.lon, a.lat, f[0], f[1], f[2], f[3]).km;
});
return hit === null ? null : { id: hit.id, km: hit.km };
},
};
let raw = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => { raw += chunk; });
process.stdin.on("end", () => {
const cases = JSON.parse(raw);
const out = cases.map((c) => {
const op = OPS[c.op];
if (!op) throw new Error(`unknown op ${c.op}`);
return op(c.args ?? {});
});
process.stdout.write(JSON.stringify(out));
});Verify
A JavaScript module in the test folder of Grid Distance Maths that works with engine haversine (`engineHaversine`) and calculates great-circle distances and angles, using Vincenty.
testgrid-distance-maths / test/verify.mjs · lines 1–200 of 200 · Not reached from any entry point (candidate for review) · pattern measure (shared by 35 files)
- What it does
- It tests its inputs. Defines ok, near, engineHaversine, measure. Side effects: starts processes.
- Inputs & outputs
- Coordinate systems named: WGS84 / EPSG:4326.
- What it achieves
- It is built from the near step (`near`), the engine haversine helper (`engineHaversine`) and the measure step (`measure`). Checks the canonical implementation against ellipsoidal truth and against the specific defects that made this repository necessary.
- Why it matters
- No other file in the estate was found to import it.
- Application
- grid-distance-maths · test · JavaScript module
- Uses
- Geodesy (import)
- Used by
- none found
- Produces
- ok, near, engineHaversine, measure
- Defines here
- ok, near, engineHaversine, measure
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- grid-distance-maths@8e91b07d8312acca5bcaef43e839f06a3b1d642a test/verify.mjs:1-200 · blob b79958191494b5a169ae685217ec6ddb60014bc9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unreached_review
/**
* Grid Distance Maths — verification.
*
* Checks the canonical implementation against ellipsoidal truth and against
* the specific defects that made this repository necessary. Run:
*
* node test/verify.mjs
*
* Exits non-zero on any failure. No dependencies.
*/
import {
R_ATLAS, R_MEAN, R_UK,
distanceKm, distanceEllipsoidalKm, pathLengthKm,
destinationPoint, initialBearingDeg,
distanceToSegmentKm, distanceToLineKm,
geodesicCircle, circleApproximationError, polygonAreaKm2, areaUnits,
SpatialIndex, curvatureKm,
} from "../src/geodesy.mjs";
const checks = [];
const ok = (name, pass, detail = "") => checks.push({ name, pass: Boolean(pass), detail });
const near = (a, b, tol) => Math.abs(a - b) <= tol;
/* ---- constants ---------------------------------------------------------- */
ok("R_ATLAS is the WGS84 semi-major axis", R_ATLAS === 6378.137);
ok("R_MEAN is the IUGG mean radius", R_MEAN === 6371.0088);
ok("R_UK is the Gaussian radius at 54N", near(R_UK, 6384.7272, 1e-4));
ok("R_ATLAS and R_MEAN differ by 0.112 percent",
near(((R_ATLAS - R_MEAN) / R_MEAN) * 100, 0.1119, 1e-4));
/* ---- agreement with the deployed tools ---------------------------------- */
// ventus-corev8engine.js haversine(), transcribed independently.
function engineHaversine(lon1, lat1, lon2, lat2) {
const R = 6378.137; const r = Math.PI / 180;
const dLat = (lat2 - lat1) * r; const dLon = (lon2 - lon1) * r;
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(lat1 * r) * Math.cos(lat2 * r) * Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
let worstDrift = 0;
for (let i = 0; i < 500; i += 1) {
const lo1 = -7 + Math.random() * 9; const la1 = 50 + Math.random() * 8.5;
const lo2 = lo1 + (Math.random() - 0.5); const la2 = la1 + (Math.random() - 0.5);
worstDrift = Math.max(worstDrift,
Math.abs(distanceKm(lo1, la1, lo2, la2) - engineHaversine(lo1, la1, lo2, la2)));
}
ok("distanceKm agrees with the GridAtlas engine to the last bit",
worstDrift < 1e-12, `worst drift ${worstDrift.toExponential(2)} km`);
/* ---- ellipsoidal reference ---------------------------------------------- */
// Land's End to John o' Groats, a published long UK baseline.
const lgj = distanceEllipsoidalKm(-5.7124, 50.0657, -3.0170, 58.6373);
ok("Vincenty reproduces the Land's End to John o' Groats baseline",
near(lgj, 969.87, 0.05), `${lgj.toFixed(3)} km`);
ok("Vincenty is symmetric",
near(lgj, distanceEllipsoidalKm(-3.0170, 58.6373, -5.7124, 50.0657), 1e-9));
ok("zero distance is zero", distanceEllipsoidalKm(-1.5, 54, -1.5, 54) === 0);
/* R_UK must beat R_ATLAS, which must beat R_MEAN, over UK pairs. */
let sumUk = 0; let sumAtlas = 0; let sumMean = 0; let n = 0;
for (let i = 0; i < 2000; i += 1) {
const la1 = 50 + Math.random() * 8.5; const lo1 = -7 + Math.random() * 9;
const brg = Math.random() * 360; const d = 0.5 + Math.random() * 59.5;
const [lo2, la2] = destinationPoint(lo1, la1, d, brg);
if (la2 < 50 || la2 > 58.6 || lo2 < -7.2 || lo2 > 1.9) continue;
const truth = distanceEllipsoidalKm(lo1, la1, lo2, la2);
if (!Number.isFinite(truth) || truth <= 0) continue;
sumUk += Math.abs(distanceKm(lo1, la1, lo2, la2, R_UK) - truth) / truth;
sumAtlas += Math.abs(distanceKm(lo1, la1, lo2, la2, R_ATLAS) - truth) / truth;
sumMean += Math.abs(distanceKm(lo1, la1, lo2, la2, R_MEAN) - truth) / truth;
n += 1;
}
ok("R_UK is more accurate than R_ATLAS over UK pairs",
sumUk / n < sumAtlas / n, `${(1e6 * sumUk / n).toFixed(0)} vs ${(1e6 * sumAtlas / n).toFixed(0)} ppm`);
ok("R_ATLAS is more accurate than R_MEAN over UK pairs",
sumAtlas / n < sumMean / n, `${(1e6 * sumAtlas / n).toFixed(0)} vs ${(1e6 * sumMean / n).toFixed(0)} ppm`);
/* ---- bearing and destination round-trip --------------------------------- */
const [dl, dp] = destinationPoint(-1.5, 54, 25, 73.4);
ok("destination then measure returns the distance travelled",
near(distanceKm(-1.5, 54, dl, dp), 25, 1e-9), `${distanceKm(-1.5, 54, dl, dp).toFixed(9)} km`);
ok("destination then bearing returns the bearing travelled",
near(initialBearingDeg(-1.5, 54, dl, dp), 73.4, 1e-6));
/* ---- point to segment: the defect this repo exists to prevent ------------ */
// A due-east span at 54N. A point opposite its midpoint is 1 km away from the
// LINE, but much further from either END. Measuring to endpoints overstates.
const A = [-1.5, 54.0];
const B = destinationPoint(A[0], A[1], 20, 90);
const mid = destinationPoint(A[0], A[1], 10, 90);
const off = destinationPoint(mid[0], mid[1], 1, 0);
const seg = distanceToSegmentKm(off[0], off[1], A[0], A[1], B[0], B[1]);
const toNearestEnd = Math.min(
distanceKm(off[0], off[1], A[0], A[1]),
distanceKm(off[0], off[1], B[0], B[1]),
);
// A GeoJSON segment is a CHORD, so the measured distance is to the chord, not
// to the great-circle arc through the same endpoints. The arc bulges away from
// the chord by L^2/8R -- 7.8 m over this deliberately long 20 km span. Real
// network segments are ~200 m, where the effect is nanometres, so the tolerance
// here is set to admit the known sagitta rather than to hide it.
ok("distance to a segment is the perpendicular, not the nearest end",
near(seg.km, 1, 0.02), `${seg.km.toFixed(4)} km, chord sagitta included`);
{
// The same geometry at a realistic segment length, where chord and arc agree.
const a2 = [-1.5, 54.0];
const b2 = destinationPoint(a2[0], a2[1], 0.5, 90);
const m2 = destinationPoint(a2[0], a2[1], 0.25, 90);
const o2 = destinationPoint(m2[0], m2[1], 1, 0);
const s2 = distanceToSegmentKm(o2[0], o2[1], a2[0], a2[1], b2[0], b2[1]);
ok("on a realistic 500 m segment the perpendicular is exact",
near(s2.km, 1, 5e-5), `${s2.km.toFixed(7)} km`);
ok("chord sagitta scales as L squared over 8R",
near(seg.km - 1, (20 ** 2) / (8 * R_ATLAS), 0.004),
`measured ${((seg.km - 1) * 1000).toFixed(1)} m, predicted ${((20 ** 2) / (8 * R_ATLAS) * 1000).toFixed(1)} m`);
}
ok("measuring to the nearest end would have overstated by an order of magnitude",
toNearestEnd > 9, `${toNearestEnd.toFixed(2)} km vs ${seg.km.toFixed(2)} km`);
ok("the foot of the perpendicular lands inside the segment",
seg.t > 0.45 && seg.t < 0.55, `t=${seg.t.toFixed(4)}`);
// Beyond an endpoint, the projection must clamp rather than run off the line.
const past = destinationPoint(B[0], B[1], 5, 90);
const clamped = distanceToSegmentKm(past[0], past[1], A[0], A[1], B[0], B[1]);
ok("projection clamps at the segment end", clamped.t === 1 && near(clamped.km, 5, 0.01));
const line = [A, mid, B];
ok("polyline search finds the same perpendicular",
near(distanceToLineKm(off[0], off[1], line).km, 1, 0.01));
/* ---- circles ------------------------------------------------------------ */
const ring = geodesicCircle(-1.5, 54, 10, 128);
ok("geodesic circle closes", ring[0][0] === ring[ring.length - 1][0]);
const radii = ring.slice(0, -1).map((p) => distanceKm(-1.5, 54, p[0], p[1]));
ok("every circle vertex is exactly the radius away",
radii.every((r) => near(r, 10, 1e-9)), `spread ${(Math.max(...radii) - Math.min(...radii)).toExponential(2)}`);
const e24 = circleApproximationError(24);
const e128 = circleApproximationError(128);
ok("24-vertex ring understates area by 1.14 percent",
near(e24.areaShortFraction * 100, 1.138, 0.01), `${(e24.areaShortFraction * 100).toFixed(3)}%`);
ok("128-vertex ring understates area by 0.04 percent",
near(e128.areaShortFraction * 100, 0.040, 0.005));
ok("24-vertex ring is 85.6 m inside a 10 km circle",
near(e24.radialFraction * 10000, 85.6, 0.5), `${(e24.radialFraction * 10000).toFixed(1)} m`);
const area = polygonAreaKm2(ring.slice(0, -1));
ok("circle area is within the inscribed-polygon bound of pi r squared",
area.areaKm2 < Math.PI * 100 && area.areaKm2 > Math.PI * 100 * 0.999,
`${area.areaKm2.toFixed(4)} vs ${(Math.PI * 100).toFixed(4)} km2`);
ok("circle perimeter is close to 2 pi r",
near(area.perimeterKm, 2 * Math.PI * 10, 0.05), `${area.perimeterKm.toFixed(4)} km`);
const u = areaUnits(1);
ok("a square kilometre is 100 hectares", near(u.hectares, 100, 1e-9));
ok("a square kilometre is 247.105 acres", near(u.acres, 247.105, 1e-3));
/* ---- path length -------------------------------------------------------- */
ok("path length sums its legs", near(pathLengthKm([A, mid, B]), 20, 1e-6));
ok("a one-point path has no length", pathLengthKm([A]) === 0);
/* ---- spatial index: the bounded-search defect ---------------------------- */
// 5,000 scattered points plus one deliberately far outside the first rings.
const pts = [];
for (let i = 0; i < 5000; i += 1) {
pts.push([-7 + Math.random() * 9, 50 + Math.random() * 8.5]);
}
const target = [-3.0, 56.0];
const idx = new SpatialIndex(0.1);
pts.forEach((p, i) => idx.add(i, p[0], p[1]));
const measure = (i) => distanceKm(target[0], target[1], pts[i][0], pts[i][1]);
const viaIndex = idx.nearest(target[0], target[1], measure);
let brute = { id: -1, km: Infinity };
pts.forEach((p, i) => {
const d = measure(i);
if (d < brute.km) brute = { id: i, km: d };
});
ok("spatial index finds the same nearest as a brute-force sweep",
viaIndex && viaIndex.id === brute.id,
`index=${viaIndex && viaIndex.km.toFixed(4)} brute=${brute.km.toFixed(4)}`);
// A lone point far from everything must still be found, not silently missed.
const lonely = new SpatialIndex(0.1);
lonely.add(0, 2.0, 51.0);
const far = lonely.nearest(-6.5, 57.5, () => distanceKm(-6.5, 57.5, 2.0, 51.0));
ok("an isolated feature is still found after many rings",
far !== null && far.id === 0, far ? `${far.km.toFixed(1)} km` : "not found");
/* ---- curvature ---------------------------------------------------------- */
const c54 = curvatureKm(54);
ok("prime vertical exceeds meridional at 54N", c54.primeVertical > c54.meridional);
ok("Gaussian radius at 54N matches R_UK",
near(Math.sqrt(c54.meridional * c54.primeVertical), R_UK, 1e-3));
/* ---- report ------------------------------------------------------------- */
const failed = checks.filter((c) => !c.pass);
for (const c of checks) {
console.log(` [${c.pass ? "PASS" : "FAIL"}] ${c.name}${c.detail ? " " + c.detail : ""}`);
}
console.log(`\n${checks.length - failed.length}/${checks.length} checks passed`);
process.exit(failed.length ? 1 : 0);