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/tutorial/step_6/A_run_non_MPI_controller.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(num_proc_list=None, fname=None, multi_level=True):
"""
A simple test program to run PFASST
Args:
num_proc_list: list of number of processes to test with
fname: filename/path for output
multi_level (bool): do multi-level run or single-level
"""
if multi_level:
description, controller_params, t0, Tend = set_parameters_ml()
else:
assert all(num_proc == 1 for num_proc in num_proc_list), (
'ERROR: single-level run can only use 1 processor, got %s' % num_proc_list
)
description, controller_params, t0, Tend = set_parameters_sl()
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/' + fname, 'w')
# loop over different numbers of processes
for num_proc in num_proc_list:
out = 'Working with %2i processes...' % num_proc
f.write(out + '\n')
print(out)
# instantiate controllers
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 functions to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare with both results
uex = P.u_exact(Tend)
err = abs(uex - uend)
out = 'Error vs. exact solution: %12.8e' % err
f.write(out + '\n')
print(out)
# 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: %1i ' % (item[0], item[1])
f.write(out + '\n')
print(out)
f.write('\n')
print()
assert all(item[1] <= 8 for item in iter_counts), "ERROR: weird iteration counts, got %s" % iter_counts
f.close()
def set_parameters_ml():
"""
Helper routine to set parameters for the following multi-level runs
Returns:
dict: dictionary containing the simulation parameters
dict: dictionary containing the controller parameters
float: starting time
float: end time
"""
# initialize level parameters
level_params = {}
level_params['restol'] = 5e-10
level_params['dt'] = 0.125
# 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'] = 2 # frequency for the test value
problem_params['nvars'] = [63, 31] # number of degrees of freedom for each level
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = {}
step_params['maxiter'] = 50
step_params['errtol'] = 1e-05
# initialize space transfer parameters
space_transfer_params = {}
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
# initialize controller parameters
controller_params = {}
controller_params['logger_level'] = 30
controller_params['all_to_done'] = True # can ask the controller to keep iterating all steps until the end
controller_params['predict_type'] = 'pfasst_burnin' # activate iteration estimator
# fill description dictionary for easy step instantiation
description = {}
description['problem_class'] = heatNd_unforced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
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 time parameters
t0 = 0.0
Tend = 1.0
return description, controller_params, t0, Tend
def set_parameters_sl():
"""
Helper routine to set parameters for the following multi-level runs
Returns:
dict: dictionary containing the simulation parameters
dict: dictionary containing the controller parameters
float: starting time
float: end time
"""
# initialize level parameters
level_params = {}
level_params['restol'] = 5e-10
level_params['dt'] = 0.125
# 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'] = 2 # frequency for the test value
problem_params['nvars'] = 63 # number of degrees of freedom for each level
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = {}
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = {}
controller_params['logger_level'] = 30
# fill description dictionary for easy step instantiation
description = {}
description['problem_class'] = heatNd_unforced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
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
# set time parameters
t0 = 0.0
Tend = 1.0
return description, controller_params, t0, Tend
if __name__ == "__main__":
main(num_proc_list=[1], fname='step_6_A_sl_out.txt', multi_level=False)
main(num_proc_list=[1, 2, 4, 8], fname='step_6_A_ml_out.txt', multi_level=True)
| 6,654 | 34.588235 | 120 | py |
pySDC | pySDC-master/pySDC/tutorial/step_6/C_MPI_parallelization.py | import os
import subprocess
def main(cwd):
"""
A simple test program to test MPI-parallel PFASST controllers
Args:
cwd: current working directory
"""
# try to import MPI here, will fail if things go wrong (and not in the subprocess part)
try:
import mpi4py
del mpi4py
except ImportError:
raise ImportError('petsc tests need mpi4py')
# Set python path once
my_env = os.environ.copy()
my_env['PYTHONPATH'] = '../../..:.'
my_env['COVERAGE_PROCESS_START'] = 'pyproject.toml'
# set list of number of parallel steps (even)
num_procs_list = [1, 2, 4, 8]
# set up new/empty file for output
fname = 'step_6_C1_out.txt'
f = open(cwd + '/../../../data/' + fname, 'w')
f.close()
# run code with different number of MPI processes
for num_procs in num_procs_list:
print('Running code with %2i processes...' % num_procs)
cmd = (
'mpirun -np ' + str(num_procs) + ' python playground_parallelization.py ../../../../data/' + fname
).split()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env, cwd=cwd)
# while True:
# line = p.stdout.readline()
# print(line)
# if not line: break
p.wait()
assert p.returncode == 0, 'ERROR: did not get return code 0, got %s with %2i processes' % (
p.returncode,
num_procs,
)
# set list of number of parallel steps (odd)
num_procs_list = [3, 5, 7, 9]
# set up new/empty file for output
fname = 'step_6_C2_out.txt'
f = open(cwd + '/../../../data/' + fname, 'w')
f.close()
# run code with different number of MPI processes
for num_procs in num_procs_list:
print('Running code with %2i processes...' % num_procs)
cmd = (
'mpirun -np ' + str(num_procs) + ' python playground_parallelization.py ../../../../data/' + fname
).split()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env, cwd=cwd)
# while True:
# line = p.stdout.readline()
# print(line)
# if not line: break
p.wait()
assert p.returncode == 0, 'ERROR: did not get return code 0, got %s with %2i processes' % (
p.returncode,
num_procs,
)
if __name__ == "__main__":
main('.')
| 2,442 | 30.320513 | 110 | py |
pySDC | pySDC-master/pySDC/tutorial/step_6/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/tutorial/step_6/B_odd_temporal_distribution.py | from pySDC.tutorial.step_6.A_run_non_MPI_controller import main as main_A
def main():
"""
A simple test program to do check PFASST for odd numbers of processes
"""
main_A(num_proc_list=[3, 5, 7, 9], fname='step_6_B_out.txt', multi_level=True)
if __name__ == "__main__":
main()
| 301 | 22.230769 | 82 | py |
pySDC | pySDC-master/pySDC/tutorial/step_6/playground_parallelization.py | import sys
from pathlib import Path
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.tutorial.step_6.A_run_non_MPI_controller import set_parameters_ml
if __name__ == "__main__":
"""
A simple test program to do MPI-parallel PFASST runs
"""
# set MPI communicator
comm = MPI.COMM_WORLD
# get parameters from Part A
description, controller_params, t0, Tend = set_parameters_ml()
# instantiate controllers
controller = controller_MPI(controller_params=controller_params, description=description, comm=comm)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# call main functions 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')
# combine statistics into list of statistics
iter_counts_list = comm.gather(iter_counts, root=0)
rank = comm.Get_rank()
size = comm.Get_size()
if rank == 0:
# we'd need to deal with variable file names here (for testing purpose only)
if len(sys.argv) == 2:
fname = sys.argv[1]
else:
fname = 'step_6_B_out.txt'
Path("data").mkdir(parents=True, exist_ok=True)
f = open('data/' + fname, 'a')
out = 'Working with %2i processes...' % size
f.write(out + '\n')
print(out)
# compute exact solutions and compare with both results
uex = P.u_exact(Tend)
err = abs(uex - uend)
out = 'Error vs. exact solution: %12.8e' % err
f.write(out + '\n')
print(out)
# build one list of statistics instead of list of lists, the sort by time
iter_counts_gather = [item for sublist in iter_counts_list for item in sublist]
iter_counts = sorted(iter_counts_gather, key=lambda tup: tup[0])
# compute and print statistics
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %1i ' % (item[0], item[1])
f.write(out + '\n')
print(out)
f.write('\n')
print()
assert all(item[1] <= 8 for item in iter_counts), "ERROR: weird iteration counts, got %s" % iter_counts
| 2,409 | 31.567568 | 111 | py |
pySDC | pySDC-master/pySDC/implementations/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/implementations/datatype_classes/cupy_mesh.py | import cupy as cp
from pySDC.core.Errors import DataError
try:
from mpi4py import MPI
except ImportError:
MPI = None
class cupy_mesh(cp.ndarray):
"""
CuPy-based datatype for serial or parallel meshes.
"""
def __new__(cls, init, val=0.0, offset=0, buffer=None, strides=None, order=None):
"""
Instantiates new datatype. This ensures that even when manipulating data, the result is still a mesh.
Args:
init: either another mesh or a tuple containing the dimensions, the communicator and the dtype
val: value to initialize
Returns:
obj of type mesh
"""
if isinstance(init, cupy_mesh):
obj = cp.ndarray.__new__(cls, shape=init.shape, dtype=init.dtype, strides=strides, order=order)
obj[:] = init[:]
obj._comm = init._comm
elif (
isinstance(init, tuple)
and (init[1] is None or isinstance(init[1], MPI.Intracomm))
and isinstance(init[2], cp.dtype)
):
obj = cp.ndarray.__new__(cls, init[0], dtype=init[2], strides=strides, order=order)
obj.fill(val)
obj._comm = init[1]
else:
raise NotImplementedError(type(init))
return obj
@property
def comm(self):
"""
Getter for the communicator
"""
return self._comm
def __array_finalize__(self, obj):
"""
Finalizing the datatype. Without this, new datatypes do not 'inherit' the communicator.
"""
if obj is None:
return
self._comm = getattr(obj, '_comm', None)
def __array_ufunc__(self, ufunc, method, *inputs, out=None, **kwargs):
"""
Overriding default ufunc, cf. https://numpy.org/doc/stable/user/basics.subclassing.html#array-ufunc-for-ufuncs
"""
args = []
comm = None
for _, input_ in enumerate(inputs):
if isinstance(input_, cupy_mesh):
args.append(input_.view(cp.ndarray))
comm = input_.comm
else:
args.append(input_)
results = super(cupy_mesh, self).__array_ufunc__(ufunc, method, *args, **kwargs).view(cupy_mesh)
if not method == 'reduce':
results._comm = comm
return results
def __abs__(self):
"""
Overloading the abs operator
Returns:
float: absolute maximum of all mesh values
"""
# take absolute values of the mesh values
local_absval = float(cp.amax(cp.ndarray.__abs__(self)))
if self.comm is not None:
if self.comm.Get_size() > 1:
global_absval = 0.0
global_absval = max(self.comm.allreduce(sendobj=local_absval, op=MPI.MAX), global_absval)
else:
global_absval = local_absval
else:
global_absval = local_absval
return float(global_absval)
def isend(self, dest=None, tag=None, comm=None):
"""
Routine for sending data forward in time (non-blocking)
Args:
dest (int): target rank
tag (int): communication tag
comm: communicator
Returns:
request handle
"""
return comm.Issend(self[:], dest=dest, tag=tag)
def irecv(self, source=None, tag=None, comm=None):
"""
Routine for receiving in time
Args:
source (int): source rank
tag (int): communication tag
comm: communicator
Returns:
None
"""
return comm.Irecv(self[:], source=source, tag=tag)
def bcast(self, root=None, comm=None):
"""
Routine for broadcasting values
Args:
root (int): process with value to broadcast
comm: communicator
Returns:
broadcasted values
"""
comm.Bcast(self[:], root=root)
return self
class imex_cupy_mesh(object):
"""
RHS data type for cupy_meshes with implicit and explicit components
This data type can be used to have RHS with 2 components (here implicit and explicit)
Attributes:
impl (cupy_mesh.cupy_mesh): implicit part
expl (cupy_mesh.cupy_mesh): explicit part
"""
def __init__(self, init, val=0.0):
"""
Initialization routine
Args:
init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested)
or another imex_cupy_mesh object
val (float): an initial number (default: 0.0)
Raises:
DataError: if init is none of the types above
"""
if isinstance(init, type(self)):
self.impl = cupy_mesh(init.impl)
self.expl = cupy_mesh(init.expl)
elif (
isinstance(init, tuple)
and (init[1] is None or isinstance(init[1], MPI.Intracomm))
and isinstance(init[2], cp.dtype)
):
self.impl = cupy_mesh(init, val=val)
self.expl = cupy_mesh(init, val=val)
# something is wrong, if none of the ones above hit
else:
raise DataError('something went wrong during %s initialization' % type(self))
class comp2_cupy_mesh(object):
"""
RHS data type for cupy_meshes with 2 components
Attributes:
comp1 (cupy_mesh.cupy_mesh): first part
comp2 (cupy_mesh.cupy_mesh): second part
"""
def __init__(self, init, val=0.0):
"""
Initialization routine
Args:
init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested)
or another comp2_mesh object
Raises:
DataError: if init is none of the types above
"""
if isinstance(init, type(self)):
self.comp1 = cupy_mesh(init.comp1)
self.comp2 = cupy_mesh(init.comp2)
elif (
isinstance(init, tuple)
and (init[1] is None or isinstance(init[1], MPI.Intracomm))
and isinstance(init[2], cp.dtype)
):
self.comp1 = cupy_mesh(init, val=val)
self.comp2 = cupy_mesh(init, val=val)
# something is wrong, if none of the ones above hit
else:
raise DataError('something went wrong during %s initialization' % type(self))
| 6,456 | 29.747619 | 118 | py |
pySDC | pySDC-master/pySDC/implementations/datatype_classes/fenics_mesh.py | import dolfin as df
from pySDC.core.Errors import DataError
class fenics_mesh(object):
"""
FEniCS Function data type with arbitrary dimensions
Attributes:
values (np.ndarray): contains the ndarray of the values
"""
def __init__(self, init=None, val=0.0):
"""
Initialization routine
Args:
init: can either be a FunctionSpace or another fenics_mesh object
val: initial value (default: 0.0)
Raises:
DataError: if init is none of the types above
"""
# if init is another fenic_mesh, do a deepcopy (init by copy)
if isinstance(init, type(self)):
self.values = init.values.copy(deepcopy=True)
# if init is FunctionSpace, create mesh object with val as initial value
elif isinstance(init, df.Function):
self.values = init.copy(deepcopy=True)
elif isinstance(init, df.FunctionSpace):
self.values = df.Function(init)
self.values.vector()[:] = val
else:
raise DataError('something went wrong during %s initialization' % type(init))
def __add__(self, other):
"""
Overloading the addition operator for mesh types
Args:
other (fenics_mesh): mesh object to be added
Raises:
DataError: if other is not a mesh object
Returns:
fenics_mesh: sum of caller and other values (self+other)
"""
if isinstance(other, type(self)):
# always create new mesh, since otherwise c = a + b changes a as well!
me = fenics_mesh(other)
me.values.vector()[:] = self.values.vector()[:] + other.values.vector()[:]
return me
else:
raise DataError("Type error: cannot add %s to %s" % (type(other), type(self)))
def __sub__(self, other):
"""
Overloading the subtraction operator for mesh types
Args:
other (fenics_mesh): mesh object to be subtracted
Raises:
DataError: if other is not a mesh object
Returns:
fenics_mesh: differences between caller and other values (self-other)
"""
if isinstance(other, type(self)):
# always create new mesh, since otherwise c = a - b changes a as well!
me = fenics_mesh(other)
me.values.vector()[:] = self.values.vector()[:] - other.values.vector()[:]
return me
else:
raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self)))
def __rmul__(self, other):
"""
Overloading the right multiply by factor operator for mesh types
Args:
other (float): factor
Raises:
DataError: is other is not a float
Returns:
fenics_mesh: copy of original values scaled by factor
"""
if isinstance(other, float):
# always create new mesh, since otherwise c = f*a changes a as well!
me = fenics_mesh(self)
me.values.vector()[:] = other * self.values.vector()[:]
return me
else:
raise DataError("Type error: cannot multiply %s to %s" % (type(other), type(self)))
def __abs__(self):
"""
Overloading the abs operator for mesh types
Returns:
float: absolute maximum of all mesh values
"""
# take absolute values of the mesh values
absval = df.norm(self.values, 'L2')
# return maximum
return absval
class rhs_fenics_mesh(object):
"""
RHS data type for fenics_meshes with implicit and explicit components
This data type can be used to have RHS with 2 components (here implicit and explicit)
Attributes:
impl (fenics_mesh): implicit part
expl (fenics_mesh): explicit part
"""
def __init__(self, init, val=0.0):
"""
Initialization routine
Args:
init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested)
or another rhs_imex_mesh object
val (float): an initial number (default: 0.0)
Raises:
DataError: if init is none of the types above
"""
# if init is another rhs_imex_mesh, do a deepcopy (init by copy)
if isinstance(init, type(self)):
self.impl = fenics_mesh(init.impl)
self.expl = fenics_mesh(init.expl)
# if init is a number or a tuple of numbers, create mesh object with None as initial value
elif isinstance(init, df.FunctionSpace):
self.impl = fenics_mesh(init, val=val)
self.expl = fenics_mesh(init, val=val)
# something is wrong, if none of the ones above hit
else:
raise DataError('something went wrong during %s initialization' % type(self))
def __sub__(self, other):
"""
Overloading the subtraction operator for rhs types
Args:
other (rhs_fenics_mesh): rhs object to be subtracted
Raises:
DataError: if other is not a rhs object
Returns:
rhs_fenics_mesh: differences between caller and other values (self-other)
"""
if isinstance(other, rhs_fenics_mesh):
# always create new rhs_imex_mesh, since otherwise c = a - b changes a as well!
me = rhs_fenics_mesh(self)
me.impl = self.impl - other.impl
me.expl = self.expl - other.expl
return me
else:
raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self)))
def __add__(self, other):
"""
Overloading the addition operator for rhs types
Args:
other (rhs_fenics_mesh): rhs object to be added
Raises:
DataError: if other is not a rhs object
Returns:
rhs_fenics_mesh: sum of caller and other values (self-other)
"""
if isinstance(other, rhs_fenics_mesh):
# always create new rhs_imex_mesh, since otherwise c = a + b changes a as well!
me = rhs_fenics_mesh(self)
me.impl = self.impl + other.impl
me.expl = self.expl + other.expl
return me
else:
raise DataError("Type error: cannot add %s to %s" % (type(other), type(self)))
def __rmul__(self, other):
"""
Overloading the right multiply by factor operator for mesh types
Args:
other (float): factor
Raises:
DataError: is other is not a float
Returns:
rhs_fenics_mesh: copy of original values scaled by factor
"""
if isinstance(other, float):
# always create new mesh, since otherwise c = f*a changes a as well!
me = rhs_fenics_mesh(self)
me.impl = other * self.impl
me.expl = other * self.expl
return me
else:
raise DataError("Type error: cannot multiply %s to %s" % (type(other), type(self)))
| 7,142 | 33.341346 | 112 | py |
pySDC | pySDC-master/pySDC/implementations/datatype_classes/__init__.py | __author__ = 'robert'
| 22 | 10.5 | 21 | py |
pySDC | pySDC-master/pySDC/implementations/datatype_classes/petsc_vec.py | from petsc4py import PETSc
from pySDC.core.Errors import DataError
class petsc_vec(PETSc.Vec):
__array_priority__ = 1000 # otherwise rmul with float64 does not work (don't ask, won't tell)
def __new__(cls, init=None, val=0.0):
if isinstance(init, petsc_vec) or isinstance(init, PETSc.Vec):
obj = PETSc.Vec.__new__(cls)
init.copy(obj)
elif isinstance(init, PETSc.DMDA):
tmp = init.createGlobalVector()
obj = petsc_vec(tmp)
objarr = init.getVecArray(obj)
objarr[:] = val
else:
obj = PETSc.Vec.__new__(cls)
return obj
def __abs__(self):
"""
Overloading the abs operator
Returns:
float: absolute maximum of all vec values
"""
# take absolute values of the mesh values (INF = 3)
return self.norm(3)
def isend(self, dest=None, tag=None, comm=None):
"""
Routine for sending data forward in time (non-blocking)
Args:
dest (int): target rank
tag (int): communication tag
comm: communicator
Returns:
request handle
"""
return comm.Issend(self.getArray(), dest=dest, tag=tag)
def irecv(self, source=None, tag=None, comm=None):
"""
Routine for receiving in time
Args:
source (int): source rank
tag (int): communication tag
comm: communicator
Returns:
None
"""
return comm.Irecv(self.getArray(), source=source, tag=tag)
def bcast(self, root=None, comm=None):
"""
Routine for broadcasting values
Args:
root (int): process with value to broadcast
comm: communicator
Returns:
broadcasted values
"""
comm.Bcast(self.getArray(), root=root)
return self
class petsc_vec_imex(object):
"""
RHS data type for Vec with implicit and explicit components
This data type can be used to have RHS with 2 components (here implicit and explicit)
Attributes:
impl (petsc_vec): implicit part
expl (petsc_vec): explicit part
"""
def __init__(self, init, val=0.0):
"""
Initialization routine
Args:
init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested)
or another imex_mesh object
val (float): an initial number (default: 0.0)
Raises:
DataError: if init is none of the types above
"""
if isinstance(init, type(self)):
self.impl = petsc_vec(init.impl)
self.expl = petsc_vec(init.expl)
elif isinstance(init, PETSc.DMDA):
self.impl = petsc_vec(init, val=val)
self.expl = petsc_vec(init, val=val)
# something is wrong, if none of the ones above hit
else:
raise DataError('something went wrong during %s initialization' % type(self))
class petsc_vec_comp2(object):
"""
RHS data type for Vec with implicit and explicit components
This data type can be used to have RHS with 2 components (here implicit and explicit)
Attributes:
impl (petsc_vec): implicit part
expl (petsc_vec): explicit part
"""
def __init__(self, init, val=0.0):
"""
Initialization routine
Args:
init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested)
or another imex_mesh object
val (float): an initial number (default: 0.0)
Raises:
DataError: if init is none of the types above
"""
if isinstance(init, type(self)):
self.comp1 = petsc_vec(init.comp1)
self.comp2 = petsc_vec(init.comp2)
elif isinstance(init, PETSc.DMDA):
self.comp1 = petsc_vec(init, val=val)
self.comp2 = petsc_vec(init, val=val)
# something is wrong, if none of the ones above hit
else:
raise DataError('something went wrong during %s initialization' % type(self))
| 4,217 | 28.914894 | 112 | py |
pySDC | pySDC-master/pySDC/implementations/datatype_classes/mesh.py | import numpy as np
from pySDC.core.Errors import DataError
try:
# TODO : mpi4py cannot be imported before dolfin when using fenics mesh
# see https://github.com/Parallel-in-Time/pySDC/pull/285#discussion_r1145850590
# This should be dealt with at some point
from mpi4py import MPI
except ImportError:
MPI = None
class mesh(np.ndarray):
"""
Numpy-based datatype for serial or parallel meshes.
Can include a communicator and expects a dtype to allow complex data.
Attributes:
_comm: MPI communicator or None
"""
def __new__(cls, init, val=0.0, offset=0, buffer=None, strides=None, order=None):
"""
Instantiates new datatype. This ensures that even when manipulating data, the result is still a mesh.
Args:
init: either another mesh or a tuple containing the dimensions, the communicator and the dtype
val: value to initialize
Returns:
obj of type mesh
"""
if isinstance(init, mesh):
obj = np.ndarray.__new__(
cls, shape=init.shape, dtype=init.dtype, buffer=buffer, offset=offset, strides=strides, order=order
)
obj[:] = init[:]
obj._comm = init._comm
elif (
isinstance(init, tuple)
and (init[1] is None or isinstance(init[1], MPI.Intracomm))
and isinstance(init[2], np.dtype)
):
obj = np.ndarray.__new__(
cls, init[0], dtype=init[2], buffer=buffer, offset=offset, strides=strides, order=order
)
obj.fill(val)
obj._comm = init[1]
else:
raise NotImplementedError(type(init))
return obj
@property
def comm(self):
"""
Getter for the communicator
"""
return self._comm
def __array_finalize__(self, obj):
"""
Finalizing the datatype. Without this, new datatypes do not 'inherit' the communicator.
"""
if obj is None:
return
self._comm = getattr(obj, '_comm', None)
def __array_ufunc__(self, ufunc, method, *inputs, out=None, **kwargs):
"""
Overriding default ufunc, cf. https://numpy.org/doc/stable/user/basics.subclassing.html#array-ufunc-for-ufuncs
"""
args = []
comm = None
for _, input_ in enumerate(inputs):
if isinstance(input_, mesh):
args.append(input_.view(np.ndarray))
comm = input_.comm
else:
args.append(input_)
results = super(mesh, self).__array_ufunc__(ufunc, method, *args, **kwargs).view(mesh)
if not method == 'reduce':
results._comm = comm
return results
def __abs__(self):
"""
Overloading the abs operator
Returns:
float: absolute maximum of all mesh values
"""
# take absolute values of the mesh values
local_absval = float(np.amax(np.ndarray.__abs__(self)))
if self.comm is not None:
if self.comm.Get_size() > 1:
global_absval = 0.0
global_absval = max(self.comm.allreduce(sendobj=local_absval, op=MPI.MAX), global_absval)
else:
global_absval = local_absval
else:
global_absval = local_absval
return float(global_absval)
def isend(self, dest=None, tag=None, comm=None):
"""
Routine for sending data forward in time (non-blocking)
Args:
dest (int): target rank
tag (int): communication tag
comm: communicator
Returns:
request handle
"""
return comm.Issend(self[:], dest=dest, tag=tag)
def irecv(self, source=None, tag=None, comm=None):
"""
Routine for receiving in time
Args:
source (int): source rank
tag (int): communication tag
comm: communicator
Returns:
None
"""
return comm.Irecv(self[:], source=source, tag=tag)
def bcast(self, root=None, comm=None):
"""
Routine for broadcasting values
Args:
root (int): process with value to broadcast
comm: communicator
Returns:
broadcasted values
"""
comm.Bcast(self[:], root=root)
return self
class imex_mesh(object):
"""
RHS data type for meshes with implicit and explicit components
This data type can be used to have RHS with 2 components (here implicit and explicit)
Attributes:
impl (mesh.mesh): implicit part
expl (mesh.mesh): explicit part
"""
def __init__(self, init, val=0.0):
"""
Initialization routine
Args:
init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested)
or another imex_mesh object
val (float): an initial number (default: 0.0)
Raises:
DataError: if init is none of the types above
"""
if isinstance(init, type(self)):
self.impl = mesh(init.impl)
self.expl = mesh(init.expl)
elif (
isinstance(init, tuple)
and (init[1] is None or isinstance(init[1], MPI.Intracomm))
and isinstance(init[2], np.dtype)
):
self.impl = mesh(init, val=val)
self.expl = mesh(init, val=val)
# something is wrong, if none of the ones above hit
else:
raise DataError('something went wrong during %s initialization' % type(self))
class comp2_mesh(object):
"""
RHS data type for meshes with 2 components
Attributes:
comp1 (mesh.mesh): first part
comp2 (mesh.mesh): second part
"""
def __init__(self, init, val=0.0):
"""
Initialization routine
Args:
init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested)
or another comp2_mesh object
Raises:
DataError: if init is none of the types above
"""
if isinstance(init, type(self)):
self.comp1 = mesh(init.comp1)
self.comp2 = mesh(init.comp2)
elif (
isinstance(init, tuple)
and (init[1] is None or isinstance(init[1], MPI.Intracomm))
and isinstance(init[2], np.dtype)
):
self.comp1 = mesh(init, val=val)
self.comp2 = mesh(init, val=val)
# something is wrong, if none of the ones above hit
else:
raise DataError('something went wrong during %s initialization' % type(self))
| 6,786 | 29.572072 | 118 | py |
pySDC | pySDC-master/pySDC/implementations/datatype_classes/particles.py | import numpy as np
from pySDC.implementations.datatype_classes.mesh import mesh
from pySDC.core.Errors import DataError
try:
from mpi4py import MPI
except ImportError:
MPI = None
class particles(object):
"""
Particle data type for particles in 3 dimensions
This data type can be used for particles in 3 dimensions with 3 position and 3 velocity values per particle
Attributes:
pos: contains the positions of all particles
vel: contains the velocities of all particles
"""
class position(mesh):
pass
class velocity(mesh):
pass
def __init__(self, init=None, val=None):
"""
Initialization routine
Args:
init: can either be a number or another particle object
val: initial tuple of values for position and velocity (default: (None,None))
Raises:
DataError: if init is none of the types above
"""
# if init is another particles object, do a copy (init by copy)
if isinstance(init, type(self)):
self.pos = particles.position(init.pos)
self.vel = particles.velocity(init.vel)
self.q = init.q.copy()
self.m = init.m.copy()
# if init is a number, create particles object and pick the corresponding initial values
elif (
isinstance(init, tuple)
and (init[1] is None or isinstance(init[1], MPI.Intracomm))
and isinstance(init[2], np.dtype)
):
if isinstance(val, int) or isinstance(val, float) or val is None:
self.pos = particles.position(init, val=val)
self.vel = particles.velocity(init, val=val)
if isinstance(init[0], tuple):
self.q = np.zeros(init[0][-1])
self.m = np.zeros(init[0][-1])
elif isinstance(init[0], int):
self.q = np.zeros(init[0])
self.m = np.zeros(init[0])
self.q[:] = 1.0
self.m[:] = 1.0
elif isinstance(val, tuple) and len(val) == 4:
self.pos = particles.position(init, val=val[0])
self.vel = particles.velocity(init, val=val[1])
if isinstance(init[0], tuple):
self.q = np.zeros(init[0][-1])
self.m = np.zeros(init[0][-1])
elif isinstance(init[0], int):
self.q = np.zeros(init[0])
self.m = np.zeros(init[0])
self.q[:] = val[2]
self.m[:] = val[3]
else:
raise DataError('type of val is wrong, got %s', val)
# something is wrong, if none of the ones above hit
else:
raise DataError('something went wrong during %s initialization' % type(self))
def __add__(self, other):
"""
Overloading the addition operator for particles types
Args:
other (particles): particles object to be added
Raises:
DataError: if other is not a particles object
Returns:
particles: sum of caller and other values (self+other)
"""
if isinstance(other, type(self)):
# always create new particles, since otherwise c = a + b changes a as well!
p = particles(self)
p.pos[:] = self.pos + other.pos
p.vel[:] = self.vel + other.vel
p.m = self.m
p.q = self.q
return p
else:
raise DataError("Type error: cannot add %s to %s" % (type(other), type(self)))
def __sub__(self, other):
"""
Overloading the subtraction operator for particles types
Args:
other (particles): particles object to be subtracted
Raises:
DataError: if other is not a particles object
Returns:
particles: differences between caller and other values (self-other)
"""
if isinstance(other, type(self)):
# always create new particles, since otherwise c = a - b changes a as well!
p = particles(self)
p.pos[:] = self.pos - other.pos
p.vel[:] = self.vel - other.vel
p.m = self.m
p.q = self.q
return p
else:
raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self)))
def __rmul__(self, other):
"""
Overloading the right multiply by factor operator for particles types
Args:
other (float): factor
Raises:
DataError: if other is not a particles object
Returns:
particles: scaled particle's velocity and position as new particle
"""
if isinstance(other, float):
# always create new particles
p = particles(self)
p.pos[:] = other * self.pos
p.vel[:] = other * self.vel
p.m = self.m
p.q = self.q
return p
else:
raise DataError("Type error: cannot multiply %s to %s" % (type(other), type(self)))
def __abs__(self):
"""
Overloading the abs operator for particles types
Returns:
float: absolute maximum of abs(pos) and abs(vel) for all particles
"""
abspos = abs(self.pos)
absvel = abs(self.vel)
return np.amax((abspos, absvel))
def send(self, dest=None, tag=None, comm=None):
"""
Routine for sending data forward in time (blocking)
Args:
dest (int): target rank
tag (int): communication tag
comm: communicator
Returns:
None
"""
comm.send(self, dest=dest, tag=tag)
return None
def isend(self, dest=None, tag=None, comm=None):
"""
Routine for sending data forward in time (non-blocking)
Args:
dest (int): target rank
tag (int): communication tag
comm: communicator
Returns:
request handle
"""
return comm.isend(self, dest=dest, tag=tag)
def recv(self, source=None, tag=None, comm=None):
"""
Routine for receiving in time
Args:
source (int): source rank
tag (int): communication tag
comm: communicator
Returns:
None
"""
part = comm.recv(source=source, tag=tag)
self.pos[:] = part.pos.copy()
self.vel[:] = part.vel.copy()
self.m = part.m.copy()
self.q = part.q.copy()
return None
class acceleration(mesh):
pass
class fields(object):
"""
Field data type for 3 dimensions
This data type can be used for electric and magnetic fields in 3 dimensions
Attributes:
elec: contains the electric field
magn: contains the magnetic field
"""
class electric(mesh):
pass
class magnetic(mesh):
pass
def __init__(self, init=None, val=None):
"""
Initialization routine
Args:
init: can either be a number or another fields object
val: initial tuple of values for electric and magnetic (default: (None,None))
Raises:
DataError: if init is none of the types above
"""
# if init is another fields object, do a copy (init by copy)
if isinstance(init, type(self)):
self.elec = fields.electric(init.elec)
self.magn = fields.magnetic(init.magn)
# if init is a number, create fields object and pick the corresponding initial values
elif (
isinstance(init, tuple)
and (init[1] is None or isinstance(init[1], MPI.Intracomm))
and isinstance(init[2], np.dtype)
):
if isinstance(val, int) or isinstance(val, float) or val is None:
self.elec = fields.electric(init, val=val)
self.magn = fields.magnetic(init, val=val)
elif isinstance(val, tuple) and len(val) == 2:
self.elec = fields.electric(init, val=val[0])
self.magn = fields.magnetic(init, val=val[1])
else:
raise DataError('wrong type of val, got %s' % val)
# something is wrong, if none of the ones above hit
else:
raise DataError('something went wrong during %s initialization' % type(self))
def __add__(self, other):
"""
Overloading the addition operator for fields types
Args:
other (fields): fields object to be added
Raises:
DataError: if other is not a fields object
Returns:
fields: sum of caller and other values (self+other)
"""
if isinstance(other, type(self)):
# always create new fields, since otherwise c = a - b changes a as well!
p = fields(self)
p.elec[:] = self.elec + other.elec
p.magn[:] = self.magn + other.magn
return p
else:
raise DataError("Type error: cannot add %s to %s" % (type(other), type(self)))
def __sub__(self, other):
"""
Overloading the subtraction operator for fields types
Args:
other (fields): fields object to be subtracted
Raises:
DataError: if other is not a fields object
Returns:
fields: differences between caller and other values (self-other)
"""
if isinstance(other, type(self)):
# always create new fields, since otherwise c = a - b changes a as well!
p = fields(self)
p.elec[:] = self.elec - other.elec
p.magn[:] = self.magn - other.magn
return p
else:
raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self)))
def __rmul__(self, other):
"""
Overloading the multiply with factor from right operator for fields types
Args:
other (float): factor
Raises:
DataError: if other is not a fields object
Returns:
fields: scaled fields
"""
if isinstance(other, float):
# always create new fields, since otherwise c = a - b changes a as well!
p = fields(self)
p.elec[:] = other * self.elec
p.magn[:] = other * self.magn
return p
else:
raise DataError("Type error: cannot multiply %s with %s" % (type(other), type(self)))
| 10,653 | 31.680982 | 111 | py |
pySDC | pySDC-master/pySDC/implementations/controller_classes/controller_nonMPI.py | import itertools
import copy as cp
import numpy as np
import dill
from pySDC.core.Controller import controller
from pySDC.core import Step as stepclass
from pySDC.core.Errors import ControllerError, CommunicationError
from pySDC.implementations.convergence_controller_classes.basic_restarting import BasicRestarting
class controller_nonMPI(controller):
"""
PFASST controller, running serialized version of PFASST in blocks (MG-style)
"""
def __init__(self, num_procs, controller_params, description):
"""
Initialization routine for PFASST controller
Args:
num_procs: number of parallel time steps (still serial, though), can be 1
controller_params: parameter set for the controller and the steps
description: all the parameters to set up the rest (levels, problems, transfer, ...)
"""
if 'predict' in controller_params:
raise ControllerError('predict flag is ignored, use predict_type instead')
# call parent's initialization routine
super().__init__(controller_params, description, useMPI=False)
self.MS = [stepclass.step(description)]
# try to initialize via dill.copy (much faster for many time-steps)
try:
for _ in range(num_procs - 1):
self.MS.append(dill.copy(self.MS[0]))
# if this fails (e.g. due to un-picklable data in the steps), initialize seperately
except (dill.PicklingError, TypeError):
self.logger.warning('Need to initialize steps separately due to pickling error')
for _ in range(num_procs - 1):
self.MS.append(stepclass.step(description))
self.base_convergence_controllers += [BasicRestarting.get_implementation("nonMPI")]
for convergence_controller in self.base_convergence_controllers:
self.add_convergence_controller(convergence_controller, description)
if self.params.dump_setup:
self.dump_setup(step=self.MS[0], controller_params=controller_params, description=description)
if num_procs > 1 and len(self.MS[0].levels) > 1:
for S in self.MS:
for L in S.levels:
if not L.sweep.coll.right_is_node:
raise ControllerError("For PFASST to work, we assume uend^k = u_M^k")
if all(len(S.levels) == len(self.MS[0].levels) for S in self.MS):
self.nlevels = len(self.MS[0].levels)
else:
raise ControllerError('all steps need to have the same number of levels')
if self.nlevels == 0:
raise ControllerError('need at least one level')
self.nsweeps = []
for nl in range(self.nlevels):
if all(S.levels[nl].params.nsweeps == self.MS[0].levels[nl].params.nsweeps for S in self.MS):
self.nsweeps.append(self.MS[0].levels[nl].params.nsweeps)
if self.nlevels > 1 and self.nsweeps[-1] > 1:
raise ControllerError('this controller cannot do multiple sweeps on coarsest level')
if self.nlevels == 1 and self.params.predict_type is not None:
self.logger.warning(
'you have specified a predictor type but only a single level.. predictor will be ignored'
)
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.reset_buffers_nonMPI(self)
C.setup_status_variables(self, MS=self.MS)
def run(self, u0, t0, Tend):
"""
Main driver for running the serial version of SDC, MSSDC, MLSDC and PFASST (virtual parallelism)
Args:
u0: initial values
t0: starting time
Tend: ending time
Returns:
end values on the finest level
stats object containing statistics for each step, each level and each iteration
"""
# some initializations and reset of statistics
uend = None
num_procs = len(self.MS)
for hook in self.hooks:
hook.reset_stats()
# initial ordering of the steps: 0,1,...,Np-1
slots = list(range(num_procs))
# initialize time variables of each step
time = [t0 + sum(self.MS[j].dt for j in range(p)) for p in slots]
# determine which steps are still active (time < Tend)
active = [time[p] < Tend - 10 * np.finfo(float).eps for p in slots]
if not any(active):
raise ControllerError('Nothing to do, check t0, dt and Tend.')
# compress slots according to active steps, i.e. remove all steps which have times above Tend
active_slots = list(itertools.compress(slots, active))
# initialize block of steps with u0
self.restart_block(active_slots, time, u0)
for hook in self.hooks:
hook.post_setup(step=None, level_number=None)
# call pre-run hook
for S in self.MS:
for hook in self.hooks:
hook.pre_run(step=S, level_number=0)
# main loop: as long as at least one step is still active (time < Tend), do something
while any(active):
MS_active = [self.MS[p] for p in active_slots]
done = False
while not done:
done = self.pfasst(MS_active)
restarts = [S.status.restart for S in MS_active]
restart_at = np.where(restarts)[0][0] if True in restarts else len(MS_active)
if True in restarts: # restart part of the block
# initial condition to next block is initial condition of step that needs restarting
uend = self.MS[restart_at].levels[0].u[0]
time[active_slots[0]] = time[restart_at]
self.logger.info(f'Starting next block with initial conditions from step {restart_at}')
else: # move on to next block
# initial condition for next block is last solution of current block
uend = self.MS[active_slots[-1]].levels[0].uend
time[active_slots[0]] = time[active_slots[-1]] + self.MS[active_slots[-1]].dt
for S in MS_active[:restart_at]:
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.post_step_processing(self, S)
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
[C.prepare_next_block(self, S, len(active_slots), time, Tend, MS=MS_active) for S in self.MS]
# setup the times of the steps for the next block
for i in range(1, len(active_slots)):
time[active_slots[i]] = time[active_slots[i] - 1] + self.MS[active_slots[i] - 1].dt
# determine new set of active steps and compress slots accordingly
active = [time[p] < Tend - 10 * np.finfo(float).eps for p in slots]
active_slots = list(itertools.compress(slots, active))
# restart active steps (reset all values and pass uend to u0)
self.restart_block(active_slots, time, uend)
# call post-run hook
for S in self.MS:
for hook in self.hooks:
hook.post_run(step=S, level_number=0)
return uend, self.return_stats()
def restart_block(self, active_slots, time, u0):
"""
Helper routine to reset/restart block of (active) steps
Args:
active_slots: list of active steps
time: list of new times
u0: initial value to distribute across the steps
"""
# loop over active slots (not directly, since we need the previous entry as well)
for j in range(len(active_slots)):
# get slot number
p = active_slots[j]
# store current slot number for diagnostics
self.MS[p].status.slot = p
# store link to previous step
self.MS[p].prev = self.MS[active_slots[j - 1]]
# resets step
self.MS[p].reset_step()
# determine whether I am the first and/or last in line
self.MS[p].status.first = active_slots.index(p) == 0
self.MS[p].status.last = active_slots.index(p) == len(active_slots) - 1
# initialize step with u0
self.MS[p].init_step(u0)
# reset some values
self.MS[p].status.done = False
self.MS[p].status.prev_done = False
self.MS[p].status.iter = 0
self.MS[p].status.stage = 'SPREAD'
self.MS[p].status.force_done = False
self.MS[p].status.time_size = len(active_slots)
for l in self.MS[p].levels:
l.tag = None
l.status.sweep = 1
for p in active_slots:
for lvl in self.MS[p].levels:
lvl.status.time = time[p]
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.reset_status_variables(self, active_slots=active_slots)
def send_full(self, S, level=None, add_to_stats=False):
"""
Function to perform the send, including bookkeeping and logging
Args:
S: the current step
level: the level number
add_to_stats: a flag to end recording data in the hooks (defaults to False)
"""
def send(source, tag):
"""
Send function
Args:
source: level which has the new values
tag: identifier for this message
"""
# sending here means computing uend ("one-sided communication")
source.sweep.compute_end_point()
source.tag = cp.deepcopy(tag)
for hook in self.hooks:
hook.pre_comm(step=S, level_number=level)
if not S.status.last:
self.logger.debug(
'Process %2i provides data on level %2i with tag %s' % (S.status.slot, level, S.status.iter)
)
send(S.levels[level], tag=(level, S.status.iter, S.status.slot))
for hook in self.hooks:
hook.post_comm(step=S, level_number=level, add_to_stats=add_to_stats)
def recv_full(self, S, level=None, add_to_stats=False):
"""
Function to perform the recv, including bookkeeping and logging
Args:
S: the current step
level: the level number
add_to_stats: a flag to end recording data in the hooks (defaults to False)
"""
def recv(target, source, tag=None):
"""
Receive function
Args:
target: level which will receive the values
source: level which initiated the send
tag: identifier to check if this message is really for me
"""
if tag is not None and source.tag != tag:
raise CommunicationError('source and target tag are not the same, got %s and %s' % (source.tag, tag))
# simply do a deepcopy of the values uend to become the new u0 at the target
target.u[0] = target.prob.dtype_u(source.uend)
# re-evaluate f on left interval boundary
target.f[0] = target.prob.eval_f(target.u[0], target.time)
for hook in self.hooks:
hook.pre_comm(step=S, level_number=level)
if not S.status.prev_done and not S.status.first:
self.logger.debug(
'Process %2i receives from %2i on level %2i with tag %s'
% (S.status.slot, S.prev.status.slot, level, S.status.iter)
)
recv(S.levels[level], S.prev.levels[level], tag=(level, S.status.iter, S.prev.status.slot))
for hook in self.hooks:
hook.post_comm(step=S, level_number=level, add_to_stats=add_to_stats)
def pfasst(self, local_MS_active):
"""
Main function including the stages of SDC, MLSDC and PFASST (the "controller")
For the workflow of this controller, check out one of our PFASST talks or the pySDC paper
This method changes self.MS directly by accessing active steps through local_MS_active. Nothing is returned.
Args:
local_MS_active (list): all active steps
"""
# if all stages are the same (or DONE), continue, otherwise abort
stages = [S.status.stage for S in local_MS_active if S.status.stage != 'DONE']
if stages[1:] == stages[:-1]:
stage = stages[0]
else:
raise ControllerError('not all stages are equal')
self.logger.debug(stage)
MS_running = [S for S in local_MS_active if S.status.stage != 'DONE']
switcher = {
'SPREAD': self.spread,
'PREDICT': self.predict,
'IT_CHECK': self.it_check,
'IT_FINE': self.it_fine,
'IT_DOWN': self.it_down,
'IT_COARSE': self.it_coarse,
'IT_UP': self.it_up,
}
switcher.get(stage, self.default)(MS_running)
return all(S.status.done for S in local_MS_active)
def spread(self, local_MS_running):
"""
Spreading phase
Args:
local_MS_running (list): list of currently running steps
"""
for S in local_MS_running:
# first stage: spread values
for hook in self.hooks:
hook.pre_step(step=S, level_number=0)
# call predictor from sweeper
S.levels[0].sweep.predict()
# update stage
if len(S.levels) > 1: # MLSDC or PFASST with predict
S.status.stage = 'PREDICT'
else:
S.status.stage = 'IT_CHECK'
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.post_spread_processing(self, S, MS=local_MS_running)
def predict(self, local_MS_running):
"""
Predictor phase
Args:
local_MS_running (list): list of currently running steps
"""
for S in local_MS_running:
for hook in self.hooks:
hook.pre_predict(step=S, level_number=0)
if self.params.predict_type is None:
pass
elif self.params.predict_type == 'fine_only':
# do a fine sweep only
for S in local_MS_running:
S.levels[0].sweep.update_nodes()
# elif self.params.predict_type == 'libpfasst_style':
#
# # loop over all steps
# for S in local_MS_running:
#
# # restrict to coarsest level
# for l in range(1, len(S.levels)):
# S.transfer(source=S.levels[l - 1], target=S.levels[l])
#
# # run in serial on coarse level
# for S in local_MS_running:
#
# self.hooks.pre_comm(step=S, level_number=len(S.levels) - 1)
# # receive from previous step (if not first)
# if not S.status.first:
# self.logger.debug('Process %2i receives from %2i on level %2i with tag %s -- PREDICT' %
# (S.status.slot, S.prev.status.slot, len(S.levels) - 1, 0))
# self.recv(S.levels[-1], S.prev.levels[-1], tag=(len(S.levels), 0, S.prev.status.slot))
# self.hooks.post_comm(step=S, level_number=len(S.levels) - 1)
#
# # do the coarse sweep
# S.levels[-1].sweep.update_nodes()
#
# self.hooks.pre_comm(step=S, level_number=len(S.levels) - 1)
# # send to succ step
# if not S.status.last:
# self.logger.debug('Process %2i provides data on level %2i with tag %s -- PREDICT'
# % (S.status.slot, len(S.levels) - 1, 0))
# self.send(S.levels[-1], tag=(len(S.levels), 0, S.status.slot))
# self.hooks.post_comm(step=S, level_number=len(S.levels) - 1, add_to_stats=True)
#
# # go back to fine level, sweeping
# for l in range(self.nlevels - 1, 0, -1):
#
# for S in local_MS_running:
# # prolong values
# S.transfer(source=S.levels[l], target=S.levels[l - 1])
#
# if l - 1 > 0:
# S.levels[l - 1].sweep.update_nodes()
#
# # end with a fine sweep
# for S in local_MS_running:
# S.levels[0].sweep.update_nodes()
elif self.params.predict_type == 'pfasst_burnin':
# loop over all steps
for S in local_MS_running:
# restrict to coarsest level
for l in range(1, len(S.levels)):
S.transfer(source=S.levels[l - 1], target=S.levels[l])
# loop over all steps
for q in range(len(local_MS_running)):
# loop over last steps: [1,2,3,4], [2,3,4], [3,4], [4]
for p in range(q, len(local_MS_running)):
S = local_MS_running[p]
# do the sweep with new values
S.levels[-1].sweep.update_nodes()
# send updated values on coarsest level
self.send_full(S, level=len(S.levels) - 1)
# loop over last steps: [2,3,4], [3,4], [4]
for p in range(q + 1, len(local_MS_running)):
S = local_MS_running[p]
# receive values sent during previous sweep
self.recv_full(S, level=len(S.levels) - 1, add_to_stats=(p == len(local_MS_running) - 1))
# loop over all steps
for S in local_MS_running:
# interpolate back to finest level
for l in range(len(S.levels) - 1, 0, -1):
S.transfer(source=S.levels[l], target=S.levels[l - 1])
# send updated values forward
self.send_full(S, level=0)
# receive values
self.recv_full(S, level=0)
# end this with a fine sweep
for S in local_MS_running:
S.levels[0].sweep.update_nodes()
elif self.params.predict_type == 'fmg':
# TODO: implement FMG predictor
raise NotImplementedError('FMG predictor is not yet implemented')
else:
raise ControllerError('Wrong predictor type, got %s' % self.params.predict_type)
for S in local_MS_running:
for hook in self.hooks:
hook.post_predict(step=S, level_number=0)
for S in local_MS_running:
# update stage
S.status.stage = 'IT_CHECK'
def it_check(self, local_MS_running):
"""
Key routine to check for convergence/termination
Args:
local_MS_running (list): list of currently running steps
"""
for S in local_MS_running:
# send updated values forward
self.send_full(S, level=0)
# receive values
self.recv_full(S, level=0)
# compute current residual
S.levels[0].sweep.compute_residual(stage='IT_CHECK')
for S in local_MS_running:
if S.status.iter > 0:
for hook in self.hooks:
hook.post_iteration(step=S, level_number=0)
# decide if the step is done, needs to be restarted and other things convergence related
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.post_iteration_processing(self, S, MS=local_MS_running)
C.convergence_control(self, S, MS=local_MS_running)
for S in local_MS_running:
if not S.status.first:
for hook in self.hooks:
hook.pre_comm(step=S, level_number=0)
S.status.prev_done = S.prev.status.done # "communicate"
for hook in self.hooks:
hook.post_comm(step=S, level_number=0, add_to_stats=True)
S.status.done = S.status.done and S.status.prev_done
if self.params.all_to_done:
for hook in self.hooks:
hook.pre_comm(step=S, level_number=0)
S.status.done = all(T.status.done for T in local_MS_running)
for hook in self.hooks:
hook.post_comm(step=S, level_number=0, add_to_stats=True)
if not S.status.done:
# increment iteration count here (and only here)
S.status.iter += 1
for hook in self.hooks:
hook.pre_iteration(step=S, level_number=0)
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.pre_iteration_processing(self, S, MS=local_MS_running)
if len(S.levels) > 1: # MLSDC or PFASST
S.status.stage = 'IT_DOWN'
else: # SDC or MSSDC
if len(local_MS_running) == 1 or self.params.mssdc_jac: # SDC or parallel MSSDC (Jacobi-like)
S.status.stage = 'IT_FINE'
else:
S.status.stage = 'IT_COARSE' # serial MSSDC (Gauss-like)
else:
S.levels[0].sweep.compute_end_point()
for hook in self.hooks:
hook.post_step(step=S, level_number=0)
S.status.stage = 'DONE'
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.reset_buffers_nonMPI(self)
def it_fine(self, local_MS_running):
"""
Fine sweeps
Args:
local_MS_running (list): list of currently running steps
"""
for S in local_MS_running:
S.levels[0].status.sweep = 0
for k in range(self.nsweeps[0]):
for S in local_MS_running:
S.levels[0].status.sweep += 1
for S in local_MS_running:
# send updated values forward
self.send_full(S, level=0)
# receive values
self.recv_full(S, level=0, add_to_stats=(k == self.nsweeps[0] - 1))
for S in local_MS_running:
# standard sweep workflow: update nodes, compute residual, log progress
for hook in self.hooks:
hook.pre_sweep(step=S, level_number=0)
S.levels[0].sweep.update_nodes()
S.levels[0].sweep.compute_residual(stage='IT_FINE')
for hook in self.hooks:
hook.post_sweep(step=S, level_number=0)
for S in local_MS_running:
# update stage
S.status.stage = 'IT_CHECK'
def it_down(self, local_MS_running):
"""
Go down the hierarchy from finest to coarsest level
Args:
local_MS_running (list): list of currently running steps
"""
for S in local_MS_running:
S.transfer(source=S.levels[0], target=S.levels[1])
for l in range(1, self.nlevels - 1):
# sweep on middle levels (not on finest, not on coarsest, though)
for _ in range(self.nsweeps[l]):
for S in local_MS_running:
# send updated values forward
self.send_full(S, level=l)
# receive values
self.recv_full(S, level=l)
for S in local_MS_running:
for hook in self.hooks:
hook.pre_sweep(step=S, level_number=l)
S.levels[l].sweep.update_nodes()
S.levels[l].sweep.compute_residual(stage='IT_DOWN')
for hook in self.hooks:
hook.post_sweep(step=S, level_number=l)
for S in local_MS_running:
# transfer further down the hierarchy
S.transfer(source=S.levels[l], target=S.levels[l + 1])
for S in local_MS_running:
# update stage
S.status.stage = 'IT_COARSE'
def it_coarse(self, local_MS_running):
"""
Coarse sweep
Args:
local_MS_running (list): list of currently running steps
"""
for S in local_MS_running:
# receive from previous step (if not first)
self.recv_full(S, level=len(S.levels) - 1)
# do the sweep
for hook in self.hooks:
hook.pre_sweep(step=S, level_number=len(S.levels) - 1)
S.levels[-1].sweep.update_nodes()
S.levels[-1].sweep.compute_residual(stage='IT_COARSE')
for hook in self.hooks:
hook.post_sweep(step=S, level_number=len(S.levels) - 1)
# send to succ step
self.send_full(S, level=len(S.levels) - 1, add_to_stats=True)
# update stage
if len(S.levels) > 1: # MLSDC or PFASST
S.status.stage = 'IT_UP'
else: # MSSDC
S.status.stage = 'IT_CHECK'
def it_up(self, local_MS_running):
"""
Prolong corrections up to finest level (parallel)
Args:
local_MS_running (list): list of currently running steps
"""
for l in range(self.nlevels - 1, 0, -1):
for S in local_MS_running:
# prolong values
S.transfer(source=S.levels[l], target=S.levels[l - 1])
# on middle levels: do communication and sweep as usual
if l - 1 > 0:
for k in range(self.nsweeps[l - 1]):
for S in local_MS_running:
# send updated values forward
self.send_full(S, level=l - 1)
# receive values
self.recv_full(S, level=l - 1, add_to_stats=(k == self.nsweeps[l - 1] - 1))
for S in local_MS_running:
for hook in self.hooks:
hook.pre_sweep(step=S, level_number=l - 1)
S.levels[l - 1].sweep.update_nodes()
S.levels[l - 1].sweep.compute_residual(stage='IT_UP')
for hook in self.hooks:
hook.post_sweep(step=S, level_number=l - 1)
for S in local_MS_running:
# update stage
S.status.stage = 'IT_FINE'
def default(self, local_MS_running):
"""
Default routine to catch wrong status
Args:
local_MS_running (list): list of currently running steps
"""
raise ControllerError('Unknown stage, got %s' % local_MS_running[0].status.stage) # TODO
| 26,987 | 38.513909 | 117 | py |
pySDC | pySDC-master/pySDC/implementations/controller_classes/controller_MPI.py | import numpy as np
from mpi4py import MPI
from pySDC.core.Controller import controller
from pySDC.core.Errors import ControllerError
from pySDC.core.Step import step
from pySDC.implementations.convergence_controller_classes.basic_restarting import BasicRestarting
class controller_MPI(controller):
"""
PFASST controller, running parallel version of PFASST in blocks (MG-style)
"""
def __init__(self, controller_params, description, comm):
"""
Initialization routine for PFASST controller
Args:
controller_params: parameter set for the controller and the step class
description: all the parameters to set up the rest (levels, problems, transfer, ...)
comm: MPI communicator
"""
# call parent's initialization routine
super().__init__(controller_params, description, useMPI=True)
# create single step per processor
self.S = step(description)
# pass communicator for future use
self.comm = comm
num_procs = self.comm.Get_size()
rank = self.comm.Get_rank()
# insert data on time communicator to the steps (helpful here and there)
self.S.status.time_size = num_procs
self.base_convergence_controllers += [BasicRestarting.get_implementation("MPI")]
for convergence_controller in self.base_convergence_controllers:
self.add_convergence_controller(convergence_controller, description)
if self.params.dump_setup and rank == 0:
self.dump_setup(step=self.S, controller_params=controller_params, description=description)
num_levels = len(self.S.levels)
# add request handler for status send
self.req_status = None
# add request handle container for isend
self.req_send = [None] * num_levels
self.req_ibcast = None
self.req_diff = None
if num_procs > 1 and num_levels > 1:
for L in self.S.levels:
if not L.sweep.coll.right_is_node or L.sweep.params.do_coll_update:
raise ControllerError("For PFASST to work, we assume uend^k = u_M^k")
if num_levels == 1 and self.params.predict_type is not None:
self.logger.warning(
'you have specified a predictor type but only a single level.. predictor will be ignored'
)
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.setup_status_variables(self, comm=comm)
def run(self, u0, t0, Tend):
"""
Main driver for running the parallel version of SDC, MSSDC, MLSDC and PFASST
Args:
u0: initial values
t0: starting time
Tend: ending time
Returns:
end values on the finest level
stats object containing statistics for each step, each level and each iteration
"""
# reset stats to prevent double entries from old runs
for hook in self.hooks:
hook.reset_stats()
# find active processes and put into new communicator
rank = self.comm.Get_rank()
num_procs = self.comm.Get_size()
all_dt = self.comm.allgather(self.S.dt)
all_time = [t0 + sum(all_dt[0:i]) for i in range(num_procs)]
time = all_time[rank]
all_active = all_time < Tend - 10 * np.finfo(float).eps
if not any(all_active):
raise ControllerError('Nothing to do, check t0, dt and Tend')
active = all_active[rank]
if not all(all_active):
comm_active = self.comm.Split(active)
rank = comm_active.Get_rank()
num_procs = comm_active.Get_size()
else:
comm_active = self.comm
self.S.status.slot = rank
# initialize block of steps with u0
self.restart_block(num_procs, time, u0, comm=comm_active)
uend = u0
# call post-setup hook
for hook in self.hooks:
hook.post_setup(step=None, level_number=None)
# call pre-run hook
for hook in self.hooks:
hook.pre_run(step=self.S, level_number=0)
comm_active.Barrier()
# while any process still active...
while active:
while not self.S.status.done:
self.pfasst(comm_active, num_procs)
# determine where to restart
restarts = comm_active.allgather(self.S.status.restart)
restart_at = np.where(restarts)[0][0] if True in restarts else comm_active.size - 1
# communicate time and solution to be used as next initial conditions
if True in restarts:
uend = self.S.levels[0].u[0].bcast(root=restart_at, comm=comm_active)
tend = comm_active.bcast(self.S.time, root=restart_at)
self.logger.info(f'Starting next block with initial conditions from step {restart_at}')
else:
time += self.S.dt
uend = self.S.levels[0].uend.bcast(root=num_procs - 1, comm=comm_active)
tend = comm_active.bcast(self.S.time + self.S.dt, root=comm_active.size - 1)
# do convergence controller stuff
if not self.S.status.restart:
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.post_step_processing(self, self.S)
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.prepare_next_block(self, self.S, self.S.status.time_size, time, Tend, comm=comm_active)
all_dt = comm_active.allgather(self.S.dt)
all_time = [tend + sum(all_dt[0:i]) for i in range(num_procs)]
time = all_time[rank]
all_active = all_time < Tend - 10 * np.finfo(float).eps
active = all_active[rank]
if not all(all_active):
comm_active = comm_active.Split(active)
rank = comm_active.Get_rank()
num_procs = comm_active.Get_size()
self.S.status.slot = rank
# initialize block of steps with u0
self.restart_block(num_procs, time, uend, comm=comm_active)
# call post-run hook
for hook in self.hooks:
hook.post_run(step=self.S, level_number=0)
comm_active.Free()
return uend, self.return_stats()
def restart_block(self, size, time, u0, comm):
"""
Helper routine to reset/restart block of (active) steps
Args:
size: number of active time steps
time: current time
u0: initial value to distribute across the steps
comm: the communicator
Returns:
block of (all) steps
"""
# store link to previous step
self.S.prev = (self.S.status.slot - 1) % size
self.S.next = (self.S.status.slot + 1) % size
# resets step
self.S.reset_step()
# determine whether I am the first and/or last in line
self.S.status.first = self.S.prev == size - 1
self.S.status.last = self.S.next == 0
# initialize step with u0
self.S.init_step(u0)
# reset some values
self.S.status.done = False
self.S.status.iter = 0
self.S.status.stage = 'SPREAD'
for l in self.S.levels:
l.tag = None
self.req_status = None
self.req_diff = None
self.req_ibcast = None
self.req_diff = None
self.req_send = [None] * len(self.S.levels)
self.S.status.prev_done = False
self.S.status.force_done = False
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.reset_status_variables(self, comm=comm)
self.S.status.time_size = size
for lvl in self.S.levels:
lvl.status.time = time
lvl.status.sweep = 1
def recv(self, target, source, tag=None, comm=None):
"""
Receive function
Args:
target: level which will receive the values
source: level which initiated the send
tag: identifier to check if this message is really for me
comm: communicator
"""
req = target.u[0].irecv(source=source, tag=tag, comm=comm)
self.wait_with_interrupt(request=req)
if self.S.status.force_done:
return None
# re-evaluate f on left interval boundary
target.f[0] = target.prob.eval_f(target.u[0], target.time)
def send_full(self, comm=None, blocking=False, level=None, add_to_stats=False):
"""
Function to perform the send, including bookkeeping and logging
Args:
comm: the communicator
blocking: flag to indicate that we need blocking communication
level: the level number
add_to_stats: a flag to end recording data in the hooks (defaults to False)
"""
for hook in self.hooks:
hook.pre_comm(step=self.S, level_number=level)
if not blocking:
self.wait_with_interrupt(request=self.req_send[level])
if self.S.status.force_done:
return None
self.S.levels[level].sweep.compute_end_point()
if not self.S.status.last:
self.logger.debug(
'isend data: process %s, stage %s, time %s, target %s, tag %s, iter %s'
% (
self.S.status.slot,
self.S.status.stage,
self.S.time,
self.S.next,
level * 100 + self.S.status.iter,
self.S.status.iter,
)
)
self.req_send[level] = self.S.levels[level].uend.isend(
dest=self.S.next, tag=level * 100 + self.S.status.iter, comm=comm
)
if blocking:
self.wait_with_interrupt(request=self.req_send[level])
if self.S.status.force_done:
return None
for hook in self.hooks:
hook.post_comm(step=self.S, level_number=level, add_to_stats=add_to_stats)
def recv_full(self, comm, level=None, add_to_stats=False):
"""
Function to perform the recv, including bookkeeping and logging
Args:
comm: the communicator
level: the level number
add_to_stats: a flag to end recording data in the hooks (defaults to False)
"""
for hook in self.hooks:
hook.pre_comm(step=self.S, level_number=level)
if not self.S.status.first and not self.S.status.prev_done:
self.logger.debug(
'recv data: process %s, stage %s, time %s, source %s, tag %s, iter %s'
% (
self.S.status.slot,
self.S.status.stage,
self.S.time,
self.S.prev,
level * 100 + self.S.status.iter,
self.S.status.iter,
)
)
self.recv(target=self.S.levels[level], source=self.S.prev, tag=level * 100 + self.S.status.iter, comm=comm)
for hook in self.hooks:
hook.post_comm(step=self.S, level_number=level, add_to_stats=add_to_stats)
def wait_with_interrupt(self, request):
"""
Wrapper for waiting for the completion of a non-blocking communication, can be interrupted
Args:
request: request to wait for
"""
if request is not None and self.req_ibcast is not None:
while not request.Test():
if self.req_ibcast.Test():
self.logger.debug(f'{self.S.status.slot} has been cancelled during {self.S.status.stage}..')
self.S.status.stage = f'CANCELLED_{self.S.status.stage}'
self.S.status.force_done = True
return None
if request is not None:
request.Wait()
def check_iteration_estimate(self, comm):
"""
Routine to compute and check error/iteration estimation
Args:
comm: time-communicator
"""
# Compute diff between old and new values
diff_new = 0.0
L = self.S.levels[0]
for m in range(1, L.sweep.coll.num_nodes + 1):
diff_new = max(diff_new, abs(L.uold[m] - L.u[m]))
# Send forward diff
for hook in self.hooks:
hook.pre_comm(step=self.S, level_number=0)
self.wait_with_interrupt(request=self.req_diff)
if self.S.status.force_done:
return None
if not self.S.status.first:
prev_diff = np.empty(1, dtype=float)
req = comm.Irecv((prev_diff, MPI.DOUBLE), source=self.S.prev, tag=999)
self.wait_with_interrupt(request=req)
if self.S.status.force_done:
return None
self.logger.debug(
'recv diff: status %s, process %s, time %s, source %s, tag %s, iter %s'
% (prev_diff, self.S.status.slot, self.S.time, self.S.prev, 999, self.S.status.iter)
)
diff_new = max(prev_diff[0], diff_new)
if not self.S.status.last:
self.logger.debug(
'isend diff: status %s, process %s, time %s, target %s, tag %s, iter %s'
% (diff_new, self.S.status.slot, self.S.time, self.S.next, 999, self.S.status.iter)
)
tmp = np.array(diff_new, dtype=float)
self.req_diff = comm.Issend((tmp, MPI.DOUBLE), dest=self.S.next, tag=999)
for hook in self.hooks:
hook.post_comm(step=self.S, level_number=0)
# Store values from first iteration
if self.S.status.iter == 1:
self.S.status.diff_old_loc = diff_new
self.S.status.diff_first_loc = diff_new
# Compute iteration estimate
elif self.S.status.iter > 1:
Ltilde_loc = min(diff_new / self.S.status.diff_old_loc, 0.9)
self.S.status.diff_old_loc = diff_new
alpha = 1 / (1 - Ltilde_loc) * self.S.status.diff_first_loc
Kest_loc = np.log(self.S.params.errtol / alpha) / np.log(Ltilde_loc) * 1.05 # Safety factor!
self.logger.debug(
f'LOCAL: {L.time:8.4f}, {self.S.status.iter}: {int(np.ceil(Kest_loc))}, '
f'{Ltilde_loc:8.6e}, {Kest_loc:8.6e}, '
f'{Ltilde_loc ** self.S.status.iter * alpha:8.6e}'
)
Kest_glob = Kest_loc
# If condition is met, send interrupt
if np.ceil(Kest_glob) <= self.S.status.iter:
if self.S.status.last:
self.logger.debug(f'{self.S.status.slot} is done, broadcasting..')
for hook in self.hooks:
hook.pre_comm(step=self.S, level_number=0)
comm.Ibcast((np.array([1]), MPI.INT), root=self.S.status.slot).Wait()
for hook in self.hooks:
hook.post_comm(step=self.S, level_number=0, add_to_stats=True)
self.logger.debug(f'{self.S.status.slot} is done, broadcasting done')
self.S.status.done = True
else:
for hook in self.hooks:
hook.pre_comm(step=self.S, level_number=0)
for hook in self.hooks:
hook.post_comm(step=self.S, level_number=0, add_to_stats=True)
def pfasst(self, comm, num_procs):
"""
Main function including the stages of SDC, MLSDC and PFASST (the "controller")
For the workflow of this controller, check out one of our PFASST talks or the pySDC paper
Args:
comm: communicator
num_procs (int): number of parallel processes
"""
stage = self.S.status.stage
self.logger.debug(stage + ' - process ' + str(self.S.status.slot))
# Wait for interrupt, if iteration estimator is used
if self.params.use_iteration_estimator and stage == 'SPREAD' and not self.S.status.last:
done = np.empty(1)
self.req_ibcast = comm.Ibcast((done, MPI.INT), root=comm.Get_size() - 1)
# If interrupt is there, cleanup and finish
if self.params.use_iteration_estimator and not self.S.status.last and self.req_ibcast.Test():
self.logger.debug(f'{self.S.status.slot} is done..')
self.S.status.done = True
if not stage == 'IT_CHECK':
self.logger.debug(f'Rewinding {self.S.status.slot} after {stage}..')
self.S.levels[0].u[1:] = self.S.levels[0].uold[1:]
for hook in self.hooks:
hook.post_iteration(step=self.S, level_number=0)
for req in self.req_send:
if req is not None and req != MPI.REQUEST_NULL:
req.Cancel()
if self.req_status is not None and self.req_status != MPI.REQUEST_NULL:
self.req_status.Cancel()
if self.req_diff is not None and self.req_diff != MPI.REQUEST_NULL:
self.req_diff.Cancel()
self.S.status.stage = 'DONE'
for hook in self.hooks:
hook.post_step(step=self.S, level_number=0)
else:
# Start cycling, if not interrupted
switcher = {
'SPREAD': self.spread,
'PREDICT': self.predict,
'IT_CHECK': self.it_check,
'IT_FINE': self.it_fine,
'IT_DOWN': self.it_down,
'IT_COARSE': self.it_coarse,
'IT_UP': self.it_up,
}
switcher.get(stage, self.default)(comm, num_procs)
def spread(self, comm, num_procs):
"""
Spreading phase
"""
# first stage: spread values
for hook in self.hooks:
hook.pre_step(step=self.S, level_number=0)
# call predictor from sweeper
self.S.levels[0].sweep.predict()
if self.params.use_iteration_estimator:
# store previous iterate to compute difference later on
self.S.levels[0].uold[1:] = self.S.levels[0].u[1:]
# update stage
if len(self.S.levels) > 1: # MLSDC or PFASST with predict
self.S.status.stage = 'PREDICT'
else:
self.S.status.stage = 'IT_CHECK'
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.post_spread_processing(self, self.S, comm=comm)
def predict(self, comm, num_procs):
"""
Predictor phase
"""
for hook in self.hooks:
hook.pre_predict(step=self.S, level_number=0)
if self.params.predict_type is None:
pass
elif self.params.predict_type == 'fine_only':
# do a fine sweep only
self.S.levels[0].sweep.update_nodes()
# elif self.params.predict_type == 'libpfasst_style':
#
# # restrict to coarsest level
# for l in range(1, len(self.S.levels)):
# self.S.transfer(source=self.S.levels[l - 1], target=self.S.levels[l])
#
# self.hooks.pre_comm(step=self.S, level_number=len(self.S.levels) - 1)
# if not self.S.status.first:
# self.logger.debug('recv data predict: process %s, stage %s, time, %s, source %s, tag %s' %
# (self.S.status.slot, self.S.status.stage, self.S.time, self.S.prev,
# self.S.status.iter))
# self.recv(target=self.S.levels[-1], source=self.S.prev, tag=self.S.status.iter, comm=comm)
# self.hooks.post_comm(step=self.S, level_number=len(self.S.levels) - 1)
#
# # do the sweep with new values
# self.S.levels[-1].sweep.update_nodes()
# self.S.levels[-1].sweep.compute_end_point()
#
# self.hooks.pre_comm(step=self.S, level_number=len(self.S.levels) - 1)
# if not self.S.status.last:
# self.logger.debug('send data predict: process %s, stage %s, time, %s, target %s, tag %s' %
# (self.S.status.slot, self.S.status.stage, self.S.time, self.S.next,
# self.S.status.iter))
# self.S.levels[-1].uend.isend(dest=self.S.next, tag=self.S.status.iter, comm=comm).Wait()
# self.hooks.post_comm(step=self.S, level_number=len(self.S.levels) - 1, add_to_stats=True)
#
# # go back to fine level, sweeping
# for l in range(len(self.S.levels) - 1, 0, -1):
# # prolong values
# self.S.transfer(source=self.S.levels[l], target=self.S.levels[l - 1])
# # on middle levels: do sweep as usual
# if l - 1 > 0:
# self.S.levels[l - 1].sweep.update_nodes()
#
# # end with a fine sweep
# self.S.levels[0].sweep.update_nodes()
elif self.params.predict_type == 'pfasst_burnin':
# restrict to coarsest level
for l in range(1, len(self.S.levels)):
self.S.transfer(source=self.S.levels[l - 1], target=self.S.levels[l])
for p in range(self.S.status.slot + 1):
if not p == 0:
self.recv_full(comm=comm, level=len(self.S.levels) - 1)
if self.S.status.force_done:
return None
# do the sweep with new values
self.S.levels[-1].sweep.update_nodes()
self.S.levels[-1].sweep.compute_end_point()
self.send_full(
comm=comm, blocking=True, level=len(self.S.levels) - 1, add_to_stats=(p == self.S.status.slot)
)
if self.S.status.force_done:
return None
# interpolate back to finest level
for l in range(len(self.S.levels) - 1, 0, -1):
self.S.transfer(source=self.S.levels[l], target=self.S.levels[l - 1])
self.send_full(comm=comm, level=0)
if self.S.status.force_done:
return None
self.recv_full(comm=comm, level=0)
if self.S.status.force_done:
return None
# end this with a fine sweep
self.S.levels[0].sweep.update_nodes()
elif self.params.predict_type == 'fmg':
# TODO: implement FMG predictor
raise NotImplementedError('FMG predictor is not yet implemented')
else:
raise ControllerError('Wrong predictor type, got %s' % self.params.predict_type)
for hook in self.hooks:
hook.post_predict(step=self.S, level_number=0)
# update stage
self.S.status.stage = 'IT_CHECK'
def it_check(self, comm, num_procs):
"""
Key routine to check for convergence/termination
"""
# Update values to compute the residual
self.send_full(comm=comm, level=0)
if self.S.status.force_done:
return None
self.recv_full(comm=comm, level=0)
if self.S.status.force_done:
return None
# compute the residual
self.S.levels[0].sweep.compute_residual(stage='IT_CHECK')
if self.params.use_iteration_estimator:
# TODO: replace with convergence controller
self.check_iteration_estimate(comm=comm)
if self.S.status.force_done:
return None
if self.S.status.iter > 0:
for hook in self.hooks:
hook.post_iteration(step=self.S, level_number=0)
# decide if the step is done, needs to be restarted and other things convergence related
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.post_iteration_processing(self, self.S, comm=comm)
C.convergence_control(self, self.S, comm=comm)
# if not ready, keep doing stuff
if not self.S.status.done:
# increment iteration count here (and only here)
self.S.status.iter += 1
for hook in self.hooks:
hook.pre_iteration(step=self.S, level_number=0)
for C in [self.convergence_controllers[i] for i in self.convergence_controller_order]:
C.pre_iteration_processing(self, self.S, comm=comm)
if self.params.use_iteration_estimator:
# store previous iterate to compute difference later on
self.S.levels[0].uold[1:] = self.S.levels[0].u[1:]
if len(self.S.levels) > 1: # MLSDC or PFASST
self.S.status.stage = 'IT_DOWN'
else:
if num_procs == 1 or self.params.mssdc_jac: # SDC or parallel MSSDC (Jacobi-like)
self.S.status.stage = 'IT_FINE'
else:
self.S.status.stage = 'IT_COARSE' # serial MSSDC (Gauss-like)
else:
if not self.params.use_iteration_estimator:
# Need to finish all pending isend requests. These will occur for the first active process, since
# in the last iteration the wait statement will not be called ("send and forget")
for req in self.req_send:
if req is not None:
req.Wait()
if self.req_status is not None:
self.req_status.Wait()
if self.req_diff is not None:
self.req_diff.Wait()
else:
for req in self.req_send:
if req is not None:
req.Cancel()
if self.req_status is not None:
self.req_status.Cancel()
if self.req_diff is not None:
self.req_diff.Cancel()
for hook in self.hooks:
hook.post_step(step=self.S, level_number=0)
self.S.status.stage = 'DONE'
def it_fine(self, comm, num_procs):
"""
Fine sweeps
"""
nsweeps = self.S.levels[0].params.nsweeps
self.S.levels[0].status.sweep = 0
# do fine sweep
for k in range(nsweeps):
self.S.levels[0].status.sweep += 1
# send values forward
self.send_full(comm=comm, level=0)
if self.S.status.force_done:
return None
# recv values from previous
self.recv_full(comm=comm, level=0, add_to_stats=(k == nsweeps - 1))
if self.S.status.force_done:
return None
for hook in self.hooks:
hook.pre_sweep(step=self.S, level_number=0)
self.S.levels[0].sweep.update_nodes()
self.S.levels[0].sweep.compute_residual(stage='IT_FINE')
for hook in self.hooks:
hook.post_sweep(step=self.S, level_number=0)
# update stage
self.S.status.stage = 'IT_CHECK'
def it_down(self, comm, num_procs):
"""
Go down the hierarchy from finest to coarsest level
"""
self.S.transfer(source=self.S.levels[0], target=self.S.levels[1])
# sweep and send on middle levels (not on finest, not on coarsest, though)
for l in range(1, len(self.S.levels) - 1):
nsweeps = self.S.levels[l].params.nsweeps
for _ in range(nsweeps):
self.send_full(comm=comm, level=l)
if self.S.status.force_done:
return None
self.recv_full(comm=comm, level=l)
if self.S.status.force_done:
return None
for hook in self.hooks:
hook.pre_sweep(step=self.S, level_number=l)
self.S.levels[l].sweep.update_nodes()
self.S.levels[l].sweep.compute_residual(stage='IT_DOWN')
for hook in self.hooks:
hook.post_sweep(step=self.S, level_number=l)
# transfer further down the hierarchy
self.S.transfer(source=self.S.levels[l], target=self.S.levels[l + 1])
# update stage
self.S.status.stage = 'IT_COARSE'
def it_coarse(self, comm, num_procs):
"""
Coarse sweep
"""
# receive from previous step (if not first)
self.recv_full(comm=comm, level=len(self.S.levels) - 1)
if self.S.status.force_done:
return None
# do the sweep
for hook in self.hooks:
hook.pre_sweep(step=self.S, level_number=len(self.S.levels) - 1)
assert self.S.levels[-1].params.nsweeps == 1, (
'ERROR: this controller can only work with one sweep on the coarse level, got %s'
% self.S.levels[-1].params.nsweeps
)
self.S.levels[-1].sweep.update_nodes()
self.S.levels[-1].sweep.compute_residual(stage='IT_COARSE')
for hook in self.hooks:
hook.post_sweep(step=self.S, level_number=len(self.S.levels) - 1)
self.S.levels[-1].sweep.compute_end_point()
# send to next step
self.send_full(comm=comm, blocking=True, level=len(self.S.levels) - 1, add_to_stats=True)
if self.S.status.force_done:
return None
# update stage
if len(self.S.levels) > 1: # MLSDC or PFASST
self.S.status.stage = 'IT_UP'
else:
self.S.status.stage = 'IT_CHECK' # MSSDC
def it_up(self, comm, num_procs):
"""
Prolong corrections up to finest level (parallel)
"""
# receive and sweep on middle levels (except for coarsest level)
for l in range(len(self.S.levels) - 1, 0, -1):
# prolong values
self.S.transfer(source=self.S.levels[l], target=self.S.levels[l - 1])
# on middle levels: do sweep as usual
if l - 1 > 0:
nsweeps = self.S.levels[l - 1].params.nsweeps
for k in range(nsweeps):
self.send_full(comm, level=l - 1)
if self.S.status.force_done:
return None
self.recv_full(comm=comm, level=l - 1, add_to_stats=(k == nsweeps - 1))
if self.S.status.force_done:
return None
for hook in self.hooks:
hook.pre_sweep(step=self.S, level_number=l - 1)
self.S.levels[l - 1].sweep.update_nodes()
self.S.levels[l - 1].sweep.compute_residual(stage='IT_UP')
for hook in self.hooks:
hook.post_sweep(step=self.S, level_number=l - 1)
# update stage
self.S.status.stage = 'IT_FINE'
def default(self, num_procs):
"""
Default routine to catch wrong status
"""
raise ControllerError('Weird stage, got %s' % self.S.status.stage)
| 31,242 | 37.667079 | 119 | py |
pySDC | pySDC-master/pySDC/implementations/controller_classes/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/step_size_limiter.py | import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController
class StepSizeLimiter(ConvergenceController):
"""
Class to set limits to adaptive step size computation during run time
Please supply dt_min or dt_max in the params to limit in either direction
"""
def setup(self, controller, params, description, **kwargs):
"""
Define parameters here
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {
"control_order": +92,
"dt_min": 0,
"dt_max": np.inf,
}
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def dependencies(self, controller, description, **kwargs):
"""
Load the slope limiter if needed.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
slope_limiter_keys = ['dt_slope_min', 'dt_slope_max']
available_keys = [me for me in slope_limiter_keys if me in self.params.__dict__.keys()]
if len(available_keys) > 0:
slope_limiter_params = {key: self.params.__dict__[key] for key in available_keys}
slope_limiter_params['control_order'] = self.params.control_order - 1
controller.add_convergence_controller(
StepSizeSlopeLimiter, params=slope_limiter_params, description=description
)
return None
def get_new_step_size(self, controller, S, **kwargs):
"""
Enforce an upper and lower limit to the step size here.
Be aware that this is only tested when a new step size has been determined. That means if you set an initial
value for the step size outside of the limits, and you don't do any further step size control, that value will
go through.
Also, the final step is adjusted such that we reach Tend as best as possible, which might give step sizes below
the lower limit set here.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
for L in S.levels:
if L.status.dt_new is not None:
if L.status.dt_new < self.params.dt_min:
self.log(
f"Step size is below minimum, increasing from {L.status.dt_new:.2e} to \
{self.params.dt_min:.2e}",
S,
)
L.status.dt_new = self.params.dt_min
elif L.status.dt_new > self.params.dt_max:
self.log(
f"Step size exceeds maximum, decreasing from {L.status.dt_new:.2e} to {self.params.dt_max:.2e}",
S,
)
L.status.dt_new = self.params.dt_max
return None
class StepSizeSlopeLimiter(ConvergenceController):
"""
Class to set limits to adaptive step size computation during run time
Please supply dt_min or dt_max in the params to limit in either direction
"""
def setup(self, controller, params, description, **kwargs):
"""
Define parameters here
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {
"control_order": 91,
"dt_slope_min": 0,
"dt_slope_max": np.inf,
}
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def get_new_step_size(self, controller, S, **kwargs):
"""
Enforce an upper and lower limit to the slope of the step size here.
The final step is adjusted such that we reach Tend as best as possible, which might give step sizes below
the lower limit set here.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
for L in S.levels:
if L.status.dt_new is not None:
if L.status.dt_new / L.params.dt < self.params.dt_slope_min:
dt_new = L.params.dt * self.params.dt_slope_min
self.log(
f"Step size slope is below minimum, increasing from {L.status.dt_new:.2e} to \
{dt_new:.2e}",
S,
)
L.status.dt_new = dt_new
elif L.status.dt_new / L.params.dt > self.params.dt_slope_max:
dt_new = L.params.dt * self.params.dt_slope_max
self.log(
f"Step size slope exceeds maximum, decreasing from {L.status.dt_new:.2e} to \
{dt_new:.2e}",
S,
)
L.status.dt_new = dt_new
return None
| 5,465 | 35.932432 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/adaptivity.py | import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController, Status
from pySDC.implementations.convergence_controller_classes.step_size_limiter import (
StepSizeLimiter,
)
from pySDC.implementations.convergence_controller_classes.basic_restarting import (
BasicRestartingNonMPI,
)
class AdaptivityBase(ConvergenceController):
"""
Abstract base class for convergence controllers that implement adaptivity based on arbitrary local error estimates
and update rules.
"""
def setup(self, controller, params, description, **kwargs):
"""
Define default parameters here.
Default parameters are:
- control_order (int): The order relative to other convergence controllers
- beta (float): The safety factor
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {
"control_order": -50,
"beta": 0.9,
}
from pySDC.implementations.hooks.log_step_size import LogStepSize
controller.add_hook(LogStepSize)
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def dependencies(self, controller, description, **kwargs):
"""
Load step size limiters here, if they are desired.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
step_limiter_keys = ['dt_min', 'dt_max', 'dt_slope_min', 'dt_slope_max']
available_keys = [me for me in step_limiter_keys if me in self.params.__dict__.keys()]
if len(available_keys) > 0:
step_limiter_params = {key: self.params.__dict__[key] for key in available_keys}
controller.add_convergence_controller(StepSizeLimiter, params=step_limiter_params, description=description)
return None
def get_new_step_size(self, controller, S, **kwargs):
"""
Determine a step size for the next step from an estimate of the local error of the current step.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
raise NotImplementedError("Please implement a rule for updating the step size!")
def compute_optimal_step_size(self, beta, dt, e_tol, e_est, order):
"""
Compute the optimal step size for the current step based on the order of the scheme.
This function can be called from `get_new_step_size` for various implementations of adaptivity, but notably not
all! We require to know the order of the error estimate and if we do adaptivity based on the residual, for
instance, we do not know that and we can't use this function.
Args:
beta (float): Safety factor
dt (float): Current step size
e_tol (float): The desired tolerance
e_est (float): The estimated local error
order (int): The order of the local error estimate
Returns:
float: The optimal step size
"""
return beta * dt * (e_tol / e_est) ** (1.0 / order)
def get_local_error_estimate(self, controller, S, **kwargs):
"""
Get the local error estimate for updating the step size.
It does not have to be an error estimate, but could be the residual or something else.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
float: The error estimate
"""
raise NotImplementedError("Please implement a way to get the local error")
def determine_restart(self, controller, S, **kwargs):
"""
Check if the step wants to be restarted by comparing the estimate of the local error to a preset tolerance
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
if S.status.iter >= S.params.maxiter:
e_est = self.get_local_error_estimate(controller, S)
if e_est >= self.params.e_tol:
# see if we try to avoid restarts
if self.params.get('avoid_restarts'):
more_iter_needed = max([L.status.iter_to_convergence for L in S.levels])
k_final = S.status.iter + more_iter_needed
rho = max([L.status.contraction_factor for L in S.levels])
coll_order = S.levels[0].sweep.coll.order
if rho > 1:
S.status.restart = True
self.log(f"Convergence factor = {rho:.2e} > 1 -> restarting", S)
elif k_final > 2 * S.params.maxiter:
S.status.restart = True
self.log(
f"{more_iter_needed} more iterations needed for convergence -> restart is more efficient", S
)
elif k_final > coll_order:
S.status.restart = True
self.log(
f"{more_iter_needed} more iterations needed for convergence -> restart because collocation problem would be over resolved",
S,
)
else:
S.status.force_continue = True
self.log(f"{more_iter_needed} more iterations needed for convergence -> no restart", S)
else:
S.status.restart = True
self.log(f"Restarting: e={e_est:.2e} >= e_tol={self.params.e_tol:.2e}", S)
return None
class Adaptivity(AdaptivityBase):
"""
Class to compute time step size adaptively based on embedded error estimate.
We have a version working in non-MPI pipelined SDC, but Adaptivity requires you to know the order of the scheme,
which you can also know for block-Jacobi, but it works differently and it is only implemented for block
Gauss-Seidel so far.
There is an option to reduce restarts if continued iterations could yield convergence in fewer iterations than
restarting based on an estimate of the contraction factor.
Since often only one or two more iterations suffice, this can boost efficiency of adaptivity significantly.
Notice that the computed step size is not effected.
Be aware that this does not work when Hot Rod is enabled, since that requires us to know the order of the scheme in
more detail. Since we reset to the second to last sweep before moving on, we cannot continue to iterate.
Set the reduced restart up by setting a boolean value for "avoid_restarts" in the parameters for the convergence
controller.
The behaviour in multi-step SDC is not well studied and it is unclear if anything useful happens there.
"""
def setup(self, controller, params, description, **kwargs):
"""
Define default parameters here.
Default parameters are:
- control_order (int): The order relative to other convergence controllers
- beta (float): The safety factor
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {
"embedded_error_flavor": 'standard',
}
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def dependencies(self, controller, description, **kwargs):
"""
Load the embedded error estimator.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
from pySDC.implementations.convergence_controller_classes.estimate_embedded_error import EstimateEmbeddedError
super().dependencies(controller, description)
controller.add_convergence_controller(
EstimateEmbeddedError.get_implementation(self.params.embedded_error_flavor, self.params.useMPI),
description=description,
)
# load contraction factor estimator if necessary
if self.params.get('avoid_restarts'):
from pySDC.implementations.convergence_controller_classes.estimate_contraction_factor import (
EstimateContractionFactor,
)
params = {'e_tol': self.params.e_tol}
controller.add_convergence_controller(EstimateContractionFactor, description=description, params=params)
return None
def check_parameters(self, controller, params, description, **kwargs):
"""
Check whether parameters are compatible with whatever assumptions went into the step size functions etc.
For adaptivity, we need to know the order of the scheme.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
bool: Whether the parameters are compatible
str: The error message
"""
if description["level_params"].get("restol", -1.0) >= 0:
return (
False,
"Adaptivity needs constant order in time and hence restol in the step parameters has to be \
smaller than 0!",
)
if controller.params.mssdc_jac:
return (
False,
"Adaptivity needs the same order on all steps, please activate Gauss-Seidel multistep mode!",
)
if "e_tol" not in params.keys():
return (
False,
"Adaptivity needs a local tolerance! Please pass `e_tol` to the parameters for this convergence controller!",
)
return True, ""
def get_new_step_size(self, controller, S, **kwargs):
"""
Determine a step size for the next step from an embedded estimate of the local error of the current step.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
# check if we performed the desired amount of sweeps
if S.status.iter == S.params.maxiter:
L = S.levels[0]
# compute next step size
order = S.status.iter # embedded error estimate is same order as time marching
e_est = self.get_local_error_estimate(controller, S)
L.status.dt_new = self.compute_optimal_step_size(
self.params.beta, L.params.dt, self.params.e_tol, e_est, order
)
self.log(f'Adjusting step size from {L.params.dt:.2e} to {L.status.dt_new:.2e}', S)
return None
def get_local_error_estimate(self, controller, S, **kwargs):
"""
Get the embedded error estimate of the finest level of the step.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
float: Embedded error estimate
"""
return S.levels[0].status.error_embedded_estimate
class AdaptivityRK(Adaptivity):
"""
Adaptivity for Runge-Kutta methods. Basically, we need to change the order in the step size update
"""
def setup(self, controller, params, description, **kwargs):
defaults = {}
defaults['update_order'] = params.get('update_order', description['sweeper_class'].get_update_order())
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def get_new_step_size(self, controller, S, **kwargs):
"""
Determine a step size for the next step from an embedded estimate of the local error of the current step.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
# check if we performed the desired amount of sweeps
if S.status.iter == S.params.maxiter:
L = S.levels[0]
# compute next step size
order = self.params.update_order
e_est = self.get_local_error_estimate(controller, S)
L.status.dt_new = self.compute_optimal_step_size(
self.params.beta, L.params.dt, self.params.e_tol, e_est, order
)
self.log(f'Adjusting step size from {L.params.dt:.2e} to {L.status.dt_new:.2e}', S)
return None
class AdaptivityResidual(AdaptivityBase):
"""
Do adaptivity based on residual.
Since we don't know a correlation between the residual and the error (for nonlinear problems), we employ a simpler
rule to update the step size. Instead of giving a local tolerance that we try to hit as closely as possible, we set
two thresholds for the residual. When we exceed the upper one, we reduce the step size by a factor of 2 and if the
residual falls below the lower threshold, we double the step size.
Please setup these parameters as "e_tol" and "e_tol_low".
"""
def setup(self, controller, params, description, **kwargs):
"""
Define default parameters here.
Default parameters are:
- control_order (int): The order relative to other convergence controllers
- e_tol_low (float): Lower absolute threshold for the residual
- e_tol (float): Upper absolute threshold for the residual
- max_restarts: Override maximum number of restarts
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {
"control_order": -45,
"e_tol_low": 0,
"e_tol": np.inf,
"max_restarts": 99 if "e_tol_low" in params else None,
"allowed_modifications": ['increase', 'decrease'], # what we are allowed to do with the step size
}
return {**defaults, **params}
def setup_status_variables(self, controller, **kwargs):
"""
Change maximum number of allowed restarts here.
Args:
controller (pySDC.Controller): The controller
Reutrns:
None
"""
if self.params.max_restarts is not None:
conv_controllers = controller.convergence_controllers
restart_cont = [me for me in conv_controllers if type(me) == BasicRestartingNonMPI]
if len(restart_cont) == 0:
raise NotImplementedError("Please implement override of maximum number of restarts!")
restart_cont[0].params.max_restarts = self.params.max_restarts
return None
def check_parameters(self, controller, params, description, **kwargs):
"""
Check whether parameters are compatible with whatever assumptions went into the step size functions etc.
For adaptivity, we want a fixed order of the scheme.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
bool: Whether the parameters are compatible
str: The error message
"""
if description["level_params"].get("restol", -1.0) >= 0:
return (
False,
"Adaptivity needs constant order in time and hence restol in the step parameters has to be \
smaller than 0!",
)
if controller.params.mssdc_jac:
return (
False,
"Adaptivity needs the same order on all steps, please activate Gauss-Seidel multistep mode!",
)
return True, ""
def get_new_step_size(self, controller, S, **kwargs):
"""
Determine a step size for the next step.
If we exceed the absolute tolerance of the residual in either direction, we either double or halve the step
size.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
# check if we performed the desired amount of sweeps
if S.status.iter == S.params.maxiter:
L = S.levels[0]
res = self.get_local_error_estimate(controller, S)
dt_planned = L.status.dt_new if L.status.dt_new is not None else L.params.dt
if res > self.params.e_tol and 'decrease' in self.params.allowed_modifications:
L.status.dt_new = min([dt_planned, L.params.dt / 2.0])
self.log(f'Adjusting step size from {L.params.dt:.2e} to {L.status.dt_new:.2e}', S)
elif res < self.params.e_tol_low and 'increase' in self.params.allowed_modifications:
L.status.dt_new = max([dt_planned, L.params.dt * 2.0])
self.log(f'Adjusting step size from {L.params.dt:.2e} to {L.status.dt_new:.2e}', S)
return None
def get_local_error_estimate(self, controller, S, **kwargs):
"""
Get the residual of the finest level of the step.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
float: Embedded error estimate
"""
return S.levels[0].status.residual
class AdaptivityCollocation(AdaptivityBase):
"""
Control the step size via a collocation based estimate of the local error.
The error estimate works by subtracting two solutions to collocation problems with different order. You can
interpolate between collocation methods as much as you want but the adaptive step size selection will always be
based on the last switch of quadrature.
"""
def setup(self, controller, params, description, **kwargs):
"""
Add a default value for control order to the parameters.
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: Updated parameters
"""
defaults = {
"adaptive_coll_params": {},
"num_colls": 0,
**super().setup(controller, params, description, **kwargs),
"control_order": 220,
}
for key in defaults['adaptive_coll_params'].keys():
if type(defaults['adaptive_coll_params'][key]) == list:
defaults['num_colls'] = max([defaults['num_colls'], len(defaults['adaptive_coll_params'][key])])
return defaults
def setup_status_variables(self, controller, **kwargs):
self.status = Status(['error', 'order'])
self.status.error = []
self.status.order = []
def reset_status_variables(self, controller, **kwargs):
self.setup_status_variables(controller, **kwargs)
def dependencies(self, controller, description, **kwargs):
"""
Load the `EstimateEmbeddedErrorCollocation` convergence controller to estimate the local error by switching
between collocation problems between iterations.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
"""
from pySDC.implementations.convergence_controller_classes.estimate_embedded_error import (
EstimateEmbeddedErrorCollocation,
)
super().dependencies(controller, description)
params = {'adaptive_coll_params': self.params.adaptive_coll_params}
controller.add_convergence_controller(
EstimateEmbeddedErrorCollocation,
params=params,
description=description,
)
def get_local_error_estimate(self, controller, S, **kwargs):
"""
Get the collocation based embedded error estimate.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
float: Embedded error estimate
"""
if len(self.status.error) > 1:
return self.status.error[-1][1]
else:
return 0.0
def post_iteration_processing(self, controller, step, **kwargs):
"""
Get the error estimate and its order if available.
Args:
controller (pySDC.Controller.controller): The controller
step (pySDC.Step.step): The current step
"""
if step.status.done:
lvl = step.levels[0]
self.status.error += [lvl.status.error_embedded_estimate_collocation]
self.status.order += [lvl.sweep.coll.order]
def get_new_step_size(self, controller, S, **kwargs):
if len(self.status.order) == self.params.num_colls:
lvl = S.levels[0]
# compute next step size
order = (
min(self.status.order[-2::]) + 1
) # local order of less accurate of the last two collocation problems
e_est = self.get_local_error_estimate(controller, S)
lvl.status.dt_new = self.compute_optimal_step_size(
self.params.beta, lvl.params.dt, self.params.e_tol, e_est, order
)
self.log(f'Adjusting step size from {lvl.params.dt:.2e} to {lvl.status.dt_new:.2e}', S)
def check_parameters(self, controller, params, description, **kwargs):
"""
Check whether parameters are compatible with whatever assumptions went into the step size functions etc.
For adaptivity, we need to know the order of the scheme.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
bool: Whether the parameters are compatible
str: The error message
"""
if controller.params.mssdc_jac:
return (
False,
"Adaptivity needs the same order on all steps, please activate Gauss-Seidel multistep mode!",
)
if "e_tol" not in params.keys():
return (
False,
"Adaptivity needs a local tolerance! Please pass `e_tol` to the parameters for this convergence controller!",
)
return True, ""
def determine_restart(self, controller, S, **kwargs):
"""
Check if the step wants to be restarted by comparing the estimate of the local error to a preset tolerance
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
if len(self.status.order) == self.params.num_colls:
e_est = self.get_local_error_estimate(controller, S)
if e_est >= self.params.e_tol:
S.status.restart = True
self.log(f"Restarting: e={e_est:.2e} >= e_tol={self.params.e_tol:.2e}", S)
class AdaptivityExtrapolationWithinQ(AdaptivityBase):
"""
Class to compute time step size adaptively based on error estimate obtained from extrapolation within the quadrature
nodes.
This error estimate depends on solving the collocation problem exactly, so make sure you set a sufficient stopping criterion.
"""
def setup(self, controller, params, description, **kwargs):
"""
Add a default value for control order to the parameters.
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: Updated parameters
"""
defaults = {
**super().setup(controller, params, description, **kwargs),
}
return defaults
def dependencies(self, controller, description, **kwargs):
"""
Load the error estimator.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
from pySDC.implementations.convergence_controller_classes.estimate_extrapolation_error import (
EstimateExtrapolationErrorWithinQ,
)
super().dependencies(controller, description)
controller.add_convergence_controller(
EstimateExtrapolationErrorWithinQ,
description=description,
)
return None
def check_parameters(self, controller, params, description, **kwargs):
"""
Check whether parameters are compatible with whatever assumptions went into the step size functions etc.
For adaptivity, we need to know the order of the scheme.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
bool: Whether the parameters are compatible
str: The error message
"""
if "e_tol" not in params.keys():
return (
False,
"Adaptivity needs a local tolerance! Please pass `e_tol` to the parameters for this convergence controller!",
)
return True, ""
def get_new_step_size(self, controller, S, **kwargs):
"""
Determine a step size for the next step from the error estimate.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
# check if the step is converged
from pySDC.implementations.convergence_controller_classes.check_convergence import CheckConvergence
if CheckConvergence.check_convergence(S):
L = S.levels[0]
# compute next step size
order = L.sweep.coll.num_nodes + 1
e_est = self.get_local_error_estimate(controller, S)
L.status.dt_new = self.compute_optimal_step_size(
self.params.beta, L.params.dt, self.params.e_tol, e_est, order
)
self.log(
f'Error target: {self.params.e_tol:.2e}, error estimate: {e_est:.2e}, update_order: {order}',
S,
level=10,
)
self.log(f'Adjusting step size from {L.params.dt:.2e} to {L.status.dt_new:.2e}', S)
# check if we need to restart
S.status.restart = e_est > self.params.e_tol
return None
def get_local_error_estimate(self, controller, S, **kwargs):
"""
Get the embedded error estimate of the finest level of the step.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
float: Embedded error estimate
"""
return S.levels[0].status.error_extrapolation_estimate
| 28,403 | 37.487805 | 151 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/spread_step_sizes.py | import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController
class SpreadStepSizesBlockwise(ConvergenceController):
"""
Take the step size from the last step in the block and spread it to all steps in the next block such that every step
in a block always has the same step size.
By block we refer to a composite collocation problem, which is solved in pipelined SDC parallel-in-time.
Also, we overrule the step size control here, if we get close to the final time and we would take too large of a
step otherwise.
"""
def setup(self, controller, params, description, **kwargs):
"""
Define parameters here
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {
"control_order": +100,
}
return {**defaults, **super().setup(controller, params, description, **kwargs)}
@classmethod
def get_implementation(cls, useMPI, **kwargs):
"""
Get MPI or non-MPI version
Args:
useMPI (bool): The implementation that you want
Returns:
cls: The child class implementing the desired flavor
"""
if useMPI:
return SpreadStepSizesBlockwiseMPI
else:
return SpreadStepSizesBlockwiseNonMPI
class SpreadStepSizesBlockwiseNonMPI(SpreadStepSizesBlockwise):
"""
Non-MPI version
"""
def prepare_next_block(self, controller, S, size, time, Tend, MS, **kwargs):
"""
Spread the step size of the last step with no restarted predecessors to all steps and limit the step size based
on Tend
Args:
controller (pySDC.Controller): The controller
S (pySDC.step): The current step
size (int): The number of ranks
time (list): List containing the time of all the steps handled by the controller (or float in MPI implementation)
Tend (float): Final time of the simulation
MS (list): Active steps
Returns:
None
"""
# inactive steps don't need to participate
if S not in MS:
return None
# figure out where the block is restarted
restarts = [me.status.restart for me in MS]
if True in restarts:
restart_at = np.where(restarts)[0][0]
else:
restart_at = len(restarts) - 1
# Compute the maximum allowed step size based on Tend.
dt_max = (Tend - time[0]) / size
# record the step sizes to restart with from all the levels of the step
new_steps = [None] * len(S.levels)
for i in range(len(MS[restart_at].levels)):
l = MS[restart_at].levels[i]
# overrule the step size control to reach Tend if needed
new_steps[i] = min(
[
l.status.dt_new if l.status.dt_new is not None else l.params.dt,
max([dt_max, l.params.dt_initial]),
]
)
if (
new_steps[i] < (l.status.dt_new if l.status.dt_new is not None else l.params.dt)
and i == 0
and l.status.dt_new is not None
):
self.log(
f"Overwriting stepsize control to reach Tend: {Tend:.2e}! New step size: {new_steps[i]:.2e}", S
)
# spread the step sizes to all levels
for i in range(len(S.levels)):
S.levels[i].params.dt = new_steps[i]
return None
class SpreadStepSizesBlockwiseMPI(SpreadStepSizesBlockwise):
def prepare_next_block(self, controller, S, size, time, Tend, comm, **kwargs):
"""
Spread the step size of the last step with no restarted predecessors to all steps and limit the step size based
on Tend
Args:
controller (pySDC.Controller): The controller
S (pySDC.step): The current step
size (int): The number of ranks
time (list): List containing the time of all the steps handled by the controller (or float in MPI implementation)
Tend (float): Final time of the simulation
comm (mpi4py.MPI.Intracomm): Communicator
Returns:
None
"""
# figure out where the block is restarted
restarts = comm.allgather(S.status.restart)
if True in restarts:
restart_at = np.where(restarts)[0][0]
else:
restart_at = len(restarts) - 1
# Compute the maximum allowed step size based on Tend.
dt_max = comm.bcast((Tend - time) / size, root=restart_at)
# record the step sizes to restart with from all the levels of the step
new_steps = [None] * len(S.levels)
if S.status.slot == restart_at:
for i in range(len(S.levels)):
l = S.levels[i]
# overrule the step size control to reach Tend if needed
new_steps[i] = min(
[
l.status.dt_new if l.status.dt_new is not None else l.params.dt,
max([dt_max, l.params.dt_initial]),
]
)
if (
new_steps[i] < l.status.dt_new
if l.status.dt_new is not None
else l.params.dt and l.status.dt_new is not None
):
self.log(
f"Overwriting stepsize control to reach Tend: {Tend:.2e}! New step size: {new_steps[i]:.2e}", S
)
new_steps = comm.bcast(new_steps, root=restart_at)
# spread the step sizes to all levels
for i in range(len(S.levels)):
S.levels[i].params.dt = new_steps[i]
return None
| 6,077 | 35.178571 | 125 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/adaptive_collocation.py | import numpy as np
from pySDC.core.Lagrange import LagrangeApproximation
from pySDC.core.ConvergenceController import ConvergenceController, Status
from pySDC.core.Collocation import CollBase
class AdaptiveCollocation(ConvergenceController):
"""
This convergence controller allows to change the underlying quadrature between iterations.
Supplying multiple quadrature rules will result in a change to a new quadrature whenever the previous one is
converged until all methods given are converged, at which point the step is ended.
Whenever the quadrature is changed, the solution is interpolated from the old nodes to the new nodes to ensure
accelerated convergence compared to starting from the initial conditions.
Use this convergence controller by supplying parameters that the sweeper accepts as a list to the `params`.
For instance, supplying
```
params = {
'num_nodes': [2, 3],
}
```
will use collocation methods like you passed to the `sweeper_params` in the `description` object, but will change
the number of nodes to 2 before the first iteration and to 3 as soon as the 2-node collocation problem is converged.
This will override whatever you set for the number of nodes in the `sweeper_params`, but you still need to set
something to allow instantiation of the levels before this convergence controller becomes active.
Make sure all lists you supply here have the same length.
Feel free to set `logger_level = 15` in the controller parameters to get comprehensive text output on what exactly
is happening.
This convergence controller has various applications.
- You could try to obtain speedup by doing some inexactness. It is currently possible to set various residual
tolerances, which will be passed to the levels, corresponding to the accuracy with which each collocation problem
is solved.
- You can compute multiple solutions to the same initial value problem with different order. This allows, for
instance, to do adaptive time stepping.
When trying to obtain speedup with this, be ware that the interpolation is not for free. In particular, it is
necessary to reevaluate the right hand side at all nodes afterwards.
"""
def setup(self, controller, params, description, **kwargs):
"""
Record what variables we want to vary.
Args:
controller (pySDC.Controller.controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {
'control_order': 300,
'num_colls': 0,
'sweeper_params': description['sweeper_params'],
'vary_keys_sweeper': [],
'vary_keys_level': [],
}
# only these keys can be changed by this convergence controller
self.allowed_sweeper_keys = ['quad_type', 'num_nodes', 'node_type', 'do_coll_update']
self.allowed_level_keys = ['restol']
# add the keys to lists so we know what we need to change later
for key in params.keys():
if type(params[key]) == list:
if key in self.allowed_sweeper_keys:
defaults['vary_keys_sweeper'] += [key]
elif key in self.allowed_level_keys:
defaults['vary_keys_level'] += [key]
else:
raise NotImplementedError(f'Don\'t know what to do with key {key} here!')
defaults['num_colls'] = max([defaults['num_colls'], len(params[key])])
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def switch_sweeper(self, S):
"""
Update to the next sweeper in line.
Args:
S (pySDC.Step.step): The current step
Returns:
None
"""
# generate dictionaries with the new parameters
new_params_sweeper = {
key: self.params.get(key)[self.status.active_coll] for key in self.params.vary_keys_sweeper
}
sweeper_params = self.params.sweeper_params.copy()
update_params_sweeper = {**sweeper_params, **new_params_sweeper}
new_params_level = {key: self.params.get(key)[self.status.active_coll] for key in self.params.vary_keys_level}
# update sweeper for all levels
for L in S.levels:
P = L.prob
# store solution of current level which will be interpolated to new level
u_old = [me.flatten() for me in L.u]
nodes_old = L.sweep.coll.nodes.copy()
# change sweeper
L.sweep.__init__(update_params_sweeper)
L.sweep.level = L
# reset level to tell it the new structure of the solution
L.params.__dict__.update(new_params_level)
L.reset_level(reset_status=False)
# interpolate solution of old collocation problem to new one
nodes_new = L.sweep.coll.nodes.copy()
interpolator = LagrangeApproximation(points=np.append(0, nodes_old))
u_inter = interpolator.getInterpolationMatrix(np.append(0, nodes_new)) @ u_old
# assign the interpolated values to the nodes in the level
for i in range(0, len(u_inter)):
me = P.dtype_u(P.init)
me[:] = np.reshape(u_inter[i], P.init[0])
L.u[i] = me
# reevaluate rhs
for i in range(L.sweep.coll.num_nodes + 1):
L.f[i] = L.prob.eval_f(L.u[i], L.time)
# log the new parameters
self.log(f'Switching to collocation {self.status.active_coll + 1} of {self.params.num_colls}', S, level=20)
msg = 'New quadrature:'
for key in list(sweeper_params.keys()) + list(new_params_level.keys()):
if key in self.params.vary_keys_sweeper:
msg += f'\n--> {key}: {update_params_sweeper[key]}'
elif key in self.params.vary_keys_level:
msg += f'\n--> {key}: {new_params_level[key]}'
else:
msg += f'\n {key}: {update_params_sweeper[key]}'
self.log(msg, S)
def setup_status_variables(self, controller, **kwargs):
"""
Add an index for which collocation method to use.
Args:
controller (pySDC.Controller.controller): The controller
Returns:
None
"""
self.status = Status(['active_coll'])
def reset_status_variables(self, controller, **kwargs):
"""
Reset the status variables between time steps.
Args:
controller (pySDC.Controller.controller): The controller
Returns:
None
"""
self.status.active_coll = 0
def post_iteration_processing(self, controller, S, **kwargs):
"""
Switch to the next collocation method if the current one is converged.
Args:
controller (pySDC.Controller.controller): The controller
S (pySDC.Step.step): The current step
Returns:
None
"""
if (self.status.active_coll < self.params.num_colls - 1) and S.status.done:
self.status.active_coll += 1
S.status.done = False
self.switch_sweeper(S)
def post_spread_processing(self, controller, S, **kwargs):
"""
Overwrite the sweeper parameters with the first collocation parameters set up here.
Args:
controller (pySDC.Controller.controller): The controller
S (pySDC.Step.step): The current step
Returns:
None
"""
self.switch_sweeper(S)
def check_parameters(self, controller, params, description, **kwargs):
"""
Check if we allow the scheme to solve the collocation problems to convergence.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
bool: Whether the parameters are compatible
str: The error message
"""
if description["level_params"].get("restol", -1.0) <= 1e-16:
return (
False,
"Switching the collocation problems requires solving them to some tolerance that can be reached. Please set attainable `restol` in the level params",
)
if description["step_params"].get("maxiter", -1.0) < 99:
return (
False,
"Switching the collocation problems requires solving them exactly, which may require many iterations please set `maxiter` to at least 99 in the step params",
)
return True, ""
| 9,027 | 39.124444 | 173 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/hotrod.py | import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController
from pySDC.implementations.convergence_controller_classes.estimate_extrapolation_error import (
EstimateExtrapolationErrorNonMPI,
)
class HotRod(ConvergenceController):
"""
Class that incorporates the Hot Rod detector [1] for soft faults. Based on comparing two estimates of the local
error.
Default control order is -40.
See for the reference:
[1]: Lightweight and Accurate Silent Data Corruption Detection in Ordinary Differential Equation Solvers,
Guhur et al. 2016, Springer. DOI: https://doi.org/10.1007/978-3-319-43659-3_47
"""
def setup(self, controller, params, description, **kwargs):
"""
Setup default values for crucial parameters.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: The updated params
"""
default_params = {
"HotRod_tol": np.inf,
"control_order": -40,
"no_storage": False,
}
return {**default_params, **super().setup(controller, params, description, **kwargs)}
def dependencies(self, controller, description, **kwargs):
"""
Load the dependencies of Hot Rod, which are the two error estimators
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
from pySDC.implementations.convergence_controller_classes.estimate_embedded_error import EstimateEmbeddedError
controller.add_convergence_controller(
EstimateEmbeddedError.get_implementation(flavor='linearized', useMPI=self.params.useMPI),
description=description,
)
if not self.params.useMPI:
controller.add_convergence_controller(
EstimateExtrapolationErrorNonMPI, description=description, params={'no_storage': self.params.no_storage}
)
else:
raise NotImplementedError("Don't know how to estimate extrapolated error with MPI")
def check_parameters(self, controller, params, description, **kwargs):
"""
Check whether parameters are compatible with whatever assumptions went into the step size functions etc.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
bool: Whether the parameters are compatible
str: Error message
"""
if self.params.HotRod_tol == np.inf:
controller.logger.warning(
"Hot Rod needs a detection threshold, which is now set to infinity, such that a \
restart is never triggered!"
)
if description["step_params"].get("restol", -1.0) >= 0:
return (
False,
"Hot Rod needs constant order in time and hence restol in the step parameters has to be \
smaller than 0!",
)
if controller.params.mssdc_jac:
return (
False,
"Hot Rod needs the same order on all steps, please activate Gauss-Seidel multistep mode!",
)
return True, ""
def determine_restart(self, controller, S, **kwargs):
"""
Check if the difference between the error estimates exceeds the allowed tolerance
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
# we determine whether to restart only on the last sweep
if S.status.iter < S.params.maxiter:
return None
for L in S.levels:
if None not in [
L.status.error_extrapolation_estimate,
L.status.error_embedded_estimate,
]:
diff = abs(L.status.error_extrapolation_estimate - L.status.error_embedded_estimate)
if diff > self.params.HotRod_tol:
S.status.restart = True
self.log(
f"Triggering restart: delta={diff:.2e}, tol={self.params.HotRod_tol:.2e}",
S,
)
return None
def post_iteration_processing(self, controller, S, **kwargs):
"""
Throw away the final sweep to match the error estimates.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
if S.status.iter == S.params.maxiter:
for L in S.levels:
L.u[:] = L.uold[:]
return None
| 5,092 | 34.368056 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/check_iteration_estimator.py | import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController, Status
from pySDC.implementations.convergence_controller_classes.store_uold import StoreUOld
class CheckIterationEstimatorNonMPI(ConvergenceController):
def __init__(self, controller, params, description, **kwargs):
"""
Initalization routine
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
"""
super(CheckIterationEstimatorNonMPI, self).__init__(controller, params, description)
self.buffers = Status(["Kest_loc", "diff_new", "Ltilde_loc"])
self.status = Status(["diff_old_loc", "diff_first_loc"])
def check_parameters(self, controller, params, description, **kwargs):
"""
Check whether parameters are compatible with whatever assumptions went into the step size functions etc.
In this case, we need the user to supply a tolerance.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
bool: Whether the parameters are compatible
str: The error message
"""
if "errtol" not in params.keys():
return (
False,
"Please give the iteration estimator a tolerance in the form of `errtol`. Thanks!",
)
return True, ""
def setup(self, controller, params, description, **kwargs):
"""
Setup parameters. Here we only give a default value for the control order.
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: The updated parameters
"""
return {"control_order": -50, **super().setup(controller, params, description, **kwargs)}
def dependencies(self, controller, description, **kwargs):
"""
Need to store the solution of previous iterations.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
controller.add_convergence_controller(StoreUOld, description=description)
return None
def reset_buffers_nonMPI(self, controller, **kwargs):
"""
Reset buffers used to immitate communication in non MPI version.
Args:
controller (pySDC.controller): The controller
Returns:
None
"""
self.buffers.Kest_loc = [99] * len(controller.MS)
self.buffers.diff_new = 0.0
self.buffers.Ltilde_loc = 0.0
def setup_status_variables(self, controller, **kwargs):
"""
Setup storage variables for the differences between sweeps for all steps.
Args:
controller (pySDC.Controller): The controller
Returns:
None
"""
self.status.diff_old_loc = [0.0] * len(controller.MS)
self.status.diff_first_loc = [0.0] * len(controller.MS)
return None
def check_iteration_status(self, controller, S, **kwargs):
"""
Args:
controller (pySDC.Controller): The controller
S (pySDC.step): The current step
Returns:
None
"""
L = S.levels[0]
slot = S.status.slot
# find the global maximum difference between iterations
for m in range(1, L.sweep.coll.num_nodes + 1):
self.buffers.diff_new = max(self.buffers.diff_new, abs(L.uold[m] - L.u[m]))
if S.status.iter == 1:
self.status.diff_old_loc[slot] = self.buffers.diff_new
self.status.diff_first_loc[slot] = self.buffers.diff_new
elif S.status.iter > 1:
# approximate contraction factor
self.buffers.Ltilde_loc = min(self.buffers.diff_new / self.status.diff_old_loc[slot], 0.9)
self.status.diff_old_loc[slot] = self.buffers.diff_new
# estimate how many more iterations we need for this step to converge to the desired tolerance
alpha = 1 / (1 - self.buffers.Ltilde_loc) * self.status.diff_first_loc[slot]
self.buffers.Kest_loc = np.log(self.params.errtol / alpha) / np.log(self.buffers.Ltilde_loc) * 1.05
self.logger.debug(
f'LOCAL: {L.time:8.4f}, {S.status.iter}: {int(np.ceil(self.buffers.Kest_loc))}, '
f'{self.buffers.Ltilde_loc:8.6e}, {self.buffers.Kest_loc:8.6e}, \
{self.buffers.Ltilde_loc ** S.status.iter * alpha:8.6e}'
)
# set global Kest as last local one, force stop if done
if S.status.last:
Kest_glob = self.buffers.Kest_loc
if np.ceil(Kest_glob) <= S.status.iter:
S.status.force_done = True
| 5,266 | 37.445255 | 112 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/estimate_embedded_error.py | import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController, Pars, Status
from pySDC.implementations.convergence_controller_classes.store_uold import StoreUOld
from pySDC.implementations.sweeper_classes.Runge_Kutta import RungeKutta
class EstimateEmbeddedError(ConvergenceController):
"""
The embedded error is obtained by computing two solutions of different accuracy and pretending the more accurate
one is an exact solution from the point of view of the less accurate solution. In practice, we like to compute the
solutions with different order methods, meaning that in SDC we can just subtract two consecutive sweeps, as long as
you make sure your preconditioner is compatible, which you have to just try out...
"""
@classmethod
def get_implementation(cls, flavor='standard', useMPI=False):
"""
Retrieve the implementation for a specific flavor of this class.
Args:
flavor (str): The implementation that you want
Returns:
cls: The child class that implements the desired flavor
"""
if flavor == 'standard':
return cls
elif flavor == 'linearized':
if useMPI:
return EstimateEmbeddedErrorLinearizedMPI
else:
return EstimateEmbeddedErrorLinearizedNonMPI
elif flavor == 'collocation':
return EstimateEmbeddedErrorCollocation
else:
raise NotImplementedError(f'Flavor {flavor} of EstimateEmbeddedError is not implemented!')
def setup(self, controller, params, description, **kwargs):
"""
Add a default value for control order to the parameters and check if we are using a Runge-Kutta sweeper
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: Updated parameters
"""
sweeper_type = 'RK' if RungeKutta in description['sweeper_class'].__bases__ else 'SDC'
return {
"control_order": -80,
"sweeper_type": sweeper_type,
**super().setup(controller, params, description, **kwargs),
}
def dependencies(self, controller, description, **kwargs):
"""
Load the convergence controller that stores the solution of the last sweep unless we are doing Runge-Kutta.
Add the hook for recording the error.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
if RungeKutta not in description["sweeper_class"].__bases__:
controller.add_convergence_controller(StoreUOld, description=description)
from pySDC.implementations.hooks.log_embedded_error_estimate import LogEmbeddedErrorEstimate
controller.add_hook(LogEmbeddedErrorEstimate)
return None
def estimate_embedded_error_serial(self, L):
"""
Estimate the serial embedded error, which may need to be modified for a parallel estimate.
Depending on the type of sweeper, the lower order solution is stored in a different place.
Args:
L (pySDC.level): The level
Returns:
dtype_u: The embedded error estimate
"""
if self.params.sweeper_type == "RK":
# lower order solution is stored in the second to last entry of L.u
return abs(L.u[-2] - L.u[-1])
elif self.params.sweeper_type == "SDC":
# order rises by one between sweeps, making this so ridiculously easy
return abs(L.uold[-1] - L.u[-1])
else:
raise NotImplementedError(
f"Don't know how to estimate embedded error for sweeper type \
{self.params.sweeper_type}"
)
def setup_status_variables(self, controller, **kwargs):
"""
Add the embedded error variable to the error function.
Args:
controller (pySDC.Controller): The controller
"""
if 'comm' in kwargs.keys():
steps = [controller.S]
else:
if 'active_slots' in kwargs.keys():
steps = [controller.MS[i] for i in kwargs['active_slots']]
else:
steps = controller.MS
where = ["levels", "status"]
for S in steps:
self.add_variable(S, name='error_embedded_estimate', where=where, init=None)
def reset_status_variables(self, controller, **kwargs):
self.setup_status_variables(controller, **kwargs)
def post_iteration_processing(self, controller, S, **kwargs):
"""
Estimate the local error here.
If you are doing MSSDC, this is the global error within the block in Gauss-Seidel mode.
In Jacobi mode, I haven't thought about what this is.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
if S.status.iter > 0 or self.params.sweeper_type == "RK":
for L in S.levels:
L.status.error_embedded_estimate = max([self.estimate_embedded_error_serial(L), np.finfo(float).eps])
return None
class EstimateEmbeddedErrorLinearizedNonMPI(EstimateEmbeddedError):
def __init__(self, controller, params, description, **kwargs):
"""
Initialisation routine. Add the buffers for communication.
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
"""
super().__init__(controller, params, description, **kwargs)
self.buffers = Pars({'e_em_last': 0.0})
def reset_buffers_nonMPI(self, controller, **kwargs):
"""
Reset buffers for imitated communication.
Args:
controller (pySDC.controller): The controller
Returns:
None
"""
self.buffers.e_em_last = 0.0
return None
def post_iteration_processing(self, controller, S, **kwargs):
"""
Compute embedded error estimate on the last node of each level
In serial this is the local error, but in block Gauss-Seidel MSSDC this is a semi-global error in each block
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
if len(S.levels) > 1 and len(controller.MS) > 1:
raise NotImplementedError(
"Embedded error estimate only works for serial multi-level or parallel single \
level"
)
if S.status.iter > 0 or self.params.sweeper_type == "RK":
for L in S.levels:
temp = self.estimate_embedded_error_serial(L)
L.status.error_embedded_estimate = max([abs(temp - self.buffers.e_em_last), np.finfo(float).eps])
self.buffers.e_em_last = temp * 1.0
return None
class EstimateEmbeddedErrorLinearizedMPI(EstimateEmbeddedError):
def __init__(self, controller, params, description, **kwargs):
"""
Initialisation routine. Add the buffers for communication.
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
"""
super().__init__(controller, params, description, **kwargs)
self.buffers = Pars({'e_em_last': 0.0})
def post_iteration_processing(self, controller, S, **kwargs):
"""
Compute embedded error estimate on the last node of each level
In serial this is the local error, but in block Gauss-Seidel MSSDC this is a semi-global error in each block
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
comm = kwargs['comm']
if S.status.iter > 0 or self.params.sweeper_type == "RK":
for L in S.levels:
# get accumulated local errors from previous steps
if not S.status.first:
if not S.status.prev_done:
self.buffers.e_em_last = self.recv(comm, S.status.slot - 1)
else:
self.buffers.e_em_last = 0.0
# estimate accumulated local error
temp = self.estimate_embedded_error_serial(L)
# estimate local error as difference of accumulated errors
L.status.error_embedded_estimate = max([abs(temp - self.buffers.e_em_last), np.finfo(float).eps])
# send the accumulated local errors forward
if not S.status.last:
self.send(comm, dest=S.status.slot + 1, data=temp, blocking=True)
return None
class EstimateEmbeddedErrorCollocation(ConvergenceController):
"""
Estimates an embedded error based on changing the underlying quadrature rule. The error estimate is stored as
`error_embedded_estimate_collocation` in the status of the level. Note that we only compute the estimate on the
finest level. The error is stored as a tuple with the first index denoting to which iteration it belongs. This
is useful since the error estimate is not available immediately after, but only when the next collocation problem
is converged to make sure the two solutions are of different accuracy.
Changing the collocation method between iterations happens using the `AdaptiveCollocation` convergence controller.
Please refer to that for documentation on how to use this. Just pass the parameters for that convergence controller
as `adaptive_coll_params` to the parameters for this one and they will be passed on when the `AdaptiveCollocation`
convergence controller is automatically added while loading dependencies.
"""
def setup(self, controller, params, description, **kwargs):
"""
Add a default value for control order to the parameters
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: Updated parameters
"""
defaults = {
"control_order": 210,
"adaptive_coll_params": {},
**super().setup(controller, params, description, **kwargs),
}
return defaults
def dependencies(self, controller, description, **kwargs):
"""
Load the `AdaptiveCollocation` convergence controller to switch between collocation problems between iterations.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
"""
from pySDC.implementations.convergence_controller_classes.adaptive_collocation import AdaptiveCollocation
controller.add_convergence_controller(
AdaptiveCollocation, params=self.params.adaptive_coll_params, description=description
)
from pySDC.implementations.hooks.log_embedded_error_estimate import LogEmbeddedErrorEstimate
controller.add_hook(LogEmbeddedErrorEstimate)
def post_iteration_processing(self, controller, step, **kwargs):
"""
Compute the embedded error as the difference between the interpolated and the current solution on the finest
level.
Args:
controller (pySDC.Controller.controller): The controller
step (pySDC.Step.step): The current step
"""
if step.status.done:
lvl = step.levels[0]
lvl.sweep.compute_end_point()
self.status.u += [lvl.uend]
self.status.iter += [step.status.iter]
if len(self.status.u) > 1:
lvl.status.error_embedded_estimate_collocation = (
self.status.iter[-2],
max([np.finfo(float).eps, abs(self.status.u[-1] - self.status.u[-2])]),
)
def setup_status_variables(self, controller, **kwargs):
"""
Add the embedded error variable to the levels and add a status variable for previous steps.
Args:
controller (pySDC.Controller): The controller
"""
self.status = Status(['u', 'iter'])
self.status.u = [] # the solutions of converged collocation problems
self.status.iter = [] # the iteration in which the solution converged
if 'comm' in kwargs.keys():
steps = [controller.S]
else:
if 'active_slots' in kwargs.keys():
steps = [controller.MS[i] for i in kwargs['active_slots']]
else:
steps = controller.MS
where = ["levels", "status"]
for S in steps:
self.add_variable(S, name='error_embedded_estimate_collocation', where=where, init=None)
def reset_status_variables(self, controller, **kwargs):
self.setup_status_variables(controller, **kwargs)
| 13,587 | 38.5 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/estimate_extrapolation_error.py | import numpy as np
from scipy.special import factorial
from pySDC.core.ConvergenceController import ConvergenceController, Status
from pySDC.core.Errors import DataError
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
from pySDC.implementations.hooks.log_extrapolated_error_estimate import LogExtrapolationErrorEstimate
class EstimateExtrapolationErrorBase(ConvergenceController):
"""
Abstract base class for extrapolated error estimates
----------------------------------------------------
This error estimate extrapolates a solution based on Taylor expansions using solutions of previous time steps.
In particular, child classes need to implement how to make these solutions available, which works differently for
MPI and non-MPI versions.
"""
def __init__(self, controller, params, description, **kwargs):
"""
Initialization routine
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
"""
self.prev = Status(["t", "u", "f", "dt"]) # store solutions etc. of previous steps here
self.coeff = Status(["u", "f", "prefactor"]) # store coefficients for extrapolation here
super().__init__(controller, params, description)
controller.add_hook(LogExtrapolationErrorEstimate)
def setup(self, controller, params, description, **kwargs):
"""
The extrapolation based method requires storage of previous values of u, f, t and dt and also requires solving
a linear system of equations to compute the Taylor expansion finite difference style. Here, all variables are
initialized which are needed for this process.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: Updated parameters with default values
"""
from pySDC.implementations.convergence_controller_classes.hotrod import HotRod
from pySDC.implementations.convergence_controller_classes.adaptivity import (
Adaptivity,
)
default_params = {
"control_order": -75,
"use_adaptivity": True in [me == Adaptivity for me in description.get("convergence_controllers", {})],
"use_HotRod": True in [me == HotRod for me in description.get("convergence_controllers", {})],
"order_time_marching": description["step_params"]["maxiter"],
}
new_params = {**default_params, **super().setup(controller, params, description, **kwargs)}
# Do a sufficiently high order Taylor expansion
new_params["Taylor_order"] = new_params["order_time_marching"] + 2
# Estimate and store values from this iteration
new_params["estimate_iter"] = new_params["order_time_marching"] - (1 if new_params["use_HotRod"] else 0)
# Store n values. Since we store u and f, we need only half of each (the +1 is for rounding)
new_params["n"] = (new_params["Taylor_order"] + 1) // 2
new_params["n_per_proc"] = new_params["n"] * 1
return new_params
def setup_status_variables(self, controller, **kwargs):
"""
Initialize coefficient variables and add variable to the levels for extrapolated error
Args:
controller (pySDC.controller): The controller
Returns:
None
"""
self.coeff.u = [None] * self.params.n
self.coeff.f = [0.0] * self.params.n
self.reset_status_variables(controller, **kwargs)
return None
def reset_status_variables(self, controller, **kwargs):
"""
Add variable for extrapolated error
Args:
controller (pySDC.Controller): The controller
Returns:
None
"""
if 'comm' in kwargs.keys():
steps = [controller.S]
else:
if 'active_slots' in kwargs.keys():
steps = [controller.MS[i] for i in kwargs['active_slots']]
else:
steps = controller.MS
where = ["levels", "status"]
for S in steps:
self.add_variable(S, name='error_extrapolation_estimate', where=where, init=None)
def check_parameters(self, controller, params, description, **kwargs):
"""
Check whether parameters are compatible with whatever assumptions went into the step size functions etc.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
bool: Whether the parameters are compatible
str: Error message
"""
if description["step_params"].get("restol", -1.0) >= 0:
return (
False,
"Extrapolation error needs constant order in time and hence restol in the step parameters \
has to be smaller than 0!",
)
if controller.params.mssdc_jac:
return (
False,
"Extrapolation error estimator needs the same order on all steps, please activate Gauss-Seid\
el multistep mode!",
)
return True, ""
def store_values(self, S, **kwargs):
"""
Store the required attributes of the step to do the extrapolation. We only care about the last collocation
node on the finest level at the moment.
Args:
S (pySDC.Step): The current step
Returns:
None
"""
# figure out which values are to be replaced by the new ones
if None in self.prev.t:
oldest_val = len(self.prev.t) - len(self.prev.t[self.prev.t == [None]])
else:
oldest_val = np.argmin(self.prev.t)
# figure out how to store the right hand side
f = S.levels[0].f[-1]
if type(f) == imex_mesh:
self.prev.f[oldest_val] = f.impl + f.expl
elif type(f) == mesh:
self.prev.f[oldest_val] = f
else:
raise DataError(
f"Unable to store f from datatype {type(f)}, extrapolation based error estimate only\
works with types imex_mesh and mesh"
)
# store the rest of the values
self.prev.u[oldest_val] = S.levels[0].u[-1]
self.prev.t[oldest_val] = S.time + S.dt
self.prev.dt[oldest_val] = S.dt
return None
def get_extrapolation_coefficients(self, t, dt, t_eval):
"""
This function solves a linear system where in the matrix A, the row index reflects the order of the derivative
in the Taylor expansion and the column index reflects the particular step and whether its u or f from that
step. The vector b on the other hand, contains a 1 in the first entry and zeros elsewhere, since we want to
compute the value itself and all the derivatives should vanish after combining the Taylor expansions. This
works to the order of the number of rows and since we want a square matrix for solving, we need the same amount
of columns, which determines the memory overhead, since it is equal to the solutions / rhs that we need in
memory at the time of evaluation.
This is enough to get the extrapolated solution, but if we want to compute the local error, we have to compute
a prefactor. This is based on error accumulation between steps (first step's solution is exact plus 1 LTE,
second solution is exact plus 2 LTE and so on), which can be computed for adaptive step sizes as well. However,
this is only true for linear problems, which means we expect the error estimate to work less well for non-linear
problems.
Since only time differences are important for computing the coefficients, we need to compute this only once when
using constant step sizes. When we allow the step size to change, however, we need to recompute this in every
step, which is activated by the `use_adaptivity` parameter.
Solving for the coefficients requires solving a dense linear system of equations. The number of unknowns is
equal to the order of the Taylor expansion, so this step should be cheap compared to the solves in each SDC
iteration.
The function stores the computed coefficients in the `self.coeff` variables.
Args:
t (list): The list of times at which we have solutions available
dt (list): The step sizes used for computing these solutions (needed for the prefactor)
t_eval (float): The time we want to extrapolate to
Returns:
None
"""
# prepare A matrix
A = np.zeros((self.params.Taylor_order, self.params.Taylor_order))
A[0, 0 : self.params.n] = 1.0
j = np.arange(self.params.Taylor_order)
inv_facs = 1.0 / factorial(j)
# get the steps backwards from the point of evaluation
idx = np.argsort(t)
steps_from_now = t[idx] - t_eval
# fill A matrix
for i in range(1, self.params.Taylor_order):
# Taylor expansions of the solutions
A[i, : self.params.n] = steps_from_now ** j[i] * inv_facs[i]
# Taylor expansions of the first derivatives a.k.a. right hand side evaluations
A[i, self.params.n : self.params.Taylor_order] = (
steps_from_now[2 * self.params.n - self.params.Taylor_order :] ** (j[i] - 1) * inv_facs[i - 1]
)
# prepare rhs
b = np.zeros(self.params.Taylor_order)
b[0] = 1.0
# solve linear system for the coefficients
coeff = np.linalg.solve(A, b)
self.coeff.u = coeff[: self.params.n]
self.coeff.f[self.params.n * 2 - self.params.Taylor_order :] = coeff[self.params.n : self.params.Taylor_order]
# determine prefactor
step_size_ratios = abs(dt[len(dt) - len(self.coeff.u) :] / dt[-1]) ** (self.params.Taylor_order - 1)
inv_prefactor = -sum(step_size_ratios[1:]) - 1.0
for i in range(len(self.coeff.u)):
inv_prefactor += sum(step_size_ratios[1 : i + 1]) * self.coeff.u[i]
self.coeff.prefactor = 1.0 / abs(inv_prefactor)
return None
class EstimateExtrapolationErrorNonMPI(EstimateExtrapolationErrorBase):
"""
Implementation of the extrapolation error estimate for the non-MPI controller.
"""
def setup(self, controller, params, description, **kwargs):
"""
Add a no parameter 'no_storage' which decides whether the standard or the no-memory-overhead version is run,
where only values are used for extrapolation which are in memory of other processes
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: Updated parameters with default values
"""
default_params = super().setup(controller, params, description)
non_mpi_defaults = {
"no_storage": False,
}
return {**non_mpi_defaults, **default_params}
def setup_status_variables(self, controller, **kwargs):
"""
Initialize storage variables.
Args:
controller (pySDC.controller): The controller
Returns:
None
"""
super().setup_status_variables(controller, **kwargs)
self.prev.t = np.array([None] * self.params.n)
self.prev.dt = np.array([None] * self.params.n)
self.prev.u = [None] * self.params.n
self.prev.f = [None] * self.params.n
return None
def post_iteration_processing(self, controller, S, **kwargs):
"""
We perform three key operations here in the last iteration:
- Compute the error estimate
- Compute the coefficients if needed
- Store the values of the step if we pretend not to for the no-memory overhead version
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
if S.status.iter == self.params.estimate_iter:
t_eval = S.time + S.dt
# compute the extrapolation coefficients if needed
if (
(
None in self.coeff.u
or self.params.use_adaptivity
or (not self.params.no_storage and S.status.time_size > 1)
)
and None not in self.prev.t
and t_eval > max(self.prev.t)
):
self.get_extrapolation_coefficients(self.prev.t, self.prev.dt, t_eval)
# compute the error if we can
if None not in self.coeff.u and None not in self.prev.t:
self.get_extrapolated_error(S)
# store the solution and pretend we didn't because in the non MPI version we take a few shortcuts
if self.params.no_storage:
self.store_values(S)
return None
def prepare_next_block(self, controller, S, size, time, Tend, MS, **kwargs):
"""
If the no-memory-overhead version is used, we need to delete stuff that shouldn't be available. Otherwise, we
need to store all the stuff that we can.
Args:
controller (pySDC.Controller): The controller
S (pySDC.step): The current step
size (int): Number of ranks
time (float): The current time
Tend (float): The final time
MS (list): Active steps
Returns:
None
"""
# delete values that should not be available in the next step
if self.params.no_storage:
self.prev.t = np.array([None] * self.params.n)
self.prev.dt = np.array([None] * self.params.n)
self.prev.u = [None] * self.params.n
self.prev.f = [None] * self.params.n
else:
# decide where we need to restart to store everything up to that point
restarts = [S.status.restart for S in MS]
restart_at = np.where(restarts)[0][0] if True in restarts else len(MS)
# store values in the current block that don't need restarting
if restart_at > S.status.slot:
self.store_values(S)
return None
def get_extrapolated_solution(self, S, **kwargs):
"""
Combine values from previous steps to extrapolate.
Args:
S (pySDC.Step): The current step
Returns:
dtype_u: The extrapolated solution
"""
if len(S.levels) > 1:
raise NotImplementedError("Extrapolated estimate only works on the finest level for now")
# prepare variables
u_ex = S.levels[0].u[-1] * 0.0
idx = np.argsort(self.prev.t)
# see if we have a solution for the current step already stored
if (abs(S.time + S.dt - self.prev.t) < 10.0 * np.finfo(float).eps).any():
idx_step = idx[np.argmin(abs(self.prev.t - S.time - S.dt))]
else:
idx_step = max(idx) + 1
# make a mask of all the steps we want to include in the extrapolation
mask = np.logical_and(idx < idx_step, idx >= idx_step - self.params.n)
# do the extrapolation by summing everything up
for i in range(self.params.n):
u_ex += self.coeff.u[i] * self.prev.u[idx[mask][i]] + self.coeff.f[i] * self.prev.f[idx[mask][i]]
return u_ex
def get_extrapolated_error(self, S, **kwargs):
"""
The extrapolation estimate combines values of u and f from multiple steps to extrapolate and compare to the
solution obtained by the time marching scheme.
Args:
S (pySDC.Step): The current step
Returns:
None
"""
u_ex = self.get_extrapolated_solution(S)
if u_ex is not None:
S.levels[0].status.error_extrapolation_estimate = abs(u_ex - S.levels[0].u[-1]) * self.coeff.prefactor
else:
S.levels[0].status.error_extrapolation_estimate = None
class EstimateExtrapolationErrorWithinQ(EstimateExtrapolationErrorBase):
"""
This convergence controller estimates the local error based on comparing the SDC solution to an extrapolated
solution within the quadrature matrix. Collocation methods compute a high order solution from a linear combination
of solutions at intermediate time points. While the intermediate solutions (a.k.a. stages) don't share the order of
accuracy with the solution at the end of the interval, for SDC we know that the order is equal to the number of
nodes + 1 (locally).
That means we can do a Taylor expansion around the end point of the interval to higher order and after cancelling
terms just like we are used to with the extrapolation based error estimate across multiple steps, we get an error
estimate that is of the order accuracy of the stages.
This can be used for adaptivity, for instance, with the nice property that it doesn't matter how we arrived at the
converged collocation solution, as long as we did. We don't rely on knowing the order of accuracy after every sweep,
only after convergence of the collocation problem has been achieved, which we can check from the residual.
"""
def setup(self, controller, params, description, **kwargs):
"""
We need this convergence controller to become active after the check for convergence, because we need the step
to be converged.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: Updated parameters with default values
"""
num_nodes = description['sweeper_params']['num_nodes']
default_params = {
'Taylor_order': 2 * num_nodes,
'n': num_nodes,
}
return {**super().setup(controller, params, description, **kwargs), **default_params}
def post_iteration_processing(self, controller, S, **kwargs):
"""
Compute the extrapolated error estimate here if the step is converged.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
from pySDC.implementations.convergence_controller_classes.check_convergence import CheckConvergence
if not CheckConvergence.check_convergence(S):
return None
lvl = S.levels[0]
nodes_ = lvl.sweep.coll.nodes * S.dt
nodes = S.time + np.append(0, nodes_[:-1])
t_eval = S.time + nodes_[-1]
dts = np.append(nodes_[0], nodes_[1:] - nodes_[:-1])
self.params.Taylor_order = 2 * len(nodes)
self.params.n = len(nodes)
# compute the extrapolation coefficients
# TODO: Maybe this can be reused
self.get_extrapolation_coefficients(nodes, dts, t_eval)
# compute the extrapolated solution
if type(lvl.f[0]) == imex_mesh:
f = [me.impl + me.expl for me in lvl.f]
elif type(lvl.f[0]) == mesh:
f = lvl.f
else:
raise DataError(
f"Unable to store f from datatype {type(lvl.f[0])}, extrapolation based error estimate only\
works with types imex_mesh and mesh"
)
u_ex = lvl.u[-1] * 0.0
for i in range(self.params.n):
u_ex += self.coeff.u[i] * lvl.u[i] + self.coeff.f[i] * f[i]
# store the error
lvl.status.error_extrapolation_estimate = abs(u_ex - lvl.u[-1]) * self.coeff.prefactor
return None
| 20,412 | 39.501984 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/estimate_contraction_factor.py | import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController
from pySDC.implementations.convergence_controller_classes.estimate_embedded_error import EstimateEmbeddedError
class EstimateContractionFactor(ConvergenceController):
"""
Estimate the contraction factor by using the evolution of the embedded error estimate across iterations.
"""
def setup(self, controller, params, description, **kwargs):
"""
Add a default value for control order to the parameters.
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
Returns:
dict: Updated parameters
"""
return {"control_order": -75, "e_tol": None, **super().setup(controller, params, description, **kwargs)}
def dependencies(self, controller, description, **kwargs):
"""
Load estimator of embedded error.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
controller.add_convergence_controller(
EstimateEmbeddedError,
description=description,
)
def setup_status_variables(self, controller, **kwargs):
"""
Add the embedded error, contraction factor and iterations to convergence variable to the status of the levels.
Args:
controller (pySDC.Controller): The controller
Returns:
None
"""
if 'comm' in kwargs.keys():
steps = [controller.S]
else:
if 'active_slots' in kwargs.keys():
steps = [controller.MS[i] for i in kwargs['active_slots']]
else:
steps = controller.MS
where = ["levels", "status"]
for S in steps:
self.add_variable(S, name='error_embedded_estimate_last_iter', where=where, init=None)
self.add_variable(S, name='contraction_factor', where=where, init=None)
if self.params.e_tol is not None:
self.add_variable(S, name='iter_to_convergence', where=where, init=None)
def reset_status_variables(self, controller, **kwargs):
"""
Reinitialize new status variables for the levels.
Args:
controller (pySDC.controller): The controller
Returns:
None
"""
self.setup_status_variables(controller, **kwargs)
def post_iteration_processing(self, controller, S, **kwargs):
"""
Estimate contraction factor here as the ratio of error estimates between iterations and estimate how many more
iterations we need.
Args:
controller (pySDC.controller): The controller
S (pySDC.step): The current step
Returns:
None
"""
for L in S.levels:
if L.status.error_embedded_estimate_last_iter is not None:
L.status.contraction_factor = (
L.status.error_embedded_estimate / L.status.error_embedded_estimate_last_iter
)
if self.params.e_tol is not None:
L.status.iter_to_convergence = max(
[
0,
np.ceil(
np.log(self.params.e_tol / L.status.error_embedded_estimate)
/ np.log(L.status.contraction_factor)
),
]
)
def pre_iteration_processing(self, controller, S, **kwargs):
"""
Store the embedded error estimate of the current iteration in a different place so it doesn't get overwritten.
Args:
controller (pySDC.controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
for L in S.levels:
if L.status.error_embedded_estimate is not None:
L.status.error_embedded_estimate_last_iter = L.status.error_embedded_estimate * 1.0
| 4,301 | 34.85 | 118 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/interpolate_between_restarts.py | import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController, Status
from pySDC.core.Lagrange import LagrangeApproximation
class InterpolateBetweenRestarts(ConvergenceController):
"""
Interpolate the solution and right hand side to the new set of collocation nodes after a restart.
The idea is that when you adjust the step size between restarts, you already know what the new quadrature method
is going to be and possibly interpolating the current iterate to these results in a better initial guess than
spreading the initial conditions or whatever you usually like to do.
"""
def setup(self, controller, params, description, **kwargs):
"""
Store the initial guess used in the sweeper when no restart has happened
Args:
controller (pySDC.Controller.controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
"""
defaults = {
'control_order': 50,
}
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def setup_status_variables(self, controller, **kwargs):
"""
Add variables to the sweeper containing the interpolated solution and right hand side.
Args:
controller (pySDC.Controller.controller): The controller
"""
self.status = Status(['u_inter', 'f_inter', 'perform_interpolation'])
self.status.u_inter = []
self.status.f_inter = []
self.status.perform_interpolation = False
def post_spread_processing(self, controller, step, **kwargs):
"""
Spread the interpolated values to the collocation nodes. This overrides whatever the sweeper uses for prediction.
Args:
controller (pySDC.Controller.controller): The controller
step (pySDC.Step.step): The current step
"""
if self.status.perform_interpolation:
for i in range(len(step.levels)):
level = step.levels[i]
for m in range(len(level.u)):
level.u[m][:] = self.status.u_inter[i][m][:]
level.f[m][:] = self.status.f_inter[i][m][:]
# reset the status variables
self.status.perform_interpolation = False
self.status.u_inter = []
self.status.f_inter = []
def post_iteration_processing(self, controller, step, **kwargs):
"""
Interpolate the solution and right hand sides and store them in the sweeper, where they will be distributed
accordingly in the prediction step.
This function is called after every iteration instead of just after the step because we might choose to stop
iterating as soon as we have decided to restart. If we let the step continue to iterate, this is not the most
efficient implementation and you may choose to write a different convergence controller.
The interpolation is based on Thibaut's magic.
Args:
controller (pySDC.Controller): The controller
step (pySDC.Step.step): The current step
"""
if step.status.restart and all(level.status.dt_new for level in step.levels):
for level in step.levels:
nodes_old = level.sweep.coll.nodes.copy()
nodes_new = level.sweep.coll.nodes.copy() * level.status.dt_new / level.params.dt
interpolator = LagrangeApproximation(points=np.append(0, nodes_old))
interpolation_matrix = interpolator.getInterpolationMatrix(np.append(0, nodes_new))
self.status.u_inter += [(interpolation_matrix @ level.u[:])[:]]
self.status.f_inter += [(interpolation_matrix @ level.f[:])[:]]
self.status.perform_interpolation = True
self.log(
f'Interpolating before restart from dt={level.params.dt:.2e} to dt={level.status.dt_new:.2e}', step
)
else:
self.status.perform_interpolation = False
| 4,166 | 43.806452 | 121 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/check_convergence.py | import numpy as np
from pySDC.core.ConvergenceController import ConvergenceController
class CheckConvergence(ConvergenceController):
"""
Perform simple checks on convergence for SDC iterations.
Iteration is terminated via one of two criteria:
- Residual tolerance
- Maximum number of iterations
"""
def setup(self, controller, params, description, **kwargs):
"""
Define default parameters here
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {'control_order': +200, 'use_e_tol': 'e_tol' in description['level_params'].keys()}
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def dependencies(self, controller, description, **kwargs):
"""
Load the embedded error estimator if needed.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
super().dependencies(controller, description)
if self.params.use_e_tol:
from pySDC.implementations.convergence_controller_classes.estimate_embedded_error import (
EstimateEmbeddedError,
)
controller.add_convergence_controller(
EstimateEmbeddedError,
description=description,
)
return None
@staticmethod
def check_convergence(S):
"""
Check the convergence of a single step.
Test the residual and max. number of iterations as well as allowing overrides to both stop and continue.
Args:
S (pySDC.Step): The current step
Returns:
bool: Convergence status of the step
"""
# do all this on the finest level
L = S.levels[0]
# get residual and check against prescribed tolerance (plus check number of iterations)
iter_converged = S.status.iter >= S.params.maxiter
res_converged = L.status.residual <= L.params.restol
e_tol_converged = (
L.status.error_embedded_estimate < L.params.e_tol
if (L.params.get('e_tol') and L.status.get('error_embedded_estimate'))
else False
)
converged = (
iter_converged or res_converged or e_tol_converged or S.status.force_done
) and not S.status.force_continue
if converged is None:
converged = False
return converged
def check_iteration_status(self, controller, S, **kwargs):
"""
Routine to determine whether to stop iterating (currently testing the residual + the max. number of iterations)
Args:
controller (pySDC.Controller.controller): The controller
S (pySDC.Step.step): The current step
Returns:
None
"""
S.status.done = self.check_convergence(S)
if "comm" in kwargs.keys():
self.communicate_convergence(controller, S, **kwargs)
S.status.force_continue = False
return None
def communicate_convergence(self, controller, S, comm):
"""
Communicate the convergence status during `check_iteration_status` if MPI is used.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step.step): The current step
comm (mpi4py.MPI.Comm): MPI communicator
Returns:
None
"""
# Either gather information about all status or send forward own
if controller.params.all_to_done:
from mpi4py.MPI import LAND
for hook in controller.hooks:
hook.pre_comm(step=S, level_number=0)
S.status.done = comm.allreduce(sendobj=S.status.done, op=LAND)
for hook in controller.hooks:
hook.post_comm(step=S, level_number=0, add_to_stats=True)
else:
for hook in controller.hooks:
hook.pre_comm(step=S, level_number=0)
# check if an open request of the status send is pending
controller.wait_with_interrupt(request=controller.req_status)
if S.status.force_done:
return None
# recv status
if not S.status.first and not S.status.prev_done:
S.status.prev_done = self.recv(comm, source=S.status.slot - 1)
S.status.done = S.status.done and S.status.prev_done
# send status forward
if not S.status.last:
self.send(comm, dest=S.status.slot + 1, data=S.status.done)
for hook in controller.hooks:
hook.post_comm(step=S, level_number=0, add_to_stats=True)
| 5,042 | 33.074324 | 119 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/store_uold.py | from pySDC.core.ConvergenceController import ConvergenceController
class StoreUOld(ConvergenceController):
"""
Class to store the solution of the last iteration in a variable called 'uold' of the levels.
Default control order is 90.
"""
def setup(self, controller, params, description, **kwargs):
"""
Define parameters here
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
return {"control_order": +90, **super().setup(controller, params, description, **kwargs)}
def post_iteration_processing(self, controller, S, **kwargs):
"""
Store the solution at the current iteration
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Return:
None
"""
for L in S.levels:
L.uold[:] = L.u[:]
return None
def post_spread_processing(self, controller, S, **kwargs):
"""
Store the initial conditions in u_old in the spread phase.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Return:
None
"""
self.post_iteration_processing(controller, S, **kwargs)
return None
| 1,556 | 27.833333 | 97 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/inexactness.py | from pySDC.core.ConvergenceController import ConvergenceController
class NewtonInexactness(ConvergenceController):
"""
Gradually refine Newton tolerance based on SDC residual.
Be aware that the problem needs a parameter called "newton_tol" which controls the tolerance for the Newton solver for this to work!
"""
def setup(self, controller, params, description, **kwargs):
"""
Define default parameters here.
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {
"control_order": 500,
"ratio": 1e-2,
"min_tol": 0,
"max_tol": 1e99,
}
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def post_iteration_processing(self, controller, step, **kwargs):
"""
Change the Newton tolerance after every iteration.
Args:
controller (pySDC.Controller.controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
for lvl in step.levels:
lvl.prob.newton_tol = max(
[min([lvl.status.residual * self.params.ratio, self.params.max_tol]), self.params.min_tol]
)
self.log(f'Changed Newton tolerance to {lvl.prob.newton_tol:.2e}', step)
| 1,607 | 33.212766 | 136 | py |
pySDC | pySDC-master/pySDC/implementations/convergence_controller_classes/basic_restarting.py | from pySDC.core.ConvergenceController import ConvergenceController, Pars
from pySDC.implementations.convergence_controller_classes.spread_step_sizes import (
SpreadStepSizesBlockwise,
)
from pySDC.core.Errors import ConvergenceError
class BasicRestarting(ConvergenceController):
"""
Class with some utilities for restarting. The specific functions are:
- Telling each step after one that requested a restart to get restarted as well
- Allowing each step to be restarted a limited number of times in a row before just moving on anyways
Default control order is 95.
"""
@classmethod
def get_implementation(cls, flavor):
"""
Retrieve the implementation for a specific flavor of this class.
Args:
flavor (str): The implementation that you want
Returns:
cls: The child class that implements the desired flavor
"""
if flavor == 'MPI':
return BasicRestartingMPI
elif flavor == 'nonMPI':
return BasicRestartingNonMPI
else:
raise NotImplementedError(f'Flavor {flavor} of BasicRestarting is not implemented!')
def __init__(self, controller, params, description, **kwargs):
"""
Initialization routine
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
"""
super().__init__(controller, params, description)
self.buffers = Pars({"restart": False, "max_restart_reached": False})
def setup(self, controller, params, description, **kwargs):
"""
Define parameters here.
Default parameters are:
- control_order (int): The order relative to other convergence controllers
- max_restarts (int): Maximum number of restarts we allow each step before we just move on with whatever we
have
- step_size_spreader (pySDC.ConvergenceController): A convergence controller that takes care of distributing
the steps sizes between blocks
Args:
controller (pySDC.Controller): The controller
params (dict): The params passed for this specific convergence controller
description (dict): The description object used to instantiate the controller
Returns:
(dict): The updated params dictionary
"""
defaults = {
"control_order": 95,
"max_restarts": 10,
"crash_after_max_restarts": True,
"step_size_spreader": SpreadStepSizesBlockwise.get_implementation(useMPI=params['useMPI']),
}
from pySDC.implementations.hooks.log_restarts import LogRestarts
controller.add_hook(LogRestarts)
return {**defaults, **super().setup(controller, params, description, **kwargs)}
def setup_status_variables(self, controller, **kwargs):
"""
Add status variables for whether to restart now and how many times the step has been restarted in a row to the
Steps
Args:
controller (pySDC.Controller): The controller
reset (bool): Whether the function is called for the first time or to reset
Returns:
None
"""
where = ["S" if 'comm' in kwargs.keys() else "MS", "status"]
self.add_variable(controller, name='restart', where=where, init=False)
self.add_variable(controller, name='restarts_in_a_row', where=where, init=0)
def reset_status_variables(self, controller, reset=False, **kwargs):
"""
Add status variables for whether to restart now and how many times the step has been restarted in a row to the
Steps
Args:
controller (pySDC.Controller): The controller
reset (bool): Whether the function is called for the first time or to reset
Returns:
None
"""
where = ["S" if 'comm' in kwargs.keys() else "MS", "status"]
self.reset_variable(controller, name='restart', where=where, init=False)
def dependencies(self, controller, description, **kwargs):
"""
Load a convergence controller that spreads the step sizes between steps.
Args:
controller (pySDC.Controller): The controller
description (dict): The description object used to instantiate the controller
Returns:
None
"""
controller.add_convergence_controller(self.params.step_size_spreader, description=description)
return None
def determine_restart(self, controller, S, **kwargs):
"""
Restart all steps after the first one which wants to be restarted as well, but also check if we lost patience
with the restarts and want to move on anyways.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
raise NotImplementedError("Please implement a function to determine if we need a restart here!")
def prepare_next_block(self, controller, S, size, time, Tend, **kwargs):
"""
Update restarts in a row for all steps.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
size (int): The number of ranks
time (list): List containing the time of all the steps
Tend (float): Final time of the simulation
Returns:
None
"""
S.status.restarts_in_a_row = S.status.restarts_in_a_row + 1 if S.status.restart else 0
return None
class BasicRestartingNonMPI(BasicRestarting):
"""
Non-MPI specific version of basic restarting
"""
def reset_buffers_nonMPI(self, controller, **kwargs):
"""
Reset all variables with are used to simulate communication here
Args:
controller (pySDC.Controller): The controller
Returns:
None
"""
self.buffers.restart = False
self.buffers.max_restart_reached = False
return None
def determine_restart(self, controller, S, **kwargs):
"""
Restart all steps after the first one which wants to be restarted as well, but also check if we lost patience
with the restarts and want to move on anyways.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
Returns:
None
"""
# check if we performed too many restarts
if S.status.first:
self.buffers.max_restart_reached = S.status.restarts_in_a_row >= self.params.max_restarts
if self.buffers.max_restart_reached and S.status.restart:
if self.params.crash_after_max_restarts:
raise ConvergenceError(f"Restarted {S.status.restarts_in_a_row} time(s) already, surrendering now.")
self.log(
f"Step(s) restarted {S.status.restarts_in_a_row} time(s) already, maximum reached, moving \
on...",
S,
)
self.buffers.restart = S.status.restart or self.buffers.restart
S.status.restart = (S.status.restart or self.buffers.restart) and not self.buffers.max_restart_reached
return None
class BasicRestartingMPI(BasicRestarting):
"""
MPI specific version of basic restarting
"""
def __init__(self, controller, params, description, **kwargs):
"""
Initialization routine. Adds a buffer.
Args:
controller (pySDC.Controller): The controller
params (dict): Parameters for the convergence controller
description (dict): The description object used to instantiate the controller
"""
super().__init__(controller, params, description)
self.buffers = Pars({"restart": False, "max_restart_reached": False, 'restart_earlier': False})
def determine_restart(self, controller, S, comm, **kwargs):
"""
Restart all steps after the first one which wants to be restarted as well, but also check if we lost patience
with the restarts and want to move on anyways.
Args:
controller (pySDC.Controller): The controller
S (pySDC.Step): The current step
comm (mpi4py.MPI.Intracomm): Communicator
Returns:
None
"""
assert S.status.slot == comm.rank
if S.status.first:
# check if we performed too many restarts
self.buffers.max_restart_reached = S.status.restarts_in_a_row >= self.params.max_restarts
self.buffers.restart_earlier = False # there is no earlier step
if self.buffers.max_restart_reached and S.status.restart:
if self.params.crash_after_max_restarts:
raise ConvergenceError(f"Restarted {S.status.restarts_in_a_row} time(s) already, surrendering now.")
self.log(
f"Step(s) restarted {S.status.restarts_in_a_row} time(s) already, maximum reached, moving \
on...",
S,
)
elif not S.status.prev_done:
# receive information about restarts from earlier ranks
self.buffers.restart_earlier, self.buffers.max_restart_reached = self.recv(comm, source=S.status.slot - 1)
# decide whether to restart
S.status.restart = (S.status.restart or self.buffers.restart_earlier) and not self.buffers.max_restart_reached
# send information about restarts forward
if not S.status.last:
self.send(comm, dest=S.status.slot + 1, data=(S.status.restart, self.buffers.max_restart_reached))
return None
| 9,993 | 36.856061 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/FermiPastaUlamTsingou.py | import numpy as np
from pySDC.core.Errors import ParameterError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.particles import particles, acceleration
# noinspection PyUnusedLocal
class fermi_pasta_ulam_tsingou(ptype):
"""
Example implementing the outer solar system problem
TODO : doku
"""
dtype_u = particles
dtype_f = acceleration
def __init__(self, npart, alpha, k, energy_modes):
"""Initialization routine"""
# invoke super init, passing nparts
super().__init__((npart, None, np.dtype('float64')))
self._makeAttributeAndRegister('npart', 'alpha', 'k', 'energy_modes', localVars=locals(), readOnly=True)
self.dx = (self.npart / 32) / (self.npart + 1)
self.xvalues = np.array([(i + 1) * self.dx for i in range(self.npart)])
self.ones = np.ones(self.npart - 2)
def eval_f(self, u, t):
"""
Routine to compute the RHS
Args:
u (dtype_u): the particles
t (float): current time (not used here)
Returns:
dtype_f: RHS
"""
me = self.dtype_f(self.init, val=0.0)
# me[1:-1] = u.pos[:-2] - 2.0 * u.pos[1:-1] + u.pos[2:] + \
# self.alpha * ((u.pos[2:] - u.pos[1:-1]) ** 2 -
# (u.pos[1:-1] - u.pos[:-2]) ** 2)
# me[0] = -2.0 * u.pos[0] + u.pos[1] + \
# self.alpha * ((u.pos[1] - u.pos[0]) ** 2 - (u.pos[0]) ** 2)
# me[-1] = u.pos[-2] - 2.0 * u.pos[-1] + \
# self.alpha * ((u.pos[-1]) ** 2 - (u.pos[-1] - u.pos[-2]) ** 2)
me[1:-1] = (u.pos[:-2] - 2.0 * u.pos[1:-1] + u.pos[2:]) * (self.ones + self.alpha * (u.pos[2:] - u.pos[:-2]))
me[0] = (-2.0 * u.pos[0] + u.pos[1]) * (1 + self.alpha * (u.pos[1]))
me[-1] = (u.pos[-2] - 2.0 * u.pos[-1]) * (1 + self.alpha * (-u.pos[-2]))
return me
def u_exact(self, t):
"""
Routine to compute the exact/initial trajectory at time t
Args:
t (float): current time
Returns:
dtype_u: exact/initial position and velocity
"""
assert t == 0.0, 'error, u_exact only works for the initial time t0=0'
me = self.dtype_u(self.init, val=0.0)
me.pos[:] = np.sin(self.k * np.pi * self.xvalues)
me.vel[:] = 0.0
return me
def eval_hamiltonian(self, u):
"""
Routine to compute the Hamiltonian
Args:
u (dtype_u): the particles
Returns:
float: hamiltonian
"""
ham = sum(
0.5 * u.vel[:-1] ** 2
+ 0.5 * (u.pos[1:] - u.pos[:-1]) ** 2
+ self.alpha / 3.0 * (u.pos[1:] - u.pos[:-1]) ** 3
)
ham += 0.5 * u.vel[-1] ** 2 + 0.5 * (u.pos[-1]) ** 2 + self.alpha / 3.0 * (-u.pos[-1]) ** 3
ham += 0.5 * (u.pos[0]) ** 2 + self.alpha / 3.0 * (u.pos[0]) ** 3
return ham
def eval_mode_energy(self, u):
"""
Routine to compute the energy following
http://www.scholarpedia.org/article/Fermi-Pasta-Ulam_nonlinear_lattice_oscillations
Args:
u (dtype_u): the particles
Returns:
dict: energies
"""
energy = {}
for k in self.energy_modes:
# Qk = np.sqrt(2.0 / (self.npart + 1)) * np.dot(u.pos, np.sin(np.pi * k * self.xvalues))
Qk = np.sqrt(2.0 * self.dx) * np.dot(u.pos, np.sin(np.pi * k * self.xvalues))
# Qkdot = np.sqrt(2.0 / (self.npart + 1)) * np.dot(u.vel, np.sin(np.pi * k * self.xvalues))
Qkdot = np.sqrt(2.0 * self.dx) * np.dot(u.vel, np.sin(np.pi * k * self.xvalues))
# omegak2 = 4.0 * np.sin(k * np.pi / (2.0 * (self.npart + 1))) ** 2
omegak2 = 4.0 * np.sin(k * np.pi * self.dx / 2.0) ** 2
energy[k] = 0.5 * (Qkdot**2 + omegak2 * Qk**2)
return energy
| 3,934 | 33.217391 | 117 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/GrayScott_MPIFFT.py | import numpy as np
import scipy.sparse as sp
from mpi4py import MPI
from mpi4py_fft import PFFT
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh, comp2_mesh
from mpi4py_fft import newDistArray
class grayscott_imex_diffusion(ptype):
"""
Example implementing the Gray-Scott equation in 2-3D using mpi4py-fft for solving linear parts,
IMEX time-stepping (implicit diffusion, explicit reaction)
mpi4py-fft: https://mpi4py-fft.readthedocs.io/en/latest/
Attributes:
fft: fft object
X: grid coordinates in real space
ndim: number of spatial dimensions
Ku: Laplace operator in spectral space (u component)
Kv: Laplace operator in spectral space (v component)
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, nvars, Du, Dv, A, B, spectral, L=2.0, comm=MPI.COMM_WORLD):
if not (isinstance(nvars, tuple) and len(nvars) > 1):
raise ProblemError('Need at least two dimensions')
# Creating FFT structure
self.ndim = len(nvars)
axes = tuple(range(self.ndim))
self.fft = PFFT(
comm,
list(nvars),
axes=axes,
dtype=np.float64,
collapse=True,
backend='fftw',
)
# get test data to figure out type and dimensions
tmp_u = newDistArray(self.fft, spectral)
# add two components to contain field and temperature
self.ncomp = 2
sizes = tmp_u.shape + (self.ncomp,)
# invoke super init, passing the communicator and the local dimensions as init
super().__init__(init=(sizes, comm, tmp_u.dtype))
self._makeAttributeAndRegister(
'nvars', 'Du', 'Dv', 'A', 'B', 'spectral', 'L', 'comm', localVars=locals(), readOnly=True
)
L = np.array([self.L] * self.ndim, dtype=float)
# get local mesh
X = np.ogrid[self.fft.local_slice(False)]
N = self.fft.global_shape()
for i in range(len(N)):
X[i] = -L[i] / 2 + (X[i] * L[i] / N[i])
self.X = [np.broadcast_to(x, self.fft.shape(False)) for x in X]
# get local wavenumbers and Laplace operator
s = self.fft.local_slice()
N = self.fft.global_shape()
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(self.ndim):
Ks[i] = (Ks[i] * Lp[i]).astype(float)
K = [np.broadcast_to(k, self.fft.shape(True)) for k in Ks]
K = np.array(K).astype(float)
self.K2 = np.sum(K * K, 0, dtype=float)
self.Ku = -self.K2 * self.Du
self.Kv = -self.K2 * self.Dv
# Need this for diagnostics
self.dx = self.L / nvars[0]
self.dy = self.L / nvars[1]
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)
if self.spectral:
f.impl[..., 0] = self.Ku * u[..., 0]
f.impl[..., 1] = self.Kv * u[..., 1]
tmpu = newDistArray(self.fft, False)
tmpv = newDistArray(self.fft, False)
tmpu[:] = self.fft.backward(u[..., 0], tmpu)
tmpv[:] = self.fft.backward(u[..., 1], tmpv)
tmpfu = -tmpu * tmpv**2 + self.A * (1 - tmpu)
tmpfv = tmpu * tmpv**2 - self.B * tmpv
f.expl[..., 0] = self.fft.forward(tmpfu)
f.expl[..., 1] = self.fft.forward(tmpfv)
else:
u_hat = self.fft.forward(u[..., 0])
lap_u_hat = self.Ku * u_hat
f.impl[..., 0] = self.fft.backward(lap_u_hat, f.impl[..., 0])
u_hat = self.fft.forward(u[..., 1])
lap_u_hat = self.Kv * u_hat
f.impl[..., 1] = self.fft.backward(lap_u_hat, f.impl[..., 1])
f.expl[..., 0] = -u[..., 0] * u[..., 1] ** 2 + self.A * (1 - u[..., 0])
f.expl[..., 1] = u[..., 0] * u[..., 1] ** 2 - self.B * u[..., 1]
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)
if self.spectral:
me[..., 0] = rhs[..., 0] / (1.0 - factor * self.Ku)
me[..., 1] = rhs[..., 1] / (1.0 - factor * self.Kv)
else:
rhs_hat = self.fft.forward(rhs[..., 0])
rhs_hat /= 1.0 - factor * self.Ku
me[..., 0] = self.fft.backward(rhs_hat, me[..., 0])
rhs_hat = self.fft.forward(rhs[..., 1])
rhs_hat /= 1.0 - factor * self.Kv
me[..., 1] = self.fft.backward(rhs_hat, me[..., 1])
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t=0, see https://www.chebfun.org/examples/pde/GrayScott.html
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
assert t == 0.0, 'Exact solution only valid as initial condition'
assert self.ndim == 2, 'The initial conditions are 2D for now..'
me = self.dtype_u(self.init, val=0.0)
# This assumes that the box is [-L/2, L/2]^2
if self.spectral:
tmp = 1.0 - np.exp(-80.0 * ((self.X[0] + 0.05) ** 2 + (self.X[1] + 0.02) ** 2))
me[..., 0] = self.fft.forward(tmp)
tmp = np.exp(-80.0 * ((self.X[0] - 0.05) ** 2 + (self.X[1] - 0.02) ** 2))
me[..., 1] = self.fft.forward(tmp)
else:
me[..., 0] = 1.0 - np.exp(-80.0 * ((self.X[0] + 0.05) ** 2 + (self.X[1] + 0.02) ** 2))
me[..., 1] = np.exp(-80.0 * ((self.X[0] - 0.05) ** 2 + (self.X[1] - 0.02) ** 2))
# tmpu = np.load('data/u_0001.npy')
# tmpv = np.load('data/v_0001.npy')
#
# me[..., 0] = self.fft.forward(tmpu)
# me[..., 1] = self.fft.forward(tmpv)
return me
class grayscott_imex_linear(grayscott_imex_diffusion):
def __init__(self, nvars, Du, Dv, A, B, spectral, L=2.0, comm=MPI.COMM_WORLD):
super().__init__(nvars, Du, Dv, A, B, spectral, L, comm)
self.Ku -= self.A
self.Kv -= self.B
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)
if self.spectral:
f.impl[..., 0] = self.Ku * u[..., 0]
f.impl[..., 1] = self.Kv * u[..., 1]
tmpu = newDistArray(self.fft, False)
tmpv = newDistArray(self.fft, False)
tmpu[:] = self.fft.backward(u[..., 0], tmpu)
tmpv[:] = self.fft.backward(u[..., 1], tmpv)
tmpfu = -tmpu * tmpv**2 + self.A
tmpfv = tmpu * tmpv**2
f.expl[..., 0] = self.fft.forward(tmpfu)
f.expl[..., 1] = self.fft.forward(tmpfv)
else:
u_hat = self.fft.forward(u[..., 0])
lap_u_hat = self.Ku * u_hat
f.impl[..., 0] = self.fft.backward(lap_u_hat, f.impl[..., 0])
u_hat = self.fft.forward(u[..., 1])
lap_u_hat = self.Kv * u_hat
f.impl[..., 1] = self.fft.backward(lap_u_hat, f.impl[..., 1])
f.expl[..., 0] = -u[..., 0] * u[..., 1] ** 2 + self.A
f.expl[..., 1] = u[..., 0] * u[..., 1] ** 2
return f
class grayscott_mi_diffusion(grayscott_imex_diffusion):
dtype_f = comp2_mesh
def __init__(self, nvars, Du, Dv, A, B, spectral, newton_maxiter, newton_tol, L=2.0, comm=MPI.COMM_WORLD):
super().__init__(nvars, Du, Dv, A, B, spectral, L, comm)
# This may not run in parallel yet..
assert self.comm.Get_size() == 1
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)
if self.spectral:
f.comp1[..., 0] = self.Ku * u[..., 0]
f.comp1[..., 1] = self.Kv * u[..., 1]
tmpu = newDistArray(self.fft, False)
tmpv = newDistArray(self.fft, False)
tmpu[:] = self.fft.backward(u[..., 0], tmpu)
tmpv[:] = self.fft.backward(u[..., 1], tmpv)
tmpfu = -tmpu * tmpv**2 + self.A * (1 - tmpu)
tmpfv = tmpu * tmpv**2 - self.B * tmpv
f.comp2[..., 0] = self.fft.forward(tmpfu)
f.comp2[..., 1] = self.fft.forward(tmpfv)
else:
u_hat = self.fft.forward(u[..., 0])
lap_u_hat = self.Ku * u_hat
f.comp1[..., 0] = self.fft.backward(lap_u_hat, f.comp1[..., 0])
u_hat = self.fft.forward(u[..., 1])
lap_u_hat = self.Kv * u_hat
f.comp1[..., 1] = self.fft.backward(lap_u_hat, f.comp1[..., 1])
f.comp2[..., 0] = -u[..., 0] * u[..., 1] ** 2 + self.A * (1 - u[..., 0])
f.comp2[..., 1] = u[..., 0] * u[..., 1] ** 2 - self.B * u[..., 1]
return f
def solve_system_1(self, rhs, factor, u0, t):
"""
Solver for the first component, can just call the super function
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 = super(grayscott_mi_diffusion, self).solve_system(rhs, factor, u0, t)
return me
def solve_system_2(self, rhs, factor, u0, t):
"""
Newton-Solver for the second component
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
"""
u = self.dtype_u(u0)
if self.spectral:
tmpu = newDistArray(self.fft, False)
tmpv = newDistArray(self.fft, False)
tmpu[:] = self.fft.backward(u[..., 0], tmpu)
tmpv[:] = self.fft.backward(u[..., 1], tmpv)
tmprhsu = newDistArray(self.fft, False)
tmprhsv = newDistArray(self.fft, False)
tmprhsu[:] = self.fft.backward(rhs[..., 0], tmprhsu)
tmprhsv[:] = self.fft.backward(rhs[..., 1], tmprhsv)
else:
tmpu = u[..., 0]
tmpv = u[..., 1]
tmprhsu = rhs[..., 0]
tmprhsv = rhs[..., 1]
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# print(n, res)
# form the function g with g(u) = 0
tmpgu = tmpu - tmprhsu - factor * (-tmpu * tmpv**2 + self.A * (1 - tmpu))
tmpgv = tmpv - tmprhsv - factor * (tmpu * tmpv**2 - self.B * tmpv)
# if g is close to 0, then we are done
res = max(np.linalg.norm(tmpgu, np.inf), np.linalg.norm(tmpgv, np.inf))
if res < self.newton_tol:
break
# assemble dg
dg00 = 1 - factor * (-(tmpv**2) - self.A)
dg01 = -factor * (-2 * tmpu * tmpv)
dg10 = -factor * (tmpv**2)
dg11 = 1 - factor * (2 * tmpu * tmpv - self.B)
# interleave and unravel to put into sparse matrix
dg00I = np.ravel(np.kron(dg00, np.array([1, 0])))
dg01I = np.ravel(np.kron(dg01, np.array([1, 0])))
dg10I = np.ravel(np.kron(dg10, np.array([1, 0])))
dg11I = np.ravel(np.kron(dg11, np.array([0, 1])))
# put into sparse matrix
dg = sp.diags(dg00I, offsets=0) + sp.diags(dg11I, offsets=0)
dg += sp.diags(dg01I, offsets=1, shape=dg.shape) + sp.diags(dg10I, offsets=-1, shape=dg.shape)
# interleave g terms to apply inverse to it
g = np.kron(tmpgu.flatten(), np.array([1, 0])) + np.kron(tmpgv.flatten(), np.array([0, 1]))
# invert dg matrix
b = sp.linalg.spsolve(dg, g)
# update real space vectors
tmpu[:] -= b[::2].reshape(self.nvars)
tmpv[:] -= b[1::2].reshape(self.nvars)
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
self.logger.warning('Newton did not converge after %i iterations, error is %s' % (n, res))
# self.newton_ncalls += 1
# self.newton_itercount += n
me = self.dtype_u(self.init)
if self.spectral:
me[..., 0] = self.fft.forward(tmpu)
me[..., 1] = self.fft.forward(tmpv)
else:
me[..., 0] = tmpu
me[..., 1] = tmpv
return me
class grayscott_mi_linear(grayscott_imex_linear):
dtype_f = comp2_mesh
def __init__(self, nvars, Du, Dv, A, B, spectral, newton_maxiter, newton_tol, L=2.0, comm=MPI.COMM_WORLD):
super().__init__(nvars, Du, Dv, A, B, spectral, L, comm)
# This may not run in parallel yet..
assert self.comm.Get_size() == 1
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)
if self.spectral:
f.comp1[..., 0] = self.Ku * u[..., 0]
f.comp1[..., 1] = self.Kv * u[..., 1]
tmpu = newDistArray(self.fft, False)
tmpv = newDistArray(self.fft, False)
tmpu[:] = self.fft.backward(u[..., 0], tmpu)
tmpv[:] = self.fft.backward(u[..., 1], tmpv)
tmpfu = -tmpu * tmpv**2 + self.A
tmpfv = tmpu * tmpv**2
f.comp2[..., 0] = self.fft.forward(tmpfu)
f.comp2[..., 1] = self.fft.forward(tmpfv)
else:
u_hat = self.fft.forward(u[..., 0])
lap_u_hat = self.Ku * u_hat
f.comp1[..., 0] = self.fft.backward(lap_u_hat, f.comp1[..., 0])
u_hat = self.fft.forward(u[..., 1])
lap_u_hat = self.Kv * u_hat
f.comp1[..., 1] = self.fft.backward(lap_u_hat, f.comp1[..., 1])
f.comp2[..., 0] = -u[..., 0] * u[..., 1] ** 2 + self.A
f.comp2[..., 1] = u[..., 0] * u[..., 1] ** 2
return f
def solve_system_1(self, rhs, factor, u0, t):
"""
Solver for the first component, can just call the super function
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 = super(grayscott_mi_linear, self).solve_system(rhs, factor, u0, t)
return me
def solve_system_2(self, rhs, factor, u0, t):
"""
Newton-Solver for the second component
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
"""
u = self.dtype_u(u0)
if self.spectral:
tmpu = newDistArray(self.fft, False)
tmpv = newDistArray(self.fft, False)
tmpu[:] = self.fft.backward(u[..., 0], tmpu)
tmpv[:] = self.fft.backward(u[..., 1], tmpv)
tmprhsu = newDistArray(self.fft, False)
tmprhsv = newDistArray(self.fft, False)
tmprhsu[:] = self.fft.backward(rhs[..., 0], tmprhsu)
tmprhsv[:] = self.fft.backward(rhs[..., 1], tmprhsv)
else:
tmpu = u[..., 0]
tmpv = u[..., 1]
tmprhsu = rhs[..., 0]
tmprhsv = rhs[..., 1]
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# print(n, res)
# form the function g with g(u) = 0
tmpgu = tmpu - tmprhsu - factor * (-tmpu * tmpv**2 + self.A)
tmpgv = tmpv - tmprhsv - factor * (tmpu * tmpv**2)
# if g is close to 0, then we are done
res = max(np.linalg.norm(tmpgu, np.inf), np.linalg.norm(tmpgv, np.inf))
if res < self.newton_tol:
break
# assemble dg
dg00 = 1 - factor * (-(tmpv**2))
dg01 = -factor * (-2 * tmpu * tmpv)
dg10 = -factor * (tmpv**2)
dg11 = 1 - factor * (2 * tmpu * tmpv)
# interleave and unravel to put into sparse matrix
dg00I = np.ravel(np.kron(dg00, np.array([1, 0])))
dg01I = np.ravel(np.kron(dg01, np.array([1, 0])))
dg10I = np.ravel(np.kron(dg10, np.array([1, 0])))
dg11I = np.ravel(np.kron(dg11, np.array([0, 1])))
# put into sparse matrix
dg = sp.diags(dg00I, offsets=0) + sp.diags(dg11I, offsets=0)
dg += sp.diags(dg01I, offsets=1, shape=dg.shape) + sp.diags(dg10I, offsets=-1, shape=dg.shape)
# interleave g terms to apply inverse to it
g = np.kron(tmpgu.flatten(), np.array([1, 0])) + np.kron(tmpgv.flatten(), np.array([0, 1]))
# invert dg matrix
b = sp.linalg.spsolve(dg, g)
# update real-space vectors
tmpu[:] -= b[::2].reshape(self.nvars)
tmpv[:] -= b[1::2].reshape(self.nvars)
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
self.logger.warning('Newton did not converge after %i iterations, error is %s' % (n, res))
# self.newton_ncalls += 1
# self.newton_itercount += n
me = self.dtype_u(self.init)
if self.spectral:
me[..., 0] = self.fft.forward(tmpu)
me[..., 1] = self.fft.forward(tmpv)
else:
me[..., 0] = tmpu
me[..., 1] = tmpv
return me
| 19,896 | 35.642726 | 114 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AllenCahn_2D_FFT.py | import numpy as np
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
# noinspection PyUnusedLocal
class allencahn2d_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
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, nvars, nu, eps, radius, L=1.0, init_type='circle'):
"""
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)
"""
# we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on
if len(nvars) != 2:
raise ProblemError('this is a 2d example, got %s' % nvars)
if nvars[0] != nvars[1]:
raise ProblemError('need a square domain, got %s' % nvars)
if 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().__init__(init=(nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'nvars', 'nu', 'eps', 'radius', 'L', 'init_type', localVars=locals(), readOnly=True
)
self.dx = self.L / self.nvars[0] # could be useful for hooks, too.
self.xvalues = np.array([i * self.dx - self.L / 2.0 for i in range(self.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.L * np.arange(0, int(self.init[0][0] / 2) + 1)
kx[int(self.init[0][0] / 2) + 1 :] = (
2 * np.pi / self.L * np.arange(int(self.init[0][0] / 2) + 1 - self.init[0][0], 0)
)
ky[:] = 2 * np.pi / self.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.lap * np.fft.rfft2(u)
f.impl[:] = np.fft.irfft2(tmp)
if self.eps > 0:
f.expl[:] = (1.0 / self.eps**2 * v * (1.0 - v**self.nu)).reshape(self.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.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.init_type == 'circle':
xv, yv = np.meshgrid(self.xvalues, self.xvalues, indexing='ij')
me[:, :] = np.tanh((self.radius - np.sqrt(xv**2 + yv**2)) / (np.sqrt(2) * self.eps))
elif self.init_type == 'checkerboard':
xv, yv = np.meshgrid(self.xvalues, self.xvalues)
me[:, :] = np.sin(2.0 * np.pi * xv) * np.sin(2.0 * np.pi * yv)
elif self.init_type == 'random':
me[:, :] = np.random.uniform(-1, 1, self.init)
else:
raise NotImplementedError('type of initial value not implemented, got %s' % self.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
class allencahn2d_imex_stab(allencahn2d_imex):
"""
Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping with
stabilized splitting
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, nvars, nu, eps, radius, L=1.0, init_type='circle'):
super().__init__(nvars, nu, eps, radius, L, init_type)
self.lap -= 2.0 / self.eps**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.lap * np.fft.rfft2(u)
f.impl[:] = np.fft.irfft2(tmp)
if self.eps > 0:
f.expl[:] = (1.0 / self.eps**2 * v * (1.0 - v**self.nu) + 2.0 / self.eps**2 * v).reshape(self.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.lap)
me[:] = np.fft.irfft2(tmp)
return me
| 6,822 | 33.459596 | 134 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/Battery.py | import numpy as np
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
class battery_n_capacitors(ptype):
r"""
Example implementing the battery drain model with :math:`N` capacitors, where :math:`N` is an arbitrary integer greater than zero.
First, the capacitor :math:`C` serves as a battery and provides energy. When the voltage of the capacitor :math:`u_{C_n}` for
:math:`n=1,..,N` drops below their reference value :math:`V_{ref,n-1}`, the circuit switches to the next capacitor. If all capacitors
has dropped below their reference value, the voltage source :math:`V_s` provides further energy. The problem of simulating the
battery draining has :math:`N + 1` different states. Each of this state can be expressed as a nonhomogeneous linear system of
ordinary differential equations (ODEs)
.. math::
\frac{d u(t)}{dt} = A_k u(t) + f_k (t)
for :math:`k=1,..,N+1` using an initial condition.
Parameters
----------
ncapacitors : int
Number of capacitors :math:`n_{capacitors}` in the circuit.
Vs : float
Voltage at the voltage source :math:`V_s`.
Rs : float
Resistance of the resistor :math:`R_s` at the voltage source.
C : np.ndarray
Capacitances of the capacitors.
R : float
Resistance for the load.
L : float
Inductance of inductor.
alpha : float
Factor greater than zero to describe the storage of the capacitor(s).
V_ref : np.ndarray
Array contains the reference values greater than zero for each capacitor to switch to the next energy source.
Attributes
----------
A: matrix
Coefficients matrix of the linear system of ordinary differential equations (ODEs).
switch_A: dict
Dictionary that contains the coefficients for the coefficient matrix A.
switch_f: dict
Dictionary that contains the coefficients of the right-hand side f of the ODE system.
t_switch: float
Time point of the discrete event found by switch estimation.
nswitches: int
Number of switches found by switch estimation.
Note
----
The array containing the capacitances :math:`C_n` and the array containing the reference values :math:`V_{ref, n-1}`
for each capacitor must be equal to the number of capacitors :math:`n_{capacitors}`.
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, ncapacitors=2, Vs=5.0, Rs=0.5, C=None, R=1.0, L=1.0, alpha=1.2, V_ref=None):
"""Initialization routine"""
n = ncapacitors
nvars = n + 1
if C is None:
C = np.array([1.0, 1.0])
if V_ref is None:
V_ref = np.array([1.0, 1.0])
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__(init=(nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'nvars', 'ncapacitors', 'Vs', 'Rs', 'C', 'R', 'L', 'alpha', 'V_ref', localVars=locals(), readOnly=True
)
self.A = np.zeros((n + 1, n + 1))
self.switch_A, self.switch_f = self.get_problem_dict()
self.t_switch = None
self.nswitches = 0
def eval_f(self, u, t):
r"""
Routine to evaluate the right-hand side of the problem. Let :math:`v_k:=v_{C_k}` be the voltage of capacitor :math:`C_k` for :math:`k=1,..,N`
with reference value :math:`V_{ref, k-1}`. No switch estimator is used: For :math:`N = 3` there are :math:`N + 1 = 4` different states of the battery:
:math:`C_1` supplies energy if:
.. math::
v_1 > V_{ref,0}, v_2 > V_{ref,1}, v_3 > V_{ref,2},
:math:`C_2` supplies energy if:
.. math::
v_1 \leq V_{ref,0}, v_2 > V_{ref,1}, v_3 > V_{ref,2},
:math:`C_3` supplies energy if:
.. math::
v_1 \leq V_{ref,0}, v_2 \leq V_{ref,1}, v_3 > V_{ref,2},
:math:`V_s` supplies energy if:
.. math::
v_1 \leq V_{ref,0}, v_2 \leq V_{ref,1}, v_3 \leq V_{ref,2}.
:math:`max_{index}` is initialized to :math:`-1`. List "switch" contains a True if :math:`u_k \leq V_{ref,k-1}` is satisfied.
- Is no True there (i.e., :math:`max_{index}=-1`), we are in the first case.
- :math:`max_{index}=k\geq 0` means we are in the :math:`(k+1)`-th case.
So, the actual RHS has key :math:`max_{index}`-1 in the dictionary self.switch_f.
In case of using the switch estimator, we count the number of switches which illustrates in which case of voltage source we are.
Parameters
----------
u : dtype_u
Current values of the numerical solution.
t : float
Current time of the numerical solution is computed.
Returns
-------
f : dtype_f
The right-hand side of the problem.
"""
f = self.dtype_f(self.init, val=0.0)
f.impl[:] = self.A.dot(u)
if self.t_switch is not None:
f.expl[:] = self.switch_f[self.nswitches]
else:
# proof all switching conditions and find largest index where it drops below V_ref
switch = [True if u[k] <= self.V_ref[k - 1] else False for k in range(1, len(u))]
max_index = max([k if switch[k] == True else -1 for k in range(len(switch))])
if max_index == -1:
f.expl[:] = self.switch_f[0]
else:
f.expl[:] = self.switch_f[max_index + 1]
return f
def solve_system(self, rhs, factor, u0, t):
r"""
Simple linear solver for :math:`(I-factor\cdot A)\vec{u}=\vec{rhs}`.
Parameters
----------
rhs : dtype_f
Right-hand side for the linear system.
factor : float
Abbrev. for the local stepsize (or any other factor required).
u0 : dtype_u
Initial guess for the iterative solver.
t : float
Current time (e.g. for time-dependent BCs).
Returns
-------
me : dtype_u
The solution as mesh.
"""
if self.t_switch is not None:
self.A = self.switch_A[self.nswitches]
else:
# proof all switching conditions and find largest index where it drops below V_ref
switch = [True if rhs[k] <= self.V_ref[k - 1] else False for k in range(1, len(rhs))]
max_index = max([k if switch[k] == True else -1 for k in range(len(switch))])
if max_index == -1:
self.A = self.switch_A[0]
else:
self.A = self.switch_A[max_index + 1]
me = self.dtype_u(self.init)
me[:] = np.linalg.solve(np.eye(self.nvars) - factor * self.A, rhs)
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t.
Parameters
----------
t : float
Time of the exact solution.
Returns
-------
me : dtype_u
The exact solution.
"""
assert t == 0, 'ERROR: u_exact only valid for t=0'
me = self.dtype_u(self.init)
me[0] = 0.0 # cL
me[1:] = self.alpha * self.V_ref # vC's
return me
def get_switching_info(self, u, t):
"""
Provides information about a discrete event for one subinterval.
Parameters
----------
u : dtype_u
Current values of the numerical solution.
t : float
Current time of the numerical solution is computed.
Returns
-------
switch_detected : bool
Indicates if a switch is found or not.
m_guess : int
Index of collocation node inside one subinterval of where the discrete event was found.
vC_switch : list
Contains function values of switching condition (for interpolation).
"""
switch_detected = False
m_guess = -100
break_flag = False
for m in range(1, len(u)):
for k in range(1, self.nvars):
if u[m][k] - self.V_ref[k - 1] <= 0:
switch_detected = True
m_guess = m - 1
k_detected = k
break_flag = True
break
if break_flag:
break
vC_switch = [u[m][k_detected] - self.V_ref[k_detected - 1] for m in range(1, len(u))] if switch_detected else []
return switch_detected, m_guess, vC_switch
def count_switches(self):
"""
Counts the number of switches. This function is called when a switch is found inside the range of tolerance
(in pySDC/projects/PinTSimE/switch_estimator.py)
"""
self.nswitches += 1
def get_problem_dict(self):
"""
Helper to create dictionaries for both the coefficent matrix of the ODE system and the nonhomogeneous part.
"""
n = self.ncapacitors
v = np.zeros(n + 1)
v[0] = 1
A, f = dict(), dict()
A = {k: np.diag(-1 / (self.C[k] * self.R) * np.roll(v, k + 1)) for k in range(n)}
A.update({n: np.diag(-(self.Rs + self.R) / self.L * v)})
f = {k: np.zeros(n + 1) for k in range(n)}
f.update({n: self.Vs / self.L * v})
return A, f
class battery(battery_n_capacitors):
r"""
Example implementing the battery drain model with :math:`N=1` capacitor, inherits from battery_n_capacitors. The ODE system
of this model is given by the following equations. If :math:`v_1 > V_{ref, 0}:`
.. math::
\frac{d i_L (t)}{dt} = 0,
.. math::
\frac{d v_1 (t)}{dt} = -\frac{1}{CR}v_1 (t),
where :math:`i_L` denotes the function of the current over time :math:`t`.
If :math:`v_1 \leq V_{ref, 0}:`
.. math::
\frac{d i_L(t)}{dt} = -\frac{R_s + R}{L}i_L (t) + \frac{1}{L} V_s,
.. math::
\frac{d v_1(t)}{dt} = 0.
Note
----
This class has the same attributes as the class it inherits from.
"""
dtype_f = imex_mesh
def eval_f(self, u, t):
"""
Routine to evaluate the right-hand side of the problem.
Parameters
----------
u : dtype_u
Current values of the numerical solution.
t : float
Current time of the numerical solution is computed.
Returns
-------
f : dtype_f
The right-hand side of the problem.
"""
f = self.dtype_f(self.init, val=0.0)
f.impl[:] = self.A.dot(u)
t_switch = np.inf if self.t_switch is None else self.t_switch
if u[1] <= self.V_ref[0] or t >= t_switch:
f.expl[0] = self.Vs / self.L
else:
f.expl[0] = 0
return f
def solve_system(self, rhs, factor, u0, t):
r"""
Simple linear solver for :math:`(I-factor\cdot A)\vec{u}=\vec{rhs}`.
Parameters
----------
rhs : dtype_f
Right-hand side for the linear system.
factor : float
Abbrev. for the local stepsize (or any other factor required).
u0 : dtype_u
Initial guess for the iterative solver.
t : float
Current time (e.g. for time-dependent BCs).
Returns
-------
me : dtype_u
The solution as mesh.
"""
self.A = np.zeros((2, 2))
t_switch = np.inf if self.t_switch is None else self.t_switch
if rhs[1] <= self.V_ref[0] or t >= t_switch:
self.A[0, 0] = -(self.Rs + self.R) / self.L
else:
self.A[1, 1] = -1 / (self.C[0] * self.R)
me = self.dtype_u(self.init)
me[:] = np.linalg.solve(np.eye(self.nvars) - factor * self.A, rhs)
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t.
Parameters
----------
t : float
Time of the exact solution.
Returns
-------
me : dtype_u
The exact solution.
"""
assert t == 0, 'ERROR: u_exact only valid for t=0'
me = self.dtype_u(self.init)
me[0] = 0.0 # cL
me[1] = self.alpha * self.V_ref[0] # vC
return me
class battery_implicit(battery):
r"""
Example implementing the battery drain model as above. The method solve_system uses a fully-implicit computation.
Parameters
----------
ncapacitors : int
Number of capacitors in the circuit.
Vs : float
Voltage at the voltage source :math:`V_s`.
Rs : float
Resistance of the resistor :math:`R_s` at the voltage source.
C : np.ndarray
Capacitances of the capacitors. Length of array must equal to number of capacitors.
R : float
Resistance for the load.
L : float
Inductance of inductor.
alpha : float
Factor greater than zero to describe the storage of the capacitor(s).
V_ref : float
Reference value greater than zero for the battery to switch to the voltage source.
newton_maxiter : int
Number of maximum iterations for the Newton solver.
newton_tol : float
Tolerance for determination of the Newton solver.
Attributes
----------
newton_itercount: int
Counts the number of Newton iterations.
newton_ncalls: int
Counts the number of how often Newton is called in the simulation of the problem.
"""
dtype_f = mesh
def __init__(
self,
ncapacitors=1,
Vs=5.0,
Rs=0.5,
C=None,
R=1.0,
L=1.0,
alpha=1.2,
V_ref=None,
newton_maxiter=200,
newton_tol=1e-8,
):
if C is None:
C = np.array([1.0])
if V_ref is None:
V_ref = np.array([1.0])
super().__init__(ncapacitors, Vs, Rs, C, R, L, alpha, V_ref)
self._makeAttributeAndRegister('newton_maxiter', 'newton_tol', localVars=locals(), readOnly=True)
self.newton_itercount = 0
self.newton_ncalls = 0
def eval_f(self, u, t):
"""
Routine to evaluate the right-hand side of the problem.
Parameters
----------
u : dtype_u
Current values of the numerical solution.
t : float
Current time of the numerical solution is computed.
Returns
-------
f : dtype_f
The right-hand side of the problem.
"""
f = self.dtype_f(self.init, val=0.0)
non_f = np.zeros(2)
t_switch = np.inf if self.t_switch is None else self.t_switch
if u[1] <= self.V_ref[0] or t >= t_switch:
self.A[0, 0] = -(self.Rs + self.R) / self.L
non_f[0] = self.Vs
else:
self.A[1, 1] = -1 / (self.C[0] * self.R)
non_f[0] = 0
f[:] = self.A.dot(u) + non_f
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver.
Parameters
----------
rhs : dtype_f
Right-hand side for the linear system.
factor : float
Abbrev. for the local stepsize (or any other factor required).
u0 : dtype_u
Initial guess for the iterative solver
t : float
Current time (e.g. for time-dependent BCs).
Returns
-------
me : dtype_u
The solution as mesh.
"""
u = self.dtype_u(u0)
non_f = np.zeros(2)
self.A = np.zeros((2, 2))
t_switch = np.inf if self.t_switch is None else self.t_switch
if rhs[1] <= self.V_ref[0] or t >= t_switch:
self.A[0, 0] = -(self.Rs + self.R) / self.L
non_f[0] = self.Vs
else:
self.A[1, 1] = -1 / (self.C[0] * self.R)
non_f[0] = 0
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form function g with g(u) = 0
g = u - rhs - factor * (self.A.dot(u) + non_f)
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = np.eye(self.nvars) - factor * self.A
# newton update: u1 = u0 - g/dg
u -= np.linalg.solve(dg, g)
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
self.logger.warning('Newton did not converge after %i iterations, error is %s' % (n, res))
self.newton_ncalls += 1
self.newton_itercount += n
me = self.dtype_u(self.init)
me[:] = u[:]
return me
| 17,158 | 29.917117 | 158 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/FastWaveSlowWave_0D.py | import numpy as np
from pySDC.core.Errors import ParameterError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
# noinspection PyUnusedLocal
class swfw_scalar(ptype):
"""
Example implementing fast-wave-slow-wave scalar problem
Attributes:
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, lambda_s=-1, lambda_f=-1000, u0=1):
"""
Initialization routine
"""
init = ([lambda_s.size, lambda_f.size], None, np.dtype('complex128'))
super().__init__(init)
self._makeAttributeAndRegister('lambda_s', 'lambda_f', 'u0', localVars=locals(), readOnly=True)
def solve_system(self, rhs, factor, u0, t):
"""
Simple im=nversion of (1-dt*lambda)u = rhs
Args:
rhs (dtype_f): right-hand side for the nonlinear 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)
for i in range(self.lambda_s.size):
for j in range(self.lambda_f.size):
me[i, j] = rhs[i, j] / (1.0 - factor * self.lambda_f[j])
return me
def __eval_fexpl(self, u, t):
"""
Helper routine to evaluate the explicit part of the RHS
Args:
u (dtype_u): current values
t (float): current time (not used here)
Returns:
explicit part of RHS
"""
fexpl = self.dtype_u(self.init)
for i in range(self.lambda_s.size):
for j in range(self.lambda_f.size):
fexpl[i, j] = self.lambda_s[i] * u[i, j]
return fexpl
def __eval_fimpl(self, u, t):
"""
Helper routine to evaluate the implicit part of the RHS
Args:
u (dtype_u): current values
t (float): current time (not used here)
Returns:
implicit part of RHS
"""
fimpl = self.dtype_u(self.init)
for i in range(self.lambda_s.size):
for j in range(self.lambda_f.size):
fimpl[i, j] = self.lambda_f[j] * u[i, j]
return fimpl
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS divided into two parts
"""
f = self.dtype_f(self.init)
f.impl = self.__eval_fimpl(u, t)
f.expl = self.__eval_fexpl(u, t)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
me = self.dtype_u(self.init)
for i in range(self.lambda_s.size):
for j in range(self.lambda_f.size):
me[i, j] = self.u0 * np.exp((self.lambda_f[j] + self.lambda_s[i]) * t)
return me
| 3,264 | 26.669492 | 103 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/HarmonicOscillator.py | import numpy as np
from pySDC.core.Errors import ParameterError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.particles import particles, acceleration
# noinspection PyUnusedLocal
class harmonic_oscillator(ptype):
"""
Example implementing the harmonic oscillator
"""
dtype_u = particles
dtype_f = acceleration
def __init__(self, k, mu=0.0, u0=(1, 0), phase=1.0, amp=0.0):
"""Initialization routine"""
# invoke super init, passing nparts, dtype_u and dtype_f
u0 = np.asarray(u0)
super().__init__((1, None, np.dtype("float64")))
self._makeAttributeAndRegister('k', 'mu', 'u0', 'phase', 'amp', localVars=locals(), readOnly=True)
def eval_f(self, u, t):
"""
Routine to compute the RHS
Args:
u (dtype_u): the particles
t (float): current time (not used here)
Returns:
dtype_f: RHS
"""
me = self.dtype_f(self.init)
me[:] = -self.k * u.pos - self.mu * u.vel
return me
def u_init(self):
u0 = self.u0
u = self.dtype_u(self.init)
u.pos[0] = u0[0]
u.vel[0] = u0[1]
return u
def u_exact(self, t):
"""
Routine to compute the exact trajectory at time t
Args:
t (float): current time
Returns:
dtype_u: exact position and velocity
"""
me = self.dtype_u(self.init)
delta = self.mu / (2)
omega = np.sqrt(self.k)
U_0 = self.u0
alpha = np.sqrt(np.abs(delta**2 - omega**2))
print(self.mu)
if delta > omega:
"""
Overdamped case
"""
lam_1 = -delta + alpha
lam_2 = -delta - alpha
L = np.array([[1, 1], [lam_1, lam_2]])
A, B = np.linalg.solve(L, U_0)
me.pos[:] = A * np.exp(lam_1 * t) + B * np.exp(lam_2 * t)
me.vel[:] = A * lam_1 * np.exp(lam_1 * t) + B * lam_2 * np.exp(lam_2 * t)
elif delta == omega:
"""
Critically damped case
"""
A = U_0[0]
B = U_0[1] + delta * A
me.pos[:] = np.exp(-delta * t) * (A + t * B)
me.vel[:] = -delta * me.pos[:] + np.exp(-delta * t) * B
elif delta < omega:
"""
Underdamped case
"""
lam_1 = -delta + alpha * 1j
lam_2 = -delta - alpha * 1j
M = np.array([[1, 1], [lam_1, lam_2]], dtype=complex)
A, B = np.linalg.solve(M, U_0)
me.pos[:] = np.real(A * np.exp(lam_1 * t) + B * np.exp(lam_2 * t))
me.vel[:] = np.real(A * lam_1 * np.exp(lam_1 * t) + B * lam_2 * np.exp(lam_2 * t))
else:
pass
raise ParameterError("Exact solution is not working")
return me
def eval_hamiltonian(self, u):
"""
Routine to compute the Hamiltonian
Args:
u (dtype_u): the particles
Returns:
float: hamiltonian
"""
ham = 0.5 * self.k * u.pos[0] ** 2 + 0.5 * u.vel[0] ** 2
return ham
| 3,195 | 26.316239 | 106 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/Boussinesq_2D_FD_imex.py | import numpy as np
from scipy.sparse.linalg import gmres
from pySDC.core.Errors import ParameterError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
from pySDC.implementations.problem_classes.boussinesq_helpers.build2DFDMatrix import get2DMesh
from pySDC.implementations.problem_classes.boussinesq_helpers.buildBoussinesq2DMatrix import getBoussinesq2DMatrix
from pySDC.implementations.problem_classes.boussinesq_helpers.buildBoussinesq2DMatrix import getBoussinesq2DUpwindMatrix
from pySDC.implementations.problem_classes.boussinesq_helpers.helper_classes import Callback, logging
from pySDC.implementations.problem_classes.boussinesq_helpers.unflatten import unflatten
# noinspection PyUnusedLocal
class boussinesq_2d_imex(ptype):
"""
Example implementing the 2D Boussinesq equation for different boundary conditions
"""
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)
"""
# these parameters will be used later, so assert their existence
essential_keys = [
'nvars',
'c_s',
'u_adv',
'Nfreq',
'x_bounds',
'z_bounds',
'order_upw',
'order',
'gmres_maxiter',
'gmres_restart',
'gmres_tol_limit',
]
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)
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(boussinesq_2d_imex, self).__init__(
(problem_params['nvars'], None, np.dtype('float64')), dtype_u, dtype_f, problem_params
)
self.N = [self.params.nvars[1], self.params.nvars[2]]
self.bc_hor = [
['periodic', 'periodic'],
['periodic', 'periodic'],
['periodic', 'periodic'],
['periodic', 'periodic'],
]
self.bc_ver = [
['neumann', 'neumann'],
['dirichlet', 'dirichlet'],
['dirichlet', 'dirichlet'],
['neumann', 'neumann'],
]
self.xx, self.zz, self.h = get2DMesh(
self.N, self.params.x_bounds, self.params.z_bounds, self.bc_hor[0], self.bc_ver[0]
)
self.Id, self.M = getBoussinesq2DMatrix(
self.N, self.h, self.bc_hor, self.bc_ver, self.params.c_s, self.params.Nfreq, self.params.order
)
self.D_upwind = getBoussinesq2DUpwindMatrix(self.N, self.h[0], self.params.u_adv, self.params.order_upw)
self.gmres_logger = logging()
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-dtA)u = rhs using GMRES
Args:
rhs (dtype_f): right-hand side for the nonlinear 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
"""
b = rhs.flatten()
cb = Callback()
sol, info = gmres(
self.Id - factor * self.M,
b,
x0=u0.flatten(),
tol=self.params.gmres_tol_limit,
restart=self.params.gmres_restart,
maxiter=self.params.gmres_maxiter,
atol=0,
callback=cb,
)
# If this is a dummy call with factor==0.0, do not log because it should not be counted as a solver call
if factor != 0.0:
self.gmres_logger.add(cb.getcounter())
me = self.dtype_u(self.init)
me[:] = unflatten(sol, 4, self.N[0], self.N[1])
return me
def __eval_fexpl(self, u, t):
"""
Helper routine to evaluate the explicit part of the RHS
Args:
u (dtype_u): current values (not used here)
t (float): current time
Returns:
explicit part of RHS
"""
# Evaluate right hand side
fexpl = self.dtype_u(self.init)
temp = u.flatten()
temp = self.D_upwind.dot(temp)
fexpl[:] = unflatten(temp, 4, self.N[0], self.N[1])
return fexpl
def __eval_fimpl(self, u, t):
"""
Helper routine to evaluate the implicit part of the RHS
Args:
u (dtype_u): current values
t (float): current time (not used here)
Returns:
implicit part of RHS
"""
temp = u.flatten()
temp = self.M.dot(temp)
fimpl = self.dtype_u(self.init)
fimpl[:] = unflatten(temp, 4, self.N[0], self.N[1])
return fimpl
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS divided into two parts
"""
f = self.dtype_f(self.init)
f.impl = self.__eval_fimpl(u, t)
f.expl = self.__eval_fexpl(u, t)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
assert t == 0, 'ERROR: u_exact only valid for t=0'
dtheta = 0.01
H = 10.0
a = 5.0
x_c = -50.0
me = self.dtype_u(self.init)
me[0, :, :] = 0.0 * self.xx
me[1, :, :] = 0.0 * self.xx
# me[2,:,:] = 0.0*self.xx
# me[3,:,:] = np.exp(-0.5*(self.xx-0.0)**2.0/0.15**2.0)*np.exp(-0.5*(self.zz-0.5)**2/0.15**2)
# me[2,:,:] = np.exp(-0.5*(self.xx-0.0)**2.0/0.05**2.0)*np.exp(-0.5*(self.zz-0.5)**2/0.2**2)
me[2, :, :] = dtheta * np.sin(np.pi * self.zz / H) / (1.0 + np.square(self.xx - x_c) / (a * a))
me[3, :, :] = 0.0 * self.xx
return me
| 6,425 | 31.619289 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AllenCahn_2D_FD.py | import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import cg
from pySDC.core.Errors import ParameterError, ProblemError
from pySDC.core.Problem import ptype
from pySDC.helpers import problem_helper
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh, comp2_mesh
# http://www.personal.psu.edu/qud2/Res/Pre/dz09sisc.pdf
# noinspection PyUnusedLocal
class allencahn_fullyimplicit(ptype):
"""
Example implementing the Allen-Cahn equation in 2D with finite differences and periodic BC
TODO : doku
Attributes:
A: second-order FD discretization of the 2D laplace operator
dx: distance between two spatial nodes (same for both directions)
"""
dtype_u = mesh
dtype_f = mesh
def __init__(self, nvars, nu, eps, newton_maxiter, newton_tol, lin_tol, lin_maxiter, radius, order=2):
"""
Initialization routine
"""
# we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on
if len(nvars) != 2:
raise ProblemError('this is a 2d example, got %s' % nvars)
if nvars[0] != nvars[1]:
raise ProblemError('need a square domain, got %s' % nvars)
if 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().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'nvars',
'nu',
'eps',
'newton_maxiter',
'newton_tol',
'lin_tol',
'lin_maxiter',
'radius',
'order',
localVars=locals(),
readOnly=True,
)
# compute dx and get discretization matrix A
self.dx = 1.0 / self.nvars[0]
self.A = problem_helper.get_finite_difference_matrix(
derivative=2,
order=self.order,
stencil_type='center',
dx=self.dx,
size=self.nvars[0],
dim=2,
bc='periodic',
)
self.xvalues = np.array([i * self.dx - 0.5 for i in range(self.nvars[0])])
self.newton_itercount = 0
self.lin_itercount = 0
self.newton_ncalls = 0
self.lin_ncalls = 0
@staticmethod
def __get_A(N, dx):
"""
Helper function to assemble FD matrix A in sparse format
Args:
N (list): number of dofs
dx (float): distance between two spatial nodes
Returns:
scipy.sparse.csc_matrix: matrix A in CSC format
"""
stencil = [1, -2, 1]
zero_pos = 2
dstencil = np.concatenate((stencil, np.delete(stencil, zero_pos - 1)))
offsets = np.concatenate(
(
[N[0] - i - 1 for i in reversed(range(zero_pos - 1))],
[i - zero_pos + 1 for i in range(zero_pos - 1, len(stencil))],
)
)
doffsets = np.concatenate((offsets, np.delete(offsets, zero_pos - 1) - N[0]))
A = sp.diags(dstencil, doffsets, shape=(N[0], N[0]), format='csc')
A = sp.kron(A, sp.eye(N[0])) + sp.kron(sp.eye(N[1]), A)
A *= 1.0 / (dx**2)
return A
# noinspection PyTypeChecker
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0).flatten()
z = self.dtype_u(self.init, val=0.0).flatten()
nu = self.nu
eps2 = self.eps**2
Id = sp.eye(self.nvars[0] * self.nvars[1])
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - factor * (self.A.dot(u) + 1.0 / eps2 * u * (1.0 - u**nu)) - rhs.flatten()
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (self.A + 1.0 / eps2 * sp.diags((1.0 - (nu + 1) * u**nu), offsets=0))
# newton update: u1 = u0 - g/dg
# u -= spsolve(dg, g)
u -= cg(dg, g, x0=z, tol=self.lin_tol, atol=0)[0]
# increase iteration count
n += 1
# print(n, res)
# if n == self.newton_maxiter:
# raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
me = self.dtype_u(self.init)
me[:] = u.reshape(self.nvars)
self.newton_ncalls += 1
self.newton_itercount += n
return me
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()
f[:] = (self.A.dot(v) + 1.0 / self.eps**2 * v * (1.0 - v**self.nu)).reshape(self.nvars)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
assert t == 0, 'ERROR: u_exact only valid for t=0'
me = self.dtype_u(self.init, val=0.0)
for i in range(self.nvars[0]):
for j in range(self.nvars[1]):
r2 = self.xvalues[i] ** 2 + self.xvalues[j] ** 2
me[i, j] = np.tanh((self.radius - np.sqrt(r2)) / (np.sqrt(2) * self.eps))
return me
# noinspection PyUnusedLocal
class allencahn_semiimplicit(allencahn_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 2D with finite differences, SDC standard splitting
"""
dtype_f = imex_mesh
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()
f.impl[:] = self.A.dot(v).reshape(self.nvars)
f.expl[:] = (1.0 / self.eps**2 * v * (1.0 - v**self.nu)).reshape(self.nvars)
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
class context:
num_iter = 0
def callback(xk):
context.num_iter += 1
return context.num_iter
me = self.dtype_u(self.init)
Id = sp.eye(self.nvars[0] * self.nvars[1])
me[:] = cg(
Id - factor * self.A,
rhs.flatten(),
x0=u0.flatten(),
tol=self.lin_tol,
maxiter=self.lin_maxiter,
atol=0,
callback=callback,
)[0].reshape(self.nvars)
self.lin_ncalls += 1
self.lin_itercount += context.num_iter
return me
# noinspection PyUnusedLocal
class allencahn_semiimplicit_v2(allencahn_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting
"""
dtype_f = imex_mesh
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()
f.impl[:] = (self.A.dot(v) - 1.0 / self.eps**2 * v ** (self.nu + 1)).reshape(self.nvars)
f.expl[:] = (1.0 / self.eps**2 * v).reshape(self.nvars)
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0).flatten()
z = self.dtype_u(self.init, val=0.0).flatten()
nu = self.nu
eps2 = self.eps**2
Id = sp.eye(self.nvars[0] * self.nvars[1])
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - factor * (self.A.dot(u) - 1.0 / eps2 * u ** (nu + 1)) - rhs.flatten()
# if g is close to 0, then we are done
# res = np.linalg.norm(g, np.inf)
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (self.A - 1.0 / eps2 * sp.diags(((nu + 1) * u**nu), offsets=0))
# newton update: u1 = u0 - g/dg
# u -= spsolve(dg, g)
u -= cg(dg, g, x0=z, tol=self.lin_tol, atol=0)[0]
# increase iteration count
n += 1
# print(n, res)
# if n == self.newton_maxiter:
# raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
me = self.dtype_u(self.init)
me[:] = u.reshape(self.nvars)
self.newton_ncalls += 1
self.newton_itercount += n
return me
# noinspection PyUnusedLocal
class allencahn_multiimplicit(allencahn_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 2D with finite differences, SDC standard splitting
"""
dtype_f = comp2_mesh
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()
f.comp1[:] = self.A.dot(v).reshape(self.nvars)
f.comp2[:] = (1.0 / self.eps**2 * v * (1.0 - v**self.nu)).reshape(self.nvars)
return f
def solve_system_1(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
class context:
num_iter = 0
def callback(xk):
context.num_iter += 1
return context.num_iter
me = self.dtype_u(self.init)
Id = sp.eye(self.nvars[0] * self.nvars[1])
me[:] = cg(
Id - factor * self.A,
rhs.flatten(),
x0=u0.flatten(),
tol=self.lin_tol,
maxiter=self.lin_maxiter,
atol=0,
callback=callback,
)[0].reshape(self.nvars)
self.lin_ncalls += 1
self.lin_itercount += context.num_iter
return me
def solve_system_2(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0).flatten()
z = self.dtype_u(self.init, val=0.0).flatten()
nu = self.nu
eps2 = self.eps**2
Id = sp.eye(self.nvars[0] * self.nvars[1])
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - factor * (1.0 / eps2 * u * (1.0 - u**nu)) - rhs.flatten()
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (1.0 / eps2 * sp.diags((1.0 - (nu + 1) * u**nu), offsets=0))
# newton update: u1 = u0 - g/dg
# u -= spsolve(dg, g)
u -= cg(dg, g, x0=z, tol=self.lin_tol, atol=0)[0]
# increase iteration count
n += 1
# print(n, res)
# if n == self.newton_maxiter:
# raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
me = self.dtype_u(self.init)
me[:] = u.reshape(self.nvars)
self.newton_ncalls += 1
self.newton_itercount += n
return me
# noinspection PyUnusedLocal
class allencahn_multiimplicit_v2(allencahn_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting
"""
dtype_f = comp2_mesh
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()
f.comp1[:] = (self.A.dot(v) - 1.0 / self.eps**2 * v ** (self.nu + 1)).reshape(self.nvars)
f.comp2[:] = (1.0 / self.eps**2 * v).reshape(self.nvars)
return f
def solve_system_1(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0).flatten()
z = self.dtype_u(self.init, val=0.0).flatten()
nu = self.nu
eps2 = self.eps**2
Id = sp.eye(self.nvars[0] * self.nvars[1])
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - factor * (self.A.dot(u) - 1.0 / eps2 * u ** (nu + 1)) - rhs.flatten()
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (self.A - 1.0 / eps2 * sp.diags(((nu + 1) * u**nu), offsets=0))
# newton update: u1 = u0 - g/dg
# u -= spsolve(dg, g)
u -= cg(
dg,
g,
x0=z,
tol=self.lin_tol,
atol=0,
)[0]
# increase iteration count
n += 1
# print(n, res)
# if n == self.newton_maxiter:
# raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
me = self.dtype_u(self.init)
me[:] = u.reshape(self.nvars)
self.newton_ncalls += 1
self.newton_itercount += n
return me
def solve_system_2(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(self.init)
me[:] = (1.0 / (1.0 - factor * 1.0 / self.eps**2) * rhs).reshape(self.nvars)
return me
| 16,814 | 28.192708 | 115 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AllenCahn_MPIFFT.py | import numpy as np
from mpi4py import MPI
from mpi4py_fft import PFFT
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
from mpi4py_fft import newDistArray
class allencahn_imex(ptype):
"""
Example implementing Allen-Cahn equation in 2-3D using mpi4py-fft for solving linear parts, IMEX time-stepping
mpi4py-fft: https://mpi4py-fft.readthedocs.io/en/latest/
Attributes:
fft: fft object
X: grid coordinates in real space
K2: Laplace operator in spectral space
dx: mesh width in x direction
dy: mesh width in y direction
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, nvars, eps, radius, spectral, dw=0.0, L=1.0, init_type='circle', comm=None):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: fft data type (will be passed to parent class)
dtype_f: fft data type wuth implicit and explicit parts (will be passed to parent class)
"""
if not (isinstance(nvars, tuple) and len(nvars) > 1):
raise ProblemError('Need at least two dimensions')
# Creating FFT structure
ndim = len(nvars)
axes = tuple(range(ndim))
self.fft = PFFT(comm, list(nvars), axes=axes, dtype=np.float64, collapse=True)
# get test data to figure out type and dimensions
tmp_u = newDistArray(self.fft, spectral)
# invoke super init, passing the communicator and the local dimensions as init
super().__init__(init=(tmp_u.shape, comm, tmp_u.dtype))
self._makeAttributeAndRegister(
'nvars', 'eps', 'radius', 'spectral', 'dw', 'L', 'init_type', 'comm', localVars=locals(), readOnly=True
)
L = np.array([self.L] * ndim, dtype=float)
# get local mesh
X = np.ogrid[self.fft.local_slice(False)]
N = self.fft.global_shape()
for i in range(len(N)):
X[i] = X[i] * L[i] / N[i]
self.X = [np.broadcast_to(x, self.fft.shape(False)) for x in X]
# get local wavenumbers and Laplace operator
s = self.fft.local_slice()
N = self.fft.global_shape()
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)
K = [np.broadcast_to(k, self.fft.shape(True)) for k in Ks]
K = np.array(K).astype(float)
self.K2 = np.sum(K * K, 0, dtype=float)
# Need this for diagnostics
self.dx = self.L / nvars[0]
self.dy = self.L / nvars[1]
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)
if self.spectral:
f.impl = -self.K2 * u
if self.eps > 0:
tmp = self.fft.backward(u)
tmpf = -2.0 / self.eps**2 * tmp * (1.0 - tmp) * (1.0 - 2.0 * tmp) - 6.0 * self.dw * tmp * (1.0 - tmp)
f.expl[:] = self.fft.forward(tmpf)
else:
u_hat = self.fft.forward(u)
lap_u_hat = -self.K2 * u_hat
f.impl[:] = self.fft.backward(lap_u_hat, f.impl)
if self.eps > 0:
f.expl = -2.0 / self.eps**2 * u * (1.0 - u) * (1.0 - 2.0 * u) - 6.0 * self.dw * u * (1.0 - u)
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
"""
if self.spectral:
me = rhs / (1.0 + factor * self.K2)
else:
me = self.dtype_u(self.init)
rhs_hat = self.fft.forward(rhs)
rhs_hat /= 1.0 + factor * self.K2
me[:] = self.fft.backward(rhs_hat)
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
assert t == 0, 'ERROR: u_exact only valid for t=0'
me = self.dtype_u(self.init, val=0.0)
if self.init_type == 'circle':
r2 = (self.X[0] - 0.5) ** 2 + (self.X[1] - 0.5) ** 2
if self.spectral:
tmp = 0.5 * (1.0 + np.tanh((self.radius - np.sqrt(r2)) / (np.sqrt(2) * self.eps)))
me[:] = self.fft.forward(tmp)
else:
me[:] = 0.5 * (1.0 + np.tanh((self.radius - np.sqrt(r2)) / (np.sqrt(2) * self.eps)))
elif self.init_type == 'circle_rand':
ndim = len(me.shape)
L = int(self.L)
# get random radii for circles/spheres
np.random.seed(1)
lbound = 3.0 * self.eps
ubound = 0.5 - self.eps
rand_radii = (ubound - lbound) * np.random.random_sample(size=tuple([L] * ndim)) + lbound
# distribute circles/spheres
tmp = newDistArray(self.fft, False)
if ndim == 2:
for i in range(0, L):
for j in range(0, L):
# build radius
r2 = (self.X[0] + i - L + 0.5) ** 2 + (self.X[1] + j - L + 0.5) ** 2
# add this blob, shifted by 1 to avoid issues with adding up negative contributions
tmp += np.tanh((rand_radii[i, j] - np.sqrt(r2)) / (np.sqrt(2) * self.eps)) + 1
# normalize to [0,1]
tmp *= 0.5
assert np.all(tmp <= 1.0)
if self.spectral:
me[:] = self.fft.forward(tmp)
else:
me[:] = tmp[:]
else:
raise NotImplementedError('type of initial value not implemented, got %s' % self.init_type)
return me
class allencahn_imex_timeforcing(allencahn_imex):
"""
Example implementing Allen-Cahn equation in 2-3D using mpi4py-fft for solving linear parts, IMEX time-stepping,
time-dependent forcing
"""
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)
if self.spectral:
f.impl = -self.K2 * u
tmp = newDistArray(self.fft, False)
tmp[:] = self.fft.backward(u, tmp)
if self.eps > 0:
tmpf = -2.0 / self.eps**2 * tmp * (1.0 - tmp) * (1.0 - 2.0 * tmp)
else:
tmpf = self.dtype_f(self.init, val=0.0)
# build sum over RHS without driving force
Rt_local = float(np.sum(self.fft.backward(f.impl) + tmpf))
if self.comm is not None:
Rt_global = self.comm.allreduce(sendobj=Rt_local, op=MPI.SUM)
else:
Rt_global = Rt_local
# build sum over driving force term
Ht_local = float(np.sum(6.0 * tmp * (1.0 - tmp)))
if self.comm is not None:
Ht_global = self.comm.allreduce(sendobj=Ht_local, op=MPI.SUM)
else:
Ht_global = Rt_local
# add/substract time-dependent driving force
if Ht_global != 0.0:
dw = Rt_global / Ht_global
else:
dw = 0.0
tmpf -= 6.0 * dw * tmp * (1.0 - tmp)
f.expl[:] = self.fft.forward(tmpf)
else:
u_hat = self.fft.forward(u)
lap_u_hat = -self.K2 * u_hat
f.impl[:] = self.fft.backward(lap_u_hat, f.impl)
if self.eps > 0:
f.expl = -2.0 / self.eps**2 * u * (1.0 - u) * (1.0 - 2.0 * u)
# build sum over RHS without driving force
Rt_local = float(np.sum(f.impl + f.expl))
if self.comm is not None:
Rt_global = self.comm.allreduce(sendobj=Rt_local, op=MPI.SUM)
else:
Rt_global = Rt_local
# build sum over driving force term
Ht_local = float(np.sum(6.0 * u * (1.0 - u)))
if self.comm is not None:
Ht_global = self.comm.allreduce(sendobj=Ht_local, op=MPI.SUM)
else:
Ht_global = Rt_local
# add/substract time-dependent driving force
if Ht_global != 0.0:
dw = Rt_global / Ht_global
else:
dw = 0.0
f.expl -= 6.0 * dw * u * (1.0 - u)
return f
| 9,302 | 32.952555 | 117 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/HeatEquation_ND_FD.py | import numpy as np
from pySDC.implementations.problem_classes.generic_ND_FD import GenericNDimFinDiff
from pySDC.implementations.datatype_classes.mesh import imex_mesh
class heatNd_unforced(GenericNDimFinDiff):
def __init__(
self,
nvars=512,
nu=0.1,
freq=2,
stencil_type='center',
order=2,
lintol=1e-12,
liniter=10000,
solver_type='direct',
bc='periodic',
sigma=6e-2,
):
super().__init__(nvars, nu, 2, freq, stencil_type, order, lintol, liniter, solver_type, bc)
if solver_type == 'GMRES':
self.logger.warn('GMRES is not usually used for heat equation')
self._makeAttributeAndRegister('nu', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister('sigma', localVars=locals())
def u_exact(self, t, **kwargs):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
ndim, freq, nu, sigma, dx, sol = self.ndim, self.freq, self.nu, self.sigma, self.dx, self.u_init
if ndim == 1:
x = self.grids
rho = (2.0 - 2.0 * np.cos(np.pi * freq[0] * dx)) / dx**2
if freq[0] > 0:
sol[:] = np.sin(np.pi * freq[0] * x) * np.exp(-t * nu * rho)
elif freq[0] == -1: # Gaussian
sol[:] = np.exp(-0.5 * ((x - 0.5) / sigma) ** 2) * np.exp(-t * nu * rho)
elif ndim == 2:
rho = (2.0 - 2.0 * np.cos(np.pi * freq[0] * dx)) / dx**2 + (
2.0 - 2.0 * np.cos(np.pi * freq[1] * dx)
) / dx**2
x, y = self.grids
sol[:] = np.sin(np.pi * freq[0] * x) * np.sin(np.pi * freq[1] * y) * np.exp(-t * nu * rho)
elif ndim == 3:
rho = (
(2.0 - 2.0 * np.cos(np.pi * freq[0] * dx)) / dx**2
+ (2.0 - 2.0 * np.cos(np.pi * freq[1] * dx))
+ (2.0 - 2.0 * np.cos(np.pi * freq[2] * dx)) / dx**2
)
x, y, z = self.grids
sol[:] = (
np.sin(np.pi * freq[0] * x)
* np.sin(np.pi * freq[1] * y)
* np.sin(np.pi * freq[2] * z)
* np.exp(-t * nu * rho)
)
return sol
class heatNd_forced(heatNd_unforced):
"""
Example implementing the ND heat equation with periodic or Diriclet-Zero BCs in [0,1]^N,
discretized using central finite differences
Attributes:
A: FD discretization of the ND laplace operator
dx: distance between two spatial nodes (here: being the same in all dimensions)
"""
dtype_f = imex_mesh
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.f_init
f.impl[:] = self.A.dot(u.flatten()).reshape(self.nvars)
ndim, freq, nu = self.ndim, self.freq, self.nu
if ndim == 1:
x = self.grids
f.expl[:] = np.sin(np.pi * freq[0] * x) * (
nu * np.pi**2 * sum([freq**2 for freq in freq]) * np.cos(t) - np.sin(t)
)
elif ndim == 2:
x, y = self.grids
f.expl[:] = (
np.sin(np.pi * freq[0] * x)
* np.sin(np.pi * freq[1] * y)
* (nu * np.pi**2 * sum([freq**2 for freq in freq]) * np.cos(t) - np.sin(t))
)
elif ndim == 3:
x, y, z = self.grids
f.expl[:] = (
np.sin(np.pi * freq[0] * x)
* np.sin(np.pi * freq[1] * y)
* np.sin(np.pi * freq[2] * z)
* (nu * np.pi**2 * sum([freq**2 for freq in freq]) * np.cos(t) - np.sin(t))
)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
ndim, freq, sol = self.ndim, self.freq, self.u_init
if ndim == 1:
x = self.grids
sol[:] = np.sin(np.pi * freq[0] * x) * np.cos(t)
elif ndim == 2:
x, y = self.grids
sol[:] = np.sin(np.pi * freq[0] * x) * np.sin(np.pi * freq[1] * y) * np.cos(t)
elif ndim == 3:
x, y, z = self.grids
sol[:] = np.sin(np.pi * freq[0] * x) * np.sin(np.pi * freq[1] * y) * np.sin(np.pi * freq[2] * z) * np.cos(t)
return sol
| 4,649 | 31.978723 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AdvectionDiffusionEquation_1D_FFT.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 advectiondiffusion1d_imex(ptype):
"""
Example implementing the unforced 1D advection diffusion equation with periodic BC in [-L/2, L/2] in spectral space,
IMEX time-stepping
Attributes:
xvalues: grid points in space
ddx: spectral operator for gradient
lap: spectral operator for Laplacian
rfft_object: planned real-valued FFT for forward transformation
irfft_object: planned IFFT for backward transformation, real-valued output
"""
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 with implicit and explicit component (will be passed to parent class)
"""
if 'L' not in problem_params:
problem_params['L'] = 1.0
# these parameters will be used later, so assert their existence
essential_keys = ['nvars', 'c', 'freq', 'nu', 'L']
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 (problem_params['nvars']) % 2 != 0:
raise ProblemError('setup requires nvars = 2^p')
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(advectiondiffusion1d_imex, self).__init__(
init=(problem_params['nvars'], None, np.dtype('float64')),
dtype_u=dtype_u,
dtype_f=dtype_f,
params=problem_params,
)
self.xvalues = np.array(
[i * self.params.L / self.params.nvars - self.params.L / 2.0 for i in range(self.params.nvars)]
)
kx = np.zeros(self.init[0] // 2 + 1)
for i in range(0, len(kx)):
kx[i] = 2 * np.pi / self.params.L * i
self.ddx = kx * 1j
self.lap = -(kx**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)
tmp_u = np.fft.rfft(u)
tmp_impl = self.params.nu * self.lap * tmp_u
tmp_expl = -self.params.c * self.ddx * tmp_u
f.impl[:] = np.fft.irfft(tmp_impl)
f.expl[:] = np.fft.irfft(tmp_expl)
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.rfft(rhs) / (1.0 - self.params.nu * factor * self.lap)
me[:] = np.fft.irfft(tmp)
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
me = self.dtype_u(self.init, val=0.0)
if self.params.freq > 0:
omega = 2.0 * np.pi * self.params.freq
me[:] = np.sin(omega * (self.xvalues - self.params.c * t)) * np.exp(-t * self.params.nu * omega**2)
elif self.params.freq == 0:
np.random.seed(1)
me[:] = np.random.rand(self.params.nvars)
else:
t00 = 0.08
if self.params.nu > 0:
nbox = int(np.ceil(np.sqrt(4.0 * self.params.nu * (t00 + t) * 37.0 / (self.params.L**2))))
for k in range(-nbox, nbox + 1):
for i in range(self.init[0]):
x = self.xvalues[i] - self.params.c * t + k * self.params.L
me[i] += (
np.sqrt(t00) / np.sqrt(t00 + t) * np.exp(-(x**2) / (4.0 * self.params.nu * (t00 + t)))
)
return me
class advectiondiffusion1d_implicit(advectiondiffusion1d_imex):
"""
Example implementing the unforced 1D advection diffusion equation with periodic BC in [-L/2, L/2] in spectral space,
fully-implicit time-stepping
"""
def __init__(self, problem_params, dtype_u=mesh, dtype_f=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 (will be passed to parent class)
"""
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(advectiondiffusion1d_implicit, self).__init__(
problem_params=problem_params, dtype_u=dtype_u, dtype_f=dtype_f
)
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)
tmp_u = np.fft.rfft(u)
tmp = self.params.nu * self.lap * tmp_u - self.params.c * self.ddx * tmp_u
f[:] = np.fft.irfft(tmp)
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple FFT solver for the diffusion and advection part (both are linear!)
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.rfft(rhs) / (1.0 - factor * (self.params.nu * self.lap - self.params.c * self.ddx))
me[:] = np.fft.irfft(tmp)
return me
| 6,693 | 33.153061 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/GrayScott_1D_FEniCS_implicit.py | import logging
import random
import dolfin as df
import numpy as np
from pySDC.core.Errors import ParameterError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.fenics_mesh import fenics_mesh
# noinspection PyUnusedLocal
class fenics_grayscott(ptype):
"""
Example implementing the forced 1D heat equation with Dirichlet-0 BC in [0,1]
Attributes:
V: function space
w: function for the RHS
w1: split of w, part 1
w2: split of w, part 2
F1: weak form of RHS, first part
F2: weak form of RHS, second part
F: weak form of RHS, full
M: full mass matrix for both parts
"""
def __init__(self, problem_params, dtype_u=fenics_mesh, dtype_f=fenics_mesh):
"""
Initialization routine
Args:
problem_params: custom parameters for the example
dtype_u: FEniCS mesh data type (will be passed to parent class)
dtype_f: FEniCS mesh data data type (will be passed to parent class)
"""
# define the Dirichlet boundary
def Boundary(x, on_boundary):
return on_boundary
# these parameters will be used later, so assert their existence
essential_keys = ['c_nvars', 't0', 'family', 'order', 'refinements', 'Du', 'Dv', 'A', 'B']
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)
# set logger level for FFC and dolfin
df.set_log_level(df.WARNING)
logging.getLogger('FFC').setLevel(logging.WARNING)
# set solver and form parameters
df.parameters["form_compiler"]["optimize"] = True
df.parameters["form_compiler"]["cpp_optimize"] = True
# set mesh and refinement (for multilevel)
mesh = df.IntervalMesh(problem_params['c_nvars'], 0, 100)
for _ in range(problem_params['refinements']):
mesh = df.refine(mesh)
# define function space for future reference
V = df.FunctionSpace(mesh, problem_params['family'], problem_params['order'])
self.V = V * V
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(fenics_grayscott, self).__init__(self.V, dtype_u, dtype_f, problem_params)
# rhs in weak form
self.w = df.Function(self.V)
q1, q2 = df.TestFunctions(self.V)
self.w1, self.w2 = df.split(self.w)
self.F1 = (
-self.params.Du * df.inner(df.nabla_grad(self.w1), df.nabla_grad(q1))
- self.w1 * (self.w2**2) * q1
+ self.params.A * (1 - self.w1) * q1
) * df.dx
self.F2 = (
-self.params.Dv * df.inner(df.nabla_grad(self.w2), df.nabla_grad(q2))
+ self.w1 * (self.w2**2) * q2
- self.params.B * self.w2 * q2
) * df.dx
self.F = self.F1 + self.F2
# mass matrix
u1, u2 = df.TrialFunctions(self.V)
a_M = u1 * q1 * df.dx
M1 = df.assemble(a_M)
a_M = u2 * q2 * df.dx
M2 = df.assemble(a_M)
self.M = M1 + M2
def __invert_mass_matrix(self, u):
"""
Helper routine to invert mass matrix
Args:
u (dtype_u): current values
Returns:
dtype_u: inv(M)*u
"""
me = self.dtype_u(self.V)
A = 1.0 * self.M
b = self.dtype_u(u)
df.solve(A, me.values.vector(), b.values.vector())
return me
def solve_system(self, rhs, factor, u0, t):
"""
Dolfin's linear solver for (M-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the nonlinear 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
Returns:
dtype_u: solution as mesh
"""
sol = self.dtype_u(self.V)
self.w.assign(sol.values)
# fixme: is this really necessary to do each time?
q1, q2 = df.TestFunctions(self.V)
w1, w2 = df.split(self.w)
r1, r2 = df.split(rhs.values)
F1 = w1 * q1 * df.dx - factor * self.F1 - r1 * q1 * df.dx
F2 = w2 * q2 * df.dx - factor * self.F2 - r2 * q2 * df.dx
F = F1 + F2
du = df.TrialFunction(self.V)
J = df.derivative(F, self.w, du)
problem = df.NonlinearVariationalProblem(F, self.w, [], J)
solver = df.NonlinearVariationalSolver(problem)
prm = solver.parameters
prm['newton_solver']['absolute_tolerance'] = 1e-09
prm['newton_solver']['relative_tolerance'] = 1e-08
prm['newton_solver']['maximum_iterations'] = 100
prm['newton_solver']['relaxation_parameter'] = 1.0
solver.solve()
sol.values.assign(self.w)
return sol
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS divided into two parts
"""
f = self.dtype_f(self.V)
self.w.assign(u.values)
f.values = df.Function(self.V, df.assemble(self.F))
f = self.__invert_mass_matrix(f)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
class InitialConditions(df.Expression):
def __init__(self):
# fixme: why do we need this?
random.seed(2)
pass
def eval(self, values, x):
values[0] = 1 - 0.5 * np.power(np.sin(np.pi * x[0] / 100), 100)
values[1] = 0.25 * np.power(np.sin(np.pi * x[0] / 100), 100)
def value_shape(self):
return (2,)
assert t == 0, 'ERROR: u_exact only valid for t=0'
uinit = InitialConditions()
me = self.dtype_u(self.V)
me.values = df.interpolate(uinit, self.V)
return me
| 6,334 | 29.023697 | 103 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/nonlinear_ODE_1.py | import numpy as np
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh
# noinspection PyUnusedLocal
class nonlinear_ODE_1(ptype):
"""
Example implementing some simple nonlinear ODE with a singularity in the derivative, taken from
https://www.osti.gov/servlets/purl/6111421 (Problem E-4)
"""
dtype_u = mesh
dtype_f = mesh
def __init__(self, u0, newton_maxiter, newton_tol, stop_at_nan=True):
nvars = 1
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'u0', 'newton_maxiter', 'newton_tol', 'stop_at_nan', localVars=locals(), readOnly=True
)
def u_exact(self, t):
"""
Exact solution
Args:
t (float): current time
Returns:
dtype_u: mesh type containing the values
"""
me = self.dtype_u(self.init)
me[:] = t - t**2 / 4
return me
def eval_f(self, u, t):
"""
Routine to compute the RHS
Args:
u (dtype_u): the current values
t (float): current time (not used here)
Returns:
dtype_f: RHS, 1 component
"""
f = self.dtype_f(self.init)
f[:] = np.sqrt(1 - u)
return f
def solve_system(self, rhs, dt, u0, t):
"""
Simple Newton solver for the nonlinear equation
Args:
rhs (dtype_f): right-hand side for the nonlinear system
dt (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution u
"""
# create new mesh object from u0 and set initial values for iteration
u = self.dtype_u(u0)
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - dt * np.sqrt(1 - u) - rhs
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol or np.isnan(res):
break
# assemble dg/du
dg = 1 - (-dt) / (2 * np.sqrt(1 - u))
# newton update: u1 = u0 - g/dg
u -= 1.0 / dg * g
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
return u
| 2,929 | 28.59596 | 101 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/GeneralizedFisher_1D_FD_implicit.py | import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import spsolve
from pySDC.core.Errors import ParameterError, ProblemError
from pySDC.core.Problem import ptype
from pySDC.helpers import problem_helper
from pySDC.implementations.datatype_classes.mesh import mesh
# noinspection PyUnusedLocal
class generalized_fisher(ptype):
"""
Example implementing the generalized Fisher's equation in 1D with finite differences
Attributes:
A: second-order FD discretization of the 1D laplace operator
dx: distance between two spatial nodes
"""
dtype_u = mesh
dtype_f = mesh
def __init__(self, nvars, nu, lambda0, newton_maxiter, newton_tol, interval, stop_at_nan=True):
"""Initialization routine"""
# we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on
if (nvars + 1) % 2 != 0:
raise ProblemError('setup requires nvars = 2^p - 1')
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'nvars',
'nu',
'lambda0',
'newton_maxiter',
'newton_tol',
'interval',
'stop_at_nan',
localVars=locals(),
readOnly=True,
)
# compute dx and get discretization matrix A
self.dx = (self.interval[1] - self.interval[0]) / (self.nvars + 1)
self.A = problem_helper.get_finite_difference_matrix(
derivative=2,
order=2,
stencil_type='center',
dx=self.dx,
size=self.nvars + 2,
dim=1,
bc='dirichlet-zero',
)
# noinspection PyTypeChecker
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0)
nu = self.nu
lambda0 = self.lambda0
# set up boundary values to embed inner points
lam1 = lambda0 / 2.0 * ((nu / 2.0 + 1) ** 0.5 + (nu / 2.0 + 1) ** (-0.5))
sig1 = lam1 - np.sqrt(lam1**2 - lambda0**2)
ul = (1 + (2 ** (nu / 2.0) - 1) * np.exp(-nu / 2.0 * sig1 * (self.interval[0] + 2 * lam1 * t))) ** (-2.0 / nu)
ur = (1 + (2 ** (nu / 2.0) - 1) * np.exp(-nu / 2.0 * sig1 * (self.interval[1] + 2 * lam1 * t))) ** (-2.0 / nu)
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
uext = np.concatenate(([ul], u, [ur]))
g = u - factor * (self.A.dot(uext)[1:-1] + lambda0**2 * u * (1 - u**nu)) - rhs
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = sp.eye(self.nvars) - factor * (
self.A[1:-1, 1:-1] + sp.diags(lambda0**2 - lambda0**2 * (nu + 1) * u**nu, offsets=0)
)
# newton update: u1 = u0 - g/dg
u -= spsolve(dg, g)
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
self.logger.warning('Newton did not converge after %i iterations, error is %s' % (n, res))
return u
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
"""
# set up boundary values to embed inner points
lam1 = self.lambda0 / 2.0 * ((self.nu / 2.0 + 1) ** 0.5 + (self.nu / 2.0 + 1) ** (-0.5))
sig1 = lam1 - np.sqrt(lam1**2 - self.lambda0**2)
ul = (1 + (2 ** (self.nu / 2.0) - 1) * np.exp(-self.nu / 2.0 * sig1 * (self.interval[0] + 2 * lam1 * t))) ** (
-2 / self.nu
)
ur = (1 + (2 ** (self.nu / 2.0) - 1) * np.exp(-self.nu / 2.0 * sig1 * (self.interval[1] + 2 * lam1 * t))) ** (
-2 / self.nu
)
uext = np.concatenate(([ul], u, [ur]))
f = self.dtype_f(self.init)
f[:] = self.A.dot(uext)[1:-1] + self.lambda0**2 * u * (1 - u**self.nu)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
me = self.dtype_u(self.init)
xvalues = np.array([(i + 1 - (self.nvars + 1) / 2) * self.dx for i in range(self.nvars)])
lam1 = self.lambda0 / 2.0 * ((self.nu / 2.0 + 1) ** 0.5 + (self.nu / 2.0 + 1) ** (-0.5))
sig1 = lam1 - np.sqrt(lam1**2 - self.lambda0**2)
me[:] = (1 + (2 ** (self.nu / 2.0) - 1) * np.exp(-self.nu / 2.0 * sig1 * (xvalues + 2 * lam1 * t))) ** (
-2.0 / self.nu
)
return me
| 5,559 | 32.69697 | 118 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/HenonHeiles.py | import numpy as np
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.particles import particles, acceleration
# noinspection PyUnusedLocal
class henon_heiles(ptype):
"""
Example implementing the harmonic oscillator
"""
dtype_u = particles
dtype_f = acceleration
def __init__(self):
"""Initialization routine"""
# invoke super init, passing nparts
super().__init__((2, None, np.dtype('float64')))
def eval_f(self, u, t):
"""
Routine to compute the RHS
Args:
u (dtype_u): the particles
t (float): current time (not used here)
Returns:
dtype_f: RHS
"""
me = self.dtype_f(self.init)
me[0] = -u.pos[0] - 2 * u.pos[0] * u.pos[1]
me[1] = -u.pos[1] - u.pos[0] ** 2 + u.pos[1] ** 2
return me
def u_exact(self, t):
"""
Routine to compute the exact/initial trajectory at time t
Args:
t (float): current time
Returns:
dtype_u: exact/initial position and velocity
"""
assert t == 0.0, 'error, u_exact only works for the initial time t0=0'
me = self.dtype_u(self.init)
q1 = 0.0
q2 = 0.2
p2 = 0.2
U0 = 0.5 * (q1 * q1 + q2 * q2) + q1 * q1 * q2 - q2 * q2 * q2 / 3.0
H0 = 0.125
me.pos[0] = q1
me.pos[1] = q2
me.vel[0] = np.sqrt(2.0 * (H0 - U0) - p2 * p2)
me.vel[1] = p2
return me
def eval_hamiltonian(self, u):
"""
Routine to compute the Hamiltonian
Args:
u (dtype_u): the particles
Returns:
float: hamiltonian
"""
ham = 0.5 * (u.vel[0] ** 2 + u.vel[1] ** 2)
ham += 0.5 * (u.pos[0] ** 2 + u.pos[1] ** 2)
ham += u.pos[0] ** 2 * u.pos[1] - u.pos[1] ** 3 / 3.0
return ham
| 1,920 | 24.959459 | 84 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/Auzinger_implicit.py | import numpy as np
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh
# noinspection PyUnusedLocal
class auzinger(ptype):
"""
Example implementing the Auzinger initial value problem
"""
dtype_u = mesh
dtype_f = mesh
def __init__(self, newton_maxiter, newton_tol):
"""
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 (will be passed to parent class)
"""
# invoke super init, passing dtype_u and dtype_f, plus setting number of elements to 2
super().__init__((2, None, np.dtype('float64')))
self._makeAttributeAndRegister('newton_maxiter', 'newton_tol', localVars=locals(), readOnly=True)
def u_exact(self, t):
"""
Routine for the exact solution
Args:
t (float): current time
Returns:
dtype_u: mesh type containing the exact solution
"""
me = self.dtype_u(self.init)
me[0] = np.cos(t)
me[1] = np.sin(t)
return me
def eval_f(self, u, t):
"""
Routine to compute the RHS for both components simultaneously
Args:
u (dtype_u): the current values
t (float): current time (not used here)
Returns:
RHS, 2 components
"""
x1 = u[0]
x2 = u[1]
f = self.dtype_f(self.init)
f[0] = -x2 + x1 * (1 - x1**2 - x2**2)
f[1] = x1 + 3 * x2 * (1 - x1**2 - x2**2)
return f
def solve_system(self, rhs, dt, u0, t):
"""
Simple Newton solver for the nonlinear system
Args:
rhs (dtype_f): right-hand side for the nonlinear system
dt (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution u
"""
# create new mesh object from u0 and set initial values for iteration
u = self.dtype_u(u0)
x1 = u[0]
x2 = u[1]
# start newton iteration
n = 0
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = np.array(
[
x1 - dt * (-x2 + x1 * (1 - x1**2 - x2**2)) - rhs[0],
x2 - dt * (x1 + 3 * x2 * (1 - x1**2 - x2**2)) - rhs[1],
]
)
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg and invert the matrix (yeah, I know)
dg = np.array(
[
[1 - dt * (1 - 3 * x1**2 - x2**2), -dt * (-1 - 2 * x1 * x2)],
[-dt * (1 - 6 * x1 * x2), 1 - dt * (3 - 3 * x1**2 - 9 * x2**2)],
]
)
idg = np.linalg.inv(dg)
# newton update: u1 = u0 - g/dg
u -= np.dot(idg, g)
# set new values and increase iteration count
x1 = u[0]
x2 = u[1]
n += 1
return u
# def eval_jacobian(self, u):
#
# x1 = u[0]
# x2 = u[1]
#
# dfdu = np.array([[1-3*x1**2-x2**2, -1-x1], [1+6*x2*x1, 3+3*x1**2-9*x2**2]])
#
# return dfdu
#
#
# def solve_system_jacobian(self, dfdu, rhs, factor, u0, t):
#
# me = mesh(2)
# me = LA.spsolve(sp.eye(2) - factor * dfdu, rhs)
# return me
| 3,816 | 27.699248 | 105 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/generic_ND_FD.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 11 22:39:30 2023
@author: telu
"""
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import gmres, spsolve, cg
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype, WorkCounter
from pySDC.helpers import problem_helper
from pySDC.implementations.datatype_classes.mesh import mesh
class GenericNDimFinDiff(ptype):
dtype_u = mesh
dtype_f = mesh
def __init__(
self,
nvars=512,
coeff=1.0,
derivative=1,
freq=2,
stencil_type='center',
order=2,
lintol=1e-12,
liniter=10000,
solver_type='direct',
bc='periodic',
):
# make sure parameters have the correct types
if not type(nvars) in [int, tuple]:
raise ProblemError('nvars should be either tuple or int')
if not type(freq) in [int, tuple]:
raise ProblemError('freq should be either tuple or int')
# transforms nvars into a tuple
if type(nvars) is int:
nvars = (nvars,)
# automatically determine ndim from nvars
ndim = len(nvars)
if ndim > 3:
raise ProblemError(f'can work with up to three dimensions, got {ndim}')
# eventually extend freq to other dimension
if type(freq) is int:
freq = (freq,) * ndim
if len(freq) != ndim:
raise ProblemError(f'len(freq)={len(freq)}, different to ndim={ndim}')
# check values for freq and nvars
for f in freq:
if ndim == 1 and f == -1:
# use Gaussian initial solution in 1D
bc = 'periodic'
break
if f % 2 != 0 and bc == 'periodic':
raise ProblemError('need even number of frequencies due to periodic BCs')
for nvar in nvars:
if nvar % 2 != 0 and bc == 'periodic':
raise ProblemError('the setup requires nvars = 2^p per dimension')
if (nvar + 1) % 2 != 0 and bc == 'dirichlet-zero':
raise ProblemError('setup requires nvars = 2^p - 1')
if ndim > 1 and nvars[1:] != nvars[:-1]:
raise ProblemError('need a square domain, got %s' % nvars)
# invoke super init, passing number of dofs
super().__init__(init=(nvars[0] if ndim == 1 else nvars, None, np.dtype('float64')))
# compute dx (equal in both dimensions) and get discretization matrix A
if bc == 'periodic':
dx = 1.0 / nvars[0]
xvalues = np.array([i * dx for i in range(nvars[0])])
elif bc == 'dirichlet-zero':
dx = 1.0 / (nvars[0] + 1)
xvalues = np.array([(i + 1) * dx for i in range(nvars[0])])
else:
raise ProblemError(f'Boundary conditions {bc} not implemented.')
self.A = problem_helper.get_finite_difference_matrix(
derivative=derivative,
order=order,
stencil_type=stencil_type,
dx=dx,
size=nvars[0],
dim=ndim,
bc=bc,
)
self.A *= coeff
self.xvalues = xvalues
self.Id = sp.eye(np.prod(nvars), format='csc')
# store attribute and register them as parameters
self._makeAttributeAndRegister('nvars', 'stencil_type', 'order', 'bc', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister('freq', 'lintol', 'liniter', 'solver_type', localVars=locals())
if self.solver_type != 'direct':
self.work_counters[self.solver_type] = WorkCounter()
@property
def ndim(self):
"""Number of dimensions of the spatial problem"""
return len(self.nvars)
@property
def dx(self):
"""Size of the mesh (in all dimensions)"""
return self.xvalues[1] - self.xvalues[0]
@property
def grids(self):
"""ND grids associated to the problem"""
x = self.xvalues
if self.ndim == 1:
return x
if self.ndim == 2:
return x[None, :], x[:, None]
if self.ndim == 3:
return x[None, :, None], x[:, None, None], x[None, None, :]
def eval_f(self, u, t):
"""
Routine to evaluate the RHS
Parameters
----------
u : dtype_u
Current values.
t : float
Current time.
Returns
-------
f : dtype_f
The RHS values.
"""
f = self.f_init
f[:] = self.A.dot(u.flatten()).reshape(self.nvars)
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs.
Parameters
----------
rhs : dtype_f
Right-hand side for the linear system.
factor : float
Abbrev. for the local stepsize (or any other factor required).
u0 : dtype_u
Initial guess for the iterative solver.
t : float
Current time (e.g. for time-dependent BCs).
Returns
-------
sol : dtype_u
The solution of the linear solver.
"""
solver_type, Id, A, nvars, lintol, liniter, sol = (
self.solver_type,
self.Id,
self.A,
self.nvars,
self.lintol,
self.liniter,
self.u_init,
)
if solver_type == 'direct':
sol[:] = spsolve(Id - factor * A, rhs.flatten()).reshape(nvars)
elif solver_type == 'GMRES':
sol[:] = gmres(
Id - factor * A,
rhs.flatten(),
x0=u0.flatten(),
tol=lintol,
maxiter=liniter,
atol=0,
callback=self.work_counters[solver_type],
)[0].reshape(nvars)
elif solver_type == 'CG':
sol[:] = cg(
Id - factor * A,
rhs.flatten(),
x0=u0.flatten(),
tol=lintol,
maxiter=liniter,
atol=0,
callback=self.work_counters[solver_type],
)[0].reshape(nvars)
else:
raise ValueError(f'solver type "{solver_type}" not known in generic advection-diffusion implementation!')
return sol
| 6,378 | 30.423645 | 117 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/Quench.py | import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import spsolve, gmres, inv
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype, WorkCounter
from pySDC.helpers import problem_helper
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
# noinspection PyUnusedLocal
class Quench(ptype):
"""
This is a toy problem to emulate a magnet that has been cooled to temperatures where superconductivity is possible.
However, there is a leak! Some point in the domain is constantly heated and when this has heated up its environment
sufficiently, there will be a runaway effect heating up the entire magnet.
This effect has actually lead to huge magnets being destroyed at CERN in the past and hence warrants investigation.
The model we use is a 1d heat equation with Neumann-zero boundary conditions, meaning this magnet is totally
insulated from its environment except for the leak.
We add a non-linear term that heats parts of the domain that exceed a certain temperature threshold as well as the
leak itself.
"""
dtype_u = mesh
dtype_f = mesh
def __init__(
self,
Cv=1000.0,
K=1000.0,
u_thresh=1e-2,
u_max=2e-2,
Q_max=1.0,
leak_range=(0.45, 0.55),
leak_type='linear',
leak_transition='step',
order=2,
stencil_type='center',
bc='neumann-zero',
nvars=2**7,
newton_tol=1e-8,
newton_iter=99,
lintol=1e-8,
liniter=99,
direct_solver=True,
reference_sol_type='scipy',
):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: mesh data type (will be passed parent class)
dtype_f: mesh data type (will be passed parent class)
"""
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__(init=(nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'Cv',
'K',
'u_thresh',
'u_max',
'Q_max',
'leak_range',
'leak_type',
'leak_transition',
'order',
'stencil_type',
'bc',
'nvars',
'newton_tol',
'newton_iter',
'lintol',
'liniter',
'direct_solver',
'reference_sol_type',
localVars=locals(),
readOnly=True,
)
# compute dx (equal in both dimensions) and get discretization matrix A
if self.bc == 'periodic':
self.dx = 1.0 / self.nvars
xvalues = np.array([i * self.dx for i in range(self.nvars)])
elif self.bc == 'dirichlet-zero':
self.dx = 1.0 / (self.nvars + 1)
xvalues = np.array([(i + 1) * self.dx for i in range(self.nvars)])
elif self.bc == 'neumann-zero':
self.dx = 1.0 / (self.nvars - 1)
xvalues = np.array([i * self.dx for i in range(self.nvars)])
else:
raise ProblemError(f'Boundary conditions {self.bc} not implemented.')
self.A = problem_helper.get_finite_difference_matrix(
derivative=2,
order=self.order,
stencil_type=self.stencil_type,
dx=self.dx,
size=self.nvars,
dim=1,
bc=self.bc,
)
self.A *= self.K / self.Cv
self.xv = xvalues
self.Id = sp.eye(np.prod(self.nvars), format='csc')
self.leak = np.logical_and(self.xv > self.leak_range[0], self.xv < self.leak_range[1])
self.work_counters['newton'] = WorkCounter()
self.work_counters['rhs'] = WorkCounter()
if not self.direct_solver:
self.work_counters['linear'] = WorkCounter()
def eval_f_non_linear(self, u, t):
"""
Get the non-linear part of f
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_u: the non-linear part of the RHS
"""
u_thresh = self.u_thresh
u_max = self.u_max
Q_max = self.Q_max
me = self.dtype_u(self.init)
if self.leak_type == 'linear':
me[:] = (u - u_thresh) / (u_max - u_thresh) * Q_max
elif self.leak_type == 'exponential':
me[:] = Q_max * (np.exp(u) - np.exp(u_thresh)) / (np.exp(u_max) - np.exp(u_thresh))
else:
raise NotImplementedError(f'Leak type \"{self.leak_type}\" not implemented!')
me[u < u_thresh] = 0
if self.leak_transition == 'step':
me[self.leak] = Q_max
elif self.leak_transition == 'Gaussian':
me[:] = np.max([me, Q_max * np.exp(-((self.xv - 0.5) ** 2) / 3e-2)], axis=0)
else:
raise NotImplementedError(f'Leak transition \"{self.leak_transition}\" not implemented!')
me[u >= u_max] = Q_max
me[:] /= self.Cv
return me
def eval_f(self, u, t):
"""
Evaluate the full right hand side.
Args:
u (dtype_u): Current solution
t (float): Current time
Returns:
dtype_f: The right hand side
"""
f = self.dtype_f(self.init)
f[:] = self.A.dot(u.flatten()).reshape(self.nvars) + self.eval_f_non_linear(u, t)
self.work_counters['rhs']()
return f
def get_non_linear_Jacobian(self, u):
"""
Evaluate the non-linear part of the Jacobian only
Args:
u (dtype_u): Current solution
Returns:
scipy.sparse.csc: The derivative of the non-linear part of the solution w.r.t. to the solution.
"""
u_thresh = self.u_thresh
u_max = self.u_max
Q_max = self.Q_max
me = self.dtype_u(self.init)
if self.leak_type == 'linear':
me[:] = Q_max / (u_max - u_thresh)
elif self.leak_type == 'exponential':
me[:] = Q_max * np.exp(u) / (np.exp(u_max) - np.exp(u_thresh))
else:
raise NotImplementedError(f'Leak type {self.leak_type} not implemented!')
me[u < u_thresh] = 0
if self.leak_transition == 'step':
me[self.leak] = 0
elif self.leak_transition == 'Gaussian':
me[self.leak] = 0
me[self.leak][u[self.leak] > Q_max * np.exp(-((self.xv[self.leak] - 0.5) ** 2) / 3e-2)] = 1
else:
raise NotImplementedError(f'Leak transition \"{self.leak_transition}\" not implemented!')
me[u > u_max] = 0
me[:] /= self.Cv
return sp.diags(me, format='csc')
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver for (I-factor*f)(u) = rhs
Args:
rhs (dtype_f): right-hand side
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
u = self.dtype_u(u0)
res = np.inf
delta = np.zeros_like(u)
# construct a preconditioner for the space solver
if not self.direct_solver:
M = inv(self.Id - factor * self.A)
for n in range(0, self.newton_iter):
# assemble G such that G(u) = 0 at the solution of the step
G = u - factor * self.eval_f(u, t) - rhs
self.work_counters[
'rhs'
].niter -= (
1 # Work regarding construction of the Jacobian etc. should count into the Newton iterations only
)
res = np.linalg.norm(G, np.inf)
if res <= self.newton_tol and n > 0: # we want to make at least one Newton iteration
break
# assemble Jacobian J of G
J = self.Id - factor * (self.A + self.get_non_linear_Jacobian(u))
# solve the linear system
if self.direct_solver:
delta = spsolve(J, G)
else:
delta, info = gmres(
J,
G,
x0=delta,
M=M,
tol=self.lintol,
maxiter=self.liniter,
atol=0,
callback=self.work_counters['linear'],
)
if not np.isfinite(delta).all():
break
# update solution
u = u - delta
self.work_counters['newton']()
return u
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
Returns:
dtype_u: exact solution
"""
me = self.dtype_u(self.init, val=0.0)
if t > 0:
if self.reference_sol_type == 'scipy':
def jac(t, u):
"""
Get the Jacobian for the implicit BDF method to use in `scipy.solve_ivp`
Args:
t (float): The current time
u (dtype_u): Current solution
Returns:
scipy.sparse.csc: The derivative of the non-linear part of the solution w.r.t. to the solution.
"""
return self.A + self.get_non_linear_Jacobian(u)
def eval_rhs(t, u):
"""
Function to pass to `scipy.solve_ivp` to evaluate the full RHS
Args:
t (float): Current time
u (numpy.1darray): Current solution
Returns:
(numpy.1darray): RHS
"""
return self.eval_f(u.reshape(self.init[0]), t).flatten()
me[:] = self.generate_scipy_reference_solution(eval_rhs, t, u_init, t_init, method='BDF', jac=jac)
elif self.reference_sol_type in ['DIRK', 'SDC']:
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.hooks.log_solution import LogSolution
from pySDC.helpers.stats_helper import get_sorted
description = {}
description['problem_class'] = Quench
description['problem_params'] = {
'newton_tol': 1e-10,
'newton_iter': 99,
'nvars': 2**10,
**self.params,
}
if self.reference_sol_type == 'DIRK':
from pySDC.implementations.sweeper_classes.Runge_Kutta import DIRK43
from pySDC.implementations.convergence_controller_classes.adaptivity import AdaptivityRK
description['sweeper_class'] = DIRK43
description['sweeper_params'] = {}
description['step_params'] = {'maxiter': 1}
description['level_params'] = {'dt': 1e-4}
description['convergence_controllers'] = {AdaptivityRK: {'e_tol': 1e-9, 'update_order': 4}}
elif self.reference_sol_type == 'SDC':
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
description['sweeper_class'] = generic_implicit
description['sweeper_params'] = {'num_nodes': 3, 'QI': 'IE', 'quad_type': 'RADAU-RIGHT'}
description['step_params'] = {'maxiter': 99}
description['level_params'] = {'dt': 0.5, 'restol': 1e-10}
controller_params = {'hook_class': LogSolution, 'mssdc_jac': False, 'logger_level': 99}
controller = controller_nonMPI(
description=description, controller_params=controller_params, num_procs=1
)
uend, stats = controller.run(
u0=u_init if u_init is not None else self.u_exact(t=0.0),
t0=t_init if t_init is not None else 0,
Tend=t,
)
u_last = get_sorted(stats, type='u', recomputed=False)[-1]
if abs(u_last[0] - t) > 1e-2:
self.logger.warning(
f'Time difference between reference solution and requested time is {abs(u_last[0]-t):.2e}!'
)
me[:] = u_last[1]
return me
class QuenchIMEX(Quench):
dtype_f = imex_mesh
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)
f.impl[:] = self.A.dot(u.flatten()).reshape(self.nvars)
f.expl[:] = self.eval_f_non_linear(u, t)
self.work_counters['rhs']()
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*f_expl)(u) = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(self.init)
me[:] = spsolve(self.Id - factor * self.A, rhs.flatten()).reshape(self.nvars)
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
Returns:
dtype_u: exact solution
"""
me = self.dtype_u(self.init, val=0.0)
if t == 0:
me[:] = super().u_exact(t, u_init, t_init)
if t > 0:
def jac(t, u):
"""
Get the Jacobian for the implicit BDF method to use in `scipy.solve_ivp`
Args:
t (float): The current time
u (dtype_u): Current solution
Returns:
scipy.sparse.csc: The derivative of the non-linear part of the solution w.r.t. to the solution.
"""
return self.A
def eval_rhs(t, u):
"""
Function to pass to `scipy.solve_ivp` to evaluate the full RHS
Args:
t (float): Current time
u (numpy.1darray): Current solution
Returns:
(numpy.1darray): RHS
"""
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, method='BDF', jac=jac)
return me
| 15,280 | 32.882483 | 119 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/HeatEquation_ND_FD_CuPy.py | import numpy as np
import cupy as cp
import cupyx.scipy.sparse as csp
from cupyx.scipy.sparse.linalg import spsolve, cg # , gmres, minres
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.helpers import problem_helper
from pySDC.implementations.datatype_classes.cupy_mesh import cupy_mesh, imex_cupy_mesh
class heatNd_forced(ptype): # pragma: no cover
"""
Example implementing the ND heat equation with periodic or Diriclet-Zero BCs in [0,1]^N,
discretized using central finite differences
Attributes:
A: FD discretization of the ND laplace operator
dx: distance between two spatial nodes (here: being the same in all dimensions)
"""
dtype_u = cupy_mesh
dtype_f = imex_cupy_mesh
def __init__(
self, nvars, nu, freq, bc, order=2, stencil_type='center', lintol=1e-12, liniter=10000, solver_type='direct'
):
"""Initialization routine"""
# make sure parameters have the correct types
if not type(nvars) in [int, tuple]:
raise ProblemError('nvars should be either tuple or int')
if not type(freq) in [int, tuple]:
raise ProblemError('freq should be either tuple or int')
# transforms nvars into a tuple
if type(nvars) is int:
nvars = (nvars,)
# automatically determine ndim from nvars
ndim = len(nvars)
if ndim > 3:
raise ProblemError(f'can work with up to three dimensions, got {ndim}')
# eventually extend freq to other dimension
if type(freq) is int:
freq = (freq,) * ndim
if len(freq) != ndim:
raise ProblemError(f'len(freq)={len(freq)}, different to ndim={ndim}')
# check values for freq and nvars
for f in freq:
if ndim == 1 and f == -1:
# use Gaussian initial solution in 1D
bc = 'periodic'
break
if f % 2 != 0 and bc == 'periodic':
raise ProblemError('need even number of frequencies due to periodic BCs')
for nvar in nvars:
if nvar % 2 != 0 and bc == 'periodic':
raise ProblemError('the setup requires nvars = 2^p per dimension')
if (nvar + 1) % 2 != 0 and bc == 'dirichlet-zero':
raise ProblemError('setup requires nvars = 2^p - 1')
if ndim > 1 and nvars[1:] != nvars[:-1]:
raise ProblemError('need a square domain, got %s' % nvars)
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__(init=(nvars[0] if ndim == 1 else nvars, None, cp.dtype('float64')))
self._makeAttributeAndRegister(
'nvars',
'nu',
'freq',
'bc',
'order',
'stencil_type',
'lintol',
'liniter',
'solver_type',
localVars=locals(),
readOnly=True,
)
# compute dx (equal in both dimensions) and get discretization matrix A
if self.bc == 'periodic':
self.dx = 1.0 / self.nvars[0]
xvalues = cp.array([i * self.dx for i in range(self.nvars[0])])
elif self.bc == 'dirichlet-zero':
self.dx = 1.0 / (self.nvars[0] + 1)
xvalues = cp.array([(i + 1) * self.dx for i in range(self.nvars[0])])
else:
raise ProblemError(f'Boundary conditions {self.bc} not implemented.')
self.A = problem_helper.get_finite_difference_matrix(
derivative=2,
order=self.order,
stencil_type=self.stencil_type,
dx=self.dx,
size=self.nvars[0],
dim=self.ndim,
bc=self.bc,
cupy=True,
)
self.A *= self.nu
self.xv = cp.meshgrid(*[xvalues for _ in range(self.ndim)])
self.Id = csp.eye(np.prod(self.nvars), format='csc')
@property
def ndim(self):
"""Number of dimensions of the spatial problem"""
return len(self.nvars)
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)
f.impl[:] = self.A.dot(u.flatten()).reshape(self.nvars)
if self.ndim == 1:
f.expl[:] = cp.sin(np.pi * self.freq[0] * self.xv[0]) * (
self.nu * np.pi**2 * sum([freq**2 for freq in self.freq]) * cp.cos(t) - cp.sin(t)
)
elif self.ndim == 2:
f.expl[:] = (
cp.sin(np.pi * self.freq[0] * self.xv[0])
* cp.sin(np.pi * self.freq[1] * self.xv[1])
* (self.nu * np.pi**2 * sum([freq**2 for freq in self.freq]) * cp.cos(t) - cp.sin(t))
)
elif self.ndim == 3:
f.expl[:] = (
cp.sin(np.pi * self.freq[0] * self.xv[0])
* cp.sin(np.pi * self.freq[1] * self.xv[1])
* cp.sin(np.pi * self.freq[2] * self.xv[2])
* (self.nu * np.pi**2 * sum([freq**2 for freq in self.freq]) * cp.cos(t) - cp.sin(t))
)
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(self.init)
if self.solver_type == 'direct':
me[:] = spsolve(self.Id - factor * self.A, rhs.flatten()).reshape(self.nvars)
elif self.solver_type == 'CG':
me[:] = cg(
self.Id - factor * self.A,
rhs.flatten(),
x0=u0.flatten(),
tol=self.lintol,
maxiter=self.liniter,
atol=0,
)[0].reshape(self.nvars)
else:
raise NotImplementedError(f'Solver {self.solver_type} not implemented in GPU heat equation!')
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
me = self.dtype_u(self.init)
if self.ndim == 1:
me[:] = cp.sin(np.pi * self.freq[0] * self.xv[0]) * cp.cos(t)
elif self.ndim == 2:
me[:] = cp.sin(np.pi * self.freq[0] * self.xv[0]) * cp.sin(np.pi * self.freq[1] * self.xv[1]) * cp.cos(t)
elif self.ndim == 3:
me[:] = (
cp.sin(np.pi * self.freq[0] * self.xv[0])
* cp.sin(np.pi * self.freq[1] * self.xv[1])
* cp.sin(np.pi * self.freq[2] * self.xv[2])
* cp.cos(t)
)
return me
class heatNd_unforced(heatNd_forced):
dtype_f = cupy_mesh
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)
f[:] = self.A.dot(u.flatten()).reshape(self.nvars)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
me = self.dtype_u(self.init)
if self.ndim == 1:
rho = (2.0 - 2.0 * cp.cos(np.pi * self.freq[0] * self.dx)) / self.dx**2
me[:] = cp.sin(np.pi * self.freq[0] * self.xv[0]) * cp.exp(-t * self.nu * rho)
elif self.ndim == 2:
rho = (2.0 - 2.0 * cp.cos(np.pi * self.freq[0] * self.dx)) / self.dx**2 + (
2.0 - 2.0 * cp.cos(np.pi * self.freq[1] * self.dx)
) / self.dx**2
me[:] = (
cp.sin(np.pi * self.freq[0] * self.xv[0])
* cp.sin(np.pi * self.freq[1] * self.xv[1])
* cp.exp(-t * self.nu * rho)
)
elif self.ndim == 3:
rho = (
(2.0 - 2.0 * cp.cos(np.pi * self.freq[0] * self.dx)) / self.dx**2
+ (2.0 - 2.0 * cp.cos(np.pi * self.freq[1] * self.dx))
+ (2.0 - 2.0 * cp.cos(np.pi * self.freq[2] * self.dx)) / self.dx**2
)
me[:] = (
cp.sin(np.pi * self.freq[0] * self.xv[0])
* cp.sin(np.pi * self.freq[1] * self.xv[1])
* cp.sin(np.pi * self.freq[2] * self.xv[2])
* cp.exp(-t * self.nu * rho)
)
return me
| 8,987 | 32.916981 | 117 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/Van_der_Pol_implicit.py | import numpy as np
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype, WorkCounter
from pySDC.implementations.datatype_classes.mesh import mesh
# noinspection PyUnusedLocal
class vanderpol(ptype):
"""
Example implementing the van der pol oscillator
TODO : doku
"""
dtype_u = mesh
dtype_f = mesh
def __init__(self, u0, mu, newton_maxiter, newton_tol, stop_at_nan=True, crash_at_maxiter=True):
"""
Initialization routine
"""
nvars = 2
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister('nvars', 'u0', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister(
'mu', 'newton_maxiter', 'newton_tol', 'stop_at_nan', 'crash_at_maxiter', localVars=locals()
)
self.work_counters['newton'] = WorkCounter()
self.work_counters['rhs'] = WorkCounter()
def u_exact(self, t, u_init=None, t_init=None):
"""
Routine to approximate the exact solution at time t by scipy or give initial conditions when called at t=0
Args:
t (float): current time
u_init (pySDC.problem.vanderpol.dtype_u): initial conditions for getting the exact solution
t_init (float): the starting time
Returns:
dtype_u: approximate exact solution
"""
me = self.dtype_u(self.init)
if t > 0.0:
def eval_rhs(t, u):
return self.eval_f(u, t)
me[:] = self.generate_scipy_reference_solution(eval_rhs, t, u_init, t_init)
else:
me[:] = self.u0
return me
def eval_f(self, u, t):
"""
Routine to compute the RHS for both components simultaneously
Args:
u (dtype_u): the current values
t (float): current time (not used here)
Returns:
dtype_f: RHS, 2 components
"""
x1 = u[0]
x2 = u[1]
f = self.f_init
f[0] = x2
f[1] = self.mu * (1 - x1**2) * x2 - x1
self.work_counters['rhs']()
return f
def solve_system(self, rhs, dt, u0, t):
"""
Simple Newton solver for the nonlinear system
Args:
rhs (dtype_f): right-hand side for the nonlinear system
dt (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution u
"""
mu = self.mu
# create new mesh object from u0 and set initial values for iteration
u = self.dtype_u(u0)
x1 = u[0]
x2 = u[1]
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = np.array([x1 - dt * x2 - rhs[0], x2 - dt * (mu * (1 - x1**2) * x2 - x1) - rhs[1]])
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol or np.isnan(res):
break
# prefactor for dg/du
c = 1.0 / (-2 * dt**2 * mu * x1 * x2 - dt**2 - 1 + dt * mu * (1 - x1**2))
# assemble dg/du
dg = c * np.array([[dt * mu * (1 - x1**2) - 1, -dt], [2 * dt * mu * x1 * x2 + dt, -1]])
# newton update: u1 = u0 - g/dg
u -= np.dot(dg, g)
# set new values and increase iteration count
x1 = u[0]
x2 = u[1]
n += 1
self.work_counters['newton']()
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter and self.crash_at_maxiter:
raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
return u
| 4,129 | 30.287879 | 114 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AllenCahn_1D_FD.py | import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import spsolve
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.helpers import problem_helper
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh, comp2_mesh
class allencahn_front_fullyimplicit(ptype):
"""
Example implementing the Allen-Cahn equation in 1D with finite differences and inhomogeneous Dirichlet-BC,
with driving force, 0-1 formulation (Bayreuth example)
Attributes:
A: second-order FD discretization of the 1D laplace operator
dx: distance between two spatial nodes
"""
dtype_u = mesh
dtype_f = mesh
def __init__(self, nvars, dw, eps, newton_maxiter, newton_tol, interval, stop_at_nan=True):
# we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on
if (nvars + 1) % 2 != 0:
raise ProblemError('setup requires nvars = 2^p - 1')
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'nvars',
'dw',
'eps',
'newton_maxiter',
'newton_tol',
'interval',
'stop_at_nan',
localVars=locals(),
readOnly=True,
)
# compute dx and get discretization matrix A
self.dx = (self.interval[1] - self.interval[0]) / (self.nvars + 1)
self.xvalues = np.array([(i + 1 - (self.nvars + 1) / 2) * self.dx for i in range(self.nvars)])
self.A = problem_helper.get_finite_difference_matrix(
derivative=2,
order=2,
type='center',
dx=self.dx,
size=self.nvars + 2,
dim=1,
bc='dirichlet-zero',
)
self.uext = self.dtype_u((self.init[0] + 2, self.init[1], self.init[2]), val=0.0)
self.newton_itercount = 0
self.lin_itercount = 0
self.newton_ncalls = 0
self.lin_ncalls = 0
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0)
eps2 = self.eps**2
dw = self.dw
Id = sp.eye(self.nvars)
v = 3.0 * np.sqrt(2) * self.eps * self.dw
self.uext[0] = 0.5 * (1 + np.tanh((self.interval[0] - v * t) / (np.sqrt(2) * self.eps)))
self.uext[-1] = 0.5 * (1 + np.tanh((self.interval[1] - v * t) / (np.sqrt(2) * self.eps)))
A = self.A[1:-1, 1:-1]
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# print(n)
# form the function g with g(u) = 0
self.uext[1:-1] = u[:]
g = (
u
- rhs
- factor
* (
self.A.dot(self.uext)[1:-1]
- 2.0 / eps2 * u * (1.0 - u) * (1.0 - 2.0 * u)
- 6.0 * dw * u * (1.0 - u)
)
)
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (
A
- 2.0
/ eps2
* sp.diags((1.0 - u) * (1.0 - 2.0 * u) - u * ((1.0 - 2.0 * u) + 2.0 * (1.0 - u)), offsets=0)
- 6.0 * dw * sp.diags((1.0 - u) - u, offsets=0)
)
# newton update: u1 = u0 - g/dg
u -= spsolve(dg, g)
# u -= gmres(dg, g, x0=z, tol=self.lin_tol)[0]
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
self.logger.warning('Newton did not converge after %i iterations, error is %s' % (n, res))
self.newton_ncalls += 1
self.newton_itercount += n
me = self.dtype_u(self.init)
me[:] = u[:]
return me
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
"""
# set up boundary values to embed inner points
v = 3.0 * np.sqrt(2) * self.eps * self.dw
self.uext[0] = 0.5 * (1 + np.tanh((self.interval[0] - v * t) / (np.sqrt(2) * self.eps)))
self.uext[-1] = 0.5 * (1 + np.tanh((self.interval[1] - v * t) / (np.sqrt(2) * self.eps)))
self.uext[1:-1] = u[:]
f = self.dtype_f(self.init)
f[:] = (
self.A.dot(self.uext)[1:-1]
- 2.0 / self.eps**2 * u * (1.0 - u) * (1.0 - 2 * u)
- 6.0 * self.dw * u * (1.0 - u)
)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
v = 3.0 * np.sqrt(2) * self.eps * self.dw
me = self.dtype_u(self.init, val=0.0)
me[:] = 0.5 * (1 + np.tanh((self.xvalues - v * t) / (np.sqrt(2) * self.eps)))
return me
class allencahn_front_semiimplicit(allencahn_front_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 1D with finite differences and inhomogeneous Dirichlet-BC,
with driving force, 0-1 formulation (Bayreuth example), semi-implicit time-stepping
Attributes:
A: second-order FD discretization of the 1D laplace operator
dx: distance between two spatial nodes
"""
dtype_f = imex_mesh
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
"""
# set up boundary values to embed inner points
v = 3.0 * np.sqrt(2) * self.eps * self.dw
self.uext[0] = 0.5 * (1 + np.tanh((self.interval[0] - v * t) / (np.sqrt(2) * self.eps)))
self.uext[-1] = 0.5 * (1 + np.tanh((self.interval[1] - v * t) / (np.sqrt(2) * self.eps)))
self.uext[1:-1] = u[:]
f = self.dtype_f(self.init)
f.impl[:] = self.A.dot(self.uext)[1:-1]
f.expl[:] = -2.0 / self.eps**2 * u * (1.0 - u) * (1.0 - 2 * u) - 6.0 * self.dw * u * (1.0 - u)
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(self.init)
self.uext[0] = 0.0
self.uext[-1] = 0.0
self.uext[1:-1] = rhs[:]
me[:] = spsolve(sp.eye(self.nvars + 2, format='csc') - factor * self.A, self.uext)[1:-1]
return me
class allencahn_front_finel(allencahn_front_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 1D with finite differences and inhomogeneous Dirichlet-BC,
with driving force, 0-1 formulation (Bayreuth example), Finel's trick/parametrization
"""
# noinspection PyTypeChecker
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0)
dw = self.dw
a2 = np.tanh(self.dx / (np.sqrt(2) * self.eps)) ** 2
Id = sp.eye(self.nvars)
v = 3.0 * np.sqrt(2) * self.eps * self.dw
self.uext[0] = 0.5 * (1 + np.tanh((self.interval[0] - v * t) / (np.sqrt(2) * self.eps)))
self.uext[-1] = 0.5 * (1 + np.tanh((self.interval[1] - v * t) / (np.sqrt(2) * self.eps)))
A = self.A[1:-1, 1:-1]
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# print(n)
# form the function g with g(u) = 0
self.uext[1:-1] = u[:]
gprim = 1.0 / self.dx**2 * ((1.0 - a2) / (1.0 - a2 * (2.0 * u - 1.0) ** 2) - 1.0) * (2.0 * u - 1.0)
g = u - rhs - factor * (self.A.dot(self.uext)[1:-1] - 1.0 * gprim - 6.0 * dw * u * (1.0 - u))
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dgprim = (
1.0
/ self.dx**2
* (
2.0 * ((1.0 - a2) / (1.0 - a2 * (2.0 * u - 1.0) ** 2) - 1.0)
+ (2.0 * u - 1) ** 2 * (1.0 - a2) * 4 * a2 / (1.0 - a2 * (2.0 * u - 1.0) ** 2) ** 2
)
)
dg = Id - factor * (A - 1.0 * sp.diags(dgprim, offsets=0) - 6.0 * dw * sp.diags((1.0 - u) - u, offsets=0))
# newton update: u1 = u0 - g/dg
u -= spsolve(dg, g)
# For some reason, doing cg or gmres does not work so well here...
# u -= cg(dg, g, x0=z, tol=self.lin_tol)[0]
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
self.logger.warning('Newton did not converge after %i iterations, error is %s' % (n, res))
self.newton_ncalls += 1
self.newton_itercount += n
me = self.dtype_u(self.init)
me[:] = u[:]
return me
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
"""
# set up boundary values to embed inner points
v = 3.0 * np.sqrt(2) * self.eps * self.dw
self.uext[0] = 0.5 * (1 + np.tanh((self.interval[0] - v * t) / (np.sqrt(2) * self.eps)))
self.uext[-1] = 0.5 * (1 + np.tanh((self.interval[1] - v * t) / (np.sqrt(2) * self.eps)))
self.uext[1:-1] = u[:]
a2 = np.tanh(self.dx / (np.sqrt(2) * self.eps)) ** 2
gprim = 1.0 / self.dx**2 * ((1.0 - a2) / (1.0 - a2 * (2.0 * u - 1.0) ** 2) - 1) * (2.0 * u - 1.0)
f = self.dtype_f(self.init)
f[:] = self.A.dot(self.uext)[1:-1] - 1.0 * gprim - 6.0 * self.dw * u * (1.0 - u)
return f
class allencahn_periodic_fullyimplicit(ptype):
"""
Example implementing the Allen-Cahn equation in 1D with finite differences and periodic BC,
with driving force, 0-1 formulation (Bayreuth example)
Attributes:
A: second-order FD discretization of the 1D laplace operator
dx: distance between two spatial nodes
"""
dtype_u = mesh
dtype_f = mesh
def __init__(self, nvars, dw, eps, newton_maxiter, newton_tol, interval, radius, stop_at_nan=True):
# we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on
if (nvars) % 2 != 0:
raise ProblemError('setup requires nvars = 2^p')
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'nvars',
'dw',
'eps',
'newton_maxiter',
'newton_tol',
'interval',
'radius',
'stop_at_nan',
localVars=locals(),
readOnly=True,
)
# compute dx and get discretization matrix A
self.dx = (self.interval[1] - self.interval[0]) / self.nvars
self.xvalues = np.array([self.interval[0] + i * self.dx for i in range(self.nvars)])
self.A = problem_helper.get_finite_difference_matrix(
derivative=2,
order=2,
type='center',
dx=self.dx,
size=self.nvars,
dim=1,
bc='periodic',
)
self.newton_itercount = 0
self.lin_itercount = 0
self.newton_ncalls = 0
self.lin_ncalls = 0
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0)
eps2 = self.eps**2
dw = self.dw
Id = sp.eye(self.nvars)
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# print(n)
# form the function g with g(u) = 0
g = (
u
- rhs
- factor * (self.A.dot(u) - 2.0 / eps2 * u * (1.0 - u) * (1.0 - 2.0 * u) - 6.0 * dw * u * (1.0 - u))
)
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (
self.A
- 2.0
/ eps2
* sp.diags((1.0 - u) * (1.0 - 2.0 * u) - u * ((1.0 - 2.0 * u) + 2.0 * (1.0 - u)), offsets=0)
- 6.0 * dw * sp.diags((1.0 - u) - u, offsets=0)
)
# newton update: u1 = u0 - g/dg
u -= spsolve(dg, g)
# u -= gmres(dg, g, x0=z, tol=self.lin_tol)[0]
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
self.logger.warning('Newton did not converge after %i iterations, error is %s' % (n, res))
self.newton_ncalls += 1
self.newton_itercount += n
me = self.dtype_u(self.init)
me[:] = u[:]
return me
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)
f[:] = self.A.dot(u) - 2.0 / self.eps**2 * u * (1.0 - u) * (1.0 - 2 * u) - 6.0 * self.dw * u * (1.0 - u)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
v = 3.0 * np.sqrt(2) * self.eps * self.dw
me = self.dtype_u(self.init, val=0.0)
me[:] = 0.5 * (1 + np.tanh((self.radius - abs(self.xvalues) - v * t) / (np.sqrt(2) * self.eps)))
return me
class allencahn_periodic_semiimplicit(allencahn_periodic_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 1D with finite differences and periodic BC,
with driving force, 0-1 formulation (Bayreuth example)
"""
dtype_f = imex_mesh
def __init__(self, nvars, dw, eps, newton_maxiter, newton_tol, interval, radius, stop_at_nan=True):
super().__init__(nvars, dw, eps, newton_maxiter, newton_tol, interval, radius, stop_at_nan)
self.A -= sp.eye(self.init) * 0.0 / self.eps**2
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(u0)
me[:] = spsolve(sp.eye(self.nvars, format='csc') - factor * self.A, rhs)
return me
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)
f.impl[:] = self.A.dot(u)
f.expl[:] = (
-2.0 / self.eps**2 * u * (1.0 - u) * (1.0 - 2.0 * u)
- 6.0 * self.dw * u * (1.0 - u)
+ 0.0 / self.eps**2 * u
)
return f
class allencahn_periodic_multiimplicit(allencahn_periodic_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 1D with finite differences and periodic BC,
with driving force, 0-1 formulation (Bayreuth example)
"""
dtype_f = comp2_mesh
def __init__(self, nvars, dw, eps, newton_maxiter, newton_tol, interval, radius, stop_at_nan=True):
super().__init__(nvars, dw, eps, newton_maxiter, newton_tol, interval, radius, stop_at_nan)
self.A -= sp.eye(self.init) * 0.0 / self.eps**2
def solve_system_1(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(u0)
me[:] = spsolve(sp.eye(self.nvars, format='csc') - factor * self.A, rhs)
return me
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)
f.comp1[:] = self.A.dot(u)
f.comp2[:] = (
-2.0 / self.eps**2 * u * (1.0 - u) * (1.0 - 2.0 * u)
- 6.0 * self.dw * u * (1.0 - u)
+ 0.0 / self.eps**2 * u
)
return f
def solve_system_2(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
u = self.dtype_u(u0)
eps2 = self.eps**2
dw = self.dw
Id = sp.eye(self.nvars)
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# print(n)
# form the function g with g(u) = 0
g = (
u
- rhs
- factor
* (-2.0 / eps2 * u * (1.0 - u) * (1.0 - 2.0 * u) - 6.0 * dw * u * (1.0 - u) + 0.0 / self.eps**2 * u)
)
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (
-2.0 / eps2 * sp.diags((1.0 - u) * (1.0 - 2.0 * u) - u * ((1.0 - 2.0 * u) + 2.0 * (1.0 - u)), offsets=0)
- 6.0 * dw * sp.diags((1.0 - u) - u, offsets=0)
+ 0.0 / self.eps**2 * Id
)
# newton update: u1 = u0 - g/dg
u -= spsolve(dg, g)
# u -= gmres(dg, g, x0=z, tol=self.lin_tol)[0]
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
self.logger.warning('Newton did not converge after %i iterations, error is %s' % (n, res))
self.newton_ncalls += 1
self.newton_itercount += n
me = self.dtype_u(self.init)
me[:] = u[:]
return me
| 21,804 | 31.447917 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/Piline.py | import numpy as np
from scipy.integrate import solve_ivp
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
# noinspection PyUnusedLocal
class piline(ptype):
r"""
Example implementing the model of the piline. It serves as a transmission line in an energy grid. The problem of simulating the
piline consists of three ordinary differential equations (ODEs) with nonhomogeneous part:
.. math::
\frac{d v_{C_1} (t)}{dt} = -\frac{1}{R_s C_1}v_{C_1} (t) - \frac{1}{C_1} i_{L_\pi} (t) + \frac{V_s}{R_s C_1},
.. math::
\frac{d v_{C_2} (t)}{dt} = -\frac{1}{R_\ell C_2}v_{C_2} (t) + \frac{1}{C_2} i_{L_\pi} (t),
.. math::
\frac{d i_{L_\pi} (t)}{dt} = \frac{1}{L_\pi} v_{C_1} (t) - \frac{1}{L_\pi} v_{C_2} (t) - \frac{R_\pi}{L_\pi} i_{L_\pi} (t),
which can be expressed as a nonhomogeneous linear system of ODEs
.. math::
\frac{d u(t)}{dt} = A u(t) + f(t)
using an initial condition.
Parameters
----------
Vs : float
Voltage at the voltage source :math:`V_s`.
Rs : float
Resistance of the resistor :math:`R_s` at the voltage source.
C1 : float
Capacitance of the capacitor :math:`C_1`.
Rpi : float
Resistance of the resistor :math:`R_\pi`.
Lpi : float
Inductance of the inductor :math:`L_\pi`.
C2 : float
Capacitance of the capacitor :math:`C_2`.
Rl : float
Resistance of the resistive load :math:`R_\ell`.
Attributes:
A: system matrix, representing the 3 ODEs
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, Vs=100.0, Rs=1.0, C1=1.0, Rpi=0.2, Lpi=1.0, C2=1.0, Rl=5.0):
"""Initialization routine"""
nvars = 3
# invoke super init, passing number of dofs
super().__init__(init=(nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'nvars', 'Vs', 'Rs', 'C1', 'Rpi', 'Lpi', 'C2', 'Rl', localVars=locals(), readOnly=True
)
# compute dx and get discretization matrix A
self.A = np.zeros((3, 3))
self.A[0, 0] = -1 / (self.Rs * self.C1)
self.A[0, 2] = -1 / self.C1
self.A[1, 1] = -1 / (self.Rl * self.C2)
self.A[1, 2] = 1 / self.C2
self.A[2, 0] = 1 / self.Lpi
self.A[2, 1] = -1 / self.Lpi
self.A[2, 2] = -self.Rpi / self.Lpi
def eval_f(self, u, t):
"""
Routine to evaluate the right-hand side of the problem.
Parameters
----------
u : dtype_u
Current values of the numerical solution.
t : float
Current time of the numerical solution is computed.
Returns
-------
f : dtype_f
The right-hand side of the problem.
"""
f = self.dtype_f(self.init, val=0.0)
f.impl[:] = self.A.dot(u)
f.expl[0] = self.Vs / (self.Rs * self.C1)
return f
def solve_system(self, rhs, factor, u0, t):
r"""
Simple linear solver for :math:`(I-factor\cdot A)\vec{u}=\vec{rhs}`.
Parameters
----------
rhs : dtype_f
Right-hand side for the linear system.
factor : float
Abbrev. for the local stepsize (or any other factor required).
u0 : dtype_u
Initial guess for the iterative solver.
t : float
Current time (e.g. for time-dependent BCs).
Returns
-------
me : dtype_u
The solution as mesh.
"""
me = self.dtype_u(self.init)
me[:] = np.linalg.solve(np.eye(self.nvars) - factor * self.A, rhs)
return me
def u_exact(self, t, u_init=None, t_init=None):
"""
Routine to approximate the exact solution at time t by scipy as a reference.
Parameters
----------
t : float
Time of the exact solution.
u_init : pySDC.problem.Piline.dtype_u
Initial conditions for getting the exact solution.
t_init : float
The starting time.
Returns
-------
me : dtype_u
The reference solution.
"""
me = self.dtype_u(self.init)
# fill initial conditions
me[0] = 0.0 # v1
me[1] = 0.0 # v2
me[2] = 0.0 # p3
if t > 0.0:
if u_init is not None:
if t_init is None:
raise ValueError(
'Please supply `t_init` when you want to get the exact solution from a point that \
is not 0!'
)
me = u_init
else:
t_init = 0.0
def rhs(t, u):
f = self.eval_f(u, t)
return f.impl + f.expl # evaluate only explicitly rather than IMEX
tol = 100 * np.finfo(float).eps
me[:] = solve_ivp(rhs, (t_init, t), me, rtol=tol, atol=tol).y[:, -1]
return me
| 5,014 | 29.02994 | 131 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/HeatEquation_2D_PETSc_forced.py | import numpy as np
from petsc4py import PETSc
from pySDC.core.Errors import ParameterError, ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.petsc_vec import petsc_vec, petsc_vec_imex
# noinspection PyUnusedLocal
class heat2d_petsc_forced(ptype):
"""
Example implementing the forced 2D heat equation with Dirichlet BCs in [0,1]^2,
discretized using central finite differences and realized with PETSc
Attributes:
A: second-order FD discretization of the 2D laplace operator
Id: identity matrix
dx: distance between two spatial nodes in x direction
dy: distance between two spatial nodes in y direction
ksp: PETSc linear solver object
"""
dtype_u = petsc_vec
dtype_f = petsc_vec_imex
def __init__(self, cnvars, nu, freq, refine, comm=PETSc.COMM_WORLD, sol_tol=1e-10, sol_maxiter=None):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: PETSc data type (will be passed parent class)
dtype_f: PETSc data type with implicit and explicit parts (will be passed parent class)
"""
# make sure parameters have the correct form
if len(cnvars) != 2:
raise ProblemError('this is a 2d example, got %s' % cnvars)
# create DMDA object which will be used for all grid operations
da = PETSc.DMDA().create([cnvars[0], cnvars[1]], stencil_width=1, comm=comm)
for _ in range(refine):
da = da.refine()
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__(init=da)
self._makeAttributeAndRegister(
'cnvars',
'nu',
'freq',
'comm',
'refine',
'comm',
'sol_tol',
'sol_maxiter',
localVars=locals(),
readOnly=True,
)
# compute dx, dy and get local ranges
self.dx = 1.0 / (self.init.getSizes()[0] - 1)
self.dy = 1.0 / (self.init.getSizes()[1] - 1)
(self.xs, self.xe), (self.ys, self.ye) = self.init.getRanges()
# compute discretization matrix A and identity
self.A = self.__get_A()
self.Id = self.__get_Id()
# setup solver
self.ksp = PETSc.KSP()
self.ksp.create(comm=self.comm)
self.ksp.setType('gmres')
pc = self.ksp.getPC()
pc.setType('none')
# pc.setType('hypre')
# self.ksp.setInitialGuessNonzero(True)
self.ksp.setFromOptions()
self.ksp.setTolerances(rtol=self.sol_tol, atol=self.sol_tol, max_it=self.sol_maxiter)
self.ksp_ncalls = 0
self.ksp_itercount = 0
def __get_A(self):
"""
Helper function to assemble PETSc matrix A
Returns:
PETSc matrix object
"""
# create matrix and set basic options
A = self.init.createMatrix()
A.setType('aij') # sparse
A.setFromOptions()
A.setPreallocationNNZ((5, 5))
A.setUp()
# fill matrix
A.zeroEntries()
row = PETSc.Mat.Stencil()
col = PETSc.Mat.Stencil()
mx, my = self.init.getSizes()
(xs, xe), (ys, ye) = self.init.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
row.index = (i, j)
row.field = 0
if i == 0 or j == 0 or i == mx - 1 or j == my - 1:
A.setValueStencil(row, row, 1.0)
else:
diag = self.nu * (-2.0 / self.dx**2 - 2.0 / self.dy**2)
for index, value in [
((i, j - 1), self.nu / self.dy**2),
((i - 1, j), self.nu / self.dx**2),
((i, j), diag),
((i + 1, j), self.nu / self.dx**2),
((i, j + 1), self.nu / self.dy**2),
]:
col.index = index
col.field = 0
A.setValueStencil(row, col, value)
A.assemble()
return A
def __get_Id(self):
"""
Helper function to assemble PETSc identity matrix
Returns:
PETSc matrix object
"""
# create matrix and set basic options
Id = self.init.createMatrix()
Id.setType('aij') # sparse
Id.setFromOptions()
Id.setPreallocationNNZ((1, 1))
Id.setUp()
# fill matrix
Id.zeroEntries()
row = PETSc.Mat.Stencil()
(xs, xe), (ys, ye) = self.init.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
row.index = (i, j)
row.field = 0
Id.setValueStencil(row, row, 1.0)
Id.assemble()
return Id
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)
# evaluate Au for implicit part
self.A.mult(u, f.impl)
# evaluate forcing term for explicit part
fa = self.init.getVecArray(f.expl)
xv, yv = np.meshgrid(range(self.xs, self.xe), range(self.ys, self.ye), indexing='ij')
fa[self.xs : self.xe, self.ys : self.ye] = (
-np.sin(np.pi * self.freq * xv * self.dx)
* np.sin(np.pi * self.freq * yv * self.dy)
* (np.sin(t) - self.nu * 2.0 * (np.pi * self.freq) ** 2 * np.cos(t))
)
return f
def solve_system(self, rhs, factor, u0, t):
"""
KSP linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution
"""
me = self.dtype_u(u0)
self.ksp.setOperators(self.Id - factor * self.A)
self.ksp.solve(rhs, me)
self.ksp_ncalls += 1
self.ksp_itercount += int(self.ksp.getIterationNumber())
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
me = self.dtype_u(self.init)
xa = self.init.getVecArray(me)
for i in range(self.xs, self.xe):
for j in range(self.ys, self.ye):
xa[i, j] = np.sin(np.pi * self.freq * i * self.dx) * np.sin(np.pi * self.freq * j * self.dy) * np.cos(t)
return me
| 6,940 | 30.694064 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AcousticAdvection_1D_FD_imex.py | import numpy as np
from scipy.sparse.linalg import spsolve
from pySDC.core.Errors import ParameterError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
from pySDC.implementations.problem_classes.acoustic_helpers.buildWave1DMatrix import (
getWave1DMatrix,
getWave1DAdvectionMatrix,
)
# noinspection PyUnusedLocal
class acoustic_1d_imex(ptype):
"""
Example implementing the one-dimensional IMEX acoustic-advection
TODO : doku
Attributes:
mesh (numpy.ndarray): 1d mesh
dx (float): mesh size
Dx: matrix for the advection operator
Id: sparse identity matrix
A: matrix for the wave operator
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, nvars, cs, cadv, order_adv, waveno):
"""
Initialization routine
"""
# invoke super init, passing number of dofs
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister('nvars', 'cs', 'cadv', 'order_adv', 'waveno', localVars=locals(), readOnly=True)
self.mesh = np.linspace(0.0, 1.0, self.nvars[1], endpoint=False)
self.dx = self.mesh[1] - self.mesh[0]
self.Dx = -self.cadv * getWave1DAdvectionMatrix(self.nvars[1], self.dx, self.order_adv)
self.Id, A = getWave1DMatrix(self.nvars[1], self.dx, ['periodic', 'periodic'], ['periodic', 'periodic'])
self.A = -self.cs * A
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-dtA)u = rhs
Args:
rhs (dtype_f): right-hand side for the nonlinear 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
"""
M = self.Id - factor * self.A
b = np.concatenate((rhs[0, :], rhs[1, :]))
sol = spsolve(M, b)
me = self.dtype_u(self.init)
me[0, :], me[1, :] = np.split(sol, 2)
return me
def __eval_fexpl(self, u, t):
"""
Helper routine to evaluate the explicit part of the RHS
Args:
u (dtype_u): current values (not used here)
t (float): current time
Returns:
explicit part of RHS
"""
b = np.concatenate((u[0, :], u[1, :]))
sol = self.Dx.dot(b)
fexpl = self.dtype_u(self.init)
fexpl[0, :], fexpl[1, :] = np.split(sol, 2)
return fexpl
def __eval_fimpl(self, u, t):
"""
Helper routine to evaluate the implicit part of the RHS
Args:
u (dtype_u): current values
t (float): current time (not used here)
Returns:
implicit part of RHS
"""
b = np.concatenate((u[:][0, :], u[:][1, :]))
sol = self.A.dot(b)
fimpl = self.dtype_u(self.init, val=0.0)
fimpl[0, :], fimpl[1, :] = np.split(sol, 2)
return fimpl
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS divided into two parts
"""
f = self.dtype_f(self.init)
f.impl = self.__eval_fimpl(u, t)
f.expl = self.__eval_fexpl(u, t)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
def u_initial(x, k):
return np.sin(k * 2.0 * np.pi * x) + np.sin(2.0 * np.pi * x)
me = self.dtype_u(self.init)
me[0, :] = 0.5 * u_initial(self.mesh - (self.cadv + self.cs) * t, self.waveno) - 0.5 * u_initial(
self.mesh - (self.cadv - self.cs) * t, self.waveno
)
me[1, :] = 0.5 * u_initial(self.mesh - (self.cadv + self.cs) * t, self.waveno) + 0.5 * u_initial(
self.mesh - (self.cadv - self.cs) * t, self.waveno
)
return me
| 4,300 | 27.673333 | 119 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/OuterSolarSystem.py | import numpy as np
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.particles import particles, acceleration
# noinspection PyUnusedLocal
class outer_solar_system(ptype):
"""
Example implementing the outer solar system problem
"""
dtype_u = particles
dtype_f = acceleration
G = 2.95912208286e-4
def __init__(self, sun_only=False):
"""Initialization routine"""
# invoke super init, passing nparts
super().__init__(((3, 6), None, np.dtype('float64')))
self._makeAttributeAndRegister('sun_only', localVars=locals())
def eval_f(self, u, t):
"""
Routine to compute the RHS
Args:
u (dtype_u): the particles
t (float): current time (not used here)
Returns:
dtype_f: RHS
"""
me = self.dtype_f(self.init, val=0.0)
# compute the acceleration due to gravitational forces
# ... only with respect to the sun
if self.sun_only:
for i in range(1, self.init[0][-1]):
dx = u.pos[:, i] - u.pos[:, 0]
r = np.sqrt(np.dot(dx, dx))
df = self.G * dx / (r**3)
me[:, i] -= u.m[0] * df
# ... or with all planets involved
else:
for i in range(self.init[0][-1]):
for j in range(i):
dx = u.pos[:, i] - u.pos[:, j]
r = np.sqrt(np.dot(dx, dx))
df = self.G * dx / (r**3)
me[:, i] -= u.m[j] * df
me[:, j] += u.m[i] * df
return me
def u_exact(self, t):
"""
Routine to compute the exact/initial trajectory at time t
Args:
t (float): current time
Returns:
dtype_u: exact/initial position and velocity
"""
assert t == 0.0, 'error, u_exact only works for the initial time t0=0'
me = self.dtype_u(self.init)
me.pos[:, 0] = [0.0, 0.0, 0.0]
me.pos[:, 1] = [-3.5025653, -3.8169847, -1.5507963]
me.pos[:, 2] = [9.0755314, -3.0458353, -1.6483708]
me.pos[:, 3] = [8.3101420, -16.2901086, -7.2521278]
me.pos[:, 4] = [11.4707666, -25.7294829, -10.8169456]
me.pos[:, 5] = [-15.5387357, -25.2225594, -3.1902382]
me.vel[:, 0] = [0.0, 0.0, 0.0]
me.vel[:, 1] = [0.00565429, -0.00412490, -0.00190589]
me.vel[:, 2] = [0.00168318, 0.00483525, 0.00192462]
me.vel[:, 3] = [0.00354178, 0.00137102, 0.00055029]
me.vel[:, 4] = [0.00288930, 0.00114527, 0.00039677]
me.vel[:, 5] = [0.00276725, -0.0017072, -0.00136504]
me.m[0] = 1.00000597682 # Sun
me.m[1] = 0.000954786104043 # Jupiter
me.m[2] = 0.000285583733151 # Saturn
me.m[3] = 0.0000437273164546 # Uranus
me.m[4] = 0.0000517759138449 # Neptune
me.m[5] = 1.0 / 130000000.0 # Pluto
return me
def eval_hamiltonian(self, u):
"""
Routine to compute the Hamiltonian
Args:
u (dtype_u): the particles
Returns:
float: hamiltonian
"""
ham = 0
for i in range(self.init[0][-1]):
ham += 0.5 * u.m[i] * np.dot(u.vel[:, i], u.vel[:, i])
for i in range(self.init[0][-1]):
for j in range(i):
dx = u.pos[:, i] - u.pos[:, j]
r = np.sqrt(np.dot(dx, dx))
ham -= self.G * u.m[i] * u.m[j] / r
return ham
| 3,545 | 29.834783 | 84 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/Lorenz.py | import numpy as np
from pySDC.core.Problem import ptype, WorkCounter
from pySDC.implementations.datatype_classes.mesh import mesh
class LorenzAttractor(ptype):
"""
Simple script to run a Lorenz attractor problem.
The Lorenz attractor is a system of three ordinary differential equations that exhibits some chaotic behaviour.
It is well known for the "Butterfly Effect", because the solution looks like a butterfly (solve to Tend = 100 or
so to see this with these initial conditions) and because of the chaotic nature.
Since the problem is non-linear, we need to use a Newton solver.
Problem and initial conditions do not originate from,
but were taken from doi.org/10.2140/camcos.2015.10.1
TODO : add equations with parameters
"""
dtype_u = mesh
dtype_f = mesh
def __init__(self, sigma=10.0, rho=28.0, beta=8.0 / 3.0, newton_tol=1e-9, newton_maxiter=99):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
"""
nvars = 3
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__(init=(nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister('nvars', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister(
'sigma', 'rho', 'beta', 'newton_tol', 'newton_maxiter', localVars=locals(), readOnly=True
)
self.work_counters['newton'] = WorkCounter()
self.work_counters['rhs'] = WorkCounter()
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
"""
# abbreviations
sigma = self.sigma
rho = self.rho
beta = self.beta
f = self.dtype_f(self.init)
f[0] = sigma * (u[1] - u[0])
f[1] = rho * u[0] - u[1] - u[0] * u[2]
f[2] = u[0] * u[1] - beta * u[2]
self.work_counters['rhs']()
return f
def solve_system(self, rhs, dt, u0, t):
"""
Simple Newton solver for the nonlinear system.
Args:
rhs (dtype_f): right-hand side for the linear system
dt (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
# abbreviations
sigma = self.sigma
rho = self.rho
beta = self.beta
# start Newton iterations
u = self.dtype_u(u0)
res = np.inf
for _n in range(0, self.newton_maxiter):
# assemble G such that G(u) = 0 at the solution to the step
G = np.array(
[
u[0] - dt * sigma * (u[1] - u[0]) - rhs[0],
u[1] - dt * (rho * u[0] - u[1] - u[0] * u[2]) - rhs[1],
u[2] - dt * (u[0] * u[1] - beta * u[2]) - rhs[2],
]
)
# compute the residual and determine if we are done
res = np.linalg.norm(G, np.inf)
if res <= self.newton_tol or np.isnan(res):
break
# assemble inverse of Jacobian J of G
prefactor = 1.0 / (
dt**3 * sigma * (u[0] ** 2 + u[0] * u[1] + beta * (-rho + u[2] + 1))
+ dt**2 * (beta * sigma + beta - rho * sigma + sigma + u[0] ** 2 + sigma * u[2])
+ dt * (beta + sigma + 1)
+ 1
)
J_inv = prefactor * np.array(
[
[
beta * dt**2 + dt**2 * u[0] ** 2 + beta * dt + dt + 1,
beta * dt**2 * sigma + dt * sigma,
-(dt**2) * sigma * u[0],
],
[
beta * dt**2 * rho + dt**2 * (-u[0]) * u[1] - beta * dt**2 * u[2] + dt * rho - dt * u[2],
beta * dt**2 * sigma + beta * dt + dt * sigma + 1,
dt**2 * sigma * (-u[0]) - dt * u[0],
],
[
dt**2 * rho * u[0] - dt**2 * u[0] * u[2] + dt**2 * u[1] + dt * u[1],
dt**2 * sigma * u[0] + dt**2 * sigma * u[1] + dt * u[0],
-(dt**2) * rho * sigma + dt**2 * sigma + dt**2 * sigma * u[2] + dt * sigma + dt + 1,
],
]
)
# solve the linear system for the Newton correction J delta = G
delta = J_inv @ G
# update solution
u = u - delta
self.work_counters['newton']()
return u
def u_exact(self, t, u_init=None, t_init=None):
"""
Routine to return initial conditions or to approximate exact solution using scipy.
Args:
t (float): current time
u_init (pySDC.implementations.problem_classes.Lorenz.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)
if t > 0:
def eval_rhs(t, u):
"""
Evaluate the right hand side, but switch the arguments for scipy.
Args:
t (float): Time
u (numpy.ndarray): Solution at time t
Returns:
(numpy.ndarray): Right hand side evaluation
"""
return self.eval_f(u, t)
me[:] = self.generate_scipy_reference_solution(eval_rhs, t, u_init, t_init)
else:
me[:] = 1.0
return me
| 5,910 | 33.16763 | 124 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/GeneralizedFisher_1D_PETSc.py | import numpy as np
from petsc4py import PETSc
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.petsc_vec import petsc_vec, petsc_vec_imex, petsc_vec_comp2
class Fisher_full(object):
"""
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
"""
def __init__(self, da, prob, factor, dx):
"""
Initialization routine
Args:
da: DMDA object
prob: problem instance
factor: temporal factor (dt*Qd)
dx: grid spacing in x direction
"""
assert da.getDim() == 1
self.da = da
self.factor = factor
self.dx = dx
self.prob = prob
self.localX = da.createLocalVec()
self.xs, self.xe = self.da.getRanges()[0]
self.mx = self.da.getSizes()[0]
self.row = PETSc.Mat.Stencil()
self.col = PETSc.Mat.Stencil()
def formFunction(self, snes, X, F):
"""
Function to evaluate the residual for the Newton solver
This function should be equal to the RHS in the solution
Args:
snes: nonlinear solver object
X: input vector
F: output vector F(X)
Returns:
None (overwrites F)
"""
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
f = self.da.getVecArray(F)
for i in range(self.xs, self.xe):
if i == 0 or i == self.mx - 1:
f[i] = x[i]
else:
u = x[i] # center
u_e = x[i + 1] # east
u_w = x[i - 1] # west
u_xx = (u_e - 2 * u + u_w) / self.dx**2
f[i] = x[i] - self.factor * (u_xx + self.prob.lambda0**2 * x[i] * (1 - x[i] ** self.prob.nu))
def formJacobian(self, snes, X, J, P):
"""
Function to return the Jacobian matrix
Args:
snes: nonlinear solver object
X: input vector
J: Jacobian matrix (current?)
P: Jacobian matrix (new)
Returns:
matrix status
"""
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
P.zeroEntries()
for i in range(self.xs, self.xe):
self.row.i = i
self.row.field = 0
if i == 0 or i == self.mx - 1:
P.setValueStencil(self.row, self.row, 1.0)
else:
diag = 1.0 - self.factor * (
-2.0 / self.dx**2 + self.prob.lambda0**2 * (1.0 - (self.prob.nu + 1) * x[i] ** self.prob.nu)
)
for index, value in [
(i - 1, -self.factor / self.dx**2),
(i, diag),
(i + 1, -self.factor / self.dx**2),
]:
self.col.i = index
self.col.field = 0
P.setValueStencil(self.row, self.col, value)
P.assemble()
if J != P:
J.assemble() # matrix-free operator
return PETSc.Mat.Structure.SAME_NONZERO_PATTERN
class Fisher_reaction(object):
"""
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
"""
def __init__(self, da, prob, factor):
"""
Initialization routine
Args:
da: DMDA object
prob: problem instance
factor: temporal factor (dt*Qd)
dx: grid spacing in x direction
"""
assert da.getDim() == 1
self.da = da
self.prob = prob
self.factor = factor
self.localX = da.createLocalVec()
def formFunction(self, snes, X, F):
"""
Function to evaluate the residual for the Newton solver
This function should be equal to the RHS in the solution
Args:
snes: nonlinear solver object
X: input vector
F: output vector F(X)
Returns:
None (overwrites F)
"""
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
f = self.da.getVecArray(F)
mx = self.da.getSizes()[0]
(xs, xe) = self.da.getRanges()[0]
for i in range(xs, xe):
if i == 0 or i == mx - 1:
f[i] = x[i]
else:
f[i] = x[i] - self.factor * self.prob.lambda0**2 * x[i] * (1 - x[i] ** self.prob.nu)
def formJacobian(self, snes, X, J, P):
"""
Function to return the Jacobian matrix
Args:
snes: nonlinear solver object
X: input vector
J: Jacobian matrix (current?)
P: Jacobian matrix (new)
Returns:
matrix status
"""
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
P.zeroEntries()
row = PETSc.Mat.Stencil()
mx = self.da.getSizes()[0]
(xs, xe) = self.da.getRanges()[0]
for i in range(xs, xe):
row.i = i
row.field = 0
if i == 0 or i == mx - 1:
P.setValueStencil(row, row, 1.0)
else:
diag = 1.0 - self.factor * self.prob.lambda0**2 * (1.0 - (self.prob.nu + 1) * x[i] ** self.prob.nu)
P.setValueStencil(row, row, diag)
P.assemble()
if J != P:
J.assemble() # matrix-free operator
return PETSc.Mat.Structure.SAME_NONZERO_PATTERN
class petsc_fisher_multiimplicit(ptype):
"""
Problem class implementing the multi-implicit 1D generalized Fisher equation with periodic BC and PETSc
"""
dtype_u = petsc_vec
dtype_f = petsc_vec_comp2
def __init__(
self,
nvars,
lambda0,
nu,
interval,
comm=PETSc.COMM_WORLD,
lsol_tol=1e-10,
nlsol_tol=1e-10,
lsol_maxiter=None,
nlsol_maxiter=None,
):
"""
Initialization routine
TODO : doku
"""
# create DMDA object which will be used for all grid operations
da = PETSc.DMDA().create([nvars], dof=1, stencil_width=1, comm=comm)
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__(init=da)
self._makeAttributeAndRegister(
'nvars',
'lambda0',
'nu',
'interval',
'comm',
'lsol_tol',
'nlsol_tol',
'lsol_maxiter',
'nlsol_maxiter',
localVars=locals(),
readOnly=True,
)
# compute dx and get local ranges
self.dx = (self.interval[1] - self.interval[0]) / (self.nvars - 1)
(self.xs, self.xe) = self.init.getRanges()[0]
# compute discretization matrix A and identity
self.A = self.__get_A()
self.localX = self.init.createLocalVec()
# setup linear solver
self.ksp = PETSc.KSP()
self.ksp.create(comm=self.comm)
self.ksp.setType('cg')
pc = self.ksp.getPC()
pc.setType('ilu')
self.ksp.setInitialGuessNonzero(True)
self.ksp.setFromOptions()
self.ksp.setTolerances(rtol=self.lsol_tol, atol=self.lsol_tol, max_it=self.lsol_maxiter)
self.ksp_itercount = 0
self.ksp_ncalls = 0
# setup nonlinear solver
self.snes = PETSc.SNES()
self.snes.create(comm=self.comm)
if self.nlsol_maxiter <= 1:
self.snes.setType('ksponly')
self.snes.getKSP().setType('cg')
pc = self.snes.getKSP().getPC()
pc.setType('ilu')
# self.snes.setType('ngmres')
self.snes.setFromOptions()
self.snes.setTolerances(
rtol=self.nlsol_tol,
atol=self.nlsol_tol,
stol=self.nlsol_tol,
max_it=self.nlsol_maxiter,
)
self.snes_itercount = 0
self.snes_ncalls = 0
self.F = self.init.createGlobalVec()
self.J = self.init.createMatrix()
def __get_A(self):
"""
Helper function to assemble PETSc matrix A
Returns:
PETSc matrix object
"""
# create matrix and set basic options
A = self.init.createMatrix()
A.setType('aij') # sparse
A.setFromOptions()
A.setPreallocationNNZ((3, 3))
A.setUp()
# fill matrix
A.zeroEntries()
row = PETSc.Mat.Stencil()
col = PETSc.Mat.Stencil()
mx = self.init.getSizes()[0]
(xs, xe) = self.init.getRanges()[0]
for i in range(xs, xe):
row.i = i
row.field = 0
if i == 0 or i == mx - 1:
A.setValueStencil(row, row, 1.0)
else:
diag = -2.0 / self.dx**2
for index, value in [
(i - 1, 1.0 / self.dx**2),
(i, diag),
(i + 1, 1.0 / self.dx**2),
]:
col.i = index
col.field = 0
A.setValueStencil(row, col, value)
A.assemble()
return A
def get_sys_mat(self, factor):
"""
Helper function to assemble the system matrix of the linear problem
Returns:
PETSc matrix object
"""
# create matrix and set basic options
A = self.init.createMatrix()
A.setType('aij') # sparse
A.setFromOptions()
A.setPreallocationNNZ((3, 3))
A.setUp()
# fill matrix
A.zeroEntries()
row = PETSc.Mat.Stencil()
col = PETSc.Mat.Stencil()
mx = self.init.getSizes()[0]
(xs, xe) = self.init.getRanges()[0]
for i in range(xs, xe):
row.i = i
row.field = 0
if i == 0 or i == mx - 1:
A.setValueStencil(row, row, 1.0)
else:
diag = 1.0 + factor * 2.0 / self.dx**2
for index, value in [
(i - 1, -factor / self.dx**2),
(i, diag),
(i + 1, -factor / self.dx**2),
]:
col.i = index
col.field = 0
A.setValueStencil(row, col, value)
A.assemble()
return A
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)
self.A.mult(u, f.comp1)
fa1 = self.init.getVecArray(f.comp1)
fa1[0] = 0
fa1[-1] = 0
fa2 = self.init.getVecArray(f.comp2)
xa = self.init.getVecArray(u)
for i in range(self.xs, self.xe):
fa2[i] = self.lambda0**2 * xa[i] * (1 - xa[i] ** self.nu)
fa2[0] = 0
fa2[-1] = 0
return f
def solve_system_1(self, rhs, factor, u0, t):
"""
Linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution
"""
me = self.dtype_u(u0)
self.ksp.setOperators(self.get_sys_mat(factor))
self.ksp.solve(rhs, me)
self.ksp_itercount += self.ksp.getIterationNumber()
self.ksp_ncalls += 1
return me
def solve_system_2(self, rhs, factor, u0, t):
"""
Nonlinear solver for (I-factor*F)(u) = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution
"""
me = self.dtype_u(u0)
target = Fisher_reaction(self.init, self, factor)
# assign residual function and Jacobian
F = self.init.createGlobalVec()
self.snes.setFunction(target.formFunction, F)
J = self.init.createMatrix()
self.snes.setJacobian(target.formJacobian, J)
self.snes.solve(rhs, me)
self.snes_itercount += self.snes.getIterationNumber()
self.snes_ncalls += 1
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
lam1 = self.lambda0 / 2.0 * ((self.nu / 2.0 + 1) ** 0.5 + (self.nu / 2.0 + 1) ** (-0.5))
sig1 = lam1 - np.sqrt(lam1**2 - self.lambda0**2)
me = self.dtype_u(self.init)
xa = self.init.getVecArray(me)
for i in range(self.xs, self.xe):
xa[i] = (
1
+ (2 ** (self.nu / 2.0) - 1)
* np.exp(-self.nu / 2.0 * sig1 * (self.interval[0] + (i + 1) * self.dx + 2 * lam1 * t))
) ** (-2.0 / self.nu)
return me
class petsc_fisher_fullyimplicit(petsc_fisher_multiimplicit):
"""
Problem class implementing the fully-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc
"""
dtype_f = petsc_vec
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)
self.A.mult(u, f)
fa2 = self.init.getVecArray(f)
xa = self.init.getVecArray(u)
for i in range(self.xs, self.xe):
fa2[i] += self.lambda0**2 * xa[i] * (1 - xa[i] ** self.nu)
fa2[0] = 0
fa2[-1] = 0
return f
def solve_system(self, rhs, factor, u0, t):
"""
Nonlinear solver for (I-factor*F)(u) = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution
"""
me = self.dtype_u(u0)
target = Fisher_full(self.init, self, factor, self.dx)
# assign residual function and Jacobian
self.snes.setFunction(target.formFunction, self.F)
self.snes.setJacobian(target.formJacobian, self.J)
self.snes.solve(rhs, me)
self.snes_itercount += self.snes.getIterationNumber()
self.snes_ncalls += 1
return me
class petsc_fisher_semiimplicit(petsc_fisher_multiimplicit):
"""
Problem class implementing the semi-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc
"""
dtype_f = petsc_vec_imex
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)
self.A.mult(u, f.impl)
fa1 = self.init.getVecArray(f.impl)
fa1[0] = 0
fa1[-1] = 0
fa2 = self.init.getVecArray(f.expl)
xa = self.init.getVecArray(u)
for i in range(self.xs, self.xe):
fa2[i] = self.lambda0**2 * xa[i] * (1 - xa[i] ** self.nu)
fa2[0] = 0
fa2[-1] = 0
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(u0)
self.ksp.setOperators(self.get_sys_mat(factor))
self.ksp.solve(rhs, me)
self.ksp_itercount += self.ksp.getIterationNumber()
self.ksp_ncalls += 1
return me
| 16,584 | 28.250441 | 118 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/GrayScott_2D_PETSc_periodic.py | import numpy as np
from petsc4py import PETSc
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.petsc_vec import petsc_vec, petsc_vec_imex, petsc_vec_comp2
class GS_full(object):
"""
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
"""
def __init__(self, da, prob, factor, dx, dy):
"""
Initialization routine
Args:
da: DMDA object
prob: problem instance
factor: temporal factor (dt*Qd)
dx: grid spacing in x direction
dy: grid spacing in x direction
"""
assert da.getDim() == 2
self.da = da
self.prob = prob
self.factor = factor
self.dx = dx
self.dy = dy
self.localX = da.createLocalVec()
def formFunction(self, snes, X, F):
"""
Function to evaluate the residual for the Newton solver
This function should be equal to the RHS in the solution
Args:
snes: nonlinear solver object
X: input vector
F: output vector F(X)
Returns:
None (overwrites F)
"""
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
f = self.da.getVecArray(F)
(xs, xe), (ys, ye) = self.da.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
u = x[i, j] # center
u_e = x[i + 1, j] # east
u_w = x[i - 1, j] # west
u_s = x[i, j + 1] # south
u_n = x[i, j - 1] # north
u_xx = u_e - 2 * u + u_w
u_yy = u_n - 2 * u + u_s
f[i, j, 0] = x[i, j, 0] - (
self.factor
* (
self.prob.Du * (u_xx[0] / self.dx**2 + u_yy[0] / self.dy**2)
- x[i, j, 0] * x[i, j, 1] ** 2
+ self.prob.A * (1 - x[i, j, 0])
)
)
f[i, j, 1] = x[i, j, 1] - (
self.factor
* (
self.prob.Dv * (u_xx[1] / self.dx**2 + u_yy[1] / self.dy**2)
+ x[i, j, 0] * x[i, j, 1] ** 2
- self.prob.B * x[i, j, 1]
)
)
def formJacobian(self, snes, X, J, P):
"""
Function to return the Jacobian matrix
Args:
snes: nonlinear solver object
X: input vector
J: Jacobian matrix (current?)
P: Jacobian matrix (new)
Returns:
matrix status
"""
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
P.zeroEntries()
row = PETSc.Mat.Stencil()
col = PETSc.Mat.Stencil()
(xs, xe), (ys, ye) = self.da.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
# diagnoal 2-by-2 block (for u and v)
row.index = (i, j)
col.index = (i, j)
row.field = 0
col.field = 0
val = 1.0 - self.factor * (
self.prob.Du * (-2.0 / self.dx**2 - 2.0 / self.dy**2) - x[i, j, 1] ** 2 - self.prob.A
)
P.setValueStencil(row, col, val)
row.field = 0
col.field = 1
val = self.factor * 2.0 * x[i, j, 0] * x[i, j, 1]
P.setValueStencil(row, col, val)
row.field = 1
col.field = 1
val = 1.0 - self.factor * (
self.prob.Dv * (-2.0 / self.dx**2 - 2.0 / self.dy**2)
+ 2.0 * x[i, j, 0] * x[i, j, 1]
- self.prob.B
)
P.setValueStencil(row, col, val)
row.field = 1
col.field = 0
val = -self.factor * x[i, j, 1] ** 2
P.setValueStencil(row, col, val)
# coupling through finite difference part
col.index = (i, j - 1)
col.field = 0
row.field = 0
P.setValueStencil(row, col, -self.factor * self.prob.Du / self.dx**2)
col.field = 1
row.field = 1
P.setValueStencil(row, col, -self.factor * self.prob.Dv / self.dy**2)
col.index = (i, j + 1)
col.field = 0
row.field = 0
P.setValueStencil(row, col, -self.factor * self.prob.Du / self.dx**2)
col.field = 1
row.field = 1
P.setValueStencil(row, col, -self.factor * self.prob.Dv / self.dy**2)
col.index = (i - 1, j)
col.field = 0
row.field = 0
P.setValueStencil(row, col, -self.factor * self.prob.Du / self.dx**2)
col.field = 1
row.field = 1
P.setValueStencil(row, col, -self.factor * self.prob.Dv / self.dy**2)
col.index = (i + 1, j)
col.field = 0
row.field = 0
P.setValueStencil(row, col, -self.factor * self.prob.Du / self.dx**2)
col.field = 1
row.field = 1
P.setValueStencil(row, col, -self.factor * self.prob.Dv / self.dy**2)
P.assemble()
if J != P:
J.assemble() # matrix-free operator
return PETSc.Mat.Structure.SAME_NONZERO_PATTERN
class GS_reaction(object):
"""
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
"""
def __init__(self, da, prob, factor):
"""
Initialization routine
Args:
da: DMDA object
prob: problem instance
factor: temporal factor (dt*Qd)
"""
assert da.getDim() == 2
self.da = da
self.prob = prob
self.factor = factor
self.localX = da.createLocalVec()
def formFunction(self, snes, X, F):
"""
Function to evaluate the residual for the Newton solver
This function should be equal to the RHS in the solution
Args:
snes: nonlinear solver object
X: input vector
F: output vector F(X)
Returns:
None (overwrites F)
"""
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
f = self.da.getVecArray(F)
(xs, xe), (ys, ye) = self.da.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
f[i, j, 0] = x[i, j, 0] - (
self.factor * (-x[i, j, 0] * x[i, j, 1] ** 2 + self.prob.A * (1 - x[i, j, 0]))
)
f[i, j, 1] = x[i, j, 1] - (self.factor * (x[i, j, 0] * x[i, j, 1] ** 2 - self.prob.B * x[i, j, 1]))
def formJacobian(self, snes, X, J, P):
"""
Function to return the Jacobian matrix
Args:
snes: nonlinear solver object
X: input vector
J: Jacobian matrix (current?)
P: Jacobian matrix (new)
Returns:
matrix status
"""
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
P.zeroEntries()
row = PETSc.Mat.Stencil()
col = PETSc.Mat.Stencil()
(xs, xe), (ys, ye) = self.da.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
row.index = (i, j)
col.index = (i, j)
row.field = 0
col.field = 0
P.setValueStencil(row, col, 1.0 - self.factor * (-x[i, j, 1] ** 2 - self.prob.A))
row.field = 0
col.field = 1
P.setValueStencil(row, col, self.factor * 2.0 * x[i, j, 0] * x[i, j, 1])
row.field = 1
col.field = 1
P.setValueStencil(row, col, 1.0 - self.factor * (2.0 * x[i, j, 0] * x[i, j, 1] - self.prob.B))
row.field = 1
col.field = 0
P.setValueStencil(row, col, -self.factor * x[i, j, 1] ** 2)
P.assemble()
if J != P:
J.assemble() # matrix-free operator
return PETSc.Mat.Structure.SAME_NONZERO_PATTERN
class petsc_grayscott_multiimplicit(ptype):
"""
Problem class implementing the multi-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc
"""
dtype_u = petsc_vec
dtype_f = petsc_vec_comp2
def __init__(
self,
nvars,
Du,
Dv,
A,
B,
comm=PETSc.COMM_WORLD,
lsol_tol=1e-10,
nlsol_tol=1e-10,
lsol_maxiter=None,
nlsol_maxiter=None,
):
"""
Initialization routine
Args:
problem_params: custom parameters for the example
dtype_u: PETSc data type (will be passed to parent class)
dtype_f: PETSc data type with 2 components (will be passed to parent class)
"""
# create DMDA object which will be used for all grid operations (boundary_type=3 -> periodic BC)
da = PETSc.DMDA().create(
[nvars[0], nvars[1]],
dof=2,
boundary_type=3,
stencil_width=1,
comm=comm,
)
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__(init=da)
self._makeAttributeAndRegister(
'nvars',
'Du',
'Dv',
'A',
'B',
'comm',
'lsol_tol',
'lsol_maxiter',
'nlsol_tol',
'nlsol_maxiter',
localVars=locals(),
readOnly=True,
)
# compute dx, dy and get local ranges
self.dx = 100.0 / (self.nvars[0])
self.dy = 100.0 / (self.nvars[1])
(self.xs, self.xe), (self.ys, self.ye) = self.init.getRanges()
# compute discretization matrix A and identity
self.AMat = self.__get_A()
self.Id = self.__get_Id()
self.localX = self.init.createLocalVec()
# setup linear solver
self.ksp = PETSc.KSP()
self.ksp.create(comm=self.comm)
self.ksp.setType('cg')
pc = self.ksp.getPC()
pc.setType('none')
self.ksp.setInitialGuessNonzero(True)
self.ksp.setFromOptions()
self.ksp.setTolerances(rtol=self.lsol_tol, atol=self.lsol_tol, max_it=self.lsol_maxiter)
self.ksp_itercount = 0
self.ksp_ncalls = 0
# setup nonlinear solver
self.snes = PETSc.SNES()
self.snes.create(comm=self.comm)
# self.snes.getKSP().setType('cg')
# self.snes.setType('ngmres')
self.snes.setFromOptions()
self.snes.setTolerances(
rtol=self.nlsol_tol,
atol=self.nlsol_tol,
stol=self.nlsol_tol,
max_it=self.nlsol_maxiter,
)
self.snes_itercount = 0
self.snes_ncalls = 0
def __get_A(self):
"""
Helper function to assemble PETSc matrix A
Returns:
PETSc matrix object
"""
A = self.init.createMatrix()
A.setType('aij') # sparse
A.setFromOptions()
A.setPreallocationNNZ((5, 5))
A.setUp()
A.zeroEntries()
row = PETSc.Mat.Stencil()
col = PETSc.Mat.Stencil()
mx, my = self.init.getSizes()
(xs, xe), (ys, ye) = self.init.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
row.index = (i, j)
row.field = 0
A.setValueStencil(row, row, self.Du * (-2.0 / self.dx**2 - 2.0 / self.dy**2))
row.field = 1
A.setValueStencil(row, row, self.Dv * (-2.0 / self.dx**2 - 2.0 / self.dy**2))
# if j > 0:
col.index = (i, j - 1)
col.field = 0
row.field = 0
A.setValueStencil(row, col, self.Du / self.dy**2)
col.field = 1
row.field = 1
A.setValueStencil(row, col, self.Dv / self.dy**2)
# if j < my - 1:
col.index = (i, j + 1)
col.field = 0
row.field = 0
A.setValueStencil(row, col, self.Du / self.dy**2)
col.field = 1
row.field = 1
A.setValueStencil(row, col, self.Dv / self.dy**2)
# if i > 0:
col.index = (i - 1, j)
col.field = 0
row.field = 0
A.setValueStencil(row, col, self.Du / self.dx**2)
col.field = 1
row.field = 1
A.setValueStencil(row, col, self.Dv / self.dx**2)
# if i < mx - 1:
col.index = (i + 1, j)
col.field = 0
row.field = 0
A.setValueStencil(row, col, self.Du / self.dx**2)
col.field = 1
row.field = 1
A.setValueStencil(row, col, self.Dv / self.dx**2)
A.assemble()
return A
def __get_Id(self):
"""
Helper function to assemble PETSc identity matrix
Returns:
PETSc matrix object
"""
Id = self.init.createMatrix()
Id.setType('aij') # sparse
Id.setFromOptions()
Id.setPreallocationNNZ((1, 1))
Id.setUp()
Id.zeroEntries()
row = PETSc.Mat.Stencil()
mx, my = self.init.getSizes()
(xs, xe), (ys, ye) = self.init.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
for indx in [0, 1]:
row.index = (i, j)
row.field = indx
Id.setValueStencil(row, row, 1.0)
Id.assemble()
return Id
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)
self.AMat.mult(u, f.comp1)
fa = self.init.getVecArray(f.comp2)
xa = self.init.getVecArray(u)
for i in range(self.xs, self.xe):
for j in range(self.ys, self.ye):
fa[i, j, 0] = -xa[i, j, 0] * xa[i, j, 1] ** 2 + self.A * (1 - xa[i, j, 0])
fa[i, j, 1] = xa[i, j, 0] * xa[i, j, 1] ** 2 - self.B * xa[i, j, 1]
return f
def solve_system_1(self, rhs, factor, u0, t):
"""
Linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution
"""
me = self.dtype_u(u0)
self.ksp.setOperators(self.Id - factor * self.AMat)
self.ksp.solve(rhs, me)
self.ksp_ncalls += 1
self.ksp_itercount += self.ksp.getIterationNumber()
return me
def solve_system_2(self, rhs, factor, u0, t):
"""
Nonlinear solver for (I-factor*F)(u) = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution
"""
me = self.dtype_u(u0)
target = GS_reaction(self.init, self, factor)
F = self.init.createGlobalVec()
self.snes.setFunction(target.formFunction, F)
J = self.init.createMatrix()
self.snes.setJacobian(target.formJacobian, J)
self.snes.solve(rhs, me)
self.snes_ncalls += 1
self.snes_itercount += self.snes.getIterationNumber()
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
assert t == 0, 'ERROR: u_exact is only valid for the initial solution'
me = self.dtype_u(self.init)
xa = self.init.getVecArray(me)
for i in range(self.xs, self.xe):
for j in range(self.ys, self.ye):
xa[i, j, 0] = 1.0 - 0.5 * np.power(
np.sin(np.pi * i * self.dx / 100) * np.sin(np.pi * j * self.dy / 100), 100
)
xa[i, j, 1] = 0.25 * np.power(
np.sin(np.pi * i * self.dx / 100) * np.sin(np.pi * j * self.dy / 100), 100
)
return me
class petsc_grayscott_fullyimplicit(petsc_grayscott_multiimplicit):
"""
Problem class implementing the fully-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc
"""
dtype_f = petsc_vec
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)
self.AMat.mult(u, f)
fa = self.init.getVecArray(f)
xa = self.init.getVecArray(u)
for i in range(self.xs, self.xe):
for j in range(self.ys, self.ye):
fa[i, j, 0] += -xa[i, j, 0] * xa[i, j, 1] ** 2 + self.A * (1 - xa[i, j, 0])
fa[i, j, 1] += xa[i, j, 0] * xa[i, j, 1] ** 2 - self.B * xa[i, j, 1]
return f
def solve_system(self, rhs, factor, u0, t):
"""
Nonlinear solver for (I-factor*F)(u) = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(u0)
target = GS_full(self.init, self, factor, self.dx, self.dy)
# assign residual function and Jacobian
F = self.init.createGlobalVec()
self.snes.setFunction(target.formFunction, F)
J = self.init.createMatrix()
self.snes.setJacobian(target.formJacobian, J)
self.snes.solve(rhs, me)
self.snes_ncalls += 1
self.snes_itercount += self.snes.getIterationNumber()
return me
class petsc_grayscott_semiimplicit(petsc_grayscott_multiimplicit):
"""
Problem class implementing the semi-implicit 2D Gray-Scott reaction-diffusion equation with periodic BC and PETSc
"""
dtype_f = petsc_vec_imex
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)
self.AMat.mult(u, f.impl)
fa = self.init.getVecArray(f.expl)
xa = self.init.getVecArray(u)
for i in range(self.xs, self.xe):
for j in range(self.ys, self.ye):
fa[i, j, 0] = -xa[i, j, 0] * xa[i, j, 1] ** 2 + self.A * (1 - xa[i, j, 0])
fa[i, j, 1] = xa[i, j, 0] * xa[i, j, 1] ** 2 - self.B * xa[i, j, 1]
return f
def solve_system(self, rhs, factor, u0, t):
"""
Linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution
"""
me = self.dtype_u(u0)
self.ksp.setOperators(self.Id - factor * self.AMat)
self.ksp.solve(rhs, me)
self.ksp_ncalls += 1
self.ksp_itercount += self.ksp.getIterationNumber()
return me
| 20,605 | 30.848532 | 118 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/BuckConverter.py | import numpy as np
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
class buck_converter(ptype):
r"""
Example implementing the model of a buck converter, which is also called a step-down converter. The converter has two different
states and each of this state can be expressed as a nonhomogeneous linear system of ordinary differential equations (ODEs)
.. math::
\frac{d u(t)}{dt} = A_k u(t) + f_k (t)
for :math:`k=1,2`. The two states are the following. Define :math:`T_{sw}:=\frac{1}{f_{sw}}` as the switching period with
switching frequency :math:`f_{sw}`. The duty cycle :math:`duty`defines the period of how long the switches are in one state
until they switch to the other state. Roughly saying, the duty cycle can be seen as a percentage. A duty cycle of one means
that the switches are always in only one state. If :math:`0 \leq \frac{t}{T_{sw}} mod 1 \leq duty`:
.. math::
\frac{d v_{C_1} (t)}{dt} = -\frac{1}{R_s C_1}v_{C_1} (t) - \frac{1}{C_1} i_{L_1} (t) + \frac{V_s}{R_s C_1},
.. math::
\frac{d v_{C_2} (t)}{dt} = -\frac{1}{R_\ell C_2}v_{C_2} (t) + \frac{1}{C_2} i_{L_1} (t),
.. math::
\frac{d i_{L_1} (t)}{dt} = \frac{1}{L_1} v_{C_1} (t) - \frac{1}{L_1} v_{C_2} (t) - \frac{R_\pi}{L_1} i_{L_1} (t),
Otherwise, the equations are
.. math::
\frac{d v_{C_1} (t)}{dt} = -\frac{1}{R_s C_1}v_{C_1} (t) + \frac{V_s}{R_s C_1},
.. math::
\frac{d v_{C_2} (t)}{dt} = -\frac{1}{R_\ell C_2}v_{C_2} (t) + \frac{1}{C_2} i_{L_1} (t),
.. math::
\frac{d i_{L_1} (t)}{dt} = \frac{R_\pi}{R_s L_1} v_{C_1} (t) - \frac{1}{L_1} v_{C_2} (t) - \frac{R_\pi V_s}{L_1 R_s}.
using an initial condition.
Parameters
----------
duty : float
Cycle between zero and one indicates the time period how long the converter stays on one switching state
until it switches to the other state.
fsw : int
Switching frequency, it is used to determine the number of time steps after the switching state is changed.
Vs : float
Voltage at the voltage source :math:`V_s`.
Rs : float
Resistance of the resistor :math:`R_s` at the voltage source.
C1 : float
Capacitance of the capacitor :math:`C_1`.
Rp : float
Resistance of the resistor in front of the inductor.
L1 : float
Inductance of the inductor :math:`L_1`.
C2 : float
Capacitance of the capacitor :math:`C_2`.
Rl : float
Resistance of the resistor :math:`R_\pi`
Attributes
----------
A: system matrix, representing the 3 ODEs
Note
----
The duty cycle needs to be a value in :math:`[0,1]`.
References
----------
.. [1] J. Sun. Pulse-Width Modulation. 25-61. Springer, (2012).
.. [2] J. Gyselinck, C. Martis, R. V. Sabariego. Using dedicated time-domain basis functions for the simulation of
pulse-width-modulation controlled devices - application to the steady-state regime of a buck converter. Electromotion (2013).
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, duty=0.5, fsw=1e3, Vs=10.0, Rs=0.5, C1=1e-3, Rp=0.01, L1=1e-3, C2=1e-3, Rl=10):
"""Initialization routine"""
# invoke super init, passing number of dofs
nvars = 3
super().__init__(init=(nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'nvars', 'duty', 'fsw', 'Vs', 'Rs', 'C1', 'Rp', 'L1', 'C2', 'Rl', localVars=locals(), readOnly=True
)
self.A = np.zeros((nvars, nvars))
def eval_f(self, u, t):
"""
Routine to evaluate the right-hand side of the problem.
Parameters
----------
u : dtype_u
Current values of the numerical solution.
t : float
Current time of the numerical solution is computed.
Returns
-------
f : dtype_f
The right-hand side of the problem.
"""
Tsw = 1 / self.fsw
f = self.dtype_f(self.init, val=0.0)
f.impl[:] = self.A.dot(u)
if 0 <= ((t / Tsw) % 1) <= self.duty:
f.expl[0] = self.Vs / (self.Rs * self.C1)
f.expl[2] = 0
else:
f.expl[0] = self.Vs / (self.Rs * self.C1)
f.expl[2] = -(self.Rp * self.Vs) / (self.L1 * self.Rs)
return f
def solve_system(self, rhs, factor, u0, t):
r"""
Simple linear solver for :math:`(I-factor\cdot A)\vec{u}=\vec{rhs}`.
Parameters
----------
rhs : dtype_f
Right-hand side for the linear system.
factor : float
Abbrev. for the local stepsize (or any other factor required).
u0 : dtype_u
Initial guess for the iterative solver.
t : float
Current time (e.g. for time-dependent BCs).
Returns
-------
me : dtype_u
The solution as mesh.
"""
Tsw = 1 / self.fsw
self.A = np.zeros((3, 3))
if 0 <= ((t / Tsw) % 1) <= self.duty:
self.A[0, 0] = -1 / (self.C1 * self.Rs)
self.A[0, 2] = -1 / self.C1
self.A[1, 1] = -1 / (self.C2 * self.Rl)
self.A[1, 2] = 1 / self.C2
self.A[2, 0] = 1 / self.L1
self.A[2, 1] = -1 / self.L1
self.A[2, 2] = -self.Rp / self.L1
else:
self.A[0, 0] = -1 / (self.C1 * self.Rs)
self.A[1, 1] = -1 / (self.C2 * self.Rl)
self.A[1, 2] = 1 / self.C2
self.A[2, 0] = self.Rp / (self.L1 * self.Rs)
self.A[2, 1] = -1 / self.L1
me = self.dtype_u(self.init)
me[:] = np.linalg.solve(np.eye(self.nvars) - factor * self.A, rhs)
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t.
Parameters
----------
t : float
Time of the exact solution.
Returns
-------
me : dtype_u
The exact solution.
"""
assert t == 0, 'ERROR: u_exact only valid for t=0'
me = self.dtype_u(self.init)
me[0] = 0.0 # v1
me[1] = 0.0 # v2
me[2] = 0.0 # p3
return me
| 6,335 | 31.492308 | 133 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AllenCahn_2D_FFT_gpu.py | import cupy as cp
import numpy as np
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.cupy_mesh import cupy_mesh, imex_cupy_mesh
class allencahn2d_imex(ptype): # pragma: no cover
"""
Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping
Attributes:
xvalues: grid points in space
dx: cupy_mesh width
lap: spectral operator for Laplacian
rfft_object: planned real FFT for forward transformation
irfft_object: planned IFFT for backward transformation
"""
dtype_u = cupy_mesh
dtype_f = imex_cupy_mesh
def __init__(self, nvars, nu, eps, radius, L=1.0, init_type='circle'):
"""Initialization routine"""
# we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on
if len(nvars) != 2:
raise ProblemError('this is a 2d example, got %s' % nvars)
if nvars[0] != nvars[1]:
raise ProblemError('need a square domain, got %s' % nvars)
if 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().__init__(init=(nvars, None, cp.dtype('float64')))
self._makeAttributeAndRegister(
'nvars', 'nu', 'eps', 'radius', 'L', 'init_type', localVars=locals(), readOnly=True
)
self.dx = self.L / self.nvars[0] # could be useful for hooks, too.
self.xvalues = cp.array([i * self.dx - self.L / 2.0 for i in range(self.nvars[0])])
kx = cp.zeros(self.init[0][0])
ky = cp.zeros(self.init[0][1] // 2 + 1)
kx[: int(self.init[0][0] / 2) + 1] = 2 * np.pi / self.L * cp.arange(0, int(self.init[0][0] / 2) + 1)
kx[int(self.init[0][0] / 2) + 1 :] = (
2 * np.pi / self.L * cp.arange(int(self.init[0][0] / 2) + 1 - self.init[0][0], 0)
)
ky[:] = 2 * np.pi / self.L * cp.arange(0, self.init[0][1] // 2 + 1)
xv, yv = cp.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.lap * cp.fft.rfft2(u)
f.impl[:] = cp.fft.irfft2(tmp)
if self.eps > 0:
f.expl[:] = (1.0 / self.eps**2 * v * (1.0 - v**self.nu)).reshape(self.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 = cp.fft.rfft2(rhs) / (1.0 - factor * self.lap)
me[:] = cp.fft.irfft2(tmp)
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
assert t == 0, 'ERROR: u_exact only valid for t=0'
me = self.dtype_u(self.init, val=0.0)
if self.init_type == 'circle':
xv, yv = cp.meshgrid(self.xvalues, self.xvalues, indexing='ij')
me[:, :] = cp.tanh((self.radius - cp.sqrt(xv**2 + yv**2)) / (cp.sqrt(2) * self.eps))
elif self.init_type == 'checkerboard':
xv, yv = cp.meshgrid(self.xvalues, self.xvalues)
me[:, :] = cp.sin(2.0 * np.pi * xv) * cp.sin(2.0 * np.pi * yv)
elif self.init_type == 'random':
me[:, :] = cp.random.uniform(-1, 1, self.init)
else:
raise NotImplementedError('type of initial value not implemented, got %s' % self.init_type)
return me
class allencahn2d_imex_stab(allencahn2d_imex):
"""
Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping with
stabilized splitting
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, nvars, nu, eps, radius, L=1.0, init_type='circle'):
super().__init__(nvars, nu, eps, radius, L, init_type)
self.lap -= 2.0 / self.eps**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.lap * cp.fft.rfft2(u)
f.impl[:] = cp.fft.irfft2(tmp)
if self.eps > 0:
f.expl[:] = (1.0 / self.eps**2 * v * (1.0 - v**self.nu) + 2.0 / self.eps**2 * v).reshape(self.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 = cp.fft.rfft2(rhs) / (1.0 - factor * self.lap)
me[:] = cp.fft.irfft2(tmp)
return me
| 6,129 | 33.055556 | 115 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/HeatEquation_1D_FEniCS_matrix_forced.py | import logging
import dolfin as df
import numpy as np
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.fenics_mesh import fenics_mesh, rhs_fenics_mesh
# noinspection PyUnusedLocal
class fenics_heat(ptype):
"""
Example implementing the forced 1D heat equation with Dirichlet-0 BC in [0,1]
Attributes:
V: function space
M: mass matrix for FEM
K: stiffness matrix incl. diffusion coefficient (and correct sign)
g: forcing term
bc: boundary conditions
"""
dtype_u = fenics_mesh
dtype_f = rhs_fenics_mesh
def __init__(self, c_nvars, t0, family, order, refinements, nu):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: FEniCS mesh data type (will be passed to parent class)
dtype_f: FEniCS mesh data data type with implicit and explicit parts (will be passed to parent class)
"""
# define the Dirichlet boundary
# def Boundary(x, on_boundary):
# return on_boundary
# set logger level for FFC and dolfin
logging.getLogger('FFC').setLevel(logging.WARNING)
logging.getLogger('UFL').setLevel(logging.WARNING)
# set solver and form parameters
df.parameters["form_compiler"]["optimize"] = True
df.parameters["form_compiler"]["cpp_optimize"] = True
df.parameters['allow_extrapolation'] = True
# set mesh and refinement (for multilevel)
mesh = df.UnitIntervalMesh(c_nvars)
for _ in range(refinements):
mesh = df.refine(mesh)
# define function space for future reference
self.V = df.FunctionSpace(mesh, family, order)
tmp = df.Function(self.V)
print('DoFs on this level:', len(tmp.vector()[:]))
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(fenics_heat, self).__init__(self.V)
self._makeAttributeAndRegister(
'c_nvars', 't0', 'family', 'order', 'refinements', 'nu', localVars=locals(), readOnly=True
)
# Stiffness term (Laplace)
u = df.TrialFunction(self.V)
v = df.TestFunction(self.V)
a_K = -1.0 * df.inner(df.nabla_grad(u), self.nu * df.nabla_grad(v)) * df.dx
# Mass term
a_M = u * v * df.dx
self.M = df.assemble(a_M)
self.K = df.assemble(a_K)
# set forcing term as expression
self.g = df.Expression(
'-cos(a*x[0]) * (sin(t) - b*a*a*cos(t))',
a=np.pi,
b=self.nu,
t=self.t0,
degree=self.order,
)
# self.g = df.Expression('0', a=np.pi, b=self.nu, t=self.t0,
# degree=self.order)
# set boundary values
# bc = df.DirichletBC(self.V, df.Constant(0.0), Boundary)
#
# bc.apply(self.M)
# bc.apply(self.K)
def solve_system(self, rhs, factor, u0, t):
"""
Dolfin's linear solver for (M-dtA)u = rhs
Args:
rhs (dtype_f): right-hand side for the nonlinear 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
Returns:
dtype_u: solution as mesh
"""
b = self.apply_mass_matrix(rhs)
u = self.dtype_u(u0)
df.solve(self.M - factor * self.K, u.values.vector(), b.values.vector())
return u
def __eval_fexpl(self, u, t):
"""
Helper routine to evaluate the explicit part of the RHS
Args:
u (dtype_u): current values (not used here)
t (fliat): current time
Returns:
explicit part of RHS
"""
self.g.t = t
fexpl = self.dtype_u(df.interpolate(self.g, self.V))
return fexpl
def __eval_fimpl(self, u, t):
"""
Helper routine to evaluate the implicit part of the RHS
Args:
u (dtype_u): current values
t (float): current time (not used here)
Returns:
implicit part of RHS
"""
tmp = self.dtype_u(self.V)
self.K.mult(u.values.vector(), tmp.values.vector())
fimpl = self.__invert_mass_matrix(tmp)
return fimpl
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS divided into two parts
"""
f = self.dtype_f(self.V)
f.impl = self.__eval_fimpl(u, t)
f.expl = self.__eval_fexpl(u, t)
return f
def apply_mass_matrix(self, u):
"""
Routine to apply mass matrix
Args:
u (dtype_u): current values
Returns:
dtype_u: M*u
"""
me = self.dtype_u(self.V)
self.M.mult(u.values.vector(), me.values.vector())
return me
def __invert_mass_matrix(self, u):
"""
Helper routine to invert mass matrix
Args:
u (dtype_u): current values
Returns:
dtype_u: inv(M)*u
"""
me = self.dtype_u(self.V)
b = self.dtype_u(u)
df.solve(self.M, me.values.vector(), b.values.vector())
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
u0 = df.Expression('cos(a*x[0]) * cos(t)', a=np.pi, t=t, degree=self.order)
me = self.dtype_u(df.interpolate(u0, self.V))
return me
# noinspection PyUnusedLocal
class fenics_heat_mass(fenics_heat):
"""
Example implementing the forced 1D heat equation with Dirichlet-0 BC in [0,1], expects mass matrix sweeper
"""
def solve_system(self, rhs, factor, u0, t):
"""
Dolfin's linear solver for (M-dtA)u = rhs
Args:
rhs (dtype_f): right-hand side for the nonlinear 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
Returns:
dtype_u: solution as mesh
"""
u = self.dtype_u(u0)
df.solve(self.M - factor * self.K, u.values.vector(), rhs.values.vector())
return u
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS divided into two parts
"""
f = self.dtype_f(self.V)
self.K.mult(u.values.vector(), f.impl.values.vector())
self.g.t = t
f.expl = self.dtype_u(df.interpolate(self.g, self.V))
f.expl = self.apply_mass_matrix(f.expl)
return f
| 7,212 | 26.32197 | 113 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/TestEquation_0D.py | import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import splu
from pySDC.core.Errors import ParameterError
from pySDC.core.Problem import ptype, WorkCounter
from pySDC.implementations.datatype_classes.mesh import mesh
# noinspection PyUnusedLocal
class testequation0d(ptype):
"""
Example implementing a bundle of test equations at once (via diagonal matrix)
Attributes:
A: digonal matrix containing the parameters
"""
dtype_u = mesh
dtype_f = mesh
# TODO : add default values
def __init__(self, lambdas, u0):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: mesh data type for solution
dtype_f: mesh data type for RHS
"""
assert not any(isinstance(i, list) for i in lambdas), 'ERROR: expect flat list here, got %s' % lambdas
nvars = len(lambdas)
assert nvars > 0, 'ERROR: expect at least one lambda parameter here'
# invoke super init, passing number of dofs, dtype_u and dtype_f
super().__init__(init=(nvars, None, np.dtype('complex128')))
self.A = self.__get_A(lambdas)
self._makeAttributeAndRegister('nvars', 'lambdas', 'u0', localVars=locals(), readOnly=True)
self.work_counters['rhs'] = WorkCounter()
@staticmethod
def __get_A(lambdas):
"""
Helper function to assemble FD matrix A in sparse format
Args:
lambdas (list): list of lambda parameters
Returns:
scipy.sparse.csc_matrix: diagonal matrix A in CSC format
"""
A = sp.diags(lambdas)
return A
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)
f[:] = self.A.dot(u)
self.work_counters['rhs']()
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(self.init)
L = splu(sp.eye(self.nvars, format='csc') - factor * self.A)
me[:] = L.solve(rhs)
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.problem.testequation0d.dtype_u
t_init : float
Returns:
dtype_u: exact solution
"""
u_init = (self.u0 if u_init is None else u_init) * 1.0
t_init = 0.0 if t_init is None else t_init * 1.0
me = self.dtype_u(self.init)
me[:] = u_init * np.exp((t - t_init) * np.array(self.lambdas))
return me
| 3,248 | 28.008929 | 110 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AdvectionEquation_ND_FD.py | import numpy as np
from pySDC.implementations.problem_classes.generic_ND_FD import GenericNDimFinDiff
# noinspection PyUnusedLocal
class advectionNd(GenericNDimFinDiff):
r"""
Example implementing the unforced ND advection equation with periodic
or Dirichlet boundary conditions in :math:`[0,1]^N`,
and initial solution of the form
.. math::
u({\bf x},0) = \prod_{i=1}^N \sin(f\pi x_i),
with :math:`x_i` the coordinate in :math:`i^{th}` dimension.
Discretization uses central finite differences.
Parameters
----------
nvars : int of tuple, optional
Spatial resolution (same in all dimensions). Using a tuple allows to
consider several dimensions, e.g nvars=(16,16) for a 2D problem.
c : float, optional
Advection speed (same in all dimensions).
freq : int of tuple, optional
Spatial frequency :math:`f` of the initial conditions, can be tuple.
stencil_type : str, optional
Type of the finite difference stencil.
order : int, optional
Order of the finite difference discretization.
lintol : float, optional
Tolerance for spatial solver (GMRES).
liniter : int, optional
Max. iterations number for GMRES.
solver_type : str, optional
Solve the linear system directly or using GMRES or CG
bc : str, optional
Boundary conditions, either "periodic" or "dirichlet".
sigma : float, optional
If freq=-1 and ndim=1, uses a Gaussian initial solution of the form
.. math::
u(x,0) = e^{
\frac{\displaystyle 1}{\displaystyle 2}
\left(
\frac{\displaystyle x-1/2}{\displaystyle \sigma}
\right)^2
}
Attributes
----------
A: sparse matrix (CSC)
FD discretization matrix of the ND grad operator.
Id: sparse matrix (CSC)
Identity matrix of the same dimension as A
Note
----
Args can be set as values or as tuples, which will increase the dimension.
Do, however, take care that all spatial parameters have the same dimension.
"""
def __init__(
self,
nvars=512,
c=1.0,
freq=2,
stencil_type='center',
order=2,
lintol=1e-12,
liniter=10000,
solver_type='direct',
bc='periodic',
sigma=6e-2,
):
super().__init__(nvars, -c, 1, freq, stencil_type, order, lintol, liniter, solver_type, bc)
if solver_type == 'CG': # pragma: no cover
self.logger.warn('CG is not usually used for advection equation')
self._makeAttributeAndRegister('c', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister('sigma', localVars=locals())
def u_exact(self, t, **kwargs):
"""
Routine to compute the exact solution at time t
Parameters
----------
t : float
Time of the exact solution.
**kwargs : dict
Additional arguments (that won't be used).
Returns
-------
sol : dtype_u
The exact solution.
"""
# Initialize pointers and variables
ndim, freq, c, sigma, sol = self.ndim, self.freq, self.c, self.sigma, self.u_init
if ndim == 1:
x = self.grids
if freq[0] >= 0:
sol[:] = np.sin(np.pi * freq[0] * (x - c * t))
elif freq[0] == -1:
# Gaussian initial solution
sol[:] = np.exp(-0.5 * (((x - (c * t)) % 1.0 - 0.5) / sigma) ** 2)
elif ndim == 2:
x, y = self.grids
sol[:] = np.sin(np.pi * freq[0] * (x - c * t)) * np.sin(np.pi * freq[1] * (y - c * t))
elif ndim == 3:
x, y, z = self.grids
sol[:] = (
np.sin(np.pi * freq[0] * (x - c * t))
* np.sin(np.pi * freq[1] * (y - c * t))
* np.sin(np.pi * freq[2] * (z - c * t))
)
return sol
| 4,028 | 31.491935 | 99 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/implementations/problem_classes/NonlinearSchroedinger_MPIFFT.py | import numpy as np
from mpi4py import MPI
from mpi4py_fft import PFFT
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype, WorkCounter
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
from mpi4py_fft import newDistArray
class nonlinearschroedinger_imex(ptype):
"""
Example implementing the nonlinear Schrödinger equation in 2-3D using mpi4py-fft for solving linear parts,
IMEX time-stepping
mpi4py-fft: https://mpi4py-fft.readthedocs.io/en/latest/
Attributes:
fft: fft object
X: grid coordinates in real space
K2: Laplace operator in spectral space
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, nvars, spectral, L=2 * np.pi, c=1.0, comm=MPI.COMM_WORLD):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: fft data type (will be passed to parent class)
dtype_f: fft data type wuth implicit and explicit parts (will be passed to parent class)
"""
if not L == 2.0 * np.pi:
raise ProblemError(f'Setup not implemented, L has to be 2pi, got {L}')
if not (c == 0.0 or c == 1.0):
raise ProblemError(f'Setup not implemented, c has to be 0 or 1, got {c}')
if not (isinstance(nvars, tuple) and len(nvars) > 1):
raise ProblemError('Need at least two dimensions')
# Creating FFT structure
self.ndim = len(nvars)
axes = tuple(range(self.ndim))
self.fft = PFFT(comm, list(nvars), axes=axes, dtype=np.complex128, collapse=True)
# get test data to figure out type and dimensions
tmp_u = newDistArray(self.fft, spectral)
L = np.array([L] * self.ndim, dtype=float)
# invoke super init, passing the communicator and the local dimensions as init
super(nonlinearschroedinger_imex, self).__init__(init=(tmp_u.shape, comm, tmp_u.dtype))
self._makeAttributeAndRegister('nvars', 'spectral', 'L', 'c', 'comm', localVars=locals(), readOnly=True)
# get local mesh
X = np.ogrid[self.fft.local_slice(False)]
N = self.fft.global_shape()
for i in range(len(N)):
X[i] = X[i] * self.L[i] / N[i]
self.X = [np.broadcast_to(x, self.fft.shape(False)) for x in X]
# get local wavenumbers and Laplace operator
s = self.fft.local_slice()
N = self.fft.global_shape()
k = [np.fft.fftfreq(n, 1.0 / n).astype(int) for n in N]
K = [ki[si] for ki, si in zip(k, s)]
Ks = np.meshgrid(*K, indexing='ij', sparse=True)
Lp = 2 * np.pi / self.L
for i in range(self.ndim):
Ks[i] = (Ks[i] * Lp[i]).astype(float)
K = [np.broadcast_to(k, self.fft.shape(True)) for k in Ks]
K = np.array(K).astype(float)
self.K2 = np.sum(K * K, 0, dtype=float)
# Need this for diagnostics
self.dx = self.L / nvars[0]
self.dy = self.L / nvars[1]
# work counters
self.work_counters['rhs'] = WorkCounter()
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)
if self.spectral:
f.impl = -self.K2 * 1j * u
tmp = self.fft.backward(u)
tmpf = self.ndim * self.c * 2j * np.absolute(tmp) ** 2 * tmp
f.expl[:] = self.fft.forward(tmpf)
else:
u_hat = self.fft.forward(u)
lap_u_hat = -self.K2 * 1j * u_hat
f.impl[:] = self.fft.backward(lap_u_hat, f.impl)
f.expl = self.ndim * self.c * 2j * np.absolute(u) ** 2 * u
self.work_counters['rhs']()
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
"""
if self.spectral:
me = rhs / (1.0 + factor * self.K2 * 1j)
else:
me = self.dtype_u(self.init)
rhs_hat = self.fft.forward(rhs)
rhs_hat /= 1.0 + factor * self.K2 * 1j
me[:] = self.fft.backward(rhs_hat)
return me
def u_exact(self, t, **kwargs):
"""
Routine to compute the exact solution at time t, see (1.3) https://arxiv.org/pdf/nlin/0702010.pdf for details
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
def nls_exact_1D(t, x, c):
ae = 1.0 / np.sqrt(2.0) * np.exp(1j * t)
if c != 0:
u = ae * ((np.cosh(t) + 1j * np.sinh(t)) / (np.cosh(t) - 1.0 / np.sqrt(2.0) * np.cos(x)) - 1.0)
else:
u = np.sin(x) * np.exp(-t * 1j)
return u
me = self.dtype_u(self.init, val=0.0)
if self.spectral:
tmp = nls_exact_1D(self.ndim * t, sum(self.X), self.c)
me[:] = self.fft.forward(tmp)
else:
me[:] = nls_exact_1D(self.ndim * t, sum(self.X), self.c)
return me
| 5,580 | 31.829412 | 117 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/PenningTrap_3D.py | import numpy as np
from numba import jit
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.particles import particles, fields, acceleration
# noinspection PyUnusedLocal
class penningtrap(ptype):
"""
Example implementing particles in a penning trap
"""
dtype_u = particles
dtype_f = fields
def __init__(self, omega_B, omega_E, u0, nparts, sig):
# invoke super init, passing nparts, dtype_u and dtype_f
super().__init__(((3, nparts), None, np.dtype('float64')))
self._makeAttributeAndRegister('nparts', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister('omega_B', 'omega_E', 'u0', 'sig', localVars=locals())
@staticmethod
@jit(nopython=True, nogil=True)
def fast_interactions(N, pos, sig, q):
Efield = np.zeros((3, N))
contrib = np.zeros(3)
for i in range(N):
contrib[:] = 0
for j in range(N):
dist2 = (
(pos[0, i] - pos[0, j]) ** 2
+ (pos[1, i] - pos[1, j]) ** 2
+ (pos[2, i] - pos[2, j]) ** 2
+ sig**2
)
contrib += q[j] * (pos[:, i] - pos[:, j]) / dist2**1.5
Efield[:, i] += contrib[:]
return Efield
def get_interactions(self, part):
"""
Routine to compute the particle-particle interaction, assuming q = 1 for all particles
Args:
part (dtype_u): the particles
Returns:
numpy.ndarray: the internal E field for each particle
"""
N = self.nparts
Efield = self.fast_interactions(N, part.pos, self.sig, part.q)
return Efield
def eval_f(self, part, t):
"""
Routine to compute the E and B fields (named f for consistency with the original PEPC version)
Args:
part (dtype_u): the particles
t (float): current time (not used here)
Returns:
dtype_f: Fields for the particles (internal and external)
"""
N = self.nparts
Emat = np.diag([1, 1, -2])
f = self.dtype_f(self.init)
f.elec[:] = self.get_interactions(part)
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
# TODO : Warning, this should be moved to u_exact(t=0) !
def u_init(self):
"""
Routine to compute the starting values for the particles
Returns:
dtype_u: particle set filled with initial data
"""
u0 = self.u0
N = self.nparts
u = self.dtype_u(self.init)
if u0[2][0] != 1 or u0[3][0] != 1:
raise ProblemError('so far only q = m = 1 is implemented')
# set first particle to u0
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[0] = u0[2][0]
u.m[0] = u0[3][0]
# initialize random seed
np.random.seed(N)
comx = u.pos[0, 0]
comy = u.pos[1, 0]
comz = u.pos[2, 0]
for n in range(1, N):
# draw 3 random variables in [-1,1] to shift positions
r = np.random.random_sample(3) - 1
u.pos[0, n] = r[0] + u0[0][0]
u.pos[1, n] = r[1] + u0[0][1]
u.pos[2, n] = r[2] + u0[0][2]
# draw 3 random variables in [-5,5] to shift velocities
r = np.random.random_sample(3) - 5
u.vel[0, n] = r[0] + u0[1][0]
u.vel[1, n] = r[1] + u0[1][1]
u.vel[2, n] = r[2] + u0[1][2]
u.q[n] = u0[2][0]
u.m[n] = u0[3][0]
# gather positions to check center
comx += u.pos[0, n]
comy += u.pos[1, n]
comz += u.pos[2, n]
# print('Center of positions:',comx/N,comy/N,comz/N)
return u
def u_exact(self, t):
"""
Routine to compute the exact trajectory at time t (only for single-particle setup)
Args:
t (float): current time
Returns:
dtype_u: particle type containing the exact position and velocity
"""
# some abbreviations
wE = self.omega_E
wB = self.omega_B
N = self.nparts
u0 = self.u0
if N != 1:
raise ProblemError('u_exact is only valid for a single particle')
u = self.dtype_u(((3, 1), self.init[1], self.init[2]))
wbar = np.sqrt(2) * wE
# position and velocity in z direction is easy to compute
u.pos[2, 0] = u0[0][2] * np.cos(wbar * t) + u0[1][2] / wbar * np.sin(wbar * t)
u.vel[2, 0] = -u0[0][2] * wbar * np.sin(wbar * t) + u0[1][2] * np.cos(wbar * t)
# define temp. variables to compute complex position
Op = 1 / 2 * (wB + np.sqrt(wB**2 - 4 * wE**2))
Om = 1 / 2 * (wB - np.sqrt(wB**2 - 4 * wE**2))
Rm = (Op * u0[0][0] + u0[1][1]) / (Op - Om)
Rp = u0[0][0] - Rm
Im = (Op * u0[0][1] - u0[1][0]) / (Op - Om)
Ip = u0[0][1] - Im
# compute position in complex notation
w = (Rp + Ip * 1j) * np.exp(-Op * t * 1j) + (Rm + Im * 1j) * np.exp(-Om * t * 1j)
# compute velocity as time derivative of the position
dw = -1j * Op * (Rp + Ip * 1j) * np.exp(-Op * t * 1j) - 1j * Om * (Rm + Im * 1j) * np.exp(-Om * t * 1j)
# get the appropriate real and imaginary parts
u.pos[0, 0] = w.real
u.vel[0, 0] = dw.real
u.pos[1, 0] = w.imag
u.vel[1, 0] = dw.imag
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 (dtype_f): the field values
part (dtype_u): the current particles data
t (float): the current time
Returns:
acceleration: correct RHS of type acceleration
"""
if not isinstance(part, particles):
raise ProblemError('something is wrong during build_f, got %s' % type(part))
N = self.nparts
rhs = acceleration(self.init)
for n in range(N):
rhs[:, n] = part.q[n] / part.m[n] * (f.elec[:, n] + np.cross(part.vel[:, n], f.magn[:, n]))
return rhs
# noinspection PyTypeChecker
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 (dtype_u): the c term gathering the known values from the previous iteration
dt (float): the (probably scaled) time step size
old_fields (dtype_f): the field values at the previous node m
new_fields (dtype_f): the field values at the current node m+1
old_parts (dtype_u): the particles at the previous node m
Returns:
the velocities at the (m+1)th node
"""
N = self.nparts
vel = particles.velocity(self.init)
Emean = 0.5 * (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
| 7,998 | 30.616601 | 112 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/VorticityVelocity_2D_FEniCS_periodic.py | import logging
import dolfin as df
import numpy as np
from pySDC.core.Errors import ParameterError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.fenics_mesh import fenics_mesh, rhs_fenics_mesh
# noinspection PyUnusedLocal
class fenics_vortex_2d(ptype):
"""
Example implementing the 2d vorticity-velocity equation with periodic BC in [0,1]
Attributes:
V: function space
M: mass matrix for FEM
K: stiffness matrix incl. diffusion coefficient (and correct sign)
"""
def __init__(self, problem_params, dtype_u=fenics_mesh, dtype_f=rhs_fenics_mesh):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: FEniCS mesh data type (will be passed to parent class)
dtype_f: FEniCS mesh data data type with implicit and explicit parts (will be passed to parent class)
"""
# Sub domain for Periodic boundary condition
class PeriodicBoundary(df.SubDomain):
# Left boundary is "target domain" G
def inside(self, x, on_boundary):
# return True if on left or bottom boundary AND NOT on one of the two corners (0, 1) and (1, 0)
return bool(
(df.near(x[0], 0) or df.near(x[1], 0))
and (not ((df.near(x[0], 0) and df.near(x[1], 1)) or (df.near(x[0], 1) and df.near(x[1], 0))))
and on_boundary
)
def map(self, x, y):
if df.near(x[0], 1) and df.near(x[1], 1):
y[0] = x[0] - 1.0
y[1] = x[1] - 1.0
elif df.near(x[0], 1):
y[0] = x[0] - 1.0
y[1] = x[1]
else: # near(x[1], 1)
y[0] = x[0]
y[1] = x[1] - 1.0
# these parameters will be used later, so assert their existence
essential_keys = ['c_nvars', 'family', 'order', 'refinements', 'nu', 'rho', 'delta']
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)
# set logger level for FFC and dolfin
df.set_log_level(df.WARNING)
logging.getLogger('FFC').setLevel(logging.WARNING)
# set solver and form parameters
df.parameters["form_compiler"]["optimize"] = True
df.parameters["form_compiler"]["cpp_optimize"] = True
# set mesh and refinement (for multilevel)
mesh = df.UnitSquareMesh(problem_params['c_nvars'][0], problem_params['c_nvars'][1])
for _ in range(problem_params['refinements']):
mesh = df.refine(mesh)
self.mesh = df.Mesh(mesh)
# define function space for future reference
self.V = df.FunctionSpace(
mesh, problem_params['family'], problem_params['order'], constrained_domain=PeriodicBoundary()
)
tmp = df.Function(self.V)
print('DoFs on this level:', len(tmp.vector().vector()[:]))
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(fenics_vortex_2d, self).__init__(self.V, dtype_u, dtype_f, problem_params)
w = df.TrialFunction(self.V)
v = df.TestFunction(self.V)
# Stiffness term (diffusion)
a_K = df.inner(df.nabla_grad(w), df.nabla_grad(v)) * df.dx
# Mass term
a_M = w * v * df.dx
self.M = df.assemble(a_M)
self.K = df.assemble(a_K)
def solve_system(self, rhs, factor, u0, t):
"""
Dolfin's linear solver for (M-dtA)u = rhs
Args:
rhs (dtype_f): right-hand side for the nonlinear 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
Returns:
dtype_u: solution as mesh
"""
A = self.M + self.nu * factor * self.K
b = self.__apply_mass_matrix(rhs)
u = self.dtype_u(u0)
df.solve(A, u.values.vector(), b.values.vector())
return u
def __eval_fexpl(self, u, t):
"""
Helper routine to evaluate the explicit part of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
explicit part of RHS
"""
A = 1.0 * self.K
b = self.__apply_mass_matrix(u)
psi = self.dtype_u(self.V)
df.solve(A, psi.values.vector(), b.values.vector())
fexpl = self.dtype_u(self.V)
fexpl.values = df.project(
df.Dx(psi.values, 1) * df.Dx(u.values, 0) - df.Dx(psi.values, 0) * df.Dx(u.values, 1), self.V
)
return fexpl
def __eval_fimpl(self, u, t):
"""
Helper routine to evaluate the implicit part of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
implicit part of RHS
"""
tmp = self.dtype_u(self.V)
tmp.values = df.Function(self.V, -1.0 * self.params.nu * self.K * u.values.vector())
fimpl = self.__invert_mass_matrix(tmp)
return fimpl
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS divided into two parts
"""
f = self.dtype_f(self.V)
f.impl = self.__eval_fimpl(u, t)
f.expl = self.__eval_fexpl(u, t)
return f
def __apply_mass_matrix(self, u):
"""
Routine to apply mass matrix
Args:
u (dtype_u): current values
Returns:
dtype_u: M*u
"""
me = self.dtype_u(self.V)
me.values = df.Function(self.V, self.M * u.values.vector())
return me
def __invert_mass_matrix(self, u):
"""
Helper routine to invert mass matrix
Args:
u (dtype_u): current values
Returns:
dtype_u: inv(M)*u
"""
me = self.dtype_u(self.V)
A = 1.0 * self.M
b = self.dtype_u(u)
df.solve(A, me.values.vector(), b.values.vector())
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
assert t == 0, 'ERROR: u_exact only valid for t=0'
w = df.Expression(
'r*(1-pow(tanh(r*((0.75-4) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-4))),2)) - \
r*(1-pow(tanh(r*((0.75-3) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-3))),2)) - \
r*(1-pow(tanh(r*((0.75-2) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-2))),2)) - \
r*(1-pow(tanh(r*((0.75-1) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-1))),2)) - \
r*(1-pow(tanh(r*((0.75-0) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-0))),2)) - \
r*(1-pow(tanh(r*((0.75+1) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25+1))),2)) - \
r*(1-pow(tanh(r*((0.75+2) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25+2))),2)) - \
r*(1-pow(tanh(r*((0.75+3) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25+3))),2)) - \
r*(1-pow(tanh(r*((0.75+4) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25+4))),2)) - \
d*2*a*cos(2*a*(x[0]+0.25))',
d=self.params.delta,
r=self.params.rho,
a=np.pi,
degree=self.params.order,
)
me = self.dtype_u(self.V)
me.values = df.interpolate(w, self.V)
# df.plot(me.values)
# df.interactive()
# exit()
return me
| 8,165 | 31.404762 | 114 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/HeatEquation_1D_FEniCS_weak_forced.py | import logging
import dolfin as df
import numpy as np
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.fenics_mesh import fenics_mesh, rhs_fenics_mesh
# noinspection PyUnusedLocal
class fenics_heat_weak_fullyimplicit(ptype):
"""
Example implementing the forced 1D heat equation with Dirichlet-0 BC in [0,1], weak formulation
Attributes:
V: function space
w: function for weak form
a_K: weak form of RHS (incl. BC)
M: mass matrix for FEM
g: forcing term
bc: boundary conditions
"""
dtype_u = fenics_mesh
dtype_f = fenics_mesh
def __init__(self, c_nvars, t0, family, order, refinements, nu):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: FEniCS mesh data type (will be passed to parent class)
dtype_f: FEniCS mesh data type (will be passed to parent class)
"""
# define the Dirichlet boundary
def Boundary(x, on_boundary):
return on_boundary
# these parameters will be used later, so assert their existence
essential_keys = ['c_nvars', 't0', 'family', 'order', 'refinements', 'nu']
# set logger level for FFC and dolfin
logging.getLogger('ULF').setLevel(logging.WARNING)
logging.getLogger('FFC').setLevel(logging.WARNING)
df.set_log_level(30)
# set solver and form parameters
df.parameters["form_compiler"]["optimize"] = True
df.parameters["form_compiler"]["cpp_optimize"] = True
# set mesh and refinement (for multilevel)
mesh = df.UnitIntervalMesh(c_nvars)
for _ in range(refinements):
mesh = df.refine(mesh)
# define function space for future reference
self.V = df.FunctionSpace(mesh, family, order)
tmp = df.Function(self.V)
print('DoFs on this level:', len(tmp.vector()[:]))
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(fenics_heat_weak_fullyimplicit, self).__init__(self.V)
self._makeAttributeAndRegister(
'c_nvars', 't0', 'family', 'order', 'refinements', 'nu', localVars=locals(), readOnly=True
)
self.g = df.Expression(
'-sin(a*x[0]) * (sin(t) - b*a*a*cos(t))',
a=np.pi,
b=self.nu,
t=self.t0,
degree=self.order,
)
# rhs in weak form
self.w = df.Function(self.V)
v = df.TestFunction(self.V)
self.a_K = -self.nu * df.inner(df.nabla_grad(self.w), df.nabla_grad(v)) * df.dx + self.g * v * df.dx
# mass matrix
u = df.TrialFunction(self.V)
a_M = u * v * df.dx
self.M = df.assemble(a_M)
self.bc = df.DirichletBC(self.V, df.Constant(0.0), Boundary)
def __invert_mass_matrix(self, u):
"""
Helper routine to invert mass matrix
Args:
u (dtype_u): current values
Returns:
dtype_u: inv(M)*u
"""
me = self.dtype_u(self.V)
A = 1.0 * self.M
b = self.dtype_u(u)
self.bc.apply(A, b.values.vector())
df.solve(A, me.values.vector(), b.values.vector())
return me
def solve_system(self, rhs, factor, u0, t):
"""
Dolfin's weak solver for (M-dtA)u = rhs
Args:
rhs (dtype_f): right-hand side for the nonlinear 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
Returns:
dtype_u: solution as mesh
"""
sol = self.dtype_u(self.V)
self.g.t = t
self.w.assign(sol.values)
v = df.TestFunction(self.V)
F = self.w * v * df.dx - factor * self.a_K - rhs.values * v * df.dx
du = df.TrialFunction(self.V)
J = df.derivative(F, self.w, du)
problem = df.NonlinearVariationalProblem(F, self.w, self.bc, J)
solver = df.NonlinearVariationalSolver(problem)
prm = solver.parameters
prm['newton_solver']['absolute_tolerance'] = 1e-12
prm['newton_solver']['relative_tolerance'] = 1e-12
prm['newton_solver']['maximum_iterations'] = 25
prm['newton_solver']['relaxation_parameter'] = 1.0
# df.set_log_level(df.PROGRESS)
solver.solve()
sol.values.assign(self.w)
return sol
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS divided into two parts
"""
self.g.t = t
f = self.dtype_f(self.V)
self.w.assign(u.values)
f.values = df.Function(self.V, df.assemble(self.a_K))
f = self.__invert_mass_matrix(f)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
u0 = df.Expression('sin(a*x[0]) * cos(t)', a=np.pi, t=t, degree=self.order)
me = self.dtype_u(self.V)
me.values = df.interpolate(u0, self.V)
return me
class fenics_heat_weak_imex(ptype):
"""
Example implementing the forced 1D heat equation with Dirichlet-0 BC in [0,1], weak formulation, IMEX
Attributes:
V: function space
w: function for weak form
a_K: weak form of RHS (incl. BC)
M: mass matrix for FEM
g: forcing term
bc: boundary conditions
"""
dtype_u = fenics_mesh
dtype_f = rhs_fenics_mesh
def __init__(self, c_nvars, t0, family, order, refinements, nu):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: particle data type (will be passed parent class)
dtype_f: acceleration data type (will be passed parent class)
"""
# define the Dirichlet boundary
def Boundary(x, on_boundary):
return on_boundary
# set logger level for FFC and dolfin
logging.getLogger('ULF').setLevel(logging.WARNING)
logging.getLogger('FFC').setLevel(logging.WARNING)
df.set_log_level(30)
# set solver and form parameters
df.parameters["form_compiler"]["optimize"] = True
df.parameters["form_compiler"]["cpp_optimize"] = True
# set mesh and refinement (for multilevel)
mesh = df.UnitIntervalMesh(c_nvars)
for _ in range(refinements):
mesh = df.refine(mesh)
# define function space for future reference
self.V = df.FunctionSpace(mesh, family, order)
tmp = df.Function(self.V)
print('DoFs on this level:', len(tmp.vector()[:]))
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(fenics_heat_weak_imex, self).__init__(self.V)
self._makeAttributeAndRegister(
'c_nvars', 't0', 'family', 'order', 'refinements', 'nu', localVars=locals(), readOnly=True
)
self.g = df.Expression(
'-sin(a*x[0]) * (sin(t) - b*a*a*cos(t))',
a=np.pi,
b=self.nu,
t=self.t0,
degree=self.order,
)
# rhs in weak form
self.u = df.TrialFunction(self.V)
self.v = df.TestFunction(self.V)
self.a_K = -self.nu * df.inner(df.grad(self.u), df.grad(self.v)) * df.dx
# mass matrix
a_M = self.u * self.v * df.dx
self.M = df.assemble(a_M)
self.bc = df.DirichletBC(self.V, df.Constant(0.0), Boundary)
def __invert_mass_matrix(self, u):
"""
Helper routine to invert mass matrix
Args:
u (dtype_u): current values
Returns:
dtype_u: inv(M)*u
"""
me = self.dtype_u(self.V)
b = self.dtype_u(u)
self.bc.apply(self.M, b.values.vector())
df.solve(self.M, me.values.vector(), b.values.vector())
return me
def solve_system(self, rhs, factor, u0, t):
"""
Dolfin's weak solver for (M-dtA)u = rhs
Args:
rhs (dtype_f): right-hand side for the nonlinear 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
Returns:
dtype_u: solution as mesh
"""
sol = self.dtype_u(u0)
df.solve(self.u * self.v * df.dx - factor * self.a_K == rhs.values * self.v * df.dx, sol.values, self.bc)
return sol
def __eval_fexpl(self, u, t):
"""
Helper routine to evaluate the explicit part of the RHS
Args:
u (dtype_u): current values (not used here)
t (fliat): current time
Returns:
explicit part of RHS
"""
self.g.t = t
fexpl = self.dtype_u(df.interpolate(self.g, self.V))
return fexpl
def __eval_fimpl(self, u, t):
"""
Helper routine to evaluate the implicit part of the RHS
Args:
u (dtype_u): current values
t (float): current time (not used here)
Returns:
implicit part of RHS
"""
tmp = self.dtype_u(self.V)
tmp.values.vector()[:] = df.assemble(-self.nu * df.inner(df.grad(u.values), df.grad(self.v)) * df.dx)
fimpl = self.__invert_mass_matrix(tmp)
return fimpl
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u (dtype_u): current values
t (float): current time
Returns:
dtype_f: the RHS divided into two parts
"""
f = self.dtype_f(self.V)
f.impl = self.__eval_fimpl(u, t)
f.expl = self.__eval_fexpl(u, t)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
u0 = df.Expression('sin(a*x[0]) * cos(t)', a=np.pi, t=t, degree=self.order)
me = self.dtype_u(df.interpolate(u0, self.V))
return me
| 10,617 | 27.239362 | 113 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/LogisticEquation.py | import numpy as np
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh
# noinspection PyUnusedLocal
class logistics_equation(ptype):
r"""
Problem implementing a specific form of the Logistic Differential Equation
.. math::
\frac{du}{dt} = \lambda u(t)(1-u(t))
with :math:`\lambda` a given real coefficient. Its analytical solution is :
.. math::
u(t) = u(0) \frac{e^{\lambda t}}{1-u(0)+u(0)e^{\lambda t}}
"""
dtype_u = mesh
dtype_f = mesh
def __init__(self, u0, newton_maxiter, newton_tol, direct, lam=1, stop_at_nan=True):
nvars = 1
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister(
'u0',
'lam',
'newton_maxiter',
'newton_tol',
'direct',
'nvars',
'stop_at_nan',
localVars=locals(),
readOnly=True,
)
def u_exact(self, t):
"""
Exact solution
Args:
t (float): current time
Returns:
dtype_u: mesh type containing the values
"""
me = self.dtype_u(self.init)
me[:] = self.u0 * np.exp(self.lam * t) / (1 - self.u0 + self.u0 * np.exp(self.lam * t))
return me
def eval_f(self, u, t):
"""
Routine to compute the RHS
Args:
u (dtype_u): the current values
t (float): current time (not used here)
Returns:
dtype_f: RHS, 1 component
"""
f = self.dtype_f(self.init)
f[:] = self.lam * u * (1 - u)
return f
def solve_system(self, rhs, dt, u0, t):
"""
Simple Newton solver for the nonlinear equation
Args:
rhs (dtype_f): right-hand side for the nonlinear system
dt (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution u
"""
# create new mesh object from u0 and set initial values for iteration
u = self.dtype_u(u0)
if self.direct:
d = (1 - dt * self.lam) ** 2 + 4 * dt * self.lam * rhs
u = (-(1 - dt * self.lam) + np.sqrt(d)) / (2 * dt * self.lam)
return u
else:
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - dt * self.lam * u * (1 - u) - rhs
# if g is close to 0, then we are done
res = np.linalg.norm(g, np.inf)
if res < self.newton_tol or np.isnan(res):
break
# assemble dg/du
dg = 1 - dt * self.lam * (1 - 2 * u)
# newton update: u1 = u0 - g/dg
u -= 1.0 / dg * g
# increase iteration count
n += 1
if np.isnan(res) and self.stop_at_nan:
raise ProblemError('Newton got nan after %i iterations, aborting...' % n)
elif np.isnan(res):
self.logger.warning('Newton got nan after %i iterations...' % n)
if n == self.newton_maxiter:
raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
return u
| 3,588 | 28.661157 | 105 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AllenCahn_2D_FD_gpu.py | import numpy as np
import cupy as cp
import cupyx.scipy.sparse as csp
from cupyx.scipy.sparse.linalg import cg # , spsolve, gmres, minres
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.cupy_mesh import cupy_mesh, imex_cupy_mesh, comp2_cupy_mesh
# http://www.personal.psu.edu/qud2/Res/Pre/dz09sisc.pdf
class allencahn_fullyimplicit(ptype): # pragma: no cover
"""
Example implementing the Allen-Cahn equation in 2D with finite differences and periodic BC
Attributes:
A: second-order FD discretization of the 2D laplace operator
dx: distance between two spatial nodes (same for both directions)
"""
dtype_u = cupy_mesh
dtype_f = cupy_mesh
def __init__(self, nvars, nu, eps, newton_maxiter, newton_tol, lin_tol, lin_maxiter, radius):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: cupy_mesh data type (will be passed parent class)
dtype_f: cupy_mesh data type (will be passed parent class)
"""
# we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on
if len(nvars) != 2:
raise ProblemError('this is a 2d example, got %s' % nvars)
if nvars[0] != nvars[1]:
raise ProblemError('need a square domain, got %s' % nvars)
if 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().__init__((nvars, None, cp.dtype('float64')))
self._makeAttributeAndRegister(
'nvars',
'nu',
'eps',
'newton_maxiter',
'newton_tol',
'lin_tol',
'lin_maxiter',
'radius',
localVars=locals(),
readOnly=True,
)
# compute dx and get discretization matrix A
self.dx = 1.0 / self.nvars[0]
self.A = self.__get_A(self.nvars, self.dx)
self.xvalues = cp.array([i * self.dx - 0.5 for i in range(self.nvars[0])])
self.newton_itercount = 0
self.lin_itercount = 0
self.newton_ncalls = 0
self.lin_ncalls = 0
@staticmethod
def __get_A(N, dx):
"""
Helper function to assemble FD matrix A in sparse format
Args:
N (list): number of dofs
dx (float): distance between two spatial nodes
Returns:
cupyx.scipy.sparse.csr_matrix: cupy-matrix A in CSR format
"""
stencil = cp.asarray([-2, 1])
A = stencil[0] * csp.eye(N[0], format='csr')
for i in range(1, len(stencil)):
A += stencil[i] * csp.eye(N[0], k=-i, format='csr')
A += stencil[i] * csp.eye(N[0], k=+i, format='csr')
A += stencil[i] * csp.eye(N[0], k=N[0] - i, format='csr')
A += stencil[i] * csp.eye(N[0], k=-N[0] + i, format='csr')
A = csp.kron(A, csp.eye(N[0])) + csp.kron(csp.eye(N[1]), A)
A *= 1.0 / (dx**2)
return A
# noinspection PyTypeChecker
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0).flatten()
z = self.dtype_u(self.init, val=0.0).flatten()
nu = self.nu
eps2 = self.eps**2
Id = csp.eye(self.nvars[0] * self.nvars[1])
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - factor * (self.A.dot(u) + 1.0 / eps2 * u * (1.0 - u**nu)) - rhs.flatten()
# if g is close to 0, then we are done
res = cp.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (self.A + 1.0 / eps2 * csp.diags((1.0 - (nu + 1) * u**nu), offsets=0))
# newton update: u1 = u0 - g/dg
# u -= spsolve(dg, g)
u -= cg(dg, g, x0=z, tol=self.lin_tol)[0]
# increase iteration count
n += 1
# print(n, res)
# if n == self.newton_maxiter:
# raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
me = self.dtype_u(self.init)
me[:] = u.reshape(self.nvars)
self.newton_ncalls += 1
self.newton_itercount += n
return me
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()
f[:] = (self.A.dot(v) + 1.0 / self.eps**2 * v * (1.0 - v**self.nu)).reshape(self.nvars)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
assert t == 0, 'ERROR: u_exact only valid for t=0'
me = self.dtype_u(self.init, val=0.0)
mx, my = cp.meshgrid(self.xvalues, self.xvalues)
me[:] = cp.tanh((self.radius - cp.sqrt(mx**2 + my**2)) / (cp.sqrt(2) * self.eps))
# print(type(me))
return me
# noinspection PyUnusedLocal
class allencahn_semiimplicit(allencahn_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 2D with finite differences, SDC standard splitting
"""
dtype_f = imex_cupy_mesh
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()
f.impl[:] = self.A.dot(v).reshape(self.nvars)
f.expl[:] = (1.0 / self.eps**2 * v * (1.0 - v**self.nu)).reshape(self.nvars)
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
class context:
num_iter = 0
def callback(xk):
context.num_iter += 1
return context.num_iter
me = self.dtype_u(self.init)
Id = csp.eye(self.nvars[0] * self.nvars[1])
me[:] = cg(
Id - factor * self.A,
rhs.flatten(),
x0=u0.flatten(),
tol=self.lin_tol,
maxiter=self.lin_maxiter,
callback=callback,
)[0].reshape(self.nvars)
self.lin_ncalls += 1
self.lin_itercount += context.num_iter
return me
# noinspection PyUnusedLocal
class allencahn_semiimplicit_v2(allencahn_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting
"""
dtype_f = imex_cupy_mesh
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()
f.impl[:] = (self.A.dot(v) - 1.0 / self.eps**2 * v ** (self.nu + 1)).reshape(self.nvars)
f.expl[:] = (1.0 / self.eps**2 * v).reshape(self.nvars)
return f
def solve_system(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0).flatten()
z = self.dtype_u(self.init, val=0.0).flatten()
nu = self.nu
eps2 = self.eps**2
Id = csp.eye(self.nvars[0] * self.nvars[1])
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - factor * (self.A.dot(u) - 1.0 / eps2 * u ** (nu + 1)) - rhs.flatten()
# if g is close to 0, then we are done
res = cp.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (self.A - 1.0 / eps2 * csp.diags(((nu + 1) * u**nu), offsets=0))
# newton update: u1 = u0 - g/dg
# u -= spsolve(dg, g)
u -= cg(dg, g, x0=z, tol=self.lin_tol)[0]
# increase iteration count
n += 1
# print(n, res)
# if n == self.newton_maxiter:
# raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
me = self.dtype_u(self.init)
me[:] = u.reshape(self.nvars)
self.newton_ncalls += 1
self.newton_itercount += n
return me
# noinspection PyUnusedLocal
class allencahn_multiimplicit(allencahn_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 2D with finite differences, SDC standard splitting
"""
dtype_f = comp2_cupy_mesh
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()
f.comp1[:] = self.A.dot(v).reshape(self.nvars)
f.comp2[:] = (1.0 / self.eps**2 * v * (1.0 - v**self.nu)).reshape(self.nvars)
return f
def solve_system_1(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
class context:
num_iter = 0
def callback(xk):
context.num_iter += 1
return context.num_iter
me = self.dtype_u(self.init)
Id = csp.eye(self.nvars[0] * self.nvars[1])
me[:] = cg(
Id - factor * self.A,
rhs.flatten(),
x0=u0.flatten(),
tol=self.lin_tol,
maxiter=self.lin_maxiter,
callback=callback,
)[0].reshape(self.nvars)
self.lin_ncalls += 1
self.lin_itercount += context.num_iter
return me
def solve_system_2(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0).flatten()
z = self.dtype_u(self.init, val=0.0).flatten()
nu = self.nu
eps2 = self.eps**2
Id = csp.eye(self.nvars[0] * self.nvars[1])
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - factor * (1.0 / eps2 * u * (1.0 - u**nu)) - rhs.flatten()
# if g is close to 0, then we are done
res = cp.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (1.0 / eps2 * csp.diags((1.0 - (nu + 1) * u**nu), offsets=0))
# newton update: u1 = u0 - g/dg
# u -= spsolve(dg, g)
u -= cg(dg, g, x0=z, tol=self.lin_tol)[0]
# increase iteration count
n += 1
# print(n, res)
# if n == self.newton_maxiter:
# raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
me = self.dtype_u(self.init)
me[:] = u.reshape(self.nvars)
self.newton_ncalls += 1
self.newton_itercount += n
return me
# noinspection PyUnusedLocal
class allencahn_multiimplicit_v2(allencahn_fullyimplicit):
"""
Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting
"""
dtype_f = comp2_cupy_mesh
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()
f.comp1[:] = (self.A.dot(v) - 1.0 / self.eps**2 * v ** (self.nu + 1)).reshape(self.nvars)
f.comp2[:] = (1.0 / self.eps**2 * v).reshape(self.nvars)
return f
def solve_system_1(self, rhs, factor, u0, t):
"""
Simple Newton solver
Args:
rhs (dtype_f): right-hand side for the nonlinear system
factor (float): abbrev. for the node-to-node stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (required here for the BC)
Returns:
dtype_u: solution u
"""
u = self.dtype_u(u0).flatten()
z = self.dtype_u(self.init, val=0.0).flatten()
nu = self.nu
eps2 = self.eps**2
Id = csp.eye(self.nvars[0] * self.nvars[1])
# start newton iteration
n = 0
res = 99
while n < self.newton_maxiter:
# form the function g with g(u) = 0
g = u - factor * (self.A.dot(u) - 1.0 / eps2 * u ** (nu + 1)) - rhs.flatten()
# if g is close to 0, then we are done
res = cp.linalg.norm(g, np.inf)
if res < self.newton_tol:
break
# assemble dg
dg = Id - factor * (self.A - 1.0 / eps2 * csp.diags(((nu + 1) * u**nu), offsets=0))
# newton update: u1 = u0 - g/dg
# u -= spsolve(dg, g)
u -= cg(dg, g, x0=z, tol=self.lin_tol)[0]
# increase iteration count
n += 1
# print(n, res)
# if n == self.newton_maxiter:
# raise ProblemError('Newton did not converge after %i iterations, error is %s' % (n, res))
me = self.dtype_u(self.init)
me[:] = u.reshape(self.nvars)
self.newton_ncalls += 1
self.newton_itercount += n
return me
def solve_system_2(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-factor*A)u = rhs
Args:
rhs (dtype_f): right-hand side for the linear system
factor (float): abbrev. for the local stepsize (or any other factor required)
u0 (dtype_u): initial guess for the iterative solver
t (float): current time (e.g. for time-dependent BCs)
Returns:
dtype_u: solution as mesh
"""
me = self.dtype_u(self.init)
me[:] = (1.0 / (1.0 - factor * 1.0 / self.eps**2) * rhs).reshape(self.nvars)
return me
| 16,456 | 28.867514 | 115 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/AllenCahn_Temp_MPIFFT.py | import numpy as np
from mpi4py_fft import PFFT
from pySDC.core.Errors import ProblemError
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
from mpi4py_fft import newDistArray
class allencahn_temp_imex(ptype):
"""
Example implementing Allen-Cahn equation in 2-3D using mpi4py-fft for solving linear parts, IMEX time-stepping
mpi4py-fft: https://mpi4py-fft.readthedocs.io/en/latest/
Attributes:
fft: fft object
X: grid coordinates in real space
K2: Laplace operator in spectral space
dx: mesh width in x direction
dy: mesh width in y direction
"""
dtype_u = mesh
dtype_f = imex_mesh
def __init__(self, nvars, eps, radius, spectral, TM, D, dw=0.0, L=1.0, init_type='circle', comm=None):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: fft data type (will be passed to parent class)
dtype_f: fft data type wuth implicit and explicit parts (will be passed to parent class)
"""
if not (isinstance(nvars, tuple) and len(nvars) > 1):
raise ProblemError('Need at least two dimensions')
# creating FFT structure
ndim = len(nvars)
axes = tuple(range(ndim))
self.fft = PFFT(comm, list(nvars), axes=axes, dtype=np.float64, collapse=True)
# get test data to figure out type and dimensions
tmp_u = newDistArray(self.fft, spectral)
# add two components to contain field and temperature
self.ncomp = 2
sizes = tmp_u.shape + (self.ncomp,)
# invoke super init, passing the communicator and the local dimensions as init
super().__init__(init=(sizes, comm, tmp_u.dtype))
self._makeAttributeAndRegister(
'nvars',
'eps',
'radius',
'spectral',
'TM',
'D',
'dw',
'L',
'init_type',
'comm',
localVars=locals(),
readOnly=True,
)
L = np.array([self.L] * ndim, dtype=float)
# get local mesh
X = np.ogrid[self.fft.local_slice(False)]
N = self.fft.global_shape()
for i in range(len(N)):
X[i] = X[i] * L[i] / N[i]
self.X = [np.broadcast_to(x, self.fft.shape(False)) for x in X]
# get local wavenumbers and Laplace operator
s = self.fft.local_slice()
N = self.fft.global_shape()
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)
K = [np.broadcast_to(k, self.fft.shape(True)) for k in Ks]
K = np.array(K).astype(float)
self.K2 = np.sum(K * K, 0, dtype=float)
# Need this for diagnostics
self.dx = self.L / nvars[0]
self.dy = self.L / nvars[1]
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)
if self.spectral:
f.impl[..., 0] = -self.K2 * u[..., 0]
if self.eps > 0:
tmp_u = newDistArray(self.fft, False)
tmp_T = newDistArray(self.fft, False)
tmp_u = self.fft.backward(u[..., 0], tmp_u)
tmp_T = self.fft.backward(u[..., 1], tmp_T)
tmpf = -2.0 / self.eps**2 * tmp_u * (1.0 - tmp_u) * (1.0 - 2.0 * tmp_u) - 6.0 * self.dw * (
tmp_T - self.TM
) / self.TM * tmp_u * (1.0 - tmp_u)
f.expl[..., 0] = self.fft.forward(tmpf)
f.impl[..., 1] = -self.D * self.K2 * u[..., 1]
f.expl[..., 1] = f.impl[..., 0] + f.expl[..., 0]
else:
u_hat = self.fft.forward(u[..., 0])
lap_u_hat = -self.K2 * u_hat
f.impl[..., 0] = self.fft.backward(lap_u_hat, f.impl[..., 0])
if self.eps > 0:
f.expl[..., 0] = -2.0 / self.eps**2 * u[..., 0] * (1.0 - u[..., 0]) * (1.0 - 2.0 * u[..., 0])
f.expl[..., 0] -= 6.0 * self.dw * (u[..., 1] - self.TM) / self.TM * u[..., 0] * (1.0 - u[..., 0])
u_hat = self.fft.forward(u[..., 1])
lap_u_hat = -self.D * self.K2 * u_hat
f.impl[..., 1] = self.fft.backward(lap_u_hat, f.impl[..., 1])
f.expl[..., 1] = f.impl[..., 0] + f.expl[..., 0]
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
"""
if self.spectral:
me = self.dtype_u(self.init)
me[..., 0] = rhs[..., 0] / (1.0 + factor * self.K2)
me[..., 1] = rhs[..., 1] / (1.0 + factor * self.D * self.K2)
else:
me = self.dtype_u(self.init)
rhs_hat = self.fft.forward(rhs[..., 0])
rhs_hat /= 1.0 + factor * self.K2
me[..., 0] = self.fft.backward(rhs_hat)
rhs_hat = self.fft.forward(rhs[..., 1])
rhs_hat /= 1.0 + factor * self.D * self.K2
me[..., 1] = self.fft.backward(rhs_hat)
return me
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
def circle():
tmp_me = newDistArray(self.fft, self.spectral)
r2 = (self.X[0] - 0.5) ** 2 + (self.X[1] - 0.5) ** 2
if self.spectral:
tmp = 0.5 * (1.0 + np.tanh((self.radius - np.sqrt(r2)) / (np.sqrt(2) * self.eps)))
tmp_me[:] = self.fft.forward(tmp)
else:
tmp_me[:] = 0.5 * (1.0 + np.tanh((self.radius - np.sqrt(r2)) / (np.sqrt(2) * self.eps)))
return tmp_me
def circle_rand():
tmp_me = newDistArray(self.fft, self.spectral)
ndim = len(tmp_me.shape)
L = int(self.L)
# get random radii for circles/spheres
np.random.seed(1)
lbound = 3.0 * self.eps
ubound = 0.5 - self.eps
rand_radii = (ubound - lbound) * np.random.random_sample(size=tuple([L] * ndim)) + lbound
# distribute circles/spheres
tmp = newDistArray(self.fft, False)
if ndim == 2:
for i in range(0, L):
for j in range(0, L):
# build radius
r2 = (self.X[0] + i - L + 0.5) ** 2 + (self.X[1] + j - L + 0.5) ** 2
# add this blob, shifted by 1 to avoid issues with adding up negative contributions
tmp += np.tanh((rand_radii[i, j] - np.sqrt(r2)) / (np.sqrt(2) * self.eps)) + 1
# normalize to [0,1]
tmp *= 0.5
assert np.all(tmp <= 1.0)
if self.spectral:
tmp_me[:] = self.fft.forward(tmp)
else:
tmp_me[:] = tmp[:]
return tmp_me
def sine():
tmp_me = newDistArray(self.fft, self.spectral)
if self.spectral:
tmp = 0.5 * (2.0 + 0.0 * np.sin(2 * np.pi * self.X[0]) * np.sin(2 * np.pi * self.X[1]))
tmp_me[:] = self.fft.forward(tmp)
else:
tmp_me[:] = 0.5 * (2.0 + 0.0 * np.sin(2 * np.pi * self.X[0]) * np.sin(2 * np.pi * self.X[1]))
return tmp_me
assert t == 0, 'ERROR: u_exact only valid for t=0'
me = self.dtype_u(self.init, val=0.0)
if self.init_type == 'circle':
me[..., 0] = circle()
me[..., 1] = sine()
elif self.init_type == 'circle_rand':
me[..., 0] = circle_rand()
me[..., 1] = sine()
else:
raise NotImplementedError('type of initial value not implemented, got %s' % self.init_type)
return me
# class allencahn_temp_imex_timeforcing(allencahn_temp_imex):
# """
# Example implementing Allen-Cahn equation in 2-3D using mpi4py-fft for solving linear parts, IMEX time-stepping,
# time-dependent forcing
# """
#
# 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)
#
# if self.spectral:
#
# f.impl = -self.K2 * u
#
# tmp = newDistArray(self.fft, False)
# tmp[:] = self.fft.backward(u, tmp)
#
# if self.eps > 0:
# tmpf = -2.0 / self.eps ** 2 * tmp * (1.0 - tmp) * (1.0 - 2.0 * tmp)
# else:
# tmpf = self.dtype_f(self.init, val=0.0)
#
# # build sum over RHS without driving force
# Rt_local = float(np.sum(self.fft.backward(f.impl) + tmpf))
# if self.comm is not None:
# Rt_global = self.comm.allreduce(sendobj=Rt_local, op=MPI.SUM)
# else:
# Rt_global = Rt_local
#
# # build sum over driving force term
# Ht_local = float(np.sum(6.0 * tmp * (1.0 - tmp)))
# if self.comm is not None:
# Ht_global = self.comm.allreduce(sendobj=Ht_local, op=MPI.SUM)
# else:
# Ht_global = Rt_local
#
# # add/substract time-dependent driving force
# if Ht_global != 0.0:
# dw = Rt_global / Ht_global
# else:
# dw = 0.0
#
# tmpf -= 6.0 * dw * tmp * (1.0 - tmp)
# f.expl[:] = self.fft.forward(tmpf)
#
# else:
#
# u_hat = self.fft.forward(u)
# lap_u_hat = -self.K2 * u_hat
# f.impl[:] = self.fft.backward(lap_u_hat, f.impl)
#
# if self.eps > 0:
# f.expl = -2.0 / self.eps ** 2 * u * (1.0 - u) * (1.0 - 2.0 * u)
#
# # build sum over RHS without driving force
# Rt_local = float(np.sum(f.impl + f.expl))
# if self.comm is not None:
# Rt_global = self.comm.allreduce(sendobj=Rt_local, op=MPI.SUM)
# else:
# Rt_global = Rt_local
#
# # build sum over driving force term
# Ht_local = float(np.sum(6.0 * u * (1.0 - u)))
# if self.comm is not None:
# Ht_global = self.comm.allreduce(sendobj=Ht_local, op=MPI.SUM)
# else:
# Ht_global = Rt_local
#
# # add/substract time-dependent driving force
# if Ht_global != 0.0:
# dw = Rt_global / Ht_global
# else:
# dw = 0.0
#
# f.expl -= 6.0 * dw * u * (1.0 - u)
#
# return f
| 11,601 | 34.157576 | 117 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/FullSolarSystem.py | import numpy as np
from pySDC.implementations.datatype_classes.particles import particles, acceleration
from pySDC.implementations.problem_classes.OuterSolarSystem import outer_solar_system
# noinspection PyUnusedLocal
class full_solar_system(outer_solar_system):
"""
Example implementing the full solar system problem
"""
dtype_u = particles
dtype_f = acceleration
def __init__(self, sun_only=False):
"""Initialization routine"""
super().__init__(sun_only)
self.init = ((3, 10), None, np.dtype('float64'))
def u_exact(self, t):
"""
Routine to compute the exact/initial trajectory at time t
Args:
t (float): current time
Returns:
dtype_u: exact/initial position and velocity
"""
assert t == 0.0, 'error, u_exact only works for the initial time t0=0'
me = self.dtype_u(self.init)
# initial positions and velocities taken from
# https://www.aanda.org/articles/aa/full/2002/08/aa1405/aa1405.right.html
me.pos[:, 0] = [0.0, 0.0, 0.0]
me.pos[:, 1] = [-2.503321047836e-01, +1.873217481656e-01, +1.260230112145e-01]
me.pos[:, 2] = [+1.747780055994e-02, -6.624210296743e-01, -2.991203277122e-01]
me.pos[:, 3] = [-9.091916173950e-01, +3.592925969244e-01, +1.557729610506e-01]
me.pos[:, 4] = [+1.203018828754e00, +7.270712989688e-01, +3.009561427569e-01]
me.pos[:, 5] = [+3.733076999471e00, +3.052424824299e00, +1.217426663570e00]
me.pos[:, 6] = [+6.164433062913e00, +6.366775402981e00, +2.364531109847e00]
me.pos[:, 7] = [+1.457964661868e01, -1.236891078519e01, -5.623617280033e00]
me.pos[:, 8] = [+1.695491139909e01, -2.288713988623e01, -9.789921035251e00]
me.pos[:, 9] = [-9.707098450131e00, -2.804098175319e01, -5.823808919246e00]
me.vel[:, 0] = [0.0, 0.0, 0.0]
me.vel[:, 1] = [-2.438808424736e-02, -1.850224608274e-02, -7.353811537540e-03]
me.vel[:, 2] = [+2.008547034175e-02, +8.365454832702e-04, -8.947888514893e-04]
me.vel[:, 3] = [-7.085843239142e-03, -1.455634327653e-02, -6.310912842359e-03]
me.vel[:, 4] = [-7.124453943885e-03, +1.166307407692e-02, +5.542098698449e-03]
me.vel[:, 5] = [-5.086540617947e-03, +5.493643783389e-03, +2.478685100749e-03]
me.vel[:, 6] = [-4.426823593779e-03, +3.394060157503e-03, +1.592261423092e-03]
me.vel[:, 7] = [+2.647505630327e-03, +2.487457379099e-03, +1.052000252243e-03]
me.vel[:, 8] = [+2.568651772461e-03, +1.681832388267e-03, +6.245613982833e-04]
me.vel[:, 9] = [+3.034112963576e-03, -1.111317562971e-03, -1.261841468083e-03]
# masses relative to the sun taken from
# https://en.wikipedia.org/wiki/Planetary_mass#Values_from_the_DE405_ephemeris
me.m[0] = 1.0 # Sun
me.m[1] = 0.1660100 * 1e-06 # Mercury
me.m[2] = 2.4478383 * 1e-06 # Venus
me.m[3] = 3.0404326 * 1e-06 # Earth+Moon
me.m[4] = 0.3227151 * 1e-06 # Mars
me.m[5] = 954.79194 * 1e-06 # Jupiter
me.m[6] = 285.88600 * 1e-06 # Saturn
me.m[7] = 43.662440 * 1e-06 # Uranus
me.m[8] = 51.513890 * 1e-06 # Neptune
me.m[9] = 0.0073960 * 1e-06 # Pluto
return me
| 3,286 | 44.652778 | 86 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/boussinesq_helpers/buildFDMatrix.py | import sys
import numpy as np
import scipy.linalg as la
import scipy.sparse as sp
# Only for periodic BC because we have advection only in x direction
def getUpwindMatrix(N, dx, order):
if order == 1:
stencil = [-1.0, 1.0]
zero_pos = 2
coeff = 1.0
elif order == 2:
stencil = [1.0, -4.0, 3.0]
coeff = 1.0 / 2.0
zero_pos = 3
elif order == 3:
stencil = [1.0, -6.0, 3.0, 2.0]
coeff = 1.0 / 6.0
zero_pos = 3
elif order == 4:
stencil = [-5.0, 30.0, -90.0, 50.0, 15.0]
coeff = 1.0 / 60.0
zero_pos = 4
elif order == 5:
stencil = [3.0, -20.0, 60.0, -120.0, 65.0, 12.0]
coeff = 1.0 / 60.0
zero_pos = 5
else:
sys.exit('Order ' + str(order) + ' not implemented')
first_col = np.zeros(N)
# Because we need to specific first column (not row) in circulant, flip stencil array
first_col[0 : np.size(stencil)] = np.flipud(stencil)
# Circulant shift of coefficient column so that entry number zero_pos becomes first entry
first_col = np.roll(first_col, -np.size(stencil) + zero_pos, axis=0)
return sp.csc_matrix(coeff * (1.0 / dx) * la.circulant(first_col))
def getMatrix(N, dx, bc_left, bc_right, order):
assert bc_left in ['periodic', 'neumann', 'dirichlet'], "Unknown type of BC"
if order == 2:
stencil = [-1.0, 0.0, 1.0]
range = [-1, 0, 1]
coeff = 1.0 / 2.0
elif order == 4:
stencil = [1.0, -8.0, 0.0, 8.0, -1.0]
range = [-2, -1, 0, 1, 2]
coeff = 1.0 / 12.0
else:
sys.exit('Order ' + str(order) + ' not implemented')
A = sp.diags(stencil, range, shape=(N, N))
A = sp.lil_matrix(A)
#
# Periodic boundary conditions
#
if bc_left in ['periodic']:
assert bc_right in ['periodic'], "Periodic BC can only be selected for both sides simultaneously"
if bc_left in ['periodic']:
if order == 2:
A[0, N - 1] = stencil[0]
elif order == 4:
A[0, N - 2] = stencil[0]
A[0, N - 1] = stencil[1]
A[1, N - 1] = stencil[0]
if bc_right in ['periodic']:
if order == 2:
A[N - 1, 0] = stencil[2]
elif order == 4:
A[N - 2, 0] = stencil[4]
A[N - 1, 0] = stencil[3]
A[N - 1, 1] = stencil[4]
#
# Neumann boundary conditions
#
if bc_left in ['neumann']:
A[0, :] = np.zeros(N)
if order == 2:
A[0, 0] = -4.0 / 3.0
A[0, 1] = 4.0 / 3.0
elif order == 4:
A[0, 0] = -8.0
A[0, 1] = 8.0
A[1, 0] = -8.0 + 4.0 / 3.0
A[1, 1] = -1.0 / 3.0
if bc_right in ['neumann']:
A[N - 1, :] = np.zeros(N)
if order == 2:
A[N - 1, N - 2] = -4.0 / 3.0
A[N - 1, N - 1] = 4.0 / 3.0
elif order == 4:
A[N - 2, N - 1] = 8.0 - 4.0 / 3.0
A[N - 2, N - 2] = 1.0 / 3.0
A[N - 1, N - 1] = 8.0
A[N - 1, N - 2] = -8.0
#
# Dirichlet boundary conditions
#
if bc_left in ['dirichlet']:
# For order==2, nothing to do here
if order == 4:
A[0, :] = np.zeros(N)
A[0, 1] = 6.0
if bc_right in ['dirichlet']:
# For order==2, nothing to do here
if order == 4:
A[N - 1, :] = np.zeros(N)
A[N - 1, N - 2] = -6.0
A *= coeff * (1.0 / dx)
return sp.csc_matrix(A)
#
#
#
def getBCLeft(value, N, dx, type, order):
assert type in ['periodic', 'neumann', 'dirichlet'], "Unknown type of BC"
if order == 2:
coeff = 1.0 / 2.0
elif order == 4:
coeff = 1.0 / 12.0
else:
raise NotImplementedError('wrong order, got %s' % order)
b = np.zeros(N)
if type in ['dirichlet']:
if order == 2:
b[0] = -value
elif order == 4:
b[0] = -6.0 * value
b[1] = 1.0 * value
if type in ['neumann']:
if order == 2:
b[0] = (2.0 / 3.0) * dx * value
elif order == 4:
b[0] = 4.0 * dx * value
b[1] = -(2.0 / 3.0) * dx * value
return coeff * (1.0 / dx) * b
#
#
#
def getBCRight(value, N, dx, type, order):
assert type in ['periodic', 'neumann', 'dirichlet'], "Unknown type of BC"
if order == 2:
coeff = 1.0 / 2.0
elif order == 4:
coeff = 1.0 / 12.0
else:
raise NotImplementedError('wrong order, got %s' % order)
b = np.zeros(N)
if type in ['dirichlet']:
if order == 2:
b[N - 1] = value
elif order == 4:
b[N - 2] = -1.0 * value
b[N - 1] = 6.0 * value
if type in ['neumann']:
if order == 2:
b[N - 1] = (2.0 / 3.0) * dx * value
elif order == 4:
b[N - 2] = -(2.0 / 3.0) * dx * value
b[N - 1] = 4.0 * dx * value
return coeff * (1.0 / dx) * b
| 4,989 | 24.854922 | 105 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/boussinesq_helpers/build2DFDMatrix.py | import numpy as np
import scipy.sparse as sp
from pySDC.implementations.problem_classes.boussinesq_helpers.buildFDMatrix import (
getMatrix,
getUpwindMatrix,
getBCLeft,
getBCRight,
)
#
#
#
def get2DUpwindMatrix(N, dx, order):
Dx = getUpwindMatrix(N[0], dx, order)
return sp.kron(Dx, sp.eye(N[1]), format="csr")
#
#
#
def get2DMesh(N, x_b, z_b, bc_hor, bc_ver):
assert np.size(N) == 2, 'N needs to be an array with two entries: N[0]=Nx and N[1]=Nz'
assert (
np.size(x_b) == 2
), 'x_b needs to be an array with two entries: x_b[0] = left boundary, x_b[1] = right boundary'
assert (
np.size(z_b) == 2
), 'z_b needs to be an array with two entries: z_b[0] = lower boundary, z_b[1] = upper boundary'
h = np.zeros(2)
x = None
z = None
if bc_hor[0] in ['periodic']:
assert bc_hor[1] in ['periodic'], 'Periodic boundary conditions must be prescribed at both boundaries'
x = np.linspace(x_b[0], x_b[1], N[0], endpoint=False)
h[0] = x[1] - x[0]
if bc_hor[0] in ['dirichlet', 'neumann']:
x = np.linspace(x_b[0], x_b[1], N[0] + 2, endpoint=True)
x = x[1 : N[0] + 1]
h[0] = x[1] - x[0]
if bc_ver[0] in ['periodic']:
assert bc_ver[1] in ['periodic'], 'Periodic boundary conditions must be prescribed at both boundaries'
z = np.linspace(z_b[0], z_b[1], N[1], endpoint=False)
h[1] = z[1] - z[0]
if bc_ver[0] in ['dirichlet', 'neumann']:
z = np.linspace(z_b[0], z_b[1], N[1] + 2, endpoint=True)
z = z[1 : N[1] + 1]
h[1] = z[1] - z[0]
xx, zz = np.meshgrid(x, z, indexing="ij")
return xx, zz, h
#
#
#
def get2DMatrix(N, h, bc_hor, bc_ver, order):
assert np.size(N) == 2, 'N needs to be an array with two entries: N[0]=Nx and N[1]=Nz'
assert np.size(h) == 2, 'h needs to be an array with two entries: h[0]=dx and h[1]=dz'
Ax = getMatrix(N[0], h[0], bc_hor[0], bc_hor[1], order)
Az = getMatrix(N[1], h[1], bc_ver[0], bc_ver[1], order)
Dx = sp.kron(Ax, sp.eye(N[1]), format="csr")
Dz = sp.kron(sp.eye(N[0]), Az, format="csr")
return Dx, Dz
#
# NOTE: So far only constant dirichlet values can be prescribed, i.e. one fixed value for a whole segment
#
def getBCHorizontal(value, N, dx, bc_hor):
assert (
np.size(value) == 2
), 'Value needs to be an array with two entries: value[0] for the left and value[1] for the right boundary'
assert np.size(N) == 2, 'N needs to be an array with two entries: N[0]=Nx and N[1]=Nz'
assert np.size(dx) == 1, 'dx must be a scalar'
assert (
np.size(bc_hor) == 2
), 'bc_hor must have two entries, bc_hor[0] specifying the BC at the left, bc_hor[1] at the right boundary'
bl = getBCLeft(value[0], N[0], dx, bc_hor[0])
bl = np.kron(bl, np.ones(N[1]))
br = getBCRight(value[1], N[0], dx, bc_hor[1])
br = np.kron(br, np.ones(N[1]))
return bl, br
def getBCVertical(value, N, dz, bc_ver):
assert (
np.size(value) == 2
), 'Value needs to be an array with two entries: value[0] for the left and value[1] for the right boundary'
assert np.size(N) == 2, 'N needs to be an array with two entries: N[0]=Nx and N[1]=Nz'
assert np.size(dz) == 1, 'dx must be a scalar'
assert (
np.size(bc_ver) == 2
), 'bc_hor must have two entries, bc_hor[0] specifying the BC at the left, bc_hor[1] at the right boundary'
bd = getBCLeft(value[0], N[1], dz, bc_ver[0])
bd = np.kron(np.ones(N[0]), bd)
bu = getBCRight(value[1], N[1], dz, bc_ver[1])
bu = np.kron(np.ones(N[0]), bu)
return bd, bu
| 3,640 | 30.119658 | 111 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/boussinesq_helpers/standard_integrators.py | import math
from decimal import Decimal, getcontext
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import gmres
from pySDC.implementations.problem_classes.Boussinesq_2D_FD_imex import boussinesq_2d_imex
from pySDC.implementations.problem_classes.boussinesq_helpers.helper_classes import logging, Callback
#
# Runge-Kutta IMEX methods of order 1 to 3
#
class rk_imex:
def __init__(self, problem, order):
assert order in [1, 2, 3, 4, 5], "Order must be between 1 and 5"
self.order = order
if self.order == 1:
self.A = np.array([[0, 0], [0, 1]])
self.A_hat = np.array([[0, 0], [1, 0]])
self.b = np.array([0, 1])
self.b_hat = np.array([1, 0])
self.nstages = 2
elif self.order == 2:
self.A = np.array([[0, 0], [0, 0.5]])
self.A_hat = np.array([[0, 0], [0.5, 0]])
self.b = np.array([0, 1])
self.b_hat = np.array([0, 1])
self.nstages = 2
elif self.order == 3:
# parameter from Pareschi and Russo, J. Sci. Comp. 2005
alpha = 0.24169426078821
beta = 0.06042356519705
eta = 0.12915286960590
self.A_hat = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 1.0, 0, 0], [0, 1.0 / 4.0, 1.0 / 4.0, 0]])
self.A = np.array(
[
[alpha, 0, 0, 0],
[-alpha, alpha, 0, 0],
[0, 1.0 - alpha, alpha, 0],
[beta, eta, 0.5 - beta - eta - alpha, alpha],
]
)
self.b_hat = np.array([0, 1.0 / 6.0, 1.0 / 6.0, 2.0 / 3.0])
self.b = self.b_hat
self.nstages = 4
elif self.order == 4:
self.A_hat = np.array(
[
[0, 0, 0, 0, 0, 0],
[1.0 / 2, 0, 0, 0, 0, 0],
[13861.0 / 62500.0, 6889.0 / 62500.0, 0, 0, 0, 0],
[
-116923316275.0 / 2393684061468.0,
-2731218467317.0 / 15368042101831.0,
9408046702089.0 / 11113171139209.0,
0,
0,
0,
],
[
-451086348788.0 / 2902428689909.0,
-2682348792572.0 / 7519795681897.0,
12662868775082.0 / 11960479115383.0,
3355817975965.0 / 11060851509271.0,
0,
0,
],
[
647845179188.0 / 3216320057751.0,
73281519250.0 / 8382639484533.0,
552539513391.0 / 3454668386233.0,
3354512671639.0 / 8306763924573.0,
4040.0 / 17871.0,
0,
],
]
)
self.A = np.array(
[
[0, 0, 0, 0, 0, 0],
[1.0 / 4, 1.0 / 4, 0, 0, 0, 0],
[8611.0 / 62500.0, -1743.0 / 31250.0, 1.0 / 4, 0, 0, 0],
[5012029.0 / 34652500.0, -654441.0 / 2922500.0, 174375.0 / 388108.0, 1.0 / 4, 0, 0],
[
15267082809.0 / 155376265600.0,
-71443401.0 / 120774400.0,
730878875.0 / 902184768.0,
2285395.0 / 8070912.0,
1.0 / 4,
0,
],
[82889.0 / 524892.0, 0, 15625.0 / 83664.0, 69875.0 / 102672.0, -2260.0 / 8211, 1.0 / 4],
]
)
self.b = np.array([82889.0 / 524892.0, 0, 15625.0 / 83664.0, 69875.0 / 102672.0, -2260.0 / 8211, 1.0 / 4])
self.b_hat = np.array(
[
4586570599.0 / 29645900160.0,
0,
178811875.0 / 945068544.0,
814220225.0 / 1159782912.0,
-3700637.0 / 11593932.0,
61727.0 / 225920.0,
]
)
self.nstages = 6
elif self.order == 5:
# from Kennedy and Carpenter
# copied from http://www.mcs.anl.gov/petsc/petsc-3.2/src/ts/impls/arkimex/arkimex.c
self.A_hat = np.zeros((8, 8))
getcontext().prec = 56
self.A_hat[1, 0] = Decimal(41.0) / Decimal(100.0)
self.A_hat[2, 0] = Decimal(367902744464.0) / Decimal(2072280473677.0)
self.A_hat[2, 1] = Decimal(677623207551.0) / Decimal(8224143866563.0)
self.A_hat[3, 0] = Decimal(1268023523408.0) / Decimal(10340822734521.0)
self.A_hat[3, 1] = 0.0
self.A_hat[3, 2] = Decimal(1029933939417.0) / Decimal(13636558850479.0)
self.A_hat[4, 0] = Decimal(14463281900351.0) / Decimal(6315353703477.0)
self.A_hat[4, 1] = 0.0
self.A_hat[4, 2] = Decimal(66114435211212.0) / Decimal(5879490589093.0)
self.A_hat[4, 3] = Decimal(-54053170152839.0) / Decimal(4284798021562.0)
self.A_hat[5, 0] = Decimal(14090043504691.0) / Decimal(34967701212078.0)
self.A_hat[5, 1] = 0.0
self.A_hat[5, 2] = Decimal(15191511035443.0) / Decimal(11219624916014.0)
self.A_hat[5, 3] = Decimal(-18461159152457.0) / Decimal(12425892160975.0)
self.A_hat[5, 4] = Decimal(-281667163811.0) / Decimal(9011619295870.0)
self.A_hat[6, 0] = Decimal(19230459214898.0) / Decimal(13134317526959.0)
self.A_hat[6, 1] = 0.0
self.A_hat[6, 2] = Decimal(21275331358303.0) / Decimal(2942455364971.0)
self.A_hat[6, 3] = Decimal(-38145345988419.0) / Decimal(4862620318723.0)
self.A_hat[6, 4] = Decimal(-1.0) / Decimal(8.0)
self.A_hat[6, 5] = Decimal(-1.0) / Decimal(8.0)
self.A_hat[7, 0] = Decimal(-19977161125411.0) / Decimal(11928030595625.0)
self.A_hat[7, 1] = 0.0
self.A_hat[7, 2] = Decimal(-40795976796054.0) / Decimal(6384907823539.0)
self.A_hat[7, 3] = Decimal(177454434618887.0) / Decimal(12078138498510.0)
self.A_hat[7, 4] = Decimal(782672205425.0) / Decimal(8267701900261.0)
self.A_hat[7, 5] = Decimal(-69563011059811.0) / Decimal(9646580694205.0)
self.A_hat[7, 6] = Decimal(7356628210526.0) / Decimal(4942186776405.0)
self.b_hat = np.zeros(8)
self.b_hat[0] = Decimal(-872700587467.0) / Decimal(9133579230613.0)
self.b_hat[1] = 0.0
self.b_hat[2] = 0.0
self.b_hat[3] = Decimal(22348218063261.0) / Decimal(9555858737531.0)
self.b_hat[4] = Decimal(-1143369518992.0) / Decimal(8141816002931.0)
self.b_hat[5] = Decimal(-39379526789629.0) / Decimal(19018526304540.0)
self.b_hat[6] = Decimal(32727382324388.0) / Decimal(42900044865799.0)
self.b_hat[7] = Decimal(41.0) / Decimal(200.0)
self.A = np.zeros((8, 8))
self.A[1, 0] = Decimal(41.0) / Decimal(200.0)
self.A[1, 1] = Decimal(41.0) / Decimal(200.0)
self.A[2, 0] = Decimal(41.0) / Decimal(400.0)
self.A[2, 1] = Decimal(-567603406766.0) / Decimal(11931857230679.0)
self.A[2, 2] = Decimal(41.0) / Decimal(200.0)
self.A[3, 0] = Decimal(683785636431.0) / Decimal(9252920307686.0)
self.A[3, 1] = 0.0
self.A[3, 2] = Decimal(-110385047103.0) / Decimal(1367015193373.0)
self.A[3, 3] = Decimal(41.0) / Decimal(200.0)
self.A[4, 0] = Decimal(3016520224154.0) / Decimal(10081342136671.0)
self.A[4, 1] = 0.0
self.A[4, 2] = Decimal(30586259806659.0) / Decimal(12414158314087.0)
self.A[4, 3] = Decimal(-22760509404356.0) / Decimal(11113319521817.0)
self.A[4, 4] = Decimal(41.0) / Decimal(200.0)
self.A[5, 0] = Decimal(218866479029.0) / Decimal(1489978393911.0)
self.A[5, 1] = 0.0
self.A[5, 2] = Decimal(638256894668.0) / Decimal(5436446318841.0)
self.A[5, 3] = Decimal(-1179710474555.0) / Decimal(5321154724896.0)
self.A[5, 4] = Decimal(-60928119172.0) / Decimal(8023461067671.0)
self.A[5, 5] = Decimal(41.0) / Decimal(200.0)
self.A[6, 0] = Decimal(1020004230633.0) / Decimal(5715676835656.0)
self.A[6, 1] = 0.0
self.A[6, 2] = Decimal(25762820946817.0) / Decimal(25263940353407.0)
self.A[6, 3] = Decimal(-2161375909145.0) / Decimal(9755907335909.0)
self.A[6, 4] = Decimal(-211217309593.0) / Decimal(5846859502534.0)
self.A[6, 5] = Decimal(-4269925059573.0) / Decimal(7827059040749.0)
self.A[6, 6] = Decimal(41.0) / Decimal(200.0)
self.A[7, 0] = Decimal(-872700587467.0) / Decimal(9133579230613.0)
self.A[7, 1] = 0.0
self.A[7, 2] = 0.0
self.A[7, 3] = Decimal(22348218063261.0) / Decimal(9555858737531.0)
self.A[7, 4] = Decimal(-1143369518992.0) / Decimal(8141816002931.0)
self.A[7, 5] = Decimal(-39379526789629.0) / Decimal(19018526304540.0)
self.A[7, 6] = Decimal(32727382324388.0) / Decimal(42900044865799.0)
self.A[7, 7] = Decimal(41.0) / Decimal(200.0)
self.b = np.zeros(8)
self.b[0] = Decimal(-975461918565.0) / Decimal(9796059967033.0)
self.b[1] = 0.0
self.b[2] = 0.0
self.b[3] = Decimal(78070527104295.0) / Decimal(32432590147079.0)
self.b[4] = Decimal(-548382580838.0) / Decimal(3424219808633.0)
self.b[5] = Decimal(-33438840321285.0) / Decimal(15594753105479.0)
self.b[6] = Decimal(3629800801594.0) / Decimal(4656183773603.0)
self.b[7] = Decimal(4035322873751.0) / Decimal(18575991585200.0)
self.nstages = 8
self.problem = problem
self.ndof = np.shape(problem.M)[0]
self.logger = logging()
self.stages = np.zeros((self.nstages, self.ndof))
def timestep(self, u0, dt):
# Solve for stages
for i in range(0, self.nstages):
# Construct RHS
rhs = np.copy(u0)
for j in range(0, i):
rhs += dt * self.A_hat[i, j] * (self.f_slow(self.stages[j, :])) + dt * self.A[i, j] * (
self.f_fast(self.stages[j, :])
)
# Solve for stage i
if self.A[i, i] == 0:
# Avoid call to spsolve with identity matrix
self.stages[i, :] = np.copy(rhs)
else:
self.stages[i, :] = self.f_fast_solve(rhs, dt * self.A[i, i], u0)
# Update
for i in range(0, self.nstages):
u0 += dt * self.b_hat[i] * (self.f_slow(self.stages[i, :])) + dt * self.b[i] * (
self.f_fast(self.stages[i, :])
)
return u0
def f_slow(self, u):
return self.problem.D_upwind.dot(u)
def f_fast(self, u):
return self.problem.M.dot(u)
def f_fast_solve(self, rhs, alpha, u0):
cb = Callback()
sol, info = gmres(
self.problem.Id - alpha * self.problem.M,
rhs,
x0=u0,
tol=self.problem.params.gmres_tol_limit,
restart=self.problem.params.gmres_restart,
maxiter=self.problem.params.gmres_maxiter,
atol=0,
callback=cb,
)
if alpha != 0.0:
self.logger.add(cb.getcounter())
return sol
#
# Trapezoidal rule
#
class trapezoidal:
def __init__(self, problem, alpha=0.5):
assert isinstance(problem, boussinesq_2d_imex), "problem is wrong type of object"
self.Ndof = np.shape(problem.M)[0]
self.order = 2
self.logger = logging()
self.problem = problem
self.alpha = alpha
def timestep(self, u0, dt):
B_trap = sp.eye(self.Ndof) + self.alpha * dt * (self.problem.D_upwind + self.problem.M)
b = B_trap.dot(u0)
return self.f_solve(b, alpha=(1.0 - self.alpha) * dt, u0=u0)
#
# Returns f(u) = c*u
#
def f(self, u):
return self.problem.D_upwind.dot(u) + self.problem.M.dot(u)
#
# Solves (Id - alpha*c)*u = b for u
#
def f_solve(self, b, alpha, u0):
cb = Callback()
sol, info = gmres(
self.problem.Id - alpha * (self.problem.D_upwind + self.problem.M),
b,
x0=u0,
tol=self.problem.params.gmres_tol_limit,
restart=self.problem.params.gmres_restart,
maxiter=self.problem.params.gmres_maxiter,
atol=0,
callback=cb,
)
if alpha != 0.0:
self.logger.add(cb.getcounter())
return sol
#
# A BDF-2 implicit two-step method
#
class bdf2:
def __init__(self, problem):
assert isinstance(problem, boussinesq_2d_imex), "problem is wrong type of object"
self.Ndof = np.shape(problem.M)[0]
self.order = 2
self.logger = logging()
self.problem = problem
def firsttimestep(self, u0, dt):
return self.f_solve(b=u0, alpha=dt, u0=u0)
def timestep(self, u0, um1, dt):
b = (4.0 / 3.0) * u0 - (1.0 / 3.0) * um1
return self.f_solve(b=b, alpha=(2.0 / 3.0) * dt, u0=u0)
#
# Returns f(u) = c*u
#
def f(self, u):
return self.problem.D_upwind.dot(u) + self.problem.M.dot(u)
#
# Solves (Id - alpha*c)*u = b for u
#
def f_solve(self, b, alpha, u0):
cb = Callback()
sol, info = gmres(
self.problem.Id - alpha * (self.problem.D_upwind + self.problem.M),
b,
x0=u0,
tol=self.problem.params.gmres_tol_limit,
restart=self.problem.params.gmres_restart,
maxiter=self.problem.params.gmres_maxiter,
atol=0,
callback=cb,
)
if alpha != 0.0:
self.logger.add(cb.getcounter())
return sol
#
# Split-Explicit method
#
class SplitExplicit:
def __init__(self, problem, method, pparams):
assert isinstance(problem, boussinesq_2d_imex), "problem is wrong type of object"
self.Ndof = np.shape(problem.M)[0]
self.method = method
self.logger = logging()
self.problem = problem
self.pparams = pparams
self.NdofTher = 2 * problem.N[0] * problem.N[1]
self.NdofMom = 2 * problem.N[0] * problem.N[1]
self.ns = None
# print("dx ",problem.h[0])
# print("dz ",problem.h[1])
assert self.method in ["MIS4_4", "RK3"], 'Method must be MIS4_4'
if self.method == 'RK3':
self.nstages = 3
self.aRunge = np.zeros((4, 4))
self.aRunge[0, 0] = 1.0 / 3.0
self.aRunge[1, 1] = 1.0 / 2.0
self.aRunge[2, 2] = 1.0
self.dRunge = np.zeros((4, 4))
self.gRunge = np.zeros((4, 4))
if self.method == 'MIS4_4':
self.nstages = 4
self.aRunge = np.zeros((4, 4))
self.aRunge[0, 0] = 0.38758444641450318
self.aRunge[1, 0] = -2.5318448354142823e-002
self.aRunge[1, 1] = 0.38668943087310403
self.aRunge[2, 0] = 0.20899983523553325
self.aRunge[2, 1] = -0.45856648476371231
self.aRunge[2, 2] = 0.43423187573425748
self.aRunge[3, 0] = -0.10048822195663100
self.aRunge[3, 1] = -0.46186171956333327
self.aRunge[3, 2] = 0.83045062122462809
self.aRunge[3, 3] = 0.27014914900250392
self.dRunge = np.zeros((4, 4))
self.dRunge[1, 1] = 0.52349249922385610
self.dRunge[2, 1] = 1.1683374366893629
self.dRunge[2, 2] = -0.75762080241712637
self.dRunge[3, 1] = -3.6477233846797109e-002
self.dRunge[3, 2] = 0.56936148730740477
self.dRunge[3, 3] = 0.47746263002599681
self.gRunge = np.zeros((4, 4))
self.gRunge[1, 1] = 0.13145089796226542
self.gRunge[2, 1] = -0.36855857648747881
self.gRunge[2, 2] = 0.33159232636600550
self.gRunge[3, 1] = -6.5767130537473045e-002
self.gRunge[3, 2] = 4.0591093109036858e-002
self.gRunge[3, 3] = 6.4902111640806712e-002
self.dtRunge = np.zeros(self.nstages)
for i in range(0, self.nstages):
self.dtRunge[i] = 0
temp = 1.0
for j in range(0, i + 1):
self.dtRunge[i] = self.dtRunge[i] + self.aRunge[i, j]
temp = temp - self.dRunge[i, j]
self.dRunge[i, 0] = temp
for j in range(0, i + 1):
self.aRunge[i, j] = self.aRunge[i, j] / self.dtRunge[i]
self.gRunge[i, j] = self.gRunge[i, j] / self.dtRunge[i]
self.U = np.zeros((self.Ndof, self.nstages + 1))
self.F = np.zeros((self.Ndof, self.nstages))
self.FSlow = np.zeros(self.Ndof)
self.nsMin = 8
self.logger.nsmall = 0
def NumSmallTimeSteps(self, dx, dz, dt):
cs = self.pparams['c_s']
ns = dt / (0.9 / np.sqrt(1 / (dx * dx) + 1 / (dz * dz)) / cs)
ns = max(np.int(np.ceil(ns)), self.nsMin)
return ns
def timestep(self, u0, dt):
self.U[:, 0] = u0
self.ns = self.NumSmallTimeSteps(self.problem.h[0], self.problem.h[1], dt)
for i in range(0, self.nstages):
self.F[:, i] = self.f_slow(self.U[:, i])
self.FSlow[:] = 0.0
for j in range(0, i + 1):
self.FSlow += self.aRunge[i, j] * self.F[:, j] + self.gRunge[i, j] / dt * (self.U[:, j] - u0)
self.U[:, i + 1] = 0
for j in range(0, i + 1):
self.U[:, i + 1] += self.dRunge[i, j] * self.U[:, j]
nsLoc = np.int(np.ceil(self.ns * self.dtRunge[i]))
self.logger.nsmall += nsLoc
dtLoc = dt * self.dtRunge[i]
dTau = dtLoc / nsLoc
self.U[:, i + 1] = self.VerletLin(self.U[:, i + 1], self.FSlow, nsLoc, dTau)
u0 = self.U[:, self.nstages]
return u0
def VerletLin(self, u0, FSlow, ns, dTau):
for _ in range(0, ns):
u0[0 : self.NdofMom] += dTau * (self.f_fastMom(u0) + FSlow[0 : self.NdofMom])
u0[self.NdofMom : self.Ndof] += dTau * (self.f_fastTher(u0) + FSlow[self.NdofMom : self.Ndof])
return u0
def RK3Lin(self, u0, FSlow, ns, dTau):
u = u0
for _ in range(0, ns):
u = u0 + dTau / 3.0 * (self.f_fast(u) + FSlow)
u = u0 + dTau / 2.0 * (self.f_fast(u) + FSlow)
u = u0 + dTau * (self.f_fast(u) + FSlow)
u0 = u
return u0
def f_slow(self, u):
return self.problem.D_upwind.dot(u)
def f_fast(self, u):
return self.problem.M.dot(u)
def f_fastMom(self, u):
return self.problem.M[0 : self.NdofMom, self.NdofMom : self.Ndof].dot(u[self.NdofMom : self.Ndof])
def f_fastTher(self, u):
return self.problem.M[self.NdofMom : self.Ndof, 0 : self.NdofMom].dot(u[0 : self.NdofMom])
class dirk:
def __init__(self, problem, order):
assert isinstance(problem, boussinesq_2d_imex), "problem is wrong type of object"
self.Ndof = np.shape(problem.M)[0]
self.order = order
self.logger = logging()
self.problem = problem
assert self.order in [2, 22, 3, 4, 5], 'Order must be 2,22,3,4'
if self.order == 2:
self.nstages = 1
self.A = np.zeros((1, 1))
self.A[0, 0] = 0.5
self.tau = [0.5]
self.b = [1.0]
if self.order == 22:
self.nstages = 2
self.A = np.zeros((2, 2))
self.A[0, 0] = 1.0 / 3.0
self.A[1, 0] = 1.0 / 2.0
self.A[1, 1] = 1.0 / 2.0
self.tau = np.zeros(2)
self.tau[0] = 1.0 / 3.0
self.tau[1] = 1.0
self.b = np.zeros(2)
self.b[0] = 3.0 / 4.0
self.b[1] = 1.0 / 4.0
if self.order == 3:
self.nstages = 2
self.A = np.zeros((2, 2))
self.A[0, 0] = 0.5 + 1.0 / (2.0 * math.sqrt(3.0))
self.A[1, 0] = -1.0 / math.sqrt(3.0)
self.A[1, 1] = self.A[0, 0]
self.tau = np.zeros(2)
self.tau[0] = 0.5 + 1.0 / (2.0 * math.sqrt(3.0))
self.tau[1] = 0.5 - 1.0 / (2.0 * math.sqrt(3.0))
self.b = np.zeros(2)
self.b[0] = 0.5
self.b[1] = 0.5
if self.order == 4:
self.nstages = 3
alpha = 2.0 * math.cos(math.pi / 18.0) / math.sqrt(3.0)
self.A = np.zeros((3, 3))
self.A[0, 0] = (1.0 + alpha) / 2.0
self.A[1, 0] = -alpha / 2.0
self.A[1, 1] = self.A[0, 0]
self.A[2, 0] = 1.0 + alpha
self.A[2, 1] = -(1.0 + 2.0 * alpha)
self.A[2, 2] = self.A[0, 0]
self.tau = np.zeros(3)
self.tau[0] = (1.0 + alpha) / 2.0
self.tau[1] = 1.0 / 2.0
self.tau[2] = (1.0 - alpha) / 2.0
self.b = np.zeros(3)
self.b[0] = 1.0 / (6.0 * alpha * alpha)
self.b[1] = 1.0 - 1.0 / (3.0 * alpha * alpha)
self.b[2] = 1.0 / (6.0 * alpha * alpha)
if self.order == 5:
self.nstages = 5
# From Kennedy, Carpenter "Diagonally Implicit Runge-Kutta Methods for Ordinary Differential Equations.
# A Review"
self.A = np.zeros((5, 5))
self.A[0, 0] = 4024571134387.0 / 14474071345096.0
self.A[1, 0] = 9365021263232.0 / 12572342979331.0
self.A[1, 1] = self.A[0, 0]
self.A[2, 0] = 2144716224527.0 / 9320917548702.0
self.A[2, 1] = -397905335951.0 / 4008788611757.0
self.A[2, 2] = self.A[0, 0]
self.A[3, 0] = -291541413000.0 / 6267936762551.0
self.A[3, 1] = 226761949132.0 / 4473940808273.0
self.A[3, 2] = -1282248297070.0 / 9697416712681.0
self.A[3, 3] = self.A[0, 0]
self.A[4, 0] = -2481679516057.0 / 4626464057815.0
self.A[4, 1] = -197112422687.0 / 6604378783090.0
self.A[4, 2] = 3952887910906.0 / 9713059315593.0
self.A[4, 3] = 4906835613583.0 / 8134926921134.0
self.A[4, 4] = self.A[0, 0]
self.b = np.zeros(5)
self.b[0] = -2522702558582.0 / 12162329469185.0
self.b[1] = 1018267903655.0 / 12907234417901.0
self.b[2] = 4542392826351.0 / 13702606430957.0
self.b[3] = 5001116467727.0 / 12224457745473.0
self.b[4] = 1509636094297.0 / 3891594770934.0
self.stages = np.zeros((self.nstages, self.Ndof))
def timestep(self, u0, dt):
uend = u0
for i in range(0, self.nstages):
b = u0
# Compute right hand side for this stage's implicit step
for j in range(0, i):
b = b + self.A[i, j] * dt * self.f(self.stages[j, :])
# Implicit solve for current stage
# if i==0:
self.stages[i, :] = self.f_solve(b, dt * self.A[i, i], u0)
# else:
# self.stages[i,:] = self.f_solve( b, dt*self.A[i,i] , self.stages[i-1,:] )
# Add contribution of current stage to final value
uend = uend + self.b[i] * dt * self.f(self.stages[i, :])
return uend
#
# Returns f(u) = c*u
#
def f(self, u):
return self.problem.D_upwind.dot(u) + self.problem.M.dot(u)
#
# Solves (Id - alpha*c)*u = b for u
#
def f_solve(self, b, alpha, u0):
cb = Callback()
sol, info = gmres(
self.problem.Id - alpha * (self.problem.D_upwind + self.problem.M),
b,
x0=u0,
tol=self.problem.params.gmres_tol_limit,
restart=self.problem.params.gmres_restart,
maxiter=self.problem.params.gmres_maxiter,
atol=0,
callback=cb,
)
if alpha != 0.0:
self.logger.add(cb.getcounter())
return sol
| 24,382 | 37.826433 | 118 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/boussinesq_helpers/buildBoussinesq2DMatrix.py | import numpy as np
import scipy.sparse as sp
from pySDC.implementations.problem_classes.boussinesq_helpers.build2DFDMatrix import (
get2DMatrix,
getBCHorizontal,
get2DUpwindMatrix,
)
def getBoussinesq2DUpwindMatrix(N, dx, u_adv, order):
Dx = get2DUpwindMatrix(N, dx, order)
# Note: In the equations it is u_t + u_adv* D_x u = ... so in order to comply with the form u_t = M u,
# add a minus sign in front of u_adv
Zero = np.zeros((N[0] * N[1], N[0] * N[1]))
M1 = sp.hstack((-u_adv * Dx, Zero, Zero, Zero), format="csr")
M2 = sp.hstack((Zero, -u_adv * Dx, Zero, Zero), format="csr")
M3 = sp.hstack((Zero, Zero, -u_adv * Dx, Zero), format="csr")
M4 = sp.hstack((Zero, Zero, Zero, -u_adv * Dx), format="csr")
M = sp.vstack((M1, M2, M3, M4), format="csr")
return sp.csc_matrix(M)
def getBoussinesq2DMatrix(N, h, bc_hor, bc_ver, c_s, Nfreq, order):
Dx_u, Dz_u = get2DMatrix(N, h, bc_hor[0], bc_ver[0], order)
Dx_w, Dz_w = get2DMatrix(N, h, bc_hor[1], bc_ver[1], order)
# Dx_b, Dz_b = get2DMatrix(N, h, bc_hor[2], bc_ver[2], order)
Dx_p, Dz_p = get2DMatrix(N, h, bc_hor[3], bc_ver[3], order)
# Id_N = sp.eye(N[0] * N[1])
Zero = np.zeros((N[0] * N[1], N[0] * N[1]))
Id_w = sp.eye(N[0] * N[1])
# Note: Bring all terms to right hand side, therefore a couple of minus signs
# are needed
M1 = sp.hstack((Zero, Zero, Zero, -Dx_p), format="csr")
M2 = sp.hstack((Zero, Zero, Id_w, -Dz_p), format="csr")
M3 = sp.hstack((Zero, -(Nfreq**2) * Id_w, Zero, Zero), format="csr")
M4 = sp.hstack((-(c_s**2) * Dx_u, -(c_s**2) * Dz_w, Zero, Zero), format="csr")
M = sp.vstack((M1, M2, M3, M4), format="csr")
Id = sp.eye(4 * N[0] * N[1])
return sp.csc_matrix(Id), sp.csc_matrix(M)
def getBoussinesqBCHorizontal(value, N, dx, bc_hor):
bu_left, bu_right = getBCHorizontal(value[0], N, dx, bc_hor[0])
bw_left, bw_right = getBCHorizontal(value[1], N, dx, bc_hor[1])
# bb_left, bb_right = getBCHorizontal(value[2], N, dx, bc_hor[2])
bp_left, bp_right = getBCHorizontal(value[3], N, dx, bc_hor[3])
b_left = np.concatenate((bp_left, bp_left, bu_left + bw_left))
b_right = np.concatenate((bp_right, bp_right, bu_right + bw_right))
return b_left, b_right
def getBoussinesqBCVertical():
return 0.0
| 2,329 | 34.846154 | 106 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/boussinesq_helpers/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/implementations/problem_classes/boussinesq_helpers/unflatten.py | import numpy as np
def unflatten(uin, dim, Nx, Nz):
temp = np.asarray(np.split(uin, dim))
uout = np.zeros((dim, Nx, Nz))
for i in range(0, dim):
uout[i, :, :] = np.split(temp[i, :], Nx)
return uout
| 224 | 21.5 | 48 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/boussinesq_helpers/helper_classes.py | class logging(object):
def __init__(self):
self.solver_calls = 0
self.iterations = 0
self.nsmall = 0
def add(self, iterations):
self.solver_calls += 1
self.iterations += iterations
class Callback(object):
def getresidual(self):
return self.residual
def getcounter(self):
return self.counter
def __init__(self):
self.counter = 0
self.residual = 0.0
def __call__(self, residuals):
self.counter += 1
self.residual = residuals
| 541 | 19.846154 | 37 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/acoustic_helpers/buildWave1DMatrix.py | import numpy as np
import scipy.sparse as sp
from pySDC.implementations.problem_classes.acoustic_helpers.buildFDMatrix import (
getMatrix,
getHorizontalDx,
getBCLeft,
getBCRight,
)
wave_order = 6
def getWave1DMatrix(N, dx, bc_left, bc_right):
Id = sp.eye(2 * N)
D_u = getMatrix(N, dx, bc_left[0], bc_right[0], wave_order)
D_p = getMatrix(N, dx, bc_left[1], bc_right[1], wave_order)
Zero = np.zeros((N, N))
M1 = sp.hstack((Zero, D_p), format="csc")
M2 = sp.hstack((D_u, Zero), format="csc")
M = sp.vstack((M1, M2), format="csc")
return sp.csc_matrix(Id), sp.csc_matrix(M)
def getWave1DAdvectionMatrix(N, dx, order):
Dx = getHorizontalDx(N, dx, order)
Zero = np.zeros((N, N))
M1 = sp.hstack((Dx, Zero), format="csc")
M2 = sp.hstack((Zero, Dx), format="csc")
M = sp.vstack((M1, M2), format="csc")
return sp.csc_matrix(M)
def getWaveBCLeft(value, N, dx, bc_left):
bu = getBCLeft(value[0], N, dx, bc_left[0], wave_order)
bp = getBCLeft(value[1], N, dx, bc_left[1], wave_order)
return np.concatenate((bp, bu))
def getWaveBCRight(value, N, dx, bc_right):
bu = getBCRight(value[0], N, dx, bc_right[0], wave_order)
bp = getBCRight(value[1], N, dx, bc_right[1], wave_order)
return np.concatenate((bp, bu))
| 1,303 | 27.977778 | 82 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/acoustic_helpers/buildFDMatrix.py | import numpy as np
import scipy.linalg as la
import scipy.sparse as sp
# Only for periodic BC because we have advection only in x direction
def getHorizontalDx(N, dx, order):
if order == 1:
stencil = [-1.0, 1.0]
zero_pos = 2
coeff = 1.0
elif order == 2:
stencil = [1.0, -4.0, 3.0]
coeff = 1.0 / 2.0
zero_pos = 3
elif order == 3:
stencil = [1.0, -6.0, 3.0, 2.0]
coeff = 1.0 / 6.0
zero_pos = 3
elif order == 4:
stencil = [-5.0, 30.0, -90.0, 50.0, 15.0]
coeff = 1.0 / 60.0
zero_pos = 4
elif order == 5:
stencil = [3.0, -20.0, 60.0, -120.0, 65.0, 12.0]
coeff = 1.0 / 60.0
zero_pos = 5
else:
print("Order " + order + " not implemented.")
first_col = np.zeros(N)
# Because we need to specific first column (not row) in circulant, flip stencil array
first_col[0 : np.size(stencil)] = np.flipud(stencil)
# Circulant shift of coefficient column so that entry number zero_pos becomes first entry
first_col = np.roll(first_col, -np.size(stencil) + zero_pos, axis=0)
return sp.csc_matrix(coeff * (1.0 / dx) * la.circulant(first_col))
def getMatrix(N, dx, bc_left, bc_right, order):
assert bc_left in ['periodic', 'neumann', 'dirichlet'], "Unknown type of BC"
if order == 2:
stencil = [-1.0, 0.0, 1.0]
range = [-1, 0, 1]
coeff = 1.0 / 2.0
elif order == 4:
stencil = [1.0, -8.0, 0.0, 8.0, -1.0]
range = [-2, -1, 0, 1, 2]
coeff = 1.0 / 12.0
elif order == 6:
stencil = [-1.0, 9.0, -45.0, 0.0, 45.0, -9.0, 1.0]
range = [-3, -2, -1, 0, 1, 2, 3]
coeff = 1.0 / 60.0
A = sp.diags(stencil, range, shape=(N, N))
A = sp.lil_matrix(A)
#
# Periodic boundary conditions
#
if bc_left in ['periodic']:
assert bc_right in ['periodic'], "Periodic BC can only be selected for both sides simultaneously"
if bc_left in ['periodic']:
if order == 2:
A[0, N - 1] = stencil[0]
elif order == 4:
A[0, N - 2] = stencil[0]
A[0, N - 1] = stencil[1]
A[1, N - 1] = stencil[0]
elif order == 6:
A[0, N - 3] = stencil[0]
A[0, N - 2] = stencil[1]
A[0, N - 1] = stencil[2]
A[1, N - 2] = stencil[0]
A[1, N - 1] = stencil[1]
A[2, N - 1] = stencil[0]
if bc_right in ['periodic']:
if order == 2:
A[N - 1, 0] = stencil[2]
elif order == 4:
A[N - 2, 0] = stencil[4]
A[N - 1, 0] = stencil[3]
A[N - 1, 1] = stencil[4]
elif order == 6:
A[N - 3, 0] = stencil[6]
A[N - 2, 0] = stencil[5]
A[N - 2, 1] = stencil[6]
A[N - 1, 0] = stencil[4]
A[N - 1, 1] = stencil[5]
A[N - 1, 2] = stencil[6]
#
# Neumann boundary conditions
#
if bc_left in ['neumann']:
A[0, :] = np.zeros(N)
if order == 2:
A[0, 0] = -4.0 / 3.0
A[0, 1] = 4.0 / 3.0
elif order == 4:
A[0, 0] = -8.0
A[0, 1] = 8.0
A[1, 0] = -8.0 + 4.0 / 3.0
A[1, 1] = -1.0 / 3.0
if bc_right in ['neumann']:
A[N - 1, :] = np.zeros(N)
if order == 2:
A[N - 1, N - 2] = -4.0 / 3.0
A[N - 1, N - 1] = 4.0 / 3.0
elif order == 4:
A[N - 2, N - 1] = 8.0 - 4.0 / 3.0
A[N - 2, N - 2] = 1.0 / 3.0
A[N - 1, N - 1] = 8.0
A[N - 1, N - 2] = -8.0
#
# Dirichlet boundary conditions
#
if bc_left in ['dirichlet']:
# For order==2, nothing to do here
if order == 4:
A[0, :] = np.zeros(N)
A[0, 1] = 6.0
if bc_right in ['dirichlet']:
# For order==2, nothing to do here
if order == 4:
A[N - 1, :] = np.zeros(N)
A[N - 1, N - 2] = -6.0
A = coeff * (1.0 / dx) * A
return sp.csc_matrix(A)
#
#
#
def getBCLeft(value, N, dx, type, order):
assert type in ['periodic', 'neumann', 'dirichlet'], "Unknown type of BC"
if order == 2:
coeff = 1.0 / 2.0
elif order == 4:
coeff = 1.0 / 12.0
b = np.zeros(N)
if type in ['dirichlet']:
if order == 2:
b[0] = -value
elif order == 4:
b[0] = -6.0 * value
b[1] = 1.0 * value
if type in ['neumann']:
if order == 2:
b[0] = (2.0 / 3.0) * dx * value
elif order == 4:
b[0] = 4.0 * dx * value
b[1] = -(2.0 / 3.0) * dx * value
return coeff * (1.0 / dx) * b
#
#
#
def getBCRight(value, N, dx, type, order):
assert type in ['periodic', 'neumann', 'dirichlet'], "Unknown type of BC"
if order == 2:
coeff = 1.0 / 2.0
elif order == 4:
coeff = 1.0 / 12.0
b = np.zeros(N)
if type in ['dirichlet']:
if order == 2:
b[N - 1] = value
elif order == 4:
b[N - 2] = -1.0 * value
b[N - 1] = 6.0 * value
if type in ['neumann']:
if order == 2:
b[N - 1] = (2.0 / 3.0) * dx * value
elif order == 4:
b[N - 2] = -(2.0 / 3.0) * dx * value
b[N - 1] = 4.0 * dx * value
return coeff * (1.0 / dx) * b
| 5,394 | 25.576355 | 105 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/acoustic_helpers/standard_integrators.py | import math
from decimal import Decimal, getcontext
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as LA
#
# Runge-Kutta IMEX methods of order 1 to 3
#
class rk_imex:
def __init__(self, M_fast, M_slow, order):
assert np.shape(M_fast)[0] == np.shape(M_fast)[1], "A_fast must be square"
assert np.shape(M_slow)[0] == np.shape(M_slow)[1], "A_slow must be square"
assert np.shape(M_fast)[0] == np.shape(M_slow)[0], "A_fast and A_slow must be of the same size"
assert order in [1, 2, 3, 4, 5], "Order must be between 2 and 5"
self.order = order
if self.order == 2:
self.A = np.array([[0, 0], [0, 0.5]])
self.A_hat = np.array([[0, 0], [0.5, 0]])
self.b = np.array([0, 1])
self.b_hat = np.array([0, 1])
self.nstages = 2
elif self.order == 3:
# parameter from Pareschi and Russo, J. Sci. Comp. 2005
alpha = 0.24169426078821
beta = 0.06042356519705
eta = 0.12915286960590
self.A_hat = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 1.0, 0, 0], [0, 1.0 / 4.0, 1.0 / 4.0, 0]])
self.A = np.array(
[
[alpha, 0, 0, 0],
[-alpha, alpha, 0, 0],
[0, 1.0 - alpha, alpha, 0],
[beta, eta, 0.5 - beta - eta - alpha, alpha],
]
)
self.b_hat = np.array([0, 1.0 / 6.0, 1.0 / 6.0, 2.0 / 3.0])
self.b = self.b_hat
self.nstages = 4
elif self.order == 4:
self.A_hat = np.array(
[
[0, 0, 0, 0, 0, 0],
[1.0 / 2, 0, 0, 0, 0, 0],
[13861.0 / 62500.0, 6889.0 / 62500.0, 0, 0, 0, 0],
[
-116923316275.0 / 2393684061468.0,
-2731218467317.0 / 15368042101831.0,
9408046702089.0 / 11113171139209.0,
0,
0,
0,
],
[
-451086348788.0 / 2902428689909.0,
-2682348792572.0 / 7519795681897.0,
12662868775082.0 / 11960479115383.0,
3355817975965.0 / 11060851509271.0,
0,
0,
],
[
647845179188.0 / 3216320057751.0,
73281519250.0 / 8382639484533.0,
552539513391.0 / 3454668386233.0,
3354512671639.0 / 8306763924573.0,
4040.0 / 17871.0,
0,
],
]
)
self.A = np.array(
[
[0, 0, 0, 0, 0, 0],
[1.0 / 4, 1.0 / 4, 0, 0, 0, 0],
[8611.0 / 62500.0, -1743.0 / 31250.0, 1.0 / 4, 0, 0, 0],
[5012029.0 / 34652500.0, -654441.0 / 2922500.0, 174375.0 / 388108.0, 1.0 / 4, 0, 0],
[
15267082809.0 / 155376265600.0,
-71443401.0 / 120774400.0,
730878875.0 / 902184768.0,
2285395.0 / 8070912.0,
1.0 / 4,
0,
],
[82889.0 / 524892.0, 0, 15625.0 / 83664.0, 69875.0 / 102672.0, -2260.0 / 8211, 1.0 / 4],
]
)
self.b = np.array([82889.0 / 524892.0, 0, 15625.0 / 83664.0, 69875.0 / 102672.0, -2260.0 / 8211, 1.0 / 4])
self.b_hat = np.array(
[
4586570599.0 / 29645900160.0,
0,
178811875.0 / 945068544.0,
814220225.0 / 1159782912.0,
-3700637.0 / 11593932.0,
61727.0 / 225920.0,
]
)
self.nstages = 6
elif self.order == 5:
# from Kennedy and Carpenter
# copied from http://www.mcs.anl.gov/petsc/petsc-3.2/src/ts/impls/arkimex/arkimex.c
self.A_hat = np.zeros((8, 8))
getcontext().prec = 56
self.A_hat[1, 0] = Decimal(41.0) / Decimal(100.0)
self.A_hat[2, 0] = Decimal(367902744464.0) / Decimal(2072280473677.0)
self.A_hat[2, 1] = Decimal(677623207551.0) / Decimal(8224143866563.0)
self.A_hat[3, 0] = Decimal(1268023523408.0) / Decimal(10340822734521.0)
self.A_hat[3, 1] = 0.0
self.A_hat[3, 2] = Decimal(1029933939417.0) / Decimal(13636558850479.0)
self.A_hat[4, 0] = Decimal(14463281900351.0) / Decimal(6315353703477.0)
self.A_hat[4, 1] = 0.0
self.A_hat[4, 2] = Decimal(66114435211212.0) / Decimal(5879490589093.0)
self.A_hat[4, 3] = Decimal(-54053170152839.0) / Decimal(4284798021562.0)
self.A_hat[5, 0] = Decimal(14090043504691.0) / Decimal(34967701212078.0)
self.A_hat[5, 1] = 0.0
self.A_hat[5, 2] = Decimal(15191511035443.0) / Decimal(11219624916014.0)
self.A_hat[5, 3] = Decimal(-18461159152457.0) / Decimal(12425892160975.0)
self.A_hat[5, 4] = Decimal(-281667163811.0) / Decimal(9011619295870.0)
self.A_hat[6, 0] = Decimal(19230459214898.0) / Decimal(13134317526959.0)
self.A_hat[6, 1] = 0.0
self.A_hat[6, 2] = Decimal(21275331358303.0) / Decimal(2942455364971.0)
self.A_hat[6, 3] = Decimal(-38145345988419.0) / Decimal(4862620318723.0)
self.A_hat[6, 4] = Decimal(-1.0) / Decimal(8.0)
self.A_hat[6, 5] = Decimal(-1.0) / Decimal(8.0)
self.A_hat[7, 0] = Decimal(-19977161125411.0) / Decimal(11928030595625.0)
self.A_hat[7, 1] = 0.0
self.A_hat[7, 2] = Decimal(-40795976796054.0) / Decimal(6384907823539.0)
self.A_hat[7, 3] = Decimal(177454434618887.0) / Decimal(12078138498510.0)
self.A_hat[7, 4] = Decimal(782672205425.0) / Decimal(8267701900261.0)
self.A_hat[7, 5] = Decimal(-69563011059811.0) / Decimal(9646580694205.0)
self.A_hat[7, 6] = Decimal(7356628210526.0) / Decimal(4942186776405.0)
self.b_hat = np.zeros(8)
self.b_hat[0] = Decimal(-872700587467.0) / Decimal(9133579230613.0)
self.b_hat[1] = 0.0
self.b_hat[2] = 0.0
self.b_hat[3] = Decimal(22348218063261.0) / Decimal(9555858737531.0)
self.b_hat[4] = Decimal(-1143369518992.0) / Decimal(8141816002931.0)
self.b_hat[5] = Decimal(-39379526789629.0) / Decimal(19018526304540.0)
self.b_hat[6] = Decimal(32727382324388.0) / Decimal(42900044865799.0)
self.b_hat[7] = Decimal(41.0) / Decimal(200.0)
self.A = np.zeros((8, 8))
self.A[1, 0] = Decimal(41.0) / Decimal(200.0)
self.A[1, 1] = Decimal(41.0) / Decimal(200.0)
self.A[2, 0] = Decimal(41.0) / Decimal(400.0)
self.A[2, 1] = Decimal(-567603406766.0) / Decimal(11931857230679.0)
self.A[2, 2] = Decimal(41.0) / Decimal(200.0)
self.A[3, 0] = Decimal(683785636431.0) / Decimal(9252920307686.0)
self.A[3, 1] = 0.0
self.A[3, 2] = Decimal(-110385047103.0) / Decimal(1367015193373.0)
self.A[3, 3] = Decimal(41.0) / Decimal(200.0)
self.A[4, 0] = Decimal(3016520224154.0) / Decimal(10081342136671.0)
self.A[4, 1] = 0.0
self.A[4, 2] = Decimal(30586259806659.0) / Decimal(12414158314087.0)
self.A[4, 3] = Decimal(-22760509404356.0) / Decimal(11113319521817.0)
self.A[4, 4] = Decimal(41.0) / Decimal(200.0)
self.A[5, 0] = Decimal(218866479029.0) / Decimal(1489978393911.0)
self.A[5, 1] = 0.0
self.A[5, 2] = Decimal(638256894668.0) / Decimal(5436446318841.0)
self.A[5, 3] = Decimal(-1179710474555.0) / Decimal(5321154724896.0)
self.A[5, 4] = Decimal(-60928119172.0) / Decimal(8023461067671.0)
self.A[5, 5] = Decimal(41.0) / Decimal(200.0)
self.A[6, 0] = Decimal(1020004230633.0) / Decimal(5715676835656.0)
self.A[6, 1] = 0.0
self.A[6, 2] = Decimal(25762820946817.0) / Decimal(25263940353407.0)
self.A[6, 3] = Decimal(-2161375909145.0) / Decimal(9755907335909.0)
self.A[6, 4] = Decimal(-211217309593.0) / Decimal(5846859502534.0)
self.A[6, 5] = Decimal(-4269925059573.0) / Decimal(7827059040749.0)
self.A[6, 6] = Decimal(41.0) / Decimal(200.0)
self.A[7, 0] = Decimal(-872700587467.0) / Decimal(9133579230613.0)
self.A[7, 1] = 0.0
self.A[7, 2] = 0.0
self.A[7, 3] = Decimal(22348218063261.0) / Decimal(9555858737531.0)
self.A[7, 4] = Decimal(-1143369518992.0) / Decimal(8141816002931.0)
self.A[7, 5] = Decimal(-39379526789629.0) / Decimal(19018526304540.0)
self.A[7, 6] = Decimal(32727382324388.0) / Decimal(42900044865799.0)
self.A[7, 7] = Decimal(41.0) / Decimal(200.0)
self.b = np.zeros(8)
self.b[0] = Decimal(-975461918565.0) / Decimal(9796059967033.0)
self.b[1] = 0.0
self.b[2] = 0.0
self.b[3] = Decimal(78070527104295.0) / Decimal(32432590147079.0)
self.b[4] = Decimal(-548382580838.0) / Decimal(3424219808633.0)
self.b[5] = Decimal(-33438840321285.0) / Decimal(15594753105479.0)
self.b[6] = Decimal(3629800801594.0) / Decimal(4656183773603.0)
self.b[7] = Decimal(4035322873751.0) / Decimal(18575991585200.0)
self.nstages = 8
self.M_fast = sp.csc_matrix(M_fast)
self.M_slow = sp.csc_matrix(M_slow)
self.ndof = np.shape(M_fast)[0]
self.stages = np.zeros((self.nstages, self.ndof), dtype='complex')
def timestep(self, u0, dt):
# Solve for stages
for i in range(0, self.nstages):
# Construct RHS
rhs = np.copy(u0)
for j in range(0, i):
rhs += dt * self.A_hat[i, j] * (self.f_slow(self.stages[j, :])) + dt * self.A[i, j] * (
self.f_fast(self.stages[j, :])
)
# Solve for stage i
if self.A[i, i] == 0:
# Avoid call to spsolve with identity matrix
self.stages[i, :] = np.copy(rhs)
else:
self.stages[i, :] = self.f_fast_solve(rhs, dt * self.A[i, i])
# Update
for i in range(0, self.nstages):
u0 += dt * self.b_hat[i] * (self.f_slow(self.stages[i, :])) + dt * self.b[i] * (
self.f_fast(self.stages[i, :])
)
return u0
def f_slow(self, u):
return self.M_slow.dot(u)
def f_fast(self, u):
return self.M_fast.dot(u)
def f_fast_solve(self, rhs, alpha):
L = sp.eye(self.ndof) - alpha * self.M_fast
return LA.spsolve(L, rhs)
#
# Trapezoidal rule
#
class trapezoidal:
def __init__(self, M, alpha=0.5):
assert np.shape(M)[0] == np.shape(M)[1], "Matrix M must be quadratic"
self.Ndof = np.shape(M)[0]
self.M = M
self.alpha = alpha
def timestep(self, u0, dt):
M_trap = sp.eye(self.Ndof) - self.alpha * dt * self.M
B_trap = sp.eye(self.Ndof) + (1.0 - self.alpha) * dt * self.M
b = B_trap.dot(u0)
return LA.spsolve(M_trap, b)
#
# A BDF-2 implicit two-step method
#
class bdf2:
def __init__(self, M):
assert np.shape(M)[0] == np.shape(M)[1], "Matrix M must be quadratic"
self.Ndof = np.shape(M)[0]
self.M = M
def firsttimestep(self, u0, dt):
b = u0
L = sp.eye(self.Ndof) - dt * self.M
return LA.spsolve(L, b)
def timestep(self, u0, um1, dt):
b = (4.0 / 3.0) * u0 - (1.0 / 3.0) * um1
L = sp.eye(self.Ndof) - (2.0 / 3.0) * dt * self.M
return LA.spsolve(L, b)
#
# A diagonally implicit Runge-Kutta method of order 2, 3 or 4
#
class dirk:
def __init__(self, M, order):
assert np.shape(M)[0] == np.shape(M)[1], "Matrix M must be quadratic"
self.Ndof = np.shape(M)[0]
self.M = sp.csc_matrix(M)
self.order = order
assert self.order in [2, 22, 3, 4, 5], 'Order must be 2,22,3,4'
if self.order == 2:
self.nstages = 1
self.A = np.zeros((1, 1))
self.A[0, 0] = 0.5
self.tau = [0.5]
self.b = [1.0]
if self.order == 22:
self.nstages = 2
self.A = np.zeros((2, 2))
self.A[0, 0] = 1.0 / 3.0
self.A[1, 0] = 1.0 / 2.0
self.A[1, 1] = 1.0 / 2.0
self.tau = np.zeros(2)
self.tau[0] = 1.0 / 3.0
self.tau[1] = 1.0
self.b = np.zeros(2)
self.b[0] = 3.0 / 4.0
self.b[1] = 1.0 / 4.0
if self.order == 3:
self.nstages = 2
self.A = np.zeros((2, 2))
self.A[0, 0] = 0.5 + 1.0 / (2.0 * math.sqrt(3.0))
self.A[1, 0] = -1.0 / math.sqrt(3.0)
self.A[1, 1] = self.A[0, 0]
self.tau = np.zeros(2)
self.tau[0] = 0.5 + 1.0 / (2.0 * math.sqrt(3.0))
self.tau[1] = 0.5 - 1.0 / (2.0 * math.sqrt(3.0))
self.b = np.zeros(2)
self.b[0] = 0.5
self.b[1] = 0.5
if self.order == 4:
self.nstages = 3
alpha = 2.0 * math.cos(math.pi / 18.0) / math.sqrt(3.0)
self.A = np.zeros((3, 3))
self.A[0, 0] = (1.0 + alpha) / 2.0
self.A[1, 0] = -alpha / 2.0
self.A[1, 1] = self.A[0, 0]
self.A[2, 0] = 1.0 + alpha
self.A[2, 1] = -(1.0 + 2.0 * alpha)
self.A[2, 2] = self.A[0, 0]
self.tau = np.zeros(3)
self.tau[0] = (1.0 + alpha) / 2.0
self.tau[1] = 1.0 / 2.0
self.tau[2] = (1.0 - alpha) / 2.0
self.b = np.zeros(3)
self.b[0] = 1.0 / (6.0 * alpha * alpha)
self.b[1] = 1.0 - 1.0 / (3.0 * alpha * alpha)
self.b[2] = 1.0 / (6.0 * alpha * alpha)
if self.order == 5:
self.nstages = 5
# From Kennedy, Carpenter "Diagonally Implicit Runge-Kutta Methods for
# Ordinary Differential Equations. A Review"
self.A = np.zeros((5, 5))
self.A[0, 0] = 4024571134387.0 / 14474071345096.0
self.A[1, 0] = 9365021263232.0 / 12572342979331.0
self.A[1, 1] = self.A[0, 0]
self.A[2, 0] = 2144716224527.0 / 9320917548702.0
self.A[2, 1] = -397905335951.0 / 4008788611757.0
self.A[2, 2] = self.A[0, 0]
self.A[3, 0] = -291541413000.0 / 6267936762551.0
self.A[3, 1] = 226761949132.0 / 4473940808273.0
self.A[3, 2] = -1282248297070.0 / 9697416712681.0
self.A[3, 3] = self.A[0, 0]
self.A[4, 0] = -2481679516057.0 / 4626464057815.0
self.A[4, 1] = -197112422687.0 / 6604378783090.0
self.A[4, 2] = 3952887910906.0 / 9713059315593.0
self.A[4, 3] = 4906835613583.0 / 8134926921134.0
self.A[4, 4] = self.A[0, 0]
self.b = np.zeros(5)
self.b[0] = -2522702558582.0 / 12162329469185.0
self.b[1] = 1018267903655.0 / 12907234417901.0
self.b[2] = 4542392826351.0 / 13702606430957.0
self.b[3] = 5001116467727.0 / 12224457745473.0
self.b[4] = 1509636094297.0 / 3891594770934.0
self.stages = np.zeros((self.nstages, self.Ndof), dtype='complex')
def timestep(self, u0, dt):
uend = u0
for i in range(0, self.nstages):
b = u0
# Compute right hand side for this stage's implicit step
for j in range(0, i):
b = b + self.A[i, j] * dt * self.f(self.stages[j, :])
# Implicit solve for current stage
self.stages[i, :] = self.f_solve(b, dt * self.A[i, i])
# Add contribution of current stage to final value
uend = uend + self.b[i] * dt * self.f(self.stages[i, :])
return uend
#
# Returns f(u) = c*u
#
def f(self, u):
return self.M.dot(u)
#
# Solves (Id - alpha*c)*u = b for u
#
def f_solve(self, b, alpha):
L = sp.eye(self.Ndof) - alpha * self.M
return LA.spsolve(L, b)
| 16,711 | 39.26988 | 118 | py |
pySDC | pySDC-master/pySDC/implementations/problem_classes/acoustic_helpers/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/Runge_Kutta.py | import numpy as np
import logging
from pySDC.core.Sweeper import sweeper, _Pars
from pySDC.core.Errors import ParameterError
from pySDC.core.Level import level
from pySDC.implementations.datatype_classes.mesh import imex_mesh, mesh
class ButcherTableau(object):
def __init__(self, weights, nodes, matrix):
"""
Initialization routine to get a quadrature matrix out of a Butcher tableau
Args:
weights (numpy.ndarray): Butcher tableau weights
nodes (numpy.ndarray): Butcher tableau nodes
matrix (numpy.ndarray): Butcher tableau entries
"""
# check if the arguments have the correct form
if type(matrix) != np.ndarray:
raise ParameterError('Runge-Kutta matrix needs to be supplied as a numpy array!')
elif len(np.unique(matrix.shape)) != 1 or len(matrix.shape) != 2:
raise ParameterError('Runge-Kutta matrix needs to be a square 2D numpy array!')
if type(weights) != np.ndarray:
raise ParameterError('Weights need to be supplied as a numpy array!')
elif len(weights.shape) != 1:
raise ParameterError(f'Incompatible dimension of weights! Need 1, got {len(weights.shape)}')
elif len(weights) != matrix.shape[0]:
raise ParameterError(f'Incompatible number of weights! Need {matrix.shape[0]}, got {len(weights)}')
if type(nodes) != np.ndarray:
raise ParameterError('Nodes need to be supplied as a numpy array!')
elif len(nodes.shape) != 1:
raise ParameterError(f'Incompatible dimension of nodes! Need 1, got {len(nodes.shape)}')
elif len(nodes) != matrix.shape[0]:
raise ParameterError(f'Incompatible number of nodes! Need {matrix.shape[0]}, got {len(nodes)}')
# Set number of nodes, left and right interval boundaries
self.num_solution_stages = 1
self.num_nodes = matrix.shape[0] + self.num_solution_stages
self.tleft = 0.0
self.tright = 1.0
self.nodes = np.append(np.append([0], nodes), [1])
self.weights = weights
self.Qmat = np.zeros([self.num_nodes + 1, self.num_nodes + 1])
self.Qmat[1:-1, 1:-1] = matrix
self.Qmat[-1, 1:-1] = weights # this is for computing the solution to the step from the previous stages
self.left_is_node = True
self.right_is_node = self.nodes[-1] == self.tright
# compute distances between the nodes
if self.num_nodes > 1:
self.delta_m = self.nodes[1:] - self.nodes[:-1]
else:
self.delta_m = np.zeros(1)
self.delta_m[0] = self.nodes[0] - self.tleft
# check if the RK scheme is implicit
self.implicit = any(matrix[i, i] != 0 for i in range(self.num_nodes - self.num_solution_stages))
class ButcherTableauEmbedded(object):
def __init__(self, weights, nodes, matrix):
"""
Initialization routine to get a quadrature matrix out of a Butcher tableau for embedded RK methods.
Be aware that the method that generates the final solution should be in the first row of the weights matrix.
Args:
weights (numpy.ndarray): Butcher tableau weights
nodes (numpy.ndarray): Butcher tableau nodes
matrix (numpy.ndarray): Butcher tableau entries
"""
# check if the arguments have the correct form
if type(matrix) != np.ndarray:
raise ParameterError('Runge-Kutta matrix needs to be supplied as a numpy array!')
elif len(np.unique(matrix.shape)) != 1 or len(matrix.shape) != 2:
raise ParameterError('Runge-Kutta matrix needs to be a square 2D numpy array!')
if type(weights) != np.ndarray:
raise ParameterError('Weights need to be supplied as a numpy array!')
elif len(weights.shape) != 2:
raise ParameterError(f'Incompatible dimension of weights! Need 2, got {len(weights.shape)}')
elif len(weights[0]) != matrix.shape[0]:
raise ParameterError(f'Incompatible number of weights! Need {matrix.shape[0]}, got {len(weights[0])}')
if type(nodes) != np.ndarray:
raise ParameterError('Nodes need to be supplied as a numpy array!')
elif len(nodes.shape) != 1:
raise ParameterError(f'Incompatible dimension of nodes! Need 1, got {len(nodes.shape)}')
elif len(nodes) != matrix.shape[0]:
raise ParameterError(f'Incompatible number of nodes! Need {matrix.shape[0]}, got {len(nodes)}')
# Set number of nodes, left and right interval boundaries
self.num_solution_stages = 2
self.num_nodes = matrix.shape[0] + self.num_solution_stages
self.tleft = 0.0
self.tright = 1.0
self.nodes = np.append(np.append([0], nodes), [1, 1])
self.weights = weights
self.Qmat = np.zeros([self.num_nodes + 1, self.num_nodes + 1])
self.Qmat[1:-2, 1:-2] = matrix
self.Qmat[-1, 1:-2] = weights[0] # this is for computing the higher order solution
self.Qmat[-2, 1:-2] = weights[1] # this is for computing the lower order solution
self.left_is_node = True
self.right_is_node = self.nodes[-1] == self.tright
# compute distances between the nodes
if self.num_nodes > 1:
self.delta_m = self.nodes[1:] - self.nodes[:-1]
else:
self.delta_m = np.zeros(1)
self.delta_m[0] = self.nodes[0] - self.tleft
# check if the RK scheme is implicit
self.implicit = any(matrix[i, i] != 0 for i in range(self.num_nodes - self.num_solution_stages))
class RungeKutta(sweeper):
"""
Runge-Kutta scheme that fits the interface of a sweeper.
Actually, the sweeper idea fits the Runge-Kutta idea when using only lower triangular rules, where solutions
at the nodes are successively computed from earlier nodes. However, we only perform a single iteration of this.
We have two choices to realise a Runge-Kutta sweeper: We can choose Q = Q_Delta = <Butcher tableau>, but in this
implementation, that would lead to a lot of wasted FLOPS from integrating with Q and then with Q_Delta and
subtracting the two. For that reason, we built this new sweeper, which does not have a preconditioner.
This class only supports lower triangular Butcher tableaux such that the system can be solved with forward
substitution. In this way, we don't get the maximum order that we could for the number of stages, but computing the
stages is much cheaper. In particular, if the Butcher tableaux is strictly lower triangular, we get an explicit
method, which does not require us to solve a system of equations to compute the stages.
Please be aware that all fundamental parameters of the Sweeper are ignored. These include
- num_nodes
- collocation_class
- initial_guess
- QI
All of these variables are either determined by the RK rule, or are not part of an RK scheme.
Attributes:
butcher_tableau (ButcherTableau): Butcher tableau for the Runge-Kutta scheme that you want
"""
def __init__(self, params):
"""
Initialization routine for the custom sweeper
Args:
params: parameters for the sweeper
"""
# set up logger
self.logger = logging.getLogger('sweeper')
essential_keys = ['butcher_tableau']
for key in essential_keys:
if key not in params:
msg = 'need %s to instantiate step, only got %s' % (key, str(params.keys()))
self.logger.error(msg)
raise ParameterError(msg)
# check if some parameters are set which only apply to actual sweepers
for key in ['initial_guess', 'collocation_class', 'num_nodes']:
if key in params:
self.logger.warning(f'"{key}" will be ignored by Runge-Kutta sweeper')
# set parameters to their actual values
params['initial_guess'] = 'zero'
params['collocation_class'] = type(params['butcher_tableau'])
params['num_nodes'] = params['butcher_tableau'].num_nodes
# disable residual computation by default
params['skip_residual_computation'] = params.get(
'skip_residual_computation', ('IT_CHECK', 'IT_FINE', 'IT_COARSE', 'IT_UP', 'IT_DOWN')
)
# check if we can skip some usually unnecessary right hand side evaluations
params['eval_rhs_at_right_boundary'] = params.get('eval_rhs_at_right_boundary', False)
self.params = _Pars(params)
self.coll = params['butcher_tableau']
# This will be set as soon as the sweeper is instantiated at the level
self.__level = None
self.parallelizable = False
self.QI = self.coll.Qmat
@classmethod
def get_update_order(cls):
"""
Get the order of the lower order method for doing adaptivity. Only applies to embedded methods.
"""
raise NotImplementedError(
f"There is not an update order for RK scheme \"{cls.__name__}\" implemented. Maybe it is not an embedded scheme?"
)
def get_full_f(self, f):
"""
Get the full right hand side as a `mesh` from the right hand side
Args:
f (dtype_f): Right hand side at a single node
Returns:
mesh: Full right hand side as a mesh
"""
if type(f) == mesh:
return f
elif type(f) == imex_mesh:
return f.impl + f.expl
elif f is None:
prob = self.level.prob
return self.get_full_f(prob.dtype_f(prob.init, val=0))
else:
raise NotImplementedError(f'Type \"{type(f)}\" not implemented in Runge-Kutta sweeper')
def integrate(self):
"""
Integrates the right-hand side
Returns:
list of dtype_u: containing the integral as values
"""
# get current level and problem
lvl = self.level
prob = lvl.prob
me = []
# integrate RHS over all collocation nodes
for m in range(1, self.coll.num_nodes + 1):
# new instance of dtype_u, initialize values with 0
me.append(prob.dtype_u(prob.init, val=0.0))
for j in range(1, self.coll.num_nodes + 1):
me[-1] += lvl.dt * self.coll.Qmat[m, j] * self.get_full_f(lvl.f[j])
return me
def update_nodes(self):
"""
Update the u- and f-values at the collocation nodes
Returns:
None
"""
# get current level and problem
lvl = self.level
prob = lvl.prob
# only if the level has been touched before
assert lvl.status.unlocked
assert lvl.status.sweep <= 1, "RK schemes are direct solvers. Please perform only 1 iteration!"
# get number of collocation nodes for easier access
M = self.coll.num_nodes
for m in range(0, M):
# build rhs, consisting of the known values from above and new values from previous nodes (at k+1)
rhs = lvl.u[0]
for j in range(1, m + 1):
rhs += lvl.dt * self.QI[m + 1, j] * self.get_full_f(lvl.f[j])
# implicit solve with prefactor stemming from the diagonal of Qd
if self.coll.implicit:
lvl.u[m + 1][:] = prob.solve_system(
rhs, lvl.dt * self.QI[m + 1, m + 1], lvl.u[0], lvl.time + lvl.dt * self.coll.nodes[m]
)
else:
lvl.u[m + 1][:] = rhs[:]
# update function values (we don't usually need to evaluate the RHS at the solution of the step)
if m < M - self.coll.num_solution_stages or self.params.eval_rhs_at_right_boundary:
lvl.f[m + 1] = prob.eval_f(lvl.u[m + 1], lvl.time + lvl.dt * self.coll.nodes[m])
# indicate presence of new values at this level
lvl.status.updated = True
return None
def compute_end_point(self):
"""
In this Runge-Kutta implementation, the solution to the step is always stored in the last node
"""
self.level.uend = self.level.u[-1]
@property
def level(self):
"""
Returns the current level
Returns:
pySDC.Level.level: Current level
"""
return self.__level
@level.setter
def level(self, lvl):
"""
Sets a reference to the current level (done in the initialization of the level)
Args:
lvl (pySDC.Level.level): Current level
"""
assert isinstance(lvl, level), f"You tried to set the sweeper's level with an instance of {type(lvl)}!"
if lvl.params.restol > 0:
lvl.params.restol = -1
self.logger.warning(
'Overwriting residual tolerance with -1 because RK methods are direct and hence may not compute a residual at all!'
)
self.__level = lvl
def predict(self):
"""
Predictor to fill values at nodes before first sweep
"""
# get current level and problem
lvl = self.level
prob = lvl.prob
for m in range(1, self.coll.num_nodes + 1):
lvl.u[m] = prob.dtype_u(init=prob.init, val=0.0)
# indicate that this level is now ready for sweeps
lvl.status.unlocked = True
lvl.status.updated = True
class ForwardEuler(RungeKutta):
"""
Forward Euler. Still a classic.
Not very stable first order method.
"""
def __init__(self, params):
nodes = np.array([0.0])
weights = np.array([1.0])
matrix = np.array(
[
[0.0],
]
)
params['butcher_tableau'] = ButcherTableau(weights, nodes, matrix)
super().__init__(params)
class BackwardEuler(RungeKutta):
"""
Backward Euler. A favorite among true connoisseurs of the heat equation.
A-stable first order method.
"""
def __init__(self, params):
nodes = np.array([0.0])
weights = np.array([1.0])
matrix = np.array(
[
[1.0],
]
)
params['butcher_tableau'] = ButcherTableau(weights, nodes, matrix)
super().__init__(params)
class CrankNicholson(RungeKutta):
"""
Implicit Runge-Kutta method of second order, A-stable.
"""
def __init__(self, params):
nodes = np.array([0, 1])
weights = np.array([0.5, 0.5])
matrix = np.zeros((2, 2))
matrix[1, 0] = 0.5
matrix[1, 1] = 0.5
params['butcher_tableau'] = ButcherTableau(weights, nodes, matrix)
super().__init__(params)
class ExplicitMidpointMethod(RungeKutta):
"""
Explicit Runge-Kutta method of second order.
"""
def __init__(self, params):
nodes = np.array([0, 0.5])
weights = np.array([0, 1])
matrix = np.zeros((2, 2))
matrix[1, 0] = 0.5
params['butcher_tableau'] = ButcherTableau(weights, nodes, matrix)
super().__init__(params)
class ImplicitMidpointMethod(RungeKutta):
"""
Implicit Runge-Kutta method of second order.
"""
def __init__(self, params):
nodes = np.array([0.5])
weights = np.array([1])
matrix = np.zeros((1, 1))
matrix[0, 0] = 1.0 / 2.0
params['butcher_tableau'] = ButcherTableau(weights, nodes, matrix)
super().__init__(params)
class RK4(RungeKutta):
"""
Explicit Runge-Kutta of fourth order: Everybody's darling.
"""
def __init__(self, params):
nodes = np.array([0, 0.5, 0.5, 1])
weights = np.array([1.0, 2.0, 2.0, 1.0]) / 6.0
matrix = np.zeros((4, 4))
matrix[1, 0] = 0.5
matrix[2, 1] = 0.5
matrix[3, 2] = 1.0
params['butcher_tableau'] = ButcherTableau(weights, nodes, matrix)
super().__init__(params)
class Heun_Euler(RungeKutta):
"""
Second order explicit embedded Runge-Kutta method.
"""
def __init__(self, params):
nodes = np.array([0, 1])
weights = np.array([[0.5, 0.5], [1, 0]])
matrix = np.zeros((2, 2))
matrix[1, 0] = 1
params['butcher_tableau'] = ButcherTableauEmbedded(weights, nodes, matrix)
super().__init__(params)
@classmethod
def get_update_order(cls):
return 2
class Cash_Karp(RungeKutta):
"""
Fifth order explicit embedded Runge-Kutta. See [here](https://doi.org/10.1145/79505.79507).
"""
def __init__(self, params):
nodes = np.array([0, 0.2, 0.3, 0.6, 1.0, 7.0 / 8.0])
weights = np.array(
[
[37.0 / 378.0, 0.0, 250.0 / 621.0, 125.0 / 594.0, 0.0, 512.0 / 1771.0],
[2825.0 / 27648.0, 0.0, 18575.0 / 48384.0, 13525.0 / 55296.0, 277.0 / 14336.0, 1.0 / 4.0],
]
)
matrix = np.zeros((6, 6))
matrix[1, 0] = 1.0 / 5.0
matrix[2, :2] = [3.0 / 40.0, 9.0 / 40.0]
matrix[3, :3] = [0.3, -0.9, 1.2]
matrix[4, :4] = [-11.0 / 54.0, 5.0 / 2.0, -70.0 / 27.0, 35.0 / 27.0]
matrix[5, :5] = [1631.0 / 55296.0, 175.0 / 512.0, 575.0 / 13824.0, 44275.0 / 110592.0, 253.0 / 4096.0]
params['butcher_tableau'] = ButcherTableauEmbedded(weights, nodes, matrix)
super().__init__(params)
@classmethod
def get_update_order(cls):
return 5
class DIRK43(RungeKutta):
"""
Embedded A-stable diagonally implicit RK pair of order 3 and 4.
Taken from [here](https://doi.org/10.1007/BF01934920).
"""
def __init__(self, params):
nodes = np.array([5.0 / 6.0, 10.0 / 39.0, 0, 1.0 / 6.0])
weights = np.array(
[[61.0 / 150.0, 2197.0 / 2100.0, 19.0 / 100.0, -9.0 / 14.0], [32.0 / 75.0, 169.0 / 300.0, 1.0 / 100.0, 0.0]]
)
matrix = np.zeros((4, 4))
matrix[0, 0] = 5.0 / 6.0
matrix[1, :2] = [-15.0 / 26.0, 5.0 / 6.0]
matrix[2, :3] = [215.0 / 54.0, -130.0 / 27.0, 5.0 / 6.0]
matrix[3, :] = [4007.0 / 6075.0, -31031.0 / 24300.0, -133.0 / 2700.0, 5.0 / 6.0]
params['butcher_tableau'] = ButcherTableauEmbedded(weights, nodes, matrix)
super().__init__(params)
@classmethod
def get_update_order(cls):
return 4
class ESDIRK53(RungeKutta):
"""
A-stable embedded RK pair of orders 5 and 3.
Taken from [here](https://ntrs.nasa.gov/citations/20160005923)
"""
def __init__(self, params):
nodes = np.array(
[0, 4024571134387.0 / 7237035672548.0, 14228244952610.0 / 13832614967709.0, 1.0 / 10.0, 3.0 / 50.0, 1.0]
)
matrix = np.zeros((6, 6))
matrix[1, :2] = [3282482714977.0 / 11805205429139.0, 3282482714977.0 / 11805205429139.0]
matrix[2, :3] = [
606638434273.0 / 1934588254988,
2719561380667.0 / 6223645057524,
3282482714977.0 / 11805205429139.0,
]
matrix[3, :4] = [
-651839358321.0 / 6893317340882,
-1510159624805.0 / 11312503783159,
235043282255.0 / 4700683032009.0,
3282482714977.0 / 11805205429139.0,
]
matrix[4, :5] = [
-5266892529762.0 / 23715740857879,
-1007523679375.0 / 10375683364751,
521543607658.0 / 16698046240053.0,
514935039541.0 / 7366641897523.0,
3282482714977.0 / 11805205429139.0,
]
matrix[5, :] = [
-6225479754948.0 / 6925873918471,
6894665360202.0 / 11185215031699,
-2508324082331.0 / 20512393166649,
-7289596211309.0 / 4653106810017.0,
39811658682819.0 / 14781729060964.0,
3282482714977.0 / 11805205429139,
]
weights = np.array(
[
[
-6225479754948.0 / 6925873918471,
6894665360202.0 / 11185215031699.0,
-2508324082331.0 / 20512393166649,
-7289596211309.0 / 4653106810017,
39811658682819.0 / 14781729060964.0,
3282482714977.0 / 11805205429139,
],
[
-2512930284403.0 / 5616797563683,
5849584892053.0 / 8244045029872,
-718651703996.0 / 6000050726475.0,
-18982822128277.0 / 13735826808854.0,
23127941173280.0 / 11608435116569.0,
2847520232427.0 / 11515777524847.0,
],
]
)
params['butcher_tableau'] = ButcherTableauEmbedded(weights, nodes, matrix)
super().__init__(params)
@classmethod
def get_update_order(cls):
return 4
| 20,808 | 35.189565 | 131 | py |
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/imex_1st_order_mass.py | from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
class imex_1st_order_mass(imex_1st_order):
"""
Custom sweeper class, implements Sweeper.py
First-order IMEX sweeper using implicit/explicit Euler as base integrator, with mass or weighting matrix
"""
def update_nodes(self):
"""
Update the u- and f-values at the collocation nodes -> corresponds to a single sweep over all nodes
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# only if the level has been touched before
assert L.status.unlocked
# get number of collocation nodes for easier access
M = self.coll.num_nodes
# gather all terms which are known already (e.g. from the previous iteration)
# this corresponds to u0 + QF(u^k) - QIFI(u^k) - QEFE(u^k) + tau
# get QF(u^k)
integral = self.integrate()
# This is somewhat ugly, but we have to apply the mass matrix on u0 only on the finest level
if L.level_index == 0:
u0 = P.apply_mass_matrix(L.u[0])
else:
u0 = L.u[0]
for m in range(M):
# subtract QIFI(u^k)_m + QEFE(u^k)_m
for j in range(M + 1):
integral[m] -= L.dt * (self.QI[m + 1, j] * L.f[j].impl + self.QE[m + 1, j] * L.f[j].expl)
# add initial value
integral[m] += u0
# add tau if associated
if L.tau[m] is not None:
integral[m] += L.tau[m]
# do the sweep
for m in range(0, M):
# build rhs, consisting of the known values from above and new values from previous nodes (at k+1)
rhs = P.dtype_u(integral[m])
for j in range(m + 1):
rhs += L.dt * (self.QI[m + 1, j] * L.f[j].impl + self.QE[m + 1, j] * L.f[j].expl)
# implicit solve with prefactor stemming from QI
L.u[m + 1] = P.solve_system(
rhs, L.dt * self.QI[m + 1, m + 1], L.u[m + 1], L.time + L.dt * self.coll.nodes[m]
)
# update function values
L.f[m + 1] = P.eval_f(L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
# indicate presence of new values at this level
L.status.updated = True
return None
def compute_end_point(self):
"""
Compute u at the right point of the interval
The value uend computed here is a full evaluation of the Picard formulation unless do_full_update==False
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# check if Mth node is equal to right point and do_coll_update is false, perform a simple copy
if self.coll.right_is_node and not self.params.do_coll_update:
# a copy is sufficient
L.uend = P.dtype_u(L.u[-1])
else:
raise NotImplementedError('Mass matrix sweeper expect u_M = u_end')
return None
def compute_residual(self, stage=None):
"""
Computation of the residual using the collocation matrix Q
Args:
stage (str): The current stage of the step the level belongs to
"""
# get current level and problem description
L = self.level
P = L.prob
# Check if we want to skip the residual computation to gain performance
# Keep in mind that skipping any residual computation is likely to give incorrect outputs of the residual!
if stage in self.params.skip_residual_computation:
L.status.residual = 0.0 if L.status.residual is None else L.status.residual
return None
# check if there are new values (e.g. from a sweep)
# assert L.status.updated
# compute the residual for each node
# build QF(u)
res_norm = []
res = self.integrate()
for m in range(self.coll.num_nodes):
# This is somewhat ugly, but we have to apply the mass matrix on u0 only on the finest level
if L.level_index == 0:
res[m] += P.apply_mass_matrix(L.u[0] - L.u[m + 1])
else:
res[m] += L.u[0] - P.apply_mass_matrix(L.u[m + 1])
# add tau if associated
if L.tau[m] is not None:
res[m] += L.tau[m]
# use abs function from data type here
res_norm.append(abs(res[m]))
# find maximal residual over the nodes
L.status.residual = max(res_norm)
# indicate that the residual has seen the new values
L.status.updated = False
return None
| 4,749 | 33.42029 | 114 | py |
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/explicit.py | from pySDC.core.Sweeper import sweeper
class explicit(sweeper):
"""
Custom sweeper class, implements Sweeper.py
Attributes:
QE: explicit Euler integration matrix
"""
def __init__(self, params):
"""
Initialization routine for the custom sweeper
Args:
params: parameters for the sweeper
"""
if 'QE' not in params:
params['QE'] = 'EE'
# call parent's initialization routine
super(explicit, self).__init__(params)
# integration matrix
self.QE = self.get_Qdelta_explicit(coll=self.coll, qd_type=self.params.QE)
def integrate(self):
"""
Integrates the right-hand side
Returns:
list of dtype_u: containing the integral as values
"""
# get current level and problem description
L = self.level
P = L.prob
me = []
# integrate RHS over all collocation nodes
for m in range(1, self.coll.num_nodes + 1):
# new instance of dtype_u, initialize values with 0
me.append(P.dtype_u(P.init, val=0.0))
for j in range(1, self.coll.num_nodes + 1):
me[-1] += L.dt * self.coll.Qmat[m, j] * L.f[j]
return me
def update_nodes(self):
"""
Update the u- and f-values at the collocation nodes -> corresponds to a single sweep over all nodes
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# only if the level has been touched before
assert L.status.unlocked
# get number of collocation nodes for easier access
M = self.coll.num_nodes
# gather all terms which are known already (e.g. from the previous iteration)
# this corresponds to u0 + QF(u^k) - QEFE(u^k) + tau
# get QF(u^k)
integral = self.integrate()
for m in range(M):
# subtract QEFE(u^k)_m
for j in range(1, M + 1):
integral[m] -= L.dt * self.QE[m + 1, j] * L.f[j]
# add initial value
integral[m] += L.u[0]
# add tau if associated
if L.tau[m] is not None:
integral[m] += L.tau[m]
# do the sweep
for m in range(0, M):
# build new u, consisting of the known values from above and new values from previous nodes (at k+1)
L.u[m + 1] = P.dtype_u(integral[m])
for j in range(1, m + 1):
L.u[m + 1] += L.dt * self.QE[m + 1, j] * L.f[j]
# update function values
L.f[m + 1] = P.eval_f(L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
# indicate presence of new values at this level
L.status.updated = True
return None
def compute_end_point(self):
"""
Compute u at the right point of the interval
The value uend computed here is a full evaluation of the Picard formulation unless do_full_update==False
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# check if Mth node is equal to right point and do_coll_update is false, perform a simple copy
if self.coll.right_is_node and not self.params.do_coll_update:
# a copy is sufficient
L.uend = P.dtype_u(L.u[-1])
else:
# start with u0 and add integral over the full interval (using coll.weights)
L.uend = P.dtype_u(L.u[0])
for m in range(self.coll.num_nodes):
L.uend += L.dt * self.coll.weights[m] * L.f[m + 1]
# add up tau correction of the full interval (last entry)
if L.tau[-1] is not None:
L.uend += L.tau[-1]
return None
| 3,872 | 29.257813 | 112 | py |
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/generic_implicit.py | from pySDC.core.Sweeper import sweeper
class generic_implicit(sweeper):
"""
Generic implicit sweeper, expecting lower triangular matrix type as input
Attributes:
QI: lower triangular matrix
"""
def __init__(self, params):
"""
Initialization routine for the custom sweeper
Args:
params: parameters for the sweeper
"""
if 'QI' not in params:
params['QI'] = 'IE'
# call parent's initialization routine
super(generic_implicit, self).__init__(params)
# get QI matrix
self.QI = self.get_Qdelta_implicit(self.coll, qd_type=self.params.QI)
def integrate(self):
"""
Integrates the right-hand side
Returns:
list of dtype_u: containing the integral as values
"""
# get current level and problem description
L = self.level
P = L.prob
me = []
# integrate RHS over all collocation nodes
for m in range(1, self.coll.num_nodes + 1):
# new instance of dtype_u, initialize values with 0
me.append(P.dtype_u(P.init, val=0.0))
for j in range(1, self.coll.num_nodes + 1):
me[-1] += L.dt * self.coll.Qmat[m, j] * L.f[j]
return me
def update_nodes(self):
"""
Update the u- and f-values at the collocation nodes -> corresponds to a single sweep over all nodes
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# only if the level has been touched before
assert L.status.unlocked
# get number of collocation nodes for easier access
M = self.coll.num_nodes
# gather all terms which are known already (e.g. from the previous iteration)
# this corresponds to u0 + QF(u^k) - QdF(u^k) + tau
# get QF(u^k)
integral = self.integrate()
for m in range(M):
# get -QdF(u^k)_m
for j in range(1, M + 1):
integral[m] -= L.dt * self.QI[m + 1, j] * L.f[j]
# add initial value
integral[m] += L.u[0]
# add tau if associated
if L.tau[m] is not None:
integral[m] += L.tau[m]
# do the sweep
for m in range(0, M):
# build rhs, consisting of the known values from above and new values from previous nodes (at k+1)
rhs = P.dtype_u(integral[m])
for j in range(1, m + 1):
rhs += L.dt * self.QI[m + 1, j] * L.f[j]
# implicit solve with prefactor stemming from the diagonal of Qd
L.u[m + 1] = P.solve_system(
rhs, L.dt * self.QI[m + 1, m + 1], L.u[m + 1], L.time + L.dt * self.coll.nodes[m]
)
# update function values
L.f[m + 1] = P.eval_f(L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
# indicate presence of new values at this level
L.status.updated = True
return None
def compute_end_point(self):
"""
Compute u at the right point of the interval
The value uend computed here is a full evaluation of the Picard formulation unless do_full_update==False
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# check if Mth node is equal to right point and do_coll_update is false, perform a simple copy
if self.coll.right_is_node and not self.params.do_coll_update:
# a copy is sufficient
L.uend = P.dtype_u(L.u[-1])
else:
# start with u0 and add integral over the full interval (using coll.weights)
L.uend = P.dtype_u(L.u[0])
for m in range(self.coll.num_nodes):
L.uend += L.dt * self.coll.weights[m] * L.f[m + 1]
# add up tau correction of the full interval (last entry)
if L.tau[-1] is not None:
L.uend += L.tau[-1]
return None
| 4,107 | 29.887218 | 112 | py |
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/boris_2nd_order.py | import numpy as np
from pySDC.core.Sweeper import sweeper
class boris_2nd_order(sweeper):
"""
Custom sweeper class, implements Sweeper.py
Second-order sweeper using velocity-Verlet with Boris scheme as base integrator
Attributes:
S: node-to-node collocation matrix (first order)
SQ: node-to-node collocation matrix (second order)
ST: node-to-node trapezoidal matrix
Sx: node-to-node Euler half-step for position update
"""
def __init__(self, params):
"""
Initialization routine for the custom sweeper
Args:
params: parameters for the sweeper
"""
# call parent's initialization routine
if "QI" not in params:
params["QI"] = "IE"
if "QE" not in params:
params["QE"] = "EE"
super(boris_2nd_order, self).__init__(params)
# S- and SQ-matrices (derived from Q) and Sx- and ST-matrices for the integrator
[
self.S,
self.ST,
self.SQ,
self.Sx,
self.QQ,
self.QI,
self.QT,
self.Qx,
self.Q,
] = self.__get_Qd()
self.qQ = np.dot(self.coll.weights, self.coll.Qmat[1:, 1:])
def __get_Qd(self):
"""
Get integration matrices for 2nd-order SDC
Returns:
S: node-to-node collocation matrix (first order)
SQ: node-to-node collocation matrix (second order)
ST: node-to-node trapezoidal matrix
Sx: node-to-node Euler half-step for position update
"""
# set implicit and explicit Euler matrices (default, but can be changed)
QI = self.get_Qdelta_implicit(self.coll, qd_type=self.params.QI)
QE = self.get_Qdelta_explicit(self.coll, qd_type=self.params.QE)
# trapezoidal rule
QT = 1 / 2 * (QI + QE)
# Qx as in the paper
Qx = np.dot(QE, QT) + 1 / 2 * QE * QE
Sx = np.zeros(np.shape(self.coll.Qmat))
ST = np.zeros(np.shape(self.coll.Qmat))
S = np.zeros(np.shape(self.coll.Qmat))
# fill-in node-to-node matrices
Sx[0, :] = Qx[0, :]
ST[0, :] = QT[0, :]
S[0, :] = self.coll.Qmat[0, :]
for m in range(self.coll.num_nodes):
Sx[m + 1, :] = Qx[m + 1, :] - Qx[m, :]
ST[m + 1, :] = QT[m + 1, :] - QT[m, :]
S[m + 1, :] = self.coll.Qmat[m + 1, :] - self.coll.Qmat[m, :]
# SQ via dot-product, could also be done via QQ
SQ = np.dot(S, self.coll.Qmat)
# QQ-matrix via product of Q
QQ = np.dot(self.coll.Qmat, self.coll.Qmat)
return [S, ST, SQ, Sx, QQ, QI, QT, Qx, self.coll.Qmat]
def update_nodes(self):
"""
Update the u- and f-values at the collocation nodes -> corresponds to a single sweep over all nodes
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# only if the level has been touched before
assert L.status.unlocked
# get number of collocation nodes for easier access
M = self.coll.num_nodes
# initialize integral terms with zeros, will add stuff later
integral = [P.dtype_u(P.init, val=0.0) for l in range(M)]
# gather all terms which are known already (e.g. from the previous iteration)
# this corresponds to SF(u^k) - SdF(u^k) + tau (note: have integrals in pos and vel!)
for m in range(M):
for j in range(M + 1):
# build RHS from f-terms (containing the E field) and the B field
f = P.build_f(L.f[j], L.u[j], L.time + L.dt * self.coll.nodes[j - 1])
# add SQF(u^k) - SxF(u^k) for the position
integral[m].pos += L.dt * (L.dt * (self.SQ[m + 1, j] - self.Sx[m + 1, j]) * f)
# add SF(u^k) - STF(u^k) for the velocity
integral[m].vel += L.dt * (self.S[m + 1, j] - self.ST[m + 1, j]) * f
# add tau if associated
if L.tau[m] is not None:
integral[m] += L.tau[m]
# tau is 0-to-node, need to change it to node-to-node here
if m > 0:
integral[m] -= L.tau[m - 1]
# do the sweep
for m in range(0, M):
# build rhs, consisting of the known values from above and new values from previous nodes (at k+1)
tmp = P.dtype_u(integral[m])
for j in range(m + 1):
# build RHS from f-terms (containing the E field) and the B field
f = P.build_f(L.f[j], L.u[j], L.time + L.dt * self.coll.nodes[j - 1])
# add SxF(u^{k+1})
tmp.pos += L.dt * (L.dt * self.Sx[m + 1, j] * f)
# add pos at previous node + dt*v0
tmp.pos += L.u[m].pos + L.dt * self.coll.delta_m[m] * L.u[0].vel
# set new position, is explicit
L.u[m + 1].pos = tmp.pos
# get E field with new positions and compute mean
L.f[m + 1] = P.eval_f(L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
ck = tmp.vel
# do the boris scheme
L.u[m + 1].vel = P.boris_solver(ck, L.dt * np.diag(self.QI)[m + 1], L.f[m], L.f[m + 1], L.u[m])
# indicate presence of new values at this level
L.status.updated = True
return None
def integrate(self):
"""
Integrates the right-hand side
Returns:
list of dtype_u: containing the integral as values
"""
# get current level and problem description
L = self.level
P = L.prob
# create new instance of dtype_u, initialize values with 0
p = []
for m in range(1, self.coll.num_nodes + 1):
p.append(P.dtype_u(P.init, val=0.0))
# integrate RHS over all collocation nodes, RHS is here only f(x,v)!
for j in range(1, self.coll.num_nodes + 1):
f = P.build_f(L.f[j], L.u[j], L.time + L.dt * self.coll.nodes[j - 1])
p[-1].pos += L.dt * (L.dt * self.QQ[m, j] * f) + L.dt * self.coll.Qmat[m, j] * L.u[0].vel
p[-1].vel += L.dt * self.coll.Qmat[m, j] * f
return p
def compute_end_point(self):
"""
Compute u at the right point of the interval
The value uend computed here is a full evaluation of the Picard formulation (always!)
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# start with u0 and add integral over the full interval (using coll.weights)
L.uend = P.dtype_u(L.u[0])
for m in range(self.coll.num_nodes):
f = P.build_f(L.f[m + 1], L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
L.uend.pos += L.dt * (L.dt * self.qQ[m] * f) + L.dt * self.coll.weights[m] * L.u[0].vel
L.uend.vel += L.dt * self.coll.weights[m] * f
# add up tau correction of the full interval (last entry)
if L.tau[-1] is not None:
L.uend += L.tau[-1]
return None
def get_sweeper_mats(self):
"""
Returns the matrices Q, QQ, Qx, QT which define the sweeper.
"""
Q = self.Q[1:, 1:]
QQ = self.QQ[1:, 1:]
Qx = self.Qx[1:, 1:]
QT = self.QT[1:, 1:]
return Q, QQ, Qx, QT
def get_scalar_problems_sweeper_mats(self, lambdas=None):
"""
This function returns the corresponding matrices of an SDC sweep matrix formulation
Args:
lambdas (numpy.narray): the first entry in lambdas is k-spring constant and the second is mu friction.
"""
Q, QQ, Qx, QT = self.get_sweeper_mats()
if lambdas is None:
pass
# should use lambdas from attached problem and make sure it is scalar SDC
raise NotImplementedError("At the moment, the values for the lambda have to be provided")
else:
k = lambdas[0]
mu = lambdas[1]
nnodes = self.coll.num_nodes
dt = self.level.dt
F = np.block(
[
[-k * np.eye(nnodes), -mu * np.eye(nnodes)],
[-k * np.eye(nnodes), -mu * np.eye(nnodes)],
]
)
C_coll = np.block([[np.eye(nnodes), dt * Q], [np.zeros([nnodes, nnodes]), np.eye(nnodes)]])
Q_coll = np.block(
[
[dt**2 * QQ, np.zeros([nnodes, nnodes])],
[np.zeros([nnodes, nnodes]), dt * Q],
]
)
Q_vv = np.block(
[
[dt**2 * Qx, np.zeros([nnodes, nnodes])],
[np.zeros([nnodes, nnodes]), dt * QT],
]
)
M_vv = np.eye(2 * nnodes) - np.dot(Q_vv, F)
return C_coll, Q_coll, Q_vv, M_vv, F
def get_scalar_problems_manysweep_mats(self, nsweeps, lambdas=None):
"""
For a scalar problem, K sweeps of SDC can be written in matrix form.
Args:
nsweeps (int): number of sweeps
lambdas (numpy.ndarray): the first entry in lambdas is k-spring constant and the second is mu friction.
"""
nnodes = self.coll.num_nodes
C_coll, Q_coll, Q_vv, M_vv, F = self.get_scalar_problems_sweeper_mats(lambdas=lambdas)
K_sdc = np.dot(np.linalg.inv(M_vv), Q_coll - Q_vv) @ F
Keig, Kvec = np.linalg.eig(K_sdc)
Kp_sdc = np.linalg.matrix_power(K_sdc, nsweeps)
Kinv_sdc = np.linalg.inv(np.eye(2 * nnodes) - K_sdc)
Kdot_sdc = np.dot(np.eye(2 * nnodes) - Kp_sdc, Kinv_sdc)
MC = np.dot(np.linalg.inv(M_vv), C_coll)
Mat_sweep = Kp_sdc + np.dot(Kdot_sdc, MC)
return Mat_sweep, np.max(np.abs(Keig))
def get_scalar_problems_picardsweep_mats(self, nsweeps, lambdas=None):
"""
For a scalar problem, K sweeps of SDC can be written in matrix form.
Args:
nsweeps (int): number of sweeps
lambdas (numpy.ndarray): the first entry in lambdas is k-spring constant and the second is mu friction.
"""
nnodes = self.coll.num_nodes
C_coll, Q_coll, Q_vv, M_vv, F = self.get_scalar_problems_sweeper_mats(lambdas=lambdas)
K_sdc = np.dot(Q_coll, F)
Keig, Kvec = np.linalg.eig(K_sdc)
Kp_sdc = np.linalg.matrix_power(K_sdc, nsweeps)
Kinv_sdc = np.linalg.inv(np.eye(2 * nnodes) - K_sdc)
Kdot_sdc = np.dot(np.eye(2 * nnodes) - Kp_sdc, Kinv_sdc)
Mat_sweep = Kp_sdc + np.dot(Kdot_sdc, C_coll)
return Mat_sweep, np.max(np.abs(Keig))
| 10,711 | 32.898734 | 115 | py |
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/verlet.py | import numpy as np
from pySDC.core.Sweeper import sweeper
class verlet(sweeper):
"""
Custom sweeper class, implements Sweeper.py
Second-order sweeper using velocity-Verlet as base integrator
Attributes:
QQ: 0-to-node collocation matrix (second order)
QT: 0-to-node trapezoidal matrix
Qx: 0-to-node Euler half-step for position update
qQ: update rule for final value (if needed)
"""
def __init__(self, params):
"""
Initialization routine for the custom sweeper
Args:
params: parameters for the sweeper
"""
if 'QI' not in params:
params['QI'] = 'IE'
if 'QE' not in params:
params['QE'] = 'EE'
# call parent's initialization routine
super(verlet, self).__init__(params)
# Trapezoidal rule, Qx and Double-Q as in the Boris-paper
[self.QT, self.Qx, self.QQ] = self.__get_Qd()
self.qQ = np.dot(self.coll.weights, self.coll.Qmat[1:, 1:])
def __get_Qd(self):
"""
Get integration matrices for 2nd-order SDC
Returns:
S: node-to-node collocation matrix (first order)
SQ: node-to-node collocation matrix (second order)
ST: node-to-node trapezoidal matrix
Sx: node-to-node Euler half-step for position update
"""
# set implicit and explicit Euler matrices
QI = self.get_Qdelta_implicit(self.coll, self.params.QI)
QE = self.get_Qdelta_explicit(self.coll, self.params.QE)
# trapezoidal rule
QT = 0.5 * (QI + QE)
# QT = QI
# Qx as in the paper
Qx = np.dot(QE, QT) + 0.5 * QE * QE
QQ = np.zeros(np.shape(self.coll.Qmat))
# if we have Gauss-Lobatto nodes, we can do a magic trick from the Book
# this takes Gauss-Lobatto IIIB and create IIIA out of this
if self.coll.node_type == 'LEGENDRE' and self.coll.quad_type == 'LOBATTO':
for m in range(self.coll.num_nodes):
for n in range(self.coll.num_nodes):
QQ[m + 1, n + 1] = self.coll.weights[n] * (
1.0 - self.coll.Qmat[n + 1, m + 1] / self.coll.weights[m]
)
QQ = np.dot(self.coll.Qmat, QQ)
# if we do not have Gauss-Lobatto, just multiply Q (will not get a symplectic method, they say)
else:
QQ = np.dot(self.coll.Qmat, self.coll.Qmat)
return [QT, Qx, QQ]
def update_nodes(self):
"""
Update the u- and f-values at the collocation nodes -> corresponds to a single sweep over all nodes
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# only if the level has been touched before
assert L.status.unlocked
# get number of collocation nodes for easier access
M = self.coll.num_nodes
# gather all terms which are known already (e.g. from the previous iteration)
# get QF(u^k)
integral = self.integrate()
for m in range(M):
# get -QdF(u^k)_m
for j in range(1, M + 1):
integral[m].pos -= L.dt * (L.dt * self.Qx[m + 1, j] * L.f[j])
integral[m].vel -= L.dt * self.QT[m + 1, j] * L.f[j]
# add initial value
integral[m].pos += L.u[0].pos
integral[m].vel += L.u[0].vel
# add tau if associated
if L.tau[m] is not None:
integral[m] += L.tau[m]
# do the sweep
for m in range(0, M):
# build rhs, consisting of the known values from above and new values from previous nodes (at k+1)
L.u[m + 1] = P.dtype_u(integral[m])
for j in range(1, m + 1):
# add QxF(u^{k+1})
L.u[m + 1].pos += L.dt * (L.dt * self.Qx[m + 1, j] * L.f[j])
L.u[m + 1].vel += L.dt * self.QT[m + 1, j] * L.f[j]
# get RHS with new positions
L.f[m + 1] = P.eval_f(L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
L.u[m + 1].vel += L.dt * self.QT[m + 1, m + 1] * L.f[m + 1]
# indicate presence of new values at this level
L.status.updated = True
# # do the sweep (alternative description)
# for m in range(0, M):
# # build rhs, consisting of the known values from above and new values from previous nodes (at k+1)
# L.u[m + 1] = P.dtype_u(integral[m])
# for j in range(1, m + 1):
# # add QxF(u^{k+1})
# L.u[m + 1].pos += L.dt * (L.dt * self.Qx[m + 1, j] * L.f[j])
#
# # get RHS with new positions
# L.f[m + 1] = P.eval_f(L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
#
# for m in range(0, M):
# for n in range(0, M):
# L.u[m + 1].vel += L.dt * self.QT[m + 1, n + 1] * L.f[n + 1]
#
# # indicate presence of new values at this level
# L.status.updated = True
return None
def integrate(self):
"""
Integrates the right-hand side
Returns:
list of dtype_u: containing the integral as values
"""
# get current level and problem description
L = self.level
P = L.prob
# create new instance of dtype_u, initialize values with 0
p = []
for m in range(1, self.coll.num_nodes + 1):
p.append(P.dtype_u(P.init, val=0.0))
# integrate RHS over all collocation nodes, RHS is here only f(x)!
for j in range(1, self.coll.num_nodes + 1):
p[-1].pos += L.dt * (L.dt * self.QQ[m, j] * L.f[j]) + L.dt * self.coll.Qmat[m, j] * L.u[0].vel
p[-1].vel += L.dt * self.coll.Qmat[m, j] * L.f[j]
# we need to set mass and charge here, too, since the code uses the integral to create new particles
p[-1].m = L.u[0].m
p[-1].q = L.u[0].q
return p
def compute_end_point(self):
"""
Compute u at the right point of the interval
The value uend computed here is a full evaluation of the Picard formulation (always!)
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# start with u0 and add integral over the full interval (using coll.weights)
if self.coll.right_is_node and not self.params.do_coll_update:
# a copy is sufficient
L.uend = P.dtype_u(L.u[-1])
else:
L.uend = P.dtype_u(L.u[0])
for m in range(self.coll.num_nodes):
L.uend.pos += L.dt * (L.dt * self.qQ[m] * L.f[m + 1]) + L.dt * self.coll.weights[m] * L.u[0].vel
L.uend.vel += L.dt * self.coll.weights[m] * L.f[m + 1]
# remember to set mass and charge here, too
L.uend.m = L.u[0].m
L.uend.q = L.u[0].q
# add up tau correction of the full interval (last entry)
if L.tau[-1] is not None:
L.uend += L.tau[-1]
return None
| 7,247 | 33.846154 | 116 | py |
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/__init__.py | __author__ = 'robert'
| 22 | 10.5 | 21 | py |
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/multi_implicit.py | from pySDC.core.Sweeper import sweeper
class multi_implicit(sweeper):
"""
Custom sweeper class, implements Sweeper.py
First-order multi-implicit sweeper for two components
Attributes:
Q1: implicit integration matrix for the first component
Q2: implicit integration matrix for the second component
"""
def __init__(self, params):
"""
Initialization routine for the custom sweeper
Args:
params: parameters for the sweeper
"""
# Default choice: implicit Euler
if 'Q1' not in params:
params['Q1'] = 'IE'
if 'Q2' not in params:
params['Q2'] = 'IE'
# call parent's initialization routine
super(multi_implicit, self).__init__(params)
# Integration matrices
self.Q1 = self.get_Qdelta_implicit(coll=self.coll, qd_type=self.params.Q1)
self.Q2 = self.get_Qdelta_implicit(coll=self.coll, qd_type=self.params.Q2)
def integrate(self):
"""
Integrates the right-hand side (two components)
Returns:
list of dtype_u: containing the integral as values
"""
# get current level and problem description
L = self.level
P = L.prob
me = []
# integrate RHS over all collocation nodes
for m in range(1, self.coll.num_nodes + 1):
# new instance of dtype_u, initialize values with 0
me.append(P.dtype_u(P.init, val=0.0))
for j in range(1, self.coll.num_nodes + 1):
me[-1] += L.dt * self.coll.Qmat[m, j] * (L.f[j].comp1 + L.f[j].comp2)
return me
def update_nodes(self):
"""
Update the u- and f-values at the collocation nodes -> corresponds to a single sweep over all nodes
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# only if the level has been touched before
assert L.status.unlocked
# get number of collocation nodes for easier access
M = self.coll.num_nodes
# gather all terms which are known already (e.g. from the previous iteration)
# get QF(u^k)
integral = self.integrate()
for m in range(M):
# subtract Q1F1(u^k)_m
for j in range(1, M + 1):
integral[m] -= L.dt * self.Q1[m + 1, j] * L.f[j].comp1
# add initial value
integral[m] += L.u[0]
# add tau if associated
if L.tau[m] is not None:
integral[m] += L.tau[m]
# store Q2F2(u^k) for later usage
Q2int = []
for m in range(M):
Q2int.append(P.dtype_u(P.init, val=0.0))
for j in range(1, M + 1):
Q2int[-1] += L.dt * self.Q2[m + 1, j] * L.f[j].comp2
# do the sweep
for m in range(0, M):
# build rhs, consisting of the known values from above and new values from previous nodes (at k+1)
rhs = P.dtype_u(integral[m])
for j in range(1, m + 1):
rhs += L.dt * self.Q1[m + 1, j] * L.f[j].comp1
# implicit solve with prefactor stemming from Q1
L.u[m + 1] = P.solve_system_1(
rhs, L.dt * self.Q1[m + 1, m + 1], L.u[m + 1], L.time + L.dt * self.coll.nodes[m]
)
# substract Q2F2(u^k) and add Q2F(u^k+1)
rhs = L.u[m + 1] - Q2int[m]
for j in range(1, m + 1):
rhs += L.dt * self.Q2[m + 1, j] * L.f[j].comp2
L.u[m + 1] = P.solve_system_2(
rhs,
L.dt * self.Q2[m + 1, m + 1],
L.u[m + 1], # TODO: is this a good guess?
L.time + L.dt * self.coll.nodes[m],
)
# update function values
L.f[m + 1] = P.eval_f(L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
# indicate presence of new values at this level
L.status.updated = True
return None
def compute_end_point(self):
"""
Compute u at the right point of the interval
The value uend computed here is a full evaluation of the Picard formulation unless do_full_update==False
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# check if Mth node is equal to right point and do_coll_update is false, perform a simple copy
if self.coll.right_is_node and not self.params.do_coll_update:
# a copy is sufficient
L.uend = P.dtype_u(L.u[-1])
else:
# start with u0 and add integral over the full interval (using coll.weights)
L.uend = P.dtype_u(L.u[0])
for m in range(self.coll.num_nodes):
L.uend += L.dt * self.coll.weights[m] * (L.f[m + 1].comp1 + L.f[m + 1].comp2)
# add up tau correction of the full interval (last entry)
if L.tau[-1] is not None:
L.uend += L.tau[-1]
return None
| 5,114 | 31.373418 | 112 | py |
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/generic_LU.py | from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
class generic_LU(generic_implicit):
"""
LU sweeper using LU decomposition of the Q matrix for the base integrator, special type of generic implicit sweeper
"""
def __init__(self, params):
"""
Initialization routine for the custom sweeper
Args:
params: parameters for the sweeper
"""
params['QI'] = 'LU'
# call parent's initialization routine
super(generic_LU, self).__init__(params)
| 558 | 24.409091 | 119 | py |
pySDC | pySDC-master/pySDC/implementations/sweeper_classes/imex_1st_order.py | import numpy as np
from pySDC.core.Sweeper import sweeper
class imex_1st_order(sweeper):
"""
Custom sweeper class, implements Sweeper.py
First-order IMEX sweeper using implicit/explicit Euler as base integrator
Attributes:
QI: implicit Euler integration matrix
QE: explicit Euler integration matrix
"""
def __init__(self, params):
"""
Initialization routine for the custom sweeper
Args:
params: parameters for the sweeper
"""
if 'QI' not in params:
params['QI'] = 'IE'
if 'QE' not in params:
params['QE'] = 'EE'
# call parent's initialization routine
super(imex_1st_order, self).__init__(params)
# IMEX integration matrices
self.QI = self.get_Qdelta_implicit(coll=self.coll, qd_type=self.params.QI)
self.QE = self.get_Qdelta_explicit(coll=self.coll, qd_type=self.params.QE)
def integrate(self):
"""
Integrates the right-hand side (here impl + expl)
Returns:
list of dtype_u: containing the integral as values
"""
# get current level and problem description
L = self.level
me = []
# integrate RHS over all collocation nodes
for m in range(1, self.coll.num_nodes + 1):
me.append(L.dt * self.coll.Qmat[m, 1] * (L.f[1].impl + L.f[1].expl))
# new instance of dtype_u, initialize values with 0
for j in range(2, self.coll.num_nodes + 1):
me[m - 1] += L.dt * self.coll.Qmat[m, j] * (L.f[j].impl + L.f[j].expl)
return me
def update_nodes(self):
"""
Update the u- and f-values at the collocation nodes -> corresponds to a single sweep over all nodes
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# only if the level has been touched before
assert L.status.unlocked
# get number of collocation nodes for easier access
M = self.coll.num_nodes
# gather all terms which are known already (e.g. from the previous iteration)
# this corresponds to u0 + QF(u^k) - QIFI(u^k) - QEFE(u^k) + tau
# get QF(u^k)
integral = self.integrate()
for m in range(M):
# subtract QIFI(u^k)_m + QEFE(u^k)_m
for j in range(1, M + 1):
integral[m] -= L.dt * (self.QI[m + 1, j] * L.f[j].impl + self.QE[m + 1, j] * L.f[j].expl)
# add initial value
integral[m] += L.u[0]
# add tau if associated
if L.tau[m] is not None:
integral[m] += L.tau[m]
# do the sweep
for m in range(0, M):
# build rhs, consisting of the known values from above and new values from previous nodes (at k+1)
rhs = P.dtype_u(integral[m])
for j in range(1, m + 1):
rhs += L.dt * (self.QI[m + 1, j] * L.f[j].impl + self.QE[m + 1, j] * L.f[j].expl)
# implicit solve with prefactor stemming from QI
L.u[m + 1] = P.solve_system(
rhs, L.dt * self.QI[m + 1, m + 1], L.u[m + 1], L.time + L.dt * self.coll.nodes[m]
)
# update function values
L.f[m + 1] = P.eval_f(L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
# indicate presence of new values at this level
L.status.updated = True
return None
def compute_end_point(self):
"""
Compute u at the right point of the interval
The value uend computed here is a full evaluation of the Picard formulation unless do_full_update==False
Returns:
None
"""
# get current level and problem description
L = self.level
P = L.prob
# check if Mth node is equal to right point and do_coll_update is false, perform a simple copy
if self.coll.right_is_node and not self.params.do_coll_update:
# a copy is sufficient
L.uend = P.dtype_u(L.u[-1])
else:
# start with u0 and add integral over the full interval (using coll.weights)
L.uend = P.dtype_u(L.u[0])
for m in range(self.coll.num_nodes):
L.uend += L.dt * self.coll.weights[m] * (L.f[m + 1].impl + L.f[m + 1].expl)
# add up tau correction of the full interval (last entry)
if L.tau[-1] is not None:
L.uend += L.tau[-1]
return None
def get_sweeper_mats(self):
"""
Returns the three matrices Q, QI, QE which define the sweeper.
The first row and column, corresponding to the left starting value, are removed to correspond to the notation
introduced in Ruprecht & Speck, Spectral deferred corrections with fast-wave slow-wave splitting, 2016
"""
QE = self.QE[1:, 1:]
QI = self.QI[1:, 1:]
Q = self.coll.Qmat[1:, 1:]
return QE, QI, Q
def get_scalar_problems_sweeper_mats(self, lambdas=None):
"""
This function returns the corresponding matrices of an IMEX-SDC sweep in matrix formulation.
See Ruprecht & Speck, Spectral deferred corrections with fast-wave slow-wave splitting, 2016 for the derivation.
Args:
lambdas (numpy.ndarray): the first entry in lambdas is lambda_fast, the second is lambda_slow.
"""
QE, QI, Q = self.get_sweeper_mats()
if lambdas is None:
pass
# should use lambdas from attached problem and make sure it is a scalar IMEX
raise NotImplementedError("At the moment, the values for lambda have to be provided")
else:
lambda_fast = lambdas[0]
lambda_slow = lambdas[1]
nnodes = self.coll.num_nodes
dt = self.level.dt
LHS = np.eye(nnodes) - dt * (lambda_fast * QI + lambda_slow * QE)
RHS = dt * ((lambda_fast + lambda_slow) * Q - (lambda_fast * QI + lambda_slow * QE))
return LHS, RHS
def get_scalar_problems_manysweep_mat(self, nsweeps, lambdas=None):
"""
For a scalar problem, K sweeps of IMEX-SDC can be written in matrix form.
Args:
nsweeps (int): number of sweeps
lambdas (numpy.ndarray): the first entry in lambdas is lambda_fast, the second is lambda_slow.
"""
LHS, RHS = self.get_scalar_problems_sweeper_mats(lambdas=lambdas)
Pinv = np.linalg.inv(LHS)
Mat_sweep = np.linalg.matrix_power(Pinv.dot(RHS), nsweeps)
for k in range(0, nsweeps):
Mat_sweep += np.linalg.matrix_power(Pinv.dot(RHS), k).dot(Pinv)
return Mat_sweep
| 6,753 | 34.547368 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/hooks/log_step_size.py | from pySDC.core.Hooks import hooks
class LogStepSize(hooks):
"""
Store the step size at the end of each step as "dt".
"""
def post_step(self, step, level_number):
"""
Record step size
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
Returns:
None
"""
super().post_step(step, level_number)
L = step.levels[level_number]
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='dt',
value=L.dt,
)
| 726 | 21.030303 | 56 | py |
pySDC | pySDC-master/pySDC/implementations/hooks/log_embedded_error_estimate.py | from pySDC.core.Hooks import hooks
class LogEmbeddedErrorEstimate(hooks):
"""
Store the embedded error estimate at the end of each step as "error_embedded_estimate".
"""
def log_error(self, step, level_number, appendix=''):
L = step.levels[level_number]
for flavour in ['', '_collocation']:
if L.status.get(f'error_embedded_estimate{flavour}'):
if flavour == '_collocation':
iter, value = L.status.error_embedded_estimate_collocation
else:
iter = step.status.iter
value = L.status.error_embedded_estimate
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=L.level_index,
iter=iter,
sweep=L.status.sweep,
type=f'error_embedded_estimate{flavour}{appendix}',
value=value,
)
def post_step(self, step, level_number, appendix=''):
"""
Record embedded error estimate
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
Returns:
None
"""
super().post_step(step, level_number)
self.log_error(step, level_number, appendix)
class LogEmbeddedErrorEstimatePostIter(LogEmbeddedErrorEstimate):
"""
Store the embedded error estimate after each iteration as "error_embedded_estimate_post_iteration".
Because the error estimate is computed after the hook is called, we record the value belonging to the last
iteration, which is also why we need to record something after the step, which belongs to the final iteration.
"""
def post_iteration(self, step, level_number):
"""
Record embedded error estimate
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
Returns:
None
"""
super().post_iteration(step, level_number)
self.log_error(step, level_number, '_post_iteration')
def post_step(self, step, level_number):
super().post_step(step, level_number, appendix='_post_iteration')
| 2,306 | 32.926471 | 114 | py |
pySDC | pySDC-master/pySDC/implementations/hooks/default_hook.py | import time
from pySDC.core.Hooks import hooks
class DefaultHooks(hooks):
"""
Hook class to contain the functions called during the controller runs (e.g. for calling user-routines)
Attributes:
__t0_setup (float): private variable to get starting time of setup
__t0_run (float): private variable to get starting time of the run
__t0_predict (float): private variable to get starting time of the predictor
__t0_step (float): private variable to get starting time of the step
__t0_iteration (float): private variable to get starting time of the iteration
__t0_sweep (float): private variable to get starting time of the sweep
__t0_comm (list): private variable to get starting time of the communication
__t1_run (float): private variable to get end time of the run
__t1_predict (float): private variable to get end time of the predictor
__t1_step (float): private variable to get end time of the step
__t1_iteration (float): private variable to get end time of the iteration
__t1_sweep (float): private variable to get end time of the sweep
__t1_setup (float): private variable to get end time of setup
__t1_comm (list): private variable to hold timing of the communication (!)
"""
def __init__(self):
super().__init__()
self.__t0_setup = None
self.__t0_run = None
self.__t0_predict = None
self.__t0_step = None
self.__t0_iteration = None
self.__t0_sweep = None
self.__t0_comm = []
self.__t1_run = None
self.__t1_predict = None
self.__t1_step = None
self.__t1_iteration = None
self.__t1_sweep = None
self.__t1_setup = None
self.__t1_comm = []
def pre_setup(self, step, level_number):
"""
Default routine called before setup starts
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().pre_setup(step, level_number)
self.__t0_setup = time.perf_counter()
def pre_run(self, step, level_number):
"""
Default routine called before time-loop starts
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().pre_run(step, level_number)
self.__t0_run = time.perf_counter()
def pre_predict(self, step, level_number):
"""
Default routine called before predictor starts
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().pre_predict(step, level_number)
self.__t0_predict = time.perf_counter()
def pre_step(self, step, level_number):
"""
Hook called before each step
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().pre_step(step, level_number)
self.__t0_step = time.perf_counter()
def pre_iteration(self, step, level_number):
"""
Default routine called before iteration starts
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().pre_iteration(step, level_number)
self.__t0_iteration = time.perf_counter()
def pre_sweep(self, step, level_number):
"""
Default routine called before sweep starts
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().pre_sweep(step, level_number)
self.__t0_sweep = time.perf_counter()
def pre_comm(self, step, level_number):
"""
Default routine called before communication starts
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().pre_comm(step, level_number)
if len(self.__t0_comm) >= level_number + 1:
self.__t0_comm[level_number] = time.perf_counter()
else:
while len(self.__t0_comm) < level_number:
self.__t0_comm.append(None)
self.__t0_comm.append(time.perf_counter())
while len(self.__t1_comm) <= level_number:
self.__t1_comm.append(0.0)
assert len(self.__t0_comm) == level_number + 1
assert len(self.__t1_comm) == level_number + 1
def post_comm(self, step, level_number, add_to_stats=False):
"""
Default routine called after each communication
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
add_to_stats (bool): set if result should go to stats object
"""
super().post_comm(step, level_number)
assert len(self.__t1_comm) >= level_number + 1
self.__t1_comm[level_number] += time.perf_counter() - self.__t0_comm[level_number]
if add_to_stats:
L = step.levels[level_number]
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='timing_comm',
value=self.__t1_comm[level_number],
)
self.__t1_comm[level_number] = 0.0
def post_sweep(self, step, level_number):
"""
Default routine called after each sweep
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().post_sweep(step, level_number)
self.__t1_sweep = time.perf_counter()
L = step.levels[level_number]
self.logger.info(
'Process %2i on time %8.6f at stage %15s: Level: %s -- Iteration: %2i -- Sweep: %2i -- ' 'residual: %12.8e',
step.status.slot,
L.time,
step.status.stage,
L.level_index,
step.status.iter,
L.status.sweep,
L.status.residual,
)
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_post_sweep',
value=L.status.residual,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='timing_sweep',
value=self.__t1_sweep - self.__t0_sweep,
)
def post_iteration(self, step, level_number):
"""
Default routine called after each iteration
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().post_iteration(step, level_number)
self.__t1_iteration = time.perf_counter()
L = step.levels[level_number]
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='residual_post_iteration',
value=L.status.residual,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='timing_iteration',
value=self.__t1_iteration - self.__t0_iteration,
)
def post_step(self, step, level_number):
"""
Default routine called after each step or block
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().post_step(step, level_number)
self.__t1_step = time.perf_counter()
L = step.levels[level_number]
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='timing_step',
value=self.__t1_step - self.__t0_step,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='niter',
value=step.status.iter,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=-1,
sweep=L.status.sweep,
type='residual_post_step',
value=L.status.residual,
)
# record the recomputed quantities at weird positions to make sure there is only one value for each step
for t in [L.time, L.time + L.dt]:
self.add_to_stats(
process=-1, time=t, level=-1, iter=-1, sweep=-1, type='_recomputed', value=step.status.get('restart')
)
def post_predict(self, step, level_number):
"""
Default routine called after each predictor
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().post_predict(step, level_number)
self.__t1_predict = time.perf_counter()
L = step.levels[level_number]
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='timing_predictor',
value=self.__t1_predict - self.__t0_predict,
)
def post_run(self, step, level_number):
"""
Default routine called after each run
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().post_run(step, level_number)
self.__t1_run = time.perf_counter()
L = step.levels[level_number]
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='timing_run',
value=self.__t1_run - self.__t0_run,
)
def post_setup(self, step, level_number):
"""
Default routine called after setup
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super().post_setup(step, level_number)
self.__t1_setup = time.perf_counter()
self.add_to_stats(
process=-1,
time=-1,
level=-1,
iter=-1,
sweep=-1,
type='timing_setup',
value=self.__t1_setup - self.__t0_setup,
)
| 11,264 | 31.747093 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/hooks/log_restarts.py | from pySDC.core.Hooks import hooks
class LogRestarts(hooks):
"""
Record restarts as `restart` at the beginning of the step.
"""
def post_step(self, step, level_number):
"""
Record here if the step was restarted.
Args:
step (pySDC.Step.step): Current step
level_number (int): Current level
"""
super().post_step(step, level_number)
L = step.levels[level_number]
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='restart',
value=int(step.status.get('restart')),
)
| 736 | 23.566667 | 62 | py |
pySDC | pySDC-master/pySDC/implementations/hooks/log_work.py | from pySDC.core.Hooks import hooks
class LogWork(hooks):
"""
Log the increment of all work counters in the problem between steps
"""
def __init__(self):
"""
Initialize the variables for the work recorded in the last step
"""
super().__init__()
self.__work_last_step = {}
def pre_step(self, step, level_number):
"""
Store the current values of the work counters
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
Returns:
None
"""
if level_number == 0:
self.__work_last_step[step.status.slot] = [
{key: step.levels[i].prob.work_counters[key].niter for key in step.levels[i].prob.work_counters.keys()}
for i in range(len(step.levels))
]
def post_step(self, step, level_number):
"""
Add the difference between current values of counters and their values before the iteration to the stats.
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
Returns:
None
"""
L = step.levels[level_number]
for key in self.__work_last_step[step.status.slot][level_number].keys():
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=f'work_{key}',
value=L.prob.work_counters[key].niter - self.__work_last_step[step.status.slot][level_number][key],
)
| 1,734 | 30.545455 | 119 | py |
pySDC | pySDC-master/pySDC/implementations/hooks/log_errors.py | import numpy as np
from pySDC.core.Hooks import hooks
class LogError(hooks):
"""
Base class with functions to add the local and global error to the stats, which can be inherited by hooks logging
these at specific places.
Errors are computed with respect to `u_exact` defined in the problem class.
Be aware that this requires the problems to be compatible with this. We need some kind of "exact" solution for this
to work, be it a reference solution or something analytical.
"""
def log_global_error(self, step, level_number, suffix=''):
"""
Function to add the global error to the stats
Args:
step (pySDC.Step.step): The current step
level_number (int): The index of the level
suffix (str): Suffix for naming the variable in stats
Returns:
None
"""
L = step.levels[level_number]
L.sweep.compute_end_point()
u_ref = L.prob.u_exact(t=L.time + L.dt)
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=f'e_global{suffix}',
value=abs(u_ref - 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=f'e_global_rel{suffix}',
value=abs((u_ref - L.uend / u_ref)),
)
def log_local_error(self, step, level_number, suffix=''):
"""
Function to add the local error to the stats
Args:
step (pySDC.Step.step): The current step
level_number (int): The index of the level
suffix (str): Suffix for naming the variable in stats
Returns:
None
"""
L = step.levels[level_number]
L.sweep.compute_end_point()
value = abs(L.prob.u_exact(t=L.time + L.dt, u_init=L.u[0] * 1.0, t_init=L.time) - 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=f'e_local{suffix}',
value=value,
)
self.logger.debug(
'Process %2i on time %8.6f at stage %15s: Level: %s -- Iteration: %2i -- Sweep: %2i -- '
'local_error: %12.8e',
step.status.slot,
L.time,
step.status.stage,
L.level_index,
step.status.iter,
L.status.sweep,
value,
)
class LogGlobalErrorPostStep(LogError):
def post_step(self, step, level_number):
super().post_step(step, level_number)
self.log_global_error(step, level_number, '_post_step')
class LogGlobalErrorPostIter(LogError):
"""
Log the global error after each iteration
"""
def post_iteration(self, step, level_number):
"""
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
Returns:
None
"""
super().post_iteration(step, level_number)
self.log_global_error(step, level_number, suffix='_post_iteration')
class LogGlobalErrorPostRun(hooks):
"""
Compute the global error once after the run is finished.
Because of some timing issues, we cannot inherit from the `LogError` class here.
The issue is that the convergence controllers can change the step size after the final iteration but before the
`post_run` functions of the hooks are called, which results in a mismatch of `L.time + L.dt` as corresponding to
when the solution is computed and when the error is computed. The issue is resolved by recording the time at which
the solution is computed in a private attribute of this class.
There is another issue: The MPI controller instantiates a step after the run is completed, meaning the final
solution is not accessed by computing the end point, but by using the initial value on the finest level.
Additionally, the number of restarts is reset, which we need to filter recomputed values in post processing.
For this reason, we need to mess with the private `__num_restarts` of the core Hooks class.
"""
def __init__(self):
"""
Add an attribute for when the last solution was added.
"""
super().__init__()
self.t_last_solution = 0
self.num_restarts = 0
def post_step(self, step, level_number):
"""
Store the time at which the solution is stored.
This is required because between the `post_step` hook where the solution is stored and the `post_run` hook
where the error is stored, the step size can change.
Args:
step (pySDC.Step.step): The current step
level_number (int): The index of the level
Returns:
None
"""
super().post_step(step, level_number)
self.t_last_solution = step.levels[0].time + step.levels[0].dt
self.num_restarts = step.status.get('restarts_in_a_row', 0)
def post_run(self, step, level_number):
"""
Log the global error.
Args:
step (pySDC.Step.step): The current step
level_number (int): The index of the level
Returns:
None
"""
super().post_run(step, level_number)
self._hooks__num_restarts = self.num_restarts
if level_number == 0 and step.status.last:
L = step.levels[level_number]
u_num = self.get_final_solution(L)
u_ref = L.prob.u_exact(t=self.t_last_solution)
self.logger.info(f'Finished with a global error of e={abs(u_num-u_ref):.2e}')
self.add_to_stats(
process=step.status.slot,
time=self.t_last_solution,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='e_global_post_run',
value=abs(u_num - u_ref),
)
self.add_to_stats(
process=step.status.slot,
time=self.t_last_solution,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='e_global_rel_post_run',
value=abs((u_num - u_ref) / u_ref),
)
def get_final_solution(self, lvl):
"""
Get the final solution from the level
Args:
lvl (pySDC.Level.level): The level
"""
return lvl.uend
class LogGlobalErrorPostRunMPI(LogGlobalErrorPostRun):
"""
The MPI controller shows slightly different behaviour which is why the final solution is stored in a different place
than in the nonMPI controller.
"""
def post_step(self, step, level_number):
super().post_step(step, level_number)
self.num_restarts = self._hooks__num_restarts
def get_final_solution(self, lvl):
"""
Get the final solution from the level
Args:
lvl (pySDC.Level.level): The level
"""
return lvl.u[0]
class LogLocalErrorPostStep(LogError):
"""
Log the local error with respect to `u_exact` defined in the problem class as "e_local_post_step".
Be aware that this requires the problems to be compatible with this. In particular, a reference solution needs to
be made available from the initial conditions of the step, not of the run. Otherwise you compute the global error.
"""
def post_step(self, step, level_number):
super().post_step(step, level_number)
self.log_local_error(step, level_number, suffix='_post_step')
class LogLocalErrorPostIter(LogError):
"""
Log the local error after each iteration
"""
def post_iteration(self, step, level_number):
"""
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
Returns:
None
"""
super().post_iteration(step, level_number)
self.log_local_error(step, level_number, suffix='_post_iteration')
| 8,424 | 31.655039 | 120 | py |
pySDC | pySDC-master/pySDC/implementations/hooks/log_solution.py | from pySDC.core.Hooks import hooks
class LogSolution(hooks):
"""
Store the solution at the end of each step as "u".
"""
def post_step(self, step, level_number):
"""
Record solution at the end of the step
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
Returns:
None
"""
super().post_step(step, level_number)
L = step.levels[level_number]
L.sweep.compute_end_point()
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='u',
value=L.uend,
)
class LogSolutionAfterIteration(hooks):
"""
Store the solution at the end of each iteration as "u".
"""
def post_iteration(self, step, level_number):
"""
Record solution at the end of the iteration
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
Returns:
None
"""
super().post_iteration(step, level_number)
L = step.levels[level_number]
L.sweep.compute_end_point()
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='u',
value=L.uend,
)
| 1,579 | 22.939394 | 59 | py |
Subsets and Splits