def plot_undul_phot(undul_phot_input,do_plot_intensity=True,do_plot_polarization=True,do_show=True,title=""):
        #
        # plots the output of undul_phot
        #
        try:
            from srxraylib.plot.gol import plot,plot_image,plot_show
        except:
            print("srxraylib not available: No plot")
            return

        if isinstance(undul_phot_input,str):
            undul_phot_dict = load_file_undul_phot(undul_phot_input)
            title += undul_phot_input
        else:
            undul_phot_dict = undul_phot_input


        if do_plot_intensity: plot_image(undul_phot_dict['radiation'][0,:,:],undul_phot_dict['theta']*1e6,undul_phot_dict['phi']*180/numpy.pi,
                   title="INTENS RN0[0] "+title,xtitle="Theta [urad]",ytitle="Phi [deg]",aspect='auto',show=False)

        if do_plot_polarization: plot_image(undul_phot_dict['polarization'][0,:,:],undul_phot_dict['theta']*1e6,undul_phot_dict['phi']*180/numpy.pi,
                   title="POL_DEG RN0[0] "+title,xtitle="Theta [urad]",ytitle="Phi [deg]",aspect='auto',show=False)


        if do_show: plot_show()
    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()
Example #3
0
def test_compare_h5_np(filename_h5, filename_np, do_plot_CSD=False):
    af1 = CompactAFReader.initialize_from_file(filename_h5)

    #
    #
    af2 = CompactAFReader.initialize_from_file(filename_np)

    test_equal(af1, af2)

    tic()
    for i in range(af1.number_modes()):
        print(i, af1.mode(i).sum())
    toc()
    print(af1.info())
    tic()
    for i in range(af2.number_modes()):
        print(i, af2.mode(i).sum())
    toc()
    # Cross spectral density

    Wx1x2, Wy1y2 = af2.CSD_in_one_dimension(mode_index_max=None)

    if do_plot_CSD:
        plot_image(np.abs(Wx1x2),
                   1e6 * af2.x_coordinates(),
                   1e6 * af2.x_coordinates(),
                   show=False,
                   title="Wx1x2")
        plot_image(np.abs(Wy1y2),
                   1e6 * af2.y_coordinates(),
                   1e6 * af2.y_coordinates(),
                   show=True,
                   title="Wy1y2")
Example #4
0
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())
Example #5
0
def plot_wfr(wfr,
             kind='intensity',
             show=True,
             xtitle="X",
             ytitle="Y",
             title="",
             aspect='auto'):

    if kind == 'intensity':
        ar1 = array('f', [0] * wfr.mesh.nx *
                    wfr.mesh.ny)  # "flat" 2D array to take intensity data
        srwl.CalcIntFromElecField(ar1, wfr, 6, 0, 3, wfr.mesh.eStart, 0, 0)
    elif kind == 'phase':
        ar1 = array(
            'd', [0] * wfr.mesh.nx * wfr.mesh.ny
        )  # "flat" array to take 2D phase data (note it should be 'd')
        srwl.CalcIntFromElecField(ar1, wfr, 0, 4, 3, wfr.mesh.eStart, 0, 0)
    else:
        raise Exception("Unknown kind of calculation: %s" % (kind))

    arxx = numpy.array(ar1)
    arxx = arxx.reshape((wfr.mesh.ny, wfr.mesh.nx)).T
    x = numpy.linspace(1e6 * wfr.mesh.xStart, 1e6 * wfr.mesh.xFin, wfr.mesh.nx)
    y = numpy.linspace(1e6 * wfr.mesh.yStart, 1e6 * wfr.mesh.yFin, wfr.mesh.ny)

    plot_image(arxx,
               x,
               y,
               xtitle="%s (%d pixels)" % (xtitle, x.size),
               ytitle="%s (%d pixels)" % (ytitle, y.size),
               title=title,
               aspect=aspect,
               show=show)

    return ar1, x, y
Example #6
0
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")
Example #7
0
    def plot_intensity_accumulated(self,
                                   show=1,
                                   filename="",
                                   aspect=None,
                                   title="intensity accumulated",
                                   xtitle="x",
                                   ytitle="y",
                                   coordinates_factor=1.0):

        fwhm_x, fwhm_y = self.get_fwhm_intensity_accumulated()

        plot_image(
            self.intensity_accumulated,
            coordinates_factor * self.coordinate_x,
            coordinates_factor * self.coordinate_y,
            title="%s fwhm of central profiles=%g x %g " %
            (title, coordinates_factor * fwhm_x, coordinates_factor * fwhm_y),
            xtitle=xtitle,
            ytitle=ytitle,
            aspect=aspect,
            show=False)

        if filename != "":
            plt.savefig(filename)
            print("File written to disk: %s" % filename)

        if show:
            plt.show()
        else:
            plt.close()
 def showIntensity(self):
     try:
         from srxraylib.plot.gol import plot_image
         plot_image(np.abs(self.intensity()[:, :]), 1e6*self.xCoordinates(), 1e6*self.yCoordinates(),
                     title = "Intensity", xtitle = "X [um]", ytitle = "Y [um]")
     except:
         pass
Example #9
0
def test_compare_h5_np(filename_h5,filename_np,do_plot_CSD=False):
    af1  = CompactAFReader.initialize_from_file(filename_h5)

    #
    #
    af2  = CompactAFReader.initialize_from_file(filename_np)

    test_equal(af1,af2)

    tic()
    for i in range(af1.number_modes()):
        print(i,af1.mode(i).sum())
    toc()
    print(af1.info())
    tic()
    for i in range(af2.number_modes()):
        print(i,af2.mode(i).sum())
    toc()
    # Cross spectral density

    Wx1x2,Wy1y2 = af2.CSD_in_one_dimension(mode_index_max=None)

    if do_plot_CSD:
        plot_image(np.abs(Wx1x2),1e6*af2.x_coordinates(),1e6*af2.x_coordinates(),show=False,title="Wx1x2")
        plot_image(np.abs(Wy1y2),1e6*af2.y_coordinates(),1e6*af2.y_coordinates(),show=True,title="Wy1y2")
Example #10
0
def test_id16(filename_ebs_np,filename_hb_np,plot_spectrum=True,plot_mode=False):


    if plot_spectrum:
        af_hb  = CompactAFReader.initialize_from_file(filename_hb_np)
        x_hb = np.arange(af_hb.number_modes())
        y_hb = np.cumsum(np.abs(af_hb.occupation_array()))
        plt.plot(x_hb,y_hb,label="High Beta")



        af_ebs  = CompactAFReader.initialize_from_file(filename_ebs_np)
        x_ebs = np.arange(af_ebs.number_modes())
        y_ebs = np.cumsum(np.abs(af_ebs.occupation_array()))
        # y_fit_coeff = np.polyfit(x_ebs, np.log(y_ebs), 1, w=np.sqrt(y_ebs))
        # print(y_fit_coeff)
        # y_fit = np.exp(y_fit_coeff[1]) * np.exp(y_fit_coeff[0] * x_ebs)
        plt.plot(x_ebs,y_ebs,label="EBS")
        plt.xlabel("Mode index")
        plt.ylabel("Cumulated occupation")
        ax = plt.subplot(111)
        ax.legend(bbox_to_anchor=None)

        plt.show()

    if plot_mode:
        af_hb  = CompactAFReader.initialize_from_file(filename_hb_h5)
        plot_image(np.abs(af_hb.mode(10)),title=filename_hb_h5)
Example #11
0
def test_id16(filename_ebs_np,
              filename_hb_np,
              plot_spectrum=True,
              plot_mode=False):

    if plot_spectrum:
        af_hb = CompactAFReader.initialize_from_file(filename_hb_np)
        x_hb = np.arange(af_hb.number_modes())
        y_hb = np.cumsum(np.abs(af_hb.occupation_array()))
        plt.plot(x_hb, y_hb, label="High Beta")

        af_ebs = CompactAFReader.initialize_from_file(filename_ebs_np)
        x_ebs = np.arange(af_ebs.number_modes())
        y_ebs = np.cumsum(np.abs(af_ebs.occupation_array()))
        # y_fit_coeff = np.polyfit(x_ebs, np.log(y_ebs), 1, w=np.sqrt(y_ebs))
        # print(y_fit_coeff)
        # y_fit = np.exp(y_fit_coeff[1]) * np.exp(y_fit_coeff[0] * x_ebs)
        plt.plot(x_ebs, y_ebs, label="EBS")
        plt.xlabel("Mode index")
        plt.ylabel("Cumulated occupation")
        ax = plt.subplot(111)
        ax.legend(bbox_to_anchor=None)

        plt.show()

    if plot_mode:
        af_hb = CompactAFReader.initialize_from_file(filename_hb_h5)
        plot_image(np.abs(af_hb.mode(10)), title=filename_hb_h5)
Example #12
0
def test_plane_wave(do_plot=0):
    #
    # plane wave
    #
    print("#                                                             ")
    print("# Tests for a plane wave                                      ")
    print("#                                                             ")

    wavelength        = 1.24e-10

    wavefront_length_x = 400e-6
    wavefront_length_y = wavefront_length_x

    npixels_x =  1024
    npixels_y =  npixels_x

    pixelsize_x = wavefront_length_x / npixels_x
    pixelsize_y = wavefront_length_y / npixels_y



    wavefront = Wavefront2D.initialize_wavefront_from_steps(
                    x_start=-0.5*wavefront_length_x,x_step=pixelsize_x,
                    y_start=-0.5*wavefront_length_y,y_step=pixelsize_y,
                    number_of_points=(npixels_x,npixels_y),wavelength=wavelength)

    # possible modifications

    wavefront.set_plane_wave_from_amplitude_and_phase(5.0,numpy.pi/2)

    wavefront.add_phase_shift(numpy.pi/2)

    wavefront.rescale_amplitude(10.0)

    wavefront.set_spherical_wave(1,10e-6)

    wavefront.rescale_amplitudes(numpy.ones_like(wavefront.get_intensity())*0.1)

    wavefront.apply_ideal_lens(5.0,10.0)

    wavefront.apply_slit(-50e-6,10e-6,-20e-6,40e-6)

    wavefront.set_plane_wave_from_complex_amplitude(2.0+3j)


    print("Wavefront X value",wavefront.get_coordinate_x())
    print("Wavefront Y value",wavefront.get_coordinate_y())

    print("wavefront intensity",wavefront.get_intensity())
    print("Wavefront complex ampl",wavefront.get_complex_amplitude())
    print("Wavefront phase",wavefront.get_phase())


    if do_plot:
        from srxraylib.plot.gol import plot_image
        plot_image(wavefront.get_intensity(),wavefront.get_coordinate_x(),wavefront.get_coordinate_y(),
                   title="Intensity",show=0)
        plot_image(wavefront.get_phase(),wavefront.get_coordinate_x(),wavefront.get_coordinate_y(),
                   title="Phase",show=1)
Example #13
0
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 showIntensityFromModes(self):
     try:
         from srxraylib.plot.gol import plot_image
         intensity = self.intensityFromModes().real
         plot_image( intensity, 1e6*self.xCoordinates(), 1e6*self.yCoordinates(),
                          title = "Intensity from modes", xtitle = "X [um]", ytitle = "Y [um]")
     except:
         pass
Example #15
0
def plot_wavefront_generic(w,show=True,title=None):
    z = w.get_intensity()
    x = w.get_coordinate_x()
    y = w.get_coordinate_y()

    if title is None:
        title="WOFRY"
    plot_image(z,1e6*x,1e6*y,title=title,xtitle='x [um]',ytitle='y [um]',show=show)
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
Example #17
0
    def test_plane_wave(self,do_plot=do_plot):
        #
        # plane wave
        #
        print("#                                                             ")
        print("# Tests for a 2D plane wave                                      ")
        print("#                                                             ")

        wavelength        = 1.24e-10

        wavefront_length_x = 400e-6
        wavefront_length_y = wavefront_length_x

        npixels_x =  1024
        npixels_y =  npixels_x

        x = numpy.linspace(-0.5*wavefront_length_x,0.5*wavefront_length_x,npixels_x)
        y = numpy.linspace(-0.5*wavefront_length_y,0.5*wavefront_length_y,npixels_y)

        wavefront = Wavefront2D.initialize_wavefront_from_steps(
                        x_start=x[0],x_step=numpy.abs(x[1]-x[0]),
                        y_start=y[0],y_step=numpy.abs(y[1]-y[0]),
                        number_of_points=(npixels_x,npixels_y),wavelength=wavelength)

        # 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,1.3)
        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_image
            plot_image(wavefront.get_intensity(),wavefront.get_coordinate_x(),wavefront.get_coordinate_y(),
                       title="Intensity (plane wave)",show=0)
            plot_image(wavefront.get_phase(),wavefront.get_coordinate_x(),wavefront.get_coordinate_y(),
                       title="Phase (plane wave)",show=1)
    def showStaticElectronDensity(self):
        try:
            from srxraylib.plot.gol import plot_image

            plot_image(np.absolute(self.staticElectronDensity()),
                                        1e6*self._wavefront.absolute_x_coordinates(),
                                        1e6*self._wavefront.absolute_y_coordinates(),
                                        title = "Electron density", xtitle = "X [um]", ytitle = "Y [um]")
        except:
            pass
Example #19
0
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
Example #20
0
 def showIntensity(self):
     try:
         from srxraylib.plot.gol import plot_image
         plot_image(np.abs(self.intensity()[:, :]),
                    1e6 * self.xCoordinates(),
                    1e6 * self.yCoordinates(),
                    title="Intensity",
                    xtitle="X [um]",
                    ytitle="Y [um]")
     except:
         pass
Example #21
0
 def showIntensityFromModes(self):
     try:
         from srxraylib.plot.gol import plot_image
         intensity = self.intensityFromModes().real
         plot_image(intensity,
                    1e6 * self.xCoordinates(),
                    1e6 * self.yCoordinates(),
                    title="Intensity from modes",
                    xtitle="X [um]",
                    ytitle="Y [um]")
     except:
         pass
Example #22
0
    def showStaticElectronDensity(self):
        try:
            from srxraylib.plot.gol import plot_image

            plot_image(np.absolute(self.staticElectronDensity()),
                       1e6 * self._wavefront.absolute_x_coordinates(),
                       1e6 * self._wavefront.absolute_y_coordinates(),
                       title="Electron density",
                       xtitle="X [um]",
                       ytitle="Y [um]")
        except:
            pass
Example #23
0
def test_interpolator(do_plot=0):
    #
    # interpolator
    #
    print("#                                                             ")
    print("# Tests for interpolator                                      ")
    print("#                                                             ")

    x = numpy.linspace(-10, 10, 100)
    y = numpy.linspace(-20, 20, 50)
    # XY = numpy.meshgrid(y,x)
    # sigma = 3.0
    # Z = numpy.exp(- (XY[0]**2+XY[1]**2)/2/sigma**2)

    xy = numpy.meshgrid(x, y)
    X = xy[0].T
    Y = xy[1].T
    sigma = 3.0
    Z = numpy.exp(-(X**2 + Y**2) / 2 / sigma**2)

    print("shape of Z", Z.shape)

    wf = Wavefront2D.initialize_wavefront_from_steps(x[0],
                                                     x[1] - x[0],
                                                     y[0],
                                                     y[1] - y[0],
                                                     number_of_points=(100,
                                                                       50))
    print("wf shape: ", wf.size())
    wf.set_complex_amplitude(Z)

    x1 = 3.2
    y1 = -2.5
    z1 = numpy.exp(-(x1**2 + y1**2) / 2 / sigma**2)
    print("complex ampl at (%g,%g): %g+%gi (exact=%g)" %
          (x1, y1, wf.get_interpolated_complex_amplitude(x1, y1).real,
           wf.get_interpolated_complex_amplitude(x1, y1).imag, z1))
    print("intensity  at (%g,%g):   %g (exact=%g)" %
          (x1, y1, wf.get_interpolated_intensity(x1, y1), z1**2))

    if do_plot:
        from srxraylib.plot.gol import plot_image
        plot_image(wf.get_intensity(),
                   wf.get_coordinate_x(),
                   wf.get_coordinate_y(),
                   title="Original",
                   show=0)
        plot_image(wf.get_interpolated_intensity(X, Y),
                   wf.get_coordinate_x(),
                   wf.get_coordinate_y(),
                   title="interpolated on same grid",
                   show=1)
Example #24
0
    def test_multiple_slit(self):
        print("#                                                             ")
        print(
            "# Tests multiple slit (2D)                                     ")
        print("#                                                             ")
        wavefront = GenericWavefront2D.initialize_wavefront_from_range(
            x_min=-0.5e-3,
            x_max=0.5e-3,
            y_min=-0.5e-3,
            y_max=0.5e-3,
            number_of_points=(2048, 1024),
            wavelength=1.5e-10,
            polarization=Polarization.TOTAL)

        ca = numpy.zeros(wavefront.size())
        wavefront.set_complex_amplitude(ca + (10 + 0j), ca + (0 + 1j))
        #

        window_circle = wavefront.clip_circle(50e-6,
                                              -2e-4,
                                              -2e-4,
                                              apply_to_wavefront=False)
        window_rectangle = wavefront.clip_square(2e-4,
                                                 3e-4,
                                                 2e-4,
                                                 3e-4,
                                                 apply_to_wavefront=False)
        window_ellipse = wavefront.clip_ellipse(50e-6,
                                                25e-6,
                                                -2e-4,
                                                2e-4,
                                                apply_to_wavefront=False)
        window_ellipse2 = wavefront.clip_ellipse(50e-6,
                                                 100e-6,
                                                 2e-4,
                                                 -2e-4,
                                                 apply_to_wavefront=False)

        wavefront.clip_window(window_circle + window_rectangle +
                              window_ellipse + window_ellipse2)

        if True:
            from srxraylib.plot.gol import plot_image
            plot_image(wavefront.get_intensity(),
                       1e6 * wavefront.get_coordinate_x(),
                       1e6 * wavefront.get_coordinate_y())

        numpy.testing.assert_almost_equal(
            wavefront.get_interpolated_intensities(
                0, 0, polarization=Polarization.TOTAL), 0.0)
    def plotDegreeOfCoherenceOneHoleFixed(self, x=0.0, y=0.0):
        try:
            from srxraylib.plot.gol import plot_image
            x_coordinates = np.array(self._wavefront.absolute_x_coordinates())
            y_coordinates = np.array(self._wavefront.absolute_x_coordinates())
            values = self.degreeOfCoherence().planeForFixedR1(x_coordinates,
                                                              y_coordinates,
                                                              np.array([x, y]))

            plot_image(np.absolute(values), 1e6*x_coordinates, 1e6*y_coordinates,
                    title = "Degree Of Coherence (modulus) One Hole Fixed",
                    xtitle = "X [um]", ytitle = "Y [um]")
        except:
            pass
Example #26
0
    def test_gaussianhermite_mode(self, do_plot=do_plot):
        #
        # plane wave
        #
        print("#                                                             ")
        print("# Tests for a 2D Gaussian Hermite mode                        ")
        print("#                                                             ")

        wavelength = 1.24e-10

        # 2D
        sigma_x = 100e-6
        mode_x = 0
        npixels_x = 100
        sigma_y = 50e-6
        mode_y = 3
        npixels_y = 100

        wavefront_length_x = 10 * sigma_x
        wavefront_length_y = 10 * sigma_y

        x = numpy.linspace(-0.5 * wavefront_length_x, 0.5 * wavefront_length_x,
                           npixels_x)
        y = numpy.linspace(-0.5 * wavefront_length_y, 0.5 * wavefront_length_y,
                           npixels_y)

        wf1 = GenericWavefront2D.initialize_wavefront_from_steps(
            x_start=x[0],
            x_step=numpy.abs(x[1] - x[0]),
            y_start=y[0],
            y_step=numpy.abs(y[1] - y[0]),
            number_of_points=(npixels_x, npixels_y),
            wavelength=wavelength)

        wf1.set_gaussian_hermite_mode(sigma_x,
                                      sigma_y,
                                      mode_x,
                                      mode_y,
                                      amplitude=1.0)

        numpy.testing.assert_almost_equal(wf1.get_amplitude()[30, 40],
                                          1383.76448118, 3)

        if do_plot:
            from srxraylib.plot.gol import plot_image
            plot_image(wf1.get_amplitude(),
                       wf1.get_coordinate_x(),
                       wf1.get_coordinate_y(),
                       title="Amplitude of gaussianhermite mode",
                       show=1)
Example #27
0
    def plotDegreeOfCoherenceOneHoleFixed(self, x=0.0, y=0.0):
        try:
            from srxraylib.plot.gol import plot_image
            x_coordinates = np.array(self._wavefront.absolute_x_coordinates())
            y_coordinates = np.array(self._wavefront.absolute_x_coordinates())
            values = self.degreeOfCoherence().planeForFixedR1(
                x_coordinates, y_coordinates, np.array([x, y]))

            plot_image(np.absolute(values),
                       1e6 * x_coordinates,
                       1e6 * y_coordinates,
                       title="Degree Of Coherence (modulus) One Hole Fixed",
                       xtitle="X [um]",
                       ytitle="Y [um]")
        except:
            pass
    def test3d(self):

        print("\n#\n# running test_3d() \n#\n")

        response = requests.get(
            "https://cdn104.picsart.com/201671193005202.jpg?r1024x1024")

        img = Image.open(BytesIO(response.content))
        img = numpy.array(img) * 1.0
        img = numpy.rot90(img, axes=(1, 0))
        image_data = img.max() - img

        if do_plots:
            plot_image(image_data[:, :, 0],
                       cmap='binary',
                       title="channel0",
                       show=1)
        # plot_image(image_data[:,:,1],cmap='binary',title="channel1",show=0)
        # plot_image(image_data[:,:,2],cmap='binary',title="channel2")

        print(image_data.shape)

        s2d = Sampler3D(image_data)

        cdf3, cdf2, cdf1 = s2d.cdf()

        # plot_image(cdf2)
        #
        # plot_image(s2d.pdf(),cmap='binary',title="pdf")
        #
        # cdf2,cdf1 = s2d.cdf()
        # plot_image(cdf2,cmap='binary',title="cdf")
        # plot(s2d.abscissas()[0],s2d.cdf()[0][:,-1])
        # plot(s2d.abscissas()[0],cdf1)
        #
        x0s, x1s, x2s = s2d.get_n_sampled_points(100000)
        if do_plots:
            plot_scatter(x0s, x1s)
        print(x2s)

        print("x0s.mean(),x0s.std(),x1s.mean(),x1s.std(): ", x0s.mean(),
              x0s.std(), x1s.mean(), x1s.std())
        assert ((numpy.abs(x0s.mean()) - 730.09) < 10.0)
        assert ((numpy.abs(x0s.std()) - 458.17) < 10.0)
        assert ((numpy.abs(x1s.mean()) - 498.805) < 10.0)
        assert ((numpy.abs(x1s.std()) - 301.21) < 10.0)
Example #29
0
def plot_wavefront_pynx(w,do_shift=True,show=True,title=None):

    x, y = w.get_x_y()

    if do_shift:
        z = abs(numpy.fft.fftshift(w.d)).T
        # added srio
        z = z**2
    else:
        z = abs(w.d).T
    # z = abs((w.d)).T
    if title is None:
        title="Near field propagation (0.5m) of a 20x200 microns aperture"

    plot_image(z,
               1e6*numpy.linspace(x.min(),x.max(),num=z.shape[0],endpoint=True),
               1e6*numpy.linspace(y.min(),y.max(),num=z.shape[1],endpoint=True),
               title=title,
               xtitle='X (µm)',ytitle='Y (µm)',show=show)
Example #30
0
def test_interpolator(do_plot=0):
    #
    # interpolator
    #
    print("#                                                             ")
    print("# Tests for interpolator                                      ")
    print("#                                                             ")

    x = numpy.linspace(-10,10,100)
    y = numpy.linspace(-20,20,50)
    # XY = numpy.meshgrid(y,x)
    # sigma = 3.0
    # Z = numpy.exp(- (XY[0]**2+XY[1]**2)/2/sigma**2)

    xy = numpy.meshgrid(x,y)
    X = xy[0].T
    Y = xy[1].T
    sigma = 3.0
    Z = numpy.exp(- (X**2+Y**2)/2/sigma**2)

    print("shape of Z",Z.shape)

    wf = Wavefront2D.initialize_wavefront_from_steps(x[0],x[1]-x[0],y[0],y[1]-y[0],number_of_points=(100,50))
    print("wf shape: ",wf.size())
    wf.set_complex_amplitude( Z )

    x1 = 3.2
    y1 = -2.5
    z1 = numpy.exp(- (x1**2+y1**2)/2/sigma**2)
    print("complex ampl at (%g,%g): %g+%gi (exact=%g)"%(x1,y1,
                                                    wf.get_interpolated_complex_amplitude(x1,y1).real,
                                                    wf.get_interpolated_complex_amplitude(x1,y1).imag,
                                                    z1))
    print("intensity  at (%g,%g):   %g (exact=%g)"%(x1,y1,wf.get_interpolated_intensity(x1,y1),z1**2))




    if do_plot:
        from srxraylib.plot.gol import plot_image
        plot_image(wf.get_intensity(),wf.get_coordinate_x(),wf.get_coordinate_y(),title="Original",show=0)
        plot_image(wf.get_interpolated_intensity(X,Y),wf.get_coordinate_x(),wf.get_coordinate_y(),
                   title="interpolated on same grid",show=1)
Example #31
0
def from_hrd5_to_ascii(filename_in,filename_out,do_plot=True):

    f = h5py.File(filename_in,'r')
    x = f["entry/data0/x"][:]
    y = f["entry/data0/y"][:]
    image = f["entry/data0/image"][:].T
    f.close()
    print(x.shape,y.shape,image.shape)

    if do_plot:
        plot_image(image,x,y,aspect='auto',xtitle="X / mm",ytitle="Y / mm",title="Power density W/mm2")

    print("Total power",image.sum()*(x[1]-x[0])*(y[1]-y[0]))

    f = open(filename_out,'w')
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            f.write("%g %g %g\n"%(1e-3*x[i],1e-3*y[j],image[i,j]))

    f.close()
    print("File written to disk: %s"%filename_out)
Example #32
0
def test_initializers(do_plot=0):

    print("#                                                             ")
    print("# Tests for initializars                                      ")
    print("#                                                             ")

    x = numpy.linspace(-100,100,50)
    y = numpy.linspace(-50,50,200)
    XY = numpy.meshgrid(x,y)
    X = XY[0].T
    Y = XY[1].T
    sigma = 10
    Z = numpy.exp(- (X**2 + Y**2)/2/sigma**2) * 1j
    print("Shapes x,y,z: ",x.shape,y.shape,Z.shape)

    wf0 = Wavefront2D.initialize_wavefront_from_steps(x[0],x[1]-x[0],y[0],y[1]-y[0],number_of_points=Z.shape)
    wf0.set_complex_amplitude(Z)

    wf1 = Wavefront2D.initialize_wavefront_from_range(x[0],x[-1],y[0],y[-1],number_of_points=Z.shape)
    wf1.set_complex_amplitude(Z)

    wf2 = Wavefront2D.initialize_wavefront_from_arrays(Z,x,y)

    if do_plot:
        from srxraylib.plot.gol import plot_image
        plot_image(wf0.get_intensity(),wf0.get_coordinate_x(),wf0.get_coordinate_y(),
                   title="initialize_wavefront_from_steps",show=0)
        plot_image(wf1.get_intensity(),wf1.get_coordinate_x(),wf1.get_coordinate_y(),
                   title="initialize_wavefront_from_range",show=0)
        plot_image(wf2.get_intensity(),wf2.get_coordinate_x(),wf2.get_coordinate_y(),
                   title="initialize_wavefront_from_arrays",show=1)
    def test_2d(self):

        print("\n#\n# running test_2d() \n#\n")
        #
        response = requests.get(
            "https://cdn104.picsart.com/201671193005202.jpg?r1024x1024")

        img = Image.open(BytesIO(response.content))
        img = numpy.array(img).sum(2) * 1.0
        img = numpy.rot90(img, axes=(1, 0))
        image_data = img.max() - img
        if do_plots:
            plot_image(image_data, cmap='binary')

        x0 = numpy.arange(image_data.shape[0])
        x1 = numpy.arange(image_data.shape[1])

        print(image_data.shape)

        s2d = Sampler2D(image_data, x0, x1)

        # plot_image(s2d.pdf(),cmap='binary',title="pdf")

        cdf2, cdf1 = s2d.cdf()
        print("cdf2.shape,cdf1.shape,s2d._pdf_x0.shape,s2d._pdf_x1.shape: ",
              cdf2.shape, cdf1.shape, s2d._pdf_x0.shape, s2d._pdf_x1.shape)
        # plot_image(cdf2,cmap='binary',title="cdf")
        # plot(s2d.abscissas()[0],s2d.cdf()[0][:,-1])
        # plot(s2d.abscissas()[0],cdf1)

        x0s, x1s = s2d.get_n_sampled_points(100000)
        if do_plots:
            plot_scatter(x0s, x1s)

        print("x0s.mean(),x0s.std(),x1s.mean(),x1s.std(): ", x0s.mean(),
              x0s.std(), x1s.mean(), x1s.std())
        assert ((numpy.abs(x0s.mean()) - 731.37) < 10.0)
        assert ((numpy.abs(x0s.std()) - 458.55) < 10.0)
        assert ((numpy.abs(x1s.mean()) - 498.05) < 10.0)
        assert ((numpy.abs(x1s.std()) - 301.05) < 10.0)
Example #34
0
 def plot_surface_image(self, invert_axes_names=False, aspect='auto'):
     if invert_axes_names:
         plot_image(self.Z_INTERPOLATED,
                    self.x_interpolated,
                    self.y_interpolated,
                    title="file: %s, axes names INVERTED from ANSYS" %
                    self.filename,
                    xtitle="Y (%d pixels, max:%f)" %
                    (self.x_interpolated.size, self.x_interpolated.max()),
                    ytitle="X (%d pixels, max:%f)" %
                    (self.y_interpolated.size, self.y_interpolated.max()),
                    aspect=aspect)
     else:
         plot_image(self.Z_INTERPOLATED,
                    self.x_interpolated,
                    self.y_interpolated,
                    title="file: %s, axes as in ANSYS" % self.filename,
                    xtitle="X (%d pixels, max:%f)" %
                    (self.x_interpolated.size, self.x_interpolated.max()),
                    ytitle="Y (%d pixels, max:%f)" %
                    (self.y_interpolated.size, self.y_interpolated.max()),
                    aspect=aspect)
Example #35
0
def plot_spectral_density(afp,mode=None,spectral_density=True,do_plot=False,
                          xrange=None,yrange=None,figsize=[9,5],
                          show_profiles=False,filename="",aspect="equal",
                          yticks=None):

    if spectral_density:
        if mode is None:
            sd = af.spectral_density()
        else:
            sd = af.intensity_from_modes(max_mode_index=mode)
    else:
        sd =  numpy.abs(af.eigenvalue(mode) * af.mode(mode))


    x = afp.x_coordinates()
    y = afp.y_coordinates()


    fig,ax = plot_image(sd,1e6*x,1e6*y,cmap='jet',figsize=figsize,add_colorbar=False,show=0,
                     xtitle="X [$\mu$m]",ytitle="Y [$\mu$m]",title="",aspect=aspect,
                     xrange=xrange,yrange=yrange,)



    # if is_propagated:
    #     ax.xaxis.label.set_size(15)
    #     ax.yaxis.label.set_size(20)
    #     plt.xticks(fontsize=15)
    #     plt.yticks(fontsize=15)
    # else:
    ax.xaxis.label.set_size(15)
    ax.yaxis.label.set_size(20)
    plt.yticks(yticks) # [-15,-10,-5,0,5,10,15])
    plt.yticks(fontsize=20)
    plt.xticks(fontsize=20)

    if filename != "":
        plt.savefig(filename) #,dpi=600)
        print("File written to disk: %s"%filename)

    plt.show()
Example #36
0
def test_initializers(do_plot=0):

    print("#                                                             ")
    print("# Tests for initializars                                      ")
    print("#                                                             ")

    x = numpy.linspace(-100, 100, 50)
    y = numpy.linspace(-50, 50, 200)
    X = numpy.outer(x, numpy.ones_like(y))
    Y = numpy.outer(numpy.ones_like(x), y)
    sigma = 10
    Z = numpy.exp(-(X**2 + Y**2) / 2 / sigma**2) * 1j
    print("Shapes x,y,z: ", x.shape, y.shape, Z.shape)

    wf0 = Wavefront2D.initialize_wavefront_from_steps(x[0],
                                                      x[1] - x[0],
                                                      y[0],
                                                      y[1] - y[0],
                                                      number_of_points=Z.shape)
    wf0.set_complex_amplitude(Z)

    wf1 = Wavefront2D.initialize_wavefront_from_range(x[0],
                                                      x[-1],
                                                      y[0],
                                                      y[-1],
                                                      number_of_points=Z.shape)
    wf1.set_complex_amplitude(Z)

    wf2 = Wavefront2D.initialize_wavefront_from_arrays(x, y, Z)

    if do_plot:
        from srxraylib.plot.gol import plot_image
        plot_image(wf0.get_intensity(),
                   wf0.get_coordinate_x(),
                   wf0.get_coordinate_y(),
                   title="initialize_wavefront_from_steps",
                   show=0)
        plot_image(wf1.get_intensity(),
                   wf1.get_coordinate_x(),
                   wf1.get_coordinate_y(),
                   title="initialize_wavefront_from_range",
                   show=0)
        plot_image(wf2.get_intensity(),
                   wf2.get_coordinate_x(),
                   wf2.get_coordinate_y(),
                   title="initialize_wavefront_from_arrays",
                   show=1)
Example #37
0
        txt += "    sigmax: %f\n"%mZ[3]
        txt += "    sigmay: %f\n"%mZ[4]
        txt += "    angle:  %f rad\n"%mZ[5]
        txt += "    offset: %f\n"%mZ[6]

    return txt

if __name__ == "__main__":
    nx = 200
    ny = 300
    x0 = np.linspace(-20,20,nx)
    y0 = np.linspace(-10,10,ny)
    x, y = np.meshgrid(x0, y0)
    data = twoD_Gaussian((x, y), 100, 0, 0, 10, 5, 0, 0)

    plot_image(data.reshape((nx,ny)),x0,y0,title="DATA")


    popt = fit_gaussian2d(data,x0,y0,p0=None)

    data_fitted = twoD_Gaussian((x, y), *popt)
        
    print(info_params(popt))

    plot_image(data_fitted.reshape((nx,ny)),x0,y0,title="FIT")



    

Example #38
0
    f = h5py.File(filename_in,'r')

    x = f["entry/data0/x"][:]
    y = f["entry/data0/y"][:]
    z = f["entry/data0/image"][:].T

    f.close()

    return z,x,y


z,x,y = extract_from_nexus("C:/Users/Manuel/Oasys/cosmic_M1_H_xoppy.h5")
za,xa,ya = extract_from_nexus("C:/Users/Manuel/Oasys/cosmic_M1_H_arriving_xoppy.h5")

nx = x.size
ny = y.size

plot_image(z,x,y,aspect='auto')

plot(y,z[nx//2,:],
     ya,za[nx//2,:],
     ya,30.78/54.962*za[nx//2,:],
     legend=["absorbed","incident","incident times averg absorp"],
     xtitle="Y / mm",ytitle="Power density W/mm2")

plot(x,z[:,ny//2],
     xa,za[:,ny//2],
     xa,30.78/54.962*za[:,ny//2],
     legend=["absorbed","incident","incident times averg absorp"],
     xtitle="X / mm",ytitle="Power density W/mm2")
def power_density(Kh=0.0, Kv=0.0, Phase=0.0, pngfile="tmp.png"):
    h5_parameters = dict()
    h5_parameters["ELECTRONENERGY"] = 2.0
    h5_parameters["ELECTRONENERGYSPREAD"] = 0.0011
    h5_parameters["ELECTRONCURRENT"] = 0.5
    h5_parameters["ELECTRONBEAMSIZEH"] = 1.21e-05
    h5_parameters["ELECTRONBEAMSIZEV"] = 1.47e-05
    h5_parameters["ELECTRONBEAMDIVERGENCEH"] = 5.7e-06
    h5_parameters["ELECTRONBEAMDIVERGENCEV"] = 4.7e-06
    h5_parameters["PERIODID"] = 0.0288
    h5_parameters["NPERIODS"] = 138.0
    h5_parameters["KV"] = Kv
    h5_parameters["KH"] = Kh
    h5_parameters["KPHASE"] = Phase
    h5_parameters["DISTANCE"] = 13.73
    h5_parameters["GAPH"] = 0.012  # 0.03
    h5_parameters["GAPV"] = 0.012  # 0.015
    h5_parameters["HSLITPOINTS"] = 201
    h5_parameters["VSLITPOINTS"] = 201
    h5_parameters["METHOD"] = 2
    h5_parameters["USEEMITTANCES"] = 1
    h5_parameters["MASK_FLAG"] = 1
    h5_parameters["MASK_ROT_H_DEG"] = 0.0
    h5_parameters["MASK_ROT_V_DEG"] = 88.75
    h5_parameters["MASK_H_MIN"] = -250.0
    h5_parameters["MASK_H_MAX"] = 250.0
    h5_parameters["MASK_V_MIN"] = -5.0
    h5_parameters["MASK_V_MAX"] = 5.0

    h, v, p, code = xoppy_calc_undulator_power_density(
        ELECTRONENERGY=h5_parameters["ELECTRONENERGY"],
        ELECTRONENERGYSPREAD=h5_parameters["ELECTRONENERGYSPREAD"],
        ELECTRONCURRENT=h5_parameters["ELECTRONCURRENT"],
        ELECTRONBEAMSIZEH=h5_parameters["ELECTRONBEAMSIZEH"],
        ELECTRONBEAMSIZEV=h5_parameters["ELECTRONBEAMSIZEV"],
        ELECTRONBEAMDIVERGENCEH=h5_parameters["ELECTRONBEAMDIVERGENCEH"],
        ELECTRONBEAMDIVERGENCEV=h5_parameters["ELECTRONBEAMDIVERGENCEV"],
        PERIODID=h5_parameters["PERIODID"],
        NPERIODS=h5_parameters["NPERIODS"],
        KV=h5_parameters["KV"],
        KH=h5_parameters["KH"],
        KPHASE=h5_parameters["KPHASE"],
        DISTANCE=h5_parameters["DISTANCE"],
        GAPH=h5_parameters["GAPH"],
        GAPV=h5_parameters["GAPV"],
        HSLITPOINTS=h5_parameters["HSLITPOINTS"],
        VSLITPOINTS=h5_parameters["VSLITPOINTS"],
        METHOD=h5_parameters["METHOD"],
        USEEMITTANCES=h5_parameters["USEEMITTANCES"],
        MASK_FLAG=h5_parameters["MASK_FLAG"],
        MASK_ROT_H_DEG=h5_parameters["MASK_ROT_H_DEG"],
        MASK_ROT_V_DEG=h5_parameters["MASK_ROT_V_DEG"],
        MASK_H_MIN=h5_parameters["MASK_H_MIN"],
        MASK_H_MAX=h5_parameters["MASK_H_MAX"],
        MASK_V_MIN=h5_parameters["MASK_V_MIN"],
        MASK_V_MAX=h5_parameters["MASK_V_MAX"],
        h5_file="",
        h5_entry_name="XOPPY_POWERDENSITY",
        h5_initialize=True,
        h5_parameters=h5_parameters,
    )

    # example plot

    plot_image(p,
               h,
               v,
               xtitle="H [mm]",
               ytitle="V [mm]",
               title="",
               aspect='auto',
               cmap='jet',
               show=0,
               figsize=figsize)

    plt.savefig(pngfile)
    plt.show()
    def plot_data2D(self, data2D, dataX, dataY, tabs_canvas_index, plot_canvas_index, title="", xtitle="", ytitle="", mode=2):

        for i in range(1+self.tab[tabs_canvas_index].layout().count()):
            self.tab[tabs_canvas_index].layout().removeItem(self.tab[tabs_canvas_index].layout().itemAt(i))

        if mode == 0:
            figure = FigureCanvas(gol.plot_image(data2D,
                                                 dataX,
                                                 dataY,
                                                 xtitle=xtitle,
                                                 ytitle=ytitle,
                                                 title=title,
                                                 show=False,
                                                 aspect='auto'))


            self.plot_canvas[plot_canvas_index] = figure
        else:

            origin = (dataX[0],dataY[0])
            scale = (dataX[1]-dataX[0],dataY[1]-dataY[0])

            data_to_plot = data2D.T

            colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}


            if mode == 1:
                #TODO: delete: srio commented this part as it is never used
                raise Exception("Cannot use XoppyPlot.XoppyImageView()")
                # self.plot_canvas[plot_canvas_index] = XoppyPlot.XoppyImageView()
                # colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}
                #
                # self.plot_canvas[plot_canvas_index]._imagePlot.setDefaultColormap(colormap)
                # self.plot_canvas[plot_canvas_index].setImage(numpy.array(data_to_plot), origin=origin, scale=scale)
            elif mode == 2:

                self.plot_canvas[plot_canvas_index] = Plot2D()

                self.plot_canvas[plot_canvas_index].resetZoom()
                self.plot_canvas[plot_canvas_index].setXAxisAutoScale(True)
                self.plot_canvas[plot_canvas_index].setYAxisAutoScale(True)
                self.plot_canvas[plot_canvas_index].setGraphGrid(False)
                self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(True)
                self.plot_canvas[plot_canvas_index].yAxisInvertedAction.setVisible(False)

                self.plot_canvas[plot_canvas_index].setXAxisLogarithmic(False)
                self.plot_canvas[plot_canvas_index].setYAxisLogarithmic(False)
                #silx 0.4.0
                self.plot_canvas[plot_canvas_index].getMaskAction().setVisible(False)
                self.plot_canvas[plot_canvas_index].getRoiAction().setVisible(False)
                self.plot_canvas[plot_canvas_index].getColormapAction().setVisible(False)
                self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(False)



                self.plot_canvas[plot_canvas_index].addImage(numpy.array(data_to_plot),
                                                             legend="zio billy",
                                                             scale=scale,
                                                             origin=origin,
                                                             colormap=colormap,
                                                             replace=True)

                self.plot_canvas[plot_canvas_index].setActiveImage("zio billy")

                # COLOR TABLE
                from matplotlib.image import AxesImage
                image = AxesImage(self.plot_canvas[plot_canvas_index]._backend.ax)
                image.set_data(numpy.array(data_to_plot))
                self.plot_canvas[plot_canvas_index]._backend.fig.colorbar(image, ax=self.plot_canvas[plot_canvas_index]._backend.ax)

            self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)
            self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)
            self.plot_canvas[plot_canvas_index].setGraphTitle(title)

        self.tab[tabs_canvas_index].layout().addWidget(self.plot_canvas[plot_canvas_index])
    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)
Example #42
0
__copyright = "ESRF, 2016"



import numpy
from scipy.special import hermite
from srxraylib.plot.gol import plot_image


#
# inputs
#
size_x = 1.0
size_y = .50
n_x = 620
n_y = 320
w = size_x/8.
m = 3
n = 0

X = numpy.linspace(-size_x/2,size_x/2,n_x)
Y = numpy.linspace(-size_y/2,size_y/2,n_y)

XX = numpy.outer(X,numpy.ones_like(Y))
YY = numpy.outer(numpy.ones_like(X),Y)

out =     (hermite(m)(numpy.sqrt(2)*XX/w)*numpy.exp(-XX**2/w**2))**2 \
        * (hermite(n)(numpy.sqrt(2)*YY/w)*numpy.exp(-YY**2/w**2))**2

plot_image(out,X,Y)
Example #43
0
    def test_interpolator(self,do_plot=do_plot):
        #
        # interpolator
        #
        print("#                                                             ")
        print("# Tests for 2D interpolator                                   ")
        print("#                                                             ")

        x = numpy.linspace(-10,10,100)
        y = numpy.linspace(-20,20,50)

        xy = numpy.meshgrid(x,y)
        X = xy[0].T
        Y = xy[1].T
        sigma = 3.0
        Z = 3*numpy.exp(- (X**2+Y**2)/2/sigma**2) +4j

        print("shape of Z",Z.shape)

        wf = Wavefront2D.initialize_wavefront_from_steps(x[0],x[1]-x[0],y[0],y[1]-y[0],number_of_points=(100,50))
        print("wf shape: ",wf.size())
        wf.set_complex_amplitude( Z )

        x1 = 3.2
        y1 = -2.5
        z1 = 3*numpy.exp(- (x1**2+y1**2)/2/sigma**2) + 4j
        print("complex ampl at (%g,%g): %g+%gi (exact=%g+%gi)"%(x1,y1,
                                                        wf.get_interpolated_complex_amplitude(x1,y1).real,
                                                        wf.get_interpolated_complex_amplitude(x1,y1).imag,
                                                        z1.real,z1.imag))
        self.assertAlmostEqual(wf.get_interpolated_complex_amplitude(x1,y1).real,z1.real,4)
        self.assertAlmostEqual(wf.get_interpolated_complex_amplitude(x1,y1).imag,z1.imag,4)
        #
        print("intensity  at (%g,%g):   %g (exact=%g)"%(x1,y1,wf.get_interpolated_intensity(x1,y1),numpy.abs(z1)**2))
        self.assertAlmostEqual(wf.get_interpolated_intensity(x1,y1),numpy.abs(z1)**2,4)

        # interpolate on same grid

        interpolated_complex_amplitude_on_same_grid = wf.get_interpolated_complex_amplitudes(X,Y)
        print("Shape interpolated at same grid: ",interpolated_complex_amplitude_on_same_grid.shape)

        numpy.testing.assert_array_almost_equal(wf.get_complex_amplitude(),interpolated_complex_amplitude_on_same_grid,4)

        print("Total intensity original wavefront: %g, interpolated on the same grid: %g"%
              (wf.get_intensity().sum(), (numpy.abs(interpolated_complex_amplitude_on_same_grid)**2).sum()))



        if do_plot:
            from srxraylib.plot.gol import plot_image
            plot_image(wf.get_intensity(),wf.get_coordinate_x(),wf.get_coordinate_y(),title="Original",show=0)
            plot_image(wf.get_interpolated_intensity(X,Y),wf.get_coordinate_x(),wf.get_coordinate_y(),
                       title="interpolated on same grid",show=1)


        # rebin wavefront

        # wf.set_plane_wave_from_complex_amplitude(3+4j)
        wf_rebin = wf.rebin(2.0,5.0,0.5,0.8,keep_the_same_intensity=1,set_extrapolation_to_zero=1)
        print("Shape before rebinning: ",wf.size())
        print("Shape after rebinning: ",wf_rebin.size())

        print("Total intensity original wavefront: %g, rebinned: %g"%
              (wf.get_intensity().sum(), wf_rebin.get_intensity().sum() ))

        if do_plot:
            from srxraylib.plot.gol import plot_image
            plot_image(wf.get_intensity(),wf.get_coordinate_x(),wf.get_coordinate_y(),title="BEFORE REBINNING",show=0)
            plot_image(wf_rebin.get_intensity(),wf_rebin.get_coordinate_x(),wf_rebin.get_coordinate_y(),
                       title="REBINNED",show=1)
Example #44
0
def test_xoppy_calc_undulator_radiation(ELECTRONENERGY=6.04,ELECTRONENERGYSPREAD=0.001,ELECTRONCURRENT=0.2,\
                                       ELECTRONBEAMSIZEH=0.000395,ELECTRONBEAMSIZEV=9.9e-06,\
                                       ELECTRONBEAMDIVERGENCEH=1.05e-05,ELECTRONBEAMDIVERGENCEV=3.9e-06,\
                                       PERIODID=0.018,NPERIODS=222,KV=1.68,DISTANCE=30.0,GAPH=0.003,GAPV=0.003,\
                                       HSLITPOINTS=41,VSLITPOINTS=41,METHOD=3):
    print("Inside xoppy_calc_undulator_radiation. ")

    bl = {}
    bl['name'] = "test_xoppy_undulator_radiation"
    bl['ElectronBeamDivergenceH'] = ELECTRONBEAMDIVERGENCEH
    bl['ElectronBeamDivergenceV'] = ELECTRONBEAMDIVERGENCEV
    bl['ElectronBeamSizeH'] = ELECTRONBEAMSIZEH
    bl['ElectronBeamSizeV'] = ELECTRONBEAMSIZEV
    bl['ElectronCurrent'] = ELECTRONCURRENT
    bl['ElectronEnergy'] = ELECTRONENERGY
    bl['ElectronEnergySpread'] = ELECTRONENERGYSPREAD
    bl['Kv'] = KV
    bl['NPeriods'] = NPERIODS
    bl['PeriodID'] = PERIODID
    bl['distance'] = DISTANCE
    bl['gapH'] = GAPH
    bl['gapV'] = GAPV


    gamma = ELECTRONENERGY / (codata_mee * 1e-3)
    print ("Gamma: %f \n"%(gamma))

    resonance_wavelength = (1 + bl['Kv']**2 / 2.0) / 2 / gamma**2 * bl["PeriodID"]
    m2ev = codata.c * codata.h / codata.e      # lambda(m)  = m2eV / energy(eV)
    resonance_energy = m2ev / resonance_wavelength

    print ("Resonance wavelength [A]: %g \n"%(1e10*resonance_wavelength))
    print ("Resonance energy [eV]: %g \n"%(resonance_energy))

    energy = None
    if energy == None:
        energy = resonance_energy+1


    outFile = "undulator_radiation.spec"


    if METHOD == 0:
        print("Undulator radiation calculation using US. Please wait...")
        e,h,v,p = calc3d_us(bl,fileName=outFile,fileAppend=False,hSlitPoints=HSLITPOINTS,vSlitPoints=VSLITPOINTS,
                                    photonEnergyMin=energy,photonEnergyMax=13000,photonEnergyPoints=1,zero_emittance=False)
        print("Done")
    if METHOD == 1:
        print("Undulator radiation calculation using URGENT. Please wait...")
        e,h,v,p = calc3d_urgent(bl,fileName=outFile,fileAppend=False,hSlitPoints=HSLITPOINTS,vSlitPoints=VSLITPOINTS,
                                    photonEnergyMin=energy,photonEnergyMax=13000,photonEnergyPoints=1,zero_emittance=False)
        print("Done")
    if METHOD == 2:
        print("Undulator radiation calculation using SRW. Please wait...")
        e,h,v,p = calc3d_srw(bl,fileName=outFile,fileAppend=False,hSlitPoints=HSLITPOINTS,vSlitPoints=VSLITPOINTS,
                                    photonEnergyMin=energy,photonEnergyMax=13000,photonEnergyPoints=1,zero_emittance=False)
        print("Done")
    if METHOD == 3:
        print("Undulator radiation calculation using SRW. Please wait...")
        e,h,v,p = calc3d_pysru(bl,fileName=outFile,fileAppend=False,hSlitPoints=HSLITPOINTS,vSlitPoints=VSLITPOINTS,
                                    photonEnergyMin=energy,photonEnergyMax=13000,photonEnergyPoints=1,zero_emittance=False)
        print("Done")


    from srxraylib.plot.gol import plot_image
    plot_image(p[0],h,v)
def main(beamline,pixels=100):

    npixels_x = pixels
    npixels_y = npixels_x


    pixelsize_x = beamline['gapH'] / npixels_x
    pixelsize_y = beamline['gapV'] / npixels_y

    print("pixelsize X=%f,Y=%f: "%(pixelsize_x,pixelsize_y))

    propagation_distance = beamline['distance']

    #
    # initialize wavefronts of dimension equal to the lens
    #
    wf_fft = 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=1e-10)


    gamma = beamline['ElectronEnergy'] / (codata_mee * 1e-3)
    print ("Gamma: %f \n"%(gamma))


    # photon_wavelength = (1 + beamline['Kv']**2 / 2.0) / 2 / gamma**2 * beamline["PeriodID"] / beamline['harmonicID']

    photon_wavelength = m2ev / beamline["photonEnergy"]


    print ("Photon wavelength [A]: %g \n"%(1e10*photon_wavelength))
    print ("Photon energy [eV]: %g \n"%(beamline["photonEnergy"]))


    myBeam = ElectronBeam(Electron_energy=beamline['ElectronEnergy'], I_current=beamline['ElectronCurrent'])
    myUndulator = MagneticStructureUndulatorPlane(K=beamline['Kv'], period_length=beamline['PeriodID'],
                        length=beamline['PeriodID']*beamline['NPeriods'])


    XX = wf_fft.get_mesh_x()
    YY = wf_fft.get_mesh_y()
    X = wf_fft.get_coordinate_x()
    Y = wf_fft.get_coordinate_y()

    source = SourceUndulatorPlane(undulator=myUndulator,
                        electron_beam=myBeam, magnetic_field=None)


    omega = beamline["photonEnergy"] * codata.e / codata.hbar
    Nb_pts_trajectory = int(source.choose_nb_pts_trajectory(0.01,photon_frequency=omega))
    print("Number of trajectory points: ",Nb_pts_trajectory)


    traj_fact = TrajectoryFactory(Nb_pts=Nb_pts_trajectory,method=TRAJECTORY_METHOD_ODE,
                                  initial_condition=None)

    print("Number of trajectory points: ",traj_fact.Nb_pts)

    if (traj_fact.initial_condition == None):
        traj_fact.initial_condition = source.choose_initial_contidion_automatic()

    print("Number of trajectory points: ",traj_fact.Nb_pts,traj_fact.initial_condition)
    #print('step 2')

    rad_fact = RadiationFactory(method=RADIATION_METHOD_NEAR_FIELD, photon_frequency=omega)


    #print('step 3')
    trajectory = traj_fact.create_from_source(source=source)


    #print('step 4')
    radiation = rad_fact.create_for_one_relativistic_electron(trajectory=trajectory, source=source,
                        XY_are_list=False,distance=beamline['distance'], X=X, Y=Y)

    efield = rad_fact.calculate_electrical_field(trajectory=trajectory,source=source,
                        distance=beamline['distance'],X_array=XX,Y_array=YY)

    tmp = efield.electrical_field()[:,:,0]


    wf_fft.set_photon_energy(beamline["photonEnergy"])

    wf_fft.set_complex_amplitude( tmp )

    # plot

    plot_image(wf_fft.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
               xtitle="X um",ytitle="Y um",title="UND source at lens plane",show=1)

    # apply lens

    focal_length = propagation_distance / 2

    wf_fft.apply_ideal_lens(focal_length,focal_length)



    plot_image(wf_fft.get_phase(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
               title="Phase just after the lens",xtitle="X um",ytitle="Y um",show=1)

    wf_fft, x_fft, y_fft = propagation_to_image(wf_fft,do_plot=0,method='fft',
                            propagation_steps=1,
                            propagation_distance = propagation_distance, defocus_factor=1.0)


    plot_image(wf_fft.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
               title="Intensity at image plane",xtitle="X um",ytitle="Y um",show=1)

    if do_plot:
        plot_table(1e6*x_fft,y_fft,ytitle="Intensity",xtitle="x coordinate [um]",
                   title="Comparison 1:1 focusing ")
Example #46
0
                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 main(mode_wavefront_before_lens):

    lens_diameter = 0.002 # 0.001 # 0.002

    if mode_wavefront_before_lens == 'Undulator with lens':
        npixels_x = 512
    else:
        npixels_x = 2048*1.5

    pixelsize_x = lens_diameter / npixels_x
    print("pixelsize: ",pixelsize_x)


    pixelsize_y = pixelsize_x
    npixels_y = npixels_x

    wavelength = 1.24e-10
    propagation_distance = 30.0
    defocus_factor = 1.0 # 1.0 is at focus
    propagation_steps = 1

    # for Gaussian source
    sigma_x = lens_diameter / 400 # 5e-6
    sigma_y = sigma_x # 5e-6
    # for Hermite-Gauss, the H and V mode index (start from 0)
    hm = 3
    hn = 1

    #
    # initialize wavefronts of dimension equal to the lens
    #
    wf_fft = 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_convolution = 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)
    if SRWLIB_AVAILABLE:
        wf_srw = 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)

    #
    # calculate/define wavefront at zero distance downstream the lens
    #
    if mode_wavefront_before_lens == 'convergent spherical':
        # no need to propagate nor define lens
        wf_fft.set_spherical_wave(complex_amplitude=1.0,radius=-propagation_distance)
        wf_convolution.set_spherical_wave(complex_amplitude=1.0,radius=-propagation_distance)
        if SRWLIB_AVAILABLE: wf_srw.set_spherical_wave(complex_amplitude=1.0,radius=-propagation_distance)

    elif mode_wavefront_before_lens == 'divergent spherical with lens':
        # define wavefront at zero distance upstream the lens and apply lens
        focal_length = propagation_distance / 2.

        wf_fft.set_spherical_wave(complex_amplitude=1.0,radius=propagation_distance)
        wf_fft.apply_ideal_lens(focal_length,focal_length)

        wf_convolution.set_spherical_wave(complex_amplitude=1.0,radius=propagation_distance)
        wf_convolution.apply_ideal_lens(focal_length,focal_length)

        if SRWLIB_AVAILABLE:
            wf_srw.set_spherical_wave(complex_amplitude=1.0,radius=propagation_distance)
            wf_srw.apply_ideal_lens(focal_length,focal_length)

    elif mode_wavefront_before_lens == 'plane with lens':
        # define wavefront at zero distance upstream the lens and apply lens
        focal_length = propagation_distance

        wf_fft.set_plane_wave_from_complex_amplitude(1.0+0j)
        wf_fft.apply_ideal_lens(focal_length,focal_length)

        wf_convolution.set_plane_wave_from_complex_amplitude(1.0+0j)
        wf_convolution.apply_ideal_lens(focal_length,focal_length)

        if SRWLIB_AVAILABLE:
            wf_srw.set_plane_wave_from_complex_amplitude(1.0+0j)
            wf_srw.apply_ideal_lens(focal_length,focal_length)

    elif mode_wavefront_before_lens == 'Gaussian with lens':
        # define wavefront at source point, propagate to the lens and apply lens
        X = wf_fft.get_mesh_x()
        Y = wf_fft.get_mesh_y()

        intensity = numpy.exp( - X**2/(2*sigma_x**2)) * numpy.exp( - Y**2/(2*sigma_y**2))


        wf_fft.set_complex_amplitude( numpy.sqrt(intensity) )
        wf_convolution.set_complex_amplitude( numpy.sqrt(intensity) )
        if SRWLIB_AVAILABLE: wf_srw.set_complex_amplitude( numpy.sqrt(intensity) )

        # plot

        plot_image(wf_fft.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
                   xtitle="X um",ytitle="Y um",title="Gaussian source",show=1)

        wf_fft, tmp1, tmp2 = propagation_to_image(wf_fft,method='fft',propagation_distance=propagation_distance,
                                              do_plot=0,plot_title="Before lens")
        wf_convolution, tmp1, tmp2 = propagation_to_image(wf_convolution,method='convolution',propagation_distance=propagation_distance,
                                              do_plot=0,plot_title="Before lens")
        if SRWLIB_AVAILABLE:
            wf_srw, tmp1, tmp2 = propagation_to_image(wf_srw,method='srw',propagation_distance=propagation_distance,
                                              do_plot=0,plot_title="Before lens")


        plot_image(wf_fft.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
                   xtitle="X um",ytitle="Y um",title="Before lens fft",show=1)

        plot_image(wf_convolution.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
                   xtitle="X um",ytitle="Y um",title="Before lens convolution",show=1)

        focal_length = propagation_distance / 2

        wf_fft.apply_ideal_lens(focal_length,focal_length)
        wf_convolution.apply_ideal_lens(focal_length,focal_length)
        if SRWLIB_AVAILABLE: wf_srw.apply_ideal_lens(focal_length,focal_length)

    elif mode_wavefront_before_lens == 'Hermite with lens':
        # define wavefront at source point, propagate to the lens and apply lens
        X = wf_fft.get_mesh_x()
        Y = wf_fft.get_mesh_y()

        efield =     (hermite(hm)(numpy.sqrt(2)*X/sigma_x)*numpy.exp(-X**2/sigma_x**2))**2 \
                   * (hermite(hn)(numpy.sqrt(2)*Y/sigma_y)*numpy.exp(-Y**2/sigma_y**2))**2

        wf_fft.set_complex_amplitude( efield )
        wf_convolution.set_complex_amplitude( efield )
        if SRWLIB_AVAILABLE: wf_srw.set_complex_amplitude( efield )

        # plot

        plot_image(wf_fft.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
                   xtitle="X um",ytitle="Y um",title="Hermite-Gauss source",show=1)

        wf_fft, tmp1, tmp2 = propagation_to_image(wf_fft,method='fft',propagation_distance=propagation_distance,
                                              do_plot=0,plot_title="Before lens")
        wf_convolution, tmp1, tmp2 = propagation_to_image(wf_convolution,method='convolution',propagation_distance=propagation_distance,
                                              do_plot=0,plot_title="Before lens")
        if SRWLIB_AVAILABLE:
            wf_srw, tmp1, tmp2 = propagation_to_image(wf_srw,method='srw',propagation_distance=propagation_distance,
                                              do_plot=0,plot_title="Before lens")


        plot_image(wf_fft.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
                   xtitle="X um",ytitle="Y um",title="Before lens fft",show=1)

        plot_image(wf_convolution.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
                   xtitle="X um",ytitle="Y um",title="Before lens convolution",show=1)

        focal_length = propagation_distance / 2

        wf_fft.apply_ideal_lens(focal_length,focal_length)
        wf_convolution.apply_ideal_lens(focal_length,focal_length)
        if SRWLIB_AVAILABLE: wf_srw.apply_ideal_lens(focal_length,focal_length)

    elif mode_wavefront_before_lens == 'Undulator with lens':

        beamline = {}
        # beamline['name'] = "ESRF_NEW_OB"
        # beamline['ElectronBeamDivergenceH'] = 5.2e-6    # these values are not used (zero emittance)
        # beamline['ElectronBeamDivergenceV'] = 1.4e-6    # these values are not used (zero emittance)
        # beamline['ElectronBeamSizeH'] = 27.2e-6         # these values are not used (zero emittance)
        # beamline['ElectronBeamSizeV'] = 3.4e-6          # these values are not used (zero emittance)
        # beamline['ElectronEnergySpread'] = 0.001        # these values are not used (zero emittance)
        beamline['ElectronCurrent'] = 0.2
        beamline['ElectronEnergy']  = 6.0
        beamline['Kv']              = 1.68  # 1.87
        beamline['NPeriods']        = 111   # 14
        beamline['PeriodID']        = 0.018 # 0.035
        beamline['distance']        =   propagation_distance
        # beamline['gapH']      = pixelsize_x*npixels_x
        # beamline['gapV']      = pixelsize_x*npixels_x

        gamma = beamline['ElectronEnergy'] / (codata_mee * 1e-3)
        print ("Gamma: %f \n"%(gamma))

        resonance_wavelength = (1 + beamline['Kv']**2 / 2.0) / 2 / gamma**2 * beamline["PeriodID"]
        resonance_energy = m2ev / resonance_wavelength



        print ("Resonance wavelength [A]: %g \n"%(1e10*resonance_wavelength))
        print ("Resonance energy [eV]: %g \n"%(resonance_energy))

        # red shift 100 eV
        resonance_energy = resonance_energy - 100


        myBeam = ElectronBeam(Electron_energy=beamline['ElectronEnergy'], I_current=beamline['ElectronCurrent'])
        myUndulator = MagneticStructureUndulatorPlane(K=beamline['Kv'], period_length=beamline['PeriodID'],
                            length=beamline['PeriodID']*beamline['NPeriods'])


        XX = wf_fft.get_mesh_x()
        YY = wf_fft.get_mesh_y()
        X = wf_fft.get_coordinate_x()
        Y = wf_fft.get_coordinate_y()

        source = SourceUndulatorPlane(undulator=myUndulator,
                            electron_beam=myBeam, magnetic_field=None)
        omega = resonance_energy * codata.e / codata.hbar
        Nb_pts_trajectory = int(source.choose_nb_pts_trajectory(0.01,photon_frequency=omega))
        print("Number of trajectory points: ",Nb_pts_trajectory)


        traj_fact = TrajectoryFactory(Nb_pts=Nb_pts_trajectory,method=TRAJECTORY_METHOD_ODE,
                                      initial_condition=None)

        print("Number of trajectory points: ",traj_fact.Nb_pts)

        if (traj_fact.initial_condition == None):
            traj_fact.initial_condition = source.choose_initial_contidion_automatic()

        print("Number of trajectory points: ",traj_fact.Nb_pts,traj_fact.initial_condition)
        #print('step 2')

        rad_fact = RadiationFactory(method=RADIATION_METHOD_NEAR_FIELD, photon_frequency=omega)


        #print('step 3')
        trajectory = traj_fact.create_from_source(source=source)


        #print('step 4')
        radiation = rad_fact.create_for_one_relativistic_electron(trajectory=trajectory, source=source,
                            XY_are_list=False,distance=beamline['distance'], X=X, Y=Y)

        efield = rad_fact.calculate_electrical_field(trajectory=trajectory,source=source,
                            distance=beamline['distance'],X_array=XX,Y_array=YY)

        tmp = efield.electrical_field()[:,:,0]


        wf_fft.set_photon_energy(resonance_energy)
        wf_convolution.set_photon_energy(resonance_energy)
        if SRWLIB_AVAILABLE: wf_srw.set_photon_energy(resonance_energy)

        wf_fft.set_complex_amplitude( tmp )
        wf_convolution.set_complex_amplitude( numpy.sqrt(tmp) )
        if SRWLIB_AVAILABLE: wf_srw.set_complex_amplitude( numpy.sqrt(tmp) )

        # plot

        plot_image(wf_fft.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
                   xtitle="X um",ytitle="Y um",title="UND source at lens plane",show=1)

        # apply lens

        focal_length = propagation_distance / 2

        wf_fft.apply_ideal_lens(focal_length,focal_length)
        wf_convolution.apply_ideal_lens(focal_length,focal_length)
        if SRWLIB_AVAILABLE: wf_srw.apply_ideal_lens(focal_length,focal_length)

    else:
        raise Exception("Unknown mode")


    plot_image(wf_fft.get_phase(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
               title="Phase just after the lens",xtitle="X um",ytitle="Y um",show=1)

    wf_fft, x_fft, y_fft = propagation_to_image(wf_fft,do_plot=0,method='fft',
                            propagation_steps=propagation_steps,
                            propagation_distance = propagation_distance, defocus_factor=defocus_factor)

    wf_convolution, x_convolution, y_convolution = propagation_to_image(wf_convolution,do_plot=0,method='convolution',
                            propagation_steps=propagation_steps,
                            propagation_distance = propagation_distance, defocus_factor=defocus_factor)
    if SRWLIB_AVAILABLE:
        wf_srw, x_srw, y_srw = propagation_to_image(wf_srw,do_plot=0,method='srw',
                                propagation_steps=propagation_steps,
                                propagation_distance = propagation_distance, defocus_factor=defocus_factor)

    plot_image(wf_fft.get_intensity(),1e6*wf_fft.get_coordinate_x(),1e6*wf_fft.get_coordinate_y(),
               title="Intensity at image plane",xtitle="X um",ytitle="Y um",show=1)

    if do_plot:
        if SRWLIB_AVAILABLE:
            x = x_fft
            y = numpy.vstack((y_fft,y_srw,y_convolution))

            plot_table(1e6*x,y,legend=["fft","srw","convolution"],ytitle="Intensity",xtitle="x coordinate [um]",
                       title="Comparison 1:1 focusing "+mode_wavefront_before_lens)
        else:
            x = x_fft
            y = numpy.vstack((y_fft,y_convolution))

            plot_table(1e6*x,y,legend=["fft","convolution"],ytitle="Intensity",xtitle="x coordinate [um]",
                       title="Comparison 1:1 focusing "+mode_wavefront_before_lens)
Example #48
0
    def test_spherical_wave(self,do_plot=do_plot):
        #
        # plane wave
        #
        print("#                                                             ")
        print("# Tests for a 2D spherical wave                               ")
        print("#                                                             ")

        wavelength        = 1.24e-10

        wavefront_length_x = 400e-6
        wavefront_length_y = wavefront_length_x

        npixels_x =  1024
        npixels_y =  npixels_x

        x = numpy.linspace(-0.5*wavefront_length_x,0.5*wavefront_length_x,npixels_x)
        y = numpy.linspace(-0.5*wavefront_length_y,0.5*wavefront_length_y,npixels_y)



        wf1 = Wavefront2D.initialize_wavefront_from_steps(
                        x_start=x[0],x_step=numpy.abs(x[1]-x[0]),
                        y_start=y[0],y_step=numpy.abs(y[1]-y[0]),
                        number_of_points=(npixels_x,npixels_y),wavelength=wavelength)

        numpy.testing.assert_almost_equal(x,wf1.get_coordinate_x(),9)
        numpy.testing.assert_almost_equal(y,wf1.get_coordinate_y(),9)

        wf2 = Wavefront2D.initialize_wavefront_from_steps(
                        x_start=x[0],x_step=numpy.abs(x[1]-x[0]),
                        y_start=y[0],y_step=numpy.abs(y[1]-y[0]),
                        number_of_points=(npixels_x,npixels_y),wavelength=wavelength)


        numpy.testing.assert_almost_equal(x,wf2.get_coordinate_x(),9)
        numpy.testing.assert_almost_equal(y,wf2.get_coordinate_y(),9)
        # 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,-20e-6,40e-6)

        wf2.set_plane_wave_from_complex_amplitude(3+0j)
        wf2.apply_ideal_lens(5.0,5.0)
        wf2.apply_slit(-50e-6,10e-6,-20e-6,40e-6)



        if do_plot:
            from srxraylib.plot.gol import plot_image
            plot_image(wf1.get_phase(),wf2.get_coordinate_x(),wf2.get_coordinate_y(),
                       title="Phase of spherical wavefront",show=0)
            plot_image(wf2.get_phase(),wf2.get_coordinate_x(),wf2.get_coordinate_y(),
                       title="Phase of focused plane wavefront",show=0)
            plot_image(wf1.get_phase(from_minimum_intensity=0.1),wf2.get_coordinate_x(),wf2.get_coordinate_y(),
                       title="Phase of spherical wavefront (for intensity > 0.1)",show=0)
            plot_image(wf2.get_phase(from_minimum_intensity=0.1),wf2.get_coordinate_x(),wf2.get_coordinate_y(),
                       title="Phase of focused plane wavefront (for intensity > 0.1)",show=1)


        numpy.testing.assert_almost_equal(wf1.get_phase(),wf2.get_phase(),5)
Example #49
0
    def plot_data2D(self, data2D, dataX, dataY, tabs_canvas_index, plot_canvas_index, title="", xtitle="", ytitle="", mode=2):

        self.tab[tabs_canvas_index].layout().removeItem(self.tab[tabs_canvas_index].layout().itemAt(0))

        if mode == 0:
            figure = FigureCanvas(gol.plot_image(data2D,
                                                 dataX,
                                                 dataY,
                                                 xtitle=xtitle,
                                                 ytitle=ytitle,
                                                 title=title,
                                                 show=False,
                                                 aspect='auto'))


            self.plot_canvas[plot_canvas_index] = figure
        else:
            xmin = numpy.min(dataX)
            xmax = numpy.max(dataX)
            ymin = numpy.min(dataY)
            ymax = numpy.max(dataY)

            origin = (xmin, ymin)
            scale = (abs((xmax-xmin)/len(dataX)), abs((ymax-ymin)/len(dataY)))

            # PyMCA inverts axis!!!! histogram must be calculated reversed
            data_to_plot = []
            for y_index in range(0, len(dataY)):
                x_values = []
                for x_index in range(0, len(dataX)):
                    x_values.append(data2D[x_index][y_index])

                data_to_plot.append(x_values)

            if mode == 1:
                self.plot_canvas[plot_canvas_index] = XoppyPlot.XoppyImageView()
                colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}

                self.plot_canvas[plot_canvas_index]._imagePlot.setDefaultColormap(colormap)
                self.plot_canvas[plot_canvas_index].setImage(numpy.array(data_to_plot), origin=origin, scale=scale)
            elif mode == 2:
                self.plot_canvas[plot_canvas_index] = PlotWindow(colormap=False,
                                                                 flip=False,
                                                                 grid=False,
                                                                 togglePoints=False,
                                                                 logx=False,
                                                                 logy=False,
                                                                 copy=False,
                                                                 save=True,
                                                                 aspect=True,
                                                                 roi=False,
                                                                 control=False,
                                                                 position=True,
                                                                 plugins=False)

                colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}

                self.plot_canvas[plot_canvas_index].setDefaultColormap(colormap)

                self.plot_canvas[plot_canvas_index].addImage(numpy.array(data_to_plot),
                                                             legend="zio billy",
                                                             xScale=(origin[0], scale[0]),
                                                             yScale=(origin[1], scale[1]),
                                                             colormap=colormap,
                                                             replace=True,
                                                             replot=True)
                self.plot_canvas[plot_canvas_index].setActiveImage("zio billy")

                from matplotlib.image import AxesImage
                image = AxesImage(self.plot_canvas[plot_canvas_index]._plot.ax)
                image.set_data(numpy.array(data_to_plot))

                self.plot_canvas[plot_canvas_index]._plot.graph.fig.colorbar(image, ax=self.plot_canvas[plot_canvas_index]._plot.ax)

            self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)
            self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)
            self.plot_canvas[plot_canvas_index].setGraphTitle(title)

        self.tab[tabs_canvas_index].layout().addWidget(self.plot_canvas[plot_canvas_index])
Example #50
0
#**********************Plotting results (requires 3rd party graphics package)


from srxraylib.plot.gol import plot,plot_image
import numpy

print('   Plotting the results (blocks script execution; close any graph windows to proceed) ... ', end='')
# uti_plot1d(arI1, [wfr1.mesh.eStart, wfr1.mesh.eFin, wfr1.mesh.ne], ['Photon Energy [eV]', 'Intensity [ph/s/.1%bw/mm^2]', 'On-Axis Spectrum'])

plot( numpy.linspace(wfr1.mesh.eStart, wfr1.mesh.eFin, wfr1.mesh.ne), arI1, xtitle='Photon Energy [eV]', ytitle='Intensity [ph/s/.1%bw/mm^2]', title='On-Axis Spectrum',show=False)

# uti_plot2d(arI2, [1000*wfr2.mesh.xStart, 1000*wfr2.mesh.xFin, wfr2.mesh.nx], [1000*wfr2.mesh.yStart, 1000*wfr2.mesh.yFin, wfr2.mesh.ny], ['Horizontal Position [mm]', 'Vertical Position [mm]', 'Intensity at ' + str(wfr2.mesh.eStart) + ' eV'])
# TODO: check correctness of H and V (I think is OK)
arI2xx = numpy.array(arI2)
arI2xx = arI2xx.reshape((wfr2.mesh.ny,wfr2.mesh.nx)).T
plot_image(arI2xx, numpy.linspace(1000*wfr2.mesh.xStart, 1000*wfr2.mesh.xFin, wfr2.mesh.nx), numpy.linspace(1000*wfr2.mesh.yStart, 1000*wfr2.mesh.yFin, wfr2.mesh.ny), xtitle='Horizontal Position [mm]', ytitle='Vertical Position [mm]', title='Intensity at ' + str(wfr2.mesh.eStart) + ' eV',show=False)

arI2x = array('f', [0]*wfr2.mesh.nx) #array to take 1D intensity data (vs X)
srwl.CalcIntFromElecField(arI2x, wfr2, 6, 0, 1, wfr2.mesh.eStart, 0, 0)

# uti_plot1d(arI2x, [1000*wfr2.mesh.xStart, 1000*wfr2.mesh.xFin, wfr2.mesh.nx], ['Horizontal Position [mm]', 'Intensity [ph/s/.1%bw/mm^2]', 'Intensity at ' + str(wfr2.mesh.eStart) + ' eV\n(horizontal cut at x = 0)'])
plot( numpy.linspace(1000*wfr2.mesh.xStart, 1000*wfr2.mesh.xFin, wfr2.mesh.nx), arI2x, xtitle='Horizontal Position [mm]', ytitle='Intensity [ph/s/.1%bw/mm^2]', title='Intensity at ' + str(wfr2.mesh.eStart) + ' eV\n(horizontal cut at x = 0)',show=False) 

arI2y = array('f', [0]*wfr2.mesh.ny) #array to take 1D intensity data (vs Y)
srwl.CalcIntFromElecField(arI2y, wfr2, 6, 0, 2, wfr2.mesh.eStart, 0, 0)

# uti_plot1d(arI2y, [1000*wfr2.mesh.yStart, 1000*wfr2.mesh.yFin, wfr2.mesh.ny], ['Vertical Position [mm]', 'Intensity [ph/s/.1%bw/mm^2]', 'Intensity at ' + str(wfr2.mesh.eStart) + ' eV\n(vertical cut at y = 0)'])
plot( numpy.linspace(1000*wfr2.mesh.yStart, 1000*wfr2.mesh.yFin, wfr2.mesh.ny), arI2y, xtitle='Vertical Position [mm]', ytitle='Intensity [ph/s/.1%bw/mm^2]', title='Intensity at ' + str(wfr2.mesh.eStart) + ' eV\n(vertical cut at y = 0)',show=True) 

# uti_plot_show() #show all graphs (and block execution)
print('done')
    def test_ScaledMatrix(self,do_plot=do_plot):
        #
        # Matrix
        #

        x = numpy.arange(10,20,2.0)
        y = numpy.arange(20,25,1.0)

        xy = numpy.meshgrid(x,y)
        X = xy[0].T
        Y = xy[1].T
        Z = Y

        print("x,y,X,Y,Z shapes: ",x.shape,y.shape,X.shape,Y.shape,Z.shape)
        print("x,y,X,Y,Z shapes: ",x.shape,y.shape,X.shape,Y.shape,Z.shape)

        #
        # scaledMatrix.initialize + set_scale_from_steps
        #
        print("\nTesting ScaledMatrix.initialize + set_scale_from_steps...")
        scaled_matrix = ScaledMatrix.initialize(Z)
        print("    Matrix shape", scaled_matrix.shape())

        scaled_matrix.set_scale_from_steps(0,x[0],numpy.abs(x[1]-x[0]))
        scaled_matrix.set_scale_from_steps(1,y[0],numpy.abs(y[1]-y[0]))

        print("Original x: ",x)
        print("Stored x:   ",scaled_matrix.get_x_values())
        print("Original y: ",y)
        print("Stored y:    ",scaled_matrix.get_y_values())
        numpy.testing.assert_equal(x,scaled_matrix.get_x_values())
        numpy.testing.assert_equal(y,scaled_matrix.get_y_values())

        print("    Matrix X value x=0 : ", scaled_matrix.get_x_value(0.0))
        print("    Matrix Y value x_index=3 is %g (to compare with %g) "%(scaled_matrix.get_x_value(2.0),x[0]+2*(x[1]-x[0])))
        print("    Matrix Y value y_index=3 is %g (to compare with %g) "%(scaled_matrix.get_y_value(2.0),y[0]+2*(y[1]-y[0])))
        self.assertAlmostEqual(scaled_matrix.get_x_value(2.0),x[0]+2*(x[1]-x[0]),10)
        self.assertAlmostEqual(scaled_matrix.get_y_value(2.0),y[0]+2*(y[1]-y[0]),10)


        #
        # scaledMatrix.initialize + set_scale_from_range
        #

        x = numpy.linspace(-10,10,10)
        y = numpy.linspace(-25,25,20)

        xy = numpy.meshgrid(x,y)
        X = xy[0].T
        Y = xy[1].T
        Z = Y

        print("\nTesting ScaledMatrix.initialize + set_scale_from_range...")
        scaled_matrix = ScaledMatrix.initialize(Z)  # Z[0] contains Y
        print("    Matrix shape", scaled_matrix.shape())

        scaled_matrix.set_scale_from_range(0,x[0],x[-1])
        scaled_matrix.set_scale_from_range(1,y[0],y[-1])

        print("Original x: ",x)
        print("Stored x:   ",scaled_matrix.get_x_values())
        print("Original y: ",y)
        print("Stored y:    ",scaled_matrix.get_y_values())

        numpy.testing.assert_almost_equal(x,scaled_matrix.get_x_values(),11)
        numpy.testing.assert_almost_equal(y,scaled_matrix.get_y_values(),11)

        print("    Matrix X value x=0 : ", scaled_matrix.get_x_value(0.0))
        print("    Matrix Y value x_index=5 is %g (to compare with %g) "%(scaled_matrix.get_x_value(5.0),x[0]+5*(x[1]-x[0])))
        print("    Matrix Y value y_index=5 is %g (to compare with %g) "%(scaled_matrix.get_y_value(5.0),y[0]+5*(y[1]-y[0])))
        self.assertAlmostEqual(scaled_matrix.get_x_value(5.0),x[0]+5*(x[1]-x[0]),10)
        self.assertAlmostEqual(scaled_matrix.get_y_value(5.0),y[0]+5*(y[1]-y[0]),10)



        #
        # scaledMatrix.initialize_from_steps
        #

        x = numpy.arange(10,20,0.2)
        y = numpy.arange(20,25,0.1)

        xy = numpy.meshgrid(x,y)
        X = xy[0].T
        Y = xy[1].T
        Z = Y

        print("\nTesting ScaledMatrix.initialize_from_steps...")

        scaled_matrix2 = ScaledMatrix.initialize_from_steps(Z,x[0],numpy.abs(x[1]-x[0]),y[0],numpy.abs(y[1]-y[0]))

        print("    Matrix 2 shape", scaled_matrix2.shape())
        print("    Matrix 2 value x=0 : ", scaled_matrix2.get_x_value(0.0))

        print("    Matrix 2 value x=5 is %g (to compare with %g) "%(scaled_matrix2.get_x_value(5.0),x[0]+5*(x[1]-x[0])))
        self.assertAlmostEqual(scaled_matrix2.get_x_value(5.0),x[0]+5*(x[1]-x[0]))
        print("    Matrix 2 value y=5 is %g (to compare with %g) "%(scaled_matrix2.get_y_value(5.0),y[0]+5*(y[1]-y[0])))
        self.assertAlmostEqual(scaled_matrix2.get_y_value(5.0),y[0]+5*(y[1]-y[0]))


        #
        # scaledMatrix.initialize_from_range
        #
        print("\nTesting ScaledMatrix.initialize_from_range...")

        x = numpy.linspace(-10,10,20)
        y = numpy.linspace(-25,25,30)

        xy = numpy.meshgrid(x,y)
        X = xy[0].T
        Y = xy[1].T
        Z = X*0+(3+2j)

        #
        scaled_matrix3 = ScaledMatrix.initialize_from_range(Z,x[0],x[-1],y[0],y[-1])

        print("Matrix 3 shape", scaled_matrix3.shape())
        print("Matrix 3 value x=0 : ", scaled_matrix3.get_x_value(0.0))

        print("Matrix 3 value x=15 is %g (to compare with %g) "%(scaled_matrix3.get_x_value(15.0),x[0]+15*(x[1]-x[0])))
        self.assertAlmostEqual(scaled_matrix3.get_x_value(15.0),x[0]+15*(x[1]-x[0]))
        print("Matrix 3 value y=15 is %g (to compare with %g) "%(scaled_matrix3.get_y_value(15.0),y[0]+15*(y[1]-y[0])))
        self.assertAlmostEqual(scaled_matrix3.get_y_value(15.0),y[0]+15*(y[1]-y[0]))

        # print("Matrix 3 X : ", scaled_matrix3.get_x_values())
        # print("Matrix 3 Y : ", scaled_matrix3.get_y_values())
        # print("Matrix 3 Z : ", scaled_matrix3.get_z_values())

        #
        # interpolator
        #
        print("\nTesting interpolator on the same grid...")
        # constant
        Z = X * Y
        scaled_matrix4 = ScaledMatrix.initialize_from_range(Z,x[0],x[-1],y[0],y[-1])
        scaled_matrix4.compute_interpolator()

        print("Matrix 4 interpolation x=110,y=210 is ",scaled_matrix4.interpolate_value(110,210))

        # interpolate in the same grid
        s4int = scaled_matrix4.interpolate_value(X,Y)
        print("Matrix 4 interpolation same grid (shape)",s4int.shape," before: ",scaled_matrix4.shape())
        numpy.testing.assert_almost_equal(scaled_matrix4.get_z_values(),s4int,3)


        print("\nTesting interpolator on a grid with less points...")
        # interpolate in a grid with much less points
        xrebin = numpy.linspace(x[0],x[-1],x.size/10)
        yrebin = numpy.linspace(y[0],y[-1],y.size/10)
        xyrebin =numpy.meshgrid( xrebin, yrebin)
        Xrebin = xyrebin[0].T
        Yrebin = xyrebin[1].T

        s4rebin = scaled_matrix4.interpolate_value(Xrebin,Yrebin)

        if do_plot == 1:
            from srxraylib.plot.gol import plot_image
            plot_image(scaled_matrix4.get_z_values(),scaled_matrix4.get_x_values(),scaled_matrix4.get_y_values(),
                       title="Original",show=0)
            plot_image(numpy.real(s4int),scaled_matrix4.get_x_values(),scaled_matrix4.get_y_values(),
                       title="Interpolated on same grid",show=0)
            plot_image(numpy.real(s4rebin),xrebin,yrebin,
                       title="Interpolated on a grid with 10 times less points")

        for xi in xrebin:
            for yi in yrebin:
                yint = scaled_matrix4.interpolate_value(xi,yi)
                print("    Interpolated at (%g,%g) is %g+%gi (expected %g)"%(xi,yi,yint.real,yint.imag,xi*yi))
                self.assertAlmostEqual(scaled_matrix4.interpolate_value(xi,yi),xi*yi)
Example #52
0
    def plot_data2D(self, data2D, dataX, dataY, tabs_canvas_index, plot_canvas_index, title="", xtitle="", ytitle="", mode=2):

        for i in range(1+self.tab[tabs_canvas_index].layout().count()):
            self.tab[tabs_canvas_index].layout().removeItem(self.tab[tabs_canvas_index].layout().itemAt(i))

        if mode == 0:
            figure = FigureCanvas(gol.plot_image(data2D,
                                                 dataX,
                                                 dataY,
                                                 xtitle=xtitle,
                                                 ytitle=ytitle,
                                                 title=title,
                                                 show=False,
                                                 aspect='auto'))


            self.plot_canvas[plot_canvas_index] = figure
        else:

            origin = (dataX[0],dataY[0])
            scale = (dataX[1]-dataX[0],dataY[1]-dataY[0])

            data_to_plot = data2D.T

            colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}


            if mode == 1:
                #TODO: delete: srio commented this part as it is never used
                raise Exception("Cannot use XoppyPlot.XoppyImageView()")
                # self.plot_canvas[plot_canvas_index] = XoppyPlot.XoppyImageView()
                # colormap = {"name":"temperature", "normalization":"linear", "autoscale":True, "vmin":0, "vmax":0, "colors":256}
                #
                # self.plot_canvas[plot_canvas_index]._imagePlot.setDefaultColormap(colormap)
                # self.plot_canvas[plot_canvas_index].setImage(numpy.array(data_to_plot), origin=origin, scale=scale)
            elif mode == 2:

                self.plot_canvas[plot_canvas_index] = Plot2D()

                self.plot_canvas[plot_canvas_index].resetZoom()
                self.plot_canvas[plot_canvas_index].setXAxisAutoScale(True)
                self.plot_canvas[plot_canvas_index].setYAxisAutoScale(True)
                self.plot_canvas[plot_canvas_index].setGraphGrid(False)
                self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(True)
                self.plot_canvas[plot_canvas_index].yAxisInvertedAction.setVisible(False)

                self.plot_canvas[plot_canvas_index].setXAxisLogarithmic(False)
                self.plot_canvas[plot_canvas_index].setYAxisLogarithmic(False)
                #silx 0.4.0
                self.plot_canvas[plot_canvas_index].getMaskAction().setVisible(False)
                self.plot_canvas[plot_canvas_index].getRoiAction().setVisible(False)
                self.plot_canvas[plot_canvas_index].getColormapAction().setVisible(False)
                self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(False)



                self.plot_canvas[plot_canvas_index].addImage(numpy.array(data_to_plot),
                                                             legend="zio billy",
                                                             scale=scale,
                                                             origin=origin,
                                                             colormap=colormap,
                                                             replace=True)

                self.plot_canvas[plot_canvas_index].setActiveImage("zio billy")

            self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)
            self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)
            self.plot_canvas[plot_canvas_index].setGraphTitle(title)

        self.tab[tabs_canvas_index].layout().addWidget(self.plot_canvas[plot_canvas_index])
Example #53
0
    mymode_index = 0
    propagation_distance = 35.0

    #
    # Source: retrieve wanted mode for source
    #
    reader = CompactAFReader(filename_source)

    reader.info(verbose=1)

    wf = reader.get_wavefront2d(mymode_index,wavelength)

    # fwhm
    fwhm_h_source,fwhm_v_source = wavefront_intensity_fwhm(wf,prefix="Source wavefront ")
    # plot
    plot_image  (wf.get_phase()**2,1e6*wf.get_coordinate_x(),1e6*reader.y_coordinates(),title="Phases for mode %i"%mymode_index, show=0)


    #
    # propagation
    #

    # method = "fraunhofer"
    # method = "srw"
    method = "fft"

    if method == "fraunhofer":
        wf_rebinned = wf.rebin(4,10,4,15,keep_the_same_intensity=1,set_extrapolation_to_zero=1)
        wf_prop = propagate_2D_fraunhofer(wf_rebinned,propagation_distance=propagation_distance,shift_half_pixel=1)
    elif method == "srw":
        wf_prop = propagate_2D_fresnel_srw(wf,propagation_distance=propagation_distance,srw_autosetting=1)
    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
Example #55
0
    def compare_undul_phot_files(self,
                                 file1,
                                 file2,
                                 do_plot=DO_PLOT,
                                 do_assert=True):
        print("Comparing undul_phot output files: %s %s" % (file1, file2))

        dict1 = SourceUndulatorInputOutput.load_file_undul_phot(file_in=file1)
        dict2 = SourceUndulatorInputOutput.load_file_undul_phot(file_in=file2)

        rad1 = dict1["radiation"]
        # Do not compare polarizartion, I believe the preprocessor one is wrong
        # pol1 = dict1["polarization"]
        e1 = dict1["photon_energy"]
        t1 = dict1["theta"]
        p1 = dict1["phi"]

        rad2 = dict2["radiation"]
        # pol2 = dict2["polarization"]
        e2 = dict2["photon_energy"]
        t2 = dict2["theta"]
        p2 = dict2["phi"]

        print(r"---> Max diff E array %f " % ((e2 - e1).max()))
        print(r"---> Max diff T array %f " % ((t2 - t1).max()))
        print(r"---> Max diff P array %f " % ((p2 - p1).max()))

        rad_max = numpy.max((rad1, rad2))
        diff_max = numpy.max((rad1 - rad2))

        print(r"---> diff_rad_max/rad_max = %f %%" %
              (100 * diff_max / rad_max))

        if do_plot:
            plot_image(dict1['radiation'][0, :, :],
                       dict1['theta'] * 1e6,
                       dict1['phi'] * 180 / numpy.pi,
                       title="INTENS UNDUL_PHOT_PREPROCESSOR: RN0[0]" + file1,
                       xtitle="Theta [urad]",
                       ytitle="Phi [deg]",
                       aspect='auto',
                       show=False)

            plot_image(dict2['radiation'][0, :, :],
                       dict1['theta'] * 1e6,
                       dict1['phi'] * 180 / numpy.pi,
                       title="INTENS UNDUL_PHOT_PREPROCESSOR: RN0[0]" + file2,
                       xtitle="Theta [urad]",
                       ytitle="Phi [deg]",
                       aspect='auto',
                       show=False)

            plot_show()

        if do_assert:
            assert_almost_equal(e1, e2)
            assert_almost_equal(t1, t2)
            assert_almost_equal(p1, p2)
            # compare only points with appreciable intensity
            # accept if differences are less that 15%
            for ie, e in enumerate(e1):
                for it, t in enumerate(t1):
                    for ip, p in enumerate(p1):
                        if rad1[ie, it, ip] > 0.1 * rad_max:
                            mydiff = 100 * numpy.abs(rad1[ie, it, ip] - rad2[
                                ie, it, ip]) / rad1[ie, it, ip]
                            print(
                                r"--> intensity first:%g second:%g  diff:%g %%"
                                % (rad1[ie, it, ip], rad2[ie, it, ip], mydiff))
                            self.assertLess(mydiff, 15.)
    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