Example #1
0
RcppExport SEXP jointLabelFusionNeighborhoodSearch( SEXP r_intvec, SEXP r_cent, SEXP r_rad, SEXP r_radSearch, SEXP r_antsimage, SEXP r_antsimageseg  )
{
try
{
  Rcpp::S4 antsimage( r_antsimage );
  std::string pixeltype =
    Rcpp::as< std::string >( antsimage.slot( "pixeltype" ) );
  unsigned int dimension = Rcpp::as< int >( antsimage.slot( "dimension" ) );
  if ( ( pixeltype == "float" ) & ( dimension == 2 ) )
  {
    typedef float PixelType;
    const unsigned int dim = 2;
    typedef itk::Image< PixelType, dim >  ImageType;
    SEXP out = jointLabelFusionNeighborhoodSearchHelper< ImageType>(
      r_intvec, r_cent,
      Rcpp::as< unsigned int >( r_rad ),
      Rcpp::as< unsigned int >( r_radSearch ),
      r_antsimage, r_antsimageseg // atlas
      );
    return( out );
  }
  else if ( ( pixeltype == "float" ) & ( dimension == 3 ) )
  {
    typedef float PixelType;
    const unsigned int dim = 3;
    typedef itk::Image< PixelType, dim >  ImageType;
    SEXP out = jointLabelFusionNeighborhoodSearchHelper< ImageType>(
      r_intvec, r_cent,
      Rcpp::as< unsigned int >( r_rad ),
      Rcpp::as< unsigned int >( r_radSearch ),
      r_antsimage, r_antsimageseg  // atlas
      );
    return( out );
  }
  else
  {
    Rcpp::stop( "Unsupported image dimension or pixel type." );
  }
}
catch( itk::ExceptionObject & err )
{
  Rcpp::Rcout << "ITK ExceptionObject caught!" << std::endl;
  forward_exception_to_r( err );
}
catch( const std::exception& exc )
{
  Rcpp::Rcout << "STD ExceptionObject caught!" << std::endl;
  forward_exception_to_r( exc );
}
catch( ... )
{
  Rcpp::stop( "C++ exception (unknown reason)");
}
 return Rcpp::wrap(NA_REAL); // not reached
}
Example #2
0
RcppExport SEXP CreateCenters(SEXP d) {

    try {
	Rcpp::NumericVector rdata(d);
	int colNum = rdata.size();

	flann::Matrix<float> input(new float[colNum], 1,  colNum);

	for (int i = 0; i  < colNum; i++) {
	    input[0][i] = rdata(i);
	}
	flann::Index<flann::L2<float> >* index = new flann::Index<flann::L2<float> >(input,flann::KDTreeSingleIndexParams());

	index->buildIndex();

	Rcpp::XPtr< flann::Index<flann::L2<float> > > p(index, true);

	return p; // -Wall

    } catch( std::exception &ex ) {		// or use END_RCPP macro
	forward_exception_to_r( ex );
    } catch(...) {
	::Rf_error( "c++ exception (unknown reason)" );
    }
    return R_NilValue; // -Wall
}
Example #3
0
RcppExport SEXP holidayList(SEXP calSexp, SEXP params) {

    try {
        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(calSexp)) );
        Rcpp::List rparam(params);
        int iw = Rcpp::as<int>(rparam["includeWeekends"]);
        std::vector<QuantLib::Date> 
            holidays = QuantLib::Calendar::holidayList(*pcal,
                                                       QuantLib::Date(dateFromR(Rcpp::as<Rcpp::Date>( rparam["from"]))), 
                                                       QuantLib::Date(dateFromR(Rcpp::as<Rcpp::Date>( rparam["to"] ))), 
                                                       iw == 1 ? true : false);                

        if (holidays.size() > 0) {
            Rcpp::DateVector dv( holidays.size() );
            for (unsigned int i = 0; i< holidays.size(); i++){
                dv[i] = Rcpp::Date(holidays[i].month(), holidays[i].dayOfMonth(), holidays[i].year());
            }
            return Rcpp::wrap(dv);
        } else {
            return R_NilValue;
        }

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
Example #4
0
RcppExport SEXP DeserializeFlann(SEXP x,SEXP m) {
    try {

	Rcpp::XPtr< flann::Index<flann::L2<float> >  > oldindex(x);
	if(oldindex)
	    return x;

	if(Rf_isNull(m))
	    ::Rf_error("Please serialize");  

	Rcpp::NumericMatrix dataset(m);

	flann::Matrix<float> input(new float[dataset.nrow()*dataset.ncol()], dataset.nrow(),  dataset.ncol());

	//#pragma omp parallel for
	for( int j = 0; j < dataset.nrow(); j++) {
	    for (int i = 0; i  < dataset.ncol(); i++) 
		input[j][i] = dataset(j,i);
	}

	flann::Index<flann::L2<float> >* index = new flann::Index<flann::L2<float> >(input,flann::KDTreeSingleIndexParams());

	index->buildIndex();

	Rcpp::XPtr< flann::Index<flann::L2<float> > > p(index, true);

	return p; // -Wall

    } catch( std::exception &ex ) {    // or use END_RCPP macro
	forward_exception_to_r( ex );
    } catch(...) {
	::Rf_error( "c++ exception (unknown reason)" );
    }
    return R_NilValue; // -Wall
}
Example #5
0
RcppExport SEXP advance2(SEXP calSexp, SEXP param, SEXP dateSexp){

    try {
        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(calSexp)) );
        Rcpp::List rparam(param);        
        QuantLib::BusinessDayConvention bdc = getBusinessDayConvention( Rcpp::as<double>(rparam["bdc"]) );
        double emr = Rcpp::as<double>(rparam["emr"]);
        double period = Rcpp::as<double>(rparam["period"]);

        Rcpp::DateVector dates  = Rcpp::DateVector(dateSexp);
        int n = dates.size();
        std::vector<QuantLib::Date> advance(n);

        for (int i=0; i<n; i++) {
            QuantLib::Date day( dateFromR(dates[i]) );
            advance[i] = pcal->advance(day, QuantLib::Period(getFrequency(period)), 
                                       bdc, (emr == 1)?true:false );
            dates[i] =  Rcpp::Date(advance[i].month(), 
                                   advance[i].dayOfMonth(), 
                                   advance[i].year());
        }

        return Rcpp::wrap(dates);

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
Example #6
0
RcppExport SEXP businessDaysBetween(SEXP calSexp, SEXP params,
                                       SEXP from, SEXP to){

    try {
        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(calSexp)) );
        Rcpp::List rparam(params);
        double ifirst = Rcpp::as<double>(rparam["includeFirst"]);
        double ilast = Rcpp::as<double>(rparam["includeLast"]);

        Rcpp::DateVector dates1  = Rcpp::DateVector(from);
        Rcpp::DateVector dates2  = Rcpp::DateVector(to);

        int n = dates1.size();
        std::vector<double> between(n);

        for (int i=0; i<n; i++) {
            QuantLib::Date day1( dateFromR(dates1[i]) );
            QuantLib::Date day2( dateFromR(dates2[i]) );
            between[i] = pcal->businessDaysBetween(day1, day2,
                                                   (ifirst == 1) ? true: false,
                                                   (ilast == 1) ? true: false);
        }
        
        return Rcpp::wrap(between);

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
Example #7
0
RcppExport SEXP adjust(SEXP calSexp, SEXP bdcSEXP, SEXP dateSexp){

    try {
        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(calSexp)) );
        QuantLib::BusinessDayConvention bdc = getBusinessDayConvention( Rcpp::as<double>(bdcSEXP) );
        Rcpp::DateVector dates  = Rcpp::DateVector(dateSexp);
        int n = dates.size();
        std::vector<QuantLib::Date> adjusted(n);

        for (int i=0; i<n; i++) {
            QuantLib::Date day( dateFromR(dates[i]) );
            adjusted[i] = pcal->adjust(day, bdc);
            dates[i] =  Rcpp::Date(adjusted[i].month(), 
                                   adjusted[i].dayOfMonth(), 
                                   adjusted[i].year());
        }

        return Rcpp::wrap(dates);

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
Example #8
0
RcppExport SEXP endOfMonth(SEXP calSexp, SEXP dateSexp){

    try {
        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(calSexp)) );

        Rcpp::DateVector dates  = Rcpp::DateVector(dateSexp);
        int n = dates.size();
        std::vector<QuantLib::Date> eom(n);

        for (int i=0; i<n; i++) {
            QuantLib::Date day( dateFromR(dates[i]) );
            eom[i] = pcal->endOfMonth(day);
            dates[i] = Rcpp::Date(eom[i].month(), eom[i].dayOfMonth(), eom[i].year());
        }
       
        return Rcpp::wrap(dates);

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
Example #9
0
RcppExport SEXP AddPoint(SEXP x,SEXP d) {

    try {
	Rcpp::XPtr< flann::Index<flann::L2<float> > > index(x);
	Rcpp::NumericVector rdata(d);
	int colNum = rdata.size();

	flann::Matrix<float> input(new float[colNum], 1,  colNum);

	for (int i = 0; i  < colNum; i++) {
	    input[0][i] = rdata(i);
	}

	index->addPoints(input);

	return R_NilValue; // -Wall


    } catch( std::exception &ex ) {		// or use END_RCPP macro
	forward_exception_to_r( ex );
    } catch(...) {
	::Rf_error( "c++ exception (unknown reason)" );
    }
    return R_NilValue; // -Wall
}
Example #10
0
RcppExport SEXP yearFraction(SEXP startDates, SEXP endDates, SEXP dayCounter){

    try {
        
        Rcpp::DateVector s = Rcpp::DateVector(startDates);
        Rcpp::DateVector e = Rcpp::DateVector(endDates);
        
		Rcpp::NumericVector dc(dayCounter);
        int n = dc.size();
        std::vector<double> result(n);
        for (int i=0; i< n; i++){
            QuantLib::Date d1( dateFromR(s[i]) );
            QuantLib::Date d2( dateFromR(e[i]) );            
            QuantLib::DayCounter counter = getDayCounter(dc[i]);
            result[i] = (double)counter.yearFraction(d1, d2);            
        }        
        return Rcpp::wrap(result);

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
Example #11
0
SEXP mdmr_fstats_to_pvals(SEXP SFmat)
{
    try {
        arma::mat Fmat(1,1);
        const double* old_fptr = sbm_to_arma_xd(SFmat, Fmat);
        
        double nvoxs = static_cast<double>(Fmat.n_cols);
        double nperms = static_cast<double>(Fmat.n_rows);
        
        Rcpp::NumericVector pvals(nvoxs);
        
        // original F-stats
        arma::rowvec realFs = Fmat.row(0);
        
        double i;
        for (i = 0; i < nvoxs; ++i)
        {
            pvals[i] = arma::as_scalar(arma::sum(Fmat.col(i) >= realFs(i))/nperms);
        }
        
        free_arma(Fmat, old_fptr);
        
        return Rcpp::wrap( pvals );;
    } catch(std::exception &ex) {
        forward_exception_to_r(ex);
    } catch(...) {
        ::Rf_error("c++ exception (unknown reason)");
    }
    
    return R_NilValue;
}
Example #12
0
RcppExport SEXP fsl2antsrTransform( SEXP r_matrix, SEXP r_reference, SEXP r_moving, SEXP r_flag )
{
try
{
  Rcpp::S4 reference( r_reference );
  //Rcpp::S4 moving( r_moving );
  std::string pixeltype = Rcpp::as<std::string>(reference.slot("pixeltype"));
  unsigned int dimension = Rcpp::as<unsigned int>(reference.slot("dimension"));
  short flag = Rcpp::as<short>(r_flag);

  if ( dimension != 3 )
    {
    Rcpp::stop("Only 3D transforms are supported");
    }

  if ( pixeltype == "double" )
    {
    return ( fsl2antsrTransform<double,3>(r_matrix, r_reference, r_moving, flag) );
    }
  else if ( pixeltype == "float" )
    {
    return( fsl2antsrTransform<float,3>(r_matrix, r_reference, r_moving, flag) );
    }
  else if ( pixeltype == "unsigned int" )
    {
    return( fsl2antsrTransform<unsigned int,3>(r_matrix, r_reference, r_moving, flag) );
    }
  else if ( pixeltype == "unsigned char" )
    {
    return( fsl2antsrTransform<unsigned char,3>(r_matrix, r_reference, r_moving, flag) );
    }
  else
    {
    Rcpp::stop("Unsupported pixel type");
    }

  // never reached
  return( Rcpp::wrap(NA_REAL) );

}
catch( itk::ExceptionObject & err )
  {
  Rcpp::Rcout << "ITK ExceptionObject caught !" << std::endl;
  Rcpp::Rcout << err << std::endl;
  Rcpp::stop("ITK exception caught");
  }
catch( const std::exception& exc )
  {
  forward_exception_to_r( exc ) ;
  }
catch(...)
  {
	Rcpp::stop("c++ exception (unknown reason)");
  }
return Rcpp::wrap(NA_REAL); //not reached
}
Example #13
0
void bvarcnw_R::build_R(const arma::mat& data_raw, bool cons_term_inp, int p_inp)
{
    try {
        this->build(data_raw,cons_term_inp,p_inp);
    } catch( std::exception &ex ) {
        forward_exception_to_r( ex );
    } catch(...) {
        ::Rf_error( "BMR: C++ exception (unknown reason)" );
    }
}
Example #14
0
void bvarcnw_R::gibbs_R(int n_draws)
{
    try {
        this->gibbs(n_draws);
    } catch( std::exception &ex ) {
        forward_exception_to_r( ex );
    } catch(...) {
        ::Rf_error( "BMR: C++ exception (unknown reason)" );
    }
}
Example #15
0
void bvarcnw_R::reset_draws_R()
{
    try {
        this->reset_draws();
    } catch( std::exception &ex ) {
        forward_exception_to_r( ex );
    } catch(...) {
        ::Rf_error( "BMR: C++ exception (unknown reason)" );
    }
}
Example #16
0
void bvarcnw_R::prior_R(const arma::vec& coef_prior, double HP_1_inp, double HP_3_inp, 
                        int gamma, bool full_cov_prior)
{
    try {
        this->prior(coef_prior,HP_1_inp,HP_3_inp,gamma,full_cov_prior);
    } catch( std::exception &ex ) {
        forward_exception_to_r( ex );
    } catch(...) {
        ::Rf_error( "BMR: C++ exception (unknown reason)" );
    }
} 
Example #17
0
/* C++ | R INTERFACE; main function */
RcppExport SEXP cophen (SEXP tree) 
{
	/* 
	 * tree: a list of elements 
		* ROOT: most internal node
		* MAXNODE: least internal internal node (and largest valued in edge matrix)
		* ENDOFCLADE: rows in edge matrix
		* ANC: first column of 'phylo' edge matrix (e.g., phy$edge[,1])
		* DES: second column of 'phylo' edge matrix (e.g., phy$edge[,2])
		* EDGES: edge lengths, sorted by node label and including the root (at position Ntip(phy)+1)
		* COPHEN: the current state of the variance-covariance matrix, initialized with 0s in R
	 */
		
	try {
		std::vector<int>::size_type i;
		
		/* call in parameters associated with 'phylo' object */
		Rcpp::List phylo(tree);

		int root = (int) Rcpp::as<int>(phylo["ROOT"]);
		int maxnode =  Rcpp::as<int>(phylo["MAXNODE"]);
		int endofclade =  Rcpp::as<int>(phylo["ENDOFCLADE"]);
		std::vector<int> anc=phylo["ANC"];
		std::vector<int> des=phylo["DES"];
		std::vector<double> unsortededges=phylo["EDGES"];
		std::vector<double> edges=phylo["EDGES"];
		std::vector<double> V=phylo["COPHEN"];
		std::vector<double> cophen=V;
		
		/* initialize edges */
		for(i=0; i<edges.size(); i++) {
			edges.at(i)=0;
		}		
		
		/* sort edges by node label */
		sortedges(unsortededges, edges, des);
		
		/* call to primary function that updates VCV matrix */
		vcv_internal(maxnode, root, endofclade, anc, des, edges, V);
		
		/* call to converter function for VCV to COPHENETIC */
		vcv_to_cophenetic(root, V, cophen);
		
		/* PREPARE OUTPUT FOR R */
		return Rcpp::List::create(Rcpp::Named("COPHEN",cophen));


    } catch( std::exception &ex ) {		
		forward_exception_to_r( ex );
    } catch(...) { 
		::Rf_error( "C++ exception: unknown reason" ); 
    }
    return R_NilValue; 
}
Example #18
0
RcppExport SEXP GetAllPoints(SEXP x,SEXP n,SEXP c) {

    try {
	Rcpp::XPtr< flann::Index<flann::L2<float> >  > index(x);
	Rcpp::NumericVector npoints(n);
	Rcpp::NumericVector cn(c);
	int colNum = cn[0];

	float *data = new float[colNum];
	
	for(int i=0;i<colNum;i++) {
	    data[i] = 0;
	    i++;
	}

	flann::Matrix<float> dataset = flann::Matrix<float>(data,1,colNum);

	delete [] data;

	std::vector< std::vector<int> > indices;
	std::vector< std::vector<float> > dists;

	index->knnSearch(dataset,indices,dists,npoints[0],flann::SearchParams(-1));

	std::sort (indices[0].begin(), indices[0].end()); 

	Rcpp::NumericMatrix results(indices[0].size(), colNum);
	Rcpp::IntegerVector rownames;

	int num = indices[0].size();

	//#pragma omp parallel for ordered schedule(dynamic)
	for(int i=0;i<num;i++) {
	    float* indexPoint = index->getPoint(indices[0][i]);
	    for(int j=0;j<colNum;j++) {
		results(i,j)=(*(indexPoint+j));
	    }

	    //#pragma omp ordered
	    rownames.push_back(indices[0][i]);
	}

	Rcpp::List dimnms = Rcpp::List::create(rownames, Rcpp::Range(1,colNum));
	results.attr("dimnames") = dimnms;

	return results;

    } catch( std::exception &ex ) {		// or use END_RCPP macro
	forward_exception_to_r( ex );
    } catch(...) {
	::Rf_error( "c++ exception (unknown reason)" );
    }
    return R_NilValue; // -Wall
}
Example #19
0
SEXP bvarcnw_R::forecast_R(const arma::mat& Y_T, int n_horizon, bool incl_shocks)
{
    try {
        arma::cube fcast_res = this->forecast(Y_T,n_horizon,incl_shocks);

        return Rcpp::List::create(Rcpp::Named("forecast_vals") = fcast_res);
    } catch( std::exception &ex ) {
        forward_exception_to_r( ex );
    } catch(...) {
        ::Rf_error( "BMR: C++ exception (unknown reason)" );
    }
    return R_NilValue;
}
Example #20
0
SEXP bvarcnw_R::FEVD_R(int n_periods)
{
    try {
        arma::cube fevd_vals = this->FEVD(n_periods);

        return Rcpp::List::create(Rcpp::Named("fevd_vals") = fevd_vals);
    } catch( std::exception &ex ) {
        forward_exception_to_r( ex );
    } catch(...) {
        ::Rf_error( "BMR: C++ exception (unknown reason)" );
    }
    return R_NilValue;
}
Example #21
0
// this could go into another file too... maybe regroup all calendar / date functions?
RcppExport SEXP setEvaluationDate(SEXP evalDateSEXP) {

    try {

        // set the date
        QuantLib::Settings::instance().evaluationDate() = QuantLib::Date(dateFromR(Rcpp::as<Rcpp::Date>(evalDateSEXP)));

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }
    return R_NilValue;
}
// [[Rcpp::export]]
Rcpp::List get_nearest_Elements(arma::mat mNew,
                                arma::mat mRef,
                                arma::vec vWeights,
                                int nCases) {
   try {
    // number of variables in model
    int nVars = vWeights.size();

    // n new cases
    int nNewCases = mNew.n_rows;

    // allocate distance and order matrix
    arma::mat retDist(nNewCases, nCases);
    arma::umat retOrder(nNewCases, nCases);

    // allocate tmp vector
    arma::colvec tmpDist(mRef.n_rows);
    arma::uvec order(mRef.n_rows);

    for (int i=0; i<nNewCases; ++i) { // loop over cases
      for (int j=0; j<nVars; ++j) { // loop over variables
        tmpDist = tmpDist + abs(vWeights(j) * (mRef.col(j) - mNew(i, j))); //
      } // end loop variables
      order = arma::sort_index(tmpDist);
      for (int k=0;k<nCases; ++k) {
        // write distance to final matrix
        retDist(i, k) = tmpDist(order(k));
        // write order to final matrix
        retOrder(i, k) = order(k) + 1;
      }
      // reset tmp distance vector
      tmpDist = arma::zeros<arma::vec>(mRef.n_rows);
    } // end loop cases
    return Rcpp::List::create(
      Rcpp::Named("distance") = retDist,
      Rcpp::Named("order")    = retOrder
    );
   } catch(std::exception &ex) {
     forward_exception_to_r(ex);
   } catch(...) {
     ::Rf_error("c++ exception (unknown reason)");
   }
   // never go here
   return NA_REAL;
}
Example #23
0
RcppExport SEXP setContext(SEXP parSEXP) {

    try {
        Rcpp::List par(parSEXP);        

        // set fixingDays and settleDate
        RQLContext::instance().fixingDays = Rcpp::as<int>(par["fixingDays"]);
        RQLContext::instance().settleDate = QuantLib::Date(dateFromR(Rcpp::as<Rcpp::Date>(par["settleDate"])));

        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(par["calendar"])) );
        RQLContext::instance().calendar = *pcal; // set calendar in global singleton

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }
    return R_NilValue;
}
Example #24
0
RcppExport SEXP RemovePoints(SEXP x,SEXP d) {

    try {
	Rcpp::XPtr< flann::Index<flann::L2<float> > > index(x);
	Rcpp::NumericVector rdata(d);
	//int colNum = rdata.size();

	for(Rcpp::NumericVector::iterator ii = rdata.begin(); ii != rdata.end(); ++ii) {
	    index->removePoint((*ii));
	}

	return R_NilValue; // -Wall


    } catch( std::exception &ex ) {		// or use END_RCPP macro
	forward_exception_to_r( ex );
    } catch(...) {
	::Rf_error( "c++ exception (unknown reason)" );
    }
    return R_NilValue; // -Wall
}
Example #25
0
RcppExport SEXP GetPoint(SEXP x,SEXP p,SEXP c) {

    try {
	Rcpp::XPtr< flann::Index<flann::L2<float> >  > index(x);
	Rcpp::NumericVector point(p);
	Rcpp::NumericVector colNum(c);
	float* indexPoint = index->getPoint(point[0]);
	Rcpp::NumericVector results;

	for(int i=0;i<colNum[0];i++) {
	    results.push_back(*(indexPoint+i));
	}

	return results; // -Wall

    } catch( std::exception &ex ) {		// or use END_RCPP macro
	forward_exception_to_r( ex );
    } catch(...) {
	::Rf_error( "c++ exception (unknown reason)" );
    }
    return R_NilValue; // -Wall
}
Example #26
0
RcppExport SEXP isHoliday(SEXP calSexp, SEXP dateSexp){

    try {
        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(calSexp)) );

        Rcpp::DateVector dates  = Rcpp::DateVector(dateSexp);
        int n = dates.size();
        std::vector<int> hdays(n);

        for (int i=0; i<n; i++) {
            QuantLib::Date day( dateFromR(dates[i]) );
            hdays[i] = pcal->isHoliday(day);
        }

        return Rcpp::wrap(hdays);

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }
    return R_NilValue;
}
Example #27
0
// Return row sum of big matrix (must be of type double)
// Y = a*X + b
SEXP big_add_multiply_scalar(SEXP SX, SEXP SY,  
                             SEXP Sa, SEXP Sb, 
                             SEXP SX_firstCol, SEXP SX_lastCol, 
                             SEXP SY_firstCol, SEXP SY_lastCol) 
{
    try {     
        double a = DOUBLE_DATA(Sa)[0];
        double b = DOUBLE_DATA(Sb)[0];
        
        arma::mat X;
        sub_sbm_to_arma_xd(SX, X, SX_firstCol, SX_lastCol);
        arma::mat Y;
        sub_sbm_to_arma_xd(SY, Y, SY_firstCol, SY_lastCol);
        
        Y = a*X + b;
        
        return R_NilValue;
    } catch(std::exception &ex) {
        forward_exception_to_r(ex);
    } catch(...) {
        ::Rf_error("c++ exception (unknown reason)");
    }    
    return R_NilValue;
}
Example #28
0
RcppExport SEXP antsImageWrite( SEXP r_img , SEXP r_filename )
{
try
{
  // check and set the filename
  if( r_img == NULL || r_filename == NULL )
    {
    Rcpp::stop("Unspecified Arguments");
    }

  bool verbose = false;
  std::string filename = Rcpp::as< std::string >( r_filename );
  Rcpp::S4 r_image( r_img ) ;
  std::string pixeltype = Rcpp::as< std::string >( r_image.slot( "pixeltype" ));
  unsigned int dimension = Rcpp::as< unsigned int >( r_image.slot( "dimension" ));
  unsigned int components = Rcpp::as< unsigned int >( r_image.slot( "components"));

  if ( (dimension < 2) || (dimension > 4) )
    {
    Rcpp::stop( "Unsupported image dimension");
    }
  if ( (pixeltype != "double") &&
       (pixeltype != "float") &&
       (pixeltype != "unsigned int") &&
       (pixeltype != "unsigned char") )
    {
    Rcpp::stop( "Unsupported pixeltype");
    }

  // write the image
  if ( pixeltype == "double" )
    {
    typedef double PixelType;

    if( dimension == 4 )
      {
      const int ImageDimension = 4;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 );
      }
    else if( dimension == 3 )
      {
      const int ImageDimension = 3 ;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl;
      return Rcpp::wrap( 0 ) ;
      }
    else if( dimension == 2 )
      {
      const int ImageDimension = 2 ;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl;
      return Rcpp::wrap( 0 );
      }
    }
  else if ( pixeltype == "float" )
    {
    typedef float PixelType;

    if( dimension == 4 )
      {
      const int ImageDimension = 4;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 );
      }
    else if( dimension == 3 )
      {
      const int ImageDimension = 3 ;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 ) ;
      }
    else if( dimension == 2 )
      {
      const int ImageDimension = 2 ;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 ) ;
      }
    }
  else if ( pixeltype == "unsigned int" )
    {
    typedef unsigned int PixelType;

    if( dimension == 4 )
      {
      const int ImageDimension = 4;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 );
      }
    else if( dimension == 3 )
      {
      const int ImageDimension = 3 ;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 ) ;
      }
    else if( dimension == 2 )
      {
      const int ImageDimension = 2 ;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 ) ;
      }
    }
  else if ( pixeltype == "unsigned char" )
    {
    typedef unsigned char PixelType;

    if( dimension == 4 )
      {
      const int ImageDimension = 4;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 );
      }
    else if( dimension == 3 )
      {
      const int ImageDimension = 3 ;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 ) ;
      }
    else if( dimension == 2 )
      {
      const int ImageDimension = 2 ;
      typedef itk::Image< PixelType , ImageDimension >      ImageType;
      typedef itk::VectorImage< PixelType, ImageDimension > VectorImageType;

      (components == 1) ?
        ants::antsImageWrite< ImageType >( r_img, filename ) :
        ants::antsImageWrite< VectorImageType >( r_img, filename);

      if ( verbose ) Rcpp::Rcout << "Done writing image. PixelType: 'double' | Dimension: '4'." << std::endl ;
      return Rcpp::wrap( 0 ) ;
      }
    }
}
catch( const itk::ExceptionObject& err )
  {
  forward_exception_to_r( err );
  }
catch( const std::exception& exc )
  {
  forward_exception_to_r( exc );
  }
catch(...)
  {
	Rcpp::stop("c++ exception (unknown reason)");
  }
return Rcpp::wrap(NA_REAL); //not reached
}
Example #29
0
RcppExport SEXP RadiusSearch(SEXP x,SEXP p,SEXP d,SEXP w) {

    try {
	Rcpp::XPtr< flann::Index<flann::L2<float> >  > index(x);
	Rcpp::NumericVector rdata(p);
	Rcpp::NumericVector radius(d);
	Rcpp::NumericVector weights(w);
	int colNum = rdata.size();

	float *data = new float[colNum];

	int i=0;
	for(Rcpp::NumericVector::iterator ii = rdata.begin(); ii != rdata.end(); ++ii) {
	    data[i] = (*ii);
	    i++;
	}
	flann::Matrix<float> dataset = flann::Matrix<float>(data,1,colNum);

	std::vector< std::vector<int> > indices;
	std::vector< std::vector<float> > dists;

	index->radiusSearch(dataset,indices,dists,radius[0],flann::SearchParams(-1));

	Rcpp::IntegerVector iresults( indices[0].begin(), indices[0].end() );
	Rcpp::IntegerVector dresults( dists[0].begin(), dists[0].end() );

	int num = indices[0].size();

	if(num>0) {
	    float partialWeight = 1/num;

	    //float tempCenters[num][colNum];
	    float *tempCenters = new float[num * colNum];

	    for(int i=0;i<num;i++) {
		float* indexPoint = index->getPoint(indices[0][i]);
		std::string s;
		std::stringstream out;
		out << indices[0][i];
		s = out.str();
		float weight = weights[s];
		for(int j=0;j<colNum;j++) {
		    //tempCenters[i][j] = (*(indexPoint+j)*weight+data[j]*partialWeight)/(weight+partialWeight);
		    tempCenters[i*colNum+j] = (*(indexPoint+j)*weight+data[j]*partialWeight)/(weight+partialWeight);
		}
	    }

	    for(int i=0;i<num;i++) {
		bool valid=true;
		for(int j=0;j<num;j++) {
		    if(i!=j) {
			float sum=0;
			for(int k=0;k<colNum;k++) {
			    //float temp=(tempCenters[i][k]-tempCenters[j][k]);
			    float temp=(tempCenters[i*colNum+k]-tempCenters[j*colNum+k]);
			    sum += temp*temp;
			}
			if(sum<(radius[0]*radius[0])) {
			    valid=false;
			}
		    }
		}
		if(valid){
		    float* indexPoint = index->getPoint(indices[0][i]);
		    for(int j=0;j<colNum;j++) {
			//*(indexPoint+j) = tempCenters[i][j];
			*(indexPoint+j) = tempCenters[i*colNum+j];
		    }
		}
	    }
	    delete [] tempCenters;
	}

	delete [] data;

	return Rcpp::DataFrame::create(Rcpp::Named("indices")=iresults, Rcpp::Named("dist")=dresults);


    } catch( std::exception &ex ) {		// or use END_RCPP macro
	forward_exception_to_r( ex );
    } catch(...) {
	::Rf_error( "c++ exception (unknown reason)" );
    }
    return R_NilValue; // -Wall
}
Example #30
0
RcppExport SEXP AsianOption(SEXP optionParameters){

    try{
        Rcpp::List rparam(optionParameters);

        std::string avgType = Rcpp::as<std::string>(rparam["averageType"]);
        std::string type = Rcpp::as<std::string>(rparam["type"]);
        double underlying = Rcpp::as<double>(rparam["underlying"]);
        double strike = Rcpp::as<double>(rparam["strike"]);
        QuantLib::Spread dividendYield = Rcpp::as<double>(rparam["dividendYield"]);
        QuantLib::Rate riskFreeRate = Rcpp::as<double>(rparam["riskFreeRate"]);
        QuantLib::Time maturity = Rcpp::as<double>(rparam["maturity"]);
        //        int length = int(maturity*360 + 0.5); // FIXME: this could be better
        double volatility = Rcpp::as<double>(rparam["volatility"]);

        QuantLib::Option::Type optionType = getOptionType(type);

        //from test-suite/asionoptions.cpp
        QuantLib::DayCounter dc = QuantLib::Actual360();
        QuantLib::Date today = QuantLib::Date::todaysDate();
        QuantLib::Settings::instance().evaluationDate() = today;

        boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote(underlying));
        boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote(dividendYield));
        boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today, qRate, dc);
        boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote(riskFreeRate));
        boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today, rRate, dc);
        boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote(volatility));
        boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);
        
        boost::shared_ptr<QuantLib::BlackScholesMertonProcess>
            stochProcess(new
                         QuantLib::BlackScholesMertonProcess(QuantLib::Handle<QuantLib::Quote>(spot),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(qTS),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(rTS),
                                                             QuantLib::Handle<QuantLib::BlackVolTermStructure>(volTS)));

        boost::shared_ptr<QuantLib::StrikedTypePayoff> payoff(new QuantLib::PlainVanillaPayoff(optionType,strike));

      

        QuantLib::Average::Type averageType = QuantLib::Average::Geometric;
        Rcpp::List rl = R_NilValue;
   
        if (avgType=="geometric"){
            averageType = QuantLib::Average::Geometric;
            boost::shared_ptr<QuantLib::PricingEngine> 
                engine(new
                       QuantLib::AnalyticContinuousGeometricAveragePriceAsianEngine(stochProcess));
            
            QuantLib::Date exDate = today + int(maturity * 360 + 0.5);
            boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::EuropeanExercise(exDate));
            QuantLib::ContinuousAveragingAsianOption option(averageType, payoff, exercise);
            option.setPricingEngine(engine);
            
            rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                    Rcpp::Named("delta") = option.delta(),
                                    Rcpp::Named("gamma") = option.gamma(),
                                    Rcpp::Named("vega") = option.vega(),
                                    Rcpp::Named("theta") = option.theta(),
                                    Rcpp::Named("rho") = option.rho(),
                                    Rcpp::Named("divRho") = option.dividendRho(),
                                    Rcpp::Named("parameters") = optionParameters);
            
        } else if (avgType=="arithmetic"){
            averageType = QuantLib::Average::Arithmetic;

            boost::shared_ptr<QuantLib::PricingEngine> engine =
                QuantLib::MakeMCDiscreteArithmeticAPEngine<QuantLib::LowDiscrepancy>(stochProcess)
                .withSamples(2047)
                .withControlVariate();
            
            //boost::shared_ptr<PricingEngine> engine =
            //    MakeMCDiscreteArithmeticASEngine<LowDiscrepancy>(stochProcess)
            //    .withSeed(3456789)
            //    .withSamples(1023);
            
            QuantLib::Size fixings = Rcpp::as<double>(rparam["fixings"]);
            QuantLib::Time length = Rcpp::as<double>(rparam["length"]);
            QuantLib::Time first = Rcpp::as<double>(rparam["first"]);
            QuantLib::Time dt = length / (fixings - 1);

            std::vector<QuantLib::Time> timeIncrements(fixings);
            std::vector<QuantLib::Date> fixingDates(fixings);
            timeIncrements[0] = first;
            fixingDates[0] = today + QuantLib::Integer(timeIncrements[0] * 360 + 0.5);
            for (QuantLib::Size i=1; i<fixings; i++) {
                timeIncrements[i] = i*dt + first;
                fixingDates[i] = today + QuantLib::Integer(timeIncrements[i]*360+0.5);
            }
            QuantLib::Real runningSum = 0.0;
            QuantLib::Size pastFixing = 0;

            boost::shared_ptr<QuantLib::Exercise> 
                exercise(new QuantLib::EuropeanExercise(fixingDates[fixings-1]));

            QuantLib::DiscreteAveragingAsianOption option(QuantLib::Average::Arithmetic, 
                                                          runningSum,
                                                          pastFixing, 
                                                          fixingDates,
                                                          payoff, 
                                                          exercise);
            option.setPricingEngine(engine);
            rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(),
                                    Rcpp::Named("delta") = R_NaN,
                                    Rcpp::Named("gamma") = R_NaN,
                                    Rcpp::Named("vega") = R_NaN,
                                    Rcpp::Named("theta") = R_NaN,
                                    Rcpp::Named("rho") = R_NaN,
                                    Rcpp::Named("divRho") = R_NaN,
                                    Rcpp::Named("parameters") = optionParameters);
        } else {
            throw std::range_error("Unknown average type " + type);
        }      
    
        return rl;

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}