Example #1
0
def plot_phases(in_file, plot_type, plot_log):
    plot_flag = 0

    def no_log(x):
        return x

    fig = pylab.figure(1)
    ax = fig.add_subplot(111)

    try:
        img = spimage.sp_image_read(in_file, 0)
    except IOError:
        raise IOError("Can't read %s." % in_file)

    values = img.image.reshape(pylab.size(img.image))

    if plot_log:
        log_function = pylab.log
    else:
        log_function = no_log

    if plot_type == PHASES:
        hist = pylab.histogram(pylab.angle(values), bins=500)
        ax.plot((hist[1][:-1] + hist[1][1:]) / 2, log_function(hist[0]))
    elif plot_flag == HISTOGRAM:
        hist = pylab.histogram2d(pylab.real(values),
                                 pylab.imag(values),
                                 bins=500)
        ax.imshow(log_function(hist[0]),
                  extent=(hist[2][0], hist[2][-1], -hist[1][-1], -hist[1][0]),
                  interpolation='nearest')
    else:
        ax.plot(pylab.real(values), pylab.imag(values), '.')
    return fig
Example #2
0
def plot_phases(in_file, plot_type, plot_log):
    flags = ['histogram','phases']
    plot_flag = 0
    log_flag = 0

    def no_log(x):
        return x

    fig = pylab.figure(1)
    ax = fig.add_subplot(111)

    try:
        img = spimage.sp_image_read(in_file,0)
    except:
        raise IOError("Can't read %s." % in_file)

    values = img.image.reshape(pylab.size(img.image))

    if plot_log:
        log_function = pylab.log
    else:
        log_function = no_log

    if plot_type == PHASES:
        hist = pylab.histogram(pylab.angle(values),bins=500)
        ax.plot((hist[1][:-1]+hist[1][1:])/2.0,log_function(hist[0]))
    elif plot_flag == HISTOGRAM:
        hist = pylab.histogram2d(pylab.real(values),pylab.imag(values),bins=500)
        ax.imshow(log_function(hist[0]),extent=(hist[2][0],hist[2][-1],-hist[1][-1],-hist[1][0]),interpolation='nearest')
    else:
        ax.plot(pylab.real(values),pylab.imag(values),'.')
    return fig
Example #3
0
    def mfreqz(self, b,a=1):
        '''
        plotting freqz of filter , like matlab representation.
        :param b: nominator
        :param a: denominator
        default: a = 1
        '''
        from matplotlib import pyplot as plt
        from pylab import unwrap, arctan2, imag, real, log10

        w, h = signal.freqz(b,a)
        h_dB = 20 * log10(abs(h))
        plt.subplot(211)
        plt.plot(w/max(w), h_dB)
        plt.grid()
        plt.ylim(-150, 5)
        plt.ylabel('Magnitude (db)')
        plt.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
        plt.title(r'Frequency response')
        plt.subplot(212)
        h_Phase = unwrap(arctan2(imag(h),real(h)))
        plt.plot(w/max(w),h_Phase)
        plt.grid()
        plt.ylabel('Phase (radians)')
        plt.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
        plt.title(r'Phase response')
        plt.subplots_adjust(hspace=0.5)
        plt.show(block=False)
Example #4
0
def get_undef_blade():
    blade = {}
    blade["tower"] = py.array(
        [[0.0, 4.15 / 2, 4.15 / 2, -4.15 / 2, -4.15 / 2, 0.0],
         [0.0, 0.0, 115.63, 115.63, 0.0, 0.0]])
    blade["shaft"] = py.array(
        [[
            blade["tower"][0, 1],
            blade["tower"][0, 1] - 7.1 * py.cos(5 * py.pi / 180)
        ],
         [
             blade["tower"][1, 2] + 2.75,
             blade["tower"][1, 2] + 2.75 + abs(7.1) * py.sin(5 * py.pi / 180)
         ]])
    shaft_tan = py.diff(blade["shaft"])
    shaft_tan = shaft_tan[0] + 1j * shaft_tan[1]
    shaft_tan /= abs(shaft_tan)
    shaft_normal = shaft_tan * 1j

    blade["hub_fun"] = lambda r: blade["shaft"][0, -1] + 1j * blade["shaft"][
        1, -1] + r * shaft_normal

    blade["hub"] = py.array(
        [[py.real(blade["hub_fun"](0)),
          py.real(blade["hub_fun"](2.8))],
         [py.imag(blade["hub_fun"](0)),
          py.imag(blade["hub_fun"](2.8))]])
    cone = -2.5 * py.pi / 180  # Cone angle
    blade_normal = (py.cos(cone) + 1j * py.sin(cone)) * shaft_normal
    blade["blade_fun"] = lambda r, R, defl: blade["hub"][0, -1] + 1j * blade[
        "hub"
    ][
        1, -1
    ] + r * blade_normal + r / R * 2.332 * blade_normal / 1j + defl * blade_normal / 1j
    R = 86.366
    blade["blade"] = py.array([[
        py.real(blade["blade_fun"](0, R, 0)),
        py.real(blade["blade_fun"](R, R, 0))
    ],
                               [
                                   py.imag(blade["blade_fun"](0, R, 0)),
                                   py.imag(blade["blade_fun"](R, R, 0))
                               ]])
    #print(py.angle(blade_normal)*180/py.pi,py.angle(shaft_normal)*180/py.pi)
    return (blade)
Example #5
0
    def plot_complex_(ax, z):
        verts = map(lambda z: (real(z), imag(z)), z)
        codes = [Path.MOVETO
                 ] + [Path.LINETO] * (len(verts) - 2) + [Path.CLOSEPOLY]

        path = mpath.Path(verts, codes)
        patch = mpatches.PathPatch(path,
                                   facecolor=[1, 0.5, 0.8],
                                   edgecolor='black',
                                   alpha=1)
        ax.add_patch(patch)
Example #6
0
def numform(element,tol):
            """numform returns a string representing num -- the string is blank if |num|<tol"""
            st=""
            reelement=real(element)
            imelement=imag(element)
            if abs(reelement)<tol: # don't print the real part
                if abs(imelement)>tol: # print the imag part
                    st+=inumform(imelement)
                    st+="i"
            elif abs(imag(element))<tol: # print real but not imag
                st+=rnumform(reelement)
            else:                       # print both
                st+=rnumform(reelement)
                if imelement>0:
                    st+="+"
                else:
                    st+="-"
                    imelement=-imelement
                st+=inumform(imelement)
                st+="i"
            return st
Example #7
0
 def plot_upd_mfreqz(self, fig, taps, a=1):
     if not signal:
         return
     self.plot_init_mfreqz(fig)
     ax1, ax2 = fig.get_axes()
     w, h = signal.freqz(taps, a)
     if sum(abs(h)) == 0:
         return
     h_dB = 20 * pylab.log10(abs(h))
     ax1.plot(w / max(w), h_dB)
     h_Phase = pylab.unwrap(pylab.arctan2(pylab.imag(h), pylab.real(h)))
     ax2.plot(w / max(w), h_Phase)
Example #8
0
def plot_image(in_file,*arguments):
    
    try:
        img = spimage.sp_image_read(in_file,0)
    except:
        print "Error: %s is not a readable .h5 file\n" % in_file

    plot_flags = ['abs','mask','phase','real','imag']
    shift_flags = ['shift']
    log_flags = ['log']

    plot_flag = 0
    shift_flag = 0
    log_flag = 0

    for flag in arguments:
        flag = flag.lower()
        if flag in plot_flags:
            plot_flag = flag
        elif flag in shift_flags:
            shift_flag = flag
        elif flag in log_flags:
            log_flag = flag
        else:
            print "unknown flag %s" % flag

    if shift_flag:
        img = spimage.sp_image_shift(img)

    def no_log(x):
        return x

    if log_flag:
        log_function = pylab.log
    else:
        log_function = no_log

    if (plot_flag == "mask"):
        pylab.imshow(img.mask,origin='lower',interpolation="nearest")
    elif(plot_flag == "phase"):
        pylab.imshow(pylab.angle(img.image),cmap='hsv',origin='lower',interpolation="nearest")
    elif(plot_flag == "real"):
        pylab.imshow(log_function(pylab.real(img.image)),origin='lower',interpolation="nearest")
    elif(plot_flag == "imag"):
        pylab.imshow(log_function(pylab.imag(img.image)),origin='lower',interpolation="nearest")
    else:
        pylab.imshow(log_function(abs(img.image)),origin='lower',interpolation="nearest")

    pylab.show()
Example #9
0
def getGrowthNakata(ky_list, Setup, init = -0.07 -.015j):
  
  results = []
  
  eta_e     = Setup['eta_e']
  kx        = Setup['kx']
  v_te      = Setup['v_te']
  rho_te2   = Setup['rho_te2']
  tau       = Setup['tau']
  theta     = Setup['theta']

  for ky in ky_list:
    
    kp  = mp.sqrt(2.) * theta * ky 
    # Dispersion Relation Equation (9)
    if ky > 2.5 : init = 0.01 - 0.01j
    def DispersionRelation(w):
        ko2 = kx**2 + ky**2
        def Lambda(b): return mp.exp(b) * (1. + tau - Gamma0(b))
        #def Lambda(b): return mp.exp(b) * (tau + b/(1.+b))
      
        #zeta = w / (kp * v_te)
        zeta = w / (kp * v_te)
        w_star_e = ky * pylab.sqrt(rho_te2) * v_te
 
        # Take care of extra pie due to normalization
        #return  1. + Lambda(ko2 * rho_te2) + zeta * Z(zeta) - ky/kp *  eta_e * zeta - ky/kp * ( eta_e * zeta**2 +\
        return  1. + Lambda(ko2 * rho_te2) + zeta * Z(zeta) - ky/kp *  eta_e * zeta - ky/kp * ( eta_e * zeta**2 +\
                    (1. - eta_e/2. * (1. + ko2 * rho_te2)))*Z(zeta) * mp.sqrt(mp.pi)
                    #(1. - eta_e/2. * (1. + ko2 * rho_te2)))*Z(zeta) 

    try:
        omega = complex(mp.findroot(DispersionRelation, init, solver='muller', maxsteps=1000))
        #omega = complex(PT.zermuller(DispersionRelation, 0., -0.2 - 0.05j, dx=.001)[0])

    except:
        omega = .0
        print "Not found : ", ky,  "  Theta : ", theta
    results.append(float(pylab.real(omega))  + 1.j * pylab.imag(omega))

  return (pylab.array(ky_list), pylab.array(results))
Example #10
0
total_bits=50
samples_per_cycle=float(sampling_rate)/float(local_osc)
samples_per_bit=cycles_per_bit*samples_per_cycle
len_iq_samples=int(float(total_bits)*samples_per_bit)
total_samples_to_read=len_iq_samples*2
fileh=open(sys.argv[1],'rb')
samples=bytearray(fileh.read(total_samples_to_read))
print len(samples)
iq_samples=pl.array([complex(samples[i*2]-128, samples[i*2+1]-128) for i in range(0,len_iq_samples) ])
dc_component=pl.sum(iq_samples)/len_iq_samples
for i in range(-5,5):
    lo=pl.exp(-1j*pl.frange(0,len_iq_samples-1)*(local_osc+i*1000)*2*pl.pi/sampling_rate)
#pl.plot(iq_samples)
    down_convert=iq_samples*lo
    decimated_samples=[pl.sum(down_convert[i:i+samples_per_bit-1]) for i in range(0,len_iq_samples-int(samples_per_bit))]
    x_axis_range=pl.frange(len(decimated_samples)-1)/samples_per_bit
    print len(x_axis_range), len(decimated_samples)
    pl.subplot(211)
    pl.plot(x_axis_range,pl.real(decimated_samples),'b',
            x_axis_range,pl.imag(decimated_samples),'r')
    pl.title('IQ Samples')
    pl.subplot(212)
    pl.plot(x_axis_range,pl.arctan(pl.imag(decimated_samples)/pl.real(decimated_samples)))
    pl.title('Phase')
    pl.figure(2)
    f_range=pl.frange(-sampling_rate/2 , sampling_rate/2 ,(sampling_rate)/len_iq_samples)
    print len(f_range), len_iq_samples
    pl.plot(f_range[0:len_iq_samples],abs(pl.fft(iq_samples)))
    pl.plot('FFT of IQ Samples')
    pl.show()
n_reS11 = keys.index('RE[S11]')
n_imS11 = keys.index('IM[S11]')
n_reS21 = keys.index('RE[S21]')
n_imS21 = keys.index('IM[S21]')

freq = data[:,n_freq]
S11 = data[:,n_reS11]+1j*data[:,n_imS11]
S21 = data[:,n_reS21]+1j*data[:,n_imS21]


for label, y, x in (('S11', S11, freq), ('S21',S21, freq)):
    cur = curve.Curve()
    cur.set_data(pandas.Series(y, index=x))
    #res, fit_curve = cur.fit('lorentz_complex_sam')
    res, fit_curve = cur.fit('lorentz_complex_thibault')
    plot(real(fit_curve.data),imag(fit_curve.data), label='fit Q='+str(fit_curve.params['Q_c'])+';f='+str(fit_curve.params['omega_0']))
    #plot(real(fit_curve.data),imag(fit_curve.data), label='fit Q='+str(fit_curve.params['Q'])+';f='+str(fit_curve.params['x0']))
    #plot(real(cur.data),imag(cur.data), 'o', label=label)
legend()
show()
title(filename)

savefig(filename + '.pdf')
savefig(filename + '.png')






Example #12
0
    def calculateinitsunc(self,H,l,sigma_L = 1e-6,sigma_Theta = 1,n_exact = 1,filename=None):
        # Calculates the uncertianty on n and k according to:
        # W. Withayachumnankul, B. M. Fisher, H. Lin, D. Abbott, "Uncertainty in terahertz time-domain spectroscopy measurement", J. Opt. Soc. Am. B., Vol. 25, No. 6, June 2008, pp. 1059-1072
        #
        # sigma_L = standard uncertainty on sample thickness in meter
        # sigma_Theta = interval of sample misallignment in degree
        # n_exact = exact value of the refractive index of air during the measurements
        
        n, k = self.calculateinits(H,l)
        n = py.asarray(n)
        k = py.asarray(k)      
        
        Asam = []
        Aref = []
        Bsam = []
        Bref = []
        for i in range(len(self.H.getfreqs())):
            Asam.append((py.sum(py.imag(self.H.fdsam.getFAbs().tolist()[i]*py.exp(1j*2*py.pi*self.H.getfreqs().tolist()[i]*self.H.fdsam._tdData.getTimes()))*self.H.fdsam._tdData.getUncEX())**2))
            Aref.append((py.sum(py.imag(self.H.fdref.getFAbs().tolist()[i]*py.exp(1j*2*py.pi*self.H.getfreqs().tolist()[i]*self.H.fdref._tdData.getTimes()))*self.H.fdref._tdData.getUncEX())**2))
            Bsam.append((py.sum(py.real(self.H.fdsam.getFAbs().tolist()[i]*py.exp(1j*2*py.pi*self.H.getfreqs().tolist()[i]*self.H.fdsam._tdData.getTimes()))*self.H.fdsam._tdData.getUncEX())**2))
            Bref.append((py.sum(py.real(self.H.fdref.getFAbs().tolist()[i]*py.exp(1j*2*py.pi*self.H.getfreqs().tolist()[i]*self.H.fdref._tdData.getTimes()))*self.H.fdref._tdData.getUncEX())**2))
        
        # Uncertainty on n
        sn_Esam_2 = ((c/(2*py.pi*self.H.getfreqs()*l))**2 * py.asarray(Asam)/self.H.fdsam.getFAbs()**4)/self.H.fdsam._tdData.numberOfDataSets
        sn_Eref_2 = ((c/(2*py.pi*self.H.getfreqs()*l))**2 * py.asarray(Aref)/self.H.fdref.getFAbs()**4)/self.H.fdref._tdData.numberOfDataSets
        sn_l_2 = ((n-self.n_0)*sigma_L/l)**2
        #sn_l_2_1 = (c*self.H.getFPh()/(2*py.pi*self.H.getfreqs()*l*l))**2 * sigma_L**2
        #sn_H_2 = (c/(2*py.pi*self.H.getfreqs()*l))**2 * self.H.getFPhUnc()**2
        fn_Theta = (n-self.n_0.real)*(1/py.cos(sigma_Theta*py.pi/180)-1)
        fn_H = (c/(2*py.pi*self.H.getfreqs()*l))*py.absolute(-py.angle(4*(n-1j*k)*self.n_0/(n-1j*k+self.n_0)**2))
        fn_FP = (c/(2*py.pi*self.H.getfreqs()*l))*py.absolute(-py.angle(1/(1-((n-1j*k-self.n_0)/(n-1j*k+self.n_0))**2*py.exp(-2*1j*(n-1j*k)*2*py.pi*self.H.getfreqs()*l/c))))
        fn_n0 = abs(self.n_0.real - n_exact)*py.ones(len(self.H.getFPh()))
        u_n = py.sqrt(sn_l_2+sn_Esam_2+sn_Eref_2)+fn_Theta+fn_H+fn_FP+fn_n0

        # Uncertianty on k
        sk_Esam_2 = ((c/(2*py.pi*self.H.getfreqs()*l))**2 *(Bsam/self.H.fdsam.getFAbs()**4 + ((n-self.n_0)/(n+self.n_0))**2 * sn_Esam_2/n**2))/self.H.fdsam._tdData.numberOfDataSets
        sk_Eref_2 = ((c/(2*py.pi*self.H.getfreqs()*l))**2 *(Bref/self.H.fdref.getFAbs()**4 + ((n-self.n_0)/(n+self.n_0))**2 * sn_Eref_2/n**2))/self.H.fdref._tdData.numberOfDataSets
        sk_l_2 = (k*sigma_L/l)**2 + (c*(n-self.n_0)/((n+self.n_0)*n*2*py.pi*self.H.getfreqs()*l))**2*sn_l_2
        #sk_l_2_1 = ((c/(2*py.pi*self.H.getfreqs()*l*l))*py.log(self.H.getFAbs()*(n+self.n_0.real)**2/(4*n*self.n_0.real)))**2 * sigma_L**2
        #sk_H_2 = (-c/(2*py.pi*self.H.getfreqs()*l*self.H.getFAbs()))**2 * self.H.getFAbsUnc()**2
        fk_Theta = k*(1/py.cos(sigma_Theta*py.pi/180)-1)+c*(n-self.n_0.real)*fn_Theta/(n*2*py.pi*self.H.getfreqs()*l*(n+self.n_0.real))
        fk_H = (c/(2*py.pi*self.H.getfreqs()*l))*(py.log(py.absolute(n/(n-1j*k)*((n-1j*k+self.n_0.real)/(n+self.n_0.real))**2))+py.absolute(fn_H)*(n-self.n_0.real)/(n*(n+self.n_0.real)))
        fk_FP = (c/(2*py.pi*self.H.getfreqs()*l))*(py.absolute(-py.log(py.absolute(1/(1-((n-1j*k-self.n_0)/(n-1j*k+self.n_0))**2*py.exp(-2*1j*(n-1j*k)*2*py.pi*self.H.getfreqs()*l/c)))))+py.absolute(fn_FP)*(n-self.n_0.real)/(n*(n+self.n_0.real)))
        fk_n0 = (c/(2*py.pi*self.H.getfreqs()*l))*(n-self.n_0.real)*(self.n_0.real - n_exact)/(n*self.n_0.real)
        u_k = py.sqrt(sk_l_2+sk_Esam_2+sk_Eref_2)+fk_Theta+fk_H+fk_FP+fk_n0
        
        # Convert n in epsilon Epsilon = Epsilon_1 + j Epsilon_2 = (n+jk)**2
        # Epsilon_1 = n**2 - k**2
        # Epsilon_2 = -2nk
        Epsilon_1 = n**2 - k **2
        Epsilon_2 = -2 * n * k
        u_Epsilon_1 = py.sqrt((2*n*u_n)**2 + (-2*k*u_k)**2)
        u_Epsilon_2 = py.sqrt((-2*k*u_n)**2 + (-2*n*u_k)**2)
        
        # Calculate absorption coefficient
        # alpha = 4 * pi * k * f / c1
        alpha = 4 * py.pi * k * self.H.getfreqs() / (100 * c)      # in cm^-1
        u_alpha = 4 * py.pi * u_k * self.H.getfreqs() / (100 * c)  # in cm^-1
        
        # Calculate maximum measurable absorption coefficient according to
        # P. U. Jepsen and B. M. Fisher: "Dynamic Range in terahertz time-domain transmission and reflection spectroscopy", Optics Letters, Vol. 30, n. 1, pp. 29-31, Jan 2005
        
        alpha_max = 2 * py.log((self.H.fdsam.getDR() * 4 * n)/(n + 1)**2) / (100 * l) # in cm^-1
        
        # Save results into a table accessible from outside
        self.n_with_unc=py.real(py.column_stack((
        self.H.getfreqs(),                            # frequencies
        n, k,                                         # real and imaginary part of n
        u_n, u_k,                                     # k=1 combined uncertainty on n and k
        py.sqrt(sn_l_2), py.sqrt(sn_Esam_2), py.sqrt(sn_Eref_2), fn_Theta, fn_H, fn_FP, fn_n0, # Uncertainty components of n due to thickness, H, sample misallignment, k<<<, Neglect FP, ref ind of air
        py.sqrt(sk_l_2), py.sqrt(sk_Esam_2), py.sqrt(sk_Eref_2), fk_Theta, fk_H, fk_FP, fk_n0, # Uncertainty components of k due to thickness, H, sample misallignment, k<<<, Neglect FP, ref ind of air
        Epsilon_1, Epsilon_2,                         # Real and imaginary part of Epsilon
        u_Epsilon_1, u_Epsilon_2,                     # k = 1 uncertainty on the real and imaginary part of Epsilon
        alpha, u_alpha,                               # Absorption coefficient and its k = 1 uncertainty
        alpha_max,                                     # Maximum measurable absorption coefficient
        )))
        return
Example #13
0
import pylab
import mpmath as mp
import scipy
from Dispersion_ConstTheta import *

        

for m_ie in [ 0. ]:
            Setup = { 'eta' : 6., 'kx' : 0.0, 'v_te' : 1., 'rho_te2' : 1., 'tau' : 1., 'theta' : 0.01 , 'm_ie' : m_ie, 'lambda_D2' : 0.}
            ky_list = pylab.logspace(-1, 1.3, 101)

            disp="Gyro1stKin"
            if m_ie == 0. : disp ="Gyro1st"
            ky, gamma, res = getGrowth(ky_list, Setup, disp=disp)
            pylab.semilogx(ky, pylab.imag(gamma), label='$m_ie=%.3f$' % m_ie)
            
pylab.legend(ncol=1, loc='best').draw_frame(0)
pylab.ylim((-0.01,0.1))
#pylab.xlim((0.,2.0))
pylab.xlabel("Poloidal Wavenumber $k_y/\\rho_{te}$")
pylab.ylabel("Growthrate $\\gamma_L [\\nu_{te}/L_T]$")
pylab.savefig("Dispersion_Nakata.pdf", bbox_inches='tight')
pylab.savefig("Dispersion_Nakata.png", bbox_inches='tight')
Example #14
0
def getGrowth(ky_list, Setup, disp="Gyro", init = -0.02 -.006j):
  mp.dps=15

  results  = []
  residuum = []
  eta     = Setup['eta']
  kx        = Setup['kx']
  v_te      = Setup['v_te']
  rho_te2   = Setup['rho_te2']
  tau       = Setup['tau']
  theta     = Setup['theta']
  m_ie      = Setup['m_ie']
  lambda_D2 = Setup['lambda_D2']

  for ky in ky_list:
    kp  = theta * ky * v_te 
        
    ko2 = kx**2 + ky**2
    kyp = ky/kp
    b   = ko2 * rho_te2
    G0  = Gamma0(b)
    G0mG1 = Gamma0(b) - Gamma1(b)
   

    if disp == 'Gyro1st':
      def DispersionRelation(w):
        
        Lambda = lambda_D2 * b + mp.exp(b) * (1. + 1. - G0) 
        zeta = w / kp
        Z = Z_PDF(zeta) 
        # Take care of extra pie due to normalization
        return  - (1. - eta/2. * (1. + b))*kyp * Z \
                - eta * kyp * (zeta + zeta**2 * Z) + zeta * Z + 1. +  Lambda 
    if disp == 'Gyro1stKin':
      def DispersionRelation(w):
        
        def Disp(w, kp, b, eta):
            zeta = w / kp
            Z  = Z_PDF(zeta)
            kyp = ky/kp
            return    - (1. - eta/2. * (1. + b))*kyp * Z \
                - eta * kyp * (zeta + zeta**2 * Z) + zeta * Z + 1. 
       
        # proton
        sum1MG0 = lambda_D2 * b + (1. - G0) +  (1. - G0/m_ie) 

        #return -mp.exp(-b) * Disp(w, kp, b, eta) +  mp.exp(-b/m_ie) * Disp(w,kp * mp.sqrt(m_ie), b/m_ie, eta*mp.sqrt(m_ie)) + sum1MG0
        return mp.exp(-b) * Disp(w, kp, b, eta) -  mp.exp(-b/m_ie) * Disp(w,kp * mp.sqrt(m_ie), b/m_ie, eta) + sum1MG0


    elif disp == 'Fluid':
      def DispersionRelation(w):
        K    = 1. + eta
        K_12 = 1. + eta/2.
        Lambda = 0.#lambda_D2 * b + mp.exp(b) * (1. + 1. - G0) 
        return -ko2 + ( (ky + w)/(K_12 * ky - w) + kp**2 /w**2 * (0.5 * (K * ky - w))  /(K_12 * ky - w)) + Lambda
        return -ko2 + ( (ky+w)/(K_12 * ky-w) + kp**2 /w**2 * (0.5 * (K * ky - w))  /(K_12 * ky-w))
    
     


    elif disp == 'Gyro':
      def DispersionRelation(w):
        Lambda = lambda_D2 *b  + (1. - G0) + 1.
        zeta = w / kp
        Z  = Z_PDF(zeta)
        # Take care of extra pie due to normalization
        return  - (1. - eta/2.)*kyp * G0 * Z +   eta * kyp * b * G0mG1 * Z   \
                - eta * kyp * G0 * ( zeta +  zeta**2 * Z) +  zeta * Z * G0  + G0  +  Lambda 
    elif disp == 'GyroKin':
      def DispersionRelation(w):
        
        # Take care of extra pie due to normalization
        # what is Debye lengtth effect here ?
        def Disp(w, kp, b, eta):
            zeta = w / kp
            Z  = Z_PDF(zeta)
            kyp = ky/kp
            G0    = Gamma0(b)
            G0mG1 = Gamma0(b) - Gamma1(b)
            return  - (1. - eta/2.)*kyp * G0 * Z +   eta * kyp * b * G0mG1 * Z   \
                    - eta * kyp * G0 * ( zeta +  zeta**2 * Z) +  zeta * Z * G0  + G0 
        
        sum1MG0 = (1. - G0) + (1. - Gamma0(b/m_ie))

        return Disp(w, kp, b, eta)  - Disp(w,kp * mp.sqrt(m_ie), b/m_ie, eta/mp.sqrt(m_ie)              ) + sum1MG0
        return Disp(w, kp, b, eta) + (1.-G0) + 1. # - Disp(w,kp * mp.sqrt(m_ie), b/m_ie, eta              ) + sum1MG0
        return Disp(w, kp, b, eta) - Disp(w,kp * mp.sqrt(m_ie), b/m_ie, eta/mp.sqrt(m_ie)) + sum1MG0
    else : print  "No such Dispersion Relation : ", disp
 
    omega = init

    def checkAndImprove(omega, solver, tol=1.e-9):
       omega2 = omega
       try  : omega2 = complex(mp.findroot(DispersionRelation, omega , solver=solver, maxsteps=100, tol=tol))
       except : pass
       if (abs(DispersionRelation(omega2)) < abs(DisperisonRelation(omega))) : return omega2
       else : return omega

    #omega = checkAndImprove(omega, "newton", 1.e-6)
    try:
                        if (ky < 0.3): omega = complex(mp.findroot(DispersionRelation, omega, solver='anewton', maxsteps=10, verify=False))
                        omega = complex(mp.findroot(DispersionRelation, omega, solver='halley', maxsteps=300))
                             
                             #omega = complex(mp.findroot(DispersionRelation, omega, solver='newton', maxsteps=100 ))
    except : 
      omega = float('nan')
    print "ky : ", ky , " w : ", omega 
    results.append(float(pylab.real(omega))  + 1.j * pylab.imag(omega))
    res = DispersionRelation(results[-1])
    residuum.append(min(1.,float(abs(res))))
  
  return (pylab.array(ky_list), pylab.array(results), pylab.array(residuum))
Example #15
0
    """
    #print " electron ky : " , ky , "  " , complex(Disp(omega,kp * mp.sqrt(m_ie), b/m_ie, eta/mp.sqrt(m_ie)              )  + 1. - Gamma0(b/m_ie))
  
  return (pylab.array(ky_list), pylab.array(results), pylab.array(residuum))
     


#for theta in [ 0.033, 0.050, 0.133, 0.15, 0.2 ]:
for theta in [ 0.10]:
            Setup = { 'eta' : 4., 'kx' : 0.0, 'v_te' : mp.sqrt(2.), 'rho_te2' : 1., 'tau' : 1., 'theta' : 0. , 'm_ie' : 100., 'lambda_D2' : 0.}
            ky_list = pylab.logspace(pylab.log10(0.2), pylab.log10(10.), 51)
            #ky_list = pylab.linspace(20., 60.,101)
            Setup['theta'] = theta

            ky, gamma, err = getGrowth(ky_list, Setup, disp="Gyro", init= 0.02 + 0.045j)
            pylab.semilogx(ky, pylab.imag(gamma), 'b-', label='Gyro')
            #pylab.plot(ky, pylab.imag(gamma), 'b-', label='Gyro')

            #ky, gamma, err = getGrowth(ky_list, Setup, disp="Gyro1st", init=0.02+0.045j)
            #pylab.semilogx(ky[:350], pylab.imag(gamma)[:350], 'g-', label='Gyro $\\mathcal{O}{(1)}$')

            #ky, gamma, err = getGrowth(ky_list, Setup, disp="Fluid", init = 0.02 + 0.045j)
            #pylab.semilogx(ky, pylab.imag(gamma), 'r-', label='Fluid ')

            #ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKin", init=-0.01 + 0.01j)
            #ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKin", init= 0.02 + 0.045j)
            #pylab.semilogx(ky, pylab.imag(gamma), 'm-', label='Kinetic')
            #pylab.semilogx(ky, pylab.real(gamma), 'r-', label='Kinetic')
            #pylab.twinx()
            ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKinI", init=-0.01 + 0.01j)
            #ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKin", init= 0.02 + 0.045j)
Example #16
0
            plot_flag = flag
        elif flag in log_flags:
            log_flag = flag
        else:
            print "unknown flag %s" % flag

    if log_flag == 'log':
        log_function = pylab.log
    else:
        log_function = no_log

    if plot_flag == 'phases':
        hist = pylab.histogram(pylab.angle(values),bins=50)
        ax.plot((hist[1][:-1]+hist[1][1:])/2.0,log_function(hist[0]))
    elif plot_flag == 'histogram':
        hist = pylab.histogram2d(pylab.real(values),pylab.imag(values),bins=500)
        ax.imshow(log_function(hist[0]),extent=(hist[2][0],hist[2][-1],-hist[1][-1],-hist[1][0]),interpolation='nearest')
    else:
        ax.plot(pylab.real(values),pylab.imag(values),'.')
    return fig
    


if __name__ == "__main__":
    try:
        plot_phases(sys.argv[1],*sys.argv[2:])
        pylab.show()
    except:
        print """
Usage: plot_phases datafile [flags]
Example #17
0
for theta in [ 0.10]:
            Setup = { 'eta' : 4., 'kx' : 0.0, 'v_te' : mp.sqrt(2.), 'rho_te2' : 1., 'tau' : 1., 'theta' : 0. , 'm_ie' : 400., 'lambda_D2' : 0.}
            ky_list = pylab.logspace(pylab.log10(0.2), pylab.log10(40.), 101)
            #ky_list = pylab.linspace(20., 60.,101)
            Setup['theta'] = theta

            #ky, gamma, err = getGrowth(ky_list, Setup, disp="Gyro", init= 0.02 + 0.045j)
            #pylab.semilogx(ky, pylab.imag(gamma), 'b-', label='Gyro')
            #pylab.plot(ky, pylab.imag(gamma), 'b-', label='Gyro')

            #ky, gamma, err = getGrowth(ky_list, Setup, disp="Gyro1st", init=0.02+0.045j)
            #pylab.semilogx(ky[:350], pylab.imag(gamma)[:350], 'g-', label='Gyro $\\mathcal{O}{(1)}$')

            #ky, gamma, err = getGrowth(ky_list, Setup, disp="Fluid", init = 0.02 + 0.045j)
            #pylab.semilogx(ky, pylab.imag(gamma), 'r-', label='Fluid ')

            ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKin", init=-0.01 + 0.01j)
            #ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKin", init= 0.02 + 0.045j)
            pylab.semilogx(ky, pylab.imag(gamma), 'm-', label='Kinetic')
            #pylab.plot(ky, pylab.imag(gamma), 'm-', label='Kinetic')
            
pylab.legend(ncol=3, loc='best').draw_frame(0)

#pylab.ylim((-0.01,0.21))
#pylab.xlim((0.,10.))
pylab.xlabel("Poloidal Wavenumber $k_y/\\rho_{te}$")
pylab.ylabel("Growthrate $\\gamma_L [\\nu_{te}/L_n]$")
pylab.savefig("Dispersion_DCT.pdf", bbox_inches='tight')
pylab.savefig("Dispersion_DCT.png", bbox_inches='tight')