max-div 0.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. max_div-0.2.5/.gitignore +36 -0
  2. max_div-0.2.5/LICENSE +201 -0
  3. max_div-0.2.5/PKG-INFO +42 -0
  4. max_div-0.2.5/README.md +13 -0
  5. max_div-0.2.5/max_div/__init__.py +0 -0
  6. max_div-0.2.5/max_div/_cli.py +109 -0
  7. max_div-0.2.5/max_div/benchmark/__init__.py +3 -0
  8. max_div-0.2.5/max_div/benchmark/_formatting.py +218 -0
  9. max_div-0.2.5/max_div/benchmark/diversity_metrics.py +105 -0
  10. max_div-0.2.5/max_div/benchmark/randint.py +104 -0
  11. max_div-0.2.5/max_div/benchmark/randint_constrained.py +385 -0
  12. max_div-0.2.5/max_div/internal/__init__.py +0 -0
  13. max_div-0.2.5/max_div/internal/benchmarking/__init__.py +2 -0
  14. max_div-0.2.5/max_div/internal/benchmarking/_micro_benchmark.py +180 -0
  15. max_div-0.2.5/max_div/internal/benchmarking/_timer.py +35 -0
  16. max_div-0.2.5/max_div/internal/formatting/__init__.py +2 -0
  17. max_div-0.2.5/max_div/internal/formatting/_markdown.py +43 -0
  18. max_div-0.2.5/max_div/internal/formatting/_time_duration.py +175 -0
  19. max_div-0.2.5/max_div/internal/math/__init__.py +1 -0
  20. max_div-0.2.5/max_div/internal/math/fast_exp.py +96 -0
  21. max_div-0.2.5/max_div/internal/math/fast_log.py +102 -0
  22. max_div-0.2.5/max_div/internal/math/random.py +165 -0
  23. max_div-0.2.5/max_div/internal/math/select_k_minmax.py +251 -0
  24. max_div-0.2.5/max_div/internal/utils/__init__.py +2 -0
  25. max_div-0.2.5/max_div/internal/utils/_clip.py +5 -0
  26. max_div-0.2.5/max_div/internal/utils/_precision.py +5 -0
  27. max_div-0.2.5/max_div/sampling/__init__.py +1 -0
  28. max_div-0.2.5/max_div/sampling/_constraint_helpers.py +201 -0
  29. max_div-0.2.5/max_div/sampling/con.py +287 -0
  30. max_div-0.2.5/max_div/sampling/uncon.py +270 -0
  31. max_div-0.2.5/max_div/solver/__init__.py +6 -0
  32. max_div-0.2.5/max_div/solver/_constraints.py +68 -0
  33. max_div-0.2.5/max_div/solver/_distance/__init__.py +2 -0
  34. max_div-0.2.5/max_div/solver/_distance/_compute.py +97 -0
  35. max_div-0.2.5/max_div/solver/_distance/_enum.py +20 -0
  36. max_div-0.2.5/max_div/solver/_diversity/__init__.py +1 -0
  37. max_div-0.2.5/max_div/solver/_diversity/_base.py +57 -0
  38. max_div-0.2.5/max_div/solver/_diversity/_numba.py +44 -0
  39. max_div-0.2.5/max_div/solver/_duration.py +225 -0
  40. max_div-0.2.5/max_div/solver/_score.py +6 -0
  41. max_div-0.2.5/max_div/solver/_solution.py +9 -0
  42. max_div-0.2.5/max_div/solver/_solver.py +93 -0
  43. max_div-0.2.5/max_div/solver/_solver_builder.py +106 -0
  44. max_div-0.2.5/max_div/solver/_solver_state.py +322 -0
  45. max_div-0.2.5/max_div/solver/_solver_step.py +157 -0
  46. max_div-0.2.5/max_div/solver/_strategies/__init__.py +2 -0
  47. max_div-0.2.5/max_div/solver/_strategies/_initialization/__init__.py +1 -0
  48. max_div-0.2.5/max_div/solver/_strategies/_initialization/_base.py +46 -0
  49. max_div-0.2.5/max_div/solver/_strategies/_initialization/_init_random.py +8 -0
  50. max_div-0.2.5/max_div/solver/_strategies/_optimization/__init__.py +1 -0
  51. max_div-0.2.5/max_div/solver/_strategies/_optimization/_base.py +50 -0
  52. max_div-0.2.5/max_div/solver/_strategies/_optimization/_optim_dummy.py +8 -0
  53. max_div-0.2.5/pyproject.toml +82 -0
@@ -0,0 +1,36 @@
1
+ # build files
2
+ dist
3
+ *.tar.gz
4
+ *.whl
5
+
6
+ # no need to track uv.lock for a Python package (where deps are not pinned)
7
+ uv.lock
8
+
9
+ # Python cache files
10
+ __pycache__
11
+ *.pyc
12
+
13
+ # various auto-generated 'reports' (coverage, mkdocs)
14
+ /reports
15
+
16
+ # Jupyter Notebook checkpoints
17
+ .ipynb_checkpoints
18
+
19
+ # Virtual environment directories
20
+ venv
21
+ .env
22
+
23
+ # Pytest cache
24
+ .cache
25
+
26
+ # OS thumbnail files
27
+ .DS_Store
28
+ Thumbs.db
29
+
30
+ # IDE files
31
+ .idea
32
+ .vscode
33
+
34
+ # other
35
+ .local
36
+ AGENTS.md
max_div-0.2.5/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
max_div-0.2.5/PKG-INFO ADDED
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: max-div
3
+ Version: 0.2.5
4
+ Summary: Configurable Solver for Maximum Diversity Problems with Fairness Constraints.
5
+ Project-URL: Documentation, https://max-div.readthedocs.io/
6
+ Project-URL: Source, https://github.com/bertpl/max-div
7
+ Project-URL: ChangeLog, https://github.com/bertpl/max-div/blob/main/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/bertpl/max-div/issues
9
+ Project-URL: Roadmap, https://github.com/bertpl/max-div/milestones
10
+ Author-email: Bert Pluymers <bert.pluymers@gmail.com>
11
+ License-File: LICENSE
12
+ Requires-Python: >=3.11
13
+ Requires-Dist: click>=8.2.0
14
+ Requires-Dist: icc-rt; platform_machine == 'x86_64' and platform_system == 'Linux'
15
+ Requires-Dist: intel-cmplr-lib-rt; platform_machine == 'x86_64' and platform_system == 'Linux'
16
+ Requires-Dist: numba>=0.57
17
+ Requires-Dist: numpy>=2.0.0
18
+ Requires-Dist: scipy>=1.10.0
19
+ Requires-Dist: sortedcontainers>=2.4.0
20
+ Requires-Dist: tqdm>=4.66.0
21
+ Provides-Extra: docs
22
+ Requires-Dist: mkdocs-autoapi[python]>=0.4.1; extra == 'docs'
23
+ Requires-Dist: mkdocs-include-markdown-plugin>=7.2.0; extra == 'docs'
24
+ Requires-Dist: mkdocs-material>=9.0.0; extra == 'docs'
25
+ Requires-Dist: mkdocs>=1.6.1; extra == 'docs'
26
+ Requires-Dist: mkdocstrings[python]>=0.24.0; extra == 'docs'
27
+ Requires-Dist: ruff>=0.14.0; extra == 'docs'
28
+ Description-Content-Type: text/markdown
29
+
30
+ ![shields.io-python-versions](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13-blue)
31
+ ![genbadge-test-count](https://bertpl.github.io/max-div/version_artifacts/release/v0.2.5/badge-test-count.svg)
32
+ ![genbadge-test-coverage](https://bertpl.github.io/max-div/version_artifacts/release/v0.2.5/badge-coverage.svg)
33
+ [![docs-build-status](https://app.readthedocs.org/projects/max-div/badge/?version=latest)](https://max-div.readthedocs.io/en/stable)
34
+ [![License](https://img.shields.io/github/license/bertpl/max-div)](https://github.com/bertpl/max-div/blob/main/LICENSE)
35
+ <p>
36
+ <img src="https://bertpl.github.io/max-div/version_artifacts/release/v0.2.5/splash.webp" alt="max-div logo" style="max-width: max(60%, min(100%,800px)); height: auto;">
37
+ </p>
38
+
39
+ # max-div
40
+ Configurable Solver for Maximum Diversity Problems with Fairness Constraints.
41
+
42
+ ### --- ***Under Development*** ---
@@ -0,0 +1,13 @@
1
+ ![shields.io-python-versions](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13-blue)
2
+ ![genbadge-test-count](https://bertpl.github.io/max-div/version_artifacts/release/v0.2.5/badge-test-count.svg)
3
+ ![genbadge-test-coverage](https://bertpl.github.io/max-div/version_artifacts/release/v0.2.5/badge-coverage.svg)
4
+ [![docs-build-status](https://app.readthedocs.org/projects/max-div/badge/?version=latest)](https://max-div.readthedocs.io/en/stable)
5
+ [![License](https://img.shields.io/github/license/bertpl/max-div)](https://github.com/bertpl/max-div/blob/main/LICENSE)
6
+ <p>
7
+ <img src="https://bertpl.github.io/max-div/version_artifacts/release/v0.2.5/splash.webp" alt="max-div logo" style="max-width: max(60%, min(100%,800px)); height: auto;">
8
+ </p>
9
+
10
+ # max-div
11
+ Configurable Solver for Maximum Diversity Problems with Fairness Constraints.
12
+
13
+ ### --- ***Under Development*** ---
File without changes
@@ -0,0 +1,109 @@
1
+ """Command-line interface for max-div."""
2
+
3
+ import click
4
+
5
+ from max_div.benchmark import benchmark_diversity_metrics as _benchmark_diversity_metrics
6
+ from max_div.benchmark import benchmark_randint as _benchmark_randint
7
+ from max_div.benchmark import benchmark_randint_constrained as _benchmark_randint_constrained
8
+
9
+
10
+ # -------------------------------------------------------------------------
11
+ # Main CLI Group
12
+ # -------------------------------------------------------------------------
13
+ @click.group()
14
+ def cli():
15
+ """max-div: Flexible Solver for Maximum Diversity Problems with Fairness Constraints."""
16
+ pass
17
+
18
+
19
+ # -------------------------------------------------------------------------
20
+ # Benchmarking Commands
21
+ # -------------------------------------------------------------------------
22
+ @cli.group()
23
+ @click.option(
24
+ "--turbo",
25
+ is_flag=True,
26
+ default=False,
27
+ help="Run shorter, less accurate benchmark; identical to --speed=1.0; intended for testing purposes.",
28
+ )
29
+ @click.option(
30
+ "--speed",
31
+ default=0.0,
32
+ help="Values closer to 1.0 result in shorter, less accurate benchmark; Overridden by --turbo when provided.",
33
+ )
34
+ @click.option(
35
+ "--markdown",
36
+ is_flag=True,
37
+ default=False,
38
+ help="Output benchmark results in Markdown table format.",
39
+ )
40
+ @click.pass_context
41
+ def benchmark(ctx, turbo: bool, speed: float, markdown: bool):
42
+ """Benchmarking commands."""
43
+ # Store flags in context so subcommands can access them
44
+ ctx.ensure_object(dict)
45
+ if turbo:
46
+ ctx.obj["speed"] = 1.0
47
+ else:
48
+ ctx.obj["speed"] = speed
49
+ ctx.obj["markdown"] = markdown
50
+
51
+
52
+ @benchmark.command(name="randint")
53
+ @click.pass_context
54
+ def randint(ctx):
55
+ """Benchmarks the `randint` function from `max_div.sampling.uncon`."""
56
+ speed = ctx.obj["speed"]
57
+ markdown = ctx.obj["markdown"]
58
+ _benchmark_randint(speed=speed, markdown=markdown)
59
+
60
+
61
+ @benchmark.command(name="randint_constrained")
62
+ @click.pass_context
63
+ def randint_constrained(ctx):
64
+ """Benchmarks the `randint_constrained` function from `max_div.sampling.con`."""
65
+ speed = ctx.obj["speed"]
66
+ markdown = ctx.obj["markdown"]
67
+ _benchmark_randint_constrained(speed=speed, markdown=markdown)
68
+
69
+
70
+ @benchmark.command(name="diversity_metrics")
71
+ @click.pass_context
72
+ def diversity_metrics(ctx):
73
+ """Benchmarks computation of DiversityMetrics."""
74
+ speed = ctx.obj["speed"]
75
+ markdown = ctx.obj["markdown"]
76
+ _benchmark_diversity_metrics(speed=speed, markdown=markdown)
77
+
78
+
79
+ # -------------------------------------------------------------------------
80
+ # Misc Commands
81
+ # -------------------------------------------------------------------------
82
+ @cli.command()
83
+ def numba_status():
84
+ """Show Numba version, llvmlite version, and configuration including SVML status."""
85
+ import llvmlite
86
+ import numba
87
+
88
+ click.echo(f"Numba version : {numba.__version__}")
89
+ click.echo(f"llvmlite version : {llvmlite.__version__}")
90
+
91
+ # Show key configuration settings
92
+ from numba import config
93
+
94
+ click.echo("\nNumba Configuration:")
95
+ click.echo("-" * 50)
96
+ click.echo(f"SVML enabled : {config.USING_SVML}")
97
+ click.echo(f"Threading layer : {config.THREADING_LAYER}")
98
+ click.echo(f"Number of threads : {config.NUMBA_NUM_THREADS}")
99
+ click.echo(f"Optimization level : {config.OPT}")
100
+ click.echo(f"Debug mode : {config.DEBUG}")
101
+ click.echo(f"Disable JIT : {config.DISABLE_JIT}")
102
+ click.echo("-" * 50)
103
+
104
+
105
+ # -------------------------------------------------------------------------
106
+ # Entrypoint
107
+ # -------------------------------------------------------------------------
108
+ if __name__ == "__main__":
109
+ cli()
@@ -0,0 +1,3 @@
1
+ from .diversity_metrics import benchmark_diversity_metrics
2
+ from .randint import benchmark_randint
3
+ from .randint_constrained import benchmark_randint_constrained
@@ -0,0 +1,218 @@
1
+ from abc import ABC, abstractmethod
2
+ from dataclasses import dataclass
3
+ from typing import Literal
4
+
5
+ from max_div.internal.benchmarking import BenchmarkResult
6
+ from max_div.internal.formatting import md_bold, md_colored, md_table
7
+
8
+
9
+ # =================================================================================================
10
+ # Helper classes / types
11
+ # =================================================================================================
12
+ @dataclass
13
+ class Percentage:
14
+ frac: float # fraction between 0.0 and 1.0
15
+ decimals: int = 1 # number of decimals to display
16
+
17
+ def __str__(self):
18
+ return f"{(self.frac * 100):.{self.decimals}f}%"
19
+
20
+
21
+ CellContent = str | BenchmarkResult | Percentage
22
+
23
+
24
+ # =================================================================================================
25
+ # Aggregation
26
+ # =================================================================================================
27
+ def extend_table_with_aggregate_row(
28
+ data: list[list[CellContent]],
29
+ agg: Literal["mean", "geomean", "sum"],
30
+ include_benchmark_result: bool = True,
31
+ include_percentage: bool = True,
32
+ ) -> list[list[CellContent]]:
33
+ """
34
+ This function adds aggregate statistics for BenchmarkResult | Percentage (=Aggregatable) columns to the data table.
35
+
36
+ Extend an extra row to the provided data that contains aggregate statistics of the provided data:
37
+ - for each column that has at least 1 row containing a Aggregatable object, compute an aggregate
38
+ - all other columns are kept empty
39
+
40
+ The last column not containing any Aggregatable objects that comes before the first column containing
41
+ Aggregatable objects is used as label for the aggregate row, based on the 'agg' argument, capitalized.
42
+
43
+ BenchmarkResults are aggregated by aggregation the q25, q50, and q75 times separately.
44
+ Percentage objects are aggregated with decimals equal to max of what we observed in that col.
45
+ """
46
+ n_cols = len(data[0])
47
+
48
+ Aggregatable = BenchmarkResult | Percentage
49
+
50
+ # Identify which columns contain Aggregatable objects
51
+ has_aggregatable = [False] * n_cols
52
+ for row in data:
53
+ for col_idx, cell in enumerate(row):
54
+ if isinstance(cell, Aggregatable):
55
+ has_aggregatable[col_idx] = True
56
+
57
+ # Find the first column with Aggregatable objects
58
+ first_aggregatable_col = None
59
+ for col_idx, has_result in enumerate(has_aggregatable):
60
+ if has_result:
61
+ first_aggregatable_col = col_idx
62
+ break
63
+
64
+ # Find the last non-Aggregatable column before the first Aggregatable column
65
+ label_col = None
66
+ for col_idx in range(first_aggregatable_col - 1, -1, -1):
67
+ if not has_aggregatable[col_idx]:
68
+ label_col = col_idx
69
+ break
70
+
71
+ # Create the aggregate row
72
+ agg_row: list[CellContent] = [""] * n_cols
73
+
74
+ # Set the label if we found a label column
75
+ if label_col is not None:
76
+ agg_row[label_col] = agg.capitalize() + ":"
77
+
78
+ # Compute aggregates for each column with BenchmarkResult objects
79
+ for col_idx in range(n_cols):
80
+ if include_benchmark_result:
81
+ # Collect all BenchmarkResult values from this column
82
+ results = [row[col_idx] for row in data if isinstance(row[col_idx], BenchmarkResult)]
83
+ if results: # Only compute if we have values
84
+ agg_row[col_idx] = BenchmarkResult.aggregate(results, method=agg)
85
+
86
+ if include_percentage:
87
+ # Collect all Percentage values from this column
88
+ percentages = [row[col_idx] for row in data if isinstance(row[col_idx], Percentage)]
89
+ if percentages: # Only compute if we have values
90
+ # Compute average fraction and max decimals
91
+ avg_frac = sum(p.frac for p in percentages) / len(percentages)
92
+ max_decimals = max(p.decimals for p in percentages)
93
+ agg_row[col_idx] = Percentage(frac=avg_frac, decimals=max_decimals + 1)
94
+
95
+ # Return data with the aggregate row appended
96
+ return data + [agg_row]
97
+
98
+
99
+ # =================================================================================================
100
+ # Markdown highlighters
101
+ # =================================================================================================
102
+ class HighLighter(ABC):
103
+ @abstractmethod
104
+ def process_row(self, row: list[CellContent]) -> list[CellContent]:
105
+ raise NotImplementedError()
106
+
107
+
108
+ class FastestBenchmark(HighLighter):
109
+ def __init__(self, bold: bool = True, color: str = "#00aa00"):
110
+ self.bold = bold
111
+ self.color = color
112
+
113
+ def process_row(self, row: list[CellContent]) -> list[CellContent]:
114
+ if any(isinstance(value, BenchmarkResult) for value in row):
115
+ # Find the fastest BenchmarkResult (minimum median time)
116
+ t_q50_min = min([value.t_sec_q_50 for value in row if isinstance(value, BenchmarkResult)])
117
+
118
+ # Convert row to strings, highlighting the results with t_q25 <= t_q50_min
119
+ converted_row: list[CellContent] = []
120
+ for i, value in enumerate(row):
121
+ if isinstance(value, BenchmarkResult):
122
+ text = str(value)
123
+ if value.t_sec_q_25 <= t_q50_min:
124
+ if self.bold:
125
+ text = md_bold(text)
126
+ text = md_colored(text, self.color)
127
+ converted_row.append(text)
128
+ else:
129
+ converted_row.append(value)
130
+ return converted_row
131
+ else:
132
+ return row
133
+
134
+
135
+ class HighestPercentage(HighLighter):
136
+ def __init__(self, bold: bool = True, color: str = "#00aa00"):
137
+ self.bold = bold
138
+ self.color = color
139
+
140
+ def process_row(self, row: list[CellContent]) -> list[CellContent]:
141
+ if any(isinstance(value, Percentage) for value in row):
142
+ # Find the highest Percentage (maximum frac)
143
+ max_perc = max([value for value in row if isinstance(value, Percentage)], key=lambda x: x.frac)
144
+
145
+ # Convert row to strings, highlighting the results with frac == max_frac
146
+ converted_row: list[CellContent] = []
147
+ for i, value in enumerate(row):
148
+ if isinstance(value, Percentage):
149
+ text = str(value)
150
+ if text == str(max_perc): # make green if its str-representation is equal
151
+ if self.bold:
152
+ text = md_bold(text)
153
+ text = md_colored(text, self.color)
154
+ converted_row.append(text)
155
+ else:
156
+ converted_row.append(value)
157
+ return converted_row
158
+ else:
159
+ return row
160
+
161
+
162
+ class BoldLabels(HighLighter):
163
+ def process_row(self, row: list[CellContent]) -> list[CellContent]:
164
+ converted_row: list[CellContent] = []
165
+ for value in row:
166
+ if isinstance(value, str) and value.endswith(":"):
167
+ converted_row.append(md_bold(value))
168
+ else:
169
+ converted_row.append(value)
170
+ return converted_row
171
+
172
+
173
+ # =================================================================================================
174
+ # Formatting
175
+ # =================================================================================================
176
+ def format_as_markdown(
177
+ headers: list[str], data: list[list[CellContent]], highlighters: list[HighLighter] | None = None
178
+ ) -> list[str]:
179
+ """
180
+ Format benchmark data as a Markdown table.
181
+
182
+ Converts BenchmarkResult objects to strings using t_sec_with_uncertainty_str.
183
+ The fastest BenchmarkResult in each row is highlighted in bold and green.
184
+
185
+ :param headers: List of column headers
186
+ :param data: 2D list where each row contains strings and/or BenchmarkResult objects
187
+ :param highlighters: Optional list of HighLighter objects to apply to each row
188
+ :return: List of strings representing the Markdown table lines
189
+ """
190
+ # Convert data to string format and identify the fastest results
191
+ converted_data: list[list[str]] = [headers]
192
+
193
+ for row in data:
194
+ # highlight if requested
195
+ for highlighter in highlighters or []:
196
+ row = highlighter.process_row(row)
197
+
198
+ # convert to str
199
+ row = [str(cell) for cell in row]
200
+
201
+ # append to converted data
202
+ converted_data.append(row)
203
+
204
+ return md_table(converted_data)
205
+
206
+
207
+ def format_for_console(headers: list[str], data: list[list[CellContent]]) -> list[str]:
208
+ """Similar to `format_as_markdown`, but without extensive formatting, to keep it readable with rendering."""
209
+ table_data = [headers]
210
+ for row in data:
211
+ converted_row: list[str] = []
212
+ for cell in row:
213
+ if isinstance(cell, BenchmarkResult):
214
+ converted_row.append(cell.t_sec_with_uncertainty_str)
215
+ else:
216
+ converted_row.append(str(cell))
217
+ table_data.append(converted_row)
218
+ return md_table(table_data)