KnotInsertionSequenceAdjuster.java

  1. package org.drip.sample.stretch;

  2. import org.drip.function.r1tor1.*;
  3. import org.drip.numerical.common.FormatUtil;
  4. import org.drip.spline.basis.PolynomialFunctionSetParams;
  5. import org.drip.spline.params.*;
  6. import org.drip.spline.stretch.*;

  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.  * KnotInsertionSequenceAdjuster demonstrates the Stretch Manipulation and Adjustment API. It shows the
  57.  *  following:
  58.  *  - Construct a simple Base Stretch.
  59.  *  - Clip a left Portion of the Stretch to construct a left-clipped Stretch.
  60.  *  - Clip a right Portion of the Stretch to construct a tight-clipped Stretch.
  61.  *  - Compare the values across all the stretches to establish a) the continuity in the base smoothness is,
  62.  *      preserved, and b) Continuity across the predictor ordinate for the implied response value is also
  63.  *      preserved.
  64.  *
  65.  * @author Lakshmi Krishnamurthy
  66.  */

  67. public class KnotInsertionSequenceAdjuster {

  68.     /*
  69.      * Build Polynomial Segment Control Parameters
  70.      *
  71.      *  WARNING: Insufficient Error Checking, so use caution
  72.      */

  73.     private static final SegmentCustomBuilderControl PolynomialSegmentControlParams (
  74.         final int iNumBasis,
  75.         final SegmentInelasticDesignControl sdic,
  76.         final ResponseScalingShapeControl rssc)
  77.         throws Exception
  78.     {
  79.         return new SegmentCustomBuilderControl (
  80.             MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  81.             new PolynomialFunctionSetParams (iNumBasis),
  82.             sdic,
  83.             rssc,
  84.             null
  85.         );
  86.     }

  87.     /*
  88.      * Basis Spline Stretch Test Sample. Performs the following:
  89.      *  - Construct the Array of Segment Builder Parameters - one per segment.
  90.      *  - Construct the Stretch instance.
  91.      *
  92.      *  WARNING: Insufficient Error Checking, so use caution
  93.      */

  94.     private static final MultiSegmentSequence BasisSplineStretchTest (
  95.         final double[] adblX,
  96.         final double[] adblY,
  97.         final SegmentCustomBuilderControl scbc)
  98.         throws Exception
  99.     {
  100.         /*
  101.          * Array of Segment Builder Parameters - one per segment
  102.          */

  103.         SegmentCustomBuilderControl[] aSCBC = new SegmentCustomBuilderControl[adblX.length - 1];

  104.         for (int i = 0; i < adblX.length - 1; ++i)
  105.             aSCBC[i] = scbc;

  106.         /*
  107.          * Construct a Stretch instance
  108.          */

  109.         return MultiSegmentSequenceBuilder.CreateCalibratedStretchEstimator (
  110.             "SPLINE_STRETCH",
  111.             adblX, // predictors
  112.             adblY, // responses
  113.             aSCBC, // Basis Segment Builder parameters
  114.             null,
  115.             BoundarySettings.NaturalStandard(), // Boundary Condition - Natural
  116.             MultiSegmentSequence.CALIBRATE // Calibrate the Stretch predictors to the responses
  117.         );
  118.     }

  119.     /*
  120.      * The Stretch Adjuster Test - this brings it altogether.
  121.      */

  122.     private static final void StretchAdjusterTest()
  123.         throws Exception
  124.     {
  125.         /*
  126.          * X predictors
  127.          */

  128.         double[] adblX = new double[] { 1.00,  1.50,  2.00, 3.00, 4.00, 5.00, 6.50, 8.00, 10.00};

  129.         /*
  130.          * Y responses
  131.          */

  132.         double[] adblY = new double[] {25.00, 20.25, 16.00, 9.00, 4.00, 1.00, 0.25, 4.00, 16.00};

  133.         /*
  134.          * Construct a rational shape controller with the shape controller tension of 1.
  135.          */

  136.         double dblShapeControllerTension = 1.;

  137.         ResponseScalingShapeControl rssc = new ResponseScalingShapeControl (
  138.             false,
  139.             new QuadraticRationalShapeControl (dblShapeControllerTension)
  140.         );

  141.         /*
  142.          * Construct the segment inelastic parameter that is C2 (iK = 2 sets it to C2), with 2nd order
  143.          *  roughness penalty derivative, and without constraint
  144.          */

  145.         int iK = 2;
  146.         int iRoughnessPenaltyDerivativeOrder = 2;

  147.         SegmentInelasticDesignControl sdic = SegmentInelasticDesignControl.Create (
  148.             iK,
  149.             iRoughnessPenaltyDerivativeOrder
  150.         );

  151.         /*
  152.          * Build the polynomial basis spline segment control parameters, and set up the stretch
  153.          */

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

  155.         int iPolyNumBasis = 4;

  156.         SegmentCustomBuilderControl scbc = PolynomialSegmentControlParams (
  157.             iPolyNumBasis,
  158.             sdic,
  159.             rssc
  160.         );

  161.         MultiSegmentSequence mssBase = BasisSplineStretchTest (
  162.             adblX,
  163.             adblY,
  164.             scbc
  165.         );

  166.         /*
  167.          * Estimate, compute the segment-by-segment monotonicity and the Stretch Jacobian
  168.          */

  169.         double dblX = mssBase.getLeftPredictorOrdinateEdge();

  170.         double dblXMax = mssBase.getRightPredictorOrdinateEdge();

  171.         while (dblX <= dblXMax) {
  172.             System.out.println ("Y[" + dblX + "] " + FormatUtil.FormatDouble (mssBase.responseValue (dblX), 1, 2, 1.) + " | "
  173.                 + mssBase.monotoneType (dblX));

  174.             System.out.println ("Jacobian Y[" + dblX + "]=" + mssBase.jackDResponseDCalibrationInput (dblX, 1).displayString());

  175.             dblX += 1.;
  176.         }

  177.         /*
  178.          * Clip part of the stretch left of the specified predictor ordinate
  179.          */

  180.         System.out.println ("\tSPLINE_STRETCH_BASE DPE: " + mssBase.curvatureDPE());

  181.         System.out.println (" \n---------- \n LEFT CLIPPED \n ---------- \n");

  182.         MultiSegmentSequence mssLeftClipped = mssBase.clipLeft (
  183.             "LEFT_CLIP",
  184.             1.66
  185.         );

  186.         dblX = mssBase.getLeftPredictorOrdinateEdge();

  187.         /*
  188.          * Estimate, compute the segment-by-segment monotonicity and the Stretch Jacobian of the left clipped stretch
  189.          */

  190.         while (dblX <= dblXMax) {
  191.             if (mssLeftClipped.in (dblX)) {
  192.                 System.out.println ("Y[" + dblX + "] " + FormatUtil.FormatDouble (mssLeftClipped.responseValue (dblX), 1, 2, 1.) + " | "
  193.                     + mssLeftClipped.monotoneType (dblX));

  194.                 System.out.println ("Jacobian Y[" + dblX + "]=" + mssLeftClipped.jackDResponseDCalibrationInput (dblX, 1).displayString());
  195.             }

  196.             dblX += 1.;
  197.         }

  198.         /*
  199.          * Left clipped stretch DPE
  200.          */

  201.         System.out.println ("\tSPLINE_STRETCH_LEFT DPE: " + mssLeftClipped.curvatureDPE());

  202.         /*
  203.          * Clip part of the stretch right of the specified predictor ordinate
  204.          */

  205.         System.out.println (" \n---------- \n RIGHT CLIPPED \n ---------- \n");

  206.         MultiSegmentSequence mssRightClipped = mssBase.clipRight (
  207.             "RIGHT_CLIP",
  208.             7.48
  209.         );

  210.         /*
  211.          * Estimate, compute the segment-by-segment monotonicity and the Stretch Jacobian of the right clipped stretch
  212.          */

  213.         dblX = mssBase.getLeftPredictorOrdinateEdge();

  214.         while (dblX <= dblXMax) {
  215.             if (mssRightClipped.in (dblX)) {
  216.                 System.out.println ("Y[" + dblX + "] " + FormatUtil.FormatDouble (mssRightClipped.responseValue (dblX), 1, 2, 1.) + " | "
  217.                     + mssRightClipped.monotoneType (dblX));

  218.                 System.out.println ("Jacobian Y[" + dblX + "]=" + mssRightClipped.jackDResponseDCalibrationInput (dblX, 1).displayString());
  219.             }

  220.             dblX += 1.;
  221.         }

  222.         /*
  223.          * Right clipped stretch DPE
  224.          */

  225.         System.out.println ("\tSPLINE_STRETCH_RIGHT DPE: " + mssRightClipped.curvatureDPE());

  226.         /*
  227.          * Ordered Side by side Comparison of left clipped - unclipped - right clipped response values
  228.          */

  229.         dblX = mssBase.getLeftPredictorOrdinateEdge();

  230.         dblXMax = mssBase.getRightPredictorOrdinateEdge();

  231.         System.out.println ("\n-----------------------------------------------------------------------------------------------------");

  232.         System.out.println ("                           BASE         ||      LEFT CLIPPED           ||      RIGHT CLIPPED");

  233.         System.out.println ("-----------------------------------------------------------------------------------------------------");

  234.         while (dblX <= dblXMax) {
  235.             java.lang.String strLeftClippedValue = "         ";
  236.             java.lang.String strRightClippedValue = "         ";
  237.             java.lang.String strLeftClippedMonotonocity = "             ";
  238.             java.lang.String strRightClippedMonotonocity = "             ";

  239.             /*
  240.              * Unclipped
  241.              */

  242.             java.lang.String strDisplay = "Y[" + FormatUtil.FormatDouble (dblX, 2, 3, 1.) + "] => "
  243.                 + FormatUtil.FormatDouble (mssBase.responseValue (dblX), 2, 6, 1.) + " | "
  244.                 + mssBase.monotoneType (dblX);

  245.             /*
  246.              * Left clipped
  247.              */

  248.             if (mssLeftClipped.in (dblX)) {
  249.                 strLeftClippedValue = FormatUtil.FormatDouble (mssLeftClipped.responseValue (dblX), 2, 6, 1.);

  250.                 strLeftClippedMonotonocity = mssLeftClipped.monotoneType (dblX).toString();
  251.             }

  252.             /*
  253.              * Right clipped
  254.              */

  255.             if (mssRightClipped.in (dblX)) {
  256.                 strRightClippedValue = FormatUtil.FormatDouble (mssRightClipped.responseValue (dblX), 2, 6, 1.);

  257.                 strRightClippedMonotonocity = mssRightClipped.monotoneType (dblX).toString();
  258.             }

  259.             System.out.println (strDisplay + "  ||  " + strLeftClippedValue + " | " + strLeftClippedMonotonocity +
  260.                 "  ||  " + strRightClippedValue + " | " + strRightClippedMonotonocity);

  261.             dblX += 0.5;
  262.         }
  263.     }

  264.     public static final void main (
  265.         final String[] astrArgs)
  266.         throws Exception
  267.     {
  268.         StretchAdjusterTest();
  269.     }
  270. }