def analyze(): # check density max and Vz and Bz components in tab slice slice_data = athena_read.tab( filename='bin/TestOutputs.block0.out2.00010.tab') if max(slice_data[0, 0, :, 1]) < 0.25: return False if max(slice_data[0, 0, :, 5]) != 0.0: return False if max(slice_data[0, 0, :, 8]) != 0.0: return False # check density max and Vz and Bz components in tab sum sum_data = athena_read.tab( filename='bin/TestOutputs.block0.out3.00010.tab') if max(sum_data[0, 0, :, 1]) < 15.0 and max(sum_data[0, 0, :, 1]) > 20.0: return False if max(sum_data[0, 0, :, 5]) != 0.0: return False if max(sum_data[0, 0, :, 8]) != 0.0: return False # check data in VTK dump # xf,yf,_,vtk_data = athena_read.vtk(filename='bin/TestOutputs.block0.out4.00010.vtk') # if max(xf) != 1.0 and min(xf) != 0.0: # return False # if max(yf) != 1.0 and min(yf) != 0.0: # return False # print vtk_data['dens'] # print max(vtk_data[:,:,:,'dens']), min(vtk_data[:,:,:,'dens']) return True
def analyze(): # Specify tab file columns columns = (1, 2, 3, 4, 5) # Check that convergence is attained for each wave for wave_flag in wave_flags: # Read low and high resolution initial and final states prim_initial_low = athena_read.tab( 'bin/sr_hydro_wave_{0}_low.block0.out1.00000.tab'.format( wave_flag), raw=True, dimensions=1) prim_initial_high = athena_read.tab( 'bin/sr_hydro_wave_{0}_high.block0.out1.00000.tab'.format( wave_flag), raw=True, dimensions=1) prim_final_low = athena_read.tab( 'bin/sr_hydro_wave_{0}_low.block0.out1.00001.tab'.format( wave_flag), raw=True, dimensions=1) prim_final_high = athena_read.tab( 'bin/sr_hydro_wave_{0}_high.block0.out1.00001.tab'.format( wave_flag), raw=True, dimensions=1) # Calculate overall errors for low and high resolution runs epsilons_low = [] epsilons_high = [] for column in columns: qi = prim_initial_low[column, :] qf = prim_final_low[column, :] epsilons_low.append(math.fsum(abs(qf - qi)) / res_low) qi = prim_initial_high[column, :] qf = prim_final_high[column, :] epsilons_high.append(math.fsum(abs(qf - qi)) / res_high) epsilons_low = np.array(epsilons_low) epsilons_high = np.array(epsilons_high) epsilon_low = (math.fsum(epsilons_low**2) / len(epsilons_low))**0.5 / amp epsilon_high = (math.fsum(epsilons_high**2) / len(epsilons_high))**0.5 / amp # Test fails if convergence is not at least that specified by cutoff if epsilon_high / epsilon_low > (float(res_low) / float(res_high))**cutoff: return False # All waves must have converged return True
def analyze(): analyze_status = True # check density max and Vz and Bz components in tab slice slice_data = athena_read.tab( filename='bin/TestOutputs.block0.out2.00010.tab', raw=True, dimensions=1) if max(slice_data[1, :]) < 0.25: analyze_status = False if max(slice_data[5, :]) != 0.0: analyze_status = False if max(slice_data[8, :]) != 0.0: analyze_status = False # check density max and Vz and Bz components in tab sum sum_data = athena_read.tab( filename='bin/TestOutputs.block0.out3.00010.tab', raw=True, dimensions=1) if max(sum_data[1, :]) < 15.0 and max(sum_data[:, 1]) > 20.0: analyze_status = False if max(sum_data[5, :]) != 0.0: analyze_status = False if max(sum_data[8, :]) != 0.0: analyze_status = False # assuming domain is 64x64 w/o ghost zones output, slice near central interface x2=0.0 # check density max and Vz and Bz components in VTK dump xf, yf, _, vtk_data = athena_read.vtk( filename='bin/TestOutputs.block0.out4.00010.vtk') if max(vtk_data['rho'][0, 32, :]) < 0.25: analyze_status = False if max(vtk_data['vel'][0, 32, :, 2]) != 0.0: analyze_status = False if max(vtk_data['Bcc'][0, 32, :, 2]) != 0.0: analyze_status = False # if max(xf) != 0.5 and min(xf) != -0.5: # analyze_status = False # if max(yf) != 0.5 and min(yf) != -0.5: # analyze_status = False # logger.debug(str(vtk_data['rho'].shape)) hdf5_data = athena_read.athdf('bin/TestOutputs.out5.00010.athdf', dtype=np.float32) if max(hdf5_data['rho'][0, 32, :]) < 0.25: analyze_status = False if max(hdf5_data['vel3'][0, 32, :]) != 0.0: analyze_status = False if max(hdf5_data['Bcc3'][0, 32, :]) != 0.0: analyze_status = False return analyze_status
def analyze(): l1ERROR = [[] for err in range(0, len(sts_integrators))] conv = [] for i in range(len(sts_integrators)): for n in resolution_range: x1v, bcc2 = athena_read.tab('bin/ResistiveDiffusion_' + str(n) + '_' + sts_integrators[i] + '.block0.out2.00001.tab', raw=True, dimensions=1) dx1 = _Lx1/len(x1v) analytic = (_amp/np.sqrt(4.*np.pi*_eta*(_t0+_tf)) * np.exp(-(x1v**2.)/(4.*_eta*(_t0+_tf)))) l1ERROR[i].append(sum(np.absolute(bcc2-analytic)*dx1)) # estimate L1 convergence analyze_status = True for i in range(len(sts_integrators)): method = sts_integrators[i].upper() conv.append(np.diff(np.log(np.array(l1ERROR[i]))) / np.diff(np.log(np.array(resolution_range)))) logger.info('[Resistive Diffusion {}]: Convergence order = {}' .format(method, conv[i])) if conv[i] > rate_tols[i]: logger.warning('[Resistive Diffusion {}]: ' 'Scheme NOT converging at expected order.'.format(method)) analyze_status = False else: logger.info('[Resistive Diffusion {}]: ' 'Scheme converging at expected order.'.format(method)) return analyze_status
def analyze(): l1ERROR = [] for n in resolution_range: x1v, v2 = athena_read.tab("bin/visc" + str(n) + ".block0.out2.00001.tab", raw=True, dimensions=1) sigma = np.sqrt(2. * _nu * _t0) dx1 = _Lx1 / len(x1v) analytic = ((_amp / np.sqrt(2. * np.pi * sigma**2.)) * (1. / np.sqrt(1. + (2. * _nu * _t0 / sigma**2.))) * np.exp(-(x1v**2.) / (2. * sigma**2. * (1. + (2. * _nu * _t0 / sigma**2.))))) l1ERROR.append(sum(np.absolute(v2 - analytic) * dx1)) # estimate L1 convergence conv = np.diff(np.log(np.array(l1ERROR))) / np.diff( np.log(np.array(resolution_range))) logger.info('[Viscous Diffusion {}]: Convergence order = {}'.format( method, conv)) analyze_status = True if conv > rate_tols[-1]: logger.warning( '[Viscous Diffusion {}]: ' 'Scheme NOT converging at expected order.'.format(method)) analyze_status = False else: logger.info('[Viscous Diffusion {}]: ' 'Scheme converging at expected order.'.format(method)) return analyze_status
def aread(filename): suffix = filename.split('.')[-1] if suffix == 'vtk': return ar.vtk(filename) if suffix == 'tab': return ar.tab(filename) if suffix == 'athdf': return ar.athdf(filename, subsample=True) else: print('Error: filetype not supported') return
def figure2_profiles(): fig = plt.figure(figsize=(1.0 * figsize[0], 1.0 * figsize[1]), dpi=dpi_global) axes = fig.subplots(2, 2, gridspec_kw={'hspace': 0.4}) for coord_, ylims_, m_, axes_row_ in zip(coords, coord_ylims, coord_m, axes): for case_, xlims_, param_str_, a_, b_, ax in zip( cases, case_xlims, case_parameters, a_params, b_params, axes_row_): for xorder_, xorder_str_ in zip(xorders, xorder_strs): filename = os.path.join( 'bin', '{}_case_{}_{}_xorder_{}_nx1_{}.tab'.format( coord_, case_, integrator, xorder_, nx1_profile)) data = athena_read.tab(filename) x = data['x1v'] y = data['r0'] ax.plot(x, y, '{}'.format(xorder_symbols[xorder_]), fillstyle='none', color=xorder_colors[xorder_], label=xorder_str_, markersize=8) x_samples = np.linspace(0, 2, nsamples) y_samples = EvolvedGaussianProfile(x_samples, a_, b_, m_, 1.0) # EvolvedGaussianProfile(x_samples, a_, b_, m_, 0.0) # Initial condition ax.plot(x_samples, y_samples, '-k', linewidth=1.0) # Drop "_polar" from "spherical_polar" Athena++ --coord choice for title coord_str = coord_.split('_')[0] ax.set_title('Radial advection ({})\n{}'.format( coord_str, param_str_)) ax.set_xlabel(r'$\xi$') ax.set_ylabel(r'$Q$') # KGF: comment-out next 2x lines to autoscale axes limits ax.set_xlim(xlims_) ax.set_ylim(ylims_) ax.yaxis.set_minor_locator(AutoMinorLocator(4)) ax.xaxis.set_minor_locator(AutoMinorLocator(4)) ax.tick_params(direction='in', which='both', axis='both') # Hide the right and top spines / plot borders ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # disable rounded edges: leg = ax.legend( handles=profile_legend_handles, fancybox=False, ) leg.get_frame().set_edgecolor('k') output_name = 'athena_mignone_fig2' pdf_name = "{}.pdf".format(output_name) fig.savefig(pdf_name, bbox_inches='tight', dpi=dpi_global)
def comp_intens(athfiles,outfile='intens_comp.pdf',xscale='linear',yscale='log',xlim=None, ylim=None): #ivars=[26,45] #ivars=[42,43,44,45] #ivars=[26,27,28,29] #ivars=[34,35,36,37] #ivars=[38,39,40,41] ivars=[44,39,34,29] #mu=[1.160841e-01,2.681522e-01,4.137792e-01,5.494671e-01,6.719567e-01,7.783057e-01,8.659595e-01,9.328128e-01,9.772599e-01,9.982377e-01] muf=read_angles() plt.xscale(xscale) plt.yscale(yscale) if xlim is not None: plt.xlim(xlim) if ylim is not None: plt.ylim(ylim) for file in athfiles: data = athena_read.tab(file) #nx3=data.shape[0] #nx2=data.shape[1] nx1=data.shape[2] x1v = np.empty(nx1) var = np.empty(nx1) mod = np.empty(nx1) for k in xrange(0,len(ivars)): j = ivars[k] jm = j-26+20 print muf[jm],muf[jm+1] print 'lim:',1./np.sqrt(1-muf[jm]**2),1./np.sqrt(1-muf[jm+1]**2) for i in xrange(nx1): x1v[i] = data[0,0,i,0] var[i] = data[0,0,i,j] plt.plot(x1v,var) mod = get_intens(x1v,muf[jm],muf[jm+1]) #print mod #print var plt.plot(x1v,mod,':') plt.xlabel("r") plt.ylabel("I") #plt.plot(r,yx,'o') plt.savefig(outfile) plt.close()
def analyze(): # Approximate range of contact discontinuities x_lims = ((0.05, 0.15), (-0.15, -0.05), (0.225, 0.325), (0.3, 0.4)) # Check that fractional concentration is correct on either side of contact analyze_status = True for n, x_lim in zip(range(1, 5), x_lims): data = athena_read.tab('bin/hydro_shock_rel_{0}.block0.out1.00001.tab'.format(n)) x = data['x1v'] chi = data['r0'] chi_left = chi[np.where(x <= x_lim[0])[0]] chi_right = chi[np.where(x >= x_lim[1])[0]] if not np.allclose(chi_left, 0.0): analyze_status = False if not np.allclose(chi_right, 1.0): analyze_status = False return analyze_status
def plot_profiles(): fig = plt.figure(figsize=(1.0*figsize[0], 0.5*figsize[1]), dpi=dpi_global) axes = fig.subplots(1, 2, squeeze=True) for case_, xlims_, param_str_, a_, b_, ax in zip(cases, case_xlims, case_parameters, a_params, b_params, axes): for xorder_, xorder_str_ in zip(xorders, xorder_strs): filename = os.path.join( 'bin', 'case_{}_{}_xorder_{}_nx2_{}.tab'.format( case_, integrator, xorder_, nx2_profile)) data = athena_read.tab(filename) x = data['x2v'] y = data['r0'] ax.plot(x, y, '{}'.format(xorder_symbols[xorder_]), fillstyle='none', color=xorder_colors[xorder_], label=xorder_str_, markersize=8) x_samples = np.linspace(0, np.pi*0.5, nsamples) y_samples = EvolvedCosineProfile(x_samples, a_, b_, 1.0) # y_samples = InitialCosineProfile(x_samples, a_, b_) ax.plot(x_samples, y_samples, '-k', linewidth=1.0) ax.set_title('Meridional advection\n{}'.format(param_str_)) ax.set_xlabel(r'$\xi$') ax.set_ylabel(r'$Q$') # KGF: comment-out next 2x lines to autoscale axes limits # ax.set_xlim(xlims_) # ax.set_ylim(ylims_) # ax.yaxis.set_minor_locator(AutoMinorLocator(4)) # ax.xaxis.set_minor_locator(AutoMinorLocator(4)) ax.tick_params(direction='in', which='both', axis='both') # Hide the right and top spines / plot borders ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # disable rounded edges: leg = ax.legend(handles=profile_legend_handles, fancybox=False,) leg.get_frame().set_edgecolor('k') output_name = 'athena_mignone_meridional_profiles' pdf_name = "{}.pdf".format(output_name) fig.savefig(pdf_name, bbox_inches='tight', dpi=dpi_global)
def plot_intens(athfiles,ivars,outfile='intens.pdf',xscale='log',yscale='linear',xlim=None, ylim=None): #mu=[1.160841e-01,2.681522e-01,4.137792e-01,5.494671e-01,6.719567e-01,7.783057e-01,8.659595e-01,9.328128e-01,9.772599e-01] #r = np.empty(9) #yx = np.empty(9) #for i in xrange(9): # r[i] = 1./(1.-mu[i])*1.e-4 # yx[i] = 0.5 #print r plt.xscale(xscale) plt.yscale(yscale) if xlim is not None: plt.xlim(xlim) if ylim is not None: plt.ylim(ylim) for file in athfiles: data = athena_read.tab(file) #nx3=data.shape[0] #nx2=data.shape[1] nx1=data.shape[2] x1v = np.empty(nx1) var = np.empty(nx1) for j in ivars: for i in xrange(nx1): x1v[i] = data[0,0,i,0] if (data[0,0,i,8] > 1.e-15): #var[i] = data[0,0,i,j] var[i] = data[0,0,i,j]/data[0,0,i,8] else: var[i] = 0. plt.plot(x1v,var) #print var #plt.plot(r,yx,'o') plt.savefig(outfile) plt.close()
def comp_er(athfiles,outfile='er_comp.pdf',xscale='linear',yscale='log',xlim=None, ylim=None): plt.xscale(xscale) plt.yscale(yscale) if xlim is not None: plt.xlim(xlim) if ylim is not None: plt.ylim(ylim) for file in athfiles: data = athena_read.tab(file) nx1=data.shape[2] x1v = np.empty(nx1) er = np.empty(nx1) mer = np.empty(nx1) fr = np.empty(nx1) mfr = np.empty(nx1) for i in xrange(nx1): x1v[i] = data[0,0,i,0] er[i] = data[0,0,i,6] fr[i] = data[0,0,i,8] plt.plot(x1v,er) plt.plot(x1v,fr) mer = get_er(x1v) mfr = get_fr(x1v) plt.plot(x1v,mer,':') plt.plot(x1v,mfr,':') #print var #print mod plt.xlabel("r") plt.ylabel("Er, Fr") plt.savefig(outfile) plt.close()
p = e*(gamma-1.0) ge = e/d else: p = (E - 0.5*d*v**2) * (gamma - 1.0) ge = p/d/(gamma - 1.0) t = gamma*p/d maxRho = max(maxRho, d.max()) minRho = min(minRho, d.min()) maxV = max(maxV, v.max()) minV = min(minV, v.min()) maxT = max(maxT, t.max()) minT = min(minT, t.min()) for directory,label in zip(athena_dirs, athena_labels): dump = directory + dump_tag + str(i_dumps[i]).zfill(5) + '.tab' athena_dic = athena_read.tab(dump, ['x', 'rho', 'pgas', 'v1', 'v2', 'v3']) x_ath = athena_dic['x'][0,0,:] d_ath = athena_dic['rho'][0,0,:] p_ath = athena_dic['pgas'][0,0,:] v_ath = athena_dic['v1'][0,0,:] t_ath = np.log(gamma*p_ath/d_ath) maxRho = max(maxRho, d_ath.max()) minRho = min(minRho, d_ath.min()) maxV = max(maxV, v_ath.max()) minV = min(minV, v_ath.min()) maxT = max(maxT, t_ath.max()) minT = min(minT, t_ath.min()) # Function called to plot the data for each time step def plotter(bundle): global x
def plot_var_anim(athfiles, ivars, outfile=None, xscale='log', yscale='log', xlim=None, ylim=None, norm=1, sparsity=1, trace=1, dt=None, title=None): n_images = len(ivars) xplots = int(np.ceil(np.sqrt(n_images))) yplots = int(np.around(np.sqrt(n_images))) fig, axes = plt.subplots(ncols=yplots, nrows=xplots, figsize=(12, 12)) # Make single ivars elements iterable, for compatibility with multi-line plot functions ivars = [[x] if type(x) is not list else x for x in ivars] # From sparsity and number of files, figure out how many lines to make num_plots = int(np.floor(len(athfiles)/sparsity)) # Load in the athena data for the files we're using athdata = [athena_read.tab(athfiles[k*sparsity]) for k in range(num_plots)] num_points = len(athdata[0][0, 0, :, 0]) print("Number of files: {}\nNumber of plots: {}".format(len(athfiles), num_plots)) line_attrs = [] plots = [] texts = [] for j, ax in enumerate(np.ndarray.flatten(axes)): nested_line_attrs = [] # store lines in nested lists so they can be plotted appropriately for l in range(len(ivars[j])): # if more than one var is being plotted on the same plot # Set up an empty data structure that contains line data and color line_attr = np.zeros(num_plots, dtype=[('x1v', float, num_points), ('var', float, num_points), ('color', float, 4)]) # Initialize the lines with the athena data for i, line in enumerate(line_attr): line['x1v'] = athdata[i][0, 0, :, 0] line['var'] = athdata[i][0, 0, :, ivars[j][l]] nested_line_attrs.append(line_attr) line_attrs.append(nested_line_attrs) # Plot aesthetics, labels, etc if ylim is not None: if ylim[j] is not None: ax.set_ylim(ylim[j]) if xlim is not None: if xlim[j] is not None: ax.set_xlim(xlim[j]) ax.set_xscale(xscale) ax.set_yscale(yscale) first_plot_id = int(athfiles[0].split(".tab")[0][-5:]) last_plot_id = int(athfiles[-1].split(".tab")[0][-5:]) plot_id_range = "{}-{}".format(first_plot_id, last_plot_id) labels = ['x1v', 'dens', 'energy/pressure', 'v1', 'v2', 'v3', 'Er', 'Er0', 'Fr1', 'Fr2', 'Fr3', 'Fr01', 'Fr02', 'Fr03', 'Pr11', 'Pr22', 'Pr33', 'Pr', 'Pr', 'Pr', 'pr', 'Pr', 'Pr', 'sigma_s', 'sigma_a', 'sigma_p'] ax.set_title(', '.join(labels[z] for z in ivars[j])[:-1]+' vs. x1v') ax.set_ylabel(', '.join(labels[z] for z in ivars[j])[:-1]) ax.set_xlabel('x1v') # Draw all the lines, which will be updated during animation nested_plots = [] for l in range(len(ivars[j])): line_attr = nested_line_attrs[l] plot = ax.plot(line_attr['x1v'].T, line_attr['var'].T, color=(0, 0, 0, 0)) negplot = ax.plot(line_attr['x1v'].T, -line_attr['var'].T, '--', color=(0, 0, 0, 0)) nested_plots.append([plot, negplot]) plots.append(nested_plots) text = ax.text(.05, .05, "INIT", transform=ax.transAxes) texts.append(text) # Make each element of these lists iterable, if not already line_attrs = [[x] if type(x) is not list else x for x in line_attrs] plots = [[x] if type(x) is not list else x for x in plots] texts = [[x] if type(x) is not list else x for x in texts] def update(frame_number): for u in range(len(ivars)): for v in range(len(ivars[u])): for w in [0, 1]: line_attr = line_attrs[u][v] plot = plots[u][v][w] text = texts[u][0] # Loop over all the lines up to the current frame for k, line in enumerate(line_attr[:frame_number]): # Only have n lines visible, fade toward edge (n = trace) stepfunc = 1 - np.heaviside(frame_number - trace - k - 1, 1) alpha = abs(stepfunc * (frame_number - trace - k - 1) / trace) # Set the color in the attribute array colors = [ (alpha, 0, 1-alpha, alpha), # red to blue (1-alpha, 0, alpha, alpha), # blue to red (1-alpha, alpha, 0, alpha), # green to red (alpha, 1-alpha, alpha, alpha), # magenta to green (1-alpha, alpha, alpha, alpha), # cyan to red (alpha, alpha, 1-alpha, alpha), # yellow to blue ] line['color'] = colors[v] # Set the line's color according to the attribute array, set the text to the current frame number plot[k].set_color(line['color']) # Display either a step ticker or a time ticker, depending on if dt is specified if dt is None: text.set_text("Step {}".format(frame_number*sparsity)) else: text.set_text("t = {:.3f}s".format(frame_number*sparsity*dt)) # If the animation is complete, reset all lines to alpha of 0 if frame_number + 1 == num_plots: line_attr['color'] = np.zeros((num_plots, 4)) anim = animation.FuncAnimation(fig, update, num_plots, interval=40, blit=False) if title is not None: plt.suptitle(title) plt.tight_layout() if outfile is None: plt.show() else: if outfile.split('.')[1] == 'gif': writer = 'imagemagick' else: writer = None anim.save(outfile, dpi=300, fps=30./sparsity, writer=writer)
parser.add_argument('-g', '--gap', type=int, help='Spacing between adjacent output plots, in steps') parser.add_argument('-o', '--output', action='store_true') args = parser.parse_args() athfiles = glob('eddingtonwind.block0.out2.*') steps = args.step if steps == []: end = int(athfiles[-1].split('.tab')[0].split('out2.')[-1]) steps = list(np.arange(args.start, end, args.gap)) for step in steps: data = athena_read.tab(athfiles[step]) #print(athfiles[step]) x1v = data[0, 0, :, 0] Fcom = data[0, 0, :, 11] fig, (ax0, ax1, ax2, ax3) = plt.subplots(nrows=4, ncols=1, sharex=True, figsize=(16, 12)) plt.tight_layout() fig.subplots_adjust(hspace=0, top=0.95, bottom=0.05) ax0.plot(x1v, data[0, 0, :, 1], 'k-', label="Density") ax1.plot(x1v, Prat * kappaes * Fcom / (GM / x1v**2),
def main(**kwargs): # Extract inputs data_files = kwargs['data_files'].split(',') x_names = kwargs['x_names'].split(',') y_names = kwargs['y_names'].split(',') output_file = kwargs['output_file'] styles = kwargs['styles'].split(',') colors = kwargs['colors'] labels = kwargs['labels'] x_log = kwargs['x_log'] y_log = kwargs['y_log'] x_min = kwargs['x_min'] x_max = kwargs['x_max'] y_min = kwargs['y_min'] y_max = kwargs['y_max'] x_label = kwargs['x_label'] y_label = kwargs['y_label'] # Verify inputs num_lines = max(len(data_files), len(x_names), len(y_names)) if data_files[0] == '': raise RuntimeError('First entry in data_files must be nonempty') if x_names[0] == '': raise RuntimeError('First entry in x_names must be nonempty') if y_names[0] == '': raise RuntimeError('First entry in y_names must be nonempty') for data_file in data_files: if data_file[-4:] != '.hst' and data_file[-4:] != '.tab': raise RuntimeError('Files must have .hst or .tab extension') if len(data_files) < num_lines: data_files += data_files[-1:] * (num_lines - len(data_files)) if len(x_names) < num_lines: x_names += x_names[-1:] * (num_lines - len(x_names)) if len(y_names) < num_lines: y_names += y_names[-1:] * (num_lines - len(y_names)) for n in range(num_lines): if data_files[n] == '': data_files[n] = data_files[n-1] if x_names[n] == '': x_names[n] = x_names[n-1] if y_names[n] == '': y_names[n] = y_names[n-1] if len(styles) < num_lines: styles += styles[-1:] * (num_lines - len(styles)) for n in range(num_lines): styles[n] = styles[n].lstrip() if styles[n] == '': styles[n] = '-' if colors is None: colors = [None] * num_lines else: colors = colors.split(',') if len(colors) < num_lines: colors += colors[-1:] * (num_lines - len(colors)) for n in range(num_lines): if colors[n] == '': colors[n] = None if num_lines == 1 and colors[0] == None: colors[0] = 'k' if labels is None: labels = [None] * num_lines else: labels = labels.split(',') if len(labels) < num_lines: labels += [None] * (num_lines - len(labels)) for n in range(num_lines): if labels[n] == '': labels[n] = None labels_used = False for n in range(num_lines): if labels[n] != None: labels_used = True break # Load Python plotting modules if output_file != 'show': import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt # Read data x_vals = [] y_vals = [] for n in range(num_lines): if data_files[n][-4:] == '.hst': data = athena_read.hst(data_files[n]) else: data = athena_read.tab(data_files[n]) x_vals.append(data[x_names[n]]) y_vals.append(data[y_names[n]]) # Plot data plt.figure() for n in range(num_lines): plt.plot(x_vals[n], y_vals[n], styles[n], color=colors[n], label=labels[n]) if x_log: plt.xscale('log') if y_log: plt.yscale('log') plt.xlim((x_min, x_max)) plt.ylim((y_min, y_max)) if x_label is not None: plt.xlabel(x_label) if y_label is not None: plt.ylabel(y_label) if labels_used: plt.legend(loc='best') if output_file == 'show': plt.show() else: plt.savefig(output_file, bbox_inches='tight')
def plotter(bundle): global x # Unpack parameters i = bundle["i"] MAKE_MOVIE = bundle["make_movie"] plot_athena_solution = bundle["plot_athena_solution"] cholla_dirs = bundle["cholla_dirs"] labels = bundle["cholla_labels"] athena_dirs = bundle["athena_dirs"] athena_labels = bundle["athena_labels"] i_dumps = bundle["i_dumps"] gamma = bundle["gamma"] ax1 = bundle["ax1"] ax2 = bundle["ax2"] ax3 = bundle["ax3"] ax4 = bundle["ax4"] ax5 = bundle["ax5"] if(STATIC_AXES): maxRho = bundle["maxRho"] minRho = bundle["minRho"] maxV = bundle["maxV"] minV = bundle["minV"] maxT = bundle["maxT"] minT = bundle["minT"] # Clear the axes if it is showing in a gui if(not MAKE_MOVIE): ax1.cla() ax2.cla() ax3.cla() ax5.cla() Nlines = len(ax4.lines) if Nlines > 0: for n in range(Nlines): del ax4.lines[0] # set limits if RESIDUALS: plt.axis([0., x[-1], -pad_d*Amp, pad_d*Amp]) plt.axis([0., x[-1], -pad_v*Amp, pad_v*Amp]) plt.axis([0., x[-1], -(pad_p*Amp)**2, pad_p*Amp]) #Display time on window time_template = 'time = %.1f' time_text = ax1.text(0.75, 0.9, '', transform=ax1.transAxes) # update time time = dt*float(i_dumps[i]) # time in code units time_text.set_text(time_template%(time)) # Loop through cholla dumps for dump_dir,color,ls,lw,label in zip(cholla_dirs,colors,linestyles,linewidths,labels): f = h5py.File(dump_dir+str(i_dumps[i])+'.h5', 'r') head = f.attrs nx = head['dims'][0] gamma = head['gamma'][0] # x = np.arange(0.5*head['dx'][0],1.,head['dx'][0]) x = np.array(range(0,nx,1)) d = np.array(f['density']) # mass density mx = np.array(f['momentum_x']) # x-momentum my = np.array(f['momentum_y']) # y-momentum mz = np.array(f['momentum_z']) # z-momentum E = np.array(f['Energy']) # total energy density v = mx/d if DE: e = np.array(f['GasEnergy']) p = e*(gamma-1.0) ge = e/d else: p = (E - 0.5*d*v**2) * (gamma - 1.0) ge = p/d/(gamma - 1.0) if RESIDUALS: d -= IVs['density'] p -= IVs['pressure'] cs2 = gamma*p/d cs = np.sqrt(cs2) M = v/cs t = gamma*p/d logT_cgs = np.log10(gamma*p/d) logxi_cgs = np.log10(xi_b/d) # plot Cholla solution ax1.plot(x/(1799/9.636),d,ls=ls,lw=lw,color=color,label=label) ax2.plot(x/(1799/9.636),v,ls=ls,lw=lw,color=color) ax3.plot(x/(1799/9.636),p,ls=ls,lw=lw,color=color) ax5.plot(x,t,ls=ls,lw=lw,color=color) # Loop through athena dumps for directory,label in zip(athena_dirs, athena_labels): dump = directory + dump_tag + str(i_dumps[i]).zfill(5) + '.tab' athena_dic = athena_read.tab(dump, ['x', 'rho', 'pgas', 'v1', 'v2', 'v3']) x_ath = athena_dic['x'][0,0,:] d_ath = athena_dic['rho'][0,0,:] p_ath = athena_dic['pgas'][0,0,:] v_ath = athena_dic['v1'][0,0,:] t_ath = np.log(gamma*p_ath/d_ath) if RESIDUALS: d_ath -= IVs['density'] p_ath -= IVs['pressure'] ax1.plot(x_ath,d_ath,ls='-',lw=1,color='orange',label=label) ax2.plot(x_ath,v_ath,ls='-',lw=1,color='orange') ax3.plot(x_ath,p_ath,ls='-',lw=1,color='orange') ax5.plot(x_ath,t_ath,ls='-',lw=1,color='orange') ax1.legend(loc='upper left') if(STATIC_AXES): ax1.set_ylim([minRho, maxRho]) ax2.set_ylim([minV, maxV]) ax5.set_ylim([minT, maxT]) if(MAKE_MOVIE): plt.savefig(tempDir + str(i) + '.png', dpi=200) plt.close()