def plotc(title): plt.figure() plt.loglog(hvec,efe,'-o',label='FE') plt.loglog(hvec,ebe,'-s',label='BE') plt.loglog(hvec,etm,'-^',label='TM') slope1, intercept, _, _, _ = linregress(np.log(hvec),np.log(ebe)) slope2, intercept, _, _, _ = linregress(np.log(hvec),np.log(etm)) annotation.slope_marker((hvec[8], ebe[8]), (slope1, 1)) annotation.slope_marker((hvec[8], etm[8]), (slope2, 1)) plt.title(title); plt.legend(); plt.tight_layout(); pp.savefig()
def convPlot(exact, approx, nels, title): error = getError(exact, approx) dx = np.divide(1, nels) fig, ax = plt.subplots() ax.loglog(dx, error) ax.set_xlabel("dx") ax.set_ylabel("% Error") ax.set_title(title) annotation.slope_marker((.01, .01), (2, 1), ax=ax) plt.grid(True) plt.gca().invert_xaxis() plt.tight_layout() plt.show()
def plot_gradient_convergence(cell_size, rel_error_zz, rel_error_l2, no_boundary, norm_type='l2'): """ Plot convergence curves for both Zienkiewicz-Zhu and L2 projection recovery methods applied to the sinusoidal test case. """ from mpltools import annotation # Plot convergence curves on a log-log axis fig, axes = plt.subplots(figsize=(5, 5)) axes.loglog(cell_size, rel_error_zz, '--x', label='Zienkiewicz-Zhu') axes.loglog(cell_size, rel_error_l2, '--x', label=r'$L^2$ projection') axes.set_xlabel("Element size") axes.set_xlim([0.01, 0.3]) assert norm_type[0] in ('l', 'L'), "Norm type '{:s}' not recognised".format(norm_type) _norm_type = r"\ell" if norm_type[0] == 'l' else r"L" _order = norm_type[1] label = r"Relative ${{{:s}}}^{{{:s}}}$ error".format(_norm_type, _order) axes.set_ylabel(label) axes.grid(True) # Add slope markers slope = 2.5 if norm_type[0] == 'l' else 2.0 if norm_type == 'L1' else 1.5 y = 3.0e-02 if norm_type[0] == 'L' else 1.0e-04 if no_boundary else 7.0e-03 annotation.slope_marker((0.1, y), slope, ax=axes, invert=not no_boundary, size_frac=0.15) if no_boundary: annotation.slope_marker((0.1, 8.0e-04), 4, invert=True, ax=axes, size_frac=0.15) # Save to file fname = 'gradient_recovery_convergence_{:s}'.format(norm_type) if no_boundary: fname += '_interior' plot_dir = 'outputs' savefig(fname, plot_dir, extensions=['pdf']) fname = 'legend_gradient_recovery' if not os.path.exists(os.path.join(plot_dir, fname + '.pdf')): fig2, axes2 = plt.subplots() lines, labels = axes.get_legend_handles_labels() legend = axes2.legend(lines, labels, fontsize=18, frameon=False, ncol=2) fig2.canvas.draw() axes2.set_axis_off() bbox = legend.get_window_extent().transformed(fig2.dpi_scale_trans.inverted()) savefig(fname, plot_dir, bbox_inches=bbox, extensions=['pdf'], tight=False)
dxV=np.array([2.0*np.pi/64,2.0*np.pi/32,2.0*np.pi/16.,2.0*np.pi/8.,2.0*np.pi/4.]) err_3p_dx=compute_error_from_exactsol(L,T,dxV,dt_err,'dx','3pt') err_5p_dx=compute_error_from_exactsol(L,T,dxV,dt_err,'dx','5pt') # #PLOTS-ERRORS # #Error ( dt ) plt.figure(1,figsize=[10,8]) plt.rc('text', usetex=True) plt.rc('font', family='serif',size=16) plt.ylabel('E($\\Delta$t)',size=20) plt.xlabel('$\\Delta$t',size=18) plt.loglog(dtV,err_3p_dt,'--sb',label='EE (time), 3-point stencil (space)') plt.loglog(dtV,err_5p_dt,'--or',fillstyle='none',label='EE (time), 5-point stencil (space)') annotation.slope_marker((3E-2, 0.002), (1, 1)) plt.gca().legend(loc=4) plt.title('Error as function of $\\Delta$t, $\\Delta$x=2$\pi$/'+str(2.*np.pi/dx_err)) plt.savefig('Error_dt.png') #plt.show() plt.close() # #Error ( dt ) plt.figure(1,figsize=[10,8]) plt.rc('text', usetex=True) plt.rc('font', family='serif',size=16) plt.ylabel('E($\\Delta$x)',size=20) plt.xlabel('$\\Delta$x',size=18) plt.loglog(dxV,err_3p_dx,'--sb',label='EE (time), 3-point stencil (space)') plt.loglog(dxV,err_5p_dx,'--or',fillstyle='none',label='EE (time), 5-point stencil (space)') annotation.slope_marker((0.8, 0.012), (2, 1))
vec_int3 = heat_DDA(u, phi, f, g, ds, dt, T, 'int_u', 0, print_steps=True) eps4 = 0.8 phi = PhiCircle(xm, ym, r, eps4) vec_int4 = heat_DDA(u, phi, f, g, ds, dt, T, 'int_u', 0, print_steps=True) epsV = np.array([eps1, eps2, eps3, eps4]) intV = abs( np.array([ np.average(vec_int1), np.average(vec_int2), np.average(vec_int3), np.average(vec_int4) ]) - np.average(vec_int0)) plt.ylabel('$|C_\\epsilon-C_{0.05}|$', size=20) plt.xlabel('$\\epsilon$', size=20) plt.loglog(epsV, intV, '--sb') annotation.slope_marker((0.3, 1e-6), (2, 1)) plt.title('Convergence for $\\epsilon \\rightarrow 0$') plt.savefig('Convergence_eps.png') plt.show() plt.close() #Full Dynamics Enable = 1 if (Enable): ds = 0.2 dt = 0.001 T = 10.0 eps = 1.0 f = 0 g = 0 xm, ym, u, phi = update_mesh_function(r, L, eps, ds, A, B)
E = np.zeros((3, len(N))) for (j, n) in enumerate(N): E[:, j] = main(n) fig = plt.figure(figsize=(5.69, 4.27)) ax = plt.gca() marks = ('or', '-g', '-ob') vars = (r'$u_x$', r'$u_y$', r'$p$') for i in range(3): plt.loglog(N, E[i, :], marks[i], label=vars[i]) slope, intercept = np.polyfit(np.log(N[-2:]), np.log(E[i, -2:]), 1) if (i != 1): annotation.slope_marker((N[-2], E[i, -2]), ("{0:.2f}".format(slope), 1), ax=ax, poly_kwargs=pa, text_kwargs=ta) plt.text(N[0], 2e-5, r"$\Delta t=5 \times 10^{-3},\; N=32^2$") plt.text(N[0], 1e-5, r"Final Time = $5 \times 10^{-2}$") plt.title(r"Stokes: $2^{nd}$-order Rotational Pressure-Correction") plt.legend() plt.autoscale() plt.ylabel(r'$|Error|_{L^2}$') plt.xticks(N) ax.get_xaxis().set_minor_formatter(NullFormatter()) fmt = lambda v: r"$\Delta t/{0}$".format(v) if v != 1 else r"$\Delta t$" plt.gca().set_xticklabels(list(map(fmt, N))) #plt.savefig("stokes.pdf", orientation='portrait') plt.show()
h_array, df.FluxErrors, label=label, # linewidth=LINEWIDTH, linestyle=linestyles[degree], # markersize=MARKERSIZE, marker=markers[degree], color=colors[degree], clip_on=False) # Slope markers for scalar annotation.slope_marker((0.1, 0.15), 1, ax=ax1, invert=False, text_kwargs={ 'fontsize': FONTSIZE - 2, 'color': colors[0], 'position': (0.05, 0.125) }, poly_kwargs={'facecolor': colors[0]}) annotation.slope_marker((0.0625, 0.0001), 3, ax=ax1, invert=False, text_kwargs={ 'fontsize': FONTSIZE - 2, 'color': colors[2], 'position': (0.0325, 0.0000525) }, poly_kwargs={'facecolor': colors[2]}) annotation.slope_marker((0.0575, 1e-7),
input_file = os.path.join(input_folder,"results_errors.txt") output_folder = os.path.join(input_folder, "plots") os.makedirs(output_folder, exist_ok=True) #read header with open(input_file) as f: error_names = f.readline()[:-1].split(",")[1:] #read data data = np.genfromtxt(input_file, delimiter=',', skip_header=1) h = data[:,0] errors = data[:,1:] #Plot errors for i in range(len(error_names)): plt.loglog(h,errors[:,i], 'o-', markersize=5, label=error_names[i]) #Add slope triangles min_error = np.min(errors) annotation.slope_marker((h[1],min_error), 1.0, invert=False) annotation.slope_marker((h[3],min_error), 2.0, invert=False) #Label plot plt.legend() plt.xlabel('h') plt.ylabel('Error Norms') plt.grid() plt.savefig(os.path.join(output_folder, 'convergence.eps'))
nx = [int(16 * 5 * res) for res in resolutions] # Get high resolution data df_real = pd.read_csv('fixed_output/bed_trench_output_uni_c_4.0000.csv') nrm = np.sqrt(np.sum(df_real['bath']**2)) N = len(df_real) # Compute discretisation errors disc_err = [] for res in resolutions: df = pd.read_csv( 'fixed_output/bed_trench_output_uni_c_{:.4f}.csv'.format(res)) disc_err.append(100 * np.sqrt( sum([(df['bath'][i] - df_real['bath'][i])**2 for i in range(N)])) / nrm) # Plot discretisation error against element count fig, axes = plt.subplots(figsize=(6, 5)) axes.plot(nx, disc_err, '-o') axes.set_xscale('log') axes.set_yscale('log') axes.set_xlabel(r"Element count in $x$-direction") axes.set_ylabel(r"Relative $\ell^2$ error") axes.set_xticks([10, 100]) yticks = [0.01, 0.1, 1, 10, 100] axes.set_yticks(yticks) axes.set_yticklabels([r"0.01\%", r"0.1\%", r"1\%", r"10\%", r"100\%"]) annotation.slope_marker((20, 0.3), -2, invert=True, ax=axes, size_frac=0.2) axes.grid(True, which='minor') savefig("discretisation_error", "plots", extensions=['pdf'])
color=colors[h_degree - 1], clip_on=False) ax4.plot(h_array, hneg1_df.PostProcessedFluxErrors, label=hneg1_label, # linewidth=LINEWIDTH, linestyle="dotted", # markersize=MARKERSIZE, marker=markers[hneg1_degree - 1], color=colors[hneg1_degree - 1], clip_on=False) # Slope markers for scalar annotation.slope_marker((0.12, 0.2), 1, ax=ax1, invert=False, text_kwargs={'fontsize': FONTSIZE-2, 'color': colors[0], 'position': (0.06, 0.15)}, poly_kwargs={'facecolor': colors[0]}) annotation.slope_marker((0.035, 2e-3), 2, ax=ax1, invert=False, text_kwargs={'fontsize': FONTSIZE-2, 'color': colors[1], 'position': (0.018, 1e-3)}, poly_kwargs={'facecolor': colors[1]}) annotation.slope_marker((0.02, 2e-7), 3, ax=ax1, text_kwargs={'fontsize': FONTSIZE-2, 'color': colors[2], 'position': (0.04, 2.75e-7)}, invert=True, poly_kwargs={'facecolor': colors[2]})
# Make a plot for each scheme lines = [] for k in range(0, numschemes): lines.append( ax.plot(meshsize, errors[k], linestyle='-', marker=markers[k], color=colours[k], label=scheme_name[k])) # Compute slope if (args.slope): slopes = [] for i in range(len(meshsize) - 1): slopes.append((log(errors[k][i + 1]) - log(errors[k][i])) / (log(meshsize[i + 1]) - log(meshsize[i]))) print(slopes) print(np.std(slopes)) if (np.std(slopes) < 0.5): slope = round(slopes[-1], 2) pos = (meshsize[-1], errors[k][-1]) annotation.slope_marker(pos, slope, ax=ax, invert=False, poly_kwargs={'color': colours[k]}) plt.legend() plt.tight_layout() plt.show()
a simple way of adding a slope marker by specifying the origin of the marker (normally, the left-most corner of the marker, but, when ``invert=True``, it's the right-most corner) and the slope---either as a float value or a (rise, run) tuple. """ import numpy as np import matplotlib.pyplot as plt from mpltools import annotation x = np.logspace(0, 2) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) ax1.plot([0, 2], [1, 0]) annotation.slope_marker((1, 0.6), (-1, 2), ax=ax1) ax1.set_title('linear, negative slope') ax2.loglog(x, x**0.5) annotation.slope_marker((10, 2), (1, 2), ax=ax2, text_kwargs={'color': 'cornflowerblue'}, poly_kwargs={'facecolor': (0.73, 0.8, 1)}) ax2.set_title('loglog, custom colors') ax3.loglog(x, x**0.5) annotation.slope_marker((10, 4), (1, 2), invert=True, ax=ax3) ax3.set_title('loglog, `invert=True`') ax4.loglog(x, x**0.5) annotation.slope_marker((10, 2), 0.5, ax=ax4) ax4.set_title('loglog, float slope')
axes.plot(out[method]['dofs'], time, linestyle, **kwargs) axes.set_xscale('log') axes.set_yscale('log') minor = ticker.LogLocator(base=10.0, subs=np.arange(1.0, 10.0) * 0.1, numticks=10) axes.xaxis.set_minor_locator(minor) axes.xaxis.set_minor_formatter(ticker.NullFormatter()) axes.yaxis.set_minor_locator(minor) axes.yaxis.set_minor_formatter(ticker.NullFormatter()) axes.set_xlabel("Degrees of freedom") axes.set_ylabel(r"CPU time [$\mathrm s$]") axes.grid(True, which='both') annotation.slope_marker((1.0e+05, 10), 1, invert=False, ax=axes, size_frac=0.2) savefig("enrichment_time_{:s}".format(alignment), plot_dir, extensions=["pdf"]) # Save legend to file if alignment == 'aligned': fig2, axes2 = plt.subplots() lines, labels = axes.get_legend_handles_labels() legend = axes2.legend(lines, labels, fontsize=18, frameon=False, ncol=1)
predicted or measured slope. ``mpltools.annotation.slope_marker`` provides a simple way of adding a slope marker by specifying the origin of the marker (normally, the left-most corner of the marker, but, when ``invert=True``, it's the right-most corner) and the slope---either as a float value or a (rise, run) tuple. """ import numpy as np import matplotlib.pyplot as plt from mpltools import annotation x = np.logspace(0, 2) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) ax1.plot([0, 2], [1, 0]) annotation.slope_marker((1, 0.6), (-1, 2), ax=ax1) ax1.set_title('linear, negative slope') ax2.loglog(x, x**0.5) annotation.slope_marker((10, 2), (1, 2), ax=ax2, text_kwargs={'color': 'cornflowerblue'}, poly_kwargs={'facecolor': (0.73, 0.8, 1)}) ax2.set_title('loglog, custom colors') ax3.loglog(x, x**0.5) annotation.slope_marker((10, 4), (1, 2), invert=True, ax=ax3) ax3.set_title('loglog, `invert=True`') ax4.loglog(x, x**0.5) annotation.slope_marker((10, 2), 0.5, ax=ax4)
p2Eu_smooth=np.loadtxt("energy_error_quad_smooth.txt") p2Lu_smooth=np.loadtxt("L2_error_quad_smooth.txt") xh=p1Eu[1::,0] plt.figure(1) line_D1=plt.plot(np.log(xh),np.log(p1Eu.diagonal()[1::]),label=r'$H^1(k=1)$',ls='-.',marker="D") line_D2=plt.plot(np.log(xh),np.log(p1Lu.diagonal()[1::]),label=r'$L_2(k=1)$',ls='--',marker="o") line_D3=plt.plot(np.log(xh),np.log(p2Eu.diagonal()[1::]),label=r'$H^1(k=2)$',marker='^') line_D4=plt.plot(np.log(xh),np.log(p2Lu.diagonal()[1::]),label=r'$L_2(k=2)$',marker="s") annotation.slope_marker((4.5,-3),-1,invert=True) annotation.slope_marker((4.5,-7.9),-1.5,invert=True) plt.xlabel(r'$\log(1/h)$') plt.legend(loc='best') plt.ylabel('log(error)') plt.title('Numerical results') plt.show() plt.figure(2) line_D1=plt.plot(np.log(xh),np.log(p1Eu_smooth.diagonal()[1::]),label=r'$H^1(k=1)$',ls='-.',marker="D") line_D2=plt.plot(np.log(xh),np.log(p1Lu_smooth.diagonal()[1::]),label=r'$L_2(k=1)$',ls='--',marker="o") line_D3=plt.plot(np.log(xh),np.log(p2Eu_smooth.diagonal()[1::]),label=r'$H^1(k=2)$',marker='^')
#print() plt.figure(1) line_D1 = plt.plot(np.log(xh), np.log(p1Eu.diagonal()[1::]), label=r'(P1)Energy', ls='-.') line_D2 = plt.plot(np.log(xh), np.log(p1Lu.diagonal()[1::]), label=r'(P1)$L_2$ of $u$', ls='--') line_D3 = plt.plot(np.log(xh), np.log(p1Lw.diagonal()[1::]), label=r'(P1)$L_2$ of $\dot u$') annotation.slope_marker((5.0, -7), -1, invert=True) annotation.slope_marker((5.0, -13.5), -2, invert=True) line_V1 = plt.plot(np.log(xh), np.log(p2Eu.diagonal()[1::]), label=r'(P2)Energy', marker="^") line_V2 = plt.plot(np.log(xh), np.log(p2Lu.diagonal()[1::]), label=r'(P2)$L_2$ of $u$', marker=".") line_V3 = plt.plot(np.log(xh), np.log(p2Lw.diagonal()[1::]), label=r'(P2)$L_2$ of $\dot u$', marker="s") plt.xlabel(r'$\log(1/h)$', fontsize=18)
if(i%100000==0): print("i=",i) vvv[i]=(((vvv[i-1])/(area)*i + ck[i])*area)/(i+1) dev[i]=(((dev[i-1]+val)/(area)*i + ck[i])*area)/(i+1)-val p=(vvv[i]/area) devBIN[i]=np.sqrt(p*(1-p)/(i+1))*area #We show results from iteration # n=nini to n=N/2 (with reference values what it obtained with n=N) # # nini=100 nvec=np.linspace(nini,int(N/2),(int(N/2)-nini)) popt, pcov = curve_fit(funcexp, nvec, abs(dev[nini:int(N/2)])) plt.loglog(nvec,abs(dev[nini:int(N/2)]),'-r') plt.loglog(nvec,funcexp(nvec,*popt),'--b',label="Fitted Exponent: "+str(np.around(popt[1],6))) annotation.slope_marker((3e4, 0.001), (-0.5, 1)) plt.title('Convergence rate (to $\hat{G}_N$), N='+str(N)) plt.ylabel('$\Delta_G(n,N)$',size=20) plt.xlabel('$n$',size=20) plt.legend(loc="best") plt.savefig('Rate_G.png') plt.show() plt.close # # default_plotting() plt.fill_between(nvec,2*devBIN[nini:int(N/2)]+vvv[nini:int(N/2)],-2*devBIN[nini:int(N/2)]+vvv[nini:int(N/2)],color='y',alpha=0.25,label="$\hat{G}_n\\pm 2\sigma$") plt.fill_between(nvec,devBIN[nini:int(N/2)]+vvv[nini:int(N/2)],-devBIN[nini:int(N/2)]+vvv[nini:int(N/2)],alpha=0.25,label="$\hat{G}_n \\pm \sigma$") plt.plot(nvec,vvv[nini:int(N/2)],'-b',linewidth=2,label='$\hat{G}_n$') plt.plot(nvec,val*np.ones(nvec.shape[0]),'--r',linewidth=2,label="$$\hat{G}_N$$") plt.title('Convergence to $\hat{G}_N$, N='+str(N))
rates[mode + '_max'] = [np.max(rate) for rate in rates[mode]] fig, axes = plt.subplots() axes.semilogx(dofs, rates['continuous_min'], '--x', color='C0') axes.semilogx(dofs, rates['continuous_max'], ':x', color='C0') axes.set_xlabel("Degrees of freedom") axes.set_ylabel("Convergence rate") axes.grid(True) savefig("taylor_remainder_convergence", "plots", extensions=["pdf"]) fig, axes = plt.subplots(figsize=(9, 4)) axes.loglog(eps, residuals['discrete'][0], '--x', label='Discrete') axes.loglog(eps, residuals['continuous'][0], '--x', label='Continuous') annotation.slope_marker((2.2e-04, 4.0e-07), 1, invert=True, ax=axes, size_frac=0.2) annotation.slope_marker((5.8e-04, 2.0e-08), 2, invert=False, ax=axes, size_frac=0.2) axes.set_xlabel("Step length") axes.set_ylabel("Taylor remainder") axes.grid(True, which='both') axes.legend(fontsize=20, loc='center left') savefig("taylor_remainder_0", "plots", extensions=["pdf"]) fig, axes = plt.subplots(figsize=(9, 4)) axes.loglog(eps, residuals['discrete'][4], '--x', label='Discrete')
#plt.show() plt.close() #compute error dtV_BE = np.logspace(-4, -1, 4) err_BE = compute_error_from_num(uini, T, dtV_BE, 'BE') #### #Error ( dt ) plt.figure(1, figsize=[10, 8]) plt.rc('text', usetex=True) plt.rc('font', family='serif', size=16) plt.ylabel('E($\\Delta$t)', size=20) plt.xlabel('$\\Delta$t', size=18) plt.loglog(dtV_BE, err_BE, '--or', label='BE') plt.loglog(dtV_FE, err_FE, '--sb', label='FE') plt.loglog(dtV_BE, np.ones(dtV_BE.shape[0]) * 1e-5, '--k', label='$\\epsilon_1$') plt.loglog(dtV_BE, np.ones(dtV_BE.shape[0]) * 2e-4, ':k', label='$\\epsilon_2$') annotation.slope_marker((0.007, 2.6e-5), (1, 1)) plt.legend(loc='best') plt.title('Error as function of $\\Delta$t, $\\Delta$x=$2\pi$/' + str(int((2.0 * np.pi) / dx))) plt.savefig('Error_FM_dt.png') #plt.show() plt.close()
plt.axis([0, T, e4[e4.shape[0] - 1] / e4[0], 1.0]) plt.savefig('Convergence_eps_1.png') plt.show() epsV = np.array([eps1, eps2, eps3, eps4]) drV = abs( np.array([ min(e1 / e1[0]), min(e2 / e2[0]), min(e3 / e3[0]), min(e4 / e4[0]) ]) - (min(e0 / e0[0]))) default_plotting() plt.ylabel('$|r_\\epsilon(t)-r_{\\rm ref}|$', size=20) plt.xlabel('$\\epsilon$', size=20) plt.loglog(epsV, drV, '--sb') annotation.slope_marker((1, 1E-4), (2, 1)) plt.title('Convergence for $\\epsilon \\rightarrow 0$') plt.savefig('Convergence_eps_2.png') plt.show() plt.close() #Full Dynamics Enable = 0 if (Enable): ds = 0.2 dt = 0.001 eps = 1.0 T = ((r**2) / 2.0) / 1.0 xm, ym, phi = update_mesh_function(r, L, eps, ds) AllenCahn_FD(phi, eps, ds, dt, L, T, label='n_plot', print_steps=True)