Пример #1
0
def constants():
    from pencil.files import pdim
    npar = pdim.read_pdim().npar
    # Get grid dimensions
    from pencil.files import dim
    nx = dim.read_dim().nx
    ny = dim.read_dim().ny
    nz = dim.read_dim().nz

    # Get parameters:
    par = pc.read_param(datadir=datadir)
    cs0 = par.cs0
    pd = par.dustdensity_powerlaw
    pg = par.density_power_law
    eps0 = par.eps_dtog

    # Box size:
    from pencil.files import grid
    Lx = grid.read_grid().Lx
    Ly = grid.read_grid().Ly
    Lz = grid.read_grid().Lz

    r_int = round(np.amin(grid.read_grid().x), 1)
    r_ext = round(np.amax(grid.read_grid().x), 1)

    fname = 'constants'
    fsave = np.savez_compressed(os.path.join(path_dir,fname), npar=npar,
                                nx=nx, ny=ny, nz=nz, cs0=cs0, pd=pd, pg=pg, eps0=eps0,
                                Lx = Lx, Ly = Ly, Lz = Lz, r_int = r_int, r_ext = r_ext)
    xyzname = 'xyz'
    fsave = np.savez_compressed(os.path.join(path_dir, xyzname), r=ff.x, phi=ff.y, z=ff.z)
Пример #2
0
def loadData(field, extension):
    global data
    
    # check if data has already been loaded
    if (field+extension in data.loaded) == False:
        data.slices[field+extension], data.t = pc.read_slices(datadir = 'data', field = field, extension = extension, proc = -1)
        data.dim[field+extension] = pc.read_dim() # system dimensions
        data.param[field+extension] = pc.read_param(quiet=True) # system parameters
        data.loaded.add(field+extension)
Пример #3
0
    def __init__(self, datadir='data/', param=None, dim=None, down=False):
        """Constructor:
         -----------

         Params:
         ------
            datadir='data/' (optionnal)

         Returns:
         -------
            a read_index class
        """
        if param is None:
            param = read_param(datadir=datadir, quiet=True)
        if dim is None:
            dim = read_dim(datadir=datadir, down=down)

        if param.lwrite_aux:
            totalvars = dim.mvar + dim.maux
        else:
            totalvars = dim.mvar

        f = open(os.path.join(datadir, 'index.pro'))
        for line in f.readlines():
            clean = line.strip()
            name = clean.split('=')[0].strip().replace('[',
                                                       '').replace(']', '')
            if (clean.split('=')[1].strip().startswith('intarr(')):
                continue
            if (clean.split('=')[1].strip().startswith('indgen(')):
                val = int(
                    clean.split('=')[1].strip().replace('indgen(',
                                                        '').split(')')[0])
                app = clean.split('=')[1].strip().split('+')
                val = np.arange(val)
                if (len(app) > 1):
                    val = val + int(app[1])
                if (all(val != 0)  and all(val <= totalvars) \
                    and not name.startswith('i_') and name.startswith('i')):
                    name = name.lstrip('i')
                    if (name == 'lnTT' and param.ltemperature_nolog):
                        name = 'tt'
                    self[name] = val
            else:
                val = int(clean.split('=')[1].strip())
                if (val != 0  and val <= totalvars \
                    and not name.startswith('i_') and name.startswith('i')):
                    name = name.lstrip('i')
                    if (name == 'lnTT' and param.ltemperature_nolog):
                        name = 'tt'
                    self[name] = val
Пример #4
0
    def __init__(self, datadir='data/', param=None, dim=None, down=False):
        """Constructor:
         -----------

         Params:
         ------
            datadir='data/' (optionnal)

         Returns:
         -------
            a read_index class
        """
        if param is None:
            param = read_param(datadir=datadir, quiet=True)
        if dim is None:
            dim = read_dim(datadir=datadir,down=down)

        if param.lwrite_aux:
            totalvars = dim.mvar+dim.maux
        else:
            totalvars = dim.mvar

        f = open(os.path.join(datadir,'index.pro'))
        for line in f.readlines():
            clean = line.strip()
            name=clean.split('=')[0].strip().replace('[','').replace(']','')
            if (clean.split('=')[1].strip().startswith('intarr(')):
                continue
            if (clean.split('=')[1].strip().startswith('indgen(')):
                val=int(clean.split('=')[1].strip().replace('indgen(','').split(')')[0])
                app=clean.split('=')[1].strip().split('+')
                val=np.arange(val)
                if (len(app) > 1 ):
                    val=val+int(app[1])
                if (all(val != 0)  and all(val <= totalvars) \
                    and not name.startswith('i_') and name.startswith('i')):
                    name=name.lstrip('i')
                    if (name == 'lnTT' and param.ltemperature_nolog):
                        name = 'tt'
                    self[name] = val
            else:
                val=int(clean.split('=')[1].strip())
                if (val != 0  and val <= totalvars \
                    and not name.startswith('i_') and name.startswith('i')):
                        name=name.lstrip('i')
                        if (name == 'lnTT' and param.ltemperature_nolog):
                                name = 'tt'
                        self[name] = val
Пример #5
0
    def __init__(self, datadir='data/', param=None, dim=None, down=False):
        """Constructor:
         -----------

         Params:
         ------
            datadir='data/' (optionnal)

         Returns:
         -------
            a read_index class
        """
        if param is None:
            param = read_param(datadir=datadir, quiet=True)
        if dim is None:
            dim = read_dim(datadir=datadir, down=down)

        if param.lwrite_aux:
            totalvars = dim.mvar + dim.maux
        else:
            totalvars = dim.mvar

        f = open(os.path.join(datadir, 'index.pro'))
        for line in f.readlines():
            clean = line.strip()
            name = clean.split('=')[0].strip().replace('[',
                                                       '').replace(']', '')
            if (clean.split('=')[1].strip().startswith('intarr(')):
                continue
            val = int(clean.split('=')[1].strip())
            # val=int(float(clean.split('=')[1].strip())) # sean150513

            #            print name,val
            # need to compare val to totalvars as global indices
            # may be present in index.pro
            #            if (val != 0 and val <= totalvars and \
            if (val != 0  and val <= totalvars \
                and not name.startswith('i_') and name.startswith('i')):
                name = name.lstrip('i')
                if (name == 'lnTT' and param.ltemperature_nolog):
                    name = 'tt'
                self[name] = val
Пример #6
0
    def __init__(self, datadir='data/', param=None, dim=None):
        """Constructor:
         -----------

         Params:
         ------
            datadir='data/' (optionnal)

         Returns:
         -------
            a read_index class
        """
        if param is None:
            param = read_param(datadir=datadir, quiet=True)
        if dim is None:
            dim = read_dim(datadir=datadir)

        if param.lwrite_aux:
            totalvars = dim.mvar+dim.maux
        else:
            totalvars = dim.mvar

        f = open(os.path.join(datadir,'index.pro'))
        for line in f.readlines():
            clean = line.strip()
            name=clean.split('=')[0].strip().replace('[','').replace(']','')
            if (clean.split('=')[1].strip().startswith('intarr(')):
	      continue
            val=int(clean.split('=')[1].strip())
           # val=int(float(clean.split('=')[1].strip())) # sean150513

            #            print name,val
            # need to compare val to totalvars as global indices
            # may be present in index.pro
            #            if (val != 0 and val <= totalvars and \
            if (val != 0  and val <= totalvars \
                and not name.startswith('i_') and name.startswith('i')):
                name=name.lstrip('i')
                if (name == 'lnTT' and param.ltemperature_nolog):
                    name = 'tt'
                self[name] = val
Пример #7
0
        dirs = sorted(dirs, key=lambda s: float(s.split('_')[-1]), reverse=True)
    except ValueError:
        dirs = sorted(dirs)
elif len(dirs) == 0:
    print('choose proper datadir')
    sys.exit(1)
if args.helical:
    #dirs.insert(0, 'helical')
    dirs.append( 'helical')
if args.verbose:
    print(dirs)
clrindx = iter(np.linspace(0,1,len(dirs)))

# calculate the timescales
tser = pc.read_ts(datadir=dirs[0])
par2 = pc.read_param(quiet=True, datadir=dirs[0], param2=True)
pars = pc.read_param(quiet=True, datadir=dirs[0])
vA0 = tser.brms[0]
k0 = pars.kpeak_aa
tau0 = (vA0*k0)**-1

# Simple plot
fig, ax  = newfig(0.45, ratio=0.75)


for dd in dirs:   
    if dstart.startswith('delta'):
        tstop = 1.
    else:
        tstop=0
    dim = pc.read_dim(datadir=dd)
Пример #8
0
def pc2vtk_vid(ti=0,
               tf=1,
               datadir='data/',
               proc=-1,
               variables=['rho', 'uu', 'bb'],
               magic=[],
               b_ext=False,
               destination='animation',
               quiet=True):
    """
    Convert data from PencilCode format to vtk.

    call signature::
    
      pc2vtk(ti = 0, tf = 1, datadir = 'data/', proc = -1,
           variables = ['rho','uu','bb'], magic = [],
           destination = 'animation')
    
    Read *varfile* and convert its content into vtk format. Write the result
    in *destination*.
    
    Keyword arguments:
    
      *ti*:
        Initial time.
        
      *tf*:
        Final time.
        
      *datadir*:
        Directory where the data is stored.
       
      *proc*:
        Processor which should be read. Set to -1 for all processors.
      
      *variables* = [ 'rho' , 'lnrho' , 'uu' , 'bb', 'b_mag', 'jj', 'j_mag', 'aa', 'ab', 'TT', 'lnTT', 'cc', 'lncc', 'ss', 'vort' ]
        Variables which should be written.
        
      *magic*: [ 'vort' , 'bb' ]
        Additional variables which should be written.
       
      *b_ext*:
        Add the external magnetic field.
        
      *destination*:
        Destination files without '.vtk' extension. 
        
      *quiet*:
        Keep quiet when reading the var files.
    """

    # this should correct for the case the user type only one variable
    if (len(variables) > 0):
        if (len(variables[0]) == 1):
            variables = [variables]
    # this should correct for the case the user type only one variable
    if (len(magic) > 0):
        if (len(magic[0]) == 1):
            magic = [magic]

    # make sure magic is set when writing 'vort' or 'bb'
    try:
        index = variables.index('vort')
        magic.append('vort')
    except:
        pass
    try:
        index = variables.index('bb')
        magic.append('bb')
    except:
        pass
    try:
        index = variables.index('b_mag')
        magic.append('bb')
    except:
        pass
    try:
        index = variables.index('jj')
        magic.append('jj')
    except:
        pass
    try:
        index = variables.index('j_mag')
        magic.append('jj')
    except:
        pass

    for i in range(ti, tf + 1):
        varfile = 'VAR' + str(i)
        # reading pc variables and setting dimensions
        var = pc.read_var(varfile=varfile,
                          datadir=datadir,
                          proc=proc,
                          magic=magic,
                          trimall=True,
                          quiet=quiet)

        grid = pc.read_grid(datadir=datadir, proc=proc, trim=True, quiet=True)

        params = pc.read_param(param2=True, quiet=True)
        B_ext = np.array(params.b_ext)
        # add external magnetic field
        if (b_ext == True):
            var.bb[0, ...] += B_ext[0]
            var.bb[1, ...] += B_ext[1]
            var.bb[2, ...] += B_ext[2]

        dimx = len(grid.x)
        dimy = len(grid.y)
        dimz = len(grid.z)
        dim = dimx * dimy * dimz
        dx = (np.max(grid.x) - np.min(grid.x)) / (dimx - 1)
        dy = (np.max(grid.y) - np.min(grid.y)) / (dimy - 1)
        dz = (np.max(grid.z) - np.min(grid.z)) / (dimz - 1)

        #fd = open(destination + "{0:1.0f}".format(var.t*1e5) + '.vtk', 'wb')
        fd = open(destination + str(i) + '.vtk', 'wb')
        fd.write('# vtk DataFile Version 2.0\n'.encode('utf-8'))
        fd.write('density + magnetic field\n'.encode('utf-8'))
        fd.write('BINARY\n'.encode('utf-8'))
        fd.write('DATASET STRUCTURED_POINTS\n'.encode('utf-8'))
        fd.write('DIMENSIONS {0:9} {1:9} {2:9}\n'.format(dimx, dimy,
                                                         dimz).encode('utf-8'))
        fd.write('ORIGIN {0:8.12} {1:8.12} {2:8.12}\n'.format(
            grid.x[0], grid.y[0], grid.z[0]).encode('utf-8'))
        fd.write('SPACING {0:8.12} {1:8.12} {2:8.12}\n'.format(
            dx, dy, dz).encode('utf-8'))
        fd.write('POINT_DATA {0:9}\n'.format(dim).encode('utf-8'))

        try:
            index = variables.index('rho')
            print('writing rho')
            fd.write('SCALARS rho float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.rho[k, j, i]))
        except:
            pass

        try:
            index = variables.index('lnrho')
            print('writing lnrho')
            fd.write('SCALARS lnrho float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.lnrho[k, j, i]))
        except:
            pass

        try:
            index = variables.index('uu')
            print('writing uu')
            fd.write('VECTORS vfield float\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.uu[0, k, j, i]))
                        fd.write(struct.pack(">f", var.uu[1, k, j, i]))
                        fd.write(struct.pack(">f", var.uu[2, k, j, i]))
        except:
            pass

        try:
            index = variables.index('bb')
            print('writing bb')
            fd.write('VECTORS bfield float\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.bb[0, k, j, i]))
                        fd.write(struct.pack(">f", var.bb[1, k, j, i]))
                        fd.write(struct.pack(">f", var.bb[2, k, j, i]))
        except:
            pass

        try:
            index = variables.index('b_mag')
            b_mag = np.sqrt(pc.dot2(var.bb))
            print('writing b_mag')
            fd.write('SCALARS b_mag float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", b_mag[k, j, i]))
        except:
            pass

        try:
            index = variables.index('jj')
            print('writing jj')
            fd.write('VECTORS jfield float\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.jj[0, k, j, i]))
                        fd.write(struct.pack(">f", var.jj[1, k, j, i]))
                        fd.write(struct.pack(">f", var.jj[2, k, j, i]))
        except:
            pass

        try:
            index = variables.index('j_mag')
            j_mag = np.sqrt(pc.dot2(var.jj))
            print('writing j_mag')
            fd.write('SCALARS j_mag float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", j_mag[k, j, i]))
        except:
            pass

        try:
            index = variables.index('aa')
            print('writing aa')
            fd.write('VECTORS afield float\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.aa[0, k, j, i]))
                        fd.write(struct.pack(">f", var.aa[1, k, j, i]))
                        fd.write(struct.pack(">f", var.aa[2, k, j, i]))
        except:
            pass

        try:
            index = variables.index('ab')
            ab = pc.dot(var.aa, var.bb)
            print('writing ab')
            fd.write('SCALARS ab float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", ab[k, j, i]))
        except:
            pass

        try:
            index = variables.index('TT')
            print('writing TT')
            fd.write('SCALARS TT float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.TT[k, j, i]))
        except:
            pass

        try:
            index = variables.index('lnTT')
            print('writing lnTT')
            fd.write('SCALARS lnTT float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.lnTT[k, j, i]))
        except:
            pass

        try:
            index = variables.index('cc')
            print('writing cc')
            fd.write('SCALARS cc float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.cc[k, j, i]))
        except:
            pass

        try:
            index = variables.index('lncc')
            print('writing lncc')
            fd.write('SCALARS lncc float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.lncc[k, j, i]))
        except:
            pass

        try:
            index = variables.index('ss')
            print('writing ss')
            fd.write('SCALARS ss float\n'.encode('utf-8'))
            fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.ss[k, j, i]))
        except:
            pass

        try:
            index = variables.index('vort')
            print('writing vort')
            fd.write('VECTORS vorticity float\n'.encode('utf-8'))
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.vort[0, k, j, i]))
                        fd.write(struct.pack(">f", var.vort[1, k, j, i]))
                        fd.write(struct.pack(">f", var.vort[2, k, j, i]))
        except:
            pass

        del (var)

        fd.close()
Пример #9
0
T_smooth = [Tk_smooth, Tp_smooth, Tq_smooth]
gauss_image = gaussian_filter(T_list[j], sigma)
#ax2.imshow(np.real(T_kpq[256,:,:]), cmap=plt.cm.hot)
im = ax2.imshow(gauss_image[:ex,:ex], extent=[0,ex/k0,ex/k0,0])
#divider = make_axes_locatable(ax2)
#ax2.set_xlim(0,100/k0)
#ax2.set_ylim(0,100/k0)
#cax = divider.append_axes("right", size="5%", pad=0.05)
ax2.set_xlabel(xlbl[j])
ax2.set_ylabel(ylbl[j])
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top')
# Setup Figure and Axes
fwidth = 0.45
#tser = pc.read_ts(datadir=args.ddir, quiet=not args.verbose)
par = pc.read_param(datadir=args.ddir, quiet=True)
kpeak = par.kpeak_aa
tau0 = (tser.brms[0]*kpeak)**-1
if args.verbose:
    print('tau = ', tau0)
#if args.peak:
#    args.tsplot = True
fig, ax  = newfig(fwidth)

ax.text(0.92, 0.08, r'$\times 10^{-5}$', va='top', transform=ax.transAxes)
ax.set_xlabel(r'time $t/\tau_0$')
fig.tight_layout()
if args.ddir.endswith('/'):
    args.ddir = args.ddir[:-1]
if args.helicity:
    fname = join(figdir, args.ddir + '_helicity_ts')
Пример #10
0
def slices2vtk(
    variables=["rho"],
    extensions=["xy", "xy2", "xz", "yz"],
    datadir="data/",
    destination="slices",
    proc=-1,
    format="native",
):
    """
    Convert slices from PencilCode format to vtk.

    call signature::
    
      slices2vtk(variables = ['rho'], extensions = ['xy', 'xy2', 'xz', 'yz'],
           datadir = 'data/', destination = 'slices', proc = -1,
           format = 'native'):
    
    Read slice files specified by *variables* and convert
    them into vtk format for the specified extensions.
    Write the result in *destination*.
    NB: You need to have called src/read_videofiles.x before using this script.
    
    Keyword arguments:
    
      *variables*:
        All allowed fields which can be written as slice files, e.g. b2, uu1, lnrho, ...
        See the pencil code manual for more (chapter: "List of parameters for `video.in'").
        
      *extensions*:
        List of slice positions.
      
      *datadir*:
        Directory where the data is stored.
       
      *destination*:
        Destination files.
        
      *proc*:
        Processor which should be read. Set to -1 for all processors.
      
      *format*:
        Endian, one of little, big, or native (default)
       
    """

    # this should correct for the case the user types only one variable
    if len(variables) > 0:
        if len(variables[0]) == 1:
            variables = [variables]
    # this should correct for the case the user types only one extension
    if len(extensions) > 0:
        if len(extensions[0]) == 1:
            extensions = [extensions]

    # read the grid dimensions
    grid = pc.read_grid(datadir=datadir, proc=proc, trim=True, quiet=True)

    # read the user given parameters for the slice positions
    params = pc.read_param(param2=True, quiet=True)

    # run through all specified variables
    for field in variables:
        # run through all specified extensions
        for ext in extensions:
            print("read ", field, " ", ext)
            slices, t = pc.read_slices(field=field, datadir=datadir, proc=proc, extension=ext, format=format)

            dim_p = slices.shape[2]
            dim_q = slices.shape[1]
            if ext[0] == "x":
                d_p = (np.max(grid.x) - np.min(grid.x)) / (dim_p)
            else:
                d_p = (np.max(grid.y) - np.min(grid.y)) / (dim_p)
            if ext[1] == "y":
                d_q = (np.max(grid.y) - np.min(grid.y)) / (dim_q)
            else:
                d_q = (np.max(grid.z) - np.min(grid.z)) / (dim_q)

            if params.ix != -1:
                x0 = grid.x[params.ix]
            elif params.slice_position == "m":
                x0 = grid.x[len(grid.x) / 2]
            if params.iy != -1:
                y0 = grid.y[params.iy]
            elif params.slice_position == "m":
                y0 = grid.y[len(grid.y) / 2]
            if params.iz != -1:
                z0 = grid.z[params.iz]
            elif params.slice_position == "m":
                z0 = grid.z[len(grid.z) / 2]

            for i in range(slices.shape[0]):
                # open the destination file for writing
                fd = open(destination + "_" + field + "_" + ext + "_" + str(i) + ".vtk", "wb")

                # write the header
                fd.write("# vtk DataFile Version 2.0\n")
                fd.write(field + "_" + ext + "\n")
                fd.write("BINARY\n")
                fd.write("DATASET STRUCTURED_POINTS\n")
                if ext[0:2] == "xy":
                    x0 = grid.x[0]
                    y0 = grid.y[0]
                    fd.write("DIMENSIONS {0:9} {1:9} {2:9}\n".format(dim_p, dim_q, 1))
                    fd.write("ORIGIN {0:8.12} {1:8.12} {2:8.12}\n".format(x0, y0, z0))
                    fd.write("SPACING {0:8.12} {1:8.12} {2:8.12}\n".format(grid.dx, grid.dy, 1.0))
                elif ext[0:2] == "xz":
                    x0 = grid.x[0]
                    z0 = grid.z[0]
                    fd.write("DIMENSIONS {0:9} {1:9} {2:9}\n".format(dim_p, 1, dim_q))
                    fd.write("ORIGIN {0:8.12} {1:8.12} {2:8.12}\n".format(x0, y0, z0))
                    fd.write("SPACING {0:8.12} {1:8.12} {2:8.12}\n".format(grid.dx, 1.0, grid.dy))
                elif ext[0:2] == "yz":
                    y0 = grid.y[0]
                    z0 = grid.z[0]
                    fd.write("DIMENSIONS {0:9} {1:9} {2:9}\n".format(1, dim_p, dim_q))
                    fd.write("ORIGIN {0:8.12} {1:8.12} {2:8.12}\n".format(x0, y0, z0))
                    fd.write("SPACING {0:8.12} {1:8.12} {2:8.12}\n".format(1.0, grid.dy, grid.dy))
                fd.write("POINT_DATA {0:9}\n".format(dim_p * dim_q))

                fd.write("SCALARS " + field + "_" + ext + " float\n")
                fd.write("LOOKUP_TABLE default\n")
                for j in range(dim_q):
                    for k in range(dim_p):
                        fd.write(struct.pack(">f", slices[i, j, k]))

                fd.close()
Пример #11
0
can be found at any given time. also the mean drift can be found.
'''


def X_(s, st, n, p, lx):
    inds = np.random.randint(0, 1000000, n)
    I, X = p[s:st, 0, :], p[s:st, 1, :]
    X_ = np.zeros((st - s, len(inds)))
    for i in range(len(inds)):
        x = deconv(X[I == inds[i]], lx)
        X_[:, i] = x - x[0]
        print(i)
    return X_


param = pc.read_param()
lx = param.lxyz[0]  # here we get the domain size

p = get_party(s, st)  # get particle info for desired time steps

xx = X_(0, st - s, n, p, lx)  # xx is the array of displacments

sig2a = np.var(
    xx, 1)  # this is the variacne of the displacment over the particles.
# by fitting this we get the diffusivity

meanxt = np.mean(xx, 1)  # by fitting this we get the mean drift
'''
this creates directory diffusio_measerments and saves both time series from
 above for latter use or refitting
'''
Пример #12
0
#
# $Id: fourier.py,v 1.3 2009-04-27 10:29:47 dintrans Exp $
# Fourier diagram of the vertical velocity
#

import numpy as N
import pylab as P
import pencil as pc
from scipy.integrate import simps
from theory import *

uz, t = pc.read_slices(field='uu3', proc=0)

dim = pc.read_dim()
par = pc.read_param(quiet=True)
par2 = pc.read_param(quiet=True, param2=True)
grid = pc.read_grid(param=par, quiet=True, trim=True)
nt = len(t)
uz = uz.reshape(nt, dim.nz, dim.nx)

w1 = N.empty((nt, dim.nz, dim.nx), dtype='Complex64')
for i in range(dim.nz):
    w1[:, i, :] = N.fft.fft2(uz[:, i, :]) / nt / dim.nx
w2 = N.abs(w1[1:nt / 2 + 1, ...])
dw = 2 * N.pi / (t[-1] - t[0])
w = dw * N.arange(nt)
w = w[1:nt / 2 + 1]

kmax = 5
inte = N.empty((nt / 2, kmax + 1), dtype='Float64')
Пример #13
0
    def find_fixed(self,
                   datadir='data/',
                   destination='fixed_points.hf5',
                   varfile='VAR0',
                   ti=-1,
                   tf=-1,
                   trace_field='bb',
                   h_min=2e-3,
                   h_max=2e4,
                   len_max=500,
                   tol=1e-2,
                   interpolation='trilinear',
                   trace_sub=1,
                   integration='simple',
                   int_q=[''],
                   n_proc=1,
                   tracer_file_name=''):
        """
        Find the fixed points.

        call signature::

        find_fixed(datadir='data/', destination='fixed_points.hf5',
                   varfile='VAR0', ti=-1, tf=-1, trace_field='bb', h_min=2e-3,
                   h_max=2e4, len_max=500, tol=1e-2, interpolation='trilinear',
                   trace_sub=1, integration='simple', int_q=[''], n_proc=1):

        Finds the fixed points. Returns the fixed points positions.

        Keyword arguments:

          *datadir*:
            Data directory.

          *destination*:
            Name of the fixed points file.

         *varfile*:
           Varfile to be read.

          *ti*:
            Initial VAR file index for tracer time sequences.

          *tf*:
            Final VAR file index for tracer time sequences.

         *trace_field*:
           Vector field used for the streamline tracing.

         *h_min*:
           Minimum step length for and underflow to occur.

         *h_max*:
           Parameter for the initial step length.

         *len_max*:
           Maximum length of the streamline. Integration will stop if
           l >= len_max.

         *tol*:
           Tolerance for each integration step.
           Reduces the step length if error >= tol.

         *interpolation*:
           Interpolation of the vector field.
           'mean': takes the mean of the adjacent grid point.
           'trilinear': weights the adjacent grid points according to
                        their distance.

         *trace_sub*:
           Number of sub-grid cells for the seeds for the initial mapping.

          *integration*:
            Integration method.
            'simple': low order method.
            'RK6': Runge-Kutta 6th order.

         *int_q*:
           Quantities to be integrated along the streamlines.

         *n_proc*:
           Number of cores for multi core computation.

         *tracer_file_name*
           Name of the tracer file to be read.
           If equal to '' it will compute the tracers.
        """

        import numpy as np

        # Return the fixed points for a subset of the domain.
        def __sub_fixed(queue, ix0, iy0, field, tracers, tidx, var, i_proc):
            diff = np.zeros((4, 2))
            fixed = []
            fixed_sign = []
            fidx = 0
            poincare_array = np.zeros(
                (tracers.x0[i_proc::self.params.n_proc].shape[0],
                 tracers.x0.shape[1]))

            for ix in ix0[i_proc::self.params.n_proc]:
                for iy in iy0:
                    # Compute Poincare index around this cell (!= 0 for potential fixed point).
                    diff[0, :] = np.array([
                        tracers.x1[ix, iy, tidx] - tracers.x0[ix, iy, tidx],
                        tracers.y1[ix, iy, tidx] - tracers.y0[ix, iy, tidx]
                    ])
                    diff[1, :] = np.array([
                        tracers.x1[ix + 1, iy, tidx] -
                        tracers.x0[ix + 1, iy, tidx],
                        tracers.y1[ix + 1, iy, tidx] -
                        tracers.y0[ix + 1, iy, tidx]
                    ])
                    diff[2, :] = np.array([
                        tracers.x1[ix + 1, iy + 1, tidx] -
                        tracers.x0[ix + 1, iy + 1, tidx],
                        tracers.y1[ix + 1, iy + 1, tidx] -
                        tracers.y0[ix + 1, iy + 1, tidx]
                    ])
                    diff[3, :] = np.array([
                        tracers.x1[ix, iy + 1, tidx] -
                        tracers.x0[ix, iy + 1, tidx],
                        tracers.y1[ix, iy + 1, tidx] -
                        tracers.y0[ix, iy + 1, tidx]
                    ])
                    if sum(np.sum(diff**2, axis=1) != 0):
                        diff = np.swapaxes(
                            np.swapaxes(diff, 0, 1) /
                            np.sqrt(np.sum(diff**2, axis=1)), 0, 1)
                    poincare = __poincare_index(
                        field, tracers.x0[ix:ix + 2, iy, tidx],
                        tracers.y0[ix, iy:iy + 2, tidx], diff)
                    poincare_array[ix / n_proc, iy] = poincare

                    if abs(
                            poincare
                    ) > 5:  # Use 5 instead of 2*pi to account for rounding errors.
                        # Subsample to get starting point for iteration.
                        nt = 4
                        xmin = tracers.x0[ix, iy, tidx]
                        ymin = tracers.y0[ix, iy, tidx]
                        xmax = tracers.x0[ix + 1, iy, tidx]
                        ymax = tracers.y0[ix, iy + 1, tidx]
                        xx = np.zeros((nt**2, 3))
                        tracers_part = np.zeros((nt**2, 5))
                        i1 = 0
                        for j1 in range(nt):
                            for k1 in range(nt):
                                xx[i1,
                                   0] = xmin + j1 / (nt - 1.) * (xmax - xmin)
                                xx[i1,
                                   1] = ymin + k1 / (nt - 1.) * (ymax - ymin)
                                xx[i1, 2] = self.params.Oz
                                i1 += 1
                        for it1 in range(nt**2):
                            stream = Stream(
                                field,
                                self.params,
                                h_min=self.params.h_min,
                                h_max=self.params.h_max,
                                len_max=self.params.len_max,
                                tol=self.params.tol,
                                interpolation=self.params.interpolation,
                                integration=self.params.integration,
                                xx=xx[it1, :])
                            tracers_part[it1, 0:2] = xx[it1, 0:2]
                            tracers_part[it1, 2:] = stream.tracers[
                                stream.stream_len - 1, :]
                        min2 = 1e6
                        minx = xmin
                        miny = ymin
                        i1 = 0
                        for j1 in range(nt):
                            for k1 in range(nt):
                                diff2 = (tracers_part[i1+k1*nt, 2] - \
                                         tracers_part[i1+k1*nt, 0])**2 + \
                                        (tracers_part[i1+k1*nt, 3] - \
                                         tracers_part[i1+k1*nt, 1])**2
                                if diff2 < min2:
                                    min2 = diff2
                                    minx = xmin + j1 / (nt - 1.) * (xmax -
                                                                    xmin)
                                    miny = ymin + k1 / (nt - 1.) * (ymax -
                                                                    ymin)
                                it1 += 1

                        # Get fixed point from this starting position using Newton's method.
                        point = np.array([minx, miny])
                        fixed_point = __null_point(point, var)

                        # Check if fixed point lies inside the cell.
                        if ((fixed_point[0] < tracers.x0[ix, iy, tidx]) or
                            (fixed_point[0] > tracers.x0[ix + 1, iy, tidx])
                                or (fixed_point[1] < tracers.y0[ix, iy, tidx])
                                or
                            (fixed_point[1] > tracers.y0[ix, iy + 1, tidx])):
                            pass
                        else:
                            fixed.append(fixed_point)
                            fixed_sign.append(np.sign(poincare))
                            fidx += np.sign(poincare)

            queue.put((i_proc, fixed, fixed_sign, fidx, poincare_array))

        # Find the Poincare index of this grid cell.
        def __poincare_index(field, sx, sy, diff):
            poincare = 0
            poincare += __edge(field, [sx[0], sx[1]], [sy[0], sy[0]],
                               diff[0, :], diff[1, :], 0)
            poincare += __edge(field, [sx[1], sx[1]], [sy[0], sy[1]],
                               diff[1, :], diff[2, :], 0)
            poincare += __edge(field, [sx[1], sx[0]], [sy[1], sy[1]],
                               diff[2, :], diff[3, :], 0)
            poincare += __edge(field, [sx[0], sx[0]], [sy[1], sy[0]],
                               diff[3, :], diff[0, :], 0)
            return poincare

        # Compute rotation along one edge.
        def __edge(field, sx, sy, diff1, diff2, rec):
            phiMin = np.pi / 8.
            dtot = m.atan2(diff1[0] * diff2[1] - diff2[0] * diff1[1],
                           diff1[0] * diff2[0] + diff1[1] * diff2[1])
            if (abs(dtot) > phiMin) and (rec < 4):
                xm = 0.5 * (sx[0] + sx[1])
                ym = 0.5 * (sy[0] + sy[1])

                # Trace the intermediate field line.
                stream = Stream(field,
                                self.params,
                                h_min=self.params.h_min,
                                h_max=self.params.h_max,
                                len_max=self.params.len_max,
                                tol=self.params.tol,
                                interpolation=self.params.interpolation,
                                integration=self.params.integration,
                                xx=np.array([xm, ym, self.params.Oz]))
                stream_x0 = stream.tracers[0, 0]
                stream_y0 = stream.tracers[0, 1]
                stream_x1 = stream.tracers[stream.stream_len - 1, 0]
                stream_y1 = stream.tracers[stream.stream_len - 1, 1]
                stream_z1 = stream.tracers[stream.stream_len - 1, 2]

                # Discard any streamline which does not converge or hits the boundary.
                #                if ((stream.len >= len_max) or
                #                (stream_z1 < self.params.Oz+self.params.Lz-10*self.params.dz)):
                #                    dtot = 0.
                if False:
                    pass
                else:
                    diffm = np.array(
                        [stream_x1 - stream_x0, stream_y1 - stream_y0])
                    if sum(diffm**2) != 0:
                        diffm = diffm / np.sqrt(sum(diffm**2))
                    dtot = __edge(field, [sx[0], xm], [sy[0], ym], diff1, diffm, rec+1) + \
                           __edge(field, [xm, sx[1]], [ym, sy[1]], diffm, diff2, rec+1)
            return dtot

        # Finds the null point of the mapping, i.e. fixed point, using Newton's method.
        def __null_point(point, var):
            dl = np.min(var.dx, var.dy) / 100.
            it = 0
            # Tracers used to find the fixed point.
            tracers_null = np.zeros((5, 4))
            while True:
                # Trace field lines at original point and for Jacobian.
                # (second order seems to be enough)
                xx = np.zeros((5, 3))
                xx[0, :] = np.array([point[0], point[1], self.params.Oz])
                xx[1, :] = np.array([point[0] - dl, point[1], self.params.Oz])
                xx[2, :] = np.array([point[0] + dl, point[1], self.params.Oz])
                xx[3, :] = np.array([point[0], point[1] - dl, self.params.Oz])
                xx[4, :] = np.array([point[0], point[1] + dl, self.params.Oz])
                for it1 in range(5):
                    stream = Stream(field,
                                    self.params,
                                    h_min=self.params.h_min,
                                    h_max=self.params.h_max,
                                    len_max=self.params.len_max,
                                    tol=self.params.tol,
                                    interpolation=self.params.interpolation,
                                    integration=self.params.integration,
                                    xx=xx[it1, :])
                    tracers_null[it1, :2] = xx[it1, :2]
                    tracers_null[it1,
                                 2:] = stream.tracers[stream.stream_len - 1,
                                                      0:2]

                # Check function convergence.
                ff = np.zeros(2)
                ff[0] = tracers_null[0, 2] - tracers_null[0, 0]
                ff[1] = tracers_null[0, 3] - tracers_null[0, 1]
                if sum(abs(ff)) <= 1e-3 * np.min(self.params.dx,
                                                 self.params.dy):
                    fixed_point = np.array([point[0], point[1]])
                    break

                # Compute the Jacobian.
                fjac = np.zeros((2, 2))
                fjac[0,
                     0] = ((tracers_null[2, 2] - tracers_null[2, 0]) -
                           (tracers_null[1, 2] - tracers_null[1, 0])) / 2. / dl
                fjac[0,
                     1] = ((tracers_null[4, 2] - tracers_null[4, 0]) -
                           (tracers_null[3, 2] - tracers_null[3, 0])) / 2. / dl
                fjac[1,
                     0] = ((tracers_null[2, 3] - tracers_null[2, 1]) -
                           (tracers_null[1, 3] - tracers_null[1, 1])) / 2. / dl
                fjac[1,
                     1] = ((tracers_null[4, 3] - tracers_null[4, 1]) -
                           (tracers_null[3, 3] - tracers_null[3, 1])) / 2. / dl

                # Invert the Jacobian.
                fjin = np.zeros((2, 2))
                det = fjac[0, 0] * fjac[1, 1] - fjac[0, 1] * fjac[1, 0]
                if abs(det) < dl:
                    fixed_point = point
                    break
                fjin[0, 0] = fjac[1, 1]
                fjin[1, 1] = fjac[0, 0]
                fjin[0, 1] = -fjac[0, 1]
                fjin[1, 0] = -fjac[1, 0]
                fjin = fjin / det
                dpoint = np.zeros(2)
                dpoint[0] = -fjin[0, 0] * ff[0] - fjin[0, 1] * ff[1]
                dpoint[1] = -fjin[1, 0] * ff[0] - fjin[1, 1] * ff[1]
                point += dpoint

                # Check root convergence.
                if sum(abs(dpoint)) < 1e-3 * np.min(self.params.dx,
                                                    self.params.dy):
                    fixed_point = point
                    break

                if it > 20:
                    fixed_point = point
                    break

                it += 1

            return fixed_point

        # Find the fixed point using Newton's method, starting at previous fixed point.
        def __sub_fixed_series(queue, t_idx, field, var, i_proc):
            fixed = []
            fixed_sign = []
            for i, point in enumerate(
                    self.fixed_points[t_idx - 1][i_proc::self.params.n_proc]):
                fixed_tentative = __null_point(point, var)
                # Check if the fixed point lies outside the domain.
                if fixed_tentative[0] >= self.params.Ox and \
                fixed_tentative[1] >= self.params.Oy and \
                fixed_tentative[0] <= self.params.Ox+self.params.Lx and \
                fixed_tentative[1] <= self.params.Oy+self.params.Ly:
                    fixed.append(fixed_tentative)
                    fixed_sign.append(self.fixed_sign[t_idx - 1][i_proc +
                                                                 i * n_proc])
            queue.put((i_proc, fixed, fixed_sign))

        # Discard fixed points which are too close to each other.
        def __discard_close_fixed_points(fixed, fixed_sign, var):
            fixed_new = []
            fixed_sign_new = []
            if len(fixed) > 0:
                fixed_new.append(fixed[0])
                fixed_sign_new.append(fixed_sign[0])

                dx = fixed[:, 0] - np.reshape(fixed[:, 0], (fixed.shape[0], 1))
                dy = fixed[:, 1] - np.reshape(fixed[:, 1], (fixed.shape[0], 1))
                mask = (abs(dx) > var.dx / 2) + (abs(dy) > var.dy / 2)

                for idx in range(1, fixed.shape[0]):
                    if all(mask[idx, :idx]):
                        fixed_new.append(fixed[idx])
                        fixed_sign_new.append(fixed_sign[idx])

            return np.array(fixed_new), np.array(fixed_sign_new)

        # Convert int_q string into list.
        if not isinstance(int_q, list):
            int_q = [int_q]
        self.params.int_q = int_q
        if any(np.array(self.params.int_q) == 'curly_A'):
            self.curly_A = []
        if any(np.array(self.params.int_q) == 'ee'):
            self.ee = []

        # Multi core setup.
        if not (np.isscalar(n_proc)) or (n_proc % 1 != 0):
            print("error: invalid processor number")
            return -1
        queue = mp.Queue()

        # Write the tracing parameters.
        self.params = TracersParameterClass()
        self.params.trace_field = trace_field
        self.params.h_min = h_min
        self.params.h_max = h_max
        self.params.len_max = len_max
        self.params.tol = tol
        self.params.interpolation = interpolation
        self.params.trace_sub = trace_sub
        self.params.int_q = int_q
        self.params.varfile = varfile
        self.params.ti = ti
        self.params.tf = tf
        self.params.integration = integration
        self.params.datadir = datadir
        self.params.destination = destination
        self.params.n_proc = n_proc

        # Make sure to read the var files with the correct magic.
        magic = []
        if trace_field == 'bb':
            magic.append('bb')
        if trace_field == 'jj':
            magic.append('jj')
        if trace_field == 'vort':
            magic.append('vort')
        if any(np.array(int_q) == 'ee'):
            magic.append('bb')
            magic.append('jj')
        dim = pc.read_dim(datadir=datadir)

        # Check if user wants a tracer time series.
        if (ti % 1 == 0) and (tf % 1 == 0) and (ti >= 0) and (tf >= ti):
            series = True
            varfile = 'VAR' + str(ti)
            n_times = tf - ti + 1
        else:
            series = False
            n_times = 1
        self.t = np.zeros(n_times)

        # Read the initial field.
        var = pc.read_var(varfile=varfile,
                          datadir=datadir,
                          magic=magic,
                          quiet=True,
                          trimall=True)
        self.t[0] = var.t
        grid = pc.read_grid(datadir=datadir, quiet=True, trim=True)
        field = getattr(var, trace_field)
        param2 = pc.read_param(datadir=datadir, param2=True, quiet=True)
        if any(np.array(int_q) == 'ee'):
            ee = var.jj * param2.eta - pc.cross(var.uu, var.bb)

        # Get the simulation parameters.
        self.params.dx = var.dx
        self.params.dy = var.dy
        self.params.dz = var.dz
        self.params.Ox = var.x[0]
        self.params.Oy = var.y[0]
        self.params.Oz = var.z[0]
        self.params.Lx = grid.Lx
        self.params.Ly = grid.Ly
        self.params.Lz = grid.Lz
        self.params.nx = dim.nx
        self.params.ny = dim.ny
        self.params.nz = dim.nz

        tracers = Tracers()
        # Create the mapping for all times.
        if not tracer_file_name:
            tracers.find_tracers(trace_field=trace_field,
                                 h_min=h_min,
                                 h_max=h_max,
                                 len_max=len_max,
                                 tol=tol,
                                 interpolation=interpolation,
                                 trace_sub=trace_sub,
                                 varfile=varfile,
                                 ti=ti,
                                 tf=tf,
                                 integration=integration,
                                 datadir=datadir,
                                 int_q=int_q,
                                 n_proc=n_proc)
        else:
            tracers.read(datadir=datadir, file_name=tracer_file_name)
        self.tracers = tracers

        # Set some default values.
        self.t = np.zeros((tf - ti + 1) * series + (1 - series))
        self.fidx = np.zeros((tf - ti + 1) * series + (1 - series))
        self.poincare = np.zeros(
            [int(trace_sub * dim.nx),
             int(trace_sub * dim.ny), n_times])
        ix0 = range(0, int(self.params.nx * trace_sub) - 1)
        iy0 = range(0, int(self.params.ny * trace_sub) - 1)

        # Start the parallelized fixed point finding.
        for tidx in range(n_times):
            if tidx > 0:
                var = pc.read_var(varfile='VAR' + str(tidx + ti),
                                  datadir=datadir,
                                  magic=magic,
                                  quiet=True,
                                  trimall=True)
                field = getattr(var, trace_field)
                self.t[tidx] = var.t

            proc = []
            sub_data = []
            fixed = []
            fixed_sign = []
            for i_proc in range(n_proc):
                proc.append(
                    mp.Process(target=__sub_fixed,
                               args=(queue, ix0, iy0, field, self.tracers,
                                     tidx, var, i_proc)))
            for i_proc in range(n_proc):
                proc[i_proc].start()
            for i_proc in range(n_proc):
                sub_data.append(queue.get())
            for i_proc in range(n_proc):
                proc[i_proc].join()
            for i_proc in range(n_proc):
                # Extract the data from the single cores. Mind the order.
                sub_proc = sub_data[i_proc][0]
                fixed.extend(sub_data[i_proc][1])
                fixed_sign.extend(sub_data[i_proc][2])
                self.fidx[tidx] += sub_data[i_proc][3]
                self.poincare[sub_proc::n_proc, :, tidx] = sub_data[i_proc][4]
            for i_proc in range(n_proc):
                proc[i_proc].terminate()

            # Discard fixed points which lie too close to each other.
            fixed, fixed_sign = __discard_close_fixed_points(
                np.array(fixed), np.array(fixed_sign), var)
            self.fixed_points.append(np.array(fixed))
            self.fixed_sign.append(np.array(fixed_sign))

        # Compute the traced quantities along the fixed point streamlines.
        if any(np.array(self.params.int_q) == 'curly_A') or \
        any(np.array(self.params.int_q) == 'ee'):
            for t_idx in range(0, n_times):
                if any(np.array(self.params.int_q) == 'curly_A'):
                    self.curly_A.append([])
                if any(np.array(self.params.int_q) == 'ee'):
                    self.ee.append([])
                for fixed in self.fixed_points[t_idx]:
                    # Trace the stream line.
                    xx = np.array([fixed[0], fixed[1], self.params.Oz])
                    stream = Stream(field,
                                    self.params,
                                    h_min=self.params.h_min,
                                    h_max=self.params.h_max,
                                    len_max=self.params.len_max,
                                    tol=self.params.tol,
                                    interpolation=self.params.interpolation,
                                    integration=self.params.integration,
                                    xx=xx)
                    # Do the field line integration.
                    if any(np.array(self.params.int_q) == 'curly_A'):
                        curly_A = 0
                        for l in range(stream.stream_len - 1):
                            aaInt = vec_int(
                                (stream.tracers[l + 1] + stream.tracers[l]) /
                                2,
                                var,
                                var.aa,
                                interpolation=self.params.interpolation)
                            curly_A += np.dot(
                                aaInt,
                                (stream.tracers[l + 1] - stream.tracers[l]))
                        self.curly_A[-1].append(curly_A)
                    if any(np.array(self.params.int_q) == 'ee'):
                        ee_p = 0
                        for l in range(stream.stream_len - 1):
                            eeInt = vec_int(
                                (stream.tracers[l + 1] + stream.tracers[l]) /
                                2,
                                var,
                                ee,
                                interpolation=self.params.interpolation)
                            ee_p += np.dot(
                                eeInt,
                                (stream.tracers[l + 1] - stream.tracers[l]))
                        self.ee[-1].append(ee_p)
                if any(np.array(self.params.int_q) == 'curly_A'):
                    self.curly_A[-1] = np.array(self.curly_A[-1])
                if any(np.array(self.params.int_q) == 'ee'):
                    self.ee[-1] = np.array(self.ee[-1])
Пример #14
0
def read_tracers(datadir = 'data/', fileName = 'tracers.dat', zlim = [], head_size = 3, post = False):
    """
    Reads the tracer files and composes a color map.

    call signature::

      tracers, mapping, t = read_tracers(fileName = 'tracers.dat', datadir = 'data/', zlim = [], head_size = 3, post = False)

    Reads from the tracer files and computes the color map according to
    A R Yeates and G Hornig 2011 J. Phys. A: Math. Theor. 44 265501
    doi:10.1088/1751-8113/44/26/265501.
    Returns the tracer values, the color mapping and the times of the snapshots.
    The color mapping can be plotted with:
    pc.animate_interactive(mapping[:,::-1,:,:], t, dimOrder = (2,1,0,3))

    Keyword arguments:

      *datadir*:
        Data directory.

      *fileName*:
        Name of the tracer file.

      *zlim*:
        The upper limit for the field line mapping at which a field line is considered
        to have reached the upper boundary.

      *head_size*:
        Size of the Fortran header in binary data. Most of the time this is 3.
        For the St Andrews cluster it is 5.
      
      *post*:
        If True reads the post processed tracer file 'data/tracers.dat'.
    """
    
    class data_struct:
        def __init__(self):
            self.xi = []
            self.yi = []
            self.xf = []
            self.yf = []
            self.zf = []
            self.l = []
            self.q = []

    data = []
    data = data_struct()

    # compute the offset in order to skip Fortran's header byte
    if (post):
        head_size = 0
        off = 2
    if (head_size == 3):
        off = 2
    if (head_size == 5):
        off = 3

    # read the cpu structure
    dim = pc.read_dim(datadir = datadir)
    if (dim.nprocz > 1):
        print(": number of cores in z-direction > 1")
        return -1

    # read the parameters
    params = pc.read_param(datadir = datadir, quiet = True)

    # read the grid
    grid = pc.read_grid(datadir = datadir, quiet = True)

    # determine the file structure
    if (post):
        n_proc = 1
        tracer_file = open(datadir+fileName, 'rb')
        trace_sub = struct.unpack("f", tracer_file.read(4))[0]
        tracer_file.close()
        n_times = int((os.path.getsize(datadir+fileName)-4)/(4*7*int(dim.nx*trace_sub)*int(dim.ny*trace_sub)))
    # sub sampling of the tracers
    if (not(post)):
        n_proc = dim.nprocx*dim.nprocy
        trace_sub = params.trace_sub
        n_times = int(os.path.getsize(datadir+'proc0/'+fileName)/(4*(head_size + 7*np.floor(dim.nx*trace_sub)*np.floor(dim.ny*trace_sub)/dim.nprocx/dim.nprocy)))

    # prepare the output arrays
    tracers = np.zeros((int(dim.nx*trace_sub), int(dim.ny*trace_sub), n_times, 7))
    mapping = np.zeros((int(dim.nx*trace_sub), int(dim.ny*trace_sub), n_times, 3))

    # temporary arrays for one core
    if (post):
        tracers_core = tracers
        mapping_core = mapping
    else:
        tracers_core = np.zeros((int(int(dim.nx*trace_sub)/dim.nprocx), int(int(dim.ny*trace_sub)/dim.nprocy), n_times, 7))
        mapping_core = np.zeros((int(int(dim.nx*trace_sub)/dim.nprocx), int(np.floor(dim.ny*trace_sub)/dim.nprocy), n_times, 3))

    # set the upper z-limit to the domain boundary
    if zlim == []:
        zlim = grid.z[-dim.nghostz-1]

    # read the data from all cores
    for i in range(n_proc):
        # read the cpu structure
        if (post):
            dim_core = pc.read_dim(datadir = datadir, proc = -1)
            dim_core.ipx = 0
            dim_core.ipy = 0
        else:
            dim_core = pc.read_dim(datadir = datadir, proc = i)
        stride = int(dim_core.nx*trace_sub)*int(dim_core.ny*trace_sub)
        llen = head_size + 7*stride + post

        if (post):
            tracer_file = open(datadir+fileName, 'rb')
        else:
            tracer_file = open(datadir+'proc{0}/'.format(i)+fileName, 'rb')
        tmp = array.array('f')
        tmp.read(tracer_file, int((head_size + post + 7*int(dim_core.nx*trace_sub)*int(dim_core.ny*trace_sub))*n_times)+post)
        tracer_file.close()

        t = []

        for j in range(n_times):
            t.append(tmp[off-1+j*llen])
            data.xi = tmp[off+j*llen          : off+1*stride+j*llen]
            data.yi = tmp[off+1*stride+j*llen : off+2*stride+j*llen]
            data.xf = tmp[off+2*stride+j*llen : off+3*stride+j*llen]
            data.yf = tmp[off+3*stride+j*llen : off+4*stride+j*llen]
            data.zf = tmp[off+4*stride+j*llen : off+5*stride+j*llen]
            data.l  = tmp[off+5*stride+j*llen : off+6*stride+j*llen]
            data.q  = tmp[off+6*stride+j*llen : off+7*stride+j*llen]

            # Squeeze the data into 2d array. This make the visualization much faster.
            for l in range(len(data.xi)):
                tracers_core[l%(int(dim_core.nx*trace_sub)),int(l/(int(dim_core.nx*trace_sub))),j,:] = \
                [data.xi[l], data.yi[l], data.xf[l], data.yf[l], data.zf[l], data.l[l], data.q[l]]
                if data.zf[l] >= zlim:
                    if (data.xi[l] - data.xf[l]) > 0:
                        if (data.yi[l] - data.yf[l]) > 0:
                            mapping_core[l%(int(dim_core.nx*trace_sub)),int(l/(int(dim_core.nx*trace_sub))),j,:] = [0,1,0]
                        else:
                            mapping_core[l%(int(dim_core.nx*trace_sub)),int(l/(int(dim_core.nx*trace_sub))),j,:] = [1,1,0]
                    else:
                        if (data.yi[l] - data.yf[l]) > 0:
                            mapping_core[l%(int(dim_core.nx*trace_sub)),int(l/(int(dim_core.nx*trace_sub))),j,:] = [0,0,1]
                        else:
                            mapping_core[l%(int(dim_core.nx*trace_sub)),int(l/(int(dim_core.nx*trace_sub))),j,:] = [1,0,0]
                else:
                    mapping_core[l%(int(dim_core.nx*trace_sub)),int(l/(int(dim_core.nx*trace_sub))),j,:] = [1,1,1]

            # copy single core data into total data arrays
            if (not(post)):
                tracers[np.round(dim_core.ipx*int(dim_core.nx*trace_sub)):np.round((dim_core.ipx+1)*np.floor(dim_core.nx*trace_sub)), \
                        np.round(dim_core.ipy*int(dim_core.ny*trace_sub)):np.round((dim_core.ipy+1)*np.floor(dim_core.ny*trace_sub)),j,:] = \
                        tracers_core[:,:,j,:]
                mapping[np.round(dim_core.ipx*int(dim_core.nx*trace_sub)):np.round((dim_core.ipx+1)*np.floor(dim_core.nx*trace_sub)), \
                        np.round(dim_core.ipy*int(dim_core.ny*trace_sub)):np.round((dim_core.ipy+1)*np.floor(dim_core.ny*trace_sub)),j,:] = \
                        mapping_core[:,:,j,:]

    # swap axes for post evaluation
    tracers = tracers.swapaxes(0, 1)
    mapping = mapping.swapaxes(0, 1)

    return tracers, mapping, t
Пример #15
0
def tracer_movie(datadir='data/',
                 tracerFile='tracers.dat',
                 fixedFile='fixed_points.dat',
                 zlim=[],
                 head_size=3,
                 hm=1,
                 imageDir='./',
                 movieFile='fixed_points.mpg',
                 fps=5.0,
                 bitrate=1800):
    """
    Plots the color mapping together with the fixed points.
    Creates a movie file.

    call signature::

      tracer_movie(datadir = 'data/', tracerFile = 'tracers.dat',
                 fixedFile = 'fixed_points.dat', zlim = [],
                 head_size = 3, hm = 1,
                 imageDir = './', movieFile = 'fixed_points.mpg',
                 fps = 5.0, bitrate = 1800)

    Plots the field line mapping together with the fixed points and creates
    a movie file.

      *datadir*:
        Data directory.

      *tracerFile*:
        Name of the tracer file.

      *fixedFile*:
        Name of the fixed points file.

      *zlim*:
        The upper limit for the field line mapping at which a field line is considered
        to have reached the upper boundary.

      *head_size*:
        Size of the fortran header in binary data. Most of the time this is 3.
        For the St Andrews cluster it is 5.

      *hm*:
        Header multiplication factor in case Fortran's binary data writes extra large
        header. For most cases hm = 1 is sufficient. For the cluster in St Andrews use hm = 2.

      *imageDir*:
        Directory with the temporary png files.

      *movieFile*:
        Output file for the movie. Ending should be 'mpg', since the compression
        format is mpg.

      *fps*:
        Frames per second of the animation.

      *bitrate*:
        Bitrate of the movie file. Set to higher value for higher quality.
    """

    import pylab as plt

    # read the mapping and the fixed point positions
    tracers, mapping, t = pc.read_tracers(datadir=datadir,
                                          fileName=tracerFile,
                                          zlim=zlim,
                                          head_size=head_size)
    fixed = pc.read_fixed_points(datadir=datadir, fileName=fixedFile, hm=hm)

    # read the parameters for the domain boundaries
    params = pc.read_param(quiet=True)
    domain = [params.xyz0[0], params.xyz1[0], params.xyz0[1], params.xyz1[1]]

    # determine the how much faster the fixed pints have been written out than the color mapping
    advance = np.ceil(float(len(fixed.t)) / len(mapping[0, 0, :, 0]))

    # determine the colors for the fixed points
    colors = np.zeros(np.shape(fixed.q) + (3, ))
    colors[:, :, :] = 0.
    print(np.shape(colors))
    for j in range(len(colors[:, 0, 0])):
        for k in range(len(colors[0, :, 0])):
            if fixed.q[j, k] >= 0:
                colors[j, k, 1] = colors[j, k, 2] = (
                    1 - fixed.q[j, k] / np.max(np.abs(fixed.q[:, k])))
                colors[j, k, 0] = fixed.q[j, k] / np.max(np.abs(fixed.q[:, k]))
            else:
                colors[j, k, 0] = colors[j, k, 1] = (
                    1 + fixed.q[j, k] / np.max(np.abs(fixed.q[:, k])))
                colors[j, k,
                       2] = -fixed.q[j, k] / np.max(np.abs(fixed.q[:, k]))

    # prepare the plot
    width = 6
    height = 6
    plt.rc("figure.subplot", left=(60 / 72.27) / width)
    plt.rc("figure.subplot", right=(width - 20 / 72.27) / width)
    plt.rc("figure.subplot", bottom=(50 / 72.27) / height)
    plt.rc("figure.subplot", top=(height - 20 / 72.27) / height)
    figure = plt.figure(figsize=(width, height))

    for k in range(len(fixed.x[0, :])):
        dots = plt.plot(fixed.x[0, k], fixed.y[0, k], 'o', c=colors[0, k, :])
    image = plt.imshow(zip(*mapping[:, ::-1, 0, :]),
                       interpolation='nearest',
                       extent=domain)
    j = 0
    frameName = imageDir + 'images%06d.png' % j
    imageFiles = []
    imageFiles.append(frameName)
    figure.savefig(frameName)

    for j in range(1, len(fixed.t)):
        #time.sleep(0.5)
        figure.clear()
        for k in range(len(fixed.x[j, :])):
            dots = plt.plot(fixed.x[j, k],
                            fixed.y[j, k],
                            'o',
                            c=colors[j, k, :])
        image = plt.imshow(zip(*mapping[:, ::-1,
                                        np.floor(j / advance), :]),
                           interpolation='nearest',
                           extent=domain)
        frameName = imageDir + 'images%06d.png' % j
        imageFiles.append(frameName)
        figure.savefig(frameName)

    # convert the images into a mpg file
    mencodeCommand = "mencoder 'mf://" + imageDir + "images*.png' -mf type=png:fps=" + np.str(
        fps) + " -ovc lavc -lavcopts vcodec=mpeg4:vhq:vbitrate=" + np.str(
            bitrate) + " -ffourcc MP4S -oac copy -o " + movieFile
    os.system(mencodeCommand)

    # remove the image files
    for fname in imageFiles:
        os.remove(fname)
Пример #16
0
import pencil as pc
import numpy as np
from helperfuncs import search_indx
from os import listdir, path
from scipy.optimize import curve_fit
try: 
    dim = pc.read_dim(datadir=dstart)
    krms = np.loadtxt(path.join(dstart,'power_krms.dat')).flatten()[:dim.nxgrid//2]
    print('krms shape: ', krms.shape)
    p0 = (-12.92758524, 1.94666781, 3.4643292)  #(-15.56, 2.20, 4.26)
except FileNotFoundError:
    sys.exit(1)

#read in simulation parameters 
dim = pc.read_dim(datadir=dstart)
pars = pc.read_param(datadir=dstart, quiet=True, param2=True)
xi = dim.nxgrid//2
t, powerb = pc.read_power('power_mag.dat', datadir=dstart)
print('t: ',t.shape, 'powerb: ',powerb.shape)
print('plotting at t = %g' % t[tfit])

# Simple plot setup
plotted = False
fig, ax  = newfig(0.45, ratio=0.75)
#ax.set_xscale('log')
ax.set_yscale('log')
#ax.set_xlim(1,dim.nxgrid//2)
ax.set_xlim(10,50)
ax.set_ylim(round_exp(powerb[tfit,10]),1.5*max(powerb[tfit,:]))
#ax.set_ylim(1e-7, 1e-3)
clr = (0.9, 0.4, 0.4, 1.0)
Пример #17
0
def read_tracers(datadir='data/',
                 fileName='tracers.dat',
                 zlim=[],
                 head_size=3,
                 post=False):
    """
    Reads the tracer files and composes a color map.

    call signature::

      tracers, mapping, t = read_tracers(fileName = 'tracers.dat', datadir = 'data/', zlim = [], head_size = 3, post = False)

    Reads from the tracer files and computes the color map according to
    A R Yeates and G Hornig 2011 J. Phys. A: Math. Theor. 44 265501
    doi:10.1088/1751-8113/44/26/265501.
    Returns the tracer values, the color mapping and the times of the snapshots.
    The color mapping can be plotted with:
    pc.animate_interactive(mapping[:,::-1,:,:], t, dimOrder = (2,1,0,3))

    Keyword arguments:

      *datadir*:
        Data directory.

      *fileName*:
        Name of the tracer file.

      *zlim*:
        The upper limit for the field line mapping at which a field line is considered
        to have reached the upper boundary.

      *head_size*:
        Size of the Fortran header in binary data. Most of the time this is 3.
        For the St Andrews cluster it is 5.
      
      *post*:
        If True reads the post processed tracer file 'data/tracers.dat'.
    """
    class data_struct:
        def __init__(self):
            self.xi = []
            self.yi = []
            self.xf = []
            self.yf = []
            self.zf = []
            self.l = []
            self.q = []

    data = []
    data = data_struct()

    # compute the offset in order to skip Fortran's header byte
    if (post):
        head_size = 0
        off = 2
    if (head_size == 3):
        off = 2
    if (head_size == 5):
        off = 3

    # read the cpu structure
    dim = pc.read_dim(datadir=datadir)
    if (dim.nprocz > 1):
        print(": number of cores in z-direction > 1")
        return -1

    # read the parameters
    params = pc.read_param(datadir=datadir, quiet=True)

    # read the grid
    grid = pc.read_grid(datadir=datadir, quiet=True)

    # determine the file structure
    if (post):
        n_proc = 1
        tracer_file = open(datadir + fileName, 'rb')
        trace_sub = struct.unpack("f", tracer_file.read(4))[0]
        tracer_file.close()
        n_times = int(
            (os.path.getsize(datadir + fileName) - 4) /
            (4 * 7 * int(dim.nx * trace_sub) * int(dim.ny * trace_sub)))
    # sub sampling of the tracers
    if (not (post)):
        n_proc = dim.nprocx * dim.nprocy
        trace_sub = params.trace_sub
        n_times = int(
            os.path.getsize(datadir + 'proc0/' + fileName) /
            (4 * (head_size + 7 * np.floor(dim.nx * trace_sub) *
                  np.floor(dim.ny * trace_sub) / dim.nprocx / dim.nprocy)))

    # prepare the output arrays
    tracers = np.zeros(
        (int(dim.nx * trace_sub), int(dim.ny * trace_sub), n_times, 7))
    mapping = np.zeros(
        (int(dim.nx * trace_sub), int(dim.ny * trace_sub), n_times, 3))

    # temporary arrays for one core
    if (post):
        tracers_core = tracers
        mapping_core = mapping
    else:
        tracers_core = np.zeros(
            (int(int(dim.nx * trace_sub) / dim.nprocx),
             int(int(dim.ny * trace_sub) / dim.nprocy), n_times, 7))
        mapping_core = np.zeros(
            (int(int(dim.nx * trace_sub) / dim.nprocx),
             int(np.floor(dim.ny * trace_sub) / dim.nprocy), n_times, 3))

    # set the upper z-limit to the domain boundary
    if zlim == []:
        zlim = grid.z[-dim.nghostz - 1]

    # read the data from all cores
    for i in range(n_proc):
        # read the cpu structure
        if (post):
            dim_core = pc.read_dim(datadir=datadir, proc=-1)
            dim_core.ipx = 0
            dim_core.ipy = 0
        else:
            dim_core = pc.read_dim(datadir=datadir, proc=i)
        stride = int(dim_core.nx * trace_sub) * int(dim_core.ny * trace_sub)
        llen = head_size + 7 * stride + post

        if (post):
            tracer_file = open(datadir + fileName, 'rb')
        else:
            tracer_file = open(datadir + 'proc{0}/'.format(i) + fileName, 'rb')
        tmp = array.array('f')
        tmp.read(
            tracer_file,
            int((head_size + post + 7 * int(dim_core.nx * trace_sub) *
                 int(dim_core.ny * trace_sub)) * n_times) + post)
        tracer_file.close()

        t = []

        for j in range(n_times):
            t.append(tmp[off - 1 + j * llen])
            data.xi = tmp[off + j * llen:off + 1 * stride + j * llen]
            data.yi = tmp[off + 1 * stride + j * llen:off + 2 * stride +
                          j * llen]
            data.xf = tmp[off + 2 * stride + j * llen:off + 3 * stride +
                          j * llen]
            data.yf = tmp[off + 3 * stride + j * llen:off + 4 * stride +
                          j * llen]
            data.zf = tmp[off + 4 * stride + j * llen:off + 5 * stride +
                          j * llen]
            data.l = tmp[off + 5 * stride + j * llen:off + 6 * stride +
                         j * llen]
            data.q = tmp[off + 6 * stride + j * llen:off + 7 * stride +
                         j * llen]

            # Squeeze the data into 2d array. This make the visualization much faster.
            for l in range(len(data.xi)):
                tracers_core[l%(int(dim_core.nx*trace_sub)),int(l/(int(dim_core.nx*trace_sub))),j,:] = \
                [data.xi[l], data.yi[l], data.xf[l], data.yf[l], data.zf[l], data.l[l], data.q[l]]
                if data.zf[l] >= zlim:
                    if (data.xi[l] - data.xf[l]) > 0:
                        if (data.yi[l] - data.yf[l]) > 0:
                            mapping_core[l % (int(dim_core.nx * trace_sub)),
                                         int(l /
                                             (int(dim_core.nx * trace_sub))),
                                         j, :] = [0, 1, 0]
                        else:
                            mapping_core[l % (int(dim_core.nx * trace_sub)),
                                         int(l /
                                             (int(dim_core.nx * trace_sub))),
                                         j, :] = [1, 1, 0]
                    else:
                        if (data.yi[l] - data.yf[l]) > 0:
                            mapping_core[l % (int(dim_core.nx * trace_sub)),
                                         int(l /
                                             (int(dim_core.nx * trace_sub))),
                                         j, :] = [0, 0, 1]
                        else:
                            mapping_core[l % (int(dim_core.nx * trace_sub)),
                                         int(l /
                                             (int(dim_core.nx * trace_sub))),
                                         j, :] = [1, 0, 0]
                else:
                    mapping_core[l % (int(dim_core.nx * trace_sub)),
                                 int(l / (int(dim_core.nx * trace_sub))),
                                 j, :] = [1, 1, 1]

            # copy single core data into total data arrays
            if (not (post)):
                tracers[np.round(dim_core.ipx*int(dim_core.nx*trace_sub)):np.round((dim_core.ipx+1)*np.floor(dim_core.nx*trace_sub)), \
                        np.round(dim_core.ipy*int(dim_core.ny*trace_sub)):np.round((dim_core.ipy+1)*np.floor(dim_core.ny*trace_sub)),j,:] = \
                        tracers_core[:,:,j,:]
                mapping[np.round(dim_core.ipx*int(dim_core.nx*trace_sub)):np.round((dim_core.ipx+1)*np.floor(dim_core.nx*trace_sub)), \
                        np.round(dim_core.ipy*int(dim_core.ny*trace_sub)):np.round((dim_core.ipy+1)*np.floor(dim_core.ny*trace_sub)),j,:] = \
                        mapping_core[:,:,j,:]

    # swap axes for post evaluation
    tracers = tracers.swapaxes(0, 1)
    mapping = mapping.swapaxes(0, 1)

    return tracers, mapping, t
Пример #18
0
import pencil as pc
import numpy as np
import math
from astropy.constants import au
#
datadir = '../data'
unit_length=au.to('cm').value
par=pc.read_param(datadir=datadir)
#
# According to the RADMC3D manual, the way the variable coordsystem works is
#
# If coordsystem<100 the coordinate system is cartesian.
# If 100<=coordsystem<200 thecoordinate system is spherical (polar).
# If 200<=coordsystem<300 the coordinate system is cylindrical.
#
xdim=unit_length
print par.coord_system
if (par.coord_system == 'cartesian'):
    coordsystem = 99
    ydim=unit_length
    zdim=unit_length
elif (par.coord_system == 'cylindric'):
    coordsystem = 200
    ydim=1.
    zdim=unit_length
elif (par.coord_system == 'spherical'):
    coordsystem = 100
    ydim=1.
    zdim=1.
else:
    print "the world is flat and we never got here"
Пример #19
0
    def find_fixed(self, data_dir='data/', destination='fixed_points.hf5',
                   varfile='VAR0', ti=-1, tf=-1, trace_field='bb', h_min=2e-3,
                   h_max=2e4, len_max=500, tol=1e-2, interpolation='trilinear',
                   trace_sub=1, integration='simple', int_q=[''], n_proc=1):
        """
        Find the fixed points.

        call signature::

        find_fixed(data_dir='data/', destination='fixed_points.hf5',
                   varfile='VAR0', ti=-1, tf=-1, trace_field='bb', h_min=2e-3,
                   h_max=2e4, len_max=500, tol=1e-2, interpolation='trilinear',
                   trace_sub=1, integration='simple', int_q=[''], n_proc=1):

        Finds the fixed points. Returns the fixed points positions.

        Keyword arguments:

          *data_dir*:
            Data directory.

          *destination*:
            Name of the fixed points file.

         *varfile*:
           Varfile to be read.

          *ti*:
            Initial VAR file index for tracer time sequences.

          *tf*:
            Final VAR file index for tracer time sequences.

         *trace_field*:
           Vector field used for the streamline tracing.

         *h_min*:
           Minimum step length for and underflow to occur.

         *h_max*:
           Parameter for the initial step length.

         *len_max*:
           Maximum length of the streamline. Integration will stop if
           l >= len_max.

         *tol*:
           Tolerance for each integration step.
           Reduces the step length if error >= tol.

         *interpolation*:
           Interpolation of the vector field.
           'mean': takes the mean of the adjacent grid point.
           'trilinear': weights the adjacent grid points according to
                        their distance.

         *trace_sub*:
           Number of sub-grid cells for the seeds for the initial mapping.

          *integration*:
            Integration method.
            'simple': low order method.
            'RK6': Runge-Kutta 6th order.

         *int_q*:
           Quantities to be integrated along the streamlines.

         *n_proc*:
           Number of cores for multi core computation.
        """


        # Return the fixed points for a subset of the domain for the initial
        # fixed points.
        def __sub_fixed_init(queue, ix0, iy0, field, tracers, var, i_proc):
            diff = np.zeros((4, 2))

            fixed = []
            fixed_sign = []
            fidx = 0
            poincare_array = np.zeros((tracers.x0[i_proc::self.params.n_proc].shape[0],
                                       tracers.x0.shape[1]))

            for ix in ix0[i_proc::self.params.n_proc]:
                for iy in iy0:
                    # Compute Poincare index around this cell (!= 0 for potential fixed point).
                    diff[0, :] = np.array([tracers.x1[ix, iy, 0] - tracers.x0[ix, iy, 0],
                                           tracers.y1[ix, iy, 0] - tracers.y0[ix, iy, 0]])
                    diff[1, :] = np.array([tracers.x1[ix+1, iy, 0] - tracers.x0[ix+1, iy, 0],
                                           tracers.y1[ix+1, iy, 0] - tracers.y0[ix+1, iy, 0]])
                    diff[2, :] = np.array([tracers.x1[ix+1, iy+1, 0] - tracers.x0[ix+1, iy+1, 0],
                                           tracers.y1[ix+1, iy+1, 0] - tracers.y0[ix+1, iy+1, 0]])
                    diff[3, :] = np.array([tracers.x1[ix, iy+1, 0] - tracers.x0[ix, iy+1, 0],
                                           tracers.y1[ix, iy+1, 0] - tracers.y0[ix, iy+1, 0]])
                    if sum(np.sum(diff**2, axis=1) != 0):
                        diff = np.swapaxes(np.swapaxes(diff, 0, 1) /
                               np.sqrt(np.sum(diff**2, axis=1)), 0, 1)
                    poincare = __poincare_index(field, tracers.x0[ix:ix+2, iy, 0],
                                                tracers.y0[ix, iy:iy+2, 0], diff)
                    poincare_array[ix/n_proc, iy] = poincare

                    if abs(poincare) > 5: # Use 5 instead of 2*pi to account for rounding errors.
                        # Subsample to get starting point for iteration.
                        nt = 4
                        xmin = tracers.x0[ix, iy, 0]
                        ymin = tracers.y0[ix, iy, 0]
                        xmax = tracers.x0[ix+1, iy, 0]
                        ymax = tracers.y0[ix, iy+1, 0]
                        xx = np.zeros((nt**2, 3))
                        tracers_part = np.zeros((nt**2, 5))
                        i1 = 0
                        for j1 in range(nt):
                            for k1 in range(nt):
                                xx[i1, 0] = xmin + j1/(nt-1.)*(xmax-xmin)
                                xx[i1, 1] = ymin + k1/(nt-1.)*(ymax-ymin)
                                xx[i1, 2] = self.params.Oz
                                i1 += 1
                        for it1 in range(nt**2):
                            stream = Stream(field, self.params,
                                            h_min=self.params.h_min,
                                            h_max=self.params.h_max,
                                            len_max=self.params.len_max,
                                            tol=self.params.tol,
                                            interpolation=self.params.interpolation,
                                            integration=self.params.integration,
                                            xx=xx[it1, :])
                            tracers_part[it1, 0:2] = xx[it1, 0:2]
                            tracers_part[it1, 2:] = stream.tracers[stream.stream_len-1, :]
                        min2 = 1e6
                        minx = xmin
                        miny = ymin
                        i1 = 0
                        for j1 in range(nt):
                            for k1 in range(nt):
                                diff2 = (tracers_part[i1+k1*nt, 2] - \
                                         tracers_part[i1+k1*nt, 0])**2 + \
                                        (tracers_part[i1+k1*nt, 3] - \
                                         tracers_part[i1+k1*nt, 1])**2
                                if diff2 < min2:
                                    min2 = diff2
                                    minx = xmin + j1/(nt-1.)*(xmax - xmin)
                                    miny = ymin + k1/(nt-1.)*(ymax - ymin)
                                it1 += 1

                        # Get fixed point from this starting position using Newton's method.
                        point = np.array([minx, miny])
                        fixed_point = __null_point(point, var)

                        # Check if fixed point lies inside the cell.
                        if ((fixed_point[0] < tracers.x0[ix, iy, 0]) or
                            (fixed_point[0] > tracers.x0[ix+1, iy, 0]) or
                            (fixed_point[1] < tracers.y0[ix, iy, 0]) or
                            (fixed_point[1] > tracers.y0[ix, iy+1, 0])):
                            print "warning: fixed point lies outside the cell"
                        else:
                            fixed.append(fixed_point)
                            fixed_sign.append(np.sign(poincare))
                            fidx += np.sign(poincare)

            queue.put((i_proc, fixed, fixed_sign, fidx, poincare_array))


        # Finds the Poincare index of this grid cell.
        def __poincare_index(field, sx, sy, diff):
            poincare = 0
            poincare += __edge(field, [sx[0], sx[1]], [sy[0], sy[0]],
                               diff[0, :], diff[1, :], 0)
            poincare += __edge(field, [sx[1], sx[1]], [sy[0], sy[1]],
                               diff[1, :], diff[2, :], 0)
            poincare += __edge(field, [sx[1], sx[0]], [sy[1], sy[1]],
                               diff[2, :], diff[3, :], 0)
            poincare += __edge(field, [sx[0], sx[0]], [sy[1], sy[0]],
                               diff[3, :], diff[0, :], 0)
            return poincare


        # Compute rotation along one edge.
        def __edge(field, sx, sy, diff1, diff2, rec):
            phiMin = np.pi/8.
            dtot = m.atan2(diff1[0]*diff2[1] - diff2[0]*diff1[1],
                           diff1[0]*diff2[0] + diff1[1]*diff2[1])
            if (abs(dtot) > phiMin) and (rec < 4):
                xm = 0.5*(sx[0]+sx[1])
                ym = 0.5*(sy[0]+sy[1])

                # Trace the intermediate field line.
                stream = Stream(field, self.params, h_min=self.params.h_min,
                                h_max=self.params.h_max,
                                len_max=self.params.len_max,
                                tol=self.params.tol,
                                interpolation=self.params.interpolation,
                                integration=self.params.integration,
                                xx=np.array([xm, ym, self.params.Oz]))
                stream_x0 = stream.tracers[0, 0]
                stream_y0 = stream.tracers[0, 1]
                stream_x1 = stream.tracers[stream.stream_len-1, 0]
                stream_y1 = stream.tracers[stream.stream_len-1, 1]
                stream_z1 = stream.tracers[stream.stream_len-1, 2]

                # Discard any streamline which does not converge or hits the boundary.
                if ((stream.len >= len_max) or
                (stream_z1 < self.params.Oz+self.params.Lz-self.params.dz)):
                    dtot = 0.
                else:
                    diffm = np.array([stream_x1 - stream_x0, stream_y1 - stream_y0])
                    if sum(diffm**2) != 0:
                        diffm = diffm/np.sqrt(sum(diffm**2))
                    dtot = __edge(field, [sx[0], xm], [sy[0], ym], diff1, diffm, rec+1) + \
                           __edge(field, [xm, sx[1]], [ym, sy[1]], diffm, diff2, rec+1)
            return dtot


        # Finds the null point of the mapping, i.e. fixed point, using Newton's method.
        def __null_point(point, var):
            dl = np.min(var.dx, var.dy)/100.
            it = 0
            # Tracers used to find the fixed point.
            tracers_null = np.zeros((5, 4))
            while True:
                # Trace field lines at original point and for Jacobian.
                # (second order seems to be enough)
                xx = np.zeros((5, 3))
                xx[0, :] = np.array([point[0], point[1], self.params.Oz])
                xx[1, :] = np.array([point[0]-dl, point[1], self.params.Oz])
                xx[2, :] = np.array([point[0]+dl, point[1], self.params.Oz])
                xx[3, :] = np.array([point[0], point[1]-dl, self.params.Oz])
                xx[4, :] = np.array([point[0], point[1]+dl, self.params.Oz])
                for it1 in range(5):
                    stream = Stream(field, self.params, h_min=self.params.h_min,
                                    h_max=self.params.h_max, len_max=self.params.len_max,
                                    tol=self.params.tol, interpolation=self.params.interpolation,
                                    integration=self.params.integration, xx=xx[it1, :])
                    tracers_null[it1, :2] = xx[it1, :2]
                    tracers_null[it1, 2:] = stream.tracers[stream.stream_len-1, 0:2]

                # Check function convergence.
                ff = np.zeros(2)
                ff[0] = tracers_null[0, 2] - tracers_null[0, 0]
                ff[1] = tracers_null[0, 3] - tracers_null[0, 1]
                if sum(abs(ff)) <= 1e-3*np.min(self.params.dx, self.params.dy):
                    fixed_point = np.array([point[0], point[1]])
                    break

                # Compute the Jacobian.
                fjac = np.zeros((2, 2))
                fjac[0, 0] = ((tracers_null[2, 2] - tracers_null[2, 0]) -
                              (tracers_null[1, 2] - tracers_null[1, 0]))/2./dl
                fjac[0, 1] = ((tracers_null[4, 2] - tracers_null[4, 0]) -
                              (tracers_null[3, 2] - tracers_null[3, 0]))/2./dl
                fjac[1, 0] = ((tracers_null[2, 3] - tracers_null[2, 1]) -
                              (tracers_null[1, 3] - tracers_null[1, 1]))/2./dl
                fjac[1, 1] = ((tracers_null[4, 3] - tracers_null[4, 1]) -
                              (tracers_null[3, 3] - tracers_null[3, 1]))/2./dl

                # Invert the Jacobian.
                fjin = np.zeros((2, 2))
                det = fjac[0, 0]*fjac[1, 1] - fjac[0, 1]*fjac[1, 0]
                if abs(det) < dl:
                    fixed_point = point
                    break
                fjin[0, 0] = fjac[1, 1]
                fjin[1, 1] = fjac[0, 0]
                fjin[0, 1] = -fjac[0, 1]
                fjin[1, 0] = -fjac[1, 0]
                fjin = fjin/det
                dpoint = np.zeros(2)
                dpoint[0] = -fjin[0, 0]*ff[0] - fjin[0, 1]*ff[1]
                dpoint[1] = -fjin[1, 0]*ff[0] - fjin[1, 1]*ff[1]
                point += dpoint

                # Check root convergence.
                if sum(abs(dpoint)) < 1e-3*np.min(self.params.dx, self.params.dy):
                    fixed_point = point
                    break

                if it > 20:
                    fixed_point = point
                    print "warning: Newton did not converged"
                    break

                it += 1

            return fixed_point


        # Find the fixed point using Newton's method, starting at previous fixed point.
        def __sub_fixed_series(queue, t_idx, field, var, i_proc):
            fixed = []
            fixed_sign = []
            for i, point in enumerate(self.fixed_points[t_idx-1][i_proc::self.params.n_proc]):
                fixed_tentative = __null_point(point, var)
                # Check if the fixed point lies outside the domain.
                if fixed_tentative[0] >= self.params.Ox and \
                fixed_tentative[1] >= self.params.Oy and \
                fixed_tentative[0] <= self.params.Ox+self.params.Lx and \
                fixed_tentative[1] <= self.params.Oy+self.params.Ly:
                    fixed.append(fixed_tentative)
                    fixed_sign.append(self.fixed_sign[t_idx-1][i_proc+i*n_proc])
            queue.put((i_proc, fixed, fixed_sign))


        # Discard fixed points which are too close to each other.
        def __discard_close_fixed_points(fixed, fixed_sign, var):
            fixed_new = []
            fixed_new.append(fixed[0])
            fixed_sign_new = []
            fixed_sign_new.append(fixed_sign[0])

            dx = fixed[:, 0] - np.reshape(fixed[:, 0], (fixed.shape[0], 1))
            dy = fixed[:, 1] - np.reshape(fixed[:, 1], (fixed.shape[0], 1))
            mask = (abs(dx) > var.dx/2) + (abs(dy) > var.dy/2)

            for idx in range(1, fixed.shape[0]):
                if all(mask[idx, :idx]):
                    fixed_new.append(fixed[idx])
                    fixed_sign_new.append(fixed_sign[idx])

            return np.array(fixed_new), np.array(fixed_sign_new)


        # Convert int_q string into list.
        if not isinstance(int_q, list):
            int_q = [int_q]
        self.params.int_q = int_q
        if any(np.array(self.params.int_q) == 'curly_A'):
            self.curly_A = []
        if any(np.array(self.params.int_q) == 'ee'):
            self.ee = []

        # Multi core setup.
        if not(np.isscalar(n_proc)) or (n_proc%1 != 0):
            print "error: invalid processor number"
            return -1
        queue = mp.Queue()

        # Write the tracing parameters.
        self.params = TracersParameterClass()
        self.params.trace_field = trace_field
        self.params.h_min = h_min
        self.params.h_max = h_max
        self.params.len_max = len_max
        self.params.tol = tol
        self.params.interpolation = interpolation
        self.params.trace_sub = trace_sub
        self.params.int_q = int_q
        self.params.varfile = varfile
        self.params.ti = ti
        self.params.tf = tf
        self.params.integration = integration
        self.params.data_dir = data_dir
        self.params.destination = destination
        self.params.n_proc = n_proc

        # Multi core setup.
        if not(np.isscalar(n_proc)) or (n_proc%1 != 0):
            print "error: invalid processor number"
            return -1

        # Make sure to read the var files with the correct magic.
        magic = []
        if trace_field == 'bb':
            magic.append('bb')
        if trace_field == 'jj':
            magic.append('jj')
        if trace_field == 'vort':
            magic.append('vort')
        if any(np.array(int_q) == 'ee'):
            magic.append('bb')
            magic.append('jj')
        dim = pc.read_dim(datadir=data_dir)

        # Check if user wants a tracer time series.
        if (ti%1 == 0) and (tf%1 == 0) and (ti >= 0) and (tf >= ti):
            series = True
            varfile = 'VAR' + str(ti)
            n_times = tf-ti+1
        else:
            series = False
            n_times = 1
        self.t = np.zeros(n_times)

        # Read the initial field.
        var = pc.read_var(varfile=varfile, datadir=data_dir, magic=magic,
                          quiet=True, trimall=True)
        self.t[0] = var.t
        grid = pc.read_grid(datadir=data_dir, quiet=True, trim=True)
        field = getattr(var, trace_field)
        param2 = pc.read_param(datadir=data_dir, param2=True, quiet=True)
        if any(np.array(int_q) == 'ee'):
            ee = var.jj*param2.eta - pc.cross(var.uu, var.bb)

        # Get the simulation parameters.
        self.params.dx = var.dx
        self.params.dy = var.dy
        self.params.dz = var.dz
        self.params.Ox = var.x[0]
        self.params.Oy = var.y[0]
        self.params.Oz = var.z[0]
        self.params.Lx = grid.Lx
        self.params.Ly = grid.Ly
        self.params.Lz = grid.Lz
        self.params.nx = dim.nx
        self.params.ny = dim.ny
        self.params.nz = dim.nz

        # Create the initial mapping.
        tracers = Tracers()
        tracers.find_tracers(trace_field='bb', h_min=h_min, h_max=h_max,
                             len_max=len_max, tol=tol,
                             interpolation=interpolation,
                             trace_sub=trace_sub, varfile=varfile,
                             integration=integration, data_dir=data_dir,
                             int_q=int_q, n_proc=n_proc)
        self.tracers = tracers

        # Set some default values.
        self.t = np.zeros((tf-ti+1)*series + (1-series))
        self.fidx = np.zeros((tf-ti+1)*series + (1-series))
        self.poincare = np.zeros([int(trace_sub*dim.nx),
                                  int(trace_sub*dim.ny)])
        ix0 = range(0, int(self.params.nx*trace_sub)-1)
        iy0 = range(0, int(self.params.ny*trace_sub)-1)

        # Start the parallelized fixed point finding for the initial time.
        proc = []
        sub_data = []
        fixed = []
        fixed_sign = []
        for i_proc in range(n_proc):
            proc.append(mp.Process(target=__sub_fixed_init,
                                   args=(queue, ix0, iy0, field, tracers, var,
                                         i_proc)))
        for i_proc in range(n_proc):
            proc[i_proc].start()
        for i_proc in range(n_proc):
            sub_data.append(queue.get())
        for i_proc in range(n_proc):
            proc[i_proc].join()
        for i_proc in range(n_proc):
            # Extract the data from the single cores. Mind the order.
            sub_proc = sub_data[i_proc][0]
            fixed.extend(sub_data[i_proc][1])
            fixed_sign.extend(sub_data[i_proc][2])
            self.fidx[0] += sub_data[i_proc][3]
            self.poincare[sub_proc::n_proc, :] = sub_data[i_proc][4]
        for i_proc in range(n_proc):
            proc[i_proc].terminate()

        # Discard fixed points which lie too close to each other.
        fixed, fixed_sign = __discard_close_fixed_points(np.array(fixed),
                                                         np.array(fixed_sign),
                                                         var)
        self.fixed_points.append(np.array(fixed))
        self.fixed_sign.append(np.array(fixed_sign))

        # Find the fixed points for the remaining times.
        for t_idx in range(1, n_times):
            # Read the data.
            varfile = 'VAR' + str(t_idx+ti)
            var = pc.read_var(varfile=varfile, datadir=data_dir, magic=magic,
                              quiet=True, trimall=True)
            field = getattr(var, trace_field)
            self.t[t_idx] = var.t

            # Find the new fixed points.
            proc = []
            sub_data = []
            fixed = []
            fixed_sign = []
            for i_proc in range(n_proc):
                proc.append(mp.Process(target=__sub_fixed_series,
                                       args=(queue, t_idx, field, var, i_proc)))
            for i_proc in range(n_proc):
                proc[i_proc].start()
            for i_proc in range(n_proc):
                sub_data.append(queue.get())
            for i_proc in range(n_proc):
                proc[i_proc].join()
            for i_proc in range(n_proc):
                # Extract the data from the single cores. Mind the order.
                sub_proc = sub_data[i_proc][0]
                fixed.extend(sub_data[i_proc][1])
                fixed_sign.extend(sub_data[i_proc][2])
            for i_proc in range(n_proc):
                proc[i_proc].terminate()

            # Discard fixed points which lie too close to each other.
            fixed, fixed_sign = __discard_close_fixed_points(np.array(fixed),
                                                             np.array(fixed_sign),
                                                             var)
            self.fixed_points.append(np.array(fixed))
            self.fixed_sign.append(np.array(fixed_sign))
            self.fidx[t_idx] = np.sum(fixed_sign)

        # Compute the traced quantities.
        if any(np.array(self.params.int_q) == 'curly_A') or \
        any(np.array(self.params.int_q) == 'ee'):
            for t_idx in range(0, n_times):
                if any(np.array(self.params.int_q) == 'curly_A'):
                    self.curly_A.append([])
                if any(np.array(self.params.int_q) == 'ee'):
                    self.ee.append([])
                for fixed in self.fixed_points[t_idx]:
                    # Trace the stream line.
                    xx = np.array([fixed[0], fixed[1], self.params.Oz])
                    stream = Stream(field, self.params,
                                    h_min=self.params.h_min,
                                    h_max=self.params.h_max,
                                    len_max=self.params.len_max,
                                    tol=self.params.tol,
                                    interpolation=self.params.interpolation,
                                    integration=self.params.integration,
                                    xx=xx)
                    # Do the field line integration.
                    if any(np.array(self.params.int_q) == 'curly_A'):
                        curly_A = 0
                        for l in range(stream.stream_len-1):
                            aaInt = vec_int((stream.tracers[l+1] + stream.tracers[l])/2,
                                             var, var.aa, interpolation=self.params.interpolation)
                            curly_A += np.dot(aaInt, (stream.tracers[l+1] - stream.tracers[l]))
                        self.curly_A[-1].append(curly_A)
                    if any(np.array(self.params.int_q) == 'ee'):
                        ee_p = 0
                        for l in range(stream.stream_len-1):
                            eeInt = vec_int((stream.tracers[l+1] + stream.tracers[l])/2,
                                             var, ee, interpolation=self.params.interpolation)
                            ee_p += np.dot(eeInt, (stream.tracers[l+1] - stream.tracers[l]))
                        self.ee[-1].append(ee_p)
                if any(np.array(self.params.int_q) == 'curly_A'):
                    self.curly_A[-1] = np.array(self.curly_A[-1])
                if any(np.array(self.params.int_q) == 'ee'):
                    self.ee[-1] = np.array(self.ee[-1])
Пример #20
0
def slices2vtk(variables=['rho'],
               extensions=['xy', 'xy2', 'xz', 'yz'],
               datadir='data/',
               destination='slices',
               proc=-1,
               format='native'):
    """
    Convert slices from PencilCode format to vtk.

    call signature::
    
      slices2vtk(variables = ['rho'], extensions = ['xy', 'xy2', 'xz', 'yz'],
           datadir = 'data/', destination = 'slices', proc = -1,
           format = 'native'):
    
    Read slice files specified by *variables* and convert
    them into vtk format for the specified extensions.
    Write the result in *destination*.
    NB: You need to have called src/read_videofiles.x before using this script.
    
    Keyword arguments:
    
      *variables*:
        All allowed fields which can be written as slice files, e.g. b2, uu1, lnrho, ...
        See the pencil code manual for more (chapter: "List of parameters for `video.in'").
        
      *extensions*:
        List of slice positions.
      
      *datadir*:
        Directory where the data is stored.
       
      *destination*:
        Destination files.
        
      *proc*:
        Processor which should be read. Set to -1 for all processors.
      
      *format*:
        Endian, one of little, big, or native (default)
       
    """

    # this should correct for the case the user types only one variable
    if (len(variables) > 0):
        if (len(variables[0]) == 1):
            variables = [variables]
    # this should correct for the case the user types only one extension
    if (len(extensions) > 0):
        if (len(extensions[0]) == 1):
            extensions = [extensions]

    # read the grid dimensions
    grid = pc.read_grid(datadir=datadir, proc=proc, trim=True, quiet=True)

    # read the user given parameters for the slice positions
    params = pc.read_param(param2=True, quiet=True)

    # run through all specified variables
    for field in variables:
        # run through all specified extensions
        for ext in extensions:
            print("read " + field + ' ' + ext)
            slices, t = pc.read_slices(field=field,
                                       datadir=datadir,
                                       proc=proc,
                                       extension=ext,
                                       format=format)

            dim_p = slices.shape[2]
            dim_q = slices.shape[1]
            if ext[0] == 'x':
                d_p = (np.max(grid.x) - np.min(grid.x)) / (dim_p)
            else:
                d_p = (np.max(grid.y) - np.min(grid.y)) / (dim_p)
            if ext[1] == 'y':
                d_q = (np.max(grid.y) - np.min(grid.y)) / (dim_q)
            else:
                d_q = (np.max(grid.z) - np.min(grid.z)) / (dim_q)

            if params.ix != -1:
                x0 = grid.x[params.ix]
            elif params.slice_position == 'm':
                x0 = grid.x[int(len(grid.x) / 2)]
            if params.iy != -1:
                y0 = grid.y[params.iy]
            elif params.slice_position == 'm':
                y0 = grid.y[int(len(grid.y) / 2)]
            if params.iz != -1:
                z0 = grid.z[params.iz]
            elif params.slice_position == 'm':
                z0 = grid.z[int(len(grid.z) / 2)]

            for i in range(slices.shape[0]):
                # open the destination file for writing
                fd = open(
                    destination + '_' + field + '_' + ext + '_' + str(i) +
                    '.vtk', 'wb')

                # write the header
                fd.write('# vtk DataFile Version 2.0\n')
                fd.write(field + '_' + ext + '\n')
                fd.write('BINARY\n')
                fd.write('DATASET STRUCTURED_POINTS\n')
                if ext[0:2] == 'xy':
                    x0 = grid.x[0]
                    y0 = grid.y[0]
                    fd.write('DIMENSIONS {0:9} {1:9} {2:9}\n'.format(
                        dim_p, dim_q, 1))
                    fd.write('ORIGIN {0:8.12} {1:8.12} {2:8.12}\n'.format(
                        x0, y0, z0))
                    fd.write('SPACING {0:8.12} {1:8.12} {2:8.12}\n'.format(
                        grid.dx, grid.dy, 1.))
                elif ext[0:2] == 'xz':
                    x0 = grid.x[0]
                    z0 = grid.z[0]
                    fd.write('DIMENSIONS {0:9} {1:9} {2:9}\n'.format(
                        dim_p, 1, dim_q))
                    fd.write('ORIGIN {0:8.12} {1:8.12} {2:8.12}\n'.format(
                        x0, y0, z0))
                    fd.write('SPACING {0:8.12} {1:8.12} {2:8.12}\n'.format(
                        grid.dx, 1., grid.dy))
                elif ext[0:2] == 'yz':
                    y0 = grid.y[0]
                    z0 = grid.z[0]
                    fd.write('DIMENSIONS {0:9} {1:9} {2:9}\n'.format(
                        1, dim_p, dim_q))
                    fd.write('ORIGIN {0:8.12} {1:8.12} {2:8.12}\n'.format(
                        x0, y0, z0))
                    fd.write('SPACING {0:8.12} {1:8.12} {2:8.12}\n'.format(
                        1., grid.dy, grid.dy))
                fd.write('POINT_DATA {0:9}\n'.format(dim_p * dim_q))

                fd.write('SCALARS ' + field + '_' + ext + ' float\n')
                fd.write('LOOKUP_TABLE default\n')
                for j in range(dim_q):
                    for k in range(dim_p):
                        fd.write(struct.pack(">f", slices[i, j, k]))

                fd.close()
Пример #21
0
import pencil as pc
import numpy as np

varfile = 'var.dat'  # or specific snaphot as required 'VAR?'
var = pc.read_var(varfile, magic=['tt'], trimall=True, quiet=True)
param = pc.read_param(quiet=True)

filename = 'init_ism.in'
f = open(filename, 'w')
#smooth and ensure symmetric about midplane - assumes centred
#convert to cgs - so units can be applied independently
rho = (var.rho[:, 0, 0] + var.rho[::-1, 0, 0]) / 2 * param.unit_density
tt = (var.tt[:, 0, 0] + var.tt[::-1, 0, 0]) / 2 * param.unit_temperature
#f.write('#--rho-------------------TT-------------\n')
for i in range(0, var.rho[:, 0, 0].size):
    f.write(str(rho[i]) + '    ' + str(tt[i]) + '\n')
f.closed
Пример #22
0
imod = len(models)
os.chdir('data')
figsdir = os.getcwd() 
figsdir = re.sub('\/data\/*$','',figsdir) + '/video_slices/' # name for dir saving figures
if not os.path.exists(figsdir):
    os.makedirs(figsdir)
os.chdir(datatopdir) 
sn=pc.read_sn()
sedov_time=sn.t_sedov
f=open('data/tsnap.dat','r')
nvar= int(str.rsplit(f.readline())[1])
#nvar= 12
print nvar
var=pc.read_var(ivar=nvar-1,quiet=True,proc=0) 
endt = var.t
param=pc.read_param(quiet=True)
tokms = param.unit_velocity/1e5

dim=pc.read_dim()
dims=3
if dim.nxgrid==1:
    dims -= 1
if dim.nygrid==1:
    dims -= 1
if dim.nzgrid==1:
    dims -= 1
print 'dims ', dims

hf = h5py.File(datatopdir+'/data/'+models[imod]+'_sedov.h5', 'w')
get_profiles(nt, endt, sn, hf)
lvar=True
Пример #23
0
def pc2vtk(varfile = 'var.dat', datadir = 'data/', proc = -1,
           variables = ['rho','uu','bb'], magic = [], b_ext = False,
           destination = 'work', quiet = True):
    """
    Convert data from PencilCode format to vtk.

    call signature::
    
      pc2vtk(varfile = 'var.dat', datadir = 'data/', proc = -1,
           variables = ['rho','uu','bb'], magic = [],
           destination = 'work.vtk')
    
    Read *varfile* and convert its content into vtk format. Write the result
    in *destination*.
    
    Keyword arguments:
    
      *varfile*:
        The original varfile.
        
      *datadir*:
        Directory where the data is stored.
       
      *proc*:
        Processor which should be read. Set to -1 for all processors.
      
      *variables* = [ 'rho' , 'lnrho' , 'uu' , 'bb', 'b_mag', 'jj', 'j_mag', 'aa', 'ab', 'TT', 'lnTT', 'cc', 'lncc', 'ss', 'vort' ]
        Variables which should be written.
        
      *magic*: [ 'vort' , 'bb' ]
        Additional variables which should be written.
       
      *b_ext*:
        Add the external magnetic field.
        
      *destination*:
        Destination file.
        
      *quiet*:
        Keep quiet when reading the var files.
    """

    # this should correct for the case the user type only one variable
    if (len(magic) > 0):
        if (len(magic[0]) == 1):
            magic = [magic]

    # make sure magic is set when writing 'vort' or 'bb'
    try:
        index = variables.index('vort')
        magic.append('vort')
    except:
        pass      
    try:
        index = variables.index('bb')
        magic.append('bb')
    except:
        pass
    try:
        index = variables.index('b_mag')
        magic.append('bb')
    except:
        pass
    try:
        index = variables.index('jj')
        magic.append('jj')
    except:
        pass
    try:
        index = variables.index('j_mag')
        magic.append('jj')
    except:
        pass

    # reading pc variables and setting dimensions
    var = pc.read_var(varfile = varfile, datadir = datadir, proc = proc,
                    magic = magic, trimall = True, quiet = quiet)
                    
    grid = pc.read_grid(datadir = datadir, proc = proc, trim = True, quiet = True)
    
    params = pc.read_param(param2 = True, quiet = True)
    B_ext = np.array(params.b_ext)    
    # add external magnetic field
    if (b_ext == True):
        var.bb[0,...] += B_ext[0]
        var.bb[1,...] += B_ext[1]
        var.bb[2,...] += B_ext[2]
       
    dimx = len(grid.x)
    dimy = len(grid.y)
    dimz = len(grid.z)
    dim = dimx * dimy * dimz
    dx = (np.max(grid.x) - np.min(grid.x))/(dimx-1)
    dy = (np.max(grid.y) - np.min(grid.y))/(dimy-1)
    dz = (np.max(grid.z) - np.min(grid.z))/(dimz-1)
    
    fd = open(destination + '.vtk', 'wb')
    fd.write('# vtk DataFile Version 2.0\n'.encode('utf-8'))
    fd.write('VAR files\n'.encode('utf-8'))
    fd.write('BINARY\n'.encode('utf-8'))
    fd.write('DATASET STRUCTURED_POINTS\n'.encode('utf-8'))
    fd.write('DIMENSIONS {0:9} {1:9} {2:9}\n'.format(dimx, dimy, dimz).encode('utf-8'))
    fd.write('ORIGIN {0:8.12} {1:8.12} {2:8.12}\n'.format(grid.x[0], grid.y[0], grid.z[0]).encode('utf-8'))
    fd.write('SPACING {0:8.12} {1:8.12} {2:8.12}\n'.format(dx, dy, dz).encode('utf-8'))
    fd.write('POINT_DATA {0:9}\n'.format(dim).encode('utf-8'))
    
    # this should correct for the case the user type only one variable
    if (len(variables) > 0):
        if (len(variables[0]) == 1):
            variables = [variables]
      
    try:
        index = variables.index('rho')
        print('writing rho')
        fd.write('SCALARS rho float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.rho[k,j,i]))
    except:
        pass
    
    try:
        index = variables.index('lnrho')
        print('writing lnrho')
        fd.write('SCALARS lnrho float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.lnrho[k,j,i]))
    except:
        pass
                
    try:
        index = variables.index('uu')
        print('writing uu')
        fd.write('VECTORS vfield float\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.uu[0,k,j,i]))
                    fd.write(struct.pack(">f", var.uu[1,k,j,i]))
                    fd.write(struct.pack(">f", var.uu[2,k,j,i]))
    except:
        pass
    
    try:
        index = variables.index('bb')
        print('writing bb')
        fd.write('VECTORS bfield float\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.bb[0,k,j,i]))
                    fd.write(struct.pack(">f", var.bb[1,k,j,i]))
                    fd.write(struct.pack(">f", var.bb[2,k,j,i]))
    except:
        pass
    
    try:
        index = variables.index('b_mag')
        b_mag = np.sqrt(pc.dot2(var.bb))
        print('writing b_mag')
        fd.write('SCALARS b_mag float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", b_mag[k,j,i]))
    except:
        pass
    
    try:
        index = variables.index('jj')
        print('writing jj')
        fd.write('VECTORS jfield float\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.jj[0,k,j,i]))
                    fd.write(struct.pack(">f", var.jj[1,k,j,i]))
                    fd.write(struct.pack(">f", var.jj[2,k,j,i]))
    except:
        pass
        
    try:
        index = variables.index('j_mag')
        j_mag = np.sqrt(pc.dot2(var.jj))
        print('writing j_mag')
        fd.write('SCALARS j_mag float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", j_mag[k,j,i]))
    except:
        pass
    
    try:
        index = variables.index('aa')
        print('writing aa')
        fd.write('VECTORS afield float\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.aa[0,k,j,i]))
                    fd.write(struct.pack(">f", var.aa[1,k,j,i]))
                    fd.write(struct.pack(">f", var.aa[2,k,j,i]))
    except:
        pass
    
    try:
        index = variables.index('ab')
        ab = pc.dot(var.aa, var.bb)
        print('writing ab')
        fd.write('SCALARS ab float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", ab[k,j,i]))
    except:
        pass
    
    try:
        index = variables.index('TT')
        print('writing TT')
        fd.write('SCALARS TT float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.TT[k,j,i]))
    except:
        pass

    try:
        index = variables.index('lnTT')
        print('writing lnTT')
        fd.write('SCALARS lnTT float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.lnTT[k,j,i]))
    except:
        pass
                    
    try:
        index = variables.index('cc')
        print('writing cc')
        fd.write('SCALARS cc float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.cc[k,j,i]))
    except:
        pass

    try:
        index = variables.index('lncc')
        print('writing lncc')
        fd.write('SCALARS lncc float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.lncc[k,j,i]))                    
    except:
        pass
    
    try:
        index = variables.index('ss')
        print('writing ss')
        fd.write('SCALARS ss float\n'.encode('utf-8'))
        fd.write('LOOKUP_TABLE default\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.ss[k,j,i]))                    
    except:
        pass
      
    try:
        index = variables.index('vort')
        print('writing vort')
        fd.write('VECTORS vorticity float\n'.encode('utf-8'))
        for k in range(dimz):
            for j in range(dimy):
                for i in range(dimx):
                    fd.write(struct.pack(">f", var.vort[0,k,j,i]))
                    fd.write(struct.pack(">f", var.vort[1,k,j,i]))
                    fd.write(struct.pack(">f", var.vort[2,k,j,i]))
    except:
        pass

    del(var)
    
    fd.close()
Пример #24
0
def tracer_movie(datadir = 'data/', tracerFile = 'tracers.dat',
                 fixedFile = 'fixed_points.dat', zlim = [],
                 head_size = 3, hm = 1,
                 imageDir = './', movieFile = 'fixed_points.mpg',
                 fps = 5.0, bitrate = 1800):
    """
    Plots the color mapping together with the fixed points.
    Creates a movie file.

    call signature::

      tracer_movie(datadir = 'data/', tracerFile = 'tracers.dat',
                 fixedFile = 'fixed_points.dat', zlim = [],
                 head_size = 3, hm = 1,
                 imageDir = './', movieFile = 'fixed_points.mpg',
                 fps = 5.0, bitrate = 1800)

    Plots the field line mapping together with the fixed points and creates
    a movie file.

      *datadir*:
        Data directory.

      *tracerFile*:
        Name of the tracer file.

      *fixedFile*:
        Name of the fixed points file.

      *zlim*:
        The upper limit for the field line mapping at which a field line is considered
        to have reached the upper boundary.

      *head_size*:
        Size of the fortran header in binary data. Most of the time this is 3.
        For the St Andrews cluster it is 5.

      *hm*:
        Header multiplication factor in case Fortran's binary data writes extra large
        header. For most cases hm = 1 is sufficient. For the cluster in St Andrews use hm = 2.

      *imageDir*:
        Directory with the temporary png files.

      *movieFile*:
        Output file for the movie. Ending should be 'mpg', since the compression
        format is mpg.

      *fps*:
        Frames per second of the animation.

      *bitrate*:
        Bitrate of the movie file. Set to higher value for higher quality.
    """
    
    import pylab as plt

    # read the mapping and the fixed point positions
    tracers, mapping, t = pc.read_tracers(datadir = datadir, fileName = tracerFile, zlim = zlim, head_size = head_size)
    fixed = pc.read_fixed_points(datadir = datadir, fileName = fixedFile, hm = hm)

    # read the parameters for the domain boundaries
    params = pc.read_param(quiet = True)
    domain = [params.xyz0[0], params.xyz1[0], params.xyz0[1], params.xyz1[1]]

    # determine the how much faster the fixed pints have been written out than the color mapping
    advance = np.ceil(float(len(fixed.t))/len(mapping[0,0,:,0]))

    # determine the colors for the fixed points
    colors = np.zeros(np.shape(fixed.q) + (3,))
    colors[:,:,:] = 0.
    print(np.shape(colors))
    for j in range(len(colors[:,0,0])):
        for k in range(len(colors[0,:,0])):
            if fixed.q[j,k] >= 0:
                colors[j,k,1] = colors[j,k,2] = (1-fixed.q[j,k]/np.max(np.abs(fixed.q[:,k])))
                colors[j,k,0] = fixed.q[j,k]/np.max(np.abs(fixed.q[:,k]))
            else:
                colors[j,k,0] = colors[j,k,1] = (1+fixed.q[j,k]/np.max(np.abs(fixed.q[:,k])))
                colors[j,k,2] = -fixed.q[j,k]/np.max(np.abs(fixed.q[:,k]))

    # prepare the plot
    width = 6
    height = 6
    plt.rc("figure.subplot", left=(60/72.27)/width)
    plt.rc("figure.subplot", right=(width-20/72.27)/width)
    plt.rc("figure.subplot", bottom=(50/72.27)/height)
    plt.rc("figure.subplot", top=(height-20/72.27)/height)
    figure = plt.figure(figsize=(width, height))

    for k in range(len(fixed.x[0,:])):
        dots = plt.plot(fixed.x[0,k], fixed.y[0,k], 'o', c = colors[0,k,:])
    image = plt.imshow(zip(*mapping[:,::-1,0,:]), interpolation = 'nearest', extent = domain)
    j = 0
    frameName = imageDir + 'images%06d.png'%j
    imageFiles = []
    imageFiles.append(frameName)
    figure.savefig(frameName)

    for j in range(1,len(fixed.t)):
        #time.sleep(0.5)
        figure.clear()
        for k in range(len(fixed.x[j,:])):
            dots = plt.plot(fixed.x[j,k], fixed.y[j,k], 'o', c = colors[j,k,:])
        image = plt.imshow(zip(*mapping[:,::-1,np.floor(j/advance),:]), interpolation = 'nearest', extent = domain)
        frameName = imageDir + 'images%06d.png'%j
        imageFiles.append(frameName)
        figure.savefig(frameName)

    # convert the images into a mpg file
    mencodeCommand = "mencoder 'mf://"+imageDir+"images*.png' -mf type=png:fps="+np.str(fps)+" -ovc lavc -lavcopts vcodec=mpeg4:vhq:vbitrate="+np.str(bitrate)+" -ffourcc MP4S -oac copy -o "+movieFile
    os.system(mencodeCommand)

    # remove the image files
    for fname in imageFiles:
        os.remove(fname)
Пример #25
0
import pencil as pc
import numpy as np
import math
from astropy.constants import au
#
datadir = '../data'
unit_length = au.to('cm').value
par = pc.read_param(datadir=datadir)
#
# According to the RADMC3D manual, the way the variable coordsystem works is
#
# If coordsystem<100 the coordinate system is cartesian.
# If 100<=coordsystem<200 thecoordinate system is spherical (polar).
# If 200<=coordsystem<300 the coordinate system is cylindrical.
#
xdim = unit_length
print par.coord_system
if (par.coord_system == 'cartesian'):
    coordsystem = 99
    ydim = unit_length
    zdim = unit_length
elif (par.coord_system == 'cylindric'):
    coordsystem = 200
    ydim = 1.
    zdim = unit_length
elif (par.coord_system == 'spherical'):
    coordsystem = 100
    ydim = 1.
    zdim = 1.
else:
    print "the world is flat and we never got here"
import pencil
import numpy
from matplotlib import pyplot
from matplotlib import cm
import sys
import os

#simulation_name = 
#script_name     = os.path.basename(__file__)

data        = pencil.read_var(trimall=True)
pdata       = pencil.read_pvar()
time_series = pencil.read_ts()
parameters  = pencil.read_param()

npar   = len(pdata.ipars)
xgrid  = data.x
ygrid  = data.y
zgrid  = data.z
dxgrid = data.dx
dygrid = data.dy
dzgrid = data.dz
x0 = xgrid[0]
y0 = ygrid[0]
z0 = zgrid[0]
x1 = xgrid[-1]
y1 = ygrid[-1]
z1 = zgrid[-1]
last_snap = numpy.floor(time_series.t[-1]/parameters.tausp) + 1

ivar_lower = 0
Пример #27
0
    dirs = sorted(dirs, key=lambda a: float(a.split('_')[-1]), reverse=True)
except ValueError:
    pass
#dirs =sorted( [s for s in listdir('.') if (isdir(s) and s.startswith(dstart) and not isfile(join(s,'.noscale')))],
             #key=lambda s: float(s.split('_')[-1]))
if args.helical:
    dirs.append('helical')
dstart=dirs[0]
if args.verbose:
    print(dirs)
clrindx = iter(np.linspace(0,1,len(dirs)))

dim = pc.read_dim(datadir=dstart)
krms = np.loadtxt(join(dstart, 'power_krms.dat')).flatten()[:dim.nxgrid//2]
tser0 = pc.read_ts(quiet=not args.verbose, datadir=dstart)
par0 = pc.read_param(datadir=dstart, quiet=True)
kpeak = par0.kpeak_aa
tau0 = (tser0.brms[0]*kpeak)**-1
print('tau = ',tau0)
if args.verbose:
    print('krms shape: ',krms.shape)

if args.light:
    cscheme = plt.cm.Paired
else:
    cscheme = plt.cm.Dark2

# Simple plot
fig, ax  = newfig(0.45, ratio=0.75)
ax.set_xscale('log')
first_dir = True
from matplotlib import cm
from matplotlib import gridspec
import sys
import os

base_path, script_name = os.path.split(sys.argv[0])
scratch, simulation_name = os.path.split(base_path)
script_name = script_name[:-3]

ivar = -1
pvar = "pvar.dat"
if len(sys.argv) > 1:
    ivar = int(sys.argv[1])
    pvar = "PVAR" + sys.argv[1]

parameters = pencil.read_param(quiet=True)
data = pencil.read_var(ivar=ivar, quiet=True)
pdata = pencil.read_pvar(varfile=pvar)

xp = pdata.xp
yp = pdata.yp
zp = pdata.zp
npar = len(pdata.ipars)

x0 = parameters.xyz0[0]
y0 = parameters.xyz0[1]
z0 = parameters.xyz0[2]
x1 = parameters.xyz1[0]
y1 = parameters.xyz1[1]
z1 = parameters.xyz1[2]
Пример #29
0
    def find_tracers(self, trace_field='bb', h_min=2e-3, h_max=2e4, len_max=500,
                     tol=1e-2, iter_max=1e3, interpolation='trilinear',
                     trace_sub=1, int_q=[''], varfile='VAR0', ti=-1, tf=-1,
                     integration='simple', data_dir='./data', n_proc=1):
        """
        Trace streamlines from the VAR files and integrate quantity 'int_q'
        along them.

        call signature::

        find_tracers(self, trace_field='bb', h_min=2e-3, h_max=2e4, len_max=500,
                     tol=1e-2, iter_max=1e3, interpolation='trilinear',
                     trace_sub=1, int_q=[''], varfile='VAR0', ti=-1, tf=-1,
                     integration='simple', data_dir='data/', n_proc=1)

        Trace streamlines of the vectofield 'field' from z = z0 to z = z1
        and integrate quantities 'int_q' along the lines. Creates a 2d
        mapping as in 'streamlines.f90'.

        Keyword arguments:

        *trace_field*:
          Vector field used for the streamline tracing.

        *h_min*:
          Minimum step length for and underflow to occur.

        *h_max*:
          Parameter for the initial step length.

        *len_max*:
          Maximum length of the streamline. Integration will stop if
          len >= len_max.

        *tol*:
          Tolerance for each integration step. Reduces the step length if
          error >= tol.

        *iter_max*:
          Maximum number of iterations.

        *interpolation*:
          Interpolation of the vector field.
          'mean': takes the mean of the adjacent grid point.
          'trilinear': weights the adjacent grid points according to
          their distance.

        *trace_sub*:
          Number of sub-grid cells for the seeds.

        *int_q*:
          Quantities to be integrated along the streamlines.

        *varfile*:
          Varfile to be read.

        *integration*:
          Integration method.
          'simple': low order method.
          'RK6': Runge-Kutta 6th order.

        *ti*:
          Initial VAR file index for tracer time sequences. Overrides
          'varfile'.

        *tf*:
          Final VAR file index for tracer time sequences. Overrides 'varfile'.

        *data_dir*:
          Directory where the data is stored.

        *n_proc*:
          Number of cores for multi core computation.
        """

        # Return the tracers for the specified starting locations.
        def __sub_tracers(queue, var, field, t_idx, i_proc, n_proc):
            xx = np.zeros([(self.x0.shape[0]+n_proc-1-i_proc)/n_proc,
                            self.x0.shape[1], 3])
            xx[:, :, 0] = self.x0[i_proc:self.x0.shape[0]:n_proc, :, t_idx].copy()
            xx[:, :, 1] = self.y0[i_proc:self.x0.shape[0]:n_proc, :, t_idx].copy()
            xx[:, :, 2] = self.z1[i_proc:self.x0.shape[0]:n_proc, :, t_idx].copy()
            # Initialize the local arrays for this core.
            sub_x1 = np.zeros(xx[:, :, 0].shape)
            sub_y1 = np.zeros(xx[:, :, 0].shape)
            sub_z1 = np.zeros(xx[:, :, 0].shape)
            sub_l = np.zeros(xx[:, :, 0].shape)
            sub_curly_A = np.zeros(xx[:, :, 0].shape)
            sub_ee = np.zeros(xx[:, :, 0].shape)
            sub_mapping = np.zeros([xx[:, :, 0].shape[0], xx[:, :, 0].shape[1], 3])
            for ix in range(i_proc, self.x0.shape[0], n_proc):
                for iy in range(self.x0.shape[1]):
                    stream = Stream(field, self.params, interpolation=interpolation,
                                    h_min=h_min, h_max=h_max, len_max=len_max, tol=tol,
                                    iter_max=iter_max, xx=xx[int(ix/n_proc), iy, :])
                    sub_x1[int(ix/n_proc), iy] = stream.tracers[stream.stream_len-1, 0]
                    sub_y1[int(ix/n_proc), iy] = stream.tracers[stream.stream_len-1, 1]
                    sub_z1[int(ix/n_proc), iy] = stream.tracers[stream.stream_len-1, 2]
                    sub_l[int(ix/n_proc), iy] = stream.len
                    if any(np.array(self.params.int_q) == 'curly_A'):
                        for l in range(stream.stream_len-1):
                            aaInt = vec_int((stream.tracers[l+1] + stream.tracers[l])/2,
                                             var, aa, interpolation=self.params.interpolation)
                            sub_curly_A[int(ix/n_proc), iy] += \
                                np.dot(aaInt, (stream.tracers[l+1] - stream.tracers[l]))
                    if any(np.array(self.params.int_q) == 'ee'):
                        for l in range(stream.stream_len-1):
                            eeInt = vec_int((stream.tracers[l+1] + stream.tracers[l])/2,
                                             var, ee, interpolation=self.params.interpolation)
                            sub_ee[int(ix/n_proc), iy] += \
                                np.dot(eeInt, (stream.tracers[l+1] - stream.tracers[l]))

                    # Create the color mapping.
                    if (sub_z1[int(ix/n_proc), iy] > self.params.Oz+self.params.Lz-self.params.dz*4):
                        if (self.x0[ix, iy, t_idx] - sub_x1[int(ix/n_proc), iy]) > 0:
                            if (self.y0[ix, iy, t_idx] - sub_y1[int(ix/n_proc), iy]) > 0:
                                sub_mapping[int(ix/n_proc), iy, :] = [0, 1, 0]
                            else:
                                sub_mapping[int(ix/n_proc), iy, :] = [1, 1, 0]
                        else:
                            if (self.y0[ix, iy, t_idx] - sub_y1[int(ix/n_proc), iy]) > 0:
                                sub_mapping[int(ix/n_proc), iy, :] = [0, 0, 1]
                            else:
                                sub_mapping[int(ix/n_proc), iy, :] = [1, 0, 0]
                    else:
                        sub_mapping[int(ix/n_proc), iy, :] = [1, 1, 1]

            queue.put((i_proc, sub_x1, sub_y1, sub_z1, sub_l, sub_mapping,
                       sub_curly_A, sub_ee))


        # Write the tracing parameters.
        self.params.trace_field = trace_field
        self.params.h_min = h_min
        self.params.h_max = h_max
        self.params.len_max = len_max
        self.params.tol = tol
        self.params.interpolation = interpolation
        self.params.trace_sub = trace_sub
        self.params.int_q = int_q
        self.params.varfile = varfile
        self.params.ti = ti
        self.params.tf = tf
        self.params.integration = integration
        self.params.data_dir = data_dir
        self.params.n_proc = n_proc

        # Multi core setup.
        if not(np.isscalar(n_proc)) or (n_proc%1 != 0):
            print "error: invalid processor number"
            return -1
        queue = mp.Queue()

        # Convert int_q string into list.
        if not isinstance(int_q, list):
            int_q = [int_q]

        # Read the data.
        magic = []
        if trace_field == 'bb':
            magic.append('bb')
        if trace_field == 'jj':
            magic.append('jj')
        if trace_field == 'vort':
            magic.append('vort')
        if any(np.array(int_q) == 'ee'):
            magic.append('bb')
            magic.append('jj')
        dim = pc.read_dim(datadir=data_dir)

        # Check if user wants a tracer time series.
        if (ti%1 == 0) and (tf%1 == 0) and (ti >= 0) and (tf >= ti):
            series = True
            nTimes = tf-ti+1
        else:
            series = False
            nTimes = 1

        # Initialize the arrays.
        self.x0 = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny), nTimes])
        self.y0 = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny), nTimes])
        self.x1 = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny), nTimes])
        self.y1 = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny), nTimes])
        self.z1 = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny), nTimes])
        self.l = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny), nTimes])
        if any(np.array(int_q) == 'curly_A'):
            self.curly_A = np.zeros([int(trace_sub*dim.nx),
                                     int(trace_sub*dim.ny), nTimes])
        if any(np.array(int_q) == 'ee'):
            self.ee = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny),
                                nTimes])
        self.mapping = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny),
                                 nTimes, 3])
        self.t = np.zeros(nTimes)

        for t_idx in range(ti, tf+1):
            if series:
                varfile = 'VAR' + str(t_idx)

            # Read the data.
            var = pc.read_var(varfile=varfile, datadir=data_dir, magic=magic,
                              quiet=True, trimall=True)
            grid = pc.read_grid(datadir=data_dir, quiet=True, trim=True)
            param2 = pc.read_param(datadir=data_dir, param2=True, quiet=True)
            self.t[t_idx] = var.t

            # Extract the requested vector trace_field.
            field = getattr(var, trace_field)
            if any(np.array(int_q) == 'curly_A'):
                aa = var.aa
            if any(np.array(int_q) == 'ee'):
                ee = var.jj*param2.eta - pc.cross(var.uu, var.bb)

            # Get the simulation parameters.
            self.params.dx = var.dx
            self.params.dy = var.dy
            self.params.dz = var.dz
            self.params.Ox = var.x[0]
            self.params.Oy = var.y[0]
            self.params.Oz = var.z[0]
            self.params.Lx = grid.Lx
            self.params.Ly = grid.Ly
            self.params.Lz = grid.Lz
            self.params.nx = dim.nx
            self.params.ny = dim.ny
            self.params.nz = dim.nz

            # Initialize the tracers.
            for ix in range(int(trace_sub*dim.nx)):
                for iy in range(int(trace_sub*dim.ny)):
                    self.x0[ix, iy, t_idx] = grid.x[0] + grid.dx/trace_sub*ix
                    self.x1[ix, iy, t_idx] = self.x0[ix, iy, t_idx].copy()
                    self.y0[ix, iy, t_idx] = grid.y[0] + grid.dy/trace_sub*iy
                    self.y1[ix, iy, t_idx] = self.y0[ix, iy, t_idx].copy()
                    self.z1[ix, iy, t_idx] = grid.z[0]

            proc = []
            sub_data = []
            for i_proc in range(n_proc):
                proc.append(mp.Process(target=__sub_tracers, args=(queue, var, field, t_idx, i_proc, n_proc)))
            for i_proc in range(n_proc):
                proc[i_proc].start()
            for i_proc in range(n_proc):
                sub_data.append(queue.get())
            for i_proc in range(n_proc):
                proc[i_proc].join()
            for i_proc in range(n_proc):
                # Extract the data from the single cores. Mind the order.
                sub_proc = sub_data[i_proc][0]
                self.x1[sub_proc::n_proc, :, t_idx] = sub_data[i_proc][1]
                self.y1[sub_proc::n_proc, :, t_idx] = sub_data[i_proc][2]
                self.z1[sub_proc::n_proc, :, t_idx] = sub_data[i_proc][3]
                self.l[sub_proc::n_proc, :, t_idx] = sub_data[i_proc][4]
                self.mapping[sub_proc::n_proc, :, t_idx, :] = sub_data[i_proc][5]
                if any(np.array(int_q) == 'curly_A'):
                    self.curly_A[sub_proc::n_proc, :, t_idx] = sub_data[i_proc][6]
                if any(np.array(int_q) == 'ee'):
                    self.ee[sub_proc::n_proc, :, t_idx] = sub_data[i_proc][7]
            for i_proc in range(n_proc):
                proc[i_proc].terminate()
Пример #30
0
def pc2vtk_vid(
    ti=0,
    tf=1,
    datadir="data/",
    proc=-1,
    variables=["rho", "uu", "bb"],
    magic=[],
    b_ext=False,
    destination="animation",
    quiet=True,
):
    """
    Convert data from PencilCode format to vtk.

    call signature::
    
      pc2vtk(ti = 0, tf = 1, datadir = 'data/', proc = -1,
           variables = ['rho','uu','bb'], magic = [],
           destination = 'animation')
    
    Read *varfile* and convert its content into vtk format. Write the result
    in *destination*.
    
    Keyword arguments:
    
      *ti*:
        Initial time.
        
      *tf*:
        Final time.
        
      *datadir*:
        Directory where the data is stored.
       
      *proc*:
        Processor which should be read. Set to -1 for all processors.
      
      *variables* = [ 'rho' , 'lnrho' , 'uu' , 'bb', 'b_mag', 'jj', 'j_mag', 'aa', 'ab', 'TT', 'lnTT', 'cc', 'lncc', 'ss', 'vort' ]
        Variables which should be written.
        
      *magic*: [ 'vort' , 'bb' ]
        Additional variables which should be written.
       
      *b_ext*:
        Add the external magnetic field.
        
      *destination*:
        Destination files without '.vtk' extension. 
        
      *quiet*:
        Keep quiet when reading the var files.
    """

    # this should correct for the case the user type only one variable
    if len(variables) > 0:
        if len(variables[0]) == 1:
            variables = [variables]
    # this should correct for the case the user type only one variable
    if len(magic) > 0:
        if len(magic[0]) == 1:
            magic = [magic]

    # make sure magic is set when writing 'vort' or 'bb'
    try:
        index = variables.index("vort")
        magic.append("vort")
    except:
        pass
    try:
        index = variables.index("bb")
        magic.append("bb")
    except:
        pass
    try:
        index = variables.index("b_mag")
        magic.append("bb")
    except:
        pass
    try:
        index = variables.index("jj")
        magic.append("jj")
    except:
        pass
    try:
        index = variables.index("j_mag")
        magic.append("jj")
    except:
        pass

    for i in range(ti, tf + 1):
        varfile = "VAR" + str(i)
        # reading pc variables and setting dimensions
        var = pc.read_var(varfile=varfile, datadir=datadir, proc=proc, magic=magic, trimall=True, quiet=quiet)

        grid = pc.read_grid(datadir=datadir, proc=proc, trim=True, quiet=True)

        params = pc.read_param(param2=True, quiet=True)
        B_ext = np.array(params.b_ext)
        # add external magnetic field
        if b_ext == True:
            var.bb[0, ...] += B_ext[0]
            var.bb[1, ...] += B_ext[1]
            var.bb[2, ...] += B_ext[2]

        dimx = len(grid.x)
        dimy = len(grid.y)
        dimz = len(grid.z)
        dim = dimx * dimy * dimz
        dx = (np.max(grid.x) - np.min(grid.x)) / (dimx - 1)
        dy = (np.max(grid.y) - np.min(grid.y)) / (dimy - 1)
        dz = (np.max(grid.z) - np.min(grid.z)) / (dimz - 1)

        # fd = open(destination + "{0:1.0f}".format(var.t*1e5) + '.vtk', 'wb')
        fd = open(destination + str(i) + ".vtk", "wb")
        fd.write("# vtk DataFile Version 2.0\n")
        fd.write("density + magnetic field\n")
        fd.write("BINARY\n")
        fd.write("DATASET STRUCTURED_POINTS\n")
        fd.write("DIMENSIONS {0:9} {1:9} {2:9}\n".format(dimx, dimy, dimz))
        fd.write("ORIGIN {0:8.12} {1:8.12} {2:8.12}\n".format(grid.x[0], grid.y[0], grid.z[0]))
        fd.write("SPACING {0:8.12} {1:8.12} {2:8.12}\n".format(dx, dy, dz))
        fd.write("POINT_DATA {0:9}\n".format(dim))

        try:
            index = variables.index("rho")
            print("writing rho")
            fd.write("SCALARS rho float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.rho[k, j, i]))
        except:
            pass

        try:
            index = variables.index("lnrho")
            print("writing lnrho")
            fd.write("SCALARS lnrho float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.lnrho[k, j, i]))
        except:
            pass

        try:
            index = variables.index("uu")
            print("writing uu")
            fd.write("VECTORS vfield float\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.uu[0, k, j, i]))
                        fd.write(struct.pack(">f", var.uu[1, k, j, i]))
                        fd.write(struct.pack(">f", var.uu[2, k, j, i]))
        except:
            pass

        try:
            index = variables.index("bb")
            print("writing bb")
            fd.write("VECTORS bfield float\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.bb[0, k, j, i]))
                        fd.write(struct.pack(">f", var.bb[1, k, j, i]))
                        fd.write(struct.pack(">f", var.bb[2, k, j, i]))
        except:
            pass

        try:
            index = variables.index("b_mag")
            b_mag = np.sqrt(pc.dot2(var.bb))
            print("writing b_mag")
            fd.write("SCALARS b_mag float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", b_mag[k, j, i]))
        except:
            pass

        try:
            index = variables.index("jj")
            print("writing jj")
            fd.write("VECTORS jfield float\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.jj[0, k, j, i]))
                        fd.write(struct.pack(">f", var.jj[1, k, j, i]))
                        fd.write(struct.pack(">f", var.jj[2, k, j, i]))
        except:
            pass

        try:
            index = variables.index("j_mag")
            j_mag = np.sqrt(pc.dot2(var.jj))
            print("writing j_mag")
            fd.write("SCALARS j_mag float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", j_mag[k, j, i]))
        except:
            pass

        try:
            index = variables.index("aa")
            print("writing aa")
            fd.write("VECTORS afield float\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.aa[0, k, j, i]))
                        fd.write(struct.pack(">f", var.aa[1, k, j, i]))
                        fd.write(struct.pack(">f", var.aa[2, k, j, i]))
        except:
            pass

        try:
            index = variables.index("ab")
            ab = pc.dot(var.aa, var.bb)
            print("writing ab")
            fd.write("SCALARS ab float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", ab[k, j, i]))
        except:
            pass

        try:
            index = variables.index("TT")
            print("writing TT")
            fd.write("SCALARS TT float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.TT[k, j, i]))
        except:
            pass

        try:
            index = variables.index("lnTT")
            print("writing lnTT")
            fd.write("SCALARS lnTT float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.lnTT[k, j, i]))
        except:
            pass

        try:
            index = variables.index("cc")
            print("writing cc")
            fd.write("SCALARS cc float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.cc[k, j, i]))
        except:
            pass

        try:
            index = variables.index("lncc")
            print("writing lncc")
            fd.write("SCALARS lncc float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.lncc[k, j, i]))
        except:
            pass

        try:
            index = variables.index("ss")
            print("writing ss")
            fd.write("SCALARS ss float\n")
            fd.write("LOOKUP_TABLE default\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.ss[k, j, i]))
        except:
            pass

        try:
            index = variables.index("vort")
            print("writing vort")
            fd.write("VECTORS vorticity float\n")
            for k in range(dimz):
                for j in range(dimy):
                    for i in range(dimx):
                        fd.write(struct.pack(">f", var.vort[0, k, j, i]))
                        fd.write(struct.pack(">f", var.vort[1, k, j, i]))
                        fd.write(struct.pack(">f", var.vort[2, k, j, i]))
        except:
            pass

        del (var)

        fd.close()
Пример #31
0
    "pgf.preamble": [
        r"\usepackage[utf8x]{inputenc}",    # use utf8 fonts becasue your computer can handle it :)
        r"\usepackage[T1]{fontenc}",        # plots will be generated using this preamble
        ]
    }
mpl.rcParams.update(pgf_with_latex)

import matplotlib.pyplot as plt

fwidth = 0.45
fig, ax = newfig(fwidth)


# calculate the timescales
tser = pc.read_ts(datadir=dirs[-1])
par2 = pc.read_param(quiet=True, datadir=dirs[-1], param2=True)
pars = pc.read_param(quiet=True, datadir=dirs[-1])
vA0 = tser.brms[0]
k0 = pars.kpeak_aa
tau0 = (vA0*k0)**-1
print('tau_0 = ',tau0)

if args.twin:
    twinax = ax.twinx()
    twinax.set_yscale('log')
    yl2 = twinax.get_ylim()
    if args.verbose:
        print(yl2)
    #twinax.set_ylim(1,1e4)
    twinax.set_ylabel(r'$E_{k\leq 7}/E_0$')
Пример #32
0
# ======================================

ts = pc.read_ts()
t = ts.t / 2 / np.pi
N = 50
tmax = t.max()
ux = ts.ux2m
uy = ts.uy2m
rhomax = ts.rhomax
rhomin = ts.rhomin

# ======================================
# pc.read_pararm()
# ======================================

par = pc.read_param()
h = par.cs0
if (par.iprimary == 1):
    q = par.pmass[1]
else:
    q = par.pmass[0]

par1 = par.pmass[1]
par2 = par.pmass[0]
gamma = par.gamma
Gamma0 = (q / h)**2
alpha = par.density_power_law
beta = par.temperature_power_law
kernel = np.ones((N, )) / N
time = np.convolve(t, kernel, mode='valid')
torqint = np.convolve(ts.torqint_2, kernel, mode='valid')
import pencil
import numpy
from matplotlib import pylab
import sys

params = pencil.read_param()
ts = pencil.read_ts()

tau = 0.014
g = 2.45

v_s = -tau * g
v_z_max = ts.vpzmax
v_z_min = ts.vpzmin
#v_z_mean = ts.vpzm
time = ts.t / tau

figure = pylab.figure()
subplot = figure.add_subplot(111)
subplot.plot(time, v_z_max, color="red", label="Maximum z-velocity")
subplot.plot(time, v_z_min, color="green", label="Minimum z-velocity")
#subplot.plot(time,v_z_min,color="black",label="Mean z-velocity")
subplot.plot(time,
             numpy.repeat(v_s, len(time)),
             linestyle="--",
             color="grey",
             label="Isolated terminal velocity")

subplot.set_title("vpzmax vs t")
subplot.set_ylabel("vpz")
subplot.set_xlabel("t (friction times)")