Exemple #1
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.file_import import file_import
from matplotlib.ticker import FixedFormatter, FormatStrFormatter, AutoLocator, AutoMinorLocator

g = file_import("uedge.grd_Up_Ni_Tei_2d.nc")

x_temp = g.get("Rxy")
y_temp = g.get("Zxy")

#print x_temp.shape
nR = x_temp.shape[0]
nZ = x_temp.shape[1]

for r in np.arange(nR):
    plt.plot(x_temp[r, :], y_temp[r, :], color='black', linewidth=0.2)

for z in np.arange(nZ):
    plt.plot(x_temp[:, z], y_temp[:, z], color='black', linewidth=0.2)

plt.savefig('mesh.pdf')
plt.show()
from builtins import range
from past.utils import old_div
import numpy as np
from boututils.file_import import file_import
from boututils.surface_average import surface_average
from boututils.showdata import showdata
from boutdata.collect 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')
Exemple #3
0
                  2:0.145174416274, #0.143251663975, Changed 25th April 2014, revision fd032da
                  4:0.226979299615,
                  8:0.28632661549,
                  16:0.295998650267,
                  32:0.271288568509,
                  64:0.222344013151,
                  128:0.1716229,
                  256:0.12957680451} #0.130220286897} Changed 25th April 2014

#zlist = map(lambda x:2**x, range(9))

# Create a directory for the data
shell_safe("mkdir -p data")

# Import the grid file
grid = file_import("uedge.grd_std.cdl")

code = 0 # Return code
for zeff in zlist:
    # Create the input file, setting Zeff
    # If we get passed Staggered or something like this, use staggered config file
    inp='BOUT_stag.inp' if 'stag' in [i.lower()[:4] for i in argv] else 'BOUT.inp'
    shell_safe("sed 's/Zeff = 128.0/Zeff = "+str(zeff)+"/g' "+inp+" > data/BOUT.inp")
    timestep = 5e3
    if zeff < 128:
        # reduce time-step. At large times these cases produce noise
        timestep = 1e3

    # Delete old output files
    shell("rm data/BOUT.dmp.*.nc")
Exemple #4
0
import numpy as np
from boututils.moment_xyzt import moment_xyzt
from boututils.file_import import file_import
from boutdata.collect import collect
import os

#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 = collect('P0', path=path)

p = collect('P', path=path)
res = moment_xyzt(p, 'RMS', 'DC')
rmsp = res.rms
dcp = res.dc
nt = dcp.shape[2]
Exemple #5
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.file_import import file_import
from matplotlib.ticker import FixedFormatter, FormatStrFormatter, AutoLocator, AutoMinorLocator

g = file_import("data/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))
Exemple #6
0
from __future__ import print_function
from boututils.file_import import file_import
from bunch import Bunch
import numpy as np


def cbmtogeqdsk(g):
    gg=Bunch()
    gg.r=g['Rxy']
    gg.z=g['Zxy']
    gg.psi=g['psi']
    gg.pres=g['mu0p']
    gg.qpsi=g['qsafe']
    gg.fpol=g['f']
    gg.nx=g['nx']
    gg.ny=g['ny']
    i=np.argwhere(g['mu0p']==0)
    
    gg.simagx=gg.psi.min()
    gg.sibdry=gg.psi[i[0]]
    gg.xlim=0
    gg.ylim=0
    gg.nlim=0

    return gg

if __name__ == '__main__':
    gfile='../cbm18_dens8.dskgato.cdl'
    g=file_import(gfile)
    print(cbmtogeqdsk(g))
Exemple #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')
Exemple #8
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.collect import collect
    from boututils.file_import 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')
Exemple #9
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.collect import collect
    from boututils.file_import 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)
    
Exemple #10
0
from __future__ import division
from builtins import range
from past.utils import old_div
from boutdata.collect import collect
import numpy as np
import matplotlib.pyplot as plt
from boututils.file_import import file_import
from matplotlib.ticker import FixedFormatter, FormatStrFormatter, AutoLocator, AutoMinorLocator

#read grid data
g = file_import('data/slab.grd.nc')
x_temp = g.get("Rxy")
y_temp = g.get("Zxy")

#read simulation data
z_temp = collect("Ni", path="data")

nx = z_temp.shape[1]
ny = z_temp.shape[2]

time = 10
plot = "1d"

fig = plt.figure(figsize=(9, 6), dpi=100)

if plot == "2d":
    ax2d = fig.add_subplot(111, aspect='equal')
    x = np.zeros((nx, ny))
    y = np.zeros((nx, ny))

    z = z_temp[10, :, :]
Exemple #11
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
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)

    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
    mayavi.add_source(src)
    mayavi.add_module(Outline())
    g = GridPlane()
    g.grid_plane.axis = "x"
    mayavi.add_module(g)


if __name__ == "__main__":
    from boutdata.collect import collect
    from boututils.file_import 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")
Exemple #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)

    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
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.file_import 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))

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