lex1dx 0.1.1__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 (56) hide show
  1. lex1dx-0.1.1/.gitignore +29 -0
  2. lex1dx-0.1.1/CMakeLists.txt +60 -0
  3. lex1dx-0.1.1/LICENSE +21 -0
  4. lex1dx-0.1.1/NOTICE +13 -0
  5. lex1dx-0.1.1/PKG-INFO +344 -0
  6. lex1dx-0.1.1/README.md +216 -0
  7. lex1dx-0.1.1/cpp/cmake/LexFloatingPoint.cmake +25 -0
  8. lex1dx-0.1.1/cpp/include/lex/lex.hpp +109 -0
  9. lex1dx-0.1.1/cpp/include/lex1dx/lex1dx.hpp +84 -0
  10. lex1dx-0.1.1/cpp/src/atoms.cpp +135 -0
  11. lex1dx-0.1.1/cpp/src/collapse.cpp +124 -0
  12. lex1dx-0.1.1/cpp/src/detail.hpp +112 -0
  13. lex1dx-0.1.1/cpp/src/exact.cpp +153 -0
  14. lex1dx-0.1.1/cpp/src/lex.cpp +308 -0
  15. lex1dx-0.1.1/cpp/src/lex1dx.cpp +330 -0
  16. lex1dx-0.1.1/cpp/src/refine.cpp +194 -0
  17. lex1dx-0.1.1/cpp/src/siggroup.hpp +139 -0
  18. lex1dx-0.1.1/cpp/src/sort.cpp +41 -0
  19. lex1dx-0.1.1/cpp/src/tuned_collapse.hpp +152 -0
  20. lex1dx-0.1.1/cpp/tests/support.hpp +140 -0
  21. lex1dx-0.1.1/cpp/tests/test_agree.cpp +120 -0
  22. lex1dx-0.1.1/cpp/tests/test_edge.cpp +178 -0
  23. lex1dx-0.1.1/cpp/tests/test_quality.cpp +171 -0
  24. lex1dx-0.1.1/cpp/tools/lex1dx_dump.cpp +48 -0
  25. lex1dx-0.1.1/data/README.md +17 -0
  26. lex1dx-0.1.1/data/athletics20.csv +21 -0
  27. lex1dx-0.1.1/data/worldathletics-mens-100m-2379.csv +2380 -0
  28. lex1dx-0.1.1/docs/examples_output.md +327 -0
  29. lex1dx-0.1.1/docs/examples_output_r.md +284 -0
  30. lex1dx-0.1.1/docs/img/histogram_athletics20_k5.png +0 -0
  31. lex1dx-0.1.1/docs/img/histogram_athletics20_k5_r.png +0 -0
  32. lex1dx-0.1.1/docs/img/histogram_lognormal_k32.png +0 -0
  33. lex1dx-0.1.1/examples/cluster_athletics.py +217 -0
  34. lex1dx-0.1.1/pyproject.toml +63 -0
  35. lex1dx-0.1.1/python/CMakeLists.txt +24 -0
  36. lex1dx-0.1.1/python/LICENSE +21 -0
  37. lex1dx-0.1.1/python/README.md +321 -0
  38. lex1dx-0.1.1/python/pyproject.toml +31 -0
  39. lex1dx-0.1.1/python/src/_core.cpp +80 -0
  40. lex1dx-0.1.1/python/src/lex1dx/__init__.py +119 -0
  41. lex1dx-0.1.1/python/src/lex1dx/data/README.md +17 -0
  42. lex1dx-0.1.1/python/src/lex1dx/data/athletics20.csv +21 -0
  43. lex1dx-0.1.1/python/src/lex1dx/data/worldathletics-mens-100m-2379.csv +2380 -0
  44. lex1dx-0.1.1/python/src/lex1dx/datasets.py +49 -0
  45. lex1dx-0.1.1/python/src/lex1dx/histogram.py +203 -0
  46. lex1dx-0.1.1/python/tests/data/builtin_cpp.txt +42 -0
  47. lex1dx-0.1.1/python/tests/data/builtin_x_bits.txt +800 -0
  48. lex1dx-0.1.1/python/tests/test_cluster.py +210 -0
  49. lex1dx-0.1.1/python/tests/test_datasets.py +44 -0
  50. lex1dx-0.1.1/python/tests/test_histogram.py +49 -0
  51. lex1dx-0.1.1/third_party/kmeans1d/LICENSE +21 -0
  52. lex1dx-0.1.1/third_party/kmeans1d/ORIGIN +24 -0
  53. lex1dx-0.1.1/third_party/kmeans1d/interval_sum.cpp +104 -0
  54. lex1dx-0.1.1/third_party/kmeans1d/interval_sum.hpp +26 -0
  55. lex1dx-0.1.1/third_party/kmeans1d/kmeans.h +189 -0
  56. lex1dx-0.1.1/third_party/kmeans1d/kmeans_wilber.cpp +335 -0
@@ -0,0 +1,29 @@
1
+ /build/
2
+ /cpp/build/
3
+ /scala/target/
4
+ /scala/project/target/
5
+ /scala/project/project/
6
+ /.bsp/
7
+ /.metals/
8
+ /.bloop/
9
+ /.idea/
10
+ *.class
11
+ *.log
12
+ /data/synth/*.f64
13
+ /agree_cpp.txt
14
+ /agree_scala.txt
15
+ CMakeFiles/
16
+ CMakeCache.txt
17
+ /python/build/
18
+ /python/dist/
19
+ /python/**/__pycache__/
20
+ /python/**/*.egg-info/
21
+ .pytest_cache/
22
+ /r/src/*.o
23
+ /r/src/*.so
24
+ /r/src/*.dll
25
+ /r/src/symbols.rds
26
+ /r/*.Rcheck/
27
+ /r/*.tar.gz
28
+ /build-san/
29
+ /dist-sdist/
@@ -0,0 +1,60 @@
1
+ cmake_minimum_required(VERSION 3.21)
2
+ project(lex1dx VERSION 0.1.1 LANGUAGES CXX)
3
+
4
+ set(CMAKE_CXX_STANDARD 17)
5
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
6
+ set(CMAKE_CXX_EXTENSIONS OFF)
7
+ if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
8
+ set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
9
+ endif()
10
+
11
+ include(${CMAKE_CURRENT_LIST_DIR}/cpp/cmake/LexFloatingPoint.cmake)
12
+
13
+ option(LEX1DX_BUILD_TESTS "Build the tests" ${PROJECT_IS_TOP_LEVEL})
14
+ option(LEX1DX_BUILD_CLI "Build the lex1dx_dump tool" ${PROJECT_IS_TOP_LEVEL})
15
+
16
+ add_library(lex1dx
17
+ cpp/src/atoms.cpp
18
+ cpp/src/collapse.cpp
19
+ cpp/src/refine.cpp
20
+ cpp/src/exact.cpp
21
+ cpp/src/sort.cpp
22
+ cpp/src/lex.cpp
23
+ cpp/src/lex1dx.cpp
24
+ third_party/kmeans1d/interval_sum.cpp
25
+ third_party/kmeans1d/kmeans_wilber.cpp
26
+ )
27
+ add_library(lex1dx::lex1dx ALIAS lex1dx)
28
+ set_target_properties(lex1dx PROPERTIES POSITION_INDEPENDENT_CODE ON)
29
+ target_include_directories(lex1dx
30
+ PUBLIC
31
+ $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/cpp/include>
32
+ $<INSTALL_INTERFACE:include>
33
+ PRIVATE
34
+ ${PROJECT_SOURCE_DIR}/cpp/src
35
+ ${PROJECT_SOURCE_DIR}/third_party/kmeans1d
36
+ )
37
+ lex_strict_fp(lex1dx)
38
+ if(MSVC)
39
+ target_compile_options(lex1dx PRIVATE /W4)
40
+ elseif(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
41
+ target_compile_options(lex1dx PRIVATE -Wall -Wextra -Wpedantic)
42
+ endif()
43
+
44
+ if(LEX1DX_BUILD_CLI)
45
+ add_executable(lex1dx_dump cpp/tools/lex1dx_dump.cpp)
46
+ target_link_libraries(lex1dx_dump PRIVATE lex1dx)
47
+ lex_strict_fp(lex1dx_dump)
48
+ endif()
49
+
50
+ if(LEX1DX_BUILD_TESTS)
51
+ enable_testing()
52
+ foreach(t edge quality agree)
53
+ add_executable(test_${t} cpp/tests/test_${t}.cpp)
54
+ target_link_libraries(test_${t} PRIVATE lex1dx)
55
+ target_include_directories(test_${t} PRIVATE ${PROJECT_SOURCE_DIR}/cpp/src ${PROJECT_SOURCE_DIR}/cpp/include)
56
+ lex_strict_fp(test_${t})
57
+ add_test(NAME ${t} COMMAND test_${t})
58
+ endforeach()
59
+ # exact.cpp is part of the library; quality/edge tests may also call lex::ckmeans_exact
60
+ endif()
lex1dx-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sriram Natarajan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
lex1dx-0.1.1/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ lex1dx
2
+ Copyright (c) 2026 Sriram Natarajan
3
+
4
+ This project includes code derived from kmeans1d by Allan Grønlund,
5
+ https://github.com/gronlund/kmeans1d, commit
6
+ 585386d4678000691706acdb954911be8fea1c5c, MIT License
7
+ (Copyright (c) 2020 Allan Grønlund). The wilber-interp dynamic program
8
+ in third_party/kmeans1d/ (and the Scala port in
9
+ scala/src/main/scala/lex1dx/Wilber.scala) comes from that work, with a
10
+ weighted interval-cost patch described in third_party/kmeans1d/ORIGIN
11
+ and LICENSE.
12
+
13
+ The full MIT license text for kmeans1d is in third_party/kmeans1d/LICENSE.
lex1dx-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,344 @@
1
+ Metadata-Version: 2.4
2
+ Name: lex1dx
3
+ Version: 0.1.1
4
+ Summary: Fast 1-D k-means with a 0.01% relative-excess-SSE tolerance
5
+ Author: N. Sriram
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ License-File: NOTICE
9
+ License-File: third_party/kmeans1d/LICENSE
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: C++
12
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
13
+ Project-URL: Homepage, https://github.com/nsram/lex1dx
14
+ Project-URL: Source, https://github.com/nsram/lex1dx
15
+ Project-URL: Issues, https://github.com/nsram/lex1dx/issues
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: numpy>=1.21
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest>=7; extra == "test"
20
+ Provides-Extra: plot
21
+ Requires-Dist: matplotlib; extra == "plot"
22
+ Description-Content-Type: text/markdown
23
+
24
+ # lex1dx
25
+
26
+ lex1dx partitions a one-dimensional array into k contiguous bins of the sorted values.
27
+
28
+ It targets a 0.01% relative-excess-SSE (REE) tolerance.
29
+
30
+ The C++17 core is also used by the [R](https://github.com/nsram/lex1dx/tree/main/r) and [Scala](https://github.com/nsram/lex1dx/tree/main/scala) bindings.
31
+
32
+ The source repository is [github.com/nsram/lex1dx](https://github.com/nsram/lex1dx).
33
+
34
+ ## Install
35
+
36
+ From PyPI:
37
+
38
+ ```sh
39
+ pip install lex1dx
40
+ pip install lex1dx[plot] # optional, for histogram()
41
+ ```
42
+
43
+ From a repository checkout, at the repository root:
44
+
45
+ ```sh
46
+ pip install .
47
+ pip install pytest
48
+ pytest
49
+ ```
50
+
51
+ ## Quick start
52
+
53
+ `athletics20` is 20 men's 100 m times, in seconds, with 12 distinct values.
54
+
55
+ ```python
56
+ import numpy as np
57
+ import lex1dx
58
+
59
+ x = lex1dx.datasets.load("athletics20")
60
+ r = lex1dx.cluster(x, 4)
61
+ print(list(r.bounds))
62
+ print(r.sse)
63
+ print(list(r.assign([9.58, 9.76, 9.84, 10.0])))
64
+ ```
65
+
66
+ That call uses the default tuned pipeline.
67
+
68
+ The result has bounds `[0, 1, 4, 11, 20]`.
69
+
70
+ The bin sizes are `[1, 3, 7, 9]`.
71
+
72
+ The centers are approximately `[9.580000, 9.700000, 9.765714, 9.824444]`.
73
+
74
+ The SSE is `0.00399365079365`.
75
+
76
+ `assign` maps `9.58`, `9.76`, `9.84`, and `10.0` to bins `[0, 2, 3, 3]`.
77
+
78
+ `D` is 12 and `Dprime` is 12.
79
+
80
+ `sig` is 0, which means full precision.
81
+
82
+ `presorted` is true because the file is already sorted.
83
+
84
+ On this data the default result matches `mode="exact"` with either solver, so the REE versus exact is 0.
85
+
86
+ ## cluster arguments
87
+
88
+ ```python
89
+ lex1dx.cluster(x, k, *, mode="tuned", sig=None, M=None, tolerance=1e-11,
90
+ weights=None, solver="wilber")
91
+ ```
92
+
93
+ `x` is a one-dimensional finite numeric array.
94
+
95
+ `k` is the requested number of bins.
96
+
97
+ If `k` is larger than the number of atoms, it is clamped to that number.
98
+
99
+ On `athletics20`, `cluster(x, 20)` returns `k=12` and SSE 0.
100
+
101
+ ### mode
102
+
103
+ `mode="tuned"` is the default pipeline.
104
+
105
+ It sorts, optionally groups, collapses to `M` groups, runs a DP, and refines the cuts.
106
+
107
+ `mode="sig5"` is an alias for `sig=5`.
108
+
109
+ `mode="exact"` skips Collapse.
110
+
111
+ The chosen solver then runs on the atoms, after optional grouping.
112
+
113
+ On `athletics20` with `k=4`, both `solver="wilber"` and `solver="ckmeans"` under `mode="exact"` give the same bounds and the same SSE `0.00399365079365`.
114
+
115
+ ### sig
116
+
117
+ `sig` is an integer in 0..9.
118
+
119
+ 0 means full precision (no grouping).
120
+
121
+ 1..9 groups values to that many significant digits.
122
+
123
+ `sig=None` follows `mode`: 5 when `mode="sig5"`, otherwise 0.
124
+
125
+ Values of 10 or more are rejected.
126
+
127
+ Use `sig=0` for full precision.
128
+
129
+ If grouping at the requested `sig` yields fewer than `k` groups, and the raw data has at least `k` distinct values, precision is raised one digit at a time (up to 15, then raw distinct-value atoms) so `k` is kept.
130
+
131
+ This is the same k-preserving fallback as v0.1.0.
132
+
133
+ `Result.sig` is the sig actually used.
134
+
135
+ It is 0 if the fallback reached raw atoms.
136
+
137
+ `Result.Dprime` is the number of groups after that grouping.
138
+
139
+ A constructed example makes the fallback visible.
140
+
141
+ Four tight groups around 0, 1.000012, 1.000017, and 2 would give only three groups at 5 digits.
142
+
143
+ With `sig=5` and `k=4`, the fallback raises precision to 6.
144
+
145
+ The result has `k=4`, `Dprime=4`, and `sig=6`.
146
+
147
+ The bounds are `[0, 50, 100, 150, 200]`.
148
+
149
+ ### M and default_M
150
+
151
+ `M=None` uses `default_M(k) = max(4096, 32 * k)`.
152
+
153
+ `default_M(4)` and `default_M(64)` are 4096.
154
+
155
+ `default_M(256)` is 8192.
156
+
157
+ `M` is ignored when `mode="exact"`.
158
+
159
+ On `athletics20` the default `M` is larger than the 12 distinct times, so Collapse does not reduce the atoms.
160
+
161
+ On the 2,379-row list, `k=8` with default `M` matches exact (SSE `0.709129743721`, REE 0).
162
+
163
+ With `M=8`, the SSE is `0.718184561908` and the REE versus exact is `1.27689%`.
164
+
165
+ With `M=32`, the REE is `0.0820787%`.
166
+
167
+ ### tolerance
168
+
169
+ `tolerance` is the Refine move threshold.
170
+
171
+ The default is `1e-11`.
172
+
173
+ A move is applied only if it lowers SSE by more than this tolerance times the size of its terms.
174
+
175
+ ### weights
176
+
177
+ `weights` is an optional non-negative finite vector of the same length as `x`.
178
+
179
+ `None` is the unweighted solver.
180
+
181
+ The result SSE and centers are then weighted.
182
+
183
+ `sizes` remain element counts.
184
+
185
+ Equal times already act as integer counts.
186
+
187
+ Clustering the 12 distinct `athletics20` times with counts `[1, 2, 1, 1, 3, 1, 1, 1, 2, 1, 4, 2]` as weights matches clustering the expanded 20 values.
188
+
189
+ The centers, SSE, and per-bin weight mass agree at `k=4`.
190
+
191
+ A different weighting changes the partition.
192
+
193
+ Clustering those 12 distinct times with no weights (each time has weight 1) gives bounds `[0, 1, 4, 9, 12]` and SSE `0.00246666666667`.
194
+
195
+ Negative, non-finite, zero-total, or wrong-length weights are rejected.
196
+
197
+ ### solver
198
+
199
+ `solver="wilber"` is the default.
200
+
201
+ It is the modified Grønlund kmeans1d wilber-interp DP.
202
+
203
+ `solver="ckmeans"` is the Fisher / ckmeans exact DP.
204
+
205
+ Both solvers are exact and give the same optimum.
206
+
207
+ Wilber is faster as k grows, because wilber-interp is O(k N) in style while ckmeans is a divide-and-conquer O(k N log N) DP.
208
+
209
+ ckmeans is the original LEX exact DP and serves as a cross-check.
210
+
211
+ On `athletics20` with `k=4` and `mode="exact"`, both solvers agree on SSE.
212
+
213
+ ## Result and assign
214
+
215
+ The result has `bounds`, `sizes`, `centers`, `upper`, `sse`, `D`, `Dprime`, `sig`, `sweeps`, `moves`, and `presorted`.
216
+
217
+ `bounds` are `k + 1` cut indices into the sorted data.
218
+
219
+ Bin `i` holds sorted values from `bounds[i]` to `bounds[i+1]`.
220
+
221
+ `sizes` are element counts per bin.
222
+
223
+ `centers` are bin means (weighted means if weights were given).
224
+
225
+ `upper` is the largest raw value in each bin.
226
+
227
+ `sse` is the (weighted) sum of squared deviations from the bin means.
228
+
229
+ `r.k` is `min(requested k, atoms)`.
230
+
231
+ `r.assign(x)` returns the bin index for each value.
232
+
233
+ It chooses the first bin whose upper value is at least `x`, or the last bin if none is.
234
+
235
+ ## Order independence
236
+
237
+ `athletics20` is already sorted, so `presorted` is true.
238
+
239
+ A shuffled copy gives the same bounds and the same SSE.
240
+
241
+ On the shuffled copy, `presorted` is false.
242
+
243
+
244
+ ## Histogram
245
+
246
+ `histogram()` draws the fitted bins as a horizontal table, one row per bin, from the lowest bin at the top.
247
+
248
+ Each row shows the bin's minimum and maximum (5 significant digits), a bar proportional to the count, and `[n, pct%, mean]`.
249
+
250
+ The header reports r² = 1 - SSE/SST and MSE = SSE/N.
251
+
252
+ ```python
253
+ x = lex1dx.datasets.load("athletics20")
254
+ r = lex1dx.cluster(x, 5)
255
+ lex1dx.bin_table(r, x)
256
+ lex1dx.histogram(r, x, file="lex1dx_histogram.png", title="athletics20")
257
+ ```
258
+
259
+ The default theme is a blue background with yellow bars and monospace text.
260
+
261
+ Pass `theme="light"` for a white background with dark grey bars.
262
+
263
+ `file=None` skips writing and returns the Axes.
264
+
265
+ `histogram()` needs matplotlib. Install it with `pip install lex1dx[plot]`.
266
+
267
+ athletics20, k = 5:
268
+
269
+ ![athletics20, k=5](https://raw.githubusercontent.com/nsram/lex1dx/main/docs/img/histogram_athletics20_k5.png)
270
+
271
+ Lognormal sample, n = 10000, k = 32:
272
+
273
+ ![Lognormal, n=10000, k=32](https://raw.githubusercontent.com/nsram/lex1dx/main/docs/img/histogram_lognormal_k32.png)
274
+
275
+ ## Example data
276
+
277
+ ```python
278
+ lex1dx.datasets.names()
279
+ # ('athletics20', 'worldathletics-mens-100m-2379')
280
+ x = lex1dx.datasets.load("athletics20")
281
+ y = lex1dx.datasets.load("worldathletics-mens-100m-2379")
282
+ ```
283
+
284
+ `athletics20` has 20 times from 9.58 to 9.84.
285
+
286
+ `worldathletics-mens-100m-2379` has 2,379 times from 9.58 to 10.30, with 58 distinct values.
287
+
288
+ The 20-row file is the prefix of the 2,379-row list.
289
+
290
+ Only the time column is kept.
291
+
292
+ Athlete names and other fields are not included.
293
+
294
+ Source: World Athletics 100m all-time lists, retrieved January 2024.
295
+
296
+ Sample Data Attribution: The sample 100m timing datasets (top 20 performances and 2379 all time bests) contain historical athletic performance records compiled from publicly available statistics published by World Athletics (https://worldathletics.org/). These datasets are provided strictly as static benchmark/example inputs for testing and demonstrating the algorithms in this package. This project is not affiliated with, endorsed by, or sponsored by World Athletics.
297
+
298
+ ## Precision on a synthetic sample
299
+
300
+ Athletics times have two decimal places, so they do not show significant-digit grouping well.
301
+
302
+ The table below uses 10,000 lognormal draws in full double precision.
303
+
304
+ The generator is `numpy.random.default_rng(1).lognormal(size=10_000)`.
305
+
306
+ `k` is 8.
307
+
308
+ REE is relative excess SSE versus `cluster(..., mode="exact", solver="ckmeans")`.
309
+
310
+ The exact SSE is `2000.58997032`.
311
+
312
+ ```python
313
+ import time
314
+ import numpy as np
315
+ import lex1dx
316
+
317
+ x = np.random.default_rng(1).lognormal(size=10_000)
318
+ k = 8
319
+ ex = lex1dx.cluster(x, k, mode="exact", solver="ckmeans")
320
+ print("sig Dprime SSE REE")
321
+ for d in range(0, 10):
322
+ r = lex1dx.cluster(x, k, sig=d)
323
+ ree = 0.0 if ex.sse == 0 else (r.sse - ex.sse) / ex.sse * 100.0
324
+ print(f"{d:3d} {r.Dprime:6d} {r.sse:.12g} {ree:g}")
325
+ ```
326
+
327
+ | sig | Dprime | SSE | REE |
328
+ |---:|---:|---:|---:|
329
+ | 0 | 10000 | 2000.58997032 | 0 |
330
+ | 1 | 31 | 2446.90052339 | 22.3089% |
331
+ | 2 | 255 | 2003.23173531 | 0.132049% |
332
+ | 3 | 1693 | 2000.59035628 | 1.92923e-05% |
333
+ | 4 | 6577 | 2000.58997032 | 0 |
334
+ | 5 | 9487 | 2000.58997032 | 0 |
335
+ | 6 | 9940 | 2000.58997032 | 0 |
336
+ | 7 | 9993 | 2000.58997032 | 0 |
337
+ | 8 | 9998 | 2000.58997032 | 0 |
338
+ | 9 | 10000 | 2000.58997032 | 0 |
339
+
340
+ `Dprime` is nondecreasing in `sig`.
341
+
342
+ `mode="sig5"` matches `sig=5` on this sample (`sig=5`, same SSE).
343
+
344
+ Worked scripts are in [`examples/cluster_athletics.py`](https://github.com/nsram/lex1dx/blob/main/examples/cluster_athletics.py).
lex1dx-0.1.1/README.md ADDED
@@ -0,0 +1,216 @@
1
+ # lex1dx
2
+
3
+ lex1dx is a fast 1-D k-means library: it splits a set of numbers into k contiguous bins with least squared error. Uses include scalar quantization, binning and histogram design.
4
+
5
+ It has a C++17 core, Python and R bindings to that core, and a Scala port:
6
+
7
+ - **C++**: the core library and a command-line tool (`lex1dx_dump`).
8
+ - **Python**: the `lex1dx` package for PyPI, which wraps the C++ core.
9
+ - **R**: the `lex1dx` package for CRAN, which compiles the same C++ core.
10
+ - **Scala**: a JVM port of the same algorithm with the same options, in `scala/`.
11
+
12
+ All four share one API: `cluster(x, k)` with optional `mode`, `sig`, `M`, `weights` and `solver`. Python, R and Scala bundle two example datasets. Python and R also have `histogram()` and `bin_table()`.
13
+
14
+ It continues [lex1d](https://github.com/nsram/lex1d) ([Zenodo](https://zenodo.org/records/24451573)).
15
+
16
+ lex1d stays the paper-faithful exact-quality reference.
17
+
18
+ Full API docs with examples are in [python/README.md](python/README.md) (the PyPI page), [r/README.md](r/README.md) and the R vignette, and [scala/README.md](scala/README.md).
19
+
20
+ lex1dx is a new repository because the objectives are different: it targets performance against a 0.01% relative-excess-SSE (REE) tolerance, so its defaults and algorithms are not the same as lex1d.
21
+
22
+ ## Defaults
23
+
24
+ The default method is the tuned pipeline.
25
+
26
+ It sorts the data (and canonicalizes `-0` to `+0`).
27
+
28
+ Optional significant-digit grouping can be turned on with `sig`, an integer in 0..9. `sig = 0` (the default) keeps full precision, so only exact ties are merged. `mode = "sig5"` is an alias for `sig = 5`.
29
+
30
+ If grouping leaves fewer than k groups while the data have at least k distinct values, lex1dx adds one digit at a time, up to 15, and then falls back to the raw atoms. `Result.sig` reports the digit count actually used.
31
+
32
+ `mode = "exact"` skips Collapse and runs the chosen solver on all atoms.
33
+
34
+ Optional `weights` give each value a nonnegative weight. Unique values with their counts as weights give the same bins, SSE and centers as the expanded data.
35
+
36
+ Collapse uses a 0.75-quantile batch rule and finishes with a heap once at most 16384 merges remain.
37
+
38
+ The Collapse target is `M = max(4096, 32k)`.
39
+
40
+ The dynamic program on those M groups uses one of two exact solvers, chosen with `solver`:
41
+
42
+ - `"wilber"` (default) is a weighted wilber-interp DP, derived from Grønlund's kmeans1d (commit `585386d`) with a weighted interval-cost patch. It runs in roughly O(kN) time.
43
+ - `"ckmeans"` is the original LEX Fisher DP with divide and conquer, roughly O(kN log N). It follows the conventions of Ckmeans.1d.dp but is independent code.
44
+
45
+ Both are exact, so they give the same partition up to floating-point ties. Use the default. Use `"ckmeans"` as a cross-check, or when you want the classic Fisher DP. A CI test checks that both give the same partition on athletics20 at k = 5.
46
+
47
+ Refine is unchanged in role: it locally improves the cuts.
48
+
49
+ k larger than the number of atoms is clamped to that number.
50
+
51
+ ## Build and use (C++)
52
+
53
+ From the repository root, with CMake 3.21+ and a C++17 compiler:
54
+
55
+ ```
56
+ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
57
+ cmake --build build --config Release
58
+ ctest --test-dir build -C Release --output-on-failure
59
+ ```
60
+
61
+ Link the `lex1dx` library and include `<lex1dx/lex1dx.hpp>`:
62
+
63
+ ```cpp
64
+ #include <lex1dx/lex1dx.hpp>
65
+ lex1dx::Result r = lex1dx::cluster(values, 64); // tuned, default M
66
+ lex1dx::Options o;
67
+ o.sig = 5;
68
+ lex1dx::Result s = lex1dx::cluster(values, 64, o); // 5-significant-digit grouping
69
+ o.mode = lex1dx::Mode::Exact;
70
+ o.solver = lex1dx::Solver::Ckmeans;
71
+ lex1dx::Result e = lex1dx::cluster(values, 64, o);
72
+ ```
73
+
74
+ `Result` holds `bounds`, `sizes`, `centers`, `upper`, `sse`, `D`, `Dprime`, and `assign(x)`.
75
+
76
+ The `lex1dx_dump` tool prints bounds, centers, and SSE for a little-endian float64 file:
77
+
78
+ ```
79
+ ./build/lex1dx_dump tuned data.f64 64
80
+ ```
81
+
82
+ ## Build and use (Scala)
83
+
84
+ Scala 3.3 and sbt 1.10, from the `scala/` directory:
85
+
86
+ ```
87
+ sbt test
88
+ ```
89
+
90
+ ```scala
91
+ import lex1dx.{Lex, Options, Mode, Solver, Datasets}
92
+ val x = Datasets.load("athletics20")
93
+ val r = Lex.cluster(x, 4)
94
+ val s = Lex.cluster(x, 4, Options(sig = 5))
95
+ val e = Lex.cluster(x, 4, Options(mode = Mode.Exact, solver = Solver.Ckmeans))
96
+ ```
97
+
98
+ ## Build and use (Python)
99
+
100
+ From the `python/` directory, with a C++17 compiler and CMake 3.21+:
101
+
102
+ ```
103
+ pip install .
104
+ pip install pytest
105
+ pytest
106
+ ```
107
+
108
+ ```python
109
+ import numpy as np
110
+ import lex1dx
111
+ x = lex1dx.datasets.load("athletics20")
112
+ r = lex1dx.cluster(x, 4) # tuned, default M
113
+ s = lex1dx.cluster(x, 4, sig=5) # group to 5 significant digits
114
+ e = lex1dx.cluster(x, 4, mode="exact", solver="ckmeans")
115
+ w = lex1dx.cluster(vals, 4, weights=counts)
116
+ ```
117
+
118
+ `mode="sig5"` is an alias for `sig=5`. `sig` is an integer in 0..9. 0 is full precision.
119
+ `M=None` (the default) uses `default_M(k) = max(4096, 32 * k)`.
120
+ `solver` is `"wilber"` (default) or `"ckmeans"`.
121
+
122
+ ## Build and use (R)
123
+
124
+ From the `r/` directory, with a C++17 compiler. `configure` copies the C++ core into `src/`. Run `sh tools/sync_core.sh` before `R CMD build` as well:
125
+
126
+ ```
127
+ sh tools/sync_core.sh
128
+ R CMD build .
129
+ R CMD check --no-manual --no-vignettes lex1dx_0.1.1.tar.gz
130
+ ```
131
+
132
+ ```r
133
+ library(lex1dx)
134
+ x <- load_dataset("athletics20")
135
+ r <- cluster(x, 4L) # tuned, default M
136
+ s <- cluster(x, 4L, sig = 5L) # group to 5 significant digits
137
+ e <- cluster(x, 4L, mode = "exact", solver = "ckmeans")
138
+ w <- cluster(vals, 4L, weights = counts)
139
+ ```
140
+
141
+ `mode = "sig5"` is an alias for `sig = 5`. `sig` is an integer in 0..9. 0 is full precision.
142
+ `M = NULL` (the default) uses `default_M(k) = max(4096, 32 * k)`.
143
+ `solver` is `"wilber"` (default) or `"ckmeans"`.
144
+
145
+ ## Histogram
146
+
147
+ `histogram()` in Python and R draws the fitted bins as a horizontal table, one row per bin, from the lowest bin at the top.
148
+
149
+ Each row shows the bin's range, a bar proportional to its count (or weight), and `[n, pct%, mean]`. The header gives r² and MSE for the k-bin model.
150
+
151
+ ```python
152
+ r = lex1dx.cluster(x, 5)
153
+ lex1dx.histogram(r, x, title="athletics20") # writes lex1dx_histogram.png
154
+ lex1dx.histogram(r, x, file=None) # draw only
155
+ rows = lex1dx.bin_table(r, x) # (lo, hi, n, pct, mean) per bin
156
+ ```
157
+
158
+ Python needs matplotlib for `histogram()` (`pip install lex1dx[plot]`). R uses base graphics. `theme = "light"` gives grey bars on white. The default blue theme follows the 2024 Scala audio figures. `bin_table()` returns the same rows as data (a data frame in R).
159
+
160
+ athletics20, k = 5, Python:
161
+
162
+ ![athletics20, k=5 (Python)](docs/img/histogram_athletics20_k5.png)
163
+
164
+ athletics20, k = 5, R:
165
+
166
+ ![athletics20, k=5 (R)](docs/img/histogram_athletics20_k5_r.png)
167
+
168
+ Lognormal sample, n = 10000, k = 32, Python:
169
+
170
+ ![Lognormal, n=10000, k=32 (Python)](docs/img/histogram_lognormal_k32.png)
171
+
172
+ ## Results (v7 Mac pack)
173
+
174
+ On the v7 scaling pack, a post-sort comparison against Grønlund wilber-interp on the raw points gave speedups up to 156× (sig5) and 37× (tuned), with REE at most 0.0056% on all 270/270 cells.
175
+
176
+ Those times exclude the sort, because both methods need the same sorted input.
177
+
178
+ Those figures come from the `bot_v7_scaling_mac_pack` Mac run (270 cells, all ok).
179
+
180
+ ## Example data
181
+
182
+ Two men's 100 m timing samples are bundled for tests and examples:
183
+ `athletics20` (20 times) and `worldathletics-mens-100m-2379` (2,379 times).
184
+
185
+ Source: World Athletics 100m all-time lists, retrieved January 2024.
186
+
187
+ Only the time column is kept. Athlete names and other fields are not included.
188
+
189
+ Sample Data Attribution: The sample 100m timing datasets (top 20 performances and 2379 all time bests) contain historical athletic performance records compiled from publicly available statistics published by World Athletics (https://worldathletics.org/). These datasets are provided strictly as static benchmark/example inputs for testing and demonstrating the algorithms in this package. This project is not affiliated with, endorsed by, or sponsored by World Athletics.
190
+
191
+ The precision examples use synthetic lognormal data generated in code with a fixed seed. See the Python and R READMEs.
192
+
193
+ Worked outputs are in `examples/cluster_athletics.py`, `r/inst/examples/cluster_athletics.R`,
194
+ and `docs/examples_output.md` / `docs/examples_output_r.md`.
195
+
196
+ ## Citation
197
+
198
+ If you use lex1dx, please cite the paper:
199
+
200
+ - Sriram, N. (2026). LEX: Fast scalar quantization by grouping and local exchanges. Preprint, Zenodo. https://doi.org/10.5281/zenodo.24543220
201
+
202
+ Software and data:
203
+
204
+ - lex1dx v0.1.0: https://doi.org/10.5281/zenodo.24544282
205
+ - lex1dx-paper v1.0.0 (scripts, data, figures and tables for the paper): https://doi.org/10.5281/zenodo.24544241
206
+
207
+ ## Attribution
208
+
209
+ lex1dx is MIT licensed (see `LICENSE`).
210
+
211
+ The wilber DP is derived from kmeans1d by Allan Grønlund, commit `585386d4678000691706acdb954911be8fea1c5c`, also MIT. See `NOTICE` and `third_party/kmeans1d/`.
212
+
213
+ The `ckmeans` solver is our own implementation of the Fisher (1958) dynamic program in the form described by Wang and Song (2011) for Ckmeans.1d.dp. No Ckmeans.1d.dp code is included.
214
+
215
+ - Fisher, W. D. (1958). On grouping for maximum homogeneity. *Journal of the American Statistical Association*, 53(284), 789–798.
216
+ - Wang, H. and Song, M. (2011). Ckmeans.1d.dp: Optimal k-means clustering in one dimension by dynamic programming. *The R Journal*, 3(2), 29–33.