distparser 0.2.0__py3-none-any.whl

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.
distparser/__init__.py ADDED
@@ -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
+ ]
distparser/core.py ADDED
@@ -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
distparser/version.py ADDED
@@ -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,8 @@
1
+ distparser/__init__.py,sha256=L9T5BxwGDZreNT1_PTI2uv_HGqz7jx7Z1nhqPBmjNgA,458
2
+ distparser/core.py,sha256=8h90DkS0qPgqz5-Q1KsFjOspR4EJEO4tw_k-jiIjjUI,6382
3
+ distparser/version.py,sha256=Zn1KFblwuFHiDRdRAiRnDBRkbPttWh44jKa5zG2ov0E,22
4
+ distparser-0.2.0.dist-info/licenses/LICENSE,sha256=u8RNx2_GVxKIxW51x77acSpdaMhiEUg_Qjvw9jqYpVs,1069
5
+ distparser-0.2.0.dist-info/METADATA,sha256=xLGHsex2fbO1EuJVPaGAwiokkcnP7I9BwA4_lFbLziA,2955
6
+ distparser-0.2.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
7
+ distparser-0.2.0.dist-info/top_level.txt,sha256=DuNswEAnvWst95hInDz0BwoaJK68emKziYILsPiPrYM,11
8
+ distparser-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ distparser