synthe 0.9.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 (36) hide show
  1. synthe-0.9.1/CONTRIBUTING.md +119 -0
  2. synthe-0.9.1/HISTORY.md +5 -0
  3. synthe-0.9.1/LICENSE +32 -0
  4. synthe-0.9.1/MANIFEST.in +10 -0
  5. synthe-0.9.1/PKG-INFO +103 -0
  6. synthe-0.9.1/README.md +21 -0
  7. synthe-0.9.1/docs/index.md +16 -0
  8. synthe-0.9.1/docs/installation.md +38 -0
  9. synthe-0.9.1/docs/t-logo.png +0 -0
  10. synthe-0.9.1/docs/t-logo2.png +0 -0
  11. synthe-0.9.1/docs/usage.md +7 -0
  12. synthe-0.9.1/pyproject.toml +85 -0
  13. synthe-0.9.1/setup.cfg +4 -0
  14. synthe-0.9.1/src/synthe/__init__.py +28 -0
  15. synthe-0.9.1/src/synthe/adaptivehistsampler.py +180 -0
  16. synthe-0.9.1/src/synthe/bayesiantweediesalesgenerator.py +466 -0
  17. synthe-0.9.1/src/synthe/conformal_inference.py +536 -0
  18. synthe-0.9.1/src/synthe/distro_simulator.py +1219 -0
  19. synthe-0.9.1/src/synthe/diversity_generator.py +196 -0
  20. synthe-0.9.1/src/synthe/empirical_copula.py +824 -0
  21. synthe-0.9.1/src/synthe/healthsims.py +283 -0
  22. synthe-0.9.1/src/synthe/helpers.py +342 -0
  23. synthe-0.9.1/src/synthe/meboot.py +500 -0
  24. synthe-0.9.1/src/synthe/metrics.py +179 -0
  25. synthe-0.9.1/src/synthe/row_subsampling.py +71 -0
  26. synthe-0.9.1/src/synthe/stratified_sampling.py +195 -0
  27. synthe-0.9.1/src/synthe/ts_distro_simulator.py +908 -0
  28. synthe-0.9.1/src/synthe/utils.py +364 -0
  29. synthe-0.9.1/src/synthe.egg-info/PKG-INFO +103 -0
  30. synthe-0.9.1/src/synthe.egg-info/SOURCES.txt +34 -0
  31. synthe-0.9.1/src/synthe.egg-info/dependency_links.txt +1 -0
  32. synthe-0.9.1/src/synthe.egg-info/entry_points.txt +2 -0
  33. synthe-0.9.1/src/synthe.egg-info/requires.txt +19 -0
  34. synthe-0.9.1/src/synthe.egg-info/top_level.txt +1 -0
  35. synthe-0.9.1/tests/__init__.py +1 -0
  36. synthe-0.9.1/tests/test_synthe.py +22 -0
@@ -0,0 +1,119 @@
1
+ # Contributing
2
+
3
+ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.
4
+
5
+ You can contribute in many ways:
6
+
7
+ ## Types of Contributions
8
+
9
+ ### Report Bugs
10
+
11
+ Report bugs at https://github.com/Techtonique/synthe/issues.
12
+
13
+ If you are reporting a bug, please include:
14
+
15
+ - Your operating system name and version.
16
+ - Any details about your local setup that might be helpful in troubleshooting.
17
+ - Detailed steps to reproduce the bug.
18
+
19
+ ### Fix Bugs
20
+
21
+ Look through the GitHub issues for bugs. Anything tagged with "bug" and "help wanted" is open to whoever wants to implement it.
22
+
23
+ ### Implement Features
24
+
25
+ Look through the GitHub issues for features. Anything tagged with "enhancement" and "help wanted" is open to whoever wants to implement it.
26
+
27
+ ### Write Documentation
28
+
29
+ synthe could always use more documentation, whether as part of the official docs, in docstrings, or even on the web in blog posts, articles, and such.
30
+
31
+ ### Submit Feedback
32
+
33
+ The best way to send feedback is to file an issue at https://github.com/Techtonique/synthe/issues.
34
+
35
+ If you are proposing a feature:
36
+
37
+ - Explain in detail how it would work.
38
+ - Keep the scope as narrow as possible, to make it easier to implement.
39
+ - Remember that this is a volunteer-driven project, and that contributions are welcome :)
40
+
41
+ ## Get Started!
42
+
43
+ Ready to contribute? Here's how to set up `synthe` for local development.
44
+
45
+ 1. Fork the `synthe` repo on GitHub.
46
+ 2. Clone your fork locally:
47
+
48
+ ```sh
49
+ git clone git@github.com:your_name_here/synthe.git
50
+ ```
51
+
52
+ 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:
53
+
54
+ ```sh
55
+ mkvirtualenv synthe
56
+ cd synthe/
57
+ python setup.py develop
58
+ ```
59
+
60
+ 4. Create a branch for local development:
61
+
62
+ ```sh
63
+ git checkout -b name-of-your-bugfix-or-feature
64
+ ```
65
+
66
+ Now you can make your changes locally.
67
+
68
+ 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:
69
+
70
+ ```sh
71
+ make lint
72
+ make test
73
+ # Or
74
+ make test-all
75
+ ```
76
+
77
+ To get flake8 and tox, just pip install them into your virtualenv.
78
+
79
+ 6. Commit your changes and push your branch to GitHub:
80
+
81
+ ```sh
82
+ git add .
83
+ git commit -m "Your detailed description of your changes."
84
+ git push origin name-of-your-bugfix-or-feature
85
+ ```
86
+
87
+ 7. Submit a pull request through the GitHub website.
88
+
89
+ ## Pull Request Guidelines
90
+
91
+ Before you submit a pull request, check that it meets these guidelines:
92
+
93
+ 1. The pull request should include tests.
94
+ 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.md.
95
+ 3. The pull request should work for Python 3.12 and 3.13. Tests run in GitHub Actions on every pull request to the main branch, make sure that the tests pass for all supported Python versions.
96
+
97
+ ## Tips
98
+
99
+ To run a subset of tests:
100
+
101
+ ```sh
102
+ pytest tests.test_synthe
103
+ ```
104
+
105
+ ## Deploying
106
+
107
+ A reminder for the maintainers on how to deploy. Make sure all your changes are committed (including an entry in HISTORY.md). Then run:
108
+
109
+ ```sh
110
+ bump2version patch # possible: major / minor / patch
111
+ git push
112
+ git push --tags
113
+ ```
114
+
115
+ You can set up a [GitHub Actions workflow](https://docs.github.com/en/actions/use-cases-and-examples/building-and-testing/building-and-testing-python#publishing-to-pypi) to automatically deploy your package to PyPI when you push a new tag.
116
+
117
+ ## Code of Conduct
118
+
119
+ Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
@@ -0,0 +1,5 @@
1
+ # History
2
+
3
+ ## 0.1.0 (2025-09-27)
4
+
5
+ * First release on PyPI.
synthe-0.9.1/LICENSE ADDED
@@ -0,0 +1,32 @@
1
+ The Clear BSD License
2
+
3
+ Copyright (c) [2025] [T. Moudiki]
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted (subject to the limitations in the disclaimer
8
+ below) provided that the following conditions are met:
9
+
10
+ * Redistributions of source code must retain the above copyright notice,
11
+ this list of conditions and the following disclaimer.
12
+
13
+ * Redistributions in binary form must reproduce the above copyright
14
+ notice, this list of conditions and the following disclaimer in the
15
+ documentation and/or other materials provided with the distribution.
16
+
17
+ * Neither the name of the copyright holder nor the names of its
18
+ contributors may be used to endorse or promote products derived from this
19
+ software without specific prior written permission.
20
+
21
+ NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
22
+ THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
23
+ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
25
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
26
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
29
+ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
30
+ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
+ POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,10 @@
1
+ include CONTRIBUTING.md
2
+ include HISTORY.md
3
+ include LICENSE
4
+ include README.md
5
+
6
+ recursive-include tests *
7
+ recursive-exclude * __pycache__
8
+ recursive-exclude * *.py[co]
9
+
10
+ recursive-include docs *.md Makefile *.jpg *.png *.gif
synthe-0.9.1/PKG-INFO ADDED
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: synthe
3
+ Version: 0.9.1
4
+ Summary: synthetic simulation
5
+ Author-email: "T. Moudiki" <thierry.moudiki@gmail.com>
6
+ Maintainer-email: "T. Moudiki" <thierry.moudiki@gmail.com>
7
+ License: The Clear BSD License
8
+
9
+ Copyright (c) [2025] [T. Moudiki]
10
+ All rights reserved.
11
+
12
+ Redistribution and use in source and binary forms, with or without
13
+ modification, are permitted (subject to the limitations in the disclaimer
14
+ below) provided that the following conditions are met:
15
+
16
+ * Redistributions of source code must retain the above copyright notice,
17
+ this list of conditions and the following disclaimer.
18
+
19
+ * Redistributions in binary form must reproduce the above copyright
20
+ notice, this list of conditions and the following disclaimer in the
21
+ documentation and/or other materials provided with the distribution.
22
+
23
+ * Neither the name of the copyright holder nor the names of its
24
+ contributors may be used to endorse or promote products derived from this
25
+ software without specific prior written permission.
26
+
27
+ NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
28
+ THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
29
+ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
31
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
32
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
33
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
34
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35
+ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
36
+ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38
+ POSSIBILITY OF SUCH DAMAGE.
39
+ Project-URL: bugs, https://github.com/Techtonique/synthe/issues
40
+ Project-URL: changelog, https://github.com/Techtonique/synthe/blob/master/changelog.md
41
+ Project-URL: homepage, https://github.com/Techtonique/synthe
42
+ Classifier: Development Status :: 4 - Beta
43
+ Classifier: Intended Audience :: Science/Research
44
+ Classifier: Intended Audience :: Developers
45
+ Classifier: License :: OSI Approved :: BSD License
46
+ Classifier: Operating System :: MacOS
47
+ Classifier: Operating System :: Microsoft :: Windows
48
+ Classifier: Operating System :: POSIX
49
+ Classifier: Programming Language :: Python :: 3.10
50
+ Classifier: Programming Language :: Python :: 3.11
51
+ Classifier: Programming Language :: Python :: 3.12
52
+ Classifier: Topic :: Software Development
53
+ Classifier: Topic :: Scientific/Engineering
54
+ Requires-Python: >=3.10
55
+ Description-Content-Type: text/markdown
56
+ License-File: LICENSE
57
+ Requires-Dist: numpy
58
+ Requires-Dist: matplotlib
59
+ Requires-Dist: nnetsauce
60
+ Requires-Dist: GPopt
61
+ Requires-Dist: tqdm
62
+ Requires-Dist: properscoring
63
+ Requires-Dist: optuna
64
+ Requires-Dist: wordcloud
65
+ Requires-Dist: seaborn
66
+ Provides-Extra: dev
67
+ Requires-Dist: black[jupyter]; extra == "dev"
68
+ Requires-Dist: build; extra == "dev"
69
+ Requires-Dist: Cython>=3.0.10; extra == "dev"
70
+ Requires-Dist: pytest; extra == "dev"
71
+ Requires-Dist: ruff; extra == "dev"
72
+ Requires-Dist: setuptools-scm>=8; extra == "dev"
73
+ Requires-Dist: black[jupyter]; extra == "dev"
74
+ Requires-Dist: build; extra == "dev"
75
+ Requires-Dist: Cython>=3.0.10; extra == "dev"
76
+ Requires-Dist: pytest; extra == "dev"
77
+ Requires-Dist: ruff; extra == "dev"
78
+ Requires-Dist: setuptools-scm>=8; extra == "dev"
79
+ Requires-Dist: sphinx; extra == "dev"
80
+ Requires-Dist: furo; extra == "dev"
81
+ Dynamic: license-file
82
+
83
+ # synthe
84
+
85
+ <hr>
86
+
87
+ A Python package for
88
+ **synthetic data generation/simulation**
89
+
90
+ ![PyPI](https://img.shields.io/pypi/v/synthe) [![PyPI - License](https://img.shields.io/pypi/l/synthe)](LICENSE) [![Downloads](https://pepy.tech/badge/synthe)](https://pepy.tech/project/synthe)
91
+ [![Documentation](https://img.shields.io/badge/documentation-is_here-green)](https://techtonique.github.io/synthe/)
92
+
93
+
94
+ ## Features
95
+
96
+ - Generate synthetic data that preserves the statistical properties of the original dataset.
97
+ - Generate realistic synthetic data for various applications.
98
+
99
+ See [examples](examples/) for usage.
100
+
101
+ ## Credits
102
+
103
+ This package was created with [Cookiecutter](https://github.com/audreyfeldroy/cookiecutter) and the [audreyfeldroy/cookiecutter-pypackage](https://github.com/audreyfeldroy/cookiecutter-pypackage) project template.
synthe-0.9.1/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # synthe
2
+
3
+ <hr>
4
+
5
+ A Python package for
6
+ **synthetic data generation/simulation**
7
+
8
+ ![PyPI](https://img.shields.io/pypi/v/synthe) [![PyPI - License](https://img.shields.io/pypi/l/synthe)](LICENSE) [![Downloads](https://pepy.tech/badge/synthe)](https://pepy.tech/project/synthe)
9
+ [![Documentation](https://img.shields.io/badge/documentation-is_here-green)](https://techtonique.github.io/synthe/)
10
+
11
+
12
+ ## Features
13
+
14
+ - Generate synthetic data that preserves the statistical properties of the original dataset.
15
+ - Generate realistic synthetic data for various applications.
16
+
17
+ See [examples](examples/) for usage.
18
+
19
+ ## Credits
20
+
21
+ This package was created with [Cookiecutter](https://github.com/audreyfeldroy/cookiecutter) and the [audreyfeldroy/cookiecutter-pypackage](https://github.com/audreyfeldroy/cookiecutter-pypackage) project template.
@@ -0,0 +1,16 @@
1
+ # Welcome to synthe's documentation!
2
+
3
+ ## Contents
4
+
5
+ - [Readme](readme.md)
6
+ - [Installation](installation.md)
7
+ - [Usage](usage.md)
8
+ - [Modules](modules.md)
9
+ - [Contributing](contributing.md)
10
+ - [History](history.md)
11
+
12
+ ## Indices and tables
13
+
14
+ - [Index](genindex)
15
+ - [Module Index](modindex)
16
+ - [Search](search)
@@ -0,0 +1,38 @@
1
+ # Installation
2
+
3
+ ## Stable release
4
+
5
+ To install synthe, run this command in your terminal:
6
+
7
+ ```sh
8
+ uv add synthe
9
+ ```
10
+
11
+ Or if you prefer to use `pip`:
12
+
13
+ ```sh
14
+ pip install synthe
15
+ ```
16
+
17
+ ## From source
18
+
19
+ The source files for synthe can be downloaded from the [Github repo](https://github.com/Techtonique/synthe).
20
+
21
+ You can either clone the public repository:
22
+
23
+ ```sh
24
+ git clone git://github.com/Techtonique/synthe
25
+ ```
26
+
27
+ Or download the [tarball](https://github.com/Techtonique/synthe/tarball/master):
28
+
29
+ ```sh
30
+ curl -OJL https://github.com/Techtonique/synthe/tarball/master
31
+ ```
32
+
33
+ Once you have a copy of the source, you can install it with:
34
+
35
+ ```sh
36
+ cd synthe
37
+ uv pip install .
38
+ ```
Binary file
Binary file
@@ -0,0 +1,7 @@
1
+ # Usage
2
+
3
+ To use synthe in a project:
4
+
5
+ ```python
6
+ import synthe
7
+ ```
@@ -0,0 +1,85 @@
1
+ [project]
2
+ name = "synthe"
3
+ version = "0.9.1"
4
+ description = "synthetic simulation"
5
+ readme = "README.md"
6
+ authors = [
7
+ {name = "T. Moudiki", email = "thierry.moudiki@gmail.com"}
8
+ ]
9
+ maintainers = [
10
+ {name = "T. Moudiki", email = "thierry.moudiki@gmail.com"}
11
+ ]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Science/Research",
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: BSD License",
17
+ "Operating System :: MacOS",
18
+ "Operating System :: Microsoft :: Windows",
19
+ "Operating System :: POSIX",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Topic :: Software Development",
24
+ "Topic :: Scientific/Engineering"
25
+ ]
26
+ license = {file = "LICENSE"}
27
+ dependencies = [
28
+ "numpy",
29
+ "matplotlib",
30
+ "nnetsauce",
31
+ "GPopt",
32
+ "tqdm",
33
+ "properscoring",
34
+ "optuna",
35
+ "wordcloud",
36
+ "seaborn"
37
+ ]
38
+ requires-python = ">= 3.10"
39
+
40
+ [project.optional-dependencies]
41
+ dev = [
42
+ "black[jupyter]",
43
+ "build",
44
+ "Cython>=3.0.10",
45
+ "pytest",
46
+ "ruff",
47
+ "setuptools-scm>=8",
48
+ "black[jupyter]",
49
+ "build",
50
+ "Cython>=3.0.10",
51
+ "pytest",
52
+ "ruff",
53
+ "setuptools-scm>=8",
54
+ "sphinx", # ✅ add this
55
+ "furo", # ✅ optional: for dark mode
56
+ ]
57
+
58
+ [project.urls]
59
+ bugs = "https://github.com/Techtonique/synthe/issues"
60
+ changelog = "https://github.com/Techtonique/synthe/blob/master/changelog.md"
61
+ homepage = "https://github.com/Techtonique/synthe"
62
+
63
+ [project.scripts]
64
+ synthe = "synthe.cli:app"
65
+
66
+ [tool.ty]
67
+ # All rules are enabled as "error" by default; no need to specify unless overriding.
68
+ # Example override: relax a rule for the entire project (uncomment if needed).
69
+ # rules.TY015 = "warn" # For invalid-argument-type, warn instead of error.
70
+
71
+ [tool.ruff]
72
+ line-length = 120
73
+
74
+ [tool.ruff.lint]
75
+ select = [
76
+ "E", # pycodestyle errors
77
+ "W", # pycodestyle warnings
78
+ "F", # Pyflakes
79
+ "I", # isort
80
+ "B", # flake8-bugbear
81
+ "UP", # pyupgrade
82
+ ]
83
+
84
+ [tool.uv]
85
+ package = true
synthe-0.9.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,28 @@
1
+ """Top-level package for synthe."""
2
+
3
+ __author__ = """T. Moudiki"""
4
+ __email__ = "thierry.moudiki@gmail.com"
5
+
6
+ from .adaptivehistsampler import AdaptiveHistogramSampler # noqa: F401
7
+ from .distro_simulator import DistroSimulator # noqa: F401
8
+ from .empirical_copula import EmpiricalCopula # noqa: F401
9
+ from .stratified_sampling import StratifiedClusteringSubsampling
10
+ from .row_subsampling import SubSampler
11
+ from .healthsims import SmartHealthSimulator # noqa: F401
12
+ from .metrics import DistanceMetrics # noqa: F401
13
+ from .meboot import MaximumEntropyBootstrap
14
+ from .ts_distro_simulator import TsDistroSimulator # noqa: F401
15
+ from .diversity_generator import DiversityGenerator # noqa: F401
16
+
17
+ __all__ = [
18
+ "AdaptiveHistogramSampler",
19
+ "DistroSimulator",
20
+ "EmpiricalCopula",
21
+ "StratifiedClusteringSubsampling",
22
+ "SubSampler",
23
+ "SmartHealthSimulator",
24
+ "DistanceMetrics",
25
+ "MaximumEntropyBootstrap",
26
+ "TsDistroSimulator",
27
+ "DiversityGenerator",
28
+ ]
@@ -0,0 +1,180 @@
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ from scipy import stats
4
+
5
+
6
+ class AdaptiveHistogramSampler:
7
+ def __init__(self, n_bins=10, method="quantile", seed=123):
8
+ self.n_bins = n_bins
9
+ self.method = method
10
+ self.rng = np.random.default_rng(seed)
11
+ self.bin_edges = None
12
+ self.bin_indices = None
13
+ self.unique_bins = None
14
+ self.bin_probs = None
15
+ self.X = None
16
+ self.n = None
17
+ self.d = None
18
+
19
+ def fit(self, X):
20
+ self.X = np.asarray(X)
21
+ self.n, self.d = self.X.shape
22
+
23
+ self.bin_edges = []
24
+ for j in range(self.d):
25
+ xj = self.X[:, j]
26
+ if self.method == "quantile":
27
+ edges_j = np.quantile(xj, np.linspace(0, 1, self.n_bins + 1))
28
+ else:
29
+ edges_j = np.linspace(xj.min(), xj.max(), self.n_bins + 1)
30
+ self.bin_edges.append(edges_j)
31
+
32
+ # Assign points to bins
33
+ bin_idx = np.zeros((self.n, self.d), dtype=int)
34
+ for j in range(self.d):
35
+ bin_idx[:, j] = np.digitize(self.X[:, j], self.bin_edges[j]) - 1
36
+ bin_idx[:, j] = np.clip(bin_idx[:, j], 0, self.n_bins - 1)
37
+ self.bin_indices = bin_idx
38
+
39
+ bin_ids = np.ravel_multi_index(
40
+ self.bin_indices.T, (self.n_bins,) * self.d
41
+ )
42
+ unique_bins, counts = np.unique(bin_ids, return_counts=True)
43
+ self.unique_bins = unique_bins
44
+ self.bin_probs = counts / counts.sum()
45
+
46
+ def sample(
47
+ self,
48
+ n_samples,
49
+ oversample=False,
50
+ oversample_method="bootstrap",
51
+ jitter_scale=0.05,
52
+ ):
53
+ if self.bin_probs is None:
54
+ raise RuntimeError("You must call `fit` before `sample`.")
55
+
56
+ chosen_bins = self.rng.choice(
57
+ self.unique_bins, size=n_samples, p=self.bin_probs
58
+ )
59
+
60
+ if not oversample:
61
+ return self._subsample_existing(chosen_bins)
62
+
63
+ if oversample_method == "uniform":
64
+ return self._oversample_uniform(chosen_bins)
65
+ elif oversample_method == "bootstrap":
66
+ return self._oversample_bootstrap(chosen_bins)
67
+ elif oversample_method == "jitter":
68
+ return self._oversample_jitter(chosen_bins, jitter_scale)
69
+ else:
70
+ raise ValueError(f"Unknown oversample_method: {oversample_method}")
71
+
72
+ # --- Internal helpers ------------------------------------------------
73
+ def _subsample_existing(self, chosen_bins):
74
+ bin_ids = np.ravel_multi_index(
75
+ self.bin_indices.T, (self.n_bins,) * self.d
76
+ )
77
+ X_sampled = []
78
+ for b in chosen_bins:
79
+ idx_in_bin = np.where(bin_ids == b)[0]
80
+ i = self.rng.choice(idx_in_bin)
81
+ X_sampled.append(self.X[i])
82
+ return np.array(X_sampled)
83
+
84
+ def _oversample_uniform(self, chosen_bins):
85
+ X_sampled = []
86
+ for b in chosen_bins:
87
+ multi_idx = np.unravel_index(b, (self.n_bins,) * self.d)
88
+ coords = []
89
+ for j, bi in enumerate(multi_idx):
90
+ left = self.bin_edges[j][bi]
91
+ right = self.bin_edges[j][bi + 1]
92
+ coords.append(self.rng.uniform(left, right))
93
+ X_sampled.append(coords)
94
+ return np.array(X_sampled)
95
+
96
+ def _oversample_bootstrap(self, chosen_bins):
97
+ return self._subsample_existing(chosen_bins)
98
+
99
+ def _oversample_jitter(self, chosen_bins, jitter_scale):
100
+ base_points = self._subsample_existing(chosen_bins)
101
+ noise = self.rng.normal(scale=jitter_scale, size=base_points.shape)
102
+ return base_points + noise
103
+
104
+ # --- Visualization ----------------------------------------------------
105
+ def plot_comparison(self, X_sampled, bins=30):
106
+ """Plot joint 2D histogram and marginal distributions (for d=2)."""
107
+ if self.d != 2:
108
+ raise ValueError("plot_comparison only supports 2D currently.")
109
+
110
+ fig = plt.figure(figsize=(10, 10))
111
+ grid = plt.GridSpec(4, 4, hspace=0.3, wspace=0.3)
112
+
113
+ main_ax = fig.add_subplot(grid[1:, :-1])
114
+ y_hist = fig.add_subplot(grid[0, :-1], sharex=main_ax)
115
+ x_hist = fig.add_subplot(grid[1:, -1], sharey=main_ax)
116
+
117
+ # 2D histogram
118
+ main_ax.hist2d(
119
+ self.X[:, 0], self.X[:, 1], bins=bins, alpha=0.5, cmap="Blues"
120
+ )
121
+ main_ax.hist2d(
122
+ X_sampled[:, 0], X_sampled[:, 1], bins=bins, alpha=0.5, cmap="Reds"
123
+ )
124
+ main_ax.set_xlabel("X1")
125
+ main_ax.set_ylabel("X2")
126
+ main_ax.set_title("Joint distribution")
127
+
128
+ # Marginals
129
+ y_hist.hist(
130
+ self.X[:, 0], bins=bins, color="blue", alpha=0.5, density=True
131
+ )
132
+ y_hist.hist(
133
+ X_sampled[:, 0], bins=bins, color="red", alpha=0.5, density=True
134
+ )
135
+ x_hist.hist(
136
+ self.X[:, 1],
137
+ bins=bins,
138
+ orientation="horizontal",
139
+ color="blue",
140
+ alpha=0.5,
141
+ density=True,
142
+ )
143
+ x_hist.hist(
144
+ X_sampled[:, 1],
145
+ bins=bins,
146
+ orientation="horizontal",
147
+ color="red",
148
+ alpha=0.5,
149
+ density=True,
150
+ )
151
+
152
+ y_hist.axis("off")
153
+ x_hist.axis("off")
154
+
155
+ plt.show()
156
+
157
+ # --- Goodness of fit tests -------------------------------------------
158
+ def goodness_of_fit(self, X_sampled):
159
+ """
160
+ Compare marginals with Kolmogorov–Smirnov and Anderson–Darling tests.
161
+ Returns dict of test results for each dimension.
162
+ """
163
+ results = {}
164
+ for j in range(self.d):
165
+ x_orig = self.X[:, j]
166
+ x_samp = X_sampled[:, j]
167
+
168
+ # KS test
169
+ ks_stat, ks_p = stats.ks_2samp(x_orig, x_samp)
170
+
171
+ # Anderson-Darling test
172
+ ad_result = stats.anderson_ksamp([x_orig, x_samp])
173
+
174
+ results[f"dim_{j}"] = {
175
+ "ks_statistic": ks_stat,
176
+ "ks_pvalue": ks_p,
177
+ "ad_statistic": ad_result.statistic,
178
+ "ad_significance_level": ad_result.significance_level,
179
+ }
180
+ return results