MDL-Density-Histogram 1.1.4__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.
@@ -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.
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: MDL-Density-Histogram
3
+ Version: 1.1.4
4
+ Summary: Cython-accelerated MDL histogram density estimation with dynamic programming, implementing Kontkanen & Myllymaki's algorithm (JMLR 2007).
5
+ Author-email: Götz Grimmer <goetz-dev@web.de>
6
+ Maintainer-email: Götz Grimmer <goetz-dev@web.de>
7
+ License: Apache-2.0
8
+ Project-URL: Repository, https://github.com/MrTarantoga/MDL-Density-Histogram
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Provides-Extra: tests
13
+ Requires-Dist: pytest; extra == "tests"
14
+ Requires-Dist: pytest-xdist; extra == "tests"
15
+ Requires-Dist: pandas; extra == "tests"
16
+ Requires-Dist: pyarrow; extra == "tests"
17
+ Requires-Dist: brotli; extra == "tests"
18
+ Dynamic: license-file
19
+
20
+ [![Upload Python Package](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-publish.yml/badge.svg?event=release)](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-publish.yml)
21
+ [![Python application test](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-app.yml/badge.svg)](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-app.yml)
22
+
23
+ # MDL Optimal Histogram Density Estimation
24
+
25
+ This package provides a Cython-accelerated implementation of the **Minimum Description Length (MDL) optimal histogram density estimation** algorithm from Kontkanen & Myllymaki (2007). It uses information-theoretic principles to automatically determine optimal variable-width bins for density estimation.
26
+
27
+ ![Freedman-Diaconis vs. MDL-Optimization](https://raw.githubusercontent.com/MrTarantoga/MDL-Density-Histogram/main/gmm5_idx_3.png)
28
+
29
+ ## Features
30
+ - **MDL Principle**: Uses stochastic complexity for model selection
31
+ - **Dynamic Programming**: Efficient O(E²·K_max) optimization (cache parametric complexity computation, speed up)
32
+ - **Score of each *K*th bin**: The score of each bin is returned to understand the performance of different properties of the same dataset.
33
+ - **Variable-Width Bins**: Adapts to data density variations
34
+ - **Automatic Bin Count**: No manual parameter tuning required (except maximum bin count to consider $K_{max}$ and data resolution $\epsilon$)
35
+ - **Cython Acceleration**: Critical operations compiled to C
36
+
37
+ ## Installation
38
+ You can install the package using pip:
39
+ ```bash
40
+ pip install MDL-Density-Histogram
41
+ ```
42
+ Alternatively, you can install it from source by cloning the repository and running:
43
+ ```bash
44
+ # From project root directory
45
+ pip install .
46
+ ```
47
+
48
+ Requires:
49
+ - Python 3.11+
50
+ - NumPy
51
+ - Cython
52
+ - C compiler (GCC/Clang/MSVC)
53
+
54
+ ## Usage Example
55
+ ```python
56
+ import numpy as np
57
+ from mdl_density_hist import mdl_optimal_histogram
58
+
59
+ # Generate sample data
60
+ data = np.random.normal(0, 1, 1000)
61
+
62
+ # Compute optimal histogram
63
+ cut_points, K_scores = mdl_optimal_histogram(data, epsilon=0.1)
64
+
65
+ # Print score of each bin
66
+ print(f"K_scores: {K_scores}")
67
+
68
+ # Visualize result
69
+ import matplotlib.pyplot as plt
70
+ plt.hist(data, bins=cut_points, density=True)
71
+ plt.title('MDL Optimal Histogram')
72
+ plt.show()
73
+ ```
74
+
75
+ ## Parameters
76
+ - `data`: Input array (1D numpy array)
77
+ - `epsilon`: Quantization precision (default: 0.1)
78
+ - `K_max`: Maximum number of bins (default: 10)
79
+
80
+ ## Algorithm Highlights
81
+ - Uses **Ramanujan's factorial approximation** for efficient parametric complexity
82
+ - Cache parameteric complexity to speed up computation
83
+
84
+ ## Paper Citation
85
+ Kontkanen, P., & Myllymäki, P. (2007).
86
+ *MDL Histogram Density Estimation*
87
+ Journal of Machine Learning Research 8 (2007)
88
+ [PDF](https://proceedings.mlr.press/v2/kontkanen07a/kontkanen07a.pdf)
89
+
90
+ ## License
91
+ Apache 2.0 License - See LICENSE file
92
+
93
+ ## Project Structure
94
+ ```
95
+ src/
96
+ ├── mdl_density_hist/
97
+ │ ├── __init__.py
98
+ │ └── mdl_hist.pyx # Core Cython implementation
99
+ └── pyproject.toml
100
+ ```
101
+
102
+ ## Performance Notes
103
+ - Precomputed parametric complexity using dynamic programming
104
+ - Memory-optimized array operations via NumPy
105
+ - Candidate cut point pruning for reduced search space
106
+
107
+
108
+ For implementation details, see the [paper](https://proceedings.mlr.press/v2/kontkanen07a/kontkanen07a.pdf) and inline code comments.
@@ -0,0 +1,89 @@
1
+ [![Upload Python Package](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-publish.yml/badge.svg?event=release)](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-publish.yml)
2
+ [![Python application test](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-app.yml/badge.svg)](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-app.yml)
3
+
4
+ # MDL Optimal Histogram Density Estimation
5
+
6
+ This package provides a Cython-accelerated implementation of the **Minimum Description Length (MDL) optimal histogram density estimation** algorithm from Kontkanen & Myllymaki (2007). It uses information-theoretic principles to automatically determine optimal variable-width bins for density estimation.
7
+
8
+ ![Freedman-Diaconis vs. MDL-Optimization](https://raw.githubusercontent.com/MrTarantoga/MDL-Density-Histogram/main/gmm5_idx_3.png)
9
+
10
+ ## Features
11
+ - **MDL Principle**: Uses stochastic complexity for model selection
12
+ - **Dynamic Programming**: Efficient O(E²·K_max) optimization (cache parametric complexity computation, speed up)
13
+ - **Score of each *K*th bin**: The score of each bin is returned to understand the performance of different properties of the same dataset.
14
+ - **Variable-Width Bins**: Adapts to data density variations
15
+ - **Automatic Bin Count**: No manual parameter tuning required (except maximum bin count to consider $K_{max}$ and data resolution $\epsilon$)
16
+ - **Cython Acceleration**: Critical operations compiled to C
17
+
18
+ ## Installation
19
+ You can install the package using pip:
20
+ ```bash
21
+ pip install MDL-Density-Histogram
22
+ ```
23
+ Alternatively, you can install it from source by cloning the repository and running:
24
+ ```bash
25
+ # From project root directory
26
+ pip install .
27
+ ```
28
+
29
+ Requires:
30
+ - Python 3.11+
31
+ - NumPy
32
+ - Cython
33
+ - C compiler (GCC/Clang/MSVC)
34
+
35
+ ## Usage Example
36
+ ```python
37
+ import numpy as np
38
+ from mdl_density_hist import mdl_optimal_histogram
39
+
40
+ # Generate sample data
41
+ data = np.random.normal(0, 1, 1000)
42
+
43
+ # Compute optimal histogram
44
+ cut_points, K_scores = mdl_optimal_histogram(data, epsilon=0.1)
45
+
46
+ # Print score of each bin
47
+ print(f"K_scores: {K_scores}")
48
+
49
+ # Visualize result
50
+ import matplotlib.pyplot as plt
51
+ plt.hist(data, bins=cut_points, density=True)
52
+ plt.title('MDL Optimal Histogram')
53
+ plt.show()
54
+ ```
55
+
56
+ ## Parameters
57
+ - `data`: Input array (1D numpy array)
58
+ - `epsilon`: Quantization precision (default: 0.1)
59
+ - `K_max`: Maximum number of bins (default: 10)
60
+
61
+ ## Algorithm Highlights
62
+ - Uses **Ramanujan's factorial approximation** for efficient parametric complexity
63
+ - Cache parameteric complexity to speed up computation
64
+
65
+ ## Paper Citation
66
+ Kontkanen, P., & Myllymäki, P. (2007).
67
+ *MDL Histogram Density Estimation*
68
+ Journal of Machine Learning Research 8 (2007)
69
+ [PDF](https://proceedings.mlr.press/v2/kontkanen07a/kontkanen07a.pdf)
70
+
71
+ ## License
72
+ Apache 2.0 License - See LICENSE file
73
+
74
+ ## Project Structure
75
+ ```
76
+ src/
77
+ ├── mdl_density_hist/
78
+ │ ├── __init__.py
79
+ │ └── mdl_hist.pyx # Core Cython implementation
80
+ └── pyproject.toml
81
+ ```
82
+
83
+ ## Performance Notes
84
+ - Precomputed parametric complexity using dynamic programming
85
+ - Memory-optimized array operations via NumPy
86
+ - Candidate cut point pruning for reduced search space
87
+
88
+
89
+ For implementation details, see the [paper](https://proceedings.mlr.press/v2/kontkanen07a/kontkanen07a.pdf) and inline code comments.
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools", "cython", "wheel", "numpy"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "MDL-Density-Histogram"
7
+ version = "1.1.4"
8
+ requires-python = ">= 3.11"
9
+ description = "Cython-accelerated MDL histogram density estimation with dynamic programming, implementing Kontkanen & Myllymaki's algorithm (JMLR 2007)."
10
+ authors = [
11
+ {name = "Götz Grimmer", email = "goetz-dev@web.de"}
12
+ ]
13
+ maintainers = [
14
+ {name = "Götz Grimmer", email = "goetz-dev@web.de"}
15
+ ]
16
+ license = {text = "Apache-2.0"}
17
+ readme = "README.md"
18
+
19
+ [project.urls]
20
+ Repository = "https://github.com/MrTarantoga/MDL-Density-Histogram"
21
+
22
+ [project.optional-dependencies]
23
+ tests = [
24
+ "pytest",
25
+ "pytest-xdist",
26
+ "pandas",
27
+ "pyarrow",
28
+ "brotli"
29
+ ]
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
33
+
34
+ [tool.setuptools]
35
+ package-dir = {"" = "src"}
36
+
37
+ [tool.cibuildwheel.linux.environment]
38
+ CFLAGS = "-O3 -funroll-loops -flto -ftree-vectorize"
39
+
40
+ [tool.cibuildwheel.macos.environment]
41
+ CFLAGS = "-O3 -funroll-loops -flto -ftree-vectorize"
42
+
43
+ [tool.cibuildwheel.windows.environment]
44
+ # Use /O2 instead of -O3 for MSVC; /GL enables link-time optimization
45
+ CFLAGS = "/O2 /GL"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,25 @@
1
+ from setuptools import setup, Extension
2
+ # Use Cython.Build instead of Cython.Distutils
3
+ from Cython.Build import build_ext
4
+ import numpy as np
5
+
6
+ # Define the source directory relative to setup.py
7
+ SRC_DIR = "src/mdl_density_hist"
8
+
9
+ # Define the Cython extension
10
+ ext_1 = Extension(
11
+ name="mdl_density_hist.mdl_hist",
12
+ sources=[SRC_DIR + "/mdl_hist.pyx"],
13
+ libraries=[],
14
+ include_dirs=[np.get_include()]
15
+ )
16
+
17
+ EXTENSIONS = [ext_1]
18
+
19
+ # Setup configuration focused only on building the extension
20
+ # Remove the __name__ == "__main__" guard
21
+ setup(
22
+ # Removed packages and package_dir
23
+ cmdclass={"build_ext": build_ext},
24
+ ext_modules=EXTENSIONS
25
+ )
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: MDL-Density-Histogram
3
+ Version: 1.1.4
4
+ Summary: Cython-accelerated MDL histogram density estimation with dynamic programming, implementing Kontkanen & Myllymaki's algorithm (JMLR 2007).
5
+ Author-email: Götz Grimmer <goetz-dev@web.de>
6
+ Maintainer-email: Götz Grimmer <goetz-dev@web.de>
7
+ License: Apache-2.0
8
+ Project-URL: Repository, https://github.com/MrTarantoga/MDL-Density-Histogram
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Provides-Extra: tests
13
+ Requires-Dist: pytest; extra == "tests"
14
+ Requires-Dist: pytest-xdist; extra == "tests"
15
+ Requires-Dist: pandas; extra == "tests"
16
+ Requires-Dist: pyarrow; extra == "tests"
17
+ Requires-Dist: brotli; extra == "tests"
18
+ Dynamic: license-file
19
+
20
+ [![Upload Python Package](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-publish.yml/badge.svg?event=release)](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-publish.yml)
21
+ [![Python application test](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-app.yml/badge.svg)](https://github.com/MrTarantoga/MDL-Density-Histogram/actions/workflows/python-app.yml)
22
+
23
+ # MDL Optimal Histogram Density Estimation
24
+
25
+ This package provides a Cython-accelerated implementation of the **Minimum Description Length (MDL) optimal histogram density estimation** algorithm from Kontkanen & Myllymaki (2007). It uses information-theoretic principles to automatically determine optimal variable-width bins for density estimation.
26
+
27
+ ![Freedman-Diaconis vs. MDL-Optimization](https://raw.githubusercontent.com/MrTarantoga/MDL-Density-Histogram/main/gmm5_idx_3.png)
28
+
29
+ ## Features
30
+ - **MDL Principle**: Uses stochastic complexity for model selection
31
+ - **Dynamic Programming**: Efficient O(E²·K_max) optimization (cache parametric complexity computation, speed up)
32
+ - **Score of each *K*th bin**: The score of each bin is returned to understand the performance of different properties of the same dataset.
33
+ - **Variable-Width Bins**: Adapts to data density variations
34
+ - **Automatic Bin Count**: No manual parameter tuning required (except maximum bin count to consider $K_{max}$ and data resolution $\epsilon$)
35
+ - **Cython Acceleration**: Critical operations compiled to C
36
+
37
+ ## Installation
38
+ You can install the package using pip:
39
+ ```bash
40
+ pip install MDL-Density-Histogram
41
+ ```
42
+ Alternatively, you can install it from source by cloning the repository and running:
43
+ ```bash
44
+ # From project root directory
45
+ pip install .
46
+ ```
47
+
48
+ Requires:
49
+ - Python 3.11+
50
+ - NumPy
51
+ - Cython
52
+ - C compiler (GCC/Clang/MSVC)
53
+
54
+ ## Usage Example
55
+ ```python
56
+ import numpy as np
57
+ from mdl_density_hist import mdl_optimal_histogram
58
+
59
+ # Generate sample data
60
+ data = np.random.normal(0, 1, 1000)
61
+
62
+ # Compute optimal histogram
63
+ cut_points, K_scores = mdl_optimal_histogram(data, epsilon=0.1)
64
+
65
+ # Print score of each bin
66
+ print(f"K_scores: {K_scores}")
67
+
68
+ # Visualize result
69
+ import matplotlib.pyplot as plt
70
+ plt.hist(data, bins=cut_points, density=True)
71
+ plt.title('MDL Optimal Histogram')
72
+ plt.show()
73
+ ```
74
+
75
+ ## Parameters
76
+ - `data`: Input array (1D numpy array)
77
+ - `epsilon`: Quantization precision (default: 0.1)
78
+ - `K_max`: Maximum number of bins (default: 10)
79
+
80
+ ## Algorithm Highlights
81
+ - Uses **Ramanujan's factorial approximation** for efficient parametric complexity
82
+ - Cache parameteric complexity to speed up computation
83
+
84
+ ## Paper Citation
85
+ Kontkanen, P., & Myllymäki, P. (2007).
86
+ *MDL Histogram Density Estimation*
87
+ Journal of Machine Learning Research 8 (2007)
88
+ [PDF](https://proceedings.mlr.press/v2/kontkanen07a/kontkanen07a.pdf)
89
+
90
+ ## License
91
+ Apache 2.0 License - See LICENSE file
92
+
93
+ ## Project Structure
94
+ ```
95
+ src/
96
+ ├── mdl_density_hist/
97
+ │ ├── __init__.py
98
+ │ └── mdl_hist.pyx # Core Cython implementation
99
+ └── pyproject.toml
100
+ ```
101
+
102
+ ## Performance Notes
103
+ - Precomputed parametric complexity using dynamic programming
104
+ - Memory-optimized array operations via NumPy
105
+ - Candidate cut point pruning for reduced search space
106
+
107
+
108
+ For implementation details, see the [paper](https://proceedings.mlr.press/v2/kontkanen07a/kontkanen07a.pdf) and inline code comments.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ src/MDL_Density_Histogram.egg-info/PKG-INFO
6
+ src/MDL_Density_Histogram.egg-info/SOURCES.txt
7
+ src/MDL_Density_Histogram.egg-info/dependency_links.txt
8
+ src/MDL_Density_Histogram.egg-info/requires.txt
9
+ src/MDL_Density_Histogram.egg-info/top_level.txt
10
+ src/mdl_density_hist/__init__.py
11
+ src/mdl_density_hist/mdl_hist.pyx
12
+ tests/test_main.py
@@ -0,0 +1,7 @@
1
+
2
+ [tests]
3
+ pytest
4
+ pytest-xdist
5
+ pandas
6
+ pyarrow
7
+ brotli
@@ -0,0 +1 @@
1
+ from .mdl_hist import mdl_optimal_histogram
@@ -0,0 +1,255 @@
1
+ # cython: language_level=3
2
+ # cython: boundscheck=False
3
+ # cython: wraparound=False
4
+ # cython: nonecheck=False
5
+ # cython: binding=False
6
+ # cython: cdivision=True
7
+
8
+ import numpy as np
9
+ cimport cython
10
+ from libc.math cimport floor, log, INFINITY, exp
11
+
12
+ cdef const double PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164062
13
+
14
+ cdef double log_fac_by_Ramanujan(const unsigned long long n):
15
+ assert n >= 0, "N is only allowed to be [0, inf)"
16
+ cdef double term_1, term_2, term_3, result
17
+
18
+ if n <= 1:
19
+ return log(1.0)
20
+ else:
21
+ term_1 = <double>n * log(n) - <double>n
22
+ term_2 = log(<double>n * <double>(1 + 4 * n * (1 + 2 * n))) / 6.0
23
+ term_3 = log(PI) / 2.0
24
+ result = term_1 + term_2 + term_3
25
+ return result
26
+
27
+ def quantize_data(const double [:] x, const double epsilon):
28
+ assert len(x) > 2, "The x must contain [2, inf)"
29
+ assert epsilon > 0, "Epsilon must be positive"
30
+
31
+ n_bins = int(np.ceil((np.max(x) - np.min(x)) / epsilon)) + 1
32
+ bins = np.arange(
33
+ np.min(x), np.max(x) + n_bins * epsilon + 1e-10, epsilon
34
+ )
35
+ data_disc = []
36
+ for lower_bin, upper_bin in zip(bins, bins[1:]):
37
+ number_bins = np.argwhere(np.logical_and(x < upper_bin, x >= lower_bin) == True).shape[0]
38
+ data_disc += [lower_bin]*number_bins
39
+ return np.asarray(data_disc)
40
+
41
+ def generate_candidate_cut_points(const double [:] x, const double epsilon):
42
+ """Generate candidate cut points between data points (Equation 22)"""
43
+ assert len(x) > 2, "The x must contain [2, inf)"
44
+ assert epsilon > 0, "Epsilon must be positive"
45
+
46
+ x = np.sort(x)
47
+ candidates = []
48
+
49
+ for _x in x:
50
+ candidates.extend([_x - epsilon/2, _x + epsilon/2])
51
+
52
+ # Remove duplicates and sort
53
+ candidates = sorted(list(set(candidates)))
54
+
55
+ # Remove implicit boundaries
56
+ implicit_lower = min(x) - epsilon/2
57
+ candidates = np.delete(candidates, np.argwhere(candidates == implicit_lower).flatten())
58
+
59
+ return candidates
60
+
61
+ cpdef unsigned long long[:] precompute_n_e(const double [:] data, const double [:] candidates):
62
+ """Precompute n_e: number of data points in [x_min, c_e] (Section 4)"""
63
+ n_e = np.zeros(len(candidates), dtype=np.uint64) # Include E+1
64
+ cdef Py_ssize_t i, d
65
+ cdef double c
66
+
67
+ for i, c in enumerate(candidates):
68
+ # Count data
69
+ for d in range(len(data)):
70
+ if data[d] < c:
71
+ n_e[i] += 1
72
+ return n_e
73
+
74
+ cdef double compute_parametric_complexity(const unsigned long long n, const unsigned long long K):
75
+ cdef double R_prev2 = 1.0 # R_n_h(K-2)
76
+ cdef double R_current = 0.0 # R_n_h(K)
77
+ cdef double R_prev1 = 0.0 # R_n_h(K-1)
78
+ cdef unsigned long long h2, h1, k
79
+ cdef double term_1, term_2, term_3
80
+ cdef double log_n = log(n)
81
+
82
+ if K == 0:
83
+ return 1.0
84
+
85
+ if K >= 1:
86
+ # Precompute log(n) once for all h2 iterations
87
+ for h2 in range(n + 1):
88
+ h1 = n - h2
89
+ term_1 = log_fac_by_Ramanujan(n) - (log_fac_by_Ramanujan(h1) + log_fac_by_Ramanujan(h2))
90
+
91
+ if h1 != 0:
92
+ term_2 = (log(<double>h1) - log_n) * <double>h1
93
+ else:
94
+ term_2 = 0.0
95
+
96
+ if h2 != 0:
97
+ term_3 = (log(<double>h2) - log_n) * <double>h2
98
+ else:
99
+ term_3 = 0.0
100
+
101
+ R_current += exp(term_1 + term_2 + term_3)
102
+
103
+ if K >= 2:
104
+ R_prev1 = R_current # R_n_h(1)
105
+ for k in range(2, K + 1):
106
+ R_current = R_prev1 + (<double>n / <double>(k-1)) * R_prev2
107
+ R_prev2 = R_prev1
108
+ R_prev1 = R_current
109
+
110
+ return R_current
111
+
112
+ cdef double dp_func_init(const unsigned long long [:] n_e,
113
+ const double [:] x,
114
+ const unsigned long long n,
115
+ const double [:] candidates,
116
+ const unsigned long long e,
117
+ const double epsilon):
118
+ cdef double term1, term2, best_score, candidates_val, x_min
119
+ cdef unsigned long long n_e_val = <unsigned long long>n_e[e]
120
+
121
+ if n_e_val != 0:
122
+ candidates_val = <double>candidates[e]
123
+ x_min = <double>np.min(x)
124
+
125
+ term1 = log(epsilon * <double>n_e_val)
126
+ term2 = log((candidates_val - (x_min - epsilon / 2.0)) * <double>n)
127
+ best_score = -<double>n_e_val * (term1 - term2)
128
+ return best_score
129
+ else:
130
+ return 0.0
131
+
132
+ cdef tuple dp_func(const unsigned long long [:] n_e,
133
+ const double [:] x,
134
+ const unsigned long long n,
135
+ const double [:] candidates,
136
+ const unsigned long long K,
137
+ const unsigned long long E,
138
+ const unsigned long long e,
139
+ const double epsilon,
140
+ double[:, :] DP_table,
141
+ dict[tuple[unsigned long long, unsigned long long], double] cache):
142
+ cdef double e_prime_best_score = INFINITY
143
+ cdef double best_score = INFINITY
144
+ cdef unsigned long long e_prime
145
+ cdef unsigned long long n_k
146
+ cdef double bin_width
147
+ cdef double term1, term2, term3, score
148
+ cdef double R, R_prime
149
+
150
+ for e_prime in range(K-1, e):
151
+ n_k = n_e[e] - n_e[e_prime]
152
+ bin_width = candidates[e] - candidates[e_prime]
153
+
154
+ if n_k != 0:
155
+ term1 = <double>n_k * (log(epsilon * <double>n_k) - log(bin_width * <double>n))
156
+ else:
157
+ term1 = 0.0
158
+
159
+ if (n_e[e], K) in cache:
160
+ R = cache[n_e[e], K]
161
+ else:
162
+ R = compute_parametric_complexity(n_e[e], K)
163
+ cache[n_e[e], K] = R
164
+
165
+ if (n_e[e_prime], K-1) in cache:
166
+ R_prime = cache[n_e[e_prime], K-1]
167
+ else:
168
+ R_prime = compute_parametric_complexity(n_e[e_prime], K - 1)
169
+ cache[n_e[e_prime], K-1] = R_prime
170
+
171
+ term2 = log(R / R_prime)
172
+ term3 = log(<double>(E - K + 4) / <double>K)
173
+
174
+ assert DP_table[K-1, e_prime] != INFINITY, "DP_table contain a infinity error, that is not allowed"
175
+
176
+ score = DP_table[K-1, e_prime] - term1 + term2 + term3
177
+ if score < best_score:
178
+ e_prime_best_score = <double>e_prime
179
+ best_score = score
180
+
181
+ return (e_prime_best_score, best_score)
182
+
183
+
184
+
185
+ def mdl_optimal_histogram(const double [:] data,
186
+ const double epsilon=0.1,
187
+ const unsigned long long K_max=10):
188
+ cdef double[:] K_scores
189
+ cdef unsigned long long n = data.shape[0]
190
+ cdef unsigned long long i
191
+ cdef unsigned long long K, e, K_best, e_pos,
192
+ cdef double[:] candidates
193
+ cdef unsigned long long[:] n_e
194
+ cdef unsigned long long E
195
+ cdef double[:, :] dp_table_score
196
+ cdef int[:, :] dp_table_e_prime
197
+ cdef double best_score
198
+ cdef list optimal_cut_points
199
+
200
+ # Check for valid input data
201
+ assert len(data) > 2, "The data must contain more than 2 datapoints"
202
+ assert epsilon > 0, "The epsilon must be positive"
203
+
204
+ # Step 0: Create lookup dictionary for parametric compute_parametric_complexity
205
+ cdef dict[tuple[unsigned long long, unsigned long long], double] cpc_cache = {}
206
+
207
+ # Step 1: Quantize data
208
+ data = quantize_data(data, epsilon)
209
+
210
+ # Step 3: Generate candidate cut points
211
+ candidates = generate_candidate_cut_points(data, epsilon)
212
+ E = candidates.shape[0] - 1 # Exclude implicit outer boundary
213
+
214
+ # Step 4: Precompute n_e
215
+ n_e = precompute_n_e(data, candidates)
216
+
217
+ assert K_max > 1, "K_max must be [2, inf)"
218
+
219
+ # Step 5: Initialize DP tables
220
+ dp_table_score = np.full((K_max + 1, E + 1), INFINITY, dtype=np.float64)
221
+ dp_table_e_prime = np.full((K_max + 1, E + 1), -1, dtype=np.int32)
222
+
223
+ # Initialize DP table for K=0
224
+ for e in range(E + 1):
225
+ dp_table_score[0, e] = dp_func_init(n_e, data, n, candidates, e, epsilon)
226
+
227
+ # Fill DP table for K >= 1
228
+ for K in range(1, K_max + 1):
229
+ for e in range(K, E + 1):
230
+ dp_table_e_prime[K, e], dp_table_score[K, e] = dp_func(
231
+ n_e, data, n, candidates, K, E, e, epsilon, dp_table_score, cpc_cache
232
+ )
233
+
234
+ # Find best K
235
+ K_best = 0
236
+ K_scores = dp_table_score[:, E]
237
+
238
+ best_score = dp_table_score[0, E]
239
+ for K in range(1, K_max + 1):
240
+ if dp_table_score[K, E] < best_score:
241
+ best_score = dp_table_score[K, E]
242
+ K_best = K
243
+
244
+ # Backtrack to find optimal cut points
245
+ optimal_cut_points = [candidates[E]]
246
+ e_pos = E
247
+ for K in range(K_best - 1, 0, -1):
248
+ e_pos = dp_table_e_prime[K, e_pos]
249
+ optimal_cut_points.append(candidates[e_pos])
250
+
251
+ # Add min and sort
252
+ optimal_cut_points.append(np.min(data))
253
+ optimal_cut_points.sort()
254
+
255
+ return np.array(optimal_cut_points, dtype=np.float64), np.array(K_scores, dtype=np.float64)
@@ -0,0 +1,197 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ import pytest
4
+ from pathlib import Path
5
+ from mdl_density_hist import mdl_optimal_histogram
6
+
7
+ import sys
8
+
9
+ sys.dont_write_bytecode = True
10
+
11
+ K_max = 100
12
+ epsilon = 0.1
13
+
14
+ @pytest.fixture
15
+ def rootdir_path(request):
16
+ return request.config.rootdir
17
+
18
+ def test_gmm3_id_0(rootdir_path):
19
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm3_samples.parquet.brotli")
20
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm3_samples_MDL_lower_bins.parquet.brotli")
21
+ id = 0
22
+
23
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
24
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
25
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
26
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
27
+
28
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
29
+
30
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
31
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
32
+
33
+ def test_gmm3_id_1(rootdir_path):
34
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm3_samples.parquet.brotli")
35
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm3_samples_MDL_lower_bins.parquet.brotli")
36
+ id = 1
37
+
38
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
39
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
40
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
41
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
42
+
43
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
44
+
45
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
46
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
47
+
48
+ def test_gmm3_id_2(rootdir_path):
49
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm3_samples.parquet.brotli")
50
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm3_samples_MDL_lower_bins.parquet.brotli")
51
+ id = 2
52
+
53
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
54
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
55
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
56
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
57
+
58
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
59
+
60
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
61
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
62
+
63
+
64
+ def test_gmm4_id_0(rootdir_path):
65
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm4_samples.parquet.brotli")
66
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm4_samples_MDL_lower_bins.parquet.brotli")
67
+ id = 0
68
+
69
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
70
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
71
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
72
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
73
+
74
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
75
+
76
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
77
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
78
+
79
+ def test_gmm4_id_1(rootdir_path):
80
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm4_samples.parquet.brotli")
81
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm4_samples_MDL_lower_bins.parquet.brotli")
82
+ id = 1
83
+
84
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
85
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
86
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
87
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
88
+
89
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
90
+
91
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
92
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
93
+
94
+ def test_gmm4_id_2(rootdir_path):
95
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm4_samples.parquet.brotli")
96
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm4_samples_MDL_lower_bins.parquet.brotli")
97
+ id = 2
98
+
99
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
100
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
101
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
102
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
103
+
104
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
105
+
106
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
107
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
108
+
109
+ def test_gmm4_id_3(rootdir_path):
110
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm4_samples.parquet.brotli")
111
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm4_samples_MDL_lower_bins.parquet.brotli")
112
+ id = 3
113
+
114
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
115
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
116
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
117
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
118
+
119
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
120
+
121
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
122
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
123
+
124
+ def test_gmm5_id_0(rootdir_path):
125
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples.parquet.brotli")
126
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples_MDL_lower_bins.parquet.brotli")
127
+ id = 0
128
+
129
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
130
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
131
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
132
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
133
+
134
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
135
+
136
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
137
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
138
+
139
+ def test_gmm5_id_1(rootdir_path):
140
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples.parquet.brotli")
141
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples_MDL_lower_bins.parquet.brotli")
142
+ id = 1
143
+
144
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
145
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
146
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
147
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
148
+
149
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
150
+
151
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
152
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
153
+
154
+ def test_gmm5_id_2(rootdir_path):
155
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples.parquet.brotli")
156
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples_MDL_lower_bins.parquet.brotli")
157
+ id = 2
158
+
159
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
160
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
161
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
162
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
163
+
164
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
165
+
166
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
167
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
168
+
169
+ def test_gmm5_id_3(rootdir_path):
170
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples.parquet.brotli")
171
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples_MDL_lower_bins.parquet.brotli")
172
+ id = 3
173
+
174
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
175
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
176
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
177
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
178
+
179
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
180
+
181
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
182
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)
183
+
184
+ def test_gmm5_id_4(rootdir_path):
185
+ gmmX_ds = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples.parquet.brotli")
186
+ gmmX_mdl_lower_bins = pd.read_parquet(Path(rootdir_path) / Path("tests") / "gmm5_samples_MDL_lower_bins.parquet.brotli")
187
+ id = 4
188
+
189
+ assert all(np.unique(gmmX_ds["dataset_id"]) == np.unique(gmmX_mdl_lower_bins["dataset_id"])), "The number of dataset ids must equal"
190
+ dataset = gmmX_ds[gmmX_ds["dataset_id"] == id]["value"].to_numpy()
191
+ lower_bins_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["lower_bin"].dropna().to_numpy()
192
+ K_scores_true = gmmX_mdl_lower_bins[gmmX_mdl_lower_bins["dataset_id"] == id]["K_score"].to_numpy()
193
+
194
+ lower_bins_pred, K_scores_pred = mdl_optimal_histogram(dataset, K_max=K_max, epsilon=epsilon)
195
+
196
+ np.testing.assert_array_almost_equal(lower_bins_pred, lower_bins_true, decimal=5)
197
+ np.testing.assert_allclose(K_scores_pred, K_scores_true, rtol=1e-5)