Пример #1
0
def new_to_old(filename):
    f = DataFile(filename)

    newfile = DataFile(os.path.splitext(filename)[0] + str(".BOUT_metrics.nc"),
                       create=True)

    name_changes = {
        "g_yy": "g_22",
        "gyy": "g22",
        "gxx": "g11",
        "gxz": "g13",
        "gzz": "g33",
        "g_xx": "g_11",
        "g_xz": "g_13",
        "g_zz": "g_33"
    }

    for key in f.keys():
        name = key
        if name in name_changes:
            name = name_changes[name]
        newfile.write(name, np.asarray(f.read(key)))

    f.close()
    newfile.close()

    newfile.list()
def calc_curvilinear_curvature(fname, field, grid):
    from scipy.signal import savgol_filter

    f = DataFile(str(fname), write=True)
    B = f.read("B")
    dBydz = np.zeros(np.shape(B))
    dBydx = np.zeros(np.shape(B))
    dBxdz = np.zeros(np.shape(B))
    dBzdx = np.zeros(np.shape(B))
    dx = grid.metric()["dx"]
    dz = grid.metric()["dz"]
    g_11 = grid.metric()["g_xx"]
    g_22 = grid.metric()["g_yy"]
    g_33 = grid.metric()["g_zz"]
    g_12 = 0.0
    g_13 = grid.metric()["g_xz"]
    g_23 = 0.0
    J = np.sqrt(g_11 * (g_22 * g_33 - g_23 * g_23) + g_12 *
                (g_13 * g_23 - g_12 * g_33) + g_13 *
                (g_12 * g_23 - g_22 * g_23))
    Bx_smooth = np.zeros(B.shape)
    By_smooth = np.zeros(B.shape)
    Bz_smooth = np.zeros(B.shape)

    for y in np.arange(0, B.shape[1]):
        pol, _ = grid.getPoloidalGrid(y)
        R = pol.R
        Z = pol.Z
        for x in np.arange(0, B.shape[0]):
            Bx_smooth[x, y, :] = savgol_filter(
                field.Bxfunc(R[x, :], y, Z[x, :]),
                np.int(np.ceil(B.shape[-1] / 21) // 2 * 2 + 1), 5)
            By_smooth[x, y, :] = savgol_filter(
                field.Byfunc(R[x, :], y, Z[x, :]),
                np.int(np.ceil(B.shape[-1] / 21) // 2 * 2 + 1), 5)

            dBydz[x, y, :] = calc.deriv(By_smooth[x, y, :]) / dz[x, y, :]
            dBxdz[x, y, :] = calc.deriv(Bx_smooth[x, y, :]) / dz[x, y, :]
        for z in np.arange(0, B.shape[-1]):
            Bz_smooth[:, y, z] = savgol_filter(
                field.Bzfunc(R[:, z], y, Z[:, z]),
                np.int(np.ceil(B.shape[0] / 7) // 2 * 2 + 1), 5)
            dBzdx[:, y, z] = calc.deriv(Bz_smooth[:, y, z]) / dx[:, y, z]
            dBydx[:, y, z] = calc.deriv(By_smooth[:, y, z]) / dx[:, y, z]

    bxcvx = (-1 / J) * (dBydz / B**2.)
    bxcvy = (1 / J) * ((dBxdz - dBzdx) / B**2.)
    bxcvz = (1 / J) * (dBydx / B**2.)

    f.write('bxcvz', bxcvz)
    f.write('bxcvx', bxcvx)
    f.write('bxcvy', bxcvy)
    f.close()
Пример #3
0
def change_variable(filename, variable, new_value):
    f = DataFile(filename)

    newfile = DataFile(os.path.splitext(filename)[0] + str(variable) + "." +
                       str(new_value),
                       create=True)

    var_changes = {str(variable)}

    for key in f.keys():
        name = key
        if name in var_changes:
            name = name_changes[name]
        newfile.write(name, np.asarray(f.read(key)))

    f.close()
    newfile.close()

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

    Parameters
    ----------
    averagelast : int, optional
        Number of time points (counting from `final`, inclusive) to
        average over (default is 1 i.e. just take last time-point)
    final : int, optional
        The last time point to use (default is last, -1)
    path : str, optional
        Path to original restart files (default: "data")
    output : str, optional
        Path to write new restart files (default: current directory)
    informat : str, optional
        File extension of original files (default: "nc")
    outformat : str, optional
        File extension of new files (default: use the same as `informat`)

    """

    if outformat is None:
        outformat = 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)

        tind = final
        if tind < 0.0:
            tind = len(t_array) + final

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

        # 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()
Пример #5
0
#!/usr/bin/env python

#
# Generate an input mesh
#

from boututils.datafile 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()
Пример #6
0
def resizeY(newy,
            path="data",
            output=".",
            informat="nc",
            outformat=None,
            myg=2):
    """Increase the number of Y points in restart files

    NOTE:
        * Can't overwrite

    Parameters
    ----------
    newy : int
        ny for the new file
    path : str, optional
        Path to original restart files (default: "data")
    output : str, optional
        Path to write new restart files (default: current directory)
    informat : str, optional
        File extension of original files (default: "nc")
    outformat : str, optional
        File extension of new files (default: use the same as `informat`)
    myg : int, optional
        Number of ghost points in y (default: 2)

    Returns
    -------
    True on success, else False

    TODO
    ----
    - Replace printing errors with raising `ValueError`
    - Make informat work like `redistribute`

    """

    if outformat is 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", "NXPE", "NYPE", "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(" -> Resizing " + 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)
            elif infile.ndims(var) == 2:
                # Assume evolving variable [x,y]
                print(" -> Resizing " + var)

                # Read variable from input
                indata = infile.read(var)

                nx, ny = 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])

                for x in range(nx):
                    f = interp1d(iny,
                                 indata[x, :],
                                 bounds_error=False,
                                 fill_value=0.0)
                    outdata[x, :] = f(outy)

                outfile.write(var, outdata)
            else:
                # Copy variable
                print(" -> Copying " + var)

                # Read variable from input
                data = infile.read(var)
                try:
                    # Convert to scalar if necessary
                    data = data[0]
                except:
                    pass
                outfile.write(var, data)

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

    if outformat is 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()
Пример #8
0
from past.utils import old_div
from boututils.datafile 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()
def smooth_metric(fname,
                  write_to_file=False,
                  return_values=False,
                  smooth_metric=True,
                  order=7):
    from scipy.signal import savgol_filter
    f = DataFile(str(fname), write=True)
    B = f.read('B')
    bxcvx = f.read('bxcvx')
    bxcvz = f.read('bxcvz')
    bxcvy = f.read('bxcvy')
    J = f.read('J')

    bxcvx_smooth = np.zeros(bxcvx.shape)
    bxcvy_smooth = np.zeros(bxcvy.shape)
    bxcvz_smooth = np.zeros(bxcvz.shape)
    J_smooth = np.zeros(J.shape)

    if smooth_metric:
        g13 = f.read('g13')
        g_13 = f.read('g_13')
        g11 = f.read('g11')
        g_11 = f.read('g_11')
        g33 = f.read('g33')
        g_33 = f.read('g_33')

        g13_smooth = np.zeros(g13.shape)
        g_13_smooth = np.zeros(g_13.shape)
        g11_smooth = np.zeros(g11.shape)
        g_11_smooth = np.zeros(g_11.shape)
        g33_smooth = np.zeros(g33.shape)
        g_33_smooth = np.zeros(g_33.shape)

    for y in np.arange(0, bxcvx.shape[1]):
        for x in np.arange(0, bxcvx.shape[0]):
            bxcvx_smooth[x, y, :] = savgol_filter(
                bxcvx[x, y, :],
                np.int(np.ceil(bxcvx.shape[-1] / 2) // 2 * 2 + 1), order)
            bxcvz_smooth[x, y, :] = savgol_filter(
                bxcvz[x, y, :],
                np.int(np.ceil(bxcvz.shape[-1] / 2) // 2 * 2 + 1), order)
            bxcvy_smooth[x, y, :] = savgol_filter(
                bxcvy[x, y, :],
                np.int(np.ceil(bxcvy.shape[-1] / 2) // 2 * 2 + 1), order)
            J_smooth[x, y, :] = savgol_filter(
                J[x, y, :], np.int(np.ceil(J.shape[-1] / 2) // 2 * 2 + 1),
                order)
            if smooth_metric:
                g11_smooth[x, y, :] = savgol_filter(
                    g11[x, y, :],
                    np.int(np.ceil(g11.shape[-1] / 2) // 2 * 2 + 1), order)
                g_11_smooth[x, y, :] = savgol_filter(
                    g_11[x, y, :],
                    np.int(np.ceil(g_11.shape[-1] / 2) // 2 * 2 + 1), order)
                g13_smooth[x, y, :] = savgol_filter(
                    g13[x, y, :],
                    np.int(np.ceil(g13.shape[-1] / 2) // 2 * 2 + 1), order)
                g_13_smooth[x, y, :] = savgol_filter(
                    g_13[x, y, :],
                    np.int(np.ceil(g_13.shape[-1] / 2) // 2 * 2 + 1), order)
                g33_smooth[x, y, :] = savgol_filter(
                    g33[x, y, :],
                    np.int(np.ceil(g33.shape[-1] / 2) // 2 * 2 + 1), order)
                g_33_smooth[x, y, :] = savgol_filter(
                    g_33[x, y, :],
                    np.int(np.ceil(g_33.shape[-1] / 2) // 2 * 2 + 1), order)

    if (write_to_file):
        # f.write('bxcvx',bxcvx_smooth)
        # f.write('bxcvy',bxcvy_smooth)
        # f.write('bxcvz',bxcvz_smooth)
        f.write('J', J_smooth)

        if smooth_metric:
            f.write('g11', g11_smooth)
            f.write('g_11', g_11_smooth)
            f.write('g13', g13_smooth)
            f.write('g_13', g_13_smooth)
            f.write('g33', g33_smooth)
            f.write('g_33', g_33_smooth)

    f.close()
    if (return_values):
        return bxcvx_smooth, bxcvy_smooth, bxcvz_smooth, bxcvx, bxcvy, bxcvz
def calc_curvilinear_curvature(fname, field, grid, maps):
    from scipy.signal import savgol_filter

    f = DataFile(str(fname), write=True)
    B = f.read("B")

    dx = grid.metric()["dx"]
    dz = grid.metric()["dz"]
    g_11 = grid.metric()["g_xx"]
    g_22 = grid.metric()["g_yy"]
    g_33 = grid.metric()["g_zz"]
    g_12 = 0.0
    g_13 = grid.metric()["g_xz"]
    g_23 = 0.0

    GR = np.zeros(B.shape)
    GZ = np.zeros(B.shape)
    Gphi = np.zeros(B.shape)
    dRdz = np.zeros(B.shape)
    dZdz = np.zeros(B.shape)
    dRdx = np.zeros(B.shape)
    dZdx = np.zeros(B.shape)

    for y in np.arange(0, B.shape[1]):
        pol, _ = grid.getPoloidalGrid(y)
        R = pol.R
        Z = pol.Z
        # G = \vec{B}/B, here in cylindrical coordinates
        GR[:, y, :] = field.Bxfunc(R, y, Z) / ((B[:, y, :])**2)
        GZ[:, y, :] = field.Bzfunc(R, y, Z) / ((B[:, y, :])**2)
        Gphi[:, y, :] = field.Byfunc(R, y, Z) / ((B[:, y, :])**2)
        for x in np.arange(0, B.shape[0]):
            dRdz[x, y, :] = calc.deriv(R[x, :]) / dz[x, y, :]
            dZdz[x, y, :] = calc.deriv(Z[x, :]) / dz[x, y, :]
        for z in np.arange(0, B.shape[-1]):
            dRdx[:, y, z] = calc.deriv(R[:, z]) / dx[:, y, z]
            dZdx[:, y, z] = calc.deriv(Z[:, z]) / dx[:, y, z]

    R = f.read("R")
    Z = f.read("Z")
    dy = f.read("dy")

    ## calculate Jacobian and contravariant terms in curvilinear coordinates
    J = R * (dZdz * dRdx - dZdx * dRdz)
    Gx = (GR * dZdz - GZ * dRdz) * (R / J)
    Gz = (GZ * dRdx - GR * dZdx) * (R / J)

    G_x = Gx * g_11 + Gphi * g_12 + Gz * g_13
    G_y = Gx * g_12 + Gphi * g_22 + Gz * g_23
    G_z = Gx * g_13 + Gphi * g_23 + Gz * g_33

    dG_zdy = np.zeros(B.shape)
    dG_ydz = np.zeros(B.shape)
    dG_xdz = np.zeros(B.shape)
    dG_zdx = np.zeros(B.shape)
    dG_ydx = np.zeros(B.shape)
    dG_xdy = np.zeros(B.shape)
    for y in np.arange(0, B.shape[1]):
        for x in np.arange(0, B.shape[0]):
            dG_ydz[x, y, :] = calc.deriv(G_y[x, y, :]) / dz[x, y, :]
            dG_xdz[x, y, :] = calc.deriv(G_x[x, y, :]) / dz[x, y, :]
        for z in np.arange(0, B.shape[-1]):
            dG_ydx[:, y, z] = calc.deriv(G_y[:, y, z]) / dx[:, y, z]
            dG_zdx[:, y, z] = calc.deriv(G_z[:, y, z]) / dx[:, y, z]

    #this should really use the maps...
    for x in np.arange(0, B.shape[0]):
        for z in np.arange(0, B.shape[-1]):
            dG_zdy[x, :, z] = calc.deriv(G_z[x, :, z]) / dy[x, :, z]
            dG_xdy[x, :, z] = calc.deriv(G_x[x, :, z]) / dy[x, :, z]

    bxcvx = (dG_zdy - dG_ydz) / J
    bxcvy = (dG_xdz - dG_zdx) / J
    bxcvz = (dG_ydx - dG_xdy) / J
    bxcv = g_11 * (bxcvx**2) + g_22 * (bxcvy**2) + g_33 * (bxcvz**2) + 2 * (
        bxcvz * bxcvx * g_13)
    f.write('bxcvx', bxcvx)
    f.write('bxcvy', bxcvy)
    f.write('bxcvz', bxcvz)
    f.write('J', J)
    f.close()
def rotating_ellipse(nx=68,
                     ny=16,
                     nz=128,
                     xcentre=5.5,
                     I_coil=0.01,
                     curvilinear=True,
                     rectangular=False,
                     fname='rotating-ellipse.fci.nc',
                     a=0.4,
                     curvilinear_inner_aligned=True,
                     curvilinear_outer_aligned=True,
                     npoints=421,
                     Btor=2.5,
                     show_maps=False,
                     calc_curvature=True,
                     smooth_curvature=False,
                     return_iota=True,
                     write_iota=False):
    yperiod = 2 * np.pi / 5.
    field = zb.field.RotatingEllipse(xcentre=xcentre,
                                     I_coil=I_coil,
                                     radius=2 * a,
                                     yperiod=yperiod,
                                     Btor=Btor)
    # Define the y locations
    ycoords = np.linspace(0.0, yperiod, ny, endpoint=False)
    start_r = xcentre + a / 2.
    start_z = 0.

    if rectangular:
        print("Making rectangular poloidal grid")
        poloidal_grid = zb.poloidal_grid.RectangularPoloidalGrid(
            nx, nz, 1.0, 1.0, Rcentre=xcentre)
    elif curvilinear:
        print("Making curvilinear poloidal grid")
        inner = zb.rzline.shaped_line(R0=xcentre,
                                      a=a / 2.,
                                      elong=0,
                                      triang=0.0,
                                      indent=0,
                                      n=npoints)
        outer = zb.rzline.shaped_line(R0=xcentre,
                                      a=a,
                                      elong=0,
                                      triang=0.0,
                                      indent=0,
                                      n=npoints)

        if curvilinear_inner_aligned:
            print("Aligning to inner flux surface...")
            inner_lines = get_lines(field,
                                    start_r,
                                    start_z,
                                    ycoords,
                                    yperiod=yperiod,
                                    npoints=npoints)
        if curvilinear_outer_aligned:
            print("Aligning to outer flux surface...")
            outer_lines = get_lines(field,
                                    xcentre + a,
                                    start_z,
                                    ycoords,
                                    yperiod=yperiod,
                                    npoints=npoints)

        print("creating grid...")
        if curvilinear_inner_aligned:
            if curvilinear_outer_aligned:
                poloidal_grid = [
                    zb.poloidal_grid.grid_elliptic(inner,
                                                   outer,
                                                   nx,
                                                   nz,
                                                   show=show_maps)
                    for inner, outer in zip(inner_lines, outer_lines)
                ]
            else:
                poloidal_grid = [
                    zb.poloidal_grid.grid_elliptic(inner,
                                                   outer,
                                                   nx,
                                                   nz,
                                                   show=show_maps)
                    for inner in inner_lines
                ]
        else:
            poloidal_grid = zb.poloidal_grid.grid_elliptic(
                inner, outer, nx, nz)

    # Create the 3D grid by putting together 2D poloidal grids
    grid = zb.grid.Grid(poloidal_grid, ycoords, yperiod, yperiodic=True)
    maps = zb.make_maps(grid, field)
    zb.write_maps(grid, field, maps, str(fname), metric2d=False)

    if (curvilinear and calc_curvature):
        print("calculating curvature...")
        calc_curvilinear_curvature(fname, field, grid, maps)

    if (calc_curvature and smooth_curvature):
        smooth_metric(fname,
                      write_to_file=True,
                      return_values=False,
                      smooth_metric=True)

    if (return_iota or write_iota):
        rindices = np.linspace(start_r, xcentre + a, nx)
        zindices = np.zeros((nx))
        iota_bar = calc_iota(field, start_r, start_z)
        if (write_iota):
            f = DataFile(str(fname), write=True)
            f.write('iota_bar', iota_bar)
            f.close()
        else:
            print("Iota_bar = ", iota_bar)
Пример #12
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)
Пример #13
0
def resizeY(newy, path="data", output=".", informat="nc", outformat=None, myg=2):
    """Increase the number of Y points in restart files

    NOTE:
        * Can't overwrite

    Parameters
    ----------
    newy : int
        ny for the new file
    path : str, optional
        Path to original restart files (default: "data")
    output : str, optional
        Path to write new restart files (default: current directory)
    informat : str, optional
        File extension of original files (default: "nc")
    outformat : str, optional
        File extension of new files (default: use the same as `informat`)
    myg : int, optional
        Number of ghost points in y (default: 2)

    Returns
    -------
    True on success, else False

    TODO
    ----
    - Replace printing errors with raising `ValueError`
    - Make informat work like `redistribute`

    """

    if outformat is 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", "NXPE", "NYPE", "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(" -> Resizing " + 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)
            elif infile.ndims(var) == 2:
                # Assume evolving variable [x,y]
                print(" -> Resizing " + var)

                # Read variable from input
                indata = infile.read(var)

                nx, ny = 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])

                for x in range(nx):
                    f = interp1d(iny, indata[x, :],
                                 bounds_error=False, fill_value=0.0)
                    outdata[x, :] = f(outy)

                outfile.write(var, outdata)
            else:
                # Copy variable
                print(" -> Copying " + var)

                # Read variable from input
                data = infile.read(var)
                try:
                    # Convert to scalar if necessary
                    data = data[0]
                except:
                    pass
                outfile.write(var, data)

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

    Parameters
    ----------
    averagelast : int, optional
        Number of time points (counting from `final`, inclusive) to
        average over (default is 1 i.e. just take last time-point)
    final : int, optional
        The last time point to use (default is last, -1)
    path : str, optional
        Path to original restart files (default: "data")
    output : str, optional
        Path to write new restart files (default: current directory)
    informat : str, optional
        File extension of original files (default: "nc")
    outformat : str, optional
        File extension of new files (default: use the same as `informat`)

    """

    if outformat is 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)

        tind = final
        if tind < 0.0:
            tind = len(t_array) + final

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

        # 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()
Пример #15
0
#!/usr/bin/env python

#
# Generate an input mesh
#

from boututils.datafile 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()
Пример #16
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)
Пример #17
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.0 * 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.0 * 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.0 * 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.0 * 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()
Пример #18
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 is 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)

        tind = final
        if tind < 0.0:
            tind = len(t_array) + final

        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()
Пример #19
0
def resizeY(newy,
            path="data",
            output=".",
            informat="nc",
            outformat=None,
            myg=2):
    """
    Resize all the restart files in Y
    """

    if outformat is 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(" -> Resizing " + 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)
            elif infile.ndims(var) == 2:
                # Assume evolving variable [x,y]
                print(" -> Resizing " + var)

                # Read variable from input
                indata = infile.read(var)

                nx, ny = 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])

                for x in range(nx):
                    f = interp1d(iny,
                                 indata[x, :],
                                 bounds_error=False,
                                 fill_value=0.0)
                    outdata[x, :] = f(outy)

                outfile.write(var, outdata)
            else:
                # Copy variable
                print(" -> Copying " + var)

                # Read variable from input
                data = infile.read(var)
                try:
                    # Convert to scalar if necessary
                    data = data[0]
                except:
                    pass
                outfile.write(var, data)

        infile.close()
        outfile.close()
Пример #20
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 is 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)

        tind = final
        if tind < 0.0:
            tind = len(t_array) + final

        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()
Пример #21
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()
Пример #22
0
#!/usr/bin/env python

#
# Generate an input mesh
#

from boututils.datafile 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()