In this section
- Explore — Lab ingest · cosmic / tools/explore/lab/run.py lines 1–192
- Semantic storage · cosmic / tools/explore/lab/semantic.py lines 1–206
- Shoot render · cosmic / tools/explore/lab/shoot.py lines 1–58
- Test Lab test · cosmic / tools/explore/lab/test_lab.py lines 1–204
Explore — Lab
A Python command-line tool in the tools folder of Cosmic that reads metrics and build graph, using Louvain and PageRank.
ingestcosmic / tools/explore/lab/run.py · lines 1–192 of 192 · Entry point · pattern run_all (shared by 2 files)
- What it does
- It loads metrics and build graph. Defines verdict, run_all, report, main. Uses libraries argparse, datetime, json, os, shutil. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file keys.json; JSON file .metrics.json; JSON file build_graph.json; JSON file graph.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Extras (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
- What it achieves
- It is built from the verdict step (`verdict`), the run all helper (`run_all`) and the report step (`report`). Explore Code intelligence lab: run every experiment, check determinism, write overlays, metrics and `REPORT.md`. It accepts `--only`, `--out` and `--graph`.
- Why it matters
- Run by Extras.
- Application
- cosmic · tools/explore/lab · Python CLI
- Uses
- Explore — Lab (import), Communities (import), Importance (import), Wafer (import), Semantic (import), Drift (import), Links (import), Pipeline (import), argparse, datetime, json, os, shutil, sys, time
- Used by
- run by Extras (script call)
- Produces
- verdict, run_all, report, main
- Defines here
- verdict, run_all, report, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/lab/run.py:1-192 · blob fce259052f298e4dc4f5139d6472c81811581093 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Explore Code intelligence lab: run every experiment, check determinism, write overlays, metrics and REPORT.md.
python3 tools/explore/lab/run.py [--only name,name] [--out /tmp/lab-out] [--graph build_graph.json]
Each experiment runs twice on the same input; the run refuses (exit 1) if the two overlays differ (a check that
examines nothing refuses: an empty overlay also fails). Outputs: <out>/<exp>.json (overlay), <out>/<exp>.metrics.json,
<out>/keys.json (id -> repo@commit:path, blob), <out>/lab.html, <out>/REPORT.md and a copy at lab/REPORT.md.
"""
import argparse
import datetime
import json
import os
import shutil
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import common # noqa: E402
import communities, importance, wafer, semantic, drift, links, pipeline # noqa: E402,E401
EXPERIMENTS = [communities, importance, wafer, semantic, drift, links, pipeline]
LAB_RULES = 'explore-lab-v1'
def verdict(name, m):
"""Fixed thresholds over the metrics; printed with the report. Returns (verdict, reason)."""
if name == 'communities':
q = m['modularity']
gain = q['louvain'] - q['repo_partition']
v = 'adds intelligence' if gain > 0.05 and m['cross_repo_communities_ge8_files'] >= 3 else 'marginal'
return v, 'Louvain Q %.3f vs repo partition %.3f (gain %.3f); %d cross-repo communities >= 8 files; NMI vs repo %.2f, topic %.2f' % (
q['louvain'], q['repo_partition'], gain, m['cross_repo_communities_ge8_files'],
m['agreement']['louvain']['repo']['nmi'], m['agreement']['louvain']['topic']['nmi'])
if name == 'importance':
p = m['top50_profile']['pagerank']
b = m['base_rates']
jac = m['top50_overlap_jaccard']['pagerank_vs_in_degree']
lift = p['production_core'] / max(1e-9, b['production_core'])
v = 'adds intelligence' if jac < 0.7 and lift > 1.3 else 'marginal'
return v, 'top-50 PageRank: %.0f%% production_core (base %.0f%%, lift %.2f), %.0f%% reachable, %.0f%% entry; Jaccard with in-degree top-50 %.2f; %d of 50 outside CORE_REPOS' % (
100 * p['production_core'], 100 * b['production_core'], lift, 100 * p['reachable'], 100 * p['entry'], jac,
m['pagerank_top50_outside_core_repos'])
if name == 'wafer':
L = m['layouts']
stable = L['hash_key']['mean_displacement'] == 0 and L['wafer_dies']['mean_displacement'] == 0
v = 'adds intelligence' if stable and min(L['force']['mean_displacement'], L['shelf']['mean_displacement']) > 0.02 else 'marginal'
return v, 'mean displacement of unchanged files (share of diameter): ' + ', '.join(
'%s %.4f' % (k, x['mean_displacement']) for k, x in L.items()) + '; edge/random length: ' + ', '.join(
'%s %.2f' % (k, x['edge_length_vs_random_pair']) for k, x in L.items())
if name == 'semantic':
d = m['silhouette_cosine'] - m['silhouette_permuted_labels']
v = 'adds intelligence' if d > 0.1 and m['clusters_spanning_ge5_repos'] >= 3 else 'marginal' if d > 0.03 else 'no'
a = m['agreement']
return v, 'silhouette %.3f vs %.3f permuted; NMI role %.2f (chance %.2f), topic %.2f, repo %.2f; %d clusters span >= 5 repos' % (
m['silhouette_cosine'], m['silhouette_permuted_labels'], a['role']['nmi'], a['role']['chance_nmi'],
a['topic']['nmi'], a['repo']['nmi'], m['clusters_spanning_ge5_repos'])
if name == 'drift':
v = 'adds intelligence' if m['unreached_with_reachable_near_copy'] >= 50 else 'marginal' if m['unreached_with_reachable_near_copy'] >= 10 else 'no'
return v, '%d families (%d cross-repo, %d files); %d of %d unreached files (%.1f%%; %.1f%% of fingerprinted unreached) have a reachable near-copy; %d family members not marked duplicate by build' % (
m['families'], m['cross_repo_families'], m['files_in_families'], m['unreached_with_reachable_near_copy'],
m['unreached_files'], 100 * m['share_of_unreached_with_reachable_copy'],
100 * m['share_of_fingerprinted_unreached_with_reachable_copy'], m['family_members_not_marked_duplicate_by_build'])
if name == 'links':
s = m['scorers']
best = max(s, key=lambda k: (s[k]['precision_at']['100'], k))
p100 = s[best]['precision_at']['100']
lift = p100 / max(1e-12, m['chance_precision'])
v = 'adds intelligence' if lift >= 20 and s[best]['auc'] >= 0.75 else 'marginal'
return v, 'best scorer %s: precision@100 %.2f, @%d %.3f, AUC %.3f (chance precision %.2g, lift %.0fx); Adamic-Adar AUC %.3f, data-only AUC %.3f; %d CANDIDATE journey links over %d gaps' % (
best, p100, m['hidden'], s[best]['precision_at'][str(m['hidden'])], s[best]['auc'], m['chance_precision'], lift,
s['adamic_adar']['auc'], s['data_items']['auc'], m['journey_candidates'], len(m['journey_gaps']))
if name == 'pipeline':
acc = m['accuracy_vs_rule_stage']
base = m['majority_baseline'][1]
v = 'adds intelligence' if acc > base + 0.1 else 'marginal' if acc > base else 'no'
return v, 'accuracy %.3f vs majority baseline %.3f (%s), NMI %.3f; %d cyclic SCCs holding %d files; max height %d' % (
acc, base, m['majority_baseline'][0], m['nmi_vs_rule_stage'], m['cyclic_sccs'], m['files_in_cycles'], m['max_height'])
return 'marginal', ''
RECOMMEND = """1. **Kuiper wafer view (law, not layout).** Add `wafer` as a third view in visualise.py, computed in the browser from
each file's key with `r = sqrt(u), theta = 2 pi frac(u x 2654435769 / 2^32)` inside a die per repository
(die on a hex spiral by permanent repo number). Store only a permanent repo number in build_graph.json
(`repos[].number`, assigned once, appended, never renumbered: Modular Star) and nothing per file: the
position is a pure function of `repo/path`. Only the key-derived laws (hash key, registry, dies) kept every
unchanged file exactly in place when 5% of the estate changed (force moved them 0.050 of the diameter,
sorted packing 0.063, rank spiral 0.320), and of those only the dies keep locality (edge length 0.28 of a
random pair vs 0.98 for a plain hash spiral).
2. **`community` field + colour mode.** Add per-file `community` (Louvain id, numbered by size) and top-level
`communities: [[id, label, size, hub_file]]` to build_graph.json and a `community` colour mode in the
visualiser; label from the three most over-represented name words. Louvain modularity is far above the
repo partition (see communities below) and several large communities span many repositories (e.g. a
"homepage versions atlas" working set across 17 repos), which neither repo nor topic colouring shows.
3. **Drift and safe-review layer.** Add `near_copies: [file ids]` and `canonical_copy` (fixed order: core repo >
reachable > dependents > newest timestamp) from Vedic struct-hash Jaccard, and a "drift edges" toggle plus a
"safe review" filter (unreached files with a reachable near-copy) to the visualiser. These are the
lowest-risk review CANDIDATES and the build's own `duplicate_of` misses most of them.
4. Also worth it: node size by PageRank (`rank` 0..1000, log-scaled) as a size toggle; CANDIDATE journey links
drawn dashed in journey pages only, never in `imports`. Not worth integrating now: the structural stage
(below the rule stage and the majority baseline) and the 2D SVD semantic map as a primary view (clusters are
useful as a colour, the map itself is a blob)."""
def run_all(only=None, out=common.OUT, graph=common.BUILD_GRAPH):
G = common.load(graph)
os.makedirs(out, exist_ok=True)
keys = {'schema': 'explore-lab-keys-v1', 'cut': G.cut, 'input_sha256': G.input_sha256,
'k': [G.key(i) for i in range(G.n)], 'blob': [G.blob.get((G.repo[i], G.path[i]), '') for i in range(G.n)]}
common.write_json(os.path.join(out, 'keys.json'), keys)
results = []
ok = True
for mod in EXPERIMENTS:
if only and mod.NAME not in only:
continue
t0 = time.time()
ov, metrics, findings = mod.run(G)
rt = time.time() - t0
ov2, metrics2, _ = mod.run(G)
det = common.digest(ov) == common.digest(ov2) and common.digest(metrics) == common.digest(metrics2)
nonempty = bool(ov.get('cols')) or bool(ov.get('edges'))
if not det or not nonempty:
ok = False
metrics = dict(metrics)
v, why = verdict(mod.NAME, metrics)
meta = {'exp': mod.NAME, 'rules': mod.RULES, 'lab_rules': LAB_RULES, 'hypothesis': mod.HYPOTHESIS,
'algorithm': mod.ALGORITHM, 'cut': G.cut, 'input_sha256': G.input_sha256,
'runtime_s': round(rt, 2), 'deterministic': det, 'overlay_sha256': common.digest(ov),
'overlay_bytes': len(json.dumps(ov, separators=(',', ':'))), 'verdict': v, 'verdict_basis': why,
'metrics': metrics, 'findings': findings}
common.write_json(os.path.join(out, mod.NAME + '.json'), ov)
common.write_json(os.path.join(out, mod.NAME + '.metrics.json'), meta, compact=False)
results.append(meta)
print('%-12s %6.1fs det=%s %s | %s' % (mod.NAME, rt, det, v, why), flush=True)
rep = report(G, results)
with open(os.path.join(out, 'REPORT.md'), 'w', encoding='utf-8') as fh:
fh.write(rep)
if not only:
shutil.copy(os.path.join(out, 'REPORT.md'), os.path.join(HERE, 'REPORT.md'))
html = os.path.join(HERE, 'lab.html')
if os.path.exists(html):
shutil.copy(html, os.path.join(out, 'lab.html'))
return ok, results
def report(G, results):
now = datetime.datetime.now().astimezone().isoformat(timespec='seconds')
L = ['# Explore Code intelligence lab: report', '',
'Generated %s by `tools/explore/lab/run.py` (%s). Input: `build_graph.json` cut `%s`, sha256 `%s`, '
'%d files, %d resolved edges (comment-url excluded), build rules `%s`.' % (
now, LAB_RULES, G.cut, G.input_sha256, G.n, len(G.edges), G.rules_version), '',
'The first law applies: every file named here carries its key `repo@commit:path` (commit = the clone the cut '
'read) and its file id in this cut; `keys.json` maps every id. Every number is recomputed by `run.py`; each '
'experiment ran twice and its overlay digest compared (determinism). Anything inferred, not measured, is '
'labelled CANDIDATE. Verdicts come from the fixed thresholds in `run.py: verdict()`, not from judgement.', '',
'## Summary', '', '| experiment | verdict | key metric | runtime | deterministic |', '|---|---|---|---|---|']
for r in results:
L.append('| %s | **%s** | %s | %.1f s | %s |' % (r['exp'], r['verdict'], r['verdict_basis'].split(';')[0],
r['runtime_s'], 'yes' if r['deterministic'] else 'NO'))
L += ['', '## Recommendations: what to integrate into build.py / visualise.py next', '', RECOMMEND, '']
for r in results:
L += ['## %s: %s' % (r['exp'], r['verdict']), '',
'- Hypothesis: ' + r['hypothesis'], '- Algorithm: ' + r['algorithm'], '- Rules: `%s`' % r['rules'],
'- Overlay: `/tmp/lab-out/%s.json` (%d bytes, sha256 `%s`), metrics `/tmp/lab-out/%s.metrics.json`' % (
r['exp'], r['overlay_bytes'], r['overlay_sha256'][:16], r['exp']),
'- Runtime %.2f s; deterministic: %s' % (r['runtime_s'], r['deterministic']),
'- Verdict basis: ' + r['verdict_basis'], '', 'Findings (keys carried):', '']
L += ['- ' + f for f in r['findings']] or ['- none']
L += ['', '<details><summary>metrics</summary>', '', '```json',
json.dumps(r['metrics'], indent=1, ensure_ascii=False)[:6000], '```', '</details>', '']
L += ['## Demo', '', '`/tmp/lab-out/lab.html` (copy of `tools/explore/lab/lab.html`): serve `/tmp` over http and open '
'`/lab-out/lab.html`; it loads `/site7/explore-code/visual/graph.json` and the overlays. Views: wafer, '
'communities, importance size, semantic map, drift edges, predicted links. Screenshots in `/tmp/lab-out/shots/`.', '']
return '\n'.join(L)
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument('--only', default='')
ap.add_argument('--out', default=common.OUT)
ap.add_argument('--graph', default=common.BUILD_GRAPH)
a = ap.parse_args(argv)
ok, _ = run_all([x for x in a.only.split(',') if x] or None, a.out, a.graph)
if not ok:
print('REFUSED: an experiment was not deterministic or produced an empty overlay', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())Semantic
A Python module in the lab folder of Cosmic that reads words, substations and cables, using k-means.
storagecosmic / tools/explore/lab/semantic.py · lines 1–206 of 206
- What it does
- It loads words, substations and cables. Defines 6 functions or classes, including file_terms, tfidf, rsvd, kmeans, silhouette. Uses libraries math, os, collections, numpy, duckdb. Side effects: uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: substations, cables.
- Inputs & outputs
- In: Parquet file words.parquet; DuckDB queries.
- Downstream impact
- Used directly by 2 files: Explore — Lab (cosmic); Test Lab (cosmic). Reached from 4 other entry points, including Extras (cosmic); Ship (cosmic); Test Extras (cosmic).
- What it achieves
- It is built from the file terms helper (`file_terms`), the tfidf step (`tfidf`) and the rsvd step (`rsvd`). Experiment 4: semantic map. TF-IDF over identifier words, truncated SVD (numpy), spherical k-means.
- Why it matters
- Imported by Explore — Lab. Checked by Test Lab.
- Application
- cosmic · tools/explore/lab · Python module
- Uses
- Explore — Lab (import), math, os, collections, numpy, duckdb
- Used by
- imported by Explore — Lab (import), imported by Test Lab (import)
- Produces
- file_terms, tfidf, rsvd, kmeans, silhouette, run
- Defines here
- file_terms, tfidf, rsvd, kmeans, silhouette, run
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/lab/semantic.py:1-206 · blob 3fa3d05995abfa6a8169623302fac62d150de915 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: storage · domain stage: unknown · users: none · canonical: supporting_data
"""Experiment 4: semantic map. TF-IDF over identifier words, truncated SVD (numpy), spherical k-means."""
import math
import os
from collections import Counter
import numpy as np
from common import DATA_DIR, SEED, STOP, nmi, overlay, r4, split_ident
NAME = 'semantic'
RULES = 'lab-semantic-v1 (tf-idf sublinear, df >= 3 and <= 25%%, vocab <= 4000; randomized SVD k=40, 3 power iterations, seed %d; spherical k-means k=16, k-means++; silhouette cosine on 2000 sampled files)' % SEED
HYPOTHESIS = ('The words a file defines and is named with place it in a meaning space whose clusters are coherent '
'(silhouette well above 0) and cut across repositories, giving a map by purpose that paths do not.')
ALGORITHM = ('Words per file: name words, defined names and signatures (camelCase/snake split), identifiers from '
'words.parquet, normalised by a small glossary (lon/lng -> longitude, ...). TF-IDF (1 + log tf) x '
'idf, rows L2-normalised; randomized truncated SVD to 40 dimensions; spherical k-means (k=16) on the '
'normalised reduced vectors; 2D: raw SVD components 2 and 3 (x, y) and a cluster-island map (mx, my: centroid anchors by classical MDS, files pulled to the anchors they resemble). Clusters named by their top centroid '
'words. Agreement by NMI against role, topic, repo, and against a label permutation (chance).')
GLOSSARY = {'lng': 'longitude', 'lon': 'longitude', 'long': 'longitude', 'lat': 'latitude', 'dist': 'distance',
'km': 'distance', 'bess': 'battery', 'batt': 'battery', 'pv': 'solar', 'ohl': 'overhead', 'sub': 'substation',
'subs': 'substation', 'substations': 'substation', 'kv': 'voltage', 'volt': 'voltage', 'volts': 'voltage',
'amp': 'current', 'amps': 'current', 'btn': 'button', 'el': 'element', 'elem': 'element', 'cfg': 'config',
'conf': 'config', 'img': 'image', 'msg': 'message', 'req': 'request', 'res': 'response', 'resp': 'response',
'ctx': 'context', 'fn': 'function', 'num': 'number', 'str': 'string', 'idx': 'index', 'coords': 'coordinate',
'coord': 'coordinate', 'cables': 'cable', 'routes': 'route', 'maps': 'map', 'tiles': 'tile', 'layers': 'layer',
'points': 'point', 'lines': 'line', 'nodes': 'node', 'edges': 'edge', 'files': 'file', 'prices': 'price'}
EXTRA_STOP = STOP | set('function const var let return value values item items list obj object args arg options opts '
'self cls init type name names text string number true false none null undefined'.split())
def file_terms(G):
ident = {}
wp = os.path.join(DATA_DIR, 'words.parquet')
if os.path.exists(wp):
import duckdb
for repo, path, word in duckdb.sql("select repo, path, word from '%s' order by repo, path, line, word" % wp).fetchall():
ident.setdefault((repo, path), []).append(word)
docs = []
for i, f in enumerate(G.files):
ws = list(f.get('name_words') or [])
for d in (f.get('defines') or []):
ws += split_ident(d)
for s in (f.get('signatures') or []):
ws += split_ident(s)
for w in ident.get((G.repo[i], G.path[i]), []):
ws += split_ident(w)
out = []
for w in ws:
w = GLOSSARY.get(w, w)
if len(w) > 2 and w not in EXTRA_STOP and not w.isdigit():
out.append(w)
docs.append(out)
return docs
def tfidf(docs, min_df=3, max_df_share=0.25, max_vocab=4000):
n = len(docs)
df = Counter()
for d in docs:
df.update(set(d))
vocab = sorted((w for w, c in df.items() if c >= min_df and c <= max_df_share * n), key=lambda w: (-df[w], w))[:max_vocab]
vocab.sort()
vix = {w: i for i, w in enumerate(vocab)}
X = np.zeros((n, len(vocab)), dtype=np.float64)
for r, d in enumerate(docs):
for w, c in Counter(d).items():
j = vix.get(w)
if j is not None:
X[r, j] = (1 + math.log(c)) * math.log((1 + n) / (1 + df[w]))
nr = np.linalg.norm(X, axis=1)
X[nr > 0] /= nr[nr > 0, None]
return X, vocab, nr > 0
def rsvd(X, k, seed=SEED, power=3):
rng = np.random.default_rng(seed)
Om = rng.standard_normal((X.shape[1], min(X.shape[1], k + 10)))
Y = X @ Om
for _ in range(power):
Y, _ = np.linalg.qr(Y)
Y = X @ (X.T @ Y)
Q, _ = np.linalg.qr(Y)
U, S, Vt = np.linalg.svd(Q.T @ X, full_matrices=False)
U = Q @ U
# sign convention: largest |loading| positive, for determinism across BLAS
sgn = np.sign(Vt[np.arange(Vt.shape[0]), np.abs(Vt).argmax(1)])
sgn[sgn == 0] = 1
return U[:, :k] * sgn[:k], S[:k], Vt[:k] * sgn[:k, None]
def kmeans(Z, k, seed=SEED, iters=60):
"""Spherical k-means with k-means++ seeding. Z rows L2-normalised. Returns labels, centroids."""
rng = np.random.default_rng(seed)
n = len(Z)
k = min(k, n)
C = [Z[rng.integers(n)]]
for _ in range(1, k):
d = 1 - np.max(Z @ np.array(C).T, axis=1)
d = np.maximum(d, 0) ** 2
p = d / d.sum() if d.sum() > 0 else np.full(n, 1.0 / n)
C.append(Z[rng.choice(n, p=p)])
C = np.array(C)
lab = np.full(n, -1)
for _ in range(iters):
new = np.argmax(Z @ C.T, axis=1)
if np.array_equal(new, lab):
break
lab = new
for c in range(k):
m = Z[lab == c]
if len(m):
v = m.sum(0)
C[c] = v / (np.linalg.norm(v) or 1)
return lab, C
def silhouette(Z, lab, sample=2000, seed=SEED):
"""Mean silhouette, cosine distance, on a seeded sample (distances among the sample only)."""
rng = np.random.default_rng(seed)
idx = np.sort(rng.choice(len(Z), min(sample, len(Z)), replace=False))
S = Z[idx]
L = lab[idx]
D = 1 - S @ S.T
ks = np.unique(L)
if len(ks) < 2:
return 0.0
vals = []
for i in range(len(idx)):
own = L == L[i]
cnt = own.sum() - 1
if cnt == 0:
vals.append(0.0)
continue
a = (D[i, own].sum()) / cnt
b = min(D[i, L == c].mean() for c in ks if c != L[i])
vals.append((b - a) / max(a, b) if max(a, b) > 0 else 0.0)
return float(np.mean(vals))
def run(G, k=16, dims=40):
docs = file_terms(G)
X, vocab, has = tfidf(docs)
U, S, Vt = rsvd(X[has], dims)
Z = U * S
nz = np.linalg.norm(Z, axis=1)
Zn = Z / np.where(nz > 0, nz, 1)[:, None]
lab, C = kmeans(Zn, k)
sil = silhouette(Zn, lab)
rng = np.random.default_rng(SEED)
perm = rng.permutation(lab)
sil_perm = silhouette(Zn, perm)
hidx = np.where(has)[0]
roles = [G.files[i].get('role', '') for i in hidx]
topics = [G.topic[i] for i in hidx]
repos = [G.repo[i] for i in hidx]
agree = {nm: {'nmi': r4(nmi(lab, ref)), 'chance_nmi': r4(nmi(perm, ref))}
for nm, ref in (('role', roles), ('topic', topics), ('repo', repos))}
# names from centroid in word space: mean tf-idf of members
legend = []
full_lab = [-1] * G.n
for j, i in enumerate(hidx):
full_lab[int(i)] = int(lab[j])
Xh = X[has]
for c in range(len(C)):
m = lab == c
cen = Xh[m].mean(0) if m.any() else np.zeros(len(vocab))
top = [vocab[t] for t in np.argsort(-cen, kind='stable')[:4]]
rc = Counter(repos[j] for j in np.where(m)[0])
legend.append([c, ' '.join(top), int(m.sum()), len(rc), rc.most_common(1)[0][0] if rc else ''])
x = [None] * G.n
y = [None] * G.n
for j, i in enumerate(hidx):
x[int(i)] = round(float(U[j, 1] * S[1]), 4)
y[int(i)] = round(float(U[j, 2] * S[2]), 4)
# cluster-island map: centroid anchors by classical MDS of centroid cosine distances, each file drawn
# towards the anchors it resembles (softmax of similarity), plus a small offset from SVD components 2-3
Dc = 1 - C @ C.T
J = np.eye(len(C)) - 1.0 / len(C)
B = -0.5 * J @ (Dc ** 2) @ J
ev, evec = np.linalg.eigh(B)
o = np.argsort(-ev, kind='stable')[:2]
A = evec[:, o] * np.sqrt(np.maximum(ev[o], 0))
A = A * np.sign(A[np.abs(A).argmax(0), [0, 1]])
sim = Zn @ C.T
w = np.exp(30 * (sim - sim.max(1, keepdims=True)))
w /= w.sum(1, keepdims=True)
loc = U[:, 1:3] * S[1:3]
loc = loc / (np.abs(loc).max(0) + 1e-12)
M = w @ A + 0.05 * loc * (np.abs(A).max())
mx = [None] * G.n
my = [None] * G.n
for j, i in enumerate(hidx):
mx[int(i)] = round(float(M[j, 0]), 4)
my[int(i)] = round(float(M[j, 1]), 4)
var = (S ** 2) / max(1e-12, (X[has] ** 2).sum())
metrics = {'files_with_words': int(has.sum()), 'vocabulary': len(vocab), 'k': k, 'svd_dims': dims,
'explained_variance_40d': r4(var.sum()), 'explained_variance_2d_map': r4(var[1:3].sum()),
'silhouette_cosine': r4(sil), 'silhouette_permuted_labels': r4(sil_perm), 'agreement': agree,
'clusters_spanning_ge5_repos': sum(1 for l in legend if l[3] >= 5),
'cluster_sizes': sorted((l[2] for l in legend), reverse=True)}
findings = ['semantic cluster %d "%s": %d files in %d repos (top %s)' % tuple(l) for l in
sorted(legend, key=lambda l: -l[3])[:5]]
ov = overlay(G, NAME, RULES, cols={'x': x, 'y': y, 'mx': mx, 'my': my, 'k': full_lab},
legend={'k': ['id', 'top_words', 'size', 'repos', 'top_repo'], 'rows': legend})
return ov, metrics, findingsShoot
A Python command-line tool in the lab folder of Cosmic that renders `lab.html` in headless Chromium (Playwright), fail on console errors, screenshot every view.
rendercosmic / tools/explore/lab/shoot.py · lines 1–58 of 58 · Entry point · pattern Quiet (shared by 9 files)
- What it does
- It draws its content. Defines main, Quiet, log_message. Uses libraries argparse, functools, http.server, json, os. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Inputs & outputs
- In: command-line arguments. Out: canvas drawing.
- 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 quiet class (`Quiet`). Defines `Quiet` and `log_message`. It accepts `--root` and `--out`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · tools/explore/lab · Python CLI
- Uses
- argparse, functools, http.server, json, os, sys, threading, playwright.sync_api
- Used by
- none found
- Produces
- main
- Defines here
- main, Quiet, log_message
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/lab/shoot.py:1-58 · blob d3e3cd6242ea4a72156e0a413b2ad005fc5dce60 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Render lab.html in headless Chromium (Playwright), fail on console errors, screenshot every view.
python3 tools/explore/lab/shoot.py [--root /tmp] [--out /tmp/lab-out/shots]
Serves --root over http on a free local port; the page is at /lab-out/lab.html.
"""
import argparse
import functools
import http.server
import json
import os
import sys
import threading
VIEWS = ['wafer', 'communities', 'importance', 'semantic', 'drift', 'links']
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument('--root', default='/tmp')
ap.add_argument('--out', default='/tmp/lab-out/shots')
a = ap.parse_args(argv)
os.makedirs(a.out, exist_ok=True)
class Quiet(http.server.SimpleHTTPRequestHandler):
def log_message(self, *args):
pass
handler = functools.partial(Quiet, directory=a.root)
srv = http.server.ThreadingHTTPServer(('127.0.0.1', 0), handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = 'http://127.0.0.1:%d/lab-out/lab.html' % srv.server_address[1]
from playwright.sync_api import sync_playwright
errors, result = [], {}
with sync_playwright() as p:
b = p.chromium.launch()
pg = b.new_page(viewport={'width': 1500, 'height': 900})
pg.on('console', lambda m: errors.append('console %s: %s' % (m.type, m.text)) if m.type == 'error' else None)
pg.on('pageerror', lambda e: errors.append('pageerror: %s' % e))
pg.on('requestfailed', lambda r: errors.append('requestfailed: %s' % r.url))
for v in VIEWS:
pg.goto(url + '#view=' + v)
pg.wait_for_selector('html[data-ready="1"]', timeout=30000)
pg.wait_for_timeout(400)
on = pg.eval_on_selector('#views button.on', 'b => b.dataset.v')
lit = pg.evaluate('''() => { const c = document.getElementById('cv'), x = c.getContext('2d');
const d = x.getImageData(0, 0, c.width, c.height).data; let n = 0;
for (let i = 0; i < d.length; i += 16) if (d[i] + d[i+1] + d[i+2] > 60) n++; return n; }''')
pg.mouse.move(750, 450)
shot = os.path.join(a.out, '%s.png' % v)
pg.screenshot(path=shot)
result[v] = {'active_button': on, 'lit_pixels_sampled': lit, 'shot': shot}
b.close()
srv.shutdown()
ok = not errors and all(r['active_button'] == v and r['lit_pixels_sampled'] > 500 for v, r in result.items())
print(json.dumps({'url': url, 'ok': ok, 'errors': errors, 'views': result}, indent=1))
return 0 if ok else 1
if __name__ == '__main__':
sys.exit(main())Test Lab
A test in the explore folder of Cosmic that checks Explore — Lab and Communities, using Louvain and PageRank.
testcosmic / tools/explore/lab/test_lab.py · lines 1–204 of 204 · Entry point · pattern Wafer (shared by 2 files)
- What it does
- It tests cables. Defines 31 functions or classes, including clique, Agreement, test_identical_partitions, test_known_values, test_modularity_two_triangles. Uses libraries math, os, sys, unittest, numpy.
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- It is built from the clique step (`clique`), the agreement class (`Agreement`) and the communities class (`Communities`). Unit tests for the intelligence lab: tiny synthetic graphs with known answers, no network, no estate files.
- Why it matters
- Guards the behaviour of Explore — Lab, Communities and Drift.
- Application
- cosmic · tools/explore/lab · test
- Uses
- Explore — Lab (import), Communities (import), Drift (import), Importance (import), Links (import), Pipeline (import), Semantic (import), Wafer (import), math, os, sys, unittest, numpy
- Used by
- none found
- Produces
- clique, Agreement, Communities, Importance, Wafer, Pipeline, LinkPrediction, Semantic, Drift
- Defines here
- clique, Agreement, test_identical_partitions, test_known_values, test_modularity_two_triangles, Communities, test_two_cliques_louvain, test_two_cliques_label_propagation, test_run_and_determinism, Importance, test_star_hub_top_pagerank, test_betweenness_path, test_kcore, Wafer, test_hash_key_invariant_under_insertion, test_registry_and_dies_invariant_rank_not, test_law_and_hex, test_procrustes_recovers_rotation, Pipeline, test_tarjan, test_layers, LinkPrediction, test_common_neighbours_and_adamic_adar, test_precision_at, Semantic, test_kmeans_silhouette_separable, test_rsvd_matches_svd, test_split_ident, Drift, test_families
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/lab/test_lab.py:1-204 · blob 35ca056534edf177aef3829dd12cf19272331edf · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Unit tests for the intelligence lab: tiny synthetic graphs with known answers, no network, no estate files.
python3 -m unittest tools/explore/lab/test_lab.py
"""
import math
import os
import sys
import unittest
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import common # noqa: E402
import communities # noqa: E402
import drift # noqa: E402
import importance # noqa: E402
import links # noqa: E402
import pipeline # noqa: E402
import semantic # noqa: E402
import wafer # noqa: E402
def clique(nodes):
return [(a, b) for i, a in enumerate(nodes) for b in nodes[i + 1:]]
TWO_CLIQUES = clique(list(range(6))) + clique(list(range(6, 12))) + [(5, 6)]
class Agreement(unittest.TestCase):
def test_identical_partitions(self):
self.assertAlmostEqual(common.nmi([0, 0, 1, 1], [5, 5, 9, 9]), 1.0)
self.assertAlmostEqual(common.ari([0, 0, 1, 1], [5, 5, 9, 9]), 1.0)
def test_known_values(self):
# independent split: MI = 0; ARI of this pair is exactly -0.5
self.assertAlmostEqual(common.nmi([0, 0, 1, 1], [0, 1, 0, 1]), 0.0)
self.assertAlmostEqual(common.ari([0, 0, 1, 1], [0, 1, 0, 1]), -0.5)
# a=[0,0,0,1,1,1], b=[0,0,1,1,2,2]: ARI = 0.24242...
self.assertAlmostEqual(common.ari([0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 2, 2]), 0.242424, places=5)
def test_modularity_two_triangles(self):
nbr = common.adjacency(6, clique([0, 1, 2]) + clique([3, 4, 5]))
self.assertAlmostEqual(common.modularity(nbr, [0, 0, 0, 1, 1, 1]), 0.5)
class Communities(unittest.TestCase):
def test_two_cliques_louvain(self):
lab = communities.louvain(12, TWO_CLIQUES)
self.assertEqual(len(set(lab)), 2)
self.assertEqual(len(set(lab[:6])), 1)
self.assertEqual(len(set(lab[6:])), 1)
def test_two_cliques_label_propagation(self):
lab = communities.label_propagation(common.adjacency(12, TWO_CLIQUES))
self.assertEqual(len(set(lab[:6])), 1)
self.assertEqual(len(set(lab[6:])), 1)
self.assertNotEqual(lab[0], lab[11])
def test_run_and_determinism(self):
G = common.synthetic(14, TWO_CLIQUES, name_words=[['cable', 'route']] * 6 + [['solar', 'panel']] * 6 + [[], []])
o1, m1, _ = communities.run(G)
o2, m2, _ = communities.run(G)
self.assertEqual(common.digest(o1), common.digest(o2))
self.assertEqual(o1['cols']['c'][12], -1) # isolated file has no community
self.assertGreater(m1['modularity']['louvain'], 0.4)
self.assertIn('cable', ' '.join(r[1] for r in o1['legend']['rows']))
class Importance(unittest.TestCase):
def test_star_hub_top_pagerank(self):
edges = [(i, 0) for i in range(1, 9)] # every leaf imports the hub
pr = importance.pagerank(9, edges)
self.assertEqual(int(np.argmax(pr)), 0)
self.assertAlmostEqual(pr.sum(), 1.0)
rpr = importance.pagerank(9, [(b, a) for a, b in edges])
self.assertNotEqual(int(np.argmax(rpr)), 0)
def test_betweenness_path(self):
out = [[1], [2], [3], []] # 0 -> 1 -> 2 -> 3
bc = importance.betweenness(4, out, [0, 1, 2, 3])
self.assertEqual(list(bc), [0.0, 2.0, 2.0, 0.0])
def test_kcore(self):
nbr = common.adjacency(5, clique([0, 1, 2, 3]) + [(3, 4)])
self.assertEqual(importance.kcore(nbr), [3, 3, 3, 3, 1])
class Wafer(unittest.TestCase):
KEYS = [('r%d' % (i % 3), 'f%03d.js' % i) for i in range(60)]
def test_hash_key_invariant_under_insertion(self):
a = wafer.hash_key(self.KEYS)
b = wafer.hash_key(self.KEYS + [('r1', 'new.js'), ('r9', 'x.js')])
for k in self.KEYS:
self.assertEqual(a[k], b[k])
def test_registry_and_dies_invariant_rank_not(self):
reg = {}
a = wafer.registry_spiral(self.KEYS, reg)
b = wafer.registry_spiral(self.KEYS + [('r0', 'a000.js')], reg)
self.assertTrue(all(a[k] == b[k] for k in self.KEYS))
rr = {}
da, _ = wafer.wafer_dies(self.KEYS, rr)
db, _ = wafer.wafer_dies(self.KEYS + [('r0', 'zz.js')], rr)
self.assertTrue(all(da[k] == db[k] for k in self.KEYS))
ra = wafer.rank_spiral(self.KEYS)
rb = wafer.rank_spiral(self.KEYS + [('r0', 'a000.js')]) # sorts first: shifts every ordinal
self.assertTrue(any(ra[k] != rb[k] for k in self.KEYS))
def test_law_and_hex(self):
self.assertEqual(wafer.law(0), (0.0, 0.0))
self.assertAlmostEqual(math.hypot(*wafer.law(49)), 7.0)
cells = [wafer.hex_cell(i) for i in range(37)]
self.assertEqual(len({(round(x, 6), round(y, 6)) for x, y in cells}), 37)
d = min(math.dist(p, q) for i, p in enumerate(cells) for q in cells[:i])
self.assertAlmostEqual(d, 1.0)
def test_procrustes_recovers_rotation(self):
rng = np.random.default_rng(1)
A = rng.standard_normal((20, 2))
th = 0.7
R = np.array([[math.cos(th), -math.sin(th)], [math.sin(th), math.cos(th)]])
B = 2.5 * A @ R + 3
self.assertLess(np.abs(wafer.procrustes(A, B) - A).max(), 1e-9)
class Pipeline(unittest.TestCase):
def test_tarjan(self):
out = [[1], [2], [0, 3], [4], [3], []]
comp, nc = pipeline.tarjan(6, out)
self.assertEqual(nc, 3)
self.assertEqual(len({comp[0], comp[1], comp[2]}), 1)
self.assertEqual(comp[3], comp[4])
self.assertNotEqual(comp[0], comp[3])
self.assertGreater(comp[0], comp[3]) # successors numbered first (reverse topological)
self.assertNotEqual(comp[5], comp[0])
def test_layers(self):
out = [[1], [2], [], [2]] # page 0 -> module 1 -> leaf 2 ; 3 -> 2
comp, nc, h, d = pipeline.layers(4, out)
self.assertEqual([h[comp[i]] for i in range(4)], [2, 1, 0, 1])
self.assertEqual([d[comp[i]] for i in range(4)], [0, 1, 2, 0])
class LinkPrediction(unittest.TestCase):
def test_common_neighbours_and_adamic_adar(self):
# 0 and 1 share neighbours 2, 3, 4; 5 hangs off 4 only
nbr = common.adjacency(6, [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (4, 5)])
sc = links.two_hop(nbr)
best = max(sc, key=lambda k: (sc[k][1], k))
self.assertEqual(best, (0, 1))
self.assertEqual(sc[(0, 1)][0], 3)
self.assertAlmostEqual(sc[(0, 1)][1], 2 / math.log(2) + 1 / math.log(3))
self.assertNotIn((0, 2), sc) # existing edges are not proposed
def test_precision_at(self):
p = links.precision_at([(0, 1), (2, 3), (4, 5)], {(0, 1), (4, 5)}, [1, 2, 3])
self.assertEqual(p, {'1': 1.0, '2': 0.5, '3': 0.6667})
class Semantic(unittest.TestCase):
def test_kmeans_silhouette_separable(self):
rng = np.random.default_rng(3)
a = rng.normal([1, 0, 0], 0.05, (30, 3))
b = rng.normal([0, 1, 0], 0.05, (30, 3))
Z = np.vstack([a, b])
Z /= np.linalg.norm(Z, axis=1, keepdims=True)
lab, _ = semantic.kmeans(Z, 2)
self.assertEqual(len(set(lab[:30])), 1)
self.assertNotEqual(lab[0], lab[59])
self.assertGreater(semantic.silhouette(Z, lab), 0.8)
lab2, _ = semantic.kmeans(Z, 2)
self.assertTrue(np.array_equal(lab, lab2))
def test_rsvd_matches_svd(self):
rng = np.random.default_rng(4)
X = rng.standard_normal((40, 12))
_, S, _ = semantic.rsvd(X, 5)
self.assertTrue(np.allclose(S, np.linalg.svd(X, compute_uv=False)[:5], rtol=1e-6))
def test_split_ident(self):
self.assertEqual(common.split_ident('distanceKm_toXMLParser2'), ['distance', 'km', 'to', 'xml', 'parser'])
class Drift(unittest.TestCase):
def test_families(self):
sets = {0: {'a', 'b', 'c', 'd'}, 1: {'a', 'b', 'c', 'e'}, 2: {'x', 'y'}, 3: {'a', 'b', 'c', 'd'}}
pairs, fams = drift.families(sets)
self.assertEqual(fams, [[0, 1, 3]])
self.assertAlmostEqual(pairs[(0, 3)][1], 1.0)
def test_canonical_prefers_core_then_reachable(self):
G = common.synthetic(3, [], repo=['side', 'core', 'side'], reachable=[True, False, True],
path=['a/202601010000/x.js', 'b/x.js', 'a/202612010000/x.js'])
G.core_repos = {'core'}
self.assertEqual(drift.canonical(G, [0, 1, 2]), 1)
G.core_repos = set()
self.assertEqual(drift.canonical(G, [0, 1, 2]), 2) # reachable tie -> newest timestamp
if __name__ == '__main__':
unittest.main()