distparser 0.2.0__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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Juyoung Choi
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.
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: distparser
3
+ Version: 0.2.0
4
+ Summary: Parse function-call strings into frozen scipy.stats distributions
5
+ Author-email: Juyoung Choi <njuyoung35@gmail.com>
6
+ Maintainer-email: Juyoung Choi <njuyoung35@gmail.com>
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/njuyoung35/distparser
9
+ Project-URL: Repository, https://github.com/njuyoung35/distparser
10
+ Project-URL: Documentation, https://distparser.readthedocs.io
11
+ Keywords: scipy,distribution,parsing,rvs
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Intended Audience :: Science/Research
16
+ Requires-Python: <3.14,>=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: scipy>=1.7.0
20
+ Requires-Dist: numpy>=1.21.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7.0; extra == "dev"
23
+ Requires-Dist: pytest-cov; extra == "dev"
24
+ Requires-Dist: ruff; extra == "dev"
25
+ Requires-Dist: mypy; extra == "dev"
26
+ Requires-Dist: build; extra == "dev"
27
+ Requires-Dist: twine; extra == "dev"
28
+ Provides-Extra: docs
29
+ Requires-Dist: mkdocs>=1.5.0; extra == "docs"
30
+ Requires-Dist: mkdocs-rtd-theme>=2.0.0; extra == "docs"
31
+ Requires-Dist: pymdown-extensions>=10.0; extra == "docs"
32
+ Dynamic: license-file
33
+
34
+ # distparser
35
+
36
+ **Parse function‑call syntax strings into frozen `scipy.stats` distributions**
37
+
38
+ [![PyPI version](https://badge.fury.io/py/distparser.svg)](https://badge.fury.io/py/distparser)
39
+ [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
40
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
41
+
42
+ ## Why `distparser`?
43
+
44
+ When you have configuration files or user input that specifies a probability
45
+ distribution (e.g. `"norm(loc=0, scale=1)"`), you want to turn that string
46
+ into a ready‑to‑sample object. `distparser` does exactly that, with a tiny
47
+ API and zero surprises.
48
+
49
+ ## Installation
50
+
51
+ ```bash
52
+ pip install distparser
53
+ ```
54
+
55
+ ## Quick Start
56
+
57
+ ```
58
+ from distparser import parse_dist
59
+
60
+ # Positional arguments (order matters)
61
+ dist = parse_dist("uniform(0, 1)")
62
+ sample = dist.rvs() # e.g. 0.374
63
+
64
+ # Keyword arguments (order ignored)
65
+ dist = parse_dist("norm(loc=0, scale=1)")
66
+ samples = dist.rvs(size=5) # array([-0.12, 1.03, ...])
67
+
68
+ # Mixed (positional + keyword) – works, but not recommended
69
+ dist = parse_dist("expon(scale=2, loc=1)")
70
+ ```
71
+
72
+ ## Supported Distributions
73
+
74
+ Built‑in registry covers the most common continuous distributions:
75
+
76
+ - `uniform(loc, scale)`
77
+ - `norm(loc, scale)`
78
+ - `expon(loc, scale)`
79
+ - … and many more (see [docs](https://distparser.readthedocs.io)).
80
+
81
+ You can **add your own** at runtime:
82
+
83
+ ```python
84
+ from distparser import register_distribution
85
+ from scipy.stats import gumbel_r
86
+
87
+ register_distribution("gumbel", gumbel_r, ["loc", "scale"])
88
+ ```
89
+
90
+ ## Development
91
+
92
+ See [AGENTS.md](AGENTS.md) for development setup and guidelines.
93
+
94
+ ## License
95
+
96
+ MIT
@@ -0,0 +1,63 @@
1
+ # distparser
2
+
3
+ **Parse function‑call syntax strings into frozen `scipy.stats` distributions**
4
+
5
+ [![PyPI version](https://badge.fury.io/py/distparser.svg)](https://badge.fury.io/py/distparser)
6
+ [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+
9
+ ## Why `distparser`?
10
+
11
+ When you have configuration files or user input that specifies a probability
12
+ distribution (e.g. `"norm(loc=0, scale=1)"`), you want to turn that string
13
+ into a ready‑to‑sample object. `distparser` does exactly that, with a tiny
14
+ API and zero surprises.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install distparser
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ```
25
+ from distparser import parse_dist
26
+
27
+ # Positional arguments (order matters)
28
+ dist = parse_dist("uniform(0, 1)")
29
+ sample = dist.rvs() # e.g. 0.374
30
+
31
+ # Keyword arguments (order ignored)
32
+ dist = parse_dist("norm(loc=0, scale=1)")
33
+ samples = dist.rvs(size=5) # array([-0.12, 1.03, ...])
34
+
35
+ # Mixed (positional + keyword) – works, but not recommended
36
+ dist = parse_dist("expon(scale=2, loc=1)")
37
+ ```
38
+
39
+ ## Supported Distributions
40
+
41
+ Built‑in registry covers the most common continuous distributions:
42
+
43
+ - `uniform(loc, scale)`
44
+ - `norm(loc, scale)`
45
+ - `expon(loc, scale)`
46
+ - … and many more (see [docs](https://distparser.readthedocs.io)).
47
+
48
+ You can **add your own** at runtime:
49
+
50
+ ```python
51
+ from distparser import register_distribution
52
+ from scipy.stats import gumbel_r
53
+
54
+ register_distribution("gumbel", gumbel_r, ["loc", "scale"])
55
+ ```
56
+
57
+ ## Development
58
+
59
+ See [AGENTS.md](AGENTS.md) for development setup and guidelines.
60
+
61
+ ## License
62
+
63
+ MIT
@@ -0,0 +1,72 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "distparser"
7
+ version = "0.2.0"
8
+ description = "Parse function-call strings into frozen scipy.stats distributions"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ authors = [{name = "Juyoung Choi", email = "njuyoung35@gmail.com"}]
12
+ maintainers = [{name = "Juyoung Choi", email = "njuyoung35@gmail.com"}]
13
+ keywords = ["scipy", "distribution", "parsing", "rvs"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Intended Audience :: Science/Research",
19
+ ]
20
+ requires-python = ">=3.8,<3.14"
21
+ dependencies = [
22
+ "scipy>=1.7.0",
23
+ "numpy>=1.21.0",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/njuyoung35/distparser"
28
+ Repository = "https://github.com/njuyoung35/distparser"
29
+ Documentation = "https://distparser.readthedocs.io"
30
+
31
+ [project.optional-dependencies]
32
+ dev = [
33
+ "pytest>=7.0",
34
+ "pytest-cov",
35
+ "ruff",
36
+ "mypy",
37
+ "build",
38
+ "twine",
39
+ ]
40
+ docs = [
41
+ "mkdocs>=1.5.0",
42
+ "mkdocs-rtd-theme>=2.0.0",
43
+ "pymdown-extensions>=10.0",
44
+ ]
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
48
+
49
+ [tool.pytest.ini_options]
50
+ minversion = "7.0"
51
+ testpaths = ["tests"]
52
+ addopts = "-v --cov=src/distparser --cov-report=term-missing"
53
+
54
+ [tool.mypy]
55
+ python_version = "3.8"
56
+ strict = true
57
+ warn_return_any = true
58
+ warn_unused_configs = true
59
+ ignore_missing_imports = true
60
+
61
+ [tool.ruff]
62
+ line-length = 88
63
+ target-version = "py38"
64
+
65
+ [tool.ruff.lint]
66
+ select = ["E", "F", "I", "W"]
67
+
68
+ [tool.ruff.format]
69
+ quote-style = "double"
70
+ indent-style = "space"
71
+ skip-magic-trailing-comma = false
72
+ line-ending = "auto"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,21 @@
1
+ """distparser – parse function-call strings into frozen scipy.stats distributions."""
2
+
3
+ from distparser.core import (
4
+ REGISTRY,
5
+ DistParserError,
6
+ ParseError,
7
+ UnknownDistributionError,
8
+ parse_dist,
9
+ register_distribution,
10
+ )
11
+ from distparser.version import __version__
12
+
13
+ __all__ = [
14
+ "__version__",
15
+ "DistParserError",
16
+ "ParseError",
17
+ "UnknownDistributionError",
18
+ "REGISTRY",
19
+ "parse_dist",
20
+ "register_distribution",
21
+ ]
@@ -0,0 +1,205 @@
1
+ """Core parsing logic and distribution registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import re
7
+ from typing import Any
8
+
9
+ from scipy.stats import (
10
+ beta,
11
+ cauchy,
12
+ chi2,
13
+ expon,
14
+ f,
15
+ gamma,
16
+ laplace,
17
+ logistic,
18
+ lognorm,
19
+ norm,
20
+ pareto,
21
+ rayleigh,
22
+ t,
23
+ uniform,
24
+ weibull_min,
25
+ )
26
+
27
+ __all__ = [
28
+ "DistParserError",
29
+ "ParseError",
30
+ "UnknownDistributionError",
31
+ "REGISTRY",
32
+ "parse_dist",
33
+ "register_distribution",
34
+ ]
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Exceptions
39
+ # ---------------------------------------------------------------------------
40
+
41
+
42
+ class DistParserError(Exception):
43
+ """Base exception for all distparser errors."""
44
+
45
+
46
+ class ParseError(DistParserError):
47
+ """Raised when a distribution string cannot be parsed."""
48
+
49
+
50
+ class UnknownDistributionError(DistParserError):
51
+ """Raised when a distribution name is not in the registry."""
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Registry
56
+ # ---------------------------------------------------------------------------
57
+
58
+ REGISTRY: dict[str, dict[str, Any]] = {
59
+ # Shape-parameter distributions (alphabetical)
60
+ "beta": {"class": beta, "param_order": ["a", "b", "loc", "scale"]},
61
+ "chi2": {"class": chi2, "param_order": ["df", "loc", "scale"]},
62
+ "f": {"class": f, "param_order": ["dfn", "dfd", "loc", "scale"]},
63
+ "gamma": {"class": gamma, "param_order": ["a", "loc", "scale"]},
64
+ "lognorm": {"class": lognorm, "param_order": ["s", "loc", "scale"]},
65
+ "pareto": {"class": pareto, "param_order": ["b", "loc", "scale"]},
66
+ "t": {"class": t, "param_order": ["df", "loc", "scale"]},
67
+ "weibull_min": {"class": weibull_min, "param_order": ["c", "loc", "scale"]},
68
+ # Loc/scale-only distributions (alphabetical)
69
+ "cauchy": {"class": cauchy, "param_order": ["loc", "scale"]},
70
+ "expon": {"class": expon, "param_order": ["loc", "scale"]},
71
+ "laplace": {"class": laplace, "param_order": ["loc", "scale"]},
72
+ "logistic": {"class": logistic, "param_order": ["loc", "scale"]},
73
+ "norm": {"class": norm, "param_order": ["loc", "scale"]},
74
+ "rayleigh": {"class": rayleigh, "param_order": ["loc", "scale"]},
75
+ "uniform": {"class": uniform, "param_order": ["loc", "scale"]},
76
+ }
77
+
78
+
79
+ def register_distribution(
80
+ name: str,
81
+ dist_class: Any,
82
+ param_order: list[str],
83
+ ) -> None:
84
+ """Register a new distribution in the global registry.
85
+
86
+ Args:
87
+ name: Name used in parse strings (e.g. ``"gumbel"``).
88
+ dist_class: A scipy.stats distribution class.
89
+ param_order: Ordered list of parameter names for positional arguments.
90
+ """
91
+ REGISTRY[name] = {"class": dist_class, "param_order": list(param_order)}
92
+
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # Argument splitting (comma-aware, quote-safe)
96
+ # ---------------------------------------------------------------------------
97
+
98
+
99
+ def _split_args(args_str: str) -> list[str]:
100
+ """Split *args_str* on commas, respecting single- and double-quoted regions.
101
+
102
+ Empty parts are filtered out so that ``"norm()"`` yields ``[]``.
103
+ """
104
+ parts: list[str] = []
105
+ current: list[str] = []
106
+ in_single = False
107
+ in_double = False
108
+
109
+ for ch in args_str:
110
+ if ch == "'" and not in_double:
111
+ in_single = not in_single
112
+ current.append(ch)
113
+ elif ch == '"' and not in_single:
114
+ in_double = not in_double
115
+ current.append(ch)
116
+ elif ch == "," and not in_single and not in_double:
117
+ parts.append("".join(current).strip())
118
+ current = []
119
+ else:
120
+ current.append(ch)
121
+
122
+ parts.append("".join(current).strip())
123
+ return [p for p in parts if p]
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # Public API
128
+ # ---------------------------------------------------------------------------
129
+
130
+ _NAME_RE = re.compile(r"^([a-zA-Z_][a-zA-Z0-9_]*)\s*\((.*)\)$")
131
+
132
+
133
+ def parse_dist(s: str) -> Any:
134
+ """Parse a function-call string into a frozen ``scipy.stats`` distribution.
135
+
136
+ Args:
137
+ s: A string like ``"norm(loc=0, scale=1)"`` or ``"uniform(0, 1)"``.
138
+
139
+ Returns:
140
+ A frozen scipy.stats distribution object (callable for ``.rvs()``).
141
+
142
+ Raises:
143
+ ParseError: If the string cannot be parsed.
144
+ UnknownDistributionError: If the distribution name is not registered.
145
+
146
+ Examples:
147
+ >>> from distparser import parse_dist
148
+ >>> d = parse_dist("norm(loc=0, scale=1)")
149
+ >>> d.rvs(size=3) # doctest: +SKIP
150
+ array([...])
151
+ """
152
+ s = s.strip()
153
+ m = _NAME_RE.match(s)
154
+ if not m:
155
+ raise ParseError(f"Cannot parse {s!r}. Expected format: 'name(args)'.")
156
+
157
+ name = m.group(1)
158
+ if name not in REGISTRY:
159
+ raise UnknownDistributionError(
160
+ f"Unknown distribution {name!r}. Registered: {', '.join(sorted(REGISTRY))}."
161
+ )
162
+
163
+ entry = REGISTRY[name]
164
+ dist_class = entry["class"]
165
+ param_order: list[str] = entry["param_order"]
166
+
167
+ raw_args = _split_args(m.group(2))
168
+
169
+ # Separate positional values from keyword assignments
170
+ positional: list[Any] = []
171
+ keyword: dict[str, Any] = {}
172
+
173
+ for arg in raw_args:
174
+ arg = arg.strip()
175
+ if "=" in arg:
176
+ key, val_str = arg.split("=", 1)
177
+ key = key.strip()
178
+ val_str = val_str.strip()
179
+ keyword[key] = _eval_arg(val_str, s)
180
+ else:
181
+ positional.append(_eval_arg(arg, s))
182
+
183
+ # Build final parameter dict: positional first, keywords override
184
+ params: dict[str, Any] = {}
185
+ for i, value in enumerate(positional):
186
+ if i >= len(param_order):
187
+ raise ParseError(
188
+ f"Too many positional arguments in {s!r}. "
189
+ f"{name!r} accepts at most {len(param_order)} "
190
+ f"positional args: {', '.join(param_order)}."
191
+ )
192
+ params[param_order[i]] = value
193
+
194
+ params.update(keyword)
195
+
196
+ return dist_class(**params)
197
+
198
+
199
+ def _eval_arg(raw: str, full_str: str) -> Any:
200
+ """Evaluate a single argument value via ``ast.literal_eval``, with a
201
+ helpful error message on failure."""
202
+ try:
203
+ return ast.literal_eval(raw)
204
+ except (ValueError, SyntaxError) as exc:
205
+ raise ParseError(f"Cannot evaluate {raw!r} in {full_str!r}: {exc}") from exc
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: distparser
3
+ Version: 0.2.0
4
+ Summary: Parse function-call strings into frozen scipy.stats distributions
5
+ Author-email: Juyoung Choi <njuyoung35@gmail.com>
6
+ Maintainer-email: Juyoung Choi <njuyoung35@gmail.com>
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/njuyoung35/distparser
9
+ Project-URL: Repository, https://github.com/njuyoung35/distparser
10
+ Project-URL: Documentation, https://distparser.readthedocs.io
11
+ Keywords: scipy,distribution,parsing,rvs
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Intended Audience :: Science/Research
16
+ Requires-Python: <3.14,>=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: scipy>=1.7.0
20
+ Requires-Dist: numpy>=1.21.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7.0; extra == "dev"
23
+ Requires-Dist: pytest-cov; extra == "dev"
24
+ Requires-Dist: ruff; extra == "dev"
25
+ Requires-Dist: mypy; extra == "dev"
26
+ Requires-Dist: build; extra == "dev"
27
+ Requires-Dist: twine; extra == "dev"
28
+ Provides-Extra: docs
29
+ Requires-Dist: mkdocs>=1.5.0; extra == "docs"
30
+ Requires-Dist: mkdocs-rtd-theme>=2.0.0; extra == "docs"
31
+ Requires-Dist: pymdown-extensions>=10.0; extra == "docs"
32
+ Dynamic: license-file
33
+
34
+ # distparser
35
+
36
+ **Parse function‑call syntax strings into frozen `scipy.stats` distributions**
37
+
38
+ [![PyPI version](https://badge.fury.io/py/distparser.svg)](https://badge.fury.io/py/distparser)
39
+ [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
40
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
41
+
42
+ ## Why `distparser`?
43
+
44
+ When you have configuration files or user input that specifies a probability
45
+ distribution (e.g. `"norm(loc=0, scale=1)"`), you want to turn that string
46
+ into a ready‑to‑sample object. `distparser` does exactly that, with a tiny
47
+ API and zero surprises.
48
+
49
+ ## Installation
50
+
51
+ ```bash
52
+ pip install distparser
53
+ ```
54
+
55
+ ## Quick Start
56
+
57
+ ```
58
+ from distparser import parse_dist
59
+
60
+ # Positional arguments (order matters)
61
+ dist = parse_dist("uniform(0, 1)")
62
+ sample = dist.rvs() # e.g. 0.374
63
+
64
+ # Keyword arguments (order ignored)
65
+ dist = parse_dist("norm(loc=0, scale=1)")
66
+ samples = dist.rvs(size=5) # array([-0.12, 1.03, ...])
67
+
68
+ # Mixed (positional + keyword) – works, but not recommended
69
+ dist = parse_dist("expon(scale=2, loc=1)")
70
+ ```
71
+
72
+ ## Supported Distributions
73
+
74
+ Built‑in registry covers the most common continuous distributions:
75
+
76
+ - `uniform(loc, scale)`
77
+ - `norm(loc, scale)`
78
+ - `expon(loc, scale)`
79
+ - … and many more (see [docs](https://distparser.readthedocs.io)).
80
+
81
+ You can **add your own** at runtime:
82
+
83
+ ```python
84
+ from distparser import register_distribution
85
+ from scipy.stats import gumbel_r
86
+
87
+ register_distribution("gumbel", gumbel_r, ["loc", "scale"])
88
+ ```
89
+
90
+ ## Development
91
+
92
+ See [AGENTS.md](AGENTS.md) for development setup and guidelines.
93
+
94
+ ## License
95
+
96
+ MIT
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/distparser/__init__.py
5
+ src/distparser/core.py
6
+ src/distparser/version.py
7
+ src/distparser.egg-info/PKG-INFO
8
+ src/distparser.egg-info/SOURCES.txt
9
+ src/distparser.egg-info/dependency_links.txt
10
+ src/distparser.egg-info/requires.txt
11
+ src/distparser.egg-info/top_level.txt
12
+ tests/test_core.py
@@ -0,0 +1,15 @@
1
+ scipy>=1.7.0
2
+ numpy>=1.21.0
3
+
4
+ [dev]
5
+ pytest>=7.0
6
+ pytest-cov
7
+ ruff
8
+ mypy
9
+ build
10
+ twine
11
+
12
+ [docs]
13
+ mkdocs>=1.5.0
14
+ mkdocs-rtd-theme>=2.0.0
15
+ pymdown-extensions>=10.0
@@ -0,0 +1 @@
1
+ distparser
@@ -0,0 +1,242 @@
1
+ """Tests for distparser.core."""
2
+
3
+ import pytest
4
+ from scipy.stats import expon, norm, uniform
5
+
6
+ from distparser.core import (
7
+ REGISTRY,
8
+ DistParserError,
9
+ ParseError,
10
+ UnknownDistributionError,
11
+ parse_dist,
12
+ register_distribution,
13
+ )
14
+
15
+ # ---------------------------------------------------------------------------
16
+ # Registry
17
+ # ---------------------------------------------------------------------------
18
+
19
+
20
+ class TestRegistry:
21
+ def test_builtin_entries(self):
22
+ assert "uniform" in REGISTRY
23
+ assert "norm" in REGISTRY
24
+ assert "expon" in REGISTRY
25
+
26
+ def test_builtin_classes(self):
27
+ assert REGISTRY["uniform"]["class"] is uniform
28
+ assert REGISTRY["norm"]["class"] is norm
29
+ assert REGISTRY["expon"]["class"] is expon
30
+
31
+ def test_builtin_param_orders(self):
32
+ assert REGISTRY["uniform"]["param_order"] == ["loc", "scale"]
33
+ assert REGISTRY["norm"]["param_order"] == ["loc", "scale"]
34
+ assert REGISTRY["expon"]["param_order"] == ["loc", "scale"]
35
+
36
+
37
+ class TestRegisterDistribution:
38
+ def test_adds_to_registry(self):
39
+ register_distribution("_test", uniform, ["loc", "scale"])
40
+ assert "_test" in REGISTRY
41
+ assert REGISTRY["_test"]["class"] is uniform
42
+ assert REGISTRY["_test"]["param_order"] == ["loc", "scale"]
43
+
44
+ def test_custom_distribution_is_usable(self):
45
+ from scipy.stats import gamma
46
+
47
+ register_distribution("_gamma_test", gamma, ["a", "loc", "scale"])
48
+ d = parse_dist("_gamma_test(2.0, loc=0, scale=1.5)")
49
+ assert abs(d.kwds["a"] - 2.0) < 1e-12
50
+ assert abs(d.kwds["scale"] - 1.5) < 1e-12
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # parse_dist – success cases
55
+ # ---------------------------------------------------------------------------
56
+
57
+
58
+ class TestParseDistPositional:
59
+ def test_all_positional(self):
60
+ d = parse_dist("uniform(0, 1)")
61
+ assert abs(d.kwds["loc"] - 0.0) < 1e-12
62
+ assert abs(d.kwds["scale"] - 1.0) < 1e-12
63
+
64
+ def test_partial_positional(self):
65
+ d = parse_dist("uniform(5)")
66
+ # Only explicitly passed args appear in kwds
67
+ assert abs(d.kwds["loc"] - 5.0) < 1e-12
68
+ # scale is not in kwds; verify default (1.0) via std
69
+ assert abs(d.std() - 1.0 / (12**0.5)) < 1e-12
70
+
71
+
72
+ class TestParseDistKeyword:
73
+ def test_all_keyword(self):
74
+ d = parse_dist("norm(loc=0, scale=2)")
75
+ assert abs(d.kwds["loc"] - 0.0) < 1e-12
76
+ assert abs(d.kwds["scale"] - 2.0) < 1e-12
77
+
78
+ def test_keyword_order_independent(self):
79
+ d = parse_dist("norm(scale=3, loc=10)")
80
+ assert abs(d.kwds["loc"] - 10.0) < 1e-12
81
+ assert abs(d.kwds["scale"] - 3.0) < 1e-12
82
+
83
+
84
+ class TestParseDistMixed:
85
+ def test_keyword_overrides_positional(self):
86
+ d = parse_dist("uniform(0, loc=5)")
87
+ assert abs(d.kwds["loc"] - 5.0) < 1e-12
88
+
89
+ def test_partial_positional_plus_keyword(self):
90
+ d = parse_dist("expon(0.5, scale=3)")
91
+ assert abs(d.kwds["loc"] - 0.5) < 1e-12
92
+ assert abs(d.kwds["scale"] - 3.0) < 1e-12
93
+
94
+
95
+ class TestParseDistDefaults:
96
+ def test_no_args_uses_defaults(self):
97
+ d = parse_dist("uniform()")
98
+ # No explicitly passed args => kwds is empty; verify via stats
99
+ assert d.kwds == {}
100
+ # uniform(0, 1): mean = (0+1)/2 = 0.5, std = 1/sqrt(12)
101
+ assert abs(d.mean() - 0.5) < 1e-12
102
+ assert abs(d.std() - 1.0 / (12**0.5)) < 1e-12
103
+
104
+ def test_whitespace_handling(self):
105
+ d = parse_dist(" norm ( loc = 0 , scale = 1 ) ")
106
+ assert abs(d.kwds["loc"] - 0.0) < 1e-12
107
+ assert abs(d.kwds["scale"] - 1.0) < 1e-12
108
+
109
+
110
+ class TestParseDistCommaInQuotes:
111
+ def test_string_arg_with_comma(self):
112
+ d = parse_dist("uniform(0, '1,2,3')")
113
+ assert abs(d.kwds["loc"] - 0.0) < 1e-12
114
+
115
+ def test_keyword_string_with_comma(self):
116
+ d = parse_dist('uniform(loc="a,b", scale=5)')
117
+ assert d.kwds["loc"] == "a,b"
118
+ assert abs(d.kwds["scale"] - 5.0) < 1e-12
119
+
120
+
121
+ class TestParseDistReturnsFrozenDistribution:
122
+ def test_rvs_returns_array(self):
123
+ import numpy as np
124
+
125
+ d = parse_dist("norm(loc=0, scale=1)")
126
+ samples = d.rvs(size=10, random_state=42)
127
+ assert isinstance(samples, np.ndarray)
128
+ assert len(samples) == 10
129
+
130
+ def test_reproducible_with_seed(self):
131
+ d = parse_dist("norm(loc=0, scale=1)")
132
+ s1 = d.rvs(size=5, random_state=42)
133
+ s2 = d.rvs(size=5, random_state=42)
134
+ import numpy as np
135
+
136
+ assert np.array_equal(s1, s2)
137
+
138
+
139
+ class TestParseDistNewDistributions:
140
+ """Smoke tests: parse + rvs for each newly added distribution."""
141
+
142
+ def test_gamma(self):
143
+ d = parse_dist("gamma(2.0, loc=0, scale=1.5)")
144
+ assert abs(d.kwds["a"] - 2.0) < 1e-12
145
+ assert d.rvs(size=3, random_state=42).shape == (3,)
146
+
147
+ def test_beta(self):
148
+ d = parse_dist("beta(2, 5, loc=0, scale=1)")
149
+ assert d.rvs(size=3, random_state=42).shape == (3,)
150
+
151
+ def test_lognorm(self):
152
+ d = parse_dist("lognorm(0.5, loc=0, scale=2)")
153
+ assert abs(d.kwds["s"] - 0.5) < 1e-12
154
+
155
+ def test_weibull_min(self):
156
+ d = parse_dist("weibull_min(1.5, loc=0, scale=1)")
157
+ assert abs(d.kwds["c"] - 1.5) < 1e-12
158
+
159
+ def test_t(self):
160
+ d = parse_dist("t(10, loc=0, scale=1)")
161
+ assert abs(d.kwds["df"] - 10.0) < 1e-12
162
+
163
+ def test_chi2(self):
164
+ d = parse_dist("chi2(5, loc=0, scale=1)")
165
+ assert abs(d.kwds["df"] - 5.0) < 1e-12
166
+
167
+ def test_f(self):
168
+ d = parse_dist("f(4, 10, loc=0, scale=1)")
169
+ assert abs(d.kwds["dfn"] - 4.0) < 1e-12
170
+ assert abs(d.kwds["dfd"] - 10.0) < 1e-12
171
+
172
+ def test_pareto(self):
173
+ d = parse_dist("pareto(3, loc=0, scale=1)")
174
+ assert abs(d.kwds["b"] - 3.0) < 1e-12
175
+
176
+ def test_cauchy(self):
177
+ d = parse_dist("cauchy(loc=0, scale=1)")
178
+ assert d.rvs(size=3, random_state=42).shape == (3,)
179
+
180
+ def test_laplace(self):
181
+ d = parse_dist("laplace(loc=0, scale=2)")
182
+ assert abs(d.kwds["scale"] - 2.0) < 1e-12
183
+
184
+ def test_logistic(self):
185
+ d = parse_dist("logistic(loc=1, scale=3)")
186
+ assert abs(d.kwds["loc"] - 1.0) < 1e-12
187
+
188
+ def test_rayleigh(self):
189
+ d = parse_dist("rayleigh(loc=0, scale=1)")
190
+ assert d.rvs(size=3, random_state=42).shape == (3,)
191
+
192
+
193
+ # ---------------------------------------------------------------------------
194
+ # parse_dist – error cases
195
+ # ---------------------------------------------------------------------------
196
+
197
+
198
+ class TestParseDistErrors:
199
+ def test_empty_string(self):
200
+ with pytest.raises(ParseError, match="Cannot parse"):
201
+ parse_dist("")
202
+
203
+ def test_no_parens(self):
204
+ with pytest.raises(ParseError, match="Cannot parse"):
205
+ parse_dist("norm")
206
+
207
+ def test_only_name_and_parens_missing(self):
208
+ with pytest.raises(ParseError):
209
+ parse_dist("123(0, 1)")
210
+
211
+ def test_unknown_distribution(self):
212
+ with pytest.raises(UnknownDistributionError, match="xyzzy"):
213
+ parse_dist("xyzzy(0, 1)")
214
+
215
+ def test_unknown_dist_suggests_registered(self):
216
+ with pytest.raises(UnknownDistributionError, match="Registered"):
217
+ parse_dist("foobar(0)")
218
+
219
+ def test_too_many_positional(self):
220
+ with pytest.raises(ParseError, match="Too many positional"):
221
+ parse_dist("uniform(0, 1, 2, 3)")
222
+
223
+ def test_unclosed_quote(self):
224
+ with pytest.raises((ParseError, SyntaxError)):
225
+ parse_dist("uniform(0, 'hello)")
226
+
227
+ def test_garbage_input(self):
228
+ with pytest.raises(ParseError):
229
+ parse_dist("!!not valid!!")
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # Exception hierarchy
234
+ # ---------------------------------------------------------------------------
235
+
236
+
237
+ class TestExceptionHierarchy:
238
+ def test_parse_error_is_distparser_error(self):
239
+ assert issubclass(ParseError, DistParserError)
240
+
241
+ def test_unknown_distribution_is_distparser_error(self):
242
+ assert issubclass(UnknownDistributionError, DistParserError)