/
distribution.py
1817 lines (1483 loc) · 57.6 KB
/
distribution.py
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
from itertools import product
import numpy as np
import xarray as xr
from scipy import stats
from scipy.special import erf, erfc
class Distribution:
"""
Base class for all probability distributions.
Parameters
----------
seed : int
Seed for random number generator.
"""
def __init__(self, seed=0):
self.RNG = np.random.RandomState(seed)
self.seed = seed
def reset(self):
"""
Reset the random number generator of this distribution.
Parameters
----------
"""
self.RNG = np.random.RandomState(self.seed)
class IndexDistribution(Distribution):
"""
This class provides a way to define a distribution that
is conditional on an index.
The current implementation combines a defined distribution
class (such as Bernoulli, LogNormal, etc.) with information
about the conditions on the parameters of the distribution.
For example, an IndexDistribution can be defined as
a Bernoulli distribution whose parameter p is a function of
a different inpute parameter.
Parameters
----------
engine : Distribution class
A Distribution subclass.
conditional: dict
Information about the conditional variation
on the input parameters of the engine distribution.
Keys should match the arguments to the engine class
constructor.
seed : int
Seed for random number generator.
"""
conditional = None
engine = None
def __init__(self, engine, conditional, RNG=None, seed=0):
if RNG is None:
# Set up the RNG
super().__init__(seed)
else:
# If an RNG is received, use it in whatever state it is in.
self.RNG = RNG
# The seed will still be set, even if it is not used for the RNG,
# for whenever self.reset() is called.
# Note that self.reset() will stop using the RNG that was passed
# and create a new one.
self.seed = seed
self.conditional = conditional
self.engine = engine
self.dstns = []
# Test one item to determine case handling
item0 = list(self.conditional.values())[0]
if type(item0) is list:
# Create and store all the conditional distributions
for y in range(len(item0)):
cond = {key: val[y] for (key, val) in self.conditional.items()}
self.dstns.append(
self.engine(seed=self.RNG.randint(0, 2**31 - 1), **cond)
)
elif type(item0) is float:
self.dstns = [
self.engine(seed=self.RNG.randint(0, 2**31 - 1), **conditional)
]
else:
raise (
Exception(
f"IndexDistribution: Unhandled case for __getitem__ access. item0: {item0}; conditional: {self.conditional}"
)
)
def __getitem__(self, y):
return self.dstns[y]
def approx(self, N, **kwds):
"""
Approximation of the distribution.
Parameters
----------
N : init
Number of discrete points to approximate
continuous distribution into.
kwds: dict
Other keyword arguments passed to engine
distribution approx() method.
Returns:
------------
dists : [DiscreteDistribution]
A list of DiscreteDistributions that are the
approximation of engine distribution under each condition.
TODO: It would be better if there were a conditional discrete
distribution representation. But that integrates with the
solution code. This implementation will return the list of
distributions representations expected by the solution code.
"""
# test one item to determine case handling
item0 = list(self.conditional.values())[0]
if type(item0) is float:
# degenerate case. Treat the parameterization as constant.
return self.dstns[0].approx(N, **kwds)
if type(item0) is list:
return TimeVaryingDiscreteDistribution(
[self[i].approx(N, **kwds) for i, _ in enumerate(item0)]
)
def draw(self, condition):
"""
Generate arrays of draws.
The input is an array containing the conditions.
The output is an array of the same length (axis 1 dimension)
as the conditions containing random draws of the conditional
distribution.
Parameters
----------
condition : np.array
The input conditions to the distribution.
Returns:
------------
draws : np.array
"""
# for now, assume that all the conditionals
# are of the same type.
# this matches the HARK 'time-varying' model architecture.
# test one item to determine case handling
item0 = list(self.conditional.values())[0]
if type(item0) is float:
# degenerate case. Treat the parameterization as constant.
N = condition.size
return self.engine(
seed=self.RNG.randint(0, 2**31 - 1), **self.conditional
).draw(N)
if type(item0) is list:
# conditions are indices into list
# somewhat convoluted sampling strategy retained
# for test backwards compatibility
draws = np.zeros(condition.size)
for c in np.unique(condition):
these = c == condition
N = np.sum(these)
cond = {key: val[c] for (key, val) in self.conditional.items()}
draws[these] = self[c].draw(N)
return draws
class TimeVaryingDiscreteDistribution(Distribution):
"""
This class provides a way to define a discrete distribution that
is conditional on an index.
Wraps a list of discrete distributions.
Parameters
----------
distributions : [DiscreteDistribution]
A list of discrete distributions
seed : int
Seed for random number generator.
"""
distributions = []
def __init__(self, distributions, seed=0):
# Set up the RNG
super().__init__(seed)
self.distributions = distributions
def __getitem__(self, y):
return self.distributions[y]
def draw(self, condition):
"""
Generate arrays of draws.
The input is an array containing the conditions.
The output is an array of the same length (axis 1 dimension)
as the conditions containing random draws of the conditional
distribution.
Parameters
----------
condition : np.array
The input conditions to the distribution.
Returns:
------------
draws : np.array
"""
# for now, assume that all the conditionals
# are of the same type.
# this matches the HARK 'time-varying' model architecture.
# conditions are indices into list
# somewhat convoluted sampling strategy retained
# for test backwards compatibility
draws = np.zeros(condition.size)
for c in np.unique(condition):
these = c == condition
N = np.sum(these)
draws[these] = self.distributions[c].draw(N)
return draws
### CONTINUOUS DISTRIBUTIONS
class Lognormal(Distribution):
"""
A Lognormal distribution
Parameters
----------
mu : float or [float]
One or more means of underlying normal distribution.
Number of elements T in mu determines number of rows of output.
sigma : float or [float]
One or more standard deviations of underlying normal distribution.
Number of elements T in sigma determines number of rows of output.
seed : int
Seed for random number generator.
"""
mu = None
sigma = None
def __init__(self, mu=0.0, sigma=1.0, seed=0):
self.mu = np.array(mu)
self.sigma = np.array(sigma)
# Set up the RNG
super().__init__(seed)
if self.mu.size != self.sigma.size:
raise Exception(
"mu and sigma must be of same size, are %s, %s"
% ((self.mu.size), (self.sigma.size))
)
def draw(self, N):
"""
Generate arrays of lognormal draws. The sigma parameter can be a number
or list-like. If a number, output is a length N array of draws from the
lognormal distribution with standard deviation sigma. If a list, output is
a length T list whose t-th entry is a length N array of draws from the
lognormal with standard deviation sigma[t].
Parameters
----------
N : int
Number of draws in each row.
Returns:
------------
draws : np.array or [np.array]
T-length list of arrays of mean one lognormal draws each of size N, or
a single array of size N (if sigma is a scalar).
"""
draws = []
for j in range(self.mu.size):
draws.append(
self.RNG.lognormal(
mean=self.mu.item(j), sigma=self.sigma.item(j), size=N
)
)
# TODO: change return type to np.array?
return draws[0] if len(draws) == 1 else draws
def approx(self, N, tail_N=0, tail_bound=None, tail_order=np.e):
"""
Construct a discrete approximation to a lognormal distribution with underlying
normal distribution N(mu,sigma). Makes an equiprobable distribution by
default, but user can optionally request augmented tails with exponentially
sized point masses. This can improve solution accuracy in some models.
Parameters
----------
N: int
Number of discrete points in the "main part" of the approximation.
tail_N: int
Number of points in each "tail part" of the approximation; 0 = no tail.
tail_bound: [float]
CDF boundaries of the tails vs main portion; tail_bound[0] is the lower
tail bound, tail_bound[1] is the upper tail bound. Inoperative when
tail_N = 0. Can make "one tailed" approximations with 0.0 or 1.0.
tail_order: float
Factor by which consecutive point masses in a "tail part" differ in
probability. Should be >= 1 for sensible spacing.
Returns
-------
d : DiscreteDistribution
Probability associated with each point in array of discrete
points for discrete probability mass function.
"""
tail_bound = tail_bound if tail_bound is not None else [0.02, 0.98]
# Find the CDF boundaries of each segment
if self.sigma > 0.0:
if tail_N > 0:
lo_cut = tail_bound[0]
hi_cut = tail_bound[1]
else:
lo_cut = 0.0
hi_cut = 1.0
inner_size = hi_cut - lo_cut
inner_CDF_vals = [
lo_cut + x * N ** (-1.0) * inner_size for x in range(1, N)
]
if inner_size < 1.0:
scale = 1.0 / tail_order
mag = (1.0 - scale**tail_N) / (1.0 - scale)
lower_CDF_vals = [0.0]
if lo_cut > 0.0:
for x in range(tail_N - 1, -1, -1):
lower_CDF_vals.append(
lower_CDF_vals[-1] + lo_cut * scale**x / mag
)
upper_CDF_vals = [hi_cut]
if hi_cut < 1.0:
for x in range(tail_N):
upper_CDF_vals.append(
upper_CDF_vals[-1] + (1.0 - hi_cut) * scale**x / mag
)
CDF_vals = lower_CDF_vals + inner_CDF_vals + upper_CDF_vals
temp_cutoffs = list(
stats.lognorm.ppf(
CDF_vals[1:-1], s=self.sigma, loc=0, scale=np.exp(self.mu)
)
)
cutoffs = [0] + temp_cutoffs + [np.inf]
CDF_vals = np.array(CDF_vals)
K = CDF_vals.size - 1 # number of points in approximation
pmv = CDF_vals[1 : (K + 1)] - CDF_vals[0:K]
atoms = np.zeros(K)
for i in range(K):
zBot = cutoffs[i]
zTop = cutoffs[i + 1]
# Manual check to avoid the RuntimeWarning generated by "divide by zero"
# with np.log(zBot).
if zBot == 0:
tempBot = np.inf
else:
tempBot = (self.mu + self.sigma**2 - np.log(zBot)) / (
np.sqrt(2) * self.sigma
)
tempTop = (self.mu + self.sigma**2 - np.log(zTop)) / (
np.sqrt(2) * self.sigma
)
if tempBot <= 4:
atoms[i] = (
-0.5
* np.exp(self.mu + (self.sigma**2) * 0.5)
* (erf(tempTop) - erf(tempBot))
/ pmv[i]
)
else:
atoms[i] = (
-0.5
* np.exp(self.mu + (self.sigma**2) * 0.5)
* (erfc(tempBot) - erfc(tempTop))
/ pmv[i]
)
else:
pmv = np.ones(N) / N
atoms = np.exp(self.mu) * np.ones(N)
return DiscreteDistribution(
pmv, atoms, seed=self.RNG.randint(0, 2**31 - 1, dtype="int32")
)
@classmethod
def from_mean_std(cls, mean, std, seed=0):
"""
Construct a LogNormal distribution from its
mean and standard deviation.
This is unlike the normal constructor for the distribution,
which takes the mu and sigma for the normal distribution
that is the logarithm of the Log Normal distribution.
Parameters
----------
mean : float or [float]
One or more means. Number of elements T in mu determines number
of rows of output.
std : float or [float]
One or more standard deviations. Number of elements T in sigma
determines number of rows of output.
seed : int
Seed for random number generator.
Returns
---------
LogNormal
"""
mean_squared = mean**2
variance = std**2
mu = np.log(mean / (np.sqrt(1.0 + variance / mean_squared)))
sigma = np.sqrt(np.log(1.0 + variance / mean_squared))
return cls(mu=mu, sigma=sigma, seed=seed)
class MeanOneLogNormal(Lognormal):
def __init__(self, sigma=1.0, seed=0):
mu = -0.5 * sigma**2
super().__init__(mu=mu, sigma=sigma, seed=seed)
class Normal(Distribution):
"""
A Normal distribution.
Parameters
----------
mu : float or [float]
One or more means. Number of elements T in mu determines number
of rows of output.
sigma : float or [float]
One or more standard deviations. Number of elements T in sigma
determines number of rows of output.
seed : int
Seed for random number generator.
"""
mu = None
sigma = None
def __init__(self, mu=0.0, sigma=1.0, seed=0):
self.mu = np.array(mu)
self.sigma = np.array(sigma)
super().__init__(seed)
def draw(self, N):
"""
Generate arrays of normal draws. The mu and sigma inputs can be numbers or
list-likes. If a number, output is a length N array of draws from the normal
distribution with mean mu and standard deviation sigma. If a list, output is
a length T list whose t-th entry is a length N array with draws from the
normal distribution with mean mu[t] and standard deviation sigma[t].
Parameters
----------
N : int
Number of draws in each row.
Returns
-------
draws : np.array or [np.array]
T-length list of arrays of normal draws each of size N, or a single array
of size N (if sigma is a scalar).
"""
draws = []
for t in range(self.sigma.size):
draws.append(self.sigma.item(t) * self.RNG.randn(N) + self.mu.item(t))
return draws
def approx(self, N):
"""
Returns a discrete approximation of this distribution.
"""
x, w = np.polynomial.hermite.hermgauss(N)
# normalize w
pmv = w * np.pi**-0.5
# correct x
atoms = math.sqrt(2.0) * self.sigma * x + self.mu
return DiscreteDistribution(
pmv, atoms, seed=self.RNG.randint(0, 2**31 - 1, dtype="int32")
)
def approx_equiprobable(self, N):
CDF = np.linspace(0, 1, N + 1)
lims = stats.norm.ppf(CDF)
pdf = stats.norm.pdf(lims)
# Find conditional means using Mills's ratio
pmv = np.diff(CDF)
atoms = self.mu - np.diff(pdf) / pmv * self.sigma
return DiscreteDistribution(
pmv, atoms, seed=self.RNG.randint(0, 2**31 - 1, dtype="int32")
)
class MVNormal(Distribution):
"""
A Multivariate Normal distribution.
Parameters
----------
mu : numpy array
Mean vector.
Sigma : 2-d numpy array. Each dimension must have length equal to that of
mu.
Variance-covariance matrix.
seed : int
Seed for random number generator.
"""
mu = None
Sigma = None
def __init__(self, mu=np.array([1, 1]), Sigma=np.array([[1, 0], [0, 1]]), seed=0):
self.mu = mu
self.Sigma = Sigma
self.M = len(self.mu)
super().__init__(seed)
def draw(self, N):
"""
Generate an array of multivariate normal draws.
Parameters
----------
N : int
Number of multivariate draws.
Returns
-------
draws : np.array
Array of dimensions N x M containing the random draws, where M is
the dimension of the multivariate normal and N is the number of
draws. Each row represents a draw.
"""
draws = self.RNG.multivariate_normal(self.mu, self.Sigma, N)
return draws
def approx(self, N, equiprobable=False):
"""
Returns a discrete approximation of this distribution.
The discretization will have N**M points, where M is the dimension of
the multivariate normal.
It uses the fact that:
- Being positive definite, Sigma can be factorized as Sigma = QVQ',
with V diagonal. So, letting A=Q*sqrt(V), Sigma = A*A'.
- If Z is an N-dimensional multivariate standard normal, then
A*Z ~ N(0,A*A' = Sigma).
The idea therefore is to construct an equiprobable grid for a standard
normal and multiply it by matrix A.
"""
# Start by computing matrix A.
v, Q = np.linalg.eig(self.Sigma)
sqrtV = np.diag(np.sqrt(v))
A = np.matmul(Q, sqrtV)
# Now find a discretization for a univariate standard normal.
if equiprobable:
z_approx = Normal().approx_equiprobable(N)
else:
z_approx = Normal().approx(N)
# Now create the multivariate grid and pmv
Z = np.array(list(product(*[z_approx.atoms.flatten()] * self.M)))
pmv = np.prod(np.array(list(product(*[z_approx.pmv] * self.M))), axis=1)
# Apply mean and standard deviation to the Z grid
atoms = self.mu[None, ...] + np.matmul(Z, A.T)
# Construct and return discrete distribution
return DiscreteDistribution(
pmv, atoms.T, seed=self.RNG.randint(0, 2**31 - 1, dtype="int32")
)
class Weibull(Distribution):
"""
A Weibull distribution.
Parameters
----------
scale : float or [float]
One or more scales. Number of elements T in scale
determines number of
rows of output.
shape : float or [float]
One or more shape parameters. Number of elements T in scale
determines number of rows of output.
seed : int
Seed for random number generator.
"""
scale = None
shape = None
def __init__(self, scale=1.0, shape=1.0, seed=0):
self.scale = np.array(scale)
self.shape = np.array(shape)
# Set up the RNG
super().__init__(seed)
def draw(self, N):
"""
Generate arrays of Weibull draws. The scale and shape inputs can be
numbers or list-likes. If a number, output is a length N array of draws from
the Weibull distribution with the given scale and shape. If a list, output
is a length T list whose t-th entry is a length N array with draws from the
Weibull distribution with scale scale[t] and shape shape[t].
Note: When shape=1, the Weibull distribution is simply the exponential dist.
Mean: scale*Gamma(1 + 1/shape)
Parameters
----------
N : int
Number of draws in each row.
Returns:
------------
draws : np.array or [np.array]
T-length list of arrays of Weibull draws each of size N, or a single
array of size N (if sigma is a scalar).
"""
draws = []
for j in range(self.scale.size):
draws.append(
self.scale.item(j)
* (-np.log(1.0 - self.RNG.rand(N))) ** (1.0 / self.shape.item(j))
)
return draws[0] if len(draws) == 1 else draws
class Uniform(Distribution):
"""
A Uniform distribution.
Parameters
----------
bot : float or [float]
One or more bottom values.
Number of elements T in mu determines number
of rows of output.
top : float or [float]
One or more top values.
Number of elements T in top determines number of
rows of output.
seed : int
Seed for random number generator.
"""
bot = None
top = None
def __init__(self, bot=0.0, top=1.0, seed=0):
self.bot = np.array(bot)
self.top = np.array(top)
# Set up the RNG
self.RNG = np.random.RandomState(seed)
def draw(self, N):
"""
Generate arrays of uniform draws. The bot and top inputs can be numbers or
list-likes. If a number, output is a length N array of draws from the
uniform distribution on [bot,top]. If a list, output is a length T list
whose t-th entry is a length N array with draws from the uniform distribution
on [bot[t],top[t]].
Parameters
----------
N : int
Number of draws in each row.
Returns
-------
draws : np.array or [np.array]
T-length list of arrays of uniform draws each of size N, or a single
array of size N (if sigma is a scalar).
"""
draws = []
for j in range(self.bot.size):
draws.append(
self.bot.item(j)
+ (self.top.item(j) - self.bot.item(j)) * self.RNG.rand(N)
)
return draws[0] if len(draws) == 1 else draws
def approx(self, N, endpoint=False):
"""
Makes a discrete approximation to this uniform distribution.
Parameters
----------
N : int
The number of points in the discrete approximation.
endpoint : bool
Whether to include the endpoints in the approximation.
Returns
-------
d : DiscreteDistribution
Probability associated with each point in array of discrete
points for discrete probability mass function.
"""
pmv = np.ones(N) / float(N)
center = (self.top + self.bot) / 2.0
width = (self.top - self.bot) / 2.0
atoms = center + width * np.linspace(-(N - 1.0) / 2.0, (N - 1.0) / 2.0, N) / (
N / 2.0
)
if endpoint: # insert endpoints with infinitesimally small mass
atoms = np.concatenate(([self.bot], atoms, [self.top]))
pmv = np.concatenate(([0.0], pmv, [0.0]))
return DiscreteDistribution(
pmv, atoms, seed=self.RNG.randint(0, 2**31 - 1, dtype="int32")
)
### DISCRETE DISTRIBUTIONS
class Bernoulli(Distribution):
"""
A Bernoulli distribution.
Parameters
----------
p : float or [float]
Probability or probabilities of the event occurring (True).
seed : int
Seed for random number generator.
"""
p = None
def __init__(self, p=0.5, seed=0):
self.p = np.array(p)
# Set up the RNG
super().__init__(seed)
def draw(self, N):
"""
Generates arrays of booleans drawn from a simple Bernoulli distribution.
The input p can be a float or a list-like of floats; its length T determines
the number of entries in the output. The t-th entry of the output is an
array of N booleans which are True with probability p[t] and False otherwise.
Arguments
---------
N : int
Number of draws in each row.
Returns
-------
draws : np.array or [np.array]
T-length list of arrays of Bernoulli draws each of size N, or a single
array of size N (if sigma is a scalar).
"""
draws = []
for j in range(self.p.size):
draws.append(self.RNG.uniform(size=N) < self.p.item(j))
return draws[0] if len(draws) == 1 else draws
class DiscreteDistribution(Distribution):
"""
A representation of a discrete probability distribution.
Parameters
----------
pmv : np.array
An array of floats representing a probability mass function.
atoms : np.array
Discrete point values for each probability mass.
For multivariate distributions, the last dimension of atoms must index
"atom" or the random realization. For instance, if atoms.shape == (2,6,4),
the random variable has 4 possible realizations and each of them has shape (2,6).
seed : int
Seed for random number generator.
"""
pmv = None
atoms = None
def __init__(self, pmv, atoms, seed=0):
self.pmv = pmv
if len(atoms.shape) < 2:
self.atoms = atoms[None, ...]
else:
self.atoms = atoms
# Set up the RNG
super().__init__(seed)
# Check that pmv and atoms have compatible dimensions.
same_dims = len(pmv) == atoms.shape[-1]
if not same_dims:
raise ValueError(
"Provided pmv and atoms arrays have incompatible dimensions. "
+ "The length of the pmv must be equal to that of atoms's last dimension."
)
def dim(self):
"""
Last dimension of self.atoms indexes "atom."
"""
return self.atoms.shape[:-1]
def draw_events(self, n):
"""
Draws N 'events' from the distribution PMF.
These events are indices into atoms.
"""
# Generate a cumulative distribution
base_draws = self.RNG.uniform(size=n)
cum_dist = np.cumsum(self.pmv)
# Convert the basic uniform draws into discrete draws
indices = cum_dist.searchsorted(base_draws)
return indices
def draw(self, N, atoms=None, exact_match=False):
"""
Simulates N draws from a discrete distribution with probabilities P and outcomes atoms.
Parameters
----------
N : int
Number of draws to simulate.
atoms : None, int, or np.array
If None, then use this distribution's atoms for point values.
If an int, then the index of atoms for the point values.
If an np.array, use the array for the point values.
exact_match : boolean
Whether the draws should "exactly" match the discrete distribution (as
closely as possible given finite draws). When True, returned draws are
a random permutation of the N-length list that best fits the discrete
distribution. When False (default), each draw is independent from the
others and the result could deviate from the input.
Returns
-------
draws : np.array
An array of draws from the discrete distribution; each element is a value in atoms.
"""
if atoms is None:
atoms = self.atoms
elif isinstance(atoms, int):
atoms = self.atoms[atoms]
if exact_match:
events = np.arange(self.pmv.size) # just a list of integers
cutoffs = np.round(np.cumsum(self.pmv) * N).astype(
int
) # cutoff points between discrete outcomes
top = 0
# Make a list of event indices that closely matches the discrete distribution
event_list = []
for j in range(events.size):
bot = top
top = cutoffs[j]
event_list += (top - bot) * [events[j]]
# Randomly permute the event indices
indices = self.RNG.permutation(event_list)
# Draw event indices randomly from the discrete distribution
else:
indices = self.draw_events(N)
# Create and fill in the output array of draws based on the output of event indices
draws = atoms[..., indices]
# TODO: some models expect univariate draws to just be a 1d vector. Fix those models.
if len(draws.shape) == 2 and draws.shape[0] == 1:
draws = draws.flatten()
return draws
def expected(self, func=None, *args):
"""
Expected value of a function, given an array of configurations of its
inputs along with a DiscreteDistribution object that specifies the
probability of each configuration.
Parameters
----------
func : function
The function to be evaluated.
This function should take the full array of distribution values
and return either arrays of arbitrary shape or scalars.
It may also take other arguments *args.
This function differs from the standalone `calc_expectation`
method in that it uses numpy's vectorization and broadcasting
rules to avoid costly iteration.
Note: If you need to use a function that acts on single outcomes
of the distribution, consier `distribution.calc_expectation`.
*args :
Other inputs for func, representing the non-stochastic arguments.
The the expectation is computed at f(dstn, *args).
Returns
-------
f_exp : np.array or scalar
The expectation of the function at the queried values.
Scalar if only one value.
"""
if func is None:
# if no function is provided, it's much faster to go straight
# to dot product instead of calling the dummy function.
f_query = self.atoms
else:
# if a function is provided, we need to add one more dimension,
# the atom dimension, to any inputs that are n-dim arrays.
# This allows numpy to easily broadcast the function's output.
# For more information on broadcasting, see:
# https://numpy.org/doc/stable/user/basics.broadcasting.html#general-broadcasting-rules
args = [
arg[..., np.newaxis] if isinstance(arg, np.ndarray) else arg
for arg in args
]
f_query = func(self.atoms, *args)
f_exp = np.dot(f_query, self.pmv)
return f_exp
def dist_of_func(self, func=lambda x: x, *args):
"""
Finds the distribution of a random variable Y that is a function
of discrete random variable atoms, Y=f(atoms).
Parameters