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/tests/test_projects/test_soft_failure/test_generate_statistics.py
import pytest @pytest.mark.base def test_generate_statistics(): from pySDC.projects.soft_failure.generate_statistics import main main()
147
15.444444
68
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_AC/test_temp_forcing.py
import pytest @pytest.mark.mpi4py def test_main_serial(): from pySDC.projects.AllenCahn_Bayreuth.run_temp_forcing_verification import main main(cwd='pySDC/projects/AllenCahn_Bayreuth/')
197
21
84
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_AC/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_AC/test_simple_forcing.py
import pytest import subprocess import os import warnings @pytest.mark.mpi4py def test_main_serial(): from pySDC.projects.AllenCahn_Bayreuth.run_simple_forcing_verification import main, visualize_radii main() visualize_radii() @pytest.mark.slow @pytest.mark.mpi4py def test_main_parallel(): # try to import MPI here, will fail if things go wrong (and not in the subprocess part) try: import mpi4py del mpi4py except ImportError: raise ImportError('petsc tests need mpi4py') my_env = os.environ.copy() my_env['PYTHONPATH'] = '../../..:.' my_env['COVERAGE_PROCESS_START'] = 'pyproject.toml' nprocs = 2 cmd = f"export PYTHONPATH=$PYTHONPATH:$(pwd); export HWLOC_HIDE_ERRORS=2; mpirun -np {nprocs} python pySDC/projects/AllenCahn_Bayreuth/run_simple_forcing_benchmark.py -n {nprocs}" p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) p.wait() (output, err) = p.communicate() print(output) if err: warnings.warn(err) # assert err == '', err nprocs = 4 cmd = f"export PYTHONPATH=$PYTHONPATH:$(pwd); export HWLOC_HIDE_ERRORS=2; mpirun -np {nprocs} python pySDC/projects/AllenCahn_Bayreuth/run_simple_forcing_benchmark.py -n {nprocs}" p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) p.wait() (output, err) = p.communicate() print(output) if err: warnings.warn(err)
1,526
30.8125
183
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_compression/test_proof_of_concept.py
import pytest @pytest.mark.libpressio @pytest.mark.parametrize("thresh", [1e-6, 1e-8]) @pytest.mark.parametrize("useMPI", [True, False]) @pytest.mark.parametrize("num_procs", [1, 4]) def test_compression_proof_of_concept(thresh, useMPI, num_procs): if useMPI: import subprocess import os # Setup environment my_env = os.environ.copy() cmd = f"mpirun -np {num_procs} python {__file__} -t {thresh} -M {useMPI} -n {num_procs}".split() p = subprocess.Popen(cmd, env=my_env, cwd=".") p.wait() assert p.returncode == 0, 'ERROR: did not get return code 0, got %s with %2i processes' % ( p.returncode, num_procs, ) else: run_single_test(thresh=thresh, useMPI=useMPI, num_procs=num_procs) def run_single_test(thresh, useMPI, num_procs): print(f'Running with error bound {thresh} and {num_procs}. MPI: {useMPI}') import matplotlib.pyplot as plt import os from pySDC.projects.compression.order import plot_order_in_time fig, ax = plt.subplots(figsize=(3, 2)) plot_order_in_time(ax=ax, thresh=thresh, useMPI=useMPI, num_procs=num_procs) if os.path.exists('data'): ax.set_title(f'{num_procs} procs, {"MPI" if useMPI else "non MPI"}') fig.savefig(f'data/compression_order_time_advection_d={thresh:.2e}_n={num_procs}_MPI={useMPI}.png', dpi=200) if __name__ == '__main__': import sys # defaults for arguments num_procs = 1 useMPI = False thresh = -1 # parse command line arguments for i in range(len(sys.argv)): if sys.argv[i] == '-n': num_procs = int(sys.argv[i + 1]) elif sys.argv[i] == '-M': useMPI = True if sys.argv[i + 1] == 'True' else False elif sys.argv[i] == '-t': thresh = float(sys.argv[i + 1]) # execute test if '--use-subprocess' in sys.argv: test_compression_proof_of_concept(thresh=thresh, useMPI=useMPI, num_procs=num_procs) else: run_single_test(thresh=thresh, useMPI=useMPI, num_procs=num_procs)
2,085
31.59375
116
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_compression/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_SDC_showdown/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_SDC_showdown/test_fisher.py
import pytest @pytest.mark.petsc def test_fisher(): from pySDC.projects.SDC_showdown.SDC_timing_Fisher import main main()
133
13.888889
66
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_SDC_showdown/test_grayscott.py
import pytest @pytest.mark.petsc def test_grayscott(): from pySDC.projects.SDC_showdown.SDC_timing_GrayScott import main main(cwd='pySDC/projects/SDC_showdown/')
173
18.333333
69
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_fwsw/test_boussinesq.py
import os import pytest @pytest.mark.base def test_plot(): from pySDC.projects.FastWaveSlowWave.plotgmrescounter_boussinesq import plot_buoyancy assert os.path.isfile('pySDC/projects/FastWaveSlowWave/data/xaxis.npy'), 'ERROR: xaxis.npy does not exist' assert os.path.isfile('pySDC/projects/FastWaveSlowWave/data/sdc.npy'), 'ERROR: sdc.npy does not exist' assert os.path.isfile('pySDC/projects/FastWaveSlowWave/data/dirk.npy'), 'ERROR: dirk.npy does not exist' assert os.path.isfile('pySDC/projects/FastWaveSlowWave/data/rkimex.npy'), 'ERROR: rkimex.npy does not exist' assert os.path.isfile('pySDC/projects/FastWaveSlowWave/data/uref.npy'), 'ERROR: uref.npy does not exist' assert os.path.isfile('pySDC/projects/FastWaveSlowWave/data/split.npy'), 'ERROR: split.npy does not exist' plot_buoyancy(cwd='pySDC/projects/FastWaveSlowWave/') assert os.path.isfile('data/boussinesq.png'), 'ERROR: buoyancy plot has not been created'
964
55.764706
112
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_fwsw/test_acoustic.py
import os import pytest @pytest.mark.base def test_plot_convergence(): from pySDC.projects.FastWaveSlowWave.runconvergence_acoustic import plot_convergence assert os.path.isfile('pySDC/projects/FastWaveSlowWave/data/conv-data.txt'), 'ERROR: conv-data.txt does not exist' plot_convergence(cwd='pySDC/projects/FastWaveSlowWave/') assert os.path.isfile('data/convergence.png'), 'ERROR: convergence plot has not been created' @pytest.mark.base def test_compute_and_plot_itererror(): from pySDC.projects.FastWaveSlowWave.runitererror_acoustic import compute_and_plot_itererror compute_and_plot_itererror() assert os.path.isfile('data/iteration.png'), 'ERROR: iteration plot has not been created' @pytest.mark.base def test_compute_and_plot_solutions(): from pySDC.projects.FastWaveSlowWave.runmultiscale_acoustic import compute_and_plot_solutions compute_and_plot_solutions() assert os.path.isfile('data/multiscale-K2-M2.png'), 'ERROR: solution plot has not been created'
1,016
35.321429
118
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_fwsw/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_fwsw/test_fwsw.py
import os import pytest import numpy as np @pytest.mark.base def test_stifflimit_specrad(): from pySDC.projects.FastWaveSlowWave.plot_stifflimit_specrad import compute_specrad, plot_specrad nodes_v, lambda_f, specrad, norm = compute_specrad() assert np.amax(specrad) < 0.9715, 'Spectral radius is too high, got %s' % specrad assert np.amax(norm) < 2.210096, 'Norm is too high, got %s' % norm plot_specrad(nodes_v, lambda_f, specrad, norm) assert os.path.isfile('data/stifflimit-specrad.png'), 'ERROR: specrad plot has not been created' assert os.path.isfile('data/stifflimit-norm.png'), 'ERROR: norm plot has not been created' @pytest.mark.base def test_stability(): from pySDC.projects.FastWaveSlowWave.plot_stability import compute_stability, plot_stability lambda_s, lambda_f, num_nodes, K, stab = compute_stability() assert np.amax(stab).real < 26.327931, "Real part of max. stability too large, got %s" % stab assert np.amax(stab).imag < 0.2467791, "Imag part of max. stability too large, got %s" % stab plot_stability(lambda_s, lambda_f, num_nodes, K, stab) assert os.path.isfile('data/stability-K3-M3.png'), 'ERROR: stability plot has not been created' @pytest.mark.base def test_stab_vs_k(): from pySDC.projects.FastWaveSlowWave.plot_stab_vs_k import compute_stab_vs_k, plot_stab_vs_k mvals, kvals, stabval = compute_stab_vs_k(slow_resolved=True) assert np.amax(stabval) < 1.4455919, 'ERROR: stability values are too high, got %s' % stabval plot_stab_vs_k(True, mvals, kvals, stabval) assert os.path.isfile('data/stab_vs_k_resolved.png'), 'ERROR: stability plot has not been created' mvals, kvals, stabval = compute_stab_vs_k(slow_resolved=False) assert np.amax(stabval) < 3.7252282, 'ERROR: stability values are too high, got %s' % stabval plot_stab_vs_k(False, mvals, kvals, stabval) assert os.path.isfile('data/stab_vs_k_unresolved.png'), 'ERROR: stability plot has not been created' @pytest.mark.base def test_dispersion(): from pySDC.projects.FastWaveSlowWave.plot_dispersion import compute_and_plot_dispersion compute_and_plot_dispersion() assert os.path.isfile('data/phase-K3-M3.png'), 'ERROR: phase plot has not been created' assert os.path.isfile('data/ampfactor-K3-M3.png'), 'ERROR: phase plot has not been created' compute_and_plot_dispersion(Nsamples=3, K=4) compute_and_plot_dispersion(Nsamples=3, K=5)
2,454
41.327586
104
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_pintsime/test_piline_model.py
import pytest @pytest.mark.base def test_main(): from pySDC.projects.PinTSimE.piline_model import main main()
121
12.555556
57
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_pintsime/test_estimation_check.py
import pytest @pytest.mark.base def test_main(): from pySDC.projects.PinTSimE.estimation_check import run run()
123
12.777778
60
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_pintsime/test_battery_model.py
import pytest @pytest.mark.base def test_main(): from pySDC.projects.PinTSimE.battery_model import run run()
120
12.444444
57
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_pintsime/test_buck_model.py
import pytest @pytest.mark.base def test_main(): from pySDC.projects.PinTSimE.buck_model import main main()
119
12.333333
55
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_pintsime/test_battery_2capacitors_model.py
import pytest @pytest.mark.base def test_main(): from pySDC.projects.PinTSimE.battery_2capacitors_model import run run()
132
13.777778
69
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_pintsime/test_estimation_check_2capacitors.py
import pytest @pytest.mark.base def test_main(): from pySDC.projects.PinTSimE.estimation_check_2capacitors import run run()
135
14.111111
72
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_parallelSDC/test_preconditioner_MPI.py
import os import subprocess import pytest @pytest.mark.slow @pytest.mark.mpi4py def test_preconditioner_playground_MPI_5(): # Set python path once my_env = os.environ.copy() my_env['PYTHONPATH'] = '../../..:.' my_env['COVERAGE_PROCESS_START'] = 'pyproject.toml' cwd = '.' num_procs = 5 cmd = ( 'mpirun -np ' + str(num_procs) + ' python pySDC/projects/parallelSDC/preconditioner_playground_MPI.py' ).split() p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env, cwd=cwd) p.wait() for line in p.stdout: print(line) for line in p.stderr: print(line) assert p.returncode == 0, 'ERROR: did not get return code 0, got %s with %2i processes' % (p.returncode, num_procs) @pytest.mark.slow @pytest.mark.mpi4py def test_preconditioner_playground_MPI_3(): # Set python path once my_env = os.environ.copy() my_env['PYTHONPATH'] = '../../..:.' my_env['COVERAGE_PROCESS_START'] = 'pyproject.toml' cwd = '.' num_procs = 3 cmd = ( 'mpirun -np ' + str(num_procs) + ' python pySDC/projects/parallelSDC/preconditioner_playground_MPI.py' ).split() p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env, cwd=cwd) p.wait() for line in p.stdout: print(line) for line in p.stderr: print(line) assert p.returncode == 0, 'ERROR: did not get return code 0, got %s with %2i processes' % (p.returncode, num_procs)
1,504
31.717391
119
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_parallelSDC/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_parallelSDC/test_preconditioner.py
import pytest @pytest.mark.base def test_main(): from pySDC.projects.parallelSDC.preconditioner_playground import main, plot_iterations main() plot_iterations()
176
16.7
90
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_parallelSDC/test_AllenCahn_parallel.py
import pytest @pytest.mark.mpi4py def test_main(): from pySDC.projects.parallelSDC.AllenCahn_parallel import main # try to import MPI here, will fail if things go wrong (and not in the subprocess part) try: import mpi4py del mpi4py except ImportError: raise ImportError('petsc tests need mpi4py') main()
353
19.823529
91
py
pySDC
pySDC-master/pySDC/tests/test_projects/test_parallelSDC/test_fisher.py
import pytest @pytest.mark.base def test_main(): from pySDC.projects.parallelSDC.nonlinear_playground import main, plot_graphs main() plot_graphs() @pytest.mark.base def test_newton_vs_sdc(): from pySDC.projects.parallelSDC.newton_vs_sdc import main as main_newton_vs_sdc from pySDC.projects.parallelSDC.newton_vs_sdc import plot_graphs as plot_graphs_newton_vs_sdc main_newton_vs_sdc() plot_graphs_newton_vs_sdc()
449
22.684211
97
py
pySDC
pySDC-master/pySDC/playgrounds/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/playground_dtype.py
import numpy as np import time from mpi4py import MPI from mpi4py_fft import PFFT from pySDC.implementations.datatype_classes.mesh import mesh from pySDC.implementations.datatype_classes.mesh import mesh class mytype(np.ndarray): def __new__(cls, init, val=0.0): if isinstance(init, mytype): obj = np.ndarray.__new__(cls, init.shape, dtype=np.float, buffer=None) obj[:] = init[:] # obj = init.copy() elif isinstance(init, tuple): obj = np.ndarray.__new__(cls, init, dtype=np.float, buffer=None) obj.fill(val) else: raise NotImplementedError(type(init)) return obj def __abs__(self): return float(np.amax(np.ndarray.__abs__(self))) nvars = 16 nruns = 100 * 16 res = 0 t0 = time.perf_counter() m = mytype((nvars, nvars), val=2.0) for i in range(nruns): o = mytype(m) o[:] = 4.0 n = mytype(m) for j in range(i): n += 0.1 * j * o res = max(res, abs(n)) t1 = time.perf_counter() print(res, t1 - t0) # res = 0 # t0 = time.perf_counter() # m = mytype((nvars, nvars), val=2.0) # for i in range(nruns): # o = mytype(m) # o.values[:] = 4.0 # res = max(res, abs(m + o)) # t1 = time.perf_counter() # print(res, t1-t0) res = 0 t0 = time.perf_counter() m = mesh(init=(nvars, nvars), val=2.0) for i in range(nruns): o = mesh(init=m) o.values[:] = 4.0 n = mesh(init=m) for j in range(i): n += 0.1 * j * o res = max(res, abs(n)) t1 = time.perf_counter() print(res, t1 - t0) m = mytype((nvars, nvars), val=2.0) n = mytype((nvars, nvars), val=2.0) m[:] = -1 n[:] = 2.9 # print(n) o = mytype(m) m[0, 0] = 2 assert o[0, 0] == -1 assert o is not m exit() print(type(m)) print(type(m + n)) print(abs(m)) print(type(abs(m))) comm = MPI.COMM_WORLD subcomm = comm.Split() # print(subcomm) nvars = 8 ndim = 2 axes = tuple(range(ndim)) N = np.array([nvars] * ndim, dtype=int) # print(N, axes) fft = PFFT(subcomm, N, axes=axes, dtype=np.float, slab=True) init = (fft, False) m = fft_datatype(init) m[:] = comm.Get_rank() print(type(m)) print(m.subcomm) print(abs(m), type(abs(m)))
2,153
20.979592
82
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/datatype_test.py
import time import numpy as np from dedalus import public as de from pySDC.implementations.datatype_classes.mesh import mesh from pySDC.implementations.datatype_classes.mesh import mesh from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field from pySDC.playgrounds.Dedalus.dedalus_field_fast import dedalus_field_fast def inner_loop(iloops, dtype, maxb, a, b): for i in range(iloops): b += 0.1 / (i + 1) * a print(type(b)) a = dtype(b) b = 1.0 / iloops * b maxb = max(maxb, abs(b)) return maxb def mesh_test(oloops, iloops, N): maxtime = 0.0 mintime = 1e99 meantime = 0.0 maxb = 0.0 for i in range(oloops): t0 = time.perf_counter() a = mesh(init=N, val=1.0 * i) b = mesh(a) maxb = inner_loop(iloops, mesh, maxb, a, b) t1 = time.perf_counter() maxtime = max(maxtime, t1 - t0) mintime = min(mintime, t1 - t0) meantime += t1 - t0 meantime /= oloops print(maxb) print(maxtime, mintime, meantime) def parallelmesh_test(oloops, iloops, N): maxtime = 0.0 mintime = 1e99 meantime = 0.0 maxb = 0.0 for i in range(oloops): t0 = time.perf_counter() a = mesh(init=(N, None, np.zeros(1).dtype), val=1.0 * i) b = mesh(a) maxb = inner_loop(iloops, mesh, maxb, a, b) t1 = time.perf_counter() maxtime = max(maxtime, t1 - t0) mintime = min(mintime, t1 - t0) meantime += t1 - t0 meantime /= oloops print(maxb) print(maxtime, mintime, meantime) def field_test(oloops, iloops, N): xbasis = de.Fourier('x', N[0], interval=(-1, 1), dealias=1) ybasis = de.Fourier('y', N[1], interval=(-1, 1), dealias=1) domain = de.Domain([xbasis, ybasis], grid_dtype=np.float64, comm=None) maxtime = 0.0 mintime = 1e99 meantime = 0.0 maxb = 0.0 for i in range(oloops): t0 = time.perf_counter() a = dedalus_field(init=domain) a.values[0]['g'][:] = 1.0 * i b = dedalus_field(a) maxb = inner_loop(iloops, dedalus_field, maxb, a, b) t1 = time.perf_counter() maxtime = max(maxtime, t1 - t0) mintime = min(mintime, t1 - t0) meantime += t1 - t0 meantime /= oloops print(maxb) print(maxtime, mintime, meantime) def fast_field_test(oloops, iloops, N): xbasis = de.Fourier('x', N[0], interval=(-1, 1), dealias=1) ybasis = de.Fourier('y', N[1], interval=(-1, 1), dealias=1) domain = de.Domain([xbasis, ybasis], grid_dtype=np.float64, comm=None) maxtime = 0.0 mintime = 1e99 meantime = 0.0 maxb = 0.0 for i in range(oloops): t0 = time.perf_counter() a = dedalus_field_fast(init=domain) a['g'][:] = 1.0 * i b = dedalus_field_fast(a) maxb = inner_loop(iloops, dedalus_field_fast, maxb, a, b) t1 = time.perf_counter() maxtime = max(maxtime, t1 - t0) mintime = min(mintime, t1 - t0) meantime += t1 - t0 meantime /= oloops print(maxb) print(maxtime, mintime, meantime) if __name__ == '__main__': oloops = 1 iloops = 1 N = (64, 64) # mesh_test(oloops, iloops, N) # parallelmesh_test(oloops, iloops, N) # field_test(oloops, iloops, N) fast_field_test(oloops, iloops, N)
3,344
24.730769
75
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_1d_imex/plotenergy.py
from subprocess import call import numpy as np from matplotlib import pyplot as plt from matplotlib.ticker import ScalarFormatter from pylab import rcParams fs = 8 params = np.array([[3, 3], [3, 4], [3, 5]]) file = open('energy-exact.txt') energy_exact = float(file.readline().strip()) Tend = float(file.readline().strip()) nsteps = float(file.readline().strip()) file.close() dt = Tend / nsteps taxis = np.linspace(dt, Tend, nsteps) energy = np.array([]) energy_imex = np.array([]) energy_dirk = np.array([]) for ii in range(3): filename = 'energy-sdc-K' + str(params[ii, 1]) + '-M' + str(params[ii, 0]) + '.txt' file = open(filename, 'r') while True: line = file.readline() if not line: break energy = np.append(energy, float(line.strip())) file.close() filename = 'energy-dirk-' + str(params[ii, 1]) + '.txt' file = open(filename, 'r') while True: line = file.readline() if not line: break energy_dirk = np.append(energy_dirk, float(line.strip())) file.close() filename = 'energy-imex-' + str(params[ii, 1]) + '.txt' file = open(filename, 'r') while True: line = file.readline() if not line: break energy_imex = np.append(energy_imex, float(line.strip())) file.close() energy = np.split(energy, 3) energy_dirk = np.split(energy_dirk, 3) energy_imex = np.split(energy_imex, 3) for ii in range(3): energy[ii][:] = energy[ii][:] / energy_exact energy_dirk[ii][:] = energy_dirk[ii][:] / energy_exact energy_imex[ii][:] = energy_imex[ii][:] / energy_exact color = ['r', 'b', 'g'] shape = ['-', '-', '-'] rcParams['figure.figsize'] = 2.5, 2.5 fig = plt.figure() for ii in range(0, 3): plt.plot(taxis, energy[ii], shape[ii], markersize=fs, color=color[ii], label='p=' + str(int(params[ii, 1]))) plt.plot( taxis, energy_dirk[ii], '--', color=color[ii], label='DIRK(' + str(int(params[ii, 1])) + ')', dashes=(2.0, 1.0) ) plt.plot(taxis, energy_imex[ii], ':', color=color[ii], label='IMEX(' + str(int(params[ii, 1])) + ')') plt.legend(loc='lower left', fontsize=fs, prop={'size': fs}, ncol=2) plt.xlabel('Time', fontsize=fs) plt.ylabel('Normalised energy', fontsize=fs, labelpad=2) plt.ylim([0.0, 1.1]) plt.yticks(fontsize=fs) plt.xticks(fontsize=fs) plt.gca().get_xaxis().get_major_formatter().labelOnlyBase = False plt.gca().get_xaxis().set_major_formatter(ScalarFormatter()) # plt.show() filename = 'energy.pdf' fig.savefig(filename, bbox_inches='tight') call(["pdfcrop", filename, filename])
2,591
30.609756
119
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_1d_imex/runconvergence_rk.py
import numpy as np import pySDC.core.deprecated.PFASST_stepwise as mp from ProblemClass_conv import acoustic_1d_imex from pySDC.projects.FastWaveSlowWave.HookClass import plot_solution from standard_integrators import rk_imex 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'] = 1e-14 sparams = {} # This comes as read-in for the problem class pparams = {} pparams['cadv'] = 0.1 pparams['cs'] = 1.00 pparams['order_adv'] = 5 pparams['waveno'] = 5 # Fill description dictionary for easy hierarchy creation description = {} description['problem_class'] = acoustic_1d_imex description['problem_params'] = pparams description['dtype_u'] = mesh description['dtype_f'] = rhs_imex_mesh ### SET TYPE OF QUADRATURE NODES ### # description['collocation_class'] = collclass.CollGaussLobatto # description['collocation_class'] = collclass.CollGaussLegendre description['collocation_class'] = collclass.CollGaussRadau_Right description['sweeper_class'] = imex_1st_order description['do_coll_update'] = True description['level_params'] = lparams description['hook_class'] = plot_solution nsteps = np.zeros((3, 9)) nsteps[0, :] = [20, 30, 40, 50, 60, 70, 80, 90, 100] nsteps[1, :] = nsteps[0, :] nsteps[2, :] = nsteps[0, :] for order in [3, 4, 5]: error = np.zeros(np.shape(nsteps)[1]) # setup parameters "in time" t0 = 0 Tend = 1.0 if order == 3: file = open('conv-data-rk.txt', 'w') else: file = open('conv-data-rk.txt', 'a') ### SET NUMBER OF NODES DEPENDING ON REQUESTED ORDER ### if order == 3: description['num_nodes'] = 3 elif order == 4: description['num_nodes'] = 3 elif order == 5: description['num_nodes'] = 3 sparams['maxiter'] = order for ii in range(0, np.shape(nsteps)[1]): ns = nsteps[order - 3, ii] if (order == 3) or (order == 4): pparams['nvars'] = [(2, 2 * ns)] elif order == 5: pparams['nvars'] = [(2, 2 * ns)] # quickly generate block of steps MS = mp.generate_steps(num_procs, sparams, description) dt = Tend / float(ns) # get initial values on finest level P = MS[0].levels[0].prob rkimex = rk_imex(P.A.astype('complex'), P.Dx.astype('complex'), order) uinit = P.u_exact(t0) y0 = np.concatenate((uinit.values[0, :], uinit.values[1, :])) y0 = y0.astype('complex') if ii == 0: print("Time step: %4.2f" % dt) print("Fast CFL number: %4.2f" % (pparams['cs'] * dt / P.dx)) print("Slow CFL number: %4.2f" % (pparams['cadv'] * dt / P.dx)) # call main function to get things done... for n in range(int(ns)): y0 = rkimex.timestep(y0, dt) # compute exact solution and compare uex = P.u_exact(Tend) uend = np.split(y0, 2) error[ii] = np.linalg.norm(uex.values - uend, np.inf) / np.linalg.norm(uex.values, np.inf) file.write(str(order) + " " + str(ns) + " " + str(error[ii]) + "\n") file.close()
3,763
32.309735
102
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_1d_imex/ploterrorconstants.py
from subprocess import call import numpy as np from matplotlib import pyplot as plt from matplotlib.ticker import ScalarFormatter from pylab import rcParams fs = 8 order = np.array([]) nsteps = np.array([]) error = np.array([]) # load SDC data file = open('conv-data.txt', 'r') while True: line = file.readline() if not line: break items = str.split(line, " ", 3) order = np.append(order, int(items[0])) nsteps = np.append(nsteps, int(float(items[1]))) error = np.append(error, float(items[2])) file.close() assert np.size(order) == np.size(nsteps), 'Found different number of entries in order and nsteps' assert np.size(nsteps) == np.size(error), 'Found different number of entries in nsteps and error' N = np.size(nsteps) / 3 assert isinstance(N, int), 'Number of entries not a multiple of three' # load Runge-Kutta data order_rk = np.array([]) nsteps_rk = np.array([]) error_rk = np.array([]) file = open('conv-data-rk.txt', 'r') while True: line = file.readline() if not line: break items = str.split(line, " ", 3) order_rk = np.append(order_rk, int(items[0])) nsteps_rk = np.append(nsteps_rk, int(float(items[1]))) error_rk = np.append(error_rk, float(items[2])) file.close() assert np.size(order_rk) == np.size(nsteps_rk), 'Found different number of entries in order and nsteps' assert np.size(nsteps_rk) == np.size(error_rk), 'Found different number of entries in nsteps and error' N = np.size(nsteps_rk) / 3 assert isinstance(N, int), 'Number of entries not a multiple of three' ### Compute and plot error constant ### errconst_sdc = np.zeros((3, N)) errconst_rk = np.zeros((3, N)) nsteps_plot_sdc = np.zeros((3, N)) nsteps_plot_rk = np.zeros((3, N)) order_plot = np.zeros(3) for ii in range(0, 3): order_plot[ii] = order[N * ii] for jj in range(0, N): p_sdc = order[N * ii + jj] err_sdc = error[N * ii + jj] nsteps_plot_sdc[ii, jj] = nsteps[N * ii + jj] dt_sdc = 1.0 / float(nsteps_plot_sdc[ii, jj]) errconst_sdc[ii, jj] = err_sdc / dt_sdc ** float(p_sdc) p_rk = order_rk[N * ii + jj] err_rk = error_rk[N * ii + jj] nsteps_plot_rk[ii, jj] = nsteps_rk[N * ii + jj] dt_rk = 1.0 / float(nsteps_plot_rk[ii, jj]) errconst_rk[ii, jj] = err_rk / dt_rk ** float(p_rk) color = ['r', 'b', 'g'] shape_sdc = ['<', '^', '>'] shape_rk = ['o', 'd', 's'] rcParams['figure.figsize'] = 2.5, 2.5 fig = plt.figure() for ii in range(0, 3): plt.semilogy( nsteps_plot_sdc[ii, :], errconst_sdc[ii, :], shape_sdc[ii], markersize=fs, color=color[ii], label='SDC(' + str(int(order_plot[ii])) + ')', ) plt.semilogy( nsteps_plot_rk[ii, :], errconst_rk[ii, :], shape_rk[ii], markersize=fs - 2, color=color[ii], label='IMEX(' + str(int(order_plot[ii])) + ')', ) plt.legend(loc='lower left', fontsize=fs, prop={'size': fs - 1}, ncol=2) plt.xlabel('Number of time steps', fontsize=fs) plt.ylabel('Estimated error constant', fontsize=fs, labelpad=2) plt.xlim([0.9 * np.min(nsteps_plot_sdc), 1.1 * np.max(nsteps_plot_sdc)]) plt.ylim([1e1, 1e6]) plt.yticks([1e1, 1e2, 1e3, 1e4, 1e5, 1e6], fontsize=fs) plt.xticks([20, 30, 40, 60, 80, 100], fontsize=fs) plt.gca().get_xaxis().get_major_formatter().labelOnlyBase = False plt.gca().get_xaxis().set_major_formatter(ScalarFormatter()) # plt.show() filename = 'error_constants.pdf' fig.savefig(filename, bbox_inches='tight') call(["pdfcrop", filename, filename])
3,561
31.981481
103
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_1d_imex/ProblemClass.py
r""" One-dimensional IMEX acoustic-advection ========================= Integrate the linear 1D acoustic-advection problem: .. math:: u_t + U u_x + c p_x & = 0 \\ p_t + U p_x + c u_x & = 0. """ import numpy as np import scipy.sparse.linalg as LA from buildWave1DMatrix import getWave1DMatrix, getWave1DAdvectionMatrix from pySDC.core.Problem import ptype from pySDC.implementations.datatype_classes.mesh import mesh, rhs_imex_mesh def u_initial(x): return np.sin(x) # return np.exp(-0.5*(x-0.5)**2/0.1**2) class acoustic_1d_imex(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 assert 'cs' in cparams assert 'cadv' in cparams assert 'order_adv' 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(acoustic_1d_imex, self).__init__(self.nvars, dtype_u, dtype_f) self.mesh = np.linspace(0.0, 1.0, self.nvars[1], endpoint=False) self.dx = self.mesh[1] - self.mesh[0] self.Dx = -self.cadv * getWave1DAdvectionMatrix(self.nvars[1], self.dx, self.order_adv) self.Id, A = getWave1DMatrix(self.nvars[1], self.dx, ['periodic', 'periodic'], ['periodic', 'periodic']) self.A = -self.cs * A def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-dtA)u = rhs Args: rhs: 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 """ M = self.Id - factor * self.A b = np.concatenate((rhs.values[0, :], rhs.values[1, :])) sol = LA.spsolve(M, b) me = mesh(self.nvars) me.values[0, :], me.values[1, :] = np.split(sol, 2) return me def __eval_fexpl(self, u, t): """ Helper routine to evaluate the explicit part of the RHS Args: u: current values (not used here) t: current time Returns: explicit part of RHS """ b = np.concatenate((u.values[0, :], u.values[1, :])) sol = self.Dx.dot(b) fexpl = mesh(self.nvars) fexpl.values[0, :], fexpl.values[1, :] = np.split(sol, 2) return fexpl def __eval_fimpl(self, u, t): """ Helper routine to evaluate the implicit part of the RHS Args: u: current values t: current time (not used here) Returns: implicit part of RHS """ b = np.concatenate((u.values[0, :], u.values[1, :])) sol = self.A.dot(b) fimpl = mesh(self.nvars, val=0.0) fimpl.values[0, :], fimpl.values[1, :] = np.split(sol, 2) 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 """ sigma_0 = 0.1 k = 7.0 * 2.0 * np.pi x_0 = 0.75 x_1 = 0.25 me = mesh(self.nvars) # me.values[0,:] = 0.5*u_initial(self.mesh - (self.cadv + self.cs)*t) + 0.5*u_initial(self.mesh - (self.cadv - self.cs)*t) # me.values[1,:] = 0.5*u_initial(self.mesh - (self.cadv + self.cs)*t) - 0.5*u_initial(self.mesh - (self.cadv - self.cs)*t) me.values[0, :] = np.exp(-np.square(self.mesh - x_0 - self.cs * t) / (sigma_0 * sigma_0)) + np.exp( -np.square(self.mesh - x_1 - self.cs * t) / (sigma_0 * sigma_0) ) * np.cos(k * (self.mesh - self.cs * t) / sigma_0) me.values[1, :] = me.values[0, :] return me
4,882
27.063218
130
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_1d_imex/ProblemClass_multiscale.py
r""" One-dimensional IMEX acoustic-advection ========================= Integrate the linear 1D acoustic-advection problem: .. math:: u_t + U u_x + c p_x & = 0 \\ p_t + U p_x + c u_x & = 0. """ import numpy as np import scipy.sparse.linalg as LA from buildWave1DMatrix import getWave1DMatrix, getWave1DAdvectionMatrix from pySDC.core.Problem import ptype from pySDC.implementations.datatype_classes import mesh, rhs_imex_mesh class acoustic_1d_imex(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 assert 'cs' in cparams assert 'cadv' in cparams assert 'order_adv' in cparams assert 'multiscale' 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(acoustic_1d_imex, self).__init__(self.nvars, dtype_u, dtype_f) self.mesh = np.linspace(0.0, 1.0, self.nvars[1], endpoint=False) self.dx = self.mesh[1] - self.mesh[0] self.Dx = -self.cadv * getWave1DAdvectionMatrix(self.nvars[1], self.dx, self.order_adv) self.Id, A = getWave1DMatrix(self.nvars[1], self.dx, ['periodic', 'periodic'], ['periodic', 'periodic']) self.A = -self.cs * A def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-dtA)u = rhs Args: rhs: 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 """ M = self.Id - factor * self.A b = np.concatenate((rhs.values[0, :], rhs.values[1, :])) sol = LA.spsolve(M, b) me = mesh(self.nvars) me.values[0, :], me.values[1, :] = np.split(sol, 2) return me def __eval_fexpl(self, u, t): """ Helper routine to evaluate the explicit part of the RHS Args: u: current values (not used here) t: current time Returns: explicit part of RHS """ b = np.concatenate((u.values[0, :], u.values[1, :])) sol = self.Dx.dot(b) fexpl = mesh(self.nvars) fexpl.values[0, :], fexpl.values[1, :] = np.split(sol, 2) return fexpl def __eval_fimpl(self, u, t): """ Helper routine to evaluate the implicit part of the RHS Args: u: current values t: current time (not used here) Returns: implicit part of RHS """ b = np.concatenate((u.values[0, :], u.values[1, :])) sol = self.A.dot(b) fimpl = mesh(self.nvars, val=0.0) fimpl.values[0, :], fimpl.values[1, :] = np.split(sol, 2) 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 """ sigma_0 = 0.1 k = 7.0 * 2.0 * np.pi x_0 = 0.75 x_1 = 0.25 ms = 0.0 if self.multiscale: ms = 1.0 me = mesh(self.nvars) me.values[0, :] = np.exp(-np.square(self.mesh - x_0 - self.cs * t) / (sigma_0 * sigma_0)) + ms * np.exp( -np.square(self.mesh - x_1 - self.cs * t) / (sigma_0 * sigma_0) ) * np.cos(k * (self.mesh - self.cs * t) / sigma_0) me.values[1, :] = me.values[0, :] return me
4,640
26.3
112
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_1d_imex/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_1d_imex/dirk.py
import math import numpy as np import scipy.sparse as sp import scipy.sparse.linalg as LA class dirk: def __init__(self, M, order): assert np.shape(M)[0] == np.shape(M)[1], "Matrix M must be quadratic" self.Ndof = np.shape(M)[0] self.M = M self.order = order assert self.order in [2, 22, 3, 4], 'Order must be 2,22,3,4' if self.order == 2: self.nstages = 1 self.A = np.zeros((1, 1)) self.A[0, 0] = 0.5 self.tau = [0.5] self.b = [1.0] if self.order == 22: self.nstages = 2 self.A = np.zeros((2, 2)) self.A[0, 0] = 1.0 / 3.0 self.A[1, 0] = 1.0 / 2.0 self.A[1, 1] = 1.0 / 2.0 self.tau = np.zeros(2) self.tau[0] = 1.0 / 3.0 self.tau[1] = 1.0 self.b = np.zeros(2) self.b[0] = 3.0 / 4.0 self.b[1] = 1.0 / 4.0 if self.order == 3: self.nstages = 2 self.A = np.zeros((2, 2)) self.A[0, 0] = 0.5 + 1.0 / (2.0 * math.sqrt(3.0)) self.A[1, 0] = -1.0 / math.sqrt(3.0) self.A[1, 1] = self.A[0, 0] self.tau = np.zeros(2) self.tau[0] = 0.5 + 1.0 / (2.0 * math.sqrt(3.0)) self.tau[1] = 0.5 - 1.0 / (2.0 * math.sqrt(3.0)) self.b = np.zeros(2) self.b[0] = 0.5 self.b[1] = 0.5 if self.order == 4: self.nstages = 3 alpha = 2.0 * math.cos(math.pi / 18.0) / math.sqrt(3.0) self.A = np.zeros((3, 3)) self.A[0, 0] = (1.0 + alpha) / 2.0 self.A[1, 0] = -alpha / 2.0 self.A[1, 1] = self.A[0, 0] self.A[2, 0] = 1.0 + alpha self.A[2, 1] = -(1.0 + 2.0 * alpha) self.A[2, 2] = self.A[0, 0] self.tau = np.zeros(3) self.tau[0] = (1.0 + alpha) / 2.0 self.tau[1] = 1.0 / 2.0 self.tau[2] = (1.0 - alpha) / 2.0 self.b = np.zeros(3) self.b[0] = 1.0 / (6.0 * alpha * alpha) self.b[1] = 1.0 - 1.0 / (3.0 * alpha * alpha) self.b[2] = 1.0 / (6.0 * alpha * alpha) self.stages = np.zeros((self.nstages, self.Ndof)) def timestep(self, u0, dt): uend = u0 for i in range(0, self.nstages): b = u0 # Compute right hand side for this stage's implicit step for j in range(0, i): b = b + self.A[i, j] * dt * self.f(self.stages[j, :]) # Implicit solve for current stage self.stages[i, :] = self.f_solve(b, dt * self.A[i, i]) # Add contribution of current stage to final value uend = uend + self.b[i] * dt * self.f(self.stages[i, :]) return uend # # Returns f(u) = c*u # def f(self, u): return self.M.dot(u) # # Solves (Id - alpha*c)*u = b for u # def f_solve(self, b, alpha): L = sp.eye(self.Ndof) - alpha * self.M return LA.spsolve(L, b)
3,105
27.236364
77
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_1d_imex/runenergy.py
from subprocess import call import numpy as np import pySDC.core.deprecated.PFASST_stepwise as mp from ProblemClass_conv import acoustic_1d_imex from pySDC.projects.FastWaveSlowWave.HookClass import plot_solution from standard_integrators import dirk, rk_imex 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'] = 1e-14 sparams = {} # This comes as read-in for the problem class pparams = {} pparams['cadv'] = 0.1 pparams['cs'] = 1.00 pparams['order_adv'] = 5 pparams['waveno'] = 5 # Fill description dictionary for easy hierarchy creation description = {} description['problem_class'] = acoustic_1d_imex description['problem_params'] = pparams description['dtype_u'] = mesh description['dtype_f'] = rhs_imex_mesh ### SET TYPE OF QUADRATURE NODES ### # description['collocation_class'] = collclass.CollGaussLobatto # description['collocation_class'] = collclass.CollGaussLegendre description['collocation_class'] = collclass.CollGaussRadau_Right description['sweeper_class'] = imex_1st_order description['do_coll_update'] = True description['level_params'] = lparams description['hook_class'] = plot_solution nsteps = 20 for order in [3, 4, 5]: # setup parameters "in time" t0 = 0 Tend = 1.0 ### SET NUMBER OF NODES DEPENDING ON REQUESTED ORDER ### if order == 3: description['num_nodes'] = 3 elif order == 4: description['num_nodes'] = 3 elif order == 5: description['num_nodes'] = 3 sparams['maxiter'] = order pparams['nvars'] = [(2, 160)] # quickly generate block of steps MS = mp.generate_steps(num_procs, sparams, description) dt = Tend / float(nsteps) # get initial values on finest level P = MS[0].levels[0].prob uinit = P.u_exact(t0) file = open('energy-exact.txt', 'w') E = np.sum(np.square(uinit.values[0, :]) + np.square(uinit.values[1, :])) file.write('%30.20f\n' % E) file.write('%30.20f\n' % float(Tend)) file.write('%30.20f' % float(nsteps)) file.close() print("Time step: %4.2f" % dt) print("Fast CFL number: %4.2f" % (pparams['cs'] * dt / P.dx)) print("Slow CFL number: %4.2f" % (pparams['cadv'] * dt / P.dx)) ### Run standard integrators first _dirk = dirk((P.A + P.Dx).astype('complex'), sparams['maxiter']) _rkimex = rk_imex(P.A.astype('complex'), P.Dx.astype('complex'), sparams['maxiter']) y_dirk = np.concatenate((uinit.values[0, :], uinit.values[1, :])) y_imex = np.concatenate((uinit.values[0, :], uinit.values[1, :])) y_dirk = y_dirk.astype('complex') y_imex = y_imex.astype('complex') file_dirk = open('energy-dirk-' + str(sparams['maxiter']) + '.txt', 'w') file_imex = open('energy-imex-' + str(sparams['maxiter']) + '.txt', 'w') for nn in range(nsteps): y_dirk = _dirk.timestep(y_dirk, dt) y_imex = _rkimex.timestep(y_imex, dt) y_e = np.split(y_dirk, 2) E = np.sum(np.square(y_e[0]) + np.square(y_e[1])) file_dirk.write('%30.20f\n' % E) y_e = np.split(y_imex, 2) E = np.sum(np.square(y_e[0]) + np.square(y_e[1])) file_imex.write('%30.20f\n' % E) ### Run SDC # call main function to get things done... uend, stats = mp.run_pfasst(MS, u0=uinit, t0=t0, dt=dt, Tend=Tend) # rename file with energy data to indicate M and K filename = 'energy-sdc-K' + str(sparams['maxiter']) + '-M' + str(description['num_nodes']) + '.txt' call(['mv', 'energy-sdc.txt', filename])
4,192
34.533898
107
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_1d_imex/playground.py
import numpy as np import pySDC.core.deprecated.PFASST_stepwise as mp from ProblemClass import acoustic_1d_imex from matplotlib import pyplot as plt from pySDC.projects.FastWaveSlowWave.HookClass import plot_solution 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'] = 1e-10 sparams = {} sparams['maxiter'] = 2 # setup parameters "in time" t0 = 0.0 Tend = 3.0 dt = Tend / float(154) # This comes as read-in for the problem class pparams = {} pparams['nvars'] = [(2, 512)] pparams['cadv'] = 0.1 pparams['cs'] = 1.0 pparams['order_adv'] = 5 # This comes as read-in for the transfer operations tparams = {} tparams['finter'] = True # Fill description dictionary for easy hierarchy creation description = {} description['problem_class'] = acoustic_1d_imex description['problem_params'] = pparams description['dtype_u'] = mesh description['dtype_f'] = rhs_imex_mesh description['collocation_class'] = collclass.CollGaussLobatto description['num_nodes'] = 2 description['sweeper_class'] = imex_1st_order description['level_params'] = lparams description['hook_class'] = plot_solution # 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)) sigma_0 = 0.1 x_0 = 0.75 # plt.plot(P.mesh, uex.values[0,:], '+', color='b', label='u (exact)') plt.plot(P.mesh, uend.values[1, :], '-', color='b', label='SDC') # plt.plot(P.mesh, uex.values[1,:], '+', color='r', label='p (exact)') # plt.plot(P.mesh, uend.values[1,:], '-', color='b', linewidth=2.0, label='p (SDC)') p_slow = np.exp(-np.square(P.mesh - x_0) / (sigma_0 * sigma_0)) # plt.plot(P.mesh, p_slow, '-', color='r', markersize=4, label='slow mode') plt.legend(loc=2) plt.xlim([0, 1]) plt.ylim([-0.1, 1.1]) fig.gca().grid() # plt.show() plt.gcf().savefig( 'fwsw-sdc-K' + str(sparams['maxiter']) + '-M' + str(description['num_nodes']) + '.pdf', bbox_inches='tight' )
3,044
31.741935
115
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/fwsw/run_convergence.py
from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import pySDC.core.deprecated.PFASST_stepwise as mp from pySDC.implementations.problem_classes.FastWaveSlowWave_Scalar import swfw_scalar from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order from pySDC.core import CollocationClasses as collclass from pySDC.core import Log 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'] = 1e-12 sparams = {} sparams['maxiter'] = 4 # This comes as read-in for the problem class pparams = {} pparams['lambda_s'] = np.array([0.1j], dtype='complex') pparams['lambda_f'] = np.array([1.0j], dtype='complex') pparams['u0'] = 1 # Fill description dictionary for easy hierarchy creation description = {} description['problem_class'] = swfw_scalar description['problem_params'] = pparams description['collocation_class'] = collclass.CollGaussLegendre description['num_nodes'] = [3] description['do_LU'] = False description['sweeper_class'] = imex_1st_order description['level_params'] = lparams # quickly generate block of steps MS = mp.generate_steps(num_procs, sparams, description) Nsteps_v = np.array([1, 2, 4, 8, 10, 15, 20]) Tend = 1.0 t0 = 0 P = MS[0].levels[0].prob uinit = P.u_exact(t0) uex = P.u_exact(Tend) error = np.zeros(np.size(Nsteps_v)) convline = np.zeros(np.size(Nsteps_v)) for j in range(0, np.size(Nsteps_v)): # setup parameters "in time" dt = Tend / float(Nsteps_v[j]) # call main function to get things done... uend, stats = mp.run_pfasst(MS, u0=uinit, t0=t0, dt=dt, Tend=Tend) error[j] = np.abs(uend.values - uex.values) convline[j] = error[j] * (float(Nsteps_v[j]) / float(Nsteps_v[j])) ** sparams['maxiter'] plt.figure() plt.loglog(Nsteps_v, error, 'bo', markersize=12) plt.loglog(Nsteps_v, convline, '-', color='k') plt.show()
2,185
30.681159
96
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/fwsw/plot_stab_vs_m.py
import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from pySDC.implementations.problem_classes.FastWaveSlowWave_Scalar import swfw_scalar from pylab import rcParams from pySDC.core import CollocationClasses as collclass from pySDC.core import Hooks as hookclass from pySDC.core import Level as lvl from pySDC.core import Step as stepclass from pySDC.implementations.datatype_classes import mesh, rhs_imex_mesh from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order as imex if __name__ == "__main__": mvals = np.arange(2, 10) kvals = [3, 5, 7] lambda_fast = 10j lambda_slow = 3j stabval = np.zeros((np.size(kvals), np.size(mvals))) for i in range(0, np.size(mvals)): pparams = {} # the following are not used in the computation pparams['lambda_s'] = np.array([0.0]) pparams['lambda_f'] = np.array([0.0]) pparams['u0'] = 1.0 swparams = {} # swparams['collocation_class'] = collclass.CollGaussLobatto # swparams['collocation_class'] = collclass.CollGaussLegendre swparams['collocation_class'] = collclass.CollGaussRadau_Right swparams['num_nodes'] = mvals[i] do_coll_update = True # # ...this is functionality copied from test_imexsweeper. Ideally, it should be available in one place. # step = stepclass.step(params={}) L = lvl.level( problem_class=swfw_scalar, problem_params=pparams, dtype_u=mesh, dtype_f=rhs_imex_mesh, sweeper_class=imex, sweeper_params=swparams, level_params={}, hook_class=hookclass.hooks, id="stability", ) step.register_level(L) step.status.dt = 1.0 # Needs to be 1.0, change dt through lambdas step.status.time = 0.0 u0 = step.levels[0].prob.u_exact(step.status.time) step.init_step(u0) nnodes = step.levels[0].sweep.coll.num_nodes level = step.levels[0] problem = level.prob QE = level.sweep.QE[1:, 1:] QI = level.sweep.QI[1:, 1:] Q = level.sweep.coll.Qmat[1:, 1:] LHS, RHS = level.sweep.get_scalar_problems_sweeper_mats(lambdas=[lambda_fast, lambda_slow]) for k in range(0, np.size(kvals)): Kmax = kvals[k] Mat_sweep = level.sweep.get_scalar_problems_manysweep_mat(nsweeps=Kmax, lambdas=[lambda_fast, lambda_slow]) if do_coll_update: stab_fh = 1.0 + (lambda_fast + lambda_slow) * level.sweep.coll.weights.dot( Mat_sweep.dot(np.ones(nnodes)) ) else: q = np.zeros(nnodes) q[nnodes - 1] = 1.0 stab_fh = q.dot(Mat_sweep.dot(np.ones(nnodes))) stabval[k, i] = np.absolute(stab_fh) rcParams['figure.figsize'] = 2.5, 2.5 fig = plt.figure() fs = 8 plt.plot(mvals, stabval[0, :], 'o-', color='b', label=(r"K=%1i" % kvals[0])) plt.plot(mvals, stabval[1, :], 's-', color='r', label=(r"K=%1i" % kvals[1])) plt.plot(mvals, stabval[2, :], 'd-', color='g', label=(r"K=%1i" % kvals[2])) plt.plot(mvals, 1.0 + 0.0 * mvals, '--', color='k') plt.xlabel('Number of nodes M', fontsize=fs) plt.ylabel(r'Modulus of stability function $\left| R \right|$', fontsize=fs) plt.ylim([0.0, 1.8]) plt.legend(loc='lower right', fontsize=fs, prop={'size': fs}) plt.gca().get_xaxis().get_major_formatter().labelOnlyBase = False plt.gca().get_xaxis().set_major_formatter(ScalarFormatter()) plt.show() # filename = 'stablimit-M'+str(mvals[0])+'.pdf' # fig.savefig(filename, bbox_inches='tight') # call(["pdfcrop", filename, filename])
3,801
39.021053
119
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/fwsw/__init__.py
__author__ = 'robert'
22
10.5
21
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/fwsw/playground.py
from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import pySDC.core.deprecated.PFASST_stepwise as mp from pySDC.implementations.problem_classes.FastWaveSlowWave_Scalar import swfw_scalar from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order from pySDC.core import CollocationClasses as collclass from pySDC.core import Log 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 N_s = 100 N_f = 125 # This comes as read-in for the level class lparams = {} lparams['restol'] = 1e-12 sparams = {} sparams['maxiter'] = 4 # This comes as read-in for the problem class pparams = {} pparams['lambda_s'] = 1j * np.linspace(0.0, 4.0, N_s) pparams['lambda_f'] = 1j * np.linspace(0.0, 8.0, N_f) pparams['u0'] = 1 # Fill description dictionary for easy hierarchy creation description = {} description['problem_class'] = swfw_scalar description['problem_params'] = pparams description['collocation_class'] = collclass.CollGaussLobatto description['num_nodes'] = [3] description['do_LU'] = False description['sweeper_class'] = imex_1st_order description['level_params'] = lparams # quickly generate block of steps MS = mp.generate_steps(num_procs, sparams, description) # setup parameters "in time" t0 = 0 dt = 1.0 Tend = 1.0 P = MS[0].levels[0].prob uinit = P.u_exact(t0) print('Init:', uinit.values) # call main function to get things done... uend, stats = mp.run_pfasst(MS, u0=uinit, t0=t0, dt=dt, Tend=Tend) uex = P.u_exact(Tend) fig = plt.figure(figsize=(4, 4)) # pcol = plt.pcolor(pparams['lambda_s'].imag, pparams['lambda_f'].imag, np.absolute(uend.values).T, vmin=0.99, vmax=1.01) pcol = plt.pcolor( pparams['lambda_s'].imag, pparams['lambda_f'].imag, np.absolute(uend.values).T, vmin=1.0, vmax=2.0 ) # plt.pcolor(np.imag(uend.values)) pcol.set_edgecolor('face') plt.plot([0, 4], [0, 4], color='w', linewidth=2.5) # plt.colorbar() plt.gca().set_xticks([0.0, 1.0, 2.0, 3.0]) plt.xlabel('$\Delta t \lambda_{slow}$', fontsize=18, labelpad=0.0) plt.ylabel('$\Delta t \lambda_{fast}$', fontsize=18) # plt.show() fig.savefig( 'sdc-fwsw-stability-K' + str(sparams['maxiter']) + '-M' + str(description['num_nodes'][0]) + '.pdf', bbox_inches='tight', ) print( 'error at time %s: %s' % (Tend, np.linalg.norm(uex.values - uend.values, np.inf) / np.linalg.norm(uex.values, np.inf)) )
2,696
30.360465
125
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/playground_datatypes.py
from dedalus import public as de from dedalus import core import numpy as np import matplotlib.pyplot as plt import time from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field class wrapper(core.field.Field): def __abs__(self): abs = super(wrapper, self).__abs__() while hasattr(abs, 'evaluate'): abs = abs.evaluate() print(type(abs), self) return np.amax(abs['g']) mytype = core.field.Field de.logging_setup.rootlogger.setLevel('INFO') xbasis = de.Fourier('x', 1024, interval=(0, 1), dealias=1) domain = de.Domain([xbasis], grid_dtype=np.float64, comm=None) print(domain.global_grid_shape(), domain.local_grid_shape()) x = domain.grid(0, scales=1) d1 = dedalus_field(domain) d1.values['g'] = np.sin(2 * np.pi * x) d2 = dedalus_field(domain) d2.values['g'] = np.sin(2 * np.pi * x) print((d1 + d2).values['g']) d1 = mytype(domain) d1['g'] = np.sin(2 * np.pi * x) d2 = mytype(domain) d2['g'] = np.sin(2 * np.pi * x) print((d1 + d2).evaluate()['g']) print((d1 - d2).evaluate()['g']) print((2.0 * d2).evaluate()['g']) print(np.amax(abs(d2).evaluate()['g'])) d1 = wrapper(domain) d1['g'] = np.sin(2 * np.pi * x) d2 = wrapper(domain) d2['g'] = np.sin(2 * np.pi * x) print((d1 + d2).evaluate()['g']) print((d1 - d2).evaluate()['g']) print((2.0 * d2).evaluate()['g']) print(abs(d2)) print(np.amax(abs(d1 + d2).evaluate()['g'])) # print(np.amax(abs(d2).evaluate()['g'])) exit() g = domain.new_field() g['g'] = np.sin(2 * np.pi * x) t0 = time.perf_counter() for i in range(10000): f = domain.new_field() f['g'] = g['g'] + g['g'] # f['c'][:] = g['c'][:] t1 = time.perf_counter() print(t1 - t0) t0 = time.perf_counter() for i in range(10000): f = (g + g).evaluate() # f['c'][:] = g['c'][:] t1 = time.perf_counter() print(t1 - t0) t0 = time.perf_counter() for i in range(10000): f = np.zeros(tuple(domain.global_grid_shape())) f = g['g'] + g['g'] # f['c'] = g['c'] t1 = time.perf_counter() print(t1 - t0) t0 = time.perf_counter() for i in range(10000): # f = wrapper(domain) f = g + g # f['c'] = g['c'] t1 = time.perf_counter() print(t1 - t0) # fxx = xbasis.Differentiate(f) # # g = de.operators.FieldCopyField(f).evaluate() # # print((f + g).evaluate()) # # # f['g'][:] = 1.0 # print(f['g'], g['g']) # print(f, g)
2,333
20.027027
65
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/Dynamo_2D_Dedalus_NEW.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh class dynamo_2d_dedalus(ptype): """ """ def __init__(self, problem_params, dtype_u=mesh, dtype_f=imex_mesh): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'Rm', 'kz', 'comm', 'initial'] 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) xbasis = de.Fourier('x', problem_params['nvars'][0], interval=(0, 2 * np.pi), dealias=1) ybasis = de.Fourier('y', problem_params['nvars'][1], interval=(0, 2 * np.pi), dealias=1) self.domain = de.Domain([xbasis, ybasis], grid_dtype=np.complex128, comm=problem_params['comm']) nvars = tuple(self.domain.local_grid_shape()) + (2,) # invoke super init, passing number of dofs (and more), dtype_u and dtype_f super(dynamo_2d_dedalus, self).__init__( init=(nvars, self.domain.dist.comm, xbasis.grid_dtype), dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params, ) self.x = self.domain.grid(0, scales=1) self.y = self.domain.grid(1, scales=1) imp_var = ['b_x', 'b_y'] self.problem_imp = de.IVP(domain=self.domain, variables=imp_var) self.problem_imp.parameters['Rm'] = self.params.Rm self.problem_imp.parameters['kz'] = self.params.kz self.problem_imp.add_equation("dt(b_x) - (1/Rm) * ( dx(dx(b_x)) + dy(dy(b_x)) - kz ** 2 * (b_x) ) = 0") self.problem_imp.add_equation("dt(b_y) - (1/Rm) * ( dx(dx(b_y)) + dy(dy(b_y)) - kz ** 2 * (b_y) ) = 0") self.solver_imp = self.problem_imp.build_solver(de.timesteppers.SBDF1) self.imp_var = [] for l in range(self.init[0][-1]): self.imp_var.append(self.solver_imp.state[imp_var[l]]) exp_var = ['b_x', 'b_y'] self.problem_exp = de.IVP(domain=self.domain, variables=exp_var) self.problem_exp.parameters['Rm'] = self.params.Rm self.problem_exp.parameters['kz'] = self.params.kz self.problem_exp.substitutions['u_x'] = 'cos(y)' self.problem_exp.substitutions['u_y'] = 'sin(x)' self.problem_exp.substitutions['u_z'] = 'cos(x) + sin(y)' self.problem_exp.add_equation("dt(b_x) = -u_x * dx(b_x) - u_y * dy(b_x) - u_z*1j*kz *b_x + b_y * dy(u_x)") self.problem_exp.add_equation("dt(b_y) = -u_x * dx(b_y) - u_y * dy(b_y) - u_z*1j*kz *b_y + b_x * dx(u_y)") self.solver_exp = self.problem_exp.build_solver(de.timesteppers.SBDF1) self.exp_var = [] for l in range(self.init[0][-1]): self.exp_var.append(self.solver_exp.state[exp_var[l]]) def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ pseudo_dt = 1e-05 f = self.dtype_f(self.init) for l in range(self.init[0][-1]): self.exp_var[l]['g'] = u[..., l] self.solver_exp.step(pseudo_dt) for l in range(self.init[0][-1]): self.exp_var[l].set_scales(1) f.expl[..., l] = 1.0 / pseudo_dt * (self.exp_var[l]['g'] - u[..., l]) for l in range(self.init[0][-1]): self.imp_var[l]['g'] = u[..., l] self.solver_imp.step(pseudo_dt) for l in range(self.init[0][-1]): f.impl[..., l] = 1.0 / pseudo_dt * (self.imp_var[l]['g'] - u[..., l]) return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as mesh """ me = self.dtype_u(self.init) for l in range(self.init[0][-1]): self.imp_var[l]['g'] = rhs[..., l] self.solver_imp.step(factor) for l in range(self.init[0][-1]): me[..., l] = self.imp_var[l]['g'] 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 """ xvar_loc = self.x.shape[0] yvar_loc = self.y.shape[1] np.random.seed(0) me = self.dtype_u(self.init) if self.params.initial == 'random': me[..., 0] = np.random.uniform(low=-1e-5, high=1e-5, size=(xvar_loc, yvar_loc)) me[..., 1] = np.random.uniform(low=-1e-5, high=1e-5, size=(xvar_loc, yvar_loc)) elif self.params.initial == 'low-res': tmp0 = self.domain.new_field() tmp1 = self.domain.new_field() tmp0['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(xvar_loc, yvar_loc)) tmp1['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(xvar_loc, yvar_loc)) tmp0.set_scales(4.0 / self.params.nvars[0]) # Need to do that because otherwise Dedalus tries to be clever.. tmpx = tmp0['g'] tmp1.set_scales(4.0 / self.params.nvars[1]) # Need to do that because otherwise Dedalus tries to be clever.. tmpy = tmp1['g'] tmp0.set_scales(1) tmp1.set_scales(1) me[..., 0] = tmp0['g'] me[..., 1] = tmp1['g'] return me
6,341
34.038674
115
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/DynamoGP_2D_Dedalus.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field, rhs_imex_dedalus_field class dynamogp_2d_dedalus(ptype): """ """ def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'Rm', 'kx', 'comm', 'initial'] 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) ybasis = de.Fourier('y', problem_params['nvars'][0], interval=(0, 2 * np.pi), dealias=1) zbasis = de.Fourier('z', problem_params['nvars'][1], interval=(0, 2 * np.pi), dealias=1) domain = de.Domain([ybasis, zbasis], grid_dtype=np.complex128, comm=problem_params['comm']) # invoke super init, passing number of dofs, dtype_u and dtype_f super(dynamogp_2d_dedalus, self).__init__( init=(domain, 2), dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params ) self.y = self.init[0].grid(0, scales=1) self.z = self.init[0].grid(1, scales=1) self.rhs = self.dtype_u(self.init, val=0.0) self.problem = de.IVP(domain=self.init[0], variables=['bz', 'by']) self.problem.parameters['Rm'] = self.params.Rm self.problem.parameters['kx'] = self.params.kx self.problem.add_equation("dt(bz) - (1/Rm) * ( dz(dz(bz)) + dy(dy(bz)) - kx ** 2 * (bz) ) = 0") self.problem.add_equation("dt(by) - (1/Rm) * ( dz(dz(by)) + dy(dy(by)) - kx ** 2 * (by) ) = 0") self.solver = self.problem.build_solver(de.timesteppers.SBDF1) self.bz = self.solver.state['bz'] self.by = self.solver.state['by'] self.u = domain.new_field() self.v = domain.new_field() self.w = domain.new_field() self.v_z = domain.new_field() self.w_y = domain.new_field() def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ f = self.dtype_f(self.init) A = np.sqrt(3 / 2) C = np.sqrt(3 / 2) self.u['g'] = A * np.sin(self.z + np.sin(t)) + C * np.cos(self.y + np.cos(t)) self.v['g'] = A * np.cos(self.z + np.sin(t)) self.w['g'] = C * np.sin(self.y + np.cos(t)) self.v_z['g'] = self.v.differentiate(z=1)['g'] self.w_y['g'] = self.w.differentiate(y=1)['g'] by_y = u.values[0].differentiate(y=1) by_z = u.values[0].differentiate(z=1) bz_y = u.values[1].differentiate(y=1) bz_z = u.values[1].differentiate(z=1) f.expl.values[0] = ( -self.u * u.values[0] * 1j * self.params.kx - self.v * by_y - self.w * by_z + u.values[1] * self.v_z ).evaluate() f.expl.values[1] = ( -self.u * u.values[1] * 1j * self.params.kx - self.v * bz_y - self.w * bz_z + u.values[0] * self.w_y ).evaluate() f.impl.values[0] = ( 1.0 / self.params.Rm * (u.values[0].differentiate(z=2) + u.values[0].differentiate(y=2) - self.params.kx**2 * u.values[0]) ).evaluate() f.impl.values[1] = ( 1.0 / self.params.Rm * (u.values[1].differentiate(z=2) + u.values[1].differentiate(y=2) - self.params.kx**2 * u.values[1]) ).evaluate() return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as mesh """ self.bz['g'] = rhs.values[1]['g'] self.bz['c'] = rhs.values[1]['c'] self.by['g'] = rhs.values[0]['g'] self.by['c'] = rhs.values[0]['c'] self.solver.step(factor) me = self.dtype_u(self.init) me.values[1]['g'] = self.bz['g'] me.values[1]['c'] = self.bz['c'] me.values[0]['g'] = self.by['g'] me.values[0]['c'] = self.by['c'] 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 """ yvar_loc = self.y.shape[0] zvar_loc = self.z.shape[1] np.random.seed(0) me = self.dtype_u(self.init) if self.params.initial == 'random': me.values[0]['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) me.values[1]['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) elif self.params.initial == 'low-res': me.values[0]['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) me.values[1]['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) me.values[0].set_scales(4.0 / self.params.nvars[0]) # Need to do that because otherwise Dedalus tries to be clever.. tmpx = me.values[0]['g'] me.values[1].set_scales(4.0 / self.params.nvars[1]) # Need to do that because otherwise Dedalus tries to be clever.. tmpy = me.values[1]['g'] me.values[0].set_scales(1) me.values[1].set_scales(1) return me
6,289
34.337079
113
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/periodic_playground_parallel.py
import numpy as np import matplotlib.pyplot as plt 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.Dedalus.TransferDedalusFields import dedalus_field_transfer from pySDC.playgrounds.Dedalus.HeatEquation_1D_Dedalus_forced import heat1d_dedalus_forced def main(): """ A simple test program to do PFASST runs for the heat equation """ # set MPI communicator comm = MPI.COMM_WORLD world_rank = comm.Get_rank() # split world communicator to create space-communicators color = int(world_rank / 1) space_comm = comm.Split(color=color) space_size = space_comm.Get_size() space_rank = space_comm.Get_rank() # initialize level parameters level_params = dict() level_params['restol'] = 1e-08 level_params['dt'] = 1.0 / 4 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['spread'] = False # 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'] = [16, 4] # number of degrees of freedom for each level problem_params['comm'] = space_comm # initialize step parameters step_params = dict() step_params['maxiter'] = 10 # initialize controller parameters controller_params = dict() controller_params['logger_level'] = 20 # controller_params['hook_class'] = error_output # fill description dictionary for easy step instantiation description = dict() description['problem_class'] = heat1d_dedalus_forced 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'] = dedalus_field_transfer # 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=comm) # get initial values on finest level P = controller.S.levels[0].prob uinit = P.u_exact(t0) # call main function to get things done... uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend) # compute exact solution and compare uex = P.u_exact(Tend) err = abs(uex - uend) # filter statistics by type (number of iterations) iter_counts = get_sorted(stats, type='niter', sortby='time') # compute and print statistics for item in iter_counts: out = 'Number of iterations for time %4.2f: %2i' % item print(out) # niters = np.array([item[1] for item in iter_counts]) # out = ' Mean number of iterations: %4.2f' % np.mean(niters) # print(out) # # out = ' Range of values for number of iterations: %2i ' % np.ptp(niters) # # print(out) # out = ' Position of max/min number of iterations: %2i -- %2i' % \ # (int(np.argmax(niters)), int(np.argmin(niters))) # print(out) # out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters))) # print(out) print('CFL number: %4.2f' % (level_params['dt'] * problem_params['nu'] / (1.0 / problem_params['nvars'][0]) ** 2)) print('Error: %8.4e' % err) if __name__ == "__main__": main()
4,047
35.142857
118
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/TransferDedalusFields.py
import numpy as np from pySDC.core.Errors import TransferError from pySDC.core.SpaceTransfer import space_transfer from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh class dedalus_field_transfer(space_transfer): """ Custon base_transfer class, implements Transfer.py This implementation can restrict and prolong between 1d meshes with FFT for periodic boundaries Attributes: ratio: ratio between fine and coarse level """ def __init__(self, fine_prob, coarse_prob, params): """ Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators """ # invoke super initialization super(dedalus_field_transfer, self).__init__(fine_prob, coarse_prob, params) self.ratio = list(fine_prob.domain.global_grid_shape() / coarse_prob.domain.global_grid_shape()) assert self.ratio.count(self.ratio[0]) == len(self.ratio) def restrict(self, F): """ Restriction implementation Args: F: the fine level data (easier to access than via the fine attribute) """ if isinstance(F, mesh): G = self.coarse_prob.dtype_u(self.coarse_prob.init) for l in range(self.coarse_prob.init[0][-1]): FG = self.fine_prob.domain.new_field() FG['g'] = F[..., l] FG.set_scales(scales=1.0 / self.ratio[0]) G[..., l] = FG['g'] elif isinstance(F, imex_mesh): G = self.coarse_prob.dtype_f(self.coarse_prob.init) for l in range(self.fine_prob.init[0][-1]): FG = self.fine_prob.domain.new_field() FG['g'] = F.impl[..., l] FG.set_scales(scales=1.0 / self.ratio[0]) G.impl[..., l] = FG['g'] FG = self.fine_prob.domain.new_field() FG['g'] = F.expl[..., l] FG.set_scales(scales=1.0 / self.ratio[0]) G.expl[..., l] = FG['g'] else: raise TransferError('Unknown data type, got %s' % type(F)) return G def prolong(self, G): """ Prolongation implementation Args: G: the coarse level data (easier to access than via the coarse attribute) """ if isinstance(G, mesh): F = self.fine_prob.dtype_u(self.fine_prob.init) for l in range(self.fine_prob.init[0][-1]): GF = self.coarse_prob.domain.new_field() GF['g'] = G[..., l] GF.set_scales(scales=self.ratio[0]) F[..., l] = GF['g'] elif isinstance(G, imex_mesh): F = self.fine_prob.dtype_f(self.fine_prob.init) for l in range(self.coarse_prob.init[0][-1]): GF = self.coarse_prob.domain.new_field() GF['g'] = G.impl[..., l] GF.set_scales(scales=self.ratio[0]) F.impl[..., l] = GF['g'] GF = self.coarse_prob.init[0].new_field() GF['g'] = G.expl[..., l] GF.set_scales(scales=self.ratio[0]) F.expl[..., l] = GF['g'] else: raise TransferError('Unknown data type, got %s' % type(G)) return F
3,367
35.608696
104
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/RayleighBenard_monitor.py
import numpy as np import matplotlib.pyplot as plt from pySDC.core.Hooks import hooks class monitor(hooks): def __init__(self): super(monitor, self).__init__() self.imshow = None def pre_run(self, step, level_number): """ Overwrite standard post step hook Args: step (pySDC.Step.step): the current step level_number (int): the current level number """ super(monitor, self).pre_run(step, level_number) # some abbreviations L = step.levels[0] # self.imshow = plt.imshow(L.u[0].values[0]['g']) # # self.plt.colorbar() # # self.plt.pause(0.001) # plt.draw() # plt.pause(0.001) 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] # # self.imshow.set_data(L.uend.values[0]['g']) # plt.draw() # plt.pause(0.0001) u_max = np.amax(abs(L.uend.values[1]['g'])) print(u_max)
1,266
23.365385
58
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/AllenCahn_2D_Dedalus_new.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError from pySDC.playgrounds.Dedalus.dedalus_field_new import dedalus_field, rhs_imex_dedalus_field class allencahn2d_dedalus(ptype): """ Example implementing the 2D Allen-Cahn equation with periodic BC in [-L/2,L/2]^2, discretized using Dedalus """ def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None if 'L' not in problem_params: problem_params['L'] = 1.0 if 'init_type' not in problem_params: problem_params['init_type'] = 'circle' # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'nu', 'eps', 'L', 'radius', 'comm', 'init_type'] 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) L = problem_params['L'] xbasis = de.Fourier('x', problem_params['nvars'][0], interval=(-L / 2, L / 2), dealias=1) ybasis = de.Fourier('y', problem_params['nvars'][1], interval=(-L / 2, L / 2), dealias=1) domain = de.Domain([xbasis, ybasis], grid_dtype=np.float64, comm=problem_params['comm']) # invoke super init, passing number of dofs, dtype_u and dtype_f super(allencahn2d_dedalus, self).__init__(init=domain, dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params) self.x = self.init.grid(0, scales=1) self.y = self.init.grid(1, scales=1) self.rhs = self.dtype_u(self.init) linear_problem = de.IVP(domain=self.init, variables=['u']) linear_problem.add_equation("dt(u) - dx(dx(u)) - dy(dy(u)) = 0") self.solver = linear_problem.build_solver(de.timesteppers.SBDF1) self.u = self.solver.state['u'] self.f = domain.new_field() self.fxx = xbasis.Differentiate(xbasis.Differentiate(self.f)) + ybasis.Differentiate( ybasis.Differentiate(self.f) ) self.dx = L / len(self.x) self.nvars = (len(self.x), len(self.y)) def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ f = self.dtype_f(self.init) self.f['g'] = u.values['g'] self.f['c'] = u.values['c'] f.impl.values = self.fxx.evaluate() if self.params.eps > 0: f.expl.values['g'] = 1.0 / self.params.eps**2 * u.values['g'] * (1.0 - u.values['g'] ** self.params.nu) else: raise NotImplementedError() return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as Dedalus field """ self.u['g'] = rhs.values['g'] self.u['c'] = rhs.values['c'] self.solver.step(factor) me = self.dtype_u(self.init) me.values['g'] = self.u['g'] # uxx = (de.operators.differentiate(self.u, x=2) + de.operators.differentiate(self.u, y=2)).evaluate() # print(np.amax(abs(self.u['g'] - factor * uxx['g'] - rhs.values['g']))) return me def u_exact(self, t): """ Routine to compute the exact solution at time t Args: t (float): current time Returns: dtype_u: exact solution """ assert t == 0, 'ERROR: u_exact only valid for t=0' me = self.dtype_u(self.init, val=0.0) if self.params.init_type == 'circle': # xv, yv = np.meshgrid(self.x, self.y, indexing='ij') me.values['g'] = np.tanh( (self.params.radius - np.sqrt(self.x**2 + self.y**2)) / (np.sqrt(2) * self.params.eps) ) elif self.params.init_type == 'checkerboard': me.values['g'] = np.sin(2.0 * np.pi * self.x) * np.sin(2.0 * np.pi * self.y) elif self.params.init_type == 'random': me.values['g'] = np.random.uniform(-1, 1, self.init) else: raise NotImplementedError('type of initial value not implemented, got %s' % self.params.init_type) return me
5,075
35.517986
119
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/DynamoGP_2D_Dedalus_NEW.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh class dynamogp_2d_dedalus(ptype): """ """ def __init__(self, problem_params, dtype_u=mesh, dtype_f=imex_mesh): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'Rm', 'kx', 'comm', 'initial'] 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) ybasis = de.Fourier('y', problem_params['nvars'][0], interval=(0, 2 * np.pi), dealias=1) zbasis = de.Fourier('z', problem_params['nvars'][1], interval=(0, 2 * np.pi), dealias=1) self.domain = de.Domain([ybasis, zbasis], grid_dtype=np.complex128, comm=problem_params['comm']) nvars = tuple(self.domain.local_grid_shape()) + (2,) # invoke super init, passing number of dofs (and more), dtype_u and dtype_f super(dynamogp_2d_dedalus, self).__init__( init=(nvars, self.domain.dist.comm, ybasis.grid_dtype), dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params, ) self.y = self.domain.grid(0, scales=1) self.z = self.domain.grid(1, scales=1) self.problem = de.IVP(domain=self.domain, variables=['by', 'bz']) self.problem.parameters['Rm'] = self.params.Rm self.problem.parameters['kx'] = self.params.kx self.problem.add_equation("dt(by) - (1/Rm) * ( dz(dz(by)) + dy(dy(by)) - kx ** 2 * (by) ) = 0") self.problem.add_equation("dt(bz) - (1/Rm) * ( dz(dz(bz)) + dy(dy(bz)) - kx ** 2 * (bz) ) = 0") self.solver = self.problem.build_solver(de.timesteppers.SBDF1) self.by = self.solver.state['by'] self.bz = self.solver.state['bz'] self.u = self.domain.new_field() self.v = self.domain.new_field() self.w = self.domain.new_field() self.w_y = self.domain.new_field() self.v_z = self.domain.new_field() def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ f = self.dtype_f(self.init) A = np.sqrt(3 / 2) C = np.sqrt(3 / 2) self.u['g'] = A * np.sin(self.z + np.sin(t)) + C * np.cos(self.y + np.cos(t)) self.v['g'] = A * np.cos(self.z + np.sin(t)) self.w['g'] = C * np.sin(self.y + np.cos(t)) self.w_y['g'] = self.w.differentiate(y=1)['g'] self.v_z['g'] = self.v.differentiate(z=1)['g'] self.by['g'] = u[..., 0] self.bz['g'] = u[..., 1] by_y = self.by.differentiate(y=1) by_z = self.by.differentiate(z=1) bz_y = self.bz.differentiate(y=1) bz_z = self.bz.differentiate(z=1) tmpfy = ( -self.u * self.by * 1j * self.params.kx - self.v * by_y - self.w * by_z + self.bz * self.v_z ).evaluate() f.expl[..., 0] = tmpfy['g'] tmpfz = ( -self.u * self.bz * 1j * self.params.kx - self.v * bz_y - self.w * bz_z + self.by * self.w_y ).evaluate() f.expl[..., 1] = tmpfz['g'] self.by['g'] = u[..., 0] self.bz['g'] = u[..., 1] pseudo_dt = 1e-05 self.solver.step(pseudo_dt) f.impl[..., 0] = 1.0 / pseudo_dt * (self.by['g'] - u[..., 0]) f.impl[..., 1] = 1.0 / pseudo_dt * (self.bz['g'] - u[..., 1]) return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as mesh """ self.by['g'] = rhs[..., 0] self.bz['g'] = rhs[..., 1] self.solver.step(factor) me = self.dtype_u(self.init) me[..., 0] = self.by['g'] me[..., 1] = self.bz['g'] 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 """ zvar_loc = self.z.shape[1] yvar_loc = self.y.shape[0] np.random.seed(0) me = self.dtype_u(self.init) if self.params.initial == 'random': me[..., 0] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) me[..., 1] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) elif self.params.initial == 'low-res': tmp0 = self.domain.new_field() tmp1 = self.domain.new_field() tmp0['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) tmp1['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(yvar_loc, zvar_loc)) tmp0.set_scales(4.0 / self.params.nvars[0]) # Need to do that because otherwise Dedalus tries to be clever.. tmpx = tmp0['g'] tmp1.set_scales(4.0 / self.params.nvars[1]) # Need to do that because otherwise Dedalus tries to be clever.. tmpy = tmp1['g'] tmp0.set_scales(1) tmp1.set_scales(1) me[..., 0] = tmp0['g'] me[..., 1] = tmp1['g'] return me
6,194
32.306452
104
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/HeatEquation_1D_Dedalus_forced.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError, ProblemError from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field, rhs_imex_dedalus_field class heat1d_dedalus_forced(ptype): """ Example implementing the forced 1D heat equation with periodic BC in [0,1], discretized using Dedalus """ def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'nu', 'freq', 'comm'] for key in essential_keys: if key not in problem_params: msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys())) raise ParameterError(msg) # we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on if problem_params['freq'] % 2 != 0: raise ProblemError('setup requires freq to be an equal number') xbasis = de.Fourier('x', problem_params['nvars'], interval=(0, 1), dealias=1) domain = de.Domain([xbasis], grid_dtype=np.float64, comm=problem_params['comm']) # invoke super init, passing number of dofs, dtype_u and dtype_f super(heat1d_dedalus_forced, self).__init__( init=(domain, 2), dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params ) self.x = self.init[0].grid(0, scales=1) self.rhs = self.dtype_u(self.init, val=0.0) self.problem = de.IVP(domain=self.init[0], variables=['u', 'v']) self.problem.parameters['nu'] = self.params.nu self.problem.add_equation("dt(u) - nu * dx(dx(u)) = 0") self.problem.add_equation("dt(v) - nu * dx(dx(v)) = 0") self.solver = self.problem.build_solver(de.timesteppers.SBDF1) self.u = self.solver.state['u'] self.v = self.solver.state['v'] def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ f = self.dtype_f(self.init) f.impl.values[0] = (self.params.nu * de.operators.differentiate(u.values[0], x=2)).evaluate() f.impl.values[1] = (self.params.nu * de.operators.differentiate(u.values[1], x=2)).evaluate() f.expl.values[0]['g'] = -np.sin(np.pi * self.params.freq * self.x) * ( np.sin(t) - self.params.nu * (np.pi * self.params.freq) ** 2 * np.cos(t) ) f.expl.values[1]['g'] = -np.sin(np.pi * self.params.freq * self.x) * ( np.sin(t) - self.params.nu * (np.pi * self.params.freq) ** 2 * np.cos(t) ) return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as mesh """ # u = self.solver.state['u'] self.u['g'] = rhs.values[0]['g'] self.v['g'] = rhs.values[1]['g'] self.solver.step(factor) me = self.dtype_u(self.init) me.values[0]['g'] = self.u['g'] me.values[1]['g'] = self.v['g'] return me def u_exact(self, t): """ Routine to compute the exact solution at time t Args: t (float): current time Returns: dtype_u: exact solution """ me = self.dtype_u(self.init) me.values[0]['g'] = np.sin(np.pi * self.params.freq * self.x) * np.cos(t) me.values[1]['g'] = np.sin(np.pi * self.params.freq * self.x) * np.cos(t) return me
4,418
35.221311
115
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/playground_parallel.py
from mpi4py import MPI import matplotlib matplotlib.use("TkAgg") from dedalus import public as de import numpy as np import matplotlib.pyplot as plt 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 / world_size) space_comm = comm.Split(color=color) space_size = space_comm.Get_size() space_rank = space_comm.Get_rank() de.logging_setup.rootlogger.setLevel('INFO') xbasis = de.Fourier('x', 128, interval=(0, 1), dealias=1) ybasis = de.Fourier('y', 128, interval=(0, 1), dealias=1) domain = de.Domain([xbasis, ybasis], grid_dtype=np.float64, comm=space_comm) print(domain.global_grid_shape(), domain.local_grid_shape()) f = domain.new_field() g = domain.new_field() x = domain.grid(0, scales=1) y = domain.grid(1, scales=1) # g['g'] = np.cos(2*np.pi*x)*np.cos(2*np.pi*y) # # u = domain.new_field() # # xbasis_c = de.Fourier('x', 16, interval=(0, 1), dealias=1) # ybasis_c = de.Fourier('y', 16, interval=(0, 1), dealias=1) # domain_c = de.Domain([xbasis_c, ybasis_c], grid_dtype=np.float64, comm=space_comm) # # f.set_scales(0.5) # fex = domain_c.new_field() # fex['g'] = np.copy(f['g']) # # f.set_scales(1) # ff = domain.new_field() # ff['g'] = np.copy(f['g']) # ff.set_scales(scales=0.5) # # fc = domain_c.new_field() # fc['g'] = ff['g'] # # print(fc['g'].shape, fex['g'].shape) # # # # local_norm = np.linalg.norm((fc-fex).evaluate()['g']) # # if space_size == 1: # global_norm = local_norm # else: # global_norm = space_comm.allreduce(sendobj=local_norm, op=MPI.MAX) # # print(global_norm) # print(domain.distributor.comm, space_comm) # # exit() # # h = (f + g).evaluate() # # # f_x = de.operators.differentiate(h, x=2).evaluate() dt = 0.1 / 32 Tend = 1.0 nsteps = int(Tend / dt) uex = domain.new_field() uex['g'] = np.sin(2 * np.pi * x) * np.sin(2 * np.pi * y) * np.cos(Tend) problem = de.IVP(domain=domain, variables=['u']) problem.add_equation("dt(u) - dx(dx(u)) - dy(dy(u)) = 0") ts = de.timesteppers.SBDF1 solver = problem.build_solver(ts) u = solver.state['u'] # tmp = np.tanh((0.25 - np.sqrt((x - 0.5) ** 2 + (y - 0.5) ** 2)) / (np.sqrt(2) * 0.04)) # tmp = # print(tmp) u['g'] = np.tanh((0.25 - np.sqrt((x - 0.5) ** 2 + (y - 0.5) ** 2)) / (np.sqrt(2) * 0.04)) u_old = domain.new_field() u_old['g'] = u['g'] t = 0.0 for n in range(nsteps): # u['g'] = u['g'] - dt * np.sin(np.pi * 2 * x) * np.sin(2*np.pi*y) * (np.sin(t) - 2.0 * (np.pi * 2) ** 2 * np.cos(t)) solver.step(dt) t += dt uxx = (de.operators.differentiate(u, x=2) + de.operators.differentiate(u, y=2)).evaluate() print(np.amax(abs(u['g'] - dt * uxx['g'] - u_old['g']))) exit() # print(t, nsteps) local_norm = np.amax(abs(u['g'] - uex['g'])) if space_size == 1: global_norm = local_norm else: global_norm = space_comm.allreduce(sendobj=local_norm, op=MPI.MAX) print(local_norm, global_norm) # print(np.linalg.norm(u['g']-uex['g'], np.inf)) # xx, yy = np.meshgrid(x, y) # # plt.figure(1) # # # plt.contourf(xx, yy, u['g'].T, 50) # plt.colorbar() # # plt.figure(2) # plt.contourf(xx, yy, uex['g'].T,50) # plt.colorbar() # # plt.figure(3) # # plt.plot(u['g'][8,:]) # # plt.plot(uex['g'][8,:]) # # # # plt.show(1)
3,250
23.628788
121
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/Dynamo_monitor.py
import numpy as np from pySDC.core.Hooks import hooks class monitor(hooks): def pre_run(self, step, level_number): """ Overwrite standard post step hook Args: step (pySDC.Step.step): the current step level_number (int): the current level number """ super(monitor, self).pre_run(step, level_number) # some abbreviations L = step.levels[0] bx_max = np.amax(abs(L.u[0][..., 0])) # bx_max = np.amax(abs(L.u[0].values[0]['g'])) self.add_to_stats( process=step.status.slot, time=L.time, level=-1, iter=step.status.iter, sweep=L.status.sweep, type='bx_max', value=bx_max, ) 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] bx_max = np.amax(abs(L.uend[..., 0])) # bx_max = np.amax(abs(L.uend.values[0]['g'])) self.add_to_stats( process=step.status.slot, time=L.time + L.dt, level=-1, iter=step.status.iter, sweep=L.status.sweep, type='bx_max', value=bx_max, )
1,481
24.551724
58
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/HeatEquation_2D_Dedalus_forced.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError, ProblemError from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field, rhs_imex_dedalus_field class heat2d_dedalus_forced(ptype): """ Example implementing the forced 2D heat equation with periodic BC in [0,1], discretized using Dedalus """ def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'nu', 'freq', 'comm'] for key in essential_keys: if key not in problem_params: msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys())) raise ParameterError(msg) # we assert that nvars looks very particular here.. this will be necessary for coarsening in space later on if problem_params['freq'] % 2 != 0: raise ProblemError('setup requires freq to be an equal number') xbasis = de.Fourier('x', problem_params['nvars'][0], interval=(0, 1), dealias=1) ybasis = de.Fourier('y', problem_params['nvars'][1], interval=(0, 1), dealias=1) domain = de.Domain([xbasis, ybasis], grid_dtype=np.float64, comm=problem_params['comm']) # invoke super init, passing number of dofs, dtype_u and dtype_f super(heat2d_dedalus_forced, self).__init__( init=domain, dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params ) self.x = self.init.grid(0, scales=1) self.y = self.init.grid(1, scales=1) self.rhs = self.dtype_u(self.init, val=0.0) self.problem = de.IVP(domain=self.init, variables=['u']) self.problem.parameters['nu'] = self.params.nu self.problem.add_equation("dt(u) - nu * dx(dx(u)) - nu * dy(dy(u)) = 0") self.solver = self.problem.build_solver(de.timesteppers.SBDF1) self.u = self.solver.state['u'] def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ f = self.dtype_f(self.init) f.impl.values = ( self.params.nu * de.operators.differentiate(u.values, x=2) + self.params.nu * de.operators.differentiate(u.values, y=2) ).evaluate() f.expl.values['g'] = ( -np.sin(np.pi * self.params.freq * self.x) * np.sin(np.pi * self.params.freq * self.y) * (np.sin(t) - 2.0 * self.params.nu * (np.pi * self.params.freq) ** 2 * np.cos(t)) ) return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as mesh """ # u = self.solver.state['u'] self.u['g'] = rhs.values['g'] self.u['c'] = rhs.values['c'] self.solver.step(factor) me = self.dtype_u(self.init) me.values['g'] = self.u['g'] return me def u_exact(self, t): """ Routine to compute the exact solution at time t Args: t (float): current time Returns: dtype_u: exact solution """ me = self.dtype_u(self.init) me.values['g'] = ( np.sin(np.pi * self.params.freq * self.x) * np.sin(np.pi * self.params.freq * self.y) * np.cos(t) ) return me
4,280
33.804878
115
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/AllenCahn_2D_Dedalus.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field, rhs_imex_dedalus_field class allencahn2d_dedalus(ptype): """ Example implementing the 2D Allen-Cahn equation with periodic BC in [-L/2,L/2]^2, discretized using Dedalus """ def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None if 'L' not in problem_params: problem_params['L'] = 1.0 if 'init_type' not in problem_params: problem_params['init_type'] = 'circle' # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'nu', 'eps', 'L', 'radius', 'comm', 'init_type'] 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) L = problem_params['L'] xbasis = de.Fourier('x', problem_params['nvars'][0], interval=(-L / 2, L / 2), dealias=1) ybasis = de.Fourier('y', problem_params['nvars'][1], interval=(-L / 2, L / 2), dealias=1) domain = de.Domain([xbasis, ybasis], grid_dtype=np.float64, comm=problem_params['comm']) # invoke super init, passing number of dofs, dtype_u and dtype_f super(allencahn2d_dedalus, self).__init__(init=domain, dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params) self.x = self.init.grid(0, scales=1) self.y = self.init.grid(1, scales=1) self.rhs = self.dtype_u(self.init) linear_problem = de.IVP(domain=self.init, variables=['u']) linear_problem.add_equation("dt(u) - dx(dx(u)) - dy(dy(u)) = 0") self.solver = linear_problem.build_solver(de.timesteppers.SBDF1) self.u = self.solver.state['u'] self.f = domain.new_field() self.fxx = xbasis.Differentiate(xbasis.Differentiate(self.f)) + ybasis.Differentiate( ybasis.Differentiate(self.f) ) self.dx = L / len(self.x) self.nvars = (len(self.x), len(self.y)) def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ f = self.dtype_f(self.init) self.f['g'] = u.values['g'] self.f['c'] = u.values['c'] f.impl.values = self.fxx.evaluate() if self.params.eps > 0: f.expl.values['g'] = 1.0 / self.params.eps**2 * u.values['g'] * (1.0 - u.values['g'] ** self.params.nu) else: raise NotImplementedError() return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as Dedalus field """ self.u['g'] = rhs.values['g'] self.u['c'] = rhs.values['c'] self.solver.step(factor) me = self.dtype_u(self.init) me.values['g'] = self.u['g'] # uxx = (de.operators.differentiate(self.u, x=2) + de.operators.differentiate(self.u, y=2)).evaluate() # print(np.amax(abs(self.u['g'] - factor * uxx['g'] - rhs.values['g']))) return me def u_exact(self, t): """ Routine to compute the exact solution at time t Args: t (float): current time Returns: dtype_u: exact solution """ assert t == 0, 'ERROR: u_exact only valid for t=0' me = self.dtype_u(self.init, val=0.0) if self.params.init_type == 'circle': # xv, yv = np.meshgrid(self.x, self.y, indexing='ij') me.values['g'] = np.tanh( (self.params.radius - np.sqrt(self.x**2 + self.y**2)) / (np.sqrt(2) * self.params.eps) ) elif self.params.init_type == 'checkerboard': me.values['g'] = np.sin(2.0 * np.pi * self.x) * np.sin(2.0 * np.pi * self.y) elif self.params.init_type == 'random': me.values['g'] = np.random.uniform(-1, 1, self.init) else: raise NotImplementedError('type of initial value not implemented, got %s' % self.params.init_type) return me
5,071
35.489209
119
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/rayleighbenard_playground.py
import numpy as np import sys import matplotlib.pyplot as plt 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.Dedalus.TransferDedalusFields import dedalus_field_transfer from pySDC.playgrounds.Dedalus.RayleighBenard_2D_Dedalus import rayleighbenard_2d_dedalus from pySDC.playgrounds.Dedalus.RayleighBenard_monitor import monitor def main(): """ A simple test program to do PFASST runs for the heat 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'] = 0.0001 level_params['nsweeps'] = [1] # initialize sweeper parameters sweeper_params = dict() sweeper_params['quad_type'] = 'RADAU-RIGHT' # sweeper_params['collocation_class'] = EquidistantNoLeft sweeper_params['num_nodes'] = [1] 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['Ra'] = 1e05 problem_params['Pr'] = 1.0 problem_params['initial'] = 'random' problem_params['nvars'] = [(64, 32)] # number of degrees of freedom for each level problem_params['comm'] = space_comm # initialize step parameters step_params = dict() step_params['maxiter'] = 1 # step_params['errtol'] = 1E-07 # initialize controller parameters controller_params = dict() controller_params['logger_level'] = 20 if space_rank == 0 else 99 controller_params['hook_class'] = monitor # controller_params['use_iteration_estimator'] = True # fill description dictionary for easy step instantiation description = dict() description['problem_class'] = rayleighbenard_2d_dedalus 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'] = dedalus_field_transfer # description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer # set time parameters t0 = 0.0 Tend = 0.1 # 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_size == 1: # bx_maxes = get_sorted(stats, type='bx_max', sortby='time') # # times = [t0 + i * level_params['dt'] for i in range(int((Tend - t0) / level_params['dt']) + 1)] # half = int(len(times) / 2) # gr = np.polyfit(times[half::], np.log([item[1] for item in bx_maxes])[half::], 1)[0] # print("Growth rate: {:.3e}".format(gr)) # # plt.figure(3) # plt.semilogy(times, [item[1] for item in bx_maxes]) # plt.pause(0.1) if __name__ == "__main__": main()
4,363
34.193548
110
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/Dynamo_2D_Dedalus.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field, rhs_imex_dedalus_field class dynamo_2d_dedalus(ptype): """ """ def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'Rm', 'kz', 'comm', 'initial'] 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) xbasis = de.Fourier('x', problem_params['nvars'][0], interval=(0, 2 * np.pi), dealias=1) ybasis = de.Fourier('y', problem_params['nvars'][1], interval=(0, 2 * np.pi), dealias=1) domain = de.Domain([xbasis, ybasis], grid_dtype=np.complex128, comm=problem_params['comm']) # invoke super init, passing number of dofs, dtype_u and dtype_f super(dynamo_2d_dedalus, self).__init__( init=(domain, 2), dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params ) self.x = self.init[0].grid(0, scales=1) self.y = self.init[0].grid(1, scales=1) imp_var = ['b_x', 'b_y'] self.problem_imp = de.IVP(domain=self.init[0], variables=imp_var) self.problem_imp.parameters['Rm'] = self.params.Rm self.problem_imp.parameters['kz'] = self.params.kz self.problem_imp.add_equation("dt(b_x) - (1/Rm) * ( dx(dx(b_x)) + dy(dy(b_x)) - kz ** 2 * (b_x) ) = 0") self.problem_imp.add_equation("dt(b_y) - (1/Rm) * ( dx(dx(b_y)) + dy(dy(b_y)) - kz ** 2 * (b_y) ) = 0") self.solver_imp = self.problem_imp.build_solver(de.timesteppers.SBDF1) self.imp_var = [] for l in range(self.init[1]): self.imp_var.append(self.solver_imp.state[imp_var[l]]) exp_var = ['b_x', 'b_y'] self.problem_exp = de.IVP(domain=self.init[0], variables=exp_var) self.problem_exp.parameters['Rm'] = self.params.Rm self.problem_exp.parameters['kz'] = self.params.kz self.problem_exp.substitutions['u_x'] = 'cos(y)' self.problem_exp.substitutions['u_y'] = 'sin(x)' self.problem_exp.substitutions['u_z'] = 'cos(x) + sin(y)' self.problem_exp.add_equation("dt(b_x) = -u_x * dx(b_x) - u_y * dy(b_x) - u_z*1j*kz *b_x + b_y * dy(u_x)") self.problem_exp.add_equation("dt(b_y) = -u_x * dx(b_y) - u_y * dy(b_y) - u_z*1j*kz *b_y + b_x * dx(u_y)") self.solver_exp = self.problem_exp.build_solver(de.timesteppers.SBDF1) self.exp_var = [] for l in range(self.init[1]): self.exp_var.append(self.solver_exp.state[exp_var[l]]) def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ pseudo_dt = 1e-05 f = self.dtype_f(self.init) for l in range(self.init[1]): self.exp_var[l]['g'] = u.values[l]['g'] self.exp_var[l]['c'] = u.values[l]['c'] self.solver_exp.step(pseudo_dt) for l in range(self.init[1]): self.exp_var[l].set_scales(1) f.expl.values[l]['g'] = 1.0 / pseudo_dt * (self.exp_var[l]['g'] - u.values[l]['g']) f.expl.values[l]['c'] = 1.0 / pseudo_dt * (self.exp_var[l]['c'] - u.values[l]['c']) for l in range(self.init[1]): self.imp_var[l]['g'] = u.values[l]['g'] self.imp_var[l]['c'] = u.values[l]['c'] self.solver_imp.step(pseudo_dt) for l in range(self.init[1]): # self.imp_var[l].set_scales(1) f.impl.values[l]['g'] = 1.0 / pseudo_dt * (self.imp_var[l]['g'] - u.values[l]['g']) f.impl.values[l]['c'] = 1.0 / pseudo_dt * (self.imp_var[l]['c'] - u.values[l]['c']) return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as mesh """ me = self.dtype_u(self.init) for l in range(self.init[1]): self.imp_var[l]['g'] = rhs.values[l]['g'] self.imp_var[l]['c'] = rhs.values[l]['c'] self.solver_imp.step(factor) for l in range(self.init[1]): # self.imp_var[l].set_scales(1) me.values[l]['g'][:] = self.imp_var[l]['g'] me.values[l]['c'][:] = self.imp_var[l]['c'] 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 """ xvar_loc = self.x.shape[0] yvar_loc = self.y.shape[1] np.random.seed(0) me = self.dtype_u(self.init) if self.params.initial == 'random': me.values[0]['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(xvar_loc, yvar_loc)) me.values[1]['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(xvar_loc, yvar_loc)) elif self.params.initial == 'low-res': me.values[0]['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(xvar_loc, yvar_loc)) me.values[1]['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(xvar_loc, yvar_loc)) me.values[0].set_scales(4.0 / self.params.nvars[0]) # Need to do that because otherwise Dedalus tries to be clever.. tmpx = me.values[0]['g'] me.values[1].set_scales(4.0 / self.params.nvars[1]) # Need to do that because otherwise Dedalus tries to be clever.. tmpy = me.values[1]['g'] me.values[0].set_scales(1) me.values[1].set_scales(1) return me
6,674
36.290503
115
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/dynamo_playground.py
import numpy as np import sys import matplotlib.pyplot as plt 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.Dedalus.TransferDedalusFields import dedalus_field_transfer # from pySDC.playgrounds.Dedalus.Dynamo_2D_Dedalus import dynamo_2d_dedalus from pySDC.playgrounds.Dedalus.Dynamo_2D_Dedalus_NEW import dynamo_2d_dedalus from pySDC.playgrounds.Dedalus.Dynamo_monitor import monitor def main(): """ A simple test program to do PFASST runs for the heat 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'] = 0.5 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['Rm'] = 4 problem_params['kz'] = 0.45 problem_params['initial'] = 'low-res' problem_params['nvars'] = [(64, 64)] # number of degrees of freedom for each level problem_params['comm'] = space_comm # initialize step parameters step_params = dict() step_params['maxiter'] = 50 # step_params['errtol'] = 1E-07 # initialize controller parameters controller_params = dict() controller_params['logger_level'] = 20 if space_rank == 0 else 99 controller_params['hook_class'] = monitor # controller_params['use_iteration_estimator'] = True # fill description dictionary for easy step instantiation description = dict() description['problem_class'] = dynamo_2d_dedalus 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'] = dedalus_field_transfer # description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer # set time parameters t0 = 0.0 Tend = 10.0 # 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) timings = get_sorted(stats, type='timing_run', sortby='time')[0][1] print(f'Time it took to run the simulation: {timings:6.3f} seconds') if space_size == 1: bx_maxes = get_sorted(stats, type='bx_max', sortby='time') times = [t0 + i * level_params['dt'] for i in range(int((Tend - t0) / level_params['dt']) + 1)] half = int(len(times) / 2) gr = np.polyfit(times[half::], np.log([item[1] for item in bx_maxes])[half::], 1)[0] print("Growth rate: {:.3e}".format(gr)) plt.figure(3) plt.semilogy(times, [item[1] for item in bx_maxes]) plt.pause(0.1) if __name__ == "__main__": main()
4,463
34.149606
110
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/periodic_playground.py
import numpy as np import matplotlib.pyplot as plt from pySDC.helpers.stats_helper import get_sorted from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order from pySDC.playgrounds.Dedalus.TransferDedalusFields import dedalus_field_transfer from pySDC.playgrounds.Dedalus.HeatEquation_1D_Dedalus_forced import heat1d_dedalus_forced def main(): """ A simple test program to do PFASST runs for the heat equation """ # initialize level parameters level_params = dict() level_params['restol'] = 1e-08 level_params['dt'] = 1.0 / 4 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['spread'] = False # 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'] = [16, 4] # number of degrees of freedom for each level # initialize step parameters step_params = dict() step_params['maxiter'] = 10 # initialize controller parameters controller_params = dict() controller_params['logger_level'] = 20 # controller_params['hook_class'] = error_output # fill description dictionary for easy step instantiation description = dict() description['problem_class'] = heat1d_dedalus_forced 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'] = dedalus_field_transfer # description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer # set time parameters t0 = 0.0 Tend = 1.0 num_procs = 4 # instantiate controller controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description) # get initial values on finest level P = controller.MS[0].levels[0].prob uinit = P.u_exact(t0) # call main function to get things done... uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend) # compute exact solution and compare uex = P.u_exact(Tend) err = abs(uex - uend) # filter statistics by type (number of iterations) iter_counts = get_sorted(stats, type='niter', sortby='time') # compute and print statistics for item in iter_counts: out = 'Number of iterations for time %4.2f: %2i' % item print(out) niters = np.array([item[1] for item in iter_counts]) out = ' Mean number of iterations: %4.2f' % np.mean(niters) print(out) out = ' Range of values for number of iterations: %2i ' % np.ptp(niters) print(out) out = ' Position of max/min number of iterations: %2i -- %2i' % (int(np.argmax(niters)), int(np.argmin(niters))) print(out) out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters))) print(out) print('CFL number: %4.2f' % (level_params['dt'] * problem_params['nu'] / (1.0 / problem_params['nvars'][0]) ** 2)) print('Error: %8.4e' % err) if __name__ == "__main__": main()
3,690
35.544554
118
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/periodic_playground_2D.py
import numpy as np import matplotlib.pyplot as plt from pySDC.helpers.stats_helper import get_sorted from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order from pySDC.playgrounds.Dedalus.TransferDedalusFields import dedalus_field_transfer from pySDC.playgrounds.Dedalus.HeatEquation_2D_Dedalus_forced import heat2d_dedalus_forced def main(): """ A simple test program to do PFASST runs for the heat equation """ # initialize level parameters level_params = dict() level_params['restol'] = 1e-08 level_params['dt'] = 1.0 / 4 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['spread'] = False # 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'] = [(16, 16), (4, 4)] # number of degrees of freedom for each level # initialize step parameters step_params = dict() step_params['maxiter'] = 10 # initialize controller parameters controller_params = dict() controller_params['logger_level'] = 20 # controller_params['hook_class'] = error_output # fill description dictionary for easy step instantiation description = dict() description['problem_class'] = heat2d_dedalus_forced 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'] = dedalus_field_transfer # description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer # set time parameters t0 = 0.0 Tend = 1.0 num_procs = 4 # instantiate controller controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description) # get initial values on finest level P = controller.MS[0].levels[0].prob uinit = P.u_exact(t0) # call main function to get things done... uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend) # 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()
3,582
34.83
118
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/AllenCahn_monitor.py
import numpy as np from pySDC.core.Hooks import hooks class monitor(hooks): def __init__(self): """ Initialization of Allen-Cahn monitoring """ super(monitor, self).__init__() self.init_radius = None def pre_run(self, step, level_number): """ Overwrite standard pre run hook Args: step (pySDC.Step.step): the current step level_number (int): the current level number """ super(monitor, self).pre_run(step, level_number) L = step.levels[0] c = np.count_nonzero(L.u[0].values['g'] > 0.0) radius = np.sqrt(c / np.pi) * L.prob.dx radius1 = 0 rows, cols = np.where(L.u[0].values['g'] > 0.0) for r in rows: radius1 = max(radius1, abs(L.prob.x[r])) rows1 = np.where(L.u[0].values['g'][int((L.prob.nvars[0]) / 2), : int((L.prob.nvars[0]) / 2)] > -0.99) rows2 = np.where(L.u[0].values['g'][int((L.prob.nvars[0]) / 2), : int((L.prob.nvars[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 print(radius, self.init_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.values['g'] >= 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.values['g'][int((L.prob.nvars[0]) / 2), : int((L.prob.nvars[0]) / 2)] > -0.99) rows2 = np.where(L.uend.values['g'][int((L.prob.nvars[0]) / 2), : int((L.prob.nvars[0]) / 2)] < 0.99) interface_width = (rows2[0][-1] - rows1[0][0]) * L.prob.dx / L.prob.params.eps print(radius, 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='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,812
30.512397
110
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/periodic_playground_2D_parallel.py
import sys import numpy as np import matplotlib.pyplot as plt 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.Dedalus.TransferDedalusFields import dedalus_field_transfer from pySDC.playgrounds.Dedalus.HeatEquation_2D_Dedalus_forced import heat2d_dedalus_forced def main(): """ A simple test program to do PFASST runs for the heat 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'] = 1.0 / 4 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['spread'] = False # 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'] = [(16, 16), (4, 4)] # number of degrees of freedom for each level problem_params['comm'] = space_comm # initialize step parameters step_params = dict() step_params['maxiter'] = 10 # 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_dedalus_forced 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'] = dedalus_field_transfer # 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) # get initial values on finest level P = controller.S.levels[0].prob uinit = P.u_exact(t0) # call main function to get things done... uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend) # compute exact solution and compare uex = P.u_exact(Tend) err = abs(uex - uend) # filter statistics by type (number of iterations) iter_counts = get_sorted(stats, type='niter', sortby='time') if space_rank == 0: out = 'This is time-rank %i...' % time_rank print(out) # 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') out = 'Time to solution: %6.4f sec.' % timing[0][1] print(out) print('Error: %8.4e' % err) if __name__ == "__main__": main()
4,915
33.377622
120
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/AllenCahn_2D_Dedalus_multiple.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field, rhs_imex_dedalus_field class allencahn2d_dedalus(ptype): """ Example implementing the 2D Allen-Cahn equation with periodic BC in [-L/2,L/2]^2, discretized using Dedalus """ def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None if 'L' not in problem_params: problem_params['L'] = 1.0 if 'init_type' not in problem_params: problem_params['init_type'] = 'circle' # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'nu', 'eps', 'L', 'radius', 'comm', 'init_type'] 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) L = problem_params['L'] xbasis = de.Fourier('x', problem_params['nvars'][0], interval=(-L / 2, L / 2), dealias=1) ybasis = de.Fourier('y', problem_params['nvars'][1], interval=(-L / 2, L / 2), dealias=1) domain = de.Domain([xbasis, ybasis], grid_dtype=np.float64, comm=problem_params['comm']) # invoke super init, passing number of dofs, dtype_u and dtype_f super(allencahn2d_dedalus, self).__init__(init=domain, dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params) self.x = self.init.grid(0, scales=1) self.y = self.init.grid(1, scales=1) self.rhs = self.dtype_u(self.init) linear_problem = de.IVP(domain=self.init, variables=['u']) linear_problem.add_equation("dt(u) - dx(dx(u)) - dy(dy(u)) = 0") self.solver = linear_problem.build_solver(de.timesteppers.SBDF1) self.u = self.solver.state['u'] self.f = domain.new_field() self.fxx = xbasis.Differentiate(xbasis.Differentiate(self.f)) + ybasis.Differentiate( ybasis.Differentiate(self.f) ) self.dx = L / len(self.x) self.nvars = (len(self.x), len(self.y)) def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ f = self.dtype_f(self.init) self.f['g'] = u.values['g'] self.f['c'] = u.values['c'] f.impl.values = self.fxx.evaluate() if self.params.eps > 0: f.expl.values['g'] = 1.0 / self.params.eps**2 * u.values['g'] * (1.0 - u.values['g'] ** self.params.nu) else: raise NotImplementedError() return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as Dedalus field """ self.u['g'] = rhs.values['g'] self.u['c'] = rhs.values['c'] self.solver.step(factor) me = self.dtype_u(self.init) me.values['g'] = self.u['g'] # uxx = (de.operators.differentiate(self.u, x=2) + de.operators.differentiate(self.u, y=2)).evaluate() # print(np.amax(abs(self.u['g'] - factor * uxx['g'] - rhs.values['g']))) return me def u_exact(self, t): """ Routine to compute the exact solution at time t Args: t (float): current time Returns: dtype_u: exact solution """ assert t == 0, 'ERROR: u_exact only valid for t=0' me = self.dtype_u(self.init, val=0.0) if self.params.init_type == 'circle': # xv, yv = np.meshgrid(self.x, self.y, indexing='ij') me.values['g'] = np.tanh( (self.params.radius - np.sqrt(self.x**2 + self.y**2)) / (np.sqrt(2) * self.params.eps) ) elif self.params.init_type == 'checkerboard': me.values['g'] = np.sin(2.0 * np.pi * self.x) * np.sin(2.0 * np.pi * self.y) elif self.params.init_type == 'random': me.values['g'] = np.random.uniform(-1, 1, self.init) else: raise NotImplementedError('type of initial value not implemented, got %s' % self.params.init_type) return me
5,071
35.489209
119
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/dedalus_field.py
import numpy as np from mpi4py import MPI from dedalus import public as de from pySDC.core.Errors import DataError class dedalus_field(object): """ Dedalus data type This data type can be used whenever structured data with a single unknown per point in space is required Attributes: values: contains the domain field domain: contains the domain """ def __init__(self, init=None, val=None): """ Initialization routine Args: init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested) or another mesh object val: initial value (default: None) Raises: DataError: if init is none of the types above """ # if init is another mesh, do a deepcopy (init by copy) if isinstance(init, de.Domain): self.values = [init.new_field()] elif isinstance(init, type(self)): self.values = [] for f in init.values: self.values.append(f.domain.new_field()) self.values[-1]['g'] = f['g'] self.values[-1]['c'] = f['c'] elif isinstance(init, tuple): self.values = [] for i in range(init[1]): self.values.append(init[0].new_field()) # elif isinstance(init, type(self)): # if hasattr(init, 'values'): # self.values = init.values.domain.new_field() # self.values['g'] = init.values['g'] # elif hasattr(init, 'list_of_values'): # self.list_of_values = [] # for f in init.list_of_values: # self.list_of_values.append(f.domain.new_field()) # self.list_of_values[-1]['g'] = f['g'] # else: # raise DataError('something went really wrong during %s initialization' % type(self)) # elif isinstance(init, tuple): # self.list_of_values = [] # for i in range(init[0]): # self.list_of_values.append(init[1].new_field()) else: raise DataError('something went wrong during %s initialization' % type(self)) def __add__(self, other): """ Overloading the addition operator for mesh types Args: other (mesh.mesh): mesh object to be added Raises: DataError: if other is not a mesh object Returns: mesh.mesh: sum of caller and other values (self+other) """ if isinstance(other, type(self)): # always create new mesh, since otherwise c = a + b changes a as well! me = dedalus_field(other) for l in range(len(me.values)): me.values[l]['g'] = self.values[l]['g'] + other.values[l]['g'] me.values[l]['c'] = self.values[l]['c'] + other.values[l]['c'] return me else: raise DataError("Type error: cannot add %s to %s" % (type(other), type(self))) def __sub__(self, other): """ Overloading the subtraction operator for mesh types Args: other (mesh.mesh): mesh object to be subtracted Raises: DataError: if other is not a mesh object Returns: mesh.mesh: differences between caller and other values (self-other) """ if isinstance(other, type(self)): # always create new mesh, since otherwise c = a - b changes a as well! me = dedalus_field(other) for l in range(len(me.values)): me.values[l]['g'] = self.values[l]['g'] - other.values[l]['g'] me.values[l]['c'] = self.values[l]['c'] - other.values[l]['c'] return me else: raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self))) def __rmul__(self, other): """ Overloading the right multiply by factor operator for mesh types Args: other (float): factor Raises: DataError: is other is not a float Returns: mesh.mesh: copy of original values scaled by factor """ if isinstance(other, float): # always create new mesh, since otherwise c = a * factor changes a as well! me = dedalus_field(self) for l in range(len(me.values)): me.values[l]['g'] = other * self.values[l]['g'] me.values[l]['c'] = other * self.values[l]['c'] return me else: raise DataError("Type error: cannot multiply %s to %s" % (type(other), type(self))) def __abs__(self): """ Overloading the abs operator for mesh types Returns: float: absolute maximum of all mesh values """ # take absolute values of the mesh values local_absval = np.amax([abs(f['g']) for f in self.values]) comm = self.values[0].domain.distributor.comm if comm is not None: if comm.Get_size() > 1: global_absval = comm.allreduce(sendobj=local_absval, op=MPI.MAX) else: global_absval = local_absval else: global_absval = local_absval return global_absval # def apply_mat(self, A): # """ # Matrix multiplication operator # # Args: # A: a matrix # # Returns: # mesh.mesh: component multiplied by the matrix A # """ # if not A.shape[1] == self.values.shape[0]: # raise DataError("ERROR: cannot apply operator %s to %s" % (A.shape[1], self)) # # me = dedalus_field(self.values.domain) # me.values['g'] = A.dot(self.values['g']) # # return me # def send(self, dest=None, tag=None, comm=None): # """ # Routine for sending data forward in time (blocking) # # Args: # dest (int): target rank # tag (int): communication tag # comm: communicator # # Returns: # None # """ # # comm.send(self.values['g'], dest=dest, tag=tag) # return None def isend(self, dest=None, tag=None, comm=None): """ Routine for sending data forward in time (non-blocking) Args: dest (int): target rank tag (int): communication tag comm: communicator Returns: request handle """ req = None for data in self.values: if req is not None: req.Free() req = comm.Issend(data['g'][:], dest=dest, tag=tag) return req def irecv(self, source=None, tag=None, comm=None): """ Routine for receiving in time Args: source (int): source rank tag (int): communication tag comm: communicator Returns: None """ req = None for data in self.values: if req is not None: req.Free() req = comm.Irecv(data['g'], source=source, tag=tag) return req # return comm.Irecv(self.values['g'][:], source=source, tag=tag) def bcast(self, root=None, comm=None): """ Routine for broadcasting values Args: root (int): process with value to broadcast comm: communicator Returns: broadcasted values """ me = dedalus_field(self) for l in range(len(me.values)): me.values[l]['g'] = comm.bcast(self.values[l]['g'], root=root) return me class rhs_imex_dedalus_field(object): """ RHS data type for meshes with implicit and explicit components This data type can be used to have RHS with 2 components (here implicit and explicit) Attributes: impl (mesh.mesh): implicit part expl (mesh.mesh): explicit part """ def __init__(self, init, val=0.0): """ Initialization routine Args: init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested) or another rhs_imex_field object val (float): an initial number (default: 0.0) Raises: DataError: if init is none of the types above """ # if init is another rhs_imex_field, do a deepcopy (init by copy) if isinstance(init, type(self)): self.impl = dedalus_field(init.impl) self.expl = dedalus_field(init.expl) elif isinstance(init, de.Domain) or isinstance(init, tuple): self.impl = dedalus_field(init) self.expl = dedalus_field(init) else: raise DataError('something went wrong during %s initialization' % type(self)) def __sub__(self, other): """ Overloading the subtraction operator for rhs types Args: other (mesh.rhs_imex_field): rhs object to be subtracted Raises: DataError: if other is not a rhs object Returns: mesh.rhs_imex_field: differences between caller and other values (self-other) """ if isinstance(other, rhs_imex_dedalus_field): # always create new rhs_imex_field, since otherwise c = a - b changes a as well! me = rhs_imex_dedalus_field(self.impl) me.impl = self.impl - other.impl me.expl = self.expl - other.expl return me else: raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self))) def __add__(self, other): """ Overloading the addition operator for rhs types Args: other (mesh.rhs_imex_field): rhs object to be added Raises: DataError: if other is not a rhs object Returns: mesh.rhs_imex_field: sum of caller and other values (self-other) """ if isinstance(other, rhs_imex_dedalus_field): # always create new rhs_imex_field, since otherwise c = a + b changes a as well! me = rhs_imex_dedalus_field(self.impl) me.impl = self.impl + other.impl me.expl = self.expl + other.expl return me else: raise DataError("Type error: cannot add %s to %s" % (type(other), type(self))) def __rmul__(self, other): """ Overloading the right multiply by factor operator for mesh types Args: other (float): factor Raises: DataError: is other is not a float Returns: mesh.rhs_imex_field: copy of original values scaled by factor """ if isinstance(other, float): # always create new rhs_imex_field me = rhs_imex_dedalus_field(self.impl) me.impl = other * self.impl me.expl = other * self.expl return me else: raise DataError("Type error: cannot multiply %s to %s" % (type(other), type(self))) # def apply_mat(self, A): # """ # Matrix multiplication operator # # Args: # A: a matrix # # Returns: # mesh.rhs_imex_field: each component multiplied by the matrix A # """ # # if not A.shape[1] == self.impl.values.shape[0]: # raise DataError("ERROR: cannot apply operator %s to %s" % (A, self.impl)) # if not A.shape[1] == self.expl.values.shape[0]: # raise DataError("ERROR: cannot apply operator %s to %s" % (A, self.expl)) # # me = rhs_imex_dedalus_field(self.domain) # me.impl.values['g'] = A.dot(self.impl.values['g']) # me.expl.values['g'] = A.dot(self.expl.values['g']) # # return me
11,938
32.256267
112
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/AC_playground_2D_parallel.py
import sys import numpy as np import matplotlib.pyplot as plt 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.Dedalus.TransferDedalusFields import dedalus_field_transfer from pySDC.playgrounds.Dedalus.AllenCahn_2D_Dedalus import allencahn2d_dedalus from pySDC.playgrounds.Dedalus.AllenCahn_monitor import monitor def main(): """ A simple test program to do PFASST runs for the heat 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['spread'] = False # initialize problem parameters problem_params = dict() problem_params['nu'] = 2 problem_params['L'] = 1.0 problem_params['nvars'] = [(128, 128), (64, 64)] problem_params['eps'] = [0.04] problem_params['radius'] = 0.25 problem_params['comm'] = space_comm # 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 # fill description dictionary for easy step instantiation description = dict() description['problem_class'] = allencahn2d_dedalus 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'] = dedalus_field_transfer # description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer # set time parameters t0 = 0.0 Tend = 27 * 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) # filter statistics by type (number of iterations) iter_counts = get_sorted(stats, type='niter', sortby='time') if space_rank == 0: # 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'Mean number of iterations on rank {time_rank}: {np.mean(niters):.4f}' 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) if __name__ == "__main__": main()
4,345
32.689922
110
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/playground.py
from dedalus import public as de from dedalus import core import numpy as np import matplotlib.pyplot as plt from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field # class wrapper(core.field.Field): # # # def __init__(self, domain): # # super(wrapper, self).__init__(domain) # # def __add__(self, other): # # return wrapper(super(wrapper, self).__add__(other).evaluate(), self.domain) # # # def __abs__(self): # return abs(self).evaluate() de.logging_setup.rootlogger.setLevel('INFO') xbasis = de.Fourier('x', 16, interval=(0, 1), dealias=1) domain = de.Domain([xbasis], grid_dtype=np.float64, comm=None) domain_2 = de.Domain([xbasis], grid_dtype=np.float64, comm=None) print(domain.global_grid_shape(), domain.local_grid_shape()) f = domain.new_field() fxx = xbasis.Differentiate(f) g = de.operators.FieldCopyField(f).evaluate() print((f + g).evaluate()) f['g'][:] = 1.0 print(f['g'], g['g']) print(f, g) # exit() g = domain.new_field() f2 = domain_2.new_field() try: print(f + f2) except ValueError: print('Non-unique domains') x = domain.grid(0, scales=1) f['g'] = np.sin(2 * np.pi * x) print(fxx.evaluate()['g']) f['g'] = np.cos(2 * np.pi * x) print(fxx.evaluate()['g']) exit() g['g'] = np.cos(2 * np.pi * x) u = domain.new_field() # xbasis_c = de.Fourier('x', 4, interval=(0,1), dealias=1) # domain_c = de.Domain([xbasis_c],grid_dtype=np.float64, comm=None) # # fex = domain.new_field() # fex['g'] = np.copy(f['g']) # # ff = domain.new_field() # ff['g'] = np.copy(f['g']) # ff.set_scales(scales=0.5) # # fc = domain_c.new_field() # fc['g'] = ff['g'] # # # print(fc['g'].shape, fex['g'].shape) # # print((fc-fex).evaluate()['g']) # exit() h = (f + g).evaluate() hxx = de.operators.differentiate(h, x=2).evaluate() hxxex = domain.new_field() hxxex['g'] = -((2 * np.pi) ** 2) * np.sin(2 * np.pi * x) - (2 * np.pi) ** 2 * np.cos(2 * np.pi * x) print(max(abs(hxx - hxxex).evaluate()['g'])) # exit() forcing = domain.new_field() forcing['g'] = -np.sin(np.pi * 2 * x) * (np.sin(0) - (np.pi * 2) ** 2 * np.cos(0)) dt = 0.1 / 16 u_old = domain.new_field() u_old['g'] = np.copy(f['g']) problem = de.LinearBoundaryValueProblem(domain=domain, variables=['u']) problem.meta[:]['x']['dirichlet'] = True problem.parameters['dt'] = dt problem.parameters['u_old'] = u_old + dt * forcing problem.add_equation("u - dt * dx(dx(u)) = u_old") solver = problem.build_solver() u = solver.state['u'] Tend = 1.0 nsteps = int(Tend / dt) t = 0.0 for n in range(nsteps): problem.parameters['u_old'] = u_old + dt * forcing solver.solve() t += dt forcing['g'] = -np.sin(np.pi * 2 * x) * (np.sin(t) - (np.pi * 2) ** 2 * np.cos(t)) u_old['g'] = np.copy(u['g']) # print(n) uex = domain.new_field() # uex['g'] = np.sin(2*np.pi*x) * np.exp(-(2*np.pi)**2 * Tend) uex['g'] = np.sin(2 * np.pi * x) * np.cos(Tend) print(np.linalg.norm(u['g'] - uex['g'], np.inf)) # plt.figure(1) # plt.plot(x,u['g']) # plt.plot(x,uex['g']) # # plt.pause(1) # # exit() # forcing = domain.new_field() # forcing['g'] = -np.sin(np.pi * 2 * x) * (np.sin(0) - (np.pi * 2) ** 2 * np.cos(0)) # u_old['g'] = np.zeros(domain.global_grid_shape()) problem = de.IVP(domain=domain, variables=['u']) # problem.parameters['RHS'] = u_old + forcing problem.parameters['RHS'] = 0 problem.add_equation("dt(u) - dx(dx(u)) = RHS") ts = de.timesteppers.SBDF1 solver = problem.build_solver(ts) u = solver.state['u'] # u['g'] = np.sin(2*np.pi*x) tmp = np.tanh((0.25 - np.sqrt((x - 0.5) ** 2)) / (np.sqrt(2) * 0.04)) u['g'] = tmp dt = 1.912834231231e07 t = 0.0 for n in range(nsteps): # u['g'] = u['g'] - dt * np.sin(np.pi * 2 * x) * (np.sin(t) - (np.pi * 2) ** 2 * np.cos(t)) solver.step(dt) t += dt uxx = de.operators.differentiate(u, x=2).evaluate() print(max(abs(u['g'] - dt * uxx['g'] - tmp))) exit() print(np.linalg.norm(u['g'] - uex['g'], np.inf)) # # # plt.figure(1) # plt.plot(x,u['g']) # plt.plot(x,uex['g']) # # # plt.pause(1)
4,014
21.683616
99
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/RayleighBenard_2D_Dedalus.py
import numpy as np from dedalus import public as de from pySDC.core.Problem import ptype from pySDC.core.Errors import ParameterError from pySDC.playgrounds.Dedalus.dedalus_field import dedalus_field, rhs_imex_dedalus_field class rayleighbenard_2d_dedalus(ptype): """ """ def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """ Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class) """ if 'comm' not in problem_params: problem_params['comm'] = None # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'Ra', 'Pr', 'comm', 'initial'] 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) xbasis = de.Fourier('x', problem_params['nvars'][0], interval=(0, 2), dealias=3 / 2) zbasis = de.Chebyshev('z', problem_params['nvars'][1], interval=(-1 / 2, +1 / 2), dealias=3 / 2) domain = de.Domain([xbasis, zbasis], grid_dtype=np.complex128, comm=problem_params['comm']) # invoke super init, passing number of dofs, dtype_u and dtype_f super(rayleighbenard_2d_dedalus, self).__init__( init=(domain, 3), dtype_u=dtype_u, dtype_f=dtype_f, params=problem_params ) self.x = self.init[0].grid(0, scales=1) self.z = self.init[0].grid(1, scales=1) imp_var = ['T', 'u', 'w', 'Tz', 'uz', 'wz', 'p'] self.problem_imp = de.IVP(domain=self.init[0], variables=imp_var) self.problem_imp.parameters['Ra'] = self.params.Ra self.problem_imp.parameters['Pr'] = self.params.Pr self.problem_imp.add_equation(" dx(u) + wz = 0 ") self.problem_imp.add_equation(" dt(T) - ( dx(dx(T)) + dz(Tz) ) = 0") self.problem_imp.add_equation(" dt(u) - ( dx(dx(u)) + dz(uz) ) +dx(p) = 0") # need to look at Pr self.problem_imp.add_equation(" dt(w) - ( dx(dx(w)) + dz(wz) ) +dz(p) - Ra*T = 0") # Need to look at Pr self.problem_imp.add_equation(" Tz - dz(T) = 0") self.problem_imp.add_equation(" uz - dz(u) = 0") self.problem_imp.add_equation(" wz - dz(w) = 0") # Boundary conditions. self.problem_imp.add_bc("left(T) = 1") self.problem_imp.add_bc("left(u) = 0") self.problem_imp.add_bc("left(w) = 0") self.problem_imp.add_bc("right(T) = 0") self.problem_imp.add_bc("right(u) = 0") self.problem_imp.add_bc("right(w) = 0", condition="(nx != 0)") self.problem_imp.add_bc("left(p) = 0", condition="(nx == 0)") self.solver_imp = self.problem_imp.build_solver(de.timesteppers.SBDF1) self.imp_var = [] for l in range(self.init[1]): self.imp_var.append(self.solver_imp.state[imp_var[l]]) exp_var = ['T', 'u', 'w'] self.problem_exp = de.IVP(domain=self.init[0], variables=exp_var) self.problem_exp.parameters['Ra'] = self.params.Ra self.problem_exp.parameters['Pr'] = self.params.Pr self.problem_exp.add_equation("dt(T) = - (u * dx(T) + w * dz(T) )") self.problem_exp.add_equation("dt(u) = - (u * dx(u) + w * dz(u) )") # Need to look at pr self.problem_exp.add_equation("dt(w) = - (u * dx(w) + w * dz(w) ) ") # need to look at pr self.solver_exp = self.problem_exp.build_solver(de.timesteppers.SBDF1) self.exp_var = [] for l in range(self.init[1]): self.exp_var.append(self.solver_exp.state[exp_var[l]]) def eval_f(self, u, t): """ Routine to evaluate both parts of the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS with two parts """ pseudo_dt = 1e-05 f = self.dtype_f(self.init) for l in range(self.init[1]): self.imp_var[l]['g'] = u.values[l]['g'] self.imp_var[l]['c'] = u.values[l]['c'] self.solver_imp.step(pseudo_dt) for l in range(self.init[1]): # self.imp_var[l].set_scales(1) f.impl.values[l]['g'] = 1.0 / pseudo_dt * (self.imp_var[l]['g'] - u.values[l]['g']) f.impl.values[l]['c'] = 1.0 / pseudo_dt * (self.imp_var[l]['c'] - u.values[l]['c']) print(self.solver_imp.timestepper.F[0].data.shape) exit() for l in range(self.init[1]): self.exp_var[l]['g'] = u.values[l]['g'] self.exp_var[l]['c'] = u.values[l]['c'] self.solver_exp.step(pseudo_dt) for l in range(self.init[1]): self.exp_var[l].set_scales(1) f.expl.values[l]['g'] = ( 1.0 / pseudo_dt * (self.exp_var[l]['g'] - u.values[l]['g']) ) # - f.impl.values[l]['g'] f.expl.values[l]['c'] = ( 1.0 / pseudo_dt * (self.exp_var[l]['c'] - u.values[l]['c']) ) # - f.impl.values[l]['c'] return f def solve_system(self, rhs, factor, u0, t): """ Simple linear solver for (I-factor*A)u = rhs Args: rhs (dtype_f): right-hand side for the linear system factor (float): abbrev. for the local stepsize (or any other factor required) u0 (dtype_u): initial guess for the iterative solver t (float): current time (e.g. for time-dependent BCs) Returns: dtype_u: solution as mesh """ me = self.dtype_u(self.init) for l in range(self.init[1]): self.imp_var[l]['g'] = rhs.values[l]['g'] self.imp_var[l]['c'] = rhs.values[l]['c'] self.solver_imp.step(factor) for l in range(self.init[1]): # self.imp_var[l].set_scales(1) me.values[l]['g'][:] = self.imp_var[l]['g'] me.values[l]['c'][:] = self.imp_var[l]['c'] 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 """ xvar_loc = self.x.shape[0] zvar_loc = self.z.shape[1] np.random.seed(0) me = self.dtype_u(self.init) if self.params.initial == 'random': for l in range(self.init[1]): me.values[l]['g'] = np.zeros((xvar_loc, zvar_loc)) me.values[0]['g'] = -self.z + 0.5 + np.random.random(size=(xvar_loc, zvar_loc)) * 1e-2 elif self.params.initial == 'low-res': for l in range(self.init[1]): me.values[l]['g'] = np.zeros((xvar_loc, zvar_loc)) me.values[0]['g'] = np.random.uniform(low=-1e-5, high=1e-5, size=(xvar_loc, zvar_loc)) me.values[0].set_scales(4.0 / self.params.nvars[0]) # Need to do that because otherwise Dedalus tries to be clever.. tmpx = me.values[0]['g'] me.values[0].set_scales(1) me.values[0]['g'] += 0.5 - self.z return me
7,344
35.725
113
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/Dedalus/dynamogp_playground.py
import numpy as np import sys import matplotlib.pyplot as plt 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.Dedalus.TransferDedalusFields import dedalus_field_transfer # from pySDC.playgrounds.Dedalus.DynamoGP_2D_Dedalus import dynamogp_2d_dedalus from pySDC.playgrounds.Dedalus.DynamoGP_2D_Dedalus_NEW import dynamogp_2d_dedalus from pySDC.playgrounds.Dedalus.Dynamo_monitor import monitor def main(): """ A simple test program to do PFASST runs for the heat 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'] = 0.25 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['Rm'] = 3 problem_params['kx'] = 0.57 problem_params['initial'] = 'low-res' problem_params['nvars'] = [(32, 32)] # number of degrees of freedom for each level problem_params['comm'] = space_comm # initialize step parameters step_params = dict() step_params['maxiter'] = 50 # step_params['errtol'] = 1E-07 # initialize controller parameters controller_params = dict() controller_params['logger_level'] = 20 if space_rank == 0 else 99 controller_params['hook_class'] = monitor # controller_params['use_iteration_estimator'] = True # fill description dictionary for easy step instantiation description = dict() description['problem_class'] = dynamogp_2d_dedalus 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'] = dedalus_field_transfer # description['space_transfer_params'] = space_transfer_params # pass paramters for spatial transfer # set time parameters t0 = 0.0 Tend = 10.0 # 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) timings = get_sorted(stats, type='timing_run', sortby='time')[0][1] print(f'Time it took to run the simulation: {timings:6.3f} seconds') if space_size == 1: bx_maxes = get_sorted(stats, type='bx_max', sortby='time') times = [t0 + i * level_params['dt'] for i in range(int((Tend - t0) / level_params['dt']) + 1)] half = int(len(times) / 2) gr = np.polyfit(times[half::], np.log([item[1] for item in bx_maxes])[half::], 1)[0] print("Growth rate: {:.3e}".format(gr)) plt.figure(3) plt.semilogy(times, [item[1] for item in bx_maxes]) plt.pause(0.1) if __name__ == "__main__": main()
4,474
34.23622
110
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_2d_imex/buildFDMatrix.py
import numpy as np import scipy.linalg as la import scipy.sparse as sp # Only for periodic BC because we have advection only in x direction def getUpwindMatrix(N, dx): # stencil = [-1.0, 1.0] # zero_pos = 2 # coeff = 1.0 # stencil = [1.0, -4.0, 3.0] # coeff = 1.0/2.0 # zero_pos = 3 # stencil = [1.0, -6.0, 3.0, 2.0] # coeff = 1.0/6.0 # zero_pos = 3 # stencil = [-5.0, 30.0, -90.0, 50.0, 15.0] # coeff = 1.0/60.0 # zero_pos = 4 stencil = [3.0, -20.0, 60.0, -120.0, 65.0, 12.0] coeff = 1.0 / 60.0 zero_pos = 5 first_col = np.zeros(N) # Because we need to specific first column (not row) in circulant, flip stencil array first_col[0 : np.size(stencil)] = np.flipud(stencil) # Circulant shift of coefficient column so that entry number zero_pos becomes first entry first_col = np.roll(first_col, -np.size(stencil) + zero_pos, axis=0) return sp.csc_matrix(coeff * (1.0 / dx) * la.circulant(first_col)) def getMatrix(N, dx, bc_left, bc_right): stencil = [1.0, -8.0, 0.0, 8.0, -1.0] range = [-2, -1, 0, 1, 2] A = sp.diags(stencil, range, shape=(N, N)) A = sp.lil_matrix(A) assert bc_left in ['periodic', 'neumann', 'dirichlet'], "Unknown type of BC" if bc_left in ['periodic']: assert bc_right in ['periodic'], "Periodic BC can only be selected for both sides simultaneously" if bc_left in ['periodic']: A[0, N - 2] = stencil[0] A[0, N - 1] = stencil[1] A[1, N - 1] = stencil[0] if bc_right in ['periodic']: A[N - 2, 0] = stencil[4] A[N - 1, 0] = stencil[3] A[N - 1, 1] = stencil[4] if bc_left in ['neumann']: A[0, :] = np.zeros(N) A[0, 0] = -8.0 A[0, 1] = 8.0 A[1, 0] = -8.0 + 4.0 / 3.0 A[1, 1] = -1.0 / 3.0 if bc_right in ['neumann']: A[N - 1, :] = np.zeros(N) A[N - 2, N - 1] = 8.0 - 4.0 / 3.0 A[N - 2, N - 2] = 1.0 / 3.0 A[N - 1, N - 1] = 8.0 A[N - 1, N - 2] = -8.0 if bc_left in ['dirichlet']: A[0, :] = np.zeros(N) A[0, 1] = 6.0 if bc_right in ['dirichlet']: A[N - 1, :] = np.zeros(N) A[N - 1, N - 2] = -6.0 A = 1.0 / (12.0 * dx) * A return sp.csc_matrix(A) def getBCLeft(value, N, dx, type): assert type in ['periodic', 'neumann', 'dirichlet'], "Unknown type of BC" b = np.zeros(N) if type in ['dirichlet']: b[0] = -6.0 * value b[1] = 1.0 * value if type in ['neumann']: b[0] = 4.0 * dx * value b[1] = -(2.0 / 3.0) * dx * value return (1.0 / (12.0 * dx)) * b def getBCRight(value, N, dx, type): assert type in ['periodic', 'neumann', 'dirichlet'], "Unknown type of BC" b = np.zeros(N) if type in ['dirichlet']: b[N - 2] = -1.0 * value b[N - 1] = 6.0 * value if type in ['neumann']: b[N - 2] = -(2.0 / 3.0) * dx * value b[N - 1] = 4.0 * dx * value return (1.0 / (12.0 * dx)) * b
3,057
25.136752
105
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_2d_imex/buildWave2DMatrix.py
import numpy as np import scipy.sparse as sp from build2DFDMatrix import get2DMatrix, getBCHorizontal, get2DUpwindMatrix def getWave2DUpwindMatrix(N, dx): Dx = get2DUpwindMatrix(N, dx) Zero = np.zeros((N[0] * N[1], N[0] * N[1])) M1 = sp.hstack((Dx, Zero, Zero), format="csr") M2 = sp.hstack((Zero, Dx, Zero), format="csr") M3 = sp.hstack((Zero, Zero, Dx), format="csr") M = sp.vstack((M1, M2, M3), format="csr") return sp.csc_matrix(M) def getWave2DMatrix(N, h, bc_hor, bc_ver): Dx_u, Dz_u = get2DMatrix(N, h, bc_hor[0], bc_ver[0]) Dx_w, Dz_w = get2DMatrix(N, h, bc_hor[1], bc_ver[1]) Dx_p, Dz_p = get2DMatrix(N, h, bc_hor[2], bc_ver[2]) Id_N = sp.eye(N[0] * N[1]) Zero = np.zeros((N[0] * N[1], N[0] * N[1])) M1 = sp.hstack((Zero, Zero, Dx_p), format="csr") M2 = sp.hstack((Zero, Zero, Dz_p), format="csr") M3 = sp.hstack((Dx_u, Dz_w, Zero), format="csr") M = sp.vstack((M1, M2, M3), format="csr") Id = sp.eye(3 * N[0] * N[1]) return sp.csc_matrix(Id), sp.csc_matrix(M) def getWaveBCHorizontal(value, N, dx, bc_hor): bu_left, bu_right = getBCHorizontal(value[0], N, dx, bc_hor[0]) bw_left, bw_right = getBCHorizontal(value[1], N, dx, bc_hor[1]) bp_left, bp_right = getBCHorizontal(value[2], N, dx, bc_hor[2]) b_left = np.concatenate((bp_left, bp_left, bu_left + bw_left)) b_right = np.concatenate((bp_right, bp_right, bu_right + bw_right)) return b_left, b_right def getWaveBCVertical(): return 0.0
1,516
29.34
75
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_2d_imex/ProblemClass.py
import numpy as np import scipy.sparse.linalg as LA from build2DFDMatrix import get2DMesh from buildWave2DMatrix import getWave2DMatrix, getWave2DUpwindMatrix from unflatten import unflatten from pySDC.core.Problem import ptype from pySDC.implementations.datatype_classes import mesh, rhs_imex_mesh class acoustic_2d_imex(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 assert 'c_s' in cparams assert 'u_adv' in cparams assert 'x_bounds' in cparams assert 'z_bounds' 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(acoustic_2d_imex, self).__init__(self.nvars, dtype_u, dtype_f) self.N = [self.nvars[1], self.nvars[2]] self.bc_hor = [['periodic', 'periodic'], ['periodic', 'periodic'], ['periodic', 'periodic']] self.bc_ver = [['neumann', 'neumann'], ['dirichlet', 'dirichlet'], ['neumann', 'neumann']] self.xx, self.zz, self.h = get2DMesh(self.N, self.x_bounds, self.z_bounds, self.bc_hor[0], self.bc_ver[0]) self.Id, self.M = getWave2DMatrix(self.N, self.h, self.bc_hor, self.bc_ver) self.D_upwind = getWave2DUpwindMatrix(self.N, self.h[0]) 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 """ b = rhs.values.flatten() # NOTE: A = -M, therefore solve Id + factor*M here sol, info = LA.gmres( self.Id + factor * self.c_s * self.M, b, x0=u0.values.flatten(), tol=1e-13, restart=10, maxiter=20, atol=0 ) me = mesh(self.nvars) me.values = unflatten(sol, 3, self.N[0], self.N[1]) return me def __eval_fexpl(self, u, t): """ Helper routine to evaluate the explicit part of the RHS Args: u: current values (not used here) t: current time Returns: explicit part of RHS """ # Evaluate right hand side fexpl = mesh(self.nvars) temp = u.values.flatten() temp = self.D_upwind.dot(temp) # NOTE: M_adv = -D_upwind, therefore add a minus here fexpl.values = unflatten(-self.u_adv * temp, 3, self.N[0], self.N[1]) # fexpl.values = np.zeros((3, self.N[0], self.N[1])) return fexpl def __eval_fimpl(self, u, t): """ Helper routine to evaluate the implicit part of the RHS Args: u: current values t: current time (not used here) Returns: implicit part of RHS """ temp = u.values.flatten() temp = self.M.dot(temp) fimpl = mesh(self.nvars, val=0.0) # NOTE: M = -A, therefore add a minus here fimpl.values = unflatten(-self.c_s * temp, 3, self.N[0], self.N[1]) 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 """ me = mesh(self.nvars) me.values[0, :, :] = 0.0 * self.xx me.values[1, :, :] = 0.0 * self.xx # me.values[2,:,:] = 0.5*np.exp(-0.5*( self.xx-self.c_s*t - self.u_adv*t )**2/0.2**2.0) + 0.5*np.exp(-0.5*( self.xx + self.c_s*t - self.u_adv*t)**2/0.2**2.0) me.values[2, :, :] = np.exp(-0.5 * (self.xx - 0.0) ** 2.0 / 0.15**2.0) * np.exp( -0.5 * (self.zz - 0.5) ** 2 / 0.15**2 ) return me
4,902
30.229299
165
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_2d_imex/HookClass.py
from matplotlib import cm from matplotlib import pyplot as plt from pySDC.core.Hooks import hooks class plot_solution(hooks): def __init__(self): """ Initialization of output """ super(plot_solution, self).__init__() # add figure object for further use # self.fig = plt.figure(figsize=(18,6)) self.fig = plt.figure(figsize=(9, 9)) def post_step(self, status): """ Overwrite standard dump per step Args: status: status object per step """ super(plot_solution, self).post_step(status) # yplot = self.level.uend.values # xx = self.level.prob.xx # zz = self.level.prob.zz # self.fig.clear() # plt.plot( xx[:,0], yplot[2,:,0]) # plt.ylim([-1.1, 1.1]) # plt.show(block=False) # plt.pause(0.00001) if True: yplot = self.level.uend.values xx = self.level.prob.xx zz = self.level.prob.zz self.fig.clear() CS = plt.contourf( xx, zz, yplot[2, :, :], rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False ) cbar = plt.colorbar(CS) plt.axes().set_xlim(xmin=self.level.prob.x_bounds[0], xmax=self.level.prob.x_bounds[1]) plt.axes().set_ylim(ymin=self.level.prob.z_bounds[0], ymax=self.level.prob.z_bounds[1]) plt.axes().set_aspect('equal') plt.xlabel('x') plt.ylabel('z') # plt.tight_layout() plt.show(block=False) plt.pause(0.00001) return None
1,663
29.254545
110
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_2d_imex/build2DFDMatrix.py
import sys sys.path.append('../') import numpy as np import scipy.sparse as sp from buildFDMatrix import getMatrix, getUpwindMatrix, getBCLeft, getBCRight def get2DUpwindMatrix(N, dx): Dx = getUpwindMatrix(N[0], dx) return sp.kron(Dx, sp.eye(N[1]), format="csr") def get2DMesh(N, x_b, z_b, bc_hor, bc_ver): assert np.size(N) == 2, 'N needs to be an array with two entries: N[0]=Nx and N[1]=Nz' assert ( np.size(x_b) == 2 ), 'x_b needs to be an array with two entries: x_b[0] = left boundary, x_b[1] = right boundary' assert ( np.size(z_b) == 2 ), 'z_b needs to be an array with two entries: z_b[0] = lower boundary, z_b[1] = upper boundary' h = np.zeros(2) if bc_hor[0] in ['periodic']: assert bc_hor[1] in ['periodic'], 'Periodic boundary conditions must be prescribed at both boundaries' x = np.linspace(x_b[0], x_b[1], N[0], endpoint=False) h[0] = x[1] - x[0] if bc_hor[0] in ['dirichlet', 'neumann']: x = np.linspace(x_b[0], x_b[1], N[0] + 2, endpoint=True) x = x[1 : N[0] + 1] h[0] = x[1] - x[0] if bc_ver[0] in ['periodic']: assert bc_ver[1] in ['periodic'], 'Periodic boundary conditions must be prescribed at both boundaries' z = np.linspace(z_b[0], z_b[1], N[1], endpoint=False) h[1] = z[1] - z[0] if bc_ver[0] in ['dirichlet', 'neumann']: z = np.linspace(z_b[0], z_b[1], N[1] + 2, endpoint=True) z = z[1 : N[1] + 1] h[1] = z[1] - z[0] xx, zz = np.meshgrid(x, z, indexing="ij") return xx, zz, h def get2DMatrix(N, h, bc_hor, bc_ver): assert np.size(N) == 2, 'N needs to be an array with two entries: N[0]=Nx and N[1]=Nz' assert np.size(h) == 2, 'h needs to be an array with two entries: h[0]=dx and h[1]=dz' Ax = getMatrix(N[0], h[0], bc_hor[0], bc_hor[1]) Az = getMatrix(N[1], h[1], bc_ver[0], bc_ver[1]) Dx = sp.kron(Ax, sp.eye(N[1]), format="csr") Dz = sp.kron(sp.eye(N[0]), Az, format="csr") return Dx, Dz # # NOTE: So far only constant dirichlet values can be prescribed, i.e. one fixed value for a whole segment # def getBCHorizontal(value, N, dx, bc_hor): assert ( np.size(value) == 2 ), 'Value needs to be an array with two entries: value[0] for the left and value[1] for the right boundary' assert np.size(N) == 2, 'N needs to be an array with two entries: N[0]=Nx and N[1]=Nz' assert np.size(dx) == 1, 'dx must be a scalar' assert ( np.size(bc_hor) == 2 ), 'bc_hor must have two entries, bc_hor[0] specifying the BC at the left, bc_hor[1] at the right boundary' bl = getBCLeft(value[0], N[0], dx, bc_hor[0]) bl = np.kron(bl, np.ones(N[1])) br = getBCRight(value[1], N[0], dx, bc_hor[1]) br = np.kron(br, np.ones(N[1])) return bl, br def getBCVertical(value, N, dz, bc_ver): assert ( np.size(value) == 2 ), 'Value needs to be an array with two entries: value[0] for the left and value[1] for the right boundary' assert np.size(N) == 2, 'N needs to be an array with two entries: N[0]=Nx and N[1]=Nz' assert np.size(dz) == 1, 'dx must be a scalar' assert ( np.size(bc_ver) == 2 ), 'bc_hor must have two entries, bc_hor[0] specifying the BC at the left, bc_hor[1] at the right boundary' bd = getBCLeft(value[0], N[1], dz, bc_ver[0]) bd = np.kron(np.ones(N[0]), bd) bu = getBCRight(value[1], N[1], dz, bc_ver[1]) bu = np.kron(np.ones(N[0]), bu) return bd, bu
3,520
32.216981
111
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_2d_imex/__init__.py
1
0
0
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_2d_imex/unflatten.py
import numpy as np def unflatten(uin, dim, Nx, Nz): temp = np.zeros((dim, Nx * Nz)) temp = np.asarray(np.split(uin, dim)) uout = np.zeros((dim, Nx, Nz)) for i in range(0, dim): uout[i, :, :] = np.split(temp[i, :], Nx) return uout
260
22.727273
48
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/acoustic_2d_imex/playground.py
import numpy as np import pySDC.core.deprecated.PFASST_stepwise as mp from ProblemClass import acoustic_2d_imex 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 from pySDC.playgrounds.deprecated.acoustic_2d_imex import plot_solution 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-11 sparams = {} sparams['maxiter'] = 8 # setup parameters "in time" t0 = 0 Tend = 50.0 Nsteps = 2000 dt = Tend / float(Nsteps) # This comes as read-in for the problem class pparams = {} pparams['nvars'] = [(3, 50, 25)] pparams['u_adv'] = 1.0 pparams['c_s'] = 0.0 pparams['x_bounds'] = [(-1.0, 1.0)] pparams['z_bounds'] = [(0.0, 1.0)] # This comes as read-in for the transfer operations # tparams = {} # tparams['finter'] = False # Fill description dictionary for easy hierarchy creation description = {} description['problem_class'] = acoustic_2d_imex description['problem_params'] = pparams description['dtype_u'] = mesh description['dtype_f'] = rhs_imex_mesh description['collocation_class'] = collclass.CollGaussLobatto description['num_nodes'] = 4 description['sweeper_class'] = imex_1st_order description['level_params'] = lparams description['hook_class'] = plot_solution # 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: %9.5e' % ( Tend, np.linalg.norm(uex.values[2, :, :].flatten() - uend.values[2, :, :].flatten(), np.inf) / np.linalg.norm(uex.values.flatten(), np.inf), ) ) 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,633
29.988235
98
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/advection_2d_explicit/ProblemClass.py
import numpy as np from clawpack import pyclaw from clawpack import riemann from unflatten import unflatten from pySDC.core.Problem import ptype from pySDC.implementations.datatype_classes import mesh, rhs_imex_mesh class advection_2d_explicit(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(advection_2d_explicit, self).__init__(self.nvars, dtype_u, dtype_f) riemann_solver = riemann.advection_2D # NOTE: This uses the FORTRAN kernels of clawpack self.solver = pyclaw.SharpClawSolver2D(riemann.advection_2D) 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.bc_lower[1] = pyclaw.BC.periodic self.solver.bc_upper[1] = pyclaw.BC.periodic self.solver.cfl_max = 1.0 assert self.solver.is_valid() x = pyclaw.Dimension(-1.0, 1.0, self.nvars[1], name='x') y = pyclaw.Dimension(0.0, 1.0, self.nvars[2], name='y') self.domain = pyclaw.Domain([x, y]) self.state = pyclaw.State(self.domain, self.solver.num_eqn) # self.dx = self.state.grid.x.centers[1] - self.state.grid.x.centers[0] self.state.problem_data['u'] = 1.0 self.state.problem_data['v'] = 0.0 solution = pyclaw.Solution(self.state, self.domain) self.solver.setup(solution) self.xc, self.yc = self.state.grid.p_centers 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 rhs 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 """ fexpl = mesh(self.nvars) # Copy values of u into pyClaw state object self.state.q[0, :, :] = u.values[0, :, :] # Evaluate right hand side self.solver.before_step(self.solver, self.state) tmp = self.solver.dqdt(self.state) fexpl.values[0, :, :] = unflatten(tmp, 1, self.nvars[1], self.nvars[2]) # Copy values of u into pyClaw state object # self.state.q[0,:,:] = u.values[1,:,:] # Evaluate right hand side # tmp = self.solver.dqdt(self.state) # fexpl.values[1,:,:] = tmp.reshape(self.nvars[1:]) 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 """ me = mesh(self.nvars) me.values[0, :, :] = np.sin(2 * np.pi * self.xc) * np.sin(2 * np.pi * self.yc) # me.values[1,:,:] = np.sin(2*np.pi*self.xc)#*np.sin(2*np.pi*self.yc) return me
4,971
28.595238
96
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/advection_2d_explicit/HookClass.py
from matplotlib import cm from matplotlib import pyplot as plt from pySDC.core.Hooks import hooks class plot_solution(hooks): def __init__(self): """ Initialization of output """ super(plot_solution, self).__init__() # add figure object for further use # self.fig = plt.figure(figsize=(18,6)) self.fig = plt.figure(figsize=(9, 9)) self.counter = 0 def post_step(self, status): """ Overwrite standard dump per step Args: status: status object per step """ super(plot_solution, self).post_step(status) if False: yplot = self.level.uend.values xx = self.level.prob.xc yy = self.level.prob.yc self.fig.clear() plt.plot(xx[:, 0], yplot[0, :, 0]) plt.ylim([-1.0, 1.0]) plt.show(block=False) plt.pause(0.00001) if True: yplot = self.level.uend.values xx = self.level.prob.xc zz = self.level.prob.yc self.fig.clear() CS = plt.contourf( xx, zz, yplot[0, :, :], rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False ) cbar = plt.colorbar(CS) # plt.axes().set_xlim(xmin = self.level.prob.x_b[0], xmax = self.level.prob.x_b[1]) # plt.axes().set_ylim(ymin = self.level.prob.z_b[0], ymax = self.level.prob.z_b[1]) # plt.axes().set_aspect('equal') plt.xlabel('x') plt.ylabel('z') # plt.tight_layout() plt.show(block=False) plt.pause(0.00001) return None
1,713
28.551724
110
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/advection_2d_explicit/__init__.py
1
0
0
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/advection_2d_explicit/unflatten.py
import numpy as np def unflatten(uin, dim, Nx, Nz): temp = np.zeros((dim, Nx * Nz)) temp = np.asarray(np.split(uin, dim)) uout = np.zeros((dim, Nx, Nz)) for i in range(0, dim): uout[i, :, :] = np.split(temp[i, :], Nx) return uout
260
22.727273
48
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/advection_2d_explicit/playground.py
import pySDC.core.Methods as mp from ProblemClass import advection_2d_explicit 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 from pySDC.playgrounds.deprecated.advection_2d_explicit import plot_solution 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'] = 1e-10 sparams = {} sparams['maxiter'] = 0 # setup parameters "in time" t0 = 0 dt = 0.001 Tend = 100 * dt # This comes as read-in for the problem class pparams = {} pparams['nvars'] = [(1, 100, 50)] # This comes as read-in for the transfer operations tparams = {} tparams['finter'] = True # Fill description dictionary for easy hierarchy creation description = {} description['problem_class'] = advection_2d_explicit description['problem_params'] = pparams description['dtype_u'] = mesh description['dtype_f'] = rhs_imex_mesh description['collocation_class'] = collclass.CollGaussLobatto description['num_nodes'] = 2 description['sweeper_class'] = imex_1st_order description['level_params'] = lparams description['hook_class'] = plot_solution # 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_serial(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.imshow(uend.values[0,:,:]) # 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()
2,457
30.922078
103
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/playground_pmesh_comm.py
from mpi4py import MPI import matplotlib matplotlib.use("TkAgg") import numpy as np import pfft import time import matplotlib.pyplot as plt from numpy.fft import rfft2, irfft2 from pmesh.pm import ParticleMesh, RealField, ComplexField 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]) nvars = 128 nruns = 1 # t0 = time.perf_counter() # pm = ParticleMesh(BoxSize=1.0, Nmesh=[nvars] * 2, dtype='f8', plan_method='measure', comm=None) # u = pm.create(type='real') # u = u.apply(doublesine, kind='index', out=Ellipsis) # # res = 0 # for i in range(nruns): # tmp = u.preview() # # print(type(u.value)) # res = max(res, np.linalg.norm(tmp)) # print(res) # t1 = time.perf_counter() # # print(f'PMESH setup time: {t1 - t0:6.4f} sec.') # # exit() 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 / 2) space_comm = comm.Split(color=color) space_size = space_comm.Get_size() space_rank = space_comm.Get_rank() color = int(world_rank % 2) time_comm = comm.Split(color=color) time_size = time_comm.Get_size() time_rank = time_comm.Get_rank() print(world_rank, time_rank, space_rank) t0 = time.perf_counter() if time_rank == 0: pm = ParticleMesh(BoxSize=1.0, Nmesh=[nvars] * 2, dtype='f8', plan_method='measure', comm=space_comm) u = pm.create(type='real') u = u.apply(doublesine, kind='index', out=Ellipsis) time_comm.send(u.value, dest=1, tag=11) else: pm = ParticleMesh(BoxSize=1.0, Nmesh=[nvars] * 2, dtype='f8', plan_method='measure', comm=space_comm) tmp = time_comm.recv(source=0, tag=11) u = pm.create(type='real', value=tmp) t1 = time.perf_counter() print(f'PMESH setup time: {t1 - t0:6.4f} sec.') exit()
1,911
24.837838
105
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AllenCahn_monitor_and_dump_NEW.py
import numpy as np import json from mpi4py import MPI from pySDC.core.Hooks import hooks class monitor_and_dump(hooks): def __init__(self): """ Initialization of Allen-Cahn monitoring """ super(monitor_and_dump, self).__init__() self.init_radius = None self.ndim = None self.comm = None self.rank = None self.size = None self.amode = MPI.MODE_WRONLY | MPI.MODE_CREATE self.time_step = 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_and_dump, self).pre_run(step, level_number) L = step.levels[0] # get space-communicator and data self.comm = L.prob.pm.comm if self.comm is not None: self.rank = self.comm.Get_rank() self.size = self.comm.Get_size() else: self.rank = 0 self.size = 1 # go back to real space tmp_u = L.prob.pm.create(type='complex', value=L.u[0].values) tmp_u = np.ascontiguousarray(tmp_u.c2r().value) # compute numerical radius self.ndim = len(tmp_u.shape) v_local = tmp_u[tmp_u > 2 * L.prob.params.eps].sum() if self.comm is not None: v_global = self.comm.allreduce(sendobj=v_local, op=MPI.SUM) else: v_global = v_local if self.ndim == 3: radius = (v_global / (np.pi * 4.0 / 3.0)) ** (1.0 / 3.0) * L.prob.dx elif self.ndim == 2: radius = np.sqrt(v_global / np.pi) * L.prob.dx else: raise NotImplementedError('Can use this only for 2 or 3D problems') # c_local = np.count_nonzero(L.u[0].values > 0.5) # if self.comm is not None: # c_global = self.comm.allreduce(sendobj=c_local, op=MPI.SUM) # else: # c_global = c_local # if self.ndim == 3: # radius = (c_global / (np.pi * 4.0 / 3.0)) ** (1.0/3.0) * L.prob.dx # elif self.ndim == 2: # radius = np.sqrt(c_global / np.pi) * L.prob.dx # else: # raise NotImplementedError('Can use this only for 2 or 3D problems') self.init_radius = L.prob.params.radius # write to stats 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, ) # compute local offset for I/O nbytes_local = tmp_u.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{0:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, tmp_u) fh.Close() # write json description if self.rank == 0 and step.status.slot == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(tmp_u.dtype) json_obj['endian'] = str(tmp_u.dtype.byteorder) json_obj['time'] = L.time json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.params.nvars json_obj['elementsize'] = tmp_u.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # set step count self.time_step = 1 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_and_dump, self).post_step(step, level_number) # some abbreviations L = step.levels[0] # go back to real space tmp_u = L.prob.pm.create(type='complex', value=L.uend.values) tmp_u = np.ascontiguousarray(tmp_u.c2r().value) # compute numerical radius v_local = tmp_u[tmp_u > 2 * L.prob.params.eps].sum() if self.comm is not None: v_global = self.comm.allreduce(sendobj=v_local, op=MPI.SUM) else: v_global = v_local if self.ndim == 3: radius = (v_global / (np.pi * 4.0 / 3.0)) ** (1.0 / 3.0) * L.prob.dx elif self.ndim == 2: radius = np.sqrt(v_global / np.pi) * L.prob.dx else: raise NotImplementedError('Can use this only for 2 or 3D problems') # c_local = np.count_nonzero(L.uend.values > 0.5) # if self.comm is not None: # c_global = self.comm.allreduce(sendobj=c_local, op=MPI.SUM) # else: # c_global = c_local # if self.ndim == 3: # radius = (c_global / (np.pi * 4.0 / 3.0)) ** (1.0 / 3.0) * L.prob.dx # elif self.ndim == 2: # radius = np.sqrt(c_global / np.pi) * L.prob.dx # else: # raise NotImplementedError('Can use this only for 2 or 3D problems') # compute exact radius exact_radius = np.sqrt(max(self.init_radius**2 - 2.0 * (self.ndim - 1) * (L.time + L.dt), 0)) # write to stats 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, ) # compute local offset for I/O nbytes_local = tmp_u.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{self.time_step + step.status.slot:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, tmp_u) fh.Close() # write json description if self.rank == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(tmp_u.dtype) json_obj['endian'] = str(tmp_u.dtype.byteorder) json_obj['time'] = L.time + L.dt json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.params.nvars json_obj['elementsize'] = tmp_u.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # update step count self.time_step += step.status.time_size
7,672
33.254464
101
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AC_Temperatur_benchmark.py
import sys import numpy as np from mpi4py import MPI from pySDC.helpers.stats_helper import get_sorted from pySDC.implementations.controller_classes.controller_MPI import controller_MPI from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order from pySDC.playgrounds.pmesh.AllenCahn_Temperature_PMESH import allencahn_imex from pySDC.playgrounds.pmesh.TransferMesh_PMESH import pmesh_to_pmesh from pySDC.playgrounds.pmesh.AllenCahn_Temperatur_monitor_and_dump import monitor_and_dump from pySDC.playgrounds.pmesh.AllenCahn_dump import dump from pySDC.playgrounds.pmesh.visualize_Temperature import plot_data 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)] # , (64, 64)]#, 128)] problem_params['eps'] = [0.04] problem_params['dw'] = [21.0] problem_params['D'] = [0.1] problem_params['TM'] = [1.0] 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 = 128 * 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_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-temperature-test' run_simulation(name=name) # plot_data(name=name)
5,148
34.756944
116
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AllenCahn_PMESH_NEW.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_NEW 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 if 'dw' not in problem_params: problem_params['dw'] = 0.0 # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'eps', 'L', 'radius', 'dw'] 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') tmps = tmp.r2c() # invoke super init, passing the communicator and the local dimensions as init super(allencahn_imex, self).__init__( init=(self.pm.comm, tmps.value.shape), 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) tmp_u = self.pm.create(type='complex', value=u.values) f.impl.values = tmp_u.apply(Laplacian).value if self.params.eps > 0: tmp_u = tmp_u.c2r(out=Ellipsis) tmp_f = -2.0 / self.params.eps**2 * tmp_u * (1.0 - tmp_u) * ( 1.0 - 2.0 * tmp_u ) - 6.0 * self.params.dw * tmp_u * (1.0 - tmp_u) f.expl.values = tmp_f.r2c(out=Ellipsis).value 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 me = self.dtype_u(self.init) tmp_rhs = self.pm.create(type='complex', value=rhs.values) me.values = tmp_rhs.apply(linear_solve, 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 assert t == 0, 'ERROR: u_exact only valid for t=0' me = self.dtype_u(self.init) if self.params.init_type == 'circle': tmp_u = self.pm.create(type='real', value=0.0) tmp_u.apply(circle, kind='index', out=Ellipsis) me.values = tmp_u.r2c().value elif self.params.init_type == 'circle_rand': tmp_u = self.pm.create(type='real', value=0.0) tmp_u.apply(circle_rand, kind='index', out=Ellipsis) me.values = tmp_u.r2c().value else: raise NotImplementedError('type of initial value not implemented, got %s' % self.params.init_type) return me class allencahn_imex_timeforcing(allencahn_imex): """ Example implementing Allen-Cahn equation in 2-3D using PMESH for solving linear parts, IMEX time-stepping, time-dependent forcing """ def eval_f(self, u, t): """ Routine to evaluate the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS """ def Laplacian(k, v): k2 = sum(ki**2 for ki in k) return -k2 * v f = self.dtype_f(self.init) tmp_u = self.pm.create(type='real', value=u.values) f.impl.values = tmp_u.r2c().apply(Laplacian, out=Ellipsis).c2r(out=Ellipsis).value if self.params.eps > 0: f.expl.values = -2.0 / self.params.eps**2 * u.values * (1.0 - u.values) * (1.0 - 2.0 * u.values) # build sum over RHS without driving force Rt_local = f.impl.values.sum() + f.expl.values.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.0 - u.values)) 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 -= 6.0 * dw * u.values * (1.0 - u.values) return f class allencahn_imex_stab(allencahn_imex): """ Example implementing Allen-Cahn equation in 2-3D using PMESH for solving linear parts, IMEX time-stepping with stabilized splitting """ 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) + 1.0 / self.params.eps**2 return -k2 * v f = self.dtype_f(self.init) tmp_u = self.pm.create(type='real', value=u.values) f.impl.values = tmp_u.r2c().apply(Laplacian, out=Ellipsis).c2r(out=Ellipsis).value if self.params.eps > 0: f.expl.values = ( -2.0 / self.params.eps**2 * u.values * (1.0 - u.values) * (1.0 - 2.0 * u.values) - 6.0 * self.params.dw * u.values * (1.0 - u.values) + 1.0 / self.params.eps**2 * u.values ) 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) + 1.0 / self.params.eps**2 return 1.0 / (1.0 + factor * k2) * v me = self.dtype_u(self.init) tmp_rhs = self.pm.create(type='real', value=rhs.values) me.values = tmp_rhs.r2c().apply(linear_solve, out=Ellipsis).c2r(out=Ellipsis).value return me
10,466
34.969072
120
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/TransferMesh_PMESH.py
from pySDC.core.Errors import TransferError from pySDC.core.SpaceTransfer import space_transfer from pySDC.playgrounds.pmesh.PMESH_datatype import pmesh_datatype, rhs_imex_pmesh import time class pmesh_to_pmesh(space_transfer): """ Custon base_transfer class, implements Transfer.py This implementation can restrict and prolong between PMESH datatypes meshes with FFT for periodic boundaries """ def __init__(self, fine_prob, coarse_prob, params): """ Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators """ # invoke super initialization super(pmesh_to_pmesh, self).__init__(fine_prob, coarse_prob, params) # self.tmp_F = self.fine_prob.pm.create(type='real') def restrict(self, F): """ Restriction implementation Args: F: the fine level data (easier to access than via the fine attribute) """ t0 = time.perf_counter() if isinstance(F, pmesh_datatype): G = self.coarse_prob.dtype_u(self.coarse_prob.init) # convert numpy array to RealField tmp_F = self.fine_prob.pm.create(type='real', value=F.values) # tmp_G = self.coarse_prob.pm.create(type='real', value=0.0) # resample fine to coarse tmp_G = self.coarse_prob.pm.upsample(tmp_F, keep_mean=True) # tmp_F.resample(tmp_G) # copy values to data structure G.values = tmp_G.value elif isinstance(F, rhs_imex_pmesh): G = self.coarse_prob.dtype_f(self.coarse_prob.init) # convert numpy array to RealField tmp_F = self.fine_prob.pm.create(type='real', value=F.impl.values) # tmp_G = self.coarse_prob.pm.create(type='real', value=0.0) tmp_G = self.coarse_prob.pm.upsample(tmp_F, keep_mean=True) # tmp_F.resample(tmp_G) # copy values to data structure G.impl.values[:] = tmp_G.value # convert numpy array to RealField tmp_F = self.fine_prob.pm.create(type='real', value=F.expl.values) # tmp_G = self.coarse_prob.pm.create(type='real', value=0.0) # resample fine to coarse tmp_G = self.coarse_prob.pm.upsample(tmp_F, keep_mean=True) # tmp_F.resample(tmp_G) # copy values to data structure G.expl.values[:] = tmp_G.value else: raise TransferError('Unknown data type, got %s' % type(F)) t1 = time.perf_counter() print(f'Space restrict: {t1 - t0}') return G def prolong(self, G): """ Prolongation implementation Args: G: the coarse level data (easier to access than via the coarse attribute) """ t0 = time.perf_counter() if isinstance(G, pmesh_datatype): F = self.fine_prob.dtype_u(self.fine_prob.init) # convert numpy array to RealField tmp_F = self.fine_prob.pm.create(type='real', value=0.0) tmp_G = self.coarse_prob.pm.create(type='real', value=G.values) # resample coarse to fine tmp_G.resample(tmp_F) # copy values to data structure F.values = tmp_F.value elif isinstance(G, rhs_imex_pmesh): F = self.fine_prob.dtype_f(self.fine_prob.init) # convert numpy array to RealField tmp_F = self.fine_prob.pm.create(type='real', value=0.0) tmp_G = self.coarse_prob.pm.create(type='real', value=G.impl.values) # resample coarse to fine tmp_G.resample(tmp_F) # copy values to data structure F.impl.values = tmp_F.value # convert numpy array to RealField tmp_F = self.fine_prob.pm.create(type='real', value=0.0) tmp_G = self.coarse_prob.pm.create(type='real', value=G.expl.values) # resample coarse to fine tmp_G.resample(tmp_F) # copy values to data structure F.expl.values = tmp_F.value / 2 else: raise TransferError('Unknown data type, got %s' % type(G)) t1 = time.perf_counter() print(f'Space interpolate: {t1 - t0}') return F
4,370
39.850467
112
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AllenCahn_monitor_and_dump.py
import numpy as np import json from mpi4py import MPI from pySDC.core.Hooks import hooks class monitor_and_dump(hooks): def __init__(self): """ Initialization of Allen-Cahn monitoring """ super(monitor_and_dump, self).__init__() self.init_radius = None self.ndim = None self.comm = None self.rank = None self.size = None self.amode = MPI.MODE_WRONLY | MPI.MODE_CREATE self.time_step = 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_and_dump, self).pre_run(step, level_number) L = step.levels[0] # get space-communicator and data self.comm = L.prob.pm.comm if self.comm is not None: self.rank = self.comm.Get_rank() self.size = self.comm.Get_size() else: self.rank = 0 self.size = 1 # compute numerical radius self.ndim = len(L.u[0].values.shape) v_local = L.u[0].values[L.u[0].values > 2 * L.prob.params.eps].sum() if self.comm is not None: v_global = self.comm.allreduce(sendobj=v_local, op=MPI.SUM) else: v_global = v_local if self.ndim == 3: radius = (v_global / (np.pi * 4.0 / 3.0)) ** (1.0 / 3.0) * L.prob.dx elif self.ndim == 2: radius = np.sqrt(v_global / np.pi) * L.prob.dx else: raise NotImplementedError('Can use this only for 2 or 3D problems') # c_local = np.count_nonzero(L.u[0].values > 0.5) # if self.comm is not None: # c_global = self.comm.allreduce(sendobj=c_local, op=MPI.SUM) # else: # c_global = c_local # if self.ndim == 3: # radius = (c_global / (np.pi * 4.0 / 3.0)) ** (1.0/3.0) * L.prob.dx # elif self.ndim == 2: # radius = np.sqrt(c_global / np.pi) * L.prob.dx # else: # raise NotImplementedError('Can use this only for 2 or 3D problems') self.init_radius = L.prob.params.radius # write to stats 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, ) # compute local offset for I/O nbytes_local = L.u[0].values.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{0:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, L.u[0].values) fh.Close() # write json description if self.rank == 0 and step.status.slot == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(L.u[0].values.dtype) json_obj['endian'] = str(L.u[0].values.dtype.byteorder) json_obj['time'] = L.time json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.params.nvars json_obj['elementsize'] = L.u[0].values.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # set step count self.time_step = 1 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_and_dump, self).post_step(step, level_number) # some abbreviations L = step.levels[0] # compute numerical radius # v_local = np.sum(L.uend.values) v_local = L.uend.values[L.uend.values > 2 * L.prob.params.eps].sum() if self.comm is not None: v_global = self.comm.allreduce(sendobj=v_local, op=MPI.SUM) else: v_global = v_local if self.ndim == 3: radius = (v_global / (np.pi * 4.0 / 3.0)) ** (1.0 / 3.0) * L.prob.dx elif self.ndim == 2: radius = np.sqrt(v_global / np.pi) * L.prob.dx else: raise NotImplementedError('Can use this only for 2 or 3D problems') # c_local = np.count_nonzero(L.uend.values > 0.5) # if self.comm is not None: # c_global = self.comm.allreduce(sendobj=c_local, op=MPI.SUM) # else: # c_global = c_local # if self.ndim == 3: # radius = (c_global / (np.pi * 4.0 / 3.0)) ** (1.0 / 3.0) * L.prob.dx # elif self.ndim == 2: # radius = np.sqrt(c_global / np.pi) * L.prob.dx # else: # raise NotImplementedError('Can use this only for 2 or 3D problems') # compute exact radius exact_radius = np.sqrt(max(self.init_radius**2 - 2.0 * (self.ndim - 1) * (L.time + L.dt), 0)) # write to stats 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, ) # compute local offset for I/O nbytes_local = L.uend.values.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{self.time_step + step.status.slot:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, L.uend.values) fh.Close() # write json description if self.rank == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(L.uend.values.dtype) json_obj['endian'] = str(L.uend.values.dtype.byteorder) json_obj['time'] = L.time + L.dt json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.params.nvars json_obj['elementsize'] = L.uend.values.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # update step count self.time_step += step.status.time_size
7,516
33.640553
101
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AllenCahn_dump.py
import numpy as np import json from mpi4py import MPI from pySDC.core.Hooks import hooks class dump(hooks): def __init__(self): """ Initialization of Allen-Cahn monitoring """ super(dump, self).__init__() self.init_radius = None self.ndim = None self.comm = None self.rank = None self.size = None self.amode = MPI.MODE_WRONLY | MPI.MODE_CREATE self.time_step = 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(dump, self).pre_run(step, level_number) L = step.levels[0] # get space-communicator and data self.comm = L.prob.pm.comm if self.comm is not None: self.rank = self.comm.Get_rank() self.size = self.comm.Get_size() else: self.rank = 0 self.size = 1 # compute local offset for I/O nbytes_local = L.u[0].values.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{0:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, L.u[0].values) fh.Close() # write json description if self.rank == 0 and step.status.slot == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(L.u[0].values.dtype) json_obj['endian'] = str(L.u[0].values.dtype.byteorder) json_obj['time'] = L.time json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.params.nvars json_obj['elementsize'] = L.u[0].values.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # set step count self.time_step = 1 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(dump, self).post_step(step, level_number) # some abbreviations L = step.levels[0] # compute local offset for I/O nbytes_local = L.uend.values.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{self.time_step + step.status.slot:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, L.uend.values) fh.Close() # write json description if self.rank == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(L.uend.values.dtype) json_obj['endian'] = str(L.uend.values.dtype.byteorder) json_obj['time'] = L.time + L.dt json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.params.nvars json_obj['elementsize'] = L.uend.values.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # update step count self.time_step += step.status.time_size
3,866
31.495798
86
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/PMESH_datatype.py
from mpi4py import MPI import numpy as np from pySDC.core.Errors import DataError class pmesh_datatype(object): """ Mesh data type with arbitrary dimensions, will contain PMESH values and communicator Attributes: values (np.ndarray): contains the ndarray of the values comm: MPI communicator or None """ def __init__(self, init=None, val=0.0): """ Initialization routine Args: init: another pmesh_datatype or a tuple containing the communicator and the local dimensions val (float): an initial number (default: 0.0) Raises: DataError: if init is none of the types above """ if isinstance(init, pmesh_datatype): self.comm = init.comm self.values = np.copy(init.values) elif isinstance(init, tuple): self.comm = init[0] self.values = np.empty(init[1], dtype=np.float64) self.values[:] = val # something is wrong, if none of the ones above hit else: raise DataError('something went wrong during %s initialization' % type(self)) def __add__(self, other): """ Overloading the addition operator for mesh types Args: other: mesh object to be added Raises: DataError: if other is not a mesh object Returns: sum of caller and other values (self+other) """ if isinstance(other, type(self)): # always create new mesh, since otherwise c = a + b changes a as well! me = pmesh_datatype(self) me.values = self.values + other.values return me else: raise DataError("Type error: cannot add %s to %s" % (type(other), type(self))) def __sub__(self, other): """ Overloading the subtraction operator for mesh types Args: other: mesh object to be subtracted Raises: DataError: if other is not a mesh object Returns: differences between caller and other values (self-other) """ if isinstance(other, type(self)): # always create new mesh, since otherwise c = a - b changes a as well! me = pmesh_datatype(self) me.values = self.values - other.values return me else: raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self))) def __rmul__(self, other): """ Overloading the right multiply by factor operator for mesh types Args: other (float): factor Raises: DataError: is other is not a float Returns: copy of original values scaled by factor """ if isinstance(other, float) or isinstance(other, complex): # always create new mesh, since otherwise c = f*a changes a as well! me = pmesh_datatype(self) me.values = other * self.values return me else: raise DataError("Type error: cannot multiply %s to %s" % (type(other), type(self))) def __abs__(self): """ Overloading the abs operator for mesh types Returns: float: absolute maximum of all mesh values """ # take absolute values of the mesh values local_absval = np.amax(abs(self.values)) comm = self.comm if comm is not None: if comm.Get_size() > 1: global_absval = comm.allreduce(sendobj=local_absval, op=MPI.MAX) else: global_absval = local_absval else: global_absval = local_absval return global_absval def send(self, dest=None, tag=None, comm=None): """ Routine for sending data forward in time (blocking) Args: dest (int): target rank tag (int): communication tag comm: communicator Returns: None """ comm.send(self.values, dest=dest, tag=tag) return None def isend(self, dest=None, tag=None, comm=None): """ Routine for sending data forward in time (non-blocking) Args: dest (int): target rank tag (int): communication tag comm: communicator Returns: request handle """ return comm.isend(self.values, dest=dest, tag=tag) def recv(self, source=None, tag=None, comm=None): """ Routine for receiving in time Args: source (int): source rank tag (int): communication tag comm: communicator Returns: None """ self.values = comm.recv(source=source, tag=tag) return None def bcast(self, root=None, comm=None): """ Routine for broadcasting values Args: root (int): process with value to broadcast comm: communicator Returns: broadcasted values """ me = pmesh_datatype(self) me.values = comm.bcast(self.values, root=root) return me class rhs_imex_pmesh(object): """ RHS data type for PMESH datatypes with implicit and explicit components This data type can be used to have RHS with 2 components (here implicit and explicit) Attributes: impl: implicit part as pmesh_datatype expl: explicit part as pmesh_datatype """ def __init__(self, init, val=0.0): """ Initialization routine Args: init: another pmesh_datatype or a tuple containing the communicator and the local dimensions val (float): an initial number (default: 0.0) Raises: DataError: if init is none of the types above """ if isinstance(init, type(self)): self.impl = pmesh_datatype(init.impl) self.expl = pmesh_datatype(init.expl) elif isinstance(init, tuple): self.impl = pmesh_datatype(init, val=val) self.expl = pmesh_datatype(init, val=val) # something is wrong, if none of the ones above hit else: raise DataError('something went wrong during %s initialization' % type(self)) def __sub__(self, other): """ Overloading the subtraction operator for rhs types Args: other: rhs object to be subtracted Raises: DataError: if other is not a rhs object Returns: differences between caller and other values (self-other) """ if isinstance(other, type(self)): # always create new rhs_imex_mesh, since otherwise c = a - b changes a as well! me = rhs_imex_pmesh(self) me.impl = self.impl - other.impl me.expl = self.expl - other.expl return me else: raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self))) def __add__(self, other): """ Overloading the addition operator for rhs types Args: other: rhs object to be added Raises: DataError: if other is not a rhs object Returns: sum of caller and other values (self-other) """ if isinstance(other, type(self)): # always create new rhs_imex_mesh, since otherwise c = a + b changes a as well! me = rhs_imex_pmesh(self) me.impl = self.impl + other.impl me.expl = self.expl + other.expl return me else: raise DataError("Type error: cannot add %s to %s" % (type(other), type(self))) def __rmul__(self, other): """ Overloading the right multiply by factor operator for mesh types Args: other (float): factor Raises: DataError: is other is not a float Returns: copy of original values scaled by factor """ if isinstance(other, float): # always create new rhs_imex_mesh me = rhs_imex_pmesh(self) me.impl = other * self.impl me.expl = other * self.expl return me else: raise DataError("Type error: cannot multiply %s to %s" % (type(other), type(self)))
8,399
29.882353
104
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AllenCahn_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 if 'dw' not in problem_params: problem_params['dw'] = 0.0 # these parameters will be used later, so assert their existence essential_keys = ['nvars', 'eps', 'L', 'radius', 'dw'] 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') # invoke super init, passing the communicator and the local dimensions as init super(allencahn_imex, self).__init__( init=(self.pm.comm, tmp.value.shape), 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) tmp_u = self.pm.create(type='real', value=u.values) f.impl.values = tmp_u.r2c().apply(Laplacian, out=Ellipsis).c2r(out=Ellipsis).value if self.params.eps > 0: f.expl.values = -2.0 / self.params.eps**2 * u.values * (1.0 - u.values) * ( 1.0 - 2.0 * u.values ) - 6.0 * self.params.dw * u.values * (1.0 - u.values) 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 me = self.dtype_u(self.init) tmp_rhs = self.pm.create(type='real', value=rhs.values) me.values = tmp_rhs.r2c().apply(linear_solve, 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 assert t == 0, 'ERROR: u_exact only valid for t=0' me = self.dtype_u(self.init) if self.params.init_type == 'circle': tmp_u = self.pm.create(type='real', value=0.0) me.values = tmp_u.apply(circle, kind='index').value elif self.params.init_type == 'circle_rand': tmp_u = self.pm.create(type='real', value=0.0) me.values = 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 class allencahn_imex_timeforcing(allencahn_imex): """ Example implementing Allen-Cahn equation in 2-3D using PMESH for solving linear parts, IMEX time-stepping, time-dependent forcing """ def eval_f(self, u, t): """ Routine to evaluate the RHS Args: u (dtype_u): current values t (float): current time Returns: dtype_f: the RHS """ def Laplacian(k, v): k2 = sum(ki**2 for ki in k) return -k2 * v f = self.dtype_f(self.init) tmp_u = self.pm.create(type='real', value=u.values) f.impl.values = tmp_u.r2c().apply(Laplacian, out=Ellipsis).c2r(out=Ellipsis).value if self.params.eps > 0: f.expl.values = -2.0 / self.params.eps**2 * u.values * (1.0 - u.values) * (1.0 - 2.0 * u.values) # build sum over RHS without driving force Rt_local = f.impl.values.sum() + f.expl.values.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.0 - u.values)) 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 -= 6.0 * dw * u.values * (1.0 - u.values) return f class allencahn_imex_stab(allencahn_imex): """ Example implementing Allen-Cahn equation in 2-3D using PMESH for solving linear parts, IMEX time-stepping with stabilized splitting """ 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) + 1.0 / self.params.eps**2 return -k2 * v f = self.dtype_f(self.init) tmp_u = self.pm.create(type='real', value=u.values) f.impl.values = tmp_u.r2c().apply(Laplacian, out=Ellipsis).c2r(out=Ellipsis).value if self.params.eps > 0: f.expl.values = ( -2.0 / self.params.eps**2 * u.values * (1.0 - u.values) * (1.0 - 2.0 * u.values) - 6.0 * self.params.dw * u.values * (1.0 - u.values) + 1.0 / self.params.eps**2 * u.values ) 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) + 1.0 / self.params.eps**2 return 1.0 / (1.0 + factor * k2) * v me = self.dtype_u(self.init) tmp_rhs = self.pm.create(type='real', value=rhs.values) me.values = tmp_rhs.r2c().apply(linear_solve, out=Ellipsis).c2r(out=Ellipsis).value return me
10,337
35.146853
120
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/TransferMesh_PMESH_NEW.py
from pySDC.core.Errors import TransferError from pySDC.core.SpaceTransfer import space_transfer from pySDC.playgrounds.pmesh.PMESH_datatype_NEW import pmesh_datatype, rhs_imex_pmesh import time class pmesh_to_pmesh(space_transfer): """ Custon base_transfer class, implements Transfer.py This implementation can restrict and prolong between PMESH datatypes meshes with FFT for periodic boundaries """ def __init__(self, fine_prob, coarse_prob, params): """ Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators """ # invoke super initialization super(pmesh_to_pmesh, self).__init__(fine_prob, coarse_prob, params) self.tmp_F = self.fine_prob.pm.create(type='complex') def restrict(self, F): """ Restriction implementation Args: F: the fine level data (easier to access than via the fine attribute) """ t0 = time.perf_counter() if isinstance(F, pmesh_datatype): G = self.coarse_prob.dtype_u(self.coarse_prob.init) # convert numpy array to RealField tmp_F = self.fine_prob.pm.create(type='complex', value=F.values) # tmp_G = self.coarse_prob.pm.create(type='complex') # resample fine to coarse # tmp_G = self.coarse_prob.pm.upsample(tmp_F, keep_mean=True) # tmp_F.resample(tmp_G) tmp_F = tmp_F.c2r(out=Ellipsis) tmp_G = self.coarse_prob.pm.upsample(tmp_F, keep_mean=True) tmp_G = tmp_G.r2c(out=Ellipsis) # copy values to data structure G.values = tmp_G.value elif isinstance(F, rhs_imex_pmesh): G = self.coarse_prob.dtype_f(self.coarse_prob.init) # convert numpy array to RealField tmp_F = self.fine_prob.pm.create(type='complex', value=F.impl.values) # tmp_G = self.coarse_prob.pm.create(type='complex') # resample fine to coarse # tmp_G = self.coarse_prob.pm.upsample(tmp_F, keep_mean=True) # tmp_F.resample(tmp_G) tmp_F = tmp_F.c2r(out=Ellipsis) tmp_G = self.coarse_prob.pm.upsample(tmp_F, keep_mean=True) tmp_G = tmp_G.r2c(out=Ellipsis) # copy values to data structure G.impl.values[:] = tmp_G.value # convert numpy array to RealField tmp_F = self.fine_prob.pm.create(type='complex', value=F.expl.values) # tmp_G = self.coarse_prob.pm.create(type='complex') # resample fine to coarse # tmp_G = self.coarse_prob.pm.upsample(tmp_F, keep_mean=True) # tmp_F.resample(tmp_G) tmp_F = tmp_F.c2r(out=Ellipsis) tmp_G = self.coarse_prob.pm.upsample(tmp_F, keep_mean=True) tmp_G = tmp_G.r2c(out=Ellipsis) # copy values to data structure G.expl.values[:] = tmp_G.value else: raise TransferError('Unknown data type, got %s' % type(F)) t1 = time.perf_counter() print(f'Space restrict: {t1-t0}') return G def prolong(self, G): """ Prolongation implementation Args: G: the coarse level data (easier to access than via the coarse attribute) """ t0 = time.perf_counter() if isinstance(G, pmesh_datatype): F = self.fine_prob.dtype_u(self.fine_prob.init) # convert numpy array to RealField # tmp_F = self.fine_prob.pm.create(type='complex') tmp_G = self.coarse_prob.pm.create(type='complex', value=G.values) # resample coarse to fine tmp_G.resample(self.tmp_F) # copy values to data structure F.values = self.tmp_F.value elif isinstance(G, rhs_imex_pmesh): F = self.fine_prob.dtype_f(self.fine_prob.init) # convert numpy array to RealField # tmp_F = self.fine_prob.pm.create(type='complex') tmp_G = self.coarse_prob.pm.create(type='complex', value=G.impl.values + G.expl.values) # resample coarse to fine tmp_G.resample(self.tmp_F) # copy values to data structure F.impl.values = self.tmp_F.value / 2 # convert numpy array to RealField # tmp_F = self.fine_prob.pm.create(type='complex') # tmp_G = self.coarse_prob.pm.create(type='complex', value=G.expl.values) # # resample coarse to fine # tmp_G.resample(self.tmp_F) # copy values to data structure F.expl.values = self.tmp_F.value / 2 else: raise TransferError('Unknown data type, got %s' % type(G)) t1 = time.perf_counter() print(f'Space interpolate: {t1 - t0}') return F
4,929
41.136752
112
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AC_2D_application.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 import allencahn_imex, allencahn_imex_stab from pySDC.playgrounds.pmesh.TransferMesh_PMESH import pmesh_to_pmesh 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'] = [3, 1] # initialize sweeper parameters sweeper_params = dict() sweeper_params['quad_type'] = 'RADAU-RIGHT' sweeper_params['num_nodes'] = [3] sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part sweeper_params['initial_guess'] = 'zero' # initialize problem parameters problem_params = dict() problem_params['nu'] = 2 problem_params['L'] = 16.0 problem_params['nvars'] = [(48 * 24, 48 * 24), (24 * 24, 24 * 24)] problem_params['eps'] = [0.04] problem_params['dw'] = [-0.04] problem_params['radius'] = 0.25 problem_params['comm'] = space_comm problem_params['name'] = name problem_params['init_type'] = 'circle_rand' # initialize step parameters step_params = dict() step_params['maxiter'] = 50 # initialize controller parameters controller_params = dict() controller_params['logger_level'] = 20 if space_rank == 0 else 99 # set level depending on rank # controller_params['hook_class'] = dump # fill description dictionary for easy step instantiation description = dict() description['problem_class'] = allencahn_imex # description['problem_class'] = allencahn_imex_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 = 1 * 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) if __name__ == "__main__": # name = 'AC-2D-application' name = 'AC-2D-application-forced' run_simulation(name=name)
4,568
34.146154
110
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AC_benchmark.py
import sys import numpy as np from mpi4py import MPI from pySDC.helpers.stats_helper import get_sorted from pySDC.implementations.controller_classes.controller_MPI import controller_MPI from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order from pySDC.playgrounds.pmesh.AllenCahn_PMESH import allencahn_imex, allencahn_imex_stab from pySDC.playgrounds.pmesh.TransferMesh_PMESH import pmesh_to_pmesh from pySDC.playgrounds.pmesh.AllenCahn_monitor_and_dump 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,136
34.923077
116
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/PMESH_datatype_NEW.py
from mpi4py import MPI import numpy as np from pySDC.core.Errors import DataError class pmesh_datatype(object): """ Mesh data type with arbitrary dimensions, will contain PMESH values and communicator Attributes: values (np.ndarray): contains the ndarray of the values comm: MPI communicator or None """ def __init__(self, init=None, val=0.0): """ Initialization routine Args: init: another pmesh_datatype or a tuple containing the communicator and the local dimensions val (float): an initial number (default: 0.0) Raises: DataError: if init is none of the types above """ if isinstance(init, pmesh_datatype): self.comm = init.comm self.values = np.copy(init.values) elif isinstance(init, tuple): self.comm = init[0] self.values = np.empty(init[1], dtype=np.complex128) self.values[:] = val # something is wrong, if none of the ones above hit else: raise DataError('something went wrong during %s initialization' % type(self)) def __add__(self, other): """ Overloading the addition operator for mesh types Args: other: mesh object to be added Raises: DataError: if other is not a mesh object Returns: sum of caller and other values (self+other) """ if isinstance(other, type(self)): # always create new mesh, since otherwise c = a + b changes a as well! me = pmesh_datatype(self) me.values = self.values + other.values return me else: raise DataError("Type error: cannot add %s to %s" % (type(other), type(self))) def __sub__(self, other): """ Overloading the subtraction operator for mesh types Args: other: mesh object to be subtracted Raises: DataError: if other is not a mesh object Returns: differences between caller and other values (self-other) """ if isinstance(other, type(self)): # always create new mesh, since otherwise c = a - b changes a as well! me = pmesh_datatype(self) me.values = self.values - other.values return me else: raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self))) def __rmul__(self, other): """ Overloading the right multiply by factor operator for mesh types Args: other (float): factor Raises: DataError: is other is not a float Returns: copy of original values scaled by factor """ if isinstance(other, float) or isinstance(other, complex): # always create new mesh, since otherwise c = f*a changes a as well! me = pmesh_datatype(self) me.values = other * self.values return me else: raise DataError("Type error: cannot multiply %s to %s" % (type(other), type(self))) def __abs__(self): """ Overloading the abs operator for mesh types Returns: float: absolute maximum of all mesh values """ # take absolute values of the mesh values local_absval = np.amax(abs(self.values)) comm = self.comm if comm is not None: if comm.Get_size() > 1: global_absval = comm.allreduce(sendobj=local_absval, op=MPI.MAX) else: global_absval = local_absval else: global_absval = local_absval return global_absval def send(self, dest=None, tag=None, comm=None): """ Routine for sending data forward in time (blocking) Args: dest (int): target rank tag (int): communication tag comm: communicator Returns: None """ comm.send(self.values, dest=dest, tag=tag) return None def isend(self, dest=None, tag=None, comm=None): """ Routine for sending data forward in time (non-blocking) Args: dest (int): target rank tag (int): communication tag comm: communicator Returns: request handle """ return comm.isend(self.values, dest=dest, tag=tag) def recv(self, source=None, tag=None, comm=None): """ Routine for receiving in time Args: source (int): source rank tag (int): communication tag comm: communicator Returns: None """ self.values = comm.recv(source=source, tag=tag) return None def bcast(self, root=None, comm=None): """ Routine for broadcasting values Args: root (int): process with value to broadcast comm: communicator Returns: broadcasted values """ me = pmesh_datatype(self) me.values = comm.bcast(self.values, root=root) return me class rhs_imex_pmesh(object): """ RHS data type for PMESH datatypes with implicit and explicit components This data type can be used to have RHS with 2 components (here implicit and explicit) Attributes: impl: implicit part as pmesh_datatype expl: explicit part as pmesh_datatype """ def __init__(self, init, val=0.0): """ Initialization routine Args: init: another pmesh_datatype or a tuple containing the communicator and the local dimensions val (float): an initial number (default: 0.0) Raises: DataError: if init is none of the types above """ if isinstance(init, type(self)): self.impl = pmesh_datatype(init.impl) self.expl = pmesh_datatype(init.expl) elif isinstance(init, tuple): self.impl = pmesh_datatype(init, val=val) self.expl = pmesh_datatype(init, val=val) # something is wrong, if none of the ones above hit else: raise DataError('something went wrong during %s initialization' % type(self)) def __sub__(self, other): """ Overloading the subtraction operator for rhs types Args: other: rhs object to be subtracted Raises: DataError: if other is not a rhs object Returns: differences between caller and other values (self-other) """ if isinstance(other, type(self)): # always create new rhs_imex_mesh, since otherwise c = a - b changes a as well! me = rhs_imex_pmesh(self) me.impl = self.impl - other.impl me.expl = self.expl - other.expl return me else: raise DataError("Type error: cannot subtract %s from %s" % (type(other), type(self))) def __add__(self, other): """ Overloading the addition operator for rhs types Args: other: rhs object to be added Raises: DataError: if other is not a rhs object Returns: sum of caller and other values (self-other) """ if isinstance(other, type(self)): # always create new rhs_imex_mesh, since otherwise c = a + b changes a as well! me = rhs_imex_pmesh(self) me.impl = self.impl + other.impl me.expl = self.expl + other.expl return me else: raise DataError("Type error: cannot add %s to %s" % (type(other), type(self))) def __rmul__(self, other): """ Overloading the right multiply by factor operator for mesh types Args: other (float): factor Raises: DataError: is other is not a float Returns: copy of original values scaled by factor """ if isinstance(other, float): # always create new rhs_imex_mesh me = rhs_imex_pmesh(self) me.impl = other * self.impl me.expl = other * self.expl return me else: raise DataError("Type error: cannot multiply %s to %s" % (type(other), type(self)))
8,401
30.00369
104
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AC_2D_application_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_NEW import pmesh_to_pmesh from pySDC.playgrounds.pmesh.AllenCahn_dump_NEW 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'] = [3, 1] # initialize sweeper parameters sweeper_params = dict() sweeper_params['quad_type'] = 'RADAU-RIGHT' sweeper_params['num_nodes'] = [3] sweeper_params['QI'] = ['LU'] # For the IMEX sweeper, the LU-trick can be activated for the implicit part sweeper_params['initial_guess'] = 'zero' # initialize problem parameters problem_params = dict() problem_params['nu'] = 2 problem_params['L'] = 16.0 problem_params['nvars'] = [(48 * 24, 48 * 24), (8 * 24, 8 * 24)] problem_params['eps'] = [0.04] problem_params['dw'] = [-0.04] problem_params['radius'] = 0.25 problem_params['comm'] = space_comm problem_params['name'] = name problem_params['init_type'] = 'circle_rand' # initialize step parameters step_params = dict() step_params['maxiter'] = 50 # initialize controller parameters controller_params = dict() controller_params['logger_level'] = 20 if space_rank == 0 else 99 # set level depending on rank # controller_params['hook_class'] = dump # fill description dictionary for easy step instantiation description = dict() description['problem_class'] = allencahn_imex # description['problem_class'] = allencahn_imex_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 = 1 * 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) if __name__ == "__main__": # name = 'AC-2D-application' name = 'AC-2D-application-forced' run_simulation(name=name)
4,578
34.223077
110
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/visualize_Temperature.py
import json import glob import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import imageio 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[..., 0], vmin=0, vmax=1) plt.colorbar() plt.title(f"Field - Time: {obj['time']:6.4f}") plt.savefig(f'data/{name}_field_{index}.png', bbox_inches='tight') plt.close() plt.figure() plt.imshow(array[..., 1], vmin=0, vmax=1) plt.colorbar() plt.title(f"Temperature - Time: {obj['time']:6.4f}") plt.savefig(f'data/{name}_temperature_{index}.png', bbox_inches='tight') plt.close() def make_gif(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')) img_list = [] c = 0 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') fig, ax = plt.subplots(1, 2) ax[0].imshow(array[..., 1], vmin=0, vmax=1) ax[1].imshow(array[..., 0], vmin=0, vmax=1) # ax.set_colorbar() ax[0].set_title(f"Temperature - Time: {obj['time']:6.4f}") ax[1].set_title(f"Field - Time: {obj['time']:6.4f}") fig.tight_layout() fig.canvas.draw() # draw the canvas, cache the renderer image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8') img_list.append(image.reshape(fig.canvas.get_width_height()[::-1] + (3,))) plt.close() # c +=1 # if c == 3: # break # imageio.mimsave('./test.gif', img_list, fps=8, subrectangles=True) imageio.mimsave('./test.mp4', img_list, fps=8) if __name__ == "__main__": # name = 'AC-test' name = 'AC-temperature-test' # name = 'AC-2D-application' # name = 'AC-2D-application-forced' # plot_data(name=name) make_gif(name=name)
3,225
27.052174
82
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/__init__.py
0
0
0
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/shift_test.py
import numpy as np from scipy.signal import resample ratio = 2 nvars = 2048 cnvars = int(nvars / ratio) xvalues = np.array([i * 1 / nvars - 0.5 for i in range(nvars)]) uexf = 0.5 * (1 + np.tanh((0.25 - abs(xvalues)) / (np.sqrt(2) * 0.04))) xvalues = np.array([i * 1 / cnvars - 0.5 for i in range(cnvars)]) uexc = 0.5 * (1 + np.tanh((0.25 - abs(xvalues)) / (np.sqrt(2) * 0.04))) tmpG = np.fft.rfft(uexc) tmpF = np.zeros(cnvars + 1, dtype=np.complex128) halfG = int(cnvars / 2) tmpF[0:halfG] = tmpG[0:halfG] tmpF[-1] = tmpG[-1] uf = np.fft.irfft(tmpF) * ratio print(np.amax(abs(uf - uexf))) uf1 = np.fft.irfftn(tmpG, s=[nvars]) * ratio # uf1 = resample(uexc, nvars) print(np.amax(abs(uf1 - uexf)))
702
26.038462
71
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AllenCahn_Temperatur_monitor_and_dump.py
import numpy as np import json from mpi4py import MPI from pySDC.core.Hooks import hooks class monitor_and_dump(hooks): def __init__(self): """ Initialization of Allen-Cahn monitoring """ super(monitor_and_dump, self).__init__() self.init_radius = None self.ndim = None self.comm = None self.rank = None self.size = None self.amode = MPI.MODE_WRONLY | MPI.MODE_CREATE self.time_step = 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_and_dump, self).pre_run(step, level_number) L = step.levels[0] # get space-communicator and data self.comm = L.prob.pm.comm if self.comm is not None: self.rank = self.comm.Get_rank() self.size = self.comm.Get_size() else: self.rank = 0 self.size = 1 # compute numerical radius self.ndim = len(L.u[0].values[..., 0].shape) v_local = L.u[0].values[L.u[0].values[..., 0] > 2 * L.prob.params.eps, 0].sum() if self.comm is not None: v_global = self.comm.allreduce(sendobj=v_local, op=MPI.SUM) else: v_global = v_local if self.ndim == 3: radius = (v_global / (np.pi * 4.0 / 3.0)) ** (1.0 / 3.0) * L.prob.dx elif self.ndim == 2: radius = np.sqrt(v_global / np.pi) * L.prob.dx else: raise NotImplementedError('Can use this only for 2 or 3D problems') # c_local = np.count_nonzero(L.u[0].values > 0.5) # if self.comm is not None: # c_global = self.comm.allreduce(sendobj=c_local, op=MPI.SUM) # else: # c_global = c_local # if self.ndim == 3: # radius = (c_global / (np.pi * 4.0 / 3.0)) ** (1.0/3.0) * L.prob.dx # elif self.ndim == 2: # radius = np.sqrt(c_global / np.pi) * L.prob.dx # else: # raise NotImplementedError('Can use this only for 2 or 3D problems') self.init_radius = L.prob.params.radius # write to stats 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, ) # compute local offset for I/O nbytes_local = L.u[0].values.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{0:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, L.u[0].values) fh.Close() # write json description if self.rank == 0 and step.status.slot == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(L.u[0].values.dtype) json_obj['endian'] = str(L.u[0].values.dtype.byteorder) json_obj['time'] = L.time json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.init[1] json_obj['elementsize'] = L.u[0].values.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # set step count self.time_step = 1 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_and_dump, self).post_step(step, level_number) # some abbreviations L = step.levels[0] # compute numerical radius # v_local = np.sum(L.uend.values) v_local = L.uend.values[L.uend.values[..., 0] > 2 * L.prob.params.eps, 0].sum() if self.comm is not None: v_global = self.comm.allreduce(sendobj=v_local, op=MPI.SUM) else: v_global = v_local if self.ndim == 3: radius = (v_global / (np.pi * 4.0 / 3.0)) ** (1.0 / 3.0) * L.prob.dx elif self.ndim == 2: radius = np.sqrt(v_global / np.pi) * L.prob.dx else: raise NotImplementedError('Can use this only for 2 or 3D problems') # c_local = np.count_nonzero(L.uend.values > 0.5) # if self.comm is not None: # c_global = self.comm.allreduce(sendobj=c_local, op=MPI.SUM) # else: # c_global = c_local # if self.ndim == 3: # radius = (c_global / (np.pi * 4.0 / 3.0)) ** (1.0 / 3.0) * L.prob.dx # elif self.ndim == 2: # radius = np.sqrt(c_global / np.pi) * L.prob.dx # else: # raise NotImplementedError('Can use this only for 2 or 3D problems') # compute exact radius exact_radius = np.sqrt(max(self.init_radius**2 - 2.0 * (self.ndim - 1) * (L.time + L.dt), 0)) # write to stats 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, ) # compute local offset for I/O nbytes_local = L.uend.values.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{self.time_step + step.status.slot:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, L.uend.values) fh.Close() # write json description if self.rank == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(L.uend.values.dtype) json_obj['endian'] = str(L.uend.values.dtype.byteorder) json_obj['time'] = L.time + L.dt json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.init[1] json_obj['elementsize'] = L.uend.values.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # update step count self.time_step += step.status.time_size
7,536
33.732719
101
py
pySDC
pySDC-master/pySDC/playgrounds/deprecated/pmesh/AllenCahn_dump_NEW.py
import numpy as np import json from mpi4py import MPI from pySDC.core.Hooks import hooks class dump(hooks): def __init__(self): """ Initialization of Allen-Cahn monitoring """ super(dump, self).__init__() self.init_radius = None self.ndim = None self.comm = None self.rank = None self.size = None self.amode = MPI.MODE_WRONLY | MPI.MODE_CREATE self.time_step = 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(dump, self).pre_run(step, level_number) L = step.levels[0] # get space-communicator and data self.comm = L.prob.pm.comm if self.comm is not None: self.rank = self.comm.Get_rank() self.size = self.comm.Get_size() else: self.rank = 0 self.size = 1 # go back to real space tmp_u = L.prob.pm.create(type='complex', value=L.u[0].values) tmp_u = np.ascontiguousarray(tmp_u.c2r().value) # compute local offset for I/O nbytes_local = tmp_u.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{0:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, tmp_u) fh.Close() # write json description if self.rank == 0 and step.status.slot == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(tmp_u.dtype) json_obj['endian'] = str(tmp_u.dtype.byteorder) json_obj['time'] = L.time json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.params.nvars json_obj['elementsize'] = tmp_u.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # set step count self.time_step = 1 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(dump, self).post_step(step, level_number) # some abbreviations L = step.levels[0] # go back to real space tmp_u = L.prob.pm.create(type='complex', value=L.uend.values) tmp_u = np.ascontiguousarray(tmp_u.c2r().value) # compute local offset for I/O nbytes_local = tmp_u.nbytes if self.comm is not None: nbytes_global = self.comm.allgather(nbytes_local) else: nbytes_global = [nbytes_local] local_offset = sum(nbytes_global[: self.rank]) # dump initial data fname = f"./data/{L.prob.params.name}_{self.time_step + step.status.slot:08d}" fh = MPI.File.Open(self.comm, fname + ".dat", self.amode) fh.Write_at_all(local_offset, tmp_u) fh.Close() # write json description if self.rank == 0: json_obj = dict() json_obj['type'] = 'dataset' json_obj['datatype'] = str(tmp_u.dtype) json_obj['endian'] = str(tmp_u.dtype.byteorder) json_obj['time'] = L.time + L.dt json_obj['space_comm_size'] = self.size json_obj['time_comm_size'] = step.status.time_size json_obj['shape'] = L.prob.params.nvars json_obj['elementsize'] = tmp_u.dtype.itemsize with open(fname + '.json', 'w') as fp: json.dump(json_obj, fp) # update step count self.time_step += step.status.time_size
4,104
31.322835
86
py