/auteur/src/oumat.cpp

http://github.com/eastman/auteur · C++ · 68 lines · 49 code · 10 blank · 9 comment · 4 complexity · a391aebe525140b79bb232138d9e60aa MD5 · raw file

  1. #include <Rcpp.h>
  2. #include <vector>
  3. /* internal C++ */
  4. void process_OU_covariance ( std::vector<double> const &VCV,
  5. double const &alphasq,
  6. double const &sigmasq,
  7. int const &ntip,
  8. std::vector<double> &V)
  9. {
  10. unsigned int i, j, nt=ntip;
  11. double sij, ti, tj, elti, eltj, W;
  12. for (i = 0; i < nt; i++) {
  13. for (j = 0; j <= i; j++) {
  14. ti = VCV[i+i*nt];
  15. sij = VCV[i+j*nt];
  16. tj = VCV[j+j*nt];
  17. elti = exp(-alphasq*(ti-sij));
  18. eltj = exp(-alphasq*(tj-sij));
  19. W = elti*sigmasq*eltj/(alphasq+alphasq);
  20. V[i+nt*j] += W;
  21. if (j != i)
  22. {
  23. V[j+nt*i] += W;
  24. }
  25. }
  26. }
  27. }
  28. /* C++ | R INTERFACE; main function */
  29. RcppExport SEXP oumat (
  30. SEXP TIMES,
  31. SEXP ALPHA,
  32. SEXP SIGMA,
  33. SEXP TIPS)
  34. {
  35. /*
  36. * TIMES: array form of VCV matrix (under Brownian motion): split times for pairs of species
  37. * ALPHA: herein, alpha is expected given as alpha^2
  38. * SIGMA: herein, sigma is expected given as sigma^2
  39. * TIPS: number of species
  40. */
  41. try {
  42. Rcpp::List phylo(TIMES);
  43. std::vector<double> VCV = phylo["vmat"];
  44. double alphasq = Rcpp::as<double> (ALPHA);
  45. double sigmasq = Rcpp::as<double> (SIGMA);
  46. unsigned int ntip = Rcpp::as<int> (TIPS);
  47. std::vector<double> V;
  48. V.assign(ntip*ntip,0);
  49. process_OU_covariance(VCV, alphasq, sigmasq, ntip, V);
  50. /* PREPARE OUTPUT FOR R */
  51. return Rcpp::List::create(Rcpp::Named("oumat", V));
  52. } catch( std::exception &ex ) {
  53. forward_exception_to_r( ex );
  54. } catch(...) {
  55. ::Rf_error( "c++ exception (unknown reason)" );
  56. }
  57. return R_NilValue;
  58. }