Tutorial¶
Advection/Diffusion¶
To run the advection/diffustion (AD) example:
$ cd PyPFASST
$ export PYTHONPATH=$PYTHONPATH:$PWD
$ cd examples/advection
$ mpirun -n 4 python main.py
This solves the 1d AD equation using a V cycle with 3 PFASST levels (5, 3, and 2 nodes) and 4 processors. The logarithm of the maximum absolute error (compared to an exact solution) is echoed after each SDC sweep.
Please skim over the overview documentation to get a jist of how PyPFASST is used, then consider the main.py script of the AD example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | """Solve the advection/diffusion equation with PyPFASST."""
# Copyright (c) 2011, Matthew Emmett. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from mpi4py import MPI
import argparse
import pfasst
import pfasst.imex
from ad import *
######################################################################
# options
parser = argparse.ArgumentParser(
description='solve the advection/diffusion equation')
parser.add_argument('-d',
type=int,
dest='dim',
default=1,
help='number of dimensions, defaults to 1')
parser.add_argument('-n',
type=int,
dest='steps',
default=MPI.COMM_WORLD.size,
help='number of time steps, defaults to number of mpi processes')
parser.add_argument('-l',
type=int,
dest='nlevs',
default=3,
help='number of levels, defaults to 3')
options = parser.parse_args()
###############################################################################
# config
comm = MPI.COMM_WORLD
nproc = comm.size
dt = 0.01
tend = dt*options.steps
N = 1024
D = options.dim
nnodes = [ 9, 5, 3 ]
###############################################################################
# init pfasst
pf = pfasst.PFASST()
pf.simple_communicators(ntime=nproc, comm=comm)
for l in range(options.nlevs):
F = AD(shape=D*(N,), refinement=2**l, dim=D)
SDC = pfasst.imex.IMEXSDC('GL', nnodes[l])
pf.add_level(F, SDC, interpolate, restrict)
if len(pf.levels) > 1:
pf.levels[-1].sweeps = 2
###############################################################################
# add hooks
def echo_error(level, state, **kwargs):
"""Compute and print error based on exact solution."""
if level.feval.burgers:
return
y1 = np.zeros(level.feval.shape)
level.feval.exact(state.t0+state.dt, y1)
err = np.log10(abs(level.qend-y1).max())
print 'step: %03d, iteration: %03d, position: %d, level: %02d, error: %f' % (
state.step, state.iteration, state.cycle, level.level, err)
pf.add_hook(0, 'post-sweep', echo_error)
###############################################################################
# create initial condition and run
F = AD(shape=D*(N,), dim=D)
q0 = np.zeros(F.shape)
F.exact(0.0, q0)
pf.run(q0=q0, dt=dt, tend=tend)
|
On line 38 we import the AD class and the spatial interpolate and restrict functions for this example from the ad.py file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | """Solve various advection/diffusion type equations with PyPFASST."""
# Copyright (c) 2011, Matthew Emmett. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import math
import numpy as np
import numpy.fft as fft
import pfasst.imex
###############################################################################
# define AD level
class AD(pfasst.imex.IMEXFEval):
"""IMEX FEval class for the adv/diff equation (or viscous Burgers)."""
def __init__(self, shape=None, refinement=1,
dim=1, L=1.0, nu=0.005, v=1.0, t0=1.0,
burgers=False, verbose=False, **kwargs):
super(AD, self).__init__()
N = shape[0] / refinement
self.shape = dim*(N,)
self.size = N**dim
self.N = N
self.L = L
self.v = v
self.nu = nu
self.t0 = t0
self.dim = dim
self.burgers = burgers
# frequencies = 2*pi/L * (wave numbers)
K = 2*math.pi/L * fft.fftfreq(N) * N
if verbose:
print 'building operators...'
# operators
if dim == 1:
sgradient = K*1j
laplacian = -K**2
elif dim == 2:
sgradient = np.zeros(self.shape, dtype=np.complex128)
laplacian = np.zeros(self.shape, dtype=np.complex128)
for i in xrange(N):
for j in xrange(N):
laplacian[i,j] = -(K[i]**2 + K[j]**2)
sgradient[i,j] = K[i] * 1j + K[j] * 1j
elif dim == 3:
sgradient = np.zeros(self.shape, dtype=np.complex128)
laplacian = np.zeros(self.shape, dtype=np.complex128)
for i in range(N):
for j in range(N):
for k in range(N):
laplacian[i,j,k] = -(
K[i]**2 + K[j]**2 + K[k]**2)
sgradient[i,j,k] = (
K[i] * 1j + K[j] * 1j + K[k] * 1j)
else:
raise ValueError, 'dimension must be 1, 2, or 3'
self.sgradient = sgradient
self.laplacian = laplacian
# spectral interpolation masks
if verbose:
print 'building interpolation masks...'
self.full, self.half = spectral_periodic_masks(dim, N)
def f1_evaluate(self, u, t, f1, **kwargs):
"""Evaluate explicit piece."""
z = fft.fftn(u)
z_sgrad = self.sgradient * z
u_sgrad = np.real(fft.ifftn(z_sgrad))
if self.burgers:
f1[...] = - (u * u_sgrad)
else:
f1[...] = - (self.v * u_sgrad)
def f2_evaluate(self, y, t, f2, **kwargs):
"""Evaluate implicit piece."""
z = fft.fftn(y)
z = self.nu * self.laplacian * z
u = np.real(fft.ifftn(z))
f2[...] = u
def f2_solve(self, rhs, y, t, dt, f2, **kwargs):
"""Solve and evaluate implicit piece."""
# solve (rebuild operator every time, as dt may change)
invop = 1.0 / (1.0 - self.nu*dt*self.laplacian)
z = fft.fftn(rhs)
z = invop * z
y[...] = np.real(fft.ifftn(z))
# evaluate
z = self.nu * self.laplacian * z
f2[...] = np.real(fft.ifftn(z))
def exact(self, t, q):
"""Exact solution (for adv/diff equation)."""
if self.burgers:
raise ValueError, 'exact solution not known for non-linear case'
dim = self.dim
L = self.L
v = self.v
nu = self.nu
t0 = self.t0
q1 = np.zeros(self.shape, q.dtype)
images = range(-1,2)
#images = [0]
if dim == 1:
nx, = self.shape
for ii in images:
for i in range(nx):
x = L*(i-nx/2)/nx + ii*L - v*t
q1[i] += ( (4.0*math.pi*nu*(t+t0))**(-0.5)
* math.exp(-x**2/(4.0*nu*(t+t0))) )
elif dim == 2:
nx, ny = self.shape
for ii in images:
for jj in images:
for i in range(nx):
x = L*(i-nx/2)/nx + ii*L - v*t
for j in range(ny):
y = L*(j-ny/2)/ny + jj*L - v*t
q1[i,j] += ( (4.0*math.pi*nu*(t+t0))**(-1.0)
* math.exp(-(x**2+y**2)/(4.0*nu*(t+t0))) )
elif dim == 3:
nx, ny, nz = self.shape
for ii in images:
for jj in images:
for kk in images:
for i in range(nx):
x = L*(i-nx/2)/nx + ii*L - v*t
for j in range(ny):
y = L*(j-ny/2)/ny + jj*L - v*t
for k in range(nz):
z = L*(j-nz/2)/nz + kk*L - v*t
q1[i,j,k] += ( (4.0*math.pi*nu*(t+t0))**(-1.5)
* math.exp(-(x**2+y**2+z**2)/(4.0*nu*(t+t0))) )
q[...] = q1
###############################################################################
# define interpolator and restrictor
def interpolate(yF, yG, fevalF=None, fevalG=None,
dim=1, xrat=2, interpolation_order=-1, **kwargs):
"""Interpolate yG to yF."""
if interpolation_order == -1:
zG = fft.fftn(yG)
zF = np.zeros(fevalF.shape, zG.dtype)
zF[fevalF.half] = zG[fevalG.full]
yF[...] = np.real(2**dim*fft.ifftn(zF))
elif interpolation_order == 2:
if dim != 1:
raise NotImplementedError
yF[0::xrat] = yG
yF[1::xrat] = (yG + np.roll(yG, -1)) / 2.0
elif interpolation_order == 4:
if dim != 1:
raise NotImplementedError
yF[0::xrat] = yG
yF[1::xrat] = ( - np.roll(yG,1)
+ 9.0*yG
+ 9.0*np.roll(yG,-1)
- np.roll(yG,-2) ) / 16.0
else:
raise ValueError, 'interpolation order must be -1, 2 or 4'
def restrict(yF, yG, fevalF=None, fevalG=None,
dim=1, xrat=2, **kwargs):
"""Restrict yF to yG."""
if yF.shape == yG.shape:
yG[:] = yF[:]
elif dim == 1:
yG[:] = yF[::xrat]
elif dim == 2:
y = np.reshape(yF, fevalF.shape)
yG[...] = y[::xrat,::xrat]
elif dim == 3:
y = np.reshape(yF, fevalF.shape)
yG[...] = y[::xrat,::xrat,::xrat]
###############################################################################
# helpers
from itertools import product
def spectral_periodic_masks(dim, N, **kwargs):
"""Spectral interpolation masks."""
if dim == 1:
mask_half = np.zeros(N, dtype=np.bool)
mask_full = np.zeros(N, dtype=np.bool)
full = range(N)
full.remove(N/2)
mask_full[full] = True
half = range(N/4) + range(3*N/4+1, N)
mask_half[half] = True
elif dim == 2:
mask_half = np.zeros((N, N), dtype=np.bool)
mask_full = np.zeros((N, N), dtype=np.bool)
full = range(N)
full.remove(N/2)
for i in product(full, full):
mask_full[i] = True
half = range(N/4) + range(3*N/4+1, N)
for i in product(half, half):
mask_half[i] = True
elif dim == 3:
mask_half = np.zeros((N, N, N), dtype=np.bool)
mask_full = np.zeros((N, N, N), dtype=np.bool)
full = range(N)
full.remove(N/2)
for i in product(full, full, full):
mask_full[i] = True
half = range(N/4) + range(3*N/4+1, N)
for i in product(half, half, half):
mask_half[i] = True
else:
raise ValueError('dimension must be 1, 2, or 3')
return mask_full, mask_half
|