diff --git a/_si_article_/benchmarks/README.md b/_si_article_/benchmarks/README.md index 59b6f263..1a7cbe15 100644 --- a/_si_article_/benchmarks/README.md +++ b/_si_article_/benchmarks/README.md @@ -55,9 +55,9 @@ DeepTrack checkout are never modified by these operations. ## Gold annotations and comparability - `gold/dogfood_kilin_code.json` contains 22 questions, including five - deliberate abstention cases, verified for source-chunk overlap against the - **23 October 2026** KíLín archive. Citation paths and line numbers describe - that snapshot; review them whenever code or notebooks change. An overlapping + deliberate abstention cases. Citation paths and line numbers were checked + by hand against commit **6cb105d20 (3 December 2026)** and describe that + revision; review them whenever code or notebooks change. An overlapping chunk does not, by itself, establish that the written reference answer is scientifically or technically correct. - `gold/dogfood_deeptrack_code.json` retains the historical DeepTrack2 diff --git a/_si_article_/benchmarks/common.py b/_si_article_/benchmarks/common.py index b5195424..147fc025 100644 --- a/_si_article_/benchmarks/common.py +++ b/_si_article_/benchmarks/common.py @@ -48,6 +48,10 @@ Heuristic answer checks that require human interpretation. +- ``bootstrap_interval`` and ``wilson_interval`` + + 95% intervals for mean scores and for counts. + Examples -------- >>> from benchmarks.common import citation_validity, format_query @@ -65,8 +69,10 @@ from difflib import SequenceMatcher import json from pathlib import Path +import random import re import shutil +from statistics import NormalDist from zoneinfo import ZoneInfo from kilin.query_formats import format_qwen3_query @@ -88,10 +94,17 @@ "citation_coverage", "abstains", "verbatim_overlap_chars", + "bootstrap_interval", + "wilson_interval", ] LOCAL_TIMEZONE = ZoneInfo("Europe/Rome") +# Resamples and seed of the bootstrap intervals; the fixed seed makes the +# intervals of a run reproducible. +BOOTSTRAP_RESAMPLES = 10_000 +BOOTSTRAP_SEED = 0 + CODE_RETRIEVAL_INSTRUCTION = ( "Given a coding problem description, retrieve the source code that " @@ -167,7 +180,9 @@ def evaluate_retrieval( Returns ------- dict[str, dict[str, float]] - Mean NDCG, MAP, recall, precision and MRR at each cutoff. + Mean NDCG, MAP, recall, precision and MRR at each cutoff, and under + ``ndcg_interval`` the 95% bootstrap interval of NDCG@10 over the + queries (when 10 is a cutoff). Notes ----- @@ -222,6 +237,13 @@ def evaluate_retrieval( mrr[f"MRR@{k}"] += 1.0 / (rank + 1) break + ndcg_interval: dict[str, list[float]] = {} + if 10 in k_values and scores: + low, high = bootstrap_interval( + [query_scores["ndcg_cut_10"] for query_scores in scores.values()] + ) + ndcg_interval["NDCG@10"] = [round(low, 5), round(high, 5)] + query_count = len(scores) or 1 qrel_count = len(qrels) or 1 for k in k_values: @@ -237,9 +259,114 @@ def evaluate_retrieval( "recall": recall, "precision": precision, "mrr": mrr, + "ndcg_interval": ndcg_interval, } +def bootstrap_interval( + values, + level: float = 0.95, + resamples: int = BOOTSTRAP_RESAMPLES, + seed: int = BOOTSTRAP_SEED, +) -> tuple[float, float]: + """Return a percentile bootstrap interval for the mean of values. + + Parameters + ---------- + values: Sequence[float] + Per-item scores, for example the NDCG@10 of each query or the + citation coverage of each answer. + level: float, optional + Coverage of the interval. Defaults to 0.95. + resamples: int, optional + Number of resamples. Defaults to ``BOOTSTRAP_RESAMPLES``. + seed: int, optional + Seed of the resampling, so that a run gives the same interval. + Defaults to ``BOOTSTRAP_SEED``. + + Returns + ------- + tuple[float, float] + Lower and upper bound of the mean. + + Raises + ------ + ValueError + If values is empty or level is not between 0 and 1. + + """ + + values = [float(value) for value in values] + if not values: + raise ValueError("values must not be empty.") + if not 0.0 < level < 1.0: + raise ValueError("level must be between 0 and 1.") + generator = random.Random(seed) + count = len(values) + means = sorted( + sum(generator.choices(values, k=count)) / count + for _ in range(resamples) + ) + tail = (1.0 - level) / 2.0 + low = means[int(tail * (resamples - 1))] + high = means[int(round((1.0 - tail) * (resamples - 1)))] + return low, high + + +def wilson_interval( + successes: int, total: int, level: float = 0.95 +) -> tuple[float, float]: + """Return the Wilson score interval of a proportion. + + Parameters + ---------- + successes: int + Number of items with the property, for example answers citing only + supplied evidence. + total: int + Number of items. + level: float, optional + Coverage of the interval. Defaults to 0.95. + + Returns + ------- + tuple[float, float] + Lower and upper bound of the proportion, between 0 and 1. + + Raises + ------ + ValueError + If the counts or level are invalid. + + Notes + ----- + Unlike the normal approximation, the Wilson interval stays inside + [0, 1] and is informative when every item succeeds (for example, 42 of + 42 gives 0.92--1.00). + + """ + + if total < 1 or not 0 <= successes <= total: + raise ValueError("Need 0 <= successes <= total and total >= 1.") + if not 0.0 < level < 1.0: + raise ValueError("level must be between 0 and 1.") + z = NormalDist().inv_cdf(0.5 + level / 2.0) + proportion = successes / total + denominator = 1.0 + z * z / total + centre = (proportion + z * z / (2.0 * total)) / denominator + half_width = ( + z + * ((proportion * (1.0 - proportion) + z * z / (4.0 * total)) / total) + ** 0.5 + / denominator + ) + # The bounds are exactly 0 or 1 when no item or every item succeeds; + # set them directly, as rounding can otherwise give 0.9999999999999999. + low = 0.0 if successes == 0 else max(0.0, centre - half_width) + high = 1.0 if successes == total else min(1.0, centre + half_width) + return low, high + + def corpus_already_written(directory: Path) -> bool: """Return whether a project's corpus folder is already populated. diff --git a/_si_article_/benchmarks/gold/dogfood_kilin_code.json b/_si_article_/benchmarks/gold/dogfood_kilin_code.json index 1a984528..260472ee 100644 --- a/_si_article_/benchmarks/gold/dogfood_kilin_code.json +++ b/_si_article_/benchmarks/gold/dogfood_kilin_code.json @@ -1,12 +1,12 @@ { "corpus": "kilin-code", - "corpus_description": "KíLín kilin/ package and tutorials/ notebooks from KiLin_source(3).zip (2026-10-23). The source includes the packaged JSON defaults and project types. Citation positions must be rechecked when the KíLín source changes.", + "corpus_description": "KíLín kilin/ package and tutorials/ notebooks at commit 6cb105d20 (2026-12-03). The source includes the packaged JSON defaults and project types. Citation positions must be rechecked when the KíLín source changes.", "tasks": [ { "task_id": "A1", "question": "Why does chunk_source_units skip source units and chunks whose text is only whitespace?", "gold_citations": [ - "kilin/chunking.py:356", + "kilin/chunking.py:356-357", "kilin/chunking.py:861" ], "fact_checklist": [ @@ -21,7 +21,7 @@ "task_id": "A2", "question": "How does code_search match named code entities and rank the corresponding chunks?", "gold_citations": [ - "kilin/retrievals/strategies/retrieval_code.py:227-335" + "kilin/retrievals/strategies/retrieval_code.py:305-420" ], "fact_checklist": [ "It resolves entities explicitly named in a nonblank query.", @@ -37,7 +37,8 @@ "task_id": "A3", "question": "What is KíLín's default RAG system prompt, word for word?", "gold_citations": [ - "kilin/rag.py:307-313" + "kilin/rag.py:436-441", + "kilin/project_types/code.json:16" ], "fact_checklist": [ "It instructs grounding in supplied project evidence.", @@ -52,7 +53,8 @@ "task_id": "A4", "question": "How does RAGSession format numbered evidence for a chat answer?", "gold_citations": [ - "kilin/rag.py:4476-4530" + "kilin/retrievals/evidence_budget.py:190-216", + "kilin/rag.py:7350-7485" ], "fact_checklist": [ "Each item starts with [n] and a path plus line range.", @@ -67,7 +69,7 @@ "task_id": "A5", "question": "Does hybrid_search use Reciprocal Rank Fusion, and what are its default rank constant and count?", "gold_citations": [ - "kilin/retrievals/strategies/retrieval_hybrid.py:106-178" + "kilin/retrievals/strategies/retrieval_hybrid.py:106-190" ], "fact_checklist": [ "Hybrid search uses Reciprocal Rank Fusion (RRF).", @@ -81,8 +83,8 @@ "task_id": "A6", "question": "What happens when scan_repository encounters more than its max_entries limit?", "gold_citations": [ - "kilin/repository.py:437-480", - "kilin/repository.py:550-578" + "kilin/repository.py:437-500", + "kilin/repository.py:566-575" ], "fact_checklist": [ "The default max_entries limit is 10,000.", @@ -96,8 +98,8 @@ "task_id": "A7", "question": "Does EmbeddingSession configure embedding batch_size, or is that specified for build_semantic_index?", "gold_citations": [ - "kilin/retrievals/strategies/retrieval_semantic.py:133-193", - "kilin/embeddings.py:144-165" + "kilin/retrievals/strategies/retrieval_semantic.py:133-202", + "kilin/embeddings.py:144-152" ], "fact_checklist": [ "EmbeddingSession does not take a batch_size constructor argument.", @@ -110,8 +112,8 @@ "task_id": "A8", "question": "What retrieval_count and max_new_tokens defaults does KíLín ship for a new project profile?", "gold_citations": [ - "kilin/kilin_defaults.json:184-193", - "kilin/project.py:214-241" + "kilin/kilin_defaults.json:221-231", + "kilin/project.py:212-239" ], "fact_checklist": [ "Project-profile retrieval_count defaults to 5.", @@ -126,8 +128,8 @@ "question": "What distinguishes KíLín's built-in code and literature project types?", "gold_citations": [ "kilin/project_type.py:1-45", - "kilin/project_types/code.json:1-15", - "kilin/project_types/literature.json:1-15" + "kilin/project_types/code.json:1-16", + "kilin/project_types/literature.json:1-17" ], "fact_checklist": [ "Different project type JSON files select extension lists and source folder names.", @@ -141,8 +143,8 @@ "task_id": "A10", "question": "What data does indexes_are_current compare to determine whether a persisted index can be reused?", "gold_citations": [ - "kilin/retrievals/persistence.py:366-405", - "kilin/retrievals/persistence.py:473-498" + "kilin/retrievals/persistence.py:366-409", + "kilin/retrievals/persistence.py:473-506" ], "fact_checklist": [ "It compares a deterministic SHA-256 fingerprint of chunks and the code graph.", @@ -168,7 +170,7 @@ "task_id": "A12", "question": "Does KíLín use a configurable registry of fourth-party retrieval channels inside RAGSession._retrieve, or explicit search calls?", "gold_citations": [ - "kilin/rag.py:2920-3160" + "kilin/rag.py:4584-4682" ], "fact_checklist": [ "The reviewed retrieval path directly calls semantic_search, lexical_search, and code_search before hybrid fusion.", @@ -230,7 +232,8 @@ "task_id": "A17", "question": "Does KíLín's deterministic context expansion replace or reorder the initial RRF ranking?", "gold_citations": [ - "kilin/retrievals/context_expansion.py:139-255" + "kilin/retrievals/context_expansion.py:260-300", + "kilin/retrievals/context_expansion.py:455-586" ], "fact_checklist": [ "plan_context_expansion identifies explicitly requested context.", @@ -244,7 +247,7 @@ "task_id": "A18", "question": "Which model presets does the KíLín GUI offer, and for which roles and backends?", "gold_citations": [ - "kilin/gui/model_catalog.py:90-166" + "kilin/gui/model_catalog.py:154-175" ], "fact_checklist": [ "The catalog lists six presets in MODEL_CHOICES.", @@ -259,7 +262,7 @@ "task_id": "A19", "question": "How does choose_backend resolve auto, and what happens if MLX is explicitly selected off Apple Silicon?", "gold_citations": [ - "kilin/runtime.py:84-112" + "kilin/runtime.py:84-117" ], "fact_checklist": [ "auto chooses MLX on native Apple Silicon and Torch otherwise.", @@ -273,8 +276,8 @@ "task_id": "A20", "question": "Does the GUI restrict model downloads to MODEL_CHOICES, or does it accept validated custom model identifiers?", "gold_citations": [ - "kilin/gui/engine.py:1157-1190", - "kilin/gui/model_catalog.py:136-155" + "kilin/gui/engine.py:1522-1559", + "kilin/gui/model_catalog.py:1-7" ], "fact_checklist": [ "The GUI catalog lists suggested presets, not an allowlist.", diff --git a/_si_article_/benchmarks/notebooks/60_kilin_dogfood_code.ipynb b/_si_article_/benchmarks/notebooks/60_kilin_dogfood_code.ipynb index 3c4aa1cd..af938987 100644 --- a/_si_article_/benchmarks/notebooks/60_kilin_dogfood_code.ipynb +++ b/_si_article_/benchmarks/notebooks/60_kilin_dogfood_code.ipynb @@ -446,9 +446,11 @@ "\n", "from benchmarks.common import (\n", " abstains,\n", + " bootstrap_interval,\n", " citation_coverage,\n", " citation_validity,\n", " verbatim_overlap_chars,\n", + " wilson_interval,\n", ")\n", "\n", "# Long verbatim overlaps need human review, except the prompt quote (A3).\n", @@ -533,6 +535,39 @@ " \"No answerable question had its gold evidence retrieved \"\n", " \"-- coverage undefined.\"\n", " )\n", + "# 95% intervals: Wilson for counts, bootstrap for the mean coverage.\n", + "answerable_rows = [r for r in tier1_rows if not r[\"requires_abstention\"]]\n", + "unanswerable_rows = [r for r in tier1_rows if r[\"requires_abstention\"]]\n", + "interval_counts = {\n", + " \"citation_valid\": (valid_count, len(tier1_rows)),\n", + " \"abstention_correct\": (abstention_correct_count, len(tier1_rows)),\n", + " \"unanswerable_declined\": (\n", + " sum(1 for r in unanswerable_rows if r[\"abstained\"]),\n", + " len(unanswerable_rows),\n", + " ),\n", + " \"answerable_declined\": (\n", + " sum(1 for r in answerable_rows if r[\"abstained\"]),\n", + " len(answerable_rows),\n", + " ),\n", + " \"answerable_gold_retrieved\": (len(coverage_values), len(answerable_rows)),\n", + "}\n", + "intervals: dict[str, object] = {\n", + " name: {\n", + " \"count\": count,\n", + " \"total\": total,\n", + " \"wilson_95\": [\n", + " round(bound, 3) for bound in wilson_interval(count, total)\n", + " ],\n", + " }\n", + " for name, (count, total) in interval_counts.items()\n", + " if total\n", + "}\n", + "if coverage_values:\n", + " intervals[\"mean_citation_coverage_bootstrap_95\"] = [\n", + " round(bound, 3) for bound in bootstrap_interval(coverage_values)\n", + " ]\n", + "for name, value in intervals.items():\n", + " print(f\"95% interval, {name}: {value}\")\n", "print(\n", " f\"Verbatim-copy flags (>= {VERBATIM_CHAR_THRESHOLD} chars, \"\n", " f\"A3 allows quotation): {verbatim_flags or 'none'}\"\n", @@ -660,6 +695,7 @@ " else None\n", " ),\n", " \"verbatim_flagged_task_ids\": verbatim_flags,\n", + " \"intervals\": intervals,\n", " },\n", " \"per_question\": [\n", " {**row, \"tier1\": tier1} for row, tier1 in zip(run_results, tier1_rows)\n", diff --git a/_si_article_/benchmarks/notebooks/70_deeptrack_dogfood_code.ipynb b/_si_article_/benchmarks/notebooks/70_deeptrack_dogfood_code.ipynb index 1e72c400..2fd5a3a2 100644 --- a/_si_article_/benchmarks/notebooks/70_deeptrack_dogfood_code.ipynb +++ b/_si_article_/benchmarks/notebooks/70_deeptrack_dogfood_code.ipynb @@ -492,9 +492,11 @@ "\n", "from benchmarks.common import (\n", " abstains,\n", + " bootstrap_interval,\n", " citation_coverage,\n", " citation_validity,\n", " verbatim_overlap_chars,\n", + " wilson_interval,\n", ")\n", "\n", "# Long verbatim overlaps indicate possible excessive copying.\n", @@ -579,6 +581,39 @@ " \"No answerable question had its gold evidence retrieved \"\n", " \"-- coverage undefined.\"\n", " )\n", + "# 95% intervals: Wilson for counts, bootstrap for the mean coverage.\n", + "answerable_rows = [r for r in tier1_rows if not r[\"requires_abstention\"]]\n", + "unanswerable_rows = [r for r in tier1_rows if r[\"requires_abstention\"]]\n", + "interval_counts = {\n", + " \"citation_valid\": (valid_count, len(tier1_rows)),\n", + " \"abstention_correct\": (abstention_correct_count, len(tier1_rows)),\n", + " \"unanswerable_declined\": (\n", + " sum(1 for r in unanswerable_rows if r[\"abstained\"]),\n", + " len(unanswerable_rows),\n", + " ),\n", + " \"answerable_declined\": (\n", + " sum(1 for r in answerable_rows if r[\"abstained\"]),\n", + " len(answerable_rows),\n", + " ),\n", + " \"answerable_gold_retrieved\": (len(coverage_values), len(answerable_rows)),\n", + "}\n", + "intervals: dict[str, object] = {\n", + " name: {\n", + " \"count\": count,\n", + " \"total\": total,\n", + " \"wilson_95\": [\n", + " round(bound, 3) for bound in wilson_interval(count, total)\n", + " ],\n", + " }\n", + " for name, (count, total) in interval_counts.items()\n", + " if total\n", + "}\n", + "if coverage_values:\n", + " intervals[\"mean_citation_coverage_bootstrap_95\"] = [\n", + " round(bound, 3) for bound in bootstrap_interval(coverage_values)\n", + " ]\n", + "for name, value in intervals.items():\n", + " print(f\"95% interval, {name}: {value}\")\n", "print(\n", " f\"Verbatim-copy flags (>= {VERBATIM_CHAR_THRESHOLD} chars): \"\n", " f\"{verbatim_flags or 'none'}\"\n", @@ -704,6 +739,7 @@ " else None\n", " ),\n", " \"verbatim_flagged_task_ids\": verbatim_flags,\n", + " \"intervals\": intervals,\n", " },\n", " \"per_question\": [\n", " {**row, \"tier1\": tier1} for row, tier1 in zip(run_results, tier1_rows)\n", diff --git a/_si_article_/code_analysis/code_example.py b/_si_article_/code_analysis/code_example.py index 7e4be064..36225ea2 100644 --- a/_si_article_/code_analysis/code_example.py +++ b/_si_article_/code_analysis/code_example.py @@ -26,7 +26,7 @@ uv run --no-sync python _si_article_/code_analysis/code_example.py \\ --ref v0.1.0 uv run --no-sync python _si_article_/code_analysis/code_example.py \\ - --sets evaluation + --questions routing,chunking Models must already be in the local Hugging Face cache unless ``--allow-download`` is given. @@ -36,6 +36,7 @@ from __future__ import annotations from argparse import ArgumentParser +import ast from collections.abc import Iterable, Sequence from datetime import datetime, timezone import json @@ -56,6 +57,7 @@ open_session, prepare_code_project, routed_intent, + set_router_model, ) ANALYSIS_DIRECTORY = Path(__file__).resolve().parent @@ -133,23 +135,94 @@ def _location(chunk: dict) -> tuple[str, int, int]: ) -def _matches(item: dict, gold: dict) -> bool: - """Tell whether a retrieved passage belongs to a gold function.""" +def gold_lines( + source: Path, gold: Sequence[dict] +) -> dict[tuple[str, str], tuple[int, int]]: + """Find the line range of each gold function in the indexed source. + + Parameters + ---------- + source: pathlib.Path + Folder of the indexed source files. + gold: Sequence[dict] + Gold functions, each with ``path`` and ``symbol`` (``Class.method`` + for a method). + + Returns + ------- + dict[tuple[str, str], tuple[int, int]] + First and last line of each gold function found, by + ``(path, symbol)``. Functions that cannot be found are left out. + + """ + + lines: dict[tuple[str, str], tuple[int, int]] = {} + for entry in gold: + path = source / entry["path"] + try: + node = ast.parse(path.read_text(encoding="utf-8")) + except (OSError, SyntaxError, UnicodeDecodeError): + continue + for part in entry["symbol"].split("."): + node = next( + ( + child for child in ast.iter_child_nodes(node) + if isinstance(child, (ast.FunctionDef, + ast.AsyncFunctionDef, + ast.ClassDef)) + and child.name == part + ), + None, + ) + if node is None: + break + if node is not None: + lines[(entry["path"], entry["symbol"])] = ( + node.lineno, node.end_lineno or node.lineno, + ) + return lines + + +def _matches( + item: dict, + gold: dict, + lines: dict[tuple[str, str], tuple[int, int]] | None = None, +) -> bool: + """Tell whether a retrieved passage holds a gold function. + + A passage holds it when it is the function's own passage, or when it is + a passage of the enclosing class whose lines contain the whole method + (a short class is indexed as one passage). + + """ symbol = item.get("symbol") or "" - return item.get("path") == gold["path"] and ( - symbol == gold["symbol"] or symbol.endswith("." + gold["symbol"]) + if item.get("path") != gold["path"]: + return False + if symbol == gold["symbol"] or symbol.endswith("." + gold["symbol"]): + return True + span = (lines or {}).get((gold["path"], gold["symbol"])) + return ( + span is not None + and bool(symbol) + and gold["symbol"].startswith(symbol + ".") + and int(item.get("start_line") or 0) <= span[0] + and int(item.get("end_line") or 0) >= span[1] ) -def _gold_found(items: Iterable[dict], gold: Sequence[dict]) -> list[str]: +def _gold_found( + items: Iterable[dict], + gold: Sequence[dict], + lines: dict[tuple[str, str], tuple[int, int]] | None = None, +) -> list[str]: """List the gold symbols present among retrieved passages.""" items = list(items) return [ entry["symbol"] for entry in gold - if any(_matches(item, entry) for item in items) + if any(_matches(item, entry, lines) for item in items) ] @@ -202,7 +275,10 @@ def read_retrieval(trace_path: Path) -> dict[str, list[dict]]: def analyze( - retrieval: dict[str, list[dict]], answer: str, gold: Sequence[dict] + retrieval: dict[str, list[dict]], + answer: str, + gold: Sequence[dict], + lines: dict[tuple[str, str], tuple[int, int]] | None = None, ) -> dict[str, object]: """Compare retrieved and cited passages with the gold functions. @@ -214,6 +290,10 @@ def analyze( Visible answer text. gold: Sequence[dict] Gold functions, each with ``path`` and ``symbol``. + lines: dict[tuple[str, str], tuple[int, int]] | None, optional + Line ranges of the gold functions (``gold_lines``), so that a class + passage containing a gold method counts for it. Defaults to None, + which matches symbols only. Returns ------- @@ -243,10 +323,10 @@ def analyze( ), }) found = { - name: _gold_found(retrieval[name], gold) + name: _gold_found(retrieval[name], gold, lines) for name in (*_CHANNELS, "hybrid", "evidence") } - found["cited"] = _gold_found(cited, gold) + found["cited"] = _gold_found(cited, gold, lines) found["code_only"] = [ symbol for symbol in found["code"] @@ -338,7 +418,7 @@ def write_worksheet(path: Path, results: dict, questions: Sequence[dict]): record = by_id[item["id"]] found = record.get("gold_found", {}) lines += [ - f"## {item['id']} ({item['kind']}, {item.get('set')})", + f"## {item['id']} ({item['kind']})", "", f"**Question.** {item['question']}", "", @@ -368,7 +448,11 @@ def write_worksheet(path: Path, results: dict, questions: Sequence[dict]): "**Facts (tick those the answer states correctly):**", "", ] - lines += [f"- [ ] {fact}" for fact in item["facts"]] + core = set(item.get("core_facts", ())) + lines += [ + f"- [ ] {'(core) ' if number in core else ''}{fact}" + for number, fact in enumerate(item["facts"], start=1) + ] lines += [ "", "**Errors or unsupported statements:** ", @@ -468,6 +552,11 @@ def main(argv: Sequence[str] | None = None) -> int: action="store_true", help="use the default intent instead of the router", ) + parser.add_argument( + "--router-model", default=None, + help="intent (router) model of the project, a Hugging Face ID such " + "as Qwen/Qwen3-8B-MLX-4bit (default: the packaged default)", + ) parser.add_argument( "--retrieval-count", type=int, @@ -485,10 +574,9 @@ def main(argv: Sequence[str] | None = None) -> int: help="allow model downloads (first run on a new machine)", ) parser.add_argument( - "--sets", + "--questions", default=None, - help="comma-separated question sets to run, such as evaluation " - "(default: all)", + help="comma-separated question identifiers to run (default: all)", ) args = parser.parse_args(argv) if args.retrieval_count is not None and args.retrieval_count < 1: @@ -502,12 +590,12 @@ def main(argv: Sequence[str] | None = None) -> int: questions = json.loads(QUESTIONS_FILE.read_text(encoding="utf-8"))[ "questions" ] - if args.sets: - wanted = {name.strip() for name in args.sets.split(",")} - unknown = wanted - {item.get("set") for item in questions} + if args.questions: + wanted = {name.strip() for name in args.questions.split(",")} + unknown = wanted - {item["id"] for item in questions} if unknown: - parser.error(f"unknown question set: {sorted(unknown)[0]}") - questions = [item for item in questions if item.get("set") in wanted] + parser.error(f"unknown question: {sorted(unknown)[0]}") + questions = [item for item in questions if item["id"] in wanted] project, revision = prepare_code_project( args.ref, DEFAULT_EXCLUDES, allow_download=args.allow_download ) @@ -516,7 +604,9 @@ def main(argv: Sequence[str] | None = None) -> int: "environment": describe_environment(), "indexed_revision": revision, "use_router": not args.no_router, - "question_sets": sorted({item.get("set") for item in questions}), + "router_model": set_router_model(project, args.router_model), + "temperature": project.profile.temperature, + "questions_run": len(questions), "retrieval_count": args.retrieval_count, } @@ -541,7 +631,6 @@ def main(argv: Sequence[str] | None = None) -> int: record = { "id": item["id"], "kind": item["kind"], - "set": item.get("set"), "intent": routed_intent(trace_path), "wall_s": round(elapsed, 2), "answer": answer, @@ -549,7 +638,10 @@ def main(argv: Sequence[str] | None = None) -> int: } retrieval = read_retrieval(trace_path) if retrieval["evidence"]: - record.update(analyze(retrieval, answer, item["gold"])) + record.update(analyze( + retrieval, answer, item["gold"], + gold_lines(project.source, item["gold"]), + )) records.append(record) print(f" {item['id']}: {elapsed:.1f} s, intent {record['intent']}") results["questions"] = records diff --git a/_si_article_/code_analysis/code_questions.json b/_si_article_/code_analysis/code_questions.json index c618fd5c..f68a466e 100644 --- a/_si_article_/code_analysis/code_questions.json +++ b/_si_article_/code_analysis/code_questions.json @@ -1,11 +1,9 @@ { - "description": "Questions about the KíLín code base for the paper's code example. Each question names code entities (except the location questions) and lists the functions a complete answer must draw on (gold), identified by file and symbol rather than line numbers, so the set stays valid while line numbers change. Facts are for grading answers by hand. The 35 questions in set 'development' were written in successive rounds (field 'round': development, held_out_1, held_out_2, held_out_3, evaluation); each round's results led to retrieval, routing, or prompt changes, so all of them are development questions. The ten questions in set 'evaluation' (round 'evaluation_2') were written after the last change (more fused results for source-code intents), in parts of the code base no earlier question covers, mostly as location questions, and were not run before the evaluation.", + "description": "Questions about the KíLín code base for the paper's code example. Each question names code entities (except the location questions) and lists the functions a complete answer must draw on (gold), identified by file and symbol rather than line numbers, so the set stays valid while line numbers change. Facts are for grading answers by hand; core_facts gives the one-based numbers of the facts that state the main mechanism, and the others are details. The 45 questions were written in rounds while KíLín was being developed, and the results of each round led to retrieval, routing, or prompt changes; they are examples of questions about code, not a held-out benchmark. On 2 December 2026, sixteen questions were reworded so that every question starts with 'Explain' and asks about the code rather than about KíLín (some had started 'Where does KíLín' or 'How does KíLín', or used another tool's words such as 'every place' or 'read a whole file'); four of them now name the function they ask about (kind changed to mechanism). Gold sets and facts were brought up to date with the code on 1 December 2026 (commit f88197142); strip_thinking_callers was narrowed to answering.py because strip_thinking had gained sixteen callers elsewhere.", "questions": [ { "id": "routing", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how route_question assigns a question to an intent, and what happens when the router reply cannot be used.", "gold": [ { @@ -26,14 +24,18 @@ "Otherwise the router model is called through side_reply with a router prompt.", "The reply is parsed by _parse_route into a RouteDecision.", "If the router call fails or its reply is unusable, the project type's default intent is used.", - "Related earlier turns proposed by the router are kept only if the question refers back or shares a distinctive term." + "Related earlier turns proposed by the router are kept only if the question refers back or shares a distinctive term.", + "Wording can overrule the router: a question that matches an intent's cue patterns gets that intent, and a router choice that the wording rules out (an intent's required words missing, or a follow-up tool for a question naming a new file) is routed once more without it." + ], + "core_facts": [ + 1, + 2, + 4 ] }, { "id": "index_reuse", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how RAGSession decides whether to reuse the saved retrieval indexes or to rebuild them.", "gold": [ { @@ -50,13 +52,16 @@ "The embedding-model identity of the saved index must match the current model.", "If the sources changed but the configuration did not, unchanged files keep their saved chunks and vectors and only new or changed files are embedded.", "Any problem with the saved index leads to embedding everything again." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "index_storage", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how build_semantic_index embeds the chunks, and how save_indexes and load_indexes protect the saved index.", "gold": [ { @@ -78,14 +83,17 @@ "save_indexes validates the records and the source fingerprint and stores a payload checksum.", "load_indexes verifies the checksum, the embedding-model identity and the fingerprint.", "The checksum detects accidental corruption; it is not an authenticity guarantee." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "strip_thinking_callers", "kind": "dependency", - "set": "development", - "round": "development", - "question": "Explain which functions call strip_thinking, and why each of them needs to remove the model's reasoning.", + "question": "Explain which functions in answering.py call strip_thinking, and why each of them needs to remove the model's reasoning.", "gold": [ { "path": "kilin/answering.py", @@ -98,19 +106,28 @@ { "path": "kilin/answering.py", "symbol": "history_messages" + }, + { + "path": "kilin/answering.py", + "symbol": "_answer_sentences" } ], "facts": [ - "turn_representation removes reasoning (and citations) from an earlier answer to build the compact representation shown to the router.", - "side_reply returns the reply of an auxiliary model call, such as the router's, without reasoning.", - "history_messages removes reasoning from earlier answers before they are included as conversation history." + "turn_representation removes reasoning from an earlier answer to build the compact representation shown to the router: the cited sources and a summary (a model-written one, or the answer's first sentence).", + "_answer_sentences removes reasoning and citations from an answer and splits off its first sentence, for turn summaries.", + "side_reply returns the reply of an auxiliary model call, such as the router's, without reasoning unless asked to keep it.", + "history_messages removes reasoning from earlier answers before they are included as conversation history, and leaves out incomplete or empty answers." + ], + "core_facts": [ + 1, + 2, + 3, + 4 ] }, { "id": "hybrid_callers", "kind": "dependency", - "set": "development", - "round": "development", "question": "Explain which RAGSession methods call hybrid_search, and how each of them uses the fused ranking.", "gold": [ { @@ -124,20 +141,28 @@ { "path": "kilin/retrievals/strategies/retrieval_hybrid.py", "symbol": "hybrid_search" + }, + { + "path": "kilin/rag.py", + "symbol": "RAGSession._source_passages" } ], "facts": [ - "_retrieve fuses the semantic, lexical and code-graph rankings for the configured retrieval count to select the evidence for an answer.", + "_retrieve fuses the semantic, lexical and code-graph rankings of all candidates, moves tests (and, for source-code intents, documentation) down, and keeps the top results as evidence for an answer.", "_rank_everything ranks every chunk with the same fused channels, for uses that need a complete ranking, such as tools.", + "_source_passages, used by source-first retrieval (literature projects), ranks every passage with the fused channels to choose original passages from the selected sources.", "hybrid_search combines the rankings by reciprocal-rank fusion." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "citation_check", "kind": "location", - "set": "development", - "round": "development", - "question": "Explain where KíLín checks that the citation numbers in an answer refer to the supplied evidence, and what happens when they do not.", + "question": "Explain where the code checks that the citation numbers in an answer refer to the supplied evidence, and what happens when they do not.", "gold": [ { "path": "kilin/rag.py", @@ -151,15 +176,18 @@ "facts": [ "_invalid_citations returns the citation numbers in the answer that do not match any supplied evidence.", "RAGSession.ask records them in the turn parameters as invalid_citations.", - "The answer is neither modified nor regenerated.", + "Only the citation formatting is normalized; the answer is not otherwise changed and is not regenerated.", "The check is syntactic: it does not verify that the cited evidence supports the claim." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "chunking", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how chunk_source_units handles a source unit that is longer than the maximum chunk size, and how the overlap between consecutive chunks is kept.", "gold": [ { @@ -185,13 +213,16 @@ "Otherwise it is split along line boundaries, and within a single line if that line is too long.", "The target size guides where to split; the maximum size is the bound every chunk must respect.", "Overlap with the previous chunk is kept as whole source lines or a character suffix, up to the overlap token limit." + ], + "core_facts": [ + 1, + 3, + 5 ] }, { "id": "rank_everything_callers", "kind": "dependency", - "set": "development", - "round": "development", "question": "Explain which RAGSession methods call _rank_everything, and why each of them needs a ranking of every chunk.", "gold": [ { @@ -211,14 +242,17 @@ "_retrieve ranks every chunk when the question names exactly one document, and keeps that document's best passages, which may not be in the project-wide top results.", "_run_tool gives tools a rank function, so a tool can rank all chunks for any text.", "_read_document ranks all chunks to choose the document to read within the token budget." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "history_selection", "kind": "location", - "set": "development", - "round": "development", - "question": "Explain where KíLín decides which earlier turns of a conversation are given to the model as history, and what determines how many.", + "question": "Explain where the code decides which earlier turns of a conversation are given to the model as history, and what determines how many.", "gold": [ { "path": "kilin/answering.py", @@ -234,13 +268,16 @@ "The intent's history policy decides: none includes nothing, recent includes the last few turns, relevant also adds the turns the router marked as related.", "The number of recent turns comes from the project type (history.recent_turns).", "A question the router judged standalone still receives the previous turn, without its evidence." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "conversation_lock", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how ConversationFileLock prevents two sessions from writing the same conversation file at the same time.", "gold": [ { @@ -258,13 +295,16 @@ "A registry within the process rejects a second owner of the same path before the file is opened.", "The operating system releases the lock when the owning process exits.", "It coordinates KíLín writers only; programs that ignore the lock are not prevented from writing." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "backend_choice", "kind": "mechanism", - "set": "development", - "round": "held_out_1", "question": "Explain how choose_backend selects the computation backend, and which PyTorch device is used when PyTorch is selected.", "gold": [ { @@ -281,13 +321,16 @@ "auto selects MLX on a native Apple silicon Mac (macOS on arm64) and PyTorch otherwise.", "Requesting mlx explicitly on any other platform raises an error.", "With PyTorch, the device is CUDA if available, otherwise Apple MPS if available, otherwise the CPU." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "tool_confirmation", "kind": "mechanism", - "set": "development", - "round": "held_out_1", "question": "Explain how needs_confirmation and confirm_plan decide whether a tool asks the user before running, and what happens with the user's answer.", "gold": [ { @@ -305,13 +348,16 @@ "confirm_plan asks only when a confirmation callback is available and needs_confirmation says so; otherwise it continues.", "The answer can be continue, quick, or cancel; any other answer is treated as cancel.", "The proposed plan and the decision are both recorded in the trace." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "ask_choice_callers", "kind": "dependency", - "set": "development", - "round": "held_out_1", "question": "Explain which functions call ask_choice, and what each of them asks the user to choose.", "gold": [ { @@ -321,19 +367,27 @@ { "path": "kilin/tools/_shared/choose_document.py", "symbol": "choose_document" + }, + { + "path": "kilin/tools/reference_check/tool.py", + "symbol": "_choose_list" } ], "facts": [ "offer_export asks whether to save a long list as a Markdown file in outputs/ or to show only the first items in the chat.", "choose_document asks the user which of several candidate files the question refers to.", - "If the user cancels the document choice, the tool stops and says which files matched." + "If the user cancels the document choice, the tool stops and says which files matched.", + "reference_check's _choose_list asks which reference list to check when a paper has several and the question names none; cancelling stops the check." + ], + "core_facts": [ + 1, + 2, + 4 ] }, { "id": "readable_trace", "kind": "mechanism", - "set": "development", - "round": "held_out_1", "question": "Explain when TraceLogger rewrites the human-readable trace file, and how it avoids leaving a partially written file.", "gold": [ { @@ -350,18 +404,20 @@ } ], "facts": [ - "The file is rewritten after each recorded event; progress updates rewrite it at most every half second.", + "The file is rewritten after each recorded event; progress updates and answer-activity events rewrite it at most every half second.", "It is also rewritten when the conversation data is updated.", "A new temporary file replaces the target in one step, while the exclusive lock on the companion file is held.", "Repeated writes replace this run's part of the file without duplicating it or overwriting earlier runs.", "If writing fails, the event stays in memory and the failure is handled rather than raised." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "workspace_sync", "kind": "mechanism", - "set": "development", - "round": "held_out_1", "question": "Explain how synchronize_project_workspace keeps its copy of a source folder up to date with the original folder.", "gold": [ { @@ -383,13 +439,15 @@ "Before using that comparison, the copied files are rehashed and checked against the saved manifest; if the copy was changed, it is rebuilt from the original.", "Otherwise only added and modified files are copied and removed files deleted, then empty folders are removed.", "The new manifest, with the source folder's path, is saved for the next synchronization. The original folder is never modified." + ], + "core_facts": [ + 2, + 4 ] }, { "id": "cached_model_callers", "kind": "dependency", - "set": "development", - "round": "held_out_2", "question": "Explain which functions call cached_model_snapshot, and when each of them uses it instead of downloading the model.", "gold": [ { @@ -407,14 +465,16 @@ "Both call cached_model_snapshot only when downloads are not allowed and the model ID is not a local folder.", "When downloads are allowed, _model_source calls snapshot_download with local_files_only=False, and ChatSession._load passes the model ID to the backend loader, which may fetch missing files.", "cached_model_snapshot never downloads (local_files_only=True) and raises FileNotFoundError if the cached snapshot has no config.json." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "file_selection", - "kind": "location", - "set": "development", - "round": "held_out_2", - "question": "Where does KíLín decide which files of a source folder are indexed, and which files does it always leave out?", + "kind": "mechanism", + "question": "Explain how scan_repository decides which files of a source folder are indexed, and which files it always leaves out.", "gold": [ { "path": "kilin/repository.py", @@ -431,14 +491,17 @@ "Environment, cache, and generated folders (such as .git, .venv, __pycache__, node_modules, build, logs, weights) are skipped.", "Potentially secret files (.env and .env.*, credentials.json, secrets.json, SSH keys) and model weights or key files by suffix (.safetensors, .pt, .gguf, .pem, .key, ...) are always skipped.", "Otherwise files are skipped when excluded by the user's selection, outside the included paths, not regular files, of an unselected file type, empty, or larger than the size limit." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "query_format", "kind": "location", - "set": "development", - "round": "held_out_2", - "question": "How is a question turned into the text that is embedded for semantic search, and does this depend on the project type?", + "question": "Explain how a question is turned into the text that is embedded for semantic search, and whether this depends on the project type.", "gold": [ { "path": "kilin/rag.py", @@ -452,16 +515,19 @@ "facts": [ "With the plain query format in the project profile, the question is embedded unchanged.", "Otherwise the text has two lines, 'Instruct: ' and 'Query: ', the format used by Qwen3 embedding models.", - "The instruction is the project type's retrieval instruction, so it depends on the project type.", + "The instruction is the project type's retrieval instruction (or the project's own, when its behavior settings override it), so it depends on the project type.", "The instruction must be a single nonempty line; surrounding whitespace is removed from both parts.", "Documents are embedded without this instruction." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "conversation_delete", "kind": "mechanism", - "set": "development", - "round": "held_out_2", "question": "Explain what happens to a saved conversation when ChatEngine.delete_conversation is called. Is the conversation file really deleted?", "gold": [ { @@ -474,18 +540,20 @@ } ], "facts": [ - "The file is not deleted: ConversationStore.archive moves it into a deleted folder under logs/traces, so it can be recovered.", + "The file is not deleted: ConversationStore.archive moves it into a hidden .deleted folder under logs/traces, so it can be recovered; its lock companion file stays in place.", "If a file with the same name is already there, the moved file gets a _2, _3, ... suffix.", "The conversation's write lock is held while the file is moved, and the conversation is removed from the store's list.", "If it was the last conversation, a new empty one is created; if it was the active one, the most recently updated remaining conversation becomes active.", "The engine detaches the trace when the active conversation is deleted, switches to the replacement, and records a conversation.deleted event; on errors the list is refreshed and the error reported." + ], + "core_facts": [ + 1, + 2 ] }, { "id": "torch_embedding", "kind": "mechanism", - "set": "development", - "round": "held_out_2", "question": "Explain how EmbeddingSession computes vectors with the PyTorch backend, which token's hidden state it uses, and how the vectors are checked before they are returned.", "gold": [ { @@ -507,14 +575,17 @@ "Vectors are L2-normalized.", "_check_vectors requires one vector per text, the same nonzero dimension for all, finite numeric values, and no all-zero vector; otherwise it raises RuntimeError.", "embed_documents rejects empty or blank texts and a closed session, and does not truncate inputs." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "notebook_extraction", "kind": "location", - "set": "development", - "round": "held_out_3", - "question": "Where does KíLín turn a Jupyter notebook into searchable text, and which parts of a notebook are left out?", + "question": "Explain how the notebook source extension turns a Jupyter notebook into searchable text, and which parts of a notebook it leaves out.", "gold": [ { "path": "kilin/sources/extensions/sources_ipynb.py", @@ -531,13 +602,15 @@ "Empty cells are skipped.", "Each kept cell is one unit with its one-based position in the original cell list (skipped cells included) and line numbers local to the cell; a Markdown cell's first heading becomes its section.", "A malformed notebook raises ValueError." + ], + "core_facts": [ + 1, + 2 ] }, { "id": "atomic_files", "kind": "mechanism", - "set": "development", - "round": "held_out_3", "question": "Explain how atomic_write_text and atomic_create_text write a file so that it is never left half-written, and how the two differ.", "gold": [ { @@ -555,13 +628,16 @@ "atomic_create_text publishes with a hard link (os.link), so it fails with FileExistsError if the destination already exists and never overwrites; unsupported hard links fail instead of falling back.", "The temporary file is removed in all cases, including failures.", "Neither takes a lock nor forces the data to disk (no fsync)." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "claim_passages_callers", "kind": "dependency", - "set": "development", - "round": "held_out_3", "question": "Explain which functions call claim_passages, and what each of them uses the selected passages for.", "gold": [ { @@ -571,20 +647,28 @@ { "path": "kilin/tools/suggest_reference/tool.py", "symbol": "run" + }, + { + "path": "kilin/tools/reference_check/tool.py", + "symbol": "_second_look" } ], "facts": [ - "The reference_check tool's _verify calls it for each citing claim, with the citing sentence (citation marks removed) and what the reference is cited for, over the cited file's passages; verify_claim then has the model judge whether they support the claim.", + "The reference_check tool's _verify calls it for each citing claim, with the citing sentence (citation marks removed, and the preceding sentence added when the sentence refers back to it), what the reference is cited for, and the focus proposed for co-cited works, over the cited file's passages; verify_claim then has the model judge whether they support the claim.", + "_second_look calls it again for a claim judged not supported or with no matching passage, skipping the passages already read, and a better verdict from these passages replaces the first.", "The suggest_reference tool's run calls it for each candidate paper with the user's statement; judge_support then has the model judge whether that paper supports the statement.", "claim_passages fuses the rankings of its texts by reciprocal rank, keeps at most count passages within a token budget (the best one is always kept), and returns them in reading order." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "model_identity", "kind": "location", - "set": "development", - "round": "held_out_3", - "question": "How does KíLín identify the embedding model that built a saved index, so that it can tell when the model has changed?", + "question": "Explain how the code identifies the embedding model that built a saved index, so that it can tell when the model has changed.", "gold": [ { "path": "kilin/retrievals/model_identity.py", @@ -605,13 +689,16 @@ "Per-file hashes are cached in a manifest outside the model folder and reused when file size, times, device, and inode are unchanged; force_verify rehashes every file.", "The identity is stored with the index; a different identity means the saved vectors are not reused.", "It is meant for index compatibility, not authentication." + ], + "core_facts": [ + 1, + 2, + 4 ] }, { "id": "conversation_branch", "kind": "mechanism", - "set": "development", - "round": "held_out_3", "question": "Explain how ConversationStore creates a branch of a conversation: what is copied from the parent, how the branch is named, and how it avoids overwriting an existing file.", "gold": [ { @@ -624,19 +711,22 @@ } ], "facts": [ - "With branch_from, the parent's saved resumable state is copied, except its metadata fields, while holding the parent's write lock; old trace operations are not copied.", - "The branch records its parent conversation and the parent's checkpoint identifier.", - "It is named ' branch N' with the first N not already used; a new independent conversation is named 'Conversation N'.", + "With branch_from, the parent's saved resumable state is copied, except its metadata fields, while holding the parent's write lock; old trace operations are not copied, and turn_count can keep only the parent's first turns (then the parent's checkpoint is not copied).", + "The branch records its parent conversation, the parent's checkpoint identifier, and the number of turns kept.", + "A branch is named 'Branch: ', then 'Branch 2: ' and so on, after the original conversation even for a branch of a branch, cut to 80 characters; a new independent conversation is named 'Conversation N'.", "A new file path is chosen, locked, and checked; if it already exists, FileExistsError is raised instead of overwriting.", "The new conversation is registered and becomes the active one." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "python_units", "kind": "location", - "set": "development", - "round": "evaluation", - "question": "How does KíLín divide a Python file into the parts it indexes, and what happens to a file that is not valid Python?", + "question": "Explain how the Python source extension divides a Python file into units, and what happens to a file that is not valid Python.", "gold": [ { "path": "kilin/sources/extensions/sources_py.py", @@ -652,14 +742,17 @@ "Each top-level function becomes one unit, and the code between definitions (imports, constants) becomes module-context units.", "A class becomes one class unit whose children are its methods and the class-level code between them.", "A file that does not parse (SyntaxError) becomes a single python_file unit." + ], + "core_facts": [ + 1, + 2, + 4 ] }, { "id": "pdf_text", "kind": "location", - "set": "development", - "round": "evaluation", - "question": "How does KíLín get the text out of a PDF file, and what happens when a PDF contains no text?", + "question": "Explain how the PDF source extension extracts the text of a PDF file, and what happens when a PDF contains no text.", "gold": [ { "path": "kilin/sources/extensions/sources_pdf.py", @@ -680,14 +773,17 @@ "The text is cleaned (invalid Unicode surrogates, unmapped glyphs, trailing spaces, repeated blank lines).", "A PDF with no extractable text raises an error saying scanned PDFs need OCR.", "Pages are joined with a page break, and each non-empty page becomes one unit labelled with its page number." + ], + "core_facts": [ + 1, + 4, + 5 ] }, { "id": "call_relations", "kind": "location", - "set": "development", - "round": "evaluation", - "question": "How does KíLín work out which functions call which other functions in Python code, and what happens when a called name could refer to several functions?", + "question": "Explain how the code graph works out which functions call which other functions in Python code, and what happens when a called name could refer to several functions.", "gold": [ { "path": "kilin/retrievals/code_graph/extensions/code_graph_py.py", @@ -707,14 +803,17 @@ "For every call, the called expression is turned into a dotted name (a plain name or attribute chain) and recorded as a calls relation from the enclosing function, method, class, or module.", "The name is resolved by its last component against the known entities: a unique match gives the qualified name.", "An ambiguous name is kept as written (unless only one candidate differs from the name itself), so no call is guessed; calls through non-static expressions are not recorded." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "keyword_scoring", "kind": "location", - "set": "development", - "round": "evaluation", - "question": "How are passages scored in KíLín's keyword search, and how are code identifiers broken into searchable words?", + "question": "Explain how the lexical search scores passages, and how code identifiers are split into searchable words.", "gold": [ { "path": "kilin/retrievals/strategies/retrieval_lexical.py", @@ -734,13 +833,16 @@ "Adjacent words also form two-word terms; there is no stemming or stop-word removal.", "Each passage and the query become TF-IDF vectors with sublinear term frequency (1 + log f) and smoothed inverse document frequency, normalized to unit length.", "Passages are ranked by cosine similarity, ties by chunk identifier, with no minimum score." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "follow_up_query", "kind": "mechanism", - "set": "development", - "round": "evaluation", "question": "Explain how refers_back decides that a question depends on the earlier conversation, and how search_text uses that to build the search query.", "gold": [ { @@ -757,13 +859,16 @@ "search_text returns the question unchanged unless the routing decision refers back and lists related turns.", "Otherwise it appends the questions of the related turns, with whitespace normalized, after the new question.", "Model-written text (earlier answers) is never added to the query." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "download_progress", "kind": "mechanism", - "set": "development", - "round": "evaluation", "question": "Explain how download_model reports download progress to its caller, and where the downloaded model files are stored.", "gold": [ { @@ -781,13 +886,15 @@ "That class disables terminal output and reports only the aggregate byte bar as (completed bytes, total bytes).", "Because a disabled tqdm stops counting, the class keeps the count itself.", "It returns the snapshot path and does not load the model." + ], + "core_facts": [ + 1, + 2 ] }, { "id": "reference_matching", "kind": "mechanism", - "set": "development", - "round": "evaluation", "question": "Explain how match_reference decides which project file a reference entry points to, and when a match is only probable.", "gold": [ { @@ -805,13 +912,16 @@ "Otherwise the score is the share of the file's title words found in the entry (or of the entry's words found on the first page when there is no title), compared with found and probable thresholds.", "A high score with a different first author, or a lower score with the same first author, is only probable.", "Found matches come before probable ones, then higher scores; other matches are listed as alternatives; an entry with too few distinctive words is unreadable, and one with no candidate is missing." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "term_hits_callers", "kind": "dependency", - "set": "development", - "round": "evaluation", "question": "Explain which functions call term_hits, and what each of them does with the passages it returns.", "gold": [ { @@ -833,13 +943,16 @@ "find_fact's run uses them for its quick version: only the parts that contain a hit, per file.", "find_passages' run uses them for its quick version: the sentences of those passages, found without the model.", "Without terms, each falls back to the best-ranked passages." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "explicit_imports_callers", "kind": "dependency", - "set": "development", - "round": "evaluation", "question": "Explain which functions call include_explicit_imports, and why each of them needs it.", "gold": [ { @@ -856,13 +969,16 @@ "_prepare_retrieval uses the scan to build the source manifest and compare it with the saved index, to decide whether to reuse or rebuild it.", "_prepare_source uses it (when no report is supplied) to choose which files to read and split into chunks.", "include_explicit_imports adds files the user imported one by one (recorded in sources.json) even when their suffix or name would otherwise be skipped; size limits and link safeguards still apply, and imported folders keep the normal rules." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "extension_callers", "kind": "dependency", - "set": "development", - "round": "evaluation", "question": "Explain which functions call normalize_extensions, and what each of them checks with it.", "gold": [ { @@ -883,14 +999,17 @@ "_read_profile checks the extensions setting of a project's profile.ini.", "_parse_project_type checks the extensions declared by a project-type JSON file.", "scan_repository checks the extensions it is asked to select before scanning." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "markdown_sections", "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does KíLín split a Markdown file into searchable parts, and what happens to the opening lines that come before any heading?", + "question": "Explain how the Markdown source extension splits a Markdown file into searchable parts, and what happens to the opening lines that come before any heading.", "gold": [ { "path": "kilin/sources/extensions/sources_md.py", @@ -906,14 +1025,16 @@ "Headings inside backtick or tilde code fences are ignored.", "The text before the first heading becomes a separate preamble unit.", "Each section keeps its heading title and original line range; nested structure and underlined (setext) headings are not recognized." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "matlab_calls", "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does KíLín work out which functions a MATLAB file calls, and how does this differ from the way it handles Python?", + "question": "Explain how the code graph works out which functions a MATLAB file calls, and how this differs from the way it handles Python.", "gold": [ { "path": "kilin/retrievals/code_graph/extensions/code_graph_m.py", @@ -921,19 +1042,22 @@ } ], "facts": [ - "MATLAB relations come from regular expressions over the text, not from a parser; the code is never run.", + "MATLAB relations come from regular expressions over the text, with comments and strings skipped, not from a parser; the code is never run.", "A classdef makes the class the parent of the file's functions and records inheritance from its base class.", - "Each function's body runs until the next function declaration; every name followed by an opening parenthesis in it is recorded as a call, except control words such as if, for, while, and switch.", + "Each function's body runs until the next function declaration; every name followed by an opening parenthesis in it is recorded as a call (by its last name for a call through an object), except control words such as if, for, while, and switch; py.module.function(...) is recorded as a call into Python.", "Names are resolved against known entities with the shared name resolution, as for Python.", - "Python files are parsed into syntax trees instead; MATLAB matches can miss or misread comments, strings, and nested constructs." + "Python files are parsed into syntax trees instead; MATLAB matches can miss or misread multiline declarations and nested definitions." + ], + "core_facts": [ + 1, + 3, + 5 ] }, { "id": "long_document", - "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "When a question asks KíLín to read a whole file that does not fit in the evidence budget, how are the parts the model sees chosen?", + "kind": "mechanism", + "question": "Explain how read_document chooses the chunks of a long file to give the model when the whole file does not fit in the evidence budget.", "gold": [ { "path": "kilin/retrievals/document_reading.py", @@ -949,14 +1073,17 @@ "If the whole file fits the budget (estimated tokens), it is supplied whole.", "Otherwise its chunks are taken in the order of the fused search ranking, unranked chunks last; a chunk that does not fit is skipped while smaller later ones may still fit.", "The selected chunks are given to the model in source order, all from one file." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "exact_mentions", - "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does KíLín find every place where an exact name appears in the project, and how does it avoid matching the name inside a longer word?", + "kind": "mechanism", + "question": "Explain how scan_mentions matches a term only as a whole word, and how it avoids counting overlapping chunks twice.", "gold": [ { "path": "kilin/tools/_shared/mentions.py", @@ -976,14 +1103,16 @@ "Each term becomes a regular expression whose parts may be joined by spaces, underscores, or hyphens.", "With whole words, the term may not continue into adjacent letters or digits (MRI does not match MRIs).", "Case sensitivity is an option (the code project's mention listing matches case); each occurrence keeps its file, line, and a few context lines." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "answer_streaming", - "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does the desktop app show an answer while the model is still writing it?", + "kind": "mechanism", + "question": "Explain how ChatEngine.ask and _AnswerStream send the answer to the window while the model is still generating it.", "gold": [ { "path": "kilin/gui/engine.py", @@ -1003,14 +1132,17 @@ "The stream buffers pieces and sends them to the window as answer_delta events at most every 0.08 seconds.", "After the answer, flush sends whatever is left.", "With MLX the text arrives piece by piece; PyTorch generation is not streamed, so it arrives at once." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "superscript_citations", "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does KíLín recognize citation numbers printed as small raised numbers in a PDF, and how does it avoid mistaking other raised numbers for citations?", + "question": "Explain how the reference check recognizes citation numbers printed as small raised numbers in a PDF, and how it avoids mistaking other raised numbers for citations.", "gold": [ { "path": "kilin/tools/reference_check/_citations.py", @@ -1027,17 +1159,19 @@ ], "facts": [ "pdfminer.six reads each line's characters with their size and position; digits, commas, and dashes smaller than a set share of the line's median letter size and raised above its baseline form a superscript run.", - "Each run is stored with the text printed just before it, as a signature.", + "Each run is stored with the text printed just before it as a signature, or, for a run printed first on its line, with the text printed after it.", "A number found in a sentence counts as a superscript citation only when the PDF confirms a matching raised run there.", "Superscripts in author lists, affiliations, and equations are skipped; a written-out 'Ref. 50' needs no confirmation.", "If the PDF cannot be read this way, no superscript is confirmed." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "claim_verdict", "kind": "mechanism", - "set": "evaluation", - "round": "evaluation_2", "question": "Explain how verify_claim reaches a verdict on a cited claim, and how the quote the model gives is checked.", "gold": [ { @@ -1058,14 +1192,18 @@ "Otherwise the model sees the claim and the cited passages and replies with a verdict, a quote, and a comment.", "An unrecognized verdict becomes 'unclear', with the reply as comment.", "The quote is kept only if it is found in a passage word for word, or for most of its words in order; otherwise it is dropped and the comment says so.", - "'contradicted' without a confirmed quote becomes 'not supported'." + "'contradicted' without a confirmed quote becomes 'not supported'.", + "Each verdict gets an evidence status: exact or approximate when the quote is found, rejected when it is not, not required for not supported, no matching passage, or unclear, and missing otherwise." + ], + "core_facts": [ + 2, + 4, + 5 ] }, { "id": "output_saving", "kind": "mechanism", - "set": "evaluation", - "round": "evaluation_2", "question": "Explain how save_output_file writes a tool's output into the project without overwriting an existing file.", "gold": [ { @@ -1087,13 +1225,16 @@ "It is then published under the requested name with a hard link, which fails if the name exists; the next candidates are name-2, name-3, and so on.", "If hard links are not supported, the staged file is copied into a newly and exclusively created file, which also cannot overwrite.", "The staging file is removed afterwards; concurrent saves get different names." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "newest_listed_callers", "kind": "dependency", - "set": "evaluation", - "round": "evaluation_2", "question": "Explain which functions call newest_listed, and what each of them does with the earlier turn it returns.", "gold": [ { @@ -1110,13 +1251,15 @@ "filter_results' run judges that turn's listed items against the question in batches with the model and keeps the matching ones.", "show_source's run picks the cited passages of that turn that the question and the earlier answer point to, and shows their text word for word with nearby sentences.", "Without such a turn, both reply that there is no earlier answer to work from." + ], + "core_facts": [ + 2, + 3 ] }, { "id": "workspace_path_callers", "kind": "dependency", - "set": "evaluation", - "round": "evaluation_2", "question": "Explain which functions call default_workspace_path, and when each of them uses the folder it suggests.", "gold": [ { @@ -1129,10 +1272,14 @@ } ], "facts": [ - "default_workspace_path suggests -<8-character hash of its path> inside a parent folder, without creating or reserving it.", + "default_workspace_path suggests -<8-character hash of its path> inside a parent folder, or new-project when there are no sources, without creating or reserving it.", "The GUI's _workspace_path uses it when the user has not chosen a workspace folder; a chosen folder is used as given.", "prepare_sources_workspace uses it when given a parent folder instead of a workspace folder.", "Creation reserves the folder exclusively and may pick a numbered sibling if the suggested folder is taken." + ], + "core_facts": [ + 2, + 3 ] } ] diff --git a/_si_article_/code_analysis/paper_numbers.py b/_si_article_/code_analysis/paper_numbers.py index 96284c81..0f6bce29 100644 --- a/_si_article_/code_analysis/paper_numbers.py +++ b/_si_article_/code_analysis/paper_numbers.py @@ -58,6 +58,7 @@ sys.path.insert(0, str(REPOSITORY_ROOT)) from assets.trace_benchmark import ( # noqa: E402 + _operation_rows, read_trace_operations, summarize_trace_turns, ) @@ -95,6 +96,9 @@ # Initialization operations reported separately from question turns. _STARTUP_OPERATIONS = ( "session.ready", + "source.read", + "source.extract", + "source.chunk", "model.embedding.load", "model.chat.load", "indexing", @@ -247,19 +251,60 @@ def export_revision( return {"ref": ref, "commit": commit, "excluded": list(excludes)} -def _disable_downloads(profile_path: Path) -> None: - """Set ``allow_download = false`` in a sandbox project profile.""" +def default_temperature(type_id: str) -> float: + """Return the temperature a new project of this type starts with. - text = profile_path.read_text(encoding="utf-8") - updated, count = re.subn( - r"^(\s*allow_download\s*=\s*).*$", - r"\1false", - text, - flags=re.M, + Parameters + ---------- + type_id: str + Project type ID, such as ``code`` or ``literature``. + + Returns + ------- + float + The type's own temperature, or the packaged default when the type + does not set one. + + """ + + from kilin.project import _PROFILE_TEMPERATURE + from kilin.project_type import load_project_types + + temperature = load_project_types()[type_id].generation_temperature + return _PROFILE_TEMPERATURE if temperature is None else temperature + + +def set_router_model(project: object, model_id: str | None) -> str: + """Save the project's intent (router) model and return it. + + Parameters + ---------- + project: kilin.QAProject + Sandbox project to configure. + model_id: str | None + Hugging Face model ID or local folder, or None for the packaged + default. Writing the default too means a model saved by an earlier + run never carries over. + + Returns + ------- + str + The router model the project now uses. + + """ + + import kilin + from kilin.model_settings import ( + default_router_model, + read_router_model, + write_router_model, ) - if count != 1: - raise RuntimeError("Could not find allow_download in profile.ini.") - profile_path.write_text(updated, encoding="utf-8") + + backend = kilin.choose_backend(project.profile.backend) + write_router_model( + project.root, backend, model_id or default_router_model(backend) + ) + return read_router_model(project.root, backend) def prepare_code_project( @@ -280,7 +325,9 @@ def prepare_code_project( Returns ------- tuple[kilin.QAProject, dict[str, object]] - The sandbox project and the description of the indexed revision. + The sandbox project, set to the code type's default temperature + (also in a workspace saved with another value), and the description + of the indexed revision. Notes ----- @@ -324,8 +371,15 @@ def prepare_code_project( f"Expected the sandbox workspace {workspace}, " f"got {project.root}." ) - if not allow_download: - _disable_downloads(project.root / "profile.ini") + from kilin.project import configure_project + + project = configure_project( + project.root, + { + "temperature": default_temperature("code"), + "allow_download": allow_download, + }, + ) return project, revision @@ -421,11 +475,94 @@ def peak_memory_gb() -> dict[str, float]: return result -def _startup_operations(trace_path: Path, label: str) -> dict[str, float]: - """Sum completed initialization operations of one traced opening.""" +# Since the project trace was introduced, startup events (indexing, model +# loading) are recorded in logs/traces/project.json rather than in the +# conversation trace; each session's entries end with its trace ID. +_PROJECT_TRACE = Path("logs") / "traces" / "project.json" +_TRACE_SUFFIX = re.compile(r"_(trace_[0-9a-f]+)$") + + +def _project_sessions(project_root: Path) -> dict[str, dict]: + """Return the project trace's sessions, or none when it is absent.""" + + path = project_root / _PROJECT_TRACE + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + sessions = payload.get("sessions") if isinstance(payload, dict) else None + return sessions if isinstance(sessions, dict) else {} + +def project_trace_ids(project_root: Path) -> frozenset[str]: + """List the session trace IDs already in the project trace. + + Parameters + ---------- + project_root: pathlib.Path + KíLín workspace. + + Returns + ------- + frozenset[str] + Trace IDs (``trace_…``) of the recorded sessions; empty when the + project has no project trace. + + """ + + return frozenset( + match.group(1) + for key in _project_sessions(project_root) + if (match := _TRACE_SUFFIX.search(key)) + ) + + +def _startup_operations( + trace_path: Path, + label: str, + project_root: Path | None = None, + known: frozenset[str] = frozenset(), +) -> dict[str, float]: + """Sum completed initialization operations of one traced opening. + + Parameters + ---------- + trace_path: pathlib.Path + Conversation trace of the session. + label: str + Run label. + project_root: pathlib.Path | None, optional + Workspace whose project trace holds the startup events in current + KíLín versions. Defaults to None (conversation trace only). + known: frozenset[str], optional + Trace IDs present before the session opened (``project_trace_ids``), + so that only the new session's events are counted. Defaults to none. + + Returns + ------- + dict[str, float] + Seconds per startup operation; empty when no events were recorded. + + """ + + rows = list(read_trace_operations(trace_path, label)) + if project_root is not None: + for key, session in _project_sessions(project_root).items(): + match = _TRACE_SUFFIX.search(key) + if ( + match is None + or match.group(1) in known + or not isinstance(session, dict) + or not isinstance(session.get("operations"), dict) + ): + continue + rows.extend(_operation_rows( + session["operations"], label=label, + category=str(session.get("category", "")), stage="", + turn=None, + )) totals: dict[str, float] = defaultdict(float) - for row in read_trace_operations(trace_path, label): + for row in rows: if ( row.get("turn") is None and row.get("status") == "completed" @@ -542,6 +679,11 @@ def main(argv: Sequence[str] | None = None) -> int: action="store_true", help="use the default intent instead of the router", ) + parser.add_argument( + "--router-model", default=None, + help="intent (router) model of the project, a Hugging Face ID such " + "as Qwen/Qwen3-8B-MLX-4bit (default: the packaged default)", + ) parser.add_argument( "--include-examples", action="store_true", @@ -573,6 +715,7 @@ def main(argv: Sequence[str] | None = None) -> int: ["git", "-C", str(REPOSITORY_ROOT), "rev-parse", "HEAD"] ), "use_router": not args.no_router, + "temperature": default_temperature("code"), } # 1. Export the pinned revision outside the repository and mirror it. @@ -581,6 +724,7 @@ def main(argv: Sequence[str] | None = None) -> int: args.ref, excludes, allow_download=args.allow_download ) results["indexed_revision"] = revision + results["router_model"] = set_router_model(project, args.router_model) project_root = project.root backend = kilin.choose_backend(project.profile.backend) results["models"] = { @@ -593,19 +737,25 @@ def main(argv: Sequence[str] | None = None) -> int: if index_file.exists(): index_file.unlink() _reset_backend_peak() + known = project_trace_ids(project_root) session, cold = open_session(project_root, "cold") trace_path = Path(session.conversation_path) session.close() - cold["operations_s"] = _startup_operations(trace_path, "cold") + cold["operations_s"] = _startup_operations( + trace_path, "cold", project_root, known + ) results["cold_open"] = cold results["corpus"] = corpus_size(project_root, project.source) print(f"Cold opening: {cold['wall_s']} s ({cold['index_status']})") # 3. Warm opening with unchanged sources. + known = project_trace_ids(project_root) session, warm = open_session(project_root, "warm") warm_trace = Path(session.conversation_path) session.close() - warm["operations_s"] = _startup_operations(warm_trace, "warm") + warm["operations_s"] = _startup_operations( + warm_trace, "warm", project_root, known + ) results["warm_open"] = warm print(f"Warm opening: {warm['wall_s']} s ({warm['index_status']})") diff --git a/_si_article_/literature_repo/papers/hosseini12gat.pdf b/_si_article_/literature_repo/papers/hosseini12gat.pdf new file mode 100644 index 00000000..609fce98 Binary files /dev/null and b/_si_article_/literature_repo/papers/hosseini12gat.pdf differ diff --git a/_si_article_/literature_repo/papers/mijalkov21dendritic.pdf b/_si_article_/literature_repo/papers/mijalkov21dendritic.pdf new file mode 100644 index 00000000..be538fe4 Binary files /dev/null and b/_si_article_/literature_repo/papers/mijalkov21dendritic.pdf differ diff --git a/_si_article_/literature_repo/papers/tanner24multimodal.pdf b/_si_article_/literature_repo/papers/tanner24multimodal.pdf new file mode 100644 index 00000000..0fe326ab Binary files /dev/null and b/_si_article_/literature_repo/papers/tanner24multimodal.pdf differ diff --git a/_si_article_/literature_repo/papers/wang15gretna.pdf b/_si_article_/literature_repo/papers/wang15gretna.pdf new file mode 100644 index 00000000..933f0fcd Binary files /dev/null and b/_si_article_/literature_repo/papers/wang15gretna.pdf differ diff --git a/_si_article_/literature_repo/papers/xia13brainnet.pdf b/_si_article_/literature_repo/papers/xia13brainnet.pdf new file mode 100644 index 00000000..b1153239 Binary files /dev/null and b/_si_article_/literature_repo/papers/xia13brainnet.pdf differ diff --git a/_si_article_/literature_repo/papers/yan25roadmap.pdf b/_si_article_/literature_repo/papers/yan25roadmap.pdf new file mode 100644 index 00000000..02b2c4b2 Binary files /dev/null and b/_si_article_/literature_repo/papers/yan25roadmap.pdf differ diff --git a/_si_article_/reference_analysis/make_planted.py b/_si_article_/reference_analysis/make_planted.py new file mode 100644 index 00000000..ff262468 --- /dev/null +++ b/_si_article_/reference_analysis/make_planted.py @@ -0,0 +1,241 @@ +"""Make the copy of the reference-example article with planted miscitations. + +Each planted miscitation changes one bracketed citation number in the +article, such as ``[15]`` to ``[25]``, so that the sentence now cites a work +in the project that does not support it. + +The copy is a plain-text file: the article's text read with the PDF reader +KíLín itself uses (pdfminer.six, with the same layout settings), with the +numbers changed. Editing the PDF instead (covering a number and printing +another) splits the edited lines into separate text blocks for that +reader, so the sentences around each change would no longer be read as +they are printed. + +The script writes the copy next to the annotation file under the name in +its ``planted_file`` key, and records the changes in its ``planted`` key, +which ``reference_example.py`` scores. Run it from the repository root, +then check the copy:: + + uv run --no-sync python \\ + _si_article_/reference_analysis/make_planted.py + uv run --no-sync python \\ + _si_article_/reference_analysis/reference_example.py --only planted + +The six "clear" changes cite a work on an unrelated subject; the two +"near" changes cite a related work (another toolbox; another paper that +uses BRAPH 2), which the tool may judge partly supported rather than flag. +Only citations that the unmodified run judged supported, with an exact +quotation, are changed, so a flag can come only from the change. + +""" + +from __future__ import annotations + +from argparse import ArgumentParser +from collections.abc import Sequence +import json +from pathlib import Path +import re +import sys + +REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +ANALYSIS_DIRECTORY = Path(__file__).resolve().parent +ANNOTATIONS_FILE = ANALYSIS_DIRECTORY / "reference_annotations.json" + +# Each change: the words printed just before the marker (to find it), the +# original and planted numbers, how clear the mismatch is, and a few +# distinctive words of the citing sentence (for scoring). +PLANTS: tuple[dict[str, object], ...] = ( + {"before": "[14], GAT", "original": 15, "planted": 25, + "kind": "clear", + "text": "Many free and open-source software platforms"}, + {"before": "BrainNet Viewer", "original": 17, "planted": 20, + "kind": "clear", + "text": "Many free and open-source software platforms"}, + {"before": "elimination pipeline for deep learning", "original": 22, + "planted": 3, "kind": "clear", + "text": "recursive feature elimination pipeline for deep learning"}, + {"before": "loss in postmortem brain tissue", "original": 25, + "planted": 18, "kind": "clear", + "text": "dendritic spine loss in postmortem brain tissue"}, + {"before": "approaches for evaluating cognitive decline", "original": 23, + "planted": 15, "kind": "clear", + "text": "reservoir computing approaches for evaluating cognitive"}, + {"before": "pipeline for recursive feature elimination", "original": 22, + "planted": 17, "kind": "clear", + "text": "Its flexibility is illustrated through three case studies"}, + {"before": "Viewer [17], GRETNA", "original": 18, "planted": 15, + "kind": "near", + "text": "Many free and open-source software platforms"}, + {"before": "study brain network memory capacity", "original": 23, + "planted": 22, "kind": "near", + "text": "standalone distribution for reservoir computing to study"}, +) + + +def article_text(article: Path) -> str: + """Read the article's text as KíLín reads a PDF file. + + Parameters + ---------- + article: pathlib.Path + The article. + + Returns + ------- + str + The text from pdfminer.six with default layout settings. + + """ + + from pdfminer.high_level import extract_text + from pdfminer.layout import LAParams + + return extract_text(str(article), laparams=LAParams()) + + +def marker_pattern(plant: dict[str, object]) -> re.Pattern[str]: + """Return the pattern of one marker after its preceding words. + + Parameters + ---------- + plant: dict[str, object] + One entry of ``PLANTS``. + + Returns + ------- + re.Pattern[str] + Matches the words (separated by any white space) and the marker; + the number is the group ``number``. + + """ + + words = [re.escape(word) for word in str(plant["before"]).split()] + return re.compile( + r"\s+".join(words) + + r"\s*\[(?P" + str(plant["original"]) + r")\]" + ) + + +def make_copy(article: Path, output: Path) -> list[dict[str, object]]: + """Write the text copy of the article with every planned change. + + Parameters + ---------- + article: pathlib.Path + The original article. + output: pathlib.Path + Path of the copy. + + Returns + ------- + list[dict[str, object]] + The changes made, for the annotation file. + + Raises + ------ + SystemExit + If a marker is not found exactly once. + + """ + + text = article_text(article) + spans = [] + for plant in PLANTS: + matches = list(marker_pattern(plant).finditer(text)) + if len(matches) != 1: + raise SystemExit( + f"Expected one [{plant['original']}] after " + f"'{plant['before']}', found {len(matches)}." + ) + spans.append((matches[0].span("number"), plant)) + # Replace from the end, so earlier positions stay valid. + for (start, end), plant in sorted(spans, key=lambda s: -s[0][0]): + text = text[:start] + str(plant["planted"]) + text[end:] + output.write_text(text, encoding="utf-8") + return [dict(plant) for _, plant in spans] + + +def check_copy(output: Path, changes: list[dict[str, object]]) -> None: + """Confirm that every planted number follows its words in the copy. + + Parameters + ---------- + output: pathlib.Path + The copy. + changes: list[dict[str, object]] + The changes made. + + Raises + ------ + SystemExit + If a planted number is missing. + + """ + + text = output.read_text(encoding="utf-8") + for change in changes: + # The preceding words can hold another changed marker. + before = str(change["before"]) + for other in changes: + before = before.replace( + f"[{other['original']}]", f"[{other['planted']}]" + ) + planted = {**change, "before": before, "original": change["planted"]} + if not marker_pattern(planted).search(text): + raise SystemExit( + f"[{change['planted']}] after '{change['before']}' is not " + "in the copy." + ) + + +def main(argv: Sequence[str] | None = None) -> int: + """Make the planted copy and record it in the annotation file. + + Parameters + ---------- + argv: Sequence[str] | None, optional + Command-line arguments. Defaults to ``None``, which reads + ``sys.argv``. + + Returns + ------- + int + Exit status, 0 on success. + + """ + + parser = ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--annotations", type=Path, default=ANNOTATIONS_FILE, + help="annotation file (default: reference_annotations.json)", + ) + args = parser.parse_args(argv) + + annotations = json.loads(args.annotations.read_text(encoding="utf-8")) + article = REPOSITORY_ROOT / annotations["corpus_folder"] / ( + annotations["article"] + ) + output = args.annotations.parent / annotations["planted_file"] + changes = make_copy(article, output) + check_copy(output, changes) + annotations["planted"] = [ + {key: change[key] for key in + ("text", "original", "planted", "kind", "before")} + for change in changes + ] + args.annotations.write_text( + json.dumps(annotations, indent=2, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + for change in changes: + print(f"[{change['original']}] → " + f"[{change['planted']}] ({change['kind']}) after " + f"'{change['before']}'") + print(f"Wrote {output.relative_to(REPOSITORY_ROOT)} and the 'planted' " + f"list of {args.annotations.name}.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/_si_article_/reference_analysis/reference_annotations.json b/_si_article_/reference_analysis/reference_annotations.json new file mode 100644 index 00000000..5834f898 --- /dev/null +++ b/_si_article_/reference_analysis/reference_annotations.json @@ -0,0 +1,227 @@ +{ + "_instructions": [ + "Hand annotations for reference_example.py. Keys starting with '_' are ignored.", + "article: file name of the citing article inside corpus_folder.", + "corpus_folder: folder of the corpus, relative to the repository root; the script exports it with git archive, so commit it first.", + "planted_file: text copy of the article with planted miscitations, written by make_planted.py next to this file (it may stay outside git). It is added to the papers project under its own file name, which must differ from the article's.", + "Projects (as in the app): sandbox/reference_example/project_reference_papers holds the article, the planted copy and the cited works; project_reference_suggest holds the cited works only.", + "check_question and suggest_question: the requests, as a user would type them.", + "references: for each reference number, the expected project file (file name), or null when the cited work is not in the project. Leave it empty to report the counts only.", + "citations: every in-text citation identified by hand in the original article, before looking at the tool's output. text = a few distinctive words of the citing sentence, copied from the PDF; references = all numbers the marker cites (expand ranges: [1-4] gives 1, 2, 3, 4).", + "planted: written by make_planted.py; one entry per planted miscitation. text = distinctive words of the citing sentence; original = the number printed in the published article; planted = the number in the copy; kind = clear or near.", + "suggestions: test sentences for suggest_reference, written without a citation marker and fixed before running. group = tools, uses, results (one work states it; expected lists that file) or background (several works support it; expected lists every acceptable file). Specific sentences state what the expected work reports, as a careful author would cite it." + ], + "article": "tiunn26braph2.pdf", + "corpus_folder": "_si_article_/literature_repo/papers", + "planted_file": "tiunn26braph2_planted.txt", + "check_question": "Check the references of {article}", + "suggest_question": "Suggest a reference for: \"{sentence}\"", + "references": {}, + "citations": [], + "planted": [ + { + "text": "Many free and open-source software platforms", + "original": 15, + "planted": 25, + "kind": "clear", + "before": "[14], GAT" + }, + { + "text": "Many free and open-source software platforms", + "original": 17, + "planted": 20, + "kind": "clear", + "before": "BrainNet Viewer" + }, + { + "text": "recursive feature elimination pipeline for deep learning", + "original": 22, + "planted": 3, + "kind": "clear", + "before": "elimination pipeline for deep learning" + }, + { + "text": "dendritic spine loss in postmortem brain tissue", + "original": 25, + "planted": 18, + "kind": "clear", + "before": "loss in postmortem brain tissue" + }, + { + "text": "reservoir computing approaches for evaluating cognitive", + "original": 23, + "planted": 15, + "kind": "clear", + "before": "approaches for evaluating cognitive decline" + }, + { + "text": "Its flexibility is illustrated through three case studies", + "original": 22, + "planted": 17, + "kind": "clear", + "before": "pipeline for recursive feature elimination" + }, + { + "text": "Many free and open-source software platforms", + "original": 18, + "planted": 15, + "kind": "near", + "before": "Viewer [17], GRETNA" + }, + { + "text": "standalone distribution for reservoir computing to study", + "original": 23, + "planted": 22, + "kind": "near", + "before": "study brain network memory capacity" + } + ], + "suggestions": [ + { + "group": "tools", + "text": "GAT is an open-source toolbox for graph-theoretical analysis of between-group differences in brain networks.", + "expected": [ + "hosseini12gat.pdf" + ] + }, + { + "group": "tools", + "text": "BrainNet Viewer is a tool for visualizing brain connectomes.", + "expected": [ + "xia13brainnet.pdf" + ] + }, + { + "group": "tools", + "text": "GRETNA is an open-source toolbox with a graphical user interface for imaging connectomics.", + "expected": [ + "wang15gretna.pdf" + ] + }, + { + "group": "tools", + "text": "BRAPH is an object-oriented software for graph-theory analysis of brain connectivity with a graphical user interface.", + "expected": [ + "mijalkov17braph.pdf" + ] + }, + { + "group": "uses", + "text": "Recursive feature elimination with deep learning has been used to classify schizophrenia from brain connectivity.", + "expected": [ + "yao25connecting.pdf" + ] + }, + { + "group": "uses", + "text": "Reservoir computing has been used to measure the memory capacity of brain networks in cognitive decline.", + "expected": [ + "mijalkov25computational.pdf" + ] + }, + { + "group": "uses", + "text": "Dendritic spine organization has been compared between neurons with and without tau pathology in postmortem brain tissue.", + "expected": [ + "mijalkov21dendritic.pdf" + ] + }, + { + "group": "uses", + "text": "Deploying machine learning in healthcare requires monitoring models after deployment.", + "expected": [ + "yan25roadmap.pdf" + ] + }, + { + "group": "results", + "text": "Tau pathology causes dendritic spines to be lost in clusters rather than at random locations.", + "expected": [ + "mijalkov21dendritic.pdf" + ] + }, + { + "group": "results", + "text": "The memory capacity of brain-network reservoirs is a robust marker of aging and is associated with cognitive performance.", + "expected": [ + "mijalkov25computational.pdf" + ] + }, + { + "group": "results", + "text": "Subregions of the hippocampus and amygdala show the strongest enrichment of genetic risk for schizophrenia.", + "expected": [ + "yao25connecting.pdf" + ] + }, + { + "group": "results", + "text": "Survivors of acute lymphoblastic leukemia show altered small-world organization of structural brain networks.", + "expected": [ + "hosseini12gat.pdf" + ] + }, + { + "group": "results", + "text": "Directed and signed edge weights estimated from multimodal data are subject-specific and highly reliable.", + "expected": [ + "tanner24multimodal.pdf" + ] + }, + { + "group": "background", + "text": "Network analyses have rapidly gained traction in neuroscience, linking brain regions, clinical scores, and biomarkers.", + "expected": [ + "tanner24multimodal.pdf", + "hosseini12gat.pdf", + "wang15gretna.pdf", + "xia13brainnet.pdf", + "mijalkov17braph.pdf", + "yao25connecting.pdf", + "mijalkov25computational.pdf" + ] + }, + { + "group": "background", + "text": "Reproducibility of analysis workflows is an increasingly important concern.", + "expected": [ + "mijalkov17braph.pdf", + "yan25roadmap.pdf", + "tanner24multimodal.pdf" + ] + } + ], + "_examples": { + "references": { + "19": "mijalkov17braph.pdf", + "13": null + }, + "citations": [ + { + "text": "linking multiple brain regions, clinical scores, and biomarkers", + "references": [ + 1, + 2, + 3, + 4 + ] + } + ], + "planted": [ + { + "text": "and BRAPH 1", + "original": 19, + "planted": 22 + } + ], + "suggestions": [ + { + "group": "tools", + "text": "BRAPH 1 is a free and open-source software platform for brain connectivity analysis.", + "expected": [ + "mijalkov17braph.pdf" + ] + } + ] + } +} diff --git a/_si_article_/reference_analysis/reference_example.py b/_si_article_/reference_analysis/reference_example.py new file mode 100644 index 00000000..587dd96a --- /dev/null +++ b/_si_article_/reference_analysis/reference_example.py @@ -0,0 +1,1275 @@ +"""Run the paper's reference example: checking and suggesting references. + +The script builds two literature projects from a committed revision of +the article corpus, as a user would in the desktop app, and asks KíLín, +through the ordinary answering pipeline (router, tool, saved conversation +and trace): + +- project ``reference_papers``: the article, the copy of the article with + planted miscitations, and the works the article cites. Two requests: + check the references of the article (run ``check``), and of the copy + (run ``planted``). A check reads only the named paper and the files its + references match, so the other copy does not take part. +- project ``reference_suggest``: the cited works only. One request per + test sentence for a reference to cite (run ``suggest``). The article and + its copy contain every test sentence word for word, and + ``suggest_reference`` cannot be told to leave a file out, so they are not + in this project. + +Each request is asked in a new conversation; the same requests typed in +the app on the same folders give the same answers. + +Every project generates at the default temperature of the literature +type, as in the app, so a rerun can give slightly different verdicts. +Confirmation prompts are answered "continue": every claim is +checked. The workspaces are kept under ``sandbox/reference_example/`` with +fixed names, so they can be opened in the desktop app afterwards and the +saved conversations used for the figures. + +Scoring uses the hand annotations in ``reference_annotations.json``: + +- reference matching: the file matched to each reference entry, against + the expected file when the annotations give one; +- citation detection: detected (sentence, reference) pairs against the + pairs identified by hand (precision and recall); +- claim checking: the verdict of each planted miscitation (flagged when + "not supported" or "contradicted") and of every unmodified citation of + the original article (flagged ones are possible false alarms, listed for + reading); +- suggestion: for sentences that one work states (tools, uses, results), + the rank of that work among the papers the tool suggested, in the order + of its answer; for background sentences, the rank of the best of the + acceptable works and how many of them were suggested. Papers with the + same verdict and score share a rank, reported as a tie. + +Matching and citation detection are rule-based: the script recomputes them +with the tool's own functions on the indexed passages and checks that the +counts agree with those the tool reported. Verdicts and suggestions are +read from the session trace. + +Results are written to ``_si_article_/reference_analysis/results/`` as +JSON, with a Markdown worksheet for reading the verdicts. + +Usage, from the repository root:: + + uv run --no-sync python \\ + _si_article_/reference_analysis/reference_example.py + uv run --no-sync python \\ + _si_article_/reference_analysis/reference_example.py \\ + --ref v0.1.0 --planted path/to/article_planted.pdf + uv run --no-sync python \\ + _si_article_/reference_analysis/reference_example.py --only check + +Models must already be in the local Hugging Face cache unless +``--allow-download`` is given. + +""" + +from __future__ import annotations + +from argparse import ArgumentParser +from collections.abc import Callable, Sequence +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory, gettempdir +from time import perf_counter + +REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +if str(REPOSITORY_ROOT) not in sys.path: + sys.path.insert(0, str(REPOSITORY_ROOT)) + +from _si_article_.code_analysis.paper_numbers import ( # noqa: E402 + default_temperature, + describe_environment, + routed_intent, + set_router_model, + show_progress, +) + +ANALYSIS_DIRECTORY = Path(__file__).resolve().parent +ANNOTATIONS_FILE = ANALYSIS_DIRECTORY / "reference_annotations.json" +OUTPUT_DIRECTORY = ANALYSIS_DIRECTORY / "results" +WORKSPACE_DIRECTORY = REPOSITORY_ROOT / "sandbox" / "reference_example" + +# Every run generates at the literature type's default temperature. +TEMPERATURE = default_temperature("literature") + +# Verdicts that flag a citation as a problem. +FLAGGED = ("not supported", "contradicted") + +RUNS = ("check", "planted", "suggest") + + +# ------------------------------------------------------------------------- +# Small helpers +# ------------------------------------------------------------------------- + + +def normalized(text: str) -> str: + """Return text reduced to lowercase letters and digits. + + Parameters + ---------- + text: str + Text from a PDF or from the annotations. + + Returns + ------- + str + The text without spaces, punctuation or line-break hyphens, so a + sentence extracted from a PDF matches the annotation of it. + + """ + + return re.sub(r"[^a-z0-9]", "", text.lower()) + + +def sha256(path: Path) -> str: + """Return the SHA-256 digest of a file. + + Parameters + ---------- + path: pathlib.Path + File to hash. + + Returns + ------- + str + Hexadecimal digest. + + """ + + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +def git(*arguments: str) -> str: + """Run a git command in the repository and return its output. + + Parameters + ---------- + *arguments: str + Arguments after ``git -C ``. + + Returns + ------- + str + Stripped standard output. + + Raises + ------ + RuntimeError + If git fails. + + """ + + completed = subprocess.run( + ["git", "-C", str(REPOSITORY_ROOT), *arguments], + capture_output=True, text=True, + ) + if completed.returncode != 0: + raise RuntimeError( + f"git {' '.join(arguments)} failed: {completed.stderr.strip()}" + ) + return completed.stdout.strip() + + +def code_version() -> dict[str, object]: + """Describe the KíLín code that runs the example. + + Returns + ------- + dict[str, object] + The checked-out commit, the installed package version, and whether + ``kilin/`` has uncommitted changes (results of a modified checkout + do not correspond to any commit). + + """ + + import kilin + + changes = git("status", "--porcelain", "--", "kilin") + return { + "commit": git("rev-parse", "HEAD"), + "describe": git("describe", "--tags", "--always", "--dirty"), + "package_version": getattr(kilin, "__version__", None), + "uncommitted_kilin_changes": bool(changes), + } + + +def trace_details(trace_path: Path, operation: str) -> list[dict]: + """Return the details of every traced operation with a given name. + + Parameters + ---------- + trace_path: pathlib.Path + Conversation trace of one session. + operation: str + Operation name without its sequence prefix, such as + ``tool_reference_check_claim``. + + Returns + ------- + list[dict] + The ``details`` of each matching operation, in trace order. + + """ + + found: list[tuple[int, dict]] = [] + + def walk(node: object) -> None: + if isinstance(node, dict): + for key, value in node.items(): + if ( + isinstance(value, dict) + and re.fullmatch(rf"\d+_{operation}", key) + ): + sequence = value.get("event", {}).get("sequence", 0) + found.append((sequence, value.get("details", {}))) + walk(value) + elif isinstance(node, list): + for item in node: + walk(item) + + walk(json.loads(trace_path.read_text(encoding="utf-8"))) + return [details for _, details in sorted(found, key=lambda x: x[0])] + + +# ------------------------------------------------------------------------- +# Corpus and projects +# ------------------------------------------------------------------------- + + +def export_corpus(ref: str, folder: str, destination: Path) -> dict: + """Export the corpus folder of one committed revision. + + Parameters + ---------- + ref: str + Git revision, tag or branch. + folder: str + Corpus folder, relative to the repository root. + destination: pathlib.Path + Empty directory that receives the files of the folder. + + Returns + ------- + dict + The requested reference and the resolved commit. + + Raises + ------ + RuntimeError + If the revision or the folder cannot be exported. + + """ + + commit = git("rev-parse", ref) + archive = subprocess.run( + ["git", "-C", str(REPOSITORY_ROOT), "archive", "--format=tar", + commit, "--", folder], + capture_output=True, + ) + if archive.returncode != 0: + raise RuntimeError( + f"Cannot export {folder} at {ref}: " + f"{archive.stderr.decode(errors='replace').strip()}" + ) + with TemporaryDirectory() as unpacked: + subprocess.run( + ["tar", "-x", "-C", unpacked], input=archive.stdout, check=True + ) + source = Path(unpacked) / folder + for path in sorted(source.rglob("*")): + if path.is_file(): + target = destination / path.relative_to(source) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, target) + return {"ref": ref, "commit": commit, "folder": folder} + + +def stage_sources( + corpus: Path, + article: str, + planted: Path | None, + planted_name: str, + staging: Path, +) -> dict[str, Path]: + """Prepare the source folder of each project. + + Parameters + ---------- + corpus: pathlib.Path + The exported corpus: the article and the works it cites. + article: str + File name of the article within the corpus. + planted: pathlib.Path | None + The copy of the article with planted miscitations, or None. + planted_name: str + File name of the copy in the project. + staging: pathlib.Path + Empty directory for the two source folders. + + Returns + ------- + dict[str, pathlib.Path] + ``papers``: the whole corpus and the copy; ``suggest``: the corpus + without the article. The folder names fix the workspace names + (``project_reference_papers`` and ``project_reference_suggest``). + + """ + + files = [path for path in sorted(corpus.rglob("*")) if path.is_file()] + + def fill(name: str, keep: list[Path]) -> Path: + folder = staging / f"reference_{name}" + folder.mkdir(parents=True) + for path in keep: + target = folder / path.relative_to(corpus) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, target) + return folder + + papers = fill("papers", files) + if planted is not None: + shutil.copy2(planted, papers / planted_name) + suggest = fill( + "suggest", + [path for path in files if path.relative_to(corpus).as_posix() + != article], + ) + return {"papers": papers, "suggest": suggest} + + +def open_project(source: Path, allow_download: bool) -> object: + """Create or synchronize a literature workspace for one run. + + Parameters + ---------- + source: pathlib.Path + Source folder of the run. + allow_download: bool + Keep model downloads enabled. + + Returns + ------- + kilin.QAProject + The workspace ``sandbox/reference_example/project_``, + set to the literature type's default temperature (also in a + workspace saved with another value). + + """ + + import kilin + from kilin.project import configure_project + + WORKSPACE_DIRECTORY.mkdir(parents=True, exist_ok=True) + workspace = WORKSPACE_DIRECTORY / f"project_{source.name}" + project = None + if workspace.exists(): + try: + project = kilin.synchronize_project_workspace(source, workspace) + except (OSError, ValueError) as error: + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + retired = workspace.with_name(f"{workspace.name}_old_{stamp}") + print(f"Cannot reuse {workspace.name} ({error}); " + f"renamed it to {retired.name}.") + workspace.rename(retired) + if project is None: + project = kilin.prepare_project_workspace( + source, "literature", WORKSPACE_DIRECTORY + ) + if project.root != workspace: + raise RuntimeError( + f"Expected the workspace {workspace}, got {project.root}." + ) + return configure_project( + project.root, + {"temperature": TEMPERATURE, "allow_download": allow_download}, + ) + + +def open_session(project_root: Path) -> object: + """Open a traced session on a workspace. + + Parameters + ---------- + project_root: pathlib.Path + Workspace to open. + + Returns + ------- + kilin.RAGSession + The open session. + + """ + + import kilin + + session = kilin.RAGSession( + project_root, + progress_callback=show_progress, + trace=kilin.TraceConfig(enabled=True), + ) + print() + return session + + +def ask(session: object, question: str) -> dict[str, object]: + """Ask one question as a user would, and record what happened. + + Parameters + ---------- + session: kilin.RAGSession + Open session. + question: str + The question. + + Returns + ------- + dict[str, object] + The answer, the routed intent, the tool's summary, the trace file + and the time. Every confirmation is answered "continue"; a request + to choose between options is recorded and cancelled, since the + questions name the paper. + + """ + + choices: list[dict[str, object]] = [] + + def choose(question_text: str, options: Sequence[str]) -> None: + choices.append({"question": question_text, "options": list(options)}) + return None + + started = perf_counter() + answer = session.ask( + question, + confirm_callback=lambda plan: "continue", + choice_callback=choose, + ) + elapsed = perf_counter() - started + trace_path = Path(session.conversation_path) + turn = session.turns[-1] + return { + "question": question, + "answer": answer, + "intent": routed_intent(trace_path), + "tool_summary": dict(turn.parameters.get("tool") or {}), + "choices_requested": choices, + "trace_file": str(trace_path.relative_to(REPOSITORY_ROOT)), + "wall_s": round(elapsed, 1), + } + + +# ------------------------------------------------------------------------- +# Rule-based stage: reference matching and citation detection +# ------------------------------------------------------------------------- + + +def rule_based_report(session: object, article: str) -> object: + """Recompute the tool's rule-based check of the article. + + Parameters + ---------- + session: kilin.RAGSession + Session on a project containing the article. + article: str + The article's file name, as indexed. + + Returns + ------- + kilin.tools.reference_check.ReferenceReport + Reference entries, the file matched to each, and the in-text + citations, without verdicts (no model is called). + + Notes + ----- + This calls the same functions as the tool, in the same way, so its + results equal those behind the tool's answer; ``score_check`` verifies + the counts against the tool's summary. When the article has several + reference lists, the last one is used, as the tool does by default. + + """ + + from collections import defaultdict + + from kilin.tools._shared.references import reference_lists + from kilin.tools.reference_check import _configuration as config + from kilin.tools.reference_check import check_references + from kilin.tools.reference_check._matching import paper_identity + from kilin.tools.reference_check._resolution import linkable_entry + + source_root = Path(session.project.source) + by_file: dict[Path, list] = defaultdict(list) + for chunk in session.chunks: + by_file[Path(chunk.path)].append(chunk) + paper = Path(article) + if paper not in by_file: + raise RuntimeError(f"{article} has no indexed passages.") + + def on_disk(path: Path) -> Path | None: + file = source_root / path + return file if file.is_file() else None + + others = [ + paper_identity(path, passages, on_disk(path), config.MATCH_RULES) + for path, passages in by_file.items() + if path != paper and path.suffix.lower() not in {".bib", ".bbl"} + ] + lists = reference_lists( + by_file[paper], config.REFERENCE_LAYOUT, on_disk(paper), + accept_short=linkable_entry, + ) + if len(lists) > 1: + print(f"Note: {article} has {len(lists)} reference lists; " + "scoring the last one.") + return check_references( + paper, by_file[paper], on_disk(paper), others, -1 + ) + + +def detected_pairs(report: object) -> list[dict[str, object]]: + """List the (sentence, reference) pairs the tool detected. + + Parameters + ---------- + report: ReferenceReport + Rule-based report of the article. + + Returns + ------- + list[dict[str, object]] + One entry per reference number cited in each sentence: the number, + the marker as printed, the sentence's line and text. + + """ + + pairs: dict[tuple[int, int, str], dict[str, object]] = {} + for citation in report.scan.citations: + sentence = citation.sentence + for number in citation.numbers: + key = (number, sentence.line, sentence.text) + pairs.setdefault(key, { + "reference": number, + "marker": citation.marker, + "line": sentence.line, + "sentence": sentence.text, + }) + return list(pairs.values()) + + +def score_check( + report: object, + tool_summary: dict[str, object], + annotations: dict[str, object], +) -> dict[str, object]: + """Score reference matching and citation detection. + + Parameters + ---------- + report: ReferenceReport + Rule-based report of the original article. + tool_summary: dict[str, object] + Summary returned by the tool for the same article. + annotations: dict[str, object] + The hand annotations. + + Returns + ------- + dict[str, object] + Matching counts and, when annotated, matches against the expected + files; citation detection precision and recall against the pairs + identified by hand; and whether the recomputed counts agree with + the tool's. + + """ + + entries = [ + { + "reference": entry.number, + "entry": entry.text, + "status": match.status, + "file": match.path.as_posix() if match.path else None, + "reason": match.reason, + } + for entry, match in zip(report.entries, report.matches) + ] + counts = { + status: sum(e["status"] == status for e in entries) + for status in ("found", "probable", "missing", "unreadable") + } + + expected = { + int(number): file + for number, file in (annotations.get("references") or {}).items() + if not str(number).startswith("_") + } + matching: dict[str, object] = {"counts": counts} + if expected: + correct = wrong = missed = 0 + for entry in entries: + want = expected.get(entry["reference"], "unannotated") + if want == "unannotated": + continue + got = entry["file"] if entry["status"] in ( + "found", "probable") else None + if want is None and got is None: + correct += 1 + elif want is not None and got == want: + correct += 1 + elif got is None: + missed += 1 + else: + wrong += 1 + matching.update( + {"annotated": len(expected), "correct": correct, + "wrong_file": wrong, "missed": missed} + ) + + detected = detected_pairs(report) + manual = [ + {"reference": number, "text": item["text"]} + for item in annotations.get("citations", []) + for number in item["references"] + ] + detection: dict[str, object] = { + "detected": len(detected), + "uncited": list(report.scan.uncited), + "beyond_list": list(report.scan.beyond_list), + "style": report.scan.style, + } + if manual: + def same(pair: dict, item: dict) -> bool: + return ( + pair["reference"] == item["reference"] + and normalized(item["text"]) in normalized(pair["sentence"]) + ) + + true_detected = [ + p for p in detected if any(same(p, m) for m in manual) + ] + found_manual = [m for m in manual if any(same(p, m) for p in detected)] + detection.update({ + "manual": len(manual), + "true_detected": len(true_detected), + "precision": round(len(true_detected) / len(detected), 3) + if detected else None, + "recall": round(len(found_manual) / len(manual), 3), + "missed": [m for m in manual if m not in found_manual], + "extra": [p for p in detected if p not in true_detected], + }) + + agreement = { + key: (counts[key], tool_summary.get(key)) + for key in ("found", "probable", "missing", "unreadable") + } + agreement["references"] = (len(entries), tool_summary.get("references")) + agreement["citations"] = ( + len(report.scan.citations), tool_summary.get("citations") + ) + return { + "entries": entries, + "matching": matching, + "detection": detection, + "agrees_with_tool": all(a == b for a, b in agreement.values()), + "agreement": {k: list(v) for k, v in agreement.items()}, + } + + +# ------------------------------------------------------------------------- +# Model stage: verdicts and suggestions +# ------------------------------------------------------------------------- + + +def claims_of(trace_path: Path) -> list[dict[str, object]]: + """Return every checked claim of a reference check, from its trace. + + Parameters + ---------- + trace_path: pathlib.Path + Trace of the session that ran the check. + + Returns + ------- + list[dict[str, object]] + Reference number, cited file, line, citing sentence, verdict, + quotation status and reading stage of each claim. + + """ + + keep = ( + "reference", "cited", "line", "citation_sentence", "cited_for", + "verdict", "evidence_status", "quote_found", "quote_lines", + "match_status", "verdict_stage", "suitability", + ) + return [ + {key: details.get(key) for key in keep} + for details in trace_details(trace_path, "tool_reference_check_claim") + ] + + +def score_planted( + claims: list[dict[str, object]], planted: list[dict[str, object]] +) -> dict[str, object]: + """Score the verdicts of the planted miscitations. + + Parameters + ---------- + claims: list[dict[str, object]] + Checked claims of the copy with planted miscitations. + planted: list[dict[str, object]] + Annotated miscitations: ``text`` (distinctive words of the citing + sentence), ``original`` and ``planted`` reference numbers. + + Returns + ------- + dict[str, object] + Per planted citation, the claim found for it and its verdict; the + number flagged ("not supported" or "contradicted"). + + """ + + rows = [] + for item in planted: + match = next( + ( + claim for claim in claims + if claim["reference"] == item["planted"] + and normalized(item["text"]) + in normalized(claim["citation_sentence"] or "") + ), + None, + ) + rows.append({ + **item, + "checked": match is not None, + "verdict": match["verdict"] if match else None, + "flagged": bool(match and match["verdict"] in FLAGGED), + "claim": match, + }) + return { + "planted": len(planted), + "checked": sum(row["checked"] for row in rows), + "flagged": sum(row["flagged"] for row in rows), + "rows": rows, + } + + +def score_unmodified(claims: list[dict[str, object]]) -> dict[str, object]: + """Count the verdicts on the original article's citations. + + Parameters + ---------- + claims: list[dict[str, object]] + Checked claims of the original article. + + Returns + ------- + dict[str, object] + Claims checked, the count of each verdict, and the flagged claims + (possible false alarms, to be read: some may be real problems of + the published article). + + """ + + verdicts: dict[str, int] = {} + for claim in claims: + verdicts[claim["verdict"]] = verdicts.get(claim["verdict"], 0) + 1 + flagged = [claim for claim in claims if claim["verdict"] in FLAGGED] + return { + "checked": len(claims), + "verdicts": verdicts, + "flagged": len(flagged), + "flagged_claims": flagged, + } + + +def suggestion_rank( + trace_path: Path, expected: Sequence[str] +) -> dict[str, object]: + """Rank the expected works among the papers the tool suggested. + + Parameters + ---------- + trace_path: pathlib.Path + Trace of the session that ran the suggestion. + expected: Sequence[str] + File names of the works that answer the sentence: the cited work + for a specific sentence, every acceptable work for a background one. + + Returns + ------- + dict[str, object] + The papers in the order of the tool's answer (best verdict first, + then the suitability score); ``rank``, the best position of an + expected work among those suggested (1 = first; papers with the same + verdict and score share a position), or None when none was + suggested; ``tied``, whether another paper shares that position; + and ``expected_suggested``, how many expected works were suggested. + + """ + + from kilin.tools.suggest_reference.tool import _ORDER, _SUGGESTED + + def key(paper: dict) -> tuple[int, int]: + return ( + _ORDER.get(paper.get("verdict"), 99), + -(paper.get("suitability_score") or 0), + ) + + papers = trace_details(trace_path, "tool_suggest_reference_paper") + ordered = sorted(papers, key=key) + suggested = [p for p in ordered if p.get("verdict") in _SUGGESTED] + wanted = set(expected) + hits = [p for p in suggested if Path(p["paper"]).name in wanted] + rank = tied = None + if hits: + best = key(hits[0]) + rank = 1 + sum(key(p) < best for p in suggested) + tied = any( + key(p) == best and Path(p["paper"]).name not in wanted + for p in suggested + ) + return { + "papers": [ + {"paper": p["paper"], "verdict": p.get("verdict"), + "score": p.get("suitability_score"), + "evidence_status": p.get("evidence_status")} + for p in ordered + ], + "expected_checked": sum( + Path(p["paper"]).name in wanted for p in papers + ), + "expected_suggested": len(hits), + "rank": rank, + "tied": tied, + } + + +def suggestion_scores( + suggest: Sequence[dict[str, object]], +) -> dict[str, dict[str, object]]: + """Count the suggestion results of each group of sentences. + + Parameters + ---------- + suggest: Sequence[dict[str, object]] + Per sentence, the recorded result with ``group``, ``rank`` and + ``tied``. + + Returns + ------- + dict[str, dict[str, object]] + Per group: sentences, expected work first (alone or tied), first + with a tie, in the top three, and suggested at all. + + """ + + groups: dict[str, dict[str, object]] = {} + for item in suggest: + counts = groups.setdefault(item.get("group", "ungrouped"), { + "sentences": 0, "first": 0, "first_tied": 0, "top3": 0, + "suggested": 0, + }) + rank = item.get("rank") + counts["sentences"] += 1 + counts["first"] += rank == 1 + counts["first_tied"] += rank == 1 and bool(item.get("tied")) + counts["top3"] += rank is not None and rank <= 3 + counts["suggested"] += rank is not None + return groups + + +# ------------------------------------------------------------------------- +# Runs +# ------------------------------------------------------------------------- + + +def run_check( + run: str, + project: object, + question: str, + article: str, +) -> tuple[dict[str, object], object]: + """Ask for a reference check and collect the results. + + Parameters + ---------- + run: str + ``check`` or ``planted``. + project: kilin.QAProject + Workspace of the run. + question: str + The request, naming the article. + article: str + The article's file name. + + Returns + ------- + tuple[dict[str, object], ReferenceReport] + The recorded answer with its claims, and the rule-based report. + + """ + + session = open_session(project.root) + try: + record = ask(session, question) + report = rule_based_report(session, article) + record["index_status"] = session.index_status + record["chunks"] = len(session.chunks) + finally: + session.close() + record["claims"] = claims_of(REPOSITORY_ROOT / record["trace_file"]) + if record["intent"] != "reference_check": + print(f"WARNING: {run} was routed to {record['intent']}.") + return record, report + + +def run_suggest( + project: object, sentences: list[dict[str, object]], template: str +) -> list[dict[str, object]]: + """Ask for a reference for each test sentence, each in a new session. + + Parameters + ---------- + project: kilin.QAProject + Workspace with the cited works only. + sentences: list[dict[str, object]] + Annotated sentences: ``group``, ``text`` and ``expected`` (file + names of the works that answer it). + template: str + Request with a ``{sentence}`` placeholder. + + Returns + ------- + list[dict[str, object]] + Per sentence, the recorded answer and the rank of the expected + works. + + """ + + results = [] + for index, item in enumerate(sentences, start=1): + print(f"Suggestion {index} of {len(sentences)}") + session = open_session(project.root) + try: + record = ask(session, template.format(sentence=item["text"])) + finally: + session.close() + record["workspace"] = str(project.root) + record.update(item) + record.update(suggestion_rank( + REPOSITORY_ROOT / record["trace_file"], item["expected"] + )) + if record["intent"] != "suggest_reference": + print(f"WARNING: sentence {index} was routed to " + f"{record['intent']}.") + results.append(record) + return results + + +def summarize(results: dict[str, object]) -> dict[str, object]: + """Collect the numbers of the article's table. + + Parameters + ---------- + results: dict[str, object] + Everything recorded by the runs. + + Returns + ------- + dict[str, object] + One value per row of the table, None where a run was skipped. + + """ + + check = results.get("check") or {} + scores = check.get("scores", {}) + matching = scores.get("matching", {}) + detection = scores.get("detection", {}) + planted = (results.get("planted") or {}).get("planted_scores", {}) + unmodified = check.get("unmodified_scores", {}) + suggest = results.get("suggest") or [] + specific = [item for item in suggest if item.get("group") != "background"] + ranks = [item["rank"] for item in specific] + return { + "references": len(scores.get("entries", [])) or None, + "references_matched": ( + matching.get("counts", {}).get("found", 0) + + matching.get("counts", {}).get("probable", 0) + ) if matching else None, + "citations_detected": detection.get("detected"), + "citations_manual": detection.get("manual"), + "detection_precision": detection.get("precision"), + "detection_recall": detection.get("recall"), + "planted_flagged": planted.get("flagged"), + "planted": planted.get("planted"), + "unmodified_flagged": unmodified.get("flagged"), + "unmodified_checked": unmodified.get("checked"), + "suggestion_first": sum(r == 1 for r in ranks) if specific else None, + "suggestion_top3": ( + sum(r is not None and r <= 3 for r in ranks) if specific else None + ), + "suggestion_sentences": len(specific) or None, + "suggestion_groups": suggestion_scores(suggest) if suggest else None, + "time_check_min": round(check["wall_s"] / 60, 1) if check else None, + "time_suggest_min": ( + round(sum(item["wall_s"] for item in suggest) / 60, 1) + if suggest else None + ), + } + + +def worksheet(results: dict[str, object]) -> str: + """Write a Markdown worksheet for reading the verdicts. + + Parameters + ---------- + results: dict[str, object] + Everything recorded by the runs. + + Returns + ------- + str + The worksheet: summary, flagged unmodified citations, planted + miscitations, and suggestions, each with the sentence and verdict. + The quotations and comments are in the reports in each workspace's + ``outputs`` folder. + + """ + + lines = ["# Reference example: worksheet", ""] + lines += [f"- {key}: {value}" for key, value in results["summary"].items()] + check = results.get("check") + if check: + lines += ["", "## Unmodified citations flagged", "", + "Read each: a false alarm, or a real problem of the " + "article?", ""] + for claim in check["unmodified_scores"]["flagged_claims"]: + lines += [ + f"- **[{claim['reference']}] {claim['cited']}**, line " + f"{claim['line']}: {claim['verdict']} " + f"({claim['evidence_status']})", + f" > {claim['citation_sentence']}", + ] + lines += ["", "## All verdicts on the original article", ""] + for claim in check["claims"]: + lines.append( + f"- [{claim['reference']}] line {claim['line']}: " + f"{claim['verdict']} ({claim['evidence_status']})" + ) + planted = results.get("planted") + if planted: + lines += ["", "## Planted miscitations", ""] + for row in planted["planted_scores"]["rows"]: + lines += [ + f"- [{row['original']}→{row['planted']}] " + f"{'flagged' if row['flagged'] else 'not flagged'}: " + f"{row['verdict']}", + f" > {row['text']}", + ] + if results.get("suggest"): + lines += ["", "## Suggestions", ""] + for item in results["suggest"]: + tie = " (tied)" if item.get("tied") else "" + lines.append( + f"- {item.get('group', '')}: expected " + f"{', '.join(item['expected'])}: rank {item['rank']}{tie}" + ) + lines.append(f" > {item['text']}") + for paper in item["papers"]: + lines.append( + f" - {paper['paper']}: {paper['verdict']} " + f"({paper['score']})" + ) + return "\n".join(lines) + "\n" + + +def main(argv: Sequence[str] | None = None) -> int: + """Run the reference example and save its results. + + Parameters + ---------- + argv: Sequence[str] | None, optional + Command-line arguments. Defaults to ``None``, which reads + ``sys.argv``. + + Returns + ------- + int + Exit status, 0 on success. + + """ + + parser = ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--ref", default="HEAD", + help="git revision of the corpus to export (default: HEAD)", + ) + parser.add_argument( + "--annotations", type=Path, default=ANNOTATIONS_FILE, + help="annotation file (default: reference_annotations.json)", + ) + parser.add_argument( + "--planted", type=Path, + help="copy of the article with planted miscitations " + "(default: the annotation file's 'planted_file')", + ) + parser.add_argument( + "--only", choices=RUNS, action="append", + help="run only this part; repeat for several", + ) + parser.add_argument( + "--router-model", default=None, + help="intent (router) model of the project, a Hugging Face ID such " + "as Qwen/Qwen3-8B-MLX-4bit (default: the packaged default)", + ) + parser.add_argument( + "--allow-download", action="store_true", + help="download models missing from the local cache", + ) + args = parser.parse_args(argv) + + if not args.allow_download: + os.environ["HF_HUB_OFFLINE"] = "1" + os.environ["TRANSFORMERS_OFFLINE"] = "1" + os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error") + + annotations = json.loads(args.annotations.read_text(encoding="utf-8")) + article = annotations["article"] + runs = args.only or list(RUNS) + planted_file = args.planted or ( + (args.annotations.parent / annotations["planted_file"]).resolve() + if annotations.get("planted_file") else None + ) + if planted_file is not None and not Path(planted_file).is_file(): + print(f"No planted copy at {planted_file}.") + planted_file = None + if "planted" in runs and planted_file is None: + print("No planted copy found; skipping the planted run.") + runs = [run for run in runs if run != "planted"] + + results: dict[str, object] = { + "date": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "environment": describe_environment(), + "code": code_version(), + "temperature": TEMPERATURE, + "runs": runs, + } + if results["code"]["uncommitted_kilin_changes"]: + print("WARNING: kilin/ has uncommitted changes; the results do not " + "correspond to a commit.") + + # A fixed staging folder: a workspace is synchronized from the same + # source path on every run, as in paper_numbers.prepare_code_project. + staging = Path(gettempdir()) / "kilin_reference_example" + if staging.exists(): + shutil.rmtree(staging) + corpus = staging / "corpus" + corpus.mkdir(parents=True) + results["corpus"] = export_corpus( + args.ref, annotations["corpus_folder"], corpus + ) + if not (corpus / article).is_file(): + raise SystemExit(f"{article} is not in the exported corpus.") + results["corpus"]["files"] = { + path.relative_to(corpus).as_posix(): sha256(path) + for path in sorted(corpus.rglob("*")) if path.is_file() + } + if planted_file is not None: + # The copy is part of the papers project whenever it exists, so the + # project holds the same files whichever runs are selected. + results["planted_file"] = { + "path": str(planted_file), "sha256": sha256(Path(planted_file)) + } + planted_name = Path(planted_file).name if planted_file else "" + if planted_name == article: + raise SystemExit( + "The planted copy needs a file name different from the " + f"article's ({article})." + ) + sources = stage_sources( + corpus, article, + Path(planted_file) if planted_file is not None else None, + planted_name, staging / "sources", + ) + projects = {} + if "check" in runs or "planted" in runs: + projects["papers"] = open_project( + sources["papers"], args.allow_download + ) + if "suggest" in runs: + projects["suggest"] = open_project( + sources["suggest"], args.allow_download + ) + + routers = { + name: set_router_model(project, args.router_model) + for name, project in projects.items() + } + results["router_model"] = next(iter(routers.values()), None) + + question = annotations["check_question"] + if "check" in runs: + record, report = run_check( + "check", projects["papers"], question.format(article=article), + article, + ) + record["scores"] = score_check( + report, record["tool_summary"], annotations + ) + record["unmodified_scores"] = score_unmodified(record["claims"]) + if not record["scores"]["agrees_with_tool"]: + print("WARNING: recomputed counts differ from the tool's: " + f"{record['scores']['agreement']}") + record["workspace"] = str(projects["papers"].root) + results["check"] = record + if "planted" in runs: + record, _ = run_check( + "planted", projects["papers"], + question.format(article=planted_name), planted_name, + ) + record["planted_scores"] = score_planted( + record["claims"], annotations.get("planted", []) + ) + record["workspace"] = str(projects["papers"].root) + results["planted"] = record + if "suggest" in runs: + results["suggest"] = run_suggest( + projects["suggest"], annotations.get("suggestions", []), + annotations["suggest_question"], + ) + + results["summary"] = summarize(results) + OUTPUT_DIRECTORY.mkdir(parents=True, exist_ok=True) + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + output = OUTPUT_DIRECTORY / f"reference_example_{stamp}.json" + output.write_text( + json.dumps(results, indent=2, ensure_ascii=False, default=str), + encoding="utf-8", + ) + sheet = OUTPUT_DIRECTORY / f"reference_example_{stamp}_worksheet.md" + sheet.write_text(worksheet(results), encoding="utf-8") + + print("\nSummary") + for key, value in results["summary"].items(): + print(f" {key}: {value}") + print(f"\nResults: {output.relative_to(REPOSITORY_ROOT)}") + print(f"Worksheet: {sheet.relative_to(REPOSITORY_ROOT)}") + print("Workspaces to open in the app: " + f"{WORKSPACE_DIRECTORY.relative_to(REPOSITORY_ROOT)}/") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/_si_article_/reference_analysis/tiunn26braph2_planted.txt b/_si_article_/reference_analysis/tiunn26braph2_planted.txt new file mode 100644 index 00000000..78cf7bc0 --- /dev/null +++ b/_si_article_/reference_analysis/tiunn26braph2_planted.txt @@ -0,0 +1,721 @@ +SoftwareX 35 (2026) 102791 + +Contents lists available at ScienceDirect + +SoftwareX + +journal homepage: www.elsevier.com/locate/softx + +Original Software Publication + +BRAPH 2: A flexible, open-source, reproducible, community-oriented, +easy-to-use framework for network analyses in neurosciences + +Io̍ k-uí Tiunn a,1 , Blanca Zufiria-Gerbol´es b,1, Emiliano G´omez-Ruiz a, Anna Canal-Garcia b, +Hang Zhao a, Mite Mijalkov b, Joana B. Pereira b,*, Giovanni Volpe a,c,* +a Department of Physics, University of Gothenburg, Gothenburg, Sweden +b Department of Clinical Neuroscience, Division of Neuro, Karolinska Institutet, Stockholm, Sweden +c Science for Life Laboratory, Department of Physics, University of Gothenburg, Gothenburg, Sweden + +A R T I C L E I N F O + +A B S T R A C T + +Keywords: +Network analyses +Neuroscience +Deep learning +Specialized distributions +Custom pipelines +Reproducibility + +1. Metadata + +As network analyses in neuroscience continue to grow in both complexity and size, flexible methods are urgently +needed to provide unbiased, reproducible insights into brain function. BRAPH 2 is a versatile, open-source +framework that meets this challenge by offering streamlined workflows for advanced statistical models and +deep learning, while supporting community-oriented extension, reuse, and sharing. Through its Genesis +compiler, users can build specialized distributions with custom pipelines, ensuring flexibility and scalability +across diverse research domains. These capabilities support reproducibility and accelerate discovery in +neuroscience. + +Nr +C1 +C2 + +C3 + +C4 + +C5 +C6 + +C7 + +C8 + +C9 + +Code metadata description +Current code version +Permanent link to code/repository +used for this code version +Permanent link to reproducible +capsule +Legal code license + +Code versioning system used +Software code languages, tools and +services used +Compilation requirements, +operating environments and +dependencies +If available, link to developer +documentation/manual +Support email for questions + +Metadata +v2.0.1 +https://github.com/braph-softwar +e/BRAPH-2 +https://codeocean.com/caps +ule/6589176/tree/v1 +Creative Commons Attribution 4.0 +International (CC-BY-4.0) +Git +MATLAB, C++ + +MATLAB; MinGW C/C++ compiler for +Windows as a MATLAB Add-On for +compiling MEX files +https://github.com/braph-software/B +RAPH-2/tree/develop/tutorials +Giov + +2. Motivation and significance + +In recent years, network analyses have rapidly gained traction in +neurosciences, linking multiple brain regions, clinical scores, and + +biomarkers to reveal system-wide interactions that often remain hidden +when single variables are studied in isolation [1–4]. This approach is +reshaping neurology, psychiatry, and cognitive sciences, driven by the +promise of new tools for disease diagnosis, improved treatment moni- +toring, and deeper insights into how the brain functions. + +The growing availability of large-scale, multimodal datasets has +made network analysis increasingly complex [5–7]. Initiatives such as +the UK Brain Biobank [8], the Human Connectome Project (HCP) [9], +and the ENIGMA Consortium [10] have generated large neuroimaging +datasets together with omics and clinical data [5–7]. Although many +software tools exist for handling these datasets, implementing new +robust, reproducible, and traceable features remains a significant chal- +lenge [11]. These features require rigorous unit testing, the ability to +trace outcomes back to original sources, continuous progress moni- +toring, and the development of user-friendly interfaces—tasks that often +demand far more time and resources than creating core functionalities. +Adopting standardized, containerized environments and automated +testing frameworks can enhance reproducibility and traceability [12], +but integrating these practices into research-oriented software is com- +plex and time-consuming. As a result, research groups often prioritize +the rapid development of new techniques at the expense of software +quality, reproducibility, and long-term maintenance. + +* Corresponding authors. + +E-mail addresses: joana.pereira@ki.se (J.B. Pereira), giovanni.volpe@gu.se (G. Volpe). + +1 These authors contributed equally to this work. + +https://doi.org/10.1016/j.softx.2026.102791 +Received 22 March 2026; Received in revised form 27 May 2026; Accepted 8 June 2026 +Available online 12 June 2026 +2352-7110/© 2026 The Authors. Published by Elsevier B.V. This is an open access article under the CC BY license ( http://creativecommons.org/licenses/by/4.0/ ). + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +Many free and open-source software platforms for brain connectivity +analysis exist, such as the Brain Connectivity Toolbox [13], eConnec- +tome [14], GAT [25], CONN [16], BrainNet Viewer [20], GRETNA [15], +and BRAPH 1 [19]. A reference table comparing BRAPH 2 with these +related software platforms is provided in the Supplementary Material. +While these tools provide essential functions such as data import, +network measures, and visualization, most focus on specific tasks. This +fragmentation can make it difficult to build full workflows without +manual intervention, increasing the risk of mistakes and bias. Moreover, +rapid advances in computational modeling and AI demand continuous +software updates, which can delay the integration of new methods. This +challenge also reflects broader machine learning operations (MLOps) +concerns in healthcare, where ML workflows increasingly require +reproducibility, maintainability, and long-term reliability [20,21]. As a +result, researchers face difficulties in adopting cutting-edge analyses in a +manner that ensures consistency, transparency, and easy verification +across studies, slowing scientific progress and potentially introducing +mistakes. + +BRAPH 2 addresses these challenges by combining a user-friendly +environment for network analysis with a software-generating frame- +work. Compared with BRAPH 1, it adds multiplex graph analysis, deep +learning pipelines, and Genesis-based generation of reusable pipelines +and specialized distributions. Unlike tools focused mainly on individual +analysis steps, BRAPH 2 centers on its Genesis module, which compiles +structured element descriptions into executable MATLAB classes, +graphical user interfaces (GUIs), and unit tests, thereby supporting in- +tegrated statistical testing and reproducible workflows. Users can create +custom elements to extend both pipelines and GUIs without extensive +coding. For example, BRAPH 2 has been used to implement a recursive +feature elimination pipeline for deep learning [3] and a standalone +distribution for reservoir computing to study brain network memory +capacity [22]. Written in MATLAB, BRAPH 2 is portable across oper- +ating systems and supports multiple data types beyond brain imaging. +During development, we also created specialized pipelines for yeast-cell +synchronization [24] and dendritic spine loss in postmortem brain tissue +[18], illustrating its flexibility across domains. + +3. Software description + +BRAPH 2 supports network analysis at three complementary levels: a +standard distribution with ready-to-use pipelines, custom pipelines built +by extending the framework, and standalone specialized distributions +that combine user-defined elements with selected standard components. +This structure supports no-code analyses for domain scientists, workflow +extension for advanced users, and development of new methods for +developers. By using a structured configuration system and modular +design, Genesis simplifies the addition of new graph types, analysis +pipelines, and user interface elements, making it easier to develop and +share specialized analytical tools. + +3.1. Software architecture + +To create a custom BRAPH 2 distribution, users define their desired +components — such as graph types, measures, analyses, and GUI ele- +ments — within a configuration file (braph2newdistribution_config.m) +(Fig. 1a). Alongside this, custom *.gen.m scripts describe the behavior +and properties of each element. The Genesis module then compiles these +inputs through a step-by-step workflow (Fig. 1b): + +• Directory Setup: Establishes the folder structure for the new + +distribution. + +• File Integration: Incorporates custom scripts and resources into the + +framework. + +• Element Compilation: Generates MATLAB classes and methods + +based on the *.gen.m templates. + +• GUI Generation: Builds interactive graphical interfaces for the new + +components. + +• Unit Test Creation: Produces tests to ensure functionality and + +maintain integrity. + +The result is a standalone BRAPH 2 distribution, packaging all +custom features into a cohesive and user-friendly environment (Fig. 1c). +For example, the “Hello, World!” distribution (https://github. +com/braph-software/HelloWorld) demonstrates the minimal setup + +Fig. 1. Genesis in action: compiling a custom BRAPH 2 distribution. a To create a specialized BRAPH 2 distribution with custom analysis pipelines, the user prepares +a compilation configuration file (braph2newdistribution_config.m) and a folder with the necessary custom elements (e.g., _NewAlgorithm.gen.m), pipeline files (e.g., +pipeline_NewAlgorithm.braph2), and optionally tutorial LaTeX files (e.g., tutorial_NewAlgorithm.tex). b The Genesis module of BRAPH 2 compiles these files +together with the core BRAPH 2 files through a series of steps, including creating directory structure, copying static files into the new directories, compiling elements, +creating layouts for the graphical user interface (GUI), and generating unit tests. c The resulting custom BRAPH 2 distribution includes a no-code GUI for end users. +This provides a framework for network analysis in neuroscience that is Flexible, Open-source, Reproducible, Community-oriented, and Easy-to-use (FORCE). + +2 + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +required to build a functional BRAPH 2 extension. On the other hand, +the “Memory Capacity” distribution (https://github.com/braph-softwar +e/MemoryCapacity) highlights how Genesis can support advanced ap- +plications, such as reservoir computing approaches for evaluating +cognitive decline [15]. + +3.2. Software functionalities + +The three usage levels introduced above are implemented in BRAPH +2 through the following complementary software functionalities, which +also correspond to different user profiles and levels of technical +expertise. + +3.2.1. Standard distribution for ready-to-use pipelines + +The standard BRAPH 2 distribution (https://github.com/braph-soft +ware/BRAPH-2) provides over 100 fully functional pipelines for +network neuroscience, including single-layer analyses, multilayer graph +analyses integrating imaging and non-imaging data, and deep learning +pipelines for supervised tasks such as classification, prediction, and +diagnosis. These deep learning pipelines are implemented in MATLAB +within BRAPH 2 and rely on the MATLAB Deep Learning Toolbox. Each +pipeline guides users through data import, graph construction, network +measure computation, statistical comparison, and visualization through +a user-friendly interface. In addition to GUI-based usage, BRAPH 2 can +also be used programmatically, facilitating scripted execution, batch +processing, and integration with high-performance computing envi- +ronments for large-scale datasets. + +3.2.2. Custom pipelines built on the standard distribution + +BRAPH 2 also allows users and developers to create custom pipelines +that are not included in the standard distribution while reusing the +functionalities already available in the framework. By relying on the +Genesis module and the modular design of BRAPH 2, users can adapt +pipeline scripts and introduce new graphs, measures, or analyses with +minimal programming effort. These custom elements integrate with the +existing GUI and workflows, which accelerates development while +maintaining robustness, reproducibility, and traceability. + +3.2.3. Standalone specialized distributions with new methods + +Beyond extending the standard distribution, BRAPH 2 supports the +generation of standalone specialized distributions for specific scientific +applications. In this case, users combine user-defined elements with +selected components from the standard distribution and specify them +through a configuration file. Genesis then assembles these resources into +a complete BRAPH 2 distribution, including executable MATLAB classes, +automatically generated GUI components, and unit tests. This allows +BRAPH 2 to function not only as a software package for network anal- +ysis, but also as a framework for creating specialized software solutions +with minimal coding effort. + +Taken together, these three levels show that BRAPH 2 serves both + +domain scientists and developers. For a quick start, users can: + +1. download the latest stable release; +2. unzip it into a directory; +3. launch MATLAB; +4. navigate to the braph2 folder; and +5. run the script braph2.m. + +This launches the GUI (Fig. 1c) for pipeline selection. The BRAPH 2 +pipeline tutorials (https://github.com/braph-software/BRAPH-2/tree/ +develop/tutorials/pipelines) and developer documentation (https: +//github.com/braph-software/BRAPH-2/tree/develop/tutorials/deve +lopers) provide +instructions for running ready-to-use pipelines, +including minimal datasets and scripts, and for creating, testing, and +distributing new features under the FORCE principles. Their practical +implementation is illustrated in Section 4. + +3 + +4. Illustrative examples + +The capabilities of BRAPH 2 are illustrated by three case studies in +network neuroscience, all realized within the same description- +centered, generative infrastructure. They are deliberately arranged to +show three scales of reuse: (i) a fully standard pipeline assembled purely +from existing elements, (ii) a new pipeline built by reusing the same +neural-network elements, and (iii) a new BRAPH 2 distribution con- +structed by adding elements implementing a state-of-the-art method on +top of the existing graph and subject infrastructure. + +4.1. Standard BRAPH 2 distribution: multiplex graph analysis + +In the first case study, ready-made pipelines from the standard +BRAPH 2 distribution (Fig. 2a) were used to investigate sex differences +in brain organization using combined diffusion magnetic resonance +imaging (dMRI) and resting-state functional magnetic resonance imag- +ing (fMRI) data from the Human Connectome Project (HCP, http://db. +humanconnectome.org). In this work, the term sex refers to the bio- +logical grouping variable provided in the dataset metadata. As shown in +Fig. 2b, the standard pipeline supports multiplex graph theory by +combining anatomical and functional connectomes into a multilayer +representation. Structural and functional connectivity matrices were +constructed from the Brainnetome atlas, and core–periphery structure +was estimated separately for each modality as well as for their multiplex +combination. Fig. 2c–e show the corresponding outputs generated +directly by BRAPH 2 from the ready-made pipeline: Fig. 2c reports the +single-layer anatomical analysis, Fig. 2d reports the single-layer func- +tional analysis, and Fig. 2e reports the multiplex analysis combining +both modalities. The regions highlighted in Fig. 2c–e correspond to sex +differences in nodal coreness, with “Women > Men” and “Men > +Women” indicating regions that show significantly higher coreness in +women and men, respectively. All analyses were performed through +standard pipelines and saved as .b2 files (available at https://github. +com/braph-software/BRAPH-2/issues/1745), +that +multiplex graph analysis and visualization can be combined reproduc- +ibly without bespoke coding. Together, these panels illustrate how a +ready-made BRAPH 2 pipeline supports core–periphery analysis and +visualization in a reproducible workflow without adding new elements. + +demonstrating + +4.2. Custom pipeline: deep learning analysis of recursive feature +elimination + +The second case study implements recursive feature elimination +(RFE) for schizophrenia classification. Most building blocks — including +subject elements, connectivity graphs, graph-derived features, the +multilayer perceptron (MLP) classifier, and brain-surface visualization +— are reused from the standard distribution. The results of this study +were published [22]. As shown in Fig. 3a, the project adds a single new +Genesis generator file (_NNxMLP_FeatureImportance.gen.m) together +with example scripts (example_RFE.m). This produces an RFE pipeline in +which the MLP classifier is trained, feature-importance scores are +computed, the least important regions are removed, and the model is +retrained until a stable subset of predictive regions is obtained (Fig. 3b). +The consistency of the identified regions across two independent cohorts +is shown in Fig. 3c, providing a robust basis for the subsequent genomic +analysis. Fig. 3d shows the corresponding brain-surface visualization. +This example shows how a new and custom analysis pipeline can be +created by reusing existing elements and adding a single Genesis +generator file. + +4.3. Standalone specialized distribution: memory capacity + +The third case study constructs the BRAPH 2 Memory Capacity dis- +tribution to quantify how reservoir-computing-based measures of +memory capacity change across the lifespan. The results of this study + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +Fig. 2. Standard BRAPH 2 distribution. a An analysis pipeline from the Standard BRAPH 2 distribution. b This pipeline implements multiplex graph theory, where +anatomical and functional data are combined to create multiplex networks, providing deeper insights into brain organization. c Results from single-layer analysis of +anatomical data. d Results from single-layer analysis of functional data. e Results from multiplex analysis combining anatomical and functional data, providing new +insights. In panels c–e, “Women > Men” and “Men > Women” denote regions with significantly higher nodal coreness in women and men, respectively. All results +and analysis steps can be reproduced using the provided .b2 files, available at https://github.com/braph-software/BRAPH-2/issues/1745, together with the standard +distribution available at https://github.com/braph-software/BRAPH-2. + +were recently published [23]. Unlike the previous examples, which +extended standard BRAPH 2 pipelines with custom scripts, this case +involved the creation of a standalone distribution. As shown in Fig. 4a, a +dedicated BRAPH 2 distribution was developed to study computational +memory capacity in brain networks. Here, almost all components — +subject and group handling, structural graphs, statistics, and visualiza- +tion — are inherited from the standard distribution, while a small set of +new elements (_GlobalMemoryCapacity.gen.m, _NodalMemoryCapacity. +gen.m) is added to implement the specialized reservoir-computing +functionality. Fig. 4b shows the relationship between memory capac- +ity and aging, Fig. 4c illustrates the reservoir-computing setup, and +Fig. 4d shows the visualization of the identified regions associated with +memory capacity decline. This approach allows researchers to build +customized tools that contain only the necessary functionalities for their +specific applications, thereby reducing complexity and enhancing us- +ability. Crucially, all distributions generated this way preserve BRAPH +2′s GUI functionality, reproducibility mechanisms, and compatibility +across platforms. The Memory Capacity distribution presented in this +case study is publicly available at https://github.com/braph-software/ +MemoryCapacity. + +An introductory video demonstrating how to build a specialized +BRAPH 2 distribution in practice, using the Memory Capacity example +in Section 3.3, is provided as supplementary material. The human +datasets used in the illustrative examples came from previously +approved studies with informed consent, as described in the source +datasets and original publications [9,22,23]. Only de-identified or +publicly available data were used here. + +5. Impact + +Network-based approaches have become central to neuroscience, yet + +many widely used tools remain limited to a single analysis type or data +modality. As the field moves toward multimodal and computationally +intensive models, including deep learning and multilayer analysis, such +limitations have become more evident. BRAPH 2 addresses them by +providing a modular, extensible, and reproducible platform for both +standard graph analysis and custom software development. Its flexibility +is illustrated through three case studies: a standard multiplex pipeline, a +custom deep learning pipeline for recursive feature elimination [17], +and a Genesis-generated standalone distribution for memory capacity +analysis [23]. + +A key strength of BRAPH 2 lies in its commitment to reproducibility +by design. All analyses can be encapsulated in a single .b2 file, as +exemplified by the .b2 files provided for the first case study (https://gith +ub.com/braph-software/BRAPH-2/issues/1745). Each file records +every step of the pipeline, including software versions and configuration +settings. These files can be shared and re-executed across systems, +ensuring exact replication while excluding sensitive personal data. This +infrastructure makes BRAPH 2 particularly useful for collaborative +studies, pre-registered workflows, and reproducible supplements to +published work. The portability of BRAPH 2 is further supported by unit +testing across different operating systems (Linux, Windows, and macOS) +and MATLAB versions (R2022a, R2022b, R2023a, R2023b, R2024a, and +R2024b), as documented in the README on its GitHub page. + +BRAPH 2′s open-source development model strengthens its reli- +ability and transparency. Hosted on GitHub, it supports issue tracking, +feature requests, code submissions, and documentation, while an active +discussion forum fosters knowledge exchange among users and de- +velopers. This model promotes sustainable development and broad +participation. + +One of the most powerful features of BRAPH 2 is the Genesis module, +which allows researchers to package tailored tools, pipelines, and + +4 + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +Fig. 3. Custom deep learning pipeline. a Custom pipeline for deep learning focusing on recursive feature elimination. b The regions were identified using a +multilayer perceptron and iterative feature elimination (used in [22]). c The deep learning pipeline identifies consistent important brain regions across two datasets. +d Results showing the identified regions on a brain surface. + +interfaces into standalone, shareable distributions. This capability is +particularly valuable in translational, clinical, and educational settings, +where simplicity, reproducibility, and scope-specific design are crucial. +The Memory Capacity distribution exemplifies this model: it introduces +two reservoir-computing-based metrics, applies them to lifespan imag- +ing data, and demonstrates their sensitivity to cognitive aging and brain +integrity. Built entirely with Genesis, the distribution is portable, +reproducible, and requires no additional configuration. + +BRAPH 2 is built on Genesis and is primarily designed for region-of- +interest (ROI)-based brain connectivity analyses, which remain standard +in many neuroimaging studies. Because BRAPH 2 is implemented in +MATLAB, large voxel-level networks may be limited by memory de- +mands, although sparse-matrix representations can help mitigate this at +the cost of some computational efficiency. A further limitation of the +present study is that Genesis, as the software-generating core of BRAPH +2, is not naturally suited to direct benchmarking against conventional +analysis tools. Rather, benchmarking is more meaningful for the soft- +ware produced by Genesis, such as the BRAPH 2 standard distribution, +and is therefore left for future work. + +Beyond technical strengths, BRAPH 2 is designed to be accessible and +inclusive. Its GUI supports users with limited coding experience, while +its modular architecture and documentation support full customization. +It accommodates multiple data types, including structural and func- +tional MRI, behavioral data, and electroencephalography (EEG), as well +as analytical approaches ranging from single-layer graphs to multiplex +models and neural networks. + +Future development of BRAPH 2 includes MATLAB–Python inter- +operability, broader multi-omics integration, improved batch processing +for scalable and automated analyses of larger datasets, and built-in +quality-control tools. The Genesis architecture further supports long- +term scalability by enabling specialized distributions to be generated +and maintained while preserving core functionality and reproducibility. +BRAPH 2 is also suited to real-time and streaming data integration, with + +5 + +potential applications in EEG, functional near-infrared spectroscopy, +neurofeedback, closed-loop systems, and brain–computer interfaces. + +6. Conclusions + +BRAPH 2 is an open-source framework that combines ready-to-use +network-neuroscience pipelines with a generative system for creating +custom pipelines and standalone software distributions. Its core inno- +vation, the Genesis module, enables new elements to be defined at a high +level and compiled into executable MATLAB classes, graphical in- +terfaces, and unit tests, thereby providing a reproducible and extensible +foundation for both network analysis and scientific software develop- +ment. Hosted through the BRAPH GitHub organization (https://github. +com/braph-software), this foundation supports the standard and +specialized BRAPH 2 distributions, together with the associated repro- +ducible capsule, while promoting the long-term accessibility and future +growth of the BRAPH software family. Through an active user forum +(https://github.com/braph-software/BRAPH-2/discussions), user tuto- +rials, and developer documentation, BRAPH 2 further lowers technical +barriers and supports shareable workflows in open and collaborative +science. + +Declaration of generative AI and AI-assisted technologies in the +manuscript preparation process + +During the preparation of this work the authors used ChatGPT +(OpenAI) in order to improve the clarity, grammar, and phrasing of the +manuscript text. After using this tool, the authors reviewed and edited +the content as needed and take full responsibility for the content of the +published article. + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +Fig. 4. Memory capacity distribution. a Distribution folder designated to the memory capacity (MC) distribution using reservoir computing. b Boxplots showing the +area under the curve (AUC) of global memory capacity in an aging cohort, highlighting differences between the young and the old groups. c This schematic illustrates +the setup of reservoir computing, where an input signal propagates through the nodes of a brain network and emerges as an output signal. If the network has +sufficient memory capacity, the output will closely resemble the original input. d Visualization showing the correlation between regional MC and age, where negative +correlations are shown in blue and positive in red. This demonstrates how a new algorithm can be provided to the community through a custom pipeline (used in +[23], https://github.com/braph-software/MemoryCapacity). + +CRediT authorship contribution statement + +Foundation (Grant No 2019.0079) (GV). + +Io̍ k-uí Tiunn: Writing – review & editing, Writing – original draft, +Visualization, Validation, Software, Investigation, Formal analysis, Data +curation. Blanca Zufiria-Gerbol´es: Writing – review & editing, Writing +– original draft, Visualization, Validation, Software, Investigation, +Formal analysis. Emiliano G´omez-Ruiz: Visualization, Software, +Investigation. Anna Canal-Garcia: Visualization, Validation, Software, +Investigation, Formal analysis, Data curation. Hang Zhao: Software, +Investigation. Mite Mijalkov: Validation, Software, Resources, Investi- +gation, Data curation. Joana B. Pereira: Writing – review & editing, +Writing – original draft, Supervision, Software, Resources, Project +administration, Methodology, Investigation, Conceptualization. Gio- +vanni Volpe: Writing – review & editing, Writing – original draft, +Visualization, Validation, Supervision, Software, Resources, Project +Investigation, Funding acquisition, +administration, Methodology, +Formal analysis, Data curation, Conceptualization. + +Declaration of competing interest + +The authors declare that they have no known competing financial +interests or personal relationships that could have appeared to influence +the work reported in this paper. + +Acknowledgements + +The authors would like to acknowledge funding from the H2020 +European Research Council (ERC) Starting Grant ComplexSwimmers +(Grant No 677511) (GV), the Horizon Europe ERC Consolidator Grant +MAPEI (Grant No 101001267) (GV), and the Knut and Alice Wallenberg + +Supplementary materials + +Supplementary material associated with this article can be found, in + +the online version, at doi:10.1016/j.softx.2026.102791. + +References + +[1] Seguin C, Sporns O, Zalesky A. Brain network communication: concepts, models + +and applications. Nat Rev Neurosci 2023;24(9):557–74. + +[2] Sebenius I, Dorfschmidt L, Seidlitz J, Alexander-Bloch A, Morgan SE, Bullmore E. + +Structural MRI of brain similarity networks. Nat Rev Neurosci 2025:1–18. + +[3] Tanner J, Faskowitz J, Teixeira AS, Seguin C, Coletta L, Gozzi A, Miˇsi´c B, Betzel RF. +A multi-modal, asymmetric, weighted, and signed description of anatomical +connectivity. Nat Commun 2024;15(1):5865. + +[4] Wang J, He Y. Toward individualized connectomes of brain morphology. Trends + +Neurosci 2024;47(2):106–19. + +[5] Nogare DD, Hartley M, Deschamps J, Ellenberg J, Jug F. Using AI in bioimage + +analysis to elevate the rate of scientific discovery as a community. Nat Methods +2023;20(7):973–5. + +[6] Marek S, Tervo-Clemmens B, Calabro FJ, Montez DF, Kay BP, Hatoum AS, + +Donohue MR, Foran W, Miller RL, Hendrickson TJ, Lynch BJ, Tam A, Chen J, +Newbold DJ, Zheng A, Seider NA, Van AN, Laumann TO, Greene DJ, +Dosenbach NUF. Reproducible brain-wide association studies require thousands of +individuals. Nature 2022;603(7902):654–60. + +[7] Li X, Zhang Y, Wu J, Dai Q. Challenges and opportunities in bioimage analysis. Nat + +Methods 2023;20(7):958–61. + +[8] Matthews PM, Sudlow C. The UK biobank. Brain 2015;138(12):3463–5. +[9] Van Essen DC, Ugurbil K, Auerbach E, Barch D, Behrens TEJ, Bucholz R, Chang A, +Chen L, Corbetta M, Curtiss SW, Della Penna S, Feinberg D, Glasser MF, Harel N, +Heath AC, Larson-Prior L, Marcus D, Michalareas G, Moeller S, Yacoub E. The +Human Connectome Project: a data acquisition perspective. Neuroimage 2012;62 +(4):2222–31. + +[10] Thompson PM, Stein JL, Medland SE, Hibar DP, Vasquez AA, Renteria ME, Toro R, + +Jahanshad N, Schumann G, Franke B, Wright MJ, Martin NG, Agartz I, Alda M, +Alhusaini S, Almasy L, Almeida J, Alpert K, Andreasen NC, Drevets W. The + +6 + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +ENIGMA Consortium: large-scale collaborative analyses of neuroimaging and +genetic data. Brain Imaging Behav 2014;8(2):153–82. + +[11] Botvinik-Nezer R, Wager TD. Reproducibility in neuroimaging analysis: challenges + +and solutions. Biol Psychiatry 2023;8(8):780–8. + +[12] Renton AI, Dao TT, Johnstone T, Civier O, Sullivan RP, White DJ, Lyons P, + +Slade BM, Abbott DF, Amos TJ, Bathelt J, Bellgrove MA, Bissett PG, Brown GG, +Calhoun VD, Cardenas VA, Chen J, Chen X, Choi YY, Gatt JM. Neurodesk: an +accessible, flexible and portable data analysis environment for reproducible +neuroimaging. Nat Methods 2024;21(5):804–8. + +[13] Rubinov M, Sporns O. Complex network measures of brain connectivity: uses and + +interpretations. Neuroimage 2010;52(3):1059–69. + +[14] He B, Dai Y, Astolfi L, Babiloni F, Yuan H, Yang L. eConnectome: a MATLAB +toolbox for mapping and imaging of brain functional connectivity. J Neurosci +Methods 2011;195(2):261–9. + +[15] Hosseini SMH, Hoeft F, Kesler SR. GAT: a graph-theoretical analysis toolbox for + +analyzing between-group differences in large-scale structural and functional brain +networks. PLoS One 2012;7(7):e40709. + +[16] Whitfield-Gabrieli S, Nieto-Castanon A. Conn: a functional connectivity toolbox for + +correlated and anticorrelated brain networks. Brain Connect 2012;2(3):125–41. +[17] Xia M, Wang J, He Y. BrainNet Viewer: a network visualization tool for human + +brain connectomics. PLoS One 2013;8(7):e68910. + +[18] Wang J, Wang X, Xia M, Liao X, Evans A, He Y. GRETNA: a graph theoretical + +network analysis toolbox for imaging connectomics. Front Hum Neurosci 2015;9: +386. + +[19] Mijalkov M, Kakaei E, Pereira JB, Westman E, Volpe G, Alzheimer’s Disease + +Neuroimaging Initiative. BRAPH: a graph theory software for the analysis of brain +connectivity. PLoS One 2017;12(8):e0178798. + +[20] Yan AP, Guo LL, Inoue J, Celi LA, Shickel B, Hong C, Michelson KA, Yoon- + +Flannery K, Brat G, Weiss JC. A roadmap to implementing machine learning in +healthcare: from concept to practice. Front Digit Health 2025;7:1462751. +[21] Steidl M, Felderer M, Ramler R. The pipeline for the continuous development of +artificial intelligence models—current state of research and practice. J Syst Softw +2023;199:111615. + +[22] Yao S, Harder A, Darki F, Chang Y-W, Li A, Nikouei K, Volpe G, Lundstr¨om JN, + +Zeng J, Wray NR, Lu Y, Sullivan PF, Hjerling-Leffler J. Connecting genomic results +for psychiatric disorders to human brain cell types and regions reveals convergence +with functional connectivity. Nat Commun 2025;16(1):395. + +[23] Mijalkov M, Storm L, Zufiria-Gerbol´es B, Ver´eb D, Xu Z, Canal-Garcia A, Sun J, +Chang Y-W, Zhao H, G´omez-Ruiz E, Passaretti M, Garcia-Ptacek S, Kivipelto M, +Svenningsson P, Zetterberg H, Jacobs H, Lüdge K, Brunner D, Mehlig B, Pereira JB. +Computational memory capacity predicts aging and cognitive decline. Nat +Commun 2025;16:2748. + +[24] Mojica-Benavides M, van Niekerk DD, Mijalkov M, Snoep JL, Mehlig B, Volpe G, + +Goks¨or M, Adiels CB. Intercellular communication induces glycolytic +synchronization waves between individually oscillating cells. In: Proceedings of +the National Academy of Sciences. 118; 2021, e2010075118. + +[25] Mijalkov M, Volpe G, Fernaud-Espinosa I, DeFelipe J, Pereira JB, Merino-Serrais P. + +Dendritic spines are lost in clusters in Alzheimer’s disease. Sci Rep 2021;11(1): +12350. + +7 + + \ No newline at end of file diff --git a/tests/test__benchmarks.py b/tests/test__benchmarks.py index 7c5e5c0b..cb381488 100644 --- a/tests/test__benchmarks.py +++ b/tests/test__benchmarks.py @@ -28,6 +28,7 @@ # pylint: disable=C0413:wrong-import-position from _si_article_.benchmarks.common import ( # noqa: E402 abstains, + bootstrap_interval, citation_coverage, citation_validity, extract_cited_indices, @@ -36,6 +37,7 @@ gold_evidence_indices, open_or_initialize, verbatim_overlap_chars, + wilson_interval, ) from kilin.project import ( # noqa: E402 configure_project, @@ -130,6 +132,34 @@ def test_abstention_is_only_a_heuristic(self) -> None: ) ) + def test_wilson_interval(self) -> None: + """Bound proportions inside [0, 1], also when all items succeed.""" + + low, high = wilson_interval(42, 42) + self.assertAlmostEqual(low, 0.916, places=3) + self.assertEqual(high, 1.0) + low, high = wilson_interval(5, 10) + self.assertAlmostEqual(low, 0.237, places=3) + self.assertAlmostEqual(high, 0.763, places=3) + self.assertEqual(wilson_interval(0, 7)[0], 0.0) + with self.assertRaises(ValueError): + wilson_interval(3, 2) + + def test_bootstrap_interval_is_reproducible(self) -> None: + """Bracket the mean and repeat exactly with the fixed seed.""" + + values = [0.0, 0.5, 1.0, 1.0, 0.25, 0.75, 1.0, 0.0] + low, high = bootstrap_interval(values, resamples=2_000) + mean = sum(values) / len(values) + self.assertLess(low, mean) + self.assertGreater(high, mean) + self.assertEqual( + (low, high), bootstrap_interval(values, resamples=2_000) + ) + self.assertEqual(bootstrap_interval([0.7] * 5), (0.7, 0.7)) + with self.assertRaises(ValueError): + bootstrap_interval([]) + def test_benchmark_query_uses_public_formatter(self) -> None: """Retain the Qwen3 instruction/query contract."""