diff --git a/Guide_to_limiters.ipynb b/Guide_to_limiters.ipynb index 1d3a104..f551313 100644 --- a/Guide_to_limiters.ipynb +++ b/Guide_to_limiters.ipynb @@ -19,7 +19,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Many interesting wave phenomena -- like fluid dynamics, lasers, and water waves -- are described by nonlinear hyperbolic partial differential equations. The solutions of these problems are discontinuous. So-called **limiters** (sometimes referred to as *slope limiters* or *flux limiters* are one of the key ingredients in approximating these discontinuous solutions." + "Many interesting wave phenomena -- like fluid dynamics, lasers, and water waves -- are described by nonlinear hyperbolic partial differential equations. The solutions of these problems often contain discontinuities. So-called **limiters** (sometimes referred to as *slope limiters* or *flux limiters*) are one of the key ingredients in approximating these discontinuous solutions." ] }, { @@ -91,7 +91,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Now what you really want to know is, what is the state of the system at the points halfway between your samples? And to figure that out, you need to guess at what's going on in the times in-between those samples. The simplest approximation would be to assume that the system just jumps from one value to the next somewhere in-between:" + "Now what you really want to know is, what is the state of the system at the points halfway between your samples? And to figure that out, you need to guess at what's going on at the points in between those samples. The simplest approximation would be to assume that the system just jumps from one value to the next somewhere in-between:" ] }, { @@ -205,7 +205,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Now all three approaches have large, obvious overshoots. This becomes even more problematic when actually solving a hyperbolic PDE; see [Lesson 3 of my HyperPython course](http://nbviewer.ipython.org/github/ketch/HyperPython/blob/master/Lesson_03_High-resolution_methods.ipynb) for details.\n", + "Now all three approaches have large, obvious overshoots. This becomes even more problematic when actually solving a hyperbolic PDE; see [Lesson 3 of my HyperPython course](https://nbviewer.org/github/ketch/HyperPython/blob/master/Lesson_03_High-resolution_methods.ipynb) for details.\n", "\n", "Is there a better way?" ] @@ -221,7 +221,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We'd like to avoid those overshoots and ensure that monotone regions of the data give monotone interpolations. We can do that by choosing the slope $\\sigma_i$ small enough that the interpolant near $x_i$ stays bounded between the neighboring averages $(y_{i-1}+y_i)/2$ and $(y_i+y_{i+1})/2$. There's an easy way to do that: just compute the forward and backward differences (like we did above), and then use *whichever is smaller* in absolute value. If $y_i$ is an extremum, then to avoid increasing the overall range of the data we always choose $\\sigma_i=0$.\n", + "We'd like to avoid those overshoots and ensure that monotone regions of the data give monotone interpolations. For equally spaced points, we can do that by choosing the slope $\\sigma_i$ small enough that the interpolant near $x_i$ stays bounded between the neighboring averages $(y_{i-1}+y_i)/2$ and $(y_i+y_{i+1})/2$. There's an easy way to do that: just compute the forward and backward differences (like we did above), and then use *whichever is smaller* in absolute value. If $y_i$ is an extremum, then to avoid increasing the overall range of the data we always choose $\\sigma_i=0$.\n", "\n", "Here's what that looks like:" ] @@ -299,7 +299,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The grey regions show the average of each value and its neighbors; the Minmod interpolant is guaranteed to stay within these bounds, so that the right edge of one interpolated region doesn't \"overshoot\" the leftmost value of the next." + "Each grey box extends from the average of $y_i$ and its left neighbor, $(y_{i-1}+y_i)/2$, to the average of $y_i$ and its right neighbor, $(y_i+y_{i+1})/2$. The minmod interpolant around $x_i$ is guaranteed to stay within these bounds, so the right edge of one interpolated piece never \"overshoots\" the left edge of the next." ] }, { @@ -313,11 +313,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "In fact, the minmod limiter guarantees an important mathematical property: it does not increase the total variation (TV) of the data. For discrete data, TV is defined as\n", + "In fact, the minmod limiter guarantees an important mathematical property: the piecewise-linear function it produces has no more total variation (TV) than the data. For discrete data, TV is defined as\n", "\n", "$$ TV(y) = \\sum_i |y_i - y_{i-1}|.$$\n", "\n", - "Essentially, TV is a measure of how much a function wiggles! This *total variation diminishing* (TVD) property of minmod is nice, because the true solutions of scalar hyperbolic PDEs have the same property. Because of this, in the 1970s-80s, researchers developed many other limiters that enforce the same property; they are referred to as" + "For a piecewise-linear function with jumps, the TV is the sum of the absolute changes along each linear piece plus the absolute size of each jump. Essentially, TV is a measure of how much a function wiggles! This *total variation diminishing* (TVD) property is important because the true solutions of scalar hyperbolic PDEs have the same property: their total variation never increases.\n", + "\n", + "In the 1970s and 80s, researchers developed many other limiters. Most of them do *not* guarantee that the interpolant has no more TV than the data. Instead, they guarantee that the full numerical method for a scalar hyperbolic PDE is TVD, as long as the time step is small enough. These are known as" ] }, { @@ -331,13 +333,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Just for fun, let's look at 3 more such limiters. If we define $F_i, B_i$ as forward- and backward-difference slope approximations at point $i$, and $\\theta_i$ as the ratio of the two, then each of these limiters can be described in terms of a function $\\phi(\\theta)$. The slope to be used is given by\n", + "Just for fun, let's look at 3 more such limiters. Let $F_i$ and $B_i$ denote the forward- and backward-difference slope approximations at point $i$, and let $\\theta_i = F_i/B_i$ be their ratio. Each of these limiters can be described in terms of a function $\\phi(\\theta)$; the slope to be used is\n", "\n", "$$\\sigma_i = \\phi(\\theta_i) B_i.$$\n", "\n", - "The limiter names and functions are:\n", + "(If $B_i = 0$, we take $\\sigma_i = 0$.) For instance, minmod corresponds to $\\phi(\\theta) = \\max(0,\\min(1,\\theta))$. The other limiter names and functions are:\n", "\n", - "- Monotonized centered difference (**MC**): $$\\phi(\\theta) = \\max(0,\\min((1+\\theta)/2,2,\\theta))$$\n", + "- Monotonized centered difference (**MC**): $$\\phi(\\theta) = \\max(0,\\min((1+\\theta)/2,2,2\\theta))$$\n", "\n", "- **van Leer**: $$\\phi(\\theta) = \\frac{\\theta + |\\theta|}{1+ |\\theta|}$$\n", "\n", @@ -354,31 +356,47 @@ "source": [ "def phi(theta,limiter):\n", " if limiter == 'minmod':\n", - " phi = (1+np.sign(theta))/2. * np.minimum(1,theta)\n", + " phi = np.maximum(0,np.minimum(1,theta))\n", " elif limiter == 'vanleer':\n", " phi = (theta + np.abs(theta))/(1+np.abs(theta))\n", " elif limiter == 'MC':\n", - " phi = np.maximum(0,np.minimum( (1.+theta)/2., np.minimum(2.,theta)))\n", + " phi = np.maximum(0,np.minimum( (1.+theta)/2., np.minimum(2.,2*theta)))\n", " elif limiter == 'superbee':\n", " phi = np.maximum(0,np.maximum(np.minimum(1.,2*theta),np.minimum(2.,theta)))\n", + " else:\n", + " raise ValueError('Unrecognized limiter: '+limiter)\n", " return phi\n", "\n", - "def pw_limited(x,y,xx,limiter='minmod'):\n", - " \"From samples (x,y) generate piecewise-linear function sampled at points xx using Minmod slopes.\"\n", - " diff = np.abs(x.reshape(1,-1) - xx.reshape(-1,1))\n", - " closest = np.argmin(diff,axis=1)\n", - " \n", + "def limited_slopes(x,y,limiter='minmod'):\n", + " \"Slopes sigma_i = phi(theta_i) B_i, with sigma = 0 at the endpoints and wherever B_i = 0.\"\n", " forward = np.zeros_like(y)\n", " backward = np.zeros_like(y)\n", " theta = np.zeros_like(y)\n", - " \n", + "\n", " forward[:-1] = (y[1:]-y[:-1])/(x[1:]-x[:-1])\n", " backward[1:] = (y[1:]-y[:-1])/(x[1:]-x[:-1])\n", - " theta[1:-1] = forward[1:-1]/backward[1:-1]\n", - " \n", + " interior = np.zeros(len(y),dtype=bool); interior[1:-1] = True\n", + " nonzero = interior & (backward != 0)\n", + " theta[nonzero] = forward[nonzero]/backward[nonzero]\n", + "\n", " sigma = phi(theta,limiter) * backward\n", - " \n", - " return y[closest] + sigma[closest]*(xx-x[closest])" + " sigma[~nonzero] = 0.\n", + " return sigma\n", + "\n", + "def pw_limited(x,y,xx,limiter='minmod'):\n", + " \"From samples (x,y) generate piecewise-linear function sampled at points xx using limited slopes.\"\n", + " diff = np.abs(x.reshape(1,-1) - xx.reshape(-1,1))\n", + " closest = np.argmin(diff,axis=1)\n", + " sigma = limited_slopes(x,y,limiter)\n", + " return y[closest] + sigma[closest]*(xx-x[closest])\n", + "\n", + "def total_variation_pw_linear(x,y,sigma):\n", + " \"\"\"Total variation of the piecewise-linear function with slope sigma[i] around x[i],\n", + " where each piece extends to the midpoints between neighboring x values.\"\"\"\n", + " edges = np.concatenate(([x[0]],(x[1:]+x[:-1])/2.,[x[-1]]))\n", + " left = y + sigma*(edges[:-1]-x) # value at the left end of each piece\n", + " right = y + sigma*(edges[1:]-x) # value at the right end of each piece\n", + " return np.sum(np.abs(right-left)) + np.sum(np.abs(left[1:]-right[:-1]))" ] }, { @@ -388,13 +406,15 @@ "outputs": [], "source": [ "y = np.sin(x/2.)+1. + 2.*(x>0)\n", + "print('TV of the data: %.3f' % np.sum(np.abs(np.diff(y))))\n", "fig, ax = plt.subplots(4,1,figsize=(width,10))\n", "for i, limiter in enumerate( ('minmod', 'vanleer','superbee','MC') ):\n", " yy = pw_limited(x,y,xx,limiter=limiter)\n", + " tv = total_variation_pw_linear(x,y,limited_slopes(x,y,limiter))\n", " ax[i].plot(xx,yy,'-k',lw=2)\n", " ax[i].plot(x,y,'or',markersize=10,alpha=0.5)\n", " ax[i].axis( (-4,4,-0.1,4.4) );\n", - " ax[i].text(.8,.2,limiter,\n", + " ax[i].text(.8,.2,'%s (TV = %.3f)' % (limiter, tv),\n", " horizontalalignment='center',\n", " transform=ax[i].transAxes,fontsize=20)" ] @@ -405,7 +425,26 @@ "source": [ "Compare these with [the finite difference approximations above](#The-problem:-overshoots!).\n", "\n", - "If you look closely (or zoom in) you'll notice that -- except for minmod -- all the limiters *do* produce some overshoot near the discontinuity. What gives? Well, these limiters are used within a larger algorithm for solving hyperbolic PDEs, and it turns out that if the overshoots are small enough, they'll go away in a full step of the algorithm. These limiters produce \"small enough\" overshoots so that no oscillations appear in the PDE solution." + "If you look closely (or zoom in) you'll notice that -- except for minmod -- all the limiters *do* produce some overshoot near the discontinuity; the total variation of each of their interpolants (shown in each panel) is larger than that of the data. Superbee even increases the total variation for the smooth data we used at the start:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "y_smooth = np.sin(x/2.)+1.\n", + "print('TV of the smooth data: %.3f' % np.sum(np.abs(np.diff(y_smooth))))\n", + "for limiter in ('minmod', 'vanleer','superbee','MC'):\n", + " print('%-8s interpolant TV: %.3f' % (limiter, total_variation_pw_linear(x,y_smooth,limited_slopes(x,y_smooth,limiter))))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What gives? Well, these limiters are used within a larger algorithm for solving hyperbolic PDEs. It turns out that if the overshoots are small enough, they are removed in a full step of the algorithm: for the advection equation, the methods based on these limiters are TVD as long as the CFL number is at most 1, even though the interpolants themselves are not. So no oscillations appear in the PDE solution." ] }, { @@ -413,7 +452,7 @@ "metadata": {}, "source": [ "# Interactive comparison\n", - "In each region, these limiter take three data points and give back a linear interpolant. It's illuminating to compare their behavior on a single set of 3 points. Note that the interactive plot below doesn't work on nbviewer; you'll need to download and run the notebook yourself." + "In each region, these limiters take three data points and give back a linear interpolant. It's illuminating to compare their behavior on a single set of 3 points. Note that the interactive plot below doesn't work on nbviewer; you'll need to download and run the notebook yourself." ] }, { @@ -465,7 +504,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The shaded region in the plot above shows the range of slopes that would give at least 2nd-order accuracy. Play with the sliders and answer the following questions:\n", + "The shaded region in the plot above shows the slopes that lie between the backward difference and the forward difference. For smooth data, both of these differences approximate the derivative to first order, so any slope in this region gives an interpolant that is second-order accurate. All four limiters always choose a slope in this region. Play with the sliders and answer the following questions:\n", "\n", "- Which limiter usually chooses the flattest approximation? Does it always?\n", "- Which limiter usually chooses the steepest approximation? Does it always?\n", @@ -479,7 +518,7 @@ "# Higher-order interpolation: WENO\n", "If we want to get higher-order accuracy (in smooth regions), then we have to give up the TVD property -- at least, in the sense defined above. The most common approach for higher order non-oscillatory piecewise interpolation is known as weighted essentially non-oscillatory (WENO) interpolation.\n", "\n", - "WENO is a very effective technique for interpolating or reconstructing functions that contain discontinuities without introducing oscillations. We'll focus on 5th-order WENO interpolation, which is the most commonly used.\n", + "WENO is a very effective technique for interpolating or reconstructing functions that contain discontinuities without introducing oscillations. We'll focus on 5th-order WENO interpolation, which is the most commonly used. As for the limiters above, we work with point values of a function. (In finite volume methods, WENO is usually applied instead to cell averages; the idea is the same, but the coefficients are different.)\n", "\n", "Let's generate some function values to interpolate:" ] @@ -490,9 +529,8 @@ "metadata": {}, "outputs": [], "source": [ - "# Note: uses PyWENO v. 0.11.2\n", - "import sympy\n", - "from pyweno import symbolic" + "matplotlib.rcParams.update({'font.size': 18})\n", + "colors = 'brg'" ] }, { @@ -515,12 +553,13 @@ "outputs": [], "source": [ "weno_order = 5 # must be odd\n", - "k = (weno_order+1)/2\n", + "k = (weno_order+1)//2\n", "\n", "size = (width,4)\n", "plt.figure(figsize=size)\n", - "x=np.arange(-k+1,k)\n", - "y=np.random.rand(len(x))\n", + "x=np.arange(-k+1,k).astype(float)\n", + "rng = np.random.default_rng(2)\n", + "y=rng.random(len(x))\n", "#y = np.array((1.,1.,1.,0.,0.))\n", "plt.plot(x,y,'ok')\n", "plt.axis((-(k-.5),k-.5,-0.5,2.1));" @@ -557,13 +596,6 @@ "Ordinary polynomial interpolation yields an oscillatory polynomial that also exceeds the bounds of the data:" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For application to hyperbolic conservation laws, our main interest is in getting values of the function at the half-integer points (interfaces). Let's suppose we're trying to interpolate around $x=0$, at $x=\\pm 1/2$. Instead of using all 5 points, we could just use three points, which might give us a less oscillatory interpolant, at least in that interval. Using the 5 points we're given, there are three natural choices of interpolation stencil: the leftmost three, the middle three, or the rightmost three. Let's see what each of these quadratic interpolants looks like." - ] - }, { "cell_type": "code", "execution_count": null, @@ -575,6 +607,13 @@ "plt.title('Quartic interpolant');" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For application to hyperbolic conservation laws, our main interest is in getting values of the function at the half-integer points (interfaces). Let's suppose we're trying to interpolate around $x=0$, at $x=\\pm 1/2$. Instead of using all 5 points, we could just use three points, which might give us a less oscillatory interpolant, at least in that interval. Using the 5 points we're given, there are three natural choices of interpolation stencil: the leftmost three, the middle three, or the rightmost three. Let's see what each of these quadratic interpolants looks like." + ] + }, { "cell_type": "code", "execution_count": null, @@ -582,9 +621,9 @@ "outputs": [], "source": [ "fig, ax = plt.subplots(3,1,figsize=(width,10))\n", - "names = ['left','right','center']\n", + "names = ['left','center','right']\n", "p = []\n", - "for i in range(int(k)):\n", + "for i in range(k):\n", " p.append(stencil_interpolant(x,y,k,i))\n", " plot_interpolants(x,y,[p[i]],axis=ax[i],color=[colors[i]])\n", " ax[i].set_title(names[i]+' interpolant')" @@ -610,15 +649,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The quadratic interpolants look less oscillatory, but they're also less accurate. The WENO idea is to use the high-order interpolant (with all 5 points) if the data is smooth, but to use one of the lower-order interpolants (or a combination of them) if the data is not smooth. This is achieved by computing point values of the interpolant as weighted averages of the point values of the candidate polynomials, e.g.\n", + "The quadratic interpolants look less oscillatory, but they're also less accurate. The WENO idea is to use the high-order interpolant (with all 5 points) if the data is smooth, but to use one of the lower-order interpolants (or a combination of them) if the data is not smooth. This is achieved by computing point values of the interpolant as weighted averages of the point values of the candidate polynomials. Writing $\\tilde{y}_{i-1/2}$ for the interpolated value at $x_{i-1/2}$,\n", "\n", - "$$y_{x_{i-1/2}} = w_{1,-1/2} p_\\text{left}(x_{i-1/2}) + w_{2,-1/2} p_\\text{center}(x_{i-1/2}) + w_{3,-1/2} p_\\text{right}(x_{i-1/2}).$$\n", + "$$\\tilde{y}_{i-1/2} = w_{1,-1/2} p_\\text{left}(x_{i-1/2}) + w_{2,-1/2} p_\\text{center}(x_{i-1/2}) + w_{3,-1/2} p_\\text{right}(x_{i-1/2}).$$\n", "\n", - "Of course, there is some particular set of weights that gives the quartic interpolant:\n", + "Of course, there is some particular set of weights that gives the value of the quartic interpolant:\n", "\n", - "$$y_{x_{i-1/2}} = \\gamma_{1,-1/2} p_\\text{left}(x_{i-1/2}) + \\gamma_{2,-1/2} p_\\text{center}(x_{i-1/2}) + \\gamma_{3,-1/2} p_\\text{right}(x_{i-1/2}).$$\n", + "$$p_\\text{quartic}(x_{i-1/2}) = \\gamma_{1,-1/2} p_\\text{left}(x_{i-1/2}) + \\gamma_{2,-1/2} p_\\text{center}(x_{i-1/2}) + \\gamma_{3,-1/2} p_\\text{right}(x_{i-1/2}).$$\n", "\n", - "We will want to have $w_{j,-1/2} \\approx \\gamma_{j,-1/2}$ for smooth data." + "These *optimal weights* $\\gamma$ do not depend on the data, but they do depend on the point where we evaluate. We will want to have $w_{j,-1/2} \\approx \\gamma_{j,-1/2}$ for smooth data. The function `compute_opt_weights` defined below computes them by requiring this equation to hold for any data." ] }, { @@ -627,42 +666,55 @@ "metadata": {}, "outputs": [], "source": [ - "def compute_opt_weights(k,xi):\n", + "def stencil_coefficients(xs,xe):\n", + " \"\"\"Coefficients c such that the polynomial interpolating (xs[j], f_j)\n", + " has the value sum_j c[j]*f_j at the point xe.\"\"\"\n", + " n = len(xs)\n", + " V = np.vander(xs,n,increasing=True)\n", + " return np.linalg.solve(V.T, xe**np.arange(n))\n", + "\n", + "def compute_opt_weights(x,k,xi):\n", " \"\"\"\n", - " Get the optimal weights (gamma) at points xi.\n", + " Optimal (linear) weights gamma for the k candidate stencils (ordered left, center, right)\n", + " at the points x_i + xi/2, where x_i is the middle point of x. These are the weights\n", + " for which the combination of the degree-(k-1) interpolants equals the degree-(2k-2)\n", + " interpolant through all 2k-1 points.\n", " \"\"\"\n", - " if not hasattr(xi,'__iter__'): xi = [xi]\n", - " opt_weights = symbolic.optimal_weights(k,xi)\n", " gamma = {}\n", - " for i, xi_val in enumerate(xi):\n", - " gamma[xi_val] = np.empty(k)\n", - " for j in range(k):\n", - " gamma[xi_val][j] = opt_weights[0][(i,j)]\n", - "\n", + " for xi_val in xi:\n", + " xe = x[k-1] + xi_val/2.\n", + " c_opt = stencil_coefficients(x,xe)\n", + " M = np.zeros((2*k-1,k))\n", + " for r in range(k):\n", + " M[r:r+k,r] = stencil_coefficients(x[r:r+k],xe)\n", + " g = np.linalg.lstsq(M,c_opt,rcond=None)[0]\n", + " assert np.allclose(M.dot(g),c_opt), 'no exact optimal weights at xi = %s' % xi_val\n", + " gamma[xi_val] = g\n", " return gamma\n", "\n", - "gamma = compute_opt_weights(k,(-1,0.5,1))\n", + "gamma = compute_opt_weights(x,k,(-1,1))\n", "\n", - "print \"$\\gamma_{j,-1/2}$:\", gamma[-1]\n", - "print \"$\\gamma_{j,+1/2}$:\", gamma[1]" + "print(\"gamma_{j,-1/2} (left, center, right):\", gamma[-1])\n", + "print(\"gamma_{j,+1/2} (left, center, right):\", gamma[1])\n", + "print(\"Check: the weighted combination equals the quartic interpolant at x = -1/2 and +1/2:\",\n", + " [np.isclose(sum(gamma[xi][j]*p[j](xi/2.) for j in range(k)), p_opt(xi/2.)) for xi in (-1,1)])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "How does one determine if a polynomial is non-oscillatory? There are several ways proposed in the literature, but the original and most widely used is the weighted Sobolev norm:\n", + "How does one determine if a polynomial is non-oscillatory? There are several ways proposed in the literature, but the original and most widely used is the weighted Sobolev norm introduced by Jiang and Shu:\n", "\n", - "$$\\beta = \\sum_{l=1}^k \\Delta x^{2l-1} \\int_{x_{i-1/2}}^{x_{i+1/2}} \\left(\\frac{d^l}{dx^l}p(x)\\right)^2 dx.$$\n", + "$$\\beta = \\sum_{l=1}^{k-1} \\Delta x^{2l-1} \\int_{x_{i-1/2}}^{x_{i+1/2}} \\left(\\frac{d^l}{dx^l}p(x)\\right)^2 dx.$$\n", "\n", - "Put simply, $\\beta$ is a scaled sum of the square $L^2$ norms of all the derivatives of the polynomial over the interval where it will be used. The scaling is chosen to make the \"smoothness indicator\" $\\beta$ independent of the choice of $\\Delta x$ (note that $\\Delta x = 1$ in our example data).\n", + "Put simply, $\\beta$ is a scaled sum of the squared $L^2$ norms of all the derivatives of the polynomial over the interval where it will be used. The scaling is chosen to make the \"smoothness indicator\" $\\beta$ independent of the choice of $\\Delta x$ (note that $\\Delta x = 1$ in our example data).\n", "\n", - "As each of the interpolants above is a linear function of the values $y_i$, the smoothness indicators are quadratic functions of the $y_i$ and can be expressed in the generic form\n", + "As each of the interpolants above is a linear function of the values $y_j$, the smoothness indicators are quadratic functions of the $y_j$. If we number the stencils $r = 0, 1, 2$ from left to right, so that stencil $r$ uses $y_{i-2+r}, y_{i-1+r}, y_{i+r}$, they can be written in the form\n", "\n", - "$$\\beta = \\sum_{m=-2}^{2} \\sum_{n=-2}^{m}\n", - " C_{m,n} y_{i-k+m} y_{i-k+n}$$\n", + "$$\\beta_r = \\sum_{m=0}^{2} \\sum_{n=0}^{m} C_{r,m,n}\\, y_{i-2+r+m}\\, y_{i-2+r+n}.$$\n", "\n", - "Of course, the coefficients $C_{m,n}$ will be different for each of the candidate polynomials $p_\\text{left},p_\\text{center},p_\\text{right}$. We can use the Python package PyWeno to automatically compute these coefficients and then apply them to our data." + "The coefficients $C_{r,m,n}$ are different for each of the candidate polynomials $p_\\text{left},p_\\text{center},p_\\text{right}$. Here we simply compute $\\beta$ directly from each polynomial." ] }, { @@ -671,17 +723,18 @@ "metadata": {}, "outputs": [], "source": [ - "def compute_smoothness_indicators(y,k):\n", - " C = symbolic.jiang_shu_smoothness_coefficients(k)\n", - " beta = np.zeros((k,1))\n", - " for m in range(k):\n", - " for n in range(m+1):\n", - " for r in range(len(beta)):\n", - " beta[r] = beta[r] + C[(r,n,m)] * y[r+m] * y[r+n]\n", + "def compute_smoothness_indicators(polys,dx=1.):\n", + " \"Jiang-Shu smoothness indicator of each polynomial on the interval [-dx/2, dx/2].\"\n", + " beta = np.zeros(len(polys))\n", + " for r, poly in enumerate(polys):\n", + " degree = poly.order\n", + " for l in range(1,degree+1):\n", + " antiderivative = np.polyint(np.polyder(poly,l)**2)\n", + " beta[r] += dx**(2*l-1) * (antiderivative(dx/2.) - antiderivative(-dx/2.))\n", " return beta\n", "\n", - "beta = compute_smoothness_indicators(y,k)\n", - "print beta" + "beta = compute_smoothness_indicators(p)\n", + "print(beta)" ] }, { @@ -739,7 +792,6 @@ "outputs": [], "source": [ "plot_interpolants(x,y,p+[p_opt],color=['b','r','g','k'])\n", - "plt.hold(True)\n", "plt.plot(-0.5,q[-1],'ok',alpha=0.3,markersize=15)\n", "plt.plot(0.5,q[1],'ok',alpha=0.3,markersize=15)\n", "\n", @@ -769,48 +821,42 @@ " xx = np.linspace(np.min(x),np.max(x))\n", " color=['b','r','g']\n", " plt.figure(figsize=size)\n", - " plt.hold(True)\n", " ax1 = plt.subplot2grid((1,8), (0,0), colspan=6)\n", " ax2 = plt.subplot2grid((1,8), (0,6))\n", " ax3 = plt.subplot2grid((1,8), (0,7))\n", "\n", " K = len(y)\n", - " k = (K+1)/2\n", + " k = (K+1)//2\n", " assert len(x)==K\n", " p_opt=np.poly1d(np.polyfit(x,y,K-1))\n", - " p = {}\n", - " for name, offset in zip(('left','right','center'),range(k)):\n", - " p[name] = stencil_interpolant(x,y,k,offset)\n", - " \n", - " gamma = compute_opt_weights(k,xi)\n", - " beta = compute_smoothness_indicators(y,k)\n", - " \n", + " names = ('left','center','right')\n", + " p = [stencil_interpolant(x,y,k,offset) for offset in range(k)]\n", + "\n", + " gamma = compute_opt_weights(x,k,xi)\n", + " beta = compute_smoothness_indicators(p)\n", + "\n", " w = {}; q = {}\n", " for loc in xi:\n", " w[loc] = compute_weights(gamma[loc],beta)\n", - " q[loc] = w[loc][0]*p['left'](loc/2.) \\\n", - " + w[loc][1]*p['center'](loc/2.) \\\n", - " + w[loc][2]*p['right'](loc/2.)\n", - " ax2.bar(range(3),w[-1],color=color,align='center'); \n", + " q[loc] = sum(w[loc][j]*p[j](loc/2.) for j in range(k))\n", + " ax2.bar(range(3),w[-1],color=color,align='center');\n", " ax2.set_title(r'$w_{i-1/2}$',fontsize=fs)\n", " ax3.bar(range(3),w[1],color=color,align='center')\n", " ax3.set_title(r'$w_{i+1/2}$',fontsize=fs)\n", " for ax in (ax2,ax3):\n", - " ax.set_xticks(range(3)); \n", - " ax.set_xticklabels(('left','center','right'))\n", + " ax.set_xticks(range(3));\n", + " ax.set_xticklabels(names, fontsize=11)\n", " ax.set_ylim(0,1); ax.set_yticks((0,1))\n", "\n", - " for name, interpolant in p.iteritems():\n", + " xc = np.linspace(-0.5,0.5)\n", + " for name, interpolant in zip(names,p):\n", " ax1.plot(xx,interpolant(xx),styles[name])\n", - " xc = np.linspace(-0.5,0.5)\n", " ax1.plot(xc,interpolant(xc),styles[name],linewidth=5)\n", - " ax1.plot(x,y,'ok')\n", - " ax1.hold(True)\n", - " ax1.plot(xx,p_opt(xx),'-k',x,y,'ok',linewidth=2)\n", + " ax1.plot(xx,p_opt(xx),'-k',linewidth=2)\n", + " ax1.plot(x,y,'ok')\n", " for loc in xi:\n", - " ax1.plot(loc/2.,q[loc],'ok', alpha=0.3,markersize=15)\n", " ax1.plot(loc/2.,q[loc],'ok',alpha=0.3,markersize=15)\n", - " \n", + "\n", " ax1.axis((-(k-0.8),k-0.8,-0.5,2.1));" ] }, @@ -820,7 +866,6 @@ "metadata": {}, "outputs": [], "source": [ - "%matplotlib inline\n", "y=np.random.rand(len(x))\n", "WENO_visualization(x,y)" ] @@ -859,9 +904,9 @@ "\n", "$$ q_t + a q_x = 0.$$\n", "\n", - "The solution $q$ simply translates at velocity $a$; if you're not familiar with this, take a look at my [HyperPython lesson on advection](http://nbviewer.ipython.org/github/ketch/HyperPython/blob/master/Lesson_01_Advection.ipynb) and then the [lesson on high-resolution methods](http://nbviewer.ipython.org/github/ketch/HyperPython/blob/master/Lesson_03_High-resolution_methods.ipynb).\n", + "The solution $q$ simply translates at velocity $a$; if you're not familiar with this, take a look at my [HyperPython lesson on advection](https://nbviewer.org/github/ketch/HyperPython/blob/master/Lesson_01_Advection.ipynb) and then the [lesson on high-resolution methods](https://nbviewer.org/github/ketch/HyperPython/blob/master/Lesson_03_High-resolution_methods.ipynb).\n", "\n", - "The cells below solve the advection equation using several of the limiters we've discussed. To run this part, you need to [install PyClaw](http://www.clawpack.org/installing.html) and Visclaw, which can be most easily accomplished via\n", + "The cells below solve the advection equation using several of the limiters we've discussed. To run this part, you need to [install PyClaw](https://www.clawpack.org/installing.html), which can be most easily accomplished via\n", "\n", " pip install clawpack" ] @@ -876,7 +921,7 @@ "from clawpack import riemann\n", "import matplotlib\n", "from matplotlib import animation\n", - "from clawpack.visclaw.JSAnimation import IPython_display\n", + "from IPython.display import HTML\n", "\n", "def setup(scheme='minmod',cfl_max=0.9,IC='gauss_square',mx=100):\n", " if 'weno' in scheme:\n", @@ -944,7 +989,7 @@ " claw.verbosity = 0\n", " claw.run()\n", " results.append(claw.frames)\n", - " \n", + "\n", "def animate(results,ymin=-0.1):\n", " fig = plt.figure(figsize=(width,8))\n", "\n", @@ -972,42 +1017,48 @@ "\n", " for i,ax in enumerate(axes):\n", " ax.set_xlim(0,1); ax.set_ylim(ymin,1.3)\n", - " #ax.grid()\n", " ax.set_title(schemes[i], x = 0.5, y=0.85 )\n", " ax.plot(xc,results[i][0].q[0,:],color='k',alpha=0.3)\n", - " \n", "\n", " def fplot(frame_number):\n", " fig.suptitle('Solution after %s cycles' % frame_number, fontsize=20)\n", " for i, line in enumerate(lines):\n", " line.set_data(xc,results[i][frame_number].q[0,:])\n", - " return lines,\n", + " return lines\n", "\n", - " return matplotlib.animation.FuncAnimation(fig, fplot, frames=len(claw.frames), interval=30)\n", + " anim = matplotlib.animation.FuncAnimation(fig, fplot, frames=len(results[0]), interval=30)\n", + " plt.close(fig)\n", + " return anim\n", "\n", - "animate(results)" + "HTML(animate(results).to_jshtml())" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "In the plot above, the solution advects across the full domain once between each frame of the animation (the boundary is periodic). By stepping through the animation, you can see how each limiter modifies the shape of the solution over time. The Lax-Wendroff method is based on a centered-difference approximation with no limiting; notice that it creates oscillations and is also less accurate than the limiter-based methods. For the advection equation, oscillations and overshoots are not a serious problem, but in the context of fluid dynamics or water wave simulations, they can be catastrophic." + "# After each full cycle the exact solution equals the initial condition.\n", + "dx = 1./len(results[0][0].q[0,:])\n", + "print('1-norm of the error after %d cycles:' % (len(results[0])-1))\n", + "for scheme, frames in zip(schemes, results):\n", + " print('%-13s %.4f' % (scheme, dx*np.sum(np.abs(frames[-1].q[0,:]-frames[0].q[0,:]))))" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "metadata": {}, - "outputs": [], - "source": [] + "source": [ + "In the plot above, the solution advects across the full domain once between each frame of the animation (the boundary is periodic). By stepping through the animation, you can see how each limiter modifies the shape of the solution over time. The Lax-Wendroff method is based on a centered-difference approximation with no limiting; notice that it creates oscillations and is also less accurate than the limiter-based methods. For the advection equation, oscillations and overshoots are not a serious problem, but in the context of fluid dynamics or water wave simulations, they can be catastrophic." + ] } ], "metadata": { "kernelspec": { - "display_name": "3.9", + "display_name": "Python 3 (ipykernel)", "language": "python", - "name": "3.9" + "name": "python3" }, "language_info": { "codemirror_mode": { @@ -1019,7 +1070,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.10" + "version": "3.13.0" }, "toc": { "base_numbering": 1, @@ -1036,5 +1087,5 @@ } }, "nbformat": 4, - "nbformat_minor": 1 + "nbformat_minor": 4 }