| . | |
| other: a number | |
| returns: new Pmf | |
| """ | |
| pmf = Pmf() | |
| for v1, p1 in self.Items(): | |
| pmf.Set(v1 + other, p1) | |
| return pmf | |
| def __sub__(self, other): | |
| """Computes the Pmf of the diff of values drawn from self and other. | |
| other: another Pmf | |
| returns: new Pmf | |
| """ | |
| try: | |
| return self.SubPmf(other) | |
| except AttributeError: | |
| return self.AddConstant(-other) | |
| def SubPmf(self, other): | |
| """Computes the Pmf of the diff of values drawn from self and other. | |
| other: another Pmf | |
| returns: new Pmf | |
| """ | |
| pmf = Pmf() | |
| for v1, p1 in self.Items(): | |
| for v2, p2 in other.Items(): | |
| pmf.Incr(v1 - v2, p1 * p2) | |
| return pmf | |
| def __mul__(self, other): | |
| """Computes the Pmf of the product of values drawn from self and other. | |
| other: another Pmf | |
| returns: new Pmf | |
| """ | |
| try: | |
| return self.MulPmf(other) | |
| except AttributeError: | |
| return self.MulConstant(other) | |
| def MulPmf(self, other): | |
| """Computes the Pmf of the diff of values drawn from self and other. | |
| other: another Pmf | |
| returns: new Pmf | |
| """ | |
| pmf = Pmf() | |
| for v1, p1 in self.Items(): | |
| for v2, p2 in other.Items(): | |
| pmf.Incr(v1 * v2, p1 * p2) | |
| return pmf | |
| def MulConstant(self, other): | |
| """Computes the Pmf of the product of a constant and values from self. | |
| other: a number | |
| returns: new Pmf | |
| """ | |
| pmf = Pmf() | |
| for v1, p1 in self.Items(): | |
| pmf.Set(v1 * other, p1) | |
| return pmf | |
| def __div__(self, other): | |
| """Computes the Pmf of the ratio of values drawn from self and other. | |
| other: another Pmf | |
| returns: new Pmf | |
| """ | |
| try: | |
| return self.DivPmf(other) | |
| except AttributeError: | |
| return self.MulConstant(1/other) | |
| __truediv__ = __div__ | |
| def DivPmf(self, other): | |
| """Computes the Pmf of the ratio of values drawn from self and other. | |
| other: another Pmf | |
| returns: new Pmf | |
| """ | |
| pmf = Pmf() | |
| for v1, p1 in self.Items(): | |
| for v2, p2 in other.Items(): | |
| pmf.Incr(v1 / v2, p1 * p2) | |
| return pmf | |
| def Max(self, k): | |
| """Computes the CDF of the maximum of k selections from this dist. | |
| k: int | |
| returns: new Cdf | |
| """ | |
| cdf = self.MakeCdf() | |
| return cdf.Max(k) | |
| class Joint(Pmf): | |
| """Represents a joint distribution. | |
| The values are sequences (usually tuples) | |
| """ | |
| def Marginal(self, i, label=None): | |
| """Gets the marginal distribution of the indicated variable. | |
| i: index of the variable we want | |
| Returns: Pmf | |
| """ | |
| pmf = Pmf(label=label) | |
| for vs, prob in self.Items(): | |
| pmf.Incr(vs[i], prob) | |
| return pmf | |
| def Conditional(self, i, j, val, label=None): | |
| """Gets the conditional distribution of the indicated variable. | |
| Distribution of vs[i], conditioned on vs[j] = val. | |
| i: index of the variable we want | |
| j: which variable is conditioned on | |
| val: the value the jth variable has to have | |
| Returns: Pmf | |
| """ | |
| pmf = Pmf(label=label) | |
| for vs, prob in self.Items(): | |
| if vs[j] != val: | |
| continue | |
| pmf.Incr(vs[i], prob) | |
| pmf.Normalize() | |
| return pmf | |
| def MaxLikeInterval(self, percentage=90): | |
| """Returns the maximum-likelihood credible interval. | |
| If percentage=90, computes a 90% CI containing the values | |
| with the highest likelihoods. | |
| percentage: float between 0 and 100 | |
| Returns: list of values from the suite | |
| """ | |
| interval = [] | |
| total = 0 | |
| t = [(prob, val) for val, prob in self.Items()] | |
| t.sort(reverse=True) | |
| for prob, val in t: | |
| interval.append(val) | |
| total += prob | |
| if total >= percentage / 100.0: | |
| break | |
| return interval | |
| def MakeJoint(pmf1, pmf2): | |
| """Joint distribution of values from pmf1 and pmf2. | |
| Assumes that the PMFs represent independent random variables. | |
| Args: | |
| pmf1: Pmf object | |
| pmf2: Pmf object | |
| Returns: | |
| Joint pmf of value pairs | |
| """ | |
| joint = Joint() | |
| for v1, p1 in pmf1.Items(): | |
| for v2, p2 in pmf2.Items(): | |
| joint.Set((v1, v2), p1 * p2) | |
| return joint | |
| def MakeHistFromList(t, label=None): | |
| """Makes a histogram from an unsorted sequence of values. | |
| Args: | |
| t: sequence of numbers | |
| label: string label for this histogram | |
| Returns: | |
| Hist object | |
| """ | |
| return Hist(t, label=label) | |
| def MakeHistFromDict(d, label=None): | |
| """Makes a histogram from a map from values to frequencies. | |
| Args: | |
| d: dictionary that maps values to frequencies | |
| label: string label for this histogram | |
| Returns: | |
| Hist object | |
| """ | |
| return Hist(d, label) | |
| def MakePmfFromList(t, label=None): | |
| """Makes a PMF from an unsorted sequence of values. | |
| Args: | |
| t: sequence of numbers | |
| label: string label for this PMF | |
| Returns: | |
| Pmf object | |
| """ | |
| return Pmf(t, label=label) | |
| def MakePmfFromDict(d, label=None): | |
| """Makes a PMF from a map from values to probabilities. | |
| Args: | |
| d: dictionary that maps values to probabilities | |
| label: string label for this PMF | |
| Returns: | |
| Pmf object | |
| """ | |
| return Pmf(d, label=label) | |
| def MakePmfFromItems(t, label=None): | |
| """Makes a PMF from a sequence of value-probability pairs | |
| Args: | |
| t: sequence of value-probability pairs | |
| label: string label for this PMF | |
| Returns: | |
| Pmf object | |
| """ | |
| return Pmf(dict(t), label=label) | |
| def MakePmfFromHist(hist, label=None): | |
| """Makes a normalized PMF from a Hist object. | |
| Args: | |
| hist: Hist object | |
| label: string label | |
| Returns: | |
| Pmf object | |
| """ | |
| if label is None: | |
| label = hist.label | |
| return Pmf(hist, label=label) | |
| def MakeMixture(metapmf, label='mix'): | |
| """Make a mixture distribution. | |
| Args: | |
| metapmf: Pmf that maps from Pmfs to probs. | |
| label: string label for the new Pmf. | |
| Returns: Pmf object. | |
| """ | |
| mix = Pmf(label=label) | |
| for pmf, p1 in metapmf.Items(): | |
| for x, p2 in pmf.Items(): | |
| mix.Incr(x, p1 * p2) | |
| return mix | |
| def MakeUniformPmf(low, high, n): | |
| """Make a uniform Pmf. | |
| low: lowest value (inclusive) | |
| high: highest value (inclusize) | |
| n: number of values | |
| """ | |
| pmf = Pmf() | |
| for x in np.linspace(low, high, n): | |
| pmf.Set(x, 1) | |
| pmf.Normalize() | |
| return pmf | |
| class Cdf(object): | |
| """Represents a cumulative distribution function. | |
| Attributes: | |
| xs: sequence of values | |
| ps: sequence of probabilities | |
| label: string used as a graph label. | |
| """ | |
| def __init__(self, obj=None, ps=None, label=None): | |
| """Initializes. | |
| If ps is provided, obj must be the corresponding list of values. | |
| obj: Hist, Pmf, Cdf, Pdf, dict, pandas Series, list of pairs | |
| ps: list of cumulative probabilities | |
| label: string label | |
| """ | |
| self.label = label if label is not None else '_nolegend_' | |
| if isinstance(obj, (_DictWrapper, Cdf, Pdf)): | |
| if not label: | |
| self.label = label if label is not None else obj.label | |
| if obj is None: | |
| # caller does not provide obj, make an empty Cdf | |
| self.xs = np.asarray([]) | |
| self.ps = np.asarray([]) | |
| if ps is not None: | |
| logging.warning("Cdf: can't pass ps without also passing xs.") | |
| return | |
| else: | |
| # if the caller provides xs and ps, just store them | |
| if ps is not None: | |
| if isinstance(ps, str): | |
| logging.warning("Cdf: ps can't be a string") | |
| self.xs = np.asarray(obj) | |
| self.ps = np.asarray(ps) | |
| return | |
| # caller has provided just obj, not ps | |
| if isinstance(obj, Cdf): | |
| self.xs = copy.copy(obj.xs) | |
| self.ps = copy.copy(obj.ps) | |
| return | |
| if isinstance(obj, _DictWrapper): | |
| dw = obj | |
| else: | |
| dw = Hist(obj) | |
| if len(dw) == 0: | |
| self.xs = np.asarray([]) | |
| self.ps = np.asarray([]) | |
| return | |
| xs, freqs = zip(*sorted(dw.Items())) | |
| self.xs = np.asarray(xs) | |
| self.ps = np.cumsum(freqs, dtype=np.float) | |
| self.ps /= self.ps[-1] | |
| def __str__(self): | |
| return 'Cdf(%s, %s)' % (str(self.xs), str(self.ps)) | |
| __repr__ = __str__ | |
| def __len__(self): | |
| return len(self.xs) | |
| def __getitem__(self, x): | |
| return self.Prob(x) | |
| def __setitem__(self): | |
| raise UnimplementedMethodException() | |
| def __delitem__(self): | |
| raise UnimplementedMethodException() | |
| def __eq__(self, other): | |
| return np.all(self.xs == other.xs) and np.all(self.ps == other.ps) | |
| def Copy(self, label=None): | |
| """Returns a copy of this Cdf. | |
| label: string label for the new Cdf | |
| """ | |
| if label is None: | |
| label = self.label | |
| return Cdf(list(self.xs), list(self.ps), label=label) | |
| def MakePmf(self, label=None): | |
| """Makes a Pmf.""" | |
| if label is None: | |
| label = self.label | |
| return Pmf(self, label=label) | |
| def Values(self): | |
| """Returns a sorted list of values. | |
| """ | |
| return self.xs | |
| def Items(self): | |
| """Returns a sorted sequence o |