def calculate_laue_monochromator(energy_setup=8000.0,energies=numpy.linspace(7990,8010,200)):

    diffraction_setup_r = DiffractionSetup(geometry_type=LaueDiffraction(),  # GeometryType object
                                           crystal_name="Si",  # string
                                           thickness=10e-6,  # meters
                                           miller_h=1,  # int
                                           miller_k=1,  # int
                                           miller_l=1,  # int
                                           asymmetry_angle=numpy.pi/2,  # 10.0*numpy.pi/180.,            # radians
                                           azimuthal_angle=0.0)  # radians                            # int

    diffraction = Diffraction()

    scan = numpy.zeros_like(energies)
    r = numpy.zeros_like(energies)


    for i in range(energies.size):
        #
        # gets Bragg angle needed to create deviation's scan
        #
        energy = energies[i]
        bragg_angle = diffraction_setup_r.angleBragg(energy_setup)
        print("Bragg angle for E=%f eV is %f deg" % (energy, bragg_angle * 180.0 / numpy.pi))
        # Create a Diffraction object (the calculator)

        deviation = 0.0  # angle_deviation_min + ia * angle_step
        angle = deviation + numpy.pi / 2 + bragg_angle

        # calculate the components of the unitary vector of the incident photon scan
        # Note that diffraction plane is YZ
        yy = numpy.cos(angle)
        zz = - numpy.abs(numpy.sin(angle))
        photon = Photon(energy_in_ev=energy,direction_vector=Vector(0.0,yy,zz))

        # perform the calculation
        coeffs_r = diffraction.calculateDiffractedComplexAmplitudes(diffraction_setup_r, photon)

        scan[i] = energy
        r[i] = numpy.abs( coeffs_r['S'].complexAmplitude() )**4

    return scan,r
Exemple #2
0
    def toDictionary(self):
        """
        Returns this setup in InfoDictionary form.
        :return: InfoDictionary form of this setup.
        """
        info_dict = DiffractionSetup.toDictionary(self)

        info_dict["Minimum energy"] = str(self.energyMin())
        info_dict["Maximum energy"] = str(self.energyMax())
        info_dict["Number of energy points"] = str(self.energyPoints())
        info_dict["Angle deviation minimum"] = "%.2e" % (self.angleDeviationMin())
        info_dict["Angle deviation maximum"] = "%.2e" % (self.angleDeviationMax())
        info_dict["Angle deviation points"] = str(self.angleDeviationPoints())

        return info_dict
def diffractionSetup():
    directions = [Vector(0, 0, 1.0 / float(n)) for n in range(1, 176)]
    photons = [Photon(10000, direction) for direction in directions]
    diffraction_setup = DiffractionSetup(
        BraggDiffraction(),
        "Si",
        thickness=0.0001,
        miller_h=1,
        miller_k=1,
        miller_l=1,
        asymmetry_angle=10 * numpy.pi / 180,
        azimuthal_angle=0.0,
    )
    # incoming_photons=photons)
    return diffraction_setup
    def testOperatorNotEqual(self):
        diffraction_setup_one = diffractionSetup()
        diffraction_setup_two = DiffractionSetup(
            BraggDiffraction(),
            "Diamond",
            thickness=0.001,
            miller_h=1,
            miller_k=1,
            miller_l=1,
            asymmetry_angle=10 * numpy.pi / 180,
            azimuthal_angle=0.0,
        )
        # incoming_photons=None)

        self.assertTrue(diffraction_setup_one != diffraction_setup_two)
        self.assertFalse(diffraction_setup_one != diffractionSetup())
Exemple #5
0
    def __init__(self,
                 geometry_type, crystal_name, thickness,
                 miller_h, miller_k, miller_l,
                 asymmetry_angle,
                 azimuthal_angle,
                 energy_min,
                 energy_max,
                 energy_points,
                 angle_deviation_min,
                 angle_deviation_max,
                 angle_deviation_points):
        """
        Constructor.
        :param geometry_type: GeometryType (BraggDiffraction,...).
        :param crystal_name: The name of the crystal, e.g. Si.
        :param thickness: The crystal thickness.
        :param miller_h: Miller index H.
        :param miller_k: Miller index K.
        :param miller_l: Miller index L.
        :param asymmetry_angle: The asymmetry angle between surface normal and Bragg normal.
        :param azimuthal_angle: The angle between the projection of the Bragg normal
                                on the crystal surface plane and the x axis.
        :param energy_min: The minimum energy.
        :param energy_max: The maximum energy.
        :param energy_points: Number of energy points.
        :param angle_deviation_min: Minimal angle deviation.
        :param angle_deviation_max: Maximal angle deviation.
        :param angle_deviation_points: Number of deviations points.
        """
        energies = numpy.linspace(energy_min,
                               energy_max,
                               energy_points)

        deviations = numpy.linspace(angle_deviation_min,
                                 angle_deviation_max,
                                 angle_deviation_points)

        # Create an "info setup" solely for the determination of deviation angles.
        info_setup = DiffractionSetup(geometry_type=geometry_type,
                                      crystal_name=crystal_name,
                                      thickness=thickness,
                                      miller_h=miller_h,
                                      miller_k=miller_k,
                                      miller_l=miller_l,
                                      asymmetry_angle=asymmetry_angle,
                                      azimuthal_angle=azimuthal_angle,)
                                      # incoming_photons=[Photon(energy_min, Vector(0, 0, -1))])


        # Call base constructor.
        DiffractionSetup.__init__(self,
                                  geometry_type=geometry_type,
                                  crystal_name=crystal_name,
                                  thickness=thickness,
                                  miller_h=miller_h,
                                  miller_k=miller_k,
                                  miller_l=miller_l,
                                  asymmetry_angle=asymmetry_angle,
                                  azimuthal_angle=azimuthal_angle,)

                                  # incoming_photons=photons)


        # Create photons according to sweeps.
        photons = PhotonBunch() # list()
        for energy in energies:
            for deviation in deviations:
                direction = info_setup.incomingPhotonDirection(energy, deviation)
                incoming_photon = Photon(energy, direction)
                # photons.append(incoming_photon)
                photons.addPhoton(incoming_photon)

        self._incoming_photons = photons
        # [email protected]: in theory, not needed as this info is in _incoming_photons
        # but buffering this accelerates a lot the calculations
        self._deviations = None
        self._energies = None
Exemple #6
0
def calculate_with_polarized_photon(method=0):

    # Create a diffraction setup.

    print("\nCreating a diffraction setup...")
    diffraction_setup = DiffractionSetup(
        geometry_type=BraggDiffraction(),  # GeometryType object
        crystal_name="Si",  # string
        thickness=1e-2,  # meters
        miller_h=1,  # int
        miller_k=1,  # int
        miller_l=1,  # int
        asymmetry_angle=
        0,  #10.0*numpy.pi/180.,                              # radians
        azimuthal_angle=0.0)  # radians                            # int

    energy = 8000.0  # eV
    angle_deviation_min = -100e-6  # radians
    angle_deviation_max = 100e-6  # radians
    angle_deviation_points = 500

    angle_step = (angle_deviation_max -
                  angle_deviation_min) / angle_deviation_points

    bunch_in = PolarizedPhotonBunch()

    bragg_angle = diffraction_setup.angleBragg(energy)

    print("Bragg angle for E=%f eV is %f deg" %
          (energy, bragg_angle * 180.0 / numpy.pi))

    # Create a Diffraction object.
    diffraction = Diffraction()

    #
    # get wavevector with incident direction matching Bragg angle
    #
    K0 = diffraction_setup.getK0(energy)
    K0unitary = K0.getNormalizedVector()

    print("K0", K0.components())

    # method = 0 # diffraction for individual photons
    # method = 1 # diffraction for bunch
    ZZ = numpy.zeros(angle_deviation_points)

    if method == 0:
        bunch_out = PolarizedPhotonBunch()

        for ia in range(angle_deviation_points):
            deviation = angle_deviation_min + ia * angle_step

            # angle =  deviation + bragg_angle
            # yy = numpy.cos(angle)
            # zz = - numpy.abs(numpy.sin(angle))
            # photon = PolarizedPhoton(energy_in_ev=energy,direction_vector=Vector(0.0,yy,zz),
            #                          stokes_vector=StokesVector([1,0,1,0]))

            # minus sign in angle is to perform cw rotation when deviation increses
            Vin = K0unitary.rotateAroundAxis(Vector(1, 0, 0), -deviation)
            photon = PolarizedPhoton(energy_in_ev=energy,
                                     direction_vector=Vin,
                                     stokes_vector=StokesVector([1, 0, 1, 0]))

            photon_out = diffraction.calculateDiffractedPolarizedPhoton(
                diffraction_setup,
                incoming_polarized_photon=photon,
                inclination_angle=0.0)
            bunch_out.addPhoton(photon_out)
            ZZ[ia] = angle_deviation_min + ia * angle_step

    elif method == 1:  # diffraction for bunch
        for ia in range(angle_deviation_points):
            deviation = angle_deviation_min + ia * angle_step

            # angle = deviation + bragg_angle
            # yy = numpy.cos(angle)
            # zz = - numpy.abs(numpy.sin(angle))
            # photon = PolarizedPhoton(energy_in_ev=energy,direction_vector=Vector(0.0,yy,zz),
            #                          stokes_vector=StokesVector([1,0,1,0]))

            # minus sign in angle is to perform cw rotation when deviation increses
            Vin = K0unitary.rotateAroundAxis(Vector(1, 0, 0), -deviation)
            photon = PolarizedPhoton(energy_in_ev=energy,
                                     direction_vector=Vin,
                                     stokes_vector=StokesVector([1, 0, 1, 0]))

            bunch_in.addPhoton(photon)
            ZZ[ia] = angle_deviation_min + ia * angle_step

        bunch_out = diffraction.calculateDiffractedPolarizedPhotonBunch(
            diffraction_setup, bunch_in, 0.0)

    bunch_out_dict = bunch_out.toDictionary()

    plot(1e6 * ZZ,
         bunch_out_dict["s0"],
         1e6 * ZZ,
         bunch_out_dict["s1"],
         legend=["S0", "S1"],
         xtitle="theta - thetaB [urad]",
         title="Polarized reflectivity calculation using method %d" % method)
def calculate_with_crystalpy(
        bragg_or_laue=0,  #
        diffracted_or_transmitted=0,  #
        crystal_name="Si",  # string
        thickness=1e-2,  # meters
        miller_h=1,  # int
        miller_k=1,  # int
        miller_l=1,  # int
        asymmetry_angle=0.0,  # radians
        energy=8000.0,  # eV
        angle_deviation_min=-100e-6,  # radians
        angle_deviation_max=100e-6,  # radians
        angle_deviation_points=500,
        method=0,  # 0=crystalpy input, 1=shadow4 preprocessor file
):

    if bragg_or_laue == 0:
        if diffracted_or_transmitted == 0:
            geometry_type = BraggDiffraction()
        elif diffracted_or_transmitted == 1:
            geometry_type = BraggTransmission()
        else:
            raise Exception("Bad geometry type")
    elif bragg_or_laue == 1:
        if diffracted_or_transmitted == 0:
            geometry_type = LaueDiffraction()
        elif diffracted_or_transmitted == 1:
            geometry_type = LaueTransmission()
        else:
            raise Exception("Bad geometry type")
    else:
        raise Exception("Bad geometry type")

    # Create a diffraction setup.

    # print("\nCreating a diffraction setup...")
    if method == 0:
        diffraction_setup = DiffractionSetup(geometry_type=geometry_type,
                                             crystal_name=crystal_name,
                                             thickness=thickness,
                                             miller_h=miller_h,
                                             miller_k=miller_k,
                                             miller_l=miller_l,
                                             asymmetry_angle=asymmetry_angle,
                                             azimuthal_angle=0.0)
    else:
        create_bragg_preprocessor_file_v1(interactive=False,
                                          DESCRIPTOR=crystal_name,
                                          H_MILLER_INDEX=miller_h,
                                          K_MILLER_INDEX=miller_k,
                                          L_MILLER_INDEX=miller_l,
                                          TEMPERATURE_FACTOR=1.0,
                                          E_MIN=5000.0,
                                          E_MAX=15000.0,
                                          E_STEP=100.0,
                                          SHADOW_FILE="bragg_xop.dat")

        diffraction_setup = DiffractionSetupShadowPreprocessor(
            geometry_type=geometry_type,
            crystal_name=crystal_name,
            thickness=thickness,
            miller_h=miller_h,
            miller_k=miller_k,
            miller_l=miller_l,
            asymmetry_angle=asymmetry_angle,
            azimuthal_angle=0.0,
            preprocessor_file="bragg_xop.dat")

    angle_step = (angle_deviation_max -
                  angle_deviation_min) / angle_deviation_points

    #
    # gets Bragg angle needed to create deviation's scan
    #
    bragg_angle = diffraction_setup.angleBragg(energy)

    # print("Bragg angle for E=%f eV is %f deg"%(energy,bragg_angle*180.0/numpy.pi))

    # Create a Diffraction object (the calculator)
    diffraction = Diffraction()

    # initialize arrays for storing outputs
    deviations = numpy.zeros(angle_deviation_points)
    intensityS = numpy.zeros(angle_deviation_points)
    intensityP = numpy.zeros(angle_deviation_points)

    for ia in range(angle_deviation_points):
        deviation = angle_deviation_min + ia * angle_step

        # angle = deviation  + bragg_angle + asymmetry_angle
        # # calculate the components of the unitary vector of the incident photon scan
        # # Note that diffraction plane is YZ
        # yy = numpy.cos(angle)
        # zz = - numpy.abs(numpy.sin(angle))
        # photon = Photon(energy_in_ev=energy,direction_vector=Vector(0.0,yy,zz))

        k_unitary = diffraction_setup.incomingPhotonDirection(
            energy, deviation)

        # or equivalently
        # k_0_unitary = diffraction_setup.incomingPhotonDirection(energy, 0.0)
        # k_unitary = k_0_unitary.rotateAroundAxis( Vector(1.0,0.0,0.0), -deviation)

        photon = Photon(energy_in_ev=energy, direction_vector=k_unitary)

        # perform the calculation
        coeffs = diffraction.calculateDiffractedComplexAmplitudes(
            diffraction_setup, photon)
        # store results
        deviations[ia] = deviation
        intensityS[ia] = coeffs['S'].intensity()
        intensityP[ia] = coeffs['P'].intensity()

    return deviations, intensityS, intensityP
    def calculate_external_Crystal(GEOMETRY_TYPE,
                                          CRYSTAL_NAME,
                                          THICKNESS,
                                          MILLER_H,
                                          MILLER_K,
                                          MILLER_L,
                                          ASYMMETRY_ANGLE,
                                          AZIMUTHAL_ANGLE,
                                          incoming_bunch,
                                          INCLINATION_ANGLE,
                                          DUMP_TO_FILE,
                                          FILE_NAME="tmp.dat"):

        # Create a GeometryType object:
        #     Bragg diffraction = 0
        #     Bragg transmission = 1
        #     Laue diffraction = 2
        #     Laue transmission = 3
        if GEOMETRY_TYPE == 0:
            GEOMETRY_TYPE_OBJECT = BraggDiffraction()

        elif GEOMETRY_TYPE == 1:
            GEOMETRY_TYPE_OBJECT = BraggTransmission()

        elif GEOMETRY_TYPE == 2:
            GEOMETRY_TYPE_OBJECT = LaueDiffraction()

        elif GEOMETRY_TYPE == 3:
            GEOMETRY_TYPE_OBJECT = LaueTransmission()

        else:
            raise Exception("Crystal: The geometry type could not be interpreted!\n")

        # Create a diffraction setup.
        # At this stage I translate angles in radians, energy in eV and all other values in SI units.
        print("Crystal: Creating a diffraction setup...\n")

        diffraction_setup = DiffractionSetup(geometry_type=GEOMETRY_TYPE_OBJECT,  # GeometryType object
                                             crystal_name=str(CRYSTAL_NAME),  # string
                                             thickness=float(THICKNESS) * 1e-2,  # meters
                                             miller_h=int(MILLER_H),  # int
                                             miller_k=int(MILLER_K),  # int
                                             miller_l=int(MILLER_L),  # int
                                             asymmetry_angle=float(ASYMMETRY_ANGLE) / 180 * np.pi,  # radians
                                             azimuthal_angle=float(AZIMUTHAL_ANGLE) / 180 * np.pi)  # radians
                                             # incoming_photons=incoming_bunch)

        # Create a Diffraction object.
        diffraction = Diffraction()

        # Create a PolarizedPhotonBunch object holding the results of the diffraction calculations.
        print("Crystal: Calculating the outgoing photons...\n")
        outgoing_bunch = diffraction.calculateDiffractedPolarizedPhotonBunch(diffraction_setup,
                                                                    incoming_bunch,
                                                                    INCLINATION_ANGLE)

        # Check that the result of the calculation is indeed a PolarizedPhotonBunch object.
        if not isinstance(outgoing_bunch, PolarizedPhotonBunch):
            raise Exception("Crystal: Expected PolarizedPhotonBunch as a result, found {}!\n".format(type(outgoing_bunch)))

        # Dump data to file if requested.
        if DUMP_TO_FILE == 0:

            print("Crystal: Writing data in {file}...\n".format(file=FILE_NAME))

            with open(FILE_NAME, "w") as file:
                try:
                    file.write("#S 1 photon bunch\n"
                               "#N 8\n"
                               "#L  Energy [eV]  Vx  Vy  Vz  S0  S1  S2  S3\n")
                    file.write(outgoing_bunch.toString())
                    file.close()
                    print("File written to disk: %s"%FILE_NAME)
                except:
                    raise Exception("Crystal: The data could not be dumped onto the specified file!\n")

        return outgoing_bunch
Exemple #9
0
def calculate_simple_diffraction():

    # Create a diffraction setup.

    print("\nCreating a diffraction setup...")
    diffraction_setup = DiffractionSetup(
        geometry_type=BraggDiffraction(),  # GeometryType object
        crystal_name="Si",  # string
        thickness=1e-2,  # meters
        miller_h=1,  # int
        miller_k=1,  # int
        miller_l=1,  # int
        asymmetry_angle=
        0,  #10.0*numpy.pi/180.,                              # radians
        azimuthal_angle=0.0)  # radians                            # int

    energy = 8000.0  # eV
    angle_deviation_min = -100e-6  # radians
    angle_deviation_max = 100e-6  # radians
    angle_deviation_points = 500

    angle_step = (angle_deviation_max -
                  angle_deviation_min) / angle_deviation_points

    #
    # gets Bragg angle needed to create deviation's scan
    #
    bragg_angle = diffraction_setup.angleBragg(energy)

    print("Bragg angle for E=%f eV is %f deg" %
          (energy, bragg_angle * 180.0 / numpy.pi))

    # Create a Diffraction object (the calculator)
    diffraction = Diffraction()

    # initialize arrays for storing outputs
    deviations = numpy.zeros(angle_deviation_points)
    intensityS = numpy.zeros(angle_deviation_points)
    intensityP = numpy.zeros(angle_deviation_points)

    for ia in range(angle_deviation_points):
        deviation = angle_deviation_min + ia * angle_step
        angle = deviation + bragg_angle

        # calculate the components of the unitary vector of the incident photon scan
        # Note that diffraction plane is YZ
        yy = numpy.cos(angle)
        zz = -numpy.abs(numpy.sin(angle))
        photon = Photon(energy_in_ev=energy,
                        direction_vector=Vector(0.0, yy, zz))

        # perform the calculation
        coeffs = diffraction.calculateDiffractedComplexAmplitudes(
            diffraction_setup, photon)

        # store results
        deviations[ia] = deviation
        intensityS[ia] = coeffs['S'].intensity()
        intensityP[ia] = coeffs['P'].intensity()

    # plot results
    import matplotlib.pylab as plt
    plt.plot(1e6 * deviations, intensityS)
    plt.plot(1e6 * deviations, intensityP)
    plt.xlabel("deviation angle [urad]")
    plt.ylabel("Reflectivity")
    plt.legend(["Sigma-polarization", "Pi-polarization"])
    plt.show()
Exemple #10
0
                                            material_constants_library=xraylib)

    a = DiffractionSetupShadowPreprocessorV2(geometry_type=BraggDiffraction,
                                             crystal_name="Si",
                                             thickness=1e-5,
                                             miller_h=1,
                                             miller_k=1,
                                             miller_l=1,
                                             asymmetry_angle=0.0,
                                             azimuthal_angle=0.0,
                                             preprocessor_file="bragg.dat")

    b = DiffractionSetup(geometry_type=BraggDiffraction,
                         crystal_name="Si",
                         thickness=1e-5,
                         miller_h=1,
                         miller_k=1,
                         miller_l=1,
                         asymmetry_angle=0.0,
                         azimuthal_angle=0.0)

    energy = 8000.0
    print("============ SHADOW / XRAYLIB  ==============")
    print("Photon energy: %g eV " % (energy))
    print("d_spacing: %g %g A " % (a.dSpacing(), b.dSpacing()))
    print("unitCellVolumw: %g %g A**3 " %
          (a.unitcellVolume(), b.unitcellVolume()))
    print("Bragg angle: %g %g deg " % (a.angleBragg(energy) * 180 / numpy.pi,
                                       b.angleBragg(energy) * 180 / numpy.pi))
    print("Asymmetry factor b: ", a.asymmetryFactor(energy),
          b.asymmetryFactor(energy))
Exemple #11
0
    def align_crystal(self):

        oe = self.get_optical_element()
        coor = self.get_coordinates()

        if oe._material_constants_library_flag == 0:
            print("\nCreating a diffraction setup (XRAYLIB)...")
            diffraction_setup = DiffractionSetup(
                geometry_type=BraggDiffraction(
                ),  # todo: use oe._diffraction_geometry
                crystal_name=oe._material,  # string
                thickness=oe._thickness,  # meters
                miller_h=oe._miller_index_h,  # int
                miller_k=oe._miller_index_k,  # int
                miller_l=oe._miller_index_l,  # int
                asymmetry_angle=oe._asymmetry_angle,  # radians
                azimuthal_angle=0.0)
        elif oe._material_constants_library_flag == 1:
            print("\nCreating a diffraction setup (DABAX)...")
            diffraction_setup = DiffractionSetupDabax(
                geometry_type=BraggDiffraction(
                ),  # todo: use oe._diffraction_geometry
                crystal_name=oe._material,  # string
                thickness=oe._thickness,  # meters
                miller_h=oe._miller_index_h,  # int
                miller_k=oe._miller_index_k,  # int
                miller_l=oe._miller_index_l,  # int
                asymmetry_angle=oe._asymmetry_angle,  # radians
                azimuthal_angle=0.0)
        elif oe._material_constants_library_flag == 2:
            print(
                "\nCreating a diffraction setup (shadow preprocessor file V1)..."
            )
            diffraction_setup = DiffractionSetupShadowPreprocessorV1(
                geometry_type=BraggDiffraction(
                ),  # todo: use oe._diffraction_geometry
                crystal_name=oe._material,  # string
                thickness=oe._thickness,  # meters
                miller_h=oe._miller_index_h,  # int
                miller_k=oe._miller_index_k,  # int
                miller_l=oe._miller_index_l,  # int
                asymmetry_angle=oe._asymmetry_angle,  # radians
                azimuthal_angle=0.0,
                preprocessor_file=oe._file_refl)
        elif oe._material_constants_library_flag == 3:
            print(
                "\nCreating a diffraction setup (shadow preprocessor file V2)..."
            )
            diffraction_setup = DiffractionSetupShadowPreprocessorV2(
                geometry_type=BraggDiffraction(
                ),  # todo: use oe._diffraction_geometry
                crystal_name=oe._material,  # string
                thickness=oe._thickness,  # meters
                miller_h=oe._miller_index_h,  # int
                miller_k=oe._miller_index_k,  # int
                miller_l=oe._miller_index_l,  # int
                asymmetry_angle=oe._asymmetry_angle,  # radians
                azimuthal_angle=0.0,
                preprocessor_file=oe._file_refl)
        else:
            raise NotImplementedError

        self._crystalpy_diffraction_setup = diffraction_setup

        if oe._f_central:
            if oe._f_phot_cent == 0:
                energy = oe._phot_cent
            else:
                energy = codata.h * codata.c / codata.e * 1e2 / (
                    oe._phot_cent * 1e-8)

            setting_angle = diffraction_setup.angleBraggCorrected(energy)

            print("Bragg angle for E=%f eV is %f deg" %
                  (energy, setting_angle * 180.0 / numpy.pi))

            coor.set_angles(angle_radial=numpy.pi / 2 - setting_angle,
                            angle_radial_out=numpy.pi / 2 - setting_angle,
                            angle_azimuthal=0.0)
        else:
            print("Info: nothing to align: f_central=0")

        print(coor.info())
def calculate_simple_diffraction_energy_scan_accelerated():

    # Create a diffraction setup.

    print("\nCreating a diffraction setup...")
    diffraction_setup = DiffractionSetup(
        geometry_type=BraggDiffraction(),  # GeometryType object
        crystal_name="Si",  # string
        thickness=1e-2,  # meters
        miller_h=1,  # int
        miller_k=1,  # int
        miller_l=1,  # int
        asymmetry_angle=
        0,  #10.0*numpy.pi/180.,                              # radians
        azimuthal_angle=0.0)  # radians                            # int

    import socket
    if socket.getfqdn().find("esrf") >= 0:
        dx = DabaxXraylib(
            dabax_repository="http://ftp.esrf.fr/pub/scisoft/DabaxFiles/")
    else:
        dx = DabaxXraylib()

    diffraction_setup_dabax = DiffractionSetupDabax(
        geometry_type=BraggDiffraction(),  # GeometryType object
        crystal_name="Si",  # string
        thickness=1e-2,  # meters
        miller_h=1,  # int
        miller_k=1,  # int
        miller_l=1,  # int
        asymmetry_angle=
        0,  #10.0*numpy.pi/180.,                              # radians
        azimuthal_angle=0.0,
        dabax=dx)  # radians

    energy = 8000.0  # eV

    angle_deviation_min = -100e-6  # radians
    angle_deviation_max = 100e-6  # radians
    angle_deviation_points = 50

    angle_step = (angle_deviation_max -
                  angle_deviation_min) / angle_deviation_points

    #
    # gets Bragg angle needed to create deviation's scan
    #
    bragg_angle_corrected = diffraction_setup.angleBraggCorrected(energy)

    print("Bragg angle corrected for E=%f eV is %f deg" %
          (energy, bragg_angle_corrected * 180.0 / numpy.pi))

    DeltaE = energy * 1e-4

    npoints = 100
    energies = numpy.linspace(energy - 3 * DeltaE, energy + 3 * DeltaE,
                              npoints)

    # Create a Diffraction object (the calculator)
    diffraction = Diffraction()
    diffraction_dabax = Diffraction()

    # initialize arrays for storing outputs
    intensityS = numpy.zeros(npoints)
    intensityP = numpy.zeros(npoints)
    intensityS_dabax = numpy.zeros(npoints)
    intensityP_dabax = numpy.zeros(npoints)

    t0 = time.time()
    for ia in range(npoints):

        # calculate the components of the unitary vector of the incident photon scan
        # Note that diffraction plane is YZ
        yy = numpy.cos(bragg_angle_corrected)
        zz = -numpy.abs(numpy.sin(bragg_angle_corrected))
        photon = Photon(energy_in_ev=energies[ia],
                        direction_vector=Vector(0.0, yy, zz))

        # perform the calculation
        coeffs = diffraction.calculateDiffractedComplexAmplitudes(
            diffraction_setup, photon)

        # store results
        intensityS[ia] = coeffs['S'].intensity()
        intensityP[ia] = coeffs['P'].intensity()

    COOR = []
    ENER = []
    for ia in range(npoints):

        # calculate the components of the unitary vector of the incident photon scan
        # Note that diffraction plane is YZ
        yy = numpy.cos(bragg_angle_corrected)
        zz = -numpy.abs(numpy.sin(bragg_angle_corrected))

        COOR.append([0.0, yy, zz])
        ENER.append(energies[ia])

    t1 = time.time()

    Psi_0, Psi_H, Psi_H_bar = diffraction_setup_dabax.psiAll(ENER)

    for ia in range(npoints):
        # perform the calculation
        incoming_photon = Photon(energy_in_ev=ENER[ia],
                                 direction_vector=Vector(
                                     COOR[ia][0], COOR[ia][1], COOR[ia][2]))
        energy = ENER[ia]

        # psi_0, psi_H, psi_H_bar = diffraction_setup_dabax.psiAll(energy)
        psi_0, psi_H, psi_H_bar = Psi_0[ia], Psi_H[ia], Psi_H_bar[ia]

        # Create PerfectCrystalDiffraction instance.
        perfect_crystal = PerfectCrystalDiffraction(
            geometry_type=diffraction_setup_dabax.geometryType(),
            bragg_normal=diffraction_setup_dabax.normalBragg(),
            surface_normal=diffraction_setup_dabax.normalSurface(),
            bragg_angle=diffraction_setup_dabax.angleBragg(energy),
            psi_0=psi_0,
            psi_H=psi_H,
            psi_H_bar=psi_H_bar,
            thickness=diffraction_setup_dabax.thickness(),
            d_spacing=diffraction_setup_dabax.dSpacing() * 1e-10)

        complex_amplitudes = perfect_crystal.calculateDiffraction(
            incoming_photon)

        intensityS_dabax[ia] = complex_amplitudes['S'].intensity(
        )  # 0.0 # coeffs_dabax['S'].intensity()
        intensityP_dabax[ia] = complex_amplitudes['P'].intensity(
        )  # 0.0 # coeffs_dabax['P'].intensity()

    t2 = time.time()

    # plot results
    import matplotlib.pylab as plt
    plt.plot(energies, intensityS)
    plt.plot(energies, intensityP)
    plt.plot(energies, intensityS_dabax)
    plt.plot(energies, intensityP_dabax)
    plt.xlabel("photon energy [eV]")
    plt.ylabel("Reflectivity")
    plt.legend([
        "Sigma-polarization XRAYLIB", "Pi-polarization XRAYLIB",
        "Sigma-polarization DABAX", "Pi-polarization DABAX"
    ])
    plt.show()

    print("Total time, Time per points XRAYLIB: ", t1 - t0,
          (t1 - t0) / npoints)
    print("Total time, Time per points DABAX: ", t2 - t1, (t2 - t1) / npoints)
def calculate_simple_diffraction_angular_scan_accelerated():

    # Create a diffraction setup.

    print("\nCreating a diffraction setup...")
    diffraction_setup = DiffractionSetup(
        geometry_type=BraggDiffraction(),  # GeometryType object
        crystal_name="Si",  # string
        thickness=1e-2,  # meters
        miller_h=1,  # int
        miller_k=1,  # int
        miller_l=1,  # int
        asymmetry_angle=
        0,  #10.0*numpy.pi/180.,                              # radians
        azimuthal_angle=0.0)  # radians                            # int

    diffraction_setup_dabax = DiffractionSetupDabax(
        geometry_type=BraggDiffraction(),  # GeometryType object
        crystal_name="Si",  # string
        thickness=1e-2,  # meters
        miller_h=1,  # int
        miller_k=1,  # int
        miller_l=1,  # int
        asymmetry_angle=
        0,  #10.0*numpy.pi/180.,                              # radians
        azimuthal_angle=0.0,
        dabax=DabaxXraylib())  # radians

    energy = 8000.0  # eV
    angle_deviation_min = -100e-6  # radians
    angle_deviation_max = 100e-6  # radians
    angle_deviation_points = 50

    angle_step = (angle_deviation_max -
                  angle_deviation_min) / angle_deviation_points

    #
    # gets Bragg angle needed to create deviation's scan
    #
    bragg_angle = diffraction_setup.angleBragg(energy)

    print("Bragg angle for E=%f eV is %f deg" %
          (energy, bragg_angle * 180.0 / numpy.pi))

    # Create a Diffraction object (the calculator)
    diffraction = Diffraction()
    diffraction_dabax = Diffraction()

    # initialize arrays for storing outputs
    deviations = numpy.zeros(angle_deviation_points)
    intensityS = numpy.zeros(angle_deviation_points)
    intensityP = numpy.zeros(angle_deviation_points)
    intensityS_dabax = numpy.zeros(angle_deviation_points)
    intensityP_dabax = numpy.zeros(angle_deviation_points)

    for ia in range(angle_deviation_points):
        deviation = angle_deviation_min + ia * angle_step
        angle = deviation + bragg_angle

        # calculate the components of the unitary vector of the incident photon scan
        # Note that diffraction plane is YZ
        yy = numpy.cos(angle)
        zz = -numpy.abs(numpy.sin(angle))
        photon = Photon(energy_in_ev=energy,
                        direction_vector=Vector(0.0, yy, zz))

        # perform the calculation
        coeffs = diffraction.calculateDiffractedComplexAmplitudes(
            diffraction_setup, photon)

        # store results
        deviations[ia] = deviation
        intensityS[ia] = coeffs['S'].intensity()
        intensityP[ia] = coeffs['P'].intensity()

    psi_0, psi_H, psi_H_bar = diffraction_setup_dabax.psiAll(energy)

    for ia in range(angle_deviation_points):
        deviation = angle_deviation_min + ia * angle_step
        angle = deviation + bragg_angle

        # calculate the components of the unitary vector of the incident photon scan
        # Note that diffraction plane is YZ
        yy = numpy.cos(angle)
        zz = -numpy.abs(numpy.sin(angle))
        photon = Photon(energy_in_ev=energy,
                        direction_vector=Vector(0.0, yy, zz))

        # perform the calculation
        # coeffs_dabax = diffraction_dabax.calculateDiffractedComplexAmplitudes(diffraction_setup_dabax, photon)
        #
        # # store results
        # deviations[ia] = deviation
        # intensityS_dabax[ia] = coeffs_dabax['S'].intensity()
        # intensityP_dabax[ia] = coeffs_dabax['P'].intensity()

        # Create PerfectCrystalDiffraction instance.
        perfect_crystal = PerfectCrystalDiffraction(
            geometry_type=diffraction_setup_dabax.geometryType(),
            bragg_normal=diffraction_setup_dabax.normalBragg(),
            surface_normal=diffraction_setup_dabax.normalSurface(),
            bragg_angle=diffraction_setup_dabax.angleBragg(energy),
            psi_0=psi_0,
            psi_H=psi_H,
            psi_H_bar=psi_H_bar,
            thickness=diffraction_setup_dabax.thickness(),
            d_spacing=diffraction_setup_dabax.dSpacing() * 1e-10)

        complex_amplitudes = perfect_crystal.calculateDiffraction(photon)

        deviations[ia] = deviation
        intensityS_dabax[ia] = complex_amplitudes['S'].intensity(
        )  # 0.0 # coeffs_dabax['S'].intensity()
        intensityP_dabax[ia] = complex_amplitudes['P'].intensity(
        )  # 0.0 # coeffs_dabax['P'].intensity()

    # plot results
    import matplotlib.pylab as plt
    plt.plot(1e6 * deviations, intensityS)
    plt.plot(1e6 * deviations, intensityP)
    plt.plot(1e6 * deviations, intensityS_dabax)
    plt.plot(1e6 * deviations, intensityP_dabax)
    plt.xlabel("deviation angle [urad]")
    plt.ylabel("Reflectivity")
    plt.legend([
        "Sigma-polarization XRAYLIB", "Pi-polarization XRAYLIB",
        "Sigma-polarization DABAX", "Pi-polarization DABAX"
    ])
    plt.show()
Exemple #14
0
from crystalpy.diffraction.GeometryType import BraggDiffraction
from crystalpy.diffraction.DiffractionSetup import DiffractionSetup
from crystalpy.diffraction.DiffractionSetupDabax import DiffractionSetupDabax
from crystalpy.diffraction.DiffractionSetupShadowPreprocessor import DiffractionSetupShadowPreprocessor
from dabax.dabax_xraylib import DabaxXraylib
import numpy

a = DiffractionSetup(
    geometry_type=BraggDiffraction,
    crystal_name="Si",
    thickness=1e-5,
    miller_h=1,
    miller_k=1,
    miller_l=1,
    asymmetry_angle=0.0,
    azimuthal_angle=0.0,
)

import socket

if socket.getfqdn().find("esrf") >= 0:
    dx = DabaxXraylib(
        dabax_repository="http://ftp.esrf.fr/pub/scisoft/DabaxFiles/")
else:
    dx = DabaxXraylib()

a2 = DiffractionSetupDabax(geometry_type=BraggDiffraction,
                           crystal_name="Si",
                           thickness=1e-5,
                           miller_h=1,
                           miller_k=1,
def calculate_with_crystalpy(
    bragg_or_laue=0,  #
    diffracted_or_transmitted=0,  #
    crystal_name="Si",  # string
    thickness=1e-2,  # meters
    miller_h=1,  # int
    miller_k=1,  # int
    miller_l=1,  # int
    asymmetry_angle=0.0,  # radians
    energy=8000.0,  # eV
    angle_deviation_min=-100e-6,  # radians
    angle_deviation_max=100e-6,  # radians
    angle_deviation_points=500,
):

    if bragg_or_laue == 0:
        if diffracted_or_transmitted == 0:
            geometry_type = BraggDiffraction()
        elif diffracted_or_transmitted == 1:
            geometry_type = BraggTransmission()
        else:
            raise Exception("Bad geometry type")
    elif bragg_or_laue == 1:
        if diffracted_or_transmitted == 0:
            geometry_type = LaueDiffraction()
        elif diffracted_or_transmitted == 1:
            geometry_type = LaueTransmission()
        else:
            raise Exception("Bad geometry type")
    else:
        raise Exception("Bad geometry type")

    # Create a diffraction setup.

    print("\nCreating a diffraction setup...")
    diffraction_setup = DiffractionSetup(geometry_type=geometry_type,
                                         crystal_name=crystal_name,
                                         thickness=thickness,
                                         miller_h=miller_h,
                                         miller_k=miller_k,
                                         miller_l=miller_l,
                                         asymmetry_angle=asymmetry_angle,
                                         azimuthal_angle=0.0)

    # energy                 = 8000.0                           # eV
    # angle_deviation_min    = -100e-6                          # radians
    # angle_deviation_max    = 100e-6                           # radians
    # angle_deviation_points = 500

    angle_step = (angle_deviation_max -
                  angle_deviation_min) / angle_deviation_points

    #
    # gets Bragg angle needed to create deviation's scan
    #
    bragg_angle = diffraction_setup.angleBragg(energy)

    print("Bragg angle for E=%f eV is %f deg" %
          (energy, bragg_angle * 180.0 / numpy.pi))

    # Create a Diffraction object (the calculator)
    diffraction = Diffraction()

    # initialize arrays for storing outputs
    deviations = numpy.zeros(angle_deviation_points)
    intensityS = numpy.zeros(angle_deviation_points)
    intensityP = numpy.zeros(angle_deviation_points)

    k_0_unitary = diffraction_setup.incomingPhotonDirection(energy, 0.0)
    # photon_0 = Photon(energy_in_ev=energy,direction_vector=k_0_unitary)
    # k_H_unitary = diffraction_setup._
    # print(">>>>>>>>>>>>>>>>>>>>>>>>k_0: ",k_0_unitary._components )

    # plot_crystal_sketch(k_0_unitary,k_0_unitary,)

    for ia in range(angle_deviation_points):
        deviation = angle_deviation_min + ia * angle_step

        # angle = deviation  + bragg_angle + asymmetry_angle
        # # calculate the components of the unitary vector of the incident photon scan
        # # Note that diffraction plane is YZ
        # yy = numpy.cos(angle)
        # zz = - numpy.abs(numpy.sin(angle))
        # photon = Photon(energy_in_ev=energy,direction_vector=Vector(0.0,yy,zz))

        k_unitary = diffraction_setup.incomingPhotonDirection(
            energy, deviation)

        # or equivalently
        # k_0_unitary = diffraction_setup.incomingPhotonDirection(energy, 0.0)
        # k_unitary = k_0_unitary.rotateAroundAxis( Vector(1.0,0.0,0.0), -deviation)

        photon = Photon(energy_in_ev=energy, direction_vector=k_unitary)

        # perform the calculation
        coeffs = diffraction.calculateDiffractedComplexAmplitudes(
            diffraction_setup, photon)

        # store results
        deviations[ia] = deviation
        intensityS[ia] = coeffs['S'].intensity()
        intensityP[ia] = coeffs['P'].intensity()

    # print(">>>>>>>>>>>>>>>>>>>>>>>>k_0: ",k_0_unitary._components,k_0_unitary.getNormalizedVector()._components )
    return deviations, intensityS, intensityP
Exemple #16
0
def calculate_simple_diffraction():

    # Create a diffraction setup.

    thickness = 2e-6

    print("\nCreating a diffraction setup...")
    diffraction_setup_r = DiffractionSetup(geometry_type          = BraggDiffraction(),  # GeometryType object
                                               crystal_name           = "Si",                             # string
                                               thickness              = thickness,                             # meters
                                               miller_h               = 1,                                # int
                                               miller_k               = 1,                                # int
                                               miller_l               = 1,                                # int
                                               asymmetry_angle        = 0,#10.0*numpy.pi/180.,            # radians
                                               azimuthal_angle        = 0.0)                              # radians                            # int

    diffraction_setup_t = DiffractionSetup(geometry_type          = BraggTransmission(),  # GeometryType object
                                               crystal_name           = "Si",                             # string
                                               thickness              = thickness,                             # meters
                                               miller_h               = 1,                                # int
                                               miller_k               = 1,                                # int
                                               miller_l               = 1,                                # int
                                               asymmetry_angle        = 0,#10.0*numpy.pi/180.,            # radians
                                               azimuthal_angle        = 0.0)                              # radians

    diffraction_setup_r_half = DiffractionSetup(geometry_type          = BraggDiffraction(),  # GeometryType object
                                               crystal_name           = "Si",                             # string
                                               thickness              = thickness/2,                             # meters
                                               miller_h               = 1,                                # int
                                               miller_k               = 1,                                # int
                                               miller_l               = 1,                                # int
                                               asymmetry_angle        = 0,#10.0*numpy.pi/180.,            # radians
                                               azimuthal_angle        = 0.0)                              # radians                            # int

    diffraction_setup_t_half = DiffractionSetup(geometry_type          = BraggTransmission(),  # GeometryType object
                                               crystal_name           = "Si",                             # string
                                               thickness              = thickness/2,                             # meters
                                               miller_h               = 1,                                # int
                                               miller_k               = 1,                                # int
                                               miller_l               = 1,                                # int
                                               asymmetry_angle        = 0,#10.0*numpy.pi/180.,            # radians
                                               azimuthal_angle        = 0.0)                              # radians



    energy                 = 8000.0                           # eV
    angle_deviation_min    = -300e-6                          # radians
    angle_deviation_max    = 300e-6                           # radians
    angle_deviation_points = 500

    wavelength = codata.h * codata.c / codata.e / energy

    print(">>>>>>>>>>>>", wavelength)
    angle_step = (angle_deviation_max-angle_deviation_min)/angle_deviation_points

    #
    # gets Bragg angle needed to create deviation's scan
    #
    bragg_angle = diffraction_setup_r.angleBragg(energy)

    print("Bragg angle for E=%f eV is %f deg"%(energy,bragg_angle*180.0/numpy.pi))


    # Create a Diffraction object (the calculator)
    diffraction = Diffraction()

    # initialize arrays for storing outputs
    deviations = numpy.zeros(angle_deviation_points)
    intensityS_r = numpy.zeros(angle_deviation_points)
    intensityS_r_half = numpy.zeros(angle_deviation_points)
    intensityS_t = numpy.zeros(angle_deviation_points)

    intensityS_rr = numpy.zeros(angle_deviation_points)
    intensityS_tt = numpy.zeros(angle_deviation_points)

    r = numpy.zeros(angle_deviation_points, dtype=complex)
    r2um = numpy.zeros(angle_deviation_points, dtype=complex)
    t = numpy.zeros(angle_deviation_points, dtype=complex)

    for ia in range(angle_deviation_points):
        deviation = angle_deviation_min + ia * angle_step
        angle = deviation  + bragg_angle

        # calculate the components of the unitary vector of the incident photon scan
        # Note that diffraction plane is YZ
        yy = numpy.cos(angle)
        zz = - numpy.abs(numpy.sin(angle))
        photon = Photon(energy_in_ev=energy,direction_vector=Vector(0.0,yy,zz))

        # perform the calculation
        coeffs_r = diffraction.calculateDiffractedComplexAmplitudes(diffraction_setup_r, photon)
        coeffs_t = diffraction.calculateDiffractedComplexAmplitudes(diffraction_setup_t, photon)
        coeffs_r_half = diffraction.calculateDiffractedComplexAmplitudes(diffraction_setup_r_half, photon)
        coeffs_t_half = diffraction.calculateDiffractedComplexAmplitudes(diffraction_setup_t_half, photon)


        # coeffs_rr = \
        #             coeffs_r_half['S'] * \
        #             (coeffs_t_half['S']**0 + \
        #              coeffs_t_half['S']**2 * ( \
        #                     coeffs_r_half['S'] ** 0 + \
        #                     coeffs_r_half['S'] ** 2 + \
        #                     coeffs_r_half['S'] ** 4 + \
        #                     coeffs_r_half['S'] ** 6 + \
        #                     coeffs_r_half['S'] ** 8 + \
        #                     coeffs_r_half['S'] ** 10 + \
        #                     coeffs_r_half['S'] ** 12 + \
        #                     coeffs_r_half['S'] ** 14 + \
        #                     coeffs_r_half['S'] ** 16 + \
        #                     coeffs_r_half['S'] ** 18 \
        #             ) )

        # a = coeffs_r_half['S']
        # b = coeffs_t_half['S']


        r[ia] = coeffs_r_half['S'].complexAmplitude()
        # t[ia] = coeffs_t_half['S'].complexAmplitude() #* numpy.exp(1j * 2 * numpy.pi / wavelength * (0.5 * thickness / numpy.sin(bragg_angle)) )
        t[ia] = coeffs_t_half['S'].complexAmplitude() * numpy.exp(-1j * 2 * numpy.pi / wavelength * numpy.cos(bragg_angle) * deviation * (thickness/2) )


        r2um[ia] = coeffs_r['S'].complexAmplitude()

        # # sum = a**0
        # # for i in range(2,400,2):
        # #     sum += a**i
        # sum = a**0 / (a**0 - a**2)
        # # coeffs_rr =  a * (b**0 + b**2 * sum)
        # one = a**0
        # coeffs_rr =   a * ( one + b**2 / (one - a**2))
        # coeffs_tt = b**2 * sum
        #
        # intensityS_rr[ia] = coeffs_rr.intensity()
        # intensityS_tt[ia] = coeffs_tt.intensity()
        #
        # # print(coeffs_r)
        # # print(coeffs_r['S'].complexAmplitude())
        #
        # # store results
        deviations[ia] = deviation
        # intensityS_r[ia] = coeffs_r['S'].intensity()
        # intensityS_r_half[ia] = coeffs_r_half['S'].intensity()
        # intensityS_t[ia] = coeffs_t['S'].intensity()


        # print(">>>>>>>>>>", coeffs_r['S'].complexAmplitude() , coeffs_rr.complexAmplitude() )

    # plot results


    print(r, r.shape)

    from srxraylib.plot.gol import plot

    # plot(1e6 * deviations, numpy.abs(r)**2,
    #      1e6 * deviations, numpy.abs(t)**2,
    #     )
    #
    plot(1e6 * deviations, numpy.abs(r)**2,
         1e6 * deviations, numpy.abs(r+r*t*t/(1-r*r))**2,
         1e6 * deviations, numpy.abs(r2um) ** 2,
         1e6 * deviations, numpy.abs(r2um) ** 2 - numpy.abs(r+r*t*t/(1-r*r))**2,
         legend=['r','r2','r 2um','r 2 um - r2']
        )