Exemple #1
0
    def get_fwhm_intensity_accumulated(self):

        nx = self.coordinate_x.size
        ny = self.coordinate_y.size

        fwhm_x, quote, coordinates = get_fwhm(
            self.intensity_accumulated[:, ny // 2], self.coordinate_x)
        fwhm_y, quote, coordinates = get_fwhm(
            self.intensity_accumulated[nx // 2, :], self.coordinate_y)

        return fwhm_x, fwhm_y
Exemple #2
0
    def process_wavefront_2d(cls, wf):
        I = wf.get_intensity()
        x = wf.get_coordinate_x()
        y = wf.get_coordinate_y()

        nx = x.size
        ny = y.size

        fwhm_x, quote, coordinates = get_fwhm(I[:, ny // 2], x)
        fwhm_y, quote, coordinates = get_fwhm(I[nx // 2, :], y)

        intensity_at_center = I[nx // 2, ny // 2]
        intensity_total = I.sum() * (x[1] - x[0]) * (y[1] - y[0])
        intensity_peak = I.max()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return e, h, v, p, traj
rangey = [0.1, 0.1, None, None]
# filename = "cryogenic1d.txt"

FWHM = []
STREHL = []

for i, filename in enumerate(filenames):

    a = numpy.loadtxt(dirdata + filename + ".txt")

    fig = plot(a[:, 0],
               a[:, 1],
               xtitle="X [$\mu$m]",
               ytitle="intensity [a.u.]",
               figsize=figsize,
               show=0)
    fig[0].subplots_adjust(bottom=0.15)

    tmp = get_fwhm(
        a[:, 1],
        a[:, 0],
    )
    FWHM.append(tmp[0])
    STREHL.append(a[:, 1].max())
    plt.savefig(dirpng + filename + ".pdf")
    print("File %s.pdf written to file" % filename)
    plt.show()

for i, filename in enumerate(filenames):
    print("%15s    FWHM: %f    STREHL: %f" %
          (filename, FWHM[i], STREHL[i] / STREHL[0]))
Exemple #5
0
    def plot_2D(self,
                histogram,
                xx=None,
                yy=None,
                title="",
                xtitle="",
                ytitle="",
                xum="[mm]",
                yum="[mm]",
                plotting_range=None,
                factor1=1.0,
                factor2=1.0,
                colormap=None):

        if xx is None:
            xx = numpy.arange(histogram.shape[0])

        if yy is None:
            yy = numpy.arange(histogram.shape[1])

        if plotting_range == None:
            nbins_h = xx.size
            nbins_v = yy.size
        else:
            range_x = numpy.where(
                numpy.logical_and(xx >= plotting_range[0],
                                  xx <= plotting_range[1]))
            range_y = numpy.where(
                numpy.logical_and(yy >= plotting_range[2],
                                  yy <= plotting_range[3]))

            xx = xx[range_x]
            yy = yy[range_y]

            nbins_h = xx.size
            nbins_v = yy.size

        if len(xx) == 0 or len(yy) == 0:
            raise Exception("Nothing to plot in the given range")

        xmin, xmax = xx.min(), xx.max()
        ymin, ymax = yy.min(), yy.max()

        origin = (xmin * factor1, ymin * factor2)
        scale = (abs(
            (xmax - xmin) / nbins_h) * factor1, abs(
                (ymax - ymin) / nbins_v) * factor2)

        # silx inverts axis!!!! histogram must be calculated reversed
        data_to_plot = []
        for y_index in range(0, nbins_v):
            x_values = []
            for x_index in range(0, nbins_h):
                x_values.append(histogram[x_index][y_index])

            data_to_plot.append(x_values)

        data_to_plot = numpy.array(data_to_plot)

        histogram_h = numpy.sum(data_to_plot,
                                axis=0)  # data to plot axis are inverted
        histogram_v = numpy.sum(data_to_plot, axis=1)

        ticket = {}
        ticket['total'] = numpy.sum(data_to_plot)

        ticket['fwhm_h'], ticket['fwhm_quote_h'], ticket[
            'fwhm_coordinates_h'] = get_fwhm(histogram_h, xx)
        ticket['sigma_h'] = get_sigma(histogram_h, xx)

        ticket['fwhm_v'], ticket['fwhm_quote_v'], ticket[
            'fwhm_coordinates_v'] = get_fwhm(histogram_v, yy)
        ticket['sigma_v'] = get_sigma(histogram_v, yy)

        self.plot_canvas.setColormap(colormap=colormap)
        self.plot_canvas.setImage(data_to_plot, origin=origin, scale=scale)

        self.plot_canvas.setGraphXLabel(xtitle)
        self.plot_canvas.setGraphYLabel(ytitle)
        self.plot_canvas.setGraphTitle(title)

        self.plot_canvas._histoHPlot.setGraphYLabel('Counts')

        self.plot_canvas._histoHPlot._backend.ax.xaxis.get_label().set_color(
            'white')
        self.plot_canvas._histoHPlot._backend.ax.xaxis.get_label(
        ).set_fontsize(1)
        for label in self.plot_canvas._histoHPlot._backend.ax.xaxis.get_ticklabels(
        ):
            label.set_color('white')
            label.set_fontsize(1)

        self.plot_canvas._histoVPlot.setGraphXLabel('Counts')

        self.plot_canvas._histoVPlot._backend.ax.yaxis.get_label().set_color(
            'white')
        self.plot_canvas._histoVPlot._backend.ax.yaxis.get_label(
        ).set_fontsize(1)
        for label in self.plot_canvas._histoVPlot._backend.ax.yaxis.get_ticklabels(
        ):
            label.set_color('white')
            label.set_fontsize(1)

        n_patches = len(self.plot_canvas._histoHPlot._backend.ax.patches)
        if (n_patches > 0):
            self.plot_canvas._histoHPlot._backend.ax.patches.remove(
                self.plot_canvas._histoHPlot._backend.ax.patches[n_patches -
                                                                 1])

        if not ticket['fwhm_h'] == 0.0:
            x_fwhm_i, x_fwhm_f = ticket['fwhm_coordinates_h']
            x_fwhm_i, x_fwhm_f = x_fwhm_i * factor1, x_fwhm_f * factor1
            y_fwhm = ticket['fwhm_quote_h']

            self.plot_canvas._histoHPlot._backend.ax.add_patch(
                FancyArrowPatch([x_fwhm_i, y_fwhm], [x_fwhm_f, y_fwhm],
                                arrowstyle=ArrowStyle.CurveAB(head_width=2,
                                                              head_length=4),
                                color='b',
                                linewidth=1.5))

        n_patches = len(self.plot_canvas._histoVPlot._backend.ax.patches)
        if (n_patches > 0):
            self.plot_canvas._histoVPlot._backend.ax.patches.remove(
                self.plot_canvas._histoVPlot._backend.ax.patches[n_patches -
                                                                 1])

        if not ticket['fwhm_v'] == 0.0:
            y_fwhm_i, y_fwhm_f = ticket['fwhm_coordinates_v']
            y_fwhm_i, y_fwhm_f = y_fwhm_i * factor2, y_fwhm_f * factor2
            x_fwhm = ticket['fwhm_quote_v']

            self.plot_canvas._histoVPlot._backend.ax.add_patch(
                FancyArrowPatch([x_fwhm, y_fwhm_i], [x_fwhm, y_fwhm_f],
                                arrowstyle=ArrowStyle.CurveAB(head_width=2,
                                                              head_length=4),
                                color='r',
                                linewidth=1.5))

        self.plot_canvas._histoHPlot.replot()
        self.plot_canvas._histoVPlot.replot()
        self.plot_canvas.replot()

        self.info_box.total.setText("{:.3e}".format(
            decimal.Decimal(ticket['total'])))
        self.info_box.fwhm_h.setText("{:5.4f}".format(ticket['fwhm_h'] *
                                                      factor1))
        self.info_box.fwhm_v.setText("{:5.4f}".format(ticket['fwhm_v'] *
                                                      factor2))
        self.info_box.label_h.setText("FWHM " + xum)
        self.info_box.label_v.setText("FWHM " + yum)
        self.info_box.sigma_h.setText("{:5.4f}".format(ticket['sigma_h'] *
                                                       factor1))
        self.info_box.sigma_v.setText("{:5.4f}".format(ticket['sigma_v'] *
                                                       factor2))
        self.info_box.label_s_h.setText("\u03c3 " + xum)
        self.info_box.label_s_v.setText("\u03c3 " + yum)
Exemple #6
0
beamline_element = BeamlineElement(
    optical_element=optical_element,
    coordinates=ElementCoordinates(p=9.934270,
                                   q=0.000000,
                                   angle_radial=numpy.radians(0.000000),
                                   angle_azimuthal=numpy.radians(0.000000)))
propagation_elements.add_beamline_element(beamline_element)
propagation_parameters = PropagationParameters(
    wavefront=input_wavefront, propagation_elements=propagation_elements)
#self.set_additional_parameters(propagation_parameters)
#
propagation_parameters.set_additional_parameters('magnification_x', 0.05)
#
propagator = PropagationManager.Instance()
try:
    propagator.add_propagator(FresnelZoom1D())
except:
    pass
output_wavefront = propagator.do_propagation(
    propagation_parameters=propagation_parameters,
    handler_name='FRESNEL_ZOOM_1D')

#
#---- plots -----
#
if plot_from_oe <= 3:
    fwhm, quote, coordinates = get_fwhm(output_wavefront.get_intensity(),
                                        1e6 * output_wavefront.get_abscissas())
    plot(output_wavefront.get_abscissas(),
         output_wavefront.get_intensity(),
         title='OPTICAL ELEMENT NR 3; FWHM = %g um' % fwhm)
Exemple #7
0
def get_wavefront_intensity_fwhm(wf):
    from oasys.util.oasys_util import get_fwhm
    fwhm, quote, coordinates = get_fwhm(wf.get_intensity(),wf.get_abscissas())
    return fwhm
Exemple #8
0
 def get_fwhm_histograms(self):
     hx, hy = self.get_histograms()
     fwhm_x, quote, coordinates = get_fwhm(hx, self.coordinate_x)
     fwhm_y, quote, coordinates = get_fwhm(hy, self.coordinate_y)
     return fwhm_x, fwhm_y