repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
pySDC | pySDC-master/pySDC/playgrounds/deprecated/pmesh/visualize.py | import json
import glob
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
def plot_data(name=''):
"""
Visualization using numpy arrays (written via MPI I/O) and json description
Produces one png file per time-step, combine as movie via e.g.
> ffmpeg -i data/name_%08d.png name.mp4
Args:
name (str): name of the simulation (expects data to be in data path)
"""
json_files = sorted(glob.glob(f'./data/{name}_*.json'))
data_files = sorted(glob.glob(f'./data/{name}_*.dat'))
for json_file, data_file in zip(json_files, data_files):
with open(json_file, 'r') as fp:
obj = json.load(fp)
index = json_file.split('_')[1].split('.')[0]
print(f'Working on step {index}...')
array = np.fromfile(data_file, dtype=obj['datatype'])
array = array.reshape(obj['shape'], order='C')
plt.figure()
plt.imshow(array, vmin=0, vmax=1)
plt.colorbar()
plt.title(f"Time: {obj['time']:6.4f}")
plt.savefig(f'data/{name}_{index}.png', bbox_inches='tight')
plt.close()
if __name__ == "__main__":
# name = 'AC-test'
name = 'AC-test-constforce'
# name = 'AC-2D-application'
# name = 'AC-2D-application-forced'
plot_data(name=name)
| 1,325 | 24.018868 | 79 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/pmesh/playground_pmesh.py | from mpi4py import MPI
import matplotlib
matplotlib.use("TkAgg")
import numpy as np
import time
from pmesh.pm import ParticleMesh
from pySDC.playgrounds.pmesh.PMESH_datatype import pmesh_datatype, rhs_imex_pmesh
from pySDC.playgrounds.pmesh.PMESH_datatype import pmesh_datatype, rhs_imex_pmesh
def doublesine(i, v):
r = [ii * (Li / ni) for ii, ni, Li in zip(i, v.Nmesh, v.BoxSize)]
# xx, yy = np.meshgrid(r[0], r[1])
return np.sin(2 * np.pi * r[0]) * np.sin(2 * np.pi * r[1])
def Lap_doublesine(i, v):
r = [ii * (Li / ni) for ii, ni, Li in zip(i, v.Nmesh, v.BoxSize)]
# xx, yy = np.meshgrid(r[0], r[1])
return -2.0 * (2.0 * np.pi) ** 2 * np.sin(2 * np.pi * r[0]) * np.sin(2 * np.pi * r[1])
def Laplacian(k, v):
k2 = sum(ki**2 for ki in k)
# print([type(ki[0][0]) for ki in k])
# k2[k2 == 0] = 1.0
return -k2 * v
def circle(i, v):
r = [ii * (Li / ni) - 0.5 * Li for ii, ni, Li in zip(i, v.Nmesh, v.BoxSize)]
r2 = sum(ri**2 for ri in r)
return np.tanh((0.25 - np.sqrt(r2)) / (np.sqrt(2) * 0.04))
nvars = 128
nruns = 1000
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
t0 = time.perf_counter()
pm = ParticleMesh(BoxSize=1.0, Nmesh=[nvars] * 2, dtype='f8', plan_method='measure', comm=comm)
tmp = pm.create(type='real')
t1 = time.perf_counter()
# a = pmesh_datatype((pm, (2, (4, 4))))
print(f'PMESH setup time: {t1 - t0:6.4f} sec.')
dt = 0.121233
res = 0.0
t0 = time.perf_counter()
# for n in range(nruns):
#
# # set initial condition
# # u = pmesh_datatype(init=pm)
# # u.values.apply(circle, kind='index', out=Ellipsis)
# u = rhs_imex_pmesh(init=(pm.comm, tmp.value.shape))
# tmp = pm.create(type='real', value=0.0)
# u.impl.value = tmp.apply(circle, kind='index', out=Ellipsis).value
#
# # save initial condition
# u_old = pmesh_datatype(init=u.impl)
#
# dt = 0.121233 / (n + 1)
#
# def linear_solve(k, v):
# global dt
# k2 = sum(ki ** 2 for ki in k)
# factor = 1 + dt * k2
# return 1.0 / factor * v
#
# # solve (I-dt*A)u = u_old
# sol = pmesh_datatype(init=(pm.comm, tmp.value.shape))
# tmp = pm.create(type='real', value=u.impl.values)
# sol.values = tmp.r2c().apply(linear_solve, out=Ellipsis).c2r(out=Ellipsis).value
#
# # compute Laplacian
# # lap = sol.values.r2c().apply(Laplacian, out=Ellipsis).c2r(out=Ellipsis)
# lap = pmesh_datatype(init=(pm.comm, tmp.value.shape))
# tmp = pm.create(type='real', value=sol.values)
# lap.values = tmp.r2c().apply(Laplacian, out=Ellipsis).c2r(out=Ellipsis).value
#
# # compute residual of (I-dt*A)u = u_old
# res = max(abs(sol - dt*lap - u_old), res)
# t1 = time.perf_counter()
#
# print(f'PMESH residual: {res:6.4e}') # Should be approx. 5.9E-11
# print(f'PMESH runtime: {t1 - t0:6.4f} sec.') # Approx. 0.9 seconds on my machine
#
# exit()
pmf = ParticleMesh(BoxSize=1.0, Nmesh=[nvars] * 2, comm=comm)
pmc = ParticleMesh(BoxSize=1.0, Nmesh=[nvars // 2] * 2, comm=comm)
uexf = pmf.create(type='real')
uexf = uexf.apply(doublesine, kind='index')
uexc = pmc.create(type='real')
uexc = uexc.apply(doublesine, kind='index')
# uc = pmc.upsample(uexf, keep_mean=True)
uc = pmc.create(type='real')
uexf.resample(uc)
print(uc.preview().shape, np.amax(abs(uc - uexc)))
uf = pmf.create(type='real')
# uf = pmf.upsample(uexc, keep_mean=True)
uexc.resample(uf)
print(uf.preview().shape, np.amax(abs(uf - uexf)))
print()
pmf = ParticleMesh(BoxSize=1.0, Nmesh=[nvars] * 2, comm=comm)
pmc = ParticleMesh(BoxSize=1.0, Nmesh=[nvars // 2] * 2, comm=comm)
uexf = pmf.create(type='real')
uexf = uexf.apply(doublesine, kind='index')
uexf = uexf.r2c()
uexc = pmc.create(type='real')
uexc = uexc.apply(doublesine, kind='index')
uexc = uexc.r2c()
# uc = pmc.upsample(uexf, keep_mean=True)
uc = pmc.create(type='complex')
uexf.resample(uc)
print(uc.value.shape, np.amax(abs(uc - uexc)))
uf = pmf.create(type='complex')
# uf = pmf.upsample(uexc, keep_mean=True)
uexc.resample(uf)
print(uf.preview().shape, np.amax(abs(uf - uexf)))
print()
t1 = time.perf_counter()
print(f'Time: {t1-t0}')
| 4,127 | 27.468966 | 95 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/pmesh/AC_benchmark_NEW.py | import sys
import numpy as np
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.playgrounds.pmesh.AllenCahn_PMESH_NEW import allencahn_imex, allencahn_imex_stab
from pySDC.playgrounds.pmesh.TransferMesh_PMESH import pmesh_to_pmesh
from pySDC.playgrounds.pmesh.AllenCahn_monitor_and_dump_NEW import monitor_and_dump
from pySDC.playgrounds.pmesh.AllenCahn_dump import dump
def run_simulation(name=''):
"""
A simple test program to do PFASST runs for the AC equation
"""
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
# split world communicator to create space-communicators
if len(sys.argv) >= 2:
color = int(world_rank / int(sys.argv[1]))
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
# space_size = space_comm.Get_size()
space_rank = space_comm.Get_rank()
# split world communicator to create time-communicators
if len(sys.argv) >= 2:
color = int(world_rank % int(sys.argv[1]))
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
# time_size = time_comm.Get_size()
time_rank = time_comm.Get_rank()
# print("IDs (world, space, time): %i / %i -- %i / %i -- %i / %i" % (world_rank, world_size, space_rank,
# space_size, time_rank, time_size))
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 1e-03
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['L'] = 1.0
problem_params['nvars'] = [(128, 128)] # , 128)]
problem_params['eps'] = [0.04]
problem_params['dw'] = [-23.6]
problem_params['radius'] = 0.25
problem_params['comm'] = space_comm
problem_params['name'] = name
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20 if space_rank == 0 else 99 # set level depending on rank
controller_params['hook_class'] = monitor_and_dump
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = allencahn_imex
# description['problem_class'] = allencahn_imex_stab
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = pmesh_to_pmesh
# set time parameters
t0 = 0.0
Tend = 10 * 0.001
# instantiate controller
controller = controller_MPI(controller_params=controller_params, description=description, comm=time_comm)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
if space_rank == 0:
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
print()
niters = np.array([item[1] for item in iter_counts])
out = f'Mean number of iterations on rank {time_rank}: {np.mean(niters):.4f}'
print(out)
timing = get_sorted(stats, type='timing_setup', sortby='time')
out = f'Setup time on rank {time_rank}: {timing[0][1]:.4f} sec.'
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
out = f'Time to solution on rank {time_rank}: {timing[0][1]:.4f} sec.'
print(out)
print()
# convert filtered statistics to list of computed radii, sorted by time
computed_radii = get_sorted(stats, type='computed_radius', sortby='time')
exact_radii = get_sorted(stats, type='exact_radius', sortby='time')
# print radii and error over time
for cr, er in zip(computed_radii, exact_radii):
if er[1] > 0:
err = abs(cr[1] - er[1]) / er[1]
else:
err = 1.0
out = f'Computed/exact/error radius for time {cr[0]:6.4f}: ' f'{cr[1]:6.4f} / {er[1]:6.4f} / {err:6.4e}'
print(out)
if __name__ == "__main__":
name = 'AC-test-constforce'
run_simulation(name=name)
| 5,144 | 34.979021 | 116 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/pmesh/AllenCahn_Temperature_PMESH.py | import numpy as np
from mpi4py import MPI
from pmesh.pm import ParticleMesh
from pySDC.core.Errors import ParameterError, ProblemError
from pySDC.core.Problem import ptype
from pySDC.playgrounds.pmesh.PMESH_datatype import pmesh_datatype, rhs_imex_pmesh
class allencahn_imex(ptype):
"""
Example implementing Allen-Cahn equation in 2-3D using PMESH for solving linear parts, IMEX time-stepping
PMESH: https://github.com/rainwoodman/pmesh
Attributes:
xvalues: grid points in space
dx: mesh width
"""
def __init__(self, problem_params, dtype_u=pmesh_datatype, dtype_f=rhs_imex_pmesh):
"""
Initialization routine
Args:
problem_params (dict): custom parameters for the example
dtype_u: pmesh data type (will be passed to parent class)
dtype_f: pmesh data type wuth implicit and explicit parts (will be passed to parent class)
"""
if 'L' not in problem_params:
problem_params['L'] = 1.0
if 'init_type' not in problem_params:
problem_params['init_type'] = 'circle'
if 'comm' not in problem_params:
problem_params['comm'] = None
# these parameters will be used later, so assert their existence
essential_keys = ['nvars', 'eps', 'L', 'radius', 'dw', 'D', 'TM']
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)
if not (isinstance(problem_params['nvars'], tuple) and len(problem_params['nvars']) > 1):
raise ProblemError('Need at least two dimensions')
# Creating ParticleMesh structure
self.pm = ParticleMesh(
BoxSize=problem_params['L'],
Nmesh=list(problem_params['nvars']),
dtype='f8',
plan_method='measure',
comm=problem_params['comm'],
)
# create test RealField to get the local dimensions (there's probably a better way to do that)
tmp = self.pm.create(type='real')
sizes = list(tmp.value.shape)
sizes.insert(len(tmp.value.shape), 2)
sizes = tuple(sizes)
# invoke super init, passing the communicator and the local dimensions as init
super(allencahn_imex, self).__init__(
init=(self.pm.comm, sizes), dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params
)
# Need this for diagnostics
self.dx = self.params.L / problem_params['nvars'][0]
self.dy = self.params.L / problem_params['nvars'][1]
self.xvalues = [i * self.dx - problem_params['L'] / 2 for i in range(problem_params['nvars'][0])]
self.yvalues = [i * self.dy - problem_params['L'] / 2 for i in range(problem_params['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
"""
def Laplacian(k, v):
k2 = sum(ki**2 for ki in k)
return -k2 * v
f = self.dtype_f(self.init, val=0.0)
tmp_u = self.pm.create(type='real', value=u.values[..., 0])
f.impl.values[..., 0] = tmp_u.r2c().apply(Laplacian, out=Ellipsis).c2r(out=Ellipsis).value
if self.params.eps > 0:
f.expl.values[..., 0] = -2.0 / self.params.eps**2 * u.values[..., 0] * (1.0 - u.values[..., 0]) * (
1.0 - 2.0 * u.values[..., 0]
) - 6.0 * self.params.dw * (u.values[..., 1] - self.params.TM) / self.params.TM * u.values[..., 0] * (
1.0 - u.values[..., 0]
)
# # build sum over RHS without driving force
# Rt_local = f.impl.values[..., 0].sum() + f.expl.values[..., 0].sum()
# if self.pm.comm is not None:
# Rt_global = self.pm.comm.allreduce(sendobj=Rt_local, op=MPI.SUM)
# else:
# Rt_global = Rt_local
#
# # build sum over driving force term
# Ht_local = np.sum(6.0 * (u.values[..., 1] - self.params.TM) / self.params.TM * u.values[..., 0] * (1.0 - u.values[..., 0]))
# if self.pm.comm is not None:
# Ht_global = self.pm.comm.allreduce(sendobj=Ht_local, op=MPI.SUM)
# else:
# Ht_global = Rt_local
#
# # add/substract time-dependent driving force
# dw = Rt_global / Ht_global
# f.expl.values[..., 0] -= 6.0 * dw * (u.values[..., 1] - self.params.TM) / self.params.TM * u.values[..., 0] * (1.0 - u.values[..., 0])
tmp_u = self.pm.create(type='real', value=u.values[..., 1])
f.impl.values[..., 1] = self.params.D * tmp_u.r2c().apply(Laplacian, out=Ellipsis).c2r(out=Ellipsis).value
f.expl.values[..., 1] = -f.impl.values[..., 0] - f.expl.values[..., 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
"""
def linear_solve(k, v):
k2 = sum(ki**2 for ki in k)
return 1.0 / (1.0 + factor * k2) * v
def linear_solve_param(k, v):
k2 = sum(ki**2 for ki in k)
return 1.0 / (1.0 + self.params.D * factor * k2) * v
me = self.dtype_u(self.init, val=0.0)
tmp_rhs = self.pm.create(type='real', value=rhs.values[..., 0])
me.values[..., 0] = tmp_rhs.r2c().apply(linear_solve, out=Ellipsis).c2r(out=Ellipsis).value
tmp_rhs = self.pm.create(type='real', value=rhs.values[..., 1])
me.values[..., 1] = tmp_rhs.r2c().apply(linear_solve_param, out=Ellipsis).c2r(out=Ellipsis).value
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(i, v):
r = [ii * (Li / ni) - 0.5 * Li for ii, ni, Li in zip(i, v.Nmesh, v.BoxSize)]
r2 = sum(ri**2 for ri in r)
return 0.5 * (1.0 + np.tanh((self.params.radius - np.sqrt(r2)) / (np.sqrt(2) * self.params.eps)))
def circle_rand(i, v):
L = [int(l) for l in v.BoxSize]
r = [ii * (Li / ni) - 0.5 * Li for ii, ni, Li in zip(i, v.Nmesh, L)]
rshift = r.copy()
ndim = len(r)
data = 0
# get random radii for circles/spheres
np.random.seed(1)
lbound = 3.0 * self.params.eps
ubound = 0.5 - self.params.eps
rand_radii = (ubound - lbound) * np.random.random_sample(size=tuple(L)) + lbound
# distribnute circles/spheres
if ndim == 2:
for indexi, i in enumerate(range(-L[0] + 1, L[0], 2)):
for indexj, j in enumerate(range(-L[1] + 1, L[1], 2)):
# shift x and y coordinate depending on which box we are in
rshift[0] = r[0] + i / 2
rshift[1] = r[1] + j / 2
# build radius
r2 = sum(ri**2 for ri in rshift)
# add this blob, shifted by 1 to avoid issues with adding up negative contributions
data += np.tanh((rand_radii[indexi, indexj] - np.sqrt(r2)) / (np.sqrt(2) * self.params.eps)) + 1
# get rid of the 1
data *= 0.5
assert np.all(data <= 1.0)
return data
def sines(i, v):
r = [ii * (Li / ni) for ii, ni, Li in zip(i, v.Nmesh, v.BoxSize)]
return np.sin(2 * np.pi * r[0]) * np.sin(2 * np.pi * r[1])
def scaled_circle(i, v):
r = [ii * (Li / ni) - 0.5 * Li for ii, ni, Li in zip(i, v.Nmesh, v.BoxSize)]
r2 = sum(ri**2 for ri in r)
return (
0.5 * 0.1 * (1.0 + np.tanh((self.params.radius - np.sqrt(r2)) / (np.sqrt(2) * self.params.eps))) + 0.9
)
assert t == 0, 'ERROR: u_exact only valid for t=0'
me = self.dtype_u(self.init, val=0.0)
if self.params.init_type == 'circle':
tmp_u = self.pm.create(type='real', value=0.0)
me.values[..., 0] = tmp_u.apply(circle, kind='index').value
tmp_u = self.pm.create(type='real', value=0.0)
me.values[..., 1] = tmp_u.apply(sines, kind='index').value
elif self.params.init_type == 'circle_rand':
tmp_u = self.pm.create(type='real', value=0.0)
me.values[..., 0] = tmp_u.apply(circle_rand, kind='index').value
else:
raise NotImplementedError('type of initial value not implemented, got %s' % self.params.init_type)
return me
| 9,200 | 40.26009 | 144 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/advection_1d_implicit/ProblemClass.py | import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as LA
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes import mesh
from pySDC.playgrounds.deprecated.advection_1d_implicit.getFDMatrix import getFDMatrix
class advection(ptype):
"""
Example implementing the forced 1D heat equation with Dirichlet-0 BC in [0,1]
Attributes:
A: second-order FD discretization of the 1D laplace operator
dx: distance between two spatial nodes
"""
def __init__(self, cparams, dtype_u, dtype_f):
"""
Initialization routine
Args:
cparams: 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)
"""
# these parameters will be used later, so assert their existence
assert 'nvars' in cparams
assert 'c' in cparams
assert 'order' in cparams
assert cparams['nvars'] % 2 == 0
# add parameters as attributes for further reference
for k, v in cparams.items():
setattr(self, k, v)
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(advection, self).__init__(self.nvars, dtype_u, dtype_f)
# compute dx and get discretization matrix A
self.mesh = np.linspace(0, 1, num=self.nvars, endpoint=False)
self.dx = self.mesh[1] - self.mesh[0]
self.A = -self.c * getFDMatrix(self.nvars, self.order, self.dx)
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-dtA)u = rhs
Args:
rhs: right-hand side for the nonlinear system
factor: abbrev. for the node-to-node stepsize (or any other factor required)
u0: initial guess for the iterative solver (not used here so far)
t: current time (e.g. for time-dependent BCs)
Returns:
solution as mesh
"""
me = mesh(self.nvars)
me.values = LA.spsolve(sp.eye(self.nvars) - factor * self.A, rhs.values)
return me
def __eval_fimpl(self, u, t):
"""
Helper routine to evaluate the implicit part of the RHS
Args:
u: current values
t: current time (not used here)
Returns:
implicit part of RHS
"""
fimpl = mesh(self.nvars)
fimpl.values = self.A.dot(u.values)
return fimpl
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u: current values
t: current time
Returns:
the RHS divided into two parts
"""
f = mesh(self.nvars)
f.values = self.A.dot(u.values)
return f
def u_exact(self, t):
"""
Routine to compute the exact solution at time t
Args:
t: current time
Returns:
exact solution
"""
me = mesh(self.nvars)
me.values = np.cos(2.0 * np.pi * (self.mesh - self.c * t))
return me
| 3,161 | 27.232143 | 88 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/advection_1d_implicit/TransferClass.py | import numpy as np
from pySDC.core.Transfer import transfer
import pySDC.helpers.transfer_helper as th
from pySDC.implementations.datatype_classes import mesh, rhs_imex_mesh
# FIXME: extend this to ndarrays
class mesh_to_mesh_1d_periodic(transfer):
"""
Custon transfer class, implements Transfer.py
This implementation can restrict and prolong between 1d meshes via matrix-vector products
Attributes:
fine: reference to the fine level
coarse: reference to the coarse level
init_f: number of variables on the fine level (whatever init represents there)
init_c: number of variables on the coarse level (whatever init represents there)
Rspace: spatial restriction matrix, dim. Nf x Nc
Pspace: spatial prolongation matrix, dim. Nc x Nf
"""
def __init__(self, fine_level, coarse_level, params):
"""
Initialization routine
Args:
fine_level: fine level connected with the transfer operations (passed to parent)
coarse_level: coarse level connected with the transfer operations (passed to parent)
params: parameters for the transfer operators
"""
# invoke super initialization
super(mesh_to_mesh_1d_periodic, self).__init__(fine_level, coarse_level, params)
fine_grid = np.array([i * fine_level.prob.dx for i in range(fine_level.prob.nvars)])
coarse_grid = np.array([i * coarse_level.prob.dx for i in range(coarse_level.prob.nvars)])
# if number of variables is the same on both levels, Rspace and Pspace are identity
if self.init_c == self.init_f:
self.Rspace = np.eye(self.init_c)
# assemble restriction as transpose of interpolation
else:
if params['rorder'] == 1:
self.Rspace = th.restriction_matrix_1d(fine_grid, coarse_grid, k=1, periodic=True)
else:
self.Rspace = (
0.5 * th.interpolation_matrix_1d(fine_grid, coarse_grid, k=params['rorder'], periodic=True).T
)
# if number of variables is the same on both levels, Rspace and Pspace are identity
if self.init_f == self.init_c:
self.Pspace = np.eye(self.init_f)
else:
self.Pspace = th.interpolation_matrix_1d(fine_grid, coarse_grid, k=params['iorder'], periodic=True)
# print(self.Rspace.todense())
# print(self.Pspace.todense())
# exit()
pass
def restrict_space(self, F):
"""
Restriction implementation
Args:
F: the fine level data (easier to access than via the fine attribute)
"""
if isinstance(F, mesh):
u_coarse = mesh(self.init_c, val=0.0)
u_coarse.values = self.Rspace.dot(F.values)
elif isinstance(F, rhs_imex_mesh):
u_coarse = rhs_imex_mesh(self.init_c)
u_coarse.impl.values = self.Rspace.dot(F.impl.values)
u_coarse.expl.values = self.Rspace.dot(F.expl.values)
return u_coarse
def prolong_space(self, G):
"""
Prolongation implementation
Args:
G: the coarse level data (easier to access than via the coarse attribute)
"""
if isinstance(G, mesh):
u_fine = mesh(self.init_c, val=0.0)
u_fine.values = self.Pspace.dot(G.values)
elif isinstance(G, rhs_imex_mesh):
u_fine = rhs_imex_mesh(self.init_c)
u_fine.impl.values = self.Pspace.dot(G.impl.values)
u_fine.expl.values = self.Pspace.dot(G.expl.values)
return u_fine
| 3,644 | 35.45 | 113 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/advection_1d_implicit/getFDMatrix.py | import numpy as np
import scipy.linalg as LA
import scipy.sparse as sp
def getFDMatrix(N, order, dx):
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))
| 1,135 | 25.418605 | 93 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/advection_1d_implicit/plotFDconvergence.py | import math
import numpy as np
import numpy.linalg as LA
from matplotlib import pyplot as plt
from pySDC.playgrounds.deprecated.advection_1d_implicit.getFDMatrix import getFDMatrix
def u_function(x):
u = np.zeros(np.size(x))
for i in range(0, np.size(x)):
u[i] = math.cos(2.0 * math.pi * x[i])
return u
def u_x_function(x):
u = np.zeros(np.size(x))
for i in range(0, np.size(x)):
u[i] = -2.0 * math.pi * math.sin(2.0 * math.pi * x[i])
return u
p = [2, 4, 6]
Nv = [10, 25, 50, 75, 100, 125, 150]
error = np.zeros([np.size(p), np.size(Nv)])
orderline = np.zeros([np.size(p), np.size(Nv)])
for j in range(0, np.size(Nv)):
x = np.linspace(0, 1, num=Nv[j], endpoint=False)
dx = x[1] - x[0]
for i in range(0, np.size(p)):
A = getFDMatrix(Nv[j], p[i], dx)
u = u_function(x)
u_x_fd = A.dot(u)
u_x_ex = u_x_function(x)
error[i, j] = LA.norm(u_x_fd - u_x_ex, np.inf) / LA.norm(u_x_ex, np.inf)
orderline[i, j] = (float(Nv[0]) / float(Nv[j])) ** p[i] * error[i, 0]
fig = plt.figure(figsize=(8, 8))
plt.loglog(Nv, error[0, :], 'o', label='p=2', markersize=12, color='b')
plt.loglog(Nv, orderline[0, :], color='b')
plt.loglog(Nv, error[1, :], 'o', label='p=4', markersize=12, color='r')
plt.loglog(Nv, orderline[1, :], color='r')
plt.loglog(Nv, error[2, :], 'o', label='p=6', markersize=12, color='g')
plt.loglog(Nv, orderline[2, :], color='g')
plt.legend()
plt.xlim([Nv[0], Nv[np.size(Nv) - 1]])
plt.xlabel(r'$N_x$')
plt.ylabel('Relative error')
plt.show()
| 1,555 | 28.358491 | 86 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/advection_1d_implicit/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/deprecated/advection_1d_implicit/playground.py | import numpy as np
import pySDC.core.deprecated.PFASST_stepwise as mp
from examples.advection_1d_implicit.TransferClass import mesh_to_mesh_1d_periodic
from pySDC.core import CollocationClasses as collclass
from pySDC.core import Log
from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.playgrounds.deprecated.advection_1d_implicit.ProblemClass import advection
if __name__ == "__main__":
# set global logger (remove this if you do not want the output at all)
logger = Log.setup_custom_logger('root')
num_procs = 1
# This comes as read-in for the level class (this is optional!)
lparams = {}
lparams['restol'] = 1e-10
# This comes as read-in for the step class (this is optional!)
sparams = {}
sparams['maxiter'] = 10
# This comes as read-in for the problem class
pparams = {}
pparams['c'] = 1
pparams['nvars'] = [8, 4]
pparams['order'] = [2]
# This comes as read-in for the transfer operations (this is optional!)
tparams = {}
tparams['finter'] = True
tparams['iorder'] = 2
tparams['rorder'] = 1
# Fill description dictionary for easy hierarchy creation
description = {}
description['problem_class'] = advection
description['problem_params'] = pparams
description['collocation_class'] = collclass.CollGaussLegendre
description['num_nodes'] = 5
description['sweeper_class'] = generic_LU
description['level_params'] = lparams
description['transfer_class'] = mesh_to_mesh_1d_periodic
description['transfer_params'] = tparams
# quickly generate block of steps
MS = mp.generate_steps(num_procs, sparams, description)
# setup parameters "in time"
t0 = 0.0
dt = 0.1
Tend = dt
# get initial values on finest level
P = MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = mp.run_pfasst(MS, u0=uinit, t0=t0, dt=dt, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
print(
'error at time %s: %s'
% (Tend, np.linalg.norm(uex.values - uend.values, np.inf) / np.linalg.norm(uex.values, np.inf))
)
# extract_stats = grep_stats(stats,iter=-1,type='residual')
# sortedlist_stats = sort_stats(extract_stats,sortby='step')
# print(extract_stats,sortedlist_stats)
| 2,362 | 30.932432 | 103 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/burgers_2d_explicit/ProblemClass.py | import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as LA
from clawpack import pyclaw
from clawpack import riemann
from pySDC.core.Problem import ptype
from pySDC.implementations.datatype_classes import mesh, rhs_imex_mesh
class sharpclaw(ptype):
"""
Example implementing the forced 1D heat equation with Dirichlet-0 BC in [0,1]
Attributes:
solver: Sharpclaw solver
state: Sharclaw state
domain: Sharpclaw domain
"""
def __init__(self, cparams, dtype_u, dtype_f):
"""
Initialization routine
Args:
cparams: 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)
"""
# these parameters will be used later, so assert their existence
assert 'nvars' in cparams
# add parameters as attributes for further reference
for k, v in cparams.items():
setattr(self, k, v)
# invoke super init, passing number of dofs, dtype_u and dtype_f
super(sharpclaw, self).__init__(self.nvars, dtype_u, dtype_f)
riemann_solver = riemann.burgers_1D # NOTE: This uses the FORTRAN kernels of clawpack
self.solver = pyclaw.SharpClawSolver1D(riemann_solver)
self.solver.weno_order = 5
self.solver.time_integrator = 'Euler' # Remove later
self.solver.kernel_language = 'Fortran'
self.solver.bc_lower[0] = pyclaw.BC.periodic
self.solver.bc_upper[0] = pyclaw.BC.periodic
self.solver.cfl_max = 1.0
assert self.solver.is_valid()
x = pyclaw.Dimension(0.0, 1.0, self.nvars, name='x')
self.domain = pyclaw.Domain(x)
self.state = pyclaw.State(self.domain, self.solver.num_eqn)
self.dx = self.state.grid.x.centers[1] - self.state.grid.x.centers[0]
solution = pyclaw.Solution(self.state, self.domain)
self.solver.setup(solution)
self.A = self.__get_A(self.nvars, self.nu, self.dx)
def __get_A(self, N, nu, dx):
"""
Helper function to assemble FD matrix A in sparse format
Args:
N: number of dofs
nu: diffusion coefficient
dx: distance between two spatial nodes
Returns:
matrix A in CSC format
"""
stencil = [1, -2, 1]
A = sp.diags(stencil, [-1, 0, 1], shape=(N, N))
A *= nu / (dx**2)
return A.tocsc()
def solve_system(self, rhs, factor, u0, t):
"""
Simple linear solver for (I-dtA)u = rhs
Args:
rhs: right-hand side for the nonlinear system
factor: abbrev. for the node-to-node stepsize (or any other factor required)
u0: initial guess for the iterative solver (not used here so far)
t: current time (e.g. for time-dependent BCs)
Returns:
solution as mesh
"""
me = mesh(self.nvars)
me.values = LA.spsolve(sp.eye(self.nvars) - factor * self.A, rhs.values)
return me
def __eval_fexpl(self, u, t):
"""
Helper routine to evaluate the explicit part of the RHS
Args:
u: current values (not used here)
t: current time
Returns:
explicit part of RHS
"""
# Copy values of u into pyClaw state object
self.state.q[0, :] = u.values
# Evaluate right hand side
fexpl = mesh(self.nvars)
fexpl.values = self.solver.dqdt(self.state)
return fexpl
def __eval_fimpl(self, u, t):
"""
Helper routine to evaluate the implicit part of the RHS
Args:
u: current values
t: current time (not used here)
Returns:
implicit part of RHS
"""
fimpl = mesh(self.nvars, val=0.0)
fimpl.values = self.A.dot(u.values)
return fimpl
def eval_f(self, u, t):
"""
Routine to evaluate both parts of the RHS
Args:
u: current values
t: current time
Returns:
the RHS divided into two parts
"""
f = rhs_imex_mesh(self.nvars)
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: current time
Returns:
exact solution
"""
xc = self.state.grid.x.centers
me = mesh(self.nvars)
me.values = np.sin(2.0 * np.pi * (xc - t))
return me
| 4,688 | 26.745562 | 94 | py |
pySDC | pySDC-master/pySDC/playgrounds/deprecated/burgers_2d_explicit/__init__.py | 1 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/deprecated/burgers_2d_explicit/playground.py | import numpy as np
import pySDC.core.deprecated.PFASST_stepwise as mp
from ProblemClass import sharpclaw
from matplotlib import pyplot as plt
from pySDC.core import CollocationClasses as collclass
from pySDC.core import Log
from pySDC.implementations.datatype_classes import mesh, rhs_imex_mesh
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
if __name__ == "__main__":
# set global logger (remove this if you do not want the output at all)
logger = Log.setup_custom_logger('root')
num_procs = 1
# This comes as read-in for the level class
lparams = {}
lparams['restol'] = 3e-12
sparams = {}
sparams['maxiter'] = 20
# setup parameters "in time"
t0 = 0
dt = 0.01
Tend = 100 * dt
# This comes as read-in for the problem class
pparams = {}
pparams['nvars'] = [127]
pparams['nu'] = 0.001
# This comes as read-in for the transfer operations
tparams = {}
tparams['finter'] = True
# Fill description dictionary for easy hierarchy creation
description = {}
description['problem_class'] = sharpclaw
description['problem_params'] = pparams
description['dtype_u'] = mesh
description['dtype_f'] = rhs_imex_mesh
description['collocation_class'] = collclass.CollGaussLobatto
description['num_nodes'] = 5
description['sweeper_class'] = imex_1st_order
description['level_params'] = lparams
# description['transfer_class'] = mesh_to_mesh
# description['transfer_params'] = tparams
# quickly generate block of steps
MS = mp.generate_steps(num_procs, sparams, description)
# get initial values on finest level
P = MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = mp.run_pfasst(MS, u0=uinit, t0=t0, dt=dt, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
print(
'error at time %s: %s'
% (Tend, np.linalg.norm(uex.values - uend.values, np.inf) / np.linalg.norm(uex.values, np.inf))
)
fig = plt.figure(figsize=(8, 8))
plt.plot(P.state.grid.x.centers, uend.values, color='b', label='SDC')
plt.plot(P.state.grid.x.centers, uex.values, color='r', label='Exact')
plt.legend()
plt.xlim([0, 1])
plt.ylim([-1, 1])
plt.show()
# extract_stats = grep_stats(stats,iter=-1,type='residual')
# sortedlist_stats = sort_stats(extract_stats,sortby='step')
# print(extract_stats,sortedlist_stats)
| 2,502 | 29.901235 | 103 | py |
pySDC | pySDC-master/pySDC/playgrounds/Gander/testequation.py | import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.TestEquation_0D import testequation0d
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.playgrounds.Gander.HookClass_error_output import error_output
def testequation_setup(prec_type=None, maxiter=None):
"""
Setup routine for the test equation
Args:
par (float): parameter for controlling stiffness
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 0.0
level_params['dt'] = 1.0
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [5]
sweeper_params['QI'] = prec_type
sweeper_params['initial_guess'] = 'spread'
# initialize problem parameters
problem_params = dict()
problem_params['u0'] = 1.0 # initial value (for all instances)
# use single values like this...
# problem_params['lambdas'] = [[-1.0]]
# .. or a list of values like this ...
# problem_params['lambdas'] = [[-1.0, -2.0, 1j, -1j]]
problem_params['lambdas'] = [[-1.0 + 0j]]
# note: PFASST will do all of those at once, but without interaction (realized via diagonal matrix).
# The propagation matrix will be diagonal too, corresponding to the respective lambda value.
# initialize step parameters
step_params = dict()
step_params['maxiter'] = maxiter
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = testequation0d # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
return description, controller_params
def compare_preconditioners(f=None, list_of_k=None):
# set time parameters
t0 = 0.0
Tend = 2.0
for k in list_of_k:
description_IE, controller_params_IE = testequation_setup(prec_type='MIN3', maxiter=k)
description_LU, controller_params_LU = testequation_setup(prec_type='LU', maxiter=k)
out = f'\nWorking with maxiter = {k}'
f.write(out + '\n')
print(out)
# instantiate controller
controller_IE = controller_nonMPI(
num_procs=1, controller_params=controller_params_IE, description=description_IE
)
controller_LU = controller_nonMPI(
num_procs=1, controller_params=controller_params_LU, description=description_LU
)
# get initial values on finest level
P = controller_IE.MS[0].levels[0].prob
uinit = P.u_exact(t0)
uex = P.u_exact(Tend)
# this is where the iteration is happening
uend_IE, stats_IE = controller_IE.run(u0=uinit, t0=t0, Tend=Tend)
uend_LU, stats_LU = controller_LU.run(u0=uinit, t0=t0, Tend=Tend)
diff = abs(uend_IE - uend_LU)
err_IE = abs(uend_IE - uex)
err_LU = abs(uend_LU - uex)
out = ' Error (IE/LU) vs. exact solution: %6.4e -- %6.4e' % (err_IE, err_LU)
f.write(out + '\n')
print(out)
out = ' Difference between both results: %6.4e' % diff
f.write(out + '\n')
print(out)
# convert filtered statistics to list
errors_IE = get_sorted(stats_IE, type='error_after_step', sortby='time')
errors_LU = get_sorted(stats_LU, type='error_after_step', sortby='time')
print(errors_IE)
print(errors_LU)
def main():
f = open('comparison_IE_vs_LU.txt', 'w')
compare_preconditioners(f=f, list_of_k=[1])
f.close()
if __name__ == "__main__":
main()
| 4,233 | 33.422764 | 104 | py |
pySDC | pySDC-master/pySDC/playgrounds/Gander/thibaut_algorithms.py | import numpy as np
import matplotlib.pyplot as plt
collDict = {
'LOBATTO': CollGaussLobatto,
'RADAU_LEFT': CollGaussRadau_Left,
'RADAU_RIGHT': CollGaussRadau_Right,
'EQUID': Equidistant,
}
# Problem parameters
tBeg = 0
tEnd = 1
lam = -1.0 + 1j # \lambda coefficient from the space operator
numType = np.array(lam).dtype
u0 = 1 # initial solution
# Discretization parameters
L = 8 # number of time steps
M = 5 # number of nodes
sweepType = 'BE'
nodesType = 'EQUID'
# Time interval decomposition
times = np.linspace(tBeg, tEnd, num=L)
dt = times[1] - times[0]
# Generate nodes, deltas and Q using pySDC
coll = collDict[nodesType](M, 0, 1)
nodes = coll._getNodes
deltas = coll._gen_deltas
Q = coll._gen_Qmatrix[1:, 1:]
Q = Q * lam * dt
# Generate Q_\Delta
QDelta = np.zeros((M, M))
if sweepType in ['BE', 'FE']:
offset = 1 if sweepType == 'FE' else 0
for i in range(offset, M):
QDelta[i:, : M - i] += np.diag(deltas[: M - i])
else:
raise ValueError(f'sweepType={sweepType}')
QDelta = QDelta * lam * dt
print(QDelta.real)
exit()
# Generate other matrices
H = np.zeros((M, M), dtype=numType)
H[:, -1] = 1
I = np.identity(M)
# Generate operators
ImQDelta = I - QDelta
ImQ = I - Q
def fineSweep(u, uStar, f):
u += np.linalg.solve(ImQDelta, H.dot(uStar) + f - ImQ.dot(u))
def coarseSweep(u, uStar, f):
u += np.linalg.solve(ImQDelta, H.dot(uStar) + f)
# Variables
f = np.zeros((L, M), dtype=numType)
f[0] = u0
u = np.zeros((L, M), dtype=numType)
t = np.array([t + dt * nodes for t in times])
# Exact solution
uExact = np.exp(t * lam)
nSweep = 3 # also number of iteration for Parareal-SDC and PFASST
# SDC solution
uSDC = u.copy()
# uSDC[:] = u0
uStar = u[0] * 0
for l in range(L):
for n in range(nSweep):
fineSweep(uSDC[l], uStar, f[l])
uStar = uSDC[l]
# Parareal-SDC solution <=> pipelined SDC <=> RIDC ?
uPar = u.copy()
# uPar[:] = u0
for n in range(nSweep):
uStar = u[0] * 0
for l in range(L):
fineSweep(uPar[l], uStar, f[l])
uStar = uPar[l]
# PFASST solution
uPFA = u.copy()
if True:
# -- initialization with coarse sweep
# (equivalent to fine sweep, since uPFA[l] = 0)
uStar = u[0] * 0
for l in range(L):
coarseSweep(uPFA[l], uStar, f[l])
uStar = uPFA[l]
# -- PFASST iteration
for n in range(nSweep):
uStar = u[0] * 0
for l in range(L):
uStarPrev = uPFA[l].copy()
fineSweep(uPFA[l], uStar, f[l])
uStar = uStarPrev
# Plot solution and error
if True:
plt.figure('Solution (amplitude)')
for sol, lbl, sym in [
[uExact, 'Exact', 'o-'],
[uSDC, 'SDC', 's-'],
[uPar, 'Parareal', '>-'],
[uPFA, 'PFASST', 'p-'],
]:
plt.plot(t.ravel(), sol.ravel().real, sym, label=lbl)
plt.legend()
plt.grid(True)
plt.xlabel('Time')
plt.figure('Solution (phase)')
for sol, lbl, sym in [
[uExact, 'Exact', 'o-'],
[uSDC, 'SDC', 's-'],
[uPar, 'Parareal', '>-'],
[uPFA, 'PFASST', 'p-'],
]:
plt.plot(t.ravel(), sol.ravel().imag, sym, label=lbl)
plt.legend()
plt.grid(True)
plt.xlabel('Time')
eSDC = np.abs(uExact.ravel() - uSDC.ravel())
ePar = np.abs(uExact.ravel() - uPar.ravel())
ePFA = np.abs(uExact.ravel() - uPFA.ravel())
plt.figure('Error')
plt.semilogy(t.ravel(), eSDC, 's-', label=f'SDC {nSweep} sweep')
plt.semilogy(t.ravel(), ePar, '>-', label=f'Parareal {nSweep} iter')
plt.semilogy(t.ravel(), ePFA, 'p-', label=f'PFASST {nSweep} iter')
plt.legend()
plt.grid(True)
plt.xlabel('Time')
plt.show()
| 3,580 | 22.405229 | 68 | py |
pySDC | pySDC-master/pySDC/playgrounds/Gander/matrix_based.py | from pySDC.core.Sweeper import sweeper
import numpy as np
import matplotlib.pyplot as plt
def iteration_vs_estimate():
M = 5
K = 10
swee = sweeper({'collocation_class': CollGaussRadau_Right, 'num_nodes': M})
Q = swee.coll.Qmat[1:, 1:]
Qd = swee.get_Qdelta_implicit(swee.coll, 'IE')[1:, 1:]
# Qd = swee.get_Qdelta_implicit(swee.coll, 'LU')[1:, 1:]
# Qd = swee.get_Qdelta_explicit(swee.coll, 'EE')[1:, 1:]
print(np.linalg.norm(Q - Qd, np.inf))
exit()
I = np.eye(M)
lam = -0.7
print(1 / np.linalg.norm(Qd, np.inf), np.linalg.norm(np.linalg.inv(Qd), np.inf))
C = I - lam * Q
P = I - lam * Qd
Pinv = np.linalg.inv(P)
R = Pinv.dot(lam * (Q - Qd))
rho = max(abs(np.linalg.eigvals(R)))
infnorm = np.linalg.norm(R, np.inf)
twonorm = np.linalg.norm(R, 2)
# uex = np.exp(lam)
u0 = np.ones(M, dtype=np.complex128)
uex = np.linalg.inv(C).dot(u0)[-1]
u = u0.copy()
# u = np.random.rand(M)
res = u0 - C.dot(u)
err = []
resnorm = []
for k in range(K):
u += Pinv.dot(res)
res = u0 - C.dot(u)
err.append(abs(u[-1] - uex))
resnorm.append(np.linalg.norm(res, np.inf))
print(k, resnorm[-1], err[-1])
plt.figure()
plt.semilogy(range(K), err, 'o-', color='red', label='error')
plt.semilogy(range(K), resnorm, 'd-', color='orange', label='residual')
plt.semilogy(range(K), [err[0] * rho**k for k in range(K)], '--', color='green', label='spectral')
plt.semilogy(range(K), [err[0] * infnorm**k for k in range(K)], '--', color='blue', label='infnorm')
plt.semilogy(range(K), [err[0] * twonorm**k for k in range(K)], '--', color='cyan', label='twonorm')
plt.semilogy(range(K), [err[0] * ((-1 / lam) ** (1 / M)) ** k for k in range(K)], 'x--', color='black', label='est')
plt.semilogy(
range(K),
[err[0] * (abs(lam) * np.linalg.norm(Q - Qd)) ** k for k in range(K)],
'x-.',
color='black',
label='est',
)
# plt.semilogy(range(K), [err[0] * (1/abs(lam) + np.linalg.norm((I-np.linalg.inv(Qd).dot(Q)) ** k)) for k in range(K)], 'x-.', color='black', label='est')
plt.grid()
plt.legend()
plt.show()
def estimates_over_lambda():
M = 5
K = 10
swee = sweeper({'collocation_class': CollGaussRadau_Right, 'num_nodes': M})
Q = swee.coll.Qmat[1:, 1:]
# Qd = swee.get_Qdelta_implicit(swee.coll, 'IE')[1:, 1:]
Qd = swee.get_Qdelta_implicit(swee.coll, 'LU')[1:, 1:]
Qdinv = np.linalg.inv(Qd)
I = np.eye(M)
# lam = 1/np.linalg.eigvals(Q)[0]
# print(np.linalg.inv(I - lam * Q))
# print(np.linalg.norm(1/lam * Qdinv, np.inf))
# exit()
# print(np.linalg.norm((I-Qdinv.dot(Q)) ** K))
# lam_list = np.linspace(start=20j, stop=0j, num=1000, endpoint=False)
lam_list = np.linspace(start=-1000, stop=0, num=100, endpoint=True)
rho = []
est = []
infnorm = []
twonorm = []
for lam in lam_list:
# C = I - lam * Q
P = I - lam * Qd
Pinv = np.linalg.inv(P)
R = Pinv.dot(lam * (Q - Qd))
# w, V = np.linalg.eig(R)
# Vinv = np.linalg.inv(V)
# assert np.linalg.norm(V.dot(np.diag(w)).dot(Vinv) - R) < 1E-14, np.linalg.norm(V.dot(np.diag(w)).dot(Vinv) - R)
rho.append(max(abs(np.linalg.eigvals(R))))
# est.append(0.62*(-1/lam) ** (1/(M-1))) # M = 3
# est.append(0.57*(-1/lam) ** (1/(M-1))) # M = 5
# est.append(0.71*(-1/lam) ** (1/(M-1.5))) # M = 7
# est.append(0.92*(-1/lam) ** (1/(M-2.5))) # M = 9
# est.append((-1/lam) ** (1/(M)))
est.append(1000 * (1 / abs(lam)) ** (1 / (1)))
# est.append(abs(lam))
# est.append(np.linalg.norm((I-Qdinv.dot(Q)) ** M) + 1/abs(lam))
# est.append(np.linalg.norm(np.linalg.inv(I - lam * Qd), np.inf))
# est.append(np.linalg.norm(np.linalg.inv(I - np.linalg.inv(I - lam * np.diag(Qd)).dot(lam*np.tril(Qd, -1))), np.inf))
infnorm.append(np.linalg.norm(np.linalg.matrix_power(R, M), np.inf))
# infnorm.append(np.linalg.norm(Vinv.dot(R).dot(V), np.inf))
twonorm.append(np.linalg.norm(np.linalg.matrix_power(R, M), 2))
# twonorm.append(np.linalg.norm(Vinv.dot(R).dot(V), 2))
plt.figure()
plt.semilogy(lam_list, rho, '--', color='green', label='spectral')
plt.semilogy(lam_list, est, '--', color='red', label='est')
# plt.semilogy(lam_list, infnorm, 'x--', color='blue', label='infnorm')
# plt.semilogy(lam_list, twonorm, 'd--', color='cyan', label='twonorm')
# plt.semilogy(np.imag(lam_list), rho, '--', color='green', label='spectral')
# plt.semilogy(np.imag(lam_list), est, '--', color='red', label='est')
# plt.semilogy(np.imag(lam_list), infnorm, '--', color='blue', label='infnorm')
# plt.semilogy(np.imag(lam_list), twonorm, '--', color='cyan', label='twonorm')
plt.grid()
plt.legend()
plt.show()
if __name__ == '__main__':
# iteration_vs_estimate()
estimates_over_lambda()
| 5,022 | 37.638462 | 158 | py |
pySDC | pySDC-master/pySDC/playgrounds/Gander/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/Gander/HookClass_error_output.py | from pySDC.core.Hooks import hooks
class error_output(hooks):
"""
Hook class to add output of error
"""
def post_step(self, step, level_number):
"""
Default routine called after each step
Args:
step: the current step
level_number: the current level number
"""
super(error_output, self).post_step(step, level_number)
# some abbreviations
L = step.levels[level_number]
P = L.prob
L.sweep.compute_end_point()
# compute and save errors
upde = P.u_exact(step.time + step.dt)
pde_err = abs(upde - L.uend)
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='error_after_step',
value=pde_err,
)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='residual_after_step',
value=L.status.residual,
)
| 1,202 | 24.595745 | 63 | py |
pySDC | pySDC-master/pySDC/playgrounds/Gander/two_grid.py | import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spl
import matplotlib.pyplot as plt
import pySDC.helpers.transfer_helper as th
np.random.seed(32)
nX = 2**3 - 1
nXc = 2**2 - 1
dx = 1 / (nX + 1)
dxc = 1 / (nXc + 1)
stencil = [1, -2, 1]
A = sp.diags(stencil, [-1, 0, 1], shape=(nX, nX), format='csc')
A *= -1.0 / (dx**2)
b = np.zeros(nX)
# %%
PGS = spl.inv(sp.csc_matrix(np.tril(A.todense())))
PJ = sp.dia_matrix(np.diag(1 / np.diag(A.todense())))
RGS = sp.eye(nX) - PGS @ A
RJ = sp.eye(nX) - PJ @ A
sRJ = sp.eye(nX) - 0.5 * PJ @ A
Ac = sp.diags(stencil, [-1, 0, 1], shape=(nX // 2, nX // 2), format='csc')
Ac *= -1.0 / (dxc**2)
Acinv = spl.inv(Ac)
PJc = sp.dia_matrix(np.diag(1 / np.diag(Ac.todense())))
fine_grid = np.linspace(dx, 1, nX, endpoint=False)
coarse_grid = np.linspace(dxc, 1, nXc, endpoint=False)
Pr = th.interpolation_matrix_1d(fine_grid, coarse_grid, k=2, periodic=False, equidist_nested=True)
Prinj = th.interpolation_matrix_1d(fine_grid, coarse_grid, k=0, periodic=False, equidist_nested=True)
Re = 0.5 * Pr.T
# Re = Prinj.T
TG = (sp.eye(nX) - Pr @ Acinv @ Re @ A) @ sRJ.power(3)
TJ = (sp.eye(nX) - Pr @ PJc @ Re @ A) @ sRJ.power(3)
# %%
nIter = 10
dK = 5
def coarse(x, dK=1):
xK = x
for k in range(dK):
xK = RJ @ xK # + RJ @ b
return xK
def fine(x, dK=dK):
xK = x
for k in range(dK):
xK = RJ @ xK # + PGS @ b
return xK
def initBlocks(x):
x0 = np.sin(np.linspace(dx, 1 * 2 * np.pi, nX))
# x0 = np.random.rand(nX)
for l in range(nB + 1):
x[l, :] = x0
nB = nIter // dK
nK = nB + 1
uSeq = np.zeros((nB + 1, nX))
uNum = np.zeros((nK + 1, nB + 1, nX))
initBlocks(uNum[0])
uSeq[0] = uNum[0, 0]
uNum[:, 0, :] = uNum[0, 0, :]
for k in range(nK):
for l in range(nB):
uF = fine(uNum[k, l])
uGk = coarse(uNum[k, l], dK=1)
uGkp1 = coarse(uNum[k + 1, l], dK=1)
uNum[k + 1, l + 1] = uF + 0.25 * (uGkp1 - uGk)
for l in range(nB):
uSeq[l + 1] = fine(uSeq[l])
# %%
err = np.linalg.norm(uNum, axis=-1)[:, -1]
errSeq = np.linalg.norm(uSeq, axis=-1)
plt.figure()
plt.semilogy(err, label='Parareal')
plt.semilogy(errSeq, label='Sequential')
plt.legend()
plt.show()
| 2,218 | 20.336538 | 101 | py |
pySDC | pySDC-master/pySDC/playgrounds/PinT_Workshop_2017/my_HookClass.py | from pySDC.core.Hooks import hooks
class error_output(hooks):
"""
Hook class to add output of error
"""
def post_iteration(self, step, level_number):
"""
Default routine called after each iteration
Args:
step: the current step
level_number: the current level number
"""
super(error_output, self).post_iteration(step, level_number)
# some abbreviations
L = step.levels[level_number]
P = L.prob
L.sweep.compute_end_point()
uex = P.u_exact(step.time + step.dt)
err = abs(uex - L.uend)
print(
'--- Current error (vs. exact solution) at iteration %2i and time %4.2f: %6.4e'
% (step.status.iter, step.time, err)
)
| 784 | 23.53125 | 91 | py |
pySDC | pySDC-master/pySDC/playgrounds/PinT_Workshop_2017/play_with_me.py | import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_forced
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
def main():
"""
A simple test program to do PFASST runs for the heat equation
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.25
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = 'LU' # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 8 # frequency for the test value
problem_params['nvars'] = 511 # number of degrees of freedom for each level
problem_params['bc'] = 'dirichlet-zero' # BCs
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 2
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_forced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
# set time parameters
t0 = 0.0
Tend = 4.0
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# The following is used only for statistics and output, the main show is over now..
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
print('\nError (vs. exact solution) at time %4.2f: %6.4e\n' % (Tend, err))
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
for item in iter_counts:
print('Number of iterations for time %4.2f: %2i' % item)
niters = np.array([item[1] for item in iter_counts])
print(' Mean number of iterations: %4.2f' % np.mean(niters))
print(' Range of values for number of iterations: %2i ' % np.ptp(niters))
print(' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters))))
if __name__ == "__main__":
main()
| 3,509 | 35.947368 | 119 | py |
pySDC | pySDC-master/pySDC/playgrounds/PinT_Workshop_2017/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/compression/run_parallel_Heat_NumPy.py | from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
from pySDC.implementations.sweeper_classes.generic_LU import generic_implicit
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
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 = dict()
level_params['restol'] = 5e-10
level_params['dt'] = 0.125
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['QI'] = 'LU'
sweeper_params['num_nodes'] = [3]
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = 2 # frequency for the test value
problem_params['nvars'] = [63, 31] # number of degrees of freedom for each level
problem_params['bc'] = 'dirichlet-zero' # boundary conditions
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
step_params['errtol'] = 1e-05
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['all_to_done'] = True # can ask the controller to keep iterating all steps until the end
controller_params['use_iteration_estimator'] = False # activate iteration estimator
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_unforced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
# set time parameters
t0 = 0.0
Tend = 1.0
return description, controller_params, t0, Tend
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:
out = 'Working with %2i processes...' % size
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
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])
print(out)
| 4,376 | 34.877049 | 111 | py |
pySDC | pySDC-master/pySDC/playgrounds/compression/run_parallel_Heat_PETSc.py | import sys
from argparse import ArgumentParser
import numpy as np
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.problem_classes.HeatEquation_2D_PETSc_forced import heat2d_petsc_forced
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferPETScDMDA import mesh_to_mesh_petsc_dmda
def main(nprocs_space=None):
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
# split world communicator to create space-communicators
if nprocs_space is not None:
color = int(world_rank / nprocs_space)
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
space_rank = space_comm.Get_rank()
space_size = space_comm.Get_size()
# split world communicator to create time-communicators
if nprocs_space is not None:
color = int(world_rank % nprocs_space)
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
time_rank = time_comm.Get_rank()
time_size = time_comm.Get_size()
print(
"IDs (world, space, time): %i / %i -- %i / %i -- %i / %i"
% (world_rank, world_size, space_rank, space_size, time_rank, time_size)
)
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 0.125
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 1.0 # diffusion coefficient
problem_params['freq'] = 2 # frequency for the test value
problem_params['cnvars'] = [(127, 127)] # number of degrees of freedom for each level
problem_params['refine'] = 1 # number of degrees of freedom for each level
problem_params['comm'] = space_comm
problem_params['sol_tol'] = 1e-12
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
# space_transfer_params = dict()
# space_transfer_params['rorder'] = 2
# space_transfer_params['iorder'] = 2
# space_transfer_params['periodic'] = True
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20 if space_rank == 0 else 99 # set level depending on rank
# controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heat2d_petsc_forced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_petsc_dmda # pass spatial transfer class
# description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
# set time parameters
t0 = 0.0
Tend = 0.5
# instantiate controller
controller = controller_MPI(controller_params=controller_params, description=description, comm=time_comm)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
if time_rank == time_size - 1 and space_rank == 0:
print(f'Error vs. exact solution: {err}')
if space_rank == 0:
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %2i' % item
print(out)
niters = np.array([item[1] for item in iter_counts])
out = f' Time-rank {time_rank} -- Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = f' Time-rank {time_rank} -- Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = f' Time-rank {time_rank} -- Position of max/min number of iterations: %2i -- %2i' % (
int(np.argmax(niters)),
int(np.argmin(niters)),
)
print(out)
out = f' Time-rank {time_rank} -- Std and var for number of iterations: %4.2f -- %4.2f' % (
float(np.std(niters)),
float(np.var(niters)),
)
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
print(f' Time-rank {time_rank} -- Time to solution: {timing[0][1]}')
if __name__ == "__main__":
# Add parser to get number of processors in space
# Run this file via `mpirun -np N python run_parallel_Heat_PETSc.py -n P`,
# where N is the overall number of processors and P is the number of processors used for spatial parallelization.
parser = ArgumentParser()
parser.add_argument("-n", "--nprocs_space", help='Specifies the number of processors in space', type=int)
args = parser.parse_args()
main(nprocs_space=args.nprocs_space)
| 5,883 | 36.96129 | 117 | py |
pySDC | pySDC-master/pySDC/playgrounds/compression/run_serial_examples.py | import numpy as np
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_forced
from pySDC.implementations.problem_classes.AdvectionEquation_ND_FD import advectionNd
from pySDC.implementations.problem_classes.Auzinger_implicit import auzinger
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
from pySDC.implementations.transfer_classes.TransferMesh_NoCoarse import mesh_to_mesh as mesh_to_mesh_nc
from pySDC.implementations.convergence_controller_classes.check_iteration_estimator import CheckIterationEstimatorNonMPI
from pySDC.playgrounds.compression.HookClass_error_output import error_output
def setup_diffusion(dt=None, ndim=None, ml=False):
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = dt # time-step size
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['ndim'] = ndim # will be iterated over
problem_params['order'] = 8 # order of accuracy for FD discretization in space
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['bc'] = 'periodic' # boundary conditions
problem_params['freq'] = tuple(2 for _ in range(ndim)) # frequencies
if ml:
problem_params['nvars'] = [tuple(64 for _ in range(ndim)), tuple(32 for _ in range(ndim))] # number of dofs
else:
problem_params['nvars'] = tuple(64 for _ in range(ndim)) # number of dofs
problem_params['solver_type'] = 'CG' # do CG instead of LU
problem_params['liniter'] = 10 # number of CG iterations
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
space_transfer_params['periodic'] = True
# setup the iteration estimator
convergence_controllers = dict()
convergence_controllers[CheckIterationEstimatorNonMPI] = {'errtol': 1e-7}
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_forced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
# description['space_transfer_class'] = mesh_to_mesh_fft # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
description['convergence_controllers'] = convergence_controllers
return description, controller_params
def setup_advection(dt=None, ndim=None, ml=False):
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = dt # time-step size
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['ndim'] = ndim # will be iterated over
problem_params['order'] = 6 # order of accuracy for FD discretization in space
problem_params['type'] = 'center' # order of accuracy for FD discretization in space
problem_params['bc'] = 'periodic' # boundary conditions
problem_params['c'] = 0.1 # diffusion coefficient
problem_params['freq'] = tuple(2 for _ in range(ndim)) # frequencies
if ml:
problem_params['nvars'] = [tuple(64 for _ in range(ndim)), tuple(32 for _ in range(ndim))] # number of dofs
else:
problem_params['nvars'] = tuple(64 for _ in range(ndim)) # number of dofs
problem_params['solver_type'] = 'GMRES' # do GMRES instead of LU
problem_params['liniter'] = 10 # number of GMRES iterations
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
space_transfer_params['periodic'] = True
# setup the iteration estimator
convergence_controllers = dict()
convergence_controllers[CheckIterationEstimatorNonMPI] = {'errtol': 1e-7}
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = advectionNd
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
# description['space_transfer_class'] = mesh_to_mesh_fft # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
description['convergence_controllers'] = convergence_controllers
return description, controller_params
def setup_auzinger(dt=None, ml=False):
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = dt # time-step size
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
if ml:
sweeper_params['num_nodes'] = [3, 2]
else:
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['newton_tol'] = 1e-12
problem_params['newton_maxiter'] = 10
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# setup the iteration estimator
convergence_controllers = dict()
convergence_controllers[CheckIterationEstimatorNonMPI] = {'errtol': 1e-7}
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = auzinger
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_nc # pass spatial transfer class
description['convergence_controllers'] = convergence_controllers
return description, controller_params
def run_simulations(type=None, ndim_list=None, Tend=None, nsteps_list=None, ml=False, nprocs=None):
"""
A simple test program to do SDC runs for the heat equation in various dimensions
"""
t0 = None
dt = None
description = None
controller_params = None
for ndim in ndim_list:
for nsteps in nsteps_list:
if type == 'diffusion':
# set time parameters
t0 = 0.0
dt = (Tend - t0) / nsteps
description, controller_params = setup_diffusion(dt, ndim, ml)
elif type == 'advection':
# set time parameters
t0 = 0.0
dt = (Tend - t0) / nsteps
description, controller_params = setup_advection(dt, ndim, ml)
elif type == 'auzinger':
assert ndim == 1
# set time parameters
t0 = 0.0
dt = (Tend - t0) / nsteps
description, controller_params = setup_auzinger(dt, ml)
print(f'Running {type} in {ndim} dimensions with time-step size {dt}...')
print()
# Warning: this is black magic used to run an 'exact' collocation solver for each step within the hooks
description['step_params']['description'] = description
description['step_params']['controller_params'] = controller_params
# instantiate controller
controller = controller_nonMPI(
num_procs=nprocs, controller_params=controller_params, description=description
)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
niters = np.array([item[1] for item in iter_counts])
out = f' Mean number of iterations: {np.mean(niters):4.2f}'
print(out)
# filter statistics by type (error after time-step)
PDE_errors = get_sorted(stats, type='PDE_error_after_step', sortby='time')
coll_errors = get_sorted(stats, type='coll_error_after_step', sortby='time')
for iters, PDE_err, coll_err in zip(iter_counts, PDE_errors, coll_errors):
out = (
f' Errors after step {PDE_err[0]:8.4f} with {iters[1]} iterations: '
f'{PDE_err[1]:8.4e} / {coll_err[1]:8.4e}'
)
print(out)
print()
# filter statistics by type (error after time-step)
timing = get_sorted(stats, type='timing_run', sortby='time')
out = f'...done, took {timing[0][1]} seconds!'
print(out)
print()
print('-----------------------------------------------------------------------------')
if __name__ == "__main__":
run_simulations(type='diffusion', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=False, nprocs=1)
run_simulations(type='diffusion', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=True, nprocs=1)
run_simulations(type='advection', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=False, nprocs=1)
run_simulations(type='advection', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=True, nprocs=1)
run_simulations(type='auzinger', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=False, nprocs=1)
run_simulations(type='auzinger', ndim_list=[1], Tend=1.0, nsteps_list=[8], ml=True, nprocs=1)
| 12,159 | 42.274021 | 120 | py |
pySDC | pySDC-master/pySDC/playgrounds/compression/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/compression/run_parallel_AC_MPIFFT.py | from argparse import ArgumentParser
import numpy as np
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.problem_classes.AllenCahn_MPIFFT import allencahn_imex, allencahn_imex_timeforcing
from pySDC.implementations.transfer_classes.TransferMesh_MPIFFT import fft_to_fft
from pySDC.projects.AllenCahn_Bayreuth.AllenCahn_dump import dump
def run_simulation(name=None, nprocs_space=None):
"""
A simple test program to do PFASST runs for the AC equation
"""
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
# split world communicator to create space-communicators
if nprocs_space is not None:
color = int(world_rank / nprocs_space)
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
space_comm.Set_name('Space-Comm')
space_size = space_comm.Get_size()
space_rank = space_comm.Get_rank()
# split world communicator to create time-communicators
if nprocs_space is not None:
color = int(world_rank % nprocs_space)
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
time_comm.Set_name('Time-Comm')
time_size = time_comm.Get_size()
time_rank = time_comm.Get_rank()
# print(time_size, space_size, world_size)
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 1e-03
level_params['nsweeps'] = [3, 1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
# This defines the number of 'patches' for the simulation per dimension in 2D. L=4 means: 4x4 patches
problem_params['L'] = 4.0
# problem_params['L'] = 16.0
# This defines the number of nodes in space, ideally with about 144 nodes per patch (48 * 12 / 4)
problem_params['nvars'] = [(48 * 12, 48 * 12), (8 * 12, 8 * 12)]
# problem_params['nvars'] = [(48 * 48, 48 * 48), (8 * 48, 8 * 48)]
problem_params['eps'] = [0.04]
problem_params['radius'] = 0.25
problem_params['comm'] = space_comm
problem_params['name'] = name
problem_params['init_type'] = 'circle_rand'
problem_params['spectral'] = False
if name == 'AC-bench-constforce':
problem_params['dw'] = [-23.59]
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20 if space_rank == 0 else 99 # set level depending on rank
controller_params['predict_type'] = 'fine_only'
# controller_params['hook_class'] = dump # activate to get data output at each step
# fill description dictionary for easy step instantiation
description = dict()
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = fft_to_fft
if name == 'AC-bench-noforce' or name == 'AC-bench-constforce':
description['problem_class'] = allencahn_imex
elif name == 'AC-bench-timeforce':
description['problem_class'] = allencahn_imex_timeforcing
else:
raise NotImplementedError(f'{name} is not implemented')
# set time parameters
t0 = 0.0
Tend = 4 * 0.001
if space_rank == 0 and time_rank == 0:
out = f'---------> Running {name} with {time_size} process(es) in time and {space_size} process(es) in space...'
print(out)
# instantiate controller
controller = controller_MPI(controller_params=controller_params, description=description, comm=time_comm)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
timing = get_sorted(stats, type='timing_setup', sortby='time')
max_timing_setup = time_comm.allreduce(timing[0][1], MPI.MAX)
timing = get_sorted(stats, type='timing_run', sortby='time')
max_timing = time_comm.allreduce(timing[0][1], MPI.MAX)
if space_rank == 0 and time_rank == time_size - 1:
print()
out = f'Setup time: {max_timing_setup:.4f} sec.'
print(out)
out = f'Time to solution: {max_timing:.4f} sec.'
print(out)
iter_counts = get_sorted(stats, type='niter', sortby='time')
niters = np.array([item[1] for item in iter_counts])
out = f'Mean number of iterations: {np.mean(niters):.4f}'
print(out)
if __name__ == "__main__":
# Add parser to get number of processors in space and setup (have to do this here to enable automatic testing)
# Run this file via `mpirun -np N python run_parallel_AC_MPIFFT.py -n P`,
# where N is the overall number of processors and P is the number of processors used for spatial parallelization.
parser = ArgumentParser()
parser.add_argument(
"-s",
"--setup",
help='Specifies the setup',
type=str,
default='AC-bench-noforce',
choices=['AC-bench-noforce', 'AC-bench-constforce', 'AC-bench-timeforce'],
)
parser.add_argument("-n", "--nprocs_space", help='Specifies the number of processors in space', type=int)
args = parser.parse_args()
run_simulation(name=args.setup, nprocs_space=args.nprocs_space)
| 6,111 | 37.440252 | 120 | py |
pySDC | pySDC-master/pySDC/playgrounds/compression/HookClass_error_output.py | from pySDC.core.Hooks import hooks
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
class error_output(hooks):
"""
Hook class to add output of error
"""
def __init__(self):
super(error_output, self).__init__()
self.uex = None
# def post_iteration(self, step, level_number):
# """
# Default routine called after each iteration
# Args:
# step: the current step
# level_number: the current level number
# """
#
# super(error_output, self).post_iteration(step, level_number)
#
# # some abbreviations
# L = step.levels[level_number]
# P = L.prob
#
# L.sweep.compute_end_point()
#
# uex = P.u_exact(step.time + step.dt)
# err = abs(uex - L.uend)
#
# 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='error_after_iter', value=err)
def pre_step(self, step, level_number):
"""
Default routine called before each step
Args:
step: the current step
level_number: the current level number
"""
super(error_output, self).pre_step(step, level_number)
L = step.levels[level_number]
description = step.params.description
description['level_params']['restol'] = 1e-14
description['problem_params']['solver_type'] = 'direct'
description['convergence_controllers'] = {}
controller_params = step.params.controller_params
del controller_params['hook_class']
controller_params['logger_level'] = 90
controller = controller_nonMPI(num_procs=1, description=description, controller_params=controller_params)
self.uex, _ = controller.run(u0=L.u[0], t0=L.time, Tend=L.time + L.dt)
def post_step(self, step, level_number):
"""
Default routine called after each step
Args:
step: the current step
level_number: the current level number
"""
super(error_output, self).post_step(step, level_number)
# some abbreviations
L = step.levels[level_number]
P = L.prob
L.sweep.compute_end_point()
upde = P.u_exact(step.time + step.dt)
pde_err = abs(upde - L.uend)
coll_err = abs(self.uex - L.uend)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='PDE_error_after_step',
value=pde_err,
)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=L.level_index,
iter=step.status.iter,
sweep=L.status.sweep,
type='coll_error_after_step',
value=coll_err,
)
| 3,027 | 30.216495 | 117 | py |
pySDC | pySDC-master/pySDC/playgrounds/other/plots_overresolve_time.py | import pySDC.helpers.plot_helper as plt_helper
def beautify_plot(nprocs, fname):
plt_helper.plt.grid()
plt_helper.plt.legend(loc=2)
plt_helper.plt.xlabel('Number of parallel steps')
plt_helper.plt.ylabel('Theoretical speedup')
plt_helper.plt.xlim(0.9 * nprocs[0], 1.1 * nprocs[-1])
plt_helper.plt.ylim(0.25, 6.5)
plt_helper.plt.xticks(nprocs, nprocs)
plt_helper.plt.minorticks_off()
# save plot, beautify
plt_helper.savefig(fname)
def plot_data():
nprocs = [1, 2, 4, 8, 16, 32]
niter_overres = [1, 2, 3, 3, 3, 4]
alpha_overres = 1.0 / 32.0
speedup_overres = [p / (p * alpha_overres + k * (1 + alpha_overres)) for p, k in zip(nprocs, niter_overres)]
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(
nprocs, speedup_overres, color='g', marker='o', markersize=6, label=r'$N_\mathcal{F}=1024, \alpha=\frac{1}{32}$'
)
beautify_plot(nprocs, 'fool_speedup_overres_time')
niter_wellres_1 = [1, 2, 4, 8, 16, 32]
alpha_wellres_1 = 1.0 / 32.0
speedup_wellres_1 = [p / (p * alpha_wellres_1 + k * (1 + alpha_wellres_1)) for p, k in zip(nprocs, niter_wellres_1)]
niter_wellres_2 = [1, 2, 4, 5, 6, 8]
alpha_wellres_2 = 1.0 / 4.0
speedup_wellres_2 = [p / (p * alpha_wellres_2 + k * (1 + alpha_wellres_2)) for p, k in zip(nprocs, niter_wellres_2)]
# niter_wellres_3 = [1, 2, 3, 3, 4, 5]
# alpha_wellres_3 = 1.0 / 2.0
# speedup_wellres_3 = [p / (p * alpha_wellres_3 + k * (1 + alpha_wellres_3)) for p, k in zip(nprocs, niter_wellres_3)]
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(
nprocs, speedup_wellres_1, color='r', marker='d', markersize=6, label=r'$N_\mathcal{F}=32, \alpha=\frac{1}{32}$'
)
plt_helper.plt.semilogx(
nprocs, speedup_wellres_2, color='b', marker='s', markersize=6, label=r'$N_\mathcal{F}=32, \alpha=\frac{1}{4}$'
)
# plt_helper.plt.semilogx(nprocs, speedup_wellres_3, color='c', marker='v', markersize=6, label=r'$Nt_f=32, \alpha=\frac{1}{2}$')
beautify_plot(nprocs, 'fool_speedup_wellres_time')
if __name__ == '__main__':
plot_data()
| 2,222 | 35.442623 | 133 | py |
pySDC | pySDC-master/pySDC/playgrounds/other/parallel_rhs_mesh.py | import numpy as np
class mymesh(np.ndarray):
def __new__(cls, init, val=0.0):
"""
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, mymesh):
obj = np.ndarray.__new__(cls, init.shape, dtype=init.dtype, buffer=None)
obj[:] = init[:]
obj.part1 = obj[0, :]
obj.part2 = obj[1, :]
elif isinstance(init, tuple):
obj = np.ndarray.__new__(cls, shape=(2, init[0]), dtype=init[1], buffer=None)
obj.fill(val)
obj.part1 = obj[0, :]
obj.part2 = obj[1, :]
else:
raise NotImplementedError(type(init))
return obj
def __array_finalize__(self, obj):
"""
Finalizing the datatype. Without this, new datatypes do not 'inherit' the communicator.
"""
if obj is None:
return
self.part1 = getattr(obj, 'part1', None)
self.part2 = getattr(obj, 'part2', None)
m = mymesh((10, np.dtype('float64')))
m.part1[:] = 1
m.part2[:] = 2
print(m.part1, m.part2)
print(m)
print()
n = mymesh(m)
n.part1[0] = 10
print(n.part1, n.part2)
print(n)
print()
print(o.part1, o.part2)
print(o)
print()
# print(n + m)
| 1,490 | 24.706897 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/other/plots_overresolve_iter.py | import pySDC.helpers.plot_helper as plt_helper
def beautify_plot(nprocs, fname):
plt_helper.plt.grid()
plt_helper.plt.legend(loc=2)
plt_helper.plt.xlabel('Number of parallel steps')
plt_helper.plt.ylabel('Theoretical speedup')
plt_helper.plt.xlim(0.9 * nprocs[0], 1.1 * nprocs[-1])
plt_helper.plt.ylim(0.25, 6.5)
plt_helper.plt.xticks(nprocs, nprocs)
plt_helper.plt.minorticks_off()
# save plot, beautify
plt_helper.savefig(fname)
def plot_data():
nprocs = [1, 2, 4, 8]
niter_overres = [9, 5, 11, 23]
alpha_overres = 1.0 / 4.0
speedup_overres = [
p / (p / niter_overres[0] * alpha_overres + k / niter_overres[0] * (1 + alpha_overres))
for p, k in zip(nprocs, niter_overres)
]
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(
nprocs,
speedup_overres,
color='orange',
marker='o',
markersize=6,
label=r'$Nx_\mathcal{F}=512, \alpha=\frac{1}{4}$',
)
beautify_plot(nprocs, 'fool_speedup_overres_iter')
niter_wellres_1 = [9, 11, 16, 28]
alpha_wellres_1 = 1.0 / 4.0
speedup_wellres_1 = [
p / (p / niter_wellres_1[0] * alpha_wellres_1 + k / niter_wellres_1[0] * (1 + alpha_wellres_1))
for p, k in zip(nprocs, niter_wellres_1)
]
niter_wellres_2 = [9, 11, 16, 29]
alpha_wellres_2 = 1.0 / 2.0
speedup_wellres_2 = [
p / (p / niter_wellres_2[0] * alpha_wellres_2 + k / niter_wellres_2[0] * (1 + alpha_wellres_2))
for p, k in zip(nprocs, niter_wellres_2)
]
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(
nprocs, speedup_wellres_1, color='r', marker='d', markersize=6, label=r'$Nx_\mathcal{F}=32, \alpha=\frac{1}{4}$'
)
plt_helper.plt.semilogx(
nprocs, speedup_wellres_2, color='b', marker='s', markersize=6, label=r'$Nx_\mathcal{F}=32, \alpha=\frac{1}{2}$'
)
beautify_plot(nprocs, 'fool_speedup_wellres_iter')
if __name__ == '__main__':
plot_data()
| 2,099 | 29 | 120 | py |
pySDC | pySDC-master/pySDC/playgrounds/other/plots_overresolve_space.py | import pySDC.helpers.plot_helper as plt_helper
def beautify_plot(nprocs, fname):
plt_helper.plt.grid()
plt_helper.plt.legend(loc=2)
plt_helper.plt.xlabel('Number of parallel steps')
plt_helper.plt.ylabel('Theoretical speedup')
plt_helper.plt.xlim(0.9 * nprocs[0], 1.1 * nprocs[-1])
plt_helper.plt.ylim(0.25, 6.5)
plt_helper.plt.xticks(nprocs, nprocs)
plt_helper.plt.minorticks_off()
# save plot, beautify
plt_helper.savefig(fname)
def plot_data():
nprocs = [1, 2, 4, 8]
# niter_overres = [7, 4, 6, 9]
niter_overres = [21, 12, 16, 22]
# niter_overres = [9, 5, 11, 23]
alpha_overres = 1.0 / 4.0
speedup_overres = [
p / (p / niter_overres[0] * alpha_overres + k / niter_overres[0] * (1 + alpha_overres))
for p, k in zip(nprocs, niter_overres)
]
print(speedup_overres)
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(
nprocs, speedup_overres, color='g', marker='o', markersize=6, label=r'$Nx_\mathcal{F}=512, \alpha=\frac{1}{4}$'
)
beautify_plot(nprocs, 'fool_speedup_overres_space')
niter_wellres_1 = [21, 24, 32, 48]
alpha_wellres_1 = 1.0 / 4.0
speedup_wellres_1 = [
p / (p / niter_wellres_1[0] * alpha_wellres_1 + k / niter_wellres_1[0] * (1 + alpha_wellres_1))
for p, k in zip(nprocs, niter_wellres_1)
]
print(speedup_wellres_1)
niter_wellres_2 = [21, 24, 33, 49]
alpha_wellres_2 = 1.0 / 2.0
speedup_wellres_2 = [
p / (p / niter_wellres_2[0] * alpha_wellres_2 + k / niter_wellres_2[0] * (1 + alpha_wellres_2))
for p, k in zip(nprocs, niter_wellres_2)
]
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(
nprocs, speedup_wellres_1, color='r', marker='d', markersize=6, label=r'$Nx_\mathcal{F}=32, \alpha=\frac{1}{4}$'
)
plt_helper.plt.semilogx(
nprocs, speedup_wellres_2, color='b', marker='s', markersize=6, label=r'$Nx_\mathcal{F}=32, \alpha=\frac{1}{2}$'
)
beautify_plot(nprocs, 'fool_speedup_wellres_space')
if __name__ == '__main__':
plot_data()
| 2,187 | 30.710145 | 120 | py |
pySDC | pySDC-master/pySDC/playgrounds/other/nonblocking.py | from mpi4py import MPI
import numpy as np
def main():
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
data = None
if rank == 0:
data = np.array([1, 2, 3])
req = comm.isend(data, dest=1)
req.wait()
elif rank == 1:
data = comm.recv(source=0)
print(data)
#
# if rank == 0:
# n = 10
# for i in range(n):
# tmp = np.array(i, dtype=int)
# # print(f'{rank} sending {i} to {1} - START')
# comm.send(tmp, dest=1)
# # req = comm.isend(tmp, dest=1, tag=i)
# # req = comm.Isend((tmp, MPI.INT), dest=1, tag=i)
# # req.wait()
# # print(f'{rank} sending {i} to {1} - STOP')
# elif rank == 1:
# pass
if __name__ == '__main__':
main()
| 832 | 22.138889 | 63 | py |
pySDC | pySDC-master/pySDC/playgrounds/other/petsc_datatype.py | from petsc4py import PETSc
import numpy as np
class mymesh(PETSc.Vec):
__array_priority__ = 1000
def __new__(cls, init=None, val=0.0):
if isinstance(init, mymesh) or isinstance(init, PETSc.Vec):
obj = PETSc.Vec().__new__(cls)
init.copy(obj)
elif isinstance(init, PETSc.DMDA):
tmp = init.createGlobalVector()
obj = mymesh(tmp)
objarr = init.getVecArray(obj)
objarr[:] = val
else:
obj = PETSc.Vec().__new__(cls)
return obj
# def __rmul__(self, other):
# print('here')
# tmp = self.getArray()
# tmp[:] *= other
# return self
def __abs__(self):
"""
Overloading the abs operator
Returns:
float: absolute maximum of all mesh values
"""
# take absolute values of the mesh values
# print(self.norm(3))
return self.norm(3)
# def __array_finalize__(self, obj):
# """
# Finalizing the datatype. Without this, new datatypes do not 'inherit' the communicator.
# """
# if obj is None:
# return
# self.part1 = getattr(obj, 'part1', None)
# self.part2 = getattr(obj, 'part2', None)
# u = mymesh((16, PETSc.COMM_WORLD), val=9)
# uarr = u.getArray()
# # uarr[:] = np.random.rand(4,4)
# print(uarr, u.getOwnershipRanges())
# v = mymesh(u)
# varr = v.getArray()
# print(varr, v.getOwnershipRange() )
# if v.comm.getRank() == 0:
# uarr[0] = 7
#
# print(uarr)
# print(varr)
#
# w = u + v
# warr = w.getArray()
# print(warr, w.getOwnershipRange())
da = PETSc.DMDA().create([4, 4], stencil_width=1)
u = mymesh(da, val=9.0)
uarr = u.getArray()
v = mymesh(u)
varr = v.getArray()
if v.comm.getRank() == 0:
uarr[0] = 7
uarr = da.getVecArray(u)
print(uarr[:], uarr.shape, type(u))
print(varr[:], v.getOwnershipRange(), type(v))
exit()
w = np.float(1.0) * (u + v)
warr = da.getVecArray(w)
print(warr[:], da.getRanges(), type(w))
print(w.norm(3))
print(abs(w))
# v = PETSc.Vec().createMPI(16)
# varr = v.getArray()
# varr[:] = 9.0
# a = np.float64(1.0) * v
# print(type(a))
exit()
| 2,170 | 22.344086 | 97 | py |
pySDC | pySDC-master/pySDC/playgrounds/other/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/other/plots_overresolve.py | import pySDC.helpers.plot_helper as plt_helper
def beautify_plot(nprocs, fname):
plt_helper.plt.grid()
plt_helper.plt.legend(loc=0)
plt_helper.plt.xlabel('Number of parallel steps')
plt_helper.plt.ylabel('Theoretical speedup')
plt_helper.plt.xlim(0.9 * nprocs[0], 1.1 * nprocs[-1])
plt_helper.plt.ylim(0.25, 5.25)
plt_helper.plt.xticks(nprocs, nprocs)
plt_helper.plt.minorticks_off()
# save plot, beautify
plt_helper.savefig(fname)
def plot_data():
nprocs = [1, 2, 4, 8, 16]
niter_fd = [2.8125, 3.875, 5.5, 7.5, 9.0]
niter_fft_overres = [2.8125, 3.875, 5.5, 7.5, 9.0]
niter_fft = [6.3125, 8.375, 11.25, 15.5, 24.0]
niter_fft_slight = [2.8125, 3.875, 5.5, 7.5, 9.0]
speedup_fd = [p / (i / niter_fd[0]) for p, i in zip(nprocs, niter_fd)]
speedup_fft_overres = [p / (i / niter_fft_overres[0]) for p, i in zip(nprocs, niter_fft_overres)]
speedup_fft = [p / (i / niter_fft_overres[0]) for p, i in zip(nprocs, niter_fft)]
speedup_fft_slight = [p / (i / niter_fft_overres[0]) for p, i in zip(nprocs, niter_fft_slight)]
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(nprocs, speedup_fd, color='b', marker='o', markersize=6, label='FD, Nx=128')
beautify_plot(nprocs, 'fool_speedup_fd')
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(nprocs, speedup_fd, color='b', marker='o', markersize=6, label='FD, Nx=128')
plt_helper.plt.semilogx(
nprocs, speedup_fft_overres, color='orange', marker='x', markersize=6, label='Spectral, Nx=128'
)
beautify_plot(nprocs, 'fool_speedup_fft_overres')
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(nprocs, speedup_fd, color='b', marker='o', markersize=6, label='FD, Nx=128')
plt_helper.plt.semilogx(
nprocs, speedup_fft_overres, color='orange', marker='x', markersize=6, label='Spectral, Nx=128'
)
plt_helper.plt.semilogx(nprocs, speedup_fft, color='r', marker='v', markersize=6, label='Spectral, Nx=8')
beautify_plot(nprocs, 'fool_speedup_fft_minimal')
plt_helper.setup_mpl()
plt_helper.newfig(textwidth=238.96, scale=1.0)
plt_helper.plt.semilogx(nprocs, speedup_fd, color='b', marker='o', markersize=6, label='FD, Nx=128')
plt_helper.plt.semilogx(
nprocs, speedup_fft_overres, color='orange', marker='x', markersize=6, label='Spectral, Nx=128'
)
plt_helper.plt.semilogx(nprocs, speedup_fft, color='r', marker='v', markersize=6, label='Spectral, Nx=8')
plt_helper.plt.semilogx(nprocs, speedup_fft_slight, color='g', marker='d', markersize=6, label='Spectral, Nx=16')
beautify_plot(nprocs, 'fool_speedup_fft_slight')
# plt_helper.plt.grid()
# plt_helper.plt.legend(loc=0)
# plt_helper.plt.xlabel('Number of parallel steps')
# plt_helper.plt.ylabel('Theoretical speedup')
#
# plt_helper.plt.xlim(0.9*nprocs[0], 1.1*nprocs[-1])
# plt_helper.plt.ylim(0.75, 5.25)
#
# plt_helper.plt.xticks(nprocs, nprocs)
# plt_helper.plt.minorticks_off()
#
# # save plot, beautify
# fname = 'fool_speedup_fd'
# plt_helper.savefig(fname)
# plt_helper.plt.semilogx(nprocs, speedup_fft, color='g', marker='o', label='FFT')
#
# fname = 'fool_speedup_fft'
# plt_helper.savefig(fname)
if __name__ == '__main__':
plot_data()
| 3,458 | 37.433333 | 117 | py |
pySDC | pySDC-master/pySDC/playgrounds/EnergyGrids/playground_battery.py | import numpy as np
import dill
from pySDC.helpers.stats_helper import get_sorted
# from pySDC.helpers.visualization_tools import show_residual_across_simulation
from pySDC.implementations.collocations import Collocation
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.Battery import battery
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
# from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.playgrounds.EnergyGrids.log_data_battery import log_data_battery
import pySDC.helpers.plot_helper as plt_helper
def main():
"""
A simple test program to do SDC/PFASST runs for the battery drain model
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = -1e-10
level_params['e_tol'] = 1e-5
level_params['dt'] = 2e-2
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = 5
sweeper_params['QI'] = 'LU' # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'spread'
# initialize problem parameters
problem_params = dict()
problem_params['Vs'] = 5.0
problem_params['Rs'] = 0.5
problem_params['C'] = 1
problem_params['R'] = 1
problem_params['L'] = 1
problem_params['alpha'] = 10
problem_params['V_ref'] = 1
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 5
# initialize controller parameters
controller_params = dict()
controller_params['use_adaptivity'] = False
controller_params['use_switch_estimator'] = True
controller_params['logger_level'] = 20
controller_params['hook_class'] = log_data_battery
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = battery # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params
# set time parameters
t0 = 0.0
Tend = 2.4
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# fname = 'data/piline.dat'
fname = 'battery.dat'
f = open(fname, 'wb')
dill.dump(stats, f)
f.close()
def plot_voltages(cwd='./'):
"""
Routine to plot the numerical solution of the model
"""
f = open(cwd + 'battery.dat', 'rb')
stats = dill.load(f)
f.close()
# convert filtered statistics to list of iterations count, sorted by process
cL = get_sorted(stats, type='current L', sortby='time')
vC = get_sorted(stats, type='voltage C', sortby='time')
times = [v[0] for v in cL]
# plt_helper.setup_mpl()
plt_helper.plt.plot(times, [v[1] for v in cL], label='current L')
plt_helper.plt.plot(times, [v[1] for v in vC], label='voltage C')
plt_helper.plt.legend()
plt_helper.plt.show()
def plot_residuals(cwd='./'):
"""
Routine to plot the residuals for one block of each iteration and each process
"""
f = open(cwd + 'battery.dat', 'rb')
stats = dill.load(f)
f.close()
# filter statistics by number of iterations
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
min_iter = 20
max_iter = 0
f = open('battery_out.txt', 'w')
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %1i' % item
f.write(out + '\n')
print(out)
min_iter = min(min_iter, item[1])
max_iter = max(max_iter, item[1])
f.close()
# call helper routine to produce residual plot
fname = 'battery_residuals.png'
show_residual_across_simulation(stats=stats, fname=fname)
if __name__ == "__main__":
main()
plot_voltages()
# plot_residuals()
| 4,433 | 29.791667 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/EnergyGrids/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/EnergyGrids/playground_buck.py | import numpy as np
import dill
from scipy.integrate import solve_ivp
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.collocations import Collocation
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.BuckConverter import buck_converter
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
# from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.playgrounds.EnergyGrids.log_data import log_data
import pySDC.helpers.plot_helper as plt_helper
def main():
"""
A simple test program to do PFASST runs for the heat equation
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-12
level_params['dt'] = 1e-5
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = 5
sweeper_params['QI'] = 'LU' # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# initialize problem parameters
problem_params = dict()
problem_params['duty'] = 0.5
problem_params['fsw'] = 1e3
problem_params['Vs'] = 10.0
problem_params['Rs'] = 0.5
problem_params['C1'] = 1e-3
problem_params['Rp'] = 0.01
problem_params['L1'] = 1e-3
problem_params['C2'] = 1e-3
problem_params['Rl'] = 10
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
controller_params['hook_class'] = log_data
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = buck_converter # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params
# set time parameters
t0 = 0.0
Tend = 2e-2
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# fname = 'data/piline.dat'
fname = 'buck.dat'
f = open(fname, 'wb')
dill.dump(stats, f)
f.close()
def plot_voltages(cwd='./'):
f = open(cwd + 'buck.dat', 'rb')
stats = dill.load(f)
f.close()
# convert filtered statistics to list of iterations count, sorted by process
v1 = get_sorted(stats, type='v1', sortby='time')
v2 = get_sorted(stats, type='v2', sortby='time')
p3 = get_sorted(stats, type='p3', sortby='time')
times = [v[0] for v in v1]
# plt_helper.setup_mpl()
plt_helper.plt.plot(times, [v[1] for v in v1], label='v1')
plt_helper.plt.plot(times, [v[1] for v in v2], label='v2')
plt_helper.plt.plot(times, [v[1] for v in p3], label='p3')
plt_helper.plt.legend()
plt_helper.plt.show()
if __name__ == "__main__":
main()
plot_voltages()
| 3,435 | 30.814815 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/EnergyGrids/log_data.py | from pySDC.core.Hooks import hooks
class log_data(hooks):
def post_step(self, step, level_number):
super(log_data, self).post_step(step, level_number)
# some abbreviations
L = step.levels[level_number]
L.sweep.compute_end_point()
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=0,
sweep=L.status.sweep,
type='v1',
value=L.uend[0],
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=0,
sweep=L.status.sweep,
type='v2',
value=L.uend[1],
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=L.level_index,
iter=0,
sweep=L.status.sweep,
type='p3',
value=L.uend[2],
)
| 989 | 23.146341 | 59 | py |
pySDC | pySDC-master/pySDC/playgrounds/EnergyGrids/battery_adaptivity.py | import numpy as np
import dill
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.collocations import Collocation
from pySDC.projects.PinTSimE.switch_controller_nonMPI import switch_controller_nonMPI
from pySDC.implementations.problem_classes.Battery import battery
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
# from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.playgrounds.EnergyGrids.log_data_battery import log_data_battery
from pySDC.projects.PinTSimE.piline_model import setup_mpl
import pySDC.helpers.plot_helper as plt_helper
def main():
"""
A simple test program to do SDC/PFASST runs for the battery drain model
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = -1e-10
level_params['e_tol'] = 1e-5
level_params['dt'] = 2e-2
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = 5
sweeper_params['QI'] = 'LU' # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'spread'
# initialize problem parameters
problem_params = dict()
problem_params['Vs'] = 5.0
problem_params['Rs'] = 0.5
problem_params['C'] = 1
problem_params['R'] = 1
problem_params['L'] = 1
problem_params['alpha'] = 3 # 10
problem_params['V_ref'] = 1
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 5
# initialize controller parameters
controller_params = dict()
controller_params['use_adaptivity'] = True
controller_params['use_switch_estimator'] = True
controller_params['logger_level'] = 20
controller_params['hook_class'] = log_data_battery
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = battery # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params
# set time parameters
t0 = 0.0
Tend = 4
# instantiate controller
controller = switch_controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# fname = 'data/piline.dat'
fname = 'battery.dat'
f = open(fname, 'wb')
dill.dump(stats, f)
f.close()
def plot_voltages(cwd='./'):
"""
Routine to plot the numerical solution of the model
"""
f = open(cwd + 'battery.dat', 'rb')
stats = dill.load(f)
f.close()
# convert filtered statistics to list of iterations count, sorted by process
cL = get_sorted(stats, type='current L', sortby='time', recomputed=False)
vC = get_sorted(stats, type='voltage C', sortby='time', recomputed=False)
times = [v[0] for v in cL]
dt = np.array(get_sorted(stats, type='dt', recomputed=False))
list_gs = get_sorted(stats, type='restart')
setup_mpl()
fig, ax = plt_helper.plt.subplots(1, 1)
ax.plot(times, [v[1] for v in cL], label='$i_L$')
ax.plot(times, [v[1] for v in vC], label='$v_C$')
ax.set_xlabel('Time', fontsize=20)
ax.set_ylabel('Energy', fontsize=20)
for element in list_gs:
if element[1] > 0:
ax.axvline(element[0])
dt_ax = ax.twinx()
dt_ax.plot(dt[:, 0], dt[:, 1], 'ko--', label='dt')
dt_ax.set_ylabel('dt', fontsize=20)
dt_ax.set_yscale('log', base=10)
ax.legend(frameon=False, loc='upper right')
dt_ax.legend(frameon=False, loc='center right')
fig.savefig('battery_adaptivity.png', dpi=300, bbox_inches='tight')
if __name__ == "__main__":
main()
plot_voltages()
| 4,166 | 31.811024 | 116 | py |
pySDC | pySDC-master/pySDC/playgrounds/EnergyGrids/log_data_battery.py | from pySDC.core.Hooks import hooks
class log_data_battery(hooks):
def post_step(self, step, level_number):
super(log_data_battery, self).post_step(step, level_number)
# some abbreviations
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=0,
sweep=L.status.sweep,
type='current L',
value=L.uend[0],
)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=L.level_index,
iter=0,
sweep=L.status.sweep,
type='voltage C',
value=L.uend[1],
)
self.increment_stats(
process=step.status.slot,
time=L.time + L.dt,
level=L.level_index,
iter=0,
sweep=L.status.sweep,
type='restart',
value=1,
initialize=0,
)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=L.level_index,
iter=0,
sweep=L.status.sweep,
type='dt',
value=L.dt,
)
| 1,307 | 24.647059 | 67 | py |
pySDC | pySDC-master/pySDC/playgrounds/EnergyGrids/playground.py | import numpy as np
import dill
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.collocations import Collocation
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.Piline import piline
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
# from pySDC.implementations.sweeper_classes.generic_LU import generic_LU
from pySDC.playgrounds.EnergyGrids.log_data import log_data
import pySDC.helpers.plot_helper as plt_helper
def main():
"""
A simple test program to do PFASST runs for the heat equation
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.25
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'LOBATTO'
sweeper_params['num_nodes'] = 3
# sweeper_params['QI'] = 'LU' # For the IMEX sweeper, the LU-trick can be activated for the implicit part
# initialize problem parameters
problem_params = dict()
problem_params['Vs'] = 100.0
problem_params['Rs'] = 1.0
problem_params['C1'] = 1.0
problem_params['Rpi'] = 0.2
problem_params['C2'] = 1.0
problem_params['Lpi'] = 1.0
problem_params['Rl'] = 5.0
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
controller_params['hook_class'] = log_data
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = piline # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # 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 = 20
# instantiate controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
fname = 'piline.dat'
f = open(fname, 'wb')
dill.dump(stats, f)
f.close()
def plot_voltages(cwd='./'):
f = open(cwd + 'piline.dat', 'rb')
stats = dill.load(f)
f.close()
# convert filtered statistics to list of iterations count, sorted by process
v1 = get_sorted(stats, type='v1', sortby='time')
v2 = get_sorted(stats, type='v2', sortby='time')
p3 = get_sorted(stats, type='p3', sortby='time')
times = [v[0] for v in v1]
# plt_helper.setup_mpl()
plt_helper.plt.plot(times, [v[1] for v in v1], label='v1')
plt_helper.plt.plot(times, [v[1] for v in v2], label='v2')
plt_helper.plt.plot(times, [v[1] for v in p3], label='p3')
plt_helper.plt.legend()
plt_helper.plt.show()
if __name__ == "__main__":
main()
plot_voltages()
| 3,305 | 30.788462 | 110 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/isend.py | from mpi4py import MPI
import numpy as np
import time
def sleep(n):
tmp = np.random.rand(n)
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
comm.Barrier()
t0 = time.perf_counter()
if rank == 0:
sbuf = np.empty(40000000)
sbuf[0] = 0
sbuf[1:4] = np.random.rand(3)
req = comm.Isend(sbuf[:], dest=1, tag=99)
sleep(100000000)
req.wait()
print("[%02d] Original data %s" % (rank, sbuf))
else:
rbuf = np.empty(40000000)
sleep(10000000)
comm.Recv(rbuf[:], source=0, tag=99)
print("[%02d] Received data %s" % (rank, rbuf))
t1 = time.perf_counter()
print(f'Rank: {rank} -- Time: {t1-t0}')
| 632 | 17.617647 | 51 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/dask_test.py | import cupy
import dask.array as da
import time
from dask.distributed import LocalCluster, Client
# generate chunked dask arrays of mamy numpy random arrays
# rs = da.random.RandomState()
# x = rs.normal(10, 1, size=(5000, 5000), chunks=(1000, 1000))
#
# print(f'{x.nbytes / 1e9} GB of data')
#
# t0 = time.perf_counter()
# (x + 1)[::2, ::2].sum().compute(scheduler='single-threaded')
# print(time.perf_counter() - t0)
#
# t0 = time.perf_counter()
# (x + 1)[::2, ::2].sum().compute(scheduler='threads')
# print(time.perf_counter() - t0)
if __name__ == '__main__':
c = LocalCluster(n_workers=2, processes=True, threads_per_worker=24)
print(c)
c = Client()
print(c)
| 684 | 24.37037 | 72 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/rma.py | from mpi4py import MPI
import numpy as np
import time
def sleep(n):
tmp = np.random.rand(n)
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
t0 = time.perf_counter()
if rank == 0:
sbuf = np.empty(40000000)
win = MPI.Win.Create(sbuf, comm=comm)
win.Lock(0, MPI.LOCK_EXCLUSIVE)
sbuf[0] = 0
sbuf[1:4] = np.random.rand(3)
win.Unlock(0)
sleep(100000000)
print("[%02d] Original data %s" % (rank, sbuf))
else:
rbuf = np.empty(40000000)
win = MPI.Win.Create(None, comm=comm)
sleep(1000000)
win.Lock(0, MPI.LOCK_EXCLUSIVE)
win.Get(rbuf, 0)
win.Unlock(0)
print("[%02d] Received data %s" % (rank, rbuf))
t1 = time.perf_counter()
win.Free()
print(f'Rank: {rank} -- Time: {t1-t0}')
| 738 | 18.447368 | 51 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/rma_async.py | from mpi4py import MPI
import numpy as np
import time
def sleep(n):
tmp = np.random.rand(n)
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
sbuf = np.empty(4)
win = MPI.Win.Create(sbuf, comm=comm)
else:
rbuf = np.empty(4)
win = MPI.Win.Create(None, comm=comm)
# tmp = np.random.rand(int(10000000/2))
group = win.Get_group()
t0 = time.perf_counter()
if rank == 0:
sleep(10000000)
# tmp = np.random.rand(100000000)
for i in range(3):
if i > 0:
sleep(100000000)
win.Wait()
sbuf[0] = i
sbuf[1:] = np.random.rand(3)
print("[%02d] Original data %s" % (rank, sbuf))
win.Post(group.Incl([1]))
win.Wait()
else:
# tmp = np.random.rand(10000)
# tmp = np.random.rand(10000000)
# tmp = np.random.rand(1)
for i in range(3):
win.Start(group.Excl([1]))
win.Get(rbuf, 0)
win.Complete()
sleep(70000000)
print("[%02d] Received data %s" % (rank, rbuf))
t1 = time.perf_counter()
group.Free()
win.Free()
print(f'Rank: {rank} -- Time: {t1-t0}')
| 1,103 | 19.830189 | 55 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/AllenCahn_contracting_circle_FFT.py | import numpy as np
import sys
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.problem_classes.AllenCahn_2D_FFT import allencahn2d_imex, allencahn2d_imex_stab
# from pySDC.implementations.problem_classes.AllenCahn_2D_parFFT import allencahn2d_imex, allencahn2d_imex_stab
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferMesh_FFT2D import mesh_to_mesh_fft2d
from pySDC.playgrounds.parallel.AllenCahn_parallel_monitor import monitor
import pySDC.helpers.plot_helper as plt_helper
# http://www.personal.psu.edu/qud2/Res/Pre/dz09sisc.pdf
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 1e-02
level_params['nsweeps'] = [3, 1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU']
sweeper_params['QE'] = ['EE']
sweeper_params['initial_guess'] = 'zero'
# This comes as read-in for the problem class
problem_params = dict()
problem_params['nu'] = 2
problem_params['L'] = 1.0
problem_params['nvars'] = [(256, 256), (64, 64)]
problem_params['eps'] = [0.04, 0.16]
problem_params['radius'] = 0.25
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
controller_params['hook_class'] = monitor
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = None # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = None # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fft2d
return description, controller_params
def run_SDC_variant(variant=None):
"""
Routine to run particular SDC variant
Args:
variant (str): string describing the variant
Returns:
timing (float)
niter (float)
"""
# load (incomplete) default parameters
description, controller_params = setup_parameters()
# add stuff based on variant
if variant == 'semi-implicit':
description['problem_class'] = allencahn2d_imex
description['sweeper_class'] = imex_1st_order
elif variant == 'semi-implicit-stab':
description['problem_class'] = allencahn2d_imex_stab
description['sweeper_class'] = imex_1st_order
else:
raise NotImplemented('Wrong variant specified, got %s' % variant)
# setup parameters "in time"
t0 = 0.0
Tend = 0.02
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
# split world communicator to create space-communicators
if len(sys.argv) >= 2:
color = int(world_rank / int(sys.argv[1]))
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
space_size = space_comm.Get_size()
space_rank = space_comm.Get_rank()
# split world communicator to create time-communicators
if len(sys.argv) >= 2:
color = int(world_rank % int(sys.argv[1]))
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
time_size = time_comm.Get_size()
time_rank = time_comm.Get_rank()
print(
"IDs (world, space, time): %i / %i -- %i / %i -- %i / %i"
% (world_rank, world_size, space_rank, space_size, time_rank, time_size)
)
description['problem_params']['comm'] = space_comm
# set level depending on rank
controller_params['logger_level'] = controller_params['logger_level'] if space_rank == 0 else 99
# instantiate controller
controller = controller_MPI(controller_params=controller_params, description=description, comm=time_comm)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# if time_rank == 0:
# plt_helper.plt.imshow(uinit.values)
# plt_helper.savefig(f'uinit_{space_rank}', save_pdf=False, save_pgf=False, save_png=True)
# exit()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# if time_rank == 0:
# plt_helper.plt.imshow(uend.values)
# plt_helper.savefig(f'uend_{space_rank}', save_pdf=False, save_pgf=False, save_png=True)
# exit()
rank = comm.Get_rank()
# filter statistics by variant (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
niters = np.array([item[1] for item in iter_counts])
print(f'Mean number of iterations on rank {rank}: {np.mean(niters):.4f}')
if rank == 0:
timing = get_sorted(stats, type='timing_run', sortby='time')
print(f'---> Time to solution: {timing[0][1]:.4f} sec.')
print()
return stats
def main(cwd=''):
"""
Main driver
Args:
cwd (str): current working directory (need this for testing)
"""
# Loop over variants, exact and inexact solves
results = {}
for variant in ['semi-implicit-stab']:
results[(variant, 'exact')] = run_SDC_variant(variant=variant)
if __name__ == "__main__":
main()
| 6,091 | 30.402062 | 116 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/wait.py | import mpi4py
mpi4py.rc.threaded = True
mpi4py.rc.thread_level = "multiple"
from mpi4py import MPI
import numpy as np
import time
from multiprocessing import Process
def sleep(n):
tmp = np.random.rand(n)
def wait(req):
print('p0', req.Test())
req.Wait()
print('p1', req.Test())
def isend(sbuf, comm):
print('sending')
comm.send(sbuf, dest=1, tag=99)
# print('waiting')
# req.Wait()
print('done')
def main():
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
comm.Barrier()
t0 = time.perf_counter()
if rank == 0:
sbuf = np.empty(4000000)
sbuf[0] = 0
sbuf[1:4] = np.random.rand(3)
p = Process(target=isend, args=(sbuf, comm))
p.start()
sleep(100000000)
p.join()
print("[%02d] Original data %s" % (rank, sbuf))
else:
print('working')
sleep(1000000)
print('receiving')
rbuf = comm.recv(source=0, tag=99)
print('rdone')
print("[%02d] Received data %s" % (rank, rbuf))
t1 = time.perf_counter()
comm.Barrier()
print(f'Rank: {rank} -- Time: {t1-t0}')
if __name__ == '__main__':
main()
| 1,179 | 17.153846 | 55 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/AllenCahn_parallel_monitor.py | import numpy as np
from pySDC.core.Hooks import hooks
class monitor(hooks):
def __init__(self):
"""
Initialization of Allen-Cahn monitoring
"""
super(monitor, self).__init__()
self.init_radius = None
def pre_run(self, step, level_number):
"""
Overwrite standard pre run hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(monitor, self).pre_run(step, level_number)
L = step.levels[0]
c = np.count_nonzero(L.u[0] > 0.0)
radius = np.sqrt(c / np.pi) * L.prob.dx
radius1 = 0
rows, cols = np.where(L.u[0] > 0.0)
for r in rows:
radius1 = max(radius1, abs(L.prob.xvalues[r]))
# rows1 = np.where(L.u[0][int((L.prob.init[0]) / 2), :int((L.prob.init[0]) / 2)] > -0.99)
# rows2 = np.where(L.u[0][int((L.prob.init[0]) / 2), :int((L.prob.init[0]) / 2)] < 0.99)
# interface_width = (rows2[0][-1] - rows1[0][0]) * L.prob.dx / L.prob.params.eps
self.init_radius = L.prob.params.radius
if L.time == 0.0:
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='computed_radius',
value=radius,
)
self.add_to_stats(
process=step.status.slot,
time=L.time,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='exact_radius',
value=self.init_radius,
)
# self.add_to_stats(process=step.status.slot, time=L.time, level=-1, iter=step.status.iter,
# sweep=L.status.sweep, type='interface_width', value=interface_width)
def post_step(self, step, level_number):
"""
Overwrite standard post step hook
Args:
step (pySDC.Step.step): the current step
level_number (int): the current level number
"""
super(monitor, self).post_step(step, level_number)
# some abbreviations
L = step.levels[0]
c = np.count_nonzero(L.uend >= 0.0)
radius = np.sqrt(c / np.pi) * L.prob.dx
exact_radius = np.sqrt(max(self.init_radius**2 - 2.0 * (L.time + L.dt), 0))
# rows1 = np.where(L.uend[int((L.prob.init[0]) / 2), :int((L.prob.init[0]) / 2)] > -0.99)
# rows2 = np.where(L.uend[int((L.prob.init[0]) / 2), :int((L.prob.init[0]) / 2)] < 0.99)
# interface_width = (rows2[0][-1] - rows1[0][0]) * L.prob.dx / L.prob.params.eps
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='computed_radius',
value=radius,
)
self.add_to_stats(
process=step.status.slot,
time=L.time + L.dt,
level=-1,
iter=step.status.iter,
sweep=L.status.sweep,
type='exact_radius',
value=exact_radius,
)
# self.add_to_stats(process=step.status.slot, time=L.time + L.dt, level=-1, iter=step.status.iter,
# sweep=L.status.sweep, type='interface_width', value=interface_width)
| 3,498 | 32.970874 | 106 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/thread.py | from mpi4py import MPI
import numpy as np
import time
import threading
from argparse import ArgumentParser
def sleep(n):
tmp = np.random.rand(n)
def recv(rbuf, source, comm):
comm.Recv(rbuf[:], source=source, tag=99)
# def send(sbuf, comm):
# comm.Send(sbuf[:], dest=1, tag=99)
def isend(sbuf, dest, comm):
return comm.Isend(sbuf[:], dest=dest, tag=99)
# req.Wait()
def wait(req):
req.Wait()
def send_stuff(th, space_rank, time_rank, time_comm):
sbuf = np.empty(40000000)
sbuf[0] = space_rank
sbuf[1:4] = np.random.rand(3)
req = isend(sbuf, time_rank + 1, time_comm)
th[0] = threading.Thread(target=wait, name='Wait-Thread', args=(req,))
th[0].start()
print(f"{time_rank}/{space_rank} - Original data: {sbuf[0:4]}")
def recv_stuff(space_rank, time_rank, time_comm):
rbuf = np.empty(40000000)
sleep(10000000 * time_rank)
recv(rbuf, time_rank - 1, time_comm)
print(f"{time_rank}/{space_rank} - Received data: {rbuf[0:4]}")
def main(nprocs_space=None):
# print(MPI.Query_thread(), MPI.THREAD_MULTIPLE)
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
# split world communicator to create space-communicators
color = int(world_rank / nprocs_space)
space_comm = comm.Split(color=color)
space_rank = space_comm.Get_rank()
# split world communicator to create time-communicators
color = int(world_rank % nprocs_space)
time_comm = comm.Split(color=color)
time_rank = time_comm.Get_rank()
time_size = time_comm.Get_size()
th = [None]
comm.Barrier()
t0 = time.perf_counter()
if time_rank < time_size - 1:
send_stuff(th, space_rank, time_rank, time_comm)
if time_rank > 0:
recv_stuff(space_rank, time_rank, time_comm)
if time_rank < time_size - 1:
sleep(100000000)
th[0].join()
t1 = time.perf_counter()
comm.Barrier()
maxtime = space_comm.allreduce(t1 - t0, MPI.MAX)
if space_rank == 0:
print(f'Time-Rank: {time_rank} -- Time: {maxtime}')
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument("-n", "--nprocs_space", help='Specifies the number of processors in space', type=int)
args = parser.parse_args()
main(nprocs_space=args.nprocs_space)
| 2,358 | 23.071429 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/parallel_iteration.py | import numpy as np
import scipy as sp
from pySDC.helpers.transfer_helper import interpolation_matrix_1d
def get_transfer_matrix_Q(f_nodes, c_nodes):
"""
Helper routine to quickly define transfer matrices between sets of nodes (fully Lagrangian)
Args:
f_nodes: fine nodes
c_nodes: coarse nodes
Returns:
matrix containing the interpolation weights
"""
nnodes_f = len(f_nodes)
nnodes_c = len(c_nodes)
tmat = np.zeros((nnodes_f, nnodes_c))
for i in range(nnodes_f):
xi = f_nodes[i]
for j in range(nnodes_c):
den = 1.0
num = 1.0
for k in range(nnodes_c):
if k == j:
continue
else:
den *= c_nodes[j] - c_nodes[k]
num *= xi - c_nodes[k]
tmat[i, j] = num / den
return tmat
def SDC():
M = 9
Mc = int((M + 1) / 2)
# Mc = 1
dt = 1.0
lamb = -1.0
tol = 1e-10
coll = CollGaussRadau_Right(M, 0, 1)
collc = CollGaussRadau_Right(Mc, 0, 1)
collc2 = CollGaussRadau_Right(1, 0, 1)
Q = coll.Qmat[1:, 1:]
Qc = collc.Qmat[1:, 1:]
Qc2 = collc2.Qmat[1:, 1:]
_, _, U = sp.linalg.lu(Q.T, overwrite_a=False)
Qd = U.T
_, _, U = sp.linalg.lu(Qc.T, overwrite_a=False)
Qdc = U.T
_, _, U = sp.linalg.lu(Qc2.T, overwrite_a=False)
Qdc2 = U.T
# Qd = np.zeros((M, M))
# Qdc = np.zeros((Mc,Mc))
I = get_transfer_matrix_Q(coll.nodes, collc.nodes)
R = get_transfer_matrix_Q(collc.nodes, coll.nodes)
Id = np.eye(M)
#
# print(I)
# print(R)
C = Id - dt * lamb * Q
Cc = np.eye(Mc) - dt * lamb * Qc
Cc2 = np.eye(1) - dt * lamb * Qc2
P = Id - dt * lamb * Qd
Pc = np.eye(Mc) - dt * lamb * Qdc
Pc2 = np.eye(1) - dt * lamb * Qdc2
Pinv = np.linalg.inv(P)
Pcinv = np.linalg.inv(Pc)
u0 = 1.0
u = np.zeros(M, dtype=np.complex128)
u[0] = u0
res = C.dot(u) - np.ones(M) * u0
k = 0
while np.linalg.norm(res, np.inf) > tol and k < 100:
u += Pinv.dot(np.ones(M) * u0 - C.dot(u))
res = C.dot(u) - np.ones(M) * u0
k += 1
print(k, np.linalg.norm(res, np.inf))
print()
I2 = get_transfer_matrix_Q(collc.nodes, collc2.nodes)
R2 = get_transfer_matrix_Q(collc2.nodes, collc.nodes)
K = k
E = np.zeros((K, K))
np.fill_diagonal(E[1:, :], 1)
S = np.kron(np.eye(K), P) - np.kron(E, P - C)
Rfull = np.kron(np.eye(K), R)
Ifull = np.kron(np.eye(K), I)
R2full = np.kron(np.eye(K), R2)
I2full = np.kron(np.eye(K), I2)
# Sc = Rfull.dot(S).dot(Ifull)
Sc = np.kron(np.eye(K), Pc) - np.kron(E, Pc - Cc)
Sc2 = np.kron(np.eye(K), Pc2) - np.kron(E, Pc2 - Cc2)
Scinv = np.linalg.inv(Sc)
Sinv = np.linalg.inv(S)
Sc2inv = np.linalg.inv(Sc2)
Sdiaginv = np.linalg.inv(np.kron(np.eye(K), P))
Scdiaginv = np.linalg.inv(np.kron(np.eye(K), Pc))
Sc2diaginv = np.linalg.inv(np.kron(np.eye(K), Pc2))
u0vec = np.kron(np.ones(K), np.ones(M) * u0)
u = np.zeros(M * K, dtype=np.complex128)
l = 0
res = C.dot(u[-M:]) - np.ones(M) * u0
while np.linalg.norm(res, np.inf) > tol and l < K:
# u += Sainv.dot(u0vec - S.dot(u))
u += Sdiaginv.dot(u0vec - S.dot(u))
uH = Rfull.dot(u)
uHold = uH.copy()
rhsH = Rfull.dot(u0vec) + Sc.dot(uH) - Rfull.dot(S.dot(u))
uH = Scinv.dot(rhsH)
# uH += Scdiaginv.dot(rhsH - Sc.dot(uH))
# uH2 = R2full.dot(uH)
# uH2old = uH2.copy()
# rhsH2 = R2full.dot(rhsH) + Sc2.dot(uH2) - R2full.dot(Sc.dot(uH))
# uH2 = Sc2inv.dot(rhsH2)
# uH += I2full.dot(uH2 - uH2old)
# uH += Scdiaginv.dot(rhsH - Sc.dot(uH))
u += Ifull.dot(uH - uHold)
u += Sdiaginv.dot(u0vec - S.dot(u))
res = C.dot(u[-M:]) - np.ones(M) * u0
l += 1
print(l, np.linalg.norm(res, np.inf))
print()
Ea = E.copy()
Ea[0, -1] = 1e00
Sa = np.kron(np.eye(K), P) - np.kron(Ea, P - C)
Sainv = np.linalg.inv(Sa)
u0vec = np.kron(np.ones(K), np.ones(M) * u0)
u = np.zeros(M * K, dtype=np.complex128)
l = 0
res = C.dot(u[-M:]) - np.ones(M) * u0
while np.linalg.norm(res, np.inf) > tol and l < K:
u += Sainv.dot(u0vec - S.dot(u))
res = C.dot(u[-M:]) - np.ones(M) * u0
l += 1
print(l, np.linalg.norm(res, np.inf))
print()
Da, Va = np.linalg.eig(Ea)
Da = np.diag(Da)
Vainv = np.linalg.inv(Va)
# print(Ea - Va.dot(Da).dot(Vainv))
# exit()
Dafull = np.kron(np.eye(K), P) - np.kron(Da, P - C)
# Dafull = Ifull.dot(np.kron(np.eye(K), Pc) - np.kron(Da, Pc - Cc)).dot(Rfull)
Dafull = np.kron(np.eye(K) - Da, np.eye(M) - P)
DaPfull = np.kron(np.eye(K), P)
Dafullinv = np.linalg.inv(Dafull)
DaPfullinv = np.linalg.inv(DaPfull)
Vafull = np.kron(Va, np.eye(M))
Vafullinv = np.kron(Vainv, np.eye(M))
u0vec = np.kron(np.ones(K), np.ones(M) * u0)
u = np.zeros(M * K, dtype=np.complex128)
l = 0
res = C.dot(u[-M:]) - np.ones(M) * u0
while np.linalg.norm(res, np.inf) > tol and l < K:
rhs = Vafullinv.dot(u0vec - Sa.dot(u))
# x = np.zeros(u.shape, dtype=np.complex128)
# x += DaPfullinv.dot(rhs - Dafull.dot(x))
# x += DaPfullinv.dot(rhs - Dafull.dot(x))
# x += DaPfullinv.dot(rhs - Dafull.dot(x))
# x += DaPfullinv.dot(rhs - Dafull.dot(x))
# u += x
u += Dafullinv.dot(rhs)
u = Vafull.dot(u)
res = C.dot(u[-M:]) - np.ones(M) * u0
l += 1
print(l, np.linalg.norm(res, np.inf))
print()
# T = np.eye(M) - Pinv.dot(C)
# Tc = I.dot(np.eye(Mc) - Pcinv.dot(Cc)).dot(R)
#
# MF = np.eye(K * M) - np.kron(E, T)
# MG = np.eye(K * M) - np.kron(E, Tc)
# MGinv = np.linalg.inv(MG)
#
# tol = np.linalg.norm(res, np.inf)
# u = np.zeros(M * K)
# # u[0] = u0
# u0vec = np.kron(np.ones(K), Pinv.dot(np.ones(M) * u0))
# res = C.dot(u[-M:]) - np.ones(M) * u0
# l = 0
#
# while np.linalg.norm(res, np.inf) > tol and l < K:
#
# u = MGinv.dot(u0vec) + (np.eye(M * K) - MGinv.dot(MF)).dot(u)
# res = C.dot(u[-M:]) - np.ones(M) * u0
# l += 1
# print(l, np.linalg.norm(res, np.inf))
# print()
#
# u = np.zeros(M * K)
# utmpf = np.zeros(M * K)
# utmpc = np.zeros(M * K)
# # u[0] = u0
# u0vec = np.kron(np.ones(K), Pinv.dot(np.ones(M) * u0))
# res = C.dot(u[-M:]) - np.ones(M) * u0
# l = 0
#
# for k in range(1, K):
# utmpc[k * M: (k + 1) * M] = Tc.dot(u[(k-1) * M: k * M])
#
# while np.linalg.norm(res, np.inf) > tol and l < K:
#
# for k in range(1, K):
# utmpf[k * M: (k + 1) * M] = T.dot(u[(k - 1) * M: k * M])
#
# for k in range(1, K):
# u[k * M: (k+1) * M] = Tc.dot(u[(k-1) * M: k * M]) + utmpf[k * M: (k + 1) * M] - utmpc[k * M: (k + 1) * M] + u0vec[(k-1) * M: k * M]
# utmpc[k * M: (k + 1) * M] = Tc.dot(u[(k - 1) * M: k * M])
#
# res = C.dot(u[-M:]) - np.ones(M) * u0
# l += 1
# print(l, np.linalg.norm(res, np.inf))
# print()
#
# u = np.zeros(M * K)
# # u[0] = u0
# u0vec = np.kron(np.ones(K), Pinv.dot(np.ones(M) * u0))
# res = C.dot(u[-M:]) - np.ones(M) * u0
# uold = u.copy()
# l = 0
#
# while np.linalg.norm(res, np.inf) > tol and l < K:
#
# for k in range(1, K):
# u[k * M: (k+1) * M] = T.dot(uold[(k-1) * M: k * M]) + Tc.dot(u[(k-1) * M: k * M] - uold[(k-1) * M: k * M]) + u0vec[(k-1) * M: k * M]
#
# res = C.dot(u[-M:]) - np.ones(M) * u0
# l += 1
# uold = u.copy()
# print(l, np.linalg.norm(res, np.inf))
# print()
def Jacobi():
N = 127
dx = 1.0 / (N + 1)
nu = 1.0
K = 20
stencil = [-1, 2, -1]
A = sp.sparse.diags(stencil, [-1, 0, 1], shape=(N, N), format='csc')
A *= nu / (dx**2)
D = sp.sparse.diags(2.0 * A.diagonal(), 0, shape=(N, N), format='csc')
Dinv = sp.sparse.diags(0.5 * 1.0 / A.diagonal(), 0, shape=(N, N), format='csc')
f = np.ones(N)
f = np.zeros(N)
u = np.sin([int(3.0 * N / 4.0) * np.pi * (i + 1) * dx for i in range(N)])
res = f - A.dot(u)
for k in range(1, K + 1):
u += Dinv.dot(res)
res = f - A.dot(u)
print(k, np.linalg.norm(res, np.inf))
print()
# print(u)
tol = np.linalg.norm(res, np.inf)
Nc = int((N + 1) / 2 - 1)
dxc = 1.0 / (Nc + 1)
Ac = sp.sparse.diags(stencil, [-1, 0, 1], shape=(Nc, Nc), format='csc')
Ac *= nu / (dxc**2)
Dc = sp.sparse.diags(2.0 * Ac.diagonal(), 0, shape=(Nc, Nc), format='csc')
Dcinv = sp.sparse.diags(0.5 * 1.0 / Ac.diagonal(), 0, shape=(Nc, Nc), format='csc')
fine_grid = np.array([(i + 1) * dx for i in range(N)])
coarse_grid = np.array([(i + 1) * dxc for i in range(Nc)])
I = sp.sparse.csc_matrix(interpolation_matrix_1d(fine_grid, coarse_grid, k=6, periodic=False, equidist_nested=True))
R = sp.sparse.csc_matrix(I.T)
T = sp.sparse.csc_matrix(sp.sparse.eye(N) - Dinv.dot(A))
Tc = sp.sparse.csc_matrix(I.dot(sp.sparse.eye(Nc) - Dcinv.dot(Ac)).dot(R))
fvec = np.kron(np.ones(K), Dinv.dot(f))
u = np.zeros(N * K)
u = np.kron(np.ones(K), np.sin([int(3.0 * N / 4.0) * np.pi * (i + 1) * dx for i in range(N)]))
# u[0: N] = np.sin([int(3.0 * N / 4.0) * np.pi * (i + 1) * dx for i in range(N)])
res = f - A.dot(u[0:N])
uold = u.copy()
l = 0
while np.linalg.norm(res, np.inf) > tol and l < K:
for k in range(1, K):
u[k * N : (k + 1) * N] = (
T.dot(uold[(k - 1) * N : k * N])
+ Tc.dot(u[(k - 1) * N : k * N] - uold[(k - 1) * N : k * N])
+ fvec[(k - 1) * N : k * N]
)
res = f - A.dot(u[-N:])
l += 1
uold = u.copy()
print(l, np.linalg.norm(res, np.inf))
print()
# print(u[-N:])
E = np.zeros((K, K))
np.fill_diagonal(E[1:, :], 1)
E = sp.sparse.csc_matrix(E)
Rfull = sp.sparse.kron(sp.sparse.eye(K), R)
Ifull = sp.sparse.kron(sp.sparse.eye(K), I)
S = sp.sparse.kron(sp.sparse.eye(K), D) - sp.sparse.kron(E, D - A)
Sc = Rfull.dot(S).dot(Ifull)
# Sc = sp.sparse.kron(sp.sparse.eye(K), Dcinv) - sp.sparse.kron(E, Dc - Ac)
Scinv = np.linalg.inv(Sc.todense())
# Sinv = np.linalg.inv(S.todense())
Sdiaginv = sp.sparse.kron(sp.sparse.eye(K), Dinv)
Scdiaginv = sp.sparse.kron(sp.sparse.eye(K), Dcinv)
u = np.zeros(N * K)
# u[0: N] = np.sin([int(3.0 * N / 4.0) * np.pi * (i + 1) * dx for i in range(N)])
u = np.kron(np.ones(K), np.sin([int(3.0 * N / 4.0) * np.pi * (i + 1) * dx for i in range(N)]))
l = 0
fvec = np.kron(np.ones(K), f)
res = f - A.dot(u[0:N])
while np.linalg.norm(res, np.inf) > tol and l < K:
# u += Sainv.dot(u0vec - S.dot(u))
u += Sdiaginv.dot(fvec - S.dot(u))
uH = Rfull.dot(u)
uHold = uH.copy()
rhsH = Rfull.dot(fvec) + Sc.dot(uH) - Rfull.dot(S.dot(u))
uH += np.ravel(Scinv.dot(rhsH))
# uH += Scdiaginv.dot(rhsH - Sc.dot(uH))
# uH2 = R2full.dot(uH)
# uH2old = uH2.copy()
# rhsH2 = R2full.dot(rhsH) + Sc2.dot(uH2) - R2full.dot(Sc.dot(uH))
# uH2 = Sc2inv.dot(rhsH2)
# uH += I2full.dot(uH2 - uH2old)
# uH += Scdiaginv.dot(rhsH - Sc.dot(uH))
u += Ifull.dot(uH - uHold)
u += Sdiaginv.dot(fvec - S.dot(u))
res = f - A.dot(u[-N:])
l += 1
print(l, np.linalg.norm(res, np.inf))
# print(u[-N:])
print()
# print(np.linalg.inv(A.todense()).dot(f))
if __name__ == "__main__":
# SDC()
Jacobi()
| 11,807 | 30.572193 | 146 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/playground_parallelization.py | import sys
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.problem_classes.HeatEquation_ND_FD import heatNd_unforced
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.transfer_classes.TransferMesh import mesh_to_mesh
def 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 = dict()
level_params['restol'] = 5e-10
level_params['dt'] = 0.125 / 2.0
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [5]
sweeper_params['QI'] = 'LU'
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 0.1 # diffusion coefficient
problem_params['freq'] = (2, 2) # frequency for the test value
problem_params['bc'] = 'periodic' # periodic BCs
problem_params['nvars'] = [(256, 256), (128, 128)] # number of degrees of freedom for each level
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
space_transfer_params = dict()
space_transfer_params['rorder'] = 2
space_transfer_params['iorder'] = 6
space_transfer_params['periodic'] = True
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heatNd_unforced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = generic_implicit # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh # pass spatial transfer class
description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
# set time parameters
t0 = 0.0
Tend = 1.0
return description, controller_params, t0, Tend
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()
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) >= 3:
fname = sys.argv[2]
else:
fname = 'step_6_B_out.txt'
f = open(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 classic: %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()
| 4,535 | 32.850746 | 104 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/process.py | import mpi4py
mpi4py.rc.threaded = True
mpi4py.rc.thread_level = "funneled"
# mpi4py.rc.profile('vt-hyb', logfile='threads')
from mpi4py import MPI
from threading import Thread
MPI.COMM_WORLD.Barrier()
# Understanding the Python GIL
# David Beazley, http://www.dabeaz.com
# PyCon 2010, Atlanta, Georgia
# http://www.dabeaz.com/python/UnderstandingGIL.pdf
# Consider this trivial CPU-bound function
def countdown(n):
while n > 0:
n -= 1
# Run it once with a lot of work
COUNT = 10000000 # 10 millon
tic = MPI.Wtime()
countdown(COUNT)
toc = MPI.Wtime()
print("sequential: %f seconds" % (toc - tic))
# Now, subdivide the work across two threads
t1 = Thread(target=countdown, args=(COUNT // 2,))
t2 = Thread(target=countdown, args=(COUNT // 2,))
tic = MPI.Wtime()
for t in (t1, t2):
t.start()
for t in (t1, t2):
t.join()
toc = MPI.Wtime()
print("threaded: %f seconds" % (toc - tic))
| 910 | 21.775 | 51 | py |
pySDC | pySDC-master/pySDC/playgrounds/parallel/thread_orig.py | from mpi4py import MPI
import time
import threading
def _send():
global time0, time1
comm.send(data, dest=otherrank, tag=1)
time1 = time.perf_counter() - time0
comm = MPI.COMM_WORLD
reqlist = []
data = ['myid_particles:' + str(comm.rank)] * 10000000
otherrank = 1 if comm.rank == 0 else 0
send_thread = threading.Thread(target=_send)
time0 = time1 = time2 = time3 = 0
time0 = time.perf_counter()
send_thread.start()
if comm.rank == 1:
time.sleep(10)
time2 = time.perf_counter() - time0
a = comm.recv(source=otherrank, tag=1)
time3 = time.perf_counter() - time0
send_thread.join()
print(str(comm.rank) + ': send at t = ' + str(time1))
print(str(comm.rank) + ': recv at t = (' + str(time2) + ',' + str(time3) + ')')
| 738 | 22.09375 | 79 | py |
pySDC | pySDC-master/pySDC/playgrounds/Hackfest 2022/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground_pySDC.py | import sys
import numpy as np
from mpi4py import MPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.problem_classes.HeatEquation_2D_PETSc_forced import heat2d_petsc_forced
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferPETScDMDA import mesh_to_mesh_petsc_dmda
def main():
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
if len(sys.argv) == 2:
color = int(world_rank / int(sys.argv[1]))
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
space_rank = space_comm.Get_rank()
space_size = space_comm.Get_size()
if len(sys.argv) == 2:
color = int(world_rank % int(sys.argv[1]))
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
time_rank = time_comm.Get_rank()
time_size = time_comm.Get_size()
print(
"IDs (world, space, time): %i / %i -- %i / %i -- %i / %i"
% (world_rank, world_size, space_rank, space_size, time_rank, time_size)
)
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-08
level_params['dt'] = 0.125
level_params['nsweeps'] = [1]
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [3]
sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'zero'
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 1.0 # diffusion coefficient
problem_params['freq'] = 2 # frequency for the test value
problem_params['cnvars'] = [(127, 127)] # number of degrees of freedom for each level
problem_params['refine'] = 1 # number of degrees of freedom for each level
problem_params['comm'] = space_comm
problem_params['sol_tol'] = 1e-12
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 50
# initialize space transfer parameters
# space_transfer_params = dict()
# space_transfer_params['rorder'] = 2
# space_transfer_params['iorder'] = 2
# space_transfer_params['periodic'] = True
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 20
# controller_params['hook_class'] = error_output
# fill description dictionary for easy step instantiation
description = dict()
description['problem_class'] = heat2d_petsc_forced # pass problem class
description['problem_params'] = problem_params # pass problem parameters
description['sweeper_class'] = imex_1st_order # pass sweeper (see part B)
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_petsc_dmda # pass spatial transfer class
# description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer
# set time parameters
t0 = 0.0
Tend = 1.0
# instantiate controller
controller = controller_MPI(controller_params=controller_params, description=description, comm=time_comm)
# controller = controller_nonMPI(num_procs=2, controller_params=controller_params, description=description)
# get initial values on finest level
P = controller.S.levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
print(err)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %2i' % item
print(out)
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
timing = get_sorted(stats, type='timing_run', sortby='time')
print(timing)
if __name__ == "__main__":
main()
| 4,894 | 34.215827 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground_fft.py | from petsc4py import PETSc
def main():
n = 4
da = PETSc.DMDA().create([n, n], stencil_width=1)
rank = PETSc.COMM_WORLD.getRank()
x = da.createGlobalVec()
xa = da.getVecArray(x)
(xs, xe), (ys, ye) = da.getRanges()
print(da.getRanges())
for i in range(xs, xe):
for j in range(ys, ye):
xa[i, j] = j * n + i
print('x=', rank, x.getArray(), xs, xe, ys, ye)
A = da.createMatrix()
A.setType(PETSc.Mat.Type.FFTW) # sparse
A.setFromOptions()
# Istart, Iend = A.getOwnershipRange()
# for I in range(Istart, Iend):
# A[I, I] = 1.0
# communicate off-processor values
# and setup internal data structures
# for performing parallel operations
A.assemblyBegin()
A.assemblyEnd()
res = da.createGlobalVec()
A.mult(x, res)
print(rank, res.getArray())
print((res - x).norm())
if __name__ == "__main__":
main()
| 927 | 21.095238 | 53 | py |
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground_comm.py | # Summary
# Creating and using vectors and basic vector operations in PETSc.
#
# Description
# Vectors are a basic mathematical building block.
#
# For a complete list of vector operations, consult the PETSc user manual.
# Also look at the petsc4py/src/PETSc/Vec.pyx file for petsc4py implementation
# details.
import sys
import numpy as np
from mpi4py import MPI
def main():
from petsc4py import PETSc
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
if len(sys.argv) == 2:
color = int(world_rank / int(sys.argv[1]))
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
space_rank = space_comm.Get_rank()
space_size = space_comm.Get_size()
if len(sys.argv) == 2:
color = int(world_rank % int(sys.argv[1]))
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
time_rank = time_comm.Get_rank()
time_size = time_comm.Get_size()
print(
"IDs (world, space, time): %i / %i -- %i / %i -- %i / %i"
% (world_rank, world_size, space_rank, space_size, time_rank, time_size)
)
n = 7
da = PETSc.DMDA().create([n, n], stencil_width=1, comm=space_comm)
x = da.createGlobalVec()
xa = da.getVecArray(x)
(xs, xe), (ys, ye) = da.getRanges()
for i in range(xs, xe):
for j in range(ys, ye):
xa[i, j] = np.sin(2 * np.pi * (i + 1) / (n + 1)) * np.sin(2 * np.pi * (j + 1) / (n + 1))
print('x=', x.getArray())
print('x:', x.getSizes(), da.getRanges())
print()
if time_rank == 0:
print('send', time_rank)
time_comm.send(x.getArray(), dest=1, tag=0)
else:
print('recv', time_rank)
y = da.createGlobalVec()
y.setArray(time_comm.recv(source=0, tag=0))
print(type(y.getArray()))
if __name__ == "__main__":
main()
| 1,939 | 25.216216 | 100 | py |
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground_ts.py | # Solves Heat equation on a periodic domain, using raw VecScatter
import petsc4py
import sys
import time
petsc4py.init(sys.argv)
from petsc4py import PETSc
from mpi4py import MPI
import numpy as np
class Fisher_full(object):
"""
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
"""
def __init__(self, da):
"""
Initialization routine
Args:
da: DMDA object
params: problem parameters
factor: temporal factor (dt*Qd)
dx: grid spacing in x direction
"""
assert da.getDim() == 1
self.da = da
self.mx = self.da.getSizes()[0]
(self.xs, self.xe) = self.da.getRanges()[0]
self.dx = 100 / (self.mx - 1)
print(self.mx, self.dx, self.xs, self.xe)
self.lambda0 = 2.0
self.nu = 1
self.localX = self.da.createLocalVec()
self.row = PETSc.Mat.Stencil()
self.col = PETSc.Mat.Stencil()
self.mat = self.da.createMatrix()
self.mat.setType('aij') # sparse
self.mat.setFromOptions()
self.mat.setPreallocationNNZ((3, 3))
self.mat.setUp()
self.gvec = self.da.createGlobalVec()
def formFunction(self, ts, t, xin, xdot, f):
self.da.globalToLocal(xin, self.localX)
x = self.da.getVecArray(self.localX)
fa = self.da.getVecArray(f)
for i in range(self.xs, self.xe):
if i == 0:
fa[i] = x[i] - 0
elif i == self.mx - 1:
fa[i] = x[i] - 1
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
fa[i] = xdot[i] - (u_xx + self.lambda0**2 * x[i] * (1 - x[i] ** self.nu))
def formJacobian(self, ts, t, xin, xdot, a, A, B):
self.da.globalToLocal(xin, self.localX)
x = self.da.getVecArray(self.localX)
B.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:
B.setValueStencil(self.row, self.row, 1.0)
else:
diag = a - (-2.0 / self.dx**2 + self.lambda0**2 * (1.0 - (self.nu + 1) * x[i] ** self.nu))
for index, value in [
(i - 1, -1.0 / self.dx**2),
(i, diag),
(i + 1, -1.0 / self.dx**2),
]:
self.col.i = index
self.col.field = 0
B.setValueStencil(self.row, self.col, value)
B.assemble()
if A != B:
A.assemble() # matrix-free operator
return PETSc.Mat.Structure.SAME_NONZERO_PATTERN
def evalSolution(self, t, x):
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)
xa = self.da.getVecArray(x)
for i in range(self.xs, self.xe):
xa[i] = (
1
+ (2 ** (self.nu / 2.0) - 1) * np.exp(-self.nu / 2.0 * sig1 * (-50 + (i + 1) * self.dx + 2 * lam1 * t))
) ** (-2.0 / self.nu)
class Fisher_split(object):
"""
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
"""
def __init__(self, da):
"""
Initialization routine
Args:
da: DMDA object
params: problem parameters
factor: temporal factor (dt*Qd)
dx: grid spacing in x direction
"""
assert da.getDim() == 1
self.da = da
self.mx = self.da.getSizes()[0]
(self.xs, self.xe) = self.da.getRanges()[0]
self.dx = 100 / (self.mx - 1)
print(self.mx, self.dx, self.xs, self.xe)
self.lambda0 = 2.0
self.nu = 1
self.localX = self.da.createLocalVec()
self.row = PETSc.Mat.Stencil()
self.col = PETSc.Mat.Stencil()
self.mat = self.da.createMatrix()
self.mat.setType('aij') # sparse
self.mat.setFromOptions()
self.mat.setPreallocationNNZ((3, 3))
self.mat.setUp()
self.gvec = self.da.createGlobalVec()
self.rhs = self.da.createGlobalVec()
def formFunction(self, ts, t, xin, xdot, f):
self.da.globalToLocal(xin, self.localX)
x = self.da.getVecArray(self.localX)
fa = self.da.getVecArray(f)
for i in range(self.xs, self.xe):
if i == 0:
fa[i] = x[i] - 0
elif i == self.mx - 1:
fa[i] = x[i] - 1
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
# fa[i] = xdot[i] - (u_xx + self.lambda0 ** 2 * x[i] * (1 - x[i] ** self.nu))
fa[i] = xdot[i] - u_xx
def formJacobian(self, ts, t, xin, xdot, a, A, B):
self.da.globalToLocal(xin, self.localX)
x = self.da.getVecArray(self.localX)
B.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:
B.setValueStencil(self.row, self.row, 1.0)
else:
# diag = a - (-2.0 / self.dx ** 2 + self.lambda0 ** 2 * (1.0 - (self.nu + 1) * x[i] ** self.nu))
diag = a - (-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),
]:
self.col.i = index
self.col.field = 0
B.setValueStencil(self.row, self.col, value)
B.assemble()
if A != B:
A.assemble() # matrix-free operator
return PETSc.Mat.Structure.SAME_NONZERO_PATTERN
# def formRHS(self, ts, t, x, F):
# # print ('MyODE.rhsfunction()')
# f = self.lambda0 ** 2 * x[:] * (1 - x[:] ** self.nu)
# f.copy(F)
def formRHS(self, ts, t, xin, F):
self.da.globalToLocal(xin, self.localX)
x = self.da.getVecArray(self.localX)
fa = self.da.getVecArray(F)
for i in range(self.xs, self.xe):
if i == 0:
fa[i] = 0
elif i == self.mx - 1:
fa[i] = 1
else:
# fa[i] = xdot[i] - (u_xx + self.lambda0 ** 2 * x[i] * (1 - x[i] ** self.nu))
fa[i] = self.lambda0**2 * x[i] * (1 - x[i] ** self.nu)
def evalSolution(self, t, x):
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)
xa = self.da.getVecArray(x)
for i in range(self.xs, self.xe):
xa[i] = (
1
+ (2 ** (self.nu / 2.0) - 1) * np.exp(-self.nu / 2.0 * sig1 * (-50 + (i + 1) * self.dx + 2 * lam1 * t))
) ** (-2.0 / self.nu)
da = PETSc.DMDA().create([2049], dof=1, stencil_width=1)
OptDB = PETSc.Options()
ode = Fisher_split(da=da)
x = ode.gvec.duplicate()
f = ode.gvec.duplicate()
ts = PETSc.TS().create(comm=MPI.COMM_WORLD)
ts.setType(ts.Type.ARKIMEXARS443) # Rosenbrock-W. ARKIMEX is a nonlinearly implicit alternative.
# ts.setRKType('3bs')
ts.setIFunction(ode.formFunction, ode.gvec)
ts.setIJacobian(ode.formJacobian, ode.mat)
ts.setRHSFunction(ode.formRHS, ode.rhs)
# ts.setMonitor(ode.monitor)
ts.setTime(0.0)
ts.setTimeStep(0.25)
ts.setMaxTime(1.0)
ts.setMaxSteps(100)
ts.setExactFinalTime(PETSc.TS.ExactFinalTime.INTERPOLATE)
ts.setMaxSNESFailures(-1) # allow an unlimited number of failures (step will be rejected and retried)
ts.setMaxStepRejections(-1)
ts.setTolerances(atol=1e-08)
snes = ts.getSNES() # Nonlinear solver
snes.setTolerances(max_it=100) # Stop nonlinear solve after 10 iterations (TS will retry with shorter step)
ksp = snes.getKSP() # Linear solver
ksp.setType(ksp.Type.CG) # Conjugate gradients
pc = ksp.getPC() # Preconditioner
if True: # Configure algebraic multigrid, could use run-time options instead
pc.setType(pc.Type.ILU) # PETSc's native AMG implementation, mostly based on smoothed aggregation
# OptDB['mg_coarse_pc_type'] = 'svd' # more specific multigrid options
# OptDB['mg_levels_pc_type'] = 'sor'
ts.setFromOptions() # Apply run-time options, e.g. -ts_adapt_monitor -ts_type arkimex -snes_converged_reason
ode.evalSolution(0.0, x)
t0 = time.perf_counter()
# pr = cProfile.Profile()
# pr.enable()
ts.solve(x)
# pr.disable()
# s = io.StringIO()
# sortby = 'cumulative'
# ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
# ps.print_stats()
# print(s.getvalue())
print('Time:', time.perf_counter() - t0)
uex = ode.gvec.duplicate()
ode.evalSolution(1.0, uex)
# uex.view()
# x.view()
print((uex - x).norm(PETSc.NormType.NORM_INFINITY))
print(
'steps %d (%d rejected, %d SNES fails), nonlinear its %d, linear its %d'
% (ts.getStepNumber(), ts.getStepRejections(), ts.getSNESFailures(), ts.getSNESIterations(), ts.getKSPIterations())
)
# if OptDB.getBool('plot_history', True) and ode.comm.rank == 0:
# ode.plotHistory()
| 9,370 | 32.952899 | 119 | py |
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground_parallel.py | from petsc4py import PETSc
def main():
n = 4
v = PETSc.Vec()
print(type(v))
v.createMPI(n, comm=PETSc.COMM_WORLD)
print(type(v))
# v.setSizes(n)
# v.assemble()
print(v.getLocalSize())
exit()
da = PETSc.DMDA().create([n, n], stencil_width=1)
rank = PETSc.COMM_WORLD.getRank()
x = da.createGlobalVec()
xa = da.getVecArray(x)
(xs, xe), (ys, ye) = da.getRanges()
print(da.getRanges())
for i in range(xs, xe):
for j in range(ys, ye):
xa[i, j] = j * n + i
print('x=', rank, x.getArray(), xs, xe, ys, ye)
A = da.createMatrix()
A.setType('aij') # sparse
A.setFromOptions()
Istart, Iend = A.getOwnershipRange()
for I in range(Istart, Iend):
A[I, I] = 1.0
# communicate off-processor values
# and setup internal data structures
# for performing parallel operations
A.assemblyBegin()
A.assemblyEnd()
res = da.createGlobalVec()
A.mult(x, res)
print(rank, res.getArray())
print((res - x).norm())
if __name__ == "__main__":
main()
| 1,087 | 19.923077 | 53 | py |
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground_data.py | import numpy as np
from petsc4py import PETSc
def main():
# import petsc4py
n = 4
dx = 1.0 / (n - 1)
dy = dx
comm = PETSc.COMM_WORLD
da = PETSc.DMDA().create([n, n], dof=1, stencil_width=1, comm=comm)
dar = da.refine()
print(dar.getSizes())
exit()
rank = PETSc.COMM_WORLD.getRank()
# comm=
x = da.createGlobalVec()
xa = da.getVecArray(x)
(xs, xe), (ys, ye) = da.getRanges()
print(xs, xe, ys, ye, xa.shape)
for i in range(xs, xe):
for j in range(ys, ye):
xa[i, j, 0] = np.sin(2 * np.pi * (i) * dx) * np.sin(2 * np.pi * (j) * dy)
xa[i, j, 1] = 0.1 * np.sin(2 * np.pi * (i) * dx) * np.sin(2 * np.pi * (j) * dy)
print('x=', rank, x.getArray())
# print('x:', x.getSizes(), da.getRanges())
# print()
y = da.createGlobalVec()
ya = da.getVecArray(y)
(xs, xe), (ys, ye) = da.getRanges()
for i in range(xs, xe):
for j in range(ys, ye):
ya[i, j, 0] = -2 * (2.0 * np.pi) ** 2 * np.sin(2 * np.pi * (i) * dx) * np.sin(2 * np.pi * (j) * dy)
ya[i, j, 1] = -0.2 * (2.0 * np.pi) ** 2 * np.sin(2 * np.pi * (i) * dx) * np.sin(2 * np.pi * (j) * dy)
#
# z = da.createGlobalVec()
# za = da.getVecArray(z)
# (xs, xe), (ys, ye) = da.getRanges()
# for i in range(xs, xe):
# for j in range(ys, ye):
# za[i, j] = 4 * (2.0 * np.pi) ** 4 * np.sin(2 * np.pi * (i + 1) * dx) * np.sin(2 * np.pi * (j + 1) * dy)
# z = y.copy()
# print('z=', z.getArray())
# ya = da.getVecArray(y)
# ya[0,0] = 10.0
# print(y.getArray()[0], z.getArray()[0])
A = da.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 = da.getSizes()
(xs, xe), (ys, ye) = da.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
if i == 0 or j == 0 or i == mx - 1 or j == my - 1:
row.index = (i, j)
row.field = 0
A.setValueStencil(row, row, 1.0)
row.field = 1
A.setValueStencil(row, row, 1.0)
# pass
else:
# u = x[i, j] # center
diag = -2.0 / dx**2 - 2.0 / dy**2
for index, value in [
((i, j - 1), 1.0 / dy**2),
((i - 1, j), 1.0 / dx**2),
((i, j), diag),
((i + 1, j), 1.0 / dx**2),
((i, j + 1), 1.0 / dy**2),
]:
row.index = (i, j)
row.field = 0
col.index = index
col.field = 0
A.setValueStencil(row, col, value)
row.field = 1
col.field = 1
A.setValueStencil(row, col, value)
A.assemble()
A.view()
exit()
Id = da.createMatrix()
Id.setType('aij') # sparse
Id.setFromOptions()
Id.setPreallocationNNZ((5, 5))
Id.setUp()
Id.zeroEntries()
row = PETSc.Mat.Stencil()
col = PETSc.Mat.Stencil()
mx, my = da.getSizes()
(xs, xe), (ys, ye) = da.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
row.index = (i, j)
row.field = 0
col.index = (i, j)
col.field = 0
Id.setValueStencil(row, row, 1.0)
row.field = 1
col.field = 1
Id.setValueStencil(row, col, 1.0)
Id.assemble()
# (xs, xe), (ys, ye) = da.getRanges()
# print(A.getValues(range(n*n), range(n*n)))
res = da.createGlobalVec()
A.mult(x, res)
print('1st turn', rank, res.getArray())
print((res - y).norm(PETSc.NormType.NORM_INFINITY))
ksp = PETSc.KSP().create()
ksp.setOperators(A)
ksp.setType('cg')
pc = ksp.getPC()
pc.setType('mg')
ksp.setFromOptions()
x1 = da.createGlobalVec()
ksp.solve(res, x1)
print((x1 - x).norm(PETSc.NormType.NORM_INFINITY))
x2 = da.createGlobalVec()
Id.mult(x1, x2)
print((x2 - x1).norm(PETSc.NormType.NORM_INFINITY))
# # A.view()
# res1 = da.createNaturalVec()
# A.mult(res, res1)
# # print('2nd turn', rank, res1.getArray())
# da.globalToNatural(res, res1)
# print(res1.getArray())
# print((res1 - y).norm(PETSc.NormType.NORM_INFINITY))
if __name__ == "__main__":
main()
| 4,511 | 28.298701 | 117 | py |
pySDC | pySDC-master/pySDC/playgrounds/PETSc/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground.py | # Summary
# Creating and using vectors and basic vector operations in PETSc.
#
# Description
# Vectors are a basic mathematical building block.
#
# For a complete list of vector operations, consult the PETSc user manual.
# Also look at the petsc4py/src/PETSc/Vec.pyx file for petsc4py implementation
# details.
import sys
import time
from mpi4py import MPI
class Poisson2D(object):
def __init__(self, da):
assert da.getDim() == 2
self.da = da
self.localX = da.createLocalVec()
def formRHS(self, B):
b = self.da.getVecArray(B)
mx, my = self.da.getSizes()
hx, hy = [1.0 / m for m in [mx, my]]
(xs, xe), (ys, ye) = self.da.getRanges()
for j in range(ys, ye):
for i in range(xs, xe):
b[i, j] = 1 * hx * hy
def mult(self, mat, X, Y):
#
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
y = self.da.getVecArray(Y)
#
mx, my = self.da.getSizes()
hx, hy = [1.0 / m for m in [mx, my]]
(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 = u_w = u_n = u_s = 0
if i > 0:
u_w = x[i - 1, j] # west
if i < mx - 1:
u_e = x[i + 1, j] # east
if j > 0:
u_s = x[i, j - 1] # south
if j < my - 1:
u_n = x[i, j + 1] # north
u_xx = (-u_e + 2 * u - u_w) * hy / hx
u_yy = (-u_n + 2 * u - u_s) * hx / hy
y[i, j] = u_xx + u_yy
def main():
from petsc4py import PETSc
# set MPI communicator
comm = MPI.COMM_WORLD
world_rank = comm.Get_rank()
world_size = comm.Get_size()
if len(sys.argv) == 2:
color = int(world_rank / int(sys.argv[1]))
else:
color = int(world_rank / 1)
space_comm = comm.Split(color=color)
space_rank = space_comm.Get_rank()
space_size = space_comm.Get_size()
if len(sys.argv) == 2:
color = int(world_rank % int(sys.argv[1]))
else:
color = int(world_rank / world_size)
time_comm = comm.Split(color=color)
time_rank = time_comm.Get_rank()
time_size = time_comm.Get_size()
print(
"IDs (world, space, time): %i / %i -- %i / %i -- %i / %i"
% (world_rank, world_size, space_rank, space_size, time_rank, time_size)
)
OptDB = PETSc.Options()
n = OptDB.getInt('n', 16)
nx = OptDB.getInt('nx', n)
ny = OptDB.getInt('ny', n)
t0 = time.perf_counter()
da = PETSc.DMDA().create([nx, ny], stencil_width=1, comm=space_comm)
pde = Poisson2D(da)
x = da.createGlobalVec()
b = da.createGlobalVec()
# A = da.createMat('python')
A = PETSc.Mat().createPython([x.getSizes(), b.getSizes()], comm=space_comm)
A.setPythonContext(pde)
A.setUp()
# print(da.comm, space_comm)
ksp = PETSc.KSP().create(comm=space_comm)
ksp.setOperators(A)
ksp.setType('cg')
pc = ksp.getPC()
pc.setType('none')
ksp.setFromOptions()
t1 = time.perf_counter()
pde.formRHS(b)
ksp.solve(b, x)
u = da.createNaturalVec()
da.globalToNatural(x, u)
t2 = time.perf_counter()
n = 8
rank = PETSc.COMM_WORLD.Get_rank()
size = PETSc.COMM_WORLD.Get_size()
print('Hello World! From process {rank} out of {size} process(es).'.format(rank=rank, size=size))
x = PETSc.Vec().createSeq(n) # Faster way to create a sequential vector.
x.setValues(range(n), range(n)) # x = [0 1 ... 9]
x.shift(1) # x = x + 1 (add 1 to all elements in x)
print('Performing various vector operations on x =', x.getArray())
print('Sum of elements of x =', x.sum())
print(t1 - t0, t2 - t1, t2 - t0)
if __name__ == "__main__":
main()
| 3,943 | 25.829932 | 101 | py |
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground_hypre.py | import petsc4py, sys
# args = "-ksp_type cg -pc_type hypre -pc_hypre_type boomeramg -ksp_converged_reason"
# args = "-ksp_type gmres -pc_type gamg -ksp_converged_reason -ksp_monitor"
args = "-ksp_type richardson -pc_type gamg -ksp_converged_reason -ksp_monitor"
petsc4py.init(args)
from petsc4py import PETSc
# grid size and spacing
for grid_sp in [500]:
m, n = grid_sp, grid_sp
hx = 1.0 / (m - 1)
hy = 1.0 / (n - 1)
# create sparse matrix
A = PETSc.Mat()
A.create(PETSc.COMM_WORLD)
A.setSizes([m * n, m * n])
A.setType('aij') # sparse
A.setPreallocationNNZ(5)
# precompute values for setting
# diagonal and non-diagonal entries
diagv = 2.0 / hx**2 + 2.0 / hy**2
offdx = -1.0 / hx**2
offdy = -1.0 / hy**2
# loop over owned block of rows on this
# processor and insert entry values
Istart, Iend = A.getOwnershipRange()
print(Istart, Iend)
for I in range(Istart, Iend):
A[I, I] = diagv
i = I // n # map row number to
j = I - i * n # grid coordinates
if i > 0:
J = I - n
A[I, J] = offdx
if i < m - 1:
J = I + n
A[I, J] = offdx
if j > 0:
J = I - 1
A[I, J] = offdy
if j < n - 1:
J = I + 1
A[I, J] = offdy
# communicate off-processor values
# and setup internal data structures
# for performing parallel operations
A.assemblyBegin()
A.assemblyEnd()
# print(A.isSymmetric())
# create linear solver
ksp = PETSc.KSP()
ksp.create(PETSc.COMM_WORLD)
# obtain sol & rhs vectors
x, b = A.createVecs()
print(type(x))
exit()
x.set(0)
b.set(1)
# and next solve
ksp.setOperators(A)
ksp.setFromOptions()
ksp.solve(b, x)
# x.set(0)
# ksp.solveTranspose(b, x)
| 1,863 | 24.534247 | 85 | py |
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground_matmult.py | import numpy as np
from petsc4py import PETSc
n = 4
dx = 1.0 / (n + 1)
da = PETSc.DMDA().create([n, n], stencil_width=1, comm=PETSc.COMM_WORLD)
# set up vectors
x = da.createNaturalVector()
b = x.duplicate()
y = x.duplicate()
xs, xe = x.getOwnershipRange()
ldim = x.getLocalSize()
for k in range(ldim):
iglobal = k + xs
j = k % n
i = k // n
# set up target
x.setValue(iglobal, np.sin(2 * np.pi * (i + 1) * dx) * np.sin(2 * np.pi * (j + 1) * dx))
# set up exact solution
y.setValue(iglobal, -2 * (2.0 * np.pi) ** 2 * np.sin(2 * np.pi * (i + 1) * dx) * np.sin(2 * np.pi * (j + 1) * dx))
x.assemblyBegin()
x.assemblyEnd()
# set up 2nd order FD matrix, taken from https://bitbucket.org/petsc/petsc4py/src/master/demo/kspsolve/petsc-mat.py
A = da.createMatrix()
A.setType('aij') # sparse
A.setFromOptions()
A.setPreallocationNNZ((5, 5))
A.setUp()
diagv = -2.0 / dx**2 - 2.0 / dx**2
offdx = 1.0 / dx**2
offdy = 1.0 / dx**2
Istart, Iend = A.getOwnershipRange()
for I in range(Istart, Iend):
A.setValue(I, I, diagv)
i = I // n # map row number to
j = I - i * n # grid coordinates
if i > 0:
J = I - n
A.setValues(I, J, offdx)
if i < n - 1:
J = I + n
A.setValues(I, J, offdx)
if j > 0:
J = I - 1
A.setValues(I, J, offdy)
if j < n - 1:
J = I + 1
A.setValues(I, J, offdy)
A.assemblyBegin()
A.assemblyEnd()
A.mult(x, b)
rank = PETSc.COMM_WORLD.getRank()
print(rank, b.getArray())
print((b - y).norm(PETSc.NormType.NORM_INFINITY))
| 1,549 | 23.603175 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/PETSc/playground_operators.py | # Summary
# Creating and using vectors and basic vector operations in PETSc.
#
# Description
# Vectors are a basic mathematical building block.
#
# For a complete list of vector operations, consult the PETSc user manual.
# Also look at the petsc4py/src/PETSc/Vec.pyx file for petsc4py implementation
# details.
import numpy as np
def main():
from petsc4py import PETSc
n_fine = 5
n_coarse = int((n_fine - 1) / 2) + 1
da_fine = PETSc.DMDA().create([n_fine, n_fine], stencil_width=1)
da_coarse = PETSc.DMDA().create([n_coarse, n_coarse], stencil_width=1)
x_fine = da_fine.createGlobalVec()
xa = da_fine.getVecArray(x_fine)
(xs, xe), (ys, ye) = da_fine.getRanges()
nx, ny = da_fine.getSizes()
for i in range(xs, xe):
for j in range(ys, ye):
# xa[i, j] = 1.0
# xa[i, j] = i / nx
xa[i, j] = np.sin(2 * np.pi * i / (nx + 1)) * np.sin(2 * np.pi * j / (ny + 1))
da_coarse.setInterpolationType(PETSc.DMDA.InterpolationType.Q1)
B, vec = da_coarse.createInterpolation(da_fine)
# print(B, vec.getArray())
x_coarse = da_coarse.createGlobalVec()
xa = da_coarse.getVecArray(x_coarse)
(xs, xe), (ys, ye) = da_coarse.getRanges()
nx, ny = da_coarse.getSizes()
for i in range(xs, xe):
for j in range(ys, ye):
xa[i, j] = 1.0
# xa[i, j] = i / nx
xa[i, j] = np.sin(2 * np.pi * i / (nx + 1)) * np.sin(2 * np.pi * j / (ny + 1))
y = da_fine.createGlobalVec()
# x_coarse.pointwiseMult(x_coarse)
# PETSc.Mat.Restrict(B, x_coarse, y)
B.mult(x_coarse, y)
# y.pointwiseMult(vec, y)
# PETSc.VecPointwiseMult()
# print(y.getArray())
# print(x_coarse.getArray())
print((y - x_fine).norm(PETSc.NormType.NORM_INFINITY))
y_coarse = da_coarse.createGlobalVec()
B.multTranspose(x_fine, y_coarse)
y_coarse.pointwiseMult(vec, y_coarse)
print((y_coarse - x_coarse).norm(PETSc.NormType.NORM_INFINITY))
if __name__ == "__main__":
main()
| 2,032 | 29.343284 | 90 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum_diag.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 3
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
# coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
# print(coll.nodes)
# exit()
Q = coll.Qmat[1:, 1:]
var = [x['x' + str(j)] for j in range(1, m + 1)]
# var = [x['x' + str(j) + 'r'] + 1j * x['x' + str(j) + 'i'] for j in range(1, m + 1)]
Qd = np.diag(var)
nsteps = 4
E = np.zeros((nsteps, nsteps))
np.fill_diagonal(E[1:, :], 1)
Ea = E.copy()
Ea[0, -1] = 0.125
# Da, Va = np.linalg.eig(Ea)
# Via = np.linalg.inv(Va)
N = np.zeros((m, m))
N[:, -1] = 1
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
R = np.linalg.inv(np.eye(nsteps * m) - lamdt * np.kron(np.eye(nsteps), Qd) - np.kron(Ea, N)).dot(
lamdt * np.kron(np.eye(nsteps), Q - Qd) + np.kron(E - Ea, N)
)
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
# y = [0.0, 0.0, 0.0, 0.0, 0.0]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = 0.0
params = dict()
# params['x1r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x1i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x6'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x7'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x8'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x9'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_sum_diag',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 12500):
reply = worker.ask_new_solutions(8)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 1000 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 4,467 | 37.852174 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_stiff.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
Q = coll.Qmat[1:, 1:]
var = [x['x' + str(j)] for j in range(1, m + 1)]
obj_val = max(abs(np.linalg.eigvals(np.eye(m) - np.diag(var).dot(Q))))
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = 0.0
params = {}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_stiff',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
for iteration in range(0, 10000):
reply = worker.ask_new_solutions(1)
solutions = {}
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
worker.tell_metrics(solutions)
rho = reply["solutions"][0]["metrics"]["rho"]
curr_min = min(curr_min, rho)
print(iteration, rho, curr_min)
else:
print(reply)
exit()
| 1,865 | 29.590164 | 93 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 3
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
# coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
Q = coll.Qmat[1:, 1:]
var = [x['x' + str(j)] for j in range(1, m + 1)]
# var = [x['x' + str(j) + 'r'] + 1j * x['x' + str(j) + 'i'] for j in range(1, m + 1)]
Qd = np.diag(var)
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
R = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd).dot(Q - Qd)
rhoR = max(abs(np.linalg.eigvals(np.linalg.matrix_power(R, 1))))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
# y = [0.0, 0.0, 0.0, 0.0, 0.0]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = 0.0
params = dict()
# params['x1r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x1i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x6'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x7'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x8'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x9'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_sum',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 12500):
reply = worker.ask_new_solutions(8)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 1000 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 4,093 | 40.353535 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_complex.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
Q = coll.Qmat[1:, 1:]
var = [x['x' + str(j) + 'r'] + 1j * x['x' + str(j) + 'i'] for j in range(1, m + 1)]
invQd = np.diag(var)
R = np.eye(m) - invQd.dot(Q)
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val = rhoR
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = 0.0
params = {}
params['x1r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x4r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x5r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x1i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x4i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x5i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_complex',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 100000):
reply = worker.ask_new_solutions(1)
solutions = {}
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
worker.tell_metrics(solutions)
rho = reply["solutions"][0]["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = reply["solutions"][0]["parameters"]
print(iteration, rho, curr_min, pars)
else:
print(reply)
exit()
| 2,529 | 33.657534 | 94 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum_norm.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 3
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
# coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
# print(coll.nodes)
# exit()
Q = coll.Qmat[1:, 1:]
# var = [x['x'+str(j)] for j in range(1, m + 1)]
var = [x['x' + str(j) + 'r'] + 1j * x['x' + str(j) + 'i'] for j in range(1, m + 1)]
Qd = np.diag(var)
nsteps = 4
E = np.zeros((nsteps, nsteps))
np.fill_diagonal(E[1:, :], 1)
Ea = E.copy()
Ea[0, -1] = 0.125
# Da, Va = np.linalg.eig(Ea)
# Via = np.linalg.inv(Va)
N = np.zeros((m, m))
N[:, -1] = 1
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
if lamdt * np.linalg.norm(Qd, np.inf) != 1.0:
rhoR = abs(lamdt * np.linalg.norm(Q - Qd, np.inf) / (1.0 - lamdt * np.linalg.norm(Qd, np.inf)))
else:
rhoR = 0.0
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
# y = [0.0, 0.0, 0.0, 0.0, 0.0]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = -20.0
params = dict()
params['x1r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x1i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x6'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x7'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x8'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x9'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_sum_norm',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 12500):
reply = worker.ask_new_solutions(8)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 1000 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 4,425 | 37.486957 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum_verlet.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
# coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
# print(coll.nodes)
# exit()
QQ = np.zeros(np.shape(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 isinstance(coll, CollGaussLobatto):
for i in range(coll.num_nodes):
for j in range(coll.num_nodes):
QQ[i + 1, j + 1] = coll.weights[j] * (1.0 - coll.Qmat[j + 1, i + 1] / coll.weights[i])
QQ = np.dot(coll.Qmat, QQ)
# if we do not have Gauss-Lobatto, just multiply Q (will not get a symplectic method, they say)
else:
exit()
QQ = np.dot(coll.Qmat, coll.Qmat)
QQ = QQ[1:, 1:]
var = [x['x' + str(j)] for j in range(1, m)]
# var = [x['x' + str(j) + 'r'] + 1j * x['x' + str(j) + 'i'] for j in range(1, m)]
Qd = np.diag(var, k=-1)
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-3, 2):
# for l in range(-8, 8):
k += 1
lamdt = -(10**i)
R = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd).dot(QQ - Qd)
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
# y = [0.0, 0.0, 0.0, 0.0, 0.0]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = -20.0
params = dict()
# params['x1r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x1i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x6'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x7'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x8'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x9'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_sum_verlet',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 25000):
reply = worker.ask_new_solutions(4)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 100 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 4,685 | 39.396552 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum_diag_complex.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 3
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
# coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
# print(coll.nodes)
# exit()
Q = coll.Qmat[1:, 1:]
var = [x['x' + str(j)] for j in range(1, m + 1)]
# var = [x['x' + str(j) + 'r'] + 1j * x['x' + str(j) + 'i'] for j in range(1, m + 1)]
Qd = np.diag(var)
nsteps = 4
E = np.zeros((nsteps, nsteps))
np.fill_diagonal(E[1:, :], 1)
Ea = E.copy()
# Ea[0, -1] = 0.125
# Ea = np.zeros(E.shape)
# Da, Va = np.linalg.eig(Ea)
# Via = np.linalg.inv(Va)
N = np.zeros((m, m))
N[:, -1] = 1
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
Rf = np.linalg.inv(np.eye(nsteps * m) - lamdt * np.kron(np.eye(nsteps), Qd)).dot(
lamdt * np.kron(np.eye(nsteps), Q - Qd) + np.kron(E, N)
)
Rc = np.linalg.inv(np.eye(nsteps * m) - lamdt * np.kron(np.eye(nsteps), Qd) - np.kron(E, N)).dot(
lamdt * np.kron(np.eye(nsteps), Q - Qd)
)
rhoR = max(abs(np.linalg.eigvals(Rc.dot(Rf))))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
# y = [0.0, 0.0, 0.0, 0.0, 0.0]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = 0.0
params = dict()
# params['x1r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x1i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
# params['x2i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
# params['x3i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
# params['x4i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x6'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x7'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x8'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x9'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_sum_diag_complex',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 25000):
reply = worker.ask_new_solutions(4)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 100 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 4,670 | 38.252101 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum_ml.py | import indiesolver
import numpy as np
import scipy
def evaluate(solution):
x = solution["parameters"]
mf = 3
collf = CollGaussRadau_Right(num_nodes=mf, tleft=0.0, tright=1.0)
# coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
Qf = collf.Qmat[1:, 1:]
Idf = np.eye(mf)
QT = Qf.T
[_, _, U] = scipy.linalg.lu(QT, overwrite_a=True)
Qdf = U.T
mc = int((mf + 1) / 2)
collc = CollGaussRadau_Right(num_nodes=mc, tleft=0.0, tright=1.0)
# coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
Qc = collc.Qmat[1:, 1:]
Idc = np.eye(mc)
QT = Qc.T
[_, _, U] = scipy.linalg.lu(QT, overwrite_a=True)
Qdc = U.T
sum1r = x['x11r'] + x['x12r'] + x['x13r']
sum2r = x['x21r'] + x['x22r'] + x['x23r']
sum1i = x['x11i'] + x['x12i']
sum2i = x['x21i'] + x['x22i']
sum3i = x['x31i'] + x['x32i']
if sum1r == 0.0 or sum2r == 0.0 or sum1i == 0.0 or sum2i == 0.0 or sum3i == 0.0:
solution["metrics"] = {}
solution["metrics"]["rho"] = 99
return solution
Tr = np.array(
[
[x['x11r'] / sum1r, x['x12r'] / sum1r, x['x13r'] / sum1r],
[x['x21r'] / sum2r, x['x22r'] / sum2r, x['x23r'] / sum2r],
]
)
Ti = np.array(
[
[x['x11i'] / sum1i, x['x12i'] / sum1i],
[x['x21i'] / sum2i, x['x22i'] / sum2i],
[x['x31i'] / sum3i, x['x32i'] / sum3i],
]
)
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
C = Idf - lamdt * Qf
Pf = Idf - lamdt * Qdf
Rf = Idf - np.linalg.inv(Pf).dot(C)
Pc = Idc - lamdt * Qdc
Rc = Idf - Ti.dot(np.linalg.inv(Pc)).dot(Tr).dot(C)
R = Rf.dot(Rc)
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
y = [0.0, 0.0, 0.0, 0.0, 0.0]
# y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = -20.0
params = dict()
params['x11r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x12r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x13r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x21r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x22r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x23r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x11i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x12i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x21i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x22i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x31i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x32i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_sum_ml',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 12500):
reply = worker.ask_new_solutions(8)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 1000 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 4,649 | 33.444444 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/clean_pending.py | import indiesolver
params = {}
problem = {'problem_name': 'bla', 'parameters': params, 'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}}}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
problem_names = worker.ask_problems()
for problem_name in problem_names['problems']:
problem = worker.ask_problem_description(problem_name)
problem['problem_name'] = problem_name
worker.set_problem(problem)
pending_solutions = worker.ask_pending_solutions()
print(pending_solutions)
for metric in problem['metrics']:
for solution in pending_solutions['solutions']:
solution['metrics'] = {}
solution['metrics'][metric] = 1e10
worker.tell_metrics(pending_solutions)
| 815 | 34.478261 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_ld_sum.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
Q = coll.Qmat[1:, 1:]
Qd = np.array(
[
[x['x11'], 0.0, 0.0, 0.0, 0.0],
[x['x21'], x['x22'], 0.0, 0.0, 0.0],
[x['x31'], x['x32'], x['x33'], 0.0, 0.0],
[x['x41'], x['x42'], x['x43'], x['x44'], 0.0],
[x['x51'], x['x52'], x['x53'], x['x54'], x['x55']],
]
)
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
R = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd).dot(Q - Qd)
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
# y = [1.0, 1.0, 1.0, 1.0, 1.0]
y = [0.0, 0.0, 0.0, 0.0, 0.0]
ymax = 20.0
ymin = 0.0
params = dict()
params['x11'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x21'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x22'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x31'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x32'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x33'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x41'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x42'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x43'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x44'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x51'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x52'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x53'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x54'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x55'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_ld_sum',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 100000):
reply = worker.ask_new_solutions(1)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
worker.tell_metrics(solutions)
rho = reply["solutions"][0]["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = reply["solutions"][0]["parameters"]
print(iteration, rho, curr_min, pars)
else:
print(reply)
exit()
| 3,458 | 35.797872 | 94 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/indiesolver.py | import json
import socket
import time
class indiesolver:
def initialize(self, url, port, token):
self.url = url
self.port = port
self.token = token
def create_problem(self, problem):
self.problem = problem
request = problem
request["request_type"] = "create_problem"
return self.send(request)
def set_problem(self, problem):
self.problem = problem
def ask_problem_description(self, name):
request = {}
request["problem_name"] = name
request["request_type"] = "ask_problem_description"
return self.send(request)
def ask_new_solutions(self, nsolutions):
request = {}
request["problem_name"] = self.problem["problem_name"]
request["request_type"] = "ask_solutions"
request["request_argument1"] = "new"
request["request_argument2"] = nsolutions
return self.send(request)
def ask_pending_solutions(self):
request = {}
request["problem_name"] = self.problem["problem_name"]
request["request_type"] = "ask_solutions"
request["request_argument1"] = "pending"
return self.send(request)
def ask_problems(self):
request = {}
request["request_type"] = "ask_problems"
return self.send(request)
def tell_metrics(self, metrics):
request = metrics
request["problem_name"] = self.problem["problem_name"]
request["request_type"] = "tell_metrics"
return self.send(request)
def send(self, request):
BUFFER_SIZE = 1024
request["token"] = self.token
message = json.dumps(request) + '\0'
while 1:
try:
# self.skt.send(message) # Python 2.x
self.skt.sendto(message.encode(), (self.url, self.port)) # Python 3.x
message_is_complete = 0
reply = ''
while message_is_complete == 0:
# reply = reply + self.skt.recv(BUFFER_SIZE) # Python 2.x
reply = reply + self.skt.recv(BUFFER_SIZE).decode('utf-8') # Python 3.x
if len(reply) > 0:
if reply[len(reply) - 1] == '\0':
message_is_complete = 1
reply = reply[: len(reply) - 1]
reply = json.loads(reply)
if reply["status"] != "success":
print(reply)
return reply
except Exception as msg:
print(msg)
try:
self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.skt.connect((self.url, self.port))
except Exception as msg:
print(msg)
print('reconnect\t')
time.sleep(2)
def disconnect_socket(self):
try:
self.skt.close()
except:
return
def __exit__(self):
self.disconnect_socket()
| 3,042 | 31.37234 | 92 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum_verlet_ld.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
# coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
# print(coll.nodes)
# exit()
QQ = np.zeros(np.shape(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 isinstance(coll, CollGaussLobatto):
for i in range(coll.num_nodes):
for j in range(coll.num_nodes):
QQ[i + 1, j + 1] = coll.weights[j] * (1.0 - coll.Qmat[j + 1, i + 1] / coll.weights[i])
QQ = np.dot(coll.Qmat, QQ)
# if we do not have Gauss-Lobatto, just multiply Q (will not get a symplectic method, they say)
else:
exit()
QQ = np.dot(coll.Qmat, coll.Qmat)
QQ = QQ[1:, 1:]
Qd = np.array(
[
[0.0, 0.0, 0.0, 0.0, 0.0],
[x['x21'], 0.0, 0.0, 0.0, 0.0],
[x['x31'], x['x32'], 0.0, 0.0, 0.0],
[x['x41'], x['x42'], x['x43'], 0.0, 0.0],
[x['x51'], x['x52'], x['x53'], x['x54'], 0.0],
]
)
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-8, 4):
k += 1
lamdt = -(10**i)
try:
R = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd).dot(QQ - Qd)
except np.linalg.linalg.LinAlgError:
obj_val += 99
continue
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
# y = [0.0, 0.0, 0.0, 0.0, 0.0]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = -20.0
params = dict()
# params['x1r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x1i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x6'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x7'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x8'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x9'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x21'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x31'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x32'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x41'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x42'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x43'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x51'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x52'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x53'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x54'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
problem = {
'problem_name': 'Qdelta_sum_verlet_ld',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 25000):
reply = worker.ask_new_solutions(4)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 100 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 5,833 | 41.583942 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum_double.py | import indiesolver
import numpy as np
import scipy
def evaluate(solution):
x = solution["parameters"]
m = 3
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
# coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
# print(coll.nodes)
# exit()
Q = coll.Qmat[1:, 1:]
var = [x['x' + str(j)] for j in range(1, m + 1)]
# var = [x['x' + str(j) + 'r'] + 1j * x['x' + str(j) + 'i'] for j in range(1, m + 1)]
Qd = np.diag(var)
QT = Q.T
[_, _, U] = scipy.linalg.lu(QT, overwrite_a=True)
Qd_LU = U.T
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
R = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd).dot(Q - Qd)
R_LU = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd_LU).dot(Q - Qd_LU)
rhoR = max(abs(np.linalg.eigvals(R_LU.dot(R))))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
y = [0.0, 0.0, 0.0, 0.0, 0.0]
# y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 10000.0
ymin = 0.0
params = dict()
# params['x1r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x1i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x6'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x7'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x8'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x9'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_sum_double',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 100000):
reply = worker.ask_new_solutions(1)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 1000 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 4,303 | 39.603774 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/playground_advdiff.py | import numpy as np
from pySDC.implementations.controller_classes.allinclusive_multigrid_nonMPI import allinclusive_multigrid_nonMPI
from pySDC.helpers.stats_helper import get_sorted
from pySDC.implementations.problem_classes.AdvectionDiffusionEquation_1D_FFT import advectiondiffusion1d_implicit
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.implementations.transfer_classes.TransferMesh_FFT import mesh_to_mesh_fft
from pySDC.playgrounds.fft.libpfasst_output import libpfasst_output
def main():
"""
A simple test program to do PFASST runs for the heat equation
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.9 / 32
level_params['nsweeps'] = 1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = [5]
sweeper_params['QI'] = ['MIN2'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part
sweeper_params['initial_guess'] = 'spread'
sweeper_params['do_coll_update'] = False
# initialize problem parameters
problem_params = dict()
problem_params['nu'] = 1.0 # diffusion coefficient
problem_params['c'] = 10.0 # advection speed
problem_params['freq'] = -1 # frequency for the test value
problem_params['nvars'] = [256] # number of degrees of freedom for each level
problem_params['L'] = 1.0 # length of the interval [-L/2, L/2]
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 100
# initialize controller parameters
controller_params = dict()
controller_params['logger_level'] = 30
controller_params['hook_class'] = libpfasst_output
controller_params['predict'] = False
# fill description dictionary for easy step instantiation
description = dict()
# description['problem_class'] = advectiondiffusion1d_imex # pass problem class
description['problem_class'] = advectiondiffusion1d_implicit # pass problem class
description['problem_params'] = problem_params # pass problem parameters
# description['sweeper_class'] = imex_1st_order # pass sweeper
description['sweeper_class'] = generic_implicit # pass sweeper
description['sweeper_params'] = sweeper_params # pass sweeper parameters
description['level_params'] = level_params # pass level parameters
description['step_params'] = step_params # pass step parameters
description['space_transfer_class'] = mesh_to_mesh_fft # pass spatial transfer class
description['space_transfer_params'] = dict() # pass paramters for spatial transfer
# set time parameters
t0 = 0.0
Tend = level_params['dt']
num_proc = 1
# instantiate controller
controller = allinclusive_multigrid_nonMPI(
num_procs=num_proc, controller_params=controller_params, description=description
)
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# print(controller.MS[0].levels[0].sweep.coll.Qmat)
# print(controller.MS[0].levels[0].sweep.QI)
# exit()
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
# compute exact solution and compare
uex = P.u_exact(Tend)
err = abs(uex - uend)
# filter statistics by type (number of iterations)
iter_counts = get_sorted(stats, type='niter', sortby='time')
# compute and print statistics
for item in iter_counts:
out = 'Number of iterations for time %4.2f: %2i' % item
print(out)
niters = np.array([item[1] for item in iter_counts])
out = ' Mean number of iterations: %4.2f' % np.mean(niters)
print(out)
out = ' Range of values for number of iterations: %2i ' % np.ptp(niters)
print(out)
out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters)))
print(out)
out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters)))
print(out)
print('Error: %8.4e' % err)
if __name__ == "__main__":
main()
| 4,239 | 37.545455 | 118 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_stiff_norm.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
Q = coll.Qmat[1:, 1:]
var = [x['x' + str(j)] for j in range(1, m + 1)]
obj_val = np.linalg.norm(np.eye(m) - np.diag(var).dot(Q), 2)
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = 0.0
params = {}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_stiff_norm',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
for iteration in range(0, 10000):
reply = worker.ask_new_solutions(1)
solutions = {}
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
worker.tell_metrics(solutions)
rho = reply["solutions"][0]["metrics"]["rho"]
curr_min = min(curr_min, rho)
print(iteration, rho, curr_min)
else:
print(reply)
exit()
| 1,860 | 29.508197 | 93 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum_ml_2.py | import indiesolver
import numpy as np
import scipy
def evaluate(solution):
x = solution["parameters"]
mf = 3
collf = CollGaussRadau_Right(num_nodes=mf, tleft=0.0, tright=1.0)
# coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
Qf = collf.Qmat[1:, 1:]
Idf = np.eye(mf)
QT = Qf.T
[_, _, U] = scipy.linalg.lu(QT, overwrite_a=True)
Qdf = U.T
mc = int((mf + 1) / 2)
collc = CollGaussRadau_Right(num_nodes=mc, tleft=0.0, tright=1.0)
# coll = CollGaussLobatto(num_nodes=m, tleft=0.0, tright=1.0)
# coll = EquidistantNoLeft(num_nodes=m, tleft=0.0, tright=1.0)
Qc = collc.Qmat[1:, 1:]
Idc = np.eye(mc)
QT = Qc.T
[_, _, U] = scipy.linalg.lu(QT, overwrite_a=True)
Qdc = U.T
sum1r = x['x11r'] + x['x12r'] + x['x13r']
sum2r = x['x21r'] + x['x22r'] + x['x23r']
sum1i = x['x11i'] + x['x12i']
sum2i = x['x21i'] + x['x22i']
sum3i = x['x31i'] + x['x32i']
if sum1r == 0.0 or sum2r == 0.0 or sum1i == 0.0 or sum2i == 0.0 or sum3i == 0.0:
solution["metrics"] = {}
solution["metrics"]["rho"] = 99
return solution
Tr = np.array(
[
[x['x11r'] / sum1r, x['x12r'] / sum1r, x['x13r'] / sum1r],
[x['x21r'] / sum2r, x['x22r'] / sum2r, x['x23r'] / sum2r],
]
)
Ti = np.array(
[
[x['x11i'] / sum1i, x['x12i'] / sum1i],
[x['x21i'] / sum2i, x['x22i'] / sum2i],
[x['x31i'] / sum3i, x['x32i'] / sum3i],
]
)
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
C = Idf - lamdt * Qf
Pf = Idf - lamdt * Qdf
Rf = Idf - np.linalg.inv(Pf).dot(C)
Pc = Idc - lamdt * Qdc
Rc = Idf - Ti.dot(np.linalg.inv(Pc)).dot(Tr).dot(C)
R = Rf.dot(Rc)
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
y = [0.0, 0.0, 0.0, 0.0, 0.0]
# y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = -20.0
params = dict()
params['x11r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x12r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x13r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x21r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x22r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x23r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x11i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x12i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x21i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x22i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x31i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x32i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_sum_ml',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 12500):
reply = worker.ask_new_solutions(8)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 1000 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 4,649 | 33.444444 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_ud_sum_diag.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
Q = coll.Qmat[1:, 1:]
Qd = np.array(
[
[x['x11'], x['x12'], x['x13'], x['x14'], x['x15']],
[0.0, x['x22'], x['x23'], x['x24'], x['x25']],
[0.0, 0.0, x['x33'], x['x34'], x['x35']],
[0.0, 0.0, 0.0, x['x44'], x['x45']],
[0.0, 0.0, 0.0, 0.0, x['x55']],
]
)
nsteps = 8
E = np.zeros((nsteps, nsteps))
np.fill_diagonal(E[1:, :], 1)
Ea = E.copy()
Ea[0, -1] = 0.001
# Da, Va = np.linalg.eig(Ea)
# Via = np.linalg.inv(Va)
N = np.zeros((m, m))
N[:, -1] = 1
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
R = np.linalg.inv(np.eye(nsteps * m) - lamdt * np.kron(np.eye(nsteps), Qd) - np.kron(Ea, N)).dot(
lamdt * np.kron(np.eye(nsteps), Q - Qd) + np.kron(E - Ea, N)
)
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
# y = [1.0, 1.0, 1.0, 1.0, 1.0]
y = [0.0, 0.0, 0.0, 0.0, 0.0]
ymax = 20.0
ymin = -20.0
params = dict()
params['x11'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x12'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x13'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x14'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x15'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x22'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x23'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x24'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x25'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x33'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x34'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x35'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x44'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x45'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x55'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_ud_sum_diag',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 1):
reply = worker.ask_new_solutions(1)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 1000 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 3,917 | 34.618182 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Mixed1.py | import indiesolver
def evaluate(solution):
x = solution["parameters"]
obj_val = 0
if x['x1'] == "A":
obj_val = 0.2 + pow(x['x2'] - 0.3456789, 2.0)
if x['x1'] == "B":
obj_val = 0.1 + pow(x['x2'] - 0.3456789, 2.0) + pow(x['x3'] - 0.3456789, 2.0)
if x['x1'] == "C":
obj_val = pow(x['x2'] - 0.456789, 2.0) + pow(x['x3'] - x['x2'] - 0.234567, 2.0)
obj_val = obj_val + pow(x['x4'] - 7, 2.0)
solution["metrics"] = {}
solution["metrics"]["obj1"] = obj_val
return solution
params = {}
params['x1'] = {'type': 'categorical', 'space': 'decision', 'domain': ["A", "B", "C"], 'init': 'B'}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': 0.0, 'max': 1.0, 'init': 0.5}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': 0.0, 'max': 1.0, 'init': 0.5}
params['x4'] = {'type': 'integer', 'space': 'decision', 'min': 1, 'max': 10, 'step': 1, 'init': 5}
problem = {
'problem_name': 'Mixed search space',
'parameters': params,
'metrics': {'obj1': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
# problem = worker.ask_problem_description('Mixed search space')
# worker.set_problem(problem)
for iteration in range(0, 100):
reply = worker.ask_new_solutions(1)
solutions = {}
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
worker.tell_metrics(solutions)
print(reply)
else:
print(reply)
exit()
| 1,738 | 30.618182 | 99 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_sum_expl.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
Q = coll.Qmat[1:, 1:]
var = [x['x' + str(j)] for j in range(1, m)]
# var = [x['x' + str(j) + 'r'] + 1j * x['x' + str(j) + 'i'] for j in range(1, m + 1)]
Qd = np.zeros((m, m))
Qd[1, 0] = var[0]
Qd[2, 1] = var[1]
Qd[3, 2] = var[2]
Qd[4, 3] = var[3]
# THIS WORKS REALLY WELL! No need to take imaginary parts in x, though (found minimum has zero imaginary parts)
k = 0
obj_val = 0.0
for i in range(-8, 1):
for l in range(-8, 1):
k += 1
lamdt = -(10**i) + 1j * 10**l
R = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd).dot(Q - Qd)
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
y = [0.0, 0.0, 0.0, 0.0]
# y = [1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = 0.0
params = dict()
# params['x1r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5r'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
# params['x1i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
# params['x2i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
# params['x3i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
# params['x4i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
# params['x5i'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
problem = {
'problem_name': 'Qdelta_sum_expl',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 100000):
reply = worker.ask_new_solutions(8)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 3,405 | 35.623656 | 115 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/playground.py | from pySDC.core.Sweeper import sweeper
from matplotlib import pyplot as plt
import scipy.optimize as opt
import numpy as np
import scipy
def rho(x):
global Q, M
return np.linalg.norm(Q - np.diag([x[i] for i in range(M)]), np.inf) / np.amin([abs(x[i]) for i in range(M)])
M = 9
prec_list = ['IE', 'LU', 'MIN', 'EE']
color_list = ['r', 'g', 'b', 'c']
ldt_list = np.arange(-2, 0.1, 0.1)
results = {}
for prec in prec_list:
sw = sweeper({'collocation_class': CollGaussRadau_Right, 'num_nodes': M})
if prec != 'EE':
QDelta = sw.get_Qdelta_implicit(sw.coll, prec)[1:, 1:]
else:
QDelta = sw.get_Qdelta_explicit(sw.coll, prec)[1:, 1:]
QDL = np.tril(QDelta, -1)
QDD = np.diag(np.diag(QDelta))
Q = sw.coll.Qmat[1:, 1:]
A = np.linalg.inv(np.diag(np.random.rand(M)))
B = np.diag(np.random.rand(M))
# a = np.linalg.norm(np.linalg.inv(QDD), np.inf)
# b = np.linalg.norm(QDL, np.inf)
# b = 1 - np.linalg.norm(Q-QDelta, np.inf) * np.linalg.norm(QDL, np.inf)
# print(prec, np.linalg.norm(np.linalg.matrix_power(np.linalg.inv(QDelta).dot(Q-QDelta), 2), np.inf), np.amin(np.diag(QDD)))
# print(prec, np.linalg.norm(np.linalg.inv(QDelta), np.inf), 1/np.linalg.norm(QDelta, np.inf))
print(
prec, np.linalg.norm(np.linalg.matrix_power(A.dot(np.eye(M) - np.linalg.inv(QDelta).dot(Q)).dot(B), 9), np.inf)
)
# print(prec, a * b)
# continue
tmp = np.zeros((1, M))
tmp[0, -1] = 1
H = np.kron(tmp, np.ones((M, 1)))
result_Rnorm = np.zeros(len(ldt_list))
result_Rrho = np.zeros(len(ldt_list))
result_est = np.zeros(len(ldt_list))
for i, ldt in enumerate(ldt_list):
R = np.linalg.matrix_power(ldt * np.linalg.inv(np.eye(M) - ldt * QDelta).dot(Q - QDelta), 1)
result_Rnorm[i] = np.linalg.norm(R, np.infty)
result_Rrho[i] = np.amax(abs(np.linalg.eigvals(R)))
# result_est[i] = abs(ldt) * np.linalg.norm(np.linalg.inv(np.eye(M) - ldt * QDelta), np.inf) * np.linalg.norm(Q - QDelta, np.inf)
# result_est[i] = abs(ldt) * np.linalg.norm(np.linalg.inv(np.eye(M) - ldt * QDD), np.inf) * np.linalg.norm(np.linalg.inv(np.eye(M) - ldt * np.linalg.inv(np.eye(M) - ldt * QDD).dot(QDL)), np.inf) * np.linalg.norm(Q - QDelta, np.inf)
# result_est[i] = abs(ldt) * 1.0 / min(1 - ldt * np.diag(QDelta)) * (1 + 1/ldt) * np.linalg.norm(Q - QDelta, np.inf)
result_est[i] = np.linalg.norm(tmp.dot(np.linalg.inv(np.eye(M) - ldt * QDelta).dot(H)), np.inf)
# result_est[i] = np.linalg.norm(np.linalg.inv(np.eye(M) - ldt * np.linalg.inv(np.eye(M) - ldt * QDD).dot(QDL)), np.inf)
# result_est[i] = abs(ldt) * np.linalg.norm(QDL, np.inf) / min(1 - ldt * np.diag(QDelta))
results[prec] = [result_Rnorm, result_Rrho, result_est]
exit()
fig = plt.figure()
for prec, color in zip(prec_list, color_list):
plt.plot(ldt_list, results[prec][0], label=prec, color=color)
plt.plot(ldt_list, results[prec][2], label=prec, ls='--', color=color)
plt.ylim(0, 2)
plt.legend()
# fig = plt.figure()
#
# for prec in prec_list:
#
#
# plt.ylim(0,2)
# plt.legend()
plt.show()
exit()
| 3,131 | 36.73494 | 239 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_ud_sum.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
Q = coll.Qmat[1:, 1:]
Qd = np.array(
[
[x['x11'], x['x12'], x['x13'], x['x14'], x['x15']],
[0.0, x['x22'], x['x23'], x['x24'], x['x25']],
[0.0, 0.0, x['x33'], x['x34'], x['x35']],
[0.0, 0.0, 0.0, x['x44'], x['x45']],
[0.0, 0.0, 0.0, 0.0, x['x55']],
]
)
k = 0
obj_val = 0.0
for i in range(-8, 8):
for l in range(-8, 8):
k += 1
lamdt = -(10**i) + 1j * 10**l
R = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd).dot(Q - Qd)
rhoR = max(abs(np.linalg.eigvals(R)))
obj_val += rhoR
obj_val /= k
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
# y = [1.0, 1.0, 1.0, 1.0, 1.0]
y = [0.0, 0.0, 0.0, 0.0, 0.0]
ymax = 20.0
ymin = -20.0
params = dict()
params['x11'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x12'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x13'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x14'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x15'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x22'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x23'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x24'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x25'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x33'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x34'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x35'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x44'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x45'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0}
params['x55'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_ud_sum',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
pars = None
for iteration in range(0, 100000):
reply = worker.ask_new_solutions(1)
solutions = dict()
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
rho = solution["metrics"]["rho"]
curr_min = min(curr_min, rho)
if curr_min == rho:
pars = [solution["parameters"][k] for k in solution["parameters"]]
if curr_min == rho or solution["ID"] % 1000 == 0:
print(solution["ID"], curr_min, pars)
worker.tell_metrics(solutions)
else:
print(reply)
exit()
| 3,557 | 36.452632 | 94 | py |
pySDC | pySDC-master/pySDC/playgrounds/optimization/Qdelta_target.py | import indiesolver
import numpy as np
def evaluate(solution):
x = solution["parameters"]
m = 5
lamdt = -100.0
coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0)
Q = coll.Qmat[1:, 1:]
var = [x['x' + str(j)] for j in range(1, m + 1)]
Qd = np.diag(var)
R = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd).dot(Q - Qd)
obj_val = max(abs(np.linalg.eigvals(R)))
solution["metrics"] = {}
solution["metrics"]["rho"] = obj_val
return solution
# y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906]
y = [1.0, 1.0, 1.0, 1.0, 1.0]
ymax = 20.0
ymin = 0.0
params = {}
params['x1'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]}
params['x2'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]}
params['x3'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]}
params['x4'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]}
params['x5'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]}
problem = {
'problem_name': 'Qdelta_target',
'parameters': params,
'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}},
}
worker = indiesolver.indiesolver()
worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed")
reply = worker.create_problem(problem)
if reply["status"] != "success":
print(reply)
exit()
curr_min = 99
for iteration in range(0, 10000):
reply = worker.ask_new_solutions(1)
solutions = {}
solutions["solutions"] = []
if reply["status"] == "success":
for solution in reply["solutions"]:
solutions["solutions"].append(evaluate(solution))
worker.tell_metrics(solutions)
rho = reply["solutions"][0]["metrics"]["rho"]
curr_min = min(curr_min, rho)
print(iteration, rho, curr_min)
else:
print(reply)
exit()
| 1,945 | 28.484848 | 93 | py |
pySDC | pySDC-master/pySDC/playgrounds/datatypes/base.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 24 17:58:37 2023
@author: cpf5546
"""
# -----------------------------------------------------------------------------
# Base core implementation
# -----------------------------------------------------------------------------
try:
from mpi4py import MPI
except ImportError:
MPI = None
class DataType(object):
"""Base datatype class for solution"""
# Methods used for time communications
def isend(self, dest=None, tag=None, comm=None):
return comm.Issend(self.values, dest=dest, tag=tag)
def irecv(self, source=None, tag=None, comm=None):
return comm.Irecv(self.values, source=source, tag=tag)
def bcast(self, root=None, comm=None):
comm.Bcast(self.values, root=root)
return self
@property
def values(self):
# Must be redefined in children class
raise NotImplementedError()
@values.setter
def values(self, values):
# Must be redefined in children class
raise NotImplementedError()
@property
def clone(self, values=None, copy=True):
# Must be redefined in children class
raise NotImplementedError()
class DataTypeF(object):
"""Base datatype class for f(u,t) evaluations"""
def __new__(cls, dataType, parts=()):
if len(parts) == 0:
return dataType.clone()
else:
obj = super().__new__(cls)
for name in parts:
super().__setattr__(obj, name, dataType.clone())
super().__setattr__(obj, '_parts', set(parts))
obj._dataType = dataType
obj.parts = tuple(obj.__getattribute__(name) for name in obj._parts)
return obj
@property
def partNames(self):
return self._parts
def __setattr__(self, name, value):
if name in self._parts:
raise ValueError(f'{name} is read-only')
super().__setattr__(name, value)
def __repr__(self):
return '{' + ',\n '.join(
f'{c}: {getattr(self, c).__repr__()}' for c in self._parts) + '}'
def toDataType(self):
parts = self.parts
out = self._dataType.clone(values=parts[0].values)
for c in parts[1:]:
out.values += c.values
return out
def __add__(self, other):
if type(other) == DataTypeF:
raise ValueError()
out = self.toDataType()
out += other
return out
def __mul__(self, other):
if type(other) == DataTypeF:
raise ValueError()
out = self.toDataType()
out *= other
return out
def __neg__(self):
out = self.toDataType()
out *= -1
return out
def __sub__(self, other):
if type(other) == DataTypeF:
raise ValueError()
out = self.toDataType()
out -= other
return out
def __radd__(self, other):
return self.__add__(other)
def __rmul__(self, other):
return self.__mul__(other)
| 3,050 | 26 | 80 | py |
pySDC | pySDC-master/pySDC/playgrounds/datatypes/check_consistency.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 24 18:23:16 2023
@author: cpf5546
"""
import numpy as np
from scipy.optimize import newton_krylov
from scipy.integrate import solve_ivp
from pySDC.playgrounds.datatypes.base import DataTypeF
from pySDC.playgrounds.datatypes.implementations import Mesh
# -> data initialization
init = {'shape': (2, 3), 'dtype': float}
u0 = Mesh(**init)
u0.values = [1.0, 0.5, 0.1]
# -> basic check for type preservation
assert type(0.1*u0) == type(u0)
assert type(u0 + 0.1*u0) == type(u0)
assert type(u0[1:]) == type(u0)
assert type(np.exp(u0)) == type(u0)
assert type(u0[None, ...]) == type(u0)
assert type(np.arange(4).reshape((2,2)) @ u0) == type(u0)
# -> RHS evaluation
def evalF(u, t):
fEval = DataTypeF(u, parts=('impl', 'expl'))
fEval.impl.values = -2*u + t**2
fEval.expl.values = 1*u - t
return fEval
# -> default mass matrix application (must return a DataType instance !)
def applyMassMatrix(u):
return u # return 1*u to check DAE limitation in uExact
# -> method for one-step implicit solve : solve (M(u) - factor*f(u,t)) = b
def solveSystem(b, factor, uGuess, t):
def fun(u):
u = u0.clone(values=u, copy=False)
return applyMassMatrix(u) - factor*evalF(u, t) - b
# Note : can probably add specific default parameters for the newton_krylov solver
sol = newton_krylov(fun, uGuess)
return uGuess.clone(values=sol, copy=False)
# -> method for ODE solve
def uExact(t, uInit=None, tInit=0.0):
uMass = applyMassMatrix(u0)
if id(uMass) != id(u0):
raise ValueError('Generic solver for DAE not implemented yet ...')
uInit = u0 if uInit is None else uInit
tol = 100 * np.finfo(float).eps
def fun(t, u):
u = u0.clone(values=u, copy=False)
return np.ravel(evalF(u, t).toDataType())
sol = solve_ivp(fun, (tInit, t), np.ravel(uInit), t_eval=(t,), rtol=tol, atol=tol)
return u0.clone(values=sol.y, copy=False)
# -> base method to integrate
def integrate(Q, nodes, dt, uNodes):
out = []
# integrate RHS over all collocation nodes
for m in range(len(nodes)):
# new instance of DataType, initialize values with 0
out.append(u0.clone(values=0.0))
for j in range(len(nodes)):
out[-1] += dt * Q[m, j] * evalF(uNodes[j], nodes[j])
return out
dt = 0.2
uTh = np.exp(-dt)*(u0-3) + dt**2 - 3*dt + 3
uBE = solveSystem(u0, dt, u0, dt)
uIVP = uExact(dt)
for v in ['uTh', 'uBE', 'uIVP']:
print(f'{v}:\n{eval(v).__repr__()}')
assert np.allclose(uTh, uIVP)
M = 5
nodes = np.linspace(0, 1, M)
Q = np.ones((M, M))/M
uNodes = [u0.clone(u0.values) for _ in range(M)]
out = integrate(Q, nodes, dt, uNodes)
for u in out:
assert type(u) == Mesh
| 2,755 | 27.412371 | 86 | py |
pySDC | pySDC-master/pySDC/playgrounds/datatypes/check_performance.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 23 18:16:35 2023
@author: cpf5546
"""
import numpy as np
from time import process_time
import matplotlib.pyplot as plt
# -----------------------------------------------------------------------------
# Some performance tests
# -----------------------------------------------------------------------------
from pySDC.playgrounds.datatypes.base import DataTypeF
from pySDC.playgrounds.datatypes.implementations import Mesh
from pySDC.implementations.datatype_classes.mesh import imex_mesh, mesh
# -> RHS evaluation functions
def evalF_new(u, t):
fEval = DataTypeF(u)
fEval.values = -2*u + t**2
return fEval
def evalF_ref(u, t):
fEval = mesh(((u.size,), None, np.dtype('float64')))
fEval[:] = -2*u + t**2
return fEval
def evalF_new_IMEX(u, t):
fEval = DataTypeF(u, parts=('impl', 'expl'))
fEval.impl.values = -2*u + t**2
fEval.expl.values = 1*u - t
return fEval
def evalF_ref_IMEX(u, t):
fEval = imex_mesh(((u.size,), None, np.dtype('float64')))
fEval.expl[:] = -2*u + t**2
fEval.expl[:] = 1*u - t
return fEval
vecN = np.array([100, 500, 1000, 5000, 10000, 50000, 100000, 1000000, 2000000])
nRuns = 10*max(vecN)//vecN
res = np.zeros((8, len(vecN)))
for i, (n, nRun) in enumerate(zip(vecN, nRuns)):
uNew = Mesh(shape=(n,), dtype=np.dtype('float64'))
uNew.values = 1.0
uRef = mesh(((n,), None, np.dtype('float64')))
uRef[:] = 1.0
for _ in range(nRun):
tBeg = process_time()
fNew = evalF_new(uNew, 0.1)
tMid = process_time()
uRes = uNew + 0.1*fNew
tEnd = process_time()
res[0, i] += tEnd-tBeg
res[1, i] += tEnd-tMid
tBeg = process_time()
fNew_IMEX = evalF_new_IMEX(uNew, 0.1)
tMid = process_time()
uRes = uNew + 0.1*fNew
tEnd = process_time()
res[2, i] += tEnd-tBeg
res[3, i] += tEnd-tMid
tBeg = process_time()
fRef = evalF_ref(uRef, 0.1)
tMid = process_time()
uRes = uRef + 0.1*fRef
tEnd = process_time()
res[4, i] += tEnd-tBeg
res[5, i] += tEnd-tMid
tBeg = process_time()
fRef_IMEX = evalF_ref_IMEX(uRef, 0.1)
tMid = process_time()
uRes = uRef + 0.1*(fRef_IMEX.impl + fRef_IMEX.expl)
tEnd = process_time()
res[6, i] += tEnd-tBeg
res[7, i] += tEnd-tMid
res /= nRuns
p = plt.loglog(vecN, res[0], label='u + dt*f(u,t)')
plt.loglog(vecN, res[4], '--', c=p[0].get_color())
p = plt.loglog(vecN, res[1], label='u + dt*f')
plt.loglog(vecN, res[5], '--', c=p[0].get_color())
p = plt.loglog(vecN, res[2], label='u + dt*f(u,t) (IMEX)')
plt.loglog(vecN, res[6], '--', c=p[0].get_color())
p = plt.loglog(vecN, res[3], label='u + dt*f (IMEX)')
plt.loglog(vecN, res[7], '--', c=p[0].get_color())
plt.legend()
plt.grid()
plt.xlabel('Vector size')
plt.ylabel('Computation time')
plt.tight_layout()
plt.show()
| 2,977 | 26.831776 | 79 | py |
pySDC | pySDC-master/pySDC/playgrounds/datatypes/implementations.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 24 17:59:56 2023
@author: cpf5546
"""
from pySDC.playgrounds.datatypes.base import DataType
import numpy as np
from petsc4py import PETSc
try:
from mpi4py import MPI
except ImportError:
MPI = None
# -----------------------------------------------------------------------------
# Specific implementations (in pySDC/implementations)
# -----------------------------------------------------------------------------
class Mesh(DataType, np.ndarray):
# Note : priority to methods from DataType class
# Space communicator
_comm = None if MPI is None else MPI.COMM_WORLD
# Mandatory redefinitions
@property
def values(self):
return self[:] # maybe 'self' alone is sufficient ...
@values.setter
def values(self, values):
np.copyto(self, values)
def clone(self, values=None, copy=True):
if values is None:
return Mesh(self.shape, self.dtype)
if not copy:
return np.asarray(values).view(Mesh).reshape(self.shape)
out = Mesh(self.shape, self.dtype)
out.values = values
return out
# Additional redefinitions
def __abs__(self):
local_absval = float(np.amax(np.ndarray.__abs__(self)))
if (self._comm is not None) and (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
return float(global_absval)
class PETScMesh(DataType, PETSc.Vec):
# Note : priority to methods from DataType class
# Mandatory redefinitions
@property
def values(self):
return self.getArray()
@values.setter
def values(self, values):
self.setArray(values)
def clone(self, values=None, copy=True):
# TODO : implementation
if values is None:
return PETScMesh()
if not copy:
pass
return self.copy()
# Additional redefinitions
def __abs__(self):
return self.norm(3)
class Particles(Mesh):
# TODO : understand what p and q are in the original implementation
def __new__(cls, nParticles):
# Note : maybe shape=(2, nParticles, 3) can also be considered ...
return super().__new__(cls, shape=(2, 3, nParticles), dtype=float)
@property
def nParticles(self):
return self.shape[2]
@property
def position(self):
return self[0]
@position.setter
def position(self, values):
np.copyto(self[0], values)
@property
def velocity(self):
return self[1]
@velocity.setter
def velocity(self, values):
np.copyto(self[1], values)
| 2,793 | 25.358491 | 102 | py |
pySDC | pySDC-master/pySDC/playgrounds/datatypes/__init__.py | # | 1 | 1 | 1 | py |
pySDC | pySDC-master/pySDC/playgrounds/ODEs/trajectory_HookClass.py | import matplotlib.pyplot as plt
# import progressbar
from pySDC.core.Hooks import hooks
class trajectories(hooks):
def __init__(self):
"""
Initialization of particles output
"""
super(trajectories, self).__init__()
fig = plt.figure()
self.ax = fig.add_subplot(111)
self.sframe = None
# self.bar_run = None
def pre_run(self, step, level_number):
"""
Overwrite default routine called before time-loop starts
Args:
step: the current step
level_number: the current level number
"""
super(trajectories, self).pre_run(step, level_number)
# some abbreviations
L = step.levels[level_number]
# if hasattr(L.prob.params, 'Tend'):
# self.bar_run = progressbar.ProgressBar(max_value=L.prob.params.Tend)
# else:
# self.bar_run = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
def post_step(self, step, level_number):
"""
Default routine called after each iteration
Args:
step: the current step
level_number: the current level number
"""
super(trajectories, self).post_step(step, level_number)
# some abbreviations
L = step.levels[level_number]
# self.bar_run.update(L.time)
L.sweep.compute_end_point()
# oldcol = self.sframe
self.sframe = self.ax.scatter(L.uend[0], L.uend[1])
# Remove old line collection before drawing
# if oldcol is not None:
# self.ax.collections.remove(oldcol)
plt.pause(0.001)
return None
| 1,681 | 25.698413 | 89 | py |
pySDC | pySDC-master/pySDC/playgrounds/ODEs/vanderpol_playground.py | from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.Van_der_Pol_implicit import vanderpol
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.playgrounds.ODEs.trajectory_HookClass import trajectories
def main():
"""
Van der Pol's oscillator inc. visualization
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.1
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = 'LU'
# initialize problem parameters
problem_params = dict()
problem_params['newton_tol'] = 1e-12
problem_params['newton_maxiter'] = 50
problem_params['mu'] = 5
problem_params['u0'] = (1.0, 0)
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
controller_params['hook_class'] = trajectories
controller_params['logger_level'] = 30
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = vanderpol
description['problem_params'] = problem_params
description['sweeper_class'] = generic_implicit
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
# instantiate the controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.0
Tend = 20.0
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
if __name__ == "__main__":
main()
| 2,011 | 30.4375 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/ODEs/ODE1_playground.py | from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.nonlinear_ODE_1 import nonlinear_ODE_1
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.playgrounds.ODEs.trajectory_HookClass import trajectories
def main():
"""
Van der Pol's oscillator inc. visualization
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 0.01
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = 'LU'
# initialize problem parameters
problem_params = dict()
problem_params['newton_tol'] = 5e-11
problem_params['newton_maxiter'] = 500
problem_params['u0'] = 0.0
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
# controller_params['hook_class'] = trajectories
controller_params['logger_level'] = 20
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = nonlinear_ODE_1
description['problem_params'] = problem_params
description['sweeper_class'] = generic_implicit
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
# instantiate the controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.0
Tend = 5
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
uex = P.u_exact(Tend)
print(abs(uend - uex))
if __name__ == "__main__":
main()
| 2,039 | 29.909091 | 109 | py |
pySDC | pySDC-master/pySDC/playgrounds/ODEs/__init__.py | 0 | 0 | 0 | py |
|
pySDC | pySDC-master/pySDC/playgrounds/ODEs/logistics_playground.py | from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.LogisticEquation import logistics_equation
from pySDC.implementations.sweeper_classes.generic_implicit import generic_implicit
from pySDC.playgrounds.ODEs.trajectory_HookClass import trajectories
def main():
"""
Van der Pol's oscillator inc. visualization
"""
# initialize level parameters
level_params = dict()
level_params['restol'] = 1e-10
level_params['dt'] = 1.0
# initialize sweeper parameters
sweeper_params = dict()
sweeper_params['quad_type'] = 'RADAU-RIGHT'
sweeper_params['num_nodes'] = 3
sweeper_params['QI'] = 'LU'
# initialize problem parameters
problem_params = dict()
problem_params['newton_tol'] = 1e-12
problem_params['newton_maxiter'] = 50
problem_params['lam'] = 20
problem_params['direct'] = True
problem_params['u0'] = 0.5
# initialize step parameters
step_params = dict()
step_params['maxiter'] = 20
# initialize controller parameters
controller_params = dict()
# controller_params['hook_class'] = trajectories
controller_params['logger_level'] = 20
# Fill description dictionary for easy hierarchy creation
description = dict()
description['problem_class'] = logistics_equation
description['problem_params'] = problem_params
description['sweeper_class'] = generic_implicit
description['sweeper_params'] = sweeper_params
description['level_params'] = level_params
description['step_params'] = step_params
# instantiate the controller
controller = controller_nonMPI(num_procs=1, controller_params=controller_params, description=description)
# set time parameters
t0 = 0.0
Tend = level_params['dt']
# get initial values on finest level
P = controller.MS[0].levels[0].prob
uinit = P.u_exact(t0)
# call main function to get things done...
uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)
uex = P.u_exact(Tend)
print(abs(uend - uex))
if __name__ == "__main__":
main()
| 2,128 | 30.308824 | 109 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.