Example #1
0
def plot_cluster_tot_size(hist, median=False, z_max=None, filename=None):
    H = hist[0:50, 0:20]
    if z_max is None:
        z_max = np.ma.max(H)
    if z_max < 1 or H.all() is np.ma.masked:
        z_max = 1
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    extent = [-0.5, 20.5, 49.5, -0.5]
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    cmap = cm.get_cmap('jet')
    cmap.set_bad('w')
    norm = colors.BoundaryNorm(bounds, cmap.N)
    im = ax.imshow(H, aspect="auto", interpolation='nearest', cmap=cmap, norm=norm, extent=extent)  # for monitoring
    ax.set_title('Cluster size and cluster ToT (' + str(np.sum(H) / 2) + ' entries)')
    ax.set_xlabel('cluster size')
    ax.set_ylabel('cluster ToT')

    ax.invert_yaxis()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.1)
    cb = fig.colorbar(im, cax=cax, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True))
    cb.set_label("#")
    fig.patch.set_facecolor('white')
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #2
0
def show_deformation_plot(model, step=None, size=(10, 10)):
    bounding_box = get_bounding_box([model])

    fig = Figure(figsize=size)
    ax = fig.add_subplot(111, projection='3d')

    ax.clear()

    ax.grid()
    plot_bounding_cube(ax, bounding_box)

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')

    plot_model(ax, model, 'gray', True)

    if step is not None:
        model = model.get_model_history()[step]
    else:
        step = len(model.get_model_history()) - 1

    plot_model(ax, model, 'red', False)

    ax.set_title('Deformed structure at time step {}\n{}'.format(
        step, model.name))

    fig.show()
Example #3
0
def plot_correlation(hist, title="Hit correlation", xlabel=None, ylabel=None, filename=None):
    logging.info("Plotting correlations")
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(1, 1, 1)
    cmap = cm.get_cmap('jet')
    extent = [hist[2][0] - 0.5, hist[2][-1] + 0.5, hist[1][-1] + 0.5, hist[1][0] - 0.5]
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    im = ax.imshow(hist[0], extent=extent, cmap=cmap, interpolation='nearest')
    ax.invert_yaxis()
    # add colorbar
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    z_max = np.max(hist[0])
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    norm = colors.BoundaryNorm(bounds, cmap.N)
    fig.colorbar(im, boundaries=bounds, cmap=cmap, norm=norm, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True), cax=cax)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #4
0
def plot_scatter(x, y, x_err=None, y_err=None, title=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, marker_style='-o', log_x=False, log_y=False, filename=None):
    logging.info('Plot scatter plot %s', (': ' + title) if title is not None else '')
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    if x_err is not None:
        x_err = [x_err, x_err]
    if y_err is not None:
        y_err = [y_err, y_err]
    if x_err is not None or y_err is not None:
        ax.errorbar(x, y, xerr=x_err, yerr=y_err, fmt=marker_style)
    else:
        ax.plot(x, y, marker_style, markersize=1)
    ax.set_title(title)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_x:
        ax.set_xscale('log')
    if log_y:
        ax.set_yscale('log')
    if plot_range:
        ax.set_xlim((min(plot_range), max(plot_range)))
    if plot_range_y:
        ax.set_ylim((min(plot_range_y), max(plot_range_y)))
    if legend:
        ax.legend(legend, 0)
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #5
0
class MatplotlibWidget(FigureCanvas):

    def __init__(self, parent=None):
        super(MatplotlibWidget, self).__init__(Figure())
        #self.hide()
        self.setParent(parent)
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)

        self.ax = self.figure.add_subplot(111)
        self.ax.yaxis.grid(color='gray', linestyle='dashed')

    def add_plot_line(self, x, y):
        self.ax.plot(x, y, 'r')

    def add_legend(self, list):
        #list of strings like "X1 = blaghlbah"
        self.figure.legend([x for x in list], loc='upper left')

    def draw_graph(self):
        self.figure.draw()

    def show_graph(self):
        self.figure.show()

    def plot_bar_graph(self):
        pass
Example #6
0
def plot_tdc_event(points, filename=None):
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111, projection='3d')
    xs = points[:, 0]
    ys = points[:, 1]
    zs = points[:, 2]
    cs = points[:, 3]

    p = ax.scatter(xs, ys, zs, c=cs, s=points[:, 3]**(2) / 5, marker='o')

    ax.set_xlabel('x [250 um]')
    ax.set_ylabel('y [50 um]')
    ax.set_zlabel('t [25 ns]')
    ax.title('Track of one TPC event')
    ax.set_xlim(0, 80)
    ax.set_ylim(0, 336)

    c_bar = fig.colorbar(p)
    c_bar.set_label('charge [TOT]')

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    elif filename:
        fig.savefig(filename)
    return fig
Example #7
0
def plot_scatter_time(x, y, yerr=None, title=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, marker_style='-o', log_x=False, log_y=False, filename=None):
    logging.info("Plot time scatter plot %s", (': ' + title) if title is not None else '')
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
    times = []
    for time in x:
        times.append(datetime.fromtimestamp(time))
    if yerr is not None:
        ax.errorbar(times, y, yerr=[yerr, yerr], fmt=marker_style)
    else:
        ax.plot(times, y, marker_style)
    ax.set_title(title)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_x:
        ax.xscale('log')
    if log_y:
        ax.yscale('log')
    if plot_range:
        ax.set_xlim((min(plot_range), max(plot_range)))
    if plot_range_y:
        ax.set_ylim((min(plot_range_y), max(plot_range_y)))
    if legend:
        ax.legend(legend, 0)
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #8
0
def plot_pixel_matrix(hist, title="Hit correlation", filename=None):
    logging.info("Plotting pixel matrix: %s", title)
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.set_title(title)
    ax.set_xlabel('Col')
    ax.set_ylabel('Row')
    cmap = cm.get_cmap('cool')
    ax.imshow(hist.T, aspect='auto', cmap=cmap, interpolation='none')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    z_max = np.max(hist)
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    norm = colors.BoundaryNorm(bounds, cmap.N)
    fig.colorbar(boundaries=bounds,
                 cmap=cmap,
                 norm=norm,
                 ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True),
                 cax=cax)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #9
0
def plotThreeWay(hist, title, filename=None, x_axis_title=None, minimum=None, maximum=None, bins=101):  # the famous 3 way plot (enhanced)
    if minimum is None:
        minimum = 0
    elif minimum == 'minimum':
        minimum = np.ma.min(hist)
    if maximum == 'median' or maximum is None:
        median = np.ma.median(hist)
        maximum = median * 2  # round_to_multiple(median * 2, math.floor(math.log10(median * 2)))
    elif maximum == 'maximum':
        maximum = np.ma.max(hist)
        maximum = maximum  # round_to_multiple(maximum, math.floor(math.log10(maximum)))
    if maximum < 1 or hist.all() is np.ma.masked:
        maximum = 1

    x_axis_title = '' if x_axis_title is None else x_axis_title
    fig = Figure()
    canvas = FigureCanvas(fig)
    fig.patch.set_facecolor('white')
    ax1 = fig.add_subplot(311)
    create_2d_pixel_hist(fig, ax1, hist, title=title, x_axis_title="column", y_axis_title="row", z_min = minimum if minimum else 0, z_max=maximum)
    ax2 = fig.add_subplot(312)
    create_1d_hist(fig, ax2, hist, bins=bins, x_axis_title=x_axis_title, y_axis_title="#", x_min=minimum, x_max=maximum)
    ax3 = fig.add_subplot(313)
    create_pixel_scatter_plot(fig, ax3, hist, x_axis_title="channel=row + column*336", y_axis_title=x_axis_title, y_min=minimum, y_max=maximum)
    fig.tight_layout()
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #10
0
def plot_scatter(x, y, x_err=None, y_err=None, title=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, marker_style='-o', log_x=False, log_y=False, filename=None):
    logging.info("Plot scatter plot %s" % ((': ' + title) if title is not None else ''))
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    if x_err is not None:
        x_err = [x_err, x_err]
    if y_err is not None:
        y_err = [y_err, y_err]
    if x_err is not None or y_err is not None:
        ax.errorbar(x, y, xerr=x_err, yerr=y_err, fmt=marker_style)
    else:
        ax.plot(x, y, marker_style, markersize=1)
    ax.set_title(title)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_x:
        ax.xscale('log')
    if log_y:
        ax.yscale('log')
    if plot_range:
        ax.set_xlim((min(plot_range), max(plot_range)))
    if plot_range_y:
        ax.set_ylim((min(plot_range_y), max(plot_range_y)))
    if legend:
        ax.legend(legend, 0)
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #11
0
def plot_cluster_tot_size(hist, median=False, z_max=None, filename=None):
    H = hist[0:50, 0:20]
    if z_max is None:
        z_max = np.ma.max(H)
    if z_max < 1 or H.all() is np.ma.masked:
        z_max = 1
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    extent = [-0.5, 20.5, 49.5, -0.5]
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    cmap = cm.get_cmap('jet')
    cmap.set_bad('w')
    norm = colors.BoundaryNorm(bounds, cmap.N)
    im = ax.imshow(H, aspect="auto", interpolation='nearest', cmap=cmap, norm=norm, extent=extent)  # for monitoring
    ax.set_title('Cluster size and cluster ToT (' + str(np.sum(H) / 2) + ' entries)')
    ax.set_xlabel('cluster size')
    ax.set_ylabel('cluster ToT')
    # fig.colorbar(cmap=cmap)
    ax.invert_yaxis()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.1)
    cb = fig.colorbar(im, cax=cax, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True))
    cb.set_label("#")
    fig.patch.set_facecolor('white')
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #12
0
def plot_1d_hist(hist, yerr=None, title=None, x_axis_title=None, y_axis_title=None, x_ticks=None, color='r', plot_range=None, log_y=False, filename=None, figure_name=None):
    logging.info("Plot 1d histogram%s" % ((': ' + title) if title is not None else ''))
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    if plot_range is None:
        plot_range = range(0, len(hist))
    if not plot_range:
        plot_range = [0]
    if yerr is not None:
        ax.bar(left=plot_range, height=hist[plot_range], color=color, align='center', yerr=yerr)
    else:
        ax.bar(left=plot_range, height=hist[plot_range], color=color, align='center')
    ax.set_xlim((min(plot_range) - 0.5, max(plot_range) + 0.5))
    ax.set_title(title)
    if x_axis_title is not None:
        ax.set_xlabel(x_axis_title)
    if y_axis_title is not None:
        ax.set_ylabel(y_axis_title)
    if x_ticks is not None:
        ax.set_xticks(range(0, len(hist[:])) if plot_range is None else plot_range)
        ax.set_xticklabels(x_ticks)
        ax.tick_params(which='both', labelsize=8)
    if np.allclose(hist, 0.0):
        ax.set_ylim((0, 1))
    else:
        if log_y:
            ax.set_yscale('log')
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #13
0
def plot_scatter_time(x, y, yerr=None, title=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, marker_style='-o', log_x=False, log_y=False, filename=None):
    logging.info("Plot time scatter plot %s" % ((': ' + title) if title is not None else ''))
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
    times = []
    for time in x:
        times.append(datetime.fromtimestamp(time))
    if yerr is not None:
        ax.errorbar(times, y, yerr=[yerr, yerr], fmt=marker_style)
    else:
        ax.plot(times, y, marker_style)
    ax.set_title(title)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_x:
        ax.xscale('log')
    if log_y:
        ax.yscale('log')
    if plot_range:
        ax.set_xlim((min(plot_range), max(plot_range)))
    if plot_range_y:
        ax.set_ylim((min(plot_range_y), max(plot_range_y)))
    if legend:
        ax.legend(legend, 0)
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #14
0
def plot_1d_hist(hist, yerr=None, title=None, x_axis_title=None, y_axis_title=None, x_ticks=None, color='r', plot_range=None, log_y=False, filename=None, figure_name=None):
    logging.info('Plot 1d histogram%s', (': ' + title) if title is not None else '')
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    if plot_range is None:
        plot_range = range(0, len(hist))
    if not plot_range:
        plot_range = [0]
    if yerr is not None:
        ax.bar(left=plot_range, height=hist[plot_range], color=color, align='center', yerr=yerr)
    else:
        ax.bar(left=plot_range, height=hist[plot_range], color=color, align='center')
    ax.set_xlim((min(plot_range) - 0.5, max(plot_range) + 0.5))
    ax.set_title(title)
    if x_axis_title is not None:
        ax.set_xlabel(x_axis_title)
    if y_axis_title is not None:
        ax.set_ylabel(y_axis_title)
    if x_ticks is not None:
        ax.set_xticks(range(0, len(hist[:])) if plot_range is None else plot_range)
        ax.set_xticklabels(x_ticks)
        ax.tick_params(which='both', labelsize=8)
    if np.allclose(hist, 0.0):
        ax.set_ylim((0, 1))
    else:
        if log_y:
            ax.set_yscale('log')
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #15
0
def plot_correlation(hist, title="Hit correlation", xlabel=None, ylabel=None, filename=None):
    logging.info("Plotting correlations")
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(1, 1, 1)
    cmap = cm.get_cmap('jet')
    extent = [hist[2][0] - 0.5, hist[2][-1] + 0.5, hist[1][-1] + 0.5, hist[1][0] - 0.5]
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    im = ax.imshow(hist[0], extent=extent, cmap=cmap, interpolation='nearest')
    ax.invert_yaxis()
    # add colorbar
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    z_max = np.max(hist[0])
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    norm = colors.BoundaryNorm(bounds, cmap.N)
    fig.colorbar(im, boundaries=bounds, cmap=cmap, norm=norm, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True), cax=cax)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #16
0
def plot_tdc_event(points, filename=None):
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111, projection='3d')
    xs = points[:, 0]
    ys = points[:, 1]
    zs = points[:, 2]
    cs = points[:, 3]

    p = ax.scatter(xs, ys, zs, c=cs, s=points[:, 3] ** (2) / 5., marker='o')

    ax.set_xlabel('x [250 um]')
    ax.set_ylabel('y [50 um]')
    ax.set_zlabel('t [25 ns]')
    ax.title('Track of one TPC event')
    ax.set_xlim(0, 80)
    ax.set_ylim(0, 336)

    c_bar = fig.colorbar(p)
    c_bar.set_label('charge [TOT]')

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    elif filename:
        fig.savefig(filename)
    return fig
Example #17
0
def plotThreeWay(hist, title, filename=None, x_axis_title=None, minimum=None, maximum=None, bins=101):  # the famous 3 way plot (enhanced)
    if minimum is None:
        minimum = 0
    elif minimum == 'minimum':
        minimum = np.ma.min(hist)
    if maximum == 'median' or maximum is None:
        median = np.ma.median(hist)
        maximum = median * 2  # round_to_multiple(median * 2, math.floor(math.log10(median * 2)))
    elif maximum == 'maximum':
        maximum = np.ma.max(hist)
        maximum = maximum  # round_to_multiple(maximum, math.floor(math.log10(maximum)))
    if maximum < 1 or hist.all() is np.ma.masked:
        maximum = 1

    x_axis_title = '' if x_axis_title is None else x_axis_title
    fig = Figure()
    FigureCanvas(fig)
    fig.patch.set_facecolor('white')
    ax1 = fig.add_subplot(311)
    create_2d_pixel_hist(fig, ax1, hist, title=title, x_axis_title="column", y_axis_title="row", z_min=minimum if minimum else 0, z_max=maximum)
    ax2 = fig.add_subplot(312)
    create_1d_hist(fig, ax2, hist, bins=bins, x_axis_title=x_axis_title, y_axis_title="#", x_min=minimum, x_max=maximum)
    ax3 = fig.add_subplot(313)
    create_pixel_scatter_plot(fig, ax3, hist, x_axis_title="channel=row + column*336", y_axis_title=x_axis_title, y_min=minimum, y_max=maximum)
    fig.tight_layout()
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #18
0
def plot_profile_histogram(x,
                           y,
                           n_bins=100,
                           title=None,
                           x_label=None,
                           y_label=None,
                           log_y=False,
                           filename=None):
    '''Takes 2D point data (x,y) and creates a profile histogram similar to the TProfile in ROOT. It calculates
    the y mean for every bin at the bin center and gives the y mean error as error bars.

    Parameters
    ----------
    x : array like
        data x positions
    y : array like
        data y positions
    n_bins : int
        the number of bins used to create the histogram
    '''
    if len(x) != len(y):
        raise ValueError('x and y dimensions have to be the same')
    n, bin_edges = np.histogram(
        x, bins=n_bins)  # needed to calculate the number of points per bin
    sy = np.histogram(x, bins=n_bins,
                      weights=y)[0]  # the sum of the bin values
    sy2 = np.histogram(x, bins=n_bins,
                       weights=y * y)[0]  # the quadratic sum of the bin values
    bin_centers = (bin_edges[1:] +
                   bin_edges[:-1]) / 2  # calculate the bin center for all bins
    mean = sy / n  # calculate the mean of all bins
    std = np.sqrt(
        (sy2 / n - mean * mean)
    )  # TODO: not understood, need check if this is really the standard deviation
    #     std_mean = np.sqrt((sy2 - 2 * mean * sy + mean * mean) / (1*(n - 1)))  # this should be the formular ?!
    std_mean = std / np.sqrt((n - 1))
    mean[np.isnan(mean)] = 0.0
    std_mean[np.isnan(std_mean)] = 0.0

    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.errorbar(bin_centers, mean, yerr=std_mean, fmt='o')
    ax.set_title(title)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_y:
        ax.yscale('log')
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
class PlotFigure(wx.Frame):
    def __init__(self,
                 title='Pyception results'
                 ):  #, style=wx.DEFAULT_FRAME_STYLE|wx.STAY_ON_TOP):
        #def __init__(self,title='Pyception Lab', pos=None, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE|wx.DIALOG_NO_PARENT):
        Frame.__init__(
            self, None, -1, title, style=wx.STAY_ON_TOP
            | wx.RESIZE_BORDER)  # style=wx.DEFAULT_FRAME_STYLE|wx.STAY_ON_TOP)
        #try:
        #wx.Dialog.__init__(self, None,-1,title)
        #except:
        #global app
        #app = wx.PySimpleApp()
        #wx.Dialog.__init__(self, None,-1,title)
        #wx.Dialog.__init__(self, None,-1,title="Pyception results")
        #style=style|wx.RESIZE_BORDER

        #self.fig = Figure((9,8), 75)
        self.fig = Figure()
        self.canvas = FigCanvas(self, -1, self.fig)
        #self.toolbar = Toolbar(self.canvas)
        #self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        #tw, th = self.toolbar.GetSizeTuple()
        #fw, fh = self.canvas.GetSizeTuple()
        #self.toolbar.SetSize(Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = BoxSizer(VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, LEFT | TOP | GROW)
        # Best to allow the toolbar to resize!
        # sizer.Add(self.toolbar, 0, GROW)

        btn = wx.Button(self, label='Close')
        btn.Bind(wx.EVT_BUTTON, self.onClose)
        sizer.Add(btn, 0, GROW)

        self.SetSizer(sizer)
        self.Fit()

    def onClose(self, event):
        self.eventLoop.Exit()
        self.Close()

    def ShowModal(self):
        self.MakeModal()
        self.fig.show()
        self.Show()
        self.eventLoop = wx.EventLoop()
        self.eventLoop.Run()
Example #20
0
def plot_tot_tdc_calibration(scan_parameters,
                             filename,
                             tot_mean,
                             tot_error=None,
                             tdc_mean=None,
                             tdc_error=None,
                             title="Charge calibration"):
    fig = Figure()
    FigureCanvas(fig)
    ax1 = fig.add_subplot(111)
    fig.patch.set_facecolor('white')
    ax1.grid(True)
    ax1.errorbar(scan_parameters, (tot_mean + 1) * 25.0,
                 yerr=(tot_error * 25.0) if tot_error is not None else None,
                 fmt='o',
                 color='b',
                 label='ToT')
    ax1.set_ylabel('ToT [ns]')
    ax1.set_title(title)
    ax1.set_xlabel('Charge [PlsrDAC]')
    if tdc_mean is not None:
        ax1.errorbar(scan_parameters,
                     tdc_mean * 1000.0 / 640.0,
                     yerr=(tdc_error * 1000.0 /
                           640.0) if tdc_error is not None else None,
                     fmt='o',
                     color='g',
                     label='TDC')
        ax1.set_ylabel('ToT / TDC [ns]')
    ax1.legend(loc=0)
    ax1.set_ylim(ymin=0.0)
    # second axis with ToT code
    ax2 = ax1.twinx()
    ax2.set_ylabel('ToT code')
    ax2.set_ylim(ax1.get_ylim())
    from matplotlib.ticker import IndexLocator, FuncFormatter, NullFormatter, MultipleLocator, FixedLocator

    def format_fn(tick_val, tick_pos):
        if tick_val <= 25 * 16:
            return str(int((tick_val / 25.0) - 1))
        else:
            return ''

    ax2.yaxis.set_major_formatter(FuncFormatter(format_fn))
    ax2.yaxis.set_major_locator(
        FixedLocator(
            locs=range(25, 17 *
                       25, 25) if ax1.get_ylim()[1] < 1000 else [25, 16 * 25]))

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #21
0
def plot_occupancy(hist, title='Occupancy', z_max=None, filename=None):
    if z_max == 'median':
        median = np.ma.median(hist)
        z_max = median * 2  # round_to_multiple(median * 2, math.floor(math.log10(median * 2)))
    elif z_max == 'maximum' or z_max is None:
        maximum = np.ma.max(hist)
        z_max = maximum  # round_to_multiple(maximum, math.floor(math.log10(maximum)))
    if z_max < 1 or hist.all() is np.ma.masked:
        z_max = 1

    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.set_adjustable('box-forced')
    #     extent = [yedges[0] - 0.5, yedges[-1] + 0.5, xedges[-1] + 0.5, xedges[0] - 0.5]
    extent = [0.5, 80.5, 336.5, 0.5]
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    cmap = cm.get_cmap('jet')
    cmap.set_bad('w')
    norm = colors.BoundaryNorm(bounds, cmap.N)
    #     norm = colors.LogNorm()

    im = ax.imshow(hist,
                   interpolation='nearest',
                   aspect='auto',
                   cmap=cmap,
                   norm=norm,
                   extent=extent)  # TODO: use pcolor or pcolormesh
    ax.set_ylim((336.5, 0.5))
    ax.set_xlim((0.5, 80.5))
    ax.set_title(title + ' (%d entrie(s))' %
                 (0 if hist.all() is np.ma.masked else np.ma.sum(hist)))
    ax.set_xlabel('Column')
    ax.set_ylabel('Row')

    divider = make_axes_locatable(ax)

    cax = divider.append_axes("right", size="5%", pad=0.1)
    cb = fig.colorbar(im,
                      cax=cax,
                      ticks=np.linspace(start=0,
                                        stop=z_max,
                                        num=9,
                                        endpoint=True))
    cb.set_label("#")

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #22
0
def plot_1d_hist(hist,
                 yerr=None,
                 title=None,
                 x_axis_title=None,
                 y_axis_title=None,
                 x_ticks=None,
                 color='r',
                 plot_range=None,
                 log_y=False,
                 filename=None):
    logging.info('Plot 1d histogram%s',
                 (': ' +
                  title.replace('\n', ' ')) if title is not None else '')
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    hist = np.array(hist)
    if plot_range is None:
        plot_range = range(0, max(1, len(hist)))
    plot_range = np.array(plot_range)
    plot_range = plot_range[plot_range < len(hist)]
    if yerr is not None:
        ax.bar(plot_range,
               hist[plot_range],
               color=color,
               align='center',
               yerr=yerr)
    else:
        ax.bar(plot_range, hist[plot_range], color=color, align='center')
    ax.set_xlim((min(plot_range) - 0.5, max(plot_range) + 0.5))
    ax.set_title(title)
    if x_axis_title is not None:
        ax.set_xlabel(x_axis_title)
    if y_axis_title is not None:
        ax.set_ylabel(y_axis_title)
    if x_ticks is not None:
        ax.set_xticks(plot_range)
        ax.set_xticklabels(x_ticks)
        ax.tick_params(which='both', labelsize=8)
    if hist.all() is np.ma.masked or np.allclose(hist, 0.0):
        ax.set_ylim((0, 1))
    else:
        if log_y:
            ax.set_yscale('log')
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #23
0
class PlotFigure(wx.Frame):
    def __init__(self, title='Pyception results'): #, style=wx.DEFAULT_FRAME_STYLE|wx.STAY_ON_TOP):
    #def __init__(self,title='Pyception Lab', pos=None, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE|wx.DIALOG_NO_PARENT):
        Frame.__init__(self, None, -1, title, style=wx.STAY_ON_TOP|wx.RESIZE_BORDER) # style=wx.DEFAULT_FRAME_STYLE|wx.STAY_ON_TOP)
        #try:
            #wx.Dialog.__init__(self, None,-1,title)
        #except:
            #global app
            #app = wx.PySimpleApp()
            #wx.Dialog.__init__(self, None,-1,title) 
        #wx.Dialog.__init__(self, None,-1,title="Pyception results")
#style=style|wx.RESIZE_BORDER

        #self.fig = Figure((9,8), 75)
        self.fig = Figure()
        self.canvas = FigCanvas(self, -1, self.fig)
        #self.toolbar = Toolbar(self.canvas)
        #self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        #tw, th = self.toolbar.GetSizeTuple()
        #fw, fh = self.canvas.GetSizeTuple()
        #self.toolbar.SetSize(Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = BoxSizer(VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, LEFT|TOP|GROW)
        # Best to allow the toolbar to resize!
        #sizer.Add(self.toolbar, 0, GROW)

        btn = wx.Button(self, label='Close')
        btn.Bind( wx.EVT_BUTTON, self.onClose)
        sizer.Add(btn, 0, GROW)

        self.SetSizer(sizer)
        self.Fit()

    def onClose(self, event):
        self.eventLoop.Exit()
        self.Close()

    def ShowModal(self):
        self.MakeModal()
        self.fig.show()
        self.Show()
        self.eventLoop = wx.EventLoop()
        self.eventLoop.Run()
Example #24
0
def plot_occupancy(hist, title='Occupancy', z_max=None, filename=None):
    if z_max == 'median':
        z_max = 2 * np.ma.median(hist)
    elif z_max == 'maximum' or z_max is None:
        z_max = np.ma.max(hist)
    if z_max < 1 or hist.all() is np.ma.masked or np.allclose(0, hist):
        z_max = 1.0

    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    extent = [0.5, 80.5, 336.5, 0.5]
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    if z_max == 'median':
        cmap = cm.get_cmap('coolwarm')
    else:
        cmap = cm.get_cmap('cool')
    cmap.set_bad('w', 1.0)
    norm = colors.BoundaryNorm(bounds, cmap.N)

    im = ax.imshow(hist,
                   interpolation='none',
                   aspect='auto',
                   cmap=cmap,
                   norm=norm,
                   extent=extent)  # TODO: use pcolor or pcolormesh
    ax.set_ylim((336.5, 0.5))
    ax.set_xlim((0.5, 80.5))
    ax.set_title(title + r' ($\Sigma$ = {0})'.format(
        (0 if (hist.all() is np.ma.masked or np.allclose(0, hist)
               ) else np.ma.sum(hist))))
    ax.set_xlabel('Column')
    ax.set_ylabel('Row')

    divider = make_axes_locatable(ax)

    cax = divider.append_axes("right", size="5%", pad=0.1)
    cb = fig.colorbar(im,
                      cax=cax,
                      ticks=np.linspace(start=0,
                                        stop=z_max,
                                        num=9,
                                        endpoint=True))
    cb.set_label("#")

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #25
0
def plotLattice(lattice):
    '''
    uncode the lattice pack and print each orbital on screen
    '''
    f=Figure()
    ax=f.add_subplot(111)
    for x in lattice:
        for y in x:
            for z in y:
                for o in z:
                    ax.scatter(o.x,o.y,color='blue')
                    ax.annotate(o.id,(o.x,o.y),size=10.5)
                    for target in o.linkedSite:
                        ax.plot([o.x,target.x],[o.y,target.y],color='red')
    f.show()
Example #26
0
def plot_scurves(occupancy_hist, scan_parameters, title='S-Curves', ylabel='Occupancy', max_occ=None, scan_parameter_name=None, min_x=None, max_x=None, x_scale=1.0, y_scale=1., filename=None):  # tornado plot
    occ_mask = np.all(occupancy_hist == 0, axis=2)
    if max_occ is None:
        max_occ = 2 * np.median(np.amax(occupancy_hist, axis=2))
        if np.allclose(max_occ, 0.0):
            max_occ = np.amax(occupancy_hist)
        if np.allclose(max_occ, 0.0):
            max_occ = 1
    if len(occupancy_hist.shape) < 3:
        raise ValueError('Found array with shape %s' % str(occupancy_hist.shape))
#     y = occupancy_hist.reshape(-1)  # np.ravel(occupancy_hist) or occupancy_hist.flat
    n_pixel = occupancy_hist.shape[0] * occupancy_hist.shape[1]
#     x = np.tile(scan_parameters, n_pixel)
    cmap = cm.get_cmap('jet', 200)
    for index, scan_parameter in enumerate(scan_parameters):
        compressed_data = np.ma.masked_array(occupancy_hist[:, :, index], mask=occ_mask, copy=True).compressed()
        heatmap, xedges, yedges = np.histogram2d(compressed_data, [scan_parameter] * compressed_data.shape[0], range=[[0, max_occ], [scan_parameters[0], scan_parameters[-1]]], bins=(max_occ + 1, len(scan_parameters)))
        if index == 0:
            hist = heatmap
        else:
            hist += heatmap
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    fig.patch.set_facecolor('white')
    if len(scan_parameters) > 1:
        scan_parameter_dist = (np.amax(scan_parameters) - np.amin(scan_parameters)) / (len(scan_parameters) - 1)
    else:
        scan_parameter_dist = 0
    extent = [yedges[0] - scan_parameter_dist / 2, yedges[-1] * x_scale + scan_parameter_dist / 2, xedges[-1] * y_scale + 0.5, xedges[0] - 0.5]
    norm = colors.LogNorm()
    im = ax.imshow(hist, interpolation='nearest', aspect="auto", cmap=cmap, extent=extent, norm=norm)
    ax.invert_yaxis()
    if min_x is not None or max_x is not None:
        ax.set_xlim((min_x if min_x is not None else np.amin(scan_parameters), max_x if max_x is not None else np.amax(scan_parameters)))
    fig.colorbar(im)
    ax.set_title(title + ' for %d pixel(s)' % (n_pixel - np.count_nonzero(occ_mask)))
    if scan_parameter_name is None:
        ax.set_xlabel('Scan parameter')
    else:
        ax.set_xlabel(scan_parameter_name)
    ax.set_ylabel(ylabel)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #27
0
def plot_scurves(occupancy_hist, scan_parameters, title='S-Curves', ylabel='Occupancy', max_occ=None, scan_parameter_name=None, min_x=None, max_x=None, x_scale=1.0, y_scale=1., filename=None):  # tornado plot
    occ_mask = np.all(occupancy_hist == 0, axis=2)
    if max_occ is None:
        max_occ = 2 * np.median(np.amax(occupancy_hist, axis=2))
        if np.allclose(max_occ, 0.0):
            max_occ = np.amax(occupancy_hist)
        if np.allclose(max_occ, 0.0):
            max_occ = 1
    if len(occupancy_hist.shape) < 3:
        raise ValueError('Found array with shape %s' % str(occupancy_hist.shape))

    n_pixel = occupancy_hist.shape[0] * occupancy_hist.shape[1]

    cmap = cm.get_cmap('jet', 200)
    for index, scan_parameter in enumerate(scan_parameters):
        compressed_data = np.ma.masked_array(occupancy_hist[:, :, index], mask=occ_mask, copy=True).compressed()
        heatmap, xedges, yedges = np.histogram2d(compressed_data, [scan_parameter] * compressed_data.shape[0], range=[[0, max_occ], [scan_parameters[0], scan_parameters[-1]]], bins=(max_occ + 1, len(scan_parameters)))
        if index == 0:
            hist = heatmap
        else:
            hist += heatmap
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    fig.patch.set_facecolor('white')
    if len(scan_parameters) > 1:
        scan_parameter_dist = (np.amax(scan_parameters) - np.amin(scan_parameters)) / (len(scan_parameters) - 1)
    else:
        scan_parameter_dist = 0
    extent = [yedges[0] - scan_parameter_dist / 2, yedges[-1] * x_scale + scan_parameter_dist / 2, xedges[-1] * y_scale + 0.5, xedges[0] - 0.5]
    norm = colors.LogNorm()
    im = ax.imshow(hist, interpolation='nearest', aspect="auto", cmap=cmap, extent=extent, norm=norm)
    ax.invert_yaxis()
    if min_x is not None or max_x is not None:
        ax.set_xlim((min_x if min_x is not None else np.amin(scan_parameters), max_x if max_x is not None else np.amax(scan_parameters)))
    fig.colorbar(im)
    ax.set_title(title + ' for %d pixel(s)' % (n_pixel - np.count_nonzero(occ_mask)))
    if scan_parameter_name is None:
        ax.set_xlabel('Scan parameter')
    else:
        ax.set_xlabel(scan_parameter_name)
    ax.set_ylabel(ylabel)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #28
0
def subplot_demo():
    f = Figure()
    t = numpy.arange(0.0, 3.0, 0.01)
    s1 = numpy.sin(2 * numpy.pi * t)
    s2 = numpy.zeros(t.shape, numpy.Float)

    a1 = Subplot(211)
    a1.plot(t, s1)
    a1.set_title('And now for something completely different')

    a2 = Subplot(212)
    a2.plot(t, s2)
    a2.set_xlabel('time (s)')

    f.add_axis(a1)
    f.add_axis(a2)
    f.show()
Example #29
0
def subplot_demo():
    f = Figure()
    t = numpy.arange(0.0,3.0,0.01)
    s1 = numpy.sin(2*numpy.pi*t)
    s2 = numpy.zeros(t.shape, numpy.Float)

    a1 = Subplot(211)
    a1.plot(t,s1)
    a1.set_title('And now for something completely different')

    a2 = Subplot(212)
    a2.plot(t,s2)
    a2.set_xlabel('time (s)')

    f.add_axis(a1)
    f.add_axis(a2)
    f.show()
Example #30
0
def plot_cluster_tot_size(hist, z_max=None, filename=None):
    tot_max = min(50, hist.shape[0])
    cluster_max = min(20, hist.shape[1])
    hist = hist[0:tot_max, 0:min(6, hist.shape[1])]  # limit size
    if z_max is None:
        z_max = math.ceil(np.ma.max(hist))
    if z_max < 1 or hist.all() is np.ma.masked or np.allclose(0, hist):
        z_max = 1.0
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    extent = [-0.5, cluster_max - 0.5, tot_max - 0.5, -0.5]
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    cmap = cm.get_cmap('cool')
    cmap.set_bad('w', 1.0)
    norm = colors.BoundaryNorm(bounds, cmap.N)
    im = ax.imshow(hist,
                   aspect="auto",
                   interpolation='none',
                   cmap=cmap,
                   norm=norm,
                   extent=extent)  # for monitoring
    ax.set_title(
        'Cluster size and cluster ToT' + r' ($\Sigma$ = %d)' %
        (np.sum(hist) // 2))  # cluster size 0 includes all hits, divide by 2
    ax.set_xlabel('cluster size')
    ax.set_ylabel('cluster ToT')

    ax.invert_yaxis()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.1)
    cb = fig.colorbar(im,
                      cax=cax,
                      ticks=np.linspace(start=0,
                                        stop=z_max,
                                        num=9,
                                        endpoint=True))
    cb.set_label("#")
    fig.patch.set_facecolor('white')
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #31
0
    def plot(self, target_fig=None, fname=None, chs=None):
        """
        plot - plot the result of an ODMR measurement
        if ax is supplied, plot into ax. Create a new figure otherwise
        if ax is none (new figure), the new figure is displayed by default.
        If a filename string fname is given, the figure is saved to this file and display is suppressed
        fname is an absolute path. No check or indexing is performed to prevent overwriting of existing files
        """

        if chs is None:
            chs = []
        if target_fig is None:
            fig = Figure()
        else:
            fig = target_fig
        fig.clear()
        axis = fig.add_subplot(111)
        if 'temp' in chs:
            axis.set_xlabel("Time (s)")
            axis.set_ylabel("Temperature (C)")
            if self.ser is None:
                xval, yval = range(
                    self.n_data_points), [0] * self.n_data_points
            else:
                xval, yval, _ = self.ser.get_serial_data(0)
                yval = yval * 100
            axis.plot(xval, yval, lw=1.3)
        if 'power' in chs:
            axis.set_xlabel("Time (s)")
            axis.set_ylabel("Illumination (W/m2)")
            for i in [1, 2, 3, 4]:
                if self.ser is None:
                    xval, yval = range(
                        self.n_data_points), [0] * self.n_data_points
                else:
                    xval, yval, _ = self.ser.get_serial_data(i)
                axis.plot(xval, yval, lw=1.3)
        if target_fig is None:
            if fname is not None:
                fig.tight_layout()
                fig.savefig(fname)
                plt.close(fig)
            else:
                fig.show()
        return fig
Example #32
0
def plot_profile_histogram(x, y, n_bins=100, title=None, x_label=None, y_label=None, log_y=False, filename=None):
    '''Takes 2D point data (x,y) and creates a profile histogram similar to the TProfile in ROOT. It calculates
    the y mean for every bin at the bin center and gives the y mean error as error bars.

    Parameters
    ----------
    x : array like
        data x positions
    y : array like
        data y positions
    n_bins : int
        the number of bins used to create the histogram
    '''
    if len(x) != len(y):
        raise ValueError('x and y dimensions have to be the same')
    n, bin_edges = np.histogram(x, bins=n_bins)  # needed to calculate the number of points per bin
    sy = np.histogram(x, bins=n_bins, weights=y)[0]  # the sum of the bin values
    sy2 = np.histogram(x, bins=n_bins, weights=y * y)[0]  # the quadratic sum of the bin values
    bin_centers = (bin_edges[1:] + bin_edges[:-1]) / 2  # calculate the bin center for all bins
    mean = sy / n  # calculate the mean of all bins
    std = np.sqrt((sy2 / n - mean * mean))  # TODO: no understood, need check if this is really the standard deviation
    #     std_mean = np.sqrt((sy2 - 2 * mean * sy + mean * mean) / (1*(n - 1)))  # this should be the formular ?!
    std_mean = std / np.sqrt((n - 1))
    mean[np.isnan(mean)] = 0.
    std_mean[np.isnan(std_mean)] = 0.

    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.errorbar(bin_centers, mean, yerr=std_mean, fmt='o')
    ax.set_title(title)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_y:
        ax.yscale('log')
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #33
0
def finalize_plot(
        fig: Figure,
        ax: Axes,
        xlabel: str = None,
        ylabel: str = None,
        title: str = None,
        filename: str = None):
    """
    set profile plot details and show plot or save to file.
    """

    if xlabel:
        ax.set_xlabel(xlabel)

    if ylabel:
        # ax.set_ylabel("Relative Elevation (m)")
        ax.set_ylabel(ylabel)

    # fig_size_inches = 6.25
    # aspect_ratio = 3
    fig_size_inches = 12.5
    aspect_ratio = 4
    cbar_L = "None"

    [fig_size_inches, map_axes, cbar_axes] = MapFigureSizer(
        fig_size_inches,
        aspect_ratio,
        cbar_loc=cbar_L,
        title=title is not None)

    plt.title(title)
    fig.set_size_inches(fig_size_inches[0], fig_size_inches[1])
    ax.set_position(map_axes)

    if filename is None:
        fig.show()
    elif filename.endswith('.pdf'):
        plt.savefig(filename, format='pdf', dpi=600)
        plt.clf()
    else:
        plt.savefig(filename, format='png', dpi=300)
        plt.clf()
Example #34
0
def finalize(fig: Figure, filename: Optional[str] = None):
    """Show and/or save the figure, and close(dispose) it afterwards.

    :param Figure fig: Figure object to manipulate
    :param str filename: (optional) file name to save to
    :return: absolute file name, or None if none was produced
    :rtype: str
    """
    if output_mode == "both":
        raise NotImplementedError(f"Unsupported due to errors with tight_layout")
    do_save = filename and (output_mode == "auto" or output_mode == "file")
    do_show = output_mode == "interactive" or (output_mode == "auto" and not filename)
    if do_show:
        fig.show()
    if do_save:
        filename = file.expand_relative(filename, output_location)
        fig.savefig(filename)
    if do_show or do_save:
        plt.close(fig)
    return filename
Example #35
0
def plot_occupancy(hist, title='Occupancy', z_max=None, filename=None):
    if z_max == 'median':
        z_max = 2 * np.ma.median(hist)
    elif z_max == 'maximum' or z_max is None:
        z_max = np.ma.max(hist)
    if z_max < 1 or hist.all() is np.ma.masked:
        z_max = 1.0

    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.set_adjustable('box-forced')
    extent = [0.5, 80.5, 336.5, 0.5]
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    if z_max == 'median':
        cmap = cm.get_cmap('coolwarm')
    else:
        cmap = cm.get_cmap('cool')
    cmap.set_bad('w', 0.0)
    norm = colors.BoundaryNorm(bounds, cmap.N)

    im = ax.imshow(hist, interpolation='nearest', aspect='auto', cmap=cmap, norm=norm, extent=extent)  # TODO: use pcolor or pcolormesh
    ax.set_ylim((336.5, 0.5))
    ax.set_xlim((0.5, 80.5))
    ax.set_title(title + r' ($\Sigma$ = %d)' % (0 if hist.all() is np.ma.masked else np.ma.sum(hist)))
    ax.set_xlabel('Column')
    ax.set_ylabel('Row')

    divider = make_axes_locatable(ax)

    cax = divider.append_axes("right", size="5%", pad=0.1)
    cb = fig.colorbar(im, cax=cax, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True))
    cb.set_label("#")

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #36
0
def plot_three_way(hist, title, filename=None, x_axis_title=None, minimum=None, maximum=None, bins=101, cmap=None):  # the famous 3 way plot (enhanced)
    if cmap is None:
        if maximum == 'median' or maximum is None:
            cmap = cm.get_cmap('coolwarm')
        else:
            cmap = cm.get_cmap('cool')
    # TODO: set color for bad pixels
    # set nan to special value
    # masked_array = np.ma.array (a, mask=np.isnan(a))
    # cmap = matplotlib.cm.jet
    # cmap.set_bad('w',1.)
    # ax.imshow(masked_array, interpolation='nearest', cmap=cmap)
    if minimum is None:
        minimum = 0.0
    elif minimum == 'minimum':
        minimum = np.ma.min(hist)
    if maximum == 'median' or maximum is None:
        maximum = 2 * np.ma.median(hist)
    elif maximum == 'maximum':
        maximum = np.ma.max(hist)
    if maximum < 1 or hist.all() is np.ma.masked:
        maximum = 1.0

    x_axis_title = '' if x_axis_title is None else x_axis_title
    fig = Figure()
    FigureCanvas(fig)
    fig.patch.set_facecolor('white')
    ax1 = fig.add_subplot(311)
    create_2d_pixel_hist(fig, ax1, hist, title=title, x_axis_title="column", y_axis_title="row", z_min=minimum if minimum else 0, z_max=maximum, cmap=cmap)
    ax2 = fig.add_subplot(312)
    create_1d_hist(fig, ax2, hist, bins=bins, x_axis_title=x_axis_title, y_axis_title="#", x_min=minimum, x_max=maximum)
    ax3 = fig.add_subplot(313)
    create_pixel_scatter_plot(fig, ax3, hist, x_axis_title="channel=row + column*336", y_axis_title=x_axis_title, y_min=minimum, y_max=maximum)
    fig.tight_layout()
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #37
0
def plot_pixel_matrix(hist, title="Hit correlation", filename=None):
    logging.info("Plotting pixel matrix: %s", title)
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.set_title(title)
    ax.set_xlabel('Col')
    ax.set_ylabel('Row')
    cmap = cm.get_cmap('jet')
    ax.imshow(hist.T, aspect='auto', cmap=cmap, interpolation='nearest')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    z_max = np.max(hist)
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    norm = colors.BoundaryNorm(bounds, cmap.N)
    fig.colorbar(boundaries=bounds, cmap=cmap, norm=norm, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True), cax=cax)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #38
0
 def plot(self, target_fig=None, fname=None):
     if target_fig is None:
         fig = Figure()
     else:
         fig = target_fig
     fig.clear()
     axis = fig.add_subplot(111)
     axis.set_xlabel("Voltage (V)")
     axis.set_ylabel("Current (A)")
     if self.gpib_port == 'dummy':
         xval = self.voltages_set
         yval = [0] * self.n_data_points
     else:
         xval = self.voltages_set
         yval = self.currents
     axis.plot(xval, yval, lw=1.3)
     if target_fig is None:
         if fname is not None:
             fig.tight_layout()
             fig.savefig(fname)
             plt.close(fig)
         else:
             fig.show()
     return fig
Example #39
0
def plot_three_way(hist,
                   title,
                   filename=None,
                   x_axis_title=None,
                   minimum=None,
                   maximum=None,
                   bins=101,
                   cmap=None):  # the famous 3 way plot (enhanced)
    if cmap is None:
        if maximum == 'median' or maximum is None:
            cmap = cm.get_cmap('coolwarm')
        else:
            cmap = cm.get_cmap('cool')
    # TODO: set color for bad pixels
    # set nan to special value
    # masked_array = np.ma.array (a, mask=np.isnan(a))
    # cmap = matplotlib.cm.jet
    # cmap.set_bad('w',1.0)
    # ax.imshow(masked_array, interpolation='none', cmap=cmap)
    hist = np.ma.masked_invalid(hist)
    if minimum is None:
        minimum = 0.0
    elif minimum == 'minimum':
        minimum = max(0, np.ma.min(hist))
    if maximum == 'median' or maximum is None:
        maximum = max(1, 2 * np.ma.median(hist))
    elif maximum == 'maximum':
        maximum = max(1, np.ma.max(hist))
    if maximum < 1 or hist.all() is np.ma.masked or np.allclose(0, hist):
        maximum = 1.0

    x_axis_title = '' if x_axis_title is None else x_axis_title
    fig = Figure()
    FigureCanvas(fig)
    fig.patch.set_facecolor('white')
    ax1 = fig.add_subplot(311)
    create_2d_pixel_hist(fig,
                         ax1,
                         hist,
                         title=title,
                         x_axis_title="column",
                         y_axis_title="row",
                         z_min=minimum if minimum else 0,
                         z_max=maximum,
                         cmap=cmap)
    ax2 = fig.add_subplot(312)
    create_1d_hist(ax2,
                   hist,
                   bins=bins,
                   x_axis_title=x_axis_title,
                   y_axis_title="#",
                   x_min=minimum,
                   x_max=maximum)
    ax3 = fig.add_subplot(313)
    create_pixel_scatter_plot(ax3,
                              hist,
                              x_axis_title="channel=row + column*336",
                              y_axis_title=x_axis_title,
                              y_min=minimum,
                              y_max=maximum)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #40
0
class HKEPlotter(object):
    """
    A class for creating and serving up the figure objects associated
    with plots from HKE data.

    Example usage:
    >>> model = HKEModel()
    >>> model.loadfile('hke_20130201_001.dat', 'U02728.txt')
    >>> plotter = HKEPlotter(model)
    >>>
    """
    def __init__(self, model=None):
        self.model = model
        self.figure = None
        self.axes = None
        self.lines = []
        self.axvlines = []
        self.axhlines = []
        self.cc = mpl.rcParams['axes.color_cycle']
        self.usedcc = []

    def makefigure(self, figsize=(4., 4.), dpi=100, **kwargs):
        self.figure = Figure(figsize=figsize, dpi=dpi, **kwargs)
        return self.figure

    def add_subplot(self, *args, **kwargs):
        if type(self.figure) is not Figure:
            print "Figure not yet initialized. Make the figure first."
            return

        self.axes = self.figure.add_subplot(*args, **kwargs)
        return self.axes

    def getnextcolor(self):
        """
        Gets the next unused color in the colormap.
        """
        self.usedcc = [line.get_c() for line in self.axes.lines]
        for c in self.cc:
            if c not in self.usedcc:
                return c

        # Only gets here if all colors already used...
        i = len(self.axes.lines)
        numc = len(self.cc)
        i = i % numc
        return self.cc[i]

    def plot(self, *args, **kwargs):
        color = self.getnextcolor()
        newline, = self.axes.plot(*args, color=color, **kwargs)

        linewidth = newline.get_linewidth()

        newlinedict = {'line': newline, 'color': color, 'vlines': [],
                       'hlines': [], 'linewidth': linewidth,
                       'highlighted': False, 'highlight factor': 1.0}
        self.lines.append(newlinedict)

        return newline

    def resetplot(self):
        self.clearplot()
        self.axes.clear()

    def clearplot(self):
        self._killlines()
        self.lines = []

    def _killlines(self):
        for ld in self.lines:
            line = ld['line']
            self.axes.lines.remove(line)
        self.usedcc = []

    def _checkfigure(self):
        """
        Checks to see if the figure has been initialized
        sufficiently. Raises a HKEPlotterNotInitializedError if this
        check fails.
        """
        if ((type(self.figure) is Figure) and
            (type(self.axes) in (Subplot, Axes))):
            return
        else:
            raise HKEPlotterNotInitializedError(self.figure,
                                                self.axes)

    # def RvsTPlot(self, datafile, dataRname, index, description='',
    #              Tcline=True):
    def RvsTPlot(self, datafile, boardindex, chindex, description='',
                 Tcline=True):
        """
        Makes an R vs T plot from a specified datafile.
        """
        try:
            self._checkfigure()
        except HKEPlotterNotInitializedError(self.figure,
                                             self.axes) as e:
            print e

        temperature = datafile['temperature']
        Ts = temperature['Ts']

        board = datafile['boards'][boardindex]
        register = board['registers'][chindex]

        dataR = board['data']
        Rs = dataR[chindex]

        chdesc = register['name']
        print "description = ", repr(description) #DELME
        if description:
            description = ' - ' + description
        print "chdesc = ", repr(chdesc) #DELME
        if chdesc:
            description = description + ' - ' + chdesc

        label = 'Ch {i}{d}'.format(i=chindex, d=description)
        line = self.plot(Ts, Rs, label=label)

        linedict = self._get_linedict(line)
        linedict['label'] = label

        Tc = board['Tcs'][chindex]
        linedict['Tc'] = Tc

        if Tcline:
            self.addTcline(line, Tc)

        return linedict

        # Ts = datafile['Temperatures']
        # dataR = datafile[dataRname]
        # Rs = dataR[index]

        # sidenum = dataRname.split()[1]
        # desclist = datafile['Side {s} Descriptions'.format(s=sidenum)]
        # chdesc = desclist[index]

        # if description:
        #     description = ' - ' + description
        # if chdesc:
        #     description = description + ' - ' + chdesc

        # label = 'Ch {i}{d}'.format(i=index, d=description)
        # line = self.plot(Ts, Rs, label=label)

        # linedict = self._get_linedict(line)
        # linedict['label'] = label

        # Tcs = datafile['Side {i} Transition Temperatures'.format(i=sidenum)]
        # Tc = Tcs[index]
        # linedict['Tc'] = Tc

        # if Tcline:
        #     self.addTcline(line, Tc)

        # return linedict

    def _get_linedict(self, line):
        """
        Finds and returns the line dictionary in self.lines that
        contains the specified line.
        """
        if (isinstance(line, dict) and
            (line in self.lines)):
            return line
        for linedict in self.lines:
            if line in linedict.itervalues():
                ld = linedict
        try:
            return ld
        except NameError:
            raise HKEPlotterLineDoesNotExistError(line)

    def addTcline(self, line, temperature=None):
        """
        Add a vertical line corresponding to line at the specified
        temperature.
        """
        self._checkfigure()
        ld = self._get_linedict(line)
        line = ld['line']
        if temperature is None:
            temperature = ld['Tc']
        color = line.get_c()
        axvl = self.axes.axvline(temperature, color=color, ls='--')
        # self.axvlines.append(axvl)
        ld['vlines'].append(axvl)

    def delTcline(self, line):
        """
        Remove a vertical line corresponding to line.
        """
        self._checkfigure()
        ld = self._get_linedict(line)
        for vline in ld['vlines']:
            vline.remove()
        ld['vlines'] = []

    def highlight_line(self, line, factor=1.5):
        """
        Highlight a line by making its linewidth slightly larger.
        """
        self._checkfigure()
        ld = self._get_linedict(line)
        ld['highlighted'] = True
        ld['highlight factor'] = factor
        self.update_lines()

    def unhighlight_line(self, line):
        """
        Remove the highlighting of a line by restoring its linewidth
        to the original size.
        """
        self._checkfigure()
        ld = self._get_linedict(line)
        ld['highlighted'] = False
        self.update_lines()

    def delete_line(self, line):
        """
        Remove a line and all lines related to it from the figure.
        """
        self._checkfigure()
        ld = self._get_linedict(line)
        self.delTcline(ld)
        line = ld['line']
        line.remove()
        self.lines.remove(ld)

    def update_lines(self):
        """
        Update all of the properties of the lines to match those
        specified by the lines dictionaries.
        """
        self._checkfigure()
        for ld in self.lines:
            line = ld['line']

            color = ld['color']
            line.set_color(color)

            lw = ld['linewidth']
            hlf = ld['highlight factor']
            highlight = hlf if ld['highlighted'] else 1.0
            lw = lw*highlight
            line.set_linewidth(lw)

            for vline in ld['vlines']:
                vline.set_color(color)
                vline.set_linestyle('--')
                vline.set_linewidth(lw)

            for hline in ld['vlines']:
                hline.set_color(color)
                hline.set_linestyle('--')
                hline.set_linewidth(lw)

    def xscale(self, newscale, linthreshx=1.e-4):
        """
        Change the scale of the x axis.
        """
        self._checkfigure()
        if newscale == 'symlog':
            self.axes.set_xscale(newscale, linthreshx=linthreshx)
        else:
            self.axes.set_xscale(newscale)

    def yscale(self, newscale, linthreshy=1.e-4):
        """
        Change the scale of the y axis.
        """
        self._checkfigure()
        if newscale == 'symlog':
            self.axes.set_yscale(newscale, linthreshy=linthreshy)
        else:
            self.axes.set_yscale(newscale)

    def autorange(self):
        """
        Automatically adjusts the range of the x and y axes to fit the
        data.
        """
        self._checkfigure()
        self.axes.autoscale_view(True)

    def legend(self, loc=None):
        """
        Create a legend.
        """
        self._checkfigure()
        self.axes.legend(loc=loc)

    def hide_legend(self):
        """
        Hide the legend.
        """
        self._checkfigure()
        leg = self.axes.get_legend()
        if leg:
            leg.set_visible(False)

    def title(self, title):
        """
        Set the title.
        """
        self._checkfigure()
        self.axes.set_title(title)

    def xlabel(self, xlabel):
        """
        Set the x label.
        """
        self._checkfigure()
        self.axes.set_xlabel(xlabel)

    def ylabel(self, ylabel):
        """
        Set the y label.
        """
        self._checkfigure()
        self.axes.set_ylabel(ylabel)

    def savefig(self, filename, dpi=300):
        """
        Save a figure to disk with the specified filename.
        """
        self._checkfigure()
        self.figure.savefig(filename, dpi=dpi)

    def draw(self):
        """
        Show and redraw the figure. Generally not useful if HKEPlotter
        is being used to serve up figures to a different front-end,
        but is useful for interactive use of HKEPlotter on its own.
        """
        self.figure.show()
        self.figure.canvas.draw()
Example #41
0
def plot_scurves(occupancy_hist,
                 scan_parameters,
                 title='S-curves',
                 ylabel='Occupancy',
                 max_occ=None,
                 scan_parameter_name=None,
                 min_x=None,
                 max_x=None,
                 extend_bin_width=True,
                 filename=None):
    occ_mask = np.all(
        (occupancy_hist == 0), axis=2) | np.all(np.isnan(occupancy_hist),
                                                axis=2)
    occupancy_hist = np.ma.masked_invalid(occupancy_hist)
    if max_occ is None:
        if np.allclose(occupancy_hist, 0.0) or np.all(occ_mask == 1):
            max_occ = 0.0
        else:
            max_occ = math.ceil(
                2 * np.ma.median(np.amax(occupancy_hist[~occ_mask], axis=1)))
    if len(occupancy_hist.shape) < 3:
        raise ValueError('Found array with shape %s' %
                         str(occupancy_hist.shape))

    n_pixel = occupancy_hist.shape[0] * occupancy_hist.shape[1]
    scan_parameters = np.array(scan_parameters)
    if extend_bin_width and len(scan_parameters) >= 2:
        # adding mirror scan parameter for plotting range -0.5 ...
        scan_parameters = np.r_[-scan_parameters[0] - 1.0, scan_parameters]
        dist = (scan_parameters[1:] - scan_parameters[:-1].astype(np.float))
        min_dist = np.minimum(np.r_[dist[0], dist[:]], np.r_[dist[:],
                                                             dist[-1]]) / 2
        min_dist = np.minimum(np.r_[(scan_parameters[0] + 0.5) * 2, dist[:]],
                              np.r_[dist[:], dist[-1]]) / 2
        # removing mirror scan parameter
        x_bins = np.unique(
            np.dstack([scan_parameters - min_dist,
                       scan_parameters + min_dist]).flatten())[1:]
        scan_parameters = scan_parameters[1:]
    else:
        x_bins = np.arange(-0.5, max(scan_parameters) + 1.5)
    y_bins = np.arange(-0.5, max_occ + 1.5)

    for index, scan_parameter in enumerate(scan_parameters):
        compressed_data = np.ma.masked_array(occupancy_hist[:, :, index],
                                             mask=occ_mask,
                                             copy=True).compressed()
        tmp_hist, yedges, xedges = np.histogram2d(
            compressed_data, [scan_parameter] * compressed_data.shape[0],
            bins=(y_bins, x_bins))
        if index == 0:
            hist = tmp_hist
        else:
            hist += tmp_hist

    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    fig.patch.set_facecolor('white')
    cmap = cm.get_cmap('cool')
    if np.allclose(hist, 0.0) or hist.max() <= 1:
        z_max = 1.0
    else:
        z_max = hist.max()
    # for small z use linear scale, otherwise log scale
    if z_max <= 10.0:
        bounds = np.linspace(start=0.0, stop=z_max, num=255, endpoint=True)
        norm = colors.BoundaryNorm(bounds, cmap.N)
    else:
        bounds = np.linspace(start=1.0, stop=z_max, num=255, endpoint=True)
        norm = colors.LogNorm()
    X, Y = np.meshgrid(xedges, yedges)
    im = ax.pcolormesh(X,
                       Y,
                       np.ma.masked_where(hist == 0, hist),
                       cmap=cmap,
                       norm=norm)
    ax.axis([xedges[0], xedges[-1], yedges[0], yedges[-1]])
    if min_x is not None or max_x is not None:
        ax.set_xlim((min_x if min_x is not None else np.min(scan_parameters),
                     max_x if max_x is not None else np.max(scan_parameters)))
    if z_max <= 10.0:
        cb = fig.colorbar(im,
                          ticks=np.linspace(start=0.0,
                                            stop=z_max,
                                            num=min(11,
                                                    math.ceil(z_max) + 1),
                                            endpoint=True),
                          fraction=0.04,
                          pad=0.05)
    else:
        cb = fig.colorbar(im, fraction=0.04, pad=0.05)
    cb.set_label("#")
    ax.set_title(title + ' for %d pixel(s)' %
                 (n_pixel - np.count_nonzero(occ_mask)))
    if scan_parameter_name is None:
        ax.set_xlabel('Scan parameter')
    else:
        ax.set_xlabel(scan_parameter_name)
    ax.set_ylabel(ylabel)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #42
0
def plot_linear_relation(x,
                         y,
                         x_err=None,
                         y_err=None,
                         title=None,
                         point_label=None,
                         legend=None,
                         plot_range=None,
                         plot_range_y=None,
                         x_label=None,
                         y_label=None,
                         y_2_label=None,
                         log_x=False,
                         log_y=False,
                         size=None,
                         filename=None):
    ''' Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation to this line is also plotted, showing the offset.

     Parameters
    ----------
    x, y, x_err, y_err: iterable

    filename: string, PdfPages object or None
        PdfPages file object: plot is appended to the pdf
        string: new plot file with the given filename is created
        None: the plot is printed to screen
    '''
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    if x_err is not None:
        x_err = [x_err, x_err]
    if y_err is not None:
        y_err = [y_err, y_err]
    ax.set_title(title)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_x:
        ax.set_xscale('log')
    if log_y:
        ax.set_yscale('log')
    if plot_range:
        ax.set_xlim((min(plot_range), max(plot_range)))
    if plot_range_y:
        ax.set_ylim((min(plot_range_y), max(plot_range_y)))
    if legend:
        fig.legend(legend, 0)
    ax.grid(True)
    ax.errorbar(x, y, xerr=x_err, yerr=y_err, fmt='o',
                color='black')  # plot points
    # label points if needed
    if point_label is not None:
        for X, Y, Z in zip(x, y, point_label):
            ax.annotate('{}'.format(Z),
                        xy=(X, Y),
                        xytext=(-5, 5),
                        ha='right',
                        textcoords='offset points')
    line_fit, _ = np.polyfit(x, y, 1, full=False, cov=True)
    fit_fn = np.poly1d(line_fit)
    ax.plot(x, fit_fn(x), '-', lw=2, color='gray')
    setp(ax.get_xticklabels(),
         visible=False)  # remove ticks at common border of both plots

    divider = make_axes_locatable(ax)
    ax_bottom_plot = divider.append_axes("bottom", 2.0, pad=0.0, sharex=ax)

    ax_bottom_plot.bar(x,
                       y - fit_fn(x),
                       align='center',
                       width=np.amin(np.diff(x)) / 2,
                       color='gray')
    #     plot(x, y - fit_fn(x))
    ax_bottom_plot.grid(True)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_2_label is not None:
        ax.set_ylabel(y_2_label)

    ax.set_ylim((-np.amax(np.abs(y - fit_fn(x)))),
                (np.amax(np.abs(y - fit_fn(x)))))

    ax.plot(ax.set_xlim(), [0, 0], '-', color='black')
    setp(ax_bottom_plot.get_yticklabels()[-2:-1], visible=False)

    if size is not None:
        fig.set_size_inches(size)

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    elif filename:
        fig.savefig(filename, bbox_inches='tight')

    return fig
Example #43
0
 def show(self, warn=True):
     utils.message('Showing figure "%s"' % self.name)
     return PLTFigure.show(self, warn=warn)
Example #44
0
def plot_fancy_occupancy(hist, z_max=None, filename=None):
    if z_max == 'median':
        median = np.ma.median(hist)
        z_max = median * 2  # round_to_multiple(median * 2, math.floor(math.log10(median * 2)))
    elif z_max == 'maximum' or z_max is None:
        maximum = np.ma.max(hist)
        z_max = maximum  # round_to_multiple(maximum, math.floor(math.log10(maximum)))
    if z_max < 1 or hist.all() is np.ma.masked:
        z_max = 1

    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    extent = [0.5, 80.5, 336.5, 0.5]
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    cmap = cm.get_cmap('jet')
    cmap.set_bad('w')
    norm = colors.BoundaryNorm(bounds, cmap.N)

    im = ax.imshow(hist, interpolation='nearest', aspect='auto', cmap=cmap, norm=norm, extent=extent)  # TODO: use pcolor or pcolormesh
    ax.set_ylim((336.5, 0.5))
    ax.set_xlim((0.5, 80.5))
    ax.set_xlabel('Column')
    ax.set_ylabel('Row')

    # create new axes on the right and on the top of the current axes
    # The first argument of the new_vertical(new_horizontal) method is
    # the height (width) of the axes to be created in inches.
    divider = make_axes_locatable(ax)
    axHistx = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
    axHisty = divider.append_axes("right", 1.2, pad=0.2, sharey=ax)

    cax = divider.append_axes("right", size="5%", pad=0.1)
    cb = fig.colorbar(im, cax=cax, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True))
    cb.set_label("#")
    # make some labels invisible
    setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(), visible=False)
    hight = np.ma.sum(hist, axis=0)

    axHistx.bar(left=range(1, 81), height=hight, align='center', linewidth=0)
    axHistx.set_xlim((0.5, 80.5))
    if hist.all() is np.ma.masked:
        axHistx.set_ylim((0, 1))
    axHistx.locator_params(axis='y', nbins=3)
    axHistx.ticklabel_format(style='sci', scilimits=(0, 4), axis='y')
    axHistx.set_ylabel('#')
    width = np.ma.sum(hist, axis=1)

    axHisty.barh(bottom=range(1, 337), width=width, align='center', linewidth=0)
    axHisty.set_ylim((336.5, 0.5))
    if hist.all() is np.ma.masked:
        axHisty.set_xlim((0, 1))
    axHisty.locator_params(axis='x', nbins=3)
    axHisty.ticklabel_format(style='sci', scilimits=(0, 4), axis='x')
    axHisty.set_xlabel('#')

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #45
0
def plot_fancy_occupancy(hist, z_max=None, filename=None):
    if z_max == 'median':
        z_max = 2 * np.ma.median(hist)
    elif z_max == 'maximum' or z_max is None:
        z_max = np.ma.max(hist)
    if z_max < 1 or hist.all() is np.ma.masked or np.allclose(0, hist):
        z_max = 1.0

    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    extent = [0.5, 80.5, 336.5, 0.5]
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    if z_max == 'median':
        cmap = cm.get_cmap('coolwarm')
    else:
        cmap = cm.get_cmap('cool')
    cmap.set_bad('w', 1.0)
    norm = colors.BoundaryNorm(bounds, cmap.N)

    im = ax.imshow(hist,
                   interpolation='none',
                   aspect='auto',
                   cmap=cmap,
                   norm=norm,
                   extent=extent)  # TODO: use pcolor or pcolormesh
    ax.set_ylim((336.5, 0.5))
    ax.set_xlim((0.5, 80.5))
    ax.set_xlabel('Column')
    ax.set_ylabel('Row')

    # create new axes on the right and on the top of the current axes
    # The first argument of the new_vertical(new_horizontal) method is
    # the height (width) of the axes to be created in inches.
    divider = make_axes_locatable(ax)
    axHistx = divider.append_axes("top", 1.2, pad=0.2, sharex=ax)
    axHisty = divider.append_axes("right", 1.2, pad=0.2, sharey=ax)

    cax = divider.append_axes("right", size="5%", pad=0.1)
    cb = fig.colorbar(im,
                      cax=cax,
                      ticks=np.linspace(start=0,
                                        stop=z_max,
                                        num=9,
                                        endpoint=True))
    cb.set_label("#")
    # make some labels invisible
    setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(), visible=False)
    height = np.ma.sum(hist, axis=0)

    axHistx.bar(range(1, 81), height, align='center', linewidth=0)
    axHistx.set_xlim((0.5, 80.5))
    if hist.all() is np.ma.masked or np.allclose(0, hist):
        axHistx.set_ylim((0, 1))
    else:
        x_c_max = np.ceil(np.percentile(height, 99))
        axHistx.set_ylim(0, max(1, x_c_max))
    axHistx.locator_params(axis='y', nbins=3)
    axHistx.ticklabel_format(style='sci', scilimits=(0, 4), axis='y')
    axHistx.set_ylabel('#')
    width = np.ma.sum(hist, axis=1)

    axHisty.barh(range(1, 337), width, align='center', linewidth=0)
    axHisty.set_ylim((336.5, 0.5))
    if hist.all() is np.ma.masked or np.allclose(0, hist):
        axHisty.set_xlim((0, 1))
    else:
        y_c_max = np.ceil(np.percentile(width, 99))
        axHisty.set_xlim(0, max(1, y_c_max))
    axHisty.locator_params(axis='x', nbins=3)
    axHisty.ticklabel_format(style='sci', scilimits=(0, 4), axis='x')
    axHisty.set_xlabel('#')

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
Example #46
0
class PlotWrap(object):
    __debug = False
    __keyArgDict =  {
        'title' : None,
        'winTitle' : None,
        'xlabel' : None,
        'xticks' : None,
        'ylabel' : None,
        'yticks' : None,
        'ylog' : False, 
        'xlog' : False, 
        'ybound' : (None,None),
        'xbound' : (None,None),
        'legend' : None,
        'style' : None,
        'aging' : None,
        'alphaMin' : 0.02,
        'agingCull' : True,
        'bball' : None,
        'accum' : False,
        'showByDefault' : True,
        'makeWinByDefault': True,
        'axes' :  None,
        'axesRect' :  None,
        'axprops' :  {},
        'figsize' : (5,4),
        'dpi' : 100,
        'window' :  None,
        'as3D' : False,
        }
    def __init__(self,
                 **keyArgs
                 ):
        
        # defaults
        for parm, val in self.__keyArgDict.iteritems():
            self.__setattr__(parm, val)
        #
        # parse keyword args
        for keyArg in self.getKeyArgList():
            if keyArgs.has_key(keyArg):
                self.__setattr__(keyArg, keyArgs.pop(keyArg))
        if len(keyArgs) > 0:
            raise RuntimeError, 'unparsed keyword args : '+str(keyArgs)
        #
        window = self.window
        del self.window
        #
        self.x_accum = self.accum
        del self.accum
        #
        axes = self.axes
        del self.axes
        
        self.x_prev = None
        self.x_store = [[],[]]

        self.win = None
        self.a   = None
        self.canvas = None
        
        self.ownCanvas = True
        if window is None:
            self.ownCanvas = True
            'checking self.showByDefault here causes trouble because it is hard to attach a figure to a window later for a general backend ***'
            if self.showByDefault or self.makeWinByDefault:
                # 'go ahead and make a window, using PlotWinP to increase backend flexibility'
                # self.win    = ...PlotWinP(as3D=self.as3D, figsize=self.figsize, dpi=self.dpi)
                # self.a      = self.win.getAxes(0)
                # self.f      = self.win.getFigure()
                # self.canvas = self.win.getCanvas()
                # self.a.set_autoscale_on(True)
                self.__checkWin()
                self.f = self.win.f
            else:
                from matplotlib.figure import Figure
                self.f = Figure(figsize=self.figsize, dpi=self.dpi)
            if self.as3D:
                import mpl_toolkits.mplot3d.axes3d as p3
                self.a = p3.Axes3D(self.f)
            else:
                if self.axesRect is None:
                    self.a = self.f.add_subplot(1, 1, 1, **self.axprops)
                else:
                    self.a = self.f.add_axes(self.axesRect, **self.axprops)
                
            if axes is not None:
                raise RuntimeError, 'do not specify axes when have not passed a window'
        else:
            self.ownCanvas = False
            self.win = window
            self.canvas = self.win.getCanvas()
            self.f = self.win.getFigure()
            if axes is None:
                if self.__debug: print 'using axprops: '+str(self.axprops)
                self.a = self.win.getNextAxes(rect=self.axesRect, attachPW=self, **self.axprops)
            elif isinstance(axes, int):
                self.a = self.win.getAxes(axes, **self.axprops)
            else:
                self.a = axes
        #
        self.clear() # sets labels and so forth

        # self.style = style # can be None
        # self.bball = bball # can be None
        #
        #self.aging = aging
        #self.agingCull = agingCull
        #self.alphaMin = alphaMin
        self.agingNumAge = -1
        if self.aging is not None:
            from math import log
            self.agingNumAge = max(int(log(self.alphaMin)/log(self.aging)),1)
        self.plotProps = {}
        # self.lineListList = [] # not needed, can, and should, use a.lines
        
        self.asImIJ = False
        # self.transform = None
        self.axIm = None
        self.__colorbar = None

        return
    def add_axes(self, arect, kwAddAxes={}, **kwarg):
        aNew = self.f.add_axes(arect, **kwAddAxes)
        # self.a.set_position((0.05, 0.05, 0.45, 0.9))
        new = self.__class__(window=self.win, axes=aNew, **kwarg)
        return new
    @classmethod
    def popKeyArgs(cls, kwargs):
        retval = {}
        for key in cls.getKeyArgList():
            if kwargs.has_key(key):
                retval[key] = kwargs.pop(key)
        return retval
    @classmethod
    def getKeyArgList(cls):
        return cls.__keyArgDict.keys()
    def __checkCanvas(self):
        'leave dead True, not checking for window, just for canvas'
        #from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
        if self.win is not None: return
        if self.canvas is not None: return

        from matplotlib.backends.backend_tkagg import FigureCanvasAgg
        
        self.canvas = FigureCanvasAgg(self.f)
        if hasattr(self.a,'mouse_init'):
            self.a.mouse_init()
        return

    def __checkWin(self):
        if self.win is not None: return
        winTitle = self.winTitle
        if winTitle is None : winTitle = self.title
        if winTitle is None : winTitle = 'plotWin'
        if hasattr(self,'f'):
            self.win = PlotWin(1,1,title=winTitle, relfigsize=self.figsize, figure=self.f, axesList=[self.a])
        else:
            self.win = PlotWin(1,1,title=winTitle, relfigsize=self.figsize, axesList=[self.a])
        #self.win = PlotWinP(title=winTitle, figure=self.f, axes=self.a)
        self.canvas = self.win.getCanvas()
        return
    def removeLines(self):
        lines = self.a.get_lines()
        for line in lines:
            line.remove()
        if self.showByDefault:
            self.show() # self.canvas.show()
        return
    def show(self):
        self.__checkWin()
        if self.legend is not None:
            pass # do not yet have this right
            # if isinstance(self.legend, str) or isinstance(self.legend, int): #  or hasattr(self.legend,'__len__')
            #     self.a.legend(loc=self.legend)
            # elif isinstance(self.legend, bool):
            #     self.a.legend()
            # elif isinstance(self.legend, list):
            #     self.a.legend(*self.legend)
            # elif isinstance(self.legend, dict):
            #     self.a.legend(**self.legend)
            # else:
            #     raise RuntimeError, 'do not know what to do with legend specification: '+str(self.legend)
        if hasattr(self.a,'mouse_init'):
            self.a.mouse_init()
        if hasattr(self.f, 'show'):
            self.f.show()
        elif hasattr(self.canvas, 'show'):
            self.canvas.show()
        else:
            raise RuntimeError, 'do not know how to do show'
        return
    def clear(self):
        self.asImIJ = False
        self.axIm = None
        # self.transform = None
        self.x_prev = None
        self.__colorbar = None
        self.x_store = [[],[]]
        if self.showByDefault:
            self.__checkWin()
        if self.a is not None:
            if hasattr(self.a,'mouse_init'):
                'doing a.clear() seems like it causes trouble with plotting collections?' 
                self.a.clear() # self.a.cla()
                self.a.set_autoscale_on(True)
            else:
                self.a.clear() # self.a.cla()
                self.a.set_autoscale_on(True)
        if self.xticks is not None:
            self.a.set_xticks(self.xticks)
        if self.title is not None:
            self.a.set_title(self.title)
        if self.xlabel is not None:
            self.a.set_xlabel(self.xlabel)  # r'X axis label $\mu\mbox{lentz}$'
            if self.win is not None:
                'make some room for the label'
                self.win.haveXLabels()
        if self.yticks is not None:
            self.a.set_yticks(self.yticks)
        if self.xlog: self.a.set_xscale('log')
        if self.ylog: self.a.set_yscale('log')
        #self.a.set_ybound(self.ybound)
        self.a.set_ylim(ymin=self.ybound[0], ymax=self.ybound[1])
        self.a.set_xlim(xmin=self.xbound[0], xmax=self.xbound[1])
        if self.ylabel is not None:
            self.a.set_ylabel(self.ylabel)
            if self.win is not None:
                'make some room for the label'
                self.win.haveYLabels()
        if self.legend is not None:
            pass # do not yet have this right
            # if isinstance(self.legend, str) or isinstance(self.legend, int): #  or hasattr(self.legend,'__len__')
            #     self.a.legend(loc=self.legend)
            # elif isinstance(self.legend, bool):
            #     self.a.legend()
            # elif isinstance(self.legend, list):
            #     self.a.legend(*self.legend)
            # elif isinstance(self.legend, dict):
            #     self.a.legend(**self.legend)
            # else:
            #     raise RuntimeError, 'do not know what to do with legend specification: '+str(self.legend)
        if self.a is not None:
            self.a.set_autoscale_on(True)
        if self.showByDefault:
            self.show() # self.canvas.show()
        return
    def setLegend(self, val=True):
        # if self.legend is None:
        #     self.legend = True
        # if val is not None:
        #     self.legend = val
        self.legend = val
        return
    def save(self, **keyArgs):
        '''make hardcopy of the current figure;
        specify filename or prefix keyword argument
        '''
        import numpy as num
        
        filename = None
        prefix = None
        if keyArgs.has_key('filename'):
            filename = keyArgs.pop('filename')
        if keyArgs.has_key('prefix'):
            prefix = keyArgs.pop('prefix')
            filename = prefix+'.pdf' # .eps
        
        if prefix is not None:
            'export data'
            if len(self.x_store[0]) > 0:
                dataFilename = prefix+'.data'
                from hexrd import arrayUtil
                try:
                    arrayUtil.writeArray(dataFilename, num.array(self.x_store))
                except:
                    import sys
                    print 'problem writing to '+dataFilename+' : '+str(self.x_store)
                    sys.exit(1)
        
        if not self.ownCanvas:
            if self.__debug:
                print 'skipping print_figure because this plot does not own its canvas'
        else:
            self.__checkCanvas()
            if filename is None:
                raise RuntimeError, 'need filename or prefix entry in keyArgs'
            #self.canvas.print_figure(filename, **keyArgs)
            self.f.savefig(filename, **keyArgs)
        
        return
    def destroy(self):
        'does not clean up self.a, just kills the window if this plot owns the window'
        if self.ownCanvas and self.win is not None:
            self.win.destroy()
        return
    def drawBBox(self, bbox, **kwargs):
        import numpy as num
        bbox_x = bbox[0]
        bbox_y = bbox[1]
        xBBox = num.array([ bbox_x[0], bbox_x[1], bbox_x[1], bbox_x[0], bbox_x[0] ])
        yBBox = num.array([ bbox_y[0], bbox_y[0], bbox_y[1], bbox_y[1], bbox_y[0] ])
        'go through call, instead of callXY, in case of asImIJ'
        self.__call__(xBBox, yBBox, **kwargs)
        return
    def __call__(self, *args, **keyArgs):
        import numpy as num
        noShow = False
        retVal = None
        # if keyArgs.has_key('transform'):
        #     'pop transform so that can keep it for other (overlaid) plots'
        #     self.transform = keyArgs.pop('transform')
        if keyArgs.has_key('noShow'):
            noShow = keyArgs.pop('noShow')
        if len(args) == 2:
            alphas = None
            if self.asImIJ:
                x = args[1]
                y = args[0]
            else:
                x = args[0]
                y = args[1]
            if keyArgs.has_key('alphas'):
                alphas = keyArgs.pop('alphas')
                assert len(args) == 2, 'len(args) != 2'
                assert len(alphas) == len(y), 'len(alphas) != len(y)'
                self.x_prev = None
                for iX in range(len(x)):
                    self.callXY([x[iX]],[y[iX]],alpha=alphas[iX],**keyArgs)
            else:
                self.callXY(x, y, **keyArgs)
        elif len(args) == 3:
            X = args[0]; Y = args[1]; data = args[2];
            cont = self.callContour(X, Y, data, **keyArgs)
            retVal = cont
        elif len(args) == 1 and isinstance(args[0],str):
            'interpret string as name of a file to plot in axes'
            filename = args[0]
            im = self.callImage(filename, **keyArgs)
            retVal = im
        elif len(args) == 1 and isinstance(args[0],num.ndarray):
            im = self.callIm(args[0], **keyArgs)
            retVal = im
        else:
            raise RuntimeError, 'do not know what to do with args'
        self.a.set_ylim(ymin=self.ybound[0], ymax=self.ybound[1])
        self.a.set_xlim(xmin=self.xbound[0], xmax=self.xbound[1])
        if not noShow:
            if self.showByDefault:
                self.show()
        return retVal
    def callImage(self, filename, 
                  **keyArgs):
        import Image
        im = Image.open(filename)
        s = im.tostring() # convert PIL image -> string
        import numpy as num
        rgb = num.fromstring(s, dtype=num.uint8).astype(num.float)/255.0 # convert string -> array of floats
        rgb = num.resize(rgb, (im.size[1], im.size[0], 3)) # resize to RGB array
        retval = self.callIm(rgb, **keyArgs)
        return retval
    def callIm(self, im, 
               interpolation='nearest', aspect='equal', 
               ijAsXY=False,
               clear=True, **keyArgs):
        if clear: 
            self.clear()
        self.a.axis('off')
        self.a.set_autoscale_on(True)
        if ijAsXY:
            self.asImIJ = False
            'imshow does not yet really support transform'
            if len(im.shape) == 3:
                imT = im.transpose(1,0,2)
            else:
                imT = im.T
            axIm = self.a.imshow(imT, 
                                 interpolation=interpolation, aspect=aspect, origin='lower', 
                                 # transform=self.transform,
                                 **keyArgs)
            self.a.format_coord = lambda x,y: 'i=%d; j=%d; val=%s' % \
                (round(x), round(y), str(im[round(x),round(y)]))
        else:
            self.asImIJ = True
            'imshow does not yet really support transform'
            axIm = self.a.imshow(im, 
                                 interpolation=interpolation, aspect=aspect, 
                                 # transform=self.transform,
                                 **keyArgs)
            self.a.format_coord = lambda x,y: 'i=%d; j=%d; val=%s' % \
                (round(y), round(x), str(im[round(y),round(x)]))
        'turn off autoscale so that axis limits do not get reset on replots'
        self.axIm = axIm
        self.mappable = axIm
        self.a.set_autoscale_on(False)
        return axIm
    def callContour(self, X, Y, data, 
                    interpolation=None, aspect=None,
                    **keyArgs):
        pp = {}
        pp.update(self.plotProps)
        pp.update(keyArgs) # plotProps
        #cont = self.a.contourf(X, Y, data, 200, **keyArgs)
        'imshow does not yet really support transform'
        self.a.set_autoscale_on(True)
        cont = self.a.imshow(data, origin='lower',
                             extent=(X[0,0],X[0,-1],Y[0,0],Y[-1,0]), 
                             interpolation=interpolation,
                             aspect=aspect,
                             # transform=self.transform,
                             **keyArgs)
        self.a.set_autoscale_on(False)
        self.mappable = cont
        return cont
    def discontXY(self):
        self.x_prev = None
        return
    def callXY(self, x, y, style=None, **keyArgs):
        assert len(x) == len(y), \
               'x and y must be same length'

        xUse = x
        yUse = y
        if len(x) == 1:
            if self.x_prev is not None:
                xUse = []; xUse.append(self.x_prev[0]); xUse.append(x)
                yUse = []; yUse.append(self.x_prev[1]); yUse.append(y)

        pp = {}
        pp.update(self.plotProps)
        pp.update(keyArgs) # plotProps
        if self.bball is not None:
            'first, get rid of last bball'
            lenCur = len(self.a.lines)
            if lenCur>0:
                self.a.lines = self.a.lines[0:lenCur-1]
        if self.aging is not None:
            #for lineList in self.lineListList[:-1]:
            #    for line in lineList:
            lenCur = len(self.a.lines)
            for line in self.a.lines[max(0,lenCur-self.agingNumAge):lenCur]:
                alphaCur = line.get_alpha()
                line.set_alpha(alphaCur*self.aging)
            if self.agingCull:
                if lenCur > self.agingNumAge:
                    self.a.lines = self.a.lines[lenCur-self.agingNumAge:lenCur]
        if style is not None:
            'passing transform of None can cause trouble'
            lines = self.a.plot(xUse, yUse, style,
                                # transform=self.transform,
                                **pp)
        elif self.style is not None:
            #self.lineListList.append(self.a.plot(x,y,self.style,**pp))
            lines = self.a.plot(xUse, yUse, self.style,
                                # transform=self.transform,
                                **pp)
        else:
            #self.lineListList.append(self.a.plot(x,y,**pp))
            lines = self.a.plot(xUse, yUse, 
                                # transform=self.transform,
                                **pp)
        if self.bball is not None:
            'add bball at end'
            self.a.plot([x[-1]],[y[-1]], self.bball)
            # transform=self.transform
        if len(x) == 1:
            if self.x_accum:
                self.x_prev = [x, y]
            self.x_store[0] = self.x_store[0] + list(x)
            self.x_store[1] = self.x_store[1] + list(y) 
        else:
            self.x_prev = None
            if len(x) == len(self.x_store[0]):
                'assume called with the same x values'
                self.x_store.append(list(y))
            else:
                self.x_store[0] = list(x)
                self.x_store[1] = list(y) 
        return
    def setVMM(self, vMM):
        if type(vMM) == int:
            iCol = vMM
            vMM = self.a.collections[iCol].get_clim()
        for col in self.a.collections:
            col.set_clim(vmin=vMM[0],vmax=vMM[1])
        return
    def colorbar(self, rect=(0.80,0.1,0.05,0.8), adjustPos=True, thing=None, **kwargs):
        '''
        if set rect to None, then colorbar steals self.a
        '''
        self.__checkWin()
        w = self.win
        f = self.f
        if len(self.a.collections) > 0:
            self.setVMM(0)
        if thing is None:
            if len(self.a.collections) > 0:
                thing = self.a.collections[0]
            elif hasattr(self, 'mappable'):
                thing = self.mappable
            else:
                raise RuntimeError, 'do not know what to colobar, pass in a thing'
        if rect is None:
            self.__colorbar = f.colorbar(thing, ax=self.a)
        else:
            cax = w.getNextAxes(rect=rect)
            self.__colorbar = f.colorbar(thing, cax=cax)
            if adjustPos:
                'adjust existing position to make room for colorbar'
                bbox = self.a.get_position().get_points()
                arect = (bbox[0,0], # left
                         bbox[0,1], # bottom
                         rect[0]-bbox[0,0]-0.02, # width
                         bbox[1,1]-bbox[0,1], # height
                         ) 
                self.a.set_position(arect) 
        self.show()
        return
Example #47
0
class PlotWin:
    __provideToolbarDflt = True
    __debug = False
    __maxAutoFigSize = (7,7)
    __softDestroy = False
    def __init__(self,
                 numRows=1, numCols=-1,
                 title='PlotWin window', 
                 figure=None,
                 relfigsize=(3,3),
                 axesList=None,
                 noAutoAxesList=False,
                 dpi=100
                 ):
        '''
        If pass negative numCols, then numRows is the number of plots
        and the layout is done automatically
        '''
        
        self.dpi = dpi
        self.f = None
        self.iaCur = 0
        if axesList is not None:
            self.axesList = axesList
        else:
            self.axesList = []
        if self.__debug:
            print 'len(axesList): %g' % (len(self.axesList))
        #self.autoAxes = False # not necessary
        self.pwList = [ None for iaCur in range(len(self.axesList)) ]
        self.iaCur = len(self.axesList)

        if numCols <= 0:
            if numRows <= 0:
                #self.autoAxes = True
                self.nc = 0
                self.nr = 0
            else:
                self.__autoNRC(numRows)
            self.figsize = (
                min(max(1,self.nc)*relfigsize[0],self.__maxAutoFigSize[0]),
                min(max(1,self.nr)*relfigsize[1],self.__maxAutoFigSize[1])
                )
        else:
            self.nr = numRows
            self.nc = numCols
            self.figsize = (
                max(1,self.nc)*relfigsize[0],
                max(1,self.nr)*relfigsize[1]
                )
        #
        self.title = title
        self.root = None # dead = True
        
        self.provideToolbar = self.__provideToolbarDflt

        self.f = figure
        self.__checkWin()
        
        if self.__debug:
            print 'nr, nc, len(axesList): %g %g %g' % (self.nr, self.nc, len(self.axesList))
        if len(self.axesList) == 0 and not noAutoAxesList:
            ia = 0
            for ir in range(1,self.nr+1):
                for ic in range(1,self.nc+1):
                    ia += 1
                    a = self.f.add_subplot(self.nr, self.nc, ia)
                    a.clear()
                    a.axis('off')
                    self.axesList.append(a)
                    self.pwList.append(None)
        self.__checkAutoNRAxes()

        return
    def __autoNRC(self, n, resizeFig=False):
        self.nc = int(math.ceil(math.sqrt(float(n))))
        self.nr = int(math.ceil(float(n)/self.nc))
        if resizeFig and hasattr(self.root, 'wm_geometry'):
            import Tkinter as Tk
            self.__checkWin()
            wInch = max(1,self.nc)*3
            hInch = max(1,self.nr)*3
            w = wInch*self.dpi
            h = hInch*self.dpi
            self.f.set_size_inches((wInch,hInch))
            curGeom = self.root.wm_geometry()
            hxw, xp, yp = curGeom.split('+')
            newGeom = str(w)+'x'+str(h)+'+'+xp+'+'+yp
            self.root.wm_geometry(newGeom)
            self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
            self.canvas.show()
            
            # wInch = max(1,self.nc)*3
            # hInch = max(1,self.nr)*3
            # # self.f.set_size_inches((wInch,hInch))
            # #self.canvas.resize(wInch*self.dpi, hInch*self.dpi)
            # #self.canvas.show() 
            # myResizeEvent = MyResizeEvent('autoNRC_resize', self.canvas, 
            #                               wInch*self.dpi, hInch*self.dpi)
            # self.canvas.resize(myResizeEvent)
        return
    def __checkAutoNRAxes(self):
        if self.__debug:
            print 'nr, nc, len(axesList): %g %g %g' % (self.nr, self.nc, len(self.axesList))
        if len(self.axesList) == 0: return
        assert len(self.axesList) <= self.nr*self.nc, \
            'axesList is wrong length'
        for ia in range(len(self.axesList)):
            axes = self.axesList[ia]
            if hasattr(axes,'change_geometry'):
                axes.change_geometry(self.nr, self.nc, ia+1)
        return
    def __checkWin(self):
        '''
        This is pretty ugly in how it is hardwired for tk;
        consider going to something like PlotWinP
        '''
        import sys
        
        if self.root is not None: return  # if not self.dead: return
        
        useTkAgg = True
        if 'matplotlib.backends' in sys.modules:
            if matplotlib.get_backend() != 'TkAgg':
                useTkAgg = False
        if not useTkAgg:
            #self.root = matplotlib.get_backend()
            # assert len(self.axesList) == 1, 'plotWrap case note coded, axesList len : %d' % (len(self.axesList))
            # self.root = PlotWinP(axes=self.axesList, figsize=self.figsize, dpi=self.dpi, 
            #                     title=self.title)
            assert self.f is None, 'self.f is not None'
            self.root = PlotWinP(axes=self.axesList, figsize=self.figsize, dpi=self.dpi)
            self.canvas = self.root.getCanvas()
            self.f = self.root.f
        else:
            # matplotlib.use('TkAgg') # moved this back to above
            from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
            
            import Tkinter as Tk
    
            self.root = root = Tk.Tk() # pops up a little window
            root.wm_title(self.title)
            root.wm_resizable(width=True, height=True)
            #self.dead = False
            
            if self.__softDestroy:
                def destroy(e): 
                    self.root = None # self.dead = True
                root.bind("<Destroy>", destroy)
            
            # a tk.DrawingArea
            if self.f is None: # if figure is None:
                from matplotlib.figure import Figure
                self.f = Figure(figsize=self.figsize,
                                dpi=self.dpi)

            self.canvas = canvas = FigureCanvasTkAgg(self.f, master=root)
            #if self.showByDefault: 
            canvas.show()
            canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) # actually displays something now!
            
            #if self.showByDefault: canvas.show() # updates display
            canvas.show() # updates display
            
            if self.provideToolbar:
                toolbar = NavigationToolbar2TkAgg( self.canvas, root )
                toolbar.update()
                canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        return
    def fillPW(self):
        for iPW in range(len(self.pwList)):
            if self.pwList[iPW] is None:
                self.pwList[iPW] = PlotWrap(window=self)
        return
    def haveXLabels(self):
        self.f.subplots_adjust(bottom=0.2,hspace=0.3) 
        return
    def haveYLabels(self):
        self.f.subplots_adjust(left=0.2,wspace=0.3) 
        return
    def destroy(self):
        if self.root is not None: # not self.dead:
            if not self.__softDestroy:
                self.axesList = []
                # for pw in self.pwList:
                #     if pw is not None:
                #         pw.destroy()
                self.pwList = []
            if hasattr(self.root,'destroy'):
                self.root.destroy()
    def save(self, **keyArgs):
        if keyArgs.has_key('filename'):
            filename = keyArgs.pop('filename')
            #self.canvas.print_figure(filename, **keyArgs)
            self.f.savefig(filename, **keyArgs)
        else:
            raise RuntimeError, 'need filename entry in keyArgs'
        return
    def isDead(self):
        return self.root is None # self.dead
    def getCanvas(self):
        return self.canvas
    def show(self):
        self.__checkWin()
        if hasattr(self.f, 'show'):
            self.f.show()
        elif hasattr(self.canvas, 'show'):
            self.canvas.show()
        else:
            raise RuntimeError, 'do not know how to do show'
    def getFigure(self):
        return self.f
    def getNextAxes(self, rect=None, attachPW=None, **axprops):
        aCur = self.getAxes(self.iaCur, rect=rect, **axprops)
        self.pwList[self.iaCur] = attachPW
        self.iaCur += 1
        return aCur
    def getAxes(self, plotNum, rect=None, withPW=False, **axprops):
        '''careful: plotNum is from 0, not 1 as is the case for subplot
        axprops is useful for this like setting sharex and sharey'''
        #if plotNum+1 > self.nr*self.nc:
        if plotNum+1 > len(self.axesList) or len(axprops) > 0:
            #if not self.autoAxes:
            #    raise RuntimeError, 'not more axes available'
            if rect is not None:
                aCur = self.f.add_axes(rect, **axprops)
                self.axesList.append(aCur)
                self.pwList.append(None)
            else:
                if plotNum < len(self.axesList):
                    'replacing existing' 
                    aCur = self.f.add_subplot(self.nr, self.nc, plotNum+1, **axprops)
                else:
                    'just add more axes, instead of fussing!' 
                    self.__autoNRC(plotNum+1, resizeFig=True)
                    aCur = self.f.add_subplot(self.nr, self.nc, self.iaCur+1, **axprops)
                    self.axesList.append(aCur)
                    self.pwList.append(None)
                self.__checkAutoNRAxes()
            if self.__debug:
                print 'length of axesList is now %d' % len(self.axesList)
            retval = aCur
        else:
            aCur = self.axesList[plotNum]
            pw = self.pwList[plotNum]
            if withPW:
                retval = aCur, pw
            else:
                retval = aCur
        return retval
Example #48
0
def plotRti(sTime,rad,eTime=None,bmnum=7,fileType='fitex',params=['velocity','power','width'], \
              scales=[],channel='a',coords='gate',colors='lasse',yrng=-1,gsct=False,lowGray=False, \
              pdf=False,png=False,dpi=500,show=True,retfig=False,filtered=False,fileName=None, \
              custType='fitex', tFreqBands=[], myFile=None,figure=None,xtick_size=9,ytick_size=9,xticks=None,axvlines=None,plotTerminator=False):
  """create an rti plot for a secified radar and time period

  **Args**:
    * **sTime** (`datetime <http://tinyurl.com/bl352yx>`_): a datetime object indicating the start time which you would like to plot
    * **rad** (str): the 3 letter radar code, e.g. 'bks'
    * **[eTime]** (`datetime <http://tinyurl.com/bl352yx>`_): a datetime object indicating th end time you would like plotted.  If this is None, 24 hours will be plotted.  default = None.
    * **[bmnum] (int)**: The beam to plot.  default: 7
    * **[fileType]** (str): The file type to be plotted, one of ['fitex','fitacf','lmfit'].  default = 'fitex'.
    * **[params]** (list): a list of the fit parameters to plot, allowable values are: ['velocity', 'power', 'width', 'elevation', 'phi0'].  default: ['velocity', 'power', 'width']
    * **[scales]** (list): a list of the min/max values for the color scale for each param.  If omitted, default scales will be used.  If present, the list should be n x 2 where n is the number of elements in the params list.  Use an empty list for default range, e.g. [[-250,300],[],[]].  default: [[-200,200],[0,30],[0,150]]
    * **[channel]** (char): the channel you wish to plot, e.g. 'a', 'b', 'c', ...  default: 'a'
    * **[coords]** (str): the coordinates to use for the y axis.  The allowable values are 'gate', 'rng', 'geo', 'mag' default: 'gate'
    * **[colors]** (str): a string indicating what color bar to use, valid inputs are ['lasse','aj'].  default: 'lasse'
    * **[yrng]** (list or -1): a list indicating the min and max values for the y axis in the chosen coordinate system, or a -1 indicating to plot everything.  default: -1.
    * **[gsct]** (boolean): a flag indicating whether to plot ground scatter as gray. default: False (ground scatter plotted normally)
    * **[lowGray]** (boolean): a flag indicating whether to plot low velocity scatter as gray. default: False (low velocity scatter plotted normally)
    * **[pdf]** (boolean): a flag indicating whether to output to a pdf file.  default = False.  WARNING: saving as pdf is slow.
    * **[png]** (boolean): a flag indicating whether to output to a png file.  default = False
    * **[dpi]** (int): dots per inch if saving as png.  default = 300
    * **[show]** (boolean): a flag indicating whether to display the figure on the screen.  This can cause problems over ssh.  default = True
    * **[retfig]** (boolean):  a flag indicating that you want the figure to be returned from the function.  Only the last figure in the list of frequency bands will be returned.  default = False
    * **[filtered]** (boolean): a flag indicating whether to boxcar filter the data.  default = False (no filter)
    * **[fileName]** (string): If you want to plot for a specific file, indicate the name of the file as fileName.  Include the type of the file in custType.
    * **[custType]** (string): the type (fitacf, lmfit, fitex) of file indicated by fileName
    * **[tFreqBands]** (list): a list of the min/max values for the transmitter frequencies in kHz.  If omitted, the default band will be used.  If more than one band is specified, retfig will cause only the last one to be returned.  default: [[8000,20000]]
    * **[myFile]** (:class:`pydarn.sdio.radDataTypes.radDataPtr`): contains the pipeline to the data we want to plot. If specified, data will be plotted from the file pointed to by myFile. default: None
    * **[figure]** (matplotlib.figure) figure object to plot on.  If None, a figure object will be created for you.
    * **[xtick_size]**: (int) fontsize of xtick labels
    * **[ytick_size]**: (int) fontsize of ytick labels
    * **[xticks]**: (list) datetime.datetime objects indicating the location of xticks
    * **[axvlines]**: (list) datetime.datetime objects indicating the location vertical lines marking the plot
    * **[plotTerminator]**: (boolean) Overlay the day/night terminator.
  **Returns**:
    * Possibly figure, depending on the **retfig** keyword

  **Example**:
    ::
    
      import datetime as dt
      pydarn.plotting.rti.plotRti(dt.datetime(2013,3,16), 'bks', eTime=dt.datetime(2013,3,16,14,30), bmnum=12, fileType='fitacf', scales=[[-500,500],[],[]], coords='geo',colors='aj', filtered=True, show=True)

    
  Written by AJ 20121002
  Modified by Matt W. 20130715
  Modified by Nathaniel F. 20131031 (added plotTerminator)
  """
  import os
    
    
  t1 = datetime.datetime.now()
  #check the inputs
  assert(isinstance(sTime,datetime.datetime)),'error, sTime must be a datetime object'
  assert(isinstance(rad,str) and len(rad) == 3),'error, rad must be a string 3 chars long'
  assert(isinstance(eTime,datetime.datetime) or eTime == None),'error, eTime must be a datetime object or None'
  assert(coords == 'gate' or coords == 'rng' or coords == 'geo' or coords == 'mag'),\
  "error, coords must be one of 'gate','rng','geo','mag"
  assert(isinstance(bmnum,int)),'error, beam must be integer'
  assert(0 < len(params) < 6),'error, must input between 1 and 5 params in LIST form'
  for i in range(0,len(params)):
    assert(params[i] == 'velocity' or params[i] == 'power' or params[i] == 'width' or \
    params[i] == 'elevation' or params[i] == 'phi0'), \
    "error, allowable params are 'velocity','power','width','elevation','phi0'"
  assert(scales == [] or len(scales)==len(params)), \
  'error, if present, scales must have same number of elements as params'
  assert(yrng == -1 or (isinstance(yrng,list) and yrng[0] <= yrng[1])), \
  'error, yrng must equal -1 or be a list with the 2nd element larger than the first'
  assert(colors == 'lasse' or colors == 'aj'),"error, valid inputs for color are 'lasse' and 'aj'"

  #assign any default color scales
  tscales = []
  for i in range(0,len(params)):
    if(scales == [] or scales[i] == []):
      if(params[i] == 'velocity'): tscales.append([-200,200])
      elif(params[i] == 'power'): tscales.append([0,30])
      elif(params[i] == 'width'): tscales.append([0,150])
      elif(params[i] == 'elevation'): tscales.append([0,50])
      elif(params[i] == 'phi0'): tscales.append([-numpy.pi,numpy.pi])
    else: tscales.append(scales[i])
  scales = tscales

  #assign default frequency band
  tbands = []
  if tFreqBands == []: tbands.append([8000,20000])
  else: 
    for band in tFreqBands: 
      #make sure that starting frequncy is less than the ending frequency for each band
      assert(band[0] < band[1]),"Starting frequency must be less than ending frequency!"
      tbands.append(band)


  if eTime == None: eTime = sTime+datetime.timedelta(days=1)
  assert(sTime<eTime),"eTime must be greater than sTime!" 
   
  #open the file if a pointer was not given to us
  #if fileName is specified then it will be read
  if not myFile:
    myFile = radDataOpen(sTime,rad,eTime,channel=channel,bmnum=bmnum,fileType=fileType,filtered=filtered,fileName=fileName)
  else:
    #make sure that we will only plot data for the time range specified by sTime and eTime
    if myFile.sTime <= sTime and myFile.eTime > sTime and myFile.eTime >= eTime:
      myFile.sTime=sTime
      myFile.eTime=eTime
    else:
      #if the times range is not covered by the file, throw an error
      print 'error, data not available in myFile for the whole sTime to eTime'
      return None


  #check that we have data available now that we may have tried
  #to read it using radDataOpen
  if not myFile:
    print 'error, no files available for the requested time/radar/filetype combination'
    return None

  #Finally we can start reading the data file
  myBeam = radDataReadRec(myFile)
  if not myBeam:
    print 'error, no data available for the requested time/radar/filetype combination'
    return None

  #initialize empty lists
  vel,pow,wid,elev,phi0,times,freq,cpid,nave,nsky,nsch,slist,mode,rsep,nrang,frang,gsflg = \
        [],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]
  for i in range(len(tbands)):
    times.append([])
    cpid.append([])
    nave.append([])
    nsky.append([])
    rsep.append([])
    nrang.append([])
    frang.append([])
    nsch.append([])
    freq.append([])
    slist.append([])
    mode.append([])
    vel.append([])
    pow.append([])
    wid.append([])
    elev.append([])
    phi0.append([])
    gsflg.append([])
  
  #read the parameters of interest
  while(myBeam != None):
    if(myBeam.time > eTime): break
    if(myBeam.bmnum == bmnum and (sTime <= myBeam.time)):
      for i in range(len(tbands)):
        if myBeam.prm.tfreq >= tbands[i][0] and myBeam.prm.tfreq <= tbands[i][1]:
          times[i].append(myBeam.time)
          cpid[i].append(myBeam.cp)
          nave[i].append(myBeam.prm.nave)
          nsky[i].append(myBeam.prm.noisesky)
          rsep[i].append(myBeam.prm.rsep)
          nrang[i].append(myBeam.prm.nrang)
          frang[i].append(myBeam.prm.frang)
          nsch[i].append(myBeam.prm.noisesearch)
          freq[i].append(myBeam.prm.tfreq/1e3)
          slist[i].append(myBeam.fit.slist)
          mode[i].append(myBeam.prm.ifmode)
          if('velocity' in params): vel[i].append(myBeam.fit.v)
          if('power' in params): pow[i].append(myBeam.fit.p_l)
          if('width' in params): wid[i].append(myBeam.fit.w_l)
          if('elevation' in params): elev[i].append(myBeam.fit.elv)
          if('phi0' in params): phi0[i].append(myBeam.fit.phi0)
          gsflg[i].append(myBeam.fit.gflg)
      
    myBeam = radDataReadRec(myFile)

  for fplot in range(len(tbands)):
    #Check to ensure that data exists for the requested frequency band else
    #continue on to the next range of frequencies
    if not freq[fplot]:
      print 'error, no data in frequency range '+str(tbands[fplot][0])+' kHz to '+str(tbands[fplot][1])+' kHz'
      rtiFig=None	#Need this line in case no data is plotted
      continue

    #get/create a figure
    if figure == None:
        if show:
          rtiFig = plot.figure(figsize=(11,8.5))
        else:
          rtiFig = Figure(figsize=(14,14))
    else:
        rtiFig = figure
  
    #give the plot a title
    rtiTitle(rtiFig,sTime,rad,fileType,bmnum)
    #plot the noise bar
    plotNoise(rtiFig,times[fplot],nsky[fplot],nsch[fplot])
    #plot the frequency bar
    plotFreq(rtiFig,times[fplot],freq[fplot],nave[fplot])
    #plot the cpid bar
    plotCpid(rtiFig,times[fplot],cpid[fplot],mode[fplot])
    
    #plot each of the parameter panels
    figtop = .77
    figheight = .72/len(params)
    for p in range(len(params)):
      if(params[p] == 'velocity'): pArr = vel[fplot]
      elif(params[p] == 'power'): pArr = pow[fplot]
      elif(params[p] == 'width'): pArr = wid[fplot]
      elif(params[p] == 'elevation'): pArr = elev[fplot]
      elif(params[p] == 'phi0'): pArr = phi0[fplot]
      pos = [.1,figtop-figheight*(p+1)+.02,.76,figheight-.02]
      
      #draw the axis
      ax = drawAxes(rtiFig,times[fplot],rad,cpid[fplot],bmnum,nrang[fplot],frang[fplot],rsep[fplot],p==len(params)-1,yrng=yrng,coords=coords,\
                    pos=pos,xtick_size=xtick_size,ytick_size=ytick_size,xticks=xticks,axvlines=axvlines)
  
      
      if(pArr == []): continue
      
      rmax = max(nrang[fplot])
      data=numpy.zeros((len(times[fplot])*2,rmax))+100000
      if gsct: gsdata=numpy.zeros((len(times[fplot])*2,rmax))+100000
      x=numpy.zeros(len(times[fplot])*2)
      tcnt = 0

      dt_list   = []
      for i in range(len(times[fplot])):
        x[tcnt]=matplotlib.dates.date2num(times[fplot][i])
        dt_list.append(times[fplot][i])

        if(i < len(times[fplot])-1):
          if(matplotlib.dates.date2num(times[fplot][i+1])-x[tcnt] > 4./1440.):
            tcnt += 1
            x[tcnt] = x[tcnt-1]+1./1440.
            dt_list.append(matplotlib.dates.num2date(x[tcnt]))
        tcnt += 1
            
        if(pArr[i] == []): continue
        
        if slist[fplot][i] != None:
          for j in range(len(slist[fplot][i])):
            if(not gsct or gsflg[fplot][i][j] == 0):
              data[tcnt][slist[fplot][i][j]] = pArr[i][j]
            elif gsct and gsflg[fplot][i][j] == 1:
              data[tcnt][slist[fplot][i][j]] = -100000.
  
      if (coords != 'gate' and coords != 'rng') or plotTerminator == True:
        site    = pydarn.radar.network().getRadarByCode(rad).getSiteByDate(times[fplot][0])
        myFov   = pydarn.radar.radFov.fov(site=site,ngates=rmax,nbeams=site.maxbeam,rsep=rsep[fplot][0],coords=coords)
        myLat   = myFov.latCenter[bmnum]
        myLon   = myFov.lonCenter[bmnum]
          
      if(coords == 'gate'): y = numpy.linspace(0,rmax,rmax+1)
      elif(coords == 'rng'): y = numpy.linspace(frang[fplot][0],rmax*rsep[fplot][0],rmax+1)
      else: y = myFov.latFull[bmnum]
        
      X, Y = numpy.meshgrid(x[:tcnt], y)

      # Calculate terminator. ########################################################
      if plotTerminator:
            def daynight_terminator(date, lons):
                """
                date is datetime object (assumed UTC).
                """
                import mpl_toolkits.basemap.solar as solar
                dg2rad = np.pi/180.
                # compute greenwich hour angle and solar declination
                # from datetime object (assumed UTC).
                tau, dec = solar.epem(date)
                # compute day/night terminator from hour angle, declination.
                longitude = lons + tau
                lats = np.arctan(-np.cos(longitude*dg2rad)/np.tan(dec*dg2rad))/dg2rad
                return lats,tau,dec

            daylight = np.ones([len(dt_list),len(myLat)],np.bool)
            for tm_inx in range(len(dt_list)):
                tm                  = dt_list[tm_inx]
                term_lats,tau,dec   = daynight_terminator(tm,myLon)

                if dec > 0: # NH Summer
                    day_inx = np.where(myLat < term_lats)[0]
                else:
                    day_inx = np.where(myLat > term_lats)[0]

                if day_inx.size != 0:
                    daylight[tm_inx,day_inx] = False
     
            from numpy import ma
            daylight = ma.array(daylight,mask=daylight)
            ax.pcolormesh(X, Y, daylight.T, lw=0,alpha=0.10,cmap=matplotlib.cm.binary_r,zorder=99)
      ################################################################################
      
      cmap,norm,bounds = utils.plotUtils.genCmap(params[p],scales[p],colors=colors,lowGray=lowGray)
      cmap=matplotlib.cm.jet
      cmap.set_under('w',alpha=1.0)
      cmap.set_over('w',alpha=1.0)
      cmap.set_bad('w',alpha=1.0)
      norm=matplotlib.colors.Normalize(vmin=scales[p][0],vmax=scales[p][1])
      pcoll = ax.pcolormesh(X, Y, data[:tcnt][:].T, lw=0.01,edgecolors='None',alpha=1,lod=True,cmap=cmap,norm=norm)
  
      cb = utils.drawCB(rtiFig,pcoll,cmap,norm,map=0,pos=[pos[0]+pos[2]+.02, pos[1], 0.02, pos[3]])
      
#      l = []
#      #define the colorbar labels
#      for i in range(0,len(bounds)):
#        if(params[p] == 'phi0'):
#          ln = 4
#          if(bounds[i] == 0): ln = 3
#          elif(bounds[i] < 0): ln = 5
#          l.append(str(bounds[i])[:ln])
#          continue
#        if((i == 0 and params[p] == 'velocity') or i == len(bounds)-1):
#          l.append(' ')
#          continue
#        l.append(str(int(bounds[i])))
#      cb.ax.set_yticklabels(l)
#        
#      #set colorbar ticklabel size
#      for t in cb.ax.get_yticklabels():
#        t.set_fontsize(9)
      
      #set colorbar label
      if(params[p] == 'velocity'): cb.set_label('Velocity [m/s]',size=10)
      if(params[p] == 'grid'): cb.set_label('Velocity [m/s]',size=10)
      if(params[p] == 'power'): cb.set_label('Power [dB]',size=10)
      if(params[p] == 'width'): cb.set_label('Spec Wid [m/s]',size=10)
      if(params[p] == 'elevation'): cb.set_label('Elev [deg]',size=10)
      if(params[p] == 'phi0'): cb.set_label('Phi0 [rad]',size=10)
  
    #handle the outputs
    if png == True:
      if not show:
        canvas = FigureCanvasAgg(rtiFig)
      rtiFig.savefig(sTime.strftime("%Y%m%d")+'_'+str(tbands[fplot][0])+'_'+str(tbands[fplot][1])+'.'+rad+'.png',dpi=dpi)
    if pdf:
      if not show:
        canvas = FigureCanvasAgg(rtiFig)
      rtiFig.savefig(sTime.strftime("%Y%m%d")+'_'+str(tbands[fplot][0])+'_'+str(tbands[fplot][1])+'.'+rad+'.pdf')
    if show:
      rtiFig.show()
      
    print 'plotting took:',datetime.datetime.now()-t1
    #end of plotting for loop
    
  if retfig:
    return rtiFig
Example #49
0
def plot_linear_relation(x, y, x_err=None, y_err=None, title=None, point_label=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, y_2_label=None, marker_style='-o', log_x=False, log_y=False, size=None, filename=None):
    ''' Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation to this line is also plotted, showing the offset.

     Parameters
    ----------
    x, y, x_err, y_err: iterable

    filename: string, PdfPages object or None
        PdfPages file object: plot is appended to the pdf
        string: new plot file with the given filename is created
        None: the plot is printed to screen
    '''
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    if x_err is not None:
        x_err = [x_err, x_err]
    if y_err is not None:
        y_err = [y_err, y_err]
    ax.set_title(title)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_x:
        ax.set_xscale('log')
    if log_y:
        ax.set_yscale('log')
    if plot_range:
        ax.set_xlim((min(plot_range), max(plot_range)))
    if plot_range_y:
        ax.set_ylim((min(plot_range_y), max(plot_range_y)))
    if legend:
        fig.legend(legend, 0)
    ax.grid(True)
    ax.errorbar(x, y, xerr=x_err, yerr=y_err, fmt='o', color='black')  # plot points
    # label points if needed
    if point_label is not None:
        for X, Y, Z in zip(x, y, point_label):
            ax.annotate('{}'.format(Z), xy=(X, Y), xytext=(-5, 5), ha='right', textcoords='offset points')
    line_fit, _ = np.polyfit(x, y, 1, full=False, cov=True)
    fit_fn = np.poly1d(line_fit)
    ax.plot(x, fit_fn(x), '-', lw=2, color='gray')
    setp(ax.get_xticklabels(), visible=False)  # remove ticks at common border of both plots

    divider = make_axes_locatable(ax)
    ax_bottom_plot = divider.append_axes("bottom", 2.0, pad=0.0, sharex=ax)

    ax_bottom_plot.bar(x, y - fit_fn(x), align='center', width=np.amin(np.diff(x)) / 2, color='gray')
#     plot(x, y - fit_fn(x))
    ax_bottom_plot.grid(True)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_2_label is not None:
        ax.set_ylabel(y_2_label)

    ax.set_ylim((-np.amax(np.abs(y - fit_fn(x)))), (np.amax(np.abs(y - fit_fn(x)))))

    ax.plot(ax.set_xlim(), [0, 0], '-', color='black')
    setp(ax_bottom_plot.get_yticklabels()[-2:-1], visible=False)

    if size is not None:
        fig.set_size_inches(size)

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    elif filename:
        fig.savefig(filename, bbox_inches='tight')

    return fig