Пример #1
0
def xoppy_calc_wigg(FIELD=0,NPERIODS=12,ULAMBDA=0.125,K=14.0,ENERGY=6.04,PHOT_ENERGY_MIN=100.0,\
                        PHOT_ENERGY_MAX=100100.0,NPOINTS=100,NTRAJPOINTS=101,CURRENT=200.0,FILE="?"):

    print("Inside xoppy_calc_wigg. ")

    outFileTraj = "xwiggler_traj.spec"
    outFile = "xwiggler.spec"

    if FIELD == 0:
        t0,p = srfunc.wiggler_trajectory(b_from=0, nPer=NPERIODS, nTrajPoints=NTRAJPOINTS, \
                                         ener_gev=ENERGY, per=ULAMBDA, kValue=K, \
                                         trajFile=outFileTraj)
    if FIELD == 1:
        # magnetic field from B(s) map
        t0,p = srfunc.wiggler_trajectory(b_from=1, nPer=NPERIODS, nTrajPoints=NTRAJPOINTS, \
                                         ener_gev=ENERGY, inData=FILE, trajFile=outFileTraj)
    if FIELD == 2:
        # magnetic field from harmonics
        # hh = srfunc.wiggler_harmonics(b_t,Nh=41,fileOutH="tmp.h")
        t0,p = srfunc.wiggler_trajectory(b_from=2, nPer=NPERIODS, nTrajPoints=NTRAJPOINTS, \
                                         ener_gev=ENERGY, per=ULAMBDA, inData="", trajFile=outFileTraj)
    print(p)
    #
    # now spectra
    #
    e, f0, p0 = srfunc.wiggler_spectrum(t0, enerMin=PHOT_ENERGY_MIN, enerMax=PHOT_ENERGY_MAX, nPoints=NPOINTS, \
                                    electronCurrent=CURRENT*1e-3, outFile=outFile, elliptical=False)

    try:
        cumulated_power = p0.cumsum() * numpy.abs(e[0] - e[1])
    except:
        cumulated_power = 0.0

    print("\nPower from integral of spectrum (sum rule): %8.3f W" % (cumulated_power[-1]))
    return e, f0, p0 , cumulated_power
Пример #2
0
def xoppy_calc_xwiggler(FIELD=0,NPERIODS=12,ULAMBDA=0.125,K=14.0,ENERGY=6.04,PHOT_ENERGY_MIN=100.0,\
                        PHOT_ENERGY_MAX=100100.0,NPOINTS=100,NTRAJPOINTS=101,CURRENT=200.0,FILE="?"):

    print("Inside xoppy_calc_xwiggler. ")

    outFileTraj = "xwiggler_traj.spec"
    outFile = "xwiggler.spec"

    if FIELD == 0:
        t0,p = srfunc.wiggler_trajectory(b_from=0, nPer=NPERIODS, nTrajPoints=NTRAJPOINTS, \
                                         ener_gev=ENERGY, per=ULAMBDA, kValue=K, \
                                         trajFile=outFileTraj)
    if FIELD == 1:
        # magnetic field from B(s) map
        t0,p = srfunc.wiggler_trajectory(b_from=1, nPer=NPERIODS, nTrajPoints=NTRAJPOINTS, \
                                         ener_gev=ENERGY, inData=FILE, trajFile=outFileTraj)
    if FIELD == 2:
        # magnetic field from harmonics
        # hh = srfunc.wiggler_harmonics(b_t,Nh=41,fileOutH="tmp.h")
        t0,p = srfunc.wiggler_trajectory(b_from=2, nPer=NPERIODS, nTrajPoints=NTRAJPOINTS, \
                                         ener_gev=ENERGY, per=ULAMBDA, inData="", trajFile=outFileTraj)
    print(p)
    #
    # now spectra
    #
    e, f0, p0 = srfunc.wiggler_spectrum(t0, enerMin=PHOT_ENERGY_MIN, enerMax=PHOT_ENERGY_MAX, nPoints=NPOINTS, \
                                    electronCurrent=CURRENT*1e-3, outFile=outFile, elliptical=False)

    print("\nPower from integral of spectrum: %8.3f W" %
          (f0.sum() * 1e3 * codata.e * (e[1] - e[0])))
    return e, f0, p0
Пример #3
0
def wiggler_preprocessor(ener_gev=6.0,e_min=5000.0,e_max=5005.0,file_field="",plot_trajectories=0,
                        shift_x_flag=0,shift_x_value=0.0,shift_betax_flag=0,shift_betax_value=0.0):

    (traj, pars) = srfunc.wiggler_trajectory(b_from=1,
                                             inData=file_field,
                                             nPer=1,
                                             nTrajPoints=501,
                                             ener_gev=ener_gev,
                                             per=None,
                                             kValue=None,
                                             trajFile="tmp.traj",
                                             shift_x_flag=shift_x_flag,
                                             shift_x_value=shift_x_value,
                                             shift_betax_flag=shift_betax_flag,
                                             shift_betax_value=shift_betax_value)


    data = numpy.loadtxt("tmp.traj",skiprows=15)

    fig = plt.figure(1)

    fig.add_subplot(221)
    plt.plot(data[:,1],data[:,7])
    plt.title("Magnetic Field "+file_field)
    plt.xlabel("Y [m]")
    plt.ylabel("B [T]")

    fig.add_subplot(222)
    plt.plot(data[:,1],data[:,0])
    plt.title("Electron trajectory")
    plt.xlabel("Y [m]")
    plt.ylabel("X [m]")

    fig.add_subplot(223)
    plt.plot(data[:,1],data[:,3])
    plt.title("Electron velocity")
    plt.xlabel("Y [m]")
    plt.ylabel("betaX")

    fig.add_subplot(224)
    plt.plot(data[:,1],data[:,6])
    plt.title("Electron curvature")
    plt.xlabel("Y [m]")
    plt.ylabel("curvature [m^-1]")



    if plot_trajectories:
        plt.show()

    fig.savefig('sw_'+file_field+'.png')
    plt.close(fig)

    srfunc.wiggler_cdf(traj,
                       enerMin=e_min,
                       enerMax=e_max,
                       enerPoints=1001,
                       outFile="xshwig.sha",
                       elliptical=False)
Пример #4
0
def run_python_preprocessors(e_min=1000.0,e_max=10000.0 ):

    import srxraylib.sources.srfunc as srfunc

    wigFile = "xshwig.sha"
    inData = ""

    nPer = 5 # 50
    nTrajPoints = 501
    ener_gev = 6.04
    per = 0.040
    kValue = 7.85
    trajFile = "tmp.traj"
    shift_x_flag = 0
    shift_x_value = 0.0
    shift_betax_flag = 0
    shift_betax_value = 0.0

    # "Calculate electron trajectory"
    (traj, pars) = srfunc.wiggler_trajectory(b_from=0,
                                             inData=inData,
                                             nPer=nPer,
                                             nTrajPoints=nTrajPoints,
                                             ener_gev=ener_gev,
                                             per=per,
                                             kValue=kValue,
                                             trajFile=trajFile,
                                             shift_x_flag=shift_x_flag,
                                             shift_x_value=shift_x_value,
                                             shift_betax_flag=shift_betax_flag,
                                             shift_betax_value=shift_betax_value)


    # traj[0,ii] = yx[i]
    # traj[1,ii] = yy[i]+j * per - start_len
    # traj[2,ii] = 0.0
    # traj[3,ii] = betax[i]
    # traj[4,ii] = betay[i]
    # traj[5,ii] = 0.0
    # traj[6,ii] = curv[i]
    # traj[7,ii] = bz[i]

    # plot(traj[1,:],traj[0,:])
    # print(pars)

    #
    # calculate cdf and write file for Shadow/Source
    #
    srfunc.wiggler_cdf(traj,
                       enerMin=e_min,
                       enerMax=e_max,
                       enerPoints=1001,
                       outFile=wigFile,
                       elliptical=False)

    print("CDF written to file %s \n"%(str(wigFile)))
Пример #5
0
def calc_wiggler_spectrum(ener_gev=6.0,e_min=100.0,e_max=100000.00,file_field="",output_file=""):

    (traj, pars) = srfunc.wiggler_trajectory(b_from=1,
                                             inData=file_field,
                                             nPer=1,
                                             nTrajPoints=501,
                                             ener_gev=ener_gev,
                                             per=None,
                                             kValue=None,
                                             trajFile="tmp.traj")

    x,y = srfunc.wiggler_spectrum(traj, enerMin=e_min, enerMax=e_max,nPoints=500, \
                     electronCurrent=0.2, outFile="", elliptical=False)

    #
    tmp = (numpy.vstack((x,y)))
    print(tmp.shape)
    numpy.savetxt(output_file,tmp.T)

    xx = numpy.array((5000.,10000,20000,40000,80000))
    return numpy.interp(xx,x,y)
Пример #6
0
    def runShadowSource(self):
        #self.error(self.error_id)
        self.setStatusMessage("")
        self.progressBarInit()

        sys.stdout = EmittingStream(textWritten=self.writeStdOut)
        if self.trace_shadow:
            grabber = TTYGrabber()
            grabber.start()

        try:
            self.checkFields()

            ###########################################
            # TODO: TO BE ADDED JUST IN CASE OF BROKEN
            #       ENVIRONMENT: MUST BE FOUND A PROPER WAY
            #       TO TEST SHADOW
            self.fixWeirdShadowBug()
            ###########################################

            wigFile = bytes(congruence.checkFileName("xshwig.sha"), 'utf-8')

            if self.type_combo == 0:
                inData = ""
            elif self.type_combo == 1:
                inData = congruence.checkUrl(self.file_with_b_vs_y)
            elif self.type_combo == 2:
                inData = congruence.checkUrl(self.file_with_harmonics)

            self.progressBarSet(10)
            #self.information(0, "Calculate electron trajectory")

            self.shadow_output.setText("")

            self.setStatusMessage("Calculate electron trajectory")


            (traj, pars) = srfunc.wiggler_trajectory(b_from=self.type_combo,
                                                     inData=inData,
                                                     nPer=self.number_of_periods,
                                                     nTrajPoints=501,
                                                     ener_gev=self.energy,
                                                     per=self.id_period,
                                                     kValue=self.k_value,
                                                     trajFile=congruence.checkFileName("tmp.traj"),
                                                     shift_x_flag=self.shift_x_flag,
                                                     shift_x_value=self.shift_x_value,
                                                     shift_betax_flag=self.shift_betax_flag,
                                                     shift_betax_value=self.shift_betax_value)

            #
            # calculate cdf and write file for Shadow/Source
            #

            self.progressBarSet(20)
            #self.information(0, "Calculate cdf and write file for Shadow/Source")
            self.setStatusMessage("Calculate cdf and write file for Shadow/Source")

            srfunc.wiggler_cdf(traj,
                               enerMin=self.e_min,
                               enerMax=self.e_max,
                               enerPoints=1001,
                               outFile=wigFile,
                               elliptical=False)

            #self.information(0, "CDF written to file %s \n"%(wigFile))
            self.setStatusMessage("CDF written to file %s \n"%(str(wigFile)))

            self.progressBarSet(40)

            #self.information(0, "Set the wiggler parameters in the wiggler container")
            self.setStatusMessage("Set the wiggler parameters in the wiggler container")

            shadow_src = ShadowSource.create_wiggler_src()

            self.populateFields(shadow_src)

            shadow_src.src.FILE_TRAJ = wigFile


            self.progressBarSet(50)

            self.setStatusMessage("Running Shadow/Source")

            write_begin_file, write_start_file, write_end_file = self.get_write_file_options()

            beam_out = ShadowBeam.traceFromSource(shadow_src,
                                                  write_begin_file=write_begin_file,
                                                  write_start_file=write_start_file,
                                                  write_end_file=write_end_file)

            if self.trace_shadow:
                grabber.stop()

                for row in grabber.ttyData:
                   self.writeStdOut(row)

            #self.information(0, "Plotting Results")
            self.setStatusMessage("Plotting Results")

            self.progressBarSet(80)

            self.plot_results(beam_out, progressBarValue=80)

            self.setStatusMessage("Plotting Wiggler Data")

            self.plot_wiggler_results()

            #self.information()
            self.setStatusMessage("")

            self.send("Beam", beam_out)

            #
            # create python script for the preprocessors and display in the standard output
            #
            dict_parameters = {
                "b_from"               : self.type_combo,
                "inData"               : inData,
                "nPer"                 : self.number_of_periods,
                "nTrajPoints"          : 501,
                "ener_gev"             : self.energy,
                "per"                  : self.id_period,
                "kValue"               : self.k_value,
                "trajFile"             : "tmp.traj",
                "shift_x_flag"         : self.shift_x_flag,
                "shift_x_value"        : self.shift_x_value,
                "shift_betax_flag"     : self.shift_betax_flag,
                "shift_betax_value"    : self.shift_betax_value,
                "enerMin"              : self.e_min,
                "enerMax"              : self.e_max,
                "enerPoints"           : 1001,
                "outFile"              : wigFile,
                "elliptical"           : False,
                "electron_current_mA"  : self.electron_current,
            }

            # write python script in standard output
            print(self.script_template().format_map(dict_parameters))

        except Exception as exception:
            QtWidgets.QMessageBox.critical(self, "Error",
                                       str(exception),
                QtWidgets.QMessageBox.Ok)

            #self.error_id = self.error_id + 1
            #self.error(self.error_id, "Exception occurred: " + str(exception))


        self.progressBarFinished()
Пример #7
0
    def runShadowSource(self):
        #self.error(self.error_id)
        self.setStatusMessage("")
        self.progressBarInit()

        try:
            self.checkFields()

            ###########################################
            # TODO: TO BE ADDED JUST IN CASE OF BROKEN
            #       ENVIRONMENT: MUST BE FOUND A PROPER WAY
            #       TO TEST SHADOW
            self.fixWeirdShadowBug()
            ###########################################

            wigFile = bytes(congruence.checkFileName("xshwig.sha"), 'utf-8')

            if self.type_combo == 0:
                inData = ""
            elif self.type_combo == 1:
                inData = congruence.checkFileName(self.file_with_b_vs_y)
            elif self.type_combo == 2:
                inData = congruence.checkFileName(self.file_with_harmonics)

            self.progressBarSet(10)
            #self.information(0, "Calculate electron trajectory")
            self.setStatusMessage("Calculate electron trajectory")

            (traj, pars) = srfunc.wiggler_trajectory(b_from=self.type_combo,
                                                     inData=inData,
                                                     nPer=self.number_of_periods,
                                                     nTrajPoints=501,
                                                     ener_gev=self.energy,
                                                     per=self.id_period,
                                                     kValue=self.k_value,
                                                     trajFile=congruence.checkFileName("tmp.traj"),
                                                     shift_x_flag=self.shift_x_flag,
                                                     shift_x_value=self.shift_x_value,
                                                     shift_betax_flag=self.shift_betax_flag,
                                                     shift_betax_value=self.shift_betax_value)

            #
            # calculate cdf and write file for Shadow/Source
            #

            self.progressBarSet(20)
            #self.information(0, "Calculate cdf and write file for Shadow/Source")
            self.setStatusMessage("Calculate cdf and write file for Shadow/Source")

            srfunc.wiggler_cdf(traj,
                               enerMin=self.e_min,
                               enerMax=self.e_max,
                               enerPoints=1001,
                               outFile=wigFile,
                               elliptical=False)

            #self.information(0, "CDF written to file %s \n"%(wigFile))
            self.setStatusMessage("CDF written to file %s \n"%(str(wigFile)))

            self.progressBarSet(40)

            #self.information(0, "Set the wiggler parameters in the wiggler container")
            self.setStatusMessage("Set the wiggler parameters in the wiggler container")

            shadow_src = ShadowSource.create_wiggler_src()

            self.populateFields(shadow_src)

            shadow_src.src.FILE_TRAJ = wigFile

            sys.stdout = EmittingStream(textWritten=self.writeStdOut)
            if self.trace_shadow:
                grabber = TTYGrabber()
                grabber.start()

            self.progressBarSet(50)

            self.setStatusMessage("Running Shadow/Source")

            write_begin_file, write_start_file, write_end_file = self.get_write_file_options()

            beam_out = ShadowBeam.traceFromSource(shadow_src,
                                                  write_begin_file=write_begin_file,
                                                  write_start_file=write_start_file,
                                                  write_end_file=write_end_file)

            if self.trace_shadow:
                grabber.stop()

                for row in grabber.ttyData:
                   self.writeStdOut(row)

            #self.information(0, "Plotting Results")
            self.setStatusMessage("Plotting Results")

            self.progressBarSet(80)

            self.plot_results(beam_out, 80)

            self.setStatusMessage("Plotting Wiggler Data")

            self.plot_wiggler_results()

            #self.information()
            self.setStatusMessage("")

            self.send("Beam", beam_out)
        except Exception as exception:
            QtGui.QMessageBox.critical(self, "Error",
                                       str(exception),
                QtGui.QMessageBox.Ok)

            #self.error_id = self.error_id + 1
            #self.error(self.error_id, "Exception occurred: " + str(exception))


        self.progressBarFinished()
Пример #8
0
def run_source_wiggler():
    from srxraylib.sources import srfunc
    (traj,
     pars) = srfunc.wiggler_trajectory(b_from=1,
                                       inData="/home/manuel/Oasys/BM_only7.b",
                                       nPer=1,
                                       nTrajPoints=501,
                                       ener_gev=2.0,
                                       per=0.01,
                                       kValue=1.0,
                                       trajFile="tmp.traj",
                                       shift_x_flag=4,
                                       shift_x_value=0.042,
                                       shift_betax_flag=4,
                                       shift_betax_value=0.035)

    #
    # calculate cdf and write file for Shadow/Source
    #

    srfunc.wiggler_cdf(traj,
                       enerMin=1000.0,
                       enerMax=1000.1,
                       enerPoints=1001,
                       outFile=b'/home/manuel/Oasys/xshwig.sha',
                       elliptical=False)

    calculate_spectrum = False

    if calculate_spectrum:
        e, f, w = srfunc.wiggler_spectrum(traj,
                                          enerMin=1000.0,
                                          enerMax=1000.1,
                                          nPoints=500,
                                          electronCurrent=500.0 * 1e-3,
                                          outFile="spectrum.dat",
                                          elliptical=False)
        from srxraylib.plot.gol import plot
        plot(e,
             f,
             xlog=False,
             ylog=False,
             show=False,
             xtitle="Photon energy [eV]",
             ytitle="Flux [Photons/s/0.1%bw]",
             title="Flux")
        plot(e,
             w,
             xlog=False,
             ylog=False,
             show=True,
             xtitle="Photon energy [eV]",
             ytitle="Spectral Power [E/eV]",
             title="Spectral Power")
    #
    # end script
    #

    # write (1) or not (0) SHADOW files start.xx end.xx star.xx
    iwrite = 0

    #
    # initialize shadow3 source (oe0) and beam
    #
    beam = Shadow.Beam()
    oe0 = Shadow.Source()

    #
    # Define variables. See meaning of variables in:
    #  https://raw.githubusercontent.com/srio/shadow3/master/docs/source.nml
    #  https://raw.githubusercontent.com/srio/shadow3/master/docs/oe.nml
    #

    oe0.BENER = 2.0
    oe0.CONV_FACT = 1.0
    oe0.EPSI_X = 70e-12
    oe0.EPSI_Z = 70e-12
    oe0.FDISTR = 0
    oe0.FILE_TRAJ = b'/home/manuel/Oasys/xshwig.sha'
    oe0.FSOUR = 0
    oe0.FSOURCE_DEPTH = 0
    oe0.F_COLOR = 0
    oe0.F_PHOT = 0
    oe0.F_WIGGLER = 1
    oe0.HDIV1 = 1.0
    oe0.HDIV2 = 1.0
    oe0.IDO_VX = 0
    oe0.IDO_VZ = 0
    oe0.IDO_X_S = 0
    oe0.IDO_Y_S = 0
    oe0.IDO_Z_S = 0
    oe0.ISTAR1 = 5676561
    oe0.NCOL = 0
    oe0.NPOINT = 50000
    oe0.N_COLOR = 0
    oe0.PH1 = 1000.0
    oe0.PH2 = 1000.1
    oe0.POL_DEG = 0.0
    oe0.SIGMAX = 7e-06
    oe0.SIGMAY = 0.0
    oe0.SIGMAZ = 1e-05
    oe0.VDIV1 = 1.0
    oe0.VDIV2 = 1.0
    oe0.WXSOU = 0.0
    oe0.WYSOU = 0.0
    oe0.WZSOU = 0.0

    #Run SHADOW to create the source

    if iwrite:
        oe0.write("start.00")

    beam.genSource(oe0)

    if iwrite:
        oe0.write("end.00")
        beam.write("begin.dat")

    return beam
Пример #9
0
def xoppy_calc_wiggler_radiation(
    ELECTRONENERGY=3.0,
    ELECTRONCURRENT=0.1,
    PERIODID=0.120,
    NPERIODS=37.0,
    KV=22.416,
    DISTANCE=30.0,
    HSLITPOINTS=500,
    VSLITPOINTS=500,
    PHOTONENERGYMIN=100.0,
    PHOTONENERGYMAX=100100.0,
    PHOTONENERGYPOINTS=101,
    NTRAJPOINTS=1001,
    FIELD=0,
    FILE="/Users/srio/Oasys/Bsin.txt",
    POLARIZATION=0,  # 0=total, 1=parallel (s), 2=perpendicular (p)
    SHIFT_X_FLAG=0,
    SHIFT_X_VALUE=0.0,
    SHIFT_BETAX_FLAG=0,
    SHIFT_BETAX_VALUE=0.0,
    CONVOLUTION=1,
    PASSEPARTOUT=3.0,
    h5_file="wiggler_radiation.h5",
    h5_entry_name="XOPPY_RADIATION",
    h5_initialize=True,
    h5_parameters=None,
    do_plot=False,
):

    # calculate wiggler trajectory
    if FIELD == 0:
        (traj, pars) = srfunc.wiggler_trajectory(
            b_from=0,
            inData="",
            nPer=int(NPERIODS),  #37,
            nTrajPoints=NTRAJPOINTS,
            ener_gev=ELECTRONENERGY,
            per=PERIODID,
            kValue=KV,
            trajFile="",
            shift_x_flag=SHIFT_X_FLAG,
            shift_x_value=SHIFT_X_VALUE,
            shift_betax_flag=SHIFT_BETAX_FLAG,
            shift_betax_value=SHIFT_BETAX_VALUE)
    if FIELD == 1:
        # magnetic field from B(s) map
        (traj,
         pars) = srfunc.wiggler_trajectory(b_from=1,
                                           nPer=1,
                                           nTrajPoints=NTRAJPOINTS,
                                           ener_gev=ELECTRONENERGY,
                                           inData=FILE,
                                           trajFile="",
                                           shift_x_flag=SHIFT_X_FLAG,
                                           shift_x_value=SHIFT_X_VALUE,
                                           shift_betax_flag=SHIFT_BETAX_FLAG,
                                           shift_betax_value=SHIFT_BETAX_FLAG)
    if FIELD == 2:
        raise ("Not implemented")

    energy, flux, power = srfunc.wiggler_spectrum(
        traj,
        enerMin=PHOTONENERGYMIN,
        enerMax=PHOTONENERGYMAX,
        nPoints=PHOTONENERGYPOINTS,
        electronCurrent=ELECTRONCURRENT,
        outFile="",
        elliptical=False,
        polarization=POLARIZATION)

    try:
        cumulated_power = power.cumsum() * numpy.abs(energy[0] - energy[1])
    except:
        cumulated_power = 0.0
    print("\nPower from integral of spectrum (sum rule): %8.3f W" %
          (cumulated_power[-1]))

    try:
        cumulated_power = cumtrapz(power, energy, initial=0)
    except:
        cumulated_power = 0.0
    print("Power from integral of spectrum (trapezoid rule): %8.3f W" %
          (cumulated_power[-1]))

    codata_mee = 1e-6 * codata.m_e * codata.c**2 / codata.e  # electron mass in meV
    gamma = ELECTRONENERGY * 1e3 / codata_mee

    Y = traj[1, :].copy()
    divX = traj[3, :].copy()
    By = traj[7, :].copy()

    # rho = (1e9 / codata.c) * ELECTRONENERGY / By
    # Ec0 = 3 * codata.h * codata.c * gamma**3 / (4 * numpy.pi * rho) / codata.e
    # Ec = 665.0 * ELECTRONENERGY**2 * numpy.abs(By)
    # Ecmax = 665.0 * ELECTRONENERGY** 2 * (numpy.abs(By)).max()
    coeff = 3 / (
        4 *
        numpy.pi) * codata.h * codata.c**2 / codata_mee**3 / codata.e  # ~665.0
    Ec = coeff * ELECTRONENERGY**2 * numpy.abs(By)
    Ecmax = coeff * ELECTRONENERGY**2 * (numpy.abs(By)).max()

    # approx formula for divergence (first formula in pag 43 of Tanaka's paper)
    sigmaBp = 0.597 / gamma * numpy.sqrt(Ecmax / PHOTONENERGYMIN)

    # we use vertical interval 6*sigmaBp and horizontal interval = vertical + trajectory interval

    divXX = numpy.linspace(divX.min() - PASSEPARTOUT * sigmaBp,
                           divX.max() + PASSEPARTOUT * sigmaBp, HSLITPOINTS)

    divZZ = numpy.linspace(-PASSEPARTOUT * sigmaBp, PASSEPARTOUT * sigmaBp,
                           VSLITPOINTS)

    e = numpy.linspace(PHOTONENERGYMIN, PHOTONENERGYMAX, PHOTONENERGYPOINTS)

    p = numpy.zeros((PHOTONENERGYPOINTS, HSLITPOINTS, VSLITPOINTS))

    for i in range(e.size):
        Ephoton = e[i]

        # vertical divergence
        intensity = srfunc.sync_g1(Ephoton / Ec, polarization=POLARIZATION)

        Ecmean = (Ec * intensity).sum() / intensity.sum()

        fluxDivZZ = srfunc.sync_ang(1,
                                    divZZ * 1e3,
                                    polarization=POLARIZATION,
                                    e_gev=ELECTRONENERGY,
                                    i_a=ELECTRONCURRENT,
                                    hdiv_mrad=1.0,
                                    energy=Ephoton,
                                    ec_ev=Ecmean)

        if do_plot:
            from srxraylib.plot.gol import plot
            plot(divZZ,
                 fluxDivZZ,
                 title="min intensity %f" % fluxDivZZ.min(),
                 xtitle="divZ",
                 ytitle="fluxDivZZ",
                 show=1)

        # horizontal divergence after Tanaka
        if False:
            e_over_ec = Ephoton / Ecmax
            uudlim = 1.0 / gamma
            uud = numpy.linspace(-uudlim * 0.99, uudlim * 0.99, divX.size)
            uu = e_over_ec / numpy.sqrt(1 - gamma**2 * uud**2)
            plot(uud, 2 * numpy.pi / numpy.sqrt(3) * srfunc.sync_g1(uu))

        # horizontal divergence
        # intensity = srfunc.sync_g1(Ephoton / Ec, polarization=POLARIZATION)
        intensity_interpolated = interpolate_multivalued_function(
            divX,
            intensity,
            divXX,
            Y,
        )

        if CONVOLUTION:  # do always convolution!
            intensity_interpolated.shape = -1
            divXX_window = divXX[-1] - divXX[0]
            divXXCC = numpy.linspace(-0.5 * divXX_window, 0.5 * divXX_window,
                                     divXX.size)
            fluxDivZZCC = srfunc.sync_ang(1,
                                          divXXCC * 1e3,
                                          polarization=POLARIZATION,
                                          e_gev=ELECTRONENERGY,
                                          i_a=ELECTRONCURRENT,
                                          hdiv_mrad=1.0,
                                          energy=Ephoton,
                                          ec_ev=Ecmax)
            fluxDivZZCC.shape = -1

            intensity_convolved = numpy.convolve(
                intensity_interpolated / intensity_interpolated.max(),
                fluxDivZZCC / fluxDivZZCC.max(),
                mode='same')
        else:
            intensity_convolved = intensity_interpolated

        if i == 0:
            print(
                "\n\n============ sizes vs photon energy ======================="
            )
            print(
                "Photon energy/eV  FWHM X'/urad  FWHM Y'/urad  FWHM X/mm  FWHM Z/mm "
            )

        print("%16.3f  %12.3f  %12.3f  %9.2f  %9.2f" %
              (Ephoton, 1e6 * get_fwhm(intensity_convolved, divXX)[0],
               1e6 * get_fwhm(fluxDivZZ, divZZ)[0],
               1e3 * get_fwhm(intensity_convolved, divXX)[0] * DISTANCE,
               1e3 * get_fwhm(fluxDivZZ, divZZ)[0] * DISTANCE))

        if do_plot:
            plot(divX,
                 intensity / intensity.max(),
                 divXX,
                 intensity_interpolated / intensity_interpolated.max(),
                 divXX,
                 intensity_convolved / intensity_convolved.max(),
                 divXX,
                 fluxDivZZCC / fluxDivZZCC.max(),
                 title="min intensity %f, Ephoton=%6.2f" %
                 (intensity.min(), Ephoton),
                 xtitle="divX",
                 ytitle="intensity",
                 legend=["orig", "interpolated", "convolved", "kernel"],
                 show=1)

        # combine H * V
        INTENSITY = numpy.outer(
            intensity_convolved / intensity_convolved.max(),
            fluxDivZZ / fluxDivZZ.max())
        p[i, :, :] = INTENSITY

        if do_plot:
            from srxraylib.plot.gol import plot_image, plot_surface, plot_show
            plot_image(INTENSITY,
                       divXX,
                       divZZ,
                       aspect='auto',
                       title="E=%6.2f" % Ephoton,
                       show=1)
            # to create oasys icon...
            # plot_surface(INTENSITY, divXX, divZZ, title="", show=0)
            # import matplotlib.pylab as plt
            # plt.xticks([])
            # plt.yticks([])
            # plt.axis('off')
            # plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off',
            #                 labeltop='off', labelright='off', labelbottom='off')
            #
            # plot_show()
    #

    h = divXX * DISTANCE * 1e3  # in mm for the h5 file
    v = divZZ * DISTANCE * 1e3  # in mm for the h5 file

    print("\nWindow size: %f mm [H] x %f mm [V]" %
          (h[-1] - h[0], v[-1] - v[0]))
    print("Window size: %g rad [H] x %g rad [V]" %
          (divXX[-1] - divXX[0], divZZ[-1] - divZZ[0]))

    # normalization and total flux
    for i in range(e.size):
        INTENSITY = p[i, :, :]
        # norm = INTENSITY.sum() * (h[1] - h[0]) * (v[1] - v[0])
        norm = trapezoidal_rule_2d_1darrays(INTENSITY, h, v)
        p[i, :, :] = INTENSITY / norm * flux[i]

    # fit
    fit_ok = False
    try:
        power = p.sum(axis=0) * (e[1] - e[0]) * codata.e * 1e3
        print(
            "\n\n============= Fitting power density to a 2D Gaussian. ==============\n"
        )
        print(
            "Please use these results with care: check if the original data looks like a Gaussian."
        )
        fit_parameters = fit_gaussian2d(power, h, v)
        print(info_params(fit_parameters))
        H, V = numpy.meshgrid(h, v)
        data_fitted = twoD_Gaussian((H, V), *fit_parameters)
        print("  Total power (sum rule) in the fitted data [W]: ",
              data_fitted.sum() * (h[1] - h[0]) * (v[1] - v[0]))
        # plot_image(data_fitted.reshape((h.size,v.size)),h, v,title="FIT")
        print("====================================================\n")
        fit_ok = True
    except:
        pass

    # output file
    if h5_file != "":
        try:
            if h5_initialize:
                h5w = H5SimpleWriter.initialize_file(
                    h5_file, creator="xoppy_wigglers.py")
            else:
                h5w = H5SimpleWriter(h5_file, None)
            h5w.create_entry(h5_entry_name, nx_default=None)
            h5w.add_stack(e,
                          h,
                          v,
                          p,
                          stack_name="Radiation",
                          entry_name=h5_entry_name,
                          title_0="Photon energy [eV]",
                          title_1="X gap [mm]",
                          title_2="Y gap [mm]")
            h5w.create_entry("parameters",
                             root_entry=h5_entry_name,
                             nx_default=None)
            if h5_parameters is not None:
                for key in h5_parameters.keys():
                    h5w.add_key(key,
                                h5_parameters[key],
                                entry_name=h5_entry_name + "/parameters")
            h5w.create_entry("trajectory",
                             root_entry=h5_entry_name,
                             nx_default="transversal trajectory")
            h5w.add_key("traj", traj, entry_name=h5_entry_name + "/trajectory")
            h5w.add_dataset(traj[1, :],
                            traj[0, :],
                            dataset_name="transversal trajectory",
                            entry_name=h5_entry_name + "/trajectory",
                            title_x="s [m]",
                            title_y="X [m]")
            h5w.add_dataset(traj[1, :],
                            traj[3, :],
                            dataset_name="transversal velocity",
                            entry_name=h5_entry_name + "/trajectory",
                            title_x="s [m]",
                            title_y="Vx/c")
            h5w.add_dataset(traj[1, :],
                            traj[7, :],
                            dataset_name="Magnetic field",
                            entry_name=h5_entry_name + "/trajectory",
                            title_x="s [m]",
                            title_y="Bz [T]")
            if fit_ok:
                h5w.add_image(power,
                              h,
                              v,
                              image_name="PowerDensity",
                              entry_name=h5_entry_name,
                              title_x="X [mm]",
                              title_y="Y [mm]")

                h5w.add_image(data_fitted.reshape(h.size, v.size),
                              h,
                              v,
                              image_name="PowerDensityFit",
                              entry_name=h5_entry_name,
                              title_x="X [mm]",
                              title_y="Y [mm]")
                h5w.add_key("fit_info",
                            info_params(fit_parameters),
                            entry_name=h5_entry_name + "/PowerDensityFit")
            print("File written to disk: %s" % h5_file)
        except:
            print("ERROR initializing h5 file")

    return e, h, v, p, traj
Пример #10
0
def calculate_flux(y, B, select_mode=0, energy_GeV=2.0, do_plot=False):
    # analyse M1

    B3 = B.copy()

    # if M==1:
    #     ibad = numpy.argwhere(y > -0.2)
    #     B3[ibad] = 0.0
    # elif M==2:
    #     ibad = numpy.argwhere( numpy.abs(y) > 0.2)
    #     B3[ibad] = 0.0
    # elif M==3:
    #     ibad = numpy.argwhere(y < 0.2)
    #     B3[ibad] = 0.0
    # else:
    #     pass

    # select_mode = 2  # 0=all, 1=Mag7, 2=Mag8, 3=both RB only, 4=RB1, 5=RB2

    if select_mode == 0:
        pass
    elif select_mode == 1:
        ibad = numpy.where(y < -0.3)
        B3[ibad] = 0.0

        ibad = numpy.where(y > 0.3)
        B3[ibad] = 0.0

    elif select_mode == 2:
        ibad = numpy.where(y < 0.66)
        B3[ibad] = 0.0

    elif select_mode == 3:
        ibad = numpy.where(numpy.abs(y) < 0.3)
        B3[ibad] = 0.0

        ibad = numpy.where(y > 0.66)
        B3[ibad] = 0.0

    elif select_mode == 4:
        ibad = numpy.where(y > -0.3)
        B3[ibad] = 0.0

    elif select_mode == 5:
        ibad = numpy.where(y < 0.3)
        B3[ibad] = 0.0

        ibad = numpy.where(y > 0.66)
        B3[ibad] = 0.0

    if do_plot:
        from srxraylib.plot.gol import plot, set_qt
        plot(y, B3, title="select_mode=%d" % select_mode)

    tmp = numpy.vstack((y, B3)).T
    print(">>>>", tmp.shape, tmp[:, 0])

    (traj, pars) = srfunc.wiggler_trajectory(
        b_from=1,
        inData=tmp,  #"BM_first.b",
        nPer=1,
        nTrajPoints=501,
        ener_gev=energy_GeV,
        per=0.01,
        kValue=1.0,
        trajFile="tmp.traj",
        shift_x_flag=5,
        shift_x_value=0.042,
        shift_betax_flag=4,
        shift_betax_value=0.0324)

    calculate_spectrum = True

    if calculate_spectrum:
        e, f, w = srfunc.wiggler_spectrum(traj,
                                          enerMin=0.0010,
                                          enerMax=10000.1,
                                          nPoints=500,
                                          electronCurrent=500.0 * 1e-3,
                                          outFile="spectrum.dat",
                                          elliptical=False)
        from srxraylib.plot.gol import plot

    return e, f, w
Пример #11
0
    def __calculate_radiation(self):

        wiggler = self.get_magnetic_structure()
        electron_beam = self.get_electron_beam()

        if wiggler._magnetic_field_periodic == 1:

            (traj, pars) = wiggler_trajectory(
                b_from=0,
                inData="",
                nPer=wiggler.number_of_periods(),
                nTrajPoints=wiggler._NG_J,
                ener_gev=electron_beam._energy_in_GeV,
                per=wiggler.period_length(),
                kValue=wiggler.K_vertical(),
                trajFile="",
            )

        elif wiggler._magnetic_field_periodic == 0:

            print(">>>>>>>>>>>>>>>>>>>>>>", "shift_x_flag =      ",
                  wiggler._shift_x_flag, "shift_x_value =     ",
                  wiggler._shift_x_value, "shift_betax_flag =  ",
                  wiggler._shift_betax_flag, "shift_betax_value = ",
                  wiggler._shift_betax_value)

            (traj, pars) = wiggler_trajectory(
                b_from=1,
                inData=wiggler._file_with_magnetic_field,
                nPer=1,
                nTrajPoints=wiggler._NG_J,
                ener_gev=electron_beam._energy_in_GeV,
                # per=self.syned_wiggler.period_length(),
                # kValue=self.syned_wiggler.K_vertical(),
                trajFile="",
                shift_x_flag=wiggler._shift_x_flag,
                shift_x_value=wiggler._shift_x_value,
                shift_betax_flag=wiggler._shift_betax_flag,
                shift_betax_value=wiggler._shift_betax_value,
            )

        self.__result_trajectory = traj
        self.__result_parameters = pars

        # print(">>>>>>>>>> traj pars: ",traj.shape,pars)
        #
        # plot(traj[1, :], traj[0, :], xtitle="Y", ytitle="X")
        # plot(traj[1, :], traj[3, :], xtitle="Y", ytitle="BetaX")
        # plot(traj[1, :], traj[6, :], xtitle="Y", ytitle="Curvature")
        # plot(traj[1, :], traj[7, :], xtitle="Y", ytitle="B")

        # traj[0,ii] = yx[i]
        # traj[1,ii] = yy[i]+j * per - start_len
        # traj[2,ii] = 0.0
        # traj[3,ii] = betax[i]
        # traj[4,ii] = betay[i]
        # traj[5,ii] = 0.0
        # traj[6,ii] = curv[i]
        # traj[7,ii] = bz[i]

        #
        # calculate cdf and write file for Shadow/Source
        #

        print(
            ">>>>>>>>>>>>>>>>>>>>  wiggler._EMIN,wiggler._EMAX,wiggler._NG_E",
            wiggler._EMIN, wiggler._EMAX, wiggler._NG_E)
        self.__result_cdf = wiggler_cdf(self.__result_trajectory,
                                        enerMin=wiggler._EMIN,
                                        enerMax=wiggler._EMAX,
                                        enerPoints=wiggler._NG_E,
                                        outFile="tmp.cdf",
                                        elliptical=False)
Пример #12
0
#
from srxraylib.sources import srfunc
from srxraylib.plot.gol import plot, plot_image
from srxraylib.sources.srfunc import sync_g1, sync_f
import numpy
import scipy.constants as codata

ener_gev = 2.0
current = 0.5

(traj, pars) = srfunc.wiggler_trajectory(b_from=0,
                                         inData="",
                                         nPer=137,
                                         nTrajPoints=501,
                                         ener_gev=ener_gev,
                                         per=0.0288,
                                         kValue=3.07,
                                         trajFile="tmp.traj",
                                         shift_x_flag=0,
                                         shift_x_value=0.0,
                                         shift_betax_flag=0,
                                         shift_betax_value=0.0)

#  0      1    2      3      4     5       6         7
#L x[m]  y[m]  z[m]  BetaX  BetaY  BetaZ  Curvature  B[T]
print(traj.shape)

xp = traj[3, :]
b0 = traj[7, :]

# plot(1e6*xp,numpy.abs(b0),xtitle="xp")
Пример #13
0
def calculate_spectrum(emin, emax, npoints=500, do_plot=False):
    #
    # script to run the wiggler preprocessor (created by ShadowOui:Wiggler)
    #

    (traj, pars) = srfunc.wiggler_trajectory(b_from=1,
                                             inData="Bz_Alba_rev3.dat",
                                             nPer=1,
                                             nTrajPoints=501,
                                             ener_gev=2.5,
                                             per=0.755,
                                             kValue=211.0,
                                             trajFile="tmp.traj",
                                             shift_x_flag=4,
                                             shift_x_value=0.0,
                                             shift_betax_flag=4,
                                             shift_betax_value=0.0)

    #
    # calculate cdf and write file for Shadow/Source
    #

    srfunc.wiggler_cdf(traj,
                       enerMin=emin,
                       enerMax=emax,
                       enerPoints=1001,
                       outFile=b'xshwig.sha',
                       elliptical=False)

    calculate_spectrum = True

    if calculate_spectrum:
        e, f, w = srfunc.wiggler_spectrum(traj,
                                          enerMin=emin,
                                          enerMax=emax,
                                          nPoints=npoints,
                                          electronCurrent=400 * 1e-3,
                                          outFile="spectrum.dat",
                                          elliptical=False)

        if do_plot:
            from srxraylib.plot.gol import plot
            plot(e,
                 f,
                 xlog=False,
                 ylog=False,
                 show=False,
                 xtitle="Photon energy [eV]",
                 ytitle="Flux [Photons/s/0.1%bw]",
                 title="Flux")
            plot(e,
                 w,
                 xlog=False,
                 ylog=False,
                 show=False,
                 xtitle="Photon energy [eV]",
                 ytitle="Spectral Power [W/eV]",
                 title="Spectral Power")
    #
    # end script
    #
    return e, w
Пример #14
0
def run_shadow3(photon_energy, n_rays=5e5, emittance=True):
    #
    # script to run the wiggler preprocessor (created by ShadowOui:Wiggler)
    #

    (traj, pars) = srfunc.wiggler_trajectory(b_from=1,
                                             inData="Bz_Alba_rev3.dat",
                                             nPer=1,
                                             nTrajPoints=501,
                                             ener_gev=2.5,
                                             per=0.755,
                                             kValue=211.0,
                                             trajFile="tmp.traj",
                                             shift_x_flag=4,
                                             shift_x_value=0.0,
                                             shift_betax_flag=4,
                                             shift_betax_value=0.0)

    #
    # calculate cdf and write file for Shadow/Source
    #

    srfunc.wiggler_cdf(
        traj,
        enerMin=photon_energy,  # 5000.0,
        enerMax=photon_energy + 1.0,
        enerPoints=1001,
        outFile=b'xshwig.sha',
        elliptical=False)

    #
    # end script
    #

    #
    #
    # Python script to run shadow3. Created automatically with ShadowTools.make_python_script_from_list().

    # write (1) or not (0) SHADOW files start.xx end.xx star.xx
    iwrite = 0

    #
    # initialize shadow3 source (oe0) and beam
    #
    beam = Shadow.Beam()
    oe0 = Shadow.Source()
    oe1 = Shadow.OE()

    #
    # Define variables. See meaning of variables in:
    #  https://raw.githubusercontent.com/srio/shadow3/master/docs/source.nml
    #  https://raw.githubusercontent.com/srio/shadow3/master/docs/oe.nml
    #

    oe0.BENER = 2.5
    oe0.CONV_FACT = 1000.0
    # oe0.EPSI_X = 2.574e-05
    # oe0.EPSI_Z = 2.574e-07
    if emittance:
        oe0.EPSI_X = 2.574e-05
        oe0.EPSI_Z = 2.574e-07
    oe0.FDISTR = 0
    oe0.FILE_TRAJ = b'xshwig.sha'
    oe0.FSOUR = 0
    oe0.FSOURCE_DEPTH = 0
    oe0.F_COLOR = 0
    oe0.F_PHOT = 0
    oe0.F_WIGGLER = 1
    oe0.HDIV1 = 1.0
    oe0.HDIV2 = 1.0
    oe0.IDO_VX = 0
    oe0.IDO_VZ = 0
    oe0.IDO_X_S = 0
    oe0.IDO_Y_S = 0
    oe0.IDO_Z_S = 0
    oe0.ISTAR1 = 420024
    oe0.NCOL = 0
    oe0.NPOINT = n_rays
    oe0.N_COLOR = 0
    oe0.POL_DEG = 0.0
    # oe0.PH1 = 40000.0
    # oe0.PH2 = 40001.0
    oe0.SIGMAX = 0.8208
    oe0.SIGMAZ = 0.014
    if emittance:
        oe0.SIGMAX = 0.8208
        oe0.SIGMAZ = 0.0142
    else:
        oe0.SIGMAX = 0.0
        oe0.SIGMAZ = 0.0

    oe0.SIGMAY = 0.0
    oe0.VDIV1 = 1.0
    oe0.VDIV2 = 1.0
    oe0.WXSOU = 0.0
    oe0.WYSOU = 0.0
    oe0.WZSOU = 0.0

    oe1.DUMMY = 0.1
    oe1.FWRITE = 3
    oe1.F_REFRAC = 2
    oe1.F_SCREEN = 1
    oe1.N_SCREEN = 1
    oe1.T_IMAGE = 0.0
    oe1.T_INCIDENCE = 0.0
    oe1.T_REFLECTION = 180.0
    oe1.T_SOURCE = 30000.0

    # Run SHADOW to create the source

    if iwrite:
        oe0.write("start.00")

    beam.genSource(oe0)

    if iwrite:
        oe0.write("end.00")
        beam.write("begin.dat")

    return beam, oe0