示例#1
0
文件: relSim.cpp 项目: cran/relSim
// [[Rcpp::export(".lrSib")]]
double lrSib_Caller(IntegerVector ProfSib1, IntegerVector ProfSib2, 
              List listFreqs){
  return lrSib(ProfSib1.begin(), ProfSib2.begin(), listFreqs);                
}
示例#2
0
文件: relSim.cpp 项目: cran/relSim
// [[Rcpp::export(".IBS_Caller")]]
int IBS_Caller(IntegerVector Prof1, IntegerVector Prof2, int nLoci){
  return IBS(Prof1.begin(), Prof2.begin(), nLoci);
}
示例#3
0
文件: relSim.cpp 项目: cran/relSim
// [[Rcpp::export(".lrPC")]]
double lrPC_Caller(IntegerVector ProfParent, IntegerVector ProfChild, 
            List listFreqs){
  return lrPC(ProfParent.begin(), ProfChild.begin(), listFreqs);
}
示例#4
0
// simulate genotypes given observed marker data
// [[Rcpp::export(".sim_geno")]]
IntegerVector sim_geno(const String& crosstype,
                       const IntegerMatrix& genotypes, // columns are individuals, rows are markers
                       const IntegerMatrix& founder_geno, // columns are markers, rows are founder lines
                       const bool is_X_chr,
                       const LogicalVector& is_female, // length n_ind
                       const IntegerMatrix& cross_info, // columns are individuals
                       const NumericVector& rec_frac,   // length nrow(genotypes)-1
                       const IntegerVector& marker_index, // length nrow(genotypes)
                       const double error_prob,
                       const int n_draws) // number of imputations
{
    const int n_ind = genotypes.cols();
    const int n_pos = marker_index.size();
    const int n_mar = genotypes.rows();

    QTLCross* cross = QTLCross::Create(crosstype);

    // check inputs
    if(is_female.size() != n_ind)
        throw std::range_error("length(is_female) != ncol(genotypes)");
    if(cross_info.cols() != n_ind)
        throw std::range_error("ncols(cross_info) != ncol(genotypes)");
    if(rec_frac.size() != n_pos-1)
        throw std::range_error("length(rec_frac) != length(marker_index)-1");

    if(error_prob < 0.0 || error_prob > 1.0)
        throw std::range_error("error_prob out of range");

    for(int i=0; i<rec_frac.size(); i++) {
        if(rec_frac[i] < 0 || rec_frac[i] > 0.5)
            throw std::range_error("rec_frac must be >= 0 and <= 0.5");
    }
    if(!cross->check_founder_geno_size(founder_geno, n_mar))
        throw std::range_error("founder_geno is not the right size");
    // end of checks

    const int mat_size = n_pos*n_draws;
    IntegerVector draws(mat_size*n_ind); // output object

    for(int ind=0; ind<n_ind; ind++) {

        Rcpp::checkUserInterrupt();  // check for ^C from user

        // possible genotypes for this individual
        IntegerVector poss_gen = cross->possible_gen(is_X_chr, is_female[ind], cross_info(_,ind));
        const int n_poss_gen = poss_gen.size();
        NumericVector probs(n_poss_gen);

        // backward equations
        NumericMatrix beta = backwardEquations(cross, genotypes(_,ind), founder_geno, is_X_chr, is_female[ind],
                                               cross_info(_,ind), rec_frac, marker_index, error_prob,
                                               poss_gen);

        // simulate genotypes
        for(int draw=0; draw<n_draws; draw++) {
            // first draw
            // calculate first prob (on log scale)
            probs[0] = cross->init(poss_gen[0], is_X_chr, is_female[ind], cross_info(_,ind)) + beta(0,0);
            if(marker_index[0] >= 0)
                probs[0] += cross->emit(genotypes(marker_index[0],ind), poss_gen[0], error_prob,
                                        founder_geno(_, marker_index[0]), is_X_chr, is_female[ind], cross_info(_,ind));
            double sumprobs = probs[0]; // to contain log(sum(probs))

            // calculate rest of probs
            for(int g=1; g<n_poss_gen; g++) {
                probs[g] = cross->init(poss_gen[g], is_X_chr, is_female[ind], cross_info(_,ind)) + beta(g,0);
                if(marker_index[0] >= 0)
                    probs[g] += cross->emit(genotypes(marker_index[0],ind), poss_gen[g], error_prob,
                                            founder_geno(_, marker_index[0]), is_X_chr, is_female[ind], cross_info(_,ind));
                sumprobs = addlog(sumprobs, probs[g]);
            }

            // re-scale probs
            for(int g=0; g<n_poss_gen; g++)
                probs[g] = exp(probs[g] - sumprobs);

            // make draw, returns a value from 1, 2, ..., n_poss_gen
            int curgeno = random_int(probs);
            draws[draw*n_pos + ind*mat_size] = poss_gen[curgeno];

            // move along chromosome
            for(int pos=1; pos<n_pos; pos++) {

                // calculate probs
                for(int g=0; g<n_poss_gen; g++) {
                    probs[g] = cross->step(poss_gen[curgeno], poss_gen[g], rec_frac[pos-1],
                                           is_X_chr, is_female[ind], cross_info(_,ind)) +
                        beta(g,pos) - beta(curgeno, pos-1);
                    if(marker_index[pos] >= 0)
                        probs[g] += cross->emit(genotypes(marker_index[pos],ind), poss_gen[g], error_prob,
                                                founder_geno(_, marker_index[pos]), is_X_chr, is_female[ind], cross_info(_,ind));
                    probs[g] = exp(probs[g]);
                }

                // make draw
                curgeno = random_int(probs);

                draws[pos + draw*n_pos + ind*mat_size] = poss_gen[curgeno];

            } // loop over positions
        } // loop over draws
    } // loop over individuals

    draws.attr("dim") = Dimension(n_pos, n_draws, n_ind);
    delete cross;
    return draws;
}
示例#5
0
文件: relSim.cpp 项目: cran/relSim
// [[Rcpp::export(".locusLRmix")]]
double locusLRmix_Caller(IntegerVector ProfVic, IntegerVector ProfSus, 
                   NumericVector Freq){ 
  return locusLRmix(ProfVic.begin(), ProfSus.begin(), Freq);
}
示例#6
0
List objectivex(const arma::mat& transition, NumericVector emissionArray,
                const arma::vec& init, IntegerVector obsArray, const arma::imat& ANZ,
                IntegerVector emissNZ, const arma::ivec& INZ, const arma::ivec& nSymbols,
                const arma::mat& coef, const arma::mat& X, arma::ivec& numberOfStates,
                int threads) {


  IntegerVector eDims = emissionArray.attr("dim"); //m,p,r
  IntegerVector oDims = obsArray.attr("dim"); //k,n,r

  arma::cube emission(emissionArray.begin(), eDims[0], eDims[1], eDims[2], false, true);
  arma::icube obs(obsArray.begin(), oDims[0], oDims[1], oDims[2], false, true);

  arma::icube BNZ(emissNZ.begin(), emission.n_rows, emission.n_cols - 1, emission.n_slices, false, true);

  unsigned int q = coef.n_rows;
  arma::vec grad(
      arma::accu(ANZ) + arma::accu(BNZ) + arma::accu(INZ) + (numberOfStates.n_elem- 1) * q,
      arma::fill::zeros);
  arma::mat weights = exp(X * coef).t();
  if (!weights.is_finite()) {
    grad.fill(-arma::math::inf());
    return List::create(Named("objective") = arma::math::inf(), Named("gradient") = wrap(grad));
  }

  weights.each_row() /= sum(weights, 0);

  arma::mat initk(emission.n_rows, obs.n_slices);

  for (unsigned int k = 0; k < obs.n_slices; k++) {
    initk.col(k) = init % reparma(weights.col(k), numberOfStates);
  }

  arma::cube alpha(emission.n_rows, obs.n_cols, obs.n_slices); //m,n,k
  arma::cube beta(emission.n_rows, obs.n_cols, obs.n_slices); //m,n,k
  arma::mat scales(obs.n_cols, obs.n_slices); //m,n,k

  arma::sp_mat sp_trans(transition);
  internalForwardx(sp_trans.t(), emission, initk, obs, alpha, scales, threads);
  if (!scales.is_finite()) {
    grad.fill(-arma::math::inf());
    return List::create(Named("objective") = arma::math::inf(), Named("gradient") = wrap(grad));
  }

  internalBackwardx(sp_trans, emission, obs, beta, scales, threads);
  if (!beta.is_finite()) {
    grad.fill(-arma::math::inf());
    return List::create(Named("objective") = arma::math::inf(), Named("gradient") = wrap(grad));
  }

  arma::ivec cumsumstate = arma::cumsum(numberOfStates);

  arma::mat gradmat(
      arma::accu(ANZ) + arma::accu(BNZ) + arma::accu(INZ) + (numberOfStates.n_elem- 1) * q,
      obs.n_slices, arma::fill::zeros);

#pragma omp parallel for if(obs.n_slices >= threads) schedule(static) num_threads(threads)       \
  default(none) shared(q, alpha, beta, scales, gradmat, nSymbols, ANZ, BNZ, INZ,          \
          numberOfStates, cumsumstate, obs, init, initk, X, weights, transition, emission)
    for (int k = 0; k < obs.n_slices; k++) {
      int countgrad = 0;
      // transitionMatrix
      if (arma::accu(ANZ) > 0) {

        for (int jj = 0; jj < numberOfStates.n_elem; jj++) {
          arma::vec gradArow(numberOfStates(jj));
          arma::mat gradA(numberOfStates(jj), numberOfStates(jj));
          int ind_jj = cumsumstate(jj) - numberOfStates(jj);

          for (int i = 0; i < numberOfStates(jj); i++) {
            arma::uvec ind = arma::find(ANZ.row(ind_jj + i).subvec(ind_jj, cumsumstate(jj) - 1));

            if (ind.n_elem > 0) {
              gradArow.zeros();
              gradA.eye();
              gradA.each_row() -= transition.row(ind_jj + i).subvec(ind_jj, cumsumstate(jj) - 1);
              gradA.each_col() %= transition.row(ind_jj + i).subvec(ind_jj, cumsumstate(jj) - 1).t();


              for (int j = 0; j < numberOfStates(jj); j++) {
                for (unsigned int t = 0; t < (obs.n_cols - 1); t++) {
                  double tmp = alpha(ind_jj + i, t, k);
                  for (unsigned int r = 0; r < obs.n_rows; r++) {
                    tmp *= emission(ind_jj + j, obs(r, t + 1, k), r);
                  }
                  gradArow(j) += tmp * beta(ind_jj + j, t + 1, k) / scales(t + 1, k);
                }

              }

              gradArow = gradA * gradArow;
              gradmat.col(k).subvec(countgrad, countgrad + ind.n_elem - 1) = gradArow.rows(ind);
              countgrad += ind.n_elem;
            }
          }
        }
      }
      if (arma::accu(BNZ) > 0) {
        // emissionMatrix
        for (unsigned int r = 0; r < obs.n_rows; r++) {
          arma::vec gradBrow(nSymbols(r));
          arma::mat gradB(nSymbols(r), nSymbols(r));
          for (unsigned int i = 0; i < emission.n_rows; i++) {
            arma::uvec ind = arma::find(BNZ.slice(r).row(i));
            if (ind.n_elem > 0) {
              gradBrow.zeros();
              gradB.eye();
              gradB.each_row() -= emission.slice(r).row(i).subvec(0, nSymbols(r) - 1);
              gradB.each_col() %= emission.slice(r).row(i).subvec(0, nSymbols(r) - 1).t();
              for (int j = 0; j < nSymbols(r); j++) {
                if (obs(r, 0, k) == j) {
                  double tmp = initk(i, k);
                  for (unsigned int r2 = 0; r2 < obs.n_rows; r2++) {
                    if (r2 != r) {
                      tmp *= emission(i, obs(r2, 0, k), r2);
                    }
                  }
                  gradBrow(j) += tmp * beta(i, 0, k) / scales(0, k);
                }
                for (unsigned int t = 0; t < (obs.n_cols - 1); t++) {
                  if (obs(r, t + 1, k) == j) {
                    double tmp = beta(i, t + 1, k) / scales(t + 1, k);
                    for (unsigned int r2 = 0; r2 < obs.n_rows; r2++) {
                      if (r2 != r) {
                        tmp *= emission(i, obs(r2, t + 1, k), r2);
                      }
                    }
                    gradBrow(j) += arma::dot(alpha.slice(k).col(t), transition.col(i)) * tmp;
                  }
                }

              }
              gradBrow = gradB * gradBrow;
              gradmat.col(k).subvec(countgrad, countgrad + ind.n_elem - 1) = gradBrow.rows(ind);
              countgrad += ind.n_elem;

            }
          }
        }
      }
      if (arma::accu(INZ) > 0) {
        for (int i = 0; i < numberOfStates.n_elem; i++) {
          int ind_i = cumsumstate(i) - numberOfStates(i);
          arma::uvec ind = arma::find(
            INZ.subvec(ind_i, cumsumstate(i) - 1));
          if (ind.n_elem > 0) {
            arma::vec gradIrow(numberOfStates(i), arma::fill::zeros);
            for (int j = 0; j < numberOfStates(i); j++) {
              double tmp = weights(i, k);
              for (unsigned int r = 0; r < obs.n_rows; r++) {
                tmp *= emission(ind_i + j, obs(r, 0, k), r);
              }
              gradIrow(j) += tmp * beta(ind_i + j, 0, k) / scales(0, k);

            }
            arma::mat gradI(numberOfStates(i), numberOfStates(i), arma::fill::zeros);
            gradI.eye();
            gradI.each_row() -= init.subvec(ind_i, cumsumstate(i) - 1).t();
            gradI.each_col() %= init.subvec(ind_i, cumsumstate(i) - 1);
            gradIrow = gradI * gradIrow;
            gradmat.col(k).subvec(countgrad, countgrad + ind.n_elem - 1) = gradIrow.rows(ind);
            countgrad += ind.n_elem;
          }
        }
      }
      for (int jj = 1; jj < numberOfStates.n_elem; jj++) {
        int ind_jj = (cumsumstate(jj) - numberOfStates(jj));

        for (int j = 0; j < emission.n_rows; j++) {
          double tmp = 1.0;
          for (unsigned int r = 0; r < obs.n_rows; r++) {
            tmp *= emission(j, obs(r, 0, k), r);
          }
          if ((j >= ind_jj) & (j < cumsumstate(jj))) {
            gradmat.col(k).subvec(countgrad + q * (jj - 1), countgrad + q * jj - 1) += tmp
            * beta(j, 0, k) / scales(0, k) * initk(j, k) * X.row(k).t() * (1.0 - weights(jj, k));
          } else {
            gradmat.col(k).subvec(countgrad + q * (jj - 1), countgrad + q * jj - 1) -= tmp
            * beta(j, 0, k) / scales(0, k) * initk(j, k) * X.row(k).t() * weights(jj, k);
          }
        }

      }
    }
    return List::create(Named("objective") = -arma::accu(log(scales)),
                        Named("gradient") = wrap(-sum(gradmat, 1)));
}
示例#7
0
// [[Rcpp::export]]
List melt_dataframe(const DataFrame& data,
                    const IntegerVector& id_ind,
                    const IntegerVector& measure_ind,
                    String variable_name,
                    String value_name,
                    SEXP measure_attributes,
                    bool factorsAsStrings,
                    bool valueAsFactor) {

  int nrow = data.nrows();

  CharacterVector data_names = as<CharacterVector>(data.attr("names"));

  int n_id = id_ind.size();
  debug(Rprintf("n_id == %i\n", n_id));

  int n_measure = measure_ind.size();
  debug(Rprintf("n_measure == %i\n", n_measure));

  // Don't melt if the value variables are non-atomic
  for (int i = 0; i < n_measure; ++i) {
    if (!Rf_isVectorAtomic(data[measure_ind[i]])) {
      stop("Can't melt data.frames with non-atomic 'measure' columns");
    }
  }

  // The output should be a data.frame with:
  // number of columns == number of id vars + 'variable' + 'value',
  // with number of rows == data.nrow() * number of value vars
  List output = no_init(n_id + 2);

  // First, allocate the ID variables
  // we repeat each ID vector n_measure times

  // A define to handle the different possible types
  #define REP(OBJECT, RTYPE)                         \
    case RTYPE: {                                    \
      output[i] = rep_(OBJECT, n_measure);           \
      Rf_copyMostAttrib(OBJECT, output[i]);          \
      break;                                         \
    }

  for (int i = 0; i < n_id; ++i) {

    SEXP object = data[id_ind[i]];

    if (Rf_inherits(object, "POSIXlt")) {
      std::string var = std::string(data_names[id_ind[i]]);
      Rcpp::stop("'%s' is a POSIXlt. Please convert to POSIXct.", var);
    }

    switch (TYPEOF(object)) {
      REP(object, LGLSXP);
      REP(object, INTSXP);
      REP(object, REALSXP);
      REP(object, STRSXP);
      REP(object, CPLXSXP);
      REP(object, RAWSXP);
      REP(object, VECSXP);
      default: { stop("internal error: unnhandled vector type in REP"); }
    }
  }

  // Now, we assign the 'variable' and 'value' columns

  // 'variable' is made up of repeating the names of the 'measure' variables,
  // each nrow times. We want this to be a factor as well.
  CharacterVector id_names = no_init(n_measure);
  for (int i = 0; i < n_measure; ++i) {
    id_names[i] = data_names[measure_ind[i]];
  }
  output[n_id] = make_variable_column(id_names, nrow);

  // 'value' is made by concatenating each of the 'value' variables
  output[n_id + 1] = concatenate(data, measure_ind, factorsAsStrings);
  if (!Rf_isNull(measure_attributes)) {
    SET_ATTRIB(output[n_id + 1], measure_attributes);
    // we also need to make sure the OBJECT bit is set for other 'object' types
    // see: http://stackoverflow.com/questions/24059460/melt-data-frame-changes-behavior-how-posixct-columns-are-printed
    // if we've entered this code block, the measure_attributes has been
    // populated because all value variables have identical attributes
    SET_OBJECT(output[n_id + 1], OBJECT(data[measure_ind[0]]));
  }

  // Make the List more data.frame like

  // Set the row names
  output.attr("row.names") =
      IntegerVector::create(IntegerVector::get_na(), -(nrow * n_measure));

  // Set the names
  CharacterVector out_names = no_init(n_id + 2);
  for (int i = 0; i < n_id; ++i) {
    out_names[i] = data_names[id_ind[i]];
  }
  out_names[n_id] = variable_name;
  out_names[n_id + 1] = value_name;
  output.attr("names") = out_names;

  // Set the class
  output.attr("class") = "data.frame";

  return output;
}
示例#8
0
文件: roc.cpp 项目: cran/fbroc
t extract(const t & in, const IntegerVector & index) {
  int n = index.size();
  t out (n);
  for (int i = 0; i < n; i++) out[i] = in[index[i]];
  return out;
} 
示例#9
0
// [[Rcpp::export]]
NumericMatrix CPP_col_dist_sparse(int nc1, IntegerVector xp, IntegerVector xrow, NumericVector x, int nc2, IntegerVector yp, IntegerVector yrow, NumericVector y, int metric_code, double param1, bool symmetric) {
  check_metric(metric_code, param1);
  NumericVector::iterator _x = x.begin();
  NumericVector::iterator _y = y.begin();
  IntegerVector::iterator _xrow = xrow.begin();
  IntegerVector::iterator _yrow = yrow.begin();

  NumericMatrix dist(nc1, nc2);

#ifdef _OPENMP
  /* average number of entries scanned when comparing two columns, used to decide whether to try parallelization */
  double avg_nr = (xp[nc1] - xp[0] + 0.0) / nc1 + (yp[nc2] - yp[0] + 0.0) / nc2; 
#endif

#pragma omp parallel for \
        if (openmp_threads > 1 && (nc1 + 0.0) * (nc2 + 0.0) * avg_nr > 40e6) \
        num_threads(openmp_threads) \
        shared(dist, nc1, xp, _xrow, _x, nc2, yp, _yrow, _y, metric_code, param1)
  for (int col2 = 0; col2 < nc2; col2++) {
    int col1_max = (symmetric) ? col2 + 1 : nc1;
    int yi_max = yp[col2 + 1];

    for (int col1 = 0; col1 < col1_max; col1++) {
      int xi_max = xp[col1 + 1];
      int xi = xp[col1];
      int yi = yp[col2];
      int xrow_curr = (xi < xi_max) ? _xrow[xi] : INT_MAX;
      int yrow_curr = (yi < yi_max) ? _yrow[yi] : INT_MAX;
      
      double accum = 0.0;
      double x_curr, y_curr;
      double d_xy, x_plus_y;
      while (xi < xi_max || yi < yi_max) {

        if (xrow_curr < yrow_curr) {
          x_curr = _x[xi]; y_curr = 0.0;
          xi++;
          xrow_curr = (xi < xi_max) ? _xrow[xi] : INT_MAX;
        }
        else if (xrow_curr == yrow_curr) {
          x_curr = _x[xi]; y_curr = _y[yi];
          xi++; yi++;
          xrow_curr = (xi < xi_max) ? _xrow[xi] : INT_MAX;
          yrow_curr = (yi < yi_max) ? _yrow[yi] : INT_MAX;
        }
        else /* xrow_curr > yrow_curr */ {
          x_curr = 0; y_curr = _y[yi];
          yi++;
          yrow_curr = (yi < yi_max) ? _yrow[yi] : INT_MAX;          
        }
        
        switch (metric_code) {
        case 0:
          d_xy = x_curr - y_curr;
          accum += d_xy * d_xy;
          break;
        case 1:
          d_xy = fabs(x_curr - y_curr);
          if (d_xy > accum) accum = d_xy;
          break;
        case 2:
          d_xy = fabs(x_curr - y_curr);
          accum += d_xy;
          break;
        case 3:
          d_xy = fabs(x_curr - y_curr);
          accum += pow(d_xy, param1);
          break;
        case 4:
          x_plus_y = fabs(x_curr) + fabs(y_curr);
          d_xy = fabs(x_curr - y_curr);
          if (x_plus_y > 0) accum += d_xy / x_plus_y;
          break;
        }
      } /* while (xi, yi) */

      switch (metric_code) {
      case 0:
        dist(col1, col2) = sqrt(accum);
        break;
      case 1:
      case 2:
      case 4:
        dist(col1, col2) = accum;
        break;
      case 3:
        if (param1 > 1.0)
          dist(col1, col2) = pow(accum, 1.0 / param1);
        else
          dist(col1, col2) = accum;
        break;
      }

    } /* for (col1) */
  } /* for (col2) */
  
  if (symmetric) mk_symmetric_matrix(dist);
  return dist;
}
//' @export
// [[Rcpp::export]]
List blockSizeCalibrate(NumericMatrix ret,
                                    IntegerVector b_vec = IntegerVector::create(1, 3, 6, 10),
                                    double alpha = 0.05,
                                    int M = 199,
                                    int K = 1000,
                                    int b_av = 5,
                                    int T_start = 50) {

  int b_len = b_vec.length();
  NumericVector emp_reject_probs = rep(0.0, b_len);
  double Delta_hat = sharpeRatioDiff(ret);
  NumericVector ret1 = ret(_,0);
  NumericVector ret2 = ret(_,1);
  int T = ret1.length();
  NumericMatrix Var_data(T_start + T, 2);
  Var_data(0,_) = ret(0,_);

  IntegerVector range1 = seq(1, T-1);
  IntegerVector range2 = seq(0, T-2);
  NumericVector intercept = rep(1.0, ret1.length());
  List fit1 = fastLm(ret1[range1], cbindCpp(intercept[range2], cbindCpp(ret1[range2],ret2[range2])));
  List fit2 = fastLm(ret2[range1], cbindCpp(intercept[range2], cbindCpp(ret1[range2],ret2[range2])));

  NumericVector coef1 = as<NumericVector>(wrap(fit1["coef"]));
  NumericVector coef2 = as<NumericVector>(wrap(fit2["coef"]));
  NumericMatrix resid_mat = cbindCpp(as<NumericVector>(fit1["resid"]),
                                     as<NumericVector>(fit2["resid"]));

  for(int k = 0; k < K; k++){
    // create resid_mat_star
    NumericMatrix resid_mat_star(T_start + T, resid_mat.cols());
    // fill with NA by default
    int xsize = resid_mat_star.nrow() * resid_mat_star.ncol();
    for (int i = 0; i < xsize; i++) {
      resid_mat_star[i] = NumericMatrix::get_na();
    }
    // fill first row with 0
    for(int c = 0; c < resid_mat_star.ncol(); c++)
      resid_mat_star(0,c) = 0.0;
    IntegerVector index = sbSequenceCpp(T-1, b_av, T_start + T - 1) - 1;
    for(int j = 0; j < index.length(); j++){
      // handling NA values
      if( IntegerVector::is_na(index(j)) ){
        // do nothing
      } else if( (j+1) > resid_mat_star.nrow() ){
        // do nothing
      } else if( index[j] > resid_mat.nrow() ){
        // do nothing
      } else {
        resid_mat_star(j+1,_) = resid_mat(index[j],_);
      }
    }

    for(int t = 1; t < (T_start + T); t++){
      Var_data(t,0) = coef1[0] + coef1[1]*Var_data(t-1,0) +
        coef1[2]*Var_data(t-1,1) + resid_mat_star(t,0);
      Var_data(t,1) = coef2[0] + coef2[1]*Var_data(t-1,0) +
        coef2[2]*Var_data(t-1,1) + resid_mat_star(t,1);
    }

    NumericMatrix Var_data_trunc = Var_data(Range(T_start,T_start+T-1), Range(0,Var_data.ncol()-1));
    for(int j = 0; j < b_len; j++){
      List bTI = bootTimeInference(Var_data_trunc, b_vec[j], M, Delta_hat);
      double p_value = as<double>(wrap(bTI["p.Value"]));
      if(p_value <= alpha)
        emp_reject_probs[j] = emp_reject_probs[j] + 1;
    }
  }
  emp_reject_probs = emp_reject_probs/(double)K;
  Environment env = Environment::base_namespace();
  Function order = env["order"];
  IntegerVector b_order = order(abs(emp_reject_probs - alpha));
  int b_opt = as<int>(wrap(b_vec(b_order[0]-1)));
  NumericMatrix b_vec_with_probs = rbindCpp(as<NumericVector>(wrap(b_vec)), emp_reject_probs);

  return(List::create(
    _["Empirical.Rejection.Probs"] = b_vec_with_probs,
    _["b.optimal"] = b_opt
  ));
}
示例#11
0
void
madara::knowledge::containers::IntegerVector::exchange (
  IntegerVector & other, bool refresh_keys, bool delete_keys)
{
  if (context_ && other.context_)
  {
    ContextGuard context_guard (*context_);
    ContextGuard other_context_guard (*other.context_);
    MADARA_GUARD_TYPE guard (mutex_), guard2 (other.mutex_);

    if (refresh_keys)
    {
      other.resize ();
      this->resize ();
    }

    size_t other_size = other.vector_.size ();
    size_t this_size = this->vector_.size ();

    for (size_t i = 0; i < this_size; ++i)
    {
      // temp = this[i];
      knowledge::KnowledgeRecord temp = context_->get (this->vector_[i], settings_);
    
      if (i < other_size)
      {
        // this[i] = other[i];
        context_->set (this->vector_[i],
          context_->get (other.vector_[i], other.settings_),
          settings_);

        // other[i] = temp;
        other.context_->set (other.vector_[i], temp, other.settings_);
      }
      else
      {
        if (delete_keys)
        {
          std::stringstream buffer;
          buffer << this->name_;
          buffer << delimiter_;
          buffer << i;
          this->context_->delete_variable (buffer.str (), other.settings_);
        }
        else
        {
          knowledge::KnowledgeRecord zero;
          this->context_->set (this->vector_[i], zero, this->settings_);
        }

        {
          std::stringstream buffer;
          buffer << other.name_;
          buffer << delimiter_;
          buffer << i;

          // other[i] = temp;
          other.context_->set (buffer.str (), temp, other.settings_);
        }
      }

    }

    // copy the other vector's elements to this vector's location
    for (size_t i = this_size; i < other_size; ++i)
    {
      std::stringstream buffer;
      buffer << this->name_;
      buffer << delimiter_;
      buffer << i;
      context_->set (buffer.str (),
        other.context_->get (other.vector_[i], other.settings_), this->settings_);
    }

    // set the size appropriately
    this->context_->set (this->size_,
      knowledge::KnowledgeRecord::Integer (other_size), this->settings_);
    other.context_->set (other.size_,
      knowledge::KnowledgeRecord::Integer (this_size), other.settings_);

    if (refresh_keys)
    {
      this->resize (-1, true);
      other.resize (-1, true);
    }
  }
}
示例#12
0
文件: match.cpp 项目: nullsatz/dauc
void wrapAssignments(int nBidders, int * assignments,
	IntegerVector& outAssignments)
{
	std::copy(assignments, assignments + nBidders, outAssignments.begin());
}