Ejemplo n.º 1
0
    def generate_heigth_profile_file(self, not_interactive_mode=False):
        if not self.zz is None and not self.yy is None and not self.xx is None:
            try:
                congruence.checkDir(self.heigth_profile_file_name)

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

                ST.write_shadow_surface(self.zz, self.xx, self.yy, outFile=congruence.checkFileName(self.heigth_profile_file_name))
                if not not_interactive_mode:
                    QMessageBox.information(self, "QMessageBox.information()",
                                            "Height Profile file " + self.heigth_profile_file_name + " written on disk",
                                            QMessageBox.Ok)
                if self.modify_y == 0:
                    dimension_y = self.si_to_user_units * (self.server.y[-1] - self.server.y[0])
                if self.modify_y == 1:
                    dimension_y = self.si_to_user_units * (self.server.y[-1] - self.server.y[0]) * self.scale_factor_y
                elif self.modify_y == 2:
                    dimension_y = self.new_length

                self.send("PreProcessor_Data", ShadowPreProcessorData(error_profile_data_file=self.heigth_profile_file_name,
                                                                      error_profile_x_dim=self.dimension_x,
                                                                      error_profile_y_dim=dimension_y))
            except Exception as exception:
                QMessageBox.critical(self, "Error",
                                     exception.args[0],
                                     QMessageBox.Ok)
Ejemplo n.º 2
0
def create_surface_file(ftype="toroid",
                        p=18.8,
                        q=8.075,
                        theta=2e-3,
                        ratio=1.0):
    from Shadow import ShadowTools as ST
    from orangecontrib.syned.als.widgets.tools.ow_als_diaboloid import ken_diaboloid_segment_to_point
    from orangecontrib.syned.als.widgets.tools.ow_als_diaboloid import valeriy_diaboloid_exact_segment_to_point
    from orangecontrib.syned.als.widgets.tools.ow_als_diaboloid import valeriy_parabolic_cone_segment_to_point
    from orangecontrib.syned.als.widgets.tools.ow_als_diaboloid import toroid_segment_to_point

    Rs = 2.0 * numpy.sin(theta) / (1 / p + 1 / q) * ratio
    Y = numpy.linspace(-0.8, 0.8, 1001)
    X = numpy.linspace(-Rs, Rs, 101)

    if ftype == "toroid":
        Z = toroid_segment_to_point(p=p, q=q, theta=theta, x=X, y=Y)
    elif ftype == "diaboloid":
        Z, XX, YY = valeriy_diaboloid_exact_segment_to_point(p=p,
                                                             q=q,
                                                             theta=theta,
                                                             x=X,
                                                             y=Y)
    elif ftype == "parabolic-cone":
        Z, XX, YY = valeriy_parabolic_cone_segment_to_point(p=p,
                                                            q=q,
                                                            theta=theta,
                                                            x=X,
                                                            y=Y)

    # print(Z.shape, X.shape, Y.shape)
    ST.write_shadow_surface(Z.T, X, Y, "diaboloid_shadow.dat")

    return Rs
Ejemplo n.º 3
0
    def generate_waviness_file(self, not_interactive_mode=False):
        if not self.zz is None and not self.yy is None and not self.xx is None:
            try:
                congruence.checkDir(self.waviness_file_name)

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

                ST.write_shadow_surface(self.zz.T,
                                        self.xx,
                                        self.yy,
                                        outFile=congruence.checkFileName(
                                            self.waviness_file_name))
                if not not_interactive_mode:
                    QMessageBox.information(
                        self, "QMessageBox.information()", "Waviness file " +
                        self.waviness_file_name + " written on disk",
                        QMessageBox.Ok)

                self.send(
                    "PreProcessor_Data",
                    ShadowPreProcessorData(
                        error_profile_data_file=self.waviness_file_name,
                        error_profile_x_dim=self.dimension_x,
                        error_profile_y_dim=self.dimension_y))
            except Exception as exception:
                QMessageBox.critical(self, "Error", exception.args[0],
                                     QMessageBox.Ok)
Ejemplo n.º 4
0
    def write_inp_file(self):
        try:
            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            self.check_fields()

            file_name = congruence.checkFileName(
                self.waviness_file_name.split(sep=".dat")[0] + ".inp")

            dict = {}

            dict["npointx"] = self.number_of_points_x
            dict["npointy"] = self.number_of_points_y
            dict["xlength"] = self.dimension_y
            dict["width"] = self.dimension_x
            dict["slp"] = self.estimated_slope_error
            dict["iseed"] = self.montecarlo_seed
            dict["file"] = self.waviness_file_name.strip('\n\r')
            dict["nharmonics"] = self.harmonic_maximum_index

            dict["c"] = self.to_float_array(self.data["c"])
            dict["y"] = self.to_float_array(self.data["y"])
            dict["g"] = self.to_float_array(self.data["g"])

            ST.waviness_write(dict, file=file_name)

            QMessageBox.information(
                self, "QMessageBox.information()",
                "File \'" + file_name + "\' written to disk", QMessageBox.Ok)

        except Exception as exception:
            QMessageBox.critical(self, "Error", exception.args[0],
                                 QMessageBox.Ok)
Ejemplo n.º 5
0
    def write_inp_file(self):
        try:
            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            self.check_fields()

            file_name = self.waviness_file_name.strip().split(sep=".dat")[0] + ".inp"

            dict = {}

            dict["npointx"] = self.number_of_points_x
            dict["npointy"] = self.number_of_points_y
            dict["xlength"] = self.dimension_y
            dict["width"] = self.dimension_x
            dict["slp"] = self.estimated_slope_error
            dict["iseed"] = self.montecarlo_seed
            dict["file"] = self.waviness_file_name.strip('\n\r')
            dict["nharmonics"] = self.harmonic_maximum_index

            dict["c"] = self.to_float_array(self.data["c"])
            dict["y"] = self.to_float_array(self.data["y"])
            dict["g"] = self.to_float_array(self.data["g"])

            ST.waviness_write(dict, file=file_name)

            QMessageBox.information(self, "QMessageBox.information()",
                                    "File \'" + file_name + "\' written to disk",
                                    QMessageBox.Ok)

        except Exception as exception:
            QMessageBox.critical(self, "QMessageBox.critical()",
                                 exception.args[0],
                                 QMessageBox.Ok)
Ejemplo n.º 6
0
    def calculate_waviness(self):
        try:
            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            self.check_fields()

            xx, yy, zz = ST.waviness_calc(npointx=self.number_of_points_x,
                                          npointy=self.number_of_points_y,
                                          width=self.dimension_x,
                                          xlength=self.dimension_y,
                                          slp=self.estimated_slope_error,
                                          nharmonics=self.harmonic_maximum_index,
                                          iseed=self.montecarlo_seed,
                                          c=self.to_float_array(self.data["c"]),
                                          y=self.to_float_array(self.data["y"]),
                                          g=self.to_float_array(self.data["g"]))
            self.xx = xx
            self.yy = yy
            self.zz = zz

            self.axis.clear()

            x_to_plot, y_to_plot = numpy.meshgrid(xx, yy)
            z_to_plot = []

            for y_index in range(0, len(yy)):
                z_array = []
                for x_index in range(0, len(xx)):
                    z_array.append(1e4 * float(zz[x_index][y_index]))  # to micron
                z_to_plot.append(z_array)

            z_to_plot = numpy.array(z_to_plot)

            self.axis.plot_surface(x_to_plot, y_to_plot, z_to_plot,
                                   rstride=1, cstride=1, cmap=cm.autumn, linewidth=0.5, antialiased=True)

            slope, sloperms = ST.slopes(zz, xx, yy)

            title = ' Slope error rms in X direction: %f arcsec' % (sloperms[0]) + '\n' + \
                    '                                            : %f urad' % (sloperms[2]) + '\n' + \
                    ' Slope error rms in Y direction: %f arcsec' % (sloperms[1]) + '\n' + \
                    '                                            : %f urad' % (sloperms[3])

            self.axis.set_xlabel("X (cm)")
            self.axis.set_ylabel("Y (cm)")
            self.axis.set_zlabel("Z (µm)")
            self.axis.set_title(title)
            self.axis.mouse_init()

            self.figure_canvas.draw()

            QMessageBox.information(self, "QMessageBox.information()",
                                    "Waviness calculated: if the result is satisfactory,\nclick \'Generate Waviness File\' to complete the operation ",
                                    QMessageBox.Ok)
        except Exception as exception:
            QMessageBox.critical(self, "QMessageBox.critical()",
                                 exception.args[0],
                                 QMessageBox.Ok)
Ejemplo n.º 7
0
    def intensityFromBeam(self, beam):
        st.plotxy(beam, 1, 3)

        # return value is expected to be [z(x,y),x,y]
        intensity = [
            np.arange(9).reshape((3, 3)),
            np.array([0.0, 1.0, 2.0]),
            np.array([0.0, 1.0, 2.0])
        ]

        return intensity
Ejemplo n.º 8
0
    def write_shadow_and_hybrid_files(self, error_profile_data_files, index, xx, yy, zz):
        zz = zz / self.workspace_units_to_m
        xx = numpy.round(xx / self.workspace_units_to_m, 6)
        yy = numpy.round(yy / self.workspace_units_to_m, 6)

        filename, _ = os.path.splitext(os.path.basename(self.surface_file_names[index]))

        error_profile_data_file        = filename + "_shadow.dat"
        hybrid_error_profile_data_file = filename + "_hybrid.h5"

        ST.write_shadow_surface(zz, xx, yy, error_profile_data_file)
        OU.write_surface_file(zz, xx, yy, hybrid_error_profile_data_file)

        error_profile_data_files.append([error_profile_data_file, hybrid_error_profile_data_file])
Ejemplo n.º 9
0
    def load_inp_file(self):
        file_name = oasysgui.selectFileFromDialog(
            self,
            None,
            "Select a input file for XSH_WAVINESS",
            file_extension_filter="Input Files (*.inp)")

        if not file_name is None:
            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            if not file_name.strip() == "":
                dict = ST.waviness_read(file=file_name)

                self.number_of_points_x = dict["npointx"]
                self.number_of_points_y = dict["npointy"]
                self.dimension_y = dict["xlength"]
                self.dimension_x = dict["width"]
                self.estimated_slope_error = dict["slp"]
                self.montecarlo_seed = dict["iseed"]
                self.waviness_file_name = dict["file"].strip('\n\r').strip()
                self.harmonic_maximum_index = dict["nharmonics"]

                self.data["c"] = self.to_str_array(dict["c"])
                self.data["y"] = self.to_str_array(dict["y"])
                self.data["g"] = self.to_str_array(dict["g"])

                self.reload_harmonics_table()
Ejemplo n.º 10
0
    def setBeam(self, beam):
        if ShadowGui.checkEmptyBeam(beam):
            if ShadowGui.checkGoodBeam(beam):
                sys.stdout = EmittingStream(textWritten=self.writeStdOut)

                self.input_beam = beam

                self.sysInfo.setText("\n\n\n\n\nNot Available")

                optical_element_list = []

                for history_element in self.input_beam.getOEHistory():
                    if not history_element.shadow_source_start is None:
                        optical_element_list.append(history_element.shadow_source_start.src)
                    elif not history_element.shadow_oe_start is None:
                        optical_element_list.append(history_element.shadow_oe_start.oe)

                    if not history_element.shadow_source_end is None:
                        self.sourceInfo.append(history_element.shadow_source_end.src.sourcinfo())
                    elif not history_element.shadow_oe_end is None:
                        self.mirInfo.append(history_element.shadow_oe_end.oe.mirinfo(title="O.E. #" + str(history_element.oe_number)))

                self.pythonScript.setText(ST.make_python_script_from_list(optical_element_list))
            else:
                QtGui.QMessageBox.critical(self, "QMessageBox.critical()",
                                           "Data not displayable: No good rays or bad content",
                                           QtGui.QMessageBox.Ok)
Ejemplo n.º 11
0
    def convert_surface(self):
        if not self.oasys_data is None:
            try:
                if isinstance(self.oasys_data, OasysPreProcessorData):
                    error_profile_data = self.oasys_data.error_profile_data
                    surface_data = error_profile_data.surface_data
                    error_profile_data_file = surface_data.surface_data_file

                    filename, file_extension = os.path.splitext(error_profile_data_file)

                    if (file_extension==".hd5" or file_extension==".hdf5" or file_extension==".hdf" or file_extension==".h5"):
                        error_profile_data_file = filename + "_shadow.dat"

                    ST.write_shadow_surface(surface_data.zz/self.workspace_units_to_m,
                                            numpy.round(surface_data.xx/self.workspace_units_to_m, 6),
                                            numpy.round(surface_data.yy/self.workspace_units_to_m, 6),
                                            error_profile_data_file)

                    self.send("PreProcessor_Data", ShadowPreProcessorData(error_profile_data_file=error_profile_data_file,
                                                                          error_profile_x_dim=error_profile_data.error_profile_x_dim/self.workspace_units_to_m,
                                                                          error_profile_y_dim=error_profile_data.error_profile_y_dim/self.workspace_units_to_m))
                elif isinstance(self.oasys_data, OasysSurfaceData):
                    surface_data_file = self.oasys_data.surface_data_file

                    filename, file_extension = os.path.splitext(surface_data_file)

                    if (file_extension==".hd5" or file_extension==".hdf5" or file_extension==".hdf" or file_extension==".h5"):
                        surface_data_file = filename + "_shadow.dat"

                    ST.write_shadow_surface(self.oasys_data.zz/self.workspace_units_to_m,
                                            numpy.round(self.oasys_data.xx/self.workspace_units_to_m, 9),
                                            numpy.round(self.oasys_data.yy/self.workspace_units_to_m, 9),
                                            surface_data_file)

                    error_profile_x_dim = abs(self.oasys_data.xx[-1] - self.oasys_data.xx[0])/self.workspace_units_to_m
                    error_profile_y_dim = abs(self.oasys_data.yy[-1] - self.oasys_data.yy[0])/self.workspace_units_to_m

                    self.send("PreProcessor_Data", ShadowPreProcessorData(error_profile_data_file=surface_data_file,
                                                                          error_profile_x_dim=error_profile_x_dim,
                                                                          error_profile_y_dim=error_profile_y_dim))



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

                if self.IS_DEVELOP: raise exception
Ejemplo n.º 12
0
    def generate_waviness_file(self):
        if not self.zz is None and not self.yy is None and not self.xx is None:
            if not self.waviness_file_name is None:
                self.waviness_file_name = self.waviness_file_name.strip()

                if self.waviness_file_name == "": raise Exception("Output File Name missing")
            else:
                raise Exception("Output File Name missing")

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

            ST.write_shadow_surface(self.zz.T, self.xx, self.yy, outFile=self.waviness_file_name)
            QMessageBox.information(self, "QMessageBox.information()",
                                    "Waviness file " + self.waviness_file_name + " written on disk",
                                    QMessageBox.Ok)

            self.send("PreProcessor_Data", ShadowPreProcessorData(waviness_data_file=self.waviness_file_name))
Ejemplo n.º 13
0
    def convert_surfaces(self):
        if not self.oasys_data is None:
            try:
                if isinstance(self.oasys_data, OasysPreProcessorData):
                    error_profile_data = self.oasys_data.error_profile_data
                    surface_data = error_profile_data.surface_data

                    error_profile_data_files = []

                    for xx, yy, zz, error_profile_data_file in zip(
                            surface_data.xx, surface_data.yy, surface_data.zz,
                            surface_data.surface_data_file):

                        filename, file_extension = os.path.splitext(
                            error_profile_data_file)

                        if (file_extension == ".hd5"
                                or file_extension == ".hdf5"
                                or file_extension == ".hdf"):
                            error_profile_data_file = filename + "_shadow.dat"

                        ST.write_shadow_surface(
                            zz / self.workspace_units_to_m,
                            numpy.round(xx / self.workspace_units_to_m, 6),
                            numpy.round(yy / self.workspace_units_to_m, 6),
                            error_profile_data_file)

                        error_profile_data_files.append(
                            error_profile_data_file)

                    self.send(
                        "PreProcessor_Data",
                        ShadowPreProcessorData(
                            error_profile_data_file=error_profile_data_files,
                            error_profile_x_dim=error_profile_data.
                            error_profile_x_dim / self.workspace_units_to_m,
                            error_profile_y_dim=error_profile_data.
                            error_profile_y_dim / self.workspace_units_to_m))
                    self.send("Files", error_profile_data_files)
            except Exception as exception:
                QMessageBox.critical(self, "Error", str(exception),
                                     QMessageBox.Ok)

                if self.IS_DEVELOP: raise exception
Ejemplo n.º 14
0
    def generate_waviness_file(self, not_interactive_mode=False):
        if not self.zz is None and not self.yy is None and not self.xx is None:
            try:
                congruence.checkDir(self.waviness_file_name)

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

                ST.write_shadow_surface(self.zz.T, self.xx, self.yy, outFile=congruence.checkFileName(self.waviness_file_name))
                if not not_interactive_mode:
                    QMessageBox.information(self, "QMessageBox.information()",
                                            "Waviness file " + self.waviness_file_name + " written on disk",
                                            QMessageBox.Ok)

                self.send("PreProcessor_Data", ShadowPreProcessorData(error_profile_data_file=self.waviness_file_name,
                                                                      error_profile_x_dim=self.dimension_x,
                                                                      error_profile_y_dim=self.dimension_y))
            except Exception as exception:
                QMessageBox.critical(self, "Error",
                                     exception.args[0],
                                     QMessageBox.Ok)
Ejemplo n.º 15
0
    def load_inp_file(self):
        file_name = QFileDialog.getOpenFileName(self, "Select a input file for XSH_WAVINESS", ".", "*.inp")

        if not file_name is None:
            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            if not file_name.strip() == "":
                dict = ST.waviness_read(file=file_name)

                self.number_of_points_x = dict["npointx"]
                self.number_of_points_y = dict["npointy"]
                self.dimension_y = dict["xlength"]
                self.dimension_x = dict["width"]
                self.estimated_slope_error = dict["slp"]
                self.montecarlo_seed = dict["iseed"]
                self.waviness_file_name = dict["file"].strip('\n\r').strip()
                self.harmonic_maximum_index = dict["nharmonics"]

                self.data["c"] = self.to_str_array(dict["c"])
                self.data["y"] = self.to_str_array(dict["y"])
                self.data["g"] = self.to_str_array(dict["g"])

                self.reload_harmonics_table()
Ejemplo n.º 16
0
    def calculate_waviness(self, not_interactive_mode=False):
        try:
            sys.stdout = EmittingStream(textWritten=self.writeStdOut)

            self.check_fields()

            xx, yy, zz = ST.waviness_calc(
                npointx=self.number_of_points_x,
                npointy=self.number_of_points_y,
                width=self.dimension_x * self.workspace_units_to_cm,
                xlength=self.dimension_y * self.workspace_units_to_cm,
                slp=self.estimated_slope_error,
                nharmonics=self.harmonic_maximum_index,
                iseed=self.montecarlo_seed,
                c=self.to_float_array(self.data["c"]),
                y=self.to_float_array(self.data["y"]),
                g=self.to_float_array(self.data["g"]))

            self.xx = xx / self.workspace_units_to_cm
            self.yy = yy / self.workspace_units_to_cm
            self.zz = zz / self.workspace_units_to_cm

            self.axis.clear()

            x_to_plot, y_to_plot = numpy.meshgrid(self.xx, self.yy)
            z_to_plot = []

            for y_index in range(0, len(yy)):
                z_array = []
                for x_index in range(0, len(xx)):
                    z_array.append(1e7 * float(zz[x_index][y_index]))  # to nm
                z_to_plot.append(z_array)

            z_to_plot = numpy.array(z_to_plot)

            self.axis.plot_surface(x_to_plot,
                                   y_to_plot,
                                   z_to_plot,
                                   rstride=1,
                                   cstride=1,
                                   cmap=cm.autumn,
                                   linewidth=0.5,
                                   antialiased=True)

            slope, sloperms = ST.slopes(zz, xx, yy)

            title = ' Slope error rms in X direction: %f $\mu$rad' % (sloperms[0]*1e6) + '\n' + \
                    ' Slope error rms in Y direction: %f $\mu$rad' % (sloperms[1]*1e6)

            self.axis.set_xlabel("X [" + self.workspace_units_label + "]")
            self.axis.set_ylabel("Y [" + self.workspace_units_label + "]")
            self.axis.set_zlabel("Z [nm]")
            self.axis.set_title(title)
            self.axis.mouse_init()

            if not not_interactive_mode:
                self.figure_canvas.draw()

                QMessageBox.information(
                    self, "QMessageBox.information()",
                    "Waviness calculated: if the result is satisfactory,\nclick \'Generate Waviness File\' to complete the operation ",
                    QMessageBox.Ok)
        except Exception as exception:
            QMessageBox.critical(self, "Error", exception.args[0],
                                 QMessageBox.Ok)
def main():
    # inputs (working in m)
    useshadow = 1
    slitdistance =     30.9   # m
    detdistance  =     1.38   # m
    detsize      =     200e-6 # m
    energy       =     14.0    # keV
    realisations    =  1000
    lensF = None # detdistance/2 # focal distance
    shadowunits2m = 1e-2

    wavelength   =   12.398/(energy)*1e-10  # m
    #wavelength   =   500.0e-6 # mm
    # open output file
    f = open('twoslitsLeitenberger.spec', 'w')
    header="#F twoslitsLeitenberger.spec \n"
    f.write(header)


     
    # read shadow files
    #
    flag=st.getshcol("star.01",10)
    igood = numpy.where(flag >= 0)
    igood = numpy.array(igood)
    igood.shape = -1
    print(flag.size)
    print('igood: ',igood.size)
    print('--------------')

    # use shadow's number of points
    #sourcepoints = 200
    sourcepoints = igood.size
    slitpoints = sourcepoints/2
    detpoints = sourcepoints

    if useshadow == 1:
        #shadow
        position1x = st.getshcol("begin.dat",3) * shadowunits2m
        position1x = position1x[igood]
        position1x.shape = -1
    else:
        #grid
        sourcesize = 140e-6
        position1x = numpy.linspace(-sourcesize/2,sourcesize/2,sourcepoints)

    #position1x = st.getshcol("begin.dat",3) # * shadowunits2m
    #position1x = position1x[igood]
    #position1x.shape = -1
    #sourcesize = 140e-6
    #position1x = numpy.linspace(-sourcesize/2,sourcesize/2,sourcepoints)
    print('>>> maxmin: ',position1x.min(), position1x.max())
    

    if useshadow == 1:
        #shadow
        position2x = st.getshcol("screen.0101",3) * shadowunits2m
        position2x = position2x[igood]
        position2x.shape = -1
    else:
        #grid
        slitsize = 2e-6
        slitgap = 11.3e-6
        tmp = numpy.linspace(-slitsize/2,slitsize/2,slitpoints)
        position2x = numpy.concatenate((tmp-slitgap/2,tmp+slitgap/2))


    #position3x = st.getshcol("star.02",3)
    #position3x = position3x[igood]
    #position3x.shape = -1
    #direction3x = st.getshcol("star.02",6)
    #direction3x = direction3x[igood]
    #direction3x.shape = -1
    #vz0101 = st.getshcol("screen.0101",6)
    #vz0201 = st.getshcol("screen.0201",6)

    # working with angles...
    #tmp3 = -numpy.cos(numpy.arcsin(vz0201 -vz0101))
    #tmp3 = (tmp3-tmp3.min()) * 1590.0
    #tmp3 = tmp3[igood]
    #tmp3.shape = -1

    # working with differences
    #tmp3 = (vz0201 -vz0101)
    #tmp3 = tmp3[igood]
    #tmp3.shape = -1

    position3x = numpy.linspace(-detsize/2,detsize/2,igood.size)


    print('igood: ',igood.size,position1x.size,position2x.size,position3x.size)
    print('shape: ',igood.shape)
    #for j in range(detpoints):
    #    print j,igood[j],position1x[j],position2x[j],position3x[j]
    

    #direction3x = None
    if useshadow == 0:
        fields12 = goFromToShadow(position1x,position2x,slitdistance, lensF=None,wavelength=wavelength)
        fields23 = goFromToShadow(position2x,position3x,detdistance, lensF=None,wavelength=wavelength)
    else:
        fields12 = goFromTo(position1x,position2x,slitdistance, lensF=None,wavelength=wavelength)
        fields23 = goFromTo(position2x,position3x,detdistance, lensF=None,wavelength=wavelength)

    # from 1 to 3, matrix multiplication
    fields13 = numpy.dot(fields12,fields23)
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #fields13 = fields23
    
    print('shape 12: ',fields12.shape)
    print('shape 23: ',fields23.shape)
    print('shape 13: ',fields23.shape)
    #sourcepoints = igood.size
    fieldComplexAmplitude = numpy.dot(numpy.ones(sourcepoints),fields13)
    fieldIntensity = numpy.power(numpy.abs(fieldComplexAmplitude),2)
    fieldPhase = numpy.arctan2(numpy.real(fieldComplexAmplitude), numpy.imag(fieldComplexAmplitude))
 

    print('fields: ',fields12.shape, fields23.shape)


    # do the ensemble average
    tmpSource = numpy.exp(1.j*2*numpy.pi* numpy.random.mtrand.rand(sourcepoints))
    fieldSource=tmpSource
    fieldIntensityEA = numpy.power(numpy.abs(fieldComplexAmplitude),2)
    for i in range(realisations-1): 
      #tmpSource = numpy.exp(1.j*2* numpy.pi*numpy.random.mtrand.rand(sourcepoints))
      #fieldComplexAmplitude = numpy.dot( tmpSource, fields13)
      #fieldIntensityEA = fieldIntensityEA + numpy.power(numpy.abs(fieldComplexAmplitude),2)

      tmpSource = numpy.exp(1.j*2* \
          numpy.pi*numpy.random.mtrand.rand(sourcepoints))
      fieldComplexAmplitude = numpy.dot( tmpSource, fields13)
      fieldIntensityEA = fieldIntensityEA + \
          numpy.power(numpy.abs(fieldComplexAmplitude),2)
    
    header="\n#S  1 2h=??\n"
    f.write(header)
    header="#N 4 \n#L Z[um]  intensityCoh  phaseCoh  intensityEnsemble\n"
    f.write(header)
    
    for i in range(igood.size):
       out = numpy.array((position3x[i]*1e6,  fieldIntensity[i], fieldPhase[i], fieldIntensityEA[i]))
       f.write( ("%20.11e "*out.size+"\n") % tuple( out.tolist())  )

    f.close()
    print("File written to disk: twoslitsLeitenberger.spec")
    return position3x,fieldIntensity,fieldIntensityEA
    def completeOperations(self, shadow_oe):
        shadow_oe_temp = shadow_oe.duplicate()
        input_beam_temp = self.input_beam.duplicate(history=False)

        self.manage_acceptance_slits(shadow_oe_temp)

        ShadowBeam.traceFromOE(input_beam_temp,
                               shadow_oe_temp,
                               write_start_file=0,
                               write_end_file=0,
                               widget_class_name=type(self).__name__)

        x, y, z = self.calculate_ideal_surface(shadow_oe_temp)

        bender_parameter, z_bender_correction = self.calculate_bender_correction(
            y, z, self.kind_of_bender, self.shape)

        self.M1_out = round(bender_parameter[0],
                            int(6 * self.workspace_units_to_mm))
        if self.shape == TRAPEZIUM:
            self.e_out = round(bender_parameter[1], 5)
            if self.kind_of_bender == DOUBLE_MOMENTUM:
                self.ratio_out = round(bender_parameter[2], 5)
        elif self.shape == RECTANGLE:
            if self.kind_of_bender == DOUBLE_MOMENTUM:
                self.ratio_out = round(bender_parameter[1], 5)

        self.plot3D(x, y, z_bender_correction, 2, "Ideal - Bender Surfaces")

        if self.modified_surface > 0:
            x_e, y_e, z_e = ShadowPreProcessor.read_surface_error_file(
                self.ms_defect_file_name)

            if len(x) == len(x_e) and len(y) == len(y_e) and \
                    x[0] == x_e[0] and x[-1] == x_e[-1] and \
                    y[0] == y_e[0] and y[-1] == y_e[-1]:
                z_figure_error = z_e
            else:
                z_figure_error = interp2d(y_e, x_e, z_e, kind='cubic')(y, x)

            z_bender_correction += z_figure_error

            self.plot3D(x, y, z_figure_error, 3, "Figure Error Surface")
            self.plot3D(x, y, z_bender_correction, 4,
                        "Ideal - Bender + Figure Error Surfaces")

        ST.write_shadow_surface(z_bender_correction.T, numpy.round(x, 6),
                                numpy.round(y, 6), self.output_file_name_full)

        # Add new surface as figure error
        shadow_oe._oe.F_RIPPLE = 1
        shadow_oe._oe.F_G_S = 2
        shadow_oe._oe.FILE_RIP = bytes(self.output_file_name_full, 'utf-8')

        # Redo Raytracing with the new file
        super().completeOperations(shadow_oe)

        self.send(
            "PreProcessor_Data",
            ShadowPreProcessorData(
                error_profile_data_file=self.output_file_name,
                error_profile_x_dim=self.dim_x_plus + self.dim_x_minus,
                error_profile_y_dim=self.dim_y_plus + self.dim_y_minus))
Ejemplo n.º 19
0
# get Shadow source
#
if source_create == 1:
    # creates source from start.00 if "-s"
    src.load('start.00')
    beamSource.genSource(src)
    if write:
        beamSource.write("begin.dat")
else:
    # reads source from binary file" start.00
    beamSource.load('begin.dat')

#
# get fwhm of the source
#
g1 = st.plotxy(beamSource, 1, 3, calfwhm=1, nbins=200, noplot=noplot)
fw0 = numpy.array([g1.fwhmx, g1.fwhmy])

#
# start loop on scanList
#
for scanIndex, scanWhat in enumerate(scanList):
    # loop on scanning variable
    out = numpy.zeros((9, scan1.size))

    for i in range(scan1.size):
        oe1.load("start.01")
        #run system with only 1 oe
        if write:
            oe1.FWRITE = 0  # write(0) or not(3) binary files
        else:
Ejemplo n.º 20
0
    def setBeam(self, beam):
        if ShadowCongruence.checkEmptyBeam(beam):
            if ShadowCongruence.checkGoodBeam(beam):
                sys.stdout = EmittingStream(textWritten=self.writeStdOut)

                self.input_beam = beam

                optical_element_list_start = []
                optical_element_list_end = []

                self.sysInfo.setText("")
                self.mirInfo.setText("")
                self.sourceInfo.setText("")
                self.distancesSummary.setText("")
                self.pythonScript.setText("")

                for history_element in self.input_beam.getOEHistory():
                    if not history_element._shadow_source_start is None:
                        optical_element_list_start.append(
                            history_element._shadow_source_start.src)
                    elif not history_element._shadow_oe_start is None:
                        optical_element_list_start.append(
                            history_element._shadow_oe_start._oe)

                    if not history_element._shadow_source_end is None:
                        optical_element_list_end.append(
                            history_element._shadow_source_end.src)
                    elif not history_element._shadow_oe_end is None:
                        optical_element_list_end.append(
                            history_element._shadow_oe_end._oe)

                    if not history_element._shadow_source_end is None:
                        try:
                            self.sourceInfo.append(
                                history_element._shadow_source_end.src.
                                sourcinfo())
                        except:
                            self.sourceInfo.append(
                                "Problem in calculating Source Info:\n" +
                                str(sys.exc_info()[0]) + ": " +
                                str(sys.exc_info()[1]))
                    elif not history_element._shadow_oe_end is None:
                        try:
                            if isinstance(history_element._shadow_oe_end._oe,
                                          CompoundOE):
                                self.mirInfo.append(
                                    history_element._shadow_oe_end._oe.mirinfo(
                                    ))
                            else:
                                self.mirInfo.append(
                                    history_element._shadow_oe_end._oe.mirinfo(
                                        title="O.E. #" +
                                        str(history_element._oe_number)))
                        except:
                            self.sourceInfo.append(
                                "Problem in calculating Mir Info for O.E. #:" +
                                str(history_element._oe_number) + "\n" +
                                str(sys.exc_info()[0]) + ": " +
                                str(sys.exc_info()[1]))

                coe_end = ShadowCompoundOpticalElement.create_compound_oe(
                    workspace_units_to_cm=self.workspace_units_to_cm)
                for oe in optical_element_list_end:
                    coe_end._oe.append(oe)

                try:
                    self.sysInfo.setText(coe_end._oe.sysinfo())
                except:
                    self.distancesSummary.setText(
                        "Problem in calculating SysInfo:\n" +
                        str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))

                try:
                    dic = coe_end._oe.syspositions()

                    self.sysPlotSide.addCurve(dic["optical_axis_y"],
                                              dic["optical_axis_z"],
                                              symbol='o',
                                              replace=True)
                    self.sysPlotSide.setGraphXLabel("Y [%s]" %
                                                    self.workspace_units_label)
                    self.sysPlotSide.setGraphYLabel("Z [%s]" %
                                                    self.workspace_units_label)
                    self.sysPlotSide.setGraphTitle("Side View of optical axis")
                    self.sysPlotSide.replot()

                    self.sysPlotTop.addCurve(dic["optical_axis_y"],
                                             dic["optical_axis_x"],
                                             symbol='o',
                                             replace=True)
                    self.sysPlotTop.setGraphXLabel("Y [%s]" %
                                                   self.workspace_units_label)
                    self.sysPlotTop.setGraphYLabel("X [%s]" %
                                                   self.workspace_units_label)
                    self.sysPlotTop.setGraphTitle("Top View of optical axis")
                    self.sysPlotTop.replot()

                except:
                    self.distancesSummary.setText(
                        "Problem in calculating SysPlot:\n" +
                        str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))

                try:
                    self.distancesSummary.setText(coe_end._oe.info())
                except:
                    self.distancesSummary.setText(
                        "Problem in calculating Distance Summary:\n" +
                        str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))

                try:
                    self.pythonScript.setText(
                        ST.make_python_script_from_list(
                            optical_element_list_start))
                except:
                    self.pythonScript.setText(
                        "Problem in writing python script:\n" +
                        str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))
            else:
                QtWidgets.QMessageBox.critical(
                    self, "Error",
                    "Data not displayable: No good rays or bad content",
                    QtWidgets.QMessageBox.Ok)
Ejemplo n.º 21
0
    bm = Shadow3BendingMagnetLightSource(
        electron_beam=electron_beam,
        bending_magnet_magnetic_structure=BendingMagnet(radius=0.0,
                                                        magnetic_field=1.2,
                                                        length=0.0),
        bending_magnet_parameters=Shadow3BendingMagnetParameters(NPOINT=50000))

    slit = Shadow3Slit(name="first slit",
                       boundary_shape=Rectangle(x_left=-0.0001,
                                                x_right=0.0001,
                                                y_bottom=-0.0005,
                                                y_top=0.0005),
                       slit_parameters=Shadow3SlitParameters())

    slit_coordinates = ElementCoordinates(p=10.0, q=0.0)

    elements = RaytracingElements()
    elements.add_beamline_element(
        BeamlineElement(optical_element=slit, coordinates=slit_coordinates))

    raytracing_parameters = RaytracingParameters(beam=bm.generate_source(),
                                                 raytracing_elements=elements)

    beam = raytracing_manager.do_raytracing(
        raytracing_parameters=raytracing_parameters,
        handler_name=Shadow3Raytracer.HANDLER_NAME)

    import Shadow.ShadowTools as ST

    ST.plotxy(beam, 1, 3, nolost=True)
    # ST.histo1(beam,11)
 def write_error_profile_file(self, zz, xx, yy, outFile):
     ST.write_shadow_surface(zz, xx, yy, outFile)
Ejemplo n.º 23
0
    def calculate(self):
        if ShadowCongruence.checkEmptyBeam(self.input_beam):
            if ShadowCongruence.checkGoodBeam(self.input_beam):

                beam_to_analize = self.input_beam._beam

                if self.image_plane == 1:
                    new_shadow_beam = self.input_beam.duplicate(history=False)
                    dist = 0.0

                    if self.image_plane_rel_abs_position == 1:  # relative
                        dist = self.image_plane_new_position
                    else:  # absolute
                        historyItem = self.input_beam.getOEHistory(oe_number=self.input_beam._oe_number)

                        if historyItem is None: image_plane = 0.0
                        elif self.input_beam._oe_number == 0: image_plane = 0.0
                        else: image_plane = historyItem._shadow_oe_end._oe.T_IMAGE

                        dist = self.image_plane_new_position - image_plane

                    new_shadow_beam._beam.retrace(dist)

                    beam_to_analize = new_shadow_beam._beam

                if self.mode==2:
                    center=[self.center_x, self.center_z]
                else:
                    center=[0.0, 0.0]

                if self.y_range == 1:
                    if self.y_range_min >= self.y_range_max:
                        raise Exception("Y range min cannot be greater or than Y range max")

                ticket = ST.focnew(beam_to_analize, mode=self.mode, center=center)

                self.focnewInfo.setText(ticket["text"])

                if self.plot_canvas_x is None:
                    self.plot_canvas_x = PlotWindow(roi=False, control=False, position=True, plugins=False)
                    self.plot_canvas_x.setDefaultPlotLines(True)
                    self.plot_canvas_x.setActiveCurveColor(color='blue')
                    self.plot_canvas_x.setDrawModeEnabled(False)
                    self.plot_canvas_x.setZoomModeEnabled(False)
                    self.plot_canvas_x.toolBar.setVisible(False)

                    self.plot_canvas_z = PlotWindow(roi=False, control=False, position=True, plugins=False)
                    self.plot_canvas_z.setDefaultPlotLines(True)
                    self.plot_canvas_z.setActiveCurveColor(color='red')
                    self.plot_canvas_z.setDrawModeEnabled(False)
                    self.plot_canvas_z.setZoomModeEnabled(False)
                    self.plot_canvas_z.toolBar.setVisible(False)

                    self.plot_canvas_t = PlotWindow(roi=False, control=False, position=True, plugins=False)
                    self.plot_canvas_t.setDefaultPlotLines(True)
                    self.plot_canvas_t.setActiveCurveColor(color='green')
                    self.plot_canvas_t.setDrawModeEnabled(False)
                    self.plot_canvas_t.setZoomModeEnabled(False)
                    self.plot_canvas_t.toolBar.setVisible(False)

                    gridLayout = QtGui.QGridLayout()

                    gridLayout.addWidget(self.plot_canvas_x, 0, 0)
                    gridLayout.addWidget(self.plot_canvas_z, 0, 1)
                    gridLayout.addWidget(self.plot_canvas_t, 1, 0)

                    widget = QtGui.QWidget()
                    widget.setLayout(gridLayout)

                    self.image_box.layout().addWidget(widget)

                if self.y_range == 0:
                    y = numpy.linspace(-10.0, 10.0, 1001)
                else:
                    y = numpy.linspace(self.y_range_min, self.y_range_max, self.y_npoints)

                pos = [0.25, 0.15, 0.7, 0.75]

                self.plot_canvas_x.addCurve(y, 2.35*ST.focnew_scan(ticket["AX"], y)*ShadowPlot.get_factor(1, self.workspace_units_to_cm), "x (tangential)", symbol='', color="blue", replace=True) #'+', '^', ','
                self.plot_canvas_x._plot.graph.ax.get_yaxis().get_major_formatter().set_useOffset(True)
                self.plot_canvas_x._plot.graph.ax.get_yaxis().get_major_formatter().set_scientific(True)
                self.plot_canvas_x._plot.graph.ax.set_position(pos)
                self.plot_canvas_x._plot.graph.ax2.set_position(pos)
                self.plot_canvas_x.setGraphXLabel("Y [" + self.workspace_units_label + "]")
                self.plot_canvas_x.setGraphYLabel("2.35*<X> [$\mu$m]")
                self.plot_canvas_x._plot.graph.ax.set_title("X", horizontalalignment='left')
                self.plot_canvas_x.replot()

                self.plot_canvas_z.addCurve(y, 2.35*ST.focnew_scan(ticket["AZ"], y)*ShadowPlot.get_factor(3, self.workspace_units_to_cm), "z (sagittal)", symbol='', color="red", replace=False) #'+', '^', ','
                self.plot_canvas_z._plot.graph.ax.get_yaxis().get_major_formatter().set_useOffset(True)
                self.plot_canvas_z._plot.graph.ax.get_yaxis().get_major_formatter().set_scientific(True)
                self.plot_canvas_z._plot.graph.ax.set_position(pos)
                self.plot_canvas_z._plot.graph.ax2.set_position(pos)
                self.plot_canvas_z.setGraphXLabel("Y [" + self.workspace_units_label + "]")
                self.plot_canvas_z.setGraphYLabel("2.35*<Z> [$\mu$m]")
                self.plot_canvas_z._plot.graph.ax.set_title("Z", horizontalalignment='left')
                self.plot_canvas_z.replot()

                self.plot_canvas_t.addCurve(y, 2.35*ST.focnew_scan(ticket["AT"], y)*ShadowPlot.get_factor(1, self.workspace_units_to_cm), "combined x,z", symbol='', color="green", replace=True) #'+', '^', ','
                self.plot_canvas_t._plot.graph.ax.get_yaxis().get_major_formatter().set_useOffset(True)
                self.plot_canvas_t._plot.graph.ax.get_yaxis().get_major_formatter().set_scientific(True)
                self.plot_canvas_t._plot.graph.ax.set_position(pos)
                self.plot_canvas_t._plot.graph.ax2.set_position(pos)
                self.plot_canvas_t.setGraphXLabel("Y [" + self.workspace_units_label + "]")
                self.plot_canvas_t.setGraphYLabel("2.35*<X,Z> [$\mu$m]")
                self.plot_canvas_t._plot.graph.ax.set_title("X,Z (Combined)", horizontalalignment='left')
                self.plot_canvas_t.replot()
Ejemplo n.º 24
0
    def calculate(self):
        if ShadowCongruence.checkEmptyBeam(self.input_beam):
            if ShadowCongruence.checkGoodBeam(self.input_beam):

                beam_to_analize = self.input_beam._beam

                if self.image_plane == 1:
                    new_shadow_beam = self.input_beam.duplicate(history=False)
                    dist = 0.0

                    if self.image_plane_rel_abs_position == 1:  # relative
                        dist = self.image_plane_new_position
                    else:  # absolute
                        historyItem = self.input_beam.getOEHistory(
                            oe_number=self.input_beam._oe_number)

                        if historyItem is None: image_plane = 0.0
                        elif self.input_beam._oe_number == 0: image_plane = 0.0
                        else:
                            image_plane = historyItem._shadow_oe_end._oe.T_IMAGE

                        dist = self.image_plane_new_position - image_plane

                    new_shadow_beam._beam.retrace(dist)

                    beam_to_analize = new_shadow_beam._beam

                if self.mode == 2:
                    center = [self.center_x, self.center_z]
                else:
                    center = [0.0, 0.0]

                if self.y_range == 1:
                    if self.y_range_min >= self.y_range_max:
                        raise Exception(
                            "Y range min cannot be greater or than Y range max"
                        )

                ticket = ST.focnew(beam_to_analize,
                                   mode=self.mode,
                                   center=center)

                self.focnewInfo.setText(ticket["text"])

                if self.plot_canvas_x is None:
                    self.plot_canvas_x = oasysgui.plotWindow(roi=False,
                                                             control=False,
                                                             position=True)
                    self.plot_canvas_x.setDefaultPlotLines(True)
                    self.plot_canvas_x.setActiveCurveColor(color='blue')
                    self.plot_canvas_x.setInteractiveMode(mode='zoom')
                    self.plot_canvas_x.toolBar().setVisible(False)

                    self.plot_canvas_z = oasysgui.plotWindow(roi=False,
                                                             control=False,
                                                             position=True)
                    self.plot_canvas_z.setDefaultPlotLines(True)
                    self.plot_canvas_z.setActiveCurveColor(color='red')
                    self.plot_canvas_z.setInteractiveMode(mode='zoom')
                    self.plot_canvas_z.toolBar().setVisible(False)

                    self.plot_canvas_t = oasysgui.plotWindow(roi=False,
                                                             control=False,
                                                             position=True)
                    self.plot_canvas_t.setDefaultPlotLines(True)
                    self.plot_canvas_t.setActiveCurveColor(color='green')
                    self.plot_canvas_t.setInteractiveMode(mode='zoom')
                    self.plot_canvas_t.toolBar().setVisible(False)

                    gridLayout = QtWidgets.QGridLayout()

                    gridLayout.addWidget(self.plot_canvas_x, 0, 0)
                    gridLayout.addWidget(self.plot_canvas_z, 0, 1)
                    gridLayout.addWidget(self.plot_canvas_t, 1, 0)

                    widget = QtWidgets.QWidget()
                    widget.setLayout(gridLayout)

                    self.image_box.layout().addWidget(widget)

                if self.y_range == 0:
                    y = numpy.linspace(-10.0, 10.0, 1001)
                else:
                    y = numpy.linspace(self.y_range_min, self.y_range_max,
                                       self.y_npoints)

                pos = [0.25, 0.15, 0.7, 0.75]

                self.plot_canvas_x.addCurve(
                    y,
                    2.35 * ST.focnew_scan(ticket["AX"], y) *
                    ShadowPlot.get_factor(1, self.workspace_units_to_cm),
                    "x (tangential)",
                    symbol='',
                    color="blue",
                    replace=True)  #'+', '^', ','
                self.plot_canvas_x._backend.ax.get_yaxis().get_major_formatter(
                ).set_useOffset(True)
                self.plot_canvas_x._backend.ax.get_yaxis().get_major_formatter(
                ).set_scientific(True)
                self.plot_canvas_x._backend.ax.set_position(pos)
                self.plot_canvas_x._backend.ax2.set_position(pos)
                self.plot_canvas_x.setGraphXLabel("Y [" +
                                                  self.workspace_units_label +
                                                  "]")
                self.plot_canvas_x.setGraphYLabel("2.35*<X> [$\mu$m]")
                self.plot_canvas_x._backend.ax.set_title(
                    "X", horizontalalignment='left')
                self.plot_canvas_x.replot()

                self.plot_canvas_z.addCurve(
                    y,
                    2.35 * ST.focnew_scan(ticket["AZ"], y) *
                    ShadowPlot.get_factor(3, self.workspace_units_to_cm),
                    "z (sagittal)",
                    symbol='',
                    color="red",
                    replace=False)  #'+', '^', ','
                self.plot_canvas_z._backend.ax.get_yaxis().get_major_formatter(
                ).set_useOffset(True)
                self.plot_canvas_z._backend.ax.get_yaxis().get_major_formatter(
                ).set_scientific(True)
                self.plot_canvas_z._backend.ax.set_position(pos)
                self.plot_canvas_z._backend.ax2.set_position(pos)
                self.plot_canvas_z.setGraphXLabel("Y [" +
                                                  self.workspace_units_label +
                                                  "]")
                self.plot_canvas_z.setGraphYLabel("2.35*<Z> [$\mu$m]")
                self.plot_canvas_z._backend.ax.set_title(
                    "Z", horizontalalignment='left')
                self.plot_canvas_z.replot()

                self.plot_canvas_t.addCurve(
                    y,
                    2.35 * ST.focnew_scan(ticket["AT"], y) *
                    ShadowPlot.get_factor(1, self.workspace_units_to_cm),
                    "combined x,z",
                    symbol='',
                    color="green",
                    replace=True)  #'+', '^', ','
                self.plot_canvas_t._backend.ax.get_yaxis().get_major_formatter(
                ).set_useOffset(True)
                self.plot_canvas_t._backend.ax.get_yaxis().get_major_formatter(
                ).set_scientific(True)
                self.plot_canvas_t._backend.ax.set_position(pos)
                self.plot_canvas_t._backend.ax2.set_position(pos)
                self.plot_canvas_t.setGraphXLabel("Y [" +
                                                  self.workspace_units_label +
                                                  "]")
                self.plot_canvas_t.setGraphYLabel("2.35*<X,Z> [$\mu$m]")
                self.plot_canvas_t._backend.ax.set_title(
                    "X,Z (Combined)", horizontalalignment='left')
                self.plot_canvas_t.replot()
Ejemplo n.º 25
0
 def write_error_profile_file(self):
     ST.write_shadow_surface(self.zz, self.xx, self.yy,
                             self.heigth_profile_file_name)
Ejemplo n.º 26
0
def main():
    # inputs (working in m)
    useshadow = 1
    slitdistance = 30.9  # m
    detdistance = 1.38  # m
    detsize = 200e-6  # m
    energy = 14.0  # keV
    realisations = 1000
    lensF = None  # detdistance/2 # focal distance
    shadowunits2m = 1e-2

    wavelength = 12.398 / (energy) * 1e-10  # m
    # wavelength   =   500.0e-6 # mm
    # open output file
    f = open("twoslitsLeitenberger.spec", "w")
    header = "#F twoslitsLeitenberger.spec \n"
    f.write(header)

    # read shadow files
    #
    flag = st.getshcol("star.01", 10)
    igood = numpy.where(flag >= 0)
    igood = numpy.array(igood)
    igood.shape = -1
    print(flag.size)
    print("igood: ", igood.size)
    print("--------------")

    # use shadow's number of points
    # sourcepoints = 200
    sourcepoints = igood.size
    slitpoints = sourcepoints / 2
    detpoints = sourcepoints

    if useshadow == 1:
        # shadow
        position1x = st.getshcol("begin.dat", 3) * shadowunits2m
        position1x = position1x[igood]
        position1x.shape = -1
    else:
        # grid
        sourcesize = 140e-6
        position1x = numpy.linspace(-sourcesize / 2, sourcesize / 2, sourcepoints)

    # position1x = st.getshcol("begin.dat",3) # * shadowunits2m
    # position1x = position1x[igood]
    # position1x.shape = -1
    # sourcesize = 140e-6
    # position1x = numpy.linspace(-sourcesize/2,sourcesize/2,sourcepoints)
    print(">>> maxmin: ", position1x.min(), position1x.max())

    if useshadow == 1:
        # shadow
        position2x = st.getshcol("screen.0101", 3) * shadowunits2m
        position2x = position2x[igood]
        position2x.shape = -1
    else:
        # grid
        slitsize = 2e-6
        slitgap = 11.3e-6
        tmp = numpy.linspace(-slitsize / 2, slitsize / 2, slitpoints)
        position2x = numpy.concatenate((tmp - slitgap / 2, tmp + slitgap / 2))

    # position3x = st.getshcol("star.02",3)
    # position3x = position3x[igood]
    # position3x.shape = -1
    # direction3x = st.getshcol("star.02",6)
    # direction3x = direction3x[igood]
    # direction3x.shape = -1
    # vz0101 = st.getshcol("screen.0101",6)
    # vz0201 = st.getshcol("screen.0201",6)

    # working with angles...
    # tmp3 = -numpy.cos(numpy.arcsin(vz0201 -vz0101))
    # tmp3 = (tmp3-tmp3.min()) * 1590.0
    # tmp3 = tmp3[igood]
    # tmp3.shape = -1

    # working with differences
    # tmp3 = (vz0201 -vz0101)
    # tmp3 = tmp3[igood]
    # tmp3.shape = -1

    position3x = numpy.linspace(-detsize / 2, detsize / 2, igood.size)

    print("igood: ", igood.size, position1x.size, position2x.size, position3x.size)
    print("shape: ", igood.shape)
    # for j in range(detpoints):
    #    print j,igood[j],position1x[j],position2x[j],position3x[j]

    # direction3x = None
    if useshadow == 0:
        fields12 = goFromToShadow(position1x, position2x, slitdistance, lensF=None, wavelength=wavelength)
        fields23 = goFromToShadow(position2x, position3x, detdistance, lensF=None, wavelength=wavelength)
    else:
        fields12 = goFromTo(position1x, position2x, slitdistance, lensF=None, wavelength=wavelength)
        fields23 = goFromTo(position2x, position3x, detdistance, lensF=None, wavelength=wavelength)

    # from 1 to 3, matrix multiplication
    fields13 = numpy.dot(fields12, fields23)
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # fields13 = fields23

    print("shape 12: ", fields12.shape)
    print("shape 23: ", fields23.shape)
    print("shape 13: ", fields23.shape)
    # sourcepoints = igood.size
    fieldComplexAmplitude = numpy.dot(numpy.ones(sourcepoints), fields13)
    fieldIntensity = numpy.power(numpy.abs(fieldComplexAmplitude), 2)
    fieldPhase = numpy.arctan2(numpy.real(fieldComplexAmplitude), numpy.imag(fieldComplexAmplitude))

    print("fields: ", fields12.shape, fields23.shape)

    # do the ensemble average
    tmpSource = numpy.exp(1.0j * 2 * numpy.pi * numpy.random.mtrand.rand(sourcepoints))
    fieldSource = tmpSource
    fieldIntensityEA = numpy.power(numpy.abs(fieldComplexAmplitude), 2)
    for i in range(realisations - 1):
        # tmpSource = numpy.exp(1.j*2* numpy.pi*numpy.random.mtrand.rand(sourcepoints))
        # fieldComplexAmplitude = numpy.dot( tmpSource, fields13)
        # fieldIntensityEA = fieldIntensityEA + numpy.power(numpy.abs(fieldComplexAmplitude),2)

        tmpSource = numpy.exp(1.0j * 2 * numpy.pi * numpy.random.mtrand.rand(sourcepoints))
        fieldComplexAmplitude = numpy.dot(tmpSource, fields13)
        fieldIntensityEA = fieldIntensityEA + numpy.power(numpy.abs(fieldComplexAmplitude), 2)

    header = "\n#S  1 2h=??\n"
    f.write(header)
    header = "#N 4 \n#L Z[um]  intensityCoh  phaseCoh  intensityEnsemble\n"
    f.write(header)

    for i in range(igood.size):
        out = numpy.array((position3x[i] * 1e6, fieldIntensity[i], fieldPhase[i], fieldIntensityEA[i]))
        f.write(("%20.11e " * out.size + "\n") % tuple(out.tolist()))

    f.close()
    print("File written to disk: twoslitsLeitenberger.spec")
    return position3x, fieldIntensity, fieldIntensityEA
Ejemplo n.º 27
0
    def setBeam(self, beam):
        if ShadowCongruence.checkEmptyBeam(beam):
            if ShadowCongruence.checkGoodBeam(beam):
                sys.stdout = EmittingStream(textWritten=self.writeStdOut)

                self.input_beam = beam

                optical_element_list_start = []
                optical_element_list_end = []

                self.sysInfo.setText("")
                self.mirInfo.setText("")
                self.sourceInfo.setText("")
                self.distancesSummary.setText("")
                self.pythonScript.setText("")

                for history_element in self.input_beam.getOEHistory():
                    if not history_element._shadow_source_start is None:
                        optical_element_list_start.append(history_element._shadow_source_start.src)
                    elif not history_element._shadow_oe_start is None:
                        optical_element_list_start.append(history_element._shadow_oe_start._oe)

                    if not history_element._shadow_source_end is None:
                        optical_element_list_end.append(history_element._shadow_source_end.src)
                    elif not history_element._shadow_oe_end is None:
                        optical_element_list_end.append(history_element._shadow_oe_end._oe)


                    if not history_element._shadow_source_end is None:
                        try:
                            self.sourceInfo.append(history_element._shadow_source_end.src.sourcinfo())
                        except:
                            self.sourceInfo.append("Problem in calculating Source Info:\n" + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))
                    elif not history_element._shadow_oe_end is None:
                        try:
                            if isinstance(history_element._shadow_oe_end._oe, CompoundOE):
                                self.mirInfo.append(history_element._shadow_oe_end._oe.mirinfo())
                            else:
                                self.mirInfo.append(history_element._shadow_oe_end._oe.mirinfo(title="O.E. #" + str(history_element._oe_number)))
                        except:
                            self.sourceInfo.append("Problem in calculating Mir Info for O.E. #:" + str(history_element._oe_number) + "\n" + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))

                coe_end = ShadowCompoundOpticalElement.create_compound_oe(workspace_units_to_cm=self.workspace_units_to_cm)
                for oe in optical_element_list_end:
                    coe_end._oe.append(oe)

                try:
                    self.sysInfo.setText(coe_end._oe.sysinfo())
                except:
                    self.distancesSummary.setText("Problem in calculating SysInfo:\n" + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))

                try:
                    self.distancesSummary.setText(coe_end._oe.info())
                except:
                    self.distancesSummary.setText("Problem in calculating Distance Summary:\n" + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))

                try:
                    self.pythonScript.setText(ST.make_python_script_from_list(optical_element_list_start))
                except:
                    self.pythonScript.setText("Problem in writing python script:\n" + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))
            else:
                QtGui.QMessageBox.critical(self, "Error",
                                           "Data not displayable: No good rays or bad content",
                                           QtGui.QMessageBox.Ok)
Ejemplo n.º 28
0
if source_create == 1:
    # creates source from start.00 if "-s" 
    src.load('start.00')
    beamSource.genSource(src)
    if write:
        beamSource.write("begin.dat")
else:
    # reads source from binary file" start.00
    beamSource.load('begin.dat')  



#
# get fwhm of the source
#
g1 = st.plotxy(beamSource,1,3,calfwhm=1,nbins=200,noplot=noplot)
fw0 = numpy.array([g1.fwhmx,g1.fwhmy])

#
# start loop on scanList
#
for scanIndex,scanWhat in enumerate(scanList):
    # loop on scanning variable
    out   = numpy.zeros( (9,scan1.size) ) 
    
    for i in range(scan1.size):
        oe1.load("start.01")
        #run system with only 1 oe
        if write:
            oe1.FWRITE=0 # write(0) or not(3) binary files
        else:
    ticket2D = shadow3_beam.histo2(col_h=1,
                                   col_v=3,
                                   nbins=nbins,
                                   ref=23,
                                   nolost=1,
                                   xrange=[x_min, x_max],
                                   yrange=[z_min, z_max])

    histogram = ticket2D["histogram"]
    fwhms[index] = ticket2D["fwhm_v"]

    for ix in range(nbins):
        for iz in range(nbins):
            stack_result[index, ix, iz] = histogram[ix, iz]

    # FOCUS POSITION
    ticketFocus = ST.focnew(shadow3_beam, mode=0, center=[0.0, 0.0])

    best_focus_positions[index] = ticketFocus['z_waist']

    print("C3, FWHM, Focus", shadow3_VLS.RUL_A3, fwhms[index],
          best_focus_positions[index])

plot_data1D(c3_values, fwhms * 1e4, "SPOT VERTICAL SIZE", "C3 [l/cm]^3",
            "Z FWHM [um]")
plot_data1D(c3_values, best_focus_positions,
            "VERTICAL FOCUS RELATIVE POSITION", "C3 [l/cm]^3", "Distance [cm]")
plot_data3D(stack_result, c3_values, numpy.linspace(x_min, x_max, nbins),
            numpy.linspace(z_min, z_max, nbins), "SPOT SIZE AT IMAGE PLANE",
            "X [um]", "Z [um]")