Exemplo n.º 1
0
def plot_avg_xas_single(bin_xas, detector):

    plotview = NXPlotView()

    if detector == "I0":
        y_array = bin_xas.i0
    elif detector == "TEY":
        y_array = bin_xas.tey
    elif detector == "DIODE" or detector == "PD1":
        y_array = bin_xas.diode
    elif detector == "PFY_SDD1":
        y_array = bin_xas.pfy_sdd1
    elif detector == "PFY_SDD2":
        y_array = bin_xas.pfy_sdd2
    elif detector == "PFY_SDD3":
        y_array = bin_xas.pfy_sdd3
    elif detector == "PFY_SDD4":
        y_array = bin_xas.pfy_sdd4
    else:
        return "Invalid dividend name"

    plotview.figure.clf()
    ax = plotview.figure.gca()
    ax.axes.get_xaxis().set_visible(True)
    ax.axes.get_yaxis().set_visible(True)

    ax.plot(bin_xas.energy, y_array)
    ax.set_xlabel('Energy (eV)')
    ax.set_ylabel(detector)
    plotview.draw()
Exemplo n.º 2
0
def eem(multi_xas, name):
    start_time = time.time()

    # matplotlib.rcParams['figure.figsize'] = (14, 10)

    name = name.upper()
    if name == "SDD1":
        intensity = multi_xas.sdd1
        # intensity = np.array(intensity)
    elif name == "SDD2":
        intensity = multi_xas.sdd2
        # intensity = np.array(intensity)
    elif name == "SDD3":
        intensity = multi_xas.sdd3
        # intensity = np.array(intensity)
    elif name == "SDD4":
        intensity = multi_xas.sdd4
        # intensity = np.array(intensity)
    else:
        return "Invalid name for the intensity of EEM"

    energy_array = np.array(multi_xas.energy)
    num_of_points = len(energy_array)
    num_of_emission_bins = len(intensity[0])

    bin_num_for_x = np.zeros(shape=(num_of_points, num_of_emission_bins))
    for i in range(num_of_points):
        bin_num_for_x[i].fill(energy_array[i])

    bin_num_for_y = np.zeros(shape=(num_of_points, num_of_emission_bins))
    bin_num_for_y[0:] = np.arange(10, (num_of_emission_bins + 1) * 10, 10)

    v_max = max(intensity[0])
    for i in range(1, num_of_points):
        temp_max = max(intensity[i])
        if temp_max > v_max:
            v_max = temp_max
    # print ("v_max: ", v_max)

    intensity = np.array(intensity)
    plotview = NXPlotView()
    plotview.figure.clf()
    ax = plotview.figure.gca()
    ax.axes.get_xaxis().set_visible(True)
    ax.axes.get_yaxis().set_visible(True)
    # print("--- %s seconds ---" % (time.time() - start_time))
    ax.scatter(bin_num_for_x,
               bin_num_for_y,
               c=intensity,
               s=7,
               linewidths=0,
               vmax=v_max,
               vmin=0)
    print("--- %s seconds ---" % (time.time() - start_time))
    ax.set_xlabel('Incident Energy (eV)')
    ax.set_ylabel('Emission Energy (eV)')
    ax.set_title("Excitation Emission Matrix")
    plotview.grid()
    plotview.draw()
    print("--- %s seconds ---" % (time.time() - start_time))
Exemplo n.º 3
0
def plot_normalized(xas, dividend, divisor):

    plotview = NXPlotView()

    # convert the string to uppercase
    dividend = dividend.upper()
    divisor = divisor.upper()

    if dividend == "I0":
        dividend_array = xas.i0
    elif dividend == "TEY":
        dividend_array = xas.tey
    elif dividend == "DIODE" or dividend == "PD1":
        dividend_array = xas.diode
    elif dividend == "PFY_SDD1":
        dividend_array = xas.pfy_sdd1
    elif dividend == "PFY_SDD2":
        dividend_array = xas.pfy_sdd2
    elif dividend == "PFY_SDD3":
        dividend_array = xas.pfy_sdd3
    elif dividend == "PFY_SDD4":
        dividend_array = xas.pfy_sdd4
    else:
        return "Invalid dividend name"

    if divisor == "I0":
        divisor_array = xas.i0
    elif divisor == "TEY":
        divisor_array = xas.tey
    elif divisor == "DIODE" or divisor == "PD1":
        divisor_array = xas.diode
    elif divisor == "PFY_SDD1":
        divisor_array = xas.pfy_sdd1
    elif divisor == "PFY_SDD2":
        divisor_array = xas.pfy_sdd2
    elif divisor == "PFY_SDD3":
        divisor_array = xas.pfy_sdd3
    elif divisor == "PFY_SDD4":
        divisor_array = xas.pfy_sdd4
    else:
        return "Invalid divisor name"

    normalized_array = np.array(dividend_array) / np.array(divisor_array)

    # the old code using Matplotlib to plot diagrams
    # plt.figure()
    # plt.plot(xas.energy, normalized_array)
    # str_y_axis = StringIO()
    # str_y_axis.write(dividend + ' / ' + divisor)
    # plt.ylabel(str_y_axis.getvalue())
    # plt.title("Averaged %s / Averaged %s" % (dividend, divisor))

    plotview.figure.clf()
    ax = plotview.figure.gca()
    ax.axes.get_xaxis().set_visible(True)
    ax.axes.get_yaxis().set_visible(True)

    ax.plot(xas.energy, normalized_array)
    ax.set_xlabel('Energy (eV)')
    str_y_axis = StringIO()
    str_y_axis.write(dividend + ' / ' + divisor)
    ax.set_ylabel(str_y_axis.getvalue())
    ax.set_title("Averaged %s / Averaged %s" % (dividend, divisor))

    plotview.draw()

    return xas.energy, normalized_array
Exemplo n.º 4
0
def plot_avg_xas_all(bin_xas):
    """
    Generate all plots (matplotlib figures) for averaged data at once
    :return: None
    """
    print("Plotting average XAS.")
    # matplotlib.rcParams['figure.figsize'] = (14, 22)

    plotview = NXPlotView()

    plotview.setMinimumHeight(200)
    plotview.resize(1400, 800)
    plotview.figure.clf()

    en = bin_xas.energy
    i0 = bin_xas.i0
    tey = bin_xas.tey
    diode = bin_xas.diode
    pfy_sdd1 = bin_xas.pfy_sdd1
    pfy_sdd2 = bin_xas.pfy_sdd2
    pfy_sdd3 = bin_xas.pfy_sdd3
    pfy_sdd4 = bin_xas.pfy_sdd4

    plt.subplot(2, 4, 1)
    plt.plot(en, tey)
    # add lable for x and y axis
    plt.xlabel('Energy (eV)')
    plt.ylabel('TEY')
    # add title of the figure
    plt.title('Binned(Averaged) TEY')

    plt.subplot(2, 4, 2)
    plt.plot(en, i0)
    plt.xlabel('Energy (eV)')
    plt.ylabel('I0')
    plt.title('Binned(Averaged) I0')

    plt.subplot(2, 4, 3)
    plt.plot(en, diode)
    plt.xlabel('Energy (eV)')
    plt.ylabel('Diode')
    plt.title('Binned(Averaged) Diode')

    plt.subplot(2, 4, 5)
    plt.plot(en, pfy_sdd1)
    plt.xlabel('Energy (eV)')
    plt.ylabel('PFY_SDD1')
    plt.title('Binned(Averaged) PFY_SDD1')

    plt.subplot(2, 4, 6)
    plt.plot(en, pfy_sdd2)
    plt.xlabel('Energy (eV)')
    plt.ylabel('PFY_SDD2')
    plt.title('Binned(Averaged) PFY_SDD2')

    plt.subplot(2, 4, 7)
    plt.plot(en, pfy_sdd3)
    plt.xlabel('Energy (eV)')
    plt.ylabel('PFY_SDD3')
    plt.title('Binned(Averaged) PFY_SDD3')

    plt.subplot(2, 4, 8)
    plt.plot(en, pfy_sdd4)
    plt.xlabel('Energy (eV)')
    plt.ylabel('PFY_SDD4')
    plt.title('Binned(Averaged) PFY_SDD4')

    plt.tight_layout()
    # use plotview from Nexpy to generate plots
    plotview.figure = plt
    plotview.tab_widget.removeTab(0)
    plotview.tab_widget.removeTab(0)
    plotview.draw()
Exemplo n.º 5
0
    def summary_plot(self, name):
        start_time = time.time()
        # matplotlib.rcParams['figure.figsize'] = (13, 10)

        # select intensity
        name = name.upper()
        if name == "TEY":
            intensity = self.tey
        elif name == "I0" or name == "IO":
            intensity = self.i0
        elif name == "DIODE" or name == "PD1":
            intensity = self.diode
        elif name == "PFY_SDD1":
            intensity = self.pfy_sdd1
        elif name == "PFY_SDD2":
            intensity = self.pfy_sdd2
        elif name == "PFY_SDD3":
            intensity = self.pfy_sdd3
        elif name == "PFY_SDD4":
            intensity = self.pfy_sdd4
        else:
            return "Invalid name for the intensity of summary plot"

        total_cscan_num = len(self.energy)
        # print (total_cscan_num)

        # show the plot in Nexpy, similar to figure.show()
        plotview = NXPlotView()

        # setup the size of figure and pop-up window
        plotview.setMinimumHeight(200)
        if total_cscan_num > 10:
            ratio = total_cscan_num / 10
        else:
            ratio = 1
        plotview.resize(700, 280 * ratio)
        plotview.figure.clf()

        # setup axis
        ax = plotview.figure.gca()
        ax.axes.get_xaxis().set_visible(True)
        ax.axes.get_yaxis().set_visible(True)

        print("--- %s seconds ---" % (time.time() - start_time))

        energy_tuple = np.array(self.energy[0][:])
        intensity_tuple = np.array(intensity[0][:])
        scan_num_tuple = np.zeros(len(self.energy[0]))
        scan_num_tuple.fill(1)

        # prepare data as tuples for x, y, and color of scatter plot
        for i in range(1, total_cscan_num):
            scan_num_list = np.zeros(len(self.energy[i]))
            scan_num_list.fill(i + 1)
            scan_num_tuple = np.concatenate([scan_num_tuple, scan_num_list])
            energy_tuple = np.concatenate(
                [energy_tuple, np.array(self.energy[i][:])])
            intensity_tuple = np.concatenate(
                [intensity_tuple, np.array(intensity[i][:])])
            # comment out the old way to generate scatter plot
            #plt.scatter(self.energy[i][:], scan_num_list, c=intensity[i][:], s=140, linewidths=0, marker='s')

        # print("--- %s seconds ---" % (time.time() - start_time))
        # main function call to generate color scatter plot
        ax.scatter(energy_tuple,
                   scan_num_tuple,
                   c=intensity_tuple,
                   s=140,
                   linewidths=0,
                   marker='s')
        # this locator puts ticks at regular intervals
        loc = plticker.MultipleLocator(base=1.0)
        # set regular ticks interval
        ax.yaxis.set_major_locator(loc)
        # set the limitation of y axis
        ax.set_ylim(ymin=0, ymax=total_cscan_num + 1)
        # manipulate the ytick labels
        t = np.arange(len(self.selected_scan_entry)) + 1.0
        ax.set_yticks(t)
        ax.set_yticklabels(self.selected_scan_entry)
        # add title of the figure
        ax.set_title("Summary Plot (Intensity: %s)" % (name))
        # add labels for x and y axis
        ax.set_xlabel('Incident Energy(eV)')
        ax.set_ylabel('Scan Entry')
        # set limit of y axis
        print("selected_scan_entry: ", self.selected_scan_entry)

        plotview.grid(True)
        plotview.draw()
        print("--- %s seconds ---" % (time.time() - start_time))
Exemplo n.º 6
0
class MaskDialog(BaseDialog):

    def __init__(self, parent=None):
        super(MaskDialog, self).__init__(parent)
        
        self.plotview = None
        self.shapes = []
        
        self.select_entry(self.choose_entry)
        self.shape_box = self.select_box(['Rectangle', 'Circle'])
        self.set_layout(self.entry_layout, 
                        self.make_layout(
                            self.action_buttons(('Add Shape', self.add_shape)),
                            self.shape_box),
                        self.close_buttons(save=True))
        self.set_title('Mask Data')

    def choose_entry(self):
        if 'calibration' not in self.entry['instrument']:
            raise NeXusError('Please load calibration data to this entry')
        self.data = self.entry['instrument/calibration']
        self.counts = self.data.nxsignal.nxvalue
        self.mask = self.entry['instrument/detector/pixel_mask'].nxvalue
        self.plot_data()
        shape = self.data.nxsignal.shape

    def plot_data(self):
        if self.plotview is None:
            if 'Mask Editor' in plotviews:
                self.plotview = plotviews['Mask Editor']
            else:
                self.plotview = NXPlotView('Mask Editor')
        self.plotview.plot(self.data, log=True)
        self.plotview.aspect='equal'
        self.plotview.ytab.flipped = True
        self.plotview.draw()

    def add_shape(self):
        self.plotview.deactivate()
        xlo, xhi = self.plotview.xaxis.lo, self.plotview.xaxis.hi
        ylo, yhi = self.plotview.yaxis.lo, self.plotview.yaxis.hi
        xc, yc = xlo + 0.5 * (xhi - xlo), ylo + 0.5 * (yhi - ylo)
        r = (xhi - xlo) / 4
        if self.shape_box.currentText() == 'Rectangle':
            self.shapes.append(NXrectangle(xc-r, yc-r, 2*r, 2*r,
                                           border_tol=0.1, plotview=self.plotview,
                                           facecolor='r', edgecolor='k',
                                           linewidth=1, alpha=0.3))
        else:
            self.shapes.append(NXcircle(xc, yc, r, border_tol=0.1, 
                                        plotview=self.plotview,
                                        facecolor='r', edgecolor='k',
                                        linewidth=1, alpha=0.3))
        self.plotview.draw()
        self.shapes[-1].connect()    

    def accept(self):
        x, y = np.arange(self.mask.shape[1]), np.arange(self.mask.shape[0])
        for shape in self.shapes:
            if isinstance(shape, NXrectangle):
                rect = shape.rectangle
                x0, y0 = int(rect.get_x()), int(rect.get_y())
                x1, y1 = int(x0+rect.get_width()), int(y0+rect.get_height())               
                self.mask[y0:y1,x0:x1] = 1
            else:
                circle = shape.circle
                xc, yc = circle.center
                r = circle.radius
                inside = (x[None,:]-int(xc))**2+(y[:,None]-int(yc))**2 < r**2
                self.mask = self.mask | inside
        self.mask[np.where(self.counts<0)] = 1
        self.entry['instrument/detector/pixel_mask'] = self.mask        
        super(MaskDialog, self).accept()
        if 'Mask Editor' in plotviews:
            plotviews['Mask Editor'].close_view()

    def reject(self):
        super(MaskDialog, self).reject()
        if 'Mask Editor' in plotviews:
            plotviews['Mask Editor'].close_view()
Exemplo n.º 7
0
class MaskDialog(NXDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.plotview = None
        self.shapes = []
        self.parameters = {}
        self.select_entry(self.choose_entry)
        self.shape_box = self.select_box(['Rectangle', 'Circle'])
        self.shape_choice = self.select_box([], slot=self.choose_shape)
        self.set_layout(
            self.entry_layout,
            self.make_layout(
                self.action_buttons(('Add Shape', self.add_shape)),
                self.shape_box), self.shape_choice,
            self.close_buttons(save=True))
        self.shape_choice.setVisible(False)
        self.set_title('Mask Data')

    def choose_entry(self):
        if 'calibration' not in self.entry['instrument']:
            raise NeXusError('Please load calibration data to this entry')
        self.data = self.entry['instrument/calibration']
        self.counts = self.data.nxsignal.nxvalue
        self.mask = self.entry['instrument/detector/pixel_mask'].nxvalue
        self.xc = self.entry['instrument/detector/beam_center_x'].nxvalue
        self.yc = self.entry['instrument/detector/beam_center_y'].nxvalue
        self.plot_data()
        shape = self.data.nxsignal.shape

    def plot_data(self):
        if self.plotview is None:
            if 'Mask Editor' in plotviews:
                self.plotview = plotviews['Mask Editor']
            else:
                self.plotview = NXPlotView('Mask Editor')
        self.plotview.plot(self.data, log=True)
        self.plotview.aspect = 'equal'
        self.plotview.ytab.flipped = True
        self.plotview.draw()

    def add_shape(self):
        if self.shape_box.currentText() == 'Rectangle':
            self.shapes.append(
                NXrectangle(self.xc - 50,
                            self.yc - 50,
                            100,
                            100,
                            border_tol=0.1,
                            plotview=self.plotview,
                            resize=True,
                            facecolor='r',
                            edgecolor='k',
                            linewidth=1,
                            alpha=0.3))
        else:
            self.shapes.append(
                NXcircle(self.xc,
                         self.yc,
                         50,
                         border_tol=0.1,
                         plotview=self.plotview,
                         resize=True,
                         facecolor='r',
                         edgecolor='k',
                         linewidth=1,
                         alpha=0.3))
        self.plotview.draw()
        self.shapes[-1].connect()
        self.shape_choice.addItem(repr(self.shapes[-1]))
        self.shape_choice.setVisible(True)
        self.insert_layout(self.shape_options(self.shapes[-1]))

    def shape_options(self, shape):
        p = self.parameters[shape] = GridParameters()
        if isinstance(shape, NXrectangle):
            x, y = shape.xy
            w, h = shape.width, shape.height
            p.add('x', x, 'Left Pixel')
            p.add('y', y, 'Bottom Pixel')
            p.add('w', w, 'Width')
            p.add('h', h, 'Height')
        else:
            x, y = shape.center
            r = abs(shape.width) / 2
            p.add('x', x, 'X-Center')
            p.add('y', y, 'Y-Center')
            p.add('r', r, 'Radius')
        return p.grid(header=False)

    def choose_shape(self):
        pass

    def accept(self):
        x, y = np.arange(self.mask.shape[1]), np.arange(self.mask.shape[0])
        for shape in self.shapes:
            if isinstance(shape, NXrectangle):
                x0, y0 = shape.xy
                x1, y1 = x0 + shape.width, y0 + shape.height
                self.mask[int(y0):int(y1), int(x0):int(x1)] = 1
            else:
                xc, yc = shape.center
                r = shape.radius
                inside = (x[None, :] - int(xc))**2 + (y[:, None] -
                                                      int(yc))**2 < r**2
                self.mask = self.mask | inside
        self.mask[np.where(self.counts < 0)] = 1
        try:
            self.entry['instrument/detector/pixel_mask'] = self.mask
        except NeXusError as error:
            report_error("Creating Mask", error)
            return
        super().accept()
        if 'Mask Editor' in plotviews:
            plotviews['Mask Editor'].close_view()

    def reject(self):
        super().reject()
        if 'Mask Editor' in plotviews:
            plotviews['Mask Editor'].close_view()