예제 #1
0
파일: sketch.c 프로젝트: BlackBoxe/minuit
void skt_msh_rectangle(float *p,float w,float h,float *color)
{
	float a[3];
	float b[3];
	float c[3];
	float d[3];

	float *vw = vnew(w,0,0);
	float *vh = vnew(0,h,0);

	vcp(a,p);
	vadd(b,a,vw);
	vadd(c,b,vh);
	vadd(d,a,vh);

	free(vw);
	free(vh);

	glColor3f(color[0],color[1],color[2]);

	glBegin(GL_POLYGON);
		glVertex3f(a[0],a[1],a[2]);
		glVertex3f(b[0],b[1],b[2]);
		glVertex3f(c[0],c[1],c[2]);
		glVertex3f(d[0],d[1],d[2]);
	glEnd();
}
예제 #2
0
파일: mathtool.cpp 프로젝트: NCIP/visda
/*******************************************************************
 Subroutine to compute the Covariance Matrix (CM)
   matrix *X:     the pointer to the matrix
   matrix *covm:  the pointer to the output covariance matrix
*******************************************************************/
void mcovar(matrix *X, matrix *covm)
{
	int i, j, k;
    vector Coli;  // the pointer to the 'i'th column vector
    vector Colj;  // the pointer to the 'j'th column vector
	double *pxi;
	double *pxj;
	double *pci;

    vnew(&Coli, X->m);
    vnew(&Colj, X->m);
	covm->m = X->n;
	covm->n = X->n;

    for (i=0; i<(X->n); i++) {  // i -- row index of CM
        for (j=0; j<(X->n); j++) {  // j -- column index of CM
            for (k=0; k<(X->m); k++) {
				pxi = X->pr + i;
				pxj = X->pr + j;
                *(Coli.pr+k) = *(pxi+(X->n)*k);
                *(Colj.pr+k) = *(pxj+(X->n)*k);
            }

            // the value of CM[i,j]
			pci = covm->pr + (covm->m)*i;
            *(pci+j) = vcovar(&Coli, &Colj);
        }
    }

	vdelete(&Coli);
	vdelete(&Colj);

}
예제 #3
0
파일: portal.cpp 프로젝트: minimoog/portals
void Portal::clipPortal(TPlane &plane)
{
    if (m_clippedPoints.empty())
        return;

    TVec3Array newClippedPoints;

    for (size_t i = 0; i < m_clippedPoints.size() - 1; ++i) {
        TVec3 vp = m_clippedPoints[i];
        TVec3 vn = m_clippedPoints[i + 1];
        TVec4 pl = plane.getPlaneVector();

        float lDotVp = vp.x * pl.x + vp.y * pl.y + vp.z * pl.z + pl.w;
        float lDotVn = vn.x * pl.x + vn.y * pl.y + vn.z * pl.z + pl.w;

        if (lDotVp > 0.0f) { //Front
            newClippedPoints.push_back(vp);

            if (lDotVn < 0.0f) {    //next vertex back, new clip vertex
                float den = pl.x * (vp.x - vn.x) + pl.y * (vp.y  - vn.y) + pl.z * (vp.z - vn.z);
                float t = lDotVp / den;
                float x = vp.x + t * (vn.x - vp.x);
                float y = vp.y + t * (vn.y - vp.y);
                float z = vp.z + t * (vn.z - vp.z);

                TVec3 vnew(x, y, z);

                newClippedPoints.push_back(vnew);
            }
        } else {    //Back
            if (lDotVn > 0.0f) {    //new vertex
                float den = pl.x * (vp.x - vn.x) + pl.y * (vp.y  - vn.y) + pl.z * (vp.z - vn.z);
                float t = lDotVp / den;
                float x = vp.x + t * (vn.x - vp.x);
                float y = vp.y + t * (vn.y - vp.y);
                float z = vp.z + t * (vn.z - vp.z);

                TVec3 vnew(x, y, z);

                newClippedPoints.push_back(vnew);
            }
        }
    }

    if (!newClippedPoints.empty())
        newClippedPoints.push_back(newClippedPoints[0]);

    m_clippedPoints.assign(newClippedPoints.begin(), newClippedPoints.end());
}
예제 #4
0
// Switch to given screen.  Return status.
int sswitch(EScreen *scrp) {

	// Nothing to do if it is already current.
	if(scrp == cursp)
		return rc.status;

	// Save the current screen's concept of current window.
	cursp->s_curwp = curwp;
	cursp->s_nrow = term.t_nrow;
	cursp->s_ncol = term.t_ncol;

	// Run exit-buffer user hook on current (old) buffer if the new screen's buffer is different.
	Value *rp;
	bool diffbuf = (scrp->s_curwp->w_bufp != curbp);
	if(vnew(&rp,false) != 0)
		return vrcset();
	if(diffbuf && bhook(rp,true) != SUCCESS)
		return rc.status;

	// Reset the current screen, window and buffer.
	wheadp = (cursp = scrp)->s_wheadp;
	curbp = (curwp = scrp->s_curwp)->w_bufp;

	// Let the display driver know we need a full screen update.
	opflags |= OPSCREDRAW;
	uphard();

	// Run enter-buffer user hook on current (new) buffer.
	if(diffbuf)
		(void) bhook(rp,false);

	return rc.status;
	}
예제 #5
0
vArray(uchar) vImageToRGBA(color_image * the_image)
{
  vint8 buffer_size = the_image->Size() * 4;
  vArray(uchar) buffer = vnew(uchar, (vector_size) buffer_size);
  vImageToRGBA(the_image, buffer);
  return buffer;
}
예제 #6
0
파일: sketch.c 프로젝트: BlackBoxe/minuit
void skt_line_rectangle(float *p,float w,float h,int line_width,float *color)
{
	float a[3];
	float b[3];
	float c[3];
	float d[3];

	float *vw = vnew(w,0,0);
	float *vh = vnew(0,h,0);

	vcp(a,p);
	vadd(b,a,vw);
	vadd(c,b,vh);
	vadd(d,a,vh);

	skt_line_quad(a,b,c,d,line_width,color);
}
예제 #7
0
파일: mathtool.cpp 프로젝트: NCIP/visda
/*******************************************************************
 Subroutine to compute the Variance of Matrix
   matrix *X:     the pointer to the matrix
   char direction: 'c' - compute the mean of each column
                   'r' - compute the mean of each row
   vector *mean:  the pointer to the mean vector
*******************************************************************/
int mvar(matrix *X, char direction, vector *var)
{
	int row_l, row_n;	
	int i;
    int result;
	vector col_vec;
	vector row_vec;

    row_l = X->n;
	row_n = X->m;
 
	vnew(&col_vec, row_n);
	vnew(&row_vec, row_l);

	if (direction == 'c') {  // compute the variance of each column
		var->l = row_l;
        for (i=0; i<row_l; i++) {
			getcolvec(X, i, &col_vec);
            *(var->pr + i) = vcovar(&col_vec, &col_vec);
        }
        result = 1;
    } else if (direction == 'r') { // compute the variance of each row
		var->l = row_n;
        for (i=0; i<row_n; i++) {
			getrowvec(X, i, &row_vec);
	        *(var->pr + i) = vcovar(&row_vec, &row_vec);;		
        }
        result = 1;
    } else {
        result = 0;
        printf("the direction parameter should be 'c' or 'r'");
    }

	vdelete(&col_vec);
	vdelete(&row_vec);

    return result;
   
}
예제 #8
0
void PDESolver::CrankNicolson(vec *v){
        double a,a2,a3; vec A1 = zeros<vec>(Nx), A2 = zeros<vec>(Nx), A3 = zeros<vec>(Nx), vtilde, vnew;
        a = dt / dx / dx; a2 = 2 - 2*a; a3 = 2 + 2*a; ofstream myfile;
        myfile.open("CrankNicolson_movie.txt");

        // Setting the diagonals on of the LHS-matrix.
        for (int i=0; i<Nx; i++){
            A1(i) = -a; A2(i) = a3; A3(i) = -a;
        }

        vnew = *v; vtilde = vnew;
        for (int j=1; j<Nt; j++){
            // Chaning the RHS vector v_old into vtilde.
            for (int i=1; i<Nx-1; i++){
                vtilde(i) = a*vnew(i-1) + a2*vnew(i) + a*vnew(i+1);
            }
            vnew = PDESolver::tridiagonal(A1,A2,A3,vtilde);
            for (int i=0; i<Nx; i++){myfile << vnew(i) + 1 - i*dx << " ";}; myfile << endl;
        }
        myfile.close();
        for (int i=0; i<Nx; i++){vnew(i) += 1 - i*dx;}
        *v = vnew;
}
예제 #9
0
  /// Replace variables as needed
  void visit(VariableExpression& e)
  { 
    VariablePtr vold(e.var());
    OptimizerImplementation::VarMap::const_iterator v = p_vmap.find(vold->name());
    BOOST_ASSERT(v != p_vmap.end());
    VariablePtr vnew(v->second);

    BOOST_ASSERT(vold);
    BOOST_ASSERT(vnew);

    if (vold != vnew) {
      e.var(vnew);
    }
  }
예제 #10
0
void CMatrix44f::Rotate(float rad, const float3& axis)
{
	const float sr = math::sin(rad);
	const float cr = math::cos(rad);

	for(int a=0;a<3;++a){
		float3 v(m[a*4],m[a*4+1],m[a*4+2]);

		float3 va(axis*v.dot(axis));
		float3 vp(v-va);
		float3 vp2(axis.cross(vp));

		float3 vpnew(vp*cr+vp2*sr);
		float3 vnew(va+vpnew);

		m[a*4]     = vnew.x;
		m[a*4 + 1] = vnew.y;
		m[a*4 + 2] = vnew.z;
	}
}
예제 #11
0
/*
	This routine is modeled after qdiag.m from Andreas Ziehe, Pavel Laskov, Guido Nolte, Klaus-Robert Müller,
	A Fast Algorithm for Joint Diagonalization with Non-orthogonal Transformations and its Application to
	Blind Source Separation, Journal of Machine Learning Research 5 (2004), 777–800.
*/
static void Diagonalizer_and_CrossCorrelationTables_ffdiag (Diagonalizer me, CrossCorrelationTables thee, long maxNumberOfIterations, double delta) {
	try {
		long iter = 0, dimension = my numberOfRows;
		double **v = my data;

		autoCrossCorrelationTables ccts = CrossCorrelationTables_and_Diagonalizer_diagonalize (thee, me);
		autoNUMmatrix<double> w (1, dimension, 1, dimension);
		autoNUMmatrix<double> vnew (1, dimension, 1, dimension);
		autoNUMmatrix<double> cc (1, dimension, 1, dimension);

		for (long i = 1; i <= dimension; i++) {
			w[i][i] = 1;
		}

		autoMelderProgress progress (U"Simultaneous diagonalization of many CrossCorrelationTables...");
		double dm_new = CrossCorrelationTables_getDiagonalityMeasure (ccts.peek(), nullptr, 0, 0);
		try {
			double dm_old, theta = 1, dm_start = dm_new;
			do {
				dm_old = dm_new;
				for (long i = 1; i <= dimension; i++) {
					for (long j = i + 1; j <= dimension; j++) {
						double zii = 0, zij = 0, zjj = 0, yij = 0, yji = 0; // zij = zji
						for (long k = 1; k <= ccts -> size; k++) {
							CrossCorrelationTable ct = (CrossCorrelationTable) ccts -> item [k];
							zii += ct -> data[i][i] * ct -> data[i][i];
							zij += ct -> data[i][i] * ct -> data[j][j];
							zjj += ct -> data[j][j] * ct -> data[j][j];
							yij += ct -> data[j][j] * ct -> data[i][j];
							yji += ct -> data[i][i] * ct -> data[i][j];
						}
						double denom = zjj * zii - zij * zij;
						if (denom != 0) {
							w[i][j] = (zij * yji - zii * yij) / denom;
							w[j][i] = (zij * yij - zjj * yji) / denom;
						}
					}
				}
				double norma = 0;
				for (long i = 1; i <= dimension; i++) {
					double normai = 0;
					for (long j = 1; j <= dimension; j++) {
						if (i != j) {
							normai += fabs (w[i][j]);
						}
					}
					if (normai > norma) {
						norma = normai;
					}
				}
				// evaluate the norm
				if (norma > theta) {
					double normf = 0;
					for (long i = 1; i <= dimension; i++)
						for (long j = 1; j <= dimension; j++)
							if (i != j) {
								normf += w[i][j] * w[i][j];
							}
					double scalef = theta / sqrt (normf);
					for (long i = 1; i <= dimension; i++) {
						for (long j = 1; j <= dimension; j++) {
							if (i != j) {
								w[i][j] *= scalef;
							}
						}
					}
				}
				// update V
				NUMmatrix_copyElements (v, vnew.peek(), 1, dimension, 1, dimension);
				NUMdmatrices_multiply_VC (v, w.peek(), dimension, dimension, vnew.peek(), dimension);
				for (long k = 1; k <= ccts -> size; k++) {
					CrossCorrelationTable ct = (CrossCorrelationTable) ccts -> item[k];
					NUMmatrix_copyElements (ct -> data, cc.peek(), 1, dimension, 1, dimension);
					NUMdmatrices_multiply_VCVp (ct -> data, w.peek(), dimension, dimension, cc.peek(), 1);
				}
				dm_new = CrossCorrelationTables_getDiagonalityMeasure (ccts.peek(), 0, 0, 0);
				iter++;
				Melder_progress ((double) iter / (double) maxNumberOfIterations, U"Iteration: ", iter, U", measure: ", dm_new, U"\n fractional measure: ", dm_new / dm_start);
			} while (fabs ((dm_old - dm_new) / dm_new) > delta && iter < maxNumberOfIterations);
		} catch (MelderError) {
			Melder_clearError ();
		}
	} catch (MelderError) {
		Melder_throw (me, U" & ", thee, U": no joint diagonalization (ffdiag).");
	}
}
예제 #12
0
파일: veCov.cpp 프로젝트: NCIP/visda
/*******************************************************************
 Subroutine to compute the inverse matrix and determinant
   matrix *cov:        the pointer to the covariance matrix
   matrix *inv_cov:    the pointer to the inverse covariance matrix
   matrix *cov_mat:    the pointer to the approximate covariance matrix
                       when singular. If unsingular, it equals to cov
   double *det_cov:    the pointer to determinant

 return value: '1' - successfully exit
               '0' - exit with waring/error
*******************************************************************/
int veCov(matrix *cov, matrix *inv_cov, matrix *cov_mat, 
		  double *det_cov)
{
	int i, j;
	matrix eigvec_re;
	matrix eigvec_im;
	vector eigval_re;
	vector eigval_im;
    int *eig_order;
	int eig_info;
	int num_v;  // the number of eigenvalue
	int rank_c; 
	double sum_v;
	double factor = 0.02;
	double ass_value;
	double min_real;

    mnew(&eigvec_re, cov->m, cov->n);
    mnew(&eigvec_im, cov->m, cov->n);
	vnew(&eigval_re, cov->n);
	vnew(&eigval_im, cov->n);
    eig_order = new int[cov->n];
    

    // the eigenvector and eigenvalue of covariance matrix
    eig_info = eig(cov, &eigvec_re, &eigvec_im, &eigval_re, &eigval_im);
	//vprint(&eigval_re);
	//vprint(&eigval_im);

	if (!eig_info) {
		printf(" The eigenvalue computation failed! \n");
		return 0;
		//....
	}
	
	// the rank of covariance matrix
	num_v = cov->n;
	
	/*rank_c = num_v;
	for (i=0; i<num_v; i++) {
		if ((fabs(*(eigval_re.pr+i)) < ZEROTHRESH) && (fabs(*(eigval_im.pr+i)) < ZEROTHRESH)) {
			rank_c--;
		}
	}
	printf("rank = %d", rank_c);*/

	rank_c = rank(cov, TOLERANCE);

	// compute the inverse and determinate
    if (rank_c == num_v) {  // nonsingular
		inv(cov, inv_cov);
		mcopy(cov, cov_mat);
		*det_cov = det(cov);
	
	} else {  // singular
		min_real = pow(10, (((double)-250) / ((double) cov->m)));

		/*for (i=0; i<num_v; i++) {
			if ((*(eigval_re.pr+i) < ZEROTHRESH) || (*(eigval_im.pr+i) != 0)) {
				*(eigval_re.pr+i) = 0;  // ???? keep the real part of complex or not
				*(eigval_im.pr+i) = 0;
			}
		}
		sort(&eigval_re, eig_order, 'd'); */

		for (i=0; i<num_v; i++) {
			// when negtive real eigenvalue, change to absolute value
			//   to ensure all the real eigenvalues are positive
			if ((eigval_re.pr[i] < 0) && (eigval_im.pr[i] == 0)) {
				eigval_re.pr[i] *= -1;
				// the i-th column of eigenvector should also be changed the sign
				for (j=0; j<(eigvec_re.m); j++) {
					eigvec_re.pr[j*(eigvec_re.n)+i] *= -1;
				}
			}
		}

		//vprint(&eigval_re);
		//vprint(&eigval_im);

		// sort real eigenvalues descendingly, put complex ones at the end
		sorteig(&eigval_re, &eigval_im, eig_order);

		for (i=rank_c; i<num_v; i++) {
				*(eigval_re.pr+i) = 0;
				*(eigval_im.pr+i) = 0;
		}

		//vprint(&eigval_re);
		//vprint(&eigval_im);

		sum_v = vsum(&eigval_re);

		ass_value = factor * sum_v / (num_v - rank_c);

		if (ass_value < (0.5 * (*(eigval_re.pr+rank_c)) * (1 - factor))) {
			if (ass_value > min_real) {
				for (i=rank_c; i<num_v; i++) {
					*(eigval_re.pr+i) = ass_value;
				}
				for (i=0; i<rank_c; i++) {
					*(eigval_re.pr+i) *= 1 - factor;
				}
			} else {
				for (i=rank_c; i<num_v; i++) {
					*(eigval_re.pr+i) = min_real;
				}
			}
		} else {
			ass_value = 0.5 * (*(eigval_re.pr+rank_c)) * (1 - factor);
			if (ass_value > min_real) {
				for (i=rank_c; i<num_v; i++) {
					*(eigval_re.pr+i) = ass_value;
				}
				for (i=0; i<rank_c; i++) {
					*(eigval_re.pr+i) = *(eigval_re.pr+i) - ass_value * (num_v - rank_c) * (*(eigval_re.pr+i)) / sum_v;
				}
			} else {
				for (i=rank_c; i<num_v; i++) {
					*(eigval_re.pr+i) = min_real;
				}
			}
		}
        
		//vprint(&eigval_re);
		//vprint(&eigval_im);

		matrix eigvec_re_sorted;
		matrix eigvec_re_sorted_t;
		mnew(&eigvec_re_sorted, num_v, num_v);
		mnew(&eigvec_re_sorted_t, num_v, num_v);

		sortcols(eig_order, &eigvec_re, &eigvec_re_sorted);
		transpose(&eigvec_re_sorted, &eigvec_re_sorted_t); 

		matrix inv_eig_vl_s;
		mnew(&inv_eig_vl_s, num_v, num_v);
		for (i=1; i<num_v; i++) {
			*(inv_eig_vl_s.pr + i*num_v + i) = 1 / (*(eigval_re.pr+i));    
		}
		
		matrix tmp;
		mnew(&tmp, num_v, num_v);

		mmMul(&eigvec_re_sorted, &inv_eig_vl_s, &tmp);
		mmMul(&tmp, &eigvec_re_sorted_t, inv_cov);

		matrix diag_eigval;
		mnew(&diag_eigval, num_v, num_v);
		for (i=0; i<num_v; i++) {
			*(diag_eigval.pr + i*num_v + i) = *(eigval_re.pr+i);    
		}
		mmMul(&eigvec_re_sorted, &diag_eigval, &tmp);
		mmMul(&tmp, &eigvec_re_sorted_t, cov_mat);

		*det_cov = 1;
		for (i=0; i<num_v; i++) {
			*det_cov = (*det_cov) * (*(eigval_re.pr+i)); 
		}

		mdelete(&inv_eig_vl_s);
		mdelete(&eigvec_re_sorted);
		mdelete(&eigvec_re_sorted_t);
		mdelete(&tmp);
		mdelete(&diag_eigval);

	}

	#ifdef _DEBUG
	printf("rank = %d \n", rank_c);
	printf("\n det_cov = %e \n", *det_cov);
	printf("inv_cov = \n");
	mprint(inv_cov);
	printf("cov_mat = \n");
	mprint(cov_mat);
	#endif

    mdelete(&eigvec_re);
	mdelete(&eigvec_im);
	vdelete(&eigval_re);
	vdelete(&eigval_im);
    delete []eig_order;

    return 1;
}
예제 #13
0
파일: misc.c 프로젝트: italia389/MightEMacs
// Set i variable.  Use numeric argument for first parameter if present; otherwise, get arguments.  Return status.
int seti(Value *rp,int n) {
	int i = ivar.i;
	int inc = ivar.inc;
	bool newfmt = false;
	Value *vp;

	// Numeric argument?
	if(n != INT_MIN) {
		ivar.i = n;
		return rcset(SUCCESS,0,text287,ivar.i);
				// "i variable set to %d"
		}

	// Get value(s).
	if(vnew(&vp,false) != 0)
		return vrcset();
	if(opflags & OPSCRIPT) {

		// Get "i" argument and decode it.
		if(funcarg(vp,ARG_FIRST | ARG_NOTNULL | ARG_INT) != SUCCESS)
			return rc.status;
		if(opflags & OPEVAL)
			i = vp->u.v_int;

		// Have "inc" argument?
		if(havesym(s_comma,false)) {

			// Yes, get it and decode it.
			if(funcarg(vp,ARG_NOTNULL | ARG_INT) != SUCCESS)
				return rc.status;
			if(opflags & OPEVAL)
				inc = vp->u.v_int;

			// Have "format" argument?
			if(havesym(s_comma,false)) {

				// Yes, get it.
				if(funcarg(vp,ARG_NOTNULL | ARG_STR) != SUCCESS)
					return rc.status;
				newfmt = true;
				}
			}

		// Bail out here if not evaluating arguments.
		if(!(opflags & OPEVAL))
			return rc.status;
		}
	else {
		char nbuf[LONGWIDTH];

		// Prompt for "i" value.
		if(terminp(vp,text102,"0",RTNKEY,0,0) != SUCCESS || toint(vp) != SUCCESS)
				// "Beginning value"
			return rc.status;
		i = vp->u.v_int;

		// Prompt for "inc" value.
		sprintf(nbuf,"%d",inc);
		if(terminp(vp,text234,nbuf,RTNKEY,0,0) != SUCCESS || toint(vp) != SUCCESS)
				// "Increment"
			return rc.status;
		inc = vp->u.v_int;

		// Prompt for "format" value.
		if(terminp(vp,text235,ivar.format.v_strp,CTRL | '[',0,0) != SUCCESS)
				// "Format string"
			return rc.status;
		newfmt = true;
		}

	// Validate arguments.
	if(inc == 0)				// Zero increment.
		return rcset(FAILURE,0,text236);
			// "i increment cannot be zero!"

	// Validate format string if changed.
	if(newfmt) {
		if(strcmp(vp->v_strp,ivar.format.v_strp) == 0)
			newfmt = false;
		else {
			int c,icount,ocount;
			bool inspec = false;
			char *strp = vp->v_strp;

			icount = ocount = 0;
			do {
				c = *strp++;
				if(inspec) {
					switch(c) {
						case '%':
							inspec = false;
							break;
						case 'd':
						case 'o':
						case 'u':
						case 'x':
						case 'X':
							++icount;
							inspec = false;
							break;
						default:
							if(strchr("0123456789+- .",c) == NULL) {
								++ocount;
								inspec = false;
								}
							}
					}
				else if(c == '%')
					inspec = true;
				} while(*strp != '\0');

			if(icount != 1 || ocount > 0)		// Bad format string.
				return rcset(FAILURE,0,text237,vp->v_strp);
					// "Invalid i format '%s' (must contain exactly one %%d, %%o, %%u, %%x, or %%X)"
			}
		}

	// Passed all edits ... update ivar.
	ivar.i = i;
	ivar.inc = inc;
	if(newfmt)
		vxfer(&ivar.format,vp);

	return rc.status;
	}
예제 #14
0
void
convert(		/* convert a T-mesh */
	char	*fname,
	FILE	*fp
)
{
	char	typ[4];
	int	id[3];
	double	vec[3];
	char	picfile[128];
	char	matname[64];
	char	objname[64];
	int	i;
	VERTEX	*lastv;
					/* start fresh */
	i = nverts;
	lastv = vlist;
	while (i--)
		(lastv++)->flags = 0;
	lastv = NULL;
	strcpy(picfile, defpat);
	strcpy(matname, defmat);
	strcpy(objname, defobj);

	printf("\n## T-mesh read from: %s\n", fname);
					/* scan until EOF */
	while (fscanf(fp, "%1s", typ) == 1)
		switch (typ[0]) {
		case 'v':		/* vertex */
			if (fscanf(fp, "%d %lf %lf %lf", &id[0],
					&vec[0], &vec[1], &vec[2]) != 4)
				syntax(fname, fp, "Bad vertex");
			lastv = vnew(id[0], vec[0], vec[1], vec[2]);
			break;
		case 't':		/* triangle */
			if (fscanf(fp, "%d %d %d", &id[0], &id[1], &id[2]) != 3)
				syntax(fname, fp, "Bad triangle");
			if (novert(id[0]) | novert(id[1]) | novert(id[2]))
				syntax(fname, fp, "Undefined triangle vertex");
			triangle(picfile, matname, objname, &vlist[id[0]],
					&vlist[id[1]], &vlist[id[2]]);
			break;
		case 'n':		/* surface normal */
			if (lastv == NULL)
				syntax(fname, fp, "No vertex for normal");
			if (fscanf(fp, "%lf %lf %lf",
					&vec[0], &vec[1], &vec[2]) != 3)
				syntax(fname, fp, "Bad vertex normal");
			lastv->nor[0] = vec[0];
			lastv->nor[1] = vec[1];
			lastv->nor[2] = vec[2];
			if (normalize(lastv->nor) == 0.0)
				syntax(fname, fp, "Zero vertex normal");
			lastv->flags |= V_HASNORM;
			break;
		case 'i':		/* index position */
			if (lastv == NULL)
				syntax(fname, fp, "No vertex for index");
			if (fscanf(fp, "%lf %lf", &vec[0], &vec[1]) != 2)
				syntax(fname, fp, "Bad index");
			lastv->ndx[0] = vec[0];
			lastv->ndx[1] = vec[1];
			lastv->flags |= V_HASINDX;
			break;
		case 'o':		/* object name */
			if (fscanf(fp, "%s", objname) != 1)
				syntax(fname, fp, "Bad object name");
			break;
		case 'm':		/* material */
			if (fscanf(fp, "%s", matname) != 1)
				syntax(fname, fp, "Bad material");
			if (matname[0] == '-' && !matname[1])
				strcpy(matname, VOIDID);
			break;
		case 'p':		/* picture */
			if (fscanf(fp, "%s", picfile) != 1)
				syntax(fname, fp, "Bad pattern");
			if (picfile[0] == '-' && !picfile[1])
				picfile[0] = '\0';
			break;
		case '#':		/* comment */
			fputs("\n#", stdout);
			while ((i = getc(fp)) != EOF) {
				putchar(i);
				if (i == '\n')
					break;
			}
			break;
		default:
			syntax(fname, fp, "Unknown type");
			break;
		}
}
예제 #15
0
파일: veSubEM.cpp 프로젝트: NCIP/visda
/*******************************************************************
 Subroutine to do the EM algorithm
   matrix *D:       the pointer to the matrix data
   matrix *mean0_x: the pointer to a matrix containing the initial Means of clusters
   vector *w0:		the pointer to a vector containing the initial mixing proportion of clusters
   double vv:       the value for initializing the Covariance matrix of clusters
   double error:    the error threshold
   vector *Zjk_up:  the pointer to a vector containing Posterior probabilities of the up-level 
                         cluster samples
   matrix *mean1_x: the pointer to a matrix containing the Means of clusters in t-space
   vector *w0_t:	the pointer to a vector containing the mixing proportions of the identified 
                         clusters in t-space
   matrix *cov_mat: the pointer to a group of matrixs containing the Covariance
                         matrix of clusters in t-space
   matrix *Zjk:     the pointer to a matrix containing Posterior probabilities of all samples 
                         belonging to all the sub-level clusters, each column is for one cluster.
   
 return value: '1' - successfully exit
               '0' - exit with waring/error
*******************************************************************/
int veSubEM(matrix *D, matrix *mean0_x, vector *w0, double vv, double error, vector *Zjk_up, //input
			matrix *mean1_x, vector *w0_t, matrix *cov_mat, matrix *Zjk)  //output
{
	int k0, kc, n, p;
	int i, j, k, u, s;
	matrix *Var0;
	matrix Gxn;
	vector Fx;
	matrix MUK;
	matrix MU1;
	int zeroFx_num = 1;
	//double error = 0.01;
	double err = error + (double)1;
	vector Zjk_temp;

	n = D->m;
	p = D->n;
	k0 = mean0_x->m;
	kc = mean0_x->n;
	
	Var0 = new matrix[k0];
	for(i=0; i<k0; i++) {
		mnew(Var0+i, p, p);
	}
	mnew(&Gxn, n, k0);
	vnew(&Fx, n);
	vnew(&Zjk_temp, n);
	mnew(&MUK, k0, p);
	mcopy(mean0_x, &MUK);
	mnew(&MU1, k0, p);

	vector D_j;
	vector Zjk_k;
	double sum_tmp = 0;
	matrix Ck;
	vector D_i;
	vector MUK_k;
	vector cen_D_i;
	matrix mtmp;
	vector vtmp;

	vnew(&D_j, n);
	vnew(&Zjk_k, n);
	mnew(&Ck, p, p);
	vnew(&D_i, p);
	vnew(&MUK_k, p);
	vnew(&cen_D_i, p);
	mnew(&mtmp, p, p);
	vnew(&vtmp, n);

	//Initializing the parameters of mixture of Gaussians
	//Initinalize the covariance matrix
	//Use EM algorithm to perform the local training.
	
	//Test intialization of covarinace matrix 
	//printf("Testing covariance matrix initialization... \n");

	while (zeroFx_num != 0) {
		for(i=0; i<k0; i++) {
			meye(Var0+i);
			for (j=0; j<p; j++) {
				*((Var0+i)->pr+j*p+j) = vv;
			}
		}
	
		veModel(D, mean0_x, Var0, w0, &Gxn, &Fx);
		//printf("\n Gxn = :\n");
		//mprint(&Gxn);
		//printf("\n Fx = :\n");
		//vprint(&Fx);

		zeroFx_num = 0;
		for (i=0; i<n; i++) {
			if (*(Fx.pr+i) == 0) {
				zeroFx_num++;
			}
		}

		vv *= 2;
	
	}

	vones(&Zjk_temp);

	//printf("\n EM in t-space starts ... \n");
	//printf("\n Data = \n");
	//mprint(D);

	int l = 0;
	while (err > error) {
		
		#ifdef _DEBUG
		printf(" \n...... in EM loop %d ......\n", ++l);

		printf("\n L%d: w0 = \n", l);
		vprint(w0);
		printf("\n L%d: MUK = \n", l);
		mprint(&MUK);
		printf("\n L%d: Var0 = \n", l);
		for(i=0; i<k0; i++) {
			mprint(Var0+i);
			printf("\n");
		}
		printf("\n L%d: Zjk = \n", l);
		mprint(Zjk);
		#endif

		veModel(D, &MUK, Var0, w0, &Gxn, &Fx);
		
		#ifdef _DEBUG
		printf("\n L%d: Gxn = \n", l);
		mprint(&Gxn);
		printf("\n L%d: Fx = \n", l);
		vprint(&Fx);
		#endif

		for (k=0; k<k0; k++) {
			u = k*p;

			double zz = 0;
			double zz_up = 0;
			for (i=0; i<n; i++) {
				*(Zjk->pr+i*k0+k) = (*(w0->pr+k)) * Zjk_up->pr[i] * (*(Gxn.pr+i*k0+k)) / (*(Fx.pr+i));
				zz += *(Zjk->pr+i*k0+k);
				zz_up += Zjk_up->pr[i];
			}
			*(w0->pr+k) = zz/zz_up;

			for (j=0; j<p; j++) {
				getcolvec(D, j, &D_j);
				getcolvec(Zjk, k, &Zjk_k);
				sum_tmp = 0;
				for (i=0; i<n; i++) {
					sum_tmp += (*(Zjk_k.pr+i)) * (*(D_j.pr+i));
				}
				*(MU1.pr+u+j) = sum_tmp / zz;
			}

			mzero(&Ck);
			for (i=0; i<n; i++) {
				getrowvec(D, i, &D_i);
				getrowvec(&MUK, k, &MUK_k);
				for (j=0; j<p; j++) {
					*(cen_D_i.pr+j) = *(D_i.pr+j) - *(MUK_k.pr+j);
				}

				vvMul(&cen_D_i, &cen_D_i, &mtmp);
				
				for (j=0; j<p; j++) {
					for (s=0; s<p; s++) {
						*(Ck.pr+j*p+s) += (*(Zjk->pr+i*k0+k)) * (*(mtmp.pr+j*p+s));
					}
				}
			}
			for (j=0; j<p; j++) {
				for (s=0; s<p; s++) {
					*(Var0[k].pr+j*p+s) = (*(Ck.pr+j*p+s)) / zz;
				}
			}
		}   // for (k...

		mcopy(&MU1, &MUK);

		for (i=0; i<n; i++) {
			*(vtmp.pr+i) = fabs(*(Zjk_k.pr+i) - *(Zjk_temp.pr+i));
		}
		err = vmean(&vtmp);
		vcopy(&Zjk_k, &Zjk_temp);
		
		
    }  // while

	vcopy(w0, w0_t);
	mcopy(&MUK, mean1_x);
	for(i=0; i<k0; i++) {
		mcopy(Var0+i, cov_mat+i);
	}

	for(i=0; i<k0; i++) {
		mdelete(Var0+i);
	} 
	mdelete(&Gxn);
	vdelete(&Fx);
	vdelete(&Zjk_temp);
	mdelete(&MUK);
	mdelete(&MU1);
    vdelete(&D_j);
	vdelete(&Zjk_k);
	mdelete(&Ck);
	vdelete(&D_i);
	vdelete(&MUK_k);
	vdelete(&cen_D_i);
	mdelete(&mtmp);
	vdelete(&vtmp);

    return 1;
}
예제 #16
0
파일: veSNR.cpp 프로젝트: NCIP/visda
/*******************************************************************
 Subroutine to perform dimension pre-screening using signal-to-noise ratio (SNR)
   matrix *cov:        the pointer to the covariance matrix
   matrix *inv_cov:    the pointer to the inverse covariance matrix
   matrix *cov_mat:    the pointer to the approximate covariance matrix
                       when singular. If unsingular, it equals to cov
   double *det_cov:    the pointer to determinant

 return value: '1' - successfully exit
               '0' - exit with waring/error
*******************************************************************/
int veSNR(matrix *data, int *label, int dim_num, 
		  int *top_label, vector *snr_sorted)
{

	int i, j, k, t, u;
    int num_class;
	int m, n;
	vector count;
	vector *data_mean;
	vector *variance;
	vector pro;
	vector snr;
	int *new_order;
	int row_T;
	double tmp;

	m = data->m;
	n = data->n;

	num_class = 0;
	for (j=0; j<m; j++) {
		if (num_class < label[j]) {
			num_class = label[j];
		}
	}

	vnew(&count, num_class);
    vnew(&pro, num_class);
    vnew(&snr, n);
	data_mean = new vector[num_class];
	for (i=0; i<num_class; i++) {
		vnew(data_mean+i, n);
	}
	variance = new vector[num_class];
	for (i=0; i<num_class; i++) {
		vnew(variance+i, n);
	}
	new_order = new int[n];

    for (i=0; i<num_class; i++) {
		
		// distingush each class
		row_T = 0;
		for (j=0; j<m; j++) {
			if (label[j] == i+1) {
				row_T ++;
			}
		}
		int *T;
		T = new int[row_T];
		t = 0;
		for (j=0; j<m; j++) {
			if (label[j] == i+1) {
				T[t++] = j;
			}
		}
        pro.pr[i] = ((double) row_T) / ((double) m);

		// compute data_mean for each class
		matrix data_i;
		mnew(&data_i, row_T, n);
		
		for (t=0; t<row_T; t++) {
			u = t*n;
			for (k=0; k<n; k++) {
				data_i.pr[u+k] = data->pr[(T[t])*n+k];
			}
		}

		
		mmean(&data_i, 'c', data_mean+i);
		mvar(&data_i, 'c', variance+i);
	
		delete []T;
		mdelete(&data_i);

    }

	//jj = [];
    for (i=0; i<num_class-1; i++) {
        for (j=i; j<num_class; j++) {
            for (k=0; k<n; k++) {
				tmp = ((variance+i)->pr[k] * pro.pr[i] + (variance+j)->pr[k] * pro.pr[j]) / (pro.pr[i] + pro.pr[j]);
                if (tmp < 1.0000e-3) {
                    //jj = [jj k]; 
					//printf(" Warning: \n ");
                } else {
                    snr.pr[k] += pro.pr[i] * pro.pr[j] * pow(((data_mean+i)->pr[k] - (data_mean+j)->pr[k]), 2) / tmp;  
				}   
			}
		}
	}
      
	sort(&snr, new_order, 'd');

	for (k=0; k<dim_num; k++) {
		top_label[k] = new_order[k];
	}

	vcopy(&snr, snr_sorted);


	//vdelete(&count);
    vdelete(&pro);
    vdelete(&snr);
	for (i=0; i<num_class; i++) {
		vdelete(data_mean+i);
	}
	for (i=0; i<num_class; i++) {
		vdelete(variance+i);
	}
	delete []new_order;

	return 1;

}
예제 #17
0
int main( int argc, char* argv[] ) {


  std::string runName = "precalib_BGO_pedestal_noSource";
  if( argc>1 ) {
    std::string runName_str(argv[1]);
    runName = runName_str;
  }

  std::string tag = "V00";
  if( argc>2 ) {
    std::string tag_str(argv[2]);
    tag = tag_str;
  }

  TString runName_tstr(runName);
  bool isOnlyRunNumber = !(runName_tstr.BeginsWith("BTF_"));


  TChain* tree = new TChain("recoTree");
  if( isOnlyRunNumber ) {
    std::cout << "-> We believe you are passing the program only the run number!" << std::endl;
    std::cout << "-> So for instance you are passing '246' for run 'BTF_246_20140501-212512_beam'" << std::endl;
    std::cout << "(if this is not the case this means TROUBLE)" << std::endl;
    std::cout << "-> Will look for runs matching run number: " << runName << std::endl;
    tree->Add(Form("analysisTrees_%s/Reco_BTF_%s_*beam.root/recoTree", tag.c_str(), runName.c_str()) );
    if( tree->GetEntries()==0 ) {
      std::cout << "WARNING! Didn't find any events matching run: " << runName << std::endl;
      std::cout << "Exiting" << std::endl;
      exit(1913);
    }
  } else {
    std::string fileName = "analysisTrees_"+tag+"/Reco_" + runName + ".root";
    TFile* file = TFile::Open(fileName.c_str());
    if( file==0 ) {
      std::cout << "ERROR! Din't find file " << fileName << std::endl;
      std::cout << "Exiting." << std::endl;
      exit(11);
    }
    tree = (TChain*)file->Get("recoTree");
  }





  UInt_t evtNumber;
  tree->SetBranchAddress( "evtNumber", &evtNumber );
  UInt_t adcData[40];
  tree->SetBranchAddress( "adcData", adcData );
  UInt_t adcBoard[40];
  tree->SetBranchAddress( "adcBoard", adcBoard );
  UInt_t adcChannel[40];
  tree->SetBranchAddress( "adcChannel", adcChannel );


  unsigned int runNumber;
  int nHodoFibersX;
  int nHodoFibersY;
  int nHodoClustersX;
  int nHodoClustersY;
  float cef3_corr[CEF3_CHANNELS];
  float bgo_corr[BGO_CHANNELS];
  float scintFront;
  float pos_hodoClustX[HODOX_CHANNELS];
  float pos_hodoClustY[HODOY_CHANNELS];
  int nFibres_hodoClustX[HODOX_CHANNELS];
  int nFibres_hodoClustY[HODOY_CHANNELS];
  float xBeam, yBeam;
  bool isSingleEle_scintFront;
  bool cef3_ok;
  bool cef3_corr_ok;
  bool bgo_ok;
  bool bgo_corr_ok;

  tree->SetBranchAddress( "runNumber", &runNumber );

  tree->SetBranchAddress( "scintFront", &scintFront );
  tree->SetBranchAddress( "cef3_corr", cef3_corr );
  tree->SetBranchAddress( "bgo_corr", bgo_corr );

  tree->SetBranchAddress( "nHodoFibersX", &nHodoFibersX );
  tree->SetBranchAddress( "nHodoFibersY", &nHodoFibersY );
  tree->SetBranchAddress( "nHodoClustersX", &nHodoClustersX );
  tree->SetBranchAddress( "pos_hodoClustX", pos_hodoClustX );
  tree->SetBranchAddress( "nFibres_hodoClustX", nFibres_hodoClustX );
  tree->SetBranchAddress( "nHodoClustersY", &nHodoClustersY );
  tree->SetBranchAddress( "pos_hodoClustY", pos_hodoClustY );
  tree->SetBranchAddress( "nFibres_hodoClustY", nFibres_hodoClustY );
  tree->SetBranchAddress( "scintFront", &scintFront );
  tree->SetBranchAddress( "isSingleEle_scintFront", &isSingleEle_scintFront );
  tree->SetBranchAddress( "xBeam", &xBeam );
  tree->SetBranchAddress( "yBeam", &yBeam );

  tree->SetBranchAddress( "cef3_ok", &cef3_ok );
  tree->SetBranchAddress( "cef3_corr_ok", &cef3_corr_ok );
  tree->SetBranchAddress( "bgo_ok", &bgo_ok );
  tree->SetBranchAddress( "bgo_corr_ok", &bgo_corr_ok );




  int nBins = 500;
  float xMax = 25.*3./2.;


  TH1D* h1_xPos = new TH1D("xPos", "", nBins, -xMax, xMax);
  TH1D* h1_yPos = new TH1D("yPos", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos = new TH2D("xyPos", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle = new TH1D("xPos_singleEle", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle = new TH1D("yPos_singleEle", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle = new TH2D("xyPos_singleEle", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_new = new TH1D("xPos_new", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_new = new TH1D("yPos_new", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_new = new TH2D("xyPos_new", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_new_singleEle = new TH1D("xPos_new_singleEle", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_new_singleEle = new TH1D("yPos_new_singleEle", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_new_singleEle = new TH2D("xyPos_new_singleEle", "", nBins, -xMax, xMax, nBins, -xMax, xMax);


  TH1D* h1_xPos_bgo = new TH1D("xPos_bgo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_bgo = new TH1D("yPos_bgo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_bgo = new TH2D("xyPos_bgo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle_bgo = new TH1D("xPos_singleEle_bgo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle_bgo = new TH1D("yPos_singleEle_bgo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_bgo = new TH2D("xyPos_singleEle_bgo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_hodo = new TH1D("xPos_hodo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_hodo = new TH1D("yPos_hodo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_hodo = new TH2D("xyPos_hodo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle_hodo = new TH1D("xPos_singleEle_hodo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle_hodo = new TH1D("yPos_singleEle_hodo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_hodo = new TH2D("xyPos_singleEle_hodo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle_hodoClust = new TH1D("xPos_singleEle_hodoClust", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle_hodoClust = new TH1D("yPos_singleEle_hodoClust", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_hodoClust = new TH2D("xyPos_singleEle_hodoClust", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_calo = new TH1D("xPos_calo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo = new TH1D("yPos_calo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_calo = new TH2D("xyPos_calo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_singleEle_calo = new TH1D("xPos_singleEle_calo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_singleEle_calo = new TH1D("yPos_singleEle_calo", "", nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_calo = new TH2D("xyPos_singleEle_calo", "", nBins, -xMax, xMax, nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_hodo = new TH1D("xPos_calo_vs_hodo", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_hodo = new TH1D("yPos_calo_vs_hodo", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_beam = new TH1D("xPos_calo_vs_beam", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_beam = new TH1D("yPos_calo_vs_beam", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_hodo_singleElectron = new TH1D("xPos_calo_vs_hodo_singleElectron", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_hodo_singleElectron = new TH1D("yPos_calo_vs_hodo_singleElectron", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_beam_singleElectron = new TH1D("xPos_calo_vs_beam_singleElectron", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_beam_singleElectron = new TH1D("yPos_calo_vs_beam_singleElectron", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_hodo_singleElectron_HR = new TH1D("xPos_calo_vs_hodo_singleElectron_HR", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_hodo_singleElectron_HR = new TH1D("yPos_calo_vs_hodo_singleElectron_HR", "", nBins, -xMax, xMax);

  TH1D* h1_xPos_calo_vs_beam_singleElectron_HR = new TH1D("xPos_calo_vs_beam_singleElectron_HR", "", nBins, -xMax, xMax);
  TH1D* h1_yPos_calo_vs_beam_singleElectron_HR = new TH1D("yPos_calo_vs_beam_singleElectron_HR", "", nBins, -xMax, xMax);


  TH2D* h2_correlation_cef3_hodo_xPos = new TH2D("correlation_cef3_hodo_xPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_cef3_hodo_yPos = new TH2D("correlation_cef3_hodo_yPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);

  TH2D* h2_correlation_cef3_bgo_xPos = new TH2D("correlation_cef3_bgo_xPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_cef3_bgo_yPos = new TH2D("correlation_cef3_bgo_yPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);

  TH2D* h2_correlation_hodo_bgo_xPos = new TH2D("correlation_hodo_bgo_xPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_hodo_bgo_yPos = new TH2D("correlation_hodo_bgo_yPos", "", 100, -12.5, 12.5,  100, -12.5, 12.5);


  TH2D* h2_correlation_cef3_hodo_xPos_singleEle = new TH2D("correlation_cef3_hodo_xPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_cef3_hodo_yPos_singleEle = new TH2D("correlation_cef3_hodo_yPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);

  TH2D* h2_correlation_cef3_bgo_xPos_singleEle = new TH2D("correlation_cef3_bgo_xPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_cef3_bgo_yPos_singleEle = new TH2D("correlation_cef3_bgo_yPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);

  TH2D* h2_correlation_hodo_bgo_xPos_singleEle = new TH2D("correlation_hodo_bgo_xPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);
  TH2D* h2_correlation_hodo_bgo_yPos_singleEle = new TH2D("correlation_hodo_bgo_yPos_singleEle", "", 100, -12.5, 12.5,  100, -12.5, 12.5);



  int nentries = tree->GetEntries();


  if( isOnlyRunNumber ) {
    // modify runname in such a way that it's useful for getBeamPosition and outfile:
    runName = "BTF_" + runName + "_beam";
  }



  std::string outputdir = "PosAnTrees_"+tag;
  system( Form("mkdir -p %s", outputdir.c_str()) );
  std::string outfileName = outputdir + "/PosAn_" + runName + ".root";
  TFile* outfile = TFile::Open( outfileName.c_str(), "RECREATE" );

  TTree* outTree = new TTree("posTree","posTree");
  float xPos_calo_, yPos_calo_;
  float xPos_bgo_, yPos_bgo_;
  float xPos_new_, yPos_new_;
  float xPos_regr2D_, yPos_regr2D_;
  float r02_, r13_;

  outTree->Branch( "isSingleEle_scintFront", &isSingleEle_scintFront, "isSingleEle_scintFront/O" );
  outTree->Branch( "nHodoClustersX", &nHodoClustersX, "nHodoClustersX/I" );
  outTree->Branch( "nHodoClustersY", &nHodoClustersY, "nHodoClustersY/I" );
  outTree->Branch( "cef3_corr", cef3_corr, "cef3_corr[4]/F" );
  outTree->Branch( "r02", &r02_, "r02_/F" );
  outTree->Branch( "r13", &r13_, "r13_/F" );
  outTree->Branch( "xBeam", &xBeam, "xBeam/F" );
  outTree->Branch( "yBeam", &yBeam, "yBeam/F" );
  outTree->Branch( "xPos_bgo", &xPos_bgo_, "xPos_bgo_/F" );
  outTree->Branch( "yPos_bgo", &yPos_bgo_, "yPos_bgo_/F" );
  outTree->Branch( "xPos_calo", &xPos_calo_, "xPos_calo_/F" );
  outTree->Branch( "yPos_calo", &yPos_calo_, "yPos_calo_/F" );
  outTree->Branch( "xPos_new", &xPos_new_, "xPos_new_/F" );
  outTree->Branch( "yPos_new", &yPos_new_, "yPos_new_/F" );
  outTree->Branch( "xPos_regr2D", &xPos_regr2D_, "xPos_regr2D_/F" );
  outTree->Branch( "yPos_regr2D", &yPos_regr2D_, "yPos_regr2D_/F" );

  float diag02_calo_;
  float diag13_calo_;
  outTree->Branch( "diag02_calo", &diag02_calo_, "diag02_calo_/F" );
  outTree->Branch( "diag13_calo", &diag13_calo_, "diag13_calo_/F" );
  float diag02_new_;
  float diag13_new_;
  outTree->Branch( "diag02_new", &diag02_new_, "diag02_new_/F" );
  outTree->Branch( "diag13_new", &diag13_new_, "diag13_new_/F" );
  float diag02_beam_;
  float diag13_beam_;
  outTree->Branch( "diag02_beam", &diag02_beam_, "diag02_beam_/F" );
  outTree->Branch( "diag13_beam", &diag13_beam_, "diag13_beam_/F" );

  
  std::vector<float> xbgo, ybgo;
  for( unsigned i=0; i<BGO_CHANNELS; ++i ) {
    float x,y;
    RunHelper::getBGOCoordinates( i, x, y );
    xbgo.push_back( x );
    ybgo.push_back( y );
  }


  
  



  float cef3_regr[CEF3_CHANNELS];
  //TMVA::Reader* readerRegrX = new TMVA::Reader( "!Color:!Silent" );
  //readerRegrX->AddVariable("cef3_corr[0]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[0] );
  //readerRegrX->AddVariable("cef3_corr[1]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[1] );
  //readerRegrX->AddVariable("cef3_corr[2]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[2] );
  //readerRegrX->AddVariable("cef3_corr[3]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[3] );

  //TMVA::Reader* readerRegrY = new TMVA::Reader( "!Color:!Silent" );
  //readerRegrY->AddVariable("cef3_corr[0]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[0] );
  //readerRegrY->AddVariable("cef3_corr[1]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[1] );
  //readerRegrY->AddVariable("cef3_corr[2]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[2] );
  //readerRegrY->AddVariable("cef3_corr[3]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3])", &cef3_regr[3] ); // let try this trick

  //TMVA::Reader* readerRegr2D = new TMVA::Reader( "!Color:!Silent" );
  //readerRegr2D->AddVariable("cef3_corr[0]", &cef3_corr_[0] );
  //readerRegr2D->AddVariable("cef3_corr[1]", &cef3_corr_[1] );
  //readerRegr2D->AddVariable("cef3_corr[2]", &cef3_corr_[2] );
  //readerRegr2D->AddVariable("cef3_corr[3]", &cef3_corr_[3] );
  //readerRegr2D->BookMVA( "MLP", "TMVA/weights/TMVARegression_MLP.weights.xml" );


  std::vector<std::string> methodNames;
  //methodNames.push_back("BDTG");
  ////methodNames.push_back("FDA_MT");
  //methodNames.push_back("LD");
  //methodNames.push_back("MLP");
  ////methodNames.push_back("PDERS");

 
  //
  //std::cout << "-> Booking TMVA Reader" << std::endl;
  //for( unsigned i=0; i<methodNames.size(); ++i ) {
  //  readerRegrX->BookMVA( methodNames[i], Form("TMVA/weights/TMVARegression_%s.weights.xml", methodNames[i].c_str()) ); 
  //  readerRegrY->BookMVA( methodNames[i], Form("TMVA/weights/TMVARegression_%s.weights.xml", methodNames[i].c_str()) ); 
  //}


  std::vector< TH1D* > h1_xPos_regr_vs_calo;
  std::vector< TH1D* > h1_yPos_regr_vs_calo;
  std::vector< TH2D* > h2_xyPos_regr;
  std::vector< TH1D* > h1_xPos_regr_vs_calo_singleEle;
  std::vector< TH1D* > h1_yPos_regr_vs_calo_singleEle;
  std::vector< TH2D* > h2_xyPos_singleEle_regr;
  for( unsigned i=0; i<methodNames.size(); ++i ) {
    TH1D* newHistx = new TH1D( Form("xPos_regr%s_vs_calo", methodNames[i].c_str()), "", nBins, -xMax, xMax);
    h1_xPos_regr_vs_calo.push_back( newHistx );
    TH1D* newHisty = new TH1D( Form("yPos_regr%s_vs_calo", methodNames[i].c_str()), "", nBins, -xMax, xMax);
    h1_yPos_regr_vs_calo.push_back( newHisty );
    TH2D* newHistxy = new TH2D( Form("xyPos_regr%s", methodNames[i].c_str()), "", nBins, -xMax, xMax, nBins, -xMax, xMax);
    h2_xyPos_regr.push_back( newHistxy );
    TH1D* newHistx_singleEle = new TH1D( Form("xPos_regr%s_vs_calo_singleEle", methodNames[i].c_str()), "", nBins, -xMax, xMax);
    h1_xPos_regr_vs_calo_singleEle.push_back( newHistx_singleEle );
    TH1D* newHisty_singleEle = new TH1D( Form("yPos_regr%s_vs_calo_singleEle", methodNames[i].c_str()), "", nBins, -xMax, xMax);
    h1_yPos_regr_vs_calo_singleEle.push_back( newHisty_singleEle );
    TH2D* newHistxy_singleEle = new TH2D( Form("xyPos_singleEle_regr%s", methodNames[i].c_str()), "", nBins, -xMax, xMax, nBins, -xMax, xMax);
    h2_xyPos_singleEle_regr.push_back( newHistxy_singleEle );
  }


  TH2D* h2_xyPos_regr2D = new TH2D("xyPos_regr2D", "", nBins, -xMax, xMax, nBins, -xMax, xMax);
  TH2D* h2_xyPos_singleEle_regr2D = new TH2D("xyPos_singleEle_regr2D", "", nBins, -xMax, xMax, nBins, -xMax, xMax);





  for( unsigned iEntry=0; iEntry<nentries; ++iEntry ) {

    xPos_bgo_ = -999.;
    yPos_bgo_ = -999.;

    xPos_calo_ = -999.;
    yPos_calo_ = -999.;


    tree->GetEntry(iEntry);

    if( iEntry % 5000 == 0 ) std::cout << "Entry: " << iEntry << " / " << nentries << std::endl;

    if( !bgo_corr_ok ) continue;

    r02_ = cef3_corr[0]/cef3_corr[2];
    r13_ = cef3_corr[1]/cef3_corr[3];

    // FIRST GET POSITION FROM HODOSCOPE:


    float xPos_hodo = getMeanposHodo(nHodoClustersX, pos_hodoClustX);
    float yPos_hodo = getMeanposHodo(nHodoClustersY, pos_hodoClustY);



    if( xPos_hodo>-100. )
      h1_xPos_hodo->Fill(xPos_hodo);
    if( yPos_hodo>-100. )
      h1_yPos_hodo->Fill(yPos_hodo);

    if( xPos_hodo>-100. && yPos_hodo>-100. ) 
      h2_xyPos_hodo->Fill(xPos_hodo, yPos_hodo);


    if( isSingleEle_scintFront ) {

      if( xPos_hodo>-100. )
        h1_xPos_singleEle_hodo->Fill(xPos_hodo);
      if( yPos_hodo>-100. )
        h1_yPos_singleEle_hodo->Fill(yPos_hodo);

      if( xPos_hodo>-100. && yPos_hodo>-100. ) 
        h2_xyPos_singleEle_hodo->Fill(xPos_hodo, yPos_hodo);

    }



    std::vector<float> xPosW_bgo;
    std::vector<float> yPosW_bgo;

    std::vector<float> v_bgo_corr;
    for( unsigned i=0; i<BGO_CHANNELS; ++i ) v_bgo_corr.push_back(bgo_corr[i]);

    float eTot_bgo_corr = sumVector(v_bgo_corr);

    if( bgo_ok && bgo_corr_ok ) {

      //   0  1  2
      //   3     4
      //   5  6  7

      xPosW_bgo.push_back(bgo_corr[0]*xbgo[0]);
      xPosW_bgo.push_back(bgo_corr[1]*xbgo[1]);
      xPosW_bgo.push_back(bgo_corr[2]*xbgo[2]);
      xPosW_bgo.push_back(bgo_corr[3]*xbgo[3]);
      xPosW_bgo.push_back(bgo_corr[4]*xbgo[4]);
      xPosW_bgo.push_back(bgo_corr[5]*xbgo[5]);
      xPosW_bgo.push_back(bgo_corr[6]*xbgo[6]);
      xPosW_bgo.push_back(bgo_corr[7]*xbgo[7]);
      
      yPosW_bgo.push_back(bgo_corr[0]*ybgo[0]);
      yPosW_bgo.push_back(bgo_corr[1]*ybgo[1]);
      yPosW_bgo.push_back(bgo_corr[2]*ybgo[2]);
      yPosW_bgo.push_back(bgo_corr[3]*ybgo[3]);
      yPosW_bgo.push_back(bgo_corr[4]*ybgo[4]);
      yPosW_bgo.push_back(bgo_corr[5]*ybgo[5]);
      yPosW_bgo.push_back(bgo_corr[6]*ybgo[6]);
      yPosW_bgo.push_back(bgo_corr[7]*ybgo[7]);
      

      xPos_bgo_ = sumVector( xPosW_bgo )/eTot_bgo_corr;
      yPos_bgo_ = sumVector( yPosW_bgo )/eTot_bgo_corr;
      
      h1_xPos_bgo->Fill( xPos_bgo_ );
      h1_yPos_bgo->Fill( yPos_bgo_ );
      h2_xyPos_bgo->Fill( xPos_bgo_, yPos_bgo_ );

      h2_correlation_hodo_bgo_xPos->Fill( xPos_hodo, xPos_bgo_ );
      h2_correlation_hodo_bgo_yPos->Fill( yPos_hodo, yPos_bgo_ );
      
      if( isSingleEle_scintFront ) {

        h1_xPos_singleEle_bgo->Fill( xPos_bgo_ );
        h1_yPos_singleEle_bgo->Fill( yPos_bgo_ );
        h2_xyPos_singleEle_bgo->Fill( xPos_bgo_, yPos_bgo_ );

        h2_correlation_hodo_bgo_xPos_singleEle->Fill( xPos_hodo, xPos_bgo_ );
        h2_correlation_hodo_bgo_yPos_singleEle->Fill( yPos_hodo, yPos_bgo_ );

      }
      
    }  // if bgo ok



    // THEN USE CeF3 DATA:

    if( cef3_ok ) {


      std::vector<float> v_cef3_corr;
      for(unsigned i=0; i<CEF3_CHANNELS; ++i) v_cef3_corr.push_back(cef3_corr[i]);

      float eTot_corr = sumVector(v_cef3_corr);

      

      if( cef3_corr_ok ) {


        //   0      1
        //          
        //          
        //   3      2


        float position = 12. - 0.696; // using FN's infallible trigonometry

        //std::vector

        std::vector<float> xPosW;
        xPosW.push_back(cef3_corr[0]*(-position));
        xPosW.push_back(cef3_corr[1]*(+position));
        xPosW.push_back(cef3_corr[2]*(+position));
        xPosW.push_back(cef3_corr[3]*(-position));

        std::vector<float> yPosW;
        yPosW.push_back(cef3_corr[0]*(+position));
        yPosW.push_back(cef3_corr[1]*(+position));
        yPosW.push_back(cef3_corr[2]*(-position));
        yPosW.push_back(cef3_corr[3]*(-position));


        getCeF3Position( v_cef3_corr, xPos_new_, yPos_new_ );
        //diag02_new_ = xPos_new_;
        //diag13_new_ = yPos_new_;

        float pi = 3.14159;
        float theta = pi/4.; // 45 degrees 
        TVector2 vnew( xPos_new_, yPos_new_ );
        TVector2 dnew = vnew.Rotate(-theta);
        diag02_new_ = dnew.Y();
        diag13_new_ = dnew.X();


        TVector2 vBeam( xBeam, yBeam );
        TVector2 dBeam = vBeam.Rotate(-theta);
        diag02_beam_ = dBeam.Y();
        diag13_beam_ = dBeam.X();

        float xPos = sumVector(xPosW)/eTot_corr;
        float yPos = sumVector(yPosW)/eTot_corr;

        h1_xPos->Fill( xPos );
        h1_yPos->Fill( yPos );

        h2_xyPos->Fill( xPos, yPos );

        h1_xPos_new->Fill( xPos_new_ );
        h1_yPos_new->Fill( yPos_new_ );

        h2_xyPos_new->Fill( xPos_new_, yPos_new_ );


        // positioning with all 9 calorimeter channels:
        //float xPos_calo = sumVector( xPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.07); // cef3 is in 0,0
        //float yPos_calo = sumVector( yPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.08); // so counts only in denominator
        xPos_calo_ = sumVector( xPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.06); // cef3 is in 0,0
        yPos_calo_ = sumVector( yPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.10); // so counts only in denominator
        //float xPos_calo = sumVector( xPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.791577); // cef3 is in 0,0
        //float yPos_calo = sumVector( yPosW_bgo )/(eTot_bgo_corr + eTot_corr*0.791577); // so counts only in denominator

        TVector2 vcalo( xPos_calo_, yPos_calo_ );
        TVector2 dcalo = vcalo.Rotate(-theta);
        diag02_calo_ = dcalo.Y();
        diag13_calo_ = dcalo.X();

        //xPos_regr2D_ = readerRegr2D->EvaluateRegression( "MLP" )[0];
        //yPos_regr2D_ = readerRegr2D->EvaluateRegression( "MLP" )[1];

        cef3_regr[0] = cef3_corr[0]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3]);
        cef3_regr[1] = cef3_corr[1]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3]);
        cef3_regr[2] = cef3_corr[2]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3]);
        cef3_regr[3] = cef3_corr[3]/(cef3_corr[0]+cef3_corr[1]+cef3_corr[2]+cef3_corr[3]);
  
        if( bgo_ok && bgo_corr_ok ) {

          h1_xPos_calo->Fill( xPos_calo_ );
          h1_yPos_calo->Fill( yPos_calo_ );
          h2_xyPos_calo->Fill( xPos_calo_, yPos_calo_ );

          //for( unsigned i=0; i<methodNames.size(); ++i ) {
          //  Float_t xPos_regr = (readerRegrX->EvaluateRegression( methodNames[i] ))[0];
          //  Float_t yPos_regr = (readerRegrY->EvaluateRegression( methodNames[i] ))[0];
          //  h1_xPos_regr_vs_calo[i]->Fill( xPos_regr-xPos_calo_ );
          //  h1_yPos_regr_vs_calo[i]->Fill( yPos_regr-yPos_calo_ );
          //  h2_xyPos_regr[i]->Fill( xPos_regr, yPos_regr );
          //}
          //h2_xyPos_regr2D->Fill( xPos_regr2D_, yPos_regr2D_ );

          h1_xPos_calo_vs_hodo->Fill( xPos_calo_-xPos_hodo );
          h1_yPos_calo_vs_hodo->Fill( yPos_calo_-yPos_hodo );

          h1_xPos_calo_vs_beam->Fill( xPos_calo_-xBeam );
          h1_yPos_calo_vs_beam->Fill( yPos_calo_-yBeam );

          // CORRELATIONS BETWEEN CALO AND HODO:

          h2_correlation_cef3_bgo_xPos->Fill( xPos, xPos_bgo_ );
          h2_correlation_cef3_bgo_yPos->Fill( yPos, yPos_bgo_ );

        }

        if( isSingleEle_scintFront ) {

          h1_xPos_singleEle->Fill( xPos );
          h1_yPos_singleEle->Fill( yPos );
          h2_xyPos_singleEle->Fill( xPos, yPos );

          h1_xPos_new_singleEle->Fill( xPos_new_ );
          h1_yPos_new_singleEle->Fill( yPos_new_ );
          h2_xyPos_new_singleEle->Fill( xPos_new_, yPos_new_ );

          h1_xPos_calo_vs_hodo_singleElectron->Fill( xPos_calo_-xPos_hodo );
          h1_yPos_calo_vs_hodo_singleElectron->Fill( yPos_calo_-yPos_hodo );

          h1_xPos_calo_vs_beam_singleElectron->Fill( xPos_calo_-xBeam );
          h1_yPos_calo_vs_beam_singleElectron->Fill( yPos_calo_-yBeam );

          if( nHodoClustersX==1 && nHodoClustersY==1 && nFibres_hodoClustX[0]<=2 && nFibres_hodoClustY[0]<=2 ) {

            h1_xPos_calo_vs_hodo_singleElectron_HR->Fill( xPos_calo_-xPos_hodo );
            h1_yPos_calo_vs_hodo_singleElectron_HR->Fill( yPos_calo_-yPos_hodo );
  
            h1_xPos_calo_vs_beam_singleElectron_HR->Fill( xPos_calo_-xBeam );
            h1_yPos_calo_vs_beam_singleElectron_HR->Fill( yPos_calo_-yBeam );

          }


          h2_correlation_cef3_hodo_xPos_singleEle->Fill( xPos, xPos_hodo );
          h2_correlation_cef3_hodo_yPos_singleEle->Fill( yPos, yPos_hodo );

  
          if( bgo_ok && bgo_corr_ok ) {

            h1_xPos_singleEle_calo->Fill( xPos_calo_ );
            h1_yPos_singleEle_calo->Fill( yPos_calo_ );
            h2_xyPos_singleEle_calo->Fill( xPos_calo_, yPos_calo_ );

            //for( unsigned i=0; i<methodNames.size(); ++i ) {
            //  Float_t xPos_regr = (readerRegrX->EvaluateRegression( methodNames[i] ))[0];
            //  Float_t yPos_regr = (readerRegrY->EvaluateRegression( methodNames[i] ))[0];
            //  h1_xPos_regr_vs_calo_singleEle[i]->Fill( xPos_regr-xPos_calo_ );
            //  h1_yPos_regr_vs_calo_singleEle[i]->Fill( yPos_regr-yPos_calo_ );
            //  h2_xyPos_singleEle_regr[i]->Fill( xPos_regr, yPos_regr );
            //}

            //h2_xyPos_singleEle_regr2D->Fill( xPos_regr2D_, yPos_regr2D_ );

            h2_correlation_cef3_bgo_xPos_singleEle->Fill( xPos, xPos_bgo_ );
            h2_correlation_cef3_bgo_yPos_singleEle->Fill( yPos, yPos_bgo_ );

          }

        }

        
        outTree->Fill();


      } // if cef3_ok

    }

  }


  outfile->cd();

  outTree->Write();


  for( unsigned i=0; i<h1_xPos_regr_vs_calo.size(); ++i ) {
    h1_xPos_regr_vs_calo[i]->Write();
    h1_yPos_regr_vs_calo[i]->Write();
    h1_xPos_regr_vs_calo_singleEle[i]->Write();
    h1_yPos_regr_vs_calo_singleEle[i]->Write();
    h2_xyPos_regr[i]->Write();
    h2_xyPos_singleEle_regr[i]->Write();
  }




  h1_xPos->Write();
  h1_yPos->Write();
  h2_xyPos->Write();

  h1_xPos_singleEle->Write();
  h1_yPos_singleEle->Write();
  h2_xyPos_singleEle->Write();

  h1_xPos_new->Write();
  h1_yPos_new->Write();
  h2_xyPos_new->Write();

  h1_xPos_new_singleEle->Write();
  h1_yPos_new_singleEle->Write();
  h2_xyPos_new_singleEle->Write();

  
  
  h1_xPos_bgo->Write();
  h1_yPos_bgo->Write();
  h2_xyPos_bgo->Write();
  

  h1_xPos_hodo->Write();
  h1_yPos_hodo->Write();
  h2_xyPos_hodo->Write();

  
  h1_xPos_calo_vs_hodo->Write();
  h1_yPos_calo_vs_hodo->Write();

  h1_xPos_calo_vs_beam->Write();
  h1_yPos_calo_vs_beam->Write();
  
  h1_xPos_calo_vs_hodo_singleElectron->Write();
  h1_yPos_calo_vs_hodo_singleElectron->Write();

  h1_xPos_calo_vs_beam_singleElectron->Write();
  h1_yPos_calo_vs_beam_singleElectron->Write();
  
  h1_xPos_calo_vs_hodo_singleElectron_HR->Write();
  h1_yPos_calo_vs_hodo_singleElectron_HR->Write();

  h1_xPos_calo_vs_beam_singleElectron_HR->Write();
  h1_yPos_calo_vs_beam_singleElectron_HR->Write();
  

  std::cout << std::endl;

  

  h2_correlation_cef3_hodo_xPos->Write();
  h2_correlation_cef3_hodo_yPos->Write();

  h2_correlation_cef3_bgo_xPos->Write();
  h2_correlation_cef3_bgo_yPos->Write();

  h2_correlation_hodo_bgo_xPos->Write();
  h2_correlation_hodo_bgo_yPos->Write();

  h1_xPos_singleEle_bgo->Write();
  h1_yPos_singleEle_bgo->Write();
  h2_xyPos_singleEle_bgo->Write();
  
  h1_xPos_singleEle_hodo->Write();
  h1_yPos_singleEle_hodo->Write();
  h2_xyPos_singleEle_hodo->Write();

  h1_xPos_singleEle_hodoClust->Write();
  h1_yPos_singleEle_hodoClust->Write();
  h2_xyPos_singleEle_hodoClust->Write();

  h1_xPos_calo->Write();
  h1_yPos_calo->Write();
  h2_xyPos_calo->Write();
  
  h1_xPos_singleEle_calo->Write();
  h1_yPos_singleEle_calo->Write();
  h2_xyPos_singleEle_calo->Write();
  

  h2_correlation_cef3_hodo_xPos_singleEle->Write();
  h2_correlation_cef3_hodo_yPos_singleEle->Write();

  h2_correlation_cef3_bgo_xPos_singleEle->Write();
  h2_correlation_cef3_bgo_yPos_singleEle->Write();

  h2_correlation_hodo_bgo_xPos_singleEle->Write();
  h2_correlation_hodo_bgo_yPos_singleEle->Write();


  outfile->Close();
  std::cout << "-> Histograms saved in: " << outfile->GetName() << std::endl;


  return 0;

}
예제 #18
0
파일: model_test.cpp 프로젝트: NCIP/visda
/* Main */ 
int main()
{
	matrix MX;
	mnew(&MX, 200, 8);
	sampleLoad("data_200x8.txt", &MX);
	printf("data=\n");
	mprint(&MX);

	double mean[2][8]=
	{{4.427227e-001,	7.671556e-001,	-9.523772e-001,	3.867558e-001,	-7.916976e-001,	1.165247e-001,	-1.261666e-001,	8.550054e-002},	
	{-2.383899e-001,	-4.130850e-001,	5.128200e-001,	-2.082537e-001,	4.263000e-001,	-6.274427e-002,	6.793605e-002,	-4.603889e-002}};
	matrix MUK;
	mnew(&MUK, 2, 8);
	MUK.pr = *mean;

	matrix *Var0;
	Var0 = new matrix[2];
	for(int i=0; i<2; i++) {
		mnew(Var0+i, 8, 8);
	}
	sampleLoad("var0.txt", Var0);
	printf("var0=\n");
	mprint(Var0);
	sampleLoad("var1.txt", Var0+1);
	printf("var1=\n");
	mprint(Var0+1);
	
	double W[] = {3.500007e-001,	6.499993e-001};
	vector w0;
	vnew(&w0, 2);
	w0.pr = W;

	matrix Gxn;
	mnew(&Gxn, 200, 2);
	vector Fx;
	vnew(&Fx, 200);
	veModel(&MX, &MUK, Var0, &w0, &Gxn, &Fx);

	printf("Gxn=\n");
	mprint(&Gxn);
	printf("Fx=\n");
	vprint(&Fx);

	matrix tmp;
	mnew(&tmp, 1, 8);
	matrix tmp2;
	mnew(&tmp2, 1, 1);
	matrix cen_Dj;
	mnew(&cen_Dj, 1, 8);
	matrix cen_Dj_t;
	mnew(&cen_Dj_t, 8, 1);

	for(i=0; i<8; i++) {
			*(cen_Dj.pr+i) = *(MX.pr+0+i) - *(MUK.pr+8+i);
	}
	transpose(&cen_Dj, &cen_Dj_t);
	printf("\ncen_Dj=\n");
	mprint(&cen_Dj);
	mprint(&cen_Dj_t);

	matrix inv_Var1;
	mnew(&inv_Var1, 8, 8);
	sampleLoad("inv_var1.txt", &inv_Var1);
	mprint(&inv_Var1);

	mmMul(&cen_Dj, &inv_Var1, &tmp);
	printf("\ntmp=\n");
	mprint(&tmp);
	mmMul(&tmp, &cen_Dj_t, &tmp2);
	printf("\ntmp2=\n");
	mprint(&tmp2);
	double val = *(tmp2.pr);
	printf("\nval=%e\n", val);

	mdelete(&MX);
	mdelete(&MUK);
	mdelete(Var0);
	mdelete(Var0+1);
	vdelete(&w0);
	mdelete(&Gxn);
	vdelete(&Fx);

	return 0;

}
예제 #19
0
파일: veSubPCAPPM.cpp 프로젝트: NCIP/visda
/*******************************************************************
 Subroutine to do the Sub-Level PCA-PPM
   matrix *pcadata_re: the pointer to the new matrix containing the real part of data
                       projected onto the space defined by the PCA
   matrix *pcadata_re: the pointer to the new matrix containing the imaginary part of data
                       projected onto the space defined by the PCA
   matrix *pcavec_re:  the pointer to a matrix containing the real part
                       of eigenvector
   matrix *pcavec_im:  the pointer to a matrix containing the imaginary part
                       of eigenvector
   vector *pcaval_re:  the pointer to a vector containing the real part
                       of eigenvalues
   vector *pcaval_im:  the pointer to a vector containing the imaginary part
                       of eigenvalues
   vector *Zjk:  the pointer to a vector containing the Zjk values
   matrix *subpcappmvec_re:  the pointer to a matrix containing the real part of
                             sorted eigenvectors by sub kurtosis rank
   matrix *subpcappmvec_re:  the pointer to a matrix containing the imaginary part of
                             sorted eigenvectors by sub kurtosis rank

 return value: '1' - successfully exit
               '0' - exit with waring/error
*******************************************************************/
int veSubPCAPPM(matrix *pcadata_re, matrix *pcadata_im,
                matrix *pcavec_re, matrix *pcavec_im,
                vector *pcaval_re, vector *pcaval_im,
                vector *Zjk,
                matrix *subpcappmvec_re, matrix *subpcappmvec_im)
{
    int m, n;
    int i, j, u=0, v=0;
    vector X1n, Xm1;
    matrix mZjk;
    matrix M1;
    matrix data_pow2;
    matrix data_pow4;
    vector V1;
    vector V2;
    vector V4;
    vector kurt;
    int* kurt_id;
    double sumZjk;
    double cen_data;
    bool allreal = true;

    m=pcadata_re->m;
    n=pcadata_im->n;

    vnew(&X1n, n);
    vnew(&Xm1, m);
    mnew(&mZjk, m, n);
    mnew(&M1, m, n);
    mnew(&data_pow2, m, n);
    mnew(&data_pow4, m, n);
    vnew(&V1, n);
    vnew(&V2, n);
    vnew(&V4, n);
    vnew(&kurt, n);
    kurt_id = new int[n];


    vector V1_im;
    vector Xm1_im;
    matrix M1_im;
    double cen_data_im;
    matrix data_pow2_im;
    matrix data_pow4_im;
    vector V2_im;
    vector V4_im;
    vector kurt_im;

    vnew(&Xm1_im, m);
    mnew(&M1_im, m, n);
    mnew(&data_pow2_im, m, n);
    mnew(&data_pow4_im, m, n);
    vnew(&V1_im, n);
    vnew(&V2_im, n);
    vnew(&V4_im, n);
    vnew(&kurt_im, n);

    // whether complex eigenvalue exists
    for (i=0; i<n; i++) {
        if (*(pcaval_im->pr+i) != 0) {
            allreal = false;
            break;
        }
    }

    // center the data set its means
    // data_proj = data_proj - ones(n,1)*(sum(Zjk*ones(1,p).*(data_proj))./sum(Zjk));
    vones(&X1n);
    vones(&Xm1);

    vvMul(Zjk, &X1n, &mZjk);
    sumZjk = vsum(Zjk);

    if (allreal==true) {
        kurtmodel(&mZjk, sumZjk, pcadata_re, &V1);
        vvMul(&Xm1, &V1, &M1);

        for (i=0; i<m*n; i++) {
            cen_data = *(pcadata_re->pr + i) - *(M1.pr + i);
            //*(data->pr + i) = cen_data;
            *(data_pow2.pr+i) = pow(cen_data, 2);
            *(data_pow4.pr+i) = pow(cen_data, 4);
        }

        // calculate kurtosis : kurt(y) = E{y^4}-3(E{y^2})^2
        //kurt = sum(Zjk*ones(1,p).*(data_proj.^4))./sum(Zjk)...
        //- 3*(sum(Zjk*ones(1,p).*(data_proj.^2))./sum(Zjk)).^2; %Not normalized Kurtosis
        kurtmodel(&mZjk, sumZjk, &data_pow2, &V2);
        kurtmodel(&mZjk, sumZjk, &data_pow4, &V4);

        for (j=0; j<n; j++) {
            *(kurt.pr+j) = *(V4.pr+j) - 3*(pow(*(V2.pr+j), 2));
        }

    } else {

        ckurtmodel(&mZjk, sumZjk, pcadata_re, pcadata_im, &V1, &V1_im);
        cvvMul(&Xm1, &Xm1_im, &V1, &V1_im, &M1, &M1_im);

        for (i=0; i<m*n; i++) {
            cen_data = *(pcadata_re->pr + i) - *(M1.pr + i);
            cen_data_im = *(pcadata_im->pr + i) - *(M1_im.pr + i);
            //*(data->pr + i) = cen_data;
            *(data_pow2.pr+i) = pow(cen_data, 2) - pow(cen_data_im, 2);
            *(data_pow2_im.pr+i) = 2 * cen_data * cen_data_im;
            *(data_pow4.pr+i) = pow(*(data_pow2.pr+i), 2) - pow(*(data_pow2_im.pr+i), 2);
            *(data_pow4_im.pr+i) = 2 * (*(data_pow2.pr+i)) * (*(data_pow2_im.pr+i));
        }

        // calculate kurtosis : kurt(y) = E{y^4}-3(E{y^2})^2
        //kurt = sum(Zjk*ones(1,p).*(data_proj.^4))./sum(Zjk)...
        //- 3*(sum(Zjk*ones(1,p).*(data_proj.^2))./sum(Zjk)).^2; %Not normalized Kurtosis
        ckurtmodel(&mZjk, sumZjk, &data_pow2, &data_pow2_im, &V2, &V2_im);
        ckurtmodel(&mZjk, sumZjk, &data_pow4, &data_pow4_im, &V4, &V4_im);

        for (j=0; j<n; j++) {
            *(kurt.pr+j) = *(V4.pr+j) - 3*(pow(*(V2.pr+j), 2) - pow(*(V2_im.pr+j), 2));
            *(kurt_im.pr+j) = *(V4_im.pr+j) - 3 * 2 * (*(V2.pr+j)) * (*(V2_im.pr+j));
        }

    }




    // sort kurt value in ascending order and reorder the pca_vec
    int realeig_num;
    int *realeig_id;
    int *compeig_id;
    vector realkurt;
    int *real_order;

    realeig_num = n;
    for (i=0; i<n; i++) {
        if (*(pcaval_im->pr+i) != 0) {
            realeig_num--;
        }
    }
    vnew(&realkurt, realeig_num);

    realeig_id = new int[realeig_num];
    compeig_id = new int[n-realeig_num];
    real_order = new int[realeig_num];

    for (i=0; i<n; i++) {
        if (*(pcaval_im->pr+i) == 0) {
            realeig_id[u] = i;
            *(realkurt.pr+u) = *(kurt.pr+i);
            u++;
        } else {
            compeig_id[v] = i;
            v++;
        }
    }

    sort(&realkurt, real_order, 'a');
    int *tmp;

    tmp = new int[realeig_num];
    for (i=0; i<realeig_num; i++) {
        tmp[i] = realeig_id[i];
    }
    for (i=0; i<realeig_num; i++) {
        realeig_id[i] = tmp[real_order[i]];
    }
    delete []tmp;

    vector kurt0;
    vector kurt0_im;
    vnew(&kurt0, kurt.l);
    vcopy(&kurt, &kurt0);
    vnew(&kurt0_im, kurt.l);
    vcopy(&kurt_im, &kurt0_im);
    for (i=0; i<realeig_num; i++) {
        kurt_id[i] = realeig_id[i];
        *(kurt.pr+i) = *(realkurt.pr+i);
        *(kurt_im.pr+i) = 0;
    }
    for (i=0; i<n-realeig_num; i++) {
        kurt_id[i+realeig_num] = compeig_id[i];
        *(kurt.pr+i+realeig_num) = *(kurt0.pr + compeig_id[i]);
        *(kurt_im.pr+i+realeig_num) = *(kurt0_im.pr + compeig_id[i]);
    }

    //printf(" the real part of kurt value is : \n");
    //vprint(&kurt);
    //printf(" the imaginary part of kurt value is : \n");
    //vprint(&kurt_im);
    //printf(" the kurt id is : \n");
    //for (i=0; i<n; i++) {
    //   printf("%d\t", kurt_id[i]);
    //}
    sortcols(kurt_id, pcavec_re, subpcappmvec_re);
    sortcols(kurt_id, pcavec_im, subpcappmvec_im);


    vdelete(&X1n);
    vdelete(&Xm1);
    mdelete(&mZjk);
    mdelete(&M1);
    mdelete(&data_pow2);
    mdelete(&data_pow4);
    vdelete(&V1);
    vdelete(&V2);
    vdelete(&V4);
    vdelete(&kurt);
    vdelete(&kurt0);
    delete []kurt_id;
    vdelete(&realkurt);
    delete []realeig_id;
    delete []compeig_id;
    delete []real_order;
    vdelete(&Xm1_im);
    mdelete(&M1_im);
    mdelete(&data_pow2_im);
    mdelete(&data_pow4_im);
    vdelete(&V1_im);
    vdelete(&V2_im);
    vdelete(&V4_im);
    vdelete(&kurt_im);
    vdelete(&kurt0_im);

    return 1;
}