void CameraFPS::Event(SDL_Event* event) {
	if (_disableCamera) {
		if (event->type == SDL_KEYDOWN && event->key.keysym.sym == SDLK_t) {
				_disableCamera = false;
		}
		return;
	}

	switch (event->type) {
	case SDL_MOUSEMOTION: if (_captureMouse) { mouseMotionCaptured(event); } break;
	case SDL_KEYDOWN:
		switch (event->key.keysym.sym){
		case SDLK_t:	 disabledCamera(true); break;
		case SDLK_s:	 move(Z, NEGATIVE); break;
		case SDLK_w:	 move(Z, POSITIVE); break;
		case SDLK_a:	 move(X, NEGATIVE); break;
		case SDLK_d:	 move(X, POSITIVE); break;
		case SDLK_LCTRL: move(Y, NEGATIVE); break;
		case SDLK_SPACE: move(Y, POSITIVE); break;
		case SDLK_z:	 turbo(!turbo());	break;

		case SDLK_PLUS:
		case SDLK_KP_PLUS:		boost(10);	  break;
		case SDLK_MINUS:
		case SDLK_KP_MINUS:		boost(-10);	  break;
		case SDLK_KP_MULTIPLY:	boost(1000); break;
		case SDLK_KP_DIVIDE:	boost(-1000); break;

		case SDLK_q:	 rotate(Y, NEGATIVE); break;
		case SDLK_e:	 rotate(Y, POSITIVE); break;
		case SDLK_r:	 rotate(X, NEGATIVE); break;
		case SDLK_f:	 rotate(X, POSITIVE); break;
		default:;
		}
		break;
	case SDL_KEYUP:
		switch (event->key.keysym.sym){
		case SDLK_s:	 move(Z, ZERO); break;
		case SDLK_w:	 move(Z, ZERO); break;
		case SDLK_a:	 move(X, ZERO); break;
		case SDLK_d:	 move(X, ZERO); break;
		case SDLK_SPACE: move(Y, ZERO); break;
		case SDLK_LCTRL: move(Y, ZERO); break;

		case SDLK_q:	 rotate(Y, ZERO); break;
		case SDLK_e:	 rotate(Y, ZERO); break;
		case SDLK_r:	 rotate(X, ZERO); break;
		case SDLK_f:	 rotate(X, ZERO); break;
		default:;
		}
		break;
	default:
		break;
	}
}
Example #2
0
    void boost::qr_decompose(boost& Q, boost& R) const {
        float mag;
        float alpha;

        bnu::matrix<float> u(this->num_rows(), 1);
        bnu::matrix<float> v(this->num_rows(), 1);

        bnu::identity_matrix<float> I(this->num_rows());

        bnu::matrix<float> q = bnu::identity_matrix<float>(this->num_rows());
        bnu::matrix<float> r(data());

        for (int i = 0; i < num_rows(); i++) {
            bnu::matrix<float> p(num_rows(), num_rows());

            u.clear();
            v.clear();

            mag = 0.0;

            for (int j = i; j < num_cols(); j++) {
                u(j,0) = r(j, i);
                mag += u(j,0) * u(j,0);
            }

            mag = std::sqrt(mag);

            alpha = -1 * mag;

            mag = 0.0;

            for (int j = i; j < num_cols(); j++) {
                v(j,0) = j == i ? u(j,0) + alpha : u(j,0);
                mag += v(j,0) * v(j,0);
            }

            mag = std::sqrt(mag); // norm

            if  (mag < 0.0000000001) continue;

            v /= mag;

            p = I - (bnu::prod(v, bnu::trans(v))) * 2.0;
            q = bnu::prod(q, p);
            r = bnu::prod(p, r);
        }

        Q = boost(q);
        R = boost(r);
    }
Example #3
0
void Lander::advance(bool isLeft, bool isRight, bool isDown, const Velocity & windHitGrav)
{
    //Velocity grav(0,0,0,-0.06);
    //velocity += grav;
    velocity += windHitGrav;

    if(fuel)
    {
        float dx = 0;
        float dy = 0;
        if(isLeft)
        {
            dx +=  0.25;
            fuel--;
        }
        if(isRight)
        {
            dx -=  0.25;
            fuel--;
        }
        if(isDown)
        {
            dy +=  0.25;
            fuel--;
        }
        Velocity boost(0,0,dx,dy);
        velocity += boost;
    }

    velocity++;
}
Example #4
0
 boost boost::subtract(const boost& rhs) const {\
     if(rhs.num_rows() != this->num_rows()){
         throw std::invalid_argument("Number of rows do not match");
     } else {
         return std::move(boost(this->data() - rhs.data()));
     }
 }
Example #5
0
static void*
pjlib_test_main(void* unused)
{
    int rc;

    /* Drop our priority to below that of the network stack, otherwise
     * select() tests will fail. */
    struct sched_param schedParam;
    int schedPolicy;
  
    printf("pjlib_test_main thread started..\n");

    TEST( pthread_getschedparam(pthread_self(), &schedPolicy, &schedParam) );

    schedParam.sched_priority = NETWORK_STACK_PRIORITY - 10;

    TEST( pthread_setschedparam(pthread_self(), schedPolicy, &schedParam) );

    boost();
    init_signals();

    //my_test_thread("from pjlib_test_main");
    //test_sock();

    rc = test_main();

    return (void*)rc;
}
Example #6
0
 boost boost::elem_div(const float a) const {
     if(a == 0) {
         throw std::overflow_error("Cannot divide by 0" );
     } else{
         bnu::matrix<float> result = this->data()/a;
         return std::move(boost(result));
     }
 }
Example #7
0
 boost boost::get_col(const int col_n) const {
     if(col_n < 0 || col_n >= num_cols()) {
         throw std::range_error("Column index out of bound");
     } else {
         bnu::matrix<float> column = bnu::subrange(data(), 0, num_rows(), col_n, col_n+1);
         return std::move(boost(column));
     }
 };
Example #8
0
CServerDoc::~CServerDoc()
{
	//*remoterun = false;
	//delete remote;
	stopAllServers();
	writeFile(true);
	boost(false);
}
Example #9
0
 boost boost::mult(const boost& rhs) const {
     if (rhs.num_rows() != num_cols()) {
         throw std::invalid_argument("Column of left matrix does not match row of right matrix");
     } else {
         bnu::matrix<float> prod(num_rows(), rhs.num_cols());
         bnu::noalias(prod) = bnu::prod(this->data(), rhs.data());
         return std::move(boost(prod));
     }
 }
Example #10
0
 boost boost::get_cols(const int start, const int end) const {
     if (start < 0 || end > num_cols()) {
         throw std::range_error("Column index out of bound");
         throw;
     } else if (start > end){
         throw std::invalid_argument("Start column greater than end column");
     } else {
         bnu::matrix<float> columns = bnu::subrange(data(), 0, num_rows(), start, end);
         return boost(columns);
     }
 }
Example #11
0
    boost boost::concat(const boost& mat) const {
        if (mat.num_rows() != this->num_rows()) {
            throw std::invalid_argument("Number of rows do not match");
        } else {
            int rows = this->num_rows();
            int cols = this->num_cols();
            int new_cols = cols + mat.num_cols();
            bnu::matrix<float> c(rows, new_cols);

            bnu::project(c, bnu::range(0, rows), bnu::range(0, cols)) = this->data();
            bnu::project(c, bnu::range(0, rows), bnu::range(cols, new_cols)) = mat.data();

            return std::move(boost(c));
        }
    }
Example #12
0
File: main.c Project: Jopie64/pjsip
int main(int argc, char *argv[])
{
    int rc;
    int interractive = 0;

    boost();
    init_signals();

    while (argc > 1) {
        char *arg = argv[--argc];

        if (*arg=='-' && *(arg+1)=='i') {
            interractive = 1;

        } else if (*arg=='-' && *(arg+1)=='p') {
            pj_str_t port = pj_str(argv[--argc]);

            param_echo_port = pj_strtoul(&port);

        } else if (*arg=='-' && *(arg+1)=='s') {
            param_echo_server = argv[--argc];

        } else if (*arg=='-' && *(arg+1)=='t') {
            pj_str_t type = pj_str(argv[--argc]);

            if (pj_stricmp2(&type, "tcp")==0)
                param_echo_sock_type = pj_SOCK_STREAM();
            else if (pj_stricmp2(&type, "udp")==0)
                param_echo_sock_type = pj_SOCK_DGRAM();
            else {
                PJ_LOG(3,("", "error: unknown socket type %s", type.ptr));
                return 1;
            }
        }
    }

    rc = test_main();

    if (interractive) {
        char s[10];
        puts("");
        puts("Press <ENTER> to exit");
        if (!fgets(s, sizeof(s), stdin))
            return rc;
    }

    return rc;
}
Example #13
0
int main(int argc, char *argv[])
{
    int rc;

    PJ_UNUSED_ARG(argc);
    PJ_UNUSED_ARG(argv);

    boost();
    init_signals();

    rc = test_main();

    if (argc==2 && pj_ansi_strcmp(argv[1], "-i")==0) {
	char s[10];

	puts("Press ENTER to quit");
	if (fgets(s, sizeof(s), stdin) == NULL)
	    return rc;
    }

    return rc;
}
Example #14
0
    boost boost::solve_x(const boost& B) const {
        if(this->num_rows() != this->num_cols())
            throw std::invalid_argument("A must be square in Ax = B");
        if(this->num_cols() != B.num_rows())
            throw std::invalid_argument("B.rows must equal A.cols in Ax = B");
        if(B.num_cols() != 1)
            throw std::invalid_argument("B must be n x 1 vector in Ax = B");

        bnu::matrix<float> A(this->data());
        bnu::matrix<float> y = bnu::trans(B.data());

        bnu::vector<float> b(B.num_rows());
        std::copy(y.begin1(), y.end1(), b.begin());

        bnu::permutation_matrix<> piv(b.size());
        bnu::lu_factorize(A, piv);
        bnu::lu_substitute(A, piv, b);

        bnu::matrix<float> x(this->num_rows(), 1);
        std::copy(b.begin(), b.end(), x.begin1());
        return std::move(boost(x));
    }
double EvtSemiLeptonicAmp::CalcMaxProb( EvtId parent, EvtId meson, 
					EvtId lepton, EvtId nudaug,
                     EvtSemiLeptonicFF *FormFactors ) {

  //This routine takes the arguements parent, meson, and lepton
  //number, and a form factor model, and returns a maximum
  //probability for this semileptonic form factor model.  A
  //brute force method is used.  The 2D cos theta lepton and
  //q2 phase space is probed.

  //Start by declaring a particle at rest.

  //It only makes sense to have a scalar parent.  For now. 
  //This should be generalized later.

  EvtScalarParticle *scalar_part;
  EvtParticle *root_part;

  scalar_part=new EvtScalarParticle;

  //cludge to avoid generating random numbers!
  scalar_part->noLifeTime();

  EvtVector4R p_init;
  
  p_init.set(EvtPDL::getMass(parent),0.0,0.0,0.0);
  scalar_part->init(parent,p_init);
  root_part=(EvtParticle *)scalar_part;
  root_part->setDiagonalSpinDensity();      

  EvtParticle *daughter, *lep, *trino;
  
  EvtAmp amp;

  EvtId listdaug[3];
  listdaug[0] = meson;
  listdaug[1] = lepton;
  listdaug[2] = nudaug;

  amp.init(parent,3,listdaug);

  root_part->makeDaughters(3,listdaug);
  daughter=root_part->getDaug(0);
  lep=root_part->getDaug(1);
  trino=root_part->getDaug(2);

  //cludge to avoid generating random numbers!
  daughter->noLifeTime();
  lep->noLifeTime();
  trino->noLifeTime();


  //Initial particle is unpolarized, well it is a scalar so it is 
  //trivial
  EvtSpinDensity rho;
  rho.setDiag(root_part->getSpinStates());
  
  double mass[3];
  
  double m = root_part->mass();
  
  EvtVector4R p4meson, p4lepton, p4nu, p4w;
  double q2min;
  double q2max;

  double q2, elepton, plepton;
  int i,j;
  double erho,prho,costl;

  double maxfoundprob = 0.0;
  double prob = -10.0;
  int massiter;

  for (massiter=0;massiter<3;massiter++){

    mass[0] = EvtPDL::getMeanMass(meson);
    mass[1] = EvtPDL::getMeanMass(lepton);
    mass[2] = EvtPDL::getMeanMass(nudaug);
    if ( massiter==1 ) {
      mass[0] = EvtPDL::getMinMass(meson);
    }
    if ( massiter==2 ) {
      mass[0] = EvtPDL::getMaxMass(meson);
      if ( (mass[0]+mass[1]+mass[2])>m) mass[0]=m-mass[1]-mass[2]-0.00001; 
    }

    q2min = mass[1]*mass[1];
    q2max = (m-mass[0])*(m-mass[0]);
    
    //loop over q2

    for (i=0;i<25;i++) {
      q2 = q2min + ((i+0.5)*(q2max-q2min))/25.0;
      
      erho = ( m*m + mass[0]*mass[0] - q2 )/(2.0*m);
      
      prho = sqrt(erho*erho-mass[0]*mass[0]);
      
      p4meson.set(erho,0.0,0.0,-1.0*prho);
      p4w.set(m-erho,0.0,0.0,prho);
      
      //This is in the W rest frame
      elepton = (q2+mass[1]*mass[1])/(2.0*sqrt(q2));
      plepton = sqrt(elepton*elepton-mass[1]*mass[1]);
      
      double probctl[3];

      for (j=0;j<3;j++) {
	
        costl = 0.99*(j - 1.0);
	
	//These are in the W rest frame. Need to boost out into
	//the B frame.
        p4lepton.set(elepton,0.0,
		  plepton*sqrt(1.0-costl*costl),plepton*costl);
        p4nu.set(plepton,0.0,
		 -1.0*plepton*sqrt(1.0-costl*costl),-1.0*plepton*costl);

	EvtVector4R boost((m-erho),0.0,0.0,1.0*prho);
        p4lepton=boostTo(p4lepton,boost);
        p4nu=boostTo(p4nu,boost);

	//Now initialize the daughters...

        daughter->init(meson,p4meson);
        lep->init(lepton,p4lepton);
        trino->init(nudaug,p4nu);

        CalcAmp(root_part,amp,FormFactors);

	//Now find the probability at this q2 and cos theta lepton point
        //and compare to maxfoundprob.

	//Do a little magic to get the probability!!
	prob = rho.normalizedProb(amp.getSpinDensity());

	probctl[j]=prob;
      }

      //probclt contains prob at ctl=-1,0,1.
      //prob=a+b*ctl+c*ctl^2

      double a=probctl[1];
      double b=0.5*(probctl[2]-probctl[0]);
      double c=0.5*(probctl[2]+probctl[0])-probctl[1];

      prob=probctl[0];
      if (probctl[1]>prob) prob=probctl[1];
      if (probctl[2]>prob) prob=probctl[2];

      if (fabs(c)>1e-20){
	double ctlx=-0.5*b/c;
	if (fabs(ctlx)<1.0){
	  double probtmp=a+b*ctlx+c*ctlx*ctlx;
	  if (probtmp>prob) prob=probtmp;
	} 

      }

      if ( prob > maxfoundprob ) {
	maxfoundprob = prob; 
      }

    }
    if ( EvtPDL::getWidth(meson) <= 0.0 ) {
      //if the particle is narrow dont bother with changing the mass.
      massiter = 4;
    }

  }
  root_part->deleteTree();  

  maxfoundprob *=1.1;
  return maxfoundprob;
  
}
Example #16
0
void StageRing::update() {
  if (p_booster->isCollisionToPlayer()) { isBoost = true; }
  boost();
  loop();
}
Example #17
0
void acceptance(const char* file = "upsilonGun.root", const char* outputName = "acceptance.root") {
  Int_t genUpsSize;
  Float_t genUpsPt[NMAX];
  Float_t genUpsEta[NMAX];
  Float_t genUpsPhi[NMAX];
  Float_t genUpsRapidity[NMAX];
  Int_t genMuSize;
  Float_t genMuPt[NMAX];
  Float_t genMuEta[NMAX];
  Float_t genMuPhi[NMAX];
  Int_t genMuCharge[NMAX];
  Int_t recoMuSize;
  Float_t recoMuPt[NMAX];
  Float_t recoMuEta[NMAX];
  Float_t recoMuPhi[NMAX];
  Int_t recoMuCharge[NMAX];

  TFile* f1 = new TFile(file);
  TTree* t = (TTree*)f1->Get("UpsTree");
  t->SetBranchAddress("genUpsSize",&genUpsSize);
  t->SetBranchAddress("genUpsPt",genUpsPt);
  t->SetBranchAddress("genUpsEta",genUpsEta);
  t->SetBranchAddress("genUpsPhi",genUpsPhi);
  t->SetBranchAddress("genUpsRapidity",genUpsRapidity);
  t->SetBranchAddress("genMuSize",&genMuSize);
  t->SetBranchAddress("genMuPt",genMuPt);
  t->SetBranchAddress("genMuEta",genMuEta);
  t->SetBranchAddress("genMuPhi",genMuPhi);
  t->SetBranchAddress("genMuCharge",genMuCharge);
  t->SetBranchAddress("recoMuSize",&recoMuSize);
  t->SetBranchAddress("recoMuPt",recoMuPt);
  t->SetBranchAddress("recoMuEta",recoMuEta);
  t->SetBranchAddress("recoMuPhi",recoMuPhi);
  t->SetBranchAddress("recoMuCharge",recoMuCharge);

  TH2F* genPtRap = new TH2F("genUps","",4,0,20,4,-2,2);
  TH1F* genPt = new TH1F("genUps1D","",4,0,20);
  genPtRap->Sumw2();
  genPt->Sumw2();
  genPtRap->SetTitle(";Upsilon pT (GeV/c);Upsilon Rapidity;");
  genPt->SetTitle(";Upsilon pT (GeV/c);Acceptance;");
  TH2F* recoPtRap = (TH2F*)genPtRap->Clone("recoUps");
  TH1F* recoPt = (TH1F*)genPt->Clone("recoUps1D");
  recoPtRap->Sumw2();
  recoPt->Sumw2();

  for(int i=0; i<t->GetEntries(); i++){
    if(i%100000 == 0)
      std::cout<<i<<std::endl;
    t->GetEntry(i);

    // calculate cosTheta
    TLorentzVector genUps; genUps.SetPtEtaPhiM(genUpsPt[0], genUpsEta[0], genUpsPhi[0], 9.46);
    TLorentzRotation boost(-genUps.BoostVector());
    int mp = genMuCharge[0]>0 ? 0 : 1;
    TLorentzVector genMuPlus; genMuPlus.SetPtEtaPhiM(genMuPt[mp], genMuEta[mp], genMuPhi[mp], 0.106);
    genMuPlus *= boost;
    Float_t cosThetaStar = genMuPlus.Vect().Dot(genUps.Vect())/genMuPlus.Vect().Mag()/genUps.Vect().Mag();

    // set the weight
    Float_t weight = 1;

    genPtRap->Fill( genUpsPt[0], genUpsRapidity[0], weight );
    genPt->Fill( genUpsPt[0], weight );

    Float_t recoUpsPt = 0;
    Float_t recoUpsRapidity = 0;
    double minDeltaM = 1000;
    for(int tr1=0; tr1<recoMuSize; tr1++){
      for(int tr2=tr1+1; tr2<recoMuSize; tr2++){
        if ( recoMuCharge[tr1]*recoMuCharge[tr2] == -1 && recoMuPt[tr1] >= 3.5 && recoMuPt[tr2] >= 3.5 && fabs(recoMuEta[tr1]) < 2.1 && fabs(recoMuEta[tr2]) < 2.1 ){
          TLorentzVector mu1; mu1.SetPtEtaPhiM(recoMuPt[tr1], recoMuEta[tr1], recoMuPhi[tr1], 0.106);
          TLorentzVector mu2; mu2.SetPtEtaPhiM(recoMuPt[tr2], recoMuEta[tr2], recoMuPhi[tr2], 0.106);
          TLorentzVector recoUps(mu1 + mu2);
          double deltaM = fabs(recoUps.M()-9.46);
          if( deltaM < minDeltaM ){
            recoUpsPt = recoUps.Pt();
            recoUpsRapidity = recoUps.Rapidity();
            minDeltaM = deltaM;
          }
        }
      }
    }
    if( minDeltaM < 1.0 ){
      recoPtRap->Fill( recoUpsPt, recoUpsRapidity, weight );
      recoPt->Fill( recoUpsPt, weight );
    }
  }

  TFile out(outputName,"recreate");
  TH2F* acc = (TH2F*)genPtRap->Clone("acceptance");
  TH1F* acc1D = (TH1F*)genPt->Clone("acceptance1D");
  acc->Sumw2();
  acc1D->Sumw2();
  acc->Divide(recoPtRap,genPtRap,1,1,"B");
  acc1D->Divide(recoPt,genPt,1,1,"B");
  acc->Write();
  acc1D->Write();
  out.Close();
}
Example #18
0
BOOL CServerDoc::OnNewDocument()
{
	stopAllServers();
	m_Servers.RemoveAll();
	if (!CDocument::OnNewDocument())
		return FALSE;
	
	SetTitle("Servers");

	char    szAppPath[MAX_PATH] = "";
	CString strAppDirectory;

	::GetModuleFileName(0, szAppPath, sizeof(szAppPath) - 1);

	strAppDirectory = szAppPath;
	strAppDirectory = strAppDirectory.Left(strAppDirectory.ReverseFind('\\'));
	
	strAppDirectory += "\\servers.sch";

	bool prevversion = false;
	try // deserializing
	{
		CFile f(strAppDirectory,CFile::modeRead);
		CArchive ar(&f,CArchive::load);
	
		ServerControl* sc;
		int nr;
		ar >> nr;
		for (int i = 0; i <= nr; i++)
		{
			sc = (ServerControl*)ar.ReadObject(RUNTIME_CLASS(ServerControl));
			m_Servers.Add(sc);
		}
		prevversion = true;

		int tmp;
		ar >> tmp;
		pingboostervalue = (UINT)tmp;
		ar >> tmp;
		bool b = (bool)tmp;
		boost(b);
	}
	catch(CException* ex)
	{
		if (!prevversion)
		{
			ex->ReportError();
			MessageBox(NULL,"Error loading servers from file","Error...",MB_OK | MB_SYSTEMMODAL |MB_ICONEXCLAMATION);
			m_Servers.RemoveAll();
		}
	}
	/*remoterun = new bool;
	*remoterun = true;
	try
	{
		remote = new CRemote(this,remoterun);
		HANDLE threadhandle = CreateThread(NULL,0,&runremote,(void*)remote,0,NULL);
		remote->setThreadHandle(threadhandle);
	}
	catch (char* ex)
	{
		MessageBox(NULL,ex,"error",MB_OK | MB_ICONEXCLAMATION);
	}	*/
	return TRUE;
}
Example #19
0
void
pcmproc(void*)
{
	Pmsg localstate, newstate, prevstate;
	int fd, n;
	Pacbuf *pb, *b;
	Alt a[3] = {
		{full, &pb, CHANRCV},
		{playout, &pb, CHANRCV},
		{nil, nil, CHANEND},
	};

	/*
	 * This is the real-time proc.
	 * It gets its input from two sources, full data/control buffers from the decproc
	 * which mixes decoded data with control messages, and data buffers from the pcmproc's
	 * (*this* proc's) own internal playout buffer.
	 * When a command is received on the `full' channel containing a command that warrants
	 * an immediate change of audio source (e.g., to silence or to another number), we just
	 * toss everything in the pipeline -- i.e., the playout channel
	 * Finally, we report all state changes using `playupdate' (another message channel)
	 */
	threadsetname("pcmproc");
	close(srvfd[1]);
	fd = -1;
	localstate.cmd = 0;	/* Force initial playupdate */
	newstate.cmd = Stop;
	newstate.off = 0;
//	rtsched();
	boost();
	for(;;){
		if(newstate.m != localstate.m){
			playupdate(newstate, nil);
			localstate = newstate;
		}
		switch(alt(a)){
		case 0:
			/* buffer received from decproc */
			if((debug & DbgPcm) && localstate.m != prevstate.m){
				fprint(2, "pcm, full: %s-%d, local state is %s-%d\n",
					statetxt[pb->cmd], pb->off,
					statetxt[localstate.cmd], localstate.off);
				prevstate.m = localstate.m;
			}
			switch(pb->cmd){
			default:
				sysfatal("pcmproc: unknown newstate: %s-%d", statetxt[pb->cmd], pb->off);
			case Resume:
				a[1].op = CHANRCV;
				newstate.cmd = Play;
				break;
			case Pause:
				a[1].op = CHANNOP;
				newstate.cmd = Pause;
				if(fd >= 0){
					close(fd);
					fd = -1;
				}
				break;
			case Stop:
				/* Dump all data in the buffer */
				while(b = nbrecvp(playout))
					if(b->cmd == Error){
						playupdate(b->Pmsg, b->data);
						sendp(spare, b);
					}else
						sendp(empty, b);
				newstate.m = pb->m;
				a[1].op = CHANRCV;
				if(fd >= 0){
					close(fd);
					fd = -1;
				}
				break;
			case Skip:
				/* Dump all data in the buffer, then fall through */
				while(b = nbrecvp(playout))
					if(b->cmd == Error){
						playupdate(pb->Pmsg, pb->data);
						sendp(spare, pb);
					}else
						sendp(empty, b);
				a[1].op = CHANRCV;
				newstate.cmd = Play;
			case Error:
			case Play:
				/* deal with at playout, just requeue */
				sendp(playout, pb);
				pb = nil;
				localstate = newstate;
				break;
			}
			/* If we still have a buffer, free it */
			if(pb)
				sendp(spare, pb);
			break;
		case 1:
			/* internal buffer */
			if((debug & DbgPlayer) && localstate.m != prevstate.m){
				fprint(2, "pcm, playout: %s-%d, local state is %s-%d\n",
					statetxt[pb->cmd], pb->off,
					statetxt[localstate.cmd], localstate.off);
				prevstate.m = localstate.m;
			}
			switch(pb->cmd){
			default:
				sysfatal("pcmproc: unknown newstate: %s-%d", statetxt[pb->cmd], pb->off);
			case Error:
				playupdate(pb->Pmsg, pb->data);
				localstate = newstate;
				sendp(spare, pb);
				break;
			case Play:
				if(fd < 0 && (fd = open("/dev/audio", OWRITE)) < 0){
					a[1].op = CHANNOP;
					newstate.cmd = Pause;
					pb->cmd = Error;
					snprint(pb->data, sizeof(pb->data),
						"/dev/audio: %r");
					playupdate(pb->Pmsg, pb->data);
					sendp(empty, pb);
					break;
				}
				/* play out this buffer */
				totbytes += pb->len;
				totbuffers++;
				n = write(fd, pb->data, pb->len);
				if (n != pb->len){
					if (debug & DbgPlayer)
						fprint(2, "pcmproc: file %d: %r\n", pb->off);
					if (n < 0)
						sysfatal("pcmproc: write: %r");
				}
				newstate.m = pb->m;
				sendp(empty, pb);
				break;
			}
			break;
		}
	}
}
Example #20
0
void ThreeBodyDecay(Particle *PParent, Particle *PChild1, Particle *PChild2,
		    Particle *PChild3, ParticlePropertyList *PPList,
		    Decay *PDecay)
{
  int i;
  double mp, md[3], Ed1, Ed2, Ed3, pd1, pd3, E12;
  double m12, m13, t1, e1s, e3s;
  double m12lo, m12hi, m13lo, m13hi, m13max, m13min;
  double costheta, sintheta, phi, sinphi, cosphi;

  int new_generation;
 
  mp=GetMass(PParent->GetID(),PPList); 
  
  for ( i=1; i<=3; i++)
  {
    md[i-1] = GetMass(PDecay->GetChildID(i),PPList);
  }

  m12lo = SQR(md[0]+md[1]);
  m12hi = SQR(mp-md[2]);
  m13lo = SQR(md[0]+md[2]);
  m13hi = SQR(mp-md[1]);
  
  for ( ; ; )
  {
    m12 = sqrt(m12lo+(m12hi-m12lo)*gRandom->Rndm());
    m13 = sqrt(m13lo+(m13hi-m13lo)*gRandom->Rndm());
    e1s = (m12*m12+md[0]*md[0]-md[1]*md[1])/(2.0*m12);
    e3s = (mp*mp-m12*m12-md[2]*md[2])/(2.0*m12);
      
    t1 = e1s*e1s-md[0]*md[0];
    if ( t1<0 ) continue;
      
    m13max = sqrt(SQR(e1s+e3s)-SQR(sqrt(t1)-sqrt(SQR(e3s)-SQR(md[2]))));
    m13min = sqrt(SQR(e1s+e3s)-SQR(sqrt(t1)+sqrt(SQR(e3s)-SQR(md[2]))));
      
    if( m13<=m13max && m13>=m13min ) break;
  }
  
  Ed3 = (SQR(mp)+SQR(md[2])-SQR(m12))/(2.0*mp);
  pd3 = sqrt((Ed3+md[2])*(Ed3-md[2]));
  
  costheta = 2.0*gRandom->Rndm()-1.;
  sintheta = sqrt((1.+costheta)*(1.-costheta));
  phi      = 2.0*PI*gRandom->Rndm();
  sinphi   = sin(phi);
  cosphi   = cos(phi);

  PChild1->SetID(PDecay->GetChildID(1));
  PChild2->SetID(PDecay->GetChildID(2));
  PChild3->SetID(PDecay->GetChildID(3));
  
  new_generation = PParent->GetGeneration()+1;
  PChild1->SetGeneration(new_generation);
  PChild2->SetGeneration(new_generation);
  PChild3->SetGeneration(new_generation);

  PChild1->SetDecaysum(0.0);
  PChild2->SetDecaysum(0.0);
  PChild3->SetDecaysum(0.0);

  PChild3->Set4mom(Ed3,pd3*sintheta*cosphi,pd3*sintheta*sinphi,pd3*costheta);
   
  Ed1      = (m12*m12+md[0]*md[0]-md[1]*md[1])/(2.*m12);
  Ed2      = m12-Ed1;
  pd1      = sqrt((Ed1+md[0])*(Ed1-md[0]));
  costheta = 2.0*gRandom->Rndm()-1.0;
  sintheta = sqrt((1.-costheta)*(1.+costheta));
  phi      = 2.0*PI*gRandom->Rndm();
  
  PChild1->Set4mom(Ed1,
		   pd1*sintheta*cos(phi), 
		   pd1*sintheta*sin(phi), 
		   pd1*costheta);
  PChild2->Set4mom(sqrt(SQR(PChild1->Get4mom().Getp())+SQR(md[1])),
		   invert(PChild1->Get4mom().Getp()));
    
  E12 = sqrt(SQR(pd3)+SQR(m12));
  Mom4 p4boost(E12,invert(PChild3->Get4mom().Getp()));

  PChild1->Set4mom(boost(PChild1->Get4mom(),p4boost));
  PChild2->Set4mom(boost(PChild2->Get4mom(),p4boost));

  PChild1->Set4mom(boost(PChild1->Get4mom(),PParent->Get4mom()));
  PChild2->Set4mom(boost(PChild2->Get4mom(),PParent->Get4mom()));
  PChild3->Set4mom(boost(PChild3->Get4mom(),PParent->Get4mom()));

  return;

}
Example #21
0
void TwoBodyDecay(Particle *PParent, Particle *PChild1, Particle *PChild2,
			    ParticlePropertyList * PPList, Decay *PDecay)
{
  Mom4   mom4;
  double wp, mp, md1, md2, Ed1, Ed2, pd1, pd2;
  double costheta, sintheta, theta, cosphi,sinphi, phi;

  int new_generation;

  wp  = GetWidth(PDecay->GetParentID(),PPList);
  if ( wp==0.0 )
    {
      mp = GetMass(PDecay->GetParentID(),PPList);
    }
  else
    {
      mp = sqrt(SQR(PParent->Get4mom()));
    }
  md1 = GetMass(PDecay->GetChildID(1),PPList);
  md2 = GetMass(PDecay->GetChildID(2),PPList);

  if ( mp<md1+md2 )
  {
    //cout << "Decay kinematically impossible for particle " 
    //	 << PDecay->GetParentID() << "!" << endl;
    return;
  }

  Ed1 = (SQR(mp)+SQR(md1)-SQR(md2))/(2.*mp);
  Ed2 = mp-Ed1;
  pd1 = sqrt((Ed1+md1)*(Ed1-md1));
  pd2 = sqrt((SQR(mp)-SQR(md1+md2))*(SQR(mp)-SQR(md1-md2)))/(2.*mp);
    
  costheta = (2.0*gRandom->Rndm())-1.0;
  sintheta = sqrt((1.+costheta)*(1.-costheta));
  phi      = 2.0*PI*gRandom->Rndm();

  PChild1->SetID(PDecay->GetChildID(1));
  PChild2->SetID(PDecay->GetChildID(2));

  new_generation = PParent->GetGeneration()+1;
  PChild1->SetGeneration(new_generation);
  PChild2->SetGeneration(new_generation);

  PChild1->SetDecaysum(0.0);
  PChild2->SetDecaysum(0.0);

  PChild1->Set4mom(Ed1,
		   pd1*sintheta*cos(phi), 
		   pd1*sintheta*sin(phi), 
		   pd1*costheta);
  PChild2->Set4mom(Ed2,invert(PChild1->Get4mom().Getp()));

  theta    = thetaof(PParent->Get4mom().Getp());
  phi      = phiof(PParent->Get4mom().Getp());
  costheta = cos(theta); 
  sintheta = sin(theta);
  cosphi   = cos(phi); 
  sinphi   = sin(phi);
  
  PChild1->Set4mom(Ed1,
    Rotate(PChild1->Get4mom().Getp(),costheta,sintheta,cosphi,sinphi));
  PChild2->Set4mom(Ed2,
    Rotate(PChild2->Get4mom().Getp(),costheta,sintheta,cosphi,sinphi));
  
  PChild1->Set4mom(boost(PChild1->Get4mom(),PParent->Get4mom()));
  PChild2->Set4mom(boost(PChild2->Get4mom(),PParent->Get4mom()));
  
  return;

}
//走行状態設定関数
void RN_setting()
{

	static int wait_count = 0;

	switch (setting_mode){

			//キャリブレーション状態
		case (RN_START):
			RN_calibrate();
			break;
		
			//対戦中
		case (RN_RUN):
			(void)ecrobot_read_bt_packet(bt_receive_buf, BT_RCV_BUF_SIZE);	/* スティック入力 */
			
			cmd_forward = -((S8)bt_receive_buf[0])/2;	/* 前進量(そのままでは早すぎるので値を半分) */
			cmd_turn = ((S8)bt_receive_buf[1]);			/* 旋回量 */
			
			//ターボチェック
			if(boost() == 1)
			{
				setting_mode = RN_BOOST;
				ecrobot_sound_tone(980,512,100);
			}

			else /* ターボ無し、スティック操作 */
			{
				nxt_motor_set_speed(NXT_PORT_C, cmd_forward + cmd_turn/2, 1);
				nxt_motor_set_speed(NXT_PORT_B, cmd_forward - cmd_turn/2, 1);
			}

			if(ecrobot_get_touch_sensor(NXT_PORT_S4) == 1)	/* ヒットチェック */
			{
				ecrobot_sound_tone(980,512,100);
				nxt_motor_set_speed(NXT_PORT_C,100,1);
				nxt_motor_set_speed(NXT_PORT_B,-100,1);
				wait_count = 0;
				setting_mode = RN_PUSHBUTTON;
			}
			
			break;

			//ターボ動作(ver 2.0新機能)
		case (RN_BOOST):
			wait_count++;

			/* 両車輪にモータ操作量の最大値を送信(スティック操作不可) */
			nxt_motor_set_speed(NXT_PORT_C,127,1);
			nxt_motor_set_speed(NXT_PORT_B,127,1);

			/* 1秒後に通常モードに復帰 */
			if(wait_count > 125)
			{
				setting_mode = RN_RUN;
				wait_count = 0;
			}
			break;

			//敗北動作
		case (RN_PUSHBUTTON):
			wait_count++;

			if(wait_count >= 150)
			{
				TailAngleChange(ANGLEOFZERO);
				nxt_motor_set_speed(NXT_PORT_C,0,1);
				nxt_motor_set_speed(NXT_PORT_B,0,1);
			}

			if(wait_count == 1000)
				setting_mode = RN_START;

			break;

		default:
			break;
	}
}
/* ---------------------------------------------------------------- space --- */
static int
space(float dim[],          /* first 4 args: arrays of 2 elements */
      float source[],
      float warp1[],
      float warp2[],
      float dec,
      float rndval)
{
   int    i;
   double pow1, pow2, pow3, pow4, rval, xval, x;
   float  rndseed, bounce[NTAPS][2];
   float  xxx, xlist[2];

   rndseed = (rndval == 0.0) ? 0.3 : rndval;

   pow1 = log((double)warp1[0]) / log(0.5);
   pow2 = log((double)warp1[1]) / log(0.5);
   pow3 = log((double)warp2[0]) / log(0.5);
   pow4 = log((double)warp2[1]) / log(0.5);

   for (i = 0; i < 2; i++) {
      source[i] *= dim[i];
      x = (double)i / 2.0;

      rval = ((double)rind(0.5, &rndseed) + 0.5) / 2.0 + x;
      xval = exp(log(rval) / pow1);
      bounce[i][0] = (float)rval;
      bounce[i][1] = (float)pow(xval, pow2);

      rval = ((double)rind(0.5, &rndseed) + 0.5) / 2.0 + x;
      xval = exp(log(rval) / pow3);
      bounce[i + 4][0] = (float)rval;
      bounce[i + 4][1] = (float)pow(xval, pow4);

      rval = ((double)rind(0.5, &rndseed) + 0.5) / 2.0 + x;
      xval = exp(log(rval) / pow2);
      bounce[i + 2][1] = (float)rval;
      bounce[i + 2][0] = (float)pow(xval, pow1);

      rval = ((double)rind(0.5, &rndseed) + 0.5) / 2.0 + x;
      xval = exp(log(rval) / pow4);
      bounce[i + 6][1] = (float)rval;
      bounce[i + 6][0] = (float)pow(xval, pow3);

      bounce[i + 8][0] = (rind(0.5, &rndseed) + 0.5) / 2.0 + x;
      bounce[i + 10][0] = (rind(0.5, &rndseed) + 0.5) / 2.0 + x;
      bounce[i + 8][1] = bounce[i + 10][1] = 0.0;

      bounce[NTAPS - 1][i] = source[i];
   }

   for (i = 0; i < 4; i++) {
      bounce[i][0] *= (0.5 * dim[0]);
      bounce[i][1] *= dim[1];
      bounce[i + 4][0] = (1.0 - bounce[i + 4][0] * 0.5) * dim[0];
      bounce[i + 4][1] *= dim[1];
   }
   for (i = 8; i < 10; i++) {
      bounce[i][0] *= 0.5 * dim[0];
      bounce[i + 2][0] = (1.0 - bounce[i + 2][0] * 0.5) * dim[0];
   }

   xlist[0] = 0.5 * dim[0];
   xlist[1] = 0.0;
   bounce[NTAPS - 1][0] = source[0];
   bounce[NTAPS - 1][1] = source[1];

   xxx = 0;
   for (i = 0; i < NTAPS; i++) {
      float d, s, a;
      specs(source, &bounce[i][0], xlist, dec, &d, &s, &a);
      delay[i] = d;
      sloc[i] = s;
      amp[i] = a * boost(s);
      xxx += amp[i];
   }
   printf(" x-loc   y-loc   delay    sloc     amp\n");
   for (i = 0; i < NTAPS; i++) {
      amp[i] /= xxx;
      delay[i] -= delay[NTAPS - 1];
      printf("%7.2f %7.2f  %6.5f  %6.5f  %6.5f\n",
             bounce[i][0], bounce[i][1], delay[i], sloc[i], amp[i]);
   }

   return 0;
}
void UpsilonMassFit_PolWeights(int iSpec = 3, int PutWeight=1)
{

  double PtCut=4;

  //minbias integrated, |y|<1.2 and |y|\in[1.2,2.4], centrality [0,10][10,20][20,100]%,  pt [0,6.5], [6.5, 10] [10,20]

  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameFillColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadBorderSize(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetOptTitle(1); // at least most of the time
  gStyle->SetOptStat(1); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(1); // set to 1 only if you want to display fit results

  //==================================== Define Histograms====================================================
  ofstream dataFile(Form("Eff_Upsilon.txt"));
  
  TH1D *diMuonsInvMass_Gen = new TH1D("diMuonsInvMass_Gen","diMuonsInvMass_Gen", 100,8.0,12.0);
  TH1D *diMuonsPt_Gen = new TH1D("diMuonsPt_Gen","diMuonsPt_Gen", 100,0,30);
  //Rapidity Gen
  TH1D *diMuonsRap_Gen0 = new TH1D("diMuonsRap_Gen0","diMuonsRap_Gen0", 100,-5,5);
  TH1D *diMuonsRap_Gen1 = new TH1D("diMuonsRap_Gen1","diMuonsRap_Gen1", 100,-5,5);
  TH1D *diMuonsRap_Gen2 = new TH1D("diMuonsRap_Gen2","diMuonsRap_Gen2", 100,-5,5);
  TH1D *diMuonsRap_Gen3 = new TH1D("diMuonsRap_Gen3","diMuonsRap_Gen3", 100,-5,5);
  TH1D *diMuonsRap_Gen4 = new TH1D("diMuonsRap_Gen4","diMuonsRap_Gen4", 100,-5,5);
  TH1D *diMuonsRap_Gen5 = new TH1D("diMuonsRap_Gen5","diMuonsRap_Gen5", 100,-5,5);
  ////Rapidity Reco
  TH1D *diMuonsRap_Rec0 = new TH1D("diMuonsRap_Rec0","diMuonsRap_Rec0", 100,-5,5);
  diMuonsRap_Rec0->SetLineColor(2);
  TH1D *diMuonsRap_Rec1 = new TH1D("diMuonsRap_Rec1","diMuonsRap_Rec1", 100,-5,5);
  diMuonsRap_Rec1->SetLineColor(2);
  TH1D *diMuonsRap_Rec2 = new TH1D("diMuonsRap_Rec2","diMuonsRap_Rec2", 100,-5,5);
  diMuonsRap_Rec2->SetLineColor(2);
  TH1D *diMuonsRap_Rec3 = new TH1D("diMuonsRap_Rec3","diMuonsRap_Rec3", 100,-5,5);
  diMuonsRap_Rec3->SetLineColor(2);
  TH1D *diMuonsRap_Rec4 = new TH1D("diMuonsRap_Rec4","diMuonsRap_Rec4", 100,-5,5);
  diMuonsRap_Rec4->SetLineColor(2);
  TH1D *diMuonsRap_Rec5 = new TH1D("diMuonsRap_Rec5","diMuonsRap_Rec5", 100,-5,5);
  diMuonsRap_Rec5->SetLineColor(2);
  TH1D *Bin_Gen = new TH1D("Bin_Gen","Bin_Gen", 40,0,40);

  //==============================================Define AccEff Stuff here===========================================
  // Pt bin sizes
  int Nptbin=1;
  double pt_bound[100] = {0};
  if(iSpec == 1) { 
    Nptbin = 5;
    pt_bound[0] = 0;
    pt_bound[1] = 20.0;
    pt_bound[2] = 0.0;
    pt_bound[3] = 6.5;
    pt_bound[4] = 10.0;
    pt_bound[5] = 20.0;
   

    pt_bound[6] = 30.0;
    pt_bound[7] = 35;
    pt_bound[8] = 40;
    pt_bound[9] = 45;
    pt_bound[10] = 50;
  }
  
  if(iSpec == 2) { 
    Nptbin = 2;
    pt_bound[0] = 0.0; 
    pt_bound[1] = 1.2; 
    pt_bound[2] = 2.4; 
    
    pt_bound[3] = 0.0; 
    pt_bound[4] = 0.8; 
    pt_bound[5] = 1.8; 
    //pt_bound[7] = 2.0; 
    pt_bound[6] = 2.4; 
  
  }
  
  
  if(iSpec == 3) {
    Nptbin = 3;
    //for plots
    pt_bound[0] = 0.0;//0
    pt_bound[1] = 4.0;//10
    pt_bound[2] = 8.0;//20
    pt_bound[3] = 40.0;//100
   

    //pt_bound[4] = 16.0;//50
    //pt_bound[5] = 20.0;//100
    //pt_bound[6] = 24.0;
    //pt_bound[7] = 32.0;
    //pt_bound[8] = 40.0;
    //pt_bound[9] = 40.0;
  }
  //X Axis error on Eff graph 
  double PT[100], DelPT[100], mom_err[100];
  for (Int_t ih = 0; ih < Nptbin; ih++) {
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = pt_bound[ih+1] - pt_bound[ih];
    mom_err[ih] = DelPT[ih]/2.0;
  }
  
  double genError, recError;
  double gen_pt[100]={0}, gen_ptError[100]={0}; 
  double rec_pt[100]={0}, rec_ptError[100]={0}; 
  double Eff_cat_1[100]={0},Err_Eff_cat_1[100]={0};  
  
  // Histogram arrays
  TH1D *diMuonsInvMass_GenA[10][1000];
  TH1D *diMuonsInvMass_RecA[10][1000];
  TH1D *diMuonsPt_GenA[10][1000];
  TH1D *diMuonsPt_RecA[10][1000];
  char nameGen[10][500], nameRec[10][500], nameGenPt[10][500], nameRecPt[10][500];
 
  
  for (int ifile = 0; ifile <= 5; ifile++) {
    for (Int_t ih = 0; ih < Nptbin; ih++) {
      sprintf(nameGen[ifile],"DiMuonMassGen_pt_%d_%d",ih,ifile);
      sprintf(nameRec[ifile],"DiMuonMassRec_pt_%d_%d",ih,ifile);

      sprintf(nameGenPt[ifile],"DiMuonPtGen_pt_%d_%d",ih,ifile);
      sprintf(nameRecPt[ifile],"DiMuonPtRec_pt_%d_%d",ih,ifile);
      
      diMuonsInvMass_GenA[ifile][ih]= new TH1D(nameGen[ifile],nameGen[ifile],  100,8.0,12.0); //for eff Gen;
      diMuonsInvMass_GenA[ifile][ih]->Sumw2();
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerStyle(7);
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_GenA[ifile][ih]->SetLineColor(4);

      diMuonsInvMass_RecA[ifile][ih] = new TH1D(nameRec[ifile],nameRec[ifile], 100,8.0,12.0); //for eff Rec;
      diMuonsInvMass_RecA[ifile][ih]->Sumw2();
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerStyle(8);
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_RecA[ifile][ih]->SetLineColor(4);


      diMuonsPt_GenA[ifile][ih]= new TH1D(nameGenPt[ifile],nameGenPt[ifile],  100,0,40); //for eff Gen;
      diMuonsPt_RecA[ifile][ih]= new TH1D(nameRecPt[ifile],nameRecPt[ifile],  100,0,40); //for eff Rec;
    }
  }
  
  //===========================================Input Root File============================================================
  char fileName[10][500];
  //0.0380228 	0.0480769 	0.0293255 	0.0125156 	0.00336587 	0.00276319*2/5 = 0.001105276
  //Scales
  double scale[10]={0};  
  scale[0]=(6.8802); // pT [0-3]
  scale[1]=(8.6995); // pT [3-6]
  scale[2]=(5.3065); // pT [6-9]
  scale[3]=(2.2647); // pT [9-12] 
  scale[4]=(3.0453); // pT [12-15] 
  scale[5]=(1.0000); // pT [15-30]
  
  sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03_N.root");
  sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36_N.root");
  sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69_N.root");
  sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912_N.root");
  sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215_N.root");
  sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530_N.root");



  //double scale[10]={0};  
  //scale[0]=(0.0380228/0.001105276);
  //scale[1]=(0.0480769/0.001105276);
  //scale[2]=(0.0293255/0.001105276);
  //scale[3]=(0.0125156/0.001105276);
  //scale[4]=(0.00336587/0.001105276);
  //scale[5]=(0.001105276/0.001105276);
   //34.55 , 43.70 , 26.65 , 11.37 , 3.05 , 1
  //sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03.root");
  //sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36.root");
  //sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69.root");
  //sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912.root");
  //sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215.root");
  //sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530.root");
  
  TFile *infile;
  TTree *tree;
  TTree *gentree;
  
  //===========File loop ======================
  
  for(int ifile =0; ifile<=5; ifile++){
    
    infile=new TFile(fileName[ifile],"R");
    tree=(TTree*)infile->Get("SingleMuonTree");
    gentree=(TTree*)infile->Get("SingleGenMuonTree");
    
    //Event variables
    int eventNb,runNb,lumiBlock, gbin, rbin;
    //Jpsi Variables
    Double_t JpsiMass,JpsiPt,JpsiPx,JpsiPy,JpsiPz,JpsiRap, JpsiCharge,JpsiE;
    Double_t JpsiVprob;
    //2.) muon variables RECO                                                                       
    double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt,muPosP,muPosPhi;
    double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt,muNegP,muNegPhi;
    //(1).Positive Muon                                     
    double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
    int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
    bool muPos_matches,muPos_tracker;
    //(2).Negative Muon                                     
    double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
    int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
    bool muNeg_matches,muNeg_tracker;
    //Gen Level variables
    //Gen JPsi Variables
    double GenJpsiMass, GenJpsiPt, GenJpsiRap;
    double GenJpsiPx, GenJpsiPy, GenJpsiPz, GenJpsiE;
   
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;

    //Event variables
    tree->SetBranchAddress("eventNb",&eventNb);
    tree->SetBranchAddress("runNb",&runNb);
    tree->SetBranchAddress("lumiBlock",&lumiBlock);
    
    //Jpsi Variables
    tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
    tree->SetBranchAddress("JpsiMass",&JpsiMass);
    tree->SetBranchAddress("JpsiPt",&JpsiPt);
    tree->SetBranchAddress("JpsiPx",&JpsiPx);
    tree->SetBranchAddress("JpsiPy",&JpsiPy);
    tree->SetBranchAddress("JpsiPz",&JpsiPz);
    tree->SetBranchAddress("JpsiRap",&JpsiRap);
    tree->SetBranchAddress("JpsiVprob",&JpsiVprob);
    tree->SetBranchAddress("rbin",&rbin);
    
    //muon variable
    tree->SetBranchAddress("muPosPx",&muPosPx);
    tree->SetBranchAddress("muPosPy",&muPosPy);
    tree->SetBranchAddress("muPosPz",&muPosPz);
    tree->SetBranchAddress("muPosEta",&muPosEta);
    tree->SetBranchAddress("muPosPhi",&muPosPhi);
    tree->SetBranchAddress("muNegPx", &muNegPx);
    tree->SetBranchAddress("muNegPy",    &muNegPy);
    tree->SetBranchAddress("muNegPz",    &muNegPz);
    tree->SetBranchAddress("muNegEta",    &muNegEta);
     tree->SetBranchAddress("muNegPhi", &muNegPhi);

    //1). Positive Muon
    tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
    tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
    tree->SetBranchAddress("muPos_dz", &muPos_dz);
    tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
    tree->SetBranchAddress("muPos_found", &muPos_found);
    tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
    tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
    tree->SetBranchAddress("muPos_matches", &muPos_matches);
    tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
    tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);  
    
    //2). Negative Muon                                                                            
    tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
    tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
    tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
    tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
    tree->SetBranchAddress("muNeg_found", &muNeg_found);
    tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
    tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
    tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
    tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
    tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
    



//====================================Gen Variables=========================================================
    //Gen Jpsi Variables
    gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
    gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
    gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
    gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
    gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
    gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
    gentree->SetBranchAddress("gbin",&gbin);
    //muon variable
    gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
    gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
    gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
    gentree->SetBranchAddress("GenmuPosEta",    &GenmuPosEta);
     gentree->SetBranchAddress("GenmuPosPhi",    &GenmuPosPhi);
    gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
    gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
    gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
    gentree->SetBranchAddress("GenmuNegEta",    &GenmuNegEta);
    gentree->SetBranchAddress("GenmuNegPhi",    &GenmuNegPhi);

    //====================================================== Gen tree loop ================================================
    int NAccep=0;
    int nGenEntries=gentree->GetEntries();
    cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ========="<<endl;
    //dataFile<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ====="<<endl;
    
    
    for(int i=0; i< nGenEntries; i++)  {	    
      gentree->GetEntry(i);
      
      if(i%1000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl; 
      }
      
      bool GenPosIn=0, GenNegIn=0,GenPosPass=0,GenNegPass=0;

      GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
      GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 
      
      GenJpsiE= TMath::Sqrt( GenJpsiPx*GenJpsiPx+GenJpsiPy*GenJpsiPy+GenJpsiPz*GenJpsiPz + 9.46*9.46);


      
      //============================ calculate Pol weight ========================================================================================= //
      Float_t w1,w2,w3,w4,w5;
      // this is the beam energy: 2760GeV->/2->1380GeV each beam
      // the mp=0.938272 is the mass of the proton, as we are looking at p+p collisions
      double E=1380; double pz = sqrt(E*E - 0.938272*0.938272);
      TLorentzVector h1; // beam 1
      TLorentzVector h2; // beam 2
     
      TLorentzVector genJpsi;    // generated upsilon (mother of the single muons) --> if you look at jpsi-> genJpsi (prompt or non-prompt)
      TLorentzVector genMuPlus,genMuMinus; // generator positive muon (charge=+1)
      
      //int mp;
      Float_t cosThetaStarHel; // cosTheta in the Helicity frame
      Float_t cosThetaStarCS;  // cosTheta in the Collins-Soper frame
      TVector3 zCS;             // collins-soper variable

      // put the coordinates of the parent in a TLorentzVector
      // ATTENTION: the last coordinate is the MASS of the parent, which in this case, since it's about Upsilon, it's 9.46
      // when you'll do this for Jpsi, this value has to change to m_jpsi=3.097
      genJpsi.SetPxPyPzE(GenJpsiPx, GenJpsiPy, GenJpsiPz, GenJpsiE); 
      TLorentzRotation boost(-genJpsi.BoostVector()); // boost it
   
      // put the muon in a LorentzVector
      genMuPlus.SetPtEtaPhiM(GenmuPosPt, GenmuPosEta, GenmuPosPhi, 0.106);
      genMuPlus *= boost; // boost it
      
      //genMuMinus.SetPtEtaPhiM(GenmuNegPt, GenmuNegEta, GenmuNegPhi, 0.106);
      //genMuMinus *= boost; // boost it


      //and get the cosTheta in the helicity frame
      cosThetaStarHel = genMuPlus.Vect().Dot(genJpsi.Vect())/(genMuPlus.Vect().Mag()*genJpsi.Vect().Mag());
     
      //int genMuCharge = 1;
      //int mp = genMuCharge>0 ? 0 : 1;
      //cout << genMuCharge << "     " << mp << endl;


      h1.SetPxPyPzE(0,0,pz,E);  // TLorentzVector for beam 1
      h2.SetPxPyPzE(0,0,-pz,E); //  TLorentzVector for beam 2
      h1*=boost;
      h2*=boost;
      // calculate cosTheta CS

      zCS = ( h1.Vect().Unit() - h2.Vect().Unit() ).Unit();
      cosThetaStarCS = genMuPlus.Vect().Dot(zCS)/genMuPlus.Vect().Mag();

      // setup the weights
      w1 = 1;
      w2 = 1 + cosThetaStarHel*cosThetaStarHel;
      w3 = 1 - cosThetaStarHel*cosThetaStarHel;
      w4 = 1 + cosThetaStarCS*cosThetaStarCS;
      w5 = 1 - cosThetaStarCS*cosThetaStarCS;
      

      //w5=1; 

      // cout<<" gen "<<w2<<"   "<<w3<<"  "<<w4<<"  "<<w5<<endl;

      //==============================================================================================================================================//


    
      diMuonsInvMass_Gen->Fill(GenJpsiMass);
      diMuonsPt_Gen->Fill(GenJpsiPt);
 
      if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
      if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}
  

    
      if(GenPosIn && GenNegIn ) NAccep++;
      
      if(GenPosIn==1 && GenmuPosPt>PtCut ) {GenPosPass=1;}
      if(GenNegIn==1 && GenmuNegPt>PtCut ) {GenNegPass=1;}

      double GenCenWeight=0,GenWeight=0;
      GenCenWeight=FindCenWeight(gbin);
      Bin_Gen->Fill(gbin);
      GenWeight=GenCenWeight*scale[ifile];
      if(PutWeight==0){GenWeight=1;}

      if(GenPosIn && GenNegIn){
	if(ifile==0){diMuonsRap_Gen0->Fill(GenJpsiRap);}
	if(ifile==1){diMuonsRap_Gen1->Fill(GenJpsiRap);}
	if(ifile==2){diMuonsRap_Gen2->Fill(GenJpsiRap);}
	if(ifile==3){diMuonsRap_Gen3->Fill(GenJpsiRap);}
	if(ifile==4){diMuonsRap_Gen4->Fill(GenJpsiRap);}
	if(ifile==5){diMuonsRap_Gen5->Fill(GenJpsiRap);}
      }
 

      for (Int_t ih = 0; ih < Nptbin; ih++) {
	//adding pT of all pt bins to see diss is cont
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 ) && (GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsPt_GenA[ifile][ih]->Fill(GenJpsiPt,GenWeight*w5);}
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 )&&(GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
	if(iSpec == 2)  if((GenPosPass==1 && GenNegPass==1) &&  (GenJpsiPt<20.0) && (TMath::Abs(GenJpsiRap) > pt_bound[ih] && TMath::Abs(GenJpsiRap) <=pt_bound[ih+1] )){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
	if(iSpec == 3)  if( (GenPosPass==1 && GenNegPass==1) && (GenJpsiPt < 20.0) &&  (TMath::Abs(GenJpsiRap)<2.4 ) && (gbin>=pt_bound[ih] && gbin<pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
      

      }

    }//gen loop end
    
    cout<<" accepted no "<< NAccep<<endl;
    //dataFile<<" accepted no "<< NAccep<<endl;
     
    //   new TCanvas;
    //diMuonsInvMass_Gen->Draw();
    //gPad->Print("plots/diMuonsInvMass_Gen.png");
    
    //new TCanvas;
    //diMuonsPt_Gen->Draw();
    //gPad->Print("plots/diMuonsPt_Gen.png");
  
    //new TCanvas;
    //diMuonsRap_Gen0->Draw();
    //sprintf(PlotName,"plots/diMuonsRap_Gen_%d.pdf",ifile);   
    //gPad->Print(PlotName);
    
    //new TCanvas;
    //Bin_Gen->Draw();
    //gPad->Print("plots/Bin_Gen.png");
    
  

    //=============== Rec Tree Loop ==============================================================================
    
    int nRecEntries=tree->GetEntries();
    cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
    //dataFile<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<<endl;
    
    for(int i=0; i<nRecEntries; i++)  {	    
      tree->GetEntry(i);
      if(i%100000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
	cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<endl; 
      }
      
      bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
      muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
      muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
      muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
      muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 
    
      
      JpsiE= TMath::Sqrt(JpsiPx*JpsiPx+JpsiPy*JpsiPy+JpsiPz*JpsiPz + JpsiMass*JpsiMass);
      //============================ calculate Pol weight rec ========================================================================================= //
      Float_t w1=0,w2=0,w3=0,w4=0,w5=0;
      double E=1380; double pz = sqrt(E*E - 0.938272*0.938272);
      TLorentzVector h1; // beam 1
      TLorentzVector h2; // beam 2
      
      TLorentzVector Jpsi;    
      TLorentzVector MuPlus;       
      Float_t cosThetaStarHel; // cosTheta in the Helicity frame
      Float_t cosThetaStarCS;  // cosTheta in the Collins-Soper frame
      TVector3 zCS;             // collins-soper variable
      
      Jpsi.SetPxPyPzE(JpsiPx, JpsiPy, JpsiPz, JpsiE); 
      TLorentzRotation boost(-Jpsi.BoostVector()); // boost it
      
      // put the muon in a LorentzVector
      MuPlus.SetPtEtaPhiM(muPosPt, muPosEta, muPosPhi, 0.106);
      MuPlus *= boost; // boost it
      //and get the cosTheta in the helicity frame
      cosThetaStarHel = MuPlus.Vect().Dot(Jpsi.Vect())/(MuPlus.Vect().Mag()*Jpsi.Vect().Mag());
      h1.SetPxPyPzE(0,0,pz,E);  // TLorentzVector for beam 1
      h2.SetPxPyPzE(0,0,-pz,E); //  TLorentzVector for beam 2
      h1*=boost;
      h2*=boost;
      zCS = ( h1.Vect().Unit() - h2.Vect().Unit() ).Unit();
      cosThetaStarCS = MuPlus.Vect().Dot(zCS)/MuPlus.Vect().Mag();
      // setup the weights
      w1 = 1;
      w2 = 1 + cosThetaStarHel*cosThetaStarHel;
      w3 = 1 - cosThetaStarHel*cosThetaStarHel;
      w4 = 1 + cosThetaStarCS*cosThetaStarCS;
      w5 = 1 - cosThetaStarCS*cosThetaStarCS;
      


      //w5=1;
      //cout<<" rec "<<w2<<"   "<<w3<<"  "<<w4<<"  "<<w5<<endl; 
      //================================================== Pol weights  ===============================================================================//
      
      if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
      if(IsAccept(muNegPt, muNegEta)){NegIn=1;}



      if(muPos_found > 10 && muPos_pixeLayers > 0 && muPos_nchi2In < 4.0 && muPos_dxy < 3 && muPos_dz < 15 && muPos_nchi2Gl < 20 &&  muPos_arbitrated==1 && muPos_tracker==1){PosPass=1;}	  
      
      if(muNeg_found >10 && muNeg_pixeLayers >0 && muNeg_nchi2In <4.0 && muNeg_dxy < 3 && muNeg_dz < 15 && muNeg_nchi2Gl < 20 && muNeg_arbitrated==1 && muNeg_tracker==1){NegPass=1;}

      // cout<<muPos_matches<<"  "<<muNeg_matches<<endl;
      
      if((muPosPt > PtCut && muNegPt > PtCut) && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1 )  &&   (PosPass==1 && NegPass==1)){AllCut=1;}
    
      double RecCenWeight=0,RecWeight=0;
      RecCenWeight=FindCenWeight(rbin);
      RecWeight=RecCenWeight*scale[ifile];
      if(PutWeight==0){RecWeight=1;}
     
      if(i%100000==0){
	cout<<" eff loop for reco "<<endl;
      }
      
      if(AllCut==1){
	if(ifile==0){diMuonsRap_Rec0->Fill(JpsiRap);}
	if(ifile==1){diMuonsRap_Rec1->Fill(JpsiRap);}
	if(ifile==2){diMuonsRap_Rec2->Fill(JpsiRap);}
	if(ifile==3){diMuonsRap_Rec3->Fill(JpsiRap);}
	if(ifile==4){diMuonsRap_Rec4->Fill(JpsiRap);}
	if(ifile==5){diMuonsRap_Rec5->Fill(JpsiRap);}
      }

      //Eff loop for reco
      if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {
	for (Int_t ih = 0; ih < Nptbin; ih++) {
	  //to see cont reco pT
	  if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap) < 2.4) && (JpsiPt>pt_bound[ih] && JpsiPt<=pt_bound[ih+1])) {diMuonsPt_RecA[ifile][ih]->Fill(JpsiPt,RecWeight*w5);}
	  
	  if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap)<2.4 ) && (JpsiPt > pt_bound[ih] && JpsiPt <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass, RecWeight*w5);}
	  if(iSpec == 2) if( (AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) > pt_bound[ih] && TMath::Abs(JpsiRap) <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight*w5);}
	  if(iSpec == 3) if((AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) < 2.4) && (rbin>=pt_bound[ih] &&  rbin < pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight*w5);}
	



	}
      }
    }
  
    /*
    new TCanvas;
    if(ifile==0){diMuonsRap_Gen0->Draw();new TCanvas; diMuonsRap_Rec0->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen0.png");}
    if(ifile==1){diMuonsRap_Gen1->Draw();new TCanvas; diMuonsRap_Rec1->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen1.png");}
    if(ifile==2){diMuonsRap_Gen2->Draw();new TCanvas; diMuonsRap_Rec2->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen2.png");}
    if(ifile==3){diMuonsRap_Gen3->Draw();new TCanvas; diMuonsRap_Rec3->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen3.png");}
    if(ifile==4){diMuonsRap_Gen4->Draw();new TCanvas; diMuonsRap_Rec4->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen4.png");}
    if(ifile==5){diMuonsRap_Gen5->Draw();new TCanvas; diMuonsRap_Rec5->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen5.png");}
    */
  }  // file loop ends 

  ///////////////////////////////////////////////////////////////////

  cout<< " adding "<<endl;
  TH1D *diMuonsInvMass_RecA1[100];
  TH1D *diMuonsInvMass_GenA1[100];
  TH1D *diMuonsPt_GenA1[100];
  TH1D *diMuonsPt_RecA1[100];
  TF1 *backfun_1;
  char namePt_1B[500];//for bkg func
 
  for(Int_t ih = 0; ih < Nptbin; ih++){
    diMuonsInvMass_RecA1[ih] = diMuonsInvMass_RecA[0][ih];
    diMuonsInvMass_GenA1[ih] = diMuonsInvMass_GenA[0][ih];
    diMuonsPt_GenA1[ih] = diMuonsPt_GenA[0][ih];
    diMuonsPt_RecA1[ih] = diMuonsPt_RecA[0][ih];
    
    for (int ifile = 1; ifile <= 5; ifile++) {
      diMuonsInvMass_RecA1[ih]->Add(diMuonsInvMass_RecA[ifile][ih]);
      diMuonsInvMass_GenA1[ih]->Add(diMuonsInvMass_GenA[ifile][ih]);     
      
      diMuonsPt_GenA1[ih]->Add(diMuonsPt_GenA[ifile][ih]); 
      diMuonsPt_RecA1[ih]->Add(diMuonsPt_RecA[ifile][ih]); 
    }
  }
  
  //===========================Fitting===================================================================//
  // Fit ranges
  double mass_low, mass_high;
  double MassUpsilon, WeidthUpsilon;
  
  // Low mass range upsilon width 54 KeV
  MassUpsilon = 9.46; WeidthUpsilon = 0.055;
  //MassUpsilon = 9.46; WeidthUpsilon = 0.068;
  mass_low = 9.0; mass_high = 10.0;  // Fit ranges
  
  // Fit Function crystall ball
  TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,8.0,12.0,6);
  GAUSPOL->SetParNames("Yield (#Upsilon)","BinWidth","Mean","Sigma","#alpha","n");
  GAUSPOL->SetParameter(2, MassUpsilon);
  GAUSPOL->SetParameter(3, WeidthUpsilon);
  //GAUSPOL->SetParLimits(3, 0.1*WeidthUpsilon,2.0*WeidthUpsilon);
  GAUSPOL->SetParameter(4, 1.0);
  GAUSPOL->SetParameter(5, 20.0);
  GAUSPOL->SetLineWidth(2.0);
  GAUSPOL->SetLineColor(2);




  //=====================Loop for eff===========================================================
  double GenNo[100]={0};
  double Eff[100]={0};
  double GenError[100]={0};
  double RecError[100]={0};
  double errEff_cat_S1[100]={0};
  double errEff_cat_S2[100]={0};
  double errEff_cat_S1_1[100]={0},errEff_cat_S1_2[100]={0};
  double errEff_cat_S2_1[100]={0},errEff_cat_S2_2[100]={0};
  char PlotName[500],PlotName1[500], PlotName2[500]; 
  char GPlotName[500],GPlotName1[500], GPlotName2[500];

  for (Int_t ih = 0; ih < Nptbin; ih++) {
   
    cout<<" no of gen dimuons from diMuons Pt histo    "<<diMuonsPt_GenA1[ih]->Integral(1,100)<<endl;
    cout<<" no of gen dimuons from diMuons Mass histo  "<<diMuonsInvMass_GenA1[ih]->Integral(1,100)<<endl;
    

    //from pT histogram
    //gen_pt[ih] =diMuonsPt_GenA1[ih]->IntegralAndError(1,100,genError);
   
    gen_pt[ih] = diMuonsInvMass_GenA1[ih]->IntegralAndError(1,100,genError);
    gen_ptError[ih]= genError;
    
    if(iSpec==1) sprintf(PlotName,"plots/DiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(PlotName,"plots/DiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(PlotName,"plots/DiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(PlotName1,"plots/DiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(PlotName1,"plots/DiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(PlotName1,"plots/DiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(PlotName2,"plots/DiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(PlotName2,"plots/DiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(PlotName2,"plots/DiMuonMass_CentBin_%d.eps",ih);
 

    //giving inetial value for crystall ball fourth parameter 
    diMuonsInvMass_RecA1[ih]->Rebin(2);
    GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[ih]->Integral(0,50));
    GAUSPOL->FixParameter(1, diMuonsInvMass_RecA1[ih]->GetBinWidth(1));
    
    new TCanvas; 
    diMuonsInvMass_RecA1[ih]->Fit("GAUSPOL","LLMERQ", "", mass_low, mass_high);
   
    double UpsilonMass = GAUSPOL->GetParameter(2);
    double UpsilonWidth = GAUSPOL->GetParameter(3);
   
    double UpsilonYield = GAUSPOL->GetParameter(0);
    double UpsilonYieldError = GAUSPOL->GetParError(0);
 
    double par[20];
    GAUSPOL->GetParameters(par);
    sprintf(namePt_1B,"pt_1B_%d",ih);
    backfun_1 = new TF1(namePt_1B, Pol2, mass_low, mass_high, 3);
    backfun_1->SetParameters(&par[4]);
   

    double MassLow=(UpsilonMass-3*UpsilonWidth);
    double MassHigh=(UpsilonMass+3*UpsilonWidth);
    
    int binlow =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassLow);
    int binhi =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassHigh);
    double binwidth=diMuonsInvMass_RecA1[ih]->GetBinWidth(1);
        
    //yield by function 
    //rec_pt[ih] = UpsilonYield;
    //rec_ptError[ih]= UpsilonYieldError;

    cout<<"Rec diMuons from Pt histo "<<diMuonsPt_RecA1[ih]->Integral(1,100)<<endl;  
    cout<<"Rec dimuons from mass "<<diMuonsInvMass_RecA1[ih]->Integral(1,100)<<endl; 
    

      
    //from pT histo
    //rec_pt[ih]=diMuonsPt_RecA1[ih]->IntegralAndError(1, 100,recError);

    //yield by histogram integral
    rec_pt[ih] = diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError);
    rec_ptError[ih]= recError;
  
    //Cal eff 
    Eff_cat_1[ih] = rec_pt[ih]/gen_pt[ih]; 
  
    //calculate error on eff
    GenNo[ih]=gen_pt[ih];
    Eff[ih]= Eff_cat_1[ih];
    GenError[ih]=gen_ptError[ih];
    RecError[ih]=rec_ptError[ih];
    //error    
    errEff_cat_S1_1[ih]= ( (Eff[ih] * Eff[ih]) /(GenNo[ih] * GenNo[ih]) );
    errEff_cat_S1_2[ih]= (RecError[ih] * RecError[ih]);
    errEff_cat_S1[ih]= (errEff_cat_S1_1[ih] * errEff_cat_S1_2[ih]);
   

    errEff_cat_S2_1[ih]= ( (1 - Eff[ih])* (1 - Eff[ih]) ) / ( GenNo[ih] * GenNo[ih]);
    errEff_cat_S2_2[ih]= (GenError[ih] * GenError[ih] ) - ( RecError[ih] * RecError[ih] );


    errEff_cat_S2[ih]=errEff_cat_S2_1[ih]*errEff_cat_S2_2[ih];
   

    Err_Eff_cat_1[ih]=sqrt(errEff_cat_S1[ih] + errEff_cat_S2[ih]);
   
    //error for no weights
    //Err_Eff_cat_1[ih]= Eff_cat_1[ih]*TMath::Sqrt(gen_ptError[ih]*gen_ptError[ih]/(gen_pt[ih]*gen_pt[ih]) + rec_ptError[ih]*rec_ptError[ih]/(rec_pt[ih]* rec_pt[ih]));

    cout<<"Upsilon Yield by integral of histo:  "<< diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError) <<"  error "<< rec_ptError[ih]<<endl; 
    cout<<"UpsilonYield by Gauss yield det:     "<< UpsilonYield << " UpsilonWidth "<< UpsilonWidth<<" UpsilonMass "<<UpsilonMass <<endl;
    cout<<"Upsilon Yield by Function integral:  "<< GAUSPOL->Integral(MassLow,MassHigh)/binwidth <<endl;
    cout<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    //dataFile<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    cout<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    dataFile<<"ih " <<ih<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    if(iSpec==1) sprintf(GPlotName,"plots/GenDiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(GPlotName,"plots/GenDiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(GPlotName,"plots/GenDiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(GPlotName1,"plots/GenDiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(GPlotName1,"plots/GenDiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(GPlotName1,"plots/GenDiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(GPlotName2,"plots/GenDiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(GPlotName2,"plots/GenDiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(GPlotName2,"plots/GenDiMuonMass_CentBin_%d.eps",ih);
       
    backfun_1->SetLineColor(4);
    backfun_1->SetLineWidth(1);
    //backfun_1->Draw("same");
    gPad->Print(PlotName);
    gPad->Print(PlotName1);
    gPad->Print(PlotName2);

    new TCanvas;
    diMuonsInvMass_GenA1[ih]->Draw();
    gPad->Print(GPlotName);
    gPad->Print(GPlotName1);
    gPad->Print(GPlotName2);


    //new TCanvas;
    //diMuonsPt_GenA1[ih]->Draw();
    //new TCanvas;
    //diMuonsPt_RecA1[ih]->Draw();
 
}
  dataFile.close();

  TGraphErrors *Eff_Upsilon = new TGraphErrors(Nptbin, PT, Eff_cat_1, mom_err,Err_Eff_cat_1);
  Eff_Upsilon->SetMarkerStyle(21);
  Eff_Upsilon->SetMarkerColor(2);
  Eff_Upsilon->GetYaxis()->SetTitle("Reco Eff");
 
  if(iSpec==1) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon pT (GeV/c^{2})");
  if(iSpec==2) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon rapidity");
  if(iSpec==3) Eff_Upsilon->GetXaxis()->SetTitle("bin");
   Eff_Upsilon->GetYaxis()->SetRangeUser(0,1.0);

  TLegend *legend_GP = new TLegend( 0.50,0.79,0.80,0.89);
  legend_GP->SetBorderSize(0);
  legend_GP->SetFillStyle(0);
  legend_GP->SetFillColor(0);
  legend_GP->SetTextSize(0.032);
  legend_GP->AddEntry(Eff_Upsilon,"PythiaEvtGen + HydjetBass", "P");
  
  new TCanvas;
  Eff_Upsilon->Draw("AP");
  legend_GP->Draw("Same");
    
  if(iSpec==1){ gPad->Print("plots/Eff_Upsilon_Pt.pdf");gPad->Print("plots/Eff_Upsilon_Pt.png");gPad->Print("plots/Eff_Upsilon_Pt.eps");}
  if(iSpec==2){ gPad->Print("plots/Eff_Upsilon_Rap.pdf");gPad->Print("plots/Eff_Upsilon_Rap.png");  gPad->Print("plots/Eff_Upsilon_Rap.eps");}
  if(iSpec==3){ gPad->Print("plots/Eff_Upsilon_Cent.pdf");gPad->Print("plots/Eff_Upsilon_Cent.png"); gPad->Print("plots/Eff_Upsilon_Cent.eps"); }

}
Example #25
0
void DalitzDecay(Particle *PParent, Particle *PLepton1, Particle *PLepton2,
		 Particle *POther, ParticlePropertyList *PPList, Decay *PDecay)
{
  double pmass, lmass, omass, lpmass;
  double E1, p1, E3, p3;
  double beta_square, lambda;
  double costheta, sintheta, cosphi, sinphi, phi;

  int new_generation;

  pmass=GetMass(PDecay->GetParentID(),PPList);
  lmass=0;
  omass=0;
  int ibody=0;
  for( ibody=1; ibody<=3; ibody++)
  {
    int ID;
    ID = PDecay->GetChildID(ibody);
    if ( abs(ID)==11 || abs(ID)==13 )
      lmass = GetMass(PDecay->GetChildID(ibody), PPList);
    else
      omass = GetMass(PDecay->GetChildID(ibody), PPList);
  }
 
  TH1F * LeptonPairMass = PDecay->GetHistogram();

  for ( ibody=1; ibody<=3; ibody++ )
  { 
    switch( PDecay->GetChildID(ibody) )
    {
       case -11:   PLepton1->SetID(-11); break;
       case  11:   PLepton2->SetID(11); break;
       case -13:   PLepton1->SetID(-13); break;
       case  13:   PLepton2->SetID(13); break;
       default :   POther->SetID(PDecay->GetChildID(ibody));
    }
  }

  for( ;; ) 
  {
    lpmass = LeptonPairMass->GetRandom();
    if ( pmass-omass>lpmass && lpmass/2.>lmass ) break;
  }

  E1 = lpmass/2.;
  p1 = sqrt((E1+lmass)*(E1-lmass));
  beta_square = 1.0 - 4.0*(lmass*lmass)/(lpmass*lpmass);
  lambda      = beta_square/(2.0-beta_square);
  if ( omass<0.01 )
  {
    do
    {
      costheta = (2.0*gRandom->Rndm())-1.;
    }
    while ( (1.0+lambda*costheta*costheta)<(2.0*gRandom->Rndm()) );
  }
  else
  {
    costheta = (2.0*gRandom->Rndm())-1.;
  }
  sintheta = sqrt((1.+costheta)*(1.-costheta));
  phi      = 2.0*PI*gRandom->Rndm();
  sinphi   = sin(phi);
  cosphi   = cos(phi);

  new_generation = PParent->GetGeneration()+1;
  PLepton1->SetGeneration(new_generation);
  PLepton2->SetGeneration(new_generation);
  POther->SetGeneration(new_generation);

  PLepton1->SetDecaysum(0.0);
  PLepton2->SetDecaysum(0.0);
  POther->SetDecaysum(0.0);

  PLepton1->Set4mom(E1,
		    p1*sintheta*cosphi,
		    p1*sintheta*sinphi,
		    p1*costheta);
  PLepton2->Set4mom(E1,invert(PLepton1->Get4mom().Getp()));
  
  E3       = (SQR(pmass)+SQR(omass)-SQR(lpmass))/(2.*pmass);
  p3       = sqrt((E3+omass)*(E3-omass));
  costheta = (2.0*gRandom->Rndm())-1.;
  sintheta = sqrt((1.+costheta)*(1.-costheta));
  phi      = 2.0*PI*gRandom->Rndm();
  sinphi   = sin(phi);
  cosphi   = cos(phi);	    

  POther->Set4mom(E3,
		  p3*sintheta*cosphi,
		  p3*sintheta*sinphi,
		  p3*costheta);

  PLepton1->Set4mom(E1,
    Rotate(PLepton1->Get4mom().Getp(),costheta,-sintheta,-cosphi,-sinphi));
  PLepton2->Set4mom(E1,
    Rotate(PLepton2->Get4mom().Getp(),costheta,-sintheta,-cosphi,-sinphi));
		    
  Mom4 lp_boost(sqrt(SQR(p3)+SQR(lpmass)),invert(POther->Get4mom().Getp()));
  PLepton1->Set4mom(boost(PLepton1->Get4mom(),lp_boost));
  PLepton2->Set4mom(boost(PLepton2->Get4mom(),lp_boost));
  
  PLepton1->Set4mom(boost(PLepton1->Get4mom(),PParent->Get4mom()));
  PLepton2->Set4mom(boost(PLepton2->Get4mom(),PParent->Get4mom()));
  POther->Set4mom(boost(POther->Get4mom(),PParent->Get4mom()));
  
  return;

}
Example #26
0
void AnalyseEvent(Blob_List* blobs)
{
#ifdef USING__ROOT
//   int outgoing = 1;
//   int incoming = -1;
//   Particle_List outparts = blobs->ExtractParticles(part_status::active, outgoing);

  ///////////////////////////////////////////////////////////////////////////////////
  // analyse primary decay blob, ignore subsequent decays                          //
  ///////////////////////////////////////////////////////////////////////////////////
  Blob * primarydecayblob = blobs->FindFirst(btp::Hadron_Decay);
//   msg_Out()<<"primary decay blob:"<<endl<<*primarydecayblob<<endl;
  // photon multiplicity and decay frame radiated energy (total)
  unsigned int photmult = 0;
  double       photener = 0.;
  for (int i=0; i<primarydecayblob->NOutP(); i++) {
    if ((primarydecayblob->OutParticle(i)->Flav().IsPhoton() == true) && 
        (primarydecayblob->OutParticle(i)->Info() == 'S')) {
      photmult++;
      photener = photener + primarydecayblob->OutParticle(i)->Momentum()[0];
    }
  }
  photonmultiplicity->Fill(photmult);
  if (photener != 0.)   decayframeenergy->Fill(photener);
  // multipole rest frame angles
  Vec4D multipolesum  = Vec4D(0.,0.,0.,0.);
  Vec4D axis          = Vec4D(0.,0.,0.,1.);
  std::list<Vec4D> multipole;
  std::list<Vec4D> newphot;
  for (int i=0; i<primarydecayblob->NOutP(); i++) {
    if (primarydecayblob->OutParticle(i)->Flav().Charge() != 0.) {
      multipolesum = multipolesum + primarydecayblob->OutParticle(i)->Momentum();
      multipole.push_back(primarydecayblob->OutParticle(i)->Momentum());
    }
  }
  if (primarydecayblob->InParticle(0)->Flav().Charge() != 0) {
    multipolesum = multipolesum + primarydecayblob->InParticle(0)->Momentum();
    multipole.push_front(primarydecayblob->InParticle(0)->Momentum());
  }
  Poincare boost(multipolesum);
  Poincare rotate;
  // charged initial state: rotate such that initial state at theta = 0
  if (mother_flav.Charge() != 0.) {
    Vec4D inmom = *multipole.begin();
    boost.Boost(inmom);
    rotate = Poincare(inmom,axis);
  }
  // neutral initial state: rotate such that heaviest charged final state at theta = 0
  else {
    std::list<Vec4D>::iterator heaviest = multipole.begin();
    for (std::list<Vec4D>::iterator iter=multipole.begin(); iter!=multipole.end(); iter++) {
      if (abs((iter->Abs2() - heaviest->Abs2())/(iter->Abs2() + heaviest->Abs2())) > 1E-6) {
        heaviest = iter;
      }
    }
    boost.Boost(*heaviest);
    rotate = Poincare(*heaviest,axis);
  }
  for (int i=0; i<primarydecayblob->NOutP(); i++) {
    if (primarydecayblob->OutParticle(i)->Flav().IsPhoton() == true) {
      Vec4D mom = primarydecayblob->OutParticle(i)->Momentum();
      boost.Boost(mom);
      rotate.Rotate(mom);
      double theta = acos((Vec3D(mom)*Vec3D(axis))/(Vec3D(mom).Abs()*Vec3D(axis).Abs()));
      multipoleframeangles->Fill(theta);
    }
  }  

  ///////////////////////////////////////////////////////////////////////////////////
  // inclusive analysis of whole decay chain                                       //
  ///////////////////////////////////////////////////////////////////////////////////

  // to be done ..
#endif
}