/** \brief Constructor.

      @param[in]     parlist is a parameter list specifying inputs

      parlist should contain sublists "SOL"->"Risk Measure"->"Convex Combination Risk Measure" and
      within the "Convex Combination Risk Measure" sublist should have the following parameters
      \li "Convex Combination Parameters" (greater than 0 and sum to 1)
      \li Sublists labeled 1 to n with risk measure definitions.
  */
  ConvexCombinationRiskMeasure(Teuchos::ParameterList &parlist)
    : RiskMeasure<Real>(), size_(0), firstReset_(true) {
    Teuchos::ParameterList &list
      = parlist.sublist("SOL").sublist("Risk Measure").sublist("Convex Combination Risk Measure");
    // Get convex combination parameters
    Teuchos::Array<Real> lambda
      = Teuchos::getArrayFromStringParameter<Real>(list,"Convex Combination Parameters");
    lambda_ = lambda.toVector();
    size_ = lambda_.size();
    // Build risk measures
    risk_.clear(); risk_.resize(size_,Teuchos::null);
    parlist_.clear(); parlist_.resize(size_);
    for (uint i = 0; i < size_; ++i) {
      std::ostringstream convert;
      convert << i;
      std::string si = convert.str();
      Teuchos::ParameterList &ilist = list.sublist(si);
      std::string name = ilist.get<std::string>("Name");
      parlist_[i].sublist("SOL").sublist("Risk Measure").set("Name",name);
      parlist_[i].sublist("SOL").sublist("Risk Measure").sublist(name) = ilist;
      risk_[i] = RiskMeasureFactory<Real>(parlist_[i]);
    }
    // Check inputs
    checkInputs();
  }
Exemplo n.º 2
0
 // fixed reference date, fixed market data
 CapFloorTermVolSurface::CapFloorTermVolSurface(
                     const Date& settlementDate,
                     const Calendar& calendar,
                     BusinessDayConvention bdc,
                     const std::vector<Period>& optionTenors,
                     const std::vector<Rate>& strikes,
                     const Matrix& vols,
                     const DayCounter& dc)
 : CapFloorTermVolatilityStructure(settlementDate, calendar, bdc, dc),
   nOptionTenors_(optionTenors.size()),
   optionTenors_(optionTenors),
   optionDates_(nOptionTenors_),
   optionTimes_(nOptionTenors_),
   nStrikes_(strikes.size()),
   strikes_(strikes),
   volHandles_(vols.rows()),
   vols_(vols)
 {
     checkInputs();
     initializeOptionDatesAndTimes();
     // fill dummy handles to allow generic handle-based computations later
     for (Size i=0; i<nOptionTenors_; ++i) {
         volHandles_[i].resize(nStrikes_);
         for (Size j=0; j<nStrikes_; ++j)
             volHandles_[i][j] = Handle<Quote>(boost::shared_ptr<Quote>(new
                 SimpleQuote(vols_[i][j])));
     }
     interpolate();
 }
///////////////////////////////////////////////////////////////////////////
// Main entry point to a MEX function
///////////////////////////////////////////////////////////////////////////
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{  
    // Ensure MATLAB's GPU support is available.
    mxInitGPU();

    // Check inputs to mex function
    checkInputs(nrhs, prhs);
     
    // Convert mxArray inputs into OpenCV types
    cv::Ptr<cv::gpu::GpuMat> frame1 = ocvMxGpuArrayToGpuMat_uint8(prhs[0]);
    cv::Ptr<cv::gpu::GpuMat> frame2 = ocvMxGpuArrayToGpuMat_uint8(prhs[1]);

    // Allocate output matrix
    int outRows = frame1->rows ;
    int outCols = frame1->cols ;

    cv::gpu::GpuMat flowx((int)outRows, (int)outCols, CV_32FC1);
    cv::gpu::GpuMat flowy((int)outRows, (int)outCols, CV_32FC1);
    cv::gpu::FarnebackOpticalFlow d_calc;
    // Run the OpenCV template matching routine
    d_calc(*frame1, *frame2, flowx,  flowy);

    // Put the data back into the output MATLAB gpuArray
    plhs[0] = ocvMxGpuArrayFromGpuMat_single(flowx);
    plhs[1] = ocvMxGpuArrayFromGpuMat_single(flowy);
    
}
Exemplo n.º 4
0
// Supports arbitrary batch dimensions for self and A
std::tuple<Tensor,Tensor> gesv(const Tensor& self, const Tensor& A) {
  if (self.dim() <= 2 && A.dim() <= 2) {
    // TODO: #7102: It's not necessary to have gesv (single) bindings for both
    // TH and ATen. We should remove the TH gesv bindings, especially
    // since the lapackGesv function is already in ATen.
    return at::_gesv_single(self, A);
  }

  checkInputs(self, A);

  // broadcast the batch dimensions of self and A.
  IntList self_batch_sizes(self.sizes().data(), self.ndimension() - 2);
  IntList A_batch_sizes(A.sizes().data(), A.ndimension() - 2);
  std::vector<int64_t> expand_batch_portion =
      infer_size(self_batch_sizes, A_batch_sizes);

  std::vector<int64_t> self_expand_size({expand_batch_portion});
  self_expand_size.insert(self_expand_size.end(),
      { self.size(-2), self.size(-1) });

  std::vector<int64_t> A_expand_size({expand_batch_portion});
  A_expand_size.insert(A_expand_size.end(),
      { A.size(-2), A.size(-1) });

  Tensor self_broadcasted  = self.expand(self_expand_size);
  Tensor A_broadcasted = A.expand(A_expand_size);
  return self.type()._gesv_helper(self_broadcasted, A_broadcasted);
}
Exemplo n.º 5
0
  void SQICInternal::evaluate() {
    if (inputs_check_) checkInputs();

    std::copy(input(QP_SOLVER_X0).begin(), input(QP_SOLVER_X0).end(), x_.begin());
    std::fill(x_.begin()+n_, x_.end(), 0);

    std::transform(input(QP_SOLVER_LAM_X0).begin(), input(QP_SOLVER_LAM_X0).end(), rc_.begin(),
                   negate<double>());
    std::fill(rc_.begin()+n_, rc_.end(), 0);

    std::copy(input(QP_SOLVER_LBX).begin(), input(QP_SOLVER_LBX).end(), bl_.begin());
    std::copy(input(QP_SOLVER_UBX).begin(), input(QP_SOLVER_UBX).end(), bu_.begin());

    std::copy(input(QP_SOLVER_LBA).begin(), input(QP_SOLVER_LBA).end(), bl_.begin()+n_);
    std::copy(input(QP_SOLVER_UBA).begin(), input(QP_SOLVER_UBA).end(), bu_.begin()+n_);

    for (int i=0;i<n_+nc_+1;++i) {
      if (bl_[i]==-std::numeric_limits<double>::infinity()) bl_[i]=-inf_;
      if (bu_[i]==std::numeric_limits<double>::infinity()) bu_[i]=inf_;
    }

    formatA_.setInput(input(QP_SOLVER_A), 0);
    formatA_.setInput(input(QP_SOLVER_G), 1);
    formatA_.evaluate();

    sqicSolve(&output(QP_SOLVER_COST).data()[0]);

    std::copy(x_.begin(), x_.begin()+n_, output(QP_SOLVER_X).begin());
    std::transform(rc_.begin(), rc_.begin()+n_, output(QP_SOLVER_LAM_X).begin(), negate<double>());
    std::transform(rc_.begin()+n_, rc_.begin()+n_+nc_, output(QP_SOLVER_LAM_A).begin(),
                   negate<double>());

    output(QP_SOLVER_COST)[0]+= x_[n_+nc_];
  }
Exemplo n.º 6
0
SceneType MainCharacter::animate(Scene &scene, float delta) {
    checkInputs();
    move(scene, delta);
    createTransformationMatrix();

    return scene.sceneType;
}
Exemplo n.º 7
0
 // fixed reference date, floating market data
 SwaptionVolatilityMatrix::SwaptionVolatilityMatrix(
                 const Date& refDate,
                 const Calendar& cal,
                 BusinessDayConvention bdc,
                 const std::vector<Period>& optionT,
                 const std::vector<Period>& swapT,
                 const std::vector<std::vector<Handle<Quote> > >& vols,
                 const DayCounter& dc,
                 const bool flatExtrapolation,
                 const std::vector<std::vector<Real> >& shifts)
 : SwaptionVolatilityDiscrete(optionT, swapT, refDate, cal, bdc, dc),
   volHandles_(vols), shiftValues_(shifts),
   volatilities_(vols.size(), vols.front().size()),
   shifts_(vols.size(), vols.front().size(), 0.0) {
     checkInputs(volatilities_.rows(), volatilities_.columns(),
                 shifts.size(), shifts.size() == 0 ? 0 : shifts.front().size());
     registerWithMarketData();
     if (flatExtrapolation) {
         interpolation_ =
             FlatExtrapolator2D(boost::make_shared<BilinearInterpolation>(
                 swapLengths_.begin(), swapLengths_.end(),
                 optionTimes_.begin(), optionTimes_.end(), volatilities_));
         interpolationShifts_ =
             FlatExtrapolator2D(boost::make_shared<BilinearInterpolation>(
                 swapLengths_.begin(), swapLengths_.end(),
                 optionTimes_.begin(), optionTimes_.end(), shifts_));
     } else {
         interpolation_ = BilinearInterpolation(
             swapLengths_.begin(), swapLengths_.end(), optionTimes_.begin(),
             optionTimes_.end(), volatilities_);
         interpolationShifts_ = BilinearInterpolation(
             swapLengths_.begin(), swapLengths_.end(), optionTimes_.begin(),
             optionTimes_.end(), shifts_);
     }
 }
    /** \brief Constructor.

        @param[in]     parlist is a parameter list specifying inputs

        parlist should contain sublists "SOL"->"Risk Measures"->"Exponential Utility"
        and withing the "Exponential Utility" sublist should have
        \li "Rate" (greater than 0).
    */
    ExpUtility(Teuchos::ParameterList &parlist)
        : RiskMeasure<Real>(), firstReset_(true) {
        Teuchos::ParameterList &list
            = parlist.sublist("SOL").sublist("Risk Measure").sublist("Exponential Utility");
        coeff_ = list.get<Real>("Rate");
        checkInputs();
    }
  /** \brief Constructor.

      @param[in]     parlist is a parameter list specifying inputs

      parlist should contain sublists "SOL"->"Risk Measures"->"Log-Exponential Quadrangle"
      and withing the "Log-Exponential Quadrangle" sublist should have
      \li "Rate" (greater than 0). 
  */
  LogExponentialQuadrangle(Teuchos::ParameterList &parlist)
    : ExpectationQuad<Real>() {
    Teuchos::ParameterList &list
      = parlist.sublist("SOL").sublist("Risk Measure").sublist("Log-Exponential Quadrangle");
    coeff_ = list.get<Real>("Rate");
    checkInputs();
  }
stList *getMatchingWithCyclicConstraints(stSortedSet *nodes,
        stList *adjacencyEdges, stList *stubEdges, stList *chainEdges,
        bool makeStubCyclesDisjoint,
        stList *(*matchingAlgorithm)(stList *edges, int64_t nodeNumber)) {
    /*
     * Check the inputs.
     */
    checkInputs(nodes, adjacencyEdges, stubEdges, chainEdges);
    st_logDebug("Checked the inputs\n");

    if (stSortedSet_size(nodes) == 0) { //Some of the following functions assume there are at least 2 nodes.
        return stList_construct();
    }

    stList *chosenEdges = getPerfectMatching(nodes, adjacencyEdges, matchingAlgorithm);

    stSortedSet *allAdjacencyEdges = stList_getSortedSet(adjacencyEdges,
                (int(*)(const void *, const void *)) stIntTuple_cmpFn);
    stList *nonZeroWeightAdjacencyEdges = getEdgesWithGreaterThanZeroWeight(
                    adjacencyEdges);

    stList *updatedChosenEdges = makeMatchingObeyCyclicConstraints(nodes, chosenEdges, allAdjacencyEdges, nonZeroWeightAdjacencyEdges, stubEdges, chainEdges, makeStubCyclesDisjoint);
    stList_destruct(chosenEdges);
    chosenEdges = updatedChosenEdges;

    stList_destruct(nonZeroWeightAdjacencyEdges);
    stSortedSet_destruct(allAdjacencyEdges);

    return chosenEdges;
}
Exemplo n.º 11
0
    // floating reference date, fixed market data
    SwaptionVolatilityHullWhite::SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,
                        const Calendar& cal,
                        BusinessDayConvention bdc,
                        const std::vector<Period>& optionT,
                        const std::vector<Period>& swapT,
                        const Matrix& vols,
                        const DayCounter& dc)
    : reversion_(reversion),yts_(yts),indexBase_(indexBase),SwaptionVolatilityDiscrete(optionT, swapT, 0, cal, bdc, dc),
      volHandles_(vols.rows()),
      hwsigmas_(vols.rows(), vols.columns()),
	  volatilities_(vols.rows(), vols.columns()) {

        checkInputs(vols.rows(), vols.columns());

        // fill dummy handles to allow generic handle-based
        // computations later on
        for (Size i=0; i<vols.rows(); ++i) {
            volHandles_[i].resize(vols.columns());
            for (Size j=0; j<vols.columns(); ++j)
                volHandles_[i][j] = Handle<Quote>(boost::shared_ptr<Quote>(new
                    SimpleQuote(vols[i][j])));
        }
        interpolation_ =
            BilinearInterpolation(swapLengths_.begin(), swapLengths_.end(),
                                  optionTimes_.begin(), optionTimes_.end(),
                                  volatilities_);
		interpolationSigma_ =
			BilinearInterpolation(swapLengths_.begin(), swapLengths_.end(),
                                  optionTimes_.begin(), optionTimes_.end(),
                                  hwsigmas_);
    }
Exemplo n.º 12
0
 // fixed reference date, floating market data
 CapFloorTermVolSurface::CapFloorTermVolSurface(
                     const Date& settlementDate,
                     const Calendar& calendar,
                     BusinessDayConvention bdc,
                     const std::vector<Period>& optionTenors,
                     const std::vector<Rate>& strikes,
                     const std::vector<std::vector<Handle<Quote> > >& vols,
                     const DayCounter& dc)
 : CapFloorTermVolatilityStructure(settlementDate, calendar, bdc, dc),
   nOptionTenors_(optionTenors.size()),
   optionTenors_(optionTenors),
   optionDates_(nOptionTenors_),
   optionTimes_(nOptionTenors_),
   nStrikes_(strikes.size()),
   strikes_(strikes),
   volHandles_(vols),
   vols_(vols.size(), vols[0].size())
 {
     checkInputs();
     initializeOptionDatesAndTimes();
     for (Size i=0; i<nOptionTenors_; ++i)
         QL_REQUIRE(volHandles_[i].size()==nStrikes_,
                    io::ordinal(i+1) << " row of vol handles has size " <<
                    volHandles_[i].size() << " instead of " << nStrikes_);
     registerWithMarketData();
     for (Size i=0; i<vols_.rows(); ++i)
         for (Size j=0; j<vols_.columns(); ++j)
             vols_[i][j] = volHandles_[i][j]->value();
     interpolate();
 }
Exemplo n.º 13
0
    // fixed reference date, fixed market data
    SwaptionVolatilityMatrix::SwaptionVolatilityMatrix(
                        const Date& refDate,
                        const Calendar& cal,
                        BusinessDayConvention bdc,
                        const std::vector<Period>& optionT,
                        const std::vector<Period>& swapT,
                        const Matrix& vols,
                        const DayCounter& dc)
    : SwaptionVolatilityDiscrete(optionT, swapT, refDate, cal, bdc, dc),
      volHandles_(vols.rows()),
      volatilities_(vols.rows(), vols.columns()) {

        checkInputs(vols.rows(), vols.columns());

        // fill dummy handles to allow generic handle-based
        // computations later on
        for (Size i=0; i<vols.rows(); ++i) {
            volHandles_[i].resize(vols.columns());
            for (Size j=0; j<vols.columns(); ++j)
                volHandles_[i][j] = Handle<Quote>(boost::shared_ptr<Quote>(new
                    SimpleQuote(vols[i][j])));
        }
        interpolation_ =
            BilinearInterpolation(swapLengths_.begin(), swapLengths_.end(),
                                  optionTimes_.begin(), optionTimes_.end(),
                                  volatilities_);
    }
 MixedQuantileQuadrangle(const std::vector<Real> &prob,
                         const std::vector<Real> &coeff,
                         const Teuchos::RCP<PlusFunction<Real> > &pf )
   : RiskMeasure<Real>(), plusFunction_(pf), prob_(prob), coeff_(coeff), firstReset_(true) {
   checkInputs();
   initialize();
 }
Exemplo n.º 15
0
 // floating reference date, floating market data
 AbcdAtmVolCurve::AbcdAtmVolCurve(
         Natural settlDays,
         const Calendar& cal,
         const std::vector<Period>& optionTenors,
         const std::vector<Handle<Quote> >& volsHandles,
         const std::vector<bool> inclusionInInterpolationFlag,
         BusinessDayConvention bdc,
         const DayCounter& dc)
 : BlackAtmVolCurve(settlDays, cal, bdc, dc),
   nOptionTenors_(optionTenors.size()),
   optionTenors_(optionTenors),
   optionDates_(nOptionTenors_),
   optionTimes_(nOptionTenors_),
   actualOptionTimes_(nOptionTenors_),
   volHandles_(volsHandles),
   vols_(volsHandles.size()),
   actualVols_(volsHandles.size()),
   inclusionInInterpolation_(inclusionInInterpolationFlag),
   interpolation_(boost::shared_ptr<AbcdInterpolation>()) // do not initialize with nOptionTenors_
 {
     checkInputs();
     initializeOptionDatesAndTimes();
     initializeVolatilities();
     registerWithMarketData();
     for (Size i=0; i<vols_.size(); ++i)
         vols_[i] = volHandles_[i]->value();
     interpolate();
 }
 SingletonKusuoka( const std::vector<Real> &pts, const std::vector<Real> &wts,
                   const Teuchos::RCP<PlusFunction<Real> > &pf)
   : RiskMeasure<Real>() {
   buildMixedQuantile(pts,wts,pf);
   // Check inputs
   checkInputs();
 }
Exemplo n.º 17
0
  /** \brief Constructor.

      @param[in]     parlist is a parameter list specifying inputs

      parlist should contain sublists "SOL"->"Risk Measure"->"Mean-Variance Quadrangle" and
      within the "Mean-Variance Quadrangle" sublist should have the following parameters
      \li "Coefficient" (array of positive scalars).
  */
  MeanVarianceQuadrangle(Teuchos::ParameterList &parlist)
    : ExpectationQuad<Real>() {
    Teuchos::ParameterList &list
      = parlist.sublist("SOL").sublist("Risk Measure").sublist("Mean-Variance Quadrangle");
    coeff_ = list.get<Real>("Coefficient");
    checkInputs();
  }
 SuperQuantileQuadrangle(const Real alpha,
                         const int nQuad,
                         const Teuchos::RCP<PlusFunction<Real> > &pf,
                         const bool useGauss = true)
   : SpectralRisk<Real>(), plusFunction_(pf),
     alpha_(alpha), nQuad_(nQuad), useGauss_(useGauss) {
   // Check inputs
   checkInputs();
   initialize();
 }
 QuantileRadiusQuadrangle( Teuchos::ParameterList &parlist )
   : RiskMeasure<Real>(), firstReset_(true) {
   Teuchos::ParameterList &list
     = parlist.sublist("SOL").sublist("Risk Measure").sublist("Quantile-Radius Quadrangle");
   // Grab probability and coefficient arrays
   prob_  = list.get<Real>("Confidence Level");
   coeff_ = list.get<Real>("Coefficient");
   // Build (approximate) plus function
   plusFunction_ = Teuchos::rcp(new PlusFunction<Real>(list));
   checkInputs();
   initialize();
 }
 SingletonKusuoka( const Teuchos::RCP<Distribution<Real> > &dist,
                   const int nQuad,
                   const Teuchos::RCP<PlusFunction<Real> > &pf)
   : RiskMeasure<Real>() {
   // Build generalized trapezoidal rule
   std::vector<Real> wts(nQuad), pts(nQuad);
   buildQuadFromDist(pts,wts,nQuad,dist);
   // Build mixed quantile quadrangle risk measure
   buildMixedQuantile(pts,wts,pf);
   // Check inputs
   checkInputs(dist);
 }
Exemplo n.º 21
0
 CVaR( Teuchos::ParameterList &parlist )
   : RiskMeasure<Real>(), xvar_(0), vvar_(0), firstReset_(true) {
   Teuchos::ParameterList &list
     = parlist.sublist("SOL").sublist("Risk Measure").sublist("CVaR");
   // Check CVaR inputs
   prob_  = list.get<Real>("Confidence Level");
   coeff_ = list.get<Real>("Convex Combination Parameter");
   // Build (approximate) plus function
   plusFunction_ = Teuchos::rcp(new PlusFunction<Real>(list));
   // Check Inputs
   checkInputs();
 }
Exemplo n.º 22
0
  /** \brief Constructor.

      @param[in]     parlist is a parameter list specifying inputs

      parlist should contain sublists "SOL"->"Risk Measures"->"Log-Quantile Quadrangle"
      and withing the "Log-Quantile Quadrangle" sublist should have
      \li "Slope for Linear Growth" (between 0 and 1)
      \li "Rate for Exponential Growth" (must be positive)
      \li "Smoothing Parameter" (must be positive)
      \li A sublist for plus function information.
  */
  LogQuantileQuadrangle(Teuchos::ParameterList &parlist)
    : ExpectationQuad<Real>() {
    Teuchos::ParameterList& list
      = parlist.sublist("SOL").sublist("Risk Measure").sublist("Log-Quantile Quadrangle");
    // Check CVaR inputs
    alpha_  = list.get<Real>("Slope for Linear Growth");
    rate_   = list.get<Real>("Rate for Exponential Growth");
    eps_    = list.get<Real>("Smoothing Parameter");
    // Build plus function
    pf_ = Teuchos::rcp( new PlusFunction<Real>(list) );
    checkInputs();
  }
 MixedQuantileQuadrangle( Teuchos::ParameterList &parlist )
   : RiskMeasure<Real>(), firstReset_(true) {
   Teuchos::ParameterList &list
     = parlist.sublist("SOL").sublist("Risk Measure").sublist("Mixed-Quantile Quadrangle");
   // Grab probability and coefficient arrays
   prob_  = Teuchos::getArrayFromStringParameter<Real>(list,"Probability Array");
   coeff_ = Teuchos::getArrayFromStringParameter<Real>(list,"Coefficient Array");
   plusFunction_ = Teuchos::rcp(new PlusFunction<Real>(list));
   // Check inputs
   checkInputs();
   initialize();
 }
Exemplo n.º 24
0
 LogQuantileQuadrangle(Teuchos::ParameterList &parlist)
   : ExpectationQuad<Real>() {
   Teuchos::ParameterList& list
     = parlist.sublist("SOL").sublist("Risk Measure").sublist("Log-Quantile Quadrangle");
   // Check CVaR inputs
   prob_  = list.get<Real>("Confidence Level");
   scale_ = list.get<Real>("Growth Constant");
   eps_   = list.get<Real>("Smoothing Parameter");
   // Build plus function
   pf_ = Teuchos::rcp( new PlusFunction<Real>(list) );
   checkInputs();
 }
Exemplo n.º 25
0
 QuantileQuadrangle(Teuchos::ParameterList &parlist) : ExpectationQuad<Real>() {
   Teuchos::ParameterList& list
     = parlist.sublist("SOL").sublist("Risk Measure").sublist("Quantile-Based Quadrangle");
   // Get CVaR parameters
   prob_ = list.get<Real>("Confidence Level");
   lam_  = list.get<Real>("Convex Combination Parameter");
   eps_  = list.get<Real>("Smoothing Parameter");
   // Build plus function
   pf_   = Teuchos::rcp( new PlusFunction<Real>(list) );
   // Check inputs
   checkInputs();
   setParameters();
 }
 SuperQuantileQuadrangle( Teuchos::ParameterList &parlist )
   : SpectralRisk<Real>() {
   Teuchos::ParameterList &list
     = parlist.sublist("SOL").sublist("Risk Measure").sublist("Super Quantile Quadrangle");
   // Grab confidence level and quadrature order
   alpha_ = list.get<Real>("Confidence Level");
   nQuad_ = list.get("Number of Quadrature Points",5);
   useGauss_ = list.get("Use Gauss-Legendre Quadrature",true);
   plusFunction_ = Teuchos::rcp(new PlusFunction<Real>(list));
   // Check inputs
   checkInputs();
   initialize();
 }
Exemplo n.º 27
0
    // fixed reference date, fixed market data
    SwaptionVolatilityMatrix::SwaptionVolatilityMatrix(
                        const Date& refDate,
                        const Calendar& cal,
                        BusinessDayConvention bdc,
                        const std::vector<Period>& optionT,
                        const std::vector<Period>& swapT,
                        const Matrix& vols,
                        const DayCounter& dc,
                        const bool flatExtrapolation,
                        const VolatilityType type,
                        const Matrix& shifts)
    : SwaptionVolatilityDiscrete(optionT, swapT, refDate, cal, bdc, dc),
      volHandles_(vols.rows()), shiftValues_(vols.rows()),
      volatilities_(vols.rows(), vols.columns()),
      shifts_(shifts.rows(), shifts.columns(), 0.0), volatilityType_(type) {

        checkInputs(vols.rows(), vols.columns(), shifts.rows(), shifts.columns());

        // fill dummy handles to allow generic handle-based
        // computations later on
        for (Size i=0; i<vols.rows(); ++i) {
            volHandles_[i].resize(vols.columns());
            shiftValues_[i].resize(vols.columns());
            for (Size j=0; j<vols.columns(); ++j) {
                volHandles_[i][j] = Handle<Quote>(boost::shared_ptr<Quote>(new
                    SimpleQuote(vols[i][j])));
                shiftValues_[i][j] = shifts.rows() > 0 ? shifts[i][j] : 0.0;
            }
        }
        if (flatExtrapolation) {
            interpolation_ =
                FlatExtrapolator2D(boost::make_shared<BilinearInterpolation>(
                    swapLengths_.begin(), swapLengths_.end(),
                    optionTimes_.begin(), optionTimes_.end(), volatilities_));
            interpolationShifts_ =
                FlatExtrapolator2D(boost::make_shared<BilinearInterpolation>(
                    swapLengths_.begin(), swapLengths_.end(),
                    optionTimes_.begin(), optionTimes_.end(), shifts_));
        } else {
            interpolation_ = BilinearInterpolation(
                swapLengths_.begin(), swapLengths_.end(), optionTimes_.begin(),
                optionTimes_.end(), volatilities_);
            interpolationShifts_ = BilinearInterpolation(
                swapLengths_.begin(), swapLengths_.end(), optionTimes_.begin(),
                optionTimes_.end(), shifts_);
        }
    }
Exemplo n.º 28
0
  // floating reference date, floating market data
  SwaptionVolatilityMatrix::SwaptionVolatilityMatrix(
                  const Calendar& cal,
                  BusinessDayConvention bdc,
                  const std::vector<Period>& optionT,
                  const std::vector<Period>& swapT,
                  const std::vector<std::vector<Handle<Quote> > >& vols,
                  const DayCounter& dc)
  : SwaptionVolatilityDiscrete(optionT, swapT, 0, cal, bdc, dc),
    volHandles_(vols),
    volatilities_(vols.size(), vols.front().size()) {
      checkInputs(volatilities_.rows(), volatilities_.columns());
      registerWithMarketData();
      interpolation_ =
          BilinearInterpolation(swapLengths_.begin(), swapLengths_.end(),
                                optionTimes_.begin(), optionTimes_.end(),
                                volatilities_);
 }
 SingletonKusuoka(Teuchos::ParameterList &parlist)
   : RiskMeasure<Real>() {
   // Parse parameter list
   Teuchos::ParameterList &list
     = parlist.sublist("SOL").sublist("Risk Measure").sublist("Singleton Kusuoka");
   int nQuad = list.get("Number of Quadrature Points",5);
   // Build distribution
   Teuchos::RCP<Distribution<Real> > dist = DistributionFactory<Real>(list);
   // Build plus function approximation
   Teuchos::RCP<PlusFunction<Real> > pf = Teuchos::rcp(new PlusFunction<Real>(list));
   // Build generalized trapezoidal rule
   std::vector<Real> wts(nQuad), pts(nQuad);
   buildQuadFromDist(pts,wts,nQuad,dist);
   // Build mixed quantile quadrangle risk measure
   buildMixedQuantile(pts,wts,pf);
   // Check inputs
   checkInputs(dist);
 }
PoseVelocityState RK4Integrator::calcStates(const PoseVelocityState &states, const base::Vector6d &control_input)
{
    checkInputs(states, control_input);
    PoseVelocityState system_states = states;

    // Runge-Kuta coefficients
    PoseVelocityState k1 = deriv(system_states, control_input);
    PoseVelocityState k2 = deriv(system_states + ((integration_step/2)*k1), control_input);
    PoseVelocityState k3 = deriv(system_states + ((integration_step/2)*k2), control_input);
    PoseVelocityState k4 = deriv(system_states + (integration_step*k3), control_input);

    // Calculating the system states
    system_states += (integration_step/6)*(k1 + 2*k2 + 2*k3 + k4);

    //Brute force normalization of quaternions due the RK4 integration.
    system_states.orientation.normalize();

    return system_states;
}