In this notebook, a numerical solution using an immersed boundary is compared to the exact solution. This exact solution was initially presented in Mulder 2017.
The top surface will be an immersed boundary, the bottom a zero-flux boundary condition, and periodic boundary conditions on the sides. The domain extends from \(0\) to \(2\pi\) in the x direction and from \(0\) to \(-\frac{3\pi}{4}\) in the y direction.
# Load the signed distance function for the boundary geometryimport pickleimport matplotlib.pyplot as pltdef read_sdf(surface, dims):"""Unpickle an sdf""" fname ='sdfs/'+ surface +'_'+str(dims) +'d.dat'withopen(fname, 'rb') as f: sdf = pickle.load(f)return sdf# Load the sinusoid 2D sdfsdf = read_sdf('exact_solution_surface_periodic_1.0', 2)plt.imshow(sdf.data.T, aspect='auto')plt.title("Boundary geometry SDF")plt.colorbar()plt.show()
# Set up the exact solutionimport numpy as np# Use SDF gridgrid = sdf.grid# Misc parametersc0 =1m =8A =0.25# Functions requireddef x1(x, y, A):return x - A*np.sin(x)*np.cosh(y)def y1(x, y, A):return y - A*np.cos(x)*np.sinh(y)def c(x, y, A, c0): term1 = (1-A*np.cos(x)*np.cosh(y))**2 term2 = (A*np.sin(x)*np.sinh(y))**2return c0*(term1 + term2)**-0.5def alpha(m, c0):return c0*np.sqrt(m**2+(np.pi/2)**2)def u(t, x, y, c0, m, A): x1_vals = x1(x, y, A) y1_vals = y1(x, y, A) alp = alpha(m, c0)return np.cos(m*x1_vals-alp*t)*np.cos(np.pi*y1_vals/2)xvals = np.linspace(0, 2*np.pi, grid.shape[0]-8) # Trim off the edges where we will have bcsyvals = np.linspace(-3*np.pi/4, 0, grid.shape[1]) # -3pi/4xmsh, ymsh = np.meshgrid(xvals, yvals, indexing='ij')u0 = u(0, xmsh, ymsh, c0, m, A)
# Need to set up the subdomainsimport devito as dv# Note that we are leaving a 4 point pad on each side to ensure stencils generate correctlyclass MainDomain(dv.SubDomain): # Main section of the grid name ='main'def__init__(self):super().__init__() def define(self, dimensions): x, y = dimensionsreturn {x: ('middle', 4, 4), y: ('middle', 0, 2)}class Left(dv.SubDomain): # Left wraparound region for periodic bcs name ='left'def__init__(self):super().__init__()def define(self, dimensions): x, y = dimensionsreturn {x: ('left', 4), y: y}class Right(dv.SubDomain): # Right wraparound region for periodic bcs name ='right'def__init__(self):super().__init__()def define(self, dimensions): x, y = dimensionsreturn {x: ('right', 4), y: y}class Base(dv.SubDomain): # Base with zero flux (centre) name ='base'def__init__(self):super().__init__()def define(self, dimensions): x, y = dimensionsreturn {x: ('middle', 4, 4), y: ('right', 2)}main_domain = MainDomain()left = Left()right = Right()base = Base()
from schism import BoundaryGeometry# Rebuild the SDF on the new grid so we can use these subdomainsnew_sdf = dv.Function(name='sdf', grid=new_grid, space_order=sdf.space_order)new_sdf.data[:] = sdf.data[:]bg = BoundaryGeometry(new_sdf)
/home/ed/anaconda3/envs/devito/lib/python3.8/site-packages/numpy/core/getlimits.py:500: UserWarning: The value of the smallest subnormal for <class 'numpy.float32'> type is zero.
setattr(self, word, getattr(machar, word).flat[0])
/home/ed/anaconda3/envs/devito/lib/python3.8/site-packages/numpy/core/getlimits.py:89: UserWarning: The value of the smallest subnormal for <class 'numpy.float32'> type is zero.
return self._float_to_str(self.smallest_subnormal)
Operator `normals` ran in 0.01 s
# Plot the solution masked with the interior maskimport sympy as spinterior_mask = bg.interior_mask[(sp.core.numbers.Zero(), sp.core.numbers.Zero())][4:-4]u0[np.logical_not(interior_mask)] =0plt.imshow(u0.T, extent=(0, 2*np.pi, 0, -3*np.pi/4), aspect='auto', cmap='seismic')plt.title("Exact solution at t = 0")plt.colorbar()plt.contour(xmsh, ymsh, sdf.data[4:-4], [0])plt.savefig("exact_solution")plt.show()
# Set up the velocity fieldvel = dv.Function(name='vel', grid=new_grid)# Cap the velocity at 3, as these points are outside the domain anywayvel_data = np.minimum(c(xmsh, ymsh, A, c0), 3)# Add the edgesvel_data_full = np.concatenate((vel_data[-5:-1], vel_data, vel_data[1:5]))vel.data[:] = vel_data_full[:]plt.imshow(vel.data.T, extent=(-4*grid.spacing[0], 2*np.pi+4*grid.spacing[0], 0, -3*np.pi/4), aspect='auto')plt.title("Velocity field")plt.colorbar()plt.show()
# Set the timestep at 10% of critical timestepdt =0.1*new_grid.spacing[0]/np.amax(vel.data)
# Set up the TimeFunctionimport devito as dvs_o =4p = dv.TimeFunction(name='p', grid=new_grid, space_order=s_o, time_order=2)un1 = u(-dt, xmsh, ymsh, c0, m, A)un1[np.logical_not(interior_mask)] =0p_data_n1 = np.concatenate((un1[-5:-1], un1, un1[1:5]))p_data_0 = np.concatenate((u0[-5:-1], u0, u0[1:5]))p.data[0] = p_data_n1p.data[1] = p_data_0plt.imshow(p.data[0].T, extent=(-4*grid.spacing[0], 2*np.pi+4*grid.spacing[0], 0, -3*np.pi/4), aspect='auto', cmap='seismic')plt.title("Initial fill of p at t = -dt")plt.colorbar()plt.show()plt.imshow(p.data[1].T, extent=(-4*grid.spacing[0], 2*np.pi+4*grid.spacing[0], 0, -3*np.pi/4), aspect='auto', cmap='seismic')plt.title("Initial fill of p at t = 0")plt.colorbar()plt.show()plt.imshow(p.data[1].T-p.data[0].T, aspect='auto', cmap='seismic')plt.title("Diff")plt.colorbar()plt.show()
# Set up the boundary conditions for the immersed boundaryfrom schism import BoundaryConditionsbc_list = [dv.Eq(p, 0), # Zero pressure on free surface dv.Eq(p.dx2+p.dy2, 0), # Zero laplacian dv.Eq(p.dx4 +2*p.dx2dy2 + p.dy4, 0)] # Zero biharmonicbcs = BoundaryConditions(bc_list)
# Get the modified stencilsderivs = (p.dx2, p.dy2)subs = boundary.substitutions(derivs)
Generating stencils for Derivative(p(t, x, y), (x, 2))
Generating stencils for Derivative(p(t, x, y), (y, 2))
# Set up the equation for the main body of the domaineq_main = dv.Eq(p.forward, 2*p-p.backward+dt**2*vel**2*(subs[p.dx2]+subs[p.dy2]), subdomain=main_domain)
# Set up periodic bcs on the left and right edges# t = p.time_dimt = new_grid.stepping_dimx, y = new_grid.dimensionsleft_bcs = [dv.Eq(p[t+1, i, y], p[t+1, new_grid.shape[0]-9+i, y], subdomain=left)for i inrange(4)]right_bcs = [dv.Eq(p[t+1, new_grid.shape[0]-4+i, y], p[t+1, i+5, y], subdomain=right)for i inrange(4)]
# Set up the zero flux bc at the basedef zero_flux_base(eq, subdomain):""" Transform an equation such that the stencils are folded back on themselves at the edge of the domain. """ lhs, rhs = eq.evaluate.args yzf = subdomain.dimensions[-1] y = yzf.parent# Functions present in stencil funcs = dv.symbolics.retrieve_functions(rhs) mapper = {}for f in funcs:# Get the y index yind = f.indices[-1]if (yind-y).as_coeff_Mul()[0] >0: pos =abs((f.shape[-1] -1)*y.spacing - yind) mapper.update({f: f.subs({yind: dv.symbolics.INT((f.shape[-1]-1)*y.spacing-pos)})})return dv.Eq(lhs, rhs.subs(mapper), subdomain=subdomain)base_bc = zero_flux_base(eq_main, base)
# Set up number of timestepst_max =2*np.pi/c0nsteps = t_max/dtnsteps
Data(7199.99979964)
op = dv.Operator([eq_main, base_bc] + left_bcs + right_bcs)
# Remember to trim edges where periodic bcs are applied# Index in the buffer where the final timestep should be stored:ind = (1+int(nsteps)) %3plt.imshow(p.data[ind, 4:-4].T, extent=(0, 2*np.pi, 0, -3*np.pi/4), aspect='auto', cmap='seismic')plt.title("Pressure field at t = 2*pi/c_0")plt.colorbar()plt.show()
uend = u(dt*(int(nsteps)), xmsh, ymsh, c0, m, A)uend[np.logical_not(interior_mask)] =0plt.imshow(uend.T, extent=(0, 2*np.pi, 0, -3*np.pi/4), aspect='auto', cmap='seismic')plt.title("Exact solution at t = 2*pi/c_0")plt.colorbar()plt.show()