Esempio n. 1
0
int xcor(Rect_Type *r, int i) {

    if (r->x == 1) {return 0;} else {
     if (r->y == 1) {return i;} else {
      if (2*r->lo->y == r->y) {
        if (i < r->lo->g - r->lo->h) {return r->lo->x - 1- xcor(r->lo,i + r->lo->h);} else {
         if (i < r->lu->g + r->lo->g - r->lo->h) {
          return r->lu->x - 1 - xcor(r->lu,r->lu->g + r->lo->g -r->lo->h -i-1);
         } else {
          if (i < r->ru->g + r->lu->g + r->lo->g -r->lo->h) {
           return r->lu->x + xcor(r->ru,i - r->lu->g- r->lo->g + r->lo->h);
          } else {
           if (i < r->g - r->lo->h) {
            return r->lo->x + xcor(r->ro,r->g -r->lo->h  -i-1);
           } else {
            return r->lo->x - 1 - xcor(r->lo,i + r->lo->h -r->g);
      } }}}} else {
       if (2*r->lo->x == r->x) { return ycor(r->sp,r->g-i);
       } else {
        if (i < r->lo->h) {return xcor(r->lo,i);} else {
         if (i < r->lu->g + r->lo->h) {
          return r->lu->x - 1 - xcor(r->lu,r->lu->g + r->lo->h -i-1);
         } else {
          if (i < r->lu->g + r->ru->g + r->lo->h) {
           return r->lu->x + xcor(r->ru,i- r->lu->g -r->lo->h);
          } else {
           if (i < r->g - r->lo->g + r->lo->h) {
            return r->lo->x + xcor(r->ro,r->g -r->lo->g + r->lo->h  -i-1);
           } else {
            return xcor(r->lo,i + r->lo->g - r->g);
    }}}}}}}}
}
Esempio n. 2
0
/* displays various state values for node */
void dsp_state(NSLNSLnet *net,long nd,float aa,float bb,float cc)
{ nio_ds *np=nsl_drv(nio_ds); char *fmtstr="%.Xf ";
  fmtstr[2]=(char)('0'+np->numelm-3);
  nd-=np->bs_hd;
  w_position(np->scr_s,xcor(nd),ycor(nd));w_printf(np->scr_s,fmtstr,aa);
  w_position(np->scr_s,xcor(nd),1+ycor(nd));w_printf(np->scr_s,fmtstr,bb);
  w_position(np->scr_s,xcor(nd),2+ycor(nd));w_printf(np->scr_s,fmtstr,cc);
}
Esempio n. 3
0
/* displays various state values for node */
void dsp_state(NSLNSLnet *net,long nd,float aa,float bb,float cc)
{ char *fmtstr="%.Xf "; hop_io_ds *hp=nsl_drv(hop_io_ds); nio_ds *np=(&hp->nio); 
  if(!np->scr_s) return; /* not enough room on vdu */
  fmtstr[2]=(char)('0'+np->numelm-3);
  nd-=np->bs_hd;
  w_position(np->scr_s,xcor(nd),ycor(nd));w_printf(np->scr_s,fmtstr,aa);
  w_position(np->scr_s,xcor(nd),1+ycor(nd));w_printf(np->scr_s,fmtstr,bb);
  w_position(np->scr_s,xcor(nd),2+ycor(nd));w_printf(np->scr_s,fmtstr,cc);
}
int main()
{
	FILE* filename;
	filename=fopen("2.txt", "w");
	double t=0, tmax, xprev, xnext, vprev, vnext, x0, v0;

	printf("Enter tmax:\n");
	scanf("%lf", &tmax);
	printf("Enter h:\n");
	scanf("%lf", &h);
	printf("Enter 0<x0<pi (rad):\n");
	scanf("%lf", &x0);
	printf("Enter v0:\n");
	scanf("%lf", &v0);
	xprev=x0;
	vprev=v0;
	for(;t<=(tmax-h/4);t=t+h)
	{
		vnext=vcor(xprev, vprev, t);
		xnext=xcor(xprev, vprev, t);
		fprintf(filename ,"%.7lf %.7lf %.7lf\n", t+h, vnext, xnext/*, e(t+h, xnext)*/); 
		vprev=vnext;
		xprev=xnext;
	}

	system("pause");
	fclose(filename);
}
Esempio n. 5
0
void makeds (int ns, float *ts, float *as, int lds, int ifds, float *ds)
/*****************************************************************************
make shaping filter to correct DMO horizontal reflection response
******************************************************************************
Input:
ns		number of shifts
ts		array[ns] of time shifts (normalized by sampling interval)
as		array[ns] of amplitudes corresponding to time shifts
lds		length of shaping filter
ifds		index of first sample of shaping filter (see notes)

Output:
ds		array[lds] containing shaping filter
******************************************************************************
Notes:
Reasonable values for lds and ifds are lds=125 and ifds=-100.
The maximum permissible lds is the dimension of dd, di, and work below.

This function must be kept consistent with that used to perform DMO.
******************************************************************************
Author:  Dave Hale, Colorado School of Mines, 11/04/90
*****************************************************************************/
#define LDMAX 400
#define LDSMAX 300
{
	int ld=LDMAX,ifd=1-ld,i,is;
	float one=1.0,d[LDMAX],dd[LDSMAX],di[LDSMAX],work[LDSMAX];
	
	/* compute dmo horizontal reflection response d(t) */
	for (i=0; i<ld; ++i)
		d[i] = 0.0;
	d[ld-1] = as[0];
	for (is=1; is<ns; ++is) {
		i = (int)ts[is];
		d[ld-i-1] += 2.0*as[is];
	}
	
	/* compute autocorrelation of d(t) */
	xcor(ld,ifd,d,ld,ifd,d,lds,0,dd);
	
	/* compute crosscorrelation of d(t) and desired impulse i(t) */
	xcor(ld,ifd,d,1,0,&one,lds,ifds,di);
	
	/* solve symmetric toeplitz system of equations for filter */
	stoepf(lds,dd,di,ds,work);
}
Esempio n. 6
0
int
main(int argc, char **argv)
{
	int nt;				/* number of samples on input */
	int ntout;			/* number of samples on output */
	int it;				/* counter */
	int istart;			/* beginning sample */
	int izero;			/* - istart */
	int norm;			/* user defined normalization value */
	int sym;			/* symmetric plot? */
	float scale;			/* scale factor computed from norm */
	float *temp=NULL;		/* temporary array */
	float dt;			/* time sampling interval (sec) */

	/* hook up getpar */
	initargs(argc, argv);
	requestdoc(1);

	/* get information from the first header */
	if (!gettr(&tr)) err("can't get first trace");
	nt = tr.ns;
	dt = tr.dt/1000000.0;

	/* get parameters */
	if (!getparint("ntout",&ntout)) ntout=101;
	if (!getparint("norm",&norm)) norm = 1;
	if (!getparint("sym",&sym)) sym = 1;
        checkpars();
	
	/* allocate workspace */
	temp = ealloc1float(ntout);
	
	/* index of first sample */
	if (sym == 0) istart = 0;
	else istart = -(ntout-1)/2;

	/* index of sample at time zero */
	izero = -istart;
	
	/* loop over traces */
	do {
		xcor(nt,0,tr.data,nt,0,tr.data,ntout,istart,temp);
		if (norm) {
			scale = 1.0/(temp[izero]==0.0?1.0:temp[izero]);
			for (it=0; it<ntout; ++it)  temp[it] *= scale;
		}
		memcpy((void *) tr.data, (const void *) temp, ntout*FSIZE);
		tr.ns = ntout;
		tr.f1 = -dt*ntout/2.0;
		tr.delrt = 0;
		puttr(&tr);
	} while(gettr(&tr));

	return(CWP_Exit());
}
Esempio n. 7
0
void find_p(float *ym,float *yp,float *a,int *b,int n)
{
#define NP 1

	float *y,**x;
	int n_s;
	
	int k;
	float *res;
	int jpvt[NP];
	float qraux[NP];
	float work[NP]; 
	
														
	x = ealloc2float(n,1);
	y = ealloc1float(n);
	res = ealloc1float(n);
	
	memcpy((void *) &x[0][0], (const void *) &ym[0], n*FSIZE);
	memset((void *) y, (int) '\0', n*FSIZE);	
	
	/* Solve for shift */
 	xcor (n,0,ym,n,0,yp,n,-n/2,y);
	/* pick the maximum */
	*b = -max_index(n,y,1)+n/2;

	n_s = n-abs(*b);
 	
	if (*b < 0) {
		memcpy((void *) &x[0][0], (const void *) &ym[*b], n_s*FSIZE);
	} else {
		memcpy((void *) &x[0][*b], (const void *) &ym[0], n_s*FSIZE);
													
	}
	/* Solve for scaler */
	sqrst(x, n_s, 1,yp,0.0,a,res,&k,&jpvt[0],&qraux[0],&work[0]);
	
	
	
	free2float(x);
	free1float(res);
	free1float(y);
}
Esempio n. 8
0
main(int argc, char **argv)
{
	int nt;			/* number of points on trace		*/
	float dt;		/* time sample interval (sec)		*/
	float *wiener;		/* Wiener error filter coefficients	*/
	float pnoise;		/* pef additive noise level		*/
	float minlag;		/* start of error filter (sec)		*/
	int iminlag;		/* ... in samples			*/
	float maxlag;		/* end of error filter (sec)		*/
	int imaxlag;		/* ... in samples			*/
	int nlag;		/* length of error filter in samples	*/
	int ncorr;		/* length of corr window in samples	*/
	float *crosscorr;	/* right hand side of Wiener eqs	*/
	float *autocorr;	/* vector of autocorrelations		*/
	float *spiker;		/* spiking decon filter			*/
	float mincorr;		/* start time of correlation window	*/
	int imincorr;		/* .. in samples			*/
	float maxcorr;		/* end time of correlation window	*/
	int imaxcorr;		/* .. in samples			*/
	int showspiker;		/* flag to display spiking filter	*/
	int showwiener;		/* flag to display pred. error filter	*/



	/* Initialize */
	initargs(argc, argv);
	askdoc(1);


	/* Get info from first trace */ 
	if (!gettr(&intrace)) err("can't get first trace");
	nt = intrace.ns;
	dt = (float)intrace.dt/1000000.0; if (!dt) MUSTGETPARFLOAT ("dt", &dt);


	/* Get parameters */
	if (!getparint("showwiener",  &showwiener))	showwiener = 0;
	if (!getparint("showspiker",  &showspiker))	showspiker = 0;

	if (!getparfloat("pnoise",  &pnoise))	pnoise = PNOISE;

	if (getparfloat("minlag", &minlag))	iminlag = NINT(minlag/dt);
	else					iminlag = 1;
	if (iminlag < 1) err("minlag=%g too small", minlag);

	if (getparfloat("maxlag", &maxlag))	imaxlag = NINT(maxlag/dt);
	else					imaxlag = NINT(0.05 * nt);
	if (imaxlag >= nt) err("maxlag=%g too large", maxlag);
	
	if (iminlag >= imaxlag)
		err("minlag=%g, maxlag=%g", minlag, maxlag);
	
	if (getparfloat("mincorr", &mincorr))	imincorr = NINT(mincorr/dt);
	else					imincorr = 0;
	if (imincorr < 0) err("mincorr=%g too small", mincorr);
	
	if (getparfloat("maxcorr", &maxcorr))	imaxcorr = NINT(maxcorr/dt);
	else					imaxcorr = nt-1;
	if (imaxcorr >= nt) err("maxcorr=%g too large", maxcorr);

	if (imincorr >= imaxcorr)
		err("mincorr=%g, maxcorr=%g", mincorr, maxcorr);
	
	nlag  = imaxlag - iminlag + 1;
	ncorr = imaxcorr - imincorr + 1;


	/* Allocate memory */
	wiener	 = ealloc1float(nlag);
	spiker	 = ealloc1float(nlag);
	autocorr = ealloc1float(imaxlag);


	/* Set pointer to "cross" correlation */
	crosscorr = autocorr + iminlag;



	/* Main loop over traces */
	do {
		static int itr = 0;
		++itr;

		/* Form autocorrelation vector */
		xcor(ncorr, imincorr, intrace.data,
		     ncorr, imincorr, intrace.data,
		     imaxlag, 0, autocorr);


		/* Leave trace alone if autocorr[0] vanishes */
		if (autocorr[0] == 0.0) {
			puttr(&intrace);
			if (showwiener)
				warn("NO Wiener filter, trace: %d", itr);
			if (showspiker)
				warn("NO spiking decon filter, trace: %d", itr);

			continue;
		}


		/* Whiten */
		autocorr[0] *= 1.0 + pnoise;


		/* Get inverse filter by Wiener-Levinson */
		stoepf(nlag, autocorr, crosscorr, wiener, spiker);
		

		/* Convolve pefilter with trace - don't do zero multiplies */
		{ register int i;
		  for (i = 0; i < nt; ++i) {
			register int j;
			register int n = MIN(i, imaxlag); 
			register float sum = intrace.data[i];

			for (j = iminlag; j <= n; ++j)
				sum -= wiener[j-iminlag] * intrace.data[i-j];

			outtrace.data[i] = sum;
		  }
		}


		/* Output filtered trace */
		memcpy((char*)&outtrace, (char*)&intrace, HDRBYTES);
		puttr(&outtrace);


		/* Show pefilter and/or spiker on request */
		if (showwiener) {
			register int i;
			warn("Wiener filter, trace: %d", itr);
			for (i = 0; i < imaxlag; ++i)
				fprintf(stderr, "%10g%c", wiener[i],
					(i%6==5 || i==nlag-1) ? '\n' : ' ');
		}
		
		if (showspiker) {
			register int i;
			warn("spiking decon filter, trace: %d", itr);
			for (i = 0; i < nlag; ++i)
				fprintf(stderr, "%10g%c", spiker[i],
					(i%6==5 || i==nlag-1) ? '\n' : ' ');
		}

	} while (gettr(&intrace));


	return EXIT_SUCCESS;
}
Esempio n. 9
0
void do_minphdec(float *tr,int nt, float *filter,int fnl,int fnr,float prw)
{

	float *rtr;
	float *rtx;     
	complex *f;
	complex *w;
	complex a;
	int iamp;
	float amp;
	float ampm=-1.0e+20;
	float amps;
	float *am;
	float *ph;	
	float mean=0.0;
	float sum=0.0;

	int nfftc; 
        int nf;    
	int i,j;			/* counter */
	float snfftc;
	

	/* Set up pfa fft */
	nfftc = npfao(nt,LOOKFAC*nt); 
        if (nfftc >= SU_NFLTS || nfftc >= PFA_MAX)
                 err("Padded nt=%d--too big", nfftc);
        nf = nfftc/2 + 1;
	snfftc=1.0/nfftc;

        rtr = ealloc1float(nfftc);
        rtx = ealloc1float(nf);
	f = ealloc1complex(nfftc);
	w = ealloc1complex(nfftc);
	am = ealloc1float(nf);
	ph = ealloc1float(nf);
        
	/* clean the arrays */
	memset( (void *) w, (int) '\0', nfftc*sizeof(complex));
        memset( (void *) rtr, (int) '\0', nfftc*FSIZE);
	
	/* Cross correlation */
	xcor(nt,0,tr,nt,0,tr,nf,0,rtr);

        /* FFT */
	pfarc(1, nfftc,rtr,w);

	/* stabilize */
	for(i=0;i<nf;i++) {
		am[i] += am[i]*prw;
	}
	
	/* Normalize */
	for(i=0;i<nf;i++) {
		a=w[i];
		am[i]= sqrt(a.r*a.r+a.i*a.i);
		sum += am[i];
		if(am[i]!=0) ph[i] = atan2(a.i,a.r);
		else ph[i]=0;
	}
	sum *=	1.0/nf;
	sum = 1.0/sum;
	sscal(nf,sum,am,1);
	
	/* Smooth the apmlitude spectra  */
	if(fnl!=0) conv (fnl+fnr+1,-fnl,filter,nf,0,am,nf,0,am);

	fprintf(stderr," %f\n",sum);	
	
	for(i=0;i<nf;i++) {
		w[i].r = am[i]*cos(ph[i]);
		w[i].i = am[i]*sin(ph[i]);
	}
	for(i=nf,j=nf-1;i<nfftc;i++,j--) {
		w[i].r = am[j]*cos(ph[j]);
		w[i].i = am[j]*sin(ph[j]);
	}
		
	/* log spectra */
	for (i = 0; i < nfftc; ++i)  w[i] =
		crmul(clog(cmul(w[i],conjg(w[i]))),0.5);

	/* Hilbert transform */
	pfacc(-1,nfftc,w);
        for (i=0; i<nfftc; ++i) {
		w[i].r *=snfftc;
		w[i].i *=snfftc;
	}
	for(i=1;i<nfftc/2;i++) w[i] = cadd(w[i],w[i]);
	for(i=nfftc/2;i<nfftc;i++) w[i] = cmplx(0,0);
	pfacc(1,nfftc,w);
	/* end of Hilbert transform */
	
	/* exponentiate */
	for(i=0;i<nfftc;i++) w[i] = cexp(w[i]);
	
	/* inverse filter */
	for(i=0;i<nfftc;i++) f[i] = cdiv(cmplx(1.0,0),w[i]);
	
	/* Load trace into tr (zero-padded) */
        memset( (void *) w, (int) '\0',nfftc*sizeof(complex));
	for(i=0;i<nt;i++) w[i].r = tr[i];

	/* Trace to frequency domain */
	pfacc(1,nfftc,w);
      
      	/* apply filter */
        for(i=0;i<nfftc;i++) w[i] = cmul(w[i],f[i]);
             
        /* Time domain */
        pfacr(-1, nfftc,w,rtr);
	for(i=0;i<nt;i++) rtr[i] *=snfftc;
	
	memcpy( (void *) tr, (const void *) rtr, nt*FSIZE);				
	
	free1float(rtr);
	free1float(am);
	free1float(ph);
	free1complex(f);
	free1complex(w);
}	
Esempio n. 10
0
int
main(int argc, char **argv)
{
	int nt;			/* number of points on trace		*/
	float dt;		/* time sample interval (sec)		*/
	float *shaper;		/* shaping filter coefficients		*/
	float *spiker;		/* spiking decon filter (not used)	*/
	float *w;		/* input wavelet			*/
	int nw;			/* length of input wavelet in samples	*/
	float *d;		/* desired output wavelet		*/
	int nd;			/* length of desired wavelet in samples	*/
	int nshape;		/* length of shaping filter in samples	*/
	float pnoise;		/* pef additive noise level		*/
	float *crosscorr;	/* right hand side of Wiener eqs	*/
	float *autocorr;	/* vector of autocorrelations		*/
	int showshaper;		/* flag to display shaping filter	*/
        float f_zero=0.0;       /* zero valued item for comparison      */

	cwp_String wfile="";	/* input wavelet file name		*/
	cwp_String dfile="";	/* desired output wavelet file name	*/
	FILE *wfp;		/* input wavelet file pointer 		*/
	FILE *dfp;		/* desired wavelet file pointer		*/


	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);


	/* Get info from first trace */ 
	if (!gettr(&intrace)) err("can't get first trace");
	nt = intrace.ns;
	dt = intrace.dt/1000000.0;	if (!dt) MUSTGETPARFLOAT ("dt", &dt);


	/* Get parameters */
	if (!getparint("showshaper",  &showshaper))	showshaper = 0;
	if (!getparint("nshape",  &nshape))		nshape = nt;
	if (!getparfloat("pnoise",  &pnoise))		pnoise = PNOISE;

	/* Open dfile and wfile if they have been getparred */
	getparstring("dfile",&dfile);	
	getparstring("wfile",&wfile);	

	if ((*dfile=='\0')) { /* if no dfile, then get from command line */
		if (!(nd = countparval("d")))
			err("must specify d= desired wavelet");
		d = ealloc1float(nd);	getparfloat("d", d);

	} else { /* read from dfile  */

                if((dfp=fopen(dfile,"r"))==NULL)
                        err("cannot open dfile=%s\n",dfile);

        	if (!fgettr(dfp,&dtr))  err("can't get input wavelet");
        		nd = (int) dtr.ns;
		d = ealloc1float(nd);
		memcpy((void *) d, (const void *) dtr.data, nd*FSIZE);
	}
		
	if ((*wfile=='\0')) { /* then get w from command line */
		if (!(nw = countparval("w")))
			err("must specify w= desired wavelet");
		w = ealloc1float(nw);	getparfloat("w", w);

	} else { /* read from wfile  */

                if((wfp=fopen(wfile,"r"))==NULL)
                        err("cannot open wfile=%s\n",wfile);

        	if (!fgettr(wfp,&wtr))  err("can't get desired output wavelet");
        		nw = (int) wtr.ns;
		w = ealloc1float(nw);
		memcpy((void *) w, (const void *) wtr.data, nw*FSIZE);
	}


	/* Get shaping filter by Wiener-Levinson */
	shaper	  = ealloc1float(nshape);
	spiker 	  = ealloc1float(nshape);	/* not used */
	crosscorr = ealloc1float(nshape);
	autocorr  = ealloc1float(nshape);
	xcor(nw, 0, w, nw, 0, w, nshape, 0, autocorr);  /* for matrix */
	xcor(nw, 0, w, nd, 0, d, nshape, 0, crosscorr); /* right hand side */
        if (CLOSETO(autocorr[0],f_zero))  err("can't shape with zero wavelet");
	autocorr[0] *= (1.0 + pnoise);			/* whiten */
	stoepf(nshape, autocorr, crosscorr, shaper, spiker);
		

	/* Show shaper on request */
	if (showshaper) {
		register int i;
		warn("Shaping filter:");
		for (i = 0; i < nshape; ++i)
			fprintf(stderr, "%10g%c", shaper[i],
				(i%6==5 || i==nshape-1) ? '\n' : ' ');
	}



	/* Main loop over traces */
	do {
		/* Center and convolve shaping filter with trace */
		conv(nshape, (nw-nd)/2, shaper,
		     nt, 0, intrace.data, 
                     nt, 0, outtrace.data);        


		/* Output filtered trace */
		memcpy( (void *) &outtrace, (const void *) &intrace, HDRBYTES);
		puttr(&outtrace);

	} while (gettr(&intrace));


	return(CWP_Exit());
}
Esempio n. 11
0
void draw_dca_distrib()
{
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat("plain");
  //gStyle->SetOptStat(000000);

  Float_t contrib[knpart][knpbin][knseg_max];
  for ( int ipart = 0; ipart < knpart; ipart++ ) 
    for ( int ipbin = 0; ipbin < knpbin; ipbin++ )
      for ( int iseg = 0; iseg < knseg_max; iseg++ )
        contrib[ipart][ipbin][iseg] = 1;
  /*
  contrib[1][0][1] = 0;
  contrib[1][1][1] = 0;
  contrib[2][0][1] = 0;
  contrib[2][1][1] = 0;
  contrib[2][2][1] = 0;
  contrib[2][3][1] = 0;
  contrib[3][0][1] = 0;
  contrib[3][1][1] = 0;
  contrib[3][2][1] = 0;
  contrib[3][3][1] = 0;
  */

  TFile *f[knpart][knseg_max];

  //f[0][0] = new TFile("../data/merge/match_pdst_pp_ba_24m_3.root");
  //f[0][0] = new TFile("../data/merge/match_pdst_pp_ba_flat.root");
  f[0][0] = new TFile("meson_transform/data/train_b.root");

  //f[1][0] = new TFile("../data/merge/match_pdst_pp_ca_4.253b_3.root");
  //f[1][0] = new TFile("../data/merge/match_pdst_pp_ca_flat.root");
  f[1][0] = new TFile("meson_transform/data/train_c.root");


  //f[2][0] = new TFile("../data/merge/match_pdst_pp_bg_250b_2.root"); 
  f[2][0] = new TFile("../data/merge/match_pdst_pp_bg_250b_2.root");


  f[3][0] = new TFile("../data/merge/match_pdst_pp_ba_24m_3.root");

  f[4][0] = new TFile("../data/merge/match_pdst_pp_all_250b_3.root");

  TFile *freadin = new TFile("bin500_10pb/draw_dca_distrib_3.root", "READ");
  TH1F *hpart_total_tmp[knpart][knpbin];

  TString tree_name("mc_trk_eval");
  TTree *t[knpart][knseg_max]; 
  for ( Int_t ipart = 0; ipart < knpart; ipart++ ) {
    for ( Int_t iseg = 0; iseg < knseg[ipart]; iseg++ ) {
      cout << f[ipart][iseg]->GetName() << endl;
      t[ipart][iseg] = (TTree*)f[ipart][iseg]->Get(tree_name);
      //if (ipart == 4) t[ipart][iseg] = (TTree*)f[ipart][iseg]->Get("trk_eval");
    }
  }

  
  TH1F *hpart[knpart][knpbin][knseg_max];
  TString hpart_name[knpart][knpbin][knseg_max];

  TH1F *hpart_total[knpart][knpbin];
  TString hpart_total_name[knpart][knpbin];

  TString draw_value("(x0reco-evtx0mc)*(px0reco/sqrt(px0reco**2+py0reco**2))+(y0reco-evty0mc)*(py0reco/sqrt(px0reco**2+py0reco**2))");
//  TString draw_value("(y0reco-evty0mc)*(px0reco/sqrt(px0reco**2+py0reco**2))-(x0reco-evtx0mc)*(py0reco/sqrt(px0reco**2+py0reco**2))");

  TString cut_value("Abs((X0reco-evtx0mc)*(px0reco/sqrt(px0reco**2+py0reco**2))+(y0reco-evty0mc)*(py0reco/sqrt(px0reco**2+py0reco**2)))<0.5&&x0reco!=-9999&&y0reco!=-9999");
  TString dca_phi_cut_value("&&abs((y0reco-evty0mc)*(px0reco/sqrt(px0reco**2+py0reco**2))-(x0reco-evtx0mc)*(py0reco/sqrt(px0reco**2+py0reco**2)))<1&&x0reco!=-9999&&y0reco!=-9999&&mu_px!=-9999");

  //TString draw_value("((x0mc-px0mc/pz0mc*(z0mc-evtz0mc))-evtx0mc)*(px0mc/sqrt(px0mc**2+py0mc**2))+((y0mc-py0mc/pz0mc*(z0mc-evtz0mc))-evty0mc)*(py0mc/sqrt(px0mc**2+py0mc**2))");

  //TString draw_value("((y0mc-py0mc/pz0mc*(z0mc-evtz0mc))-evty0mc)*(px0mc/sqrt(px0mc**2+py0mc**2))-((x0mc-px0mc/pz0mc*(z0mc-evtz0mc))-evtx0mc)*(py0mc/sqrt(px0mc**2+py0mc**2))");

  //TString draw_value("mu_chi2");
  //TString cut_value("mu_chi2<100&&x0reco!=-9999&&y0reco!=-9999&&mu_px!=-9999");

  TString mu_cut_value("&&mu_chi2<5&&mu_lastGap==4&&abs(mu_eta)>1.2&&abs(mu_eta)<2.4&&mu_DG0<15&&mu_pT<30&&abs(mu_pz)>2.8&&abs(mu_pz)<=30&&mu_DDG0<10&&mu_mutr_nhits>=12");
 
  TString xcor("mu_pT");

  cut_value += dca_phi_cut_value;
  cut_value += mu_cut_value;

  //cut_value += "&&Entry$<100";

  TH1F *hmu_pT[knpart];
  for ( Int_t ipart = 0; ipart < knpart; ipart++ ) {
    TString hmu_pT_name("mu_pT_");
    hmu_pT_name += kpart_name[ipart];
    hmu_pT[ipart] = new TH1F(hmu_pT_name, hmu_pT_name, 2*knpbin, kpmin, kpmax);

    if (kreadin[ipart] == 0) t[ipart][0]->Draw( xcor + ">>" + hmu_pT_name, cut_value );
  } 


  TH1F *hdca_res[knpart];
  for ( Int_t ipart = 0; ipart < knpart; ipart++ ) {
    TString dca_res_name("DCA_res_");
    dca_res_name += kpart_name[ipart];
    hdca_res[ipart] = new TH1F(dca_res_name, dca_res_name, knpbin, kpmin, kpmax);
  }

  TH1F *hppart[knpart][knpbin];
  TString hppart_name[knpart][knpbin];  
  TH1F *hppart_total[knpart];
  TString hppart_total_name[knpart];
  for ( Int_t ipart = 0 ; ipart < 2; ipart++ ) {
    hppart_total_name[ipart] = TString("h_") + kpart_name[ipart] + "_p_pt_total";
    hppart_total[ipart] = new TH1F(hppart_total_name[ipart], hppart_total_name[ipart], knppbin, kppmin, kppmax);
    if (kreadin[ipart] == 0) t[ipart][0]->Draw( "py_p_pT>>" + hppart_total_name[ipart], cut_value );
  }
  for ( Int_t ipbin = 0; ipbin < knpbin; ipbin++ ) {
    Float_t pmin = kpmin + ipbin * kpstep;
    Float_t pmax = kpmin + (ipbin+1) * kpstep;

    for ( Int_t ipart = 0; ipart < knpart; ipart++ ) {
      hpart_total_name[ipart][ipbin] = TString("h_") + kpart_name[ipart] + "_pt_" + int((ipbin+2)/2);
      if (ipbin%2 == 1) hpart_total_name[ipart][ipbin] += TString(".5");
   
      //read in hist
      if (kreadin[ipart] == 1)
      {
        hpart_total_tmp[ipart][ipbin] = (TH1F*)((TCanvas*)freadin->Get("dca"))->GetPad(ipbin+1)->FindObject( hpart_total_name[ipart][ipbin] );
        if (!hpart_total_tmp[ipart][ipbin]) cout << hpart_total_name[ipart][ipbin] << " not found " << endl;
        hpart_total_tmp[ipart][ipbin]->SetName(hpart_total_name[ipart][ipbin] + "_readin");
        //cout << "  hpart_total_tmp name " << hpart_total_tmp[ipart][ipbin]->GetName() << endl;
      }

      hpart_total[ipart][ipbin] = new TH1F( hpart_total_name[ipart][ipbin], hpart_total_name[ipart][ipbin], khbin, khxmin, khxmax );
      if (kreadin[ipart] == 1) 
      {
        for (int idcabin = 0; idcabin < khbin; idcabin++) hpart_total[ipart][ipbin]->SetBinContent(idcabin+1, hpart_total_tmp[ipart][ipbin]->GetBinContent(idcabin+1));
      }

      for ( Int_t iseg = 0; iseg < knseg[ipart]; iseg++ ) {
        hpart_name[ipart][ipbin][iseg] = TString("h_") + kpart_name[ipart] + "_pt_" + (ipbin+1) + "_seg" + iseg;
        cout << hpart_name[ipart][ipbin][iseg] << endl;
        hpart[ipart][ipbin][iseg] = new TH1F( hpart_name[ipart][ipbin][iseg], hpart_name[ipart][ipbin][iseg], khbin, khxmin, khxmax );

        TString pcut;
        stringstream pcutstr;
        //pcutstr << "py_p_pT>4&&";
        pcutstr << xcor.Data() << ">=" << pmin << "&&" << xcor.Data() << "<" << pmax;
        pcut = pcutstr.str();
        cout << pcut << endl;

        //if (ipart != 4) t[ipart][iseg]->Draw( draw_value + ">>" + hpart_name[ipart][ipbin][iseg], cut_value+"&&"+pcut+"&&Entry$%2==0");
        //else t[ipart][iseg]->Draw( draw_value + ">>" + hpart_name[ipart][ipbin][iseg], cut_value+"&&"+pcut+"&&Entry$%2==1");
        if (kreadin[ipart] == 0) t[ipart][iseg]->Draw( draw_value + ">>" + hpart_name[ipart][ipbin][iseg], cut_value+"&&"+pcut );
      }
      hppart_name[ipart][ipbin] = TString("h_") + kpart_name[ipart] + "_p_pt_" + int((ipbin+2)/2);
      if (ipbin%2 == 1) hppart_name[ipart][ipbin] += TString(".5");
      cout << hppart_name[ipart][ipbin] << endl;
      hppart[ipart][ipbin] = new TH1F( hppart_name[ipart][ipbin], hppart_name[ipart][ipbin], knppbin, kppmin, kppmax );
      TString pcut;
      stringstream pcutstr;
      pcutstr << xcor.Data() << ">=" << pmin << "&&" << xcor.Data() << "<" << pmax;
      pcut = pcutstr.str();
      cout << pcut << endl;
      if (kreadin[ipart] == 0) t[ipart][0]->Draw( "py_p_pT>>" + hppart_name[ipart][ipbin], cut_value+"&&"+pcut );

      for (int jpbin = 0; jpbin < knppbin; jpbin++)
      {
        if (ipart >= 2) continue;
        if (hppart_total[ipart] != 0 && hppart_total[ipart]->GetBinContent(jpbin+1) != 0)
          hppart[ipart][ipbin]->SetBinContent(jpbin+1, hppart[ipart][ipbin]->GetBinContent(jpbin+1)/hppart_total[ipart]->GetBinContent(jpbin+1));
        else 
          hppart[ipart][ipbin]->SetBinContent(jpbin+1, 0);
      } 
    }
  }

  TCanvas *c_dca = new TCanvas( "dca", "dca", 1200, 900 );
  c_dca->Divide(knpadx, knpady) ;

  for ( Int_t ipbin = 0; ipbin < knpbin; ipbin++ ) {
    c_dca->cd(ipbin+1);
    Float_t hymax = 0.0;

    for ( Int_t ipart = knpart-1 ; ipart >= 0; ipart-- ) {
      hdca_res[ipart]->SetBinContent(ipbin, hpart[ipart][ipbin][0]->GetRMS());
      hdca_res[ipart]->SetBinError(ipbin, hpart[ipart][ipbin][0]->GetRMSError());

      TString draw_option("");
      if (ipart != knpart-1) draw_option = TString("same");

      int nseg_contrib = 0;
      for ( Int_t iseg = 0; iseg < knseg[ipart]; iseg++ ) {
        float scale = klt*ksigma[ipart]/knevent[ipart][iseg];
        cout << "ipart " << ipart << " iseg " << iseg << " ipbin " << ipbin << " : " << scale << endl;
/*        if ( ipart != knpart-1 ) {
          if( knevent[ipart][iseg] != 0 ) hpart[ipart][ipbin][iseg]->Scale( klt*ksigma[ipart]/knevent[ipart][iseg] );
          else hpart[ipart][ipbin][iseg]->Scale(0);
        }
*/
        if ( hpart[ipart][ipbin][iseg] ) hpart[ipart][ipbin][iseg]->Scale( contrib[ipart][ipbin][iseg] );
        if ( contrib[ipart][ipbin][iseg] != 0 ) nseg_contrib += contrib[ipart][ipbin][iseg];
        
        *hpart_total[ipart][ipbin] = *hpart_total[ipart][ipbin] + *hpart[ipart][ipbin][iseg];
      }

      cout << "nseg_contrib " << nseg_contrib << endl;

      hpart_total[ipart][ipbin]->Scale( 1.0/nseg_contrib );
      //if ( ipart != knpart-1 ) 
      //hpart_total[ipart][ipbin]->Scale( kreal[ipart] );

      hpart_total[ipart][ipbin]->GetXaxis()->SetTitle("dca_r [cm]");
      hpart_total[ipart][ipbin]->SetLineColor( khcolor[ipart] );
      hpart_total[ipart][ipbin]->SetLineWidth( khwidth[ipart] );
      hpart_total[ipart][ipbin]->SetMinimum(khymin);
      hpart_total[ipart][ipbin]->SetMaximum(khymax);
      if (ipart != 3) 
      hpart_total[ipart][ipbin]->Draw( draw_option );
      
      /*
      TGraphErrors *tg = histo_to_tgraph( hpart_total[ipart][ipbin], false );
      TString tg_title = hpart_total_name[ipart][ipbin];
      tg_title.Replace(0, 8, "@pT=");
      tg_title += TString("GeV");
      tg->SetTitle( tg_title );
      tg->GetXaxis()->SetTitle("DCA_r [cm]"); 
      tg->SetMarkerColor( khcolor[ipart] );
      tg->SetLineColor( khcolor[ipart] );
      tg->SetLineWidth( khwidth[ipart] );
      tg->SetMinimum(khymin);
      tg->SetMaximum(khymax);
      if (ipart != 3) tg->Draw( draw_option );

      TLatex ll[4];
      ll[0].SetTextSize(0.045);
      ll[0].DrawLatex(1., 0.9,"Merged events");
      ll[1].SetTextColor(2);
      ll[1].DrawLatex(1., 0.8, "B events");
      ll[2].SetTextColor(4);
      ll[2].DrawLatex(1., 0.7, "D events");
      ll[3].SetTextColor(6);
      ll[3].DrawLatex(1., 0.6, "Bkgnd events");
      */

      c_dca->GetPad( ipbin+1 )->SetLogy();
      c_dca->GetPad( ipbin+1 )->SetGridx();
      c_dca->GetPad( ipbin+1 )->SetGridy();

    }
  }

  TCanvas *c_dca_res = new TCanvas("c_dca_res", "c_dca_res"); 
  for ( Int_t ipart = knpart-1 ; ipart >= 0; ipart-- ) {
    TString draw_option("pl");
    if (ipart != knpart-1) draw_option += "same";

    hdca_res[ipart]->SetMinimum(0.0);
    hdca_res[ipart]->SetMaximum(0.2);
    hdca_res[ipart]->SetLineColor( khcolor[ipart] );
    if (ipart != 3) hdca_res[ipart]->Draw( draw_option ); 
  }

  TCanvas *c_ppT = new TCanvas( "ppT", "ppT", 1200, 900 );
  c_ppT->Divide(knpadx, knpady);
  for ( Int_t ipbin = 0; ipbin < knpbin; ipbin++ ) {
    c_ppT->cd(ipbin+1);

    double hbin_max = 0;
    for ( Int_t ipart = 1 ; ipart >= 0; ipart-- ) {
      if (hppart[ipart][ipbin]->GetBinContent( hppart[ipart][ipbin]->GetMaximumBin() ) > hbin_max)
        hbin_max = hppart[ipart][ipbin]->GetBinContent( hppart[ipart][ipbin]->GetMaximumBin() );
    }

    for ( Int_t ipart = knpart-1 ; ipart >= 0; ipart-- ) {
      TString draw_option("");
      if (ipart != knpart-1) draw_option = TString("same");

      hppart[ipart][ipbin]->SetLineColor( khcolor[ipart] );
      hppart[ipart][ipbin]->SetLineWidth( khwidth[ipart] );
      hppart[ipart][ipbin]->SetMaximum( hbin_max*1.2 );

      if (ipart == 0 || ipart == 1)
        hppart[ipart][ipbin]->Draw( draw_option );
    }
  }
  c_ppT->SaveAs("c_ppT.gif");

  TCanvas *c_mu_pT = new TCanvas("c_mu_pT", "c_mu_pT", 1200, 900 );
  for ( Int_t ipart = knpart-1 ; ipart >= 0; ipart-- ) {
    TString draw_option("");
    if (ipart != knpart-1) draw_option += "same";

    hmu_pT[ipart]->SetLineColor( khcolor[ipart] );
    if (ipart != 3) hmu_pT[ipart]->Draw( draw_option );
  }

  TFile *f_out = new TFile("draw_dca_distrib.root", "RECREATE");
  c_dca->Write();
  c_dca_res->Write();
  c_ppT->Write();
  c_mu_pT->Write();
}