def propagate_1D(self,do_plot=do_plot,method='fft', wavelength=1.24e-10,aperture_type='square',aperture_diameter=40e-6, wavefront_length=100e-6,npoints=500, propagation_distance = 30.0,show=1): print("\n# ") print("# far field 1D (fraunhofer) diffraction from a %s aperture "%aperture_type) print("# ") wf = Wavefront1D.initialize_wavefront_from_range(x_min=-wavefront_length/2, x_max=wavefront_length/2, number_of_points=npoints,wavelength=wavelength) wf.set_plane_wave_from_complex_amplitude((2.0+1.0j)) # an arbitraty value if aperture_type == 'square': wf.apply_slit(-aperture_diameter/2, aperture_diameter/2) elif aperture_type == 'gaussian': X = wf.get_mesh_x() Y = wf.get_mesh_y() window = numpy.exp(- (X*X + Y*Y)/2/(aperture_diameter/2.35)**2) wf.rescale_amplitudes(window) else: raise Exception("Not implemented! (accepted: circle, square, gaussian)") if method == 'fft': wf1 = propagate_1D_fresnel(wf, propagation_distance) elif method == 'convolution': wf1 = propagate_1D_fresnel_convolution(wf, propagation_distance) elif method == 'integral': wf1 = propagate_1D_integral(wf, propagation_distance) elif method == 'fraunhofer': wf1 = propagate_1D_fraunhofer(wf, propagation_distance) else: raise Exception("Not implemented method: %s"%method) # get the theoretical value angle_x = wf1.get_abscissas() / propagation_distance intensity_theory = get_theoretical_diffraction_pattern(angle_x,aperture_type=aperture_type,aperture_diameter=aperture_diameter, wavelength=wavelength,normalization=True) intensity_calculated = wf1.get_intensity() intensity_calculated /= intensity_calculated.max() if do_plot: from srxraylib.plot.gol import plot plot(wf1.get_abscissas()*1e6/propagation_distance,intensity_calculated, angle_x*1e6,intensity_theory, legend=["%s "%method,"Theoretical (far field)"], legend_position=(0.95, 0.95), title="1D (%s) diffraction from a %s aperture of %3.1f um at wavelength of %3.1f A"% (method,aperture_type,aperture_diameter*1e6,wavelength*1e10), xtitle="X (urad)", ytitle="Intensity",xrange=[-20,20], show=show) return wf1.get_abscissas()/propagation_distance,intensity_calculated,intensity_theory
def plot_undul_cdf(undul_cdf_input,do_show=True): # # plots output of undul_cdf # try: from srxraylib.plot.gol import plot,plot_image,plot_show except: print("srxraylib not available: No plot") return if isinstance(undul_cdf_input,str): undul_cdf_dict = load_file_undul_cdf(undul_cdf_input) else: undul_cdf_dict = undul_cdf_input TWO = undul_cdf_dict['cdf_EnergyThetaPhi'] ONE = undul_cdf_dict['cdf_EnergyTheta'] ZERO = undul_cdf_dict['cdf_Energy'] # E = undul_cdf_dict['energy'] # T = undul_cdf_dict['theta'] # P = undul_cdf_dict['phi'] NG_E,NG_T,NG_P = ZERO.shape plot(numpy.arange(NG_E),TWO,title="cdf(energy) TWO",xtitle="index Energy",ytitle="cdf(E) TWO",show=0) plot_image(ONE,numpy.arange(NG_E),numpy.arange(NG_T),aspect='auto', title="cdf(energy,theta) ONE",xtitle="index Energy",ytitle="index Theta",show=0) plot_image(ZERO[0,:,:],numpy.arange(NG_T),numpy.arange(NG_P),aspect='auto', title="cdf (theta,phi) ZERO[0]",xtitle="index Theta",ytitle="index Phi",show=0) if do_show: plot_show()
def test_xoppy(): # from orangecontrib.xoppy.util.mlayer import MLayer out = MLayer.initialize_from_bilayer_stack( material_S="Si", density_S=None, roughness_S=0.0, material_E="W", density_E="10", roughness_E=0.0, material_O="Si", density_O=None, roughness_O=0.0, bilayer_pairs=50, bilayer_thickness=50.0, bilayer_gamma=0.5, ) for key in out.pre_mlayer_dict.keys(): print(key, out.pre_mlayer_dict[key]) # rs, rp, e, t = out.scan(h5file="", energyN=1, energy1=8050.0, energy2=15000.0, thetaN=600, theta1=0.0, theta2=6.0) # # plot (example) # myscan = 0 from srxraylib.plot.gol import plot, plot_image if DO_PLOTS: if myscan == 0: # angle scan plot(t, rs[0], xtitle="angle [deg]", ytitle="Reflectivity-s", title="") elif myscan == 1: # energy scan plot(e, rs[:, 0], xtitle="Photon energy [eV]", ytitle="Reflectivity-s", title="") elif myscan == 2: # double scan plot_image(rs, e, t, xtitle="Photon energy [eV]", ytitle="Grazing angle [deg]", title="Reflectivity-s", aspect="auto")
def create_magnetic_field_for_bending_magnet(do_plot=False, filename="", B0=-1.0, divergence=1e-3, radius=10.0, npoints=500): L = radius * divergence Lmax = numpy.abs(L * 1.1) y = numpy.linspace(-Lmax / 2, Lmax / 2, npoints) B = y * 0.0 + B0 ybad = numpy.where(numpy.abs(y) > numpy.abs(L / 2)) B[ybad] = 0 if do_plot: from srxraylib.plot.gol import plot plot(y, B, xtitle="y [m]", ytitle="B [T]", title=filename) if filename != "": f = open(filename, "w") for i in range(y.size): f.write("%f %f\n" % (y[i], B[i])) f.close() print("File written to disk: %s" % filename) return y, B
def test_schmidt(self): npixels = 2**9 pixelsize = 9.48e-6 wavelength = 1e-6 m = 2.996 # radius = 1 propagation_distance = 0.1 wavefront_propagated, intensity_theory = self.schmidt( pixelsize, npixels, wavelength, m, propagation_distance) show_plot = True # show_plot = False if show_plot: plot( wavefront_propagated.get_abscissas() * 1e6, wavefront_propagated.get_intensity() / wavefront_propagated.get_intensity().max(), wavefront_propagated.get_abscissas() * 1e6, abs(intensity_theory)**2 / abs(intensity_theory.max())**2, legend=["V profile", "Theoretical"], legend_position=(0.60, 0.95), title= "diffraction of a square slit of %3.1f um at wavelength of %3.1f A" % (2e-3 * 1e6, wavelength * 1e-6), xtitle="Y (um)", ytitle="Intensity", xrange=[-20000, 20000], show=1) numpy.testing.assert_almost_equal(wavefront_propagated.get_intensity(), abs(intensity_theory)**2, 1)
def plot_undulator(wavefront, method, show=0): plot_image(wavefront.get_intensity(), wavefront.get_coordinate_x(), wavefront.get_coordinate_y(), title='Intensity (%s)' % method, show=show) plot_image(wavefront.get_phase(), wavefront.get_coordinate_x(), wavefront.get_coordinate_y(), title='Phase (%s)' % method, show=show) horizontal_profile = line_image(wavefront.get_intensity(), horizontal_or_vertical='H') vertical_profile = line_image(wavefront.get_intensity(), horizontal_or_vertical='V') horizontal_phase_profile_wf = line_image(wavefront.get_phase(), horizontal_or_vertical='H') plot(wavefront.get_coordinate_x(), horizontal_profile, wavefront.get_coordinate_y(), vertical_profile, legend=['Horizontal profile', 'Vertical profile'], title="%s" % method, show=show) plot(wavefront.get_coordinate_x(), horizontal_phase_profile_wf, legend=['Horizontal phase profile'], title="%s" % method, show=show) print("Output intensity: ", wavefront.get_intensity().sum())
def test_1d_gaussian_slope_error(self): mirror_length=200.0 step=1.0 rms_slopes=1.3e-7 rms_heights = 1e-7 correlation_length = 10.0 x, f = simulate_profile_1D_gaussian(step=step, \ mirror_length=mirror_length, \ rms_heights=rms_heights, \ correlation_length=correlation_length,\ renormalize_to_slopes_sd=None) slopes = numpy.gradient(f, x[1]-x[0]) print("test_1d_gaussian: test function: %s, Stdev (not normalized): HEIGHTS=%g.SLOPES=%g"%("test_1d_gaussian_slope_error",f.std(),slopes.std())) x, f = simulate_profile_1D_gaussian(step=step, \ mirror_length=mirror_length, \ rms_heights=rms_heights, \ correlation_length=correlation_length,\ renormalize_to_slopes_sd=rms_slopes) slopes = numpy.gradient(f, x[1]-x[0]) print("test_1d_gaussian: test function: %s, SLOPES Stdev (normalized to %g)=%g"%("test_1d_gaussian_slope_error",rms_slopes,slopes.std())) assert numpy.abs( rms_slopes - slopes.std() ) < 0.01 * numpy.abs(rms_slopes) if do_plot: from srxraylib.plot.gol import plot plot(x,slopes,title="test_1d_gaussian_slope_error",xtitle="Y",ytitle="slopes Z'")
def run_limits(): wf_h = run_beamline_horizontal(center=0, angle=0) # wf_hl = run_beamline_horizontal(center=-35e-6,angle=0) # wf_hr = run_beamline_horizontal(center=+35e-6,angle=0) wf_hl = run_beamline_horizontal(center=0, angle=-8e-6) wf_hr = run_beamline_horizontal(center=0, angle=+8e-6) plot(1e6 * wf_h.get_abscissas(), wf_h.get_intensity(), 1e6 * wf_hl.get_abscissas(), wf_hl.get_intensity(), 1e6 * wf_hr.get_abscissas(), wf_hr.get_intensity(), title="wf_h " + get_fwhm_in_microns(wf_h, string=True), legend=["center", "left", "right"], show=False) plot(1e6 * wf_h.get_abscissas(), wf_h.get_intensity() + wf_hl.get_intensity() + wf_hr.get_intensity(), 1e6 * wf_h.get_abscissas(), wf_h.get_intensity(), title="wf_h " + get_fwhm_in_microns(wf_h, string=True), legend=["sum", "center"], show=True)
def test_1d_aps_figure_error(self): mirror_length = 200.0 step = 1.0 random_seed = 898882 rms = 1e-7 # units mm wName_x, wName = create_simulated_1D_file_APS( mirror_length=mirror_length, step=step, random_seed=random_seed, error_type=FIGURE_ERROR, rms=rms) print("%s, HEIGHTS Stdev: input=%g, obtained=%g" % ("test_1d_aps_figure_error", rms, wName.std())) assert numpy.abs(rms - wName.std()) < 0.01 * numpy.abs(rms) if do_plot: from srxraylib.plot.gol import plot plot(wName_x, wName, title="test_1d_aps_figure_error", xtitle="Y", ytitle="heights profile Z")
def test_1d_gaussian_figure_error(self): mirror_length = 200.0 step = 1.0 rms = 1e-7 correlation_length = 10.0 x, f = simulate_profile_1D_gaussian(step=step, \ mirror_length=mirror_length, \ rms_heights=rms, \ correlation_length=correlation_length,\ renormalize_to_heights_sd=None) slopes = numpy.gradient(f, x[1] - x[0]) print( "test_1d_gaussian: test function: %s, Stdev (not normalized): HEIGHTS=%g.SLOPES=%g" % ("test_1d_gaussian_figure_error", f.std(), slopes.std())) x, f = simulate_profile_1D_gaussian(step=step, \ mirror_length=mirror_length, \ rms_heights=rms, \ correlation_length=correlation_length,\ renormalize_to_heights_sd=rms) print( "test_1d_gaussian: test function: %s, HEIGHTS Stdev (normalized to %g)=%g" % ("test_1d_gaussian_figure_error", rms, f.std())) assert numpy.abs(rms - f.std()) < 0.01 * numpy.abs(rms) if do_plot: from srxraylib.plot.gol import plot plot(x, f, title="test_1d_gaussian_figure_error", xtitle="Y", ytitle="heights profile Z")
def get_magnetic_field_ALSU_onlyMag7(do_plot=False, filename=""): drift = 75.0 lengthBM = 500.0 L = 2 * drift + lengthBM y = numpy.linspace(0, L, 2000) B = y * 0.0 B0_7 = -0.876 for i in range(y.size): if y[i] > drift and y[i] < drift + lengthBM: B[i] = B0_7 # plot(y, B) B2 = gaussian_filter1d(B, 2.5) yy = y.copy() yy -= drift + lengthBM / 2 yy *= 1e-3 if do_plot: # plot(yy, B, yy, B2, legend=["original","smoothed"],xtitle="y / m",ytitle="B / T") plot(yy, B2, xtitle="y [m]", ytitle="B [T]", title=filename) if filename != "": f = open(filename, "w") for i in range(y.size): f.write("%f %f\n" % (yy[i], B2[i])) f.close() print("File written to disk: %s" % filename) return yy, B2
def test_1d_aps_slope_error(self): mirror_length = 200.0 step = 1.0 random_seed = 898882 rms = 1e-7 # units mm wName_x, wName = create_simulated_1D_file_APS( mirror_length=mirror_length, step=step, random_seed=random_seed, error_type=SLOPE_ERROR, rms=rms) slopes = numpy.gradient(wName, wName_x[1] - wName_x[0]) print( "test_1d: test function: %s, SLOPES Stdev: input=%g, obtained=%g" % ("test_1d_aps_figure_error", rms, slopes.std())) assert numpy.abs(rms - slopes.std()) < 0.01 * numpy.abs(rms) if do_plot: from srxraylib.plot.gol import plot plot(wName_x, slopes, title="test_1d_aps_slope_error", xtitle="Y", ytitle="slopes Z'")
def twocylinders(y, delta=0.1, radius1=8.84, radius2=8.48, do_plot=False): zc1 = numpy.sqrt(radius1**2 - delta**2) zc2 = numpy.sqrt(radius2**2 - delta**2) A1 = 1.0 B1 = -2 * zc1 C1 = y**2 + zc1**2 - radius1**2 Dis1 = B1**2 - 4 * A1 * C1 z1 = (0.5 / A1) * (-B1 - numpy.sqrt(Dis1)) A2 = 1.0 B2 = -2 * zc2 C2 = y**2 + zc2**2 - radius2**2 Dis2 = B2**2 - 4 * A2 * C2 z2 = (0.5 / A2) * (-B2 - numpy.sqrt(Dis2)) iflat = numpy.argwhere(numpy.abs(y) < delta) z1[iflat] = 0 z2[iflat] = 0 z = z1.copy() iplus = numpy.argwhere(y >= delta) z[iplus] = z2[iplus] if do_plot: plot(y, z1, y, z2, y, z, legend=["z1", "z2", "z"], title="R1: %f, R2: %f" % (radius1, radius2)) return z
def create_file_with_magnetic_field(filename): L = 1605.0 #mm y = numpy.linspace(0, L, 2000) B = y * 0.0 for i in range(y.size): if y[i] > 75 and y[i] < 575: B[i] = -0.876 if y[i] > 650 and y[i] < 975: B[i] = 0.16 if y[i] > 1030 and y[i] < 1530: B[i] = -0.8497 # plot(y, B) B2 = gaussian_filter1d(B, 2.5) y -= y[y.size // 2] y *= 1e-3 plot(y, B, y, B2, legend=["original", "smoothed"], xtitle="y / m", ytitle="B / T") f = open(filename, "w") for i in range(y.size): f.write("%f %f\n" % (y[i], B2[i])) f.close() print("File written to disk: %s" % filename)
def apply_Mirror(wf_in, radius=None, focal_x=1000.0, theta_grazing=1.25*numpy.pi/180.0, do_plot=False): output_wavefront = wf_in.duplicate() if radius is None: radius = 2 * focal_x / numpy.sin(theta_grazing) abscissas = output_wavefront.get_abscissas() abscissas_on_mirror = abscissas / numpy.sin(theta_grazing) if radius >= 0: height = radius - numpy.sqrt( radius**2 - abscissas_on_mirror**2) else: height = radius + numpy.sqrt(radius ** 2 - abscissas_on_mirror ** 2) phi = -2 * output_wavefront.get_wavenumber() * height * numpy.sin(theta_grazing) if do_plot: plot(abscissas_on_mirror, height, title="R = %f"%radius) output_wavefront.add_phase_shifts(phi) return output_wavefront
def RUN_WOFRY(photon_energy=250,do_plot=True,do_optimize_M3=False,error_radius=1e10): wf = gaussian_profile(source(photon_energy=photon_energy)) # plot(wf.get_abscissas(),wf.get_intensity()) focal_x_error = 0.5 * error_radius * numpy.sin(1.25 * numpy.pi / 180) # wf0 = apply_error_on_M1(wf, focal_x=focal_x_error) wf0 = apply_Mirror(wf, error_radius) # <======================================================= wf1 = propagate_from_M1_to_M3(wf0) # plot(wf1.get_abscissas(), wf1.get_intensity()) # # optimization (adaptive optics) # focal_x = 1.0/(1.0/(13.73+13.599)+1.0/(2.64)) # 2.407000 if do_optimize_M3: DELTA_FOCAL_X = numpy.linspace(-0.4,0.4,200) FWHM = numpy.zeros_like(DELTA_FOCAL_X) II = numpy.zeros_like(DELTA_FOCAL_X) # I0 = numpy.zeros_like(DELTA_FOCAL_X) for i in range(DELTA_FOCAL_X.size): # wf2 = apply_M3_focusing(wf1,focal_x=focal_x+DELTA_FOCAL_X[i]) wf2 = apply_Mirror(wf1,focal_x=focal_x+DELTA_FOCAL_X[i]) # <======================================================= wf2 = propagate_from_M3_to_sample(wf2) # plot_wavefront_intensity(wf2) FWHM[i] = get_wavefront_intensity_fwhm(wf2) II[i] = get_wavefront_intensity_I0(wf2) # print("FWHM is: ",FWHM[i]) if do_plot: plot(DELTA_FOCAL_X, FWHM, ytitle="FWHM", xtitle="Delta focal distance [m]") plot(DELTA_FOCAL_X, II, ytitle="I0", xtitle="Delta focal distance [m]") i_opt = II.argmax() # FWHM.argmin() print("Start FWHM [um]: %f, optimized: %f : "%(focal_x,focal_x+FWHM[i_opt])) # print("Radius [start]: %f",get_R_incidence_deg(13.73+13.599,2.64,90-1.25)) print("Radius initial: %f optimized: %f "% (get_R_incidence_deg(1./(1/focal_x-1./2.64), 2.64, 90 - 1.25), get_R_incidence_deg(1./(1/(focal_x+FWHM[i_opt])-1./2.64), 2.64, 90 - 1.25))) # calculate optimized # wf2 = apply_M3_focusing(wf1,focal_x=focal_x+DELTA_FOCAL_X[i_opt]) wf2 = apply_Mirror(wf1, focal_x=focal_x+DELTA_FOCAL_X[i_opt]) # <======================================================= wf2 = propagate_from_M3_to_sample(wf2) else: # wf2 = apply_M3_focusing(wf1, focal_x=focal_x) wf2 = apply_Mirror(wf1, focal_x=focal_x) # <======================================================= wf2 = propagate_from_M3_to_sample(wf2) if do_plot: plot_wavefront_intensity(wf2) print("Using error with radius: %f focal: %f"%(error_radius,focal_x_error)) return wf2
def generic_wfr_add_grating_error(wfr, file_name, do_plot=False): wavelength = wfr.get_wavelength() print(wfr.is_polarized()) # x (mm) measured d-spacing error (nm) e = numpy.loadtxt(file_name, skiprows=1) # plot(e[:, 0], e[:, 1]) alpha_deg = 88.7946477 beta_deg = -87.912865 alpha_grazing = (90 - alpha_deg) * numpy.pi / 180 print(e.shape) x = e[:, 0] * 1e-3 x *= numpy.sin(alpha_grazing) y = e[:, 1] * 1e-9 phi = y / wavelength phi *= numpy.sin(alpha_deg * numpy.pi / 180) + numpy.sin( beta_deg * numpy.pi / 180) # plot(x,phi,xtitle="Diffraction direction perpendicular to axis [m]",ytitle="Phi grating [rad]") yy = wfr.get_coordinate_y() print("wavefront size: ", wfr.size()) print("error file x: min:%f max: %f size: %d" % (x.min(), x.max(), x.size)) print("wavefront yy: min:%f max: %f size: %d" % (yy.min(), yy.max(), yy.size)) phi_interpolated = numpy.interp(yy, x, phi) if do_plot: plot(x, phi, yy, phi_interpolated, legend=["original", "interpolated"], xtitle="Diffraction direction perpendicular to axis [m]", ytitle="Phi grating [rad]") PHI = numpy.zeros(wfr.size()) for i in range(wfr.size()[0]): PHI[i, :] = phi_interpolated if do_plot: plot_image(PHI, wfr.get_coordinate_x(), wfr.get_coordinate_y(), title="PHI in rads") wfr2 = wfr.duplicate() wfr2.add_phase_shifts(PHI, polarization=Polarization.SIGMA) wfr2.add_phase_shifts(PHI, polarization=Polarization.PI) return wfr2
def model_analysis(country1): print("day tomorrowC tomorrowD todayC todayD real-prevision real-prevision coeC coeD") tomorrowC_old, tomorrowD_old, todayC_old, todayD_old = 0,0,0,0 ndays = 45 out = numpy.zeros((ndays,9)) for i,day in enumerate(range(0,-ndays,-1)): tomorrowC, tomorrowD, todayC, todayD, poptC,poptD = analyze_country(country1,do_plot=False,day=day) print("%2d %d %d %d %d %d %d %2.1f %2.1f"%\ (day,tomorrowC, tomorrowD, todayC, todayD,todayC_old-tomorrowC,todayD_old-tomorrowD,poptC,poptD)) out[i,0] = day out[i,1] = tomorrowC out[i,2] = tomorrowD out[i,3] = todayC out[i,4] = todayD out[i,5] = poptC out[i,6] = poptD out[i,7] = todayC_old-tomorrowC out[i,8] = todayD_old-tomorrowD if i==0: out[i, 7] = numpy.nan out[i, 8] = numpy.nan tomorrowC_old, tomorrowD_old, todayC_old, todayD_old = tomorrowC, tomorrowD, todayC, todayD # plot(out[:, 0]+1, out[:, 1], # out[:, 0]+1, out[:, 2], # out[:, 0], out[:, 3], # out[:, 0], out[:, 4], # legend=["Prevision Cases","Prevision Deaths","Cases","Deaths"],ylog=1, # title=country1, # xtitle="Days from today %s"%date.today(), # yrange=[10**1,10**5], # show=0) # # plt.savefig(country1+"_1.png") # plt.show() if (out[:, 6]).max() > 3000: yrange=[0,3000] else: yrange = None plot(out[:, 0], out[:, 5], out[:, 0], out[:, 6], legend=["Double-days Cases", "Double-days Deaths"],marker=['o','o'], title=country1, xtitle="Days from today %s" % date.today(), yrange=yrange, show=0) plt.grid(True) filepng = "../figures/%s_x2.png"%country1 plt.savefig(filepng) print("File %s written to disk"%filepng) plt.show()
def plot_wavefront_intensity(wf, title=""): plot(1e6 * wf.get_abscissas(), wf.get_intensity(), title=title + " FWHM = %f um, I0=%f" % (1e6 * get_wavefront_intensity_fwhm(wf), get_wavefront_intensity_I0(wf)), xtitle="X [um]", ytitle="Intensity [a.u.]")
def showModeDistribution(self): try: from srxraylib.plot.gol import plot y = (self.modeDistribution()).real x = np.arange(y.shape[0]) plot(x, y, title = "Mode distribution", xtitle = "Mode index", ytitle = "Occupancy") except: pass
def propagate_wavefront_scaling_new(wavefront, distance, handler_name=Fresnel1D.HANDLER_NAME, zoom=0.005, using_radius=None): wavefront_inside = wavefront.duplicate() # # if R of curvature to be remove is not defined, guess it # if using_radius is None: plot_scan = True if plot_scan: radii, fig_of_mer = wavefront_inside.scan_wavefront_curvature( rmin=-1000, rmax=1000, rpoints=100) plot(radii, fig_of_mer) using_radius = wavefront_inside.guess_wavefront_curvature(rmin=-1000, rmax=1000, rpoints=100) # # propagate flattened wavefront to a new distance: distance/magnification # slit = WOSlit1D(name="PIRRONE2", boundary_shape=Rectangle( -0.00005, 0.00005, -0.00005, 0.00005, )) coordinates = ElementCoordinates(p=0.0, q=0.0) propagation_elements = PropagationElements() propagation_elements.add_beamline_element( BeamlineElement(optical_element=slit, coordinates=coordinates)) parameters = PropagationParameters( wavefront=wavefront_inside, propagation_elements=propagation_elements) parameters.set_additional_parameters("shift_half_pixel", 1) parameters.set_additional_parameters("magnification_x", zoom) output_wf_1 = propagator.do_propagation(propagation_parameters=parameters, handler_name=handler_name) screen = WOScreen(name="PIRRONE") coordinates = ElementCoordinates(p=0.0, q=distance) propagation_elements = PropagationElements() propagation_elements.add_beamline_element( BeamlineElement(optical_element=screen, coordinates=coordinates)) parameters = PropagationParameters( wavefront=output_wf_1, propagation_elements=propagation_elements) parameters.set_additional_parameters("shift_half_pixel", 1) parameters.set_additional_parameters("magnification_x", zoom) parameters.set_additional_parameters("radius", using_radius) output_wf_2 = propagator.do_propagation(propagation_parameters=parameters, handler_name=handler_name) return output_wf_2
def propagation_to_image(wf,do_plot=do_plot,plot_title="Before lens",method='fft', propagation_distance=30.0,defocus_factor=1.0,propagation_steps=1,show=1): method_label = "fresnel (%s)"%method print("\n# ") print("# near field fresnel (%s) diffraction and focusing "%(method_label)) print("# ") # \ | / # * | | | * # / | \ # <------- d ---------------><--------- d -------> # d is propagation_distance print("Incident intensity: ",wf.get_intensity().sum()) # propagation downstream the lens to image plane for i in range(propagation_steps): if propagation_steps > 1: print(">>> Propagating step %d of %d; propagation_distance=%g m"%(i+1,propagation_steps, propagation_distance*defocus_factor/propagation_steps)) if method == 'fft': wf = propagate_2D_fresnel(wf, propagation_distance*defocus_factor/propagation_steps) elif method == 'convolution': wf = propagate_2D_fresnel_convolution(wf, propagation_distance*defocus_factor/propagation_steps) elif method == 'srw': wf = propagate_2D_fresnel_srw(wf, propagation_distance*defocus_factor/propagation_steps) elif method == 'fraunhofer': wf = propagate_2D_fraunhofer(wf, propagation_distance*defocus_factor/propagation_steps) else: raise Exception("Not implemented method: %s"%method) horizontal_profile = wf.get_intensity()[:,wf.size()[1]/2] horizontal_profile /= horizontal_profile.max() print("FWHM of the horizontal profile: %g um"%(1e6*line_fwhm(horizontal_profile)*wf.delta()[0])) vertical_profile = wf.get_intensity()[wf.size()[0]/2,:] vertical_profile /= vertical_profile.max() print("FWHM of the vertical profile: %g um"%(1e6*line_fwhm(vertical_profile)*wf.delta()[1])) if do_plot: from srxraylib.plot.gol import plot,plot_image plot_image(wf.get_intensity(),1e6*wf.get_coordinate_x(),1e6*wf.get_coordinate_y(), xtitle="X um",ytitle="Y um",title='intensity (%s)'%method,show=0) # plot_image(wf.get_amplitude(),wf.get_coordinate_x(),wf.get_coordinate_y(),title='amplitude (%s)'%method,show=0) plot_image(wf.get_phase(),1e6*wf.get_coordinate_x(),1e6*wf.get_coordinate_y(), xtitle="X um",ytitle="Y um",title='phase (%s)'%method,show=0) plot(wf.get_coordinate_x(),horizontal_profile, wf.get_coordinate_y(),vertical_profile, legend=['Horizontal profile','Vertical profile'],title="%s %s"%(plot_title,method),show=show) print("Output intensity: ",wf.get_intensity().sum()) return wf,wf.get_coordinate_x(),horizontal_profile
def test_aw1(): a = MLayer.pre_mlayer( interactive=False, FILE="pre_mlayer.dat", E_MIN=100.0, #100.0, E_MAX=5000.0, #1000.0, O_DENSITY=7.19, O_MATERIAL="Cr", # odd: closer to vacuum E_DENSITY=3.00, E_MATERIAL="Sc", # even: closer to substrate S_DENSITY=2.33, S_MATERIAL="Si", # substrate GRADE_DEPTH=0, N_PAIRS=50, THICKNESS=22.0, GAMMA=10.0/22.0, # gamma ratio = t(even) / (t(odd) + t(even))") ROUGHNESS_EVEN=0.0, ROUGHNESS_ODD=0.0, FILE_DEPTH="myfile_depth.dat", GRADE_SURFACE=0, FILE_SHADOW="mlayer1.sha", FILE_THICKNESS="mythick.dat", FILE_GAMMA="mygamma.dat", AA0=1.0,AA1=0.0,AA2=0.0,AA3=0.0) # # energy scan # rs, rp, e, t = a.scan(h5file="", #"pre_mlayer_scan.dat", energyN=300, energy1=300.0, #300.0, energy2=500.0, #500.0, thetaN=1, theta1=45.0, theta2=45.0, ) print(rs.shape,rp.shape,e.shape,t.shape) if DO_PLOTS: plot(e,rs[:,0],xtitle="Photon energy [eV]",ytitle="Reflectivity",title="Example AW",) if COMPARE_WITH_SHADOW3: f = open("shadow3.inp",'w') f.write("pre_mlayer_scan\npre_mlayer.dat\n300\n1\n300.0\n500.0\n45.0\nexit\n") f.close() os.system(SHADOW3_BINARY+" < shadow3.inp") s3 = numpy.loadtxt("pre_mlayer_scan.dat",skiprows=5) print(s3.shape) if DO_PLOTS: plot(s3[:,0],s3[:,2],e, rs[:,0], xtitle="energy [eV]", ytitle="Reflectivity", title="Example AW", legend = ["shadow3 (pre_mlayer_scan)","shadow4 (MLayer)"]) print(s3[:,0].shape,s3[:,2].shape,t.shape, rs[:,0].shape) assert_almost_equal(s3[:,2],rs[:,0],5)
def propagation_to_image(wf,do_plot=do_plot,plot_title="Before lens",method='fft', propagation_distance=30.0,defocus_factor=1.0,propagation_steps=1,show=1): method_label = "fresnel (%s)"%method print("\n# ") print("# near field fresnel (%s) diffraction and focusing "%(method_label)) print("# ") # \ | / # * /users/pirro/Documents/workspace/syned | | | * # / | \ # <------- d ---------------><--------- d -------> # d is propagation_distance print("Incident intensity: ",wf.get_intensity().sum()) # propagation downstream the lens to image plane for i in range(propagation_steps): if propagation_steps > 1: print(">>> Propagating step %d of %d; propagation_distance=%g m"%(i+1,propagation_steps, propagation_distance*defocus_factor/propagation_steps)) if method == 'fft': wf = propagate_2D_fresnel(wf, propagation_distance*defocus_factor/propagation_steps) elif method == 'convolution': wf = propagate_2D_fresnel_convolution(wf, propagation_distance*defocus_factor/propagation_steps) elif method == 'srw': wf = propagate_2D_fresnel_srw(wf, propagation_distance*defocus_factor/propagation_steps) elif method == 'fraunhofer': wf = propagate_2D_fraunhofer(wf, propagation_distance*defocus_factor/propagation_steps) else: raise Exception("Not implemented method: %s"%method) horizontal_profile = wf.get_intensity()[:,int(wf.size()[1]/2)] horizontal_profile /= horizontal_profile.max() print("FWHM of the horizontal profile: %g um"%(1e6*line_fwhm(horizontal_profile)*wf.delta()[0])) vertical_profile = wf.get_intensity()[int(wf.size()[0]/2),:] vertical_profile /= vertical_profile.max() print("FWHM of the vertical profile: %g um"%(1e6*line_fwhm(vertical_profile)*wf.delta()[1])) if do_plot: from srxraylib.plot.gol import plot,plot_image plot_image(wf.get_intensity(),1e6*wf.get_coordinate_x(),1e6*wf.get_coordinate_y(), xtitle="X um (%d pixels)"%(wf.size()[0]),ytitle="Y um (%d pixels)",title='intensity (%s)'%method,show=False) plot_image(wf.get_phase(),1e6*wf.get_coordinate_x(),1e6*wf.get_coordinate_y(), xtitle="X um (%d pixels)"%(wf.size()[0]),ytitle="Y um (%d pixels)"%(wf.size[1]),title='phase (%s)'%method,show=False) plot(wf.get_coordinate_x(),horizontal_profile, wf.get_coordinate_y(),vertical_profile, legend=['Horizontal profile','Vertical profile'],title="%s %s"%(plot_title,method),show=show) print("Output intensity: ",wf.get_intensity().sum()) return wf,wf.get_coordinate_x(),horizontal_profile
def test_xoppy_defauls(): a = MLayer.pre_mlayer( interactive=False, FILE="pre_mlayer.dat", E_MIN=5000.0, E_MAX=10000.0, O_DENSITY=2.33, O_MATERIAL="Si", # odd: closer to vacuum E_DENSITY=19.3, E_MATERIAL="W", # even: closer to substrate S_DENSITY=2.33, S_MATERIAL="Si", # substrate GRADE_DEPTH=0, N_PAIRS=50, THICKNESS=50.0, GAMMA=0.5, # gamma ratio = t(even) / (t(odd) + t(even))") ROUGHNESS_EVEN=0.0, ROUGHNESS_ODD=0.0, FILE_DEPTH="myfile_depth.dat", GRADE_SURFACE=0, FILE_SHADOW="mlayer1.sha", FILE_THICKNESS="mythick.dat", FILE_GAMMA="mygamma.dat", AA0=1.0, AA1=0.0, AA2=0.0, AA3=0.0) # # theta scan # rs, rp, e, t = a.scan( energyN=1, energy1=8050.0, energy2=8050.0, thetaN=600, theta1=0.0, theta2=6.0) print(rs.shape, rp.shape, e.shape, t.shape) if DO_PLOTS: plot(t, rs[0], xtitle="angle [deg]", ytitle="Reflectivity", title="Default xoppy", ylog=False) # a.plot_optical_constants() if COMPARE_WITH_SHADOW3: f = open("shadow3.inp",'w') f.write("pre_mlayer_scan\npre_mlayer.dat\n1\n600\n8050\n0.0\n6.0\nexit\n") f.close() os.system(SHADOW3_BINARY+" < shadow3.inp") s3 = numpy.loadtxt("pre_mlayer_scan.dat",skiprows=5) print(s3.shape) if DO_PLOTS: plot(s3[:,1],s3[:,2],t, rs[0], xtitle="angle [deg]", ytitle="Reflectivity", title="Default xoppy", legend = ["shadow3 (pre_mlayer_scan)","shadow4 (MLayer)"]) print(s3[:,1].shape,s3[:,2].shape,t.shape, rs[0].shape) assert_almost_equal(s3[:,2], rs[0], 4)
def showModeDistribution(self): try: from srxraylib.plot.gol import plot y = (self.modeDistribution()).real x = np.arange(y.shape[0]) plot(x, y, title="Mode distribution", xtitle="Mode index", ytitle="Occupancy") except: pass
def test_plane_wave(self,do_plot=do_plot): # # plane wave # print("# ") print("# Tests for a 1D plane wave ") print("# ") wavelength = 1.24e-10 wavefront_length_x = 400e-6 npixels_x = 1024 wavefront_x = numpy.linspace(-0.5*wavefront_length_x,0.5*wavefront_length_x,npixels_x) wavefront = Wavefront1D.initialize_wavefront_from_steps( x_start=wavefront_x[0],x_step=numpy.abs(wavefront_x[1]-wavefront_x[0]), number_of_points=npixels_x,wavelength=wavelength) numpy.testing.assert_almost_equal(wavefront_x,wavefront.get_abscissas(),9) # possible modifications wavefront.set_plane_wave_from_amplitude_and_phase(5.0,numpy.pi/2) numpy.testing.assert_almost_equal(wavefront.get_intensity(),25,5) wavefront.set_plane_wave_from_complex_amplitude(2.0+3j) numpy.testing.assert_almost_equal(wavefront.get_intensity(),13,5) phase_before = wavefront.get_phase() wavefront.add_phase_shift(numpy.pi/2) phase_after = wavefront.get_phase() numpy.testing.assert_almost_equal(phase_before+numpy.pi/2,phase_after,5) intensity_before = wavefront.get_intensity() wavefront.rescale_amplitude(10.0) intensity_after = wavefront.get_intensity() numpy.testing.assert_almost_equal(intensity_before*100,intensity_after,5) # interpolation wavefront.set_plane_wave_from_complex_amplitude(2.0+3j) test_value1 = wavefront.get_interpolated_complex_amplitude(0.01) self.assertAlmostEqual( (2.0+3j).real, test_value1.real, 5) self.assertAlmostEqual( (2.0+3j).imag, test_value1.imag, 5) if do_plot: from srxraylib.plot.gol import plot plot(wavefront.get_abscissas(),wavefront.get_intensity(),title="Intensity (plane wave)",show=0) plot(wavefront.get_abscissas(),wavefront.get_phase(),title="Phase (plane wave)",show=1)
def change_trajectory(simulation_test_input): simulation_test = simulation_test_input.copy() t = simulation_test.trajectory.t x = simulation_test.trajectory.x y = simulation_test.trajectory.y z = simulation_test.trajectory.z x0 = x.copy() x *= codata.c xM = x.max() x /= xM # x = np.sign(x) a = 0.099/2 tt = t*codata.c + 20 x = (2/a) * (tt - a * np.fix(tt/a + 0.5) ) * (-1)**(np.fix(tt/a-0.5)) x = x * xM / codata.c # v_x = simulation_test.trajectory.v_x * 0 # v_y = simulation_test.trajectory.v_y * 0 # v_z = simulation_test.trajectory.v_z * 0 v_x = np.gradient(x, t) v_y = np.gradient(y, t) v_z = np.gradient(z, t) a_x = simulation_test.trajectory.a_x * 0 a_y = simulation_test.trajectory.a_y * 0 a_z = simulation_test.trajectory.a_z * 0 plot(z*codata.c,x0,z*codata.c,x,legend=["sinusoidal","modified"]) simulation_test_input.trajectory = Trajectory(t=t,x=x,y=y,z=z,v_x=v_x,v_y=v_y,v_z=v_z, a_x=a_x,a_y=a_y,a_z=a_z) return simulation_test
def get_magnetic_field_ALSU_centeredMag7(do_plot=False, filename=""): drift = 75.0 lengthBM = 500.0 lengthAB = 305 L = 4 * drift + 2 * lengthAB + lengthBM # 1605.0 #mm L = 5 * drift + 2 * lengthAB + 2 * lengthBM # 1605.0 #mm y = numpy.linspace(0, L, 2000) B = y * 0.0 B0_7 = -0.876 B0_AB = 0.16 B0_8 = -0.8497 for i in range(y.size): # if y[i] > drift and y[i] < drift+lengthBM: B[i] = -0.876 # if y[i] > 2*drift+lengthBM and y[i] < 2*drift+lengthBM+lengthAB: B[i] = 0.16 # if y[i] > 3*drift+lengthBM+lengthAB and y[i] < 3*drift+2*lengthBM+lengthAB: B[i] = -0.8497 if y[i] > drift and y[i] < drift + lengthAB: B[i] = B0_AB if y[i] > 2 * drift + lengthAB and y[ i] < 2 * drift + lengthAB + lengthBM: B[i] = B0_7 if y[i] > 3 * drift + lengthAB + lengthBM and y[ i] < 3 * drift + 2 * lengthAB + lengthBM: B[i] = B0_AB if y[i] > 4 * drift + 2 * lengthAB + lengthBM and y[ i] < 4 * drift + 2 * lengthAB + 2 * lengthBM: B[i] = B0_8 # plot(y, B) B2 = gaussian_filter1d(B, 2.5) yy = y.copy() yy -= 2 * drift + lengthAB + lengthBM / 2 yy *= 1e-3 if do_plot: # plot(yy, B, yy, B2, legend=["original","smoothed"],xtitle="y / m",ytitle="B / T") plot(yy, B2, xtitle="y [m]", ytitle="B [T]", title=filename) if filename != "": f = open(filename, "w") for i in range(y.size): f.write("%f %f\n" % (yy[i], B2[i])) f.close() print("File written to disk: %s" % filename) return yy, B2
def get_tkt_fwhm(tkt): from srxraylib.plot.gol import plot # from oasys.util.oasys_util import get_fwhm x = tkt["bin_h_center"] y = tkt["bin_v_center"] hx = tkt["histogram_h"] hy = tkt["histogram_v"] plot(x, hx) plot(y, hy) fwhm_x, _, _ = get_fwhm(hx, x) fwhm_y, _, _ = get_fwhm(hy, y) return fwhm_x, fwhm_y
def test_spherical_wave(self, do_plot=do_plot): # # plane wave # print("# ") print("# Tests for a 1D spherical wave ") print("# ") wavelength = 1.24e-10 wavefront_length_x = 400e-6 npixels_x = 1024 wavefront_x = numpy.linspace(-0.5 * wavefront_length_x, 0.5 * wavefront_length_x, npixels_x) wf1 = GenericWavefront1D.initialize_wavefront_from_steps( x_start=wavefront_x[0], x_step=numpy.abs(wavefront_x[1] - wavefront_x[0]), number_of_points=npixels_x, wavelength=wavelength) wf2 = GenericWavefront1D.initialize_wavefront_from_steps( x_start=wavefront_x[0], x_step=numpy.abs(wavefront_x[1] - wavefront_x[0]), number_of_points=npixels_x, wavelength=wavelength) # an spherical wavefront is obtained 1) by creation, 2) focusing a planewave wf1.set_spherical_wave(radius=-5.0, complex_amplitude=3 + 0j) wf1.clip(-50e-6, 10e-6) wf2.set_plane_wave_from_complex_amplitude(3 + 0j) ideal_lens = WOIdealLens1D("test", 5.0) ideal_lens.applyOpticalElement(wf2) wf2.clip(-50e-6, 10e-6) if do_plot: from srxraylib.plot.gol import plot plot(wf1.get_abscissas(), wf1.get_phase(), title="Phase of spherical wavefront", show=0) plot(wf2.get_abscissas(), wf2.get_phase(), title="Phase of focused plane wavefront", show=0) plot(wf1.get_abscissas(), wf1.get_phase(from_minimum_intensity=0.1), title="Phase of spherical wavefront (for intensity > 0.1)", show=0) plot( wf2.get_abscissas(), wf2.get_phase(from_minimum_intensity=0.1), title="Phase of focused plane wavefront (for intensity > 0.1)", show=1) numpy.testing.assert_almost_equal(wf1.get_phase(), wf2.get_phase(), 5)
def test_plane_wave(do_plot=0): import copy # # plane wave # value_amplitude = 5.0 value_phase = numpy.pi wavefront = Wavefront1D.initialize_wavefront_from_range( wavelength=1e-2, number_of_points=1000000, x_min=-1, x_max=1) wavefront.set_plane_wave_from_amplitude_and_phase(value_amplitude, value_phase) wavefront.apply_slit(-0.4, 0.4) wavefront_focused = copy.deepcopy(wavefront) wavefront_focused.apply_ideal_lens(100) # # some tests # test_value1 = wavefront.get_interpolated_amplitude(0.01) - value_amplitude assert (numpy.abs(test_value1) < 1e-6) test_value2 = wavefront.get_interpolated_amplitudes(-4) assert (numpy.abs(test_value2) < 1e-6) if do_plot: from srxraylib.plot.gol import plot plot( wavefront.get_abscissas(), wavefront.get_intensity(), show=0, title="Plane wave defined in [-1,1] and clipped by a [-.4,.4] slit", xtitle="X (m)", ytitle="Intensity") plot( wavefront.get_abscissas(), wavefront.get_amplitude(), show=0, title="Plane wave defined in [-1,1] and clipped by a [-.4,.4] slit", xtitle="X (m)", ytitle="Amplitude") plot( wavefront.get_abscissas(), wavefront.get_phase(), show=0, title="Plane wave defined in [-1,1] and clipped by a [-.4,.4] slit", xtitle="X (m)", ytitle="Phase [rad]") plot(wavefront.get_abscissas(), wavefront_focused.get_phase(), show=1, title="Plane wave after ideal lens", xtitle="X (m)", ytitle="Phase [rad]")
def test_1d_fractal_figure_error(self): mirror_length=200.0 step=1.0 rms=1.25e-7 x, f = simulate_profile_1D_fractal(step=step,mirror_length=mirror_length, renormalize_to_heights_sd=rms) print("%s, HEIGHTS Stdev: input=%g, obtained=%g"%("test_1d_fractal_figure_error",rms,f.std())) assert numpy.abs( rms - f.std() ) < 0.01 * numpy.abs(rms) if do_plot: from srxraylib.plot.gol import plot plot(x,f,title="test_1d_fractal_figure_error",xtitle="Y",ytitle="heights profile Z")
def test_1d_fractal_slope_error(self): mirror_length=200.0 step=1.0 rms=3e-6 x, f = simulate_profile_1D_fractal(step=step,mirror_length=mirror_length, renormalize_to_slopes_sd=rms) slopes = numpy.gradient(f, x[1]-x[0]) print("%s, SLOPES Stdev: input=%g, obtained=%g"%("test_1d_fractal_slope_error",rms,slopes.std())) assert numpy.abs( rms - slopes.std() ) < 0.01 * numpy.abs(rms) if do_plot: from srxraylib.plot.gol import plot plot(x,slopes,title="test_1d_fractal_slope_error",xtitle="Y",ytitle="slopes Z'")
def run_v(): wf_v = run_beamline_vertical(center=0, angle=0, fresnel=False) plot(1e9 * wf_v.get_abscissas(), wf_v.get_intensity(), xtitle="H [nm]", ytitle="V [nm]", xrange=[-50, 50], show=False) print(">>>> FWHM V [um]: ", get_fwhm_in_microns(wf_v)) plt.savefig("/tmp/wofry1Dv.png") print("File written to disk: /tmp/wofry1Dv.png") plt.show()
def test_1d_aps_figure_error(self): mirror_length=200.0 step=1.0 random_seed=898882 rms=1e-7 # units mm wName_x,wName = create_simulated_1D_file_APS(mirror_length=mirror_length,step=step, random_seed=random_seed, error_type=FIGURE_ERROR, rms=rms) print("%s, HEIGHTS Stdev: input=%g, obtained=%g"%("test_1d_aps_figure_error",rms,wName.std())) assert numpy.abs( rms - wName.std() ) < 0.01 * numpy.abs(rms) if do_plot: from srxraylib.plot.gol import plot plot(wName_x,wName,title="test_1d_aps_figure_error",xtitle="Y",ytitle="heights profile Z")
def lateral_histogram(H,coordinate='Y',show=1, filename="", title=""): if coordinate == 'Y': direction = "h" else: direction = 'v' # CALCULATE fwhm h hh = h["histogram_%s"%direction] bin = h["bin_%s_center"%direction] tt = numpy.where(hh >= max(hh) * 0.1) if hh[tt].size > 1: binSize = bin[1] - bin[0] fwp1m = binSize * (tt[0][-1] - tt[0][0]) fwp1m_coordinates = (bin[tt[0][0]], bin[tt[0][-1]]) print(fwp1m, fwp1m_coordinates) xt = numpy.array([1e3*bin.min(),1e3*bin.max()]) yt = numpy.array([0.1*hh.max(),0.1*hh.max()]) f = plot(1e3*bin, hh, xt, yt, xtitle="%s [mm]"%coordinate, title=title+"; Size at 0.1*height: %7.1f mm"%(1e3*fwp1m),show=0) if filename != "": f[0].savefig(filename) print("File written to disk: ",filename) if show: plot_show() return 1e3*fwp1m
def test_1d_aps_slope_error(self): mirror_length=200.0 step=1.0 random_seed=898882 rms=1e-7 # units mm wName_x,wName = create_simulated_1D_file_APS(mirror_length=mirror_length,step=step, random_seed=random_seed, error_type=SLOPE_ERROR, rms=rms) slopes = numpy.gradient(wName, wName_x[1]-wName_x[0]) print("test_1d: test function: %s, SLOPES Stdev: input=%g, obtained=%g"%("test_1d_aps_figure_error",rms,slopes.std())) assert numpy.abs( rms - slopes.std() ) < 0.01 * numpy.abs(rms) if do_plot: from srxraylib.plot.gol import plot plot(wName_x,slopes,title="test_1d_aps_slope_error",xtitle="Y",ytitle="slopes Z'")
def test_initializers(self,do_plot=do_plot): print("# ") print("# Tests for initializars (1D) ") print("# ") x = numpy.linspace(-100,100,50) y = numpy.abs(x)**1.5 + 1j*numpy.abs(x)**1.8 wf0 = Wavefront1D.initialize_wavefront_from_steps(x[0],numpy.abs(x[1]-x[0]),y.size) wf0.set_complex_amplitude(y) wf1 = Wavefront1D.initialize_wavefront_from_range(x[0],x[-1],y.size) wf1.set_complex_amplitude(y) wf2 = Wavefront1D.initialize_wavefront_from_arrays(x,y) print("wavefront sizes: ",wf1.size(),wf1.size(),wf2.size()) if do_plot: from srxraylib.plot.gol import plot plot(wf0.get_abscissas(),wf0.get_intensity(), title="initialize_wavefront_from_steps",show=0) plot(wf1.get_abscissas(),wf1.get_intensity(), title="initialize_wavefront_from_range",show=0) plot(wf2.get_abscissas(),wf2.get_intensity(), title="initialize_wavefront_from_arrays",show=1) numpy.testing.assert_almost_equal(wf0.get_intensity(),numpy.abs(y)**2,5) numpy.testing.assert_almost_equal(wf1.get_intensity(),numpy.abs(y)**2,5) numpy.testing.assert_almost_equal(x,wf1.get_abscissas(),11) numpy.testing.assert_almost_equal(x,wf2.get_abscissas(),11)
def test_interpolator(self,do_plot=do_plot): # # interpolator # print("# ") print("# Tests for 1D interpolator ") print("# ") x = numpy.linspace(-10,10,100) sigma = 3.0 Z = numpy.exp(-1.0*x**2/2/sigma**2) print("shape of Z",Z.shape) wf = Wavefront1D.initialize_wavefront_from_steps(x[0],numpy.abs(x[1]-x[0]),number_of_points=100) print("wf shape: ",wf.size()) wf.set_complex_amplitude( Z ) x1 = 3.2 z1 = numpy.exp(x1**2/-2/sigma**2) print("complex ampl at (%g): %g+%gi (exact=%g)"%(x1, wf.get_interpolated_complex_amplitude(x1).real, wf.get_interpolated_complex_amplitude(x1).imag, z1)) self.assertAlmostEqual(wf.get_interpolated_complex_amplitude(x1).real,z1,4) print("intensity at (%g): %g (exact=%g)"%(x1,wf.get_interpolated_intensity(x1),z1**2)) self.assertAlmostEqual(wf.get_interpolated_intensity(x1),z1**2,4) if do_plot: from srxraylib.plot.gol import plot plot(wf.get_abscissas(),wf.get_intensity(),title="Original",show=1) xx = wf.get_abscissas() yy = wf.get_interpolated_intensities(wf.get_abscissas()-1e-5) plot(xx,yy,title="interpolated on same grid",show=1)
def test_spherical_wave(self,do_plot=do_plot): # # plane wave # print("# ") print("# Tests for a 1D spherical wave ") print("# ") wavelength = 1.24e-10 wavefront_length_x = 400e-6 npixels_x = 1024 wavefront_x = numpy.linspace(-0.5*wavefront_length_x,0.5*wavefront_length_x,npixels_x) wf1 = Wavefront1D.initialize_wavefront_from_steps( x_start=wavefront_x[0],x_step=numpy.abs(wavefront_x[1]-wavefront_x[0]), number_of_points=npixels_x,wavelength=wavelength) wf2 = Wavefront1D.initialize_wavefront_from_steps( x_start=wavefront_x[0],x_step=numpy.abs(wavefront_x[1]-wavefront_x[0]), number_of_points=npixels_x,wavelength=wavelength) # an spherical wavefront is obtained 1) by creation, 2) focusing a planewave wf1.set_spherical_wave(-5.0, 3+0j) wf1.apply_slit(-50e-6,10e-6) wf2.set_plane_wave_from_complex_amplitude(3+0j) wf2.apply_ideal_lens(5.0) wf2.apply_slit(-50e-6,10e-6) if do_plot: from srxraylib.plot.gol import plot plot(wf1.get_abscissas(),wf1.get_phase(),title="Phase of spherical wavefront",show=0) plot(wf2.get_abscissas(),wf2.get_phase(),title="Phase of focused plane wavefront",show=0) plot(wf1.get_abscissas(),wf1.get_phase(from_minimum_intensity=0.1),title="Phase of spherical wavefront (for intensity > 0.1)",show=0) plot(wf2.get_abscissas(),wf2.get_phase(from_minimum_intensity=0.1),title="Phase of focused plane wavefront (for intensity > 0.1)",show=1) numpy.testing.assert_almost_equal(wf1.get_phase(),wf2.get_phase(),5)
h5w = H5SimpleWriter.initialize_file(h5_file,creator="xoppy_undulators.py") else: h5w = H5SimpleWriter(h5_file,None) h5w.create_entry(h5_entry_name,nx_default=None) h5w.add_stack(e,h,v,p,stack_name="Radiation",entry_name=h5_entry_name, title_0="Photon energy [eV]", title_1="X gap [mm]", title_2="Y gap [mm]") h5w.create_entry("parameters",root_entry=h5_entry_name,nx_default=None) for key in h5_parameters.keys(): h5w.add_key(key,h5_parameters[key], entry_name=h5_entry_name+"/parameters") print("File written to disk: %s"%h5_file) except: print("ERROR initializing h5 file") return e, h, v, p, code if __name__ == "__main__": from srxraylib.plot.gol import plot,plot_image e, f, spectral_power, cumulated_power = xoppy_calc_undulator_spectrum() plot(e,f) h, v, p, code = xoppy_calc_undulator_power_density(h5_file="test.h5",h5_initialize=True) plot_image(p,h,v) e, h, v, p, code = xoppy_calc_undulator_radiation(ELECTRONENERGY=6.0, h5_file="test.h5",h5_entry_name="first_entry",h5_initialize=True) e, h, v, p, code = xoppy_calc_undulator_radiation(ELECTRONENERGY=7.0, h5_file="test.h5",h5_entry_name="second_entry",h5_initialize=False)
def test_ScaledArray(self,do_plot=do_plot): # # ScaledArray.initialize + set_scale_from_steps # test_array = numpy.arange(15.0, 18.8, 0.2) print("\nTesting ScaledArray.initialize + set_scale_from_steps...") scaled_array = ScaledArray.initialize(test_array) scaled_array.set_scale_from_steps(test_array[0],0.2) print("Using array: ",test_array) print("Stored array: ",scaled_array.get_values()) print("Using array: ",test_array) print("Stored abscissas: ",scaled_array.get_abscissas()) numpy.testing.assert_almost_equal(test_array,scaled_array.get_values(),11) numpy.testing.assert_almost_equal(test_array,scaled_array.get_abscissas(),11) self.assertAlmostEqual(0.2,scaled_array.delta(),11) self.assertAlmostEqual(15.0,scaled_array.offset(),11) x_in = (18.80,16.22,22.35) x_good = (18.80,16.22,18.8) for i,x in enumerate(x_in): print("interpolated at %3.2f is: %3.2f (must give %3.2f)"%( x,scaled_array.interpolate_value(x), x_good[i] )) self.assertAlmostEqual(scaled_array.interpolate_value(x), x_good[i], 2) # # ScaledArray.initialize + set_scale_from_range ; interpolate vectorized # print("\nTesting ScaledArray.initialize + set_scale_from_range ; interpolate vectorized...") scaled_array = ScaledArray.initialize(test_array) scaled_array.set_scale_from_range(test_array[0],test_array[-1]) x_in = (18.80,16.22,22.35) x_good = (18.80,16.22,18.8) for i,x in enumerate(x_in): print("interpolated at %3.2f is: %3.2f (must give %3.2f)"%( x,scaled_array.interpolate_value(x), x_good[i] )) self.assertAlmostEqual(scaled_array.interpolate_value(x), x_good[i], 2) # # ScaledArray.initialize_from_steps # print("\nTesting ScaledArray.initialize_from_steps...") scaled_array = ScaledArray.initialize_from_steps(test_array, test_array[0], 0.2) x_in = (18.80,16.22,22.35) x_good = (18.80,16.22,18.8) for i,x in enumerate(x_in): print("interpolated at %3.2f is: %3.2f (must give %3.2f)"%( x,scaled_array.interpolate_value(x), x_good[i] )) self.assertAlmostEqual(scaled_array.interpolate_value(x), x_good[i], 2) # # ScaledArray.initialize_from_steps # print("\nTesting ScaledArray.initialize_from_range...") scaled_array = ScaledArray.initialize_from_range(test_array,test_array[0], test_array[-1]) x_in = (18.80,16.22,22.35) x_good = (18.80,16.22,18.8) for i,x in enumerate(x_in): print("interpolated at %3.2f is: %3.2f (must give %3.2f)"%( x,scaled_array.interpolate_value(x), x_good[i] )) self.assertAlmostEqual(scaled_array.interpolate_value(x), x_good[i], 2) # # interpolator # print("\nTesting interpolator...") x = numpy.arange(-5.0, 18.8, 3) y = x**2 scaled_array = ScaledArray.initialize_from_range(y,x[0],x[-1]) print("for interpolation; x=",x) print("for interpolation; offset, delta:=",scaled_array.offset(),scaled_array.delta()) print("for interpolation; abscissas:=",scaled_array.get_abscissas()) x1 = numpy.concatenate( ( numpy.arange(-6, -4, 0.1) , [0], numpy.arange(11, 20.0, 0.1) ) ) y1 = scaled_array.interpolate_values(x1) if do_plot: from srxraylib.plot.gol import plot plot(x,y,x1,y1,legend=["Data",'Interpolated'],legend_position=[0.4,0.8], marker=['','o'],linestyle=['-',''],xrange=[-6,21],yrange=[-5,375]) for i in range(len(x1)): y2 = x1[i]**2 if x1[i] <= x[0]: y2 = y[0] if x1[i] >= x[-1]: y2 = y[-1] print(" interpolated at x=%g is: %g (expected: %g)"%(x1[i],y1[i],y2)) self.assertAlmostEqual(1e-3*y1[i], 1e-3*y2, 2) # interpolate on same grid print("\nTesting interpolation on the same grid...") y1 = scaled_array.interpolate_values(scaled_array.get_abscissas()) if do_plot: from srxraylib.plot.gol import plot plot(scaled_array.get_abscissas(),scaled_array.get_values(), scaled_array.get_abscissas(),y1,legend=["Data",'Interpolated on same grid'],legend_position=[0.4,0.8], marker=['','o'],linestyle=['-','']) numpy.testing.assert_almost_equal(scaled_array.get_values(),y1,5)
def propagation_with_lens(self,do_plot=do_plot,method='fft', wavelength=1.24e-10, pixelsize_x=1e-6,npixels_x=2000,pixelsize_y=1e-6,npixels_y=2000, propagation_distance=30.0,defocus_factor=1.0,propagation_steps=1,show=1): method_label = "fresnel (%s)"%method print("\n# ") print("# near field fresnel (%s) diffraction and focusing "%(method_label)) print("# ") # \ | / # * | | | * # / | \ # <------- d ---------------><--------- d -------> # d is propagation_distance # wf = Wavefront2D.initialize_wavefront_from_steps(x_start=-pixelsize_x*npixels_x/2, # x_step=pixelsize_x, # y_start=-pixelsize_y*npixels_y/2, # y_step=pixelsize_y, # wavelength=wavelength, # number_of_points=(npixels_x,npixels_y)) wf = Wavefront2D.initialize_wavefront_from_range(x_min=-pixelsize_x*npixels_x/2,x_max=pixelsize_x*npixels_x/2, y_min=-pixelsize_y*npixels_y/2,y_max=pixelsize_y*npixels_y/2, number_of_points=(npixels_x,npixels_y),wavelength=wavelength) spherical_or_plane_and_lens = 0 if spherical_or_plane_and_lens == 0: # set spherical wave at the lens entrance (radius=distance) wf.set_spherical_wave(complex_amplitude=1.0,radius=-propagation_distance) else: # apply lens that will focus at propagation_distance downstream the lens. # Note that the vertical is a bit defocused wf.set_plane_wave_from_complex_amplitude(1.0+0j) focal_length = propagation_distance # / 2 wf.apply_ideal_lens(focal_length,focal_length) print("Incident intensity: ",wf.get_intensity().sum()) # propagation downstream the lens to image plane for i in range(propagation_steps): if propagation_steps > 1: print(">>> Propagating step %d of %d; propagation_distance=%g m"%(i+1,propagation_steps, propagation_distance*defocus_factor/propagation_steps)) if method == 'fft': wf = propagate_2D_fresnel(wf, propagation_distance*defocus_factor/propagation_steps) elif method == 'convolution': wf = propagate_2D_fresnel_convolution(wf, propagation_distance*defocus_factor/propagation_steps) elif method == 'srw': wf = propagate_2D_fresnel_srw(wf, propagation_distance*defocus_factor/propagation_steps) elif method == 'fraunhofer': wf = propagate_2D_fraunhofer(wf, propagation_distance*defocus_factor/propagation_steps) else: raise Exception("Not implemented method: %s"%method) horizontal_profile = wf.get_intensity()[:,wf.size()[1]/2] horizontal_profile /= horizontal_profile.max() print("FWHM of the horizontal profile: %g um"%(1e6*line_fwhm(horizontal_profile)*wf.delta()[0])) vertical_profile = wf.get_intensity()[wf.size()[0]/2,:] vertical_profile /= vertical_profile.max() print("FWHM of the vertical profile: %g um"%(1e6*line_fwhm(vertical_profile)*wf.delta()[1])) if do_plot: from srxraylib.plot.gol import plot,plot_image plot_image(wf.get_intensity(),wf.get_coordinate_x(),wf.get_coordinate_y(),title='intensity (%s)'%method,show=0) # plot_image(wf.get_amplitude(),wf.get_coordinate_x(),wf.get_coordinate_y(),title='amplitude (%s)'%method,show=0) plot_image(wf.get_phase(),wf.get_coordinate_x(),wf.get_coordinate_y(),title='phase (%s)'%method,show=0) plot(wf.get_coordinate_x(),horizontal_profile, wf.get_coordinate_y(),vertical_profile, legend=['Horizontal profile','Vertical profile'],title="%s"%method,show=show) print("Output intensity: ",wf.get_intensity().sum()) return wf.get_coordinate_x(),horizontal_profile
def test_propagate_2D_fraunhofer(self,do_plot=do_plot,aperture_type='square',aperture_diameter=40e-6, pixelsize_x=1e-6,pixelsize_y=1e-6,npixels_x=1024,npixels_y=1024,wavelength=1.24e-10): """ :param do_plot: 0=No plot, 1=Do plot :param aperture_type: 'circle' 'square' 'gaussian' (Gaussian sigma = aperture_diameter/2.35) :param aperture_diameter: :param pixelsize_x: :param pixelsize_y: :param npixels_x: :param npixels_y: :param wavelength: :return: """ print("\n# ") print("# far field 2D (fraunhofer) diffraction from a square aperture ") print("# ") method = "fraunhofer" print("Fraunhoffer diffraction valid for distances > > a^2/lambda = %f m"%((aperture_diameter/2)**2/wavelength)) # wf = Wavefront2D.initialize_wavefront_from_steps(x_start=-pixelsize_x*npixels_x/2, # x_step=pixelsize_x, # y_start=-pixelsize_y*npixels_y/2, # y_step=pixelsize_y, # wavelength=wavelength, # number_of_points=(npixels_x,npixels_y)) wf = Wavefront2D.initialize_wavefront_from_range(x_min=-pixelsize_x*npixels_x/2,x_max=pixelsize_x*npixels_x/2, y_min=-pixelsize_y*npixels_y/2,y_max=pixelsize_y*npixels_y/2, number_of_points=(npixels_x,npixels_y),wavelength=wavelength) wf.set_plane_wave_from_complex_amplitude((1.0+0j)) if aperture_type == 'circle': wf.apply_pinhole(aperture_diameter/2) elif aperture_type == 'square': wf.apply_slit(-aperture_diameter/2, aperture_diameter/2,-aperture_diameter/2, aperture_diameter/2) elif aperture_type == 'gaussian': X = wf.get_mesh_x() Y = wf.get_mesh_y() window = numpy.exp(- (X*X + Y*Y)/2/(aperture_diameter/2.35)**2) wf.rescale_amplitudes(window) else: raise Exception("Not implemented! (accepted: circle, square, gaussian)") wf1 = propagate_2D_fraunhofer(wf, propagation_distance=1.0) # propagating at 1 m means the result is like in angles if do_plot: plot_image(wf.get_intensity(),1e6*wf.get_coordinate_x(),1e6*wf.get_coordinate_y(), title="aperture intensity (%s), Diameter=%5.1f um"% (aperture_type,1e6*aperture_diameter),xtitle="X [um]",ytitle="Y [um]", show=0) plot_image(wf1.get_intensity(),1e6*wf1.get_coordinate_x(),1e6*wf1.get_coordinate_y(), title="2D Diffracted intensity (%s) by a %s slit of aperture %3.1f um"% (aperture_type,method,1e6*aperture_diameter), xtitle="X [urad]",ytitle="Y [urad]", show=0) angle_x = wf1.get_coordinate_x() # + 0.5*wf1.delta()[0] # shifted of half-pixel!!! intensity_theory = get_theoretical_diffraction_pattern(angle_x, aperture_type=aperture_type,aperture_diameter=aperture_diameter, wavelength=wavelength,normalization=True) intensity_calculated = wf1.get_intensity()[:,wf1.size()[1]/2] intensity_calculated /= intensity_calculated.max() if do_plot: plot(wf1.get_coordinate_x()*1e6,intensity_calculated, angle_x*1e6,intensity_theory, legend=["Calculated (FT) H profile","Theoretical"],legend_position=(0.95, 0.95), title="2D Fraunhofer Diffraction of a %s slit of %3.1f um at wavelength of %3.1f A"% (aperture_type,aperture_diameter*1e6,wavelength*1e10), xtitle="X (urad)", ytitle="Intensity",xrange=[-80,80]) numpy.testing.assert_almost_equal(intensity_calculated,intensity_theory,1)
def test_plane_wave(do_plot=0): import copy # # plane wave # value_amplitude = 5.0 value_phase = numpy.pi wavefront = Wavefront1D.initialize_wavefront_from_range( wavelength=1e-2, number_of_points=1000000, x_min=-1, x_max=1 ) wavefront.set_plane_wave_from_amplitude_and_phase(value_amplitude, value_phase) wavefront.apply_slit(-0.4, 0.4) wavefront_focused = copy.deepcopy(wavefront) wavefront_focused.apply_ideal_lens(100) # # some tests # test_value1 = wavefront.get_interpolated_amplitude(0.01) - value_amplitude assert numpy.abs(test_value1) < 1e-6 test_value2 = wavefront.get_interpolated_amplitudes(-4) assert numpy.abs(test_value2) < 1e-6 if do_plot: from srxraylib.plot.gol import plot plot( wavefront.get_abscissas(), wavefront.get_intensity(), show=0, title="Plane wave defined in [-1,1] and clipped by a [-.4,.4] slit", xtitle="X (m)", ytitle="Intensity", ) plot( wavefront.get_abscissas(), wavefront.get_amplitude(), show=0, title="Plane wave defined in [-1,1] and clipped by a [-.4,.4] slit", xtitle="X (m)", ytitle="Amplitude", ) plot( wavefront.get_abscissas(), wavefront.get_phase(), show=0, title="Plane wave defined in [-1,1] and clipped by a [-.4,.4] slit", xtitle="X (m)", ytitle="Phase [rad]", ) plot( wavefront.get_abscissas(), wavefront_focused.get_phase(), show=1, title="Plane wave after ideal lens", xtitle="X (m)", ytitle="Phase [rad]", )
# # plot profiles # horizontal_intensity_profile = wf_prop.get_intensity()[:,wf_prop.size()[1]/2] horizontal_intensity_profile /= horizontal_intensity_profile.max() vertical_intensity_profile = wf_prop.get_intensity()[wf_prop.size()[0]/2,:] vertical_intensity_profile /= vertical_intensity_profile.max() horizontal_intensity_profile_srw = wf_prop_srw.get_intensity()[:,wf_prop_srw.size()[1]/2] horizontal_intensity_profile_srw /= horizontal_intensity_profile_srw.max() vertical_intensity_profile_srw = wf_prop_srw.get_intensity()[wf_prop_srw.size()[0]/2,:] vertical_intensity_profile_srw /= vertical_intensity_profile_srw.max() plot( 1e6*wf_prop.get_coordinate_x(), horizontal_intensity_profile, 1e6*wf_prop_srw.get_coordinate_x(), horizontal_intensity_profile_srw, show=0, legend=["in-python","SRW"],color=["red","black"], title="Horizontal profile of diffracted intensity",xtitle='X [um]',ytitle='Diffracted intensity [a.u.]') plot( 1e6*wf_prop.get_coordinate_y(), vertical_intensity_profile, 1e6*wf_prop_srw.get_coordinate_y(), vertical_intensity_profile_srw, show=0, legend=["in-python","SRW"],color=["red","black"], title="Vertical profile of diffracted intensity",xtitle='X [um]',ytitle='Diffracted intensity [a.u.]') plot_show() # # sample rays fro SHADOW
def propagate_2D_fresnel(self,do_plot=do_plot,method='fft', wavelength=1.24e-10,aperture_type='square',aperture_diameter=40e-6, pixelsize_x=1e-6,pixelsize_y=1e-6,npixels_x=1024,npixels_y=1024, propagation_distance = 30.0,show=1): method_label = "fresnel (%s)"%method print("\n# ") print("# 2D near field fresnel (%s) diffraction from a %s aperture "%(method_label,aperture_type)) print("# ") # wf = Wavefront2D.initialize_wavefront_from_steps(x_start=-pixelsize_x*npixels_x/2, # x_step=pixelsize_x, # y_start=-pixelsize_y*npixels_y/2, # y_step=pixelsize_y, # wavelength=wavelength, # number_of_points=(npixels_x,npixels_y)) wf = Wavefront2D.initialize_wavefront_from_range(x_min=-pixelsize_x*npixels_x/2,x_max=pixelsize_x*npixels_x/2, y_min=-pixelsize_y*npixels_y/2,y_max=pixelsize_y*npixels_y/2, number_of_points=(npixels_x,npixels_y),wavelength=wavelength) wf.set_plane_wave_from_complex_amplitude((1.0+0j)) if aperture_type == 'circle': wf.apply_pinhole(aperture_diameter/2) elif aperture_type == 'square': wf.apply_slit(-aperture_diameter/2, aperture_diameter/2,-aperture_diameter/2, aperture_diameter/2) elif aperture_type == 'gaussian': X = wf.get_mesh_x() Y = wf.get_mesh_y() window = numpy.exp(- (X*X + Y*Y)/2/(aperture_diameter/2.35)**2) wf.rescale_amplitudes(window) else: raise Exception("Not implemented! (accepted: circle, square, gaussian)") if method == 'fft': wf1 = propagate_2D_fresnel(wf, propagation_distance) elif method == 'convolution': wf1 = propagate_2D_fresnel_convolution(wf, propagation_distance) elif method == 'srw': wf1 = propagate_2D_fresnel_srw(wf, propagation_distance) elif method == 'integral': wf1 = propagate_2D_integral(wf, propagation_distance) else: raise Exception("Not implemented method: %s"%method) if do_plot: from srxraylib.plot.gol import plot_image plot_image(wf.get_intensity(),1e6*wf.get_coordinate_x(),1e6*wf.get_coordinate_y(), title="aperture intensity (%s), Diameter=%5.1f um"% (aperture_type,1e6*aperture_diameter),xtitle="X [um]",ytitle="Y [um]", show=0) plot_image(wf1.get_intensity(), 1e6*wf1.get_coordinate_x()/propagation_distance, 1e6*wf1.get_coordinate_y()/propagation_distance, title="Diffracted intensity (%s) by a %s slit of aperture %3.1f um"% (aperture_type,method_label,1e6*aperture_diameter), xtitle="X [urad]",ytitle="Y [urad]", show=0) # get the theoretical value angle_x = wf1.get_coordinate_x() / propagation_distance intensity_theory = get_theoretical_diffraction_pattern(angle_x,aperture_type=aperture_type,aperture_diameter=aperture_diameter, wavelength=wavelength,normalization=True) intensity_calculated = wf1.get_intensity()[:,wf1.size()[1]/2] intensity_calculated /= intensity_calculated.max() if do_plot: from srxraylib.plot.gol import plot plot(wf1.get_coordinate_x()*1e6/propagation_distance,intensity_calculated, angle_x*1e6,intensity_theory, legend=["%s H profile"%method_label,"Theoretical (far field)"], legend_position=(0.95, 0.95), title="%s diffraction of a %s slit of %3.1f um at wavelength of %3.1f A"% (method_label,aperture_type,aperture_diameter*1e6,wavelength*1e10), xtitle="X (urad)", ytitle="Intensity",xrange=[-20,20], show=show) return wf1.get_coordinate_x()/propagation_distance,intensity_calculated,angle_x,intensity_theory