Exemple #1
0
void Camera::preHandle ()
{
    _dx = standardize (_dx);
    _dy = standardize (_dy);
    _normal = standardize (_normal);
    _r2 = _radius * _radius;
    _apertureDis = std::uniform_real_distribution<> (-_radius, _radius);
}
void Request::addHeader(const char* key, const char* value) {
  std::string header_type(key);
  std::string header_value(value);
  
  if(!header_type.compare("If-Modified-Since")){
    headers[header_type] = header_value;}
  else{
    header_type = standardize(header_type);
    header_value = standardize(header_value);
    headers[header_type] = header_value;
  }
}
Exemple #3
0
calendar &calendar::operator +=(int rhs)
{
    turn_number += rhs;
    second += rhs * 6;
    standardize();
    return *this;
}
Exemple #4
0
std::string calendar::textify_period()
{
 standardize();
 std::stringstream ret;
 int am;
 std::string tx;
// Describe the biggest time period, as "<am> <tx>s", am = amount, tx = name 
 if (year > 0) {
  am = year;
  tx = "year";
 } else if (season > 0) {
  am = season;
  tx = "season";
 } else if (day > 0) {
  am = day;
  tx = "day";
 } else if (hour > 0) {
  am = hour;
  tx = "hour";
 } else if (minute >= 5) {
  am = minute;
  tx = "minute";
 } else {
  am = second / 6 + minute * 10;
  tx = "turn";
 }

 ret << am << " " << tx << (am > 1 ? "s" : "");

 return ret.str();
}
PUBLIC char *
pure_lambda_action (char *A, char *B, char *Law, interpreter * L)
{
  char *r, *result;
  char buffer[BUFSIZE];

  /* (A)B -> result */

  if ((strlen (A) + strlen (B)) >= (BUFSIZE-200))
    return NULL;

  strcpy (buffer, "eval ((");
  strcat (buffer, Law);
  strcat (buffer, ")");
  strcat (buffer, A);
  strcat (buffer, ")");
  strcat (buffer, B);
  strcat (buffer, ";");

  /* reduce to normal form */

  r = reduce_lambda (buffer, L);
  result = standardize (r, L);
  free (r);

  return result;
}
Exemple #6
0
std::string calendar::textify_period()
{
 standardize();
 int am;
 const char* tx;
// Describe the biggest time period, as "<am> <tx>s", am = amount, tx = name
 if (year > 0) {
  am = year;
  tx = ngettext("%d year", "%d years", am);
 } else if (season > 0) {
  am = season;
  tx = ngettext("%d season", "%d seasons", am);
 } else if (day > 0) {
  am = day;
  tx = ngettext("%d day", "%d days", am);
 } else if (hour > 0) {
  am = hour;
  tx = ngettext("%d hour", "%d hours", am);
 } else if (minute >= 5) {
  am = minute;
  tx = ngettext("%d minute", "%d minutes", am);
 } else {
  am = second / 6 + minute * 10;
  tx = ngettext("%d turn", "%d turns", am);
 }

 return string_format(tx, am);
}
Exemple #7
0
void calendar::increment()
{
    turn_number++;
    second += 6;
    if (second >= 60) {
        standardize();
    }
}
bool c_CurveClustering::standardize(void)
{
    /*!< for each curve, convert to the standard form */
    size_t n_curves = m_p_curve_set->size();
    for (size_t i = 0; i < n_curves; ++i)
    {
        standardize((*m_p_curve_set)[i], m_standard_curve_set[i]);
    }
    return true;
}
Metavalue::Metavalue(const std::string& _keyword, std::type_index _datatype,
	const std::string& _value, const std::string& _comment)
		: keyword(_keyword), datatype(_datatype), value(_value),
		  comment(_comment) {
	if (datatype != std::type_index(typeid(void))) {
		standardize();
	} else {
		debug(LOG_DEBUG, DEBUG_LOG, 0, "don't standardize comments");
	}
}
/**
 * \brief parse a buffer into a property triple
 */
property_triple::property_triple(const std::string& buffer) {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "creating property from '%s'",
		buffer.c_str());
	std::string	b = standardize(buffer);
	size_t	equalsign = b.rfind('=');
	if (std::string::npos == equalsign) {
		throw badproperty();
	}
	value = trim(b.substr(equalsign + 1));
	std::string	key = trim(b.substr(0, equalsign));
	size_t	position = key.find_last_of(" \t");
	if (std::string::npos == position) {
		throw badproperty();
	}
	devicename = standardize(key.substr(0, position));
	property = standardize(key.substr(position + 1));
	debug(LOG_DEBUG, DEBUG_LOG, 0, "found triple: device = '%s', "
		"property = '%s', value = '%s'",
		devicename.c_str(), property.c_str(), value.c_str());
}
Exemple #11
0
bool URL::isEqual(wchar_t* urlString) {
	if (!urlString) {
		return !isValid();
	}

	std::wstring string(urlString);
	if (!standardize(&string)) {
		return false;
	}

	return wcscmp(m_value, string.c_str()) == 0;
}
bool c_CurveClustering::solve(void)
{
    /*!< step 1: standardize curve set for further process */
    standardize();

    /*!< step 2: calculate similarities */
    calculate_similarities(m_similarities);

//    show_similarity_matrix();

    /*!< step 3: cluster standardized curve set */
    cluster(m_similarities);

    return true;
}
Exemple #13
0
Population SUS::do_selection(const Population& population, const vector<float>& fitness) {
  vector<float> standard_fitness = standardize(fitness);
  Population new_population;
  float flindex = random_number_in_01();
  int picked_index = 1;
  for (int i = 0; i < int(population.size()) && picked_index <= int(population.size()); i++) {
    flindex += standard_fitness[i];
    while (picked_index < flindex) {
      if (picked_index <= int(population.size()))
        new_population.push_back(population[picked_index - 1]);
      picked_index++;
    }
  }
  return new_population;
}
Exemple #14
0
bool URL::setString(wchar_t* value) {
	if (m_value) {
		delete[] m_value;
		m_value = NULL;
	}

	if (value) {
		std::wstring string(value);
		if (!standardize(&string)) {
			return false;
		}
		m_value = _wcsdup(string.c_str());
	}
	return true;
}
Exemple #15
0
calendar& calendar::operator +=(calendar &rhs)
{
 second += rhs.second;
 minute += rhs.minute;
 hour   += rhs.hour;
 day    += rhs.day;
 int tmpseason = int(season) + int(rhs.season);
 while (tmpseason >= 4) {
  year++;
  tmpseason -= 4;
 }
 season = season_type(tmpseason);
 year += rhs.year;
 standardize();
 return *this;
}
Exemple #16
0
calendar& calendar::operator -=(calendar &rhs)
{
 calendar tmp(rhs);
 tmp.standardize();
 second -= tmp.second;
 minute -= tmp.minute;
 hour   -= tmp.hour;
 day    -= tmp.day;
 int tmpseason = int(season) - int(tmp.season);
 while (tmpseason < 0) {
  year--;
  tmpseason += 4;
 }
 season = season_type(tmpseason);
 year -= tmp.year;
 standardize();
 return *this;
}
Exemple #17
0
float detect_lm(SPH &searchsph, SPH &testsph, SHORTIM testim, int lmcm[], SPH &refsph, int lm[])
{
   float ccmax=-1.0;

   for(int n=0; n<searchsph.n; n++)
   {
      testsph.set(testim, lmcm[0]+searchsph.i[n], lmcm[1]+searchsph.j[n], lmcm[2]+searchsph.k[n]);
      standardize(testsph.v, testsph.n);
      searchsph.v[n] = dot(testsph.v, refsph.v, testsph.n);
      if( searchsph.v[n] > ccmax )
      {
         ccmax = searchsph.v[n];
         lm[0] = lmcm[0]+searchsph.i[n];
         lm[1] = lmcm[1]+searchsph.j[n];
         lm[2] = lmcm[2]+searchsph.k[n];
      }
   }

   return(ccmax);
}
Exemple #18
0
int main(int narg, char *arg[10])
{
struct edge *color[maxrank];
int i,j,rank,vert;
int graph[maxvert][maxvert];
long time; float t;
long start_time,end_time;
f=fopen(arg[1],"r");        /* char */
if (f == NULL) { printf("\n file does not exist\n"); exit(0);}
fscanf (f,"%d%d",&rank,&vert);
for (i=0;i<vert;i++) for(j=0;j<vert;j++) fscanf (f, "%d", &graph[i][j]);
antisymmetrize(graph, vert);
rank=standardize(graph,vert);
i=edgepack (graph,rank,vert,color); 
if(i==0) {printf("please check your input!\n"); return;}
printf ("\n\n number of colors: ");

start_time=clock()/1000;
stabil (&rank,vert,graph,color);
end_time=clock()/1000-start_time;

printf("\b\b\b\b\b\b%6d",rank);
for(i=0; i<rank; i++) color[i]->row=-1; j=0;
for(i=0; i<vert; ++i) {
 if(color[graph[i][i]]->row<0) color[graph[i][i]]->row=j++;};
printf ("\n\n number of cells: %6d", j);
for(i=0; i<rank; ++i) if(color[i]->row<0) color[i]->row=j++;
printf("\n\n adjacency matrix of the cellular algebra:\n\n");
 for(i=0; i<vert; ++i) { 
     for(j=0; j<vert; ++j) { 
       printf("%4d ",graph[i][j]);
     };
     printf("\n");
 };
/* printf("\n\n%ld msec \n\n",end_time); */
}
void RandomPCA::pca(MatrixXd &X, int method, bool transpose,
   unsigned int ndim, unsigned int nextra, unsigned int maxiter, double tol,
   long seed, int kernel, double sigma, bool rbf_center,
   unsigned int rbf_sample, bool save_kernel, bool do_orth, bool do_loadings)
{
   unsigned int N;

   if(kernel != KERNEL_LINEAR)
   {
      transpose = false;
      verbose && std::cout << timestamp()
	 << " Kernel not linear, can't transpose" << std::endl;
   }

   verbose && std::cout << timestamp() << " Transpose: " 
      << (transpose ? "yes" : "no") << std::endl;

   if(transpose)
   {
      if(stand_method != STANDARDIZE_NONE)
	  X_meansd = standardize_transpose(X, stand_method, verbose);
      N = X.cols();
   }
   else
   {
      if(stand_method != STANDARDIZE_NONE)
	 X_meansd = standardize(X, stand_method, verbose);
      N = X.rows();
   }

   unsigned int total_dim = ndim + nextra;
   MatrixXd R = make_gaussian(X.cols(), total_dim, seed);
   MatrixXd Y = X * R;
   verbose && std::cout << timestamp() << " dim(Y): " << dim(Y) << std::endl;
   normalize(Y);
   MatrixXd Yn;

   verbose && std::cout << timestamp() << " dim(X): " << dim(X) << std::endl;
   MatrixXd K; 
   if(kernel == KERNEL_RBF)
   {
      if(sigma == 0)
      {
	 unsigned int med_samples = fminl(rbf_sample, N);
      	 double med = median_dist(X, med_samples, seed, verbose);
      	 sigma = sqrt(med);
      }
      verbose && std::cout << timestamp() << " Using RBF kernel with sigma="
	 << sigma << std::endl;
      K.noalias() = rbf_kernel(X, sigma, rbf_center, verbose);
   }
   else
   {
      verbose && std::cout << timestamp() << " Using linear kernel" << std::endl;
      K.noalias() = X * X.transpose() / (N - 1);
   }

   //trace = K.diagonal().array().sum() / (N - 1);
   trace = K.diagonal().array().sum();
   verbose && std::cout << timestamp() << " Trace(K): " << trace 
      << " (N: " << N << ")" << std::endl;

   verbose && std::cout << timestamp() << " dim(K): " << dim(K) << std::endl;
   if(save_kernel)
   {
      verbose && std::cout << timestamp() << " saving K" << std::endl;
      save_text("kernel.txt", K);
   }

   for(unsigned int iter = 0 ; iter < maxiter ; iter++)
   {
      verbose && std::cout << timestamp() << " iter " << iter;
      Yn.noalias() = K * Y;
      if(do_orth)
      {
	 verbose && std::cout << " (orthogonalising)";
	 ColPivHouseholderQR<MatrixXd> qr(Yn);
	 MatrixXd I = MatrixXd::Identity(Yn.rows(), Yn.cols());
	 Yn = qr.householderQ() * I;
	 Yn.conservativeResize(NoChange, Yn.cols());
      }
      else
	 normalize(Yn);

      double diff =  (Y -  Yn).array().square().sum() / Y.size(); 
      verbose && std::cout << " " << diff << std::endl;
      Y.noalias() = Yn;
      if(diff < tol)
	 break;
   }

   verbose && std::cout << timestamp() << " QR begin" << std::endl;
   ColPivHouseholderQR<MatrixXd> qr(Y);
   MatrixXd Q = MatrixXd::Identity(Y.rows(), Y.cols());
   Q = qr.householderQ() * Q;
   Q.conservativeResize(NoChange, Y.cols());
   verbose && std::cout << timestamp() << " dim(Q): " << dim(Q) << std::endl;
   verbose && std::cout << timestamp() << " QR done" << std::endl;

   MatrixXd B = Q.transpose() * X;
   verbose && std::cout << timestamp() << " dim(B): " << dim(B) << std::endl;

   MatrixXd Et;
   pca_small(B, method, Et, d, verbose);
   verbose && std::cout << timestamp() << " dim(Et): " << dim(Et) << std::endl;

   d = d.array() / (N - 1);

   if(transpose)
   {
      V.noalias() = Q * Et;
      // We divide P by sqrt(N - 1) since X has not been divided
      // by it (but B has)
      P.noalias() = X.transpose() * V;
      VectorXd s = 1 / (d.array().sqrt() * sqrt(N - 1));
      MatrixXd Dinv = s.asDiagonal();
      U = P * Dinv;
   }
   else
   {
      // P = U D = X V
      U.noalias() = Q * Et;
      P.noalias() = U * d.asDiagonal();
      if(do_loadings)
      {
	 VectorXd s = 1 / (d.array().sqrt() * sqrt(N - 1));
	 MatrixXd Dinv = s.asDiagonal();
	 V = X.transpose() * U * Dinv;
      }
   }

   P.conservativeResize(NoChange, ndim);
   U.conservativeResize(NoChange, ndim);
   V.conservativeResize(NoChange, ndim);
   d.conservativeResize(ndim);
   pve = d.array() / trace;
}
PRIVATE char *
_lambda_action (char *A, organization * OA, char *B, organization * OB,
		simulation * S, interpreter * L)
{
  char *r, *result, *sigma;
  char buffer[BUFSIZE];

  I_CODE = '+';
  
  /* (A)B -> result */
  
  if ((strlen (A) + strlen (B)) >= (BUFSIZE-500))
    return NULL;

  if (syntax_sieve (A, OA->Filter.regexp[OPERATOR], S->type_check))
    {
      if (syntax_sieve (B, OB->Filter.regexp[ARGUMENT], S->type_check))
	{
	  strcpy (buffer, "eval ((");
	  strcat (buffer, choose_law (OA));
	  strcat (buffer, ")");
	  strcat (buffer, A);
	  strcat (buffer, ")");
	  strcat (buffer, B);

	  /* type checking filter */
	  
	  if (S->type_check)
	    sigma = type_synthesis (buffer + 5);
	  else
	    sigma = buffer; /* something non-NULL */
	    
	  if (sigma)
	    {
	      /* passed filters; now reduce to normal form */

	      strcat (buffer, ";");  /* terminate phrase */
	      
	      r = reduce_lambda (buffer, L);  REDUCTIONS = L->reductions;
	      result = standardize (r, L);
	      free (r);
	      
	      if (syntax_sieve (result, OA->Filter.regexp[RESULT], S->type_check))
		{
		  return result;
		}
	      else
		{
		  I_CODE = 'R';
		  free (result);
		}
	    }
	  else
	    {
	      I_CODE = 'T';
	      S->typeclashes++;
	    }
	}
      else
	{
	  I_CODE = 'A';
	}
    }
  else
    {
      I_CODE = 'O';
    }
  return NULL;
}
Metavalue::Metavalue(const std::string& _keyword, const unsigned int ui,
	const std::string& _comment)
	: keyword(_keyword), datatype(typeid(ui)), comment(_comment) {
	value = stringprintf("%u", ui);
	standardize();
}
double RoomyGraphAlg_degreePrestigeStandardized(RoomyGraph *g, uint64 node) {
  return standardize(g, node, RoomyGraphAlg_degreePrestige);
}
/*
C'_d(n_i) = C_d(n_i) / (g-1)
where g is the number of nodes in graph g
*/
double RoomyGraphAlg_degreeCentralityStandardized(RoomyGraph *g, uint64 node) {
  return standardize(g, node, RoomyGraphAlg_degreeCentrality);
}
Metavalue::Metavalue(const std::string& _keyword, const long l,
	const std::string& _comment)
	: keyword(_keyword), datatype(typeid(l)), comment(_comment) {
	value = stringprintf("%ld", l);
	standardize();
}
Exemple #25
0
int
main (int argc, char** argv)
{
  // const char trace = 0;
  // const unsigned debug = 0;
  const char *me = "main";

  // parse and validate the command line options
  struct paramsStruct params;
  parseCommandLine(argc, argv, &params);

  // create results directory in ANALYSIS directory
  // permissions are read, write for the owner
  char resultsDirectoryName[256] = "";
  makeResultsDirectory(resultsDirectoryName, 
                       sizeof(resultsDirectoryName), 
                       &params);

  // start logging
  char logFilePath[256] = "";
  {
    const int outputLength =  snprintf(logFilePath, 
                                       sizeof(logFilePath), 
                                       "%s/run.log", 
                                       resultsDirectoryName);
    if (outputLength > (int) sizeof(logFilePath)) {
      fprintf(stderr, "%s: logFilePath too small", me);
      exit(1);
    }
  }
  Log_T log = Log_new(logFilePath, stderr);

  // log the command line parameters
  LOG(log,"started log file %s\n", logFilePath);

  LOG(log,"params: algo=%s\n",          params.algo);
  LOG(log,"      : obs=%s\n",           params.obs); 
  LOG(log,"      : radius=%d\n",        params.radius);
  LOG(log,"      : which=%s\n",         params.which);
  
  // check the command line parameters
  assert(strcmp(params.algo, "knn") == 0); 
  assert(strcmp(params.obs, "1A") == 0);
 
  // read the input files
  const unsigned nObservations = 217376;  // adjust of OBS != 1A
  const unsigned nFeatures = 55;

  double *apns = readCsvNoHeader(nObservations, "aps.csv");
  double *dates = readCsvNoHeader(nObservations, "date.csv");
  char   *featuresHeaderP;
  double *features = readFeatures(nObservations, 
				  nFeatures,
				  &featuresHeaderP);
  double *prices = readCsvNoHeader(nObservations, "SALE-AMOUNT-log.csv");

  // convert dates to days past the epoch
  unsigned dayStdColumn = 5; // the 6th column contains the standardized day value
  assert(columnHeaderEqual(featuresHeaderP, dayStdColumn, "day-std"));  
  double *days = convertDatesToDays(nObservations, dates);
  free(dates);
  double mean;
  double stdv;
  determineMeanStdv(nObservations, days, &mean, &stdv);
  double *daysStd = standardize(nObservations, days, mean, stdv);
  replaceDay(nObservations, nFeatures, features, daysStd, dayStdColumn);
  free(days);
  free(daysStd);


  // generate one set of estimates
  FILE *resultFile;
  {
    char resultFilePath[256];
    const int outputLength = 
      snprintf(resultFilePath,
               sizeof(resultFilePath),
               "%s/estimates-laufer.csv",
               resultsDirectoryName);
    if (outputLength > (int) sizeof(resultFilePath)) {
      fprintf(stderr, "%s: resultFilePath too small", me);
      exit(1);
    }
    LOG(log, " result file path: %s\n", resultFilePath);
    resultFile = fopen(resultFilePath, "w");
  }
  assert(resultFile);

  if (strcmp(params.which, "laufer"))
    createLaufer(nObservations, nFeatures, 
		 apns, dates, features, prices,
		 log,
		 resultFile);
  else
    assert(NULL != "logic error");

  // OLD CODE BELOW THIS LINE
#if 0
  double **pricesHatP = NULL;
  if (params.useCache)
    pricesHatP = readCache(nObservations, params.obs, log, kMax);

  // determine estimated prices for any missing entries in the cache
  // this operation could be fast or very slow
  // MAYBE: write out cache periodically 
  const unsigned cacheMutated = completeCache(nObservations, 
                                              pricesHatP, 
                                              params.obs, 
                                              log, 
                                              kMax, 
                                              pricesP, 
                                              debug);

  if (params.useCache && cacheMutated)
    writeCache(nObservations, pricesHatP, params.obs, log, kMax);


  // select which set of estimates to create
  if (paramsP->whichIsLaufer)
    createEstimatesLaufer(nObservations, nFeatures,
			  features, dates, prices);
  else
    assert(false); // should never get here

  // pricesHatP[i][k] is
  // the estimate priced of transaction indexed i for k nearest neighbors

  // for each value of k, determine RMSE overall all the test transactions
  // determine kArgMin, the k providing the lowest RMSE
  // write CSV containing <k, rmse> values
  char resultFilePath[256];
  {
    const int outputLength = 
      snprintf(resultFilePath,
               sizeof(resultFilePath),
               "%s/k-rmse.csv",
               directoryName);
    if (outputLength > (int) sizeof(resultFilePath)) {
      fprintf(stderr, "%s: resultFilePath too small", me);
      exit(1);
    }
    LOG(log, " result file path: %s\n", resultFilePath);
  }
  FILE *resultFile = fopen(resultFilePath, "w");
  assert(resultFile);

  // log best k for random sample of test observations
  bestK(0.01, nObservations, pricesHatP, pricesP, log, kMax);

  // write CSV header 
  fprintf(resultFile, "k,rmse\n");
  unsigned kArgMin = 0;
  double lowestRMSE = DBL_MAX;
  for (unsigned hpK = 0; hpK < kMax; hpK++) {

    // determine rmse for this k
    const double rmse = determineRmse(nObservations, pricesHatP, pricesP, hpK);

    // check if we have a new best k
    LOG(log, "hpK %u rmse %f\n", hpK + 1, rmse);
    fprintf(resultFile, "%u,%f\n", hpK + 1, rmse);
    if (rmse < lowestRMSE) {
      lowestRMSE = rmse;
      kArgMin = hpK;
    }
  }

#endif
  // 
  LOG(log, "%s\n", "finished");

  exit(0);
}
Metavalue::Metavalue(const std::string& _keyword, const int i,
	const std::string& _comment)
	: keyword(_keyword), datatype(typeid(i)), comment(_comment) {
	value = stringprintf("%d", i);
	standardize();
}
Exemple #27
0
void calendar::increment()
{
 second += 6;
 if (second >= 60)
  standardize();
}
Exemple #28
0
int main(int argc, char * argv[])
{
   po::options_description desc("Options");
   desc.add_options()
      ("help", "produce help message")
      ("bfile", po::value<std::string>(), "PLINK root name")
      ("w", po::value<std::string>(), "SNP weights filename")
      ("stand", po::value<std::string>(), "standardization method [none | binom | sd | center]")
      ("out", po::value<std::string>(), "output filename")
      ("numthreads", po::value<int>(), "set number of OpenMP threads")
   ;

   po::variables_map vm;
   po::store(po::parse_command_line(argc, argv, desc), vm);
   po::notify(vm);

   if(vm.count("help"))
   {
      std::cerr << desc << std::endl;
      return EXIT_FAILURE;
   }

   int num_threads = 1;
   if(vm.count("numthreads"))
      num_threads = vm["numthreads"].as<int>();


   int stand_method = STANDARDIZE_BINOM;
   if(vm.count("stand"))
   {
      std::string m = vm["stand"].as<std::string>();
      if(m == "binom")
	 stand_method = STANDARDIZE_BINOM;
      else if(m == "sd")
	 stand_method = STANDARDIZE_SD;
      else if(m == "center")
	 stand_method = STANDARDIZE_CENTER;
      else if(m == "none")
	 stand_method = STANDARDIZE_NONE;
      else
      {
	 std::cerr << "Error: unknown standardization method (--stand): "
	    << m << std::endl;
	 return EXIT_FAILURE;
      }
   }

   std::string geno_file, fam_file;
   if(vm.count("bfile"))
   {
      geno_file = vm["bfile"].as<std::string>() + std::string(".bed");
      fam_file = vm["bfile"].as<std::string>() + std::string(".fam");
      std::cout << ">>> genotype file: " << geno_file << std::endl;
   }
   else
   {
      std::cerr << "Error: bfile not specified" << std::endl;
      return EXIT_FAILURE;
   }

   std::string w_file;
   if(vm.count("w"))
   {
      w_file = vm["w"].as<std::string>();
   }

   std::string out_file = "PredX.txt";
   if(vm.count("out"))
   {
      out_file = vm["out"].as<std::string>();
   }

#ifdef _OPENMP
#ifdef EIGEN_HAS_OPENMP
   omp_set_num_threads(num_threads);
   std::cout << timestamp() << " Using " << num_threads 
      << " OpenMP threads" << std::endl;
#endif
#endif

   Data data(1);
   data.verbose = true;
   data.read_pheno(fam_file.c_str(), 6);
   data.geno_filename = geno_file.c_str();
   data.get_size();
   data.read_bed(false);

   standardize(data.X, stand_method, false);
   MatrixXd W = data.read_plink_pheno(w_file.c_str(), 1);
   MatrixXd P = data.X * W;

   save_text(P, out_file.c_str());

   return EXIT_SUCCESS;
}
Exemple #29
0
static int pca_save_components (VMatrix *cmat, 
				gretl_matrix *E, 
				gretl_matrix *C, 
				DATASET *dset,
				int nsave,
				gretlopt opt)
{
    int save_all = (opt & OPT_A);
    double x, **sZ = NULL;
    int m = 0, v = dset->v;
    int k = cmat->dim;
    int i, j, t, vi;
    int err = 0;

    if (save_all) {
	m = k;
    } else if (nsave > 0) {
	m = nsave > k ? k : nsave;
    } else {
	for (i=0; E->val[i] > 1.0; i++) {
	    m++;
	} 
    }

    err = dataset_add_series(dset, m);

    if (!err) {
	/* construct standardized versions of all variables */
	sZ = doubles_array_new(k, dset->n); 
	if (sZ == NULL) {
	    err = E_ALLOC;
	} else {
	    for (i=0; i<k && !err; i++) {
		vi = cmat->list[i+1];
		err = standardize(sZ[i], dset->Z[vi], dset->n);
	    }
	}
    }

    if (!err) {
	gchar *label;
	double load;

	for (i=0; i<m; i++) {
	    vi = v + i;
	    sprintf(dset->varname[vi], "PC%d", i+1);
	    make_varname_unique(dset->varname[vi], vi, dset);
	    label = g_strdup_printf(_("Component with eigenvalue = %.4f"),
				    E->val[i]);
	    series_set_label(dset, vi, label);
	    g_free(label);
	    for (t=0; t<dset->n; t++) {
		if (t < dset->t1 || t > dset->t2) {
		    dset->Z[vi][t] = NADBL;
		    continue;
		}
		dset->Z[vi][t] = 0.0;
		for (j=0; j<k; j++) {
		    x = sZ[j][t];
		    if (na(x)) {
			dset->Z[vi][t] = NADBL;
			break;
		    } else {
			load = gretl_matrix_get(C, j, i);
			dset->Z[vi][t] += load * x;
		    }
		}
	    }
	}
    }

    doubles_array_free(sZ, k);

    return err;
}
matrix::Matrix loadInputData()
{
    auto matrix = loadInputDataMatrix();

    return standardize(slice(matrix, {0, 0}, {matrix.size()[0] - 1, matrix.size()[1]}));
}