LinearSystemSolver.java

  1. package org.drip.numerical.linearalgebra;

  2. /*
  3.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  4.  */

  5. /*!
  6.  * Copyright (C) 2020 Lakshmi Krishnamurthy
  7.  * Copyright (C) 2019 Lakshmi Krishnamurthy
  8.  * Copyright (C) 2018 Lakshmi Krishnamurthy
  9.  * Copyright (C) 2017 Lakshmi Krishnamurthy
  10.  * Copyright (C) 2016 Lakshmi Krishnamurthy
  11.  * Copyright (C) 2015 Lakshmi Krishnamurthy
  12.  * Copyright (C) 2014 Lakshmi Krishnamurthy
  13.  * Copyright (C) 2013 Lakshmi Krishnamurthy
  14.  *
  15.  *  This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics,
  16.  *      asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment
  17.  *      analytics, and portfolio construction analytics within and across fixed income, credit, commodity,
  18.  *      equity, FX, and structured products. It also includes auxiliary libraries for algorithm support,
  19.  *      numerical analysis, numerical optimization, spline builder, model validation, statistical learning,
  20.  *      and computational support.
  21.  *  
  22.  *      https://lakshmidrip.github.io/DROP/
  23.  *  
  24.  *  DROP is composed of three modules:
  25.  *  
  26.  *  - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/
  27.  *  - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/
  28.  *  - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/
  29.  *
  30.  *  DROP Product Core implements libraries for the following:
  31.  *  - Fixed Income Analytics
  32.  *  - Loan Analytics
  33.  *  - Transaction Cost Analytics
  34.  *
  35.  *  DROP Portfolio Core implements libraries for the following:
  36.  *  - Asset Allocation Analytics
  37.  *  - Asset Liability Management Analytics
  38.  *  - Capital Estimation Analytics
  39.  *  - Exposure Analytics
  40.  *  - Margin Analytics
  41.  *  - XVA Analytics
  42.  *
  43.  *  DROP Computational Core implements libraries for the following:
  44.  *  - Algorithm Support
  45.  *  - Computation Support
  46.  *  - Function Analysis
  47.  *  - Model Validation
  48.  *  - Numerical Analysis
  49.  *  - Numerical Optimizer
  50.  *  - Spline Builder
  51.  *  - Statistical Learning
  52.  *
  53.  *  Documentation for DROP is Spread Over:
  54.  *
  55.  *  - Main                     => https://lakshmidrip.github.io/DROP/
  56.  *  - Wiki                     => https://github.com/lakshmiDRIP/DROP/wiki
  57.  *  - GitHub                   => https://github.com/lakshmiDRIP/DROP
  58.  *  - Repo Layout Taxonomy     => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md
  59.  *  - Javadoc                  => https://lakshmidrip.github.io/DROP/Javadoc/index.html
  60.  *  - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal
  61.  *  - Release Versions         => https://lakshmidrip.github.io/DROP/version.html
  62.  *  - Community Credits        => https://lakshmidrip.github.io/DROP/credits.html
  63.  *  - Issues Catalog           => https://github.com/lakshmiDRIP/DROP/issues
  64.  *  - JUnit                    => https://lakshmidrip.github.io/DROP/junit/index.html
  65.  *  - Jacoco                   => https://lakshmidrip.github.io/DROP/jacoco/index.html
  66.  *
  67.  *  Licensed under the Apache License, Version 2.0 (the "License");
  68.  *      you may not use this file except in compliance with the License.
  69.  *  
  70.  *  You may obtain a copy of the License at
  71.  *      http://www.apache.org/licenses/LICENSE-2.0
  72.  *  
  73.  *  Unless required by applicable law or agreed to in writing, software
  74.  *      distributed under the License is distributed on an "AS IS" BASIS,
  75.  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  76.  *  
  77.  *  See the License for the specific language governing permissions and
  78.  *      limitations under the License.
  79.  */

  80. /**
  81.  * <i>LinearSystemSolver</i> implements the solver for a system of linear equations given by
  82.  *
  83.  *                                          A * x = B
  84.  *
  85.  * where A is the matrix, x the set of variables, and B is the result to be solved for. It exports the
  86.  * following functions:
  87.  *
  88.  * <br><br>
  89.  *  <ul>
  90.  *      <li>
  91.  *          Row Regularization and Diagonal Pivoting
  92.  *      </li>
  93.  *      <li>
  94.  *          Check for Diagonal Dominance
  95.  *      </li>
  96.  *      <li>
  97.  *          Solving the linear system using any one of the following: Gaussian Elimination, Gauss Seidel
  98.  *              reduction, or matrix inversion.
  99.  *      </li>
  100.  *  </ul>
  101.  *
  102.  * <br><br>
  103.  *  <ul>
  104.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li>
  105.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/NumericalAnalysisLibrary.md">Numerical Analysis Library</a></li>
  106.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/numerical/README.md">Numerical Quadrature, Differentiation, Eigenization, Linear Algebra, and Utilities</a></li>
  107.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/numerical/linearalgebra/README.md">Linear Algebra Matrix Transform Library</a></li>
  108.  *  </ul>
  109.  * <br><br>
  110.  *
  111.  * @author Lakshmi Krishnamurthy
  112.  */

  113. public class LinearSystemSolver {

  114.     /**
  115.      * Regularize (i.e., convert the diagonal entries of the given cell to non-zero using suitable linear
  116.      *  transformations)
  117.      *
  118.      * @param aadblA In/Out Matrix to be regularized
  119.      * @param adblSolution In/out RHS
  120.      * @param iInnerRow Matrix Cell Row that needs to be regularized
  121.      * @param iOuter Matrix Cell Column that needs to be regularized
  122.      *
  123.      * @return TRUE - Matrix has been successfully regularized
  124.      */

  125.     public static final boolean RegulariseRow (
  126.         final double[][] aadblA,
  127.         final double[] adblSolution,
  128.         final int iInnerRow,
  129.         final int iOuter)
  130.     {
  131.         double dblInnerScaler = aadblA[iInnerRow][iOuter];

  132.         if (0. != dblInnerScaler) return true;

  133.         int iSize = aadblA.length;
  134.         int iProxyRow = iSize - 1;

  135.         while (0. == aadblA[iProxyRow][iOuter] && iProxyRow >= 0) --iProxyRow;

  136.         if (iProxyRow < 0) return false;

  137.         adblSolution[iInnerRow] += adblSolution[iProxyRow];

  138.         for (int i = 0; i < iSize; ++i)
  139.             aadblA[iInnerRow][i] += aadblA[iProxyRow][i];

  140.         return 0. != aadblA[iInnerRow][iOuter];
  141.     }

  142.     /**
  143.      * Check to see if the matrix is diagonally dominant.
  144.      *
  145.      * @param aadblA Input Matrix
  146.      * @param bCheckForStrongDominance TRUE - Fail if the matrix is not strongly diagonally dominant.
  147.      *
  148.      * @return TRUE - Strongly or weakly Diagonally Dominant
  149.      */

  150.     public static final boolean IsDiagonallyDominant (
  151.         final double[][] aadblA,
  152.         final boolean bCheckForStrongDominance)
  153.     {
  154.         if (null == aadblA) return false;

  155.         int iSize = aadblA.length;

  156.         if (0 == iSize || null == aadblA[0] || iSize != aadblA[0].length) return false;

  157.         for (int i = 0; i < iSize; ++i) {
  158.             double dblAbsoluteDiagonalEntry = java.lang.Math.abs (aadblA[i][i]);

  159.             for (int j = 0; j < iSize; ++j) {
  160.                 if (i != j) {
  161.                     if ((bCheckForStrongDominance && dblAbsoluteDiagonalEntry <= java.lang.Math.abs
  162.                         (aadblA[i][j])) || (!bCheckForStrongDominance && dblAbsoluteDiagonalEntry <
  163.                             java.lang.Math.abs (aadblA[i][j])))
  164.                         return false;
  165.                 }
  166.             }
  167.         }

  168.         return true;
  169.     }

  170.     /**
  171.      * Pivots the matrix A (Refer to wikipedia to find out what "pivot a matrix" means ;))
  172.      *
  173.      * @param aadblA Input Matrix
  174.      * @param adblB Input RHS
  175.      *
  176.      * @return The pivoted input matrix and the re-jigged input RHS
  177.      */

  178.     public static final double[] Pivot (
  179.         final double[][] aadblA,
  180.         final double[] adblB)
  181.     {
  182.         if (null == aadblA || null == adblB) return null;

  183.         int iSize = aadblA.length;
  184.         double[] adblSolution = new double[iSize];

  185.         if (0 == iSize || null == aadblA[0] || iSize != aadblA[0].length || iSize != adblB.length)
  186.             return null;

  187.         for (int i = 0; i < iSize; ++i)
  188.             adblSolution[i] = adblB[i];

  189.         for (int iDiagonal = 0; iDiagonal < iSize; ++iDiagonal) {
  190.             if (!RegulariseRow (aadblA, adblSolution, iDiagonal, iDiagonal)) return null;
  191.         }

  192.         return adblSolution;
  193.     }

  194.     /**
  195.      * Solve the Linear System using Matrix Inversion from the Set of Values in the Array
  196.      *
  197.      * @param aadblAIn Input Matrix
  198.      * @param adblB The Array of Values to be calibrated to
  199.      *
  200.      * @return The Linear System Solution for the Coefficients
  201.      */

  202.     public static final org.drip.numerical.linearalgebra.LinearizationOutput SolveUsingMatrixInversion (
  203.         final double[][] aadblAIn,
  204.         final double[] adblB)
  205.     {
  206.         if (null == aadblAIn || null == adblB) return null;

  207.         int iSize = aadblAIn.length;
  208.         double[] adblSolution = new double[iSize];

  209.         if (0 == iSize || null == aadblAIn[0] || iSize != aadblAIn[0].length) return null;

  210.         if (adblB.length != iSize) return null;

  211.         double[][] aadblInv = org.drip.numerical.linearalgebra.Matrix.InvertUsingGaussianElimination (aadblAIn);

  212.         if (null == aadblInv) return null;

  213.         double[] adblProduct = org.drip.numerical.linearalgebra.Matrix.Product (aadblInv, adblB);

  214.         if (null == adblProduct || iSize != adblProduct.length) return null;

  215.         for (int i = 0; i < iSize; ++i)
  216.             adblSolution[i] = adblProduct[i];

  217.         try {
  218.             return new LinearizationOutput (adblSolution, aadblInv, "GaussianElimination");
  219.         } catch (java.lang.Exception e) {
  220.             e.printStackTrace();
  221.         }

  222.         return null;
  223.     }

  224.     /**
  225.      * Solve the Linear System using Gaussian Elimination from the Set of Values in the Array
  226.      *
  227.      * @param aadblAIn Input Matrix
  228.      * @param adblB The Array of Values to be calibrated to
  229.      *
  230.      * @return The Linear System Solution for the Coefficients
  231.      */

  232.     public static final org.drip.numerical.linearalgebra.LinearizationOutput SolveUsingGaussianElimination (
  233.         final double[][] aadblAIn,
  234.         final double[] adblB)
  235.     {
  236.         if (null == aadblAIn || null == adblB) return null;

  237.         int iSize = aadblAIn.length;
  238.         double[][] aadblA = new double[iSize][iSize];

  239.         if (0 == iSize || null == aadblAIn[0] || iSize != aadblAIn[0].length) return null;

  240.         if (adblB.length != iSize) return null;

  241.         for (int i = 0; i < iSize; ++i) {
  242.             for (int j = 0; j < iSize; ++j)
  243.                 aadblA[i][j] = aadblAIn[i][j];
  244.         }

  245.         double[] adblSolution = Pivot (aadblA, adblB);

  246.         if (null == adblSolution || adblSolution.length != iSize) return null;

  247.         for (int iEliminationDiagonalPivot = iSize - 1; iEliminationDiagonalPivot >= 0;
  248.             --iEliminationDiagonalPivot) {
  249.             for (int iRow = 0; iRow < iSize; ++iRow) {
  250.                 if (iRow == iEliminationDiagonalPivot) continue;

  251.                 if (0. == aadblA[iRow][iEliminationDiagonalPivot]) continue;

  252.                 double dblEliminationRatio = aadblA[iEliminationDiagonalPivot][iEliminationDiagonalPivot] /
  253.                     aadblA[iRow][iEliminationDiagonalPivot];
  254.                 adblSolution[iRow] = adblSolution[iRow] * dblEliminationRatio -
  255.                     adblSolution[iEliminationDiagonalPivot];

  256.                 for (int iCol = 0; iCol < iSize; ++iCol)
  257.                     aadblA[iRow][iCol] = aadblA[iRow][iCol] * dblEliminationRatio -
  258.                         aadblA[iEliminationDiagonalPivot][iCol];
  259.             }
  260.         }

  261.         for (int i = iSize - 1; i >= 0; --i) {
  262.             for (int j = iSize - 1; j > i; --j)
  263.                 adblSolution[i] -= adblSolution[j] * aadblA[i][j];

  264.             adblSolution[i] /= aadblA[i][i];
  265.         }

  266.         try {
  267.             return new LinearizationOutput (adblSolution, aadblA, "GaussianElimination");
  268.         } catch (java.lang.Exception e) {
  269.             e.printStackTrace();
  270.         }

  271.         return null;
  272.     }

  273.     /**
  274.      * Solve the Linear System using the Gauss-Seidel algorithm from the Set of Values in the Array
  275.      *
  276.      * @param aadblAIn Input Matrix
  277.      * @param adblB The Array of Values to be calibrated to
  278.      *
  279.      * @return The Linear System Solution for the Coefficients
  280.      */

  281.     public static final org.drip.numerical.linearalgebra.LinearizationOutput SolveUsingGaussSeidel (
  282.         final double[][] aadblAIn,
  283.         final double[] adblB)
  284.     {
  285.         if (null == aadblAIn || null == adblB) return null;

  286.         int NUM_SIM = 5;
  287.         int iSize = aadblAIn.length;
  288.         double[] adblSolution = new double[iSize];
  289.         double[][] aadblA = new double[iSize][iSize];

  290.         if (0 == iSize || null == aadblAIn[0] || iSize != aadblAIn[0].length || iSize != adblB.length)
  291.             return null;

  292.         for (int i = 0; i < iSize; ++i) {
  293.             for (int j = 0; j < iSize; ++j)
  294.                 aadblA[i][j] = aadblAIn[i][j];
  295.         }

  296.         double[] adblRHS = Pivot (aadblA, adblB);

  297.         if (null == adblRHS || iSize != adblRHS.length ||
  298.             !org.drip.numerical.linearalgebra.LinearSystemSolver.IsDiagonallyDominant (aadblA, true))
  299.             return null;

  300.         for (int i = 0; i < iSize; ++i)
  301.             adblSolution[i] = 0.;

  302.         for (int k = 0; k < NUM_SIM; ++k) {
  303.             for (int i = 0; i < iSize; ++i) {
  304.                 adblSolution[i] = adblRHS[i];

  305.                 for (int j = 0; j < iSize; ++j) {
  306.                     if (j != i) adblSolution[i] -= aadblA[i][j] * adblSolution[j];
  307.                 }

  308.                 adblSolution[i] /= aadblA[i][i];
  309.             }
  310.         }

  311.         try {
  312.             return new LinearizationOutput (adblSolution, aadblA, "GaussianSeidel");
  313.         } catch (java.lang.Exception e) {
  314.             e.printStackTrace();
  315.         }

  316.         return null;
  317.     }
  318. }