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
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
//! Economic capital for a loan portfolio.  
//! Based on [my paper](https://github.com/phillyfan1138/CreditRiskExtensions/releases/download/0.1.0/main.pdf)
//! on credit economic capital.
//!

use num_complex::Complex;
use rayon::prelude::*;
use serde_derive::Deserialize;
mod vec_to_mat;

/// Struct representing loan attributes
#[derive(Debug, Deserialize)]
pub struct Loan {
    /// Balance for the loan (in dollars)
    pub balance: f64,
    /// Annualized probability of default.
    /// Can be point in time or through the
    /// cycle.
    pub pd: f64,
    /// Expected value of the loss given
    /// default for the loan.  A positive
    /// number.
    pub lgd: f64,
    /// Vector of weights describing the
    /// exposure of this loan to each
    /// systemic variable.
    pub weight: Vec<f64>,
    #[serde(default = "default_zero")]
    /// Amount of liquidity exposure as a
    /// percent of the balance.  A positive
    /// number.
    pub r: f64,
    #[serde(default = "default_zero")]
    /// Variance of the loss given
    /// default for the loan.
    pub lgd_variance: f64,
    #[serde(default = "default_one")]
    /// The number of loans that have these
    /// features.  Grouping loans into
    /// single Loan structs can vastly
    /// improve computation time.
    pub num: f64,
}

fn default_one() -> f64 {
    1.0
}
fn default_zero() -> f64 {
    0.0
}

/// Returns increment of expected loss for a given loan.
/// A typical use case would have this called multiple
/// times for each loan; once for each weight element
/// in the weight vector of the Loan struct.
///
/// # Arguments
///
/// * `loan` - An instance of the [Loan](struct.Loan.html) struct
/// * `w` - A single element from the weight
/// vector in the Loan struct.
fn get_el_from_loan(loan: &Loan, w: f64) -> f64 {
    -loan.lgd * loan.balance * w * loan.pd * loan.num
}
/// Returns increment of variance for a given loan.
/// A typical use case would have this called multiple
/// times for each loan; once for each weight element
/// in the weight vector of the Loan struct.
///
/// # Arguments
///
/// * `loan` - An instance of the [Loan](struct.Loan.html) struct
/// * `w` - A single element from the weight
/// vector in the Loan struct.
fn get_var_from_loan(loan: &Loan, w: f64) -> f64 {
    (1.0 + loan.lgd_variance) * (loan.lgd * loan.balance).powi(2) * w * loan.pd * loan.num
}
/// Returns incremental "lambda" for a given loan
///
/// # Arguments
///
/// * `loan` - An instance of the [Loan](struct.Loan.html) struct
fn get_lambda_from_loan(loan: &Loan) -> f64 {
    loan.balance * loan.r * loan.num
}
/// Returns risk contribution for a given loan.  This
/// function is used by
/// [experiment_risk_contribution](struct.EconomicCapitalAttributes.html#method.experiment_risk_contribution)
/// but can also be used on its own.  
///
/// # Arguments
///
/// * `loan` - An instance of the [Loan](struct.Loan.html) struct
/// * `el_vec` - The portfolio vector of expected
/// loss.  Has the same size as the weight vector
/// in the Loan struct.
/// * `el_sys` - The vector of expected values for
/// the systemic random variables.  This is
/// typically a vector of ones.
/// * `var_vec` - The portfolio vector of
/// variance.  Has the same size as the weight
/// vector in the Loan struct.
/// * `var_sys` - The vector of variances for the
/// systemic random variables.
/// * `lambda0` - Base loss (in dollars) from a
/// liquidity event.  A positive number.
/// * `lambda` - Sum of r*balance over each loan
/// in the portfolio.
/// * `q` - Probability of liquidity event (scaled
/// by the total portfolio loss).
/// * `c` - Scalar for multiplying the covariance
/// for the risk contribution when using the
/// variance risk measure.  Typically
/// (rho(X)-E\[X\])/sqrt(Var(X)) where rho is the
/// value of the portfolio risk measure (eg, VaR).
pub fn risk_contribution(
    loan: &Loan,
    el_vec: &[f64],
    el_sys: &[f64],
    var_vec: &[f64],
    var_sys: &[f64],
    lambda0: f64,
    lambda: f64,
    q: f64,
    c: f64,
) -> f64 {
    let el_scalar_incremental = 1.0 + q * lambda0;
    let el_scalar_total = q * get_lambda_from_loan(loan);
    let expectation_total = portfolio_expectation(el_vec, el_sys);
    let variance_total = portfolio_variance(el_vec, el_sys, var_vec, var_sys);

    let standard_deviation =
        variance_liquidity(lambda + lambda0, q, expectation_total, variance_total).sqrt();

    let var_scalar_incremental = el_scalar_incremental.powi(2);

    let var_scalar_total = el_scalar_total * (2.0 * el_scalar_incremental + q * lambda);
    let var_el_total = el_scalar_total * (2.0 * lambda0 + lambda);
    let expectation_incremental = el_sys
        .iter()
        .zip(&loan.weight)
        .map(|(e_s, &w)| get_el_from_loan(loan, w) * e_s)
        .sum::<f64>();

    let variance_incremental = el_sys
        .iter()
        .zip(&loan.weight)
        .map(|(el_s, &w)| get_var_from_loan(loan, w) * el_s)
        .sum::<f64>()
        + var_sys
            .iter()
            .zip(&loan.weight)
            .zip(el_vec)
            .map(|((v_s, &w), e_v)| e_v * v_s * get_el_from_loan(loan, w))
            .sum::<f64>();

    el_scalar_incremental * expectation_incremental
        + el_scalar_total * expectation_total
        + c * (var_scalar_incremental * variance_incremental + var_scalar_total * variance_total
            - expectation_incremental * q * lambda0.powi(2)
            - expectation_total * var_el_total)
            / standard_deviation
}
/// Returns the variance of a portfolio with liquidity risk.
///
/// # Arguments
///
/// * `lambda` - Sum of lambda0 (base loss in liquidity event)
/// and the lambda element from the [Loan](struct.Loan.html) struct.
/// * `q` - Probability of liquidity event scaled
/// by the total portfolio loss.
/// * `expectation` - Base expectation for the portfolio
/// without liquidity risk.  Can be computed using the
/// [get_portfolio_expectation](struct.EconomicCapitalAttributes.html#method.get_portfolio_expectation)
/// method.
/// * `variance` - Base variance for the portfolio
/// without liquidity risk.  Can be computed using the
/// [get_portfolio_variance](struct.EconomicCapitalAttributes.html#method.get_portfolio_variance)
/// method.
///
/// # Examples
/// ```
/// extern crate loan_ec;
/// # fn main(){
/// let lambda=1.0;
/// let q=0.01;
/// let expectation=500.0;
/// let variance= 5000.0;
/// let liq_var=loan_ec::variance_liquidity(lambda, q, expectation, variance);
/// # }
/// ```
pub fn variance_liquidity(lambda: f64, q: f64, expectation: f64, variance: f64) -> f64 {
    variance * (1.0 + q * lambda).powi(2) - expectation * q * lambda.powi(2)
}
/// Returns the expectation of a portfolio with liquidity risk
///
/// # Arguments
///
/// * `lambda` - Sum of lambda0 (base loss in liquidity event)
/// and the lambda element from the [Loan](struct.Loan.html) struct.
/// * `q` - Probability of liquidity event (scaled
/// by the total portfolio loss).
/// * `expectation` - Base expectation for the portfolio
/// without liquidity risk.  Can be computed using the
/// [get_portfolio_expectation](struct.EconomicCapitalAttributes.html#method.get_portfolio_expectation)
/// method.
///
/// # Examples
/// ```
/// extern crate loan_ec;
/// # fn main(){
/// let lambda=1.0;
/// let q=0.01;
/// let expectation=500.0;
/// let liq_exp=loan_ec::expectation_liquidity(lambda, q, expectation);
/// # }
/// ```
pub fn expectation_liquidity(lambda: f64, q: f64, expectation: f64) -> f64 {
    expectation * (1.0 + q * lambda)
}

/// Returns a function incorporating liquidity risk to the characteristic
/// function.  This function makes lambda negative: the probability
/// of lambda occurring is -qX since X is negative.
///
/// # Arguments
///
/// * `lambda` - Sum of lambda0 (base loss in liquidity event)
/// and the lambda element from the [Loan](struct.Loan.html) struct.
/// * `q` - Probability of liquidity event (scaled
/// by the total portfolio loss).
pub fn get_liquidity_risk_fn(lambda: f64, q: f64) -> impl Fn(&Complex<f64>) -> Complex<f64> {
    move |u: &Complex<f64>| u - ((-u * lambda).exp() - 1.0) * q
}

/// Returns a function which is the characteristic exponent
/// for a given loan.  The result of this function is used
/// as the third argument in
/// [process_loan](struct.EconomicCapitalAttributes.html#method.process_loan).
///
/// # Arguments
///
/// * `lgd_cf` - The characteristic function for a given
/// loan's loss given default.
/// * `liquidity_cf` - The liquidity function typically
/// instantiated from [get_liquidity_risk_fn](fn.get_liquidity_risk_fn.html).
pub fn get_log_lpm_cf<T, U>(
    lgd_cf: T,
    liquidity_cf: U,
) -> impl Fn(&Complex<f64>, &Loan) -> Complex<f64>
where
    T: Fn(&Complex<f64>, f64, f64) -> Complex<f64>,
    U: Fn(&Complex<f64>) -> Complex<f64>,
{
    move |u: &Complex<f64>, loan: &Loan| {
        (lgd_cf(&liquidity_cf(u), loan.lgd * loan.balance, loan.lgd_variance) - 1.0) * loan.pd
    }
}

/// Holds the attributes for the entire
/// portfolio.
pub struct EconomicCapitalAttributes {
    /// Holds the characteristic function for the portfolio
    /// (without multiplying by the systemic variables).
    /// The only use case for this element is when used as
    /// an input into
    /// [get_experiment_full_cf](struct.EconomicCapitalAttributes.html#method.get_experiment_full_cf).
    pub cf: Vec<Complex<f64>>,
    /// The expected value (first moment) vector of length
    /// num_w for the portfolio.
    pub el_vec: Vec<f64>,
    /// The second moment vector of length num_w for the
    /// portfolio (p_j E[l^2]w_j).
    pub var_vec: Vec<f64>,
    /// The number of systemic random variables.
    pub num_w: usize,
    /// The total liquidity risk for the portfolio.
    /// This is the sum of r*balance over the
    /// portfolio.
    pub lambda: f64,
}
/// Computes portfolio expectation given
/// the incremental vectors of portfolio
/// expectation and systemic expectation.
///
/// # Arguments
///
/// * `el_vec` - The portfolio vector of expected
/// loss.  Has the same size as the weight vector
/// in the [Loan](struct.Loan.html) struct.
/// * `el_sys` - The vector of expected values for
/// the systemic random variables.  This is
/// typically a vector of ones.  Has the same size
/// as the weight vector in the
/// [Loan](struct.Loan.html) struct.
fn portfolio_expectation(el_vec: &[f64], el_sys: &[f64]) -> f64 {
    el_vec
        .iter()
        .zip(el_sys)
        .map(|(el_v, el_s)| el_v * el_s)
        .sum::<f64>()
}
/// Computes portfolio variance given
/// the incremental vectors of portfolio
/// variance and systemic variance.
/// The assumption is that the var_sys
/// are independent.  Otherwise the var_sys
/// needs to be a matrix.
///
/// # Arguments
///
/// * `el_vec` - The portfolio vector of expected
/// loss.  Has the same size as the weight vector
/// in the [Loan](struct.Loan.html) struct.
/// * `el_sys` - The vector of expected values for
/// the systemic random variables.  This is
/// typically a vector of ones.  Has the same size
/// as the weight vector in the
/// [Loan](struct.Loan.html) struct.
/// * `var_vec` - The portfolio vector of
/// variance.  Has the same size as the weight
/// vector in the [Loan](struct.Loan.html) struct.
/// * `var_sys` - The vector of variances for the
/// systemic random variables.  Has the same size
/// as the weight vector in the
/// [Loan](struct.Loan.html) struct.
fn portfolio_variance(el_vec: &[f64], el_sys: &[f64], var_vec: &[f64], var_sys: &[f64]) -> f64 {
    let v_p: f64 = var_vec
        .iter()
        .zip(el_sys)
        .map(|(var_v, el_s)| el_s * var_v)
        .sum::<f64>();
    let e_p: f64 = el_vec
        .iter()
        .zip(var_sys)
        .map(|(el_v, var_s)| el_v.powi(2) * var_s)
        .sum::<f64>();
    v_p + e_p
}
/// Implements economic capital structure
impl EconomicCapitalAttributes {
    /// Creates a new (base) economic capital struct
    /// # Examples
    /// ```
    /// extern crate loan_ec;
    /// # fn main(){
    /// let num_u:usize=100;
    /// let num_w:usize=3;
    /// let ec_attributes=loan_ec::EconomicCapitalAttributes::new(num_u, num_w);
    /// # }
    /// ```
    pub fn new(num_u: usize, num_w: usize) -> Self {
        EconomicCapitalAttributes {
            cf: vec![Complex::new(0.0, 0.0); num_u * num_w],
            el_vec: vec![0.0; num_w],
            var_vec: vec![0.0; num_w],
            num_w,
            lambda: 0.0, // This is sum of r_j*balance_j
        }
    }
    /// Adds a new loan to the portfolio.
    /// Mutates el_vec, var_vec, cf, and lambda.
    ///
    /// # Arguments
    ///
    /// * `loan` - An instance of the [Loan](struct.Loan.html) struct.
    /// * `u_domain` - The vector of complex values
    /// provided to the characteristic function.  Is
    /// typically generated by the
    /// [fang_oost](https://github.com/phillyfan1138/fang_oost_rust)
    /// repository.  See the example.
    /// * `log_lpm_cf` - The result from calling
    /// [get_log_lpm_cf](fn.get_log_lpm_cf.html).
    ///
    /// # Examples
    /// ```
    /// extern crate loan_ec;
    /// extern crate fang_oost;
    /// extern crate rayon;
    /// extern crate num_complex;
    /// use rayon::prelude::*;
    /// use num_complex::Complex;
    /// # fn main(){
    /// let num_u:usize=100;
    /// let num_w:usize=1;
    /// let x_min=-5000.0;
    /// let x_max=0.0;
    /// let mut ec_attributes=loan_ec::EconomicCapitalAttributes::new(num_u, num_w);
    /// let loan=loan_ec::Loan{
    ///     pd: 0.05,
    ///     lgd: 0.5,
    ///     lgd_variance: 0.2,
    ///     balance: 1.0,
    ///     r: 0.0,
    ///     weight: vec![1.0],
    ///     num: 10000.0
    /// };
    /// let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
    /// let lambda=1000.0;
    /// let q=0.0001;
    /// let liquid_fn = loan_ec::get_liquidity_risk_fn(lambda, q);
    /// //the exponent is negative because l represents a loss
    /// let lgd_fn = |u: &Complex<f64>, l: f64, _lgd_v: f64| (-u * l).exp();
    /// let log_lpm_cf = loan_ec::get_log_lpm_cf(&lgd_fn, &liquid_fn);
    /// ec_attributes.process_loan(&loan, &u_domain, &log_lpm_cf);
    /// # }
    /// ```
    pub fn process_loan<U>(&mut self, loan: &Loan, u_domain: &[Complex<f64>], log_lpm_cf: U)
    where
        U: Fn(&Complex<f64>, &Loan) -> Complex<f64> + std::marker::Sync + std::marker::Send,
    {
        let vec_of_cf_u: Vec<Complex<f64>> =
            u_domain.par_iter().map(|u| log_lpm_cf(&u, loan)).collect();
        let num_w = self.num_w;
        self.cf
            .par_iter_mut()
            .enumerate()
            .for_each(|(index, elem)| {
                let row_num = vec_to_mat::get_row_from_index(index, num_w);
                let col_num = vec_to_mat::get_col_from_index(index, num_w);
                *elem += vec_of_cf_u[col_num] * loan.weight[row_num] * loan.num;
            });
        self.el_vec
            .iter_mut()
            .zip(&loan.weight)
            .for_each(|(el, &w)| {
                *el += get_el_from_loan(&loan, w);
            });
        self.var_vec
            .iter_mut()
            .zip(&loan.weight)
            .for_each(|(var, &w)| {
                *var += get_var_from_loan(&loan, w);
            });
        self.lambda += get_lambda_from_loan(&loan);
    }
    /// Performs marginal analytics for a potential loan
    /// to the portfolio.  The typical use case is for
    /// pricing a new loan that could potentially be added
    /// to the portfolio.  For a loan is already in the
    /// portfolio, the
    /// [process_loan](struct.EconomicCapitalAttributes.html#method.process_loan)
    /// method should be used.
    ///
    /// # Arguments
    ///
    /// * `loan` - An instance of the [Loan](struct.Loan.html)
    /// struct.  This is the loan to experiment on.  
    /// * `u_domain` - The vector of complex values
    /// provided to the characteristic function.  Is
    /// typically generated by the
    /// [fang_oost](https://github.com/phillyfan1138/fang_oost_rust)
    /// repository.  See the example.
    /// * `log_lpm_cf` - The result from calling
    /// [get_log_lpm_cf](fn.get_log_lpm_cf.html).
    ///
    /// # Examples
    /// ```
    /// extern crate loan_ec;
    /// extern crate fang_oost;
    /// extern crate rayon;
    /// extern crate num_complex;
    /// use rayon::prelude::*;
    /// use num_complex::Complex;
    /// # fn main(){
    /// let num_u:usize=100;
    /// let num_w:usize=1;
    /// let x_min=-5000.0;
    /// let x_max=0.0;
    /// let q=0.0001;
    /// let lambda=1000.0;
    /// let mut ec_attributes=loan_ec::EconomicCapitalAttributes::new(num_u, num_w);
    /// let loan=loan_ec::Loan{
    ///     pd: 0.05,
    ///     lgd: 0.5,
    ///     lgd_variance: 0.2,
    ///     balance: 1.0,
    ///     r: 0.0,
    ///     weight: vec![1.0],
    ///     num: 10000.0
    /// };
    /// let liquid_fn = loan_ec::get_liquidity_risk_fn(lambda, q);
    /// let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
    /// let lgd_fn = |u: &Complex<f64>, l: f64, _lgd_v: f64| (-u * l).exp();
    /// let log_lpm_cf = loan_ec::get_log_lpm_cf(&lgd_fn, &liquid_fn);
    /// ec_attributes.process_loan(&loan, &u_domain, &log_lpm_cf);
    /// let loan_ec::EconomicCapitalAttributes{
    ///     cf, el_vec, var_vec, lambda, num_w
    /// }=ec_attributes.experiment_loan(
    ///     &loan, &u_domain,
    ///     &log_lpm_cf
    /// );
    /// # }
    /// ```
    pub fn experiment_loan<U>(
        &self,
        loan: &Loan,
        u_domain: &[Complex<f64>],
        log_lpm_cf: U,
    ) -> EconomicCapitalAttributes
    where
        U: Fn(&Complex<f64>, &Loan) -> Complex<f64> + std::marker::Sync + std::marker::Send,
    {
        let vec_of_cf_u: Vec<Complex<f64>> =
            u_domain.par_iter().map(|u| log_lpm_cf(&u, loan)).collect();
        let num_w = self.num_w;
        EconomicCapitalAttributes {
            cf: self
                .cf
                .par_iter()
                .enumerate()
                .map(|(index, elem)| {
                    let row_num = vec_to_mat::get_row_from_index(index, num_w);
                    let col_num = vec_to_mat::get_col_from_index(index, num_w);
                    elem + vec_of_cf_u[col_num] * loan.weight[row_num] * loan.num
                })
                .collect::<Vec<_>>(),
            el_vec: self
                .el_vec
                .iter()
                .zip(&loan.weight)
                .map(|(el, &w)| el + get_el_from_loan(&loan, w))
                .collect::<Vec<_>>(),
            var_vec: self
                .var_vec
                .iter()
                .zip(&loan.weight)
                .map(|(var, &w)| var + get_var_from_loan(&loan, w))
                .collect::<Vec<_>>(),
            lambda: self.lambda + get_lambda_from_loan(&loan),
            num_w,
        }
    }
    /// Finds the risk contribution of a new loan.
    /// This provides a simpler API than obtaining
    /// the results from
    /// [experiment_loan](struct.EconomicCapitalAttributes.html#method.experiment_loan)
    /// and running them through the
    /// [risk_contribution](fn.risk_contribution.html)
    /// function.
    ///
    /// # Arguments
    ///
    /// * `loan` - An instance of the [Loan](struct.Loan.html) struct.  
    /// This is the loan to experiment on.
    /// * `u_domain` - The vector of complex values
    /// provided to the characteristic function.  Is
    /// typically generated by the
    /// [fang_oost](https://github.com/phillyfan1138/fang_oost_rust)
    /// repository.  See the example.
    /// * `log_lpm_cf` - The result from calling
    /// [get_log_lpm_cf](fn.get_log_lpm_cf.html).
    /// * `lambda0` - Base loss (in dollars) from a
    /// liquidity event.  A positive number.
    /// * `q` - Probability of liquidity event (scaled
    /// by the total portfolio loss).
    /// * `mgf_systemic` - Moment generating function
    /// for the systemic random variables.  Typically
    /// a function of el_sys and var_sys.
    /// * `el_sys` - The vector of expected values for
    /// the systemic random variables.  This is
    /// typically a vector of ones.
    /// * `var_sys` - The vector of variances for the
    /// systemic random variables.
    /// * `risk_measure_fn` - Function which computes
    /// the risk measure for the portfolio, e.g. VaR.
    ///
    /// # Examples
    /// ```
    /// extern crate loan_ec;
    /// extern crate fang_oost;
    /// extern crate rayon;
    /// extern crate num_complex;
    /// use rayon::prelude::*;
    /// use num_complex::Complex;
    /// extern crate cf_dist_utils;
    /// # fn main(){
    /// let num_u:usize=100;
    /// let num_w:usize=1;
    /// let x_min=-5000.0;
    /// let x_max=0.0;
    /// let mut ec_attributes=loan_ec::EconomicCapitalAttributes::new(num_u, num_w);
    /// let loan=loan_ec::Loan{
    ///     pd: 0.05,
    ///     lgd: 0.5,
    ///     lgd_variance: 0.2,
    ///     balance: 1.0,
    ///     r: 0.0,
    ///     weight: vec![1.0],
    ///     num: 10000.0
    /// };
    /// let lambda0=1000.0;
    /// let q=0.0001;
    /// let liquid_fn = loan_ec::get_liquidity_risk_fn(lambda0, q);
    /// let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
    /// let lgd_fn = |u: &Complex<f64>, l: f64, _lgd_v: f64| (-u * l).exp();
    /// let log_lpm_cf = loan_ec::get_log_lpm_cf(&lgd_fn, &liquid_fn);
    /// ec_attributes.process_loan(&loan, &u_domain, &log_lpm_cf);
    /// let systemic_expectation = vec![1.0];
    /// let v = vec![0.4];
    /// let quantile=0.01;
    /// let systemic_mgf=|u_weights: &[Complex<f64>]| -> Complex<f64> {
    ///     u_weights
    ///     .iter()
    ///     .zip(&v)
    ///     .map(|(u, v_inst)| -(1.0 - v_inst * u).ln() / v_inst)
    ///     .sum::<Complex<f64>>()
    ///     .exp()
    /// };
    /// let max_iterations = 100;
    /// let tolerance = 0.0001;
    /// let risk_measure_fn = |final_cf: &[Complex<f64>]| {
    ///     let cf_dist_utils::RiskMetric{value_at_risk, ..} =  cf_dist_utils::get_expected_shortfall_and_value_at_risk_discrete_cf(
    ///         quantile,
    ///         x_min,
    ///         x_max,
    ///         max_iterations,
    ///         tolerance,
    ///         final_cf,
    ///     ).unwrap();  
    ///     value_at_risk
    /// };
    /// let rc = ec_attributes.experiment_risk_contribution(
    ///     &loan,
    ///     &u_domain,
    ///     &log_lpm_cf,
    ///     lambda0,
    ///     q,
    ///     &systemic_mgf,
    ///     &systemic_expectation,
    ///     &v,
    ///     &risk_measure_fn,
    /// );
    /// # }
    pub fn experiment_risk_contribution<U, V, T>(
        &self,
        loan: &Loan,
        u_domain: &[Complex<f64>],
        log_lpm_cf: U,
        lambda0: f64,
        q: f64,
        mgf_systemic: V,
        el_sys: &[f64],
        var_sys: &[f64],
        risk_measure_fn: T,
    ) -> f64
    where
        U: Fn(&Complex<f64>, &Loan) -> Complex<f64> + std::marker::Sync + std::marker::Send,
        V: Fn(&[Complex<f64>]) -> Complex<f64> + std::marker::Sync + std::marker::Send,
        T: Fn(&[Complex<f64>]) -> f64 + std::marker::Sync + std::marker::Send,
    {
        let EconomicCapitalAttributes {
            cf,
            el_vec,
            var_vec,
            lambda,
            ..
        } = self.experiment_loan(loan, u_domain, log_lpm_cf);
        let full_cf = self.get_experiment_full_cf(&cf, &mgf_systemic);
        let risk_measure = risk_measure_fn(&full_cf);
        let port_expectation = portfolio_expectation(&el_vec, el_sys);
        let port_variance = portfolio_variance(&el_vec, el_sys, &var_vec, var_sys);
        let liq_expectation = expectation_liquidity(lambda + lambda0, q, port_expectation);
        let liq_variance = variance_liquidity(lambda + lambda0, q, port_expectation, port_variance);
        let c = (risk_measure - liq_expectation) / liq_variance.sqrt();
        risk_contribution(
            loan, &el_vec, el_sys, &var_vec, var_sys, lambda0, lambda, q, c,
        )
    }
    /// Gets the expected value of the portfolio
    /// without liquidity risk.  This should be
    /// called after processing
    /// all the loans in the portfolio.  The
    /// result of this function can be used as
    /// the third argument in
    /// [expectation_liquidity](fn.expectation_liquidity.html)
    /// to obtain the expectation with liquidity
    /// risk.  The result of this function can be
    /// used as the third argument in
    /// [variance_liquidity](fn.variance_liquidity.html)
    /// to obtain the variance with liquidity
    /// risk.
    ///
    /// # Arguments
    ///
    /// * `el_sys` - The vector of expected values for
    /// the systemic random variables.  This is
    /// typically a vector of ones.
    ///
    /// # Examples
    /// ```
    /// extern crate loan_ec;
    /// extern crate fang_oost;
    /// extern crate rayon;
    /// extern crate num_complex;
    /// use rayon::prelude::*;
    /// use num_complex::Complex;
    /// # fn main(){
    /// let num_u:usize=100;
    /// let num_w:usize=1;
    /// let x_min=-5000.0;
    /// let x_max=0.0;
    /// let expectation=vec![1.0];
    /// let lambda=1000.0;
    /// let q=0.0001;
    /// let liquid_fn = loan_ec::get_liquidity_risk_fn(lambda, q);
    /// //the exponent is negative because l represents a loss
    /// let lgd_fn = |u: &Complex<f64>, l: f64, _lgd_v: f64| (-u * l).exp();
    /// let log_lpm_cf = loan_ec::get_log_lpm_cf(&lgd_fn, &liquid_fn);
    /// let mut ec_attributes=loan_ec::EconomicCapitalAttributes::new(num_u, num_w);
    /// let loan=loan_ec::Loan{
    ///     pd: 0.05,
    ///     lgd: 0.5,
    ///     lgd_variance: 0.2,
    ///     balance: 1.0,
    ///     r: 0.0,
    ///     weight: vec![1.0],
    ///     num: 10000.0
    /// };
    /// let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
    /// ec_attributes.process_loan(&loan, &u_domain, &log_lpm_cf);
    /// let expectation_portfolio=ec_attributes.get_portfolio_expectation(&expectation);
    /// # }
    pub fn get_portfolio_expectation(&self, el_sys: &[f64]) -> f64 {
        portfolio_expectation(&self.el_vec, el_sys)
    }
    /// Gets the variance of the portfolio
    /// without liquidity risk.  This should
    /// be called after processing
    /// all the loans in the portfolio.
    /// The result of this function can be
    /// used as the fourth argument in
    /// [variance_liquidity](fn.variance_liquidity.html)
    /// to obtain the variance with liquidity
    /// risk.
    /// # Arguments
    ///
    /// * `el_sys` - The vector of expected values for
    /// the systemic random variables.  This is
    /// typically a vector of ones.
    /// * `var_sys` - The vector of variances for the
    /// systemic random variables.
    ///
    /// # Examples
    /// ```
    /// extern crate loan_ec;
    /// extern crate fang_oost;
    /// extern crate rayon;
    /// extern crate num_complex;
    /// use num_complex::Complex;
    /// use rayon::prelude::*;
    /// # fn main(){
    /// let num_u:usize=100;
    /// let num_w:usize=1;
    /// let x_min=-5000.0;
    /// let x_max=0.0;
    /// let systemic_expectation = vec![1.0];
    /// let v = vec![0.4];
    /// let mut ec_attributes=loan_ec::EconomicCapitalAttributes::new(num_u, num_w);
    /// let loan=loan_ec::Loan{
    ///     pd: 0.05,
    ///     lgd: 0.5,
    ///     lgd_variance: 0.2,
    ///     balance: 1.0,
    ///     r: 0.0,
    ///     weight: vec![1.0],
    ///     num: 10000.0
    /// };
    /// let lambda=1000.0;
    /// let q=0.0001;
    /// let liquid_fn = loan_ec::get_liquidity_risk_fn(lambda, q);
    /// //the exponent is negative because l represents a loss
    /// let lgd_fn = |u: &Complex<f64>, l: f64, _lgd_v: f64| (-u * l).exp();
    /// let log_lpm_cf = loan_ec::get_log_lpm_cf(&lgd_fn, &liquid_fn);
    /// let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
    /// ec_attributes.process_loan(&loan, &u_domain, &log_lpm_cf);
    /// let variance_portfolio=ec_attributes.get_portfolio_variance(&systemic_expectation, &v);
    /// # }
    pub fn get_portfolio_variance(&self, el_sys: &[f64], var_sys: &[f64]) -> f64 {
        portfolio_variance(&self.el_vec, el_sys, &self.var_vec, var_sys)
    }
    /// Merges the loan exponents with the
    /// systemic variables moment generating
    /// function to obtain the discrete
    /// characteristic function for the
    /// portfolio.  This should be called
    /// after obtaining the cf element from
    /// an
    /// [experiment](struct.EconomicCapitalAttributes.html#method.experiment_loan).
    /// If only the risk contribution is
    /// required, consider using the
    /// [experiment_risk_contribution](struct.EconomicCapitalAttributes.html#method.experiment_risk_contribution)
    /// method instead.
    pub fn get_experiment_full_cf<U>(&self, cf: &[Complex<f64>], mgf: &U) -> Vec<Complex<f64>>
    where
        U: Fn(&[Complex<f64>]) -> Complex<f64> + std::marker::Sync + std::marker::Send,
    {
        cf.par_chunks(self.num_w).map(mgf).collect()
    }
    /// Gets the discrete characteristic function
    /// for the portfolio. This should be called
    /// after processing all the loans in the portfolio.
    ///
    /// # Arguments
    ///
    /// * `mgf_systemic` - Moment generating function
    /// for the systemic random variables.  Typically
    /// a function of el_sys and var_sys.
    ///
    /// # Examples
    /// ```
    /// extern crate loan_ec;
    /// extern crate fang_oost;
    /// extern crate rayon;
    /// extern crate num_complex;
    /// use rayon::prelude::*;
    /// use num_complex::Complex;
    /// extern crate cf_dist_utils;
    /// # fn main(){
    /// let num_u:usize=100;
    /// let num_w:usize=1;
    /// let x_min=-5000.0;
    /// let x_max=0.0;
    /// let systemic_expectation = vec![1.0];
    /// let v = vec![0.4];
    /// let lambda=1000.0;
    /// let q=0.0001;
    /// let liquid_fn = loan_ec::get_liquidity_risk_fn(lambda, q);
    /// //the exponent is negative because l represents a loss
    /// let lgd_fn = |u: &Complex<f64>, l: f64, _lgd_v: f64| (-u * l).exp();
    /// let log_lpm_cf = loan_ec::get_log_lpm_cf(&lgd_fn, &liquid_fn);
    /// let mut ec_attributes=loan_ec::EconomicCapitalAttributes::new(num_u, num_w);
    /// let systemic_mgf=|u_weights: &[Complex<f64>]| -> Complex<f64> {
    ///     u_weights
    ///     .iter()
    ///     .zip(&v)
    ///     .map(|(u, v_inst)| -(1.0 - v_inst * u).ln() / v_inst)
    ///     .sum::<Complex<f64>>()
    ///     .exp()
    /// };
    /// let loan=loan_ec::Loan{
    ///     pd: 0.05,
    ///     lgd: 0.5,
    ///     lgd_variance: 0.2,
    ///     balance: 1.0,
    ///     r: 0.0,
    ///     weight: vec![1.0],
    ///     num: 10000.0
    /// };
    /// let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
    /// ec_attributes.process_loan(&loan, &u_domain, &log_lpm_cf);
    /// let cf=ec_attributes.get_full_cf(&systemic_mgf);
    /// # }
    pub fn get_full_cf<U>(&self, mgf_systemic: &U) -> Vec<Complex<f64>>
    where
        U: Fn(&[Complex<f64>]) -> Complex<f64> + std::marker::Sync + std::marker::Send,
    {
        self.get_experiment_full_cf(&self.cf, mgf_systemic)
    }
}

#[cfg(test)]
fn gamma_mgf<'a, 'b: 'a>(variance: &'b [f64]) -> impl Fn(&[Complex<f64>]) -> Complex<f64> + 'a {
    move |u_weights: &[Complex<f64>]| -> Complex<f64> {
        u_weights
            .iter()
            .zip(variance)
            .map(|(u, v)| -(1.0 - v * u).ln() / v)
            .sum::<Complex<f64>>()
            .exp()
    }
}

#[cfg(test)]
fn test_mgf(u_weights: &[Complex<f64>]) -> Complex<f64> {
    u_weights.iter().sum::<Complex<f64>>().exp()
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::*;
    #[test]
    fn construct_hold_discrete_cf() {
        let discrete_cf = EconomicCapitalAttributes::new(256, 3);
        let cf = discrete_cf.cf;
        assert_eq!(cf.len(), 256 * 3);
        assert_eq!(cf[0], Complex::new(0.0, 0.0)); //first three should be the same "u"
        assert_eq!(cf[1], Complex::new(0.0, 0.0));
        assert_eq!(cf[2], Complex::new(0.0, 0.0));
    }
    #[test]
    fn test_process_loan() {
        let mut discrete_cf = EconomicCapitalAttributes::new(256, 3);
        let loan = Loan {
            pd: 0.05,
            lgd: 0.5,
            r: 0.0,
            balance: 1000.0,
            lgd_variance: 0.0,
            weight: vec![0.5, 0.5, 0.5],
            num: 1.0,
        };
        let log_lpm_cf = |_u: &Complex<f64>, _loan: &Loan| Complex::new(1.0, 0.0);
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(256, 0.0, 1.0).collect();
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);
        let cf = discrete_cf.cf;
        assert_eq!(cf.len(), 256 * 3);
        cf.iter().for_each(|cf_el| {
            assert_eq!(cf_el, &Complex::new(0.5 as f64, 0.0 as f64));
        });
    }
    #[test]
    fn test_process_loans_with_final() {
        let mut discrete_cf = EconomicCapitalAttributes::new(256, 3);
        let loan = Loan {
            pd: 0.05,
            lgd: 0.5,
            balance: 1000.0,
            lgd_variance: 0.0,
            r: 0.0,
            weight: vec![0.5, 0.5, 0.5],
            num: 1.0,
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(256, 0.0, 1.0).collect();
        let log_lpm_cf = |_u: &Complex<f64>, _loan: &Loan| Complex::new(1.0, 0.0);
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);
        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&test_mgf);

        assert_eq!(final_cf.len(), 256);
        final_cf.iter().for_each(|cf_el| {
            assert_eq!(cf_el, &Complex::new(1.5 as f64, 0.0 as f64).exp());
        });
    }
    #[test]
    fn test_actually_get_density() {
        let x_min = -6000.0;
        let x_max = 0.0;
        let mut discrete_cf = EconomicCapitalAttributes::new(256, 1);
        let lambda = 1000.0;
        let q = 0.0001;
        let liquid_fn = get_liquidity_risk_fn(lambda, q);

        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(256, x_min, x_max).collect();
        let lgd_fn = |u: &Complex<f64>, l: f64, _lgd_v: f64| (-u * l).exp();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan = Loan {
            pd: 0.05,
            lgd: 0.5,
            lgd_variance: 0.0, //doesnt matter for this test
            balance: 1.0,
            r: 0.0,
            weight: vec![1.0],
            num: 10000.0,
        };
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);
        let v = vec![0.3];
        let v_mgf = gamma_mgf(&v);
        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);

        assert_eq!(final_cf.len(), 256);
        let max_iterations = 100;
        let tolerance = 0.0001;
        let cf_dist_utils::RiskMetric {
            expected_shortfall,
            value_at_risk,
        } = cf_dist_utils::get_expected_shortfall_and_value_at_risk_discrete_cf(
            0.01,
            x_min,
            x_max,
            max_iterations,
            tolerance,
            &final_cf,
        )
        .unwrap();
        assert!(expected_shortfall > value_at_risk);
    }
    #[test]
    fn test_compare_expected_value() {
        let balance = 1.0;
        let pd = 0.05;
        let lgd = 0.5;
        let num_loans = 10000.0;
        let lambda = 1000.0; //loss in the event of a liquidity crisis
        let q = 0.01 / (num_loans * pd * lgd * balance);
        let expectation = -pd * lgd * balance * (1.0 + lambda * q) * num_loans;
        let x_min = (expectation - lambda) * 3.0;
        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, 1);

        let liquid_fn = get_liquidity_risk_fn(lambda, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, _lgd_v: f64| (-u * l).exp();

        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan = Loan {
            pd,
            lgd,
            balance,
            r: 0.0,
            lgd_variance: 0.0,
            weight: vec![1.0],
            num: num_loans, //homogenous
        };
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);
        let v = vec![0.3];
        let v_mgf = gamma_mgf(&v);
        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);
        assert_eq!(final_cf.len(), num_u);
        let expectation_approx =
            cf_dist_utils::get_expectation_discrete_cf(x_min, x_max, &final_cf);

        assert_abs_diff_eq!(expectation_approx, expectation, epsilon = 0.00001);
        assert_abs_diff_eq!(
            expectation_liquidity(lambda, q, discrete_cf.get_portfolio_expectation(&vec![1.0])),
            expectation,
            epsilon = 0.00001
        );
    }
    #[test]
    fn test_compare_expected_value_and_variance_no_stochastic_lgd() {
        let balance = 1.0;
        let pd = 0.05;
        let lgd = 0.5;
        let num_loans = 10000.0;
        let lambda = 1000.0; //loss in the event of a liquidity crisis
        let q = 0.01 / (num_loans * pd * lgd * balance);
        let x_min = (-num_loans * pd * lgd * balance - lambda) * 3.0;

        let v = vec![0.4, 0.3];
        //let v2=vec![0.4, 0.3];
        let systemic_expectation = vec![1.0, 1.0];
        let v_mgf = gamma_mgf(&v);

        let weight = vec![0.4, 0.6];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, _lgd_v: f64| (-u * l).exp();
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan = Loan {
            pd,
            lgd,
            r: 0.0,
            balance,
            weight,
            lgd_variance: 0.0,
            num: num_loans, //homogenous
        };
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);

        let expectation = discrete_cf.get_portfolio_expectation(&systemic_expectation);
        let variance = discrete_cf.get_portfolio_variance(&systemic_expectation, &v);
        let expectation_liquid = expectation_liquidity(lambda, q, expectation);
        let variance_liquid = variance_liquidity(lambda, q, expectation, variance);

        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);
        assert_eq!(final_cf.len(), num_u);
        let expectation_approx =
            cf_dist_utils::get_expectation_discrete_cf(x_min, x_max, &final_cf);
        let variance_approx = cf_dist_utils::get_variance_discrete_cf(x_min, x_max, &final_cf);

        assert_abs_diff_eq!(expectation_approx, expectation_liquid, epsilon = 0.00001);
        assert_abs_diff_eq!(variance_approx, variance_liquid, epsilon = 0.1);
    }
    #[test]
    fn test_compare_expected_value_and_variance_stochastic_lgd() {
        let balance = 1.0;
        let pd = 0.05;
        let lgd = 0.5;
        let num_loans = 10000.0;
        let lambda = 1000.0; //loss in the event of a liquidity crisis
        let q = 0.01 / (num_loans * pd * lgd * balance);
        let x_min = (-num_loans * pd * lgd * balance - lambda) * 3.0;
        let v = vec![0.4, 0.3];
        let systemic_expectation = vec![1.0, 1.0];
        let v_mgf = gamma_mgf(&v);
        let lgd_variance = 0.2;
        let weight = vec![0.4, 0.6];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, lgd_v: f64| {
            cf_functions::gamma::gamma_cf(&(-u * l), 1.0 / lgd_v, lgd_v)
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan = Loan {
            pd,
            lgd,
            balance,
            r: 0.0,
            lgd_variance,
            weight,
            num: num_loans, //homogenous
        };
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);

        let expectation = discrete_cf.get_portfolio_expectation(&systemic_expectation);
        let variance = discrete_cf.get_portfolio_variance(&systemic_expectation, &v);

        let expectation_liquid = expectation_liquidity(lambda, q, expectation);
        let variance_liquid = variance_liquidity(lambda, q, expectation, variance);
        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);
        assert_eq!(final_cf.len(), num_u);
        let expectation_approx =
            cf_dist_utils::get_expectation_discrete_cf(x_min, x_max, &final_cf);
        let variance_approx = cf_dist_utils::get_variance_discrete_cf(x_min, x_max, &final_cf);

        assert_abs_diff_eq!(expectation_approx, expectation_liquid, epsilon = 0.00001);
        assert_abs_diff_eq!(variance_approx, variance_liquid, epsilon = 0.1);
    }
    #[test]
    fn test_compare_expected_value_and_variance_stochastic_lgd_non_homogenous() {
        let balance1 = 1.0;
        let balance2 = 1.5;
        let pd1 = 0.05;
        let pd2 = 0.03;
        let lgd1 = 0.5;
        let lgd2 = 0.6;
        let num_loans = 5000.0;
        let lambda = 1000.0; //loss in the event of a liquidity crisis
        let q = 0.01 / (num_loans * pd1 * lgd1 * balance1 * 2.0);
        let x_min = (-num_loans * pd1 * lgd1 * balance1 * 2.0 - lambda) * 3.0;
        let v = vec![0.4, 0.3];
        //let v2=vec![0.4, 0.3];
        let systemic_expectation = vec![1.0, 1.0];
        let v_mgf = gamma_mgf(&v);
        let lgd_variance = 0.2;
        let weight1 = vec![0.4, 0.6];
        let weight2 = vec![0.3, 0.7];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, lgd_v: f64| {
            cf_functions::gamma::gamma_cf(&(-u * l), 1.0 / lgd_v, lgd_v)
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan1 = Loan {
            pd: pd1,
            lgd: lgd1,
            balance: balance1,
            r: 0.0,
            lgd_variance,
            weight: weight1,
            num: num_loans, //homogenous
        };
        let loan2 = Loan {
            pd: pd2,
            lgd: lgd2,
            balance: balance2,
            r: 0.0,
            lgd_variance,
            weight: weight2,
            num: num_loans, //homogenous
        };
        discrete_cf.process_loan(&loan1, &u_domain, &log_lpm_cf);
        discrete_cf.process_loan(&loan2, &u_domain, &log_lpm_cf);

        let expectation = discrete_cf.get_portfolio_expectation(&systemic_expectation);
        let variance = discrete_cf.get_portfolio_variance(&systemic_expectation, &v);

        let expectation_liquid = expectation_liquidity(lambda, q, expectation);
        let variance_liquid = variance_liquidity(lambda, q, expectation, variance);
        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);
        assert_eq!(final_cf.len(), num_u);
        let expectation_approx =
            cf_dist_utils::get_expectation_discrete_cf(x_min, x_max, &final_cf);
        let variance_approx = cf_dist_utils::get_variance_discrete_cf(x_min, x_max, &final_cf);

        assert_abs_diff_eq!(expectation_approx, expectation_liquid, epsilon = 0.00001);
        assert_abs_diff_eq!(variance_approx, variance_liquid, epsilon = 0.1);
    }
    #[test]
    fn test_compare_expected_value_and_variance_stochastic_lgd_non_homogenous_large_w() {
        let balance1 = 1.0;
        let balance2 = 1.5;
        let pd1 = 0.05;
        let pd2 = 0.03;
        let lgd1 = 0.5;
        let lgd2 = 0.6;
        let num_loans = 5000.0;
        let lambda = 1000.0; //loss in the event of a liquidity crisis
        let q = 0.01 / (num_loans * pd1 * lgd1 * balance1 * 2.0);
        let x_min = (-num_loans * pd1 * lgd1 * balance1 * 2.0 - lambda) * 5.0;
        let v = vec![0.4, 0.3, 4.0, 3.0];
        let systemic_expectation = vec![1.0, 1.0, 1.0, 1.0];
        let v_mgf = gamma_mgf(&v);
        let lgd_variance = 0.2;
        let weight1 = vec![0.2, 0.3, 0.3, 0.2];
        let weight2 = vec![0.3, 0.2, 0.2, 0.3];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, lgd_v: f64| {
            cf_functions::gamma::gamma_cf(&(-u * l), 1.0 / lgd_v, lgd_v)
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan1 = Loan {
            pd: pd1,
            lgd: lgd1,
            balance: balance1,
            r: 0.0,
            lgd_variance,
            weight: weight1,
            num: num_loans, //homogenous
        };
        let loan2 = Loan {
            pd: pd2,
            lgd: lgd2,
            balance: balance2,
            r: 0.0,
            lgd_variance,
            weight: weight2,
            num: num_loans, //homogenous
        };
        discrete_cf.process_loan(&loan1, &u_domain, &log_lpm_cf);
        discrete_cf.process_loan(&loan2, &u_domain, &log_lpm_cf);

        let expectation = discrete_cf.get_portfolio_expectation(&systemic_expectation);
        let variance = discrete_cf.get_portfolio_variance(&systemic_expectation, &v);

        let expectation_liquid = expectation_liquidity(lambda, q, expectation);
        let variance_liquid = variance_liquidity(lambda, q, expectation, variance);
        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);
        assert_eq!(final_cf.len(), num_u);
        let expectation_approx =
            cf_dist_utils::get_expectation_discrete_cf(x_min, x_max, &final_cf);
        let variance_approx = cf_dist_utils::get_variance_discrete_cf(x_min, x_max, &final_cf);

        assert_abs_diff_eq!(expectation_approx, expectation_liquid, epsilon = 0.00001);
        assert_abs_diff_eq!(variance_approx, variance_liquid, epsilon = 0.1);
    }
    #[test]
    fn test_basic_risk_contribution() {
        let balance = 1.0;
        let pd = 0.05;
        let lgd = 0.5;
        let num_loans = 9999.0;
        let lambda = 0.0; //loss in the event of a liquidity crisis
        let q = 0.0 / (num_loans * pd * lgd * balance);
        let x_min = (-num_loans * pd * lgd * balance - lambda) * 3.0;
        let v = vec![0.4, 0.3];
        //let v2=vec![0.4, 0.3];
        let systemic_expectation = vec![1.0, 1.0];
        let v_mgf = gamma_mgf(&v);
        let lgd_variance = 0.2;
        let weight1 = vec![0.4, 0.6];
        let weight2 = vec![0.4, 0.6];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, lgd_v: f64| {
            cf_functions::gamma::gamma_cf(&(-u * l), 1.0 / lgd_v, lgd_v)
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan = Loan {
            pd,
            lgd,
            balance,
            lgd_variance,
            weight: weight1,
            r: 0.0,
            num: num_loans, //homogenous
        };
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);

        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);
        assert_eq!(final_cf.len(), num_u);

        let new_loan = Loan {
            pd,
            lgd,
            balance,
            lgd_variance,
            weight: weight2,
            r: 0.0,
            num: 1.0,
        };

        let c = 5.0; //arbitrary
        let EconomicCapitalAttributes {
            el_vec, var_vec, ..
        } = discrete_cf.experiment_loan(&new_loan, &u_domain, &log_lpm_cf);
        let new_variance = portfolio_variance(&el_vec, &systemic_expectation, &var_vec, &v);
        let new_expectation = portfolio_expectation(&el_vec, &systemic_expectation);
        let rc = risk_contribution(
            &new_loan,
            &el_vec,
            &systemic_expectation,
            &var_vec,
            &v,
            0.0,
            0.0,
            q,
            c,
        );
        assert_abs_diff_eq!(
            rc * 10000.0,
            new_expectation + c * new_variance.sqrt(),
            epsilon = 0.1
        );
    }
    #[test]
    fn test_lambda_risk_contribution() {
        let balance = 1.0;
        let pd = 0.05;
        let lgd = 0.5;
        let num_loans = 9999.0;
        let r = 0.0;
        let lambda0 = 1000.0; //loss in the event of a liquidity crisis
        let q = 0.01 / (num_loans * pd * lgd * balance);
        let x_min = (-num_loans * pd * lgd * balance - lambda0) * 3.0;
        let v = vec![0.4, 0.3];
        //let v2=vec![0.4, 0.3];
        let systemic_expectation = vec![1.0, 1.0];
        let v_mgf = gamma_mgf(&v);
        let lgd_variance = 0.2;
        let weight1 = vec![0.4, 0.6];
        let weight2 = vec![0.4, 0.6];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda0, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, lgd_v: f64| {
            cf_functions::gamma::gamma_cf(&(-u * l), 1.0 / lgd_v, lgd_v)
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan = Loan {
            pd,
            lgd,
            balance,
            lgd_variance,
            weight: weight1,
            r,
            num: num_loans, //homogenous
        };
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);

        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);
        assert_eq!(final_cf.len(), num_u);

        let new_loan = Loan {
            pd,
            lgd,
            balance,
            lgd_variance,
            weight: weight2,
            r,
            num: 1.0,
        };

        let c = 5.0; //arbitrary
        let EconomicCapitalAttributes {
            el_vec,
            var_vec,
            lambda,
            ..
        } = discrete_cf.experiment_loan(&new_loan, &u_domain, &log_lpm_cf);
        let new_variance = portfolio_variance(&el_vec, &systemic_expectation, &var_vec, &v);
        let new_expectation = portfolio_expectation(&el_vec, &systemic_expectation);
        let liquid_exp = expectation_liquidity(lambda0, q, new_expectation);
        let liquid_var = variance_liquidity(lambda0, q, new_expectation, new_variance);
        assert_abs_diff_eq!(lambda, 0.0, epsilon = 0.00000001);
        let rc = risk_contribution(
            &new_loan,
            &el_vec,
            &systemic_expectation,
            &var_vec,
            &v,
            lambda0,
            0.0,
            q,
            c,
        );
        assert_abs_diff_eq!(
            rc * (num_loans + 1.0),
            liquid_exp + c * liquid_var.sqrt(),
            epsilon = 0.1
        );
    }
    #[test]
    fn test_lambda_qzero_risk_contribution() {
        let balance = 1.0;
        let pd = 0.05;
        let lgd = 0.5;
        let num_loans = 9999.0;
        let r = 0.2;
        let lambda0 = 1000.0; //loss in the event of a liquidity crisis
        let q = 0.0 / (num_loans * pd * lgd * balance);
        let x_min = (-num_loans * pd * lgd * balance - lambda0) * 3.0;
        let v = vec![0.4, 0.3];
        //let v2=vec![0.4, 0.3];
        let systemic_expectation = vec![1.0, 1.0];
        let v_mgf = gamma_mgf(&v);
        let lgd_variance = 0.2;
        let weight1 = vec![0.4, 0.6];
        let weight2 = vec![0.4, 0.6];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda0, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, lgd_v: f64| {
            cf_functions::gamma::gamma_cf(&(-u * l), 1.0 / lgd_v, lgd_v)
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan = Loan {
            pd,
            lgd,
            balance,
            lgd_variance,
            weight: weight1,
            r,
            num: num_loans, //homogenous
        };
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);

        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);
        assert_eq!(final_cf.len(), num_u);

        let new_loan = Loan {
            pd,
            lgd,
            balance,
            lgd_variance,
            weight: weight2,
            r,
            num: 1.0,
        };

        let c = 5.0; //arbitrary
        let EconomicCapitalAttributes {
            el_vec, var_vec, ..
        } = discrete_cf.experiment_loan(&new_loan, &u_domain, &log_lpm_cf);
        let new_variance = portfolio_variance(&el_vec, &systemic_expectation, &var_vec, &v);
        let new_expectation = portfolio_expectation(&el_vec, &systemic_expectation);
        let liquid_exp = expectation_liquidity(lambda0, q, new_expectation);
        let liquid_var = variance_liquidity(lambda0, q, new_expectation, new_variance);
        let rc = risk_contribution(
            &new_loan,
            &el_vec,
            &systemic_expectation,
            &var_vec,
            &v,
            lambda0,
            0.0,
            q,
            c,
        );
        assert_abs_diff_eq!(
            rc * (num_loans + 1.0),
            liquid_exp + c * liquid_var.sqrt(),
            epsilon = 0.1
        );
    }
    #[test]
    fn test_lambda_incremental_risk_contribution() {
        let balance = 1.0;
        let pd = 0.05;
        let lgd = 0.5;
        let num_loans = 9999.0;
        let r = 0.1;
        let lambda0 = 100.0; //loss in the event of a liquidity crisis
        let lambda = r * balance * (num_loans + 1.0);
        let q = 0.01 / (num_loans * pd * lgd * balance);
        let x_min = (-num_loans * pd * lgd * balance - lambda0 - lambda) * 3.0;
        let v = vec![0.4, 0.3];
        //let v2=vec![0.4, 0.3];
        let systemic_expectation = vec![1.0, 1.0];
        let v_mgf = gamma_mgf(&v);
        let lgd_variance = 0.2;
        let weight1 = vec![0.4, 0.6];
        let weight2 = vec![0.4, 0.6];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda0 + lambda, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, lgd_v: f64| {
            cf_functions::gamma::gamma_cf(&(-u * l), 1.0 / lgd_v, lgd_v)
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan = Loan {
            pd,
            lgd,
            balance,
            lgd_variance,
            weight: weight1,
            r,
            num: num_loans, //homogenous
        };
        discrete_cf.process_loan(&loan, &u_domain, &log_lpm_cf);

        let final_cf: Vec<Complex<f64>> = discrete_cf.get_full_cf(&v_mgf);
        assert_eq!(final_cf.len(), num_u);

        let new_loan = Loan {
            pd,
            lgd,
            balance,
            lgd_variance,
            weight: weight2,
            r,
            num: 1.0,
        };

        let c = 5.0; //arbitrary
        let EconomicCapitalAttributes {
            el_vec,
            var_vec,
            lambda: lambda_new,
            ..
        } = discrete_cf.experiment_loan(&new_loan, &u_domain, &log_lpm_cf);
        let new_variance = portfolio_variance(&el_vec, &systemic_expectation, &var_vec, &v);
        let new_expectation = portfolio_expectation(&el_vec, &systemic_expectation);
        let liquid_exp = expectation_liquidity(lambda + lambda0, q, new_expectation);
        let liquid_var = variance_liquidity(lambda + lambda0, q, new_expectation, new_variance);

        assert_abs_diff_eq!(lambda, lambda_new, epsilon = 0.0000001);

        let rc = risk_contribution(
            &new_loan,
            &el_vec,
            &systemic_expectation,
            &var_vec,
            &v,
            lambda0,
            lambda,
            q,
            c,
        );
        assert_abs_diff_eq!(
            rc * (num_loans + 1.0),
            liquid_exp + c * liquid_var.sqrt(),
            epsilon = 0.1
        );
    }
    #[test]
    fn test_lambda_incremental_risk_contribution_non_homogenous() {
        let balance1 = 1.0;
        let balance2 = 2.0;
        let pd1 = 0.05;
        let pd2 = 0.03;
        let lgd1 = 0.5;
        let lgd2 = 0.4;
        let num_loans1 = 6000.0;
        let num_loans2 = 4000.0;
        let r1 = 0.1;
        let r2 = 0.2;
        let lambda0 = 100.0; //loss in the event of a liquidity crisis
        let lambda = r1 * balance1 * num_loans1 + r2 * balance2 * num_loans2;
        let q = 0.01 / (num_loans1 * pd1 * lgd1 * balance1 + num_loans2 * pd2 * lgd2 * balance2);
        let x_min = (-num_loans1 * pd1 * lgd1 * balance1
            - num_loans2 * pd2 * lgd2 * balance2
            - lambda0
            - lambda)
            * 3.0;
        let v = vec![0.4, 0.3];
        let systemic_expectation = vec![1.0, 1.0];
        let lgd_variance = 0.2;
        let weight1_1 = vec![0.4, 0.6];
        let weight2_1 = vec![0.3, 0.7];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda0 + lambda, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, lgd_v: f64| {
            cf_functions::gamma::gamma_cf(&(-u * l), 1.0 / lgd_v, lgd_v)
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan1 = Loan {
            pd: pd1,
            lgd: lgd1,
            balance: balance1,
            lgd_variance,
            weight: weight1_1,
            r: r1,
            num: num_loans1, //homogenous
        };
        discrete_cf.process_loan(&loan1, &u_domain, &log_lpm_cf);

        let loan2 = Loan {
            pd: pd2,
            lgd: lgd2,
            balance: balance2,
            lgd_variance,
            weight: weight2_1,
            r: r2,
            num: num_loans2,
        };

        let c = 5.0; //arbitrary
        let EconomicCapitalAttributes {
            el_vec,
            var_vec,
            lambda: lambda_new,
            ..
        } = discrete_cf.experiment_loan(&loan2, &u_domain, &log_lpm_cf);
        let new_variance = portfolio_variance(&el_vec, &systemic_expectation, &var_vec, &v);
        let new_expectation = portfolio_expectation(&el_vec, &systemic_expectation);
        let liquid_exp = expectation_liquidity(lambda + lambda0, q, new_expectation);
        let liquid_var = variance_liquidity(lambda + lambda0, q, new_expectation, new_variance);

        assert_abs_diff_eq!(lambda, lambda_new, epsilon = 0.0000001);

        let rc1 = risk_contribution(
            &loan1,
            &el_vec,
            &systemic_expectation,
            &var_vec,
            &v,
            lambda0,
            lambda,
            q,
            c,
        );
        let rc2 = risk_contribution(
            &loan2,
            &el_vec,
            &systemic_expectation,
            &var_vec,
            &v,
            lambda0,
            lambda,
            q,
            c,
        );
        assert_abs_diff_eq!(rc1 + rc2, liquid_exp + c * liquid_var.sqrt(), epsilon = 0.1);
    }
    #[test]
    fn test_lambda_incremental_risk_contribution_non_homogenous_internal_function() {
        let balance1 = 1.0;
        let balance2 = 2.0;
        let pd1 = 0.05;
        let pd2 = 0.03;
        let lgd1 = 0.5;
        let lgd2 = 0.4;
        let num_loans1 = 6000.0;
        let num_loans2 = 4000.0;
        let r1 = 0.1;
        let r2 = 0.2;
        let lambda0 = 100.0; //loss in the event of a liquidity crisis
        let lambda = r1 * balance1 * num_loans1 + r2 * balance2 * num_loans2;
        let q = 0.01 / (num_loans1 * pd1 * lgd1 * balance1 + num_loans2 * pd2 * lgd2 * balance2);
        let x_min = (-num_loans1 * pd1 * lgd1 * balance1
            - num_loans2 * pd2 * lgd2 * balance2
            - lambda0
            - lambda)
            * 3.0;
        let v = vec![0.4, 0.3];
        let systemic_expectation = vec![1.0, 1.0];
        let lgd_variance = 0.2;
        let weight1_1 = vec![0.4, 0.6];
        let weight2_1 = vec![0.3, 0.7];

        let x_max = 0.0;
        let num_u: usize = 1024;
        let mut discrete_cf = EconomicCapitalAttributes::new(num_u, v.len());

        let liquid_fn = get_liquidity_risk_fn(lambda0 + lambda, q);

        //the exponent is negative because l represents a loss
        let lgd_fn = |u: &Complex<f64>, l: f64, lgd_v: f64| {
            cf_functions::gamma::gamma_cf(&(-u * l), 1.0 / lgd_v, lgd_v)
        };
        let u_domain: Vec<Complex<f64>> = fang_oost::get_u_domain(num_u, x_min, x_max).collect();
        let log_lpm_cf = get_log_lpm_cf(&lgd_fn, &liquid_fn);

        let loan1 = Loan {
            pd: pd1,
            lgd: lgd1,
            balance: balance1,
            lgd_variance,
            weight: weight1_1,
            r: r1,
            num: num_loans1, //homogenous
        };
        discrete_cf.process_loan(&loan1, &u_domain, &log_lpm_cf);
        let systemic_mgf = gamma_mgf(&v);

        let loan2 = Loan {
            pd: pd2,
            lgd: lgd2,
            balance: balance2,
            lgd_variance,
            weight: weight2_1,
            r: r2,
            num: num_loans2,
        };

        let quantile = 0.01;
        let max_iterations = 100;
        let tolerance = 0.0001;
        let risk_measure_fn = |final_cf: &[Complex<f64>]| {
            let cf_dist_utils::RiskMetric { value_at_risk, .. } =
                cf_dist_utils::get_expected_shortfall_and_value_at_risk_discrete_cf(
                    quantile,
                    x_min,
                    x_max,
                    max_iterations,
                    tolerance,
                    final_cf,
                )
                .unwrap();
            value_at_risk
        };
        let rc1 = discrete_cf.experiment_risk_contribution(
            &loan2,
            &u_domain,
            &log_lpm_cf,
            lambda0,
            q,
            &systemic_mgf,
            &systemic_expectation,
            &v,
            &risk_measure_fn,
        );

        let EconomicCapitalAttributes {
            el_vec,
            var_vec,
            lambda: lambda_new,
            cf,
            ..
        } = discrete_cf.experiment_loan(&loan2, &u_domain, &log_lpm_cf);

        let new_variance = portfolio_variance(&el_vec, &systemic_expectation, &var_vec, &v);
        let new_expectation = portfolio_expectation(&el_vec, &systemic_expectation);
        let liquid_exp = expectation_liquidity(lambda + lambda0, q, new_expectation);
        let liquid_var = variance_liquidity(lambda + lambda0, q, new_expectation, new_variance);
        let cf_d = discrete_cf.get_experiment_full_cf(&cf, &systemic_mgf);
        let cf_dist_utils::RiskMetric { value_at_risk, .. } =
            cf_dist_utils::get_expected_shortfall_and_value_at_risk_discrete_cf(
                quantile,
                x_min,
                x_max,
                max_iterations,
                tolerance,
                &cf_d,
            )
            .unwrap();
        let c = (value_at_risk - liquid_exp) / liquid_var.sqrt();
        assert_abs_diff_eq!(lambda, lambda_new, epsilon = 0.0000001);

        let rc2 = risk_contribution(
            &loan2,
            &el_vec,
            &systemic_expectation,
            &var_vec,
            &v,
            lambda0,
            lambda,
            q,
            c,
        );

        assert_abs_diff_eq!(rc2, rc1, epsilon = 0.00001);
    }
}