Exemple #1
0
    CharacterVector get_uniques( const CharacterVector& left, const CharacterVector& right){
        int nleft = left.size(), nright = right.size() ;
        int n = nleft + nright ;

        CharacterVector big = no_init(n) ;
        CharacterVector::iterator it = big.begin() ;
        std::copy( left.begin(), left.end(), it ) ;
        std::copy( right.begin(), right.end(), it + nleft ) ;
        return Language( "unique", big ).fast_eval() ;
    }
void count_clusters(std::map<std::string, int> &counts,
                    CharacterVector these_clusters,
                    CharacterVector cluster_names) {

    int n = these_clusters.size();

    for(int i=0; i < n; i++) {
        counts[as<std::string>(these_clusters[i])]++;
    }

    //print_cluster_counts(counts);

    // add clusters with no counts
    CharacterVector::iterator it;
    for(it = cluster_names.begin(); it != cluster_names.end(); ++it) {

        // if this name not in map, make an entry and set it to zero
        if(counts.find(as<std::string>(*it)) == counts.end()) {
            counts[as<std::string>(*it)] = 0;
        }

    }

    //print_cluster_counts(counts);

    return;
}
Exemple #3
0
HttpResponse* listToResponse(HttpRequest* pRequest,
                             const Rcpp::List& response) {
  using namespace Rcpp;

  if (response.isNULL() || response.size() == 0)
    return NULL;

  CharacterVector names = response.names();

  int status = Rcpp::as<int>(response["status"]);
  std::string statusDesc = getStatusDescription(status);

  List responseHeaders = response["headers"];

  // Self-frees when response is written
  DataSource* pDataSource = NULL;

  // The response can either contain:
  // - bodyFile: String value that names the file that should be streamed
  // - body: Character vector (which is charToRaw-ed) or raw vector, or NULL
    if (std::find(names.begin(), names.end(), "bodyFile") != names.end()) {
    FileDataSource* pFDS = new FileDataSource();
    pFDS->initialize(Rcpp::as<std::string>(response["bodyFile"]),
        Rcpp::as<bool>(response["bodyFileOwned"]));
    pDataSource = pFDS;
  }
  else if (Rf_isString(response["body"])) {
    RawVector responseBytes = Function("charToRaw")(response["body"]);
    pDataSource = new RawVectorDataSource(responseBytes);
  }
  else {
    RawVector responseBytes = response["body"];
    pDataSource = new RawVectorDataSource(responseBytes);
  }

  HttpResponse* pResp = new HttpResponse(pRequest, status, statusDesc,
                                         pDataSource);
  CharacterVector headerNames = responseHeaders.names();
  for (R_len_t i = 0; i < responseHeaders.size(); i++) {
    pResp->addHeader(
      std::string((char*)headerNames[i], headerNames[i].size()),
      Rcpp::as<std::string>(responseHeaders[i]));
  }

  return pResp;
}
// [[Rcpp::export]]
List ctmcFit(List data, bool byrow=true, String name="", double confidencelevel = 0.95)
{
  CharacterVector stateData(as<CharacterVector>(data[0]).size());
  for(int i = 0; i < as<CharacterVector>(data[0]).size(); i++)
    stateData[i] = as<CharacterVector>(data[0])[i];
  NumericVector transData = data[1];
  CharacterVector sortedStates = unique(as<CharacterVector>(data[0])).sort();
  NumericVector stateCount(sortedStates.size());
  NumericVector stateSojournTime(sortedStates.size());
  
  List dtmcData = markovchainFit(stateData, "mle", byrow, 10, 0, name, false, confidencelevel);
  
  for(int i = 0; i < stateData.size() - 1; i++){
    int idx = std::find(sortedStates.begin(), sortedStates.end(), stateData[i]) - sortedStates.begin();
    stateCount[idx]++;
    stateSojournTime[idx] += transData[i+1] - transData[i];
  }
  
  S4 dtmcEst = dtmcData["estimate"];
  NumericMatrix gen = dtmcEst.slot("transitionMatrix");
  
  for(int i = 0; i < gen.nrow(); i++){
    for(int j = 0; j < gen.ncol(); j++){
      if(stateCount[i] > 0)
        gen(i, j) *= stateCount[i] / stateSojournTime[i];
    }
    if(stateCount[i] > 0)
      gen(i, i) = - stateCount[i] / stateSojournTime[i];
    else  
      gen(i, i) = -1;
  }
  
  double zscore = stats::qnorm_0(confidencelevel, 1.0, 0.0);
  NumericVector lowerConfVecLambda(sortedStates.size()), upperConfVecLambda(sortedStates.size());
  
  for(int i = 0; i < sortedStates.size(); i++){
    if(stateCount[i] > 0){
      lowerConfVecLambda(i) = std::max(0., stateCount[i] / stateSojournTime[i] * (1 - zscore / sqrt(stateCount[i])));
      upperConfVecLambda(i) = std::min(1., stateCount[i] / stateSojournTime[i] * (1 + zscore / sqrt(stateCount[i])));
    }
    else{
      lowerConfVecLambda(i) = 1;
      upperConfVecLambda(i) = 1;
    }
  }
  
  S4 outCtmc("ctmc");
  outCtmc.slot("states") = sortedStates;
  outCtmc.slot("generator") = gen;
  outCtmc.slot("name") = name;
  
  return List::create(_["estimate"] = outCtmc,
                      _["errors"] = List::create(_["dtmcConfidenceInterval"] = dtmcData["confidenceInterval"],
                      _["lambdaConfidenceInterval"] = List::create(_["lowerEndpointVector"] = lowerConfVecLambda,
                      _["upperEndpointVector"] = upperConfVecLambda)));
}
// [[Rcpp::export]]
std::string character_iterator1( CharacterVector letters ){
    std::string res ;
    CharacterVector::iterator first = letters.begin() ;
    CharacterVector::iterator last = letters.end() ;
    while( first != last ){
        res += *first ;
    	++first ;
    }
    return res ;
}
Exemple #6
0
void check_dataframes_names_consistency(const List& x) {
  CharacterVector ref = get_element_names(x, 0);
  int equi_named = 1;

  for (int i = 0; i < x.size(); ++i) {
    CharacterVector names = get_element_names(x, i);
    equi_named *= std::equal(ref.begin(), ref.end(), names.begin());
  }

  if (!equi_named)
    stop("data frames do not have consistent names");
}
Exemple #7
0
void inner_find(CharacterVector& y,IDFmap& m,unsigned int dis){
  for(CharacterVector::iterator it = y.begin();it!=y.end();it++){
    string tmp = as<string>(*it);
    IDFmap::iterator m_it = m.find(tmp);
    if(m_it==m.end()){
      m[tmp].first=dis;
      m[tmp].second=1;
    }else{
      if((*m_it).second.first != dis){
        (*m_it).second.first = dis;
        (*m_it).second.second =(*m_it).second.second+1;
      }
    }
  }
}
Exemple #8
0
// [[Rcpp::export]]
void write_lines_(const CharacterVector &lines, const std::string &path, const std::string& na, bool append = false) {

  std::ofstream output(path.c_str(), append ? std::ofstream::app : std::ofstream::trunc);
  if (output.fail()) {
    stop("Failed to open '%s'.", path);
  }
  for (CharacterVector::const_iterator i = lines.begin(); i != lines.end(); ++i) {

    if (CharacterVector::is_na(*i)) {
      output << na << '\n';
    } else {
      output << Rf_translateCharUTF8(*i) << '\n';
    }
  }

  return;
}
Exemple #9
0
vector<mihandle_t> open_minc2_volumes(CharacterVector filenames){
  
  vector<mihandle_t> volumes;
  mihandle_t current_handle;
  CharacterVector::iterator file_iterator;
  vector<mihandle_t>::iterator volume_iterator;
  
  for(file_iterator = filenames.begin();
      file_iterator != filenames.end();
      ++file_iterator){
    try {
      current_handle = open_minc2_volume(wrap(*file_iterator));
    } catch(...){
      for(volume_iterator = volumes.begin(); volume_iterator != volumes.end(); ++volume_iterator){
        miclose_volume(*volume_iterator);
      }
      throw;
    }
    
    volumes.push_back(current_handle);
  }
  
  return(volumes);
}
// [[Rcpp::export]]
int character_find_(CharacterVector y){
	CharacterVector::iterator it = std::find( y.begin(), y.end(), "foo" ) ;
	return std::distance( y.begin(), it );
}
// [[Rcpp::export]]
CharacterVector character_reverse( CharacterVector y ){
    std::reverse( y.begin(), y.end() ) ;
    return y ;
}
// [[Rcpp::export]]
std::string character_iterator2( CharacterVector letters ){
    std::string res(std::accumulate(letters.begin(), letters.end(), std::string()));
    return res ;
}
// Checks for unknown variables in expression
// [[Rcpp::export]]
void check_for_unknown_vars_impl(List model, SEXP x) {
  std::stack<SEXP> stack;
  stack.push(x);
  List model_vars = model["variables"];
  std::string error_msg =
      "The expression contains a variable that is not part of the model.";
  while (!stack.empty()) {
    SEXP local_obj = stack.top();
    stack.pop();
    int local_obj_type = TYPEOF(local_obj);
    bool is_call = local_obj_type == LANGSXP;
    if (local_obj_type == SYMSXP) {
      try {
        CharacterVector var = local_obj;
        std::string var_name = as<std::string>(var[0]);
        List model_var = model_vars[var_name];
        int arity = model_var["arity"];
        if (arity > 0) {
          throw std::invalid_argument("");
        }
      } catch (...) {
        ::Rf_error(error_msg.c_str());
      }
    }
    if (is_call) {
      Language ast(local_obj);
      int n_size = ast.size();
      if (n_size >= 3) {
        CharacterVector op(ast[0]);
        std::string op_string = as<std::string>(op);
        if (op_string == "[" && TYPEOF(ast[1]) == SYMSXP) {
          CharacterVector var = ast[1];
          std::string var_name = as<std::string>(var[0]);
          try {
            List var = model_vars[var_name];
            CharacterVector instances = var["instances"];

            // build search key
            std::ostringstream str;
            for (int i = 2; i < n_size; i++) {
              CharacterVector idx = ast[i];
              str << as<std::string>(idx);
              if (i != n_size - 1) {
                str << "_";
              }
            }
            if (n_size > 1) {
              CharacterVector search_key = str.str();
              bool found = std::find(instances.begin(), instances.end(),
                                     search_key[0]) != instances.end();
              if (!found) {
                throw std::invalid_argument("");
              }
            }
          } catch (...) {
            ::Rf_error(error_msg.c_str());
          }
          continue;
        }
      }
      for (int i = 1; i < ast.size(); i++) {
        stack.push(ast[i].get());
      }
    }
  }
}
// [[Rcpp::export]]
List is_valid_nt_fasta_format(CharacterVector file_lines)
{
	long header_count = 0;
	long line_count = 0;
	for(CharacterVector::iterator it = file_lines.begin(); it != file_lines.end(); ++it)
	{	
		line_count++;
		long count = 0;
		for (int i = 0; i < (*it).size(); ++i)
		{
			char x = (*it)[i];
		// }
		// for(auto &x : *it)
		// {

      if(header_count == 0 && x != '>')
      {
        return List::create(_["isFasta"] = false, _["failMsg"] = "First non-blank line was not FASTA header line beginning with '>' on line ");// + static_cast<std::ostringstream*>( &(std::ostringstream() << line_count)->str() ));
      }
			if(count == 0 && x == '>')
			{
				header_count++;
				break;
			}
			count++;
			switch (x)
			{
				case 'A':case 'a':
				case 'C':case 'c':
				case 'G':case 'g':
				case 'T':case 't':
				case 'R':case 'r':
				case 'Y':case 'y':
				case 'S':case 's':
				case 'W':case 'w':
				case 'K':case 'k':
				case 'M':case 'm':
				case 'B':case 'b':
				case 'D':case 'd':
				case 'H':case 'h':
				case 'V':case 'v':
				case 'N':case 'n':
					continue;
				default:
					std::string tmp;
					std::stringstream ss;
					ss << x;
					ss >> tmp;
					return List::create(_["isFasta"] = false, _["failMsg"] = "Unexpected character '" + tmp + "' on line ");// + static_cast<std::ostringstream*>( &(std::ostringstream() << line_count) )-str() + " column " + static_cast<std::ostringstream*>( &(std::ostringstream() << count)->str() ));
			}
		}
	}
	if (header_count > 0)
	{
		return List::create(_["isFasta"] = true, _["failMsg"] = "");
	}
	else
	{
		return List::create(_["isFasta"] = false, _["failMsg"] = "No headers (i.e. lines starting with '>') in file");
	}
}
//' 
//' Convert Japanese alphanumerics to ASCII alphanumerics
//' 
//' @title halfwidthen
//' @name halfwidthen
//' 
//' @param x A string to convert
//' 
//' @examples
//' x = c("\uff10", "\uff11")
//' halfwidthen(x)
//'
//' @export
// [[Rcpp::export]]
CharacterVector halfwidthen(CharacterVector x) {
  CharacterVector str(x.size());
  std::transform(x.begin(), x.end(), str.begin(), halfwidthen_one);
  return str;
}