def get_dummy_source(wofry_wavefront):
    return Foundation.OpticalElement(
        Name="Wofry Source",
        IsSource=True,
        CoreOpticsElement=DummyElement(wofry_wavefront=wofry_wavefront),
        PositioningDirectives=Foundation.PositioningDirectives(
            ReferTo=Foundation.PositioningDirectives.ReferTo.AbsoluteReference,
            XYCentre=[0.0, 0.0],
            Angle=0.0))
def get_virtual_source():
    return WiserOpticalElement(
        name="Virtual source",
        isSource=True,
        native_CoreOptics=Optics.SourceVirtual(),
        native_PositioningDirectives=Foundation.PositioningDirectives(
            ReferTo=Foundation.PositioningDirectives.ReferTo.AbsoluteReference,
            XYCentre=[0.0, 0.0],
            Angle=0.0))
def get_wavefront_source(wofry_wavefront):
    mesh_x = wofry_wavefront.get_abscissas()

    return WiserOpticalElement(
        name="Wavefront Source",
        isSource=False,
        native_CoreOptics=Optics.SourceWavefront(
            Lambda=wofry_wavefront.get_wavelength(),
            L=numpy.abs(mesh_x[0]) + numpy.abs(mesh_x[-1]),
            Field=wofry_wavefront.get_amplitude() *
            numpy.exp(1j * wofry_wavefront.get_phase()),
            Orientation=Optics.OPTICS_ORIENTATION.ISOTROPIC),
        native_PositioningDirectives=Foundation.PositioningDirectives(
            ReferTo=Foundation.PositioningDirectives.ReferTo.Source,
            PlaceWhat='centre',
            PlaceWhere='centre',
            Distance=4))
    PropagationManager.Instance().add_propagator(WiserPropagator())

    tl.Debug.On = True
    N = 3000
    UseCustomSampling = True
    # SOURCE
    #==========================================================================
    Lambda = 2e-9
    Waist0 = 180e-6  #Fermi.Waist0E(Lambda)

    ww_s = WiserOpticalElement(
        name='FEL2 source',
        boundary_shape=None,
        isSource=True,
        native_CoreOptics=Optics.SourceGaussian(Lambda=Lambda, Waist0=Waist0),
        native_PositioningDirectives=Foundation.PositioningDirectives(
            ReferTo='absolute', XYCentre=[0, 0], Angle=pi / 4. - AngleGrazing))

    s = ww_s.native_optical_element  # Wiser optical element
    s.ComputationSettings.UseSmallDisplacements = True
    s.Orientation = Optics.OPTICS_ORIENTATION.ANY
    s.CoreOptics.SmallDisplacements.Long = DeltaSourceList[0]
    s.CoreOptics.SmallDisplacements.Rotation = 0.

    # PM1 (h)
    #==========================================================================
    ww_pm1_h = WiserOpticalElement(
        name='pm1h',
        boundary_shape=None,
        native_CoreOptics=Optics.MirrorPlane(L=L, AngleGrazing=AngleGrazing),
        native_PositioningDirectives=Foundation.PositioningDirectives(
            ReferTo='upstream',
    def __init__(self):
        super(WiserPropagationElements, self).__init__()

        self.__wise_propagation_elements = Foundation.BeamlineElements()
예제 #6
0
    def do_find_focus_calculation(self):
        try:
            if self.input_data is None:
                raise Exception("No Input Data!")

            if not self.output_data_best_focus:
                raise Exception("Run computation first!")

            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            self.oe_f2 = self.output_data_best_focus.wise_beamline.get_wise_propagation_element(
                -1).PositioningDirectives.Distance

            self.check_fields()
            if self.defocus_start >= self.defocus_stop:
                raise Exception(
                    "Defocus sweep start must be < Defocus sweep stop")
            self.defocus_step = congruence.checkStrictlyPositiveNumber(
                self.defocus_step, "Defocus sweep step")
            if self.defocus_step >= self.defocus_stop - self.defocus_start:
                raise Exception("Defocus step is too big")

            if self.best_focus_slider is None:
                self.best_focus_slider = QSlider(self.tab[1])
                self.best_focus_slider.setGeometry(QRect(0, 0, 320, 50))
                self.best_focus_slider.setMinimumHeight(30)
                self.best_focus_slider.setOrientation(Qt.Horizontal)
                self.best_focus_slider.setInvertedAppearance(False)
                self.best_focus_slider.setInvertedControls(False)

                self.tab[2].layout().addWidget(self.best_focus_slider)
            else:
                self.best_focus_slider.valueChanged.disconnect()

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

            progress_bar_increment = 100. / self.max_iter

            hew_min = numpy.inf
            index_min_list = []

            self.best_focus_index = -1
            self.electric_fields_list = []
            self.positions_list = []
            self.hews_list = []

            import copy
            last_element = self.get_last_element()
            last_element = copy.deepcopy(last_element)

            self.setStatusMessage("Executing Foundation.FocusFind()")

            self.run_calculation = True

            #   Results : struct-like class with the following attributes
            #   	- BestField : 1d-array (complex)
            #   				    Field at the best focus
            #       - BestDefocus : scalar (real)
            #                       Defocus of the best spot
            #       - BestHew : scalar (real)
            #				        Half energy width of the best spot
            #       - OptResult : OptimizationResult object
            #                       Contains the results of the optimization

            Results = Foundation.FocusFind(
                last_element,
                DefocusRange=(self.defocus_start * 1e-3,
                              self.defocus_stop * 1e-3),
                DetectorSize=self.length)

            BestField = Results.BestField
            self.BestDefocus = Results.BestDefocus
            self.BestHew = Results.BestHew
            OptResult = Results.OptResult
            S = Results.S

            best_focus_I = numpy.abs(BestField)**2
            norm = max(best_focus_I)
            norm = 1.0 if norm == 0.0 else norm
            best_focus_I = best_focus_I / norm

            self.ActualBestHew = self.get_ActualBestHew()
            self.ActualBestDefocus = self.get_ActualBestDefocus()

            QMessageBox.information(
                self, "Best focus calculation",
                "Best Focus Found!\n\nPosition: " +
                str(self.ActualBestDefocus) + " [m]" + "\nHEW: " +
                str(self.ActualBestHew) + " [" + u"\u03BC" + "m]",
                QMessageBox.Ok)

            self.plot_histo(S * 1e6,
                            best_focus_I,
                            100,
                            tabs_canvas_index=2,
                            plot_canvas_index=2,
                            title="(BEST FOCUS) Position: " +
                            str(self.ActualBestDefocus) + " [m] , HEW: " +
                            str(self.ActualBestHew) + " [" + u"\u03BC" + "m]",
                            xtitle="Y [" + u"\u03BC" + "m]",
                            ytitle="Intensity",
                            log_x=False,
                            log_y=False)
            #
            # self.plot_histo(self._defocus_sign * self.defocus_list,
            #                 numpy.multiply(self.hews_list, 1e6),
            #                 100,
            #                 tabs_canvas_index=3,
            #                 plot_canvas_index=3,
            #                 title="HEW vs Defocus Sweep",
            #                 xtitle="",
            #                 ytitle="",
            #                 log_x=False,
            #                 log_y=False)
            #
            # self.plot_canvas[3].setDefaultPlotLines(True)
            # self.plot_canvas[3].setDefaultPlotPoints(True)
            # self.plot_canvas[3].setGraphXLabel("Defocus [mm]")
            # self.plot_canvas[3].setGraphYLabel("HEW [$\mu$m]")
            #
            # self.best_focus_slider.setValue(index_min)
            #
            self.tabs.setCurrentIndex(2)
            self.setStatusMessage("")

            self.save_button.setEnabled(True)

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

            self.setStatusMessage("Error!")

            #raise exception

        if not self.best_focus_slider is None:
            self.best_focus_slider.valueChanged.connect(self.plot_detail)
        self.progressBarFinished()
예제 #7
0
    def do_focus_sweep_calculation(self):
        # Equivalent to Focal scan in the GUI
        try:
            if self.input_data is None:
                raise Exception("No Input Data!")

            if not self.output_data_best_focus:
                raise Exception("Run computation first!")

            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            # TODO: TO BE CHECKED THE EQUiVALENT OF THE OLD QUANTITY!!!!
            self.oe_f2 = self.output_data_best_focus.wise_beamline.get_wise_propagation_element(
                -1).PositioningDirectives.Distance

            self.check_fields()
            if self.defocus_start >= self.defocus_stop:
                raise Exception(
                    "Defocus sweep start must be < Defocus sweep stop")
            self.defocus_step = congruence.checkStrictlyPositiveNumber(
                self.defocus_step, "Defocus sweep step")
            if self.defocus_step >= self.defocus_stop - self.defocus_start:
                raise Exception("Defocus step is too big")

            if self.best_focus_slider is None:
                self.best_focus_slider = QSlider(self.tab[1])
                self.best_focus_slider.setGeometry(QRect(0, 0, 320, 50))
                self.best_focus_slider.setMinimumHeight(30)
                self.best_focus_slider.setOrientation(Qt.Horizontal)
                self.best_focus_slider.setInvertedAppearance(False)
                self.best_focus_slider.setInvertedControls(False)

                self.tab[2].layout().addWidget(self.best_focus_slider)
            else:
                self.best_focus_slider.valueChanged.disconnect()

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

            self.defocus_list = numpy.arange(self.defocus_start * 1e-3,
                                             self.defocus_stop * 1e-3,
                                             self.defocus_step * 1e-3)

            n_defocus = len(self.defocus_list)

            if self.defocus_list[-1] != self.defocus_stop * 1e-3:
                n_defocus += 1
                self.defocus_list.resize(n_defocus)
                self.defocus_list[-1] = self.defocus_stop * 1e-3

            self.best_focus_slider.setTickInterval(1)
            self.best_focus_slider.setSingleStep(1)
            self.best_focus_slider.setMinimum(0)
            self.best_focus_slider.setMaximum(n_defocus - 1)
            self.best_focus_slider.setValue(0)

            progress_bar_increment = 100 / n_defocus

            n_pools = self.n_pools if self.use_multipool == 1 else 1

            hew_min = numpy.inf
            index_min_list = []

            self.best_focus_index = -1
            self.electric_fields_list = []
            self.positions_list = []
            self.hews_list = []
            self.sigmas_list = []

            import copy
            last_element = self.get_last_element()
            last_element = copy.deepcopy(last_element)

            self.setStatusMessage("Executing Foundation.FocusSweep()")

            self.run_calculation = True

            self.defocus_list[numpy.where(
                numpy.abs(self.defocus_list) < 1e-15)] = 0.0

            if self.show_animation == 1:
                for i, defocus in enumerate(self.defocus_list):
                    if not self.run_calculation:
                        if not self.best_focus_slider is None:
                            self.best_focus_slider.valueChanged.connect(
                                self.plot_detail)
                        return

                    ResultList, HewList, SigmaList, More = Foundation.FocusSweep(
                        last_element, [self.defocus_list[i]],
                        DetectorSize=self.length)

                    S = ResultList[0].S
                    E = ResultList[0].Field
                    I = abs(E)**2
                    norm = max(I)
                    norm = 1.0 if norm == 0.0 else norm
                    I = I / norm
                    HEW = HewList[0]
                    sigma0 = SigmaList[0]

                    # E1
                    self.electric_fields_list.append(E)
                    self.positions_list.append(S)
                    self.hews_list.append(HEW)
                    self.sigmas_list.append(sigma0)

                    self.best_focus_slider.setValue(i)

                    self.plot_histo(
                        S * 1e6,
                        I,
                        i * progress_bar_increment,
                        tabs_canvas_index=2,
                        plot_canvas_index=2,
                        title="Defocus Sweep: " +
                        str(self._defocus_sign * round(defocus, 2) / 1e-3) +
                        " (" + str(i + 1) + "/" + str(n_defocus) + "), HEW: " +
                        str(round(HEW * 1e6, 4)) + " [" + u"\u03BC" + "m]",
                        xtitle="Y [" + u"\u03BC" + "m]",
                        ytitle="Intensity",
                        log_x=False,
                        log_y=False)

                    self.tabs.setCurrentIndex(2)

                    hew = round(
                        HEW * 1e6, 11
                    )  # problems with double precision numbers: inconsistent comparisons

                    if hew < hew_min:
                        hew_min = hew
                        index_min_list = [i]
                    elif hew == hew_min:
                        index_min_list.append(i)
            else:  # NOT INTERACTIVE
                ResultList, HewList, SigmaList, More = Foundation.FocusSweep(
                    last_element, self.defocus_list, DetectorSize=self.length)

                i = 0
                for Result, HEW, sigma0 in zip(ResultList, HewList, SigmaList):
                    self.electric_fields_list.append(Result.Field)
                    self.positions_list.append(Result.S)
                    self.hews_list.append(HEW)
                    self.sigmas_list.append(sigma0)

                    hew = round(
                        HEW * 1e6, 11
                    )  # problems with double precision numbers: inconsistent comparisons

                    if hew < hew_min:
                        hew_min = hew
                        index_min_list = [i]
                    elif hew == hew_min:
                        index_min_list.append(i)

                    i += 1

            index_min = index_min_list[int(
                len(index_min_list) /
                2)]  # choosing the central value, when hew reach a pletau

            self.best_focus_index = index_min
            best_focus_electric_fields = self.electric_fields_list[index_min]
            best_focus_I = abs(best_focus_electric_fields)**2
            norm = max(best_focus_I)
            norm = 1.0 if norm == 0.0 else norm
            best_focus_I = best_focus_I / norm

            best_focus_positions = self.positions_list[index_min]
            self.ActualBestDefocus = self.get_ActualBestDefocus()
            self.ActualBestHew = self.get_ActualBestHew()

            QMessageBox.information(
                self, "Focal Scan calculation",
                "Best Focus Found!\n\nPosition: " +
                str(self.oe_f2 +
                    (self._defocus_sign *
                     round(self.defocus_list[index_min], 2) / 1e-3)) + " [m]" +
                "\nHEW: " + str(round(self.hews_list[index_min] * 1e6, 4)) +
                " [" + u"\u03BC" + "m]", QMessageBox.Ok)

            self.plot_histo(
                best_focus_positions * 1e6,
                best_focus_I,
                100,
                tabs_canvas_index=2,
                plot_canvas_index=2,
                title="(BEST FOCUS) Defocus Sweep: " + str(
                    round(
                        self._defocus_sign * self.defocus_list[index_min] /
                        1e-3, 4)) + " (" + str(index_min + 1) + "/" +
                str(n_defocus) + "), Position: " +
                str(self.oe_f2 +
                    (self._defocus_sign *
                     round(self.defocus_list[index_min], 2) / 1e-3)) + " [m]" +
                ", HEW: " + str(self.ActualBestHew) + " [" + u"\u03BC" + "m]",
                xtitle="Y [" + u"\u03BC" + "m]",
                ytitle="Intensity",
                log_x=False,
                log_y=False)

            self.plot_histo(self._defocus_sign * self.defocus_list * 1e3,
                            numpy.multiply(self.hews_list, 1e6),
                            100,
                            tabs_canvas_index=3,
                            plot_canvas_index=3,
                            title="HEW (blue) and SIGMA (red)",
                            xtitle="",
                            ytitle="",
                            log_x=False,
                            log_y=False)

            self.plot_canvas[3].addCurve(self._defocus_sign *
                                         self.defocus_list * 1e3,
                                         numpy.multiply(self.sigmas_list, 1e6),
                                         legend="HEW (blue) and SIGMA (red)",
                                         color='red',
                                         replace=False)

            self.plot_canvas[3].addCurve(self._defocus_sign *
                                         self.defocus_list * 1e3,
                                         numpy.multiply(self.hews_list, 1e6),
                                         color='blue',
                                         replace=False)

            # self.plot_histo(self._defocus_sign * self.defocus_list,
            #                 numpy.multiply(self.sigmas_list, 1e6),
            #                 100,
            #                 tabs_canvas_index=3,
            #                 plot_canvas_index=3,
            #                 title="SIGMA",
            #                 xtitle="",
            #                 ytitle="",
            #                 log_x=False,
            #                 log_y=False)

            self.plot_canvas[3].setDefaultPlotLines(True)
            self.plot_canvas[3].setDefaultPlotPoints(True)
            self.plot_canvas[3].setGraphXLabel("Defocus [mm]")
            self.plot_canvas[3].setGraphYLabel("Size [" + u"\u03BC" + "m]")

            self.best_focus_slider.setValue(index_min)

            self.tabs.setCurrentIndex(3 if self.show_animation == 1 else 2)
            self.setStatusMessage("")

            self.save_button.setEnabled(True)

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

            self.setStatusMessage("Error!")

            # raise exception

        if not self.best_focus_slider is None:
            self.best_focus_slider.valueChanged.connect(self.plot_detail)
        self.progressBarFinished()