CurvatureLengthRoughnessPenalty.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.  * PenalizedCurvatureLCurvatureLengthRoughnessPenaltyengthFit demonstrates the setting up and the usage of
  57.  *  the curvature, the length, and the closeness of fit penalizing spline. This sample shows the following:
  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 First Order Segment
  64.  *      Length Penalty Derivative, Second Order Segment Curvature Penalty Derivative, their Amplitudes, and
  65.  *      without Constraint.
  66.  *  - Construct the base, the base + 1 degree segment builder control.
  67.  *  - Construct the base, the elevated, and the best fit basis spline stretches.
  68.  *  - Compute the segment-by-segment monotonicity for all the three stretches.
  69.  *  - Compute the Stretch Jacobian for all the three stretches.
  70.  *  - Compute the Base Stretch Curvature, Length, and the Best Fit DPE.
  71.  *  - Compute the Elevated Stretch Curvature, Length, and the Best Fit DPE.
  72.  *  - Compute the Best Fit Stretch Curvature, Length, and the Best Fit DPE.
  73.  *
  74.  * @author Lakshmi Krishnamurthy
  75.  */

  76. public class CurvatureLengthRoughnessPenalty {

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

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

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

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

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

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

  116.         /*
  117.          * Construct a Stretch instance
  118.          */

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

  129.     /*
  130.      * Illustrate the Penalized Curvature+Length+BestFit Usage Sample. This sample shows the following:
  131.      *  - Set up the X Predictor Ordinate and the Y Response Value Set.
  132.      *  - Construct a set of Predictor Ordinates, their Responses, and corresponding Weights to serve as
  133.      *      weighted closeness of fit.
  134.      *  - Construct a rational shape controller with the desired shape controller tension parameters and Global Scaling.
  135.      *  - Construct the Segment Inelastic Parameter that is C2 (iK = 2 sets it to C2), with First Order
  136.      *      Segment Length Penalty Derivative, Second Order Segment Curvature Penalty Derivative, their
  137.      *      Amplitudes, and without Constraint.
  138.      *  - Construct the base, the base + 1 degree segment builder control.
  139.      *  - Construct the base, the elevated, and the best fit basis spline stretches.
  140.      *  - Compute the segment-by-segment monotonicity for all the three stretches.
  141.      *  - Compute the Stretch Jacobian for all the three stretches.
  142.      *  - Compute the Base Stretch Curvature, Length, and the Best Fit DPE.
  143.      *  - Compute the Elevated Stretch Curvature, Length, and the Best Fit DPE.
  144.      *  - Compute the Best Fit Stretch Curvature, Length, and the Best Fit DPE.
  145.      */

  146.     public static final void PenalizedCurvatureLengthFitTest()
  147.         throws Exception
  148.     {
  149.         /*
  150.          * X predictors
  151.          */

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

  153.         /*
  154.          * Y responses
  155.          */

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

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

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

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

  169.         double dblShapeControllerTension = 1.;

  170.         ResponseScalingShapeControl rssc = new ResponseScalingShapeControl (
  171.             false,
  172.             new QuadraticRationalShapeControl (dblShapeControllerTension)
  173.         );

  174.         /*
  175.          * Construct the Segment Inelastic Parameter that is C2 (iK = 2 sets it to C2), with First Order
  176.          *  Segment Length Penalty Derivative, Second Order Segment Curvature Penalty Derivative, their
  177.          *  Amplitudes, and without Constraint
  178.          */

  179.         int iK = 2;
  180.         double dblLengthPenaltyAmplitude = 1.;
  181.         double dblCurvaturePenaltyAmplitude = 1.;
  182.         int iLengthPenaltyDerivativeOrder = 1;
  183.         int iCurvaturePenaltyDerivativeOrder = 2;

  184.         SegmentInelasticDesignControl sdic = new SegmentInelasticDesignControl (
  185.             iK,
  186.             new org.drip.spline.params.SegmentFlexurePenaltyControl (
  187.                 iLengthPenaltyDerivativeOrder,
  188.                 dblLengthPenaltyAmplitude
  189.             ),
  190.             new org.drip.spline.params.SegmentFlexurePenaltyControl (
  191.                 iCurvaturePenaltyDerivativeOrder,
  192.                 dblCurvaturePenaltyAmplitude
  193.             )
  194.         );

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

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

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

  198.         int iPolyNumBasis = 4;

  199.         /*
  200.          * Construct the base, the base + 1 degree segment builder control
  201.          */

  202.         SegmentCustomBuilderControl scbc1 = PolynomialSegmentControlParams (
  203.             iPolyNumBasis,
  204.             sdic,
  205.             rssc
  206.         );

  207.         SegmentCustomBuilderControl scbc2 = PolynomialSegmentControlParams (
  208.             iPolyNumBasis + 1,
  209.             sdic,
  210.             rssc
  211.         );

  212.         /*
  213.          * Construct the base, the elevated, and the best fit basis spline stretches
  214.          */

  215.         MultiSegmentSequence mssBase1 = BasisSplineStretchTest (
  216.             adblX,
  217.             adblY,
  218.             scbc1,
  219.             null
  220.         );

  221.         MultiSegmentSequence mssBase2 = BasisSplineStretchTest (
  222.             adblX,
  223.             adblY,
  224.             scbc2,
  225.             null
  226.         );

  227.         MultiSegmentSequence mssBestFit = BasisSplineStretchTest (
  228.             adblX,
  229.             adblY,
  230.             scbc2,
  231.             rbfr
  232.         );

  233.         /*
  234.          * Compute the segment-by-segment response and monotonicity for all the three stretches
  235.          */

  236.         double dblX = mssBase1.getLeftPredictorOrdinateEdge();

  237.         double dblXMax = mssBase1.getRightPredictorOrdinateEdge();

  238.         while (dblX <= dblXMax) {
  239.             System.out.println (
  240.                 "Y[" + FormatUtil.FormatDouble (dblX, 1, 2, 1.) + "] " +
  241.                 FormatUtil.FormatDouble (mssBase1.responseValue (dblX), 2, 2, 1.) + " | "
  242.                     + mssBase1.monotoneType (dblX) + " $$ "
  243.                 + FormatUtil.FormatDouble (mssBase2.responseValue (dblX), 2, 2, 1.) + " | "
  244.                     + mssBase2.monotoneType (dblX) + " $$ "
  245.                 + FormatUtil.FormatDouble (mssBestFit.responseValue (dblX), 2, 2, 1.) + " | "
  246.                     + mssBestFit.monotoneType (dblX));

  247.             dblX += 0.25;
  248.         }

  249.         /*
  250.          * Compute the Stretch Jacobian for all the three stretches
  251.          */

  252.         dblX = mssBase1.getLeftPredictorOrdinateEdge();

  253.         while (dblX <= dblXMax) {
  254.             System.out.println (
  255.                 "\t\tJacobian Y[" + FormatUtil.FormatDouble (dblX, 2, 2, 1.) + "] => " +
  256.                     mssBase1.jackDResponseDCalibrationInput (dblX, 1).displayString());

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

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

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

  264.             dblX += 0.25;
  265.         }

  266.         /*
  267.          * Compute the Base Stretch Curvature, Length, and the Best Fit DPE
  268.          */

  269.         System.out.println ("\n\t\t----STRETCH #1----\n\t\t-----------------");

  270.         System.out.println ("\tCURVATURE DPE         => " +
  271.             FormatUtil.FormatDouble (mssBase1.curvatureDPE(), 10, 0, 1.));

  272.         System.out.println ("\tLENGTH DPE            => " +
  273.             FormatUtil.FormatDouble (mssBase1.lengthDPE(), 10, 0, 1.));

  274.         System.out.println ("\tBEST FIT DPE          => " +
  275.             FormatUtil.FormatDouble (mssBase1.bestFitDPE (rbfr), 10, 0, 1.));

  276.         /*
  277.          * Compute the Elevated Stretch Curvature, Length, and the Best Fit DPE
  278.          */

  279.         System.out.println ("\n\t\t----STRETCH #2----\n\t\t-----------------");

  280.         System.out.println ("\tCURVATURE DPE         => " +
  281.             FormatUtil.FormatDouble (mssBase2.curvatureDPE(), 10, 0, 1.));

  282.         System.out.println ("\tLENGTH DPE            => " +
  283.             FormatUtil.FormatDouble (mssBase2.lengthDPE(), 10, 0, 1.));

  284.         System.out.println ("\tBEST FIT DPE          => " +
  285.             FormatUtil.FormatDouble (mssBase2.bestFitDPE (rbfr), 10, 0, 1.));

  286.         /*
  287.          * Compute the Best Fit Stretch Curvature, Length, and the Best Fit DPE
  288.          */

  289.         System.out.println ("\n\t\t----STRETCH BEST FIT----\n\t\t-----------------------");

  290.         System.out.println ("\tCURVATURE DPE         => " +
  291.             FormatUtil.FormatDouble (mssBestFit.curvatureDPE(), 10, 0, 1.));

  292.         System.out.println ("\tLENGTH DPE            => " +
  293.             FormatUtil.FormatDouble (mssBestFit.lengthDPE(), 10, 0, 1.));

  294.         System.out.println ("\tBEST FIT DPE          => " +
  295.             FormatUtil.FormatDouble (mssBestFit.bestFitDPE (rbfr), 10, 0, 1.));
  296.     }

  297.     public static final void main (
  298.         final String[] astrArgs)
  299.         throws Exception
  300.     {
  301.         PenalizedCurvatureLengthFitTest();
  302.     }
  303. }