BasisSplineSet.java

  1. package org.drip.sample.spline;

  2. import org.drip.function.r1tor1.*;
  3. import org.drip.numerical.differentiation.WengertJacobian;
  4. import org.drip.spline.basis.*;
  5. import org.drip.spline.params.*;
  6. import org.drip.spline.segment.*;

  7. /*
  8.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  9.  */

  10. /*!
  11.  * Copyright (C) 2018 Lakshmi Krishnamurthy
  12.  * Copyright (C) 2017 Lakshmi Krishnamurthy
  13.  * Copyright (C) 2016 Lakshmi Krishnamurthy
  14.  * Copyright (C) 2015 Lakshmi Krishnamurthy
  15.  * Copyright (C) 2014 Lakshmi Krishnamurthy
  16.  * Copyright (C) 2013 Lakshmi Krishnamurthy
  17.  *
  18.  *  This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
  19.  *      libraries targeting analysts and developers
  20.  *      https://lakshmidrip.github.io/DRIP/
  21.  *  
  22.  *  DRIP is composed of four main libraries:
  23.  *  
  24.  *  - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
  25.  *  - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
  26.  *  - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
  27.  *  - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
  28.  *
  29.  *  - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
  30.  *      Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
  31.  *      Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
  32.  *      Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
  33.  *      Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
  34.  *
  35.  *  - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
  36.  *      Incorporator, Holdings Constraint, and Transaction Costs.
  37.  *
  38.  *  - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
  39.  *
  40.  *  - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
  41.  *
  42.  *  Licensed under the Apache License, Version 2.0 (the "License");
  43.  *      you may not use this file except in compliance with the License.
  44.  *  
  45.  *  You may obtain a copy of the License at
  46.  *      http://www.apache.org/licenses/LICENSE-2.0
  47.  *  
  48.  *  Unless required by applicable law or agreed to in writing, software
  49.  *      distributed under the License is distributed on an "AS IS" BASIS,
  50.  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  51.  *  
  52.  *  See the License for the specific language governing permissions and
  53.  *      limitations under the License.
  54.  */

  55. /**
  56.  * BasisSplineSet implements Samples for the Construction and the usage of various basis spline functions. It
  57.  *  demonstrates the following:
  58.  *  - Construction of segment control parameters - polynomial (regular/Bernstein) segment control,
  59.  *      exponential/hyperbolic tension segment control, Kaklis-Pandelis tension segment control, and C1
  60.  *      Hermite.
  61.  *  - Control the segment using the rational shape controller, and the appropriate Ck.
  62.  *  - Estimate the node value and the node value Jacobian with the segment, as well as at the boundaries.
  63.  *  - Calculate the segment monotonicity.

  64.  * @author Lakshmi Krishnamurthy
  65.  */

  66. public class BasisSplineSet {

  67.     /*
  68.      * Sample demonstrating the creation of the polynomial basis spline set
  69.      *
  70.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  71.      */

  72.     private static final FunctionSet CreatePolynomialSpline()
  73.         throws Exception
  74.     {
  75.         int iNumBasis = 4;

  76.         /*
  77.          * Create the basis parameter set from the number of basis functions, and construct the basis
  78.          */

  79.         PolynomialFunctionSetParams polybsbp = new PolynomialFunctionSetParams (iNumBasis);

  80.         return FunctionSetBuilder.PolynomialBasisSet (polybsbp);
  81.     }

  82.     /*
  83.      * Sample demonstrating the creation of the Bernstein polynomial basis spline set
  84.      *
  85.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  86.      */

  87.     private static final FunctionSet CreateBernsteinPolynomialSpline()
  88.         throws Exception
  89.     {
  90.         int iNumBasis = 4;

  91.         /*
  92.          * Create the basis parameter set from the number of basis functions, and construct the basis
  93.          */

  94.         PolynomialFunctionSetParams polybsbp = new PolynomialFunctionSetParams (iNumBasis);

  95.         return FunctionSetBuilder.BernsteinPolynomialBasisSet (polybsbp);
  96.     }

  97.     /*
  98.      * Sample demonstrating the creation of the exponential tension basis spline set
  99.      *
  100.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  101.      */

  102.     private static final FunctionSet CreateExponentialTensionSpline()
  103.         throws Exception
  104.     {
  105.         double dblTension = 1.;

  106.         /*
  107.          * Create the basis parameter set from the segment tension parameter, and construct the basis
  108.          */

  109.         ExponentialTensionSetParams etbsbp = new ExponentialTensionSetParams (dblTension);

  110.         return FunctionSetBuilder.ExponentialTensionBasisSet (etbsbp);
  111.     }

  112.     /*
  113.      * Sample demonstrating the creation of the hyperbolic tension basis spline set
  114.      *
  115.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  116.      */

  117.     private static final FunctionSet CreateHyperbolicTensionSpline()
  118.         throws Exception
  119.     {
  120.         double dblTension = 1.;

  121.         /*
  122.          * Create the basis parameter set from the segment tension parameter, and construct the basis
  123.          */

  124.         ExponentialTensionSetParams etbsbp = new ExponentialTensionSetParams (dblTension);

  125.         return FunctionSetBuilder.HyperbolicTensionBasisSet (etbsbp);
  126.     }

  127.     /*
  128.      * Sample demonstrating the creation of the Kaklis Pandelis basis spline set
  129.      *
  130.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  131.      */

  132.     private static final FunctionSet CreateKaklisPandelisSpline()
  133.         throws Exception
  134.     {
  135.         int iPolynomialTensionDegree = 2;

  136.         /*
  137.          * Create the basis parameter set from the segment polynomial tension control, and construct the basis
  138.          */

  139.         KaklisPandelisSetParams kpbpsp = new KaklisPandelisSetParams (iPolynomialTensionDegree);

  140.         return FunctionSetBuilder.KaklisPandelisBasisSet (kpbpsp);
  141.     }

  142.     /*
  143.      * This sample demonstrates the following:
  144.      *
  145.      *  - Construction of two segments, 1 and 2.
  146.      *  - Calibration of the segments to the left and the right node values
  147.      *  - Extraction of the segment Jacobians and segment monotonicity
  148.      *  - Estimate point value and the Jacobian
  149.      *  - Estimate the curvature penalty
  150.      *
  151.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  152.      */

  153.     private static final void TestSpline (
  154.         final FunctionSet fs,
  155.         final ResponseScalingShapeControl rssc,
  156.         final SegmentInelasticDesignControl segParams)
  157.         throws Exception
  158.     {
  159.         /*
  160.          * Construct the left and the right segments
  161.          */

  162.         LatentStateResponseModel seg1 = LatentStateResponseModel.Create (
  163.             1.0,
  164.             1.5,
  165.             fs,
  166.             rssc,
  167.             segParams
  168.         );

  169.         LatentStateResponseModel seg2 = LatentStateResponseModel.Create (
  170.             1.5,
  171.             2.0,
  172.             fs,
  173.             rssc,
  174.             segParams
  175.         );

  176.         /*
  177.          * Calibrate the left segment using the node values, and compute the segment Jacobian, monotonicity, and curvature penalty
  178.          */

  179.         WengertJacobian wj1 = seg1.jackDCoeffDEdgeParams (
  180.             25.,
  181.             0.,
  182.             20.25,
  183.             null
  184.         );

  185.         System.out.println ("\tY[" + 1.0 + "]: " + seg1.responseValue (1.));

  186.         System.out.println ("\tY[" + 1.5 + "]: " + seg1.responseValue (1.5));

  187.         System.out.println ("Segment 1 Jacobian: " + wj1.displayString());

  188.         System.out.println ("Segment 1 Head: " + seg1.jackDCoeffDEdgeInputs().displayString());

  189.         System.out.println ("Segment 1 Monotone Type: " + seg1.monotoneType());

  190.         System.out.println ("Segment 1 DPE: " + seg1.curvatureDPE());

  191.         /*
  192.          * Calibrate the right segment using the node values, and compute the segment Jacobian, monotonicity, and curvature penalty
  193.          */

  194.         WengertJacobian wj2 = seg2.jackDCoeffDEdgeParams (
  195.             seg1,
  196.             "Default",
  197.             16.,
  198.             null,
  199.             Double.NaN,
  200.             null
  201.         );

  202.         System.out.println ("\tY[" + 1.5 + "]: " + seg2.responseValue (1.5));

  203.         System.out.println ("\tY[" + 2. + "]: " + seg2.responseValue (2.));

  204.         System.out.println ("Segment 2 Jacobian: " + wj2.displayString());

  205.         System.out.println ("Segment 2 Regular Jacobian: " + seg2.jackDCoeffDEdgeInputs().displayString());

  206.         System.out.println ("Segment 2 Monotone Type: " + seg2.monotoneType());

  207.         System.out.println ("Segment 2 DPE: " + seg2.curvatureDPE());

  208.         /*
  209.          * Re-calibrate Segment #2 with a different response value
  210.          */

  211.         seg2.calibrate (
  212.             seg1,
  213.             14.,
  214.             null
  215.         );

  216.         /*
  217.          * Estimate the segment value at the given variate, and compute the corresponding Jacobian and curvature penalty
  218.          */

  219.         double dblX = 2.0;

  220.         System.out.println ("\t\tValue[" + dblX + "]: " + seg2.responseValue (dblX));

  221.         System.out.println ("\t\tValue Jacobian[" + dblX + "]: " + seg2.jackDResponseDEdgeInput (dblX, 1).displayString());

  222.         System.out.println ("\t\tSegment 2 DPE: " + seg2.curvatureDPE());
  223.     }

  224.     /*
  225.      * This sample demonstrates the following specifically for the C1 Hermite Splines, which are calibrated
  226.      *  using left and right node values, along with their derivatives:
  227.      *
  228.      *  - Construction of two segments, 1 and 2.
  229.      *  - Calibration of the segments to the left and the right node values
  230.      *  - Extraction of the segment Jacobians and segment monotonicity
  231.      *  - Estimate point value and the Jacobian
  232.      *  - Estimate the curvature penalty
  233.      *
  234.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  235.      */

  236.     private static final void TestC1HermiteSpline (
  237.         final FunctionSet fs,
  238.         final ResponseScalingShapeControl sc,
  239.         final SegmentInelasticDesignControl segParams)
  240.         throws Exception
  241.     {
  242.         /*
  243.          * Construct the left and the right segments
  244.          */

  245.         LatentStateResponseModel seg1 = LatentStateResponseModel.Create (
  246.             0.0,
  247.             1.0,
  248.             fs,
  249.             sc,
  250.             segParams
  251.         );

  252.         LatentStateResponseModel seg2 = LatentStateResponseModel.Create (
  253.             1.0,
  254.             2.0,
  255.             fs,
  256.             sc,
  257.             segParams
  258.         );

  259.         /*
  260.          * Calibrate the left segment using the node values, and compute the segment Jacobian, monotonicity, and curvature penalty
  261.          */

  262.         WengertJacobian wj1 = seg1.jackDCoeffDEdgeParams (
  263.             new double[] {0., 1.}, // Left/Right X
  264.             new double[] {1., 4.}, // Left/Right Y
  265.             new double[] {1.}, // Left Deriv
  266.             new double[] {6.}, // Right Deriv
  267.             null,
  268.             null // Constraints, Fitness Weighted Response
  269.         );

  270.         System.out.println ("\tY[" + 0.0 + "]: " + seg1.responseValue (0.0));

  271.         System.out.println ("\tY[" + 1.0 + "]: " + seg1.responseValue (1.0));

  272.         System.out.println ("Segment 1 Jacobian: " + wj1.displayString());

  273.         System.out.println ("Segment 1 Head: " + seg1.jackDCoeffDEdgeInputs().displayString());

  274.         System.out.println ("Segment 1 Monotone Type: " + seg1.monotoneType());

  275.         System.out.println ("Segment 1 DPE: " + seg1.curvatureDPE());

  276.         /*
  277.          * Calibrate the right segment using the node values, and compute the segment Jacobian, monotonicity, and curvature penalty
  278.          */

  279.         WengertJacobian wj2 = seg2.jackDCoeffDEdgeParams (
  280.             new double[] {1., 2.}, // Left/Right X
  281.             new double[] {4., 15.}, // Left/Right Y
  282.             new double[] {6.}, // Left Deriv
  283.             new double[] {17.}, // Right Deriv
  284.             null,
  285.             null // Constraints, Fitness Weighted Response
  286.         );

  287.         System.out.println ("\tY[" + 1.0 + "]: " + seg2.responseValue (1.0));

  288.         System.out.println ("\tY[" + 2.0 + "]: " + seg2.responseValue (2.0));

  289.         System.out.println ("Segment 2 Jacobian: " + wj2.displayString());

  290.         System.out.println ("Segment 2 Regular Jacobian: " + seg2.jackDCoeffDEdgeInputs().displayString());

  291.         System.out.println ("Segment 2 Monotone Type: " + seg2.monotoneType());

  292.         System.out.println ("Segment 2 DPE: " + seg2.curvatureDPE());

  293.         /*
  294.          * Re-calibrate Segment #2 with a different response value
  295.          */

  296.         seg2.calibrate (
  297.             seg1,
  298.             14.,
  299.             null
  300.         );

  301.         /*
  302.          * Estimate the segment value at the given variate, and compute the corresponding Jacobian, monotonicity, and curvature penalty
  303.          */

  304.         double dblX = 2.0;

  305.         System.out.println ("\t\tValue[" + dblX + "]: " + seg2.responseValue (dblX));

  306.         System.out.println ("\t\tValue Jacobian[" + dblX + "]: " + seg2.jackDResponseDEdgeInput (dblX, 1).displayString());

  307.         System.out.println ("\t\tSegment 2 DPE: " + seg2.curvatureDPE());
  308.     }

  309.     /*
  310.      * This sample illustrates the construction and the usage of basis splines (all types, really). It shows
  311.      *  the following:
  312.      *  - Construct a rational shape controller with the specified shape controller tension.
  313.      *  - Construct the segment inelastic parameter that is C2 (iK = 2 sets it to C2), with second order
  314.      *      curvature penalty, and without constraint.
  315.      *  - Test the polynomial basis spline.
  316.      *  - Test the Bernstein polynomial basis spline.
  317.      *  - Test the exponential tension basis spline.
  318.      *  - Test the hyperbolic tension basis spline.
  319.      *  - Test the Kaklis-Pandelis basis spline.
  320.      *  - Test the C1 Hermite basis spline.
  321.      *
  322.      *      USE WITH CARE: This sample ignores errors and does not handle exceptions.
  323.      */

  324.     private static final void BasisSplineSetSample()
  325.         throws Exception
  326.     {
  327.         /*
  328.          * Construct a rational shape controller with the shape controller tension of 1.
  329.          */

  330.         double dblShapeControllerTension = 1.;

  331.         ResponseScalingShapeControl rssc = new ResponseScalingShapeControl (
  332.             true,
  333.             new QuadraticRationalShapeControl (dblShapeControllerTension)
  334.         );

  335.         /*
  336.          * Construct the segment inelastic parameter that is C2 (iK = 2 sets it to C2), with second order
  337.          *  curvature penalty, and without constraint
  338.          */

  339.         int iK = 2;
  340.         int iCurvaturePenaltyDerivativeOrder = 2;

  341.         SegmentInelasticDesignControl segParams = SegmentInelasticDesignControl.Create (
  342.             iK,
  343.             iCurvaturePenaltyDerivativeOrder
  344.         );

  345.         /*
  346.          * Test the polynomial spline
  347.          */

  348.         System.out.println (" ---------- \n POLYNOMIAL \n ---------- \n");

  349.         TestSpline (
  350.             CreatePolynomialSpline(),
  351.             null,
  352.             segParams
  353.         );

  354.         /*
  355.          * Test the Bernstein polynomial spline
  356.          */

  357.         System.out.println (" -------------------- \n BERNSTEINPOLYNOMIAL \n -------------------- \n");

  358.         TestSpline (
  359.             CreateBernsteinPolynomialSpline(),
  360.             rssc,
  361.             segParams
  362.         );

  363.         /*
  364.          * Test the exponential tension spline
  365.          */

  366.         System.out.println ( " ----------- \n EXPONENTIAL \n ----------- \n");

  367.         TestSpline (
  368.             CreateExponentialTensionSpline(),
  369.             rssc,
  370.             segParams
  371.         );

  372.         /*
  373.          * Test the hyperbolic tension spline
  374.          */

  375.         System.out.println (" ---------- \n HYPERBOLIC \n ---------- \n");

  376.         TestSpline (
  377.             CreateHyperbolicTensionSpline(),
  378.             rssc,
  379.             segParams
  380.         );

  381.         /*
  382.          * Test the Kaklis-Pandelis spline
  383.          */

  384.         System.out.println (" -------------------- \n KAKLISPANDELIS \n -------------------- \n");

  385.         TestSpline (
  386.             CreateKaklisPandelisSpline(),
  387.             rssc,
  388.             segParams
  389.         );

  390.         /*
  391.          * Test the C1 Hermite spline
  392.          */

  393.         System.out.println (" -------------------- \n C1 HERMITE \n -------------------- \n");

  394.         TestC1HermiteSpline (
  395.             CreatePolynomialSpline(),
  396.             rssc,
  397.             SegmentInelasticDesignControl.Create (
  398.                 1,
  399.                 iCurvaturePenaltyDerivativeOrder
  400.             )
  401.         );
  402.     }

  403.     public static final void main (
  404.         final String[] astrArgs)
  405.         throws Exception
  406.     {
  407.         BasisSplineSetSample();
  408.     }
  409. }