repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
pySDC | pySDC-master/pySDC/playgrounds/ODEs/auzinger_playground.py | import matplotlib.pyplot as plt
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.Auzinger_implicit import auzinger
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.playgrounds.ODEs.trajectory_HookClass import trajectories
def main():
"""
The Auzinger test problem
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = 'LU'
# initialize problem parameters
problem_params = dict()
problem_params['newton_tol'] = 1e-12
problem_params['newton_maxiter'] = 50
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['hook_class'] = trajectories
controller_params['logger_level'] = 30
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = auzinger
description['problem_params'] = problem_params
description['sweeper_class'] = generic_implicit
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
# instantiate the controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.0
Tend = 20.0
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
print('\nError: %8.6e' % err)
plt.ioff()
plt.show()
if __name__ == "__main__":
main()
| 2,117 | 27.621622 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/paralpha/explicit.py | ######################################################################################
# Roberts advection test for IMEX sdc in Paralpha with just an explicit part and Euler
# no spatial variables here, just time
######################################################################################
import numpy as np
# Paralpha settings
N = int(1e03) # spatial points
dt = 1e-03
Tend = 1e-02
L = int(Tend / dt)
alpha = 1e-01
K = 5 # maxiter
# equation settings
T1 = 0
T2 = L * dt + T1
X1 = 0
X2 = 1
c = 1
x = np.linspace(X1, X2, N + 2)[1:-1]
dx = x[1] - x[0]
t = np.linspace(T1, T2, L + 1)[1:]
print(f'CFL: {c*dt/dx}')
print('solving on [{}, {}] x [{}, {}]'.format(T1, T2, X1, X2))
# functions
A = 1 / (1 * dx) * (-np.eye(k=-1, N=N) + np.eye(k=0, N=N))
A[0, -1] = -1 / (1 * dx)
# A = 1/(2 * dx) * (-np.eye(k=-1, N=N) + np.eye(k=1, N=N))
# A[0, -1] = -1/(2 * dx)
# A[-1, 0] = 1/(2 * dx)
def u_exact(t, x):
return np.sin(2 * np.pi * (x - c * t))
def f_exp(t, x, u):
y = -c * A @ u
return y
# the rest
u0 = u_exact(T1, x)
# explicit euler
us = u0.copy()
for l in range(L):
us = us + dt * f_exp(t[l] - dt, x, us)
err_euler = np.linalg.norm((us - u_exact(T2, x)).flatten(), np.inf)
print('seq err = ', err_euler)
Ea = np.eye(k=-1, N=L) # + alpha * np.eye(k=-1, N=L)
Ea[0, -1] = alpha
print(sum([np.linalg.matrix_power(Ea, l) for l in range(10)]))
print(np.linalg.norm(np.linalg.inv(Ea), np.inf))
exit()
print(np.linalg.norm(np.eye(k=-1, N=L) + Ea, np.inf))
u = np.zeros(N * L, dtype=complex)
# for l in range(L):
# u[l * N: (l + 1) * N] = u0
u[:N] = u0
rhs = np.empty(N * L, dtype=complex)
d, S = np.linalg.eig(Ea)
Sinv = np.linalg.inv(S) # S @ d @ Sinv = Ea
print(f'Diagonalization error: {np.linalg.norm(S @ np.diag(d) @ Sinv - Ea, np.inf)}')
# exit()
err = np.linalg.norm(u[-N:] - u_exact(T2, x), np.inf)
print(err, 0)
for k in range(K):
rhs[:N] = u0 - alpha * u[-N:] + dt * f_exp(t[0] - dt, x, u[:N])
for l in range(1, L, 1):
rhs[l * N : (l + 1) * N] = dt * f_exp(t[l] - dt, x, u[(l - 1) * N : l * N]) - alpha * u[(l - 1) * N : l * N]
# u = np.kron(Sinv, np.eye(N)) @ rhs
for i in range(L):
temp = np.zeros(N, dtype=complex)
for j in range(L):
temp += Sinv[i, j] * rhs[j * N : (j + 1) * N]
u[i * N : (i + 1) * N] = temp.copy()
# solve diagonal systems
for l in range(L):
u[l * N : (l + 1) * N] /= 1 + d[l]
# u = np.kron(S, np.eye(N)) @ u
u1 = u.copy()
for i in range(L):
temp = np.zeros(N, dtype=complex)
for j in range(L):
temp += S[i, j] * u1[j * N : (j + 1) * N]
u[i * N : (i + 1) * N] = temp.copy()
err_paralpha = np.linalg.norm((u[-N:] - u_exact(T2, x)).flatten(), np.inf)
print(err_paralpha, k + 1)
if err_euler > err_paralpha:
break
err = np.linalg.norm((us - u[-N:]).flatten(), np.inf)
print('error between seq and paralpha = ', err)
# gc. collect()
| 2,962 | 23.286885 | 116 | py |
pySDC | pySDC-master/pySDC/playgrounds/paralpha/playground_linear.py | import numpy as np
import matplotlib.pyplot as plt
from pySDC.core.Collocation import CollBase
from pySDC.implementations.problem_classes.AdvectionEquation_ND_FD import advectionNd
def run():
nsteps = 8
L = 4
M = 3
N = 16
alpha = 0.001
dt = 0.2
t0 = 0.0
nblocks = nsteps // L
# initialize problem (ADVECTION)
ndim = 1
problem_params = dict()
problem_params['ndim'] = ndim # will be iterated over
problem_params['order'] = 6 # order of accuracy for FD discretization in space
problem_params['type'] = 'center' # order of accuracy for FD discretization in space
problem_params['c'] = 0.1 # diffusion coefficient
problem_params['freq'] = tuple(2 for _ in range(ndim)) # frequencies
problem_params['nvars'] = tuple(N for _ in range(ndim)) # number of dofs
problem_params['solver_type'] = 'GMRES' # do GMRES instead of LU
problem_params['liniter'] = 10 # number of GMRES iterations
problem_params['bc'] = 'periodic' # boundary conditions
prob = advectionNd(problem_params)
IL = np.eye(L)
LM = np.eye(M)
IN = np.eye(N)
coll = CollBase(M, 0, 1, quad_type='RADAU-RIGHT')
Q = coll.Qmat[1:, 1:]
A = prob.A.todense()
E = np.zeros((L, L))
np.fill_diagonal(E[1:, :], 1)
Ealpha = np.zeros((L, L))
np.fill_diagonal(Ealpha[1:, :], 1)
if L > 1:
Ealpha[0, -1] = alpha
H = np.zeros((M, M))
H[:, -1] = 1
C = np.kron(np.kron(IL, LM), IN) - dt * np.kron(np.kron(IL, Q), A) - np.kron(np.kron(E, H), IN)
Calpha = np.kron(np.kron(IL, LM), IN) - dt * np.kron(np.kron(IL, Q), A) - np.kron(np.kron(Ealpha, H), IN)
Calpha_inv = np.linalg.inv(Calpha)
uinit = prob.u_exact(t=t0)
u0_M = np.kron(np.ones(M), uinit)
u0 = np.kron(np.concatenate([[1], [0] * (L - 1)]), u0_M)[:, None]
u = np.kron(np.ones(L * M), uinit)[:, None]
u = u0.copy()
maxiter = 10
for nb in range(nblocks):
k = 0
restol = 1e-10
res = u0 - C @ u
while k < maxiter and np.linalg.norm(res, np.inf) > restol:
k += 1
u += Calpha_inv @ res
res = u0 - C @ u
uex = prob.u_exact(t=t0 + (nb + 1) * L * dt)[:, None]
err = np.linalg.norm(uex - u[-N:], np.inf)
print(k, np.linalg.norm(res, np.inf), err)
uinit = u[-N:, 0]
u0_M = np.kron(np.ones(M), uinit)
u0 = np.kron(np.concatenate([[1], [0] * (L - 1)]), u0_M)[:, None]
u = u0.copy()
# plt.plot(uex-u[-N:])
# plt.plot(uinit)
# plt.plot(u[-N:])
# plt.show()
if __name__ == '__main__':
run()
| 2,638 | 27.376344 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/paralpha/explicit_v2.py | import numpy as np
import scipy.sparse as sp
import scipy.linalg as sl
from pySDC.implementations.problem_classes.AdvectionEquation_ND_FD import advectionNd
def get_config():
problem_params = dict()
problem_params['nvars'] = (1024,)
problem_params['c'] = 1
problem_params['freq'] = (2,)
problem_params['type'] = 'upwind'
problem_params['ndim'] = 1
problem_params['order'] = 1
problem_params['bc'] = 'periodic' # boundary conditions
problem = advectionNd(problem_params)
time_params = dict()
time_params['dt'] = 5e-04
time_params['Tend'] = 1e-02
return problem, time_params
def run_explicit_euler(problem, time_params):
u0 = problem.u_exact(t=0)
dt = time_params['dt']
L = int(time_params['Tend'] / time_params['dt'])
t = 0
# explicit euler
us = problem.dtype_u(u0)
for l in range(L):
us = us + dt * problem.eval_f(us, t=t)
t += dt
err_euler = abs(us - problem.u_exact(t=time_params['Tend']))
print('seq err = ', err_euler)
return err_euler
def get_alpha(m0, rhs1, uL, Lip, L):
eps = np.finfo(complex).eps
norm_rhs1 = max([abs(r) for r in rhs1])
p = L * 6 * eps * norm_rhs1 / (m0 + L * Lip * m0 - L * 3 * eps * norm_rhs1)
alpha = -p / 2 + np.sqrt(p**2 + 2 * p) / 2
m0 = (alpha + L * Lip) / (1 - alpha) * m0 + L * 3 * eps * norm_rhs1 / alpha + L * 3 * eps * abs(uL)
return alpha, m0
def run_paralpha(problem, time_params, err_euler):
# coll = CollGaussRadau_Right(M, 0, 1)
# Q = coll.Qmat[1:, 1:]
dt = time_params['dt']
L = int(time_params['Tend'] / time_params['dt'])
print(L)
kmax = 10
k = 0
Lip = problem.params.c * dt * max(abs(np.linalg.eigvals(problem.A.todense()))) / problem.dx
Lip = problem.params.c * dt / problem.dx
# lip = problem_params['c'] * time_params['dt'] * max(abs(np.linalg.eigvals(problem.A.todense()))) / problem.dx
print(Lip)
u = [problem.dtype_u(problem.init, val=0.0) for _ in range(L)]
u0 = [problem.u_exact(t=0) for _ in range(L)]
m0 = abs(problem.u_exact(0) - problem.u_exact(time_params['Tend']))
err = 99
t = 0
while k < kmax and err > err_euler * 5:
rhs1 = []
for l in range(L):
rhs1.append(dt * problem.eval_f(u[l], t + dt * l))
rhs1[0] += u0[0]
alpha, m0 = get_alpha(m0, rhs1, u[L - 1], Lip, L)
Ea = sp.eye(k=-1, m=L) + alpha * sp.eye(k=L - 1, m=L)
d, S = np.linalg.eig(Ea.todense())
Sinv = np.linalg.inv(S) # S @ d @ Sinv = Ea
print(f'Diagonalization error: {np.linalg.norm(S @ np.diag(d) @ Sinv - Ea, np.inf)}')
rhs1[0] -= alpha * u[-1]
for i in range(L):
tmp = problem.dtype_u(problem.init, val=0.0 + 0.0j)
for j in range(L):
tmp += Sinv[i, j] * rhs1[j]
u[i] = problem.dtype_u(tmp)
for l in range(L):
u[l] = 1.0 / (1.0 - d[l]) * u[l]
u1 = [problem.dtype_u(u[l], val=0.0) for l in range(L)]
for i in range(L):
tmp = problem.dtype_u(problem.init, val=0.0 + 0.0j)
for j in range(L):
tmp += S[i, j] * u1[j]
u[i] = problem.dtype_u(tmp)
err = abs(u[-1] - problem.u_exact(t=time_params['Tend']))
k += 1
print('paralpha err = ', k, alpha, m0, err)
if __name__ == '__main__':
problem, time_params = get_config()
err_euler = run_explicit_euler(problem, time_params)
run_paralpha(problem, time_params, err_euler)
pass
| 3,553 | 27.432 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/paralpha/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/paralpha/playground_nonlinear.py | import numpy as np
import matplotlib.pyplot as plt
from pySDC.implementations.problem_classes.AllenCahn_1D_FD import allencahn_front_fullyimplicit
def run():
nsteps = 4
L = 4
M = 3
N = 127
alpha = 0.001
dt = 0.0001
t0 = 0.0
nblocks = nsteps // L
# initialize problem (ALLEN-CAHN)
problem_params = dict()
problem_params['nvars'] = N
problem_params['dw'] = -0.04
problem_params['eps'] = 0.04
problem_params['newton_maxiter'] = 200
problem_params['newton_tol'] = 1e-08
problem_params['lin_tol'] = 1e-08
problem_params['lin_maxiter'] = 100
problem_params['radius'] = 0.5
problem_params['interval'] = (-2.0, 2.0)
prob = allencahn_front_fullyimplicit(problem_params)
IL = np.eye(L)
LM = np.eye(M)
IN = np.eye(N + 2)
coll = CollGaussRadau_Right(M, 0, 1)
Q = coll.Qmat[1:, 1:]
A = prob.A.todense()
A[0, :] = 0
A[-1, :] = 0
# A[0, 0] = 1
# A[-1, -1] = 1
E = np.zeros((L, L))
np.fill_diagonal(E[1:, :], 1)
Ealpha = np.zeros((L, L))
np.fill_diagonal(Ealpha[1:, :], 1)
if L > 1:
Ealpha[0, -1] = alpha
H = np.zeros((M, M))
H[:, -1] = 1
uinit = np.zeros(N + 2)
uinit[1:-1] = prob.u_exact(t=t0)
uinit[0] = 0.5 * (1 + np.tanh((prob.params.interval[0]) / (np.sqrt(2) * prob.params.eps)))
uinit[-1] = 0.5 * (1 + np.tanh((prob.params.interval[1]) / (np.sqrt(2) * prob.params.eps)))
u0_M = np.kron(np.ones(M), uinit)
u0 = np.kron(np.concatenate([[1], [0] * (L - 1)]), u0_M)[:, None]
u = u0.copy()
maxiter = 10
for nb in range(nblocks):
outer_k = 0
outer_restol = 1e-10
outer_res = u0 - (
(np.kron(np.kron(IL, LM), IN) - np.kron(np.kron(E, H), IN)) @ u
- dt * np.kron(np.kron(IL, Q), A) @ u
+ dt
* np.kron(np.kron(IL, Q), IN)
@ (-2.0 / prob.params.eps**2 * u * (1.0 - u) * (1.0 - 2 * u) - 6.0 * prob.params.dw * u * (1.0 - u))
)
inner_iter = 0
while outer_k < maxiter and np.linalg.norm(outer_res, np.inf) > outer_restol:
outer_k += 1
A_grad = np.zeros((N + 2, N + 2))
for l in range(L):
for m in range(M):
istart = m * (N + 2) + M * l * (N + 2)
iend = istart + N + 2
# print(istart, iend)
tmp = u[istart:iend, 0]
A_grad += (
A
- 2.0
/ prob.params.eps**2
* np.diag((1.0 - tmp) * (1.0 - 2.0 * tmp) - tmp * ((1.0 - 2.0 * tmp) + 2.0 * (1.0 - tmp)))
- 6.0 * prob.params.dw * np.diag((1.0 - tmp) - tmp)
)
A_grad /= L * M
A_grad[0, :] = 0
A_grad[-1, :] = 0
C_grad = -(np.kron(np.kron(IL, LM), IN) - dt * np.kron(np.kron(IL, Q), A_grad) - np.kron(np.kron(E, H), IN))
Calpha_grad = -(
np.kron(np.kron(IL, LM), IN) - dt * np.kron(np.kron(IL, Q), A_grad) - np.kron(np.kron(Ealpha, H), IN)
)
Calpha_grad_inv = np.linalg.inv(Calpha_grad)
inner_k = 0
inner_restol = 1e-11
e = np.zeros(L * M * (N + 2))[:, None]
inner_res = outer_res - C_grad @ e
while inner_k < maxiter and np.linalg.norm(inner_res, np.inf) > inner_restol:
inner_k += 1
e += Calpha_grad_inv @ inner_res
inner_res = outer_res - C_grad @ e
print(inner_k, np.linalg.norm(inner_res, np.inf))
inner_iter += inner_k
u -= e
outer_res = u0 - (
(np.kron(np.kron(IL, LM), IN) - np.kron(np.kron(E, H), IN)) @ u
- dt * np.kron(np.kron(IL, Q), A) @ u
- dt
* np.kron(np.kron(IL, Q), IN)
@ (-2.0 / prob.params.eps**2 * u * (1.0 - u) * (1.0 - 2 * u) - 6.0 * prob.params.dw * u * (1.0 - u))
)
ures = u[-(N + 2) :, 0]
uinit = u[-(N + 2) :, 0]
u0_M = np.kron(np.ones(M), uinit)
u0 = np.kron(np.concatenate([[1], [0] * (L - 1)]), u0_M)[:, None]
u = u0.copy()
uex = np.zeros(N + 2)
t = t0 + (nb + 1) * L * dt
uex[1:-1] = prob.u_exact(t=t)
v = 3.0 * np.sqrt(2) * prob.params.eps * prob.params.dw
uex[0] = 0.5 * (1 + np.tanh((prob.params.interval[0] - v * t) / (np.sqrt(2) * prob.params.eps)))
uex[-1] = 0.5 * (1 + np.tanh((prob.params.interval[1] - v * t) / (np.sqrt(2) * prob.params.eps)))
err = np.linalg.norm(uex[:, None] - ures[:, None], np.inf)
print(outer_k, inner_iter, np.linalg.norm(outer_res, np.inf), err)
uinit = prob.u_exact(t=t0)
# plt.plot(uex)
plt.plot(uex[:, None] - ures[:, None])
# plt.plot(uinit)
# plt.plot(u[-(N + 2):])
plt.show()
if __name__ == '__main__':
run()
| 5,003 | 31.283871 | 120 | py |
pySDC | pySDC-master/pySDC/playgrounds/lagrange/quadrature.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 10 14:07:30 2022
@author: cpf5546
"""
import numpy as np
import matplotlib.pyplot as plt
from time import time
from pySDC.core import NodesGenerator, LagrangeApproximation
from pySDC.implementations.collocations import Collocation
from pySDC.core.Errors import CollocationError
from scipy.integrate import quad
from scipy.interpolate import BarycentricInterpolator
class OriginCollocation(Collocation):
def _getWeights(self, a, b):
"""
Computes weights using barycentric interpolation
Args:
a (float): left interval boundary
b (float): right interval boundary
Returns:
numpy.ndarray: weights of the collocation formula given by the nodes
"""
if self.nodes is None:
raise CollocationError("Need nodes before computing weights, got %s" % self.nodes)
circ_one = np.zeros(self.num_nodes)
circ_one[0] = 1.0
tcks = []
for i in range(self.num_nodes):
tcks.append(BarycentricInterpolator(self.nodes, np.roll(circ_one, i)))
weights = np.zeros(self.num_nodes)
for i in range(self.num_nodes):
weights[i] = quad(tcks[i], a, b, epsabs=1e-14)[0]
return weights
@property
def _gen_Qmatrix(self):
"""
Compute tleft-to-node integration matrix for later use in collocation
formulation
Returns:
numpy.ndarray: matrix containing the weights for tleft to node
"""
M = self.num_nodes
Q = np.zeros([M + 1, M + 1])
# for all nodes, get weights for the interval [tleft,node]
for m in np.arange(M):
Q[m + 1, 1:] = self._getWeights(self.tleft, self.nodes[m])
return Q
def getLastPlotCol():
return plt.gca().get_lines()[-1].get_color()
nodeTypes = ['EQUID', 'LEGENDRE']
quadTypes = ['LOBATTO', 'RADAU-LEFT', 'RADAU-RIGHT', 'GAUSS']
symbols = ['s', '>', '<', 'o']
nMax = 12
nNodes = np.arange(3, nMax + 1)
nInterTest = 10
nPolyTest = 20
QMatrixOrder = lambda n: n - 1 - (n % 2)
weightsOrder = {
'EQUID': lambda n: n - 1 - (n % 2),
'LEGENDRE': {
'LOBATTO': lambda n: 2 * n - 3,
'RADAU-LEFT': lambda n: 2 * n - 2,
'RADAU-RIGHT': lambda n: 2 * n - 2,
'GAUSS': lambda n: 2 * n - 1,
},
}
def testWeights(weights, nodes, orderFunc, tBeg, tEnd):
deg = orderFunc(np.size(nodes))
err = np.zeros(nPolyTest)
for i in range(nPolyTest):
poly_coeff = np.random.rand(deg + 1)
poly_vals = np.polyval(poly_coeff, nodes)
poly_int_coeff = np.polyint(poly_coeff)
int_ex = np.polyval(poly_int_coeff, tEnd) - np.polyval(poly_int_coeff, tBeg)
int_coll = np.sum(weights * poly_vals)
err[i] = abs(int_ex - int_coll)
return err
def testQMatrix(QMatrix, nodes, tBeg):
n = np.size(nodes)
deg = QMatrixOrder(n)
err = np.zeros((nPolyTest, n))
for i in range(nPolyTest):
poly_coeff = np.random.rand(deg + 1)
poly_vals = np.polyval(poly_coeff, nodes)
poly_int_coeff = np.polyint(poly_coeff)
for j in range(n):
int_ex = np.polyval(poly_int_coeff, nodes[j])
int_ex -= np.polyval(poly_int_coeff, tBeg)
int_coll = np.sum(poly_vals * QMatrix[j, :])
err[i, j] = abs(int_ex - int_coll)
return err
def computeQuadratureErrors(nodeType, quadType, numQuad):
errors = np.zeros((4, nMax - 2))
errWeights = errors[:2]
errQuad = errors[2:]
tComp = np.zeros(nMax - 2)
np.random.seed(1990)
for i in range(nInterTest):
tLeft = np.random.rand() * 0.2
tRight = 0.8 + np.random.rand() * 0.2
for l, n in enumerate(nNodes):
tBeg = time()
if numQuad == 'ORIG':
# Use origin collocation class
coll = OriginCollocation(n, tLeft, tRight, nodeType, quadType)
nodes = coll.nodes
weights = coll.weights
QMatrix = coll.Qmat[1:, 1:]
elif numQuad == 'NEW':
# Use collocation class
coll = Collocation(n, tLeft, tRight, nodeType, quadType)
nodes = coll.nodes
weights = coll.weights
QMatrix = coll.Qmat[1:, 1:]
else:
# Generate nodes
nodesGen = NodesGenerator(nodeType, quadType)
nodes = nodesGen.getNodes(n)
a = tLeft
b = tRight
nodes += 1
nodes /= 2
nodes *= b - a
nodes += a
# Set-up Lagrange interpolation polynomial
approx = LagrangeApproximation(nodes)
# Compute quadrature weights for the whole interval
weights = approx.getIntegrationMatrix([[tLeft, tRight]], numQuad=numQuad)
# Compute quadrature weights for the Q matrix
QMatrix = approx.getIntegrationMatrix([[tLeft, tau] for tau in approx.points], numQuad=numQuad)
tComp[l] += time() - tBeg
# Get the corresponding accuracy order
try:
orderFunc = weightsOrder[nodeType]
orderFunc(1990)
except TypeError:
orderFunc = orderFunc[quadType]
# Test weights error
err = testWeights(weights, nodes, orderFunc, tLeft, tRight)
errWeights[0, l] += np.sum(err)
errWeights[1, l] = max(np.max(err), errWeights[1, l])
# Test quadrature matrix error
err = testQMatrix(QMatrix, nodes, tLeft)
errQuad[0, l] += np.sum(err)
errQuad[1, l] = max(np.max(err), errQuad[1, l])
errWeights[0] /= nPolyTest * nInterTest
errQuad[0] /= nPolyTest * nInterTest * nNodes
tComp /= nInterTest
return errors, tComp
def plotQuadErrors(nodesType, numQuad, figTitle=False):
def setFig(title, err=True):
plt.title(title)
plt.grid(True)
plt.legend()
if err:
if numQuad == 'ORIG':
plt.ylim(1e-17, 1e-9)
else:
plt.ylim(1e-17, 1e-11)
plt.xlabel('Polynomial degree')
plt.figure()
maxWeigts = 0
maxQMatrix = 0
for qType, sym in zip(quadTypes, symbols):
errs, tComp = computeQuadratureErrors(nodesType, qType, numQuad)
plt.subplot(1, 3, 1)
plt.semilogy(nNodes - 1, errs[0], sym + '-', label=qType)
plt.semilogy(nNodes - 1, errs[1], sym + ':', c=getLastPlotCol())
maxWeigts = max(maxWeigts, errs[1].max())
setFig('Weights error')
plt.subplot(1, 3, 2)
plt.semilogy(nNodes - 1, errs[2], sym + '-', label=qType)
plt.semilogy(nNodes - 1, errs[3], sym + ':', c=getLastPlotCol())
maxQMatrix = max(maxQMatrix, errs[3].max())
setFig('QMatrix error')
plt.subplot(1, 3, 3)
plt.semilogy(nNodes - 1, tComp, sym + '-', label=qType)
setFig('Computation time', err=False)
textArgs = dict(bbox=dict(boxstyle="round", ec=(0.5, 0.5, 0.5), fc=(0.8, 0.8, 0.8)))
plt.subplot(1, 3, 1)
plt.hlines(maxWeigts, 2, nMax, linestyles='--', colors='gray')
plt.text(7, 1.5 * maxWeigts, f'{maxWeigts:1.2e}', **textArgs)
plt.subplot(1, 3, 2)
plt.hlines(maxQMatrix, 2, nMax, linestyles='--', colors='gray')
plt.text(7, 1.5 * maxQMatrix, f'{maxQMatrix:1.2e}', **textArgs)
if figTitle:
plt.suptitle(f'node distribution : {nodesType}; ' f'numQuad : {numQuad}')
plt.gcf().set_size_inches(17, 5)
plt.tight_layout()
if __name__ == '__main__':
nodesType = 'EQUID'
numQuad = 'ORIG'
plotQuadErrors(nodesType, numQuad)
| 7,811 | 30.5 | 111 | py |
pySDC | pySDC-master/pySDC/playgrounds/lagrange/__init__.py | #
| 2 | 0.5 | 1 | py |
pySDC | pySDC-master/pySDC/playgrounds/VSDC/hamiltonian_output.py | from pySDC.core.Hooks import hooks
class hamiltonian_output(hooks):
def __init__(self):
"""
Initialization of particles output
"""
super(hamiltonian_output, self).__init__()
self.ham_init = None
def pre_run(self, step, level_number):
# some abbreviations
L = step.levels[0]
P = L.prob
super(hamiltonian_output, self).pre_run(step, level_number)
self.ham_init = P.eval_hamiltonian(L.u[0])
def post_iteration(self, step, level_number):
"""
Overwrite standard post iteration hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(hamiltonian_output, self).post_iteration(step, level_number)
# some abbreviations
L = step.levels[0]
P = L.prob
L.sweep.compute_end_point()
H = P.eval_hamiltonian(L.uend)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='hamiltonian',
value=H,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='err_hamiltonian',
value=abs(self.ham_init - H),
)
return None
def post_step(self, step, level_number):
"""
Overwrite standard post iteration hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(hamiltonian_output, self).post_step(step, level_number)
# some abbreviations
L = step.levels[0]
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='position',
value=L.uend.pos,
)
return None
| 2,130 | 24.987805 | 74 | py |
pySDC | pySDC-master/pySDC/playgrounds/VSDC/simple_problems.py | import os
from collections import defaultdict
import dill
import numpy as np
import pySDC.helpers.plot_helper as plt_helper
from pySDC.helpers.stats_helper import get_sorted, filter_stats
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HarmonicOscillator import harmonic_oscillator
from pySDC.implementations.problem_classes.HenonHeiles import henon_heiles
from pySDC.implementations.sweeper_classes.verlet import verlet
from pySDC.implementations.transfer_classes.TransferParticles_NoCoarse import particles_to_particles
from pySDC.projects.Hamiltonian.hamiltonian_output import hamiltonian_output
def setup_harmonic():
"""
Helper routine for setting up everything for the harmonic oscillator
Returns:
description (dict): description of the controller
controller_params (dict): controller parameters
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.5
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = [5]
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters for the Penning trap
problem_params = dict()
problem_params['k'] = 1.0
problem_params['phase'] = 0.0
problem_params['amp'] = 1.0
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 3
# initialize controller parameters
controller_params = dict()
controller_params['hook_class'] = hamiltonian_output # specialized hook class for more statistics and output
controller_params['logger_level'] = 30
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = harmonic_oscillator
description['problem_params'] = problem_params
description['sweeper_class'] = verlet
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
# description['space_transfer_class'] = particles_to_particles
return description, controller_params
def setup_henonheiles():
"""
Helper routine for setting up everything for the Henon Heiles problem
Returns:
description (dict): description of the controller
controller_params (dict): controller parameters
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 0e-10
level_params['dt'] = 0.25
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = [5]
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters for the Penning trap
problem_params = dict()
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 5
# initialize controller parameters
controller_params = dict()
controller_params['hook_class'] = hamiltonian_output # specialized hook class for more statistics and output
controller_params['logger_level'] = 30
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = henon_heiles
description['problem_params'] = problem_params
description['sweeper_class'] = verlet
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
# description['space_transfer_class'] = particles_to_particles
return description, controller_params
def run_simulation(prob=None):
"""
Routine to run the simulation of a second order problem
Args:
prob (str): name of the problem
"""
# check what problem type we have and set up corresponding description and variables
if prob == 'harmonic':
description, controller_params = setup_harmonic()
# set time parameters
t0 = 0.0
Tend = 5000.0
num_procs = 1
elif prob == 'henonheiles':
description, controller_params = setup_henonheiles()
# set time parameters
t0 = 0.0
Tend = 100000.0
num_procs = 1
else:
raise NotImplemented('Problem type not implemented, got %s' % prob)
# instantiate the controller
controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t=t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
# for item in iter_counts:
# out = 'Number of iterations for time %4.2f: %2i' % item
# print(out)
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
fname = 'data/' + prob + '.dat'
f = open(fname, 'wb')
dill.dump(stats, f)
f.close()
assert os.path.isfile(fname), 'Run for %s did not create stats file' % prob
def show_results(prob=None, cwd=''):
"""
Helper function to plot the error of the Hamiltonian
Args:
prob (str): name of the problem
cwd (str): current working directory
"""
# read in the dill data
f = open(cwd + 'data/' + prob + '.dat', 'rb')
stats = dill.load(f)
f.close()
# extract error in hamiltonian and prepare for plotting
extract_stats = filter_stats(stats, type='err_hamiltonian')
result = defaultdict(list)
for k, v in extract_stats.items():
result[k.iter].append((k.time, v))
for k, v in result.items():
result[k] = sorted(result[k], key=lambda x: x[0])
plt_helper.mpl.style.use('classic')
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=0.89)
# Rearrange data for easy plotting
err_ham = 1
for k, v in result.items():
time = [item[0] for item in v]
ham = [item[1] for item in v]
err_ham = ham[-1]
plt_helper.plt.semilogy(time, ham, '-', lw=1, label='Iter ' + str(k))
plt_helper.plt.xlabel('Time')
plt_helper.plt.ylabel('Error in Hamiltonian')
plt_helper.plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
fname = 'data/' + prob + '_hamiltonian'
plt_helper.savefig(fname)
assert os.path.isfile(fname + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(fname + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(fname + '.png'), 'ERROR: plotting did not create PNG file'
def main():
# prob = 'harmonic'
# run_simulation(prob)
# show_results(prob)
prob = 'henonheiles'
run_simulation(prob)
show_results(prob)
if __name__ == "__main__":
main()
| 7,442 | 31.502183 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/VSDC/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/VSDC/hamiltonian_and_energy_output.py | from pySDC.core.Hooks import hooks
class hamiltonian_and_energy_output(hooks):
def __init__(self):
"""
Initialization of particles output
"""
super(hamiltonian_and_energy_output, self).__init__()
self.ham_init = None
self.energy_init = None
def pre_run(self, step, level_number):
# some abbreviations
L = step.levels[0]
P = L.prob
super(hamiltonian_and_energy_output, self).pre_run(step, level_number)
self.ham_init = P.eval_hamiltonian(L.u[0])
self.energy_init = P.eval_mode_energy(L.u[0])
def post_iteration(self, step, level_number):
"""
Overwrite standard post iteration hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(hamiltonian_and_energy_output, self).post_iteration(step, level_number)
# some abbreviations
L = step.levels[0]
P = L.prob
L.sweep.compute_end_point()
H = P.eval_hamiltonian(L.uend)
E = P.eval_mode_energy(L.uend)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='hamiltonian',
value=H,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='err_hamiltonian',
value=abs(self.ham_init - H),
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='energy_iter',
value=E,
)
return None
def post_step(self, step, level_number):
"""
Overwrite standard post iteration hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(hamiltonian_and_energy_output, self).post_step(step, level_number)
# some abbreviations
L = step.levels[0]
P = L.prob
E = P.eval_mode_energy(L.uend)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='position',
value=L.uend.pos,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='energy_step',
value=E,
)
return None
| 2,859 | 25.481481 | 85 | py |
pySDC | pySDC-master/pySDC/playgrounds/12th_PinT_Workshop/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/HeatEquation/periodic_playground.py | import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
def main():
"""
A simple test program to do PFASST runs for the heat equation
"""
# set up number of parallel time-steps to run PFASST with
num_proc = 16
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 1.0 / num_proc
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['nvars'] = [128, 64] # number of degrees of freedom for each level
problem_params['bc'] = 'periodic' # BCs
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 0
space_transfer_params['iorder'] = 2
space_transfer_params['periodic'] = True
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
# controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_unforced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
# set time parameters
t0 = 0.0
Tend = 1.0
# instantiate controller
controller = controller_nonMPI(num_procs=num_proc, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %2i' % item
print(out)
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
print('CFL number: %4.2f' % (level_params['dt'] * problem_params['nu'] / (1.0 / problem_params['nvars'][0]) ** 2))
print('Error: %8.4e' % err)
if __name__ == "__main__":
main()
| 4,042 | 36.785047 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/HeatEquation/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/HeatEquation/HookClass_error_output.py | from pySDC.core.Hooks import hooks
class error_output(hooks):
"""
Hook class to add output of error
"""
def pre_iteration(self, step, level_number):
super(error_output, self).pre_iteration(step, level_number)
# some abbreviations
L = step.levels[level_number]
P = L.prob
for m in range(1, L.sweep.coll.num_nodes + 1):
L.uold[m] = P.dtype_u(L.u[m])
def post_iteration(self, step, level_number):
"""
Default routine called after each iteration
Args:
step: the current step
level_number: the current level number
"""
super(error_output, self).post_iteration(step, level_number)
# some abbreviations
L = step.levels[level_number]
P = L.prob
L.sweep.compute_end_point()
uex = P.u_exact(step.time + step.dt)
err = abs(uex - L.uend)
est = []
for m in range(1, L.sweep.coll.num_nodes + 1):
est.append(abs(L.uold[m] - L.u[m]))
est_all = max(est)
print(step.status.iter, err, est_all, L.status.residual)
| 1,137 | 23.212766 | 68 | py |
pySDC | pySDC-master/pySDC/playgrounds/FEniCS/heat_equation_weak.py | from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_1D_FEniCS_weak_forced import fenics_heat_weak_imex
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferFenicsMesh import mesh_to_mesh_fenics
if __name__ == "__main__":
num_procs = 1
t0 = 0
dt = 0.2
Tend = 1.0
# initialize level parameters
level_params = dict()
level_params['restol'] = 5e-12
level_params['dt'] = dt
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
problem_params = dict()
problem_params['nu'] = 0.1
problem_params['t0'] = t0 # ugly, but necessary to set up ProblemClass
problem_params['c_nvars'] = [128]
problem_params['family'] = 'CG'
problem_params['order'] = [4]
problem_params['refinements'] = [0]
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
base_transfer_params = dict()
base_transfer_params['finter'] = True
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = fenics_heat_weak_imex
description['problem_params'] = problem_params
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fenics # pass spatial transfer class
description['base_transfer_params'] = base_transfer_params # pass paramters for spatial transfer
# quickly generate block of steps
controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
print('(classical) error at time %s: %s' % (Tend, abs(uex - uend) / abs(uex)))
| 2,508 | 36.447761 | 117 | py |
pySDC | pySDC-master/pySDC/playgrounds/FEniCS/mass_playground.py | import dolfin as df
import numpy as np
import matplotlib.pyplot as plt
import pySDC.helpers.plot_helper as plt_helper
import pylustrator
# pylustrator.start()
N = 128 # Number of elements
k = 7 # Wave frequency
d = 4 # FE order
# Get mesh and function space (CG or DG)
mesh = df.UnitIntervalMesh(N)
V = df.FunctionSpace(mesh, "CG", d)
# V = df.FunctionSpace(mesh, "DG", d)
# Build mass matrix
u = df.TrialFunction(V)
v = df.TestFunction(V)
a_M = u * v * df.dx
M = df.assemble(a_M)
# Create vector with sine function
u0 = df.Expression('sin(k*pi*x[0])', pi=np.pi, k=k, degree=d)
w = df.interpolate(u0, V)
# Apply mass matrix to this vector
Mw = df.Function(V)
M.mult(w.vector(), Mw.vector())
# Do FFT to get the frequencies
fw = np.fft.fft(w.vector()[:])
fMw = np.fft.fft(Mw.vector()[:])
# Shift to have zero frequency in the middle of the plot
fw2 = np.fft.fftshift(fw)
fMw2 = np.fft.fftshift(fMw)
fw2 /= np.amax(abs(fw2))
fMw2 /= np.amax(abs(fMw2))
ndofs = fw.shape[0]
# Plot
plt_helper.setup_mpl()
plt_helper.newfig(240, 1, ratio=0.8)
plt_helper.plt.plot(abs(fw2), lw=2, label=f'N = {N} \n degree = {d} \n wave number = {k}')
plt_helper.plt.xticks(
[0, ndofs / 4 - 1, ndofs / 2 - 1, 3 * ndofs / 4 - 1, ndofs - 1],
(r'-$\pi$', r'-$\pi/2$', r'$0$', r'+$\pi$/2', r'+$\pi$'),
)
plt_helper.plt.xlabel('spectrum')
plt_helper.plt.ylabel('normed amplitude')
# plt_helper.plt.legend()
plt_helper.plt.grid()
plt_helper.savefig('spectrum_noM_CG')
# plt_helper.savefig('spectrum_noM_DG')
# plt_helper.savefig('spectrum_noM_DG_8')
plt_helper.newfig(240, 1, ratio=0.8)
plt_helper.plt.plot(abs(fMw2), lw=2, label=f'N = {N} \n degree = {d} \n wave number = {k}')
plt_helper.plt.xticks(
[0, ndofs / 4 - 1, ndofs / 2 - 1, 3 * ndofs / 4 - 1, ndofs - 1],
(r'-$\pi$', r'-$\pi/2$', r'$0$', r'+$\pi$/2', r'+$\pi$'),
)
plt_helper.plt.xlabel('spectrum')
plt_helper.plt.ylabel('normed amplitude')
# plt_helper.plt.legend()
plt_helper.plt.grid()
plt_helper.savefig('spectrum_M_CG')
# plt_helper.savefig('spectrum_M_DG')
# plt_helper.savefig('spectrum_M_DG_8')
# plt.show()
| 2,083 | 25.379747 | 91 | py |
pySDC | pySDC-master/pySDC/playgrounds/FEniCS/heat_equation_M.py | import numpy as np
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_1D_FEniCS_matrix_forced import fenics_heat_mass
from pySDC.implementations.sweeper_classes.imex_1st_order_mass import imex_1st_order_mass
from pySDC.implementations.transfer_classes.BaseTransfer_mass import base_transfer_mass
from pySDC.implementations.transfer_classes.TransferFenicsMesh import mesh_to_mesh_fenics
from pySDC.implementations.problem_classes.HeatEquation_1D_FEniCS_matrix_forced import fenics_heat
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.playgrounds.FEniCS.HookClass_FEniCS_output import fenics_output
from pySDC.helpers.stats_helper import get_sorted
import pySDC.helpers.plot_helper as plt_helper
def run_simulation(ml=None, mass=None):
t0 = 0
dt = 0.2
Tend = 0.2
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = dt
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
problem_params = dict()
problem_params['nu'] = 0.1
problem_params['t0'] = t0 # ugly, but necessary to set up ProblemClass
problem_params['c_nvars'] = [128]
problem_params['family'] = 'CG'
problem_params['order'] = [4]
if ml:
problem_params['refinements'] = [1, 0]
else:
problem_params['refinements'] = [1]
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = fenics_output
# Fill description dictionary for easy hierarchy creation
description = dict()
if mass:
description['problem_class'] = fenics_heat_mass
description['sweeper_class'] = imex_1st_order_mass
description['base_transfer_class'] = base_transfer_mass
else:
description['problem_class'] = fenics_heat
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['problem_params'] = problem_params
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
description['space_transfer_class'] = mesh_to_mesh_fenics
# quickly generate block of steps
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
errors = get_sorted(stats, type='error', sortby='iter')
residuals = get_sorted(stats, type='residual', sortby='iter')
return errors, residuals
def visualize():
errors_sdc_M = np.load('errors_sdc_M.npy')
errors_sdc_noM = np.load('errors_sdc_noM.npy')
errors_mlsdc_M = np.load('errors_mlsdc_M.npy')
errors_mlsdc_noM = np.load('errors_mlsdc_noM.npy')
plt_helper.setup_mpl()
plt_helper.newfig(240, 1, ratio=0.8)
plt_helper.plt.semilogy(
[err[0] for err in errors_sdc_noM],
[err[1] for err in errors_sdc_noM],
lw=2,
marker='s',
markersize=6,
color='darkblue',
label='SDC without M',
)
plt_helper.plt.xlim([0, 11])
plt_helper.plt.ylim([6e-09, 2e-03])
plt_helper.plt.xlabel('iteration')
plt_helper.plt.ylabel('error')
plt_helper.plt.legend()
plt_helper.plt.grid()
plt_helper.savefig('error_SDC_noM_CG_4')
plt_helper.newfig(240, 1, ratio=0.8)
plt_helper.plt.semilogy(
[err[0] for err in errors_sdc_noM],
[err[1] for err in errors_sdc_noM],
lw=2,
color='darkblue',
marker='s',
markersize=6,
label='SDC without M',
)
plt_helper.plt.semilogy(
[err[0] for err in errors_sdc_M],
[err[1] for err in errors_sdc_M],
lw=2,
marker='o',
markersize=6,
color='red',
label='SDC with M',
)
plt_helper.plt.xlim([0, 11])
plt_helper.plt.ylim([6e-09, 2e-03])
plt_helper.plt.xlabel('iteration')
plt_helper.plt.ylabel('error')
plt_helper.plt.legend()
plt_helper.plt.grid()
plt_helper.savefig('error_SDC_M_CG_4')
plt_helper.newfig(240, 1, ratio=0.8)
plt_helper.plt.semilogy(
[err[0] for err in errors_mlsdc_noM],
[err[1] for err in errors_mlsdc_noM],
lw=2,
marker='s',
markersize=6,
color='darkblue',
label='MLSDC without M',
)
plt_helper.plt.xlim([0, 11])
plt_helper.plt.ylim([6e-09, 2e-03])
plt_helper.plt.xlabel('iteration')
plt_helper.plt.ylabel('error')
plt_helper.plt.legend()
plt_helper.plt.grid()
plt_helper.savefig('error_MLSDC_noM_CG_4')
plt_helper.newfig(240, 1, ratio=0.8)
plt_helper.plt.semilogy(
[err[0] for err in errors_mlsdc_noM],
[err[1] for err in errors_mlsdc_noM],
lw=2,
color='darkblue',
marker='s',
markersize=6,
label='MLSDC without M',
)
plt_helper.plt.semilogy(
[err[0] for err in errors_mlsdc_M],
[err[1] for err in errors_mlsdc_M],
lw=2,
marker='o',
markersize=6,
color='red',
label='MLSDC with M',
)
plt_helper.plt.xlim([0, 11])
plt_helper.plt.ylim([6e-09, 2e-03])
plt_helper.plt.xlabel('iteration')
plt_helper.plt.ylabel('error')
plt_helper.plt.legend()
plt_helper.plt.grid()
plt_helper.savefig('error_MLSDC_M_CG_4')
if __name__ == "__main__":
# errors_sdc_noM, _ = run_simulation(ml=False, mass=False)
# errors_sdc_M, _ = run_simulation(ml=False, mass=True)
# errors_mlsdc_noM, _ = run_simulation(ml=True, mass=False)
# errors_mlsdc_M, _ = run_simulation(ml=True, mass=True)
#
# np.save('errors_sdc_M.npy', errors_sdc_M)
# np.save('errors_sdc_noM.npy', errors_sdc_noM)
# np.save('errors_mlsdc_M.npy', errors_mlsdc_M)
# np.save('errors_mlsdc_noM.npy', errors_mlsdc_noM)
visualize()
| 6,347 | 29.228571 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/FEniCS/heat_equation_Minv.py | from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_1D_FEniCS_matrix_forced import fenics_heat
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferFenicsMesh import mesh_to_mesh_fenics
from pySDC.playgrounds.FEniCS.HookClass_FEniCS_output import fenics_output
from pySDC.helpers.stats_helper import get_sorted
if __name__ == "__main__":
num_procs = 1
t0 = 0
dt = 0.2
Tend = 0.2
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = dt
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
problem_params = dict()
problem_params['nu'] = 0.1
problem_params['t0'] = t0 # ugly, but necessary to set up ProblemClass
problem_params['c_nvars'] = [128]
problem_params['family'] = 'CG'
problem_params['order'] = [4]
problem_params['refinements'] = [1, 0]
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
controller_params['hook_class'] = fenics_output
base_transfer_params = dict()
# base_transfer_params['finter'] = True
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = fenics_heat
description['problem_params'] = problem_params
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fenics # pass spatial transfer class
description['base_transfer_params'] = base_transfer_params # pass paramters for spatial transfer
# quickly generate block of steps
controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
print('(classical) error at time %s: %s' % (Tend, abs(uex - uend) / abs(uex)))
errors = get_sorted(stats, type='error', sortby='iter')
residuals = get_sorted(stats, type='residual', sortby='iter')
for err, res in zip(errors, residuals):
print(err[0], err[1], res[1])
| 2,883 | 36.454545 | 117 | py |
pySDC | pySDC-master/pySDC/playgrounds/FEniCS/HookClass_FEniCS_output.py | import dolfin as df
from pySDC.core.Hooks import hooks
file = df.File('output1d/grayscott.pvd') # dirty, but this has to be unique (and not per step or level)
class fenics_output(hooks):
"""
Hook class to add output to FEniCS runs
"""
# def pre_run(self, step, level_number):
# """
# Overwrite default routine called before time-loop starts
#
# Args:
# step: the current step
# level_number: the current level number
# """
# super(fenics_output, self).pre_run(step, level_number)
#
# # some abbreviations
# L = step.levels[level_number]
#
# v = L.u[0].values
# v.rename('func', 'label')
#
# file << v
def post_iteration(self, step, level_number):
super(fenics_output, self).post_iteration(step, level_number)
# some abbreviations
L = step.levels[level_number]
uex = L.prob.u_exact(L.time + L.dt)
err = abs(uex - L.u[-1]) / abs(uex)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='error',
value=err,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='residual',
value=L.status.residual / abs(L.u[0]),
)
# def post_step(self, step, level_number):
# """
# Default routine called after each iteration
# Args:
# step: the current step
# level_number: the current level number
# """
#
# super(fenics_output, self).post_step(step, level_number)
#
# # some abbreviations
# L = step.levels[level_number]
#
# # u1,u2 = df.split(L.uend.values)
# v = L.uend.values
# v.rename('func', 'label')
#
# file << v
| 2,084 | 25.0625 | 104 | py |
pySDC | pySDC-master/pySDC/playgrounds/FEniCS/weak_formulation_heat.py | from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_1D_FEniCS_weak_forced import fenics_heat
from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.implementations.transfer_classes.TransferFenicsMesh import mesh_to_mesh_fenics
if __name__ == "__main__":
num_procs = 1
t0 = 0
dt = 0.5
Tend = 8.0
# initialize level parameters
level_params = dict()
level_params['restol'] = 5e-09
level_params['dt'] = dt
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['finter'] = True
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
problem_params = dict()
problem_params['nu'] = 1.0
problem_params['t0'] = t0 # ugly, but necessary to set up ProblemClass
problem_params['c_nvars'] = [128]
problem_params['family'] = 'CG'
problem_params['order'] = [4]
problem_params['refinements'] = [1, 0]
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = fenics_heat
description['problem_params'] = problem_params
description['sweeper_class'] = generic_LU # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fenics # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
# quickly generate block of steps
controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
print('(classical) error at time %s: %s' % (Tend, abs(uex - uend) / abs(uex)))
| 2,526 | 36.161765 | 117 | py |
pySDC | pySDC-master/pySDC/playgrounds/FEniCS/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/FEniCS/vortex.py | from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.VorticityVelocity_2D_FEniCS_periodic import fenics_vortex_2d
from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.implementations.transfer_classes.TransferFenicsMesh import mesh_to_mesh_fenics
if __name__ == "__main__":
num_procs = 1
t0 = 0
dt = 0.001
Tend = 4 * dt
# initialize level parameters
level_params = dict()
level_params['restol'] = 5e-09
level_params['dt'] = dt
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['finter'] = True
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
problem_params = dict()
problem_params['nu'] = 0.01
problem_params['delta'] = 0.05
problem_params['rho'] = 50
problem_params['c_nvars'] = [(32, 32)]
problem_params['family'] = 'CG'
problem_params['order'] = [4]
problem_params['refinements'] = [1, 0]
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = fenics_vortex_2d
description['problem_params'] = problem_params
description['sweeper_class'] = generic_LU # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fenics # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
# quickly generate block of steps
controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
print('(classical) error at time %s: %s' % (Tend, abs(uex - uend) / abs(uex)))
| 2,539 | 35.811594 | 117 | py |
pySDC | pySDC-master/pySDC/playgrounds/FEniCS/playground.py | import dolfin as df
mesh1 = df.UnitSquareMesh(2, 2)
mesh2 = df.UnitSquareMesh(2, 2)
V1 = df.FunctionSpace(mesh1, "CG", 1)
V2 = df.FunctionSpace(mesh2, "CG", 1)
u1 = df.Function(V1)
v1 = df.TestFunction(V1)
u2 = df.Function(V2)
v2 = df.TestFunction(V2)
u3 = df.Function(V2)
u1.vector()[0] = 1
u3.vector()[:] = u1.vector()[:]
u1.vector()[0] = 2
print(u1.vector()[0], u3.vector()[0])
df.assemble(-1.0 * df.inner(df.grad(u1), df.grad(v1)) * df.dx)
df.assemble(-1.0 * df.inner(df.grad(u2), df.grad(v2)) * df.dx)
df.assemble(-1.0 * df.inner(df.grad(u3), df.grad(v2)) * df.dx)
| 575 | 24.043478 | 62 | py |
pySDC | pySDC-master/pySDC/playgrounds/libpfasst/playground_advdiff.py | import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AdvectionDiffusionEquation_1D_FFT import advectiondiffusion1d_implicit
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.transfer_classes.TransferMesh_FFT import mesh_to_mesh_fft
from pySDC.playgrounds.fft.libpfasst_output import libpfasst_output
def main():
"""
A simple test program to do PFASST runs for the heat equation
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-12
level_params['dt'] = 0.9 / 32
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = [5, 3]
sweeper_params['QI'] = ['LU']
sweeper_params['initial_guess'] = 'spread'
sweeper_params['do_coll_update'] = False
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.02 # diffusion coefficient
problem_params['c'] = 1.0 # advection speed
problem_params['freq'] = -1 # frequency for the test value
problem_params['nvars'] = [256, 128] # number of degrees of freedom for each level
problem_params['L'] = 1.0 # length of the interval [-L/2, L/2]
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 10
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
controller_params['hook_class'] = libpfasst_output
controller_params['log_to_file'] = True
# fill description dictionary for easy step instantiation
description = dict()
# description['problem_class'] = advectiondiffusion1d_imex # pass problem class
description['problem_class'] = advectiondiffusion1d_implicit # pass problem class
description['problem_params'] = problem_params # pass problem parameters
# description['sweeper_class'] = imex_1st_order # pass sweeper
description['sweeper_class'] = generic_implicit # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fft # pass spatial transfer class
description['space_transfer_params'] = dict() # pass paramters for spatial transfer
# set time parameters
t0 = 0.0
Tend = level_params['dt']
num_proc = 1
# instantiate controller
controller = controller_nonMPI(num_procs=num_proc, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# print(controller.MS[0].levels[0].sweep.coll.Qmat)
# print(controller.MS[0].levels[0].sweep.QI)
# exit()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %2i' % item
print(out)
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
print('Error: %8.4e' % err)
if __name__ == "__main__":
main()
| 4,116 | 37.12037 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/libpfasst/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/Boris/spiraling_particle_ProblemClass.py | import numpy as np
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.particles import particles, fields, acceleration
class planewave_single(ptype):
"""
Example implementing a single particle spiraling in a trap
"""
def __init__(self, cparams, dtype_u=particles, dtype_f=fields):
"""
Initialization routine
Args:
cparams: custom parameters for the example
dtype_u: particle data type (will be passed parent class)
dtype_f: fields data type (will be passed parent class)
"""
# these parameters will be used later, so assert their existence
assert 'delta' in cparams # polarization
assert 'a0' in cparams # normalized amplitude
assert 'u0' in cparams # initial position and velocity
# add parameters as attributes for further reference
for k, v in cparams.items():
setattr(self, k, v)
# set nparts to one (lonely particle, you know)
self.nparts = 1
# invoke super init, passing nparts, dtype_u and dtype_f
super(planewave_single, self).__init__((self.nparts, None, np.dtype('float64')), dtype_u, dtype_f, cparams)
def eval_f(self, part, t):
"""
Routine to compute the electric and magnetic fields
Args:
t: current time
part: the current particle
Returns:
E and B field for the particle (external only)
"""
f = self.dtype_f(((3, self.nparts), self.init[1], self.init[2]))
R = np.linalg.norm(part.pos[:, 0], 2)
f.elec[0, 0] = self.params.a0 / (R**3) * part.pos[0, 0]
f.elec[1, 0] = self.params.a0 / (R**3) * part.pos[1, 0]
f.elec[2, 0] = 0
f.magn[0, 0] = 0
f.magn[1, 0] = 0
f.magn[2, 0] = R
return f
def u_init(self):
"""
Initialization routine for the single particle
Returns:
particle type
"""
u0 = self.params.u0
# some abbreviations
u = self.dtype_u(((3, 1), self.init[1], self.init[2]))
u.pos[0, 0] = u0[0][0]
u.pos[1, 0] = u0[0][1]
u.pos[2, 0] = u0[0][2]
u.vel[0, 0] = u0[1][0]
u.vel[1, 0] = u0[1][1]
u.vel[2, 0] = u0[1][2]
u.q[:] = u0[2][0]
u.m[:] = u0[3][0]
return u
def build_f(self, f, part, t):
"""
Helper function to assemble the correct right-hand side out of B and E field
Args:
f: wannabe right-hand side, actually the E field
part: particle data
t: current time
Returns:
correct RHS of type acceleration
"""
assert isinstance(part, particles)
rhs = acceleration(((3, self.nparts), self.init[1], self.init[2]))
rhs[:, 0] = part.q[:] / part.m[:] * (f.elec[:, 0] + np.cross(part.vel[:, 0], f.magn[:, 0]))
return rhs
def boris_solver(self, c, dt, old_fields, new_fields, old_parts):
"""
The actual Boris solver for static (!) B fields, extended by the c-term
Args:
c: the c term gathering the known values from the previous iteration
dt: the (probably scaled) time step size
old_fields: the field values at the previous node m
new_fields: the field values at the current node m+1
old_parts: the particles at the previous node m
Returns:
the velocities at the (m+1)th node
"""
N = self.nparts
vel = particles.velocity(((3, 1), self.init[1], self.init[2]))
Emean = 1.0 / 2.0 * (old_fields.elec + new_fields.elec)
for n in range(N):
a = old_parts.q[n] / old_parts.m[n]
c[:, n] += dt / 2 * a * np.cross(old_parts.vel[:, n], old_fields.magn[:, n] - new_fields.magn[:, n])
# pre-velocity, separated by the electric forces (and the c term)
vm = old_parts.vel[:, n] + dt / 2 * a * Emean[:, n] + c[:, n] / 2
# rotation
t = dt / 2 * a * new_fields.magn[:, n]
s = 2 * t / (1 + np.linalg.norm(t, 2) ** 2)
vp = vm + np.cross(vm + np.cross(vm, t), s)
# post-velocity
vel[:, n] = vp + dt / 2 * a * Emean[:, n] + c[:, n] / 2
return vel
| 4,367 | 30.883212 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/Boris/penningtrap_HookClass.py | import matplotlib.pyplot as plt
import numpy as np
# import progressbar
from pySDC.core.Hooks import hooks
class particles_output(hooks):
def __init__(self):
"""
Initialization of particles output
"""
super(particles_output, self).__init__()
fig = plt.figure()
self.ax = fig.add_subplot(111, projection="3d")
self.ax.set_xlim3d([-20, 20])
self.ax.set_ylim3d([-20, 20])
self.ax.set_zlim3d([-20, 20])
plt.ion()
self.sframe = None
self.bar_run = None
def pre_run(self, step, level_number):
"""
Overwrite default routine called before time-loop starts
Args:
step: the current step
level_number: the current level number
"""
super(particles_output, self).pre_run(step, level_number)
# some abbreviations
L = step.levels[level_number]
# if hasattr(L.prob.params, 'Tend'):
# self.bar_run = progressbar.ProgressBar(max_value=L.prob.params.Tend)
# else:
# self.bar_run = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
part = L.u[0]
N = L.prob.nparts
w = np.array([1, 1, -2])
# compute (slowly..) the potential at u0
fpot = np.zeros(N)
for i in range(N):
# inner loop, omit ith particle
for j in range(0, i):
dist2 = np.linalg.norm(part.pos[:, i] - part.pos[:, j], 2) ** 2 + L.prob.sig**2
fpot[i] += part.q[j] / np.sqrt(dist2)
for j in range(i + 1, N):
dist2 = np.linalg.norm(part.pos[:, i] - part.pos[:, j], 2) ** 2 + L.prob.sig**2
fpot[i] += part.q[j] / np.sqrt(dist2)
fpot[i] -= (
L.prob.omega_E**2 * part.m[i] / part.q[i] / 2.0 * np.dot(w, part.pos[:, i] * part.pos[:, i])
)
# add up kinetic and potntial contributions to total energy
epot = 0
ekin = 0
for n in range(N):
epot += part.q[n] * fpot[n]
ekin += part.m[n] / 2.0 * np.dot(part.vel[:, n], part.vel[:, n])
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=0,
sweep=L.status.sweep,
type="etot",
value=epot + ekin,
)
def post_step(self, step, level_number):
"""
Default routine called after each iteration
Args:
step: the current step
level_number: the current level number
"""
super(particles_output, self).post_step(step, level_number)
# some abbreviations
L = step.levels[level_number]
# self.bar_run.update(L.time)
L.sweep.compute_end_point()
part = L.uend
N = L.prob.nparts
w = np.array([1, 1, -2])
# compute (slowly..) the potential at uend
fpot = np.zeros(N)
for i in range(N):
# inner loop, omit ith particle
for j in range(0, i):
dist2 = np.linalg.norm(part.pos[:, i] - part.pos[:, j], 2) ** 2 + L.prob.sig**2
fpot[i] += part.q[j] / np.sqrt(dist2)
for j in range(i + 1, N):
dist2 = np.linalg.norm(part.pos[:, i] - part.pos[:, j], 2) ** 2 + L.prob.sig**2
fpot[i] += part.q[j] / np.sqrt(dist2)
fpot[i] -= (
L.prob.omega_E**2 * part.m[i] / part.q[i] / 2.0 * np.dot(w, part.pos[:, i] * part.pos[:, i])
)
# add up kinetic and potntial contributions to total energy
epot = 0
ekin = 0
for n in range(N):
epot += part.q[n] * fpot[n]
ekin += part.m[n] / 2.0 * np.dot(part.vel[:, n], part.vel[:, n])
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type="etot",
value=epot + ekin,
)
oldcol = self.sframe
# # self.sframe = self.ax.scatter(L.uend.pos[0],L.uend.pos[1],L.uend.pos[2])
self.sframe = self.ax.scatter(L.uend.pos[0::3], L.uend.pos[1::3], L.uend.pos[2::3])
# Remove old line collection before drawing
if oldcol is not None:
oldcol.remove()
plt.pause(0.001)
return None
class convergence_data(hooks):
def __init__(self):
super(convergence_data, self).__init__()
self.storage = dict()
self.values = [
"position",
"velocity",
"position_exact",
"velocity_exact",
"pos_nodes",
"vel_nodes",
"pos_nodes_ex",
"vel_nodes_ex",
]
for ii, jj in enumerate(self.values):
self.storage[jj] = dict()
def post_step(self, step, level_number):
"""
Default runtine called after each iteration
Args:
step: the current step
level_number: the current level number
"""
super(convergence_data, self).pre_run(step, level_number)
# some abbreviations
L = step.levels[level_number]
# self.bar_run.update(L.time)
L.sweep.compute_end_point()
part = L.uend
self.storage["position"][L.time] = part.pos
self.storage["velocity"][L.time] = part.vel
self.storage["position_exact"][L.time] = L.prob.u_exact(L.time + L.dt).pos
self.storage["velocity_exact"][L.time] = L.prob.u_exact(L.time + L.dt).vel
if L.time + L.dt >= L.prob.Tend:
self.add_to_stats(
process=step.status.slot,
time=L.dt,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type="error",
value=self.storage,
)
return None
| 6,009 | 29.507614 | 108 | py |
pySDC | pySDC-master/pySDC/playgrounds/Boris/penningtrap_playground.py | import matplotlib.pyplot as plt
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.PenningTrap_3D import penningtrap
from pySDC.implementations.sweeper_classes.boris_2nd_order import boris_2nd_order
from pySDC.playgrounds.Boris.penningtrap_HookClass import particles_output
def main():
"""
Particle cloud in a penning trap, incl. live visualization
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 0.015625
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = 3
# initialize problem parameters for the Penning trap
problem_params = dict()
problem_params['omega_E'] = 4.9
problem_params['omega_B'] = 25.0
problem_params['u0'] = np.array([[10, 0, 0], [100, 0, 100], [1], [1]], dtype=object)
problem_params['nparts'] = 10
problem_params['sig'] = 0.1
# problem_params['Tend'] = 16.0
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['hook_class'] = particles_output # specialized hook class for more statistics and output
controller_params['logger_level'] = 30
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = penningtrap
description['problem_params'] = problem_params
description['sweeper_class'] = boris_2nd_order
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
# description['space_transfer_class'] = particles_to_particles # this is only needed for more than 2 levels
description['step_params'] = step_params
# instantiate the controller (no controller parameters used here)
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.0
Tend = 128 * 0.015625
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_init()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
sortedlist_stats = get_sorted(stats, type='etot', sortby='time')
energy = [entry[1] for entry in sortedlist_stats]
plt.figure()
plt.plot(energy, 'bo--')
plt.xlabel('Time')
plt.ylabel('Energy')
plt.savefig('penningtrap_energy.png', transparent=True, bbox_inches='tight')
if __name__ == "__main__":
main()
| 2,757 | 31.833333 | 111 | py |
pySDC | pySDC-master/pySDC/playgrounds/Boris/spiraling_particle_HookClass.py | import numpy as np
# import progressbar
from pySDC.core.Hooks import hooks
class particles_output(hooks):
def __init__(self):
"""
Initialization of particles output
"""
super(particles_output, self).__init__()
self.bar_run = None
def pre_run(self, step, level_number):
"""
Overwrite standard pre run hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(particles_output, self).pre_run(step, level_number)
L = step.levels[0]
# if hasattr(L.prob.params, 'Tend'):
# self.bar_run = progressbar.ProgressBar(max_value=L.prob.params.Tend)
# else:
# self.bar_run = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
def post_step(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(particles_output, self).post_step(step, level_number)
# some abbreviations
L = step.levels[0]
u = L.uend
# self.bar_run.update(L.time)
R = np.linalg.norm(u.pos)
H = 1 / 2 * np.dot(u.vel[:, 0], u.vel[:, 0]) + L.prob.params.a0 / R
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='energy',
value=H,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='position',
value=L.uend.pos,
)
return None
| 1,882 | 25.152778 | 89 | py |
pySDC | pySDC-master/pySDC/playgrounds/Boris/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/Boris/spiraling_particle_playground.py | import matplotlib.pyplot as plt
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.sweeper_classes.boris_2nd_order import boris_2nd_order
from pySDC.playgrounds.Boris.spiraling_particle_HookClass import particles_output
from pySDC.playgrounds.Boris.spiraling_particle_ProblemClass import planewave_single
def main(dt, Tend):
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = dt
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = 3
# initialize problem parameters for the Penning trap
problem_params = dict()
problem_params['delta'] = 1
problem_params['a0'] = 0.07
problem_params['u0'] = np.array([[0, -1, 0], [0.05, 0.01, 0], [1], [1]])
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['hook_class'] = particles_output # specialized hook class for more statistics and output
controller_params['logger_level'] = 30
# controller_params['log_to_file'] = True
# controller_params['fname'] = 'step_3_B_out.txt'
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = planewave_single
description['problem_params'] = problem_params
description['sweeper_class'] = boris_2nd_order
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
# description['space_transfer_class'] = particles_to_particles # this is only needed for more than 2 levels
description['step_params'] = step_params
# instantiate the controller (no controller parameters used here)
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.0
Tend = Tend
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_init()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
return uinit, stats, problem_params['a0']
def plot_error_and_positions(uinit, stats, a0):
sortedlist_stats = get_sorted(stats, type='energy', sortby='time')
R0 = np.linalg.norm(uinit.pos[:])
H0 = 1 / 2 * np.dot(uinit.vel[:].T, uinit.vel[:]) + a0 / R0
energy_err = [abs(entry[1] - H0) / H0 for entry in sortedlist_stats]
plt.figure()
plt.plot(energy_err, 'bo--')
plt.xlabel('Time')
plt.ylabel('Error in hamiltonian')
plt.savefig('spiraling_particle_error_ham.png', transparent=True, bbox_inches='tight')
sortedlist_stats = get_sorted(stats, type='position', sortby='time')
xpositions = [item[1][0] for item in sortedlist_stats]
ypositions = [item[1][1] for item in sortedlist_stats]
plt.figure()
plt.xlim([-1.5, 1.5])
plt.ylim([-1.5, 1.5])
plt.xlabel('x')
plt.ylabel('y')
plt.scatter(xpositions, ypositions)
plt.savefig('spiraling_particle_positons.png', transparent=True, bbox_inches='tight')
plt.show()
if __name__ == "__main__":
uinit, stats, a0 = main(dt=1.0, Tend=5000)
plot_error_and_positions(uinit, stats, a0)
| 3,449 | 31.857143 | 111 | py |
pySDC | pySDC-master/pySDC/playgrounds/Diagonal/dahlquist.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 1 16:24:21 2022
Generic implementation of IMEX-SDC for the Dahlquist test problem
@author: cpf5546
"""
import numpy as np
from collections import deque
from scipy.linalg import blas
from qmatrix import genCollocation, genQDelta
class IMEXSDC(object):
# -------------------------------------------------------------------------
# SDC settings (class attributes and methods)
# -------------------------------------------------------------------------
# Default : RADAU-RIGHT nodes (using a LEGENDRE distribution), two sweeps
nSweep = 2
nodeDistr = 'LEGENDRE'
quadType = 'RADAU-RIGHT'
implSweep = 'BE'
explSweep = 'FE'
initSweep = 'QDELTA'
forceProl = False
# Collocation method attributes
nodes, weights, Q = genCollocation(3, nodeDistr, quadType)
# IMEX SDC attributes
QDeltaI, dtauI = genQDelta(nodes, implSweep, Q)
QDeltaE, dtauE = genQDelta(nodes, explSweep, Q)
@classmethod
def setParameters(cls, M=None, nodeDistr=None, quadType=None,
implSweep=None, explSweep=None, initSweep=None,
nSweep=None, forceProl=None):
# Get non-changing parameters
keepM = M is None
keepNodeDistr = nodeDistr is None
keepQuadType = quadType is None
keepImplSweep = implSweep is None
keepExplSweep = explSweep is None
# Set parameter values
M = len(cls.nodes) if keepM else M
nodeDistr = cls.nodeDistr if keepNodeDistr else nodeDistr
quadType = cls.quadType if keepQuadType else quadType
implSweep = cls.implSweep if keepImplSweep else implSweep
explSweep = cls.explSweep if keepExplSweep else explSweep
# Determine updated parts
updateNode = (not keepM) or (not keepNodeDistr) or (not keepQuadType)
updateQDeltaI = (not keepImplSweep) or updateNode
updateQDeltaE = (not keepExplSweep) or updateNode
# Update parameters
if updateNode:
cls.nodes, cls.weights, cls.Q = genCollocation(
M, nodeDistr, quadType)
cls.nodeDistr, cls.quadType = nodeDistr, quadType
if updateQDeltaI:
cls.QDeltaI, cls.dtauI = genQDelta(cls.nodes, implSweep, cls.Q)
cls.implSweep = implSweep
if updateQDeltaE:
cls.QDeltaE, cls.dtauE = genQDelta(cls.nodes, explSweep, cls.Q)
cls.explSweep = explSweep
# Eventually update nSweep, initSweep and forceProlongation
cls.initSweep = cls.initSweep if initSweep is None else initSweep
cls.nSweep = cls.nSweep if nSweep is None else nSweep
cls.forceProl = cls.forceProl if forceProl is None else forceProl
@classmethod
def getMaxOrder(cls):
# TODO : adapt to non-LEGENDRE node distributions
M = len(cls.nodes)
return 2*M if cls.quadType == 'GAUSS' else \
2*M-1 if cls.quadType.startswith('RADAU') else \
2*M-2 # LOBATTO
def __init__(self, u0, lambdaI, lambdaE):
model = np.asarray(np.asarray(lambdaI) + np.asarray(lambdaE) + 0.)
c = lambda : np.zeros_like(model)
self.lambdaI, self.lambdaE = c(), c()
np.copyto(self.lambdaI, lambdaI)
np.copyto(self.lambdaE, lambdaE)
self.u = c() # Equivalent to solver state
np.copyto(self.u, u0) # Initialize state
self.rhs, self.u0 = c(), c()
self.lamIU = deque([[c() for _ in range(self.M)] for _ in range(2)])
self.lamEU = deque([[c() for _ in range(self.M)] for _ in range(2)])
if not self.leftIsNode:
self.lamEU0, self.lamIU0 = c(), c()
# Instanciate list of solver (ony first time step)
self.lhs = [None] * self.M
self.dt = None
self.axpy = blas.get_blas_funcs('axpy', dtype=self.u.dtype)
@property
def M(self):
return len(self.nodes)
@property
def rightIsNode(self):
return np.allclose(self.nodes[-1], 1.0)
@property
def leftIsNode(self):
return np.allclose(self.nodes[0], 0.0)
@property
def doProlongation(self):
return not self.rightIsNode or self.forceProl
def _storeU0(self):
np.copyto(self.u0, self.u)
def _updateLHS(self, dt, init=False):
"""Update LHS coefficients
Parameters
----------
dt : float
Time-step for the updated LHS.
init : bool, optional
Wether or not initialize the LHS_solvers attribute for each
subproblem. The default is False.
"""
# Attribute references
qI = self.QDeltaI
for i in range(self.M):
self.lhs[i] = 1 - dt*qI[i, i]*self.lambdaI
def _evalImplicit(self, lamIU):
np.copyto(lamIU, self.u)
lamIU *= self.lambdaI
def _evalExplicit(self, lamEU):
np.copyto(lamEU, self.u)
lamEU *= self.lambdaE
def _solveAndStoreState(self, iNode):
np.copyto(self.u, self.rhs)
self.u /= self.lhs[iNode]
def _initSweep(self, iType='QDELTA'):
"""
Initialize node terms for one given time-step
Parameters
----------
iType : str, optional
Type of initialization, can be :
- iType="QDELTA" : use QDelta[I,E] for coarse time integration.
- iType="COPY" : just copy the values from the initial solution.
"""
# Attribute references
qI, qE = self.QDeltaI, self.QDeltaE
dt = self.dt
rhs, u0 = self.rhs, self.u0
lamIUk, lamEUk = self.lamIU[0], self.lamEU[0]
if not self.leftIsNode:
lamEU0, lamIU0 = self.lamEU0, self.lamIU0
axpy = self.axpy
if iType == 'QDELTA':
# Prepare initial field evaluation
if not self.leftIsNode:
self._evalExplicit(lamEU0)
lamEU0 *= dt*self.dtauE
if self.dtauI != 0.0:
self._evalImplicit(lamIU0)
axpy(a=dt*self.dtauI, x=lamIU0, y=lamEU0)
# Loop on all quadrature nodes
for i in range(self.M):
# Build RHS
# -- initialize with U0 term
np.copyto(rhs, u0)
# -- add initial field evaluation
if not self.leftIsNode:
rhs += lamEU0
# -- add explicit and implicit terms (already computed)
for j in range(i):
axpy(a=dt*qE[i, j], x=lamEUk[j], y=rhs)
axpy(a=dt*qI[i, j], x=lamIUk[j], y=rhs)
# Solve system and store node solution in solver state
self._solveAndStoreState(i)
# Evaluate implicit and implicit terms with current state
self._evalImplicit(lamIUk[i])
self._evalExplicit(lamEUk[i])
elif iType == 'COPY': # also called "spread" in pySDC
self._evalImplicit(lamIUk[0])
self._evalExplicit(lamEUk[0])
for i in range(1, self.M):
np.copyto(lamIUk[i], lamIUk[0])
np.copyto(lamEUk[i], lamEUk[0])
else:
raise NotImplementedError(f'iType={iType}')
def _sweep(self):
"""Perform a sweep for the current time-step"""
# Attribute references
qI, qE, q = self.QDeltaI, self.QDeltaE, self.Q
dt = self.dt
rhs, u0 = self.rhs, self.u0
lamIUk, lamEUk = self.lamIU[0], self.lamEU[0]
lamIUk1, lamEUk1 = self.lamIU[1], self.lamEU[1]
axpy = self.axpy
# Loop on all quadrature nodes
for i in range(self.M):
# Build RHS
# -- initialize with U0 term
np.copyto(rhs, u0)
# -- add quadrature terms
for j in range(self.M):
axpy(a=dt*q[i, j], x=lamEUk[j], y=rhs)
axpy(a=dt*q[i, j], x=lamIUk[j], y=rhs)
# -- add explicit and implicit terms from iteration k+1
for j in range(i):
axpy(a=dt*qE[i, j], x=lamEUk1[j], y=rhs)
axpy(a=dt*qI[i, j], x=lamIUk1[j].data, y=rhs)
# -- add explicit and implicit terms from iteration k
for j in range(i):
axpy(a=-dt*qE[i, j], x=lamEUk[j], y=rhs)
axpy(a=-dt*qI[i, j], x=lamIUk[j], y=rhs)
axpy(a=-dt*qI[i, i], x=lamIUk[i], y=rhs)
# Solve system and store node solution in solver state
self._solveAndStoreState(i)
# Evaluate implicit and implicit terms with current state
self._evalImplicit(lamIUk1[i])
self._evalExplicit(lamEUk1[i])
# Inverse position for iterate k and k+1 in storage
# ie making the new evaluation the old for next iteration
self.lamEU.rotate()
self.lamIU.rotate()
def _prolongation(self):
"""Compute prolongation, or collocation update"""
w, dt = self.weights, self.dt
rhs, u0 = self.rhs, self.u0
lamIUk, lamEUk = self.lamIU[0], self.lamEU[0]
axpy = self.axpy
# Compute update formula
# -- initialize with u0 term
np.copyto(rhs, u0)
# -- add quadrature terms
for i in range(self.M):
axpy(a=dt*w[i], x=lamEUk[i], y=rhs)
axpy(a=dt*w[i], x=lamIUk[i], y=rhs)
# -- store to state
np.copyto(self.u, rhs)
def step(self, dt):
"""
Compute the next time-step solution using the time-stepper method,
and modify to state solution vector u
Parameters
----------
dt : float
Lenght of the current time-step.
"""
# Initialize and/or update LHS terms, depending on dt
if dt != self.dt:
self._updateLHS(dt)
self.dt = dt
# Store U0 for the whole time step
self._storeU0()
# Initialize node values
self._initSweep(iType=self.initSweep)
# Performs sweeps
for k in range(self.nSweep):
self._sweep()
# Compute prolongation if needed
if self.doProlongation:
self._prolongation()
@classmethod
def imagStability(cls):
zoom = 5
lamBnd = -4*zoom, 4*zoom, 201
lam = np.linspace(*lamBnd)
lams = 1j*lam
nSweepPrev = cls.nSweep
cls.nSweep = 1
solver = cls(1.0, lams, 0)
solver.step(1.)
cls.nSweep = nSweepPrev
uNum = solver.u
stab = np.abs(uNum)
return lam[np.argwhere(stab <= 1)].max()
if __name__ == '__main__':
# Basic testing
import matplotlib.pyplot as plt
nStep = 15
dt = 2*np.pi/nStep
times = np.linspace(0, 2*np.pi, nStep+1)
u0 = 1.0
lambdaE = 1j
lambdaI = -0.1
IMEXSDC.setParameters(
M=3, quadType='LOBATTO', nodeDistr='LEGENDRE',
implSweep='BEpar', explSweep='PIC', initSweep='COPY',
forceProl=False)
IMEXSDC.nSweep = 1
solver = IMEXSDC(u0, lambdaI, lambdaE)
u = [solver.u.copy()]
for i in range(nStep):
solver.step(dt)
u += [solver.u.copy()]
u = np.array(u)
plt.plot(u.real[0], u.imag[0], 's', ms=15)
plt.plot(u.real, u.imag, 'o-')
uTh = u0*np.exp(times*(lambdaE+lambdaI))
plt.plot(uTh.real, uTh.imag, '^-')
print(IMEXSDC.imagStability())
| 11,463 | 31.660969 | 79 | py |
pySDC | pySDC-master/pySDC/playgrounds/Diagonal/spectralRadius.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 6 16:28:32 2022
@author: cpf5546
"""
# Python imports
import numpy as np
import pandas as pd
# Local imports
from mplsettings import plt # matplotlib with adapted font size settings
from qmatrix import genCollocation
from dahlquist import IMEXSDC
from optim import findLocalMinima
# ----------------------------------------------------------------------------
# Main parameters
# ----------------------------------------------------------------------------
# Collocation parameters
M = 3
distr = 'LEGENDRE'
quadType = 'LOBATTO'
# Optimization parameters
optimType = 'Speck'
# -- "Speck" : minimizes the spectral radius of I - QDelta^{-1}Q ... ImQdInvQ
# -- "QmQd" : minimizes the spectral radius of Q-QDelta
# -- "probDep" : minimizes the spectral radius of (I-QDelta)^{-1} (Q-QDelta)
# Value used for probDep optimization
lamDt = 1j
optimParams = {
'nSamples': 200, # Number of samples for initial optimization guess
'nLocalOptim': 3, # Number of local optimization for one sample
'localOptimTol': 1e-9, # Local optimization tolerance for one sample
'randomSeed': None, # Random seed to generate all samples
'alphaFunc': 1.0, # Exponant added to the optimization function
'threshold': 1e-6} # Threshold used to keep optimization candidates
# ----------------------------------------------------------------------------
# Script run
# ----------------------------------------------------------------------------
Q = genCollocation(M, distr, quadType)[2]
if quadType in ['RADAU-LEFT', 'LOBATTO']:
dim = M-1
Q = Q[1:,1:]
else:
dim = M
if optimType == 'Speck':
# Maximum inverse coefficient investigated
maxCoeff = 13.
def spectralRadius(x):
QDeltaInv = np.diag(x)
R = np.eye(dim) - QDeltaInv @ Q
return np.max(np.abs(np.linalg.eigvals(R)))
elif optimType == 'QmQd':
# Maximum coefficient investigated
maxCoeff = 1.
def spectralRadius(x):
R = (Q - np.diag(x))
return np.max(np.abs(np.linalg.eigvals(R)))
elif optimType == 'probDep':
# Maximum coefficient investigated
maxCoeff = 1.
def spectralRadius(x):
x = np.asarray(x)
R = np.diag((1-lamDt*x)**(-1)) @ (Q - np.diag(x))
return np.max(np.abs(np.linalg.eigvals(R)))
else:
raise NotImplementedError(f'optimType={optimType}')
# Use Monte-Carlo Local Minima finder
res, xStarts = findLocalMinima(
spectralRadius, dim, bounds=(0, maxCoeff), **optimParams)
# Manually compute Rho, and plot for 2D optimization
nPlotPts = int(50000**(1/dim))
limits = [maxCoeff]*dim
grids = np.meshgrid(*[
np.linspace(0, l, num=nPlotPts) for l in limits])
flatGrids = np.array([g.ravel() for g in grids])
# Computing spectral radius for many coefficients
print('Computing spectral radius values')
rho = []
for coeffs in flatGrids.T:
rho.append(spectralRadius(coeffs))
rho = np.reshape(rho, grids[0].shape)
rho[rho>1] = 1
if dim == 2:
plt.figure()
plt.contourf(*grids, rho,
levels=np.linspace(0, 1, 101), cmap='OrRd')
plt.colorbar(ticks=np.linspace(0, 1, 11))
for x0 in xStarts:
plt.plot(*x0, '+', c='gray', ms=6, alpha=0.75)
for xMin in res:
plt.plot(*xMin, 'o', ms=12)
pos = [1.1*x for x in xMin]
plt.text(*pos, r'$\rho_{opt}='f'{res[xMin]:1.2e}$',
fontsize=16)
if optimType == 'QmQd' and False:
# Only if you want to check A-stability ...
print('Computing imaginary stability')
iStab = []
IMEXSDC.setParameters(
M=M, quadType=quadType, nodeDistr=distr, implSweep='BEpar',
initSweep='COPY', forceProl=True)
for coeffs in flatGrids.T:
if quadType in ['RADAU-LEFT', 'LOBATTO']:
IMEXSDC.QDeltaI[1:,1:] = np.diag(coeffs)
else:
IMEXSDC.QDeltaI[:] = np.diag(coeffs)
iStab.append(IMEXSDC.imagStability())
iStab = np.reshape(iStab, grids[0].shape)
plt.figure()
plt.contourf(*grids, iStab,
levels=np.linspace(0, 20, 101), cmap='OrRd')
plt.colorbar(ticks=np.linspace(0, 20, 11))
if optimType == 'Speck':
# For Speck optim type, optimization produces the coefficient of the
# inverse of the QDelta matrix
for xOpt in list(res.keys()):
rho = res.pop(xOpt)
xOpt = tuple(1/x for x in xOpt)
res[xOpt] = rho
print('Optimum diagonal coefficients found :')
print(f' -- optimType={optimType}')
for xOpt in res:
print(f' -- xOpt={xOpt} (rho={res[xOpt]:1.2e})')
# Store results in Markdown dataframe
if optimType != 'probDep':
try:
df = pd.read_table(
'optimDiagCoeffs.md', sep="|", header=0, index_col=0,
skipinitialspace=True).dropna(axis=1, how='all').iloc[1:]
df.reset_index(inplace=True, drop=True)
df.columns = [label.strip() for label in df.columns]
df = df.applymap(lambda x: x.strip())
df['rho'] = df.rho.astype(float)
df['M'] = df.M.astype(int)
df['coeffs'] = df.coeffs.apply(
lambda x: tuple(float(n) for n in x[1:-1].split(', ')))
except Exception:
df = pd.DataFrame(
columns=['M', 'quadType', 'distr', 'optim', 'coeffs', 'rho'])
def formatCoeffs(c):
out = tuple(round(v, 6) for v in c)
if quadType in ['RADAU-LEFT', 'LOBATTO']:
out = (0.,) + out
return out
def addCoefficients(line, df):
cond = (df == line.values)
l = df[cond].iloc[:, :-1].dropna()
if l.shape[0] == 1:
# Coefficients already stored
idx = l.index[0]
if line.rho[0] < df.loc[idx, 'rho']:
df.loc[idx, 'rho'] = line.rho[0]
else:
# New computed coefficients
df = pd.concat((df, line), ignore_index=True)
return df
for c in res:
line = pd.DataFrame(
[[M, quadType, distr, optimType, formatCoeffs(c), res[c]]],
columns=df.columns)
df = addCoefficients(line, df)
df.sort_values(by=['M', 'quadType', 'optim', 'coeffs'], inplace=True)
df.to_markdown(buf='optimDiagCoeffs.md', index=False)
| 6,295 | 31.453608 | 78 | py |
pySDC | pySDC-master/pySDC/playgrounds/Diagonal/optim.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 19 10:19:55 2022
@author: cpf5546
"""
import numpy as np
import scipy.optimize as sco
import skopt
def findLocalMinima(func, dim, bounds=(0, 15),
nSamples=200, nLocalOptim=3, localOptimTol=1e-8,
alphaFunc=1, randomSeed=None, threshold=1e-2):
print('Monte-Carlo local minima finder')
# Initialize random seed
np.random.seed(randomSeed)
# Compute starting points
print(' -- generating random samples (Maximin Optimized Latin Hypercube)')
space = skopt.space.Space([bounds]*dim)
lhs = skopt.sampler.Lhs(criterion="maximin", iterations=10000)
xStarts = lhs.generate(space.dimensions, nSamples)
# Optimization functional
modFunc = lambda x: func(x)**alphaFunc
res = {}
def findRes(x):
x = [round(v, 6) for v in x]
for x0 in res:
if np.allclose(x, x0, rtol=1e-1):
return x0
return False
# Look at randomly generated staring points
print(' -- running local optimizations')
for x0 in xStarts:
# Run one or several local optimization
for _ in range(nLocalOptim):
opt = sco.minimize(modFunc, x0,
method='Nelder-Mead', tol=localOptimTol)
x0 = opt.x
if not opt.success:
break
funcEval = func(x0)
# Eventually add local minimum to results
xOrig = findRes(x0)
if xOrig:
if funcEval < res[xOrig]:
res.pop(xOrig)
res[tuple(x0)] = funcEval
print(' -- found better local minimum')
else:
if funcEval < threshold:
print(' -- found new local minimum')
res[tuple(x0)] = funcEval
return res, xStarts
| 1,869 | 27.333333 | 78 | py |
pySDC | pySDC-master/pySDC/playgrounds/Diagonal/mplsettings.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 14 09:44:56 2022
@author: cpf5546
"""
import matplotlib.pyplot as plt
plt.rc('font', size=12)
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['axes.titlesize'] = 18
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['xtick.labelsize'] = 16
plt.rcParams['ytick.labelsize'] = 16
plt.rcParams['xtick.major.pad'] = 5
plt.rcParams['ytick.major.pad'] = 5
plt.rcParams['axes.labelpad'] = 6
plt.rcParams['markers.fillstyle'] = 'none'
plt.rcParams['lines.markersize'] = 7.0
plt.rcParams['lines.markeredgewidth'] = 1.5
plt.rcParams['mathtext.fontset'] = 'cm'
plt.rcParams['mathtext.rm'] = 'serif'
plt.rcParams['figure.max_open_warning'] = 100
| 704 | 27.2 | 45 | py |
pySDC | pySDC-master/pySDC/playgrounds/Diagonal/convergenceOrder.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 12:30:23 2022
Plot convergence order for any flavor of IMEX-SDC,
using the Dahlquist test problem with one lambda value treaded explicitly,
and the other one treated implicitely
@author: cpf5546
"""
import numpy as np
import matplotlib.pyplot as plt
from dahlquist import IMEXSDC
listNumStep = [2**(i+2) for i in range(11)]
u0 = 1.0
lambdaI = 1j-0.1
lambdaE = 0
IMEXSDC.setParameters(
M=3, quadType='GAUSS', nodeDistr='LEGENDRE',
implSweep='OPT-Speck-0', explSweep='FE', initSweep='COPY',
forceProl=True)
solver = IMEXSDC(u0, lambdaI, lambdaE)
plt.figure()
for nSweep in [0, 1, 2, 3]:
IMEXSDC.nSweep = nSweep
def getErr(nStep):
dt = 2*np.pi/nStep
times = np.linspace(0, 2*np.pi, nStep+1)
uTh = u0*np.exp(times*(lambdaE+lambdaI))
np.copyto(solver.u, u0)
uNum = [solver.u.copy()]
for i in range(nStep):
solver.step(dt)
uNum += [solver.u.copy()]
uNum = np.array(uNum)
err = np.linalg.norm(uNum-uTh, ord=np.inf)
return dt, err
# Run all simulations
listNumStep = [2**(i+2) for i in range(11)]
dt, err = np.array([getErr(n) for n in listNumStep]).T
# Plot error VS time step
lbl = f'SDC, nSweep={IMEXSDC.nSweep}'
sym = '^-'
plt.loglog(dt, err, sym, label=lbl)
# Plot order curve
order = nSweep+1
c = err[0]/dt[0]**order * 2
plt.plot(dt, c*dt**order, '--', color='gray')
plt.xlabel(r'$\Delta{t}$')
plt.ylabel(r'error ($L_{inf}$)')
plt.ylim(1e-10, 1e1)
plt.legend()
plt.grid(True)
plt.title(IMEXSDC.implSweep)
plt.tight_layout()
| 1,670 | 22.871429 | 74 | py |
pySDC | pySDC-master/pySDC/playgrounds/Diagonal/qmatrix.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 23 10:17:08 2022
@author: cpf5546
"""
import numpy as np
from scipy.linalg import lu
from pySDC.core.Nodes import NodesGenerator
from pySDC.core.Lagrange import LagrangeApproximation
# Storage for diagonaly optimized QDelta matrices
OPT_COEFFS = {
"QmQd": {
2: {'GAUSS':
[(0.105662, 0.394338),
(0.394338, 0.105662)],
'RADAU-LEFT':
[(0.0, 0.333333)],
'RADAU-RIGHT':
[(0.166667, 0.5),
(0.666667, 0.0)],
'LOBATTO':
[(0.0, 0.5)]
},
3: {'GAUSS':
[(0.037571, 0.16667, 0.29577),
(0.156407, 0.076528, 0.267066),
(0.267065, 0.076528, 0.156407),
(0.295766, 0.166666, 0.037567)],
'RADAU-RIGHT':
[(0.051684, 0.214984, 0.333334), # Winner for advection
(0.233475, 0.080905, 0.285619),
(0.390077, 0.094537, 0.115385),
(0.422474, 0.177525, 0.0)],
'LOBATTO':
[(0.0, 0.166667, 0.333333),
(0.0, 0.5, 0.0)],
},
5: {'RADAU-RIGHT':
[(0.193913, 0.141717, 0.071975, 0.018731, 0.119556),
(0.205563, 0.143134, 0.036388, 0.073742, 0.10488),
(0.176822, 0.124251, 0.031575, 0.084012, 0.142621)],
},
},
"Speck": {
2: {'GAUSS':
[(0.166667, 0.5),
(0.5, 0.166667)],
'RADAU-LEFT':
[(0.0, 0.333333)],
'RADAU-RIGHT':
[(0.258418, 0.644949),
(1.074915, 0.155051)],
'LOBATTO':
[(0.0, 0.5)]
},
3: {'GAUSS':
[(0.07672, 0.258752, 0.419774),
(0.214643, 0.114312, 0.339631),
(0.339637, 0.114314, 0.214647),
(0.419779, 0.258755, 0.076721)],
'RADAU-RIGHT':
[(0.10405, 0.332812, 0.48129),
(0.320383, 0.139967, 0.371668), # Winner for advection
(0.558747, 0.136536, 0.218466),
(0.747625, 0.404063, 0.055172)],
'LOBATTO':
[(0.0, 0.211325, 0.394338),
(0.0, 0.788675, 0.105662)]
},
}
}
# Coefficient allowing A-stability with prolongation=True
WEIRD_COEFFS = {
'GAUSS':
{2: (0.5, 0.5)},
'RADAU-RIGHT':
{2: (0.5, 0.5)},
'RADAU-LEFT':
{3: (0.0, 0.5, 0.5)},
'LOBATTO':
{3: (0.0, 0.5, 0.5)}}
def genQDelta(nodes, sweepType, Q):
"""
Generate QDelta matrix for a given node distribution
Parameters
----------
nodes : array (M,)
quadrature nodes, scaled to [0, 1]
sweepType : str
Type of sweep, that defines QDelta. Can be selected from :
- BE : Backward Euler sweep (first order)
- FE : Forward Euler sweep (first order)
- LU : uses the LU trick
- TRAP : sweep based on Trapezoidal rule (second order)
- EXACT : don't bother and just use Q
- PIC : Picard iteration => zeros coefficient (cannot be used for initSweep)
- OPT-[...] : Diagonaly precomputed coefficients, for which one has to
provide different parameters. For instance, [...]='QmQd-2' uses the
diagonal coefficients using the optimization method QmQd with the index 2
solution (index starts at 0 !). Quadtype and number of nodes are
determined automatically from the Q matrix.
- WEIRD-[...] : diagonal coefficient allowing A-stability with collocation
update (forceProl=True).
Q : array (M,M)
Q matrix associated to the node distribution
(used only when sweepType in [LU, EXACT, OPT-[...], WEIRD]).
Returns
-------
QDelta : array (M,M)
The generated QDelta matrix.
dtau : float
Correction coefficient for time integration with QDelta
"""
# Generate deltas
deltas = np.copy(nodes)
deltas[1:] = np.ediff1d(nodes)
# Extract informations from Q matrix
M = deltas.size
if sweepType.startswith('OPT') or sweepType == 'WEIRD':
leftIsNode = np.allclose(Q[0], 0)
rightIsNode = np.isclose(Q[-1].sum(), 1)
quadType = 'LOBATTO' if (leftIsNode and rightIsNode) else \
'RADAU-LEFT' if leftIsNode else \
'RADAU-RIGHT' if rightIsNode else \
'GAUSS'
# Compute QDelta
QDelta = np.zeros((M, M))
dtau = 0.0
if sweepType in ['BE', 'FE']:
offset = 1 if sweepType == 'FE' else 0
for i in range(offset, M):
QDelta[i:, :M-i] += np.diag(deltas[offset:M-i+offset])
if sweepType == 'FE':
dtau = deltas[0]
elif sweepType == 'TRAP':
for i in range(0, M):
QDelta[i:, :M-i] += np.diag(deltas[:M-i])
for i in range(1, M):
QDelta[i:, :M-i] += np.diag(deltas[1:M-i+1])
QDelta /= 2.0
dtau = deltas[0]/2.0
elif sweepType == 'LU':
QT = Q.T.copy()
[_, _, U] = lu(QT, overwrite_a=True)
QDelta = U.T
elif sweepType == 'EXACT':
QDelta = np.copy(Q)
elif sweepType == 'PIC':
QDelta = np.zeros(Q.shape)
elif sweepType.startswith('OPT'):
try:
oType, idx = sweepType[4:].split('-')
except ValueError:
raise ValueError(f'missing parameter(s) in sweepType={sweepType}')
M, idx = int(M), int(idx)
try:
coeffs = OPT_COEFFS[oType][M][quadType][idx]
QDelta[:] = np.diag(coeffs)
except (KeyError, IndexError):
raise ValueError('no OPT diagonal coefficients for '
f'{oType}-{M}-{quadType}-{idx}')
elif sweepType == 'BEpar':
QDelta[:] = np.diag(nodes)
elif sweepType == 'WEIRD':
try:
coeffs = WEIRD_COEFFS[quadType][M]
QDelta[:] = np.diag(coeffs)
except (KeyError, IndexError):
raise ValueError('no WEIRD diagonal coefficients for '
f'{M}-{quadType} nodes')
else:
raise NotImplementedError(f'sweepType={sweepType}')
return QDelta, dtau
def genCollocation(M, distr, quadType):
"""
Generate the nodes, weights and Q matrix for a given collocation method
Parameters
----------
M : int
Number of quadrature nodes.
distr : str
Node distribution. Can be selected from :
- LEGENDRE : nodes from the Legendre polynomials
- EQUID : equidistant nodes distribution
- CHEBY-{1,2,3,4} : nodes from the Chebyshev polynomial (1st to 4th kind)
quadType : str
Quadrature type. Can be selected from :
- GAUSS : do not include the boundary points in the nodes
- RADAU-LEFT : include left boundary points in the nodes
- RADAU-RIGHT : include right boundary points in the nodes
- LOBATTO : include both boundary points in the nodes
Returns
-------
nodes : array (M,)
quadrature nodes, scaled to [0, 1]
weights : array (M,)
quadrature weights associated to the nodes
Q : array (M,M)
normalized Q matrix of the collocation problem
"""
# Generate nodes between [0, 1]
nodes = NodesGenerator(node_type=distr, quad_type=quadType).getNodes(M)
nodes += 1
nodes /= 2
np.round(nodes, 14, out=nodes)
# Compute Q and weights
approx = LagrangeApproximation(nodes)
Q = approx.getIntegrationMatrix([(0, tau) for tau in nodes])
weights = approx.getIntegrationMatrix([(0, 1)]).ravel()
return nodes, weights, Q
| 7,717 | 32.556522 | 80 | py |
pySDC | pySDC-master/pySDC/playgrounds/Diagonal/stabilityNeumann.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 12:49:22 2022
Plot the stability contour of any flavor of SDC
SDC parameters can be set directly in the plotStabContour function ...
@author: cpf5546
"""
import numpy as np
import matplotlib.pyplot as plt
from dahlquist import IMEXSDC
u0 = 1.0
zoom = 5
lamReals = -5*zoom, 1*zoom, 301
lamImags = -4*zoom, 4*zoom, 400
xLam = np.linspace(*lamReals)[:, None]
yLam = np.linspace(*lamImags)[None, :]
lams = xLam + 1j*yLam
plt.figure()
def plotStabContour(nSweep):
IMEXSDC.setParameters(
M=2, quadType='GAUSS', nodeDistr='LEGENDRE',
implSweep='WEIRD', explSweep='FE', initSweep='COPY',
forceProl=True)
IMEXSDC.nSweep = nSweep
solver = IMEXSDC(u0, lams.ravel(), 0)
solver.step(1.)
uNum = solver.u.reshape(lams.shape)
stab = np.abs(uNum)
coords = np.meshgrid(xLam.ravel(), yLam.ravel(), indexing='ij')
CS = plt.contour(*coords, stab, levels=[1.0], colors='k')
plt.clabel(CS, inline=True, fmt=f'K={nSweep}')
plt.grid(True)
plt.gca().set_aspect('equal', 'box')
plt.xlabel(r'$Re(\lambda)$')
plt.ylabel(r'$Im(\lambda)$')
plt.gcf().set_size_inches(4, 5)
plt.title(IMEXSDC.implSweep)
plt.tight_layout()
return stab
for nSweep in [1, 2]:
stab = plotStabContour(nSweep)
| 1,337 | 22.473684 | 70 | py |
pySDC | pySDC-master/pySDC/playgrounds/Diagonal/stabilityFWSW.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 14:19:08 2022
@author: cpf5546
"""
import numpy as np
import matplotlib.pyplot as plt
from dahlquist import IMEXSDC
# ----------------------------------------------------------------------------
# Main parameters
# ----------------------------------------------------------------------------
params = dict(
M=3, # Number of quadrature nodes
qType='LOBATTO', # Type of quadrature nodes
implSweep='BE', # Implicit sweep type
explSweep='PIC', # Explicit sweep type
forceProl=False, # Wether or not forcing the collocation update
initSweep='COPY') # What to do for initial sweep
# Representation parameters
u0 = 1.0
lamSlows = 0, 5, 500
lamFasts = 0, 12, 501
# ----------------------------------------------------------------------------
# Script run
# ----------------------------------------------------------------------------
lamSlow, lamFast = np.meshgrid(
1j*np.linspace(*lamSlows), 1j*np.linspace(*lamFasts), indexing='ij')
def plotStabContour(ax, nSweep, implSweep='BE', explSweep='PIC',
forceProl=True, qType='LOBATTO', M=3, initSweep='COPY'):
IMEXSDC.setParameters(
M=M, quadType=qType, nodeDistr='LEGENDRE',
implSweep=implSweep, explSweep=explSweep, initSweep=initSweep,
forceProl=forceProl)
IMEXSDC.nSweep = nSweep
solver = IMEXSDC(u0, lamFast.ravel(), lamSlow.ravel())
solver.step(1.)
uNum = solver.u.reshape(lamSlow.shape)
stab = np.abs(uNum)
CS1 = ax.contour(lamSlow.imag, lamFast.imag, stab,
levels=[0.95, 1.05], colors='gray', linestyles='--')
CS2 = ax.contour(lamSlow.imag, lamFast.imag, stab,
levels=[1.0], colors='black')
plt.clabel(CS1, inline=True, fmt='%3.2f')
plt.clabel(CS2, inline=True, fmt='%3.2f')
ax.plot(lamSlows[:-1], lamSlows[:-1], ':', c='gray')
ax.set_xlabel(r'$\Delta t \lambda_{slow}$')
ax.set_ylabel(r'$\Delta t \lambda_{fast}$')
ax.set_title(f'K={nSweep}')
plt.gcf().suptitle(f'Q={qType}-{M}, QI={implSweep}, QE={explSweep}, '
f'forceProl={forceProl}, initSweep={initSweep}', y=0.95)
lSweeps = [1, 2, 3]
fig, axs = plt.subplots(1, len(lSweeps))
fig.set_size_inches(len(lSweeps)*4, 4)
for i, nSweep in enumerate(lSweeps):
plotStabContour(axs[i], nSweep, **params)
fig.tight_layout()
plt.savefig('stabContourFWSW.pdf')
| 2,472 | 32.418919 | 79 | py |
pySDC | pySDC-master/pySDC/playgrounds/monodomain/Monodomain.py | import numpy as np
from pySDC.core.Errors import ParameterError, ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
# noinspection PyUnusedLocal
class monodomain2d_imex(ptype):
"""
Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping
Attributes:
xvalues: grid points in space
dx: mesh width
lap: spectral operator for Laplacian
rfft_object: planned real FFT for forward transformation
irfft_object: planned IFFT for backward transformation
"""
def __init__(self, problem_params, dtype_u=mesh, dtype_f=imex_mesh):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: mesh data type (will be passed to parent class)
dtype_f: mesh data type wuth implicit and explicit parts (will be passed to parent class)
"""
if 'L' not in problem_params:
problem_params['L'] = 1.0
if 'init_type' not in problem_params:
problem_params['init_type'] = 'circle'
# these parameters will be used later, so assert their existence
essential_keys = ['nvars', 'a', 'kappa', 'rest', 'thresh', 'depol', 'init_type', 'eps']
for key in essential_keys:
if key not in problem_params:
msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))
raise ParameterError(msg)
# we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on
if len(problem_params['nvars']) != 2:
raise ProblemError('this is a 2d example, got %s' % problem_params['nvars'])
if problem_params['nvars'][0] != problem_params['nvars'][1]:
raise ProblemError('need a square domain, got %s' % problem_params['nvars'])
if problem_params['nvars'][0] % 2 != 0:
raise ProblemError('the setup requires nvars = 2^p per dimension')
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(monodomain2d_imex, self).__init__(
init=(problem_params['nvars'], None, np.dtype('float64')),
dtype_u=dtype_u,
dtype_f=dtype_f,
params=problem_params,
)
self.dx = self.params.L / self.params.nvars[0] # could be useful for hooks, too.
self.xvalues = np.array([i * self.dx - self.params.L / 2.0 for i in range(self.params.nvars[0])])
kx = np.zeros(self.init[0][0])
ky = np.zeros(self.init[0][1] // 2 + 1)
kx[: int(self.init[0][0] / 2) + 1] = 2 * np.pi / self.params.L * np.arange(0, int(self.init[0][0] / 2) + 1)
kx[int(self.init[0][0] / 2) + 1 :] = (
2 * np.pi / self.params.L * np.arange(int(self.init[0][0] / 2) + 1 - self.init[0][0], 0)
)
ky[:] = 2 * np.pi / self.params.L * np.arange(0, self.init[0][1] // 2 + 1)
xv, yv = np.meshgrid(kx, ky, indexing='ij')
self.lap = -xv**2 - yv**2
def eval_f(self, u, t):
"""
Routine to evaluate the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS
"""
f = self.dtype_f(self.init)
v = u.flatten()
tmp = self.params.kappa * self.lap * np.fft.rfft2(u)
f.impl[:] = np.fft.irfft2(tmp)
f.expl[:] = -(self.params.a * (v - self.params.rest) * (v - self.params.thresh) * (v - self.params.depol)).reshape(self.params.nvars)
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple FFT solver for the diffusion part
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float) : abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver (not used here so far)
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(self.init)
tmp = np.fft.rfft2(rhs) / (1.0 - factor * self.params.kappa * self.lap)
me[:] = np.fft.irfft2(tmp)
return me
def u_exact(self, t, u_init=None, t_init=None):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
u_init (pySDC.implementations.problem_classes.allencahn2d_imex.dtype_u): initial conditions for getting the exact solution
t_init (float): the starting time
Returns:
dtype_u: exact solution
"""
me = self.dtype_u(self.init, val=0.0)
if t == 0:
if self.params.init_type == 'tanh':
xv, yv = np.meshgrid(self.xvalues, self.xvalues, indexing='ij')
me[:, :] = 0.5 * (1 + np.tanh((self.params.radius - np.sqrt(xv**2 + yv**2)) / (np.sqrt(2) * self.params.eps)))
me[:, :] = me[:, :] * self.params.depol + (1 - me[:, :]) * self.params.rest
elif self.params.init_type == 'plateau':
xv, yv = np.meshgrid(self.xvalues, self.xvalues, indexing='ij')
me[:, :] = np.where(np.sqrt(xv**2 + yv**2) < self.params.radius * self.params.L, self.params.depol, self.params.rest)
# me[:, :] = me[:, :] * self.params.depol + (1 - me[:, :]) * self.params.rest
else:
raise NotImplementedError('type of initial value not implemented, got %s' % self.params.init_type)
else:
def eval_rhs(t, u):
f = self.eval_f(u.reshape(self.init[0]), t)
return (f.impl + f.expl).flatten()
me[:, :] = self.generate_scipy_reference_solution(eval_rhs, t, u_init, t_init)
return me
| 5,966 | 39.04698 | 141 | py |
pySDC | pySDC-master/pySDC/playgrounds/monodomain/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/monodomain/playground.py | import sys
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.playgrounds.monodomain.Monodomain import monodomain2d_imex
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.playgrounds.Allen_Cahn.AllenCahn_output import output
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-07
level_params['dt'] = 0.08
level_params['nsweeps'] = None
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU']
sweeper_params['QE'] = ['PIC']
# sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['L'] = 20.0
problem_params['nvars'] = None
cm = 0.01
sigma = 0.1334177215
chi = 140.0
problem_params['a'] = 1.4E-5 / cm
problem_params['kappa'] = sigma / (cm * chi)
problem_params['rest'] = -85.0
problem_params['thresh'] = -57.6
problem_params['depol'] = 30.0
problem_params['radius'] = 0.1
problem_params['eps'] = 0.001
problem_params['init_type'] = 'plateau'
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = monodomain2d_imex # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
# description['space_transfer_class'] = mesh_to_mesh_fft2d
return description, controller_params
def run_variant(nlevels=None):
"""
Routine to run particular SDC variant
Args:
Returns:
"""
# load (incomplete) default parameters
description, controller_params = setup_parameters()
# add stuff based on variant
if nlevels == 1:
description['level_params']['nsweeps'] = 1
description['problem_params']['nvars'] = [(128, 128)]
# description['problem_params']['nvars'] = [(32, 32)]
elif nlevels == 2:
description['level_params']['nsweeps'] = [1, 1]
description['problem_params']['nvars'] = [(128, 128), (32, 32)]
# description['problem_params']['nvars'] = [(32, 32), (16, 16)]
else:
raise NotImplemented('Wrong variant specified, got %s' % nlevels)
out = 'Working on %s levels...' % nlevels
print(out)
# setup parameters "in time"
t0 = 0.0
Tend = 40
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# filter statistics by variant (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
print('Time to solution: %6.4f sec.' % timing[0][1])
return stats
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
if len(sys.argv) == 2:
nlevels = int(sys.argv[1])
else:
nlevels = 1
# raise NotImplementedError('Need input of nsweeps, got % s' % sys.argv)
_ = run_variant(nlevels=nlevels)
if __name__ == "__main__":
main()
| 4,924 | 29.974843 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_monitor_Bayreuth.py | import numpy as np
from pySDC.core.Hooks import hooks
class monitor(hooks):
def __init__(self):
"""
Initialization of Allen-Cahn monitoring
"""
super(monitor, self).__init__()
self.init_volume = None
def pre_run(self, step, level_number):
"""
Overwrite standard pre run hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(monitor, self).pre_run(step, level_number)
L = step.levels[0]
self.init_volume = L.prob.dx * sum(L.u[0])
print(self.init_volume)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='exact_volume',
value=self.init_volume,
)
def post_step(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(monitor, self).post_step(step, level_number)
# some abbreviations
L = step.levels[0]
computed_volume = L.prob.dx * sum(L.uend)
uex = L.prob.u_exact(L.time + L.dt)
exact_volume = L.prob.dx * sum(uex)
print(exact_volume, computed_volume, abs(exact_volume - computed_volume), abs(L.uend - uex))
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='exact_volume',
value=exact_volume,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='computed_volume',
value=computed_volume,
)
| 2,026 | 24.658228 | 100 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_Bayreuth_periodic_1D.py | import os
import dill
import matplotlib.ticker as ticker
import numpy as np
import pySDC.helpers.plot_helper as plt_helper
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AllenCahn_1D_FD import (
allencahn_periodic_fullyimplicit,
allencahn_periodic_semiimplicit,
allencahn_periodic_multiimplicit,
)
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.sweeper_classes.multi_implicit import multi_implicit
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
from pySDC.implementations.transfer_classes.TransferMesh_FFT import mesh_to_mesh_fft
from pySDC.playgrounds.Allen_Cahn.AllenCahn_monitor_Bayreuth import monitor
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 2e-02
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['Q1'] = ['LU']
sweeper_params['Q2'] = ['LU']
sweeper_params['QI'] = ['LU']
sweeper_params['QE'] = ['EE']
sweeper_params['initial_guess'] = 'spread'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nvars'] = [128 * 8] # , 128 * 4]
problem_params['dw'] = [-0.04]
problem_params['eps'] = [0.04]
problem_params['newton_maxiter'] = 200
problem_params['newton_tol'] = 1e-08
problem_params['lin_tol'] = 1e-08
problem_params['lin_maxiter'] = 100
problem_params['radius'] = 0.5
problem_params['interval'] = (-2.0, 2.0)
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
# controller_params['hook_class'] = monitor
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = None # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = None # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
# description['space_transfer_class'] = mesh_to_mesh_fft # pass spatial transfer class
# description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
return description, controller_params
def run_SDC_variant(variant=None, inexact=False):
"""
Routine to run particular SDC variant
Args:
variant (str): string describing the variant
inexact (bool): flag to use inexact nonlinear solve (or nor)
Returns:
results and statistics of the run
"""
# load (incomplete) default parameters
description, controller_params = setup_parameters()
# add stuff based on variant
if variant == 'fully-implicit':
description['problem_class'] = allencahn_periodic_fullyimplicit
# description['problem_class'] = allencahn_front_finel
description['sweeper_class'] = generic_implicit
if inexact:
description['problem_params']['newton_maxiter'] = 1
elif variant == 'semi-implicit':
description['problem_class'] = allencahn_periodic_semiimplicit
description['sweeper_class'] = imex_1st_order
if inexact:
description['problem_params']['lin_maxiter'] = 10
elif variant == 'multi-implicit':
description['problem_class'] = allencahn_periodic_multiimplicit
description['sweeper_class'] = multi_implicit
if inexact:
description['problem_params']['newton_maxiter'] = 1
description['problem_params']['lin_maxiter'] = 10
# elif variant == 'multi-implicit_v2':
# description['problem_class'] = allencahn_multiimplicit_v2
# description['sweeper_class'] = multi_implicit
# if inexact:
# description['problem_params']['newton_maxiter'] = 1
else:
raise NotImplemented('Wrong variant specified, got %s' % variant)
if inexact:
out = 'Working on inexact %s variant...' % variant
else:
out = 'Working on exact %s variant...' % variant
print(out)
# setup parameters "in time"
t0 = 0
Tend = description['level_params']['dt']
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# plt_helper.plt.plot(uinit)
# plt_helper.savefig('uinit', save_pdf=False, save_pgf=False, save_png=True)
#
# uex = P.u_exact(Tend)
# plt_helper.plt.plot(uex)
# plt_helper.savefig('uex', save_pdf=False, save_pgf=False, save_png=True)
# exit()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
plt_helper.plt.plot(uend)
plt_helper.savefig('uend', save_pdf=False, save_pgf=False, save_png=True)
# exit()
# filter statistics by variant (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
print(' Iteration count (nonlinear/linear): %i / %i' % (P.newton_itercount, P.lin_itercount))
print(
' Mean Iteration count per call: %4.2f / %4.2f'
% (P.newton_itercount / max(P.newton_ncalls, 1), P.lin_itercount / max(P.lin_ncalls, 1))
)
timing = get_sorted(stats, type='timing_run', sortby='time')
print('Time to solution: %6.4f sec.' % timing[0][1])
print()
return stats
def show_results(fname, cwd=''):
"""
Plotting routine
Args:
fname (str): file name to read in and name plots
cwd (str): current working directory
"""
file = open(cwd + fname + '.pkl', 'rb')
results = dill.load(file)
file.close()
# plt_helper.mpl.style.use('classic')
plt_helper.setup_mpl()
# set up plot for timings
fig, ax1 = plt_helper.newfig(textwidth=238.96, scale=1.5, ratio=0.4)
timings = {}
niters = {}
for key, item in results.items():
timings[key] = get_sorted(item, type='timing_run', sortby='time')[0][1]
iter_counts = get_sorted(item, type='niter', sortby='time')
niters[key] = np.mean(np.array([item[1] for item in iter_counts]))
xcoords = [i for i in range(len(timings))]
sorted_timings = sorted([(key, timings[key]) for key in timings], reverse=True, key=lambda tup: tup[1])
sorted_niters = [(k, niters[k]) for k in [key[0] for key in sorted_timings]]
heights_timings = [item[1] for item in sorted_timings]
heights_niters = [item[1] for item in sorted_niters]
keys = [(item[0][1] + ' ' + item[0][0]).replace('-', '\n').replace('_v2', ' mod.') for item in sorted_timings]
ax1.bar(xcoords, heights_timings, align='edge', width=-0.3, label='timings (left axis)')
ax1.set_ylabel('time (sec)')
ax2 = ax1.twinx()
ax2.bar(xcoords, heights_niters, color='r', align='edge', width=0.3, label='iterations (right axis)')
ax2.set_ylabel('mean number of iterations')
ax1.set_xticks(xcoords)
ax1.set_xticklabels(keys, rotation=90, ha='center')
# ask matplotlib for the plotted objects and their labels
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)
# save plot, beautify
f = fname + '_timings'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
# set up plot for radii
fig, ax = plt_helper.newfig(textwidth=238.96, scale=1.0)
exact_radii = []
for key, item in results.items():
computed_radii = get_sorted(item, type='computed_radius', sortby='time')
xcoords = [item0[0] for item0 in computed_radii]
radii = [item0[1] for item0 in computed_radii]
if key[0] + ' ' + key[1] == 'fully-implicit exact':
ax.plot(xcoords, radii, label=(key[0] + ' ' + key[1]).replace('_v2', ' mod.'))
exact_radii = get_sorted(item, type='exact_radius', sortby='time')
diff = np.array([abs(item0[1] - item1[1]) for item0, item1 in zip(exact_radii, computed_radii)])
max_pos = int(np.argmax(diff))
assert max(diff) < 0.07, 'ERROR: computed radius is too far away from exact radius, got %s' % max(diff)
assert 0.028 < computed_radii[max_pos][0] < 0.03, (
'ERROR: largest difference is at wrong time, got %s' % computed_radii[max_pos][0]
)
xcoords = [item[0] for item in exact_radii]
radii = [item[1] for item in exact_radii]
ax.plot(xcoords, radii, color='k', linestyle='--', linewidth=1, label='exact')
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
ax.set_ylabel('radius')
ax.set_xlabel('time')
ax.grid()
ax.legend(loc=3)
# save plot, beautify
f = fname + '_radii'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
# set up plot for interface width
fig, ax = plt_helper.newfig(textwidth=238.96, scale=1.0)
interface_width = []
for key, item in results.items():
interface_width = get_sorted(item, type='interface_width', sortby='time')
xcoords = [item[0] for item in interface_width]
width = [item[1] for item in interface_width]
if key[0] + ' ' + key[1] == 'fully-implicit exact':
ax.plot(xcoords, width, label=key[0] + ' ' + key[1])
xcoords = [item[0] for item in interface_width]
init_width = [interface_width[0][1]] * len(xcoords)
ax.plot(xcoords, init_width, color='k', linestyle='--', linewidth=1, label='exact')
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
ax.set_ylabel(r'interface width ($\epsilon$)')
ax.set_xlabel('time')
ax.grid()
ax.legend(loc=3)
# save plot, beautify
f = fname + '_interface'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
return None
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
# Loop over variants, exact and inexact solves
results = {}
# for variant in ['multi-implicit', 'semi-implicit', 'fully-implicit', 'semi-implicit_v2', 'multi-implicit_v2']:
# for variant in ['fully-implicit']:
# for variant in ['semi-implicit']:
for variant in ['multi-implicit']:
results[(variant, 'exact')] = run_SDC_variant(variant=variant, inexact=False)
# results[(variant, 'inexact')] = run_SDC_variant(variant=variant, inexact=True)
# dump result
# fname = 'data/results_SDC_variants_AllenCahn_1E-03'
# file = open(cwd + fname + '.pkl', 'wb')
# dill.dump(results, file)
# file.close()
# assert os.path.isfile(cwd + fname + '.pkl'), 'ERROR: dill did not create file'
# visualize
# show_results(fname, cwd=cwd)
if __name__ == "__main__":
main()
| 13,025 | 36.111111 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_contracting_circle_standard_integrators.py | import time
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
from pySDC.implementations.problem_classes.AllenCahn_2D_FD import allencahn_fullyimplicit, allencahn_semiimplicit
# http://www.personal.psu.edu/qud2/Res/Pre/dz09sisc.pdf
def setup_problem():
problem_params = dict()
problem_params['nu'] = 2
problem_params['nvars'] = (128, 128)
problem_params['eps'] = 0.04
problem_params['newton_maxiter'] = 100
problem_params['newton_tol'] = 1e-07
problem_params['lin_tol'] = 1e-08
problem_params['lin_maxiter'] = 100
problem_params['radius'] = 0.25
return problem_params
def run_implicit_Euler(t0, dt, Tend):
"""
Routine to run particular SDC variant
Args:
Tend (float): end time for dumping
"""
problem = allencahn_fullyimplicit(problem_params=setup_problem(), dtype_u=mesh, dtype_f=mesh)
u = problem.u_exact(t0)
radius = []
exact_radius = []
nsteps = int((Tend - t0) / dt)
startt = time.perf_counter()
t = t0
for n in range(nsteps):
u_new = problem.solve_system(rhs=u, factor=dt, u0=u, t=t)
u = u_new
t += dt
r, re = compute_radius(u, problem.dx, t, problem.params.radius)
radius.append(r)
exact_radius.append(re)
print(' ... done with time = %6.4f, step = %i / %i' % (t, n + 1, nsteps))
print('Time to solution: %6.4f sec.' % (time.perf_counter() - startt))
fname = 'data/AC_reference_Tend{:.1e}'.format(Tend) + '.npz'
loaded = np.load(fname)
uref = loaded['uend']
err = np.linalg.norm(uref - u, np.inf)
print('Error vs. reference solution: %6.4e' % err)
return err, radius, exact_radius
def run_imex_Euler(t0, dt, Tend):
"""
Routine to run particular SDC variant
Args:
Tend (float): end time for dumping
"""
problem = allencahn_semiimplicit(problem_params=setup_problem(), dtype_u=mesh, dtype_f=imex_mesh)
u = problem.u_exact(t0)
radius = []
exact_radius = []
nsteps = int((Tend - t0) / dt)
startt = time.perf_counter()
t = t0
for n in range(nsteps):
f = problem.eval_f(u, t)
rhs = u + dt * f.expl
u_new = problem.solve_system(rhs=rhs, factor=dt, u0=u, t=t)
u = u_new
t += dt
r, re = compute_radius(u, problem.dx, t, problem.params.radius)
radius.append(r)
exact_radius.append(re)
print(' ... done with time = %6.4f, step = %i / %i' % (t, n + 1, nsteps))
print('Time to solution: %6.4f sec.' % (time.perf_counter() - startt))
fname = 'data/AC_reference_Tend{:.1e}'.format(Tend) + '.npz'
loaded = np.load(fname)
uref = loaded['uend']
err = np.linalg.norm(uref - u, np.inf)
print('Error vs. reference solution: %6.4e' % err)
return err, radius, exact_radius
def run_CrankNicholson(t0, dt, Tend):
"""
Routine to run particular SDC variant
Args:
Tend (float): end time for dumping
"""
problem = allencahn_fullyimplicit(problem_params=setup_problem(), dtype_u=mesh, dtype_f=mesh)
u = problem.u_exact(t0)
radius = []
exact_radius = []
nsteps = int((Tend - t0) / dt)
startt = time.perf_counter()
t = t0
for n in range(nsteps):
rhs = u + dt / 2 * problem.eval_f(u, t)
u_new = problem.solve_system(rhs=rhs, factor=dt / 2, u0=u, t=t)
u = u_new
t += dt
r, re = compute_radius(u, problem.dx, t, problem.params.radius)
radius.append(r)
exact_radius.append(re)
print(' ... done with time = %6.4f, step = %i / %i' % (t, n + 1, nsteps))
print('Time to solution: %6.4f sec.' % (time.perf_counter() - startt))
fname = 'data/AC_reference_Tend{:.1e}'.format(Tend) + '.npz'
loaded = np.load(fname)
uref = loaded['uend']
err = np.linalg.norm(uref - u, np.inf)
print('Error vs. reference solution: %6.4e' % err)
return err, radius, exact_radius
def compute_radius(u, dx, t, init_radius):
c = np.count_nonzero(u >= 0.0)
radius = np.sqrt(c / np.pi) * dx
exact_radius = np.sqrt(max(init_radius**2 - 2.0 * t, 0))
return radius, exact_radius
def plot_radius(xcoords, exact_radius, radii):
fig, ax = plt.subplots()
plt.plot(xcoords, exact_radius, color='k', linestyle='--', linewidth=1, label='exact')
for type, radius in radii.items():
plt.plot(xcoords, radius, linestyle='-', linewidth=2, label=type)
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
ax.set_ylabel('radius')
ax.set_xlabel('time')
ax.grid()
ax.legend(loc=3)
fname = 'data/AC_contracting_circle_standard_integrators'
plt.savefig('{}.pdf'.format(fname), bbox_inches='tight')
# plt.show()
def main_radius(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
# setup parameters "in time"
t0 = 0.0
dt = 0.001
Tend = 0.032
radii = {}
_, radius, exact_radius = run_implicit_Euler(t0=t0, dt=dt, Tend=Tend)
radii['implicit-Euler'] = radius
_, radius, exact_radius = run_imex_Euler(t0=t0, dt=dt, Tend=Tend)
radii['imex-Euler'] = radius
_, radius, exact_radius = run_CrankNicholson(t0=t0, dt=dt, Tend=Tend)
radii['CrankNicholson'] = radius
xcoords = [t0 + i * dt for i in range(int((Tend - t0) / dt))]
plot_radius(xcoords, exact_radius, radii)
def main_error(cwd=''):
t0 = 0
Tend = 0.032
errors = {}
# err, _, _ = run_implicit_Euler(t0=t0, dt=0.001/512, Tend=Tend)
# errors['implicit-Euler'] = err
# err, _, _ = run_imex_Euler(t0=t0, dt=0.001/512, Tend=Tend)
# errors['imex-Euler'] = err
err, _, _ = run_CrankNicholson(t0=t0, dt=0.001 / 64, Tend=Tend)
errors['CrankNicholson'] = err
if __name__ == "__main__":
main_error()
# main_radius()
| 5,979 | 25.113537 | 113 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_contracting_circle_FFT.py | import sys
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AllenCahn_2D_FFT import allencahn2d_imex
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferMesh_FFT2D import mesh_to_mesh_fft2d
from pySDC.playgrounds.Allen_Cahn.AllenCahn_output import output
# http://www.personal.psu.edu/qud2/Res/Pre/dz09sisc.pdf
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-07
level_params['dt'] = 1e-03
level_params['nsweeps'] = None
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU']
sweeper_params['QE'] = ['EE']
sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nu'] = 2
problem_params['L'] = 1.0
problem_params['nvars'] = None
problem_params['eps'] = 0.04
problem_params['radius'] = 0.25
problem_params['init_type'] = 'circle'
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = allencahn2d_imex # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fft2d
return description, controller_params
def run_variant(nlevels=None):
"""
Routine to run particular SDC variant
Args:
Returns:
"""
# load (incomplete) default parameters
description, controller_params = setup_parameters()
# add stuff based on variant
if nlevels == 1:
description['level_params']['nsweeps'] = 1
description['problem_params']['nvars'] = [(128, 128)]
# description['problem_params']['nvars'] = [(32, 32)]
elif nlevels == 2:
description['level_params']['nsweeps'] = [1, 1]
description['problem_params']['nvars'] = [(128, 128), (32, 32)]
# description['problem_params']['nvars'] = [(32, 32), (16, 16)]
else:
raise NotImplemented('Wrong variant specified, got %s' % nlevels)
out = 'Working on %s levels...' % nlevels
print(out)
# setup parameters "in time"
t0 = 0.0
Tend = 0.032
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# filter statistics by variant (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
print('Time to solution: %6.4f sec.' % timing[0][1])
fname = 'data/AC_reference_FFT_Tend{:.1e}'.format(Tend) + '.npz'
loaded = np.load(fname)
uref = loaded['uend']
err = np.linalg.norm(uref - uend, np.inf)
print('Error vs. reference solution: %6.4e' % err)
print()
return stats
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
if len(sys.argv) == 2:
nlevels = int(sys.argv[1])
else:
nlevels = 1
# raise NotImplementedError('Need input of nsweeps, got % s' % sys.argv)
_ = run_variant(nlevels=nlevels)
if __name__ == "__main__":
main()
| 5,098 | 30.282209 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_contracting_circle_FFT_PFASST.py | import sys
import numpy as np
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.problem_classes.AllenCahn_2D_FFT import allencahn2d_imex
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferMesh_FFT2D import mesh_to_mesh_fft2d
from pySDC.playgrounds.Allen_Cahn.AllenCahn_monitor import monitor
# http://www.personal.psu.edu/qud2/Res/Pre/dz09sisc.pdf
def setup_parameters(nsweeps=None):
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-07
level_params['dt'] = 1e-03 / 2
level_params['nsweeps'] = [nsweeps, 1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU']
sweeper_params['QE'] = ['EE']
sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nu'] = 2
problem_params['L'] = 1.0
problem_params['nvars'] = [(128, 128), (32, 32)]
problem_params['eps'] = 0.04
problem_params['radius'] = 0.25
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = monitor
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = allencahn2d_imex # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fft2d
return description, controller_params
def run_variant(nsweeps):
"""
Routine to run particular SDC variant
Args:
Returns:
"""
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
# split world communicator to create space-communicators
if len(sys.argv) >= 3:
color = int(world_rank / int(sys.argv[2]))
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
space_size = space_comm.Get_size()
space_rank = space_comm.Get_rank()
# split world communicator to create time-communicators
if len(sys.argv) >= 3:
color = int(world_rank % int(sys.argv[2]))
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
time_size = time_comm.Get_size()
time_rank = time_comm.Get_rank()
print(
"IDs (world, space, time): %i / %i -- %i / %i -- %i / %i"
% (world_rank, world_size, space_rank, space_size, time_rank, time_size)
)
# load (incomplete) default parameters
description, controller_params = setup_parameters(nsweeps=nsweeps)
# setup parameters "in time"
t0 = 0.0
Tend = 0.032
# instantiate controller
controller = controller_MPI(controller_params=controller_params, description=description, comm=time_comm)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# filter statistics by variant (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
maxtiming = comm.allreduce(sendobj=timing[0][1], op=MPI.MAX)
if time_rank == time_size - 1 and space_rank == 0:
print('Time to solution: %6.4f sec.' % maxtiming)
# if time_rank == time_size - 1:
# fname = 'data/AC_reference_FFT_Tend{:.1e}'.format(Tend) + '.npz'
# loaded = np.load(fname)
# uref = loaded['uend']
#
# err = np.linalg.norm(uref - uend, np.inf)
# print('Error vs. reference solution: %6.4e' % err)
# print()
return stats
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
nsweeps = 3
if len(sys.argv) >= 2:
nsweeps = int(sys.argv[1])
else:
raise NotImplementedError('Need input of nsweeps, got % s' % sys.argv)
# Loop over variants, exact and inexact solves
_ = run_variant(nsweeps=nsweeps)
if __name__ == "__main__":
main()
| 5,668 | 30.320442 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_Bayreuth_front_1D.py | import os
import dill
import matplotlib.ticker as ticker
import numpy as np
import pySDC.helpers.plot_helper as plt_helper
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AllenCahn_1D_FD import (
allencahn_front_fullyimplicit,
allencahn_front_semiimplicit,
)
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.playgrounds.Allen_Cahn.AllenCahn_monitor_Bayreuth import monitor
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-03
level_params['dt'] = 16.0 / 1
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['Q1'] = ['LU']
sweeper_params['Q2'] = ['LU']
sweeper_params['QI'] = ['LU']
sweeper_params['QE'] = ['EE']
sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nvars'] = 127
problem_params['dw'] = -0.04
problem_params['eps'] = 0.04
problem_params['newton_maxiter'] = 100
problem_params['newton_tol'] = 1e-04
problem_params['lin_tol'] = 1e-08
problem_params['lin_maxiter'] = 100
problem_params['radius'] = 0.25
problem_params['interval'] = (-0.5, 0.5)
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
controller_params['hook_class'] = monitor
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = None # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = None # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
return description, controller_params
def run_SDC_variant(variant=None, inexact=False):
"""
Routine to run particular SDC variant
Args:
variant (str): string describing the variant
inexact (bool): flag to use inexact nonlinear solve (or nor)
Returns:
results and statistics of the run
"""
# load (incomplete) default parameters
description, controller_params = setup_parameters()
# add stuff based on variant
if variant == 'fully-implicit':
description['problem_class'] = allencahn_front_fullyimplicit
# description['problem_class'] = allencahn_front_finel
description['sweeper_class'] = generic_implicit
if inexact:
description['problem_params']['newton_maxiter'] = 200
elif variant == 'semi-implicit':
description['problem_class'] = allencahn_front_semiimplicit
description['sweeper_class'] = imex_1st_order
if inexact:
description['problem_params']['lin_maxiter'] = 10
# elif variant == 'multi-implicit':
# description['problem_class'] = allencahn_multiimplicit
# description['sweeper_class'] = multi_implicit
# if inexact:
# description['problem_params']['newton_maxiter'] = 1
# description['problem_params']['lin_maxiter'] = 10
# elif variant == 'multi-implicit_v2':
# description['problem_class'] = allencahn_multiimplicit_v2
# description['sweeper_class'] = multi_implicit
# if inexact:
# description['problem_params']['newton_maxiter'] = 1
else:
raise NotImplemented('Wrong variant specified, got %s' % variant)
if inexact:
out = 'Working on inexact %s variant...' % variant
else:
out = 'Working on exact %s variant...' % variant
print(out)
# setup parameters "in time"
t0 = 0
Tend = 32.0
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# plt_helper.plt.plot(uinit.values)
# plt_helper.savefig('uinit', save_pdf=False, save_pgf=False, save_png=True)
#
# uex = P.u_exact(Tend)
# plt_helper.plt.plot(uex.values)
# plt_helper.savefig('uex', save_pdf=False, save_pgf=False, save_png=True)
# exit()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# plt_helper.plt.plot(uend.values)
# plt_helper.savefig('uend', save_pdf=False, save_pgf=False, save_png=True)
# exit()
# filter statistics by variant (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
print(' Iteration count (nonlinear/linear): %i / %i' % (P.newton_itercount, P.lin_itercount))
print(
' Mean Iteration count per call: %4.2f / %4.2f'
% (P.newton_itercount / max(P.newton_ncalls, 1), P.lin_itercount / max(P.lin_ncalls, 1))
)
timing = get_sorted(stats, type='timing_run', sortby='time')
print('Time to solution: %6.4f sec.' % timing[0][1])
print()
return stats
def show_results(fname, cwd=''):
"""
Plotting routine
Args:
fname (str): file name to read in and name plots
cwd (str): current working directory
"""
file = open(cwd + fname + '.pkl', 'rb')
results = dill.load(file)
file.close()
# plt_helper.mpl.style.use('classic')
plt_helper.setup_mpl()
# set up plot for timings
fig, ax1 = plt_helper.newfig(textwidth=238.96, scale=1.5, ratio=0.4)
timings = {}
niters = {}
for key, item in results.items():
timings[key] = get_sorted(item, type='timing_run', sortby='time')[0][1]
iter_counts = get_sorted(item, type='niter', sortby='time')
niters[key] = np.mean(np.array([item[1] for item in iter_counts]))
xcoords = [i for i in range(len(timings))]
sorted_timings = sorted([(key, timings[key]) for key in timings], reverse=True, key=lambda tup: tup[1])
sorted_niters = [(k, niters[k]) for k in [key[0] for key in sorted_timings]]
heights_timings = [item[1] for item in sorted_timings]
heights_niters = [item[1] for item in sorted_niters]
keys = [(item[0][1] + ' ' + item[0][0]).replace('-', '\n').replace('_v2', ' mod.') for item in sorted_timings]
ax1.bar(xcoords, heights_timings, align='edge', width=-0.3, label='timings (left axis)')
ax1.set_ylabel('time (sec)')
ax2 = ax1.twinx()
ax2.bar(xcoords, heights_niters, color='r', align='edge', width=0.3, label='iterations (right axis)')
ax2.set_ylabel('mean number of iterations')
ax1.set_xticks(xcoords)
ax1.set_xticklabels(keys, rotation=90, ha='center')
# ask matplotlib for the plotted objects and their labels
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)
# save plot, beautify
f = fname + '_timings'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
# set up plot for radii
fig, ax = plt_helper.newfig(textwidth=238.96, scale=1.0)
exact_radii = []
for key, item in results.items():
computed_radii = get_sorted(item, type='computed_radius', sortby='time')
xcoords = [item0[0] for item0 in computed_radii]
radii = [item0[1] for item0 in computed_radii]
if key[0] + ' ' + key[1] == 'fully-implicit exact':
ax.plot(xcoords, radii, label=(key[0] + ' ' + key[1]).replace('_v2', ' mod.'))
exact_radii = get_sorted(item, type='exact_radius', sortby='time')
diff = np.array([abs(item0[1] - item1[1]) for item0, item1 in zip(exact_radii, computed_radii)])
max_pos = int(np.argmax(diff))
assert max(diff) < 0.07, 'ERROR: computed radius is too far away from exact radius, got %s' % max(diff)
assert 0.028 < computed_radii[max_pos][0] < 0.03, (
'ERROR: largest difference is at wrong time, got %s' % computed_radii[max_pos][0]
)
xcoords = [item[0] for item in exact_radii]
radii = [item[1] for item in exact_radii]
ax.plot(xcoords, radii, color='k', linestyle='--', linewidth=1, label='exact')
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
ax.set_ylabel('radius')
ax.set_xlabel('time')
ax.grid()
ax.legend(loc=3)
# save plot, beautify
f = fname + '_radii'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
# set up plot for interface width
fig, ax = plt_helper.newfig(textwidth=238.96, scale=1.0)
interface_width = []
for key, item in results.items():
interface_width = get_sorted(item, type='interface_width', sortby='time')
xcoords = [item[0] for item in interface_width]
width = [item[1] for item in interface_width]
if key[0] + ' ' + key[1] == 'fully-implicit exact':
ax.plot(xcoords, width, label=key[0] + ' ' + key[1])
xcoords = [item[0] for item in interface_width]
init_width = [interface_width[0][1]] * len(xcoords)
ax.plot(xcoords, init_width, color='k', linestyle='--', linewidth=1, label='exact')
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
ax.set_ylabel(r'interface width ($\epsilon$)')
ax.set_xlabel('time')
ax.grid()
ax.legend(loc=3)
# save plot, beautify
f = fname + '_interface'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
return None
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
# Loop over variants, exact and inexact solves
results = {}
# for variant in ['multi-implicit', 'semi-implicit', 'fully-implicit', 'semi-implicit_v2', 'multi-implicit_v2']:
for variant in ['fully-implicit']:
# for variant in ['semi-implicit']:
# results[(variant, 'exact')] = run_SDC_variant(variant=variant, inexact=False)
results[(variant, 'inexact')] = run_SDC_variant(variant=variant, inexact=True)
# dump result
# fname = 'data/results_SDC_variants_AllenCahn_1E-03'
# file = open(cwd + fname + '.pkl', 'wb')
# dill.dump(results, file)
# file.close()
# assert os.path.isfile(cwd + fname + '.pkl'), 'ERROR: dill did not create file'
# visualize
# show_results(fname, cwd=cwd)
if __name__ == "__main__":
main()
| 12,314 | 35.327434 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_Bayreuth_front_1D_reference.py | import timeit
import numpy as np
import pySDC.helpers.plot_helper as plt_helper
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AllenCahn_1D_FD import allencahn_front_fullyimplicit
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.sweeper_classes.explicit import explicit
from pySDC.playgrounds.Allen_Cahn.AllenCahn_monitor_Bayreuth import monitor
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 1.0 / (16.0 * 128.0**2)
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [1]
sweeper_params['Q1'] = ['LU']
sweeper_params['Q2'] = ['LU']
sweeper_params['QI'] = ['LU']
sweeper_params['QE'] = ['EE']
sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nvars'] = 127
problem_params['dw'] = -0.04
problem_params['eps'] = 0.04
problem_params['newton_maxiter'] = 100
problem_params['newton_tol'] = 1e-08
problem_params['lin_tol'] = 1e-08
problem_params['lin_maxiter'] = 100
problem_params['radius'] = 0.25
problem_params['interval'] = (-0.5, 0.5)
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = monitor
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = allencahn_front_fullyimplicit
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = explicit
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
return description, controller_params
def run_SDC_variant(variant=None, inexact=False):
"""
Routine to run particular SDC variant
Args:
variant (str): string describing the variant
inexact (bool): flag to use inexact nonlinear solve (or nor)
Returns:
results and statistics of the run
"""
# load (incomplete) default parameters
description, controller_params = setup_parameters()
# add stuff based on variant
if variant == 'explicit':
description['problem_class'] = allencahn_front_fullyimplicit
description['sweeper_class'] = explicit
else:
raise NotImplemented('Wrong variant specified, got %s' % variant)
# setup parameters "in time"
t0 = 0
Tend = 1.0 / (16.0 * 128.0**2)
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
# uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
wrapped = wrapper(controller.run, u0=uinit, t0=t0, Tend=Tend)
print(timeit.timeit(wrapped, number=10000) / 10000.0)
def wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
# Loop over variants, exact and inexact solves
run_SDC_variant(variant='explicit')
if __name__ == "__main__":
main()
| 4,157 | 30.029851 | 116 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_monitor.py | import numpy as np
from pySDC.core.Hooks import hooks
class monitor(hooks):
def __init__(self):
"""
Initialization of Allen-Cahn monitoring
"""
super(monitor, self).__init__()
self.init_radius = None
def pre_run(self, step, level_number):
"""
Overwrite standard pre run hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(monitor, self).pre_run(step, level_number)
L = step.levels[0]
c = np.count_nonzero(L.u[0] > 0.0)
radius = np.sqrt(c / np.pi) * L.prob.dx
radius1 = 0
rows, cols = np.where(L.u[0] > 0.0)
for r in rows:
radius1 = max(radius1, abs(L.prob.xvalues[r]))
rows1 = np.where(L.u[0][int((L.prob.init[0][0]) / 2), : int((L.prob.init[0][0]) / 2)] > -0.99)
rows2 = np.where(L.u[0][int((L.prob.init[0][0]) / 2), : int((L.prob.init[0][0]) / 2)] < 0.99)
interface_width = (rows2[0][-1] - rows1[0][0]) * L.prob.dx / L.prob.eps
self.init_radius = L.prob.radius
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='computed_radius',
value=radius,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='exact_radius',
value=self.init_radius,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='interface_width',
value=interface_width,
)
def post_step(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(monitor, self).post_step(step, level_number)
# some abbreviations
L = step.levels[0]
c = np.count_nonzero(L.uend >= 0.0)
radius = np.sqrt(c / np.pi) * L.prob.dx
exact_radius = np.sqrt(max(self.init_radius**2 - 2.0 * (L.time + L.dt), 0))
rows1 = np.where(L.uend[int((L.prob.init[0][0]) / 2), : int((L.prob.init[0][0]) / 2)] > -0.99)
rows2 = np.where(L.uend[int((L.prob.init[0][0]) / 2), : int((L.prob.init[0][0]) / 2)] < 0.99)
interface_width = (rows2[0][-1] - rows1[0][0]) * L.prob.dx / L.prob.eps
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='computed_radius',
value=radius,
)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='exact_radius',
value=exact_radius,
)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='interface_width',
value=interface_width,
)
| 3,517 | 29.327586 | 102 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_reference.py | import os
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AllenCahn_2D_FD import allencahn_fullyimplicit
from pySDC.implementations.problem_classes.AllenCahn_2D_FFT import allencahn2d_imex
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.playgrounds.Allen_Cahn.AllenCahn_monitor import monitor
# http://www.personal.psu.edu/qud2/Res/Pre/dz09sisc.pdf
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-11
level_params['dt'] = 1e-05
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [5]
sweeper_params['QI'] = ['LU']
sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nu'] = 2
problem_params['nvars'] = [(128, 128)]
problem_params['eps'] = [0.04]
problem_params['newton_maxiter'] = 100
problem_params['newton_tol'] = 1e-12
problem_params['lin_tol'] = 1e-12
problem_params['lin_maxiter'] = 100
problem_params['radius'] = 0.25
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
# controller_params['hook_class'] = monitor
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = allencahn_fullyimplicit # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
return description, controller_params
def setup_parameters_FFT():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-11
level_params['dt'] = 1e-04
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [5]
sweeper_params['QI'] = ['LU']
sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nu'] = 2
problem_params['nvars'] = [(128, 128)]
problem_params['eps'] = [0.04]
problem_params['newton_maxiter'] = 100
problem_params['newton_tol'] = 1e-12
problem_params['lin_tol'] = 1e-12
problem_params['lin_maxiter'] = 100
problem_params['radius'] = 0.25
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
controller_params['hook_class'] = monitor
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = allencahn2d_imex # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
return description, controller_params
def run_reference(Tend):
"""
Routine to run particular SDC variant
Args:
Tend (float): end time for dumping
"""
# load (incomplete) default parameters
description, controller_params = setup_parameters_FFT()
# setup parameters "in time"
t0 = 0
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# filter statistics by variant (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
print('Time to solution: %6.4f sec.' % timing[0][1])
print()
computed_radii_tmp = get_sorted(stats, type='computed_radius', sortby='time')
computed_radii = np.array([item0[1] for item0 in computed_radii_tmp])
print(len(computed_radii_tmp), len(computed_radii))
fname = 'data/AC_reference_FFT_Tend{:.1e}'.format(Tend)
np.savez_compressed(file=fname, uend=uend, radius=computed_radii)
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
Tend = 0.032
run_reference(Tend=Tend)
fname = cwd + 'data/AC_reference_FFT_Tend{:.1e}'.format(Tend) + '.npz'
assert os.path.isfile(fname), 'ERROR: numpy did not create file'
loaded = np.load(fname)
uend = loaded['uend']
if __name__ == "__main__":
main()
| 6,640 | 32.205 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_contracting_circle_SDC.py | import os
import dill
import matplotlib.ticker as ticker
import numpy as np
import pySDC.helpers.plot_helper as plt_helper
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AllenCahn_2D_FD import (
allencahn_fullyimplicit,
allencahn_semiimplicit,
allencahn_semiimplicit_v2,
allencahn_multiimplicit,
allencahn_multiimplicit_v2,
)
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.sweeper_classes.multi_implicit import multi_implicit
from pySDC.playgrounds.Allen_Cahn.AllenCahn_monitor import monitor
# http://www.personal.psu.edu/qud2/Res/Pre/dz09sisc.pdf
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-07
level_params['dt'] = 1e-03 / 2
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['Q1'] = ['LU']
sweeper_params['Q2'] = ['LU']
sweeper_params['QI'] = ['LU']
sweeper_params['QE'] = ['EE']
sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nu'] = 2
problem_params['nvars'] = (128, 128)
problem_params['eps'] = 0.04
problem_params['newton_maxiter'] = 100
problem_params['newton_tol'] = 1e-08
problem_params['lin_tol'] = 1e-09
problem_params['lin_maxiter'] = 100
problem_params['radius'] = 0.25
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = monitor
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = None # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = None # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
return description, controller_params
def run_SDC_variant(variant=None, inexact=False):
"""
Routine to run particular SDC variant
Args:
variant (str): string describing the variant
inexact (bool): flag to use inexact nonlinear solve (or nor)
Returns:
results and statistics of the run
"""
# load (incomplete) default parameters
description, controller_params = setup_parameters()
# add stuff based on variant
if variant == 'fully-implicit':
description['problem_class'] = allencahn_fullyimplicit
description['sweeper_class'] = generic_implicit
if inexact:
description['problem_params']['newton_maxiter'] = 1
elif variant == 'semi-implicit':
description['problem_class'] = allencahn_semiimplicit
description['sweeper_class'] = imex_1st_order
if inexact:
description['problem_params']['lin_maxiter'] = 10
elif variant == 'semi-implicit_v2':
description['problem_class'] = allencahn_semiimplicit_v2
description['sweeper_class'] = imex_1st_order
if inexact:
description['problem_params']['newton_maxiter'] = 1
elif variant == 'multi-implicit':
description['problem_class'] = allencahn_multiimplicit
description['sweeper_class'] = multi_implicit
if inexact:
description['problem_params']['newton_maxiter'] = 1
description['problem_params']['lin_maxiter'] = 10
elif variant == 'multi-implicit_v2':
description['problem_class'] = allencahn_multiimplicit_v2
description['sweeper_class'] = multi_implicit
if inexact:
description['problem_params']['newton_maxiter'] = 1
else:
raise NotImplemented('Wrong variant specified, got %s' % variant)
if inexact:
out = 'Working on inexact %s variant...' % variant
else:
out = 'Working on exact %s variant...' % variant
print(out)
# setup parameters "in time"
t0 = 0
Tend = 0.032
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# filter statistics by variant (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
print(' Iteration count (nonlinear/linear): %i / %i' % (P.newton_itercount, P.lin_itercount))
print(
' Mean Iteration count per call: %4.2f / %4.2f'
% (P.newton_itercount / max(P.newton_ncalls, 1), P.lin_itercount / max(P.lin_ncalls, 1))
)
timing = get_sorted(stats, type='timing_run', sortby='time')
print('Time to solution: %6.4f sec.' % timing[0][1])
fname = 'data/AC_reference_Tend{:.1e}'.format(Tend) + '.npz'
loaded = np.load(fname)
uref = loaded['uend']
err = np.linalg.norm(uref - uend, np.inf)
print('Error vs. reference solution: %6.4e' % err)
print()
return stats
def show_results(fname, cwd=''):
"""
Plotting routine
Args:
fname (str): file name to read in and name plots
cwd (str): current working directory
"""
file = open(cwd + fname + '.pkl', 'rb')
results = dill.load(file)
file.close()
# plt_helper.mpl.style.use('classic')
plt_helper.setup_mpl()
# set up plot for timings
fig, ax1 = plt_helper.newfig(textwidth=238.96, scale=1.5, ratio=0.4)
timings = {}
niters = {}
for key, item in results.items():
timings[key] = get_sorted(item, type='timing_run', sortby='time')[0][1]
iter_counts = get_sorted(item, type='niter', sortby='time')
niters[key] = np.mean(np.array([item[1] for item in iter_counts]))
xcoords = [i for i in range(len(timings))]
sorted_timings = sorted([(key, timings[key]) for key in timings], reverse=True, key=lambda tup: tup[1])
sorted_niters = [(k, niters[k]) for k in [key[0] for key in sorted_timings]]
heights_timings = [item[1] for item in sorted_timings]
heights_niters = [item[1] for item in sorted_niters]
keys = [(item[0][1] + ' ' + item[0][0]).replace('-', '\n').replace('_v2', ' mod.') for item in sorted_timings]
ax1.bar(xcoords, heights_timings, align='edge', width=-0.3, label='timings (left axis)')
ax1.set_ylabel('time (sec)')
ax2 = ax1.twinx()
ax2.bar(xcoords, heights_niters, color='r', align='edge', width=0.3, label='iterations (right axis)')
ax2.set_ylabel('mean number of iterations')
ax1.set_xticks(xcoords)
ax1.set_xticklabels(keys, rotation=90, ha='center')
# ask matplotlib for the plotted objects and their labels
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)
# save plot, beautify
f = fname + '_timings'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
# set up plot for radii
fig, ax = plt_helper.newfig(textwidth=238.96, scale=1.0)
exact_radii = []
for key, item in results.items():
computed_radii = get_sorted(item, type='computed_radius', sortby='time')
xcoords = [item0[0] for item0 in computed_radii]
radii = [item0[1] for item0 in computed_radii]
if key[0] + ' ' + key[1] == 'fully-implicit exact':
ax.plot(xcoords, radii, label=(key[0] + ' ' + key[1]).replace('_v2', ' mod.'))
exact_radii = get_sorted(item, type='exact_radius', sortby='time')
diff = np.array([abs(item0[1] - item1[1]) for item0, item1 in zip(exact_radii, computed_radii)])
max_pos = int(np.argmax(diff))
assert max(diff) < 0.07, 'ERROR: computed radius is too far away from exact radius, got %s' % max(diff)
assert 0.028 < computed_radii[max_pos][0] < 0.03, (
'ERROR: largest difference is at wrong time, got %s' % computed_radii[max_pos][0]
)
xcoords = [item[0] for item in exact_radii]
radii = [item[1] for item in exact_radii]
ax.plot(xcoords, radii, color='k', linestyle='--', linewidth=1, label='exact')
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
ax.set_ylabel('radius')
ax.set_xlabel('time')
ax.grid()
ax.legend(loc=3)
# save plot, beautify
f = fname + '_radii'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
# set up plot for interface width
fig, ax = plt_helper.newfig(textwidth=238.96, scale=1.0)
interface_width = []
for key, item in results.items():
interface_width = get_sorted(item, type='interface_width', sortby='time')
xcoords = [item[0] for item in interface_width]
width = [item[1] for item in interface_width]
if key[0] + ' ' + key[1] == 'fully-implicit exact':
ax.plot(xcoords, width, label=key[0] + ' ' + key[1])
xcoords = [item[0] for item in interface_width]
init_width = [interface_width[0][1]] * len(xcoords)
ax.plot(xcoords, init_width, color='k', linestyle='--', linewidth=1, label='exact')
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
ax.set_ylabel(r'interface width ($\epsilon$)')
ax.set_xlabel('time')
ax.grid()
ax.legend(loc=3)
# save plot, beautify
f = fname + '_interface'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
return None
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
# Loop over variants, exact and inexact solves
results = {}
for variant in ['multi-implicit', 'semi-implicit', 'fully-implicit', 'semi-implicit_v2', 'multi-implicit_v2']:
results[(variant, 'exact')] = run_SDC_variant(variant=variant, inexact=False)
results[(variant, 'inexact')] = run_SDC_variant(variant=variant, inexact=True)
# dump result
fname = 'data/results_SDC_variants_AllenCahn_1E-03'
file = open(cwd + fname + '.pkl', 'wb')
dill.dump(results, file)
file.close()
assert os.path.isfile(cwd + fname + '.pkl'), 'ERROR: dill did not create file'
# visualize
# show_results(fname, cwd=cwd)
if __name__ == "__main__":
main()
| 12,332 | 35.167155 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/parallel_playground.py | import h5py
from mpi4py import MPI
rank = MPI.COMM_WORLD.rank # The process ID (integer 0-3 for 4-process run)
f = h5py.File('parallel_test.hdf5', 'w', driver='mpio', comm=MPI.COMM_WORLD)
dset = f.create_dataset('test', (4,), dtype='i')
dset[rank] = rank
f.close()
| 270 | 21.583333 | 76 | py |
pySDC | pySDC-master/pySDC/playgrounds/Allen_Cahn/AllenCahn_output.py | import pySDC.helpers.plot_helper as plt_helper
from pySDC.core.Hooks import hooks
class output(hooks):
def __init__(self):
"""
Initialization of Allen-Cahn monitoring
"""
super(output, self).__init__()
plt_helper.setup_mpl()
self.counter = 0
self.fig = None
self.ax = None
self.output_ratio = 1
def pre_run(self, step, level_number):
super(output, self).pre_step(step, level_number)
# some abbreviations
L = step.levels[0]
self.counter = 0
if self.counter % self.output_ratio == 0:
self.fig, self.ax = plt_helper.newfig(textwidth=238, scale=1.0, ratio=1.0)
im1 = self.ax.imshow(L.u[0], vmin=L.prob.params.rest, vmax=L.prob.params.depol)
self.fig.colorbar(im1, ax=self.ax)
fname = 'data/AC_' + L.prob.params.init_type + '_output_' + str(self.counter).zfill(8)
plt_helper.savefig(fname, save_pgf=False, save_pdf=False, save_png=True)
def post_step(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(output, self).post_step(step, level_number)
# some abbreviations
L = step.levels[0]
self.counter += 1
if self.counter % self.output_ratio == 0:
self.fig, self.ax = plt_helper.newfig(textwidth=238, scale=1.0, ratio=1.0)
im1 = self.ax.imshow(L.uend, vmin=L.prob.params.rest, vmax=L.prob.params.depol)
self.fig.colorbar(im1, ax=self.ax)
fname = 'data/AC_' + L.prob.params.init_type + '_output_' + str(self.counter).zfill(8)
plt_helper.savefig(fname, save_pgf=False, save_pdf=False, save_png=True)
| 1,861 | 32.25 | 98 | py |
pySDC | pySDC-master/pySDC/playgrounds/fft/AllenCahn_contracting_circle_FFT.py | import os
import dill
import matplotlib.ticker as ticker
import numpy as np
import pySDC.helpers.plot_helper as plt_helper
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AllenCahn_2D_FFT import allencahn2d_imex, allencahn2d_imex_stab
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferMesh_FFT2D import mesh_to_mesh_fft2d
from pySDC.projects.TOMS.AllenCahn_monitor import monitor
# http://www.personal.psu.edu/qud2/Res/Pre/dz09sisc.pdf
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 1e-03
level_params['nsweeps'] = [3, 1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU']
sweeper_params['QE'] = ['EE']
sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nu'] = 2
problem_params['L'] = 1.0
problem_params['nvars'] = [(256, 256), (64, 64)]
problem_params['eps'] = [0.04, 0.16]
problem_params['radius'] = 0.25
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
controller_params['hook_class'] = monitor
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = None # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = None # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fft2d
return description, controller_params
def run_SDC_variant(variant=None):
"""
Routine to run particular SDC variant
Args:
variant (str): string describing the variant
Returns:
timing (float)
niter (float)
"""
# load (incomplete) default parameters
description, controller_params = setup_parameters()
# add stuff based on variant
if variant == 'semi-implicit':
description['problem_class'] = allencahn2d_imex
description['sweeper_class'] = imex_1st_order
elif variant == 'semi-implicit-stab':
description['problem_class'] = allencahn2d_imex_stab
description['sweeper_class'] = imex_1st_order
else:
raise NotImplemented('Wrong variant specified, got %s' % variant)
# setup parameters "in time"
t0 = 0
Tend = 0.032
# instantiate controller
controller = controller_nonMPI(num_procs=8, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# plt_helper.plt.imshow(uinit)
# plt_helper.plt.show()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# plt_helper.plt.imshow(uend)
# plt_helper.plt.show()
# filter statistics by variant (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
print('Time to solution: %6.4f sec.' % timing[0][1])
print()
return stats
def show_results(fname, cwd=''):
"""
Plotting routine
Args:
fname (str): file name to read in and name plots
cwd (str): current working directory
"""
file = open(cwd + fname + '.pkl', 'rb')
results = dill.load(file)
file.close()
# plt_helper.mpl.style.use('classic')
plt_helper.setup_mpl()
# set up plot for timings
fig, ax1 = plt_helper.newfig(textwidth=238.96, scale=1.5, ratio=0.4)
timings = {}
niters = {}
for key, item in results.items():
timings[key] = get_sorted(item, type='timing_run', sortby='time')[0][1]
iter_counts = get_sorted(item, type='niter', sortby='time')
niters[key] = np.mean(np.array([item[1] for item in iter_counts]))
xcoords = [i for i in range(len(timings))]
sorted_timings = sorted([(key, timings[key]) for key in timings], reverse=True, key=lambda tup: tup[1])
sorted_niters = [(k, niters[k]) for k in [key[0] for key in sorted_timings]]
heights_timings = [item[1] for item in sorted_timings]
heights_niters = [item[1] for item in sorted_niters]
keys = [(item[0][1] + ' ' + item[0][0]).replace('-', '\n').replace('_v2', ' mod.') for item in sorted_timings]
ax1.bar(xcoords, heights_timings, align='edge', width=-0.3, label='timings (left axis)')
ax1.set_ylabel('time (sec)')
ax2 = ax1.twinx()
ax2.bar(xcoords, heights_niters, color='r', align='edge', width=0.3, label='iterations (right axis)')
ax2.set_ylabel('mean number of iterations')
ax1.set_xticks(xcoords)
ax1.set_xticklabels(keys, rotation=90, ha='center')
# ask matplotlib for the plotted objects and their labels
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)
# save plot, beautify
f = fname + '_timings'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
# set up plot for radii
fig, ax = plt_helper.newfig(textwidth=238.96, scale=1.0)
exact_radii = []
for key, item in results.items():
computed_radii = get_sorted(item, type='computed_radius', sortby='time')
xcoords = [item0[0] for item0 in computed_radii]
radii = [item0[1] for item0 in computed_radii]
if key[0] + ' ' + key[1] == 'semi-implicit-stab exact':
ax.plot(xcoords, radii, label=(key[0] + ' ' + key[1]).replace('_v2', ' mod.'))
exact_radii = get_sorted(item, type='exact_radius', sortby='time')
# diff = np.array([abs(item0[1] - item1[1]) for item0, item1 in zip(exact_radii, computed_radii)])
# max_pos = int(np.argmax(diff))
# assert max(diff) < 0.07, 'ERROR: computed radius is too far away from exact radius, got %s' % max(diff)
# assert 0.028 < computed_radii[max_pos][0] < 0.03, \
# 'ERROR: largest difference is at wrong time, got %s' % computed_radii[max_pos][0]
xcoords = [item[0] for item in exact_radii]
radii = [item[1] for item in exact_radii]
ax.plot(xcoords, radii, color='k', linestyle='--', linewidth=1, label='exact')
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
ax.set_ylabel('radius')
ax.set_xlabel('time')
ax.grid()
ax.legend(loc=3)
# save plot, beautify
f = fname + '_radii'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
# set up plot for interface width
fig, ax = plt_helper.newfig(textwidth=238.96, scale=1.0)
interface_width = []
for key, item in results.items():
interface_width = get_sorted(item, type='interface_width', sortby='time')
xcoords = [item[0] for item in interface_width]
width = [item[1] for item in interface_width]
if key[0] + ' ' + key[1] == 'fully-implicit exact':
ax.plot(xcoords, width, label=key[0] + ' ' + key[1])
xcoords = [item[0] for item in interface_width]
init_width = [interface_width[0][1]] * len(xcoords)
ax.plot(xcoords, init_width, color='k', linestyle='--', linewidth=1, label='exact')
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.2f'))
ax.set_ylabel(r'interface width ($\epsilon$)')
ax.set_xlabel('time')
ax.grid()
ax.legend(loc=3)
# save plot, beautify
f = fname + '_interface'
plt_helper.savefig(f)
assert os.path.isfile(f + '.pdf'), 'ERROR: plotting did not create PDF file'
# assert os.path.isfile(f + '.pgf'), 'ERROR: plotting did not create PGF file'
assert os.path.isfile(f + '.png'), 'ERROR: plotting did not create PNG file'
return None
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
# Loop over variants, exact and inexact solves
results = {}
for variant in ['semi-implicit-stab']:
results[(variant, 'exact')] = run_SDC_variant(variant=variant)
# dump result
fname = 'data/results_SDC_variants_AllenCahn_1E-03'
file = open(cwd + fname + '.pkl', 'wb')
dill.dump(results, file)
file.close()
assert os.path.isfile(cwd + fname + '.pkl'), 'ERROR: dill did not create file'
# visualize
show_results(fname, cwd=cwd)
if __name__ == "__main__":
main()
| 10,278 | 33.844068 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/fft/fft_in_time.py | from mpi4py import MPI
from mpi4py_fft import PFFT, newDistArray
from mpi4py_fft.pencil import Subcomm
import numpy as np
def main():
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
L = 16
N = 1
pfft = PFFT(comm, [L, N], axes=0, dtype=np.complex128, grid=(0, -1))
tmp_u = newDistArray(pfft, False)
# print(rank, tmp_u.shape)
Lloc = tmp_u.shape[0]
tvalues = np.linspace(rank * 1.0 / size, (rank + 1) * 1.0 / size, Lloc, endpoint=False)
print(tvalues)
u = np.zeros(tmp_u.shape)
for n in range(N):
u[:, n] = np.sin((n + 1) * 2 * np.pi * tvalues)
print(u)
print(pfft.forward(u))
if __name__ == '__main__':
main()
| 713 | 18.833333 | 91 | py |
pySDC | pySDC-master/pySDC/playgrounds/fft/playground_advdiff.py | import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AdvectionDiffusionEquation_1D_FFT import advectiondiffusion1d_implicit
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.transfer_classes.TransferMesh_FFT import mesh_to_mesh_fft
from pySDC.playgrounds.fft.libpfasst_output import libpfasst_output
def main():
"""
A simple test program to do PFASST runs for the heat equation
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-14
level_params['dt'] = 0.9 / 32
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = [5, 3, 2]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'spread'
sweeper_params['do_coll_update'] = False
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.02 # diffusion coefficient
problem_params['c'] = 1.0 # advection speed
problem_params['freq'] = -1 # frequency for the test value
problem_params['nvars'] = [256, 128, 64] # number of degrees of freedom for each level
problem_params['L'] = 1.0 # length of the interval [-L/2, L/2]
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 10
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = libpfasst_output
# fill description dictionary for easy step instantiation
description = dict()
# description['problem_class'] = advectiondiffusion1d_imex # pass problem class
description['problem_class'] = advectiondiffusion1d_implicit # pass problem class
description['problem_params'] = problem_params # pass problem parameters
# description['sweeper_class'] = imex_1st_order # pass sweeper
description['sweeper_class'] = generic_implicit # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fft # pass spatial transfer class
description['space_transfer_params'] = dict() # pass paramters for spatial transfer
# set time parameters
t0 = 0.0
Tend = level_params['dt']
num_proc = 1
# instantiate controller
controller = controller_nonMPI(num_procs=num_proc, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# print(controller.MS[0].levels[0].sweep.coll.Qmat)
# print(controller.MS[0].levels[0].sweep.QI)
# exit()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %2i' % item
print(out)
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
print('Error: %8.4e' % err)
if __name__ == "__main__":
main()
| 4,156 | 37.850467 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/fft/libpfasst_output.py | from pySDC.core.Hooks import hooks
class libpfasst_output(hooks):
def __init__(self):
"""
Initialization of Allen-Cahn monitoring
"""
super(libpfasst_output, self).__init__()
self.step_counter = 1
def pre_run(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(libpfasst_output, self).pre_run(step, level_number)
if step.status.slot == 0:
print()
print('--- BEGIN RUN OUTPUT')
def post_sweep(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(libpfasst_output, self).post_sweep(step, level_number)
# some abbreviations
L = step.levels[level_number]
L.sweep.compute_end_point()
uex = L.prob.u_exact(L.time + L.dt)
err = abs(uex - L.uend)
out = 'error: step: ' + str(step.status.slot + self.step_counter).zfill(3)
out += ' iter: ' + str(step.status.iter).zfill(3) + ' level: ' + str(level_number + 1).zfill(2)
out += ' error: % 10.7e' % err
out += ' res: %12.10e' % L.status.residual
print(out)
def post_predict(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(libpfasst_output, self).post_predict(step, level_number)
# some abbreviations
L = step.levels[level_number]
L.sweep.compute_end_point()
L.sweep.compute_residual()
uex = L.prob.u_exact(L.time + L.dt)
err = abs(uex - L.uend)
out = 'error: step: ' + str(step.status.slot + self.step_counter).zfill(3)
out += ' iter: ' + str(step.status.iter).zfill(3) + ' level: ' + str(level_number + 1).zfill(2)
out += ' error: % 10.7e' % err
out += ' res: %12.10e' % L.status.residual
print(out)
def post_step(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(libpfasst_output, self).post_step(step, level_number)
self.step_counter += 1
def post_run(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(libpfasst_output, self).post_run(step, level_number)
if step.status.slot == 0:
print('--- END RUN OUTPUT')
print()
| 2,990 | 28.613861 | 104 | py |
pySDC | pySDC-master/pySDC/playgrounds/fft/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/mpifft/grayscott.py | import numpy as np
from mpi4py import MPI
import matplotlib.pyplot as plt
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.sweeper_classes.multi_implicit import multi_implicit
from pySDC.implementations.problem_classes.GrayScott_MPIFFT import (
grayscott_imex_diffusion,
grayscott_imex_linear,
grayscott_mi_diffusion,
grayscott_mi_linear,
)
from pySDC.implementations.transfer_classes.TransferMesh_MPIFFT import fft_to_fft
def run_simulation(spectral=None, splitting_type=None, ml=None, num_procs=None):
"""
A test program to do SDC, MLSDC and PFASST runs for the 2D NLS equation
Args:
spectral (bool): run in real or spectral space
ml (bool): single or multiple levels
num_procs (int): number of parallel processors
"""
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-12
level_params['dt'] = 8e-00
level_params['nsweeps'] = [1]
level_params['residual_type'] = 'last_abs'
# initialize sweeper parameters
sweeper_params = dict()
# sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = [5]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['Q1'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['Q2'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['QE'] = ['EE'] # You can try PIC here, but PFASST doesn't like this..
sweeper_params['initial_guess'] = 'spread'
# initialize problem parameters
problem_params = dict()
if ml:
problem_params['nvars'] = [(128, 128), (32, 32)]
else:
problem_params['nvars'] = [(128, 128)]
problem_params['spectral'] = spectral
problem_params['comm'] = comm
problem_params['Du'] = 0.00002
problem_params['Dv'] = 0.00001
problem_params['A'] = 0.04
problem_params['B'] = 0.1
problem_params['newton_maxiter'] = 50
problem_params['newton_tol'] = 1e-11
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 100
step_params['errtol'] = 1e-09
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20 if rank == 0 else 99
# controller_params['predict_type'] = 'fine_only'
# fill description dictionary for easy step instantiation
description = dict()
description['problem_params'] = problem_params # pass problem parameters
if splitting_type == 'diffusion':
description['problem_class'] = grayscott_imex_diffusion
elif splitting_type == 'linear':
description['problem_class'] = grayscott_imex_linear
elif splitting_type == 'mi_diffusion':
description['problem_class'] = grayscott_mi_diffusion
elif splitting_type == 'mi_linear':
description['problem_class'] = grayscott_mi_linear
else:
raise NotImplementedError(f'splitting_type = {splitting_type} not implemented')
if splitting_type == 'mi_diffusion' or splitting_type == 'mi_linear':
description['sweeper_class'] = multi_implicit
else:
description['sweeper_class'] = imex_1st_order
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = fft_to_fft
# set time parameters
t0 = 0.0
Tend = 32
f = None
if rank == 0:
f = open('GS_out.txt', 'a')
out = f'Running with ml = {ml} and num_procs = {num_procs}...'
f.write(out + '\n')
print(out)
# instantiate controller
controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# plt.figure()
# plt.imshow(uinit[..., 0], vmin=0, vmax=1)
# plt.title('v')
# plt.colorbar()
# plt.figure()
# plt.imshow(uinit[..., 1], vmin=0, vmax=1)
# plt.title('v')
# plt.colorbar()
# plt.figure()
# plt.imshow(uinit[..., 0] + uinit[..., 1])
# plt.title('sum')
# plt.colorbar()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# plt.figure()
# plt.imshow(P.fft.backward(uend[..., 0]))#, vmin=0, vmax=1)
# # plt.imshow(np.fft.irfft2(uend[..., 0]))#, vmin=0, vmax=1)
# plt.title('u')
# plt.colorbar()
# plt.figure()
# plt.imshow(P.fft.backward(uend[..., 1]))#, vmin=0, vmax=1)
# # plt.imshow(np.fft.irfft2(uend[..., 1]))#, vmin=0, vmax=1)
# plt.title('v')
# plt.colorbar()
# # plt.figure()
# # plt.imshow(uend[..., 0] + uend[..., 1])
# # plt.title('sum')
# # plt.colorbar()
# plt.show()
# # exit()
if rank == 0:
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
niters = np.array([item[1] for item in iter_counts])
out = (
f' Min/Mean/Max number of iterations: '
f'{np.min(niters):4.2f} / {np.mean(niters):4.2f} / {np.max(niters):4.2f}'
)
f.write(out + '\n')
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
f.write(out + '\n')
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (
int(np.argmax(niters)),
int(np.argmin(niters)),
)
f.write(out + '\n')
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
f.write(out + '\n')
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
out = f'Time to solution: {timing[0][1]:6.4f} sec.'
f.write(out + '\n')
print(out)
f.write('\n')
print()
f.close()
def main():
"""
Little helper routine to run the whole thing
Note: This can also be run with "mpirun -np 2 python grayscott.py"
"""
# run_simulation(spectral=False, splitting_type='diffusion', ml=False, num_procs=1)
# run_simulation(spectral=True, splitting_type='diffusion', ml=False, num_procs=1)
# run_simulation(spectral=True, splitting_type='linear', ml=False, num_procs=1)
# run_simulation(spectral=False, splitting_type='diffusion', ml=True, num_procs=1)
# run_simulation(spectral=True, splitting_type='diffusion', ml=True, num_procs=1)
# run_simulation(spectral=False, splitting_type='diffusion', ml=True, num_procs=10)
# run_simulation(spectral=True, splitting_type='diffusion', ml=True, num_procs=10)
# run_simulation(spectral=False, splitting_type='mi_diffusion', ml=False, num_procs=1)
run_simulation(spectral=True, splitting_type='mi_diffusion', ml=False, num_procs=1)
# run_simulation(spectral=False, splitting_type='mi_linear', ml=False, num_procs=1)
# run_simulation(spectral=True, splitting_type='mi_linear', ml=False, num_procs=1)
if __name__ == "__main__":
main()
| 7,617 | 36.160976 | 120 | py |
pySDC | pySDC-master/pySDC/playgrounds/mpifft/AC_benchmark.py | import sys
import numpy as np
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.problem_classes.AllenCahn_MPIFFT import allencahn_imex_timeforcing
from pySDC.projects.AllenCahn_Bayreuth.AllenCahn_dump import dump
from pySDC.implementations.transfer_classes.TransferMesh_MPIFFT import fft_to_fft
def run_simulation(name=''):
"""
A simple test program to do PFASST runs for the AC equation
"""
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
# split world communicator to create space-communicators
if len(sys.argv) >= 2:
color = int(world_rank / int(sys.argv[1]))
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
# space_size = space_comm.Get_size()
space_rank = space_comm.Get_rank()
# split world communicator to create time-communicators
if len(sys.argv) >= 2:
color = int(world_rank % int(sys.argv[1]))
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
# time_size = time_comm.Get_size()
time_rank = time_comm.Get_rank()
# print("IDs (world, space, time): %i / %i -- %i / %i -- %i / %i" % (world_rank, world_size, space_rank,
# space_size, time_rank, time_size))
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 1e-03
level_params['nsweeps'] = [3, 1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['L'] = 1.0
problem_params['nvars'] = [(128, 128), (32, 32)]
problem_params['eps'] = [0.04]
problem_params['dw'] = [-23.6]
problem_params['radius'] = 0.25
problem_params['comm'] = space_comm
problem_params['name'] = name
problem_params['init_type'] = 'circle'
problem_params['spectral'] = False
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20 if space_rank == 0 else 99 # set level depending on rank
controller_params['hook_class'] = dump
# fill description dictionary for easy step instantiation
description = dict()
# description['problem_class'] = allencahn_imex
description['problem_class'] = allencahn_imex_timeforcing
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = fft_to_fft
# set time parameters
t0 = 0.0
Tend = 32 * 0.001
# instantiate controller
controller = controller_MPI(controller_params=controller_params, description=description, comm=time_comm)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
if space_rank == 0:
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
print()
niters = np.array([item[1] for item in iter_counts])
out = f'Mean number of iterations on rank {time_rank}: {np.mean(niters):.4f}'
print(out)
timing = get_sorted(stats, type='timing_setup', sortby='time')
out = f'Setup time on rank {time_rank}: {timing[0][1]:.4f} sec.'
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
out = f'Time to solution on rank {time_rank}: {timing[0][1]:.4f} sec.'
print(out)
print()
# convert filtered statistics to list of computed radii, sorted by time
computed_radii = get_sorted(stats, type='computed_radius', sortby='time')
exact_radii = get_sorted(stats, type='exact_radius', sortby='time')
# print radii and error over time
for cr, er in zip(computed_radii, exact_radii):
if er[1] > 0:
err = abs(cr[1] - er[1]) / er[1]
else:
err = 1.0
out = f'Computed/exact/error radius for time {cr[0]:6.4f}: ' f'{cr[1]:6.4f} / {er[1]:6.4f} / {err:6.4e}'
print(out)
if __name__ == "__main__":
name = 'AC-test-constforce'
run_simulation(name=name)
| 5,159 | 34.833333 | 116 | py |
pySDC | pySDC-master/pySDC/playgrounds/mpifft/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/mpifft/playground.py | import numpy as np
from mpi4py import MPI
from mpi4py_fft import PFFT, newDistArray, DistArray
import time
import copy as cp
def get_local_mesh(FFT, L):
"""Returns local mesh."""
X = np.ogrid[FFT.local_slice(False)]
N = FFT.global_shape()
for i in range(len(N)):
X[i] = X[i] * L[i] / N[i]
X = [np.broadcast_to(x, FFT.shape(False)) for x in X]
return X
def get_local_wavenumbermesh(FFT, L):
"""Returns local wavenumber mesh."""
s = FFT.local_slice()
N = FFT.global_shape()
# Set wavenumbers in grid
k = [np.fft.fftfreq(n, 1.0 / n).astype(int) for n in N[:-1]]
k.append(np.fft.rfftfreq(N[-1], 1.0 / N[-1]).astype(int))
K = [ki[si] for ki, si in zip(k, s)]
Ks = np.meshgrid(*K, indexing='ij', sparse=True)
Lp = 2 * np.pi / L
for i in range(ndim):
Ks[i] = (Ks[i] * Lp[i]).astype(float)
return [np.broadcast_to(k, FFT.shape(True)) for k in Ks]
comm = MPI.COMM_WORLD
subcomm = comm.Split()
print(subcomm)
nvars = 8
ndim = 2
axes = tuple(range(ndim))
N = np.array([nvars] * ndim, dtype=int)
print(N, axes)
fft = PFFT(subcomm, N, axes=axes, dtype=np.float, slab=True)
# L = np.array([2*np.pi] * ndim, dtype=float)
L = np.array([1] * ndim, dtype=float)
print(fft.subcomm)
X = get_local_mesh(fft, L)
K = get_local_wavenumbermesh(fft, L)
K = np.array(K).astype(float)
K2 = np.sum(K * K, 0, dtype=float)
u = newDistArray(fft, False)
print(type(u))
print(u.subcomm)
uex = newDistArray(fft, False)
u[:] = np.sin(2 * np.pi * X[0]) * np.sin(2 * np.pi * X[1])
print(u.shape, X[0].shape)
# exit()
uex[:] = -2.0 * (2.0 * np.pi) ** 2 * np.sin(2 * np.pi * X[0]) * np.sin(2 * np.pi * X[1])
u_hat = fft.forward(u)
lap_u_hat = -K2 * u_hat
lap_u = np.zeros_like(u)
lap_u = fft.backward(lap_u_hat, lap_u)
local_error = np.amax(abs(lap_u - uex))
err = MPI.COMM_WORLD.allreduce(local_error, MPI.MAX)
print('Laplace error:', err)
ratio = 2
Nc = np.array([nvars // ratio] * ndim, dtype=int)
fftc = PFFT(MPI.COMM_WORLD, Nc, axes=axes, dtype=np.float, slab=True)
print(Nc, fftc.global_shape())
Xc = get_local_mesh(fftc, L)
uex = newDistArray(fft, False)
uexc = newDistArray(fftc, False)
r2 = (X[0] - 0.5) ** 2 + (X[1] - 0.5) ** 2
uex[:] = 0.5 * (1.0 + np.tanh((0.25 - np.sqrt(r2)) / (np.sqrt(2) * 0.04)))
r2c = (Xc[0] - 0.5) ** 2 + (Xc[1] - 0.5) ** 2
uexc[:] = 0.5 * (1.0 + np.tanh((0.25 - np.sqrt(r2c)) / (np.sqrt(2) * 0.04)))
uc = uex[::ratio, ::ratio]
local_error = np.amax(abs(uc - uexc))
err = MPI.COMM_WORLD.allreduce(local_error, MPI.MAX)
print('Restriction error real:', err)
uexcs = fftc.forward(uexc)
uc = uex[::ratio, ::ratio]
ucs = fftc.forward(uc)
local_error = np.amax(abs(ucs - uexcs))
err = MPI.COMM_WORLD.allreduce(local_error, MPI.MAX)
print('Restriction error spectral:', err)
uexc_hat = fftc.forward(uexc)
fft_pad = PFFT(MPI.COMM_WORLD, Nc, padding=[ratio] * ndim, axes=axes, dtype=np.float, slab=True)
uf = newDistArray(fft_pad, False)
uf = fft_pad.backward(uexc_hat, uf)
local_error = np.amax(abs(uf - uex))
err = MPI.COMM_WORLD.allreduce(local_error, MPI.MAX)
print('Interpolation error real:', err)
uexs = fft.forward(uex)
fft_pad = PFFT(MPI.COMM_WORLD, Nc, padding=[ratio] * ndim, axes=axes, dtype=np.float, slab=True)
# uf = fft_pad.backward(uexc_hat)
# ufs = fft.forward(uf)
ufs = np.pad(uexc_hat, [(0, Nc[0]), (0, Nc[1] // 2)], mode='constant')
# ufs[:][0] *= 2
print(uexc_hat[1])
print(uexs[1])
print(uexc_hat.shape, ufs.shape, uexs.shape)
local_error = np.amax(abs(ufs / 4 - uexs))
err = MPI.COMM_WORLD.allreduce(local_error, MPI.MAX)
print('Interpolation error spectral:', err)
exit()
u = newDistArray(fft, False)
ucopy = u.copy()
print(type(u), type(ucopy), u is ucopy)
u[0] = 1
print(ucopy[0, 0])
print(np.all(u == ucopy))
nruns = 30000
s = 0
t0 = time.perf_counter()
for i in range(nruns):
u = newDistArray(fft, False, val=i)
v = u.copy()
u[0][0] = 0
# print(u[0][0], v[0][0])
s += u[0][0] - v[0][0]
t1 = time.perf_counter()
print(s + nruns * (nruns - 1) / 2, t1 - t0)
s = 0
t0 = time.perf_counter()
for i in range(nruns):
u = np.full((nvars, nvars), fill_value=i, dtype=np.float64)
# u = np.empty((nvars, nvars), dtype=np.float64)
# u[:] = i
v = u.copy()
# v = cp.deepcopy(u)
u[0][0] = 0
# print(u[0][0], v[0][0])
s += u[0][0] - v[0][0]
t1 = time.perf_counter()
print(s + nruns * (nruns - 1) / 2, t1 - t0)
| 4,368 | 27.743421 | 96 | py |
pySDC | pySDC-master/pySDC/tutorial/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/tutorial/step_3/C_study_collocations.py | from pathlib import Path
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.PenningTrap_3D import penningtrap
from pySDC.implementations.sweeper_classes.boris_2nd_order import boris_2nd_order
from pySDC.tutorial.step_3.HookClass_Particles import particle_hook
def main():
"""
A simple test program to show the energy deviation for different quadrature nodes
"""
stats_dict = run_simulation()
ediff = dict()
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_3_C_out.txt', 'w')
for cclass, stats in stats_dict.items():
# filter and convert/sort statistics by etot and iterations
energy = get_sorted(stats, type='etot', sortby='iter')
# compare base and final energy
base_energy = energy[0][1]
final_energy = energy[-1][1]
ediff[cclass] = abs(base_energy - final_energy)
out = "Energy deviation for %s: %12.8e" % (cclass, ediff[cclass])
f.write(out + '\n')
print(out)
f.close()
# set expected differences and check
ediff_expect = dict()
ediff_expect['RADAU-RIGHT'] = 15
ediff_expect['LOBATTO'] = 1e-05
ediff_expect['GAUSS'] = 3e-05
for k, v in ediff.items():
assert v < ediff_expect[k], "ERROR: energy deviated too much, got %s" % ediff[k]
def run_simulation():
"""
A simple test program to run IMEX SDC for a single time step
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-06
level_params['dt'] = 1.0 / 16
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['num_nodes'] = 3
# initialize problem parameters
problem_params = dict()
problem_params['omega_E'] = 4.9
problem_params['omega_B'] = 25.0
problem_params['u0'] = np.array([[10, 0, 0], [100, 0, 100], [1], [1]], dtype=object)
problem_params['nparts'] = 1
problem_params['sig'] = 0.1
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['hook_class'] = particle_hook # specialized hook class for more statistics and output
controller_params['logger_level'] = 30 # reduce verbosity of each run
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = penningtrap
description['problem_params'] = problem_params
description['sweeper_class'] = boris_2nd_order
description['level_params'] = level_params
description['step_params'] = step_params
# assemble and loop over list of collocation classes
quad_types = ['RADAU-RIGHT', 'GAUSS', 'LOBATTO']
stats_dict = dict()
for qtype in quad_types:
sweeper_params['quad_type'] = qtype
description['sweeper_params'] = sweeper_params
# instantiate the controller (no controller parameters used here)
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.0
Tend = level_params['dt']
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_init()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# gather stats in dictionary, collocation classes being the keys
stats_dict[qtype] = stats
return stats_dict
if __name__ == "__main__":
main()
| 3,691 | 33.185185 | 113 | py |
pySDC | pySDC-master/pySDC/tutorial/step_3/HookClass_Particles.py | import numpy as np
from pySDC.core.Hooks import hooks
class particle_hook(hooks):
def __init__(self):
"""
Initialization of particles output
"""
super(particle_hook, self).__init__()
def pre_run(self, step, level_number):
"""
Overwrite default routine called before time-loop starts
Args:
step: the current step
level_number: the current level number
"""
super(particle_hook, self).pre_run(step, level_number)
# some abbreviations
L = step.levels[level_number]
part = L.u[0]
N = L.prob.nparts
w = np.array([1, 1, -2])
# compute (slowly..) the potential at u0
fpot = np.zeros(N)
for i in range(N):
# inner loop, omit ith particle
for j in range(0, i):
dist2 = np.linalg.norm(part.pos[:, i] - part.pos[:, j], 2) ** 2 + L.prob.sig**2
fpot[i] += part.q[j] / np.sqrt(dist2)
for j in range(i + 1, N):
dist2 = np.linalg.norm(part.pos[:, i] - part.pos[:, j], 2) ** 2 + L.prob.sig**2
fpot[i] += part.q[j] / np.sqrt(dist2)
fpot[i] -= L.prob.omega_E**2 * part.m[i] / part.q[i] / 2.0 * np.dot(w, part.pos[:, i] * part.pos[:, i])
# add up kinetic and potntial contributions to total energy
epot = 0
ekin = 0
for n in range(N):
epot += part.q[n] * fpot[n]
ekin += part.m[n] / 2.0 * np.dot(part.vel[:, n], part.vel[:, n])
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=0,
sweep=L.status.sweep,
type='etot',
value=epot + ekin,
)
def post_step(self, step, level_number):
"""
Default routine called after each iteration
Args:
step: the current step
level_number: the current level number
"""
super(particle_hook, self).post_step(step, level_number)
# some abbreviations
L = step.levels[level_number]
L.sweep.compute_end_point()
part = L.uend
N = L.prob.nparts
w = np.array([1, 1, -2])
# compute (slowly..) the potential at uend
fpot = np.zeros(N)
for i in range(N):
# inner loop, omit ith particle
for j in range(0, i):
dist2 = np.linalg.norm(part.pos[:, i] - part.pos[:, j], 2) ** 2 + L.prob.sig**2
fpot[i] += part.q[j] / np.sqrt(dist2)
for j in range(i + 1, N):
dist2 = np.linalg.norm(part.pos[:, i] - part.pos[:, j], 2) ** 2 + L.prob.sig**2
fpot[i] += part.q[j] / np.sqrt(dist2)
fpot[i] -= L.prob.omega_E**2 * part.m[i] / part.q[i] / 2.0 * np.dot(w, part.pos[:, i] * part.pos[:, i])
# add up kinetic and potntial contributions to total energy
epot = 0
ekin = 0
for n in range(N):
epot += part.q[n] * fpot[n]
ekin += part.m[n] / 2.0 * np.dot(part.vel[:, n], part.vel[:, n])
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='etot',
value=epot + ekin,
)
return None
| 3,432 | 32.009615 | 115 | py |
pySDC | pySDC-master/pySDC/tutorial/step_3/B_adding_statistics.py | import numpy as np
from pathlib import Path
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.PenningTrap_3D import penningtrap
from pySDC.implementations.sweeper_classes.boris_2nd_order import boris_2nd_order
from pySDC.tutorial.step_3.HookClass_Particles import particle_hook
def main():
"""
A simple test program to retrieve user-defined statistics from a run
"""
Path("data").mkdir(parents=True, exist_ok=True)
err, stats = run_penning_trap_simulation()
# filter statistics type (etot)
energy = get_sorted(stats, type='etot', sortby='iter')
# get base energy and show difference
base_energy = energy[0][1]
f = open('data/step_3_B_out.txt', 'a')
for item in energy:
out = 'Total energy and deviation in iteration %2i: %12.10f -- %12.8e' % (
item[0],
item[1],
abs(base_energy - item[1]),
)
f.write(out + '\n')
print(out)
f.close()
assert abs(base_energy - energy[-1][1]) < 15, 'ERROR: energy deviated too much, got %s' % (
base_energy - energy[-1][1]
)
assert err < 5e-04, "ERROR: solution is not as exact as expected, got %s" % err
def run_penning_trap_simulation():
"""
A simple test program to run IMEX SDC for a single time step of the penning trap example
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 1.0 / 16
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
# initialize problem parameters for the Penning trap
problem_params = dict()
problem_params['omega_E'] = 4.9 # E-field frequency
problem_params['omega_B'] = 25.0 # B-field frequency
problem_params['u0'] = np.array([[10, 0, 0], [100, 0, 100], [1], [1]], dtype=object) # initial center of positions
problem_params['nparts'] = 1 # number of particles in the trap
problem_params['sig'] = 0.1 # smoothing parameter for the forces
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['hook_class'] = particle_hook # specialized hook class for more statistics and output
controller_params['log_to_file'] = True
controller_params['fname'] = 'data/step_3_B_out.txt'
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = penningtrap
description['problem_params'] = problem_params
description['sweeper_class'] = boris_2nd_order
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
# instantiate the controller (no controller parameters used here)
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.0
Tend = level_params['dt']
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_init()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute error compared to know exact solution for one particle
uex = P.u_exact(Tend)
err = np.linalg.norm(uex.pos - uend.pos, np.inf) / np.linalg.norm(uex.pos, np.inf)
return err, stats
if __name__ == "__main__":
main()
| 3,657 | 33.509434 | 119 | py |
pySDC | pySDC-master/pySDC/tutorial/step_3/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/tutorial/step_3/A_getting_statistics.py | from pathlib import Path
from pySDC.helpers.stats_helper import get_list_of_types, get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_forced
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
def main():
"""
A simple test program to describe how to get statistics of a run
"""
# run simulation
stats = run_simulation()
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_3_A_out.txt', 'w')
out = 'List of registered statistic types: %s' % get_list_of_types(stats)
f.write(out + '\n')
print(out)
# filter statistics by first time interval and type (residual)
residuals = get_sorted(stats, time=0.1, type='residual_post_iteration', sortby='iter')
for item in residuals:
out = 'Residual in iteration %2i: %8.4e' % item
f.write(out + '\n')
print(out)
# get and convert filtered statistics to list of iterations count, sorted by time
# the get_sorted function is just a shortcut for sort_stats(filter_stats()) with all the same arguments
iter_counts = get_sorted(stats, type='niter', sortby='time')
for item in iter_counts:
out = 'Number of iterations at time %4.2f: %2i' % item
f.write(out + '\n')
print(out)
f.close()
assert all(item[1] == 12 for item in iter_counts), (
'ERROR: number of iterations are not as expected, got %s' % iter_counts
)
def run_simulation():
"""
A simple test program to run IMEX SDC for a single time step
"""
# initialize level parameters
level_params = {}
level_params['restol'] = 1e-10
level_params['dt'] = 0.1
# initialize sweeper parameters
sweeper_params = {}
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
# initialize problem parameters
problem_params = {}
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['nvars'] = 1023 # number of degrees of freedom
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = {}
step_params['maxiter'] = 20
# initialize controller parameters (<-- this is new!)
controller_params = {}
controller_params['logger_level'] = 30 # reduce verbosity of each run
# Fill description dictionary for easy hierarchy creation
description = {}
description['problem_class'] = heatNd_forced
description['problem_params'] = problem_params
description['sweeper_class'] = imex_1st_order
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
# instantiate the controller (no controller parameters used here)
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.1
Tend = 0.9
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
return stats
if __name__ == "__main__":
main()
| 3,380 | 31.2 | 109 | py |
pySDC | pySDC-master/pySDC/tutorial/step_4/PenningTrap_3D_coarse.py | import numpy as np
from pySDC.implementations.problem_classes.PenningTrap_3D import penningtrap
class penningtrap_coarse(penningtrap):
"""
Coarse level problem description class, will only overwrite what is needed
"""
def eval_f(self, part, t):
"""
Routine to compute the E and B fields (named f for consistency with the original PEPC version)
Args:
t: current time (not used here)
part: the particles
Returns:
Fields for the particles (external only)
"""
N = self.nparts
Emat = np.diag([1, 1, -2])
f = self.dtype_f(self.init, val=0.0)
# only compute external forces here: O(N) instead of O(N*N)
for n in range(N):
f.elec[:, n] = self.omega_E**2 / (part.q[n] / part.m[n]) * np.dot(Emat, part.pos[:, n])
f.magn[:, n] = self.omega_B * np.array([0, 0, 1])
return f
| 935 | 27.363636 | 102 | py |
pySDC | pySDC-master/pySDC/tutorial/step_4/B_multilevel_hierarchy.py | from pathlib import Path
from pySDC.core.Step import step
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
def main():
"""
A simple test program to set up a full step hierarchy
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [5, 3]
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['nvars'] = [31, 15, 7] # number of degrees of freedom for each level
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 2
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_unforced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_LU # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass parameters for spatial transfer
# now the description contains more or less everything we need to create a step with multiple levels
S = step(description=description)
# print out and check
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_4_B_out.txt', 'w')
for l in range(len(S.levels)):
L = S.levels[l]
out = 'Level %2i: nvars = %4i -- nnodes = %2i' % (l, L.prob.nvars[0], L.sweep.coll.num_nodes)
f.write(out + '\n')
print(out)
assert L.prob.nvars[0] == problem_params['nvars'][min(l, len(problem_params['nvars']) - 1)], (
"ERROR: number of DOFs is not correct on this level, got %s" % L.prob.nvars
)
assert L.sweep.coll.num_nodes == sweeper_params['num_nodes'][min(l, len(sweeper_params['num_nodes']) - 1)], (
"ERROR: number of nodes is not correct on this level, got %s" % L.sweep.coll.num_nodes
)
f.close()
if __name__ == "__main__":
main()
| 2,931 | 38.621622 | 117 | py |
pySDC | pySDC-master/pySDC/tutorial/step_4/C_SDC_vs_MLSDC.py | from pathlib import Path
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
def main():
"""
A simple test program to compare SDC and MLSDC
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-09
level_params['dt'] = 0.1
# initialize sweeper parameters
sweeper_params_sdc = dict()
sweeper_params_sdc['node_type'] = 'LEGENDRE'
sweeper_params_sdc['quad_type'] = 'RADAU-RIGHT'
sweeper_params_sdc['num_nodes'] = 5
sweeper_params_mlsdc = dict()
sweeper_params_mlsdc['node_type'] = 'LEGENDRE'
sweeper_params_mlsdc['quad_type'] = 'RADAU-RIGHT'
sweeper_params_mlsdc['num_nodes'] = [5, 3, 2]
# initialize problem parameters
problem_params_sdc = dict()
problem_params_sdc['nu'] = 0.1 # diffusion coefficient
problem_params_sdc['freq'] = 4 # frequency for the test value
problem_params_sdc['nvars'] = 1023 # number of degrees of freedom for each level
problem_params_sdc['bc'] = 'dirichlet-zero' # boundary conditions
problem_params_mlsdc = dict()
problem_params_mlsdc['nu'] = 0.1 # diffusion coefficient
problem_params_mlsdc['freq'] = 4 # frequency for the test value
problem_params_mlsdc['nvars'] = [1023, 511, 255] # number of degrees of freedom for each level
problem_params_mlsdc['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
# fill description dictionary for SDC
description_sdc = dict()
description_sdc['problem_class'] = heatNd_unforced # pass problem class
description_sdc['problem_params'] = problem_params_sdc # pass problem parameters
description_sdc['sweeper_class'] = generic_LU # pass sweeper (see part B)
description_sdc['sweeper_params'] = sweeper_params_sdc # pass sweeper parameters
description_sdc['level_params'] = level_params # pass level parameters
description_sdc['step_params'] = step_params # pass step parameters
# fill description dictionary for MLSDC
description_mlsdc = dict()
description_mlsdc['problem_class'] = heatNd_unforced # pass problem class
description_mlsdc['problem_params'] = problem_params_mlsdc # pass problem parameters
description_mlsdc['sweeper_class'] = generic_LU # pass sweeper (see part B)
description_mlsdc['sweeper_params'] = sweeper_params_mlsdc # pass sweeper parameters
description_mlsdc['level_params'] = level_params # pass level parameters
description_mlsdc['step_params'] = step_params # pass step parameters
description_mlsdc['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description_mlsdc['space_transfer_params'] = space_transfer_params # pass parameters for spatial transfer
# instantiate the controller (no controller parameters used here)
controller_sdc = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description_sdc)
controller_mlsdc = controller_nonMPI(
num_procs=1, controller_params=controller_params, description=description_mlsdc
)
# set time parameters
t0 = 0.0
Tend = 0.1
# get initial values on finest level
P = controller_sdc.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main functions to get things done...
uend_sdc, stats_sdc = controller_sdc.run(u0=uinit, t0=t0, Tend=Tend)
uend_mlsdc, stats_mlsdc = controller_mlsdc.run(u0=uinit, t0=t0, Tend=Tend)
# get number of iterations for both
niter_sdc = get_sorted(stats_sdc, type='niter', sortby='time')[0][1]
niter_mlsdc = get_sorted(stats_mlsdc, type='niter', sortby='time')[0][1]
# compute exact solution and compare both
uex = P.u_exact(Tend)
err_sdc = abs(uex - uend_sdc)
err_mlsdc = abs(uex - uend_mlsdc)
diff = abs(uend_mlsdc - uend_sdc)
# print out and check
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_4_C_out.txt', 'a')
out = 'Error SDC and MLSDC: %12.8e -- %12.8e' % (err_sdc, err_mlsdc)
f.write(out + '\n')
print(out)
out = 'Difference SDC vs. MLSDC: %12.8e' % diff
f.write(out + '\n')
print(out)
out = 'Number of iterations SDC and MLSDC: %2i -- %2i' % (niter_sdc, niter_mlsdc)
f.write(out + '\n')
print(out)
assert diff < 6e-10, "ERROR: difference between MLSDC and SDC is higher than expected, got %s" % diff
assert niter_sdc - niter_mlsdc <= 6, "ERROR: MLSDC required more iterations than expected, got %s" % niter_mlsdc
if __name__ == "__main__":
main()
| 5,164 | 40.32 | 117 | py |
pySDC | pySDC-master/pySDC/tutorial/step_4/D_MLSDC_with_particles.py | import time
from pathlib import Path
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.PenningTrap_3D import penningtrap
from pySDC.implementations.sweeper_classes.boris_2nd_order import boris_2nd_order
from pySDC.implementations.transfer_classes.TransferParticles_NoCoarse import particles_to_particles
from pySDC.tutorial.step_3.HookClass_Particles import particle_hook
from pySDC.tutorial.step_4.PenningTrap_3D_coarse import penningtrap_coarse
def main():
"""
A simple test program to compare SDC with two flavors of MLSDC for particle dynamics
"""
# run SDC, MLSDC and MLSDC plus f-interpolation and compare
stats_sdc, time_sdc = run_penning_trap_simulation(mlsdc=False)
stats_mlsdc, time_mlsdc = run_penning_trap_simulation(mlsdc=True)
stats_mlsdc_finter, time_mlsdc_finter = run_penning_trap_simulation(mlsdc=True, finter=True)
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_4_D_out.txt', 'w')
out = 'Timings for SDC, MLSDC and MLSDC+finter: %12.8f -- %12.8f -- %12.8f' % (
time_sdc,
time_mlsdc,
time_mlsdc_finter,
)
f.write(out + '\n')
print(out)
# sort and convert stats to list, sorted by iteration numbers (only pre- and after-step are present here)
energy_sdc = get_sorted(stats_sdc, type='etot', sortby='iter')
energy_mlsdc = get_sorted(stats_mlsdc, type='etot', sortby='iter')
energy_mlsdc_finter = get_sorted(stats_mlsdc_finter, type='etot', sortby='iter')
# get base energy and show differences
base_energy = energy_sdc[0][1]
for item in energy_sdc:
out = 'Total energy and relative deviation in iteration %2i: %12.10f -- %12.8e' % (
item[0],
item[1],
abs(base_energy - item[1]) / base_energy,
)
f.write(out + '\n')
print(out)
for item in energy_mlsdc:
out = 'Total energy and relative deviation in iteration %2i: %12.10f -- %12.8e' % (
item[0],
item[1],
abs(base_energy - item[1]) / base_energy,
)
f.write(out + '\n')
print(out)
for item in energy_mlsdc_finter:
out = 'Total energy and relative deviation in iteration %2i: %12.10f -- %12.8e' % (
item[0],
item[1],
abs(base_energy - item[1]) / base_energy,
)
f.write(out + '\n')
print(out)
f.close()
assert (
abs(energy_sdc[-1][1] - energy_mlsdc[-1][1]) / base_energy < 6e-10
), 'ERROR: energy deviated too much between SDC and MLSDC, got %s' % (
abs(energy_sdc[-1][1] - energy_mlsdc[-1][1]) / base_energy
)
assert (
abs(energy_mlsdc[-1][1] - energy_mlsdc_finter[-1][1]) / base_energy < 8e-10
), 'ERROR: energy deviated too much after using finter, got %s' % (
abs(energy_mlsdc[-1][1] - energy_mlsdc_finter[-1][1]) / base_energy
)
def run_penning_trap_simulation(mlsdc, finter=False):
"""
A simple test program to run IMEX SDC for a single time step
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-07
level_params['dt'] = 1.0 / 8
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 5
# initialize problem parameters for the Penning trap
problem_params = dict()
problem_params['omega_E'] = 4.9 # E-field frequency
problem_params['omega_B'] = 25.0 # B-field frequency
problem_params['u0'] = np.array([[10, 0, 0], [100, 0, 100], [1], [1]], dtype=object) # initial center of positions
problem_params['nparts'] = 50 # number of particles in the trap
problem_params['sig'] = 0.1 # smoothing parameter for the forces
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['hook_class'] = particle_hook # specialized hook class for more statistics and output
controller_params['logger_level'] = 30
transfer_params = dict()
transfer_params['finter'] = finter
# Fill description dictionary for easy hierarchy creation
description = dict()
if mlsdc:
# MLSDC: provide list of two problem classes: one for the fine, one for the coarse level
description['problem_class'] = [penningtrap, penningtrap_coarse]
else:
# SDC: provide only one problem class
description['problem_class'] = penningtrap
description['problem_params'] = problem_params
description['sweeper_class'] = boris_2nd_order
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
description['space_transfer_class'] = particles_to_particles
description['base_transfer_params'] = transfer_params
# instantiate the controller (no controller parameters used here)
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.0
Tend = level_params['dt']
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_init()
# call and time main function to get things done...
start_time = time.perf_counter()
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
end_time = time.perf_counter() - start_time
return stats, end_time
if __name__ == "__main__":
main()
| 5,685 | 36.407895 | 119 | py |
pySDC | pySDC-master/pySDC/tutorial/step_4/A_spatial_transfer_operators.py | from collections import namedtuple
from pathlib import Path
import numpy as np
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
from pySDC.tutorial.step_1.B_spatial_accuracy_check import get_accuracy_order
# setup id for gathering the results (will sort by nvars)
ID = namedtuple('ID', 'nvars_fine')
def main():
"""
A simple test program to test interpolation order in space
"""
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 3 # frequency for the test value
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 4
nvars_fine_list = [2**p - 1 for p in range(5, 10)]
# set up dictionary to store results (plus lists)
results = dict()
results['nvars_list'] = nvars_fine_list
for nvars_fine in nvars_fine_list:
print('Working on nvars_fine = %4i...' % nvars_fine)
# instantiate fine problem
problem_params['nvars'] = nvars_fine # number of degrees of freedom
Pfine = heatNd_unforced(**problem_params)
# instantiate coarse problem using half of the DOFs
problem_params['nvars'] = int((nvars_fine + 1) / 2.0 - 1)
Pcoarse = heatNd_unforced(**problem_params)
# instantiate spatial interpolation
T = mesh_to_mesh(fine_prob=Pfine, coarse_prob=Pcoarse, params=space_transfer_params)
# set exact fine solution to compare with
xvalues_fine = np.array([(i + 1) * Pfine.dx for i in range(Pfine.nvars[0])])
uexact_fine = Pfine.dtype_u(Pfine.init)
uexact_fine[:] = np.sin(np.pi * Pfine.freq[0] * xvalues_fine)
# set exact coarse solution as source
xvalues_coarse = np.array([(i + 1) * Pcoarse.dx for i in range(Pcoarse.nvars[0])])
uexact_coarse = Pfine.dtype_u(Pcoarse.init)
uexact_coarse[:] = np.sin(np.pi * Pcoarse.freq[0] * xvalues_coarse)
# do the interpolation/prolongation
uinter = T.prolong(uexact_coarse)
# compute error and store
id = ID(nvars_fine=nvars_fine)
results[id] = abs(uinter - uexact_fine)
# print out and check
print('Running order checks...')
orders = get_accuracy_order(results)
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_4_A_out.txt', 'w')
for p in range(len(orders)):
out = 'Expected order %2i, got order %5.2f, deviation of %5.2f%%' % (
space_transfer_params['iorder'],
orders[p],
100 * abs(space_transfer_params['iorder'] - orders[p]) / space_transfer_params['iorder'],
)
f.write(out + '\n')
print(out)
assert (
abs(space_transfer_params['iorder'] - orders[p]) / space_transfer_params['iorder'] < 0.05
), 'ERROR: did not get expected orders for interpolation, got %s' % str(orders[p])
f.close()
print('...got what we expected!')
if __name__ == "__main__":
main()
| 3,239 | 35.404494 | 101 | py |
pySDC | pySDC-master/pySDC/tutorial/step_4/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/tutorial/step_5/C_advection_and_PFASST.py | from pathlib import Path
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.AdvectionEquation_ND_FD import advectionNd
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
def main():
"""
A simple test program to run PFASST for the advection equation in multiple ways...
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-09
level_params['dt'] = 0.0625
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
# initialize problem parameters
problem_params = dict()
problem_params['c'] = 1 # advection coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['nvars'] = [128, 64] # number of degrees of freedom for each level
problem_params['order'] = 4
problem_params['bc'] = 'periodic'
problem_params['stencil_type'] = 'center'
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
space_transfer_params['periodic'] = True
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['predict_type'] = 'pfasst_burnin'
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = advectionNd # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit # pass sweeper (see part B)
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass parameters for spatial transfer
# set time parameters
t0 = 0.0
Tend = 1.0
# set up list of parallel time-steps to run PFASST with
nsteps = int(Tend / level_params['dt'])
num_proc_list = [2**i for i in range(int(np.log2(nsteps) + 1))]
# set up list of types of implicit SDC sweepers: LU and implicit Euler here
QI_list = ['LU', 'IE']
niters_min_all = {}
niters_max_all = {}
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_5_C_out.txt', 'w')
# loop over different types of implicit sweeper types
for QI in QI_list:
# define and set preconditioner for the implicit sweeper
sweeper_params['QI'] = QI
description['sweeper_params'] = sweeper_params # pass sweeper parameters
# init min/max iteration counts
niters_min_all[QI] = 99
niters_max_all[QI] = 0
# loop over different number of processes
for num_proc in num_proc_list:
out = 'Working with QI = %s on %2i processes...' % (QI, num_proc)
f.write(out + '\n')
print(out)
# instantiate controller
controller = controller_nonMPI(
num_procs=num_proc, controller_params=controller_params, description=description
)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
niters_min_all[QI] = min(np.mean(niters), niters_min_all[QI])
niters_max_all[QI] = max(np.mean(niters), niters_max_all[QI])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
f.write(out + '\n')
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
f.write(out + '\n')
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (
int(np.argmax(niters)),
int(np.argmin(niters)),
)
f.write(out + '\n')
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (
float(np.std(niters)),
float(np.var(niters)),
)
f.write(out + '\n')
f.write(out + '\n')
print(out)
f.write('\n')
print()
assert err < 5.1365e-04, "ERROR: error is too high, got %s" % err
out = 'Mean number of iterations went up from %4.2f to %4.2f for QI = %s!' % (
niters_min_all[QI],
niters_max_all[QI],
QI,
)
f.write(out + '\n')
print(out)
f.write('\n\n')
print()
print()
f.close()
if __name__ == "__main__":
main()
| 5,577 | 34.75641 | 104 | py |
pySDC | pySDC-master/pySDC/tutorial/step_5/B_my_first_PFASST_run.py | from pathlib import Path
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_forced
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
def main():
"""
A simple test program to do PFASST runs for the heat equation
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.25
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = 'LU' # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 8 # frequency for the test value
problem_params['nvars'] = [511, 255] # number of degrees of freedom for each level
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['predict_type'] = 'pfasst_burnin'
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_forced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass parameters for spatial transfer
# set time parameters
t0 = 0.0
Tend = 4.0
# set up list of parallel time-steps to run PFASST with
nsteps = int(Tend / level_params['dt'])
num_proc_list = [2**i for i in range(int(np.log2(nsteps) + 1))]
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_5_B_out.txt', 'w')
# loop over different number of processes and check results
for num_proc in num_proc_list:
out = 'Working with %2i processes...' % num_proc
f.write(out + '\n')
print(out)
# instantiate controller
controller = controller_nonMPI(num_procs=num_proc, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %2i' % item
f.write(out + '\n')
print(out)
f.write('\n')
print()
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
f.write(out + '\n')
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
f.write(out + '\n')
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (
int(np.argmax(niters)),
int(np.argmin(niters)),
)
f.write(out + '\n')
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
f.write(out + '\n')
print(out)
f.write('\n\n')
print()
print()
assert err < 1.3505e-04, "ERROR: error is too high, got %s" % err
assert np.ptp(niters) <= 1, "ERROR: range of number of iterations is too high, got %s" % np.ptp(niters)
assert np.mean(niters) <= 5.0, "ERROR: mean number of iterations is too high, got %s" % np.mean(niters)
f.close()
if __name__ == "__main__":
main()
| 4,871 | 36.767442 | 120 | py |
pySDC | pySDC-master/pySDC/tutorial/step_5/A_multistep_multilevel_hierarchy.py | from pathlib import Path
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_forced
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
def main():
"""
A simple test program to setup a full multi-step multi-level hierarchy
"""
# initialize level parameters
level_params = {}
level_params['restol'] = 1e-10
level_params['dt'] = 0.5
# initialize sweeper parameters
sweeper_params = {}
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
# initialize problem parameters
problem_params = {}
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['nvars'] = [31, 15, 7] # number of degrees of freedom for each level
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = {}
step_params['maxiter'] = 20
# initialize space transfer parameters
space_transfer_params = {}
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
# fill description dictionary for easy step instantiation
description = {}
description['problem_class'] = heatNd_forced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass parameters for spatial transfer
# instantiate controller
controller = controller_nonMPI(num_procs=10, controller_params={}, description=description)
# check number of levels
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_5_A_out.txt', 'w')
for i in range(len(controller.MS)):
out = "Process %2i has %2i levels" % (i, len(controller.MS[i].levels))
f.write(out + '\n')
print(out)
f.close()
assert all(len(S.levels) == 3 for S in controller.MS), "ERROR: not all steps have the same number of levels"
if __name__ == "__main__":
main()
| 2,614 | 36.898551 | 112 | py |
pySDC | pySDC-master/pySDC/tutorial/step_5/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/tutorial/step_8/C_iteration_estimator.py | import numpy as np
from pathlib import Path
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_forced
from pySDC.implementations.problem_classes.AdvectionEquation_ND_FD import advectionNd
from pySDC.implementations.problem_classes.Auzinger_implicit import auzinger
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
from pySDC.implementations.transfer_classes.TransferMesh_NoCoarse import mesh_to_mesh as mesh_to_mesh_nc
from pySDC.implementations.convergence_controller_classes.check_iteration_estimator import CheckIterationEstimatorNonMPI
from pySDC.tutorial.step_8.HookClass_error_output import error_output
def setup_diffusion(dt=None, ndim=None, ml=False):
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = dt # time-step size
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['order'] = 8 # order of accuracy for FD discretization in space
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['bc'] = 'periodic' # boundary conditions
problem_params['freq'] = tuple(2 for _ in range(ndim)) # frequencies
if ml:
problem_params['nvars'] = [tuple(64 for _ in range(ndim)), tuple(32 for _ in range(ndim))] # number of dofs
else:
problem_params['nvars'] = tuple(64 for _ in range(ndim)) # number of dofs
problem_params['solver_type'] = 'CG' # do CG instead of LU
problem_params['liniter'] = 10 # number of CG iterations
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
step_params['errtol'] = 1e-07
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
space_transfer_params['periodic'] = True
# setup the iteration estimator
convergence_controllers = dict()
convergence_controllers[CheckIterationEstimatorNonMPI] = {'errtol': 1e-7}
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_forced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['convergence_controllers'] = convergence_controllers
if ml:
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass parameters for spatial transfer
return description, controller_params
def setup_advection(dt=None, ndim=None, ml=False):
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = dt # time-step size
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['order'] = 6 # order of accuracy for FD discretization in space
problem_params['stencil_type'] = 'center' # order of accuracy for FD discretization in space
problem_params['bc'] = 'periodic' # boundary conditions
problem_params['c'] = 0.1 # diffusion coefficient
problem_params['freq'] = tuple(2 for _ in range(ndim)) # frequencies
if ml:
problem_params['nvars'] = [tuple(64 for _ in range(ndim)), tuple(32 for _ in range(ndim))] # number of dofs
else:
problem_params['nvars'] = tuple(64 for _ in range(ndim)) # number of dofs
problem_params['solver_type'] = 'GMRES' # do GMRES instead of LU
problem_params['liniter'] = 10 # number of GMRES iterations
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
step_params['errtol'] = 1e-07
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
space_transfer_params['periodic'] = True
# setup the iteration estimator
convergence_controllers = dict()
convergence_controllers[CheckIterationEstimatorNonMPI] = {'errtol': 1e-7}
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = advectionNd
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['convergence_controllers'] = convergence_controllers
if ml:
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass parameters for spatial transfer
return description, controller_params
def setup_auzinger(dt=None, ml=False):
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = dt # time-step size
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
if ml:
sweeper_params['num_nodes'] = [3, 2]
else:
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['newton_tol'] = 1e-12
problem_params['newton_maxiter'] = 10
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
step_params['errtol'] = 1e-07
# setup the iteration estimator
convergence_controllers = dict()
convergence_controllers[CheckIterationEstimatorNonMPI] = {'errtol': 1e-7}
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = auzinger
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['convergence_controllers'] = convergence_controllers
if ml:
description['space_transfer_class'] = mesh_to_mesh_nc # pass spatial transfer class
return description, controller_params
def run_simulations(type=None, ndim_list=None, Tend=None, nsteps_list=None, ml=False, nprocs=None):
"""
A simple test program to do SDC runs for the heat equation in various dimensions
"""
t0 = None
dt = None
description = None
controller_params = None
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_8_C_out.txt', 'a')
for ndim in ndim_list:
for nsteps in nsteps_list:
if type == 'diffusion':
# set time parameters
t0 = 0.0
dt = (Tend - t0) / nsteps
description, controller_params = setup_diffusion(dt, ndim, ml)
mean_number_of_iterations = 3.00 if ml else 5.75
elif type == 'advection':
# set time parameters
t0 = 0.0
dt = (Tend - t0) / nsteps
description, controller_params = setup_advection(dt, ndim, ml)
mean_number_of_iterations = 2.00 if ml else 4.00
elif type == 'auzinger':
assert ndim == 1
# set time parameters
t0 = 0.0
dt = (Tend - t0) / nsteps
description, controller_params = setup_auzinger(dt, ml)
mean_number_of_iterations = 3.62 if ml else 5.62
out = f'Running {type} in {ndim} dimensions with time-step size {dt}...\n'
f.write(out + '\n')
print(out)
# Warning: this is black magic used to run an 'exact' collocation solver for each step within the hooks
description['step_params']['description'] = description
description['step_params']['controller_params'] = controller_params
# instantiate controller
controller = controller_nonMPI(
num_procs=nprocs, controller_params=controller_params, description=description
)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
niters = np.array([item[1] for item in iter_counts])
out = f' Mean number of iterations: {np.mean(niters):4.2f}'
f.write(out + '\n')
print(out)
# filter statistics by type (error after time-step)
PDE_errors = get_sorted(stats, type='PDE_error_after_step', sortby='time')
coll_errors = get_sorted(stats, type='coll_error_after_step', sortby='time')
for iters, PDE_err, coll_err in zip(iter_counts, PDE_errors, coll_errors):
assert coll_err[1] < description['step_params']['errtol'], f'Error too high, got {coll_err[1]:8.4e}'
out = (
f' Errors after step {PDE_err[0]:8.4f} with {iters[1]} iterations: '
f'{PDE_err[1]:8.4e} / {coll_err[1]:8.4e}'
)
f.write(out + '\n')
print(out)
f.write('\n')
print()
# filter statistics by type (error after time-step)
timing = get_sorted(stats, type='timing_run', sortby='time')
out = f'...done, took {timing[0][1]} seconds!'
f.write(out + '\n')
print(out)
print()
out = '-----------------------------------------------------------------------------'
f.write(out + '\n')
print(out)
f.close()
assert np.isclose(
mean_number_of_iterations, np.mean(niters), atol=1e-2
), f'Expected \
{mean_number_of_iterations:.2f} mean iterations, but got {np.mean(niters):.2f}'
def main():
run_simulations(type='diffusion', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=False, nprocs=1)
run_simulations(type='diffusion', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=True, nprocs=1)
run_simulations(type='advection', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=False, nprocs=1)
run_simulations(type='advection', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=True, nprocs=1)
run_simulations(type='auzinger', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=False, nprocs=1)
run_simulations(type='auzinger', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=True, nprocs=1)
if __name__ == "__main__":
main()
| 12,876 | 41.358553 | 120 | py |
pySDC | pySDC-master/pySDC/tutorial/step_8/B_multistep_SDC.py | import os
from pathlib import Path
from pySDC.helpers.stats_helper import get_sorted
from pySDC.helpers.visualization_tools import show_residual_across_simulation
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
def main():
"""
A simple test program to do compare PFASST with multi-step SDC
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 5e-10
level_params['dt'] = 0.125
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 2 # frequency for the test value
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 40
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_unforced # pass problem class
description['sweeper_class'] = generic_LU # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass parameters for spatial transfer
# set up parameters for PFASST run
problem_params['nvars'] = [63, 31]
description['problem_params'] = problem_params.copy()
description_pfasst = description.copy()
# set up parameters for MSSDC run
problem_params['nvars'] = [63]
description['problem_params'] = problem_params.copy()
description_mssdc = description.copy()
controller_params['mssdc_jac'] = True
controller_params_jac = controller_params.copy()
controller_params['mssdc_jac'] = False
controller_params_gs = controller_params.copy()
# set time parameters
t0 = 0.0
Tend = 1.0
# set up list of parallel time-steps to run PFASST/MSSDC with
num_proc = 8
# instantiate controllers
controller_mssdc_jac = controller_nonMPI(
num_procs=num_proc, controller_params=controller_params_jac, description=description_mssdc
)
controller_mssdc_gs = controller_nonMPI(
num_procs=num_proc, controller_params=controller_params_gs, description=description_mssdc
)
controller_pfasst = controller_nonMPI(
num_procs=num_proc, controller_params=controller_params, description=description_pfasst
)
# get initial values on finest level
P = controller_mssdc_jac.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main functions to get things done...
uend_pfasst, stats_pfasst = controller_pfasst.run(u0=uinit, t0=t0, Tend=Tend)
uend_mssdc_jac, stats_mssdc_jac = controller_mssdc_jac.run(u0=uinit, t0=t0, Tend=Tend)
uend_mssdc_gs, stats_mssdc_gs = controller_mssdc_gs.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare for both runs
uex = P.u_exact(Tend)
err_mssdc_jac = abs(uex - uend_mssdc_jac)
err_mssdc_gs = abs(uex - uend_mssdc_gs)
err_pfasst = abs(uex - uend_pfasst)
diff_jac = abs(uend_mssdc_jac - uend_pfasst)
diff_gs = abs(uend_mssdc_gs - uend_pfasst)
diff_jac_gs = abs(uend_mssdc_gs - uend_mssdc_jac)
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_8_B_out.txt', 'w')
out = 'Error PFASST: %12.8e' % err_pfasst
f.write(out + '\n')
print(out)
out = 'Error parallel MSSDC: %12.8e' % err_mssdc_jac
f.write(out + '\n')
print(out)
out = 'Error serial MSSDC: %12.8e' % err_mssdc_gs
f.write(out + '\n')
print(out)
out = 'Diff PFASST vs. parallel MSSDC: %12.8e' % diff_jac
f.write(out + '\n')
print(out)
out = 'Diff PFASST vs. serial MSSDC: %12.8e' % diff_gs
f.write(out + '\n')
print(out)
out = 'Diff parallel vs. serial MSSDC: %12.8e' % diff_jac_gs
f.write(out + '\n')
print(out)
# convert filtered statistics to list of iterations count, sorted by process
iter_counts_pfasst = get_sorted(stats_pfasst, type='niter', sortby='time')
iter_counts_mssdc_jac = get_sorted(stats_mssdc_jac, type='niter', sortby='time')
iter_counts_mssdc_gs = get_sorted(stats_mssdc_gs, type='niter', sortby='time')
# compute and print statistics
for item_pfasst, item_mssdc_jac, item_mssdc_gs in zip(
iter_counts_pfasst, iter_counts_mssdc_jac, iter_counts_mssdc_gs
):
out = 'Number of iterations for time %4.2f (PFASST/parMSSDC/serMSSDC): %2i / %2i / %2i' % (
item_pfasst[0],
item_pfasst[1],
item_mssdc_jac[1],
item_mssdc_gs[1],
)
f.write(out + '\n')
print(out)
f.close()
# call helper routine to produce residual plot
show_residual_across_simulation(stats_mssdc_jac, 'data/step_8_residuals_mssdc_jac.png')
show_residual_across_simulation(stats_mssdc_gs, 'data/step_8_residuals_mssdc_gs.png')
assert os.path.isfile('data/step_8_residuals_mssdc_jac.png')
assert os.path.isfile('data/step_8_residuals_mssdc_gs.png')
assert diff_jac < 3.1e-10, (
"ERROR: difference between PFASST and parallel MSSDC controller is too large, got %s" % diff_jac
)
assert diff_gs < 3.1e-10, (
"ERROR: difference between PFASST and serial MSSDC controller is too large, got %s" % diff_gs
)
assert diff_jac_gs < 3.1e-10, (
"ERROR: difference between parallel and serial MSSDC controller is too large, got %s" % diff_jac_gs
)
if __name__ == "__main__":
main()
| 6,368 | 36.464706 | 107 | py |
pySDC | pySDC-master/pySDC/tutorial/step_8/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/tutorial/step_8/HookClass_error_output.py | from pySDC.core.Hooks import hooks
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.Auzinger_implicit import auzinger
class error_output(hooks):
"""
Hook class to add output of error
"""
def __init__(self):
super(error_output, self).__init__()
self.uex = None
def pre_step(self, step, level_number):
"""
Default routine called before each step
Args:
step: the current step
level_number: the current level number
"""
super(error_output, self).pre_step(step, level_number)
L = step.levels[level_number]
# This is a bit black magic: we are going to run pySDC within the hook to check the error against the "exact"
# solution of the collocation problem
description = step.params.description
description['level_params']['restol'] = 1e-14
if type(L.prob) != auzinger:
description['problem_params']['solver_type'] = 'direct'
controller_params = step.params.controller_params
del controller_params['hook_class'] # get rid of the hook, otherwise this will be an endless recursion..
controller_params['logger_level'] = 90
controller_params['convergence_controllers'] = {}
controller = controller_nonMPI(num_procs=1, description=description, controller_params=controller_params)
self.uex, _ = controller.run(u0=L.u[0], t0=L.time, Tend=L.time + L.dt)
def post_step(self, step, level_number):
"""
Default routine called after each step
Args:
step: the current step
level_number: the current level number
"""
super(error_output, self).post_step(step, level_number)
# some abbreviations
L = step.levels[level_number]
P = L.prob
L.sweep.compute_end_point()
# compute and save errors
upde = P.u_exact(step.time + step.dt)
pde_err = abs(upde - L.uend)
coll_err = abs(self.uex - L.uend)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='PDE_error_after_step',
value=pde_err,
)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='coll_error_after_step',
value=coll_err,
)
| 2,662 | 32.2875 | 117 | py |
pySDC | pySDC-master/pySDC/tutorial/step_8/A_visualize_residuals.py | import os
from pathlib import Path
from pySDC.helpers.stats_helper import get_sorted
from pySDC.helpers.visualization_tools import show_residual_across_simulation
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.tutorial.step_6.A_run_non_MPI_controller import set_parameters_ml
def main():
"""
A simple test program to demonstrate residual visualization
"""
# get parameters from Step 6, Part A
description, controller_params, t0, Tend = set_parameters_ml()
# use 8 processes here
num_proc = 8
# instantiate controller
controller = controller_nonMPI(num_procs=num_proc, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare (for testing purposes only)
uex = P.u_exact(Tend)
err = abs(uex - uend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
min_iter = 99
max_iter = 0
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_8_A_out.txt', 'w')
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %1i' % item
f.write(out + '\n')
print(out)
min_iter = min(min_iter, item[1])
max_iter = max(max_iter, item[1])
f.close()
# call helper routine to produce residual plot
fname = 'data/step_8_residuals.png'
show_residual_across_simulation(stats=stats, fname=fname)
assert err < 6.1555e-05, 'ERROR: error is too large, got %s' % err
assert os.path.isfile(fname), 'ERROR: residual plot has not been created'
assert min_iter == 7 and max_iter == 7, "ERROR: number of iterations not as expected, got %s and %s" % (
min_iter,
max_iter,
)
if __name__ == "__main__":
main()
| 2,085 | 30.606061 | 116 | py |
pySDC | pySDC-master/pySDC/tutorial/step_1/C_collocation_problem_setup.py | import numpy as np
import scipy.sparse as sp
from pathlib import Path
from pySDC.core.Collocation import CollBase
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
def main():
"""
A simple test program to create and solve a collocation problem directly
"""
# instantiate problem
prob = heatNd_unforced(
nvars=1023, # number of degrees of freedom
nu=0.1, # diffusion coefficient
freq=4, # frequency for the test value
bc='dirichlet-zero', # boundary conditions
)
# instantiate collocation class, relative to the time interval [0,1]
coll = CollBase(num_nodes=3, tleft=0, tright=1, node_type='LEGENDRE', quad_type='RADAU-RIGHT')
# set time-step size (warning: the collocation matrices are relative to [0,1], see above)
dt = 0.1
# solve collocation problem
err = solve_collocation_problem(prob=prob, coll=coll, dt=dt)
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_1_C_out.txt', 'w')
out = 'Error of the collocation problem: %8.6e' % err
f.write(out + '\n')
print(out)
f.close()
assert err <= 4e-04, "ERROR: did not get collocation error as expected, got %s" % err
def solve_collocation_problem(prob, coll, dt):
"""
Routine to build and solve the linear collocation problem
Args:
prob: a problem instance
coll: a collocation instance
dt: time-step size
Return:
the analytic error of the solved collocation problem
"""
# shrink collocation matrix: first line and column deals with initial value, not needed here
Q = coll.Qmat[1:, 1:]
# build system matrix M of collocation problem
M = sp.eye(prob.nvars[0] * coll.num_nodes) - dt * sp.kron(Q, prob.A)
# get initial value at t0 = 0
u0 = prob.u_exact(t=0)
# fill in u0-vector as right-hand side for the collocation problem
u0_coll = np.kron(np.ones(coll.num_nodes), u0)
# get exact solution at Tend = dt
uend = prob.u_exact(t=dt)
# solve collocation problem directly
u_coll = sp.linalg.spsolve(M, u0_coll)
# compute error
err = np.linalg.norm(u_coll[-prob.nvars[0] :] - uend, np.inf)
return err
if __name__ == "__main__":
main()
| 2,276 | 28.192308 | 98 | py |
pySDC | pySDC-master/pySDC/tutorial/step_1/B_spatial_accuracy_check.py | from pathlib import Path
import matplotlib
matplotlib.use('Agg')
from collections import namedtuple
import matplotlib.pylab as plt
import numpy as np
import os.path
from pySDC.implementations.datatype_classes.mesh import mesh
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
# setup id for gathering the results (will sort by nvars)
ID = namedtuple('ID', 'nvars')
def main():
"""
A simple test program to check order of accuracy in space for a simple test problem
"""
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# create list of nvars to do the accuracy test with
nvars_list = [2**p - 1 for p in range(4, 15)]
# run accuracy test for all nvars
results = run_accuracy_check(nvars_list=nvars_list, problem_params=problem_params)
# compute order of accuracy
order = get_accuracy_order(results)
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_1_B_out.txt', 'w')
for l in range(len(order)):
out = 'Expected order: %2i -- Computed order %4.3f' % (2, order[l])
f.write(out + '\n')
print(out)
f.close()
# visualize results
plot_accuracy(results)
assert os.path.isfile('data/step_1_accuracy_test_space.png'), 'ERROR: plotting did not create file'
assert all(np.isclose(order, 2, rtol=0.06)), "ERROR: spatial order of accuracy is not as expected, got %s" % order
def run_accuracy_check(nvars_list, problem_params):
"""
Routine to check the error of the Laplacian vs. its FD discretization
Args:
nvars_list: list of nvars to do the testing with
problem_params: dictionary containing the problem-dependent parameters
Returns:
a dictionary containing the errors and a header (with nvars_list)
"""
results = {}
# loop over all nvars
for nvars in nvars_list:
# setup problem
problem_params['nvars'] = nvars
prob = heatNd_unforced(**problem_params)
# create x values, use only inner points
xvalues = np.array([(i + 1) * prob.dx for i in range(prob.nvars[0])])
# create a mesh instance and fill it with a sine wave
u = prob.u_exact(t=0)
# create a mesh instance and fill it with the Laplacian of the sine wave
u_lap = prob.dtype_u(init=prob.init)
u_lap[:] = -((np.pi * prob.freq[0]) ** 2) * prob.nu * np.sin(np.pi * prob.freq[0] * xvalues)
# compare analytic and computed solution using the eval_f routine of the problem class
err = abs(prob.eval_f(u, 0) - u_lap)
# get id for this nvars and put error into dictionary
id = ID(nvars=nvars)
results[id] = err
# add nvars_list to dictionary for easier access later on
results['nvars_list'] = nvars_list
return results
def get_accuracy_order(results):
"""
Routine to compute the order of accuracy in space
Args:
results: the dictionary containing the errors
Returns:
the list of orders
"""
# retrieve the list of nvars from results
assert 'nvars_list' in results, 'ERROR: expecting the list of nvars in the results dictionary'
nvars_list = sorted(results['nvars_list'])
order = []
# loop over two consecutive errors/nvars pairs
for i in range(1, len(nvars_list)):
# get ids
id = ID(nvars=nvars_list[i])
id_prev = ID(nvars=nvars_list[i - 1])
# compute order as log(prev_error/this_error)/log(this_nvars/old_nvars) <-- depends on the sorting of the list!
tmp = np.log(results[id_prev] / results[id]) / np.log(nvars_list[i] / nvars_list[i - 1])
order.append(tmp)
return order
def plot_accuracy(results):
"""
Routine to visualize the errors as well as the expected errors
Args:
results: the dictionary containing the errors
"""
# retrieve the list of nvars from results
assert 'nvars_list' in results, 'ERROR: expecting the list of nvars in the results dictionary'
nvars_list = sorted(results['nvars_list'])
# Set up plotting parameters
params = {
'legend.fontsize': 20,
'figure.figsize': (12, 8),
'axes.labelsize': 20,
'axes.titlesize': 20,
'xtick.labelsize': 16,
'ytick.labelsize': 16,
'lines.linewidth': 3,
}
plt.rcParams.update(params)
# create new figure
plt.figure()
# take x-axis limits from nvars_list + some spacing left and right
plt.xlim([min(nvars_list) / 2, max(nvars_list) * 2])
plt.xlabel('nvars')
plt.ylabel('abs. error')
plt.grid()
# get guide for the order of accuracy, i.e. the errors to expect
# get error for first entry in nvars_list
id = ID(nvars=nvars_list[0])
base_error = results[id]
# assemble optimal errors for 2nd order method and plot
order_guide_space = [base_error / (2 ** (2 * i)) for i in range(0, len(nvars_list))]
plt.loglog(nvars_list, order_guide_space, color='k', ls='--', label='2nd order')
min_err = 1e99
max_err = 0e00
err_list = []
# loop over nvars, get errors and find min/max error for y-axis limits
for nvars in nvars_list:
id = ID(nvars=nvars)
err = results[id]
min_err = min(err, min_err)
max_err = max(err, max_err)
err_list.append(err)
plt.loglog(nvars_list, err_list, ls=' ', marker='o', markersize=10, label='experiment')
# adjust y-axis limits, add legend
plt.ylim([min_err / 10, max_err * 10])
plt.legend(loc=1, ncol=1, numpoints=1)
# save plot as PDF, beautify
fname = 'data/step_1_accuracy_test_space.png'
plt.savefig(fname, bbox_inches='tight')
return None
if __name__ == "__main__":
main()
| 5,936 | 30.247368 | 119 | py |
pySDC | pySDC-master/pySDC/tutorial/step_1/D_collocation_accuracy_check.py | from pathlib import Path
import matplotlib
matplotlib.use('Agg')
from collections import namedtuple
import matplotlib.pylab as plt
import numpy as np
import os.path
import scipy.sparse as sp
from pySDC.core.Collocation import CollBase
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
# setup id for gathering the results (will sort by dt)
ID = namedtuple('ID', 'dt')
def main():
"""
A simple test program to compute the order of accuracy in time
"""
# initialize problem parameters
problem_params = {}
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['nvars'] = 16383 # number of DOFs in space
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# instantiate problem
prob = heatNd_unforced(**problem_params)
# instantiate collocation class, relative to the time interval [0,1]
coll = CollBase(num_nodes=3, tleft=0, tright=1, node_type='LEGENDRE', quad_type='RADAU-RIGHT')
# assemble list of dt
dt_list = [0.1 / 2**p for p in range(0, 4)]
# run accuracy test for all dt
results = run_accuracy_check(prob=prob, coll=coll, dt_list=dt_list)
# get order of accuracy
order = get_accuracy_order(results)
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_1_D_out.txt', 'w')
for l in range(len(order)):
out = 'Expected order: %2i -- Computed order %4.3f' % (5, order[l])
f.write(out + '\n')
print(out)
f.close()
# visualize results
plot_accuracy(results)
assert os.path.isfile('data/step_1_accuracy_test_coll.png')
assert all(np.isclose(order, 2 * coll.num_nodes - 1, rtol=0.4)), (
"ERROR: did not get order of accuracy as expected, got %s" % order
)
def run_accuracy_check(prob, coll, dt_list):
"""
Routine to build and solve the linear collocation problem
Args:
prob: a problem instance
coll: a collocation instance
dt_list: list of time-step sizes
Return:
the analytic error of the solved collocation problem
"""
results = {}
# loop over all nvars
for dt in dt_list:
# shrink collocation matrix: first line and column deals with initial value, not needed here
Q = coll.Qmat[1:, 1:]
# build system matrix M of collocation problem
M = sp.eye(prob.nvars[0] * coll.num_nodes) - dt * sp.kron(Q, prob.A)
# get initial value at t0 = 0
u0 = prob.u_exact(t=0)
# fill in u0-vector as right-hand side for the collocation problem
u0_coll = np.kron(np.ones(coll.num_nodes), u0)
# get exact solution at Tend = dt
uend = prob.u_exact(t=dt)
# solve collocation problem directly
u_coll = sp.linalg.spsolve(M, u0_coll)
# compute error
err = np.linalg.norm(u_coll[-prob.nvars[0] :] - uend, np.inf)
# get id for this dt and store error in results
id = ID(dt=dt)
results[id] = err
# add list of dt to results for easier access
results['dt_list'] = dt_list
return results
def get_accuracy_order(results):
"""
Routine to compute the order of accuracy in time
Args:
results: the dictionary containing the errors
Returns:
the list of orders
"""
# retrieve the list of dt from results
assert 'dt_list' in results, 'ERROR: expecting the list of dt in the results dictionary'
dt_list = sorted(results['dt_list'], reverse=True)
order = []
# loop over two consecutive errors/dt pairs
for i in range(1, len(dt_list)):
# get ids
id = ID(dt=dt_list[i])
id_prev = ID(dt=dt_list[i - 1])
# compute order as log(prev_error/this_error)/log(this_dt/old_dt) <-- depends on the sorting of the list!
tmp = np.log(results[id] / results[id_prev]) / np.log(dt_list[i] / dt_list[i - 1])
order.append(tmp)
return order
def plot_accuracy(results):
"""
Routine to visualize the errors as well as the expected errors
Args:
results: the dictionary containing the errors
"""
# retrieve the list of nvars from results
assert 'dt_list' in results, 'ERROR: expecting the list of dts in the results dictionary'
dt_list = sorted(results['dt_list'])
# Set up plotting parameters
params = {
'legend.fontsize': 20,
'figure.figsize': (12, 8),
'axes.labelsize': 20,
'axes.titlesize': 20,
'xtick.labelsize': 16,
'ytick.labelsize': 16,
'lines.linewidth': 3,
}
plt.rcParams.update(params)
# create new figure
plt.figure()
# take x-axis limits from nvars_list + some spacning left and right
plt.xlim([min(dt_list) / 2, max(dt_list) * 2])
plt.xlabel('dt')
plt.ylabel('abs. error')
plt.grid()
# get guide for the order of accuracy, i.e. the errors to expect
# get error for first entry in nvars_list
id = ID(dt=dt_list[0])
base_error = results[id]
# assemble optimal errors for 5th order method and plot
order_guide_space = [base_error * (2 ** (5 * i)) for i in range(0, len(dt_list))]
plt.loglog(dt_list, order_guide_space, color='k', ls='--', label='5th order')
min_err = 1e99
max_err = 0e00
err_list = []
# loop over nvars, get errors and find min/max error for y-axis limits
for dt in dt_list:
id = ID(dt=dt)
err = results[id]
min_err = min(err, min_err)
max_err = max(err, max_err)
err_list.append(err)
plt.loglog(dt_list, err_list, ls=' ', marker='o', markersize=10, label='experiment')
# adjust y-axis limits, add legend
plt.ylim([min_err / 10, max_err * 10])
plt.legend(loc=2, ncol=1, numpoints=1)
# save plot as PDF, beautify
fname = 'data/step_1_accuracy_test_coll.png'
plt.savefig(fname, bbox_inches='tight')
return None
if __name__ == "__main__":
main()
| 6,011 | 28.910448 | 113 | py |
pySDC | pySDC-master/pySDC/tutorial/step_1/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/tutorial/step_1/A_spatial_problem_setup.py | import numpy as np
from pathlib import Path
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
def main():
"""
A simple test program to set up a spatial problem and play with it
"""
# instantiate problem
prob = heatNd_unforced(
nvars=1023, # number of degrees of freedom
nu=0.1, # diffusion coefficient
freq=4, # frequency for the test value
bc='dirichlet-zero', # boundary conditions
)
# run accuracy test, get error back
err = run_accuracy_check(prob)
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_1_A_out.txt', 'w')
out = 'Error of the spatial accuracy test: %8.6e' % err
f.write(out)
print(out)
f.close()
assert err <= 2e-04, "ERROR: the spatial accuracy is higher than expected, got %s" % err
def run_accuracy_check(prob):
"""
Routine to check the error of the Laplacian vs. its FD discretization
Args:
prob: a problem instance
Returns:
the error between the analytic Laplacian and the computed one of a given function
"""
# create x values, use only inner points
xvalues = np.array([(i + 1) * prob.dx for i in range(prob.nvars[0])])
# create a mesh instance and fill it with a sine wave
u = prob.dtype_u(init=prob.init)
u[:] = np.sin(np.pi * prob.freq[0] * xvalues)
# create a mesh instance and fill it with the Laplacian of the sine wave
u_lap = prob.dtype_u(init=prob.init)
u_lap[:] = -((np.pi * prob.freq[0]) ** 2) * prob.nu * np.sin(np.pi * prob.freq[0] * xvalues)
# compare analytic and computed solution using the eval_f routine of the problem class
err = abs(prob.eval_f(u, 0) - u_lap)
return err
if __name__ == "__main__":
main()
| 1,797 | 28 | 96 | py |
pySDC | pySDC-master/pySDC/tutorial/step_2/C_using_pySDCs_frontend.py | from pathlib import Path
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_forced
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
def main():
"""
A simple test program to run IMEX SDC for a single time step
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['nvars'] = 1023 # number of degrees of freedom
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['log_to_file'] = True
controller_params['fname'] = 'data/step_2_C_out.txt'
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = heatNd_forced
description['problem_params'] = problem_params
description['sweeper_class'] = imex_1st_order
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
Path("data").mkdir(parents=True, exist_ok=True)
# instantiate the controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.1
Tend = 0.3 # note that we are requesting 2 time steps here (dt is 0.1)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
f = open('data/step_2_C_out.txt', 'a')
out = 'Error after SDC iterations: %8.6e' % err
f.write(out)
print(out)
f.close()
assert err <= 2e-5, "ERROR: controller doing IMEX SDC iteration did not reduce the error enough, got %s" % err
if __name__ == "__main__":
main()
| 2,531 | 31.050633 | 114 | py |
pySDC | pySDC-master/pySDC/tutorial/step_2/A_step_data_structure.py | from pathlib import Path
from pySDC.core.Step import step
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.tutorial.step_1.A_spatial_problem_setup import run_accuracy_check
def main():
"""
A simple test program to setup a full step instance
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['nvars'] = 1023 # number of degrees of freedom
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_unforced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_LU # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
# now the description contains more or less everything we need to create a step
S = step(description=description)
# we only have a single level, make a shortcut
L = S.levels[0]
# one of the integral parts of each level is the problem class, make a shortcut
P = L.prob
# now we can do e.g. what we did before with the problem
err = run_accuracy_check(P)
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_2_A_out.txt', 'w')
out = 'Error of the spatial accuracy test: %8.6e' % err
f.write(out)
print(out)
f.close()
assert err <= 2e-04, "ERROR: the spatial accuracy is higher than expected, got %s" % err
if __name__ == "__main__":
main()
| 2,321 | 32.652174 | 92 | py |
pySDC | pySDC-master/pySDC/tutorial/step_2/B_my_first_sweeper.py | from pathlib import Path
from pySDC.core.Step import step
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_forced
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
def main():
"""
A simple test program to run IMEX SDC for a single time step
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 4 # frequency for the test value
problem_params['nvars'] = 1023 # number of degrees of freedom
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = heatNd_forced
description['problem_params'] = problem_params
description['sweeper_class'] = imex_1st_order
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
# instantiate the step we are going to work on
S = step(description=description)
# run IMEX SDC test and check error, residual and number of iterations
err, res, niter = run_imex_sdc(S)
print('Error and residual: %12.8e -- %12.8e' % (err, res))
assert err <= 1e-5, "ERROR: IMEX SDC iteration did not reduce the error enough, got %s" % err
assert res <= level_params['restol'], "ERROR: IMEX SDC iteration did not reduce the residual enough, got %s" % res
assert niter <= 12, "ERROR: IMEX SDC took too many iterations, got %s" % niter
def run_imex_sdc(S):
"""
Routine to run IMEX SDC on a single time step
Args:
S: an instance of a step representing the time step
Returns:
the error of SDC vs. exact solution
the residual after the SDC sweeps
the number of iterations
"""
# make shortcuts for the level and the problem
L = S.levels[0]
P = L.prob
# set initial time in the status of the level
L.status.time = 0.1
# compute initial value (using the exact function here)
L.u[0] = P.u_exact(L.time)
# access the sweeper's predict routine to get things started
# if we don't do this, the values at the nodes are not initialized
L.sweep.predict()
# compute the residual (we may be done already!)
L.sweep.compute_residual()
# reset iteration counter
S.status.iter = 0
# run the SDC iteration until either the maximum number of iterations is reached or the residual is small enough
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_2_B_out.txt', 'w')
while S.status.iter < S.params.maxiter and L.status.residual > L.params.restol:
# this is where the nodes are actually updated according to the SDC formulas
L.sweep.update_nodes()
# compute/update the residual
L.sweep.compute_residual()
# increment the iteration counter
S.status.iter += 1
out = 'Time %4.2f of %s -- Iteration: %2i -- Residual: %12.8e' % (
L.time,
L.level_index,
S.status.iter,
L.status.residual,
)
f.write(out + '\n')
print(out)
f.close()
# compute the interval's endpoint: this (and only this) will set uend, depending on the collocation nodes
L.sweep.compute_end_point()
# update the simulation time
L.status.time += L.dt
# compute exact solution and compare
uex = P.u_exact(L.status.time)
err = abs(uex - L.uend)
return err, L.status.residual, S.status.iter
if __name__ == "__main__":
main()
| 3,992 | 32.838983 | 118 | py |
pySDC | pySDC-master/pySDC/tutorial/step_2/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/tutorial/step_7/B_pySDC_with_mpi4pyfft.py | import numpy as np
from pathlib import Path
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.problem_classes.NonlinearSchroedinger_MPIFFT import nonlinearschroedinger_imex
from pySDC.implementations.transfer_classes.TransferMesh_MPIFFT import fft_to_fft
def run_simulation(spectral=None, ml=None, num_procs=None):
"""
A test program to do SDC, MLSDC and PFASST runs for the 2D NLS equation
Args:
spectral (bool): run in real or spectral space
ml (bool): single or multiple levels
num_procs (int): number of parallel processors
"""
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 1e-01 / 2
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
if ml:
problem_params['nvars'] = [(128, 128), (32, 32)]
else:
problem_params['nvars'] = [(128, 128)]
problem_params['spectral'] = spectral
problem_params['comm'] = comm
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30 if rank == 0 else 99
# controller_params['predict_type'] = 'fine_only'
# fill description dictionary for easy step instantiation
description = dict()
description['problem_params'] = problem_params # pass problem parameters
description['problem_class'] = nonlinearschroedinger_imex
description['sweeper_class'] = imex_1st_order
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = fft_to_fft
# set time parameters
t0 = 0.0
Tend = 1.0
f = None
if rank == 0:
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_7_B_out.txt', 'a')
out = f'Running with ml={ml} and num_procs={num_procs}...'
f.write(out + '\n')
print(out)
# instantiate controller
controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
uex = P.u_exact(Tend)
err = abs(uex - uend)
if rank == 0:
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
niters = np.array([item[1] for item in iter_counts])
out = (
f' Min/Mean/Max number of iterations: '
f'{np.min(niters):4.2f} / {np.mean(niters):4.2f} / {np.max(niters):4.2f}'
)
f.write(out + '\n')
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
f.write(out + '\n')
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (
int(np.argmax(niters)),
int(np.argmin(niters)),
)
f.write(out + '\n')
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
f.write(out + '\n')
print(out)
out = f'Error: {err:6.4e}'
f.write(out + '\n')
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
out = f'Time to solution: {timing[0][1]:6.4f} sec.'
f.write(out + '\n')
print(out)
assert err <= 1.133e-05, 'Error is too high, got %s' % err
if ml:
if num_procs > 1:
maxmean = 12.5
else:
maxmean = 6.6
else:
maxmean = 12.7
assert np.mean(niters) <= maxmean, 'Mean number of iterations is too high, got %s' % np.mean(niters)
f.write('\n')
print()
f.close()
def main():
"""
Little helper routine to run the whole thing
Note: This can also be run with "mpirun -np 2 python B_pySDC_with_mpi4pyfft.py"
"""
run_simulation(spectral=False, ml=False, num_procs=1)
run_simulation(spectral=True, ml=False, num_procs=1)
run_simulation(spectral=False, ml=True, num_procs=1)
run_simulation(spectral=True, ml=True, num_procs=1)
run_simulation(spectral=False, ml=True, num_procs=10)
run_simulation(spectral=True, ml=True, num_procs=10)
if __name__ == "__main__":
main()
| 5,270 | 33.006452 | 120 | py |
pySDC | pySDC-master/pySDC/tutorial/step_7/C_pySDC_with_PETSc.py | import sys
from pathlib import Path
import numpy as np
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.problem_classes.HeatEquation_2D_PETSc_forced import heat2d_petsc_forced
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferPETScDMDA import mesh_to_mesh_petsc_dmda
def main():
"""
Program to demonstrate usage of PETSc data structures and spatial parallelization,
combined with parallelization in time.
"""
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
# split world communicator to create space-communicators
if len(sys.argv) >= 2:
color = int(world_rank / int(sys.argv[1]))
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
space_rank = space_comm.Get_rank()
# split world communicator to create time-communicators
if len(sys.argv) >= 2:
color = int(world_rank % int(sys.argv[1]))
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
time_rank = time_comm.Get_rank()
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 0.125
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 1.0 # diffusion coefficient
problem_params['freq'] = 2 # frequency for the test value
problem_params['cnvars'] = [(65, 65)] # number of degrees of freedom for the coarsest level
problem_params['refine'] = [1, 0] # number of refinements
problem_params['comm'] = space_comm # pass space-communicator to problem class
problem_params['sol_tol'] = 1e-12 # set tolerance to PETSc' linear solver
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 2
space_transfer_params['periodic'] = False
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20 if space_rank == 0 else 99 # set level depending on rank
controller_params['dump_setup'] = False
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heat2d_petsc_forced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_petsc_dmda # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass parameters for spatial transfer
# set time parameters
t0 = 0.0
Tend = 0.25
# instantiate controller
controller = controller_MPI(controller_params=controller_params, description=description, comm=time_comm)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
niters = np.array([item[1] for item in iter_counts])
# limit output to space-rank 0 (as before when setting the logger level)
if space_rank == 0:
if len(sys.argv) == 3:
fname = str(sys.argv[2])
else:
fname = 'step_7_C_out.txt'
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/' + fname, 'a+')
out = 'This is time-rank %i...' % time_rank
f.write(out + '\n')
print(out)
# compute and print statistics
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %2i' % item
f.write(out + '\n')
print(out)
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
f.write(out + '\n')
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
f.write(out + '\n')
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (
int(np.argmax(niters)),
int(np.argmin(niters)),
)
f.write(out + '\n')
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
f.write(out + '\n')
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
out = 'Time to solution: %6.4f sec.' % timing[0][1]
f.write(out + '\n')
print(out)
out = 'Error vs. PDE solution: %6.4e' % err
f.write(out + '\n')
print(out)
f.close()
assert err < 2e-04, 'ERROR: did not match error tolerance, got %s' % err
assert np.mean(niters) <= 12, 'ERROR: number of iterations is too high, got %s' % np.mean(niters)
if __name__ == "__main__":
main()
| 5,967 | 35.169697 | 120 | py |
pySDC | pySDC-master/pySDC/tutorial/step_7/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/tutorial/step_7/A_pySDC_with_FEniCS.py | from pathlib import Path
import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_1D_FEniCS_matrix_forced import fenics_heat_mass, fenics_heat
from pySDC.implementations.problem_classes.HeatEquation_1D_FEniCS_weak_forced import fenics_heat_weak_imex
from pySDC.implementations.sweeper_classes.imex_1st_order_mass import imex_1st_order_mass, imex_1st_order
from pySDC.implementations.transfer_classes.TransferFenicsMesh import mesh_to_mesh_fenics
def setup(t0=None, ml=None):
"""
Helper routine to set up parameters
Args:
t0 (float): initial time
ml (bool): use single or multiple levels
Returns:
description and controller_params parameter dictionaries
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 5e-10
level_params['dt'] = 0.2
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
if ml:
# Note that coarsening in the nodes actually HELPS MLSDC to converge (M=1 is exact on the coarse level)
sweeper_params['num_nodes'] = [3, 1]
else:
sweeper_params['num_nodes'] = [3]
problem_params = dict()
problem_params['nu'] = 0.1
problem_params['t0'] = t0 # ugly, but necessary to set up this ProblemClass
problem_params['c_nvars'] = [128]
problem_params['family'] = 'CG'
if ml:
# We can do rather aggressive coarsening here. As long as we have 1 node on the coarse level, all is "well" (ie.
# MLSDC does not take more iterations than SDC, but also not less). If we just coarsen in the refinement (and
# not in the nodes and order, the mass inverse approach is way better, ie. halves the number of iterations!
problem_params['order'] = [4, 1]
problem_params['refinements'] = [1, 0]
else:
problem_params['order'] = [4]
problem_params['refinements'] = [1]
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
base_transfer_params = dict()
base_transfer_params['finter'] = True
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = None
description['problem_params'] = problem_params
description['sweeper_class'] = None
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
description['space_transfer_class'] = mesh_to_mesh_fenics
description['base_transfer_params'] = base_transfer_params
return description, controller_params
def run_variants(variant=None, ml=None, num_procs=None):
"""
Main routine to run the different implementations of the heat equation with FEniCS
Args:
variant (str): specifies the variant
ml (bool): use single or multiple levels
num_procs (int): number of processors in time
"""
Tend = 1.0
t0 = 0.0
description, controller_params = setup(t0=t0, ml=ml)
if variant == 'mass':
# Note that we need to reduce the tolerance for the residual here, since otherwise the error will be too high
description['level_params']['restol'] /= 500
description['problem_class'] = fenics_heat_mass
description['sweeper_class'] = imex_1st_order_mass
elif variant == 'mass_inv':
description['problem_class'] = fenics_heat
description['sweeper_class'] = imex_1st_order
elif variant == 'weak':
description['problem_class'] = fenics_heat_weak_imex
description['sweeper_class'] = imex_1st_order
else:
raise NotImplementedError('Variant %s is not implemented' % variant)
# quickly generate block of steps
controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(0.0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend) / abs(uex)
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/step_7_A_out.txt', 'a')
out = f'Variant {variant} with ml={ml} and num_procs={num_procs} -- error at time {Tend}: {err}'
f.write(out + '\n')
print(out)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
f.write(out + '\n')
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
f.write(out + '\n')
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
f.write(out + '\n')
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
f.write(out + '\n')
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
out = f'Time to solution: {timing[0][1]:6.4f} sec.'
f.write(out + '\n')
print(out)
if num_procs == 1:
assert np.mean(niters) <= 6.0, 'Mean number of iterations is too high, got %s' % np.mean(niters)
assert err <= 4.1e-08, 'Error is too high, got %s' % err
else:
assert np.mean(niters) <= 11.6, 'Mean number of iterations is too high, got %s' % np.mean(niters)
assert err <= 4.0e-08, 'Error is too high, got %s' % err
f.write('\n')
print()
f.close()
def main():
run_variants(variant='mass_inv', ml=False, num_procs=1)
run_variants(variant='mass', ml=False, num_procs=1)
run_variants(variant='weak', ml=False, num_procs=1)
run_variants(variant='mass_inv', ml=True, num_procs=1)
run_variants(variant='mass', ml=True, num_procs=1)
run_variants(variant='weak', ml=True, num_procs=1)
run_variants(variant='mass_inv', ml=True, num_procs=5)
# WARNING: all other variants do NOT work, either because of FEniCS restrictions (weak forms with different meshes
# will not work together) or because of inconsistent use of the mass matrix (locality condition for the tau
# correction is not satisfied, mass matrix does not permute with restriction).
# run_pfasst_variants(variant='mass', ml=True, num_procs=5)
# run_pfasst_variants(variant='weak', ml=True, num_procs=5)
if __name__ == "__main__":
main()
| 6,892 | 37.50838 | 120 | py |
Subsets and Splits