示例#1
0
    def compare_undul_phot_files(self,
                                 file1,
                                 file2,
                                 do_plot=DO_PLOT,
                                 do_assert=True):
        print("Comparing undul_phot output files: %s %s" % (file1, file2))

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

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

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

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

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

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

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

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

            plot_show()

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

        self.setStatusMessage("")
        self.progressBarInit()

        # this is to be able to start the widget out of Oasys
        try:
            tmp = self.workspace_units
        except:
            self.workspace_units = 'm'
            self.workspace_units_label = 'm'
            self.workspace_units_to_m = 1.0
            self.workspace_units_to_cm = 1e2
            self.workspace_units_to_mm = 1e3

        self.checkFields()

        self.progressBarSet(10)

        self.setStatusMessage("Running SHADOW")

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

        self.progressBarSet(50)

        try:
            self.shadow_output.setText("")
            su = Undulator.initialize_as_vertical_undulator(
                K=self.K,
                period_length=self.period_length,
                periods_number=int(self.periods_number))

            ebeam = ElectronBeam(energy_in_GeV=self.energy_in_GeV,
                                 energy_spread=0.0,
                                 current=self.current,
                                 number_of_bunches=1,
                                 moment_xx=(self.sigma_x)**2,
                                 moment_xxp=0.0,
                                 moment_xpxp=(self.sigma_divergence_x)**2,
                                 moment_yy=(self.sigma_z)**2,
                                 moment_yyp=0.0,
                                 moment_ypyp=(self.sigma_divergence_z)**2)

            print(ebeam.info())

            codes = ["internal", "pySRU", "SRW"]
            selected_code = codes[self.code_undul_phot]

            self.sourceundulator = SourceUndulator(
                name="shadowOui-Full-Undulator",
                syned_electron_beam=ebeam,
                syned_undulator=su,
                flag_emittance=self.use_emittances_combo,
                flag_size=self.flag_size,
                emin=1000,  # to be set later
                emax=1001,  # to be set later
                ng_e=2,  # to be set later
                maxangle=self.maxangle_urad * 1e-6,
                ng_t=self.ng_t,
                ng_p=self.ng_p,
                ng_j=self.ng_j,
                code_undul_phot=selected_code)

            if self.set_at_resonance == 0:
                if self.delta_e == 0:
                    self.sourceundulator.set_energy_box(
                        self.photon_energy, self.photon_energy, 1)
                else:
                    self.sourceundulator.set_energy_box(
                        self.photon_energy - 0.5 * self.delta_e,
                        self.photon_energy + 0.5 * self.delta_e, self.ng_e)
            else:
                self.sourceundulator.set_energy_monochromatic_at_resonance(
                    self.harmonic)
                if self.delta_e > 0.0:
                    e0, e1, ne = self.sourceundulator.get_energy_box()
                    self.sourceundulator.set_energy_box(
                        e0 - 0.5 * self.delta_e, e0 + 0.5 * self.delta_e,
                        self.ng_e)

            rays = self.sourceundulator.calculate_rays(
                user_unit_to_m=self.workspace_units_to_m,
                F_COHER=self.coherent,
                SEED=self.seed,
                NRAYS=self.number_of_rays)

            if self.plot_aux_graph:
                self.set_PlotAuxGraphs()

            print(self.sourceundulator.info())

            shadow3_beam = Shadow3Beam(N=rays.shape[0])
            shadow3_beam.rays = rays

            if self.file_to_write_out >= 1:
                shadow3_beam.write("begin.dat")
                print("File written to disk: begin.dat")

            if self.file_to_write_out >= 2:
                SourceUndulatorInputOutput.write_file_undul_phot_h5(
                    self.sourceundulator.get_result_dictionary(),
                    file_out="radiation.h5",
                    mode="w",
                    entry_name="radiation")

            beam_out = ShadowBeam(beam=shadow3_beam)
            beam_out.getOEHistory().append(ShadowOEHistoryItem())

            if self.add_power:
                additional_parameters = {}

                pd, vx, vy = self.sourceundulator.get_power_density_interpolated_cartesian(
                )

                total_power = self.power_step if self.power_step > 0 else pd.sum(
                ) * (vx[1] - vx[0]) * (vy[1] - vy[0])

                additional_parameters["total_power"] = total_power
                additional_parameters["photon_energy_step"] = self.delta_e

                beam_out.setScanningData(
                    ShadowBeam.ScanningData("photon_energy",
                                            self.photon_energy,
                                            "Energy for Power Calculation",
                                            "eV", additional_parameters))

            if self.delta_e == 0.0:
                beam_out.set_initial_flux(self.sourceundulator.get_flux()[0])

            self.progressBarSet(80)
            self.plot_results(beam_out)

            #
            # create python script for creating the shadow3 beam and display the script in the standard output
            #
            dict_parameters = {
                "K": self.K,
                "period_length": self.period_length,
                "periods_number": self.periods_number,
                "energy_in_GeV": self.energy_in_GeV,
                "energy_spread": 0.0,
                "current": self.current,
                "number_of_bunches": 1,
                "moment_xx": (self.sigma_x)**2,
                "moment_xxp": 0.0,
                "moment_xpxp": (self.sigma_divergence_x)**2,
                "moment_yy": (self.sigma_z)**2,
                "moment_yyp": 0.0,
                "moment_ypyp": (self.sigma_divergence_z)**2,
                "name": "shadowOui-Full-Undulator",
                "flag_emittance": self.use_emittances_combo,
                "flag_size": self.flag_size,
                "emin": 1000,  # to be set later
                "emax": 1001,  # to be set later
                "ng_e": 2,  # to be set later
                "maxangle": self.maxangle_urad * 1e-6,
                "ng_t": self.ng_t,
                "ng_p": self.ng_p,
                "ng_j": self.ng_j,
                "code_undul_phot": selected_code,
                "user_unit_to_m": self.workspace_units_to_m,
                "F_COHER": self.coherent,
                "SEED": self.seed,
                "NRAYS": self.number_of_rays,
                "EMIN": self.sourceundulator._EMIN,
                "EMAX": self.sourceundulator._EMAX,
                "NG_E": self.sourceundulator._NG_E,
                "MAXANGLE": self.sourceundulator._MAXANGLE,
            }

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

            self.setStatusMessage("")
            self.send("Beam", beam_out)

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

            if self.IS_DEVELOP: raise exception

        self.progressBarFinished()
示例#3
0
    def test_undul_cdf(self, do_plot=DO_PLOT):

        print(
            "\n#                                                            ")
        print("# test_undul_cdf  ")
        print(
            "#                                                              ")
        tmp = \
            """
            {
            "LAMBDAU":     0.0320000015,
            "K":      0.250000000,
            "E_ENERGY":       6.03999996,
            "E_ENERGY_SPREAD":    0.00100000005,
            "NPERIODS": 50,
            "_EMIN":       10200.0000,
            "_EMAX":       10650.0000,
            "INTENSITY":      0.2,
            "_MAXANGLE":     0.000015,
            "_NG_E": 11,
            "_NG_T": 51,
            "_NG_P": 11,
            "NG_PLOT(1)":"1",
            "NG_PLOT(2)":"No",
            "NG_PLOT(3)":"Yes",
            "UNDUL_PHOT_FLAG(1)":"4",
            "UNDUL_PHOT_FLAG(2)":"Shadow code",
            "UNDUL_PHOT_FLAG(3)":"Urgent code",
            "UNDUL_PHOT_FLAG(4)":"SRW code",
            "UNDUL_PHOT_FLAG(5)":"Gaussian Approx",
            "UNDUL_PHOT_FLAG(6)":"python code by Sophie",
            "SEED": 36255,
            "SX":     0.0399999991,
            "SZ":    0.00100000005,
            "EX":   4.00000005E-07,
            "EZ":   3.99999989E-09,
            "_FLAG_EMITTANCE(1)":"1",
            "_FLAG_EMITTANCE(2)":"No",
            "_FLAG_EMITTANCE(3)":"Yes",
            "NRAYS": 15000,
            "F_BOUND_SOUR": 0,
            "FILE_BOUND":"NONESPECIFIED",
            "SLIT_DISTANCE":       1000.00000,
            "SLIT_XMIN":      -1.00000000,
            "SLIT_XMAX":       1.00000000,
            "SLIT_ZMIN":      -1.00000000,
            "SLIT_ZMAX":       1.00000000,
            "NTOTALPOINT": 10000000,
            "JUNK4JSON":0
            }
            """

        h = json.loads(tmp)
        #
        # run_shadow3_using_preprocessors(h) # uphot.dat must exist

        # u = SourceUndulator()
        # u.load_json_shadowvui_dictionary(h)
        _calculate_shadow3_beam_using_preprocessors(h)

        #
        #
        #
        radiation = SourceUndulatorInputOutput.load_file_undul_phot(
            file_in="uphot.dat")

        cdf2 = SourceUndulatorFactory.undul_cdf(radiation, method='sum')
        SourceUndulatorInputOutput.write_file_undul_cdf(
            cdf2, file_out="xshundul2.sha")

        cdf3 = SourceUndulatorFactory.undul_cdf(radiation, method='trapz')
        SourceUndulatorInputOutput.write_file_undul_cdf(
            cdf3, file_out="xshundul3.sha")

        cdf1 = SourceUndulatorInputOutput.load_file_undul_cdf(
            file_in="xshundul.sha")
        cdf2 = SourceUndulatorInputOutput.load_file_undul_cdf(
            file_in="xshundul2.sha")
        cdf3 = SourceUndulatorInputOutput.load_file_undul_cdf(
            file_in="xshundul3.sha")

        ZERO1 = cdf1['cdf_Energy']
        ONE1 = cdf1['cdf_EnergyTheta']
        TWO1 = cdf1['cdf_EnergyThetaPhi']

        ZERO2 = cdf2['cdf_Energy']
        ONE2 = cdf2['cdf_EnergyTheta']
        TWO2 = cdf2['cdf_EnergyThetaPhi']

        ZERO3 = cdf3['cdf_Energy']
        ONE3 = cdf3['cdf_EnergyTheta']
        TWO3 = cdf3['cdf_EnergyThetaPhi']

        tmp = numpy.where(ZERO1 > 0.1 * ZERO1.max())
        print("test_undul_cdf: ZERO:   sum/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (ZERO2[tmp] - ZERO1[tmp]) / ZERO1[tmp]))))
        print("test_undul_cdf: ZERO: trapz/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (ZERO3[tmp] - ZERO1[tmp]) / ZERO1[tmp]))))

        tmp = numpy.where(ONE1 > 0.1 * ONE1.max())
        print(r"test_undul_cdf: ONE:   sum/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (ONE2[tmp] - ONE1[tmp]) / ONE1[tmp]))))
        print(r"test_undul_cdf: ONE: trapz/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (ONE3[tmp] - ONE1[tmp]) / ONE1[tmp]))))

        tmp = numpy.where(TWO1 > 0.1 * TWO1.max())
        print("test_undul_cdf: TWO:   sum/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (TWO2[tmp] - TWO1[tmp]) / TWO1[tmp]))))
        print("test_undul_cdf: TWO: trapz/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (TWO3[tmp] - TWO1[tmp]) / TWO1[tmp]))))

        if do_plot:

            plot(cdf1["energy"],
                 cdf1["cdf_EnergyThetaPhi"],
                 cdf2["energy"],
                 cdf2["cdf_EnergyThetaPhi"],
                 cdf3["energy"],
                 cdf3["cdf_EnergyThetaPhi"],
                 title="cdf vs energy ",
                 xtitle="photon energy [eV]",
                 ytitle="cdf (integrated in theta,phi)",
                 legend=[
                     "preprocessor", "internal by sumation",
                     "internal by trapezoidal integration"
                 ],
                 show=False)

            plot_image(cdf1['cdf_Energy'][0, :, :],
                       1e6 * radiation['theta'],
                       radiation['phi'],
                       title="PREPROCESSORS cdf_Energy[0]",
                       xtitle="Theta [urad]",
                       ytitle="Phi",
                       aspect='auto',
                       show=False)
            plot_image(cdf3['cdf_Energy'][0, :, :],
                       1e6 * radiation['theta'],
                       radiation['phi'],
                       title="internal-trapezoidal cdf_Energy[0]",
                       xtitle="Theta [urad]",
                       ytitle="Phi",
                       aspect='auto',
                       show=False)

            plot_image(cdf1['cdf_EnergyTheta'],
                       1e6 * radiation['theta'],
                       radiation['phi'],
                       title="PREPROCESSORS cdf_EnergyTheta",
                       xtitle="Theta [urad]",
                       ytitle="Phi",
                       aspect='auto',
                       show=False)
            plot_image(cdf3['cdf_EnergyTheta'],
                       1e6 * radiation['theta'],
                       radiation['phi'],
                       title="internal-trapezoidal cdf_EnergyTheta",
                       xtitle="Theta [urad]",
                       ytitle="Phi",
                       aspect='auto',
                       show=False)
            plot_show()
示例#4
0
    def test_undul_cdf_NG_E_one(self, do_plot=DO_PLOT):

        print(
            "\n#                                                            ")
        print("# test_undul_cdf_NG_E_one  ")
        print(
            "#                                                              ")

        case = 0  # 2 = vui file

        if case == 0:

            tmp = \
                """
                {
                "LAMBDAU":     0.0320000015,
                "K":      0.250000000,
                "E_ENERGY":       6.03999996,
                "E_ENERGY_SPREAD":    0.00100000005,
                "NPERIODS": 50,
                "_EMIN":       10498.0000,
                "_EMAX":       10499.0000,
                "INTENSITY":      0.200000003,
                "_MAXANGLE":      0.000100,
                "_NG_E": 1,
                "_NG_T": 51,
                "_NG_P": 11,
                "NG_PLOT(1)":"0",
                "NG_PLOT(2)":"No",
                "NG_PLOT(3)":"Yes",
                "UNDUL_PHOT_FLAG(1)":"0",
                "UNDUL_PHOT_FLAG(2)":"Shadow code",
                "UNDUL_PHOT_FLAG(3)":"Urgent code",
                "UNDUL_PHOT_FLAG(4)":"SRW code",
                "UNDUL_PHOT_FLAG(5)":"Gaussian Approximation",
                "UNDUL_PHOT_FLAG(6)":"ESRF python code",
                "SEED": 36255,
                "SX":     0.0399999991,
                "SZ":    0.00100000005,
                "EX":   4.00000005E-07,
                "EZ":   3.99999989E-09,
                "_FLAG_EMITTANCE(1)":"0",
                "_FLAG_EMITTANCE(2)":"No",
                "_FLAG_EMITTANCE(3)":"Yes",
                "NRAYS": 15000,
                "F_BOUND_SOUR": 0,
                "FILE_BOUND":"NONESPECIFIED",
                "SLIT_DISTANCE":       1000.00000,
                "SLIT_XMIN":      -1.00000000,
                "SLIT_XMAX":       1.00000000,
                "SLIT_ZMIN":      -1.00000000,
                "SLIT_ZMAX":       1.00000000,
                "NTOTALPOINT": 10000000,
                "JUNK4JSON":0
                }
                """

            h = json.loads(tmp)

            # u = SourceUndulator()
            # u.load_json_shadowvui_dictionary(h)
            _calculate_shadow3_beam_using_preprocessors(h)

        elif case == 1:

            # some inputs
            E_ENERGY = 6.04
            INTENSITY = 0.2
            SX = 0.04
            SZ = 0.001
            SXP = 10e-6
            SZP = 4e-6
            FLAG_EMITTANCE = 1
            LAMBDAU = 0.032
            NPERIODS = 50
            K = 0.25
            EMIN = 10498.0000
            EMAX = 10499.0000
            NG_E = 101
            MAXANGLE = 100e-6
            NG_T = 51
            NG_P = 11
            N_J = 20
            SEED = 36255
            NRAYS = 15000

            u = SourceUndulator()

            u.set_from_keywords(
                E_ENERGY=E_ENERGY,
                INTENSITY=INTENSITY,
                SX=SX,
                SZ=SZ,
                SXP=SXP,
                SZP=SZP,
                FLAG_EMITTANCE=FLAG_EMITTANCE,
                LAMBDAU=LAMBDAU,
                NPERIODS=NPERIODS,
                K=K,
                EMIN=EMIN,
                EMAX=EMAX,
                NG_E=NG_E,
                MAXANGLE=MAXANGLE,
                NG_T=NG_T,
                NG_P=NG_P,
                N_J=N_J,
                SEED=SEED,
                NRAYS=NRAYS,
            )

            u.set_energy_monochromatic_at_resonance(harmonic_number=1)
        elif case == 2:

            # u = SourceUndulator()
            # u.load_json_shadowvui_file("xshundul.json")
            # calculate_shadow3_beam_using_preprocessors(json.loads(tmp))

            pass
        else:
            raise Exception("Undefined")

        #
        #
        #
        radiation = SourceUndulatorInputOutput.load_file_undul_phot(
            file_in="uphot.dat")

        cdf2 = SourceUndulatorFactory.undul_cdf(radiation, method='sum')
        SourceUndulatorInputOutput.write_file_undul_cdf(
            cdf2, file_out="xshundul2.sha")

        cdf3 = SourceUndulatorFactory.undul_cdf(radiation, method='trapz')
        SourceUndulatorInputOutput.write_file_undul_cdf(
            cdf3, file_out="xshundul3.sha")

        cdf1 = SourceUndulatorInputOutput.load_file_undul_cdf(
            file_in="xshundul.sha", )
        cdf2 = SourceUndulatorInputOutput.load_file_undul_cdf(
            file_in="xshundul2.sha")
        cdf3 = SourceUndulatorInputOutput.load_file_undul_cdf(
            file_in="xshundul3.sha")

        ZERO1 = cdf1['cdf_Energy']
        ONE1 = cdf1['cdf_EnergyTheta']
        TWO1 = cdf1['cdf_EnergyThetaPhi']

        ZERO2 = cdf2['cdf_Energy']
        ONE2 = cdf2['cdf_EnergyTheta']
        TWO2 = cdf2['cdf_EnergyThetaPhi']

        ZERO3 = cdf3['cdf_Energy']
        ONE3 = cdf3['cdf_EnergyTheta']
        TWO3 = cdf3['cdf_EnergyThetaPhi']

        #
        #
        NG_E = (radiation["photon_energy"]).size
        NG_T = (radiation["theta"]).size
        NG_P = (radiation["phi"]).size
        #
        print("-----> shape comparison", NG_E, NG_T, NG_P, ZERO1.shape,
              ZERO2.shape, ZERO3.shape)
        print("-----> shape comparison", NG_E, NG_T, NG_P, ONE1.shape,
              ONE2.shape, ONE3.shape)
        print("-----> shape comparison", NG_E, NG_T, NG_P, TWO1.shape,
              TWO2.shape, TWO3.shape)
        for ie in range(NG_E):
            for it in range(NG_T):
                for ip in range(NG_P):
                    # print(">>>>",TWO1[ie],TWO2[ie],TWO3[ie])
                    print(">>>>[%d %d %d]>>" % (ie, it, ip), ONE1[ie, it],
                          ONE2[ie, it], ONE3[ie, it])
                    # print(">>>>[%d %d %d]>>"%(ie,it,ip),ZERO1[ie,it,ip],ZERO2[ie,it,ip],ZERO3[ie,it,ip])

        tmp = numpy.where(ZERO1 > 0.1 * ZERO1.max())
        print("test_undul_cdf: ZERO:   sum/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (ZERO2[tmp] - ZERO1[tmp]) / ZERO1[tmp]))))
        print("test_undul_cdf: ZERO: trapz/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (ZERO3[tmp] - ZERO1[tmp]) / ZERO1[tmp]))))

        tmp = numpy.where(ONE1 > 0.1 * ONE1.max())
        print(r"test_undul_cdf: ONE:   sum/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (ONE2[tmp] - ONE1[tmp]) / ONE1[tmp]))))
        print(r"test_undul_cdf: ONE: trapz/shadow3 %4.2f %%: " %
              (numpy.average(100 * numpy.abs(
                  (ONE3[tmp] - ONE1[tmp]) / ONE1[tmp]))))

        if do_plot:

            plot_image(cdf1['cdf_Energy'][0, :, :],
                       1e6 * radiation['theta'],
                       radiation['phi'],
                       title="PREPROCESSORS cdf_Energy[0]",
                       xtitle="Theta [urad]",
                       ytitle="Phi",
                       aspect='auto',
                       show=False)
            plot_image(cdf3['cdf_Energy'][0, :, :],
                       1e6 * radiation['theta'],
                       radiation['phi'],
                       title="internal-trapezoidal cdf_Energy[0]",
                       xtitle="Theta [urad]",
                       ytitle="Phi",
                       aspect='auto',
                       show=False)

            plot_image(cdf1['cdf_EnergyTheta'],
                       1e6 * radiation['theta'],
                       radiation['phi'],
                       title="PREPROCESSORS cdf_EnergyTheta",
                       xtitle="Theta [urad]",
                       ytitle="Phi",
                       aspect='auto',
                       show=False)
            plot_image(cdf3['cdf_EnergyTheta'],
                       1e6 * radiation['theta'],
                       radiation['phi'],
                       title="internal-trapezoidal cdf_EnergyTheta",
                       xtitle="Theta [urad]",
                       ytitle="Phi",
                       aspect='auto',
                       show=False)
            plot_show()
示例#5
0
    def test_comparison_undul_phot(self,
                                   do_plot_intensity=DO_PLOT,
                                   do_plot_polarization=DO_PLOT,
                                   do_plot_trajectory=DO_PLOT):

        print(
            "\n#                                                            ")
        print("# test_comparison_undul_phot  ")
        print(
            "#                                                              ")

        #
        # test undul_phot (undulator radiation)
        #

        # try:
        #     import pySRU
        #     is_available_pysru = True
        # except:
        #     is_available_pysru = False
        #
        # try:
        #     import srwlib
        #     is_available_srw = True
        # except:
        #     is_available_srw = False

        is_available_pysru = False
        is_available_srw = False

        tmp = \
            """
            {
            "LAMBDAU":     0.0320000015,
            "K":      0.250000000,
            "E_ENERGY":       6.03999996,
            "E_ENERGY_SPREAD":    0.00100000005,
            "NPERIODS": 50,
            "_EMIN":       10200.0000,
            "_EMAX":       10650.0000,
            "INTENSITY":      0.2,
            "_MAXANGLE":     0.000015,
            "_NG_E": 11,
            "_NG_T": 51,
            "_NG_P": 11,
            "NG_PLOT(1)":"1",
            "NG_PLOT(2)":"No",
            "NG_PLOT(3)":"Yes",
            "UNDUL_PHOT_FLAG(1)":"4",
            "UNDUL_PHOT_FLAG(2)":"Shadow code",
            "UNDUL_PHOT_FLAG(3)":"Urgent code",
            "UNDUL_PHOT_FLAG(4)":"SRW code",
            "UNDUL_PHOT_FLAG(5)":"Gaussian Approx",
            "UNDUL_PHOT_FLAG(6)":"python code by Sophie",
            "SEED": 36255,
            "SX":     0.0399999991,
            "SZ":    0.00100000005,
            "EX":   4.00000005E-07,
            "EZ":   3.99999989E-09,
            "_FLAG_EMITTANCE(1)":"1",
            "_FLAG_EMITTANCE(2)":"No",
            "_FLAG_EMITTANCE(3)":"Yes",
            "NRAYS": 15000,
            "F_BOUND_SOUR": 0,
            "FILE_BOUND":"NONESPECIFIED",
            "SLIT_DISTANCE":       1000.00000,
            "SLIT_XMIN":      -1.00000000,
            "SLIT_XMAX":       1.00000000,
            "SLIT_ZMIN":      -1.00000000,
            "SLIT_ZMAX":       1.00000000,
            "NTOTALPOINT": 10000000,
            "JUNK4JSON":0
            }
            """
        h = json.loads(tmp)

        # SHADOW3 preprocessor
        # run_shadow3_using_preprocessors(h)

        # u = SourceUndulator()
        # u.load_json_shadowvui_dictionary(h)
        _calculate_shadow3_beam_using_preprocessors(h)

        undul_phot_preprocessor_dict = SourceUndulatorInputOutput.load_file_undul_phot(
            "uphot.dat")

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

        SourceUndulatorInputOutput.plot_undul_phot(
            undul_phot_preprocessor_dict,
            title="UNDUL_PHOT_PREPROCESSOR",
            do_plot_intensity=do_plot_intensity,
            do_plot_polarization=do_plot_polarization,
            do_show=False)

        # internal code
        undul_phot_dict = SourceUndulatorFactory.undul_phot(
            E_ENERGY=h["E_ENERGY"],
            INTENSITY=h["INTENSITY"],
            LAMBDAU=h["LAMBDAU"],
            NPERIODS=h["NPERIODS"],
            K=h["K"],
            EMIN=h["_EMIN"],
            EMAX=h["_EMAX"],
            NG_E=h["_NG_E"],
            MAXANGLE=h["_MAXANGLE"],
            NG_T=h["_NG_T"],
            NG_P=h["_NG_P"])

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

        SourceUndulatorInputOutput.plot_undul_phot(
            undul_phot_dict,
            title="UNDUL_PHOT",
            do_plot_intensity=do_plot_intensity,
            do_plot_polarization=do_plot_polarization,
            do_show=False)

        # pySRU
        if is_available_pysru:
            undul_phot_pysru_dict = SourceUndulatorFactoryPysru.undul_phot(
                E_ENERGY=h["E_ENERGY"],
                INTENSITY=h["INTENSITY"],
                LAMBDAU=h["LAMBDAU"],
                NPERIODS=h["NPERIODS"],
                K=h["K"],
                EMIN=h["_EMIN"],
                EMAX=h["_EMAX"],
                NG_E=h["_NG_E"],
                MAXANGLE=h["_MAXANGLE"],
                NG_T=h["_NG_T"],
                NG_P=h["_NG_P"])
            # if do_plot_intensity: plot_image(undul_phot_pysru_dict['radiation'][0,:,:],undul_phot_pysru_dict['theta']*1e6,undul_phot_pysru_dict['phi']*180/numpy.pi,
            #            title="INTENS UNDUL_PHOT_PYSRU: RN0[0]",xtitle="Theta [urad]",ytitle="Phi [deg]",aspect='auto',show=False)
            # if do_plot_polarization: plot_image(undul_phot_pysru_dict['polarization'][0,:,:],undul_phot_pysru_dict['theta']*1e6,undul_phot_pysru_dict['phi']*180/numpy.pi,
            #            title="POL_DEG UNDUL_PHOT_PYSRU: RN0[0]",xtitle="Theta [urad]",ytitle="Phi [deg]",aspect='auto',show=False)

            SourceUndulatorInputOutput.plot_undul_phot(
                undul_phot_pysru_dict,
                title="UNDUL_PHOT_PYSRU",
                do_plot_intensity=do_plot_intensity,
                do_plot_polarization=do_plot_polarization,
                do_show=False)

        # srw
        if is_available_srw:
            undul_phot_srw_dict = SourceUndulatorFactorySrw.undul_phot(
                E_ENERGY=h["E_ENERGY"],
                INTENSITY=h["INTENSITY"],
                LAMBDAU=h["LAMBDAU"],
                NPERIODS=h["NPERIODS"],
                K=h["K"],
                EMIN=h["_EMIN"],
                EMAX=h["_EMAX"],
                NG_E=h["_NG_E"],
                MAXANGLE=h["_MAXANGLE"],
                NG_T=h["_NG_T"],
                NG_P=h["_NG_P"])
            # if do_plot_intensity: plot_image(undul_phot_srw_dict['radiation'][0,:,:],undul_phot_srw_dict['theta']*1e6,undul_phot_srw_dict['phi']*180/numpy.pi,
            #            title="INTENS UNDUL_PHOT_SRW: RN0[0]",xtitle="Theta [urad]",ytitle="Phi [deg]",aspect='auto',show=False)
            # if do_plot_polarization: plot_image(undul_phot_srw_dict['polarization'][0,:,:],undul_phot_srw_dict['theta']*1e6,undul_phot_srw_dict['phi']*180/numpy.pi,
            #            title="POL_DEG UNDUL_PHOT_SRW: RN0[0]",xtitle="Theta [urad]",ytitle="Phi [deg]",aspect='auto',show=False)

            SourceUndulatorInputOutput.plot_undul_phot(
                undul_phot_srw_dict,
                title="UNDUL_PHOT_SRW",
                do_plot_intensity=do_plot_intensity,
                do_plot_polarization=do_plot_polarization,
                do_show=False)

        x = undul_phot_dict["photon_energy"]
        y0 = (undul_phot_preprocessor_dict["radiation"]).sum(axis=2).sum(
            axis=1)
        y1 = (undul_phot_dict["radiation"]).sum(axis=2).sum(axis=1)
        if is_available_pysru:
            y2 = (undul_phot_pysru_dict["radiation"]).sum(axis=2).sum(axis=1)
        if is_available_srw:
            y3 = (undul_phot_srw_dict["radiation"]).sum(axis=2).sum(axis=1)

        if do_plot_intensity:
            if is_available_pysru and is_available_srw:
                plot(x,
                     y0,
                     x,
                     y1,
                     x,
                     y2,
                     x,
                     y3,
                     xtitle="Photon energy [eV]",
                     ytitle="Flux[photons/s/eV/rad^2]",
                     legend=["preprocessor", "internal", "pySRU", "SRW"])
            else:
                if is_available_pysru:
                    plot(x,
                         y0,
                         x,
                         y1,
                         x,
                         y2,
                         xtitle="Photon energy [eV]",
                         ytitle="Flux[photons/s/eV/rad^2]",
                         legend=["preprocessor", "internal", "pySRU"])
                if is_available_srw:
                    plot(x,
                         y0,
                         x,
                         y1,
                         x,
                         y3,
                         xtitle="Photon energy [eV]",
                         ytitle="Flux[photons/s/eV/rad^2]",
                         legend=["preprocessor", "internal", "SRW"])
        tmp = numpy.where(y0 > 0.1)

        print("\n")
        print(">>> test_undul_phot: preprocessor/internal: %4.2f %% " %
              (numpy.average(100 * numpy.abs((y0[tmp] - y1[tmp]) / y1[tmp]))))
        self.assertLess(
            numpy.average(100 * numpy.abs((y0[tmp] - y1[tmp]) / y1[tmp])), 5)
        if is_available_pysru:
            print(">>> test_undul_phot:        pySRU/internal: %4.2f %% " %
                  (numpy.average(100 * numpy.abs(
                      (y2[tmp] - y1[tmp]) / y1[tmp]))))
            self.assertLess(
                numpy.average(100 * numpy.abs((y2[tmp] - y1[tmp]) / y1[tmp])),
                1)
        if is_available_srw:
            print(">>> test_undul_phot:          SRW/internal: %4.2f %% " %
                  (numpy.average(100 * numpy.abs(
                      (y3[tmp] - y1[tmp]) / y1[tmp]))))
            self.assertLess(
                numpy.average(100 * numpy.abs((y3[tmp] - y1[tmp]) / y1[tmp])),
                5)

        #
        # trajectory
        #
        if do_plot_trajectory:
            # Trajectory is only in undul_phot (internal) and und_phot_pysru
            # t0 = (undul_phot_preprocessor_dict["trajectory"])
            t1 = (undul_phot_dict["trajectory"])
            if is_available_pysru:
                t2 = (undul_phot_pysru_dict["trajectory"])
                plot(t1[3],
                     1e6 * t1[1],
                     t2[3],
                     1e6 * t2[1],
                     title='Trajectory',
                     xtitle='z [m]',
                     ytitle='x[um]',
                     legend=['internal', 'pysru'],
                     show=False)
            else:
                plot(t1[3],
                     1e6 * t1[1],
                     title='Trajectory',
                     xtitle='z [m]',
                     ytitle='x[um]',
                     legend=['internal'],
                     show=False)

        if do_plot_polarization or do_plot_intensity or do_plot_trajectory:
            plot_show()