prspace 0.1.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.
prspace/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """prspace: probability spaces with the same syntax in Python and R."""
2
+
3
+ from ._core import Condition, Event, PrSpace, UndefinedProbabilityError
4
+
5
+ __all__ = ["PrSpace", "Event", "Condition", "UndefinedProbabilityError"]
6
+ __version__ = "0.1.0"
prspace/_core.py ADDED
@@ -0,0 +1,195 @@
1
+ """Core objects: PrSpace, Event, and the Condition you get by comparing an Event."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import math
7
+ import numbers
8
+ import sys
9
+ from types import FrameType
10
+ from typing import Any
11
+
12
+ _ids = itertools.count(1)
13
+
14
+ # The complement of each comparison, e.g. not (X == 0) is (X != 0).
15
+ _NEGATE = {"==": "!=", "!=": "==", "<": ">=", ">=": "<", ">": "<=", "<=": ">"}
16
+
17
+
18
+ class UndefinedProbabilityError(KeyError):
19
+ """Raised when reading ``Pr[cond]`` that was never assigned (directly or via its complement)."""
20
+
21
+ def __init__(self, condition: Condition):
22
+ super().__init__(condition)
23
+ self.condition = condition
24
+
25
+ def __str__(self) -> str:
26
+ return (
27
+ f"Pr[{self.condition}] has not been assigned "
28
+ f"(nor has its complement Pr[{~self.condition}])"
29
+ )
30
+
31
+
32
+ class Event:
33
+ """A quantity you can make probability statements about.
34
+
35
+ Comparing an Event with a value (``S_B == 0``, ``S_B >= 1``) gives a
36
+ :class:`Condition`, which is what you index a :class:`PrSpace` with.
37
+
38
+ If ``name`` is omitted, it is taken from the variable the Event is bound to
39
+ the first time it is compared, so ``S_B = Event()`` prints as ``S_B``.
40
+ """
41
+
42
+ def __init__(self, name: str | None = None):
43
+ if name is not None and not isinstance(name, str):
44
+ raise TypeError("`name` must be a string")
45
+ self._id = next(_ids)
46
+ self.name = name
47
+
48
+ @property
49
+ def label(self) -> str:
50
+ return self.name if self.name is not None else f"E{self._id}"
51
+
52
+ def _compare(self, op: str, value: Any, frame: FrameType | None) -> Condition:
53
+ if isinstance(value, Event):
54
+ raise TypeError("comparing two Events is not supported yet")
55
+ try:
56
+ hash(value)
57
+ except TypeError:
58
+ raise TypeError(
59
+ f"an Event can only be compared with a single value, not {type(value).__name__}"
60
+ ) from None
61
+ if self.name is None and frame is not None:
62
+ self.name = _infer_name(self, frame)
63
+ return Condition(self, op, value)
64
+
65
+ # Python reflects `0 == S_B` to `S_B == 0` (and `1 <= S_B` to `S_B >= 1`) on its own.
66
+ def __eq__(self, value: Any) -> Condition: # type: ignore[override]
67
+ return self._compare("==", value, sys._getframe(1))
68
+
69
+ def __ne__(self, value: Any) -> Condition: # type: ignore[override]
70
+ return self._compare("!=", value, sys._getframe(1))
71
+
72
+ def __lt__(self, value: Any) -> Condition:
73
+ return self._compare("<", value, sys._getframe(1))
74
+
75
+ def __le__(self, value: Any) -> Condition:
76
+ return self._compare("<=", value, sys._getframe(1))
77
+
78
+ def __gt__(self, value: Any) -> Condition:
79
+ return self._compare(">", value, sys._getframe(1))
80
+
81
+ def __ge__(self, value: Any) -> Condition:
82
+ return self._compare(">=", value, sys._getframe(1))
83
+
84
+ def __hash__(self) -> int:
85
+ return hash(("prspace.Event", self._id))
86
+
87
+ def __repr__(self) -> str:
88
+ return f"<Event {self.label}>"
89
+
90
+
91
+ class Condition:
92
+ """An event such as ``S_B == 0``. Use it as a key: ``Pr[S_B == 0]``.
93
+
94
+ ``~cond`` is the complement (``~(S_B == 0)`` is ``S_B != 0``).
95
+ """
96
+
97
+ __slots__ = ("event", "op", "value")
98
+
99
+ def __init__(self, event: Event, op: str, value: Any):
100
+ self.event = event
101
+ self.op = op
102
+ self.value = value
103
+
104
+ @property
105
+ def _key(self) -> tuple:
106
+ return (self.event._id, self.op, self.value)
107
+
108
+ def __invert__(self) -> Condition:
109
+ return Condition(self.event, _NEGATE[self.op], self.value)
110
+
111
+ def __eq__(self, other: object) -> bool:
112
+ return isinstance(other, Condition) and self._key == other._key
113
+
114
+ def __hash__(self) -> int:
115
+ return hash(self._key)
116
+
117
+ def __bool__(self) -> bool:
118
+ raise TypeError(
119
+ f"`{self}` is an event, not True/False; use it as a key, e.g. Pr[{self}]"
120
+ )
121
+
122
+ def __str__(self) -> str:
123
+ return f"{self.event.label} {self.op} {self.value!r}"
124
+
125
+ def __repr__(self) -> str:
126
+ return f"<Condition {self}>"
127
+
128
+
129
+ class PrSpace:
130
+ """A probability space: assign ``Pr[cond] = p`` and read back ``Pr[cond]``.
131
+
132
+ Complements are derived: after ``Pr[X == 0] = 0.3``, ``Pr[X != 0]`` is 0.7.
133
+ Assigning a condition replaces any stored value for its complement.
134
+ """
135
+
136
+ def __init__(self) -> None:
137
+ self._store: dict[tuple, tuple[Condition, float]] = {}
138
+
139
+ def __setitem__(self, condition: Condition, p: Any) -> None:
140
+ condition = _as_condition(condition)
141
+ p = _as_probability(p, condition)
142
+ self._store.pop((~condition)._key, None)
143
+ self._store[condition._key] = (condition, p)
144
+
145
+ def __getitem__(self, condition: Condition) -> float:
146
+ condition = _as_condition(condition)
147
+ if condition._key in self._store:
148
+ return self._store[condition._key][1]
149
+ complement = (~condition)._key
150
+ if complement in self._store:
151
+ return 1.0 - self._store[complement][1]
152
+ raise UndefinedProbabilityError(condition)
153
+
154
+ def __delitem__(self, condition: Condition) -> None:
155
+ condition = _as_condition(condition)
156
+ for key in (condition._key, (~condition)._key):
157
+ if key in self._store:
158
+ del self._store[key]
159
+ return
160
+ raise UndefinedProbabilityError(condition)
161
+
162
+ def __len__(self) -> int:
163
+ return len(self._store)
164
+
165
+ def __repr__(self) -> str:
166
+ if not self._store:
167
+ return "PrSpace with no probabilities assigned"
168
+ lines = [f"PrSpace with {len(self._store)} probabilit{'y' if len(self._store) == 1 else 'ies'}:"]
169
+ lines += [f" Pr[{c}] = {p:.7g}" for c, p in self._store.values()]
170
+ return "\n".join(lines)
171
+
172
+
173
+ def _as_condition(x: Any) -> Condition:
174
+ if isinstance(x, Condition):
175
+ return x
176
+ if isinstance(x, Event):
177
+ raise TypeError(f"index a PrSpace with a condition such as Pr[{x.label} == 0], not a bare Event")
178
+ raise TypeError(f"index a PrSpace with a condition such as Pr[X == 0], not {type(x).__name__}")
179
+
180
+
181
+ def _as_probability(p: Any, condition: Condition) -> float:
182
+ if isinstance(p, bool) or not isinstance(p, numbers.Real):
183
+ raise TypeError(f"Pr[{condition}] must be a number, not {type(p).__name__}")
184
+ p = float(p)
185
+ if math.isnan(p) or not 0.0 <= p <= 1.0:
186
+ raise ValueError(f"Pr[{condition}] must be between 0 and 1, got {p}")
187
+ return p
188
+
189
+
190
+ def _infer_name(event: Event, frame: FrameType) -> str | None:
191
+ for scope in (frame.f_locals, frame.f_globals):
192
+ for name, value in list(scope.items()):
193
+ if value is event:
194
+ return name
195
+ return None
prspace/py.typed ADDED
File without changes
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.5
2
+ Name: prspace
3
+ Version: 0.1.0
4
+ Summary: Probability spaces with the same syntax in Python and R: Pr[X == 0] = 0.25
5
+ Project-URL: Homepage, https://github.com/ivanharvard/prspace
6
+ Project-URL: Issues, https://github.com/ivanharvard/prspace/issues
7
+ Author-email: Ivan Gutierrez <gutierrezi0222@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: education,probability,statistics
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+
19
+ # prspace
20
+
21
+ Probability spaces with the same syntax in Python and R: `Pr[X == 0] = 0.25`.
22
+
23
+ > **Alpha.** The API may change between 0.x releases.
24
+
25
+ ```python
26
+ import math
27
+ from prspace import PrSpace, Event
28
+
29
+ n_samples = math.comb(19, 10)
30
+ Pr = PrSpace()
31
+ S_B = Event()
32
+
33
+ for B in (100, 1000):
34
+ Pr[S_B == 0] = math.prod(1 - k / n_samples for k in range(B))
35
+ Pr[S_B >= 1] = 1 - Pr[S_B == 0]
36
+ print("Pr[S_B >= 1] =", Pr[S_B >= 1])
37
+
38
+ print(Pr)
39
+ # PrSpace with 2 probabilities:
40
+ # Pr[S_B == 0] = 0.004397413
41
+ # Pr[S_B >= 1] = 0.9956026
42
+ ```
43
+
44
+ - Complements are derived: after `Pr[X == 0] = 0.25`, `Pr[X != 0]` and `Pr[~(X == 0)]` are `0.75`.
45
+ - Reading a condition that was never assigned raises `UndefinedProbabilityError` (a `KeyError`).
46
+ - Event names are inferred from the variable they're bound to, or pass `Event("name")`.
47
+
48
+ The R package has the same syntax. See the [repository](https://github.com/ivanharvard/prspace)
49
+ for both.
@@ -0,0 +1,7 @@
1
+ prspace/__init__.py,sha256=lU2iFMrsenOp7o-oUQKSYstrr_dFulMA4ESjNInE-ZY,241
2
+ prspace/_core.py,sha256=i9_pMluzIwXkxUixX9hE6lJM840-Xb34Q0D5T0Ey9HY,6717
3
+ prspace/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ prspace-0.1.0.dist-info/METADATA,sha256=uvORu0xXJpszKcMjTzCgF6cPBbjY9R8xFk0gnIjqVnI,1646
5
+ prspace-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
+ prspace-0.1.0.dist-info/licenses/LICENSE,sha256=_M5dt9rPHP8uxoZKiTkgziXevqkBfoZzaBtb1_Bvd3Q,1071
7
+ prspace-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ivan Gutierrez
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.