LatentStateSequenceBuilder.java

  1. package org.drip.state.inference;

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

  79. /**
  80.  * <i>LatentStateSequenceBuilder</i> holds the logic behind building the bootstrap segments contained in the
  81.  * given Stretch.
  82.  *
  83.  *  <br><br>
  84.  *  <ul>
  85.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ProductCore.md">Product Core Module</a></li>
  86.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/FixedIncomeAnalyticsLibrary.md">Fixed Income Analytics</a></li>
  87.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/state/README.md">Latent State Inference and Creation Utilities</a></li>
  88.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/state/inference/README.md">Latent State Stretch Sequence Inference</a></li>
  89.  *  </ul>
  90.  * <br><br>
  91.  *
  92.  * It extends SegmentSequenceBuilder by implementing/customizing the calibration of the starting as well as
  93.  *  the subsequent segments.
  94.  *
  95.  * @author Lakshmi Krishnamurthy
  96.  */

  97. public class LatentStateSequenceBuilder implements org.drip.spline.stretch.SegmentSequenceBuilder {
  98.     private org.drip.spline.grid.Span _span = null;
  99.     private double _dblEpochResponse = java.lang.Double.NaN;
  100.     private org.drip.spline.stretch.BoundarySettings _bs = null;
  101.     private org.drip.state.estimator.CurveStretch _stretch = null;
  102.     private org.drip.param.pricer.CreditPricerParams _pricerParams = null;
  103.     private org.drip.param.market.CurveSurfaceQuoteContainer _csqs = null;
  104.     private org.drip.param.valuation.ValuationParams _valParams = null;
  105.     private org.drip.spline.params.StretchBestFitResponse _sbfr = null;
  106.     private org.drip.param.valuation.ValuationCustomizationParams _vcp = null;
  107.     private org.drip.state.inference.LatentStateStretchSpec _stretchSpec = null;
  108.     private org.drip.spline.params.StretchBestFitResponse _sbfrQuoteSensitivity = null;
  109.     private
  110.         org.drip.analytics.support.CaseInsensitiveHashMap<org.drip.spline.params.PreceedingManifestSensitivityControl>
  111.             _mapPMSC = null;

  112.     private java.util.Map<java.lang.Double, org.drip.spline.params.ResponseValueSensitivityConstraint>
  113.         _mapRVSC = new
  114.             java.util.HashMap<java.lang.Double, org.drip.spline.params.ResponseValueSensitivityConstraint>();

  115.     private org.drip.spline.params.PreceedingManifestSensitivityControl getPMSC (
  116.         final java.lang.String strManifestMeasure)
  117.     {
  118.         return _mapPMSC.containsKey (strManifestMeasure) ? _mapPMSC.get (strManifestMeasure) : null;
  119.     }

  120.     private org.drip.spline.params.SegmentResponseValueConstraint segmentCalibResponseConstraint (
  121.         final org.drip.state.estimator.PredictorResponseWeightConstraint prwc)
  122.     {
  123.         java.util.TreeMap<java.lang.Double, java.lang.Double> mapPredictorLSQMLoading =
  124.             prwc.getPredictorResponseWeight();

  125.         if (null == mapPredictorLSQMLoading || 0 == mapPredictorLSQMLoading.size()) return null;

  126.         java.util.Set<java.util.Map.Entry<java.lang.Double, java.lang.Double>> esPredictorLSQMLoading =
  127.             mapPredictorLSQMLoading.entrySet();

  128.         if (null == esPredictorLSQMLoading || 0 == esPredictorLSQMLoading.size()) return null;

  129.         double dblConstraint = 0.;

  130.         java.util.List<java.lang.Double> lsPredictor = new java.util.ArrayList<java.lang.Double>();

  131.         java.util.List<java.lang.Double> lsResponseLSQMLoading = new java.util.ArrayList<java.lang.Double>();

  132.         for (java.util.Map.Entry<java.lang.Double, java.lang.Double> me : esPredictorLSQMLoading) {
  133.             if (null == me) return null;

  134.             double dblPredictorDate = me.getKey();

  135.             try {
  136.                 if (null != _span && _span.in (dblPredictorDate))
  137.                     dblConstraint -= _span.calcResponseValue (dblPredictorDate) * me.getValue();
  138.                 else if (_stretch.inBuiltRange (dblPredictorDate))
  139.                     dblConstraint -= _stretch.responseValue (dblPredictorDate) * me.getValue();
  140.                 else {
  141.                     lsPredictor.add (dblPredictorDate);

  142.                     lsResponseLSQMLoading.add (me.getValue());
  143.                 }
  144.             } catch (java.lang.Exception e) {
  145.                 e.printStackTrace();

  146.                 return null;
  147.             }
  148.         }

  149.         int iSize = lsPredictor.size();

  150.         double[] adblPredictor = new double[iSize];
  151.         double[] adblResponseLSQMLoading = new double[iSize];

  152.         for (int i = 0; i < iSize; ++i) {
  153.             adblPredictor[i] = lsPredictor.get (i);

  154.             adblResponseLSQMLoading[i] = lsResponseLSQMLoading.get (i);
  155.         }

  156.         try {
  157.             return new org.drip.spline.params.SegmentResponseValueConstraint (adblPredictor,
  158.                 adblResponseLSQMLoading, (prwc.getValue()) + dblConstraint);
  159.         } catch (java.lang.Exception e) {
  160.             e.printStackTrace();
  161.         }

  162.         return null;
  163.     }

  164.     private org.drip.spline.params.SegmentResponseValueConstraint segmentSensResponseConstraint (
  165.         final org.drip.state.estimator.PredictorResponseWeightConstraint prwc,
  166.         final java.lang.String strManifestMeasure)
  167.     {
  168.         java.util.TreeMap<java.lang.Double, java.lang.Double> mapPredictorSensLoading =
  169.             prwc.getDResponseWeightDManifestMeasure (strManifestMeasure);

  170.         if (null == mapPredictorSensLoading || 0 == mapPredictorSensLoading.size()) return null;

  171.         java.util.Set<java.util.Map.Entry<java.lang.Double, java.lang.Double>> esPredictorSensLoading =
  172.             mapPredictorSensLoading.entrySet();

  173.         if (null == esPredictorSensLoading || 0 == esPredictorSensLoading.size()) return null;

  174.         double dblSensLoadingConstraint = 0.;

  175.         java.util.List<java.lang.Double> lsPredictor = new java.util.ArrayList<java.lang.Double>();

  176.         java.util.List<java.lang.Double> lsSensLoading = new java.util.ArrayList<java.lang.Double>();

  177.         for (java.util.Map.Entry<java.lang.Double, java.lang.Double> me : esPredictorSensLoading) {
  178.             if (null == me) return null;

  179.             double dblPredictorDate = me.getKey();

  180.             try {
  181.                 if (null != _span && _span.in (dblPredictorDate))
  182.                     dblSensLoadingConstraint -= _span.calcResponseValue (dblPredictorDate) * me.getValue();
  183.                 else if (_stretch.inBuiltRange (dblPredictorDate))
  184.                     dblSensLoadingConstraint -= _stretch.responseValue (dblPredictorDate) * me.getValue();
  185.                 else {
  186.                     lsPredictor.add (dblPredictorDate);

  187.                     lsSensLoading.add (me.getValue());
  188.                 }
  189.             } catch (java.lang.Exception e) {
  190.                 e.printStackTrace();

  191.                 return null;
  192.             }
  193.         }

  194.         int iSize = lsPredictor.size();

  195.         double[] adblPredictor = new double[iSize];
  196.         double[] adblSensLoading = new double[iSize];

  197.         for (int i = 0; i < iSize; ++i) {
  198.             adblPredictor[i] = lsPredictor.get (i);

  199.             adblSensLoading[i] = lsSensLoading.get (i);
  200.         }

  201.         try {
  202.             return new org.drip.spline.params.SegmentResponseValueConstraint (adblPredictor, adblSensLoading,
  203.                 prwc.getDValueDManifestMeasure (strManifestMeasure) + dblSensLoadingConstraint);
  204.         } catch (java.lang.Exception e) {
  205.             e.printStackTrace();
  206.         }

  207.         return null;
  208.     }

  209.     private boolean generateSegmentConstraintSet (
  210.         final double dblSegmentRight,
  211.         final org.drip.state.estimator.PredictorResponseWeightConstraint prwc)
  212.     {
  213.         org.drip.spline.params.SegmentResponseValueConstraint srvcBase = segmentCalibResponseConstraint
  214.             (prwc);

  215.         if (null == srvcBase) return false;

  216.         org.drip.spline.params.ResponseValueSensitivityConstraint rvsc = null;

  217.         try {
  218.             rvsc = new org.drip.spline.params.ResponseValueSensitivityConstraint (srvcBase);
  219.         } catch (java.lang.Exception e) {
  220.             e.printStackTrace();

  221.             return false;
  222.         }

  223.         java.util.Set<java.lang.String> setstrSensitivity = prwc.sensitivityKeys();

  224.         if (null == setstrSensitivity || 0 == setstrSensitivity.size()) {
  225.             _mapRVSC.put (dblSegmentRight, rvsc);

  226.             return true;
  227.         }

  228.         for (java.lang.String strManifestMeasure : setstrSensitivity) {
  229.             org.drip.spline.params.SegmentResponseValueConstraint srvcSensitivity =
  230.                 segmentSensResponseConstraint (prwc, strManifestMeasure);

  231.             if (null == srvcSensitivity || !rvsc.addManifestMeasureSensitivity (strManifestMeasure,
  232.                 srvcSensitivity))
  233.                 continue;
  234.         }

  235.         _mapRVSC.put (dblSegmentRight, rvsc);

  236.         return true;
  237.     }

  238.     /**
  239.      * LatentStateSequenceBuilder constructor
  240.      *
  241.      * @param dblEpochResponse Segment Sequence Left-most Response Value
  242.      * @param stretchSpec The Latent State Stretch Specification
  243.      * @param valParams Valuation Parameter
  244.      * @param pricerParams Pricer Parameter
  245.      * @param csqs The Market Parameter Set
  246.      * @param vcp Valuation Customization Parameters
  247.      * @param span The Containing Span this Stretch will become a part of
  248.      * @param sbfr Stretch Fitness Weighted Response
  249.      * @param mapPMSC Map of Preceeding Manifest Sensitivity Control Parameters
  250.      * @param sbfrQuoteSensitivity Stretch Fitness Weighted Response Quote Sensitivity
  251.      * @param bs The Calibration Boundary Condition
  252.      *
  253.      * @throws java.lang.Exception Thrown if the Inputs are invalid
  254.      */

  255.     public LatentStateSequenceBuilder (
  256.         final double dblEpochResponse,
  257.         final org.drip.state.inference.LatentStateStretchSpec stretchSpec,
  258.         final org.drip.param.valuation.ValuationParams valParams,
  259.         final org.drip.param.pricer.CreditPricerParams pricerParams,
  260.         final org.drip.param.market.CurveSurfaceQuoteContainer csqs,
  261.         final org.drip.param.valuation.ValuationCustomizationParams vcp,
  262.         final org.drip.spline.grid.Span span,
  263.         final org.drip.spline.params.StretchBestFitResponse sbfr,
  264.         final
  265.             org.drip.analytics.support.CaseInsensitiveHashMap<org.drip.spline.params.PreceedingManifestSensitivityControl>
  266.                 mapPMSC,
  267.         final org.drip.spline.params.StretchBestFitResponse sbfrQuoteSensitivity,
  268.         final org.drip.spline.stretch.BoundarySettings bs)
  269.         throws java.lang.Exception
  270.     {
  271.         if (!org.drip.numerical.common.NumberUtil.IsValid (_dblEpochResponse = dblEpochResponse) || null ==
  272.             (_stretchSpec = stretchSpec) || null == (_valParams = valParams) || null == (_bs = bs) || null ==
  273.                 (_mapPMSC = mapPMSC))
  274.             throw new java.lang.Exception ("LatentStateSequenceBuilder ctr: Invalid Inputs");

  275.         _vcp = vcp;
  276.         _csqs = csqs;
  277.         _sbfr = sbfr;
  278.         _span = span;
  279.         _pricerParams = pricerParams;
  280.         _sbfrQuoteSensitivity = sbfrQuoteSensitivity;
  281.     }

  282.     @Override public boolean setStretch (
  283.         final org.drip.spline.stretch.MultiSegmentSequence mss)
  284.     {
  285.         if (null == mss || !(mss instanceof org.drip.state.estimator.CurveStretch)) return false;

  286.         _stretch = (org.drip.state.estimator.CurveStretch) mss;

  287.         org.drip.spline.segment.LatentStateResponseModel[] aLSRM = _stretch.segments();

  288.         if (null == aLSRM || aLSRM.length != _stretchSpec.segmentSpec().length) return false;

  289.         return true;
  290.     }

  291.     @Override public org.drip.spline.stretch.BoundarySettings getCalibrationBoundaryCondition()
  292.     {
  293.         return _bs;
  294.     }

  295.     @Override public boolean calibStartingSegment (
  296.         final double dblLeftSlope)
  297.     {
  298.         if (null == _stretch || !_stretch.clearBuiltRange()) return false;

  299.         org.drip.product.definition.CalibratableComponent cfic =
  300.             _stretchSpec.segmentSpec()[0].component();

  301.         if (null == cfic) return false;

  302.         org.drip.spline.segment.LatentStateResponseModel[] aLSRM = _stretch.segments();

  303.         if (null == aLSRM || 0 == aLSRM.length) return false;

  304.         org.drip.state.estimator.PredictorResponseWeightConstraint prwc = cfic.calibPRWC (_valParams,
  305.             _pricerParams, _csqs, _vcp, _stretchSpec.segmentSpec()[0].manifestMeasures());

  306.         double dblSegmentRight = aLSRM[0].right();

  307.         if (null == prwc || !generateSegmentConstraintSet (dblSegmentRight, prwc)) return false;

  308.         org.drip.spline.params.SegmentResponseValueConstraint rvcLeading =
  309.             org.drip.spline.params.SegmentResponseValueConstraint.FromPredictorResponsePair
  310.                 (_valParams.valueDate(), _dblEpochResponse);

  311.         if (null == rvcLeading) return false;

  312.         return aLSRM[0].calibrate (rvcLeading, dblLeftSlope, _mapRVSC.get (dblSegmentRight).base(), null ==
  313.             _sbfr ? null : _sbfr.sizeToSegment (aLSRM[0])) && _stretch.markSegmentBuilt (0,
  314.                 prwc.mergeLabelSet());
  315.     }

  316.     @Override public boolean calibSegmentSequence (
  317.         final int iStartingSegment)
  318.     {
  319.         org.drip.spline.segment.LatentStateResponseModel[] aLSRM = _stretch.segments();

  320.         org.drip.state.inference.LatentStateSegmentSpec[] aLSSS = _stretchSpec.segmentSpec();

  321.         int iNumSegment = aLSRM.length;

  322.         if (null == aLSSS || aLSSS.length != iNumSegment) return false;

  323.         for (int iSegment = iStartingSegment; iSegment < iNumSegment; ++iSegment) {
  324.             org.drip.product.definition.CalibratableComponent cfic = aLSSS[iSegment].component();

  325.             if (null == cfic) return false;

  326.             org.drip.state.estimator.PredictorResponseWeightConstraint prwc = cfic.calibPRWC (_valParams,
  327.                 _pricerParams, _csqs, _vcp, aLSSS[iSegment].manifestMeasures());

  328.             double dblSegmentRight = aLSRM[iSegment].right();

  329.             if (null == prwc || !generateSegmentConstraintSet (dblSegmentRight, prwc)) return false;

  330.             if (!aLSRM[iSegment].calibrate (0 == iSegment ? null : aLSRM[iSegment - 1], _mapRVSC.get
  331.                 (dblSegmentRight).base(), null == _sbfr ? null : _sbfr.sizeToSegment (aLSRM[iSegment])) ||
  332.                     !_stretch.markSegmentBuilt (iSegment, prwc.mergeLabelSet()))
  333.                 return false;
  334.         }

  335.         return true;
  336.     }

  337.     @Override public boolean manifestMeasureSensitivity (
  338.         final double dblLeftSlopeSensitivity)
  339.     {
  340.         org.drip.spline.segment.LatentStateResponseModel[] aLSRM = _stretch.segments();

  341.         int iNumSegment = aLSRM.length;

  342.         for (int iSegment = 0; iSegment < iNumSegment; ++iSegment) {
  343.             double dblSegmentRight = aLSRM[iSegment].right();

  344.             org.drip.spline.params.ResponseValueSensitivityConstraint rvsc = _mapRVSC.get (dblSegmentRight);

  345.             java.util.Set<java.lang.String> setstrManifestMeasures = rvsc.manifestMeasures();

  346.             if (null == setstrManifestMeasures || 0 == setstrManifestMeasures.size()) return false;

  347.             for (java.lang.String strManifestMeasure : setstrManifestMeasures) {
  348.                 if (!aLSRM[iSegment].setPreceedingManifestSensitivityControl (strManifestMeasure, getPMSC
  349.                     (strManifestMeasure)))
  350.                     return false;

  351.                 if (0 == iSegment) {
  352.                     if (!aLSRM[0].manifestMeasureSensitivity (strManifestMeasure,
  353.                         org.drip.spline.params.SegmentResponseValueConstraint.FromPredictorResponsePair
  354.                             (_valParams.valueDate(), _dblEpochResponse), rvsc.base(),
  355.                                 dblLeftSlopeSensitivity,
  356.                                     org.drip.spline.params.SegmentResponseValueConstraint.FromPredictorResponsePair
  357.                         (_valParams.valueDate(), 0.), rvsc.manifestMeasureSensitivity (strManifestMeasure),
  358.                             null == _sbfrQuoteSensitivity ? null : _sbfrQuoteSensitivity.sizeToSegment
  359.                                 (aLSRM[0])))
  360.                         return false;
  361.                 } else {
  362.                     if (!aLSRM[iSegment].manifestMeasureSensitivity (aLSRM[iSegment - 1], strManifestMeasure,
  363.                         rvsc.base(), rvsc.manifestMeasureSensitivity (strManifestMeasure), null ==
  364.                             _sbfrQuoteSensitivity ? null : _sbfrQuoteSensitivity.sizeToSegment
  365.                                 (aLSRM[iSegment])))
  366.                         return false;
  367.                 }
  368.             }
  369.         }

  370.         return true;
  371.     }
  372. }