Exemple #1
0
    def plot_joy(self,
                 var_names: tuple = None,
                 obs: Union[str, float] = None,
                 data=None,
                 iteration=-1,
                 samples_size=1000,
                 cmap='auto'):
        """

        A0rgs:
            var_names: mu and sigma of the likelihood!
            obs:
            data:
            iteration:
            samples_size:
            cmap:

        Returns:

        """
        [i.clear() for i in self.joy]
        n_iterations = self.n_samples
        iteration_label = [None for i in range(self.n_samples)]

        if data is None:
            data = self.data

        obs = data.observed_data[obs] if type(obs) is str else obs

        data = convert_to_dataset(data, group="posterior")
        coords = {}
        var_names = _var_names(var_names, data)

        plotters = list(
            xarray_var_iter(get_coords(data, coords),
                            var_names=var_names,
                            combined=True))

        x = plotters[0][2].flatten()
        y = plotters[1][2].flatten()

        n_data = x.shape[0]
        # This is the special case if n_samples is smaller than the number of bells to plot
        if iteration < self.n_samples / 2:
            l_0 = 0
            l_1 = int(self.n_samples)
            iteration_label[-1] = 0
            iteration_label[0] = l_1
        elif iteration > n_data - self.n_samples / 2:
            l_0 = int(n_data - self.n_samples)
            l_1 = n_data
            iteration_label[-1] = l_0
            iteration_label[0] = l_1
        else:
            l_0 = int(iteration - np.round(self.n_samples / 2)) + 1
            l_1 = int(iteration + np.round(self.n_samples / 2))
            iteration_label[-1] = l_0
            iteration_label[int(np.round(self.n_samples / 2)) -
                            1] = iteration - 1
            iteration_label[0] = l_1

        x = x[l_0:l_1]
        y = y[l_0:l_1]

        self.set_likelihood_limits(x + 4 * y, 'x_max')
        self.set_likelihood_limits(x - 4 * y, 'x_min')
        df = pn.DataFrame()

        color = []

        for e in range(l_1 - l_0):
            e = -e - 1
            num = np.random.normal(loc=x[e], scale=y[e], size=samples_size)
            name = e + (iteration - int(n_iterations / 2))
            df[name] = num

            if obs is not None:
                self.set_likelihood_limits(
                    stats.norm.pdf(obs, loc=x[e], scale=y[e]), 'y_max')

            if cmap is None:
                color = default_blue
            else:
                if cmap == 'auto':
                    if self.likelihood_axes is None:
                        cmap = self.create_color_map()
                    else:
                        cmap = self.cmap_l

                color.append(self.evaluate_cmap(cmap, x[e], y[e], obs))

        if self.likelihood_axes is not None:
            x_range = self.likelihood_axes.get_xlim()
        else:
            x_range = (self.x_min_like, self.x_max_like)
        f, axes = joyplot(df,
                          bw_method=1,
                          labels=iteration_label,
                          ax=self.joy,
                          yrot=0,
                          range_style='all',
                          x_range=x_range,
                          color=color,
                          grid='y',
                          fade=False,
                          last_axis=False,
                          linewidth=.1,
                          alpha=1)

        n_axes = len(axes[:-1])
        if int(n_axes / 2) >= iteration:
            ax_sel = axes[-iteration - 1]
            ax_sel.hlines(0,
                          ax_sel.get_xlim()[0],
                          ax_sel.get_xlim()[1],
                          color='#DA8886',
                          linewidth=3)
        elif iteration > n_data - int(self.n_samples / 2):
            ax_sel = axes[-iteration - self.n_samples + n_data - 1]
            ax_sel.hlines(0,
                          ax_sel.get_xlim()[0],
                          ax_sel.get_xlim()[1],
                          color='#DA8886',
                          linewidth=3)
        else:
            ax_sel = axes[int(n_axes / 2)]
            ax_sel.hlines(0,
                          ax_sel.get_xlim()[0],
                          ax_sel.get_xlim()[1],
                          color='#DA8886',
                          linewidth=3)

        if obs is not None:
            if self.likelihood_axes is None:
                self.joy[0].scatter(obs,
                                    np.ones_like(obs) *
                                    self.joy[0].get_ylim()[1],
                                    marker='v',
                                    s=200,
                                    c='#DA8886')
            self.joy[-1].scatter(obs,
                                 np.ones_like(obs) *
                                 self.joy[-1].get_ylim()[0],
                                 marker='^',
                                 s=200,
                                 c='#DA8886')

        return axes
Exemple #2
0
    def plot_marginal(self,
                      var_names=None,
                      data=None,
                      iteration=-1,
                      group='both',
                      plot_trace=True,
                      n_iterations=20,
                      kind='kde',
                      coords=None,
                      credible_interval=.98,
                      marginal_kwargs=None,
                      marginal_kwargs_prior=None,
                      joint_kwargs=None,
                      joint_kwargs_prior=None):
        self.axjoin.clear()
        self.ax_hist_x.clear()
        self.ax_hist_y.clear()

        if data is None:
            data = self.data

        valid_kinds = ["scatter", "kde", "hexbin"]
        if kind not in valid_kinds:
            raise ValueError(
                ("Plot type {} not recognized."
                 "Plot type must be in {}").format(kind, valid_kinds))

        if coords is None:
            coords = {}

        if joint_kwargs is None:
            joint_kwargs = {}

        if marginal_kwargs is None:
            marginal_kwargs = {}

        data_0 = convert_to_dataset(data, group="posterior")
        var_names = _var_names(var_names, data_0)

        plotters = list(
            xarray_var_iter(get_coords(data_0, coords),
                            var_names=var_names,
                            combined=True))

        if len(plotters) != 2:
            raise Exception(
                "Number of variables to be plotted must 2 (you supplied {})".
                format(len(plotters)))

        if kind == 'kde':
            joint_kwargs.setdefault('contourf_kwargs', {})
            joint_kwargs.setdefault('contour_kwargs', {})
            joint_kwargs['contourf_kwargs'].setdefault('cmap', my_cmap_l)
            joint_kwargs['contourf_kwargs'].setdefault('levels', 11)
            joint_kwargs['contourf_kwargs'].setdefault('alpha', .8)
            joint_kwargs['contour_kwargs'].setdefault('alpha', 0)

        marginal_kwargs.setdefault('fill_kwargs', {})
        marginal_kwargs.setdefault("plot_kwargs", {})
        marginal_kwargs["plot_kwargs"]["linewidth"] = self.linewidth

        marginal_kwargs["plot_kwargs"].setdefault('color', default_l)
        marginal_kwargs['fill_kwargs'].setdefault('color', default_l)
        marginal_kwargs['fill_kwargs'].setdefault('alpha', .8)

        if group == 'both' or group == 'posterior':

            self.plot_joint_posterior(plotters,
                                      kind=kind,
                                      iteration=iteration,
                                      **joint_kwargs)
            self.plot_marginal_posterior(plotters,
                                         iteration=iteration,
                                         **marginal_kwargs)

        if group == 'both' or group == 'prior':
            if joint_kwargs_prior is None:
                joint_kwargs_prior = {}

            if marginal_kwargs_prior is None:
                marginal_kwargs_prior = {}

            joint_kwargs_prior.setdefault('contourf_kwargs', {})
            marginal_kwargs_prior.setdefault('fill_kwargs', {})
            marginal_kwargs_prior.setdefault("plot_kwargs", {})
            marginal_kwargs_prior["plot_kwargs"]["linewidth"] = self.linewidth

            if kind == 'kde':
                joint_kwargs_prior.setdefault('contourf_kwargs', {})
                joint_kwargs_prior.setdefault('contour_kwargs', {})
                joint_kwargs_prior['contourf_kwargs'].setdefault(
                    'cmap', my_cmap)
                joint_kwargs_prior['contourf_kwargs'].setdefault('levels', 11)
                alpha_p = .8 if group == 'prior' else .4
                joint_kwargs_prior['contourf_kwargs'].setdefault(
                    'alpha', alpha_p)
                joint_kwargs_prior['contour_kwargs'].setdefault('alpha', 0)

            marginal_kwargs_prior["plot_kwargs"].setdefault(
                'color', default_blue)
            marginal_kwargs_prior['fill_kwargs'].setdefault(
                'color', default_blue)
            marginal_kwargs_prior['fill_kwargs'].setdefault('alpha', alpha_p)

            data_1 = convert_to_dataset(data, group="prior")
            plotters_prior = list(
                xarray_var_iter(get_coords(data_1, coords),
                                var_names=var_names,
                                combined=True))

            self.plot_joint_posterior(plotters_prior,
                                      kind=kind,
                                      **joint_kwargs_prior)
            self.plot_marginal_posterior(plotters_prior,
                                         **marginal_kwargs_prior)

            x_min, x_max, y_min, y_max = self.compute_hpd(
                plotters_prior, credible_interval=credible_interval)

        else:
            x_min, x_max, y_min, y_max = self.compute_hpd(
                plotters,
                iteration=iteration,
                credible_interval=credible_interval)
        if plot_trace is True:
            self.plot_trace(plotters, iteration, n_iterations)

        self.axjoin.set_xlim(x_min, x_max)
        self.axjoin.set_ylim(y_min, y_max)
        self.ax_hist_x.set_xlim(self.axjoin.get_xlim())
        self.ax_hist_y.set_ylim(self.axjoin.get_ylim())

        return self.axjoin, self.ax_hist_x, self.ax_hist_y