CurvatureRoughnessPenaltyFit.java

  1. package org.drip.sample.stretch;

  2. import org.drip.function.r1tor1.QuadraticRationalShapeControl;
  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.  * CurvatureRoughnessPenaltyFit demonstrates the setting up and the usage of the curvature and closeness of
  57.  *  fit penalizing spline. It illustrates in detail the following steps:
  58.  *  - Set up the X Predictor Ordinate and the Y Response Value Set.
  59.  *  - Construct a set of Predictor Ordinates, their Responses, and corresponding Weights to serve as
  60.  *      weighted closeness of fit.
  61.  *  - Construct a rational shape controller with the desired shape controller tension parameters and Global
  62.  *      Scaling.
  63.  *  - Construct the segment inelastic parameter that is C2 (iK = 2 sets it to C2), with 2nd order roughness
  64.  *      penalty derivative, and without constraint.
  65.  *  - Construct the base, the base + 1 degree segment builder control.
  66.  *  - Construct the base, the elevated, and the best fit basis spline stretches.
  67.  *  - Compute the segment-by-segment monotonicity for all the three stretches.
  68.  *  - Compute the Stretch Jacobian for all the three stretches.
  69.  *  - Compute the Base Stretch Curvature Penalty Estimate.
  70.  *  - Compute the Elevated Stretch Curvature Penalty Estimate.
  71.  *  - Compute the Best Fit Stretch Curvature Penalty Estimate.
  72.  *
  73.  * @author Lakshmi Krishnamurthy
  74.  */

  75. public class CurvatureRoughnessPenaltyFit {

  76.     /*
  77.      * Build Polynomial Segment Control Parameters
  78.      *
  79.      *  WARNING: Insufficient Error Checking, so use caution
  80.      */

  81.     public static final SegmentCustomBuilderControl PolynomialSegmentControlParams (
  82.         final int iNumBasis,
  83.         final SegmentInelasticDesignControl sdic,
  84.         final ResponseScalingShapeControl rssc)
  85.         throws Exception
  86.     {
  87.         return new SegmentCustomBuilderControl (
  88.             MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
  89.             new PolynomialFunctionSetParams (iNumBasis),
  90.             sdic,
  91.             rssc,
  92.             null
  93.         );
  94.     }

  95.     /*
  96.      * Construct the Basis Spline Stretch Instance using the following inputs:
  97.      *  - Array of Segment Builder Parameters - one per segment
  98.      *  - Construct a Calibrated Stretch instance
  99.      *
  100.      *  WARNING: Insufficient Error Checking, so use caution
  101.      */

  102.     public static final MultiSegmentSequence BasisSplineStretchTest (
  103.         final double[] adblX,
  104.         final double[] adblY,
  105.         final SegmentCustomBuilderControl scbc,
  106.         final StretchBestFitResponse sbfr)
  107.         throws Exception
  108.     {
  109.         /*
  110.          * Array of Segment Builder Parameters - one per segment
  111.          */

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

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

  115.         /*
  116.          * Construct a Calibrated Stretch instance
  117.          */

  118.         return MultiSegmentSequenceBuilder.CreateCalibratedStretchEstimator (
  119.             "SPLINE_STRETCH",
  120.             adblX, // predictors
  121.             adblY, // responses
  122.             aSCBC, // Basis Segment Builder parameters
  123.             sbfr, // Stretch Fitness Weighted Response
  124.             BoundarySettings.NaturalStandard(), // Boundary Condition - Natural
  125.             MultiSegmentSequence.CALIBRATE // Calibrate the Stretch predictors to the responses
  126.         );
  127.     }

  128.     /*
  129.      * Bring it all together in the Penalized Curvature Fit Test using the following steps:
  130.      *  - Set up the X Predictor Ordinate and the Y Response Value Set.
  131.      *  - Construct a set of Predictor Ordinates, their Responses, and corresponding Weights to serve as
  132.      *      weighted closeness of fit.
  133.      *  - Construct a rational shape controller with the desired shape controller tension parameters and Global Scaling.
  134.      *  - Construct the segment inelastic parameter that is C2 (iK = 2 sets it to C2), with 2nd order
  135.      *      roughness penalty derivative, and without constraint.
  136.      *  - Construct the base, the base + 1 degree segment builder control.
  137.      *  - Construct the base, the elevated, and the best fit basis spline stretches.
  138.      *  - Compute the segment-by-segment monotonicity for all the three stretches.
  139.      *  - Compute the Stretch Jacobian for all the three stretches.
  140.      *  - Compute the Base Stretch Curvature Penalty Estimate.
  141.      *  - Compute the Elevated Stretch Curvature Penalty Estimate.
  142.      *  - Compute the Best Fit Stretch Curvature Penalty Estimate.
  143.      */

  144.     public static final void PenalizedCurvatureFitTest()
  145.         throws Exception
  146.     {
  147.         /*
  148.          * X predictors
  149.          */

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

  151.         /*
  152.          * Y responses
  153.          */

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

  155.         /*
  156.          * Construct a set of Predictor Ordinates, their Responses, and corresponding Weights to serve as
  157.          *  weighted closeness of fit.
  158.          */

  159.         StretchBestFitResponse sbfr = StretchBestFitResponse.Create (
  160.             new double[] { 2.28,  2.52,  2.73, 3.00,  5.50, 8.44,  8.76,  9.08,  9.80,  9.92},
  161.             new double[] {14.27, 12.36, 10.61, 9.25, -0.50, 7.92, 10.07, 12.23, 15.51, 16.36},
  162.             new double[] { 1.09,  0.82,  1.34, 1.10,  0.50, 0.79,  0.65,  0.49,  0.24,  0.21}
  163.         );

  164.         /*
  165.          * Construct a rational shape controller with the shape controller tension of 1, and Global Scaling.
  166.          */

  167.         double dblShapeControllerTension = 1.;

  168.         ResponseScalingShapeControl rssc = new ResponseScalingShapeControl (
  169.             false,
  170.             new QuadraticRationalShapeControl (dblShapeControllerTension)
  171.         );

  172.         /*
  173.          * Construct the segment inelastic parameter that is C2 (iK = 2 sets it to C2), with 2nd order
  174.          *  roughness penalty derivative, and without constraint
  175.          */

  176.         int iK = 2;
  177.         int iRoughnessPenaltyDerivativeOrder = 2;

  178.         SegmentInelasticDesignControl sdic = SegmentInelasticDesignControl.Create (
  179.             iK,
  180.             iRoughnessPenaltyDerivativeOrder
  181.         );

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

  183.         System.out.println (" \n         == ORIGINAL #1 ==      $$   == ORIGINAL #2 ==    $$   == BEST FIT ==    ");

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

  185.         int iPolyNumBasis = 4;

  186.         /*
  187.          * Construct the base, the base + 1 degree segment builder control
  188.          */

  189.         SegmentCustomBuilderControl scbc1 = PolynomialSegmentControlParams (
  190.             iPolyNumBasis,
  191.             sdic,
  192.             rssc
  193.         );

  194.         SegmentCustomBuilderControl scbc2 = PolynomialSegmentControlParams (
  195.             iPolyNumBasis + 1,
  196.             sdic,
  197.             rssc
  198.         );

  199.         /*
  200.          * Construct the base, the elevated, and the best fit basis spline stretches
  201.          */

  202.         MultiSegmentSequence mssBase1 = BasisSplineStretchTest (
  203.             adblX,
  204.             adblY,
  205.             scbc1,
  206.             null
  207.         );

  208.         MultiSegmentSequence mssBase2 = BasisSplineStretchTest (
  209.             adblX,
  210.             adblY,
  211.             scbc2,
  212.             null
  213.         );

  214.         MultiSegmentSequence mssBestFit = BasisSplineStretchTest (
  215.             adblX,
  216.             adblY,
  217.             scbc2,
  218.             sbfr
  219.         );

  220.         /*
  221.          * Compute the segment-by-segment monotonicity for all the three stretches
  222.          */

  223.         double dblX = mssBase1.getLeftPredictorOrdinateEdge();

  224.         double dblXMax = mssBase1.getRightPredictorOrdinateEdge();

  225.         while (dblX <= dblXMax) {
  226.             System.out.println (
  227.                 "Y[" + FormatUtil.FormatDouble (dblX, 1, 2, 1.) + "] " +
  228.                 FormatUtil.FormatDouble (mssBase1.responseValue (dblX), 2, 2, 1.) + " | "
  229.                     + mssBase1.monotoneType (dblX) + " $$ "
  230.                 + FormatUtil.FormatDouble (mssBase2.responseValue (dblX), 2, 2, 1.) + " | "
  231.                     + mssBase2.monotoneType (dblX) + " $$ "
  232.                 + FormatUtil.FormatDouble (mssBestFit.responseValue (dblX), 2, 2, 1.) + " | "
  233.                     + mssBestFit.monotoneType (dblX));

  234.             dblX += 0.25;
  235.         }

  236.         /*
  237.          * Compute the Stretch Jacobian for all the three stretches
  238.          */

  239.         dblX = mssBase1.getLeftPredictorOrdinateEdge();

  240.         while (dblX <= dblXMax) {
  241.             System.out.println (
  242.                 "\t\tJacobian Y[" + FormatUtil.FormatDouble (dblX, 2, 2, 1.) + "] => " +
  243.                     mssBase1.jackDResponseDCalibrationInput (dblX, 1).displayString());

  244.             System.out.println (
  245.                 "\t\tJacobian Y[" + FormatUtil.FormatDouble (dblX, 2, 2, 1.) + "] => " +
  246.                     mssBase2.jackDResponseDCalibrationInput (dblX, 1).displayString());

  247.             System.out.println (
  248.                 "\t\tJacobian Y[" + FormatUtil.FormatDouble (dblX, 2, 2, 1.) + "] => " +
  249.                     mssBestFit.jackDResponseDCalibrationInput (dblX, 1).displayString());

  250.             System.out.println ("\t\t----\n\t\t----");

  251.             dblX += 0.25;
  252.         }

  253.         /*
  254.          * Compute the Base Stretch Curvature Penalty Estimate
  255.          */

  256.         System.out.println ("\tBASE #1  DPE: " + FormatUtil.FormatDouble (mssBase1.curvatureDPE(), 10, 0, 1.));

  257.         /*
  258.          * Compute the Elevated Stretch Curvature Penalty Estimate
  259.          */

  260.         System.out.println ("\tBASE #2  DPE: " + FormatUtil.FormatDouble (mssBase2.curvatureDPE(), 10, 0, 1.));

  261.         /*
  262.          * Compute the Best Fit Stretch Curvature Penalty Estimate
  263.          */

  264.         System.out.println ("\tBEST FIT DPE: " + FormatUtil.FormatDouble (mssBestFit.curvatureDPE(), 10, 0, 1.));
  265.     }

  266.     public static final void main (
  267.         final String[] astrArgs)
  268.         throws Exception
  269.     {
  270.         PenalizedCurvatureFitTest();
  271.     }
  272. }