Update documentation
Browse files- MODIFICATIONS.md +1 -1
- NOTICE +3 -3
- README.md +28 -5
- evaluation/README.md +1 -1
- evaluation/figures.py +8 -8
- evaluation/metrics.py +15 -2
- evaluation/svg_figures.py +576 -576
- figures/classifier-comparison.svg +64 -65
- publication-manifest.json +19 -19
MODIFICATIONS.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# Modifications from the upstream model
|
| 2 |
|
| 3 |
-
|
| 4 |
`knowledgator/gliclass-base-v3.0`. It is not endorsed by Knowledgator or by
|
| 5 |
Microsoft, whose `deberta-v3-base` backbone the upstream model builds on.
|
| 6 |
|
|
|
|
| 1 |
# Modifications from the upstream model
|
| 2 |
|
| 3 |
+
GLiClass Knowledge Classifier v2 is not an unmodified copy of
|
| 4 |
`knowledgator/gliclass-base-v3.0`. It is not endorsed by Knowledgator or by
|
| 5 |
Microsoft, whose `deberta-v3-base` backbone the upstream model builds on.
|
| 6 |
|
NOTICE
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
|
| 2 |
-
Copyright 2026
|
| 3 |
|
| 4 |
This model is a modified derivative of knowledgator/gliclass-base-v3.0
|
| 5 |
(https://huggingface.co/knowledgator/gliclass-base-v3.0, revision
|
|
@@ -9,6 +9,6 @@ Version 2.0. That model builds on microsoft/deberta-v3-base
|
|
| 9 |
License. Neither upstream author endorses this derivative.
|
| 10 |
|
| 11 |
Changes from the upstream model are described in MODIFICATIONS.md: a
|
| 12 |
-
supervised fine-tune on five
|
| 13 |
quantization of the token-embedding table. The upstream weights are not
|
| 14 |
distributed unmodified here.
|
|
|
|
| 1 |
+
GLiClass Knowledge Classifier v2
|
| 2 |
+
Copyright 2026 Tuan Hoang. Licensed under the Apache License, Version 2.0.
|
| 3 |
|
| 4 |
This model is a modified derivative of knowledgator/gliclass-base-v3.0
|
| 5 |
(https://huggingface.co/knowledgator/gliclass-base-v3.0, revision
|
|
|
|
| 9 |
License. Neither upstream author endorses this derivative.
|
| 10 |
|
| 11 |
Changes from the upstream model are described in MODIFICATIONS.md: a
|
| 12 |
+
supervised fine-tune on five knowledge facets, an ONNX export, and INT8
|
| 13 |
quantization of the token-embedding table. The upstream weights are not
|
| 14 |
distributed unmodified here.
|
README.md
CHANGED
|
@@ -21,7 +21,13 @@ tags:
|
|
| 21 |
|
| 22 |
A GLiClass Base v3 fine-tune that tags English passages by what they contain: a **trap, decision, constraint, mechanism or procedure**. It scores all five facets in one pass, allows several per passage, and runs locally through ONNX Runtime. Use it to organize notes and documentation, or to see what kind of material a search returned.
|
| 23 |
|
| 24 |
-
On 1,300 generated passages from three document families excluded from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
This revision's ONNX graph adds Vulkan compatibility. Learned weights, prompts, calibration and thresholds are unchanged.
|
| 27 |
|
|
@@ -31,6 +37,8 @@ This revision's ONNX graph adds Vulkan compatibility. Learned weights, prompts,
|
|
| 31 |
- **Size:** about 461.5 MB for the package, excluding runtime libraries; the ONNX graph is 452.8 MB
|
| 32 |
- **License:** Apache-2.0
|
| 33 |
|
|
|
|
|
|
|
| 34 |
## Quick start
|
| 35 |
|
| 36 |
Install the runtime dependencies and download the package:
|
|
@@ -58,7 +66,7 @@ prefix = "".join(
|
|
| 58 |
) + prep["separator_token"]
|
| 59 |
tokenizer = Tokenizer.from_file(f"{root}/tokenizer.json")
|
| 60 |
tokenizer.enable_truncation(max_length=prep["max_length"])
|
| 61 |
-
encoded = tokenizer.encode(prefix + "
|
| 62 |
session = ort.InferenceSession(
|
| 63 |
f"{root}/model.onnx", providers=["CPUExecutionProvider"]
|
| 64 |
)
|
|
@@ -90,9 +98,9 @@ Mentioning a decision is different from making one; training labels treat “men
|
|
| 90 |
|
| 91 |
## Before and after fine-tuning
|
| 92 |
|
| 93 |
-
“Upstream” is the exact `knowledgator/gliclass-base-v3.0` checkpoint used to start training, applied zero-shot with the same label definitions and **no
|
| 94 |
|
| 95 |
-
| Metric, macro average over five facets | Upstream GLiClass | Word-feature baseline |
|
| 96 |
|---|---:|---:|---:|
|
| 97 |
| Average precision | 0.7709 | 0.9384 | **0.9676** |
|
| 98 |
| Precision at 90% recall | 66.11% | 83.35% | **90.21%** |
|
|
@@ -110,12 +118,27 @@ Average precision summarizes how well scores rank positives across thresholds. P
|
|
| 110 |
|
| 111 |

|
| 112 |
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
## Data and training choices
|
| 116 |
|
| 117 |
The final fit used **59,886 passages from 9,376 documents**: 54,803 generated and 5,083 real. The real portion is 4,583 passages from self-owned workspaces and 500 from public-domain US Federal Register documents; all real rows were used for training, none for evaluation. Workspace documents may also be AI-written; real describes their source, not human authorship. Generated material was written as complete organizational documents and then parsed into passages, covering more settings and document types than the available workspaces.
|
| 118 |
|
|
|
|
|
|
|
| 119 |
Models applied fixed facet definitions to produce the labels. The main label campaigns used independent judgments with conflict resolution; 3,750 inherited rows used a single primary judge with a separate audit. Splits separate whole source families: the three evaluation families and four calibration families are disjoint from training and from each other. Calibration uses 1,700 passages to set per-facet temperatures and the two threshold tables.
|
| 120 |
|
| 121 |
| Training choice | Value and reason |
|
|
|
|
| 21 |
|
| 22 |
A GLiClass Base v3 fine-tune that tags English passages by what they contain: a **trap, decision, constraint, mechanism or procedure**. It scores all five facets in one pass, allows several per passage, and runs locally through ONNX Runtime. Use it to organize notes and documentation, or to see what kind of material a search returned.
|
| 23 |
|
| 24 |
+
On 1,300 generated passages from three document families excluded from
|
| 25 |
+
training, macro average precision is **0.9676** for the fine-tune, 0.9384 for
|
| 26 |
+
a trained word-feature baseline, and 0.7709 for the original model before
|
| 27 |
+
fine-tuning. This metric measures how well positive examples rank ahead
|
| 28 |
+
of negative ones, averaged equally over the five labels.
|
| 29 |
+
|
| 30 |
+
**Experimental.** This is an early fine-tune from ongoing training experiments, and a later version is likely to replace it. The results below describe generated evaluation data, not a general improvement over the upstream model.
|
| 31 |
|
| 32 |
This revision's ONNX graph adds Vulkan compatibility. Learned weights, prompts, calibration and thresholds are unchanged.
|
| 33 |
|
|
|
|
| 37 |
- **Size:** about 461.5 MB for the package, excluding runtime libraries; the ONNX graph is 452.8 MB
|
| 38 |
- **License:** Apache-2.0
|
| 39 |
|
| 40 |
+
**On this page:** [Use the model](#quick-start) · [Labels](#what-the-labels-mean) · [Results](#before-and-after-fine-tuning) · [Runtime and limits](#runtime-and-limits)
|
| 41 |
+
|
| 42 |
## Quick start
|
| 43 |
|
| 44 |
Install the runtime dependencies and download the package:
|
|
|
|
| 66 |
) + prep["separator_token"]
|
| 67 |
tokenizer = Tokenizer.from_file(f"{root}/tokenizer.json")
|
| 68 |
tokenizer.enable_truncation(max_length=prep["max_length"])
|
| 69 |
+
encoded = tokenizer.encode(prefix + "Weekly releases were chosen to reduce rollout risk.")
|
| 70 |
session = ort.InferenceSession(
|
| 71 |
f"{root}/model.onnx", providers=["CPUExecutionProvider"]
|
| 72 |
)
|
|
|
|
| 98 |
|
| 99 |
## Before and after fine-tuning
|
| 100 |
|
| 101 |
+
“Upstream” is the exact `knowledgator/gliclass-base-v3.0` checkpoint used to start training, applied zero-shot with the same label definitions and **no fine-tuning**. The word-feature baseline is TF-IDF plus logistic regression, trained on the same labeled rows as the fine-tune. All three use the same 1,300-passage panel; unresolved labels are excluded per facet for every model.
|
| 102 |
|
| 103 |
+
| Metric, macro average over five facets | Upstream GLiClass | Word-feature baseline | Fine-tuned |
|
| 104 |
|---|---:|---:|---:|
|
| 105 |
| Average precision | 0.7709 | 0.9384 | **0.9676** |
|
| 106 |
| Precision at 90% recall | 66.11% | 83.35% | **90.21%** |
|
|
|
|
| 118 |
|
| 119 |

|
| 120 |
|
| 121 |
+
Constraint is common in this panel, so its near-perfect AP says less than the decision and procedure results. The panel was deliberately enriched for difficult decision and procedure cases and is not a sample of natural traffic. The [evaluation companion](evaluation/README.md) contains the text-free labels and scores, model identities and calculation code.
|
| 122 |
+
|
| 123 |
+
### Where a word-feature baseline falls short
|
| 124 |
+
|
| 125 |
+
The word-feature baseline comes close on average, 0.9384 against 0.9676 macro AP, because much of this task can be learned from word cues. The average hides where it falls behind: decisions and procedures, where a passage often mentions the subject without making a decision or giving steps, using the same words either way.
|
| 126 |
+
|
| 127 |
+
| Facet | Model | Average precision | Precision at 90% recall | Precision at 95% recall |
|
| 128 |
+
|---|---|---:|---:|---:|
|
| 129 |
+
| Decision | Word-feature baseline | 0.8472 | 63.04% | 57.10% |
|
| 130 |
+
| Decision | Fine-tuned | **0.9135** | **74.14%** | **65.82%** |
|
| 131 |
+
| Procedure | Word-feature baseline | 0.9143 | 73.57% | 65.21% |
|
| 132 |
+
| Procedure | Fine-tuned | **0.9578** | **88.69%** | **82.24%** |
|
| 133 |
+
|
| 134 |
+
The gap is widest at high recall, where an application keeps nearly every real decision or procedure and has to reject the rest. Scored only on passages that make a decision against passages that only mention one (598 against 398), precision at 90% recall is 74.86% for the baseline and 84.35% for the fine-tune; for procedures (485 against 277) it is 84.20% and 95.02%. These two comparisons use the evaluation's mentions-only labels, which the published record does not include.
|
| 135 |
|
| 136 |
## Data and training choices
|
| 137 |
|
| 138 |
The final fit used **59,886 passages from 9,376 documents**: 54,803 generated and 5,083 real. The real portion is 4,583 passages from self-owned workspaces and 500 from public-domain US Federal Register documents; all real rows were used for training, none for evaluation. Workspace documents may also be AI-written; real describes their source, not human authorship. Generated material was written as complete organizational documents and then parsed into passages, covering more settings and document types than the available workspaces.
|
| 139 |
|
| 140 |
+
Two targeted batches added supervision for decisions and procedures, the two facets that scored lowest during development: 3,000 judged passages aimed at procedures and 2,000 at decisions. An earlier checkpoint scored unused candidates, and the draws took uncertain scores, passages that only mention the facet and boundaries with neighboring facets, plus controls; the judges never saw those scores. The batches entered training alongside other rotated rows, so no evaluation isolates their own effect.
|
| 141 |
+
|
| 142 |
Models applied fixed facet definitions to produce the labels. The main label campaigns used independent judgments with conflict resolution; 3,750 inherited rows used a single primary judge with a separate audit. Splits separate whole source families: the three evaluation families and four calibration families are disjoint from training and from each other. Calibration uses 1,700 passages to set per-facet temperatures and the two threshold tables.
|
| 143 |
|
| 144 |
| Training choice | Value and reason |
|
evaluation/README.md
CHANGED
|
@@ -32,7 +32,7 @@ Average precision is the area under the stepwise precision–recall curve, group
|
|
| 32 |
|
| 33 |
`serving-qualification.json` records checks on the released graph across CPU, CUDA and Vulkan. All 1,300 predictions matched the reference within 5.62e-6, and neither threshold table changed any labels. Learned weights, prompts, calibration and thresholds are unchanged by the Vulkan graph rewrite.
|
| 34 |
|
| 35 |
-
Checks used Windows x64 with an NVIDIA RTX 3060 Ti (8 GB). Other GPUs and Linux remain untested.
|
| 36 |
|
| 37 |
## Limits
|
| 38 |
|
|
|
|
| 32 |
|
| 33 |
`serving-qualification.json` records checks on the released graph across CPU, CUDA and Vulkan. All 1,300 predictions matched the reference within 5.62e-6, and neither threshold table changed any labels. Learned weights, prompts, calibration and thresholds are unchanged by the Vulkan graph rewrite.
|
| 34 |
|
| 35 |
+
Checks used Windows x64 with an NVIDIA RTX 3060 Ti (8 GB). Other GPUs and Linux remain untested.
|
| 36 |
|
| 37 |
## Limits
|
| 38 |
|
evaluation/figures.py
CHANGED
|
@@ -24,7 +24,7 @@ svg = importlib.util.module_from_spec(spec)
|
|
| 24 |
sys.modules[spec.name] = svg
|
| 25 |
spec.loader.exec_module(svg)
|
| 26 |
|
| 27 |
-
UPSTREAM, FIT, REFERENCE = '#
|
| 28 |
|
| 29 |
|
| 30 |
def classifier(summary: dict) -> str:
|
|
@@ -35,7 +35,7 @@ def classifier(summary: dict) -> str:
|
|
| 35 |
return svg.render_bars(
|
| 36 |
facets, [('Upstream', values('upstream'), UPSTREAM),
|
| 37 |
('TF-IDF + logistic regression', values('linear'), REFERENCE),
|
| 38 |
-
('
|
| 39 |
title='Classifier: matched before and after fine-tuning',
|
| 40 |
subtitle='1,300 generated passages · 3 held-out families · resolved labels only',
|
| 41 |
ylabel='average precision', ylim=(0, 1.05), separator_before=5,
|
|
@@ -54,9 +54,9 @@ def reranker(summary: dict) -> str:
|
|
| 54 |
for model, (label, color, dash) in zip(('upstream', 'finetuned', 'random'), legend, strict=True):
|
| 55 |
values = summary['models'][model]['answerable']
|
| 56 |
series.append(svg.Series(label, list(range(len(cutoffs))), [values[str(k)][field] for k in cutoffs], color, dash=dash))
|
| 57 |
-
panels.append(svg.Panel(title, series, xlabel='
|
| 58 |
ylabel={'hit': 'Hit@k', 'precision': 'Precision@k', 'ndcg': 'nDCG@k'}[field],
|
| 59 |
-
xlim=(0, len(cutoffs) - 1), ylim=(0, 1.02), xticks=
|
| 60 |
return svg.render_grid(panels, columns=3, title='Ettin: identical candidates, different ordering',
|
| 61 |
subtitle='873 answerable pools · 3–20 returned in Daecore · 50 is the full candidate pool',
|
| 62 |
legend=legend, panel_width=300, panel_height=270)
|
|
@@ -74,12 +74,12 @@ def retriever(summary: dict) -> str:
|
|
| 74 |
('ndcg', 'Graded ranking quality')]:
|
| 75 |
series = [svg.Series(label, x, [summary['models'][name][str(k)][field] for k in cutoffs], color)
|
| 76 |
for name, (label, color, _) in zip(('upstream', 'finetuned'), legend, strict=True)]
|
| 77 |
-
panels.append(svg.Panel(title, series, xlabel='
|
| 78 |
ylabel={'hit': 'Hit@k', 'precision': 'Precision@k', 'ndcg': 'nDCG@k'}[field],
|
| 79 |
-
xlim=(0, len(cutoffs) - 1), ylim=(0, 1.02), xticks=
|
| 80 |
return svg.render_grid(panels, columns=3,
|
| 81 |
-
title='Gemma v2: matched dense retrieval on
|
| 82 |
-
subtitle=f"{summary['queries']:,} known-answerable queries · {corpus_passages:,} passages ·
|
| 83 |
legend=legend, panel_width=300, panel_height=270)
|
| 84 |
|
| 85 |
|
|
|
|
| 24 |
sys.modules[spec.name] = svg
|
| 25 |
spec.loader.exec_module(svg)
|
| 26 |
|
| 27 |
+
UPSTREAM, FIT, REFERENCE = '#3b8eea', '#f0883e', '#8b949e'
|
| 28 |
|
| 29 |
|
| 30 |
def classifier(summary: dict) -> str:
|
|
|
|
| 35 |
return svg.render_bars(
|
| 36 |
facets, [('Upstream', values('upstream'), UPSTREAM),
|
| 37 |
('TF-IDF + logistic regression', values('linear'), REFERENCE),
|
| 38 |
+
('Fine-tuned', values('finetuned'), FIT)],
|
| 39 |
title='Classifier: matched before and after fine-tuning',
|
| 40 |
subtitle='1,300 generated passages · 3 held-out families · resolved labels only',
|
| 41 |
ylabel='average precision', ylim=(0, 1.05), separator_before=5,
|
|
|
|
| 54 |
for model, (label, color, dash) in zip(('upstream', 'finetuned', 'random'), legend, strict=True):
|
| 55 |
values = summary['models'][model]['answerable']
|
| 56 |
series.append(svg.Series(label, list(range(len(cutoffs))), [values[str(k)][field] for k in cutoffs], color, dash=dash))
|
| 57 |
+
panels.append(svg.Panel(title, series, xlabel='results kept',
|
| 58 |
ylabel={'hit': 'Hit@k', 'precision': 'Precision@k', 'ndcg': 'nDCG@k'}[field],
|
| 59 |
+
xlim=(0, len(cutoffs) - 1), ylim=(0, 1.02), xticks=[(i, f'top {k}') for i, k in enumerate(cutoffs)]))
|
| 60 |
return svg.render_grid(panels, columns=3, title='Ettin: identical candidates, different ordering',
|
| 61 |
subtitle='873 answerable pools · 3–20 returned in Daecore · 50 is the full candidate pool',
|
| 62 |
legend=legend, panel_width=300, panel_height=270)
|
|
|
|
| 74 |
('ndcg', 'Graded ranking quality')]:
|
| 75 |
series = [svg.Series(label, x, [summary['models'][name][str(k)][field] for k in cutoffs], color)
|
| 76 |
for name, (label, color, _) in zip(('upstream', 'finetuned'), legend, strict=True)]
|
| 77 |
+
panels.append(svg.Panel(title, series, xlabel='results kept',
|
| 78 |
ylabel={'hit': 'Hit@k', 'precision': 'Precision@k', 'ndcg': 'nDCG@k'}[field],
|
| 79 |
+
xlim=(0, len(cutoffs) - 1), ylim=(0, 1.02), xticks=[(i, f'top {k}') for i, k in enumerate(cutoffs)]))
|
| 80 |
return svg.render_grid(panels, columns=3,
|
| 81 |
+
title='Gemma v2: matched dense retrieval on experimental data',
|
| 82 |
+
subtitle=f"{summary['queries']:,} known-answerable queries · {corpus_passages:,} passages · ungradable positions excluded",
|
| 83 |
legend=legend, panel_width=300, panel_height=270)
|
| 84 |
|
| 85 |
|
evaluation/metrics.py
CHANGED
|
@@ -267,10 +267,22 @@ def summarize_serving(data: dict) -> dict:
|
|
| 267 |
'answerable': _summarize_ranked_grades(data, include_selected=True, answerable_only=True)}
|
| 268 |
|
| 269 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
SUMMARIZERS = {
|
| 271 |
'classifier': summarize_classifier, 'reranker': summarize_reranker,
|
| 272 |
'retriever': summarize_retriever, 'dimensions': summarize_dimensions,
|
| 273 |
-
'promotion': summarize_promotion, 'serving': summarize_serving,
|
| 274 |
}
|
| 275 |
|
| 276 |
|
|
@@ -283,6 +295,7 @@ def summarize_record(name: str, data: dict) -> dict:
|
|
| 283 |
'dimensions': {'id', 'dataset', 'ndcg@10'},
|
| 284 |
'promotion': {'id', 'group', 'reference_grade_counts', 'ranked_grades', 'excluded', 'selected_depth'},
|
| 285 |
'serving': {'id', 'group', 'reference_grade_counts', 'ranked_grades', 'excluded', 'selected_depth'},
|
|
|
|
| 286 |
}[name]
|
| 287 |
rows = data['rows']
|
| 288 |
if not rows or any(set(row) != fields for row in rows):
|
|
@@ -336,7 +349,7 @@ def main() -> None:
|
|
| 336 |
parser = argparse.ArgumentParser(description=__doc__)
|
| 337 |
parser.add_argument("--directory", type=Path, default=Path(__file__).resolve().parent)
|
| 338 |
parser.add_argument("--output", type=Path)
|
| 339 |
-
parser.add_argument("--model", choices=(
|
| 340 |
args = parser.parse_args()
|
| 341 |
names = [args.model] if args.model else [
|
| 342 |
name for name in SUMMARIZERS if (args.directory / f"{name}.json").is_file()
|
|
|
|
| 267 |
'answerable': _summarize_ranked_grades(data, include_selected=True, answerable_only=True)}
|
| 268 |
|
| 269 |
|
| 270 |
+
def summarize_pipeline(data: dict) -> dict:
|
| 271 |
+
"""Matched component changes on a frozen, known-answerable query cohort."""
|
| 272 |
+
if type(data['corpus_passages']) is not int or data['corpus_passages'] <= 0:
|
| 273 |
+
raise ValueError('Pipeline comparison requires a positive corpus size')
|
| 274 |
+
output = _summarize_ranked_grades(data, include_selected=False)
|
| 275 |
+
if any(row['reference_grade_counts']['2'] + row['reference_grade_counts']['3'] == 0
|
| 276 |
+
for row in data['rows']):
|
| 277 |
+
raise ValueError('Pipeline cohort requires known useful evidence for every query')
|
| 278 |
+
return {**output, 'corpus_passages': data['corpus_passages'],
|
| 279 |
+
'reference_pairs': sum(sum(row['reference_grade_counts'].values()) for row in data['rows'])}
|
| 280 |
+
|
| 281 |
+
|
| 282 |
SUMMARIZERS = {
|
| 283 |
'classifier': summarize_classifier, 'reranker': summarize_reranker,
|
| 284 |
'retriever': summarize_retriever, 'dimensions': summarize_dimensions,
|
| 285 |
+
'promotion': summarize_promotion, 'serving': summarize_serving, 'pipeline': summarize_pipeline,
|
| 286 |
}
|
| 287 |
|
| 288 |
|
|
|
|
| 295 |
'dimensions': {'id', 'dataset', 'ndcg@10'},
|
| 296 |
'promotion': {'id', 'group', 'reference_grade_counts', 'ranked_grades', 'excluded', 'selected_depth'},
|
| 297 |
'serving': {'id', 'group', 'reference_grade_counts', 'ranked_grades', 'excluded', 'selected_depth'},
|
| 298 |
+
'pipeline': {'id', 'group', 'reference_grade_counts', 'ranked_grades', 'excluded'},
|
| 299 |
}[name]
|
| 300 |
rows = data['rows']
|
| 301 |
if not rows or any(set(row) != fields for row in rows):
|
|
|
|
| 349 |
parser = argparse.ArgumentParser(description=__doc__)
|
| 350 |
parser.add_argument("--directory", type=Path, default=Path(__file__).resolve().parent)
|
| 351 |
parser.add_argument("--output", type=Path)
|
| 352 |
+
parser.add_argument("--model", choices=tuple(SUMMARIZERS), help="Recompute one comparison; default: every record in this package")
|
| 353 |
args = parser.parse_args()
|
| 354 |
names = [args.model] if args.model else [
|
| 355 |
name for name in SUMMARIZERS if (args.directory / f"{name}.json").is_file()
|
evaluation/svg_figures.py
CHANGED
|
@@ -1,576 +1,576 @@
|
|
| 1 |
-
"""Dependency-free SVG charts for tracked evaluation figures.
|
| 2 |
-
|
| 3 |
-
The evaluation figures are generated from private per-row evidence into tracked SVG files.
|
| 4 |
-
Keeping the renderer inside the repository, with no plotting dependency, means a figure can be
|
| 5 |
-
regenerated by any contributor with the private inputs and compared byte for byte.
|
| 6 |
-
|
| 7 |
-
Everything is emitted as presentation attributes rather than CSS. Markdown hosts sanitize
|
| 8 |
-
embedded stylesheets and scripts out of SVG, so a figure that carries its styling in attributes
|
| 9 |
-
renders the same in the repository, on a model-card host, and in a local viewer.
|
| 10 |
-
|
| 11 |
-
Layout is measured rather than assumed: legend entries, panel titles, and reference-line labels
|
| 12 |
-
are placed from an estimated text width, so a longer label reflows instead of overlapping its
|
| 13 |
-
neighbour. ``text_width`` approximates a sans-serif advance table, which is enough to keep
|
| 14 |
-
elements apart but is not a substitute for a real font metric.
|
| 15 |
-
"""
|
| 16 |
-
|
| 17 |
-
from __future__ import annotations
|
| 18 |
-
|
| 19 |
-
import math
|
| 20 |
-
from dataclasses import dataclass, field
|
| 21 |
-
from xml.sax.saxutils import escape
|
| 22 |
-
|
| 23 |
-
# Okabe-Ito, chosen because it stays distinguishable under the common colour-vision
|
| 24 |
-
# deficiencies and prints legibly in greyscale
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
parts.append(
|
| 253 |
-
f'<line x1="{
|
| 254 |
-
f'
|
| 255 |
-
|
| 256 |
-
)
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
f"{tx(
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
f
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
parts.append(
|
| 283 |
-
f'<
|
| 284 |
-
f'
|
| 285 |
-
)
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
f'
|
| 296 |
-
f'stroke-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
f'
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
f'
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
f'
|
| 336 |
-
f'fill
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
f'
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
parts.append(
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
f'text
|
| 362 |
-
f"
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
f'
|
| 387 |
-
f'
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
cursor_x +
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
f'
|
| 408 |
-
f"
|
| 409 |
-
f"<
|
| 410 |
-
|
| 411 |
-
]
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
def render_grid(
|
| 415 |
-
panels: list[Panel],
|
| 416 |
-
*,
|
| 417 |
-
columns: int,
|
| 418 |
-
title: str,
|
| 419 |
-
subtitle: str = "",
|
| 420 |
-
panel_width: float = 352.0,
|
| 421 |
-
panel_height: float = 256.0,
|
| 422 |
-
legend: list[tuple[str, str, str | None]] | None = None,
|
| 423 |
-
description: str = "",
|
| 424 |
-
) -> str:
|
| 425 |
-
"""Render panels on a grid with one shared title and a flowed legend.
|
| 426 |
-
|
| 427 |
-
A final short row is centred, so a five-panel figure on three columns has no empty cell.
|
| 428 |
-
"""
|
| 429 |
-
|
| 430 |
-
if not panels:
|
| 431 |
-
raise ValueError("render_grid needs at least one panel")
|
| 432 |
-
if columns < 1:
|
| 433 |
-
raise ValueError("render_grid needs at least one column")
|
| 434 |
-
legend = _dedupe(legend or [])
|
| 435 |
-
rows = math.ceil(len(panels) / columns)
|
| 436 |
-
width = columns * panel_width
|
| 437 |
-
header = 26.0 + (16.0 if subtitle else 0.0)
|
| 438 |
-
legend_svg, legend_h = "", 0.0
|
| 439 |
-
if legend:
|
| 440 |
-
legend_svg, legend_h = _legend_svg(legend, x=18.0, y=header + 10.0, max_width=width - 36.0)
|
| 441 |
-
legend_h += 8.0
|
| 442 |
-
height = header + legend_h + rows * panel_height
|
| 443 |
-
parts = _open_svg(width, height, title, description or title)
|
| 444 |
-
parts.append(_text(width / 2, 19, title, size=14.5, anchor="middle", weight="700"))
|
| 445 |
-
if subtitle:
|
| 446 |
-
parts.append(_text(width / 2, 34, subtitle, size=11, fill=MUTED, anchor="middle"))
|
| 447 |
-
if legend_svg:
|
| 448 |
-
parts.append(legend_svg)
|
| 449 |
-
# One title row count for the whole grid, so a panel whose title wraps does not push its
|
| 450 |
-
# plot box below its neighbours'.
|
| 451 |
-
title_rows = max(
|
| 452 |
-
len(_fit_lines(panel.title, _TITLE_SIZE, panel_width - 68.0, weight="600"))
|
| 453 |
-
for panel in panels
|
| 454 |
-
)
|
| 455 |
-
for index, panel in enumerate(panels):
|
| 456 |
-
row, column = divmod(index, columns)
|
| 457 |
-
in_row = min(columns, len(panels) - row * columns)
|
| 458 |
-
offset = (columns - in_row) * panel_width / 2.0
|
| 459 |
-
px = offset + column * panel_width
|
| 460 |
-
py = header + legend_h + row * panel_height
|
| 461 |
-
parts.append(f'<g transform="translate({px:.1f},{py:.1f})">')
|
| 462 |
-
parts.append(_panel_svg(panel, panel_width, panel_height, title_rows=title_rows))
|
| 463 |
-
parts.append("</g>")
|
| 464 |
-
parts.append("</svg>")
|
| 465 |
-
return "\n".join(parts) + "\n"
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
def render_bars(
|
| 469 |
-
groups: list[str],
|
| 470 |
-
series: list[tuple[str, list[float], str]],
|
| 471 |
-
*,
|
| 472 |
-
title: str,
|
| 473 |
-
ylabel: str,
|
| 474 |
-
subtitle: str = "",
|
| 475 |
-
ylim: tuple[float, float] = (0.0, 1.0),
|
| 476 |
-
reference: list[tuple[str, list[float], str]] | None = None,
|
| 477 |
-
notes: list[str] | None = None,
|
| 478 |
-
separator_before: int | None = None,
|
| 479 |
-
width: float = 780.0,
|
| 480 |
-
height: float = 350.0,
|
| 481 |
-
description: str = "",
|
| 482 |
-
) -> str:
|
| 483 |
-
"""Render grouped bars with per-group dashed reference levels.
|
| 484 |
-
|
| 485 |
-
Bars keep a zero baseline. Value labels are drawn only where a bar is wide enough to hold
|
| 486 |
-
one, because a crowded label is worse than none.
|
| 487 |
-
"""
|
| 488 |
-
|
| 489 |
-
if not groups or not series:
|
| 490 |
-
raise ValueError("render_bars needs at least one group and one series")
|
| 491 |
-
if any(len(values) != len(groups) for _, values, _ in series):
|
| 492 |
-
raise ValueError("every bar series must carry one value per group")
|
| 493 |
-
notes = notes or []
|
| 494 |
-
left, right, top = 54.0, 16.0, 26.0 + (15.0 if subtitle else 0.0)
|
| 495 |
-
legend_entries = [(label, color, None) for label, _, color in series]
|
| 496 |
-
legend_entries += [(label, color, "5 3") for label, _, color in reference or []]
|
| 497 |
-
legend_svg, legend_h = _legend_svg(
|
| 498 |
-
_dedupe(legend_entries), x=18.0, y=top + 12.0, max_width=width - 36.0
|
| 499 |
-
)
|
| 500 |
-
top += legend_h + 10.0
|
| 501 |
-
bottom = 46.0 + 12.0 * len(notes)
|
| 502 |
-
plot_w, plot_h = width - left - right, height - top - bottom
|
| 503 |
-
group_w = plot_w / len(groups)
|
| 504 |
-
bar_w = group_w * 0.74 / len(series)
|
| 505 |
-
|
| 506 |
-
def ty(value: float) -> float:
|
| 507 |
-
return top + plot_h - (value - ylim[0]) / (ylim[1] - ylim[0]) * plot_h
|
| 508 |
-
|
| 509 |
-
parts = _open_svg(width, height, title, description or title)
|
| 510 |
-
parts.append(_text(width / 2, 19, title, size=14.5, anchor="middle", weight="700"))
|
| 511 |
-
if subtitle:
|
| 512 |
-
parts.append(_text(width / 2, 34, subtitle, size=11, fill=MUTED, anchor="middle"))
|
| 513 |
-
parts.append(legend_svg)
|
| 514 |
-
for value, label in _auto_ticks(*ylim):
|
| 515 |
-
y = ty(value)
|
| 516 |
-
parts.append(
|
| 517 |
-
f'<line x1="{left}" y1="{y:.1f}" x2="{left + plot_w:.1f}" y2="{y:.1f}" '
|
| 518 |
-
f'stroke="{GRID}" stroke-width="1"/>'
|
| 519 |
-
)
|
| 520 |
-
parts.append(_text(left - 6, y + 3.4, label, size=10, fill=MUTED, anchor="end"))
|
| 521 |
-
|
| 522 |
-
label_fits = bar_w - 2 >= text_width("0.000", 8.5) + 2
|
| 523 |
-
for g_index, group in enumerate(groups):
|
| 524 |
-
gx = left + g_index * group_w + group_w * 0.13
|
| 525 |
-
for s_index, (_, values, color) in enumerate(series):
|
| 526 |
-
value = values[g_index]
|
| 527 |
-
x = gx + s_index * bar_w
|
| 528 |
-
parts.append(
|
| 529 |
-
f'<rect x="{x:.1f}" y="{ty(value):.1f}" width="{bar_w - 2:.1f}" '
|
| 530 |
-
f'height="{ty(ylim[0]) - ty(value):.1f}" fill="{color}"/>'
|
| 531 |
-
)
|
| 532 |
-
if label_fits:
|
| 533 |
-
parts.append(
|
| 534 |
-
_text(
|
| 535 |
-
x + (bar_w - 2) / 2,
|
| 536 |
-
ty(value) - 4,
|
| 537 |
-
f"{value:.3f}",
|
| 538 |
-
size=8.5,
|
| 539 |
-
anchor="middle",
|
| 540 |
-
)
|
| 541 |
-
)
|
| 542 |
-
for _, values, color in reference or []:
|
| 543 |
-
y = ty(values[g_index])
|
| 544 |
-
parts.append(
|
| 545 |
-
f'<line x1="{gx - 3:.1f}" y1="{y:.1f}" '
|
| 546 |
-
f'x2="{gx + group_w * 0.74 + 3:.1f}" y2="{y:.1f}" stroke="{color}" '
|
| 547 |
-
f'stroke-width="1.6" stroke-dasharray="5 3"/>'
|
| 548 |
-
)
|
| 549 |
-
parts.append(
|
| 550 |
-
_text(
|
| 551 |
-
left + g_index * group_w + group_w / 2,
|
| 552 |
-
top + plot_h + 16,
|
| 553 |
-
group,
|
| 554 |
-
size=11,
|
| 555 |
-
anchor="middle",
|
| 556 |
-
)
|
| 557 |
-
)
|
| 558 |
-
if separator_before is not None and 0 < separator_before < len(groups):
|
| 559 |
-
x = left + separator_before * group_w
|
| 560 |
-
parts.append(
|
| 561 |
-
f'<line x1="{x:.1f}" y1="{top}" x2="{x:.1f}" y2="{top + plot_h + 6:.1f}" '
|
| 562 |
-
f'stroke="{GRID_STRONG}" stroke-width="1.4"/>'
|
| 563 |
-
)
|
| 564 |
-
parts.append(
|
| 565 |
-
f'<rect x="{left}" y="{top}" width="{plot_w:.1f}" height="{plot_h:.1f}" fill="none" '
|
| 566 |
-
f'stroke="{AXIS}" stroke-width="1"/>'
|
| 567 |
-
)
|
| 568 |
-
parts.append(
|
| 569 |
-
f'<text transform="translate(13,{top + plot_h / 2:.1f}) rotate(-90)" '
|
| 570 |
-
f'text-anchor="middle" font-size="10.5" fill="{MUTED}" {FONT}>'
|
| 571 |
-
f"{escape(ylabel)}</text>"
|
| 572 |
-
)
|
| 573 |
-
for index, note in enumerate(notes):
|
| 574 |
-
parts.append(_text(left, top + plot_h + 34 + 12 * index, note, size=9.5, fill=MUTED))
|
| 575 |
-
parts.append("</svg>")
|
| 576 |
-
return "\n".join(parts) + "\n"
|
|
|
|
| 1 |
+
"""Dependency-free SVG charts for tracked evaluation figures.
|
| 2 |
+
|
| 3 |
+
The evaluation figures are generated from private per-row evidence into tracked SVG files.
|
| 4 |
+
Keeping the renderer inside the repository, with no plotting dependency, means a figure can be
|
| 5 |
+
regenerated by any contributor with the private inputs and compared byte for byte.
|
| 6 |
+
|
| 7 |
+
Everything is emitted as presentation attributes rather than CSS. Markdown hosts sanitize
|
| 8 |
+
embedded stylesheets and scripts out of SVG, so a figure that carries its styling in attributes
|
| 9 |
+
renders the same in the repository, on a model-card host, and in a local viewer.
|
| 10 |
+
|
| 11 |
+
Layout is measured rather than assumed: legend entries, panel titles, and reference-line labels
|
| 12 |
+
are placed from an estimated text width, so a longer label reflows instead of overlapping its
|
| 13 |
+
neighbour. ``text_width`` approximates a sans-serif advance table, which is enough to keep
|
| 14 |
+
elements apart but is not a substitute for a real font metric.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from dataclasses import dataclass, field
|
| 21 |
+
from xml.sax.saxutils import escape
|
| 22 |
+
|
| 23 |
+
# Okabe-Ito, chosen because it stays distinguishable under the common colour-vision
|
| 24 |
+
# deficiencies and prints legibly in greyscale; its black is a neutral grey here, because
|
| 25 |
+
# black disappears on a dark page.
|
| 26 |
+
PALETTE = ("#0072B2", "#D55E00", "#009E73", "#CC79A7", "#E69F00", "#56B4E9", "#8b949e")
|
| 27 |
+
FONT_STACK = "system-ui, Segoe UI, Roboto, Helvetica, Arial, sans-serif"
|
| 28 |
+
FONT = f'font-family="{FONT_STACK}"'
|
| 29 |
+
|
| 30 |
+
# Figures have no background, so one set of mid-tone colours has to read on a light page and
|
| 31 |
+
# on a dark one: a page's theme toggle never reaches an image, so the colours cannot follow it.
|
| 32 |
+
INK = "#6e7681"
|
| 33 |
+
MUTED = "#7d8590"
|
| 34 |
+
AXIS = "#8b949e"
|
| 35 |
+
GRID = "#8b949e33"
|
| 36 |
+
GRID_STRONG = "#8b949e66"
|
| 37 |
+
|
| 38 |
+
# Per-character advance as a fraction of font size, for a humanist sans at normal weight.
|
| 39 |
+
_NARROW = set("iljft.,;:|!()[]{}I '")
|
| 40 |
+
_WIDE = set("mwMW@%")
|
| 41 |
+
_DIGIT = set("0123456789")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def text_width(text: str, size: float, *, weight: str = "normal") -> float:
|
| 45 |
+
"""Estimate rendered width in user units."""
|
| 46 |
+
|
| 47 |
+
total = 0.0
|
| 48 |
+
for character in text:
|
| 49 |
+
if character in _NARROW:
|
| 50 |
+
total += 0.30
|
| 51 |
+
elif character in _WIDE:
|
| 52 |
+
total += 0.86
|
| 53 |
+
elif character in _DIGIT:
|
| 54 |
+
total += 0.56
|
| 55 |
+
elif character.isupper():
|
| 56 |
+
total += 0.66
|
| 57 |
+
else:
|
| 58 |
+
total += 0.52
|
| 59 |
+
if weight in {"600", "700", "bold"}:
|
| 60 |
+
total *= 1.05
|
| 61 |
+
return total * size
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _fit_lines(text: str, size: float, limit: float, *, weight: str = "normal") -> list[str]:
|
| 65 |
+
"""Wrap to at most two lines, breaking on whitespace."""
|
| 66 |
+
|
| 67 |
+
if text_width(text, size, weight=weight) <= limit:
|
| 68 |
+
return [text]
|
| 69 |
+
words = text.split(" ")
|
| 70 |
+
line: list[str] = []
|
| 71 |
+
for index, word in enumerate(words):
|
| 72 |
+
candidate = " ".join([*line, word])
|
| 73 |
+
if line and text_width(candidate, size, weight=weight) > limit:
|
| 74 |
+
return [" ".join(line), " ".join(words[index:])]
|
| 75 |
+
line.append(word)
|
| 76 |
+
return [" ".join(line)]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@dataclass
|
| 80 |
+
class Series:
|
| 81 |
+
label: str
|
| 82 |
+
x: list[float]
|
| 83 |
+
y: list[float]
|
| 84 |
+
color: str = PALETTE[0]
|
| 85 |
+
dash: str | None = None
|
| 86 |
+
marker: bool = True
|
| 87 |
+
width: float = 1.9
|
| 88 |
+
marker_size: float = 2.6
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@dataclass
|
| 92 |
+
class Band:
|
| 93 |
+
"""A shaded interval drawn behind its series."""
|
| 94 |
+
|
| 95 |
+
x: list[float]
|
| 96 |
+
low: list[float]
|
| 97 |
+
high: list[float]
|
| 98 |
+
color: str = PALETTE[0]
|
| 99 |
+
opacity: float = 0.16
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@dataclass
|
| 103 |
+
class Counts:
|
| 104 |
+
"""A support strip under the plot: how many rows sit behind each x position."""
|
| 105 |
+
|
| 106 |
+
x: list[float]
|
| 107 |
+
values: list[float]
|
| 108 |
+
color: str = MUTED
|
| 109 |
+
label: str = "rows per bin"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@dataclass
|
| 113 |
+
class Panel:
|
| 114 |
+
title: str
|
| 115 |
+
series: list[Series] = field(default_factory=list)
|
| 116 |
+
bands: list[Band] = field(default_factory=list)
|
| 117 |
+
xlabel: str = ""
|
| 118 |
+
ylabel: str = ""
|
| 119 |
+
xlim: tuple[float, float] | None = None
|
| 120 |
+
ylim: tuple[float, float] | None = None
|
| 121 |
+
xticks: list[tuple[float, str]] | None = None
|
| 122 |
+
yticks: list[tuple[float, str]] | None = None
|
| 123 |
+
xscale: str = "linear"
|
| 124 |
+
hlines: list[tuple[float, str, str]] = field(default_factory=list)
|
| 125 |
+
diagonal: bool = False
|
| 126 |
+
notes: list[str] = field(default_factory=list)
|
| 127 |
+
counts: Counts | None = None
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _fmt(value: float) -> str:
|
| 131 |
+
if abs(value) >= 1e6:
|
| 132 |
+
return f"{value:.3g}"
|
| 133 |
+
text = f"{value:.3f}".rstrip("0").rstrip(".")
|
| 134 |
+
return text or "0"
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _auto_ticks(low: float, high: float, count: int = 5) -> list[tuple[float, str]]:
|
| 138 |
+
if high <= low:
|
| 139 |
+
high = low + 1.0
|
| 140 |
+
step = (high - low) / count
|
| 141 |
+
magnitude = 10 ** math.floor(math.log10(step)) if step > 0 else 1.0
|
| 142 |
+
for factor in (1, 2, 2.5, 5, 10):
|
| 143 |
+
if step <= factor * magnitude:
|
| 144 |
+
step = factor * magnitude
|
| 145 |
+
break
|
| 146 |
+
start = math.ceil(low / step) * step
|
| 147 |
+
ticks = []
|
| 148 |
+
value = start
|
| 149 |
+
while value <= high + 1e-9:
|
| 150 |
+
ticks.append((value, _fmt(0.0 if abs(value) < step * 1e-6 else value)))
|
| 151 |
+
value += step
|
| 152 |
+
return ticks
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _text(
|
| 156 |
+
x: float,
|
| 157 |
+
y: float,
|
| 158 |
+
body: str,
|
| 159 |
+
*,
|
| 160 |
+
size: float,
|
| 161 |
+
fill: str = INK,
|
| 162 |
+
anchor: str = "start",
|
| 163 |
+
weight: str | None = None,
|
| 164 |
+
) -> str:
|
| 165 |
+
weight_attr = f' font-weight="{_attribute(weight)}"' if weight else ""
|
| 166 |
+
return (
|
| 167 |
+
f'<text x="{x:.1f}" y="{y:.1f}" text-anchor="{_attribute(anchor)}" font-size="{size}" '
|
| 168 |
+
f'fill="{_attribute(fill)}"{weight_attr} {FONT}>{escape(body)}</text>'
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _attribute(value: str) -> str:
|
| 173 |
+
return escape(value, {'"': '"'})
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
_TITLE_SIZE = 12.5
|
| 177 |
+
|
| 178 |
+
# Everything below the plot box is stacked in fixed bands rather than placed at absolute
|
| 179 |
+
# offsets, so an x-axis label, a support strip, and a note can coexist without overlapping.
|
| 180 |
+
_TICK_BAND = 18.0
|
| 181 |
+
_XLABEL_BAND = 16.0
|
| 182 |
+
_COUNTS_BAND = 30.0
|
| 183 |
+
_NOTE_BAND = 12.0
|
| 184 |
+
_NOTE_LEAD = 6.0
|
| 185 |
+
_FLOOR_SLACK = 8.0
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _panel_bottom(panel: Panel) -> float:
|
| 189 |
+
bottom = _TICK_BAND + _FLOOR_SLACK
|
| 190 |
+
if panel.xlabel:
|
| 191 |
+
bottom += _XLABEL_BAND
|
| 192 |
+
if panel.counts:
|
| 193 |
+
bottom += _COUNTS_BAND
|
| 194 |
+
if panel.notes:
|
| 195 |
+
bottom += _NOTE_LEAD + _NOTE_BAND * len(panel.notes)
|
| 196 |
+
return bottom
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _panel_svg(panel: Panel, width: float, height: float, *, title_rows: int | None = None) -> str:
|
| 200 |
+
left, right = 54.0, 14.0
|
| 201 |
+
plot_w = width - left - right
|
| 202 |
+
title_lines = _fit_lines(panel.title, _TITLE_SIZE, plot_w, weight="600")
|
| 203 |
+
top = 18.0 + 14.0 * (title_rows or len(title_lines))
|
| 204 |
+
plot_h = height - top - _panel_bottom(panel)
|
| 205 |
+
|
| 206 |
+
xs = [x for s in panel.series for x in s.x] or [0.0, 1.0]
|
| 207 |
+
ys = [y for s in panel.series for y in s.y] or [0.0, 1.0]
|
| 208 |
+
ys += [value for band in panel.bands for value in (*band.low, *band.high)]
|
| 209 |
+
ys += [level for level, _, _ in panel.hlines]
|
| 210 |
+
xlim = panel.xlim or (min(xs), max(xs))
|
| 211 |
+
ylim = panel.ylim or (min(ys), max(ys))
|
| 212 |
+
if ylim[0] == ylim[1]:
|
| 213 |
+
ylim = (ylim[0] - 0.5, ylim[1] + 0.5)
|
| 214 |
+
|
| 215 |
+
def tx(value: float) -> float:
|
| 216 |
+
if panel.xscale == "log":
|
| 217 |
+
lo, hi = math.log(xlim[0]), math.log(xlim[1])
|
| 218 |
+
return left + (math.log(value) - lo) / (hi - lo) * plot_w
|
| 219 |
+
return left + (value - xlim[0]) / (xlim[1] - xlim[0]) * plot_w
|
| 220 |
+
|
| 221 |
+
def ty(value: float) -> float:
|
| 222 |
+
return top + plot_h - (value - ylim[0]) / (ylim[1] - ylim[0]) * plot_h
|
| 223 |
+
|
| 224 |
+
parts: list[str] = []
|
| 225 |
+
for index, line in enumerate(title_lines):
|
| 226 |
+
parts.append(
|
| 227 |
+
_text(
|
| 228 |
+
left + plot_w / 2,
|
| 229 |
+
16.0 + 14.0 * index,
|
| 230 |
+
line,
|
| 231 |
+
size=_TITLE_SIZE,
|
| 232 |
+
anchor="middle",
|
| 233 |
+
weight="600",
|
| 234 |
+
)
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
xticks = panel.xticks or _auto_ticks(*xlim)
|
| 238 |
+
yticks = panel.yticks or _auto_ticks(*ylim)
|
| 239 |
+
for value, label in yticks:
|
| 240 |
+
if not ylim[0] - 1e-9 <= value <= ylim[1] + 1e-9:
|
| 241 |
+
continue
|
| 242 |
+
y = ty(value)
|
| 243 |
+
parts.append(
|
| 244 |
+
f'<line x1="{left}" y1="{y:.1f}" x2="{left + plot_w:.1f}" y2="{y:.1f}" '
|
| 245 |
+
f'stroke="{GRID}" stroke-width="1"/>'
|
| 246 |
+
)
|
| 247 |
+
parts.append(_text(left - 6, y + 3.4, label, size=10, fill=MUTED, anchor="end"))
|
| 248 |
+
for value, label in xticks:
|
| 249 |
+
if not xlim[0] - 1e-9 <= value <= xlim[1] + 1e-9:
|
| 250 |
+
continue
|
| 251 |
+
x = tx(value)
|
| 252 |
+
parts.append(
|
| 253 |
+
f'<line x1="{x:.1f}" y1="{top}" x2="{x:.1f}" y2="{top + plot_h:.1f}" '
|
| 254 |
+
f'stroke="{GRID}" stroke-width="1"/>'
|
| 255 |
+
)
|
| 256 |
+
parts.append(_text(x, top + plot_h + 13, label, size=10, fill=MUTED, anchor="middle"))
|
| 257 |
+
|
| 258 |
+
if panel.diagonal:
|
| 259 |
+
parts.append(
|
| 260 |
+
f'<line x1="{tx(xlim[0]):.1f}" y1="{ty(ylim[0]):.1f}" '
|
| 261 |
+
f'x2="{tx(xlim[1]):.1f}" y2="{ty(ylim[1]):.1f}" stroke="{AXIS}" '
|
| 262 |
+
f'stroke-width="1.1" stroke-dasharray="4 3"/>'
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
for band in panel.bands:
|
| 266 |
+
forward = " ".join(
|
| 267 |
+
f"{tx(x):.1f},{ty(y):.1f}" for x, y in zip(band.x, band.high, strict=True)
|
| 268 |
+
)
|
| 269 |
+
backward = " ".join(
|
| 270 |
+
f"{tx(x):.1f},{ty(y):.1f}"
|
| 271 |
+
for x, y in zip(reversed(band.x), reversed(band.low), strict=True)
|
| 272 |
+
)
|
| 273 |
+
parts.append(
|
| 274 |
+
f'<polygon points="{forward} {backward}" fill="{_attribute(band.color)}" '
|
| 275 |
+
f'fill-opacity="{_attribute(str(band.opacity))}" stroke="none"/>'
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
# A reference line carries its label just above it at the left margin. Figures have no
|
| 279 |
+
# background, so no backing box can hide the data beneath a label in both page themes.
|
| 280 |
+
for value, label, color in panel.hlines:
|
| 281 |
+
y = ty(value)
|
| 282 |
+
parts.append(
|
| 283 |
+
f'<line x1="{left}" y1="{y:.1f}" x2="{left + plot_w:.1f}" y2="{y:.1f}" '
|
| 284 |
+
f'stroke="{_attribute(color)}" stroke-width="1.2" stroke-dasharray="5 3"/>'
|
| 285 |
+
)
|
| 286 |
+
if label:
|
| 287 |
+
parts.append(_text(left + 7, y - 3.5, label, size=9.5, fill=color))
|
| 288 |
+
|
| 289 |
+
for series in panel.series:
|
| 290 |
+
points = " ".join(
|
| 291 |
+
f"{tx(x):.1f},{ty(y):.1f}" for x, y in zip(series.x, series.y, strict=True)
|
| 292 |
+
)
|
| 293 |
+
dash = f' stroke-dasharray="{_attribute(series.dash)}"' if series.dash else ""
|
| 294 |
+
parts.append(
|
| 295 |
+
f'<polyline points="{points}" fill="none" stroke="{_attribute(series.color)}" '
|
| 296 |
+
f'stroke-width="{_attribute(str(series.width))}" stroke-linejoin="round" '
|
| 297 |
+
f'stroke-linecap="round"{dash}/>'
|
| 298 |
+
)
|
| 299 |
+
if series.marker:
|
| 300 |
+
for x, y in zip(series.x, series.y, strict=True):
|
| 301 |
+
parts.append(
|
| 302 |
+
f'<circle cx="{tx(x):.1f}" cy="{ty(y):.1f}" r="{_attribute(str(series.marker_size))}" '
|
| 303 |
+
f'fill="{_attribute(series.color)}"/>'
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
parts.append(
|
| 307 |
+
f'<rect x="{left}" y="{top}" width="{plot_w:.1f}" height="{plot_h:.1f}" fill="none" '
|
| 308 |
+
f'stroke="{AXIS}" stroke-width="1"/>'
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
cursor = top + plot_h + _TICK_BAND
|
| 312 |
+
if panel.xlabel:
|
| 313 |
+
parts.append(
|
| 314 |
+
_text(
|
| 315 |
+
left + plot_w / 2,
|
| 316 |
+
cursor + 11,
|
| 317 |
+
panel.xlabel,
|
| 318 |
+
size=10.5,
|
| 319 |
+
fill=MUTED,
|
| 320 |
+
anchor="middle",
|
| 321 |
+
)
|
| 322 |
+
)
|
| 323 |
+
cursor += _XLABEL_BAND
|
| 324 |
+
if panel.counts:
|
| 325 |
+
counts = panel.counts
|
| 326 |
+
if not counts.values:
|
| 327 |
+
raise ValueError("a support strip needs at least one count")
|
| 328 |
+
strip_top = cursor + 2.0
|
| 329 |
+
strip_h = 15.0
|
| 330 |
+
peak = max(counts.values) or 1.0
|
| 331 |
+
slot = plot_w / max(len(counts.x), 1) * 0.7
|
| 332 |
+
for x, value in zip(counts.x, counts.values, strict=True):
|
| 333 |
+
bar_h = (value / peak) * strip_h
|
| 334 |
+
parts.append(
|
| 335 |
+
f'<rect x="{tx(x) - slot / 2:.1f}" y="{strip_top + strip_h - bar_h:.1f}" '
|
| 336 |
+
f'width="{slot:.1f}" height="{bar_h:.1f}" fill="{_attribute(counts.color)}" '
|
| 337 |
+
f'fill-opacity="0.5"/>'
|
| 338 |
+
)
|
| 339 |
+
parts.append(
|
| 340 |
+
f'<line x1="{left}" y1="{strip_top + strip_h:.1f}" x2="{left + plot_w:.1f}" '
|
| 341 |
+
f'y2="{strip_top + strip_h:.1f}" stroke="{GRID_STRONG}" stroke-width="1"/>'
|
| 342 |
+
)
|
| 343 |
+
parts.append(_text(left, strip_top + strip_h + 9, counts.label, size=9, fill=MUTED))
|
| 344 |
+
parts.append(
|
| 345 |
+
_text(
|
| 346 |
+
left + plot_w,
|
| 347 |
+
strip_top + strip_h + 9,
|
| 348 |
+
f"tallest {int(peak):,}",
|
| 349 |
+
size=9,
|
| 350 |
+
fill=MUTED,
|
| 351 |
+
anchor="end",
|
| 352 |
+
)
|
| 353 |
+
)
|
| 354 |
+
cursor += _COUNTS_BAND
|
| 355 |
+
for index, note in enumerate(panel.notes):
|
| 356 |
+
parts.append(
|
| 357 |
+
_text(left, cursor + _NOTE_LEAD + 9 + _NOTE_BAND * index, note, size=9.5, fill=MUTED)
|
| 358 |
+
)
|
| 359 |
+
if panel.ylabel:
|
| 360 |
+
parts.append(
|
| 361 |
+
f'<text transform="translate(13,{top + plot_h / 2:.1f}) rotate(-90)" '
|
| 362 |
+
f'text-anchor="middle" font-size="10.5" fill="{MUTED}" {FONT}>'
|
| 363 |
+
f"{escape(panel.ylabel)}</text>"
|
| 364 |
+
)
|
| 365 |
+
return "\n".join(parts)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _legend_svg(
|
| 369 |
+
entries: list[tuple[str, str, str | None]],
|
| 370 |
+
*,
|
| 371 |
+
x: float,
|
| 372 |
+
y: float,
|
| 373 |
+
max_width: float,
|
| 374 |
+
) -> tuple[str, float]:
|
| 375 |
+
"""Flow legend entries across as many rows as their measured widths need."""
|
| 376 |
+
|
| 377 |
+
swatch, gap, pad = 22.0, 7.0, 22.0
|
| 378 |
+
parts: list[str] = []
|
| 379 |
+
cursor_x, cursor_y, rows = x, y, 1
|
| 380 |
+
for label, color, dash in entries:
|
| 381 |
+
entry_w = swatch + gap + text_width(label, 11) + pad
|
| 382 |
+
if cursor_x > x and cursor_x + entry_w - pad > x + max_width:
|
| 383 |
+
cursor_x, cursor_y, rows = x, cursor_y + 16.0, rows + 1
|
| 384 |
+
dash_attr = f' stroke-dasharray="{_attribute(dash)}"' if dash else ""
|
| 385 |
+
parts.append(
|
| 386 |
+
f'<line x1="{cursor_x:.1f}" y1="{cursor_y:.1f}" x2="{cursor_x + swatch:.1f}" '
|
| 387 |
+
f'y2="{cursor_y:.1f}" stroke="{_attribute(color)}" stroke-width="2.4" '
|
| 388 |
+
f'stroke-linecap="round"{dash_attr}/>'
|
| 389 |
+
)
|
| 390 |
+
parts.append(_text(cursor_x + swatch + gap, cursor_y + 3.8, label, size=11))
|
| 391 |
+
cursor_x += entry_w
|
| 392 |
+
return "\n".join(parts), 16.0 * rows
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def _dedupe(entries: list[tuple[str, str, str | None]]) -> list[tuple[str, str, str | None]]:
|
| 396 |
+
seen: set[tuple[str, str, str | None]] = set()
|
| 397 |
+
unique = []
|
| 398 |
+
for entry in entries:
|
| 399 |
+
if entry not in seen:
|
| 400 |
+
seen.add(entry)
|
| 401 |
+
unique.append(entry)
|
| 402 |
+
return unique
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def _open_svg(width: float, height: float, title: str, description: str) -> list[str]:
|
| 406 |
+
return [
|
| 407 |
+
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width:.0f}" height="{height:.0f}" '
|
| 408 |
+
f'viewBox="0 0 {width:.0f} {height:.0f}" role="img" aria-label="{_attribute(title)}">',
|
| 409 |
+
f"<title>{escape(title)}</title>",
|
| 410 |
+
f"<desc>{escape(description)}</desc>",
|
| 411 |
+
]
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def render_grid(
|
| 415 |
+
panels: list[Panel],
|
| 416 |
+
*,
|
| 417 |
+
columns: int,
|
| 418 |
+
title: str,
|
| 419 |
+
subtitle: str = "",
|
| 420 |
+
panel_width: float = 352.0,
|
| 421 |
+
panel_height: float = 256.0,
|
| 422 |
+
legend: list[tuple[str, str, str | None]] | None = None,
|
| 423 |
+
description: str = "",
|
| 424 |
+
) -> str:
|
| 425 |
+
"""Render panels on a grid with one shared title and a flowed legend.
|
| 426 |
+
|
| 427 |
+
A final short row is centred, so a five-panel figure on three columns has no empty cell.
|
| 428 |
+
"""
|
| 429 |
+
|
| 430 |
+
if not panels:
|
| 431 |
+
raise ValueError("render_grid needs at least one panel")
|
| 432 |
+
if columns < 1:
|
| 433 |
+
raise ValueError("render_grid needs at least one column")
|
| 434 |
+
legend = _dedupe(legend or [])
|
| 435 |
+
rows = math.ceil(len(panels) / columns)
|
| 436 |
+
width = columns * panel_width
|
| 437 |
+
header = 26.0 + (16.0 if subtitle else 0.0)
|
| 438 |
+
legend_svg, legend_h = "", 0.0
|
| 439 |
+
if legend:
|
| 440 |
+
legend_svg, legend_h = _legend_svg(legend, x=18.0, y=header + 10.0, max_width=width - 36.0)
|
| 441 |
+
legend_h += 8.0
|
| 442 |
+
height = header + legend_h + rows * panel_height
|
| 443 |
+
parts = _open_svg(width, height, title, description or title)
|
| 444 |
+
parts.append(_text(width / 2, 19, title, size=14.5, anchor="middle", weight="700"))
|
| 445 |
+
if subtitle:
|
| 446 |
+
parts.append(_text(width / 2, 34, subtitle, size=11, fill=MUTED, anchor="middle"))
|
| 447 |
+
if legend_svg:
|
| 448 |
+
parts.append(legend_svg)
|
| 449 |
+
# One title row count for the whole grid, so a panel whose title wraps does not push its
|
| 450 |
+
# plot box below its neighbours'.
|
| 451 |
+
title_rows = max(
|
| 452 |
+
len(_fit_lines(panel.title, _TITLE_SIZE, panel_width - 68.0, weight="600"))
|
| 453 |
+
for panel in panels
|
| 454 |
+
)
|
| 455 |
+
for index, panel in enumerate(panels):
|
| 456 |
+
row, column = divmod(index, columns)
|
| 457 |
+
in_row = min(columns, len(panels) - row * columns)
|
| 458 |
+
offset = (columns - in_row) * panel_width / 2.0
|
| 459 |
+
px = offset + column * panel_width
|
| 460 |
+
py = header + legend_h + row * panel_height
|
| 461 |
+
parts.append(f'<g transform="translate({px:.1f},{py:.1f})">')
|
| 462 |
+
parts.append(_panel_svg(panel, panel_width, panel_height, title_rows=title_rows))
|
| 463 |
+
parts.append("</g>")
|
| 464 |
+
parts.append("</svg>")
|
| 465 |
+
return "\n".join(parts) + "\n"
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def render_bars(
|
| 469 |
+
groups: list[str],
|
| 470 |
+
series: list[tuple[str, list[float], str]],
|
| 471 |
+
*,
|
| 472 |
+
title: str,
|
| 473 |
+
ylabel: str,
|
| 474 |
+
subtitle: str = "",
|
| 475 |
+
ylim: tuple[float, float] = (0.0, 1.0),
|
| 476 |
+
reference: list[tuple[str, list[float], str]] | None = None,
|
| 477 |
+
notes: list[str] | None = None,
|
| 478 |
+
separator_before: int | None = None,
|
| 479 |
+
width: float = 780.0,
|
| 480 |
+
height: float = 350.0,
|
| 481 |
+
description: str = "",
|
| 482 |
+
) -> str:
|
| 483 |
+
"""Render grouped bars with per-group dashed reference levels.
|
| 484 |
+
|
| 485 |
+
Bars keep a zero baseline. Value labels are drawn only where a bar is wide enough to hold
|
| 486 |
+
one, because a crowded label is worse than none.
|
| 487 |
+
"""
|
| 488 |
+
|
| 489 |
+
if not groups or not series:
|
| 490 |
+
raise ValueError("render_bars needs at least one group and one series")
|
| 491 |
+
if any(len(values) != len(groups) for _, values, _ in series):
|
| 492 |
+
raise ValueError("every bar series must carry one value per group")
|
| 493 |
+
notes = notes or []
|
| 494 |
+
left, right, top = 54.0, 16.0, 26.0 + (15.0 if subtitle else 0.0)
|
| 495 |
+
legend_entries = [(label, color, None) for label, _, color in series]
|
| 496 |
+
legend_entries += [(label, color, "5 3") for label, _, color in reference or []]
|
| 497 |
+
legend_svg, legend_h = _legend_svg(
|
| 498 |
+
_dedupe(legend_entries), x=18.0, y=top + 12.0, max_width=width - 36.0
|
| 499 |
+
)
|
| 500 |
+
top += legend_h + 10.0
|
| 501 |
+
bottom = 46.0 + 12.0 * len(notes)
|
| 502 |
+
plot_w, plot_h = width - left - right, height - top - bottom
|
| 503 |
+
group_w = plot_w / len(groups)
|
| 504 |
+
bar_w = group_w * 0.74 / len(series)
|
| 505 |
+
|
| 506 |
+
def ty(value: float) -> float:
|
| 507 |
+
return top + plot_h - (value - ylim[0]) / (ylim[1] - ylim[0]) * plot_h
|
| 508 |
+
|
| 509 |
+
parts = _open_svg(width, height, title, description or title)
|
| 510 |
+
parts.append(_text(width / 2, 19, title, size=14.5, anchor="middle", weight="700"))
|
| 511 |
+
if subtitle:
|
| 512 |
+
parts.append(_text(width / 2, 34, subtitle, size=11, fill=MUTED, anchor="middle"))
|
| 513 |
+
parts.append(legend_svg)
|
| 514 |
+
for value, label in _auto_ticks(*ylim):
|
| 515 |
+
y = ty(value)
|
| 516 |
+
parts.append(
|
| 517 |
+
f'<line x1="{left}" y1="{y:.1f}" x2="{left + plot_w:.1f}" y2="{y:.1f}" '
|
| 518 |
+
f'stroke="{GRID}" stroke-width="1"/>'
|
| 519 |
+
)
|
| 520 |
+
parts.append(_text(left - 6, y + 3.4, label, size=10, fill=MUTED, anchor="end"))
|
| 521 |
+
|
| 522 |
+
label_fits = bar_w - 2 >= text_width("0.000", 8.5) + 2
|
| 523 |
+
for g_index, group in enumerate(groups):
|
| 524 |
+
gx = left + g_index * group_w + group_w * 0.13
|
| 525 |
+
for s_index, (_, values, color) in enumerate(series):
|
| 526 |
+
value = values[g_index]
|
| 527 |
+
x = gx + s_index * bar_w
|
| 528 |
+
parts.append(
|
| 529 |
+
f'<rect x="{x:.1f}" y="{ty(value):.1f}" width="{bar_w - 2:.1f}" '
|
| 530 |
+
f'height="{ty(ylim[0]) - ty(value):.1f}" fill="{_attribute(color)}"/>'
|
| 531 |
+
)
|
| 532 |
+
if label_fits:
|
| 533 |
+
parts.append(
|
| 534 |
+
_text(
|
| 535 |
+
x + (bar_w - 2) / 2,
|
| 536 |
+
ty(value) - 4,
|
| 537 |
+
f"{value:.3f}",
|
| 538 |
+
size=8.5,
|
| 539 |
+
anchor="middle",
|
| 540 |
+
)
|
| 541 |
+
)
|
| 542 |
+
for _, values, color in reference or []:
|
| 543 |
+
y = ty(values[g_index])
|
| 544 |
+
parts.append(
|
| 545 |
+
f'<line x1="{gx - 3:.1f}" y1="{y:.1f}" '
|
| 546 |
+
f'x2="{gx + group_w * 0.74 + 3:.1f}" y2="{y:.1f}" stroke="{_attribute(color)}" '
|
| 547 |
+
f'stroke-width="1.6" stroke-dasharray="5 3"/>'
|
| 548 |
+
)
|
| 549 |
+
parts.append(
|
| 550 |
+
_text(
|
| 551 |
+
left + g_index * group_w + group_w / 2,
|
| 552 |
+
top + plot_h + 16,
|
| 553 |
+
group,
|
| 554 |
+
size=11,
|
| 555 |
+
anchor="middle",
|
| 556 |
+
)
|
| 557 |
+
)
|
| 558 |
+
if separator_before is not None and 0 < separator_before < len(groups):
|
| 559 |
+
x = left + separator_before * group_w
|
| 560 |
+
parts.append(
|
| 561 |
+
f'<line x1="{x:.1f}" y1="{top}" x2="{x:.1f}" y2="{top + plot_h + 6:.1f}" '
|
| 562 |
+
f'stroke="{GRID_STRONG}" stroke-width="1.4"/>'
|
| 563 |
+
)
|
| 564 |
+
parts.append(
|
| 565 |
+
f'<rect x="{left}" y="{top}" width="{plot_w:.1f}" height="{plot_h:.1f}" fill="none" '
|
| 566 |
+
f'stroke="{AXIS}" stroke-width="1"/>'
|
| 567 |
+
)
|
| 568 |
+
parts.append(
|
| 569 |
+
f'<text transform="translate(13,{top + plot_h / 2:.1f}) rotate(-90)" '
|
| 570 |
+
f'text-anchor="middle" font-size="10.5" fill="{MUTED}" {FONT}>'
|
| 571 |
+
f"{escape(ylabel)}</text>"
|
| 572 |
+
)
|
| 573 |
+
for index, note in enumerate(notes):
|
| 574 |
+
parts.append(_text(left, top + plot_h + 34 + 12 * index, note, size=9.5, fill=MUTED))
|
| 575 |
+
parts.append("</svg>")
|
| 576 |
+
return "\n".join(parts) + "\n"
|
figures/classifier-comparison.svg
CHANGED
|
|
|
|
publication-manifest.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
{
|
| 2 |
"schema": "daecore.classifier-publication-manifest",
|
| 3 |
-
"tool_sha256": "
|
| 4 |
"public_repo": "Daecore/gliclass-knowledge-classifier-v2",
|
| 5 |
"classifier_version": "gliclass-std-base-v3-daecore-5facet-qint8-v2",
|
| 6 |
"upstream": {
|
|
@@ -10,7 +10,7 @@
|
|
| 10 |
"nominee_receipt_sha256": "d463fc167b2a26f8f5b56e03c18e4c604b231eb25b5093064dd8a9bd7ffa6373",
|
| 11 |
"derivation_preparation_sha256": "bfd902e06b7a984348283dc279f5e46d76398ff59633a9b5b426f33d872a67d3",
|
| 12 |
"source_nominee_binding": "unchanged learned model and calibration; graph bytes separately derived",
|
| 13 |
-
"staged_at": "2026-
|
| 14 |
"files": {
|
| 15 |
"classifier-metadata.json": {
|
| 16 |
"sha256": "736d8b615fb8c4bd7cc36d1c2e0e86bbe096d63dc373d047ca75af9cc6119a11",
|
|
@@ -48,18 +48,18 @@
|
|
| 48 |
"binding": "packaging record"
|
| 49 |
},
|
| 50 |
"NOTICE": {
|
| 51 |
-
"sha256": "
|
| 52 |
-
"size":
|
| 53 |
"binding": "packaging record"
|
| 54 |
},
|
| 55 |
"MODIFICATIONS.md": {
|
| 56 |
-
"sha256": "
|
| 57 |
-
"size":
|
| 58 |
"binding": "packaging record"
|
| 59 |
},
|
| 60 |
"evaluation/README.md": {
|
| 61 |
-
"sha256": "
|
| 62 |
-
"size":
|
| 63 |
"binding": "packaging record"
|
| 64 |
},
|
| 65 |
"evaluation/serving-qualification.json": {
|
|
@@ -68,8 +68,8 @@
|
|
| 68 |
"binding": "packaging record"
|
| 69 |
},
|
| 70 |
"evaluation/metrics.py": {
|
| 71 |
-
"sha256": "
|
| 72 |
-
"size":
|
| 73 |
"binding": "packaging record"
|
| 74 |
},
|
| 75 |
"evaluation/classifier-summary.json": {
|
|
@@ -83,25 +83,25 @@
|
|
| 83 |
"binding": "packaging record"
|
| 84 |
},
|
| 85 |
"evaluation/figures.py": {
|
| 86 |
-
"sha256": "
|
| 87 |
-
"size":
|
| 88 |
"binding": "packaging record"
|
| 89 |
},
|
| 90 |
"evaluation/svg_figures.py": {
|
| 91 |
-
"sha256": "
|
| 92 |
-
"size":
|
| 93 |
"binding": "packaging record"
|
| 94 |
},
|
| 95 |
"figures/classifier-comparison.svg": {
|
| 96 |
-
"sha256": "
|
| 97 |
-
"size":
|
| 98 |
"binding": "packaging record"
|
| 99 |
},
|
| 100 |
"README.md": {
|
| 101 |
-
"sha256": "
|
| 102 |
-
"size":
|
| 103 |
"binding": "model card with upload-relative links",
|
| 104 |
-
"source_sha256": "
|
| 105 |
}
|
| 106 |
}
|
| 107 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"schema": "daecore.classifier-publication-manifest",
|
| 3 |
+
"tool_sha256": "1451c82d45b3cf8e37c7d5300902dc825d2065ac754a73c673cae95151a9c895",
|
| 4 |
"public_repo": "Daecore/gliclass-knowledge-classifier-v2",
|
| 5 |
"classifier_version": "gliclass-std-base-v3-daecore-5facet-qint8-v2",
|
| 6 |
"upstream": {
|
|
|
|
| 10 |
"nominee_receipt_sha256": "d463fc167b2a26f8f5b56e03c18e4c604b231eb25b5093064dd8a9bd7ffa6373",
|
| 11 |
"derivation_preparation_sha256": "bfd902e06b7a984348283dc279f5e46d76398ff59633a9b5b426f33d872a67d3",
|
| 12 |
"source_nominee_binding": "unchanged learned model and calibration; graph bytes separately derived",
|
| 13 |
+
"staged_at": "2026-11-24T22:07:20+00:00",
|
| 14 |
"files": {
|
| 15 |
"classifier-metadata.json": {
|
| 16 |
"sha256": "736d8b615fb8c4bd7cc36d1c2e0e86bbe096d63dc373d047ca75af9cc6119a11",
|
|
|
|
| 48 |
"binding": "packaging record"
|
| 49 |
},
|
| 50 |
"NOTICE": {
|
| 51 |
+
"sha256": "31d3ca2802f859adf5f63344e9a89e9e29c4300314e3611d4fdbc6902aa2ca1c",
|
| 52 |
+
"size": 761,
|
| 53 |
"binding": "packaging record"
|
| 54 |
},
|
| 55 |
"MODIFICATIONS.md": {
|
| 56 |
+
"sha256": "36350ed9f70e7fe8d9e6146eb785d860fd7bf2288422ac6b79cd02c48d30d994",
|
| 57 |
+
"size": 1759,
|
| 58 |
"binding": "packaging record"
|
| 59 |
},
|
| 60 |
"evaluation/README.md": {
|
| 61 |
+
"sha256": "53cd10dfaf8db310db30e8ffa6430ead8e3a46cda6e0b9c2044b0f66ae33ec1e",
|
| 62 |
+
"size": 3121,
|
| 63 |
"binding": "packaging record"
|
| 64 |
},
|
| 65 |
"evaluation/serving-qualification.json": {
|
|
|
|
| 68 |
"binding": "packaging record"
|
| 69 |
},
|
| 70 |
"evaluation/metrics.py": {
|
| 71 |
+
"sha256": "8123f75da6edb158db74c62c1c65b6eefbc2713572409ac8a9bfb5424497aaf1",
|
| 72 |
+
"size": 19927,
|
| 73 |
"binding": "packaging record"
|
| 74 |
},
|
| 75 |
"evaluation/classifier-summary.json": {
|
|
|
|
| 83 |
"binding": "packaging record"
|
| 84 |
},
|
| 85 |
"evaluation/figures.py": {
|
| 86 |
+
"sha256": "cb7dd2c37cf744df87b70add16a27d4a551b814d50ae2a6e6107672c387c9e7f",
|
| 87 |
+
"size": 5527,
|
| 88 |
"binding": "packaging record"
|
| 89 |
},
|
| 90 |
"evaluation/svg_figures.py": {
|
| 91 |
+
"sha256": "001c82690851f6e5e7c3862ff9a4e49de3d52905ae45b2e5d841efd1464f8742",
|
| 92 |
+
"size": 21234,
|
| 93 |
"binding": "packaging record"
|
| 94 |
},
|
| 95 |
"figures/classifier-comparison.svg": {
|
| 96 |
+
"sha256": "465dce6d4e47e7cfa5ebe9c13e52b83efe905b6de1e9fee527b2353f943fdad6",
|
| 97 |
+
"size": 8599,
|
| 98 |
"binding": "packaging record"
|
| 99 |
},
|
| 100 |
"README.md": {
|
| 101 |
+
"sha256": "a627c38d77d5634f254932ba30c3e820a7369e645b2d4ad28f4a90cef944e906",
|
| 102 |
+
"size": 11072,
|
| 103 |
"binding": "model card with upload-relative links",
|
| 104 |
+
"source_sha256": "1ec9c7f4d7735ddd9106db6bcc5bb3cd06ccc4aa636a31aee62e9a74f4296f3c"
|
| 105 |
}
|
| 106 |
}
|
| 107 |
}
|