コード例 #1
0
ファイル: utilMask.py プロジェクト: JeromeKnappett/SXRL
def test():
    """ Testing theoretical efficiency """
    m = 1  #order of diffracted beam
    beta = 1.76493861 * 1e-3  #imaginary part of refractive index
    delta = 1 - (2.068231 * 1e-2)  #(1-real part) of refractive index
    d = 200e-9  #grating periodicity
    k = 197.3 * 6.7  #photon energy in units of (hbar*c)
    b = 72e-9
    theta = 0  #np.pi/2 #incident angle

    # print(" ")
    # print("-----Grating efficiency (DEL)-----")
    # gratingEfficiencyDEL(m, beta, delta, d, k, b,theta)

    print(" ")
    print("-----Grating efficiency (amplitude)-----")
    gratingEfficiencyHARV(1, 100e-9, 200e-9, G=0)

    print(" ")
    print("-----Grating efficiency (phase)-----")
    gratingEfficiencyHARV(1, 100e-9, 200e-9, G=1)
    """ Testing simulated efficiency """
    eMin = 1e8
    Nx = 150
    Ny = 150
    Nz = 1
    xMin = -10e-6
    xMax = 10e-6
    yMin = -10e-6
    yMax = 10e-6
    zMin = 100
    # Fx = 1/2
    # Fy = 1/2

    print(" ")
    print('Running Test:')
    print('building wavefront...')
    w = build_gauss_wavefront(Nx, Ny, Nz, eMin / 1000, xMin, xMax, yMin, yMax,
                              1, 1e-6, 1e-6, 1)

    wf0 = Wavefront(srwl_wavefront=w)
    """ Intensity from test Gaussian """
    # I = wf0.get_intensity()

    directory = "/home/jerome/Documents/MASTERS/data/wavefields/Efficiency/"
    """ Load pickled Wavefronts """
    path1 = directory + "incident.pkl"
    path2 = directory + "exit_TH10.pkl"
    path3 = directory + "prop_TH10.pkl"
    """ Intensity from tif file """
    I0 = getImageData(directory + "intensityIN.tif")
    I1 = getImageData(directory + "intensityEX_1-2.tif")
    I2 = getImageData(directory + "intensityPR_1-2.tif")  #getImageData('/hom

    pathm0 = directory + "zeroOrder"
    pathm1 = directory + "firstOrder"
    pathm2 = directory + "secondOrder"

    # getEfficiency(I0,I1,I2,3,0)#,540)
    getEfficiency(path1, path2, path3, 2, 1, pathm0=pathm0)  #,540)
コード例 #2
0
ファイル: test_wpg.py プロジェクト: twguest/WPG
def test_hisotry():
    import sys

    sys.path.insert(0, "..")
    import os

    import wpg
    from wpg.generators import build_gauss_wavefront
    from wpg.beamline import Beamline
    from wpg.optical_elements import Drift, Use_PP

    # from wpg.srwlib import srwl

    import numpy as np

    d2waist = 270.0
    # beam parameters:
    qnC = 0.1  # [nC] e-bunch charge
    thetaOM = 3.6e-3
    ekev = 5.0

    # calculate angular divergence:
    theta_fwhm = (17.2 - 6.4 * np.sqrt(qnC)) * 1e-6 / ekev**0.85
    theta_rms = theta_fwhm / 2.35
    sigX = 12.4e-10 / (ekev * 4 * np.pi * theta_rms)

    # define limits
    xmax = theta_rms * d2waist * 3.5
    xmin = -xmax
    ymin = xmin
    ymax = xmax
    nx = 300
    ny = nx
    nz = 3
    tau = 0.12e-15

    srw_wf = build_gauss_wavefront(nx, ny, nz, ekev, xmin, xmax, ymin, ymax,
                                   tau, sigX, sigX, d2waist)
    wf = wpg.Wavefront(srw_wf)
    b = Beamline()
    # b.append(Drift(5), Use_PP())
    # b.propagate(wf)
    # srwl.ResizeElecField(srw_wf, 'c', [0, 0.25, 1, 0.25, 1])

    out_folder = os.path.join(os.path.dirname(__file__), "tests_data")
    if not os.path.exists(out_folder):
        os.mkdir(out_folder)

    wf_hdf5_out_file_path = os.path.join(out_folder, "my_gauss_history.h5")
    wf.store_hdf5(wf_hdf5_out_file_path)

    wf.custom_fields["/history/params/beamline/printout"] = str(b)
    wf.store_hdf5(wf_hdf5_out_file_path)

    wf_out = wpg.Wavefront()
    wf_out.load_hdf5(wf_hdf5_out_file_path)
    wf_out.custom_fields["/history/params/beamline/printout"] = str(b)
    wf_out.store_hdf5(wf_hdf5_out_file_path)
    return wf
コード例 #3
0
ファイル: BeamlinesTest.py プロジェクト: samoylv/WPG
def setupTestWavefront():
    """ Utility to setup a Gaussian wavefront. Geometry corresponds to SPB-SFX Day1 configuration. """

    ### Geometry ###
    src_to_hom1 = 257.8  # Distance source to HOM 1 [m]
    src_to_hom2 = 267.8  # Distance source to HOM 2 [m]
    src_to_crl = 887.8  # Distance source to CRL [m]
    src_to_exp = 920.42  # Distance source to experiment [m]

    # Central photon energy.
    ekev = 8.4  # Energy [keV]

    # Pulse parameters.
    qnC = 0.5  # e-bunch charge, [nC]
    pulse_duration = 9.e-15  # [s]
    pulseEnergy = 1.5e-3  # total pulse energy, J

    # Coherence time
    coh_time = 0.24e-15  # [s]

    # Distance to first HOM.
    z1 = src_to_hom1

    # Angular distribution
    theta_fwhm = 2.124e-6  # Beam divergence        # From Patrick's raytrace.

    wlambda = 12.4 * 1e-10 / ekev  # wavelength [AKM]
    w0 = wlambda / (numpy.pi * theta_fwhm)  # beam waist
    zR = (numpy.pi * w0**2) / wlambda  #Rayleigh range
    fwhm_at_zR = theta_fwhm * zR  #FWHM at Rayleigh range
    sigmaAmp = w0 / (2 * numpy.sqrt(numpy.log(2)))  #sigma of amplitude

    # Number of points in each x and y dimension.
    np = 100

    bSaved = False
    dx = 10.e-6
    range_xy = dx * (np - 1)
    #print ('range_xy = ', range_xy)
    nslices = 10

    srwl_wf = build_gauss_wavefront(np,
                                    np,
                                    nslices,
                                    ekev,
                                    -range_xy / 2,
                                    range_xy / 2,
                                    -range_xy / 2,
                                    range_xy / 2,
                                    coh_time / numpy.sqrt(2),
                                    sigmaAmp,
                                    sigmaAmp,
                                    src_to_hom1,
                                    pulseEn=pulseEnergy,
                                    pulseRange=8.)

    wf = Wavefront(srwl_wf)

    wf.store_hdf5("source.h5")
コード例 #4
0
ファイル: test_wpg.py プロジェクト: twguest/WPG
def test_simple_gauusina_propagation():
    # TODO: fix propagation for coerrect results
    import sys

    sys.path.insert(0, "..")
    import os

    import wpg
    from wpg.generators import build_gauss_wavefront
    from wpg.beamline import Beamline
    from wpg.optical_elements import Drift, Use_PP
    from wpg.srwlib import srwl

    import numpy as np

    d2waist = 270.0
    # beam parameters:
    qnC = 0.1  # [nC] e-bunch charge
    thetaOM = 3.6e-3
    ekev = 5.0

    # calculate angular divergence:
    theta_fwhm = (17.2 - 6.4 * np.sqrt(qnC)) * 1e-6 / ekev**0.85
    theta_rms = theta_fwhm / 2.35
    sigX = 12.4e-10 / (ekev * 4 * np.pi * theta_rms)

    # define limits
    xmax = theta_rms * d2waist * 3.5
    xmin = -xmax
    ymin = xmin
    ymax = xmax
    nx = 300
    ny = nx
    nz = 3
    tau = 0.12e-15

    srw_wf = build_gauss_wavefront(nx, ny, nz, ekev, xmin, xmax, ymin, ymax,
                                   tau, sigX, sigX, d2waist)
    wf = wpg.Wavefront(srw_wf)
    b = Beamline()
    b.append(Drift(5), Use_PP())
    srwl.SetRepresElecField(wf._srwl_wf, "f")
    b.propagate(wf)
    srwl.SetRepresElecField(wf._srwl_wf, "c")
    srwl.ResizeElecField(srw_wf, "c", [0, 0.25, 1, 0.25, 1])

    ti = wf.get_intensity()

    out_folder = os.path.join(os.path.dirname(__file__), "tests_data")
    if not os.path.exists(out_folder):
        os.mkdir(out_folder)

    wf_hdf5_out_file_path = os.path.join(out_folder, "my_gauss.h5")
    wf.store_hdf5(wf_hdf5_out_file_path)

    wf_out = wpg.Wavefront()
    wf_out.load_hdf5(wf_hdf5_out_file_path)
    return wf
コード例 #5
0
    def backengine(self):

        # The rms of the amplitude distribution (Gaussian)
        theta = self.parameters.divergence.m_as(radian)
        E = self.parameters.photon_energy
        coherence_time = 2. * math.pi * hbar / self.parameters.photon_energy_relative_bandwidth / E.m_as(
            joule)

        beam_waist = 2. * hbar * c / theta / E.m_as(joule)
        wavelength = 1239.8e-9 / E.m_as(electronvolt)
        rayleigh_length = math.pi * beam_waist**2 / wavelength

        print(rayleigh_length)

        beam_diameter_fwhm = self.parameters.beam_diameter_fwhm.m_as(meter)
        beam_waist_radius = beam_diameter_fwhm / math.sqrt(2. * math.log(2.))

        # x-y range at beam waist.
        range_xy = 30.0 * beam_waist_radius

        # Set number of sampling points in x and y and number of temporal slices.
        np = self.parameters.number_of_transverse_grid_points
        nslices = self.parameters.number_of_time_slices

        # Distance from source position.
        z = self.parameters.z.m_as(meter)

        # Build wavefront
        srwl_wf = build_gauss_wavefront(
            np,
            np,
            nslices,
            E.m_as(electronvolt) / 1.0e3,
            -range_xy / 2,
            range_xy / 2,
            -range_xy / 2,
            range_xy / 2,
            coherence_time / math.sqrt(2),
            beam_waist_radius / 2,
            beam_waist_radius /
            2,  # Scaled such that fwhm comes out as demanded by parameters.
            d2waist=z,
            pulseEn=self.parameters.pulse_energy.m_as(joule),
            pulseRange=8.)

        # Correct radius of curvature.
        Rx = Ry = z * math.sqrt(1. + (rayleigh_length / z)**2)

        # Store on class.
        srwl_wf.Rx = Rx
        srwl_wf.Ry = Ry

        self.__wavefront = Wavefront(srwl_wf)
コード例 #6
0
def generatePulse(n = 1):

    
    wfr = Wavefront(build_gauss_wavefront(nx = 512, ny = 512, nz = 5,
                                          ekev = 4.96,
                                          xMin = -400e-06, xMax = 400e-06,
                                          yMin = -400e-06, yMax = 400e-06,
                                          tau = 1e-05,
                                          sigX = np.random.random()*125e-06, sigY = np.random.random()*125e-06,
                                          d2waist = 1))
                    
    wfr.store_hdf5("../../data/tests/pulseTests/gaussianSource/gsn_{}.h5".format(n))
コード例 #7
0
ファイル: wfStokes.py プロジェクト: JeromeKnappett/SXRL
def test():
    eMin = 10e6
    Nx = 100
    Ny = 100
    Nz = 1
    xMin = -10e-6
    xMax = 10e-6
    yMin = -10e-6
    yMax = 10e-6
    zMin = 1
    mutual = 1
    Fx = 1 / 2
    Fy = 1 / 2
    print('-----Running Test-----')
    print('-----building wavefront-----')
    w = build_gauss_wavefront(Nx, Ny, Nz, eMin / 1000, xMin, xMax, yMin, yMax,
                              1, 1e-6, 1e-6, 1)
    #build_gauss_wavefront()

    print(w)

    wf = Wavefront(srwl_wavefront=w)

    intensity = wf.get_intensity()
    plt.imshow(intensity)
    plt.title("Intensity")
    plt.show()

    print('-----Getting Stokes parameters-----')
    S, Dx, Dy = getStokes(w, mutual=mutual, Fx=Fx, Fy=Fy)
    s = getStokesParamFromStokes(S)
    _s = normaliseStoke(s)

    print("-----Plotting Stokes parameters-----")
    plotStokes(s, S, Dx=Dx, Dy=Dy)

    # print("-----Plotting normalised Stokes parameters-----")
    # plotStokes(_s,S,"_s0","_s1","_s2","_s3")

    print("-----Getting degree of coherence from Stokes parameters------")
    start1 = time.time()
    coherenceFromSTKS(S, Dx, Dy)
    end1 = time.time()
    print("Time taken to get degree of coherence from Stokes (s): {}".format(
        end1 - start1))

    print('------Done------')
コード例 #8
0
    def backengine(self):

        # The rms of the amplitude distribution (Gaussian)
        theta = self.parameters.divergence.m_as(radian)
        E = self.parameters.photon_energy
        coherence_time = 2. * math.pi * hbar / self.parameters.photon_energy_relative_bandwidth / E.m_as(
            joule)

        beam_waist = 2. * hbar * c / theta / E.m_as(joule)

        beam_diameter_fwhm = self.parameters.beam_diameter_fwhm.m_as(meter)
        beam_waist_radius = beam_diameter_fwhm / math.sqrt(2. * math.log(2.))

        print("beam waist radius from divergence angle = {0:4.3e}".format(
            beam_waist))
        print(
            "beam waist radius from fwhm = {0:4.3e}".format(beam_waist_radius))

        # Rule of thumb: 7 times w0
        # x-y range at beam waist.
        range_xy = 30.0 * beam_waist_radius

        # Set number of sampling points in x and y and number of temporal slices.
        np = self.parameters.number_of_transverse_grid_points
        nslices = self.parameters.number_of_time_slices

        # Build wavefront
        srwl_wf = build_gauss_wavefront(
            np,
            np,
            nslices,
            E.m_as(electronvolt) / 1.0e3,
            -range_xy / 2,
            range_xy / 2,
            -range_xy / 2,
            range_xy / 2,
            coherence_time / math.sqrt(2),
            # beam_diameter_fwhm, beam_diameter_fwhm,
            beam_waist_radius / 2,
            beam_waist_radius /
            2,  # Scaled such that fwhm comes out as demanded by parameters.
            0.0,
            pulseEn=self.parameters.pulse_energy.m_as(joule),
            pulseRange=8.)
        # Store on class.
        self.__wavefront = Wavefront(srwl_wf)
コード例 #9
0
ファイル: UtilitiesTest.py プロジェクト: twguest/WPG
def setup_gauss_wavefront(sanity=True):
    """ Gaussian wavefront builder """
    if sanity:
        np = 700
        nslices = 100
    else:
        np = 10
        nslices = 10

    photon_energy = 1.6e3
    theta_fwhm = 6.0e-6  ### ADJUST ME

    wlambda = 1.24 * 1e-6 / photon_energy  # wavelength [AKM]
    w0 = wlambda / (numpy.pi * theta_fwhm)  # beam waist
    zR = (numpy.pi * w0 ** 2) / wlambda  # Rayleigh range
    sigmaAmp = w0 / (2 * numpy.sqrt(numpy.log(2)))  # sigma of amplitude
    src_to_aperture_distance = 170.0
    pulse_energy = 4e-4  # [J]

    # Coherence time
    pulse_duration = 30.0e-15  # [s]
    coh_time = pulse_duration / 10.0  # estimate, [s]

    # expected beam radius at HOM1 position to get the range of the wavefront
    range_xy = w0 * numpy.sqrt(1 + (src_to_aperture_distance / zR) ** 2) * 5.5

    srwl_wf = build_gauss_wavefront(
        np,
        np,
        nslices,
        photon_energy / 1e3,
        -range_xy / 2,
        range_xy / 2,
        -range_xy / 2,
        range_xy / 2,
        coh_time / numpy.sqrt(2),
        sigmaAmp,
        sigmaAmp,
        src_to_aperture_distance,
        pulseEn=pulse_energy,
        pulseRange=8.0,
    )

    return Wavefront(srwl_wf)
コード例 #10
0
ファイル: test_gauss_store.py プロジェクト: ia-petrov/WPG
def main():
    d2waist = 270.
    # beam parameters:
    qnC = 0.1  # [nC] e-bunch charge
    thetaOM = 3.6e-3
    ekev = 5.0

    # calculate angular divergence:
    theta_fwhm = (17.2 - 6.4 * np.sqrt(qnC)) * 1e-6 / ekev**0.85
    theta_rms = theta_fwhm / 2.35
    sigX = 12.4e-10 / (ekev * 4 * np.pi * theta_rms)

    # define limits
    xmax = theta_rms * d2waist * 3.5
    xmin = -xmax
    ymin = xmin
    ymax = xmax
    nx = 600
    ny = nx
    nz = 5
    tau = 0.12e-15

    srw_wf = build_gauss_wavefront(nx, ny, nz, ekev, xmin, xmax, ymin, ymax,
                                   tau, sigX, sigX, d2waist)
    wf = wpg.Wavefront(srw_wf)
    b = Beamline()
    b.append(Drift(5), Use_PP())
    b.propagate(wf)
    # srwl.ResizeElecField(srw_wf, 'c', [0, 0.25, 1, 0.25, 1])

    if not os.path.exists('tests_data'):
        os.mkdir('tests_data')

    wf_hdf5_out_file_path = os.path.join('tests_data', 'my_gauss.h5')
    wf.store_hdf5(wf_hdf5_out_file_path)

    wf_out = wpg.Wavefront()
    wf_out.load_hdf5(wf_hdf5_out_file_path)
    return wf
コード例 #11
0
ファイル: test_gauss_store.py プロジェクト: samoylv/WPG
def main():
    d2waist = 270.
    # beam parameters:
    qnC = 0.1  # [nC] e-bunch charge
    thetaOM = 3.6e-3
    ekev = 5.0

    # calculate angular divergence:
    theta_fwhm = (17.2 - 6.4 * np.sqrt(qnC)) * 1e-6 / ekev ** 0.85
    theta_rms = theta_fwhm / 2.35
    sigX = 12.4e-10 / (ekev * 4 * np.pi * theta_rms)

    # define limits
    xmax = theta_rms * d2waist * 3.5
    xmin = - xmax
    ymin = xmin
    ymax = xmax
    nx = 600
    ny = nx
    nz = 5
    tau = 0.12e-15

    srw_wf = build_gauss_wavefront(
        nx, ny, nz, ekev, xmin, xmax, ymin, ymax, tau, sigX, sigX, d2waist)
    wf = wpg.Wavefront(srw_wf)  
    b = Beamline()
    b.append(Drift(5), Use_PP())
    b.propagate(wf)
    # srwl.ResizeElecField(srw_wf, 'c', [0, 0.25, 1, 0.25, 1])

    if not os.path.exists('tests_data'):
        os.mkdir('tests_data')

    wf_hdf5_out_file_path = os.path.join('tests_data', 'my_gauss.h5')
    wf.store_hdf5(wf_hdf5_out_file_path)

    wf_out = wpg.Wavefront()
    wf_out.load_hdf5(wf_hdf5_out_file_path)
    return wf
コード例 #12
0
def test():
    eMin = 10e6
    Nx = 150
    Ny = 150
    Nz = 1
    xMin = -10e-6
    xMax = 10e-6
    yMin = -10e-6
    yMax = 10e-6
    zMin = 100
    Fx = 1/2
    Fy = 1/2
    print('Running Test:')
    print('building wavefront...')
    w = build_gauss_wavefront(Nx,Ny,Nz,eMin/1000,xMin,xMax,yMin,yMax,1,1e-6,1e-6,1) 
    
    wf0 = Wavefront(srwl_wavefront=w)
    
    wf = wf0.toComplex()
    
    # g = build_gauss_wavefront(Nx,Ny,Nz, eMin/1000,xMin,xMax,yMin,yMax,1,2e-6,2e-6,1)
    
    # gf0 = Wavefront(srwl_wavefront=g)    
    # gf = gf0.toComplex()
    
    # COH = getCoherence(wf0)
    # C = abs(COH)
    
    # print(C)
    # plt.imshow(C)
    # plt.colorbar()
    # plt.show()
    
    B, Dx , Dy = Coherence(wf0,Fx,Fy)
    plotCoherence(B,Dx,Dy)
    coherenceProfiles(wf0,Fx,Fy)
コード例 #13
0
    def testGaussianReference(self, debug=False):
        """ Check that propagation of a Gaussian pulse (in t,x,y) through vacuum reproduces reference data. """


        # Central photon energy.
        ekev = 8.4 # Energy [keV]

        # Pulse parameters.
        qnC = 0.5               # e-bunch charge, [nC]
        pulse_duration = 9.0e-15 # [s]
        pulseEnergy = 1.5e-3    # total pulse energy, J

        # Coherence time
        coh_time = 0.25e-15 # [s]

        # Distance in free space.
        z0 = 10. # (m), position where to build the wavefront.
        z1 = 10. # (m), distance to travel in free space.

        # Beam divergence.
        theta_fwhm = 2.5e-6 # rad

        wlambda = 12.4*1e-10/ekev # wavelength, m
        w0 = wlambda/(numpy.pi*theta_fwhm) # beam waist, m
        zR = (math.pi*w0**2)/wlambda #Rayleigh range, m
        fwhm_at_zR = theta_fwhm*zR #FWHM at Rayleigh range, m
        sigmaAmp = w0/(2.0*math.sqrt(math.log(2.0))) #sigma of amplitude, m

        if debug:
            print (" *** Pulse properties ***")
            print (" lambda = %4.3e m" % (wlambda) )
            print (" w0 = %4.3e m" % (w0) )
            print (" zR = %4.3e m" % (zR) )
            print (" fwhm at zR = %4.3e m" % (fwhm_at_zR) )
            print (" sigma = %4.3e m" % (sigmaAmp) )

        # expected beam radius after free space drift.
        expected_beam_radius = w0*math.sqrt(1.0+(z0/zR)**2)


        # Number of points in each x and y dimension.
        np=400

        # Sampling window = 6 sigma of initial beam.
        range_xy = 6.*expected_beam_radius
        dx = range_xy / (np-1)
        nslices = 20

        if debug:
            print (" Expected beam waist at z=%4.3f m : %4.3e m." % (z0, expected_beam_radius) )
            print ("Setting up mesh of %d points per dimension on a %4.3e x %4.3e m^2 grid with grid spacing %4.3e m." % (np, range_xy, range_xy, dx) )

        # Construct srw wavefront.
        srwl_wf = build_gauss_wavefront(np, np, nslices, ekev, -range_xy/2., range_xy/2.,
                                        -range_xy/2., range_xy/2., coh_time/math.sqrt(2.),
                                        sigmaAmp, sigmaAmp, z0,
                                        pulseEn=pulseEnergy, pulseRange=8.)

        # Convert to wpg.
        wf = Wavefront(srwl_wf)

        if debug:
            print('*** z=%4.3e m ***' % (z0))
            fwhm = calculate_fwhm(wf)
            print('fwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            look_at_q_space(wf)

        # Construct the beamline.
        beamline = Beamline()

        # Add free space drift.
        drift = Drift(z1)
        beamline.append( drift, Use_PP(semi_analytical_treatment=1))

        # Propagate
        srwl.SetRepresElecField(wf._srwl_wf, 'f') # <---- switch to frequency domain
        beamline.propagate(wf)
        srwl.SetRepresElecField(wf._srwl_wf, 't')

        if debug:
            print('*** z=%4.3e m ***' % (z0+z1))
            fwhm = calculate_fwhm(wf)
            print('fwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            look_at_q_space(wf)


        # Get propagated wavefront data.
        wf_intensity = wf.get_intensity()

        # Project on t axis.
        wf_onaxis = wf_intensity.sum(axis=(0,1))

        # Get hash of the data.
        wf_hash = hash( wf_intensity.tostring() )

        # Load reference hash.
        with open(TestUtilities.generateTestFilePath("reference_wf_gauss_10m.hash.txt"), 'r') as hashfile:
            ref_hash = hashfile.readline()
            hashfile.close()
        ref_onaxis = numpy.loadtxt(TestUtilities.generateTestFilePath("reference_wf_gauss_onaxis_10m.txt"))

        # Weak test.
        for x,y in zip(wf_onaxis, ref_onaxis):
            self.assertAlmostEqual( x, y, 14 )

        # Strong test.
        self.assertEqual( str(wf_hash), ref_hash)
コード例 #14
0
    def testGaussianVsAnalytic(self, debug=False):
        """ Check that propagation of a Gaussian pulse (in t,x,y) through vacuum gives the correct result, compare
        to analytic solution. """


        # Central photon energy.
        ekev = 8.4 # Energy [keV]

        # Pulse parameters.
        qnC = 0.5               # e-bunch charge, [nC]
        pulse_duration = 9.0e-15 # [s]
        pulseEnergy = 1.5e-3    # total pulse energy, J

        # Coherence time
        coh_time = 0.25e-15 # [s]

        # Distance in free space.
        z0 = 10. # (m), position where to build the wavefront.
        z1 = 20. # (m), distance to travel in free space.
        z2 = z0 + z1 #  distance where to build the reference wavefront.

        # Beam divergence.
        theta_fwhm = 2.5e-6 # rad

        wlambda = 12.4*1e-10/ekev # wavelength, m
        w0 = wlambda/(numpy.pi*theta_fwhm) # beam waist, m
        zR = (math.pi*w0**2)/wlambda #Rayleigh range, m
        fwhm_at_zR = theta_fwhm*zR #FWHM at Rayleigh range, m
        sigmaAmp = w0/(2.0*math.sqrt(math.log(2.0))) #sigma of amplitude, m

        if debug:
            print (" *** Pulse properties ***")
            print (" lambda = %4.3e m" % (wlambda) )
            print (" w0 = %4.3e m" % (w0) )
            print (" zR = %4.3e m" % (zR) )
            print (" fwhm at zR = %4.3e m" % (fwhm_at_zR) )
            print (" sigma = %4.3e m" % (sigmaAmp) )

        # expected beam radius after free space drift.
        expected_beam_radius = w0*math.sqrt(1.0+(z0/zR)**2)

        # Number of points in each x and y dimension.
        np=600

        # Sampling window = 6 sigma of initial beam.
        range_xy = 6.*expected_beam_radius
        dx = range_xy / (np-1)
        nslices = 20

        #if debug:
            #print (" Expected beam waist at z=%4.3f m : %4.3e m." % (z0, expected_beam_radius) )
            #print ("Setting up mesh of %d points per dimension on a %4.3e x %4.3e m^2 grid with grid spacing %4.3e m." % (np, range_xy, range_xy, dx) )

        # Construct srw wavefront.
        srwl_wf = build_gauss_wavefront(np, np, nslices, ekev, -range_xy/2., range_xy/2.,
                                        -range_xy/2., range_xy/2., coh_time/math.sqrt(2.),
                                        sigmaAmp, sigmaAmp, z0,
                                        pulseEn=pulseEnergy, pulseRange=8.)

        # Convert to wpg.
        wf = Wavefront(srwl_wf)

        # Construct reference srw wavefront.
        reference_srwl_wf = build_gauss_wavefront(np, np, nslices, ekev, -1.5*range_xy/2., 1.5*range_xy/2.,
                                        -1.5*range_xy/2., 1.5*range_xy/2., coh_time/math.sqrt(2.),
                                        sigmaAmp, sigmaAmp, z2,
                                        pulseEn=pulseEnergy, pulseRange=8.)

        reference_wf = Wavefront(reference_srwl_wf)

        if debug:
            print('*** z=%4.3e m ***' % (z0))
            fwhm = calculate_fwhm(wf)
            print('wf:\nfwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            #look_at_q_space(wf)

        # Construct the beamline.
        beamline = Beamline()

        # Add free space drift.
        drift = Drift(z1)
        beamline.append( drift, Use_PP(semi_analytical_treatment=0, zoom=2.0, sampling=0.5))

        # Propagate
        srwl.SetRepresElecField(wf._srwl_wf, 'f')
        beamline.propagate(wf)
        srwl.SetRepresElecField(wf._srwl_wf, 't')

        fwhm = calculate_fwhm(wf)
        reference_fwhm = calculate_fwhm(reference_wf)
        if debug:
            print('*** z=%4.3e m ***' % (z0+z1))
            print('wf :\nfwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            print('ref:\nfwhm_x = %4.3e\nfwhm_y = %4.3e' % (reference_fwhm['fwhm_x'], reference_fwhm['fwhm_y']) )
            plot_t_wf(reference_wf)
            #look_at_q_space(wf)

        # Calculate difference
        reference_norm = numpy.linalg.norm(numpy.array([reference_fwhm['fwhm_x'], reference_fwhm['fwhm_y']]))
        difference_norm = numpy.linalg.norm(numpy.array([fwhm['fwhm_x'], fwhm['fwhm_y']]) - numpy.array([reference_fwhm['fwhm_x'], reference_fwhm['fwhm_y']]))

        if debug:
            print ("|ref_fwhm_xy| = %4.3e" % (reference_norm) )
            print ("|ref_fwhm_xy - fhwm_xy| = %4.3e" % (difference_norm) )

        self.assertLess(difference_norm / reference_norm, 0.01)
コード例 #15
0
    def testGaussianReference(self, debug=False):
        """ Check that propagation of a Gaussian pulse (in t,x,y) through vacuum reproduces reference data. """


        # Central photon energy.
        ekev = 8.4 # Energy [keV]

        # Pulse parameters.
        qnC = 0.5               # e-bunch charge, [nC]
        pulse_duration = 9.0e-15 # [s]
        pulseEnergy = 1.5e-3    # total pulse energy, J

        # Coherence time
        coh_time = 0.25e-15 # [s]

        # Distance in free space.
        z0 = 10. # (m), position where to build the wavefront.
        z1 = 10. # (m), distance to travel in free space.

        # Beam divergence.
        theta_fwhm = 2.5e-6 # rad

        wlambda = 12.4*1e-10/ekev # wavelength, m
        w0 = wlambda/(numpy.pi*theta_fwhm) # beam waist, m
        zR = (math.pi*w0**2)/wlambda #Rayleigh range, m
        fwhm_at_zR = theta_fwhm*zR #FWHM at Rayleigh range, m
        sigmaAmp = w0/(2.0*math.sqrt(math.log(2.0))) #sigma of amplitude, m

        if debug:
            print (" *** Pulse properties ***")
            print (" lambda = %4.3e m" % (wlambda) )
            print (" w0 = %4.3e m" % (w0) )
            print (" zR = %4.3e m" % (zR) )
            print (" fwhm at zR = %4.3e m" % (fwhm_at_zR) )
            print (" sigma = %4.3e m" % (sigmaAmp) )

        # expected beam radius after free space drift.
        expected_beam_radius = w0*math.sqrt(1.0+(z0/zR)**2)


        # Number of points in each x and y dimension.
        np=400

        # Sampling window = 6 sigma of initial beam.
        range_xy = 6.*expected_beam_radius
        dx = range_xy / (np-1)
        nslices = 20

        if debug:
            print (" Expected beam waist at z=%4.3f m : %4.3e m." % (z0, expected_beam_radius) )
            print ("Setting up mesh of %d points per dimension on a %4.3e x %4.3e m^2 grid with grid spacing %4.3e m." % (np, range_xy, range_xy, dx) )

        # Construct srw wavefront.
        srwl_wf = build_gauss_wavefront(np, np, nslices, ekev, -range_xy/2., range_xy/2.,
                                        -range_xy/2., range_xy/2., coh_time/math.sqrt(2.),
                                        sigmaAmp, sigmaAmp, z0,
                                        pulseEn=pulseEnergy, pulseRange=8.)

        # Convert to wpg.
        wf = Wavefront(srwl_wf)

        if debug:
            print('*** z=%4.3e m ***' % (z0))
            fwhm = calculate_fwhm(wf)
            print('fwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            look_at_q_space(wf)

        # Construct the beamline.
        beamline = Beamline()

        # Add free space drift.
        drift = Drift(z1)
        beamline.append( drift, Use_PP(semi_analytical_treatment=1))

        # Propagate
        srwl.SetRepresElecField(wf._srwl_wf, 'f') # <---- switch to frequency domain
        beamline.propagate(wf)
        srwl.SetRepresElecField(wf._srwl_wf, 't')

        if debug:
            print('*** z=%4.3e m ***' % (z0+z1))
            fwhm = calculate_fwhm(wf)
            print('fwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            look_at_q_space(wf)


        # Get propagated wavefront data.
        wf_intensity = wf.get_intensity()

        # Project on t axis.
        wf_onaxis = wf_intensity.sum(axis=(0,1))

        # Get hash of the data.
        wf_hash = hash( wf_intensity.tostring() )

        # Load reference hash.
        with open(TestUtilities.generateTestFilePath("reference_wf_gauss_10m.hash.txt"), 'r') as hashfile:
            ref_hash = hashfile.readline()
            hashfile.close()
        ref_onaxis = numpy.loadtxt(TestUtilities.generateTestFilePath("reference_wf_gauss_onaxis_10m.txt"))

        # Weak test.
        for x,y in zip(wf_onaxis, ref_onaxis):
            self.assertAlmostEqual( x, y, 14 )

        # Strong test.
        self.assertEqual( str(wf_hash), ref_hash)
コード例 #16
0
    def testGaussianVsAnalytic(self, debug=False):
        """ Check that propagation of a Gaussian pulse (in t,x,y) through vacuum gives the correct result, compare
        to analytic solution. """


        # Central photon energy.
        ekev = 8.4 # Energy [keV]

        # Pulse parameters.
        qnC = 0.5               # e-bunch charge, [nC]
        pulse_duration = 9.0e-15 # [s]
        pulseEnergy = 1.5e-3    # total pulse energy, J

        # Coherence time
        coh_time = 0.25e-15 # [s]

        # Distance in free space.
        z0 = 10. # (m), position where to build the wavefront.
        z1 = 20. # (m), distance to travel in free space.
        z2 = z0 + z1 #  distance where to build the reference wavefront.

        # Beam divergence.
        theta_fwhm = 2.5e-6 # rad

        wlambda = 12.4*1e-10/ekev # wavelength, m
        w0 = wlambda/(numpy.pi*theta_fwhm) # beam waist, m
        zR = (math.pi*w0**2)/wlambda #Rayleigh range, m
        fwhm_at_zR = theta_fwhm*zR #FWHM at Rayleigh range, m
        sigmaAmp = w0/(2.0*math.sqrt(math.log(2.0))) #sigma of amplitude, m

        if debug:
            print (" *** Pulse properties ***")
            print (" lambda = %4.3e m" % (wlambda) )
            print (" w0 = %4.3e m" % (w0) )
            print (" zR = %4.3e m" % (zR) )
            print (" fwhm at zR = %4.3e m" % (fwhm_at_zR) )
            print (" sigma = %4.3e m" % (sigmaAmp) )

        # expected beam radius after free space drift.
        expected_beam_radius = w0*math.sqrt(1.0+(z0/zR)**2)

        # Number of points in each x and y dimension.
        np=600

        # Sampling window = 6 sigma of initial beam.
        range_xy = 6.*expected_beam_radius
        dx = range_xy / (np-1)
        nslices = 20

        #if debug:
            #print (" Expected beam waist at z=%4.3f m : %4.3e m." % (z0, expected_beam_radius) )
            #print ("Setting up mesh of %d points per dimension on a %4.3e x %4.3e m^2 grid with grid spacing %4.3e m." % (np, range_xy, range_xy, dx) )

        # Construct srw wavefront.
        srwl_wf = build_gauss_wavefront(np, np, nslices, ekev, -range_xy/2., range_xy/2.,
                                        -range_xy/2., range_xy/2., coh_time/math.sqrt(2.),
                                        sigmaAmp, sigmaAmp, z0,
                                        pulseEn=pulseEnergy, pulseRange=8.)

        # Convert to wpg.
        wf = Wavefront(srwl_wf)

        # Construct reference srw wavefront.
        reference_srwl_wf = build_gauss_wavefront(np, np, nslices, ekev, -1.5*range_xy/2., 1.5*range_xy/2.,
                                        -1.5*range_xy/2., 1.5*range_xy/2., coh_time/math.sqrt(2.),
                                        sigmaAmp, sigmaAmp, z2,
                                        pulseEn=pulseEnergy, pulseRange=8.)

        reference_wf = Wavefront(reference_srwl_wf)

        if debug:
            print('*** z=%4.3e m ***' % (z0))
            fwhm = calculate_fwhm(wf)
            print('wf:\nfwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            #look_at_q_space(wf)

        # Construct the beamline.
        beamline = Beamline()

        # Add free space drift.
        drift = Drift(z1)
        beamline.append( drift, Use_PP(semi_analytical_treatment=0, zoom=2.0, sampling=0.5))

        # Propagate
        srwl.SetRepresElecField(wf._srwl_wf, 'f')
        beamline.propagate(wf)
        srwl.SetRepresElecField(wf._srwl_wf, 't')

        fwhm = calculate_fwhm(wf)
        reference_fwhm = calculate_fwhm(reference_wf)
        if debug:
            print('*** z=%4.3e m ***' % (z0+z1))
            print('wf :\nfwhm_x = %4.3e\nfwhm_y = %4.3e' % (fwhm['fwhm_x'], fwhm['fwhm_y']) )
            plot_t_wf(wf)
            print('ref:\nfwhm_x = %4.3e\nfwhm_y = %4.3e' % (reference_fwhm['fwhm_x'], reference_fwhm['fwhm_y']) )
            plot_t_wf(reference_wf)
            #look_at_q_space(wf)

        # Calculate difference
        reference_norm = numpy.linalg.norm(numpy.array([reference_fwhm['fwhm_x'], reference_fwhm['fwhm_y']]))
        difference_norm = numpy.linalg.norm(numpy.array([fwhm['fwhm_x'], fwhm['fwhm_y']]) - numpy.array([reference_fwhm['fwhm_x'], reference_fwhm['fwhm_y']]))

        if debug:
            print ("|ref_fwhm_xy| = %4.3e" % (reference_norm) )
            print ("|ref_fwhm_xy - fhwm_xy| = %4.3e" % (difference_norm) )

        self.assertLess(difference_norm / reference_norm, 0.01)
コード例 #17
0
def constructPulse():
    
    wfr = Wavefront(build_gauss_wavefront(512, 512, 10, 5.0, -400e-06, 400e-06, -400e-06, 400e-06, 1e-15, 5e-06, 5e-06, 19))
    srwlib.srwl.SetRepresElecField(wfr._srwl_wf, 'f')
    #look_at_q_space(wfr)
    return wfr
コード例 #18
0
    def backengine(self):

        # check for WPG first
        if not WPG_AVAILABLE:
            raise ModuleNotFoundError(
                'Cannot find the "WPG" module, which is required to run '
                "GaussianSourceCalculator.backengine(). Is it included in PYTHONPATH?"
            )

        # The rms of the amplitude distribution (Gaussian)
        theta = self.parameters["divergence"].value_no_conversion.to(
            "radian").magnitude
        E_joule = (self.parameters["photon_energy"].value_no_conversion.to(
            "joule").magnitude)
        E_eV = self.parameters["photon_energy"].value_no_conversion.to(
            "eV").magnitude
        relative_bandwidth = self.parameters[
            "photon_energy_relative_bandwidth"].value
        coherence_time = 2.0 * np.pi * hbar / relative_bandwidth / E_joule
        pulse_energy = self.parameters["pulse_energy"].value_no_conversion

        beam_waist = 2.0 * hbar * c / theta / E_joule
        wavelength = 1239.8e-9 / E_eV
        rayleigh_length = np.pi * beam_waist**2 / wavelength

        logger.info(f"rayleigh_length = {rayleigh_length}")

        beam_diameter_fwhm = (self.parameters["beam_diameter_fwhm"].
                              value_no_conversion.to("meter").magnitude)
        beam_waist_radius = beam_diameter_fwhm / np.sqrt(2.0 * np.log(2.0))

        # x-y range at beam waist.
        range_xy = 30.0 * beam_waist_radius

        # Set number of sampling points in x and y and number of temporal slices.
        npoints = self.parameters["number_of_transverse_grid_points"].value
        nslices = self.parameters["number_of_time_slices"].value

        # Distance from source position.
        z = self.parameters["z"].value_no_conversion.to("meter").magnitude

        # Build wavefront
        srwl_wf = build_gauss_wavefront(
            npoints,
            npoints,
            nslices,
            E_eV / 1.0e3,
            -range_xy / 2,
            range_xy / 2,
            -range_xy / 2,
            range_xy / 2,
            coherence_time / np.sqrt(2),
            beam_waist_radius / 2,
            beam_waist_radius /
            2,  # Scaled such that fwhm comes out as demanded by parameters.
            d2waist=z,
            pulseEn=pulse_energy.to("joule").magnitude,
            pulseRange=8.0,
        )

        # Correct radius of curvature.
        Rx = Ry = z * np.sqrt(1.0 + (rayleigh_length / z)**2)

        # Store on class.
        srwl_wf.Rx = Rx
        srwl_wf.Ry = Ry

        key = self.output_keys[0]
        filename = self.output_file_paths[0]
        output_data = self.output[key]

        wavefront = Wavefront(srwl_wf)
        wavefront.store_hdf5(filename)

        output_data.set_file(filename, WPGFormat)

        return self.output
コード例 #19
0
    qnC = 0.1  # [nC] e-bunch charge
    thetaOM = 3.6e-3
    ekev = 5.0

    # calculate angular divergence:
    theta_fwhm = (17.2 - 6.4 * np.sqrt(qnC)) * 1e-6 / ekev ** 0.85
    theta_rms = theta_fwhm / 2.35
    sigX = 12.4e-10 / (ekev * 4 * np.pi * theta_rms)

    # define limits
    xmax = theta_rms * d2waist * 3.5
    xmin = - xmax
    ymin = xmin
    ymax = xmax
    nx = 600
    ny = nx
    nz = 5
    tau = 0.12e-15

    srw_wf = build_gauss_wavefront(
        nx, ny, nz, ekev, xmin, xmax, ymin, ymax, tau, sigX, sigX, d2waist)
    wf = wpg.Wavefront(srw_wf)

    if not os.path.exists('tests_data'):
        os.mkdir('tests_data')

    wf_hdf5_out_file_path = os.path.join('tests_data', 'my_gauss.h5')
    wf.store_hdf5(wf_hdf5_out_file_path)

    wf_out = wpg.Wavefront()
    wf_out.load_hdf5(wf_hdf5_out_file_path)