Пример #1
0
        %%%%def generate_mode(self, mode_no, eigenfn, outPath = None):
        
        gauss_0 = primary_gaussian() # properties of gaussian

        gauss_0.d2waist = 0
        print("Generating Mode {}".format(mode_no))
        mx = self.modeIndices[n][0]
        my = self.modeIndices[n][1]
        
        xw = self.rho_I *
        yw = self.rho_I * 
        
        M2x = (2*mx)+1
        M2y = (2*my)+1
        
        wfr = Wavefront(build_gauss_wavefront_xy(gauss_0.nx ,gauss_0.ny,
                                                      self.EkeV,
                                                      self.xMin, self.xMax,
                                                      self.yMin, self.yMax,
                                                      gauss_0.sigX*(M2x**-0.5),
                                                      gauss_0.sigY*(M2y**-0.5),
                                                      gauss_0.d2waist,
                                                      tiltX = 0,
                                                      tiltY = 0,
                                                      _mx = mx,
                                                      _my = my))
        
        if outPath is not None:
            wfr.store_hdf5(outdir + "wfr_mode_{}.hdf5".format(mode_no))
        
        return wfr
Пример #2
0
 def __init__(self):
     """
     
     """
     self.wfr = Wavefront()
     self.eigenModes = []
     self.weightings = []
Пример #3
0
    def generate_mode_test(self, mode_no, eigenfn, outdir, gwaist = None):
        gauss_0 = primary_gaussian() # properties of gaussian
        gauss_0.d2waist = -9.0000
        if gwaist is not None:
            gauss_0.d2waist = gwaist
        print("Generating Mode {}".format(mode_no))
        _mx = eigenfn[mode_no][0]
        _my = eigenfn[mode_no][1]
        
        M2x = (2*_mx)+1
        M2y = (2*_my)+1
        
        GsnBm = SRWLGsnBm(_x = 0, _y = 0, _z = 0,
                          _sigX = 100e-06,#gauss_0.sigX*(M2x**-0.25),
                          _sigY = 100e-06,#gauss_0.sigY*(M2y**-0.25),
                          _xp = 0, #gauss_0.xp,
                          _yp = 0,#gauss_0.yp,
                          _mx = _mx,
                          _my = _my,
                          _avgPhotEn = gauss_0.E)
        
        wfr = Wavefront(build_gaussian(GsnBm,
                                       gauss_0.nx*2, gauss_0.ny*2,
                                       gauss_0.xMin*2, gauss_0.xMax*2,
                                       gauss_0.yMin*2, gauss_0.yMax*2))

        wfr.store_hdf5(outdir + "wfr_mode_{}.hdf5".format(mode_no))
        return wfr
Пример #4
0
    def generateEigenmodes(self, nx, ny, ekev, xMin, xMax, yMin, yMax, sigX,
                           sigY, d2Waist):
        """
        Generates eigenmodes of the partially coherent GSM beam
        
        :param nx: wfr horizontal dimensions in pixels (int)
        :param ny: wfr vertical dimensions in pixels (int)
        :param ekev: wfr energy in keV (float)
        :param xMin: wfr horizontal spatial minimum (float)
        :param xMax: wfr horizontal spatial maximum (float)
        :param yMin: wfr vertical spatial minimum (float)
        :param yMax: wfr vertical spatial maximum (float)
        :param sigX: fundamental gaussian horizontal FWHM (1st dev.) (float)
        :param sigY: fundamental gaussian vertical FWHM (1st dev.) (float)
        :param d2Waist: distance to waist - defines beam curvature (float)
        """

        for mx, my in self.eigenModes:

            if mx == 0 and my == 0:

                self.wfr = Wavefront(
                    build_gauss_wavefront_xy(nx,
                                             ny,
                                             ekev,
                                             xMin,
                                             xMax,
                                             yMin,
                                             yMax,
                                             sigX,
                                             sigY,
                                             d2Waist,
                                             _mx=mx,
                                             _my=my))

                self.wfr.params.type = 'Gaussian Schell Model Type Beam'
            else:

                tmp_gsn = Wavefront(
                    build_gauss_wavefront_xy(nx,
                                             ny,
                                             ekev,
                                             xMin,
                                             xMax,
                                             yMin,
                                             yMax,
                                             sigX,
                                             sigY,
                                             d2Waist,
                                             _mx=mx,
                                             _my=my))

                addSlice(self.wfr, tmp_gsn)

                del tmp_gsn
Пример #5
0
def main():
    v = srwl_bl.srwl_uti_parse_options(varParam, use_sys_argv=True)
    op = set_optics(v)
    v.ws = True
    v.ws_pl = 'xy'
    mag = None
    if v.rs_type == 'm':
        mag = srwlib.SRWLMagFldC()
        mag.arXc.append(0)
        mag.arYc.append(0)
        mag.arMagFld.append(srwlib.SRWLMagFldM(v.mp_field, v.mp_order, v.mp_distribution, v.mp_len))
        mag.arZc.append(v.mp_zc)
    srwl_bl.SRWLBeamline(_name=v.name, _mag_approx=mag).calc_all(v, op)
    w = v.w_res
    
    from utilMultislice import sliceNums
    import math
    
    """ Finding number of necessary slices for each mask layer """
    lam = 6.7e-9 # Incident wavelength
    et1 = 0.1    # Transverse sampling factor (must be < 0.25)
    et2 = 0.1    # Longitudinal sampling factor (must be < 0.25)
    x1 = 2.5e-9  # Resolution at photon block layer
    x2 = x1      # Resolution at substrate layer
    x3 = x1      # Resolution at absorber layer
    t1 = 200e-9  # Thickness of photon block layer
    t2 = 40e-9   # Thickness of substrate layer
    t3 = 720e-9  # Thickness of absorber layer
    
    
    N1 = sliceNums(t1, lam, x1, et1, et2)
    N2 = sliceNums(t2, lam, x2, et1, et2)
    N3 = sliceNums(t3, lam, x3, et1, et2)
    
    print("Number of slices necessary for photon block layer: {}".format(math.ceil(N1)))
    print("Number of slices necessary for substrate layer: {}".format(math.ceil(N2)))
    print("Number of slices necessary for absorber layer: {}".format(math.ceil(N3)))
    
    wf0 = Wavefront(srwl_wavefront=w)
    
    phase = wf0.get_phase()
    newphase = np.squeeze(phase)
    # plt.imshow(newphase)
    # plt.show()
    
    intensity = wf0.get_intensity()
    # plt.imshow(intensity)
    # plt.show()
    
    import imageio
    imageio.imwrite('phaseTest.tif', newphase)
    imageio.imwrite('intensity_maskprop.tif',intensity)
Пример #6
0
def propagate_wavefront(wavefront, beamline, output_file=None):
    """
    Propagate wavefront and store it in output file.

    :param wavefront: wpg.Wavefront object or path to HDF5 file
    :param beamline: SRWLOptC container of beamline
    :param output_file: if parameter present - store propagaed wavefront to file
    :return: propagated wavefront object
    """

    if not isinstance(beamline, Beamline):
        bl = Beamline(beamline)
    else:
        bl = beamline
    print(bl)

    if isinstance(wavefront, Wavefront):
        wfr = Wavefront(srwl_wavefront=wavefront._srwl_wf)
    else:
        print('*****reading wavefront from h5 file...')
        wfr = Wavefront()
        wfr.load_hdf5(wavefront)

    print_mesh(wfr)
    print('*****propagating wavefront (with resizing)...')
    bl.propagate(wfr)

    if output_file is not None:
        print('save hdf5:', output_file)
        wfr.store_hdf5(output_file)
    print('done')
    return wfr
Пример #7
0
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)
Пример #8
0
def gsmSource(wfr, mx, my, sigX=None, sigY=None, d2waist=None):
    """
    takes an existing wavefield structure and uses it to generate a gsm source
    w/ a coherence function defined by starikov and wolf
    """

    if sigX == None:
        sigX = (wfr.params.Mesh.xMax - wfr.params.Mesh.xMin) / 10

    if sigY == None:
        sigY = (wfr.params.Mesh.yMax - wfr.params.Mesh.yMin) / 10

    wfr.params.type = 'Gaussian Schell Model Type Beam'

    #### GENERATE TRANSVERSE ELECTRIC MODE PAIRS
    wfr.params.eigenmodes = ordered_pairs(mx, my)

    #xMin, xMax, yMin, yMax = wfr.get_limits()
    for mx, my in wfr.params.eigenmodes:
        tmp_gsn = Wavefront(
            build_gauss_wavefront_xy(wfr.params.Mesh.nx,
                                     wfr.params.Mesh.ny,
                                     wfr.params.photonEnergy / 1000,
                                     *wfr.get_limits(),
                                     sigX,
                                     sigY,
                                     wfr.params.Mesh.zCoord,
                                     _mx=mx,
                                     _my=my))
        addSlice(wfr, tmp_gsn)

    return wfr
Пример #9
0
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------')
Пример #10
0
def testComplex():
    path = 'wavefield_1.pkl'
    
    import pickle
    with open(path, 'rb') as wav:
        w = pickle.load(wav)
    
        
    wc = Wavefront(srwl_wavefront=w)
    getComplex(wc)
    print(" ")
Пример #11
0
def propagate_wavefront(wavefront, beamline, output_file=None):
    """
    Propagate wavefront and store it in output file.

    :param wavefront: Wavefront object or path to HDF5 file
    :param beamline: SRWLOptC container of beamline
    :param output_file: if parameter present - store propagaed wavefront to file
    :return: propagated wavefront object:
    """

    if not isinstance(beamline, Beamline):
        bl = Beamline(beamline)
    else:
        bl = beamline
    print(bl)

    if isinstance(wavefront, Wavefront):
        wfr = Wavefront(srwl_wavefront=wavefront._srwl_wf)
    else:
        print("*****reading wavefront from h5 file...")
        wfr = Wavefront()
        wfr.load_hdf5(wavefront)

    print_mesh(wfr)
    print("*****propagating wavefront (with resizing)...")
    bl.propagate(wfr)

    if output_file is not None:
        print("save hdf5:", output_file)
        wfr.store_hdf5(output_file)
    print("done")
    return wfr
Пример #12
0
def extract_intensity(fname):
    
    wfr = Wavefront()
    wfr.load_hdf5(indir + fname)
    
   
    np.save(intensity_dir + fname, wfr.get_intensity().sum(-1))
    np.save(complex_dir + fname, wfr.as_complex_array().sum(-1))
Пример #13
0
def look_at_q_space(wf, output_file=None, save="", range_x=None, range_y=None):
    """
    change wavefront representation from R- to Q-space and store it in output file.

    :params wf: Wavefront object in R-space representation
    :params output_file: if parameter present - store propagaed wavefront to file

    :params save: Whether to save the figure on disk
    :type:  string for filename. Empty string '' means don't save.
    :default: '', do not save the figure.

    :params range_x: x-axis range.
    :type: float
    :default: None, take entire x range.

    :params range_y: y-ayis range.
    :type: float
    :default: None, take entire y range.

    :return: propagated wavefront object:
    """
    wfr = Wavefront(srwl_wavefront=wf._srwl_wf)

    if not wf.params.wSpace == "R-space":
        print("space should be in R-space, but not " + wf.params.wSpace)
        return
    srwl_wf = wfr._srwl_wf
    srwl_wf_a = copy.deepcopy(srwl_wf)
    srwl.SetRepresElecField(srwl_wf_a, "a")
    wf_a = Wavefront(srwl_wf_a)
    if output_file is not None:
        print("store wavefront to HDF5 file: " + output_file + "...")
        wf_a.store_hdf5(output_file)
        print("done")

    print(calculate_fwhm(wf_a))
    plot_t_wf_a(wf_a, save=save, range_x=range_x, range_y=range_y)
    return
Пример #14
0
def look_at_q_space(wf, output_file=None, save='', range_x=None, range_y=None):
    """
    change wavefront representation from R- to Q-space and store it in output file.

    :params wf: Wavefront object in R-space representation
    :params output_file: if parameter present - store propagaed wavefront to file

    :params save: Whether to save the figure on disk
    :type:  string for filename. Empty string '' means don't save.
    :default: '', do not save the figure.

    :params range_x: x-axis range.
    :type: float
    :default: None, take entire x range.

    :params range_y: y-ayis range.
    :type: float
    :default: None, take entire y range.

    :return: propagated wavefront object:
    """
    wfr = Wavefront(srwl_wavefront=wf._srwl_wf)

    if not wf.params.wSpace == 'R-space':
        print('space should be in R-space, but not ' + wf.params.wSpace)
        return
    srwl_wf = wfr._srwl_wf
    srwl_wf_a = copy.deepcopy(srwl_wf)
    srwl.SetRepresElecField(srwl_wf_a, 'a')
    wf_a = Wavefront(srwl_wf_a)
    if output_file is not None:
        print('store wavefront to HDF5 file: ' + output_file+'...')
        wf_a.store_hdf5(output_file)
        print('done')

    print(calculate_fwhm(wf_a))
    plot_t_wf_a(wf_a, save=save, range_x=range_x, range_y=range_y)
    return
Пример #15
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)
Пример #16
0
def testPoynting():
    """ Loading Pickled Wavefield """
    path = '/home/jerome/Documents/MASTERS/testWave.pkl'

    with open(path, 'rb') as wav:
        w = pickle.load(wav)

    wf = Wavefront(srwl_wavefront=w)

    I = Wavefront.get_intensity(wf)
    pGrad = getPhaseGradient(wf, 'total', 0)
    # Ph = Wavefront.get_phase(wf)

    plt.imshow(I)
    plt.title("Intensity")
    plt.show()

    plt.imshow(pGrad)
    plt.title("Phase Gradient")
    plt.show()

    dX, dY = Wavefront.pixelsize(wf)

    # print("shape of Ph: {}".format(np.shape(Ph)))
    print("(dX,dY): {}".format((dX, dY)))

    # pGradX = np.gradient(Ph[1])#,varargs = (dX,dY),axis = (0,1))

    lamb = 6.7e-9  #wavelength of incident radiation

    Px = poynting(lamb, np.squeeze(I), pGrad)

    print("Shape of Intensity: {}".format(np.shape(I)))
    print("Shape of pGrad: {}".format(np.shape(pGrad)))
    print("shape of Poynting vector: {}".format(np.shape(Px)))
    # print("P: {}".format(Px))

    plt.imshow(Px)
    plt.title("poynting vector")
    plt.show()

    poyntY = Px[:, int(np.shape(Px)[0] / 2)]
    pGradY = pGrad[:, int(np.shape(pGrad)[0] / 2)]

    plt.plot(pGradY)
    plt.title('Phase Gradient (Vertical cut)')
    plt.show()

    plt.plot(poyntY)
    plt.title('Poynting Vector (Vertical cut)')
    plt.show()

    m1 = (abs(pGrad) > 0.04) & (abs(pGrad) < 0.08)

    #plt.imshow(gradient[mask])
    print("shape of m1: {}".format(np.shape(m1)))
    print("shape of pGrad: {}".format(np.shape(pGrad)))
    print("shape of pGrad[m1]: {}".format(np.shape(pGrad[m1])))
    ## plt.imshow(pGrad[m1])
    # print("pGrad[m1]: {}".format(pGrad[m1]))
    # print("m1: {}".format(m1))
    # print("max pGrad: {}".format(np.max(pGrad)))

    m1 = m1 != True  # invert mask
    pGrad[m1] = 0
    plt.imshow(pGrad)
    plt.title("m=1 phase gradient")
    plt.show()
Пример #17
0
def analyseWave(path,
                S=1,
                C=1,
                Cp=1,
                Fx=1 / 3,
                Fy=1 / 3,
                pathS0=None,
                pathS1=None,
                pathS2=None,
                pathS3=None,
                pathD=None,
                pathE=None,
                pathIn=None,
                pathCS=None,
                pathCSL=None,
                pathX=None,
                pathY=None,
                pathC=None,
                pathCL=None,
                pathI=None,
                pathCm=None,
                pathCmL=None):
    ''''
    Return the Stokes parameters and degree of coherence of a pickled wavefield:
        path: File path of pickled wavefield
        S: Get Stokes parameters?                              0 - No, 1 - Yes (mutual=0) , 2 - Yes (mutual=1)
        C: Get Coherence?                                      0 - No, 1 - Yes
        Cp: Get horizontal & vertical Coherence profiles?      0 - No, 1 - Yes
        Fx: Fraction of wavefield to sample (Horizontal)
        Fy: Fraction of wavefield to sample (vertical)
    '''

    with open(path, 'rb') as wav:
        w = pickle.load(wav)

    wc = Wavefront(srwl_wavefront=w)
    print(" ")

    if S == 1:
        print('-----Getting Stokes Parameters-----')
        start1 = time.time()
        S, Dx, Dy = wfStokes.getStokes(w, 0, Fx, Fy)
        s = wfStokes.getStokesParamFromStokes(S)
        _s = wfStokes.normaliseStoke(s)
        end1 = time.time()
        print('Time taken to get Stokes parameters (s): {}'.format(end1 -
                                                                   start1))

        print("(Dx,Dy):{}".format((Dx, Dy)))

        print(" ")
        print("-----Plotting Stokes parameters-----")
        wfStokes.plotStokes(s, S, 'S0', 'S1', 'S2', 'S3', Dx, Dy, pathS0,
                            pathS1, pathS2, pathS3, pathD, pathE, pathIn)
        print(" ")
        print("-----Plotting normalised Stokes parameters-----")
        wfStokes.plotStokes(_s, S, '_s0', '_s1', '_s2', '_s3')

    elif S == 2:
        print('-----Getting Stokes Parameters-----')
        start1 = time.time()
        S, Dx, Dy = wfStokes.getStokes(w, 1, Fx, Fy)
        s = wfStokes.getStokesParamFromStokes(S)
        _s = wfStokes.normaliseStoke(s)
        end1 = time.time()
        print('Time taken to get Stokes parameters (s): {}'.format(end1 -
                                                                   start1))

        print("(Dx,Dy):{}".format((Dx, Dy)))
        print("S (shape): {}".format(np.shape(S)))

        print(" ")
        print("-----Plotting Stokes parameters-----")
        wfStokes.plotStokes(s, S, 'S0', 'S1', 'S2', 'S3', Dx, Dy, pathS0,
                            pathS1, pathS2, pathS3, pathD, pathE, pathIn)
        # print(" ")
        # print("-----Plotting normalised Stokes parameters-----")
        # wfStokes.plotStokes(_s,S,'_s0','_s1','_s2','_s3')

        print(" ")
        print("-----Getting degree of coherence from Stokes-----")
        start2 = time.time()
        wfStokes.coherenceFromSTKS(S, Dx, Dy, pathCS, pathCSL)
        end2 = time.time()
        print('Time taken to get Coherence from Stokes parameters (s): {}'.
              format(end2 - start2))

    if C == 1:
        print(" ")
        print("-----Getting Coherence by Convolution-----")
        start3 = time.time()
        Cw, Dx, Dy = coh.Coherence(wc, Fx, Fy, pathX, pathY, pathC, pathCL,
                                   pathI)
        end3 = time.time()
        print(
            'Time taken to get Coherence of Cw by convolution (s): {}'.format(
                end3 - start3))

        print(" ")
        print("-----Plotting Coherence by Convolution")
        coh.plotCoherence(Cw, Dx, Dy, pathCm, pathCmL)

    # if Cp ==1:
    #     start4 = time.time()
    #     Cp = coh.coherenceProfiles(wc, Fx, Fy)
    #     end4 = time.time()
    #     print('Time taken to get Coherence profiles (s): {}'.format(end4 - start4))

    print(" ")
    print("Done")
Пример #18
0
def main():
    v = srwl_bl.srwl_uti_parse_options(varParam, use_sys_argv=True)
    op = set_optics(v)
    v.ws = True
    v.ws_pl = 'xy'
    mag = None
    if v.rs_type == 'm':
        mag = srwlib.SRWLMagFldC()
        mag.arXc.append(0)
        mag.arYc.append(0)
        mag.arMagFld.append(
            srwlib.SRWLMagFldM(v.mp_field, v.mp_order, v.mp_distribution,
                               v.mp_len))
        mag.arZc.append(v.mp_zc)
    srwl_bl.SRWLBeamline(_name=v.name, _mag_approx=mag).calc_all(v, op)
    w = v.w_res

    try:
        from utilMultislice import sliceNums
    except ImportError:
        from SXRL.utilMultislice import sliceNums
    import math
    """ Finding number of necessary slices for each mask layer """
    lam = 6.7e-9  # Incident wavelength
    et1 = 0.1  # Transverse sampling factor (must be < 0.25)
    et2 = 0.1  # Longitudinal sampling factor (must be < 0.25)
    x1 = 2.5e-9  # Resolution at photon block layer
    x2 = x1  # Resolution at substrate layer
    x3 = x1  # Resolution at absorber layer
    t1 = 200e-9  # Thickness of photon block layer
    t2 = 40e-9  # Thickness of substrate layer
    t3 = 720e-9  # Thickness of absorber layer

    wf0 = Wavefront(srwl_wavefront=w)

    dx, dy = wf0.pixelsize(
    )  # resolution of final wavefront (can be used for multislice calculations if no change from wavefront at mask)
    print("final pixel size (dx,dy): {}".format((dx, dy)))

    N1 = sliceNums(t1, lam, dx, et1, et2)
    N2 = sliceNums(t2, lam, dx, et1, et2)
    N3 = sliceNums(t3, lam, dx, et1, et2)

    print("Number of slices necessary for photon block layer: {}".format(
        math.ceil(N1)))
    print("Number of slices necessary for substrate layer: {}".format(
        math.ceil(N2)))
    print("Number of slices necessary for absorber layer: {}".format(
        math.ceil(N3)))

    phase = wf0.get_phase()
    newphase = np.squeeze(phase)
    # plt.imshow(newphase)
    # plt.show()

    intensity = wf0.get_intensity()
    # plt.imshow(intensity)
    # plt.show()

    path = '/data/maskTest/'  # path for writing files
    waveName = 'testWave.pkl'  # name of wavefield pickle file
    phaseName = 'phaseTest.tif'  # name of phase tif file
    intensityName = 'intensity_propMask.tif'  # name of intensity tif file

    import pickle
    with open(path + waveName, "wb") as g:
        pickle.dump(w, g)
    print("Wavefield written to: {}".format(path + waveName))

    import imageio
    imageio.imwrite(path + phaseName, newphase)
    print("Phase written to {}".format(path + phaseName))
    imageio.imwrite(path + intensityName, intensity)
    print("Intensity written to {}".format(path + intensityName))
Пример #19
0
def getEfficiency(path1,
                  path2,
                  path3,
                  m=1,
                  pickle=1,
                  pathm0=None,
                  pathm1=None,
                  pathm2=None):  #, intV = 300):
    """ Get the diffraction efficiency of a mask from intensity before mask, 
    at exit plane & after propagation.
    params:
        path1: intensity/wavefield before mask
        path2: intensity/wavefield at mask exit plane
        path3: intensity/wavefield after propagation
        m: maximum order to be analysed (accepts 0<m<5)
        pickle: input to be analysed. 0 = intensity tif files, 1 = wavefield pickle files
        pathm0: Save path for m=0 order intensity
        pathm1: Save path for m=1 order intensity
        pathm2: Save path for m=2 order intensity
    returns:
        efficiency of each order up to maximum """

    from wfAnalyseWave import pixelsize

    if pickle == 1:

        import pickle
        with open(path1, 'rb') as wav:
            w1 = pickle.load(wav)
        with open(path2, 'rb') as wav:
            w2 = pickle.load(wav)
        with open(path3, 'rb') as wav:
            w3 = pickle.load(wav)

        wf1 = Wavefront(srwl_wavefront=w1)
        wf2 = Wavefront(srwl_wavefront=w2)
        wf3 = Wavefront(srwl_wavefront=w3)

        p1 = pixelsize(wf1)
        p2 = pixelsize(wf2)
        p3 = pixelsize(wf3)

        pR1 = p1[0] / p2[0]
        pR2 = p1[0] / p3[0]
        pR3 = p2[0] / p3[0]

        print("pixel size at mask [m]: {}".format(p1))
        print("pixel size after mask [m]: {}".format(p2))
        print("pixel size after propagation [m]: {}".format(p3))
        print("ratio of pixel sizes (p1/p2): {}".format(pR1))
        print("ratio of pixel sizes (p1/p3): {}".format(pR2))
        print("ratio of pixel sizes (p2/p3): {}".format(pR3))
        """ Intensity from wavefield """
        I0 = wf1.get_intensity()
        I1 = wf2.get_intensity()
        I2 = wf3.get_intensity()
        """ Total intensity at each plane """
        I0_tot = np.sum(I0) / (p1[0] * p1[1])  #*p1[0]#6.25e-09*s0[0]*s0[1]
        I1_tot = np.sum(I1) / (p2[0] * p2[1])  #*p2[0]#*s1[0]*s1[1]
        I2_tot = np.sum(I2) / (p3[0] * p3[1])  #*p3[0]#*s2[0]*s1[1]

    else:
        """ Intensity from tif file """
        I0 = path1  #getImageData("/home/jerome/Documents/MASTERS/data/wavefields/Efficiency/intensityIN.tif")
        I1 = path2  #getImageData('/home/jerome/Documents/MASTERS/data/wavefields/Efficiency/intensityEX_1-2.tif')
        I2 = path3  #getImageData('/home/jerome/Documents/MASTERS/data/wavefields/Efficiency/intensityPR_1-2.tif') #getImageData('/home/jerome/WPG/intensityTot_maskprop.tif')
        """ Total intensity at each plane """
        I0_tot = np.sum(I0)  #*p1[0]#6.25e-09*s0[0]*s0[1]
        I1_tot = np.sum(I1)  #*p2[0]#*s1[0]*s1[1]
        I2_tot = np.sum(I2)  #*p3[0]#*s2[0]*s1[1]

    s0 = np.shape(I0)
    s1 = np.shape(I1)
    s2 = np.shape(I2)

    print("Shape of I (at mask): {}".format(s0))
    print("Shape of I (after mask): {}".format(s1))
    print("Shape of I (after propagation): {}".format(s2))

    F0 = s0[0] / s1[0]
    F1 = s0[0] / s2[0]
    F2 = s1[0] / s2[0]

    print("pixel ratio (I0/I1): {}".format(F0))
    print("pixel ratio (I0/I2): {}".format(F1))
    print("pixel ratio (I1/I2): {}".format(F2))

    if F0 != 1.0:
        print(
            "WARNING! Number of pixels in intensity files does not match! Efficiency values may not be accurate!"
        )

    if F1 != 1.0:
        print(
            "WARNING! Number of pixels in intensity files does not match! Efficiency values may not be accurate!"
        )

    if F2 != 1.0:
        print(
            "WARNING! Number of pixels in intensity files does not match! Efficiency values may not be accurate!"
        )

    Ir0 = (
        I1_tot / I0_tot
    )  #(F0**2)*(I1_tot/I0_tot)    # ratio of intensity before & after mask
    Ir1 = (
        I2_tot / I0_tot
    )  #(F1**2)*(I2_tot/I0_tot)    # ratio of intensity before & after mask
    Ir2 = (
        I2_tot / I1_tot
    )  #(F2**2)*(I2_tot/I1_tot)    # ratio of intensity before & after mask

    print("Intensity Ratio I_ex/I_in: {}".format(Ir0))
    print("Intensity Ratio I_prop/I_in: {}".format(Ir1))
    print("Intensity Ratio I_prop/I_exit: {}".format(Ir2))

    plt.imshow(I0)
    plt.title("at mask")
    plt.colorbar()
    plt.show()

    plt.imshow(I1)
    plt.title("After mask")
    plt.colorbar()
    plt.show()

    plt.imshow(I2)
    plt.title("after propagation")
    plt.colorbar()
    plt.show()

    print(" ")
    print("-----Total Intensity-----")
    print("At mask: {}".format(I0_tot))
    print("After mask: {}".format(I1_tot))
    print("After propagation: {}".format(I2_tot))
    """ Defining region of interest to inspect separate orders """
    Mi = int((s2[0] / 2) - 300)  #initial position for order sampling
    Mf = int((s2[0] / 2) + 300)  #final position for order sampling

    print("coordinates for start and end of each order: {}".format((Mi, Mf)))
    """Finding each order"""

    intV = int(s2[0] /
               (2 * m + 1))  #500 # Number of pixels for segmentation interval

    if m >= 1:
        # region for m=0
        ROI_0 = ((int((s2[0] / 2) - (intV / 2)), Mi),
                 ((int((s2[0] / 2) + (intV / 2))), Mf))
        # region for m=+1
        ROI_1 = ((ROI_0[1][0], Mi), (ROI_0[1][0] + intV, Mf))
        # region for m=-1
        ROI_n1 = ((ROI_0[0][0] - intV, Mi), (ROI_0[0][0], Mf))
    if m >= 2:
        # region for m=+2
        ROI_2 = ((ROI_1[1][0], Mi), (ROI_1[1][0] + intV, Mf))
        # region for m=-2
        ROI_n2 = ((ROI_n1[0][0] - intV, Mi), (ROI_n1[0][0], Mf))
    if m >= 3:
        # region for m=+3
        ROI_3 = ((ROI_2[1][0], Mi), (ROI_2[1][0] + intV, Mf))
        # region for m=-3
        ROI_n3 = ((ROI_n2[0][0] - intV, Mi), (ROI_n2[0][0], Mf))
    if m >= 4:
        # region for m=+4
        ROI_4 = ((ROI_3[1][0], Mi), (ROI_3[1][0] + intV, Mf))
        # region for m=-4
        ROI_n4 = ((ROI_n3[0][0] - intV, Mi), (ROI_n3[0][0], Mf))

    x0_0, y0_0 = ROI_0[0][0], ROI_0[0][1]
    x1_0, y1_0 = ROI_0[1][0], ROI_0[1][1]

    x0_1, y0_1 = ROI_1[0][0], ROI_1[0][1]
    x1_1, y1_1 = ROI_1[1][0], ROI_1[1][1]

    x0_n1, y0_n1 = ROI_n1[0][0], ROI_n1[0][1]
    x1_n1, y1_n1 = ROI_n1[1][0], ROI_n1[1][1]

    try:
        x0_2, y0_2 = ROI_2[0][0], ROI_2[0][1]
        x1_2, y1_2 = ROI_2[1][0], ROI_2[1][1]

        x0_n2, y0_n2 = ROI_n2[0][0], ROI_n2[0][1]
        x1_n2, y1_n2 = ROI_n2[1][0], ROI_n2[1][1]

        x0_3, y0_3 = ROI_3[0][0], ROI_3[0][1]
        x1_3, y1_3 = ROI_3[1][0], ROI_3[1][1]

        x0_n3, y0_n3 = ROI_n3[0][0], ROI_n3[0][1]
        x1_n3, y1_n3 = ROI_n3[1][0], ROI_n3[1][1]

        x0_4, y0_4 = ROI_4[0][0], ROI_4[0][1]
        x1_4, y1_4 = ROI_4[1][0], ROI_4[1][1]

        x0_n4, y0_n4 = ROI_n4[0][0], ROI_n4[0][1]
        x1_n4, y1_n4 = ROI_n4[1][0], ROI_n4[1][1]
    except NameError:
        pass

    A_0 = I2[y0_0:y1_0, x0_0:x1_0]
    A_1 = I2[y0_1:y1_1, x0_1:x1_1]
    A_n1 = I2[y0_n1:y1_n1, x0_n1:x1_n1]
    try:
        A_2 = I2[y0_2:y1_2, x0_2:x1_2]
        A_n2 = I2[y0_n2:y1_n2, x0_n2:x1_n2]
        A_3 = I2[y0_3:y1_3, x0_3:x1_3]
        A_n3 = I2[y0_n3:y1_n3, x0_n3:x1_n3]
        A_4 = I2[y0_4:y1_4, x0_4:x1_4]
        A_n4 = I2[y0_n4:y1_n4, x0_n4:x1_n4]
    except NameError:
        pass

    plt.imshow(A_0)
    plt.title('m=0')
    plt.colorbar()
    if pathm0 != None:
        print("Saving m=0 figure to path: {}".format(pathm0))
        plt.savefig(pathm0)
    plt.show()

    plt.imshow(A_1)
    plt.title('m=+1')
    plt.colorbar()
    if pathm1 != None:
        print("Saving m=1 figure to path: {}".format(pathm1))
        plt.savefig(pathm1)
    plt.show()

    plt.imshow(A_n1)
    plt.title('m=-1')
    plt.colorbar()
    plt.show()

    try:
        plt.imshow(A_2)
        plt.title('m=+2')
        plt.colorbar()
        if pathm2 != None:
            print("Saving m=2 figure to path: {}".format(pathm2))
            plt.savefig(pathm2)
        plt.show()

        plt.imshow(A_n2)
        plt.title('m=-2')
        plt.colorbar()
        plt.show()

        plt.imshow(A_3)
        plt.title('m=+3')
        plt.colorbar()
        plt.show()

        plt.imshow(A_n3)
        plt.title('m=-3')
        plt.colorbar()
        plt.show()

        plt.imshow(A_4)
        plt.title('m=+4')
        plt.colorbar()
        plt.show()

        plt.imshow(A_n4)
        plt.title('m=-4')
        plt.colorbar()
        plt.show()
    except NameError:
        pass

    Im_0 = np.sum(A_0)
    Im_1 = np.sum(A_1)
    Im_n1 = np.sum(A_n1)
    try:
        Im_2 = np.sum(A_2) / Ir2
        Im_n2 = np.sum(A_n2) / Ir2
        Im_3 = np.sum(A_3) / Ir2
        Im_n3 = np.sum(A_n3) / Ir2
        Im_4 = np.sum(A_4) / Ir2
        Im_n4 = np.sum(A_n4) / Ir2
    except NameError:
        pass

    print(" ")
    print("----- Intensity of m = 0-----")
    print("Im_1: {}".format(Im_0))
    print(" ")
    print("----- Intensity of m = +1-----")
    print("Im_1: {}".format(Im_1))
    print(" ")
    print("----- Intensity of m = -1-----")
    print("Im_n1: {}".format(Im_n1))
    try:
        print(" ")
        print("----- Intensity of m = +2-----")
        print("Im_2: {}".format(Im_2))
        print(" ")
        print("----- Intensity of m = -2-----")
        print("Im_n2: {}".format(Im_n2))
        print(" ")
        print("----- Intensity of m = +3-----")
        print("Im_3: {}".format(Im_3))
        print(" ")
        print("----- Intensity of m = -3-----")
        print("Im_n3: {}".format(Im_n3))
        print(" ")
        print("----- Intensity of m = +4-----")
        print("Im_4: {}".format(Im_4))
        print(" ")
        print("----- Intensity of m = -4-----")
        print("Im_n4: {}".format(Im_n4))
    except NameError:
        pass

    if pickle == 1:
        """ Get Efficiency of each order """  # Not sure if should be dividing by total intensity at mask or after mask
        E0 = (Im_0 / I0_tot) / p3[0]  #p3[0]*(Im_0/I0_tot)
        E1 = (Im_1 / I0_tot) / p3[0]  # p3[0]*(Im_1/I0_tot)/p3[0] #
        En1 = (Im_n1 / I0_tot) / p3[0]  # p3[0]*(Im_n1/I0_tot)/p3[0] #

        try:
            E2 = p3[0] * (Im_2 / I0_tot)
            En2 = p3[0] * (Im_n2 / I0_tot)
            E3 = p3[0] * (Im_3 / I0_tot)
            En3 = p3[0] * (Im_n3 / I0_tot)
            E4 = p3[0] * (Im_4 / I0_tot)
            En4 = p3[0] * (Im_n4 / I0_tot)
        except NameError:
            pass
    else:
        """ Get Efficiency of each order """  # Not sure if should be dividing by total intensity at mask or after mask
        E0 = (Im_0 / I0_tot)
        E1 = (Im_1 / I0_tot)
        En1 = (Im_n1 / I0_tot)

        try:
            E2 = (Im_2 / I0_tot)
            En2 = (Im_n2 / I0_tot)
            E3 = (Im_3 / I0_tot)
            En3 = (Im_n3 / I0_tot)
            E4 = (Im_4 / I0_tot)
            En4 = (Im_n4 / I0_tot)
        except NameError:
            pass

    print(" ")
    print("Efficiency of m=0 order: {}".format(E0))
    print("Efficiency of m=+1 order: {}".format(E1))
    print("Efficiency of m=-1 order: {}".format(En1))
    try:
        print("Efficiency of m=+2 order: {}".format(E2))
        print("Efficiency of m=-2 order: {}".format(En2))
        print("Efficiency of m=+3 order: {}".format(E3))
        print("Efficiency of m=-3 order: {}".format(En3))
        print("Efficiency of m=+4 order: {}".format(E4))
        print("Efficiency of m=-4 order: {}".format(En4))
    except NameError:
        pass
Пример #20
0
    def test_gsm(self, beta = 1, nx = 10, ny = 1, pos = "end", export = False, outdir = ""):
        """
        Initialise GSM beam as a container of multiple coherent modes

        Modes dictionary is setup by order {wfr, eigenvalue/weight}

        :param p_mu: rms width of the degree of coherence
        :param p_I: rms width of the intensity profile
        :param n: number of values for eigenvalue calculation (almost arb.)
        """
        print("Initialising Gaussian-Schell Model Beam")
        self.log.info("Initialising Gaussian-Schell Model Beam")

        gauss_0 = primary_gaussian() # properties of gaussian
        N = nx*ny
        

        results = []

        if export == True:
            os.mkdir(outdir)
        else:
            pass

        for itr in range(N):
            self.wfr.eigenval.append(eigenvaluePartCoh(1, beta,itr))

        self.wfr.eigenval = self.wfr.eigenval[0:N]
        self.wfr.eigenfn = gen_modes(nx, ny)

        if pos == "start":
            gauss_0.d2waist = 0
        elif pos == "end":
            gauss_0.d2waist = 2.012
        else:
            assert("wavefront posn' should be 'start' or 'end'")

        print("Generating {} Coherent Modes".format(N))
        self.log.info("Generating {} Coherent Modes".format(N))
        
        eField = np.zeros((2048, 2048, 1))

        if pos == "start":
            gauss_0.d2waist = 0
        elif pos == "end":
            gauss_0.d2waist = 2.012
        else:
            assert("wavefront posn' should be 'start' or 'end'")
        
        print(self.wfr.eigenfn)
        print("Generating {} Coherent Modes".format(N))
        self.log.info("Generating {} Coherent Modes".format(N))
        for itr in range(N):
            
            res = []
            res.append(self.wfr.eigenfn[itr])
            res.append(self.wfr.eigenval[itr])

            if itr % 5 == 0:
                print("Generating Mode {}/{}".format(itr+1, N))
                self.log.info("Generating Mode {}/{}".format(itr+1, N))
                
            _mx = self.wfr.eigenfn[itr][0]
            _my = self.wfr.eigenfn[itr][1]

            M2x = (2*_mx)+1
            M2y = (2*_my)+1
            self.wfr.modes.append(Wavefront(build_gauss_wavefront_xy(gauss_0.nx ,gauss_0.ny,
                                           self.global_E*1e-03,
                                           gauss_0.xMin, gauss_0.xMax,
                                           gauss_0.yMin,gauss_0.yMax,
                                           gauss_0.sigX*M2x**-0.25,
                                           gauss_0.sigY*M2y**-0.25,
                                           gauss_0.d2waist,
                                           tiltX = 0,
                                           tiltY = 0,
                                           _mx = - _mx, ## NOTE NEGATIVE 
                                           _my = _my,
                                           pulseEn = 2.51516e-2)))


            self.wfr.type = 'gsm'

        print("Coherent Modes Generated")
        self.log.info("Coherent Modes Generated")
        
        print("Testing Coherent Modes")
        self.log.info("Testing Coherent Modes")
        
        axis_x = np.linspace(-0.002, 0.002, 2048)
        axis_y = np.linspace(-0.002, 0.002, 2048)
        
        eField = np.zeros((2048,2048,1))
        
        for itr in range(len(self.wfr.modes)):
            eField += self.wfr.modes[itr].data.arrEhor[:,:,:,0] * self.wfr.eigenval[itr]
            [cohx, cohy] = coherence_log(eField, axis_x, axis_y)
            
            
            self.log.info("**************************************************")
            self.log.info("Addition of Mode {}".format(itr))
            self.log.info("Mode Weighting {}".format(self.wfr.eigenval[itr]))
            self.log.info("Mode Weighting {}".format(self.wfr.eigenfn[itr]))
            self.log.info("\n")
            self.log.info("Ix: {} m\nJx: {} m".format(cohx[2], cohx[3]))
            self.log.info("Iy: {} m\nJy: {} m".format(cohy[2], cohy[3]))
            self.log.info("x-beta: {} \n y-beta: {}".format(cohx[4], cohy[4]))

            res.append(cohx[2])
            res.append(cohy[2])
            res.append(cohx[3])
            res.append(cohy[3])
            res.append(cohx[4])
            res.append(cohy[4])

            results.append(res)
        
        return results
Пример #21
0
 def load_mode(self, mode_no, indir):
        wfr = Wavefront()
        wfr.load_hdf5(indir + "/wfr_mode_{}.hdf5".format(mode_no))
        return wfr
Пример #22
0
def constructTestWaveField(npoints=256,ekeV=0.6,z1=5, show=False):  
    # Simple function for generating  simple Gaussian wavefield for testing purposes


    from wpg.srwlib import srwl_uti_ph_en_conv
    from extensions.gvrutils import calculate_theta_fwhm_cdr
    from wpg.generators import build_gauss_wavefront_xy


    # set wavefield parameters
    qnC        = 0.01
    wlambda    = srwl_uti_ph_en_conv(ekeV, _in_u='keV', _out_u='nm')
    theta_fwhm = calculate_theta_fwhm_cdr(ekeV,qnC)
    k          = 2*np.sqrt(2*np.log(2))
    range_xy   = (theta_fwhm/k*z1*5.)*2.0
    sigX       = 12.4e-10*k/(ekeV*4*np.pi*theta_fwhm)

    # construct wavefield
    wf0=build_gauss_wavefront_xy(nx=npoints, ny=npoints, ekev=ekeV,
                                              xMin=-range_xy/2 ,xMax=range_xy/2,
                                              yMin=-range_xy/2, yMax=range_xy/2,
                                              sigX=sigX, sigY=sigX,
                                              d2waist=z1,
                                              _mx=0, _my=0 )
    wfr = Wavefront(srwl_wavefront=wf0)    
    print('Wavelength=%f, theta FWWM=%f, range XY = %f, sig X = %f' % (wlambda, theta_fwhm, range_xy, sigX))

    wfr._srwl_wf.unitElFld = 1#'sqrt(Phot/s/0.1%bw/mm^2)'

    if show==True: #display the wavefield
        plotWavefront(wfr, 'Wavefield at source')

    return wfr



    
    def generate_mode_test(self, mode_no, eigenfn, outdir, gwaist = None):
        gauss_0 = primary_gaussian() # properties of gaussian
        gauss_0.d2waist = -9.0000
        if gwaist is not None:
            gauss_0.d2waist = gwaist
        print("Generating Mode {}".format(mode_no))
        _mx = eigenfn[mode_no][0]
        _my = eigenfn[mode_no][1]
        
        M2x = (2*_mx)+1
        M2y = (2*_my)+1
        
        GsnBm = SRWLGsnBm(_x = 0, _y = 0, _z = 0,
                          _sigX = 100e-06,#gauss_0.sigX*(M2x**-0.25),
                          _sigY = 100e-06,#gauss_0.sigY*(M2y**-0.25),
                          _xp = 0, #gauss_0.xp,
                          _yp = 0,#gauss_0.yp,
                          _mx = _mx,
                          _my = _my,
                          _avgPhotEn = gauss_0.E)
        
        wfr = Wavefront(build_gaussian(GsnBm,
                                       gauss_0.nx*2, gauss_0.ny*2,
                                       gauss_0.xMin*2, gauss_0.xMax*2,
                                       gauss_0.yMin*2, gauss_0.yMax*2))

        wfr.store_hdf5(outdir + "wfr_mode_{}.hdf5".format(mode_no))
        return wfr
Пример #23
0
def plot_intensity_qmap(wf,
                        output_file=None,
                        save='',
                        range_x=None,
                        range_y=None,
                        im_aspect='equal'):
    """
    change wavefront representation from R- to Q-space and plot it the resulting wavefront.

    :param wf: Wavefront object in R-space representation
    :param output_file: if parameter present - store wavefront in Q-space to the file
    :param save: string for filename. Empty string '' means don't save.
    :param range_x: x-axis range, _float_. If None, take entire x range.
    :param range_y: y-ayis range, float. If None, take entire y range.
    :return: propagated wavefront object:
    """
    wfr = Wavefront(srwl_wavefront=wf._srwl_wf)

    if not wf.params.wSpace == 'R-space':
        print('space should be in R-space, but not ' + wf.params.wSpace)
        return
    srwl_wf = wfr._srwl_wf
    srwl_wf_a = copy.deepcopy(srwl_wf)
    srwl.SetRepresElecField(srwl_wf_a, 'a')
    wf_a = Wavefront(srwl_wf_a)
    if output_file is not None:
        print('store wavefront to HDF5 file: ' + output_file + '...')
        wf_a.store_hdf5(output_file)
        print('done')

    print(calculate_fwhm(wf_a))

    #plot_t_wf_a(wf_a, save=save, range_x=range_x, range_y=range_y)
    import matplotlib.pyplot as plt
    wf_intensity = wf_a.get_intensity().sum(axis=-1)
    plt.figure(figsize=(10, 10), dpi=100)
    plt.axis('tight')

    profile = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
    xmin, xmax, ymax, ymin = wf_a.get_limits()

    profile.imshow(wf_intensity,
                   extent=[xmin * 1.e6, xmax * 1.e6, ymax * 1.e6, ymin * 1.e6],
                   cmap="YlGnBu_r")
    profile.set_aspect(im_aspect)

    # [LS:2016-03-17]
    # change shape dimension, otherwise, in case nx!=ny ,
    # 'x, y should have the same dimension' error from py plot
    # x = numpy.linspace(xmin*1.e6,xmax*1.e6,wf_intensity.shape[0])
    # y = numpy.linspace(ymin*1.e6,ymax*1.e6,wf_intensity.shape[1])
    x = numpy.linspace(xmin * 1.e6, xmax * 1.e6, wf_intensity.shape[1])
    y = numpy.linspace(ymin * 1.e6, ymax * 1.e6, wf_intensity.shape[0])
    profile.set_xlabel(r'$\mu$rad', fontsize=12)
    profile.set_ylabel(r'$\mu$rad', fontsize=12)

    x_projection = plt.subplot2grid((3, 3), (0, 0), sharex=profile, colspan=2)
    print(x.shape, wf_intensity.sum(axis=0).shape)
    x_projection.plot(x, wf_intensity.sum(axis=0), label='x projection')
    if range_x is None:
        profile.set_xlim([xmin * 1.e6, xmax * 1.e6])
    else:
        profile.set_xlim([-range_x / 2., range_x / 2.])

    y_projection = plt.subplot2grid((3, 3), (1, 2), rowspan=2, sharey=profile)
    y_projection.plot(wf_intensity.sum(axis=1), y, label='y projection')

    # Hide minor tick labels.
    plt.minorticks_off()

    if range_y is None:
        profile.set_ylim([ymin * 1.e6, ymax * 1.e6])
    else:
        profile.set_ylim([-range_y / 2., range_y / 2.])

    if save != '':
        plt.savefig(save)
    else:
        plt.show()

    return
Пример #24
0
class gsmSource():
    def __init__(self):
        """
        
        """
        self.wfr = Wavefront()
        self.eigenModes = []
        self.weightings = []

    def generatePairs(self, mx, my):
        """
        
        generates ordered pairs for use as transverse electric modes up (mx,my) 
        
        :param mx: highest horizontal transverse mode
        :param my: vertical transverse mode
        
        """
        pairs = []
        for x in range(mx + 1):
            for y in range(my + 1):
                pairs.append((x, y))

        self.eigenModes = pairs

    def generateEigenmodes(self, nx, ny, ekev, xMin, xMax, yMin, yMax, sigX,
                           sigY, d2Waist):
        """
        Generates eigenmodes of the partially coherent GSM beam
        
        :param nx: wfr horizontal dimensions in pixels (int)
        :param ny: wfr vertical dimensions in pixels (int)
        :param ekev: wfr energy in keV (float)
        :param xMin: wfr horizontal spatial minimum (float)
        :param xMax: wfr horizontal spatial maximum (float)
        :param yMin: wfr vertical spatial minimum (float)
        :param yMax: wfr vertical spatial maximum (float)
        :param sigX: fundamental gaussian horizontal FWHM (1st dev.) (float)
        :param sigY: fundamental gaussian vertical FWHM (1st dev.) (float)
        :param d2Waist: distance to waist - defines beam curvature (float)
        """

        for mx, my in self.eigenModes:

            if mx == 0 and my == 0:

                self.wfr = Wavefront(
                    build_gauss_wavefront_xy(nx,
                                             ny,
                                             ekev,
                                             xMin,
                                             xMax,
                                             yMin,
                                             yMax,
                                             sigX,
                                             sigY,
                                             d2Waist,
                                             _mx=mx,
                                             _my=my))

                self.wfr.params.type = 'Gaussian Schell Model Type Beam'
            else:

                tmp_gsn = Wavefront(
                    build_gauss_wavefront_xy(nx,
                                             ny,
                                             ekev,
                                             xMin,
                                             xMax,
                                             yMin,
                                             yMax,
                                             sigX,
                                             sigY,
                                             d2Waist,
                                             _mx=mx,
                                             _my=my))

                addSlice(self.wfr, tmp_gsn)

                del tmp_gsn

    def generateWeightings(self, sigma_I, sigma_mu, axisName='x'):
        """
        @author: gvr 
        @modded: twguest 25/03/20
        
        returns set of eigenvalues normalised to 1
        
        definitions follow Starikov and Wolf, 1982:
            
        beta =  p_mu/p_I is a measure of the "degree of global coherence" of the source.
       
        When beta >> 1, the source is effectively spatially coherent in the global sense and is then
        found to be well represented by a single mode. 
        
        When beta << 1, the source is effectively spatially incoherent in the global
        sense, and the number of modes needed to describe its behavior is larget
        
        :param sigma_I: 1D FWHM of intensity profile (float)
        :param sigma_mu: 1D Coherence Width (defined FWHM) (float)
        """

        a = 1 / (2 * sigma_I**2)
        b = 1 / (2 * sigma_mu**2)
        c = (a**2 + 2 * a * b)**(1 / 2)

        weightfundamental = 1.0  ## Fundamental Mode Weight

        if axisName == 'x':
            M = max(self.eigenModes, key=itemgetter(0))[0]  # gets max x mode
        elif axisName == 'y':
            M = max(self.eigenModes, key=itemgetter(1))[1]  # gets max y mode

        self.weightings = [
            weightfundamental * (b / (a + b + c))**n for n in range(M + 1)
        ]
        self.weightings /= np.sum(self.weightings)

    def generateWeights2D(self, sigma_Ix, sigma_mux, sigma_Iy, sigma_muy):
        """
        @author: twguest 
        @modded: twguest 25/03/20
        
        returns set of eigenvalue normalised to 1
        
        under the assumption that the transverse components of the MCF are seperable
        definitions follow Starikov and Wolf, 1982:Merges from masterMerges from master
            
        beta =  p_mu/p_I is a measure of the "degree of global coherence" of the source.
       
        When beta >> 1, the source is effectively spatially coherent in the global sense and is then
        found to be well represented by a single mode. 
        
        When beta << 1, the source is effectively spatially incoherent in the global
        sense, and the number of modes needed to describe its behavior is larget
        
        :param sigma_Ix: 1D FWHM of horizontal intensity profile (float)
        :param sigma_mux: 1D horizontal Coherence Width (defined FWHM) (float)
        
        :param sigma_Iy: 1D FWHM of vertical intensity profile (float)
        :param sigma_muy: 1D vertical Coherence Width (defined FWHM) (float)
        """

        a = 1 / (2 * sigma_I**2)
        b = 1 / (2 * sigma_mu**2)
        c = (a**2 + 2 * a * b)**(1 / 2)

        weightfundamental = 1.0  ## Fundamental Mode Weight

        Mx = max(a, key=itemgetter(0))[0]  # gets max x mode
        My = max(a, key=itemgetter(1))[1]  # gets max y mode

        self.weightings = [
            weightfundamental * (b / (a + b + c))**n for n in range(M)
        ]
        self.weightings /= np.sum(self.weightings)

    def replaceWavefront(self, new_wfr):
        """
        replaces current wfr with new_wfr, useful after propagation
        """
        self.wfr = new_wfr

    def collapseModes(self):
        """
        (this should be checked)
        
        :returns cmplx: scaled cmplx incoherent sum of modes valued array
        """
        wfield = []

        cmplx = self.wfr.toComplex()
        print(cmplx.shape)
        for pol in cmplx:
            print(pol.shape)
            for itr in range(pol.shape[2]):
                pol[:, :, itr] *= self.weightings[itr]

            wfield.append(np.sum(pol, axis=2))

        return wfield

    def get_wavefront(self):
        """
        :returns self.wfr: Wavefront object of GSM source
        """
        return self.wfr

    def get_fundamental(self):
        """  
        :returns fnd: [Wavefront Obj.] 
        fundamental mode of gaussian schell model source TEM_{00}.
        """
        fnd = deepcopy(self.wfr)

        fnd.params.type = 'fundamental mode'

        fnd.data.wfr.arrEhor = fnd.data.wfr.arrEhor[:, :, 0, :]
        fnd.data.wfr.arrEver = fnd.data.wfr.arrEver[:, :, 0, :]

        return fnd
Пример #25
0
    ax1 = fig.add_subplot(111)
    ax1.plot(ax_x, Ix, color="blue", label="Horizontal Profile")
    ax1.set_ylabel("Intensity (W/$mm^2$)", fontsize=22)

    ax1.plot(ax_y, Iy, color="red", label="Vertical Profile")
    ax1.set_xlabel("Position ($\mu m$)", fontsize=22)

    plt.legend(fontsize=22)

    if show == True:
        plt.show()


def plotWavefront(wfr):

    fig = plt.figure(figsize=[12, 8])

    ii = wfr.get_intensity()[:, :, 0]
    ph = wfr.get_phase()[:, :, 0]

    plt.imshow(ph * ii)


if __name__ == '__main__':

    ### CONSTRUCT ARB. WFR
    wfr = Wavefront(
        build_gauss_wavefront_xy(256, 256, 9.2, -5e-07, 5e-07, -5e-07, 5e-07,
                                 1e-07, 1e-07, 1e-09))
    plotWavefront(wfr)
Пример #26
0
def main():
    v = srwl_bl.srwl_uti_parse_options(varParam, use_sys_argv=True)
    op = set_optics(v)
    v.ss = True
    v.ss_pl = 'e'
    v.sm = True
    v.sm_pl = 'e'
    v.pw = True
    v.pw_pl = 'xy'
    v.si = True
    v.si_pl = 'xy'
    v.tr = True
    v.tr_pl = 'xz'
    
    """Multi-Electron propagation"""
    v.wm = True
    v.wm_pl = 'xy'
    v.wm_ns = v.sm_ns = 5
    
    """Single-Electron propagation"""
    # v.ws = True
    # v.ws_pl = 'xy'
    
    mag = None
    if v.rs_type == 'm':
        mag = srwlib.SRWLMagFldC()
        mag.arXc.append(0)
        mag.arYc.append(0)
        mag.arMagFld.append(srwlib.SRWLMagFldM(v.mp_field, v.mp_order, v.mp_distribution, v.mp_len))
        mag.arZc.append(v.mp_zc)
    #srwl_bl.SRWLBeamline(_name=v.name, _mag_approx=mag).calc_all(v, op)
    

    if v.rs_type != 'r':
 
        # wf0 = srwl_bl.SRWLBeamline(_name=v.name, _mag_approx=mag).calc_all(v, op)
        srwl_bl.SRWLBeamline(_name=v.name, _mag_approx=mag).calc_all(v, op)
        wf0 = v.w_res
        
        # Fraction of wavefront to sample for analysis
        Fx = 1/4
        Fy = 1/4
        
        """ For multi-electron propagation - wavefront is pickled in srwlib.py line 7188 """
        # import analyseWave as aw
        
        # print(" ")
        # print("""-----Analysing Wavefield-----""")
        # aw.analyseWave('wavefield.pkl')
    
        import pickle
        Fx = 1/4
        Fy = 1/4
        
        """ For single-electron propagation """
        print(" ")
        print("""-----Writing Wavefield to pickle file----""")
                
        
        path = "/home/jerome/WPG/" #"/data/group/vanriessenlab/project/xrnl-srw-wpg-docker/data/maskTest/"
        waveName = path + "wavefield_TESTY.pkl"  # Save path for wavefield pickle
        pathS0 = path + "S0.png"               # Save path for Stokes parameter S0 plot
        pathS1 = path + "S1.png"               # Save path for Stokes parameter S1 plot
        pathS2 = path + "S2.png"               # Save path for Stokes parameter S2 plot
        pathS3 = path + "S3.png"               # Save path for Stokes parameter S3 plot
        pathD = path + "D.png"                 # Save path for Degree of Polarisation (D) plot
        pathE = path + "E.png"                 # Save path for Ellipticity (E) plot
        pathIn = path + "In.png"               # Save path for Inclination (In) plot
        pathCS = path + "CS.png"               # Save path for Coherence plot from wfStokes()
        pathCSL = path + "CSL.png"             # Save path for Coherence profiles from wfStokes())
        pathX = path + "X.png"                 # Save path for horizontal cut coherence plot
        pathY = path + "Y.png"                 # Save path for vertical cut coherence plot
        pathC = path + "C.png"                 # Save path for Degree of coherence (U) plot
        pathCL = path + "CL.png"               # Save path for Coherence line profiles plot
        pathI = path + "I.png"                 # Save path for Intensity (I) plot
        pathCm = path + "Cm.png"               # Save path for mean coherence plot
        pathCmL = path + "CmL.png"             # Save path for mean coherence line profile plot
        
        with open(waveName, "wb") as g:
            pickle.dump(wf0, g)
        print("Wavefield written to: {}".format(waveName))
        
        print(" ")
        print("""-----Analysing Wavefield-----""")
        
        aw.analyseWave(waveName,2,1,1,Fx,Fy)#, 
                       # pathS0, pathS1, pathS2, pathS3,
                       # pathD, pathE, pathIn, pathCS, 
                       # pathCSL, pathX, pathY, pathC,
                       # pathCL, pathI, pathCm, pathCmL)

    ''' Add this block and edit as required:
            ***** start block A  *****'''


    if v.rs_type == 'r':
            if v.wfr_file is None:
                print ('Wavefront file not specified')
            else:
                print('\nSetting up beamline {} with elements:\n{}...'.format(v.name,v.opList))
                BL = srwl_blx.beamline(v, _op=op)

                print('Loading wavefront from file {}'.format(v.wfr_file) )
                wfr = Wavefront()
                wfr.load_hdf5(v.wfr_file)
                
                BL.show(wfr._srwl_wf,v)
                
                # Getting phase of initial wavefront and displaying
                phase = wfr.get_phase()
                newphase = np.squeeze(phase) #phase.reshape((phase.shape[2]*phase.shape[0]),phase.shape[1])
                #newphase = newphase.transpose()
                plt.imshow(newphase)
                
                
                import imageio
                imageio.imwrite('fileP.tif',phase)
                imageio.imwrite('fileI.tif',wfr.get_intensity())

                
#                from extensions.wfutils import modifyDimensions
#                modifyDimensions(wfr,
#                                R=(100e-6,
#                                    100e-6)) 
#                modifyDimensions(wfr, 
#                                D=(v.op_MaskResolutionX,
#                                    v.op_MaskResolutionY))                
#                BL.show(wfr._srwl_wf,v)
#                
#                # Getting phase of wavefront after resizing/resampling
#                phase = wfr.get_phase()
#                newphase = np.squeeze(phase)
#                plt.imshow(newphase)                
                
               # for l in disabledList:
               #     BL.disable(l)
                # toggle enabled state of all optical elements (BEWARE!!)
                #BL.toggleEnabledState(v.opList)
                
                # implement following (todo)
                #BL.disable(optElemType = Screen)
                
                BL.printOE()
                print('\nPropagating wavefront through optical elements...')
                BL.calc_part(v, wfr=wfr._srwl_wf)
                BL.show(wfr._srwl_wf,v)
                
                # Getting phase of wavefront after propagation
                phase = wfr.get_phase()
                newphase = np.squeeze(phase)
                plt.imshow(newphase)

                # drift through multiple slices.
#                zRange = 200e-6 
#                zPlanes = 2 
#                outPath='/opt/WPG/extensions/data_jk/vol_test/'
#                dVol=driftVol((0.0,zRange,zPlanes),
#                              Use_PP(),
#                              outPath, saveIntensity=True, 
#                              zoomXOutput = 0.5,zoomYOutput = 0.5, 
#                              method=1)
#                dVol.propagate(wfr)

                
    ''' ***** end block A  ******'''