예제 #1
0
def do_tango_write_attr(device,
                        name,
                        write_attr_cmd_string,
                        new_value,
                        quality,
                        timeout,
                        parent_proxy=None):
    with gevent.Timeout(timeout):
        # get attribute cfg to have attr. type and dims
        try:
            attr_cfg = device.get_attribute_config([name])[0]
        except:
            if parent_proxy:
                parent_proxy.connect()
                device = parent_proxy._device
                return do_tango_write_attr(device, name, write_attr_cmd_string,
                                           new_value, quality, timeout)

        write_attr_cmd = getattr(device, write_attr_cmd_string)

        try:
            # weird: even for single values, the data type has to be an array!!!
            write_attr_cmd([
                Tango.AttributeValue(
                    python2any(new_value,
                               attr_cfg.data_type,
                               force_array=True,
                               attr=True), quality,
                    Tango.TimeVal(int(time.time()), 0, 0), name,
                    attr_cfg.max_dim_x, attr_cfg.max_dim_y)
            ])
        except Tango.MultiDevFailed, e:
            raise RuntimeError(e.errors[0].err_list[0].desc)
        except Tango.DevFailed, e:
            raise RuntimeError(e.errors[0].desc)
예제 #2
0
def shadow(x, y, **kwargs):
    #color palette
    light1 = Tango.colors('lightBlue')
    dark1 = Tango.colors('darkBlue')

    #args
    expected_kwargs = ('linewidth', 'axis_lim', 'figsize', 'ref', 'data',
                       'fontsize', 'capthick', 'subplot')
    default_values = (3, (0, 10, -2, 2), (24, 9), None, None, 22, 6)
    linewidth, axis_lim, figsize, ref, data, fontsize, capthick = get_from_kwargs(
        expected_kwargs, default_values, kwargs)

    #fig
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(1, 1, 1)

    ymean = np.mean(y, axis=0)
    plt.plot(x, ymean, color=dark1, linewidth=linewidth)

    for yi in y:
        plt.plot(x, yi, color=light1, linewidth=linewidth - 2)

    ax.set_xlabel('Time step', fontsize=fontsize, fontweight='bold')
    ax.set_ylabel('Error[m]', fontsize=fontsize, fontweight='bold')
    ax.axis(axis_lim)
    ax.yaxis.grid(True)

    plt.legend(loc=1, ncol=3)  #, mode="expand", borderaxespad=0.)
예제 #3
0
def plot_ARD(kernel, fignum=None, ax=None, title='', legend=False, filtering=None):
    """
    If an ARD kernel is present, plot a bar representation using matplotlib

    :param fignum: figure number of the plot
    :param ax: matplotlib axis to plot on
    :param title:
        title of the plot,
        pass '' to not print a title
        pass None for a generic title
    :param filtering: list of names, which to use for plotting ARD parameters.
                      Only kernels which match names in the list of names in filtering
                      will be used for plotting.
    :type filtering: list of names to use for ARD plot
    """
    fig, ax = ax_default(fignum,ax)

    if title is None:
        ax.set_title('ARD parameters, %s kernel' % kernel.name)
    else:
        ax.set_title(title)

    Tango.reset()
    bars = []

    ard_params = np.atleast_2d(kernel.input_sensitivity(summarize=False))
    bottom = 0
    last_bottom = bottom

    x = np.arange(kernel.input_dim)

    if filtering is None:
        filtering = kernel.parameter_names(recursive=False)

    for i in range(ard_params.shape[0]):
        if kernel.parameters[i].name in filtering:
            c = Tango.nextMedium()
            bars.append(plot_bars(fig, ax, x, ard_params[i,:], c, kernel.parameters[i].name, bottom=bottom))
            last_bottom = ard_params[i,:]
            bottom += last_bottom
        else:
            print "filtering out {}".format(kernel.parameters[i].name)

    ax.set_xlim(-.5, kernel.input_dim - .5)
    add_bar_labels(fig, ax, [bars[-1]], bottom=bottom-last_bottom)

    if legend:
        if title is '':
            mode = 'expand'
            if len(bars) > 1:
                mode = 'expand'
            ax.legend(bbox_to_anchor=(0., 1.02, 1., 1.02), loc=3,
                      ncol=len(bars), mode=mode, borderaxespad=0.)
            fig.tight_layout(rect=(0, 0, 1, .9))
        else:
            ax.legend()
    return ax
예제 #4
0
def plot_ARD(kernel, fignum=None, ax=None, title='', legend=False, filtering=None):
    """
    If an ARD kernel is present, plot a bar representation using matplotlib

    :param fignum: figure number of the plot
    :param ax: matplotlib axis to plot on
    :param title:
        title of the plot,
        pass '' to not print a title
        pass None for a generic title
    :param filtering: list of names, which to use for plotting ARD parameters.
                      Only kernels which match names in the list of names in filtering
                      will be used for plotting.
    :type filtering: list of names to use for ARD plot
    """
    fig, ax = ax_default(fignum,ax)

    if title is None:
        ax.set_title('ARD parameters, %s kernel' % kernel.name)
    else:
        ax.set_title(title)

    Tango.reset()
    bars = []

    ard_params = np.atleast_2d(kernel.input_sensitivity(summarize=False))
    bottom = 0
    last_bottom = bottom

    x = np.arange(kernel.input_dim)

    if filtering is None:
        filtering = kernel.parameter_names(recursive=False)

    for i in range(ard_params.shape[0]):
        if kernel.parameters[i].name in filtering:
            c = Tango.nextMedium()
            bars.append(plot_bars(fig, ax, x, ard_params[i,:], c, kernel.parameters[i].name, bottom=bottom))
            last_bottom = ard_params[i,:]
            bottom += last_bottom
        else:
            print("filtering out {}".format(kernel.parameters[i].name))

    ax.set_xlim(-.5, kernel.input_dim - .5)
    add_bar_labels(fig, ax, [bars[-1]], bottom=bottom-last_bottom)

    if legend:
        if title is '':
            mode = 'expand'
            if len(bars) > 1:
                mode = 'expand'
            ax.legend(bbox_to_anchor=(0., 1.02, 1., 1.02), loc=3,
                      ncol=len(bars), mode=mode, borderaxespad=0.)
            fig.tight_layout(rect=(0, 0, 1, .9))
        else:
            ax.legend()
    return ax
예제 #5
0
def errorbar(x, y, yvar, **kwargs):
    #args
    x = x.copy().flatten()
    y = y.copy().flatten()
    yvar = yvar.copy().flatten()
    expected_kwargs = ('linewidth', 'axis_lim', 'figsize', 'x_ref', 'y_ref',
                       'yvar_ref', 'fontsize', 'capthick', 'xlabel', 'ylabel')
    default_values = (3, (0, 10, -2, 2), (24, 9), None, None, None, 22, 6, 'x',
                      'z')
    linewidth, axis_lim, figsize, x_ref, y_ref, yvar_ref, fontsize, capthick = get_from_kwargs(
        expected_kwargs, default_values, kwargs)

    light = Tango.colors('lightPurple')
    dark = Tango.colors('darkPurple')

    #fig
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(1, 1, 1)

    if (x_ref is not None) and (y_ref is not None) and (yvar_ref is not None):
        y_ref_upper = y_ref + 2 * (yvar_ref**0.5)
        y_ref_lower = y_ref - 2 * (yvar_ref**0.5)

        refz, = plt.plot(x_ref,
                         y_ref,
                         '--k',
                         linewidth=linewidth,
                         label='Reference function')
        refz2, = plt.plot(x_ref,
                          y_ref_upper,
                          ':k',
                          linewidth=linewidth,
                          label='Reference confidence interval')
        plt.plot(x_ref, y_ref_lower, ':k', linewidth=linewidth)

    plt.errorbar(x,
                 y,
                 yerr=2 * (yvar**0.5),
                 fmt='o',
                 ecolor=light,
                 capthick=capthick,
                 elinewidth=linewidth,
                 label='Training data',
                 mfc=light,
                 mec=dark,
                 marker='s',
                 ms=3 * linewidth,
                 mew=linewidth)
    ax.set_xlabel(xlabel, fontsize=fontsize, fontweight='bold')
    ax.set_ylabel(ylabel, fontsize=fontsize, fontweight='bold')
    if axis_lim is not None:
        ax.axis(axis_lim)
    ax.yaxis.grid(True)

    plt.legend(loc=1, ncol=3)  #, mode="expand", borderaxespad=0.)
예제 #6
0
def plot_steepest_gradient_map(model, fignum=None, ax=None, which_indices=None, labels=None, data_labels=None, data_marker='o', data_s=40, resolution=20, aspect='auto', updates=False, ** kwargs):

    input_1, input_2 = significant_dims = most_significant_input_dimensions(model, which_indices)

    X = np.zeros((resolution ** 2, model.input_dim))
    indices = np.r_[:X.shape[0]]
    if labels is None:
        labels = range(model.output_dim)

    def plot_function(x):
        X[:, significant_dims] = x
        dmu_dX = model.dmu_dXnew(X)
        argmax = np.argmax(dmu_dX, 1)
        return dmu_dX[indices, argmax], np.array(labels)[argmax]

    if ax is None:
        fig = pb.figure(num=fignum)
        ax = fig.add_subplot(111)

    if data_labels is None:
        data_labels = np.ones(model.num_data)
    ulabels = []
    for lab in data_labels:
        if not lab in ulabels:
            ulabels.append(lab)
    marker = itertools.cycle(list(data_marker))
    for i, ul in enumerate(ulabels):
        if type(ul) is np.string_:
            this_label = ul
        elif type(ul) is np.int64:
            this_label = 'class %i' % ul
        else:
            this_label = 'class %i' % i
        m = marker.next()
        index = np.nonzero(data_labels == ul)[0]
        x = X[index, input_1]
        y = X[index, input_2]
        ax.scatter(x, y, marker=m, s=data_s, color=Tango.nextMedium(), label=this_label)

    ax.set_xlabel('latent dimension %i' % input_1)
    ax.set_ylabel('latent dimension %i' % input_2)

    controller = ImAnnotateController(ax,
                                  plot_function,
                                  tuple(X.min(0)[:, significant_dims]) + tuple(X.max(0)[:, significant_dims]),
                                  resolution=resolution,
                                  aspect=aspect,
                                  cmap=get_cmap('jet'),
                                  **kwargs)
    ax.legend()
    ax.figure.tight_layout()
    if updates:
        pb.show()
        clear = raw_input('Enter to continue')
        if clear.lower() in 'yes' or clear == '':
            controller.deactivate()
    return controller.view
예제 #7
0
    def __init__(self):
        """
        The constructor builds the first menu to select the dance type.
        Various strings to support the menu system are also created
        """

        # the current_state variable holds which menu is being displayed
        self.current_state = MenuState.SELECT_DANCE
        self.dance_menu = []
        self.dance_menu.append(Waltz.Waltz())
        self.dance_menu.append(Tango.Tango())
        self.dance_menu.append(Foxtrot.Foxtrot())
        self.dance_menu.append(ChaCha.ChaCha())
        self.dance_menu.append(Rumba.Rumba())
        self.dance_menu.append(EastCoastSwing.East_Coast_Swing())
        # more dances go here

        # the current_dance variable holds which dance was selected
        self.current_dance = None

        self.dance_prompt = arcade.create_text("SELECT A DANCE",
                                               arcade.color.BLACK,
                                               24,
                                               bold=True)
        self.song_prompt = arcade.create_text("Select a song",
                                              arcade.color.BLACK,
                                              14,
                                              bold=True,
                                              italic=True)
        self.routine_prompt = arcade.create_text("Create a routine",
                                                 arcade.color.BLACK,
                                                 14,
                                                 bold=True,
                                                 italic=True)
        self.avail_prompt = arcade.create_text("Available Figures",
                                               arcade.color.BLACK,
                                               14,
                                               bold=True,
                                               italic=True)
        self.current_prompt = arcade.create_text("Currently Dancing",
                                                 arcade.color.BLACK,
                                                 14,
                                                 bold=True,
                                                 italic=True)
        self.done_prompt = arcade.create_text("0: Stop adding figures",
                                              arcade.color.BLACK, 14)
        self.silent_prompt = arcade.create_text("0: No music",
                                                arcade.color.BLACK, 14)
        self.start_prompt = arcade.create_text("Press space bar to start",
                                               arcade.color.BLACK, 14)
        self.customize_prompt = arcade.create_text("Customize Figure",
                                                   arcade.color.BLACK,
                                                   14,
                                                   bold=True,
                                                   italic=True)
예제 #8
0
def plot_latent(model, labels=None, which_indices=None,
                resolution=50, ax=None, marker='o', s=40,
                fignum=None, plot_inducing=False, legend=True,
                plot_limits=None,
                aspect='auto', updates=False, predict_kwargs={}, imshow_kwargs={}):
    """
    :param labels: a np.array of size model.num_data containing labels for the points (can be number, strings, etc)
    :param resolution: the resolution of the grid on which to evaluate the predictive variance
    """
    if ax is None:
        fig = pb.figure(num=fignum)
        ax = fig.add_subplot(111)
    else:
        fig = ax.figure
    Tango.reset()

    if labels is None:
        labels = np.ones(model.num_data)

    input_1, input_2 = most_significant_input_dimensions(model, which_indices)

    #fethch the data points X that we'd like to plot
    X = model.X
    if isinstance(X, VariationalPosterior):
        X = X.mean
    else:
        X = X


    if X.shape[0] > 1000:
        print("Warning: subsampling X, as it has more samples then 1000. X.shape={!s}".format(X.shape))
        subsample = np.random.choice(X.shape[0], size=1000, replace=False)
        X = X[subsample]
        labels = labels[subsample]
        #=======================================================================
        #     <<<WORK IN PROGRESS>>>
        #     <<<DO NOT DELETE>>>
        #     plt.close('all')
        #     fig, ax = plt.subplots(1,1)
        #     from GPy.plotting.matplot_dep.dim_reduction_plots import most_significant_input_dimensions
        #     import matplotlib.patches as mpatches
        #     i1, i2 = most_significant_input_dimensions(m, None)
        #     xmin, xmax = 100, -100
        #     ymin, ymax = 100, -100
        #     legend_handles = []
        #
        #     X = m.X.mean[:, [i1, i2]]
        #     X = m.X.variance[:, [i1, i2]]
        #
        #     xmin = X[:,0].min(); xmax = X[:,0].max()
        #     ymin = X[:,1].min(); ymax = X[:,1].max()
        #     range_ = [[xmin, xmax], [ymin, ymax]]
        #     ul = np.unique(labels)
        #
        #     for i, l in enumerate(ul):
        #         #cdict = dict(red  =[(0., colors[i][0], colors[i][0]), (1., colors[i][0], colors[i][0])],
        #         #             green=[(0., colors[i][0], colors[i][1]), (1., colors[i][1], colors[i][1])],
        #         #             blue =[(0., colors[i][0], colors[i][2]), (1., colors[i][2], colors[i][2])],
        #         #             alpha=[(0., 0., .0), (.5, .5, .5), (1., .5, .5)])
        #         #cmap = LinearSegmentedColormap('{}'.format(l), cdict)
        #         cmap = LinearSegmentedColormap.from_list('cmap_{}'.format(str(l)), [colors[i], colors[i]], 255)
        #         cmap._init()
        #         #alphas = .5*(1+scipy.special.erf(np.linspace(-2,2, cmap.N+3)))#np.log(np.linspace(np.exp(0), np.exp(1.), cmap.N+3))
        #         alphas = (scipy.special.erf(np.linspace(0,2.4, cmap.N+3)))#np.log(np.linspace(np.exp(0), np.exp(1.), cmap.N+3))
        #         cmap._lut[:, -1] = alphas
        #         print l
        #         x, y = X[labels==l].T
        #
        #         heatmap, xedges, yedges = np.histogram2d(x, y, bins=300, range=range_)
        #         #heatmap, xedges, yedges = np.histogram2d(x, y, bins=100)
        #
        #         im = ax.imshow(heatmap, extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], cmap=cmap, aspect='auto', interpolation='nearest', label=str(l))
        #         legend_handles.append(mpatches.Patch(color=colors[i], label=l))
        #     ax.set_xlim(xmin, xmax)
        #     ax.set_ylim(ymin, ymax)
        #     plt.legend(legend_handles, [l.get_label() for l in legend_handles])
        #     plt.draw()
        #     plt.show()
        #=======================================================================

    # create a function which computes the shading of latent space according to the output variance
    def plot_function(x):
        Xtest_full = np.zeros((x.shape[0], X.shape[1]))
        Xtest_full[:, [input_1, input_2]] = x
        _, var = model.predict(Xtest_full, **predict_kwargs)
        var = var[:, :1]
        return np.log(var)

    #Create an IMshow controller that can re-plot the latent space shading at a good resolution
    if plot_limits is None:
        xmin, ymin = X[:, [input_1, input_2]].min(0)
        xmax, ymax = X[:, [input_1, input_2]].max(0)
        x_r, y_r = xmax-xmin, ymax-ymin
        xmin -= .1*x_r
        xmax += .1*x_r
        ymin -= .1*y_r
        ymax += .1*y_r
    else:
        try:
            xmin, xmax, ymin, ymax = plot_limits
        except (TypeError, ValueError) as e:
            raise e.__class__("Wrong plot limits: {} given -> need (xmin, xmax, ymin, ymax)".format(plot_limits))
    view = ImshowController(ax, plot_function,
                            (xmin, ymin, xmax, ymax),
                            resolution, aspect=aspect, interpolation='bilinear',
                            cmap=cm.binary, **imshow_kwargs)

    # make sure labels are in order of input:
    labels = np.asarray(labels)
    ulabels = []
    for lab in labels:
        if not lab in ulabels:
            ulabels.append(lab)

    marker = itertools.cycle(list(marker))

    for i, ul in enumerate(ulabels):
        if type(ul) is np.string_:
            this_label = ul
        elif type(ul) is np.int64:
            this_label = 'class %i' % ul
        else:
            this_label = unicode(ul)
        m = marker.next()

        index = np.nonzero(labels == ul)[0]
        if model.input_dim == 1:
            x = X[index, input_1]
            y = np.zeros(index.size)
        else:
            x = X[index, input_1]
            y = X[index, input_2]
        ax.scatter(x, y, marker=m, s=s, c=Tango.nextMedium(), label=this_label, linewidth=.2, edgecolor='k', alpha=.9)

    ax.set_xlabel('latent dimension %i' % input_1)
    ax.set_ylabel('latent dimension %i' % input_2)

    if not np.all(labels == 1.) and legend:
        ax.legend(loc=0, numpoints=1)

    ax.grid(b=False) # remove the grid if present, it doesn't look good
    ax.set_aspect('auto') # set a nice aspect ratio

    if plot_inducing:
        Z = model.Z
        ax.scatter(Z[:, input_1], Z[:, input_2], c='w', s=14, marker="^", edgecolor='k', linewidth=.3, alpha=.6)

    ax.set_xlim((xmin, xmax))
    ax.set_ylim((ymin, ymax))

    try:
        fig.canvas.draw()
        fig.tight_layout()
        fig.canvas.draw()
    except Exception as e:
        print("Could not invoke tight layout: {}".format(e))
        pass

    if updates:
        try:
            fig.canvas.show()
        except Exception as e:
            print("Could not invoke show: {}".format(e))
        #raw_input('Enter to continue')
        return view
    return ax
예제 #9
0
def plot(x, y, **kwargs):
    #color palette
    light1 = Tango.colors('lightBlue')
    light2 = Tango.colors('lightPurple')
    light3 = Tango.colors('lightRed')
    dark1 = Tango.colors('darkBlue')
    dark2 = Tango.colors('darkPurple')
    dark3 = Tango.colors('darkRed')

    #args
    linewidth = kwargs.get('linewidth', 3)
    axis_lim = kwargs.get('axis_lim', (0, 1, 0, 1))
    figsize = kwargs.get('figsize', (12, 4.5))
    fontsize = kwargs.get('fontsize', 22)
    capthick = kwargs.get('capthick', 6)
    subplot = kwargs.get('subplot', None)
    ref = kwargs.get('ref', None)
    yvar = kwargs.get('yvar', None)
    data = kwargs.get('data', None)
    data2 = kwargs.get('data2', None)
    labels = kwargs.get(
        'labels', ('', '', '', '', '', '', '', '', '', '', '', '', '', '', ''))

    #fig
    if subplot is None:
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(1, 1, 1)
        # REFERENCE FUNCTION
    else:
        ax = subplot

    if ref is not None:
        y_ref = ref[0]
        yvar_ref = ref[1]
        y_ref_upper = y_ref + 2 * (yvar_ref**0.5)
        y_ref_lower = y_ref - 2 * (yvar_ref**0.5)

        ax.plot(x, y_ref, '--k', linewidth=linewidth, label=labels[2])
        ax.plot(x, y_ref_upper, ':k', linewidth=linewidth, label=labels[3])
        ax.plot(x, y_ref_lower, ':k', linewidth=linewidth)
    #DATA1
    if data is not None:
        X = data[0].copy().flatten()
        Y = data[1].copy().flatten()
        if len(data) > 2:
            Yvar = data[2].copy().flatten()
        else:
            Yvar = 0
        ax.errorbar(X,
                    Y,
                    yerr=2 * (Yvar**0.5),
                    fmt='o',
                    ecolor=light2,
                    capthick=capthick,
                    elinewidth=3,
                    mfc=light2,
                    mec=dark2,
                    marker='s',
                    ms=8,
                    mew=3,
                    label=labels[4])
    #DATA2
    if data2 is not None:
        X = data2[0].copy().flatten()
        Y = data2[1].copy().flatten()
        if len(data2) > 2:
            Yvar = data2[2].copy().flatten()
        else:
            Yvar = 0
        ax.errorbar(X,
                    Y,
                    yerr=2 * (Yvar**0.5),
                    fmt='o',
                    ecolor=light3,
                    capthick=capthick,
                    elinewidth=3,
                    mfc=light3,
                    mec=dark3,
                    marker='^',
                    ms=8,
                    mew=3,
                    label=labels[5])

    # MAIN FUNCTION
    ax.plot(x, y, color=dark1, linewidth=linewidth, label=labels[0])
    if yvar is not None:
        y_upper = y + 2 * (yvar**0.5)  # +2 SD
        y_lower = y - 2 * (yvar**0.5)  # -2 SD
        ax.fill_between(x.flatten(),
                        y_upper.flatten(),
                        y_lower.flatten(),
                        facecolor=light1,
                        alpha=0.3)
        ax.plot([], [], light1, alpha=0.3, linewidth=10, label=labels[1])

    ax.set_xlabel('x', fontsize=fontsize, fontweight='bold')
    ax.set_ylabel('z', fontsize=fontsize, fontweight='bold')
    ax.axis(axis_lim)
    ax.yaxis.grid(True)

    plt.legend(loc=1, ncol=3)  #, mode="expand", borderaxespad=0.)
예제 #10
0
def surf(X, Y, **kwargs):
    #color palette
    light1 = Tango.colors('lightBlue')
    light2 = Tango.colors('lightRed')
    dark1 = Tango.colors('darkBlue')
    dark2 = Tango.colors('darkRed')

    #args

    linewidth = kwargs.get('linewidth', 0.5)
    axis_lim = kwargs.get('axis_lim', None)
    figsize = kwargs.get('figsize', (16, 12))
    fontsize = kwargs.get('fontsize', 22)
    capthick = kwargs.get('capthick', 6)
    subplot = kwargs.get('subplot', None)
    ref = kwargs.get('ref', None)
    data = kwargs.get('data', None)

    #fig
    if subplot is None:
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111, projection='3d')
        # REFERENCE FUNCTION
    else:
        ax = subplot

    if ref is not None:
        ref_X = ref[0]
        ref_Y = ref[1]

        ax.plot_trisurf(ref_X[:, 0],
                        ref_X[:, 1],
                        ref_Y.copy().flatten(),
                        color='k',
                        alpha=0.1,
                        linewidth=2 * linewidth,
                        edgecolors='k',
                        label='Reference')

    ax.plot_trisurf(X[:, 0],
                    X[:, 1],
                    Y.copy().flatten(),
                    color=light1,
                    alpha=0.25,
                    linewidth=linewidth,
                    edgecolors=dark1,
                    label='Prediction')

    if data is not None:
        data_X = data[0]
        data_Y = data[1]

        ax.scatter(data_X[:, 0],
                   data_X[:, 1],
                   data_Y.copy().flatten(),
                   c=dark2,
                   marker='s',
                   s=50)


#    train = plt.errorbar(X, Y, yerr=2*(Yvar**0.5), fmt='o',ecolor=light2,capthick=capthick,elinewidth=linewidth,mfc=light2,mec=dark2,marker='s',ms=3*linewidth,mew=linewidth)

    ax.set_xlabel('x[m]', fontsize=fontsize, fontweight='bold')
    ax.set_ylabel('y[m]', fontsize=fontsize, fontweight='bold')
    plt.legend(loc=1, ncol=3)  #, mode="expand", borderaxespad=0.)
예제 #11
0
def GP(x, y, yvar, **kwargs):

    nsd = kwargs.get('nsd', 2)
    #color palette
    light1 = Tango.colors('lightBlue')
    light2 = Tango.colors('lightPurple')
    dark1 = Tango.colors('darkBlue')
    dark2 = Tango.colors('darkPurple')

    #args
    expected_kwargs = ('linewidth', 'axis_lim', 'figsize', 'ref', 'data',
                       'fontsize', 'capthick')
    default_values = (3, (0, 10, -2, 2), (24, 9), None, None, 22, 6)
    linewidth, axis_lim, figsize, ref, data, fontsize, capthick = get_from_kwargs(
        expected_kwargs, default_values, kwargs)

    #fig
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(1, 1, 1)

    y_upper = y + nsd * (yvar**0.5)  # +2 SD
    y_lower = y - nsd * (yvar**0.5)  # -2 SD

    if ref is not None:
        y_ref = ref[0]
        yvar_ref = ref[1]
        y_ref_upper = y_ref + nsd * (yvar_ref**0.5)
        y_ref_lower = y_ref - nsd * (yvar_ref**0.5)

        refz, = plt.plot(x,
                         y_ref,
                         '--k',
                         linewidth=linewidth,
                         label='Ref. function')
        refz2, = plt.plot(x,
                          y_ref_upper,
                          ':k',
                          linewidth=linewidth,
                          label='Ref. confidence interval')
        plt.plot(x, y_ref_lower, ':k', linewidth=linewidth)

    expz, = plt.plot(x,
                     y,
                     color=dark1,
                     linewidth=linewidth,
                     label='Expected value')
    plt.fill_between(x.flatten(),
                     y_upper.flatten(),
                     y_lower.flatten(),
                     facecolor=light1,
                     alpha=0.3)
    expz2, = plt.plot([], [],
                      light1,
                      alpha=0.3,
                      linewidth=10,
                      label='Confidence interval')

    if data is not None:
        X = data[0].copy().flatten()
        Y = data[1].copy().flatten()
        if len(data) > 2:
            Yvar = data[2].copy().flatten()
        else:
            Yvar = 0
        train = plt.errorbar(X,
                             Y,
                             yerr=(nsd * Yvar**0.5),
                             linewidth=0,
                             fmt='-o',
                             ecolor=light2,
                             capthick=capthick,
                             elinewidth=linewidth,
                             mfc=light2,
                             mec=dark2,
                             marker='s',
                             ms=3 * linewidth,
                             mew=linewidth,
                             label='Training data')

    ax.set_xlabel('x', fontsize=fontsize, fontweight='bold')
    ax.set_ylabel('z', fontsize=fontsize, fontweight='bold')
    ax.axis(axis_lim)
    ax.yaxis.grid(True)

    plt.legend(loc=1, ncol=3)  #, mode="expand", borderaxespad=0.)
예제 #12
0
def plot_latent(model,
                labels=None,
                which_indices=None,
                resolution=50,
                ax=None,
                marker='o',
                s=40,
                fignum=None,
                plot_inducing=False,
                legend=True,
                plot_limits=None,
                aspect='auto',
                updates=False,
                predict_kwargs={},
                imshow_kwargs={}):
    """
    :param labels: a np.array of size model.num_data containing labels for the points (can be number, strings, etc)
    :param resolution: the resolution of the grid on which to evaluate the predictive variance
    """
    if ax is None:
        fig = pb.figure(num=fignum)
        ax = fig.add_subplot(111)
    else:
        fig = ax.figure
    Tango.reset()

    if labels is None:
        labels = np.ones(model.num_data)

    input_1, input_2 = most_significant_input_dimensions(model, which_indices)

    #fethch the data points X that we'd like to plot
    X = model.X
    if isinstance(X, VariationalPosterior):
        X = X.mean
    else:
        X = X

    if X.shape[0] > 1000:
        print "Warning: subsampling X, as it has more samples then 1000. X.shape={!s}".format(
            X.shape)
        subsample = np.random.choice(X.shape[0], size=1000, replace=False)
        X = X[subsample]
        labels = labels[subsample]
        #=======================================================================
        #     <<<WORK IN PROGRESS>>>
        #     <<<DO NOT DELETE>>>
        #     plt.close('all')
        #     fig, ax = plt.subplots(1,1)
        #     from GPy.plotting.matplot_dep.dim_reduction_plots import most_significant_input_dimensions
        #     import matplotlib.patches as mpatches
        #     i1, i2 = most_significant_input_dimensions(m, None)
        #     xmin, xmax = 100, -100
        #     ymin, ymax = 100, -100
        #     legend_handles = []
        #
        #     X = m.X.mean[:, [i1, i2]]
        #     X = m.X.variance[:, [i1, i2]]
        #
        #     xmin = X[:,0].min(); xmax = X[:,0].max()
        #     ymin = X[:,1].min(); ymax = X[:,1].max()
        #     range_ = [[xmin, xmax], [ymin, ymax]]
        #     ul = np.unique(labels)
        #
        #     for i, l in enumerate(ul):
        #         #cdict = dict(red  =[(0., colors[i][0], colors[i][0]), (1., colors[i][0], colors[i][0])],
        #         #             green=[(0., colors[i][0], colors[i][1]), (1., colors[i][1], colors[i][1])],
        #         #             blue =[(0., colors[i][0], colors[i][2]), (1., colors[i][2], colors[i][2])],
        #         #             alpha=[(0., 0., .0), (.5, .5, .5), (1., .5, .5)])
        #         #cmap = LinearSegmentedColormap('{}'.format(l), cdict)
        #         cmap = LinearSegmentedColormap.from_list('cmap_{}'.format(str(l)), [colors[i], colors[i]], 255)
        #         cmap._init()
        #         #alphas = .5*(1+scipy.special.erf(np.linspace(-2,2, cmap.N+3)))#np.log(np.linspace(np.exp(0), np.exp(1.), cmap.N+3))
        #         alphas = (scipy.special.erf(np.linspace(0,2.4, cmap.N+3)))#np.log(np.linspace(np.exp(0), np.exp(1.), cmap.N+3))
        #         cmap._lut[:, -1] = alphas
        #         print l
        #         x, y = X[labels==l].T
        #
        #         heatmap, xedges, yedges = np.histogram2d(x, y, bins=300, range=range_)
        #         #heatmap, xedges, yedges = np.histogram2d(x, y, bins=100)
        #
        #         im = ax.imshow(heatmap, extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], cmap=cmap, aspect='auto', interpolation='nearest', label=str(l))
        #         legend_handles.append(mpatches.Patch(color=colors[i], label=l))
        #     ax.set_xlim(xmin, xmax)
        #     ax.set_ylim(ymin, ymax)
        #     plt.legend(legend_handles, [l.get_label() for l in legend_handles])
        #     plt.draw()
        #     plt.show()
        #=======================================================================

    # create a function which computes the shading of latent space according to the output variance
    def plot_function(x):
        Xtest_full = np.zeros((x.shape[0], model.X.shape[1]))
        Xtest_full[:, [input_1, input_2]] = x
        _, var = model.predict(Xtest_full, **predict_kwargs)
        var = var[:, :1]
        return np.log(var)

    #Create an IMshow controller that can re-plot the latent space shading at a good resolution
    if plot_limits is None:
        xmin, ymin = X[:, [input_1, input_2]].min(0)
        xmax, ymax = X[:, [input_1, input_2]].max(0)
        x_r, y_r = xmax - xmin, ymax - ymin
        xmin -= .1 * x_r
        xmax += .1 * x_r
        ymin -= .1 * y_r
        ymax += .1 * y_r
    else:
        try:
            xmin, xmax, ymin, ymax = plot_limits
        except (TypeError, ValueError) as e:
            raise e.__class__, "Wrong plot limits: {} given -> need (xmin, xmax, ymin, ymax)".format(
                plot_limits)
    view = ImshowController(ax,
                            plot_function, (xmin, ymin, xmax, ymax),
                            resolution,
                            aspect=aspect,
                            interpolation='bilinear',
                            cmap=pb.cm.binary,
                            **imshow_kwargs)

    # make sure labels are in order of input:
    labels = np.asarray(labels)
    ulabels = []
    for lab in labels:
        if not lab in ulabels:
            ulabels.append(lab)

    marker = itertools.cycle(list(marker))

    for i, ul in enumerate(ulabels):
        if type(ul) is np.string_:
            this_label = ul
        elif type(ul) is np.int64:
            this_label = 'class %i' % ul
        else:
            this_label = unicode(ul)
        m = marker.next()

        index = np.nonzero(labels == ul)[0]
        if model.input_dim == 1:
            x = X[index, input_1]
            y = np.zeros(index.size)
        else:
            x = X[index, input_1]
            y = X[index, input_2]
        ax.scatter(x,
                   y,
                   marker=m,
                   s=s,
                   c=Tango.nextMedium(),
                   label=this_label,
                   linewidth=.2,
                   edgecolor='k',
                   alpha=.9)

    ax.set_xlabel('latent dimension %i' % input_1)
    ax.set_ylabel('latent dimension %i' % input_2)

    if not np.all(labels == 1.) and legend:
        ax.legend(loc=0, numpoints=1)

    ax.grid(b=False)  # remove the grid if present, it doesn't look good
    ax.set_aspect('auto')  # set a nice aspect ratio

    if plot_inducing:
        Z = model.Z
        ax.scatter(Z[:, input_1],
                   Z[:, input_2],
                   c='w',
                   s=14,
                   marker="^",
                   edgecolor='k',
                   linewidth=.3,
                   alpha=.6)

    ax.set_xlim((xmin, xmax))
    ax.set_ylim((ymin, ymax))

    try:
        fig.canvas.draw()
        fig.tight_layout()
        fig.canvas.draw()
    except Exception as e:
        print "Could not invoke tight layout: {}".format(e)
        pass

    if updates:
        try:
            ax.figure.canvas.show()
        except Exception as e:
            print "Could not invoke show: {}".format(e)
        raw_input('Enter to continue')
        view.deactivate()
    return ax
예제 #13
0
def plot_steepest_gradient_map(model,
                               fignum=None,
                               ax=None,
                               which_indices=None,
                               labels=None,
                               data_labels=None,
                               data_marker='o',
                               data_s=40,
                               resolution=20,
                               aspect='auto',
                               updates=False,
                               **kwargs):

    input_1, input_2 = significant_dims = most_significant_input_dimensions(
        model, which_indices)

    X = np.zeros((resolution**2, model.input_dim))
    indices = np.r_[:X.shape[0]]
    if labels is None:
        labels = range(model.output_dim)

    def plot_function(x):
        X[:, significant_dims] = x
        dmu_dX = model.dmu_dXnew(X)
        argmax = np.argmax(dmu_dX, 1)
        return dmu_dX[indices, argmax], np.array(labels)[argmax]

    if ax is None:
        fig = pb.figure(num=fignum)
        ax = fig.add_subplot(111)

    if data_labels is None:
        data_labels = np.ones(model.num_data)
    ulabels = []
    for lab in data_labels:
        if not lab in ulabels:
            ulabels.append(lab)
    marker = itertools.cycle(list(data_marker))
    for i, ul in enumerate(ulabels):
        if type(ul) is np.string_:
            this_label = ul
        elif type(ul) is np.int64:
            this_label = 'class %i' % ul
        else:
            this_label = 'class %i' % i
        m = marker.next()
        index = np.nonzero(data_labels == ul)[0]
        x = model.X[index, input_1]
        y = model.X[index, input_2]
        ax.scatter(x,
                   y,
                   marker=m,
                   s=data_s,
                   color=Tango.nextMedium(),
                   label=this_label)

    ax.set_xlabel('latent dimension %i' % input_1)
    ax.set_ylabel('latent dimension %i' % input_2)

    controller = ImAnnotateController(
        ax,
        plot_function,
        tuple(model.X.min(0)[:, significant_dims]) +
        tuple(model.X.max(0)[:, significant_dims]),
        resolution=resolution,
        aspect=aspect,
        cmap=get_cmap('jet'),
        **kwargs)
    ax.legend()
    ax.figure.tight_layout()
    if updates:
        pb.show()
        clear = raw_input('Enter to continue')
        if clear.lower() in 'yes' or clear == '':
            controller.deactivate()
    return controller.view
예제 #14
0
def plot_magnification(model,
                       labels=None,
                       which_indices=None,
                       resolution=60,
                       ax=None,
                       marker='o',
                       s=40,
                       fignum=None,
                       plot_inducing=False,
                       legend=True,
                       aspect='auto',
                       updates=False):
    """
    :param labels: a np.array of size model.num_data containing labels for the points (can be number, strings, etc)
    :param resolution: the resolution of the grid on which to evaluate the predictive variance
    """
    if ax is None:
        fig = pb.figure(num=fignum)
        ax = fig.add_subplot(111)
    Tango.reset()

    if labels is None:
        labels = np.ones(model.num_data)

    input_1, input_2 = most_significant_input_dimensions(model, which_indices)

    # first, plot the output variance as a function of the latent space
    Xtest, xx, yy, xmin, xmax = x_frame2D(model.X[:, [input_1, input_2]],
                                          resolution=resolution)
    Xtest_full = np.zeros((Xtest.shape[0], model.X.shape[1]))

    def plot_function(x):
        Xtest_full[:, [input_1, input_2]] = x
        mf = model.magnification(Xtest_full)
        return mf

    view = ImshowController(ax,
                            plot_function,
                            tuple(model.X.min(0)[:, [input_1, input_2]]) +
                            tuple(model.X.max(0)[:, [input_1, input_2]]),
                            resolution,
                            aspect=aspect,
                            interpolation='bilinear',
                            cmap=pb.cm.gray)

    # make sure labels are in order of input:
    ulabels = []
    for lab in labels:
        if not lab in ulabels:
            ulabels.append(lab)

    marker = itertools.cycle(list(marker))

    for i, ul in enumerate(ulabels):
        if type(ul) is np.string_:
            this_label = ul
        elif type(ul) is np.int64:
            this_label = 'class %i' % ul
        else:
            this_label = 'class %i' % i
        m = marker.next()

        index = np.nonzero(labels == ul)[0]
        if model.input_dim == 1:
            x = model.X[index, input_1]
            y = np.zeros(index.size)
        else:
            x = model.X[index, input_1]
            y = model.X[index, input_2]
        ax.scatter(x,
                   y,
                   marker=m,
                   s=s,
                   color=Tango.nextMedium(),
                   label=this_label)

    ax.set_xlabel('latent dimension %i' % input_1)
    ax.set_ylabel('latent dimension %i' % input_2)

    if not np.all(labels == 1.) and legend:
        ax.legend(loc=0, numpoints=1)

    ax.set_xlim(xmin[0], xmax[0])
    ax.set_ylim(xmin[1], xmax[1])
    ax.grid(b=False)  # remove the grid if present, it doesn't look good
    ax.set_aspect('auto')  # set a nice aspect ratio

    if plot_inducing:
        ax.plot(model.Z[:, input_1], model.Z[:, input_2], '^w')

    if updates:
        fig.canvas.show()
        raw_input('Enter to continue')

    pb.title('Magnification Factor')
    return ax
예제 #15
0
def plot_magnification(model, labels=None, which_indices=None,
                resolution=60, ax=None, marker='o', s=40,
                fignum=None, plot_inducing=False, legend=True,
                aspect='auto', updates=False):
    """
    :param labels: a np.array of size model.num_data containing labels for the points (can be number, strings, etc)
    :param resolution: the resolution of the grid on which to evaluate the predictive variance
    """
    if ax is None:
        fig = pb.figure(num=fignum)
        ax = fig.add_subplot(111)
    Tango.reset()

    if labels is None:
        labels = np.ones(model.num_data)

    input_1, input_2 = most_significant_input_dimensions(model, which_indices)

    # first, plot the output variance as a function of the latent space
    Xtest, xx, yy, xmin, xmax = x_frame2D(model.X[:, [input_1, input_2]], resolution=resolution)
    Xtest_full = np.zeros((Xtest.shape[0], model.X.shape[1]))

    def plot_function(x):
        Xtest_full[:, [input_1, input_2]] = x
        mf=model.magnification(Xtest_full)
        return mf

    view = ImshowController(ax, plot_function,
                            tuple(model.X.min(0)[:, [input_1, input_2]]) + tuple(model.X.max(0)[:, [input_1, input_2]]),
                            resolution, aspect=aspect, interpolation='bilinear',
                            cmap=pb.cm.gray)

    # make sure labels are in order of input:
    ulabels = []
    for lab in labels:
        if not lab in ulabels:
            ulabels.append(lab)

    marker = itertools.cycle(list(marker))

    for i, ul in enumerate(ulabels):
        if type(ul) is np.string_:
            this_label = ul
        elif type(ul) is np.int64:
            this_label = 'class %i' % ul
        else:
            this_label = 'class %i' % i
        m = marker.next()

        index = np.nonzero(labels == ul)[0]
        if model.input_dim == 1:
            x = model.X[index, input_1]
            y = np.zeros(index.size)
        else:
            x = model.X[index, input_1]
            y = model.X[index, input_2]
        ax.scatter(x, y, marker=m, s=s, color=Tango.nextMedium(), label=this_label)

    ax.set_xlabel('latent dimension %i' % input_1)
    ax.set_ylabel('latent dimension %i' % input_2)

    if not np.all(labels == 1.) and legend:
        ax.legend(loc=0, numpoints=1)

    ax.set_xlim(xmin[0], xmax[0])
    ax.set_ylim(xmin[1], xmax[1])
    ax.grid(b=False) # remove the grid if present, it doesn't look good
    ax.set_aspect('auto') # set a nice aspect ratio

    if plot_inducing:
        ax.plot(model.Z[:, input_1], model.Z[:, input_2], '^w')

    if updates:
        fig.canvas.show()
        raw_input('Enter to continue')

    pb.title('Magnification Factor')
    return ax