rustframe 0.0.1-a.20250805

A simple dataframe and math toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# create_benchmark_table.py

import argparse
import json
import re
import sys
from pathlib import Path
from pprint import pprint
from collections import defaultdict
from typing import Dict, Any, Optional

import pandas as pd
import html  # Import the html module for escaping


# Regular expression to parse "test_name (size)" format
DIR_PATTERN = re.compile(r"^(.*?) \((.*?)\)$")

# Standard location for criterion estimates relative to the benchmark dir
ESTIMATES_PATH_NEW = Path("new") / "estimates.json"
# Fallback location (older versions or baseline comparisons)
ESTIMATES_PATH_BASE = Path("base") / "estimates.json"

# Standard location for the HTML report relative to the benchmark's specific directory
REPORT_HTML_RELATIVE_PATH = Path("report") / "index.html"


def get_default_criterion_report_path() -> Path:
    """
    Returns the default path for the Criterion benchmark report.
    This is typically 'target/criterion'.
    """
    return Path("target") / "criterion" / "report" / "index.html"


def load_criterion_reports(
    criterion_root_dir: Path,
) -> Dict[str, Dict[str, Dict[str, Any]]]:
    """
    Loads Criterion benchmark results from a specified directory and finds HTML paths.

    Args:
        criterion_root_dir: The Path object pointing to the main
                           'target/criterion' directory.

    Returns:
        A nested dictionary structured as:
        { test_name: { size: {'json': json_content, 'html_path': relative_html_path}, ... }, ... }
        Returns an empty dict if the root directory is not found or empty.
    """
    results: Dict[str, Dict[str, Dict[str, Any]]] = defaultdict(dict)

    if not criterion_root_dir.is_dir():
        print(
            f"Error: Criterion root directory not found or is not a directory: {criterion_root_dir}",
            file=sys.stderr,
        )
        return {}

    print(f"Scanning for benchmark reports in: {criterion_root_dir}")

    for item in criterion_root_dir.iterdir():
        if not item.is_dir():
            continue

        match = DIR_PATTERN.match(item.name)
        if not match:
            continue

        test_name = match.group(1).strip()
        size = match.group(2).strip()
        benchmark_dir_name = item.name
        benchmark_dir_path = item

        json_path: Optional[Path] = None

        if (benchmark_dir_path / ESTIMATES_PATH_NEW).is_file():
            json_path = benchmark_dir_path / ESTIMATES_PATH_NEW
        elif (benchmark_dir_path / ESTIMATES_PATH_BASE).is_file():
            json_path = benchmark_dir_path / ESTIMATES_PATH_BASE

        html_path = benchmark_dir_path / REPORT_HTML_RELATIVE_PATH

        if json_path is None or not json_path.is_file():
            print(
                f"Warning: Could not find estimates JSON in {benchmark_dir_path}. Skipping benchmark size '{test_name} ({size})'.",
                file=sys.stderr,
            )
            continue

        if not html_path.is_file():
            print(
                f"Warning: Could not find HTML report at expected location {html_path}. Skipping benchmark size '{test_name} ({size})'.",
                file=sys.stderr,
            )
            continue

        try:
            with json_path.open("r", encoding="utf-8") as f:
                json_data = json.load(f)

            results[test_name][size] = {
                "json": json_data,
                "html_path_relative_to_criterion_root": str(
                    Path(benchmark_dir_name) / REPORT_HTML_RELATIVE_PATH
                ).replace("\\", "/"),
            }
        except json.JSONDecodeError:
            print(f"Error: Failed to decode JSON from {json_path}", file=sys.stderr)
        except IOError as e:
            print(f"Error: Failed to read file {json_path}: {e}", file=sys.stderr)
        except Exception as e:
            print(
                f"Error: An unexpected error occurred loading {json_path}: {e}",
                file=sys.stderr,
            )

    return dict(results)


def format_nanoseconds(ns: float) -> str:
    """Formats nanoseconds into a human-readable string with units."""
    if pd.isna(ns):
        return "-"
    if ns < 1_000:
        return f"{ns:.2f} ns"
    elif ns < 1_000_000:
        return f"{ns / 1_000:.2f} µs"
    elif ns < 1_000_000_000:
        return f"{ns / 1_000_000:.2f} ms"
    else:
        return f"{ns / 1_000_000_000:.2f} s"


def generate_html_table_with_links(
    results: Dict[str, Dict[str, Dict[str, Any]]], html_base_path: str
) -> str:
    """
    Generates a full HTML page with a styled table from benchmark results.
    """
    css_styles = """
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background-color: #f4f7f6;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
            border-radius: 8px;
        }
        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 10px;
        }
        p.subtitle {
            text-align: center;
            margin-bottom: 8px;
            color: #555;
            font-size: 0.95em;
        }
        p.note {
            text-align: center;
            margin-bottom: 25px;
            color: #777;
            font-size: 0.85em;
        }
        .benchmark-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 25px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .benchmark-table th, .benchmark-table td {
            border: 1px solid #dfe6e9; /* Lighter border */
            padding: 12px 15px;
        }
        .benchmark-table th {
            background-color: #3498db; /* Primary blue */
            color: #ffffff;
            font-weight: 600; /* Slightly bolder */
            text-transform: uppercase;
            letter-spacing: 0.05em;
            text-align: center; /* Center align headers */
        }
        .benchmark-table td {
            text-align: right; /* Default for data cells (times) */
        }
        .benchmark-table td:first-child { /* Benchmark Name column */
            font-weight: 500;
            color: #2d3436;
            text-align: left; /* Left align benchmark names */
        }
        .benchmark-table tbody tr:nth-child(even) {
            background-color: #f8f9fa; /* Very light grey for even rows */
        }
        .benchmark-table tbody tr:hover {
            background-color: #e9ecef; /* Slightly darker on hover */
        }
        .benchmark-table a {
            color: #2980b9; /* Link blue */
            text-decoration: none;
            font-weight: 500;
        }
        .benchmark-table a:hover {
            text-decoration: underline;
            color: #1c5a81; /* Darker blue on hover */
        }
        .no-results {
            text-align: center;
            font-size: 1.2em;
            color: #7f8c8d;
            margin-top: 30px;
        }
    </style>
    """

    html_doc_start = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Criterion Benchmark Results</title>
    {css_styles}
</head>
<body>
    <div class="container">
        <h1 id="criterion-benchmark-results">Criterion Benchmark Results</h1>
"""

    html_doc_end = """
    </div>
</body>
</html>"""

    if not results:
        return f"""{html_doc_start}
        <p class="no-results">No benchmark results found or loaded.</p>
{html_doc_end}"""

    all_sizes = sorted(
        list(set(size for test_data in results.values() for size in test_data.keys())),
        key=(lambda x: int(x.split("x")[0])),
    )
    all_test_names = sorted(list(results.keys()))

    table_content = """
        <p class="subtitle">Each cell links to the detailed Criterion.rs report for that specific benchmark size.</p>
        <p class="note">Note: Values shown are the midpoint of the mean confidence interval, formatted for readability.</p>
        <p class="note"><a href="report/index.html">[Switch to the standard Criterion.rs report]</a></p>
        <table class="benchmark-table">
            <thead>
                <tr>
                    <th>Benchmark Name</th>
    """

    for size in all_sizes:
        table_content += f"<th>{html.escape(size)}</th>\n"

    table_content += """
                </tr>
            </thead>
            <tbody>
    """

    for test_name in all_test_names:
        table_content += f"<tr>\n"
        table_content += f"    <td>{html.escape(test_name)}</td>\n"

        for size in all_sizes:
            cell_data = results.get(test_name, {}).get(size)
            mean_value = pd.NA
            full_report_url = "#"

            if (
                cell_data
                and "json" in cell_data
                and "html_path_relative_to_criterion_root" in cell_data
            ):
                try:
                    mean_data = cell_data["json"].get("mean")
                    if mean_data and "confidence_interval" in mean_data:
                        ci = mean_data["confidence_interval"]
                        if "lower_bound" in ci and "upper_bound" in ci:
                            lower, upper = ci["lower_bound"], ci["upper_bound"]
                            if isinstance(lower, (int, float)) and isinstance(
                                upper, (int, float)
                            ):
                                mean_value = (lower + upper) / 2.0
                            else:
                                print(
                                    f"Warning: Non-numeric bounds for {test_name} ({size}).",
                                    file=sys.stderr,
                                )
                        else:
                            print(
                                f"Warning: Missing confidence_interval bounds for {test_name} ({size}).",
                                file=sys.stderr,
                            )
                    else:
                        print(
                            f"Warning: Missing 'mean' data for {test_name} ({size}).",
                            file=sys.stderr,
                        )

                    relative_report_path = cell_data[
                        "html_path_relative_to_criterion_root"
                    ]
                    joined_path = Path(html_base_path) / relative_report_path
                    full_report_url = str(joined_path).replace("\\", "/")

                except Exception as e:
                    print(
                        f"Error processing cell data for {test_name} ({size}): {e}",
                        file=sys.stderr,
                    )

            formatted_mean = format_nanoseconds(mean_value)

            if full_report_url and full_report_url != "#":
                table_content += f'    <td><a href="{html.escape(full_report_url)}">{html.escape(formatted_mean)}</a></td>\n'
            else:
                table_content += f"    <td>{html.escape(formatted_mean)}</td>\n"
        table_content += "</tr>\n"

    table_content += """
            </tbody>
        </table>
    """
    return f"{html_doc_start}{table_content}{html_doc_end}"


if __name__ == "__main__":
    DEFAULT_CRITERION_PATH = "target/criterion"
    DEFAULT_OUTPUT_FILE = "./target/criterion/index.html"
    DEFAULT_HTML_BASE_PATH = ""

    parser = argparse.ArgumentParser(
        description="Load Criterion benchmark results from JSON files and generate an HTML table with links to reports."
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Perform a dry run without writing the HTML file.",
    )
    parser.add_argument(
        "--criterion-dir",
        type=str,
        default=DEFAULT_CRITERION_PATH,
        help=f"Path to the main 'target/criterion' directory (default: {DEFAULT_CRITERION_PATH}) containing benchmark data.",
    )
    parser.add_argument(
        "--html-base-path",
        type=str,
        default=DEFAULT_HTML_BASE_PATH,
        help=(
            f"Prefix for HTML links to individual benchmark reports. "
            f"This is prepended to each report's relative path (e.g., 'benchmark_name/report/index.html'). "
            f"If the main output HTML (default: '{DEFAULT_OUTPUT_FILE}') is in the 'target/criterion/' directory, "
            f"this should typically be empty (default: '{DEFAULT_HTML_BASE_PATH}'). "
        ),
    )
    parser.add_argument(
        "--output-file",
        type=str,
        default=DEFAULT_OUTPUT_FILE,
        help=f"Path to save the generated HTML summary report (default: {DEFAULT_OUTPUT_FILE}).",
    )

    args = parser.parse_args()

    if args.dry_run:
        print(
            "Dry run mode: No files will be written. Use --dry-run to skip writing the HTML file."
        )
        sys.exit(0)

    criterion_path = Path(args.criterion_dir)
    output_file_path = Path(args.output_file)

    try:
        output_file_path.parent.mkdir(parents=True, exist_ok=True)
    except OSError as e:
        print(
            f"Error: Could not create output directory {output_file_path.parent}: {e}",
            file=sys.stderr,
        )
        sys.exit(1)

    all_results = load_criterion_reports(criterion_path)

    # Generate HTML output regardless of whether results were found (handles "no results" page)
    html_output = generate_html_table_with_links(all_results, args.html_base_path)

    if not all_results:
        print("\nNo benchmark results found or loaded.")
        # Fallthrough to write the "no results" page generated by generate_html_table_with_links
    else:
        print("\nSuccessfully loaded benchmark results.")
        # pprint(all_results) # Uncomment for debugging

    print(
        f"Generating HTML report with links using HTML base path: '{args.html_base_path}'"
    )

    try:
        with output_file_path.open("w", encoding="utf-8") as f:
            f.write(html_output)
        print(f"\nSuccessfully wrote HTML report to {output_file_path}")
        if not all_results:
            sys.exit(1)  # Exit with error code if no results, though file is created
        sys.exit(0)
    except IOError as e:
        print(f"Error writing HTML output to {output_file_path}: {e}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"An unexpected error occurred while writing HTML: {e}", file=sys.stderr)
        sys.exit(1)