API Reference

Cdf

Bases: Distribution

Represents a Cumulative Distribution Function (CDF).

Source code in empiricaldist/empiricaldist.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
class Cdf(Distribution):
    """Represents a Cumulative Distribution Function (CDF)."""

    def copy(self, deep=True):
        """Make a copy.

        Args:
            deep: whether to make a deep copy

        Returns: new Cdf
        """
        return Cdf(self, copy=deep)

    @staticmethod
    def from_seq(seq, normalize=True, sort=True, **options):
        """Make a CDF from a sequence of values.

        Args:
            seq: iterable
            normalize: whether to normalize the Cdf, default True
            sort: whether to sort the Cdf by values, default True
            options: passed to the pd.Series constructor

        Returns: CDF object
        """
        # if normalize==True, normalize AFTER making the Cdf
        # so the last element is exactly 1.0
        pmf = Pmf.from_seq(seq, normalize=False, sort=sort, **options)
        return pmf.make_cdf(normalize=normalize)

    def step(self, **options):
        """Plot the Cdf as a step function.

        Args:
            options: passed to pd.Series.plot
        """
        underride(options, drawstyle="steps-post")
        self.plot(**options)

    def normalize(self):
        """Make the probabilities add up to 1 (modifies self).

        Returns: normalizing constant
        """
        total = self.ps[-1]
        self /= total
        return total

    @property
    def forward(self, **kwargs):
        """Make a function that computes the forward Cdf.

        Args:
            kwargs: keyword arguments passed to interp1d

        Returns: interpolation function from qs to ps
        """

        underride(
            kwargs,
            kind="previous",
            copy=False,
            assume_sorted=True,
            bounds_error=False,
            fill_value=(0, 1),
        )

        interp = interp1d(self.qs, self.ps, **kwargs)
        return interp

    @property
    def inverse(self, **kwargs):
        """Make a function that computes the inverse Cdf.

        Args:
            kwargs: keyword arguments passed to interp1d

        Returns: interpolation function from ps to qs
        """
        underride(
            kwargs,
            kind="next",
            copy=False,
            assume_sorted=True,
            bounds_error=False,
            fill_value=(self.qs[0], np.nan),
        )

        interp = interp1d(self.ps, self.qs, **kwargs)
        return interp

    # calling a Cdf like a function does forward lookup
    __call__ = forward

    # quantile is the same as an inverse lookup
    quantile = inverse

    def median(self):
        """Median (50th percentile).

        Returns: float
        """
        return self.quantile(0.5)

    def make_pmf(self, **kwargs):
        """Make a Pmf from the Cdf.

        Args:
            normalize: Boolean, whether to normalize the Pmf
            kwargs: passed to the Pmf constructor

        Returns: Pmf
        """
        normalize = kwargs.pop("normalize", False)

        diff = np.diff(self, prepend=0)
        pmf = Pmf(diff, index=self.index.copy(), **kwargs)
        if normalize:
            pmf.normalize()
        return pmf

    def make_surv(self, **kwargs):
        """Make a Surv object from the Cdf.

        Args:
            kwargs: passed to the Surv constructor

        Returns: Surv object
        """
        normalize = kwargs.pop("normalize", False)
        total = self.ps[-1]
        surv = Surv(total - self, **kwargs)
        surv.total = total
        if normalize:
            self.normalize()
        return surv

    def make_hazard(self, **kwargs):
        """Make a Hazard from the Cdf.

        Args:
            kwargs: passed to the Hazard constructor

        Returns: Hazard
        """
        pmf = self.make_pmf()
        surv = self.make_surv()
        haz = Hazard(pmf / (pmf + surv), **kwargs)
        haz.total = getattr(surv, "total", 1.0)
        return haz

    def make_same(self, dist):
        """Convert the given dist to Cdf.

        Args:
            dist: Distribution

        Returns: Cdf
        """
        return dist.make_cdf()

    def sample(self, n=1, **kwargs):
        """Sample with replacement using probabilities as weights.

        Uses the inverse CDF.

        Args:
            n: number of values
            **kwargs: passed to interp1d

        Returns: NumPy array
        """
        ps = np.random.random(n)
        return self.inverse(ps, **kwargs)

    def max_dist(self, n):
        """Distribution of the maximum of `n` values from this distribution.

        Args:
            n: integer

        Returns: Cdf
        """
        ps = self**n
        return Cdf(ps, self.index.copy())

    def min_dist(self, n):
        """Distribution of the minimum of `n` values from this distribution.

        Args:
            n: integer

        Returns: Cdf
        """
        ps = 1 - (1 - self) ** n
        return Cdf(ps, self.index.copy())

forward property

Make a function that computes the forward Cdf.

Parameters:
  • kwargs

    keyword arguments passed to interp1d

Returns: interpolation function from qs to ps

inverse property

Make a function that computes the inverse Cdf.

Parameters:
  • kwargs

    keyword arguments passed to interp1d

Returns: interpolation function from ps to qs

copy(deep=True)

Make a copy.

Parameters:
  • deep

    whether to make a deep copy

Returns: new Cdf

Source code in empiricaldist/empiricaldist.py
925
926
927
928
929
930
931
932
933
def copy(self, deep=True):
    """Make a copy.

    Args:
        deep: whether to make a deep copy

    Returns: new Cdf
    """
    return Cdf(self, copy=deep)

from_seq(seq, normalize=True, sort=True, **options) staticmethod

Make a CDF from a sequence of values.

Parameters:
  • seq

    iterable

  • normalize

    whether to normalize the Cdf, default True

  • sort

    whether to sort the Cdf by values, default True

  • options

    passed to the pd.Series constructor

Returns: CDF object

Source code in empiricaldist/empiricaldist.py
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
@staticmethod
def from_seq(seq, normalize=True, sort=True, **options):
    """Make a CDF from a sequence of values.

    Args:
        seq: iterable
        normalize: whether to normalize the Cdf, default True
        sort: whether to sort the Cdf by values, default True
        options: passed to the pd.Series constructor

    Returns: CDF object
    """
    # if normalize==True, normalize AFTER making the Cdf
    # so the last element is exactly 1.0
    pmf = Pmf.from_seq(seq, normalize=False, sort=sort, **options)
    return pmf.make_cdf(normalize=normalize)

make_hazard(**kwargs)

Make a Hazard from the Cdf.

Parameters:
  • kwargs

    passed to the Hazard constructor

Returns: Hazard

Source code in empiricaldist/empiricaldist.py
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
def make_hazard(self, **kwargs):
    """Make a Hazard from the Cdf.

    Args:
        kwargs: passed to the Hazard constructor

    Returns: Hazard
    """
    pmf = self.make_pmf()
    surv = self.make_surv()
    haz = Hazard(pmf / (pmf + surv), **kwargs)
    haz.total = getattr(surv, "total", 1.0)
    return haz

make_pmf(**kwargs)

Make a Pmf from the Cdf.

Parameters:
  • normalize

    Boolean, whether to normalize the Pmf

  • kwargs

    passed to the Pmf constructor

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
def make_pmf(self, **kwargs):
    """Make a Pmf from the Cdf.

    Args:
        normalize: Boolean, whether to normalize the Pmf
        kwargs: passed to the Pmf constructor

    Returns: Pmf
    """
    normalize = kwargs.pop("normalize", False)

    diff = np.diff(self, prepend=0)
    pmf = Pmf(diff, index=self.index.copy(), **kwargs)
    if normalize:
        pmf.normalize()
    return pmf

make_same(dist)

Convert the given dist to Cdf.

Parameters:
  • dist

    Distribution

Returns: Cdf

Source code in empiricaldist/empiricaldist.py
1073
1074
1075
1076
1077
1078
1079
1080
1081
def make_same(self, dist):
    """Convert the given dist to Cdf.

    Args:
        dist: Distribution

    Returns: Cdf
    """
    return dist.make_cdf()

make_surv(**kwargs)

Make a Surv object from the Cdf.

Parameters:
  • kwargs

    passed to the Surv constructor

Returns: Surv object

Source code in empiricaldist/empiricaldist.py
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
def make_surv(self, **kwargs):
    """Make a Surv object from the Cdf.

    Args:
        kwargs: passed to the Surv constructor

    Returns: Surv object
    """
    normalize = kwargs.pop("normalize", False)
    total = self.ps[-1]
    surv = Surv(total - self, **kwargs)
    surv.total = total
    if normalize:
        self.normalize()
    return surv

max_dist(n)

Distribution of the maximum of n values from this distribution.

Parameters:
  • n

    integer

Returns: Cdf

Source code in empiricaldist/empiricaldist.py
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
def max_dist(self, n):
    """Distribution of the maximum of `n` values from this distribution.

    Args:
        n: integer

    Returns: Cdf
    """
    ps = self**n
    return Cdf(ps, self.index.copy())

median()

Median (50th percentile).

Returns: float

Source code in empiricaldist/empiricaldist.py
1019
1020
1021
1022
1023
1024
def median(self):
    """Median (50th percentile).

    Returns: float
    """
    return self.quantile(0.5)

min_dist(n)

Distribution of the minimum of n values from this distribution.

Parameters:
  • n

    integer

Returns: Cdf

Source code in empiricaldist/empiricaldist.py
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
def min_dist(self, n):
    """Distribution of the minimum of `n` values from this distribution.

    Args:
        n: integer

    Returns: Cdf
    """
    ps = 1 - (1 - self) ** n
    return Cdf(ps, self.index.copy())

normalize()

Make the probabilities add up to 1 (modifies self).

Returns: normalizing constant

Source code in empiricaldist/empiricaldist.py
961
962
963
964
965
966
967
968
def normalize(self):
    """Make the probabilities add up to 1 (modifies self).

    Returns: normalizing constant
    """
    total = self.ps[-1]
    self /= total
    return total

sample(n=1, **kwargs)

Sample with replacement using probabilities as weights.

Uses the inverse CDF.

Parameters:
  • n

    number of values

  • **kwargs

    passed to interp1d

Returns: NumPy array

Source code in empiricaldist/empiricaldist.py
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
def sample(self, n=1, **kwargs):
    """Sample with replacement using probabilities as weights.

    Uses the inverse CDF.

    Args:
        n: number of values
        **kwargs: passed to interp1d

    Returns: NumPy array
    """
    ps = np.random.random(n)
    return self.inverse(ps, **kwargs)

step(**options)

Plot the Cdf as a step function.

Parameters:
  • options

    passed to pd.Series.plot

Source code in empiricaldist/empiricaldist.py
952
953
954
955
956
957
958
959
def step(self, **options):
    """Plot the Cdf as a step function.

    Args:
        options: passed to pd.Series.plot
    """
    underride(options, drawstyle="steps-post")
    self.plot(**options)

Distribution

Bases: Series

Parent class of all distribution representations.

This class inherits from Pandas Series and provides methods common to all distribution types.

Source code in empiricaldist/empiricaldist.py
 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
class Distribution(pd.Series):
    """Parent class of all distribution representations.

    This class inherits from Pandas `Series` and provides
    methods common to all distribution types.
    """

    # total is defined here as a class level variable so it
    # is always available, even if it is not set in an instance
    total = None

    @property
    def qs(self):
        """Get the quantities.

        Returns: NumPy array
        """
        return self.index.values

    @property
    def ps(self):
        """Get the probabilities.

        Returns: NumPy array
        """
        return self.values

    def head(self, n=3):
        """Override Series.head to return a Distribution.

        Args:
            n: number of rows

        Returns: Distribution
        """
        s = super().head(n)
        return self.__class__(s)

    def tail(self, n=3):
        """Override Series.tail to return a Distribution.

        Args:
            n: number of rows

        Returns: Distribution
        """
        s = super().tail(n)
        return self.__class__(s)

    def bar(self, **options):
        """Make a bar plot.

        Note: A previous version of this function used pd.Series.plot.bar,
        but that was a mistake, because that function treats the quantities
        as categorical, even if they are numerical, leading to hilariously
        unexpected results!

        Args:
            options: passed to plt.bar
        """
        underride(options, label=self.name)
        plt.bar(self.qs, self.ps, **options)

    def transform(self, *args, **kwargs):
        """Override to transform the quantities, not the probabilities.

        Args:
            *args: passed to Series.transform
            **kwargs: passed to Series.transform

        Returns: Distribution with the same type as self
        """
        qs = self.index.to_series().transform(*args, **kwargs)
        return self.__class__(self.ps, qs, copy=True)

    def _repr_html_(self):
        """Returns an HTML representation of the series.

        Mostly used for Jupyter notebooks.
        """
        df = pd.DataFrame(dict(probs=self))
        return df._repr_html_()

    def __call__(self, qs):
        """Look up quantities, return counts/probabilities/hazards.

        Args:
            qs: quantity or sequence of quantities

        Returns:
            count/probability/hazard or array of count/probabiliy/hazard
        """
        string_types = (str, bytes, bytearray)

        # if qs is a sequence type, use reindex;
        # otherwise use get
        if hasattr(qs, "__iter__") and not isinstance(qs, string_types):
            s = self.reindex(qs, fill_value=0)
            return s.to_numpy()
        else:
            return self.get(qs, default=0)

    def mean(self):
        """Expected value.

        Returns: float
        """
        return self.make_pmf().mean()

    def mode(self, **kwargs):
        """Most common value.

        If multiple quantities have the maximum probability,
        the first maximal quantity is returned.

        Args:
            kwargs: passed to Series.mode

        Returns: type of the quantities
        """
        return self.make_pmf().mode(**kwargs)

    def var(self):
        """Variance.

        Returns: float
        """
        return self.make_pmf().var()

    def std(self):
        """Standard deviation.

        Returns: float
        """
        return self.make_pmf().std()

    def median(self):
        """Median (50th percentile).

        There are several definitions of median;
        the one implemented here is just the 50th percentile.

        Returns: float
        """
        return self.make_cdf().median()

    def quantile(self, ps, **kwargs):
        """Compute the inverse CDF of ps.

        That is, the quantities that correspond to the given probabilities.

        Args:
            ps: float or sequence of floats
            kwargs: passed to Cdf.quantile

        Returns: float
        """
        return self.make_cdf().quantile(ps, **kwargs)

    def credible_interval(self, p):
        """Credible interval containing the given probability.

        Args:
            p: float 0-1

        Returns: array of two quantities
        """
        tail = (1 - p) / 2
        ps = [tail, 1 - tail]
        return self.quantile(ps)

    def choice(self, size=1, **kwargs):
        """Makes a random selection.

        Uses the probabilities as weights unless `p` is provided.

        Args:
            size: number of values or tuple of dimensions
            kwargs: passed to np.random.choice

        Returns: NumPy array
        """
        pmf = self.make_pmf()
        return pmf.choice(size, **kwargs)

    def sample(self, n, **kwargs):
        """Sample with replacement using probabilities as weights.

        Uses the inverse CDF.

        Args:
            n: number of values
            **kwargs: passed to interp1d

        Returns: NumPy array
        """
        cdf = self.make_cdf()
        return cdf.sample(n, **kwargs)

    def add_dist(self, x):
        """Distribution of the sum of values drawn from self and x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: new Distribution, same subtype as self
        """
        pmf = self.make_pmf()
        res = pmf.add_dist(x)
        return self.make_same(res)

    def sub_dist(self, x):
        """Distribution of the diff of values drawn from self and x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: new Distribution, same subtype as self
        """
        pmf = self.make_pmf()
        res = pmf.sub_dist(x)
        return self.make_same(res)

    def mul_dist(self, x):
        """Distribution of the product of values drawn from self and x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: new Distribution, same subtype as self
        """
        pmf = self.make_pmf()
        res = pmf.mul_dist(x)
        return self.make_same(res)

    def div_dist(self, x):
        """Distribution of the ratio of values drawn from self and x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: new Distribution, same subtype as self
        """
        pmf = self.make_pmf()
        res = pmf.div_dist(x)
        return self.make_same(res)

    def pmf_outer(self, dist, ufunc):
        """Computes the outer product of two PMFs.

        Args:
            dist: Distribution object
            ufunc: function to apply to the qs

        Returns: NumPy array
        """
        pmf = self.make_pmf()
        return pmf.pmf_outer(dist, ufunc)

    def gt_dist(self, x):
        """Probability that a value from self is greater than a value from x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: float probability
        """
        pmf = self.make_pmf()
        return pmf.gt_dist(x)

    def lt_dist(self, x):
        """Probability that a value from self is less than a value from x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: float probability
        """
        pmf = self.make_pmf()
        return pmf.lt_dist(x)

    def ge_dist(self, x):
        """Probability that a value from self is >= than a value from x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: float probability
        """
        pmf = self.make_pmf()
        return pmf.ge_dist(x)

    def le_dist(self, x):
        """Probability that a value from self is <= than a value from x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: float probability
        """
        pmf = self.make_pmf()
        return pmf.le_dist(x)

    def eq_dist(self, x):
        """Probability that a value from self equals a value from x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: float probability
        """
        pmf = self.make_pmf()
        return pmf.eq_dist(x)

    def ne_dist(self, x):
        """Probability that a value from self is <= than a value from x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: float probability
        """
        pmf = self.make_pmf()
        return pmf.ne_dist(x)

    def max_dist(self, n):
        """Distribution of the maximum of `n` values from this distribution.

        Args:
            n: integer

        Returns: Distribution, same type as self
        """
        cdf = self.make_cdf().max_dist(n)
        return self.make_same(cdf)

    def min_dist(self, n):
        """Distribution of the minimum of `n` values from this distribution.

        Args:
            n: integer

        Returns: Distribution, same type as self
        """
        cdf = self.make_cdf().min_dist(n)
        return self.make_same(cdf)

    prob_gt = gt_dist
    prob_lt = lt_dist
    prob_ge = ge_dist
    prob_le = le_dist
    prob_eq = eq_dist
    prob_ne = ne_dist

ps property

Get the probabilities.

Returns: NumPy array

qs property

Get the quantities.

Returns: NumPy array

__call__(qs)

Look up quantities, return counts/probabilities/hazards.

Parameters:
  • qs

    quantity or sequence of quantities

Returns:
  • count/probability/hazard or array of count/probabiliy/hazard

Source code in empiricaldist/empiricaldist.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def __call__(self, qs):
    """Look up quantities, return counts/probabilities/hazards.

    Args:
        qs: quantity or sequence of quantities

    Returns:
        count/probability/hazard or array of count/probabiliy/hazard
    """
    string_types = (str, bytes, bytearray)

    # if qs is a sequence type, use reindex;
    # otherwise use get
    if hasattr(qs, "__iter__") and not isinstance(qs, string_types):
        s = self.reindex(qs, fill_value=0)
        return s.to_numpy()
    else:
        return self.get(qs, default=0)

add_dist(x)

Distribution of the sum of values drawn from self and x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: new Distribution, same subtype as self

Source code in empiricaldist/empiricaldist.py
243
244
245
246
247
248
249
250
251
252
253
def add_dist(self, x):
    """Distribution of the sum of values drawn from self and x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: new Distribution, same subtype as self
    """
    pmf = self.make_pmf()
    res = pmf.add_dist(x)
    return self.make_same(res)

bar(**options)

Make a bar plot.

Note: A previous version of this function used pd.Series.plot.bar, but that was a mistake, because that function treats the quantities as categorical, even if they are numerical, leading to hilariously unexpected results!

Parameters:
  • options

    passed to plt.bar

Source code in empiricaldist/empiricaldist.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def bar(self, **options):
    """Make a bar plot.

    Note: A previous version of this function used pd.Series.plot.bar,
    but that was a mistake, because that function treats the quantities
    as categorical, even if they are numerical, leading to hilariously
    unexpected results!

    Args:
        options: passed to plt.bar
    """
    underride(options, label=self.name)
    plt.bar(self.qs, self.ps, **options)

choice(size=1, **kwargs)

Makes a random selection.

Uses the probabilities as weights unless p is provided.

Parameters:
  • size

    number of values or tuple of dimensions

  • kwargs

    passed to np.random.choice

Returns: NumPy array

Source code in empiricaldist/empiricaldist.py
215
216
217
218
219
220
221
222
223
224
225
226
227
def choice(self, size=1, **kwargs):
    """Makes a random selection.

    Uses the probabilities as weights unless `p` is provided.

    Args:
        size: number of values or tuple of dimensions
        kwargs: passed to np.random.choice

    Returns: NumPy array
    """
    pmf = self.make_pmf()
    return pmf.choice(size, **kwargs)

credible_interval(p)

Credible interval containing the given probability.

Parameters:
  • p

    float 0-1

Returns: array of two quantities

Source code in empiricaldist/empiricaldist.py
203
204
205
206
207
208
209
210
211
212
213
def credible_interval(self, p):
    """Credible interval containing the given probability.

    Args:
        p: float 0-1

    Returns: array of two quantities
    """
    tail = (1 - p) / 2
    ps = [tail, 1 - tail]
    return self.quantile(ps)

div_dist(x)

Distribution of the ratio of values drawn from self and x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: new Distribution, same subtype as self

Source code in empiricaldist/empiricaldist.py
279
280
281
282
283
284
285
286
287
288
289
def div_dist(self, x):
    """Distribution of the ratio of values drawn from self and x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: new Distribution, same subtype as self
    """
    pmf = self.make_pmf()
    res = pmf.div_dist(x)
    return self.make_same(res)

eq_dist(x)

Probability that a value from self equals a value from x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: float probability

Source code in empiricaldist/empiricaldist.py
347
348
349
350
351
352
353
354
355
356
def eq_dist(self, x):
    """Probability that a value from self equals a value from x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: float probability
    """
    pmf = self.make_pmf()
    return pmf.eq_dist(x)

ge_dist(x)

Probability that a value from self is >= than a value from x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: float probability

Source code in empiricaldist/empiricaldist.py
325
326
327
328
329
330
331
332
333
334
def ge_dist(self, x):
    """Probability that a value from self is >= than a value from x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: float probability
    """
    pmf = self.make_pmf()
    return pmf.ge_dist(x)

gt_dist(x)

Probability that a value from self is greater than a value from x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: float probability

Source code in empiricaldist/empiricaldist.py
303
304
305
306
307
308
309
310
311
312
def gt_dist(self, x):
    """Probability that a value from self is greater than a value from x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: float probability
    """
    pmf = self.make_pmf()
    return pmf.gt_dist(x)

head(n=3)

Override Series.head to return a Distribution.

Parameters:
  • n

    number of rows

Returns: Distribution

Source code in empiricaldist/empiricaldist.py
71
72
73
74
75
76
77
78
79
80
def head(self, n=3):
    """Override Series.head to return a Distribution.

    Args:
        n: number of rows

    Returns: Distribution
    """
    s = super().head(n)
    return self.__class__(s)

le_dist(x)

Probability that a value from self is <= than a value from x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: float probability

Source code in empiricaldist/empiricaldist.py
336
337
338
339
340
341
342
343
344
345
def le_dist(self, x):
    """Probability that a value from self is <= than a value from x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: float probability
    """
    pmf = self.make_pmf()
    return pmf.le_dist(x)

lt_dist(x)

Probability that a value from self is less than a value from x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: float probability

Source code in empiricaldist/empiricaldist.py
314
315
316
317
318
319
320
321
322
323
def lt_dist(self, x):
    """Probability that a value from self is less than a value from x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: float probability
    """
    pmf = self.make_pmf()
    return pmf.lt_dist(x)

max_dist(n)

Distribution of the maximum of n values from this distribution.

Parameters:
  • n

    integer

Returns: Distribution, same type as self

Source code in empiricaldist/empiricaldist.py
369
370
371
372
373
374
375
376
377
378
def max_dist(self, n):
    """Distribution of the maximum of `n` values from this distribution.

    Args:
        n: integer

    Returns: Distribution, same type as self
    """
    cdf = self.make_cdf().max_dist(n)
    return self.make_same(cdf)

mean()

Expected value.

Returns: float

Source code in empiricaldist/empiricaldist.py
146
147
148
149
150
151
def mean(self):
    """Expected value.

    Returns: float
    """
    return self.make_pmf().mean()

median()

Median (50th percentile).

There are several definitions of median; the one implemented here is just the 50th percentile.

Returns: float

Source code in empiricaldist/empiricaldist.py
180
181
182
183
184
185
186
187
188
def median(self):
    """Median (50th percentile).

    There are several definitions of median;
    the one implemented here is just the 50th percentile.

    Returns: float
    """
    return self.make_cdf().median()

min_dist(n)

Distribution of the minimum of n values from this distribution.

Parameters:
  • n

    integer

Returns: Distribution, same type as self

Source code in empiricaldist/empiricaldist.py
380
381
382
383
384
385
386
387
388
389
def min_dist(self, n):
    """Distribution of the minimum of `n` values from this distribution.

    Args:
        n: integer

    Returns: Distribution, same type as self
    """
    cdf = self.make_cdf().min_dist(n)
    return self.make_same(cdf)

mode(**kwargs)

Most common value.

If multiple quantities have the maximum probability, the first maximal quantity is returned.

Parameters:
  • kwargs

    passed to Series.mode

Returns: type of the quantities

Source code in empiricaldist/empiricaldist.py
153
154
155
156
157
158
159
160
161
162
163
164
def mode(self, **kwargs):
    """Most common value.

    If multiple quantities have the maximum probability,
    the first maximal quantity is returned.

    Args:
        kwargs: passed to Series.mode

    Returns: type of the quantities
    """
    return self.make_pmf().mode(**kwargs)

mul_dist(x)

Distribution of the product of values drawn from self and x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: new Distribution, same subtype as self

Source code in empiricaldist/empiricaldist.py
267
268
269
270
271
272
273
274
275
276
277
def mul_dist(self, x):
    """Distribution of the product of values drawn from self and x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: new Distribution, same subtype as self
    """
    pmf = self.make_pmf()
    res = pmf.mul_dist(x)
    return self.make_same(res)

ne_dist(x)

Probability that a value from self is <= than a value from x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: float probability

Source code in empiricaldist/empiricaldist.py
358
359
360
361
362
363
364
365
366
367
def ne_dist(self, x):
    """Probability that a value from self is <= than a value from x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: float probability
    """
    pmf = self.make_pmf()
    return pmf.ne_dist(x)

pmf_outer(dist, ufunc)

Computes the outer product of two PMFs.

Parameters:
  • dist

    Distribution object

  • ufunc

    function to apply to the qs

Returns: NumPy array

Source code in empiricaldist/empiricaldist.py
291
292
293
294
295
296
297
298
299
300
301
def pmf_outer(self, dist, ufunc):
    """Computes the outer product of two PMFs.

    Args:
        dist: Distribution object
        ufunc: function to apply to the qs

    Returns: NumPy array
    """
    pmf = self.make_pmf()
    return pmf.pmf_outer(dist, ufunc)

quantile(ps, **kwargs)

Compute the inverse CDF of ps.

That is, the quantities that correspond to the given probabilities.

Parameters:
  • ps

    float or sequence of floats

  • kwargs

    passed to Cdf.quantile

Returns: float

Source code in empiricaldist/empiricaldist.py
190
191
192
193
194
195
196
197
198
199
200
201
def quantile(self, ps, **kwargs):
    """Compute the inverse CDF of ps.

    That is, the quantities that correspond to the given probabilities.

    Args:
        ps: float or sequence of floats
        kwargs: passed to Cdf.quantile

    Returns: float
    """
    return self.make_cdf().quantile(ps, **kwargs)

sample(n, **kwargs)

Sample with replacement using probabilities as weights.

Uses the inverse CDF.

Parameters:
  • n

    number of values

  • **kwargs

    passed to interp1d

Returns: NumPy array

Source code in empiricaldist/empiricaldist.py
229
230
231
232
233
234
235
236
237
238
239
240
241
def sample(self, n, **kwargs):
    """Sample with replacement using probabilities as weights.

    Uses the inverse CDF.

    Args:
        n: number of values
        **kwargs: passed to interp1d

    Returns: NumPy array
    """
    cdf = self.make_cdf()
    return cdf.sample(n, **kwargs)

std()

Standard deviation.

Returns: float

Source code in empiricaldist/empiricaldist.py
173
174
175
176
177
178
def std(self):
    """Standard deviation.

    Returns: float
    """
    return self.make_pmf().std()

sub_dist(x)

Distribution of the diff of values drawn from self and x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: new Distribution, same subtype as self

Source code in empiricaldist/empiricaldist.py
255
256
257
258
259
260
261
262
263
264
265
def sub_dist(self, x):
    """Distribution of the diff of values drawn from self and x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: new Distribution, same subtype as self
    """
    pmf = self.make_pmf()
    res = pmf.sub_dist(x)
    return self.make_same(res)

tail(n=3)

Override Series.tail to return a Distribution.

Parameters:
  • n

    number of rows

Returns: Distribution

Source code in empiricaldist/empiricaldist.py
82
83
84
85
86
87
88
89
90
91
def tail(self, n=3):
    """Override Series.tail to return a Distribution.

    Args:
        n: number of rows

    Returns: Distribution
    """
    s = super().tail(n)
    return self.__class__(s)

transform(*args, **kwargs)

Override to transform the quantities, not the probabilities.

Parameters:
  • *args

    passed to Series.transform

  • **kwargs

    passed to Series.transform

Returns: Distribution with the same type as self

Source code in empiricaldist/empiricaldist.py
107
108
109
110
111
112
113
114
115
116
117
def transform(self, *args, **kwargs):
    """Override to transform the quantities, not the probabilities.

    Args:
        *args: passed to Series.transform
        **kwargs: passed to Series.transform

    Returns: Distribution with the same type as self
    """
    qs = self.index.to_series().transform(*args, **kwargs)
    return self.__class__(self.ps, qs, copy=True)

var()

Variance.

Returns: float

Source code in empiricaldist/empiricaldist.py
166
167
168
169
170
171
def var(self):
    """Variance.

    Returns: float
    """
    return self.make_pmf().var()

Hazard

Bases: Distribution

Represents a Hazard function.

Source code in empiricaldist/empiricaldist.py
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
class Hazard(Distribution):
    """Represents a Hazard function."""

    def copy(self, deep=True):
        """Make a copy.

        Args:
            deep: whether to make a deep copy

        Returns: new Pmf
        """
        return Hazard(self, copy=deep)

    # Hazard inherits __call__ from Distribution

    def normalize(self):
        """Normalize the hazard function (modifies self).

        Returns: normalizing constant
        """
        old_total = getattr(self, "total", 1.0)
        self.total = 1.0
        return old_total

    def make_surv(self, **kwargs):
        """Make a Surv from the Hazard.

        Args:
            kwargs: passed to the Surv constructor

        Returns: Surv
        """
        normalize = kwargs.pop("normalize", False)
        ps = (1 - self).cumprod()
        total = getattr(self, "total", 1.0)
        surv = Surv(ps * total, **kwargs)
        surv.total = total

        if normalize:
            surv.normalize()
        return surv

    def make_cdf(self, **kwargs):
        """Make a Cdf from the Hazard.

        Args:
            kwargs: passed to the Cdf constructor

        Returns: Cdf
        """
        return self.make_surv().make_cdf(**kwargs)

    def make_pmf(self, **kwargs):
        """Make a Pmf from the Hazard.

        Args:
            kwargs: passed to the Pmf constructor

        Returns: Pmf
        """
        return self.make_surv().make_cdf().make_pmf(**kwargs)

    def make_same(self, dist):
        """Convert the given dist to Hazard.

        Args:
            dist: Distribution

        Returns: Hazard
        """
        return dist.make_hazard()

    @staticmethod
    def from_seq(seq, **kwargs):
        """Make a Hazard from a sequence of values.

        Args:
            seq: iterable
            normalize: whether to normalize the Pmf, default True
            sort: whether to sort the Pmf by values, default True
            kwargs: passed to Pmf.from_seq

        Returns: Hazard object
        """
        pmf = Pmf.from_seq(seq, **kwargs)
        return pmf.make_hazard()

copy(deep=True)

Make a copy.

Parameters:
  • deep

    whether to make a deep copy

Returns: new Pmf

Source code in empiricaldist/empiricaldist.py
1277
1278
1279
1280
1281
1282
1283
1284
1285
def copy(self, deep=True):
    """Make a copy.

    Args:
        deep: whether to make a deep copy

    Returns: new Pmf
    """
    return Hazard(self, copy=deep)

from_seq(seq, **kwargs) staticmethod

Make a Hazard from a sequence of values.

Parameters:
  • seq

    iterable

  • normalize

    whether to normalize the Pmf, default True

  • sort

    whether to sort the Pmf by values, default True

  • kwargs

    passed to Pmf.from_seq

Returns: Hazard object

Source code in empiricaldist/empiricaldist.py
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
@staticmethod
def from_seq(seq, **kwargs):
    """Make a Hazard from a sequence of values.

    Args:
        seq: iterable
        normalize: whether to normalize the Pmf, default True
        sort: whether to sort the Pmf by values, default True
        kwargs: passed to Pmf.from_seq

    Returns: Hazard object
    """
    pmf = Pmf.from_seq(seq, **kwargs)
    return pmf.make_hazard()

make_cdf(**kwargs)

Make a Cdf from the Hazard.

Parameters:
  • kwargs

    passed to the Cdf constructor

Returns: Cdf

Source code in empiricaldist/empiricaldist.py
1316
1317
1318
1319
1320
1321
1322
1323
1324
def make_cdf(self, **kwargs):
    """Make a Cdf from the Hazard.

    Args:
        kwargs: passed to the Cdf constructor

    Returns: Cdf
    """
    return self.make_surv().make_cdf(**kwargs)

make_pmf(**kwargs)

Make a Pmf from the Hazard.

Parameters:
  • kwargs

    passed to the Pmf constructor

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
1326
1327
1328
1329
1330
1331
1332
1333
1334
def make_pmf(self, **kwargs):
    """Make a Pmf from the Hazard.

    Args:
        kwargs: passed to the Pmf constructor

    Returns: Pmf
    """
    return self.make_surv().make_cdf().make_pmf(**kwargs)

make_same(dist)

Convert the given dist to Hazard.

Parameters:
  • dist

    Distribution

Returns: Hazard

Source code in empiricaldist/empiricaldist.py
1336
1337
1338
1339
1340
1341
1342
1343
1344
def make_same(self, dist):
    """Convert the given dist to Hazard.

    Args:
        dist: Distribution

    Returns: Hazard
    """
    return dist.make_hazard()

make_surv(**kwargs)

Make a Surv from the Hazard.

Parameters:
  • kwargs

    passed to the Surv constructor

Returns: Surv

Source code in empiricaldist/empiricaldist.py
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
def make_surv(self, **kwargs):
    """Make a Surv from the Hazard.

    Args:
        kwargs: passed to the Surv constructor

    Returns: Surv
    """
    normalize = kwargs.pop("normalize", False)
    ps = (1 - self).cumprod()
    total = getattr(self, "total", 1.0)
    surv = Surv(ps * total, **kwargs)
    surv.total = total

    if normalize:
        surv.normalize()
    return surv

normalize()

Normalize the hazard function (modifies self).

Returns: normalizing constant

Source code in empiricaldist/empiricaldist.py
1289
1290
1291
1292
1293
1294
1295
1296
def normalize(self):
    """Normalize the hazard function (modifies self).

    Returns: normalizing constant
    """
    old_total = getattr(self, "total", 1.0)
    self.total = 1.0
    return old_total

Hist

Bases: Pmf

Represents a Pmf that maps from values to frequencies/counts.

Source code in empiricaldist/empiricaldist.py
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
class Hist(Pmf):
    """Represents a Pmf that maps from values to frequencies/counts."""

    @staticmethod
    def from_seq(seq, normalize=False, **options):
        """Make a distribution from a sequence of values.

        Args:
            seq: sequence of anything
            normalize: whether to normalize the probabilities
            options: passed along to Pmf

        Returns:  Counter object
        """
        pmf = Pmf.from_seq(seq, normalize=normalize, **options)
        return Hist(pmf, copy=False)

    def _repr_html_(self):
        """Returns an HTML representation of the series.

        Mostly used for Jupyter notebooks.
        """
        df = pd.DataFrame(dict(freqs=self))
        return df._repr_html_()

from_seq(seq, normalize=False, **options) staticmethod

Make a distribution from a sequence of values.

Parameters:
  • seq

    sequence of anything

  • normalize

    whether to normalize the probabilities

  • options

    passed along to Pmf

Returns: Counter object

Source code in empiricaldist/empiricaldist.py
899
900
901
902
903
904
905
906
907
908
909
910
911
@staticmethod
def from_seq(seq, normalize=False, **options):
    """Make a distribution from a sequence of values.

    Args:
        seq: sequence of anything
        normalize: whether to normalize the probabilities
        options: passed along to Pmf

    Returns:  Counter object
    """
    pmf = Pmf.from_seq(seq, normalize=normalize, **options)
    return Hist(pmf, copy=False)

Pmf

Bases: Distribution

Represents a probability Mass Function (PMF).

Source code in empiricaldist/empiricaldist.py
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
class Pmf(Distribution):
    """Represents a probability Mass Function (PMF)."""

    def copy(self, deep=True):
        """Make a copy.

        Returns: new Pmf
        """
        return Pmf(self, copy=deep)

    def make_pmf(self, **kwargs):
        """Make a Pmf from the Pmf.

        Returns: Pmf
        """
        if kwargs:
            return Pmf(self, **kwargs)
        return self

    # Pmf overrides the arithmetic operations in order
    # to provide fill_value=0 and return a Pmf.

    def add(self, x, **kwargs):
        """Override add to default fill_value to 0.

        Args:
            x: Distribution, sequence, array, or scalar
            kwargs: passed to Series.add

        Returns: Pmf
        """
        underride(kwargs, fill_value=0)
        s = pd.Series(self, copy=False).add(x, **kwargs)
        return Pmf(s)

    __add__ = add
    __radd__ = add

    def sub(self, x, **kwargs):
        """Override the - operator to default fill_value to 0.

        Args:
            x: Distribution, sequence, array, or scalar
            kwargs: passed to Series.sub

        Returns:  Pmf
        """
        underride(kwargs, fill_value=0)
        s = pd.Series.sub(self, x, **kwargs)
        # s = pd.Series(self, copy=False).sub(self, x, **kwargs)
        return Pmf(s)

    subtract = sub
    __sub__ = sub

    def __rsub__(self, x, **kwargs):
        """Handle reverse subtraction operation.

        Args:
            x: Distribution, sequence, array, or scalar
            kwargs: passed to Series.sub

        Returns: Pmf
        """
        # Reverse the subtraction: x - self
        return Pmf(x).sub(self, **kwargs)

    def mul(self, x, **kwargs):
        """Override the * operator to default fill_value to 0.

        Args:
            x: Distribution, sequence, array, or scalar
            kwargs: passed to Series.mul

        Returns:  Pmf
        """
        underride(kwargs, fill_value=0)
        s = pd.Series(self, copy=False).mul(x, **kwargs)
        return Pmf(s)

    multiply = mul
    __mul__ = mul
    __rmul__ = mul

    def div(self, x, **kwargs):
        """Override the / operator to default fill_value to 0.

        Args:
            x: Distribution, sequence, array, or scalar
            kwargs: passed to Series.div

        Returns:  Pmf
        """
        underride(kwargs, fill_value=0)
        s = pd.Series(self, copy=False).div(x, **kwargs)
        return Pmf(s)

    divide = div
    __truediv__ = div

    def __rtruediv__(self, x, **kwargs):
        """Handle reverse division operation.

        Args:
            x: Distribution, sequence, array, or scalar
            kwargs: passed to Series.div

        Returns:
            Pmf
        """
        # Reverse the division: x / self
        # TODO: Make this work with sequence, array, and scalar
        return Pmf(x).div(self, **kwargs)

    def normalize(self):
        """Make the probabilities add up to 1 (modifies self).

        Returns: float, normalizing constant
        """
        total = self.sum()
        self /= total
        return total

    def mean(self):
        """Computes expected value.

        Returns: float
        """
        if not np.allclose(1, self.sum()):
            raise ValueError("Pmf must be normalized before computing mean")

        if not pd.api.types.is_numeric_dtype(self.dtype):
            raise ValueError("mean is only defined for numeric data")

        return np.sum(self.ps * self.qs)

    def var(self):
        """Variance of a PMF.

        Returns: float
        """
        m = self.mean()
        d = self.qs - m
        return np.sum(d**2 * self.ps)

    def std(self):
        """Standard deviation of a PMF.

        Returns: float
        """
        return np.sqrt(self.var())

    def mode(self, **kwargs):
        """Most common value.

        If multiple quantities have the maximum probability,
        the first maximal quantity is returned.

        Args:
            kwargs: passed to Series.mode

        Returns: type of the quantities
        """
        underride(kwargs, skipna=True)
        return self.idxmax(**kwargs)

    max_prob = mode

    def choice(self, size=1, **kwargs):
        """Makes a random selection.

        Uses the probabilities as weights unless `p` is provided.

        Args:
            size: number of values or tuple of dimensions
            kwargs: passed to np.random.choice

        Returns: NumPy array
        """
        underride(kwargs, p=self.ps)
        return np.random.choice(self.qs, size, **kwargs)

    def add_dist(self, x):
        """Computes the Pmf of the sum of values drawn from self and x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: new Pmf
        """
        if isinstance(x, Distribution):
            return self.convolve_dist(x, np.add.outer)
        else:
            return Pmf(self.ps.copy(), index=self.qs + x)

    def sub_dist(self, x):
        """Computes the Pmf of the diff of values drawn from self and other.

        Args:
            x: Distribution, scalar, or sequence

        Returns: new Pmf
        """
        if isinstance(x, Distribution):
            return self.convolve_dist(x, np.subtract.outer)
        else:
            return Pmf(self.ps.copy(), index=self.qs - x)

    def mul_dist(self, x):
        """Computes the Pmf of the product of values drawn from self and x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: new Pmf
        """
        if isinstance(x, Distribution):
            return self.convolve_dist(x, np.multiply.outer)
        else:
            return Pmf(self.ps.copy(), index=self.qs * x)

    def div_dist(self, x):
        """Computes the Pmf of the ratio of values drawn from self and x.

        Args:
            x: Distribution, scalar, or sequence

        Returns: new Pmf
        """
        if isinstance(x, Distribution):
            return self.convolve_dist(x, np.divide.outer)
        else:
            return Pmf(self.ps.copy(), index=self.qs / x)

    def convolve_dist(self, dist, ufunc):
        """Convolve two distributions.

        Args:
            dist: Distribution
            ufunc: elementwise function for arrays

        Returns: new Pmf
        """
        dist = dist.make_pmf()
        qs = ufunc(self.qs, dist.qs).flatten()
        ps = np.multiply.outer(self.ps, dist.ps).flatten()
        series = pd.Series(ps).groupby(qs).sum()

        return Pmf(series)

    def gt_dist(self, x):
        """Probability that a value from self exceeds a value from x.

        Args:
            x: Distribution object or scalar

        Returns: float probability
        """
        if isinstance(x, Distribution):
            return self.pmf_outer(x, np.greater).sum()
        else:
            return self[self.qs > x].sum()

    def lt_dist(self, x):
        """Probability that a value from self is less than a value from x.

        Args:
            x: Distribution object or scalar

        Returns: float probability
        """
        if isinstance(x, Distribution):
            return self.pmf_outer(x, np.less).sum()
        else:
            return self[self.qs < x].sum()

    def ge_dist(self, x):
        """Probability that a value from self is >= than a value from x.

        Args:
            x: Distribution object or scalar

        Returns: float probability
        """
        if isinstance(x, Distribution):
            return self.pmf_outer(x, np.greater_equal).sum()
        else:
            return self[self.qs >= x].sum()

    def le_dist(self, x):
        """Probability that a value from self is <= than a value from x.

        Args:
            x: Distribution object or scalar

        Returns: float probability
        """
        if isinstance(x, Distribution):
            return self.pmf_outer(x, np.less_equal).sum()
        else:
            return self[self.qs <= x].sum()

    def eq_dist(self, x):
        """Probability that a value from self equals a value from x.

        Args:
            x: Distribution object or scalar

        Returns: float probability
        """
        if isinstance(x, Distribution):
            return self.pmf_outer(x, np.equal).sum()
        else:
            return self[self.qs == x].sum()

    def ne_dist(self, x):
        """Probability that a value from self is <= than a value from x.

        Args:
            x: Distribution object or scalar

        Returns: float probability
        """
        if isinstance(x, Distribution):
            return self.pmf_outer(x, np.not_equal).sum()
        else:
            return self[self.qs != x].sum()

    def pmf_outer(self, dist, ufunc):
        """Computes the outer product of two PMFs.

        Args:
            dist: Distribution object
            ufunc: function to apply to the quantities

        Returns: NumPy array
        """
        dist = dist.make_pmf()
        qs = ufunc.outer(self.qs, dist.qs)
        ps = np.multiply.outer(self.ps, dist.ps)
        return qs * ps

    def make_joint(self, other, **options):
        """Make joint distribution (assuming independence).

        Args:
            other: Pmf
            options: passed to Pmf constructor

        Returns: new Pmf
        """
        qs = pd.MultiIndex.from_product([self.qs, other.qs])
        ps = np.multiply.outer(self.ps, other.ps).flatten()
        return Pmf(ps, index=qs, **options)

    def marginal(self, i, name=None):
        """Gets the marginal distribution of the indicated variable.

        Args:
            i: index of the variable we want
            name: string

        Returns: Pmf
        """
        # The following is deprecated now
        # return Pmf(self.sum(level=i))

        # here's the new version
        return Pmf(self.groupby(level=i).sum(), name=name)

    def conditional(self, i, val, name=None):
        """Gets the conditional distribution of the indicated variable.

        Args:
            i: index of the variable we're conditioning on
            val: the value the ith variable has to have
            name: string

        Returns: Pmf
        """
        pmf = Pmf(self.xs(key=val, level=i), copy=True, name=name)
        pmf.normalize()
        return pmf

    def update(self, likelihood, data):
        """Bayesian update.

        Args:
            likelihood: function that takes (data, hypo) and returns
                        likelihood of data under hypo, P(data|hypo)
            data: in whatever format likelihood understands

        Returns: normalizing constant
        """
        for hypo in self.qs:
            self[hypo] *= likelihood(data, hypo)

        return self.normalize()

    def make_cdf(self, **kwargs):
        """Make a Cdf from the Pmf.

        Args:
            kwargs: passed to the pd.Series constructor

        Returns: Cdf
        """
        normalize = kwargs.pop("normalize", False)

        pmf = self.sort_index()
        cumulative = np.cumsum(pmf)
        cdf = Cdf(cumulative, pmf.index.copy(), **kwargs)

        if normalize:
            cdf.normalize()

        return cdf

    def make_surv(self, **kwargs):
        """Make a Surv from the Pmf.

        Args:
            kwargs: passed to the pd.Series constructor

        Returns: Surv
        """
        cdf = self.make_cdf()
        return cdf.make_surv(**kwargs)

    def make_hazard(self, normalize=False, **kwargs):
        """Make a Hazard from the Pmf.

        Args:
            kwargs: passed to the pd.Series constructor

        Returns: Hazard
        """
        surv = self.make_surv()
        haz = Hazard(self / (self + surv), **kwargs)
        haz.total = getattr(surv, "total", 1.0)
        if normalize:
            self.normalize()
        return haz

    def make_same(self, dist):
        """Convert the given dist to Pmf.

        Args:
            dist: Distribution

        Returns: Pmf
        """
        return dist.make_pmf()

    @staticmethod
    def from_seq(
        seq,
        normalize=True,
        sort=True,
        ascending=True,
        dropna=True,
        na_position="last",
        **options,
    ):
        """Make a PMF from a sequence of values.

        Args:
            seq: iterable
            normalize: whether to normalize the Pmf, default True
            sort: whether to sort the Pmf by values, default True
            ascending: whether to sort in ascending order, default True
            dropna: whether to drop NaN values, default True
            na_position: If 'first' puts NaNs at the beginning,
                        'last' puts NaNs at the end.
        options: passed to the pd.Series constructor

        Returns: Pmf object
        """
        # compute the value counts
        series = pd.Series(seq).value_counts(
            normalize=normalize, sort=False, dropna=dropna
        )
        # make the result a Pmf
        # (since we just made a fresh Series, there is no reason to copy it)
        options["copy"] = False
        underride(options, name="")
        pmf = Pmf(series, **options)

        # sort in place, if desired
        if sort:
            pmf.sort_index(
                inplace=True, ascending=ascending, na_position=na_position
            )

        return pmf

__rsub__(x, **kwargs)

Handle reverse subtraction operation.

Parameters:
  • x

    Distribution, sequence, array, or scalar

  • kwargs

    passed to Series.sub

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
454
455
456
457
458
459
460
461
462
463
464
def __rsub__(self, x, **kwargs):
    """Handle reverse subtraction operation.

    Args:
        x: Distribution, sequence, array, or scalar
        kwargs: passed to Series.sub

    Returns: Pmf
    """
    # Reverse the subtraction: x - self
    return Pmf(x).sub(self, **kwargs)

__rtruediv__(x, **kwargs)

Handle reverse division operation.

Parameters:
  • x

    Distribution, sequence, array, or scalar

  • kwargs

    passed to Series.div

Returns:
  • Pmf

Source code in empiricaldist/empiricaldist.py
499
500
501
502
503
504
505
506
507
508
509
510
511
def __rtruediv__(self, x, **kwargs):
    """Handle reverse division operation.

    Args:
        x: Distribution, sequence, array, or scalar
        kwargs: passed to Series.div

    Returns:
        Pmf
    """
    # Reverse the division: x / self
    # TODO: Make this work with sequence, array, and scalar
    return Pmf(x).div(self, **kwargs)

add(x, **kwargs)

Override add to default fill_value to 0.

Parameters:
  • x

    Distribution, sequence, array, or scalar

  • kwargs

    passed to Series.add

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
421
422
423
424
425
426
427
428
429
430
431
432
def add(self, x, **kwargs):
    """Override add to default fill_value to 0.

    Args:
        x: Distribution, sequence, array, or scalar
        kwargs: passed to Series.add

    Returns: Pmf
    """
    underride(kwargs, fill_value=0)
    s = pd.Series(self, copy=False).add(x, **kwargs)
    return Pmf(s)

add_dist(x)

Computes the Pmf of the sum of values drawn from self and x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: new Pmf

Source code in empiricaldist/empiricaldist.py
581
582
583
584
585
586
587
588
589
590
591
592
def add_dist(self, x):
    """Computes the Pmf of the sum of values drawn from self and x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: new Pmf
    """
    if isinstance(x, Distribution):
        return self.convolve_dist(x, np.add.outer)
    else:
        return Pmf(self.ps.copy(), index=self.qs + x)

choice(size=1, **kwargs)

Makes a random selection.

Uses the probabilities as weights unless p is provided.

Parameters:
  • size

    number of values or tuple of dimensions

  • kwargs

    passed to np.random.choice

Returns: NumPy array

Source code in empiricaldist/empiricaldist.py
567
568
569
570
571
572
573
574
575
576
577
578
579
def choice(self, size=1, **kwargs):
    """Makes a random selection.

    Uses the probabilities as weights unless `p` is provided.

    Args:
        size: number of values or tuple of dimensions
        kwargs: passed to np.random.choice

    Returns: NumPy array
    """
    underride(kwargs, p=self.ps)
    return np.random.choice(self.qs, size, **kwargs)

conditional(i, val, name=None)

Gets the conditional distribution of the indicated variable.

Parameters:
  • i

    index of the variable we're conditioning on

  • val

    the value the ith variable has to have

  • name

    string

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
769
770
771
772
773
774
775
776
777
778
779
780
781
def conditional(self, i, val, name=None):
    """Gets the conditional distribution of the indicated variable.

    Args:
        i: index of the variable we're conditioning on
        val: the value the ith variable has to have
        name: string

    Returns: Pmf
    """
    pmf = Pmf(self.xs(key=val, level=i), copy=True, name=name)
    pmf.normalize()
    return pmf

convolve_dist(dist, ufunc)

Convolve two distributions.

Parameters:
  • dist

    Distribution

  • ufunc

    elementwise function for arrays

Returns: new Pmf

Source code in empiricaldist/empiricaldist.py
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
def convolve_dist(self, dist, ufunc):
    """Convolve two distributions.

    Args:
        dist: Distribution
        ufunc: elementwise function for arrays

    Returns: new Pmf
    """
    dist = dist.make_pmf()
    qs = ufunc(self.qs, dist.qs).flatten()
    ps = np.multiply.outer(self.ps, dist.ps).flatten()
    series = pd.Series(ps).groupby(qs).sum()

    return Pmf(series)

copy(deep=True)

Make a copy.

Returns: new Pmf

Source code in empiricaldist/empiricaldist.py
402
403
404
405
406
407
def copy(self, deep=True):
    """Make a copy.

    Returns: new Pmf
    """
    return Pmf(self, copy=deep)

div(x, **kwargs)

Override the / operator to default fill_value to 0.

Parameters:
  • x

    Distribution, sequence, array, or scalar

  • kwargs

    passed to Series.div

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
483
484
485
486
487
488
489
490
491
492
493
494
def div(self, x, **kwargs):
    """Override the / operator to default fill_value to 0.

    Args:
        x: Distribution, sequence, array, or scalar
        kwargs: passed to Series.div

    Returns:  Pmf
    """
    underride(kwargs, fill_value=0)
    s = pd.Series(self, copy=False).div(x, **kwargs)
    return Pmf(s)

div_dist(x)

Computes the Pmf of the ratio of values drawn from self and x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: new Pmf

Source code in empiricaldist/empiricaldist.py
620
621
622
623
624
625
626
627
628
629
630
631
def div_dist(self, x):
    """Computes the Pmf of the ratio of values drawn from self and x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: new Pmf
    """
    if isinstance(x, Distribution):
        return self.convolve_dist(x, np.divide.outer)
    else:
        return Pmf(self.ps.copy(), index=self.qs / x)

eq_dist(x)

Probability that a value from self equals a value from x.

Parameters:
  • x

    Distribution object or scalar

Returns: float probability

Source code in empiricaldist/empiricaldist.py
701
702
703
704
705
706
707
708
709
710
711
712
def eq_dist(self, x):
    """Probability that a value from self equals a value from x.

    Args:
        x: Distribution object or scalar

    Returns: float probability
    """
    if isinstance(x, Distribution):
        return self.pmf_outer(x, np.equal).sum()
    else:
        return self[self.qs == x].sum()

from_seq(seq, normalize=True, sort=True, ascending=True, dropna=True, na_position='last', **options) staticmethod

Make a PMF from a sequence of values.

Parameters:
  • seq

    iterable

  • normalize

    whether to normalize the Pmf, default True

  • sort

    whether to sort the Pmf by values, default True

  • ascending

    whether to sort in ascending order, default True

  • dropna

    whether to drop NaN values, default True

  • na_position

    If 'first' puts NaNs at the beginning, 'last' puts NaNs at the end.

options: passed to the pd.Series constructor

Returns: Pmf object

Source code in empiricaldist/empiricaldist.py
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
@staticmethod
def from_seq(
    seq,
    normalize=True,
    sort=True,
    ascending=True,
    dropna=True,
    na_position="last",
    **options,
):
    """Make a PMF from a sequence of values.

    Args:
        seq: iterable
        normalize: whether to normalize the Pmf, default True
        sort: whether to sort the Pmf by values, default True
        ascending: whether to sort in ascending order, default True
        dropna: whether to drop NaN values, default True
        na_position: If 'first' puts NaNs at the beginning,
                    'last' puts NaNs at the end.
    options: passed to the pd.Series constructor

    Returns: Pmf object
    """
    # compute the value counts
    series = pd.Series(seq).value_counts(
        normalize=normalize, sort=False, dropna=dropna
    )
    # make the result a Pmf
    # (since we just made a fresh Series, there is no reason to copy it)
    options["copy"] = False
    underride(options, name="")
    pmf = Pmf(series, **options)

    # sort in place, if desired
    if sort:
        pmf.sort_index(
            inplace=True, ascending=ascending, na_position=na_position
        )

    return pmf

ge_dist(x)

Probability that a value from self is >= than a value from x.

Parameters:
  • x

    Distribution object or scalar

Returns: float probability

Source code in empiricaldist/empiricaldist.py
675
676
677
678
679
680
681
682
683
684
685
686
def ge_dist(self, x):
    """Probability that a value from self is >= than a value from x.

    Args:
        x: Distribution object or scalar

    Returns: float probability
    """
    if isinstance(x, Distribution):
        return self.pmf_outer(x, np.greater_equal).sum()
    else:
        return self[self.qs >= x].sum()

gt_dist(x)

Probability that a value from self exceeds a value from x.

Parameters:
  • x

    Distribution object or scalar

Returns: float probability

Source code in empiricaldist/empiricaldist.py
649
650
651
652
653
654
655
656
657
658
659
660
def gt_dist(self, x):
    """Probability that a value from self exceeds a value from x.

    Args:
        x: Distribution object or scalar

    Returns: float probability
    """
    if isinstance(x, Distribution):
        return self.pmf_outer(x, np.greater).sum()
    else:
        return self[self.qs > x].sum()

le_dist(x)

Probability that a value from self is <= than a value from x.

Parameters:
  • x

    Distribution object or scalar

Returns: float probability

Source code in empiricaldist/empiricaldist.py
688
689
690
691
692
693
694
695
696
697
698
699
def le_dist(self, x):
    """Probability that a value from self is <= than a value from x.

    Args:
        x: Distribution object or scalar

    Returns: float probability
    """
    if isinstance(x, Distribution):
        return self.pmf_outer(x, np.less_equal).sum()
    else:
        return self[self.qs <= x].sum()

lt_dist(x)

Probability that a value from self is less than a value from x.

Parameters:
  • x

    Distribution object or scalar

Returns: float probability

Source code in empiricaldist/empiricaldist.py
662
663
664
665
666
667
668
669
670
671
672
673
def lt_dist(self, x):
    """Probability that a value from self is less than a value from x.

    Args:
        x: Distribution object or scalar

    Returns: float probability
    """
    if isinstance(x, Distribution):
        return self.pmf_outer(x, np.less).sum()
    else:
        return self[self.qs < x].sum()

make_cdf(**kwargs)

Make a Cdf from the Pmf.

Parameters:
  • kwargs

    passed to the pd.Series constructor

Returns: Cdf

Source code in empiricaldist/empiricaldist.py
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
def make_cdf(self, **kwargs):
    """Make a Cdf from the Pmf.

    Args:
        kwargs: passed to the pd.Series constructor

    Returns: Cdf
    """
    normalize = kwargs.pop("normalize", False)

    pmf = self.sort_index()
    cumulative = np.cumsum(pmf)
    cdf = Cdf(cumulative, pmf.index.copy(), **kwargs)

    if normalize:
        cdf.normalize()

    return cdf

make_hazard(normalize=False, **kwargs)

Make a Hazard from the Pmf.

Parameters:
  • kwargs

    passed to the pd.Series constructor

Returns: Hazard

Source code in empiricaldist/empiricaldist.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
def make_hazard(self, normalize=False, **kwargs):
    """Make a Hazard from the Pmf.

    Args:
        kwargs: passed to the pd.Series constructor

    Returns: Hazard
    """
    surv = self.make_surv()
    haz = Hazard(self / (self + surv), **kwargs)
    haz.total = getattr(surv, "total", 1.0)
    if normalize:
        self.normalize()
    return haz

make_joint(other, **options)

Make joint distribution (assuming independence).

Parameters:
  • other

    Pmf

  • options

    passed to Pmf constructor

Returns: new Pmf

Source code in empiricaldist/empiricaldist.py
741
742
743
744
745
746
747
748
749
750
751
752
def make_joint(self, other, **options):
    """Make joint distribution (assuming independence).

    Args:
        other: Pmf
        options: passed to Pmf constructor

    Returns: new Pmf
    """
    qs = pd.MultiIndex.from_product([self.qs, other.qs])
    ps = np.multiply.outer(self.ps, other.ps).flatten()
    return Pmf(ps, index=qs, **options)

make_pmf(**kwargs)

Make a Pmf from the Pmf.

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
409
410
411
412
413
414
415
416
def make_pmf(self, **kwargs):
    """Make a Pmf from the Pmf.

    Returns: Pmf
    """
    if kwargs:
        return Pmf(self, **kwargs)
    return self

make_same(dist)

Convert the given dist to Pmf.

Parameters:
  • dist

    Distribution

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
843
844
845
846
847
848
849
850
851
def make_same(self, dist):
    """Convert the given dist to Pmf.

    Args:
        dist: Distribution

    Returns: Pmf
    """
    return dist.make_pmf()

make_surv(**kwargs)

Make a Surv from the Pmf.

Parameters:
  • kwargs

    passed to the pd.Series constructor

Returns: Surv

Source code in empiricaldist/empiricaldist.py
817
818
819
820
821
822
823
824
825
826
def make_surv(self, **kwargs):
    """Make a Surv from the Pmf.

    Args:
        kwargs: passed to the pd.Series constructor

    Returns: Surv
    """
    cdf = self.make_cdf()
    return cdf.make_surv(**kwargs)

marginal(i, name=None)

Gets the marginal distribution of the indicated variable.

Parameters:
  • i

    index of the variable we want

  • name

    string

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
754
755
756
757
758
759
760
761
762
763
764
765
766
767
def marginal(self, i, name=None):
    """Gets the marginal distribution of the indicated variable.

    Args:
        i: index of the variable we want
        name: string

    Returns: Pmf
    """
    # The following is deprecated now
    # return Pmf(self.sum(level=i))

    # here's the new version
    return Pmf(self.groupby(level=i).sum(), name=name)

mean()

Computes expected value.

Returns: float

Source code in empiricaldist/empiricaldist.py
522
523
524
525
526
527
528
529
530
531
532
533
def mean(self):
    """Computes expected value.

    Returns: float
    """
    if not np.allclose(1, self.sum()):
        raise ValueError("Pmf must be normalized before computing mean")

    if not pd.api.types.is_numeric_dtype(self.dtype):
        raise ValueError("mean is only defined for numeric data")

    return np.sum(self.ps * self.qs)

mode(**kwargs)

Most common value.

If multiple quantities have the maximum probability, the first maximal quantity is returned.

Parameters:
  • kwargs

    passed to Series.mode

Returns: type of the quantities

Source code in empiricaldist/empiricaldist.py
551
552
553
554
555
556
557
558
559
560
561
562
563
def mode(self, **kwargs):
    """Most common value.

    If multiple quantities have the maximum probability,
    the first maximal quantity is returned.

    Args:
        kwargs: passed to Series.mode

    Returns: type of the quantities
    """
    underride(kwargs, skipna=True)
    return self.idxmax(**kwargs)

mul(x, **kwargs)

Override the * operator to default fill_value to 0.

Parameters:
  • x

    Distribution, sequence, array, or scalar

  • kwargs

    passed to Series.mul

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
466
467
468
469
470
471
472
473
474
475
476
477
def mul(self, x, **kwargs):
    """Override the * operator to default fill_value to 0.

    Args:
        x: Distribution, sequence, array, or scalar
        kwargs: passed to Series.mul

    Returns:  Pmf
    """
    underride(kwargs, fill_value=0)
    s = pd.Series(self, copy=False).mul(x, **kwargs)
    return Pmf(s)

mul_dist(x)

Computes the Pmf of the product of values drawn from self and x.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: new Pmf

Source code in empiricaldist/empiricaldist.py
607
608
609
610
611
612
613
614
615
616
617
618
def mul_dist(self, x):
    """Computes the Pmf of the product of values drawn from self and x.

    Args:
        x: Distribution, scalar, or sequence

    Returns: new Pmf
    """
    if isinstance(x, Distribution):
        return self.convolve_dist(x, np.multiply.outer)
    else:
        return Pmf(self.ps.copy(), index=self.qs * x)

ne_dist(x)

Probability that a value from self is <= than a value from x.

Parameters:
  • x

    Distribution object or scalar

Returns: float probability

Source code in empiricaldist/empiricaldist.py
714
715
716
717
718
719
720
721
722
723
724
725
def ne_dist(self, x):
    """Probability that a value from self is <= than a value from x.

    Args:
        x: Distribution object or scalar

    Returns: float probability
    """
    if isinstance(x, Distribution):
        return self.pmf_outer(x, np.not_equal).sum()
    else:
        return self[self.qs != x].sum()

normalize()

Make the probabilities add up to 1 (modifies self).

Returns: float, normalizing constant

Source code in empiricaldist/empiricaldist.py
513
514
515
516
517
518
519
520
def normalize(self):
    """Make the probabilities add up to 1 (modifies self).

    Returns: float, normalizing constant
    """
    total = self.sum()
    self /= total
    return total

pmf_outer(dist, ufunc)

Computes the outer product of two PMFs.

Parameters:
  • dist

    Distribution object

  • ufunc

    function to apply to the quantities

Returns: NumPy array

Source code in empiricaldist/empiricaldist.py
727
728
729
730
731
732
733
734
735
736
737
738
739
def pmf_outer(self, dist, ufunc):
    """Computes the outer product of two PMFs.

    Args:
        dist: Distribution object
        ufunc: function to apply to the quantities

    Returns: NumPy array
    """
    dist = dist.make_pmf()
    qs = ufunc.outer(self.qs, dist.qs)
    ps = np.multiply.outer(self.ps, dist.ps)
    return qs * ps

std()

Standard deviation of a PMF.

Returns: float

Source code in empiricaldist/empiricaldist.py
544
545
546
547
548
549
def std(self):
    """Standard deviation of a PMF.

    Returns: float
    """
    return np.sqrt(self.var())

sub(x, **kwargs)

Override the - operator to default fill_value to 0.

Parameters:
  • x

    Distribution, sequence, array, or scalar

  • kwargs

    passed to Series.sub

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
437
438
439
440
441
442
443
444
445
446
447
448
449
def sub(self, x, **kwargs):
    """Override the - operator to default fill_value to 0.

    Args:
        x: Distribution, sequence, array, or scalar
        kwargs: passed to Series.sub

    Returns:  Pmf
    """
    underride(kwargs, fill_value=0)
    s = pd.Series.sub(self, x, **kwargs)
    # s = pd.Series(self, copy=False).sub(self, x, **kwargs)
    return Pmf(s)

sub_dist(x)

Computes the Pmf of the diff of values drawn from self and other.

Parameters:
  • x

    Distribution, scalar, or sequence

Returns: new Pmf

Source code in empiricaldist/empiricaldist.py
594
595
596
597
598
599
600
601
602
603
604
605
def sub_dist(self, x):
    """Computes the Pmf of the diff of values drawn from self and other.

    Args:
        x: Distribution, scalar, or sequence

    Returns: new Pmf
    """
    if isinstance(x, Distribution):
        return self.convolve_dist(x, np.subtract.outer)
    else:
        return Pmf(self.ps.copy(), index=self.qs - x)

update(likelihood, data)

Bayesian update.

Parameters:
  • likelihood

    function that takes (data, hypo) and returns likelihood of data under hypo, P(data|hypo)

  • data

    in whatever format likelihood understands

Returns: normalizing constant

Source code in empiricaldist/empiricaldist.py
783
784
785
786
787
788
789
790
791
792
793
794
795
796
def update(self, likelihood, data):
    """Bayesian update.

    Args:
        likelihood: function that takes (data, hypo) and returns
                    likelihood of data under hypo, P(data|hypo)
        data: in whatever format likelihood understands

    Returns: normalizing constant
    """
    for hypo in self.qs:
        self[hypo] *= likelihood(data, hypo)

    return self.normalize()

var()

Variance of a PMF.

Returns: float

Source code in empiricaldist/empiricaldist.py
535
536
537
538
539
540
541
542
def var(self):
    """Variance of a PMF.

    Returns: float
    """
    m = self.mean()
    d = self.qs - m
    return np.sum(d**2 * self.ps)

Surv

Bases: Distribution

Represents a survival function (complementary CDF).

Source code in empiricaldist/empiricaldist.py
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
class Surv(Distribution):
    """Represents a survival function (complementary CDF)."""

    def copy(self, deep=True):
        """Make a copy.

        Args:
            deep: whether to make a deep copy

        Returns: new Surv
        """
        return Surv(self, copy=deep)

    @staticmethod
    def from_seq(seq, normalize=True, sort=True, **options):
        """Make a Surv from a sequence of values.

        Args:
            seq: iterable
            normalize: whether to normalize the Surv, default True
            sort: whether to sort the Surv by values, default True
            options: passed to the pd.Series constructor

        Returns: Surv object
        """
        cdf = Cdf.from_seq(seq, normalize=normalize, sort=sort, **options)
        return cdf.make_surv()

    def step(self, **options):
        """Plot the Surv as a step function.

        Args:
            options: passed to pd.Series.plot
        """
        underride(options, drawstyle="steps-post")
        self.plot(**options)

    def normalize(self):
        """Normalize the survival function (modifies self).

        Returns: normalizing constant
        """
        old_total = getattr(self, "total", 1.0)
        self.ps /= old_total
        self.total = 1.0
        return old_total

    @property
    def forward(self, **kwargs):
        """Make a function that computes the forward survival function.

        Args:
            kwargs: keyword arguments passed to interp1d

        Returns: array of probabilities
        """
        total = getattr(self, "total", 1.0)
        underride(
            kwargs,
            kind="previous",
            copy=False,
            assume_sorted=True,
            bounds_error=False,
            fill_value=(total, 0),
        )
        interp = interp1d(self.qs, self.ps, **kwargs)
        return interp

    @property
    def inverse(self, **kwargs):
        """Make a function that computes the inverse survival function.

        Args:
            kwargs: keyword arguments passed to interp1d

        Returns: interpolation function from ps to qs
        """
        total = getattr(self, "total", 1.0)
        underride(
            kwargs,
            kind="previous",
            copy=False,
            assume_sorted=True,
            bounds_error=False,
            fill_value=(np.nan, np.nan),
        )
        # sort in descending order
        # I don't remember why
        rev = self.sort_values()

        # If the reversed Surv doesn't get all the way to total
        # add a fake entry at -inf
        if rev.iloc[-1] != total:
            rev[-np.inf] = total

        interp = interp1d(rev, rev.index, **kwargs)
        return interp

    # calling a Surv like a function does forward lookup
    __call__ = forward

    def make_cdf(self, **kwargs):
        """Make a Cdf from the Surv.

        Args:
            kwargs: passed to the Cdf constructor

        Returns: Cdf
        """
        normalize = kwargs.pop("normalize", False)
        total = getattr(self, "total", 1.0)
        cdf = Cdf(total - self, **kwargs)
        if normalize:
            cdf.normalize()
        return cdf

    def make_pmf(self, **kwargs):
        """Make a Pmf from the Surv.

        Args:
            kwargs: passed to the Pmf constructor

        Returns: Pmf
        """
        cdf = self.make_cdf()
        pmf = cdf.make_pmf(**kwargs)
        return pmf

    def make_hazard(self, **kwargs):
        """Make a Hazard from the Surv.

        Args:
            kwargs: passed to the Hazard constructor

        Returns: Hazard
        """
        pmf = self.make_pmf()
        at_risk = self + pmf
        haz = Hazard(pmf / at_risk, **kwargs)
        haz.total = getattr(self, "total", 1.0)
        haz.name = self.name
        return haz

    def make_same(self, dist):
        """Convert the given dist to Surv.

        Args:
            dist: Distribution

        Returns: Surv
        """
        return dist.make_surv()

forward property

Make a function that computes the forward survival function.

Parameters:
  • kwargs

    keyword arguments passed to interp1d

Returns: array of probabilities

inverse property

Make a function that computes the inverse survival function.

Parameters:
  • kwargs

    keyword arguments passed to interp1d

Returns: interpolation function from ps to qs

copy(deep=True)

Make a copy.

Parameters:
  • deep

    whether to make a deep copy

Returns: new Surv

Source code in empiricaldist/empiricaldist.py
1123
1124
1125
1126
1127
1128
1129
1130
1131
def copy(self, deep=True):
    """Make a copy.

    Args:
        deep: whether to make a deep copy

    Returns: new Surv
    """
    return Surv(self, copy=deep)

from_seq(seq, normalize=True, sort=True, **options) staticmethod

Make a Surv from a sequence of values.

Parameters:
  • seq

    iterable

  • normalize

    whether to normalize the Surv, default True

  • sort

    whether to sort the Surv by values, default True

  • options

    passed to the pd.Series constructor

Returns: Surv object

Source code in empiricaldist/empiricaldist.py
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
@staticmethod
def from_seq(seq, normalize=True, sort=True, **options):
    """Make a Surv from a sequence of values.

    Args:
        seq: iterable
        normalize: whether to normalize the Surv, default True
        sort: whether to sort the Surv by values, default True
        options: passed to the pd.Series constructor

    Returns: Surv object
    """
    cdf = Cdf.from_seq(seq, normalize=normalize, sort=sort, **options)
    return cdf.make_surv()

make_cdf(**kwargs)

Make a Cdf from the Surv.

Parameters:
  • kwargs

    passed to the Cdf constructor

Returns: Cdf

Source code in empiricaldist/empiricaldist.py
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
def make_cdf(self, **kwargs):
    """Make a Cdf from the Surv.

    Args:
        kwargs: passed to the Cdf constructor

    Returns: Cdf
    """
    normalize = kwargs.pop("normalize", False)
    total = getattr(self, "total", 1.0)
    cdf = Cdf(total - self, **kwargs)
    if normalize:
        cdf.normalize()
    return cdf

make_hazard(**kwargs)

Make a Hazard from the Surv.

Parameters:
  • kwargs

    passed to the Hazard constructor

Returns: Hazard

Source code in empiricaldist/empiricaldist.py
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
def make_hazard(self, **kwargs):
    """Make a Hazard from the Surv.

    Args:
        kwargs: passed to the Hazard constructor

    Returns: Hazard
    """
    pmf = self.make_pmf()
    at_risk = self + pmf
    haz = Hazard(pmf / at_risk, **kwargs)
    haz.total = getattr(self, "total", 1.0)
    haz.name = self.name
    return haz

make_pmf(**kwargs)

Make a Pmf from the Surv.

Parameters:
  • kwargs

    passed to the Pmf constructor

Returns: Pmf

Source code in empiricaldist/empiricaldist.py
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
def make_pmf(self, **kwargs):
    """Make a Pmf from the Surv.

    Args:
        kwargs: passed to the Pmf constructor

    Returns: Pmf
    """
    cdf = self.make_cdf()
    pmf = cdf.make_pmf(**kwargs)
    return pmf

make_same(dist)

Convert the given dist to Surv.

Parameters:
  • dist

    Distribution

Returns: Surv

Source code in empiricaldist/empiricaldist.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
def make_same(self, dist):
    """Convert the given dist to Surv.

    Args:
        dist: Distribution

    Returns: Surv
    """
    return dist.make_surv()

normalize()

Normalize the survival function (modifies self).

Returns: normalizing constant

Source code in empiricaldist/empiricaldist.py
1157
1158
1159
1160
1161
1162
1163
1164
1165
def normalize(self):
    """Normalize the survival function (modifies self).

    Returns: normalizing constant
    """
    old_total = getattr(self, "total", 1.0)
    self.ps /= old_total
    self.total = 1.0
    return old_total

step(**options)

Plot the Surv as a step function.

Parameters:
  • options

    passed to pd.Series.plot

Source code in empiricaldist/empiricaldist.py
1148
1149
1150
1151
1152
1153
1154
1155
def step(self, **options):
    """Plot the Surv as a step function.

    Args:
        options: passed to pd.Series.plot
    """
    underride(options, drawstyle="steps-post")
    self.plot(**options)

underride(d, **options)

Add key-value pairs to d only if key is not in d.

Parameters:
  • d (dict) –

    The dictionary to update with new key-value pairs.

  • **options

    Additional keyword arguments to add to d if absent.

Returns:
  • The modified dictionary d.

Source code in empiricaldist/empiricaldist.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def underride(d, **options):
    """Add key-value pairs to d only if key is not in d.

    Args:
        d (dict): The dictionary to update with new key-value pairs.
        **options: Additional keyword arguments to add to `d` if absent.

    Returns:
        The modified dictionary `d`.
    """
    for key, val in options.items():
        d.setdefault(key, val)

    return d