Пример #1
0
def write2grid(prof, prof_name, grid_path, overwrite=False):
    '''Write profile to a specified grid file.

    Parameters:
    prof -- 1D or 2D array, an equilibrium quantity to be
        written to the grid file. An easy way to generate
        an appropriate profile is to use the interpolate2grid(...)
        routine above
    prof_name -- str, name assigned to profile in grid file
    grid_path -- str, path to the grid file to interpolate onto
    overwrite -- bool, if False, this will prevent overwiting
        a preexisting grid variable with the same name as prof_name

    Returns:
    True if the write is successful, False otherwise.

    '''
    grid_file = DataFile(grid_path, write=True)

    if not overwrite and (prof_name in grid_file.list()):
        raise ValueError(prof_name + ' is already in use in '
                + grid_path
                + '. Specify overwrite=True to overwrite existing profile')

    grid_file.write(prof_name, prof)

    return 0
Пример #2
0
def save2nc(file_name,**var):
  """save2nc(file_name, varName=var, ...)
    save variables to netCDF file. 

    'file_name' is the exported file name, and the suffix ".nc" will be append automatically.
    'varName' is the name saved in exported files,
    'var' is the variable saved. varName and var do NOT need the quotation mark.

    E.g. save2nc('file',t=t,x=psi,P0=P0_origin) will save variables t as t, psi as x, P0_origin as P0 into a netcdf file named 'file.nc'.
  """
  if file_name[-3:] != '.nc':
    file_name += '.nc'
  f = DataFile(file_name, write=True, create=True)
  for v in var:
    try:
      varg = var[v]
      f.write(v,varg)
    except:
      print 'check the source code "save2nv.py" for more infomation'
  f.close()
Пример #3
0
from past.utils import old_div
from boututils import DataFile # Wrapper around NetCDF4 libraries
from math import pow
from sys import argv

length = 80. # Length of the domain in m

nx = 5   # Minimum is 5: 2 boundary, one evolved
if len(argv)>1:
  ny = int(argv[1])  # Minimum 5. Should be divisible by number of processors (so powers of 2 nice)
else:
  ny = 256  # Minimum 5. Should be divisible by number of processors (so powers of 2 nice)
#dy = [[1.]*ny]*nx # distance between points in y, in m/g22/lengthunit
g22 = [[pow(old_div(float(ny-1),length),2)]*ny]*nx
g_22 = [[pow(old_div(length,float(ny-1)),2)]*ny]*nx
ixseps1 = -1
ixseps2 = 0

f = DataFile()
f.open("conduct_grid.nc", create=True)

f.write("nx", nx)
f.write("ny", ny)
#f.write("dy", dy)
f.write("g22",g22)
f.write("g_22", g_22)
f.write("ixseps1", ixseps1)
f.write("ixseps2", ixseps2)

f.close()
Пример #4
0
def resizeY(newy, path="data", output=".", informat="nc", outformat=None,myg=2):
    """
    Resize all the restart files in Y
    """

    if outformat == None:
        outformat = informat

    file_list = glob.glob(os.path.join(path, "BOUT.restart.*."+informat))
    
    nfiles = len(file_list)
    
    if nfiles == 0:
        print("ERROR: No restart files found")
        return False
    
    for i in range(nfiles):
        # Open each data file
        infname  = os.path.join(path, "BOUT.restart."+str(i)+"."+informat)
        outfname = os.path.join(output, "BOUT.restart."+str(i)+"."+outformat)

        print("Processing %s -> %s", infname, outfname)
        
        infile = DataFile(infname)
        outfile = DataFile(outfname, create=True)

        # Copy basic information
        for var in ["hist_hi", "NPES", "NXPE", "tt"]:
            data = infile.read(var)
            try:
                # Convert to scalar if necessary
                data = data[0]
            except:
                pass
            outfile.write(var, data)
        
        # Get a list of variables
        varnames = infile.list()
        
        for var in varnames:
            if infile.ndims(var) == 3:
                # Could be an evolving variable [x,y,z]
                
                print(" -> " + var)
                
                # Read variable from input
                indata = infile.read(var)
            
                nx,ny,nz = indata.shape
                
                # y coordinate in input and output data
                iny = (arange(ny) - myg + 0.5) / (ny - 2*myg)
                outy = (arange(newy) - myg + 0.5) / (newy - 2*myg)
                
                outdata = zeros([nx, newy, nz])
                
                for x in range(nx):
                    for z in range(nz):
                        f = interp1d(iny, indata[x,:,z], bounds_error=False, fill_value=0.0)
                        outdata[x,:,z] = f(outy)
                
                outfile.write(var, outdata)
        infile.close()
        outfile.close()
Пример #5
0
def create(averagelast=1, final=-1, path="data", output="./", informat="nc", outformat=None):
    """
    Create restart files from data (dmp) files.

    Inputs
    ======

    averagelast   Number of time points to average over.
                  Default is 1 i.e. just take last time-point

    final         The last time point to use. Default is last (-1)

    path          Path to the input data files

    output        Path where the output restart files should go

    informat      Format of the input data files

    outformat     Format of the output restart files

    """

    if outformat == None:
        outformat = informat

    file_list = glob.glob(os.path.join(path, "BOUT.dmp.*."+informat))
    nfiles = len(file_list)

    print(("Number of data files: ", nfiles))

    for i in range(nfiles):
        # Open each data file
        infname  = os.path.join(path, "BOUT.dmp."+str(i)+"."+informat)
        outfname = os.path.join(output, "BOUT.restart."+str(i)+"."+outformat)

        print((infname, " -> ", outfname))

        infile = DataFile(infname)
        outfile = DataFile(outfname, create=True)

        # Get the data always needed in restart files
        hist_hi = infile.read("iteration")
        print(("hist_hi = ", hist_hi))
        outfile.write("hist_hi", hist_hi)

        t_array = infile.read("t_array")
        tt = t_array[final]
        print(("tt = ", tt))
        outfile.write("tt", tt)

        NXPE = infile.read("NXPE")
        NYPE = infile.read("NYPE")
        NPES = NXPE * NYPE
        print(("NPES = ", NPES, " NXPE = ", NXPE))
        outfile.write("NPES", NPES)
        outfile.write("NXPE", NXPE)

        # Get a list of variables
        varnames = infile.list()

        for var in varnames:
            if infile.ndims(var) == 4:
                # Could be an evolving variable

                print((" -> ", var))

                data = infile.read(var)

                if averagelast == 1:
                    slice = data[final,:,:,:]
                else:
                    slice = mean(data[(final - averagelast):final,:,:,:], axis=0)

                print(slice.shape)

                outfile.write(var, slice)

        infile.close()
        outfile.close()
Пример #6
0
ydown_xsplit = [nx]
yup_xin = [0]
yup_xout = [-1]
ydown_xin = [0]
ydown_xout = [-1]
nrad = [nx]
npol = [ny]

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

print "Writing grid to file "+output

of = DataFile()
of.open(output, create=True)

of.write("nx", nx)
of.write("ny", ny)

# Topology for original scheme
of.write("ixseps1", ixseps1)
of.write("ixseps2", ixseps2)
of.write("jyseps1_1", jyseps1_1)
of.write("jyseps1_2", jyseps1_2)
of.write("jyseps2_1", jyseps2_1)
of.write("jyseps2_2", jyseps2_2)
of.write("ny_inner", ny_inner)

# Grid spacing
of.write("dx", dx)
of.write("dy", dy)
Пример #7
0
ydown_xsplit = [nx]
yup_xin = [0]
yup_xout = [-1]
ydown_xin = [0]
ydown_xout = [-1]
nrad = [nx]
npol = [ny]

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

print("Writing grid to file "+output)

of = DataFile()
of.open(output, create=True)

of.write("nx", nx)
of.write("ny", ny)

# Topology for original scheme
of.write("ixseps1", ixseps1)
of.write("ixseps2", ixseps2)
of.write("jyseps1_1", jyseps1_1)
of.write("jyseps1_2", jyseps1_2)
of.write("jyseps2_1", jyseps2_1)
of.write("jyseps2_2", jyseps2_2)
of.write("ny_inner", ny_inner)

# Grid spacing
of.write("dx", dx)
of.write("dy", dy)
Пример #8
0
def generate(nx, ny,
             R = 2.0, r=0.2, # Major & minor radius
             dr=0.05,  # Radial width of domain
             Bt=1.0,   # Toroidal magnetic field
             q=5.0,    # Safety factor
             mxg=2,
             file="circle.nc"
             ):
    
    # q = rBt / RBp
    Bp = r*Bt / (R*q)

    # Minor radius as function of x. Choose so boundary
    # is half-way between grid points

    h = dr / (nx - 2.*mxg) # Grid spacing in r
    rminor = linspace(r - 0.5*dr - (mxg-0.5)*h,
                      r + 0.5*dr + (mxg-0.5)*h,
                      nx)
    
    # mesh spacing in x and y
    dx = ndarray([nx,ny])
    dx[:,:] = r*Bt*h      # NOTE: dx is toroidal flux

    dy = ndarray([nx,ny])
    dy[:,:] = 2.*pi / ny

    # LogB = log(1/(1+r/R cos(theta))) =(approx) -(r/R)*cos(theta)
    logB = zeros([nx, ny, 3]) # (constant, n=1 real, n=1 imag) 

    # At y = 0, Rmaj = R + r*cos(theta)
    logB[:,0,1] = -(rminor/R)

    # Moving in y, phase shift by (toroidal angle) / q
    for y in range(1,ny):
        dtheta = y * 2.*pi / ny / q # Change in poloidal angle

        logB[:,y,1] = -(rminor/R)*cos(dtheta)
        logB[:,y,2] = -(rminor/R)*sin(dtheta)

    # Shift angle from one end of y to the other
    ShiftAngle = ndarray([nx])
    ShiftAngle[:] = 2.*pi / q
    
    Rxy = ndarray([nx,ny])
    Rxy[:,:] = r    # NOTE  : opposite to standard BOUT convention

    Btxy = ndarray([nx,ny])
    Btxy[:,:] = Bp

    Bpxy = ndarray([nx,ny])
    Bpxy[:,:] = Bt

    Bxy = ndarray([nx,ny])
    Bxy[:,:] = sqrt(Bt**2 + Bp**2)

    hthe = ndarray([nx,ny])
    hthe[:,:] = R

    print("Writing to file '"+file+"'")

    f = DataFile()
    f.open(file, create=True)

    # Mesh size
    f.write("nx", nx)
    f.write("ny", ny)

    # Mesh spacing
    f.write("dx", dx)
    f.write("dy", dy)

    # Metric components
    f.write("Rxy", Rxy)
    f.write("Btxy", Btxy)
    f.write("Bpxy", Bpxy)
    f.write("Bxy", Bxy)
    f.write("hthe", hthe)

    # Shift
    f.write("ShiftAngle", ShiftAngle);

    # Curvature
    f.write("logB", logB)

    # Input parameters
    f.write("R", R)
    f.write("r", r)
    f.write("dr", dr)
    f.write("Bt", Bt)
    f.write("q", q)
    f.write("mxg", mxg)

    f.close()
Пример #9
0
def create(averagelast=1,
           final=-1,
           path="data",
           output="./",
           informat="nc",
           outformat=None):
    """
    Create restart files from data (dmp) files.

    Inputs
    ======

    averagelast   Number of time points to average over.
                  Default is 1 i.e. just take last time-point

    final         The last time point to use. Default is last (-1)

    path          Path to the input data files

    output        Path where the output restart files should go

    informat      Format of the input data files

    outformat     Format of the output restart files
    
    """

    if outformat == None:
        outformat = informat

    file_list = glob.glob(os.path.join(path, "BOUT.dmp.*." + informat))
    nfiles = len(file_list)

    print "Number of data files: ", nfiles

    for i in range(nfiles):
        # Open each data file
        infname = os.path.join(path, "BOUT.dmp." + str(i) + "." + informat)
        outfname = os.path.join(output,
                                "BOUT.restart." + str(i) + "." + outformat)

        print infname, " -> ", outfname

        infile = DataFile(infname)
        outfile = DataFile(outfname, create=True)

        # Get the data always needed in restart files
        hist_hi = infile.read("iteration")
        print "hist_hi = ", hist_hi
        outfile.write("hist_hi", hist_hi)

        t_array = infile.read("t_array")
        tt = t_array[final]
        print "tt = ", tt
        outfile.write("tt", tt)

        NXPE = infile.read("NXPE")
        NYPE = infile.read("NYPE")
        NPES = NXPE * NYPE
        print "NPES = ", NPES, " NXPE = ", NXPE
        outfile.write("NPES", NPES)
        outfile.write("NXPE", NXPE)

        # Get a list of variables
        varnames = infile.list()

        for var in varnames:
            if infile.ndims(var) == 4:
                # Could be an evolving variable

                print " -> ", var

                data = infile.read(var)

                if averagelast == 1:
                    slice = data[final, :, :, :]
                else:
                    slice = mean(data[(final - averagelast):final, :, :, :],
                                 axis=0)

                print slice.shape

                outfile.write(var, slice)

        infile.close()
        outfile.close()
Пример #10
0
from math import pow
from sys import argv

length = 80.  # Length of the domain in m

nx = 5  # Minimum is 5: 2 boundary, one evolved
if len(argv) > 1:
    ny = int(
        argv[1]
    )  # Minimum 5. Should be divisible by number of processors (so powers of 2 nice)
else:
    ny = 256  # Minimum 5. Should be divisible by number of processors (so powers of 2 nice)
#dy = [[1.]*ny]*nx # distance between points in y, in m/g22/lengthunit
g22 = [[pow(old_div(float(ny - 1), length), 2)] * ny] * nx
g_22 = [[pow(old_div(length, float(ny - 1)), 2)] * ny] * nx
ixseps1 = -1
ixseps2 = 0

f = DataFile()
f.open("conduct_grid.nc", create=True)

f.write("nx", nx)
f.write("ny", ny)
#f.write("dy", dy)
f.write("g22", g22)
f.write("g_22", g_22)
f.write("ixseps1", ixseps1)
f.write("ixseps2", ixseps2)

f.close()
Пример #11
0
def resizeY(newy, path="data", output=".", informat="nc", outformat=None,myg=2):
    """
    Resize all the restart files in Y
    """

    if outformat == None:
        outformat = informat

    file_list = glob.glob(os.path.join(path, "BOUT.restart.*."+informat))
    
    nfiles = len(file_list)
    
    if nfiles == 0:
        print("ERROR: No restart files found")
        return False
    
    for i in range(nfiles):
        # Open each data file
        infname  = os.path.join(path, "BOUT.restart."+str(i)+"."+informat)
        outfname = os.path.join(output, "BOUT.restart."+str(i)+"."+outformat)

        print("Processing %s -> %s", infname, outfname)
        
        infile = DataFile(infname)
        outfile = DataFile(outfname, create=True)

        # Copy basic information
        for var in ["hist_hi", "NPES", "NXPE", "tt"]:
            data = infile.read(var)
            try:
                # Convert to scalar if necessary
                data = data[0]
            except:
                pass
            outfile.write(var, data)
        
        # Get a list of variables
        varnames = infile.list()
        
        for var in varnames:
            if infile.ndims(var) == 3:
                # Could be an evolving variable [x,y,z]
                
                print(" -> " + var)
                
                # Read variable from input
                indata = infile.read(var)
            
                nx,ny,nz = indata.shape
                
                # y coordinate in input and output data
                iny = (arange(ny) - myg + 0.5) / (ny - 2*myg)
                outy = (arange(newy) - myg + 0.5) / (newy - 2*myg)
                
                outdata = zeros([nx, newy, nz])
                
                for x in range(nx):
                    for z in range(nz):
                        f = interp1d(iny, indata[x,:,z], bounds_error=False, fill_value=0.0)
                        outdata[x,:,z] = f(outy)
                
                outfile.write(var, outdata)
        infile.close()
        outfile.close()
Пример #12
0
def generate(
        nx,
        ny,
        R=2.0,
        r=0.2,  # Major & minor radius
        dr=0.05,  # Radial width of domain
        Bt=1.0,  # Toroidal magnetic field
        q=5.0,  # Safety factor
        mxg=2,
        file="circle.nc"):

    # q = rBt / RBp
    Bp = r * Bt / (R * q)

    # Minor radius as function of x. Choose so boundary
    # is half-way between grid points

    h = dr / (nx - 2. * mxg)  # Grid spacing in r
    rminor = linspace(r - 0.5 * dr - (mxg - 0.5) * h,
                      r + 0.5 * dr + (mxg - 0.5) * h, nx)

    # mesh spacing in x and y
    dx = ndarray([nx, ny])
    dx[:, :] = r * Bt * h  # NOTE: dx is toroidal flux

    dy = ndarray([nx, ny])
    dy[:, :] = 2. * pi / ny

    # LogB = log(1/(1+r/R cos(theta))) =(approx) -(r/R)*cos(theta)
    logB = zeros([nx, ny, 3])  # (constant, n=1 real, n=1 imag)

    # At y = 0, Rmaj = R + r*cos(theta)
    logB[:, 0, 1] = -(rminor / R)

    # Moving in y, phase shift by (toroidal angle) / q
    for y in range(1, ny):
        dtheta = y * 2. * pi / ny / q  # Change in poloidal angle

        logB[:, y, 1] = -(rminor / R) * cos(dtheta)
        logB[:, y, 2] = -(rminor / R) * sin(dtheta)

    # Shift angle from one end of y to the other
    ShiftAngle = ndarray([nx])
    ShiftAngle[:] = 2. * pi / q

    Rxy = ndarray([nx, ny])
    Rxy[:, :] = r  # NOTE  : opposite to standard BOUT convention

    Btxy = ndarray([nx, ny])
    Btxy[:, :] = Bp

    Bpxy = ndarray([nx, ny])
    Bpxy[:, :] = Bt

    Bxy = ndarray([nx, ny])
    Bxy[:, :] = sqrt(Bt**2 + Bp**2)

    hthe = ndarray([nx, ny])
    hthe[:, :] = R

    print("Writing to file '" + file + "'")

    f = DataFile()
    f.open(file, create=True)

    # Mesh size
    f.write("nx", nx)
    f.write("ny", ny)

    # Mesh spacing
    f.write("dx", dx)
    f.write("dy", dy)

    # Metric components
    f.write("Rxy", Rxy)
    f.write("Btxy", Btxy)
    f.write("Bpxy", Bpxy)
    f.write("Bxy", Bxy)
    f.write("hthe", hthe)

    # Shift
    f.write("ShiftAngle", ShiftAngle)

    # Curvature
    f.write("logB", logB)

    # Input parameters
    f.write("R", R)
    f.write("r", r)
    f.write("dr", dr)
    f.write("Bt", Bt)
    f.write("q", q)
    f.write("mxg", mxg)

    f.close()
Пример #13
0
#!/usr/bin/env python

#
# Generate an input mesh
#

from boututils import DataFile  # Wrapper around NetCDF4 libraries

nx = 5  # Minimum is 5: 2 boundary, one evolved
ny = 64  # Minimum 5. Should be divisible by number of processors (so powers of 2 nice)

f = DataFile()
f.open("conduct_grid.nc", create=True)

f.write("nx", nx)
f.write("ny", ny)

f.close()
Пример #14
0
#!/usr/bin/env python

#
# Generate an input mesh
#

from boututils import DataFile # Wrapper around NetCDF4 libraries

nx = 5   # Minimum is 5: 2 boundary, one evolved
ny = 64  # Minimum 5. Should be divisible by number of processors (so powers of 2 nice)

f = DataFile()
f.open("conduct_grid.nc", create=True)

f.write("nx", nx)
f.write("ny", ny)

f.close()
Пример #15
0
#!/usr/bin/env python

#
# Generate an input mesh
#

from boututils import DataFile # Wrapper around NetCDF4 libraries

nx = 5   # Minimum is 5: 2 boundary, one evolved
ny = 32  # Minimum 5. Should be divisible by number of processors (so powers of 2 nice)
dy = 1. # distance between points in y, in m/g22/lengthunit
ixseps1 = -1
ixseps2 = -1

f = DataFile()
f.open("test-staggered.nc", create=True)

f.write("nx", nx)
f.write("ny", ny)
f.write("dy", dy)
f.write("ixseps1", ixseps1)
f.write("ixseps2", ixseps2)

f.close()
Пример #16
0
        a[ix, jy] = -1.0

        

# === Print normalization information === #
print '=============================='
print ' n0 = ', n0
print ' v0 = ', v0
print '=============================='

# ============== Write to grid file ============ #

f=DataFile() 
f.open("slab.grd.nc",create=True)
                                    
f.write("nx" ,nx)         #write the value of nx to the element of name "nx" in f
f.write("ny", ny)

# == auxiliary quantities == #

f.write("dx", dx)
f.write("a", a)

# == normalization quantities == #

f.write("n0", n0)
f.write("v0", v0)


f.close()