File size: 5,446 Bytes
9542666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/env python3
"""Regenerate _methods-index.md: a lineage forest over method notes.

This is NOT a taxonomy. The `family` field is coarse grouping only and each
method's real signature lives in its aspects (see Methods.md). This view just
surfaces the genealogy the lineage edges already encode: `variant-of` is the
tree spine; `refines` / `combines` are shown inline. Roots are ranked by number
of descendants so the biggest method families float to the top. A node with no
method note (ⓘ) is a lineage anchor only (a canonical method name others descend
from that has not been analyzed as its own note).

    python3 _scripts/make_methods_index.py
"""
import glob
import os
import re
from collections import defaultdict, Counter

VAULT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def fm_field(text, name):
    parts = text.split("---")
    if len(parts) < 2:
        return ""
    m = re.search(rf'^{name}:[ \t]*([^#\n]*)', parts[1], flags=re.M)  # YAML: `# ...` is a comment
    return m.group(1).strip().strip('"') if m else ""


def edge_targets(text, edge):
    out = []
    for m in re.finditer(rf'^{edge}::\s*\[\[([^\]]+)\]\]', text, flags=re.M):
        out.append(m.group(1).split("|")[0].strip())
    return out


def paper_slug(text):
    m = re.search(r'^introduced-in:\s*"?\[\[([^\]]+)\]\]', text.split("---")[1], flags=re.M) \
        if len(text.split("---")) > 1 else None
    return m.group(1).strip() if m else ""


def main():
    methods = {}
    for path in sorted(glob.glob(os.path.join(VAULT, "methods", "*.md"))):
        slug = os.path.splitext(os.path.basename(path))[0]
        text = open(path, encoding="utf-8").read()
        methods[slug] = {
            "family": fm_field(text, "family"),
            "paper": paper_slug(text),
            "variant_of": edge_targets(text, "variant-of"),
            "refines": edge_targets(text, "refines"),
            "combines": edge_targets(text, "combines"),
        }

    # tree spine = first variant-of target
    parent = {}
    for s, d in methods.items():
        parent[s] = d["variant_of"][0] if d["variant_of"] else None

    nodes = set(methods) | {p for p in parent.values() if p}
    children = defaultdict(list)
    for s in methods:
        p = parent[s]
        if p:
            children[p].append(s)
    roots = sorted(n for n in nodes if not parent.get(n))

    def subtree_size(n, seen=None):
        seen = seen or set()
        if n in seen:
            return 0
        seen.add(n)
        return len(children[n]) + sum(subtree_size(c, seen) for c in children[n])

    def render(n, depth, out, seen):
        if n in seen:
            out.append("  " * depth + f"- {n} (cycle)")
            return
        seen = seen | {n}
        d = methods.get(n)
        if d:
            bits = []
            if d["paper"]:
                bits.append(f"[[{d['paper']}]]")
            if d["family"]:
                bits.append(f"·{d['family']}·")
            extra = d["variant_of"][1:]
            ann = []
            if extra:
                ann.append("also variant-of " + ", ".join(extra))
            if d["refines"]:
                ann.append("refines " + ", ".join(d["refines"]))
            if d["combines"]:
                ann.append("combines " + ", ".join(d["combines"]))
            tail = (" — " + "; ".join(ann)) if ann else ""
            out.append("  " * depth + f"- [[{n}]] {' '.join(bits)}{tail}")
        else:
            out.append("  " * depth + f"- {n} ⓘ")
        for c in sorted(children[n], key=lambda x: (-subtree_size(x), x)):
            render(c, depth + 1, out, seen)

    fam = Counter(d["family"] or "—" for d in methods.values())

    L = ["---", "tags: [meta]", "---", "", "# Methods index", "",
         "Generated by `_scripts/make_methods_index.py` — a lineage forest, **not a",
         "taxonomy**. The `family` label is coarse; a method's real signature is its",
         "aspects ([[Methods]]). `variant-of` is the tree spine; `refines`/`combines`",
         "are shown inline. Roots are ranked by descendant count. `ⓘ` = lineage anchor",
         "with no method note of its own.", "",
         "## Families (coarse)", "",
         "| Family | Methods |", "|---|---|"]
    for f, n in sorted(fam.items(), key=lambda kv: (-kv[1], kv[0])):
        L.append(f"| {f} | {n} |")
    L += ["", f"Total method notes: {len(methods)}", "",
          "## Lineage forest", ""]

    ranked = sorted(roots, key=lambda r: (-subtree_size(r), r))
    for r in ranked:
        # skip singletons (a root that is a lone method note with no children) into a tail section
        if not children[r]:
            continue
        out = []
        render(r, 0, out, set())
        L.extend(out)
        L.append("")

    singletons = sorted(r for r in ranked if r in methods and not children[r])
    if singletons:
        L += ["## Standalone methods (no lineage edges)", ""]
        for s in singletons:
            d = methods[s]
            bits = (f"[[{d['paper']}]] " if d["paper"] else "") + (f"·{d['family']}·" if d["family"] else "")
            L.append(f"- [[{s}]] {bits}")

    open(os.path.join(VAULT, "_methods-index.md"), "w", encoding="utf-8").write("\n".join(L) + "\n")
    print(f"wrote _methods-index.md: {len(methods)} methods, "
          f"{len([r for r in ranked if children[r]])} lineage trees, {len(singletons)} standalone")


if __name__ == "__main__":
    main()