def vort_plot(ivar): ff = pc.read_var(trimall=True, ivar=ivar, magic=["vort"]) vort_z = ff.vort[2, ...] fig, ax = subplots(1, 1) ax.contourf(ff.x, ff.y, mean(vort_z, axis=0), linspace(-1, 1, 256)) ax.set_title('Vorticity') xy_label(ax, 'r', r'$\phi$') show() #84
def Disk(ivar): ff = pc.read_var(trimall=True, ivar=ivar, quiet=True) global x, y, z, rhop, res, ny, nz, epsi r2d, p2d = meshgrid(ff.x, ff.y) # r, phi x, y, z = r2d * cos(p2d), r2d * sin(p2d), ff.z # Coordinates ny, nz = 1024, 32 # Grid resolutions epsi = 1e-4 rhop = ff.rhop lg_rhop_xy = log10(rhop[int(nz / 2), ...] + epsi) # log10 dust density res = linspace(lg_rhop_xy.max() - 3.5, lg_rhop_xy.max(), 256) return lg_rhop_xy
def readField(simdir, varfile): var = pc.read_var(datadir = simdir, varfile = varfile, magic = 'bb', quiet = True, trimall = True) grid = pc.read_grid(datadir = simdir, quiet = True) bb = var.bb p = pClass() p.dx = var.dx; p.dy = var.dy; p.dz = var.dz p.Ox = var.x[0]; p.Oy = var.y[0]; p.Oz = var.z[0] p.Lx = grid.Lx; p.Ly = grid.Ly; p.Lz = grid.Lz p.nx = var.bb.shape[1]; p.ny = var.bb.shape[2]; p.nz = var.bb.shape[3] return bb, p, var.t
def readField(simdir, varfile): var = pc.read_var(datadir=simdir, varfile=varfile, magic='bb', quiet=True, trimall=True) grid = pc.read_grid(datadir=simdir, quiet=True) bb = var.bb p = pClass() p.dx = var.dx p.dy = var.dy p.dz = var.dz p.Ox = var.x[0] p.Oy = var.y[0] p.Oz = var.z[0] p.Lx = grid.Lx p.Ly = grid.Ly p.Lz = grid.Lz p.nx = var.bb.shape[1] p.ny = var.bb.shape[2] p.nz = var.bb.shape[3] return bb, p, var.t
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()
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()
def pc2vtkxml(varfile = 'var.dat', datadir = 'data/', proc = -1, variables = ['rho','uu','bb'], magic = [], destination = 'work', quiet = True): """ Convert data from PencilCode format to XML vtk. Write .vts Structured Grid, not Rectilinear Grid as VisIt screws up reading Rectilinear Grid. However, this is set to write large grids in VTK XML, which is not yet suported by VisIt anyways. Use ParaView. call signature:: pc2xmlvtk(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', 'tt', 'lnTT', 'cc', 'lncc', 'ss', 'vort', 'eth' ] Variables which should be written. *magic*: [ 'vort' , 'bb' ] Additional variables which should be written. *destination*: Destination file. """ # 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('tt') magic.append('tt') except: pass # get endian format of the data format = pc.get_format(datadir = datadir) # reading pc variables and setting dimensions var = pc.read_var(varfile = varfile, datadir = datadir, proc = proc, magic = magic, trimall = True, quiet = quiet, format = format) grid = pc.read_grid(datadir = datadir, proc = proc, trim = True, quiet = True, format = format) dimx = len(grid.x) dimy = len(grid.y) dimz = len(grid.z) dim = dimx * dimy * dimz scalardata = {} if ('rho' in variables) : rho = np.transpose(var.rho.copy()) scalardata['rho'] = rho if ('lnrho' in variables) : lnrho = np.transpose(var.lnrho.copy()) scalardata['lnrho'] = lnrho if ('tt' in variables) : tt = np.transpose(var.tt.copy()) scalardata['tt'] = tt if ('lntt' in variables) : lntt = np.transpose(var.lntt.copy()) scalardata['lntt'] = lntt if ('cc' in variables) : cc = np.transpose(var.cc.copy()) scalardata['cc'] = cc if ('lncc' in variables) : lncc = np.transpose(var.lncc.copy()) scalardata['lncc'] = lncc if ('ss' in variables) : ss = np.transpose(var.ss.copy()) scalardata['ss'] = ss if ('eth' in variables) : eth = np.transpose(var.eth.copy()) scalardata['eth'] = eth vectordata = {} if ('uu' in variables) : uu1 = np.transpose(var.uu[0,:,:,:].copy()) uu2 = np.transpose(var.uu[1,:,:,:].copy()) uu3 = np.transpose(var.uu[2,:,:,:].copy()) vectordata['uu'] = (uu1,uu2,uu3) if ('bb' in variables) : bb1 = np.transpose(var.bb[0,:,:,:].copy()) bb2 = np.transpose(var.bb[1,:,:,:].copy()) bb3 = np.transpose(var.bb[2,:,:,:].copy()) vectordata['bb'] = (bb1,bb2,bb3) if ('jj' in variables) : jj1 = np.transpose(var.jj[0,:,:,:].copy()) jj2 = np.transpose(var.jj[1,:,:,:].copy()) jj3 = np.transpose(var.jj[2,:,:,:].copy()) vectordata['jj'] = (jj1,jj2,jj3) if ('aa' in variables) : aa1 = np.transpose(var.aa[0,:,:,:].copy()) aa2 = np.transpose(var.aa[1,:,:,:].copy()) aa3 = np.transpose(var.aa[2,:,:,:].copy()) vectordata['aa'] = (aa1,aa2,aa3) if ('vort' in variables) : vort1 = np.transpose(var.vort[0,:,:,:].copy()) vort2 = np.transpose(var.vort[1,:,:,:].copy()) vort3 = np.transpose(var.vort[2,:,:,:].copy()) vectordata['vort'] = (vort1,vort2,vort3) X = np.zeros([dimx,dimy,dimz]) Y = np.zeros([dimx,dimy,dimz]) Z = np.zeros([dimx,dimy,dimz]) for k in range(dimz): for j in range(dimy): for i in range(dimx): X[i,j,k] = grid.x[i] Y[i,j,k] = grid.y[j] Z[i,j,k] = grid.z[k] start = (0,0,0) end = (dimx-1, dimy-1, dimz-1) time = np.array([var.t]) w = VtkFile(destination, VtkStructuredGrid,largeFile=True) w.openGrid(start = start, end = end) #this s for wirting Time in VisIt files. However, when usign large grid Visit does not work anyways. #w.openFieldData() #w.addTuple('TIME', time.dtype.name,len(time)) #w.closeFieldData() w.openPiece(start = start, end = end) w.openElement("Points") w.addData("points", (X,Y,Z)) w.closeElement("Points") w.openData("Point", scalars = scalardata.keys(), vectors = vectordata.keys()) for key in scalardata: w.addData(key,scalardata[key]) for key in vectordata: w.addData(key,vectordata[key]) w.closeData("Point") w.closePiece() w.closeGrid() #w.appendData( time ) w.appendData( (X,Y,Z) ) for key in scalardata: w.appendData(data = scalardata[key]) for key in vectordata: w.appendData(data = vectordata[key]) w.save()
t = 0 import pencil as pc # Animate wave as it's advected by the background shear for it in range(nt): # Increment time # Advance radial wave number # New wave profile testarr = sin(kx[iy, ix] * x + ky[iy, ix] * y) # testarr = sin (ky[iy,ix]*y ) # testarr = sin (kx[ix,iy]*x + ky[ix,iy]*y) ivar = it datadir = "data" D = pc.read_var(datadir=datadir, trimall=True, ivar=ivar, magic=["bb"]) sim = D.uu[0, 0, :, :] # I am transposing here since the python script is in y,x not x,y sim = transpose(D.uu[0, 0, :, :]) f = sim fft_test = fft_sheet(testarr, t) fft_sim = fft_sheet(sim, t) fft_test_p = log(abs(roll(roll(fft_test, 64, axis=0), 64, axis=1))) fft_sim_p = log(abs(roll(roll(fft_sim, 64, axis=0), 64, axis=1))) ifft_test = ifft(ifft(fft_test, axis=0), axis=1) ifft_sim = ifft(ifft(fft_sim, axis=0), axis=1) ifft_test_p = real(ifft_test) ifft_sim_p = real(ifft_sim)
import pencil as pc import matplotlib.pyplot as plt import numpy as np from pylab import * import sys ivar = int(input("Orbit:")) ff = pc.read_var(trimall=True, ivar=ivar, magic=["TT"]) ts = pc.read_ts() f0 = pc.read_var(trimall=True, ivar=0, magic=["TT"]) print np.amax(ff.rho), np.amin(ff.rho) print ff.t rad = ff.x theta = ff.y rad2d, theta2d = np.meshgrid(rad, theta) x2d = rad2d * np.cos(theta2d) y2d = rad2d * np.sin(theta2d) radq2 = ts.xq2 thetaq2 = ts.yq2 xrq2 = radq2 * np.cos(thetaq2) yrq2 = radq2 * np.sin(thetaq2) rad = ff.x theta = ff.y rad2d, theta2d = np.meshgrid(rad, theta)
def fixed_points(datadir = 'data/', fileName = 'fixed_points_post.dat', varfile = 'VAR0', ti = -1, tf = -1, traceField = 'bb', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, interpolation = 'weighted', trace_sub = 1, integration = 'simple', nproc = 1): """ Find the fixed points. call signature:: fixed = fixed_points(datadir = 'data/', fileName = 'fixed_points_post.dat', varfile = 'VAR0', ti = -1, tf = -1, traceField = 'bb', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, interpolation = 'weighted', trace_sub = 1, integration = 'simple', nproc = 1) Finds the fixed points. Returns the fixed points positions. Keyword arguments: *datadir*: Data directory. *fileName*: Name of the fixed points file. *varfile*: Varfile to be read. *ti*: Initial VAR file index for tracer time sequences. Overrides 'varfile'. *tf*: Final VAR file index for tracer time sequences. Overrides 'varfile'. *traceField*: Vector field used for the streamline tracing. *hMin*: Minimum step length for and underflow to occur. *hMax*: Parameter for the initial step length. *lMax*: Maximum length of the streamline. Integration will stop if l >= lMax. *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. 'weighted': weights the adjacent grid points according to their distance. *trace_sub*: Number of sub-grid cells for the seeds for the initial mapping. *intQ*: Quantities to be integrated along the streamlines. *integration*: Integration method. 'simple': low order method. 'RK6': Runge-Kutta 6th order. *nproc*: Number of cores for multi core computation. """ class data_struct: def __init__(self): self.t = [] self.fidx = [] # number of fixed points at this time self.x = [] self.y = [] self.q = [] # Computes rotation along one edge. def edge(vv, p, sx, sy, diff1, diff2, phiMin, rec, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration): 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 intermediate field line s = pc.stream(vv, p, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration, xx = np.array([xm, ym, p.Oz])) tracer = np.concatenate((s.tracers[0,0:2], s.tracers[s.sl-1,:], np.reshape(s.l,(1)))) # discard any streamline which does not converge or hits the boundary if ((tracer[5] >= lMax) or (tracer[4] < p.Oz+p.Lz-p.dz)): dtot = 0. else: diffm = np.array([tracer[2] - tracer[0], tracer[3] - tracer[1]]) if (sum(diffm**2) != 0): diffm = diffm / np.sqrt(sum(diffm**2)) dtot = edge(vv, p, [sx[0], xm], [sy[0], ym], diff1, diffm, phiMin, rec+1, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration)+ \ edge(vv, p, [xm, sx[1]], [ym, sy[1]], diffm, diff2, phiMin, rec+1, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration) return dtot # Finds the Poincare index of this grid cell. def pIndex(vv, p, sx, sy, diff, phiMin, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration): poincare = 0 poincare += edge(vv, p, [sx[0], sx[1]], [sy[0], sy[0]], diff[0,:], diff[1,:], phiMin, 0, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration) poincare += edge(vv, p, [sx[1], sx[1]], [sy[0], sy[1]], diff[1,:], diff[2,:], phiMin, 0, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration) poincare += edge(vv, p, [sx[1], sx[0]], [sy[1], sy[1]], diff[2,:], diff[3,:], phiMin, 0, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration) poincare += edge(vv, p, [sx[0], sx[0]], [sy[1], sy[0]], diff[3,:], diff[0,:], phiMin, 0, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration) return poincare # fixed point finder for a subset of the domain def subFixed(queue, ix0, iy0, vv, p, tracers, iproc, hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, interpolation = 'weighted', integration = 'simple'): diff = np.zeros((4,2)) phiMin = np.pi/8. x = [] y = [] q = [] fidx = 0 for ix in ix0: for iy in iy0: # compute Poincare index around this cell (!= 0 for potential fixed point) diff[0,:] = tracers[iy, ix, 0, 2:4] - tracers[iy, ix, 0, 0:2] diff[1,:] = tracers[iy, ix+1, 0, 2:4] - tracers[iy, ix+1, 0, 0:2] diff[2,:] = tracers[iy+1, ix+1, 0, 2:4] - tracers[iy+1, ix+1, 0, 0:2] diff[3,:] = tracers[iy+1, ix, 0, 2:4] - tracers[iy+1, ix, 0, 0:2] if (sum(np.sum(diff**2, axis = 1) != 0) == True): diff = np.swapaxes(np.swapaxes(diff, 0, 1) / np.sqrt(np.sum(diff**2, axis = 1)), 0, 1) poincare = pIndex(vv, p, tracers[iy, ix:ix+2, 0, 0], tracers[iy:iy+2, ix, 0, 1], diff, phiMin, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration) if (abs(poincare) > 5): # use 5 instead of 2pi to account for rounding errors # subsample to get starting point for iteration nt = 4 xmin = tracers[iy, ix, 0, 0] ymin = tracers[iy, ix, 0, 1] xmax = tracers[iy, ix+1, 0, 0] ymax = tracers[iy+1, ix, 0, 1] xx = np.zeros((nt**2,3)) tracersSub = 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] = p.Oz i1 += 1 for it1 in range(nt**2): s = pc.stream(vv, p, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration, xx = xx[it1,:]) tracersSub[it1,0:2] = xx[it1,0:2] tracersSub[it1,2:] = s.tracers[s.sl-1,:] min2 = 1e6 minx = xmin miny = ymin i1 = 0 for j1 in range(nt): for k1 in range(nt): diff2 = (tracersSub[i1, 2] - tracersSub[i1, 0])**2 + (tracersSub[i1, 3] - tracersSub[i1, 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 #TODO: dl = np.min(var.dx, var.dy)/100. # step-size for calculating the Jacobian by finite differences it = 0 # tracers used to find the fixed point tracersNull = np.zeros((5,4)) point = np.array([minx, miny]) 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], p.Oz]) xx[1,:] = np.array([point[0]-dl, point[1], p.Oz]) xx[2,:] = np.array([point[0]+dl, point[1], p.Oz]) xx[3,:] = np.array([point[0], point[1]-dl, p.Oz]) xx[4,:] = np.array([point[0], point[1]+dl, p.Oz]) for it1 in range(5): s = pc.stream(vv, p, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration, xx = xx[it1,:]) tracersNull[it1,:2] = xx[it1,:2] tracersNull[it1,2:] = s.tracers[s.sl-1,0:2] # check function convergence ff = np.zeros(2) ff[0] = tracersNull[0,2] - tracersNull[0,0] ff[1] = tracersNull[0,3] - tracersNull[0,1] #TODO: if (sum(abs(ff)) <= 1e-4): fixedPoint = np.array([point[0], point[1]]) break # compute the Jacobian fjac = np.zeros((2,2)) fjac[0,0] = ((tracersNull[2,2] - tracersNull[2,0]) - (tracersNull[1,2] - tracersNull[1,0]))/2./dl fjac[0,1] = ((tracersNull[4,2] - tracersNull[4,0]) - (tracersNull[3,2] - tracersNull[3,0]))/2./dl fjac[1,0] = ((tracersNull[2,3] - tracersNull[2,1]) - (tracersNull[1,3] - tracersNull[1,1]))/2./dl fjac[1,1] = ((tracersNull[4,3] - tracersNull[4,1]) - (tracersNull[3,3] - tracersNull[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] #TODO: if (abs(det) < dl): fixedPoint = 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 #TODO: if (sum(abs(dpoint)) < 1e-4): fixedPoint = point break if (it > 20): fixedPoint = point print("warning: Newton did not converged") break it += 1 # check if fixed point lies inside the cell if ((fixedPoint[0] < tracers[iy, ix, 0, 0]) or (fixedPoint[0] > tracers[iy, ix+1, 0, 0]) or (fixedPoint[1] < tracers[iy, ix, 0, 1]) or (fixedPoint[1] > tracers[iy+1, ix, 0, 1])): print("warning: fixed point lies outside the cell") else: x.append(fixedPoint[0]) y.append(fixedPoint[1]) #q.append() fidx += 1 queue.put((x, y, q, fidx, iproc)) # multi core setup if (np.isscalar(nproc) == False) or (nproc%1 != 0): print("error: invalid processor number") return -1 queue = mp.Queue() proc = [] # make sure to read the var files with the correct magic if (traceField == 'bb'): magic = 'bb' if (traceField == 'jj'): magic = 'jj' if (traceField == 'vort'): magic = 'vort' # read the cpu structure dim = pc.read_dim(datadir = datadir) if (dim.nprocz > 1): print("error: number of cores in z-direction > 1") var = pc.read_var(varfile = varfile, datadir = datadir, magic = magic, quiet = True, trimall = True) grid = pc.read_grid(datadir = datadir, quiet = True, trim = True) vv = getattr(var, traceField) # initialize the parameters p = pc.pClass() p.dx = var.dx; p.dy = var.dy; p.dz = var.dz p.Ox = var.x[0]; p.Oy = var.y[0]; p.Oz = var.z[0] p.Lx = grid.Lx; p.Ly = grid.Ly; p.Lz = grid.Lz p.nx = dim.nx; p.ny = dim.ny; p.nz = dim.nz # create the initial mapping tracers, mapping, t = pc.tracers(traceField = 'bb', hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, trace_sub = trace_sub, varfile = varfile, integration = integration, datadir = datadir, destination = '', nproc = nproc) # find fixed points fixed = pc.fixed_struct() xyq = [] # list of return values from subFixed ix0 = range(0,p.nx*trace_sub-1) # set of grid indices for the cores iy0 = range(0,p.ny*trace_sub-1) # set of grid indices for the cores subFixedLambda = lambda queue, ix0, iy0, vv, p, tracers, iproc: \ subFixed(queue, ix0, iy0, vv, p, tracers, iproc, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration) for iproc in range(nproc): proc.append(mp.Process(target = subFixedLambda, args = (queue, ix0[iproc::nproc], iy0, vv, p, tracers, iproc))) for iproc in range(nproc): proc[iproc].start() for iproc in range(nproc): xyq.append(queue.get()) for iproc in range(nproc): proc[iproc].join() # put together return values from subFixed fixed.fidx = 0 fixed.t = var.t for iproc in range(nproc): fixed.x.append(xyq[xyq[iproc][4]][0]) fixed.y.append(xyq[xyq[iproc][4]][1]) fixed.q.append(xyq[xyq[iproc][4]][2]) fixed.fidx += xyq[xyq[iproc][4]][3] fixed.t = np.array(fixed.t) fixed.x = np.array(fixed.x) fixed.y = np.array(fixed.y) fixed.q = np.array(fixed.q) fixed.fidx = np.array(fixed.fidx) return fixed
def interp_var(var='var.dat', source='old_run', target='new_run', source_path=None, target_path=None, xlim=None, ylim=None, zlim=None, time=None, deltay=None, nghosts=3): """ load var file to be interpolated from old simulation and var file from started new simulation of correct shape and processor layout interpolate the old snapshot onto a mesh of the new shape and old grid limits then rescale new grid and deltay to new limits. """ if source_path == None: localdir = os.getcwd() + '/' if not os.path.exists(localdir + source): print('error: source_path must be specified as string') return os.chdir(localdir + source) print('loading data from ' + localdir + source) fold = pc.read_var(var, quiet=True) else: if not os.path.exists(source_path): print('error: source_path does not exist') return os.chdir(source_path) print('loading data from ' + source_path) fold = pc.read_var(var, quiet=True) if target_path == None: if not os.path.exists(localdir + target): print('error: target_path must be specified as string') return os.chdir(localdir + target) print('loading data from ' + localdir + target) fnew = pc.read_var(var, quiet=True) else: if not os.path.exists(target_path): print('error: target_path does not exist') return os.chdir(target_path) print('loading data from ' + target_path) fnew = pc.read_var(var, quiet=True) if xlim == None: xlim = [fold.x.min(), fold.x.max()] if ylim == None: ylim = [fold.y.min(), fold.y.max()] if zlim == None: zlim = [fold.z.min(), fold.z.max()] arrs = ['uu', 'rho', 'lnrho', 'ss', 'aa', 'shock', 'netheat', 'cooling'] iarr = 0 x = np.linspace(xlim[0], xlim[1], fnew.x.size) y = np.linspace(ylim[0], ylim[1], fnew.y.size) z = np.linspace(zlim[0], zlim[1], fnew.z.size) for arr in arrs: if hasattr(fold, arr): print('interpolating ' + arr) tmp = fold.__getattribute__(arr) intmpx = interp1d(fold.x, tmp, axis=-1) tmp = intmpx(x) intmpy = interp1d(fold.y, tmp, axis=-2) tmp = intmpy(y) intmpz = interp1d(fold.z, tmp, axis=-3) tmp = intmpz(z) fnew.__getattribute__(arr)[:] = tmp if len(tmp.shape) == 4: fnew.f[iarr:iarr + 3] = tmp iarr += 3 else: fnew.f[iarr] = tmp iarr += 1 if hasattr(fold, 'deltay'): fnew.deltay = fold.deltay * ( fnew.y.size - 2 * nghosts) / float(fold.y.size - 2 * nghosts) if not time == None: fnew.t = time return fnew
P.ion() P.figure(figsize=(6, 6), dpi=64) frame = grid.x.min(), grid.x.max(), grid.y.min(), grid.y.max() P.subplots_adjust(bottom=0, top=1, left=0, right=1) x0 = grid.x.mean() P.axvline(x0 + 0.5, color='black', linestyle='--') P.axvline(x0 - 0.5, color='black', linestyle='--') P.axhline(0.5, color='black', linestyle='--') P.axhline(-0.5, color='black', linestyle='--') for ivar in range(0, 8): print "read VAR%d" % ivar var = pc.read_var(ivar=ivar, run2D=param.lwrite_2d, param=param, dim=dim, index=index, quiet=True, trimall=True) f = var.lnrho[dim.nz / 2, ...] # acceleration using an handle if (ivar == 0): im = P.imshow(f, extent=frame, origin='lower', aspect='auto') else: im.set_data(f) im.set_clim(f.min(), f.max()) P.draw() # filename='movie/img%04d.png'%ivar # print 'write', filename
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()
# $Id: init.py,v 1.3 2009-04-27 11:02:31 dintrans Exp $ # Plot the initial setup for the isothermal atmosphere with an entropy # bubble # import pencil as pc import pylab as P param = pc.read_param(quiet=True) grid = pc.read_grid(trim=True, param=param, quiet=True) frame = param.xyz0[0], param.xyz1[0], param.xyz0[2], param.xyz1[2] var = pc.read_var(ivar=0, run2D=True, quiet=True, param=param, trimall=True, magic=['rho']) P.subplot(311) im = P.imshow(var.ss, extent=frame, origin='lower', aspect='auto') P.ylabel('z') P.title('Initial entropy field') P.subplot(312) im = P.imshow(var.rho, extent=frame, origin='lower', aspect='auto') P.xlabel('x') P.ylabel('z') P.title('Initial density field') P.subplot(313)
def __init__(self, dataDir='data/', fileName='var.dat', streamFile='stream.vtk', interpolation='weighted', integration='RK6', hMin=2e-3, hMax=2e4, lMax=500, tol=1e-2, iterMax=1e3, xx=np.array([0, 0, 0])): """ Creates, and returns the traced streamline. call signature: streamInit(datadir = 'data/', fileName = 'save.dat, interpolation = 'weighted', integration = 'simple', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, iterMax = 1e3, xx = np.array([0,0,0])) Trace magnetic streamlines. Keyword arguments: *dataDir*: Data directory. *fileName*: Name of the file with the field information. *interpolation*: Interpolation of the vector field. 'mean': takes the mean of the adjacent grid point. 'weighted': weights the adjacent grid points according to their distance. *integration*: Integration method. 'simple': low order method. 'RK6': Runge-Kutta 6th order. *hMin*: Minimum step length for and underflow to occur. *hMax*: Parameter for the initial step length. *lMax*: Maximum length of the streamline. Integration will stop if l >= lMax. *tol*: Tolerance for each integration step. Reduces the step length if error >= tol. *iterMax*: Maximum number of iterations. *xx*: Initial seeds. """ # read the data var = pc.read_var(datadir=dataDir, varfile=fileName, magic='bb', quiet=True, trimall=True) grid = pc.read_grid(datadir=dataDir, quiet=True) vv = var.bb p = pClass() p.dx = var.dx p.dy = var.dy p.dz = var.dz p.Ox = var.x[0] p.Oy = var.y[0] p.Oz = var.z[0] p.Lx = grid.Lx p.Ly = grid.Ly p.Lz = grid.Lz p.nx = var.bb.shape[1] p.ny = var.bb.shape[2] p.nz = var.bb.shape[3] ss = [] for i in range(xx.shape[1]): s = streamSingle(vv, p, interpolation='weighted', integration='simple', hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, iterMax=iterMax, xx=xx[:, i]) ss.append(s) slMax = 0 for i in range(xx.shape[1]): if (slMax < ss[i].sl): slMax = ss[i].sl self.tracers = np.zeros((xx.shape[1], slMax, 3)) + np.nan self.sl = np.zeros(xx.shape[1], dtype='int32') self.l = np.zeros(xx.shape[1]) for i in range(xx.shape[1]): self.tracers[i, :ss[i].sl, :] = ss[i].tracers self.sl[i] = ss[i].sl self.l[i] = ss[i].l self.p = s.p self.nt = xx.shape[1] # save into vtk file if (streamFile != []): writer = vtk.vtkPolyDataWriter() writer.SetFileName(dataDir + '/' + streamFile) polyData = vtk.vtkPolyData() fieldData = vtk.vtkFieldData() # field containing length of stream lines for later decomposition field = VN.numpy_to_vtk(self.l) field.SetName('l') fieldData.AddArray(field) field = VN.numpy_to_vtk(self.sl.astype(np.int32)) field.SetName('sl') fieldData.AddArray(field) # streamline parameters tmp = range(10) tmp[0] = np.array([hMin], dtype='float32') field = VN.numpy_to_vtk(tmp[0]) field.SetName('hMin') fieldData.AddArray(field) tmp[1] = np.array([hMax], dtype='float32') field = VN.numpy_to_vtk(tmp[1]) field.SetName('hMax') fieldData.AddArray(field) tmp[2] = np.array([lMax], dtype='float32') field = VN.numpy_to_vtk(tmp[2]) field.SetName('lMax') fieldData.AddArray(field) tmp[3] = np.array([tol], dtype='float32') field = VN.numpy_to_vtk(tmp[3]) field.SetName('tol') fieldData.AddArray(field) tmp[4] = np.array([iterMax], dtype='int32') field = VN.numpy_to_vtk(tmp[4]) field.SetName('iterMax') fieldData.AddArray(field) tmp[5] = np.array([self.nt], dtype='int32') field = VN.numpy_to_vtk(tmp[5]) field.SetName('nt') fieldData.AddArray(field) # fields containing simulation parameters stored in paramFile dic = dir(p) params = range(len(dic)) i = 0 for attr in dic: if (attr[0] != '_'): params[i] = getattr(p, attr) params[i] = np.array([params[i]], dtype=type(params[i])) field = VN.numpy_to_vtk(params[i]) field.SetName(attr) fieldData.AddArray(field) i += 1 # all streamlines as continuous array of points points = vtk.vtkPoints() for i in range(xx.shape[1]): for sl in range(self.sl[i]): points.InsertNextPoint(self.tracers[i, sl, :]) polyData.SetPoints(points) polyData.SetFieldData(fieldData) writer.SetInput(polyData) writer.SetFileTypeToBinary() writer.Write()
datatopdir=os.getcwd() models=['sedov'] 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')
def read_var(datadir, filename='var.dat'): return pc.read_var( datadir=datadir, varfile=filename, trimall=True, quiet=True )
# Define path of new directory to save npz files to path_dir = './saved/' # Make the directory if it doesn't already exists if not os.path.exists(path_dir): os.makedirs(path_dir) # Grab VAR number from CLI input: parser = argparse.ArgumentParser() parser.add_argument("datafile", type=int, help='Input var file') var = parser.parse_args().datafile datadir='./data' # Assing data to object ff = pc.read_var(trimall=True, datadir=datadir, ivar=var, magic=["vort"]) fname = ('var%02d' % var) fsave = np.savez_compressed(os.path.join(path_dir,fname), r=ff.x, phi=ff.y, z=ff.z, rhop=ff.rhop, rho=ff.rho, vort=ff.vort, NP=ff.np) 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
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
def post_compute(variables = ['b2m'], datadir = 'data'): """ Compute diagnostic variables from the VAR files. call signature:: post_compute(variables = ['urms'], datadir = 'data') Read the VAR files and compute the diagnostic variables. Write the result in 'post_evaluation.dat'. Keyword arguments: *variables*: The diagnostic variables to be computed. *datadir*: Data directory. """ # open the destination file for writing fd = open(datadir + '/post_evaluation.dat', 'w') # write the header fd.write('#--t-------------'.encode('utf-8')) for variable in variables: fd.write('--{0:15}'.format((variable+'--------------------')[:15]).encode('utf-8')) fd.write('\n') # read the list of all VAR files var_list_file = open('data/proc0/varN.list') var_list = var_list_file.readlines() var_list_file.close() if (len(variables[0]) == 1): variables = [variables] # check if bb needs to be computed bb_flag = False # array containing the variables which depend on bb b_dep = ['ab_int', 'jb_int', 'b1m', 'b2m', 'bm2', 'abm', 'abrms', 'jbm', 'brms', 'gffz'] if (len(set(variables + b_dep)) < len(variables + b_dep)): bb_flag = True # check if jj needs to be computed jj_flag = False # array containing the variables which depend on jj j_dep = ['jb_int', 'j2m', 'jm2', 'jbm', 'jrms'] if (len(set(variables + j_dep)) < len(variables + j_dep)): jj_flag = True for var_file in var_list: # read the var file var = pc.read_var(varfile = var_file[:-1], datadir = datadir, quiet = True) # the output string which will be written in the destination file out_string = '{0:1.9e} '.format(np.float64(var.t)) aa = var.aa[:,var.n1:var.n2,var.m1:var.m2,var.l1:var.l2] if bb_flag: bb = pc.curl(var.aa, var.dx, var.dy, var.dz) bb = bb[:,var.n1:var.n2,var.m1:var.m2,var.l1:var.l2] if jj_flag: jj = pc.curl2(var.aa, var.dx, var.dy, var.dz) jj = jj[:,var.n1:var.n2,var.m1:var.m2,var.l1:var.l2] for variable in variables: if variable == 'b2m': b2m = (pc.dot2(bb)).mean() out_string += '{0:1.9e} '.format(np.float64(b2m)) elif variable == 'j2m': j2m = (pc.dot2(jj)).mean() out_string += '{0:1.9e} '.format(np.float64(j2m)) break elif variable == 'abm': abm = (pc.dot(var.aa, bb)).mean() out_string += '{0:1.9e} '.format(np.float64(abm)) # generalized flux function (see Yeates, Hornig 2011) elif variable == 'gffz': gffz = np.sum(pc.dot(aa, bb)*np.sqrt(pc.dot2(bb)) / \ ((bb[2,:,:,:]) * np.mean(np.mean(np.sqrt(pc.dot2(bb)), axis = 2), axis = 1))) out_string += '{0:1.9e} '.format(np.float64(gffz)) fd.write((out_string+'\n').encode('utf-8')) fd.close()
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()
def read_var(datadir, filename='var.dat'): return pc.read_var(datadir=datadir, varfile=filename, trimall=True, quiet=True)
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
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])
param=pc.read_param(quiet=True) grid=pc.read_grid(trim=True,param=param,quiet=True) P.ion() P.figure(figsize=(6,6),dpi=64) frame=grid.x.min(),grid.x.max(),grid.y.min(),grid.y.max() P.subplots_adjust(bottom=0,top=1,left=0,right=1) x0=grid.x.mean() P.axvline(x0+0.5,color='black',linestyle='--') P.axvline(x0-0.5,color='black',linestyle='--') P.axhline(0.5,color='black',linestyle='--') P.axhline(-0.5,color='black',linestyle='--') for ivar in range(0,8): print "read VAR%d"%ivar var=pc.read_var(ivar=ivar,run2D=param.lwrite_2d,param=param,dim=dim,index=index,quiet=True,trimall=True) f=var.lnrho[dim.nz/2,...] # acceleration using an handle if (ivar==0): im=P.imshow(f,extent=frame,origin='lower',aspect='auto') else: im.set_data(f) im.set_clim(f.min(),f.max()) P.draw() # filename='movie/img%04d.png'%ivar # print 'write', filename # P.savefig(filename,dpi=64) P.show()
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) filename = "init_ism.dat" f = open(filename, "w") # f.write('#--rho-------------------TT-------------\n') for i in range(0, var.rho[:, 0, 0].size): f.write(str(var.rho[i, 0, 0]) + " " + str(var.tt[i, 0, 0]) + "\n") f.closed
# Set up Python load path and configure a matplotlib backend that does not # need X11. This needs to happen before importing the pencil module. import sys sys.path.append('../../../python') import matplotlib matplotlib.use('agg') import pencil as pc # Description: # Read time series and data cube, write a few values datadir = '../data' ts = pc.read_ts(datadir=datadir, plot_data=False, quiet=True) var = pc.read_var(datadir=datadir, trimall=True, quiet=True) # Now write to file file = open('read_data.out', 'w') file.write('ts.times :') for t in ts.t[0:5]: file.write(' %g' % (t, )) file.write('\n') file.write('aa(5,5,0:4,1) :') for a in var.aa[1, 0:5, 5, 5]: file.write(' %g' % (a, )) file.write('\n')
def post_compute(variables = ['b2m'], datadir = 'data'): """ Compute diagnostic variables from the VAR files. call signature:: post_compute(variables = ['urms'], datadir = 'data') Read the VAR files and compute the diagnostic variables. Write the result in 'post_evaluation.dat'. Keyword arguments: *variables*: The diagnostic variables to be computed. *datadir*: Data directory. """ # open the destination file for writing fd = open(datadir + '/post_evaluation.dat', 'w') # write the header fd.write('#--t-------------'.encode('utf-8')) for variable in variables: fd.write('--{0:15}'.format((variable+'--------------------')[:15]).encode('utf-8')) fd.write('\n') # read the list of all VAR files var_list_file = open('data/proc0/varN.list') var_list = var_list_file.readlines() var_list_file.close() if (len(variables[0]) == 1): variables = [variables] # check if bb needs to be computed bb_flag = False # array containing the variables which depend on bb b_dep = ['ab_int', 'jb_int', 'b1m', 'b2m', 'bm2', 'abm', 'abrms', 'jbm', 'brms', 'gffz'] if (len(set(variables + b_dep)) < len(variables + b_dep)): bb_flag = True # check if jj needs to be computed jj_flag = False # array containing the variables which depend on jj j_dep = ['jb_int', 'j2m', 'jm2', 'jbm', 'jrms'] if (len(set(variables + j_dep)) < len(variables + j_dep)): jj_flag = True for var_file in var_list: # read the var file var = pc.read_var(varfile = var_file[:-1], datadir = datadir, quiet = True) # the output string which will be written in the destination file out_string = '{0:1.9e} '.format(np.float64(var.t)) aa = var.aa[:,var.n1:var.n2,var.m1:var.m2,var.l1:var.l2] if bb_flag: bb = pc.curl(var.aa, var.dx, var.dy, var.dz, var.x, var.y, var.z) bb = bb[:,var.n1:var.n2,var.m1:var.m2,var.l1:var.l2] if jj_flag: jj = pc.curl2(var.aa, var.dx, var.dy, var.dz, var.x, var.y, var.z) jj = jj[:,var.n1:var.n2,var.m1:var.m2,var.l1:var.l2] for variable in variables: if variable == 'b2m': b2m = (pc.dot2(bb)).mean() out_string += '{0:1.9e} '.format(np.float64(b2m)) elif variable == 'j2m': j2m = (pc.dot2(jj)).mean() out_string += '{0:1.9e} '.format(np.float64(j2m)) break elif variable == 'abm': abm = (pc.dot(var.aa, bb)).mean() out_string += '{0:1.9e} '.format(np.float64(abm)) # generalized flux function (see Yeates, Hornig 2011) elif variable == 'gffz': gffz = np.sum(pc.dot(aa, bb)*np.sqrt(pc.dot2(bb)) / \ ((bb[2,:,:,:]) * np.mean(np.mean(np.sqrt(pc.dot2(bb)), axis = 2), axis = 1))) out_string += '{0:1.9e} '.format(np.float64(gffz)) fd.write((out_string+'\n').encode('utf-8')) fd.close()
import pencil import numpy from matplotlib import pyplot import sys parameters = pencil.read_param() var = "pvar.dat" data = pencil.read_var() t = data.t if len(sys.argv) > 1: var = sys.argv[1] if (var != "pvar.dat"): t = int(var[4:]) * parameters.tausp pdata = pencil.read_pvar(varfile=var) pdata0 = pencil.read_pvar(varfile="PVAR0") xp = pdata.xp yp = pdata.yp zp = pdata.zp xp0 = pdata0.xp yp0 = pdata0.yp zp0 = pdata0.zp x0 = parameters.xyz0[0] y0 = parameters.xyz0[1] z0 = parameters.xyz0[2] x1 = parameters.xyz1[0] y1 = parameters.xyz1[1] z1 = parameters.xyz1[2]
def tracers(traceField='bb', hMin=2e-3, hMax=2e4, lMax=500, tol=1e-2, interpolation='weighted', trace_sub=1, intQ=[''], varfile='VAR0', ti=-1, tf=-1, integration='simple', datadir='data/', destination='tracers.dat', nproc=1): """ Trace streamlines from the VAR files and integrate quantity 'intQ' along them. call signature:: tracers(field = 'bb', hMin = 2e-3, hMax = 2e2, lMax = 500, tol = 2e-3, interpolation = 'weighted', trace_sub = 1, intQ = '', varfile = 'VAR0', ti = -1, tf = -1, datadir = 'data', destination = 'tracers.dat', nproc = 1) Trace streamlines of the vectofield 'field' from z = z0 to z = z1 and integrate quantities 'intQ' along the lines. Creates a 2d mapping as in 'streamlines.f90'. Keyword arguments: *traceField*: Vector field used for the streamline tracing. *hMin*: Minimum step length for and underflow to occur. *hMax*: Parameter for the initial step length. *lMax*: Maximum length of the streamline. Integration will stop if l >= lMax. *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. 'weighted': weights the adjacent grid points according to their distance. *trace_sub*: Number of sub-grid cells for the seeds. *intQ*: 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'. *datadir*: Directory where the data is stored. *destination*: Destination file. *nproc*: Number of cores for multi core computation. """ # returns the tracers for the specified starting locations def subTracers(q, vv, p, tracers0, iproc, hMin=2e-3, hMax=2e4, lMax=500, tol=1e-2, interpolation='weighted', integration='simple', intQ=['']): tracers = tracers0 mapping = np.zeros((tracers.shape[0], tracers.shape[1], 3)) for ix in range(tracers.shape[0]): for iy in range(tracers.shape[1]): xx = tracers[ix, iy, 2:5].copy() s = pc.stream(vv, p, interpolation=interpolation, integration=integration, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, xx=xx) tracers[ix, iy, 2:5] = s.tracers[s.sl - 1] tracers[ix, iy, 5] = s.l if (any(intQ == 'curlyA')): for l in range(s.sl - 1): aaInt = pc.vecInt( (s.tracers[l + 1] + s.tracers[l]) / 2, aa, p, interpolation) tracers[ix, iy, 6] += np.dot(aaInt, (s.tracers[l + 1] - s.tracers[l])) # create the color mapping if (tracers[ix, iy, 4] > grid.z[-2]): if (tracers[ix, iy, 0] - tracers[ix, iy, 2]) > 0: if (tracers[ix, iy, 1] - tracers[ix, iy, 3]) > 0: mapping[ix, iy, :] = [0, 1, 0] else: mapping[ix, iy, :] = [1, 1, 0] else: if (tracers[ix, iy, 1] - tracers[ix, iy, 3]) > 0: mapping[ix, iy, :] = [0, 0, 1] else: mapping[ix, iy, :] = [1, 0, 0] else: mapping[ix, iy, :] = [1, 1, 1] q.put((tracers, mapping, iproc)) # multi core setup if (np.isscalar(nproc) == False) or (nproc % 1 != 0): print("error: invalid processor number") return -1 queue = mp.Queue() # read the data # make sure to read the var files with the correct magic if (traceField == 'bb'): magic = 'bb' if (traceField == 'jj'): magic = 'jj' if (traceField == 'vort'): magic = 'vort' # convert intQ string into list if (isinstance(intQ, list) == False): intQ = [intQ] intQ = np.array(intQ) grid = pc.read_grid(datadir=datadir, trim=True, quiet=True) dim = pc.read_dim(datadir=datadir) tol2 = tol**2 # check if user wants a tracer time series if ((ti % 1 == 0) and (tf % 1 == 0) and (ti >= 0) and (tf >= ti)): series = True n_times = tf - ti + 1 else: series = False n_times = 1 tracers = np.zeros([ int(trace_sub * dim.nx), int(trace_sub * dim.ny), n_times, 6 + len(intQ) ]) mapping = np.zeros( [int(trace_sub * dim.nx), int(trace_sub * dim.ny), n_times, 3]) t = np.zeros(n_times) for tIdx in range(n_times): if series: varfile = 'VAR' + str(tIdx) # read the data var = pc.read_var(varfile=varfile, datadir=datadir, magic=magic, quiet=True, trimall=True) grid = pc.read_grid(datadir=datadir, quiet=True, trim=True) t[tIdx] = var.t # extract the requested vector traceField vv = getattr(var, traceField) if (any(intQ == 'curlyA')): aa = var.aa # initialize the parameters p = pc.pClass() p.dx = var.dx p.dy = var.dy p.dz = var.dz p.Ox = var.x[0] p.Oy = var.y[0] p.Oz = var.z[0] p.Lx = grid.Lx p.Ly = grid.Ly p.Lz = grid.Lz p.nx = dim.nx p.ny = dim.ny p.nz = dim.nz # initialize the tracers for ix in range(int(trace_sub * dim.nx)): for iy in range(int(trace_sub * dim.ny)): tracers[ix, iy, tIdx, 0] = grid.x[0] + int(grid.dx / trace_sub) * ix tracers[ix, iy, tIdx, 2] = tracers[ix, iy, tIdx, 0] tracers[ix, iy, tIdx, 1] = grid.y[0] + int(grid.dy / trace_sub) * iy tracers[ix, iy, tIdx, 3] = tracers[ix, iy, tIdx, 1] tracers[ix, iy, tIdx, 4] = grid.z[0] # declare vectors xMid = np.zeros(3) xSingle = np.zeros(3) xHalf = np.zeros(3) xDouble = np.zeros(3) tmp = [] subTracersLambda = lambda queue, vv, p, tracers, iproc: \ subTracers(queue, vv, p, tracers, iproc, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration, intQ = intQ) proc = [] for iproc in range(nproc): proc.append( mp.Process(target=subTracersLambda, args=(queue, vv, p, tracers[iproc::nproc, :, tIdx, :], iproc))) for iproc in range(nproc): proc[iproc].start() for iproc in range(nproc): tmp.append(queue.get()) for iproc in range(nproc): proc[iproc].join() for iproc in range(nproc): tracers[tmp[iproc][2]::nproc, :, tIdx, :], mapping[tmp[iproc][2]::nproc, :, tIdx, :] = (tmp[iproc][0], tmp[iproc][1]) for iproc in range(nproc): proc[iproc].terminate() tracers = np.copy(tracers.swapaxes(0, 3), order='C') if (destination != ''): f = open(datadir + destination, 'wb') f.write(np.array(trace_sub, dtype='float32')) # write tracers into file for tIdx in range(n_times): f.write(t[tIdx].astype('float32')) f.write(tracers[:, :, tIdx, :].astype('float32')) f.close() tracers = tracers.swapaxes(0, 3) tracers = tracers.swapaxes(0, 1) mapping = mapping.swapaxes(0, 1) return tracers, mapping, t
def lo_pass(self, kthresh): pass def filter_field(self, k, dk=1.): shell = self.get_shell(k) hat = (self.fft).copy() hat[~shell] = 0 return (self._ifftn(hat, **self._extra_fft_args)).real if __name__ == "__main__": import pencil as pc import pylab as P import os import pickle from .utils import pc_en_spec datadir = os.path.expanduser( '~/vc/pencil-code/samples/helical-MHDturb/data/') t, pcpow = pc.read_power('power_kin.dat', datadir=datadir) var = pc.read_var(datadir=datadir) power2 = 0.5 * abs( fpack.fftn(pc.dot2(var.f[0:3, 3:-3, 3:-3, 3:-3])) / var.f[0, 3:-3, 3:-3, 3:-3].size) spec = pc_en_spec(var) q = FourierFilter(power2) spec2 = na.array([power2[q.get_shell(bin)].sum() for bin in range(q.nx)]) P.loglog(pcpow[-1, :], 'rx', markersize=10) P.loglog(spec) P.loglog(spec2) P.show()
import pencil import numpy from matplotlib import pyplot from matplotlib import cm import sys import os ivar = -1 pvar = "pvar.dat" if (len(sys.argv) > 1): ivar = int(sys.argv[1]) pvar = "PVAR" + sys.argv[1] data = pencil.read_var(ivar=ivar, trimall=True, quiet=True) xgrid = data.x nx = len(xgrid) dxgrid = data.dx x0 = xgrid[0] x1 = xgrid[-1] ygrid = data.y ny = len(ygrid) dygrid = data.dy y0 = ygrid[0] y1 = ygrid[-1] zgrid = data.z nz = len(zgrid) dzgrid = data.dz z0 = zgrid[0] z1 = zgrid[-1] z_ref = 0.0
def tracers(traceField = 'bb', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, interpolation = 'weighted', trace_sub = 1, intQ = [''], varfile = 'VAR0', ti = -1, tf = -1, integration = 'simple', datadir = 'data/', destination = 'tracers.dat', nproc = 1): """ Trace streamlines from the VAR files and integrate quantity 'intQ' along them. call signature:: tracers(field = 'bb', hMin = 2e-3, hMax = 2e2, lMax = 500, tol = 2e-3, interpolation = 'weighted', trace_sub = 1, intQ = '', varfile = 'VAR0', ti = -1, tf = -1, datadir = 'data', destination = 'tracers.dat', nproc = 1) Trace streamlines of the vectofield 'field' from z = z0 to z = z1 and integrate quantities 'intQ' along the lines. Creates a 2d mapping as in 'streamlines.f90'. Keyword arguments: *traceField*: Vector field used for the streamline tracing. *hMin*: Minimum step length for and underflow to occur. *hMax*: Parameter for the initial step length. *lMax*: Maximum length of the streamline. Integration will stop if l >= lMax. *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. 'weighted': weights the adjacent grid points according to their distance. *trace_sub*: Number of sub-grid cells for the seeds. *intQ*: 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'. *datadir*: Directory where the data is stored. *destination*: Destination file. *nproc*: Number of cores for multi core computation. """ # returns the tracers for the specified starting locations def subTracers(q, vv, p, tracers0, iproc, hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, interpolation = 'weighted', integration = 'simple', intQ = ['']): tracers = tracers0 mapping = np.zeros((tracers.shape[0], tracers.shape[1], 3)) for ix in range(tracers.shape[0]): for iy in range(tracers.shape[1]): xx = tracers[ix, iy, 2:5].copy() s = pc.stream(vv, p, interpolation = interpolation, integration = integration, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, xx = xx) tracers[ix, iy, 2:5] = s.tracers[s.sl-1] tracers[ix, iy, 5] = s.l if (any(intQ == 'curlyA')): for l in range(s.sl-1): aaInt = pc.vecInt((s.tracers[l+1] + s.tracers[l])/2, aa, p, interpolation) tracers[ix, iy, 6] += np.dot(aaInt, (s.tracers[l+1] - s.tracers[l])) # create the color mapping if (tracers[ix, iy, 4] > grid.z[-2]): if (tracers[ix, iy, 0] - tracers[ix, iy, 2]) > 0: if (tracers[ix, iy, 1] - tracers[ix, iy, 3]) > 0: mapping[ix, iy, :] = [0,1,0] else: mapping[ix, iy, :] = [1,1,0] else: if (tracers[ix, iy, 1] - tracers[ix, iy, 3]) > 0: mapping[ix, iy, :] = [0,0,1] else: mapping[ix, iy, :] = [1,0,0] else: mapping[ix, iy, :] = [1,1,1] q.put((tracers, mapping, iproc)) # multi core setup if (np.isscalar(nproc) == False) or (nproc%1 != 0): print("error: invalid processor number") return -1 queue = mp.Queue() # read the data # make sure to read the var files with the correct magic if (traceField == 'bb'): magic = 'bb' if (traceField == 'jj'): magic = 'jj' if (traceField == 'vort'): magic = 'vort' # convert intQ string into list if (isinstance(intQ, list) == False): intQ = [intQ] intQ = np.array(intQ) grid = pc.read_grid(datadir = datadir, trim = True, quiet = True) dim = pc.read_dim(datadir = datadir) tol2 = tol**2 # check if user wants a tracer time series if ((ti%1 == 0) and (tf%1 == 0) and (ti >= 0) and (tf >= ti)): series = True n_times = tf-ti+1 else: series = False n_times = 1 tracers = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny), n_times, 6+len(intQ)]) mapping = np.zeros([int(trace_sub*dim.nx), int(trace_sub*dim.ny), n_times, 3]) t = np.zeros(n_times) for tIdx in range(n_times): if series: varfile = 'VAR' + str(tIdx) # read the data var = pc.read_var(varfile = varfile, datadir = datadir, magic = magic, quiet = True, trimall = True) grid = pc.read_grid(datadir = datadir, quiet = True, trim = True) t[tIdx] = var.t # extract the requested vector traceField vv = getattr(var, traceField) if (any(intQ == 'curlyA')): aa = var.aa # initialize the parameters p = pc.pClass() p.dx = var.dx; p.dy = var.dy; p.dz = var.dz p.Ox = var.x[0]; p.Oy = var.y[0]; p.Oz = var.z[0] p.Lx = grid.Lx; p.Ly = grid.Ly; p.Lz = grid.Lz p.nx = dim.nx; p.ny = dim.ny; p.nz = dim.nz # initialize the tracers for ix in range(int(trace_sub*dim.nx)): for iy in range(int(trace_sub*dim.ny)): tracers[ix, iy, tIdx, 0] = grid.x[0] + int(grid.dx/trace_sub)*ix tracers[ix, iy, tIdx, 2] = tracers[ix, iy, tIdx, 0] tracers[ix, iy, tIdx, 1] = grid.y[0] + int(grid.dy/trace_sub)*iy tracers[ix, iy, tIdx, 3] = tracers[ix, iy, tIdx, 1] tracers[ix, iy, tIdx, 4] = grid.z[0] # declare vectors xMid = np.zeros(3) xSingle = np.zeros(3) xHalf = np.zeros(3) xDouble = np.zeros(3) tmp = [] subTracersLambda = lambda queue, vv, p, tracers, iproc: \ subTracers(queue, vv, p, tracers, iproc, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration, intQ = intQ) proc = [] for iproc in range(nproc): proc.append(mp.Process(target = subTracersLambda, args = (queue, vv, p, tracers[iproc::nproc,:,tIdx,:], iproc))) for iproc in range(nproc): proc[iproc].start() for iproc in range(nproc): tmp.append(queue.get()) for iproc in range(nproc): proc[iproc].join() for iproc in range(nproc): tracers[tmp[iproc][2]::nproc,:,tIdx,:], mapping[tmp[iproc][2]::nproc,:,tIdx,:] = (tmp[iproc][0], tmp[iproc][1]) for iproc in range(nproc): proc[iproc].terminate() tracers = np.copy(tracers.swapaxes(0, 3), order = 'C') if (destination != ''): f = open(datadir + destination, 'wb') f.write(np.array(trace_sub, dtype = 'float32')) # write tracers into file for tIdx in range(n_times): f.write(t[tIdx].astype('float32')) f.write(tracers[:,:,tIdx,:].astype('float32')) f.close() tracers = tracers.swapaxes(0, 3) tracers = tracers.swapaxes(0, 1) mapping = mapping.swapaxes(0, 1) return tracers, mapping, t
def fixed_points(datadir='data/', fileName='fixed_points_post.dat', varfile='VAR0', ti=-1, tf=-1, traceField='bb', hMin=2e-3, hMax=2e4, lMax=500, tol=1e-2, interpolation='weighted', trace_sub=1, integration='simple', nproc=1): """ Find the fixed points. call signature:: fixed = fixed_points(datadir = 'data/', fileName = 'fixed_points_post.dat', varfile = 'VAR0', ti = -1, tf = -1, traceField = 'bb', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, interpolation = 'weighted', trace_sub = 1, integration = 'simple', nproc = 1) Finds the fixed points. Returns the fixed points positions. Keyword arguments: *datadir*: Data directory. *fileName*: Name of the fixed points file. *varfile*: Varfile to be read. *ti*: Initial VAR file index for tracer time sequences. Overrides 'varfile'. *tf*: Final VAR file index for tracer time sequences. Overrides 'varfile'. *traceField*: Vector field used for the streamline tracing. *hMin*: Minimum step length for and underflow to occur. *hMax*: Parameter for the initial step length. *lMax*: Maximum length of the streamline. Integration will stop if l >= lMax. *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. 'weighted': weights the adjacent grid points according to their distance. *trace_sub*: Number of sub-grid cells for the seeds for the initial mapping. *intQ*: Quantities to be integrated along the streamlines. *integration*: Integration method. 'simple': low order method. 'RK6': Runge-Kutta 6th order. *nproc*: Number of cores for multi core computation. """ class data_struct: def __init__(self): self.t = [] self.fidx = [] # number of fixed points at this time self.x = [] self.y = [] self.q = [] # Computes rotation along one edge. def edge(vv, p, sx, sy, diff1, diff2, phiMin, rec, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration): 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 intermediate field line s = pc.stream(vv, p, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration, xx=np.array([xm, ym, p.Oz])) tracer = np.concatenate( (s.tracers[0, 0:2], s.tracers[s.sl - 1, :], np.reshape(s.l, (1)))) # discard any streamline which does not converge or hits the boundary if ((tracer[5] >= lMax) or (tracer[4] < p.Oz + p.Lz - p.dz)): dtot = 0. else: diffm = np.array( [tracer[2] - tracer[0], tracer[3] - tracer[1]]) if (sum(diffm**2) != 0): diffm = diffm / np.sqrt(sum(diffm**2)) dtot = edge(vv, p, [sx[0], xm], [sy[0], ym], diff1, diffm, phiMin, rec+1, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration)+ \ edge(vv, p, [xm, sx[1]], [ym, sy[1]], diffm, diff2, phiMin, rec+1, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration) return dtot # Finds the Poincare index of this grid cell. def pIndex(vv, p, sx, sy, diff, phiMin, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration): poincare = 0 poincare += edge(vv, p, [sx[0], sx[1]], [sy[0], sy[0]], diff[0, :], diff[1, :], phiMin, 0, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration) poincare += edge(vv, p, [sx[1], sx[1]], [sy[0], sy[1]], diff[1, :], diff[2, :], phiMin, 0, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration) poincare += edge(vv, p, [sx[1], sx[0]], [sy[1], sy[1]], diff[2, :], diff[3, :], phiMin, 0, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration) poincare += edge(vv, p, [sx[0], sx[0]], [sy[1], sy[0]], diff[3, :], diff[0, :], phiMin, 0, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration) return poincare # fixed point finder for a subset of the domain def subFixed(queue, ix0, iy0, vv, p, tracers, iproc, hMin=2e-3, hMax=2e4, lMax=500, tol=1e-2, interpolation='weighted', integration='simple'): diff = np.zeros((4, 2)) phiMin = np.pi / 8. x = [] y = [] q = [] fidx = 0 for ix in ix0: for iy in iy0: # compute Poincare index around this cell (!= 0 for potential fixed point) diff[0, :] = tracers[iy, ix, 0, 2:4] - tracers[iy, ix, 0, 0:2] diff[1, :] = tracers[iy, ix + 1, 0, 2:4] - tracers[iy, ix + 1, 0, 0:2] diff[2, :] = tracers[iy + 1, ix + 1, 0, 2:4] - tracers[iy + 1, ix + 1, 0, 0:2] diff[3, :] = tracers[iy + 1, ix, 0, 2:4] - tracers[iy + 1, ix, 0, 0:2] if (sum(np.sum(diff**2, axis=1) != 0) == True): diff = np.swapaxes( np.swapaxes(diff, 0, 1) / np.sqrt(np.sum(diff**2, axis=1)), 0, 1) poincare = pIndex(vv, p, tracers[iy, ix:ix + 2, 0, 0], tracers[iy:iy + 2, ix, 0, 1], diff, phiMin, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration) if (abs(poincare) > 5 ): # use 5 instead of 2pi to account for rounding errors # subsample to get starting point for iteration nt = 4 xmin = tracers[iy, ix, 0, 0] ymin = tracers[iy, ix, 0, 1] xmax = tracers[iy, ix + 1, 0, 0] ymax = tracers[iy + 1, ix, 0, 1] xx = np.zeros((nt**2, 3)) tracersSub = 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] = p.Oz i1 += 1 for it1 in range(nt**2): s = pc.stream(vv, p, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration, xx=xx[it1, :]) tracersSub[it1, 0:2] = xx[it1, 0:2] tracersSub[it1, 2:] = s.tracers[s.sl - 1, :] min2 = 1e6 minx = xmin miny = ymin i1 = 0 for j1 in range(nt): for k1 in range(nt): diff2 = (tracersSub[i1, 2] - tracersSub[i1, 0] )**2 + (tracersSub[i1, 3] - tracersSub[i1, 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 #TODO: dl = np.min( var.dx, var.dy ) / 100. # step-size for calculating the Jacobian by finite differences it = 0 # tracers used to find the fixed point tracersNull = np.zeros((5, 4)) point = np.array([minx, miny]) 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], p.Oz]) xx[1, :] = np.array([point[0] - dl, point[1], p.Oz]) xx[2, :] = np.array([point[0] + dl, point[1], p.Oz]) xx[3, :] = np.array([point[0], point[1] - dl, p.Oz]) xx[4, :] = np.array([point[0], point[1] + dl, p.Oz]) for it1 in range(5): s = pc.stream(vv, p, hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, integration=integration, xx=xx[it1, :]) tracersNull[it1, :2] = xx[it1, :2] tracersNull[it1, 2:] = s.tracers[s.sl - 1, 0:2] # check function convergence ff = np.zeros(2) ff[0] = tracersNull[0, 2] - tracersNull[0, 0] ff[1] = tracersNull[0, 3] - tracersNull[0, 1] #TODO: if (sum(abs(ff)) <= 1e-4): fixedPoint = np.array([point[0], point[1]]) break # compute the Jacobian fjac = np.zeros((2, 2)) fjac[0, 0] = ( (tracersNull[2, 2] - tracersNull[2, 0]) - (tracersNull[1, 2] - tracersNull[1, 0])) / 2. / dl fjac[0, 1] = ( (tracersNull[4, 2] - tracersNull[4, 0]) - (tracersNull[3, 2] - tracersNull[3, 0])) / 2. / dl fjac[1, 0] = ( (tracersNull[2, 3] - tracersNull[2, 1]) - (tracersNull[1, 3] - tracersNull[1, 1])) / 2. / dl fjac[1, 1] = ( (tracersNull[4, 3] - tracersNull[4, 1]) - (tracersNull[3, 3] - tracersNull[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] #TODO: if (abs(det) < dl): fixedPoint = 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 #TODO: if (sum(abs(dpoint)) < 1e-4): fixedPoint = point break if (it > 20): fixedPoint = point print "warning: Newton did not converged" break it += 1 # check if fixed point lies inside the cell if ((fixedPoint[0] < tracers[iy, ix, 0, 0]) or (fixedPoint[0] > tracers[iy, ix + 1, 0, 0]) or (fixedPoint[1] < tracers[iy, ix, 0, 1]) or (fixedPoint[1] > tracers[iy + 1, ix, 0, 1])): print "warning: fixed point lies outside the cell" else: x.append(fixedPoint[0]) y.append(fixedPoint[1]) #q.append() fidx += 1 queue.put((x, y, q, fidx, iproc)) # multi core setup if (np.isscalar(nproc) == False) or (nproc % 1 != 0): print("error: invalid processor number") return -1 queue = mp.Queue() proc = [] # make sure to read the var files with the correct magic if (traceField == 'bb'): magic = 'bb' if (traceField == 'jj'): magic = 'jj' if (traceField == 'vort'): magic = 'vort' # read the cpu structure dim = pc.read_dim(datadir=datadir) if (dim.nprocz > 1): print "error: number of cores in z-direction > 1" var = pc.read_var(varfile=varfile, datadir=datadir, magic=magic, quiet=True, trimall=True) grid = pc.read_grid(datadir=datadir, quiet=True, trim=True) vv = getattr(var, traceField) # initialize the parameters p = pc.pClass() p.dx = var.dx p.dy = var.dy p.dz = var.dz p.Ox = var.x[0] p.Oy = var.y[0] p.Oz = var.z[0] p.Lx = grid.Lx p.Ly = grid.Ly p.Lz = grid.Lz p.nx = dim.nx p.ny = dim.ny p.nz = dim.nz # create the initial mapping tracers, mapping, t = pc.tracers(traceField='bb', hMin=hMin, hMax=hMax, lMax=lMax, tol=tol, interpolation=interpolation, trace_sub=trace_sub, varfile=varfile, integration=integration, datadir=datadir, destination='', nproc=nproc) # find fixed points fixed = pc.fixed_struct() xyq = [] # list of return values from subFixed ix0 = range(0, p.nx * trace_sub - 1) # set of grid indices for the cores iy0 = range(0, p.ny * trace_sub - 1) # set of grid indices for the cores subFixedLambda = lambda queue, ix0, iy0, vv, p, tracers, iproc: \ subFixed(queue, ix0, iy0, vv, p, tracers, iproc, hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, interpolation = interpolation, integration = integration) for iproc in range(nproc): proc.append( mp.Process(target=subFixedLambda, args=(queue, ix0[iproc::nproc], iy0, vv, p, tracers, iproc))) for iproc in range(nproc): proc[iproc].start() for iproc in range(nproc): xyq.append(queue.get()) for iproc in range(nproc): proc[iproc].join() # put together return values from subFixed fixed.fidx = 0 fixed.t = var.t for iproc in range(nproc): fixed.x.append(xyq[xyq[iproc][4]][0]) fixed.y.append(xyq[xyq[iproc][4]][1]) fixed.q.append(xyq[xyq[iproc][4]][2]) fixed.fidx += xyq[xyq[iproc][4]][3] fixed.t = np.array(fixed.t) fixed.x = np.array(fixed.x) fixed.y = np.array(fixed.y) fixed.q = np.array(fixed.q) fixed.fidx = np.array(fixed.fidx) return fixed
""" import numpy as np import matplotlib.pyplot as plt import pencil as pc import os import sys s = int(sys.argv[1]) #VAR file to start from st = int(sys.argv[2]) #VAR file to stop at n = int(sys.argv[3]) #number of particles to pick out var = pc.read_var(varfile='VAR1') #read in fisrt var dt = var.t # gets time step to use latter def patry(v=-1): # this function stores all info of v-th pvar on array p if v == -1: pvar = pc.read_pvar() else: pvar = pc.read_pvar(varfile='PVAR' + str(v)) i, x, y, z, vx, vy, vz = pvar.ipars, pvar.xp, pvar.yp, pvar.zp, pvar.vpx, pvar.vpy, pvar.vpz p = np.array([i, x, y, z, vx, vy, vz]) return p def get_party(s, st): # sotres partilce data for selcted time slices p = patry()
from matplotlib import pyplot 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() data = pencil.read_var(ivar=ivar) pdata = pencil.read_pvar(varfile=pvar) xp = pdata.xp*1000. yp = pdata.yp*1000. zp = pdata.zp*1000. ipars = pdata.ipars closeness = numpy.zeros(len(ipars)) for i in range(len(ipars)): x_ref = xp[i] y_ref = yp[i] z_ref = zp[i] for j in range(len(ipars)): if(j == i): continue
# Set up Python load path and configure a matplotlib backend that does not # need X11. This needs to happen before importing the pencil module. import sys sys.path.append('../../../python') import matplotlib matplotlib.use('agg') import pencil as pc # Description: # Read time series and data cube, write a few values datadir = '../data' ts = pc.read_ts(datadir=datadir, plot_data=False, quiet=True) var = pc.read_var(datadir=datadir, trimall=True, quiet=True) # Now write to file file = open('read_data.out', 'w') file.write('ts.times :') for t in ts.t[0:5]: file.write(' %g' % (t, )) file.write('\n') file.write('aa(5,5,0:4,1) :') for a in var.aa[1, 0:5, 5, 5]: file.write(' %g' % (a, )) file.write('\n') file.close()
datatopdir=os.getcwd() models=['snowplough'] 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]+'_snowplough.h5', 'w')
import pencil as pc import matplotlib.pyplot as plt import numpy as np from pylab import * import sys #n=int(input("Eccentricty value")) #dirint=int(input("Run int?")) Orbits = int(input('Orbits?:')) ff = pc.read_var(trimall=True, ivar=Orbits) print np.amax(ff.rho), np.amin(ff.rho) print ff.t rad = ff.x theta = ff.y rad2d, theta2d = np.meshgrid(rad, theta) x2d = rad2d*np.cos(theta2d) y2d = rad2d*np.sin(theta2d) # Cartesian plot fig, ((ax1, ax2)) = plt.subplots(1, 2, figsize=(30, 5)) # plt.suptitle('AGNRun'+str(dirint).zfill(0)+'_EnergyE0.'+str(n).zfill(0)) # plt.tight_layout() # X,Y & data2D must all be the same dimesions ncolors = 256 fig.subplots_adjust(left=0.05, top=0.9, wspace=0.10)
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])
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] y_lower_frac = 1.0
def __init__(self, dataDir = 'data/', fileName = 'var.dat', streamFile = 'stream.vtk', interpolation = 'weighted', integration = 'RK6', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, iterMax = 1e3, xx = np.array([0,0,0])): """ Creates, and returns the traced streamline. call signature: streamInit(datadir = 'data/', fileName = 'save.dat, interpolation = 'weighted', integration = 'simple', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, iterMax = 1e3, xx = np.array([0,0,0])) Trace magnetic streamlines. Keyword arguments: *dataDir*: Data directory. *fileName*: Name of the file with the field information. *interpolation*: Interpolation of the vector field. 'mean': takes the mean of the adjacent grid point. 'weighted': weights the adjacent grid points according to their distance. *integration*: Integration method. 'simple': low order method. 'RK6': Runge-Kutta 6th order. *hMin*: Minimum step length for and underflow to occur. *hMax*: Parameter for the initial step length. *lMax*: Maximum length of the streamline. Integration will stop if l >= lMax. *tol*: Tolerance for each integration step. Reduces the step length if error >= tol. *iterMax*: Maximum number of iterations. *xx*: Initial seeds. """ # read the data var = pc.read_var(datadir = dataDir, varfile = fileName, magic = 'bb', quiet = True, trimall = True) grid = pc.read_grid(datadir = dataDir, quiet = True) vv = var.bb p = pClass() p.dx = var.dx; p.dy = var.dy; p.dz = var.dz p.Ox = var.x[0]; p.Oy = var.y[0]; p.Oz = var.z[0] p.Lx = grid.Lx; p.Ly = grid.Ly; p.Lz = grid.Lz p.nx = var.bb.shape[1]; p.ny = var.bb.shape[2]; p.nz = var.bb.shape[3] ss = [] for i in range(xx.shape[1]): s = streamSingle(vv, p, interpolation = 'weighted', integration = 'simple', hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, iterMax = iterMax, xx = xx[:,i]) ss.append(s) slMax = 0 for i in range(xx.shape[1]): if (slMax < ss[i].sl): slMax = ss[i].sl self.tracers = np.zeros((xx.shape[1], slMax, 3)) + np.nan self.sl = np.zeros(xx.shape[1], dtype = 'int32') self.l = np.zeros(xx.shape[1]) for i in range(xx.shape[1]): self.tracers[i,:ss[i].sl,:] = ss[i].tracers self.sl[i] = ss[i].sl self.l[i] = ss[i].l self.p = s.p self.nt = xx.shape[1] # save into vtk file if (streamFile != []): writer = vtk.vtkPolyDataWriter() writer.SetFileName(dataDir + '/' + streamFile) polyData = vtk.vtkPolyData() fieldData = vtk.vtkFieldData() # field containing length of stream lines for later decomposition field = VN.numpy_to_vtk(self.l) field.SetName('l') fieldData.AddArray(field) field = VN.numpy_to_vtk(self.sl.astype(np.int32)) field.SetName('sl') fieldData.AddArray(field) # streamline parameters tmp = range(10) tmp[0] = np.array([hMin], dtype = 'float32'); field = VN.numpy_to_vtk(tmp[0]); field.SetName('hMin'); fieldData.AddArray(field) tmp[1] = np.array([hMax], dtype = 'float32'); field = VN.numpy_to_vtk(tmp[1]); field.SetName('hMax'); fieldData.AddArray(field) tmp[2] = np.array([lMax], dtype = 'float32'); field = VN.numpy_to_vtk(tmp[2]); field.SetName('lMax'); fieldData.AddArray(field) tmp[3] = np.array([tol], dtype = 'float32'); field = VN.numpy_to_vtk(tmp[3]); field.SetName('tol'); fieldData.AddArray(field) tmp[4] = np.array([iterMax], dtype = 'int32'); field = VN.numpy_to_vtk(tmp[4]); field.SetName('iterMax'); fieldData.AddArray(field) tmp[5] = np.array([self.nt], dtype = 'int32'); field = VN.numpy_to_vtk(tmp[5]); field.SetName('nt'); fieldData.AddArray(field) # fields containing simulation parameters stored in paramFile dic = dir(p) params = range(len(dic)) i = 0 for attr in dic: if( attr[0] != '_'): params[i] = getattr(p, attr) params[i] = np.array([params[i]], dtype = type(params[i])) field = VN.numpy_to_vtk(params[i]) field.SetName(attr) fieldData.AddArray(field) i += 1 # all streamlines as continuous array of points points = vtk.vtkPoints() for i in range(xx.shape[1]): for sl in range(self.sl[i]): points.InsertNextPoint(self.tracers[i,sl,:]) polyData.SetPoints(points) polyData.SetFieldData(fieldData) writer.SetInput(polyData) writer.SetFileTypeToBinary() writer.Write()
# ====================================== # get the disk energy Int = 0 dInt = 1 Orbit = 3 KE_Sum = [] UE_Sum = [] UINT_Sum = [] while Int <= Orbit: ff = pc.read_var(trimall=True, ivar=Int, magic=["TT"]) TT = ff.TT rad = ff.x phi = ff.y uu = ff.uu ux = ff.ux uy = ff.uy rho = ff.rho i = 0 di = 1 j = 0 dj = 1 KE = [] UE = [] UINT = []
def interp_var( oldvar='var.dat', newvar='var.dat', source='old_run', target='new_run', source_path=None, target_path=None, xlim=None, ylim=None, zlim=None, xrepeat=1, yrepeat=1, zrepeat=1, time=None, deltay=None, arrs=None, innghosts=3, outghosts=3 ): """ load var file to be interpolated from old simulation and var file from started new simulation of correct shape and processor layout interpolate the old snapshot onto a mesh of the new shape and old grid limits then rescale new grid and deltay to new limits. """ if source_path==None: localdir=os.getcwd()+'/' if not os.path.exists(localdir+source): print('error: source_path must be specified as string') return os.chdir(localdir+source) print('loading data from '+localdir+source) fold=pc.read_var(oldvar,quiet=True) else: if not os.path.exists(source_path): print('error: source_path does not exist') return os.chdir(source_path) print('loading data from '+source_path) fold=pc.read_var(oldvar,quiet=True) if target_path==None: if not os.path.exists(localdir+target): print('error: target_path must be specified as string') return os.chdir(localdir+target) print('loading data from '+localdir+target) fnew=pc.read_var(newvar,quiet=True) else: if not os.path.exists(target_path): print('error: target_path does not exist') return os.chdir(target_path) print('loading data from '+target_path) fnew=pc.read_var(newvar,quiet=True) if xlim==None: xlim=[fold.x.min(),fold.x.max()] if ylim==None: ylim=[fold.y.min(),fold.y.max()] if zlim==None: zlim=[fold.z.min(),fold.z.max()] if arrs==None: arrs=['uu','rho','lnrho','ss','aa','shock','netheat','cooling'] iarr=0 x=np.linspace(xlim[0],xlim[1],fnew.x.size) y=np.linspace(ylim[0],ylim[1],fnew.y.size) z=np.linspace(zlim[0],zlim[1],fnew.z.size) for arr in arrs: if hasattr(fold,arr): print('interpolating '+arr) tmp = fold.__getattribute__(arr) if xrepeat == 1: intmpx = interp1d(fold.x,tmp,axis=-1) tmp = intmpx(x) if yrepeat == 1: intmpy = interp1d(fold.y,tmp,axis=-2) tmp=intmpy(y) if zrepeat == 1: intmpz = interp1d(fold.z,tmp,axis=-3) tmp = intmpz(z) fnew.__getattribute__(arr)[:] = tmp if len(tmp.shape)==4: fnew.f[iarr:iarr+3] = tmp iarr += 3 else: fnew.f[iarr] = tmp iarr += 1 if hasattr(fold,'deltay'): fnew.deltay = fold.deltay*(fnew.y.size-2*innghosts)/float( fold.y.size-2*outghosts) if not time==None: fnew.t=time return fnew