forked from magnetotellurics/ModEM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEMsolve3D.f90
More file actions
1641 lines (1547 loc) · 67.7 KB
/
Copy pathEMsolve3D.f90
File metadata and controls
1641 lines (1547 loc) · 67.7 KB
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
!**********************************************************************
! driver modules for solving the forward EM problem, including setup and
! solver
! this module is modified to use sparse matrix
module EMsolve3D
use sg_boundary! work between different data types
! (between boundary conditions and
! complex vectors)
use sg_sparse_vector, only: add_scvector
use modelOperator3D ! Maxwell operator module for sp
use vectranslate ! translate back and forth between Cvec and vec
use solver ! generic solvers rewrite for sp
use solnspace
use utilities
implicit none
public :: FWDSolve3D
public :: deallSolverDiag, deallEMsolveControl
public :: createSolverDiag, getEMsolveDiag, setEMsolveControl
private :: SdivCorr
#ifdef FG
interface FWDSolve3D
MODULE PROCEDURE FWDSolve3D
MODULE PROCEDURE FWDSolve3Dfg
end interface
#endif
type :: emsolve_control
! Values of solver control parameters, e.g., read in from file
! plus other information on how the solver is to be initialized,
! called, etc.
! idea is that this is the public access version of this info, which is
! copied into private version for actual solver control
integer :: IterPerDivCor, MaxDivCor, MaxIterDivCor
real(kind = 8) :: tolEMfwd, tolEMadj, tolDivCor
logical :: E0fromFile
logical :: UseDefaults
logical :: read_E0_from_File=.false.
character (len=80) :: E0fileName
integer :: ioE0
character (len=80) :: AirLayersMethod
integer :: AirLayersNz
real(kind = 8) :: AirLayersMaxHeight, AirLayersAlpha
real(kind = 8) :: AirLayersMinTopDz
real(kind = 8), pointer, dimension(:) :: AirLayersDz
logical :: AirLayersPresent=.false.
character (len=10) :: solver_name="BICG"
character (len=50) , public :: get_1D_from="Geometric_mean"
end type emsolve_control
type :: emsolve_diag
! Solver diagnostic arrays, computed during run of forward solver.
! idea is that this is the public access version of this info, which is
! copied from the private version in module em_solve where this info is
! initially stored
logical :: diagOut
character (len=80) :: fn_diagn
integer :: ioDiag
integer :: nIterTotal, nDivCor
real(kind = 8), pointer, dimension(:) :: EMrelErr
real(kind = 8), pointer, dimension(:,:) :: divJ
real(kind = 8), pointer, dimension(:,:) :: DivCorRelErr
end type emsolve_diag
! Default solver control parameters
! number of iterations for each call to divergence correction:
integer, parameter :: IterPerDivCorDef = 150
! maximum number of divergence correction calls allowed
integer, parameter :: MaxDivCorDef = 8
! maximum number of PCG iterations for divergence correction
integer, parameter :: MaxIterDivCorDef = 100
! misfit tolerance for convergence of EMsolve algorithm
real(kind=prec), parameter :: tolEMDef = 1E-10
! misfit tolerance for convergence of divergence correction solver
real(kind=prec), parameter :: tolDivCorDef = 1E-7
!Solver name, by default we use BICG
character (len=10) :: solver_name="BICG"
character (len=50) , public :: get_1D_from="Geometric_mean"
save
type(timer_t), private :: timer
! Actual values of control parameters must be set before first use,
! by call to setEMsolveControl
! of em_solve; are saved between calls, private to this module
integer, private :: IterPerDivCor, MaxDivCor, MaxIterDivCor
integer, private :: MaxIterTotal ! = MaxDivCor*IterPerDivCor
real(kind=prec), private :: tolEMfwd, tolEMadj, tolDivCor
! EMsolve diagnostics: these are computed during execution of em_solve
! can be retrieved by call to getEmsolveDiag
integer, private :: nIterTotal, nDivCor
logical, private :: failed
! nIterTotal keeps tally on number of iterations so far
! nDivCor keeps tally on number of divergence correction so far
real(kind=prec), pointer, dimension(:), private :: EMrelErr
real(kind=prec), pointer, dimension(:,:), private :: divJ
real(kind=prec), pointer, dimension(:,:), private :: DivCorRelErr
Contains
!**********************************************************************
! main subroutine to Solve the forward EM problem;
! modified to use the sparse matrix data structure defined in
! sp modelOperator3D module
! If bRHS%adj = 'TRN' solves transposed problem A^T x = b
!
! below is Anna's comment copied from the MF equivalent subroutine
!
! Note [AK 2018-05-10]:
! Any physical source has already been pre-multiplied by
! [- ISIGN i\omega\mu_0]
! to yield
! [- ISIGN i\omega\mu_0 j]
! on input to this routine. Note that this also holds for the secondary field
! formulation, where
! j = dsigma * e,
! as well as for the tidal forcing, where
! j = sigma (v x B).
! However, we still want to pre-compute the source RHS outside of this
! routine, for "generality".
! Specifically, Jmult supplies an interior source on the RHS that is
! not physical and is not pre-multiplied by that factor (except in Pmult).
! So it's cleaner to pass on the complete interior forcing in bRHS.
! For divergence correction, we divide by [+ ISIGN i\omega\mu_0] to get
! i[- Div(j)].
! The plus sign is needed because we're taking the divergence of
! curl(curl(E)) + ISIGN i\omega\mu_0 sigma E = f - curl(curl(b))
! Terms 1 and 4 vanishes, leaving:
! Div(sigma E) - Div(f)/(+ ISIGN i\omega\mu_0) = 0.
! For a physical source j, this is equivalent to Div(sigma E) + Div(j) = 0;
! but the divergence correction may be applied also for non-physical sources,
! such as in Jmult ('FWD') and JmultT ('TRN').
subroutine FWDSolve3D(bRHS,omega,eSol,device_id)
! redefine some of the interfaces (locally) for our convenience
use sg_vector !, only: copy => copy_cvector, &
use vectranslate ! translate back and forth between Cvec and vec
use solver
use spoptools
! generic routines for vector operations on the edge/face nodes
! in a staggered grid
! in cvec copy, remember the order is copy(new, old) i.e new = old
implicit none
! INPUTS:
type (RHS_t), intent(in) :: bRHS
real(kind=prec), intent(in) :: omega
integer,optional,intent(in) :: device_id ! use GPU device
! OUTPUTS:
! eSol must be allocated before calling this routine
type (cvector), intent(inout) :: eSol
! LOCAL VARIABLES
logical :: converged,trans
integer :: iter, fid, ierr
integer :: Ne,Nei,Nni,Nn,i
complex(kind=prec) :: iOmegaMuInv
! e(lectric field) s(ource) b(rhs) phi0(div(s))
complex(kind=prec), pointer, dimension (:) :: e,s,b
complex(kind=prec), allocatable, dimension (:) :: ei,si,phi0
complex(kind=prec), allocatable, dimension (:) :: temp, stemp
character(80) :: cfile
! band-aid cvector ...
type (cvector) :: tvec
! diagnostic structure for Krylov Subspace Solvers(KSS)
type (solverControl_t) :: KSSiter
! initialize solver diagnostic variables
nIterTotal = 0
nDivCor = 0
EMrelErr = R_ZERO
divJ = R_ZERO
DivCorRelErr = R_ZERO
failed = .false.
trans = (bRHS%adj .eq. TRN)
iOmegaMuInv = C_ONE/cmplx(0.0,1.0d0*ISIGN*omega*MU_0,kind=prec)
if (.not.eSol%allocated) then
call errStop('eSol in EMsolve not allocated yet')
else
! determine the edge numbers of the mesh
! need to write a interface for these
! since these will be private after debugging
Nei = size(EDGEi,1)
Ne = size(EDGEb,1)+Nei
if (output_level > 3) then
write(*,'(a36,i8,a4,i8)') 'FWDSolve3D model grid #edges: Nei=', &
Nei,' Ne=',Ne
end if
end if
! allocate/initialize local data structures
! cboundary is a quite complex type...
! *essentially it should be e(EDGEb)
! for now we don't have an interface to deal with cboundary
! so just use cvectors to deliver the value...
call create_cvector(bRHS%grid, tvec, eSol%gridtype)
allocate(e(Ne))
allocate(ei(Nei))
allocate(s(Ne))
allocate(si(Nei))
allocate(b(Nei))
allocate(temp(Ne))
allocate(stemp(Nei))
! at this point e should be all zeros if there's no initial guess
call getCVector(eSol,e)
if(bRHS%nonZero_Source) then ! source (TRN)
! this is for *all* nodes
Nni = size(NODEi,1)
Nn = size(NODEb,1) + Nni
if (output_level > 3) then
write(*,'(a36,i8,a4,i8)') 'FWDSolve3D source grid #nodes: Nni=',&
& Nni,' Nn=',Nn
end if
! uncomment the following line to try divergence correction in CCGD
! allocate(phi0(Nn)) ! make sure you *WANT* to do this, first!
endif
! Using boundary condition and sources from rHS data structure
! construct vector b (defined only on interior nodes) for rHS of
! reduced (interior nodes only) linear system of equations
if(trans) then ! TRN, trans=.true.
! In this case boundary conditions do not enter into forcing
! for reduced (interior node) linear system; solution on
! boundary is determined after solving for interior nodes
if (bRHS%nonZero_Source) then
if (bRHS%sparse_Source) then
! sparse source
! not sure how to do it efficiently with normal array
! for now it is just a walkaround, probably not going to
! be used by most
call add_scvector(C_ONE,bRHS%sSparse,tvec)
call getVector(tvec,s) !s is of size nEdge (all edges)
else
! normal source
call getVector(bRHS%s,s)
endif
else
! doesn't need to tamper with this part for sparse matrix
! let it go with cvectors...
call zero(eSol)
write(0,*) 'Warning: no sources for adjoint problem'
write(0,*) 'Solution is identically zero'
if(bRHS%nonzero_BC) then
! just copy input BC into boundary nodes of solution and return
Call setBC(bRHS%bc, eSol)
endif ! otherwise the eSol should be all zeros
return
endif
! NOTE that here we DO NOT divide the source by volume weights before
! the Div as the divcorr operation in SP is using VDiv instead of Div
si = s(EDGEi) ! taking only the interior edges
! note that Div is formed from inner edges to all nodes
! uncomment the following line, to do divergence correction
! call Div(si,phi0)
! divide by iOmegaMu and Volume weight to get the source term j
si = si * iOmegaMuInv / Vedge(EDGEi)
! calculate the modification term V_E GD_II j
call RMATxCVEC(GDii,si,stemp)
! now i\omega\mu_0 V_E j + V_E GD_II j
b = s(EDGEi) + stemp * Vedge(EDGEi)
else ! trans = .false.
! In the usual forward model case BC does enter into forcing
! First compute contribution of BC term to RHS of reduced interior
! node system of equations : - A_IB*b
if (bRHS%nonzero_BC) then
! copy from rHS structure into zeroed complex edge vector
! note that bRHS%bc is a cboundary type
Call setBC(bRHS%bc, tvec) ! setBC -> copy_bcvector
! get info form BC
call getVector(tvec,s)
! but only the boundary parts
e(EDGEb) = s(EDGEb)
! Then multiply by curl_curl operator (use Mult_Aib ...
! Note that Mult_Aib is already multiplied by volume weights
! required to symmetrize the problem, so the result is V*A_IB*b)
! essentially b = A(i,b)*e(b)
Call Mult_Aib(e(EDGEb), trans, b)
endif
! Add internal sources if appropriate:
! Note that these must be multiplied explictly by volume weights
! [V_E^{-1} C_II^T V_F] C_II e + i\omega\mu_0\sigma e
! = - i\omega\mu_0 j - V_E^{-1} G_IA \Lambda D_AI j
! - [V_E^{-1} C_II^T V_F] C_IB b
! here we multiply by V_E throughout to obtain a symmetric system:
! V_E A_II e = - i\omega\mu_0 V_E j - V_E GD_II j - V_E A_IB b
! where
! A_II = V_E^{-1} C_II^T V_F C_II + i\omega\mu_0 \sigma,
! while
! A_IB = V_E^{-1} C_II^T V_F C_IB,
! and
! GD_II = V_E{-1} G_IA \Lambda D_AI.
if (bRHS%nonzero_Source) then
if (bRHS%sparse_Source) then
! sparse source
call zero(tvec)
call add_scvector(C_ONE,bRHS%sSparse,tvec)
call getVector(tvec,s)
else
! normal source
call getVector(bRHS%s, s)
endif
! At this point, s = - ISIGN * i\omega\mu_0 j
! Now Div(s) - will later divide by i_omega_mu to get the general
! divergence correction (j)
temp = s*Vedge
! uncomment the following line to do divergence correction
! call Div(temp(EDGEi), phi0)
! now temp = - ISIGN * i\omega\mu_0 V_E j
! divide by iOmegaMu to get the source term (j)
si = s(EDGEi) * iOmegaMuInv
! calculate the modification term GD_II j
call RMATxCVEC(GDii,si,stemp)
! i\omega\mu_0 V_E j + V_E GD_II j
stemp = temp(EDGEi) + stemp * Vedge(EDGEi)
! now add the V_E A_IB b term
if(bRHS%nonzero_BC) then
b = stemp - b
else
b = stemp
endif
else ! there is no source
b = -b
endif
endif
! uncomment the following 3 lines to do divergence correction
! if (bRHS%nonzero_Source) then
! phi0 = phi0 * iOmegaMuInv ! 1/i_omega_mu
! endif
! Outer part of KSS loop ... alternates between Calls to KSS solver
! and Calls to divcor ... this will be part of EMsolve
!
! e = current best solution (only on interior edges)
! b = rHS
! resetting
nIterTotal = 0
nDivCor = 0
! Initialize iteration control/diagnostic structure for KSS
if (trans) then
KSSiter%tol = tolEMadj
else
if (bRHS%nonzero_BC) then
KSSiter%tol = tolEMfwd
else
KSSiter%tol = tolEMadj
end if
end if
KSSiter%niter = 0
#if defined(CUDA) || defined(HIP)
! FIXME this is now hard coded here
! need a more elegant way to deal with it
KSSiter%maxIt = maxIterTotal
MaxDivCor = 1
#else
KSSiter%maxIt = IterPerDivCor
call reset_time(timer)
#endif
allocate(KSSiter%rerr(KSSiter%maxIt))
KSSiter%rerr = 0.0
converged = .false.
failed = .false.
! just take the interior elements
! Note: e here can be used for some initial guess
ei = e(EDGEi)
! idea to test: for non-zero source START with divergence
! correction
! if(bRHS%nonzero_Source) then
! nDivCor = 1
! Call SdivCorr(ei,phi0)
! endif
loop: do while ((.not.converged).and.(.not.failed))
#if defined(CUDA) || defined(HIP)
if (device_id.ge.0) then
! before start, need to tell if the device is available
ierr = cf_hookDev(device_id)
call reset_time(timer)
if (trim(solver_name) .eq. 'PCG') then
write(*,*) '[WARNING] GPU PCG is not yet implemented'
write(*,*) '[WARNING] Fall back to CPU version of PCG'
write(*,*) 'I am using PCG with initial relative error ', &
& KSSiter%rerr(1)
Call PCG(b, ei, KSSiter)
elseif (trim(solver_name) .eq. 'QMR') then
write(*,*) '[WARNING] GPU QMR is not yet implemented '
write(*,*) '[WARNING] Fall back to CPU version of QMR'
write(*,*) 'I am using QMR with initial relative error ', &
& KSSiter%rerr(1)
Call QMR(b, ei, KSSiter)
elseif (trim(solver_name) .eq. 'TFQMR') then
write(*,*) '[WARNING] GPU TFQMR is not yet implemented ', &
& KSSiter%rerr(1)
write(*,*) '[WARNING] Fall back to CPU version of TFQMR'
write(*,*) 'I am using TFQMR with initial relative error ', &
& KSSiter%rerr(1)
Call TFQMR(b, ei, KSSiter)
elseif (trim(solver_name) .eq. 'BICG') then
write(*,*) 'I am using BICG with initial relative error ', &
& KSSiter%rerr(1)
Call BiCG(b, ei, KSSiter, device_id)
else
write(1,*) 'ERROR: Unknown Forward Solver Method: ', &
& trim(solver_name)
write(6,*) '[WARNING] Fall back to CPU version of TFQMR'
write(6,*) 'I am using TFQMR with initial relative error ', &
& KSSiter%rerr(1)
Call TFQMR(b, ei, KSSiter)
end if
else
write(6,*) '[WARNING] could not find a valid GPU...'
if (trim(solver_name) .eq. 'PCG') then
write(6,*) '[WARNING] Fall back to CPU version of PCG'
write(6,*) 'I am using PCG with initial relative error ', &
& KSSiter%rerr(1)
Call PCG(b, ei, KSSiter)
elseif (trim(solver_name) .eq. 'QMR') then
write(6,*) '[WARNING] Fall back to CPU version of QMR'
write(6,*) 'I am using QMR with initial relative error ', &
& KSSiter%rerr(1)
Call QMR(b, ei, KSSiter)
elseif (trim(solver_name) .eq. 'TFQMR') then
write(6,*) '[WARNING] Fall back to CPU version of TFQMR'
write(6,*) 'I am using TFQMR with initial relative error ', &
& KSSiter%rerr(1)
Call TFQMR(b, ei, KSSiter)
elseif (trim(solver_name) .eq. 'BICG') then
write(6,*) '[WARNING] Fall back to CPU version of BICG'
write(6,*) 'I am using BICG with initial relative error ', &
& KSSiter%rerr(1)
Call BiCG(b, ei, KSSiter)
else
write(1,*) 'ERROR: Unknown Forward Solver Method: ', &
& trim(solver_name)
write(6,*) '[WARNING] Fall back to CPU version of TFQMR'
write(6,*) 'I am using TFQMR with initial relative error ', &
& KSSiter%rerr(1)
Call TFQMR(b, ei, KSSiter)
end if
end if
#else
if (trim(solver_name) .eq. 'PCG') then
write(6,*) 'I am using PCG with initial relative error ', &
& KSSiter%rerr(1)
Call PCG(b, ei, KSSiter)
elseif (trim(solver_name) .eq. 'QMR') then
write(6,*) 'I am using QMR with initial relative error ', &
& KSSiter%rerr(1)
Call QMR(b, ei, KSSiter)
elseif (trim(solver_name) .eq. 'TFQMR') then
write(6,*) 'I am using TFQMR with initial relative error ', &
& KSSiter%rerr(1)
Call TFQMR(b, ei, KSSiter)
elseif (trim(solver_name) .eq. 'BICG') then
write(6,*) 'I am using BICG with initial relative error ', &
& KSSiter%rerr(1)
Call BiCG(b, ei, KSSiter)
else
write(1,*) 'ERROR: Unknown Forward Solver Method: ', trim(solver_name)
write(6,*) '[WARNING] Fall back to TFQMR'
write(6,*) 'I am using TFQMR with initial relative error ', &
& KSSiter%rerr(1)
Call TFQMR(b, ei, KSSiter)
end if
#endif
! algorithm is converged when the relative error is less than tolerance
! (in which case KSSiter%niter will be less than KSSiter%maxIt)
converged = KSSiter%niter .lt. KSSiter%maxIt
! there are two ways of failing:
! 1) the specific KSS did not work or
! 2) total number of divergence corrections exceeded
failed = failed .or. KSSiter%failed
! update diagnostics output from KSS
do iter = 1,KSSiter%niter
EMrelErr(nIterTotal+iter) = KSSiter%rerr(iter)
end do
if (KSSiter%niter.eq.0) then ! in case a initial guess is good enough
KSSiter%niter = 1
EMrelErr(KSSiter%niter) = KSSiter%rerr(1)
endif
nIterTotal = nIterTotal + KSSiter%niter
nDivCor = nDivCor+1
if( nDivCor < MaxDivCor) then
! uncomment the following lines to try divergence correction after
! solving the system matrix...
! if(bRHS%nonzero_Source) then
! Call SdivCorr(ei,phi0)
! else
! Call SdivCorr(ei)
! endif
else
! max number of divergence corrections exceeded; convergence failed
failed = .true.
endif
if (output_level > 3) then
write (6,*) 'iter: ', nIterTotal, ' residual: ', &
& EMrelErr(nIterTotal)
end if
end do loop
if (output_level > 2) then
write (*,'(a12,a20,i8,g15.7)') node_info, 'finished solving:', &
& nIterTotal, EMrelErr(nIterTotal)
write (*,'(a12,a22,f12.6)') node_info, 'solving time (sec): ', &
& elapsed_time(timer)
end if
e(EDGEi) = ei
! After solving symetrized system, need to do different things for
! transposed, standard cases
if(trans) then ! trans = .true.
! compute solution on boundary nodes: first A_IB^T eSol
call Mult_Aib(ei ,trans, s)
! Multiply solution on interior nodes by volume weights
! but after filling the solution on boundary
temp = Vedge*e
e = temp
! then b - A_IB^T eSol, where b is input boundary values (if any)
if(bRHS%nonzero_BC) then
e(EDGEb) = e(EDGEb) - s(EDGEb)
else
e(EDGEb) = -s(EDGEb)
endif
else ! trans = .false.
! just copy input BC into boundary nodes of solution
if(.not.bRHS%nonzero_BC) then
e(EDGEb) = 0
endif
endif
call setVector(e,eSol)
! deallocate local temporary arrays
deallocate(e)
deallocate(ei)
deallocate(s)
deallocate(si)
deallocate(b)
deallocate(temp)
deallocate(stemp)
! uncomment the following lines for divergence correction
! if(bRHS%nonzero_Source) then
! deallocate(phi0)
! end if
Call deall(tvec)
deallocate(KSSiter%rerr)
! Release GPU lock so other processes can hook on
! NOTE: do NOT call cf_cleanupLock() here — the shared-memory lock
! must persist across transmitter iterations
#if defined(CUDA) || defined(HIP)
if (device_id >= 0) then
call cf_releaseDev(device_id)
end if
#endif
end subroutine FWDsolve3D
#if defined(MPI) && defined(FG)
! fine-grained parallel version
subroutine FWDsolve3Dfg(bRHS,omega,eSol,device_id,comm_local)
!----------------------------------------------------------------------
! redefine some of the interfaces (locally) for our convenience
use sg_vector !, only: copy => copy_cvector, &
use vectranslate ! translate back and forth between Cvec and vec
use solver
use spoptools
! generic routines for vector operations on the edge/face nodes
! in a staggered grid
! in cvec copy, remember the order is copy(new, old) i.e new = old
implicit none
! INPUTS:
type (RHS_t), intent(in) :: bRHS
real(kind=prec), intent(in) :: omega
integer, intent(in) :: device_id
integer, intent(in) :: comm_local
! OUTPUTS:
! eSol must be allocated before calling this routine
type (cvector), intent(inout) :: eSol
!----------------------------------------------------------------------
! variables related to parallel computation
!----------------------------------------------------------------------
integer, dimension(:), allocatable :: idx
integer, dimension(:), pointer :: isizes, isubs, displs
integer, dimension(3) :: iedges
integer :: nrow, ncol, nnz ! spMAT parameter
integer :: block_size
integer :: rank_local,size_local
integer :: ierr
integer :: Nsub,Ntotal,istart,iend,csize
integer, allocatable, dimension(:) :: ilocal,jlocal
real(kind=prec) , dimension (:), allocatable :: vlocal
complex(kind=prec), dimension (:), allocatable :: clocal
complex(kind=prec), dimension (:), allocatable :: xlocal
complex(kind=prec), dimension (:), allocatable :: blocal
real(kind=prec) :: ptol=1e-2
real :: normu
!----------------------------------------------------------------------
! LOCAL VARIABLES
logical :: converged,trans
integer :: iter, fid
integer :: Ne,Nei,Neb
integer :: Nn,Nni,Nnb,i
complex(kind=prec) :: iOmegaMuInv
! e(lectric field) s(ource) b(rhs) phi0(div(s))
complex(kind=prec), pointer, dimension (:) :: e,s
complex(kind=prec), allocatable, dimension (:) :: ei,b,si,phi0,phii
complex(kind=prec), allocatable, dimension (:) :: temp,stemp
character(80) :: cfile
! band-aid cvector ...
type (cvector) :: tmpvec
! diagnostic structure for Krylov Subspace Solvers(KSS)
type (solverControl_t) :: KSSiter
! initialize solver diagnostic variables
! now initialize solver diagnostic variables
nIterTotal = 0
nDivCor = 0
EMrelErr = R_ZERO
divJ = R_ZERO
DivCorRelErr = R_ZERO
failed = .false.
iOmegaMuInv = C_ONE/cmplx(0.0,1.0d0*ISIGN*omega*MU_0,kind=prec)
! now see how many workers do we have
call MPI_COMM_RANK(comm_local,rank_local,ierr)
call MPI_COMM_SIZE(comm_local,size_local,ierr)
!------------------------------------------------------------------------
! check the input variables
!------------------------------------------------------------------------
if (rank_local.eq.0) then ! leader
trans = (bRHS%adj .eq. TRN)
if (.not.eSol%allocated) then
call errStop('eSol in EMsolve not allocated yet')
end if
! determine the edge numbers of the mesh
! need to write a interface for these
! since these will be private after debugging
Nei = size(EDGEi,1)
Neb = size(EDGEb,1)
Ne = Nei+Neb
if(bRHS%nonZero_Source) then ! source (TRN)
! this is for *all* nodes
Nni = size(NODEi,1)
Nnb = size(NODEb,1)
Nn = Nni+Nnb
if (output_level > 3) then
write(*,'(a36,i8,a4,i8)') &
& 'FWDSolve3D source grid #nodes: Nni=',&
& Nni,' Nn=',Nn
end if
! uncomment the following line to try divergence correction in CCGD
! allocate(phi0(Nn)) ! make sure you *WANT* to do this, first!
endif
iedges(1) = eSol%Nx*(eSol%Ny-1)*(eSol%Nz-1)
iedges(2) = eSol%Ny*(eSol%Nx-1)*(eSol%Nz-1)
iedges(3) = eSol%Nz*(eSol%Nx-1)*(eSol%Ny-1)
end if
! common part for leader and workers
! broadcast those parameters to all workers
call MPI_BCAST(trans,1, MPI_LOGICAL,0, comm_local,ierr)
call MPI_BCAST(Nei,1, MPI_INTEGER,0, comm_local,ierr)
call MPI_BCAST(Neb,1, MPI_INTEGER,0, comm_local,ierr)
call MPI_BCAST(Ne ,1, MPI_INTEGER,0, comm_local,ierr)
call MPI_BCAST(Nni,1, MPI_INTEGER,0, comm_local,ierr)
call MPI_BCAST(Nnb,1, MPI_INTEGER,0, comm_local,ierr)
call MPI_BCAST(Nn ,1, MPI_INTEGER,0, comm_local,ierr)
call MPI_BCAST(iedges ,3, MPI_INTEGER,0, comm_local,ierr)
! calculate the sizes of each local row matrix
! as well as the size of block preconditioners
! *note* every process knows about this
call calc_dist(size_local,iedges,isizes,isubs)
! now setup the displacement to send to each process
allocate(displs(size_local))
displs = 0
do i=2,size_local
displs(i) = sum(isizes(1:i-1))
end do
! output information for debug
Ntotal = size(isubs)
csize = 0
Nsub = 0
istart = 1
do i=1,Ntotal
csize = csize + isubs(i)
if (csize.le.sum(isizes(1:rank_local))) then ! go on
istart = istart + 1
elseif (csize.le.sum(isizes(1:rank_local+1))) then
! count sub-blocks in the local block
Nsub = Nsub + 1
else
exit
end if
end do
iend = istart+Nsub-1
if (output_level > 3) then
! for debug
write(6,*) 'number of sub blocks =', Nsub, rank_local
write(6,*) 'from #', istart, 'to #', iend, rank_local
end if
if (rank_local .eq. 0) then !leader
! leader does all the works to allocate/initialize
! local data structures
if (output_level > 3) then
! for debug
write(6,*) 'system matrix iedges =', iedges
write(6,*) 'system matrix isubs =', isubs
write(6,*) 'system matrix isizes =', isizes
endif
! cboundary is a quite complex type...
! *essentially it should be e(EDGEb)
! for now we don't have an interface to deal with cboundary
! so just use cvectors to deliver the value...
call create_cvector(bRHS%grid, tmpvec, eSol%gridtype)
allocate(e(Ne))
allocate(ei(Nei))
allocate(s(Ne))
allocate(si(Nei))
allocate(b(Nei))
allocate(temp(Ne))
allocate(stemp(Nei))
! at this point e should be all zeros if there's no initial guess
call getCVector(eSol,e)
! Using boundary condition and sources from rHS data structure
! construct vector b (defined only on interior nodes) for rHS of
! reduced (interior nodes only) linear system of equations
if (trans) then ! TRN, trans=.true.
! In this case boundary conditions do not enter into forcing
! for reduced (interior node) linear system; solution on
! boundary is determined after solving for interior nodes
if (bRHS%nonZero_Source) then
if (bRHS%sparse_Source) then
! sparse source
! not sure how to do it efficiently with normal array
! for now it is just a walkaround, probably not going to
! be used by most
call add_scvector(C_ONE,bRHS%sSparse,tmpvec)
call getVector(tmpvec,s)
else
! normal source
call getVector(bRHS%s,s)
endif
else
! doesn't need to tamper with this part for sparse matrix
! let it go with cvectors...
call zero(eSol)
write(0,*) 'Warning: no sources for adjoint problem'
write(0,*) 'Solution is identically zero'
if (bRHS%nonzero_BC) then
! just copy input BC into boundary nodes of solution
! and return
Call setBC(bRHS%bc, eSol)
endif ! otherwise the eSol should be all zeros
return
endif
! NOTE that here we DO NOT divide the source by volume weights
! before the Div as the divcorr operation in SP is using VDiv
! instead of Div
si = s(EDGEi) ! taking only the interior edges
! note that Div is formed from inner edges to all nodes
! uncomment the following line, to do divergence correction
! call Div(si,phi0)
! divide by iOmegaMu and Volume weight to get the source term j
si = si * iOmegaMuInv / Vedge(EDGEi)
! calculate the modification term V_E GD_II j
call RMATxCVEC(GDii,si,stemp)
! now i\omega\mu_0 V_E j + V_E GD_II j
b = s(EDGEi) + stemp * Vedge(EDGEi)
else ! trans = .false.
! In the usual forward model case BC does enter into forcing
! First compute contribution of BC term to RHS of reduced
! interior node system of equations : - A_IB*b
if (bRHS%nonzero_BC) then
! copy from rHS structure into zeroed complex edge vector
! note that bRHS%bc is a cboundary type
Call setBC(bRHS%bc, tmpvec) ! setBC -> copy_bcvector
! get info form BC
call getVector(tmpvec,s)
! but only the boundary parts
e(EDGEb) = s(EDGEb)
! Then multiply by curl_curl operator (use Mult_Aib ...
! Note that Mult_Aib already multiplies by volume weights
! required to symetrize problem, so the result is V*A_IB*b)
! essentially b = A(i,b)*e(b)
Call Mult_Aib(e(EDGEb), trans, b)
endif
! Add internal sources if appropriate:
! Note that these must be multiplied explictly by volume weights
! [V_E^{-1} C_II^T V_F] C_II e + i\omega\mu_0\sigma e
! = - i\omega\mu_0 j - V_E^{-1} G_IA \Lambda D_AI j
! - [V_E^{-1} C_II^T V_F] C_IB b
! here we multiply by V_E throughout to obtain a symmetric system:
! V_E A_II e = - i\omega\mu_0 V_E j - V_E GD_II j - V_E A_IB b
! where
! A_II = V_E^{-1} C_II^T V_F C_II + i\omega\mu_0 \sigma,
! while
! A_IB = V_E^{-1} C_II^T V_F C_IB,
! and
! GD_II = V_E{-1} G_IA \Lambda D_AI.
if (bRHS%nonzero_Source) then
if (bRHS%sparse_Source) then
! sparse source
call zero(tmpvec)
call add_scvector(C_ONE,bRHS%sSparse,tmpvec)
call getVector(tmpvec,s)
else
! normal source
call getVector(bRHS%s, s)
endif
! At this point, s = - ISIGN * i\omega\mu_0 j
! Now Div(s) - will later divide by i_omega_mu to get the
! general divergence correction (j)
temp = s*Vedge
! now temp = - ISIGN * i\omega\mu_0 V_E j
! divide by iOmegaMu to get the source (j)
si = s(EDGEi) * iOmegaMuInv
! calculate the modification term GD_II j
call RMATxCVEC(GDii,si,stemp)
! i\omega\mu_0 V_E j + V_E GD_II j
stemp = temp(EDGEi) + stemp * Vedge(EDGEi)
! now add the V_E A_IB b term
if(bRHS%nonzero_BC) then
b = stemp - b
else
b = stemp
endif
else! there is no source
b = -b
endif
endif ! trans
endif ! if rank == 0
!-------------------------------------------------------------------------
! now start to decompose the system matrix
!-------------------------------------------------------------------------
if (rank_local.eq.0) then ! leader
if (output_level > 2) then
write (*,'(a12,a25,a15,i8)') node_info,'sending sub-systems to', &
& ' workers...', rank_local
endif
! firstly leader split the system matrix AAii (real)
! now calculate the rows that should be stored locally...
! AAii (Nei x Nei)
do i = 2,size_local !now send those to your fellow workers
call splitMAT(AAii,i-1,size_local,Alocal,isizes)
nrow = size(Alocal%row)
ncol = size(Alocal%col)
nnz = ncol
! send the info to workers
call MPI_SEND(nrow,1,MPI_INTEGER,i-1, 1,comm_local,ierr)
call MPI_SEND(ncol,1,MPI_INTEGER,i-1, 1,comm_local,ierr)
call MPI_SEND(nnz,1,MPI_INTEGER,i-1, 1,comm_local,ierr)
! now send the local matrix (in CSR format) that will be
! stored in that worker process
call MPI_SEND(Alocal%row,nrow, MPI_INTEGER,i-1,2, comm_local,ierr)
call MPI_SEND(Alocal%col,ncol, MPI_INTEGER,i-1,2, comm_local,ierr)
call MPI_SEND(Alocal%val,nnz, MPI_DOUBLE,i-1,2, &
& comm_local, ierr)
call deall_spMatCSR(Alocal) ! and release the temp sp matrix
end do
! now deal with the local rows in leader
call splitMAT(AAii,rank_local,size_local,Alocal,isizes)
! this is required as the original splitMAT is designed for PETSc
! (c index that starts from 0)
Alocal%col = Alocal%col+1
Alocal%row = Alocal%row+1
else !workers
if (output_level > 2) then
write (*,'(a12,a25,a15,i8)') node_info,'receiving sub-systems', &
& ' from leader...', rank_local
endif
! get the info from leader
call MPI_RECV(nrow,1, MPI_INTEGER,0,1, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(ncol,1, MPI_INTEGER,0,1, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(nnz,1, MPI_INTEGER,0,1, comm_local, &
& MPI_STATUS_IGNORE,ierr)
! now get the local matrix (in CSR format)
allocate(ilocal(nrow))
allocate(jlocal(ncol))
allocate(vlocal(nnz))
call MPI_RECV(ilocal,nrow, MPI_INTEGER,0,2, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(jlocal,ncol, MPI_INTEGER,0,2, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(vlocal,nnz, MPI_DOUBLE,0,2, comm_local,&
& MPI_STATUS_IGNORE,ierr)
! now assemble the matrix manually
call create_spMatCSR_Real(isizes(rank_local+1),Nei,nnz,Alocal)
! this is required as the original splitMAT is designed for PETSc
! (c index that starts from 0)
Alocal%row=ilocal+1
Alocal%col=jlocal+1
Alocal%val=vlocal
Alocal%allocated=.true.
deallocate(ilocal)
deallocate(jlocal)
deallocate(vlocal)
end if
!-------------------------------------------------------------------------
! now start to decompose the L/U matrix
!-------------------------------------------------------------------------
if (rank_local.eq.0) then ! leader
! firstly leader split the system matrix L/U (complex)
! now calculate the blocks that should be stored locally...
! L/U (Nei x Nei)
do i = 2,size_local !now send those to your fellow workers
! L matrix
call splitBlkMAT(L,i-1,size_local,Llocal,isizes)
nrow = size(Llocal%row)
ncol = size(Llocal%col)
nnz = ncol
! send the info to workers
call MPI_SEND(nrow,1,MPI_INTEGER,i-1, 1,comm_local,ierr)
call MPI_SEND(ncol,1,MPI_INTEGER,i-1, 1,comm_local,ierr)
call MPI_SEND(nnz,1,MPI_INTEGER,i-1, 1,comm_local,ierr)
! now send the local matrix (in CSR format) that will be
! stored in that worker process
call MPI_SEND(Llocal%row,nrow, MPI_INTEGER,i-1,2, comm_local,ierr)
call MPI_SEND(Llocal%col,ncol, MPI_INTEGER,i-1,2, comm_local,ierr)
call MPI_SEND(Llocal%val,nnz, MPI_DOUBLE_COMPLEX,i-1,2, &
& comm_local, ierr)
call deall_spMatCSR(Llocal) ! and release the temp sp matrix
! U matrix
call splitBlkMAT(U,i-1,size_local,Ulocal,isizes)
nrow = size(Ulocal%row)
ncol = size(Ulocal%col)
nnz = ncol
! send the info to workers
call MPI_SEND(nrow,1,MPI_INTEGER,i-1, 1,comm_local,ierr)
call MPI_SEND(ncol,1,MPI_INTEGER,i-1, 1,comm_local,ierr)
call MPI_SEND(nnz,1,MPI_INTEGER,i-1, 1,comm_local,ierr)
! now send the local matrix (in CSR format) that will be
! stored in that worker process
call MPI_SEND(Ulocal%row,nrow, MPI_INTEGER,i-1,2, comm_local,ierr)
call MPI_SEND(Ulocal%col,ncol, MPI_INTEGER,i-1,2, comm_local,ierr)
call MPI_SEND(Ulocal%val,nnz, MPI_DOUBLE_COMPLEX,i-1,2, &
& comm_local, ierr)
call deall_spMatCSR(Ulocal) ! and release the temp sp matrix
end do
! now deal with the local rows in leader
call splitBlkMAT(L,rank_local,size_local,Llocal,isizes)
call splitBlkMAT(U,rank_local,size_local,Ulocal,isizes)
else !workers
! L
! get the info from leader
call MPI_RECV(nrow,1, MPI_INTEGER,0,1, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(ncol,1, MPI_INTEGER,0,1, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(nnz,1, MPI_INTEGER,0,1, comm_local, &
& MPI_STATUS_IGNORE,ierr)
! now get the local matrix (in CSR format)
allocate(ilocal(nrow))
allocate(jlocal(ncol))
allocate(clocal(nnz))
call MPI_RECV(ilocal,nrow, MPI_INTEGER,0,2, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(jlocal,ncol, MPI_INTEGER,0,2, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(clocal,nnz, MPI_DOUBLE_COMPLEX,0,2, comm_local,&
& MPI_STATUS_IGNORE,ierr)
! now assemble the matrix manually
call create_spMatCSR_Cmplx(isizes(rank_local+1),isizes(rank_local+1),&
& nnz,Llocal)
Llocal%row=ilocal
Llocal%col=jlocal
Llocal%val=clocal
Llocal%allocated=.true.
! setup the triangular flags
Llocal%lower=.true.
deallocate(ilocal)
deallocate(jlocal)
deallocate(clocal)
! U
! get the info from leader
call MPI_RECV(nrow,1, MPI_INTEGER,0,1, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(ncol,1, MPI_INTEGER,0,1, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(nnz,1, MPI_INTEGER,0,1, comm_local, &
& MPI_STATUS_IGNORE,ierr)
! now get the local matrix (in CSR format)
allocate(ilocal(nrow))
allocate(jlocal(ncol))
allocate(clocal(nnz))
call MPI_RECV(ilocal,nrow, MPI_INTEGER,0,2, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(jlocal,ncol, MPI_INTEGER,0,2, comm_local, &
& MPI_STATUS_IGNORE,ierr)
call MPI_RECV(clocal,nnz, MPI_DOUBLE_COMPLEX,0,2, comm_local,&
& MPI_STATUS_IGNORE,ierr)
! now assemble the matrix manually
call create_spMatCSR_Cmplx(isizes(rank_local+1),isizes(rank_local+1),&
& ncol,Ulocal)
Ulocal%row=ilocal
Ulocal%col=jlocal
Ulocal%val=clocal
Ulocal%allocated=.true.
! setup the triangular flags
Ulocal%upper=.true.
deallocate(ilocal)
deallocate(jlocal)
deallocate(clocal)