예제 #1
0
def metadata(inpfile='BOUT.inp', path='.', v=False):
    filepath = path + '/' + inpfile
    print(filepath)
    inp = read_inp(path=path, boutinp=inpfile)
    inp = parse_inp(inp)  #inp file
    print(path)
    outinfo = file_import(path + '/BOUT.dmp.0.nc')  #output data

    try:
        print(path)
        cxxinfo = no_comment_cxx(path=path, boutcxx='physics_code.cxx.ref')
        #evolved = get_evolved_cxx(cxxinfo)
        fieldkeys = get_evolved_cxx(cxxinfo)
        fieldkeys = ['[' + elem + ']' for elem in fieldkeys]
    except:
        print('cant find the cxx file')

    #gridoptions = {'grid':grid,'mesh':mesh}
    if '[mesh]' in list(inp.keys()):
        #IC = outinfo
        IC = read_grid(path + '/BOUT.dmp.0.nc')  #output data again
    elif 'grid' in inp['[main]']:
        gridname = inp['[main]']['grid']
        try:
            IC = read_grid(gridname)  #have to be an ansoulte file path for now
            print('IC: ', type(IC))
        # print IC.variables
        # print gridname
        except:
            #print gridname
            print('Fail to load the grid file')
    #print IC

    #print gridname
    #print len(IC)
    #print IC

    evolved = []
    collected = []
    ICscale = []

    # fieldkeys = ['[Ni]','[Te]','[Ti]','[Vi]','[rho]',
    #              '[Ajpar]','[Apar]','[vEBx]','[vEBy]','[vEBz]',
    #              '[jpar]','[phi]']

    #construct fieldkeys from cxx info
    #fieldkeys = ['['+x+']' for x in evolved]
    #fieldkeys = evolved

    #just look ahead and see what 3D fields have been output
    available = np.array([str(x) for x in outinfo])
    a = np.array([(len(outinfo[x].shape) == 4) for x in available])
    available = available[a]

    defaultIC = float(inp['[All]'].get('scale', 0.0))

    # print inp.keys()

    #figure out which fields are evolved
    print(fieldkeys)

    for section in list(inp.keys()):  #loop over section keys
        print('section: ', section)
        if section in fieldkeys:  #pick the relevant sections
            print(section)
            #print inp[section].get('evolve','True')
            #rint (inp[section].get('evolve','True')).lower().strip()
            if (inp[section].get('evolve', 'True').lower().strip() == 'true'
                ):  # and section[1:-1] in available :
                print('ok reading')
                evolved.append(section.strip('[]'))
                ICscale.append(float(inp[section].get('scale', defaultIC)))

        if inp[section].get('collect', 'False').lower().strip() == 'true':
            collected.append(section.strip('[]'))

    try:
        if inp['[physics]'].get('transport',
                                'False').lower().strip() == 'true':
            vEBstr = ['vEBx', 'vEBy', 'vEBz', 'vEBrms']
            [collected.append(item) for item in vEBstr]
    except:
        print('no [physics] key')

    meta = OrderedDict()

    class ValUnit(object):
        def __init__(self, value=0, units=''):
            self.u = units
            self.v = value

        def todict(self):
            return {'u': self.u, 'v': self.v}

    #def decode_valunit(d):

    def ToFloat(metaString):
        try:
            return float(metaString)
        except ValueError:
            return metaString

    #meta['evolved'] = ValUnit(evolved,'')
    meta['evolved'] = evolved
    meta['collected'] = collected
    meta['IC'] = np.array(ICscale)
    d = {}

    print('evolved: ', evolved)

    # read meta data from .inp file, this is whre most metadata get written
    for section in list(inp.keys()):
        if (('evolve' not in inp[section]) and ('first' not in inp[section])
            ):  #hacky way to exclude some less relevant metadata
            for elem in list(inp[section].keys()):
                meta[elem] = ValUnit(ToFloat(inp[section][elem]))
                d[elem] = np.array(ToFloat(inp[section][elem]))

    #read in some values from the grid(IC) and scale them as needed
    norms = {
        'Ni0': ValUnit(1.e14, 'cm^-3'),
        'bmag': ValUnit(1.0e4, 'gauss'),
        'Ni_x': ValUnit(1.e14, 'cm^-3'),
        'Te_x': ValUnit(1.0, 'eV'),
        'Ti_x': ValUnit(1.0, 'eV'),
        'Rxy': ValUnit(1, 'm'),
        'Bxy': ValUnit(1.0e4, 'gauss'),
        'Bpxy': ValUnit(1.0e4, 'gauss'),
        'Btxy': ValUnit(1.0e4, 'gauss'),
        'Zxy': ValUnit(1, 'm'),
        'dlthe': ValUnit(1, 'm'),
        'dx': ValUnit(1, 'm'),
        'hthe0': ValUnit(1, 'm')
    }

    availkeys = np.array([str(x) for x in outinfo])
    tmp1 = np.array([x for x in availkeys])
    #b = np.array([x if x not in available for x in a])
    tmp2 = np.array([x for x in tmp1 if x not in available])
    static_fields = np.array([x for x in tmp2 if x in list(norms.keys())])
    #static_fields = tmp2

    #print availkeys
    # print meta.keys()
    #print IC.variables.keys()
    # print tmp1
    # print tmp2

    for elem in static_fields:
        print('elem: ', elem)
        meta[elem] = ValUnit(IC.variables[elem][:] * norms[elem].v,
                             norms[elem].u)
        d[elem] = np.array(IC.variables[elem][:] * norms[elem].v)

    for elem in IC.variables:
        if elem not in meta:
            if elem in list(norms.keys()):
                meta[elem] = ValUnit(IC.variables[elem][:] * norms[elem].v,
                                     norms[elem].u)
                d[elem] = np.array(IC.variables[elem][:] * norms[elem].v)
            else:
                meta[elem] = IC.variables[elem][:]
                d[elem] = IC.variables[elem][:]

    #print d.keys()

    #if case some values are missing
    default = {
        'bmag': 1,
        'Ni_x': 1,
        'NOUT': 100,
        'TIMESTEP': 1,
        'MZ': 32,
        'AA': 1,
        'Zeff': ValUnit(1, ''),
        'ZZ': 1,
        'zlowpass': 0.0,
        'transport': False
    }
    diff = set(default.keys()).difference(set(d.keys()))

    for elem in diff:
        #print 'diff: ',elem
        meta[elem] = default[elem]
        d[elem] = np.array(default[elem])

    #print meta.keys()
    #print d.keys()

    #print meta['zlowpass']

    if meta['zlowpass'] != 0:
        print(meta['MZ'].v, meta['zlowpass'].v)
        meta['maxZ'] = int(np.floor(meta['MZ'].v * meta['zlowpass'].v))
    else:
        meta['maxZ'] = 5

    #meta['nx'] = nx
    #meta['ny']= ny
    meta['dt'] = meta['TIMESTEP']

    #nx,ny  = d['Rxy'].shape

    #print meta['AA'].v

    meta['rho_s'] = ValUnit(1.02e2 * np.sqrt(d['AA'] * d['Te_x']) /
                            (d['ZZ'] * d['bmag']),
                            'cm')  # ion gyrorad at T_e, in cm
    meta['rho_i'] = ValUnit(
        1.02e2 * np.sqrt(d['AA'] * d['Ti_x']) / (d['ZZ'] * d['bmag']), 'cm')
    meta['rho_e'] = ValUnit(2.38 * np.sqrt(d['Te_x']) / (d['bmag']), 'cm')

    meta['fmei'] = ValUnit(1. / 1836.2 / d['AA'])

    meta['lambda_ei'] = 24. - np.log(old_div(np.sqrt(d['Ni_x']), d['Te_x']))
    meta['lambda_ii'] = 23. - np.log(d['ZZ']**3 * np.sqrt(2. * d['Ni_x']) /
                                     (d['Ti_x']**1.5))  #

    meta['wci'] = 1.0 * 9.58e3 * d['ZZ'] * d['bmag'] / d['AA']  # ion gyrofrteq
    meta['wpi'] = 1.32e3 * d['ZZ'] * np.sqrt(old_div(
        d['Ni_x'], d['AA']))  # ion plasma freq

    meta['wce'] = 1.78e7 * d['bmag']  #electron gyrofreq
    meta['wpe'] = 5.64e4 * np.sqrt(d['Ni_x'])  #electron plasma freq

    meta['v_the'] = 4.19e7 * np.sqrt(d['Te_x'])  #cm/s
    meta['v_thi'] = 9.79e5 * np.sqrt(old_div(d['Ti_x'], d['AA']))  #cm/s
    meta['c_s'] = 9.79e5 * np.sqrt(
        5.0 / 3.0 * d['ZZ'] * d['Te_x'] / d['AA'])  #
    meta['v_A'] = 2.18e11 * np.sqrt(old_div(1.0, (d['AA'] * d['Ni_x'])))

    meta['nueix'] = 2.91e-6 * d['Ni_x'] * meta['lambda_ei'] / d['Te_x']**1.5  #
    meta['nuiix'] = 4.78e-8 * d['ZZ']**4. * d['Ni_x'] * meta['lambda_ii'] / d[
        'Ti_x']**1.5 / np.sqrt(d['AA'])  #
    meta['nu_hat'] = meta['Zeff'].v * meta['nueix'] / meta['wci']

    meta['L_d'] = 7.43e2 * np.sqrt(old_div(d['Te_x'], d['Ni_x']))
    meta['L_i_inrt'] = 2.28e7 * np.sqrt(old_div(
        d['AA'], d['Ni_x'])) / d['ZZ']  #ion inertial length in cm
    meta['L_e_inrt'] = 5.31e5 * np.sqrt(d['Ni_x'])  #elec inertial length in cm

    meta['Ve_x'] = 4.19e7 * d['Te_x']

    meta['R0'] = old_div((d['Rxy'].max() + d['Rxy'].min()), 2.0)

    print(d['Rxy'].mean(1))
    print(d['ZMAX'])
    print(d['ZMIN'])
    meta['L_z'] = 1e2 * 2 * np.pi * d['Rxy'].mean(1) * (
        d['ZMAX'] - d['ZMIN'])  # in cm toroidal range
    meta['dz'] = (d['ZMAX'] - d['ZMIN'])

    #meta['lbNorm']=meta['L_z']*(d['Bpxy']/d['Bxy']).mean(1)     #-binormal coord range [cm]
    meta['lbNorm'] = meta['L_z'] * (old_div(d['Bxy'], d['Bpxy'])).mean(1)

    #meta['zPerp']=np.array(meta['lbNorm']).mean*np.array(range(d['MZ']))/(d['MZ']-1)
    #let's calculate some profile properties
    dx = np.gradient(d['Rxy'])[0]
    meta['L'] = 1.0 * 1e2 * dx * (meta['Ni0'].v) / np.gradient(
        meta['Ni0'].v)[0] / meta['rho_s'].v

    meta['w_Ln'] = old_div(meta['c_s'], (np.min(abs(meta['L'])) * meta['wci'] *
                                         meta['rho_s'].v))  #normed to wci

    AA = meta['AA'].v
    ZZ = d['ZZ']
    Te_x = d['Te_x']
    Ti_x = d['Ti_x']
    fmei = meta['fmei'].v

    meta['lpar'] = 1e2 * (
        (old_div(d['Bxy'], d['Bpxy'])) * d['dlthe']).sum(1) / meta[
            'rho_s'].v  #-[normed], average over flux surfaces, parallel length

    #yes dlthe is always the vertical displacement
    #dlthe = (hthe0*2 pi)/nz
    #meta['lpar']=1e2*(d['Bxy']/d['Bpxy']).mean(1)*d['dlthe'].mean(1) #function of x
    meta['sig_par'] = old_div(1.0, (fmei * 0.51 * meta['nu_hat']))
    #meta['heat_nue'] = ((2*np.pi/meta['lpar'])**2)/(fmei*meta['nu_hat'])
    #kz_e = kz_i*(rho_e/rho_i)
    # kz_s = kz_i*(rho_s/rho_i)
    # kz_i = (TWOPI/L_z)*(indgen((*current_str).fft.nz+1))*rho_i

    # knorm = (TWOPI/lbNorm)*(indgen((*current_str).fft.nz+1))*rho_s

    # for now just translate
    for elem in meta:
        if type(meta[elem]).__name__ == 'ValUnit':
            meta[elem] = {'u': meta[elem].u, 'v': meta[elem].v}

    print('meta: ', type(meta))
    return meta
예제 #2
0
from __future__ import division
from builtins import zip
from builtins import range
from past.utils import old_div
import numpy as np
from boututils import file_import, surface_average, showdata
from boutdata import collect
from pylab import plot, show, annotate, xlabel, ylabel, figure, xlim, ylim, legend, gca
import os

 
path='./data'

gfile='../cbm18_dens8.grid_nx68ny64.nc'
  
g = file_import(gfile)
   
var=collect("P", path=path)   
   
sol=surface_average(var, g)
#sol=np.mean(var,axis=3)

p0av=collect("P0", path=path)

q=np.zeros(sol.shape)

for i in range(sol.shape[1]):
    q[:,i]=sol[:,i]+p0av[:,0]
    
    
psixy=g.get('psixy')
예제 #3
0
    mayavi.add_source(src)
    mayavi.add_module(Outline())
    g = GridPlane()
    g.grid_plane.axis = 'x'
    mayavi.add_module(g)


if __name__ == '__main__':
    from boutdata import collect
    from boututils import file_import

    path = "/media/449db594-b2fe-4171-9e79-2d9b76ac69b6/runs/data_33/"
    #path="/home/ben/run4"

    #g = file_import("../cbm18_dens8.grid_nx68ny64.nc")
    g = file_import("data/cbm18_8_y064_x516_090309.nc")
    #g = file_import("/home/ben/run4/reduced_y064_x256.nc")

    data = collect("P", tind=50, path=path)
    data = data[0, :, :, :]
    s = np.shape(data)
    nz = s[2]

    bkgd = collect("P0", path=path)
    for z in range(nz):
        data[:, :, z] += bkgd

    # Create a structured grid
    sgrid = create_grid(g, data, 10)

    w = tvtk.XMLStructuredGridWriter(input=sgrid, file_name='sgrid.vts')
예제 #4
0
    mayavi.add_source(src)
    mayavi.add_module(Outline())
    g = GridPlane()
    g.grid_plane.axis = 'x'
    mayavi.add_module(g)

if __name__ == '__main__':
    from boutdata import collect
    from boututils import file_import
    
    path = "/hwdisks/data/adm518/data_33/"
    #path = "/media/449db594-b2fe-4171-9e79-2d9b76ac69b6/runs/data_33/"
    #path="/home/ben/run4"

    #g = file_import("../cbm18_dens8.grid_nx68ny64.nc")
    g = file_import("/hwdisks/data/bd512/elm-pb/cbm18_8_y064_x516_090309.nc")
    #g = file_import("/home/ben/run4/reduced_y064_x256.nc")
    
    data = collect("P", tind=50, path=path)
    data = data[0,:,:,:]
    s = np.shape(data)
    nz = s[2]
    
    bkgd = collect("P0", path=path)
    for z in range(nz):
        data[:,:,z] += bkgd

    # Create a structured grid
    sgrid = create_grid(g, data, 10)
    
예제 #5
0
파일: read_inp.py 프로젝트: AlxMar/BOUT-2.0
def metadata(inpfile='BOUT.inp',path ='.',v=False):    
    filepath = path+'/'+inpfile
    print filepath
    inp = read_inp(path=path,boutinp=inpfile)
    inp = parse_inp(inp) #inp file
    print path
    outinfo = file_import(path+'/BOUT.dmp.0.nc') #output data
    
    try:
       print path
       cxxinfo = no_comment_cxx(path=path,boutcxx='physics_code.cxx.ref')
       #evolved = get_evolved_cxx(cxxinfo)
       fieldkeys = get_evolved_cxx(cxxinfo)
       fieldkeys = ['['+elem+']' for elem  in fieldkeys]
    except:
       print 'cant find the cxx file'
    
    
    #gridoptions = {'grid':grid,'mesh':mesh}
    if '[mesh]' in inp.keys():
       #IC = outinfo  
       IC = read_grid(path+'/BOUT.dmp.0.nc') #output data again
    elif 'grid' in inp['[main]']:
       gridname = inp['[main]']['grid']
       try:
          IC = read_grid(gridname) #have to be an ansoulte file path for now
          print 'IC: ',type(IC)
       # print IC.variables
       # print gridname
       except:
       #print gridname
          print 'Fail to load the grid file'
    #print IC

    #print gridname
    #print len(IC)
    #print IC
       
    evolved = []
    collected =[]
    ICscale = []
   
    # fieldkeys = ['[Ni]','[Te]','[Ti]','[Vi]','[rho]',
    #              '[Ajpar]','[Apar]','[vEBx]','[vEBy]','[vEBz]',
    #              '[jpar]','[phi]']
    
    #construct fieldkeys from cxx info
    #fieldkeys = ['['+x+']' for x in evolved]
    #fieldkeys = evolved

    #just look ahead and see what 3D fields have been output
    available = np.array([str(x) for x in outinfo])
    a = np.array([(len(outinfo[x].shape) ==4) for x in available])
    available = available[a]
    
    
    
    defaultIC = float(inp['[All]'].get('scale',0.0))

    # print inp.keys()
    
    #figure out which fields are evolved
    print fieldkeys
    
    for section in inp.keys(): #loop over section keys 
       print 'section: ', section
       if section in fieldkeys: #pick the relevant sections
          print section
          #print inp[section].get('evolve','True')
          #rint (inp[section].get('evolve','True')).lower().strip()
          if (inp[section].get('evolve','True').lower().strip() == 'true'):# and section[1:-1] in available :
             print 'ok reading'
             evolved.append(section.strip('[]'))
             ICscale.append(float(inp[section].get('scale',defaultIC)))
            
       if inp[section].get('collect','False').lower().strip() == 'true':
          collected.append(section.strip('[]'))
    
        
    
             
    try:         
       if inp['[physics]'].get('transport','False').lower().strip() == 'true':
          vEBstr = ['vEBx','vEBy','vEBz','vEBrms']     
          [collected.append(item) for item in vEBstr]
    except:
       print 'no [physics] key'
                
    meta = OrderedDict()
    
    class ValUnit(object):
       def __init__(self,value=0,units=''):
          self.u = units
          self.v = value
       def todict(self):
          return {'u':self.u,'v':self.v}

   

    #def decode_valunit(d):
       
    
    def ToFloat(metaString):
       try:
          return float(metaString)
       except ValueError:
          return metaString
    
    #meta['evolved'] = ValUnit(evolved,'')
    meta['evolved'] = evolved
    meta['collected'] = collected
    meta['IC']= np.array(ICscale)
    d = {}

    print 'evolved: ',evolved

    # read meta data from .inp file, this is whre most metadata get written
    for section in inp.keys():
        if (('evolve' not in inp[section]) and ('first' not in inp[section])): #hacky way to exclude some less relevant metadata
           for elem in inp[section].keys():
              meta[elem] = ValUnit(ToFloat(inp[section][elem]))
              d[elem] = np.array(ToFloat(inp[section][elem]))
              
    #read in some values from the grid(IC) and scale them as needed
    norms = {'Ni0':ValUnit(1.e14,'cm^-3'),'bmag':ValUnit(1.0e4,'gauss'),
             'Ni_x':ValUnit(1.e14,'cm^-3'),
             'Te_x':ValUnit(1.0,'eV'),'Ti_x':ValUnit(1.0,'eV'),'Rxy':ValUnit(1,'m'),
             'Bxy':ValUnit(1.0e4,'gauss'),'Bpxy':ValUnit(1.0e4,'gauss'),
             'Btxy':ValUnit(1.0e4,'gauss'),'Zxy':ValUnit(1,'m'),
             'dlthe':ValUnit(1,'m'),'dx':ValUnit(1,'m'),'hthe0':ValUnit(1,'m')}

    availkeys = np.array([str(x) for x in outinfo])
    tmp1 = np.array([x for x in availkeys])
    #b = np.array([x if x not in available for x in a])
    tmp2 = np.array([x for x in tmp1 if x not in available])
    static_fields = np.array([x for x in tmp2 if x in norms.keys()])
    #static_fields = tmp2
    
    #print availkeys
    # print meta.keys()
    #print IC.variables.keys()
    # print tmp1
    # print tmp2
    

    for elem in static_fields:
       print 'elem: ',elem
       meta[elem] = ValUnit(IC.variables[elem][:]*norms[elem].v,norms[elem].u)
       d[elem] = np.array(IC.variables[elem][:]*norms[elem].v)
    
    for elem in IC.variables:
       if elem not in meta:
          if elem in norms.keys():
             meta[elem] = ValUnit(IC.variables[elem][:]*norms[elem].v,norms[elem].u)
             d[elem] = np.array(IC.variables[elem][:]*norms[elem].v)
          else:
            meta[elem] = IC.variables[elem][:]
            d[elem] = IC.variables[elem][:] 
       
    #print d.keys()

    #if case some values are missing   
    default = {'bmag':1,'Ni_x':1,'NOUT':100,'TIMESTEP':1,
               'MZ':32,'AA':1,'Zeff':ValUnit(1,''),'ZZ':1,
               'zlowpass':0.0,'transport':False}
    diff = set(default.keys()).difference(set(d.keys()))
       
    for elem in diff:
       #print 'diff: ',elem
       meta[elem] = default[elem]
       d[elem] = np.array(default[elem])

    #print meta.keys()
    #print d.keys()
    
    #print meta['zlowpass']
    
       
    if meta['zlowpass'] != 0:
          print meta['MZ'].v, meta['zlowpass'].v
          meta['maxZ'] = int(np.floor(meta['MZ'].v*meta['zlowpass'].v))
    else:
       meta['maxZ'] = 5
       
    #meta['nx'] = nx
    #meta['ny']= ny
    meta['dt'] = meta['TIMESTEP'] 
    
    
    #nx,ny  = d['Rxy'].shape
       
       
    #print meta['AA'].v
    
    meta['rho_s'] = ValUnit(1.02e2*np.sqrt(d['AA']*d['Te_x'])/(d['ZZ']* d['bmag']),'cm')   # ion gyrorad at T_e, in cm 
    meta['rho_i'] = ValUnit(1.02e2*np.sqrt(d['AA']*d['Ti_x'])/(d['ZZ']* d['bmag']),'cm') 
    meta['rho_e'] = ValUnit(2.38*np.sqrt(d['Te_x'])/(d['bmag']),'cm') 
    
    meta['fmei']  = ValUnit(1./1836.2/d['AA'])   
    
    meta['lambda_ei'] = 24.-np.log(np.sqrt(d['Ni_x'])/d['Te_x']) ;
    meta['lambda_ii'] = 23.-np.log(d['ZZ']**3 * np.sqrt(2.*d['Ni_x'])/(d['Ti_x']**1.5)) #

    meta['wci']       = 1.0*9.58e3*d['ZZ']*d['bmag']/d['AA'] # ion gyrofrteq
    meta['wpi']       = 1.32e3*d['ZZ']*np.sqrt(d['Ni_x']/d['AA']) # ion plasma freq 

    meta['wce']       = 1.78e7*d['bmag'] #electron gyrofreq
    meta['wpe']       = 5.64e4*np.sqrt(d['Ni_x'])#electron plasma freq
    
    meta['v_the']    = 4.19e7*np.sqrt(d['Te_x'])#cm/s
    meta['v_thi']    = 9.79e5*np.sqrt(d['Ti_x']/d['AA']) #cm/s
    meta['c_s']      = 9.79e5*np.sqrt(5.0/3.0 * d['ZZ'] * d['Te_x']/d['AA'])#
    meta['v_A']     = 2.18e11*np.sqrt(1.0/(d['AA'] * d['Ni_x']))
    
    meta['nueix']     = 2.91e-6*d['Ni_x']*meta['lambda_ei']/d['Te_x']**1.5 #
    meta['nuiix']     = 4.78e-8*d['ZZ']**4.*d['Ni_x']*meta['lambda_ii']/d['Ti_x']**1.5/np.sqrt(d['AA']) #
    meta['nu_hat']    = meta['Zeff'].v*meta['nueix']/meta['wci'] 
    
    meta['L_d']      = 7.43e2*np.sqrt(d['Te_x']/d['Ni_x'])
    meta['L_i_inrt']  = 2.28e7*np.sqrt(d['AA']/d['Ni_x'])/ d['ZZ'] #ion inertial length in cm
    meta['L_e_inrt']  = 5.31e5*np.sqrt(d['Ni_x']) #elec inertial length in cm
    
    meta['Ve_x'] = 4.19e7*d['Te_x']

    
    meta['R0'] =  (d['Rxy'].max()+d['Rxy'].min())/2.0 
    
 
    print d['Rxy'].mean(1) 
    print d['ZMAX']
    print  d['ZMIN'] 
    meta['L_z'] = 1e2 * 2*np.pi * d['Rxy'].mean(1) *(d['ZMAX'] - d['ZMIN']) # in cm toroidal range
    meta['dz'] = (d['ZMAX'] - d['ZMIN'])
 
    #meta['lbNorm']=meta['L_z']*(d['Bpxy']/d['Bxy']).mean(1)     #-binormal coord range [cm]
    meta['lbNorm']=meta['L_z']*(d['Bxy']/d['Bpxy']).mean(1)
    
    #meta['zPerp']=np.array(meta['lbNorm']).mean*np.array(range(d['MZ']))/(d['MZ']-1) 
  #let's calculate some profile properties
    dx = np.gradient(d['Rxy'])[0]
    meta['L'] = 1.0*1e2*dx*(meta['Ni0'].v)/np.gradient(meta['Ni0'].v)[0]/meta['rho_s'].v
    
    meta['w_Ln']     =  meta['c_s']/(np.min(abs(meta['L']))*meta['wci'] *meta['rho_s'].v) #normed to wci

    AA = meta['AA'].v
    ZZ = d['ZZ']
    Te_x = d['Te_x']
    Ti_x = d['Ti_x']
    fmei = meta['fmei'].v
    
    meta['lpar'] =1e2*((d['Bxy']/d['Bpxy'])*d['dlthe']).sum(1)/meta['rho_s'].v #-[normed], average over flux surfaces, parallel length

    #yes dlthe is always the vertical displacement 
    #dlthe = (hthe0*2 pi)/nz
    #meta['lpar']=1e2*(d['Bxy']/d['Bpxy']).mean(1)*d['dlthe'].mean(1) #function of x
    meta['sig_par'] = 1.0/(fmei*0.51*meta['nu_hat'])
    #meta['heat_nue'] = ((2*np.pi/meta['lpar'])**2)/(fmei*meta['nu_hat'])
    #kz_e = kz_i*(rho_e/rho_i)
    # kz_s = kz_i*(rho_s/rho_i)
    # kz_i = (TWOPI/L_z)*(indgen((*current_str).fft.nz+1))*rho_i
    
    # knorm = (TWOPI/lbNorm)*(indgen((*current_str).fft.nz+1))*rho_s

    # for now just translate
    for elem in meta:
       if type(meta[elem]).__name__ =='ValUnit':
          meta[elem] = {'u':meta[elem].u,'v':meta[elem].v}
    
       
    print 'meta: ', type(meta)
    return meta
예제 #6
0
import numpy as np
from boututils import moment_xyzt, file_import
from boutdata  import collect
import os
from scipy.io import readsav

#Dynamic matplotlib settings
from matplotlib import rcParams
rcParams['font.size'] = 20.
rcParams['legend.fontsize'] = 'small'
rcParams['lines.linewidth'] = 2

if not os.path.exists('image'):
   os.makedirs('image')

g = file_import('../cbm18_dens8.grid_nx68ny64.nc')
psi = old_div((g['psixy'][:, 32] - g['psi_axis']), (g['psi_bndry'] - g['psi_axis']))

path = './data'

plt.figure()

#p0 = transpose(readsav(os.path.join(path, 'p0.idl.dat'))['p0'])
p0=collect('P0', path=path)

#dcp = transpose(readsav(os.path.join(path, 'dcp.idl.dat'))['dcp'])
p=collect('P', path=path)
res = moment_xyzt(p,'RMS','DC')
rmsp = res.rms
dcp = res.dc
nt = dcp.shape[2]
예제 #7
0
path = './data'

t_array = collect('t_array', path=path)
save('t_array.dat', t_array)
p0 = collect('P0', path=path)
save('p0.dat', p0)

# n0=collect('n0', path=path)
# save('n0.dat', n0
# ti0=collect('ti0', path=path)
# save('ti0.dat', ti0)
# te0=collect('te0', path=path)
# save('te0.idl.dat', te0)

gfile = file_import('./cbm18_dens8.grid_nx68ny64.nc')

p = collect('P', path=path)
save('p.dat', p)
res = moment_xyzt(p, 'RMS', 'DC')
rmsp = res.rms
dcp = res.dc
save('rmsp.dat', rmsp)
save('dcp.dat', dcp)
elmsp = elm_size(dcp, p0, gfile, yind=32, Bbar=gfile['bmag'])
save('elmsp.dat', elmsp)

figure(0)
plot(t_array, elmsp.s2, 'k-')
xlabel('t/Ta')
ylabel('Elm size')
예제 #8
0
from __future__ import division
from builtins import range
from past.utils import old_div
import numpy as np
import matplotlib.pyplot as plt
from boututils import file_import
from matplotlib.ticker import FixedFormatter, FormatStrFormatter, AutoLocator, AutoMinorLocator

g = file_import("./cbm18_dens8.grid_nx68ny64.nc")

majorLocator   = AutoLocator()
majorFormatter = FormatStrFormatter('%3.0e')
minorLocator   = AutoMinorLocator()
Fm = FixedFormatter(['0','$1 \\times 10^4$','$2 \\times  10^4$','$3 \\times 10^4$','$4 \\times 10^4$'])
Fm2 = FixedFormatter(['0','$2 \\times 10^5$','$4 \\times  10^5$','$6 \\times 10^5$'])

bxy=g.get('Bxy')
p=g.get('pressure')
jpar0=g.get('Jpar0')
psixy=g.get('psixy')
btxy=g.get('Btxy')
shiftangle=g.get('ShiftAngle')

nx=g.get('nx')
ny=g.get('ny')

q = np.zeros((nx, ny))
for i in range(ny):
    q[:,i] = old_div(- shiftangle, (2 * np.pi))

예제 #9
0
from __future__ import division
from builtins import range
from past.utils import old_div
import numpy as np
import matplotlib.pyplot as plt
from boututils import file_import
from matplotlib.ticker import FixedFormatter, FormatStrFormatter, AutoLocator, AutoMinorLocator

g = file_import("./cbm18_dens8.grid_nx68ny64.nc")

majorLocator = AutoLocator()
majorFormatter = FormatStrFormatter('%3.0e')
minorLocator = AutoMinorLocator()
Fm = FixedFormatter([
    '0', '$1 \\times 10^4$', '$2 \\times  10^4$', '$3 \\times 10^4$',
    '$4 \\times 10^4$'
])
Fm2 = FixedFormatter(
    ['0', '$2 \\times 10^5$', '$4 \\times  10^5$', '$6 \\times 10^5$'])

bxy = g.get('Bxy')
p = g.get('pressure')
jpar0 = g.get('Jpar0')
psixy = g.get('psixy')
btxy = g.get('Btxy')
shiftangle = g.get('ShiftAngle')

nx = g.get('nx')
ny = g.get('ny')

q = np.zeros((nx, ny))
예제 #10
0
#    mayavi.new_scene()
    src = VTKDataSource(data=sgrid)
    e.add_source(src)
    e.add_module(Outline())
    g = GridPlane()
    g.grid_plane.axis = 'x'
    e.add_module(g)

if __name__ == '__main__':
    from boutdata import collect
    from boututils import file_import
    
    #path = "/media/449db594-b2fe-4171-9e79-2d9b76ac69b6/runs/data_33/"
    path="../data"

    g = file_import("../bout.grd.nc")
    #g = file_import("../cbm18_8_y064_x516_090309.nc")
    #g = file_import("/home/ben/run4/reduced_y064_x256.nc")
    
    data = collect("P", tind=10, path=path)
    data = data[0,:,:,:]
    s = np.shape(data)
    nz = s[2]
    
    #bkgd = collect("P0", path=path)
    #for z in range(nz):
     #   data[:,:,z] += bkgd

    # Create a structured grid
    sgrid = create_grid(g, data, 1)
    
예제 #11
0
def interpolate2grid(prof, psi, grid_path, dim=2, pf='decreasing'):
    '''Interpolate given profile onto the specified BOUT++ grid.

    Parameters:
    prof -- 1D array, containing the profile (Q) to interpolate
        onto the BOUT++ grid. The profile should be a flux function
        such that Q = Q(psi)
    psi -- 1D array, containing the normalized poloidal flux
        (i.e. 0 on the magnetic axis and 1 on the separatrix)
    grid_path -- str, path to the grid file to interpolate onto
    dim -- int, valid options are: 1, 2
        dim specifies dimension of resulting interpolated profile;
        for example, many of the BOUT++ equilibrium profiles
        (e.g. pressure, jpar, etc) are specified as 2D grids.
        Dimensions of 3 or higher (which are *not* needed for
        axisymmetric equilibria) are not supported.
    pf -- str, valid options are: 'decreasing', 'flat', 'none'.
        As the flux decreases moving radially outwards in
        the private flux (PF) region, a simple flux function formalism is
        no longer valid in this region. Instead, we must determine
        an appropriate model for the PF region.

        --  'decreasing':
            Create a dummy flux variable, psi', defined as
                        psi' = 1 + |psi - 1|
            and then use the mapping Q_{PF}(psi') = Q_{non-PF}
            such that the profile in the PF region behaves
            similarly to the profile in the SOL

        --  'flat':
            Gives a flat profile in the PF region, with the
            constant value determined by the value of the
            profile on the separatrix

        --  'none':
            Simply uses the flux function formalism, i.e. Q = Q(psi).
            For equilibrium values, such as the pressure, this
            will give an unphysical grid and is *NOT* recommended

    Returns:
    An array of the speficied dimension interpolated onto the
    BOUT++ grid. This array can subsequently be written to
    the grid file for use in simulations.

    '''
    g = file_import(grid_path)

    if dim == 1:
        psi_grid = grid.grid2psi(g, vector=True)
        prof_interp = interpolate.spline(psi, prof, psi_grid)

    # TODO: Generalize this to double null
    elif dim == 2:
        prof_interp = np.zeros(g['Rxy'].shape)


       # PF region:

        # Determine the poloidal indices of the PF region
        pf_ind1 = np.arange(0, (g['jyseps1_1'] + 1))
        pf_ind2 = np.arange((g['jyseps2_2'] + 1), prof_interp.shape[1])
        pol_ind = np.concatenate((pf_ind1, pf_ind2))

        # Restricting ourselves to the poloidal PF domain identified above,
        # the PF region is fully specified by radial indices where psi < 1
        psi_grid = grid.grid2psi(g, vector=True, yind=pol_ind[0])
        rad_ind = np.where(psi_grid < 1.0)
        sep_ind = np.max(rad_ind) + 1

        if pf == 'decreasing':
            psi_dummy = 1.0 + np.abs(psi_grid[rad_ind] - 1)
            prof_interp[0:sep_ind, pol_ind] = interpolate.spline(
                    psi, prof, psi_dummy)[:, np.newaxis]
        elif pf == 'flat':
            prof_interp[0:sep_ind, pol_ind] = interpolate.spline(
                    psi, prof, 1.0)
        elif pf == 'none':
            prof_interp[0:sep_ind, pol_ind] = interpolate.spline(
                    psi, prof, psi_grid[rad_ind])[:, np.newaxis]


        # Non-PF region 1:

        # This region lies in the poloidal PF domain identified above,
        # but it does *not* satisfy psi < 1 (that is, this region is
        # in the SOL)
        rad_ind = np.where(psi_grid >= 1.0)
        prof_interp[sep_ind:, pol_ind] = interpolate.spline(
                psi, prof, psi_grid[rad_ind])[:, np.newaxis]


        # Non-PF region 2:

        # The entire radial domain in this region (core and SOL)
        # are *not* in the PF region
        psi_grid = grid.grid2psi(g, vector=True)
        pol_ind = np.arange(g['jyseps1_1'] + 1, g['jyseps2_2'])
        prof_interp[:, pol_ind] = interpolate.spline(
                psi, prof, psi_grid)[:, np.newaxis]

    else:
        raise ValueError('Interpolation not supported above 2D')

    return prof_interp
예제 #12
0
def metadata(inpfile="BOUT.inp", path=".", v=False):
    filepath = path + "/" + inpfile
    print(filepath)
    inp = read_inp(path=path, boutinp=inpfile)
    inp = parse_inp(inp)  # inp file
    print(path)
    outinfo = file_import(path + "/BOUT.dmp.0.nc")  # output data

    try:
        print(path)
        cxxinfo = no_comment_cxx(path=path, boutcxx="physics_code.cxx.ref")
        # evolved = get_evolved_cxx(cxxinfo)
        fieldkeys = get_evolved_cxx(cxxinfo)
        fieldkeys = ["[" + elem + "]" for elem in fieldkeys]
    except:
        print("cant find the cxx file")

    # gridoptions = {'grid':grid,'mesh':mesh}
    if "[mesh]" in list(inp.keys()):
        # IC = outinfo
        IC = read_grid(path + "/BOUT.dmp.0.nc")  # output data again
    elif "grid" in inp["[main]"]:
        gridname = inp["[main]"]["grid"]
        try:
            IC = read_grid(gridname)  # have to be an ansoulte file path for now
            print("IC: ", type(IC))
        # print IC.variables
        # print gridname
        except:
            # print gridname
            print("Fail to load the grid file")
    # print IC

    # print gridname
    # print len(IC)
    # print IC

    evolved = []
    collected = []
    ICscale = []

    # fieldkeys = ['[Ni]','[Te]','[Ti]','[Vi]','[rho]',
    #              '[Ajpar]','[Apar]','[vEBx]','[vEBy]','[vEBz]',
    #              '[jpar]','[phi]']

    # construct fieldkeys from cxx info
    # fieldkeys = ['['+x+']' for x in evolved]
    # fieldkeys = evolved

    # just look ahead and see what 3D fields have been output
    available = np.array([str(x) for x in outinfo])
    a = np.array([(len(outinfo[x].shape) == 4) for x in available])
    available = available[a]

    defaultIC = float(inp["[All]"].get("scale", 0.0))

    # print inp.keys()

    # figure out which fields are evolved
    print(fieldkeys)

    for section in list(inp.keys()):  # loop over section keys
        print("section: ", section)
        if section in fieldkeys:  # pick the relevant sections
            print(section)
            # print inp[section].get('evolve','True')
            # rint (inp[section].get('evolve','True')).lower().strip()
            if inp[section].get("evolve", "True").lower().strip() == "true":  # and section[1:-1] in available :
                print("ok reading")
                evolved.append(section.strip("[]"))
                ICscale.append(float(inp[section].get("scale", defaultIC)))

        if inp[section].get("collect", "False").lower().strip() == "true":
            collected.append(section.strip("[]"))

    try:
        if inp["[physics]"].get("transport", "False").lower().strip() == "true":
            vEBstr = ["vEBx", "vEBy", "vEBz", "vEBrms"]
            [collected.append(item) for item in vEBstr]
    except:
        print("no [physics] key")

    meta = OrderedDict()

    class ValUnit(object):
        def __init__(self, value=0, units=""):
            self.u = units
            self.v = value

        def todict(self):
            return {"u": self.u, "v": self.v}

    # def decode_valunit(d):

    def ToFloat(metaString):
        try:
            return float(metaString)
        except ValueError:
            return metaString

    # meta['evolved'] = ValUnit(evolved,'')
    meta["evolved"] = evolved
    meta["collected"] = collected
    meta["IC"] = np.array(ICscale)
    d = {}

    print("evolved: ", evolved)

    # read meta data from .inp file, this is whre most metadata get written
    for section in list(inp.keys()):
        if ("evolve" not in inp[section]) and (
            "first" not in inp[section]
        ):  # hacky way to exclude some less relevant metadata
            for elem in list(inp[section].keys()):
                meta[elem] = ValUnit(ToFloat(inp[section][elem]))
                d[elem] = np.array(ToFloat(inp[section][elem]))

    # read in some values from the grid(IC) and scale them as needed
    norms = {
        "Ni0": ValUnit(1.0e14, "cm^-3"),
        "bmag": ValUnit(1.0e4, "gauss"),
        "Ni_x": ValUnit(1.0e14, "cm^-3"),
        "Te_x": ValUnit(1.0, "eV"),
        "Ti_x": ValUnit(1.0, "eV"),
        "Rxy": ValUnit(1, "m"),
        "Bxy": ValUnit(1.0e4, "gauss"),
        "Bpxy": ValUnit(1.0e4, "gauss"),
        "Btxy": ValUnit(1.0e4, "gauss"),
        "Zxy": ValUnit(1, "m"),
        "dlthe": ValUnit(1, "m"),
        "dx": ValUnit(1, "m"),
        "hthe0": ValUnit(1, "m"),
    }

    availkeys = np.array([str(x) for x in outinfo])
    tmp1 = np.array([x for x in availkeys])
    # b = np.array([x if x not in available for x in a])
    tmp2 = np.array([x for x in tmp1 if x not in available])
    static_fields = np.array([x for x in tmp2 if x in list(norms.keys())])
    # static_fields = tmp2

    # print availkeys
    # print meta.keys()
    # print IC.variables.keys()
    # print tmp1
    # print tmp2

    for elem in static_fields:
        print("elem: ", elem)
        meta[elem] = ValUnit(IC.variables[elem][:] * norms[elem].v, norms[elem].u)
        d[elem] = np.array(IC.variables[elem][:] * norms[elem].v)

    for elem in IC.variables:
        if elem not in meta:
            if elem in list(norms.keys()):
                meta[elem] = ValUnit(IC.variables[elem][:] * norms[elem].v, norms[elem].u)
                d[elem] = np.array(IC.variables[elem][:] * norms[elem].v)
            else:
                meta[elem] = IC.variables[elem][:]
                d[elem] = IC.variables[elem][:]

    # print d.keys()

    # if case some values are missing
    default = {
        "bmag": 1,
        "Ni_x": 1,
        "NOUT": 100,
        "TIMESTEP": 1,
        "MZ": 32,
        "AA": 1,
        "Zeff": ValUnit(1, ""),
        "ZZ": 1,
        "zlowpass": 0.0,
        "transport": False,
    }
    diff = set(default.keys()).difference(set(d.keys()))

    for elem in diff:
        # print 'diff: ',elem
        meta[elem] = default[elem]
        d[elem] = np.array(default[elem])

    # print meta.keys()
    # print d.keys()

    # print meta['zlowpass']

    if meta["zlowpass"] != 0:
        print(meta["MZ"].v, meta["zlowpass"].v)
        meta["maxZ"] = int(np.floor(meta["MZ"].v * meta["zlowpass"].v))
    else:
        meta["maxZ"] = 5

    # meta['nx'] = nx
    # meta['ny']= ny
    meta["dt"] = meta["TIMESTEP"]

    # nx,ny  = d['Rxy'].shape

    # print meta['AA'].v

    meta["rho_s"] = ValUnit(
        1.02e2 * np.sqrt(d["AA"] * d["Te_x"]) / (d["ZZ"] * d["bmag"]), "cm"
    )  # ion gyrorad at T_e, in cm
    meta["rho_i"] = ValUnit(1.02e2 * np.sqrt(d["AA"] * d["Ti_x"]) / (d["ZZ"] * d["bmag"]), "cm")
    meta["rho_e"] = ValUnit(2.38 * np.sqrt(d["Te_x"]) / (d["bmag"]), "cm")

    meta["fmei"] = ValUnit(1.0 / 1836.2 / d["AA"])

    meta["lambda_ei"] = 24.0 - np.log(old_div(np.sqrt(d["Ni_x"]), d["Te_x"]))
    meta["lambda_ii"] = 23.0 - np.log(d["ZZ"] ** 3 * np.sqrt(2.0 * d["Ni_x"]) / (d["Ti_x"] ** 1.5))  #

    meta["wci"] = 1.0 * 9.58e3 * d["ZZ"] * d["bmag"] / d["AA"]  # ion gyrofrteq
    meta["wpi"] = 1.32e3 * d["ZZ"] * np.sqrt(old_div(d["Ni_x"], d["AA"]))  # ion plasma freq

    meta["wce"] = 1.78e7 * d["bmag"]  # electron gyrofreq
    meta["wpe"] = 5.64e4 * np.sqrt(d["Ni_x"])  # electron plasma freq

    meta["v_the"] = 4.19e7 * np.sqrt(d["Te_x"])  # cm/s
    meta["v_thi"] = 9.79e5 * np.sqrt(old_div(d["Ti_x"], d["AA"]))  # cm/s
    meta["c_s"] = 9.79e5 * np.sqrt(5.0 / 3.0 * d["ZZ"] * d["Te_x"] / d["AA"])  #
    meta["v_A"] = 2.18e11 * np.sqrt(old_div(1.0, (d["AA"] * d["Ni_x"])))

    meta["nueix"] = 2.91e-6 * d["Ni_x"] * meta["lambda_ei"] / d["Te_x"] ** 1.5  #
    meta["nuiix"] = 4.78e-8 * d["ZZ"] ** 4.0 * d["Ni_x"] * meta["lambda_ii"] / d["Ti_x"] ** 1.5 / np.sqrt(d["AA"])  #
    meta["nu_hat"] = meta["Zeff"].v * meta["nueix"] / meta["wci"]

    meta["L_d"] = 7.43e2 * np.sqrt(old_div(d["Te_x"], d["Ni_x"]))
    meta["L_i_inrt"] = 2.28e7 * np.sqrt(old_div(d["AA"], d["Ni_x"])) / d["ZZ"]  # ion inertial length in cm
    meta["L_e_inrt"] = 5.31e5 * np.sqrt(d["Ni_x"])  # elec inertial length in cm

    meta["Ve_x"] = 4.19e7 * d["Te_x"]

    meta["R0"] = old_div((d["Rxy"].max() + d["Rxy"].min()), 2.0)

    print(d["Rxy"].mean(1))
    print(d["ZMAX"])
    print(d["ZMIN"])
    meta["L_z"] = 1e2 * 2 * np.pi * d["Rxy"].mean(1) * (d["ZMAX"] - d["ZMIN"])  # in cm toroidal range
    meta["dz"] = d["ZMAX"] - d["ZMIN"]

    # meta['lbNorm']=meta['L_z']*(d['Bpxy']/d['Bxy']).mean(1)     #-binormal coord range [cm]
    meta["lbNorm"] = meta["L_z"] * (old_div(d["Bxy"], d["Bpxy"])).mean(1)

    # meta['zPerp']=np.array(meta['lbNorm']).mean*np.array(range(d['MZ']))/(d['MZ']-1)
    # let's calculate some profile properties
    dx = np.gradient(d["Rxy"])[0]
    meta["L"] = 1.0 * 1e2 * dx * (meta["Ni0"].v) / np.gradient(meta["Ni0"].v)[0] / meta["rho_s"].v

    meta["w_Ln"] = old_div(meta["c_s"], (np.min(abs(meta["L"])) * meta["wci"] * meta["rho_s"].v))  # normed to wci

    AA = meta["AA"].v
    ZZ = d["ZZ"]
    Te_x = d["Te_x"]
    Ti_x = d["Ti_x"]
    fmei = meta["fmei"].v

    meta["lpar"] = (
        1e2 * ((old_div(d["Bxy"], d["Bpxy"])) * d["dlthe"]).sum(1) / meta["rho_s"].v
    )  # -[normed], average over flux surfaces, parallel length

    # yes dlthe is always the vertical displacement
    # dlthe = (hthe0*2 pi)/nz
    # meta['lpar']=1e2*(d['Bxy']/d['Bpxy']).mean(1)*d['dlthe'].mean(1) #function of x
    meta["sig_par"] = old_div(1.0, (fmei * 0.51 * meta["nu_hat"]))
    # meta['heat_nue'] = ((2*np.pi/meta['lpar'])**2)/(fmei*meta['nu_hat'])
    # kz_e = kz_i*(rho_e/rho_i)
    # kz_s = kz_i*(rho_s/rho_i)
    # kz_i = (TWOPI/L_z)*(indgen((*current_str).fft.nz+1))*rho_i

    # knorm = (TWOPI/lbNorm)*(indgen((*current_str).fft.nz+1))*rho_s

    # for now just translate
    for elem in meta:
        if type(meta[elem]).__name__ == "ValUnit":
            meta[elem] = {"u": meta[elem].u, "v": meta[elem].v}

    print("meta: ", type(meta))
    return meta
예제 #13
0
def plotpolslice(var3d,gridfile,period=1,zangle=0.0, rz=1, fig=0):
    """ data2d = plotpolslice(data3d, 'gridfile' , period=1, zangle=0.0, rz:return (r,z) grid also=1, fig: to do the graph, set to 1 ) """
    
    g=file_import(gridfile)
    
    nx=var3d.shape[0]
    ny=var3d.shape[1]
    nz=var3d.shape[2]


    zShift=g.get('zShift')
    rxy=g.get('Rxy')
    zxy=g.get('Zxy')

    dz = 2.0*np.pi / float(period*(nz-1))

    ny2=ny
    nskip=np.zeros(ny-1)
    for i in range(ny-1):
        ip=(i+1)%ny
        nskip[i]=0
        for x in range(nx):
            ns=old_div(np.max(np.abs(zShift[x,ip]-zShift[x,i])),dz)-1
            if ns > nskip[i] : nskip[i] = ns 

    nskip = np.int_(np.round(nskip))
    ny2 = np.int_(ny2 + np.sum(nskip))

    print("Number of poloidal points in output:" + str(ny2))

    var2d = np.zeros((nx, ny2))
    r = np.zeros((nx, ny2))
    z = np.zeros((nx, ny2))

    ypos = 0
    for y in range (ny-1) :
      # put in the original points
        for x in range (nx):
            zind = old_div((zangle - zShift[x,y]),dz)
            var2d[x,ypos] = zinterp(var3d[x,y,:], zind)
     #     IF KEYWORD_SET(profile) THEN var2d[x,ypos] = var2d[x,ypos] + profile[x,y]
            r[x,ypos] = rxy[x,y]
            z[x,ypos] = zxy[x,y]
      
        ypos = ypos + 1
    
        print((y, ypos))

      # and the extra points
    
        for x in range (nx):
            zi0 = old_div((zangle - zShift[x,y]),dz)
            zip1 = old_div((zangle - zShift[x,y+1]),dz)

            dzi = old_div((zip1 - zi0), (nskip[y] + 1))

            for i in range (nskip[y]):
                zi = zi0 + float(i+1)*dzi # zindex 
                w = old_div(float(i+1),float(nskip[y]+1)) # weighting

                var2d[x,ypos+i] = w*zinterp(var3d[x,y+1,:], zi) + (1.0-w)*zinterp(var3d[x,y,:], zi)
            #  IF KEYWORD_SET(profile) THEN var2d[x,ypos+i] = var2d[x,ypos+i] + w*profile[x,y+1] + (1.0-w)*profile[x,y]
                r[x,ypos+i] = w*rxy[x,y+1] + (1.0-w)*rxy[x,y]
                z[x,ypos+i] = w*zxy[x,y+1] + (1.0-w)*zxy[x,y]
          
      

        ypos = ypos + nskip[y]


  # FINAL POINT

    for x in range(nx):
        zind = old_div((zangle - zShift[x,ny-1]),dz)
        var2d[x,ypos] = zinterp(var3d[x,ny-1,:], zind)
     # IF KEYWORD_SET(profile) THEN var2d[x,ypos] = var2d[x,ypos] + profile[x,ny-1]
        r[x,ypos] = rxy[x,ny-1]
        z[x,ypos] = zxy[x,ny-1]
           
 
    if(fig==1):  
    
        f = mlab.figure(size=(600,600))
        # Tell visual to use this as the viewer.
        visual.set_viewer(f)


        s = mlab.mesh(r,z,var2d, colormap='PuOr')#, wrap_scale='true')#, representation='wireframe')
        s.enable_contours=True
        s.contour.filled_contours=True
        mlab.view(0,0)
        
    else:   
        # return according to opt 
        if rz==1 :
            return r,z,var2d
        else:
            return var2d
예제 #14
0
def plotpolslice(var3d, gridfile, period=1, zangle=0.0, rz=1, fig=0):
    """ data2d = plotpolslice(data3d, 'gridfile' , period=1, zangle=0.0, rz:return (r,z) grid also=1, fig: to do the graph, set to 1 ) """

    g = file_import(gridfile)

    nx = var3d.shape[0]
    ny = var3d.shape[1]
    nz = var3d.shape[2]

    zShift = g.get('zShift')
    rxy = g.get('Rxy')
    zxy = g.get('Zxy')

    dz = 2.0 * np.pi / float(period * (nz - 1))

    ny2 = ny
    nskip = np.zeros(ny - 1)
    for i in range(ny - 1):
        ip = (i + 1) % ny
        nskip[i] = 0
        for x in range(nx):
            ns = old_div(np.max(np.abs(zShift[x, ip] - zShift[x, i])), dz) - 1
            if ns > nskip[i]: nskip[i] = ns

    nskip = np.int_(np.round(nskip))
    ny2 = np.int_(ny2 + np.sum(nskip))

    print("Number of poloidal points in output:" + str(ny2))

    var2d = np.zeros((nx, ny2))
    r = np.zeros((nx, ny2))
    z = np.zeros((nx, ny2))

    ypos = 0
    for y in range(ny - 1):
        # put in the original points
        for x in range(nx):
            zind = old_div((zangle - zShift[x, y]), dz)
            var2d[x, ypos] = zinterp(var3d[x, y, :], zind)
            #     IF KEYWORD_SET(profile) THEN var2d[x,ypos] = var2d[x,ypos] + profile[x,y]
            r[x, ypos] = rxy[x, y]
            z[x, ypos] = zxy[x, y]

        ypos = ypos + 1

        print((y, ypos))

        # and the extra points

        for x in range(nx):
            zi0 = old_div((zangle - zShift[x, y]), dz)
            zip1 = old_div((zangle - zShift[x, y + 1]), dz)

            dzi = old_div((zip1 - zi0), (nskip[y] + 1))

            for i in range(nskip[y]):
                zi = zi0 + float(i + 1) * dzi  # zindex
                w = old_div(float(i + 1), float(nskip[y] + 1))  # weighting

                var2d[x, ypos + i] = w * zinterp(var3d[x, y + 1, :], zi) + (
                    1.0 - w) * zinterp(var3d[x, y, :], zi)
                #  IF KEYWORD_SET(profile) THEN var2d[x,ypos+i] = var2d[x,ypos+i] + w*profile[x,y+1] + (1.0-w)*profile[x,y]
                r[x, ypos + i] = w * rxy[x, y + 1] + (1.0 - w) * rxy[x, y]
                z[x, ypos + i] = w * zxy[x, y + 1] + (1.0 - w) * zxy[x, y]

        ypos = ypos + nskip[y]

# FINAL POINT

    for x in range(nx):
        zind = old_div((zangle - zShift[x, ny - 1]), dz)
        var2d[x, ypos] = zinterp(var3d[x, ny - 1, :], zind)
        # IF KEYWORD_SET(profile) THEN var2d[x,ypos] = var2d[x,ypos] + profile[x,ny-1]
        r[x, ypos] = rxy[x, ny - 1]
        z[x, ypos] = zxy[x, ny - 1]

    if (fig == 1):

        f = mlab.figure(size=(600, 600))
        # Tell visual to use this as the viewer.
        visual.set_viewer(f)

        s = mlab.mesh(r, z, var2d, colormap='PuOr'
                      )  #, wrap_scale='true')#, representation='wireframe')
        s.enable_contours = True
        s.contour.filled_contours = True
        mlab.view(0, 0)

    else:
        # return according to opt
        if rz == 1:
            return r, z, var2d
        else:
            return var2d
예제 #15
0
from __future__ import print_function
from boututils import file_import, volume_integral
from boutdata import collect
# Integrate over a volume

path = './data/'

gfile = './cbm18_dens8.grid_nx68ny64.nc'

g = file_import(gfile)

var = collect("P", path=path)

sol = volume_integral(var, g)

print(sol)
예제 #16
0
파일: mayavi2.py 프로젝트: AlxMar/BOUT-2.0
    src = VTKDataSource(data=sgrid)
    mayavi.add_source(src)
    mayavi.add_module(Outline())
    g = GridPlane()
    g.grid_plane.axis = 'x'
    mayavi.add_module(g)

if __name__ == '__main__':
    from boutdata import collect
    from boututils import file_import
    
    path = "/media/449db594-b2fe-4171-9e79-2d9b76ac69b6/runs/data_33/"
    #path="/home/ben/run4"

    #g = file_import("../cbm18_dens8.grid_nx68ny64.nc")
    g = file_import("data/cbm18_8_y064_x516_090309.nc")
    #g = file_import("/home/ben/run4/reduced_y064_x256.nc")
    
    data = collect("P", tind=50, path=path)
    data = data[0,:,:,:]
    s = np.shape(data)
    nz = s[2]
    
    bkgd = collect("P0", path=path)
    for z in range(nz):
        data[:,:,z] += bkgd

    # Create a structured grid
    sgrid = create_grid(g, data, 10)
    
예제 #17
0
    src = VTKDataSource(data=sgrid)
    e.add_source(src)
    e.add_module(Outline())
    g = GridPlane()
    g.grid_plane.axis = 'x'
    e.add_module(g)


if __name__ == '__main__':
    from boutdata import collect
    from boututils import file_import

    #path = "/media/449db594-b2fe-4171-9e79-2d9b76ac69b6/runs/data_33/"
    path = "../data"

    g = file_import("../bout.grd.nc")
    #g = file_import("../cbm18_8_y064_x516_090309.nc")
    #g = file_import("/home/ben/run4/reduced_y064_x256.nc")

    data = collect("P", tind=10, path=path)
    data = data[0, :, :, :]
    s = np.shape(data)
    nz = s[2]

    #bkgd = collect("P0", path=path)
    #for z in range(nz):
    #   data[:,:,z] += bkgd

    # Create a structured grid
    sgrid = create_grid(g, data, 1)