graph.py¶
clew/wiki/graph.py
The system graph every visual view of the wiki reads: one typed model, several zoom levels.
_barycentre
float clew.wiki.graph._barycentre(str c, dict[str, set[str]] down, dict[str, float] pos)
The mean position of a component's callers already placed (or last when none).
Source · 6 lines
def _barycentre(c: str, down: dict[str, set[str]], pos: dict[str, float]) -> float:
"""@brief Mean caller position. @return Value."""
callers = [pos[a] for a in pos if c in down.get(a, ())]
return sum(callers) / len(callers) if callers else float("inf")
Activity · 2 steps
Flows
_blocks
tuple[dict[str, str], dict[str, set[str]]] clew.wiki.graph._blocks(Any conn, dict funcs, tuple declared, int depth=2)
Every file's block: declared, else Vendor, else joined by coupling, else Unassigned.
Source · 44 lines
def _blocks(
conn: Any, funcs: dict, declared: tuple, depth: int = 2
) -> tuple[dict[str, str], dict[str, set[str]]]:
"""DECLARED BLOCKS WIN (round 4, R1; the reflexion method with clustering, Christl, Koschke &
Storey, WCRE 2005). With nothing declared every file keeps its package and nothing is
inferred. Otherwise an undeclared file joins the block it shares the most calls with, either
direction, repeated until nothing moves, so a file coupled only through another undeclared
file still lands. Ties go to the block declared first. A file coupled to none is Unassigned.
@brief Assign blocks.
@return Blocks and inferred placements.
"""
files = {rel for _n, rel, _t in funcs.values()}
named = {name for name, _g in declared}
areas = vendor_areas(conn)
owner = {
rel: f"{VENDOR}: {areas[rel]}" if rel in areas and block not in named else block
for rel, block in ((rel, component_of(rel, declared, depth)) for rel in files)
}
if not declared:
return owner, {}
loose = {rel for rel, b in owner.items() if b not in named and not is_vendor(b)}
pairs = _file_calls(conn, funcs)
order = {name: i for i, (name, _g) in enumerate(declared)}
placed: dict[str, set[str]] = defaultdict(set)
moved = True
while loose and moved:
moved = False
for rel in sorted(loose):
weight: dict[str, int] = defaultdict(int)
for other, n in pairs.get(rel, {}).items():
if owner.get(other) in named:
weight[owner[other]] += n
if weight:
best = min(weight, key=lambda b: (-weight[b], order[b]))
owner[rel] = best
placed[best].add(rel)
loose.discard(rel)
moved = True
for rel in loose:
owner[rel] = "Unassigned"
return owner, dict(placed)
Activity · 27 steps
Requirements
_bump
None clew.wiki.graph._bump(dict out, str|None a, str|None b, str kind)
Count one link between two different components.
Source · 6 lines
def _bump(out: dict, a: str | None, b: str | None, kind: str) -> None:
"""@brief Count. @return None."""
if a and b and a != b:
out[(a, b)][kind] += 1
Activity · 2 steps
Flows
_components
dict[str, dict[str, Any]] clew.wiki.graph._components(funcs, comp, evidence, impact, threads)
Per-component facts for every lens.
Source · 22 lines
def _components(funcs, comp, evidence, impact, threads) -> dict[str, dict[str, Any]]:
"""@brief Component nodes. @return Nodes."""
nodes: dict[str, dict[str, Any]] = {}
file_comp: dict[str, str] = {}
for rowid, (_n, rel, is_test) in funcs.items():
cid = comp[rowid]
node = nodes.setdefault(cid, {"id": cid, "files": set(), "functions": 0, "test": True})
node["files"].add(rel)
node["functions"] += 1
node["test"] = node["test"] and is_test
file_comp[rel] = cid
_requirements_into(nodes, file_comp, evidence)
if impact is not None:
_impact_into(nodes, file_comp, impact)
for name, node in nodes.items():
node["paths"] = sorted(node["files"])
node["files"] = len(node["files"])
if threads.get(name):
node["threads"] = sorted(threads[name])
return nodes
Activity · 18 steps
Flows
_downward
dict[str, set[str]] clew.wiki.graph._downward(dict links)
The call direction between components with every cycle broken by weight.
Source · 15 lines
def _downward(links: dict) -> dict[str, set[str]]:
"""OF TWO COMPONENTS CALLING EACH OTHER, the heavier direction is "down"; a tie goes to the
alphabetically earlier caller, so the result never depends on dict order.
@brief De-cycle.
@return Direction.
"""
down: dict[str, set[str]] = defaultdict(set)
for (a, b), w in links.items():
back = links.get((b, a), {"calls": 0})["calls"]
if w["calls"] and (w["calls"] > back or (w["calls"] == back and a < b)):
down[a].add(b)
return down
Activity · 6 steps
Flows
_impact_into
None clew.wiki.graph._impact_into(dict nodes, dict[str, str] file_comp, list[dict] impact)
Functions changed by the last impact report, per component.
Source · 15 lines
def _impact_into(nodes: dict, file_comp: dict[str, str], impact: list[dict]) -> None:
"""MEASURED ZERO when the report exists: every component gets `changed`.
@brief Change counts.
@return None.
"""
for node in nodes.values():
node["changed"] = 0
for entry in impact:
for fn in entry.get("functions") or []:
cid = file_comp.get(str(fn.get("file") or ""))
if cid is not None:
nodes[cid]["changed"] += 1
Activity · 7 steps
Flows
_layers
dict[int, list[str]] clew.wiki.graph._layers(list[str] names, dict[str, set[str]] down)
Longest-path layers over the downward graph, bounded so a residual cycle terminates.
Source · 17 lines
def _layers(names: list[str], down: dict[str, set[str]]) -> dict[int, list[str]]:
"""@brief Assign layers. @return Rows."""
layer = dict.fromkeys(names, 0)
for _ in range(len(names)):
moved = False
for a in names:
for b in down.get(a, ()):
if b in layer and layer[b] < layer[a] + 1 <= len(names):
layer[b], moved = layer[a] + 1, True
if not moved:
break
rows: dict[int, list[str]] = defaultdict(list)
for c in names:
rows[layer[c]].append(c)
return rows
Activity · 13 steps
Flows
_layout
list[str] clew.wiki.graph._layout(dict[str, dict] components, dict links)
Deterministic layered layout: callers above callees, barycentre ordering.
Source · 22 lines
def _layout(components: dict[str, dict], links: dict) -> list[str]:
"""Layer = longest path from a source over the de-cycled call direction; within a layer,
components are ordered by the mean position of their callers, ties by name.
@brief Layout.
@return Order.
"""
down = _downward(links)
rows = _layers(sorted(components), down)
pos: dict[str, float] = {}
order = []
for depth in sorted(rows):
rows[depth].sort(key=lambda c: (_barycentre(c, down, pos), c))
for i, c in enumerate(rows[depth]):
pos[c] = float(i)
components[c].update(
x=i * (_BOX_W + _GAP_X), y=depth * (_BOX_H + _GAP_Y), w=_BOX_W, h=_BOX_H
)
order.append(c)
return order
Activity · 11 steps
Flows
_links
dict[tuple[str, str], dict[str, int]] clew.wiki.graph._links(Any conn, dict[int, str] comp)
Calls and shared keys between components.
Source · 21 lines
def _links(conn: Any, comp: dict[int, str]) -> dict[tuple[str, str], dict[str, int]]:
"""A BINDING IS NOT A CALL and a fuzzy edge is a guess: neither weighs a component link.
@brief Aggregate links.
@return Links.
"""
out: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {"calls": 0, "keys": 0})
if table_exists(conn, "call_edges"):
for a, b in conn.execute(
"SELECT DISTINCT caller_rowid, callee_rowid FROM call_edges "
"WHERE source != 'binding' AND confidence != 'fuzzy'"
):
_bump(out, comp.get(int(a)), comp.get(int(b)), "calls")
if table_exists(conn, "shared_key_edges"):
for a, b in conn.execute(
"SELECT DISTINCT writer_rowid, reader_rowid FROM shared_key_edges"
):
_bump(out, comp.get(int(a)), comp.get(int(b)), "keys")
return dict(out)
Activity · 8 steps
Flows
_points
list[dict[str, Any]] clew.wiki.graph._points(funcs, comp, components, evidence, impact)
The code-level point cloud: each function placed inside its component's box.
Source · 39 lines
def _points(funcs, comp, components, evidence, impact) -> list[dict[str, Any]]:
"""A GRID PER BOX, by file then name, so neighbours in the cloud are neighbours in the source.
@brief Point cloud.
@return Points.
"""
tier_of: dict[tuple[str, str], str] = {}
reqs_of: dict[tuple[str, str], set[str]] = defaultdict(set)
for row in evidence:
for name, rel, _line in row.implementer_sites:
tier_of[(name, rel)] = row.tier
reqs_of[(name, rel)].add(row.req_id)
changed = {
(f.get("name"), f.get("file")) for e in impact or [] for f in e.get("functions") or []
}
by_comp: dict[str, list[int]] = defaultdict(list)
for rowid in sorted(funcs, key=lambda r: (funcs[r][1], funcs[r][0])):
by_comp[comp[rowid]].append(rowid)
points = []
for cid, rowids in by_comp.items():
box = components[cid]
cols = max(1, int((len(rowids) * box["w"] / (box["h"] - _HEAD)) ** 0.5))
rows = max(1, -(-len(rowids) // cols))
for i, rowid in enumerate(rowids):
name, rel, _t = funcs[rowid]
point = {
"id": rowid,
"name": name,
"file": rel,
"x": box["x"] + 6 + (i % cols) * (box["w"] - 12) / cols,
"y": box["y"] + _HEAD + (i // cols) * (box["h"] - _HEAD - 6) / rows,
}
if (name, rel) in tier_of:
point["tier"] = tier_of[(name, rel)]
point["reqs"] = sorted(reqs_of[(name, rel)])
if impact is not None:
point["changed"] = (name, rel) in changed
points.append(point)
return points1 more lines, not shown
Activity · 25 steps
Flows
_requirements_into
None clew.wiki.graph._requirements_into(dict nodes, dict[str, str] file_comp, list evidence)
Requirement tiers per component, from implementer sites.
Source · 13 lines
def _requirements_into(nodes: dict, file_comp: dict[str, str], evidence: list) -> None:
"""A REQUIREMENT COUNTS ONCE PER COMPONENT, however many of its implementers live there.
@brief Tier counts.
@return None.
"""
for row in evidence:
for cid in {file_comp.get(rel) for _n, rel, _l in row.implementer_sites} - {None}:
tiers = nodes[cid].setdefault("requirements", {})
tiers[row.tier] = tiers.get(row.tier, 0) + 1
nodes[cid].setdefault("req_ids", []).append([row.req_id, row.tier])
Activity · 5 steps
Flows
_tested_calls
dict[int, int] clew.wiki.graph._tested_calls(Any conn, dict[int, tuple[str, str, bool]] funcs)
Calls from test code into each non-test function.
Source · 18 lines
def _tested_calls(conn: Any, funcs: dict[int, tuple[str, str, bool]]) -> dict[int, int]:
"""A BINDING IS NOT A CALL and a fuzzy edge is a guess, as for links.
@brief Count test calls.
@return Counts.
"""
out: dict[int, int] = defaultdict(int)
if table_exists(conn, "call_edges"):
for a, b in conn.execute(
"SELECT DISTINCT caller_rowid, callee_rowid FROM call_edges "
"WHERE source != 'binding' AND confidence != 'fuzzy'"
):
caller, callee = funcs.get(int(a)), funcs.get(int(b))
if caller and callee and caller[2] and not callee[2]:
out[int(b)] += 1
return dict(out)
Activity · 7 steps
Flows
_threads
dict[str, set[str]] clew.wiki.graph._threads(Any conn, dict[int, str] comp)
The threads each component's functions run on.
Source · 13 lines
def _threads(conn: Any, comp: dict[int, str]) -> dict[str, set[str]]:
"""@brief Thread membership. @return Map."""
out: dict[str, set[str]] = defaultdict(set)
if table_exists(conn, "thread_membership") and table_exists(conn, "threads"):
for rowid, name in conn.execute(
"SELECT tm.memberdef_rowid, t.name FROM thread_membership tm "
"JOIN threads t ON t.id = tm.thread_id"
):
if int(rowid) in comp:
out[comp[int(rowid)]].add(str(name))
return out
Activity · 6 steps
Flows
_vendor_calls_in
dict[str, int] clew.wiki.graph._vendor_calls_in(Any conn, dict funcs, dict[int, str] comp)
Per vendor area, the distinct first-party functions-to-its-functions calls.
Source · 20 lines
def _vendor_calls_in(conn: Any, funcs: dict, comp: dict[int, str]) -> dict[str, int]:
"""BY FUNCTION, NOT BY ROW: doxygen writes a declaration row and a definition row for one C
function, so one call reads as several rowid pairs. A pair is (name, file) on each side.
@brief Count calls into vendor areas.
@return Counts.
"""
if not table_exists(conn, "call_edges"):
return {}
pairs: dict[str, set] = defaultdict(set)
for a, b in conn.execute(
"SELECT DISTINCT caller_rowid, callee_rowid FROM call_edges "
"WHERE source != 'binding' AND confidence != 'fuzzy'"
):
into, out_of = comp.get(int(b)), comp.get(int(a))
if into and out_of and is_vendor(into) and not is_vendor(out_of):
pairs[into].add((funcs[int(a)][:2], funcs[int(b)][:2]))
return {block: len(p) for block, p in pairs.items()}
Activity · 8 steps
Flows
build_graph
dict[str, Any] clew.wiki.graph.build_graph(Path db, list evidence, list[dict]|None impact, tuple declared=(), int component_depth=2, bool exclude_tests=False)
Build the graph.
Called by _build_site, _data
Tested by 12 tests
test_a_declared_block_still_wins_over_vendor, test_a_file_coupled_to_no_declared_block_is_unassigned, test_an_undeclared_file_joins_the_block_it_is_most_coupled_to, test_components_links_and_layout, test_each_function_carries_the_requirements_it_implements, test_lens_facts_ride_on_components_and_absent_sources_stay_absent, test_test_code_is_a_lens_not_a_box, test_the_change_lens_exists_only_with_an_impact_report, test_the_point_cloud_places_every_function_inside_its_box, test_vendored_code_is_its_areas_block_never_joined_by_coupling, test_vendored_code_is_its_areas_block_with_nothing_declared, test_with_nothing_declared_blocks_are_packages
Calls _components, _layout, _links, _points, _tested_calls, _threads, _vendor_calls_in, connect, is_vendor
Source · 41 lines
def build_graph(
db: Path,
evidence: list,
impact: list[dict] | None,
declared: tuple = (),
component_depth: int = 2,
exclude_tests: bool = False,
) -> dict[str, Any]:
"""@brief Aggregate and lay out. @return Graph."""
with connect(db) as conn:
funcs = _functions(conn)
tested = _tested_calls(conn, funcs) if exclude_tests else None
if exclude_tests:
funcs = {r: f for r, f in funcs.items() if not f[2]}
file_block, inferred = _blocks(conn, funcs, declared, component_depth)
comp = {rowid: file_block[rel] for rowid, (_n, rel, _t) in funcs.items()}
links = _links(conn, comp)
threads = _threads(conn, comp)
calls_in = _vendor_calls_in(conn, funcs, comp)
components = _components(funcs, comp, evidence, impact, threads)
for cid, node in components.items():
node["declared"] = any(cid == name for name, _g in declared)
node["inferred_files"] = sorted(inferred.get(cid, ()))
if is_vendor(cid):
## A VENDOR AREA IS SIZED BY USE (P5): the calls into it from first-party code.
node["vendor"] = True
node["calls_in"] = calls_in.get(cid, 0)
if tested is not None:
for rowid, cid in comp.items():
components[cid].setdefault("tested_calls", 0)
components[cid]["tested_calls"] += tested.get(rowid, 0)
order = _layout(components, links)
return {
"graph_version": GRAPH_VERSION,
"components": [components[c] for c in order],
"links": [{"from": a, "to": b, **w} for (a, b), w in sorted(links.items())],
"symbols": _points(funcs, comp, components, evidence, impact),
"file_block": dict(sorted(file_block.items())),
}
Activity · 23 steps
Requirements
Flows
component_of
str clew.wiki.graph.component_of(str rel, tuple[tuple[str, tuple[str,...]],...] declared=(), int depth=2)
The component a file belongs to.
Source · 14 lines
def component_of(
rel: str, declared: tuple[tuple[str, tuple[str, ...]], ...] = (), depth: int = 2
) -> str:
"""A DECLARED GROUPING WINS; otherwise the package (`package_of`).
@brief Component of a file.
@return Component id.
"""
for name, globs in declared:
if any(fnmatch.fnmatch(rel, g) for g in globs):
return name
return package_of(rel, depth)
Activity · 4 steps
Requirements
is_vendor
bool clew.wiki.graph.is_vendor(str block)
Whether a block id is a vendor area.
Source · 5 lines
def is_vendor(block: str) -> bool:
"""@brief Vendor block? @return Bool."""
return block == VENDOR or block.startswith(f"{VENDOR}: ")
Activity · 1 steps
Flows
package_of
str clew.wiki.graph.package_of(str rel, int depth=2)
The package a file sits in: its first depth directories.
Source · 15 lines
def package_of(rel: str, depth: int = 2) -> str:
"""`clew/query/x.py` → `clew/query`, a top-level module `clew/cli.py` → `clew`, a root file →
`(root)`. THE DEPTH IS DECLARED (R5-CFG C7, 2.0.0): two segments made every Maven/Gradle file
(`src/main/java/com/acme/...`) one block `src/main`, and Go's `internal/x/y` one `internal/x`.
@brief Package of a file.
@return Package id.
"""
parts = rel.split("/")
if len(parts) == 1:
return "(root)"
dirs = parts[:-1]
return "/".join(dirs[:depth])