def test_radial_1D_flat_distribution(self):

        print("\n#\n# running test_radial_1D_flat_distribution() \n#\n")

        R = 50.0e-6
        NRAYS = 10000

        x = numpy.linspace(0, R, 300)
        y = numpy.ones_like(x)

        s = Sampler1D(y * x, x)

        sampled_point, hy, hx = s.get_n_sampled_points_and_histogram(NRAYS,
                                                                     bins=101)

        angle = numpy.random.random(NRAYS) * 2 * numpy.pi

        if do_plots:
            plot(x, y, title="Constant Radial Distribution")
            plot(x, y * x, title="pdf")
            plot(hx, hy, title="histogram of sampled r")

        X = sampled_point * numpy.sin(angle)
        Y = sampled_point * numpy.cos(angle)

        if do_plots:
            plot_scatter(X, Y)

        RR = numpy.sqrt(X * X + Y * Y)
        assert (numpy.abs(RR.max()) - R < 0.05 * R)  # 5% difference
Exemplo n.º 2
0
def check_six_columns_mean_and_std(beam3,
                                   beam4,
                                   do_plot=True,
                                   do_assert=False,
                                   assert_value=1e-2,
                                   to_meters=1.0,
                                   good_only=True):

    raysnew = beam4.rays
    rays = beam3.rays

    if good_only:
        indices = numpy.where(rays[:, 9] > 0)[0]
        print(indices)
        rays = rays[indices, :].copy()
        raysnew = raysnew[indices, :].copy()

    if do_plot:
        # plot_scatter(rays[:,1],rays[:,0],title="Trajectory shadow3",show=False)
        # plot_scatter(raysnew[:,1],raysnew[:,0],title="Trajectory shadow4")

        plot_scatter(rays[:, 3],
                     rays[:, 5],
                     title="Divergences shadow3",
                     show=False)
        plot_scatter(raysnew[:, 3], raysnew[:, 5], title="Divergences shadow4")

        plot_scatter(rays[:, 0],
                     rays[:, 2],
                     title="Real Space shadow3",
                     show=False)
        plot_scatter(raysnew[:, 0], raysnew[:, 2], title="Real Space shadow4")

        #
        b3 = Shadow.Beam()
        b3.rays = rays

        b4 = Shadow.Beam()
        b4.rays = raysnew
        Shadow.ShadowTools.histo1(b3, 11, ref=23, nolost=1)
        Shadow.ShadowTools.histo1(b4, 11, ref=23, nolost=1)

    print("Comparing...")
    for i in range(6):

        m0 = (raysnew[:, i]).mean()
        m1 = (rays[:, i] * to_meters).mean()
        print("\ncol %d, mean sh3, sh4, |sh4-sh3|: %10g  %10g  %10g" %
              (i + 1, m1, m0, numpy.abs(m0 - m1)))
        std0 = raysnew[:, i].std()
        std1 = (rays[:, i] * to_meters).std()
        print("col %d, stdv sh3, sh4, |sh4-sh3|: %10g  %10g  %10g" %
              (i + 1, std1, std0, numpy.abs(std0 - std1)))

        if do_assert:
            assert (numpy.abs(m0 - m1) < assert_value)
            assert (numpy.abs(std0 - std1) < assert_value)
    def test3d(self):

        print("\n#\n# running test_3d() \n#\n")

        response = requests.get(
            "https://cdn104.picsart.com/201671193005202.jpg?r1024x1024")

        img = Image.open(BytesIO(response.content))
        img = numpy.array(img) * 1.0
        img = numpy.rot90(img, axes=(1, 0))
        image_data = img.max() - img

        if do_plots:
            plot_image(image_data[:, :, 0],
                       cmap='binary',
                       title="channel0",
                       show=1)
        # plot_image(image_data[:,:,1],cmap='binary',title="channel1",show=0)
        # plot_image(image_data[:,:,2],cmap='binary',title="channel2")

        print(image_data.shape)

        s2d = Sampler3D(image_data)

        cdf3, cdf2, cdf1 = s2d.cdf()

        # plot_image(cdf2)
        #
        # plot_image(s2d.pdf(),cmap='binary',title="pdf")
        #
        # cdf2,cdf1 = s2d.cdf()
        # plot_image(cdf2,cmap='binary',title="cdf")
        # plot(s2d.abscissas()[0],s2d.cdf()[0][:,-1])
        # plot(s2d.abscissas()[0],cdf1)
        #
        x0s, x1s, x2s = s2d.get_n_sampled_points(100000)
        if do_plots:
            plot_scatter(x0s, x1s)
        print(x2s)

        print("x0s.mean(),x0s.std(),x1s.mean(),x1s.std(): ", x0s.mean(),
              x0s.std(), x1s.mean(), x1s.std())
        assert ((numpy.abs(x0s.mean()) - 730.09) < 10.0)
        assert ((numpy.abs(x0s.std()) - 458.17) < 10.0)
        assert ((numpy.abs(x1s.mean()) - 498.805) < 10.0)
        assert ((numpy.abs(x1s.std()) - 301.21) < 10.0)
Exemplo n.º 4
0
def example_collimated_source():
    #
    a = SourceGaussian.initialize_collimated_source(
        number_of_rays=10000,
        sigmaX=1.0,
        sigmaY=0.0,
        sigmaZ=1.0,
        real_space_center=[0.0, 0.0, 0.0],
        direction_space_center=[0.0, 0.0])

    print(a.info())
    beam = a.get_beam()

    plotxy(beam, 1, 3, title="collimated source")

    plot_scatter(beam.get_column(1),
                 beam.get_column(3),
                 xtitle="col 1",
                 ytitle="col 3",
                 title="collimated source")
    print(beam.info())
Exemplo n.º 5
0
    def test_collimated_source(self):

        #
        #
        #
        a = SourceGridCartesian.initialize_collimated_source(
            real_space=[1., 0.0, 1.0], real_space_points=[100, 1, 100])
        print(a.info())
        beam_shadow3 = Beam3.initialize_from_shadow4_beam(a.get_beam())

        beam = a.get_beam()

        if DO_PLOT:

            from srxraylib.plot.gol import plot_scatter, set_qt
            set_qt()
            plot_scatter(beam.get_column(1), beam.get_column(3))
            import Shadow
            Shadow.ShadowTools.plotxy(beam_shadow3, 1, 3)

        print(beam.info())
    def test_2d(self):

        print("\n#\n# running test_2d() \n#\n")
        #
        response = requests.get(
            "https://cdn104.picsart.com/201671193005202.jpg?r1024x1024")

        img = Image.open(BytesIO(response.content))
        img = numpy.array(img).sum(2) * 1.0
        img = numpy.rot90(img, axes=(1, 0))
        image_data = img.max() - img
        if do_plots:
            plot_image(image_data, cmap='binary')

        x0 = numpy.arange(image_data.shape[0])
        x1 = numpy.arange(image_data.shape[1])

        print(image_data.shape)

        s2d = Sampler2D(image_data, x0, x1)

        # plot_image(s2d.pdf(),cmap='binary',title="pdf")

        cdf2, cdf1 = s2d.cdf()
        print("cdf2.shape,cdf1.shape,s2d._pdf_x0.shape,s2d._pdf_x1.shape: ",
              cdf2.shape, cdf1.shape, s2d._pdf_x0.shape, s2d._pdf_x1.shape)
        # plot_image(cdf2,cmap='binary',title="cdf")
        # plot(s2d.abscissas()[0],s2d.cdf()[0][:,-1])
        # plot(s2d.abscissas()[0],cdf1)

        x0s, x1s = s2d.get_n_sampled_points(100000)
        if do_plots:
            plot_scatter(x0s, x1s)

        print("x0s.mean(),x0s.std(),x1s.mean(),x1s.std(): ", x0s.mean(),
              x0s.std(), x1s.mean(), x1s.std())
        assert ((numpy.abs(x0s.mean()) - 731.37) < 10.0)
        assert ((numpy.abs(x0s.std()) - 458.55) < 10.0)
        assert ((numpy.abs(x1s.mean()) - 498.05) < 10.0)
        assert ((numpy.abs(x1s.std()) - 301.05) < 10.0)
Exemplo n.º 7
0
def example_double_gaussian():
    #
    #
    a = SourceGaussian.initialize_from_keywords(
        number_of_rays=10000,
        sigmaX=2.0e-6,
        sigmaY=1.0e-3,
        sigmaZ=1.0e-6,
        sigmaXprime=3e-6,
        sigmaZprime=3e-6,
        real_space_center=[0.0, 0.0, 0.0],
        direction_space_center=[0.0, 0.0])

    print(a.info())

    beam = a.get_beam()
    plot_scatter(beam.get_column(2),
                 beam.get_column(1),
                 title="double Gaussian",
                 xtitle="col 2",
                 ytitle="col 1")
    plot_scatter(beam.get_column(1),
                 beam.get_column(3),
                 title="double Gaussian",
                 xtitle="col 1",
                 ytitle="col 3")
    plot_scatter(beam.get_column(4),
                 beam.get_column(6),
                 title="double Gaussian",
                 xtitle="col 4",
                 ytitle="col 6")
    print(beam.info())

    print(isinstance(a, SourceGaussian))
    def test_radial_1D_gaussian_distribution(self):

        print("\n#\n# running test_radial_1D_gaussian_distribution() \n#\n")

        R = 50.0e-6
        sigma = 5e-6
        NRAYS = 10000

        x = numpy.linspace(0, R, 300)
        y = numpy.exp(-x * x / 2 / sigma / sigma)  # numpy.ones_like(x) * R

        s = Sampler1D(y * x, x)

        sampled_point, hy, hx = s.get_n_sampled_points_and_histogram(NRAYS,
                                                                     bins=101)

        angle = numpy.random.random(NRAYS) * 2 * numpy.pi

        if do_plots:
            plot(x, y, title="Gaussian Radial Distribution sigma:%f" % sigma)
            plot(x, y * x, title="pdf")
            plot(hx, hy, title="histogram of sampled r")

        X = sampled_point / numpy.sqrt(2) * numpy.sin(angle)
        Y = sampled_point / numpy.sqrt(2) * numpy.cos(angle)

        if do_plots:
            plot_scatter(X, Y)

        print("sigma, stdev R,  stdev X, srdev Y: ", sigma,
              Std_zero_mean(numpy.sqrt(X * X + Y * Y)), Std_zero_mean(X),
              Std_zero_mean(Y))
        print("stdev sampled R: ", Std_zero_mean(sampled_point))
        print(
            "error (percent) : ", 100 / sigma *
            numpy.abs(sigma - (Std_zero_mean(numpy.sqrt(X * X + Y * Y)))))

        assert (numpy.abs(sigma - (Std_zero_mean(numpy.sqrt(X * X + Y * Y)))) <
                0.05 * sigma)  # 5% difference
Exemplo n.º 9
0
def compare_rays_with_shadow3_beam(raysnew,beam,user_unit_to_m=1.0,do_plot=True,do_assert=False):

    import Shadow
    from srxraylib.plot.gol import plot_scatter

    rays = beam.rays

    if do_plot:
        plot_scatter(rays[:,1],rays[:,0],title="Trajectory shadow3",show=False)
        plot_scatter(raysnew[:,1],raysnew[:,0],title="Trajectory new")


        plot_scatter(rays[:,3],rays[:,5],title="Divergences shadow3",show=False)
        plot_scatter(raysnew[:,3],raysnew[:,5],title="Divergences new")

        plot_scatter(rays[:,0],rays[:,2],title="Real Space shadow3",show=False)
        plot_scatter(raysnew[:,0],raysnew[:,2],title="Real Space new")

        b = Shadow.Beam()
        b.rays = raysnew
        Shadow.ShadowTools.histo1(beam,11,ref=23,nolost=1)
        Shadow.ShadowTools.histo1(b,11,ref=23,nolost=1)


    print("Comparing...")
    for i in range(6):
        if i <= 2:
            fact = 1.0 / user_unit_to_m
        else:
            fact = 1.0
        m0 = (raysnew[:,i]*fact).mean()
        m1 = beam.rays[:,i].mean()
        print("\ncol %i, mean (new,old,diff/old): "%(i+1),m0,m1,numpy.abs(m0-m1)/numpy.abs(m1))
        std0 = (raysnew[:,i]*fact).std()
        std1 = beam.rays[:,i].std()
        print("col %i, std (new,old,diff/old): "%(i+1),std0,std1,numpy.abs(std0-std1)/numpy.abs(std1))

        if do_assert:
            if True: # i != 5:  # TODO check why it fails!!!
                assert((numpy.abs(numpy.abs(m0)   -numpy.abs(m1) )    /numpy.abs(m1)) < 15.0)
            assert((numpy.abs(numpy.abs(std0) -numpy.abs(std1))  /numpy.abs(std1)) < 0.075)
Exemplo n.º 10
0
                   aspect='auto',
                   title="polarization",
                   xtitle="theta [urad]",
                   ytitle="phi [rad]")

    print("Beam intensity: ", beam.get_column(23).sum())
    print("Beam intensity s-pol: ", beam.get_column(24).sum())
    print("Beam intensity: p-pol", beam.get_column(25).sum())

    #
    # plot
    #
    if do_plots:
        plot_scatter(1e6 * beam.rays[:, 0],
                     1e6 * beam.rays[:, 2],
                     title="real space",
                     xtitle="X [um]",
                     ytitle="Z [um]",
                     show=False)
        plot_scatter(1e6 * beam.rays[:, 3],
                     1e6 * beam.rays[:, 5],
                     title="divergence space",
                     xtitle="X [urad]",
                     ytitle="Z [urad]",
                     show=True)

        plot(ls.get_photon_size_distribution()[0] * 1e6,
             ls.get_photon_size_distribution()[1],
             title="Photon size distribution",
             xtitle="R [um]",
             ytitle="Intensity [a.u.]")
Exemplo n.º 11
0
def compare_rays_with_shadow3_beam(raysnew,beam,do_plot=True,do_assert=False):

    import Shadow

    rays = beam.rays

    if do_plot:
        plot_scatter(rays[:,1],rays[:,0],title="Trajectory shadow3",show=False)
        plot_scatter(raysnew[:,1],raysnew[:,0],title="Trajectory new")


        plot_scatter(rays[:,3],rays[:,5],title="Divergences shadow3",show=False)
        plot_scatter(raysnew[:,3],raysnew[:,5],title="Divergences new")

        plot_scatter(rays[:,0],rays[:,2],title="Real Space shadow3",show=False)
        plot_scatter(raysnew[:,0],raysnew[:,2],title="Real Space new")

        b = Shadow.Beam()
        b.rays = raysnew
        Shadow.ShadowTools.histo1(beam_shadow3,11,ref=23,nolost=1)
        Shadow.ShadowTools.histo1(b,11,ref=23,nolost=1)

    if do_assert:
        print("Comparing...")
        for i in range(6):
            if i <= 2:
                fact = 100
            else:
                fact = 1.0
            m0 = (raysnew[:,i]*fact).mean()
            m1 = beam.rays[:,i].mean()
            print("\ncol %d, mean: "%(i+1),m0,m1,numpy.abs(m0-m1)/numpy.abs(m1))
            std0 = (raysnew[:,i]*fact).std()
            std1 = beam.rays[:,i].std()
            print("col %d, std: "%(i+1),std0,std1,numpy.abs(std0-std1)/numpy.abs(std1))

            assert((numpy.abs(m0-m1)/numpy.abs(m1)) < 15.0)
            assert((numpy.abs(std0-std1)/numpy.abs(std1)) < 0.05)
Exemplo n.º 12
0
                                        skiprows=5,
                                        do_plot=0)
        dict2 = ray_tracing(dict1)
        dict3 = compute_power_density_footprint(dict2)
    elif test == 2:
        dict1 = load_srcalc_output_file(filename=path + "D_IDPower.TXT",
                                        skiprows=5,
                                        do_plot=0)
        dict2 = ray_tracing(dict1)
        OE_FOOTPRINT = dict2["OE_FOOTPRINT"]
        OE_IMAGE = dict2["OE_IMAGE"]
        print(OE_FOOTPRINT[0].shape)
        from srxraylib.plot.gol import plot_scatter
        plot_scatter(OE_FOOTPRINT[0][0, :],
                     OE_FOOTPRINT[0][1, :],
                     plot_histograms=False,
                     title="Footprint",
                     show=False)
        plot_scatter(OE_IMAGE[0][0, :],
                     OE_IMAGE[0][1, :],
                     plot_histograms=False,
                     title="Image")

    elif test == 3:
        a = numpy.loadtxt(path + "D_IDPower.TXT", skiprows=5)
        nX = 31  # intervals - URGENT input
        nY = 21  # intervals - URGENT input
        npointsX = nX + 1
        npointsY = nY + 1

        print("Dimensions ", a.shape, npointsX * npointsY)
Exemplo n.º 13
0
    Vx = a.get_volume_real_space()
    print("Vx: ", Vx.shape)

    V = a.get_volume()
    print("V: ", V.shape)

    beam = a.get_beam()
    beam_shadow3 = Beam3.initialize_from_shadow4_beam(beam)

    beam_shadow3.write("begin.dat")

    import Shadow
    Shadow.ShadowTools.plotxy(beam_shadow3, 4, 6)

    #
    #
    a = SourceGridCartesian.initialize_collimated_source(
        real_space=[10., 0.0, 10.0], real_space_points=[100, 1, 100])
    print(a.info())

    beam = a.get_beam()
    plot_scatter(beam.get_column(1), beam.get_column(3))

    beam_shadow3 = Beam3.initialize_from_shadow4_beam(beam)

    import Shadow
    Shadow.ShadowTools.plotxy(beam_shadow3, 1, 3)
    #

    beam_shadow3.write("begin.dat")
Exemplo n.º 14
0
    do_shadow = 0

    if do_shadow:

        import Shadow
        npoints = 10000
        xs, ys = sample_rays(wf.get_coordinate_x(),
                             wf.get_coordinate_y(),
                             wf.get_intensity(),
                             number_of_points=npoints)
        xps, yps = sample_rays(wf_prop_srw.get_coordinate_x(),
                               wf_prop_srw.get_coordinate_y(),
                               wf_prop_srw.get_intensity(),
                               number_of_points=npoints)
        #
        plot_scatter(xps, yps, show=1, title="Divergences")

        shadow_beam = Shadow.Beam(10000)
        rays = shadow_beam.rays
        rays[:, 10] = 2 * np.pi / (1e2 * wavelength)
        rays[:, 0] = xs
        rays[:, 1] = 0.0
        rays[:, 2] = ys
        rays[:, 3] = xps
        rays[:, 4] = np.sqrt(1 - (xps / propagation_distance)**2 -
                             (yps / propagation_distance)**2)
        rays[:, 5] = yps
        rays[:, 9] = 1.0
        rays[:, 11] = np.arange(1, npoints + 1)

        rays[:, 6] = 1.0  # electric vector s
Exemplo n.º 15
0
                              file_with_magnetic_field=filename,
                              flag_emittance=use_emittances,
                              emin=e_min,
                              emax=e_max,
                              ng_e=ng_e,
                              ng_j=nTrajPoints)
    sourcewiggler.set_electron_initial_conditions_by_label(
        position_label="value_at_zero", velocity_label="value_at_zero")

    ls = S4WigglerLightSource(name="",
                              electron_beam=syned_electron_beam,
                              wiggler_magnetic_structure=sourcewiggler)

    print(ls.info())

    beam = ls.get_beam(NRAYS=NRAYS)
    rays = beam.rays

    plot_scatter(rays[:, 0] * 1e6,
                 rays[:, 2] * 1e6,
                 xtitle="X um",
                 ytitle="Z um")
    plot_scatter(rays[:, 1], rays[:, 0] * 1e6, xtitle="Y m", ytitle="X um")
    plot_scatter(rays[:, 1], rays[:, 2] * 1e6, xtitle="Y m", ytitle="Z um")
    plot_scatter(rays[:, 3] * 1e6,
                 rays[:, 5] * 1e6,
                 xtitle="X' urad",
                 ytitle="Z' urad")

    # Beam.initialize_from_array(rays).write_h5("begin.h5")
Exemplo n.º 16
0
    # plot_scatter(x,y,xrange=[-6,6],yrange=[-6,6])

    #
    # Rectangle2D
    #

    dx, dy = Rectangle2D.sample(
        5000,
        -2.5e-6,
        2.5e-6,
        -0.5e-6,
        0.5e-6,
    )
    print(dx)
    if do_plot:
        plot_scatter(1e6 * dx, 1e6 * dy, title="Rectangle")

    #
    # Uniform2D
    #

    dx, dy = Uniform2D.sample(
        5000,
        -2.5e-6,
        2.5e-6,
        -0.5e-6,
        0.5e-6,
    )
    print(dx)
    if do_plot:
        plot_scatter(1e6 * dx, 1e6 * dy, title="Uniform")
Exemplo n.º 17
0
if __name__ == "__main__":

    from srxraylib.plot.gol import plot,plot_scatter, set_qt
    set_qt()

    do_plot=True

    # rectangle
    gs = SourceGeometrical()
    gs.set_spatial_type_rectangle(4,2)
    rays = gs.calculate_rays(1000)

    for i in range(6):
        print("Limits for column %d : %g,%g"%(1+i,rays[:,i].min(),rays[:,i].max()))
    if do_plot:
        plot_scatter(rays[:,0],rays[:,2],xrange=[-3,3],yrange=[-3,3],title="Rectangle")


    # Gaussian
    gs = SourceGeometrical()
    gs.set_spatial_type_gaussian(2e-6,1e-6)
    rays = gs.calculate_rays(10000)

    for i in range(6):
        print("Std for column %d : %g"%(i+1,rays[:,i].std()))
    if do_plot:
        plot_scatter(1e6*rays[:,0],1e6*rays[:,2],xrange=[-6,6],yrange=[-3,3],title="Gaussian")

    # Ellipse
    gs = SourceGeometrical()
    gs.set_spatial_type_ellipse(2,1)
Exemplo n.º 18
0
                                   moment_xxp=0.0,
                                   moment_xpxp=(10e-6)**2,
                                   moment_yy=(10e-6)**2,
                                   moment_yyp=0.0,
                                   moment_ypyp=(4e-6)**2)

    w = S4Wiggler(K_vertical=kValue,
                  period_length=per,
                  number_of_periods=nPer,
                  flag_emittance=use_emittances,
                  emin=e_min,
                  emax=e_max,
                  ng_e=10,
                  ng_j=nTrajPoints)

    # print(w.info())

    ls = S4WigglerLightSource(name="Undefined",
                              electron_beam=electron_beam,
                              magnetic_structure=w)

    print(ls.info())

    beam = ls.get_beam(NRAYS=NRAYS)

    rays = beam.rays

    plot_scatter(rays[:, 1], rays[:, 0], title="trajectory", show=False)
    plot_scatter(rays[:, 0], rays[:, 2], title="real space", show=False)
    plot_scatter(rays[:, 3], rays[:, 5], title="divergence space")
Exemplo n.º 19
0
# calculate bragg angle for each ray energy
#

d_spacing_cm = 3.266272e-8
theta = numpy.arcsin(wavelength_cm / 2 / d_spacing_cm)

theta_deg = theta * 180 / numpy.pi

print("ratio", wavelength_cm / 2 / d_spacing_cm)
print("theta_deg: ", theta_deg)
print("wavelength_cm: ", wavelength_cm)
print("incident_angles_deg", incident_angles_deg)
print("theta_deg", theta_deg)

plot_scatter(incident_angles_deg,
             theta_deg,
             xtitle="incident angle [deg]",
             ytitle="Bragg angle [deg]")

print(energies.shape, incident_angles_deg.shape)
# plot(energies,incident_angles_deg)

angle_diff_in_urad = (incident_angles_deg - theta_deg) * numpy.pi / 180 * 1e6
plot_scatter(indices, angle_diff_in_urad, xtitle="index", ytitle="angle diff")

# f = interpolate.interp2d(en, ang, ref.T, kind='cubic')
# f(energies,angle_diff_in_urad)

interpolated_weight = numpy.exp(-angle_diff_in_urad**2 / 2 / (400 / 2.35)**2)
plot_scatter(angle_diff_in_urad, interpolated_weight)

beam.rays[:, 6] = numpy.sqrt(interpolated_weight) * beam.rays[:, 6]
Exemplo n.º 20
0
def calculate_efficiency(mirr=None,angle_file="angle.02",material="Au",gamma_blaze_deg=None,lines_per_mm=300.0):

    import Shadow

    beam = Shadow.Beam()
    beam.load(mirr)

    angle = numpy.loadtxt(angle_file)

    alpha_deg = angle[:, 1]
    beta_deg = -angle[:, 2]
    wavelength = beam.getshonecol(19) * 1e-10
    energy = beam.getshonecol(11)

    # plot(numpy.arange(alpha_deg.size),alpha_deg,
    #      numpy.arange(alpha_deg.size), -beta_deg,
    #      legend=["alpha","beta"])
    # print(">>>",angle.shape)

    # plot(energy,wavelength)

    theta_deg = (alpha_deg - beta_deg) / 2
    gamma_deg = (alpha_deg + beta_deg) / 2

    # plot(energy,alpha*180/numpy.pi,
    #      energy, -beta * 180 / numpy.pi,
    #      energy, (alpha-beta) / 2 * 180 / numpy.pi,
    #      xtitle="energy / eV", ytitle="deg", legend=["alpha","-beta","theta"])

    RS = numpy.zeros_like(energy)

    if gamma_blaze_deg is None:
        gamma_blaze_deg = gamma_deg.mean()
        print(">>>> using blaze angle: %f deg " % (gamma_blaze_deg))

    #
    # reflectivity
    #
    theta = theta_deg * numpy.pi / 180

    method = 1

    if method == 0:
        for i in range(energy.size):
            rs, rp, runp = reflectivity("Au", numpy.array([energy[i]]), numpy.pi / 2 - theta[i], )
            RS[i] = rs[0]
    else:
        n2_interp = numpy.zeros(energy.size, complex)
        for i in range(energy.size):
            n2_interp[i] = xraylib.Refractive_Index(material, 1e-3 * energy[i],
                                                    xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(material)))
        n1 = 1 + 0j  # % air
        k0 = 2 * numpy.pi / wavelength
        # % calculate the k values
        k1 = (n2_interp ** 2 - 1 + (sind(90.0 - theta_deg)) ** 2) ** 0.5
        # % calculate fresnel coefficients for the 0-1 and 1-2 interfaces
        r1 = (sind(90.0 - theta_deg) - k1) / (sind(90.0 - theta_deg) + k1)
        RS = (numpy.abs(r1)) ** 2

    plot_scatter(energy, RS, xtitle="energy / eV", ytitle="R(theta)")

    #
    # efficiency
    #

    C = numpy.cos(numpy.deg2rad(beta_deg)) / numpy.cos(numpy.deg2rad(alpha_deg))

    plot_scatter(energy, C)
    efficiency = RS / C

    dspacing = 1e-3 / lines_per_mm
    sf = structure_factor(wavelength,
                          numpy.deg2rad(gamma_blaze_deg),
                          numpy.deg2rad(alpha_deg),
                          numpy.deg2rad(beta_deg),
                          dspacing)

    efficiency *= sf ** 2

    plot_scatter(energy, sf ** 2, xtitle="energy / eV", ytitle="S**2", title="S**2")
    plot_scatter(energy, efficiency, title="", xtitle="Phonon energy [eV]", ytitle="Efficiency")

    print("results: ")
    print("Reflectivity R min: %f, max: %f, average: %f" % (RS.min(), RS.max(), RS.mean()))
    print("C min: %f, max: %f, average: %f" % (C.min(), C.max(), C.mean()))
    print("sf**2 min: %f, max: %f, average: %f" % ((sf ** 2).min(), (sf ** 2).max(), (sf ** 2).mean()))
    print("Efficiency min: %f, max: %f, average: %f" % (efficiency.min(), efficiency.max(), efficiency.mean()))

    return efficiency
Exemplo n.º 21
0
    plot_scatter(energy, C)
    efficiency = RS / C

    dspacing = 1e-3 / lines_per_mm
    sf = structure_factor(wavelength,
                          numpy.deg2rad(gamma_blaze_deg),
                          numpy.deg2rad(alpha_deg),
                          numpy.deg2rad(beta_deg),
                          dspacing)

    efficiency *= sf ** 2

    plot_scatter(energy, sf ** 2, xtitle="energy / eV", ytitle="S**2", title="S**2")
    plot_scatter(energy, efficiency, title="", xtitle="Phonon energy [eV]", ytitle="Efficiency")

    print("results: ")
    print("Reflectivity R min: %f, max: %f, average: %f" % (RS.min(), RS.max(), RS.mean()))
    print("C min: %f, max: %f, average: %f" % (C.min(), C.max(), C.mean()))
    print("sf**2 min: %f, max: %f, average: %f" % ((sf ** 2).min(), (sf ** 2).max(), (sf ** 2).mean()))
    print("Efficiency min: %f, max: %f, average: %f" % (efficiency.min(), efficiency.max(), efficiency.mean()))

    return efficiency

if __name__ == "__main__":

    # beam = run_shadow()

    eff = calculate_efficiency(mirr="mirr.02",angle_file="angle.02",material="Au",gamma_blaze_deg=0.45,lines_per_mm=300.0)
    plot_scatter(numpy.arange(eff.size),eff,title="Efficiency",xtitle="ray index)",ytitle="Efficiency")

Exemplo n.º 22
0
    zmin = 0.

    bound1 = BoundaryRectangle(xmax, xmin, ymax, ymin, zmax, zmin)
    bound2 = BoundaryRectangle(xmax, xmin, ymax, ymin, zmax, zmin)

    montel = CompoundOpticalElement.initialize_as_montel_parabolic(
        p=p,
        q=q,
        theta_z=theta,
        bound1=bound1,
        bound2=bound2,
        distance_of_the_screen=q)
    beam1, beam2, beam03 = montel.trace_montel(beam,
                                               name_file='polletto',
                                               print_footprint=0)

    f = h5py.File('polletto' + '.h5', 'r')
    n = np.ones(1)
    f['montel_good_rays/Number of rays'].read_direct(n)
    n = int(n[0])
    x1 = np.ones(n)
    y1 = np.ones(n)
    f['montel_good_rays/xoe1'].read_direct(x1)
    f['montel_good_rays/yoe1'].read_direct(y1)
    f.close()

    plot_scatter(y1 * 1e3,
                 x1 * 1e3,
                 title="footprint on oe1",
                 xtitle='y[mm]',
                 ytitle='x[mm]')
Exemplo n.º 23
0
import numpy
from matplotlib import rc

# # rc('font', **{'family':'serif','serif':['Palatino']})
# rc('text', usetex=True)

b = Shadow.Beam()
b.load("/home/manuel/Oasys/star_ken.01")

x = b.getshonecol(1, nolost=1)
y = b.getshonecol(3, nolost=1)

f = plot_scatter(1e6 * x,
                 1e6 * y,
                 xrange=[-500, 500],
                 yrange=[-500, 500],
                 nbins=51,
                 xtitle='X [$\mu$ m]',
                 ytitle='y [$\mu$ m]',
                 show=0)

# change in gol.py
# if plot_histograms:
#     left, width = 0.12, 0.65
#     bottom, height = 0.1, 0.65

f[1].set_ylabel("y [$\mu$ m]", fontsize=15)
f[1].set_xlabel("x [$\mu$ m]", fontsize=15)
f[1].tick_params(labelsize=15)
f[2].tick_params(labelsize=0)
f[3].tick_params(labelsize=0)
Exemplo n.º 24
0
    #
    # sample rays fro SHADOW
    #

    do_shadow = 0

    if do_shadow:

        import Shadow
        npoints = 10000
        xs, ys = sample_rays(wf.get_coordinate_x(),wf.get_coordinate_y(),wf.get_intensity(),number_of_points=npoints)
        xps, yps = sample_rays(wf_prop_srw.get_coordinate_x(),wf_prop_srw.get_coordinate_y(),wf_prop_srw.get_intensity(),
                               number_of_points=npoints)
        #
        plot_scatter(xps,yps,show=1,title="Divergences")

        shadow_beam = Shadow.Beam(10000)
        rays = shadow_beam.rays
        rays[:,10] = 2 * np.pi / (1e2*wavelength)
        rays[:,0] = xs
        rays[:,1] = 0.0
        rays[:,2] = ys
        rays[:,3] = xps
        rays[:,4] = np.sqrt(1 - (xps/propagation_distance)**2 - (yps/propagation_distance)**2)
        rays[:,5] = yps
        rays[:,9] = 1.0
        rays[:,11] = np.arange(1,npoints+1)

        rays[:,6] = 1.0 # electric vector s
Exemplo n.º 25
0
def respower_plot(beam, d, plot_substracted=False, nolost=True):
    from srxraylib.plot.gol import plot, plot_scatter
    import matplotlib.pylab as plt

    colE = d["colE"]
    col1 = d["col1"]
    coeff = d["coeff"]
    nolost = d["nolost"]
    coordinates_at_hlimit = d["coordinates_at_hlimit"]
    orig = d["origin"]
    title = d["title"]
    deltax1 = d["deltax1"]
    deltax2 = d["deltax2"]

    if colE == 11:
        xtitle = "Photon energy [eV]"
        unit = "eV"
    elif colE == 19:
        xtitle = "Photon wavelength [A]"
        unit = "A"

    ytitle = "column %i [user units]" % col1

    energy = beam.getshonecol(colE, nolost=nolost)
    z = beam.getshonecol(col1, nolost=nolost)
    yfit = coeff[1] + coeff[0] * energy

    #
    # substracted plot
    #
    if plot_substracted:
        f = plot_scatter(energy,
                         z - (coeff[1] + coeff[0] * energy),
                         xtitle=xtitle,
                         ytitle=ytitle,
                         title=title,
                         show=0)
        f[1].plot(energy, energy * 0 + coordinates_at_hlimit[0])
        f[1].plot(energy, energy * 0 + coordinates_at_hlimit[1])
        plt.show()

    #
    # main plot
    #

    g = plot_scatter(energy,
                     z,
                     show=0,
                     xtitle=xtitle,
                     ytitle=ytitle,
                     title=title + " E/DE=%d, DE=%f %s" %
                     (d["resolvingPower"], d["deltaE"], unit))
    g[1].plot(energy, yfit)
    g[1].plot(energy, yfit + coordinates_at_hlimit[0])
    g[1].plot(energy, yfit + coordinates_at_hlimit[1])
    g[1].plot(energy, energy * 0)
    if colE == 19:  # wavelength
        g[1].plot(numpy.array((orig + deltax1, orig + deltax1)),
                  numpy.array((-1000, 1000)))
        g[1].plot(numpy.array((orig - deltax2, orig - deltax2)),
                  numpy.array((-1000, 1000)))
    else:  # energy
        g[1].plot(numpy.array((orig - deltax1, orig - deltax1)),
                  numpy.array((-1000, 1000)))
        g[1].plot(numpy.array((orig + deltax2, orig + deltax2)),
                  numpy.array((-1000, 1000)))

    plt.show()