Index of theproofnetwork/open-problems@860a535/scripts/build_index.py

qedmarket’s copy of theproofnetwork/open-problems@860a535, 30 Nov 2026original source ↗

264 lines · 15.6 kBraw
#!/usr/bin/env python3"""Write index.json: every open problem in this repository that can be a challenge for the official Lean verifier.     lake build && python3 -I scripts/build_index.py Runs `lake exe index` over all modules of FormalConjectures/ and Prove2Me/, then keeps a theorem only if- its module and name are names the platform and the verifier take (dotted ASCII identifiers);- nothing it rests on has `sorry`, an axiom beyond propext, Quot.sound and Classical.choice, or a private  declaration of its own module;- it has no formal proof recorded upstream, and isn't a question for a value (`<theorem>.answer := sorry`, which no  proof can fill).Everything left out is in `excluded.json` with the reasons."""import collectionsimport jsonimport reimport subprocessimport sysfrom pathlib import Path ROOT = Path(__file__).resolve().parent.parentREPO = "https://github.com/theproofnetwork/open-problems"IDENT = r"[A-Za-z_][A-Za-z0-9_]*"MODULE = re.compile(rf"^{IDENT}(\.{IDENT})*$")NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_'!?]*(\.[A-Za-z_][A-Za-z0-9_'!?]*)*$")# formal-conjectures' README: CC-BY 4.0, except material from Wikipedia, MathOverflow and the OEIS (CC BY-SA 4.0)# and from arXiv (the paper's licence, at the URL in the file).SHARE_ALIKE = {"Wikipedia", "Mathoverflow", "OEIS"}SOURCE_TAG = {"ErdosProblems": "erdos problems", "OEIS": "oeis", "Wikipedia": "wikipedia",              "GreensOpenProblems": "greens open problems", "Arxiv": "arxiv", "Paper": "paper",              "Mathoverflow": "mathoverflow", "Millennium": "millennium problems", "HilbertProblems": "hilbert problems",              "Kourovka": "kourovka notebook", "OpenQuantumProblems": "quantum", "Books": "books",              "OptimizationConstants": "optimization constants", "WrittenOnTheWallII": "written on the wall",              "LittProblems": "litt problems", "Other": None, "Subsets": None}  # What a statement is about, from the Mathlib constants it rests on (`uses`, from scripts/Index.lean): a constant# whose name is a key, or starts with a key and a dot, gives the tag. Specific ones first; the fallbacks only when# an entry got no topic at all (neither from here nor from its AMS class).TOPICS = {    "Nat.Prime": "prime numbers", "Nat.Primes": "prime numbers", "Prime": "prime numbers",    "Nat.primeCounting": "prime numbers", "Nat.primeCounting'": "prime numbers", "Nat.nth_prime": "prime numbers",    "Nat.primeFactors": "prime factors", "Nat.factorization": "prime factors", "Nat.primeFactorsList": "prime factors",    "Nat.divisors": "divisors", "Nat.properDivisors": "divisors", "Nat.Perfect": "perfect numbers",    "ArithmeticFunction": "arithmetic functions", "Nat.totient": "arithmetic functions",    "Nat.Coprime": "divisibility", "Nat.gcd": "divisibility", "Nat.lcm": "divisibility",    "Nat.factorial": "factorials", "Nat.choose": "binomial coefficients", "Nat.fib": "fibonacci numbers",    "Nat.digits": "digits", "Nat.ofDigits": "digits", "Squarefree": "squarefree numbers",    "Nat.Partition": "partitions", "ZMod": "modular arithmetic", "Nat.ModEq": "modular arithmetic",    "Int.ModEq": "modular arithmetic", "legendreSym": "modular arithmetic", "jacobiSym": "modular arithmetic",    "Polynomial": "polynomials", "MvPolynomial": "polynomials",    "NumberField": "algebraic number theory", "IsAlgebraic": "irrationality and transcendence",    "Transcendental": "irrationality and transcendence", "Irrational": "irrationality and transcendence",    "riemannZeta": "zeta function", "LSeries": "l functions", "DirichletCharacter": "l functions",    "WeierstrassCurve": "elliptic curves", "EllipticCurve": "elliptic curves",    "SimpleGraph": "graph theory", "Digraph": "graph theory",    "SimpleGraph.chromaticNumber": "graph coloring", "SimpleGraph.Coloring": "graph coloring",    "SimpleGraph.Colorable": "graph coloring",    "Matrix": "linear algebra", "LinearMap": "linear algebra", "Module.finrank": "linear algebra",    "Submodule": "linear algebra",    "MeasureTheory": "measure theory", "ProbabilityTheory": "probability", "PMF": "probability",    "EuclideanSpace": "geometry", "EuclideanGeometry": "geometry", "Convex": "convexity",    "convexHull": "convexity", "ConvexOn": "convexity",    "Subgroup": "group theory", "Sylow": "group theory", "IsCyclic": "group theory", "Equiv.Perm": "permutations",    "deriv": "calculus", "HasDerivAt": "calculus", "iteratedDeriv": "calculus", "ContDiff": "calculus",    "intervalIntegral": "integrals", "AnalyticAt": "complex analysis", "DifferentiableOn": "calculus",    "Asymptotics": "asymptotics", "Filter.atTop": "asymptotics",    "Turing": "computability", "Computable": "computability", "Nat.Partrec": "computability",    "Partrec": "computability",    "Cardinal.aleph": "set theory", "Cardinal.beth": "set theory", "Ordinal": "set theory",  # not Cardinal.mk: a size    "TopologicalSpace": "topology", "ModelWithCorners": "manifolds", "CategoryTheory": "category theory",    "Function.IsPeriodicPt": "dynamical systems", "Function.periodicPts": "dynamical systems",}FALLBACK_TOPICS = {"Finset": "combinatorics", "Finpartition": "combinatorics"}  def topics(uses, table=TOPICS):    """The tags of `table` whose key names one of the constants, in the table's order."""    found = set()    for name in uses:        parts = name.split(".")        for i in range(1, len(parts) + 1):  # every key it starts with: SimpleGraph.chromaticNumber is both            tag_ = table.get(".".join(parts[:i]))            if tag_:                found.add(tag_)    return [t for t in dict.fromkeys(table.values()) if t in found]  def ams_names():    """AMS class number → its name, from the constructors' docstrings."""    text = (ROOT / ".lake/packages/open_problems_support/FormalConjecturesUtil/Attributes/AMS.lean").read_text()    return {int(n): d.strip() for d, n in re.findall(r"/--\s*(.*?)\s*-/\s*\|\s*«(\d+)»", text, re.S)}  def tag(text):    """One tag as the platform spells it (lib/tags.ts): lower case, letters and digits, at most 40 characters."""    t = re.sub(r"[-_]", " ", text.lower())    t = re.sub(r"[^a-z0-9 ]", "", t)    return re.sub(r" +", " ", t).strip()[:40].strip()  def plain_title(text):    """A heading as plain text: Markdown emphasis, code and links dropped, `--` as a dash. Math in `$…$` stays."""    text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text)  # [text](url)    text = re.sub(r"`([^`]*)`", r"\1", text)    text = re.sub(r"(\*\*|__|\*|(?<![\w$])_)(?=\S)(.+?)(?<=\S)\1(?![\w$])", r"\2", text)    return re.sub(r"\s+", " ", re.sub(r"\s+--\s+", " – ", text)).strip()  # Titles set by hand, by theorem name: the problems people look for by name.TITLE_OVERRIDES = {    "ComplexityTheory.P_ne_NP": "P ≠ NP",    "PvsNP.P_ne_NP": "P ≠ NP",    "ComplexityTheory.NP_ne_coNP": "NP ≠ coNP",}  def title_of(module_doc, theorem, siblings):    """The module docstring's first heading. When the module has several open theorems, a variant    (`….variants.<name>`) gets "(variant <name>)" and any other theorem but the main one its last name part;    the main one, without `variants` in its name, keeps the plain title."""    m = re.search(r"^#\s+(.+)$", module_doc or "", re.M)    base = plain_title(m.group(1)) if m else theorem.split(".")[0]    parts = theorem.split(".")    if "variants" in parts:        base += f" (variant {'.'.join(parts[parts.index('variants') + 1:])})"    elif siblings.get("main", 0) > 1:        base += f" ({parts[-1]})"    return base[:300]  # erdosproblems.com statuses (metadata/erdos.json) under which a market makes no sense: a proof in Lean is linked there# (any status ending in "(Lean)"), the problem is disproved, or it can't be proved. The status is the whole problem's,# so a variant that is still open is left out too: cautious, and listed in excluded.json.ERDOS_SETTLED = re.compile(r"\(Lean\)$|^disproved$|^not provable$|^independent$")# Solved on paper without a Lean proof: kept (a market asks whether someone formalizes it), and said in a tag.ERDOS_ON_PAPER = {"proved", "solved"}  def erdos_meta(row, erdos):    m = re.fullmatch(r"FormalConjectures\.ErdosProblems\.Erdos(\d+)", row["module"])    return erdos.get(m.group(1)) if m else None  def reasons(row, erdos=None):    out = []    meta = erdos_meta(row, erdos or {})    if meta and ERDOS_SETTLED.search(meta.get("status") or ""):        out.append(f"erdosproblems.com lists it as {meta['status']}")    if not MODULE.match(row["module"]):        out.append("module name not supported")    if not NAME.match(row["theorem"]):        out.append("theorem name not supported")    if row["sorry"]:        out.append("rests on sorry")    if row["axioms"]:        out.append("rests on axioms " + ", ".join(row["axioms"]))    if row["private"]:        out.append("rests on private declarations " + ", ".join(row["private"]))    if row["formalProofs"]:        out.append("has a formal proof: " + ", ".join(p["link"] for p in row["formalProofs"]))    if row["question"] == "value":        out.append("asks for a value (the answer is left as sorry)")    return out  def main():    upstream = json.loads((ROOT / "upstream.json").read_text())    p2m_path = ROOT / "Prove2Me/upstream.json"    p2m = json.loads(p2m_path.read_text()) if p2m_path.exists() else {"theorems": {}}    erdos_path = ROOT / "metadata/erdos.json"    erdos = json.loads(erdos_path.read_text())["problems"] if erdos_path.exists() else {}    dup_path = ROOT / "Prove2Me/duplicates.json"    possible = json.loads(dup_path.read_text())["possible"] if dup_path.exists() else {}    # One run per library: their declarations needn't have distinct names across libraries.    raw = {"theorems": [], "moduleDocs": {}}    (ROOT / ".lake").mkdir(exist_ok=True)    for lib, names in (("FormalConjectures", []), ("Prove2Me", sorted(p2m["theorems"]))):        mods = sorted(".".join(p.with_suffix("").relative_to(ROOT).parts) for p in (ROOT / lib).glob("**/*.lean"))        if not mods:            continue        (ROOT / ".lake/index-modules.txt").write_text("\n".join(mods) + "\n")        (ROOT / ".lake/index-names.txt").write_text("\n".join(names) + "\n")        out = subprocess.run(["lake", "exe", "index", ".lake/index-modules.txt", ".lake/index-names.txt"], cwd=ROOT,                             check=True, stdout=subprocess.PIPE, text=True).stdout        part = json.loads(out)        raw["theorems"] += part["theorems"]        raw["moduleDocs"].update(part["moduleDocs"])    ams = ams_names()    per_module = {}  # module → how many theorems of it are in the index without `variants` in their name    for row in raw["theorems"]:        if not reasons(row, erdos) and "variants" not in row["theorem"].split("."):            per_module.setdefault(row["module"], {"main": 0})["main"] += 1     entries, excluded = [], []    for row in sorted(raw["theorems"], key=lambda r: (r["module"], r["line"] or 0)):        why = reasons(row, erdos)        if why:            excluded.append({"module": row["module"], "theorem": row["theorem"], "reasons": why})            continue        file = Path(*row["module"].split(".")).with_suffix(".lean")        lines = (ROOT / file).read_text().split("\n")        statement = "\n".join(lines[row["line"] - 1:row["endLine"]]) if row["line"] else None        if row["module"].startswith("Prove2Me."):            info = p2m["theorems"][row["theorem"]]            source = {"name": "prove2me", "id": info["theorem_id"], "url": info["url"],                      "mathlibRev": info.get("mathlib_rev"), "origin": info.get("source"),                      **({"openLemmas": info["openLemmas"], "openLemmasTotal": info["openLemmasTotal"],                          "openLemmasAt": info["openLemmasAt"], "mission": info["mission_url"]}                         if info.get("openLemmas") else {})}            license_ = "Apache-2.0"            tags = ["prove2me"] + [tag(t) for t in info.get("fields") or []] + [tag(t) for t in info.get("tags") or []]            title = info["title"][:300]            row["docstring"] = row["docstring"] or info.get("statement")            dup = possible.get(row["theorem"])        else:            path = upstream["modules"][row["module"]]            folder = path.split("/")[1]            source = {"name": "formal-conjectures", "repository": upstream["repository"], "commit": upstream["commit"],                      "path": path, "url": f"{upstream['repository']}/blob/{upstream['commit']}/{path}"                                          + (f"#L{row['line']}-L{row['endLine']}" if row["line"] else "")}            license_ = ("CC-BY-SA-4.0" if folder in SHARE_ALIKE else                        "arXiv paper's licence (see the file)" if folder == "Arxiv" else "CC-BY-4.0")            tags = [t for t in [SOURCE_TAG.get(folder, tag(folder))] if t]            dup = None            title = title_of(raw["moduleDocs"].get(row["module"]), row["theorem"], per_module.get(row["module"], {}))        title = TITLE_OVERRIDES.get(row["theorem"], title)        tags += [tag(ams[s]) for s in row["subjects"] if s in ams]        meta = erdos_meta(row, erdos)        if meta:  # erdosproblems.com's own tags, whether a prize is offered, and whether it is solved on paper            tags += ((["solved on paper"] if meta.get("status") in ERDOS_ON_PAPER else [])                     + [tag(x) for x in meta["tags"]] + (["erdos prize"] if meta["prize"] else []))        found = topics(row.get("uses") or [])        if not found and len(tags) <= 1:            found = topics(row.get("uses") or [], FALLBACK_TOPICS)        tags += found        tags = list(dict.fromkeys(t for t in tags if t))        # At most 10 (the platform's limit), and the yes/no warning always among them.        tags = tags[:9] + ["yes no question"] if row["question"] == "yes_no" else tags[:10]        entries.append({            "module": row["module"], "theorem": row["theorem"], "title": title,            "file": str(file), "line": row["line"], "endLine": row["endLine"],            "statement": statement, "docstring": row["docstring"], "moduleDoc": raw["moduleDocs"].get(row["module"]),            "subjects": row["subjects"], "question": row["question"], "constructive": not row["classical"],            "tags": tags, "license": license_, "source": source,            **({"possibleDuplicateOf": {"theorem": dup["of"], "note": dup["note"]}} if dup else {}),        })    (ROOT / "index.json").write_text(json.dumps({        "repository": REPO,        "verifier": {"lean": "v4.34.0-rc2", "mathlib": "85e3a25e006c35636f0e53b0e9296caca2685bc0"},        "entries": entries}, indent=1, ensure_ascii=False) + "\n")    (ROOT / "excluded.json").write_text(json.dumps(excluded, indent=1, ensure_ascii=False) + "\n")    # Two theorems of one file can end in the same name (`riemannZeta.simple_prop_lt`, `DirichletCharacter.simple_prop_lt`):    # such a title names the theorem in full, so every title is its own, except the hand-set ones.    count = collections.Counter(e["title"] for e in entries)    for e in entries:        last = "(" + e["theorem"].split(".")[-1] + ")"        if count[e["title"]] > 1 and e["theorem"] not in TITLE_OVERRIDES and e["title"].endswith(last):            e["title"] = e["title"][:-len(last)] + "(" + e["theorem"] + ")"    print(f"{len(entries)} entries, {len(excluded)} excluded", file=sys.stderr)  if __name__ == "__main__":    main()

download (.tar)