Instruction:
Given the following Python 3 function, write the documentation
def plot(self, figsize="GROW", parameters=None, chains=None, extents=None, filename=None,
             display=False, truth=None, legend=None, blind=None, watermark=None):  # pragma: no cover
        """ Plot the chain!

        Parameters
        ----------
        figsize : str|tuple(float)|float, optional
            The figure size to generate. Accepts a regular two tuple of size in inches,
            or one of several key words. The default value of ``COLUMN`` creates a figure
            of appropriate size of insertion into an A4 LaTeX document in two-column mode.
            ``PAGE`` creates a full page width figure. ``GROW`` creates an image that
            scales with parameters (1.5 inches per parameter). String arguments are not
            case sensitive. If you pass a float, it will scale the default ``GROW`` by
            that amount, so ``2.0`` would result in a plot 3 inches per parameter.
        parameters : list[str]|int, optional
            If set, only creates a plot for those specific parameters (if list). If an
            integer is given, only plots the fist so many parameters.
        chains : int|str, list[str|int], optional
            Used to specify which chain to show if more than one chain is loaded in.
            Can be an integer, specifying the
            chain index, or a str, specifying the chain name.
        extents : list[tuple[float]] or dict[str], optional
            Extents are given as two-tuples. You can pass in a list the same size as
            parameters (or default parameters if you don't specify parameters),
            or as a dictionary.
        filename : str, optional
            If set, saves the figure to this location
        display : bool, optional
            If True, shows the figure using ``plt.show()``.
        truth : list[float] or dict[str], optional
            A list of truth values corresponding to parameters, or a dictionary of
            truth values indexed by key
        legend : bool, optional
            If true, creates a legend in your plot using the chain names.
        blind : bool|string|list[string], optional
            Whether to blind axes values. Can be set to `True` to blind all parameters,
            or can pass in a string (or list of strings) which specify the parameters to blind.
        watermark : str, optional
            A watermark to add to the figure

        Returns
        -------
        figure
            the matplotlib figure

        """

        chains, parameters, truth, extents, blind = self._sanitise(chains, parameters, truth,
                                                                          extents, color_p=True, blind=blind)
        names = [chain.name for chain in chains]

        if legend is None:
            legend = len(chains) > 1

        # If no chains have names, don't plot the legend
        legend = legend and len([n for n in names if n]) > 0

        # Calculate cmap extents
        unique_color_params = list(set([c.config["color_params"] for c in chains if c.config["color_params"] is not None]))
        num_cax = len(unique_color_params)
        color_param_extents = {}
        for u in unique_color_params:
            umin, umax = np.inf, -np.inf
            for chain in chains:
                if chain.config["color_params"] == u:
                    data = chain.get_color_data()
                    if data is not None:
                        umin = min(umin, data.min())
                        umax = max(umax, data.max())
            color_param_extents[u] = (umin, umax)

        grow_size = 1.5
        if isinstance(figsize, float):
            grow_size *= figsize
            figsize = "GROW"

        if isinstance(figsize, str):
            if figsize.upper() == "COLUMN":
                figsize = (5 + (1 if num_cax > 0 else 0), 5)
            elif figsize.upper() == "PAGE":
                figsize = (10, 10)
            elif figsize.upper() == "GROW":
                figsize = (grow_size * len(parameters) + num_cax * 1.0, grow_size * len(parameters))
            else:
                raise ValueError("Unknown figure size %s" % figsize)
        elif isinstance(figsize, float):
            figsize = (figsize * grow_size * len(parameters), figsize * grow_size * len(parameters))

        plot_hists = self.parent.config["plot_hists"]
        flip = (len(parameters) == 2 and plot_hists and self.parent.config["flip"])

        fig, axes, params1, params2, extents = self._get_figure(parameters, chains=chains, figsize=figsize, flip=flip,
                                                                external_extents=extents, blind=blind)
        axl = axes.ravel().tolist()
        summary = self.parent.config["summary"]

        if summary is None:
            summary = len(parameters) < 5 and len(self.parent.chains) == 1
        if len(chains) == 1:
            self._logger.debug("Plotting surfaces for chain of dimension %s" %
                               (chains[0].chain.shape,))
        else:
            self._logger.debug("Plotting surfaces for %d chains" % len(chains))
        cbar_done = []

        chain_points = [c for c in chains if c.config["plot_point"]]
        num_chain_points = len(chain_points)
        if num_chain_points:
            subgroup_names = list(set([c.name for c in chain_points]))
            subgroups = [[c for c in chain_points if c.name == n] for n in subgroup_names]
            markers = [group[0].config["marker_style"] for group in subgroups]  # Only one marker per group
            marker_sizes = [[g.config["marker_size"] for g in group] for group in subgroups]  # But size can diff
            marker_alphas = [group[0].config["marker_alpha"] for group in subgroups]  # Only one marker per group
        for i, p1 in enumerate(params1):
            for j, p2 in enumerate(params2):
                if i < j:
                    continue
                ax = axes[i, j]
                do_flip = (flip and i == len(params1) - 1)

                # Plot the histograms
                if plot_hists and i == j:
                    if do_flip:
                        self._add_truth(ax, truth, p1)
                    else:
                        self._add_truth(ax, truth,  None, py=p2)
                    max_val = None

                    # Plot each chain
                    for chain in chains:
                        if p1 not in chain.parameters:
                            continue
                        if not chain.config["plot_contour"]:
                            continue

                        param_summary = summary and p1 not in blind
                        m = self._plot_bars(ax, p1, chain, flip=do_flip, summary=param_summary)

                        if max_val is None or m > max_val:
                            max_val = m

                    if num_chain_points and self.parent.config["global_point"]:
                        m = self._plot_point_histogram(ax, subgroups, p1, flip=do_flip)
                        if max_val is None or m > max_val:
                            max_val = m

                    if max_val is not None:
                        if do_flip:
                            ax.set_xlim(0, 1.1 * max_val)
                        else:
                            ax.set_ylim(0, 1.1 * max_val)

                else:
                    for chain in chains:
                        if p1 not in chain.parameters or p2 not in chain.parameters:
                            continue
                        if not chain.config["plot_contour"]:
                            continue
                        h = None
                        if p1 in chain.parameters and p2 in chain.parameters:
                            h = self._plot_contour(ax, chain, p1, p2, color_extents=color_param_extents)
                        cp = chain.config["color_params"]
                        if h is not None and cp is not None and cp not in cbar_done:
                            cbar_done.append(cp)
                            aspect = figsize[1] / 0.15
                            fraction = 0.85 / figsize[0]
                            cbar = fig.colorbar(h, ax=axl, aspect=aspect, pad=0.03, fraction=fraction, drawedges=False)
                            label = cp
                            if label == "weights":
                                label = "Weights"
                            elif label == "log_weights":
                                label = "log(Weights)"
                            elif label == "posterior":
                                label = "log(Posterior)"
                            cbar.set_label(label, fontsize=14)
                            cbar.solids.set(alpha=1)

                    if num_chain_points:
                        self._plot_points(ax, subgroups, markers, marker_sizes, marker_alphas, p1, p2)

                    self._add_truth(ax, truth, p1, py=p2)

        colors = [c.config["color"] for c in chains]
        plot_points = [c.config["plot_point"] for c in chains]
        plot_contours = [c.config["plot_contour"] for c in chains]
        linestyles = [c.config["linestyle"] for c in chains]
        linewidths = [c.config["linewidth"] for c in chains]
        marker_styles = [c.config["marker_style"] for c in chains]
        marker_sizes = [c.config["marker_size"] for c in chains]
        legend_kwargs = self.parent.config["legend_kwargs"]
        legend_artists = self.parent.config["legend_artists"]
        legend_color_text = self.parent.config["legend_color_text"]
        legend_location = self.parent.config["legend_location"]

        if legend_location is None:
            if not flip or len(parameters) > 2:
                legend_location = (0, -1)
            else:
                legend_location = (-1, 0)
        outside = (legend_location[0] >= legend_location[1])
        if names is not None and legend:
            ax = axes[legend_location[0], legend_location[1]]
            if "markerfirst" not in legend_kwargs:
                # If we have legend inside a used subplot, switch marker order
                legend_kwargs["markerfirst"] = outside or not legend_artists
            linewidths2 = linewidths if legend_artists else [0]*len(linewidths)
            linestyles2 = linestyles if legend_artists else ["-"]*len(linestyles)
            marker_sizes2 = marker_sizes if legend_artists else [0]*len(linestyles)

            artists = []
            done_names = []
            final_colors = []
            for i, (n, c, ls, lw, marker, size, pp, pc) in enumerate(zip(names, colors, linestyles2, linewidths2,
                                                                         marker_styles, marker_sizes2, plot_points, plot_contours)):
                if n is None or n in done_names:
                    continue
                done_names.append(n)
                final_colors.append(c)
                size = np.sqrt(size)  # plot vs scatter use size differently, hence the sqrt
                if pc and not pp:
                    artists.append(plt.Line2D((0, 1), (0, 0), color=c, ls=ls, lw=lw))
                elif not pc and pp:
                    artists.append(plt.Line2D((0, 1), (0, 0), color=c, ls=ls, lw=0, marker=marker, markersize=size))
                else:
                    artists.append(plt.Line2D((0, 1), (0, 0), color=c, ls=ls, lw=lw, marker=marker, markersize=size))

            leg = ax.legend(artists, done_names, **legend_kwargs)
            if legend_color_text:
                for text, c in zip(leg.get_texts(), final_colors):
                    text.set_weight("medium")
                    text.set_color(c)
            if not outside:
                loc = legend_kwargs.get("loc") or ""
                if "right" in loc.lower():
                    vp = leg._legend_box._children[-1]._children[0]
                    vp.align = "right"

        fig.canvas.draw()
        for ax in axes[-1, :]:
            offset = ax.get_xaxis().get_offset_text()
            ax.set_xlabel('{0} {1}'.format(ax.get_xlabel(), "[{0}]".format(offset.get_text()) if offset.get_text() else ""))
            offset.set_visible(False)
        for ax in axes[:, 0]:
            offset = ax.get_yaxis().get_offset_text()
            ax.set_ylabel('{0} {1}'.format(ax.get_ylabel(), "[{0}]".format(offset.get_text()) if offset.get_text() else ""))
            offset.set_visible(False)

        dpi = 300
        if watermark:
            if flip and len(parameters) == 2:
                ax = axes[-1, 0]
            else:
                ax = None
            self._add_watermark(fig, ax, figsize, watermark, dpi=dpi)

        if filename is not None:
            if isinstance(filename, str):
                filename = [filename]
            for f in filename:
                self._save_fig(fig, f, dpi)
        if display:
            plt.show()

        return fig

Response: Plots the key - word entry for the current location.


Instruction:
Here you have a function in Python 3, explain what it does
def plot_walks(self, parameters=None, truth=None, extents=None, display=False,
                   filename=None, chains=None, convolve=None, figsize=None,
                   plot_weights=True, plot_posterior=True, log_weight=None):  # pragma: no cover
        """ Plots the chain walk; the parameter values as a function of step index.

        This plot is more for a sanity or consistency check than for use with final results.
        Plotting this before plotting with :func:`plot` allows you to quickly see if the
        chains are well behaved, or if certain parameters are suspect
        or require a greater burn in period.

        The desired outcome is to see an unchanging distribution along the x-axis of the plot.
        If there are obvious tails or features in the parameters, you probably want
        to investigate.

        Parameters
        ----------
        parameters : list[str]|int, optional
            Specify a subset of parameters to plot. If not set, all parameters are plotted.
            If an integer is given, only the first so many parameters are plotted.
        truth : list[float]|dict[str], optional
            A list of truth values corresponding to parameters, or a dictionary of
            truth values keyed by the parameter.
        extents : list[tuple]|dict[str], optional
            A list of two-tuples for plot extents per parameter, or a dictionary of
            extents keyed by the parameter.
        display : bool, optional
            If set, shows the plot using ``plt.show()``
        filename : str, optional
            If set, saves the figure to the filename
        chains : int|str, list[str|int], optional
            Used to specify which chain to show if more than one chain is loaded in.
            Can be an integer, specifying the
            chain index, or a str, specifying the chain name.
        convolve : int, optional
            If set, overplots a smoothed version of the steps using ``convolve`` as
            the width of the smoothing filter.
        figsize : tuple, optional
            If set, sets the created figure size.
        plot_weights : bool, optional
            If true, plots the weight if they are available
        plot_posterior : bool, optional
            If true, plots the log posterior if they are available
        log_weight : bool, optional
            Whether to display weights in log space or not. If None, the value is
            inferred by the mean weights of the plotted chains.

        Returns
        -------
        figure
            the matplotlib figure created

        """

        chains, parameters, truth, extents, _ = self._sanitise(chains, parameters, truth, extents)

        n = len(parameters)
        extra = 0
        if plot_weights:
            plot_weights = plot_weights and np.any([np.any(c.weights != 1.0) for c in chains])

        plot_posterior = plot_posterior and np.any([c.posterior is not None for c in chains])

        if plot_weights:
            extra += 1
        if plot_posterior:
            extra += 1

        if figsize is None:
            figsize = (8, 0.75 + (n + extra))

        fig, axes = plt.subplots(figsize=figsize, nrows=n + extra, squeeze=False, sharex=True)

        for i, axes_row in enumerate(axes):
            ax = axes_row[0]
            if i >= extra:
                p = parameters[i - n]
                for chain in chains:
                    if p in chain.parameters:
                        chain_row = chain.get_data(p)
                        self._plot_walk(ax, p, chain_row, extents=extents.get(p), convolve=convolve, color=chain.config["color"])
                if truth.get(p) is not None:
                    self._plot_walk_truth(ax, truth.get(p))
            else:
                if i == 0 and plot_posterior:
                    for chain in chains:
                        if chain.posterior is not None:
                            self._plot_walk(ax, "$\log(P)$", chain.posterior - chain.posterior.max(),
                                            convolve=convolve, color=chain.config["color"])
                else:
                    if log_weight is None:
                        log_weight = np.any([chain.weights.mean() < 0.1 for chain in chains])
                    if log_weight:
                        for chain in chains:
                            self._plot_walk(ax, r"$\log_{10}(w)$", np.log10(chain.weights),
                                            convolve=convolve, color=chain.config["color"])
                    else:
                        for chain in chains:
                            self._plot_walk(ax, "$w$", chain.weights,
                                            convolve=convolve, color=chain.config["color"])

        if filename is not None:
            if isinstance(filename, str):
                filename = [filename]
            for f in filename:
                self._save_fig(fig, f, 300)
        if display:
            plt.show()
        return fig

Response: Plots the chain walks for the specified parameters.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def plot_distributions(self, parameters=None, truth=None, extents=None, display=False,
                           filename=None, chains=None, col_wrap=4, figsize=None, blind=None):  # pragma: no cover
        """ Plots the 1D parameter distributions for verification purposes.

        This plot is more for a sanity or consistency check than for use with final results.
        Plotting this before plotting with :func:`plot` allows you to quickly see if the
        chains give well behaved distributions, or if certain parameters are suspect
        or require a greater burn in period.

        Parameters
        ----------
        parameters : list[str]|int, optional
            Specify a subset of parameters to plot. If not set, all parameters are plotted.
            If an integer is given, only the first so many parameters are plotted.
        truth : list[float]|dict[str], optional
            A list of truth values corresponding to parameters, or a dictionary of
            truth values keyed by the parameter.
        extents : list[tuple]|dict[str], optional
            A list of two-tuples for plot extents per parameter, or a dictionary of
            extents keyed by the parameter.
        display : bool, optional
            If set, shows the plot using ``plt.show()``
        filename : str, optional
            If set, saves the figure to the filename
        chains : int|str, list[str|int], optional
            Used to specify which chain to show if more than one chain is loaded in.
            Can be an integer, specifying the
            chain index, or a str, specifying the chain name.
        col_wrap : int, optional
            How many columns to plot before wrapping.
        figsize : tuple(float)|float, optional
            Either a tuple specifying the figure size or a float scaling factor.
        blind : bool|string|list[string], optional
            Whether to blind axes values. Can be set to `True` to blind all parameters,
            or can pass in a string (or list of strings) which specify the parameters to blind.

        Returns
        -------
        figure
            the matplotlib figure created

        """
        chains, parameters, truth, extents, blind = self._sanitise(chains, parameters, truth, extents, blind=blind)

        n = len(parameters)
        num_cols = min(n, col_wrap)
        num_rows = int(np.ceil(1.0 * n / col_wrap))

        if figsize is None:
            figsize = 1.0
        if isinstance(figsize, float):
            figsize_float = figsize
            figsize = (num_cols * 2 * figsize, num_rows * 2 * figsize)
        else:
            figsize_float = 1.0

        summary = self.parent.config["summary"]
        label_font_size = self.parent.config["label_font_size"]
        tick_font_size = self.parent.config["tick_font_size"]
        max_ticks = self.parent.config["max_ticks"]
        diagonal_tick_labels = self.parent.config["diagonal_tick_labels"]

        if summary is None:
            summary = len(self.parent.chains) == 1

        hspace = (0.8 if summary else 0.5) / figsize_float
        fig, axes = plt.subplots(nrows=num_rows, ncols=num_cols, figsize=figsize, squeeze=False)
        fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.1, wspace=0.05, hspace=hspace)

        formatter = ScalarFormatter(useOffset=False)
        formatter.set_powerlimits((-3, 4))

        for i, ax in enumerate(axes.flatten()):
            if i >= len(parameters):
                ax.set_axis_off()
                continue
            p = parameters[i]

            ax.set_yticks([])
            if p in blind:
                ax.set_xticks([])
            else:
                if diagonal_tick_labels:
                    _ = [l.set_rotation(45) for l in ax.get_xticklabels()]
                _ = [l.set_fontsize(tick_font_size) for l in ax.get_xticklabels()]
                ax.xaxis.set_major_locator(MaxNLocator(max_ticks, prune="lower"))
                ax.xaxis.set_major_formatter(formatter)
            ax.set_xlim(extents.get(p) or self._get_parameter_extents(p, chains))
            max_val = None
            for chain in chains:
                if p in chain.parameters:
                    param_summary = summary and p not in blind
                    m = self._plot_bars(ax, p, chain, summary=param_summary)
                    if max_val is None or m > max_val:
                        max_val = m

            self._add_truth(ax, truth, None, py=p)
            ax.set_ylim(0, 1.1 * max_val)
            ax.set_xlabel(p, fontsize=label_font_size)

        if filename is not None:
            if isinstance(filename, str):
                filename = [filename]
            for f in filename:
                self._save_fig(fig, f, 300)
        if display:
            plt.show()
        return fig

Response: Plots the 1D parameter distributions for verification purposes.


Instruction:
Write a Python 3 script for
plotting the parameter summaries for the current system.

Response:
def plot_summary(self, parameters=None, truth=None, extents=None, display=False,
                     filename=None, chains=None, figsize=1.0, errorbar=False, include_truth_chain=True,
                     blind=None, watermark=None, extra_parameter_spacing=0.5,
                     vertical_spacing_ratio=1.0, show_names=True):  # pragma: no cover
        """ Plots parameter summaries

        This plot is more for a sanity or consistency check than for use with final results.
        Plotting this before plotting with :func:`plot` allows you to quickly see if the
        chains give well behaved distributions, or if certain parameters are suspect
        or require a greater burn in period.

        Parameters
        ----------
        parameters : list[str]|int, optional
            Specify a subset of parameters to plot. If not set, all parameters are plotted.
            If an integer is given, only the first so many parameters are plotted.
        truth : list[float]|list|list[float]|dict[str]|str, optional
            A list of truth values corresponding to parameters, or a dictionary of
            truth values keyed by the parameter. Each "truth value" can be either a float (will
            draw a vertical line), two floats (a shaded interval) or three floats (min, mean, max),
            which renders as a shaded interval with a line for the mean. Or, supply a string
            which matches a chain name, and the results for that chain will be used as the 'truth'
        extents : list[tuple]|dict[str], optional
            A list of two-tuples for plot extents per parameter, or a dictionary of
            extents keyed by the parameter.
        display : bool, optional
            If set, shows the plot using ``plt.show()``
        filename : str, optional
            If set, saves the figure to the filename
        chains : int|str, list[str|int], optional
            Used to specify which chain to show if more than one chain is loaded in.
            Can be an integer, specifying the
            chain index, or a str, specifying the chain name.
        figsize : float, optional
            Scale horizontal and vertical figure size.
        errorbar : bool, optional
            Whether to onle plot an error bar, instead of the marginalised distribution.
        include_truth_chain : bool, optional
            If you specify another chain as the truth chain, determine if it should still
            be plotted.
        blind : bool|string|list[string], optional
            Whether to blind axes values. Can be set to `True` to blind all parameters,
            or can pass in a string (or list of strings) which specify the parameters to blind.
        watermark : str, optional
            A watermark to add to the figure
        extra_parameter_spacing : float, optional
            Increase horizontal space for parameter values
        vertical_spacing_ratio : float, optional
            Increase vertical space for each model
        show_names : bool, optional
            Whether to show chain names or not. Defaults to `True`.

        Returns
        -------
        figure
            the matplotlib figure created

        """
        wide_extents = not errorbar
        chains, parameters, truth, extents, blind = self._sanitise(chains, parameters, truth, extents, blind=blind, wide_extents=wide_extents)

        all_names = [c.name for c in self.parent.chains]

        # Check if we're using a chain for truth values
        if isinstance(truth, str):
            assert truth in all_names, "Truth chain %s is not in the list of added chains %s" % (truth, all_names)
            if not include_truth_chain:
                chains = [c for c in chains if c.name != truth]
            truth = self.parent.analysis.get_summary(chains=truth, parameters=parameters)

        max_param = self._get_size_of_texts(parameters)
        fid_dpi = 65  # Seriously I have no idea what value this should be
        param_width = extra_parameter_spacing + max(0.5, max_param / fid_dpi)

        if show_names:
            max_model_name = self._get_size_of_texts([chain.name for chain in chains])
            model_width = 0.25 + (max_model_name / fid_dpi)
            gridspec_kw = {'width_ratios': [model_width] + [param_width] * len(parameters), 'height_ratios': [1] * len(chains)}
            ncols = 1 + len(parameters)
        else:
            model_width = 0
            gridspec_kw = {'width_ratios': [param_width] * len(parameters), 'height_ratios': [1] * len(chains)}
            ncols = len(parameters)

        top_spacing = 0.3
        bottom_spacing = 0.2
        row_height = (0.5 if not errorbar else 0.3) * vertical_spacing_ratio
        width = param_width * len(parameters) + model_width
        height = top_spacing + bottom_spacing + row_height * len(chains)
        top_ratio = 1 - (top_spacing / height)
        bottom_ratio = bottom_spacing / height

        figsize = (width * figsize, height * figsize)
        fig, axes = plt.subplots(nrows=len(chains), ncols=ncols, figsize=figsize, squeeze=False, gridspec_kw=gridspec_kw)
        fig.subplots_adjust(left=0.05, right=0.95, top=top_ratio, bottom=bottom_ratio, wspace=0.0, hspace=0.0)
        label_font_size = self.parent.config["label_font_size"]
        legend_color_text = self.parent.config["legend_color_text"]

        max_vals = {}
        for i, row in enumerate(axes):
            chain = chains[i]

            cs, ws, ps, = chain.chain, chain.weights, chain.parameters
            gs, ns = chain.grid, chain.name

            colour = chain.config["color"]

            # First one put name of model
            if show_names:
                ax_first = row[0]
                ax_first.set_axis_off()
                text_colour = "k" if not legend_color_text else colour
                ax_first.text(0, 0.5, ns, transform=ax_first.transAxes, fontsize=label_font_size, verticalalignment="center", color=text_colour, weight="medium")
                cols = row[1:]
            else:
                cols = row

            for ax, p in zip(cols, parameters):
                # Set up the frames
                if i > 0:
                    ax.spines['top'].set_visible(False)
                if i < (len(chains) - 1):
                    ax.spines['bottom'].set_visible(False)
                if i < (len(chains) - 1) or p in blind:
                    ax.set_xticks([])
                ax.set_yticks([])
                ax.set_xlim(extents[p])

                # Put title in
                if i == 0:
                    ax.set_title(r"$%s$" % p, fontsize=label_font_size)

                # Add truth values
                truth_value = truth.get(p)
                if truth_value is not None:
                    if isinstance(truth_value, float) or isinstance(truth_value, int):
                        truth_mean = truth_value
                        truth_min, truth_max = None, None
                    else:
                        if len(truth_value) == 1:
                            truth_mean = truth_value
                            truth_min, truth_max = None, None
                        elif len(truth_value) == 2:
                            truth_min, truth_max = truth_value
                            truth_mean = None
                        else:
                            truth_min, truth_mean, truth_max = truth_value
                    if truth_mean is not None:
                        ax.axvline(truth_mean, **self.parent.config_truth)
                    if truth_min is not None and truth_max is not None:
                        ax.axvspan(truth_min, truth_max, color=self.parent.config_truth["color"], alpha=0.15, lw=0)
                # Skip if this chain doesnt have the parameter
                if p not in ps:
                    continue

                # Plot the good stuff
                if errorbar:
                    fv = self.parent.analysis.get_parameter_summary(chain, p)
                    if fv[0] is not None and fv[2] is not None:
                        diff = np.abs(np.diff(fv))
                        ax.errorbar([fv[1]], 0, xerr=[[diff[0]], [diff[1]]], fmt='o', color=colour)
                else:
                    m = self._plot_bars(ax, p, chain)
                    if max_vals.get(p) is None or m > max_vals.get(p):
                        max_vals[p] = m

        for i, row in enumerate(axes):
            index = 1 if show_names else 0
            for ax, p in zip(row[index:], parameters):
                if not errorbar:
                    ax.set_ylim(0, 1.1 * max_vals[p])

        dpi = 300
        if watermark:
            ax = None
            self._add_watermark(fig, ax, figsize, watermark, dpi=dpi, size_scale=0.8)

        if filename is not None:
            if isinstance(filename, str):
                filename = [filename]
            for f in filename:
                self._save_fig(fig, f, dpi)
        if display:
            plt.show()

        return fig


Instruction:
Write a Python 3 script to
run the Geweke diagnostic on the supplied chains.

Response:
def geweke(self, chain=None, first=0.1, last=0.5, threshold=0.05):
        """ Runs the Geweke diagnostic on the supplied chains.

        Parameters
        ----------
        chain : int|str, optional
            Which chain to run the diagnostic on. By default, this is `None`,
            which will run the diagnostic on all chains. You can also
            supply and integer (the chain index) or a string, for the chain
            name (if you set one).
        first : float, optional
            The amount of the start of the chain to use
        last : float, optional
            The end amount of the chain to use
        threshold : float, optional
            The p-value to use when testing for normality.

        Returns
        -------
        float
            whether or not the chains pass the test

        """
        if chain is None:
            return np.all([self.geweke(k, threshold=threshold) for k in range(len(self.parent.chains))])

        index = self.parent._get_chain(chain)
        assert len(index) == 1, "Please specify only one chain, have %d chains" % len(index)
        chain = self.parent.chains[index[0]]

        num_walkers = chain.walkers
        assert num_walkers is not None and num_walkers > 0, \
            "You need to specify the number of walkers to use the Geweke diagnostic."
        name = chain.name
        data = chain.chain
        chains = np.split(data, num_walkers)
        n = 1.0 * chains[0].shape[0]
        n_start = int(np.floor(first * n))
        n_end = int(np.floor((1 - last) * n))
        mean_start = np.array([np.mean(c[:n_start, i])
                               for c in chains for i in range(c.shape[1])])
        var_start = np.array([self._spec(c[:n_start, i]) / c[:n_start, i].size
                              for c in chains for i in range(c.shape[1])])
        mean_end = np.array([np.mean(c[n_end:, i])
                             for c in chains for i in range(c.shape[1])])
        var_end = np.array([self._spec(c[n_end:, i]) / c[n_end:, i].size
                            for c in chains for i in range(c.shape[1])])
        zs = (mean_start - mean_end) / (np.sqrt(var_start + var_end))
        _, pvalue = normaltest(zs)
        print("Gweke Statistic for chain %s has p-value %e" % (name, pvalue))
        return pvalue > threshold


Instruction:
Implement a function in Python 3 to
generate a LaTeX table from parameter summaries.

Response:
def get_latex_table(self, parameters=None, transpose=False, caption=None,
                        label="tab:model_params", hlines=True, blank_fill="--"):  # pragma: no cover
        """ Generates a LaTeX table from parameter summaries.

        Parameters
        ----------
        parameters : list[str], optional
            A list of what parameters to include in the table. By default, includes all parameters
        transpose : bool, optional
            Defaults to False, which gives each column as a parameter, each chain (framework)
            as a row. You can swap it so that you have a parameter each row and a framework
            each column by setting this to True
        caption : str, optional
            If you want to generate a caption for the table through Python, use this.
            Defaults to an empty string
        label : str, optional
            If you want to generate a label for the table through Python, use this.
            Defaults to an empty string
        hlines : bool, optional
            Inserts ``\\hline`` before and after the header, and at the end of table.
        blank_fill : str, optional
            If a framework does not have a particular parameter, will fill that cell of
            the table with this string.

        Returns
        -------
        str
            the LaTeX table.
        """
        if parameters is None:
            parameters = self.parent._all_parameters
        for p in parameters:
            assert isinstance(p, str), \
                "Generating a LaTeX table requires all parameters have labels"
        num_parameters = len(parameters)
        num_chains = len(self.parent.chains)
        fit_values = self.get_summary(squeeze=False)
        if label is None:
            label = ""
        if caption is None:
            caption = ""

        end_text = " \\\\ \n"
        if transpose:
            column_text = "c" * (num_chains + 1)
        else:
            column_text = "c" * (num_parameters + 1)

        center_text = ""
        hline_text = "\\hline\n"
        if hlines:
            center_text += hline_text + "\t\t"
        if transpose:
            center_text += " & ".join(["Parameter"] + [c.name for c in self.parent.chains]) + end_text
            if hlines:
                center_text += "\t\t" + hline_text
            for p in parameters:
                arr = ["\t\t" + p]
                for chain_res in fit_values:
                    if p in chain_res:
                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))
                    else:
                        arr.append(blank_fill)
                center_text += " & ".join(arr) + end_text
        else:
            center_text += " & ".join(["Model"] + parameters) + end_text
            if hlines:
                center_text += "\t\t" + hline_text
            for name, chain_res in zip([c.name for c in self.parent.chains], fit_values):
                arr = ["\t\t" + name]
                for p in parameters:
                    if p in chain_res:
                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))
                    else:
                        arr.append(blank_fill)
                center_text += " & ".join(arr) + end_text
        if hlines:
            center_text += "\t\t" + hline_text
        final_text = get_latex_table_frame(caption, label) % (column_text, center_text)

        return final_text


Instruction:
Create a Python 3 function to
get a summary of the marginalised parameter distributions.

Response:
def get_summary(self, squeeze=True, parameters=None, chains=None):
        """  Gets a summary of the marginalised parameter distributions.

        Parameters
        ----------
        squeeze : bool, optional
            Squeeze the summaries. If you only have one chain, squeeze will not return
            a length one list, just the single summary. If this is false, you will
            get a length one list.
        parameters : list[str], optional
            A list of parameters which to generate summaries for.
        chains : list[int|str], optional
            A list of the chains to get a summary of.

        Returns
        -------
        list of dictionaries
            One entry per chain, parameter bounds stored in dictionary with parameter as key
        """
        results = []
        if chains is None:
            chains = self.parent.chains
        else:
            if isinstance(chains, (int, str)):
                chains = [chains]
            chains = [self.parent.chains[i] for c in chains for i in self.parent._get_chain(c)]

        for chain in chains:
            res = {}
            params_to_find = parameters if parameters is not None else chain.parameters
            for p in params_to_find:
                if p not in chain.parameters:
                    continue
                summary = self.get_parameter_summary(chain, p)
                res[p] = summary
            results.append(res)
        if squeeze and len(results) == 1:
            return results[0]
        return results


Instruction:
Write a Python 3 function for
getting the maximum posterior point in parameter space from the passed parameters.

Response:
def get_max_posteriors(self, parameters=None, squeeze=True, chains=None):
        """  Gets the maximum posterior point in parameter space from the passed parameters.

        Requires the chains to have set `posterior` values.

        Parameters
        ----------
        parameters : str|list[str]
            The parameters to find
        squeeze : bool, optional
            Squeeze the summaries. If you only have one chain, squeeze will not return
            a length one list, just the single summary. If this is false, you will
            get a length one list.
        chains : list[int|str], optional
            A list of the chains to get a summary of.

        Returns
        -------
        list of two-tuples
            One entry per chain, two-tuple represents the max-likelihood coordinate
        """

        results = []
        if chains is None:
            chains = self.parent.chains
        else:
            if isinstance(chains, (int, str)):
                chains = [chains]
            chains = [self.parent.chains[i] for c in chains for i in self.parent._get_chain(c)]

        if isinstance(parameters, str):
            parameters = [parameters]

        for chain in chains:
            if chain.posterior_max_index is None:
                results.append(None)
                continue
            res = {}
            params_to_find = parameters if parameters is not None else chain.parameters
            for p in params_to_find:
                if p in chain.parameters:
                    res[p] = chain.posterior_max_params[p]
            results.append(res)

        if squeeze and len(results) == 1:
            return results[0]
        return results


Instruction:
Given the following Python 3 function, write the documentation
def get_correlations(self, chain=0, parameters=None):
        parameters, cov = self.get_covariance(chain=chain, parameters=parameters)
        diag = np.sqrt(np.diag(cov))
        divisor = diag[None, :] * diag[:, None]
        correlations = cov / divisor
        return parameters, correlations

Response: Takes a chain and returns the correlation between chain parameters and all parameters.


Instruction:
Create a Python 3 function for
taking a chain and returns the covariance between the parameters and the covariance matrix between the chain parameters.

Response:
def get_covariance(self, chain=0, parameters=None):
        """
        Takes a chain and returns the covariance between chain parameters.

        Parameters
        ----------
        chain : int|str, optional
            The chain index or name. Defaults to first chain.
        parameters : list[str], optional
            The list of parameters to compute correlations. Defaults to all parameters
            for the given chain.

        Returns
        -------
            tuple
                The first index giving a list of parameter names, the second index being the
                2D covariance matrix.
        """
        index = self.parent._get_chain(chain)
        assert len(index) == 1, "Please specify only one chain, have %d chains" % len(index)
        chain = self.parent.chains[index[0]]
        if parameters is None:
            parameters = chain.parameters

        data = chain.get_data(parameters)
        cov = np.atleast_2d(np.cov(data, aweights=chain.weights, rowvar=False))

        return parameters, cov


Instruction:
How would you explain what the following Python 3 function does
def get_correlation_table(self, chain=0, parameters=None, caption="Parameter Correlations",
                              label="tab:parameter_correlations"):
        """
        Gets a LaTeX table of parameter correlations.

        Parameters
        ----------
        chain : int|str, optional
            The chain index or name. Defaults to first chain.
        parameters : list[str], optional
            The list of parameters to compute correlations. Defaults to all parameters
            for the given chain.
        caption : str, optional
            The LaTeX table caption.
        label : str, optional
            The LaTeX table label.

        Returns
        -------
            str
                The LaTeX table ready to go!
        """
        parameters, cor = self.get_correlations(chain=chain, parameters=parameters)
        return self._get_2d_latex_table(parameters, cor, caption, label)

Response: Returns a LaTeX table of parameter correlations.


Instruction:
Write a Python 3 function for
returning a LaTeX table of parameter covariance.

Response:
def get_covariance_table(self, chain=0, parameters=None, caption="Parameter Covariance",
                              label="tab:parameter_covariance"):
        """
        Gets a LaTeX table of parameter covariance.

        Parameters
        ----------
        chain : int|str, optional
            The chain index or name. Defaults to first chain.
        parameters : list[str], optional
            The list of parameters to compute correlations. Defaults to all parameters
            for the given chain.
        caption : str, optional
            The LaTeX table caption.
        label : str, optional
            The LaTeX table label.

        Returns
        -------
            str
                The LaTeX table ready to go!
        """
        parameters, cov = self.get_covariance(chain=chain, parameters=parameters)
        return self._get_2d_latex_table(parameters, cov, caption, label)


Instruction:
Create a Python 3 function for
generating LaTeX appropriate text given the marginalised parameter bounds.

Response:
def get_parameter_text(self, lower, maximum, upper, wrap=False):
        """ Generates LaTeX appropriate text from marginalised parameter bounds.

        Parameters
        ----------
        lower : float
            The lower bound on the parameter
        maximum : float
            The value of the parameter with maximum probability
        upper : float
            The upper bound on the parameter
        wrap : bool
            Wrap output text in dollar signs for LaTeX

        Returns
        -------
        str
            The formatted text given the parameter bounds
        """
        if lower is None or upper is None:
            return ""
        upper_error = upper - maximum
        lower_error = maximum - lower
        if upper_error != 0 and lower_error != 0:
            resolution = min(np.floor(np.log10(np.abs(upper_error))),
                            np.floor(np.log10(np.abs(lower_error))))
        elif upper_error == 0 and lower_error != 0:
            resolution = np.floor(np.log10(np.abs(lower_error)))
        elif upper_error != 0 and lower_error == 0:
            resolution = np.floor(np.log10(np.abs(upper_error)))
        else:
            resolution = np.floor(np.log10(np.abs(maximum)))
        factor = 0
        fmt = "%0.1f"
        r = 1
        if np.abs(resolution) > 2:
            factor = -resolution
        if resolution == 2:
            fmt = "%0.0f"
            factor = -1
            r = 0
        if resolution == 1:
            fmt = "%0.0f"
        if resolution == -1:
            fmt = "%0.2f"
            r = 2
        elif resolution == -2:
            fmt = "%0.3f"
            r = 3
        upper_error *= 10 ** factor
        lower_error *= 10 ** factor
        maximum *= 10 ** factor
        upper_error = round(upper_error, r)
        lower_error = round(lower_error, r)
        maximum = round(maximum, r)
        if maximum == -0.0:
            maximum = 0.0
        if resolution == 2:
            upper_error *= 10 ** -factor
            lower_error *= 10 ** -factor
            maximum *= 10 ** -factor
            factor = 0
            fmt = "%0.0f"
        upper_error_text = fmt % upper_error
        lower_error_text = fmt % lower_error
        if upper_error_text == lower_error_text:
            text = r"%s\pm %s" % (fmt, "%s") % (maximum, lower_error_text)
        else:
            text = r"%s^{+%s}_{-%s}" % (fmt, "%s", "%s") % \
                   (maximum, upper_error_text, lower_error_text)
        if factor != 0:
            text = r"\left( %s \right) \times 10^{%d}" % (text, -factor)
        if wrap:
            text = "$%s$" % text
        return text


Instruction:
Here you have a function in Python 3, explain what it does
def add_chain(self, chain, parameters=None, name=None, weights=None, posterior=None, walkers=None,
                  grid=False, num_eff_data_points=None, num_free_params=None, color=None, linewidth=None,
                  linestyle=None, kde=None, shade=None, shade_alpha=None, power=None, marker_style=None, marker_size=None,
                  marker_alpha=None, plot_contour=None, plot_point=None, statistics=None, cloud=None,
                  shade_gradient=None, bar_shade=None, bins=None, smooth=None, color_params=None,
                  plot_color_params=None, cmap=None, num_cloud=None):
        """
        Add a chain to the consumer.

        Parameters
        ----------
        chain : str|ndarray|dict
            The chain to load. Normally a ``numpy.ndarray``. If a string is found, it
            interprets the string as a filename and attempts to load it in. If a ``dict``
            is passed in, it assumes the dict has keys of parameter names and values of
            an array of samples. Notice that using a dictionary puts the order of
            parameters in the output under the control of the python ``dict.keys()`` function.
            If you passed ``grid`` is set, you can pass in the parameter ranges in list form.
        parameters : list[str], optional
            A list of parameter names, one for each column (dimension) in the chain. This parameter
            should remain ``None`` if a dictionary is given as ``chain``, as the parameter names
            are taken from the dictionary keys.
        name : str, optional
            The name of the chain. Used when plotting multiple chains at once.
        weights : ndarray, optional
            If given, uses this array to weight the samples in chain
        posterior : ndarray, optional
            If given, records the log posterior for each sample in the chain
        walkers : int, optional
            How many walkers went into creating the chain. Each walker should
            contribute the same number of steps, and should appear in contiguous
            blocks in the final chain.
        grid : boolean, optional
            Whether the input is a flattened chain from a grid search instead of a Monte-Carlo
            chains. Note that when this is set, `walkers` should not be set, and `weights` should
            be set to the posterior evaluation for the grid point. **Be careful** when using
            a coarse grid of setting a high smoothing value, as this may oversmooth the posterior
            surface and give unreasonably large parameter bounds.
        num_eff_data_points : int|float, optional
            The number of effective (independent) data points used in the model fitting. Not required
            for plotting, but required if loading in multiple chains to perform model comparison.
        num_free_params : int, optional
            The number of degrees of freedom in your model. Not required for plotting, but required if
            loading in multiple chains to perform model comparison.
        color : str(hex), optional
            Provide a colour for the chain. Can be used instead of calling `configure` for convenience.
        linewidth : float, optional
            Provide a line width to plot the contours. Can be used instead of calling `configure` for convenience.
        linestyle : str, optional
            Provide a line style to plot the contour. Can be used instead of calling `configure` for convenience.
        kde : bool|float, optional
            Set the `kde` value for this specific chain. Can be used instead of calling `configure` for convenience.
        shade : booloptional
            If set, overrides the default behaviour and plots filled contours or not. If a list of
            bools is passed, you can turn shading on or off for specific chains.
        shade_alpha : float, optional
            Filled contour alpha value. Can be used instead of calling `configure` for convenience.
        power : float, optional
            The power to raise the posterior surface to. Useful for inflating or deflating uncertainty for debugging.
        marker_style : str|, optional
            The marker style to use when plotting points. Defaults to `'.'`
        marker_size : numeric|, optional
            Size of markers, if plotted. Defaults to `4`.
        marker_alpha : numeric, optional
            The alpha values when plotting markers.
        plot_contour : bool, optional
            Whether to plot the whole contour (as opposed to a point). Defaults to true for less than
            25 concurrent chains.
        plot_point : bool, optional
            Whether to plot a maximum likelihood point. Defaults to true for more then 24 chains.
        statistics : string, optional
            Which sort of statistics to use. Defaults to `"max"` for maximum likelihood
            statistics. Other available options are `"mean"`, `"cumulative"`, `"max_symmetric"`,
            `"max_closest"` and `"max_central"`. In the
            very, very rare case you want to enable different statistics for different
            chains, you can pass in a list of strings.
        cloud : bool, optional
            If set, overrides the default behaviour and plots the cloud or not        shade_gradient :
        bar_shade : bool, optional
            If set to true, shades in confidence regions in under histogram. By default
            this happens if you less than 3 chains, but is disabled if you are comparing
            more chains. You can pass a list if you wish to shade some chains but not others.
        bins : int|float, optional
            The number of bins to use. By default uses :math:`\frac{\sqrt{n}}{10}`, where
            :math:`n` are the number of data points. Giving an integer will set the number
            of bins to the given value. Giving a float will scale the number of bins, such
            that giving ``bins=1.5`` will result in using :math:`\frac{1.5\sqrt{n}}{10}` bins.
            Note this parameter is most useful if `kde=False` is also passed, so you
            can actually see the bins and not a KDE.        smooth :
        color_params : str, optional
            The name of the parameter to use for the colour scatter. Defaults to none, for no colour. If set
            to 'weights', 'log_weights', or 'posterior' (without the quotes), and that is not a parameter in the chain,
            it will respectively  use the weights, log weights, or posterior, to colour the points.
        plot_color_params : bool, optional
            Whether or not the colour parameter should also be plotted as a posterior surface.
        cmaps : str, optional
            The matplotlib colourmap to use in the `colour_param`. If you have multiple `color_param`s, you can
            specific a different cmap for each variable. By default ChainConsumer will cycle between several
            cmaps.
        num_cloud : int, optional
            The number of scatter points to show when enabling `cloud` or setting one of the parameters
            to colour scatter. Defaults to 15k per chain.

        Returns
        -------
        ChainConsumer
            Itself, to allow chaining calls.
        """
        is_dict = False
        assert chain is not None, "You cannot have a chain of None"
        if isinstance(chain, str):
            if chain.endswith("txt"):
                chain = np.loadtxt(chain)
            else:
                chain = np.load(chain)
        elif isinstance(chain, dict):
            assert parameters is None, \
                "You cannot pass a dictionary and specify parameter names"
            is_dict = True
            parameters = list(chain.keys())
            chain = np.array([chain[p] for p in parameters]).T
        elif isinstance(chain, list):
            chain = np.array(chain).T

        if grid:
            assert walkers is None, "If grid is set, walkers should not be"
            assert weights is not None, "If grid is set, you need to supply weights"
            if len(weights.shape) > 1:
                assert not is_dict, "We cannot construct a meshgrid from a dictionary, as the parameters" \
                                    "are no longer ordered. Please pass in a flattened array instead."
                self._logger.info("Constructing meshgrid for grid results")
                meshes = np.meshgrid(*[u for u in chain.T], indexing="ij")
                chain = np.vstack([m.flatten() for m in meshes]).T
                weights = weights.flatten()
                assert weights.size == chain[:,
                                       0].size, "Error, given weight array size disagrees with parameter sampling"

        if len(chain.shape) == 1:
            chain = chain[None].T

        if name is None:
            name = "Chain %d" % len(self.chains)

        if power is not None:
            assert isinstance(power, int) or isinstance(power, float), "Power should be numeric, but is %s" % type(
                power)

        if self._default_parameters is None and parameters is not None:
            self._default_parameters = parameters

        if parameters is None:
            if self._default_parameters is not None:
                assert chain.shape[1] == len(self._default_parameters), \
                    "Chain has %d dimensions, but default parameters have %d dimensions" \
                    % (chain.shape[1], len(self._default_parameters))
                parameters = self._default_parameters
                self._logger.debug("Adding chain using default parameters")
            else:
                self._logger.debug("Adding chain with no parameter names")
                parameters = ["%d" % x for x in range(chain.shape[1])]
        else:
            self._logger.debug("Adding chain with defined parameters")
            assert len(parameters) <= chain.shape[1], \
                "Have only %d columns in chain, but have been given %d parameters names! " \
                "Please double check this." % (chain.shape[1], len(parameters))
        for p in parameters:
            if p not in self._all_parameters:
                self._all_parameters.append(p)

        # Sorry, no KDE for you on a grid.
        if grid:
            kde = None
        if color is not None:
            color = self.color_finder.get_formatted([color])[0]

        c = Chain(chain, parameters, name, weights=weights, posterior=posterior, walkers=walkers,
                  grid=grid, num_free_params=num_free_params, num_eff_data_points=num_eff_data_points,
                  color=color, linewidth=linewidth, linestyle=linestyle, kde=kde, shade_alpha=shade_alpha, power=power,
                  marker_style=marker_style, marker_size=marker_size, marker_alpha=marker_alpha,
                  plot_contour=plot_contour, plot_point=plot_point, statistics=statistics, cloud=cloud,
                  shade=shade, shade_gradient=shade_gradient, bar_shade=bar_shade, bins=bins, smooth=smooth,
                  color_params=color_params, plot_color_params=plot_color_params, cmap=cmap,
                  num_cloud=num_cloud)
        self.chains.append(c)
        self._init_params()
        return self

Response: This function adds a new chain to the consumer.


Instruction:
Can you write a function in Python 3 where it
removes a chain from the ChainConsumer.

Response:
def remove_chain(self, chain=-1):
        """
        Removes a chain from ChainConsumer. Calling this will require any configurations set to be redone!

        Parameters
        ----------
        chain : int|str, list[str|int]
            The chain(s) to remove. You can pass in either the chain index, or the chain name, to remove it.
            By default removes the last chain added.

        Returns
        -------
        ChainConsumer
            Itself, to allow chaining calls.
        """
        if isinstance(chain, str) or isinstance(chain, int):
            chain = [chain]

        chain = sorted([i for c in chain for i in self._get_chain(c)])[::-1]
        assert len(chain) == len(list(set(chain))), "Error, you are trying to remove a chain more than once."

        for index in chain:
            del self.chains[index]

        seen = set()
        self._all_parameters = [p for c in self.chains for p in c.parameters if not (p in seen or seen.add(p))]

        # Need to reconfigure
        self._init_params()

        return self


Instruction:
Can you generate the documentation for the following Python 3 function
def configure(self, statistics="max", max_ticks=5, plot_hists=True, flip=True,
                  serif=True, sigma2d=False, sigmas=None, summary=None, bins=None, rainbow=None,
                  colors=None, linestyles=None, linewidths=None, kde=False, smooth=None,
                  cloud=None, shade=None, shade_alpha=None, shade_gradient=None, bar_shade=None,
                  num_cloud=None, color_params=None, plot_color_params=False, cmaps=None,
                  plot_contour=None, plot_point=None, global_point=True, marker_style=None, marker_size=None, marker_alpha=None,
                  usetex=True, diagonal_tick_labels=True, label_font_size=12, tick_font_size=10,
                  spacing=None, contour_labels=None, contour_label_font_size=10,
                  legend_kwargs=None, legend_location=None, legend_artists=None,
                  legend_color_text=True, watermark_text_kwargs=None, summary_area=0.6827):  # pragma: no cover
        r""" Configure the general plotting parameters common across the bar
        and contour plots.

        If you do not call this explicitly, the :func:`plot`
        method will invoke this method automatically.

        Please ensure that you call this method *after* adding all the relevant data to the
        chain consumer, as the consume changes configuration values depending on
        the supplied data.

        Parameters
        ----------
        statistics : string|list[str], optional
            Which sort of statistics to use. Defaults to `"max"` for maximum likelihood
            statistics. Other available options are `"mean"`, `"cumulative"`, `"max_symmetric"`,
            `"max_closest"` and `"max_central"`. In the
            very, very rare case you want to enable different statistics for different
            chains, you can pass in a list of strings.
        max_ticks : int, optional
            The maximum number of ticks to use on the plots
        plot_hists : bool, optional
            Whether to plot marginalised distributions or not
        flip : bool, optional
            Set to false if, when plotting only two parameters, you do not want it to
            rotate the histogram so that it is horizontal.
        sigma2d: bool, optional
            Defaults to `False`. When `False`, uses :math:`\sigma` levels for 1D Gaussians - ie confidence
            levels of 68% and 95%. When `True`, uses the confidence levels for 2D Gaussians, where 1 and 2
            :math:`\sigma` represents 39% and 86% confidence levels respectively.
        sigmas : np.array, optional
            The :math:`\sigma` contour levels to plot. Defaults to [0, 1, 2, 3] for a single chain
            and [0, 1, 2] for multiple chains.
        serif : bool, optional
            Whether to display ticks and labels with serif font.
        summary : bool, optional
            If overridden, sets whether parameter summaries should be set as axis titles.
            Will not work if you have multiple chains
        bins : int|float,list[int|float], optional
            The number of bins to use. By default uses :math:`\frac{\sqrt{n}}{10}`, where
            :math:`n` are the number of data points. Giving an integer will set the number
            of bins to the given value. Giving a float will scale the number of bins, such
            that giving ``bins=1.5`` will result in using :math:`\frac{1.5\sqrt{n}}{10}` bins.
            Note this parameter is most useful if `kde=False` is also passed, so you
            can actually see the bins and not a KDE.
        rainbow : bool|list[bool], optional
            Set to True to force use of rainbow colours
        colors : str(hex)|list[str(hex)], optional
            Provide a list of colours to use for each chain. If you provide more chains
            than colours, you *will* get the rainbow colour spectrum. If you only pass
            one colour, all chains are set to this colour. This probably won't look good.
        linestyles : str|list[str], optional
            Provide a list of line styles to plot the contours and marginalised
            distributions with. By default, this will become a list of solid lines. If a
            string is passed instead of a list, this style is used for all chains.
        linewidths : float|list[float], optional
            Provide a list of line widths to plot the contours and marginalised
            distributions with. By default, this is a width of 1. If a float
            is passed instead of a list, this width is used for all chains.
        kde : bool|float|list[bool|float], optional
            Whether to use a Gaussian KDE to smooth marginalised posteriors. If false, uses
            bins and linear interpolation, so ensure you have plenty of samples if your
            distribution is highly non-gaussian. Due to the slowness of performing a
            KDE on all data, it is often useful to disable this before producing final
            plots. If float, scales the width of the KDE bandpass manually.
        smooth : int|list[int], optional
            Defaults to 3. How much to smooth the marginalised distributions using a gaussian filter.
            If ``kde`` is set to true, this parameter is ignored. Setting it to either
            ``0``, ``False`` disables smoothing. For grid data, smoothing
            is set to 0 by default, not 3.
        cloud : bool|list[bool], optional
            If set, overrides the default behaviour and plots the cloud or not
        shade : bool|list[bool] optional
            If set, overrides the default behaviour and plots filled contours or not. If a list of
            bools is passed, you can turn shading on or off for specific chains.
        shade_alpha : float|list[float], optional
            Filled contour alpha value override. Default is 1.0. If a list is passed, you can set the
            shade opacity for specific chains.
        shade_gradient : float|list[float], optional
            How much to vary colours in different contour levels.
        bar_shade : bool|list[bool], optional
            If set to true, shades in confidence regions in under histogram. By default
            this happens if you less than 3 chains, but is disabled if you are comparing
            more chains. You can pass a list if you wish to shade some chains but not others.
        num_cloud : int|list[int], optional
            The number of scatter points to show when enabling `cloud` or setting one of the parameters
            to colour scatter. Defaults to 15k per chain.
        color_params : str|list[str], optional
            The name of the parameter to use for the colour scatter. Defaults to none, for no colour. If set
            to 'weights', 'log_weights', or 'posterior' (without the quotes), and that is not a parameter in the chain,
            it will respectively  use the weights, log weights, or posterior, to colour the points.
        plot_color_params : bool|list[bool], optional
            Whether or not the colour parameter should also be plotted as a posterior surface.
        cmaps : str|list[str], optional
            The matplotlib colourmap to use in the `colour_param`. If you have multiple `color_param`s, you can
            specific a different cmap for each variable. By default ChainConsumer will cycle between several
            cmaps.
        plot_contour : bool|list[bool], optional
            Whether to plot the whole contour (as opposed to a point). Defaults to true for less than
            25 concurrent chains.
        plot_point : bool|list[bool], optional
            Whether to plot a maximum likelihood point. Defaults to true for more then 24 chains.
        global_point : bool, optional
            Whether the point which gets plotted is the global posterior maximum, or the marginalised 2D
            posterior maximum. Note that when you use marginalised 2D maximums for the points, you do not
             get the 1D histograms. Defaults to `True`, for a global maximum value.
        marker_style : str|list[str], optional
            The marker style to use when plotting points. Defaults to `'.'`
        marker_size : numeric|list[numeric], optional
            Size of markers, if plotted. Defaults to `4`.
        marker_alpha : numeric|list[numeric], optional
            The alpha values when plotting markers.
        usetex : bool, optional
            Whether or not to parse text as LaTeX in plots.
        diagonal_tick_labels : bool, optional
            Whether to display tick labels on a 45 degree angle.
        label_font_size : int|float, optional
            The font size for plot axis labels and axis titles if summaries are configured to display.
        tick_font_size : int|float, optional
            The font size for the tick labels in the plots.
        spacing : float, optional
            The amount of spacing to add between plots. Defaults to `None`, which equates to 1.0 for less
            than 6 dimensions and 0.0 for higher dimensions.
        contour_labels : string, optional
            If unset do not plot contour labels. If set to "confidence", label the using confidence
            intervals. If set to "sigma", labels using sigma.
        contour_label_font_size : int|float, optional
            The font size for contour labels, if they are enabled.
        legend_kwargs : dict, optional
            Extra arguments to pass to the legend api.
        legend_location : tuple(int,int), optional
            Specifies the subplot in which to locate the legend. By default, this will be (0, -1),
            corresponding to the top right subplot if there are more than two parameters,
            and the bottom left plot for only two parameters with flip on.
            For having the legend in the primary subplot
            in the bottom left, set to (-1,0).
        legend_artists : bool, optional
            Whether to include hide artists in the legend. If all linestyles and line widths are identical,
            this will default to false (as only the colours change). Otherwise it will be true.
        legend_color_text : bool, optional
            Whether to colour the legend text.
        watermark_text_kwargs : dict, optional
            Options to pass to the fontdict property when generating text for the watermark.
        summary_area : float, optional
            The confidence interval used when generating parameter summaries. Defaults to 1 sigma, aka 0.6827

        Returns
        -------
        ChainConsumer
            Itself, to allow chaining calls.
        """
        # Dirty way of ensuring overrides happen when requested
        l = locals()
        explicit = []
        for k in l.keys():
            if l[k] is not None:
                explicit.append(k)
                if k.endswith("s"):
                    explicit.append(k[:-1])
        self._init_params()

        num_chains = len(self.chains)

        assert rainbow is None or colors is None, \
            "You cannot both ask for rainbow colours and then give explicit colours"

        # Determine statistics
        assert statistics is not None, "statistics should be a string or list of strings!"
        if isinstance(statistics, str):
            assert statistics in list(Analysis.summaries), "statistics %s not recognised. Should be in %s" % (statistics, Analysis.summaries)
            statistics = [statistics.lower()] * len(self.chains)
        elif isinstance(statistics, list):
            for i, l in enumerate(statistics):
                statistics[i] = l.lower()
        else:
            raise ValueError("statistics is not a string or a list!")

        # Determine KDEs
        if isinstance(kde, bool) or isinstance(kde, float):
            kde = [False if c.grid else kde for c in self.chains]

        kde_override = [c.kde for c in self.chains]
        kde = [c2 if c2 is not None else c1 for c1, c2 in zip(kde, kde_override)]

        # Determine bins
        if bins is None:
            bins = get_bins(self.chains)
        elif isinstance(bins, list):
            bins = [b2 if isinstance(b2, int) else np.floor(b2 * b1) for b1, b2 in zip(get_bins(self.chains), bins)]
        elif isinstance(bins, float):
            bins = [np.floor(b * bins) for b in get_bins(self.chains)]
        elif isinstance(bins, int):
            bins = [bins] * len(self.chains)
        else:
            raise ValueError("bins value is not a recognised class (float or int)")

        # Determine smoothing
        if smooth is None:
            smooth = [0 if c.grid or k else 3 for c, k in zip(self.chains, kde)]
        else:
            if smooth is not None and not smooth:
                smooth = 0
            if isinstance(smooth, list):
                smooth = [0 if k else s for s, k in zip(smooth, kde)]
            else:
                smooth = [0 if k else smooth for k in kde]

        # Determine color parameters
        if color_params is None:
            color_params = [None] * num_chains
        else:
            if isinstance(color_params, str):
                color_params = [
                    color_params if color_params in cs.parameters + ["log_weights", "weights", "posterior"] else None
                    for cs in self.chains]
                color_params = [None if c == "posterior" and self.chains[i].posterior is None else c for i, c in
                                enumerate(color_params)]
            elif isinstance(color_params, list) or isinstance(color_params, tuple):
                for c, chain in zip(color_params, self.chains):
                    p = chain.parameters
                    if c is not None:
                        assert c in p, "Color parameter %s not in parameters %s" % (c, p)
        # Determine if we should plot color parameters
        if isinstance(plot_color_params, bool):
            plot_color_params = [plot_color_params] * len(color_params)

        # Determine cmaps
        if cmaps is None:
            param_cmaps = {}
            cmaps = []
            i = 0
            for cp in color_params:
                if cp is None:
                    cmaps.append(None)
                elif cp in param_cmaps:
                    cmaps.append(param_cmaps[cp])
                else:
                    param_cmaps[cp] = self._cmaps[i]
                    cmaps.append(self._cmaps[i])
                    i = (i + 1) % len(self._cmaps)

        # Determine colours
        if colors is None:
            if rainbow:
                colors = self.color_finder.get_colormap(num_chains)
            else:
                if num_chains > len(self._all_colours):
                    num_needed_colours = np.sum([c is None for c in color_params])
                    colour_list = self.color_finder.get_colormap(num_needed_colours)
                else:
                    colour_list = self._all_colours
                colors = []
                ci = 0
                for c in color_params:
                    if c:
                        colors.append('#000000')
                    else:
                        colors.append(colour_list[ci])
                        ci += 1
        elif isinstance(colors, str):
            colors = [colors] * len(self.chains)
        colors = self.color_finder.get_formatted(colors)

        # Determine linestyles
        if linestyles is None:
            i = 0
            linestyles = []
            for c in color_params:
                if c is None:
                    linestyles.append(self._linestyles[0])
                else:
                    linestyles.append(self._linestyles[i])
                    i = (i + 1) % len(self._linestyles)
        elif isinstance(linestyles, str):
            linestyles = [linestyles] * len(self.chains)

        # Determine linewidths
        if linewidths is None:
            linewidths = [1.0] * len(self.chains)
        elif isinstance(linewidths, float) or isinstance(linewidths, int):
            linewidths = [linewidths] * len(self.chains)

        # Determine clouds
        if cloud is None:
            cloud = False
        cloud = [cloud or c is not None for c in color_params]

        # Determine cloud points
        if num_cloud is None:
            num_cloud = 30000
        if isinstance(num_cloud, int) or isinstance(num_cloud, float):
            num_cloud = [int(num_cloud)] * num_chains

        # Should we shade the contours
        if shade is None:
            if shade_alpha is None:
                shade = num_chains <= 3
            else:
                shade = True
        if isinstance(shade, bool):
            # If not overridden, do not shade chains with colour scatter points
            shade = [shade and c is None for c in color_params]

        # Modify shade alpha based on how many chains we have
        if shade_alpha is None:
            if num_chains == 1:
                if contour_labels is not None:
                    shade_alpha = 0.75
                else:
                    shade_alpha = 1.0
            else:
                shade_alpha = 1.0 / num_chains
        # Decrease the shading amount if there are colour scatter points
        if isinstance(shade_alpha, float) or isinstance(shade_alpha, int):
            shade_alpha = [shade_alpha if c is None else 0.25 * shade_alpha for c in color_params]

        if shade_gradient is None:
            shade_gradient = 1.0
        if isinstance(shade_gradient, float):
            shade_gradient = [shade_gradient] * num_chains
        elif isinstance(shade_gradient, list):
            assert len(shade_gradient) == num_chains, \
                "Have %d shade_gradient but % chains" % (len(shade_gradient), num_chains)

        contour_over_points = num_chains < 20

        if plot_contour is None:
            plot_contour = [contour_over_points if chain.posterior is not None else True for chain in self.chains]
        elif isinstance(plot_contour, bool):
            plot_contour = [plot_contour] * num_chains

        if plot_point is None:
            plot_point = [not contour_over_points] * num_chains
        elif isinstance(plot_point, bool):
            plot_point = [plot_point] * num_chains

        if marker_style is None:
            marker_style = ['.'] * num_chains
        elif isinstance(marker_style, str):
            marker_style = [marker_style] * num_chains

        if marker_size is None:
            marker_size = [4] * num_chains
        elif isinstance(marker_style, (int, float)):
            marker_size = [marker_size] * num_chains

        if marker_alpha is None:
            marker_alpha = [1.0] * num_chains
        elif isinstance(marker_alpha, (int, float)):
            marker_alpha = [marker_alpha] * num_chains

        # Figure out if we should display parameter summaries
        if summary is not None:
            summary = summary and num_chains == 1

        # Figure out bar shading
        if bar_shade is None:
            bar_shade = num_chains <= 3
        if isinstance(bar_shade, bool):
            bar_shade = [bar_shade] * num_chains

        # Figure out how many sigmas to plot
        if sigmas is None:
            if num_chains == 1:
                sigmas = np.array([0, 1, 2])
            else:
                sigmas = np.array([0, 1, 2])
        if sigmas[0] != 0:
            sigmas = np.concatenate(([0], sigmas))
        sigmas = np.sort(sigmas)

        if contour_labels is not None:
            assert isinstance(contour_labels, str), "contour_labels parameter should be a string"
            contour_labels = contour_labels.lower()
            assert contour_labels in ["sigma", "confidence"], "contour_labels should be either sigma or confidence"
        assert isinstance(contour_label_font_size, int) or isinstance(contour_label_font_size, float), \
            "contour_label_font_size needs to be numeric"

        if legend_artists is None:
            legend_artists = len(set(linestyles)) > 1 or len(set(linewidths)) > 1

        if legend_kwargs is not None:
            assert isinstance(legend_kwargs, dict), "legend_kwargs should be a dict"
        else:
            legend_kwargs = {}

        if num_chains < 3:
            labelspacing = 0.5
        elif num_chains == 3:
            labelspacing = 0.2
        else:
            labelspacing = 0.15
        legend_kwargs_default = {
            "labelspacing": labelspacing,
            "loc": "upper right",
            "frameon": False,
            "fontsize": label_font_size,
            "handlelength": 1,
            "handletextpad": 0.2,
            "borderaxespad": 0.0
        }
        legend_kwargs_default.update(legend_kwargs)

        watermark_text_kwargs_default = {
            "color": "#333333",
            "alpha": 0.7,
            "verticalalignment": "center",
            "horizontalalignment": "center"
        }
        if watermark_text_kwargs is None:
            watermark_text_kwargs = {}
        watermark_text_kwargs_default.update(watermark_text_kwargs)

        assert isinstance(summary_area, float), "summary_area needs to be a float, not %s!" % type(summary_area)
        assert summary_area > 0, "summary_area should be a positive number, instead is %s!" % summary_area
        assert summary_area < 1, "summary_area must be less than unity, instead is %s!" % summary_area
        assert isinstance(global_point, bool), "global_point should be a bool"

        # List options
        for i, c in enumerate(self.chains):
            try:
                c.update_unset_config("statistics", statistics[i], override=explicit)
                c.update_unset_config("color", colors[i], override=explicit)
                c.update_unset_config("linestyle", linestyles[i], override=explicit)
                c.update_unset_config("linewidth", linewidths[i], override=explicit)
                c.update_unset_config("cloud", cloud[i], override=explicit)
                c.update_unset_config("shade", shade[i], override=explicit)
                c.update_unset_config("shade_alpha", shade_alpha[i], override=explicit)
                c.update_unset_config("shade_gradient", shade_gradient[i], override=explicit)
                c.update_unset_config("bar_shade", bar_shade[i], override=explicit)
                c.update_unset_config("bins", bins[i], override=explicit)
                c.update_unset_config("kde", kde[i], override=explicit)
                c.update_unset_config("smooth", smooth[i], override=explicit)
                c.update_unset_config("color_params", color_params[i], override=explicit)
                c.update_unset_config("plot_color_params", plot_color_params[i], override=explicit)
                c.update_unset_config("cmap", cmaps[i], override=explicit)
                c.update_unset_config("num_cloud", num_cloud[i], override=explicit)
                c.update_unset_config("marker_style", marker_style[i], override=explicit)
                c.update_unset_config("marker_size", marker_size[i], override=explicit)
                c.update_unset_config("marker_alpha", marker_alpha[i], override=explicit)
                c.update_unset_config("plot_contour", plot_contour[i], override=explicit)
                c.update_unset_config("plot_point", plot_point[i], override=explicit)
                c.config["summary_area"] = summary_area

            except IndentationError as e:
                print("Index error when assigning chain properties, make sure you "
                      "have enough properties set for the number of chains you have loaded! "
                      "See the stack trace for which config item has the wrong number of entries.")
                raise e

        # Non list options
        self.config["sigma2d"] = sigma2d
        self.config["sigmas"] = sigmas
        self.config["summary"] = summary
        self.config["flip"] = flip
        self.config["serif"] = serif
        self.config["plot_hists"] = plot_hists
        self.config["max_ticks"] = max_ticks
        self.config["usetex"] = usetex
        self.config["diagonal_tick_labels"] = diagonal_tick_labels
        self.config["label_font_size"] = label_font_size
        self.config["tick_font_size"] = tick_font_size
        self.config["spacing"] = spacing
        self.config["contour_labels"] = contour_labels
        self.config["contour_label_font_size"] = contour_label_font_size
        self.config["legend_location"] = legend_location
        self.config["legend_kwargs"] = legend_kwargs_default
        self.config["legend_artists"] = legend_artists
        self.config["legend_color_text"] = legend_color_text
        self.config["watermark_text_kwargs"] = watermark_text_kwargs_default
        self.config["global_point"] = global_point

        self._configured = True
        return self

Response: r Configure the general plotting parameters common across all barracatic and contour plots.


Instruction:
How would you explain what the following Python 3 function does
def configure_truth(self, **kwargs):  # pragma: no cover
        if kwargs.get("ls") is None and kwargs.get("linestyle") is None:
            kwargs["ls"] = "--"
            kwargs["dashes"] = (3, 3)
        if kwargs.get("color") is None:
            kwargs["color"] = "#000000"
        self.config_truth = kwargs
        self._configured_truth = True
        return self

Response: Configure the arguments passed to the AxvLine and AxhLine methods when plotting truth values.


Instruction:
Make a summary of the following Python 3 code
def divide_chain(self, chain=0):
        indexes = self._get_chain(chain)
        con = ChainConsumer()

        for index in indexes:
            chain = self.chains[index]
            assert chain.walkers is not None, "The chain you have selected was not added with any walkers!"
            num_walkers = chain.walkers
            data = np.split(chain.chain, num_walkers)
            ws = np.split(chain.weights, num_walkers)
            for j, (c, w) in enumerate(zip(data, ws)):
                con.add_chain(c, weights=w, name="Chain %d" % j, parameters=chain.parameters)
        return con

Response: Divide a chain into several ChainConsumer instances.


Instruction:
Write a Python 3 script for
calculating motif score threshold for a given FPR.

Response:
def threshold(args):
    """Calculate motif score threshold for a given FPR."""
    if args.fpr < 0 or args.fpr > 1:
        print("Please specify a FPR between 0 and 1")
        sys.exit(1)

    motifs = read_motifs(args.pwmfile)

    s = Scanner()
    s.set_motifs(args.pwmfile)
    s.set_threshold(args.fpr, filename=args.inputfile)

    print("Motif\tScore\tCutoff")
    for motif in motifs:
        min_score = motif.pwm_min_score()
        max_score = motif.pwm_max_score()
        opt_score = s.threshold[motif.id]
        if opt_score is None:
            opt_score = motif.pwm_max_score()
        threshold = (opt_score - min_score) / (max_score - min_score)
        print("{0}\t{1}\t{2}".format(
                motif.id, opt_score, threshold))


Instruction:
Can you create a Python 3 function that
converts two arrays of values to an array of labels and array of scores.

Response:
def values_to_labels(fg_vals, bg_vals):
    """
    Convert two arrays of values to an array of labels and an array of scores.

    Parameters
    ----------
    fg_vals : array_like
        The list of values for the positive set.

    bg_vals : array_like
        The list of values for the negative set.

    Returns
    -------
    y_true : array
        Labels.
    y_score : array
        Values.
    """
    y_true = np.hstack((np.ones(len(fg_vals)), np.zeros(len(bg_vals))))
    y_score = np.hstack((fg_vals, bg_vals))

    return y_true, y_score


Instruction:
Implement a Python 3 function for
computing the recall at a specific FDR.

Response:
def recall_at_fdr(fg_vals, bg_vals, fdr_cutoff=0.1):
    """
    Computes the recall at a specific FDR (default 10%).

    Parameters
    ----------
    fg_vals : array_like
        The list of values for the positive set.

    bg_vals : array_like
        The list of values for the negative set.

    fdr : float, optional
        The FDR (between 0.0 and 1.0).

    Returns
    -------
    recall : float
        The recall at the specified FDR.
    """
    if len(fg_vals) == 0:
        return 0.0

    y_true, y_score = values_to_labels(fg_vals, bg_vals)

    precision, recall, _ = precision_recall_curve(y_true, y_score)
    fdr = 1 - precision
    cutoff_index = next(i for i, x in enumerate(fdr) if x <= fdr_cutoff)
    return recall[cutoff_index]


Instruction:
Here you have a function in Python 3, explain what it does
def matches_at_fpr(fg_vals, bg_vals, fpr=0.01):
    fg_vals = np.array(fg_vals)
    s = scoreatpercentile(bg_vals, 100 - fpr * 100)

    return [sum(fg_vals >= s), sum(bg_vals >= s)]

Response: Computes the hypergeometric p - value at a specific FPR.


Instruction:
Here you have a function in Python 3, explain what it does
def phyper_at_fpr(fg_vals, bg_vals, fpr=0.01):
    fg_vals = np.array(fg_vals)
    s = scoreatpercentile(bg_vals, 100 - fpr * 100)

    table = [
            [sum(fg_vals >= s), sum(bg_vals >= s)],
            [sum(fg_vals < s), sum(bg_vals < s)],
            ]

    return fisher_exact(table, alternative="greater")[1]

Response: Computes the hypergeometric p - value at a specific FPR.


Instruction:
Can you write a function in Python 3 where it
computes the fraction positives at a specific FPR.

Response:
def fraction_fpr(fg_vals, bg_vals, fpr=0.01):
    """
    Computes the fraction positives at a specific FPR (default 1%).

    Parameters
    ----------
    fg_vals : array_like
        The list of values for the positive set.

    bg_vals : array_like
        The list of values for the negative set.

    fpr : float, optional
        The FPR (between 0.0 and 1.0).

    Returns
    -------
    fraction : float
        The fraction positives at the specified FPR.
    """
    fg_vals = np.array(fg_vals)
    s = scoreatpercentile(bg_vals, 100 - 100 * fpr)
    return len(fg_vals[fg_vals >= s]) / float(len(fg_vals))


Instruction:
Write a Python 3 script to
return the motif score at a specific FPR.

Response:
def score_at_fpr(fg_vals, bg_vals, fpr=0.01):
    """
    Returns the motif score at a specific FPR (default 1%).

    Parameters
    ----------
    fg_vals : array_like
        The list of values for the positive set.

    bg_vals : array_like
        The list of values for the negative set.

    fpr : float, optional
        The FPR (between 0.0 and 1.0).

    Returns
    -------
    score : float
        The motif score at the specified FPR.
    """
    bg_vals = np.array(bg_vals)
    return scoreatpercentile(bg_vals, 100 - 100 * fpr)


Instruction:
Make a summary of the following Python 3 code
def enr_at_fpr(fg_vals, bg_vals, fpr=0.01):
    pos = np.array(fg_vals)
    neg = np.array(bg_vals)
    s = scoreatpercentile(neg, 100 - fpr * 100)
    neg_matches = float(len(neg[neg >= s]))
    if neg_matches == 0:
        return float("inf")
    return len(pos[pos >= s]) / neg_matches * len(neg) / float(len(pos))

Response: Computes the enrichment at a specific FPR.


Instruction:
How would you explain what the following Python 3 function does
def max_enrichment(fg_vals, bg_vals, minbg=2):
    scores = np.hstack((fg_vals, bg_vals))
    idx = np.argsort(scores)
    x = np.hstack((np.ones(len(fg_vals)), np.zeros(len(bg_vals))))
    xsort = x[idx]
    l_fg = len(fg_vals)
    l_bg = len(bg_vals)
    m = 0
    s = 0
    for i in range(len(scores), 0, -1):
        bgcount = float(len(xsort[i:][xsort[i:] == 0]))
        if bgcount >= minbg:
            enr = (len(xsort[i:][xsort[i:] == 1]) / l_fg) / (bgcount / l_bg)
            if enr > m:
                m = enr
                s = scores[idx[i]]
    return m

Response: Computes the maximum enrichment of a single set of values.


Instruction:
Write a Python 3 function for
computing the Mean Normalized Conditional Probability of a set of positive and negative sets.

Response:
def mncp(fg_vals, bg_vals):
    """
    Computes the Mean Normalized Conditional Probability (MNCP).

    MNCP is described in Clarke & Granek, Bioinformatics, 2003.

    Parameters
    ----------
    fg_vals : array_like
        The list of values for the positive set.

    bg_vals : array_like
        The list of values for the negative set.

    Returns
    -------
    score : float
        MNCP score
    """
    fg_len = len(fg_vals)
    total_len = len(fg_vals) + len(bg_vals)

    if not isinstance(fg_vals, np.ndarray):
        fg_vals = np.array(fg_vals)
    if not isinstance(bg_vals, np.ndarray):
        bg_vals = np.array(bg_vals)

    fg_rank = stats.rankdata(fg_vals)
    total_rank = stats.rankdata(np.hstack((fg_vals, bg_vals)))

    slopes = []
    for i in range(len(fg_vals)):
        slope = ((fg_len - fg_rank[i] + 1) / fg_len ) / (
                (total_len - total_rank[i] + 1)/ total_len)
        slopes.append(slope)

    return np.mean(slopes)


Instruction:
Can you create a Python 3 function that
computes the Precision - Recall Area Under Curve of a node.

Response:
def pr_auc(fg_vals, bg_vals):
    """
    Computes the Precision-Recall Area Under Curve (PR AUC)

    Parameters
    ----------
    fg_vals : array_like
        list of values for positive set

    bg_vals : array_like
        list of values for negative set

    Returns
    -------
    score : float
        PR AUC score
    """
    # Create y_labels
    y_true, y_score = values_to_labels(fg_vals, bg_vals)

    return average_precision_score(y_true, y_score)


Instruction:
Can you create a Python 3 function that
computes the ROC Area Under Curve ROC AUC score for a single node.

Response:
def roc_auc(fg_vals, bg_vals):
    """
    Computes the ROC Area Under Curve (ROC AUC)

    Parameters
    ----------
    fg_vals : array_like
        list of values for positive set

    bg_vals : array_like
        list of values for negative set

    Returns
    -------
    score : float
        ROC AUC score
    """
    # Create y_labels
    y_true, y_score = values_to_labels(fg_vals, bg_vals)

    return roc_auc_score(y_true, y_score)


Instruction:
Write a Python 3 script for
computing the ROC Area Under Curve until a certain FPR value.

Response:
def roc_auc_xlim(x_bla, y_bla, xlim=0.1):
    """
    Computes the ROC Area Under Curve until a certain FPR value.

    Parameters
    ----------
    fg_vals : array_like
        list of values for positive set

    bg_vals : array_like
        list of values for negative set

    xlim : float, optional
        FPR value

    Returns
    -------
    score : float
        ROC AUC score
    """
    x = x_bla[:]
    y = y_bla[:]

    x.sort()
    y.sort()

    u = {}
    for i in x + y:
        u[i] = 1

    vals = sorted(u.keys())

    len_x = float(len(x))
    len_y = float(len(y))

    new_x = []
    new_y = []

    x_p = 0
    y_p = 0
    for val in vals[::-1]:
        while len(x) > 0 and x[-1] >= val:
            x.pop()
            x_p += 1
        while len(y) > 0 and y[-1] >= val:
            y.pop()
            y_p += 1
        new_y.append((len_x - x_p) / len_x)
        new_x.append((len_y - y_p) / len_y)

    #print new_x
    #print new_y
    new_x = 1 - np.array(new_x)
    new_y = 1 - np.array(new_y)
    #plot(new_x, new_y)
    #show()

    x = new_x
    y = new_y

    if len(x) != len(y):
        raise ValueError("Unequal!")

    if not xlim:
        xlim = 1.0

    auc = 0.0
    bla = zip(stats.rankdata(x), range(len(x)))
    bla = sorted(bla, key=lambda x: x[1])

    prev_x = x[bla[0][1]]
    prev_y = y[bla[0][1]]
    index = 1

    while index < len(bla) and x[bla[index][1]] <= xlim:

        _, i = bla[index]

        auc += y[i] * (x[i] - prev_x) - ((x[i] - prev_x) * (y[i] - prev_y) / 2.0)
        prev_x = x[i]
        prev_y = y[i]
        index += 1

    if index < len(bla):
        (rank, i) = bla[index]
        auc += prev_y * (xlim - prev_x) + ((y[i] - prev_y)/(x[i] - prev_x) * (xlim -prev_x) * (xlim - prev_x)/2)

    return auc


Instruction:
Can you tell what is the following Python 3 function doing
def roc_values(fg_vals, bg_vals):
    if len(fg_vals) == 0:
        return 0

    y_true, y_score = values_to_labels(fg_vals, bg_vals)

    fpr, tpr, _thresholds = roc_curve(y_true, y_score)

    return fpr, tpr

Response: Returns fpr and tpr of the ROC curve.


Instruction:
Can you generate the documentation for the following Python 3 function
def max_fmeasure(fg_vals, bg_vals):
    x, y = roc_values(fg_vals, bg_vals)
    x, y = x[1:], y[1:] # don't include origin

    p = y / (y + x)
    filt = np.logical_and((p * y) > 0, (p + y) > 0)
    p = p[filt]
    y = y[filt]

    f = (2 * p * y) / (p + y)
    if len(f) > 0:
        #return np.nanmax(f), np.nanmax(y[f == np.nanmax(f)])
        return np.nanmax(f)
    else:
        return None

Response: Computes the maximum F - measure.


Instruction:
Can you create a Python 3 function that
computes the Kolmogorov - Smirnov p - value of position distribution.

Response:
def ks_pvalue(fg_pos, bg_pos=None):
    """
    Computes the Kolmogorov-Smirnov p-value of position distribution.

    Parameters
    ----------
    fg_pos : array_like
        The list of values for the positive set.

    bg_pos : array_like, optional
        The list of values for the negative set.

    Returns
    -------
    p : float
        KS p-value.
    """
    if len(fg_pos) == 0:
        return 1.0
    a = np.array(fg_pos, dtype="float") / max(fg_pos)
    p = kstest(a, "uniform")[1]
    return p


Instruction:
Here you have a function in Python 3, explain what it does
def ks_significance(fg_pos, bg_pos=None):
    p = ks_pvalue(fg_pos, max(fg_pos))
    if p > 0:
        return -np.log10(p)
    else:
        return np.inf

Response: Computes the log10 of Kolmogorov - Smirnov p - value of position distribution.