In this section
- Importance transform · cosmic / tools/explore/lab/importance.py lines 1–159
- Lab render · cosmic / tools/explore/lab/lab.html lines 1–243
- Links transform · cosmic / tools/explore/lab/links.py lines 1–223
Importance
A Python module in the lab folder of Cosmic that uses PageRank. It is built from the pagerank step (`pagerank`), the betweenness step (`betweenness`) and the kcore step (`kcore`).
transformcosmic / tools/explore/lab/importance.py · lines 1–159 of 159 · pattern pagerank (shared by 2 files)
- What it does
- It calculates its inputs. Defines 8 functions or classes, including pagerank, betweenness, kcore, quant, topk. Uses libraries random, collections, numpy, heapq.
- 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
- Experiment 2: importance by PageRank, reverse PageRank, sampled betweenness and k-core.
- Why it matters
- Imported by Explore — Lab. Checked by Test Lab.
- Application
- cosmic · tools/explore/lab · Python module
- Uses
- Explore — Lab (import), random, collections, numpy, heapq
- Used by
- imported by Explore — Lab (import), imported by Test Lab (import)
- Produces
- pagerank, betweenness, kcore, quant, topk, spearman, run
- Defines here
- pagerank, betweenness, kcore, quant, topk, spearman, run, profile
- 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/importance.py:1-159 · blob 42cd2630bf3483cb90eac562605d56cc325935f9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Experiment 2: importance by PageRank, reverse PageRank, sampled betweenness and k-core."""
import random
from collections import deque
import numpy as np
from common import SEED, overlay, r4
NAME = 'importance'
RULES = 'lab-importance-v1 (pagerank d=0.85 over all resolved edges and over load edges only (no link/estate-url) tol 1e-10, dangling uniform; betweenness Brandes on 400 seeded sources; k-core undirected)'
HYPOTHESIS = ('Link-analysis ranks pick out the estate\'s load-bearing files better than counting dependents, and '
'surface important files outside CORE_REPOS that a reader would otherwise miss.')
ALGORITHM = ('Directed graph importer -> imported (comment-url excluded). PageRank flows importance to what is used '
'("used by important things"); reverse PageRank on the reversed graph ranks files that depend on many '
'(orchestrators, pages). Betweenness: Brandes from 400 seeded sources, scaled n/400 (an estimate). '
'k-core: peeling on the undirected graph. Overlay sizes are log-scaled ranks quantised 0..1000.')
def pagerank(n, edges, d=0.85, tol=1e-10, max_iter=200):
if n == 0:
return np.zeros(0)
src = np.array([a for a, _ in edges], dtype=np.int64)
dst = np.array([b for _, b in edges], dtype=np.int64)
outdeg = np.bincount(src, minlength=n).astype(np.float64) if len(edges) else np.zeros(n)
pr = np.full(n, 1.0 / n)
dangling = outdeg == 0
w = np.zeros(len(src))
if len(src):
w = 1.0 / outdeg[src]
for _ in range(max_iter):
new = np.full(n, (1 - d) / n + d * pr[dangling].sum() / n)
if len(src):
new += d * np.bincount(dst, weights=pr[src] * w, minlength=n)
if np.abs(new - pr).sum() < tol:
pr = new
break
pr = new
return pr / pr.sum()
def betweenness(n, out_adj, sources):
"""Brandes (unweighted, directed) restricted to the given sources; unscaled."""
bc = np.zeros(n)
for s in sources:
stack = []
pred = {}
sigma = {s: 1.0}
dist = {s: 0}
q = deque([s])
while q:
v = q.popleft()
stack.append(v)
for w in out_adj[v]:
if w not in dist:
dist[w] = dist[v] + 1
q.append(w)
if dist[w] == dist[v] + 1:
sigma[w] = sigma.get(w, 0.0) + sigma[v]
pred.setdefault(w, []).append(v)
delta = {}
while stack:
w = stack.pop()
for v in pred.get(w, ()):
delta[v] = delta.get(v, 0.0) + sigma[v] / sigma[w] * (1 + delta.get(w, 0.0))
if w != s:
bc[w] += delta.get(w, 0.0)
return bc
def kcore(nbr):
"""Core number of every node (lazy-heap peeling)."""
import heapq
n = len(nbr)
deg = [len(l) for l in nbr]
heap = [(d, i) for i, d in enumerate(deg)]
heapq.heapify(heap)
removed = [False] * n
core = [0] * n
k = 0
while heap:
d, v = heapq.heappop(heap)
if removed[v] or d != deg[v]:
continue
k = max(k, d)
core[v] = k
removed[v] = True
for w in nbr[v]:
if not removed[w]:
deg[w] -= 1
heapq.heappush(heap, (deg[w], w))
return core
def quant(x):
x = np.log1p(np.asarray(x, dtype=np.float64) / max(1e-300, float(np.min(x[x > 0])) if np.any(x > 0) else 1.0))
m = x.max() if len(x) else 0
return [int(v) for v in np.round(1000 * x / m)] if m > 0 else [0] * len(x)
def topk(score, k):
return [int(i) for i in sorted(range(len(score)), key=lambda i: (-score[i], i))[:k]]
def spearman(a, b):
ra = np.argsort(np.argsort(-np.asarray(a), kind='stable'), kind='stable')
rb = np.argsort(np.argsort(-np.asarray(b), kind='stable'), kind='stable')
return float(np.corrcoef(ra, rb)[0, 1]) if len(a) > 1 else 1.0
def run(G, n_sources=400):
n = G.n
pr = pagerank(n, G.edges)
rpr = pagerank(n, [(b, a) for a, b in G.edges])
load = sorted({(int(e[0]), int(e[1])) for e in G.raw.get('edges', [])
if e[2] not in ('comment-url', 'link', 'estate-url') and e[0] != e[1]})
prl = pagerank(n, load)
rng = random.Random(SEED)
active = [i for i in range(n) if G.out_adj[i]]
src = sorted(rng.sample(active, min(n_sources, len(active)))) if active else []
bc = betweenness(n, G.out_adj, src) * (len(active) / max(1, len(src)))
core = kcore(G.nbr)
indeg = np.array([len(l) for l in G.in_adj], dtype=float)
entry = [bool(f.get('entry')) for f in G.files]
reach = [bool(f.get('reachable')) for f in G.files]
incore = [G.repo[i] in G.core_repos for i in range(n)]
prod = [f.get('canonical_status') == 'production_core' for f in G.files]
K = 50
def profile(top):
return {'entry': r4(np.mean([entry[i] for i in top])), 'reachable': r4(np.mean([reach[i] for i in top])),
'core_repo': r4(np.mean([incore[i] for i in top])),
'production_core': r4(np.mean([prod[i] for i in top]))}
tops = {'pagerank': topk(pr, K), 'pagerank_load_only': topk(prl, K), 'reverse_pagerank': topk(rpr, K), 'betweenness': topk(bc, K),
'in_degree': topk(indeg, K), 'kcore': topk(np.array(core) + 1e-6 * indeg, K)}
base = {'entry': r4(np.mean(entry)), 'reachable': r4(np.mean(reach)), 'core_repo': r4(np.mean(incore)),
'production_core': r4(np.mean(prod))}
jac = lambda a, b: r4(len(set(a) & set(b)) / len(set(a) | set(b)))
metrics = {
'top50_profile': {k: profile(v) for k, v in tops.items()}, 'base_rates': base,
'top50_overlap_jaccard': {'pagerank_vs_in_degree': jac(tops['pagerank'], tops['in_degree']),
'pagerank_load_only_vs_in_degree': jac(tops['pagerank_load_only'], tops['in_degree']),
'pagerank_vs_betweenness': jac(tops['pagerank'], tops['betweenness']),
'reverse_pagerank_vs_pagerank': jac(tops['reverse_pagerank'], tops['pagerank'])},
'spearman_pagerank_in_degree_over_linked': r4(spearman(pr[indeg > 0], indeg[indeg > 0])),
'max_core': int(max(core) if core else 0), 'betweenness_sources': len(src),
'pagerank_top50_outside_core_repos': sum(1 for i in tops['pagerank'] if not incore[i]),
}
surprising = [i for i in tops['pagerank'] if not incore[i]][:10]
hub_bt = [i for i in tops['betweenness'] if not incore[i]][:5]
metrics['surprising_pagerank_outside_core'] = [[i, G.key(i), round(float(pr[i]) * n, 2), int(indeg[i])] for i in surprising]
metrics['betweenness_bridges_outside_core'] = [[i, G.key(i), round(float(bc[i]), 1)] for i in hub_bt]
findings = ['high PageRank outside CORE_REPOS (x mean, in-degree %d): %s' % (int(indeg[i]), G.ref(i)) for i in surprising[:5]]
findings += ['bridge (betweenness %.0f) outside core: %s' % (bc[i], G.ref(i)) for i in hub_bt[:3]]
cols = {'pr': quant(pr), 'rpr': quant(rpr), 'bt': quant(bc + 0.0), 'k': core}
size = [max(a, b) for a, b in zip(cols['pr'], cols['bt'])]
cols['size'] = size
ov = overlay(G, NAME, RULES, cols=cols,
extra={'scale': 'log1p(x / min positive) / max, x1000; size = max(pr, bt)'})
return ov, metrics, findingsLab
A web page in the explore folder of Cosmic that draws metrics, using SHA-256 and Louvain. Published at https://ventusltd.github.io/cosmic/tools/explore/lab/lab.html. It gets JSON (`getJSON`), reads hash (`readHash`) and sets view (`setView`).
rendercosmic / tools/explore/lab/lab.html · lines 1–243 of 243 · Entry point · pattern radius (shared by 3 files)
- What it does
- It draws metrics. Defines 20 functions or classes, including esc, hue, getJSON, readHash, layoutFor. Side effects: changes the web page (DOM); makes network requests.
- Inputs & outputs
- In: JSON file graph.json; JSON file keys.json; JSON file .metrics.json. Out: web page; canvas drawing.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/cosmic/tools/explore/lab/lab.html.
- What it achieves
- Explore Code intelligence lab. It responds to hashchange, resize and mousedown events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · tools/explore/lab · page
- Uses
- none found
- Used by
- none found
- Produces
- esc, hue, getJSON, readHash, layoutFor, fit, setView, sx, sy, colour, radius, resize
- Defines here
- esc, hue, getJSON, readHash, layoutFor, fit, setView, sx, sy, colour, radius, resize, edgeSet, draw, legend, row, buildGrid, pick, info, bindPointer
- 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/lab.html:1-243 · blob 6539111dc410a9e567f5f6eb8fa620bbca3cd1aa · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Explore Code intelligence lab</title>
<style>
:root { --bg:#000; --panel:#0b0e14; --line:#2f343d; --ink:#fff; --muted:#a6adbb; --link:#66ccff; --acc:#00ffff; }
html, body { margin:0; height:100%; background:var(--bg); color:var(--ink); font:13px/1.45 system-ui, -apple-system, Segoe UI, sans-serif; }
a { color:var(--link); }
#side { position:absolute; left:0; top:0; bottom:0; width:300px; background:var(--panel); border-right:1px solid var(--line);
overflow:auto; padding:12px 14px; box-sizing:border-box; }
#stage { position:absolute; left:300px; right:0; top:0; bottom:0; }
canvas { display:block; width:100%; height:100%; }
h1 { font-size:15px; margin:0 0 4px; color:var(--acc); }
h2 { font-size:12px; margin:14px 0 6px; color:var(--muted); text-transform:uppercase; letter-spacing:.06em; }
.views button { display:block; width:100%; text-align:left; margin:0 0 4px; padding:6px 8px; background:#000; color:var(--ink);
border:1px solid var(--line); border-radius:3px; cursor:pointer; font:inherit; }
.views button.on { border-color:var(--acc); color:var(--acc); }
.muted { color:var(--muted); }
#legend div { display:flex; gap:6px; align-items:baseline; margin:2px 0; }
#legend i { flex:0 0 10px; height:10px; border-radius:50%; display:inline-block; }
#legend span.n { margin-left:auto; color:var(--muted); }
#tip { position:absolute; pointer-events:none; background:var(--panel); border:1px solid var(--line); padding:6px 8px; max-width:420px;
display:none; font-size:12px; }
#tip b { color:var(--acc); font-weight:600; }
.cand { color:#ffd24a; }
#status { color:var(--muted); }
</style>
</head>
<body>
<div id="side">
<h1>Explore Code intelligence lab</h1>
<div class="muted">Overlays from <code>tools/explore/lab/run.py</code> on the Explore Code graph. Every dot is a file key
<code>repo@commit:path</code>; proposals marked <span class="cand">CANDIDATE</span> are not facts.</div>
<h2>View</h2>
<div class="views" id="views"></div>
<h2>What this view shows</h2>
<div id="about" class="muted"></div>
<div id="verdict" style="margin-top:6px"></div>
<h2>Legend</h2>
<div id="legend"></div>
<h2>Status</h2>
<div id="status">loading...</div>
</div>
<div id="stage"><canvas id="cv"></canvas><div id="tip"></div></div>
<script>
(function () {
'use strict';
var GRAPH = '../site7/explore-code/visual/graph.json';
var EXPS = ['communities', 'importance', 'wafer', 'semantic', 'drift', 'links', 'pipeline'];
var VIEWS = [
['wafer', 'Wafer (Kuiper law)', 'wafer', 'Each repository is a die on a hex spiral by its permanent repo number; inside it, each file sits where its own key puts it: r = sqrt(u), theta = 2 pi frac(u x 2654435769 / 2^32), u = first 32 bits of sha256(repo/path). Positions are computed from the key, never stored: unchanged files never move when the estate changes.'],
['communities', 'Communities', 'communities', 'Louvain communities over resolved references (comment links excluded), drawn on the visualiser map layout. Colour = community, named by its most over-represented name words. Grey = no reference at all.'],
['importance', 'Importance size', 'importance', 'Dot size = max(PageRank, sampled betweenness), log scaled. Colour = role. Large dots outside the core repositories are the surprising load-bearing files.'],
['semantic', 'Semantic map', 'semantic', 'Files placed by meaning: TF-IDF over identifier words, truncated SVD, spherical k-means. Islands are clusters, named by their top words; a cluster spanning many repositories is shared purpose.'],
['drift', 'Drift edges', 'drift', 'Families of near-identical code (Vedic struct-hash Jaccard >= 0.5) across files and repositories. Lines run from each copy to its canonical CANDIDATE. Pink rings: unreached files with a reachable near-copy (safest review candidates).'],
['links', 'Predicted links', 'links', 'CANDIDATE links by Adamic-Adar + shared data items, dashed; journey B/C gap proposals in amber. Never facts: a key confirms nothing here until the code references it.']
];
var cv = document.getElementById('cv'), ctx = cv.getContext('2d'), tip = document.getElementById('tip');
var D = null, P = null, N = 0, O = {}, M = {}, keys = null, view = 'wafer', W = 0, H = 0, dpr = 1;
var cam = { s: 1, x: 0, y: 0 }, pos = null, grid = null, hov = -1, errors = [];
var SEL = '#0066ff', ACC = '#00ffff', LINE = '#2f343d', GREY = '#2a3038';
function esc(s) { return String(s).replace(/[&<>"']/g, function (c) { return '&#' + c.charCodeAt(0) + ';'; }); }
function hue(i) { var h = (i * 137.508) % 360; return 'hsl(' + h.toFixed(1) + ',85%,' + (i % 2 ? 62 : 52) + '%)'; }
function getJSON(u) { return fetch(u).then(function (r) { if (!r.ok) throw new Error(u + ' ' + r.status); return r.json(); }); }
Promise.all([getJSON(GRAPH), getJSON('keys.json')].concat(EXPS.map(function (e) { return getJSON(e + '.json'); }))
.concat(EXPS.map(function (e) { return getJSON(e + '.metrics.json'); })))
.then(function (a) {
D = a[0]; P = D.n; N = P.r.length; keys = a[1];
EXPS.forEach(function (e, i) { O[e] = a[2 + i]; M[e] = a[2 + EXPS.length + i]; });
if (O.wafer.n !== N) throw new Error('overlay n ' + O.wafer.n + ' != graph n ' + N + ' (different cuts)');
var bv = document.getElementById('views');
VIEWS.forEach(function (v) {
var b = document.createElement('button'); b.textContent = v[1]; b.dataset.v = v[0];
b.onclick = function () { location.hash = 'view=' + v[0]; }; bv.appendChild(b);
});
document.getElementById('status').innerHTML = esc(N + ' files, cut ' + D.cut) + '<br>overlays: ' + EXPS.length +
', rules ' + esc(O.wafer.schema);
window.addEventListener('hashchange', readHash); window.addEventListener('resize', resize);
bindPointer(); readHash(); resize();
document.documentElement.dataset.ready = '1';
}).catch(function (e) { document.getElementById('status').textContent = 'Could not load: ' + e.message + ' (serve /tmp over http)'; errors.push(String(e)); });
function readHash() {
var m = /view=([a-z]+)/.exec(location.hash); var v = m ? m[1] : 'wafer';
if (!VIEWS.some(function (x) { return x[0] === v; })) v = 'wafer';
view = v; setView();
}
function layoutFor(v) {
var xs = new Float64Array(N), ys = new Float64Array(N), ok = new Uint8Array(N), c;
for (var i = 0; i < N; i++) {
if (v === 'wafer' || v === 'drift') { c = O.wafer.cols; xs[i] = c.wx[i]; ys[i] = c.wy[i]; ok[i] = 1; }
else if (v === 'semantic') { c = O.semantic.cols; if (c.mx[i] !== null) { xs[i] = c.mx[i]; ys[i] = c.my[i]; ok[i] = 1; } }
else { xs[i] = P.mx[i]; ys[i] = P.my[i]; ok[i] = 1; }
}
return { x: xs, y: ys, ok: ok };
}
function fit() {
var minx = 1e18, maxx = -1e18, miny = 1e18, maxy = -1e18;
for (var i = 0; i < N; i++) if (pos.ok[i]) {
if (pos.x[i] < minx) minx = pos.x[i]; if (pos.x[i] > maxx) maxx = pos.x[i];
if (pos.y[i] < miny) miny = pos.y[i]; if (pos.y[i] > maxy) maxy = pos.y[i];
}
var s = Math.min(W / (maxx - minx || 1), H / (maxy - miny || 1)) * 0.92;
cam = { s: s, x: W / 2 - s * (minx + maxx) / 2, y: H / 2 - s * (miny + maxy) / 2 };
}
function setView() {
Array.prototype.forEach.call(document.querySelectorAll('#views button'), function (b) { b.className = b.dataset.v === view ? 'on' : ''; });
var v = VIEWS.filter(function (x) { return x[0] === view; })[0];
document.getElementById('about').textContent = v[3];
var m = M[v[2]];
document.getElementById('verdict').innerHTML = '<b style="color:' + (m.verdict === 'adds intelligence' ? ACC : '#ffd24a') + '">' +
esc(m.verdict) + '</b> <span class="muted">' + esc(m.verdict_basis) + '</span><br><span class="muted">rules: ' + esc(m.rules) + '</span>';
pos = layoutFor(view); if (W) { fit(); buildGrid(); }
legend(); draw();
}
function sx(i) { return cam.x + cam.s * pos.x[i]; }
function sy(i) { return cam.y + cam.s * pos.y[i]; }
function colour(i) {
if (view === 'communities') { var c = O.communities.cols.c[i]; return c < 0 ? GREY : hue(c); }
if (view === 'semantic') { var k = O.semantic.cols.k[i]; return k < 0 ? GREY : hue(k * 3 + 1); }
if (view === 'wafer') return hue(P.r[i] * 7);
if (view === 'drift') return O.drift.cols.fam[i] >= 0 ? '#ffae00' : '#1c2128';
if (view === 'links') return '#3a4350';
return D.roles[P.o[i]][2];
}
function radius(i) {
if (view === 'importance') return 1 + 9 * Math.pow(O.importance.cols.size[i] / 1000, 2);
if (view === 'drift') return O.drift.cols.fam[i] >= 0 ? 2.2 : 1.1;
return 1.6;
}
function resize() {
var st = document.getElementById('stage'); dpr = window.devicePixelRatio || 1;
W = st.clientWidth; H = st.clientHeight; cv.width = W * dpr; cv.height = H * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); if (pos) { fit(); buildGrid(); draw(); }
}
function edgeSet(list, stride, colourFn, dash, width) {
ctx.setLineDash(dash || []);
for (var k = 0; k + 1 < list.length; k += stride) {
var a = list[k], b = list[k + 1]; if (!pos.ok[a] || !pos.ok[b]) continue;
ctx.strokeStyle = colourFn(k); ctx.lineWidth = width || 1;
ctx.beginPath(); ctx.moveTo(sx(a), sy(a)); ctx.lineTo(sx(b), sy(b)); ctx.stroke();
}
ctx.setLineDash([]);
}
function draw() {
if (!pos) return;
ctx.fillStyle = '#000'; ctx.fillRect(0, 0, W, H);
if (view === 'wafer') {
ctx.strokeStyle = LINE; ctx.lineWidth = 1;
O.wafer.legend.rows.forEach(function (r) {
ctx.beginPath(); ctx.arc(cam.x + cam.s * r[2], cam.y + cam.s * r[3], cam.s * r[4], 0, 2 * Math.PI); ctx.stroke();
});
}
if (view === 'communities') {
ctx.globalAlpha = 0.18; edgeSet(D.e, 2, function () { return '#66ccff'; }); ctx.globalAlpha = 1;
}
var order = [];
for (var i = 0; i < N; i++) if (pos.ok[i]) order.push(i);
if (view === 'importance') order.sort(function (a, b) { return O.importance.cols.size[a] - O.importance.cols.size[b]; });
for (var j = 0; j < order.length; j++) {
i = order[j]; ctx.fillStyle = colour(i);
var r = radius(i); ctx.beginPath(); ctx.arc(sx(i), sy(i), r, 0, 2 * Math.PI); ctx.fill();
}
if (view === 'drift') {
ctx.globalAlpha = 0.8;
edgeSet(O.drift.edges, 3, function (k) { return O.drift.edges[k + 2] >= 1000 ? '#ffae00' : '#ff6666'; });
ctx.globalAlpha = 1; ctx.strokeStyle = '#ff66cc'; ctx.lineWidth = 1.2;
O.drift.safe_review.forEach(function (i) { ctx.beginPath(); ctx.arc(sx(i), sy(i), 4.5, 0, 2 * Math.PI); ctx.stroke(); });
}
if (view === 'links') {
ctx.globalAlpha = 0.7; edgeSet(O.links.edges, 3, function () { return ACC; }, [4, 3]);
ctx.globalAlpha = 1; edgeSet(O.links.journey_edges, 3, function () { return '#ffd24a'; }, [6, 3], 2);
}
if (hov >= 0) { ctx.strokeStyle = SEL; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(sx(hov), sy(hov), radius(hov) + 4, 0, 2 * Math.PI); ctx.stroke(); }
}
function legend() {
var el = document.getElementById('legend'), h = [];
function row(c, t, n) { h.push('<div><i style="background:' + c + '"></i><span>' + esc(t) + '</span>' + (n !== undefined ? '<span class="n">' + n + '</span>' : '') + '</div>'); }
if (view === 'communities') O.communities.legend.rows.slice(0, 14).forEach(function (r) { row(hue(r[0]), '#' + r[0] + ' ' + r[1] + ' (' + r[5] + ' repos)', r[2]); });
else if (view === 'semantic') O.semantic.legend.rows.forEach(function (r) { row(hue(r[0] * 3 + 1), '#' + r[0] + ' ' + r[1] + ' (' + r[3] + ' repos)', r[2]); });
else if (view === 'importance') { D.roles.forEach(function (r) { row(r[2], r[1]); }); h.push('<div class="muted">size: PageRank / betweenness</div>'); }
else if (view === 'wafer') h.push('<div class="muted">' + O.wafer.legend.rows.length + ' dies (repositories). Colour = repository. Mean displacement of unchanged files after a 5% estate change: wafer 0, force ' +
M.wafer.metrics.layouts.force.mean_displacement + ', sorted packing ' + M.wafer.metrics.layouts.shelf.mean_displacement + ', rank spiral ' + M.wafer.metrics.layouts.rank_spiral.mean_displacement + ' (share of diameter).</div>');
else if (view === 'drift') { row('#ffae00', 'file in a near-copy family / identical copy line'); row('#ff6666', 'drifted copy (Jaccard < 1) to canonical'); row('#ff66cc', 'unreached with reachable near-copy (review CANDIDATE)', O.drift.safe_review.length); }
else if (view === 'links') { row(ACC, 'CANDIDATE link (Adamic-Adar + data)', O.links.edges.length / 3); row('#ffd24a', 'CANDIDATE journey-gap link', O.links.journey_edges.length / 3); }
el.innerHTML = h.join('');
}
function buildGrid() {
grid = {}; var c = 12;
for (var i = 0; i < N; i++) if (pos.ok[i]) { var k = Math.floor(sx(i) / c) + ',' + Math.floor(sy(i) / c); (grid[k] = grid[k] || []).push(i); }
}
function pick(x, y) {
var c = 12, best = -1, bd = 100, gx = Math.floor(x / c), gy = Math.floor(y / c);
for (var a = -1; a <= 1; a++) for (var b = -1; b <= 1; b++) {
(grid[(gx + a) + ',' + (gy + b)] || []).forEach(function (i) { var d = Math.pow(sx(i) - x, 2) + Math.pow(sy(i) - y, 2); if (d < bd) { bd = d; best = i; } });
}
return best;
}
function info(i) {
var s = '<b>' + esc(keys.k[i]) + '</b><br><span class="muted">file ' + i + ' · ' + esc(D.roles[P.o[i]][1]) + '</span>';
var c = O.communities.cols.c[i]; if (c >= 0) s += '<br>community #' + c + ' ' + esc(O.communities.legend.rows[c][1]);
var k = O.semantic.cols.k[i]; if (k >= 0) s += '<br>semantic #' + k + ' ' + esc(O.semantic.legend.rows[k][1]);
s += '<br>PageRank ' + O.importance.cols.pr[i] + ' · betweenness ' + O.importance.cols.bt[i] + ' · core ' + O.importance.cols.k[i];
var f = O.drift.cols.fam[i]; if (f >= 0) s += '<br>near-copy family ' + f + ', canonical <span class="cand">CANDIDATE</span> ' + esc(keys.k[O.drift.cols.canon[i]]);
s += '<br>structural stage <span class="cand">CANDIDATE</span>: ' + O.pipeline.legend.st[O.pipeline.cols.st[i]];
return s;
}
function bindPointer() {
var drag = null;
cv.addEventListener('mousedown', function (e) { drag = [e.clientX, e.clientY, cam.x, cam.y]; });
window.addEventListener('mouseup', function () { if (drag) { drag = null; buildGrid(); } });
cv.addEventListener('mousemove', function (e) {
var r = cv.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top;
if (drag) { cam.x = drag[2] + e.clientX - drag[0]; cam.y = drag[3] + e.clientY - drag[1]; draw(); return; }
var i = pick(x, y);
if (i !== hov) { hov = i; draw(); }
if (i >= 0) { tip.style.display = 'block'; tip.style.left = Math.min(x + 14, W - 430) + 'px'; tip.style.top = (y + 14) + 'px'; tip.innerHTML = info(i); }
else tip.style.display = 'none';
});
cv.addEventListener('wheel', function (e) {
e.preventDefault(); var r = cv.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top;
var f = Math.exp(-e.deltaY * 0.0015); cam.x = x - (x - cam.x) * f; cam.y = y - (y - cam.y) * f; cam.s *= f; buildGrid(); draw();
}, { passive: false });
}
window.__lab = { errors: errors, info: function (i) { return keys.k[i]; } };
})();
</script>
</body>
</html>Links
A Python module in the lab folder of Cosmic that steps files (`step_files`).
transformcosmic / tools/explore/lab/links.py · lines 1–223 of 223
- What it does
- It calculates its inputs. Defines 7 functions or classes, including data_items, data_score, two_hop, precision_at, run. Uses libraries math, random, collections, numpy.
- 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 data items helper (`data_items`), the data score helper (`data_score`) and the two hop helper (`two_hop`). Experiment 6: missing links and journey gaps by link prediction.
- Why it matters
- Imported by Explore — Lab. Checked by Test Lab.
- Application
- cosmic · tools/explore/lab · Python module
- Uses
- Explore — Lab (import), math, random, collections, numpy
- Used by
- imported by Explore — Lab (import), imported by Test Lab (import)
- Produces
- data_items, data_score, two_hop, precision_at, run, step_files
- Defines here
- data_items, data_score, two_hop, precision_at, run, feats, step_files
- 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/links.py:1-223 · blob 071cd77433c2d525706031164b3330fa3a987806 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Experiment 6: missing links and journey gaps by link prediction. Every proposal is a CANDIDATE."""
import math
import random
from collections import Counter
import numpy as np
from common import SEED, adjacency, file_words, overlay, r4
NAME = 'links'
RULES = ('lab-links-v1 (hold out 10%% of undirected edges, seed %d; common neighbours, Jaccard, Adamic-Adar, '
'shared data items (idf, items in <= 60 files, producer->consumer by file name); journey gap score = '
'Adamic-Adar + data + 0.5 x name-word Jaccard)' % SEED)
HYPOTHESIS = ('Neighbourhood link prediction recovers held-out real references far above chance, and the same '
'scores propose plausible CANDIDATE connections between journey steps that have no code link today.')
ALGORITHM = ('Undirected resolved graph (comment-url excluded). 10% of edges are hidden; on the remaining graph every '
'pair at distance two is scored by common neighbours (CN), Jaccard, Adamic-Adar (AA: sum of 1/log '
'degree of shared neighbours); pairs sharing a specific data item (a named file or data source in '
'data_contracts, idf-weighted; producer out -> consumer in by file name) get a data score. Precision@k '
'counts hidden edges among the top k proposals; AUC compares hidden edges with random non-edges. For '
'journeys B and C, every pair across adjacent steps with zero links is scored on the full graph and the '
'top 5 per gap are published as CANDIDATE links with their evidence.')
def data_items(G, max_df=60):
raw = []
for f in G.files:
dc = f.get('data_contracts') or {}
items = set()
for side in ('in', 'out'):
for x in dc.get(side) or []:
x = x.strip()
if x.startswith('data source:'):
items.add((side, 'src:' + x.split(':', 1)[1].strip().lower()))
elif ' file ' in x and '.' in x.split()[-1]:
items.add((side, 'file:' + x.split()[-1].lower()))
raw.append(items)
df = Counter()
for s in raw:
df.update({it for _, it in s})
n = len(G.files)
idf = {it: math.log((n + 1) / (c + 1)) for it, c in df.items() if c >= 2 and c <= max_df}
ins = [{it for side, it in s if it in idf and side == 'in'} for s in raw]
outs = [{it for side, it in s if it in idf and side == 'out'} for s in raw]
return ins, outs, idf
def data_score(a, b, ins, outs, idf):
shared = (ins[a] & ins[b]) | (outs[a] & ins[b]) | (outs[b] & ins[a])
return sum(idf[x] for x in shared), sorted(shared)
def two_hop(nbr):
"""dict (a, b) a < b -> (cn, aa) over pairs at distance two that are not adjacent."""
deg = [len(l) for l in nbr]
sc = {}
for z in range(len(nbr)):
l = nbr[z]
if len(l) < 2:
continue
w = 1.0 / math.log(deg[z])
for x in range(len(l)):
a = l[x]
for y in range(x + 1, len(l)):
b = l[y]
k = (a, b)
cn, aa = sc.get(k, (0, 0.0))
sc[k] = (cn + 1, aa + w)
adj = [set(l) for l in nbr]
return {k: v for k, v in sc.items() if k[1] not in adj[k[0]]}
def precision_at(ranked, hidden, ks):
out = {}
for k in ks:
top = ranked[:k]
out[str(k)] = r4(sum(1 for p in top if p in hidden) / max(1, len(top)))
return out
def run(G, hold=0.10):
rng = random.Random(SEED)
E = list(G.uedges)
hidden = set(rng.sample(E, int(hold * len(E))))
train = [e for e in E if e not in hidden]
nbr = adjacency(G.n, train)
deg = [len(l) for l in nbr]
sc = two_hop(nbr)
ins, outs, idf = data_items(G)
# data pairs (inverted index over items)
inv = {}
for i in range(G.n):
for it in ins[i] | outs[i]:
inv.setdefault(it, []).append(i)
dpairs = {}
trainset = set(train)
for it in sorted(inv):
mem = inv[it]
for x in range(len(mem)):
for y in range(x + 1, len(mem)):
k = (mem[x], mem[y])
if k not in trainset and k not in dpairs:
dpairs[k] = data_score(k[0], k[1], ins, outs, idf)[0]
cand = set(sc) | {k for k, v in dpairs.items() if v > 0}
dirs = {i: G.path[i].rsplit('/', 1)[0] if '/' in G.path[i] else '' for i in range(G.n)}
def feats(k):
cn, aa = sc.get(k, (0, 0.0))
u = deg[k[0]] + deg[k[1]] - cn
return cn, (cn / u if u else 0.0), aa, dpairs.get(k, 0.0)
F = {k: feats(k) for k in cand}
order = sorted(cand)
scorers = {
'common_neighbours': lambda f, k: f[0],
'jaccard': lambda f, k: f[1],
'adamic_adar': lambda f, k: f[2],
'data_items': lambda f, k: f[3],
'adamic_adar_plus_data': lambda f, k: f[2] + f[3],
'same_folder_then_aa': lambda f, k: (1000 if (G.repo[k[0]] == G.repo[k[1]] and dirs[k[0]] == dirs[k[1]]) else 0) + f[2],
}
ks = [100, 500, len(hidden)]
res = {}
nrand = np.random.default_rng(SEED)
neg = []
allset = set(E)
while len(neg) < 3000:
a, b = sorted(int(x) for x in nrand.integers(0, G.n, 2))
if a != b and (a, b) not in allset:
neg.append((a, b))
hid = sorted(hidden)
for nm, fn in scorers.items():
ranked = sorted(order, key=lambda k: (-fn(F[k], k), k))
ranked = [k for k in ranked if fn(F[k], k) > 0]
pos_s = np.array([fn(F[k], k) if k in F else 0.0 for k in hid])
neg_s = np.array([fn(F[k], k) if k in F else 0.0 for k in neg])
auc = ((pos_s[:, None] > neg_s[None, :]).mean() + 0.5 * (pos_s[:, None] == neg_s[None, :]).mean())
res[nm] = {'precision_at': precision_at(ranked, hidden, ks), 'auc': r4(auc),
'hidden_recoverable_share': r4(sum(1 for k in hid if fn(F.get(k, (0, 0, 0, 0)), k) > 0) / max(1, len(hid)))}
density = len(hidden) / max(1, G.n * (G.n - 1) / 2 - len(train))
# journey gaps on the full graph
full_sc = two_hop(G.nbr)
words = [set(file_words(f)) | {w.lower() for w in (f.get('defines') or [])} for f in G.files]
wdf = Counter()
for ws in words:
wdf.update(ws)
generic = {'github', 'workflows', 'workflow', 'import', 'main', 'num', 'strip', 'yml', 'yaml', 'tools', 'tool'}
words = [{w for w in ws if wdf[w] <= 0.01 * G.n and w not in generic} for ws in words]
proposals = []
gaps = []
for j in G.raw.get('journeys', []):
if j.get('id') not in ('b', 'c'):
continue
steps = {s['label']: s for s in j['steps']}
for ln in j.get('links', []):
if ln.get('count', 0) != 0:
continue
A = step_files(G, steps.get(ln['from']))
B = step_files(G, steps.get(ln['to']))
gap = {'journey': j['id'], 'from': ln['from'], 'to': ln['to'], 'files_from': len(A), 'files_to': len(B),
'proposals': 0}
best = []
for a in A:
for b in B:
if a == b:
continue
k = (min(a, b), max(a, b))
cn, aa = full_sc.get(k, (0, 0.0))
ds, shared = data_score(a, b, ins, outs, idf)
u = words[a] | words[b]
wj = len(words[a] & words[b]) / len(u) if u else 0.0
s = aa + ds + 0.5 * wj
if s > 0 and (aa > 0 or ds > 0 or wj >= 0.2):
best.append((-s, a, b, cn, aa, shared, sorted(words[a] & words[b])[:6]))
best.sort()
seen = set()
per_file = Counter()
for s, a, b, cn, aa, shared, sw in best:
if len(seen) >= 5:
break
if (a, b) in seen or per_file[a] >= 2 or per_file[b] >= 2:
continue
seen.add((a, b))
per_file[a] += 1
per_file[b] += 1
proposals.append({'state': 'CANDIDATE', 'journey': j['id'], 'gap': '%s -> %s' % (ln['from'], ln['to']),
'from': a, 'to': b, 'from_key': G.key(a), 'to_key': G.key(b), 'score': round(-s, 3),
'common_neighbours': cn, 'adamic_adar': round(aa, 3), 'shared_data': shared,
'shared_words': sw})
gap['proposals'] = len(seen)
gaps.append(gap)
metrics = {'edges': len(E), 'hidden': len(hidden), 'candidate_pairs_scored': len(cand),
'chance_precision': float('%.3g' % density), 'scorers': res, 'journey_gaps': gaps,
'journey_candidates': len(proposals)}
findings = ['CANDIDATE %s gap %s: %s -> %s (score %.2f; shared data %s; words %s)' %
(p['journey'], p['gap'], p['from_key'], p['to_key'], p['score'], ','.join(p['shared_data']) or '-',
','.join(p['shared_words']) or '-') for p in proposals[:8]]
# overlay: top predicted links on the full graph (AA + data) plus journey candidates
full_cand = set(full_sc)
top = sorted(full_cand, key=lambda k: (-(full_sc[k][1] + data_score(k[0], k[1], ins, outs, idf)[0]), k))[:300]
edges = []
for k in top:
edges += [k[0], k[1], int(round(100 * (full_sc[k][1])))]
jedges = []
for p in proposals:
jedges += [p['from'], p['to'], int(round(100 * p['score']))]
ov = overlay(G, NAME, RULES, cols={}, edges=edges, state='CANDIDATE',
extra={'edges_format': 'flat [a, b, score x100]; undirected; top 300 by Adamic-Adar + data',
'journey_edges': jedges, 'journey_proposals': proposals})
return ov, metrics, findings
def step_files(G, step):
if not step:
return []
out = set()
for loc in step.get('locations') or []:
rp, folder = loc.get('repo'), (loc.get('folder') or '').strip('/')
for i in range(G.n):
if G.repo[i] == rp and (not folder or G.path[i].startswith(folder + '/')):
out.add(i)
for k in ('entry_files', 'key_files'):
out.update(int(x) for x in step.get(k) or [])
return sorted(out)