Пример #1
0
    def sendNewBeam(self, trigger):
        self.scanning_data = None

        if trigger and trigger.new_object == True:
            if trigger.has_additional_parameter("seed_increment"):
                self.seed += trigger.get_additional_parameter("seed_increment")
            elif trigger.has_additional_parameter(
                    "variable_name") and self.is_scanning_enabled():
                variable_name = trigger.get_additional_parameter(
                    "variable_name").strip()
                variable_display_name = trigger.get_additional_parameter(
                    "variable_display_name").strip()
                variable_value = trigger.get_additional_parameter(
                    "variable_value")
                variable_um = trigger.get_additional_parameter("variable_um")

                def check_number(x):
                    try:
                        return float(x)
                    except:
                        return x

                if "," in variable_name:
                    variable_names = variable_name.split(",")

                    if isinstance(variable_value,
                                  str) and "," in variable_value:
                        variable_values = variable_value.split(",")
                        for variable_name, variable_value in zip(
                                variable_names, variable_values):
                            setattr(self, variable_name.strip(),
                                    check_number(variable_value))
                            self.check_source_options(variable_name)
                    else:
                        for variable_name in variable_names:
                            setattr(self, variable_name.strip(),
                                    check_number(variable_value))
                            self.check_source_options(variable_name)
                else:
                    setattr(self, variable_name, check_number(variable_value))
                    self.check_source_options(variable_name)

                self.scanning_data = ShadowBeam.ScanningData(
                    variable_name, variable_value, variable_display_name,
                    variable_um)

            self.runShadowSource()
Пример #2
0
    def setBeam(self, input_beam):
        if input_beam.scanned_variable_data and input_beam.scanned_variable_data.has_additional_parameter("photon_energy_step"):

            photon_energy      = input_beam.scanned_variable_data.get_scanned_variable_value()
            photon_energy_step = input_beam.scanned_variable_data.get_additional_parameter("photon_energy_step")

            if input_beam.scanned_variable_data.has_additional_parameter("intensity_arrays") and self.redo_calculation == 0:
                h_array, v_array, intensity_array = input_beam.scanned_variable_data.get_additional_parameter("intensity_arrays")

                total_power = self.calculate_power(h_array, v_array, intensity_array, photon_energy_step)
            else:
                total_power = self.calc2d_srw(photon_energy, photon_energy_step, input_beam.scanned_variable_data)

            additional_parameters = {}
            additional_parameters["total_power"] = total_power
            additional_parameters["photon_energy_step"] = photon_energy_step

            input_beam.setScanningData(ShadowBeam.ScanningData(input_beam.scanned_variable_data.get_scanned_variable_name(),
                                                               photon_energy,
                                                               input_beam.scanned_variable_data.get_scanned_variable_display_name(),
                                                               input_beam.scanned_variable_data.get_scanned_variable_um(),
                                                               additional_parameters))

        self.send("Beam", input_beam)
Пример #3
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()
    def calculate_footprint(self):
        self.setStatusMessage("")

        try:
            beam_out = self.footprint_beam.duplicate()
            beam_out.history.append(ShadowOEHistoryItem())  # fake Source
            beam_out._oe_number = 0

            # just to create a safe history for possible re-tracing
            beam_out.traceFromOE(beam_out,
                                 self.create_dummy_oe(),
                                 history=True)

            total_power = self.input_beam.scanned_variable_data.get_additional_parameter(
                "total_power")

            additional_parameters = {}
            additional_parameters["total_power"] = total_power
            additional_parameters[
                "photon_energy_step"] = self.input_beam.scanned_variable_data.get_additional_parameter(
                    "photon_energy_step")
            additional_parameters["is_footprint"] = True

            n_rays = len(beam_out._beam.rays[:, 0])  # lost and good!

            incident_beam = self.input_beam.getOEHistory(
                self.input_beam._oe_number)._input_beam

            ticket = incident_beam._beam.histo2(1,
                                                3,
                                                nbins=100,
                                                xrange=None,
                                                yrange=None,
                                                nolost=1,
                                                ref=23)
            ticket['histogram'] *= (total_power / n_rays)  # power

            additional_parameters["incident_power"] = ticket['histogram'].sum()

            if self.kind_of_power == 0:  # incident
                beam_out._beam.rays[:, 6] = incident_beam._beam.rays[:, 6]
                beam_out._beam.rays[:, 7] = incident_beam._beam.rays[:, 7]
                beam_out._beam.rays[:, 8] = incident_beam._beam.rays[:, 8]
                beam_out._beam.rays[:, 15] = incident_beam._beam.rays[:, 15]
                beam_out._beam.rays[:, 16] = incident_beam._beam.rays[:, 16]
                beam_out._beam.rays[:, 17] = incident_beam._beam.rays[:, 17]
            elif self.kind_of_power == 1:  # absorbed
                # need a trick: put the whole intensity of one single component

                incident_intensity = incident_beam._beam.rays[:, 6]**2 + incident_beam._beam.rays[:, 7]**2 + incident_beam._beam.rays[:, 8]**2 +\
                                     incident_beam._beam.rays[:, 15]**2 + incident_beam._beam.rays[:, 16]**2 + incident_beam._beam.rays[:, 17]**2
                transmitted_intensity = beam_out._beam.rays[:, 6]**2 + beam_out._beam.rays[:, 7]**2 + beam_out._beam.rays[:, 8]**2 +\
                                        beam_out._beam.rays[:, 15]**2 + beam_out._beam.rays[:, 16]**2 + beam_out._beam.rays[:, 17]**2

                electric_field = numpy.sqrt(incident_intensity -
                                            transmitted_intensity)
                electric_field[numpy.where(electric_field == numpy.nan)] = 0.0

                beam_out._beam.rays[:, 6] = electric_field
                beam_out._beam.rays[:, 7] = 0.0
                beam_out._beam.rays[:, 8] = 0.0
                beam_out._beam.rays[:, 15] = 0.0
                beam_out._beam.rays[:, 16] = 0.0
                beam_out._beam.rays[:, 17] = 0.0

            beam_out.setScanningData(
                ShadowBeam.ScanningData(
                    self.input_beam.scanned_variable_data.
                    get_scanned_variable_name(),
                    self.input_beam.scanned_variable_data.
                    get_scanned_variable_value(),
                    self.input_beam.scanned_variable_data.
                    get_scanned_variable_display_name(),
                    self.input_beam.scanned_variable_data.
                    get_scanned_variable_um(), additional_parameters))
            self.send("Beam", beam_out)
        except Exception as exception:
            QtWidgets.QMessageBox.critical(self, "Error", str(exception),
                                           QtWidgets.QMessageBox.Ok)
    def calculate_footprint(self):
        self.setStatusMessage("")

        try:
            if not self.input_beam is None and not self.footprint_beam is None:
                beam_out = self.footprint_beam.duplicate()
                beam_out._oe_number = self.input_beam._oe_number

                for history_item in self.input_beam.history:
                    beam_out.history.append(history_item)  # Source

                is_scanning = self.input_beam.scanned_variable_data and self.input_beam.scanned_variable_data.has_additional_parameter(
                    "total_power")

                additional_parameters = {}

                if is_scanning:
                    total_power = self.input_beam.scanned_variable_data.get_additional_parameter(
                        "total_power")

                    additional_parameters["total_power"] = total_power
                    additional_parameters[
                        "current_step"] = self.input_beam.scanned_variable_data.get_additional_parameter(
                            "current_step")
                    additional_parameters[
                        "total_steps"] = self.input_beam.scanned_variable_data.get_additional_parameter(
                            "total_steps")
                    additional_parameters[
                        "photon_energy_step"] = self.input_beam.scanned_variable_data.get_additional_parameter(
                            "photon_energy_step")

                additional_parameters["is_footprint"] = True

                incident_beam = self.input_beam.getOEHistory(
                    self.input_beam._oe_number)._input_beam

                if is_scanning:
                    n_rays = len(beam_out._beam.rays[:, 0])  # lost and good!

                    ticket = incident_beam._beam.histo2(1,
                                                        3,
                                                        nbins=100,
                                                        xrange=None,
                                                        yrange=None,
                                                        nolost=1,
                                                        ref=23)
                    ticket['histogram'] *= (total_power / n_rays)  # power

                    additional_parameters["incident_power"] = ticket[
                        'histogram'].sum()

                if self.kind_of_power == 0:  # incident
                    beam_out._beam.rays[:, 6] = incident_beam._beam.rays[:, 6]
                    beam_out._beam.rays[:, 7] = incident_beam._beam.rays[:, 7]
                    beam_out._beam.rays[:, 8] = incident_beam._beam.rays[:, 8]
                    beam_out._beam.rays[:, 15] = incident_beam._beam.rays[:,
                                                                          15]
                    beam_out._beam.rays[:, 16] = incident_beam._beam.rays[:,
                                                                          16]
                    beam_out._beam.rays[:, 17] = incident_beam._beam.rays[:,
                                                                          17]
                elif self.kind_of_power == 1:  # absorbed
                    # need a trick: put the whole intensity of one single component

                    incident_intensity = incident_beam._beam.rays[:, 6]**2 + incident_beam._beam.rays[:, 7]**2 + incident_beam._beam.rays[:, 8]**2 +\
                                         incident_beam._beam.rays[:, 15]**2 + incident_beam._beam.rays[:, 16]**2 + incident_beam._beam.rays[:, 17]**2
                    transmitted_intensity = beam_out._beam.rays[:, 6]**2 + beam_out._beam.rays[:, 7]**2 + beam_out._beam.rays[:, 8]**2 +\
                                            beam_out._beam.rays[:, 15]**2 + beam_out._beam.rays[:, 16]**2 + beam_out._beam.rays[:, 17]**2

                    electric_field = numpy.sqrt(incident_intensity -
                                                transmitted_intensity)
                    electric_field[numpy.where(
                        electric_field == numpy.nan)] = 0.0

                    beam_out._beam.rays[:, 6] = electric_field
                    beam_out._beam.rays[:, 7] = 0.0
                    beam_out._beam.rays[:, 8] = 0.0
                    beam_out._beam.rays[:, 15] = 0.0
                    beam_out._beam.rays[:, 16] = 0.0
                    beam_out._beam.rays[:, 17] = 0.0

                if is_scanning:
                    beam_out.setScanningData(
                        ShadowBeam.ScanningData(
                            self.input_beam.scanned_variable_data.
                            get_scanned_variable_name(),
                            self.input_beam.scanned_variable_data.
                            get_scanned_variable_value(),
                            self.input_beam.scanned_variable_data.
                            get_scanned_variable_display_name(),
                            self.input_beam.scanned_variable_data.
                            get_scanned_variable_um(), additional_parameters))
                else:
                    beam_out.setScanningData(
                        scanned_variable_data=ShadowBeam.ScanningData(
                            None,
                            None,
                            None,
                            None,
                            additional_parameters=additional_parameters))

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