prspace 0.1.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,12 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ *.egg-info/
6
+ .pytest_cache/
7
+ uv.lock
8
+ .Rhistory
9
+ .RData
10
+ .Rproj.user/
11
+ *.Rcheck/
12
+ prspace_*.tar.gz
prspace-0.1.0/LICENSE ADDED
@@ -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.
prspace-0.1.0/PKG-INFO ADDED
@@ -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,31 @@
1
+ # prspace
2
+
3
+ Probability spaces with the same syntax in Python and R: `Pr[X == 0] = 0.25`.
4
+
5
+ > **Alpha.** The API may change between 0.x releases.
6
+
7
+ ```python
8
+ import math
9
+ from prspace import PrSpace, Event
10
+
11
+ n_samples = math.comb(19, 10)
12
+ Pr = PrSpace()
13
+ S_B = Event()
14
+
15
+ for B in (100, 1000):
16
+ Pr[S_B == 0] = math.prod(1 - k / n_samples for k in range(B))
17
+ Pr[S_B >= 1] = 1 - Pr[S_B == 0]
18
+ print("Pr[S_B >= 1] =", Pr[S_B >= 1])
19
+
20
+ print(Pr)
21
+ # PrSpace with 2 probabilities:
22
+ # Pr[S_B == 0] = 0.004397413
23
+ # Pr[S_B >= 1] = 0.9956026
24
+ ```
25
+
26
+ - Complements are derived: after `Pr[X == 0] = 0.25`, `Pr[X != 0]` and `Pr[~(X == 0)]` are `0.75`.
27
+ - Reading a condition that was never assigned raises `UndefinedProbabilityError` (a `KeyError`).
28
+ - Event names are inferred from the variable they're bound to, or pass `Event("name")`.
29
+
30
+ The R package has the same syntax. See the [repository](https://github.com/ivanharvard/prspace)
31
+ for both.
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "prspace"
7
+ version = "0.1.0"
8
+ description = "Probability spaces with the same syntax in Python and R: Pr[X == 0] = 0.25"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Ivan Gutierrez", email = "gutierrezi0222@gmail.com" }]
13
+ requires-python = ">=3.10"
14
+ keywords = ["probability", "statistics", "education"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Education",
18
+ "Intended Audience :: Science/Research",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Scientific/Engineering :: Mathematics",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/ivanharvard/prspace"
25
+ Issues = "https://github.com/ivanharvard/prspace/issues"
26
+
27
+ [dependency-groups]
28
+ dev = ["pytest>=8"]
@@ -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"
@@ -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
File without changes
@@ -0,0 +1,131 @@
1
+ # Keep these cases in sync with r/tests/testthat/test-prspace.R.
2
+ import math
3
+
4
+ import pytest
5
+
6
+ from prspace import Event, PrSpace, UndefinedProbabilityError
7
+
8
+
9
+ def test_readme_example():
10
+ n_samples = math.comb(2 * 10 - 1, 10)
11
+ Pr = PrSpace()
12
+ S_B = Event()
13
+ for B in (100, 1000):
14
+ Pr[S_B == 0] = math.prod(1 - k / n_samples for k in range(B))
15
+ Pr[S_B >= 1] = 1 - Pr[S_B == 0]
16
+ assert Pr[S_B == 0] + Pr[S_B >= 1] == pytest.approx(1)
17
+ assert Pr[S_B == 0] == pytest.approx(math.prod(1 - k / n_samples for k in range(1000)))
18
+
19
+
20
+ def test_assign_and_read():
21
+ Pr = PrSpace()
22
+ X = Event()
23
+ Pr[X == 0] = 0.25
24
+ assert Pr[X == 0] == 0.25
25
+ assert len(Pr) == 1
26
+
27
+
28
+ def test_complements_are_derived():
29
+ Pr = PrSpace()
30
+ X = Event()
31
+ Pr[X == 0] = 0.25
32
+ assert Pr[X != 0] == 0.75
33
+ assert Pr[~(X == 0)] == 0.75
34
+ Pr[X < 3] = 0.4
35
+ assert Pr[X >= 3] == pytest.approx(0.6)
36
+
37
+
38
+ def test_assigning_replaces_stored_complement():
39
+ Pr = PrSpace()
40
+ X = Event()
41
+ Pr[X != 0] = 0.9
42
+ Pr[X == 0] = 0.3
43
+ assert len(Pr) == 1
44
+ assert Pr[X != 0] == pytest.approx(0.7)
45
+
46
+
47
+ def test_reversed_comparisons():
48
+ Pr = PrSpace()
49
+ X = Event()
50
+ Pr[1 <= X] = 0.4
51
+ assert Pr[X >= 1] == 0.4
52
+ Pr[0 == X] = 0.1
53
+ assert Pr[X == 0] == 0.1
54
+
55
+
56
+ def test_values_are_part_of_the_key():
57
+ Pr = PrSpace()
58
+ X = Event()
59
+ Pr[X == 0] = 0.1
60
+ Pr[X == 1] = 0.2
61
+ Pr[X == "heads"] = 0.5
62
+ assert (Pr[X == 0], Pr[X == 1], Pr[X == "heads"]) == (0.1, 0.2, 0.5)
63
+
64
+
65
+ def test_events_are_distinct():
66
+ Pr = PrSpace()
67
+ X, Y = Event(), Event()
68
+ Pr[X == 0] = 0.1
69
+ with pytest.raises(UndefinedProbabilityError):
70
+ Pr[Y == 0]
71
+
72
+
73
+ def test_undefined_probability_message():
74
+ Pr = PrSpace()
75
+ X = Event()
76
+ with pytest.raises(UndefinedProbabilityError, match=r"Pr\[X >= 1\] has not been assigned"):
77
+ Pr[X >= 1]
78
+
79
+
80
+ def test_names_are_inferred_or_given():
81
+ X = Event()
82
+ Z = Event("Z_total")
83
+ assert str(X == 0) == "X == 0"
84
+ assert str(Z > 2) == "Z_total > 2"
85
+
86
+
87
+ def test_rejects_bad_probabilities():
88
+ Pr = PrSpace()
89
+ X = Event()
90
+ for bad in (-0.1, 1.5, float("nan")):
91
+ with pytest.raises(ValueError):
92
+ Pr[X == 0] = bad
93
+ for bad in ("0.5", None, True):
94
+ with pytest.raises(TypeError):
95
+ Pr[X == 0] = bad
96
+
97
+
98
+ def test_rejects_bad_keys():
99
+ Pr = PrSpace()
100
+ X = Event()
101
+ with pytest.raises(TypeError):
102
+ Pr[X] = 0.5
103
+ with pytest.raises(TypeError):
104
+ Pr["X == 0"] = 0.5
105
+ with pytest.raises(TypeError):
106
+ X == [1, 2]
107
+
108
+
109
+ def test_condition_is_not_a_bool():
110
+ X = Event()
111
+ with pytest.raises(TypeError):
112
+ if X == 0:
113
+ pass
114
+
115
+
116
+ def test_delete():
117
+ Pr = PrSpace()
118
+ X = Event()
119
+ Pr[X == 0] = 0.25
120
+ del Pr[X != 0] # deleting via the complement removes the stored value
121
+ assert len(Pr) == 0
122
+ with pytest.raises(UndefinedProbabilityError):
123
+ del Pr[X == 0]
124
+
125
+
126
+ def test_print():
127
+ Pr = PrSpace()
128
+ S_B = Event()
129
+ assert repr(Pr) == "PrSpace with no probabilities assigned"
130
+ Pr[S_B == 0] = 0.25
131
+ assert repr(Pr) == "PrSpace with 1 probability:\n Pr[S_B == 0] = 0.25"