def main(): import matplotlib matplotlib.use('Agg') import pylab import glob import re import numpy import h5py import tqdm import imageio def extract_snapshot_number(fpath): return int(re.search(r'_(\d+).', fpath).group(1)) ss_files = sorted(glob.glob('output/snapshot_*.h5'), key=extract_snapshot_number) for fname in tqdm.tqdm(ss_files): with h5py.File(fname, 'r') as f: pylab.tricontourf(f['geometry']['x_coordinate'], f['geometry']['y_coordinate'], numpy.log10(f['hydrodynamic']['density']), 50) pylab.title('t = %10.2f' % numpy.array(f['time'])[0]) pylab.colorbar() pylab.axis('equal') pylab.savefig(fname.replace('.h5', '.png')) pylab.close() with imageio.get_writer('density.gif', mode='I', duration=0.2) as writer: for fname in tqdm.tqdm(ss_files): image = imageio.imread(fname.replace('.h5', '.png')) writer.append_data(image)
def plot_plasma(self): P.tricontourf(self.rzt[:, 0], self.rzt[:, 1], self.tris, self.beta, 1001, zorder=0) cticks = P.linspace(0.0, 0.2, 5) P.colorbar(ticks=cticks, format='%.2f') P.jet()
def triangular_chiral_toroid_membrane(): x, y = TriangleWaveEquation.xy(512) t = TriangleWaveEquation(np.exp(-1000 * (x * x + y * y)), 0 * x, decay=0) for _ in range(222): t.step() pylab.tricontourf(x, y, t.numpy()) pylab.show()
def check_metric_ellipse(width=2e-2, eta = 0.02, Nadapt=6): set_log_level(WARNING) parameters["allow_extrapolation"] = True ### CONSTANTS meshsz = 40 hd = Constant(width) ### SETUP MESH mesh = RectangleMesh(Point(-0.5,-0.5),Point(0.5,0.5),1*meshsz,1*meshsz,"left/right") ### SETUP SOLUTION angle = pi/8#rand()*pi/2 #testsol = 'tanh(x[0]/' + str(float(hd)) + ')' #tanh(x[0]/hd) testsol = 'tanh((' + str(cos(angle)) + '*x[0]+'+ str(sin(angle)) + '*x[1])/' + str(float(hd)) + ')' #tanh(x[0]/hd) ddtestsol = str(cos(angle)+sin(angle))+'*2*'+testsol+'*(1-pow('+testsol+',2))/'+str(float(hd)**2) #testsol2 = 'tanh(x[1]/' + str(float(hd)) + ')' #tanh(x[0]/hd) testsol2 = 'tanh((' + str(cos(angle)) + '*x[1]-'+ str(sin(angle)) + '*x[0])/' + str(float(hd)) + ')' #tanh(x[0]/hd) ddtestsol2 = str(cos(angle)-sin(angle))+'*2*'+testsol2+'*(1-pow('+testsol2+',2))/'+str(float(hd)**2) def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min()+0.5 < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS # PERFORM ONE ADAPTATION ITERATION for iii in range(Nadapt): V = FunctionSpace(mesh, "CG" ,2); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V); u2 = Function(V) bc = DirichletBC(V, Expression(testsol), boundary) bc2 = DirichletBC(V, Expression(testsol2), boundary) R = interpolate(Expression(ddtestsol),V) R2 = interpolate(Expression(ddtestsol2),V) a = inner(grad(dis), grad(dus))*dx L = R*dus*dx L2 = R2*dus*dx solve(a == L, u, bc) solve(a == L2, u2, bc2) H = metric_pnorm(u , eta, max_edge_length=1., max_edge_ratio=50); #Mp = project(H, TensorFunctionSpace(mesh, "CG", 1)) H2 = metric_pnorm(u2, eta, max_edge_length=1., max_edge_ratio=50); #Mp2 = project(H2, TensorFunctionSpace(mesh, "CG", 1)) H3 = metric_ellipse(H,H2); Mp3 = project(H3, TensorFunctionSpace(mesh, "CG", 1)) print("H11: %0.0f, H22: %0.0f, V: %0.0f,E: %0.0f" % (assemble(abs(H3[0,0])*dx),assemble(abs(H3[1,1])*dx),mesh.num_vertices(),mesh.num_cells())) startTime = time() if iii != 6: # mesh2 = Mesh(adapt(Mp2)) mesh = Mesh(adapt(Mp3)) # mesh3 = adapt(Mp) print("total time was %0.1fs" % (time()-startTime)) # PLOT MESH figure(1); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells()); axis('equal'); axis('off'); box('off') #figure(2); triplot(mesh2.coordinates()[:,0],mesh2.coordinates()[:,1],mesh2.cells()) #mesh = mesh2 #figure(3); triplot(mesh3.coordinates()[:,0],mesh3.coordinates()[:,1],mesh3.cells()) #mesh = mesh3 figure(4); testf = interpolate(u2,FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100) show()
def meshplot(x, y, z, levels=None): """ Plots values on 2D unstructured mesh """ r = (np.max(x) - np.min(x)) / (np.max(y) - np.min(y)) rx = r / np.sqrt(1 + r**2) ry = 1 / np.sqrt(1 + r**2) f = pylab.figure(figsize=(15 * rx, 15 * ry)) p = pylab.tricontourf(x, 200000 - y, z, 125, levels=levels, extend='neither') pylab.axis('image') """ tmp = np.vstack((x,-y,z)) print x[3] np.savetxt('tmp.txt',tmp.T) """ fout = open('kernel.txt', 'w') for i in range(0, 320000): if (x[i] > 600000 and x[i] < 1000000 and y[i] > 140000): fout.write( str(x[i]) + ' ' + str(200000 - y[i]) + ' ' + str(z[i]) + '\n') fout.close() return f, p
def meshplot(x, y, z, levels=None): """ Plots values on 2D unstructured mesh """ r = (np.max(x) - np.min(x)) / (np.max(y) - np.min(y)) rx = r / np.sqrt(1 + r**2) ry = 1 / np.sqrt(1 + r**2) f = pylab.figure(figsize=(15 * rx, 15 * ry)) p = pylab.tricontourf(x, y, z, 125, levels=levels, extend='neither') pylab.axis('image') return f, p
def meshplot(x, y, z): """Plots values on 2-D unstructured mesh.""" import pylab r = (max(x) - min(x))/(max(y) - min(y)) rx = r/np.sqrt(1 + r**2) ry = 1/np.sqrt(1 + r**2) f = pylab.figure(figsize=(10*rx, 10*ry)) p = pylab.tricontourf(x, y, z, 125) pylab.axis('image') return f, p
def meshplot(x, y, z): """ Plots values on 2D unstructured mesh """ import pylab r = (max(x) - min(x))/(max(y) - min(y)) rx = r/np.sqrt(1 + r**2) ry = 1/np.sqrt(1 + r**2) f = pylab.figure(figsize=(10*rx, 10*ry)) p = pylab.tricontourf(x, y, z, 125) pylab.axis('image') return f, p
inj_params = dict(mass1=2e6, mass2=1e6, distance=10e3, beta=-0.073604, inclination=0.6459, polarization=1.7436, n_modes=5, f_low=1e-3, n_samples=32768, log_samples=True) inj_params['lambda'] = 3.4435 # doh injection = flare.generate_injection_reim(**inj_params) # calculate the log-likelihood for a bunch # of random masses around the injected masses m1s_ = np.random.normal(inj_params['mass1'], 50, 100) m2s_ = np.random.normal(inj_params['mass2'], 50, 100) m1s = np.where(m1s_ > m2s_, m1s_, m2s_) m2s = np.where(m1s_ > m2s_, m2s_, m1s_) lls = [] for m1, m2 in zip(m1s, m2s): template_params = inj_params.copy() template_params['mass1'] = m1 template_params['mass2'] = m2 template_params['injection'] = injection lls.append(flare.calculate_logl_reim(**template_params)) # plot the likelihood lls = np.array(lls) sorter = np.argsort(lls) pl.tricontourf(m1s[sorter], m2s[sorter], np.exp(lls[sorter]), 100, cmap='gnuplot2_r') pl.colorbar() pl.axvline(inj_params['mass1'], color='#00ff00') pl.axhline(inj_params['mass2'], color='#00ff00') pl.xlabel('Mass 1') pl.ylabel('Mass 2') pl.show()
def minimal_example(width=2e-2, Nadapt=10, eta=0.01): ### CONSTANTS meshsz = 40 hd = Constant(width) ### SETUP MESH mesh = RectangleMesh(Point(-0.5, -0.5), Point(0.5, 0.5), 1 * meshsz, 1 * meshsz, "left/right") ### DERIVE FORCING TERM angle = pi / 8 #rand*pi/2 sx = Symbol('sx') sy = Symbol('sy') width_ = Symbol('ww') aa = Symbol('aa') testsol = pytanh((sx * pycos(aa) + sy * pysin(aa)) / width_) ddtestsol = str(diff(testsol, sx, sx) + diff(testsol, sy, sy)).replace( 'sx', 'x[0]').replace('sy', 'x[1]') #replace ** with pow ddtestsol = ddtestsol.replace( 'tanh((x[0]*sin(aa) + x[1]*cos(aa))/ww)**2', 'pow(tanh((x[0]*sin(aa) + x[1]*cos(aa))/ww),2.)') ddtestsol = ddtestsol.replace('cos(aa)**2', 'pow(cos(aa),2.)').replace( 'sin(aa)**2', 'pow(sin(aa),2.)').replace('ww**2', '(ww*ww)') #insert vaulues ddtestsol = ddtestsol.replace('aa', str(angle)).replace('ww', str(width)) testsol = str(testsol).replace('sx', 'x[0]').replace('sy', 'x[1]').replace( 'aa', str(angle)).replace('ww', str(width)) ddtestsol = "-(" + ddtestsol + ")" def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min()+0.5 < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = FunctionSpace(mesh, "CG", 2) dis = TrialFunction(V) dus = TestFunction(V) u = Function(V) a = inner(grad(dis), grad(dus)) * dx L = Expression(ddtestsol) * dus * dx bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) startTime = time() H = metric_pnorm(u, eta, max_edge_length=3., max_edge_ratio=None) H = logproject(H) if iii != Nadapt - 1: mesh = adapt(H) L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') log( INFO + 1, "total (adapt+metric) time was %0.1fs, L2error=%0.0e, nodes: %0.0f" % (time() - startTime, L2error, mesh.num_vertices())) # # PLOT MESH # figure() coords = mesh.coordinates().transpose() # triplot(coords[0],coords[1],mesh.cells(),linewidth=0.1) # #savefig('mesh.png',dpi=300) #savefig('mesh.eps'); figure() #solution testf = interpolate(Expression(testsol), FunctionSpace(mesh, 'CG', 1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG", 1)) zz = testf.vector().array()[vtx2dof] hh = tricontourf(coords[0], coords[1], mesh.cells(), zz, 100) colorbar(hh) # savefig('solution.png',dpi=300) #savefig('solution.eps'); figure() #analytical solution testfe = interpolate(u, FunctionSpace(mesh, 'CG', 1)) zz = testfe.vector().array()[vtx2dof] hh = tricontourf(coords[0], coords[1], mesh.cells(), zz, 100) colorbar(hh) #savefig('analyt.png',dpi=300) #savefig('analyt.eps'); figure() #error zz -= testf.vector().array()[vtx2dof] zz[zz == 1] -= 1e-16 hh = tricontourf(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), zz, 100, cmap=get_cmap('binary')) colorbar(hh) hold('on') triplot(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), color='r', linewidth=0.5) hold('off') axis('equal') box('off') title('error') show()
def adv_convergence(width=2e-2, delta=1e-2, relp=1, Nadapt=10, use_adapt=True, problem=3, outname='', use_reform=False, CGorderL=[2, 3], noplot=False, Lx=3.): ### SETUP SOLUTION sy = Symbol('sy') width_ = Symbol('ww') if problem == 3: stepfunc = 0.5 + 165. / 104. / width_ * sy - 20. / 13. / width_**3 * sy**3 - 102. / 13. / width_**5 * sy**5 + 240. / 13. / width_**7 * sy**7 elif problem == 2: stepfunc = 0.5 + 15. / 8. / width_ * sy - 5. / width_**3 * sy**3 + 6. / width_**5 * sy**5 elif problem == 1: stepfunc = 0.5 + 1.5 / width_ * sy - 2 / width_**3 * sy**3 stepfunc = str(stepfunc).replace('sy', 'x[1]').replace('x[1]**2', '(x[1]*x[1])') #REPLACE ** with pow stepfunc = stepfunc.replace('x[1]**3', 'pow(x[1],3.)') stepfunc = stepfunc.replace('x[1]**5', 'pow(x[1],5.)') stepfunc = stepfunc.replace('x[1]**7', 'pow(x[1],7.)') testsol = '(-ww/2 < x[1] && x[1] < ww/2 ? ' + stepfunc + ' : 0) + (ww/2<x[1] ? 1 : 0)' testsol = testsol.replace('ww**2', '(ww*ww)').replace( 'ww**3', 'pow(ww,3.)').replace('ww**5', 'pow(ww,5.)').replace('ww**7', 'pow(ww,7.)') testsol = testsol.replace('ww', str(width)) dp = Constant(1.) fac = Constant(1 + 2. * delta) delta = Constant(delta) def left(x, on_boundary): return x[0] + Lx / 2. < DOLFIN_EPS def right(x, on_boundary): return x[0] - Lx / 2. > -DOLFIN_EPS def top_bottom(x, on_boundary): return x[1] - 0.5 > -DOLFIN_EPS or x[1] + 0.5 < DOLFIN_EPS class Inletbnd(SubDomain): def inside(self, x, on_boundary): return x[0] + Lx / 2. < DOLFIN_EPS for CGorder in [2]: #CGorderL: dofs = [] L2errors = [] for eta in 0.04 * pyexp2(-array(range(9)) * pylog(2) / 2): ### SETUP MESH meshsz = int( round(80 * 0.005 / (eta * (bool(use_adapt) == False) + 0.05 * (bool(use_adapt) == True)))) if not bool(use_adapt) and meshsz > 80: continue mesh = RectangleMesh(-Lx / 2., -0.5, Lx / 2., 0.5, meshsz, meshsz, "left/right") # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = VectorFunctionSpace(mesh, "CG", CGorder) Q = FunctionSpace(mesh, "CG", CGorder - 1) W = V * Q (u, p) = TrialFunctions(W) (v, q) = TestFunctions(W) alpha = Expression( "-0.25<x[0] && x[0]<0.25 && 0. < x[1] ? 1e4 : 0") boundaries = FacetFunction("size_t", mesh) #outletbnd = Outletbnd() inletbnd = Inletbnd() boundaries.set_all(0) #outletbnd.mark(boundaries, 1) inletbnd.mark(boundaries, 1) ds = Measure("ds")[boundaries] bc0 = DirichletBC(W.sub(0), Constant((0., 0.)), top_bottom) bc1 = DirichletBC(W.sub(1), dp, left) bc2 = DirichletBC(W.sub(1), Constant(0), right) bc3 = DirichletBC(W.sub(0).sub(1), Constant(0.), left) bc4 = DirichletBC(W.sub(0).sub(1), Constant(0.), right) bcs = [bc0, bc1, bc2, bc3, bc4] bndterm = dp * dot(v, Constant((-1., 0.))) * ds(1) a = eta * inner(grad(u), grad( v)) * dx - div(v) * p * dx + q * div(u) * dx + alpha * dot( u, v) * dx #+bndterm L = inner(Constant((0., 0.)), v) * dx - bndterm U = Function(W) solve(a == L, U, bcs) u, ps = U.split() #SOLVE CONCENTRATION mm = mesh_metric2(mesh) vdir = u / sqrt(inner(u, u) + DOLFIN_EPS) if iii == 0 or use_reform == False: Q2 = FunctionSpace(mesh, 'CG', 2) c = Function(Q2) q = TestFunction(Q2) p = TrialFunction(Q2) newq = (q + dot(vdir, dot(mm, vdir)) * inner(grad(q), vdir) ) #SUPG if use_reform: F = newq * (fac / ( (1 + exp(-c))**2) * exp(-c)) * inner(grad(c), u) * dx J = derivative(F, c) bc = DirichletBC( Q2, Expression("-log(" + str(float(fac)) + "/(" + testsol + "+" + str(float(delta)) + ")-1)"), left) # bc = DirichletBC(Q, -ln(fac/(Expression(testsol)+delta)-1), left) problem = NonlinearVariationalProblem(F, c, bc, J) solver = NonlinearVariationalSolver(problem) solver.parameters["newton_solver"][ "relaxation_parameter"] = relp solver.solve() else: a2 = newq * inner(grad(p), u) * dx bc = DirichletBC(Q2, Expression(testsol), left) L2 = Constant(0.) * q * dx solve(a2 == L2, c, bc) if (not bool(use_adapt)) or iii == Nadapt - 1: break um = project(sqrt(inner(u, u)), FunctionSpace(mesh, 'CG', 2)) H = metric_pnorm(um, eta, max_edge_ratio=1 + 49 * (use_adapt != 2), p=2) H2 = metric_pnorm(c, eta, max_edge_ratio=1 + 49 * (use_adapt != 2), p=2) #H3 = metric_pnorm(ps , eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) H4 = metric_ellipse(H, H2) #H5 = metric_ellipse(H3,H4,mesh) mesh = adapt(H4) if use_reform: Q2 = FunctionSpace(mesh, 'CG', 2) c = interpolate(c, Q2) if use_reform: c = project(fac / (1 + exp(-c)) - delta, FunctionSpace(mesh, 'CG', 2)) L2error = bnderror(c, Expression(testsol), ds) dofs.append(len(c.vector().array()) + len(U.vector().array())) L2errors.append(L2error) # fid = open("DOFS_L2errors_mesh_c_CG"+str(CGorder)+outname+".mpy",'w') # pickle.dump([dofs[0],L2errors[0],c.vector().array().min(),c.vector().array().max()-1,mesh.cells(),mesh.coordinates(),c.vector().array()],fid) # fid.close(); log( INFO + 1, "%1dX ADAPT<->SOLVE complete: DOF=%5d, error=%0.0e, min(c)=%0.0e,max(c)-1=%0.0e" % (Nadapt, dofs[len(dofs) - 1], L2error, c.vector().array().min(), c.vector().array().max() - 1)) # PLOT MESH + solution figure() testf = interpolate(c, FunctionSpace(mesh, 'CG', 1)) testfe = interpolate(Expression(testsol), FunctionSpace(mesh, 'CG', 1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG", 1)) zz = testf.vector().array()[vtx2dof] zz[zz == 1] -= 1e-16 hh = tricontourf(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), zz, 100, cmap=get_cmap('binary')) colorbar(hh) hold('on') triplot(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), color='r', linewidth=0.5) hold('off') axis('equal') box('off') # savefig(outname+'final_mesh_CG2.png',dpi=300) #; savefig('outname+final_mesh_CG2.eps',dpi=300) #PLOT ERROR figure() xe = interpolate(Expression("x[0]"), FunctionSpace(mesh, 'CG', 1)).vector().array() ye = interpolate(Expression("x[1]"), FunctionSpace(mesh, 'CG', 1)).vector().array() I = xe - Lx / 2 > -DOLFIN_EPS I2 = ye[I].argsort() pyplot(ye[I][I2], testf.vector().array()[I][I2] - testfe.vector().array()[I][I2], '-b') ylabel('error') # PLOT L2error graph figure() pyloglog(dofs, L2errors, '-b.', linewidth=2, markersize=16) xlabel('Degree of freedoms') ylabel('L2 error') # SAVE SOLUTION dofs = array(dofs) L2errors = array(L2errors) fid = open("DOFS_L2errors_CG" + str(CGorder) + outname + ".mpy", 'w') pickle.dump([dofs, L2errors], fid) fid.close() # #show() # #LOAD SAVED SOLUTIONS # fid = open("DOFS_L2errors_CG2"+outname+".mpy",'r') # [dofs,L2errors] = pickle.load(fid) # fid.close() # # PERFORM FITS ON LAST THREE POINTS NfitP = 5 I = array(range(len(dofs) - NfitP, len(dofs))) slope, ints = polyfit(pylog(dofs[I]), pylog(L2errors[I]), 1) fid = open("DOFS_L2errors_CG2_fit" + outname + ".mpy", 'w') pickle.dump([dofs, L2errors, slope, ints], fid) fid.close() #PLOT THEM TOGETHER if CGorderL != [2]: fid = open("DOFS_L2errors_CG3.mpy", 'r') [dofs_old, L2errors_old] = pickle.load(fid) fid.close() slope2, ints2 = polyfit(pylog(dofs_old[I]), pylog(L2errors_old[I]), 1) figure() pyloglog(dofs, L2errors, '-b.', dofs_old, L2errors_old, '--b.', linewidth=2, markersize=16) hold('on') pyloglog(dofs, pyexp2(ints) * dofs**slope, '-r', dofs_old, pyexp2(ints2) * dofs_old**slope2, '--r', linewidth=1) hold('off') xlabel('Degree of freedoms') ylabel('L2 error') legend([ 'CG2', 'CG3', "%0.2f*log(DOFs)" % slope, "%0.2f*log(DOFs)" % slope2 ]) #legend(['new data','old_data']) # savefig('comparison.png',dpi=300) #savefig('comparison.eps'); if not noplot: show()
#rsub = P.where(r_arr[0, :] >= 5.0)[0] #levels = P.arange(1.0, psi_max + delta_psi, delta_psi) * i_fact #P.contour(r_arr[:, rsub], z_arr[:, rsub], psi[:, rsub], # levels=levels, colors='gray') P.plot(r_floops, z_floops, 'ro') #P.plot(-r_floops, z_floops, 'ro') if 'tris' not in dir(): rzt, tris, pt = t3dinp('hitpops.05.t3d') #do_conf = False do_conf = True if do_conf: P.tricontourf(rzt[:, 0], rzt[:, 1], tris, beta, 1001, zorder=0) cticks = P.linspace(0.0, 0.2, 5) P.colorbar(ticks=cticks, format='%.2f') P.jet() #no_text = True no_text = False # whether to annotate in MA or MW show_MA = True if not no_text: # annotate coil powers for ii in xrange(n_b_coils): if i_floops[ii] >= 0: signum = '+' else:
magU = np.sqrt(U*U+V*V) factor = 1 - int(np.log10(magU.max())) magU *= 10**factor print "Magnitude of U (min, max):", magU.min(), magU.max() import matplotlib.tri as tri triang = tri.Triangulation(X,Y) xmid = X[triang.triangles].mean(axis=1) ymid = Y[triang.triangles].mean(axis=1) mask = np.where(np.square(xmid-d) + np.square(ymid) < np.square(1), 1, 0) triang.set_mask(mask) lev = np.linspace(0, (int(magU.max()*10) + 1.)/10, 11) cmap = py.cm.get_cmap('coolwarm') CF = py.tricontourf(triang, magU, cmap=cmap, levels=lev) from matplotlib.mlab import griddata N = 50 interp = 'linear' xi = np.linspace(-r, r, 2*N) yi = np.linspace(0 , r, N ) U = griddata(X,Y,U,xi,yi,interp=interp) V = griddata(X,Y,V,xi,yi,interp=interp) py.streamplot(xi, yi, U, V, color='k', density=1.5, minlength=.5, arrowstyle='->') py.text(1.5, 1.7, r'$u_{i1}\times10^{' + str(factor) + r'}$') py.text(.2, .8, r'$R_1, T_1$', zorder=50) py.text(-1.6, 1.7, r'$R_2, T_2$') py.xlim(-r-.01,r+.01) py.ylim(0,r+.01)
element_data -= 1 element_data = element_data.astype(int) element_id, nn0, nn1, nn2, _ = element_data.T #node_data.astype(float) node_id, x, y, node_type = node_data.T verts = [[(x[n0], y[n0]), (x[n1], y[n1]), (x[n2], y[n2])] for n0, n1, n2 in zip(nn0, nn1, nn2)] #verts = [[[x[n0], x[n1], x[n2]], [y[n0], y[n1], y[n2]]] for n0, n1, n2 in zip(nn0, nn1, nn2)] verts = np.array(verts) _, colorby = np.loadtxt( "cont2_px0.588889py0.722222ix0.100000iy0.455556e_result.mat").T assert len(colorby) % len(x) == 0 res_list = np.hsplit(colorby, len(colorby) / len(x)) plt.tricontourf(x, y, res_list[-1]) plt.show() # # need to interpolate to cell centers to do this # coll = PolyCollection(verts, # array=colorby, linewidths=0, # edgecolors='none') # plt.gca().add_collection(coll) # plt.gca().autoscale_view() # plt.gca().set_aspect(1.0) # plt.gcf().colorbar(coll, ax=plt.gca()) # plt.show()
def minimal_example(width=2e-2, Nadapt=10, eta = 0.01): ### CONSTANTS meshsz = 40 hd = Constant(width) ### SETUP MESH mesh = RectangleMesh(Point(-0.5,-0.5),Point(0.5,0.5),1*meshsz,1*meshsz,"left/right") ### DERIVE FORCING TERM angle = pi/8 #rand*pi/2 sx = Symbol('sx'); sy = Symbol('sy'); width_ = Symbol('ww'); aa = Symbol('aa') testsol = pytanh((sx*pycos(aa)+sy*pysin(aa))/width_) ddtestsol = str(diff(testsol,sx,sx)+diff(testsol,sy,sy)).replace('sx','x[0]').replace('sy','x[1]') #replace ** with pow ddtestsol = ddtestsol.replace('tanh((x[0]*sin(aa) + x[1]*cos(aa))/ww)**2','pow(tanh((x[0]*sin(aa) + x[1]*cos(aa))/ww),2.)') ddtestsol = ddtestsol.replace('cos(aa)**2','pow(cos(aa),2.)').replace('sin(aa)**2','pow(sin(aa),2.)').replace('ww**2','(ww*ww)') #insert vaulues ddtestsol = ddtestsol.replace('aa',str(angle)).replace('ww',str(width)) testsol = str(testsol).replace('sx','x[0]').replace('sy','x[1]').replace('aa',str(angle)).replace('ww',str(width)) ddtestsol = "-("+ddtestsol+")" def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min()+0.5 < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = FunctionSpace(mesh, "CG" ,2); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V) a = inner(grad(dis), grad(dus))*dx L = Expression(ddtestsol)*dus*dx bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) startTime = time() H = metric_pnorm(u, eta, max_edge_length=3., max_edge_ratio=None) H = logproject(H) if iii != Nadapt-1: mesh = adapt(H) L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') log(INFO+1,"total (adapt+metric) time was %0.1fs, L2error=%0.0e, nodes: %0.0f" % (time()-startTime,L2error,mesh.num_vertices())) # # PLOT MESH # figure() coords = mesh.coordinates().transpose() # triplot(coords[0],coords[1],mesh.cells(),linewidth=0.1) # #savefig('mesh.png',dpi=300) #savefig('mesh.eps'); figure() #solution testf = interpolate(Expression(testsol),FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof] hh=tricontourf(coords[0],coords[1],mesh.cells(),zz,100) colorbar(hh) # savefig('solution.png',dpi=300) #savefig('solution.eps'); figure() #analytical solution testfe = interpolate(u,FunctionSpace(mesh,'CG',1)) zz = testfe.vector().array()[vtx2dof] hh=tricontourf(coords[0],coords[1],mesh.cells(),zz,100) colorbar(hh) #savefig('analyt.png',dpi=300) #savefig('analyt.eps'); figure() #error zz -= testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh) hold('on'); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),color='r',linewidth=0.5); hold('off') axis('equal'); box('off'); title('error') show()
plt.close('all') width = 3.487 * 2 height = width / 1.618 / 2 fig = plt.figure(num=1, figsize=(width, height), facecolor='w', edgecolor='k') fig.subplots_adjust(left=0.073, right=1.05, top=.725, bottom=0.2) #fig.set_size_inches(width, height) #plt.draw() #fig, ax = plt.subplots(constrained_layout=True) dLdt = np.array(dLdt) F = np.array(F) plt.tricontour(S, F / 1e3, dLdt / 1e3, [0], colors='k', linestyles='--') c = plt.tricontourf(S, F / 1e3, dLdt / 1e3, v, cmap='bwr_r', norm=norm, extend='both') #plt.scatter([-0.03],[4],s=50,c=[351.5094769326309 /1e3],cmap='bwr_r',norm=norm,marker='o',edgecolor='k') #plt.scatter([-0.01],[2],s=50,c=[-2137.5210508252835/1e3],cmap='bwr_r',norm=norm,marker='o',edgecolor='k') #plt.scatter([0.0],[5],s=50,c=[487.56420334626046/1e3],cmap='bwr_r',norm=norm,marker='o',edgecolor='k') cbar = plt.colorbar(extend='both', ticks=[vmin, 0, vmax]) #plt.clim([vmin,vmax]) cbar.ax.set_yticklabels([vmin, 0, vmax]) cbar.set_label(r'$dL/dt$ (km/a)') #plt.text(-0.0+surf_slope+0.005-surf_slope,4.5,'Advance',fontsize=12,weight='bold') #plt.text(-0.025+surf_slope-surf_slope,2.8,'Retreat',fontsize=12,weight='bold') #plt.text(-0.0375,1.0,'Collapse',fontsize=12,weight='bold',rotation=90)
##cmap = ccm.cmaps['CubicYF'] ## plot the data if iunst == 1: nodefile, elefile = GetNodeEleFile(inputfile) nnode, nodelocs = ReadNodeLocs(nodefile) nele, elenodes = ReadElems(elefile) x = nodelocs[:,0] y = nodelocs[:,1] z = mat[plotvar[ivar]] import matplotlib.tri as tri grid = tri.Triangulation(x, y, triangles=elenodes, mask=None) CSF = plt.tricontourf(grid,z,256,cmap=cmap) #specify cmin and cmax - Kelley #gridlines = plt.triplot(grid,color='k') else: x,y = GetStrucGrid(inputfile) xi, yi = np.meshgrid(x,y) z = mat[plotvar[ivar]] CSF = plt.contourf(xi,yi,z,256,cmap=cmap) #minz=z.min() #maxz=z.max() #print plotvar[ivar],'Value Range', minz,maxz ## square axes #plt.axis('equal')
injection = flare.generate_injection_reim(**inj_params) # calculate the log-likelihood for a bunch # of random masses around the injected masses m1s_ = np.random.normal(inj_params['mass1'], 50, 100) m2s_ = np.random.normal(inj_params['mass2'], 50, 100) m1s = np.where(m1s_ > m2s_, m1s_, m2s_) m2s = np.where(m1s_ > m2s_, m2s_, m1s_) lls = [] for m1, m2 in zip(m1s, m2s): template_params = inj_params.copy() template_params['mass1'] = m1 template_params['mass2'] = m2 template_params['injection'] = injection lls.append(flare.calculate_logl_reim(**template_params)) # plot the likelihood lls = np.array(lls) sorter = np.argsort(lls) pl.tricontourf(m1s[sorter], m2s[sorter], np.exp(lls[sorter]), 100, cmap='gnuplot2_r') pl.colorbar() pl.axvline(inj_params['mass1'], color='#00ff00') pl.axhline(inj_params['mass2'], color='#00ff00') pl.xlabel('Mass 1') pl.ylabel('Mass 2') pl.show()
import pylab class MyDesign(LHSDesign): spec = (('x', (0, 6.28, 'uniform', 10)), ('y', (0, 6.28, 'uniform', 10))) samples = 50 class MyModel: # model can be any class, but it is required to have 'solve' method # which takes sample `d` as argument and returns dict of results `res` def solve(self, d): x, y = d.x, d.y res = {'F': sin(x) * cos(y), 'G': x * y} return res # Evaluate experiments and dump everything to 'test' directory: ex = Experiment(MyDesign(), MyModel(), dirname='test') ex.run() # Plot 'F' x = ex.design.x y = ex.design.y F = ex.result.F pylab.tricontour(x, y, F, levels=14, linewidths=0.5, colors='k') cntr = pylab.tricontourf(x, y, F, levels=14, cmap="RdBu_r") pylab.colorbar(cntr) pylab.plot(x, y, 'ko', ms=3) pylab.title('$\sin(x)\cos(y)$\n (%d LHS samples)' % ex.design.samples)
def plot2D(array, marker='', colour='', vmin=0, vmax=200, cbar=3, fig=1, figsize=None, aspect="equal", name="", fname="Cmax", dir=this_dir, axes=['on', 'off']): """ Plots a surface represented explicitly by a 2D array XY or implicitly by a set of 3D points XYZ """ cmap = "Greys_r" norm = plt.Normalize(vmin=vmin, vmax=vmax) if dir != "": fname = '%s/%s' % (dir, fname) ext = ".png" if fig != 0: plt.figure(fig, figsize=figsize) plt.title("%s gamut" % name) plt.xlabel("H") plt.ylabel("L", rotation='horizontal') plt.xlim([0, 360]) plt.ylim([0, 100]) if array.shape[1] == 3: # array is the 3D surface of a 2D function L = array[:, 0] C = array[:, 1] H = array[:, 2] plt.tricontourf(H, L, C, cmap=cmap, norm=norm) if marker != '': ax = plt.gca() if len(colour) > 0: ax.plot(H, L, marker, c=colour) else: #ax.plot(H,L,marker,color=convert.clip3(convert.LCH2RGB(L,C,H)).tolist()) for h, l, c in zip(H, L, array): ax.plot(h, l, marker, color=convert.clip3( convert.LCH2RGB(c[0], c[1], c[2]))) plt.gca().set_aspect(aspect) else: # array is a 2D map plt.imshow(array, origin='lower', extent=[H_min, H_max, L_min, L_max], aspect=aspect, interpolation='nearest', cmap=cmap, norm=norm) locator = ticker.MultipleLocator(60) plt.gca().xaxis.set_major_locator(locator) if cbar > 0: cax = make_axes_locatable(plt.gca()).append_axes("right", size="%.f%%" % cbar, pad=0.10) cb = plt.colorbar(plt.gci(), cax=cax) cb.locator = ticker.MultipleLocator(50) cb.update_ticks() cb.set_label("Cmax") if dir != "" and 'on' in axes: print("writing %s" % (fname + "_axon" + ext)) plt.savefig(fname + "_axon" + ext, dpi=None, bbox_inches='tight') if dir != "" and 'off' in axes and array.shape[1] > 3: print("writing %s" % (fname + "_axoff" + ext)) plt.imsave(arr=array, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax, fname=fname + "_axoff" + ext)
def check_metric_ellipse(width=2e-2, eta=0.02, Nadapt=6): set_log_level(WARNING) parameters["allow_extrapolation"] = True ### CONSTANTS meshsz = 40 hd = Constant(width) ### SETUP MESH mesh = RectangleMesh(-0.5, -0.5, 0.5, 0.5, 1 * meshsz, 1 * meshsz, "left/right") ### SETUP SOLUTION angle = pi / 8 #rand()*pi/2 #testsol = 'tanh(x[0]/' + str(float(hd)) + ')' #tanh(x[0]/hd) testsol = 'tanh((' + str(cos(angle)) + '*x[0]+' + str( sin(angle)) + '*x[1])/' + str(float(hd)) + ')' #tanh(x[0]/hd) ddtestsol = str(cos(angle) + sin(angle) ) + '*2*' + testsol + '*(1-pow(' + testsol + ',2))/' + str( float(hd)**2) #testsol2 = 'tanh(x[1]/' + str(float(hd)) + ')' #tanh(x[0]/hd) testsol2 = 'tanh((' + str(cos(angle)) + '*x[1]-' + str( sin(angle)) + '*x[0])/' + str(float(hd)) + ')' #tanh(x[0]/hd) ddtestsol2 = str(cos(angle) - sin( angle)) + '*2*' + testsol2 + '*(1-pow(' + testsol2 + ',2))/' + str( float(hd)**2) def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min()+0.5 < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS # PERFORM ONE ADAPTATION ITERATION for iii in range(Nadapt): V = FunctionSpace(mesh, "CG", 2) dis = TrialFunction(V) dus = TestFunction(V) u = Function(V) u2 = Function(V) bc = DirichletBC(V, Expression(testsol), boundary) bc2 = DirichletBC(V, Expression(testsol2), boundary) R = interpolate(Expression(ddtestsol), V) R2 = interpolate(Expression(ddtestsol2), V) a = inner(grad(dis), grad(dus)) * dx L = R * dus * dx L2 = R2 * dus * dx solve(a == L, u, bc) solve(a == L2, u2, bc2) H = metric_pnorm(u, eta, max_edge_length=1., max_edge_ratio=50) #Mp = project(H, TensorFunctionSpace(mesh, "CG", 1)) H2 = metric_pnorm(u2, eta, max_edge_length=1., max_edge_ratio=50) #Mp2 = project(H2, TensorFunctionSpace(mesh, "CG", 1)) H3 = metric_ellipse(H, H2) Mp3 = project(H3, TensorFunctionSpace(mesh, "CG", 1)) print("H11: %0.0f, H22: %0.0f, V: %0.0f,E: %0.0f" % (assemble(abs(H3[0, 0]) * dx), assemble( abs(H3[1, 1]) * dx), mesh.num_vertices(), mesh.num_cells())) startTime = time() if iii != 6: # mesh2 = Mesh(adapt(Mp2)) mesh = Mesh(adapt(Mp3)) # mesh3 = adapt(Mp) print("total time was %0.1fs" % (time() - startTime)) # PLOT MESH figure(1) triplot(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells()) axis('equal') axis('off') box('off') #figure(2); triplot(mesh2.coordinates()[:,0],mesh2.coordinates()[:,1],mesh2.cells()) #mesh = mesh2 #figure(3); triplot(mesh3.coordinates()[:,0],mesh3.coordinates()[:,1],mesh3.cells()) #mesh = mesh3 figure(4) testf = interpolate(u2, FunctionSpace(mesh, 'CG', 1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG", 1)) zz = testf.vector().array()[vtx2dof] zz[zz == 1] -= 1e-16 tricontourf(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), zz, 100) show()
element_data -= 1 element_data = element_data.astype(int) element_id, nn0, nn1, nn2, _ = element_data.T #node_data.astype(float) node_id, x, y, node_type = node_data.T verts = [ [(x[n0], y[n0]), (x[n1], y[n1]), (x[n2], y[n2])] for n0, n1, n2 in zip(nn0, nn1, nn2) ] #verts = [[[x[n0], x[n1], x[n2]], [y[n0], y[n1], y[n2]]] for n0, n1, n2 in zip(nn0, nn1, nn2)] verts = np.array(verts) _, colorby = np.loadtxt("cont2_px0.588889py0.722222ix0.100000iy0.455556e_result.mat").T assert len(colorby) % len(x) == 0 res_list = np.hsplit(colorby, len(colorby)/len(x)) plt.tricontourf(x,y,res_list[-1]) plt.show() # # need to interpolate to cell centers to do this # coll = PolyCollection(verts, # array=colorby, linewidths=0, # edgecolors='none') # plt.gca().add_collection(coll) # plt.gca().autoscale_view() # plt.gca().set_aspect(1.0) # plt.gcf().colorbar(coll, ax=plt.gca()) # plt.show()
def maximal_example(eta_list=array([0.001]), Nadapt=5, timet=1., period=2 * pi): ### CONSTANTS ### SETUP SOLUTION #testsol = '0.1*sin(50*x+2*pi*t/T)+atan(-0.1/(2*x - sin(5*y+2*pi*t/T)))'; sx = Symbol('sx') sy = Symbol('sy') sT = Symbol('sT') st = Symbol('st') spi = Symbol('spi') testsol = 0.1 * pysin(50 * sx + 2 * spi * st / sT) + pyatan( -0.1, 2 * sx - pysin(5 * sy + 2 * spi * st / sT)) ddtestsol = str(diff(testsol, sx, sx) + diff(testsol, sy, sy)).replace( 'sx', 'x[0]').replace('sy', 'x[1]').replace('spi', 'pi') # replacing **P with pow(,P) ddtestsol = ddtestsol.replace("(2*x[0] - sin(5*x[1] + 2*pi*st/sT))**2", "pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.)") ddtestsol = ddtestsol.replace("cos(5*x[1] + 2*pi*st/sT)**2", "pow(cos(5*x[1] + 2*pi*st/sT),2.)") ddtestsol = ddtestsol.replace( "(pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.) + 0.01)**2", "pow((pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.) + 0.01),2.)") ddtestsol = ddtestsol.replace( "(1 + 0.01/pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.))**2", "pow(1 + 0.01/pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.),2.)") ddtestsol = ddtestsol.replace("(2*x[0] - sin(5*x[1] + 2*pi*st/sT))**5", "pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),5.)") #insert values ddtestsol = ddtestsol.replace('sT', str(period)).replace('st', str(timet)) testsol = str(testsol).replace('sx', 'x[0]').replace('sy', 'x[1]').replace( 'spi', 'pi').replace('sT', str(period)).replace('st', str(timet)) ddtestsol = "-(" + ddtestsol + ")" error_list = [] dof_list = [] for eta in eta_list: meshsz = 40 ### SETUP MESH # mesh = RectangleMesh(0.4,-0.1,0.6,0.3,1*meshsz,1*meshsz,"left/right") #shock # mesh = RectangleMesh(-0.75,-0.3,-0.3,0.5,1*meshsz,1*meshsz,"left/right") #waves mesh = RectangleMesh(-1.5, -0.25, 0.5, 0.75, 1 * meshsz, 1 * meshsz, "left/right") #shock+waves def boundary(x): return near(x[0],mesh.coordinates()[:,0].min()) or near(x[0],mesh.coordinates()[:,0].max()) \ or near(x[1],mesh.coordinates()[:,1].min()) or near(x[1],mesh.coordinates()[:,1].max()) # PERFORM ONE ADAPTATION ITERATION for iii in range(Nadapt): startTime = time() V = FunctionSpace(mesh, "CG", 2) dis = TrialFunction(V) dus = TestFunction(V) u = Function(V) # R = interpolate(Expression(ddtestsol),V) a = inner(grad(dis), grad(dus)) * dx L = Expression(ddtestsol) * dus * dx # bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) soltime = time() - startTime startTime = time() H = metric_pnorm(u, eta, max_edge_ratio=50, CG0H=3, p=4) metricTime = time() - startTime if iii != Nadapt - 1: mesh = adapt(H) TadaptTime = time() - startTime L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') printstr = "%5.0f elements, %0.0e L2error, adapt took %0.0f %% of the total time, (%0.0f %% of which was the metric calculation)" \ % (mesh.num_cells(),L2error,TadaptTime/(TadaptTime+soltime)*100,metricTime/TadaptTime*100) if len(eta_list) == 1: print(printstr) else: error_list.append(L2error) dof_list.append(len(u.vector().array())) print(printstr) if len(dof_list) > 1: dof_list = array(dof_list) error_list = array(error_list) figure() loglog(dof_list, error_list, '.b-', linewidth=2, markersize=16) xlabel('Degree of freedoms') ylabel('L2 error') # # PLOT MESH # figure() coords = mesh.coordinates().transpose() # triplot(coords[0],coords[1],mesh.cells(),linewidth=0.1) # #savefig('mesh.png',dpi=300) #savefig('mesh.eps'); figure() #solution testf = interpolate(Expression(testsol), FunctionSpace(mesh, 'CG', 1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG", 1)) zz = testf.vector().array()[vtx2dof] hh = tricontourf(coords[0], coords[1], mesh.cells(), zz, 100) colorbar(hh) #savefig('solution.png',dpi=300) #savefig('solution.eps'); figure() #analytical solution testfe = interpolate(u, FunctionSpace(mesh, 'CG', 1)) zz = testfe.vector().array()[vtx2dof] hh = tricontourf(coords[0], coords[1], mesh.cells(), zz, 100) colorbar(hh) #savefig('analyt.png',dpi=300) #savefig('analyt.eps'); figure() #error zz -= testf.vector().array()[vtx2dof] zz[zz == 1] -= 1e-16 hh = tricontourf(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), zz, 100, cmap=get_cmap('binary')) colorbar(hh) hold('on') triplot(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), color='r', linewidth=0.5) hold('off') axis('equal') box('off') title('error') show()
##cmap = ccm.cmaps['CubicYF'] ## plot the data if iunst == 1: nodefile, elefile = GetNodeEleFile(inputfile) nnode, nodelocs = ReadNodeLocs(nodefile) nele, elenodes = ReadElems(elefile) x = nodelocs[:, 0] y = nodelocs[:, 1] z = mat[plotvar[ivar]] import matplotlib.tri as tri grid = tri.Triangulation(x, y, triangles=elenodes, mask=None) CSF = plt.tricontourf(grid, z, 256, cmap=cmap) #specify cmin and cmax - Kelley #gridlines = plt.triplot(grid,color='k') else: x, y = GetStrucGrid(inputfile) xi, yi = np.meshgrid(x, y) z = mat[plotvar[ivar]] CSF = plt.contourf(xi, yi, z, 256, cmap=cmap) #minz=z.min() #maxz=z.max() #print plotvar[ivar],'Value Range', minz,maxz ## square axes #plt.axis('equal')
def adv_convergence(width=2e-2, delta=1e-2, relp=1, Nadapt=10, use_adapt=True, problem=3, outname='', use_reform=False, CGorderL = [2, 3], noplot=False, Lx=3.): ### SETUP SOLUTION sy = Symbol('sy'); width_ = Symbol('ww') if problem == 3: stepfunc = 0.5+165./104./width_*sy-20./13./width_**3*sy**3-102./13./width_**5*sy**5+240./13./width_**7*sy**7 elif problem == 2: stepfunc = 0.5+15./8./width_*sy-5./width_**3*sy**3+6./width_**5*sy**5 elif problem == 1: stepfunc = 0.5+1.5/width_*sy-2/width_**3*sy**3 stepfunc = str(stepfunc).replace('sy','x[1]').replace('x[1]**2','(x[1]*x[1])') #REPLACE ** with pow stepfunc = stepfunc.replace('x[1]**3','pow(x[1],3.)') stepfunc = stepfunc.replace('x[1]**5','pow(x[1],5.)') stepfunc = stepfunc.replace('x[1]**7','pow(x[1],7.)') testsol = '(-ww/2 < x[1] && x[1] < ww/2 ? ' + stepfunc +' : 0) + (ww/2<x[1] ? 1 : 0)' testsol = testsol.replace('ww**2','(ww*ww)').replace('ww**3','pow(ww,3.)').replace('ww**5','pow(ww,5.)').replace('ww**7','pow(ww,7.)') testsol = testsol.replace('ww',str(width)) dp = Constant(1.) fac = Constant(1+2.*delta) delta = Constant(delta) def left(x, on_boundary): return x[0] + Lx/2. < DOLFIN_EPS def right(x, on_boundary): return x[0] - Lx/2. > -DOLFIN_EPS def top_bottom(x, on_boundary): return x[1] - 0.5 > -DOLFIN_EPS or x[1] + 0.5 < DOLFIN_EPS class Inletbnd(SubDomain): def inside(self, x, on_boundary): return x[0] + Lx/2. < DOLFIN_EPS for CGorder in [2]: #CGorderL: dofs = [] L2errors = [] for eta in 0.04*pyexp2(-array(range(9))*pylog(2)/2): ### SETUP MESH meshsz = int(round(80*0.005/(eta*(bool(use_adapt)==False)+0.05*(bool(use_adapt)==True)))) if not bool(use_adapt) and meshsz > 80: continue mesh = RectangleMesh(-Lx/2.,-0.5,Lx/2.,0.5,meshsz,meshsz,"left/right") # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = VectorFunctionSpace(mesh, "CG", CGorder); Q = FunctionSpace(mesh, "CG", CGorder-1) W = V*Q (u, p) = TrialFunctions(W) (v, q) = TestFunctions(W) alpha = Expression("-0.25<x[0] && x[0]<0.25 && 0. < x[1] ? 1e4 : 0") boundaries = FacetFunction("size_t",mesh) #outletbnd = Outletbnd() inletbnd = Inletbnd() boundaries.set_all(0) #outletbnd.mark(boundaries, 1) inletbnd.mark(boundaries, 1) ds = Measure("ds")[boundaries] bc0 = DirichletBC(W.sub(0), Constant((0., 0.)), top_bottom) bc1 = DirichletBC(W.sub(1), dp , left) bc2 = DirichletBC(W.sub(1), Constant(0), right) bc3 = DirichletBC(W.sub(0).sub(1), Constant(0.), left) bc4 = DirichletBC(W.sub(0).sub(1), Constant(0.), right) bcs = [bc0,bc1,bc2,bc3,bc4] bndterm = dp*dot(v,Constant((-1.,0.)))*ds(1) a = eta*inner(grad(u), grad(v))*dx - div(v)*p*dx + q*div(u)*dx+alpha*dot(u,v)*dx#+bndterm L = inner(Constant((0.,0.)), v)*dx -bndterm U = Function(W) solve(a == L, U, bcs) u, ps = U.split() #SOLVE CONCENTRATION mm = mesh_metric2(mesh) vdir = u/sqrt(inner(u,u)+DOLFIN_EPS) if iii == 0 or use_reform == False: Q2 = FunctionSpace(mesh,'CG',2); c = Function(Q2) q = TestFunction(Q2); p = TrialFunction(Q2) newq = (q+dot(vdir,dot(mm,vdir))*inner(grad(q),vdir)) #SUPG if use_reform: F = newq*(fac/((1+exp(-c))**2)*exp(-c))*inner(grad(c),u)*dx J = derivative(F,c) bc = DirichletBC(Q2, Expression("-log("+str(float(fac)) +"/("+testsol+"+"+str(float(delta))+")-1)"), left) # bc = DirichletBC(Q, -ln(fac/(Expression(testsol)+delta)-1), left) problem = NonlinearVariationalProblem(F,c,bc,J) solver = NonlinearVariationalSolver(problem) solver.parameters["newton_solver"]["relaxation_parameter"] = relp solver.solve() else: a2 = newq*inner(grad(p),u)*dx bc = DirichletBC(Q2, Expression(testsol), left) L2 = Constant(0.)*q*dx solve(a2 == L2, c, bc) if (not bool(use_adapt)) or iii == Nadapt-1: break um = project(sqrt(inner(u,u)),FunctionSpace(mesh,'CG',2)) H = metric_pnorm(um, eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) H2 = metric_pnorm(c, eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) #H3 = metric_pnorm(ps , eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) H4 = metric_ellipse(H,H2) #H5 = metric_ellipse(H3,H4,mesh) mesh = adapt(H4) if use_reform: Q2 = FunctionSpace(mesh,'CG',2) c = interpolate(c,Q2) if use_reform: c = project(fac/(1+exp(-c))-delta,FunctionSpace(mesh,'CG',2)) L2error = bnderror(c,Expression(testsol),ds) dofs.append(len(c.vector().array())+len(U.vector().array())) L2errors.append(L2error) # fid = open("DOFS_L2errors_mesh_c_CG"+str(CGorder)+outname+".mpy",'w') # pickle.dump([dofs[0],L2errors[0],c.vector().array().min(),c.vector().array().max()-1,mesh.cells(),mesh.coordinates(),c.vector().array()],fid) # fid.close(); log(INFO+1,"%1dX ADAPT<->SOLVE complete: DOF=%5d, error=%0.0e, min(c)=%0.0e,max(c)-1=%0.0e" % (Nadapt, dofs[len(dofs)-1], L2error,c.vector().array().min(),c.vector().array().max()-1)) # PLOT MESH + solution figure() testf = interpolate(c ,FunctionSpace(mesh,'CG',1)) testfe = interpolate(Expression(testsol),FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh) hold('on'); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),color='r',linewidth=0.5); hold('off') axis('equal'); box('off') # savefig(outname+'final_mesh_CG2.png',dpi=300) #; savefig('outname+final_mesh_CG2.eps',dpi=300) #PLOT ERROR figure() xe = interpolate(Expression("x[0]"),FunctionSpace(mesh,'CG',1)).vector().array() ye = interpolate(Expression("x[1]"),FunctionSpace(mesh,'CG',1)).vector().array() I = xe - Lx/2 > -DOLFIN_EPS; I2 = ye[I].argsort() pyplot(ye[I][I2],testf.vector().array()[I][I2]-testfe.vector().array()[I][I2],'-b'); ylabel('error') # PLOT L2error graph figure() pyloglog(dofs,L2errors,'-b.',linewidth=2,markersize=16); xlabel('Degree of freedoms'); ylabel('L2 error') # SAVE SOLUTION dofs = array(dofs); L2errors = array(L2errors) fid = open("DOFS_L2errors_CG"+str(CGorder)+outname+".mpy",'w') pickle.dump([dofs,L2errors],fid) fid.close(); # #show() # #LOAD SAVED SOLUTIONS # fid = open("DOFS_L2errors_CG2"+outname+".mpy",'r') # [dofs,L2errors] = pickle.load(fid) # fid.close() # # PERFORM FITS ON LAST THREE POINTS NfitP = 5 I = array(range(len(dofs)-NfitP,len(dofs))) slope,ints = polyfit(pylog(dofs[I]), pylog(L2errors[I]), 1) fid = open("DOFS_L2errors_CG2_fit"+outname+".mpy",'w') pickle.dump([dofs,L2errors,slope,ints],fid) fid.close() #PLOT THEM TOGETHER if CGorderL != [2]: fid = open("DOFS_L2errors_CG3.mpy",'r') [dofs_old,L2errors_old] = pickle.load(fid) fid.close() slope2,ints2 = polyfit(pylog(dofs_old[I]), pylog(L2errors_old[I]), 1) figure() pyloglog(dofs,L2errors,'-b.',dofs_old,L2errors_old,'--b.',linewidth=2,markersize=16) hold('on'); pyloglog(dofs,pyexp2(ints)*dofs**slope,'-r',dofs_old,pyexp2(ints2)*dofs_old**slope2,'--r',linewidth=1); hold('off') xlabel('Degree of freedoms'); ylabel('L2 error') legend(['CG2','CG3',"%0.2f*log(DOFs)" % slope, "%0.2f*log(DOFs)" % slope2]) #legend(['new data','old_data']) # savefig('comparison.png',dpi=300) #savefig('comparison.eps'); if not noplot: show()
def ellipse_convergence(asp=2,width=1e-2, Nadapt=10, eta_list=0.04*pyexp2(-array(range(15))*pylog(2)/2), \ use_adapt=True, problem=2, outname='', CGorderL = [2, 3], noplot=False, octaveimpl=False): ### SETUP SOLUTION sx = Symbol('sx'); sy = Symbol('sy'); width_ = Symbol('ww'); asp_ = Symbol('a') rrpy = pysqrt(sx*sx/asp_+sy*sy*asp_) if problem == 2: stepfunc = 0.5+165./104./width_*(rrpy-0.25)-20./13./width_**3*(rrpy-0.25)**3-102./13./width_**5*(rrpy-0.25)**5+240./13./width_**7*(rrpy-0.25)**7 elif problem == 1: stepfunc = 0.5+15./8./width_*(rrpy-0.25)-5./width_**3*(rrpy-0.25)**3+6./width_**5*(rrpy-0.25)**5 else: stepfunc = 0.5+1.5/width_*(rrpy-0.25)-2/width_**3*(rrpy-0.25)**3 ddstepfunc = str(diff(stepfunc,sx,sx)+diff(stepfunc,sy,sy)).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') stepfunc = str(stepfunc).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') #REPLACE ** with pow stepfunc = stepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(1/2)','sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a)') ddstepfunc = ddstepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(1/2)','sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a)') ddstepfunc = ddstepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(3/2)','pow(a*x[1]*x[1]+x[0]*x[0]/a,1.5)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**2','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,2.)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,3.)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**4','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,4.)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**5','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,5.)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**6','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,6.)') stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*x[1]*x[1] + x[0]*x[0]/a) - 0.25,3.)') stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**5','pow(sqrt(a*x[1]*x[1] + x[0]*x[0]/a) - 0.25,5.)') stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**7','pow(sqrt(a*x[1]*x[1] + x[0]*x[0]/a) - 0.25,7.)') testsol = '(0.25-ww/2<sqrt(x[0]*x[0]/a+x[1]*x[1]*a) && sqrt(x[0]*x[0]/a+x[1]*x[1]*a) < 0.25+ww/2 ? (' + stepfunc + ') : 0) + (0.25+ww/2<sqrt(x[0]*x[0]/a+x[1]*x[1]*a) ? 1 : 0)' # testsol = '(0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + stepfunc + ')) : (0.25<sqrt(x[0]*x[0]+x[1]*x[1]) ? 1 : 0)' ddtestsol = '0.25-ww/2<sqrt(x[0]*x[0]/a+x[1]*x[1]*a) && sqrt(x[0]*x[0]/a+x[1]*x[1]*a) < 0.25+ww/2 ? (' + ddstepfunc + ') : 0' # A = array([[0.5,0.5**3,0.5**5],[1,3*0.5**2,5*0.5**4],[0,6*0.5,20*0.5**3]]); b = array([0.5,0,0]) # from numpy.linalg import solve as pysolve #15/8,-5,6 # X = pysolve(A,b); from numpy import linspace; xx = linspace(-0.5,0.5,100) # from pylab import plot as pyplot; pyplot(xx,X[0]*xx+X[1]*xx**3+X[2]*xx**5,'-b') # rrpy = pysqrt(sx*sx+sy*sy) # # ddstepfunc = str(diff(stepfunc,sx,sx)+diff(stepfunc,sy,sy)).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') # stepfunc = str(stepfunc).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') # #REPLACE ** with pow # ddstepfunc = ddstepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(3/2)','pow(a*x[1]*x[1]+x[0]*x[0]/a,1.5)') # ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**2','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,2.)') # ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,3.)') # ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**4','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,4.)') # stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,3.)') # stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**5','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,5.)') # testsol = '(0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + stepfunc + ') : 0) + (0.25+ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) ? 1 : 0)' ## testsol = '(0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + stepfunc + ')) : (0.25<sqrt(x[0]*x[0]+x[1]*x[1]) ? 1 : 0)' # ddtestsol = '0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + ddstepfunc + ') : 0' # else: # problem == 0: # rrpy = pysqrt(sx*sx+sy*sy) # #'if(t<2*WeMax,0,if(t<4*WeMax,0.5+3/2/(2*WeMax)*(t-3*WeMax)-2/(2*WeMax)^3*(t-3*WeMax)^3,1))'; %0.5+3/2/dx*(x-xc)-2/dx^3*(x-xc)^3 # ddstepfunc = str(diff(stepfunc,sx,sx)+diff(stepfunc,sy,sy)).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') # stepfunc = str(stepfunc).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') # #REPLACE ** with pow # ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**2','pow(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25,2.)') # ddstepfunc = ddstepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(3/2)','pow(a*(x[1]*x[1]) + (x[0]*x[0])/a,1.5)') # stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25,3.)') # testsol = '0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + stepfunc + ') : (0.25<sqrt(x[0]*x[0]+x[1]*x[1]) ? 1 : 0)' # ddtestsol = '0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + ddstepfunc + ') : 0' ddtestsol = ddtestsol.replace('a**2','(a*a)').replace('ww**2','(ww*ww)').replace('ww**3','pow(ww,3.)').replace('ww**4','pow(ww,4.)').replace('ww**5','pow(ww,5.)').replace('ww**6','pow(ww,6.)').replace('ww**7','pow(ww,7.)') testsol = testsol.replace('ww**2','(ww*ww)').replace('ww**3','pow(ww,3.)').replace('ww**5','pow(ww,5.)').replace('ww**7','pow(ww,7.)') ddtestsol = ddtestsol.replace('ww',str(width)).replace('a',str(asp)) testsol = testsol.replace('ww',str(width)).replace('a',str(asp)) ddtestsol = '-('+ddtestsol+')' def boundary(x): return x[0]+0.5 < DOLFIN_EPS or 0.5-x[0] < DOLFIN_EPS or x[1]+0.5 < DOLFIN_EPS or 0.5-x[1] < DOLFIN_EPS for CGorder in CGorderL: dofs = [] L2errors = [] #for eta in [0.16, 0.08, 0.04, 0.02, 0.01, 0.005, 0.0025] #, 0.0025/2, 0.0025/4, 0.0025/8]: # for eta in eta_list: ### SETUP MESH meshsz = int(round(80*0.005/(eta*(bool(use_adapt)==False)+0.05*(bool(use_adapt)==True)))) if (not bool(use_adapt)) and meshsz > 80: continue mesh = RectangleMesh(-0.0,-0.0,0.5*sqrt(asp),0.5/sqrt(asp),meshsz,meshsz,"left/right") # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = FunctionSpace(mesh, "CG", CGorder); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V) #V2 = FunctionSpace(mesh, "CG", CGorder+2) R = Expression(ddtestsol) #interpolate(Expression(ddtestsol),V2) a = inner(grad(dis), grad(dus))*dx L = R*dus*dx bc = DirichletBC(V, Expression(testsol), boundary) #Constant(0.) solve(a == L, u, bc) if not bool(use_adapt): break H = metric_pnorm(u, eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) H = logproject(H) if iii != Nadapt-1: mesh = adapt(H, octaveimpl=octaveimpl, debugon=False) L2error = errornorm(Expression(testsol), u, degree_rise=CGorder+2, norm_type='L2') dofs.append(len(u.vector().array())) L2errors.append(L2error) log(INFO+1,"%1dX ADAPT<->SOLVE complete: DOF=%5d, error=%0.0e" % (Nadapt, dofs[len(dofs)-1], L2error)) # PLOT MESH + solution figure() testf = interpolate(u ,FunctionSpace(mesh,'CG',1)) testfe = interpolate(Expression(testsol),FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh) axis('equal'); axis('off'); box('off'); xlim([0,0.5*sqrt(asp)]); ylim([0, 0.5/sqrt(asp)]); savefig('solution.png',dpi=300) figure() hold('on'); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),color='r',linewidth=0.5); hold('off') axis('equal'); box('off') axis('off'); xlim([0,0.5*sqrt(asp)]); ylim([0, 0.5/sqrt(asp)]) savefig(outname+'final_mesh_CG2.png',dpi=300) #; savefig('outname+final_mesh_CG2.eps',dpi=300) #PLOT ERROR figure() zz = pyabs(testf.vector().array()-testfe.vector().array())[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh); axis('equal'); box('off'); title('error') # PLOT L2error graph figure() pyloglog(dofs,L2errors,'-b.',linewidth=2,markersize=16); xlabel('Degree of freedoms'); ylabel('L2 error') # SAVE SOLUTION dofs = array(dofs); L2errors = array(L2errors) fid = open("DOFS_L2errors_CG"+str(CGorder)+outname+".mpy",'w') pickle.dump([dofs,L2errors],fid) fid.close(); #LOAD SAVED SOLUTIONS fid = open("DOFS_L2errors_CG2"+outname+".mpy",'r') [dofs,L2errors] = pickle.load(fid) fid.close() # PERFORM FITS ON LAST THREE POINTS NfitP = 9 I = array(range(len(dofs)-NfitP,len(dofs))) slope,ints = polyfit(pylog(dofs[I]), pylog(L2errors[I]), 1) if slope < -0.7: fid = open("DOFS_L2errors_CG2_fit"+outname+".mpy",'w') pickle.dump([dofs,L2errors,slope,ints],fid) fid.close() log(INFO+1,'succes') else: os.system('rm '+outname+'.lock') log(INFO+1,'fail') #PLOT THEM TOGETHER if CGorderL != [2]: fid = open("DOFS_L2errors_CG3.mpy",'r') [dofs_old,L2errors_old] = pickle.load(fid) fid.close() slope2,ints2 = polyfit(pylog(dofs_old[I]), pylog(L2errors_old[I]), 1) figure() pyloglog(dofs,L2errors,'-b.',dofs_old,L2errors_old,'--b.',linewidth=2,markersize=16) hold('on'); pyloglog(dofs,pyexp2(ints)*dofs**slope,'-r',dofs_old,pyexp2(ints2)*dofs_old**slope2,'--r',linewidth=1); hold('off') xlabel('Degree of freedoms'); ylabel('L2 error') legend(['CG2','CG3',"%0.2f*log(DOFs)" % slope, "%0.2f*log(DOFs)" % slope2]) #legend(['new data','old_data']) # savefig('comparison.png',dpi=300) #savefig('comparison.eps'); if not noplot: show()
def maximal_example(eta_list = array([0.001]), Nadapt=5, timet=1., period=2*pi): ### CONSTANTS ### SETUP SOLUTION #testsol = '0.1*sin(50*x+2*pi*t/T)+atan(-0.1/(2*x - sin(5*y+2*pi*t/T)))'; sx = Symbol('sx'); sy = Symbol('sy'); sT = Symbol('sT'); st = Symbol('st'); spi = Symbol('spi') testsol = 0.1*pysin(50*sx+2*spi*st/sT)+pyatan(-0.1,2*sx - pysin(5*sy+2*spi*st/sT)) ddtestsol = str(diff(testsol,sx,sx)+diff(testsol,sy,sy)).replace('sx','x[0]').replace('sy','x[1]').replace('spi','pi') # replacing **P with pow(,P) ddtestsol = ddtestsol.replace("(2*x[0] - sin(5*x[1] + 2*pi*st/sT))**2","pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.)") ddtestsol = ddtestsol.replace("cos(5*x[1] + 2*pi*st/sT)**2","pow(cos(5*x[1] + 2*pi*st/sT),2.)") ddtestsol = ddtestsol.replace("(pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.) + 0.01)**2","pow((pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.) + 0.01),2.)") ddtestsol = ddtestsol.replace("(1 + 0.01/pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.))**2","pow(1 + 0.01/pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.),2.)") ddtestsol = ddtestsol.replace("(2*x[0] - sin(5*x[1] + 2*pi*st/sT))**5","pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),5.)") #insert values ddtestsol = ddtestsol.replace('sT',str(period)).replace('st',str(timet)) testsol = str(testsol).replace('sx','x[0]').replace('sy','x[1]').replace('spi','pi').replace('sT',str(period)).replace('st',str(timet)) ddtestsol = "-("+ddtestsol+")" error_list = []; dof_list = [] for eta in eta_list: meshsz = 40 ### SETUP MESH # mesh = RectangleMesh(0.4,-0.1,0.6,0.3,1*meshsz,1*meshsz,"left/right") #shock # mesh = RectangleMesh(-0.75,-0.3,-0.3,0.5,1*meshsz,1*meshsz,"left/right") #waves mesh = RectangleMesh(-1.5,-0.25,0.5,0.75,1*meshsz,1*meshsz,"left/right") #shock+waves def boundary(x): return near(x[0],mesh.coordinates()[:,0].min()) or near(x[0],mesh.coordinates()[:,0].max()) \ or near(x[1],mesh.coordinates()[:,1].min()) or near(x[1],mesh.coordinates()[:,1].max()) # PERFORM ONE ADAPTATION ITERATION for iii in range(Nadapt): startTime = time() V = FunctionSpace(mesh, "CG" ,2); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V) # R = interpolate(Expression(ddtestsol),V) a = inner(grad(dis), grad(dus))*dx L = Expression(ddtestsol)*dus*dx # bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) soltime = time()-startTime startTime = time() H = metric_pnorm(u, eta, max_edge_ratio=50, CG0H=3, p=4) metricTime = time()-startTime if iii != Nadapt-1: mesh = adapt(H) TadaptTime = time()-startTime L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') printstr = "%5.0f elements, %0.0e L2error, adapt took %0.0f %% of the total time, (%0.0f %% of which was the metric calculation)" \ % (mesh.num_cells(),L2error,TadaptTime/(TadaptTime+soltime)*100,metricTime/TadaptTime*100) if len(eta_list) == 1: print(printstr) else: error_list.append(L2error); dof_list.append(len(u.vector().array())) print(printstr) if len(dof_list) > 1: dof_list = array(dof_list); error_list = array(error_list) figure() loglog(dof_list,error_list,'.b-',linewidth=2,markersize=16); xlabel('Degree of freedoms'); ylabel('L2 error') # # PLOT MESH # figure() coords = mesh.coordinates().transpose() # triplot(coords[0],coords[1],mesh.cells(),linewidth=0.1) # #savefig('mesh.png',dpi=300) #savefig('mesh.eps'); figure() #solution testf = interpolate(Expression(testsol),FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof] hh=tricontourf(coords[0],coords[1],mesh.cells(),zz,100) colorbar(hh) #savefig('solution.png',dpi=300) #savefig('solution.eps'); figure() #analytical solution testfe = interpolate(u,FunctionSpace(mesh,'CG',1)) zz = testfe.vector().array()[vtx2dof] hh=tricontourf(coords[0],coords[1],mesh.cells(),zz,100) colorbar(hh) #savefig('analyt.png',dpi=300) #savefig('analyt.eps'); figure() #error zz -= testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh) hold('on'); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),color='r',linewidth=0.5); hold('off') axis('equal'); box('off'); title('error') show()