This file is indexed.

/usr/include/ql/experimental/credit/saddlepointlossmodel.hpp is in libquantlib0-dev 1.7.1-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2014 Jose Aparicio

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program 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 license for more details.
*/

#ifndef quantlib_saddle_point_lossmodel_hpp
#define quantlib_saddle_point_lossmodel_hpp

#include <ql/math/solvers1d/brent.hpp>
#include <ql/math/solvers1d/newton.hpp>

#include <ql/experimental/credit/basket.hpp>
#include <ql/experimental/credit/defaultlossmodel.hpp>
#include <ql/experimental/credit/constantlosslatentmodel.hpp>

namespace QuantLib {

    /*! \brief Saddle point portfolio credit default loss model.\par
      Default Loss model implementing the Saddle point expansion 
      integrations on several default risk metrics. Codepence is dealt 
      through a latent model making the integrals conditional to the latent 
      model factor. Latent variables are integrated indirectly.\par
    See:\par
    <b>Taking to the saddle</b> by R.Martin, K.Thompson and C.Browne; RISK JUNE 
        2001; p.91\par
    <b>The saddlepoint method and portfolio optionalities</b> R.Martin in Risk 
        December 2006\par
    <b>VAR: who contributes and how much?</b> R.Martin, K.Thompson and 
        C.Browne RISK AUGUST 2001\par
    <b>Shortfall: Who contributes and how much?</b> R. J. Martin, Credit Suisse 
        January 3, 2007 \par
    <b>Don�t Fall from the Saddle: the Importance of Higher Moments of Credit 
        Loss Distributions</b> J.Annaert, C.Garcia Joao Batista, J.Lamoot, 
        G.Lanine February 2006, Gent University\par
    <b>Analytical techniques for synthetic CDOs and credit default risk 
        measures</b> A. Antonov, S. Mechkovy, and T. Misirpashaevz; 
        NumeriX May 23, 2005 \par
    <b>Computation of VaR and VaR contribution in the Vasicek portfolio credit 
        loss model: a comparative study</b> X.Huang, C.W.Oosterlee, M.Mesters
        Journal of Credit Risk (75�96) Volume 3/ Number 3, Fall 2007 \par
    <b>Higher-order saddlepoint approximations in the Vasicek portfolio credit 
        loss model</b> X.Huang, C.W.Oosterlee, M.Mesters  Journal of 
        Computational Finance (93�113) Volume 11/Number 1, Fall 2007 \par
    While more expensive, a high order expansion is used here; see the paper by 
    Antonov et al for the terms retained.\par
    For a discussion of an alternative to fix the error at low loss levels 
    (more relevant to pricing than risk metrics) see: \par
    <b>The hybrid saddlepoint method for credit portfolios</b> by A.Owen, 
    A.McLeod and K.Thompson; in Risk, August 2009. This is not implemented here
    though (yet?...)\par
    For the more general context mathematical theory see: <b>Saddlepoint 
    approximations with applications</b> by R.W. Butler, Cambridge series in 
    statistical and probabilistic mathematics. 2007 \par
    \todo Some portfolios show instabilities in the high order expansion terms.
    \todo Methods here are calling and integrating using the unconditional 
        probabilities without inverting them first; quite a lot of calls to 
        the copula inversion can be avoided; this should improve performance.
    \todo Revise the model for stability of the saddle point calculation. The
        search for the point does not convege in extreme cases; e.g. very high
        value of all the factors; factors for each variable not ordered from 
        high to low,...
    */

    /* The treatment of recovery wont work with random recoveries, they should
    be passed to the conditional methods in the same way as the probabilities.
    */

    /*
    TO DO:
    -> Failing when the tranche upper loss limit goes over the max attainable 
        loss.

    - With 15 quadrature points things are OK but 25 gives me -1#IND000 errors 
            (over region around the EL I think) 
    - Silly bug when calling some methods on todays date (zero time). 
            ProbDef = 0 there
    - VaR <- tranched?????!
    - ESF <- tranched????!!
    - VaR split
    - ESF split?

    When introducing defaults; somewhere, (after an update?) there should be 
    a check that: copula_->basketSize() EQUALS remainingBasket_.size()
    */
    template<class CP> 
    class SaddlePointLossModel : public DefaultLossModel {
    public:
        SaddlePointLossModel(
            const boost::shared_ptr<ConstantLossLatentmodel<CP> >& m)
            : copula_(m) { }
    protected:
        // ----------- Cumulants and derivatives auxiliary functions ---------

        /*! Returns the cumulant generating function (zero-th order 
        expansion term) conditional to the mkt factor:
            \f$ K = \sum_j ln(1-p_j + p_j e^{N_j \times lgd_j \times s}) \f$
        */
        Real CumulantGeneratingCond(
            const std::vector<Real>& invUncondProbs,
            Real lossFraction,// saddle pt
            const std::vector<Real>&  mktFactor) const;
        /*! Returns the first derivative of the cumulant generating function 
        (first order expansion term) conditional to the mkt factor:
           \f$ K1 = \sum_j \frac{p_j \times N_j \times LGD_j \times 
                e^{N_j \times LGD_j \times s}} \
                             {1-p_j + p_j e^{N_j \times LGD_j \times s}} \f$
           One of its properties is that its value at zero is the portfolio 
           expected loss (in fractional units). Its value at infinity is the 
           max attainable portfolio loss. To be understood conditional to the 
           market factor.
        */
        Real CumGen1stDerivativeCond(
            const std::vector<Real>& invUncondProbs,
            Real saddle, // in fract loss units... humm not really
            const std::vector<Real>&  mktFactor) const;
        /*! Returns the second derivative of the cumulant generating function 
        (first order expansion term) conditional to the mkt factor:
            \f$ K2 = \sum_j \frac{p_j \times (N_j \times LGD_j)^2 \times 
                e^{N_j \times LGD_j \times s}}
                             {1-p_j + p_j e^{N_j \times LGD_j \times s}}
                      - (\frac{p_j \times N_j \times LGD_j \times e^{N_j \times 
                      LGD_j \times s}}
                             {1-p_j + p_j e^{N_j \times LGD_j \times s}})^2 \f$
        */
        Real CumGen2ndDerivativeCond(
            const std::vector<Real>& invUncondProbs,
            Real saddle, 
            const std::vector<Real>&  mktFactor) const;
        Real CumGen3rdDerivativeCond(
            const std::vector<Real>& invUncondProbs,
            Real saddle, 
            const std::vector<Real>&  mktFactor) const;
        Real CumGen4thDerivativeCond(
            const std::vector<Real>& invUncondProbs,
            Real saddle, 
            const std::vector<Real>&  mktFactor) const ;
        /*! Returns the cumulant and second to fourth derivatives together.
          Included for optimization, most methods work on expansion of these 
          terms.
          Alternatively use a local private buffer member? */
        boost::tuples::tuple<Real, Real, Real, Real> CumGen0234DerivCond(
            const std::vector<Real>& invUncondProbs,
            Real saddle, 
            const std::vector<Real>&  mktFactor) const;
        boost::tuples::tuple<Real, Real> CumGen02DerivCond(
            const std::vector<Real>& invUncondProbs,
            Real saddle, 
            const std::vector<Real>&  mktFactor) const;

        /* Unconditional cumulants. Because this class integrates the various
          statistics it provides in indirect mode they are never used. 
          Provided for completeness/extendability */
        /*! Returns the cumulant generating function (zero-th order expansion
          term) weighting the conditional value by the prob density of the 
          market factor, called by integrations */
        Real CumulantGenerating(const Date& date, Real s) const;
        Real CumGen1stDerivative(const Date& date, Real s) const;
        Real CumGen2ndDerivative(const Date& date, Real s) const;
        Real CumGen3rdDerivative(const Date& date, Real s) const;
        Real CumGen4thDerivative(const Date& date, Real s) const;
        
        // -------- Saddle point search functions ---------------------------
        class SaddleObjectiveFunction : 
            public std::unary_function<Real, Real> {
            const SaddlePointLossModel& me_;
            Real targetValue_;
            const std::vector<Real>& mktFactor_;
            const std::vector<Real>& invUncondProbs_;
        public:
            //! @param target in fractional loss units
            SaddleObjectiveFunction(const SaddlePointLossModel& me,
                                    const Real target,
                                    const std::vector<Real>& invUncondProbs,
                                    const std::vector<Real>& mktFactor
                                    )
            : me_(me), 
              targetValue_(target), 
              mktFactor_(mktFactor), 
              invUncondProbs_(invUncondProbs)
            {}
            Real operator()(const Real x) const {
                return me_.CumGen1stDerivativeCond(invUncondProbs_, x, 
                    mktFactor_) - targetValue_;
            }
            Real derivative(Real x) const {
                return me_.CumGen2ndDerivativeCond(invUncondProbs_, x, 
                    mktFactor_);
            }
        };

        /*! Calculates the mkt-fct-conditional saddle point for the loss level 
            given and the probability passed. 
            The date is implicitly given through the probability. Performance 
            requires to pass the probabilities for that date. Otherwise once we
            integrate this over the market factor we would be computing the same
            probabilities over and over. While this works fine here some models
            of the recovery rate might require the date.

            @param lossLevel in total portfolio loss fractional unit
            \todo Improve convergence speed (which is bad at the moment).See 
            discussion in several places; references above and The Oxford 
            Handbook of CD, sect 2.9
        */
        Real findSaddle(
            const std::vector<Real>& invUncondProbs,
            Real lossLevel,
            const std::vector<Real>& mktFactor, 
            Real accuracy = 1.0e-3,//1.e-4
            Natural maxEvaluations = 50
            ) const;

        class SaddlePercObjFunction : public std::unary_function<Real, Real> {
            const SaddlePointLossModel& me_;
            Real targetValue_;
            Date date_;
        public:
            SaddlePercObjFunction(
                const SaddlePointLossModel& me,
                const Real target,
                const Date& date)
            : me_(me), targetValue_(1.-target), date_(date) {}
            /*!
                @param x Is the _tranche_ loss fraction
            */
            Real operator()(const Real x) const {
                return me_.probOverLoss(date_, x) - targetValue_;
            }
        };
        // Functionality, Provides various portfolio statistics---------------
    public:
        /*! Returns the loss amount at the requested date for which the 
        probability of lossing that amount or less is equal to the value passed.
        */
        Real percentile(const Date& d, Probability percentile) const;
    protected:
        /*! Conditional (on the mkt factor) prob of a loss fraction of the the 
                tranched portfolio.

            @param trancheLossFract Fraction over the tranche notional. In [0,1]
        */
        Probability probOverLossCond( 
            const std::vector<Real>& invUncondProbs,
            Real trancheLossFract, 
            const std::vector<Real>& mktFactor) const;
        Probability probOverLossPortfCond1stOrder(
            const std::vector<Real>& invUncondProbs,
            Real loss, 
            const std::vector<Real>& mktFactor) const;
    public:
        Probability probOverLoss(const Date& d, Real trancheLossFract) const;

        Disposable<std::map<Real, Probability> > 
            lossDistribution(const Date& d) const;
    protected:
        /*! 
            Probability of having losses in the portfolio due to default 
            events equal or larger than a given absolute loss value on a 
            given date conditional to the latent model factor.
            The integral expression on the expansion is the first order 
            integration as presented in several references, see for instance; 
            equation 8 in R.Martin, K.Thompson, and C. Browne 's 
            'Taking to the Saddle', Risk Magazine, June 2001, page 91

            @param loss loss in absolute value
        */
        Probability probOverLossPortfCond(
                        const std::vector<Real>& invUncondProbs,

            Real loss, 
            const std::vector<Real>& mktFactor) const;
    public:
        Probability probOverPortfLoss(const Date& d, Real loss) const;
        Real expectedTrancheLoss(const Date& d) const;
    protected:
        /*!
        Probability density of having losses in the total portfolio (untranched)
        due to default events equal to a given value on a given date conditional
        to the latent model factor.
        Based on the integrals of the expected shortfall. 
        */
        Probability probDensityCond(const std::vector<Real>& invUncondProbs,
            Real loss, const std::vector<Real>& mktFactor) const;
    public:
        Probability probDensity(const Date& d, Real loss) const;
    protected:
        Disposable<std::vector<Real> > splitLossCond(
            const std::vector<Real>& invUncondProbs,
            Real loss, std::vector<Real> mktFactor) const;
        Real expectedShortfallFullPortfolioCond(
            const std::vector<Real>& invUncondProbs,
            Real lossPerc, const std::vector<Real>& mktFactor) const;
        Real expectedShortfallTrancheCond(
            const std::vector<Real>& invUncondProbs,
            Real lossPerc, Probability percentile, 
            const std::vector<Real>& mktFactor) const;
        Disposable<std::vector<Real> > expectedShortfallSplitCond(
            const std::vector<Real>& invUncondProbs,
            Real lossPerc, const std::vector<Real>& mktFactor) const;
    public:
        /*! Sensitivities of the individual names to a given portfolio loss 
            value due to defaults. It returns ratios to the total structure 
            notional, which aggregated add up to the requested loss value.
            Notice then that it refers to the total portfolio, not the tranched
            basket.
            \todo  Fix this.
            \par
            see equation 8 in <b>VAR: who contributes and how much?</b> by 
            R.Martin, K.Thompson, and C. Browne in Risk Magazine, August 2001

        @param loss Loss amount level at which we want to request the 
                        sensitivity. Equivalent to a percentile.
        */
        Disposable<std::vector<Real> > 
            splitVaRLevel(const Date& date, Real loss) const;
        Real expectedShortfall(const Date&d, Probability percentile) const;
    protected:
        Real conditionalExpectedLoss(
            const std::vector<Real>& invUncondProbs,
            const std::vector<Real>& mktFactor) const;
        Real conditionalExpectedTrancheLoss(
            const std::vector<Real>& invUncondProbs,
            const std::vector<Real>& mktFactor) const;

        void resetModel() {
            remainingNotionals_ = basket_->remainingNotionals();
            remainingNotional_  = basket_->remainingNotional();
            attachRatio_ = std::min(basket_->remainingAttachmentAmount() 
                / basket_->remainingNotional(), 1.);
            detachRatio_ = std::min(basket_->remainingDetachmentAmount() 
                / basket_->remainingNotional(), 1.);
            copula_->resetBasket(basket_.currentLink());
        }
    protected:
        const boost::shared_ptr<ConstantLossLatentmodel<CP> > copula_;
        // cached todays arguments values
        mutable Size remainingSize_;
        mutable std::vector<Real> remainingNotionals_;
        mutable Real remainingNotional_;
        // remaining basket levels:
        mutable Real attachRatio_, detachRatio_;
        /*
        // Just for testing the ESF direct integration, not for release, 
        //   this is very inneficient:
        class ESFIntegrator {
        public:
            ESFIntegrator(const SaddlePointLossModel& me,
                const Date& date,
                Real lossPercentileFract//,
                //const std::vector<Real>& mktFactor
                )
                : me_(me), date_(date),lossPercentileFract_(lossPercentileFract)
            {}


            Real operator()(Real x) const {
                return me_.densityTrancheLoss(date_, x + lossPercentileFract_) 
                    * (x + lossPercentileFract_);
            }

            Real lossPercentileFract_;
            Date date_;
            //  const std::vector<Real>& mktFactor_;
            const SaddlePointLossModel& me_;
        };
        */
    };


    // -- Inlined integrations------------------------------------------------

    // Unconditional Moments and derivatives. --------------------------------
    template<class CP>
    inline Real SaddlePointLossModel<CP>::CumulantGenerating(
        const Date& date, Real s) const 
    {
        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(date);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

        return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                    &SaddlePointLossModel<CP>::CumulantGeneratingCond,
                    this,
                    boost::cref(invUncondProbs),
                   s,
                    _1)
                )
            );
    }

    template<class CP>
    inline Real SaddlePointLossModel<CP>::CumGen1stDerivative(
        const Date& date, Real s) const 
    {
        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(date);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

       return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                    &SaddlePointLossModel<CP>::CumGen1stDerivativeCond,
                    this,
                    boost::cref(invUncondProbs),
                    s,
                    _1)
                )
            );
    }

    template<class CP>
    inline Real SaddlePointLossModel<CP>::CumGen2ndDerivative(
        const Date& date, Real s) const 
    {
        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(date);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

        return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                    &SaddlePointLossModel<CP>::CumGen2ndDerivativeCond,
                    this,
                    boost::cref(invUncondProbs),
                    s,
                    _1)
                )
            );
    }

    template<class CP>
    inline Real SaddlePointLossModel<CP>::CumGen3rdDerivative(
        const Date& date, Real s) const 
    {
        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(date);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

        return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                    &SaddlePointLossModel<CP>::CumGen3rdDerivativeCond,
                    this,
                    boost::cref(invUncondProbs),
                    s,
                    _1)
                )
            );
    }

    template<class CP>
    inline Real SaddlePointLossModel<CP>::CumGen4thDerivative(
        const Date& date, Real s) const 
    {
        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(date);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

        return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                    &SaddlePointLossModel<CP>::CumGen4thDerivativeCond,
                    this,
                    boost::cref(invUncondProbs),
                    s,
                    _1)
                )
            );
    }

    template<class CP>
    inline Probability SaddlePointLossModel<CP>::probOverLoss(
        const Date& d, Real trancheLossFract) const 
    {
        // avoid computation:
        if (trancheLossFract >= 
            // time dependent soon:
            basket_->detachmentAmount()) return 0.;

        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(d);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

        return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                    &SaddlePointLossModel<CP>::probOverLossCond,
                    this,
                    boost::cref(invUncondProbs),
                    trancheLossFract,
                    _1)
                )
            );
        }

    template<class CP>
    inline Probability SaddlePointLossModel<CP>::probOverPortfLoss(
        const Date& d, Real loss) const 
    {
        const std::vector<Probability> uncondProbs = 
            basket_->remainingProbabilities(d);

        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(d);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

        return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                    &SaddlePointLossModel<CP>::probOverLossPortfCond,
                    this,
                    boost::cref(invUncondProbs),
                    loss,
                    _1)
                )
            );
    }

    template<class CP>
    inline Real SaddlePointLossModel<CP>::expectedTrancheLoss(
        const Date& d) const 
    {
        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(d);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

        return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                    &SaddlePointLossModel<CP>::conditionalExpectedTrancheLoss,
                    this,
                    boost::cref(invUncondProbs),
                    _1)
                )
            );
    }

    template<class CP>
    inline Probability SaddlePointLossModel<CP>::probDensity(
        const Date& d, Real loss) const 
    {
        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(d);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

        return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                    &SaddlePointLossModel<CP>::probDensityCond,
                    this,
                    boost::cref(invUncondProbs),
                    loss,
                    _1)
                )
            );
    }

    template<class CP>
    inline Disposable<std::vector<Real> > 
    SaddlePointLossModel<CP>::splitVaRLevel(const Date& date, Real s) const 
    {
        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(date);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
            copula_->inverseCumulativeY(invUncondProbs[i], i);

        return copula_->integratedExpectedValue(
            boost::function<Disposable<std::vector<Real> > (
                const std::vector<Real>& v1)>(
                    boost::bind(
                        &SaddlePointLossModel<CP>::splitLossCond,
                        this,
                    boost::cref(invUncondProbs),
                        s,
                        _1)
                )
            );
    }







    /* ------------------------------------------------------------------------
                    Conditional Moments and derivatives. 

        Notice that in all this methods the date dependence is implicitly
        present in the unconditional probabilities. But, as in other LMs, it
        is redundant and expensive to perform the call to the probabilities in
        these methods since they are integrands.
       ---------------------------------------------------------------------- */

    template<class CP>
    Real SaddlePointLossModel<CP>::CumulantGeneratingCond(
        const std::vector<Real>& invUncondProbs,
        Real lossFraction,
        const std::vector<Real>&  mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        Real sum = 0.;

        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = 
                copula_->conditionalDefaultProbabilityInvP(
                    invUncondProbs[iName], iName, mktFactor);
            sum += std::log(1. - pBuffer + 
                pBuffer * std::exp(remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName],
                    iName, mktFactor)) * lossFraction / remainingNotional_));
        }
       return sum;
    }

    template<class CP>
    Real SaddlePointLossModel<CP>::CumGen1stDerivativeCond(
        const std::vector<Real>& invUncondProbs,
        Real saddle,
        const std::vector<Real>&  mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        Real sum = 0.;

        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = 
                copula_->conditionalDefaultProbabilityInvP(
                    invUncondProbs[iName], iName, mktFactor);
            // loss in fractional units
            Real lossInDef = remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName], 
                    iName, mktFactor)) / remainingNotional_;
            Real midFactor = pBuffer * std::exp(lossInDef * saddle);
            sum += lossInDef * midFactor / (1.-pBuffer + midFactor);
        }
       return sum;
    }

    template<class CP>
    Real SaddlePointLossModel<CP>::CumGen2ndDerivativeCond(
        const std::vector<Real>& invUncondProbs,
        Real saddle, 
        const std::vector<Real>&  mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        Real sum = 0.;

        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = 
                copula_->conditionalDefaultProbabilityInvP(
                    invUncondProbs[iName], iName, mktFactor);
            // loss in fractional units
            Real lossInDef = remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName], 
                    iName, mktFactor)) / remainingNotional_;
            Real midFactor = pBuffer * std::exp(lossInDef * saddle);
            Real denominator = 1.-pBuffer + midFactor;
            sum += lossInDef * lossInDef * midFactor / denominator - 
                std::pow(lossInDef * midFactor / denominator , 2.);
        }
       return sum;
    }

    template<class CP>
    Real SaddlePointLossModel<CP>::CumGen3rdDerivativeCond(
        const std::vector<Real>& invUncondProbs,
        Real saddle, 
        const std::vector<Real>&  mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        Real sum = 0.;

        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = 
                copula_->conditionalDefaultProbabilityInvP(
                    invUncondProbs[iName], iName, mktFactor);
            Real lossInDef = remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName], 
                    iName, mktFactor)) / remainingNotional_;

            const Real midFactor = pBuffer * std::exp(lossInDef * saddle);
            const Real denominator = 1.-pBuffer + midFactor;

            const Real& suma0 = denominator;
            const Real suma1  = lossInDef * midFactor;
            const Real suma2  = lossInDef * suma1;
            const Real suma3  = lossInDef * suma2;

            sum += (suma3 + (2.*std::pow(suma1, 3.)/suma0 - 
                3.*suma1*suma2)/suma0)/suma0;
        }
       return sum;
    }

    template<class CP>
    Real SaddlePointLossModel<CP>::CumGen4thDerivativeCond(
        const std::vector<Real>& invUncondProbs,
        Real saddle, 
        const std::vector<Real>&  mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        Real sum = 0.;

        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = 
                copula_->conditionalDefaultProbabilityInvP(
                    invUncondProbs[iName], iName, mktFactor);
            Real lossInDef = remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName], 
                    iName, mktFactor)) / remainingNotional_;

            Real midFactor = pBuffer * std::exp(lossInDef * saddle);
            Real denominator = 1.-pBuffer + midFactor;

            const Real& suma0 = denominator;
            const Real suma1  = lossInDef * midFactor;
            const Real suma2  = lossInDef * suma1;
            const Real suma3  = lossInDef * suma2;
            const Real suma4  = lossInDef * suma3;

            sum += (suma4 + (-4.*suma1*suma3 - 3.*suma2*suma2 + 
                (12.*suma1*suma1*suma2 - 
                    6.*std::pow(suma1,4.)/suma0)/suma0)/suma0)/suma0;
        }
       return sum;
    }

    template<class CP>
    boost::tuples::tuple<Real, Real, Real, Real> /// DISPOSABLE????
        SaddlePointLossModel<CP>::CumGen0234DerivCond(
        const std::vector<Real>& invUncondProbs,
        Real saddle, 
        const std::vector<Real>&  mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        Real deriv0 = 0.,
             //deriv1 = 0.,
             deriv2 = 0.,
             deriv3 = 0.,
             deriv4 = 0.;
        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = 
                copula_->conditionalDefaultProbabilityInvP(
                    invUncondProbs[iName], iName, mktFactor);
            Real lossInDef = remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName], 
                    iName, mktFactor)) / remainingNotional_;

            Real midFactor = pBuffer * std::exp(lossInDef * saddle);
            Real denominator = 1.-pBuffer + midFactor;

            const Real& suma0 = denominator;
            const Real suma1  = lossInDef * midFactor;
            const Real suma2  = lossInDef * suma1;
            const Real suma3  = lossInDef * suma2;
            const Real suma4  = lossInDef * suma3;

            // To do: optimize these:
            deriv0 += std::log(suma0);
            //deriv1 += suma1 / suma0;
            deriv2 += suma2 / suma0 - std::pow(suma1 / suma0 , 2.);
            deriv3 += (suma3 + (2.*std::pow(suma1, 3.)/suma0 - 
                3.*suma1*suma2)/suma0)/suma0;
            deriv4 += (suma4 + (-4.*suma1*suma3 - 3.*suma2*suma2 + 
                (12.*suma1*suma1*suma2 - 
                    6.*std::pow(suma1,4.)/suma0)/suma0)/suma0)/suma0;
        }
        return boost::tuples::tuple<Real, Real, Real, Real>(deriv0, deriv2, 
            deriv3, deriv4);
    }

    template<class CP>
    boost::tuples::tuple<Real, Real> /// DISPOSABLE???? 
        SaddlePointLossModel<CP>::CumGen02DerivCond(
        const std::vector<Real>& invUncondProbs,
        Real saddle, 
        const std::vector<Real>&  mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        Real deriv0 = 0.,
             //deriv1 = 0.,
             deriv2 = 0.;
        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = 
                copula_->conditionalDefaultProbabilityInvP(
                    invUncondProbs[iName], iName, mktFactor);
            Real lossInDef = remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName], 
                    iName, mktFactor)) / remainingNotional_;

            Real midFactor = pBuffer * std::exp(lossInDef * saddle);
            Real denominator = 1.-pBuffer + midFactor;

            const Real& suma0 = denominator;
            const Real suma1  = lossInDef * midFactor;
            const Real suma2  = lossInDef * suma1;

            // To do: optimize these:
            deriv0 += std::log(suma0);
            //deriv1 += suma1 / suma0;
            deriv2 += suma2 / suma0 - std::pow(suma1 / suma0 , 2.);
        }
        return boost::tuples::tuple<Real, Real>(deriv0, deriv2);
    }

    // ----- Saddle point search ----------------------------------------------

    template<class CP>
    Real SaddlePointLossModel<CP>::findSaddle(
        const std::vector<Real>& invUncondPs,
        Real lossLevel, // in total portfolio loss fractional unit 
        const std::vector<Real>& mktFactor, 
        Real accuracy,
        Natural maxEvaluations
        ) const 
    {
        // \to do:
        // REQUIRE that loss level is below the max loss attainable in 
        //   the portfolio, otherwise theres no solution...
        SaddleObjectiveFunction f(*this, lossLevel, invUncondPs, mktFactor);

        Size nNames = remainingNotionals_.size();
        std::vector<Real> lgds;
        for(Size iName=0; iName<nNames; iName++)
            lgds.push_back(remainingNotionals_[iName] * 
            (1.-copula_->conditionalRecoveryInvP(invUncondPs[iName], iName,
                mktFactor)) );

        // computed limits:
        // position of the name with the largest relative exposure loss (i.e.:
        //   largest: N_i LGD_i / N_{total})
        Size iNamMax = std::distance(lgds.begin(), 
            std::max_element(lgds.begin(), lgds.end()) );
        // gap to be considered zero at the negative side of the logistic 
        //   inversion:
        static const Real deltaMin = 1.e-5;
        //
        Probability pMaxName = copula_->conditionalDefaultProbabilityInvP(
            invUncondPs[iNamMax], iNamMax, mktFactor);
        // aproximates the  saddle pt corresponding to this minimum; finds 
        //   it by using only the smallest logistic term and thus this is 
        //   smaller than the true value:
        Real saddleMin = 1./(lgds[iNamMax]/remainingNotional_) * 
            std::log(deltaMin*(1.-pMaxName)/
                (pMaxName*lgds[iNamMax]/remainingNotional_-pMaxName*deltaMin));
        // and the associated minimum loss is approximately: (this is thence 
        //   the minimum loss we can resolve/invert)
        Real minLoss = 
            CumGen1stDerivativeCond(invUncondPs, saddleMin, mktFactor);

        // If we are below the loss resolution it returns approximating 
        //  by the minimum/maximum attainable point. Typically the functionals
        //  to integrate will have a low dependency on this point.
        if(lossLevel < minLoss) return saddleMin;
        static const Real deltaMax = 1.e-6; // 1.e-9;
        Real saddleMax = 1./(lgds[iNamMax]/remainingNotional_) * 
            std::log((lgds[iNamMax]/remainingNotional_
                -deltaMin)*(1.-pMaxName)/(pMaxName*deltaMin));
        Real maxLoss = 
            CumGen1stDerivativeCond(invUncondPs, saddleMax, mktFactor);
        if(lossLevel > maxLoss) return saddleMax;

        Brent solverBrent;
        Real guess = (saddleMin+saddleMax)/2.;
        /*
            (lossLevel - 
                CumGen1stDerivativeCond(invUncondPs, lossLevel, mktFactor))
                /CumGen2ndDerivativeCond(invUncondPs, lossLevel, mktFactor);
        if(guess > saddleMax) guess = (saddleMin+saddleMax)/2.;
        */
        solverBrent.setMaxEvaluations(maxEvaluations);
        return solverBrent.solve(f, accuracy, guess, saddleMin, saddleMax);
    }


    // ----- Statistics -------------------------------------------------------


    template<class CP>
    Real SaddlePointLossModel<CP>::percentile(const Date& d, 
        Probability percentile) const 
    {
        //this test should be in the calling basket...?
        QL_REQUIRE(percentile >=0. && percentile <=1., 
            "Incorrect percentile value.");

        // still this does not tackle the situation where we have cumulated 
        //   losses from previous defaults:
        if(d <= Settings::instance().evaluationDate()) return 0.;

        // Trivial cases when the percentile is outside the prob range 
        //   associated to the tranche limits:
        if(percentile <= 1.-probOverLoss(d, 0.)) return 0.;
        if(percentile >= 1.-probOverLoss(d, 1.)) 
            return basket_->remainingTrancheNotional();

        SaddlePercObjFunction f(*this, percentile, d);
        Brent solver;
        solver.setMaxEvaluations(100);
        Real minVal = QL_EPSILON;

        Real maxVal = 1.-QL_EPSILON; 
        Real guess = 0.5;

        Real solut = solver.solve(f, 1.e-4, guess, minVal, maxVal);
        return basket_->remainingTrancheNotional() * solut;
    }

    template<class CP>
    Probability SaddlePointLossModel<CP>::probOverLossCond(
        const std::vector<Real>& invUncondPs,
        Real trancheLossFract, 
        const std::vector<Real>& mktFactor) const {
        Real portfFract = attachRatio_ + trancheLossFract * 
            (detachRatio_-attachRatio_);// these are remaining ratios
        
        // for non-equity losses add the probability jump at zero tranche 
        //   losses (since this method returns prob of losing more or 
        //   equal to)
        ////////////////---       if(trancheLossFract <= QL_EPSILON) return 1.;
        return 
            probOverLossPortfCond(invUncondPs,
            //below; should substract realized loses. Use remaining amounts??
                portfFract * basket_->basketNotional(),
                mktFactor);
    }

    template<class CP>
    Disposable<std::map<Real, Probability> > 
        SaddlePointLossModel<CP>::lossDistribution(const Date& d) const {
        std::map<Real, Probability> distrib;
        static const Real numPts = 500.;
        for(Real lossFraction=1./numPts; lossFraction<0.45; 
            lossFraction+= 1./numPts)
            distrib.insert(std::make_pair<Real, Probability>(
                lossFraction * remainingNotional_ , 
                  1.-probOverPortfLoss(d, lossFraction* remainingNotional_ )));
        return distrib;
    }

    /*  NOTICE THIS IS ON THE TOTAL PORTFOLIO ---- UNTRANCHED..............
        Probability of having losses in the portfolio due to default 
        events equal or larger than a given absolute loss value on a 
        given date conditional to the latent model factor.
        The integral expression on the expansion is the first order 
        integration as presented in several references, see for instance; 
        equation 8 in R.Martin, K.Thompson, and C. Browne 's 
        'Taking to the Saddle', Risk Magazine, June 2001, page 91

        @param loss loss in absolute value
    */
    template<class CP>
    Probability SaddlePointLossModel<CP>::probOverLossPortfCond(
        const std::vector<Real>& invUncondProbs,
        Real loss, 
        const std::vector<Real>& mktFactor) const 
    {
        /* This is taking in the unconditional probabilites non inverted. See if
        the callers can be written taking the inversion already; if they are 
        performing it thats a perf hit. At least this can be seen to be true
        for the recovery call (but rand rr are not intended to be used yet)
        */
       // return probOverLossPortfCond1stOrder(d, loss, mktFactor);
        if (loss <= QL_EPSILON) return 1.;

        Real relativeLoss = loss / remainingNotional_;
        if (relativeLoss >= 1.-QL_EPSILON) return 0.;

        const Size nNames = remainingNotionals_.size();

        Real averageRecovery_ = 0.;
        for(Size iName=0; iName < nNames; iName++)
            averageRecovery_ += copula_->conditionalRecoveryInvP(
                invUncondProbs[iName], iName, mktFactor);
        averageRecovery_ = averageRecovery_ / nNames;

        Real maxAttLossFract = 1.-averageRecovery_;
        if(relativeLoss > maxAttLossFract) return 0.;

        Real saddlePt = findSaddle(invUncondProbs,
            relativeLoss, mktFactor);

        boost::tuples::tuple<Real, Real, Real, Real> cumulants = 
            CumGen0234DerivCond(invUncondProbs, 
                saddlePt, mktFactor);
        Real baseVal = cumulants.get<0>();
        Real secondVal = cumulants.get<1>();
        Real K3Saddle = cumulants.get<2>();
        Real K4Saddle = cumulants.get<3>();

        Real saddleTo2 = saddlePt * saddlePt;
        Real saddleTo3 = saddleTo2 * saddlePt;
        Real saddleTo4 = saddleTo3 * saddlePt;
        Real saddleTo6 = saddleTo4 * saddleTo2;
        Real K3SaddleTo2 = K3Saddle*K3Saddle;

        if(saddlePt > 0.) { // <-> (loss > condEL)
            Real exponent = baseVal - relativeLoss * saddlePt + 
                .5 * saddleTo2 * secondVal;
            if( std::abs(exponent) > 700.) return 0.;
            return 
                std::exp(exponent)
                * CumulativeNormalDistribution()(-std::abs(saddlePt)*
                    std::sqrt(/*saddleTo2 **/secondVal))

                // high order corrections:
                * (1. - saddleTo3*K3Saddle/6. + saddleTo4*K4Saddle/24. + 
                    saddleTo6*K3SaddleTo2/72.) 
                /*
                // FIX ME: this term introduces at times numerical 
                //   instabilty (shows up in percentile computation)
                + (3.*secondVal*(1.-secondVal*saddleTo2)*
                        (saddlePt*K4Saddle-4.*K3Saddle)
                    - saddlePt*K3SaddleTo2*(3.-saddleTo2*secondVal + 
                            saddleTo4*secondVal*secondVal)) 
                     / (72.*M_SQRTPI*M_SQRT_2*std::pow(secondVal, 5./2.) ) 
                 */
                 ;
        }else if(saddlePt==0.){// <-> (loss == condEL)
            return .5;
        }else {// <->(loss < condEL)
            Real exponent = baseVal - relativeLoss * saddlePt + 
                .5 * saddleTo2 * secondVal;
            if( std::abs(exponent) > 700.) return 0.;
            return 
                1.-
                std::exp(exponent)
                * CumulativeNormalDistribution()(-std::abs(saddlePt)
                    * std::sqrt(/*saddleTo2 **/secondVal))// static call?

                // high order corrections:
                * (1. - saddleTo3*K3Saddle/6. + saddleTo4*K4Saddle/24. + 
                    saddleTo6*K3SaddleTo2/72.) 
                /*
                  + (3.*secondVal*(1.-secondVal*saddleTo2)*
                    (saddlePt*K4Saddle-4.*K3Saddle)
                  - saddlePt*K3SaddleTo2*(3.-saddleTo2*secondVal +
                        saddleTo4*secondVal*secondVal)) 
                    / (72.*M_SQRTPI*M_SQRT_2*std::pow(secondVal, 5./2.) ) 
                */
                ;
        }
    }

    template<class CP>
    // cheaper; less terms retained; yet the cost lies in the saddle point calc
    Probability SaddlePointLossModel<CP>::probOverLossPortfCond1stOrder(
        const std::vector<Real>& invUncondPs,
        Real loss, 
        const std::vector<Real>& mktFactor) const 
    {
        if (loss <= QL_EPSILON) return 1.;
        const Size nNames = remainingNotionals_.size();

        Real relativeLoss = loss / remainingNotional_;
        if(relativeLoss >= 1.-QL_EPSILON) return 0.;

        // only true for constant recovery models......?
        Real averageRecovery_ = 0.;
        for(Size iName=0; iName < nNames; iName++)
            averageRecovery_ += 
            copula_->conditionalRecoveryInvP(invUncondPs[iName], iName, 
            mktFactor);  
        averageRecovery_ = averageRecovery_ / nNames;

        Real maxAttLossFract = 1.-averageRecovery_;
        if(relativeLoss > maxAttLossFract) return 0.;

        Real saddlePt = findSaddle(invUncondPs,
            relativeLoss, mktFactor);

        boost::tuples::tuple<Real, Real> cumulants = 
            CumGen02DerivCond(invUncondPs,
                saddlePt, mktFactor);
        Real baseVal = cumulants.get<0>();
        Real secondVal = cumulants.get<1>();

        Real saddleTo2 = saddlePt * saddlePt;

        if(saddlePt > 0.) { // <-> (loss > condEL)
            Real exponent = baseVal - relativeLoss * saddlePt + 
                .5 * saddleTo2 * secondVal;
            if( std::abs(exponent) > 700.) return 0.;
            return 
                // dangerous exponential; fix me
                std::exp(exponent)
                /*  std::exp(baseVal - relativeLoss * saddlePt 
                    + .5 * saddleTo2 * secondVal)*/
                * CumulativeNormalDistribution()(-std::abs(saddlePt)*
                    std::sqrt(/*saddleTo2 **/secondVal));
        }else if(saddlePt==0.){// <-> (loss == condEL)
            return .5;
        }else {// <->(loss < condEL)
            Real exponent = baseVal - relativeLoss * saddlePt + 
                .5 * saddleTo2 * secondVal;
            if( std::abs(exponent) > 700.) return 0.;

            return 
                1.-
               /* std::exp(baseVal - relativeLoss * saddlePt 
               + .5 * saddleTo2 * secondVal)*/
                std::exp(exponent)
                * CumulativeNormalDistribution()(-std::abs(saddlePt)*
                    std::sqrt(/*saddleTo2 **/secondVal));
        }
    }


    /*!   NOTICE THIS IS ON THE TOTAL PORTFOLIO ---- UNTRANCHED
    Probability density of having losses in the portfolio due to default 
        events equal to a given value on a given date conditional to the w
        latent model factor.
        Based on the integrals of the expected shortfall. See......refernce.
    */
    template<class CP>
    Probability SaddlePointLossModel<CP>::probDensityCond(
        const std::vector<Real>& invUncondPs,
        Real loss,
        const std::vector<Real>& mktFactor) const 
    {
        if (loss <= QL_EPSILON) return 0.;

        Real relativeLoss = loss / remainingNotional_;
        Real saddlePt = findSaddle(invUncondPs,
            relativeLoss, mktFactor);

        boost::tuples::tuple<Real, Real, Real, Real> cumulants = 
            CumGen0234DerivCond(invUncondPs,
            saddlePt, mktFactor);
        /// access them directly rather than through this copy
        Real K0Saddle = cumulants.get<0>();
        Real K2Saddle = cumulants.get<1>();
        Real K3Saddle = cumulants.get<2>();
        Real K4Saddle = cumulants.get<3>();
        /* see, for instance R.Martin "he saddle point method and portfolio 
        optionalities." in Risk December 2006 p.93 */
        Real cum2DerCond = CumGen2ndDerivativeCond(invUncondPs,
            saddlePt, mktFactor);
        //\todo the exponentials below are dangerous and agressive, tame them.
        return 
            (
            1.
            + K4Saddle
                /(8.*std::pow(K2Saddle, 2.))
            - 5.*std::pow(K3Saddle,2.)
                /(24.*std::pow(K2Saddle, 3.))
            ) * std::exp(K0Saddle - saddlePt * relativeLoss)
             / (std::sqrt(2. * M_PI * K2Saddle));
    }

    /*    NOTICE THIS IS ON THE TOTAL PORTFOLIO ---- UNTRANCHED..
        Sensitivities of the individual names to a given portfolio loss value 
        due to defaults. It returns ratios to the total structure notional, 
        which aggregated add up to the requested loss value.

    see equation 8 in 'VAR: who contributes and how much?' by R.Martin, 
    K.Thompson, and C. Browne in Risk Magazine, August 2001
    @param loss Loss amount level at which we want to request the sensitivity. 
    Equivalent to a percentile.
    */
    template<class CP>
    Disposable<std::vector<Real> > SaddlePointLossModel<CP>::splitLossCond(
        const std::vector<Real>& invUncondProbs,
        Real loss, 
        std::vector<Real> mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        std::vector<Real> condContrib(nNames, 0.);
        if (loss <= QL_EPSILON) return condContrib;

        Real saddlePt = findSaddle(invUncondProbs, loss / remainingNotional_, 
            mktFactor);

        for(Size iName=0; iName<nNames; iName++) {
            Probability pBuffer = 
                copula_->conditionalDefaultProbabilityInvP(
                    invUncondProbs[iName], iName, mktFactor);
            Real lossInDef = remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName], 
                    iName, mktFactor));
            Real midFactor = pBuffer * 
                std::exp(lossInDef * saddlePt/ remainingNotional_);
            Real denominator = 1.-pBuffer + midFactor;

            condContrib[iName] = lossInDef * midFactor / denominator; 
        }
        return condContrib;
    }

    template<class CP>
    Real SaddlePointLossModel<CP>::conditionalExpectedLoss(
        const std::vector<Real>& invUncondProbs,
        const std::vector<Real>& mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        Real eloss = 0.;
        /// USE STL.....-------------------
        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = copula_->conditionalDefaultProbabilityInvP(
                invUncondProbs[iName], iName, mktFactor);
            eloss += pBuffer * remainingNotionals_[iName] *
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName], 
                    iName, mktFactor));
        }
        return eloss;
    }

    template<class CP>
    Real SaddlePointLossModel<CP>::conditionalExpectedTrancheLoss(
        const std::vector<Real>& invUncondProbs,
        const std::vector<Real>& mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        Real eloss = 0.;
        /// USE STL.....-------------------
        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = copula_->conditionalDefaultProbabilityInvP(
                invUncondProbs[iName], iName, mktFactor);
            eloss += 
                pBuffer * remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName], 
                iName, mktFactor));
        }
        return std::min(
            std::max(eloss - attachRatio_ * remainingNotional_, 0.), 
                (detachRatio_ - attachRatio_) * remainingNotional_);
    }

    template<class CP>
    Disposable<std::vector<Real> > 
        SaddlePointLossModel<CP>::expectedShortfallSplitCond(
            const std::vector<Real>& invUncondProbs,
            Real lossPerc, const std::vector<Real>& mktFactor) const 
    {
        const Size nNames = remainingNotionals_.size();
        std::vector<Real> lgds;
        for(Size iName=0; iName<nNames; iName++)
            lgds.push_back(remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName],
                    iName, mktFactor))); 
        std::vector<Real> vola(nNames, 0.), mu(nNames, 0.);
        Real volaTot = 0., muTot = 0.;
        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = copula_->conditionalDefaultProbabilityInvP(
                invUncondProbs[iName], iName, mktFactor);
            mu[iName] = lgds[iName] * pBuffer / remainingNotionals_[iName];
            muTot += lgds[iName] * pBuffer;
            vola[iName] = lgds[iName] * lgds[iName] * pBuffer * (1.-pBuffer) 
                / remainingNotionals_[iName];
            volaTot += lgds[iName] * lgds[iName] * pBuffer * (1.-pBuffer) ;
        }
        std::for_each(vola.begin(), vola.end(), 
            std::bind1st(std::divides<Real>(), volaTot));
        for(Size iName=0; iName < nNames; iName++)
            vola[iName] = vola[iName] / volaTot;

        std::vector<Real> esfPartition(nNames, 0.);
        for(Size iName=0; iName < nNames; iName++) {
            Real uEdisp = (lossPerc-muTot)/std::sqrt(volaTot);
            esfPartition[iName] = mu[iName]
                * CumulativeNormalDistribution()(uEdisp) // static call?
                + vola[iName] * NormalDistribution()(uEdisp);
        }
        return esfPartition;
    }

    template<class CP>
    Real SaddlePointLossModel<CP>::expectedShortfallTrancheCond(
        const std::vector<Real>& invUncondProbs,
        Real lossPerc, // value 
        Probability percentile,
        const std::vector<Real>& mktFactor) const 
    {
        /* TO DO: this is too crude, a general expresion valid for all 
        situations is possible (with no extra cost as long as the loss limits 
        are checked).
        */
        //tranche correction term:
        Real correctionTerm = 0.;
        Real probLOver = probOverLossPortfCond(invUncondProbs,
            basket_->detachmentAmount(), mktFactor);
        if(basket_->attachmentAmount() > QL_EPSILON) {
            if(lossPerc < basket_->attachmentAmount()) {
                correctionTerm = ( (basket_->detachmentAmount() 
                    - 2.*basket_->attachmentAmount())*
                        probOverLossPortfCond(invUncondProbs, lossPerc, 
                            mktFactor)
                    + basket_->attachmentAmount() * probLOver )/(1.-percentile);
            }else{
                correctionTerm = ( (percentile-1)*basket_->attachmentAmount()
                    + basket_->detachmentAmount() * probLOver
                    )/(1.-percentile);
            }
        }

        return expectedShortfallFullPortfolioCond(invUncondProbs, 
            std::max(lossPerc, basket_->attachmentAmount()), mktFactor)
            + expectedShortfallFullPortfolioCond(invUncondProbs, 
                basket_->detachmentAmount(), mktFactor)
            - correctionTerm;
    }

    template<class CP>
    Real SaddlePointLossModel<CP>::expectedShortfallFullPortfolioCond(
        const std::vector<Real>& invUncondProbs,
        Real lossPerc, // value 
        const std::vector<Real>& mktFactor) const 
    {
        /* This version is based on: Martin 2006 paper and on the expression 
        in 'SaddlePoint approximation of expected shortfall for transformed 
        means' S.A. Broda and M.S.Paolella , Amsterdam School of Economics 
        discussion paper, available online.
        */
        Real lossPercRatio = lossPerc  /remainingNotional_;
        Real elCond = 0.;
        const Size nNames = remainingNotionals_.size();

        /// use stl algorthms
        for(Size iName=0; iName < nNames; iName++) {
            Probability pBuffer = copula_->conditionalDefaultProbabilityInvP(
                invUncondProbs[iName], iName, mktFactor);
            elCond += pBuffer * remainingNotionals_[iName] * 
                (1.-copula_->conditionalRecoveryInvP(invUncondProbs[iName],
                    iName, mktFactor));
        }
        Real saddlePt = findSaddle(invUncondProbs, lossPercRatio, mktFactor);

        // Martin 2006:
        return 
            elCond * probOverLossPortfCond(invUncondProbs, lossPerc, mktFactor)
              + (lossPerc - elCond) * probDensityCond(invUncondProbs, lossPerc,
                    mktFactor) /saddlePt;

        // calling the EL tranche
        // return elCond - expectedEquityLossCond(d, lossPercRatio, mktFactor);

        /*
        // Broda and Paolella:
        Real elCondRatio = elCond / remainingNotional_;

        boost::tuples::tuple<Real, Real, Real, Real> cumulants = 
            CumGen0234DerivCond(uncondProbs, 
                saddlePt, mktFactor);
        Real K0Saddle = cumulants.get<0>();///USE THEM DIRECTLY
        Real K2Saddle = cumulants.get<1>();

        Real wq = std::sqrt(2. * saddlePt * lossPercRatio - 2. * K0Saddle);
        //std::sqrt(-2. * saddlePt * lossPerc + 2. * K0Saddle);????
        Real factor = 1.;
        if(saddlePt<0.) {
            wq = -wq;
            factor = -1.;
        }

        Real numNames = static_cast<Real>(nNames);

        Real term1 = CumulativeNormalDistribution()(wq)// * std::sqrt(numNames)
            * elCond ;
        Real term2 = .5 * M_2_SQRTPI * M_SQRT1_2 * (1./std::sqrt(numNames))
            * exp(-wq*wq * numNames/2.)*(elCond/wq - 
                lossPerc/(saddlePt * std::sqrt(K2Saddle)));
        return term1 + term2;
        */
    }

    template<class CP>
    Real SaddlePointLossModel<CP>::expectedShortfall(const Date&d, 
        Probability percProb) const 
    {
        // assuming I have the tranched one.
        Real lossPerc = percentile(d, percProb);

        // check the trivial case when the loss is over the detachment limit 
        //   to avoid computation:
        Real trancheAmount = basket_->trancheNotional() * 
            (detachRatio_-attachRatio_);
        //assumed the amount includes the realized loses
        if(lossPerc >= trancheAmount) return trancheAmount;
        //SHOULD CHECK NOW THE OPPOSITE LIMIT ("zero" losses)....
        std::vector<Real> invUncondProbs = 
            basket_->remainingProbabilities(d);
        for(Size i=0; i<invUncondProbs.size(); i++)
            invUncondProbs[i] = 
                copula_->inverseCumulativeY(invUncondProbs[i], i);

        // Integrate with the tranche or the portfolio according to the limits.
        return copula_->integratedExpectedValue(
            boost::function<Real (const std::vector<Real>& v1)>(
                boost::bind(
                  &SaddlePointLossModel<CP>::expectedShortfallFullPortfolioCond,
                  this,
                  boost::cref(invUncondProbs),
                  lossPerc,
                  _1)
                )
            ) / (1.-percProb);

    /* test:?
        return std::inner_product(integrESFPartition.begin(), 
        integrESFPartition.end(), remainingNotionals_.begin(), 0.);
    */        

    }



}

#endif