RdToR1.java

  1. package org.drip.function.definition;

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

  78. /**
  79.  * <i>RdToR1</i> provides the evaluation of the R<sup>d</sup> To R<sup>1</sup> objective function and its
  80.  * derivatives for a specified set of R<sup>d</sup> variates. Default implementation of the derivatives are
  81.  * for non-analytical lack box objective functions.
  82.  *
  83.  *  <br><br>
  84.  *  <ul>
  85.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li>
  86.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/NumericalAnalysisLibrary.md">Numerical Analysis Library</a></li>
  87.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/function/README.md">R<sup>d</sup> To R<sup>d</sup> Function Analysis</a></li>
  88.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/function/definition/README.md">Function Implementation Ancillary Support Objects</a></li>
  89.  *  </ul>
  90.  *
  91.  * @author Lakshmi Krishnamurthy
  92.  */

  93. public abstract class RdToR1 {
  94.     private static final int EXTREMA_SAMPLING = 10000;
  95.     private static final int QUADRATURE_SAMPLING = 10000;

  96.     protected static final int DIMENSION_NOT_FIXED = -1;

  97.     protected org.drip.numerical.differentiation.DerivativeControl _dc = null;

  98.     /**
  99.      * Validate the Input Double Array
  100.      *
  101.      * @param adblVariate The Input Double Array
  102.      *
  103.      * @return The Input Double Array consists of valid Values
  104.      */

  105.     public static final boolean ValidateInput (
  106.         final double[] adblVariate)
  107.     {
  108.         if (null == adblVariate) return false;

  109.         int iNumVariate = adblVariate.length;

  110.         if (0 == iNumVariate) return false;

  111.         for (int i = 0; i < iNumVariate; ++i) {
  112.             if (!org.drip.numerical.common.NumberUtil.IsValid (adblVariate[i])) return false;
  113.         }

  114.         return true;
  115.     }

  116.     protected RdToR1 (
  117.         final org.drip.numerical.differentiation.DerivativeControl dc)
  118.     {
  119.         if (null == (_dc = dc)) _dc = new org.drip.numerical.differentiation.DerivativeControl();
  120.     }

  121.     /**
  122.      * Retrieve the Dimension of the Input Variate
  123.      *
  124.      * @return The Dimension of the Input Variate
  125.      */

  126.     public abstract int dimension();

  127.     /**
  128.      * Evaluate for the given Input Variates
  129.      *
  130.      * @param adblVariate Array of Input Variates
  131.      *  
  132.      * @return The Calculated Value
  133.      *
  134.      * @throws java.lang.Exception Thrown if the Evaluation cannot be done
  135.      */

  136.     public abstract double evaluate (
  137.         final double[] adblVariate)
  138.         throws java.lang.Exception;

  139.     /**
  140.      * Calculate the Differential
  141.      *
  142.      * @param adblVariate Variate Array at which the derivative is to be calculated
  143.      * @param iVariateIndex Index of the Variate whose Derivative is to be computed
  144.      * @param iOrder Order of the derivative to be computed
  145.      *
  146.      * @return The Derivative
  147.      */

  148.     public org.drip.numerical.differentiation.Differential differential (
  149.         final double[] adblVariate,
  150.         final int iVariateIndex,
  151.         final int iOrder)
  152.     {
  153.         if (!org.drip.numerical.common.NumberUtil.IsValid (adblVariate) || 0 >= iOrder) return null;

  154.         double dblDerivative = 0.;
  155.         int iNumVariate = adblVariate.length;
  156.         double dblOrderedVariateInfinitesimal = 1.;
  157.         double dblVariateInfinitesimal = java.lang.Double.NaN;

  158.         if (iNumVariate <= iVariateIndex) return null;

  159.         try {
  160.             dblVariateInfinitesimal = _dc.getVariateInfinitesimal (adblVariate[iVariateIndex]);
  161.         } catch (java.lang.Exception e) {
  162.             e.printStackTrace();

  163.             return null;
  164.         }

  165.         for (int i = 0; i <= iOrder; ++i) {
  166.             if (0 != i) dblOrderedVariateInfinitesimal *= (2. * dblVariateInfinitesimal);

  167.             double[] adblVariateIncremental = new double[iNumVariate];

  168.             for (int j = 0; j < iNumVariate; ++j)
  169.                 adblVariateIncremental[j] = j == iVariateIndex ? adblVariate[j] + dblVariateInfinitesimal *
  170.                     (iOrder - 2. * i) : adblVariate[j];

  171.             try {
  172.                 dblDerivative += (i % 2 == 0 ? 1 : -1) * org.drip.numerical.common.NumberUtil.NCK (iOrder, i) *
  173.                     evaluate (adblVariateIncremental);
  174.             } catch (java.lang.Exception e) {
  175.                 e.printStackTrace();

  176.                 return null;
  177.             }
  178.         }

  179.         try {
  180.             return new org.drip.numerical.differentiation.Differential (dblOrderedVariateInfinitesimal, dblDerivative);
  181.         } catch (java.lang.Exception e) {
  182.             e.printStackTrace();
  183.         }

  184.         return null;
  185.     }

  186.     /**
  187.      * Calculate the derivative as a double
  188.      *
  189.      * @param adblVariate Variate Array at which the derivative is to be calculated
  190.      * @param iVariateIndex Index of the Variate whose Derivative is to be computed
  191.      * @param iOrder Order of the derivative to be computed
  192.      *
  193.      * @return The Derivative
  194.      *
  195.      * @throws java.lang.Exception Thrown if the Derivative cannot be calculated
  196.      */

  197.     public double derivative (
  198.         final double[] adblVariate,
  199.         final int iVariateIndex,
  200.         final int iOrder)
  201.         throws java.lang.Exception
  202.     {
  203.         return differential (adblVariate, iVariateIndex, iOrder).calcSlope (true);
  204.     }

  205.     /**
  206.      * Evaluate the Jacobian for the given Input Variates
  207.      *
  208.      * @param adblVariate Array of Input Variates
  209.      *  
  210.      * @return The Jacobian Array
  211.      */

  212.     public double[] jacobian (
  213.         final double[] adblVariate)
  214.     {
  215.         if (null == adblVariate) return null;

  216.         int iNumVariate = adblVariate.length;
  217.         double[] adblJacobian = new double[iNumVariate];

  218.         if (0 == iNumVariate) return null;

  219.         for (int i = 0; i < iNumVariate; ++i) {
  220.             try {
  221.                 adblJacobian[i] = derivative (adblVariate, i, 1);
  222.             } catch (java.lang.Exception e) {
  223.                 e.printStackTrace();

  224.                 return null;
  225.             }
  226.         }

  227.         return adblJacobian;
  228.     }

  229.     /**
  230.      * Construct an Instance of the Unit Gradient Vector at the given Input Variates
  231.      *
  232.      * @param adblVariate Array of Input Variates
  233.      *  
  234.      * @return Instance of the Unit Gradient Vector Array
  235.      */

  236.     public org.drip.function.definition.UnitVector gradient (
  237.         final double[] adblVariate)
  238.     {
  239.         return org.drip.function.definition.UnitVector.Standard (jacobian (adblVariate));
  240.     }

  241.     /**
  242.      * Evaluate The Hessian for the given Input Variates
  243.      *
  244.      * @param adblVariate Array of Input Variates
  245.      *  
  246.      * @return The Hessian Matrix
  247.      */

  248.     public double[][] hessian (
  249.         final double[] adblVariate)
  250.     {
  251.         if (null == adblVariate) return null;

  252.         final int iNumVariate = adblVariate.length;
  253.         double[][] adblHessian = new double[iNumVariate][iNumVariate];

  254.         if (0 == iNumVariate) return null;

  255.         for (int i = 0; i < iNumVariate; ++i) {
  256.             final int iVariateIndex = i;

  257.             org.drip.function.definition.RdToR1 gradientRdToR1 = new org.drip.function.definition.RdToR1
  258.                 (null) {
  259.                 @Override public int dimension()
  260.                 {
  261.                     return iNumVariate;
  262.                 }

  263.                 @Override public double evaluate (
  264.                     final double[] adblVariate)
  265.                     throws java.lang.Exception
  266.                 {
  267.                     return derivative (adblVariate, iVariateIndex, 1);
  268.                 }
  269.             };

  270.             for (int j = 0; j < iNumVariate; ++j) {
  271.                 try {
  272.                     adblHessian[i][j] = gradientRdToR1.derivative (adblVariate, j, 1);
  273.                 } catch (java.lang.Exception e) {
  274.                     e.printStackTrace();

  275.                     return null;
  276.                 }
  277.             }
  278.         }

  279.         return adblHessian;
  280.     }

  281.     /**
  282.      * Integrate over the given Input Range Using Uniform Monte-Carlo
  283.      *
  284.      * @param adblLeftEdge Array of Input Left Edge
  285.      * @param adblRightEdge Array of Input Right Edge
  286.      *  
  287.      * @return The Result of the Integration over the specified Range
  288.      *
  289.      * @throws java.lang.Exception Thrown if the Integration cannot be done
  290.      */

  291.     public double integrate (
  292.         final double[] adblLeftEdge,
  293.         final double[] adblRightEdge)
  294.         throws java.lang.Exception
  295.     {
  296.         if (!org.drip.numerical.common.NumberUtil.IsValid (adblLeftEdge) ||
  297.             !org.drip.numerical.common.NumberUtil.IsValid (adblRightEdge))
  298.             throw new java.lang.Exception ("RdToR1::integrate => Invalid Inputs");

  299.         double dblIntegrand = 0.;
  300.         int iNumVariate = adblLeftEdge.length;
  301.         double[] adblVariate = new double[iNumVariate];
  302.         double[] adblVariateWidth = new double[iNumVariate];

  303.         if (adblRightEdge.length != iNumVariate)
  304.             throw new java.lang.Exception ("RdToR1::integrate => Invalid Inputs");

  305.         for (int j = 0; j < iNumVariate; ++j)
  306.             adblVariateWidth[j] = adblRightEdge[j] - adblLeftEdge[j];

  307.         for (int i = 0; i < QUADRATURE_SAMPLING; ++i) {
  308.             for (int j = 0; j < iNumVariate; ++j)
  309.                 adblVariate[j] = adblLeftEdge[j] + java.lang.Math.random() * adblVariateWidth[j];

  310.             dblIntegrand += evaluate (adblVariate);
  311.         }

  312.         for (int j = 0; j < iNumVariate; ++j)
  313.             dblIntegrand = dblIntegrand * adblVariateWidth[j];

  314.         return dblIntegrand / QUADRATURE_SAMPLING;
  315.     }

  316.     /**
  317.      * Compute the Maximum VOP within the Variate Array Range Using Uniform Monte-Carlo
  318.      *
  319.      * @param adblVariateLeft The Range Left End Array
  320.      * @param adblVariateRight The Range Right End Array
  321.      *
  322.      * @return The Maximum VOP
  323.      */

  324.     public org.drip.function.definition.VariateOutputPair maxima (
  325.         final double[] adblVariateLeft,
  326.         final double[] adblVariateRight)
  327.     {
  328.         if (!org.drip.numerical.common.NumberUtil.IsValid (adblVariateLeft) ||
  329.             !org.drip.numerical.common.NumberUtil.IsValid (adblVariateRight))
  330.             return null;

  331.         double dblValue = java.lang.Double.NaN;
  332.         double dblMaxima = java.lang.Double.NaN;
  333.         int iNumVariate = adblVariateLeft.length;
  334.         double[] adblVariate = new double[iNumVariate];
  335.         double[] adblVariateWidth = new double[iNumVariate];
  336.         double[] adblMaximaVariate = new double[iNumVariate];

  337.         if (adblVariateRight.length != iNumVariate) return null;

  338.         for (int j = 0; j < iNumVariate; ++j)
  339.             adblVariateWidth[j] = adblVariateRight[j] - adblVariateLeft[j];

  340.         for (int i = 0; i < EXTREMA_SAMPLING; ++i) {
  341.             for (int j = 0; j < iNumVariate; ++j)
  342.                 adblVariate[j] = adblVariateLeft[j] + java.lang.Math.random() * adblVariateWidth[j];

  343.             try {
  344.                 dblValue = evaluate (adblVariate);
  345.             } catch (java.lang.Exception e) {
  346.                 e.printStackTrace();

  347.                 return null;
  348.             }

  349.             if (!org.drip.numerical.common.NumberUtil.IsValid (dblMaxima)) {
  350.                 dblMaxima = dblValue;

  351.                 for (int j = 0; j < iNumVariate; ++j)
  352.                     adblMaximaVariate[j] = adblVariate[j];
  353.             } else {
  354.                 if (dblMaxima < dblValue) {
  355.                     dblMaxima = dblValue;

  356.                     for (int j = 0; j < iNumVariate; ++j)
  357.                         adblMaximaVariate[j] = adblVariate[j];
  358.                 }
  359.             }
  360.         }

  361.         try {
  362.             return new org.drip.function.definition.VariateOutputPair (adblMaximaVariate, new double[]
  363.                 {dblMaxima});
  364.         } catch (java.lang.Exception e) {
  365.             e.printStackTrace();
  366.         }

  367.         return null;
  368.     }

  369.     /**
  370.      * Compute the Minimum VOP within the Variate Array Range Using Uniform Monte-Carlo
  371.      *
  372.      * @param adblVariateLeft The Range Left End Array
  373.      * @param adblVariateRight The Range Right End Array
  374.      *
  375.      * @return The Minimum VOP
  376.      */

  377.     public org.drip.function.definition.VariateOutputPair minima (
  378.         final double[] adblVariateLeft,
  379.         final double[] adblVariateRight)
  380.     {
  381.         if (!org.drip.numerical.common.NumberUtil.IsValid (adblVariateLeft) ||
  382.             !org.drip.numerical.common.NumberUtil.IsValid (adblVariateRight))
  383.             return null;

  384.         double dblValue = java.lang.Double.NaN;
  385.         double dblMinima = java.lang.Double.NaN;
  386.         int iNumVariate = adblVariateLeft.length;
  387.         double[] adblVariate = new double[iNumVariate];
  388.         double[] adblVariateWidth = new double[iNumVariate];
  389.         double[] adblMinimaVariate = new double[iNumVariate];

  390.         if (adblVariateRight.length != iNumVariate) return null;

  391.         for (int j = 0; j < iNumVariate; ++j)
  392.             adblVariateWidth[j] = adblVariateRight[j] - adblVariateLeft[j];

  393.         for (int i = 0; i < EXTREMA_SAMPLING; ++i) {
  394.             for (int j = 0; j < iNumVariate; ++j)
  395.                 adblVariate[j] = adblVariateLeft[j] + java.lang.Math.random() * adblVariateWidth[j];

  396.             try {
  397.                 dblValue = evaluate (adblVariate);
  398.             } catch (java.lang.Exception e) {
  399.                 e.printStackTrace();

  400.                 return null;
  401.             }

  402.             if (!org.drip.numerical.common.NumberUtil.IsValid (dblMinima)) {
  403.                 dblMinima = dblValue;

  404.                 for (int j = 0; j < iNumVariate; ++j)
  405.                     adblMinimaVariate[j] = adblVariate[j];
  406.             } else {
  407.                 if (dblMinima > dblValue) {
  408.                     dblMinima = dblValue;

  409.                     for (int j = 0; j < iNumVariate; ++j)
  410.                         adblMinimaVariate[j] = adblVariate[j];
  411.                 }
  412.             }
  413.         }

  414.         try {
  415.             return new org.drip.function.definition.VariateOutputPair (adblMinimaVariate, new double[]
  416.                 {dblMinima});
  417.         } catch (java.lang.Exception e) {
  418.             e.printStackTrace();
  419.         }

  420.         return null;
  421.     }

  422.     /**
  423.      * Compute the Modulus of the Gradient at the Specified Variate location
  424.      *
  425.      * @param adblVariate The Variate Array location
  426.      *
  427.      * @return The Modulus of the Gradient at the Specified Variate location
  428.      *
  429.      * @throws java.lang.Exception Thrown if the Inputs are Invalid
  430.      */

  431.     public double gradientModulus (
  432.         final double[] adblVariate)
  433.         throws java.lang.Exception
  434.     {
  435.         double[] adblJacobian = jacobian (adblVariate);

  436.         if (null == adblJacobian)
  437.             throw new java.lang.Exception ("RdToR1::gradientModulus => Invalid Inputs!");

  438.         double dblGradientModulus = 0.;
  439.         int iNumVariate = adblVariate.length;

  440.         for (int i = 0; i < iNumVariate; ++i)
  441.             dblGradientModulus += adblJacobian[i] * adblJacobian[i];

  442.         return dblGradientModulus;
  443.     }

  444.     /**
  445.      * Generate the Gradient Modulus Function
  446.      *
  447.      * @return The Gradient Modulus Function
  448.      */

  449.     public org.drip.function.definition.RdToR1 gradientModulusFunction()
  450.     {
  451.         org.drip.function.definition.RdToR1 gradientModulusRdToR1 = new org.drip.function.definition.RdToR1
  452.             (null) {
  453.             @Override public int dimension()
  454.             {
  455.                 return dimension();
  456.             }

  457.             @Override public double evaluate (
  458.                 final double[] adblVariate)
  459.                 throws java.lang.Exception
  460.             {
  461.                 return gradientModulus (adblVariate);
  462.             }

  463.             @Override public double[] jacobian (
  464.                 final double[] adblVariate)
  465.             {
  466.                 double[] adblParentJacobian = jacobian (adblVariate);

  467.                 double[][] adblParentHessian = hessian (adblVariate);

  468.                 if (null == adblParentJacobian || null == adblParentHessian) return null;

  469.                 int iDimension = adblParentJacobian.length;
  470.                 double[] adblGradientModulusJacobian = new double[iDimension];

  471.                 for (int k = 0; k < iDimension; ++k) {
  472.                     adblGradientModulusJacobian[k] = 0.;

  473.                     for (int i = 0; i < iDimension; ++i)
  474.                         adblGradientModulusJacobian[k] += adblParentJacobian[i] * adblParentHessian[i][k];

  475.                     adblGradientModulusJacobian[k] *= 2.;
  476.                 }

  477.                 return adblGradientModulusJacobian;
  478.             }
  479.         };

  480.         return gradientModulusRdToR1;
  481.     }
  482. }