Example #1
0
//' Marginal correlation matrix
//' 
//' Various workhorse functions to compute the marginal (or unconditional) 
//' correlations (and cross-correlation) estimates efficiently. 
//' They are (almost) 
//' equivalent implementations of \code{\link[stats]{cor}} in Rcpp, 
//' RcppArmadillo, and RcppEigen.
//' 
//' @rdname corFamily
//' @aliases corFamily
//'   corRcpp xcorRcpp corArma xcorArma corEigen xcorEigen
//' @param X A numeric matrix.
//' @param Y A numeric matrix of compatible dimension with the \code{X}, i.e. 
//'   \code{nrow(X)} equals \code{nrow(Y)}.
//' @return
//'   The \code{corXX} family returns a numeric correlation matrix of size 
//'   \code{ncol(X)} times \code{ncol(X)}.
//'   
//'   The \code{xcorXX} family returns a numeric cross-correlation matrix 
//'   of size \code{ncol(X)} times \code{ncol(Y)}.
//' @details
//'   Functions almost like \code{\link{cor}}.
//'   For the \code{xcorXX} functions, the \code{i}'th and \code{j}'th 
//'   entry of the output matrix is the correlation between \code{X[i, ]} and 
//'   \code{X[j, ]}.
//'   Likewise, for the \code{xcorXX} functions, the \code{i}'th and
//'   \code{j}'th entry of the output is the correlation between \code{X[i, ]} 
//'   and \code{Y[j, ]}.
//' @note 
//'   \code{NA}s in \code{X} or \code{Y} will yield \code{NA}s in the correlation matrix.
//'   This also includes the diagonal unlike the behavior of 
//'   \code{\link[stats]{cor}}.
//' @author Anders Ellern Bilgrau <anders.ellern.bilgrau (at) gmail.com>
//' @export
// [[Rcpp::export]]
Rcpp::NumericMatrix corRcpp(Rcpp::NumericMatrix & X) {
  
  const int m = X.ncol();
  const int n = X.nrow();
  
  // Centering the matrix
  X = centerNumericMatrix(X);
  
  Rcpp::NumericMatrix cor(m, m);
  
  // Degenerate case
  if (n == 0) {
    std::fill(cor.begin(), cor.end(), Rcpp::NumericVector::get_na());
    return cor; 
  }
  
  // Compute 1 over the sample standard deviation
  Rcpp::NumericVector inv_sqrt_ss(m);
  for (int i = 0; i < m; ++i) {
    inv_sqrt_ss(i) = 1/sqrt(Rcpp::sum(X(Rcpp::_, i)*X(Rcpp::_, i)));
  }
  
  // Computing the correlation matrix
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j <= i; ++j) {
      cor(i, j) = Rcpp::sum(X(Rcpp::_,i)*X(Rcpp::_,j)) *
        inv_sqrt_ss(i) * inv_sqrt_ss(j);
      cor(j, i) = cor(i, j);
    }
  }

  return cor;
}
Example #2
0
//T: O(ElogV), M: theta(V + E)
void dijkstra(vector<vector<Aresta> > &g, int r) {
    int n = g.size();
	
	vector<Vertice> Q;
	d.clear();
	d.resize(n, INT_MAX);
    vector<bool> cor(n, false);

    Q.push_back(r);
    d[r] = 0;
    cor[r] = true;
 
    while (!Q.empty()) {
        int u = Q[0];
        //if(procurado == u) return;
        pop_heap(Q.begin(), Q.end(), comp); 
		Q.pop_back();
 
        for (int i = 0; i < g[u].size(); i++) {
            if (d[u] + g[u][i].p < d[g[u][i].v])
                d[g[u][i].v] = d[u] + g[u][i].p; //relaxamento
            if (!cor[g[u][i].v]) {
                cor[g[u][i].v] = true;
                Q.push_back(g[u][i].v);
            }
        }
 
        make_heap(Q.begin(), Q.end(), comp);
    }
}
Example #3
0
void tst_QTemporaryDir::nonWritableCurrentDir()
{
#ifdef Q_OS_UNIX
    if (::geteuid() == 0)
        QSKIP("not valid running this test as root");

    struct ChdirOnReturn
    {
        ChdirOnReturn(const QString& d) : dir(d) {}
        ~ChdirOnReturn() {
            QDir::setCurrent(dir);
        }
        QString dir;
    };
    ChdirOnReturn cor(QDir::currentPath());

    QDir::setCurrent("/home");
    // QTemporaryDir("tempXXXXXX") is probably a bad idea in any app
    // where the current dir could anything...
    QTemporaryDir dir("tempXXXXXX");
    dir.setAutoRemove(true);
    QVERIFY(!dir.isValid());
    QVERIFY(dir.path().isEmpty());
#endif
}
Example #4
0
char obj_figura::exibe()
{
  if (!carquivo_definido)
    return FALSO;
  else
   {
     if (!cbuffer_definido)
     {
       cbuffer = (estrutura_circular*) malloc(sizeof(estrutura_circular) * cnumero_de_nos);
       cbuffer_definido = VERDADEIRO;

       rewind(carquivo);
       fread(cbuffer, sizeof(estrutura_circular), cnumero_de_nos, carquivo);
     }

     if (cgrossura == 3)
       setlinestyle(SOLID_LINE, 1, 3);
     else
       setlinestyle(SOLID_LINE, 1, 1);

     for (unsigned int cont = 0; cont < cnumero_de_nos; cont++)
     {
       tipo_xy x1, y1, x2, y2;
       converte(cbuffer[cont].angulo1 + cangulo, cbuffer[cont].raio1 * craio, &x1, &y1, cx, cy);
       converte(cbuffer[cont].angulo2 + cangulo, cbuffer[cont].raio2 * craio, &x2, &y2, cx, cy);
       cor(cbuffer[cont].cor);
       line(x1, y1, x2, y2);
     }

     return VERDADEIRO;
   }
}
Example #5
0
double Fractais::leftRigth(Mat image, int op, int p)
{
    Mat aux;
    cvtColor(image,image,CV_BGR2GRAY);
    threshold(image,image,200.0,255.0,THRESH_BINARY);
    cvtColor(image,aux,CV_GRAY2RGB);

    int c;
    switch (op) {
    case 1:
        c = image.cols-1;
        break;
    default:
        c = 0;
        break;
    }

    Vec3b cor(0,0,0);
    for(int i=0; i<aux.rows;i++){
        if(aux.at<Vec3b>(i,c) != cor){
            floodFill(aux, Point(c,i), Scalar(0.0,0.0,0.0));
        }
    }

    cvtColor(aux,aux,CV_RGB2GRAY);
    absdiff(aux,image,aux);

    return press(aux,1, p);
}
Example #6
0
char obj_figura::apaga(const tipo_cor& vcor)
{
  if (!carquivo_definido)
    return FALSO;
  else
   {
     if (!cbuffer_definido)
     {
       cbuffer = (estrutura_circular*) malloc(sizeof(estrutura_circular) * cnumero_de_nos);
       cbuffer_definido = VERDADEIRO;
       rewind(carquivo);
       fread(cbuffer, sizeof(estrutura_circular), cnumero_de_nos, carquivo);
     }

     for (unsigned int cont = 0; cont < cnumero_de_nos; cont++)
     {
       tipo_xy x1, y1, x2, y2;
       converte(cbuffer[cont].angulo1 + cangulo, cbuffer[cont].raio1 * craio, &x1, &y1, cx, cy);
       converte(cbuffer[cont].angulo2 + cangulo, cbuffer[cont].raio2 * craio, &x2, &y2, cx, cy);
       cor(vcor);
       line(x1, y1, x2, y2);
     }

     return VERDADEIRO;
   }
}
Example #7
0
double Fractais::topDown(Mat image, int op, int p)
{
    Mat aux;
    cvtColor(image,image,CV_BGR2GRAY);
    threshold(image,image,200.0,255.0,THRESH_BINARY);
    cvtColor(image,aux,CV_GRAY2RGB);

    int r;
    switch (op) {
    case 1:
        r=image.rows-1;
        break;
    default:
        r = 0;
        break;
    }

    Vec3b cor(0,0,0);

    for(int i=0; i<aux.cols;i++){
        Vec3b c = aux.at<Vec3b>(r,i);
        if(c != cor){
            Point x(i,r);
            floodFill(aux, x, Scalar(0.0,0.0,0.0));
        }
    }

    cvtColor(aux,aux,CV_RGB2GRAY);
    absdiff(aux,image,aux);

    return press(aux,0,p);
}
Example #8
0
arma::vec Vespucci::Math::Quantification::CorrelationMat(const arma::mat &X, arma::vec control)
{
    arma::vec results;
    results.set_size(X.n_cols);
    for(arma::uword i = 0; i < X.n_cols; ++i){
        results(i) = arma::as_scalar(cor(control, X.col(i)));
    }
    return results;
}
Example #9
0
Arv* moveDirRed(Arv* arv)
{
	trocarCor(arv);
	if(cor(arv->esq->esq) == RED)
	{
		arv = rDir(arv);
		trocaCor(arv);
	}
	return arv;
}
Example #10
0
vector<vector<size_t> > match2corv(const vector<vector<cv::DMatch> >& matches)
{
	vector<vector<size_t> > cor(matches.size());
	for(size_t i=0; i<matches.size(); i++) {
		cor[i].resize(matches[i].size());
		for(size_t j=0; j<matches[i].size(); j++)
			cor[i][j] = matches[i][j].trainIdx;
	}
	return cor;
}
Example #11
0
Arv* moveEsqRed(Arv* arv)
{
	trocarCor(arv);
	if(cor(arv->dir->esq) == RED)
	{
		arv->dir = rDir(arv->dir);
		arv = rEsq(arv);
		trocarCor(arv);
	}
	return arv;
}
// [[Rcpp::export]]
arma::mat BeQTL2(const arma::mat & A, const arma::mat & B, const arma::umat & Bootmat){
  int bsi= Bootmat.n_rows;
  arma::mat C(A.n_cols*B.n_cols,Bootmat.n_rows);
  arma::mat tC(A.n_rows,B.n_rows);
  for(int i=0; i<bsi; i++){
    tC = cor(A.rows(Bootmat.row(i)),B.rows(Bootmat.row(i)));
    C.col(i) = vectorise(tC,0);
  }
  C.elem(find_nonfinite(C)).zeros();

  return reshape(median(C,1),A.n_cols,B.n_cols);
}
Example #13
0
// Cross-correlation implementation in Rcpp
//' @rdname corFamily
//' @export
// [[Rcpp::export]]
Rcpp::NumericMatrix xcorRcpp(Rcpp::NumericMatrix & X,
                             Rcpp::NumericMatrix & Y) {
  
  const int m_X = X.ncol();
  const int m_Y = Y.ncol();
  const int n = X.nrow();
  
  // Centering the matrices
  X = centerNumericMatrix(X);
  Y = centerNumericMatrix(Y);
  
  Rcpp::NumericMatrix cor(m_X, m_Y);
  
  // Degenerate case
  if (n == 0) {
    std::fill(cor.begin(), cor.end(), Rcpp::NumericVector::get_na());
    return cor; 
  }
  
  // Compute 1 over square root the sum of squares
  Rcpp::NumericVector inv_sqrt_ss_X(m_X);
  for (int i = 0; i < m_X; ++i) {
    inv_sqrt_ss_X(i) = 1/sqrt(Rcpp::sum(X(Rcpp::_, i)*X(Rcpp::_, i)));
  }
  Rcpp::NumericVector inv_sqrt_ss_Y(m_Y);
  for (int i = 0; i < m_Y; ++i) {
    inv_sqrt_ss_Y(i) = 1/sqrt(Rcpp::sum(Y(Rcpp::_, i)*Y(Rcpp::_, i)));
  }
  
  // Computing the cross-correlation matrix
  for (int i = 0; i < m_X; ++i) {
    for (int j = 0; j < m_Y; ++j) {
      cor(i, j) = Rcpp::sum(X(Rcpp::_, i)*Y(Rcpp::_, j)) *
        inv_sqrt_ss_X(i) * inv_sqrt_ss_Y(j);
    }
  }

  return cor;
}
Example #14
0
int run_as_correlation(int argc,const char *argv[])
{
	CTimeSegmentedQuote ct,dt;
	bool bRet;
	double dPrice0[2000],dPrice1[2000];
	double dHigh,dLow,dPre,dCor;
	
	
	bRet = ct.ReadFromFile(argv[2]);
	if (bRet == false)
	{
		EVENT("不能打开文件:%s",argv[2]);
		return 0;
	}
	bRet = dt.ReadFromFile(argv[3]);
	if (bRet == false)
	{
		EVENT("不能打开文件:%s",argv[3]);
		return 0;
	}
	
	bRet = ct.GetQuoteLastPrice(0, 2000, dPrice0, nullptr,&dHigh, &dLow, &dPre);
	if (bRet == false)
	{
		EVENT("不能GetLastPrice:%s",argv[2]);
		return 0;
	}
	bRet = dt.GetQuoteLastPrice(0, 2000, dPrice1, nullptr,&dHigh, &dLow, &dPre);
	if (bRet == false)
	{
		EVENT("不能GetLastPrice:%s",argv[3]);
		return 0;
	}
	dCor = cor(2000,dPrice0,dPrice1);
	EVENT("DCore:%.4f",dCor);
	FILE *fh;
	int i;
	fh = fopen("1.csv","w");
	for(i=0;i<2000;i++)
	{
		fprintf(fh,"%.3f\n",dPrice0[i]);
	}
	fclose(fh);
	fh = fopen("2.csv","w");
	for(i=0;i<2000;i++)
	{
		fprintf(fh,"%.3f\n",dPrice1[i]);
	}
	fclose(fh);
	return 0;
}
//Script that takes two matrices, performs bootstrapped correlation, and returns the median
// [[Rcpp::export]]
arma::mat BeQTL(const arma::mat & A, const arma::mat & B, const arma::umat & Bootmat){
  int bsi= Bootmat.n_rows;
  Rcpp::Rcout<<"Starting Bootstrap!"<<std::endl;
  arma::mat C(A.n_cols*B.n_cols,Bootmat.n_rows);
  arma::mat tA(A.n_rows,A.n_cols);
  arma::mat tB(B.n_rows,B.n_cols);
  arma::mat tC(A.n_rows,B.n_rows);
  for(int i=0; i<bsi; i++){
    tA = A.rows(Bootmat.row(i));
    tB = B.rows(Bootmat.row(i));
    tC = cor(tA,tB);
    C.col(i) = vectorise(tC,0);
  }
  C.elem(find_nonfinite(C)).zeros();

 return reshape(median(C,1),A.n_cols,B.n_cols);
}
Example #16
0
void autohf(float *si, float *w, int n, float omega, float *a)
{
    int i;
    float c0, c[MAXNO], atemp[MAXNO+1], s[MAXLL];

    memset(atemp, 0, sizeof(atemp));
    
    for (i = 0;  i < n ; i++)
        s[i] = si[i] * w[i];		/* apply window			*/

    cor(s, n, &c0, c);			/* calculate autocorrelations	*/

    atemp[0] = 1.0f;			/* convert autocorrelations to pc's  */
    durbin(c0, c, &atemp[1]);

    bwexp1(omega, atemp, a, MAXNO);		/* expand corrected pc's	*/
}
Example #17
0
// EDITOR -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
inline void obj_figura::poe(const tipo_xy& x1, const tipo_xy& y1,
                            const tipo_xy& x2, const tipo_xy& y2,
                            const tipo_cor& vcor)
{
  estrutura_circular caux;

  converte(x1, y1, &caux.angulo1, &caux.raio1);
  converte(x2, y2, &caux.angulo2, &caux.raio2);

  caux.angulo1 = -caux.angulo1;
  caux.angulo2 = -caux.angulo2;
  caux.cor = vcor;
  cor(vcor);
  line(x1, y1, x2, y2);

  fwrite(&caux, sizeof(estrutura_circular), 1, carquivo);

  cnumero_de_nos++;
}
Example #18
0
Arv* auxInsere(Arv* no, int valor,int* resp, int *chave)
{
	if(no == NULL)
	{
		Arv* novo = (Arv*) malloc(sizeof(Arv));
		if(novo == NULL)
		{
			*resp = 0;
			return NULL;
		}
		novo->val = valor;
		novo->chave = *chave;
		novo->esq = NULL;
		novo->dir = NULL;
		novo->cor = RED;
		*resp = 1;
		return novo;
	}
	if(valor == no->val)
	{
		*resp = 0;	
	}
	else
	{
		if(valor > no->val)
		{
			no->dir = auxInsere(no->dir,valor,resp, chave);
		}
		else
		{
			no->esq = auxInsere(no->esq,valor,resp, chave);
		}
	}

	if((cor(no->dir) == RED) && (cor(no->esq) == BLACK))
	{
		no = rEsq(no);
	}
	if((cor(no->esq) == RED) && (cor(no->esq->esq) == RED))
	{
		no = rDir(no);
	}
	if((cor(no->esq) == RED) && (cor(no->dir) == RED))
	{
		trocarCor(no);
	}

	return no;
}
Example #19
0
void tst_QTemporaryFile::nonWritableCurrentDir()
{
#ifdef Q_OS_UNIX
    struct ChdirOnReturn
    {
        ChdirOnReturn(const QString& d) : dir(d) {}
        ~ChdirOnReturn() {
            QDir::setCurrent(dir);
        }
        QString dir;
    };
    ChdirOnReturn cor(QDir::currentPath());

    QDir::setCurrent("/home");
    // QTemporaryFile("tempXXXXXX") is probably a bad idea in any app
    // where the current dir could anything...
    QTemporaryFile file("tempXXXXXX");
    file.setAutoRemove(true);
    QVERIFY(!file.open());
    QVERIFY(file.fileName().isEmpty());
#endif
}
void tst_QTemporaryFile::nonWritableCurrentDir()
{
#ifdef Q_OS_UNIX
    if (::geteuid() == 0)
        QSKIP("not valid running this test as root");

    ChdirOnReturn cor(QDir::currentPath());

#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_NO_SDK)
    QDir::setCurrent("/data");
#else
    QDir::setCurrent("/home");
#endif

    // QTemporaryFile("tempXXXXXX") is probably a bad idea in any app
    // where the current dir could anything...
    QTemporaryFile file("tempXXXXXX");
    file.setAutoRemove(true);
    QVERIFY(!file.open());
    QVERIFY(file.fileName().isEmpty());
#endif
}
Example #21
0
char obj_figura::exibe()
{
  if (!carquivo_definido)
    return FALSO;
  else
   {
     if (ctela.pagina_atual == 0)
       setactivepage(1);
     else
       setactivepage(0);

     if (!cbuffer_definido)
     {
       cbuffer = (estrutura_circular*) malloc(sizeof(estrutura_circular) * cnumero_de_nos);
       cbuffer_definido = VERDADEIRO;

       rewind(carquivo);
       fread(cbuffer, sizeof(estrutura_circular), cnumero_de_nos, carquivo);
     }

     for (unsigned int cont = 0; cont < cnumero_de_nos; cont++)
     {
       tipo_xy x1, y1, x2, y2;
       converte(cbuffer[cont].angulo1 + cangulo, cbuffer[cont].raio1 * craio, &x1, &y1, cx, cy);
       converte(cbuffer[cont].angulo2 + cangulo, cbuffer[cont].raio2 * craio, &x2, &y2, cx, cy);
       cor(cbuffer[cont].cor);
       line(x1, y1, x2, y2);
     }

     if (ctela.pagina_atual == 0)
       setactivepage(0);
     else
       setactivepage(1);

     return VERDADEIRO;
   }
}
Example #22
0
Cor operator*(double escalar, const Cor &c) {
  Cor cor(escalar * c.r, escalar * c.g, escalar * c.b);
  cor.filtre();
  return cor;
}
Example #23
0
void C3DPlotCanvas::SelectByRect()
{
	int hl_size = highlight_state->GetHighlightSize();
	std::vector<bool>& hs = highlight_state->GetHighlight();
	std::vector<int>& nh = highlight_state->GetNewlyHighlighted();
	std::vector<int>& nuh = highlight_state->GetNewlyUnhighlighted();
	int total_newly_selected = 0;
	int total_newly_unselected = 0;		
	
	double world11[3], world12[3], world22[3], world21[3];
	double world113[3], world123[3], world223[3], world213[3];
	
	int pixel11[2], pixel12[2], pixel22[2], pixel21[2];
	
    int small_x = (select_start.x < select_end.x)? select_start.x:select_end.x;
    int large_x = (select_start.x > select_end.x)? select_start.x:select_end.x;
    int small_y = (select_start.y < select_end.y)? select_start.y:select_end.y;
    int large_y = (select_start.y > select_end.y)? select_start.y:select_end.y;
	
	pixel11[0] = small_x;	pixel12[0] = small_x; 
	pixel21[0] = large_x;   pixel22[0] = large_x;
	pixel11[1] = small_y;   pixel21[1] = small_y;
	pixel12[1] = large_y;	pixel22[1] = large_y;
	
	ball->apply_transform();
	
	unproject_pixel(pixel11, world11, 0.0);	
	unproject_pixel(pixel12, world12, 0.0);
	unproject_pixel(pixel22, world22, 0.0);
    unproject_pixel(pixel21, world21, 0.0);
	
	unproject_pixel(pixel11, world113, 1.0);	
	unproject_pixel(pixel12, world123, 1.0);
	unproject_pixel(pixel22, world223, 1.0);
    unproject_pixel(pixel21, world213, 1.0);
	
	ball->unapply_transform();
	
	SPlane* plane;
	int i;
	
	bool *inside = new bool[num_obs*4];
	for(i=0; i<num_obs*4; i++) inside[i] = false;
	double *world1, *world2, *world3, *world4;
	for (int k=0; k<4; k++) {
		switch(k)
		{
			case 0: 
				world1 = world11;
				world2 = world12;
				world3 = world113;
				world4 = world123;
				break;
			case 1:
				world1 = world12;
				world2 = world22;
				world3 = world123;
				world4 = world223;
				break;
			case 2:
				world1 = world22;
				world2 = world21;
				world3 = world223;
				world4 = world213;
				break;
			case 3:
				world1 = world21;
				world2 = world11;
				world3 = world213;
				world4 = world113;
				break;
			default:
				break;
		}
		
		plane = new SPlane(world1, world2, world3);
		
		Vec3f a1(world1[0], world1[1], world1[2]);
		Vec3f a2(world2[0], world2[1], world2[2]);
		Vec3f a3(world3[0], world3[1], world3[2]);
		Vec3f a4(world4[0], world4[1], world4[2]);
		Vec3f l1 = a3 - a1;
		Vec3f l2 = a4 - a2;
		
		int xt = var_info[0].time;
		int yt = var_info[1].time;
		int zt = var_info[2].time;
		
		for (i=0; i<num_obs; i++) {
			Vec3f cor(scaled_d[0][xt][i], scaled_d[1][yt][i],
					  scaled_d[2][zt][i]);
			if (plane->isPositive(cor)) inside[k*num_obs+i] = true;
		}
        delete plane;
    }
	
	delete [] inside;
	
	for (i=0; i<num_obs; i++) {
		bool contains = (inside[i] && inside[num_obs+i] && inside[2*num_obs+i]
						 && inside[3*num_obs+i]);
		if (contains) {
			if (!hs[i]) nh[total_newly_selected++] = i;
		} else {
			if (hs[i]) nuh[total_newly_unselected++] = i;
		}
	}
	
	if (total_newly_selected == 0 && total_newly_unselected == 0) return;
	if (total_newly_selected == 0 &&
		total_newly_unselected == highlight_state->GetTotalHighlighted()) {
		highlight_state->SetEventType(HighlightState::unhighlight_all);
		highlight_state->notifyObservers();
	} else {
		highlight_state->SetEventType(HighlightState::delta);
		highlight_state->SetTotalNewlyHighlighted(total_newly_selected);
		highlight_state->SetTotalNewlyUnhighlighted(total_newly_unselected);
		highlight_state->notifyObservers();
	}
}
Example #24
0
TGraphErrors* newCorrCoefGraph(const T* const dat1,
                               const U* const dat2,
                               const Int_t    nd,
                               const Int_t    minbin=-1, // -1 => 0
                               const Int_t    maxbin=-1  // -1 => nd-1
                               ) {
   const Int_t minb = (minbin<0) ?    0 : minbin;
   const Int_t maxb = (maxbin<0) ? nd-1 : maxbin;
   if ( (maxb<=minb) || (maxb>=nd) ) {
      Fatal("newCorrCoefGraph",
            "Invalid maxb=%d. (minb=%d, nd=%d)",
            maxb, minb, nd);
   }

   // find correlation coef for different shifts
   //const Int_t ndh = nd/2;
   const T* c1 = dat1+minb;
   const U* c2 = dat2+minb;
   const Int_t ndh = (maxb-minb+1)/2;
   Int_t pos, j(0);
   TGraphErrors* gc = new TGraphErrors;
   for (Int_t sh=1-ndh; sh<ndh; ++sh) {
      Double_t a1(0), a2(0), r1(0), r2(0);
      Double_t cor(0), ncr(0);
      c1 = dat1+minb;
      c2 = dat2+minb-sh;
      for (Int_t i=minb; i<=maxb; ++i, ++c1, ++c2) {
         pos = c2 - dat2;
#ifdef SHIFT_INTO_WINDOW
         if (pos<nd) { // CHECK: can c1 go above nd?
            if (pos>=0) {
#else
         if (pos<=maxb) {
            if (pos>=minb) {
#endif
               a1  += *c1;
               a2  += *c2;
               r1  += (*c1)*(*c1);
               r2  += (*c2)*(*c2);
               cor += (*c1)*(*c2);
               ncr += 1.0;
            }
         } else {
            break;
         }
      } // sample
      if (ncr>1) {
         // rms
         r1  -= (a1*a1)/ncr;
         r2  -= (a2*a2)/ncr;
         r1  /= ncr-1.0;
         r2  /= ncr-1.0;
         r1   = TMath::Sqrt(r1);
         r2   = TMath::Sqrt(r2);
         // ave
         a1  /= ncr;
         a2  /= ncr;
         // cor
         cor -= ncr*a1*a2;
         cor /= (ncr-1.0)*r1*r2;
         gc->SetPoint(j, static_cast<Double_t>(sh), cor);
         gc->SetPointError(j, 0, 
            (1.0-(cor*cor))/TMath::Sqrt(ncr-1.0));
         ++j;
      }
   } // shift

   return gc;
}
Example #25
0
void f_calc_cor(FILE *fh,double *dPrice0,int iSize0,int iSize1,CTimeSegmentedQuote *dt,const char *sInst1)
{
    bool bRet;
    double *dPrice1;
    double dHigh,dLow,dPre,dCor;
    char m_sExchangeID[11];
    char m_sInstrumentID[41];
    char m_sTradingDay[11];
    int i;
    double dMax;
    int iMax;

    dPrice1 = new double[iSize0+iSize1];

    bRet = dt->GetQuoteLastPrice(0, iSize0, dPrice1, nullptr,&dHigh, &dLow, &dPre);
    if (bRet == false)
    {
        WARN("不能GetLastPrice:%s","");
        delete [] dPrice1;
        return ;
    }
    dt->GetQuoteInfo(m_sExchangeID, m_sInstrumentID, m_sTradingDay);
    bRet = dt->GetQuoteLastPrice(1, iSize1, &(dPrice1[iSize0]),nullptr, &dHigh, &dLow, &dPre);
    if (bRet == false)
    {
        EVENT("不能GetLastPrice:%s","");
        delete [] dPrice1;
        return ;
    }
    /* 看看前后移动移动计算一下 */
    /*  [C0] [C-3] [C-2] [C-1] [C+1] [C+2] [C+3]
        C0:     不进行移动的计算
        C-3:    向前3个时间跨度的计算
        C-2:    向前2个时间跨度的计算
        C-1:    向前1个时间跨度的计算
        C+1:    向后1个时间跨度的计算
        C+2:    向后2个时间跨度的计算
        C+3:    向后3个时间跨度的计算

        C0:
        TS0:    I0,I1,I2,I3,I4,I5..In
        TS1:    J0,J1,J2,J3,J4,J5..Jn

        C-3:
        TS0:    I0,I1,I2,I3,I4,I5..In-3
        TS1:    J3,J4,J5...........Jn

        C-2:
        TS0:    I0,I1,I2,I3,I4,I5..In-2
        TS1:    J2,J3,J4,J5........Jn

        C+3:
        TS0:    I3,I4,I5...........In
        TS1:    J0,J1,J2,J3,J4,J5..Jn-3
     */

    dCor = cor(iSize0+iSize1,dPrice0,dPrice1);
//    EVENT3("%s-%s DCore:%.4f",sInst1,m_sInstrumentID,dCor);
    fprintf(fh,"%s,%.5f",m_sInstrumentID,dCor);

    dMax = dCor;
    iMax = 0;
    /* 计算向前的个数 */
    for(i=0; i<g_var.m_iCorrelationOffsetCount; i++)
    {
        /* C-3:= 3-0 */
        dCor = cor(iSize0+iSize1 - (g_var.m_iCorrelationOffsetCount -i) * g_var.m_iCorrelationFrameCount,dPrice0,&(dPrice1[(g_var.m_iCorrelationOffsetCount -i)* g_var.m_iCorrelationFrameCount]));
        if (dCor > dMax)
        {
            iMax = g_var.m_iCorrelationOffsetCount - i;
            dMax = dCor;
        }
        fprintf(fh,",%.5f",dCor);
    }
    /* 计算向后的个数 */
    for(i=0; i<g_var.m_iCorrelationOffsetCount; i++)
    {
        /* C+3:= 3-0 */
        dCor = cor(iSize0+iSize1 - (g_var.m_iCorrelationOffsetCount -i) * g_var.m_iCorrelationFrameCount,&(dPrice0[(g_var.m_iCorrelationOffsetCount -i)* g_var.m_iCorrelationFrameCount]),dPrice1);
        if (dCor > dMax)
        {
            iMax = i - g_var.m_iCorrelationOffsetCount;
            dMax = dCor;
        }
        fprintf(fh,",%.5f",dCor);
    }

    if (iMax)
        fprintf(fh,",(%.5f,%d)\n",dMax,iMax);
    else
        fprintf(fh,"\n");
    delete [] dPrice1;
    return ;
}
Example #26
0
Cor operator+(const Cor &a, const Cor &b) {
  Cor cor(a.r + b.r, a.g + b.g, a.b + b.b);
  cor.filtre();
  return cor;
}
//Function to perform point estimate of correlation
// [[Rcpp::export]]
arma::mat PointCor(const arma::mat & A, const arma::mat & B){
  arma::mat C= cor(A,B);
  C.elem(find_nonfinite(C)).zeros();
  return C;
}
Example #28
0
char obj_figura::edita()
{
  ctela.limpa_teclado();

  if (carquivo_somente_leitura)
    return FALSO;
  else
    if (!carquivo_definido)
      return FALSO;
    else
     {
       tipo_xy cx, cy;
       tipo_xy cxant, cyant;
       tipo_xy ccentrox, ccentroy;
       tipo_angulo cangulo = 0;
       tipo_raio craio = 1;
       char ccirculo = FALSO;
       char ccor = 15;
       char* cursor = (char*) malloc(sizeof(char) * 2);
       char caracter = NULL;
       char clicado = FALSO;
       char velocidade = 1;

       cx = (tipo_xy) (ctela.max_x + 1) / 2;
       cy = (tipo_xy) (ctela.max_y + 1) / 2;

       ccentrox = cx;
       ccentroy = cy;

       cor(8);
       line(cx, 0, cx, ctela.max_y);
       line(0, cy, ctela.max_x, cy);

       putpixel(0, 0, 15);
       getimage(0, 0, 0, 0, cursor);
       putpixel(0, 0, 0);

       do
       {
         if (keypressed)
         {
           ctela.le_teclado(&caracter);

           switch (caracter)
           {
             case CARACTER_NULO:
               ctela.le_teclado(&caracter);

               if (!ccirculo)
               {
                 switch (caracter)
                 {
                   case SETA_CIMA:
                     cy -= velocidade;
                   break;

                   case SETA_BAIXO:
                     cy += velocidade;
                   break;

                   case SETA_DIREITA:
                     cx += velocidade;
                   break;

                   case SETA_ESQUERDA:
                     cx -= velocidade;
                   break;
                 }
               }
               else
                 {
                   switch (caracter)
                   {
                     case SETA_CIMA:
                       craio += velocidade;
                     break;

                     case SETA_BAIXO:
                       craio -= velocidade;
                     break;

                     case SETA_DIREITA:
                       cangulo += velocidade;
                     break;

                     case SETA_ESQUERDA:
                       cangulo -= velocidade;
                     break;
                   }

                   converte(cangulo, craio, &cx, &cy, ccentrox, ccentroy);
                 }

             break;

             case BARRA_DE_ESPACO:
               if (!clicado)
               {
                 clicado = VERDADEIRO;
                 cxant = cx;
                 cyant = cy;
               }
               else
                 {
                   clicado = FALSO;
                   poe(cx, cy, cxant, cyant, ccor);
                 }
             break;

             case CTRL_A:
               poe(cx + 5, cy, cx + 20, cy + 13, ccor);
               poe(cx, cy, cx + 15, cy + 16, ccor);
               poe(cx - 2, cy + 5, cx + 13, cy + 19, ccor);
               poe(cx - 4, cy + 7, cx + 11, cy + 20, ccor);
               poe(cx - 5, cy + 14, cx + 12, cy, ccor);
               poe(cx - 1, cy + 16, cx + 15, cy + 2, ccor);
               poe(cx + 3, cy + 19, cx + 17, cy + 5, ccor);
               poe(cx + 6, cy + 20, cx + 20, cy + 8, ccor);
             break;

             case CTRL_B:
               ccor++;

               if (ccor > 15)
                 ccor = 0;
             break;

             case CTRL_D:
               if (!ccirculo)
               {
                 ccentrox = cx;
                 ccentroy = cy;
               }
               else
                 if (ccirculo)
                 {
                   cx = ccentrox;
                   cy = ccentroy;
                 }

               ccirculo = !ccirculo;
             break;

             case MAIS:
               velocidade++;
             break;

             case MENOS:
               velocidade--;
             break;

             case CTRL_Z:
               tira();
             break;
           }
         }

         putimage(cx, cy, cursor, XOR_PUT);
         delay(1);
         putimage(cx, cy, cursor, XOR_PUT);
       }
       while(caracter != ENTER);

       return VERDADEIRO;
     }
}
Example #29
0
Cor operator*(const Cor &a, const Cor &b) {
  Cor cor(a.r * b.r, a.g * b.g, a.b * b.b);
  cor.filtre();
  return cor;
}
Example #30
0
main(int argc, char**argv)
{ 
  int NPTS =0;
  int NCHN =0;
  int NTRLS =0;
  int WIN=0;
  int MODORDER=0;
  if (argc==9)
   {
     NCHN=atoi(argv[4]);
     NTRLS=atoi(argv[5]);
     NPTS=atoi(argv[6]);
     WIN=atoi(argv[7]);
     MODORDER=atoi(argv[8]);
   }
  else if ( argc!=4 && argc!=9)
	{
	  fprintf(stderr,"opsswhite datfile A Ve Nchannels Ntrails Npoints WIN MODORDER\n");
	  exit(1);
	}
  else { 
  double chan[1],trai[1],poin[1],wind[1],order[1];
  FILE *chanfp,*traifp,*poinfp,*windfp,*orderfp;
  if((chanfp=fopen("channel","r"))==NULL)   
              printf("The file'channel' was not opened\n");   
  else   
    fscanf(chanfp,"%lf",&chan[0]);  
    NCHN=(int)chan[0];
    fclose(chanfp);
  if((traifp=fopen("trail","r"))==NULL)   
              printf("The file'trail' was not opened\n");   
  else   
    fscanf(traifp,"%lf",&trai[0]);  
    NTRLS=(int)trai[0];
    fclose(traifp);
  if((poinfp=fopen("points","r"))==NULL)   
              printf("The file'points' was not opened\n");   
  else   
    fscanf(poinfp,"%lf",&poin[0]);  
    NPTS=(int)poin[0];
    fclose(poinfp);
  if((windfp=fopen("window","r"))==NULL)   
              printf("The file'window' was not opened\n");   
  else   
    fscanf(windfp,"%lf",&wind[0]);  
    WIN=(int)wind[0];
    fclose(windfp);
  if((orderfp=fopen("order","r"))==NULL)   
              printf("The file'order' was not opened\n");   
  else   
    fscanf(orderfp,"%lf",&order[0]);  
    MODORDER=(int)order[0];
    fclose(orderfp);}

  FILE *inpt, *shfp, *stimp, *fp;
  FILE *fr;

  int *shift, *stim;
  int shfmin=0, shfmax=0, stimmin, stimmax;

  double *A[MAXORDER],*Ve,*tildA;
  float **dat; 
  double **x;   /*  rout is residual output */
  int *n;  /* n[j] is the number of data in j-th segment, 120 */  
  int i, j, k, rec, idx, t;

  double **rout;   /*  rout is residual output */
  double *xtemp[NCHN];
  double *rtemp[NCHN];

  double mean[NCHN], ss[NCHN], corfun[50], sigthresh, prob;
  int nlags = 5;
  int nresids = WIN-MODORDER;
  int l, lag, nsig=0, ntot=0;

  sigthresh = 2.000 / sqrt((double)nresids);
  
  if( argc<4)
	{
	  fprintf(stderr,"Usage: opss datfile A Ve\n");
	  exit(1);
	}


  for(i=0;i<MAXORDER;i++){
    if((A[i]=malloc(NCHN*NCHN*sizeof(double)))==NULL)
      EEGerror("main---memory allocation error\n");
  }
  if((tildA=malloc(MAXORDER*(MAXORDER+1)*NCHN*NCHN*sizeof(double)/2))==NULL)
    EEGerror("main---memory allocation error\n");
  if((Ve=malloc(NCHN*NCHN*sizeof(double)))==NULL)
    EEGerror("main---memory allocation error\n");


  /* allocation of memory for dat */
  dat = malloc(NCHN*sizeof(float*));
  for( i = 0; i < NCHN; i++)
    dat[i] = malloc(WIN*NTRLS*sizeof(float));

  x = malloc(NCHN*sizeof(double*));
  for( i = 0; i < NCHN; i++)
    x[i] = malloc(WIN*NTRLS*sizeof(double));

  /***  For residual calculation   ****/
  rout = malloc(NCHN*sizeof(double*));
  for( i = 0; i < NCHN; i++)
    rout[i] = malloc((WIN-MODORDER)*NTRLS*sizeof(double));
  /*
  rtemp = malloc(NCHN*sizeof(double*));
  for( i = 0; i < NCHN; i++)
    rtemp[i] = malloc((WIN-MODORDER)*sizeof(double));
	*/

  n=malloc(NTRLS*sizeof(int));
  shift = malloc(NTRLS*sizeof(int));
  stim = malloc(NTRLS*sizeof(int));


  if((inpt = fopen(argv[1],"rb")) == NULL) {
	printf("\007Error opening input file!\n"); return;
  } 
/*  if((shfp = fopen(argv[2],"rt")) == NULL) {
	printf("\007Error opening shift file!\n"); return;
  } 
  if((stimp = fopen(argv[3],"rt")) == NULL) {
	printf("\007Error opening stim file!\n"); return;
  } 
*/

  /* Initialization, required by MARfit */ 	
  for( i = 0; i < NTRLS; i++) n[i] = WIN;

  /*  for( i=0; i<NTRLS; i++ ) fscanf(shfp,"%d",&shift[i]); */
 /* for( i=0; i<NTRLS; i++ ) fscanf(shfp,"%d", &shift[i]); 
  fclose(shfp);
  minmax(NTRLS, shift, &shfmin, &shfmax);*/
  /*  printf("min, max = %d  %d\n", shfmin, shfmax); */

 /* for( i=0; i<NTRLS; i++ ) fscanf(stimp,"%d", &stim[i]); 
  fclose(stimp);
  minmax(NTRLS, stim, &stimmin, &stimmax);*/
  stimmin=0;  /* convert to points  */
  /*  printf("min, max = %d  %d\n", stimmin, stimmax); */


  /* printf("Trl, CHN, T, WIN = %d %d %d %d\n",NTRLS,NCHN, NPTS, WIN); */

  /*********  read monkey dat *********/

  t = -(stimmin - WIN/2)*5 - 5;   /* - (20-8)*5 +5 = -60 - 5 msec */    
  /*  for (rec=3; rec < 104; rec++) {  */
   for ( rec=abs(shfmin); rec < (NPTS-WIN-shfmax+1); rec++) { 
	t+=5;
	/*printf("index, t = %d  %d msec\n", (rec-abs(shfmin)+1), t);*/
    for( j = 0; j < NCHN; j++){
	  idx=0;
	  for( i = 0; i < NTRLS; i++){
		if(fseek(inpt, sizeof(float)*(shift[i] + rec + i*NCHN*NPTS + j*NPTS), 0) != 0){
		  printf("Error in fseek\n"); exit(-1);
		} 
		
		if( fread(&dat[j][idx],sizeof(float),WIN,inpt) !=WIN) {
		  if(feof(inpt)) 
			{printf("premature end of file in read data");exit(-1);}
		  else {printf("file read error");exit(-1);}
		}
		
		idx+=WIN;
	  }
	}

	/*
	  for( i = 0; i < 3; i++){
	  for( j = 0; j < WIN*NTRLS; j++) { 
	  printf("%f\n", dat[i][j]);
	  }
	  printf("OOOOOOOO\n");
	  }
	  */



/* convert data format from float to double  */
  for (i=0; i < NCHN; i++)
	for(j=0; j < WIN*NTRLS; j++)
	  x[i][j] = dat[i][j];

  MARfit(x,NCHN,n,NTRLS,MODORDER,tildA);
  EEGrealA(tildA,A,Ve,NCHN,MODORDER);
  /*
  MARfit(x,NCHN,n,NTRLS,6,tildA);
  EEGrealA(tildA,A,Ve,NCHN,5);
  */

  /******  calculate residual of MVAR for whiteness test  *******/
  /* First loop over trials, and then loop over channels & allocate memory for 
	 xtemp & rtemp at proper locations in x & rout */
  if((fr = fopen("resid.out","a")) == NULL) {
	printf("\007Error opening MAR coeff file!\n"); return;
  } 
  for(j=0;j<NTRLS;j++){
	for(k=0;k<NCHN;k++){
	  xtemp[k]=x[k]+j*WIN;
	  rtemp[k]=rout[k] + j*(WIN-MODORDER);  
	}
	MAR_residual(xtemp,rtemp,A,NCHN,MODORDER,WIN);

	/* compute mean and sum of squares for residuals of each channel */
	for(k=0;k<NCHN;k++){
	  mean[k] = getmean(rtemp[k],nresids);
	  ss[k] = getss(rtemp[k],mean[k],nresids);
	  /*	  fprintf(stderr,"%d %lf %lf\n", k, mean[k], ss[k]);*/
	}

	/* loop over channel pairs to get correlations */
	for(k=0;k<NCHN;k++){
	  for(l=0;l<NCHN;l++){	
	    if(l >= k){
		  cor(rtemp[k],mean[k],ss[k],rtemp[l],mean[l],ss[l],nresids,nlags,corfun);
	      for(lag=0;lag<nlags*2;lag++){
			ntot++;
			if(fabs(corfun[lag]) > sigthresh){
			  nsig++;
			}
	      }
	    }
	  }
	}

  } /* end of trial */
  prob = (double)nsig / (double)ntot;
  fprintf(fr,"%lf\n", prob);
  fclose(fr);

	/***  write MAR coefficients(including noise) to output files ***/
	/***  Each line of the output file corresponds to ONE MAR model at each 
	  given time instant  ***/

	if((fp = fopen(argv[2],"a")) == NULL) {
	  printf("\007Error opening MAR coeff file!\n"); return;
	} 
	/*   for ( i=0; i < 6; i++) *//* 5 order, 1st is identity; if 7, then new =0 */
   for ( i=0; i < MODORDER+1; i++) /* 5 order, 1st is identity; if 7, then new =0 */
	 for ( j=0; j < NCHN*NCHN; j++)
	   fprintf(fp,"%.3g  ",A[i][j]);
   fprintf(fp,"\n");
   fclose(fp);
   
  if((fp = fopen(argv[3],"a")) == NULL) {
	printf("\007Error opening MAR noise file!\n"); return;
  } 
   for ( i=0; i < NCHN*NCHN; i++)
	 fprintf(fp,"%.3g  ",Ve[i]);
   fprintf(fp,"\n");
   fclose(fp);
   
/*  if((fp = fopen(argv[6],"a")) == NULL) {
	printf("\007Error opening time file!\n"); return;
  } 
  fprintf(fp,"%d\n", t);
  fclose(fp);
 */  

  }   /* end of rec  */

  free(tildA);
  free(Ve);
  for(i=0;i<MAXORDER;i++)free(A[i]);
  free(n);

  for (i = 0; i < NCHN; i++)
    free(dat[i]);
  free(dat);

  for (i = 0; i < NCHN; i++)
    free(x[i]);
  free(x);

  for (j = 0; j < NCHN; j++){
	free(rout[j]);
  }
  free(rout);
  
  exit(0);

}