elpa1_merge_systems_real_template.X90 37 KB
Newer Older
Pavel Kus's avatar
Pavel Kus committed
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
#if 0
!    This file is part of ELPA.
!
!    The ELPA library was originally created by the ELPA consortium,
!    consisting of the following organizations:
!
!    - Max Planck Computing and Data Facility (MPCDF), formerly known as
!      Rechenzentrum Garching der Max-Planck-Gesellschaft (RZG),
!    - Bergische Universität Wuppertal, Lehrstuhl für angewandte
!      Informatik,
!    - Technische Universität München, Lehrstuhl für Informatik mit
!      Schwerpunkt Wissenschaftliches Rechnen ,
!    - Fritz-Haber-Institut, Berlin, Abt. Theorie,
!    - Max-Plack-Institut für Mathematik in den Naturwissenschaften,
!      Leipzig, Abt. Komplexe Strukutren in Biologie und Kognition,
!      and
!    - IBM Deutschland GmbH
!
!    This particular source code file contains additions, changes and
!    enhancements authored by Intel Corporation which is not part of
!    the ELPA consortium.
!
!    More information can be found here:
!    http://elpa.mpcdf.mpg.de/
!
!    ELPA is free software: you can redistribute it and/or modify
!    it under the terms of the version 3 of the license of the
!    GNU Lesser General Public License as published by the Free
!    Software Foundation.
!
!    ELPA is distributed in the hope that it will be useful,
!    but WITHOUT ANY WARRANTY; without even the implied warranty of
!    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
!    GNU Lesser General Public License for more details.
!
!    You should have received a copy of the GNU Lesser General Public License
!    along with ELPA.  If not, see <http://www.gnu.org/licenses/>
!
!    ELPA reflects a substantial effort on the part of the original
!    ELPA consortium, and we ask you to respect the spirit of the
!    license that we chose: i.e., please contribute any changes you
!    may have back to the original ELPA library distribution, and keep
!    any derivatives of ELPA under the same license that we chose for
!    the original distribution, the GNU Lesser General Public License.
!
!
! ELPA1 -- Faster replacements for ScaLAPACK symmetric eigenvalue routines
!
! Copyright of the original code rests with the authors inside the ELPA
! consortium. The copyright of any additional modifications shall rest
! with their original authors, but shall adhere to the licensing terms
! distributed along with the original code in the file "COPYING".
#endif
    subroutine M_merge_systems_PRECISSION( na, nm, d, e, q, ldq, nqoff, nblk, matrixCols, mpi_comm_rows, mpi_comm_cols, &
                          l_col, p_col, l_col_out, p_col_out, npc_0, npc_n, wantDebug, success)

#ifdef HAVE_DETAILED_TIMINGS
      use timings
#endif
      use precision
      implicit none

      integer(kind=ik)              :: na, nm, ldq, nqoff, nblk, matrixCols, mpi_comm_rows, &
                                       mpi_comm_cols, npc_0, npc_n
      integer(kind=ik)              :: l_col(na), p_col(na), l_col_out(na), p_col_out(na)
      real(kind=REAL_DATATYPE)                 :: d(na), e
#ifdef USE_ASSUMED_SIZE
      real(kind=REAL_DATATYPE)                 :: q(ldq,*)
#else
      real(kind=REAL_DATATYPE)                 :: q(ldq,matrixCols)
#endif

      integer(kind=ik), parameter   :: max_strip=128      
      

      real(kind=REAL_DATATYPE)                 :: M_PRECISSION_LAMCH, M_PRECISSION_LAPY2
      real(kind=REAL_DATATYPE)                 :: beta, sig, s, c, t, tau, rho, eps, tol, &
                                       qtrans(2,2), dmax, zmax, d1new, d2new
      real(kind=REAL_DATATYPE)                 :: z(na), d1(na), d2(na), z1(na), delta(na),  &
                                       dbase(na), ddiff(na), ev_scale(na), tmp(na)
      real(kind=REAL_DATATYPE)                 :: d1u(na), zu(na), d1l(na), zl(na)
      real(kind=REAL_DATATYPE), allocatable    :: qtmp1(:,:), qtmp2(:,:), ev(:,:)
#ifdef WITH_OPENMP
      real(kind=REAL_DATATYPE), allocatable    :: z_p(:,:)
#endif

      integer(kind=ik)              :: i, j, na1, na2, l_rows, l_cols, l_rqs, l_rqe, &
                                       l_rqm, ns, info
      integer(kind=ik)              :: l_rnm, nnzu, nnzl, ndef, ncnt, max_local_cols, &
                                       l_cols_qreorg, np, l_idx, nqcols1, nqcols2
      integer(kind=ik)              :: my_proc, n_procs, my_prow, my_pcol, np_rows, &
                                       np_cols, mpierr
#ifdef WITH_MPI
      integer(kind=ik)              :: my_mpi_status(mpi_status_size)
#endif
      integer(kind=ik)              :: np_next, np_prev, np_rem
      integer(kind=ik)              :: idx(na), idx1(na), idx2(na)
      integer(kind=ik)              :: coltyp(na), idxq1(na), idxq2(na)

      logical, intent(in)           :: wantDebug
      logical, intent(out)          :: success
      integer(kind=ik)              :: istat
      character(200)                :: errorMessage

#ifdef WITH_OPENMP
      integer(kind=ik)              :: max_threads, my_thread
      integer(kind=ik)              :: omp_get_max_threads, omp_get_thread_num


      max_threads = omp_get_max_threads()

      allocate(z_p(na,0:max_threads-1), stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"merge_systems: error when allocating z_p "//errorMessage
        stop
      endif
#endif

#ifdef HAVE_DETAILED_TIMINGS
120
      call timer%start("merge_systems" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#endif
      success = .true.
#ifdef HAVE_DETAILED_TIMINGS
      call timer%start("mpi_communication")
#endif
      call mpi_comm_rank(mpi_comm_rows,my_prow,mpierr)
      call mpi_comm_size(mpi_comm_rows,np_rows,mpierr)
      call mpi_comm_rank(mpi_comm_cols,my_pcol,mpierr)
      call mpi_comm_size(mpi_comm_cols,np_cols,mpierr)
#ifdef HAVE_DETAILED_TIMINGS
      call timer%stop("mpi_communication")
#endif

      ! If my processor column isn't in the requested set, do nothing

      if (my_pcol<npc_0 .or. my_pcol>=npc_0+npc_n) then
#ifdef HAVE_DETAILED_TIMINGS
138
        call timer%stop("merge_systems" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#endif
        return
      endif
      ! Determine number of "next" and "prev" column for ring sends

      if (my_pcol == npc_0+npc_n-1) then
        np_next = npc_0
      else
        np_next = my_pcol + 1
      endif

      if (my_pcol == npc_0) then
        np_prev = npc_0+npc_n-1
      else
        np_prev = my_pcol - 1
      endif
      call M_check_monotony_PRECISSION(nm,d,'Input1',wantDebug, success)
      if (.not.(success)) then
#ifdef HAVE_DETAILED_TIMINGS
158
        call timer%stop("merge_systems" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
159
160
161
162
163
164
#endif
        return
      endif
      call M_check_monotony_PRECISSION(na-nm,d(nm+1),'Input2',wantDebug, success)
      if (.not.(success)) then
#ifdef HAVE_DETAILED_TIMINGS
165
        call timer%stop("merge_systems" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
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
#endif
        return
      endif
      ! Get global number of processors and my processor number.
      ! Please note that my_proc does not need to match any real processor number,
      ! it is just used for load balancing some loops.

      n_procs = np_rows*npc_n
      my_proc = my_prow*npc_n + (my_pcol-npc_0) ! Row major


      ! Local limits of the rows of Q

      l_rqs = local_index(nqoff+1 , my_prow, np_rows, nblk, +1) ! First row of Q
      l_rqm = local_index(nqoff+nm, my_prow, np_rows, nblk, -1) ! Last row <= nm
      l_rqe = local_index(nqoff+na, my_prow, np_rows, nblk, -1) ! Last row of Q

      l_rnm  = l_rqm-l_rqs+1 ! Number of local rows <= nm
      l_rows = l_rqe-l_rqs+1 ! Total number of local rows


      ! My number of local columns

      l_cols = COUNT(p_col(1:na)==my_pcol)

      ! Get max number of local columns

      max_local_cols = 0
      do np = npc_0, npc_0+npc_n-1
        max_local_cols = MAX(max_local_cols,COUNT(p_col(1:na)==np))
      enddo

      ! Calculations start here

      beta = abs(e)
      sig  = sign(M_CONST_1_0,e)

      ! Calculate rank-1 modifier z

      z(:) = 0

      if (MOD((nqoff+nm-1)/nblk,np_rows)==my_prow) then
        ! nm is local on my row
        do i = 1, na
          if (p_col(i)==my_pcol) z(i) = q(l_rqm,l_col(i))
         enddo
      endif

      if (MOD((nqoff+nm)/nblk,np_rows)==my_prow) then
        ! nm+1 is local on my row
        do i = 1, na
          if (p_col(i)==my_pcol) z(i) = z(i) + sig*q(l_rqm+1,l_col(i))
        enddo
      endif

      call M_global_gather_PRECISSION(z, na)
      ! Normalize z so that norm(z) = 1.  Since z is the concatenation of
      ! two normalized vectors, norm2(z) = sqrt(2).
      z = z/sqrt(M_CONST_2_0)
      rho = M_CONST_2_0*beta
      ! Calculate index for merging both systems by ascending eigenvalues
      call M_PRECISSION_LAMRG( nm, na-nm, d, 1, 1, idx )

! Calculate the allowable deflation tolerance

      zmax = maxval(abs(z))
      dmax = maxval(abs(d))
      EPS = M_PRECISSION_LAMCH( 'Epsilon' )
      TOL = M_CONST_8_0*EPS*MAX(dmax,zmax)

      ! If the rank-1 modifier is small enough, no more needs to be done
      ! except to reorganize D and Q

      IF ( RHO*zmax <= TOL ) THEN

        ! Rearrange eigenvalues

        tmp = d
        do i=1,na
          d(i) = tmp(idx(i))
        enddo

        ! Rearrange eigenvectors
        call M_resort_ev_PRECISSION(idx, na)

#ifdef HAVE_DETAILED_TIMINGS
252
        call timer%stop("merge_systems" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
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
#endif

        return
      ENDIF

      ! Merge and deflate system

      na1 = 0
      na2 = 0

      ! COLTYP:
      ! 1 : non-zero in the upper half only;
      ! 2 : dense;
      ! 3 : non-zero in the lower half only;
      ! 4 : deflated.

      coltyp(1:nm) = 1
      coltyp(nm+1:na) = 3

      do i=1,na

        if (rho*abs(z(idx(i))) <= tol) then

          ! Deflate due to small z component.

          na2 = na2+1
          d2(na2)   = d(idx(i))
          idx2(na2) = idx(i)
          coltyp(idx(i)) = 4

        else if (na1>0) then

          ! Check if eigenvalues are close enough to allow deflation.

          S = Z(idx(i))
          C = Z1(na1)

          ! Find sqrt(a**2+b**2) without overflow or
          ! destructive underflow.
          TAU = M_PRECISSION_LAPY2( C, S )
          T = D1(na1) - D(idx(i))
          C = C / TAU
          S = -S / TAU
          IF ( ABS( T*C*S ) <= TOL ) THEN

            ! Deflation is possible.

            na2 = na2+1

            Z1(na1) = TAU

            d2new = D(idx(i))*C**2 + D1(na1)*S**2
            d1new = D(idx(i))*S**2 + D1(na1)*C**2

            ! D(idx(i)) >= D1(na1) and C**2 + S**2 == 1.0
            ! This means that after the above transformation it must be
            !    D1(na1) <= d1new <= D(idx(i))
            !    D1(na1) <= d2new <= D(idx(i))
            !
            ! D1(na1) may get bigger but it is still smaller than the next D(idx(i+1))
            ! so there is no problem with sorting here.
            ! d2new <= D(idx(i)) which means that it might be smaller than D2(na2-1)
            ! which makes a check (and possibly a resort) necessary.
            !
            ! The above relations may not hold exactly due to numeric differences
            ! so they have to be enforced in order not to get troubles with sorting.


            if (d1new<D1(na1)  ) d1new = D1(na1)
            if (d1new>D(idx(i))) d1new = D(idx(i))

            if (d2new<D1(na1)  ) d2new = D1(na1)
            if (d2new>D(idx(i))) d2new = D(idx(i))

            D1(na1) = d1new

            do j=na2-1,1,-1
              if (d2new<d2(j)) then
                d2(j+1)   = d2(j)
                idx2(j+1) = idx2(j)
              else
                exit ! Loop
              endif
            enddo

            d2(j+1)   = d2new
            idx2(j+1) = idx(i)

            qtrans(1,1) = C; qtrans(1,2) =-S
            qtrans(2,1) = S; qtrans(2,2) = C
            call M_transform_columns_PRECISSION(idx(i), idx1(na1))
            if (coltyp(idx(i))==1 .and. coltyp(idx1(na1))/=1) coltyp(idx1(na1)) = 2
            if (coltyp(idx(i))==3 .and. coltyp(idx1(na1))/=3) coltyp(idx1(na1)) = 2

            coltyp(idx(i)) = 4

          else
            na1 = na1+1
            d1(na1) = d(idx(i))
            z1(na1) = z(idx(i))
            idx1(na1) = idx(i)
          endif
        else
          na1 = na1+1
          d1(na1) = d(idx(i))
          z1(na1) = z(idx(i))
          idx1(na1) = idx(i)
        endif

      enddo
      call M_check_monotony_PRECISSION(na1,d1,'Sorted1', wantDebug, success)
      if (.not.(success)) then
#ifdef HAVE_DETAILED_TIMINGS
366
        call timer%stop("merge_systems" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
367
368
369
370
371
372
#endif
        return
      endif
      call M_check_monotony_PRECISSION(na2,d2,'Sorted2', wantDebug, success)
      if (.not.(success)) then
#ifdef HAVE_DETAILED_TIMINGS
373
        call timer%stop("merge_systems" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
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
#endif
        return
      endif

      if (na1==1 .or. na1==2) then
        ! if(my_proc==0) print *,'--- Remark solve_tridi: na1==',na1,' proc==',myid

        if (na1==1) then
          d(1) = d1(1) + rho*z1(1)**2 ! solve secular equation
        else ! na1==2
          call M_PRECISSION_LAED5(1, d1, z1, qtrans(1,1), rho, d(1))
          call M_PRECISSION_LAED5(2, d1, z1, qtrans(1,2), rho, d(2))

          call M_transform_columns_PRECISSION(idx1(1), idx1(2))
        endif

        ! Add the deflated eigenvalues
        d(na1+1:na) = d2(1:na2)

        ! Calculate arrangement of all eigenvalues  in output
        call M_PRECISSION_LAMRG( na1, na-na1, d, 1, 1, idx )
        ! Rearrange eigenvalues

        tmp = d
        do i=1,na
          d(i) = tmp(idx(i))
        enddo

        ! Rearrange eigenvectors

        do i=1,na
          if (idx(i)<=na1) then
            idxq1(i) = idx1(idx(i))
          else
            idxq1(i) = idx2(idx(i)-na1)
          endif
        enddo
        call M_resort_ev_PRECISSION(idxq1, na)
      else if (na1>2) then

        ! Solve secular equation

        z(1:na1) = 1
#ifdef WITH_OPENMP
        z_p(1:na1,:) = 1
#endif
        dbase(1:na1) = 0
        ddiff(1:na1) = 0

        info = 0
#ifdef WITH_OPENMP

#ifdef HAVE_DETAILED_TIMINGS
427
        call timer%start("OpenMP parallel" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
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
#endif

!$OMP PARALLEL PRIVATE(i,my_thread,delta,s,info,j)
        my_thread = omp_get_thread_num()
!$OMP DO
#endif
        DO i = my_proc+1, na1, n_procs ! work distributed over all processors
          call M_PRECISSION_LAED4(na1, i, d1, z1, delta, rho, s, info) ! s is not used!
          if (info/=0) then
            ! If DLAED4 fails (may happen especially for LAPACK versions before 3.2)
            ! use the more stable bisection algorithm in solve_secular_equation
            ! print *,'ERROR DLAED4 n=',na1,'i=',i,' Using Bisection'
            call M_solve_secular_equation_PRECISSION(na1, i, d1, z1, delta, rho, s)
          endif

          ! Compute updated z

#ifdef WITH_OPENMP
          do j=1,na1
            if (i/=j)  z_p(j,my_thread) = z_p(j,my_thread)*( delta(j) / (d1(j)-d1(i)) )
          enddo
          z_p(i,my_thread) = z_p(i,my_thread)*delta(i)
#else
          do j=1,na1
            if (i/=j)  z(j) = z(j)*( delta(j) / (d1(j)-d1(i)) )
          enddo
          z(i) = z(i)*delta(i)
#endif
          ! store dbase/ddiff

          if (i<na1) then
            if (abs(delta(i+1)) < abs(delta(i))) then
              dbase(i) = d1(i+1)
              ddiff(i) = delta(i+1)
            else
              dbase(i) = d1(i)
              ddiff(i) = delta(i)
            endif
          else
            dbase(i) = d1(i)
            ddiff(i) = delta(i)
          endif
        enddo
#ifdef WITH_OPENMP
!$OMP END PARALLEL

#ifdef HAVE_DETAILED_TIMINGS
475
        call timer%stop("OpenMP parallel" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
#endif

        do i = 0, max_threads-1
          z(1:na1) = z(1:na1)*z_p(1:na1,i)
        enddo
#endif

        call M_global_product_PRECISSION(z, na1)
        z(1:na1) = SIGN( SQRT( -z(1:na1) ), z1(1:na1) )

        call M_global_gather_PRECISSION(dbase, na1)
        call M_global_gather_PRECISSION(ddiff, na1)
        d(1:na1) = dbase(1:na1) - ddiff(1:na1)

        ! Calculate scale factors for eigenvectors
        ev_scale(:) = M_CONST_0_0

#ifdef WITH_OPENMP

#ifdef HAVE_DETAILED_TIMINGS
496
        call timer%start("OpenMP parallel" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#endif

!$OMP PARALLEL DO PRIVATE(i) SHARED(na1, my_proc, n_procs,  &
!$OMP d1,dbase, ddiff, z, ev_scale) &
!$OMP DEFAULT(NONE)

#endif
        DO i = my_proc+1, na1, n_procs ! work distributed over all processors

          ! tmp(1:na1) = z(1:na1) / delta(1:na1,i)  ! original code
          ! tmp(1:na1) = z(1:na1) / (d1(1:na1)-d(i))! bad results

          ! All we want to calculate is tmp = (d1(1:na1)-dbase(i))+ddiff(i)
          ! in exactly this order, but we want to prevent compiler optimization
!         ev_scale_val = ev_scale(i)
          call M_add_tmp_PRECISSION(d1, dbase, ddiff, z, ev_scale(i), na1,i)
!         ev_scale(i) = ev_scale_val
        enddo
#ifdef WITH_OPENMP
!$OMP END PARALLEL DO

#ifdef HAVE_DETAILED_TIMINGS
519
        call timer%stop("OpenMP parallel" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#endif

#endif

        call M_global_gather_PRECISSION(ev_scale, na1)
        ! Add the deflated eigenvalues
        d(na1+1:na) = d2(1:na2)

        ! Calculate arrangement of all eigenvalues  in output
        call M_PRECISSION_LAMRG( na1, na-na1, d, 1, 1, idx )

        ! Rearrange eigenvalues
        tmp = d
        do i=1,na
          d(i) = tmp(idx(i))
        enddo
        call M_check_monotony_PRECISSION(na,d,'Output', wantDebug, success)

        if (.not.(success)) then
#ifdef HAVE_DETAILED_TIMINGS
540
          call timer%stop("merge_systems" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
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
#endif
          return
        endif
        ! Eigenvector calculations


        ! Calculate the number of columns in the new local matrix Q
        ! which are updated from non-deflated/deflated eigenvectors.
        ! idxq1/2 stores the global column numbers.

        nqcols1 = 0 ! number of non-deflated eigenvectors
        nqcols2 = 0 ! number of deflated eigenvectors
        DO i = 1, na
          if (p_col_out(i)==my_pcol) then
            if (idx(i)<=na1) then
              nqcols1 = nqcols1+1
              idxq1(nqcols1) = i
            else
              nqcols2 = nqcols2+1
              idxq2(nqcols2) = i
            endif
          endif
        enddo

        allocate(ev(max_local_cols,MIN(max_strip,MAX(1,nqcols1))), stat=istat, errmsg=errorMessage)
        if (istat .ne. 0) then
          print *,"merge_systems: error when allocating ev "//errorMessage
          stop
        endif

        allocate(qtmp1(MAX(1,l_rows),max_local_cols), stat=istat, errmsg=errorMessage)
        if (istat .ne. 0) then
          print *,"merge_systems: error when allocating qtmp1 "//errorMessage
          stop
        endif

        allocate(qtmp2(MAX(1,l_rows),MIN(max_strip,MAX(1,nqcols1))), stat=istat, errmsg=errorMessage)
        if (istat .ne. 0) then
          print *,"merge_systems: error when allocating qtmp2 "//errorMessage
          stop
        endif

!        if (useGPU) then
!          allocate(qtmp1_dev(MAX(1,l_rows),max_local_cols))
!   endif

        ! Gather nonzero upper/lower components of old matrix Q
        ! which are needed for multiplication with new eigenvectors

        qtmp1 = 0 ! May contain empty (unset) parts
        qtmp2 = 0 ! Not really needed

        nnzu = 0
        nnzl = 0
        do i = 1, na1
          l_idx = l_col(idx1(i))
          if (p_col(idx1(i))==my_pcol) then
            if (coltyp(idx1(i))==1 .or. coltyp(idx1(i))==2) then
              nnzu = nnzu+1
              qtmp1(1:l_rnm,nnzu) = q(l_rqs:l_rqm,l_idx)
            endif
            if (coltyp(idx1(i))==3 .or. coltyp(idx1(i))==2) then
              nnzl = nnzl+1
              qtmp1(l_rnm+1:l_rows,nnzl) = q(l_rqm+1:l_rqe,l_idx)
            endif
          endif
        enddo

        ! Gather deflated eigenvalues behind nonzero components

        ndef = max(nnzu,nnzl)
        do i = 1, na2
          l_idx = l_col(idx2(i))
          if (p_col(idx2(i))==my_pcol) then
            ndef = ndef+1
            qtmp1(1:l_rows,ndef) = q(l_rqs:l_rqe,l_idx)
          endif
        enddo

        l_cols_qreorg = ndef ! Number of columns in reorganized matrix

        ! Set (output) Q to 0, it will sum up new Q

        DO i = 1, na
          if(p_col_out(i)==my_pcol) q(l_rqs:l_rqe,l_col_out(i)) = 0
        enddo

        np_rem = my_pcol

        do np = 1, npc_n

          ! Do a ring send of qtmp1

          if (np>1) then

            if (np_rem==npc_0) then
              np_rem = npc_0+npc_n-1
            else
              np_rem = np_rem-1
            endif
#ifdef WITH_MPI
#ifdef HAVE_DETAILED_TIMINGS
            call timer%start("mpi_communication")
#endif
            call MPI_Sendrecv_replace(qtmp1, l_rows*max_local_cols, M_MPI_REAL_PRECISSION, &
                                        np_next, 1111, np_prev, 1111, &
                                        mpi_comm_cols, MPI_STATUS_IGNORE, mpierr)
#ifdef HAVE_DETAILED_TIMINGS
           call timer%stop("mpi_communication")
#endif
#endif /* WITH_MPI */
          endif

!          if (useGPU) then
!            qtmp1_dev(:,:) = qtmp1(:,:)
!          endif

          ! Gather the parts in d1 and z which are fitting to qtmp1.
          ! This also delivers nnzu/nnzl for proc np_rem

          nnzu = 0
          nnzl = 0
          do i=1,na1
            if (p_col(idx1(i))==np_rem) then
              if (coltyp(idx1(i))==1 .or. coltyp(idx1(i))==2) then
                nnzu = nnzu+1
                d1u(nnzu) = d1(i)
                zu (nnzu) = z (i)
              endif
              if (coltyp(idx1(i))==3 .or. coltyp(idx1(i))==2) then
                nnzl = nnzl+1
                d1l(nnzl) = d1(i)
                zl (nnzl) = z (i)
              endif
            endif
          enddo

          ! Set the deflated eigenvectors in Q (comming from proc np_rem)

          ndef = MAX(nnzu,nnzl) ! Remote counter in input matrix
          do i = 1, na
            j = idx(i)
            if (j>na1) then
              if (p_col(idx2(j-na1))==np_rem) then
                ndef = ndef+1
                if (p_col_out(i)==my_pcol) &
                      q(l_rqs:l_rqe,l_col_out(i)) = qtmp1(1:l_rows,ndef)
              endif
            endif
          enddo

          do ns = 0, nqcols1-1, max_strip ! strimining loop

            ncnt = MIN(max_strip,nqcols1-ns) ! number of columns in this strip

            ! Get partial result from (output) Q

            do i = 1, ncnt
              qtmp2(1:l_rows,i) = q(l_rqs:l_rqe,l_col_out(idxq1(i+ns)))
            enddo

            ! Compute eigenvectors of the rank-1 modified matrix.
            ! Parts for multiplying with upper half of Q:

            do i = 1, ncnt
              j = idx(idxq1(i+ns))
              ! Calculate the j-th eigenvector of the deflated system
              ! See above why we are doing it this way!
              tmp(1:nnzu) = d1u(1:nnzu)-dbase(j)
              call M_v_add_s_PRECISSION(tmp,nnzu,ddiff(j))
              ev(1:nnzu,i) = zu(1:nnzu) / tmp(1:nnzu) * ev_scale(j)
            enddo

            ! Multiply old Q with eigenvectors (upper half)

!            if (useGPU) then
!              if(l_rnm>0 .and. ncnt>0 .and. nnzu>0) &
!                 call dgemm('N','N',l_rnm,ncnt,nnzu,1.d0,qtmp1_dev,ubound(qtmp1_dev,1),ev,ubound(ev,1), &
!                            1.d0,qtmp2(1,1),ubound(qtmp2,1))
!       else
              if (l_rnm>0 .and. ncnt>0 .and. nnzu>0) &
                  call M_PRECISSION_GEMM('N', 'N', l_rnm, ncnt, nnzu, M_CONST_1_0, qtmp1, ubound(qtmp1,dim=1), ev, ubound(ev,dim=1), &
                             M_CONST_1_0, qtmp2(1,1), ubound(qtmp2,dim=1))
!            endif ! useGPU
            ! Compute eigenvectors of the rank-1 modified matrix.
            ! Parts for multiplying with lower half of Q:

            do i = 1, ncnt
              j = idx(idxq1(i+ns))
              ! Calculate the j-th eigenvector of the deflated system
              ! See above why we are doing it this way!
              tmp(1:nnzl) = d1l(1:nnzl)-dbase(j)
              call M_v_add_s_PRECISSION(tmp,nnzl,ddiff(j))
              ev(1:nnzl,i) = zl(1:nnzl) / tmp(1:nnzl) * ev_scale(j)
            enddo

            ! Multiply old Q with eigenvectors (lower half)

!            if (useGPU) then
!              if(l_rows-l_rnm>0 .and. ncnt>0 .and. nnzl>0) &
!                 call dgemm('N','N',l_rows-l_rnm,ncnt,nnzl,1.d0,qtmp1_dev(l_rnm+1,1),ubound(qtmp1_dev,1),ev,ubound(ev,1), &
!                            1.d0,qtmp2(l_rnm+1,1),ubound(qtmp2,1))
!       else
              if (l_rows-l_rnm>0 .and. ncnt>0 .and. nnzl>0) &
                 call M_PRECISSION_GEMM('N', 'N', l_rows-l_rnm, ncnt, nnzl, M_CONST_1_0, qtmp1(l_rnm+1,1), ubound(qtmp1,dim=1), ev, &
                            ubound(ev,dim=1), M_CONST_1_0, qtmp2(l_rnm+1,1), ubound(qtmp2,dim=1))
!            endif ! useGPU
             ! Put partial result into (output) Q

             do i = 1, ncnt
               q(l_rqs:l_rqe,l_col_out(idxq1(i+ns))) = qtmp2(1:l_rows,i)
             enddo

           enddo
        enddo

        deallocate(ev, qtmp1, qtmp2, stat=istat, errmsg=errorMessage)
        if (istat .ne. 0) then
          print *,"merge_systems: error when deallocating ev "//errorMessage
          stop
        endif
      endif

#ifdef WITH_OPENMP
      deallocate(z_p, stat=istat, errmsg=errorMessage)
      if (istat .ne. 0) then
        print *,"merge_systems: error when deallocating z_p "//errorMessage
        stop
      endif
#endif

#ifdef HAVE_DETAILED_TIMINGS
773
      call timer%stop("merge_systems" // M_PRECISSION_SUFFIX)
Pavel Kus's avatar
Pavel Kus committed
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
#endif


      return

      contains
        subroutine M_add_tmp_PRECISSION(d1, dbase, ddiff, z, ev_scale_value, na1,i)
          use precision
          implicit none

          integer(kind=ik), intent(in) :: na1, i

          real(kind=REAL_DATATYPE), intent(in)    :: d1(:), dbase(:), ddiff(:), z(:)
          real(kind=REAL_DATATYPE), intent(inout) :: ev_scale_value
          real(kind=REAL_DATATYPE)                :: tmp(1:na1)

               ! tmp(1:na1) = z(1:na1) / delta(1:na1,i)  ! original code
               ! tmp(1:na1) = z(1:na1) / (d1(1:na1)-d(i))! bad results

               ! All we want to calculate is tmp = (d1(1:na1)-dbase(i))+ddiff(i)
               ! in exactly this order, but we want to prevent compiler optimization

          tmp(1:na1) = d1(1:na1) -dbase(i)
          call M_v_add_s_PRECISSION(tmp(1:na1),na1,ddiff(i))
          tmp(1:na1) = z(1:na1) / tmp(1:na1)
          ev_scale_value = M_CONST_1_0/sqrt(dot_product(tmp(1:na1),tmp(1:na1)))

        end subroutine M_add_tmp_PRECISSION

        subroutine M_resort_ev_PRECISSION(idx_ev, nLength)
#ifdef HAVE_DETAILED_TIMINGS
          use timings
#endif
          use precision
          implicit none

          integer(kind=ik), intent(in) :: nLength
          integer(kind=ik)             :: idx_ev(nLength)
          integer(kind=ik)             :: i, nc, pc1, pc2, lc1, lc2, l_cols_out

          real(kind=REAL_DATATYPE), allocatable   :: qtmp(:,:)
          integer(kind=ik)             :: istat
          character(200)               :: errorMessage

          if (l_rows==0) return ! My processor column has no work to do

          ! Resorts eigenvectors so that q_new(:,i) = q_old(:,idx_ev(i))

          l_cols_out = COUNT(p_col_out(1:na)==my_pcol)
          allocate(qtmp(l_rows,l_cols_out), stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"resort_ev: error when allocating qtmp "//errorMessage
            stop
          endif

          nc = 0

          do i=1,na

            pc1 = p_col(idx_ev(i))
            lc1 = l_col(idx_ev(i))
            pc2 = p_col_out(i)

            if (pc2<0) cycle ! This column is not needed in output

            if (pc2==my_pcol) nc = nc+1 ! Counter for output columns

            if (pc1==my_pcol) then
              if (pc2==my_pcol) then
                ! send and recieve column are local
                qtmp(1:l_rows,nc) = q(l_rqs:l_rqe,lc1)
              else
#ifdef WITH_MPI
#ifdef HAVE_DETAILED_TIMINGS
                call timer%start("mpi_communication")
#endif
                call mpi_send(q(l_rqs,lc1), l_rows, M_MPI_REAL_PRECISSION, pc2, mod(i,4096), mpi_comm_cols, mpierr)
#ifdef HAVE_DETAILED_TIMINGS
                call timer%stop("mpi_communication")
#endif
#endif /* WITH_MPI */
              endif
            else if (pc2==my_pcol) then
#ifdef WITH_MPI
#ifdef HAVE_DETAILED_TIMINGS
              call timer%start("mpi_communication")
#endif
              call mpi_recv(qtmp(1,nc), l_rows, M_MPI_REAL_PRECISSION, pc1, mod(i,4096), mpi_comm_cols, MPI_STATUS_IGNORE, mpierr)
#ifdef HAVE_DETAILED_TIMINGS
              call timer%stop("mpi_communication")
#endif
#else /* WITH_MPI */
              qtmp(1:l_rows,nc) = q(l_rqs:l_rqe,lc1)
#endif /* WITH_MPI */
            endif
          enddo

          ! Insert qtmp into (output) q

          nc = 0

          do i=1,na

            pc2 = p_col_out(i)
            lc2 = l_col_out(i)

            if (pc2==my_pcol) then
              nc = nc+1
              q(l_rqs:l_rqe,lc2) = qtmp(1:l_rows,nc)
            endif
          enddo

          deallocate(qtmp, stat=istat, errmsg=errorMessage)
          if (istat .ne. 0) then
            print *,"resort_ev: error when deallocating qtmp "//errorMessage
            stop
          endif
        end subroutine M_resort_ev_PRECISSION

        subroutine M_transform_columns_PRECISSION(col1, col2)
#ifdef HAVE_DETAILED_TIMINGS
          use timings
#endif
          use precision
          implicit none

          integer(kind=ik) :: col1, col2
          integer(kind=ik) :: pc1, pc2, lc1, lc2

          if (l_rows==0) return ! My processor column has no work to do

          pc1 = p_col(col1)
          lc1 = l_col(col1)
          pc2 = p_col(col2)
          lc2 = l_col(col2)

          if (pc1==my_pcol) then
            if (pc2==my_pcol) then
              ! both columns are local
              tmp(1:l_rows)      = q(l_rqs:l_rqe,lc1)*qtrans(1,1) + q(l_rqs:l_rqe,lc2)*qtrans(2,1)
              q(l_rqs:l_rqe,lc2) = q(l_rqs:l_rqe,lc1)*qtrans(1,2) + q(l_rqs:l_rqe,lc2)*qtrans(2,2)
              q(l_rqs:l_rqe,lc1) = tmp(1:l_rows)
            else
#ifdef WITH_MPI
#ifdef HAVE_DETAILED_TIMINGS
              call timer%start("mpi_communication")
#endif
              call mpi_sendrecv(q(l_rqs,lc1), l_rows, M_MPI_REAL_PRECISSION, pc2, 1, &
                                tmp, l_rows, M_MPI_REAL_PRECISSION, pc2, 1,          &
                                mpi_comm_cols, MPI_STATUS_IGNORE, mpierr)
#ifdef HAVE_DETAILED_TIMINGS
              call timer%stop("mpi_communication")
#endif
#else /* WITH_MPI */
              tmp(1:l_rows) = q(l_rqs:l_rqe,lc1)
#endif /* WITH_MPI */
              q(l_rqs:l_rqe,lc1) = q(l_rqs:l_rqe,lc1)*qtrans(1,1) + tmp(1:l_rows)*qtrans(2,1)
            endif
          else if (pc2==my_pcol) then
#ifdef WITH_MPI
#ifdef HAVE_DETAILED_TIMINGS
            call timer%start("mpi_communication")
#endif
            call mpi_sendrecv(q(l_rqs,lc2), l_rows, M_MPI_REAL_PRECISSION, pc1, 1, &
                               tmp, l_rows, M_MPI_REAL_PRECISSION, pc1, 1,         &
                               mpi_comm_cols, MPI_STATUS_IGNORE, mpierr)
#ifdef HAVE_DETAILED_TIMINGS
            call timer%stop("mpi_communication")
#endif
#else /* WITH_MPI */
            tmp(1:l_rows) = q(l_rqs:l_rqe,lc2)
#endif /* WITH_MPI */

            q(l_rqs:l_rqe,lc2) = tmp(1:l_rows)*qtrans(1,2) + q(l_rqs:l_rqe,lc2)*qtrans(2,2)
          endif
        end subroutine M_transform_columns_PRECISSION

        subroutine M_global_gather_PRECISSION(z, n)
          ! This routine sums up z over all processors.
          ! It should only be used for gathering distributed results,
          ! i.e. z(i) should be nonzero on exactly 1 processor column,
          ! otherways the results may be numerically different on different columns
          use precision
#ifdef HAVE_DETAILED_TIMINGS
          use timings
#endif
          implicit none

          integer(kind=ik) :: n
          real(kind=REAL_DATATYPE)    :: z(n)
          real(kind=REAL_DATATYPE)    :: tmp(n)

          if (npc_n==1 .and. np_rows==1) return ! nothing to do

          ! Do an mpi_allreduce over processor rows
#ifdef WITH_MPI
#ifdef HAVE_DETAILED_TIMINGS
          call timer%start("mpi_communication")
#endif
          call mpi_allreduce(z, tmp, n, M_MPI_REAL_PRECISSION, MPI_SUM, mpi_comm_rows, mpierr)
#ifdef HAVE_DETAILED_TIMINGS
          call timer%stop("mpi_communication")
#endif
#else /* WITH_MPI */
          tmp = z
#endif /* WITH_MPI */
          ! If only 1 processor column, we are done
          if (npc_n==1) then
            z(:) = tmp(:)
            return
          endif

          ! If all processor columns are involved, we can use mpi_allreduce
          if (npc_n==np_cols) then
#ifdef WITH_MPI
#ifdef HAVE_DETAILED_TIMINGS
            call timer%start("mpi_communication")
#endif
            call mpi_allreduce(tmp, z, n, M_MPI_REAL_PRECISSION, MPI_SUM, mpi_comm_cols, mpierr)
#ifdef HAVE_DETAILED_TIMINGS
            call timer%stop("mpi_communication")
#endif
#else /* WITH_MPI */
            tmp = z
#endif /* WITH_MPI */

            return