def save_profile_from_sdf(fname, nprofiles=3, direction='V', savecsv=True): data, pixelsize, headerdic = wpu.load_sdf_file(fname) saveFileSuf = fname.replace('.sdf', '') if 'V' in direction: xvec = wpu.realcoordvec(data.shape[0], pixelsize[0])[np.newaxis] data2save = np.c_[xvec.T] for j in np.linspace(0, np.shape(data)[1] - 1, nprofiles + 2, dtype=int): data2save = np.c_[data2save, data[:, j]] else: xvec = wpu.realcoordvec(data.shape[1], pixelsize[1])[np.newaxis] data2save = np.c_[xvec.T] for i in np.linspace(0, np.shape(data)[0] - 1, nprofiles + 2, dtype=int): data2save = np.c_[data2save, data[i, :]] if savecsv: wpu.save_csv_file(data2save, wpu.get_unique_filename(saveFileSuf + '_profiles_V', 'csv'), headerList='bla') return data2save, headerdic
def _lsq_fit_1D_parabola(yy, pixelsize): xx = wpu.realcoordvec(yy.shape[0], pixelsize) if np.all(np.isfinite(yy)): # if there is no nan f = yy.flatten() x = xx.flatten() else: argNotNAN = np.isfinite(yy) f = yy[argNotNAN].flatten() x = xx[argNotNAN].flatten() X_matrix = np.vstack([x**2, x, x * 0.0 + 1]).T beta_matrix = np.linalg.lstsq(X_matrix, f)[0] fit = (beta_matrix[0] * xx**2 + beta_matrix[1] * xx + beta_matrix[2]) if np.all(np.isfinite(yy)): mask = yy * 0.0 + 1.0 else: mask = yy * 0.0 + 1.0 mask[~argNotNAN] = np.nan return fit * mask, beta_matrix
sx, sy, \ error, step = wps.speckleDisplacement(image, image_ref, halfsubwidth=halfsubwidth, halfTemplateSize=halfTemplateSize, subpixelResolution=subpixelResolution, npointsmax=npointsmax, ncores=ncores, taskPerCore=15, verbose=True) totalS = np.sqrt(sx**2 + sy**2) xVec2 = wpu.realcoordvec(sx.shape[1], pixelsize*step) yVec2 = wpu.realcoordvec(sx.shape[0], pixelsize*step) # %% # ============================================================================= # Save data in hdf5 format # ============================================================================= fname_output = fname[:-4] + '_' + wpu.datetime_now_str() + ".h5" f = h5.File(fname_output, "w") h5rawdata = f.create_group('raw') f.create_dataset("raw/image_sample", data=image) f.create_dataset("raw/image_ref", data=image_ref)
def fit_radius_dpc(dpx, dpy, pixelsize, radius4fit, kwave, saveFigFlag=False, str4title=''): xVec = wpu.realcoordvec(dpx.shape[1], pixelsize[1]) yVec = wpu.realcoordvec(dpx.shape[0], pixelsize[0]) lim_x = np.argwhere(xVec >= -radius4fit * 1.01)[0, 0] lim_y = np.argwhere(yVec >= -radius4fit * 1.01)[0, 0] xmatrix, ymatrix = np.meshgrid(xVec[lim_x:-lim_x + 1], yVec[lim_y:-lim_y + 1]) fig = plt.figure(figsize=(14, 5)) fig.suptitle(str4title + 'Phase [rad]', fontsize=14) ax1 = plt.subplot(121) ax2 = plt.subplot(122, sharex=ax1, sharey=ax1) ax1.plot(xVec[lim_x:-lim_x + 1] * 1e6, dpx[dpx.shape[1] // 4, lim_x:-lim_x + 1], '-ob', label='1/4') ax1.plot(xVec[lim_x:-lim_x + 1] * 1e6, dpx[dpx.shape[1] // 2, lim_x:-lim_x + 1], '-or', label='1/2') ax1.plot(xVec[lim_x:-lim_x + 1] * 1e6, dpx[dpx.shape[1] // 4 * 3, lim_x:-lim_x + 1], '-og', label='3/4') lin_fitx = np.polyfit(xVec[lim_x:-lim_x + 1], dpx[dpx.shape[1] // 2, lim_x:-lim_x + 1], 1) lin_funcx = np.poly1d(lin_fitx) ax1.plot(xVec[lim_x:-lim_x + 1] * 1e6, lin_funcx(xVec[lim_x:-lim_x + 1]), '--c', lw=2, label='Fit 1/2') curvrad_x = kwave / (lin_fitx[0]) wpu.print_blue('lin_fitx[0] x: {:.3g} m'.format(lin_fitx[0])) wpu.print_blue('lin_fitx[1] x: {:.3g} m'.format(lin_fitx[1])) wpu.print_blue('Curvature Radius of WF x: {:.3g} m'.format(curvrad_x)) ax1.ticklabel_format(style='sci', axis='y', scilimits=(0, 1)) ax1.set_xlabel(r'[$\mu m$]') ax1.set_ylabel('dpx [radians]') ax1.legend(loc=0, fontsize='small') ax1.set_title('Curvature Radius of WF {:.3g} m'.format(curvrad_x), fontsize=16) ax1.set_adjustable('box-forced') ax2.plot(yVec[lim_y:-lim_y + 1] * 1e6, dpy[lim_y:-lim_y + 1, dpy.shape[0] // 4], '-ob', label='1/4') ax2.plot(yVec[lim_y:-lim_y + 1] * 1e6, dpy[lim_y:-lim_y + 1, dpy.shape[0] // 2], '-or', label='1/2') ax2.plot(yVec[lim_y:-lim_y + 1] * 1e6, dpy[lim_y:-lim_y + 1, dpy.shape[0] // 4 * 3], '-og', label='3/4') lin_fity = np.polyfit(yVec[lim_y:-lim_y + 1], dpy[lim_y:-lim_y + 1, dpy.shape[0] // 2], 1) lin_funcy = np.poly1d(lin_fity) ax2.plot(yVec[lim_y:-lim_y + 1] * 1e6, lin_funcy(yVec[lim_y:-lim_y + 1]), '--c', lw=2, label='Fit 1/2') curvrad_y = kwave / (lin_fity[0]) wpu.print_blue('Curvature Radius of WF y: {:.3g} m'.format(curvrad_y)) ax2.ticklabel_format(style='sci', axis='y', scilimits=(0, 1)) ax2.set_xlabel(r'[$\mu m$]') ax2.set_ylabel('dpy [radians]') ax2.legend(loc=0, fontsize='small') ax2.set_title('Curvature Radius of WF {:.3g} m'.format(curvrad_y), fontsize=16) ax2.set_adjustable('box-forced') if saveFigFlag: wpu.save_figs_with_idx(fname2save, extension='png') plt.show(block=False)
error_raw = np.array(f['displacement/error'])[::stride, ::stride] xVec_raw = np.array(f['displacement/xvec'])[::stride] yVec_raw = np.array(f['displacement/yvec'])[::stride] #============================================================================== # %% Crop #============================================================================== idx4crop = wpu.graphical_roi_idx(np.sqrt(sx_raw**2 + sy_raw**2), verbose=True) sx = wpu.crop_matrix_at_indexes(sx_raw, idx4crop) sy = wpu.crop_matrix_at_indexes(sy_raw, idx4crop) error = wpu.crop_matrix_at_indexes(error_raw, idx4crop) xVec = wpu.realcoordvec(sx.shape[1], pixelsizeImg) yVec = wpu.realcoordvec(sx.shape[0], pixelsizeImg) xmatrix, ymatrix = np.meshgrid(xVec, yVec) #============================================================================== # %% Calculations of physical quantities #============================================================================== totalS = np.sqrt(sx**2 + sy**2) # Differenctial Phase dpx = kwave * np.arctan2(sx * pixelsizeDetector, distDet2sample) dpy = kwave * np.arctan2(sy * pixelsizeDetector, distDet2sample) # Differenctial Thickness
def curv_from_height(height, virtual_pixelsize, grazing_angle=0.0, projectionFromDiv=1.0, labels=[], xlabel='x', ylabel='Curvature', titleStr='', saveFileSuf=''): ls_cycle, lc_cycle = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'], ncurves=height.shape[1] - 1, cmap_str='gist_rainbow_r') if grazing_angle // .00001 > 0: projection = 1 / np.sin(grazing_angle) * projectionFromDiv else: projection = projectionFromDiv projected_pixel = virtual_pixelsize * projection xvec = wpu.realcoordvec(height.shape[0] - 2, projected_pixel) print('projected_pixel') print(projected_pixel) plt.figure(figsize=(12, 12 * 9 / 16)) list_curv = [xvec] header = [xlabel + ' [m]'] for j_line in range(1, height.shape[1]): curv = np.diff(np.diff(height[:, j_line])) / projected_pixel**2 if j_line == 1: factor_x, unit_x = wpu.choose_unit(xvec) #factor_y, unit_y = wpu.choose_unit(curv) list_curv.append(curv) header.append(labels[j_line - 1]) plt.plot(xvec * factor_x, curv, next(ls_cycle), c=next(lc_cycle), label=labels[j_line - 1]) marginx = 0.1 * np.ptp(xvec * factor_x) plt.xlim( [np.min(xvec * factor_x) - marginx, np.max(xvec * factor_x) + marginx]) plt.xlabel(xlabel + r' [$' + unit_x + ' m$]') plt.ylabel(ylabel + r'[$m^{-1}$]') plt.legend(loc=0, fontsize=12) if grazing_angle // .00001 > 0: plt.title(titleStr + 'Mirror Curvature,\n' + 'grazing angle {:.2f} mrad,\n'.format(grazing_angle * 1e3) + 'projection due divergence = ' + r'$ \times $ {:.2f}'.format(projectionFromDiv)) else: plt.title(titleStr + 'Curvature') plt.tight_layout() wpu.save_figs_with_idx(saveFileSuf) plt.show() data2saveV = np.asarray(list_curv).T header.append(ylabel + ' [1/m]') if grazing_angle // .00001 > 0: header.append(', grazing_angle = {:.4g}'.format(grazing_angle)) if projectionFromDiv // 1 != 1: header.append('projection due divergence = ' + '{:.2f}x'.format(projectionFromDiv)) wpu.save_csv_file(data2saveV, wpu.get_unique_filename(saveFileSuf + '_curv_' + xlabel, 'csv'), headerList=header) return np.asarray(list_curv).T
def curv_from_height(height, virtual_pixelsize, grazing_angle=0.0, projectionFromDiv=1.0, labels=[], xlabel='x', ylabel='Curvature', titleStr='', saveFileSuf=''): ls_cycle, lc_cycle = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'], ncurves=height.shape[1] - 1, cmap_str='gist_rainbow_r') if grazing_angle//.00001 > 0: projection = 1/np.sin(grazing_angle)*projectionFromDiv else: projection = projectionFromDiv projected_pixel = virtual_pixelsize*projection xvec = wpu.realcoordvec(height.shape[0]-2, projected_pixel) print('projected_pixel') print(projected_pixel) plt.figure(figsize=(12, 12*9/16)) list_curv = [xvec] header = [xlabel + ' [m]'] for j_line in range(1, height.shape[1]): curv = np.diff(np.diff(height[:, j_line]))/projected_pixel**2 if j_line == 1: factor_x, unit_x = wpu.choose_unit(xvec) #factor_y, unit_y = wpu.choose_unit(curv) list_curv.append(curv) header.append(labels[j_line - 1]) plt.plot(xvec*factor_x, curv, next(ls_cycle), c=next(lc_cycle), label=labels[j_line - 1]) marginx = 0.1*np.ptp(xvec*factor_x) plt.xlim([np.min(xvec*factor_x)-marginx, np.max(xvec*factor_x)+marginx]) plt.xlabel(xlabel + r' [$' + unit_x + ' m$]') plt.ylabel(ylabel + r'[$m^{-1}$]') plt.legend(loc=0, fontsize=12) if grazing_angle//.00001 > 0: plt.title(titleStr + 'Mirror Curvature,\n' + 'grazing angle {:.2f} mrad,\n'.format(grazing_angle*1e3) + 'projection due divergence = ' + r'$ \times $ {:.2f}'.format(projectionFromDiv)) else: plt.title(titleStr + 'Curvature') plt.tight_layout() wpu.save_figs_with_idx(saveFileSuf) plt.show() data2saveV = np.asarray(list_curv).T header.append(ylabel + ' [1/m]') if grazing_angle//.00001 > 0: header.append(', grazing_angle = {:.4g}'.format(grazing_angle)) if projectionFromDiv//1 != 1: header.append('projection due divergence = ' + '{:.2f}x'.format(projectionFromDiv)) wpu.save_csv_file(data2saveV, wpu.get_unique_filename(saveFileSuf + '_curv_' + xlabel, 'csv'), headerList=header) return np.asarray(list_curv).T
yVec_raw = np.array(f['displacement/yvec']) #============================================================================== # %% Crop #============================================================================== idx4crop = wpu.graphical_roi_idx(np.sqrt(sx_raw**2 + sy_raw**2), verbose=True) sx = wpu.crop_matrix_at_indexes(sx_raw, idx4crop) sy = wpu.crop_matrix_at_indexes(sy_raw, idx4crop) error = wpu.crop_matrix_at_indexes(error_raw, idx4crop) xVec = wpu.realcoordvec(sx.shape[1], pixelsizeImg) yVec = wpu.realcoordvec(sx.shape[0], pixelsizeImg) xmatrix, ymatrix = np.meshgrid(xVec, yVec) #============================================================================== # %% Calculations of physical quantities #============================================================================== totalS = np.sqrt(sx**2 + sy**2)