def perform_MMS_test(paths, extension='.pdf', show_plot=False): """Collects the data members belonging to a convergence plot""" # Make a variable to store the errors and the spacing data = {'error_2':[], 'error_inf':[], 'spacing':[]} # Loop over the runs in order to collect for path in paths: # Collect n_solution - n_numerical error_array = collect('E_n', path=path, info=False,\ xguards = False, yguards = False) # Pick the last time point error_array = error_array[-1] # The error in the 2-norm and infintiy-norm data['error_2'] .append( np.sqrt(np.mean( error_array**2.0 )) ) data['error_inf'].append( np.max(np.abs( error_array )) ) # Collect the spacings dx_spacing = collect("dx", path=path, info=False,\ xguards = False, yguards = False) dy_spacing = collect("dy", path=path, info=False,\ xguards = False, yguards = False) dz_spacing = collect("dz", path=path, info=False,\ xguards = False, yguards = False) # We are interested in the max of the spacing dx_spacing = np.max(dx_spacing) dy_spacing = np.max(dy_spacing) dz_spacing = np.max(dz_spacing) # Store the spacing in the data data['spacing'].append(np.max([dx_spacing, dy_spacing, dz_spacing])) # Sort the data data = sort_data(data) # Find the order of convergence in the 2 norm and infinity norm order_2, order_inf = get_order(data) # Get the root name of the path (used for saving files) root_folder = paths[0].split('/')[0] + '/' # Get the name of the plot based on the first folder name name = paths[0].split('/') # Remove the root folder and put 'MMS-' in front name = 'MMS-' + '_'.join(name[1:]) # Print the convergence rate print_convergence_rate(data, order_2, order_inf, root_folder, name) # Plot # We want to show the lines of the last orders, so we send in # order_2[-1] and order_inf[-1] do_plot(data, order_2[-1], order_inf[-1],\ root_folder, name, extension, show_plot)
def perform_MMS_test(paths, extension='.pdf', show_plot=False): """Collects the data members belonging to a convergence plot""" # Make a variable to store the errors and the spacing data = {'error_2': [], 'error_inf': [], 'spacing': []} # Loop over the runs in order to collect for path in paths: # Collect n_solution - n_numerical error_array = collect('E_n', path=path, info=False,\ xguards = False, yguards = False) # Pick the last time point error_array = error_array[-1] # The error in the 2-norm and infintiy-norm data['error_2'].append(np.sqrt(np.mean(error_array**2.0))) data['error_inf'].append(np.max(np.abs(error_array))) # Collect the spacings dx_spacing = collect("dx", path=path, info=False,\ xguards = False, yguards = False) dy_spacing = collect("dy", path=path, info=False,\ xguards = False, yguards = False) dz_spacing = collect("dz", path=path, info=False,\ xguards = False, yguards = False) # We are interested in the max of the spacing dx_spacing = np.max(dx_spacing) dy_spacing = np.max(dy_spacing) dz_spacing = np.max(dz_spacing) # Store the spacing in the data data['spacing'].append(np.max([dx_spacing, dy_spacing, dz_spacing])) # Sort the data data = sort_data(data) # Find the order of convergence in the 2 norm and infinity norm order_2, order_inf = get_order(data) # Get the root name of the path (used for saving files) root_folder = paths[0].split('/')[0] + '/' # Get the name of the plot based on the first folder name name = paths[0].split('/') # Remove the root folder and put 'MMS-' in front name = 'MMS-' + '_'.join(name[1:]) # Print the convergence rate print_convergence_rate(data, order_2, order_inf, root_folder, name) # Plot # We want to show the lines of the last orders, so we send in # order_2[-1] and order_inf[-1] do_plot(data, order_2[-1], order_inf[-1],\ root_folder, name, extension, show_plot)
def get_Isat(n, Pe, path='.'): qe = 1.602176634e-19 m_i = 1.672621898e-27 Te = np.divide(Pe, n) T0 = collect('Tnorm', path=path, info=False) n0 = collect('Nnorm', path=path, info=False) Isat = n * 0.49 * qe * np.sqrt((2 * qe * Te) / (m_i)) * 1e-3 J0 = n0 * 0.49 * qe * np.sqrt( (2 * qe * T0) / (m_i)) * 1e-3 #floor to subtract. return Isat - J0
def show_the_data(paths, t=None, x=None, y=None, z=None, **kwargs): """Function which plots the data. Parameters ---------- paths : tuple The paths of the runs t : slice The desired t slice of showdata x : slice The desired x slice of showdata y : slice The desired y slice of showdata z : slice The desired z slice of showdata **kwargs : key word arguments Not used here, but acts like a "dumpster" for additional keyword arguments """ for path in paths: print("Showing data from {}".format(path)) n = collect('n', xguards=False, yguards=False, path=path, info=False) # Show the data showdata(n[t,x,y,z])
def show_the_data(paths, t=None, x=None, y=None, z=None, **kwargs): """Function which plots the data. Parameters ---------- paths : tuple The paths of the runs t : slice The desired t slice of showdata x : slice The desired x slice of showdata y : slice The desired y slice of showdata z : slice The desired z slice of showdata **kwargs : key word arguments Not used here, but acts like a "dumpster" for additional keyword arguments """ for path in paths: print("Showing data from {}".format(path)) n = collect('n', xguards=False, yguards=False, path=path, info=False) # Show the data showdata(n[t, x, y, z])
def _collect(self, *args, **kwargs): """Wrapper for collect to pass self._DataFileCache if necessary. """ if self._DataFileCaching and self._DataFileCache is None: # Need to create the cache self._DataFileCache = create_cache(self._path, self._prefix) return collect(*args, datafile_cache=self._DataFileCache, **kwargs)
def pickleAll(self): for q_id in self.dat.list(): os.chdir(self.pickle_dir) if os.path.isfile(q_id) is True: continue os.chdir(self.out_dir) quant = collect(q_id) os.chdir(self.pickle_dir) pickle_on = open('{}'.format(q_id), 'wb') pickle.dump(quant, pickle_on, protocol=pickle.HIGHEST_PROTOCOL) pickle_on.close() print('########## pickled {}'.format(q_id))
def check_redistributed_data( expected, *, fieldperp_global_yind, path, ): """ Use `collect()` to read 'actual' data from the files. Test that 'actual' and 'expected' data and attributes match. Parameters ---------- expected : dict {str: numpy array} dict of expected data (key is name, value is scalar or numpy array of data). Arrays should be global (not per-process). fieldperp_global_yind : int Global y-index where FieldPerps are expected to be defined. path : pathlib.Path or str Path to collect data from. """ expected_different = ["MXSUB", "MYSUB", "NXPE", "NYPE"] for varname in expected: if varname in expected_different: # These variables are expected to be changed by restart.redistribute continue actual = collect(varname, path=path, prefix="BOUT.restart", xguards=False, yguards=False) npt.assert_array_equal(expected[varname], actual) actual_keys = list(actual.attributes.keys()) if varname in expected_attributes: for a in expected_attributes[varname]: assert actual.attributes[a] == expected_attributes[varname][a] actual_keys.remove(a) if "fieldperp" in varname: assert actual.attributes["yindex_global"] == fieldperp_global_yind actual_keys.remove("yindex_global") assert actual_keys == ["bout_type"] if "field3d" in varname: assert actual.attributes["bout_type"] == "Field3D" elif "field2d" in varname: assert actual.attributes["bout_type"] == "Field2D" elif "fieldperp" in varname: assert actual.attributes["bout_type"] == "FieldPerp" else: assert actual.attributes["bout_type"] == "scalar"
def show_the_data(path, t=None, x=None, y=None, z=None): """Function which plots the data. Input path - the path of a run t - the desired t slice of showdata x - the desired x slice of showdata y - the desired y slice of showdata z - the desired z slice of showdata """ print("Showing data from " + path) n = collect('n', xguards=False, yguards=False, path=path, info=False) # Show the data showdata(n[t, x, y, z])
def collectData(self, quant, simIndex=0, simType='1-base'): try: quant2 = np.squeeze(self.unPickle(quant, simIndex, simType)) except(FileNotFoundError): print('{} has not been pickled'.format(quant)) if simType == '1-base': os.chdir('{}/{}'.format(self.outDir, simIndex)) else: os.chdir('{}/{}/{}'.format(self.outDir, simIndex, simType)) try: quant2 = np.squeeze(collect(quant)) except(ValueError): print('quant in gridFile') self.gridFile = fnmatch.filter(next(os.walk('./'))[2], '*profile*')[0] grid_dat = DataFile(self.gridFile) quant2 = grid_dat[quant] return quant2
def saveData(self, quant, subDir=[]): ''' quant, subDirs: will always assume populated base directory ''' if len(subDir) == 0: subDirs = self.subDirs else: subDirs = [] for i in range(self.scanNum): subDirs.append(subDir) for i in range(self.scanNum): print('################# collecting for scanParam {}'.format( self.scanParams[i])) for j in range(-1, len(subDirs[i])): if j == -1: title = '1-base' else: title = subDirs[i][j] print('############## collecting for {}'.format(title)) for q_id in quant: os.chdir('{}/{}/{}'.format(self.pickleDir, i, title)) if os.path.isfile(q_id) is True: print('already pickled {}'.format(q_id)) continue if j == -1: os.chdir('{}/{}'.format(self.dataDir, i)) else: os.chdir('{}/{}/{}'.format(self.dataDir, i, title)) try: quant2 = collect(q_id) except(ValueError, KeyError, OSError): print('could not collect {}'.format(q_id)) continue os.chdir('{}/{}/{}'.format(self.pickleDir, i, title)) pickle_on = open('{}'.format(q_id), 'wb') pickle.dump(quant2, pickle_on) pickle_on.close() print('pickled {}'.format(q_id))
from __future__ import print_function from numpy import * from boutdata.collect import collect path='./data/' data=collect('P',path=path) print('Saving P..') fa=fft.fft(data,axis=3) save('fp',rollaxis(fa,0,4))
rcParams['font.size'] = 20. rcParams['legend.fontsize'] = 'small' rcParams['lines.linewidth'] = 2 if not os.path.exists('image'): os.makedirs('image') g = file_import('../cbm18_dens8.grid_nx68ny64.nc') psi = old_div((g['psixy'][:, 32] - g['psi_axis']), (g['psi_bndry'] - g['psi_axis'])) path = './data' plt.figure() #p0 = transpose(readsav(os.path.join(path, 'p0.idl.dat'))['p0']) p0=collect('P0', path=path) #dcp = transpose(readsav(os.path.join(path, 'dcp.idl.dat'))['dcp']) p=collect('P', path=path) res = moment_xyzt(p,'RMS','DC') rmsp = res.rms dcp = res.dc nt = dcp.shape[2] plt.plot(psi, p0[:, 32], 'k--', label='t=0') plt.plot(psi, p0[:, 32] + dcp[old_div(nt,4), :, 32], 'r-', label='t='+np.str(old_div(nt,4))) plt.plot(psi, p0[:, 32] + dcp[old_div(nt,2), :, 32], 'g-', label='t='+np.str(old_div(nt,2))) plt.plot(psi, p0[:, 32] + dcp[3*nt/4, :, 32], 'b-', label='t='+np.str(3*nt/4)) plt.plot(psi, p0[:, 32] + dcp[-1, :, 32], 'c-', label='t='+np.str(nt)) plt.legend()
g.grid_plane.axis = "x" mayavi.add_module(g) if __name__ == "__main__": from boutdata.collect import collect from boututils.file_import import file_import path = "/media/449db594-b2fe-4171-9e79-2d9b76ac69b6/runs/data_33/" # path="/home/ben/run4" # g = file_import("../cbm18_dens8.grid_nx68ny64.nc") g = file_import("data/cbm18_8_y064_x516_090309.nc") # g = file_import("/home/ben/run4/reduced_y064_x256.nc") data = collect("P", tind=50, path=path) data = data[0, :, :, :] s = np.shape(data) nz = s[2] bkgd = collect("P0", path=path) for z in range(nz): data[:, :, z] += bkgd # Create a structured grid sgrid = create_grid(g, data, 10) w = tvtk.XMLStructuredGridWriter(input=sgrid, file_name="sgrid.vts") w.write() # View the structured grid
for i in range(nt): s.mlab_source.scalars = d[i, :, :] if s1 is not None: s1.mlab_source.scalars = d[i, :, :] title = "t=" + np.string0(i) mlab.title(title, height=1.1, size=0.26) if save: mlab.savefig("Movie/anim%d.png" % i) yield if __name__ == "__main__": path = "../../../examples/elm-pb/data" data = collect("P", path=path) nt = data.shape[0] ns = data.shape[1] ne = data.shape[2] nz = data.shape[3] f = mlab.figure(size=(600, 600)) # Tell visual to use this as the viewer. visual.set_viewer(f) # First way s1 = contour_surf(data[0, :, :, 10] + 0.1, contours=30,
else: return vx, vz import numpy as np from boutdata.collect import collect import pickle data = 'data' if True: import sys if len(sys.argv) > 1: data = sys.argv[1] n = collect('n', path=data, info=False) vx, vy, xx, yy = blob_velocity(n[:, :, 0, :], type='COM', Index=True) f = open('Velocity.dat', 'wb') pickle.dump(vx, f) f.close() f = open('Position.dat', 'wb') pickle.dump(xx, f) f.close() f = open('Velocity.dat', 'rb') vx = pickle.load(f) f.close()
# real and imaginary components are weighted equally dist = ((eigs_r - event.xdata)/range_r)**2 + ((eigs_i - event.ydata)/range_i)**2 ind = argmin(dist) # Update the highlight plot overplot.set_data([eigs_r[ind]], [eigs_i[ind]]) print("Eigenvalue number: %d (%e,%e)" % (ind, eigs_r[ind], eigs_i[ind])) if data is not None: # Update plots nx = data.shape[1] vector_r.set_data(arange(nx), data[2*ind,:]) vector_i.set_data(arange(nx), data[2*ind+1,:]) ax2.relim() ax2.autoscale_view() fig.canvas.draw() cid = fig.canvas.mpl_connect('button_press_event', onclick) plt.show() if __name__ == "__main__": path = "data" eigs = collect("t_array", path=path) data = collect("f", path=path) plot_eigenvals(eigs, data=data[:,2:-2,0,0])
from boututils.calculus import deriv from mayavi import mlab path0="./data0/" path1="./data/" period=15 gfile='./cbm18_dens8.grid_nx68ny64.nc' g = file_import(gfile) Dphi0 = collect("Dphi0", path=path0) phi0 = collect("phi0", path=path1) # needs diamagnetic effects # psixy=g.get('psixy') PSI_AXIS=g.get('psi_axis') PSI_BNDRY=g.get('psi_bndry') # psix=old_div((psixy[:,32]-PSI_AXIS),(PSI_BNDRY-PSI_AXIS)) Epsi=-deriv(phi0[:,32],psix) # # fig=figure() plot(psix,-Dphi0[:,32], 'r', linewidth=5) plot(psix,Epsi,'k',linewidth=5) annotate('w/o flow', xy=(.3, .7), xycoords='axes fraction',horizontalalignment='center', verticalalignment='center', size=30) annotate('w/ flow', xy=(.7, .4), xycoords='axes fraction',horizontalalignment='center', verticalalignment='center', color='r', size=30)
def showdata(vars, titles=[], legendlabels = [], surf = [], polar = [], tslice = 0, movie = 0, intv = 1, Ncolors = 25, x = [], y = [], global_colors = False, symmetric_colors = False,hold_aspect=False): """ A Function to animate time dependent data from BOUT++ Requires numpy, mpl_toolkits, matplotlib, boutdata libaries. To animate multiple variables on different axes: showdata([var1, var2, var3]) To animate more than one line on a single axes: showdata([[var1, var2, var3]]) The default graph types are: 2D (time + 1 spatial dimension) arrays = animated line plot 3D (time + 2 spatial dimensions) arrays = animated contour plot. To use surface or polar plots: showdata(var, surf = 1) showdata(var, polar = 1) Can plot different graph types on different axes. Default graph types will be used depending on the dimensions of the input arrays. To specify polar/surface plots on different axes: showdata([var1,var2], surf = [1,0], polar = [0,1]) Movies require FFmpeg to be installed. The tslice variable is used to control the time value that is printed on each frame of the animation. If the input data matches the time values found within BOUT++'s dmp data files, then these time values will be used. Otherwise, an integer counter is used. During animation click once to stop in the current frame. Click again to continue. global_colors = True: if "vars" is a list the colorlevels are determined from the mximum of the maxima and and the minimum of the minima in all fields in vars. symmetric_colors = True: colorlevels are symmetric. """ plt.ioff() # Check to see whether vars is a list or not. if isinstance(vars, list): Nvar = len(vars) else: vars = [vars] Nvar = len(vars) if Nvar < 1: raise ValueError("No data supplied") # Check to see whether each variable is a list - used for line plots only Nlines = [] for i in range(0, Nvar): if isinstance(vars[i], list): Nlines.append(len(vars[i])) else: Nlines.append(1) vars[i] = [vars[i]] # Sort out titles if len(titles) == 0: for i in range(0,Nvar): titles.append(('Var' + str(i+1))) elif len(titles) != Nvar: raise ValueError('The length of the titles input list must match the length of the vars list.') # Sort out legend labels if len(legendlabels) == 0: for i in range(0,Nvar): legendlabels.append([]) for j in range(0,Nlines[i]): legendlabels[i].append(chr(97+j)) elif (isinstance(legendlabels[0], list) != 1): if Nvar != 1: check = 0 for i in range(0,Nvar): if len(legendlabels) != Nlines[i]: check = check+1 if check == 0: print("Warning, the legendlabels list does not contain a sublist for each variable, but it's length matches the number of lines on each plot. Will apply labels to each plot") legendlabelsdummy = [] for i in range(0, Nvar): legendlabelsdummy.append([]) for j in range(0,Nlines[i]): legendlabelsdummy[i].append(legendlabels[j]) legendlabels = legendlabelsdummy else: print("Warning, the legendlabels list does not contain a sublist for each variable, and it's length does not match the number of lines on each plot. Will default apply labels to each plot") legendlabels = [] for i in range(0,Nvar): legendlabels.append([]) for j in range(0,Nlines[i]): legendlabels[i].append(chr(97+j)) else: if (Nlines[0] == len(legendlabels)): legendlabels = [legendlabels] elif len(legendlabels) != Nvar: print("Warning, the length of the legendlabels list does not match the length of the vars list, will continue with default values") legendlabels = [] for i in range(0,Nvar): legendlabels.append([]) for j in range(0,Nlines[i]): legendlabels[i].append(chr(97+j)) else: for i in range(0,Nvar): if isinstance(legendlabels[i], list): if len(legendlabels[i]) != Nlines[i]: print('Warning, the length of the legendlabel (sub)list for each plot does not match the number of datasets for each plot. Will continue with default values') legendlabels[i] = [] for j in range(0,Nlines[i]): legendlabels[i].append(chr(97+j)) else: legendlabels[i] = [legendlabels[i]] if len(legendlabels[i]) != Nlines[i]: print('Warning, the length of the legendlabel (sub)list for each plot does not match the number of datasets for each plot. Will continue with default values') legendlabels[i] = [] for j in range(0,Nlines[i]): legendlabels[i].append(chr(97+j)) # Sort out surf list if isinstance(surf, list): if (len(surf) == Nvar): for i in range(0, Nvar): if surf[i] >= 1: surf[i] = 1 else: surf[i] = 0 elif (len(surf) == 1): if surf[0] >= 1: surf[0] = 1 else: surf[0] = 0 if (Nvar > 1): for i in range(1,Nvar): surf.append(surf[0]) elif (len(surf) == 0): for i in range(0,Nvar): surf.append(0) else: print('Warning, length of surf list does not match number of variables. Will default to no polar plots') for i in range(0,Nvar): surf.append(0) else: surf = [surf] if surf[0] >= 1: surf[0] = 1 else: surf[0] = 0 if (Nvar > 1): for i in range(1,Nvar): surf.append(surf[0]) # Sort out polar list if isinstance(polar, list): if (len(polar) == Nvar): for i in range(0, Nvar): if polar[i] >= 1: polar[i] = 1 else: polar[i] = 0 elif (len(polar) == 1): if polar[0] >= 1: polar[0] = 1 else: polar[0] = 0 if (Nvar > 1): for i in range(1,Nvar): polar.append(polar[0]) elif (len(polar) == 0): for i in range(0,Nvar): polar.append(0) else: print('Warning, length of polar list does not match number of variables. Will default to no polar plots') for i in range(0,Nvar): polar.append(0) else: polar = [polar] if polar[0] >= 1: polar[0] = 1 else: polar[0] = 0 if (Nvar > 1): for i in range(1,Nvar): polar.append(polar[0]) # Determine shapes of arrays dims = [] Ndims = [] lineplot = [] contour = [] for i in range(0,Nvar): dims.append([]) Ndims.append([]) for j in range(0, Nlines[i]): dims[i].append(array((vars[i][j].shape))) Ndims[i].append(dims[i][j].shape[0]) # Perform check to make sure that data is either 2D or 3D if (Ndims[i][j] < 2): raise ValueError('data must be either 2 or 3 dimensional. Exiting') if (Ndims[i][j] > 3): raise ValueError('data must be either 2 or 3 dimensional. Exiting') if ((Ndims[i][j] == 2) & (polar[i] != 0)): print('Warning, data must be 3 dimensional (time, r, theta) for polar plots. Will plot lineplot instead') if ((Ndims[i][j] == 2) & (surf[i] != 0)): print('Warning, data must be 3 dimensional (time, x, y) for surface plots. Will plot lineplot instead') if ((Ndims[i][j] == 3) & (Nlines[i] != 1)): raise ValueError('cannot have multiple sets of 3D (time + 2 spatial dimensions) on each subplot') if ((Ndims[i][j] != Ndims[i][0])): raise ValueError('Error, Number of dimensions must be the same for all variables on each plot.') if (Ndims[i][0] == 2): # Set polar and surf list entries to 0 polar[i] = 0 surf[i] = 0 lineplot.append(1) contour.append(0) else: if ((polar[i] == 1) & (surf[i] == 1)): print('Warning - cannot do polar and surface plots at the same time. Default to contour plot') contour.append(1) lineplot.append(0) polar[i] = 0 surf[i] = 0 elif (polar[i] == 1) | (surf[i] == 1): contour.append(0) lineplot.append(0) else: contour.append(1) lineplot.append(0) # Obtain size of data arrays Nt = [] Nx = [] Ny = [] for i in range(0, Nvar): Nt.append([]) Nx.append([]) Ny.append([]) for j in range(0, Nlines[i]): Nt[i].append(vars[i][j].shape[0]) Nx[i].append(vars[i][j].shape[1]) if (Nt[i][j] != Nt[0][0]): raise ValueError('time dimensions must be the same for all variables.') #if (Nx[i][j] != Nx[i][0]): # raise ValueError('Dimensions must be the same for all variables on each plot.') if (Ndims[i][j] == 3): Ny[i].append(vars[i][j].shape[2]) #if (Ny[i][j] != Ny[i][0]): # raise ValueError('Dimensions must be the same for all variables.') # Collect time data from file if (tslice == 0): # Only wish to collect time data if it matches try: t = collect('t_array') if t == None: raise ValueError("t_array is None") if len(t) != Nt[0][0]: raise ValueError("t_array is wrong size") except: t = linspace(0,Nt[0][0], Nt[0][0]) # Obtain number of frames Nframes = int(Nt[0][0]/intv) # Generate grids for plotting # Try to use provided grids where possible xnew = [] ynew = [] for i in range(0,Nvar): xnew.append([]) try: xnew[i].append(x[i]) except: for j in range(0, Nlines[i]): xnew[i].append(linspace(0,Nx[i][j]-1, Nx[i][j])) #x.append(linspace(0,Nx[i][0]-1, Nx[i][0])) if (Ndims[i][0] == 3): try: ynew.append(y[i]) except: ynew.append(linspace(0, Ny[i][0]-1, Ny[i][0])) else: ynew.append(0) x = xnew y = ynew # Determine range of data. Used to ensure constant colour map and # to set y scale of line plot. fmax = [] fmin = [] xmax = [] dummymax = [] dummymin = [] clevels = [] for i in range(0,Nvar): dummymax.append([]) dummymin.append([]) for j in range(0,Nlines[i]): dummymax[i].append(max(vars[i][j])) dummymin[i].append(min(vars[i][j])) fmax.append(max(dummymax[i])) fmin.append(min(dummymin[i])) if(symmetric_colors): absmax = max(abs(fmax[i]),abs(fmin[i])) fmax[i] = absmax fmin[i] = -absmax for j in range(0,Nlines[i]): dummymax[i][j] = max(x[i][j]) xmax.append(max(dummymax[i])) if not (global_colors): clevels.append(linspace(fmin[i], fmax[i], Ncolors)) if(global_colors): fmaxglobal = max(fmax) fminglobal = min(fmin) for i in range(0,Nvar): fmax[i] = fmaxglobal fmin[i] = fminglobal clevels.append(linspace(fmin[i], fmax[i], Ncolors)) # Create figures for animation plotting if (Nvar < 2): row = 1 col = 1 h = 6.0 w = 8.0 elif (Nvar <3): row = 1 col = 2 h = 6.0 w = 12.0 elif (Nvar < 5): row = 2 col = 2 h = 8.0 w = 12.0 elif (Nvar < 7): row = 2 col = 3 h = 8.0 w = 14.0 elif (Nvar < 10) : row = 3 col = 3 h = 12.0 w = 14.0 else: raise ValueError('too many variables...') fig = plt.figure(figsize=(w,h)) title = fig.suptitle(r' ', fontsize=14 ) # Initiate all list variables required for plotting here ax = [] lines = [] plots = [] cbars = [] xstride = [] ystride = [] r = [] theta = [] # Initiate figure frame for i in range(0,Nvar): lines.append([]) if (lineplot[i] == 1): ax.append(fig.add_subplot(row,col,i+1)) ax[i].set_xlim((0,xmax[i])) ax[i].set_ylim((fmin[i], fmax[i])) for j in range(0,Nlines[i]): lines[i].append(ax[i].plot([],[],lw=2, label = legendlabels[i][j])[0]) #Need the [0] to 'unpack' the line object from tuple. Alternatively: #lines[i], = lines[i] ax[i].set_xlabel(r'x') ax[i].set_ylabel(titles[i]) if (Nlines[i] != 1): legendneeded = 1 for k in range(0,i): if (Nlines[i] == Nlines[k]): legendneeded = 0 if (legendneeded == 1): plt.axes(ax[i]) plt.legend(loc = 0) # Pad out unused list variables with zeros plots.append(0) cbars.append(0) xstride.append(0) ystride.append(0) r.append(0) theta.append(0) elif (contour[i] == 1): ax.append(fig.add_subplot(row,col,i+1)) #ax[i].set_xlim((0,Nx[i][0]-1)) #ax[i].set_ylim((0,Ny[i][0]-1)) ax[i].set_xlim(min(x[i]),max(x[i])) ax[i].set_ylim(min(y[i]),max(y[i])) ax[i].set_xlabel(r'x') ax[i].set_ylabel(r'y') ax[i].set_title(titles[i]) if hold_aspect: ax[i].set_aspect('equal') plots.append(ax[i].contourf(x[i][0],y[i],vars[i][0][0,:,:].T, Ncolors, lw=0, levels=clevels[i] )) plt.axes(ax[i]) cbars.append(fig.colorbar(plots[i], format='%1.1e')) # Pad out unused list variables with zeros lines[i].append(0) xstride.append(0) ystride.append(0) r.append(0) theta.append(0) elif (surf[i] == 1): x[i][0],y[i] = meshgrid(x[i][0],y[i]) if (Nx[i][0]<= 20): xstride.append(1) else: xstride.append(int(floor(Nx[i][0]/20))) if (Ny[i][0]<=20): ystride.append(1) else: ystride.append(int(floor(Ny[i][0]/20))) ax.append(fig.add_subplot(row,col,i+1, projection='3d')) plots.append(ax[i].plot_wireframe(x[i][0], y[i], vars[i][0][0,:,:].T, rstride=ystride[i], cstride=xstride[i])) title = fig.suptitle(r'', fontsize=14 ) ax[i].set_xlabel(r'x') ax[i].set_ylabel(r'y') ax[i].set_zlabel(titles[i]) # Pad out unused list variables with zeros lines[i].append(0) cbars.append(0) r.append(0) theta.append(0) elif (polar[i] == 1): r.append(linspace(1,Nx[i][0], Nx[i][0])) theta.append(linspace(0,2*pi, Ny[i][0])) r[i],theta[i] = meshgrid(r[i], theta[i]) ax.append(fig.add_subplot(row,col,i+1, projection='polar')) plots.append(ax[i].contourf(theta[i], r[i], vars[i][0][0,:,:].T, levels=clevels[i])) plt.axes(ax[i]) cbars.append(fig.colorbar(plots[i], format='%1.1e')) ax[i].set_rmax(Nx[i][0]-1) ax[i].set_title(titles[i]) # Pad out unused list variables with zeros lines[i].append(0) xstride.append(0) ystride.append(0) def onClick(event): global pause pause ^= True def control(): global j, pause if j == Nframes-1 : j = -1 if not pause: j=j+1 return j # Animation function def animate(i): j=control() index = j*intv for j in range(0,Nvar): if (lineplot[j] == 1): for k in range(0,Nlines[j]): lines[j][k].set_data(x[j][k], vars[j][k][index,:]) elif (contour[j] == 1): plots[j] = ax[j].contourf(x[j][0],y[j],vars[j][0][index,:,:].T, Ncolors, lw=0, levels=clevels[j]) elif (surf[j] == 1): ax[j] = fig.add_subplot(row,col,j+1, projection='3d') plots[j] = ax[j].plot_wireframe(x[j][0], y[j], vars[j][0][index,:,:].T, rstride=ystride[j], cstride=xstride[j]) ax[j].set_zlim(fmin[j],fmax[j]) ax[j].set_xlabel(r'x') ax[j].set_ylabel(r'y') ax[j].set_title(titles[j]) elif (polar[j] == 1): plots[j] = ax[j].contourf(theta[j], r[j], vars[j][0][index,:,:].T, levels=clevels[j]) ax[j].set_rmax(Nx[j][0]-1) if (tslice == 0): title.set_text('t = %1.2e' % t[index]) else: title.set_text('t = %i' % index) return plots def init(): global j, pause j=-2 pause = False return animate(0) # Call Animation function fig.canvas.mpl_connect('button_press_event', onClick) anim = animation.FuncAnimation(fig, animate, init_func=init, frames=Nframes) # Save movie with given name if ((isinstance(movie,str)==1)): try: anim.save(movie+'.mp4',writer = FFwriter, fps=30, extra_args=['-vcodec', 'libx264']) except Exception: print("Save failed: Check ffmpeg path") # Save movie with default name if ((isinstance(movie,str)==0)): if (movie != 0): try: anim.save('animation.mp4',writer = FFwriter, fps=28, extra_args=['-vcodec', 'libx264']) except Exception: print("Save failed: Check ffmpeg path") # Show animation if (movie == 0): plt.show()
g.grid_plane.axis = 'x' mayavi.add_module(g) if __name__ == '__main__': from boutdata.collect import collect from boututils.file_import import file_import path = "/media/449db594-b2fe-4171-9e79-2d9b76ac69b6/runs/data_33/" #path="/home/ben/run4" #g = file_import("../cbm18_dens8.grid_nx68ny64.nc") g = file_import("data/cbm18_8_y064_x516_090309.nc") #g = file_import("/home/ben/run4/reduced_y064_x256.nc") data = collect("P", tind=50, path=path) data = data[0, :, :, :] s = np.shape(data) nz = s[2] bkgd = collect("P0", path=path) for z in range(nz): data[:, :, z] += bkgd # Create a structured grid sgrid = create_grid(g, data, 10) w = tvtk.XMLStructuredGridWriter(input=sgrid, file_name='sgrid.vts') w.write() # View the structured grid
def showdata(vars, titles=[], legendlabels=[], surf=[], polar=[], tslice=0, movie=0, intv=1, Ncolors=25, x=[], y=[], global_colors=False, symmetric_colors=False, hold_aspect=False): """ A Function to animate time dependent data from BOUT++ Requires numpy, mpl_toolkits, matplotlib, boutdata libaries. To animate multiple variables on different axes: showdata([var1, var2, var3]) To animate more than one line on a single axes: showdata([[var1, var2, var3]]) The default graph types are: 2D (time + 1 spatial dimension) arrays = animated line plot 3D (time + 2 spatial dimensions) arrays = animated contour plot. To use surface or polar plots: showdata(var, surf = 1) showdata(var, polar = 1) Can plot different graph types on different axes. Default graph types will be used depending on the dimensions of the input arrays. To specify polar/surface plots on different axes: showdata([var1,var2], surf = [1,0], polar = [0,1]) Movies require FFmpeg to be installed. The tslice variable is used to control the time value that is printed on each frame of the animation. If the input data matches the time values found within BOUT++'s dmp data files, then these time values will be used. Otherwise, an integer counter is used. During animation click once to stop in the current frame. Click again to continue. global_colors = True: if "vars" is a list the colorlevels are determined from the mximum of the maxima and and the minimum of the minima in all fields in vars. symmetric_colors = True: colorlevels are symmetric. """ plt.ioff() # Check to see whether vars is a list or not. if isinstance(vars, list): Nvar = len(vars) else: vars = [vars] Nvar = len(vars) if Nvar < 1: raise ValueError("No data supplied") # Check to see whether each variable is a list - used for line plots only Nlines = [] for i in range(0, Nvar): if isinstance(vars[i], list): Nlines.append(len(vars[i])) else: Nlines.append(1) vars[i] = [vars[i]] # Sort out titles if len(titles) == 0: for i in range(0, Nvar): titles.append(('Var' + str(i + 1))) elif len(titles) != Nvar: raise ValueError( 'The length of the titles input list must match the length of the vars list.' ) # Sort out legend labels if len(legendlabels) == 0: for i in range(0, Nvar): legendlabels.append([]) for j in range(0, Nlines[i]): legendlabels[i].append(chr(97 + j)) elif (isinstance(legendlabels[0], list) != 1): if Nvar != 1: check = 0 for i in range(0, Nvar): if len(legendlabels) != Nlines[i]: check = check + 1 if check == 0: print( "Warning, the legendlabels list does not contain a sublist for each variable, but it's length matches the number of lines on each plot. Will apply labels to each plot" ) legendlabelsdummy = [] for i in range(0, Nvar): legendlabelsdummy.append([]) for j in range(0, Nlines[i]): legendlabelsdummy[i].append(legendlabels[j]) legendlabels = legendlabelsdummy else: print( "Warning, the legendlabels list does not contain a sublist for each variable, and it's length does not match the number of lines on each plot. Will default apply labels to each plot" ) legendlabels = [] for i in range(0, Nvar): legendlabels.append([]) for j in range(0, Nlines[i]): legendlabels[i].append(chr(97 + j)) else: if (Nlines[0] == len(legendlabels)): legendlabels = [legendlabels] elif len(legendlabels) != Nvar: print( "Warning, the length of the legendlabels list does not match the length of the vars list, will continue with default values" ) legendlabels = [] for i in range(0, Nvar): legendlabels.append([]) for j in range(0, Nlines[i]): legendlabels[i].append(chr(97 + j)) else: for i in range(0, Nvar): if isinstance(legendlabels[i], list): if len(legendlabels[i]) != Nlines[i]: print( 'Warning, the length of the legendlabel (sub)list for each plot does not match the number of datasets for each plot. Will continue with default values' ) legendlabels[i] = [] for j in range(0, Nlines[i]): legendlabels[i].append(chr(97 + j)) else: legendlabels[i] = [legendlabels[i]] if len(legendlabels[i]) != Nlines[i]: print( 'Warning, the length of the legendlabel (sub)list for each plot does not match the number of datasets for each plot. Will continue with default values' ) legendlabels[i] = [] for j in range(0, Nlines[i]): legendlabels[i].append(chr(97 + j)) # Sort out surf list if isinstance(surf, list): if (len(surf) == Nvar): for i in range(0, Nvar): if surf[i] >= 1: surf[i] = 1 else: surf[i] = 0 elif (len(surf) == 1): if surf[0] >= 1: surf[0] = 1 else: surf[0] = 0 if (Nvar > 1): for i in range(1, Nvar): surf.append(surf[0]) elif (len(surf) == 0): for i in range(0, Nvar): surf.append(0) else: print( 'Warning, length of surf list does not match number of variables. Will default to no polar plots' ) for i in range(0, Nvar): surf.append(0) else: surf = [surf] if surf[0] >= 1: surf[0] = 1 else: surf[0] = 0 if (Nvar > 1): for i in range(1, Nvar): surf.append(surf[0]) # Sort out polar list if isinstance(polar, list): if (len(polar) == Nvar): for i in range(0, Nvar): if polar[i] >= 1: polar[i] = 1 else: polar[i] = 0 elif (len(polar) == 1): if polar[0] >= 1: polar[0] = 1 else: polar[0] = 0 if (Nvar > 1): for i in range(1, Nvar): polar.append(polar[0]) elif (len(polar) == 0): for i in range(0, Nvar): polar.append(0) else: print( 'Warning, length of polar list does not match number of variables. Will default to no polar plots' ) for i in range(0, Nvar): polar.append(0) else: polar = [polar] if polar[0] >= 1: polar[0] = 1 else: polar[0] = 0 if (Nvar > 1): for i in range(1, Nvar): polar.append(polar[0]) # Determine shapes of arrays dims = [] Ndims = [] lineplot = [] contour = [] for i in range(0, Nvar): dims.append([]) Ndims.append([]) for j in range(0, Nlines[i]): dims[i].append(array((vars[i][j].shape))) Ndims[i].append(dims[i][j].shape[0]) # Perform check to make sure that data is either 2D or 3D if (Ndims[i][j] < 2): raise ValueError( 'data must be either 2 or 3 dimensional. Exiting') if (Ndims[i][j] > 3): raise ValueError( 'data must be either 2 or 3 dimensional. Exiting') if ((Ndims[i][j] == 2) & (polar[i] != 0)): print( 'Warning, data must be 3 dimensional (time, r, theta) for polar plots. Will plot lineplot instead' ) if ((Ndims[i][j] == 2) & (surf[i] != 0)): print( 'Warning, data must be 3 dimensional (time, x, y) for surface plots. Will plot lineplot instead' ) if ((Ndims[i][j] == 3) & (Nlines[i] != 1)): raise ValueError( 'cannot have multiple sets of 3D (time + 2 spatial dimensions) on each subplot' ) if ((Ndims[i][j] != Ndims[i][0])): raise ValueError( 'Error, Number of dimensions must be the same for all variables on each plot.' ) if (Ndims[i][0] == 2): # Set polar and surf list entries to 0 polar[i] = 0 surf[i] = 0 lineplot.append(1) contour.append(0) else: if ((polar[i] == 1) & (surf[i] == 1)): print( 'Warning - cannot do polar and surface plots at the same time. Default to contour plot' ) contour.append(1) lineplot.append(0) polar[i] = 0 surf[i] = 0 elif (polar[i] == 1) | (surf[i] == 1): contour.append(0) lineplot.append(0) else: contour.append(1) lineplot.append(0) # Obtain size of data arrays Nt = [] Nx = [] Ny = [] for i in range(0, Nvar): Nt.append([]) Nx.append([]) Ny.append([]) for j in range(0, Nlines[i]): Nt[i].append(vars[i][j].shape[0]) Nx[i].append(vars[i][j].shape[1]) if (Nt[i][j] != Nt[0][0]): raise ValueError( 'time dimensions must be the same for all variables.') #if (Nx[i][j] != Nx[i][0]): # raise ValueError('Dimensions must be the same for all variables on each plot.') if (Ndims[i][j] == 3): Ny[i].append(vars[i][j].shape[2]) #if (Ny[i][j] != Ny[i][0]): # raise ValueError('Dimensions must be the same for all variables.') # Collect time data from file if (tslice == 0): # Only wish to collect time data if it matches try: t = collect('t_array') if t is None: raise ValueError("t_array is None") if len(t) != Nt[0][0]: raise ValueError("t_array is wrong size") except: t = linspace(0, Nt[0][0], Nt[0][0]) # Obtain number of frames Nframes = int(Nt[0][0] / intv) # Generate grids for plotting # Try to use provided grids where possible xnew = [] ynew = [] for i in range(0, Nvar): xnew.append([]) try: xnew[i].append(x[i]) except: for j in range(0, Nlines[i]): xnew[i].append(linspace(0, Nx[i][j] - 1, Nx[i][j])) #x.append(linspace(0,Nx[i][0]-1, Nx[i][0])) if (Ndims[i][0] == 3): try: ynew.append(y[i]) except: ynew.append(linspace(0, Ny[i][0] - 1, Ny[i][0])) else: ynew.append(0) x = xnew y = ynew # Determine range of data. Used to ensure constant colour map and # to set y scale of line plot. fmax = [] fmin = [] xmax = [] dummymax = [] dummymin = [] clevels = [] for i in range(0, Nvar): dummymax.append([]) dummymin.append([]) for j in range(0, Nlines[i]): dummymax[i].append(max(vars[i][j])) dummymin[i].append(min(vars[i][j])) fmax.append(max(dummymax[i])) fmin.append(min(dummymin[i])) if (symmetric_colors): absmax = max(abs(fmax[i]), abs(fmin[i])) fmax[i] = absmax fmin[i] = -absmax for j in range(0, Nlines[i]): dummymax[i][j] = max(x[i][j]) xmax.append(max(dummymax[i])) if not (global_colors): clevels.append(linspace(fmin[i], fmax[i], Ncolors)) if (global_colors): fmaxglobal = max(fmax) fminglobal = min(fmin) for i in range(0, Nvar): fmax[i] = fmaxglobal fmin[i] = fminglobal clevels.append(linspace(fmin[i], fmax[i], Ncolors)) # Create figures for animation plotting if (Nvar < 2): row = 1 col = 1 h = 6.0 w = 8.0 elif (Nvar < 3): row = 1 col = 2 h = 6.0 w = 12.0 elif (Nvar < 5): row = 2 col = 2 h = 8.0 w = 12.0 elif (Nvar < 7): row = 2 col = 3 h = 8.0 w = 14.0 elif (Nvar < 10): row = 3 col = 3 h = 12.0 w = 14.0 else: raise ValueError('too many variables...') fig = plt.figure(figsize=(w, h)) title = fig.suptitle(r' ', fontsize=14) # Initiate all list variables required for plotting here ax = [] lines = [] plots = [] cbars = [] xstride = [] ystride = [] r = [] theta = [] # Initiate figure frame for i in range(0, Nvar): lines.append([]) if (lineplot[i] == 1): ax.append(fig.add_subplot(row, col, i + 1)) ax[i].set_xlim((0, xmax[i])) ax[i].set_ylim((fmin[i], fmax[i])) for j in range(0, Nlines[i]): lines[i].append(ax[i].plot([], [], lw=2, label=legendlabels[i][j])[0]) #Need the [0] to 'unpack' the line object from tuple. Alternatively: #lines[i], = lines[i] ax[i].set_xlabel(r'x') ax[i].set_ylabel(titles[i]) if (Nlines[i] != 1): legendneeded = 1 for k in range(0, i): if (Nlines[i] == Nlines[k]): legendneeded = 0 if (legendneeded == 1): plt.axes(ax[i]) plt.legend(loc=0) # Pad out unused list variables with zeros plots.append(0) cbars.append(0) xstride.append(0) ystride.append(0) r.append(0) theta.append(0) elif (contour[i] == 1): ax.append(fig.add_subplot(row, col, i + 1)) #ax[i].set_xlim((0,Nx[i][0]-1)) #ax[i].set_ylim((0,Ny[i][0]-1)) ax[i].set_xlim(min(x[i]), max(x[i])) ax[i].set_ylim(min(y[i]), max(y[i])) ax[i].set_xlabel(r'x') ax[i].set_ylabel(r'y') ax[i].set_title(titles[i]) if hold_aspect: ax[i].set_aspect('equal') plots.append(ax[i].contourf(x[i][0], y[i], vars[i][0][0, :, :].T, Ncolors, lw=0, levels=clevels[i])) plt.axes(ax[i]) cbars.append(fig.colorbar(plots[i], format='%1.1e')) # Pad out unused list variables with zeros lines[i].append(0) xstride.append(0) ystride.append(0) r.append(0) theta.append(0) elif (surf[i] == 1): x[i][0], y[i] = meshgrid(x[i][0], y[i]) if (Nx[i][0] <= 20): xstride.append(1) else: xstride.append(int(floor(Nx[i][0] / 20))) if (Ny[i][0] <= 20): ystride.append(1) else: ystride.append(int(floor(Ny[i][0] / 20))) ax.append(fig.add_subplot(row, col, i + 1, projection='3d')) plots.append(ax[i].plot_wireframe(x[i][0], y[i], vars[i][0][0, :, :].T, rstride=ystride[i], cstride=xstride[i])) title = fig.suptitle(r'', fontsize=14) ax[i].set_xlabel(r'x') ax[i].set_ylabel(r'y') ax[i].set_zlabel(titles[i]) # Pad out unused list variables with zeros lines[i].append(0) cbars.append(0) r.append(0) theta.append(0) elif (polar[i] == 1): r.append(linspace(1, Nx[i][0], Nx[i][0])) theta.append(linspace(0, 2 * pi, Ny[i][0])) r[i], theta[i] = meshgrid(r[i], theta[i]) ax.append(fig.add_subplot(row, col, i + 1, projection='polar')) plots.append(ax[i].contourf(theta[i], r[i], vars[i][0][0, :, :].T, levels=clevels[i])) plt.axes(ax[i]) cbars.append(fig.colorbar(plots[i], format='%1.1e')) ax[i].set_rmax(Nx[i][0] - 1) ax[i].set_title(titles[i]) # Pad out unused list variables with zeros lines[i].append(0) xstride.append(0) ystride.append(0) def onClick(event): global pause pause ^= True def control(): global j, pause if j == Nframes - 1: j = -1 if not pause: j = j + 1 return j # Animation function def animate(i): j = control() index = j * intv for j in range(0, Nvar): if (lineplot[j] == 1): for k in range(0, Nlines[j]): lines[j][k].set_data(x[j][k], vars[j][k][index, :]) elif (contour[j] == 1): plots[j] = ax[j].contourf(x[j][0], y[j], vars[j][0][index, :, :].T, Ncolors, lw=0, levels=clevels[j]) elif (surf[j] == 1): ax[j] = fig.add_subplot(row, col, j + 1, projection='3d') plots[j] = ax[j].plot_wireframe(x[j][0], y[j], vars[j][0][index, :, :].T, rstride=ystride[j], cstride=xstride[j]) ax[j].set_zlim(fmin[j], fmax[j]) ax[j].set_xlabel(r'x') ax[j].set_ylabel(r'y') ax[j].set_title(titles[j]) elif (polar[j] == 1): plots[j] = ax[j].contourf(theta[j], r[j], vars[j][0][index, :, :].T, levels=clevels[j]) ax[j].set_rmax(Nx[j][0] - 1) if (tslice == 0): title.set_text('t = %1.2e' % t[index]) else: title.set_text('t = %i' % index) return plots def init(): global j, pause j = -2 pause = False return animate(0) # Call Animation function fig.canvas.mpl_connect('button_press_event', onClick) anim = animation.FuncAnimation(fig, animate, init_func=init, frames=Nframes) # Save movie with given name if ((isinstance(movie, str) == 1)): try: anim.save(movie + '.mp4', writer=FFwriter, fps=30, extra_args=['-vcodec', 'libx264']) except Exception: print("Save failed: Check ffmpeg path") # Save movie with default name if ((isinstance(movie, str) == 0)): if (movie != 0): try: anim.save('animation.mp4', writer=FFwriter, fps=28, extra_args=['-vcodec', 'libx264']) except Exception: print("Save failed: Check ffmpeg path") # Show animation if (movie == 0): plt.show()
elif len(argv) == 2: try: end_index = int(argv[1]) data_path = "data" except ValueError: end_index = -1 data_path = str(argv[1]) elif len(argv) == 3: end_index = int(argv[1]) data_path = str(argv[2]) else: print("Arguments: '[end_index] [data_path]' or 'gamma [data_path]'") Exit(1) # Collect the data Te = collect("T_electron", path=data_path, xind=2, info=True, yguards=True) Ti = collect("T_ion", path=data_path, xind=2, info=True, yguards=True) if end_index < 0: end_index = len(Te[:, 0, 0, 0]) Te_left = [] Ti_left = [] for i in range(end_index): Te_left.append(old_div((Te[i, 0, 2, 0] + Te[i, 0, 3, 0]), 2)) Ti_left.append(old_div((Ti[i, 0, 2, 0] + Ti[i, 0, 3, 0]), 2)) # Make plot if len(argv) > 2: pyplot.semilogx(Te_left[:end_index], 'r', Ti_left[:end_index], 'b') pyplot.title("Te (red) and Ti (blue) at the (left) boundary")
return -1. massunit = 1.602176565e-19 electron_mass = old_div(9.10938291e-31, massunit) electron_charge = -1.602176565e-19 ion_mass = old_div(3.34358348e-27, massunit) ion_charge = 1.602176565e-19 epsilon_0 = old_div(8.85418781762039e-12, pow(massunit, -1)) logLambda = 16.0 stagger = True t_interval = 10 # Collect the data Te = collect("T_electron", path="data", info=True, yguards=True) Ti = collect("T_ion", path="data", info=True, yguards=True) n = collect("n_ion", path="data", info=True, yguards=True) ylength = len(Te[0, 2, :, 0]) tlength = len(Te[:, 2, 0, 0]) try: dy = collect("dy", path="data", info=True, yguards=True) except TypeError: print("Warning, could not find dy, setting to 1.0") dy = [[1.] * ylength] * 5 try: g_22 = collect("g_22", path="data", info=True, yguards=True) except TypeError:
from builtins import str from builtins import range # Plot interpolating functions # Input generated by simple_test.py from numpy import linspace import matplotlib.pyplot as plt from boutdata.collect import collect f = collect("f", path="data") yup = collect("yup", path="data") ny = 20 nz = 8 # Note: yup[y=0] is never set y = linspace(-1, 1, ny-1) plt.plot(f[0,4,4,:], 'o', label="f") for z in range(nz): plt.plot(y+z, yup[4,1:,z], label="z = "+str(z)) plt.legend(loc='upper center') plt.savefig("plot_funcs.pdf") plt.show()
def redistribute(self, npes, nxpe=None, mxg=2, myg=2, include_restarts=True): """Create a new set of dump files for npes processors. Useful for restarting simulations using more or fewer processors. Existing data and restart files are kept in the directory "redistribution_backups". redistribute() will fail if this directory already exists, to avoid overwriting anything Parameters ---------- npes : int Number of new files to create nxpe : int, optional If nxpe is None (the default), then an 'optimal' number will be selected automatically mxg, myg : int, optional Number of guard cells in x, y (default: 2) include_restarts : bool, optional If True, then restart.redistribute will be used to redistribute the restart files also (default: True) """ from boutdata.processor_rearrange import get_processor_layout, create_processor_layout from os import rename, path, mkdir # use get_processor_layout to get nx, ny old_processor_layout = get_processor_layout( DataFile(self._file_list[0]), has_t_dimension=True, mxg=mxg, myg=myg) old_nxpe = old_processor_layout.nxpe old_nype = old_processor_layout.nype old_npes = old_processor_layout.npes old_mxsub = old_processor_layout.mxsub old_mysub = old_processor_layout.mysub nx = old_processor_layout.nx ny = old_processor_layout.ny mz = old_processor_layout.mz mxg = old_processor_layout.mxg myg = old_processor_layout.myg # calculate new processor layout new_processor_layout = create_processor_layout( old_processor_layout, npes, nxpe=nxpe) nxpe = new_processor_layout.nxpe nype = new_processor_layout.nype mxsub = new_processor_layout.mxsub mysub = new_processor_layout.mysub # move existing files to backup directory # don't overwrite backup: os.mkdir will raise exception if directory already exists backupdir = path.join(self._path, "redistribution_backups") mkdir(backupdir) for f in self._file_list: rename(f, path.join(backupdir, path.basename(f))) # create new output files outfile_list = [] this_prefix = self._prefix if not this_prefix[-1] == '.': # ensure prefix ends with a '.' this_prefix = this_prefix + "." for i in range(npes): outpath = os.path.join( self._path, this_prefix+str(i)+"."+self._suffix) if self._suffix.split(".")[-1] in ["nc", "ncdf", "cdl"]: # set format option to DataFile explicitly to avoid creating netCDF3 files, which can only contain up to 2GB of data outfile_list.append( DataFile(outpath, write=True, create=True, format='NETCDF4')) else: outfile_list.append(DataFile(outpath, write=True, create=True)) # Create a DataFileCache, if needed if self._DataFileCaching: DataFileCache = create_cache(backupdir, self._prefix) else: DataFileCache = None # read and write the data for v in self.varNames: print("processing "+v) data = collect(v, path=backupdir, prefix=self._prefix, xguards=True, yguards=True, info=False, datafile_cache=DataFileCache) ndims = len(data.shape) # write data for i in range(npes): ix = i % nxpe iy = int(i/nxpe) outfile = outfile_list[i] if v == "NPES": outfile.write(v, npes) elif v == "NXPE": outfile.write(v, nxpe) elif v == "NYPE": outfile.write(v, nype) elif v == "MXSUB": outfile.write(v, mxsub) elif v == "MYSUB": outfile.write(v, mysub) elif ndims == 0: # scalar outfile.write(v, data) elif ndims == 1: # time evolving scalar outfile.write(v, data) elif ndims == 2: # Field2D if data.shape != (nx + 2*mxg, ny + 2*myg): # FieldPerp? # check is not perfect, fails if ny=nz raise ValueError( "Error: Found FieldPerp '"+v+"'. This case is not currently handled by BoutOutputs.redistribute().") outfile.write( v, data[ix*mxsub:(ix+1)*mxsub+2*mxg, iy*mysub:(iy+1)*mysub+2*myg]) elif ndims == 3: # Field3D if data.shape[:2] != (nx + 2*mxg, ny + 2*myg): # evolving Field2D, but this case is not handled # check is not perfect, fails if ny=nx and nx=nt raise ValueError("Error: Found evolving Field2D '"+v + "'. This case is not currently handled by BoutOutputs.redistribute().") outfile.write( v, data[ix*mxsub:(ix+1)*mxsub+2*mxg, iy*mysub:(iy+1)*mysub+2*myg, :]) elif ndims == 4: outfile.write( v, data[:, ix*mxsub:(ix+1)*mxsub+2*mxg, iy*mysub:(iy+1)*mysub+2*myg, :]) else: print( "ERROR: variable found with unexpected number of dimensions,", ndims) for outfile in outfile_list: outfile.close() if include_restarts: print("processing restarts") from boutdata import restart from glob import glob restart_prefix = "BOUT.restart" restarts_list = glob(path.join(self._path, restart_prefix+"*")) # Move existing restart files to backup directory for f in restarts_list: rename(f, path.join(backupdir, path.basename(f))) # Redistribute restarts restart.redistribute(npes, path=backupdir, nxpe=nxpe, output=self._path, mxg=mxg, myg=myg)
from past.utils import old_div import numpy as np from boututils.file_import import file_import from boututils.surface_average import surface_average from boututils.showdata import showdata from boutdata.collect import collect from pylab import plot, show, annotate, xlabel, ylabel, figure, xlim, ylim, legend, gca import os path = './data' gfile = '../cbm18_dens8.grid_nx68ny64.nc' g = file_import(gfile) var = collect("P", path=path) sol = surface_average(var, g) #sol=np.mean(var,axis=3) p0av = collect("P0", path=path) q = np.zeros(sol.shape) for i in range(sol.shape[1]): q[:, i] = sol[:, i] + p0av[:, 0] psixy = g.get('psixy') psi0 = g.get('psi_axis') psix = g.get('psi_bndry')
from builtins import str from builtins import range # Plot interpolating functions # Input generated by simple_test.py from numpy import linspace import matplotlib.pyplot as plt from boutdata.collect import collect f = collect("f", path="data") yup = collect("yup", path="data") ny = 20 nz = 8 # Note: yup[y=0] is never set y = linspace(-1, 1, ny - 1) plt.plot(f[0, 4, 4, :], 'o', label="f") for z in range(nz): plt.plot(y + z, yup[4, 1:, z], label="z = " + str(z)) plt.legend(loc='upper center') plt.savefig("plot_funcs.pdf") plt.show()
from boututils.moment_xyzt import moment_xyzt from boututils.mode_structure import mode_structure from boututils.plotpolslice import plotpolslice from boututils.calculus import deriv from mayavi import mlab path0 = "./data0/" path1 = "./data/" period = 15 gfile = './cbm18_dens8.grid_nx68ny64.nc' g = file_import(gfile) Dphi0 = collect("Dphi0", path=path0) phi0 = collect("phi0", path=path1) # needs diamagnetic effects # psixy = g.get('psixy') PSI_AXIS = g.get('psi_axis') PSI_BNDRY = g.get('psi_bndry') # psix = old_div((psixy[:, 32] - PSI_AXIS), (PSI_BNDRY - PSI_AXIS)) Epsi = -deriv(phi0[:, 32], psix) # # fig = figure() plot(psix, -Dphi0[:, 32], 'r', linewidth=5) plot(psix, Epsi, 'k', linewidth=5) annotate('w/o flow', xy=(.3, .7),
else: return -1. massunit = 1.602176565e-19 electron_mass = old_div(9.10938291e-31,massunit) electron_charge = -1.602176565e-19 ion_mass = old_div(3.34358348e-27,massunit) ion_charge = 1.602176565e-19 epsilon_0 = old_div(8.85418781762039e-12,pow(massunit,-1)) logLambda = 16.0 stagger = True t_interval = 10 # Collect the data Te = collect("T_electron", path="data", info=True, yguards=True) Ti = collect("T_ion", path="data", info=True, yguards=True) n = collect("n_ion", path="data", info=True, yguards=True) ylength = len(Te[0,2,:,0]) tlength = len(Te[:,2,0,0]) try: dy = collect("dy", path="data", info=True, yguards=True) except TypeError: print("Warning, could not find dy, setting to 1.0") dy=[[1.]*ylength]*5 try: g_22 = collect("g_22", path="data", info=True, yguards=True) except TypeError: print("Warning, could not find g_22, setting to (80./256)^2") g_22=[[pow(old_div(80.,256),2)]*ylength]*5
if return_index: return vx,vz,x,z else: return vx,vz data='data' if True: import sys if len(sys.argv) > 1: data=sys.argv[1] n = collect('n', path=data, info=False) vx,vy,xx,yy = blob_velocity(n[:,:,0,:],type='COM',Index=True) f = open('Velocity.dat','wb') pickle.dump(vx,f) f.close() f = open('Position.dat','wb') pickle.dump(xx,f) f.close() f = open('Velocity.dat','rb') vx = pickle.load(f)
import matplotlib.pyplot as plt from boutdata.collect import collect f = collect("f", path="data") yup = collect("yup", path="data") ydown = collect("ydown", path="data") plt.plot(f[0,4,4,:], label="f") plt.plot(yup[4,4,:], label="f.yup") plt.plot(ydown[4,4,:], label="f.ydown") plt.legend() plt.savefig("plot_interp.pdf") plt.show()
from __future__ import print_function from numpy import * from boutdata.collect import collect path = './data/' data = collect('P', path=path) print('Saving P..') fa = fft.fft(data, axis=3) save('fp', rollaxis(fa, 0, 4))
t = 900 x_temp = g.get("Rxy") y_temp = g.get("Zxy") nx = g.get("nx") ny = g.get("ny") Ni_x = g.get("Ni_x") Ti_x = g.get("Ti_x") Te_x = g.get("Te_x") Vi_x = g.get("Vi_x") x = np.zeros((nx, ny)) y = np.zeros((nx, ny)) z = np.zeros((nx, ny)) z_temp = collect(var, path="./") z = z_temp[t, :, :, 0] * Te_x print(z_temp.shape) for i in np.arange(nx): for j in np.arange(ny): x[i, j] = x_temp[i, j] y[i, j] = y_temp[i, j] cmap = plt.get_cmap('jet') fig = plt.figure(figsize=(6, 12)) plt.contourf(x, y, z, cmap=cmap, antialiased=True) plt.colorbar()
# Program name: atomic1D/reference/build_json.py # Author: Thomas Body # Author email: [email protected] # Date of creation: 14 July 2017 # # # Makes data_dict and copies it into a .json file 'sd1d-case-05.json' filename = 'sd1d-case-05' from boutdata.collect import collect data_dict = {} # Normalisation factor for temperature - T * Tnorm returns in eV data_dict["Tnorm"] = collect("Tnorm") # Normalisation factor for density - N * Nnorm returns in m^-3 data_dict["Nnorm"] = collect("Nnorm") # Plasma pressure (normalised). Pe = 2 Ne Te => P/Ne = Te (and assume Ti=Te) data_dict["P"] = collect("P") # Electron density (normalised) data_dict["Ne"] = collect("Ne") # Neutral density (normalised) data_dict["Nn"] = collect("Nn") # Help for user data_dict[ "help"] = "Contains outputs from Boutprojects/SD1D/case-05 example. Created with data_dict_export.py - stored in Github.com/TBody/atomic1D/reference" from copy import deepcopy import numpy as np
from __future__ import division from builtins import range from past.utils import old_div from boutdata.collect import collect import numpy as np import matplotlib.pyplot as plt from boututils.file_import import file_import from matplotlib.ticker import FixedFormatter, FormatStrFormatter, AutoLocator, AutoMinorLocator #read grid data g = file_import('data/slab.grd.nc') x_temp = g.get("Rxy") y_temp = g.get("Zxy") #read simulation data z_temp = collect("Ni", path="data") nx = z_temp.shape[1] ny = z_temp.shape[2] time = 10 plot = "1d" fig = plt.figure(figsize=(9, 6), dpi=100) if plot == "2d": ax2d = fig.add_subplot(111, aspect='equal') x = np.zeros((nx, ny)) y = np.zeros((nx, ny)) z = z_temp[10, :, :]
# computes polslice for time series #################################### import numpy as np from boutdata.collect import collect from boututils.plotpolslice import plotpolslice ########################### # Specify parameters path='./data/' variable="P" p = collect(variable, path=path) period=15 grid='../cbm18_dens8.grid_nx68ny64.nc' ######################################################## # Call plotpolslice once to get extended poloidal grid r,z,fun=plotpolslice(p[0,:,:,:],grid,period=period,rz=1) nx=r.shape[0] # number of points in r ny=r.shape[1] # number of points in z nt=p.shape[0] # time intervals
def redistribute(self, npes, nxpe=None, mxg=2, myg=2, include_restarts=True): """Create a new set of dump files for npes processors. Useful for restarting simulations using more or fewer processors. Existing data and restart files are kept in the directory "redistribution_backups". redistribute() will fail if this directory already exists, to avoid overwriting anything Parameters ---------- npes : int Number of new files to create nxpe : int, optional If nxpe is None (the default), then an 'optimal' number will be selected automatically mxg, myg : int, optional Number of guard cells in x, y (default: 2) include_restarts : bool, optional If True, then restart.redistribute will be used to redistribute the restart files also (default: True) """ from boutdata.processor_rearrange import get_processor_layout, create_processor_layout from os import rename, path, mkdir # use get_processor_layout to get nx, ny old_processor_layout = get_processor_layout(DataFile( self._file_list[0]), has_t_dimension=True, mxg=mxg, myg=myg) old_nxpe = old_processor_layout.nxpe old_nype = old_processor_layout.nype old_npes = old_processor_layout.npes old_mxsub = old_processor_layout.mxsub old_mysub = old_processor_layout.mysub nx = old_processor_layout.nx ny = old_processor_layout.ny mz = old_processor_layout.mz mxg = old_processor_layout.mxg myg = old_processor_layout.myg # calculate new processor layout new_processor_layout = create_processor_layout(old_processor_layout, npes, nxpe=nxpe) nxpe = new_processor_layout.nxpe nype = new_processor_layout.nype mxsub = new_processor_layout.mxsub mysub = new_processor_layout.mysub # move existing files to backup directory # don't overwrite backup: os.mkdir will raise exception if directory already exists backupdir = path.join(self._path, "redistribution_backups") mkdir(backupdir) for f in self._file_list: rename(f, path.join(backupdir, path.basename(f))) # create new output files outfile_list = [] this_prefix = self._prefix if not this_prefix[-1] == '.': # ensure prefix ends with a '.' this_prefix = this_prefix + "." for i in range(npes): outpath = os.path.join(self._path, this_prefix + str(i) + "." + self._suffix) if self._suffix.split(".")[-1] in ["nc", "ncdf", "cdl"]: # set format option to DataFile explicitly to avoid creating netCDF3 files, which can only contain up to 2GB of data outfile_list.append( DataFile(outpath, write=True, create=True, format='NETCDF4')) else: outfile_list.append(DataFile(outpath, write=True, create=True)) # Create a DataFileCache, if needed if self._DataFileCaching: DataFileCache = create_cache(backupdir, self._prefix) else: DataFileCache = None # read and write the data for v in self.varNames: print("processing " + v) data = collect(v, path=backupdir, prefix=self._prefix, xguards=True, yguards=True, info=False, datafile_cache=DataFileCache) ndims = len(data.shape) # write data for i in range(npes): ix = i % nxpe iy = int(i / nxpe) outfile = outfile_list[i] if v == "NPES": outfile.write(v, npes) elif v == "NXPE": outfile.write(v, nxpe) elif v == "NYPE": outfile.write(v, nype) elif v == "MXSUB": outfile.write(v, mxsub) elif v == "MYSUB": outfile.write(v, mysub) elif ndims == 0: # scalar outfile.write(v, data) elif ndims == 1: # time evolving scalar outfile.write(v, data) elif ndims == 2: # Field2D if data.shape != (nx + 2 * mxg, ny + 2 * myg): # FieldPerp? # check is not perfect, fails if ny=nz raise ValueError( "Error: Found FieldPerp '" + v + "'. This case is not currently handled by BoutOutputs.redistribute()." ) outfile.write( v, data[ix * mxsub:(ix + 1) * mxsub + 2 * mxg, iy * mysub:(iy + 1) * mysub + 2 * myg]) elif ndims == 3: # Field3D if data.shape[:2] != (nx + 2 * mxg, ny + 2 * myg): # evolving Field2D, but this case is not handled # check is not perfect, fails if ny=nx and nx=nt raise ValueError( "Error: Found evolving Field2D '" + v + "'. This case is not currently handled by BoutOutputs.redistribute()." ) outfile.write( v, data[ix * mxsub:(ix + 1) * mxsub + 2 * mxg, iy * mysub:(iy + 1) * mysub + 2 * myg, :]) elif ndims == 4: outfile.write( v, data[:, ix * mxsub:(ix + 1) * mxsub + 2 * mxg, iy * mysub:(iy + 1) * mysub + 2 * myg, :]) else: print( "ERROR: variable found with unexpected number of dimensions,", ndims) for outfile in outfile_list: outfile.close() if include_restarts: print("processing restarts") from boutdata import restart from glob import glob restart_prefix = "BOUT.restart" restarts_list = glob(path.join(self._path, restart_prefix + "*")) # Move existing restart files to backup directory for f in restarts_list: rename(f, path.join(backupdir, path.basename(f))) # Redistribute restarts restart.redistribute(npes, path=backupdir, nxpe=nxpe, output=self._path, mxg=mxg, myg=myg)
def View3D(g, path=None, gb=None): ############################################################################## # Resolution n = 51 # compute Bxy [Br, Bz, x, y, q] = View2D(g, option=1) rd = g.r.max() + 0.5 zd = g.z.max() + 0.5 ############################################################################## # The grid of points on which we want to evaluate the field X, Y, Z = np.mgrid[-rd:rd:n * 1j, -rd:rd:n * 1j, -zd:zd:n * 1j] # # Avoid rounding issues : # f = 1e4 # this gives the precision we are interested by : # X = np.round(X * f) / f # Y = np.round(Y * f) / f # Z = np.round(Z * f) / f # r = np.c_[X.ravel(), Y.ravel(), Z.ravel()] ############################################################################## # Calculate field # First initialize a container matrix for the field vector : # B = np.empty_like(r) # Compute Toroidal field # fpol is given between simagx (psi on the axis) and sibdry ( # psi on limiter or separatrix). So the toroidal field (fpol/R) and the q profile # are within these boundaries # For each r,z we have psi thus we get fpol if (r,z) is within the boundary # (limiter or separatrix) and fpol=fpol(outer_boundary) for outside # The range of psi is g.psi.max(), g.psi.min() but we have f(psi) up to the limit. # Thus we use a new extended variable padded up to max psi # set points between psi_limit and psi_max add_psi = np.linspace(g.sibdry, g.psi.max(), 10) # define the x (psi) array xf = (np.arange(np.float(g.qpsi.size)) * (g.sibdry - g.simagx) / np.float(g.qpsi.size - 1) + g.simagx) # pad the extra values excluding the 1st value xf = np.concatenate((xf, add_psi[1::]), axis=0) # pad fpol with corresponding points fp = np.lib.pad(g.fpol, (0, 9), "edge") # create interpolating function f = interpolate.interp1d(xf, fp) # calculate Toroidal field Btrz = old_div(f(g.psi), g.r) rmin = g.r[:, 0].min() rmax = g.r[:, 0].max() zmin = g.z[0, :].min() zmax = g.z[0, :].max() B1p, B2p, B3p, B1t, B2t, B3t = magnetic_field(g, X, Y, Z, rmin, rmax, zmin, zmax, Br, Bz, Btrz) # bpnorm = np.sqrt(B1p ** 2 + B2p ** 2 + B3p ** 2) # btnorm = np.sqrt(B1t ** 2 + B2t ** 2 + B3t ** 2) BBx = B1p + B1t BBy = B2p + B2t BBz = B3p + B3t btotal = np.sqrt(BBx**2 + BBy**2 + BBz**2) Psi = psi_field(g, X, Y, Z, rmin, rmax, zmin, zmax) ############################################################################## # Visualization # We threshold the data ourselves, as the threshold filter produce a # data structure inefficient with IsoSurface # bmax = bnorm.max() # # B1[B > bmax] = 0 # B2[B > bmax] = 0 # B3[B > bmax] = 0 # bnorm[bnorm > bmax] = bmax mlab.figure(1, size=(1080, 1080)) # , bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5)) mlab.clf() # fieldp = mlab.pipeline.vector_field( # X, Y, Z, B1p, B2p, B3p, scalars=bpnorm, name="Bp field" # ) # # fieldt = mlab.pipeline.vector_field( # X, Y, Z, B1t, B2t, B3t, scalars=btnorm, name="Bt field" # ) field = mlab.pipeline.vector_field(X, Y, Z, BBx, BBy, BBz, scalars=btotal, name="B field") field2 = mlab.pipeline.scalar_field(X, Y, Z, Psi, name="Psi field") # vectors = mlab.pipeline.vectors(field, # scale_factor=1,#(X[1, 0, 0] - X[0, 0, 0]), # ) # vcp1 = mlab.pipeline.vector_cut_plane(fieldp, # scale_factor=1, # colormap='jet', # plane_orientation='y_axes') ## # vcp2 = mlab.pipeline.vector_cut_plane(fieldt, # scale_factor=1, # colormap='jet', # plane_orientation='x_axes') # Mask random points, to have a lighter visualization. # vectors.glyph.mask_input_points = True # vectors.glyph.mask_points.on_ratio = 6 # vcp = mlab.pipeline.vector_cut_plane(field1) # vcp.glyph.glyph.scale_factor=5*(X[1, 0, 0] - X[0, 0, 0]) # For prettier picture: # vcp1.implicit_plane.widget.enabled = False # vcp2.implicit_plane.widget.enabled = False iso = mlab.pipeline.iso_surface(field2, contours=[Psi.min() + 0.01], opacity=0.4, colormap="bone") for i in range(q.size): iso.contour.contours[i + 1:i + 2] = [q[i]] iso.compute_normals = True # # mlab.pipeline.image_plane_widget(field2, # plane_orientation='x_axes', # #slice_index=10, # extent=[-rd, rd, -rd, rd, -zd,zd] # ) # mlab.pipeline.image_plane_widget(field2, # plane_orientation='y_axes', # # slice_index=10, # extent=[-rd, rd, -rd,rd, -zd,zd] # ) # scp = mlab.pipeline.scalar_cut_plane(field2, # colormap='jet', # plane_orientation='x_axes') # For prettier picture and with 2D streamlines: # scp.implicit_plane.widget.enabled = False # scp.enable_contours = True # scp.contour.number_of_contours = 20 # # Magnetic Axis s = mlab.pipeline.streamline(field) s.streamline_type = "line" s.seed.widget = s.seed.widget_list[3] s.seed.widget.position = [g.rmagx, 0.0, g.zmagx] s.seed.widget.enabled = False # q=i surfaces for i in range(np.shape(x)[0]): s = mlab.pipeline.streamline(field) s.streamline_type = "line" # s.seed.widget = s.seed.widget_list[0] # s.seed.widget.center = 0.0, 0.0, 0.0 # s.seed.widget.radius = 1.725 # s.seed.widget.phi_resolution = 16 # s.seed.widget.handle_direction =[ 1., 0., 0.] # s.seed.widget.enabled = False # s.seed.widget.enabled = True # s.seed.widget.enabled = False # if x[i].size > 1: s.seed.widget = s.seed.widget_list[3] s.seed.widget.position = [x[i][0], 0.0, y[i][0]] s.seed.widget.enabled = False # A trick to make transparency look better: cull the front face iso.actor.property.frontface_culling = True # mlab.view(39, 74, 0.59, [.008, .0007, -.005]) out = mlab.outline(extent=[-rd, rd, -rd, rd, -zd, zd], line_width=0.5) out.outline_mode = "cornered" out.outline_filter.corner_factor = 0.0897222 w = mlab.gcf() w.scene.camera.position = [ 13.296429046581462, 13.296429046581462, 12.979811259697154, ] w.scene.camera.focal_point = [0.0, 0.0, -0.31661778688430786] w.scene.camera.view_angle = 30.0 w.scene.camera.view_up = [0.0, 0.0, 1.0] w.scene.camera.clipping_range = [13.220595435695394, 35.020427055647517] w.scene.camera.compute_view_plane_normal() w.scene.render() w.scene.show_axes = True mlab.show() if path is not None: # BOUT data # path='../Aiba/' # # gb = file_import(path+'aiba.bout.grd.nc') # gb = file_import("../cbm18_8_y064_x516_090309.nc") # gb = file_import("cbm18_dens8.grid_nx68ny64.nc") # gb = file_import("/home/ben/run4/reduced_y064_x256.nc") data = collect("P", path=path) data = data[50, :, :, :] # data0=collect("P0", path=path) # data=data+data0[:,:,None] s = np.shape(data) # nz = s[2] sgrid = create_grid(gb, data, 1) # OVERPLOT the GRID # mlab.pipeline.add_dataset(sgrid) # gr=mlab.pipeline.grid_plane(sgrid) # gr.grid_plane.axis='x' # pressure scalar cut plane from bout scpb = mlab.pipeline.scalar_cut_plane(sgrid, colormap="jet", plane_orientation="x_axes") scpb.implicit_plane.widget.enabled = False scpb.enable_contours = True scpb.contour.filled_contours = True # scpb.contour.number_of_contours = 20 # # # loc=sgrid.points # p=sgrid.point_data.scalars # compute pressure from scatter points interpolation # pint=interpolate.griddata(loc, p, (X, Y, Z), method='linear') # dpint=np.ma.masked_array(pint,np.isnan(pint)).filled(0.) # # p2 = mlab.pipeline.scalar_field(X, Y, Z, dpint, name='P field') # # scp2 = mlab.pipeline.scalar_cut_plane(p2, # colormap='jet', # plane_orientation='y_axes') # # scp2.implicit_plane.widget.enabled = False # scp2.enable_contours = True # scp2.contour.filled_contours=True # scp2.contour.number_of_contours = 20 # scp2.contour.minimum_contour=.001 # CHECK grid orientation # fieldr = mlab.pipeline.vector_field(X, Y, Z, -BBx, BBy, BBz, # scalars=btotal, name='B field') # # sg=mlab.pipeline.streamline(fieldr) # sg.streamline_type = 'tube' # sg.seed.widget = sg.seed.widget_list[3] # sg.seed.widget.position=loc[0] # sg.seed.widget.enabled = False # OUTPUT grid # ww = tvtk.XMLStructuredGridWriter(input=sgrid, file_name='sgrid.vts') # ww.write() return
from __future__ import print_function from __future__ import division from builtins import range from past.utils import old_div ### # computes average growth rate for all points at the final timestep # computes average growth rate for points in the mead plane at the final timestep ### import numpy as np from boutdata.collect import collect from boututils.moment_xyzt import moment_xyzt path='./data/' p=collect('P',path=path) nmpy=old_div(p.shape[2],2) # define mead plane ik = 50 # disregard the first ik timesteps def gr(p): rmsp_f=moment_xyzt(p, 'RMS').rms ni=np.shape(rmsp_f)[1] nj=np.shape(rmsp_f)[2] growth=np.zeros((ni,nj)) for i in range(ni): for j in range(nj): growth[i,j]=np.gradient(np.log(rmsp_f[ik::,i,j]))[-1]
g = GridPlane() g.grid_plane.axis = 'x' e.add_module(g) if __name__ == '__main__': from boutdata.collect import collect from boututils.file_import import file_import #path = "/media/449db594-b2fe-4171-9e79-2d9b76ac69b6/runs/data_33/" path="../data" g = file_import("../bout.grd.nc") #g = file_import("../cbm18_8_y064_x516_090309.nc") #g = file_import("/home/ben/run4/reduced_y064_x256.nc") data = collect("P", tind=10, path=path) data = data[0,:,:,:] s = np.shape(data) nz = s[2] #bkgd = collect("P0", path=path) #for z in range(nz): # data[:,:,z] += bkgd # Create a structured grid sgrid = create_grid(g, data, 1) w = tvtk.XMLStructuredGridWriter(input=sgrid, file_name='sgrid.vts') w.write()
from boutdata.collect import collect from boututils.moment_xyzt import moment_xyzt from boututils.file_import import file_import from pylab import save, figure, plot, title, xlabel, ylabel, show, tight_layout from elm_size import elm_size path='./data' t_array=collect('t_array', path=path) save('t_array.dat', t_array) p0=collect('P0', path=path) save('p0.dat', p0) # n0=collect('n0', path=path) # save('n0.dat', n0 # ti0=collect('ti0', path=path) # save('ti0.dat', ti0) # te0=collect('te0', path=path) # save('te0.idl.dat', te0) gfile=file_import('./cbm18_dens8.grid_nx68ny64.nc') p=collect('P', path=path) save('p.dat', p) res=moment_xyzt(p,'RMS','DC') rmsp=res.rms dcp=res.dc save('rmsp.dat', rmsp) save('dcp.dat', dcp) elmsp=elm_size(dcp,p0,gfile,yind=32,Bbar=gfile['bmag'])
import numpy as np from boututils.file_import import file_import from boututils.surface_average import surface_average from boututils.showdata import showdata from boutdata.collect import collect from pylab import plot, show, annotate, xlabel, ylabel, figure, xlim, ylim, legend, gca import os path='./data' gfile='../cbm18_dens8.grid_nx68ny64.nc' g = file_import(gfile) var=collect("P", path=path) sol=surface_average(var, g) #sol=np.mean(var,axis=3) p0av=collect("P0", path=path) q=np.zeros(sol.shape) for i in range(sol.shape[1]): q[:,i]=sol[:,i]+p0av[:,0] psixy=g.get('psixy') psi0=g.get('psi_axis') psix=g.get('psi_bndry')
# reduce time-step. At large times these cases produce noise timestep = 1e3 # Delete old output files shell("rm data/BOUT.dmp.*.nc") print("Running drift instability test, zeff = ", zeff) # Run the case s, out = launch_safe("./2fluid timestep="+str(timestep), runcmd=MPIRUN, nproc=nproc, mthread=nthreads, pipe=True) f = open("run.log."+str(zeff), "w") f.write(out) f.close() # Collect data Ni = collect("Ni", path="data", xind=2, yind=20, info=False) phi = collect("phi", path="data", xind=2, yind=20, info=False) zmax = collect("ZMAX", path="data", info=False) rho_s = collect("rho_s", path="data", info=False) wci = collect("wci", path="data", info=False) t_array = collect("t_array", path="data", info=False) dims = np.shape(Ni) nt = dims[0] ny = dims[2] nz = dims[3] ##### Calculate geometric and physical quantities lZeta = 1e2*zmax*2*np.pi*grid['R0'] # toroidal range [cm] lbNorm = lZeta*(grid['Bpxy'][0, ny // 2] / grid['Bxy'][0, ny // 2]) # binormal coord range [cm]
import numpy as np from sys import argv from math import sqrt, log10, log, pi from matplotlib import pyplot gamma = 3. if len(argv)>1: data_path = str(argv[1]) else: data_path = "data" electron_mass = 9.10938291e-31 ion_mass = 3.34358348e-27 # Collect the data Te = collect("T_electron", path=data_path, info=True, yguards=True) Ti = collect("T_ion", path=data_path, info=True, yguards=True) n = collect("n_ion", path=data_path, info=True, yguards=True) V = collect("Vpar_ion", path=data_path, info=True, yguards=True) q = collect("heat_flux", path=data_path, info=True, yguards=True) q_electron_left = [] q_electron_right = [] right_index = len(Te[0,2,:,0])-4 for i in range(len(Te[:,2,0,0])): Te_left = old_div((Te[i,2,2,0]+Te[i,2,1,0]),2.) Ti_left = old_div((Ti[i,2,2,0]+Ti[i,2,1,0]),2.) n_left = old_div((n[i,2,2,0]+n[i,2,1,0]),2.) Te_right = old_div((Te[i,2,right_index,0]+Te[i,2,right_index+1,0]),2) Ti_right = old_div((Ti[i,2,right_index,0]+Ti[i,2,right_index+1,0]),2)
from __future__ import print_function from boututils.file_import import file_import from boututils.volume_integral import volume_integral from boutdata.collect import collect # Integrate over a volume path = "./data/" gfile = "./cbm18_dens8.grid_nx68ny64.nc" g = file_import(gfile) var = collect("P", path=path) sol = volume_integral(var, g) print(sol)
data_path = "data" except ValueError: end_index = -1 data_path = str(argv[2]) elif len(argv)==4: end_index = int(argv[2]) data_path = str(argv[3]) else: print("Arguments: 'gamma [end_index] [data_path]' or 'gamma [data_path]'") Exit(1) electron_mass = 9.10938291e-31 ion_mass = 3.34358348e-27 # Collect the data Te = collect("T_electron", path=data_path, info=True, yguards=True) Ti = collect("T_ion", path=data_path, info=True, yguards=True) n = collect("n_ion", path=data_path, info=True, yguards=True) if end_index<0: end_index = len(n[:,0,0,0]) logtime = [] q_electron_left = [] q_electron_right = [] q_ion_left = [] q_ion_right = [] q_total_left = [] q_total_right = [] q_target_electron_left = [] q_target_electron_right = []
elif len(argv)==2: try: end_index = int(argv[1]) data_path = "data" except ValueError: end_index = -1 data_path = str(argv[1]) elif len(argv)==3: end_index = int(argv[1]) data_path = str(argv[2]) else: print("Arguments: '[end_index] [data_path]' or 'gamma [data_path]'") Exit(1) # Collect the data Te = collect("T_electron", path=data_path, xind=2, info=True, yguards=True) Ti = collect("T_ion", path=data_path, xind=2, info=True, yguards=True) if end_index<0: end_index = len(Te[:,0,0,0]) Te_left = [] Ti_left = [] for i in range(end_index): Te_left.append(old_div((Te[i,0,2,0]+Te[i,0,3,0]),2)) Ti_left.append(old_div((Ti[i,0,2,0]+Ti[i,0,3,0]),2)) # Make plot if len(argv)>2: pyplot.semilogx(Te_left[:end_index],'r',Ti_left[:end_index],'b') pyplot.title("Te (red) and Ti (blue) at the (left) boundary")
rcParams['font.size'] = 20. rcParams['legend.fontsize'] = 'small' rcParams['lines.linewidth'] = 2 if not os.path.exists('image'): os.makedirs('image') g = file_import('../cbm18_dens8.grid_nx68ny64.nc') psi = old_div((g['psixy'][:, 32] - g['psi_axis']), (g['psi_bndry'] - g['psi_axis'])) path = './data' plt.figure() p0 = collect('P0', path=path) p = collect('P', path=path) res = moment_xyzt(p, 'RMS', 'DC') rmsp = res.rms dcp = res.dc nt = dcp.shape[2] plt.plot(psi, p0[:, 32], 'k--', label='t=0') plt.plot(psi, p0[:, 32] + dcp[old_div(nt, 4), :, 32], 'r-', label='t=' + np.str(old_div(nt, 4))) plt.plot(psi, p0[:, 32] + dcp[old_div(nt, 2), :, 32], 'g-',
def View3D(g,path=None, gb=None): ############################################################################## # Resolution n=51 #compute Bxy [Br,Bz,x,y,q]=View2D(g,option=1) rd=g.r.max()+.5 zd=g.z.max()+.5 ############################################################################## # The grid of points on which we want to evaluate the field X, Y, Z = np.mgrid[-rd:rd:n*1j, -rd:rd:n*1j, -zd:zd:n*1j] ## Avoid rounding issues : #f = 1e4 # this gives the precision we are interested by : #X = np.round(X * f) / f #Y = np.round(Y * f) / f #Z = np.round(Z * f) / f r = np.c_[X.ravel(), Y.ravel(), Z.ravel()] ############################################################################## # Calculate field # First initialize a container matrix for the field vector : B = np.empty_like(r) #Compute Toroidal field # fpol is given between simagx (psi on the axis) and sibdry ( # psi on limiter or separatrix). So the toroidal field (fpol/R) and the q profile are within these boundaries # For each r,z we have psi thus we get fpol if (r,z) is within the boundary (limiter or separatrix) and fpol=fpol(outer_boundary) for outside #The range of psi is g.psi.max(), g.psi.min() but we have f(psi) up to the limit. Thus we use a new extended variable padded up to max psi # set points between psi_limit and psi_max add_psi=np.linspace(g.sibdry,g.psi.max(),10) # define the x (psi) array xf=np.arange(np.float(g.qpsi.size))*(g.sibdry-g.simagx)/np.float(g.qpsi.size-1) + g.simagx # pad the extra values excluding the 1st value xf=np.concatenate((xf, add_psi[1::]), axis=0) # pad fpol with corresponding points fp=np.lib.pad(g.fpol, (0,9), 'edge') # create interpolating function f = interpolate.interp1d(xf, fp) #calculate Toroidal field Btrz = old_div(f(g.psi), g.r) rmin=g.r[:,0].min() rmax=g.r[:,0].max() zmin=g.z[0,:].min() zmax=g.z[0,:].max() B1p,B2p,B3p,B1t,B2t,B3t = magnetic_field(g,X,Y,Z,rmin,rmax,zmin,zmax, Br,Bz,Btrz) bpnorm = np.sqrt(B1p**2 + B2p**2 + B3p**2) btnorm = np.sqrt(B1t**2 + B2t**2 + B3t**2) BBx=B1p+B1t BBy=B2p+B2t BBz=B3p+B3t btotal = np.sqrt(BBx**2 + BBy**2 + BBz**2) Psi = psi_field(g,X,Y,Z,rmin,rmax,zmin,zmax) ############################################################################## # Visualization # We threshold the data ourselves, as the threshold filter produce a # data structure inefficient with IsoSurface #bmax = bnorm.max() # #B1[B > bmax] = 0 #B2[B > bmax] = 0 #B3[B > bmax] = 0 #bnorm[bnorm > bmax] = bmax mlab.figure(1, size=(1080,1080))#, bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5)) mlab.clf() fieldp = mlab.pipeline.vector_field(X, Y, Z, B1p, B2p, B3p, scalars=bpnorm, name='Bp field') fieldt = mlab.pipeline.vector_field(X, Y, Z, B1t, B2t, B3t, scalars=btnorm, name='Bt field') field = mlab.pipeline.vector_field(X, Y, Z, BBx, BBy, BBz, scalars=btotal, name='B field') field2 = mlab.pipeline.scalar_field(X, Y, Z, Psi, name='Psi field') #vectors = mlab.pipeline.vectors(field, # scale_factor=1,#(X[1, 0, 0] - X[0, 0, 0]), # ) #vcp1 = mlab.pipeline.vector_cut_plane(fieldp, # scale_factor=1, # colormap='jet', # plane_orientation='y_axes') ## #vcp2 = mlab.pipeline.vector_cut_plane(fieldt, # scale_factor=1, # colormap='jet', # plane_orientation='x_axes') # Mask random points, to have a lighter visualization. #vectors.glyph.mask_input_points = True #vectors.glyph.mask_points.on_ratio = 6 #vcp = mlab.pipeline.vector_cut_plane(field1) #vcp.glyph.glyph.scale_factor=5*(X[1, 0, 0] - X[0, 0, 0]) # For prettier picture: #vcp1.implicit_plane.widget.enabled = False #vcp2.implicit_plane.widget.enabled = False iso = mlab.pipeline.iso_surface(field2, contours=[Psi.min()+.01], opacity=0.4, colormap='bone') for i in range(q.size): iso.contour.contours[i+1:i+2]=[q[i]] iso.compute_normals = True # #mlab.pipeline.image_plane_widget(field2, # plane_orientation='x_axes', # #slice_index=10, # extent=[-rd, rd, -rd, rd, -zd,zd] # ) #mlab.pipeline.image_plane_widget(field2, # plane_orientation='y_axes', # # slice_index=10, # extent=[-rd, rd, -rd,rd, -zd,zd] # ) #scp = mlab.pipeline.scalar_cut_plane(field2, # colormap='jet', # plane_orientation='x_axes') # For prettier picture and with 2D streamlines: #scp.implicit_plane.widget.enabled = False #scp.enable_contours = True #scp.contour.number_of_contours = 20 # # Magnetic Axis s=mlab.pipeline.streamline(field) s.streamline_type = 'line' s.seed.widget = s.seed.widget_list[3] s.seed.widget.position=[g.rmagx,0.,g.zmagx] s.seed.widget.enabled = False # q=i surfaces for i in range(np.shape(x)[0]): s=mlab.pipeline.streamline(field) s.streamline_type = 'line' ##s.seed.widget = s.seed.widget_list[0] ##s.seed.widget.center = 0.0, 0.0, 0.0 ##s.seed.widget.radius = 1.725 ##s.seed.widget.phi_resolution = 16 ##s.seed.widget.handle_direction =[ 1., 0., 0.] ##s.seed.widget.enabled = False ##s.seed.widget.enabled = True ##s.seed.widget.enabled = False # if x[i].size>1 : s.seed.widget = s.seed.widget_list[3] s.seed.widget.position=[x[i][0],0.,y[i][0]] s.seed.widget.enabled = False # A trick to make transparency look better: cull the front face iso.actor.property.frontface_culling = True #mlab.view(39, 74, 0.59, [.008, .0007, -.005]) out=mlab.outline(extent=[-rd, rd, -rd, rd, -zd, zd], line_width=.5 ) out.outline_mode = 'cornered' out.outline_filter.corner_factor = 0.0897222 w = mlab.gcf() w.scene.camera.position = [13.296429046581462, 13.296429046581462, 12.979811259697154] w.scene.camera.focal_point = [0.0, 0.0, -0.31661778688430786] w.scene.camera.view_angle = 30.0 w.scene.camera.view_up = [0.0, 0.0, 1.0] w.scene.camera.clipping_range = [13.220595435695394, 35.020427055647517] w.scene.camera.compute_view_plane_normal() w.scene.render() w.scene.show_axes = True mlab.show() if(path != None): #BOUT data #path='../Aiba/' # #gb = file_import(path+'aiba.bout.grd.nc') #gb = file_import("../cbm18_8_y064_x516_090309.nc") #gb = file_import("cbm18_dens8.grid_nx68ny64.nc") #gb = file_import("/home/ben/run4/reduced_y064_x256.nc") data = collect('P', path=path) data = data[50,:,:,:] #data0=collect("P0", path=path) #data=data+data0[:,:,None] s = np.shape(data) nz = s[2] sgrid = create_grid(gb, data, 1) # OVERPLOT the GRID #mlab.pipeline.add_dataset(sgrid) #gr=mlab.pipeline.grid_plane(sgrid) #gr.grid_plane.axis='x' ## pressure scalar cut plane from bout scpb = mlab.pipeline.scalar_cut_plane(sgrid, colormap='jet', plane_orientation='x_axes') scpb.implicit_plane.widget.enabled = False scpb.enable_contours = True scpb.contour.filled_contours=True # scpb.contour.number_of_contours = 20 # # #loc=sgrid.points #p=sgrid.point_data.scalars # compute pressure from scatter points interpolation #pint=interpolate.griddata(loc, p, (X, Y, Z), method='linear') #dpint=np.ma.masked_array(pint,np.isnan(pint)).filled(0.) # #p2 = mlab.pipeline.scalar_field(X, Y, Z, dpint, name='P field') # #scp2 = mlab.pipeline.scalar_cut_plane(p2, # colormap='jet', # plane_orientation='y_axes') # #scp2.implicit_plane.widget.enabled = False #scp2.enable_contours = True #scp2.contour.filled_contours=True #scp2.contour.number_of_contours = 20 #scp2.contour.minimum_contour=.001 # CHECK grid orientation #fieldr = mlab.pipeline.vector_field(X, Y, Z, -BBx, BBy, BBz, # scalars=btotal, name='B field') # #sg=mlab.pipeline.streamline(fieldr) #sg.streamline_type = 'tube' #sg.seed.widget = sg.seed.widget_list[3] #sg.seed.widget.position=loc[0] #sg.seed.widget.enabled = False #OUTPUT grid #ww = tvtk.XMLStructuredGridWriter(input=sgrid, file_name='sgrid.vts') #ww.write() return
dist = ((eigs_r - event.xdata)/range_r)**2 + \ ((eigs_i - event.ydata)/range_i)**2 ind = argmin(dist) # Update the highlight plot overplot.set_data([eigs_r[ind]], [eigs_i[ind]]) print("Eigenvalue number: %d (%e,%e)" % (ind, eigs_r[ind], eigs_i[ind])) if eigenvectors is not None: # Update plots nx = eigenvectors.shape[1] vector_r.set_data(arange(nx), eigenvectors[2 * ind, :]) vector_i.set_data(arange(nx), eigenvectors[2 * ind + 1, :]) ax[1].relim() ax[1].autoscale_view() fig.canvas.draw() fig.canvas.mpl_connect('button_press_event', onclick) plt.show() if __name__ == "__main__": path = "data" eigenvalues = collect("t_array", path=path, info=False) eigenvectors = collect("f", xguards=False, path=path, info=False) plot_eigenvals(eigenvalues, eigenvectors[..., 0, 0])
colors = ['k','b','g','r'] ngroups_list = [20, 40, 80] syms = ['x', 'o', 'D'] for beta_max, color in zip(beta_max_list, colors): for ngroups, sym in zip(ngroups_list, syms): flux_ratio = [] for Te in Telist: cmd = "./conduction-snb \"Te={0}+0.01*sin(y)\" Ne={1} mesh:length={2} snb:beta_max={3} snb:ngroups={4}".format(Te, Ne, length, beta_max, ngroups) # Run the case s, out = launch_safe(cmd, nproc=1, mthread=1, pipe=True) div_q = collect("Div_Q", path="data").ravel() div_q_SH = collect("Div_Q_SH", path="data").ravel() # Get the index of maximum S-H heat flux ind = np.argmax(div_q_SH) flux_ratio.append(div_q[ind] / div_q_SH[ind]) plt.plot(lambda_ee_T / length, flux_ratio, '-'+sym+color, label=r"$\beta_{{max}}={0}, N_g={1}$".format(beta_max,ngroups)) plt.legend() plt.xlabel(r"$\lambda_{ee,T} / L$") plt.ylabel(r"$q / q_{SH}$") plt.xscale("log") plt.savefig("snb-sinusoidal.png")
os.makedirs('Movie') for i in range(nt): s.mlab_source.scalars = d[i,:,:] if s1 != None : s1.mlab_source.scalars = d[i,:,:] title="t="+np.string0(i) mlab.title(title,height=1.1, size=0.26) if save == True : mlab.savefig('Movie/anim%d.png'%i) yield if __name__ == '__main__': path='../../../examples/elm-pb/data' data = collect("P", path=path) nt=data.shape[0] ns=data.shape[1] ne=data.shape[2] nz=data.shape[3] f = mayavi.mlab.figure(size=(600,600)) # Tell visual to use this as the viewer. visual.set_viewer(f) #First way s1 = contour_surf(data[0,:,:,10]+.1, contours=30, line_width=.5, transparent=True)
data_path = "data" except ValueError: end_index = -1 data_path = str(argv[1]) elif len(argv)==3: end_index = int(argv[1]) data_path = str(argv[2]) else: print("Arguments: '[end_index] [data_path]' or '[data_path]'") Exit(1) electron_mass = 9.10938291e-31 ion_mass = 3.34358348e-27 # Collect the data f = collect("effective_alpha_e", path=data_path, info=True) #Te = collect("T_electron", path=data_path, xind=2, info=True, yguards=True) #Ti = collect("T_ion", path=data_path, xind=2, info=True, yguards=True) #n = collect("n_ion", path="data", xind=2, info=True, yguards=True) if end_index<0: end_index = len(f[:]) alpha0 = 1 alphaoveralpha0 = [] for i in range(end_index): alphaoveralpha0.append(old_div(f[i],alpha0)) print(i,alphaoveralpha0[i]) # Make plot pyplot.figure(1, facecolor='w')