def _default_plot_for_pickle(data, pixelsize, patternforpickle='graph',
                             title='', xlabel=r'$x$', ylabel=r'$y$', ctitle='',
                             removeSpark=True, cmap='viridis'):

    if removeSpark:
        vmin = wpu.mean_plus_n_sigma(data, -6)
        vmax = wpu.mean_plus_n_sigma(data, 6)
    else:
        vmin = np.min(data)
        vmax = np.max(data)

    #    vmax = np.max((np.abs(vmin), np.abs(vmax)))
    #    vmin = -vmax

    fig = plt.figure(figsize=(12, 9.5))

    plt.imshow(data,
               extent=wpu.extent_func(data, pixelsize)*1e6,
               cmap=cmap, vmin=vmin, vmax=vmax)

    plt.xlabel(xlabel, fontsize=24)
    plt.ylabel(ylabel, fontsize=24)

    cbar = plt.colorbar(shrink=0.9)
    cbar.ax.set_title(ctitle, y=1.01)

    plt.title(title, fontsize=24, weight='bold', y=1.01)

    wpu.save_figs_with_idx_pickle(fig, patternforpickle)

    plt.show(block=True)
예제 #2
0
def plot_DPC(dpc01,
             dpc10,
             pixelsize,
             titleStr='',
             saveFigFlag=False,
             saveFileSuf='graph'):
    '''
    TODO: Write Docstring
    Plot differencial phase signal
    '''
    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(dpc01.size) * pixelsize[0])

    dpc01_plot = dpc01 * pixelsize[1] / np.pi
    dpc10_plot = dpc10 * pixelsize[0] / np.pi

    vlim01 = np.max((np.abs(wpu.mean_plus_n_sigma(dpc01_plot, -5)),
                     np.abs(wpu.mean_plus_n_sigma(dpc01_plot, 5))))
    vlim10 = np.max((np.abs(wpu.mean_plus_n_sigma(dpc10_plot, -5)),
                     np.abs(wpu.mean_plus_n_sigma(dpc10_plot, 5))))

    plt.figure(figsize=(12, 6))
    plt.subplot(121)
    plt.imshow(dpc01_plot,
               cmap='RdGy_r',
               vmin=-vlim01,
               vmax=vlim01,
               extent=wpu.extent_func(dpc01_plot, pixelsize) * factor)

    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('DPC - Horizontal', fontsize=18, weight='bold')  # 01

    plt.subplot(122)
    plt.imshow(dpc10_plot,
               cmap='RdGy_r',
               vmin=-vlim10,
               vmax=vlim10,
               extent=wpu.extent_func(dpc10_plot, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('DPC - Vertical', fontsize=18, weight='bold')

    plt.suptitle('Differential Phase ' + r'[$\pi$ rad]' + titleStr,
                 fontsize=18,
                 weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #3
0
def dpc_integration(dpc01,
                    dpc10,
                    pixelsize,
                    idx4crop=[0, -1, 0, -1],
                    plotErrorIntegration=False,
                    saveFileSuf=None,
                    shifthalfpixel=False,
                    method='FC'):
    '''
    TODO: Write Docstring

    Integration of DPC to obtain phase. Currently only supports
    Frankot Chellappa
    '''

    if idx4crop == '':

        vmin = wpu.mean_plus_n_sigma(dpc01**2 + dpc10**2, -3)
        vmax = wpu.mean_plus_n_sigma(dpc01**2 + dpc10**2, 3)

        _, idx = wpu.crop_graphic_image(dpc01**2 + dpc10**2,
                                        kargs4graph={
                                            'cmap': 'viridis',
                                            'vmin': vmin,
                                            'vmax': vmax
                                        })
    else:
        idx = idx4crop

    dpc01 = wpu.crop_matrix_at_indexes(dpc01, idx)
    dpc10 = wpu.crop_matrix_at_indexes(dpc10, idx)

    if method == 'FC':

        phase = wps.frankotchellappa(dpc01 * pixelsize[1],
                                     dpc10 * pixelsize[0],
                                     reflec_pad=True)
        phase = np.real(phase)

    else:
        wpu.print_red('ERROR: Unknown integration method: ' + method)

    if plotErrorIntegration:
        wps.error_integration(dpc01 * pixelsize[1],
                              dpc10 * pixelsize[0],
                              phase,
                              pixelsize,
                              errors=False,
                              shifthalfpixel=shifthalfpixel,
                              plot_flag=True)

        if saveFileSuf is not None:
            wpu.save_figs_with_idx(saveFileSuf)

    return phase
예제 #4
0
def plot_intensities_harms(int00,
                           int01,
                           int10,
                           pixelsize,
                           titleStr,
                           saveFigFlag=False,
                           saveFileSuf='graph'):
    # Plot Real image (intensity)

    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(int00.size) * pixelsize[0])

    plt.figure(figsize=(14, 6))

    plt.subplot(131)
    plt.imshow(int00,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int00, 4),
               extent=wpu.extent_func(int00, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('00', fontsize=18, weight='bold')

    plt.subplot(132)
    plt.imshow(int01,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int01, 4),
               extent=wpu.extent_func(int01, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('01', fontsize=18, weight='bold')

    plt.subplot(133)
    plt.imshow(int10,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int10, 4),
               extent=wpu.extent_func(int10, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('10', fontsize=18, weight='bold')

    plt.suptitle('Absorption obtained from the Harmonics' + titleStr,
                 fontsize=18,
                 weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #5
0
def plot_DPC(dpc01, dpc10,
             pixelsize, titleStr='',
             saveFigFlag=False, saveFileSuf='graph'):
    '''
    TODO: Write Docstring
    Plot differencial phase signal
    '''
    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(dpc01.size)*pixelsize[0])

    dpc01_plot = dpc01*pixelsize[1]/np.pi
    dpc10_plot = dpc10*pixelsize[0]/np.pi

    vlim01 = np.max((np.abs(wpu.mean_plus_n_sigma(dpc01_plot, -5)),
                     np.abs(wpu.mean_plus_n_sigma(dpc01_plot, 5))))
    vlim10 = np.max((np.abs(wpu.mean_plus_n_sigma(dpc10_plot, -5)),
                     np.abs(wpu.mean_plus_n_sigma(dpc10_plot, 5))))

    plt.figure(figsize=(12, 6))
    plt.subplot(121)
    plt.imshow(dpc01_plot, cmap='RdGy_r',
               vmin=-vlim01, vmax=vlim01,
               extent=wpu.extent_func(dpc01_plot, pixelsize)*factor)

    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('DPC - Horizontal', fontsize=18, weight='bold')  # 01

    plt.subplot(122)
    plt.imshow(dpc10_plot, cmap='RdGy_r',
               vmin=-vlim10, vmax=vlim10,
               extent=wpu.extent_func(dpc10_plot, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('DPC - Vertical', fontsize=18,
              weight='bold')

    plt.suptitle('Differential Phase ' + r'[$\pi$ rad]' + titleStr,
                 fontsize=18, weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #6
0
def plot_dark_field(darkField01,
                    darkField10,
                    pixelsize,
                    titleStr='',
                    saveFigFlag=False,
                    saveFileSuf='graph'):
    '''
    TODO: Write Docstring

    Plot Dark field

    '''

    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(darkField01.size) * pixelsize[0])

    plt.figure(figsize=(14, 6))

    plt.subplot(121)
    plt.imshow(darkField01,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(darkField01, 4),
               extent=wpu.extent_func(darkField01, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('Horizontal', fontsize=18, weight='bold')  # 01

    plt.subplot(122)
    plt.imshow(darkField10,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(darkField01, 4),
               extent=wpu.extent_func(darkField10, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('Vertical', fontsize=18, weight='bold')  # 10

    plt.suptitle('Dark Field', fontsize=18, weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #7
0
def plot_intensities_harms(int00, int01, int10,
                           pixelsize, titleStr,
                           saveFigFlag=False, saveFileSuf='graph'):
    # Plot Real image (intensity)

    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(int00.size)*pixelsize[0])

    plt.figure(figsize=(14, 6))

    plt.subplot(131)
    plt.imshow(int00, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int00, 4),
               extent=wpu.extent_func(int00, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('00', fontsize=18, weight='bold')

    plt.subplot(132)
    plt.imshow(int01, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int01, 4),
               extent=wpu.extent_func(int01, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('01', fontsize=18, weight='bold')

    plt.subplot(133)
    plt.imshow(int10, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int10, 4),
               extent=wpu.extent_func(int10, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('10', fontsize=18, weight='bold')

    plt.suptitle('Absorption obtained from the Harmonics' + titleStr,
                 fontsize=18, weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #8
0
def dpc_integration(dpc01, dpc10, pixelsize, idx4crop=[0, -1, 0, -1],
                    plotErrorIntegration=False,
                    saveFileSuf=None,
                    shifthalfpixel=False, method='FC'):
    '''
    TODO: Write Docstring

    Integration of DPC to obtain phase. Currently only supports
    Frankot Chellappa
    '''

    if idx4crop == '':

        vmin = wpu.mean_plus_n_sigma(dpc01**2+dpc10**2, -3)
        vmax = wpu.mean_plus_n_sigma(dpc01**2+dpc10**2, 3)
        _, idx = wpu.crop_graphic_image(dpc01**2+dpc10**2,
                                        kargs4graph={'cmap': 'viridis',
                                                     'vmin': vmin,
                                                     'vmax': vmax})
    else:
        idx = idx4crop

    dpc01 = wpu.crop_matrix_at_indexes(dpc01, idx)
    dpc10 = wpu.crop_matrix_at_indexes(dpc10, idx)

    if method == 'FC':

        phase = wps.frankotchellappa(dpc01*pixelsize[1],
                                     dpc10*pixelsize[0],
                                     reflec_pad=True)
        phase = np.real(phase)

    else:
        wpu.print_red('ERROR: Unknown integration method: ' + method)

    if plotErrorIntegration:
        wps.error_integration(dpc01*pixelsize[1],
                              dpc10*pixelsize[0],
                              phase, pixelsize, errors=False,
                              shifthalfpixel=shifthalfpixel, plot_flag=True)

        if saveFileSuf is not None:
            wpu.save_figs_with_idx(saveFileSuf)

    return phase
예제 #9
0
def plot_dark_field(darkField01, darkField10,
                    pixelsize, titleStr='',
                    saveFigFlag=False, saveFileSuf='graph'):
    '''
    TODO: Write Docstring

    Plot Dark field

    '''

    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(darkField01.size)*pixelsize[0])

    plt.figure(figsize=(14, 6))

    plt.subplot(121)
    plt.imshow(darkField01, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(darkField01, 4),
               extent=wpu.extent_func(darkField01, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('Horizontal', fontsize=18, weight='bold')  # 01

    plt.subplot(122)
    plt.imshow(darkField10, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(darkField01, 4),
               extent=wpu.extent_func(darkField10, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('Vertical', fontsize=18, weight='bold')  # 10

    plt.suptitle('Dark Field', fontsize=18, weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #10
0
def plot_residual_parabolic_lens_2d(thickness,
                                    pixelsize,
                                    fitted,
                                    fitParameters,
                                    saveFigFlag=False,
                                    savePickle=False,
                                    str4title='',
                                    saveSdfData=False,
                                    vlimErrSigma=1,
                                    plotProfileFlag=True,
                                    plot3dFlag=True,
                                    makeAnimation=False):

    xmatrix, ymatrix = wpu.grid_coord(thickness, pixelsize)

    errorThickness = thickness - fitted
    argNotNAN = np.isfinite(errorThickness)

    factorx, unitx = wpu.choose_unit(xmatrix)
    factory, unity = wpu.choose_unit(ymatrix)
    factorz, unitz = wpu.choose_unit(errorThickness[argNotNAN])

    ptp = np.ptp(errorThickness[argNotNAN].flatten() * factorz)
    wpu.print_red('PV: {0:4.3g} '.format(ptp) + unitz[-1] + 'm')

    sigmaError = np.std(errorThickness[argNotNAN].flatten() * factorz)
    wpu.print_red('SDV: {0:4.3g} '.format(sigmaError) + unitz[-1] + 'm')

    str4title += r'Residual, ' + \
                 r'R $= {:.4g} \mu m$,'.format(fitParameters[0]*1e6) + '\n' + \
                 r'PV $= {0:.2f}$ '.format(ptp) + '$' + unitz + '  m$, '\
                 'SDV $= {0:.2f}$ '.format(sigmaError) + '$' + unitz + '  m$'

    # Plot Histogram

    plt.figure(figsize=(7, 8))
    plt.hist(errorThickness[argNotNAN] * factorz,
             100,
             color='r',
             histtype='step')
    plt.xlabel(r'Residual [$' + unitz + '  m$ ]')
    plt.title(str4title)

    if saveFigFlag:
        wpu.save_figs_with_idx(fname2save, extension='png')

    plt.show(block=False)

    # Plot Profiles

    vlimErr = wpu.mean_plus_n_sigma(errorThickness[argNotNAN] * factorz,
                                    vlimErrSigma / 2)
    cmap4graph = plt.cm.Spectral_r
    cmap4graph.set_over('m')
    cmap4graph.set_under('c')

    if plotProfileFlag:

        wpu.plot_profile(xmatrix * factorx,
                         ymatrix * factory,
                         errorThickness * factorz,
                         title=str4title,
                         xlabel=r'[$' + unitx + '  m$ ]',
                         ylabel=r'[$' + unity + '  m$ ]',
                         zlabel=r'[$' + unitz + '  m$ ]',
                         arg4main={
                             'cmap': 'Spectral_r',
                             'vmin': -vlimErr,
                             'vmax': vlimErr,
                             'extend': 'both'
                         })

    if savePickle or saveFigFlag:
        fig = plt.figure(figsize=(10, 7))

        cf = plt.contourf(xmatrix * factorx,
                          ymatrix * factory,
                          errorThickness * factorz,
                          256,
                          cmap=cmap4graph,
                          extend='both')

        plt.clim(-vlimErr, vlimErr)
        plt.contour(cf, levels=cf.levels[::32], colors='gray')

        plt.xlabel(r'[$' + unitx + '  m$ ]', fontsize=22)
        plt.ylabel(r'[$' + unity + '  m$ ]', fontsize=22)
        plt.title(str4title, fontsize=22)
        cbar = plt.colorbar(cf, shrink=.8, aspect=20)
        #        cbar.set_clim(-vlimErr, vlimErr)
        cbar.ax.set_title(r'[$' + unitz + '  m$ ]', y=1.01)

        plt.gca().set_aspect('equal', adjustable='box')
        plt.grid(color='grey')

        if saveFigFlag:
            wpu.save_figs_with_idx(fname2save, extension='png')

        if savePickle:
            wpu.save_figs_with_idx_pickle(fig, fname2save)

        plt.show(block=True)

    # Plot 3D

    if plot3dFlag:

        wpu.print_red('MESSAGE: Ploting 3d in the background')

        fig = plt.figure(figsize=(10, 7), facecolor="white")
        ax = fig.gca(projection='3d')
        plt.tight_layout(pad=2.5)

        surf = ax.plot_trisurf(xmatrix[argNotNAN].flatten() * factorx,
                               ymatrix[argNotNAN].flatten() * factory,
                               errorThickness[argNotNAN].flatten() * factorz,
                               vmin=-vlimErr,
                               vmax=vlimErr,
                               cmap=cmap4graph,
                               linewidth=0.1,
                               shade=False)

        ax.view_init(azim=-120, elev=40)

        plt.xlabel(r'$x$ [$' + unitx + '  m$ ]')
        plt.ylabel(r'$y$ [$' + unity + '  m$ ]')

        plt.title(str4title)

        cbar = plt.colorbar(surf, shrink=.8, aspect=20, extend='both')
        cbar.ax.set_title(r'[$' + unitz + '  m$ ]', y=1.01)

        plt.tight_layout()

        if saveFigFlag:
            wpu.save_figs_with_idx(fname2save, extension='png')

            ax.view_init(azim=690, elev=40)

            wpu.save_figs_with_idx(fname2save, extension='png')

        if makeAnimation:
            #            plt.show(block=False)
            plt.pause(1.0)
            wpu.rocking_3d_figure(ax,
                                  wpu.get_unique_filename(fname2save, 'gif'),
                                  elevOffset=45,
                                  azimOffset=60,
                                  elevAmp=0,
                                  azimAmpl=-1,
                                  dpi=80,
                                  npoints=5)

        plt.pause(1.0)
        plt.close('all')
        #    plt.show(block=True)

    if saveSdfData:
        mask_for_sdf = errorThickness * 0.0
        mask_for_sdf[~argNotNAN] = 1.0
        errorThickness[~argNotNAN] = 00000000
        wpu.save_sdf_file(
            errorThickness, pixelsize,
            wpu.get_unique_filename(fname2save + '_residual', 'sdf'))
        wpu.save_sdf_file(
            mask_for_sdf, pixelsize,
            wpu.get_unique_filename(fname2save + '_residual_mask', 'sdf'))

    return sigmaError / factorz, ptp / factorz
def _n_profiles_H_V(arrayH,
                    arrayV,
                    virtual_pixelsize,
                    zlabel=r'z',
                    titleH='Horiz',
                    titleV='Vert',
                    nprofiles=5,
                    filter_width=0,
                    remove2ndOrder=False,
                    saveFileSuf='',
                    saveFigFlag=True):

    xxGrid, yyGrid = wpu.grid_coord(arrayH, virtual_pixelsize)

    fit_coefs = [[], []]
    data2saveH = None
    data2saveV = None
    labels_H = None
    labels_V = None

    plt.rcParams['lines.markersize'] = 4
    plt.rcParams['lines.linewidth'] = 2

    # Horizontal
    if np.all(np.isfinite(arrayH)):

        plt.figure(figsize=(12, 12 * 9 / 16))

        xvec = xxGrid[0, :]
        data2saveH = np.c_[xvec]
        header = ['x [m]']

        ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                                ncurves=nprofiles,
                                                cmap_str='gist_rainbow_r')

        lc = []
        labels_H = []
        for i, row in enumerate(
                np.linspace(filter_width // 2,
                            np.shape(arrayV)[0] - filter_width // 2 - 1,
                            nprofiles + 2,
                            dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            if filter_width != 0:
                yvec = arrayH[row - filter_width:row + filter_width, :]
                yvec = np.sum(yvec, 0) / filter_width / 2
            else:
                yvec = arrayH[row, :]

            lc.append(next(lc_jet))
            p01 = np.polyfit(xvec, yvec, 1)
            fit_coefs[0].append(p01)

            if remove2ndOrder:
                yvec -= p01[0] * xvec + p01[1]

            plt.plot(xvec * 1e6,
                     yvec,
                     next(ls_cycle),
                     color=lc[i - 1],
                     label=str(row))

            if not remove2ndOrder:
                plt.plot(xvec * 1e6,
                         p01[0] * xvec + p01[1],
                         '--',
                         color=lc[i - 1],
                         lw=3)

            data2saveH = np.c_[data2saveH, yvec]
            header.append(str(row))
            labels_H.append(str(row))

        if remove2ndOrder:
            titleH = titleH + ', 2nd order removed'
        plt.legend(title='Pixel Y', loc=0, fontsize=12)

        plt.xlabel(r'x [$\mu m$]', fontsize=18)
        plt.ylabel(zlabel, fontsize=18)
        plt.title(titleH + ', Filter Width = {:d} pixels'.format(filter_width),
                  fontsize=20)

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_H')

        plt.show(block=False)

        header.append(zlabel +
                      ', Filter Width = {:d} pixels'.format(filter_width))

        wpu.save_csv_file(data2saveH,
                          wpu.get_unique_filename(
                              saveFileSuf + '_WF_profiles_H', 'csv'),
                          headerList=header)

        plt.figure(figsize=(12, 12 * 9 / 16))
        plt.imshow(arrayH,
                   cmap='RdGy',
                   vmin=wpu.mean_plus_n_sigma(arrayH, -3),
                   vmax=wpu.mean_plus_n_sigma(arrayH, 3))
        plt.xlabel('Pixel')
        plt.ylabel('Pixel')
        plt.title(titleH + ', Profiles Position')

        currentAxis = plt.gca()

        _, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                         ncurves=nprofiles,
                                         cmap_str='gist_rainbow_r')

        for i, row in enumerate(
                np.linspace(filter_width // 2,
                            np.shape(arrayV)[0] - filter_width // 2 - 1,
                            nprofiles + 2,
                            dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            currentAxis.add_patch(
                Rectangle((-.5, row - filter_width // 2 - .5),
                          np.shape(arrayH)[1],
                          filter_width,
                          facecolor=lc[i - 1],
                          alpha=.5))
            plt.axhline(row, color=lc[i - 1])

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_H')

        plt.show(block=True)

    # Vertical
    if np.all(np.isfinite(arrayV)):

        plt.figure(figsize=(12, 12 * 9 / 16))

        xvec = yyGrid[:, 0]
        data2saveV = np.c_[xvec]
        header = ['y [m]']

        ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                                ncurves=nprofiles,
                                                cmap_str='gist_rainbow_r')

        lc = []
        labels_V = []
        for i, col in enumerate(
                np.linspace(filter_width // 2,
                            np.shape(arrayH)[1] - filter_width // 2 - 1,
                            nprofiles + 2,
                            dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            if filter_width != 0:
                yvec = arrayV[:, col - filter_width:col + filter_width]
                yvec = np.sum(yvec, 1) / filter_width / 2
            else:
                yvec = arrayV[:, col]

            lc.append(next(lc_jet))
            p10 = np.polyfit(xvec, yvec, 1)
            fit_coefs[1].append(p10)

            if remove2ndOrder:
                yvec -= p10[0] * xvec + p10[1]

            plt.plot(xvec * 1e6,
                     yvec,
                     next(ls_cycle),
                     color=lc[i - 1],
                     label=str(col))

            if not remove2ndOrder:
                plt.plot(xvec * 1e6,
                         p10[0] * xvec + p10[1],
                         '--',
                         color=lc[i - 1],
                         lw=3)

            data2saveV = np.c_[data2saveV, yvec]
            header.append(str(col))
            labels_V.append(str(col))

        if remove2ndOrder:
            titleV = titleV + ', 2nd order removed'

        plt.legend(title='Pixel X', loc=0, fontsize=12)

        plt.xlabel(r'y [$\mu m$]', fontsize=18)
        plt.ylabel(zlabel, fontsize=18)

        plt.title(titleV + ', Filter Width = {:d} pixels'.format(filter_width),
                  fontsize=20)
        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Y')
        plt.show(block=False)

        header.append(zlabel +
                      ', Filter Width = {:d} pixels'.format(filter_width))

        wpu.save_csv_file(data2saveV,
                          wpu.get_unique_filename(
                              saveFileSuf + '_WF_profiles_V', 'csv'),
                          headerList=header)

        plt.figure(figsize=(12, 12 * 9 / 16))
        plt.imshow(arrayV,
                   cmap='RdGy',
                   vmin=wpu.mean_plus_n_sigma(arrayV, -3),
                   vmax=wpu.mean_plus_n_sigma(arrayV, 3))
        plt.xlabel('Pixel')
        plt.ylabel('Pixel')
        plt.title(titleV + ', Profiles Position')

        currentAxis = plt.gca()

        for i, col in enumerate(
                np.linspace(filter_width // 2,
                            np.shape(arrayH)[1] - filter_width // 2 - 1,
                            nprofiles + 2,
                            dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            currentAxis.add_patch(
                Rectangle((col - filter_width // 2 - .5, -.5),
                          filter_width,
                          np.shape(arrayV)[0],
                          facecolor=lc[i - 1],
                          alpha=.5))
            plt.axvline(col, color=lc[i - 1])

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Y')

        plt.show(block=True)

    return data2saveH, data2saveV, labels_H, labels_V, fit_coefs
예제 #12
0
def _n_profiles_H_V(arrayH, arrayV, virtual_pixelsize,
                    zlabel=r'z',
                    titleH='Horiz', titleV='Vert',
                    nprofiles=5, filter_width=0,
                    remove1stOrderDPC=False,
                    saveFileSuf='',
                    saveFigFlag=True):

    xxGrid, yyGrid = wpu.grid_coord(arrayH, virtual_pixelsize)

    fit_coefs = [[], []]
    data2saveH = None
    data2saveV = None
    labels_H = None
    labels_V = None

    plt.rcParams['lines.markersize'] = 4
    plt.rcParams['lines.linewidth'] = 2

    # Horizontal
    if np.all(np.isfinite(arrayH)):

        plt.figure(figsize=(12, 12*9/16))

        xvec = xxGrid[0, :]
        data2saveH = np.c_[xvec]
        header = ['x [m]']

        if filter_width != 0:
            arrayH_filtered = uniform_filter1d(arrayH, filter_width, 0)
        else:
            arrayH_filtered = arrayH

        ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                                ncurves=nprofiles,
                                                cmap_str='gist_rainbow_r')

        lc = []
        labels_H = []
        for i, row in enumerate(np.linspace(filter_width//2,
                                            np.shape(arrayV)[0]-filter_width//2-1,
                                            nprofiles + 2, dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            yvec = arrayH_filtered[row, :]

            lc.append(next(lc_jet))
            p01 = np.polyfit(xvec, yvec, 1)
            fit_coefs[0].append(p01)

            if remove1stOrderDPC:
                yvec -= p01[0]*xvec + p01[1]

            plt.plot(xvec*1e6, yvec, next(ls_cycle), color=lc[i-1],
                     label=str(row))

            if not remove1stOrderDPC:
                plt.plot(xvec*1e6, p01[0]*xvec + p01[1], '--',
                         color=lc[i-1], lw=3)

            data2saveH = np.c_[data2saveH, yvec]
            header.append(str(row))
            labels_H.append(str(row))

        if remove1stOrderDPC:
            titleH = titleH + ', 2nd order removed'
        plt.legend(title='Pixel Y', loc=0, fontsize=12)

        plt.xlabel(r'x [$\mu m$]', fontsize=18)
        plt.ylabel(zlabel, fontsize=18)
        plt.title(titleH + ', Filter Width = {:d} pixels'.format(filter_width),
                  fontsize=20)

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_H')

        plt.show(block=False)

        header.append(zlabel + ', Filter Width = {:d} pixels'.format(filter_width))

        wpu.save_csv_file(data2saveH,
                          wpu.get_unique_filename(saveFileSuf +
                                                  '_WF_profiles_H', 'csv'),
                          headerList=header)

        plt.figure(figsize=(12, 12*9/16))
        plt.imshow(arrayH, cmap='RdGy',
                   vmin=wpu.mean_plus_n_sigma(arrayH, -3),
                   vmax=wpu.mean_plus_n_sigma(arrayH, 3))
        plt.xlabel('Pixel')
        plt.ylabel('Pixel')
        plt.title(titleH + ', Profiles Position')

        currentAxis = plt.gca()

        _, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                         ncurves=nprofiles,
                                         cmap_str='gist_rainbow_r')

        for i, row in enumerate(np.linspace(filter_width//2,
                                            np.shape(arrayV)[0]-filter_width//2-1,
                                            nprofiles + 2, dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            currentAxis.add_patch(Rectangle((-.5, row - filter_width//2 - .5),
                                            np.shape(arrayH)[1], filter_width,
                                            facecolor=lc[i-1], alpha=.5))
            plt.axhline(row, color=lc[i-1])

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_H')

        plt.show(block=True)

    # Vertical
    if np.all(np.isfinite(arrayV)):

        plt.figure(figsize=(12, 12*9/16))

        xvec = yyGrid[:, 0]
        data2saveV = np.c_[xvec]
        header = ['y [m]']

        if filter_width != 0:
            arrayV_filtered = uniform_filter1d(arrayV, filter_width, 1)
        else:
            arrayV_filtered = arrayV

        ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                                ncurves=nprofiles,
                                                cmap_str='gist_rainbow_r')

        lc = []
        labels_V = []
        for i, col in enumerate(np.linspace(filter_width//2,
                                            np.shape(arrayH)[1]-filter_width//2-1,
                                            nprofiles + 2, dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            yvec = arrayV_filtered[:, col]

            lc.append(next(lc_jet))
            p10 = np.polyfit(xvec, yvec, 1)
            fit_coefs[1].append(p10)

            if remove1stOrderDPC:
                yvec -= p10[0]*xvec + p10[1]

            plt.plot(xvec*1e6, yvec, next(ls_cycle), color=lc[i-1],
                     label=str(col))

            if not remove1stOrderDPC:
                plt.plot(xvec*1e6, p10[0]*xvec + p10[1], '--',
                         color=lc[i-1], lw=3)

            data2saveV = np.c_[data2saveV, yvec]
            header.append(str(col))
            labels_V.append(str(col))

        if remove1stOrderDPC:
            titleV = titleV + ', 2nd order removed'

        plt.legend(title='Pixel X', loc=0, fontsize=12)

        plt.xlabel(r'y [$\mu m$]', fontsize=18)
        plt.ylabel(zlabel, fontsize=18)

        plt.title(titleV + ', Filter Width = {:d} pixels'.format(filter_width),
                  fontsize=20)
        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Y')
        plt.show(block=False)

        header.append(zlabel + ', Filter Width = {:d} pixels'.format(filter_width))

        wpu.save_csv_file(data2saveV,
                          wpu.get_unique_filename(saveFileSuf +
                                                  '_WF_profiles_V', 'csv'),
                          headerList=header)

        plt.figure(figsize=(12, 12*9/16))
        plt.imshow(arrayV, cmap='RdGy',
                   vmin=wpu.mean_plus_n_sigma(arrayV, -3),
                   vmax=wpu.mean_plus_n_sigma(arrayV, 3))
        plt.xlabel('Pixel')
        plt.ylabel('Pixel')
        plt.title(titleV + ', Profiles Position')

        currentAxis = plt.gca()

        for i, col in enumerate(np.linspace(filter_width//2,
                                            np.shape(arrayH)[1]-filter_width//2-1,
                                            nprofiles + 2, dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue


            currentAxis.add_patch(Rectangle((col - filter_width//2 - .5, -.5),
                                            filter_width, np.shape(arrayV)[0],
                                            facecolor=lc[i-1], alpha=.5))
            plt.axvline(col, color=lc[i-1])

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Y')

        plt.show(block=True)

    return data2saveH, data2saveV, labels_H, labels_V, fit_coefs
def correct_zero_DPC(dpc01, dpc10,
                     pixelsize, distDet2sample, phenergy, saveFileSuf):

    title = ['Angle displacement of fringes 01',
             'Angle displacement of fringes 10']

    factor = distDet2sample*hc/phenergy

    angle = [dpc01/pixelsize[1]*factor, dpc10/pixelsize[0]*factor]
    dpc = [dpc01, dpc10]

    pi_jump = [0, 0]

    iamhappy = False
    while not iamhappy:

        pi_jump[0] = int(np.round(np.mean(angle[0])/np.pi))
        pi_jump[1] = int(np.round(np.mean(angle[1])/np.pi))

        plt.figure()
        plt.hist(angle[0].flatten()/np.pi, 201,
                 histtype='step')
        plt.hist(angle[1].flatten()/np.pi, 201,
                 histtype='step')

        plt.xlabel(r'Angle [$\pi$rad]')

        plt.title('Correct DPC\n' +
                  r'Angle displacement of fringes $[\pi$ rad]' +
                  '\n' + r'Calculated jumps $x$ and $y$ : ' +
                  '{:d}, {:d} $\pi$'.format(pi_jump[0], pi_jump[1]))

        plt.legend(('DPC x', 'DPC y'))
        plt.show(block=False)
        plt.pause(.5)

        if pi_jump == [0, 0]:
            break

        if easyqt.get_yes_or_no('Subtract pi jump of DPC?'):
            plt.close('all')

            angle[0] -= pi_jump[0]*np.pi
            angle[1] -= pi_jump[1]*np.pi

            dpc01 = angle[0]*pixelsize[0]/factor
            dpc10 = angle[1]*pixelsize[1]/factor
            dpc = [dpc01, dpc10]

            wgi.plot_DPC(dpc01, dpc10,
                         virtual_pixelsize, saveFigFlag=True,
                         saveFileSuf=saveFileSuf)
        else:
            plt.close('all')
            iamhappy = True


    wpu.print_blue('MESSAGE: mean angle/pi ' +
                               '0: {:} pi'.format(np.mean(angle[0]/np.pi)))
    wpu.print_blue('MESSAGE: mean angle/pi ' +
                               '1: {:} pi'.format(np.mean(angle[1]/np.pi)))

    if easyqt.get_yes_or_no('Subtract mean of DPC?'):
        plt.close('all')

        angle[0] -= np.mean(angle[0])
        angle[1] -= np.mean(angle[1])

        dpc01 = angle[0]*pixelsize[0]/factor
        dpc10 = angle[1]*pixelsize[1]/factor
        dpc = [dpc01, dpc10]

        wgi.plot_DPC(dpc01, dpc10,
                     virtual_pixelsize, saveFigFlag=True,
                     saveFileSuf=saveFileSuf)
        plt.pause(.1)
    else:
        pass

    if easyqt.get_yes_or_no('Correct DPC center?'):
        plt.close('all')

        for i in [0, 1]:

            iamhappy = False
            while not iamhappy:

                angle[i], pi_jump[i] = correct_zero_from_unwrap(angle[i])

                wpu.print_blue('MESSAGE: pi jump ' +
                               '{:}: {:} pi'.format(i, pi_jump[i]))
                wpu.print_blue('MESSAGE: mean angle/pi ' +
                               '{:}: {:} pi'.format(i, np.mean(angle[i]/np.pi)))
                plt.figure()
                plt.hist(angle[i].flatten() / np.pi, 101)
                plt.title(r'Angle displacement of fringes $[\pi$ rad]')
                plt.show()

                plt.figure()

                vlim = np.max((np.abs(wpu.mean_plus_n_sigma(angle[i]/np.pi,
                                                            -5)),
                               np.abs(wpu.mean_plus_n_sigma(angle[i]/np.pi,
                                                            5))))

                plt.imshow(angle[i] / np.pi,
                           cmap='RdGy',
                           vmin=-vlim, vmax=vlim)

                plt.colorbar()
                plt.title(title[i] + r' [$\pi$ rad],')
                plt.xlabel('Pixels')
                plt.ylabel('Pixels')

                plt.pause(.1)

                iamhappy = easyqt.get_yes_or_no('Happy?')
                plt.close('all')

            dpc[i] = angle[i]*pixelsize[i]/factor

    plt.close('all')

    return dpc
예제 #14
0
            img_0 = dxchange.read_tiff(imgfname)
            all_img = np.zeros((len(listOfDataFiles),
                                img_0.shape[0], img_0.shape[1]), dtype=int)

        all_img[i,:,:] = dxchange.read_tiff(imgfname)

        wpu.print_blue('MESSAGE: Loading ' + imgfname)

    for i, imgfname in enumerate(listOfDataFiles):

        plt.figure()
        plt.figure(figsize=(12, 12*9/16))

        plt.imshow(all_img[i, :, :],
                   cmap='jet',
                   vmin=0, vmax=wpu.mean_plus_n_sigma(all_img, 6)//1)

        outfname = 'png_figs/' + \
                   imgfname.split('.')[0].rsplit('/', 1)[-1] + '.png'
        plt.title(imgfname.split('/')[-1])
        plt.savefig(outfname)
        print(outfname + ' saved!')

        plt.close()

#        if i > 0: break

    # %%

#    wpu.print_red('MESSAGE: Done!')
    #    plt.show(block=True)