Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
def propagate_NVE():
            
    wfr_directory = sys.argv[1].replace("*", "/")
 
    job_name = "NKB_4980eV_250pC_NVE_to_EHC"
    python_command = propagate_NVE
    input_directory = dCache + "/NanoKB-Pulse/NVE/"
    
    save_directory = input_directory.replace("/NVE/", "/EHC/")
    mkdir_p(save_directory)
    
    log_directory = logs
    
    focus = "nano"
    analysis = False
    
    filename = __file__
    dt = datetime.now().__str__()
    function = python_command.__name__
    
    description = "Propagate NanoKB Pulses 4.98 keV, 250 pC from Undulator NVE mirror to the EHC Screen"
    
    append = None
    
    print("info")
    print("wavefront directory: {}".format(wfr_directory))
    print("save directory: {}".format(save_directory))
    print("focus (i.e. beamline option): {}".format(focus))
    print("analysis: {}".format(analysis))
    print("datetime: {}".format(dt))
    print("filename: {}".format(filename))
    print("function: {}".format(function))
    print("description: {}".format(description))
    
  
    wfr = Wavefront()
    wfr.load_hdf5(wfr_directory)
     
    bl = Beamline()
    bl.append(Drift(2.2+3.5), propagation_parameters(1/3,1,1/3,1,'quadratic'))
    bl.propagate(wfr)
    
    wfr.custom_fields['focus'] = focus
    wfr.custom_fields['job name'] = job_name
    wfr.custom_fields['input directory'] = wfr_directory
    wfr.custom_fields['datetime'] = dt
    wfr.custom_fields['function'] = function
    wfr.custom_fields['filename'] = filename
    wfr.custom_fields['description'] = description
    #wfr.custom_fields['bl'] = bl.__str__
                
    if analysis: 
        wfr.analysis()
        
    wfr.store_hdf5(wfr_directory.replace("/NVE/", "/EHC/"))
Ejemplo n.º 3
0
 def detect(self, wfr):
     
     xMin, xMax, yMax, yMin = wfr.get_limits()
     
     idx, idy = xMax-xMin, yMax-yMin
     inx, iny = wfr.params.Mesh.nx, wfr.params.Mesh.ny
     print(idx,idy)
     print((self.dy*self.ny)/idy)
     bl = Beamline()
     bl.append(Drift(0),
               propagation_parameters((self.dx*self.nx)/idx, self.nx/inx, (self.dy*self.ny)/idy, self.ny/iny))
 
     bl.propagate(wfr)
Ejemplo n.º 4
0
    def detect(self, wfr):
        """
        return the detected intensity distribution
        """

        bl = Beamline()
        bl.append(
            Drift(0),
            propagation_parameters(self.mesh.dx / wfr.dx, 1,
                                   self.mesh.dy / wfr.dy, 1))
        bl.propagate(wfr)

        ii = wfr.get_intensity().sum(-1)
        ii = compress_and_average(ii, (self.mesh.nx, self.mesh.ny))

        return ii
Ejemplo n.º 5
0
def modify_beam_divergence(wfr, sig, dtheta):
    """
    Construct a thin-lens with a focal length defined by a desired divergence,
    see: thin_lens_mod, and then propagate to 2f

    :param wfr: WPG wfr structure
    :params sig: beam fwhm [m]
    :params dtheta: pulse divergence [rad]
    """
    f = sig/(np.tan(dtheta))

    tl = thinLens(f,f)
    bl = Beamline()
    bl.append(tl, [0,0,0,0,0,1,1,1,1,0,0,0])
    bl.append(Drift(2*f), [0,0,0,0,0,1,1,1,1,0,0,0])
    bl.propagate(wfr)

    wfr.params.Mesh.zCoord = 0
Ejemplo n.º 6
0
    def do_wpg_calculation(self):
        rMinCRL = 2 * self.delta * self.input_data.get_distance_to_previous(
        ) / self.nCRL  #CRL radius at the tip of parabola [m]

        opCRL = create_CRL_from_file(self.working_directory, self.file_name, 3,
                                     self.delta, self.attenLen, 1,
                                     self.diamCRL, self.diamCRL, rMinCRL,
                                     self.nCRL, self.wallThickCRL, 0, 0, None)

        wavefront = self.input_data.get_wavefront()

        beamline_for_propagation = Beamline()
        beamline_for_propagation.append(opCRL, Use_PP())
        beamline_for_propagation.append(Drift(self.distance),
                                        Use_PP(semi_analytical_treatment=1))

        beamline_for_propagation.propagate(wavefront)

        return wavefront
Ejemplo n.º 7
0
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
Ejemplo n.º 8
0
def get_beamline():
    import os
    import wpg
    from wpg import Beamline
    from wpg.optical_elements import Aperture, Drift, CRL, Empty, Use_PP, WF_dist, calculateOPD

    wpg_path = os.path.abspath(os.path.dirname(wpg.__file__))

    # S1 beamline layout
    # 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]

    # Drift to focus aperture
    # crl_to_exp_drift = Drift( src_to_exp - src_to_crl )
    z = 34.0
    # define distances, angles, etc
    # ...
    # Incidence angle at HOM

    # should be checked for other beams !!!

    theta_om = 3.6e-3  # [rad]

    om_mirror_length = 0.8  # [m]
    om_clear_ap = om_mirror_length * theta_om

    # define the beamline:
    bl0 = Beamline()
    zoom = 1

    # Define HOM1.
    aperture_x_to_y_ratio = 1
    hom1 = Aperture(shape='r',
                    ap_or_ob='a',
                    Dx=om_clear_ap,
                    Dy=om_clear_ap / aperture_x_to_y_ratio)
    bl0.append(hom1,
               Use_PP(semi_analytical_treatment=0, zoom=zoom, sampling=zoom))

    # Define mirror profile
    hom1_wavefront_distortion = WF_dist(nx=1500,
                                        ny=100,
                                        Dx=om_clear_ap,
                                        Dy=om_clear_ap / aperture_x_to_y_ratio)
    # Apply distortion.
    mirrors_path = os.path.join(wpg_path, '..', 'samples', 'data_common')
    hom1_wavefront_distortion = calculateOPD(wf_dist=hom1_wavefront_distortion,
                                             mdatafile=os.path.join(
                                                 mirrors_path, 'mirror1.dat'),
                                             ncol=2,
                                             delim=' ',
                                             Orient='x',
                                             theta=theta_om,
                                             scale=1.,
                                             stretching=1.)
    bl0.append(hom1_wavefront_distortion,
               Use_PP(semi_analytical_treatment=0, zoom=zoom, sampling=zoom))

    # Free space propagation from hom1 to hom2
    hom1_to_hom2_drift = Drift(src_to_hom2 - src_to_hom1)
    bl0.append(hom1_to_hom2_drift, Use_PP(semi_analytical_treatment=0))

    # Define HOM2.
    zoom = 1.0
    hom2 = Aperture('r', 'a', om_clear_ap, om_clear_ap / aperture_x_to_y_ratio)
    bl0.append(
        hom2,
        Use_PP(semi_analytical_treatment=0, zoom=zoom, sampling=zoom / 0.75))

    # define mirror 2
    # nx, ny from tutorial #3 (new).
    hom2_wavefront_distortion = WF_dist(nx=1500,
                                        ny=100,
                                        Dx=om_clear_ap,
                                        Dy=om_clear_ap / aperture_x_to_y_ratio)
    # Apply distortion.
    hom2_wavefront_distortion = calculateOPD(wf_dist=hom2_wavefront_distortion,
                                             mdatafile=os.path.join(
                                                 mirrors_path, 'mirror2.dat'),
                                             ncol=2,
                                             delim=' ',
                                             Orient='x',
                                             theta=theta_om,
                                             scale=1.,
                                             stretching=1.)

    bl0.append(hom2_wavefront_distortion,
               Use_PP(semi_analytical_treatment=0, zoom=zoom, sampling=zoom))

    # drift to CRL aperture
    hom2_to_crl_drift = Drift(src_to_crl - src_to_hom2)

    bl0.append(hom2_to_crl_drift, Use_PP(semi_analytical_treatment=1))

    # Define CRL
    crl_focussing_plane = 3  # Both horizontal and vertical.
    # Refractive index decrement (n = 1- delta - i*beta)
    crl_delta = 4.7177e-06
    crl_attenuation_length = 6.3e-3  # Attenuation length [m], Henke data.
    crl_shape = 1  # Parabolic lenses
    crl_aperture = 5.0e-3  # [m]
    crl_curvature_radius = 5.8e-3  # [m]
    crl_number_of_lenses = 19
    crl_wall_thickness = 8.0e-5  # Thickness
    crl_center_horizontal_coordinate = 0.0
    crl_center_vertical_coordinate = 0.0
    crl_initial_photon_energy = 8.48e3  # [eV] ### OK ???
    crl_final_photon_energy = 8.52e3  # [eV]   ### OK ???

    crl = CRL(
        _foc_plane=crl_focussing_plane,
        _delta=crl_delta,
        _atten_len=crl_attenuation_length,
        _shape=crl_shape,
        _apert_h=crl_aperture,
        _apert_v=crl_aperture,
        _r_min=crl_curvature_radius,
        _n=crl_number_of_lenses,
        _wall_thick=crl_wall_thickness,
        _xc=crl_center_horizontal_coordinate,
        _yc=crl_center_vertical_coordinate,
        _void_cen_rad=None,
        _e_start=crl_initial_photon_energy,
        _e_fin=crl_final_photon_energy,
    )
    zoom = 0.6

    bl0.append(
        crl, Use_PP(semi_analytical_treatment=1,
                    zoom=zoom,
                    sampling=zoom / 0.1))

    crl_to_exp_drift = Drift(z)
    bl0.append(crl_to_exp_drift,
               Use_PP(semi_analytical_treatment=1, zoom=1, sampling=1))
    #     bl0.append(Empty(),Use_PP(zoom=0.25, sampling=0.25))

    return bl0
Ejemplo n.º 9
0
ny = 25

plt.imshow(create_mask(nx, ny))
wfr = construct_SA1_wavefront(512, 512, 5, .8, mx=0, xoff=0, tiltX=0)

period = nx * wfr.get_spatial_resolution()[0] * (512 / (nx))
print(period)
wav = wfr.get_wavelength()

d = (2 * period**2) / wav

arr = create_mask(nx, ny)
np.save("/opt/arr", arr)
im = Image.fromarray(arr)
im = im.convert('RGB')
im.save("/opt/arr.png")

obj = srwloptT("/opt/arr.png",
               wfr.get_spatial_resolution()[0] * (512 / 75),
               wfr.get_spatial_resolution()[1] * (512 / 75),
               1e-06,
               1e-8,
               atten_len=1e-08)

bl = Beamline()
bl.append(Drift(50), propagation_parameters(1, 1, 1, 1, mode='quadratic'))
bl.append(obj, propagation_parameters(1, 1, 1, 1))
bl.append(Drift(d),
          propagation_parameters(1 / 3, 4, 1 / 3, 4, mode='fraunhofer'))
bl.propagate(wfr)
plot_intensity_map(wfr)
Ejemplo n.º 10
0
def get_beamline():
    from wpg import Beamline
    from wpg.optical_elements import Aperture, Drift, CRL, Empty, Use_PP

    # S1 beamline layout
    ### 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]
    z0 = src_to_hom1

    # Drift to focus aperture
    # crl_to_exp_drift = Drift( src_to_exp - src_to_crl )
    z = 34.0
    # define distances, angles, etc
    # ...
    # Incidence angle at HOM
    theta_om = 3.6e-3  # [rad]

    om_mirror_length = 0.8  # [m]
    om_clear_ap = om_mirror_length * theta_om

    # define the beamline:
    bl0 = Beamline()
    zoom = 1

    # Define HOM1.
    aperture_x_to_y_ratio = 1
    hom1 = Aperture(shape="r",
                    ap_or_ob="a",
                    Dx=om_clear_ap,
                    Dy=om_clear_ap / aperture_x_to_y_ratio)
    bl0.append(hom1,
               Use_PP(semi_analytical_treatment=0, zoom=zoom, sampling=zoom))

    # Free space propagation from hom1 to hom2
    hom1_to_hom2_drift = Drift(src_to_hom2 - src_to_hom1)
    z0 = z0 + (src_to_hom2 - src_to_hom1)
    bl0.append(hom1_to_hom2_drift, Use_PP(semi_analytical_treatment=0))

    # Define HOM2.
    zoom = 1.0
    hom2 = Aperture("r", "a", om_clear_ap, om_clear_ap / aperture_x_to_y_ratio)
    bl0.append(
        hom2,
        Use_PP(semi_analytical_treatment=0, zoom=zoom, sampling=zoom / 0.75))

    # drift to CRL aperture
    hom2_to_crl_drift = Drift(src_to_crl - src_to_hom2)
    z0 = z0 + (src_to_crl - src_to_hom2)
    # bl0.append( hom2_to_crl_drift, Use_PP(semi_analytical_treatment=0))
    bl0.append(hom2_to_crl_drift, Use_PP(semi_analytical_treatment=1))

    # Define CRL
    crl_focussing_plane = 3  # Both horizontal and vertical.
    crl_delta = 4.7177e-06  # Refractive index decrement (n = 1- delta - i*beta)
    crl_attenuation_length = 6.3e-3  # Attenuation length [m], Henke data.
    crl_shape = 1  # Parabolic lenses
    crl_aperture = 5.0e-3  # [m]
    crl_curvature_radius = 5.8e-3  # [m]
    crl_number_of_lenses = 19
    crl_wall_thickness = 8.0e-5  # Thickness
    crl_center_horizontal_coordinate = 0.0
    crl_center_vertical_coordinate = 0.0
    crl_initial_photon_energy = 8.48e3  # [eV] ### OK ???
    crl_final_photon_energy = 8.52e3  # [eV]   ### OK ???

    crl = CRL(
        _foc_plane=crl_focussing_plane,
        _delta=crl_delta,
        _atten_len=crl_attenuation_length,
        _shape=crl_shape,
        _apert_h=crl_aperture,
        _apert_v=crl_aperture,
        _r_min=crl_curvature_radius,
        _n=crl_number_of_lenses,
        _wall_thick=crl_wall_thickness,
        _xc=crl_center_horizontal_coordinate,
        _yc=crl_center_vertical_coordinate,
        _void_cen_rad=None,
        _e_start=crl_initial_photon_energy,
        _e_fin=crl_final_photon_energy,
    )
    zoom = 0.6

    bl0.append(
        crl, Use_PP(semi_analytical_treatment=1,
                    zoom=zoom,
                    sampling=zoom / 0.1))

    crl_to_exp_drift = Drift(z)
    z0 = z0 + z
    bl0.append(crl_to_exp_drift,
               Use_PP(semi_analytical_treatment=1, zoom=1, sampling=1))
    #     bl0.append(Empty(),Use_PP(zoom=0.25, sampling=0.25))

    return bl0
Ejemplo n.º 11
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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
k = np.pi * 2 / wav
delta = 4e-07
d2waist = (wav) / (np.arctan(.27 / 8) * np.pi)

r = 75e-03

wfr = Wavefront(
    construct_gaussian(1024, 1024, 25, -15e-02, 15e-02, -15e-02, 15e-02, 3e-2,
                       3e-02, d2waist))

### PLOT 1
plot_intensity_map(wfr)

bl = Beamline()

bl.append(Drift(1), propagation_parameters(1, 1, 1, 1))
bl.propagate(wfr)

x = np.linspace(wfr.params.Mesh.xMin, wfr.params.Mesh.xMax, wfr.params.Mesh.nx)
y = np.ones([wfr.params.Mesh.nx, wfr.params.Mesh.ny])

thickness = norm(cylinder_thickness(x, r, offset=0), lim=(0, 255))

sdir = "../../data/samples/cylinder_thickness.png"

im = Image.fromarray(thickness * y)
im = im.convert("L")
im.save(sdir)

np.save(sdir, thickness)
rx, ry = wfr.get_spatial_resolution()
Ejemplo n.º 14
0
        src.store_hdf5("../data/tmp/source.h5")
    except (KeyError):
        os.remove("../data/tmp/source.h5")
        src.store_hdf5("../data/tmp/source.h5")

    src = Source()
    src.load_hdf5("../data/tmp/source.h5")
    from felpy.model.wavefront import Wavefront
    from wpg.wpg_uti_wf import plot_intensity_map
    wfr = Wavefront()

    from felpy.model.beamline import Beamline
    from wpg.optical_elements import Drift
    from felpy.model.tools import propagation_parameters
    from matplotlib import pyplot as plt

    bl = Beamline()
    bl.append(Drift(50), propagation_parameters(1, 1, 1, 1, mode='fresnel'))

    for w in src.pulses:

        wfr.load_hdf5(w)
        bl.propagate(wfr)
        plt.plot(wfr.x_axis,
                 wfr.get_x_profile(),
                 label="{} $\mu$ rad".format(wfr.source_properties['theta_x'] *
                                             1e6))
        #plot_intensity_map(wfr)
        print(wfr.com)

    plt.legend()
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-

import sys

from felpy.model.wavefront import Wavefront
from felpy.model.beamline import Beamline
from wpg.optical_elements import Drift
from felpy.model.tools import propagation_parameters
from felpy.utils.os_utils import mkdir_p

if __name__ == '__main__':
    print("working")
    in_directory = sys.argv[1]
    print("in: ", in_directory)
    out_directory = sys.argv[2]
    print("out: ", out_directory)
    wfr = Wavefront()
    wfr.load_hdf5(in_directory)
    print("wfr loaded")
    bl = Beamline()
    bl.append(Drift(3.644 - 2.2),
              propagation_parameters(1, 1, 1, 1, 'quadratic'))
    bl.propagate(wfr)
    print("wfr propagated")
    wfr.store_hdf5(out_directory)
    print("wfr stored")
    wfr.analysis(VERBOSE=True, DEBUG=True)
    #print(wfr.custom_fields) ## good debug
Ejemplo n.º 16
0
    return wfr


def z_eff(z1, z2):
    return z1 * z2 / (z1 + z2)


if __name__ == '__main__':
    z = z_eff(8e-03, 3.5)
    from wpg.wpg_uti_wf import plot_intensity_map as plotIntensity
    from felpy.model.src.coherent import construct_gaussian

    wfr = construct_SA1_wavefront(1024, 1024, 9.3, 0.25)

    bl = get_beamline_object(crop="NVE")
    bl.append(Drift(2.2 + 8e-02), propagation_parameters(1 / 20, 1, 1 / 50, 1))
    bl.propagate(wfr)
    plotIntensity(wfr)
# =============================================================================
#
#     plotIntensity(wfr)
#     # print("Pixel Size: {}".format(wfr.get_spatial_resolution()))
#     propThruMaskLite(wfr)
#     plotIntensity(wfr)
#
#     bl = Beamline()
#     bl.append(Drift(z), propagation_parameters(1/10,1,1/10,1, 'quadratic'))
#     bl.propagate(wfr)
#     plotIntensity(wfr)
#
#     print("Pixel Size: {}".format(wfr.get_spatial_resolution()))
Ejemplo n.º 17
0
                print(oe)
             
            
            srwl.PropagElecField(wfr._srwl_wf, bl)
            
            if return_intensity:
                intensity.append(wfr.get_intensity().sum(-1))
            if return_mesh:
                mesh.append(wfr.get_mesh())
                    
            plot_intensity_map(wfr)
            
        if return_intensity:
            
            if return_mesh:
                return intensity, mesh
            else:
                return intensity
            
            
if __name__ == '__main__':

    from felpy.model.src.coherent import construct_SA1_pulse
    from felpy.model.tools import propagation_parameters
    from wpg.optical_elements import Drift
    wfr = construct_SA1_pulse(512,512,2,5.0,1)
    print(wfr.params.wDomain)
    wfr.plot()
    bl = Beamline()
    bl.append(Drift(10), propagation_parameters(2,1,2,1,'quadratic'))
    bl.propagate_sequential(wfr)
Ejemplo n.º 18
0
@author: twguest

test to see if backpropagation works (it does)
"""

import sys

sys.path.append("../")
sys.path.append("/opt/WPG/")

from model.tools import constructPulse
from model.beamline.structure import propagation_parameters
from felpy.model.beamline import Beamline
from wpg.optical_elements import Drift
from wpg.wpg_uti_wf import plot_intensity_map as plotIntensity



if __name__ == "__main__":
    
    wfr = constructPulse(nz = 2)
    plotIntensity(wfr)
    
    bl = Beamline()
    bl.append(Drift(-10), propagation_parameters(1,1,1,1))
    
    bl.propagate(wfr)
    
    plotIntensity(wfr)
    
Ejemplo n.º 19
0
def get_beamline():
    """ Setup and return the WPG.Beamline object representing the SPB/SFX nanofocus beamline (KB mirrors).

    :return: beamline
    :rtype beamline: wpg.Beamline
    """

    ### 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]

    #Incidence angle at HOM
    theta_om = 3.6e-3  # [rad]

    om_mirror_length = 0.8  # [m]
    om_clear_ap = om_mirror_length * theta_om

    #define the beamline:
    beamline = Beamline()
    zoom = 1

    # Define HOM1 = Aperture + Wavefront distortion.
    aperture_x_to_y_ratio = 1
    hom1_aperture = Aperture(shape='r',
                             ap_or_ob='a',
                             Dx=om_clear_ap,
                             Dy=om_clear_ap / aperture_x_to_y_ratio)

    # Append to beamline.
    beamline.append(
        hom1_aperture,
        Use_PP(semi_analytical_treatment=0, zoom=zoom, sampling=zoom))

    # Free space propagation from hom1 to hom2
    hom1_to_hom2_drift = Drift(src_to_hom2 - src_to_hom1)
    beamline.append(hom1_to_hom2_drift, Use_PP(semi_analytical_treatment=0))

    # Define HOM2.
    zoom = 1.0
    hom2_aperture = Aperture('r', 'a', om_clear_ap,
                             om_clear_ap / aperture_x_to_y_ratio)
    beamline.append(
        hom2_aperture,
        Use_PP(semi_analytical_treatment=0, zoom=zoom, sampling=zoom))

    #drift to CRL aperture
    hom2_to_crl_drift = Drift(src_to_crl - src_to_hom2)
    beamline.append(hom2_to_crl_drift, Use_PP(semi_analytical_treatment=1))

    # Circular Aperture before CRL.
    crl_front_aperture_diameter = 2.8e-3
    crl_front_aperture = Aperture('c', 'a', crl_front_aperture_diameter,
                                  crl_front_aperture_diameter)

    ### Define CRL
    crl_focussing_plane = 3  # Both horizontal and vertical.
    crl_delta = 4.8308e-06  # Refractive index decrement (n = 1- delta - i*beta) @ 8.4 keV
    crl_attenuation_length = 6.053e-3  # Attenuation length [m], Henke data.
    crl_shape = 1  # Parabolic lenses
    crl_aperture = 3.0e-3  # [m]
    crl_curvature_radius = 5.8e-3  # [m]
    crl_number_of_lenses = 19
    crl_wall_thickness = 8.0e-5  # Thickness
    crl_center_horizontal_coordinate = 0.0
    crl_center_vertical_coordinate = 0.0
    crl_initial_photon_energy = 8.48e3  # [eV]
    crl_final_photon_energy = 8.52e3  # [eV]

    crl = CRL(
        _foc_plane=crl_focussing_plane,
        _delta=crl_delta,
        _atten_len=crl_attenuation_length,
        _shape=crl_shape,
        _apert_h=crl_aperture,
        _apert_v=crl_aperture,
        _r_min=crl_curvature_radius,
        _n=crl_number_of_lenses,
        _wall_thick=crl_wall_thickness,
        _xc=crl_center_horizontal_coordinate,
        _yc=crl_center_vertical_coordinate,
        _void_cen_rad=None,
        _e_start=crl_initial_photon_energy,
        _e_fin=crl_final_photon_energy,
    )

    zoom = 0.6
    beamline.append(
        crl_front_aperture,
        Use_PP(semi_analytical_treatment=0, zoom=zoom, sampling=zoom / 0.1))
    beamline.append(crl, Use_PP(semi_analytical_treatment=0,
                                zoom=1,
                                sampling=1))

    # Drift to focus aperture
    crl_to_exp_drift = Drift(src_to_exp - src_to_crl)
    beamline.append(crl_to_exp_drift,
                    Use_PP(semi_analytical_treatment=1, zoom=1, sampling=1))

    return beamline
Ejemplo n.º 20
0
        bl.append(sp, propagation_parameters(1,1,1,1))
        bl.propagate(wfr)
        
        
        bl = Beamline()
        bl.append(ps, propagation_parameters(1,1,1,1))
        bl.propagate(wfr)
        
        
        PH[:,:,i] = wfr.get_phase()[:,:,0] #% np.pi*2
        ## PH = (PH + np.pi) % (2 * np.pi) - np.pi


        
        bl = Beamline()
        bl.append(Drift(0.10), propagation_parameters(1,1,1,1, mode = 'normal'))
        bl.propagate(wfr)
        II[:,:,i] =  wfr.get_intensity()[:,:,0]
        
        plotIntensity(wfr)
    
    II = np.random.rand(*II.shape)*1e-100
    
    print("")
    
    for i in range(N):
        
        a = II[:,:,i]
        
        if i+1 != N:
            b = II[:,:,i+1]