Exemplo n.º 1
0
    def get_xray_dose_thickness(self,
                                i_matrix,
                                i_feature,
                                i_ftf,
                                i_btb,
                                i_btf,
                                hold_thickness=10):

        assert isinstance(i_matrix, result_holder)
        assert isinstance(i_feature, result_holder)

        theta_x_zpc = self.get_xray_theta_complete(i_matrix,
                                                   i_feature,
                                                   i_ftf,
                                                   i_btb,
                                                   i_btf,
                                                   contrast_mode='zpc')
        theta_x_abs = self.get_xray_theta_complete(i_matrix,
                                                   i_feature,
                                                   i_ftf,
                                                   i_btb,
                                                   i_btf,
                                                   contrast_mode='abs')

        # calculate contrast parameter
        ridelta_f = 1 - xraylib.Refractive_Index_Re(self.sample.feature,
                                                    i_feature.beam.energy,
                                                    self.sample.feature_den)
        ridelta_b = 1 - xraylib.Refractive_Index_Re(
            self.sample.matrix, i_matrix.beam.energy, self.sample.matrix_den)
        k_pi_f = i_feature.constants['k_pi_f']
        k_pi_b = i_matrix.constants['k_pi_b']
        i_abs_f = i_ftf.i_pi_ff.data

        # calculate dose wrt thickness
        t_f = i_matrix.output.t_f
        t_b = i_matrix.output.t_b
        wavelen = i_feature.beam.wavelength
        pixel = i_feature.measurement.pixel
        k_tot_b_x = i_matrix.constants['k_tot_b']
        feature_den = self.sample.feature_den
        energy = i_feature.beam.energy

        nprobe_x_zpc = 25. / theta_x_zpc**2
        nprobe_x_abs = 25. / theta_x_abs**2
        # feat_mass = pixel ** 2. * feature_den * t_f * 1.e-15
        # dose_x_zpc = nprobe_x_zpc * energy * ECharge * 1.e3 * i_abs_f / feat_mass
        # dose_x_abs = nprobe_x_abs * energy * ECharge * 1.e3 * i_abs_f / feat_mass

        dose_x_zpc = nprobe_x_zpc * energy * ECharge * 1.e3 * k_pi_f * np.exp(
            -k_pi_b * t_b / 2) / (feature_den * t_f**2 * 1e-15)
        dose_x_abs = nprobe_x_abs * energy * ECharge * 1.e3 * k_pi_f * np.exp(
            -k_pi_b * t_b / 2) / (feature_den * t_f**2 * 1e-15)

        print('i_abs_f', i_abs_f)
        print('nprobe_x_zpc', nprobe_x_zpc)
        print('dose_x_zpc', dose_x_zpc)

        self.doses_x_thickness.append(
            (dose_x_zpc, dose_x_abs, i_matrix, i_feature))
Exemplo n.º 2
0
    def get_ri_delta_beta(self, beam):

        delta_f = 1 - xraylib.Refractive_Index_Re(self.feature, beam.energy,
                                                  self.feature_den)
        delta_b = 1 - xraylib.Refractive_Index_Re(self.matrix, beam.energy,
                                                  self.matrix_den)
        beta_f = xraylib.Refractive_Index_Im(self.feature, beam.energy,
                                             self.feature_den)
        beta_b = xraylib.Refractive_Index_Im(self.matrix, beam.energy,
                                             self.matrix_den)
        return (delta_f, beta_f), (delta_b, beta_b)
Exemplo n.º 3
0
def crlRadius(f, E, material='Be', density=None):
    if density is None:
        density = xraylib.ElementDensity(
            xraylib.SymbolToAtomicNumber(material))
    #print getElementsName(material),E,density
    return f * 2. * (1. - xraylib.Refractive_Index_Re(
        getElementsName(material), E, density))
Exemplo n.º 4
0
def get_delta(input_parameters, calculation_parameters):
    density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(input_parameters.crl_material))

    energy_in_KeV = ShadowPhysics.getEnergyFromWavelength(calculation_parameters.gwavelength*input_parameters.widget.workspace_units_to_m*1e10)/1000
    delta = 1-xraylib.Refractive_Index_Re(input_parameters.crl_material, energy_in_KeV, density)

    return delta
Exemplo n.º 5
0
    def fixWeirdShadowBug(self):
        if not LNLSShadowWidget.is_weird_shadow_bug_fixed:
            try:
                xraylib.Refractive_Index_Re("LaB6", 10000, 4)
            except:
                pass

            LNLSShadowWidget.is_weird_shadow_bug_fixed = True
Exemplo n.º 6
0
    def fixWeirdShadowBug(self):
        if not AutomaticElement.is_weird_shadow_bug_fixed:
            try:
                xraylib.Refractive_Index_Re("LaB6", 10000, 4)
            except:
                pass

            AutomaticElement.is_weird_shadow_bug_fixed = True
Exemplo n.º 7
0
def index(ID,E=None):
  if E==None:
    E=pypsepics.get("SIOC:SYS0:ML00:AO627")/1000
  E=eV(E)/1000
  d=Density[ID]
  n_real=xraylib.Refractive_Index_Re(ID,E,d)  
  n_imag=xraylib.Refractive_Index_Im(ID,E,d)  
  n=complex(n_real,n_imag)
  return n
Exemplo n.º 8
0
def ri_delta(compound, energy_kev, density):
    """
    Return delta part of the refractive index of a certain compound. Convention follows
    n = 1 - \delta - i\beta.
    :param compound: str
    :param energy_kev: float
    :param density: float; in g/cm3
    :return: float
    """
    return 1 - xraylib.Refractive_Index_Re(compound, energy_kev, density)
Exemplo n.º 9
0
 def get_delta_beta(cls, shadow_rays, material):
     beta = numpy.zeros(len(shadow_rays))
     delta = numpy.zeros(len(shadow_rays))
     density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(material))
 
     for i in range(0, len(shadow_rays)):
         energy_in_KeV = ShadowPhysics.getEnergyFromShadowK(shadow_rays[i, 10])/1000
         delta[i] = (1-xraylib.Refractive_Index_Re(material, energy_in_KeV, density))
         beta[i]  = xraylib.Refractive_Index_Im(material, energy_in_KeV, density)
 
     return delta, beta 
Exemplo n.º 10
0
    def calculate_efficiency(cls, wavelength, zone_plate_material, zone_plate_thickness):
        energy_in_KeV = ShadowPhysics.getEnergyFromWavelength(wavelength*10)/1000

        density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(zone_plate_material))
        delta   = (1-xraylib.Refractive_Index_Re(zone_plate_material, energy_in_KeV, density))
        beta    = xraylib.Refractive_Index_Im(zone_plate_material, energy_in_KeV, density)
        phi     = 2*numpy.pi*zone_plate_thickness*delta/wavelength
        rho     = beta/delta

        efficiency     = (1/(numpy.pi**2))*(1 + numpy.exp(-2*rho*phi)      - (2*numpy.exp(-rho*phi)*numpy.cos(phi)))
        max_efficiency = (1/(numpy.pi**2))*(1 + numpy.exp(-2*rho*numpy.pi) + (2*numpy.exp(-rho*numpy.pi)))
        thickness_max_efficiency = numpy.round(wavelength/(2*delta), 2)

        return efficiency, max_efficiency, thickness_max_efficiency
Exemplo n.º 11
0
 def delta(self):
     """Decrement of refractive index."""
     return 1 - xl.Refractive_Index_Re(self.compound, self.energy,
                                       self.density)
Exemplo n.º 12
0
    def test_refractiveindex(self):
        density = float(2.328)
        c = compoundfromformula.CompoundFromFormula("Si", density, name="silicon")
        energy = np.asarray([5, 10], dtype=float)
        Z = 14

        # Xraylib (TODO: n_im sign is wrong!)
        n_re0 = np.asarray(
            [xraylib.Refractive_Index_Re("Si", e, density) for e in energy]
        )
        n_im0 = -np.asarray(
            [xraylib.Refractive_Index_Im("Si", e, density) for e in energy]
        )

        # Exactly like Xraylib (TODO: CS_Total -> CS_Photo_Total)
        delta = (
            density
            * 4.15179082788e-4
            * (Z + np.asarray([xraylib.Fi(Z, e) for e in energy]))
            / xraylib.AtomicWeight(Z)
            / energy ** 2
        )
        beta = (
            np.asarray([xraylib.CS_Total(Z, e) for e in energy])
            * density
            * 9.8663479e-9
            / energy
        )
        n_re1 = 1 - delta
        n_im1 = -beta

        np.testing.assert_allclose(n_re0, n_re1)
        np.testing.assert_allclose(n_im0, n_im1)

        # Im: Kissel
        n_im1b = (
            -np.asarray([xraylib.CS_Total_Kissel(Z, e) for e in energy])
            * density
            * 9.8663479e-9
            / energy
        )

        # Im: Kissel with pint
        n_im1d = (
            ureg.Quantity(c.mass_att_coeff(energy), "cm^2/g")
            * ureg.Quantity(c.density, "g/cm^3")
            * ureg.Quantity(energy, "keV").to("cm", "spectroscopy")
            / (4 * np.pi)
        )
        n_im1d = -n_im1d.to("dimensionless").magnitude

        r = n_im1b / n_im1d
        np.testing.assert_allclose(r, r[0])

        # Im: other formula
        n_im1c = (
            density
            * 4.15179082788e-4
            * (np.asarray([xraylib.Fii(Z, e) for e in energy]))
            / xraylib.AtomicWeight(Z)
            / energy ** 2
        )

        # Spectrocrunch
        n_re2 = c.refractive_index_real(energy)
        n_im2 = c.refractive_index_imag(energy)

        np.testing.assert_allclose(n_re2, n_re0)
        np.testing.assert_allclose(n_im2, n_im1c, rtol=1e-6)
Exemplo n.º 13
0
	print ("Bi M1N2 radiative rate: %f" % xraylib.RadRate(83,xraylib.M1N2_LINE))
	print ("U M3O3 Fluorescence Line Energy: %f" % xraylib.LineEnergy(92,xraylib.M3O3_LINE))
	print ("Ca(HCO3)2 Rayleigh cs at 10.0 keV: %f" % xraylib.CS_Rayl_CP("Ca(HCO3)2",10.0))

	cdtest = xraylib.CompoundParser("Ca(HCO3)2")
	print ("Ca(HCO3)2 contains %g atoms and %i elements"% (cdtest['nAtomsAll'], cdtest['nElements']))
	for i in range(cdtest['nElements']):
        	print ("Element %i: %lf %%" % (cdtest['Elements'][i],cdtest['massFractions'][i]*100.0))
		
	cdtest = xraylib.CompoundParser("SiO2")
	print ("SiO2 contains %g atoms and %i elements"% (cdtest['nAtomsAll'], cdtest['nElements']))
	for i in range(cdtest['nElements']):
        	print ("Element %i: %lf %%" % (cdtest['Elements'][i],cdtest['massFractions'][i]*100.0))
		

	print ("CS2 Refractive Index at 10.0 keV : %g - %g i" % (xraylib.Refractive_Index_Re("CS2",10.0,1.261),xraylib.Refractive_Index_Im("CS2",10.0,1.261)))
	print ("C16H14O3 Refractive Index at 1 keV : %g - %g i" % (xraylib.Refractive_Index_Re("C16H14O3",1.0,1.2),xraylib.Refractive_Index_Im("C16H14O3",1.0,1.2)))
	print ("SiO2 Refractive Index at 5 keV : %g - %g i" % (xraylib.Refractive_Index_Re("SiO2",5.0,2.65),xraylib.Refractive_Index_Im("SiO2",5.0,2.65)))
	print ("Compton profile for Fe at pz = 1.1 : %g" % xraylib.ComptonProfile(26,1.1))
	print ("M5 Compton profile for Fe at pz = 1.1 : %g" % xraylib.ComptonProfile_Partial(26,xraylib.M5_SHELL,1.1))
	print ("M1->M5 Coster-Kronig transition probability for Au : %f" % xraylib.CosKronTransProb(79,xraylib.FM15_TRANS))
	print ("L1->L3 Coster-Kronig transition probability for Fe : %f" % xraylib.CosKronTransProb(26,xraylib.FL13_TRANS))
	print ("Au Ma1 XRF production cs at 10.0 keV (Kissel): %f" % xraylib.CS_FluorLine_Kissel(79,xraylib.MA1_LINE,10.0))
	print ("Au Mb XRF production cs at 10.0 keV (Kissel): %f" % xraylib.CS_FluorLine_Kissel(79,xraylib.MB_LINE,10.0))
	print ("Au Mg XRF production cs at 10.0 keV (Kissel): %f" % xraylib.CS_FluorLine_Kissel(79,xraylib.MG_LINE,10.0))
	print ("K atomic level width for Fe: %g" % xraylib.AtomicLevelWidth(26,xraylib.K_SHELL))
	print ("Bi L2-M5M5 Auger non-radiative rate: %g" % xraylib.AugerRate(86,xraylib.L2_M5M5_AUGER))
	print ("Bi L3 Auger yield: %g" % xraylib.AugerYield(86, xraylib.L3_SHELL))
	symbol = xraylib.AtomicNumberToSymbol(26)
	print ("Symbol of element 26 is: %s" % symbol)
	print ("Number of element Fe is: %i" % xraylib.SymbolToAtomicNumber("Fe"))
def prerefl():
    """
     Preprocessor for mirrors - python+xraylib version

     -""" 
  
    # retrieve physical constants needed
    codata = scipy.constants.codata.physical_constants
    codata_c, tmp1, tmp2 = codata["speed of light in vacuum"]
    codata_h, tmp1, tmp2 = codata["Planck constant"]
    codata_ec, tmp1, tmp2 = codata["elementary charge"]
    # or hard code them 
    # In [174]: print("codata_c = %20.11e \n" % codata_c )
    # codata_c =    2.99792458000e+08 
    # In [175]: print("codata_h = %20.11e \n" % codata_h )
    # codata_h =    6.62606930000e-34 
    # In [176]: print("codata_ec = %20.11e \n" % codata_ec )
    # codata_ec =    1.60217653000e-19

    tocm = codata_h*codata_c/codata_ec*1e2

    # input section
    print("prerefl: Preprocessor for mirrors - python+xraylib version")
    iMaterial = raw_input("Enter material expression (symbol,formula): ")
    density = raw_input("Density [ g/cm3 ] ?") 
    density = float(density)

    estart = raw_input("Enter starting photon energy: ") 
    estart = float(estart)

    efinal = raw_input("Enter end photon energy: ") 
    efinal = float(efinal)

    estep = raw_input("Enter step photon energy:") 
    estep = float(estep)

    out_file  = raw_input("Output file : ")

    twopi = math.pi*2
    npoint = int( (efinal-estart)/estep + 1 )
    depth0 = density/2.0
    qmin = estart/tocm*twopi
    qmax = efinal/tocm*twopi
    qstep = estep/tocm*twopi

    f = open(out_file, 'wb')
    f.write( ("%20.11e "*4+"\n") % tuple([qmin,qmax,qstep,depth0]) )
    f.write("%i \n" % int(npoint))
    for i in range(npoint):
       energy = (estart+estep*i)*1e-3
       tmp = 2e0*(1e0-xraylib.Refractive_Index_Re(iMaterial,energy,density))
       f.write("%e \n" % tmp)
    for i in range(npoint):
       energy = (estart+estep*i)*1e-3
       tmp2 = 2e0*(xraylib.Refractive_Index_Im(iMaterial,energy,density))
       f.write("%e \n" % tmp2)
    print("File written to disk: %s" % out_file)
    f.close()

    # test (not needed)
    itest = 0
    if itest:
       cdtest = xraylib.CompoundParser(iMaterial)
       print "    ",iMaterial," contains %i atoms and %i elements"% (cdtest['nAtomsAll'], cdtest['nElements'])
       for i in range(cdtest['nElements']):
          print "    Element %i: %lf %%" % (cdtest['Elements'][i],cdtest['massFractions'][i]*100.0)
       print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
       print qmin,qmax,qstep,depth0
       print npoint
       for i in range(npoint):
          energy = (estart+estep*i)*1e-3
          qq = qmin+qstep*i
          print energy,qq, \
              2e0*(1e0-xraylib.Refractive_Index_Re(iMaterial,energy,density)),\
              2e0*(xraylib.Refractive_Index_Im(iMaterial,energy,density))
       print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"

    return None
def pre_mlayer():
    """
     SHADOW preprocessor for multilayers - python+xraylib version

     -""" 
    # input section
    print("pre_mlayer: SHADOW preprocessor for multilayers - python+xraylib version")
    fileout = raw_input("Name of output file : ")
    estart = raw_input("Photon energy (eV) from : ")
    estart = float(estart)
    efinal = raw_input("                     to : ")
    efinal = float(efinal)

    elfactor = math.log10(1.0e4/30.0)/300.0
    istart = int(math.log10(estart/30.0e0)/elfactor + 1)
    ifinal = int(math.log10(efinal/30.0e0)/elfactor + 2)
    np = int(ifinal - istart) + 1

    f = open(fileout, 'wb')
    f.write("%i \n" % np)
    for i in range(np):
        energy = 30e0*math.pow(10,elfactor*(istart+i-1))
        f.write("%e " % energy)
    f.write( "\n")

    print("  ")
    print("The stack is as follows: ")
    print("      ")
    print("                 vacuum   ")
    print("      |------------------------------|  \   ")
    print("      |          odd (n)             |  |   ")
    print("      |------------------------------|  | BILAYER # n   ")
    print("      |          even (n)            |  |   ")
    print("      |------------------------------|  /   ")
    print("      |          .                   |   ")
    print("      |          .                   |   ")
    print("      |          .                   |   ")
    print("      |------------------------------|  \   ")
    print("      |          odd (1)             |  |   ")
    print("      |------------------------------|  | BILAYER # 1   ")
    print("      |          even (1)            |  |   ")
    print("      |------------------------------|  /   ")
    print("      |                              |   ")
    print("      |///////// substrate //////////|   ")
    print("      |                              |   ")
    print("      ")
    print(" ")

    # substrate
    matSubstrate = raw_input("Specify the substrate material : ")
    denSubstrate = raw_input("Specify the substrate density [g/cm^3] : ")
    denSubstrate = float(denSubstrate)
    for i in range(np):
        energy = 30e0*math.pow(10,elfactor*(istart+i-1)) *1e-3 # in keV!!
        delta = 1e0-xraylib.Refractive_Index_Re(matSubstrate,energy,denSubstrate)
        beta = xraylib.Refractive_Index_Im(matSubstrate,energy,denSubstrate)
        f.write( ("%26.17e "*2+"\n") % tuple([delta,beta]) )
    
    print("Right above the substrate is the even layer material")
    matEven = raw_input("Specify the even layer material : ")
    denEven = raw_input("Specify the even layer density [g/cm^3] : ")
    denEven = float(denEven)
    for i in range(np):
        energy = 30e0*math.pow(10,elfactor*(istart+i-1)) *1e-3 # in keV!!
        delta = 1e0-xraylib.Refractive_Index_Re(matEven,energy,denEven)
        beta = xraylib.Refractive_Index_Im(matEven,energy,denEven)
        f.write( ("%26.17e  "*2+"\n") % tuple([delta,beta]) )

    print("Odd layer material is on top of the even layer.")
    matOdd = raw_input("Specify the odd layer material : ")
    denOdd = raw_input("Specify the odd layer density [g/cm^3] : ")
    denOdd = float(denOdd)
    for i in range(np):
        energy = 30e0*math.pow(10,elfactor*(istart+i-1)) *1e-3 # in keV!!
        delta = 1e0-xraylib.Refractive_Index_Re(matOdd,energy,denOdd)
        beta = xraylib.Refractive_Index_Im(matOdd,energy,denOdd)
        f.write( ("%26.17e "*2+"\n") % tuple([delta,beta]) )


    npair = raw_input("No. of layer pairs : ")
    npair = int(npair)
    #! [email protected] 2012-06-07 Nevot-Croce ML roughness model implemented.
    #! By convention, starting from the version that includes ML roughness
    #! we set NPAR negative, in order to assure compatibility with old
    #! versions. If NPAR<0, roughness data are read, if NPAR>0 no roughness.
    f.write("%i \n" % -npair)

    print(" ")
    print("Starting from the substrate surface, specify the thickness t :")
    print("      t = t(odd) + t(even)        in Angstroms,")
    print("and the gamma ratio :")
    print("      t(even) / (t(odd) + t(even))")
    print("for EACH bilayer.")
    print(" ")
    print("Type two -1 whenever you want the remaining layers ")
    print("to assume the thickness, gamma ratio and roughnesses of the previous one.")
    print(" ")
 
    #define variables
    thick=[0e0]*npair
    gamma1=[0e0]*npair
    mlroughness1=[0e0]*npair
    mlroughness2=[0e0]*npair

    for i in range(npair): 
        tmps = ("thickness [A], gamma ratio, roughness even [A] and roughness odd [A] of bilayer %i: \n"% (i+1) )
        tmp = raw_input(tmps)
        tmp1 = tmp.split()
        if ((i != 0) and (int(float(tmp1[0])) == -1)):
            thick[i:(npair-1)] = [thick[i-1]] * (npair-i)
            gamma1[i:(npair-1)] = [gamma1[i-1]] * (npair-i)
            mlroughness1[i:(npair-1)] = [mlroughness1[i-1]] * (npair-i)
            mlroughness2[i:(npair-1)] = [mlroughness2[i-1]] * (npair-i)
            break
        else:
            thick[i] = float(tmp1[0])
            gamma1[i] = float(tmp1[1])
            mlroughness1[i] = float(tmp1[2])
            mlroughness2[i] = float(tmp1[3])

    for i in range(npair):
        f.write( ("%26.17e "*4+"\n") % tuple([thick[i],gamma1[i],mlroughness1[i],mlroughness2[i]]) )

    print("***************************************************")
    print("  Is the multilayer graded over the surface? ")
    print("      0: No ")
    print("      1: t and/or gamma graded over the surface ")
    print("         (input spline files with t and gamma gradient")
    print("      2: t graded over the surface ")
    print("         (input quadratic fit to t gradient)")
    print("      ")

    igrade = raw_input("Is t and/or gamma graded over the surface [0=No/1=Yes] ? ")
    igrade = int(igrade)
    f.write("%i \n" % igrade)
    if igrade == 1:
        print("Generation of the spline coefficients for the t and gamma factors")
        print("over the surface.")
        print("Then GRADE_MLAYER should be run to generate the spline ")
        print("coefficients for the t and gamma factors over the surface.")
        print("Here just type in the file name that WILL be used to store")
        print("the spline coefficients :")
        fgrade = raw_input("File name (output from grade_mlayer: ")
        f.write("%s \n" % fgrade)
    elif igrade == 2:  # igrade=2, coefficients
        print("A second degree polynomial fit of the thickness grading")
        print("must be available:")
        print("t(y) = BILATER_THICHNESS(y)/BILAYER_THICKNESS(y=0)")
        print("t(y) = a0 + a1*y + a2*(y^2)  ")
        print("a0 (constant term) ")
        print("a1 (slope term) ")
        print("a2 (quadratic term) ")
        tmp = raw_input("Enter a0, a1, a2: ")
        f.write("%s \n" % tmp)

    f.close()
    print("File written to disk: %s" % fileout)
    return None
Exemplo n.º 16
0
    def reflec(self, WNUM, SIN_REF, COS_POLE, K_WHAT):

        # ! C+++
        # ! C	SUBROUTINE	REFLEC
        # ! C
        # ! C	PURPOSE		To compute the local reflectivity of a mirror or
        # ! C                     multilayer. Also compute filter transmittivity.
        # ! C
        # ! C
        # ! C	ARGUMENTS	[ I ] PIN	: (x,y,z) of the intercept
        # ! C			[ I ] wnum 	: wavenumber (cm-1)
        # ! C			[ I ] sin_ref	: sine of angle from surface
        # ! C			[ I ] cos_pole  : cosine of angle of normal from pole
        # ! C			[ O ] R_P 	: p-pol reflection coefficient
        # ! C			[ O ] R_S 	: s-pol    "  "
        # ! C
        # ! C---

        phases = 0.0
        phasep = 0.0

        NIN = self.pre_mlayer_dict["np"]
        PHOT_ENER = WNUM * tocm / (2 * numpy.pi)  # eV
        NPAIR = numpy.abs(self.pre_mlayer_dict["npair"])
        XLAM = 2 * numpy.pi / WNUM * 1.0e8  # Angstrom
        gamma1 = self.pre_mlayer_dict["gamma1"]
        t_oe = self.pre_mlayer_dict["thick"]

        # gamma1 = ratio t(even)/(t(odd)+t(even))  of each layer pair
        t_e = gamma1 * t_oe
        t_o = (1.0 - gamma1) * t_oe

        mlroughness1 = self.pre_mlayer_dict["mlroughness1"]
        mlroughness2 = self.pre_mlayer_dict["mlroughness2"]

        if self.using_pre_mlayer:
            ENER = self.pre_mlayer_dict["energy"]
            wnum = 2 * numpy.pi * ENER / tocm
            QMIN = wnum[0]
            QSTEP = wnum[1] - wnum[0]

            DELTA_S = self.pre_mlayer_dict["delta_s"]
            DELTA_E = self.pre_mlayer_dict["delta_e"]
            DELTA_O = self.pre_mlayer_dict["delta_o"]
            BETA_S = self.pre_mlayer_dict["beta_s"]
            BETA_E = self.pre_mlayer_dict["beta_e"]
            BETA_O = self.pre_mlayer_dict["beta_o"]

            i_grade = self.pre_mlayer_dict["igrade"]

            # TODO graded ml
            #         ! C
            #         ! C Is the multilayer thickness graded ?
            #         ! C
            #         read    (iunit,*)   i_grade
            #         ! 0=None
            #         ! 1=spline files
            #         ! 2=quadic coefficients
            #
            #         ! spline
            #         if (i_grade.eq.1) then
            #           read  (iunit,'(a)') file_grade
            #           OPEN  (45, FILE=adjustl(FILE_GRADE), STATUS='OLD', &
            #                 FORM='UNFORMATTED', IOSTAT=iErr)
            #           ! srio added test
            #           if (iErr /= 0 ) then
            #             print *,"REFLEC: File not found: "//trim(adjustl(file_grade))
            #             print *,'Error: REFLEC: File not found. Aborted.'
            #             ! stop 'File not found. Aborted.'
            #           end if
            #
            #           READ  (45) NTX, NTY
            #           READ  (45) TX,TY
            #           !DO 205 I = 1, NTX
            #           !DO 205 J = 1, NTY
            #           DO I = 1, NTX
            #             DO J = 1, NTY
            #               READ  (45) TSPL(1,I,1,J),TSPL(1,I,2,J),    & ! spline for t
            #                          TSPL(2,I,1,J),TSPL(2,I,2,J)
            #             END DO
            #           END DO
            #
            #           READ (45) NGX, NGY
            #           READ (45) GX,GY
            #           DO I = 1, NGX
            #             DO J = 1, NGY
            #               READ (45) GSPL(1,I,1,J),GSPL(1,I,2,J),    & ! spline for gamma
            #                         GSPL(2,I,1,J),GSPL(2,I,2,J)
            #             END DO
            #           END DO
            #
            #           CLOSE (45)
            #         end if
            #
            #         if (i_grade.eq.2) then  ! quadric coefficients
            #           !
            #           ! laterally gradded multilayer
            #           !
            #
            #           ! [email protected] added cubic term (requested B Meyer, LNLS)
            #           read(iunit,*,IOSTAT=iErr) lateral_grade_constant,lateral_grade_slope, &
            #                         lateral_grade_quadratic,lateral_grade_cubic
            #
            #         end if
            #
            #         close(unit=iunit)
            #         tfilm = absor
            #         RETURN
            #     END IF
            # END IF

            #         ! C
            #         ! C Multilayers reflectivity.
            #         ! C First interpolate for all the refractive indices.
            #         ! C

            ELFACTOR = numpy.log10(1.0e4 / 30.0e0) / 300.0e0

            index1 = numpy.log10(PHOT_ENER / ENER[0]) / ELFACTOR
            index1 = int(index1)

            DELS = DELTA_S[index1] + (DELTA_S[index1 + 1] - DELTA_S[index1]
                                      ) * (PHOT_ENER - ENER[index1]) / (
                                          ENER[index1 + 1] - ENER[index1])
            BETS = BETA_S[index1] + (BETA_S[index1 + 1] - BETA_S[index1]) * (
                PHOT_ENER - ENER[index1]) / (ENER[index1 + 1] - ENER[index1])
            DELE = DELTA_E[index1] + (DELTA_E[index1 + 1] - DELTA_E[index1]
                                      ) * (PHOT_ENER - ENER[index1]) / (
                                          ENER[index1 + 1] - ENER[index1])
            BETE = BETA_E[index1] + (BETA_E[index1 + 1] - BETA_E[index1]) * (
                PHOT_ENER - ENER[index1]) / (ENER[index1 + 1] - ENER[index1])
            DELO = DELTA_O[index1] + (DELTA_O[index1 + 1] - DELTA_O[index1]
                                      ) * (PHOT_ENER - ENER[index1]) / (
                                          ENER[index1 + 1] - ENER[index1])
            BETO = BETA_O[index1] + (BETA_O[index1 + 1] - BETA_O[index1]) * (
                PHOT_ENER - ENER[index1]) / (ENER[index1 + 1] - ENER[index1])
        else:  # not using preprocessor, using xraylib
            DELS = 1.0 - xraylib.Refractive_Index_Re(
                self.pre_mlayer_dict["materialS"], 1e-3 * PHOT_ENER,
                self.pre_mlayer_dict["densityS"])
            BETS = xraylib.Refractive_Index_Im(
                self.pre_mlayer_dict["materialS"], 1e-3 * PHOT_ENER,
                self.pre_mlayer_dict["densityS"])
            DELE = 1.0 - xraylib.Refractive_Index_Re(
                self.pre_mlayer_dict["material1"], 1e-3 * PHOT_ENER,
                self.pre_mlayer_dict["density1"])
            BETE = xraylib.Refractive_Index_Im(
                self.pre_mlayer_dict["material1"], 1e-3 * PHOT_ENER,
                self.pre_mlayer_dict["density1"])
            DELO = 1.0 - xraylib.Refractive_Index_Re(
                self.pre_mlayer_dict["material2"], 1e-3 * PHOT_ENER,
                self.pre_mlayer_dict["density2"])
            BETO = xraylib.Refractive_Index_Im(
                self.pre_mlayer_dict["material2"], 1e-3 * PHOT_ENER,
                self.pre_mlayer_dict["density2"])

        TFACT = 1.0
        GFACT = 1.0

        #TODO graded multilayers
        #         IF (I_GRADE.EQ.1) THEN
        #             XIN = PIN(1)
        #             YIN = PIN(2)
        #             CALL DBCEVL (TX,NTX,TY,NTY,TSPL,i101,XIN,YIN,PDS,IER)
        #             IF (IER.NE.0) THEN
        #               CALL      MSSG ('REFLEC','Spline error # ',IER)
        #               RETURN
        #             END IF
        #             TFACT = PDS(1)
        #             ! C
        #             CALL DBCEVL (GX,NGX,GY,NGY,GSPL,i101,XIN,YIN,PDS,IER)
        #             IF (IER.NE.0) THEN
        #               CALL MSSG ('REFLEC','Spline error # ',IER)
        #               RETURN
        #             END IF
        #             GFACT = PDS(1)
        #         ELSE IF (I_GRADE.EQ.2) THEN
        #             TFACT = lateral_grade_constant+ &
        #                     lateral_grade_slope*pin(2) + &
        #                     lateral_grade_quadratic*pin(2)*pin(2) + &
        #                     lateral_grade_cubic*pin(2)*pin(2)*pin(2)
        #         ELSE
        #         END IF
        #
        #

        R_S, R_P, PHASES, PHASEP = self.fresnel(TFACT, GFACT, NPAIR, SIN_REF,
                                                COS_POLE, XLAM, DELO, DELE,
                                                DELS, BETO, BETE, BETS, t_o,
                                                t_e, mlroughness1,
                                                mlroughness2)

        return R_S, R_P, 0, phases, phasep
Exemplo n.º 17
0
    def pre_mlayer(cls,
                   interactive=False,
                   FILE="pre_mlayer.dat",
                   E_MIN=5000.0,
                   E_MAX=20000.0,
                   S_DENSITY=2.33,
                   S_MATERIAL="Si",
                   E_DENSITY=2.40,
                   E_MATERIAL="B4C",
                   O_DENSITY=9.40,
                   O_MATERIAL="Ru",
                   GRADE_DEPTH=0,
                   N_PAIRS=70,
                   THICKNESS=33.1,
                   GAMMA=0.483,
                   ROUGHNESS_EVEN=3.3,
                   ROUGHNESS_ODD=3.1,
                   FILE_DEPTH="myfile_depth.dat",
                   GRADE_SURFACE=0,
                   FILE_SHADOW="mlayer1.sha",
                   FILE_THICKNESS="mythick.dat",
                   FILE_GAMMA="mygamma.dat",
                   AA0=1.0,
                   AA1=0.0,
                   AA2=0.0,
                   AA3=0.0):
        """
         SHADOW preprocessor for multilayers - python+xraylib version
        """

        import xraylib

        # input section
        if interactive:
            print(
                "pre_mlayer: SHADOW preprocessor for multilayers - python+xraylib version"
            )
            fileout = input("Name of output file : ")
            estart = input("Photon energy (eV) from : ")
            estart = float(estart)
            efinal = input("                     to : ")
            efinal = float(efinal)

            print("  ")
            print("The stack is as follows: ")
            print("      ")
            print("                 vacuum   ")
            print("      |------------------------------|  \   ")
            print("      |          odd (n)             |  |   ")
            print("      |------------------------------|  | BILAYER # n   ")
            print("      |          even (n)            |  |   ")
            print("      |------------------------------|  /   ")
            print("      |          .                   |   ")
            print("      |          .                   |   ")
            print("      |          .                   |   ")
            print("      |------------------------------|  \   ")
            print("      |          odd (1)             |  |   ")
            print("      |------------------------------|  | BILAYER # 1   ")
            print("      |          even (1)            |  |   ")
            print("      |------------------------------|  /   ")
            print("      |                              |   ")
            print("      |///////// substrate //////////|   ")
            print("      |                              |   ")
            print("      ")
            print(" ")

            # substrate
            matSubstrate = input("Specify the substrate material : ")
            denSubstrate = input("Specify the substrate density [g/cm^3] : ")
            denSubstrate = float(denSubstrate)

            print("Right above the substrate is the even layer material")
            matEven = input("Specify the even layer material : ")
            denEven = input("Specify the even layer density [g/cm^3] : ")
            denEven = float(denEven)

            print("Odd layer material is on top of the even layer.")
            matOdd = input("Specify the odd layer material : ")
            denOdd = input("Specify the odd layer density [g/cm^3] : ")
            denOdd = float(denOdd)

            #! By convention, starting from the version that includes ML roughness
            #! we set NPAR negative, in order to assure compatibility with old
            #! versions. If NPAR<0, roughness data are read, if NPAR>0 no roughness.
            npair = input("No. of layer pairs : ")
            npair = int(npair)

            print(" ")
            print(
                "Starting from the substrate surface, specify the thickness t :"
            )
            print("      t = t(odd) + t(even)        in Angstroms,")
            print("and the gamma ratio :")
            print("      t(even) / (t(odd) + t(even))")
            print("for EACH bilayer.")
            print(" ")
            print("Type two -1 whenever you want the remaining layers ")
            print(
                "to assume the thickness, gamma ratio and roughnesses of the previous one."
            )
            print(" ")

            #define variables
            thick = [0e0] * npair
            gamma1 = [0e0] * npair
            mlroughness1 = [0e0] * npair
            mlroughness2 = [0e0] * npair

            for i in range(npair):
                tmps = (
                    "thickness [A], gamma ratio, roughness even [A] and roughness odd [A] of bilayer %i: \n"
                    % (i + 1))
                tmp = input(tmps)
                tmp1 = tmp.split()
                if ((i != 0) and (int(float(tmp1[0])) == -1)):
                    thick[i:(npair - 1)] = [thick[i - 1]] * (npair - i)
                    gamma1[i:(npair - 1)] = [gamma1[i - 1]] * (npair - i)
                    mlroughness1[i:(npair -
                                    1)] = [mlroughness1[i - 1]] * (npair - i)
                    mlroughness2[i:(npair -
                                    1)] = [mlroughness2[i - 1]] * (npair - i)
                    break
                else:
                    thick[i] = float(tmp1[0])
                    gamma1[i] = float(tmp1[1])
                    mlroughness1[i] = float(tmp1[2])
                    mlroughness2[i] = float(tmp1[3])

            print("***************************************************")
            print("  Is the multilayer graded over the surface? ")
            print("      0: No ")
            print("      1: t and/or gamma graded over the surface ")
            print("         (input spline files with t and gamma gradient")
            print("      2: t graded over the surface ")
            print("         (input quadratic fit to t gradient)")
            print("      ")

            igrade = input(
                "Is t and/or gamma graded over the surface [0=No/1=Yes] ? ")
            igrade = int(igrade)
            if igrade == 1:
                print(
                    "Generation of the spline coefficients for the t and gamma factors"
                )
                print("over the surface.")
                print(
                    "Then GRADE_MLAYER should be run to generate the spline ")
                print(
                    "coefficients for the t and gamma factors over the surface."
                )
                print(
                    "Here just type in the file name that WILL be used to store"
                )
                print("the spline coefficients :")
                fgrade = input("File name (output from grade_mlayer: ")
            elif igrade == 2:  # igrade=2, coefficients
                print(
                    "A second degree polynomial fit of the thickness grading")
                print("must be available:")
                print("t(y) = BILATER_THICHNESS(y)/BILAYER_THICKNESS(y=0)")
                print("t(y) = a0 + a1*y + a2*(y^2) + a3*(y^3)  ")
                print("a0 (constant term) ")
                print("a1 (slope term) ")
                print("a2 (quadratic term) ")
                print("a3 (cubic term) ")
                tmp = input("Enter a0, a1, a2, a3: ")
                tmp = tmp.split()
                a0 = float(tmp[0])
                a1 = float(tmp[1])
                a2 = float(tmp[2])
                a3 = float(tmp[3])
        else:
            #--- From input keywords...
            fileout = FILE
            estart = float(E_MIN)
            efinal = float(E_MAX)

            # substrate
            matSubstrate = S_MATERIAL
            denSubstrate = float(S_DENSITY)

            matEven = E_MATERIAL
            denEven = float(E_DENSITY)

            matOdd = O_MATERIAL
            denOdd = float(O_DENSITY)

            npair = int(N_PAIRS)

            #define variables
            thick = [0e0] * npair
            gamma1 = [0e0] * npair
            mlroughness1 = [0e0] * npair
            mlroughness2 = [0e0] * npair

            for i in range(npair):
                thick[i] = float(THICKNESS)
                gamma1[i] = float(GAMMA)
                mlroughness1[i] = float(ROUGHNESS_EVEN)
                mlroughness2[i] = float(ROUGHNESS_ODD)

            igrade = int(GRADE_SURFACE)

            #TODO: check if needed file_gamma
            fgrade = FILE_THICKNESS  # raw_input("File name (output from grade_mlayer: ")

            a0 = float(AA0)
            a1 = float(AA1)
            a2 = float(AA2)
            a3 = float(AA3)

        elfactor = numpy.log10(1.0e4 / 30.0) / 300.0
        istart = int(numpy.log10(estart / 30.0e0) / elfactor + 1)
        ifinal = int(numpy.log10(efinal / 30.0e0) / elfactor + 2)
        np = int(ifinal - istart) + 1

        f = open(fileout, 'wt')

        pre_mlayer_dict = {}

        f.write("%i \n" % np)
        pre_mlayer_dict["np"] = np

        ENERGY = numpy.zeros(np)
        for i in range(np):
            energy = 30e0 * numpy.power(10, elfactor * (istart + i - 1))
            f.write("%e " % energy)
            ENERGY[i] = energy
        f.write("\n")
        pre_mlayer_dict["energy"] = ENERGY

        DELTA = numpy.zeros(np)
        BETA = numpy.zeros(np)
        for i in range(np):  #substrate
            energy = 30e0 * numpy.power(10, elfactor *
                                        (istart + i - 1)) * 1e-3  # in keV!!
            delta = 1e0 - xraylib.Refractive_Index_Re(matSubstrate, energy,
                                                      denSubstrate)
            beta = xraylib.Refractive_Index_Im(matSubstrate, energy,
                                               denSubstrate)
            DELTA[i] = delta
            BETA[i] = beta
            f.write(("%26.17e " * 2 + "\n") % tuple([delta, beta]))
        pre_mlayer_dict["delta_s"] = DELTA
        pre_mlayer_dict["beta_s"] = BETA

        DELTA = numpy.zeros(np)
        BETA = numpy.zeros(np)
        for i in range(np):  #even
            energy = 30e0 * numpy.power(10, elfactor *
                                        (istart + i - 1)) * 1e-3  # in keV!!
            delta = 1e0 - xraylib.Refractive_Index_Re(matEven, energy, denEven)
            beta = xraylib.Refractive_Index_Im(matEven, energy, denEven)
            DELTA[i] = delta
            BETA[i] = beta
            f.write(("%26.17e  " * 2 + "\n") % tuple([delta, beta]))
        pre_mlayer_dict["delta_e"] = DELTA
        pre_mlayer_dict["beta_e"] = BETA

        DELTA = numpy.zeros(np)
        BETA = numpy.zeros(np)
        for i in range(np):  #odd
            energy = 30e0 * numpy.power(10, elfactor *
                                        (istart + i - 1)) * 1e-3  # in keV!!
            delta = 1e0 - xraylib.Refractive_Index_Re(matOdd, energy, denOdd)
            beta = xraylib.Refractive_Index_Im(matOdd, energy, denOdd)
            DELTA[i] = delta
            BETA[i] = beta
            f.write(("%26.17e " * 2 + "\n") % tuple([delta, beta]))
        pre_mlayer_dict["delta_o"] = DELTA
        pre_mlayer_dict["beta_o"] = BETA

        #! [email protected] 2012-06-07 Nevot-Croce ML roughness model implemented.
        #! By convention, starting from the version that includes ML roughness
        #! we set NPAR negative, in order to assure compatibility with old
        #! versions. If NPAR<0, roughness data are read, if NPAR>0 no roughness.
        f.write("%i \n" % -npair)
        pre_mlayer_dict["npair"] = -npair

        for i in range(npair):
            f.write(
                ("%26.17e " * 4 + "\n") %
                tuple([thick[i], gamma1[i], mlroughness1[i], mlroughness2[i]]))
        pre_mlayer_dict["thick"] = numpy.array(thick)
        pre_mlayer_dict["gamma1"] = numpy.array(gamma1)
        pre_mlayer_dict["mlroughness1"] = numpy.array(mlroughness1)
        pre_mlayer_dict["mlroughness2"] = numpy.array(mlroughness2)

        f.write("%i \n" % igrade)
        pre_mlayer_dict["igrade"] = igrade
        if igrade == 1:
            f.write("%s \n" % fgrade)
            pre_mlayer_dict["fgrade"] = fgrade
        elif igrade == 2:  # igrade=2, coefficients
            f.write("%f  %f  %f  %f\n" % (a0, a1, a2, a3))
            pre_mlayer_dict["a0"] = a0
            pre_mlayer_dict["a1"] = a1
            pre_mlayer_dict["a2"] = a2
            pre_mlayer_dict["a3"] = a3

        f.close()
        print("File written to disk: %s" % fileout)

        out = MLayer()
        out.pre_mlayer_dict = pre_mlayer_dict
        out.using_pre_mlayer = True
        return out
Exemplo n.º 18
0
    .format(cdtest['nAtomsAll'], cdtest['nElements'], cdtest['molarMass']))
for i in range(cdtest['nElements']):
    print("Element {}: %lf %% and {} atoms".format(
        cdtest['Elements'][i], cdtest['massFractions'][i] * 100.0,
        cdtest['nAtoms'][i]))

cdtest = xraylib.CompoundParser("SiO2")
print("SiO2 contains {} atoms, {} elements and has a molar mass of {} g/mol".
      format(cdtest['nAtomsAll'], cdtest['nElements'], cdtest['molarMass']))
for i in range(cdtest['nElements']):
    print("Element {}: %lf %% and {} atoms".format(
        cdtest['Elements'][i], cdtest['massFractions'][i] * 100.0,
        cdtest['nAtoms'][i]))

print("CS2 Refractive Index at 10.0 keV : {} - {} i".format(
    xraylib.Refractive_Index_Re("CS2", 10.0, 1.261),
    xraylib.Refractive_Index_Im("CS2", 10.0, 1.261)))
print("C16H14O3 Refractive Index at 1 keV : {} - {} i".format(
    xraylib.Refractive_Index_Re("C16H14O3", 1.0, 1.2),
    xraylib.Refractive_Index_Im("C16H14O3", 1.0, 1.2)))
print("SiO2 Refractive Index at 5 keV : {} - {} i".format(
    xraylib.Refractive_Index_Re("SiO2", 5.0, 2.65),
    xraylib.Refractive_Index_Im("SiO2", 5.0, 2.65)))
print("Compton profile for Fe at pz = 1.1 : {}".format(
    xraylib.ComptonProfile(26, 1.1)))
print("M5 Compton profile for Fe at pz = 1.1 : {}".format(
    xraylib.ComptonProfile_Partial(26, xraylib.M5_SHELL, 1.1)))
print("M1->M5 Coster-Kronig transition probability for Au : {}".format(
    xraylib.CosKronTransProb(79, xraylib.FM15_TRANS)))
print("L1->L3 Coster-Kronig transition probability for Fe : {}".format(
    xraylib.CosKronTransProb(26, xraylib.FL13_TRANS)))
Exemplo n.º 19
0
    def prerefl(cls, interactive=True, SYMBOL="SiC", DENSITY=3.217, FILE="prerefl.dat", E_MIN=100.0, E_MAX=20000.0,
                E_STEP=100.0):
        """
         Preprocessor for mirrors - python+xraylib version

         -"""

        # retrieve physical constants needed
        import scipy
        import xraylib

        import scipy.constants as codata

        tocm = codata.h * codata.c / codata.e * 1e2

        if interactive:
            # input section
            print("prerefl: Preprocessor for mirrors - python+xraylib version")
            iMaterial = input("Enter material expression (symbol,formula): ")
            density = input("Density [ g/cm3 ] ?")
            density = float(density)

            estart = input("Enter starting photon energy: ")
            estart = float(estart)

            efinal = input("Enter end photon energy: ")
            efinal = float(efinal)

            estep = input("Enter step photon energy:")
            estep = float(estep)

            out_file = input("Output file : ")
        else:
            iMaterial = SYMBOL
            density = DENSITY
            estart = E_MIN
            efinal = E_MAX
            estep = E_STEP
            out_file = FILE

        twopi = numpy.pi * 2
        npoint = int((efinal - estart) / estep + 1)
        depth0 = density / 2.0
        qmin = estart / tocm * twopi
        qmax = efinal / tocm * twopi
        qstep = estep / tocm * twopi

        f = open(out_file, 'wt')
        f.write(("%20.11e " * 4 + "\n") % tuple([qmin, qmax, qstep, depth0]))
        f.write("%i \n" % int(npoint))
        for i in range(npoint):
            energy = (estart + estep * i) * 1e-3
            tmp = 2e0 * (1e0 - xraylib.Refractive_Index_Re(iMaterial, energy, density))
            f.write("%e \n" % tmp)
        for i in range(npoint):
            energy = (estart + estep * i) * 1e-3
            tmp2 = 2e0 * (xraylib.Refractive_Index_Im(iMaterial, energy, density))
            f.write("%e \n" % tmp2)
        print("File written to disk: %s" % out_file)
        f.close()

        # test (not needed)
        itest = 0
        if itest:
            cdtest = xraylib.CompoundParser(iMaterial)
            print("    ", iMaterial, " contains %i atoms and %i elements" % (cdtest['nAtomsAll'], cdtest['nElements']))
            for i in range(cdtest['nElements']):
                print("    Element %i: %lf %%" % (cdtest['Elements'][i], cdtest['massFractions'][i] * 100.0))
            print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            print(qmin, qmax, qstep, depth0)
            print(npoint)
            for i in range(npoint):
                energy = (estart + estep * i) * 1e-3
                qq = qmin + qstep * i
                print(energy, qq, \
                      2e0 * (1e0 - xraylib.Refractive_Index_Re(iMaterial, energy, density)), \
                      2e0 * (xraylib.Refractive_Index_Im(iMaterial, energy, density)))
            print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")

        return None
Exemplo n.º 20
0
curv_radius = 100e-6
nlenses = 1
nsurfaces = 1 * nlenses

title = 'Berylium' + ' Lens, Curv. Radius ' + \
        ' {:.1f} um, {:d} curved surfaces'.format(curv_radius*1e6, nsurfaces)

phenergy = np.arange(7e3, 9e3, 100)

# %% Obtain delta refractive index

delta = phenergy * 0.0

for i in range(delta.shape[0]):

    delta[i] = 1 - xraylib.Refractive_Index_Re("Be", phenergy[i] / 1e3,
                                               density)

# %%

focal_d = curv_radius / delta / nsurfaces

# %% q_arm vs energy

plt.figure()
plt.plot(phenergy * 1e-3, focal_d, '.-')
plt.xlabel('ph Energy [eV]')
plt.ylabel('Focal distance [m]')
plt.title(title)
#wpu.save_figs_with_idx()
plt.show(block=True)
Exemplo n.º 21
0
def crlFocalLength(r, E, material='Be', density=None):
    if density is None:
        density = xraylib.ElementDensity(
            xraylib.SymbolToAtomicNumber(material))
    return r / 2 / (
        1 - xraylib.Refractive_Index_Re(getElementsName(material), E, density))
Exemplo n.º 22
0
    def xoppy_calc_power3D(self):

        #
        # prepare input for xpower_calc
        # Note that the input for xpower_calc accepts any number of elements.
        #

        substance = [
            self.EL1_FOR, self.EL2_FOR, self.EL3_FOR, self.EL4_FOR,
            self.EL5_FOR
        ]
        thick = numpy.array((self.EL1_THI, self.EL2_THI, self.EL3_THI,
                             self.EL4_THI, self.EL5_THI))
        angle = numpy.array((self.EL1_ANG, self.EL2_ANG, self.EL3_ANG,
                             self.EL4_ANG, self.EL5_ANG))
        dens = [
            self.EL1_DEN, self.EL2_DEN, self.EL3_DEN, self.EL4_DEN,
            self.EL5_DEN
        ]
        roughness = numpy.array((self.EL1_ROU, self.EL2_ROU, self.EL3_ROU,
                                 self.EL4_ROU, self.EL5_ROU))
        flags = numpy.array((self.EL1_FLAG, self.EL2_FLAG, self.EL3_FLAG,
                             self.EL4_FLAG, self.EL5_FLAG))

        substance = substance[0:self.NELEMENTS + 1]
        thick = thick[0:self.NELEMENTS + 1]
        angle = angle[0:self.NELEMENTS + 1]
        dens = dens[0:self.NELEMENTS + 1]
        roughness = roughness[0:self.NELEMENTS + 1]
        flags = flags[0:self.NELEMENTS + 1]

        p, e, h, v = self.input_beam.get_content("xoppy_data")

        nelem_including_source = self.NELEMENTS + 1
        energies = e

        # initialize results

        # note that element of zero index corresponds to source!!!
        transmittance = numpy.zeros(
            (nelem_including_source, p.shape[0], p.shape[1], p.shape[2]))
        for i in range(nelem_including_source):
            transmittance[i] = numpy.ones_like(p)

        #
        # get undefined densities
        #
        for i in range(nelem_including_source):
            try:
                rho = float(dens[i])
            except:
                rho = xraylib.ElementDensity(
                    xraylib.SymbolToAtomicNumber(substance[i]))
                print("Density for %s: %g g/cm3" % (substance[i], rho))

            dens[i] = rho

        #info oe
        txt = ""
        for i in range(self.NELEMENTS):
            if flags[i] == 0:
                txt += '      *****   oe ' + str(
                    i + 1) + '  [Filter] *************\n'
                txt += '      Material: %s\n' % (substance[i])
                txt += '      Density [g/cm^3]: %f \n' % (dens[i])
                txt += '      thickness [mm] : %f \n' % (thick[i])
            else:
                txt += '      *****   oe ' + str(
                    i + 1) + '  [Mirror] *************\n'
                txt += '      Material: %s\n' % (substance[i])
                txt += '      Density [g/cm^3]: %f \n' % (dens[i])
                txt += '      grazing angle [mrad]: %f \n' % (angle[i])
                txt += '      roughness [A]: %f \n' % (roughness[i])

        for i in range(self.NELEMENTS):
            if flags[i] == 0:  # filter

                for j, energy in enumerate(energies):

                    tmp = xraylib.CS_Total_CP(substance[i], energy / 1000.0)

                    # pay attention to the element index...
                    transmittance[i + 1, j, :, :] = numpy.exp(
                        -tmp * dens[i] * (thick[i] / 10.0))

            if flags[i] == 1:  # mirror
                tmp = numpy.zeros(energies.size)
                for j, energy in enumerate(energies):
                    tmp[j] = xraylib.Refractive_Index_Re(
                        substance[i], energy / 1000.0, dens[i])
                delta = 1.0 - tmp

                beta = numpy.zeros(energies.size)
                for j, energy in enumerate(energies):
                    beta[j] = xraylib.Refractive_Index_Im(
                        substance[i], energy / 1000.0, dens[i])

                (rs,rp,runp) = reflectivity_fresnel(refraction_index_beta=beta,refraction_index_delta=delta,\
                                            grazing_angle_mrad=angle[i],roughness_rms_A=roughness[i],\
                                            photon_energy_ev=energies)

                for j, energy in enumerate(energies):
                    transmittance[i + 1, j, :, :] = rs[j]

        txt += "\n\n\n"
        integration_constante = (e[1] - e[0]) * (h[1] - h[0]) * (
            v[1] - v[0]) * codata.e * 1e3
        p_cumulated = p.copy()
        power_cumulated = p_cumulated.sum() * integration_constante
        txt += '      Input beam power: %f W\n' % (power_cumulated)
        for i in range(self.NELEMENTS):
            p_cumulated *= transmittance[i + 1]
            power_transmitted = (p_cumulated).sum() * integration_constante
            txt += '      Beam power after optical element %d: %6.3f W (absorbed: %6.3f W)\n'%\
                   (i+1,power_transmitted,power_cumulated-power_transmitted)
            power_cumulated = power_transmitted
        print(txt)

        return transmittance
Exemplo n.º 23
0
    def xoppy_calc_power3Dcomponent(self):

        #
        # important: the transmittivity calculated here is referred on axes perp to the beam
        # therefore they do not include geometrical corrections for correct integral
        #

        substance = self.EL1_FOR
        thick     = self.EL1_THI
        angle     = self.EL1_ANG
        defection = self.EL1_DEF
        dens      = self.EL1_DEN
        roughness = self.EL1_ROU
        flags     = self.EL1_FLAG
        hgap = self.EL1_HGAP
        vgap = self.EL1_VGAP
        hmag = self.EL1_HMAG
        vmag = self.EL1_VMAG
        hrot = self.EL1_HROT
        vrot = self.EL1_VROT


        if self.INPUT_BEAM_FROM == 1:
            self.load_input_file()

        p0, e0, h0, v0 = self.input_beam.get_content("xoppy_data")

        p = p0.copy()
        e = e0.copy()
        h = h0.copy()
        v = v0.copy()

        transmittance = numpy.ones_like(p)
        E =  e.copy()
        H =  h.copy()
        V =  v.copy()

        # initialize results

        #
        # get undefined densities
        #
        if flags <= 1:
            try:  # apply written value
                rho = float(dens)
            except:   # in case of ?
                # grabber = TTYGrabber()
                # grabber.start()
                rho = density(substance)
                # grabber.stop()
                # for row in grabber.ttyData:
                #     self.writeStdOut(row)
                print("Density for %s: %g g/cm3"%(substance,rho))
            dens = rho


        txt = ""

        if flags == 0:
            txt += '      *****   oe  [Filter] *************\n'
            txt += '      Material: %s\n'%(substance)
            txt += '      Density [g/cm^3]: %f \n'%(dens)
            txt += '      thickness [mm] : %f \n'%(thick)
            txt += '      H gap [mm]: %f \n'%(hgap)
            txt += '      V gap [mm]: %f \n'%(vgap)
            txt += '      H rotation angle [deg]: %f \n'%(hrot)
            txt += '      V rotation angle [deg]: %f \n'%(vrot)
        elif flags == 1:
            txt += '      *****   oe  [Mirror] *************\n'
            txt += '      Material: %s\n'%(substance)
            txt += '      Density [g/cm^3]: %f \n'%(dens)
            txt += '      grazing angle [mrad]: %f \n'%(angle)
            txt += '      roughness [A]: %f \n'%(roughness)
        elif flags == 2:
            txt += '      *****   oe  [Aperture] *************\n'
            txt += '      H gap [mm]: %f \n'%(hgap)
            txt += '      V gap [mm]: %f \n'%(vgap)
        elif flags == 3:
            txt += '      *****   oe  [Magnifier] *************\n'
            txt += '      H magnification: %f \n'%(hmag)
            txt += '      V magnification: %f \n'%(vmag)
        elif flags == 4:
            txt += '      *****   oe  [Screen rotated] *************\n'
            txt += '      H rotation angle [deg]: %f \n'%(hrot)
            txt += '      V rotation angle [deg]: %f \n'%(vrot)


        if flags == 0: # filter
            grabber = TTYGrabber()
            grabber.start()
            for j,energy in enumerate(e):
                tmp = xraylib.CS_Total_CP(substance,energy/1000.0)
                transmittance[j,:,:] = numpy.exp(-tmp*dens*(thick/10.0))

            grabber.stop()
            for row in grabber.ttyData:
                self.writeStdOut(row)

            # rotation
            H = h / numpy.cos(hrot * numpy.pi / 180)
            V = v / numpy.cos(vrot * numpy.pi / 180)

            # aperture
            h_indices_bad = numpy.where(numpy.abs(H) > 0.5*hgap)
            if len(h_indices_bad) > 0:
                transmittance[:, h_indices_bad, :] = 0.0
            v_indices_bad = numpy.where(numpy.abs(V) > 0.5*vgap)
            if len(v_indices_bad) > 0:
                transmittance[:, :, v_indices_bad] = 0.0

            absorbance = 1.0 - transmittance

        elif flags == 1: # mirror
            tmp = numpy.zeros(e.size)

            for j,energy in enumerate(e):
                tmp[j] = xraylib.Refractive_Index_Re(substance,energy/1000.0,dens)

            if tmp[0] == 0.0:
                raise Exception("Probably the substrance %s is wrong"%substance)

            delta = 1.0 - tmp
            beta = numpy.zeros(e.size)

            for j,energy in enumerate(e):
                beta[j] = xraylib.Refractive_Index_Im(substance,energy/1000.0,dens)

            try:
                (rs,rp,runp) = reflectivity_fresnel(refraction_index_beta=beta,refraction_index_delta=delta,\
                                            grazing_angle_mrad=angle,roughness_rms_A=roughness,\
                                            photon_energy_ev=e)
            except:
                raise Exception("Failed to run reflectivity_fresnel")

            for j,energy in enumerate(e):
                transmittance[j,:,:] = rs[j]

            # rotation
            if defection == 0: # horizontally deflecting
                H = h / numpy.sin(self.EL1_ANG * 1e-3)
            elif defection == 1: # vertically deflecting
                V = v / numpy.sin(self.EL1_ANG * 1e-3)

            # size
            absorbance = 1.0 - transmittance

            h_indices_bad = numpy.where(numpy.abs(H) > 0.5*hgap)
            if len(h_indices_bad) > 0:
                transmittance[:, h_indices_bad, :] = 0.0
                absorbance[:, h_indices_bad, :] = 0.0
            v_indices_bad = numpy.where(numpy.abs(V) > 0.5*vgap)
            if len(v_indices_bad) > 0:
                transmittance[:, :, v_indices_bad] = 0.0
                absorbance[:, :, v_indices_bad] = 0.0

        elif flags == 2:  # aperture
            h_indices_bad = numpy.where(numpy.abs(H) > 0.5*hgap)
            if len(h_indices_bad) > 0:
                transmittance[:, h_indices_bad, :] = 0.0
            v_indices_bad = numpy.where(numpy.abs(V) > 0.5*vgap)
            if len(v_indices_bad) > 0:
                transmittance[:, :, v_indices_bad] = 0.0

            absorbance = 1.0 - transmittance

        elif flags == 3:  # magnifier
            H = h * hmag
            V = v * vmag

            absorbance = 1.0 - transmittance

        elif flags == 4:  # rotation screen
            # transmittance[:, :, :] = numpy.cos(hrot * numpy.pi / 180) * numpy.cos(vrot * numpy.pi / 180)
            H = h / numpy.cos(hrot * numpy.pi / 180)
            V = v / numpy.cos(vrot * numpy.pi / 180)

            absorbance = 1.0 - transmittance

        txt += self.info_total_power(p, e, v, h, transmittance, absorbance)

        print(txt)

        calculated_data = (transmittance, absorbance, E, H, V)

        if self.FILE_DUMP == 0:
            pass
        elif self.FILE_DUMP == 1:
            self.xoppy_write_h5file(calculated_data)
        elif self.FILE_DUMP == 2:
            self.xoppy_write_txt(calculated_data, method="3columns")
        elif self.FILE_DUMP == 3:
            self.xoppy_write_txt(calculated_data, method="matrix")

        return calculated_data