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
     1001
     1002
     1003
     1004
     1005
     1006
     1007
     1008
     1009
     1010
     1011
     1012
     1013
     1014
     1015
     1016
     1017
     1018
     1019
     1020
     1021
     1022
     1023
     1024
     1025
     1026
     1027
     1028
     1029
     1030
     1031
     1032
     1033
     1034
     1035
     1036
     1037
     1038
     1039
     1040
     1041
     1042
     1043
     1044
     1045
     1046
     1047
     1048
     1049
     1050
     1051
     1052
     1053
     1054
     1055
     1056
     1057
     1058
     1059
     1060
     1061
     1062
     1063
     1064
     1065
     1066
     1067
     1068
     1069
     1070
     1071
     1072
     1073
     1074
     1075
     1076
     1077
     1078
     1079
     1080
     1081
     1082
     1083
     1084
     1085
     1086
     1087
     1088
     1089
     1090
     1091
     1092
     1093
     1094
     1095
     1096
     1097
     1098
     1099
     1100
     1101
     1102
     1103
     1104
     1105
     1106
     1107
     1108
     1109
     1110
     1111
     1112
     1113
     1114
     1115
     1116
     1117
     1118
     1119
     1120
     1121
/*
 *   Copyright (c) 2011, Michael Lehn
 *
 *   All rights reserved.
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 *
 *   1) Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *   2) Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in
 *      the documentation and/or other materials provided with the
 *      distribution.
 *   3) Neither the name of the FLENS development group nor the names of
 *      its contributors may be used to endorse or promote products derived
 *      from this software without specific prior written permission.
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/* Based on
 *
       SUBROUTINE DGEESX( JOBVS, SORT, SELECT, SENSE, N, A, LDA, SDIM,
      $                   WR, WI, VS, LDVS, RCONDE, RCONDV, WORK, LWORK,
      $                   IWORK, LIWORK, BWORK, INFO )
       SUBROUTINE ZGEESX( JOBVS, SORT, SELECT, SENSE, N, A, LDA, SDIM, W,
      $                   VS, LDVS, RCONDE, RCONDV, WORK, LWORK, RWORK,
      $                   BWORK, INFO )
 *
 *  -- LAPACK driver routine (version 3.2.2) --
 *  -- LAPACK is a software package provided by Univ. of Tennessee,    --
 *  -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
 *     June 2010
 */

#ifndef FLENS_LAPACK_GE_ESX_TCC
#define FLENS_LAPACK_GE_ESX_TCC 1

#include <cmath>
#include <flens/blas/blas.h>
#include <flens/lapack/lapack.h>

namespace flens { namespace lapack {

//== generic lapack implementation =============================================

namespace generic {

//-- (ge)esx_wsq [real variant] ------------------------------------------------

template <typename MA>
Quadruple<typename GeMatrix<MA>::IndexType>
esx_wsq_impl(bool                 computeSchurVectors,
             SENSE::Sense         sense,
             const GeMatrix<MA>   &A)
{
    using std::max;

    typedef typename GeMatrix<MA>::ElementType  T;
    typedef typename GeMatrix<MA>::IndexType    IndexType;

    const IndexType n = A.numRows();
    const bool wantSN = (sense==SENSE::None);
    const bool wantSV = (sense==SENSE::InvariantSubspaceOnly);
    const bool wantSB = (sense==SENSE::Both);

    IndexType minWork, maxWork, liWork, lWork;

    liWork1;
    if (n==0) {
        minWork1;
        maxWork1;
        lWork1;
    } else {
        maxWork2*n + n*ilaenv<T>(1"GEHRD""", n1, n0);
        minWork3*n;

        HSEQR::ComputeZ computeZ = (computeSchurVectors) ? HSEQR::NoInit
                                                         : HSEQR::No;
        IndexType hsWork = hseqr_wsq(HSEQR::Schur, computeZ,
                                     IndexType(1), n, A);

        if (!computeSchurVectors) {
            maxWork = max(maxWork, n + hsWork);
        } else {
            maxWork = max(maxWork,
                          2*n + (n-1)*ilaenv<T>(1"ORGHR""", n1, n));
            maxWork = max(maxWork, n +hsWork);
        }
        lWork = maxWork;
        if (!wantSN) {
            lWork = max(lWork, n + (n*n)/2);
        }
        if (wantSV || wantSB) {
            liWork = (n*n)/4;
        }

    }
    return Quadruple<IndexType>(minWork, maxWork, lWork, liWork);
}

//-- (ge)esx [real variant] ----------------------------------------------------

template <typename SelectFunction, typename MA, typename IndexType,
          typename VWR, typename VWI, typename MVS,
          typename RCONDE, typename RCONDV,
          typename VWORK, typename VIWORK, typename BWORK>
IndexType
esx_impl(bool                 computeSchurVectors,
         bool                 sortEigenvalues,
         SelectFunction       selectFunction,
         SENSE::Sense         sense,
         GeMatrix<MA>         &A,
         IndexType            &sDim,
         DenseVector<VWR>     &wr,
         DenseVector<VWI>     &wi,
         GeMatrix<MVS>        &VS,
         RCONDE               &rCondE,
         RCONDV               &rCondV,
         DenseVector<VWORK>   &work,
         DenseVector<VIWORK>  &iWork,
         DenseVector<BWORK>   &bWork)
{
    using std::sqrt;

    typedef typename GeMatrix<MA>::ElementType  T;

    const Underscore<IndexType> _;
    const IndexType n = A.numRows();
    const T Zero(0), One(1);

//
//  .. Local Arrays ..
//  this array is used to save variables between calls to lacn2
//
    T _dum[1];
    DenseVectorView<T>  dum = typename DenseVectorView<T>::Engine(1, _dum);
//
//  Test the input arguments
//
    IndexType info = 0;
    const bool wantSN = (sense==SENSE::None);
    const bool wantSV = (sense==SENSE::InvariantSubspaceOnly);
    const bool wantSB = (sense==SENSE::Both);
//
//  Compute workspace
//   (Note: Comments in the code beginning "RWorkspace:" describe the
//    minimal amount of real workspace needed at that point in the
//    code, as well as the preferred amount for good performance.
//    IWorkspace refers to integer workspace.
//    NB refers to the optimal block size for the immediately
//    following subroutine, as returned by ILAENV.
//    HSWORK refers to the workspace preferred by DHSEQR, as
//    calculated below. HSWORK is computed assuming ILO=1 and IHI=N,
//    the worst case.
//    If SENSE = 'E', 'V' or 'B', then the amount of workspace needed
//    depends on SDIM, which is computed by the routine DTRSEN later
//    in the code.)
//
    Quadruple<IndexType> wsQuery = esx_wsq(computeSchurVectors, sense, A);
    IndexType minWork = wsQuery.first;
    IndexType maxWork = wsQuery.second;
    IndexType lWork   = wsQuery.third;
    IndexType liWork  = wsQuery.forth;

    if (work.length()!=0 && work.length()<minWork) {
        ASSERT(0);
    } else if (work.length()==0) {
        work.resize(lWork);
    }
    work(1) = lWork;

    if (iWork.length()!=0 && iWork.length()<liWork) {
        ASSERT(0);
    } else if (iWork.length()==0) {
        iWork.resize(liWork);
    }
    iWork(1) = liWork;

//
//  Quick return if possible
//
    if (n==0) {
        sDim0;
        return info;
    }
//
//  Get machine constants
//
    const T eps = lamch<T>(Precision);
    T smallNum  = lamch<T>(SafeMin);
    T bigNum    = One / smallNum;
    labad(smallNum, bigNum);

    smallNum    = sqrt(smallNum) / eps;
    bigNum      = One / smallNum;
//
//  Scale A if max element outside range [SMLNUM,BIGNUM]
//
    const T normA = lan(MaximumNorm, A);

    bool scaleA = false;
    T    cScale;

    if (normA>Zero && normA<smallNum) {
        scaleAtrue;
        cScale = smallNum;
    } else if (normA>bigNum) {
        scaleAtrue;
        cScale = bigNum;
    }
    if (scaleA) {
        lascl(LASCL::FullMatrix, IndexType(0), IndexType(0), normA, cScale, A);
    }

//
//  Permute the matrix to make it more nearly triangular
//  (RWorkspace: need N)
//
    IndexType iBal = 1;
    auto balWork = work(_(iBal,iBal+n-1));

    IndexType iLo, iHi;
    bal(BALANCE::PermuteOnly, A, iLo, iHi, balWork);
//
//  Reduce to upper Hessenberg form
//  (RWorkspace: need 3*N, prefer 2*N+N*NB)
//
    IndexType iTau  = iBal + n;
    IndexType iWrk = iTau + n;
    lWork = work.length();

    auto tau = work(_(iTau, iTau+n-2));
    auto hrdWork = work(_(iWrk, lWork));

    hrd(iLo, iHi, A, tau, hrdWork);

    if (computeSchurVectors) {
//
//      Copy Householder vectors to VS
//
        VS.lower() = A.lower();
//
//      Generate orthogonal matrix in VS
//      (RWorkspace: need 3*N-1, prefer 2*N+(N-1)*NB)
//
        orghr(iLo, iHi, VS, tau, hrdWork);
    }

    sDim0;
//
//  Perform QR iteration, accumulating Schur vectors in VS if desired
//  (RWorkspace: need N+1, prefer N+HSWORK (see comments) )
//
    iWrk = iTau;
    auto hseqrWork = work(_(iWrk, lWork));
    HSEQR::ComputeZ computeZ = (computeSchurVectors) ? HSEQR::NoInit
                                                     : HSEQR::No;
    IndexType iEval = hseqr(HSEQR::Schur, computeZ, iLo, iHi,
                            A, wr, wi, VS, hseqrWork);
    if (iEval>0) {
        info = iEval;
    }
//
//  Sort eigenvalues if desired
//
    if (sortEigenvalues && info==0) {
        if (scaleA) {
            lascl(LASCL::FullMatrix, IndexType(0), IndexType(0),
                  cScale, normA, wr);
            lascl(LASCL::FullMatrix, IndexType(0), IndexType(0),
                  cScale, normA, wi);
        }
        for (IndexType i=1; i<=n; ++i) {
            bWork(i) = selectFunction(wr(i), wi(i));
        }
//
//      Reorder eigenvalues, transform Schur vectors, and compute
//      reciprocal condition numbers
//      (RWorkspace: if SENSE is not 'N', need N+2*SDIM*(N-SDIM)
//                   otherwise, need N )
//      (IWorkspace: if SENSE is 'V' or 'B', need SDIM*(N-SDIM)
//                   otherwise, need 0 )
//
        IndexType iCond = trsen(TRSEN::Job(sense), computeSchurVectors, bWork,
                                A, VS, wr, wi, sDim, rCondE, rCondV,
                                hseqrWork, iWork);
        if (!wantSN) {
            maxWork = max(maxWork, n+2*sDim*(n-sDim));
        }
        if (iCond>0) {
//
//          DTRSEN failed to reorder or to restore standard Schur form
//
            info = iCond + n;
        }
    }

    if (computeSchurVectors) {
//
//      Undo balancing
//      (Workspace: need N)
//
        bak(BALANCE::PermuteOnly, Right, iLo, iHi, balWork, VS);
    }

    if (scaleA) {
//
//      Undo scaling for the Schur form of A
//
        lascl(LASCL::UpperHessenberg, IndexType(0), IndexType(0),
              cScale, normA, A);
        wr = A.diag(0);
        if ((wantSV || wantSB) && info==0) {
            dum(1) = rCondV;
            lascl(LASCL::FullMatrix, IndexType(0), IndexType(0),
                  cScale, normA, dum);
            rCondV = dum(1);
        }
        if (cScale==smallNum) {
//
//          If scaling back towards underflow, adjust WI if an
//          offdiagonal element of a 2-by-2 block in the Schur form
//          underflows.
//
            IndexType i1, i2;
            if (iEval>0) {
                i1 = iEval1;
                i2 = iHi1;
                lascl(LASCL::FullMatrix, IndexType(0), IndexType(0),
                      cScale, normA, wi(_(1,iLo-1)));
            } else if (sortEigenvalues) {
                i11;
                i2 = n1;
            } else {
                i1 = iLo;
                i2 = iHi1;
            }
            IndexType iNext = i1-1;
            for (IndexType i=i1; i<=i2; ++i) {
                if (i<iNext) {
                    continue;
                }
                if (wi(i)==Zero) {
                    iNext = i1;
                } else {
                    if (A(i+1,i)==Zero) {
                        wi(i)   = Zero;
                        wi(i+1) = Zero;
                    } else if (A(i+1,i)!=Zero && A(i,i+1)==Zero) {
                        wi(i)   = Zero;
                        wi(i+1) = Zero;
                        if (i>1) {
                            blas::swap(A(_(1,i-1),i), A(_(1,i-1),i+1));
                        }
                        if (n>i+1) {
                            blas::swap(A(i,_(i+2,n)), A(i+1,_(i+2,n)));
                        }
                        blas::swap(VS(_,i), VS(_,i+1));
                        A(i,i+1) = A(i+1,i);
                        A(i+1,i) = Zero;
                    }
                    iNext = i2;
                }
            }
        }
        lascl(LASCL::FullMatrix, IndexType(0), IndexType(0),
              cScale, normA, wi(_(iEval+1,n)));
    }

    if (sortEigenvalues && info==0) {
//
//       Check if reordering successful
//
        bool lastSelect = true;
        bool last2Select = true;
        sDim0;
        IndexType ip = 0;
        for (IndexType i=1; i<=n; ++i) {
            bool currentSelect = selectFunction(wr(i), wi(i));
            if (wi(i)==Zero) {
               if (currentSelect) {
                   ++sDim;
               }
               ip0;
               if (currentSelect && !lastSelect) {
                   info = n2;
               }
            } else {
                if (ip==1) {
//
//                  Last eigenvalue of conjugate pair
//
                    currentSelect = currentSelect || lastSelect;
                    lastSelect = currentSelect;
                    if (currentSelect) {
                        sDim += 2;
                    }
                    ip = -1;
                    if (currentSelect && !last2Select) {
                        info = n2;
                    }
                } else {
//
//                  First eigenvalue of conjugate pair
//
                    ip1;
                }
            }
            last2Select = lastSelect;
            lastSelect = currentSelect;
        }
    }

    work(1) = maxWork;
    if (wantSV || wantSB) {
        iWork(1) = max(IndexType(1), sDim*(n-sDim));
    } else {
        iWork(1) = 1;
    }

    return info;
}

// namespace generic

//== interface for native lapack ===============================================

#ifdef USE_CXXLAPACK

namespace external {

//-- (ge)esx_wsq [worksize query real variant] ---------------------------------

template <typename MA>
typename RestrictTo<IsNotComplex<typename MA::ElementType>::value,
         Quadruple<typename MA::IndexType> >::Type
esx_wsq_impl(bool                 computeSchurVectors,
             SENSE::Sense         sense,
             const GeMatrix<MA>   &A)
{
    using std::max;

    typedef typename GeMatrix<MA>::ElementType  T;
    typedef typename GeMatrix<MA>::IndexType    IndexType;

    const IndexType n = A.numRows();
    //const bool wantSN = (sense==SENSE::None);
    const bool wantSV = (sense==SENSE::InvariantSubspaceOnly);
    const bool wantSB = (sense==SENSE::Both);

    IndexType minWork, maxWork, liWork, lWork;

    liWork1;
    if (n==0) {
        minWork1;
    } else {
        minWork3*n;
        if (wantSV || wantSB) {
            liWork = (n*n)/4;
        }
    }

//
//  Compute optimal size for work
//
    const IndexType     LDVS   = max(IndexType(1), A.numRows());
    IndexType           IDUMMY, IWORK;
    T                   DUMMY;
    const IndexType     LWORK  = -1;
    T                   WORK;

    cxxlapack::geesx<IndexType>(computeSchurVectors'V' : 'N',
                                'S',
                                0,
                                getF77Char(sense),
                                n,
                                0,
                                A.leadingDimension(),
                                IDUMMY,
                                &DUMMY,
                                &DUMMY,
                                &DUMMY,
                                LDVS,
                                DUMMY,
                                DUMMY,
                                &WORK,
                                LWORK,
                                &IWORK,
                                IDUMMY,
                                &IDUMMY);

    return Quadruple<IndexType>(minWork, WORK, WORK, liWork);
}

//-- (ge)esx_wsq [worksize query complex variant] ------------------------------

template <typename MA>
typename RestrictTo<IsComplex<typename MA::ElementType>::value,
         Triple<typename MA::IndexType> >::Type
esx_wsq_impl(bool                 computeSchurVectors,
             SENSE::Sense         sense,
             const GeMatrix<MA>   &A)
{
    using std::max;

    typedef typename GeMatrix<MA>::ElementType        T;
    typedef typename ComplexTrait<T>::PrimitiveType   RT;
    typedef typename GeMatrix<MA>::IndexType          IndexType;

    const IndexType n = A.numRows();
    //const bool wantSN = (sense==SENSE::None);
    //const bool wantSV = (sense==SENSE::InvariantSubspaceOnly);
    //const bool wantSB = (sense==SENSE::Both);

    IndexType minWork, maxWork, lWork;

    if (n==0) {
        minWork1;
    } else {
        minWork2*n;
    }

//
//  Compute optimal size for work
//
    const IndexType     LDVS   = max(IndexType(1), A.numRows());
    IndexType           IDUMMY, IWORK;
    T                   DUMMY;
    RT                  RDUMMY;
    const IndexType     LWORK  = -1;
    T                   WORK;

    cxxlapack::geesx<IndexType>(computeSchurVectors'V' : 'N',
                                'S',
                                0,
                                getF77Char(sense),
                                n,
                                0,
                                A.leadingDimension(),
                                IDUMMY,
                                &DUMMY,
                                &DUMMY,
                                LDVS,
                                RDUMMY,
                                RDUMMY,
                                &DUMMY,
                                LWORK,
                                &RDUMMY,
                                &IDUMMY);

    return Triple<IndexType>(minWork, WORK.real(), WORK.real());
}

//-- (ge)esx [real variant] ----------------------------------------------------

template <typename SelectFunction, typename MA, typename IndexType,
          typename VWR, typename VWI, typename MVS,
          typename RCONDE, typename RCONDV,
          typename VWORK, typename VIWORK, typename BWORK>
IndexType
esx_impl(bool                 computeSchurVectors,
         bool                 sortEigenvalues,
         SelectFunction       selectFunction,
         SENSE::Sense         sense,
         GeMatrix<MA>         &A,
         IndexType            &sDim,
         DenseVector<VWR>     &wr,
         DenseVector<VWI>     &wi,
         GeMatrix<MVS>        &VS,
         RCONDE               &rCondE,
         RCONDV               &rCondV,
         DenseVector<VWORK>   &work,
         DenseVector<VIWORK>  &iWork,
         DenseVector<BWORK>   &bWork)
{
    if (work.length()==0 || iWork.length()==0) {
        const auto ws = esx_wsq_impl(computeSchurVectors, sense, A);

        if (work.length()==0) {
            work.resize(ws.third, 1);
        }
        if (iWork.length()==0) {
            iWork.resize(ws.forth, 1);
        }
    }

    IndexType info;
    info = cxxlapack::geesx<IndexType>(computeSchurVectors'V' : 'N',
                                       sortEigenvalues'S' : 'N',
                                       selectFunction.select,
                                       getF77Char(sense),
                                       A.numRows(),
                                       A.data(),
                                       A.leadingDimension(),
                                       sDim,
                                       wr.data(),
                                       wi.data(),
                                       VS.data(),
                                       VS.leadingDimension(),
                                       rCondE,
                                       rCondV,
                                       work.data(),
                                       work.length(),
                                       iWork.data(),
                                       iWork.length(),
                                       bWork.data());
    ASSERT(info>=0);
    return info;
}

//-- (ge)esx [complex variant] -------------------------------------------------

template <typename SelectFunction, typename MA, typename IndexType,
          typename VW, typename MVS, typename RCONDE, typename RCONDV,
          typename VWORK, typename VRWORK, typename BWORK>
IndexType
esx_impl(bool                 computeSchurVectors,
         bool                 sortEigenvalues,
         SelectFunction       selectFunction,
         SENSE::Sense         sense,
         GeMatrix<MA>         &A,
         IndexType            &sDim,
         DenseVector<VW>      &w,
         GeMatrix<MVS>        &VS,
         RCONDE               &rCondE,
         RCONDV               &rCondV,
         DenseVector<VWORK>   &work,
         DenseVector<VRWORK>  &rWork,
         DenseVector<BWORK>   &bWork)
{
    if (work.length()==0) {
        const auto ws = esx_wsq_impl(computeSchurVectors, sense, A);

        work.resize(IndexType(ws.third), 1);
    }

    IndexType info;
    info = cxxlapack::geesx<IndexType>(computeSchurVectors'V' : 'N',
                                       sortEigenvalues'S' : 'N',
                                       selectFunction.select,
                                       getF77Char(sense),
                                       A.numRows(),
                                       A.data(),
                                       A.leadingDimension(),
                                       sDim,
                                       w.data(),
                                       VS.data(),
                                       VS.leadingDimension(),
                                       rCondE,
                                       rCondV,
                                       work.data(),
                                       work.length(),
                                       rWork.data(),
                                       bWork.data());
    ASSERT(info>=0);
    return info;
}


// namespace external

#endif // USE_CXXLAPACK

//== public interface ==========================================================

//-- (ge)esx [real variant] ----------------------------------------------------

template <typename SelectFunction, typename MA, typename IndexType,
          typename VWR, typename VWI, typename MVS,
          typename RCONDE, typename RCONDV,
          typename VWORK, typename VIWORK, typename VBWORK>
typename RestrictTo<IsRealGeMatrix<MA>::value
                 && IsInteger<IndexType>::value
                 && IsRealDenseVector<VWR>::value
                 && IsRealDenseVector<VWI>::value
                 && IsRealGeMatrix<MVS>::value
                 && IsNotComplex<RCONDE>::value
                 && IsNotComplex<RCONDV>::value
                 && IsRealDenseVector<VWORK>::value
                 && IsRealDenseVector<VIWORK>::value
                 && IsRealDenseVector<VBWORK>::value,
         IndexType>::Type
esx(bool                computeSchurVectors,
    bool                sortEigenvalues,
    SelectFunction      selectFunction,
    SENSE::Sense        sense,
    MA                  &&A,
    IndexType           &sDim,
    VWR                 &&wr,
    VWI                 &&wi,
    MVS                 &&VS,
    RCONDE              &rCondE,
    RCONDV              &rCondV,
    VWORK               &&work,
    VIWORK              &&iWork,
    VBWORK              &&bWork)
{
    LAPACK_DEBUG_OUT("(ge)esx [real]");

//
//  Remove references from rvalue types
//
    typedef typename RemoveRef<MA>::Type        MatrixA;
    typedef typename RemoveRef<VWR>::Type       VectorWR;
    typedef typename RemoveRef<VWI>::Type       VectorWI;
    typedef typename RemoveRef<MVS>::Type       MatrixVS;
    typedef typename RemoveRef<VWORK>::Type     VectorWork;
    typedef typename RemoveRef<VIWORK>::Type    VectorIWork;
    typedef typename RemoveRef<VBWORK>::Type    VectorBWork;

//
//  Test the input parameters
//
    IndexType n = A.numRows();
#   ifndef NDEBUG
    ASSERT(A.numRows()==A.numCols());
    ASSERT(A.firstRow()==1);
    ASSERT(A.firstCol()==1);
    ASSERT(work.firstIndex()==1);
    ASSERT(iWork.firstIndex()==1);
    ASSERT(bWork.firstIndex()==1);

    ASSERT(wr.firstIndex()==1);
    ASSERT(wr.length()==0 || wr.length()==n);

    ASSERT(wi.firstIndex()==1);
    ASSERT(wi.length()==0 || wi.length()==n);

    if (computeSchurVectors) {
        ASSERT(VS.numRows()==VS.numCols());
        ASSERT(VS.numRows()==0 || VS.numRows()==n);
        ASSERT(VS.firstRow()==1);
        ASSERT(VS.firstCol()==1);
    }

    if (sortEigenvalues) {
        ASSERT(bWork.firstIndex()==1);
        ASSERT(bWork.length()==0 || bWork.length()==n);
    }
#   endif

//
//  Resize output arguments if they are empty and needed
//
    if (wr.length()==0) {
        wr.resize(n1);
    }
    if (wi.length()==0) {
        wi.resize(n1);
    }
    if (computeSchurVectors && VS.numRows()==0) {
        VS.resize(n, n11);
    }
    if (sortEigenvalues && bWork.length()==0) {
        bWork.resize(n1);
    }
//
//  Make copies of output arguments
//
#   ifdef CHECK_CXXLAPACK

    typename MatrixA::NoView      A_org      = A;
    IndexType                     sDim_org   = sDim;
    typename VectorWR::NoView     wr_org     = wr;
    typename VectorWI::NoView     wi_org     = wi;
    typename MatrixVS::NoView     VS_org     = VS;
    RCONDE                        rCondE_org = rCondE;
    RCONDV                        rCondV_org = rCondV;
    typename VectorWork::NoView   work_org   = work;
    typename VectorIWork::NoView  iWork_org  = iWork;
    typename VectorBWork::NoView  bWork_org  = bWork;

#   endif

//
//  Call implementation
//
    IndexType result = LAPACK_SELECT::esx_impl(computeSchurVectors,
                                               sortEigenvalues,
                                               selectFunction,
                                               sense,
                                               A,
                                               sDim,
                                               wr,
                                               wi,
                                               VS,
                                               rCondE,
                                               rCondV,
                                               work,
                                               iWork,
                                               bWork);

#   ifdef CHECK_CXXLAPACK
//
//  Make copies of results computed by the generic implementation
//
    typename MatrixA::NoView      A_generic      = A;
    IndexType                     sDim_generic   = sDim;
    typename VectorWR::NoView     wr_generic     = wr;
    typename VectorWI::NoView     wi_generic     = wi;
    typename MatrixVS::NoView     VS_generic     = VS;
    RCONDE                        rCondE_generic = rCondE;
    RCONDV                        rCondV_generic = rCondV;
    typename VectorWork::NoView   work_generic   = work;
    typename VectorIWork::NoView  iWork_generic  = iWork;
    typename VectorBWork::NoView  bWork_generic  = bWork;

//
//  restore output arguments
//
    A      = A_org;
    sDim   = sDim_org;
    wr     = wr_org;
    wi     = wi_org;
    VS     = VS_org;
    rCondE = rCondE_org;
    rCondV = rCondV_org;
    work   = work_org;
    iWork  = iWork_org;
    bWork  = bWork_org;

//
//  Compare generic results with results from the native implementation
//
    IndexType _result = external::esx_impl(computeSchurVectors,
                                           sortEigenvalues,
                                           selectFunction,
                                           sense,
                                           A,
                                           sDim,
                                           wr,
                                           wi,
                                           VS,
                                           rCondE,
                                           rCondV,
                                           work,
                                           iWork,
                                           bWork);

    bool failed = false;
    if (! isIdentical(A_generic, A, "A_generic""A")) {
        std::cerr << "CXXLAPACK: A_generic = " << A_generic << std::endl;
        std::cerr << "F77LAPACK: A = " << A << std::endl;
        failed = true;
    }

    if (! isIdentical(sDim_generic, sDim, "sDim_generic""sDim")) {
        std::cerr << "CXXLAPACK: sDim_generic = " << sDim_generic << std::endl;
        std::cerr << "F77LAPACK: sDim = " << sDim << std::endl;
        failed = true;
    }

    if (! isIdentical(wr_generic, wr, "wr_generic""wr")) {
        std::cerr << "CXXLAPACK: wr_generic = " << wr_generic << std::endl;
        std::cerr << "F77LAPACK: wr = " << wr << std::endl;
        failed = true;
    }

    if (! isIdentical(wi_generic, wi, "wi_generic""wi")) {
        std::cerr << "CXXLAPACK: wi_generic = " << wi_generic << std::endl;
        std::cerr << "F77LAPACK: wi = " << wi << std::endl;
        failed = true;
    }

    if (! isIdentical(VS_generic, VS, "VS_generic""VS")) {
        std::cerr << "CXXLAPACK: VS_generic = " << VS_generic << std::endl;
        std::cerr << "F77LAPACK: VS = " << VS << std::endl;
        failed = true;
    }

    if (! isIdentical(rCondE_generic, rCondE, "rCondE_generic""rCondE")) {
        std::cerr << "CXXLAPACK: rCondE_generic = "
                  << rCondE_generic << std::endl;
        std::cerr << "F77LAPACK: rCondE = " << rCondE << std::endl;
        failed = true;
    }

    if (! isIdentical(rCondV_generic, rCondV, "rCondV_generic""rCondV")) {
        std::cerr << "CXXLAPACK: rCondV_generic = "
                  << rCondV_generic << std::endl;
        std::cerr << "F77LAPACK: rCondV = " << rCondV << std::endl;
        failed = true;
    }

    if (! isIdentical(work_generic, work, "work_generic""work")) {
        std::cerr << "CXXLAPACK: work_generic = " << work_generic << std::endl;
        std::cerr << "F77LAPACK: work = " << work << std::endl;
        failed = true;
    }

    if (! isIdentical(iWork_generic, iWork, "iWork_generic""iWork")) {
        std::cerr << "CXXLAPACK: iWork_generic = "
                  << iWork_generic << std::endl;
        std::cerr << "F77LAPACK: iWork = " << iWork << std::endl;
        failed = true;
    }

    if (! isIdentical(bWork_generic, bWork, "bWork_generic""bWork")) {
        std::cerr << "CXXLAPACK: bWork_generic = "
                  << bWork_generic << std::endl;
        std::cerr << "F77LAPACK: bWork = " << bWork << std::endl;
        failed = true;
    }

    if (! isIdentical(result, _result, " result""_result")) {
        std::cerr << "CXXLAPACK:  result = " << result << std::endl;
        std::cerr << "F77LAPACK: _result = " << _result << std::endl;
        failed = true;
    }

    if (failed) {
        ASSERT(0);
    } else {
//        std::cerr << "passed: esx.tcc" << std::endl;
    }

#   endif

    return result;
}

#ifdef USE_CXXLAPACK

//-- (ge)esx [complex variant] -------------------------------------------------

template <typename SelectFunction, typename MA, typename IndexType,
          typename VW, typename MVS, typename RCONDE, typename RCONDV,
          typename VWORK, typename VRWORK, typename VBWORK>
typename RestrictTo<IsComplexGeMatrix<MA>::value
                 && IsInteger<IndexType>::value
                 && IsComplexDenseVector<VW>::value
                 && IsComplexGeMatrix<MVS>::value
                 && IsNotComplex<RCONDE>::value
                 && IsNotComplex<RCONDV>::value
                 && IsComplexDenseVector<VWORK>::value
                 && IsRealDenseVector<VRWORK>::value
                 && IsRealDenseVector<VBWORK>::value,
         IndexType>::Type
esx(bool                computeSchurVectors,
    bool                sortEigenvalues,
    SelectFunction      selectFunction,
    SENSE::Sense        sense,
    MA                  &&A,
    IndexType           &sDim,
    VW                  &&w,
    MVS                 &&VS,
    RCONDE              &rCondE,
    RCONDV              &rCondV,
    VWORK               &&work,
    VRWORK              &&rWork,
    VBWORK              &&bWork)
{
    LAPACK_DEBUG_OUT("(ge)esx [complex]");

//
//  Remove references from rvalue types
//
    typedef typename RemoveRef<MA>::Type        MatrixA;
    typedef typename RemoveRef<VW>::Type        VectorW;
    typedef typename RemoveRef<MVS>::Type       MatrixVS;
    typedef typename RemoveRef<VWORK>::Type     VectorWork;
    typedef typename RemoveRef<VRWORK>::Type    VectorRWork;
    typedef typename RemoveRef<VBWORK>::Type    VectorBWork;

    IndexType n = A.numRows();

//
//  Test the input parameters
//
#   ifndef NDEBUG
    ASSERT(A.numRows()==A.numCols());
    ASSERT(A.firstRow()==1);
    ASSERT(A.firstCol()==1);
    ASSERT(work.firstIndex()==1);
    ASSERT(rWork.firstIndex()==1);
    ASSERT(bWork.firstIndex()==1);

    ASSERT(w.firstIndex()==1);
    ASSERT(w.length()==0 || w.length()==n);

    if (computeSchurVectors) {
        ASSERT(VS.numRows()==VS.numCols());
        ASSERT(VS.numRows()==0 || VS.numRows()==n);
        ASSERT(VS.firstRow()==1);
        ASSERT(VS.firstCol()==1);
    }

    if (sortEigenvalues) {
        ASSERT(bWork.firstIndex()==1);
        ASSERT(bWork.length()==0 || bWork.length()==n);
    }
#   endif

//
//  Resize output arguments if they are empty and needed
//
    if (w.length()==0) {
        w.resize(n1);
    }
    if (computeSchurVectors && VS.numRows()==0) {
        VS.resize(n, n11);
    }
    if (sortEigenvalues && bWork.length()==0) {
        bWork.resize(n1);
    }

//
//  Call external implementation
//
    IndexType result = external::esx_impl(computeSchurVectors,
                                          sortEigenvalues,
                                          selectFunction,
                                          sense,
                                          A,
                                          sDim,
                                          w,
                                          VS,
                                          rCondE,
                                          rCondV,
                                          work,
                                          rWork,
                                          bWork);
    return result;
}

#endif // USE_CXXLAPACK

//-- (ge)esx [worksize query, real variant] ------------------------------------

template <typename MA>
typename RestrictTo<IsNotComplex<typename MA::ElementType>::value,
         Quadruple<typename MA::IndexType> >::Type
esx_wsq(bool                 computeSchurVectors,
        SENSE::Sense         sense,
        const GeMatrix<MA>   &A)
{
    LAPACK_DEBUG_OUT("ev_wsq [real]");

//
//  Test the input parameters
//
#   ifndef NDEBUG
    ASSERT(A.numRows()==A.numCols());
    ASSERT(A.firstRow()==1);
    ASSERT(A.firstCol()==1);
#   endif

//
//  Call implementation
//
    const auto ws = LAPACK_SELECT::esx_wsq_impl(computeSchurVectors, sense, A);

#   ifdef CHECK_CXXLAPACK
//
//  Compare results
//
    const auto _ws = external::esx_wsq_impl(computeSchurVectors, sense, A);
    if (! isIdentical(ws.first, _ws.first, "ws.first""_ws.first")) {
        ASSERT(0);
    }
    if (! isIdentical(ws.third, _ws.third, "ws.third""_ws.third")) {
        ASSERT(0);
    }
    if (! isIdentical(ws.forth, _ws.forth, "ws.forth""_ws.forth")) {
        ASSERT(0);
    }
#   endif

    return ws;
}


#ifdef USE_CXXLAPACK

//-- (ge)esx [worksize query, complex variant] ---------------------------------

template <typename MA>
typename RestrictTo<IsComplex<typename MA::ElementType>::value,
         Triple<typename MA::IndexType> >::Type
esx_wsq(bool                 computeSchurVectors,
        SENSE::Sense         sense,
        const GeMatrix<MA>   &A)
{
    LAPACK_DEBUG_OUT("ev_wsq [complex]");

//
//  Test the input parameters
//
#   ifndef NDEBUG
    ASSERT(A.numRows()==A.numCols());
    ASSERT(A.firstRow()==1);
    ASSERT(A.firstCol()==1);
#   endif

//
//  Call external implementation
//
    const auto ws = external::esx_wsq_impl(computeSchurVectors, sense, A);

    return ws;
}

#endif // USE_CXXLAPACK


} } // namespace lapack, flens

#endif // FLENS_LAPACK_GE_ESX_TCC