Example #1
0
def e2pz(w1,w2,th):
	"""
	Calculates the momentum scale and the relativistic Compton cross section 
	correction according to P. Holm, PRA 37, 3706 (1988).
	from KH 29.05.96
	input:
	w1 = incident energy  [keV]
	w2 = scattered energy [keV]
	th = scattering angle [deg]
	returns:
	pz = momentum scale   [a.u.]
	cf = cross section correction factor such that:
	J(pz) = cf * d^2(sigma)/d(w2)*d(Omega) [barn/atom/keV/srad]
	"""
	w1  = np.array(w1)    # make sure arrays are used
	w2  = np.array(w2)           
	m   = constants.value('electron mass energy equivalent in MeV')*1e3 #511.003      # Mass in natural units
	th  = math.radians(th) # th/180.0*np.pi  # Angle to radians
	alp = constants.value('fine-structure constant') #1.0/137.036  # Fine structure constant
	r0  = constants.value('classical electron radius') #2.8179e-15   # Electron radius
	q   = np.sqrt(w1**2 + w2**2-2*w1*w2*np.cos(th))                        # Momentum transfer    
	pz  = q/2.0 - (w1-w2) * np.sqrt(1/4.0 + m**2/(2*w1*w2*(1-np.cos(th)))) # In natural units
	E   = np.sqrt(m**2+pz**2)
	A   = ((w1-w2)*E-w1*w2*(1-np.cos(th)))/q
	D   = (w1-w2*np.cos(th))*A/q
	R   = w1*(E-D)
	R2  = R-w1*w2*(1-np.cos(th))
	chi = R/R2 + R2/R + 2.0*m**2 * (1/R-1/R2) + m**4 * (1/R-1/R2)**2
	cf  = 2.0*w1*q*E/(m**2*r0**2*w2*chi)
	cf  = cf*(1e-28*(m*alp))			                             # Cross section now in barns/atom/keV/srad
	pz  = pz/(m*alp)                                                 # pz to atomic units (a.u.)
	return pz, cf
Example #2
0
 def showPONI(self,event=None):
     if self.ai is None:
         print(' xxxxx NO CALIBRATION INFORMATION TO PRINT xxxxx ')
     else:
         print
         print
         print ' ====== CURRENT CALIBRATION INFORMATION ====== '
         print
         try:
             print 'Detector name: %s' % self.ai.detector.name
             #ai.detector.splineFile
         except:
             pass
         prt_str = 'Detector distance: %.1f mm'
         print prt_str % (self.ai._dist*1000.)
         prt_str = 'Pixel size (x,y): %.1f um, %.1f um'
         print prt_str % (self.ai.detector.pixel1*1000000.,
                          self.ai.detector.pixel2*1000000.)
         prt_str = 'Detector center (x,y): %i pixels, %i pixels'
         print prt_str % (self.ai._poni1/self.ai.detector.pixel1,
                          self.ai._poni2/self.ai.detector.pixel2)
         prt_str = 'Detector tilts: %0.5f, %0.5f %0.5f'
         print prt_str % (self.ai._rot1,self.ai._rot2,self.ai._rot3)
         prt_str = 'Incident energy, wavelegth: %0.2f keV, %0.4f A'
         hc = constants.value(u'Planck constant in eV s') * \
                 constants.value(u'speed of light in vacuum') * 1e-3 ## units: keV-m
         E = hc/(self.ai._wavelength) ## units: keV
         print prt_str % (E,self.ai._wavelength*1.e10)
Example #3
0
File: nrc.py Project: almadelia/nrc
def electrostatic_units(energy):
    """ coefficient to convert to appropriate electrostatic units """
    area = (1 / ((2 * sqrt(2)) ** 2)) * 2 * sqrt(3)
    factor = (1j * ((2 *
              constants.value("Rydberg constant times hc in eV")) ** 5) *
              1e-5 * 2.08e-15 *
            ((constants.value("lattice parameter of silicon") / 1e-10) ** 3))\
              / (area * ((energy) ** 3))
    return factor
Example #4
0
    def loadCIF(self,event):
    
        wildcards = 'XRD cifile (*.cif)|*.cif|All files (*.*)|*.*'
        dlg = wx.FileDialog(self, message='Choose CIF',
                           defaultDir=os.getcwd(),
                           wildcard=wildcards, style=wx.FD_OPEN)

        path, read = None, False
        if dlg.ShowModal() == wx.ID_OK:
            read = True
            path = dlg.GetPath().replace('\\', '/')
        dlg.Destroy()
        
        if read:
            cifile = os.path.split(path)[-1]

            try:
                cif = xu.materials.Crystal.fromCIF(path)
            except:
                print('incorrect file format: %s' % os.path.split(path)[-1])
                return

            ## generate hkl list
            hkllist = []
            maxhkl = 8
            for i in range(-maxhkl,maxhkl+1):
                for j in range(-maxhkl,maxhkl+1):
                    for k in range(-maxhkl,maxhkl+1):
                        if i+j+k > 0: # as long as h,k,l all positive, eliminates 0,0,0
                            hkllist.append([i,j,k])
            
            hc = constants.value(u'Planck constant in eV s') * \
                       constants.value(u'speed of light in vacuum') * 1e-3 ## units: keV-m

            if self.wavelength is not None:
                qlist = cif.Q(hkllist)
                Flist = cif.StructureFactorForQ(qlist,(hc/(self.wavelength*(1e-10))*1e3))
            
                Fall = []
                qall = []
                hklall = []
                for i,hkl in enumerate(hkllist):
                    if np.abs(Flist[i]) > 0.01:
                        Fadd = np.abs(Flist[i])
                        qadd = np.linalg.norm(qlist[i])
                        if qadd not in qall and qadd < 6:
                            Fall.extend((0,Fadd,0))
                            qall.extend((qadd,qadd,qadd))
                if np.shape(Fall)[0] > 0:
                    Fall = np.array(Fall)
                    qall = np.array(qall)
                    self.add1Ddata(qall,Fall,name=os.path.split(path)[-1],cif=True)
                else:
                    print('Could not calculate real structure factors.')
            else:
                print('Wavelength/energy must be specified for structure factor calculations.')
Example #5
0
 def onEorLSel(self,event): 
     hc = constants.value(u'Planck constant in eV s') * \
                    constants.value(u'speed of light in vacuum') * 1e-3 ## units: keV-m
     if self.ch_EorL.GetSelection() == 1:
         energy = float(self.entr_EorL.GetValue()) ## units keV
         wavelength = hc/(energy)*1e10 ## units: A
         self.entr_EorL.SetValue(str(wavelength))
     else:
         wavelength = float(self.entr_EorL.GetValue())*1e-10 ## units: m
         energy = hc/(wavelength) ## units: keV
         self.entr_EorL.SetValue(str(energy))
Example #6
0
 def __init__(self, frep_MHz = None, n = None):
     if frep_MHz is not None:
         self._frep_MHz = frep_MHz
         if frep_MHz > 1.0e6:
             warnings.warn("frep should be specified in MHz; large value given.")
     if n is not None:
         self.set_NPTS(n)            
     # Constants, moved here so that module runs through Sphynx autodoc when
     # scipy is Mocked out.
     self._c_nmps = constants.value('speed of light in vacuum')*1e9/1e12 # c in nm/ps
     self._c_mks  = constants.value('speed of light in vacuum') # m/s        
Example #7
0
    def __init__(self):
    
        ## Constructor
        dialog = wx.Dialog.__init__(self, None, title='Define wavelength/energy')#,size=(500, 440))
        ## remember: size=(width,height)
        
        panel = wx.Panel(self)
        
        main = wx.BoxSizer(wx.VERTICAL)
        hmain1 = wx.BoxSizer(wx.HORIZONTAL)
        
        #####
        ## Energy or Wavelength
        hmain1 = wx.BoxSizer(wx.HORIZONTAL)
        self.ch_EorL = wx.Choice(panel,choices=['Energy (keV)','Wavelength (A)'])
        self.entr_EorL = wx.TextCtrl(panel)#, size=(110, -1))
 
        self.ch_EorL.Bind(wx.EVT_CHOICE, self.onEorLSel)
 
        hmain1.Add(self.ch_EorL,   flag=wx.RIGHT,  border=8)
        hmain1.Add(self.entr_EorL, flag=wx.RIGHT,  border=8)
        
        #####
        ## OKAY!
        hmain2 = wx.BoxSizer(wx.HORIZONTAL)
        #hlpBtn = wx.Button(panel, wx.ID_HELP    )
        okBtn  = wx.Button(panel, wx.ID_OK      )
        canBtn = wx.Button(panel, wx.ID_CANCEL  )

        #hmain2.Add(hlpBtn,flag=wx.RIGHT,  border=8)
        hmain2.Add(canBtn, flag=wx.RIGHT, border=8) 
        hmain2.Add(okBtn,  flag=wx.RIGHT,  border=8)

        main.Add(hmain1, flag=wx.ALL, border=10) 
        main.Add(hmain2, flag=wx.ALL|wx.ALIGN_RIGHT, border=10) 

        panel.SetSizer(main)

        self.Show()
        ix,iy = panel.GetBestSize()
        self.SetSize((ix+20, iy+20))
        
        ## set default
        self.hc = constants.value(u'Planck constant in eV s') * \
                       constants.value(u'speed of light in vacuum') * 1e-3 ## units: keV-m
        self.energy = 19.0        
        self.wavelength = self.hc/(self.energy)*1e10 ## units: A
        self.ch_EorL.SetSelection(0)
        self.entr_EorL.SetValue(str(self.energy))
Example #8
0
def convert():
    """ converts xyz file from angstroms to bohrs """
    conversion_factor = constants.angstrom / constants.value("Bohr radius")
    xx_coord, yy_coord, zz_coord = genfromtxt(XYZ_CONVERT, unpack="True")
    xyz = column_stack((xx_coord, yy_coord, zz_coord))
    new_xyz = xyz * 1/conversion_factor
    savetxt(XYZ_CONVERT_OUT, new_xyz, fmt=('%3.15f'), delimiter=' ')
Example #9
0
    def get_electron_density(self):
        r"""
        Return electron density :math:`\rho_e` in unit inverse cubic meter

        .. math::

          \rho_e = \frac{\rho_m \cdot \sum_i}{\left( \sum_i c_i m_i \right) \left( \sum_i c_i Z_i \right)}

        :math:`\rho_m`: Mass denisty of material

        :math:`c_i`: Normalised fraction of atom species :math:`i`

        :math:`m_i`: Standard atomic mass of atom species :math:`i` 
      
        :math:`Z_i`: Atomic number of atom species :math:`i`
        """
        u = constants.value("atomic mass constant")

        atomic_composition = self.get_atomic_composition(normed=True)

        M = 0
        Q = 0
        for element in atomic_composition.keys():
            # sum up electrons
            M += atomic_composition[element]*get_atomic_mass(element)*u
            Q += atomic_composition[element]*get_atomic_number(element)

        electron_density = Q*self.massdensity/M
        
        return electron_density
Example #10
0
    def get_scatterer_density(self):
        r"""
        Return total atom density :math:`\rho` in unit inverse cubic meter

        .. math::

          \rho = \frac{\rho_m}{\sum_i c_i m_i}
        
        :math:`\rho_m`: Mass denisty of material

        :math:`c_i`: Normalised fraction of atom species :math:`i`

        :math:`m_i`: Standard atomic mass of atom species :math:`i`       
        """
                
        u = constants.value("atomic mass constant")

        atomic_composition = self.get_atomic_composition(normed=True)

        M = 0
        for element in atomic_composition.keys():
            # sum up average mass
            M += atomic_composition[element]*get_atomic_mass(element)*u

        number_density = self.massdensity/M
        
        return number_density
Example #11
0
    def get_n(self,photon_wavelength):
        r"""
        Return complex refractive index at a given wavelength (Henke, 1994)

        .. math::

          n = 1 - \frac{ r_0 }{ 2\pi } \lambda^2 \sum_i \rho_i f_i(0)
        
        :math:`r_0`: classical electron radius

        :math:`\rho_q`: atomic number density of atom species :math:`i`

        :math:`f_q(0)`: atomic scattering factor (forward scattering) of atom species :math:`i`

        Args:
          :photon_wavelength (float): Photon wavelength in unit meter
        """
        f = self.get_f(photon_wavelength)
        scatterer_density = self.get_scatterer_density()
        
        r_0 = constants.value("classical electron radius")

        n = 1 - r_0/2/numpy.pi * photon_wavelength**2 * f * scatterer_density

        return n
Example #12
0
 def __init__(self,Ts,qE0T,phis,lamb,length=22.e-3):
     self.Ts       = Ts
     self.Tsf      = Ts     # final kin. energy
     self.qE0T     = qE0T
     self.phis     = phis   # rad
     self.lamb     = lamb
     self.length   = length
     self.nbslices = 10     # nbof slices
     dl            = length/self.nbslices
     m0c2          = C.value('proton mass energy equivalent in MeV')  # MeV
     g             = 1.+Ts/m0c2   # Lorentz gamma
     bg            = sqrt(g**2-1.)
     beta          = bg/g         # Lorentz beta
     # phases,energies & maps of slices
     phases    = []
     dtks      = []
     self.maps = []
     for i in range(self.nbslices+1):
         phase = self.phis+2*pi/(beta*lamb)*(i*dl-self.length/2.)
         phases.append(phase)
         dtk = qE0T*dl*cos(phase)
         dtks.append(dtk)
     for i in range(self.nbslices):
         dgdp,f,pot,ham = Hamiltonian(self.Tsf,qE0T,phases[i],lamb)
         self.maps.append(Order3Map(+dl,dgdp,f))
         self.Tsf += dtks[i]
     self.Tsf -= dtks[i]     # one too much
Example #13
0
def Hamiltonian(Ts,qE0T,phis,lamb):       
    """ 
        kanonische Koordinaten: p (aka w), x (aka phi)
        unabhaegige Variable: t (aka s)
        Hamiltonian H(p,x,t) = g(p) + V(x,t)
        g = A*p**2/2
        V = B*(sin(x)-x*cos(phis))
        f = -dV/dx = -B*(cos(x)-cos(phis))
        dgdp = dH/dp = A*p
    """
    # closure
    m0c2 = C.value('proton mass energy equivalent in MeV')  # MeV
    g    = 1+Ts/m0c2
    bgs  = sqrt(g**2-1.)
    A    = 2.*pi/bgs**3/lamb
    B    = qE0T/m0c2
    # potential
    def V(x,B=B,phis=phis):
        return B*(sin(x)-x*cos(phis))
    # hamiltonian
    def H(p,x,B=B,phis=phis):
        return A*p**2+V(x)
    # dH/dp
    def dgdp(p,A=A):
        return A*p
    # -dV/dx
    def f(x,t,B=B,phis=phis):
        return -B*(cos(x)-cos(phis))

    return dgdp,f,V,H
Example #14
0
def freq_units(units):
    """
    Returns conversion factor from THz to the requred units and the label in the form of a namedtuple
    Accepted values: thz, ev, mev, ha, cm-1, cm^-1
    """

    d = {"thz": FreqUnits(1, "THz"),
         "ev": FreqUnits(const.value("hertz-electron volt relationship") * const.tera, "eV"),
         "mev": FreqUnits(const.value("hertz-electron volt relationship") * const.tera / const.milli, "meV"),
         "ha": FreqUnits(const.value("hertz-hartree relationship") * const.tera, "Ha"),
         "cm-1": FreqUnits(const.value("hertz-inverse meter relationship") * const.tera * const.centi, "cm^{-1}"),
         'cm^-1': FreqUnits(const.value("hertz-inverse meter relationship") * const.tera * const.centi, "cm^{-1}")
         }
    try:
        return d[units.lower().strip()]
    except KeyError:
        raise KeyError('Value for units `{}` unknown\nPossible values are:\n {}'.format(units, list(d.keys())))
Example #15
0
def water_term_pol(B0, T):
    gamma = constants.value('proton gyromag. ratio')
    hbar = constants.hbar
    k = constants.k

    larmor_w = gamma * B0
    pol = hbar * larmor_w
    pol /= (2 * k * T)
    return pol
Example #16
0
    def _read_funcfl_file(self):
        rphi = np.sqrt(27.2*0.529)
        eV2J = spc.value('electron volt')

        print('Reading EAM potential in single-element (funcfl) format')
        f = open(self.filename, 'r')

        line = f.readline()  # comment line
        self.atomic_number = int(f.readline().split()[0])

        line = f.readline().split()
        self.nrho    =   int(line[0]) 
        self.drho    = float(line[1])
        self.nr      =   int(line[2])
        self.dr      = float(line[3])
        self.cutoff  = float(line[4])

        self.fembed  = np.zeros((self.nrho,2))
        self.effchg  = np.zeros((self.nr,2))
        self.fdens   = np.zeros((self.nr,2))

        # read embedding functional
        line    = f.readline().split()
        n_col   = len(line)
        n_lines = int(self.nrho/self.ncol)-1

        i_rows = 0
        while i_rows < self.nrho:
            for val in line:
                self.fembed[i_rows,0] = i_rows*self.drho
                self.fembed[i_rows,1] = float(val)
                i_rows += 1
                if i_rows >= self.nrho: 
                    break
            line=f.readline().split()
        
        # read charge function
        i_rows = 0
        while i_rows < self.nr:
            for val in line:
                self.effchg[i_rows,0]=i_rows*self.dr
                self.effchg[i_rows,1]=float(val)*rphi/(1.e-30+self.effchg[self.i_rows,0])
                i_rows += 1
                if i_rows >= self.nr: 
                    break
            line=f.readline().split()

        # read density function
        i_rows = 0
        while i_rows < self.nr:
            for val in line:
                self.fdens[i_rows,0]=i_rows*self.dr
                self.fdens[i_rows,1]=float(val)
                i_rows += 1
                if i_rows >= self.nr:
                    break
            line=f.readline().split()
Example #17
0
 def rotational_constants(self, units='ghz'):
     """Compute the rotational constants in 1/cm or GHz."""
     choices = ('invcm', 'ghz')
     units = units.lower()
     if units not in choices:
         raise ValueError("Invalid units, pick one of {}".format(choices))
     principal_moments = self.principal_moments_of_inertia()[0]
     _check_scipy(_found_scipy)
     bohr2ang = spc.value('atomic unit of length') / spc.angstrom
     xfamu = 1 / spc.value('electron mass in u')
     xthz = spc.value('hartree-hertz relationship')
     rotghz = xthz * (bohr2ang ** 2) / (2 * xfamu * spc.giga)
     if units == 'ghz':
         conv = rotghz
     if units == 'invcm':
         ghz2invcm = spc.giga * spc.centi / spc.c
         conv = rotghz * ghz2invcm
     return conv / principal_moments
Example #18
0
    def __init__(self, N=DEFAULT_N):
        """
        Parameters
        ----------
        N : int
            the number of grid points, it should be a power of 2

        Examples
        --------
        >>> from generic_potential import GenericPotential
        >>> device = GenericPotential(1024)
        """

        # default grid size
        self.N = N
        self.hN = int(self.N/2) # half grid
        self.points_before = int(self.N/2)
        self.points_after = int(self.N/2)

        # useful atomic unities
        self.au_l    = cte.value('atomic unit of length')
        self.au_t    = cte.value('atomic unit of time')
        self.au_e    = cte.value('atomic unit of energy')
        self.au_v    = cte.value('atomic unit of electric potential')
        self.hbar_au = 1.0
        self.me_au   = 1.0

        # other useful constants
        self.ev = cte.value('electron volt')
        self.c  = cte.value('speed of light in vacuum') # m/s
        self.me = cte.value('electron mass')
        self.q  = cte.value('elementary charge')

        # relations of interest
        self.au2ev  = self.au_e / self.ev
        self.au2ang = self.au_l / 1e-10

        # specific for default quantum harmonic oscillator
        self.l     = 0.0000081 # m
        self.f     = self.c / self.l # Hz
        self.w     = 2.0 * np.pi * self.f
        self.z_m   = np.linspace(-5e-9,5e-9, self.N)
        self.v_j   = 0.5 * self.me * self.z_m**2 * self.w**2
        self.z_nm  = self.z_m / 1e-9
        self.v_ev  = self.v_j / self.ev
        self.m_eff = np.ones(self.z_nm.size)

        # set default time increment
        self._set_dt()

        # adjust grid
        self.normalize_device()
Example #19
0
 def principal_moments_of_inertia(self, units='amu_bohr_2'):
     """Return the principal moments of inertia in 3 kinds of units:
     1. [amu][bohr]^2
     2. [amu][angstrom]^2
     3. [g][cm]^2
     and the principal axes.
     """
     choices = ('amu_bohr_2', 'amu_angstrom_2', 'g_cm_2')
     units = units.lower()
     if units not in choices:
         raise ValueError("Invalid units, pick one of {}".format(choices))
     moi_tensor = self.moment_of_inertia_tensor()
     principal_moments, principal_axes = np.linalg.eigh(moi_tensor)
     if units == 'amu_bohr_2':
         conv = 1
     if units == 'amu_angstrom_2':
         _check_scipy(_found_scipy)
         bohr2ang = spc.value('atomic unit of length') / spc.angstrom
         conv = bohr2ang ** 2
     if units == 'g_cm_2':
         _check_scipy(_found_scipy)
         amu2g = spc.value('unified atomic mass unit') * spc.kilo
         conv = amu2g * (spc.value('atomic unit of length') * spc.centi) ** 2
     return conv * principal_moments, principal_axes
Example #20
0
    def onLoadCIF(self, event=None):

        wildcards = 'CIF file (*.cif)|*.cif|All files (*.*)|*.*'
        dlg = wx.FileDialog(self, message='Choose CIF file',
                           defaultDir=os.getcwd(),
                           wildcard=wildcards, style=wx.FD_OPEN)

        path, read = None, False
        if dlg.ShowModal() == wx.ID_OK:
            read = True
            path = dlg.GetPath().replace('\\', '/')
        dlg.Destroy()

        if read:
            cry_strc = struc_from_cif(path)

            if cry_strc:
                hc = constants.value(u'Planck constant in eV s') * \
                         constants.value(u'speed of light in vacuum') * 1e-3 ## units: keV-m
                energy = hc/(self.xrd.wavelength) ## units: keV
                q,F = calc_all_F(cry_strc,energy,maxhkl=10,qmax=5)

                #self.plot1Dxrd(xrddata, show_xrd2=True)
                print('Values are calculated; plotting not yet implemented.')
Example #21
0
def test1(Ts,qE0T,phis,lamb):
    print("----------------------Test 1--------------")
    # prep plot
    m0c2   = C.value('proton mass energy equivalent in MeV')  # MeV
    phimin = radians(-60.)
    phimax = -phimin
    # dphi = (phimax-phimin)/20.
    wmin = -0.05/m0c2
    wmax = +0.05/m0c2
    # dw = (wmax-wmin)/20.
    pou    = []
    pin    = []
    nbprtcls  = 5000
    nbgaps    = 40
    # loop particles
    for j in range(nbprtcls):
        # x0 = phi0 = rn.uniform(phimin,phimax)
        # p0 = w0   = rn.uniform(wmin,wmax)
        x0 = phi0 = rn.gauss(phis,2*phis)
        p0 = w0   = rn.gauss(0,2*wmax)
        t0 = 0
        v = (p0,x0,t0)
        pin.append(v)
        gap  = Gap(Ts,qE0T,phis,lamb)
        # loop gaps
        for i in range(nbgaps):
            v = gap.map(v)
            # increase particle impulse for next gap
            gap(gap.Tsf)
        pou.append(v)
    print("Ts {}".format(gap.Tsf))
 
    # plot results
    win   = [x[0]*m0c2     for x in pin]
    phin  = [degrees(x[1]) for x in pin]
    wf    = [x[0]*m0c2     for x in pou]
    phif  = [degrees(x[1]) for x in pou]
 
    ax1   = plt.subplot(121)
    plt.xlim([-100,200])
    plt.ylim([-0.4,1.2])
    ax1.autoscale(enable=False)
    ax1.scatter(phin,win,s=1,c='r')

    ax2   = plt.subplot(122,sharex=ax1,sharey=ax1)
    ax2.autoscale(enable=False)
    ax2.scatter(phif,wf,s=1,c='r')
    plt.show()
    def axis_conversion(self, data, unit, name):
        # Converts the x-axis units to a format Mantid accepts,
        # frequency to wavenumber, time to time of flight

        logger.debug('Axis for conversion: name={0}, unit={1}'.format(name, unit))
        if name == 'frequency' and unit == 'THz':
            logger.information('Axis {0} will be converted to wave number in cm^-1'.format(name))
            unit = 'Energy_inWavenumber'
            data *= sc.tera
            data *= sc.value('Planck constant in eV s')
            data *= 8065.54
        elif name == 'time' and unit == 'ps':
            logger.information('Axis {0} will be converted to time in microsecond'.format(name))
            unit = 'TOF'
            data *= sc.micro
        else:
            unit = 'Empty'
        return (data, unit, name)
Example #23
0
def test0(Ts,qE0T,phis,lamb):
    print("----------------------Test 0--------------")
    m0c2 = C.value('proton mass energy equivalent in MeV')  # MeV
    dgdp,dfdx,pot,ham  = Hamiltonian(Ts,qE0T,phis,lamb)
    dt = 1.e-2
    map3p = Order3Map(+dt,dgdp,dfdx)
    map3m = Order3Map(-dt,dgdp,dfdx)

    ax = plt.subplot()
    phimin = 1.5*phis
    phimax = -phis
    dphi = (phimax-phimin)/20.
    phi0 = phimin

    wmin = -0.05/m0c2
    wmax = +0.05/m0c2
    dw = (wmax-wmin)/20.
    w0 = wmin
    # while phi0 <= phimax:
    for i in range(50):
        # phi0 = rn.gauss(degrees(phis),1.*degrees(abs(phis)))
        phi0 = rn.uniform(phimin,phimax)
        w0   = rn.uniform(wmin,wmax)

        t0 = 0.
        p0 = w0
        x0 = phi0
        vp = (p0,x0,t0)
        vm = (p0,x0,t0)
        pou = [vp]
        for step in range(300):
            vp = map3p.map(vp)
            vm = map3m.map(vm)
            pou.append(vp)
            pou.append(vm)
        # phi0 += dphi
        w   = [x[0]*m0c2     for x in pou]
        phi = [degrees(x[1]) for x in pou]
        plt.xlim([-60,60])
        plt.ylim([-0.1,0.1])
        plt.autoscale(enable=False,axis='both')
        ax.scatter(phi,w,s=1,c='r')
    plt.show()
Example #24
0
    def _axis_conversion(self, data, unit, name):
        """
        Converts an axis to a Mantid axis type (possibly performing a unit
        conversion).

        @param data The axis data as Numpy array
        @param unit The axis unit as read from the file
        @param name The axis name as read from the file
        @return Tuple containing updated axis details
        """
        logger.debug('Axis for conversion: name={0}, unit={1}'.format(name, unit))

        # Q (nm**-1) to Q (Angstrom**-1)
        if name.lower() == 'q' and unit.lower() == 'inv_nm':
            logger.information('Axis {0} will be converted to Q in Angstrom**-1'.format(name))
            unit = 'MomentumTransfer'
            data /= sc.nano # nm to m
            data *= sc.angstrom # m to Angstrom

        # Frequency (THz) to Energy (meV)
        elif name.lower() == 'frequency' and unit.lower() == 'thz':
            logger.information('Axis {0} will be converted to energy in meV'.format(name))
            unit = 'Energy'
            data *= sc.tera # THz to Hz
            data *= sc.value('Planck constant in eV s') # Hz to eV
            data /= sc.milli # eV to meV

        # Time (ps) to TOF (s)
        elif name.lower() == 'time' and unit.lower() == 'ps':
            logger.information('Axis {0} will be converted to time in microsecond'.format(name))
            unit = 'TOF'
            data *= sc.micro # ps to us

        # No conversion
        else:
            unit = 'Empty'

        return (data, unit, name)
Example #25
0
def disorder():
    """ extracts selected rows from input, converts to matrix,
    disorders, and returns matrix which is written to file """
    count = 1
    chosen = [x - 1 for x in ATOMS_DISORDERED]
    blbohr = BOND_LENGTH * constants.angstrom / constants.value("Bohr radius")
    xyz = loadtxt(XYZ_DISORDER)
    data = xyz[chosen]
    new_xyz = xyz.copy()
    final = zip(data, DISORDER_AMOUNT)
    while count <= REPEAT:
        for atom in range(0, len(final)):
            polar = random() * constants.pi
            azimuthal = 2 * polar
            new_xyz[chosen[atom], 0] = final[atom][0][0] + (final[atom][1] *
                    (blbohr / 2) * sin(polar) * cos(azimuthal))
            new_xyz[chosen[atom], 1] = final[atom][0][1] + (final[atom][1] *
                    (blbohr / 2) * sin(polar) * sin(azimuthal))
            new_xyz[chosen[atom], 2] = final[atom][0][2] + (final[atom][1] *
                    (blbohr / 2) * cos(polar))
            out = "data/disorder/si_h_14_" + str(count).zfill(3) + ".xyz"
            savetxt(out, new_xyz, fmt=('%5.14e'), delimiter='\t')
        count += 1
Example #26
0
    def get_f(self, photon_wavelength):
        r"""
        Get effective average complex scattering factor for forward scattering at a given photon wavlength from Henke tables

        Args:
              :photon_wavlength (float): Photon wavelength in unit meter
        """
    
        atomic_composition = self.get_atomic_composition(normed=True)

        r_0 = constants.value("classical electron radius")
        h   =  constants.h
        c   =  constants.c
        qe   = constants.e
        photon_energy_eV = h*c/photon_wavelength/qe
        
        f_sum = complex(0.,0.)
        for element in atomic_composition.keys():
            # sum up average atom factor
            f = get_f_element(element,photon_energy_eV)
            f_sum += atomic_composition[element] * f
        
        return f_sum
Example #27
0
    def get_photoabsorption_cross_section(self, photon_wavelength):
        r"""
        Return the photoabsorption cross section :math:`\mu_a` at a given wavelength :math:`\lambda`

        .. math::
        
          \mu_a = 2 r_0 \lambda f_2

        :math:`r_0`: classical electron radius

        :math:`f_2`: imaginary part of the atomic scattering factor     

        Args:
          :photon_wavelength (float): Photon wavelength in unit meter
        """        
        r_0 = constants.value("classical electron radius")
        h =  constants.h
        c =  constants.c
        qe = constants.e

        mu = 2*r_0*photon_wavelength*self.get_f(photon_wavelength).imag

        return mu
Example #28
0
def parallel_band_conductivity(frequency, plane, a, m0, k_fermi, U, tau):
    """
    Return the contribution to the optical conductivity resulting from
    parallel-band absorption in a certain plane.
    @frequency: frequency in Hz
    @plane: a CrystalPlane instance
    @a: lattice constant in m
    @m0: mass ratio
    @k_fermi: fermi wave vector in 1/m
    @U: crystal plane pseudopotential in J
    @tau: parallel-band relaxation time in s
    """
    K = plane.magnitude_factor / a

    energy_low, energy_high = pb_absorption_energy_range(plane, a, m0, k_fermi, U)
    energy = Const.hbar * frequency
    damping_energy = Const.hbar / tau

    z = energy / energy_low
    z0 = energy_high / energy_low
    t0 = N.sqrt(z0 ** 2 - 1.0)

    # "To obtain the total absorption corresponding to the entire first zone
    # we simply weight these results by the appropriate number of planes
    # bounding the zone."
    factor = plane.multiplicity * sigma_a * Const.value('Bohr radius') * K

    b = damping_energy / energy_low
    rho = ((1 + b ** 2 - z ** 2) ** 2 + (2 * b * z) ** 2) ** 0.25
    phi1 = 0.5 * (0.5 * N.pi + N.arctan2(1 + b ** 2 - z ** 2, 2 * b * z))
    phi2 = 0.5 * (0.5 * N.pi - N.arctan2(1 + b ** 2 - z ** 2, 2 * b * z))
    realpart = (((z / rho) / (z ** 2 + b ** 2))
        * horrible_function(z, b, t0, rho, phi2))
    imagpart = imaginary_horrible_function(z, b, t0, rho, phi1, phi2)

    return factor * (realpart - 1j * imagpart)
Example #29
0
class CherenkovYield(gc):
    '''A class for calculating the Cherenkov yield of an upward going air shower
    '''
    c = value('speed of light in vacuum')
    hc = value('Planck constant in eV s') * c
    gga = CherenkovPhotonArray('gg_t_delta_theta_2020_normalized.npz')

    def __init__(self, X_max, N_max, h0, theta, direction, tel_vectors, min_l,
                 max_l):
        super().__init__(X_max, N_max, h0, theta, direction, tel_vectors)
        self.tel_dE = self.hc / (min_l * nano) - self.hc / (max_l * nano)
        self.ng, self.ng_sum, self.gg = self.calculate_ng(
            self.shower_t, self.shower_delta, self.tel_q, self.shower_nch,
            self.shower_dr, self.tel_omega, self.tel_dE)
        self.axis_time = self.shower_r / self.c / nano
        self.delay_prime = self.calculate_delay()
        self.delay = self.calculate_vertical_delay(
            self.axis_delta, self.axis_dh)[self.i_ch] / self.cQ
        self.counter_time = self.axis_time + self.travel_length / self.c / nano + self.delay
        self.counter_time_prime = self.axis_time + self.travel_length / self.c / nano + self.delay_prime

    def interpolate_gg(self, t, delta, theta):
        '''This funtion returns the interpolated values of gg at a given delta
        and theta
        parameters:
        t: single value of the stage
        delta: single value of the delta
        theta: array of theta values at which we want to return the angular
        distribution

        returns:
        the angular distribution values at the desired thetas
        '''

        gg_td = self.gga.angular_distribution(t, delta)
        return np.interp(theta, self.gga.theta, gg_td)

    def calculate_gg(self, t, delta, theta):
        '''This funtion returns the interpolated values of gg at a given deltas
        and thetas
        parameters:
        t: array of stages
        delta: array of corresponding deltas
        theta: array of theta values at each stage

        returns:
        the angular distribution values at the desired thetas
        '''
        gg = np.empty_like(theta)
        for i in range(theta.shape[1]):
            gg_td = self.gga.angular_distribution(t[i], delta[i])
            gg[:, i] = np.interp(theta[:, i], self.gga.theta, gg_td)
        return gg

    def calculate_yield(self, delta, shower_nch, shower_dr, tel_dE):
        ''' This function returns the total number of Cherenkov photons emitted
        at a given stage of a shower per all solid angle.

        Parameters:
        delta: single value or array of the differences from unity of the index of
        refraction (n-1)
        shower_nch: single value or array of the number of charged particles.
        shower_dr: single value or array, the spatial distance represented by
        the given stage
        lw: the wavelength of the lower bound of the Cherenkov energy interval
        hw: the wavelength of the higher bound of the Cherenkov energy interval

        returns: the total number of photons per all solid angle
        '''

        alpha_over_hbarc = 370.e2  # per eV per m, from PDG
        c = value('speed of light in vacuum')
        hc = value('Planck constant in eV s') * c
        chq = CherenkovPhoton.cherenkov_angle(1.e12, delta)
        cy = alpha_over_hbarc * np.sin(chq)**2 * tel_dE
        return shower_nch * shower_dr * cy

    def calculate_ng(self, t, delta, theta, shower_nch, shower_dr, omega,
                     tel_dE):
        gg = self.calculate_gg(t, delta, theta)
        ng = gg * omega * self.calculate_yield(delta, shower_nch, shower_dr,
                                               tel_dE)
        return ng, ng.sum(axis=1), gg

    def calculate_vertical_delay(self, axis_delta, axis_dh):
        return np.cumsum((axis_delta * axis_dh)[::-1])[::-1] / self.c / nano

    def calculate_delay(self):
        delay = np.empty_like(self.cQ)
        i_min = np.min(self.i_ch)
        Q = np.arccos(self.cQ)
        for i in range(delay.shape[0]):
            for j in range(delay.shape[1]):
                cos = self.theta_normal(self.axis_h[i_min + j:-1], Q[i, j])
                delay[i, j] = np.sum((self.axis_delta[i_min + j:-1] *
                                      self.axis_dh[i_min + j:-1]) / cos)
        return delay / self.c / nano
Example #30
0
def t_K(t):
    eV_per_K = value('Boltzmann constant in eV/K')
    return t / eV_per_K
    file.close()

if __name__ == '__main__':
    # lattice
    lattice  = factory('yml/simuIN.yml')
    sections = lattice.get_sections()
    waccept(lattice.first_gap)
        
    # Parameters
    # The following parameters are hardcoded to a specific value.
    particles           = 3000
    tof_time_adjustment = 0 
    attenuation_factor  = 1.0
    c                   = C.c
    pi                  = C.pi    
    m0c2                = C.value('proton mass energy equivalent in MeV')
    t1                  = 0.83
    tp1                 = 4.9e-2
    tpp1                = 4.9e-3
    
    # Parameter import
    # Import all the parameters and convert them to the correct units apart from the accelerating 
    # and transport elements which are imported later on as thier parameters are not global.
    alphax    = PARAMS['alfax_i']
    betax     = PARAMS['betax_i']      # mm/mrad - DYNAC units
    emitx     = PARAMS['emitx_i']*1E06 # mm*mrad - DYNAC units
    alphay    = PARAMS['alfay_i']
    betay     = PARAMS['betay_i']
    emity     = PARAMS['emity_i']*1E06 # mm*mrad - DYNAC units
    emitw     = PARAMS['emitw']        # mm/mrad - DYNAC units
    rfphdeg   = PARAMS['phisoll']
Example #32
0
class ExcitingInput(MSONable):
    """
    Object for representing the data stored in the structure part of the
    exciting input.

    .. attribute:: structure

        Associated Structure.

    .. attribute:: title

        Optional title string.

    .. attribute:: lockxyz

        Lockxyz attribute for each site if available. A Nx3 array of
        booleans.
    """
    def __init__(self, structure, title=None, lockxyz=None):
        """
        Args:
            structure (Structure):  Structure object.
            title (str): Optional title for exciting input. Defaults to unit
                cell formula of structure. Defaults to None.
            lockxyz (Nx3 array): bool values for selective dynamics,
                where N is number of sites. Defaults to None.
        """

        if structure.is_ordered:
            site_properties = {}
            if lockxyz:
                site_properties["selective_dynamics"] = lockxyz
            self.structure = structure.copy(site_properties=site_properties)
            self.title = structure.formula if title is None else title
        else:
            raise ValueError("Structure with partial occupancies cannot be "
                             "converted into exciting input!")

    # define conversion factor between Bohr radius and Angstrom
    bohr2ang = const.value("Bohr radius") / const.value("Angstrom star")

    @property
    def lockxyz(self):
        """
        :return: Selective dynamics site properties.
        """
        return self.structure.site_properties.get("selective_dynamics")

    @lockxyz.setter
    def lockxyz(self, lockxyz):
        self.structure.add_site_property("selective_dynamics", lockxyz)

    @staticmethod
    def from_string(data):
        """
        Reads the exciting input from a string
        """

        root = ET.fromstring(data)
        speciesnode = root.find("structure").iter("species")
        elements = []
        positions = []
        vectors = []
        lockxyz = []
        # get title
        title_in = str(root.find("title").text)
        # Read elements and coordinates
        for nodes in speciesnode:
            symbol = nodes.get("speciesfile").split(".")[0]
            if len(symbol.split("_")) == 2:
                symbol = symbol.split("_")[0]
            if Element.is_valid_symbol(symbol):
                # Try to recognize the element symbol
                element = symbol
            else:
                raise ValueError("Unknown element!")
            for atom in nodes.iter("atom"):
                x, y, z = atom.get("coord").split()
                positions.append([float(x), float(y), float(z)])
                elements.append(element)
                # Obtain lockxyz for each atom
                if atom.get("lockxyz") is not None:
                    lxyz = []
                    for l in atom.get("lockxyz").split():
                        if l in ("True", "true"):
                            lxyz.append(True)
                        else:
                            lxyz.append(False)
                    lockxyz.append(lxyz)
                else:
                    lockxyz.append([False, False, False])
        # check the atomic positions type
        if "cartesian" in root.find("structure").attrib.keys():
            if root.find("structure").attrib["cartesian"]:
                cartesian = True
                for i, p in enumerate(positions):
                    for j in range(3):
                        p[j] = p[j] * ExcitingInput.bohr2ang
                print(positions)
        else:
            cartesian = False
        # get the scale attribute
        scale_in = root.find("structure").find("crystal").get("scale")
        if scale_in:
            scale = float(scale_in) * ExcitingInput.bohr2ang
        else:
            scale = ExcitingInput.bohr2ang
        # get the stretch attribute
        stretch_in = root.find("structure").find("crystal").get("stretch")
        if stretch_in:
            stretch = np.array([float(a) for a in stretch_in])
        else:
            stretch = np.array([1.0, 1.0, 1.0])
        # get basis vectors and scale them accordingly
        basisnode = root.find("structure").find("crystal").iter("basevect")
        for vect in basisnode:
            x, y, z = vect.text.split()
            vectors.append([
                float(x) * stretch[0] * scale,
                float(y) * stretch[1] * scale,
                float(z) * stretch[2] * scale,
            ])
        # create lattice and structure object
        lattice_in = Lattice(vectors)
        structure_in = Structure(lattice_in,
                                 elements,
                                 positions,
                                 coords_are_cartesian=cartesian)

        return ExcitingInput(structure_in, title_in, lockxyz)

    @staticmethod
    def from_file(filename):
        """
        :param filename: Filename
        :return: ExcitingInput
        """
        with zopen(filename, "rt") as f:
            data = f.read().replace("\n", "")
        return ExcitingInput.from_string(data)

    def write_etree(self,
                    celltype,
                    cartesian=False,
                    bandstr=False,
                    symprec=0.4,
                    angle_tolerance=5,
                    **kwargs):
        """
        Writes the exciting input parameters to an xml object.

        Args:
            celltype (str): Choice of unit cell. Can be either the unit cell
            from self.structure ("unchanged"), the conventional cell
            ("conventional"), or the primitive unit cell ("primitive").

            cartesian (bool): Whether the atomic positions are provided in
            Cartesian or unit-cell coordinates. Default is False.

            bandstr (bool): Whether the bandstructure path along the
            HighSymmKpath is included in the input file. Only supported if the
            celltype is set to "primitive". Default is False.

            symprec (float): Tolerance for the symmetry finding. Default is 0.4.

            angle_tolerance (float): Angle tolerance for the symmetry finding.
            Default is 5.

            **kwargs: Additional parameters for the input file.

        Returns:
            ET.Element containing the input XML structure
        """
        root = ET.Element("input")
        root.set(
            "{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation",
            "http://xml.exciting-code.org/excitinginput.xsd",
        )
        title = ET.SubElement(root, "title")
        title.text = self.title
        if cartesian:
            structure = ET.SubElement(root,
                                      "structure",
                                      cartesian="true",
                                      speciespath="./")
        else:
            structure = ET.SubElement(root, "structure", speciespath="./")

        crystal = ET.SubElement(structure, "crystal")
        # set scale such that lattice vector can be given in Angstrom
        ang2bohr = const.value("Angstrom star") / const.value("Bohr radius")
        crystal.set("scale", str(ang2bohr))
        # determine which structure to use
        finder = SpacegroupAnalyzer(self.structure,
                                    symprec=symprec,
                                    angle_tolerance=angle_tolerance)
        if celltype == "primitive":
            new_struct = finder.get_primitive_standard_structure(
                international_monoclinic=False)
        elif celltype == "conventional":
            new_struct = finder.get_conventional_standard_structure(
                international_monoclinic=False)
        elif celltype == "unchanged":
            new_struct = self.structure
        else:
            raise ValueError("Type of unit cell not recognized!")

        # write lattice
        basis = new_struct.lattice.matrix
        for i in range(3):
            basevect = ET.SubElement(crystal, "basevect")
            basevect.text = "%16.8f %16.8f %16.8f" % (
                basis[i][0],
                basis[i][1],
                basis[i][2],
            )
        # write atomic positions for each species
        index = 0
        for i in sorted(new_struct.types_of_species, key=lambda el: el.X):
            species = ET.SubElement(structure,
                                    "species",
                                    speciesfile=i.symbol + ".xml")
            sites = new_struct.indices_from_symbol(i.symbol)

            for j in sites:
                coord = "%16.8f %16.8f %16.8f" % (
                    new_struct[j].frac_coords[0],
                    new_struct[j].frac_coords[1],
                    new_struct[j].frac_coords[2],
                )
                # obtain cartesian coords from fractional ones if needed
                if cartesian:
                    coord2 = []
                    for k in range(3):
                        inter = (new_struct[j].frac_coords[k] * basis[0][k] +
                                 new_struct[j].frac_coords[k] * basis[1][k] +
                                 new_struct[j].frac_coords[k] *
                                 basis[2][k]) * ang2bohr
                        coord2.append(inter)
                    coord = "%16.8f %16.8f %16.8f" % (coord2[0], coord2[1],
                                                      coord2[2])

                # write atomic positions
                index = index + 1
                _ = ET.SubElement(species, "atom", coord=coord)
        # write bandstructure if needed
        if bandstr and celltype == "primitive":
            kpath = HighSymmKpath(new_struct,
                                  symprec=symprec,
                                  angle_tolerance=angle_tolerance)
            prop = ET.SubElement(root, "properties")
            bandstrct = ET.SubElement(prop, "bandstructure")
            for i in range(len(kpath.kpath["path"])):
                plot = ET.SubElement(bandstrct, "plot1d")
                path = ET.SubElement(plot, "path", steps="100")
                for j in range(len(kpath.kpath["path"][i])):
                    symbol = kpath.kpath["path"][i][j]
                    coords = kpath.kpath["kpoints"][symbol]
                    coord = "%16.8f %16.8f %16.8f" % (coords[0], coords[1],
                                                      coords[2])
                    if symbol == "\\Gamma":
                        symbol = "GAMMA"
                    _ = ET.SubElement(path, "point", coord=coord, label=symbol)
        elif bandstr and celltype != "primitive":
            raise ValueError("Bandstructure is only implemented for the \
                              standard primitive unit cell!")

        # write extra parameters from kwargs if provided
        self._dicttoxml(kwargs, root)

        return root

    def write_string(self,
                     celltype,
                     cartesian=False,
                     bandstr=False,
                     symprec=0.4,
                     angle_tolerance=5,
                     **kwargs):
        """
        Writes exciting input.xml as a string.

        Args:
            celltype (str): Choice of unit cell. Can be either the unit cell
            from self.structure ("unchanged"), the conventional cell
            ("conventional"), or the primitive unit cell ("primitive").

            cartesian (bool): Whether the atomic positions are provided in
            Cartesian or unit-cell coordinates. Default is False.

            bandstr (bool): Whether the bandstructure path along the
            HighSymmKpath is included in the input file. Only supported if the
            celltype is set to "primitive". Default is False.

            symprec (float): Tolerance for the symmetry finding. Default is 0.4.

            angle_tolerance (float): Angle tolerance for the symmetry finding.
            Default is 5.

            **kwargs: Additional parameters for the input file.

        Returns:
            String
        """
        try:
            root = self.write_etree(celltype, cartesian, bandstr, symprec,
                                    angle_tolerance, **kwargs)
            self._indent(root)
            # output should be a string not a bytes object
            string = ET.tostring(root).decode("UTF-8")
        except Exception:
            raise ValueError("Incorrect celltype!")
        return string

    def write_file(self,
                   celltype,
                   filename,
                   cartesian=False,
                   bandstr=False,
                   symprec=0.4,
                   angle_tolerance=5,
                   **kwargs):
        """
        Writes exciting input file.

        Args:
            celltype (str): Choice of unit cell. Can be either the unit cell
            from self.structure ("unchanged"), the conventional cell
            ("conventional"), or the primitive unit cell ("primitive").

            filename (str): Filename for exciting input.

            cartesian (bool): Whether the atomic positions are provided in
            Cartesian or unit-cell coordinates. Default is False.

            bandstr (bool): Whether the bandstructure path along the
            HighSymmKpath is included in the input file. Only supported if the
            celltype is set to "primitive". Default is False.

            symprec (float): Tolerance for the symmetry finding. Default is 0.4.

            angle_tolerance (float): Angle tolerance for the symmetry finding.
            Default is 5.

            **kwargs: Additional parameters for the input file.
        """
        try:
            root = self.write_etree(celltype, cartesian, bandstr, symprec,
                                    angle_tolerance, **kwargs)
            self._indent(root)
            tree = ET.ElementTree(root)
            tree.write(filename)
        except Exception:
            raise ValueError("Incorrect celltype!")

    # Missing PrettyPrint option in the current version of xml.etree.cElementTree
    @staticmethod
    def _indent(elem, level=0):
        """
        Helper method to indent elements.

        :param elem:
        :param level:
        :return:
        """
        i = "\n" + level * "  "
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "  "
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for el in elem:
                ExcitingInput._indent(el, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i

    def _dicttoxml(self, paramdict_, element):
        for key, value in paramdict_.items():
            if isinstance(value, str) and key == "text()":
                element.text = value
            elif isinstance(value, str):
                element.attrib[key] = value
            elif isinstance(value, list):
                for item in value:
                    self._dicttoxml(item, ET.SubElement(element, key))
            elif isinstance(value, dict):
                if element.findall(key) == []:
                    self._dicttoxml(value, ET.SubElement(element, key))
                else:
                    self._dicttoxml(value, element.findall(key)[0])
            else:
                print("cannot deal with", key, "=", value)
Example #33
0
def pressure_pPa(n, t):
    k = value('Boltzmann constant')
    assert unit('Boltzmann constant') == 'J K^-1'
    return k * n * t * (100**3) * (1e12)
Example #34
0
def test_exact_values():
    # Check that updating stored values with exact ones worked.
    for key in codata.exact_values:
        assert_((codata.exact_values[key][0] - value(key)) / value(key) == 0)
def C(s):
    return Q(constants.value(s), constants.unit(s))
 

import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as plt
import cmath 
import scipy.constants as const
from scipy import fftpack
import time as tti
import skfuzzy.membership as fuzzy


t0=tti.time()
pi=np.pi
aSi=0.6101*10**(-9)
a=aSi/const.value('Bohr radius')                            #Lattice constant in a.u.
a=1                                                         #Lattice constant in a.u.
p1=a/8                                                      #dimensioni della buca
p2=7*a/8                                                    #Boundary
V0=-0.15                                                     #potenziale normalizzato
N=12                                                       #numero vettori base
p=p2-p1                                                     #ampiezza della buca
kpoints=100                                                #numero punti nello spazio k
#ESW=((const.hbar**2)*(const.pi**2))/(2*const.m_e*(a**2))    #Infinite square well energy
lamb=3200*10**(-9)                                          #Laser Wavelenght
w=2*np.pi*const.c/lamb                                      #Laser pulsation
freqau=const.value('atomic unit of velocity')/const.value('Bohr radius')
wau=w/freqau
timeau=const.value('Bohr radius')/const.value('atomic unit of velocity')
T=16*np.pi/w
Td=16*np.pi/wau                                               #Pulse Duration in a.u.
Example #37
0
"""Derivation of variable `toz`."""

import cf_units
import iris
from scipy import constants

from ._baseclass import DerivedVariableBase
from ._shared import pressure_level_widths

# Constants
AVOGADRO_CONST = constants.value('Avogadro constant')
AVOGADRO_CONST_UNIT = constants.unit('Avogadro constant')
STANDARD_GRAVITY = constants.value('standard acceleration of gravity')
STANDARD_GRAVITY_UNIT = constants.unit('standard acceleration of gravity')
MW_AIR = 29
MW_AIR_UNIT = cf_units.Unit('g mol^-1')
MW_O3 = 48
MW_O3_UNIT = cf_units.Unit('g mol^-1')
DOBSON_UNIT = cf_units.Unit('2.69e20 m^-2')


class DerivedVariable(DerivedVariableBase):
    """Derivation of variable `toz`."""
    @staticmethod
    def required(project):
        """Declare the variables needed for derivation."""
        if project == 'CMIP6':
            required = [{'short_name': 'o3'}, {'short_name': 'ps'}]
        else:
            required = [{'short_name': 'tro3'}, {'short_name': 'ps'}]
        return required
Example #38
0
def mg(dl, B, lam):
    return const.h * const.c / (lam**2 * B * const.value("Bohr magneton")) * dl
Example #39
0
def main():
    # Input parser
    parser = argparse.ArgumentParser(
        description="Reorganize abICS RXMC results by temperature")

    parser.add_argument("inputfi", help="toml input file used for abICS run")

    parser.add_argument(
        "skipsteps",
        nargs="?",
        type=int,
        default=0,
        help="number of thermalization steps to skip in energy averaging." +
        " Default: 0",
    )

    args = parser.parse_args()
    inputfi = args.inputfi
    nskip = args.skipsteps
    rxparams = RXParams.from_toml(inputfi)
    nreplicas = rxparams.nreplicas
    comm = RX_MPI_init(rxparams)

    myreplica = comm.Get_rank()

    if myreplica == 0:
        if os.path.exists("Tseparate"):
            shutil.move("Tseparate",
                        "Tseparate.bak.{}".format(datetime.datetime.now()))
        os.mkdir("Tseparate")
    comm.Barrier()

    # Separate structure files
    os.mkdir(os.path.join("Tseparate", str(myreplica)))
    Trank_hist = np.load(os.path.join(str(myreplica), "Trank_hist.npy"))
    os.chdir(str(myreplica))
    for j in range(len(Trank_hist)):
        shutil.copy(
            "structure.{}.vasp".format(j),
            os.path.join(os.pardir, "Tseparate", str(Trank_hist[j])),
        )

    # Separate energies
    myreplica_energies = np.load("obs_save.npy")[:, 0]
    for Tid in range(nreplicas):
        T_energies = np.where(Trank_hist == Tid, myreplica_energies, 0)
        T_energies_rcvbuf = np.zeros(T_energies.shape[0], "d")
        comm.Reduce(
            [T_energies, MPI.DOUBLE],
            [T_energies_rcvbuf, MPI.DOUBLE],
            op=MPI.SUM,
            root=Tid,
        )
        if myreplica == Tid:
            np.savetxt(
                os.path.join(os.pardir, "Tseparate", str(Tid), "energies.dat"),
                T_energies_rcvbuf,
            )

    comm.Barrier()

    if myreplica == 0:
        os.chdir(os.path.join(os.pardir, "Tseparate"))
        with open("energies_T.dat", "w") as fi:
            kTs = np.load(os.path.join(os.pardir, "kTs.npy"))
            Ts = kTs / constants.value(u"Boltzmann constant in eV/K")
            for Tid in range(nreplicas):
                energy_mean = np.mean(
                    np.loadtxt(os.path.join(str(Tid), "energies.dat"))[nskip:])
                fi.write("{}\t{}\n".format(Ts[Tid], energy_mean))
Example #40
0
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module defines classes to represent the phonon density of states, etc.
"""

import numpy as np
import scipy.constants as const
from monty.functools import lazy_property
from monty.json import MSONable

from pymatgen.core.structure import Structure
from pymatgen.util.coord import get_linear_interpolated_value

BOLTZ_THZ_PER_K = (const.value("Boltzmann constant in Hz/K") / const.tera
                   )  # Boltzmann constant in THz/K
THZ_TO_J = const.value("hertz-joule relationship") * const.tera


def coth(x):
    """
    Coth function.

    Args:
        x (): value

    Returns:
        coth(x)
    """
    return 1.0 / np.tanh(x)
Example #41
0
import numpy as np
from scipy.integrate import quad
import scipy.constants as spc
from atmosphere import *
from charged_particle import EnergyDistribution, AngularDistribution

twopi = 2. * np.pi
m_e = spc.value('electron mass energy equivalent in MeV')


class CherenkovPhoton:
    inner_precision = 1.e-5
    outer_precision = 1.e-4

    def __init__(self, t, delta, ntheta=321, minlgtheta=-3., maxlgtheta=0.2):
        """Create a normalized Cherenkov-photon angular distribution at the
        given shower stage, t, and with the index-of-refraction of the atmosphere
        given by delta. By default there are 321 logarithmically spaced angular
        points from 1 mR to pi/2 R.

        Parameters:
            t: shower stage
            delta: difference of index-of-refraction from unity
            ntheta: number of log-spaced theta points to create
            minlgtheta: the minimum value of lgtheta
            maxlgtheta: the maximum value of lgtheta
        """
        self.t = t
        self.delta = delta
        lgtheta, dlgtheta = np.linspace(minlgtheta,
                                        maxlgtheta,
Example #42
0
#!/usr/bin/env python3

import pickle

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import numpy
from scipy import constants

from pysolidg2p import asymmetry, cross_section, sim_reader, structure_f

_alpha = constants.alpha
_m_p = constants.value('proton mass energy equivalent in MeV') * 1e-3
_inv_fm_to_gev = constants.hbar * constants.c / constants.e * 1e6
_inv_gev_to_fm = _inv_fm_to_gev
_inv_gev_to_mkb = _inv_gev_to_fm**2 * 1e4

e = 11
binning = {'bins': 20, 'range': (0.0, 1.0)}
yield_limit = 10000


def create_bins():
    bins = binning['bins']
    bin_low, bin_high = binning['range']
    bin_centers = numpy.linspace(bin_low + (bin_high - bin_low) / bins / 2,
                                 bin_high - (bin_high - bin_low) / bins / 2,
                                 bins)
    bin_edges = numpy.linspace(bin_low, bin_high, bins + 1)

    return bin_centers, bin_edges
Example #43
0
from hyperspy.misc.eels.base_gos import GOSBase

_logger = logging.getLogger(__name__)

XU = [
    .82, .52, .52, .42, .30, .29, .22, .30, .22, .16, .12, .13, .13, .14, .16,
    .18, .19, .22, .14, .11, .12, .12, .12, .10, .10, .10
]
# IE3=[73,99,135,164,200,245,294,347,402,455,513,575,641,710,
# 779,855,931,1021,1115,1217,1323,1436,1550,1675]

# IE1=[118,149,189,229,270,320,377,438,500,564,628,695,769,846,
# 926,1008,1096,1194,1142,1248,1359,1476,1596,1727]

R = constants.value("Rydberg constant times hc in eV")


class HydrogenicGOS(GOSBase):
    """Computes the K and L GOS using R. Egerton's  routines.

    Parameters
    ----------
    element_subshell : str
        For example, 'Ti_L3' for the GOS of the titanium L3 subshell

    Methods
    -------
    parametrize_GOS()
        Parametrize the GOS to speed up the calculation.
    get_qaxis_and_gos(ienergy, qmin, qmax)
Example #44
0
# Filename of mesh (excluding .xml)
# fname = "../mesh/3D/laframboise_sphere_in_sphere_res1c"
fname = "../mesh/3D/laframboise_sphere_in_cube_res1"

# Get the mesh
mesh, bnd = load_mesh(fname)
ext_bnd_id, int_bnd_ids = get_mesh_ids(bnd)
ext_bnd = ExteriorBoundaries(bnd, ext_bnd_id)

npc = 4             # Number of particles per cell
# num = 300000        # Total number of particles in the domain
V = df.assemble(1*df.dx(mesh))
Np = npc*mesh.num_cells()

me   = constants.value('electron mass')
mp   = constants.value('proton mass')
e    = constants.value('elementary charge')
eps0 = constants.value('electric constant')
kB   = constants.value('Boltzmann constant')

ne      = 1e10
# Te    = 1000
# debye = np.sqrt(eps0*kB*Te/(e**2 * ne))
debye   = 1.0
Te      = (e*debye)**2*ne/(eps0*kB)
wpe     = np.sqrt(ne*e**2/(eps0*me))
vthe    = debye*wpe
vthi    = vthe/np.sqrt(1836)
Rp      = 1*debye
X       = Rp
Example #45
0
#!/usr/bin/env python

from scipy import constants as K # <1>

print("pi: {0}".format(K.pi)) # <2>
print("Planck: {0}".format(K.Planck)) # <2>
print("c (speed of light): {0}".format(K.c)) # <2>

print("natural unit of energy: {0}".format(K.value('natural unit of energy')))
print("natural unit of energy (Unit): {0}".format(K.unit('natural unit of energy')))

Example #46
0
"""
  This script collects the data from forward and backward switchings and computed the absolute free energy for each temperature.

  Usage:
    python integrate.py
"""

from numpy import *
import scipy.constants as sc
from scipy.integrate import cumtrapz

T0 = 100  # Reference temperature [K]
kB = sc.value('Boltzmann constant in eV/K')

# Load free energy reference value.
T, F0 = loadtxt('../../frenkel_ladd/data/free_energy.dat', unpack=True)
F0 = F0[T == T0]

# Load potential energy and lambda.
U_f, lamb_f = loadtxt('../data/forward.dat', unpack=True)
U_b, lamb_b = loadtxt('../data/backward.dat', unpack=True)

# Fix adapt also scales the potential energy besides the forces, so we unscale.
U_f /= lamb_f
U_b /= lamb_b

# Compute work done using cummulative integrals [Eq.(21) in the paper].
I_f = cumtrapz(U_f, lamb_f, initial=0)
I_b = cumtrapz(U_b[::-1], lamb_b[::-1], initial=0)
W = (I_f + I_b) / (2 * lamb_f)
Example #47
0
"""Constants and helper methods for use within the schedule submodule.
"""
import numpy as np
from scipy import constants
from scipy import sparse
import scipy.special as special

BOLTZ = constants.value("Boltzmann constant in Hz/K")
E_CHARGE = constants.value("atomic unit of charge")
H_PLANCK = constants.value("Planck constant")
PHI_0 = constants.value("mag. flux quantum")


def e_j(i_c):
    """Returns the josephson energy for the given critical current
    in GHZ (omega)
    E_j = Phi_0/2pi * I_c

    Arguments
    ---------
    i_c : float
        Junction critical current, in nA

    Returns
    -------
    float
         Josephson energy in GHz (i.e., omega = 2*pi*f)

    """
    return PHI_0 * (i_c * 1e-9) / H_PLANCK / 1e9
Example #48
0
from numpy.lib import scimath
import scipy
from scipy.optimize import curve_fit
from scipy import constants
from scipy.stats import sem
import matplotlib.pyplot as plt
from uncertainties import ufloat
import uncertainties.unumpy as unp
from uncertainties.unumpy import log10, log, exp, sqrt
import sympy
import cmath

plt.rcParams['figure.figsize'] = (10, 8)
plt.rcParams['font.size'] = 16

h = constants.value(u'Planck constant')
c = constants.value(u'speed of light in vacuum')
mb = constants.value(u'Bohr magneton')

l_blue = 480 * 10**(-9)
l_red = 643.8 * 10**(-9)
ld_red = 48.9 * 10**(-12)
ld_blue = 26.9 * 10**(-12)

data_b = np.genfromtxt('magnetfeld.txt', unpack='True')

data_deltas_red = np.genfromtxt('deltas_red.txt', unpack='True', skip_header=1)
data_deltas_blue = np.genfromtxt('deltas_blue.txt',
                                 unpack='True',
                                 skip_header=1)
Example #49
0
    ValenceIonicRadiusEvaluator
from pymatgen.analysis.local_env import get_okeeffe_distance_prediction, MinimumDistanceNN, \
    VoronoiNN, MinimumOKeeffeNN, MinimumVIRENN
from pymatgen.analysis.structure_analyzer import OrderParameters
from pymatgen.core.periodic_table import Specie, Element
from pymatgen.analysis.structure_analyzer import VoronoiCoordFinder as VCF
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer

from matminer.featurizers.base import BaseFeaturizer
from matminer.featurizers.stats import PropertyStats

__authors__ = 'Anubhav Jain <*****@*****.**>, Saurabh Bajaj <*****@*****.**>, ' \
              'Nils E.R. Zimmerman <*****@*****.**>'
# ("@article{label, title={}, volume={}, DOI={}, number={}, pages={}, journal={}, author={}, year={}}")

ANG_TO_BOHR = const.value('Angstrom star') / const.value('Bohr radius')


# To do:
# - Use local_env-based neighbor finding
#   once this is part of the stable Pymatgen version.

class DensityFeatures(BaseFeaturizer):

    def __init__(self, desired_features=None):
        self.features = ["density", "vpa", "packing fraction"] if not desired_features else desired_features

    def featurize(self, s):
        features = []

        if "density" in self.features:
Example #50
0
# %%
#
#dummy = wpu.dummy_images('Shapes',  shape=(110, 110), noise = 1)
#fname = 'dummy.tif'
#image = dummy[5:-5,5:-5]
#image_ref = dummy[7:-3,4:-6]

# =============================================================================
# %% parameters
# =============================================================================

rad2deg = np.rad2deg(1)
deg2rad = np.deg2rad(1)
NAN = float('Nan')  # not a number alias

hc = constants.value('inverse meter-electron volt relationship')  # hc

wavelength = hc / phenergy
kwave = 2 * np.pi / wavelength

# =============================================================================
# %% Crop
# =============================================================================

#image = np.rot90(image)  # rotate images, good for sanity checks
#image_ref = np.rot90(image_ref)

kb_input = input('\nGraphic Crop? [N/y] : ')
if kb_input.lower() == 'y':
    # Graphical Crop
Example #51
0
    def write_etree(self,
                    celltype,
                    cartesian=False,
                    bandstr=False,
                    symprec=0.4,
                    angle_tolerance=5,
                    **kwargs):
        """
        Writes the exciting input parameters to an xml object.

        Args:
            celltype (str): Choice of unit cell. Can be either the unit cell
            from self.structure ("unchanged"), the conventional cell
            ("conventional"), or the primitive unit cell ("primitive").

            cartesian (bool): Whether the atomic positions are provided in
            Cartesian or unit-cell coordinates. Default is False.

            bandstr (bool): Whether the bandstructure path along the
            HighSymmKpath is included in the input file. Only supported if the
            celltype is set to "primitive". Default is False.

            symprec (float): Tolerance for the symmetry finding. Default is 0.4.

            angle_tolerance (float): Angle tolerance for the symmetry finding.
            Default is 5.

            **kwargs: Additional parameters for the input file.

        Returns:
            ET.Element containing the input XML structure
        """
        root = ET.Element("input")
        root.set(
            "{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation",
            "http://xml.exciting-code.org/excitinginput.xsd",
        )
        title = ET.SubElement(root, "title")
        title.text = self.title
        if cartesian:
            structure = ET.SubElement(root,
                                      "structure",
                                      cartesian="true",
                                      speciespath="./")
        else:
            structure = ET.SubElement(root, "structure", speciespath="./")

        crystal = ET.SubElement(structure, "crystal")
        # set scale such that lattice vector can be given in Angstrom
        ang2bohr = const.value("Angstrom star") / const.value("Bohr radius")
        crystal.set("scale", str(ang2bohr))
        # determine which structure to use
        finder = SpacegroupAnalyzer(self.structure,
                                    symprec=symprec,
                                    angle_tolerance=angle_tolerance)
        if celltype == "primitive":
            new_struct = finder.get_primitive_standard_structure(
                international_monoclinic=False)
        elif celltype == "conventional":
            new_struct = finder.get_conventional_standard_structure(
                international_monoclinic=False)
        elif celltype == "unchanged":
            new_struct = self.structure
        else:
            raise ValueError("Type of unit cell not recognized!")

        # write lattice
        basis = new_struct.lattice.matrix
        for i in range(3):
            basevect = ET.SubElement(crystal, "basevect")
            basevect.text = "%16.8f %16.8f %16.8f" % (
                basis[i][0],
                basis[i][1],
                basis[i][2],
            )
        # write atomic positions for each species
        index = 0
        for i in sorted(new_struct.types_of_species, key=lambda el: el.X):
            species = ET.SubElement(structure,
                                    "species",
                                    speciesfile=i.symbol + ".xml")
            sites = new_struct.indices_from_symbol(i.symbol)

            for j in sites:
                coord = "%16.8f %16.8f %16.8f" % (
                    new_struct[j].frac_coords[0],
                    new_struct[j].frac_coords[1],
                    new_struct[j].frac_coords[2],
                )
                # obtain cartesian coords from fractional ones if needed
                if cartesian:
                    coord2 = []
                    for k in range(3):
                        inter = (new_struct[j].frac_coords[k] * basis[0][k] +
                                 new_struct[j].frac_coords[k] * basis[1][k] +
                                 new_struct[j].frac_coords[k] *
                                 basis[2][k]) * ang2bohr
                        coord2.append(inter)
                    coord = "%16.8f %16.8f %16.8f" % (coord2[0], coord2[1],
                                                      coord2[2])

                # write atomic positions
                index = index + 1
                _ = ET.SubElement(species, "atom", coord=coord)
        # write bandstructure if needed
        if bandstr and celltype == "primitive":
            kpath = HighSymmKpath(new_struct,
                                  symprec=symprec,
                                  angle_tolerance=angle_tolerance)
            prop = ET.SubElement(root, "properties")
            bandstrct = ET.SubElement(prop, "bandstructure")
            for i in range(len(kpath.kpath["path"])):
                plot = ET.SubElement(bandstrct, "plot1d")
                path = ET.SubElement(plot, "path", steps="100")
                for j in range(len(kpath.kpath["path"][i])):
                    symbol = kpath.kpath["path"][i][j]
                    coords = kpath.kpath["kpoints"][symbol]
                    coord = "%16.8f %16.8f %16.8f" % (coords[0], coords[1],
                                                      coords[2])
                    if symbol == "\\Gamma":
                        symbol = "GAMMA"
                    _ = ET.SubElement(path, "point", coord=coord, label=symbol)
        elif bandstr and celltype != "primitive":
            raise ValueError("Bandstructure is only implemented for the \
                              standard primitive unit cell!")

        # write extra parameters from kwargs if provided
        self._dicttoxml(kwargs, root)

        return root
Example #52
0
# Author: Chao Gu, 2018

from scipy import constants

__all__ = ['mass']

_ma = constants.value('atomic mass constant energy equivalent in MeV') / 1000


def mass(z, a):
    return {
        (1, 1): 1.007940,
        (2, 4): 4.002602,
        (6, 12): 12.0107,
        (7, 14): 14.0067,
    }.get((z, a), a) * _ma
Example #53
0
num_cpu = mp.cpu_count()

# Tracking
from tqdm import tqdm

#########################
#                       #
#   GLOBAL PARAMETERS   #
#                       #
#########################

# Physical Constants
hbar = constants.hbar
kB = constants.Boltzmann
muB = constants.value('Bohr magneton')
Da = constants.value('atomic mass constant')

# Strontium 88 parameters
m = 88 * Da
Gamma = 2 * np.pi * 32 * 10**6  # linewidth of 32MHz (angular frequency)
k = (2 * np.pi) / (0.461 * 10**-6)
IO = 42.5  # Saturation intensity, mW/cm^2
gJ = 1.

# Fixed parameters
MOT3dXoffset = 0.
MOT3dYoffset = -0.003
MOT3dZoffset = 0.43
offset = np.array([MOT3dXoffset, MOT3dYoffset, MOT3dZoffset])
g = 9.8
Example #54
0
    def get_number_of_effective_electrons(self, nat, cumulative=False):
        """Compute the number of effective electrons using the Bethe f-sum
        rule.

        The Bethe f-sum rule gives rise to two definitions of the effective
        number (see [Egerton2011]_):
        $n_{\mathrm{eff}}\left(-\Im\left(\epsilon^{-1}\right)\right)$ that
        we'll call neff1 and
        $n_{\mathrm{eff}}\left(\epsilon_{2}\right)$ that we'll call neff2. This
        method computes both.

        Parameters
        ----------
        nat: float
            Number of atoms (or molecules) per unit volume of the
            sample.
        cumulative : bool
            If False calculate the number of effective electrons up to the
            higher energy-loss of the spectrum. If True, calculate the
            number of effective electrons as a function of the energy-loss up
            to the higher energy-loss of the spectrum. *True is only supported
            by SciPy newer than 0.13.2*.

        Returns
        -------
        neff1, neff2: Signal
            Signal instances containing neff1 and neff2. The signal and
            navigation dimensions are the same as the current signal if
            `cumulative` is True, otherwise the signal dimension is 0
            and the navigation dimension is the same as the current
            signal.

        Notes
        -----
        .. [Egerton2011] Ray Egerton, "Electron Energy-Loss
        Spectroscopy in the Electron Microscope", Springer-Verlag, 2011.

        """

        m0 = constants.value("electron mass")
        epsilon0 = constants.epsilon_0    # Vacuum permittivity [F/m]
        hbar = constants.hbar     # Reduced Plank constant [J·s]
        k = 2 * epsilon0 * m0 / (np.pi * nat * hbar ** 2)

        axis = self.axes_manager.signal_axes[0]
        if cumulative is False:
            dneff1 = k * simps((-1. / self.data).imag * axis.axis,
                               x=axis.axis,
                               axis=axis.index_in_array)
            dneff2 = k * simps(self.data.imag * axis.axis,
                               x=axis.axis,
                               axis=axis.index_in_array)
            neff1 = self._get_navigation_signal()
            neff2 = self._get_navigation_signal()
            neff1.data = dneff1
            neff2.data = dneff2
        else:
            neff1 = self._deepcopy_with_new_data(
                k * cumtrapz((-1. / self.data).imag * axis.axis,
                             x=axis.axis,
                             axis=axis.index_in_array,
                             initial=0))
            neff2 = self._deepcopy_with_new_data(
                k * cumtrapz(self.data.imag * axis.axis,
                             x=axis.axis,
                             axis=axis.index_in_array,
                             initial=0))

        # Prepare return
        neff1.metadata.General.title = (
            r"$n_{\mathrm{eff}}\left(-\Im\left(\epsilon^{-1}\right)\right)$ "
            "calculated from " +
            self.metadata.General.title +
            " using the Bethe f-sum rule.")
        neff2.metadata.General.title = (
            r"$n_{\mathrm{eff}}\left(\epsilon_{2}\right)$ "
            "calculated from " +
            self.metadata.General.title +
            " using the Bethe f-sum rule.")

        return neff1, neff2
Example #55
0
def fit_sdm_desoto(v_mp,
                   i_mp,
                   v_oc,
                   i_sc,
                   alpha_sc,
                   beta_voc,
                   cells_in_series,
                   EgRef=1.121,
                   dEgdT=-0.0002677,
                   temp_ref=25,
                   irrad_ref=1000,
                   root_kwargs={}):
    """
    Calculates the parameters for the De Soto single diode model using the
    procedure described in [1]_. This procedure has the advantage of
    using common specifications given by manufacturers in the
    datasheets of PV modules.

    The solution is found using the scipy.optimize.root() function,
    with the corresponding default solver method 'hybr'.
    No restriction is put on the fit variables, i.e. series
    or shunt resistance could go negative. Nevertheless, if it happens,
    check carefully the inputs and their units; alpha_sc and beta_voc are
    often given in %/K in manufacturers datasheets and should be given
    in A/K and V/K here.

    The parameters returned by this function can be used by
    pvsystem.calcparams_desoto to calculate the values at different
    irradiance and cell temperature.

    Parameters
    ----------
    v_mp: float
        Module voltage at the maximum-power point at reference conditions [V].
    i_mp: float
        Module current at the maximum-power point at reference conditions [A].
    v_oc: float
        Open-circuit voltage at reference conditions [V].
    i_sc: float
        Short-circuit current at reference conditions [A].
    alpha_sc: float
        The short-circuit current (i_sc) temperature coefficient of the
        module [A/K].
    beta_voc: float
        The open-circuit voltage (v_oc) temperature coefficient of the
        module [V/K].
    cells_in_series: integer
        Number of cell in the module.
    EgRef: float, default 1.121 eV - value for silicon
        Energy of bandgap of semi-conductor used [eV]
    dEgdT: float, default -0.0002677 - value for silicon
        Variation of bandgap according to temperature [eV/K]
    temp_ref: float, default 25
        Reference temperature condition [C]
    irrad_ref: float, default 1000
        Reference irradiance condition [W/m2]
    root_kwargs: dictionary, default None
        Dictionary of arguments to pass onto scipy.optimize.root()

    Returns
    -------
    Dictionary with the following elements:
        * ``I_L_ref`` (float) --
          Light-generated current at reference conditions [A]
        * ``I_o_ref`` (float) --
          Diode saturation current at reference conditions [A]
        * ``R_s`` (float) --
          Series resistance [ohms]
        * ``R_sh_ref`` (float) --
          Shunt resistance at reference conditions [ohms].
        * ``a_ref`` (float) --
          Modified ideality factor at reference conditions.
          The product of the usual diode ideality factor (n, unitless),
          number of cells in series (Ns), and cell thermal voltage at
          specified effective irradiance and cell temperature.
        * ``alpha_sc`` (float) --
          The short-circuit current (i_sc) temperature coefficient of the
          module [A/K].
        * ``EgRef`` (float) --
          Energy of bandgap of semi-conductor used [eV]
        * ``dEgdT`` (float) --
          Variation of bandgap according to temperature [eV/K]
        * ``irrad_ref`` (float) --
          Reference irradiance condition [W/m2]
        * ``temp_ref`` (float) --
          Reference temperature condition [C]
    scipy.optimize.OptimizeResult
        Optimization result of scipy.optimize.root().
        See scipy.optimize.OptimizeResult for more details.

    References
    ----------
    .. [1] W. De Soto et al., "Improvement and validation of a model for
       photovoltaic array performance", Solar Energy, vol 80, pp. 78-88,
       2006.

    .. [2] John A Duffie, William A Beckman, "Solar Engineering of Thermal
       Processes", Wiley, 2013
    """

    try:
        from scipy.optimize import root
        from scipy import constants
    except ImportError:
        raise ImportError("The fit_sdm_desoto function requires scipy.")

    # Constants
    k = constants.value('Boltzmann constant in eV/K')
    Tref = temp_ref + 273.15  # [K]

    # initial guesses of variables for computing convergence:
    # Values are taken from [2], p753
    Rsh_0 = 100.0
    a_0 = 1.5 * k * Tref * cells_in_series
    IL_0 = i_sc
    Io_0 = i_sc * np.exp(-v_oc / a_0)
    Rs_0 = (a_0 * np.log1p((IL_0 - i_mp) / Io_0) - v_mp) / i_mp
    # params_i : initial values vector
    params_i = np.array([IL_0, Io_0, a_0, Rsh_0, Rs_0])

    # specs of module
    specs = (i_sc, v_oc, i_mp, v_mp, beta_voc, alpha_sc, EgRef, dEgdT, Tref, k)

    # computing with system of equations described in [1]
    optimize_result = root(_system_of_equations_desoto,
                           x0=params_i,
                           args=(specs, ),
                           **root_kwargs)

    if optimize_result.success:
        sdm_params = optimize_result.x
    else:
        raise RuntimeError('Parameter estimation failed:\n' +
                           optimize_result.message)

    # results
    return ({
        'I_L_ref': sdm_params[0],
        'I_o_ref': sdm_params[1],
        'a_ref': sdm_params[2],
        'R_sh_ref': sdm_params[3],
        'R_s': sdm_params[4],
        'alpha_sc': alpha_sc,
        'EgRef': EgRef,
        'dEgdT': dEgdT,
        'irrad_ref': irrad_ref,
        'temp_ref': temp_ref
    }, optimize_result)
Example #56
0
import numpy as np
import pylab as pl
import matplotlib.pyplot as plt
from scipy import constants as cst
from matplotlib.ticker import FormatStrFormatter
#from scipy.signal import savgol_filter

verbose = 2  # control verbosity

if verbose == 2:
    fig = plt.figure(figsize=(6.5, 5))
    ax = fig.add_subplot(1, 1, 1)
    tmpl = [0.8, 1., 1.2, 1.5, 2., 2.5, 3., 4., 5., 6., 7.5]

## Physical cst
c0 = cst.value('speed of light in vacuum') * 1.e6  #um/s
h0 = cst.value('Planck constant')  # J.s
kb = cst.value('Boltzmann constant')  # J/K
hc = c0 * h0  # um.J

Apert = 0.83  # Aperture in m
fnum = 4.5  # fnumber
R = 300  # lambda / delta lambda spectral resolution
lmax = 7.5  # maximum wavelength, microns
lmin = 0.75  # minumin wavelength, microns
Area_dp = 31  # deep survey area, sq deg
Area_sh = 311  # shallow survey area, sq deg
Tmission = 2.  # mission length, years
obs_eff = 0.8  # observation efficiency (that is, fraction of time
# spent surveying)
t_dp = 104  # minutes per band per resolution element, deep survey
# ## Constantes e Definições

# In[3]:


# dataframe de pandas com valores utilizados para calculos
device = pd.DataFrame()

N = 1024  # tamanho padrao do grid
L = 500.0  # tamanho padrao do sistema em angstrom
dt = 1e-17  # incremento de tempo padrao em segundos
device['z_ang'] = np.linspace(-L/2, L/2, N)  # malha espacial em angstrom

# fatores de conversao para unidades atomicas
au_l = cte.value('atomic unit of length')
au_t = cte.value('atomic unit of time')
au_e = cte.value('atomic unit of energy')
au_v = cte.value('atomic unit of electric potential')
au_ef = cte.value('atomic unit of electric field')
hbar_au = 1.0
me_au = 1.0

# constantes fisicas
ev = cte.value('electron volt')
c = cte.value('speed of light in vacuum')
me = cte.value('electron mass')
q = cte.value('elementary charge')
hbar_ev = cte.value('Planck constant over 2 pi in eV s')
hbar = cte.value('Planck constant over 2 pi')
h = cte.value('Planck constant')
Example #58
0
# -*- coding: utf-8 -*-
"""
Contains constants and unit conversions.
"""
import scipy.constants as spc

###############################################################################

kcal_to_J = 4184
cal_to_J = 4.184
# Speed of light in m/s
C = spc.c
# ħ = h / 2π in J/s
HBAR = spc.hbar
# Conversion factor for momentum in SI to atomic units
P_AU = spc.value("atomic unit of momentum")

# Bohr radius in m
BOHR2M = spc.value("Bohr radius")
# Bohr -> Å conversion factor
BOHR2ANG = BOHR2M * 1e10
# Å -> Bohr conversion factor
ANG2BOHR = 1 / BOHR2ANG
# Hartree to J
AU2J = spc.value("Hartree energy")
# Hartree to kJ / mol
AU2KJPERMOL = AU2J / 1000 * spc.Avogadro
# Hartree to kcal / mol
AU2KCALMOL = AU2KJPERMOL / spc.calorie
# cal to j
CAL2J = AU2KJPERMOL / AU2KCALMOL
Example #59
0
            from Xpect_2 import LR as meth

        else:
            raise KeyError("specified method unkown")

        self.spec = meth.ECD(kwargs)

    def spectrum(self, **kwargs):
        print("ECD!!!")
        return self.spec.spectrum(kwargs)


if __name__ == '__main__':
    import matplotlib.pyplot as plt

    broadening = 0.1 * const.e / const.value('Hartree energy')  #
    print(broadening)

    files = (
        "/home/jmatti/projects/uracil/functionals_ts_au/functionals/uracil_pbe_rtp_x-dir-output-moments.dat",
        "/home/jmatti/projects/uracil/functionals_ts_au/functionals/uracil_pbe_rtp_y-dir-output-moments.dat",
        "/home/jmatti/projects/uracil/functionals_ts_au/functionals/uracil_pbe_rtp_z-dir-output-moments.dat",
    )
    files_lr = ("/home/jmatti/projects/uracil/tm_lrtddft/pbe/escf.out", )
    files_mag = (
        "/home/jmatti/projects/methyloxirane/ts_au_TZVP/r-methyloxirane_pbe_x-dir_TZVP-output-moments.dat",
        "/home/jmatti/projects/methyloxirane/ts_au_TZVP/r-methyloxirane_pbe_y-dir_TZVP-output-moments.dat",
        "/home/jmatti/projects/methyloxirane/ts_au_TZVP/r-methyloxirane_pbe_z-dir_TZVP-output-moments.dat"
    )
    files_mag_s = (
        "/home/jmatti/projects/methyloxirane/ts_au_TZVP/s-methyloxirane_pbe_x-dir_TZVP-output-moments.dat",
Example #60
0
 def load_consts(self):
     r""" Load constants, needed after unpickling in some cases """
     self._c_nmps = constants.value(
         'speed of light in vacuum') * 1e9 / 1e12  # c in nm/ps
     self._c_mks = constants.value('speed of light in vacuum')  # m/s