Repository navigation
Expand file tree
/
Copy pathpdf.py
More file actions
478 lines (384 loc) · 18.4 KB
/
Copy pathpdf.py
File metadata and controls
478 lines (384 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
from matplotlib import pyplot as plt
from collections import defaultdict
from typing import Callable, overload
from itertools import product
import math
import random
import operator
import argparse
import re
class PDF:
outcomes: dict[int, int]
total: int
@overload
def __init__(self, outcomes: dict[int, int], weights: None = None): ...
@overload
def __init__(self, outcomes: list[int], weights: list[int] | None = None): ...
def __init__(self, outcomes: dict[int, int] | list[int], weights: list[int] | None = None):
"""Define an integer Probability Distribution Function from an `{outcome: weight}` dict.
Arguments
---------
outcomes : dict[int, int] or list[int]
Dictionary where the keys are the possible outcomes for this random variable
and the values are the relative weights. If a list is given, `weights` is
used for the weights instead.
weights : list[int] or None (default: None)
Relative weights of the outcomes. Used if and only if `outcomes` is given as a list.
"""
# Normalize outcomes to a dictionary
if isinstance(outcomes, dict):
if weights is not None:
raise ValueError("weights cannot be given when passing outcomes as a dictionary")
elif isinstance(outcomes, list):
if not isinstance(weights, list) and weights is not None:
raise TypeError(f"weights has to be a list, not {type(weights).__name__}")
outcomes = PDF.from_lists(outcomes, weights)
else:
raise TypeError(f"outcomes has to be a dictionary or list, not {type(outcomes).__name__}")
if any(weight < 0 for weight in outcomes.values()):
raise ValueError("All weights must be nonnegative")
if not any(outcomes.values()):
raise ValueError("At least one weight must be nonzero")
# Simplify and remove outcomes with weight 0
common_weight_factor = math.gcd(*outcomes.values())
# Cast to int because bools are subtypes of int
self.outcomes = {
int(outcome): weight // common_weight_factor
for outcome, weight in outcomes.items()
if weight
}
self.total = sum(self.outcomes.values())
def __repr__(self) -> str:
outcomes, weights = self.as_lists()
return f"PDF({outcomes}, {weights})"
def __call__(self, value: int) -> float:
"""Return the probability of a sample from `self` being equal to `value`."""
return self.outcomes.get(value, 0) / self.total
def sample(self, n: int = 1) -> list[int]:
"""Return `n` samples with this probability distribution."""
outcomes, weights = self.as_lists()
return random.choices(outcomes, weights, k=n)
@staticmethod
def from_lists(
values: list[int],
weights: list[int] | None = None,
) -> dict[int, int]:
"""Get the outcome dictionary from lists of outcome values and weights.
Values that occur several times have their weights summed.
Arguments
---------
values : list[int]
Possible outcomes the random variable can take.
weights : list[int] or None
Relative probabilities of the outcomes. If not given, defaults to a list of ones,
signifying that all outcomes are equally probable.
"""
if weights is None:
weights = [1] * len(values)
elif len(values) != len(weights):
raise ValueError("values and weights must have the same length")
outcomes = defaultdict(int)
for value, weight in zip(values, weights):
outcomes[value] += weight
return outcomes
@staticmethod
def eval(expression: str, **pdfs: PDF) -> PDF:
"""Evaluate an expression where variable names can be used as stand-ins for PDFs.
This is a generalization of `unary_operation` and `binary_operation` that
works for any number of PDFs as well as expressions that don't assume that
all operands are independent.
Examples
--------
>>> d6 = PDF.from_lists([1, 2, 3, 4, 5, 6])
>>> PDF.eval("A + A", A=d6)
PDF([2, 4, 6, 8, 10, 12], [1, 1, 1, 1, 1, 1])
>>> PDF.eval("max(A, B) // min(A, B)", A=d6, B=d6)
PDF([1, 2, 3, 4, 5, 6], [9, 4, 2, 1, 1, 1])
>>> PDF.eval("A + B + C + D - min(A, B, C, D) - max(A, B, C, D)", A=d6, B=d6, C=d6, D=d6)
PDF([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [7, 18, 37, 52, 67, 70, 67, 52, 37, 18, 7])
"""
# The expression will be evaluated many times, so we precompile it here
compiled_expression = compile(expression, "<string>", mode="eval")
outcome_tuples = [pdf.outcomes.items() for pdf in pdfs.values()]
new_outcomes = defaultdict(int)
# Iterate through all combinations of possible outcomes
for outcome_combination in product(*outcome_tuples):
# Dictionary of current combination of outcomes
outcomes = {
name: outcome for name, (outcome, weight) in zip(pdfs, outcome_combination)
}
# Weight of the current outcome combination
outcome_weight = math.prod(weight for outcome, weight in outcome_combination)
new_outcome = eval(compiled_expression, globals=outcomes)
if not isinstance(new_outcome, int):
raise TypeError(f"Expression evaluated to {type(new_outcome).__name__}, not int")
new_outcomes[new_outcome] += outcome_weight
return PDF(new_outcomes)
def unary_operation(self, operation: Callable[[int], int]) -> PDF:
r"""Return the result of a unary operation on a PDF.
Given a PDF $A$ and a unary operation $f:\mathbb{Z}\to\mathbb{Z}$, return the PDF $X$ such that
$P(X = x) = P(f(A)=x)$
by means of the formula
$P(f(A)=x) = \sum_{a:f(a)=x}P(A=a).$
"""
new_outcomes = defaultdict(int)
for value, weight in self.outcomes.items():
new_outcomes[operation(value)] += weight
return PDF(new_outcomes)
def binary_operation(self, other: PDF, operation: Callable[[int, int], int]) -> PDF:
r"""Return the result of a binary operation on two PDFs.
Given PDFs $A$ and $B$ and a binary operation $f:\mathbb{Z}^2\to\mathbb{Z}$, return the PDF $X$ such that
$P(X = x) = P(f(A, B)=x)$
by means of the formula
$P(f(A, B)=x) = \sum_a\sum_{b:f(a,b)=x}P(A=a)P(B=b).$
"""
new_outcomes = defaultdict(int)
for outcome1, weight1 in self.outcomes.items():
for outcome2, weight2 in other.outcomes.items():
new_outcomes[operation(outcome1, outcome2)] += weight1 * weight2
return PDF(new_outcomes)
def as_lists(self) -> tuple[list[int], list[int]]:
"""Get a tuple `(outcomes, weights)` of sorted outcomes and their weights."""
sorted_tuples = sorted(self.outcomes.items(), key=lambda pair: pair[0])
outcomes, weights = zip(*sorted_tuples)
return list(outcomes), list(weights)
# Mathematical operators
def __pos__(self) -> PDF:
return PDF(self.outcomes)
def __neg__(self) -> PDF:
return PDF({-outcome: weight for outcome, weight in self.outcomes.items()})
def __abs__(self) -> PDF:
return self.unary_operation(int.__abs__)
def max(self, other: PDF | int) -> PDF:
if isinstance(other, int):
return self.unary_operation(lambda x: max(x, other))
return self.binary_operation(other, max)
def min(self, other: PDF | int) -> PDF:
if isinstance(other, int):
return self.unary_operation(lambda x: min(x, other))
return self.binary_operation(other, min)
def __add__(self, other: PDF | int) -> PDF:
"""self + other"""
if isinstance(other, int):
return PDF({outcome + other: weight for outcome, weight in self.outcomes.items()})
return self.binary_operation(other, int.__add__)
def __radd__(self, other: int) -> PDF:
"""other + self"""
return self.__add__(other)
def __sub__(self, other: PDF | int) -> PDF:
"""self - other"""
if isinstance(other, int):
return PDF({outcome - other: weight for outcome, weight in self.outcomes.items()})
return self.binary_operation(other, int.__sub__)
def __rsub__(self, other: int) -> PDF:
"""other - self"""
return PDF({other - outcome: weight for outcome, weight in self.outcomes.items()})
def __mul__(self, other: PDF | int) -> PDF:
"""self * other"""
if isinstance(other, int):
return PDF({outcome * other: weight for outcome, weight in self.outcomes.items()})
return self.binary_operation(other, int.__mul__)
def __rmul__(self, other: int) -> PDF:
"""other * self"""
return self.__mul__(other)
def __floordiv__(self, other: PDF | int) -> PDF:
"""self // other"""
if isinstance(other, int):
if other == 0:
raise ZeroDivisionError("Cannot divide by 0")
return self.unary_operation(lambda x: x // other)
if 0 in other.outcomes:
raise ZeroDivisionError("Cannot divide by a PDF that has 0 as a possible outcome")
return self.binary_operation(other, int.__floordiv__)
def __rfloordiv__(self, other: int) -> PDF:
"""other // self"""
if 0 in self.outcomes:
raise ZeroDivisionError("Cannot divide by a PDF that has 0 as a possible outcome")
return self.unary_operation(lambda x: other // x)
def __mod__(self, other: PDF | int) -> PDF:
"""self % other"""
if isinstance(other, int):
if other == 0:
raise ZeroDivisionError("Cannot divide by 0")
return self.unary_operation(lambda x: x % other)
if 0 in other.outcomes:
raise ZeroDivisionError("Cannot divide by a PDF that has 0 as a possible outcome")
return self.binary_operation(other, int.__mod__)
def __rmod__(self, other: int) -> PDF:
"""other % self"""
if 0 in self.outcomes:
raise ZeroDivisionError("Cannot divide by a PDF that has 0 as a possible outcome")
return self.unary_operation(lambda x: other % x)
def __pow__(self, other: PDF | int) -> PDF:
"""self ** other"""
if isinstance(other, int):
if other < 0:
raise ValueError("Exponent must be nonnegative")
return self.unary_operation(lambda x: x**other)
if any(outcome < 0 for outcome in other.outcomes):
raise ValueError("Exponent PDF must be nonnegative")
return self.binary_operation(other, int.__pow__)
def __rpow__(self, other: int) -> PDF:
"""other ** self"""
if any(outcome < 0 for outcome in self.outcomes):
raise ValueError("Exponent PDF must be nonnegative")
return self.unary_operation(lambda x: other**x)
def summed(self, n: int) -> PDF:
"""Return the n-fold sum of this PDF."""
if n < 1:
return PDF({0: 1})
elif n == 1:
return self
return sum([self] * (n - 1), start=self)
# Bitwise operators
def __lshift__(self, other: PDF | int) -> PDF:
"""self << other"""
if isinstance(other, int):
return self.unary_operation(lambda x: x << other)
return self.binary_operation(other, int.__lshift__)
def __rlshift__(self, other: int) -> PDF:
"""other << self"""
return self.unary_operation(lambda x: other << x)
def __rshift__(self, other: PDF | int) -> PDF:
"""self >> other"""
if isinstance(other, int):
return self.unary_operation(lambda x: x >> other)
return self.binary_operation(other, int.__rshift__)
def __rrshift__(self, other: int) -> PDF:
"""other >> self"""
return self.unary_operation(lambda x: other >> x)
def __invert__(self) -> PDF:
"""~self"""
return self.unary_operation(int.__invert__)
def __and__(self, other: PDF | int) -> PDF:
"""self & other"""
if isinstance(other, int):
return self.unary_operation(lambda x: x & other)
return self.binary_operation(other, int.__and__)
def __rand__(self, other: int) -> PDF:
"""other & self"""
return self.__and__(other)
def __or__(self, other: PDF | int) -> PDF:
"""self | other"""
if isinstance(other, int):
return self.unary_operation(lambda x: x | other)
return self.binary_operation(other, int.__or__)
def __ror__(self, other: int) -> PDF:
"""other & self"""
return self.__or__(other)
def __xor__(self, other: PDF | int) -> PDF:
"""self ^ other"""
if isinstance(other, int):
return self.unary_operation(lambda x: x ^ other)
return self.binary_operation(other, int.__xor__)
def __rxor__(self, other: int) -> PDF:
"""other ^ self"""
return self.__xor__(other)
# Comparison operators
def __eq__(self, other: PDF | int) -> PDF: # type: ignore
"""Return the PDF that has outcome 1 with the probability of self and other being equal."""
if isinstance(other, int):
# 1 with weight equal to self.outcomes[other] (or zero if it doesn't exist)
one_weight = self.outcomes.get(other, 0)
total = self.total
elif isinstance(other, PDF):
# 1 with weight equal to the sum of products of weights of the outcomes that are equal
one_weight = sum(self.outcomes.get(value, 0) * weight for value, weight in other.outcomes.items())
total = self.total * other.total
else:
raise TypeError("PDFs can only be compared with ints or other PDFs")
zero_weight = total - one_weight
return PDF({1: one_weight, 0: zero_weight})
def __ne__(self, other: PDF | int) -> PDF: # type: ignore
return (self == other).not_()
def __lt__(self, other: PDF | int):
if isinstance(other, int):
return self.unary_operation(lambda x: x < other)
return self.binary_operation(other, operator.lt)
def __le__(self, other: PDF | int):
if isinstance(other, int):
return self.unary_operation(lambda x: x <= other)
return self.binary_operation(other, operator.le)
def __gt__(self, other: PDF | int):
if isinstance(other, int):
return self.unary_operation(lambda x: x > other)
return self.binary_operation(other, operator.gt)
def __ge__(self, other: PDF | int):
if isinstance(other, int):
return self.unary_operation(lambda x: x >= other)
return self.binary_operation(other, operator.ge)
def bool_(self):
"""Same as `self != 0`."""
zero_weight = self.outcomes.get(0, 0)
one_weight = self.total - zero_weight
return PDF({1: one_weight, 0: zero_weight})
def not_(self):
"""Same as `self == 0`."""
one_weight = self.outcomes.get(0, 0)
zero_weight = self.total - one_weight
return PDF({1: one_weight, 0: zero_weight})
def equivalent(self, other: PDF | int) -> bool:
"""Return whether two PDFs are equal in probability."""
if isinstance(other, int):
return self.outcomes == {other: 1}
return self.outcomes == other.outcomes
# Statistical properties
def mean(self) -> float:
"""Get the mean outcome."""
return sum(outcome * weight for outcome, weight in self.outcomes.items()) / self.total
def median(self) -> float:
"""Get the median outcome."""
outcomes, _ = self.as_lists()
middle = len(outcomes) // 2
if len(outcomes) % 2 == 0:
return 0.5 * (outcomes[middle - 1] + outcomes[middle])
return outcomes[middle]
def mode(self) -> int:
"""Get one out of the most common outcomes."""
return max(self.outcomes.items(), key=lambda pair: pair[1])[0]
# Plotting
def plot(self, ax=None, *, normalize=True, show=True, label=True, title: str = "", **bar_kwargs):
"""Plot the outcomes and weights as a bar chart.
The bars are labeled with the weights if the range of the
outcomes is less than 30 (so text isn't drawn on too thin bars).
"""
if ax is None:
ax = plt.gca()
outcomes, weights = self.as_lists()
if normalize:
weights = [weight / self.total for weight in weights]
bars = ax.bar(outcomes, height=weights, width=0.9, alpha=0.5, **bar_kwargs)
if label and max(outcomes) - min(outcomes) < 30:
labels = [f"{weight:.5g}" for weight in weights]
annotations = ax.bar_label(bars, labels, rotation="vertical", padding=2.0, color="0.5")
# Update y-limit to include the annotations
pixel_to_xy = ax.transData.inverted()
new_ymax = max(annotation.get_window_extent().transformed(pixel_to_xy).ymax for annotation in annotations)
ax.update_datalim([[0.0, new_ymax]], updatex=False)
ax.autoscale_view(scalex=False)
if title:
ax.set_title(title)
if show:
plt.show()
def d(n, start=1):
return PDF(list(range(start, n + start)))
def main(args, show=True):
def convert_dice_name_to_PDF(match: re.Match[str]) -> str:
num_dice = match.group(1)
num_faces = match.group(2)
return f"d({num_faces})" if num_dice is None else f"d({num_faces}).summed({num_dice})"
original_expression = args.expression
# Parse dice literals (e.g. "2d8") to point to a PDF expression (e.g. "sum([d(8)] * 2)").
expression = re.sub(r"(?<!\w)([1-9][0-9]*)?[dD]([1-9][0-9]*)(?!\w)", convert_dice_name_to_PDF, original_expression)
result = eval(expression, globals={"PDF": PDF, "d": d})
if not isinstance(result, PDF):
raise ValueError("Expression did not result in a PDF")
result.plot(normalize=not args.unnormalized, label=not args.no_bar_labels, title=original_expression, show=show)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("expression", nargs="?", help="The PDF expression to evaluate.")
parser.add_argument("-u", "--unnormalized", action="store_true", help="Plot the PDF without normalization.")
parser.add_argument("-n", "--no-bar-labels", action="store_true", help="Plot the PDF without bar labels.")
args = parser.parse_args()
if args.expression:
main(args)