-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_rmhd2d.py
864 lines (618 loc) · 31.4 KB
/
run_rmhd2d.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
'''
Created on 21.03.2016
@author: Michael Kraus ([email protected])
'''
import sys, petsc4py
from importlib import import_module
from petsc4py import PETSc
import h5py
import numpy as np
import argparse, datetime, time
import pstats, cProfile
from rmhd.config.config import Config
from rmhd.solvers.common.PETScDerivatives import PETScDerivatives
from rmhd.solvers.linear.PETScPoissonCFD2 import PETScPoisson
class rmhd2d(object):
'''
PETSc/Python Reduced MHD Solver in 2D.
'''
def __init__(self, cfgfile, mode = "none"):
'''
Constructor
'''
petsc4py.init(sys.argv)
if PETSc.COMM_WORLD.getRank() == 0:
print("")
print("Reduced MHD 2D")
print("==============")
print("")
# solver mode
self.mode = mode
# set run id to timestamp
self.run_id = datetime.datetime.fromtimestamp(time.time()).strftime("%y%m%d%H%M%S")
if PETSc.COMM_WORLD.getRank() == 0:
print(" Config: %s" % cfgfile)
# load run config file
self.cfg = Config(cfgfile)
# timestep setup
self.ht = self.cfg['grid']['ht'] # timestep size
self.nt = self.cfg['grid']['nt'] # number of timesteps
self.nsave = self.cfg['io']['nsave'] # save only every nsave'th timestep
# grid setup
self.nx = self.cfg['grid']['nx'] # number of points in x
self.ny = self.cfg['grid']['ny'] # number of points in y
self.Lx = self.cfg['grid']['Lx'] # spatial domain in x
x1 = self.cfg['grid']['x1'] #
x2 = self.cfg['grid']['x2'] #
self.Ly = self.cfg['grid']['Ly'] # spatial domain in y
y1 = self.cfg['grid']['y1'] #
y2 = self.cfg['grid']['y2'] #
self.hx = self.cfg['grid']['hx'] # gridstep size in x
self.hy = self.cfg['grid']['hy'] # gridstep size in y
# create time vector
self.time = PETSc.Vec().createMPI(1, comm=PETSc.COMM_WORLD)
self.time.setName('t')
# electron skin depth
self.de = self.cfg['initial_data']['skin_depth']
# double bracket dissipation
self.nu = self.cfg['initial_data']['dissipation']
# set global tolerance
self.tolerance = self.cfg['solver']['petsc_snes_atol'] * self.nx * self.ny
# direct solver package
self.solver_package = self.cfg['solver']['lu_solver_package']
# set some PETSc solver options
OptDB = PETSc.Options()
OptDB.setValue('ksp_rtol', self.cfg['solver']['petsc_ksp_rtol'])
OptDB.setValue('ksp_atol', self.cfg['solver']['petsc_ksp_atol'])
OptDB.setValue('ksp_max_it', self.cfg['solver']['petsc_ksp_max_iter'])
OptDB.setValue('pc_type', 'hypre')
OptDB.setValue('pc_hypre_type', 'boomeramg')
# create DA with single dof
self.da1 = PETSc.DA().create(dim=2, dof=1,
sizes=[self.nx, self.ny],
proc_sizes=[PETSc.DECIDE, PETSc.DECIDE],
boundary_type=('periodic', 'periodic'),
stencil_width=1,
stencil_type='box')
# create DA (dof = 4 for A, J, P, O)
self.da4 = PETSc.DA().create(dim=2, dof=4,
sizes=[self.nx, self.ny],
proc_sizes=[PETSc.DECIDE, PETSc.DECIDE],
boundary_type=('periodic', 'periodic'),
stencil_width=1,
stencil_type='box')
# create DA for x grid
self.dax = PETSc.DA().create(dim=1, dof=1,
sizes=[self.nx],
proc_sizes=[PETSc.DECIDE],
boundary_type=('periodic'))
# create DA for y grid
self.day = PETSc.DA().create(dim=1, dof=1,
sizes=[self.ny],
proc_sizes=[PETSc.DECIDE],
boundary_type=('periodic'))
# initialise grid
self.da1.setUniformCoordinates(xmin=x1, xmax=x2,
ymin=y1, ymax=y2)
self.da4.setUniformCoordinates(xmin=x1, xmax=x2,
ymin=y1, ymax=y2)
self.dax.setUniformCoordinates(xmin=x1, xmax=x2)
self.day.setUniformCoordinates(xmin=y1, xmax=y2)
# create solution and RHS vector
self.dx = self.da4.createGlobalVec()
self.dy = self.da4.createGlobalVec()
self.x = self.da4.createGlobalVec()
self.b = self.da4.createGlobalVec()
self.f = self.da4.createGlobalVec()
self.Pb = self.da1.createGlobalVec()
self.FA = self.da1.createGlobalVec()
self.FJ = self.da1.createGlobalVec()
self.FP = self.da1.createGlobalVec()
self.FO = self.da1.createGlobalVec()
# create initial guess vectors
self.igFA1= self.da1.createGlobalVec()
self.igFA2= self.da1.createGlobalVec()
self.igFO1= self.da1.createGlobalVec()
self.igFO2= self.da1.createGlobalVec()
# nullspace vectors
self.x0 = self.da4.createGlobalVec()
self.P0 = self.da1.createGlobalVec()
# create vectors for magnetic and velocity field
self.A = self.da1.createGlobalVec() # magnetic vector potential A
self.J = self.da1.createGlobalVec() # current density J
self.P = self.da1.createGlobalVec() # streaming function psi
self.O = self.da1.createGlobalVec() # vorticity omega
self.Bx = self.da1.createGlobalVec()
self.By = self.da1.createGlobalVec()
self.Vx = self.da1.createGlobalVec()
self.Vy = self.da1.createGlobalVec()
# set variable names
self.A.setName('A')
self.J.setName('J')
self.P.setName('P')
self.O.setName('O')
self.Bx.setName('Bx')
self.By.setName('By')
self.Vx.setName('Vx')
self.Vy.setName('Vy')
# initialise nullspace
self.x0.set(0.)
x0_arr = self.da4.getVecArray(self.x0)[...]
x0_arr[:,:,2] = 1.
self.x0.assemble()
self.x0.normalize()
self.solver_nullspace = PETSc.NullSpace().create(constant=False, vectors=(self.x0,))
self.poisson_nullspace = PETSc.NullSpace().create(constant=True)
# initialise Poisson matrix
self.Pm = self.da1.createMat()
self.Pm.setOption(PETSc.Mat.Option.NEW_NONZERO_ALLOCATION_ERR, False)
self.Pm.setUp()
self.Pm.setNullSpace(self.poisson_nullspace)
# create Poisson solver object
self.petsc_poisson = PETScPoisson(self.da1, self.nx, self.ny, self.hx, self.hy)
# setup linear Poisson solver
self.poisson_ksp = PETSc.KSP().create()
self.poisson_ksp.setFromOptions()
self.poisson_ksp.setOperators(self.Pm)
self.poisson_ksp.setTolerances(rtol=self.cfg['solver']['poisson_ksp_rtol'],
atol=self.cfg['solver']['poisson_ksp_atol'],
max_it=self.cfg['solver']['poisson_ksp_max_iter'])
self.poisson_ksp.setType('cg')
self.poisson_ksp.getPC().setType('hypre')
self.poisson_ksp.setUp()
self.petsc_poisson.formMat(self.Pm)
# create derivatives object
self.derivatives = PETScDerivatives(self.da1, self.nx, self.ny, self.ht, self.hx, self.hy)
# read initial data
if self.cfg["io"]["hdf5_input"] != None and self.cfg["io"]["hdf5_input"] != "":
if self.cfg["initial_data"]["python"] != None and self.cfg["initial_data"]["python"] != "":
if PETSc.COMM_WORLD.getRank() == 0:
print("WARNING: Both io.hdf5_input and initial_data.python are set!")
print(" Reading initial data from HDF5 file.")
self.read_initial_data_from_hdf5()
else:
self.read_initial_data_from_python()
# copy initial data vectors to x
self.copy_x_from_da1_to_da4()
# create HDF5 output file and write parameters
hdf5_filename = self.cfg['io']['hdf5_output']
last_dot = hdf5_filename.rfind('.')
hdf5_filename = hdf5_filename[:last_dot] + "." + str(self.run_id) + hdf5_filename[last_dot:]
if PETSc.COMM_WORLD.getRank() == 0:
print(" Output: %s" % hdf5_filename)
hdf5out = h5py.File(hdf5_filename, "w", driver="mpio", comm=PETSc.COMM_WORLD.tompi4py())
hdf5out.attrs["run_id"] = self.run_id
for cfg_group in self.cfg:
for cfg_item in self.cfg[cfg_group]:
if self.cfg[cfg_group][cfg_item] != None:
value = self.cfg[cfg_group][cfg_item]
else:
value = ""
hdf5out.attrs[cfg_group + "." + cfg_item] = value
hdf5out.attrs["solver.solver_mode"] = self.mode
if self.cfg["initial_data"]["python"] != None and self.cfg["initial_data"]["python"] != "":
python_input = open("examples/" + self.cfg['initial_data']['python'] + ".py", 'r')
python_file = python_input.read()
python_input.close()
else:
python_file = ""
hdf5out.attrs["initial_data.python_file"] = python_file
hdf5out.close()
# create HDF5 viewer
self.hdf5_viewer = PETSc.ViewerHDF5().create(hdf5_filename,
mode=PETSc.Viewer.Mode.APPEND,
comm=PETSc.COMM_WORLD)
self.hdf5_viewer.pushGroup("/")
# write grid data to hdf5 file
coords_x = self.dax.getCoordinates()
coords_y = self.day.getCoordinates()
coords_x.setName('x')
coords_y.setName('y')
self.hdf5_viewer(coords_x)
self.hdf5_viewer(coords_y)
# write initial data to hdf5 file
self.save_to_hdf5(0)
# output some more information
if PETSc.COMM_WORLD.getRank() == 0:
print("")
print(" nt = %i" % (self.nt))
print(" nx = %i" % (self.nx))
print(" ny = %i" % (self.ny))
print("")
print(" ht = %f" % (self.ht))
print(" hx = %f" % (self.hx))
print(" hy = %f" % (self.hy))
print("")
print(" PETSc SNES rtol = %e" % self.cfg['solver']['petsc_snes_rtol'])
print(" atol = %e" % self.cfg['solver']['petsc_snes_atol'])
print(" stol = %e" % self.cfg['solver']['petsc_snes_stol'])
print(" max iter = %i" % self.cfg['solver']['petsc_snes_max_iter'])
print("")
print(" PETSc KSP rtol = %e" % self.cfg['solver']['petsc_ksp_rtol'])
print(" atol = %e" % self.cfg['solver']['petsc_ksp_atol'])
print(" max iter = %i" % self.cfg['solver']['petsc_ksp_max_iter'])
print("")
def __del__(self):
self.poisson_ksp.destroy()
self.Pm.destroy()
self.hdf5_viewer.destroy()
def run(self):
raise NotImplementedError
def read_initial_data_from_python(self):
python_module = "examples." + self.cfg['initial_data']['python']
if PETSc.COMM_WORLD.getRank() == 0:
print(" Input: %s" % python_module)
print("")
# get whole grid
xGrid, yGrid = self.get_coordinate_vectors_from_das()
# set initial data
(xs, xe), (ys, ye) = self.da1.getRanges()
init_data = import_module(python_module)
if hasattr(init_data, 'magnetic_A'):
if PETSc.COMM_WORLD.getRank() == 0:
print(" Computing magnetic potential from initial data.")
A_arr = self.da1.getVecArray(self.A)
for i in range(xs, xe):
for j in range(ys, ye):
A_arr[i,j] = init_data.magnetic_A(xGrid[i], yGrid[j], self.Lx, self.Ly)
# apply Fourier filtering to magnetic potential
self.fourier_filter_magnetic_potential()
# compute current density
self.derivatives.laplace_vec(self.A, self.J, -1.)
elif hasattr(init_data, 'magnetic_J'):
if PETSc.COMM_WORLD.getRank() == 0:
print(" Computing current density from initial data.")
J_arr = self.da1.getVecArray(self.J)
for i in range(xs, xe):
for j in range(ys, ye):
J_arr[i,j] = init_data.magnetic_J(xGrid[i], yGrid[j], self.Lx, self.Ly)
# solve for consistent initial magnetic potential
self.A.set(0.)
self.petsc_poisson.formRHS(self.J, self.Pb)
self.poisson_nullspace.remove(self.Pb)
self.poisson_ksp.solve(self.Pb, self.A)
self.derivatives.laplace_vec(self.A, self.J, -1.)
else:
if PETSc.COMM_WORLD.getRank() == 0:
print(" WARNING: Neither magnetic potential nor current density given in initial data.")
if hasattr(init_data, 'velocity_P'):
if PETSc.COMM_WORLD.getRank() == 0:
print(" Computing streaming function from initial data.")
P_arr = self.da1.getVecArray(self.P)
for i in range(xs, xe):
for j in range(ys, ye):
P_arr[i,j] = init_data.velocity_P(xGrid[i], yGrid[j], self.Lx, self.Ly)
# remmove nullspace
self.poisson_nullspace.remove(self.P)
# compute vorticity
self.derivatives.laplace_vec(self.P, self.O, -1.)
elif hasattr(init_data, 'velocity_O'):
if PETSc.COMM_WORLD.getRank() == 0:
print(" Computing vorticity from initial data.")
O_arr = self.da1.getVecArray(self.O)
for i in range(xs, xe):
for j in range(ys, ye):
O_arr[i,j] = init_data.velocity_O(xGrid[i], yGrid[j], self.Lx, self.Ly)
self.poisson_nullspace.remove(self.O)
# solve for consistent initial streaming function
self.P.set(0.)
self.petsc_poisson.formRHS(self.O, self.Pb)
self.poisson_nullspace.remove(self.Pb)
self.poisson_ksp.solve(self.Pb, self.P)
else:
if PETSc.COMM_WORLD.getRank() == 0:
print(" WARNING: Neither streaming function nor vorticity given in initial data.")
if PETSc.COMM_WORLD.getRank() == 0:
print("")
def read_initial_data_from_hdf5(self):
hdf5_filename = self.cfg["io"]["hdf5_input"]
if PETSc.COMM_WORLD.getRank() == 0:
print(" Input: %s" % hdf5_filename)
hdf5in = h5py.File(hdf5_filename, "r", driver="mpio", comm=PETSc.COMM_WORLD.tompi4py())
assert self.nx == hdf5in.attrs["grid.nx"]
assert self.ny == hdf5in.attrs["grid.ny"]
assert self.hx == hdf5in.attrs["grid.hx"]
assert self.hy == hdf5in.attrs["grid.hy"]
assert self.Lx == hdf5in.attrs["grid.Lx"]
assert self.Ly == hdf5in.attrs["grid.Ly"]
assert self.de == hdf5in.attrs["initial_data.skin_depth"]
timestep = len(hdf5in["t"][...].flatten()) - 1
hdf5in.close()
hdf5_viewer = PETSc.ViewerHDF5().create(hdf5_filename,
mode=PETSc.Viewer.Mode.READ,
comm=PETSc.COMM_WORLD)
hdf5_viewer.setTimestep(timestep)
self.A.load(hdf5_viewer)
self.J.load(hdf5_viewer)
self.P.load(hdf5_viewer)
self.O.load(hdf5_viewer)
hdf5_viewer.destroy()
def copy_x_from_da4_to_da1(self):
x_arr = self.da4.getVecArray(self.x)
self.da1.getVecArray(self.A)[:,:] = x_arr[:,:,0]
self.da1.getVecArray(self.J)[:,:] = x_arr[:,:,1]
self.da1.getVecArray(self.P)[:,:] = x_arr[:,:,2]
self.da1.getVecArray(self.O)[:,:] = x_arr[:,:,3]
def copy_x_from_da1_to_da4(self):
x_arr = self.da4.getVecArray(self.x)
x_arr[:,:,0] = self.da1.getVecArray(self.A)[:,:]
x_arr[:,:,1] = self.da1.getVecArray(self.J)[:,:]
x_arr[:,:,2] = self.da1.getVecArray(self.P)[:,:]
x_arr[:,:,3] = self.da1.getVecArray(self.O)[:,:]
def get_coordinate_vectors_from_das(self):
# get coordinate vectors
coords_x = self.dax.getCoordinates()
coords_y = self.day.getCoordinates()
# save x coordinate arrays
scatter, xVec = PETSc.Scatter.toAll(coords_x)
scatter.begin(coords_x, xVec, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD)
scatter.end (coords_x, xVec, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD)
xGrid = xVec.getValues(range(self.nx)).copy()
scatter.destroy()
xVec.destroy()
# save y coordinate arrays
scatter, yVec = PETSc.Scatter.toAll(coords_y)
scatter.begin(coords_y, yVec, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD)
scatter.end (coords_y, yVec, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD)
yGrid = yVec.getValues(range(self.ny)).copy()
scatter.destroy()
yVec.destroy()
return xGrid, yGrid
def fourier_filter_magnetic_potential(self):
# Fourier Filtering
self.nfourier = self.cfg['initial_data']['nfourier']
if self.nfourier >= 0:
(xs, xe), (ys, ye) = self.da1.getRanges()
# obtain whole A vector everywhere
scatter, Aglobal = PETSc.Scatter.toAll(self.A)
scatter.begin(self.A, Aglobal, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD)
scatter.end (self.A, Aglobal, PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD)
petsc_indices = self.da1.getAO().app2petsc(np.arange(self.nx*self.ny, dtype=np.int32))
Ainit = Aglobal.getValues(petsc_indices).copy().reshape((self.ny, self.nx))
scatter.destroy()
Aglobal.destroy()
# compute FFT, cut, compute inverse FFT
from scipy.fftpack import rfft, irfft
Afft = rfft(Ainit, axis=1)
# Afft[:,0] = 0.
Afft[:,self.nfourier+1:] = 0.
self.da1.getVecArray(self.A)[:,:] = irfft(Afft).T[xs:xe, ys:ye]
def calculate_initial_guess(self, initial=False):
# set some variables for hermite extrapolation
t0 = 0.
t1 = 1.
t = 2.
a0 = 2./(t0-t1)
a1 = 2./(t1-t0)
b0 = 1./(t0-t1)**2
b1 = 1./(t1-t0)**2
d0 = 1./(t-t0)
d1 = 1./(t-t1)
e0 = d0*b0
e1 = d1*b1
self.hermite_x0 = e0*(d0-a0)
self.hermite_x1 = e1*(d1-a1)
self.hermite_f0 = e0*self.ht
self.hermite_f1 = e1*self.ht
self.hermite_den = 1. / (self.hermite_x0 + self.hermite_x1)
self.petsc_solver.Ap.copy(self.A)
self.petsc_solver.Op.copy(self.O)
if initial:
self.derivatives.arakawa_vec(self.petsc_solver.Ap, self.petsc_solver.Pp, self.igFA1)
self.derivatives.arakawa_vec(self.petsc_solver.Op, self.petsc_solver.Pp, self.igFO1)
self.derivatives.arakawa_vec(self.petsc_solver.Ap, self.petsc_solver.Jp, self.igFO2)
self.A.axpy(0.5*self.ht, self.igFA1)
self.O.axpy(0.5*self.ht, self.igFO1)
self.O.axpy(0.5*self.ht, self.igFO2)
if self.de != 0.:
self.derivatives.arakawa_vec(self.petsc_solver.Jp, self.petsc_solver.Pp, self.igFA2)
self.igFA2.scale(self.de**2)
self.A.axpy(0.5*self.ht, self.igFA2)
self.derivatives.laplace_vec(self.A, self.J, -1.)
self.P.set(0.)
self.O.copy(self.Pb)
self.poisson_nullspace.remove(self.Pb)
self.poisson_ksp.solve(self.Pb, self.P)
self.derivatives.arakawa_vec(self.A, self.P, self.igFA1)
self.derivatives.arakawa_vec(self.O, self.P, self.igFO1)
self.derivatives.arakawa_vec(self.A, self.J, self.igFO2)
self.petsc_solver.Ap.copy(self.A)
self.petsc_solver.Op.copy(self.O)
self.A.axpy(self.ht, self.igFA1)
self.O.axpy(self.ht, self.igFO1)
self.O.axpy(self.ht, self.igFO2)
if self.de != 0.:
self.derivatives.arakawa_vec(self.J, self.P, self.igFA2)
self.igFA2.scale(self.de**2)
self.A.axpy(self.ht, self.igFA2)
# self.A.axpy(-self.de**2, self.petsc_solver.Jp)
# self.A.axpy(+self.de**2, self.J)
self.derivatives.laplace_vec(self.A, self.J, -1.)
self.P.set(0.)
self.O.copy(self.Pb)
self.poisson_nullspace.remove(self.Pb)
self.poisson_ksp.solve(self.Pb, self.P)
self.derivatives.arakawa_vec(self.petsc_solver.Ap, self.petsc_solver.Pp, self.igFA1)
self.derivatives.arakawa_vec(self.petsc_solver.Op, self.petsc_solver.Pp, self.igFO1)
self.derivatives.arakawa_vec(self.petsc_solver.Ap, self.petsc_solver.Jp, self.igFO2)
if self.de != 0.:
self.derivatives.arakawa_vec(self.petsc_solver.Jp, self.petsc_solver.Pp, self.igFA2)
self.igFA2.scale(self.de**2)
else:
self.A.set(0.)
self.O.set(0.)
self.A.axpy(self.hermite_x0, self.petsc_solver.Ah)
self.A.axpy(self.hermite_f0, self.igFA1)
if self.de != 0.:
# self.A.axpy(+self.de**2, self.petsc_solver.Jh)
self.A.axpy(self.hermite_f0, self.igFA2)
self.O.axpy(self.hermite_x0, self.petsc_solver.Oh)
self.O.axpy(self.hermite_f0, self.igFO1)
self.O.axpy(self.hermite_f0, self.igFO2)
self.derivatives.arakawa_vec(self.petsc_solver.Ap, self.petsc_solver.Pp, self.igFA1)
self.derivatives.arakawa_vec(self.petsc_solver.Op, self.petsc_solver.Pp, self.igFO1)
self.derivatives.arakawa_vec(self.petsc_solver.Ap, self.petsc_solver.Jp, self.igFO2)
if self.de != 0.:
self.derivatives.arakawa_vec(self.petsc_solver.Jp, self.petsc_solver.Pp, self.igFA2)
self.igFA2.scale(self.de**2)
self.A.axpy(self.hermite_x1, self.petsc_solver.Ap)
self.A.axpy(self.hermite_f1, self.igFA1)
if self.de != 0.:
# self.A.axpy(-self.de**2, self.petsc_solver.Jp)
self.A.axpy(self.hermite_f1, self.igFA2)
self.O.axpy(self.hermite_x1, self.petsc_solver.Op)
self.O.axpy(self.hermite_f1, self.igFO1)
self.O.axpy(self.hermite_f1, self.igFO2)
self.A.scale(self.hermite_den)
self.O.scale(self.hermite_den)
self.derivatives.laplace_vec(self.A, self.J, -1.)
self.P.set(0.)
self.O.copy(self.Pb)
self.poisson_nullspace.remove(self.Pb)
self.poisson_ksp.solve(self.Pb, self.P)
def save_to_hdf5(self, timestep):
if timestep % self.nsave == 0:
if PETSc.COMM_WORLD.getRank() == 0:
self.time.setValue(0, self.ht*timestep)
# copy solution to A, J, psi, omega vectors
self.copy_x_from_da4_to_da1()
# calculate B and V field
self.derivatives.dy(self.A, self.Bx, +1.)
self.derivatives.dx(self.A, self.By, -1.)
self.derivatives.dy(self.P, self.Vx, +1.)
self.derivatives.dx(self.P, self.Vy, -1.)
# save timestep
self.hdf5_viewer.setTimestep(timestep // self.nsave)
self.hdf5_viewer(self.time)
self.hdf5_viewer(self.A)
self.hdf5_viewer(self.J)
self.hdf5_viewer(self.P)
self.hdf5_viewer(self.O)
self.hdf5_viewer(self.Bx)
self.hdf5_viewer(self.By)
self.hdf5_viewer(self.Vx)
self.hdf5_viewer(self.Vy)
def check_jacobian(self):
(xs, xe), (ys, ye) = self.da1.getRanges()
eps = 1.E-7
# calculate initial guess
# self.calculate_initial_guess()
# update previous iteration
self.petsc_solver.update_previous(self.x)
# calculate jacobian
self.petsc_solver.formMat(self.Jac)
# create working vectors
Jx = self.da4.createGlobalVec()
dJ = self.da4.createGlobalVec()
ex = self.da4.createGlobalVec()
dx = self.da4.createGlobalVec()
dF = self.da4.createGlobalVec()
Fxm = self.da4.createGlobalVec()
Fxp = self.da4.createGlobalVec()
# sx = -2
# sx = -1
sx = 0
# sx = +1
# sx = +2
# sy = -1
sy = 0
# sy = +1
nfield=4
for ifield in range(0, nfield):
for ix in range(xs, xe):
for iy in range(ys, ye):
for tfield in range(0, nfield):
# compute ex
ex_arr = self.da4.getVecArray(ex)
ex_arr[:] = 0.
ex_arr[(ix+sx) % self.nx, (iy+sy) % self.ny, ifield] = 1.
# compute J.e
self.Jac.function(ex, dJ)
dJ_arr = self.da4.getVecArray(dJ)
Jx_arr = self.da4.getVecArray(Jx)
Jx_arr[ix, iy, tfield] = dJ_arr[ix, iy, tfield]
# compute F(x - eps ex)
self.x.copy(dx)
dx_arr = self.da4.getVecArray(dx)
dx_arr[(ix+sx) % self.nx, (iy+sy) % self.ny, ifield] -= eps
self.petsc_solver.function(dx, Fxm)
# compute F(x + eps ex)
self.x.copy(dx)
dx_arr = self.da4.getVecArray(dx)
dx_arr[(ix+sx) % self.nx, (iy+sy) % self.ny, ifield] += eps
self.petsc_solver.function(dx, Fxp)
# compute dF = [F(x + eps ex) - F(x - eps ex)] / (2 eps)
Fxm_arr = self.da4.getVecArray(Fxm)
Fxp_arr = self.da4.getVecArray(Fxp)
dF_arr = self.da4.getVecArray(dF)
dF_arr[ix, iy, tfield] = ( Fxp_arr[ix, iy, tfield] - Fxm_arr[ix, iy, tfield] ) / (2. * eps)
diff = np.zeros(nfield)
for tfield in range(0,nfield):
# print()
# print("Fields: (%5i, %5i)" % (ifield, tfield))
# print()
Jx_arr = self.da4.getVecArray(Jx)[...][:, :, tfield]
dF_arr = self.da4.getVecArray(dF)[...][:, :, tfield]
# print("Jacobian:")
# print(Jx_arr)
# print()
#
# print("[F(x+dx) - F(x-dx)] / [2 eps]:")
# print(dF_arr)
# print()
#
# print("Difference:")
# print(Jx_arr - dF_arr)
# print()
# if ifield == 3 and tfield == 2:
# print("Jacobian:")
# print(Jx_arr)
# print()
#
# print("[F(x+dx) - F(x-dx)] / [2 eps]:")
# print(dF_arr)
# print()
diff[tfield] = (Jx_arr - dF_arr).max()
print()
for tfield in range(0,nfield):
print("max(difference)[field=%i, equation=%i] = %16.8E" % ( ifield, tfield, diff[tfield] ))
print()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='PETSc Reduced MHD Solver in 2D')
parser.add_argument('-c', '--config', metavar='<cfg_file>', type=str, required=True,
help='Configuration File')
parser.add_argument('-m', '--mode', metavar='[asm, lu, ppc, split]', type=str, required=True,
help='Solver Mode')
parser.add_argument('-p', '--profiler', action='store_true', required=False,
help='Activate Profiler')
parser.add_argument('-j', '--jacobian', action='store_true', required=False,
help='Check Jacobian')
#
args = parser.parse_args()
runfile = args.config
mode = args.mode
if mode == "ppc":
# physics based preconditioner
from run_rmhd2d_ppc import rmhd2d_ppc
petscvp = rmhd2d_ppc(runfile)
elif mode == "split":
# split solver with physics based preconditioner
from run_rmhd2d_split import rmhd2d_split
petscvp = rmhd2d_split(runfile)
elif mode == "asm":
# additive schwarz preconditioner
from run_rmhd2d_asm import rmhd2d_asm
petscvp = rmhd2d_asm(runfile)
else:
# direct solver (lu decomposition)
from run_rmhd2d_lu import rmhd2d_lu
petscvp = rmhd2d_lu(runfile)
if args.profiler:
cProfile.runctx("petscvp.run()", globals(), locals(), "profile.prof")
if PETSc.COMM_WORLD.getRank() == 0:
s = pstats.Stats("profile.prof")
s.strip_dirs().sort_stats("time").print_stats()
elif args.jacobian:
petscvp.check_jacobian()
else:
petscvp.run()