Пример #1
0
void dataLogV(const char* format, va_list argList)
{
    vfprintf(dataFile(), format, argList);
}
Пример #2
0
int main( int argc, char * * argv )
{
	// intialize RNG
	srand( getpid() + time( 0 ) );

	bool core_only = false;
	bool fullscreen = true;
	bool exit_after_import = false;
	QString file_to_load, file_to_save, file_to_import, render_out;

	for( int i = 1; i < argc; ++i )
	{
		if( argc > i && ( ( QString( argv[i] ) == "--render" ||
					QString( argv[i] ) == "-r" ) ||
				( QString( argv[i] ) == "--help" ||
						QString( argv[i] ) == "-h" ) ) )
		{
			core_only = true;
		}
		else if( argc > i && QString( argv[i] ) == "-geometry" )
		{
			// option -geometry is filtered by Qt later,
			// so we need to check its presence now to
			// determine, if the application should run in
			// fullscreen mode (default, no -geometry given).
			fullscreen = false;
		}
	}

	QCoreApplication * app = core_only ?
			new QCoreApplication( argc, argv ) :
					new QApplication( argc, argv ) ;


	Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality );
	ProjectRenderer::OutputSettings os( 44100, false, 160,
						ProjectRenderer::Depth_16Bit );
	ProjectRenderer::ExportFileFormats eff = ProjectRenderer::WaveFile;


	for( int i = 1; i < argc; ++i )
	{
		if( QString( argv[i] ) == "--version" ||
						QString( argv[i] ) == "-v" )
		{
			printf( "\nLinux MultiMedia Studio %s\n(%s %s, Qt %s, %s)\n\n"
	"Copyright (c) 2004-2014 LMMS developers.\n\n"
	"This program is free software; you can redistribute it and/or\n"
	"modify it under the terms of the GNU General Public\n"
	"License as published by the Free Software Foundation; either\n"
	"version 2 of the License, or (at your option) any later version.\n\n"
	"Try \"%s --help\" for more information.\n\n", LMMS_VERSION, 
				PLATFORM, MACHINE, QT_VERSION_STR, GCC_VERSION,
				argv[0] );

			return( EXIT_SUCCESS );
		}
		else if( argc > i && ( QString( argv[i] ) == "--help" ||
						QString( argv[i] ) == "-h" ) )
		{
			printf( "\nLinux MultiMedia Studio %s\n"
	"Copyright (c) 2004-2014 LMMS developers.\n\n"
	"usage: lmms [ -r <project file> ] [ options ]\n"
	"            [ -u <in> <out> ]\n"
	"            [ -d <in> ]\n"
	"            [ -h ]\n"
	"            [ <file to load> ]\n\n"
	"-r, --render <project file>	render given project file\n"
	"-o, --output <file>		render into <file>\n"
	"-f, --output-format <format>	specify format of render-output where\n"
	"				format is either 'wav' or 'ogg'.\n"
	"-s, --samplerate <samplerate>	specify output samplerate in Hz\n"
	"				range: 44100 (default) to 192000\n"
	"-b, --bitrate <bitrate>		specify output bitrate in kHz\n"
	"				default: 160.\n"
	"-i, --interpolation <method>	specify interpolation method\n"
	"				possible values:\n"
	"				   - linear\n"
	"				   - sincfastest (default)\n"
	"				   - sincmedium\n"
	"				   - sincbest\n"
	"-x, --oversampling <value>	specify oversampling\n"
	"				possible values: 1, 2, 4, 8\n"
	"				default: 2\n"
	"-u, --upgrade <in> [out]	upgrade file <in> and save as <out>\n"
	"       standard out is used if no output file is specifed\n"
	"-d, --dump <in>			dump XML of compressed file <in>\n"
	"-v, --version			show version information and exit.\n"
	"-h, --help			show this usage information and exit.\n\n",
							LMMS_VERSION );
			return( EXIT_SUCCESS );
		}
		else if( argc > i+1 && ( QString( argv[i] ) == "--upgrade" ||
						QString( argv[i] ) == "-u" ) )
		{
			QString inFile( argv[i + 1] );
			DataFile dataFile( inFile );
			if (argc > i+2)
			{
				const QString outFile = argv[i + 2];
				dataFile.writeFile( outFile );
			}
			else
			{
				QTextStream ts( stdout );
				dataFile.write( ts );
				fflush( stdout );
			}
			return( EXIT_SUCCESS );
		}
		else if( argc > i && ( QString( argv[i] ) == "--dump" ||
						QString( argv[i] ) == "-d" ) )
		{
			QFile f( argv[i + 1] );
			f.open( QIODevice::ReadOnly );
			QString d = qUncompress( f.readAll() );
			printf( "%s\n", d.toUtf8().constData() );
			return( EXIT_SUCCESS );
		}
		else if( argc > i && ( QString( argv[i] ) == "--render" ||
						QString( argv[i] ) == "-r" ) )
		{
			file_to_load = QString( argv[i + 1] );
			render_out = baseName( file_to_load ) + ".";
			++i;
		}
		else if( argc > i && ( QString( argv[i] ) == "--output" ||
						QString( argv[i] ) == "-o" ) )
		{
			render_out = baseName( QString( argv[i + 1] ) ) + ".";
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--format" ||
						QString( argv[i] ) == "-f" ) )
		{
			const QString ext = QString( argv[i + 1] );
			if( ext == "wav" )
			{
				eff = ProjectRenderer::WaveFile;
			}
#ifdef LMMS_HAVE_OGGVORBIS
			else if( ext == "ogg" )
			{
				eff = ProjectRenderer::OggFile;
			}
#endif
			else
			{
				printf( "\nInvalid output format %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--samplerate" ||
						QString( argv[i] ) == "-s" ) )
		{
			sample_rate_t sr = QString( argv[i + 1] ).toUInt();
			if( sr >= 44100 && sr <= 192000 )
			{
				os.samplerate = sr;
			}
			else
			{
				printf( "\nInvalid samplerate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--bitrate" ||
						QString( argv[i] ) == "-b" ) )
		{
			int br = QString( argv[i + 1] ).toUInt();
			if( br >= 64 && br <= 384 )
			{
				os.bitrate = br;
			}
			else
			{
				printf( "\nInvalid bitrate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--interpolation" ||
						QString( argv[i] ) == "-i" ) )
		{
			const QString ip = QString( argv[i + 1] );
			if( ip == "linear" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_Linear;
			}
			else if( ip == "sincfastest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincFastest;
			}
			else if( ip == "sincmedium" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincMedium;
			}
			else if( ip == "sincbest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincBest;
			}
			else
			{
				printf( "\nInvalid interpolation method %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--oversampling" ||
						QString( argv[i] ) == "-x" ) )
		{
			int o = QString( argv[i + 1] ).toUInt();
			switch( o )
			{
				case 1:
		qs.oversampling = Mixer::qualitySettings::Oversampling_None;
		break;
				case 2:
		qs.oversampling = Mixer::qualitySettings::Oversampling_2x;
		break;
				case 4:
		qs.oversampling = Mixer::qualitySettings::Oversampling_4x;
		break;
				case 8:
		qs.oversampling = Mixer::qualitySettings::Oversampling_8x;
		break;
				default:
				printf( "\nInvalid oversampling %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--import" ) )
		{
			file_to_import = argv[i+1];
			++i;
			// exit after import? (only for debugging)
			if( argc > i && QString( argv[i+1] ) == "-e" )
			{
				exit_after_import = true;
			}
		}
		else
		{
			if( argv[i][0] == '-' )
			{
				printf( "\nInvalid option %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return( EXIT_FAILURE );
			}
			file_to_load = argv[i];
		}
	}


	QString pos = QLocale::system().name().left( 2 );

#ifdef LMMS_BUILD_WIN32
#undef QT_TRANSLATIONS_DIR
#define QT_TRANSLATIONS_DIR configManager::inst()->localeDir()
#endif

#ifdef QT_TRANSLATIONS_DIR
	// load translation for Qt-widgets/-dialogs
	loadTranslation( QString( "qt_" ) + pos,
					QString( QT_TRANSLATIONS_DIR ) );
#endif
	// load actual translation for LMMS
	loadTranslation( pos );


	// try to set realtime priority
#ifdef LMMS_BUILD_LINUX
#ifdef LMMS_HAVE_SCHED_H
#ifndef __OpenBSD__
	struct sched_param sparam;
	sparam.sched_priority = ( sched_get_priority_max( SCHED_FIFO ) +
				sched_get_priority_min( SCHED_FIFO ) ) / 2;
	if( sched_setscheduler( 0, SCHED_FIFO, &sparam ) == -1 )
	{
		printf( "Notice: could not set realtime priority.\n" );
	}
#endif
#endif
#endif

	configManager::inst()->loadConfigFile();

	if( render_out.isEmpty() )
	{
		// init style and palette
		QApplication::setStyle( new LmmsStyle() );

		// show splash screen
		QSplashScreen splashScreen( embed::getIconPixmap( "splash" ) );
		splashScreen.show();
		splashScreen.showMessage( MainWindow::tr( "Version %1" ).arg( LMMS_VERSION ),
									Qt::AlignRight | Qt::AlignBottom, Qt::white );
		qApp->processEvents();

		// init central engine which handles all components of LMMS
		engine::init();

		splashScreen.hide();

		// re-intialize RNG - shared libraries might have srand() or
		// srandom() calls in their init procedure
		srand( getpid() + time( 0 ) );

		// recover a file?
		QString recoveryFile = QDir(configManager::inst()->workingDir()).absoluteFilePath("recover.dataFile");
		if( QFileInfo(recoveryFile).exists() &&
			QMessageBox::question( engine::mainWindow(), MainWindow::tr( "Project recovery" ),
						MainWindow::tr( "It looks like the last session did not end properly. "
										"Do you want to recover the project of this session?" ),
						QMessageBox::Yes | QMessageBox::No ) == QMessageBox::Yes )
		{
			file_to_load = recoveryFile;
		}

		// we try to load given file
		if( !file_to_load.isEmpty() )
		{
			engine::mainWindow()->show();
			if( fullscreen )
			{
				engine::mainWindow()->showMaximized();
			}
			if( file_to_load == recoveryFile )
			{
				engine::getSong()->createNewProjectFromTemplate( file_to_load );
			}
			else
			{
				engine::getSong()->loadProject( file_to_load );
			}
		}
		else if( !file_to_import.isEmpty() )
		{
			ImportFilter::import( file_to_import, engine::getSong() );
			if( exit_after_import )
			{
				return 0;
			}

			engine::mainWindow()->show();
			if( fullscreen )
			{
				engine::mainWindow()->showMaximized();
			}
		}
		else
		{
			engine::getSong()->createNewProject();

			// [Settel] workaround: showMaximized() doesn't work with
			// FVWM2 unless the window is already visible -> show() first
			engine::mainWindow()->show();
			if( fullscreen )
			{
				engine::mainWindow()->showMaximized();
			}
		}
	}
	else
	{
		// we're going to render our song
		engine::init( false );
		printf( "loading project...\n" );
		engine::getSong()->loadProject( file_to_load );
		printf( "done\n" );

		// create renderer
		ProjectRenderer * r = new ProjectRenderer( qs, os, eff,
			render_out +
				QString( ( eff ==
					ProjectRenderer::WaveFile ) ?
						"wav" : "ogg" ) );
		QCoreApplication::instance()->connect( r,
				SIGNAL( finished() ), SLOT( quit() ) );

		// timer for progress-updates
		QTimer * t = new QTimer( r );
		r->connect( t, SIGNAL( timeout() ),
				SLOT( updateConsoleProgress() ) );
		t->start( 200 );

		// start now!
		r->startProcessing();
	}

	const int ret = app->exec();
	delete app;
	return( ret );
}
void ppEffJpsiSysSFsSTA__idx_()   
{
  double minRap = 0.0;
  double maxRap = 2.4;
  double minPt = 6.5;
  double maxPt = 30.0;

  // if you want to measure low pT, you can set up minRap = 1.6 and minPt = 3.0, maxPt = 6.5;

  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(0); // at least most of the time
  gStyle->SetOptStat(0); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(0); // set to 1 only if you want to display fit results
  //==================================== Define Histograms====================================================

  //==============================================Define Acc Eff Stuff here===========================================
  // Pt bin sizes
  // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

  TFile *outfile;
  char tmp_output[512];
  sprintf(tmp_output,"ppPrJpsi_pT_%0.1f_%0.1f_y_%0.1f_%0.1f_HighQ_tnpWgt.root", minPt, maxPt, minRap, maxRap);
  outfile =new TFile(tmp_output, "Recreate");

  for(int iSpec = 0; iSpec < 2; iSpec++){

    const int nPtBins = 7;
    const int nRapBins = 6; // 6
    const int ndPhiBins = 4;
    double pt_bound[nPtBins+1] = {6.5, 7.5, 8.5, 9.5, 11.0, 13.0, 16.0, 30.0};
    double xpt_bound[nPtBins] = {0.0};
    //double rap_bound[nRapBins+1] = {0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4};
    double rap_bound[nRapBins+1] = {0.0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4};
    double xrap_bound[nRapBins] = {0.0};
    double dphi_bound[ndPhiBins+1] = {0.0, TMath::Pi()/8, TMath::Pi()/4, 3*TMath::Pi()/8, TMath::Pi()/2};
    double xdphi_bound[ndPhiBins] = {0.0};

    const char *cSp[2] = {"Pts","Raps"};
    char OutTextFile[100];
    sprintf(OutTextFile,"ppPromp_eff_%s_pT_%0.1f_%0.1f_y_%0.1f_%0.1f_HighQ.tex", cSp[iSpec], minPt, maxPt, minRap, maxRap);
    ofstream dataFile(OutTextFile);
    //ofstream dataFile(Form(OutTextFile));

    cout<< "%%%% Getting Efficiency starts : %s !!!!! %%%%%" << endl;
    //dataFile<< "%%%% Getting Efficiency starts : %s !!!!! %%%%%" << endl;

    // x, y, z - axis 
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of pT"<<endl;
    for(int i = 0; i < nPtBins; i++){
      xpt_bound[i] = pt_bound[i] + (pt_bound[i+1]-pt_bound[i])/2;
      cout<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
      //dataFile<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of rap"<<endl;
    for(int i = 0; i < nRapBins; i++){
      xrap_bound[i] = rap_bound[i] + (rap_bound[i+1]-rap_bound[i])/2;
      cout<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
      //dataFile<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of dphi"<<endl;
    for(int i = 0; i < ndPhiBins; i++){
      xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
      cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      //dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
    }

    int nBins_tmp = 0;
    if(iSpec == 0) { nBins_tmp = nPtBins; }
    if(iSpec == 1) { nBins_tmp = nRapBins; }
    const int nBins = nBins_tmp;

    TH1F *hTempMass = new TH1F("hTempMass","",100, 2.0, 4.0);
    TH1F *hGenDiMuon[nBins];
    TH1F *hRecoDiMuon[nBins];
    double genNo[nBins];
    double genErr[nBins];
    double recoNo[nBins];
    double recoErr[nBins];
    double eff[nBins];
    double effErr[nBins];
    for(int i = 0; i < nBins; i++){
      hGenDiMuon[i] = (TH1F*)hTempMass->Clone();
      hRecoDiMuon[i] = (TH1F*)hTempMass->Clone();
      hGenDiMuon[i]->Sumw2();
      hRecoDiMuon[i]->Sumw2();
    }

    char fileName[10][512];

    // loop for pT
    cout<<"==================Prompt PrJpsi================================================"<<endl;

    sprintf(fileName[0],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_538_pp/HiDiMuonAna_538_pp_NonPromptJpsi_20140317_Trg21.root");


    TFile *infile;
    TTree *tree;
    TTree *gentree;
    TTree *evttree;

    infile=new TFile(fileName[0],"R");
    tree=(TTree*)infile->Get("SingleMuonTree");
    gentree=(TTree*)infile->Get("SingleGenMuonTree");
    evttree=(TTree*)infile->Get("EventTree");
    //Event variables
    int eventNb,runNb,lumiBlock;
    int hbit1;
    //double vertexZ;
    //double GenvertexZ;
    //Jpsi Variables
    Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
    Double_t JpsiVprob;
    Double_t JpsiPhi;
    Double_t JpsiEta;
    //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;
    int muPos_Trigger10, muPos_Trigger2, muPos_Trigger21, muPos_Trigger22;
    //(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;
    int muNeg_Trigger10, muNeg_Trigger2, muNeg_Trigger21, muNeg_Trigger22;

    //Gen Level variables
    //Gen PrJpsi Variables
    double GenJpsiMass, GenJpsiPt, GenJpsiRap;
    double GenJpsiPx, GenJpsiPy, GenJpsiPz;
    double GenJpsiPhi;
    double GenJpsiEta;
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;
    double zVtx;

    //Event variables
    tree->SetBranchAddress("eventNb",&eventNb);
    tree->SetBranchAddress("runNb",&runNb);
    tree->SetBranchAddress("lumiBlock",&lumiBlock);
    tree->SetBranchAddress("hbit1",&hbit1);
    tree->SetBranchAddress("zVtx",&zVtx);
    //tree->SetBranchAddress("vertexZ",&vertexZ);

    //Jpsi Variables
    tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
    tree->SetBranchAddress("JpsiMass",&JpsiMass);
    tree->SetBranchAddress("JpsiPt",&JpsiPt);
    tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
    tree->SetBranchAddress("JpsiEta",&JpsiEta);
    tree->SetBranchAddress("JpsiRap",&JpsiRap);
    tree->SetBranchAddress("JpsiVprob",&JpsiVprob);

    //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);
    tree->SetBranchAddress("muPos_Trigger10", &muPos_Trigger10);
    tree->SetBranchAddress("muPos_Trigger2", &muPos_Trigger2);
    tree->SetBranchAddress("muPos_Trigger21", &muPos_Trigger21);
    tree->SetBranchAddress("muPos_Trigger22", &muPos_Trigger22);

    //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);
    tree->SetBranchAddress("muNeg_Trigger10", &muNeg_Trigger10);
    tree->SetBranchAddress("muNeg_Trigger2", &muNeg_Trigger2);
    tree->SetBranchAddress("muNeg_Trigger21", &muNeg_Trigger21);
    tree->SetBranchAddress("muNeg_Trigger22", &muNeg_Trigger22);
    //====================================Gen Variables=========================================================
    //Gen Jpsi Variables
    gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
    gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
    gentree->SetBranchAddress("GenJpsiPhi",    &GenJpsiPhi);
    gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
    gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
    gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
    gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
    gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
    //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);
    //gentree->SetBranchAddress("GenvertexZ",&GenvertexZ);

    //====================================================== Gen tree loop ================================================
    int NAccep=0;
    int nGenEntries=gentree->GetEntries();
    cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[0]<<"  "<<   nGenEntries<< " ==============="<<endl;

    for(int i=0; i< nGenEntries; i++)  {        
      //cout<<"i : "<<i<<endl;
      if(!(gentree->GetEntry(i))) continue;
      //cout<<" gentree ("<<i<<")"<<endl;
      //Only printing 
      if(i%1000000==0){
        cout<<" processing record "<<i<<"/"<<nGenEntries<<endl;
        //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
      }

      bool GenPosIn=0, GenNegIn=0;
      GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
      GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

      if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
      if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

      int AccJpsi = 0;
      //if(GenJpsiPt < 6.5) continue;
      if((GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && TMath::Abs(GenJpsiRap) <= maxRap && GenPosIn == 1 && GenNegIn == 1)
          && GenJpsiMass > 2.0 && GenJpsiMass < 4.0
          ) {AccJpsi = 1;}

      if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

      //cout<<"1. GenJpsiPt : "<<GenJpsiPt<<", GenJpsiEta : "<<GenJpsiEta<<", GenJpsiRap : "<<GenJpsiRap<<", |GenJpsiPsi| : "<<TMath::Abs(GenJpsiPsi)<<endl;
      //cout<<"1. GenPosIn : "<<GenPosIn<<", GenNegIn : "<<GenNegIn<<endl;
      double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
      if(iSpec == 0) vars = GenJpsiPt;
      if(iSpec == 1) vars = fabs(GenJpsiRap);
      for(int j = 0; j < nBins; j++){
        if(iSpec == 0){
          bin1 = pt_bound[j]; bin2 = pt_bound[j+1];
          if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && fabs(GenJpsiRap) >= minRap && TMath::Abs(GenJpsiRap) <= maxRap && TMath::Abs(GenJpsiRap) >= minRap) {
            hGenDiMuon[j]->Fill(GenJpsiMass);
          }
        }
        if(iSpec == 1){
          bin1 = rap_bound[j]; bin2 = rap_bound[j+1];
          if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && GenJpsiPt >= minPt && GenJpsiPt <= maxPt) {
            hGenDiMuon[j]->Fill(GenJpsiMass);
          }
        }
      }
    }//gen loop end

    //cout<<" accepted no "<< NAccep<<endl;

    //=============== Rec Tree Loop ==============================================================================

    int nRecEntries=tree->GetEntries();
    cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[0]<<"  "<<nRecEntries<< "====="<<endl;
    for(int i=0; i<nRecEntries; i++)  {     
      tree->GetEntry(i);
      //Only printing 
      if(i%1000000==0){
        cout<<" processing record "<<i<<"/"<<nRecEntries<<endl;
        //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
        //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<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); 

      double tnpWgt1 = 0.0, tnpWgt2 = 0.0;
      double staWgt1 = 0.0, staWgt2 = 0.0;

      double x = 0.0;
      double xta = 0.0;
      // tnp MuonID X Trg
      if(fabs(muPosEta) < 0.9){
        x = muPosPt;
        tnpWgt1 = tnpSF1->Eval(x);
      }else if(fabs(muPosEta) < 1.6){
        x = muPosPt;
        tnpWgt1 = tnpSF2->Eval(x);
      }else if(fabs(muPosEta) < 2.1){
        x = muPosPt;
        tnpWgt1 = tnpSF3->Eval(x);
      }else{
        x = muPosPt;
        tnpWgt1 = tnpSF4->Eval(x);
      }

      if(fabs(muNegEta) < 0.9){
        x = muNegPt;
        tnpWgt2 = tnpSF1->Eval(x);
      }else if(fabs(muNegEta) < 1.6){
        x = muNegPt;
        tnpWgt2 = tnpSF2->Eval(x);
      }else if(fabs(muNegEta) < 2.1){
        x = muNegPt;
        tnpWgt2 = tnpSF3->Eval(x);
      }else{
        x = muNegPt;
        tnpWgt2 = tnpSF4->Eval(x);
      }

      // tnp STA 
      if(fabs(muPosEta) < 1.6){
        xta = muPosPt;
        staWgt1 = fun1->Eval(xta);
      }else{
        xta = muPosPt;
        staWgt1 = fun2->Eval(xta);
      }

      if(fabs(muNegEta) < 1.6){
        xta = muNegPt;
        staWgt2 = fun1->Eval(xta);
      }else{
        xta = muNegPt;
        staWgt2 = fun2->Eval(xta);
      }

      double RecWeight = 1.0;
      RecWeight = tnpWgt1*tnpWgt2*staWgt1*staWgt2;

      if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
      if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

      int AccJpsi = 0;
      //if(JpsiPt < 6.5) continue;
      if((JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && TMath::Abs(JpsiRap) <= maxRap && PosIn == 1 && NegIn == 1)
          && (JpsiMass >= 2.95 && JpsiMass < 3.25)
          ) {AccJpsi = 1;}

      bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
      bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

      if(muPos_found > 10 
          && muPos_pixeLayers > 0 
          && muPos_nchi2In < 4.0 
          && TMath::Abs(muPos_dxy) < 3 
          && TMath::Abs(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 
          && TMath::Abs(muNeg_dxy) < 3 
          && TMath::Abs(muNeg_dz) < 15 
          && muNeg_nchi2Gl < 20 
          && muNeg_arbitrated==1 
          && muNeg_tracker==1){NegPass=1;}


      // Trigger10 : HLT_PAL2DoubleMu3_v1, Trigger 2 : HLT_PAL1DoubleMu0_HighQ_v1, Trigger 1 : HLT_PAL1DoubleMu0_v1
      // muPos_matches : HLT_PAL1DoubleMuOpen_v1
      //if((muPos_Trigger21==1 && muNeg_Trigger21==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      if(hbit1 == 1 && (muPos_Trigger22==1 && muNeg_Trigger22==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if(hbit1 == 1 && (muPos_Trigger2==1 && muNeg_Trigger2==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if((muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if((muPos_Trigger10==1 && muNeg_Trigger10==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

      // without trigger matched
      // if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

      //Eff loop for reco
      double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
      if(iSpec == 0) vars = JpsiPt;
      if(iSpec == 1) vars = fabs(JpsiRap);
      if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {     
        for(int j = 0; j < nBins; j++){
          if(iSpec == 0){
            bin1 = pt_bound[j]; bin2 = pt_bound[j+1];
            if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && TMath::Abs(JpsiRap) <= maxRap && TMath::Abs(JpsiRap) >= minRap) {
              hRecoDiMuon[j]->Fill(JpsiMass,RecWeight);
            }
          }
          if(iSpec == 1){ 
            bin1 = rap_bound[j]; bin2 = rap_bound[j+1];
            if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && JpsiPt >= minPt && JpsiPt <= maxPt) {
              hRecoDiMuon[j]->Fill(JpsiMass,RecWeight);
            }
          }
        }
      }
    } //rec tree loop ends

    //======================  File loop Starts ============================

    ///////////////////////////////////////////////////////////////////
    cout<< " adding "<<endl;
    char gtmp[512], gtmp1[512];
    char rtmp[512], rtmp1[512];

    for(int i = 0; i < nBins; i++){
      if(iSpec == 1) sprintf(gtmp,"hGenDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(gtmp,"hGenDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Pt_%0.1f_%0.1f.png",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Rap_%0.1f_%0.1f.png",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(rtmp,"hRecDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(rtmp,"hRecDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Pt_%0.1f_%0.1f.png",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Rap_%0.1f_%0.1f.png",rap_bound[i],rap_bound[i+1]);
      hGenDiMuon[i]->SetName(gtmp);
      hRecoDiMuon[i]->SetName(rtmp);
    }

    cout<<"Starts to calculate efficiency"<<endl;
    //dataFile<<""<<endl;
    //=====================Loop for eff========================================================================================//
    //define stuff here for error on weighted samples
    for(int i = 0; i < nBins; i++){
      int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.0);//2.95
      int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(4.0);//2.95

      int Rbinlow =hRecoDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
      int Rbinhi=hRecoDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

      genNo[i] = hGenDiMuon[i]->IntegralAndError(Gbinlow, Gbinhi, genErr[i]); 
      recoNo[i] = hRecoDiMuon[i]->IntegralAndError(Rbinlow, Rbinhi, recoErr[i]);
      //calculate Eff         
      if(genNo[i] == 0 || recoNo[i] == 0) {
        eff[i] = 0;
        effErr[i] = 0;
      }else{
        eff[i] = recoNo[i]/genNo[i]; 

        effErr[i] = recoNo[i]/genNo[i]*TMath::Sqrt(genErr[i]*genErr[i]/(genNo[i]*genNo[i]) + recoErr[i]*recoErr[i]/(recoNo[i]*recoNo[i]));

        //error without weight
        //dataFile<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< recoNo[i]  <<", Gen Jpsi : "<< genNo[i] <<endl;
        //dataFile<<" Eff ["<<i<<"] - "<< eff[i] <<" Error "<< effErr[i] <<endl;
        cout<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< recoNo[i]  <<", Gen Jpsi : "<< genNo[i] <<endl;
        cout<<" Eff ["<<i<<"] - "<< eff[i] <<" Error "<< effErr[i] <<endl;
      }
    }
    TH1F *hEff = new TH1F();
    int nEffBins = 0;
    if(iSpec == 0) {hEff = new TH1F("hEff","hEff;p_{T} GeV/c;Efficiency",nPtBins,pt_bound); nEffBins = nPtBins;}
    if(iSpec == 1) {hEff = new TH1F("hEff","hEff;y;Efficiency",nRapBins,rap_bound); nEffBins = nRapBins;}

    //dataFile<<"Efficiency"<<endl;
    for(int i = 0; i < nEffBins; i++){
      hEff->SetBinContent(i+1,eff[i]);
      hEff->SetBinError(i+1,effErr[i]);
      cout<<"Trying to measure eff vs "<<cSp[iSpec]<<endl;
      cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      dataFile<<eff[i]<<endl;
    }

    //dataFile<<""<<endl;
    //dataFile<<"Errors"<<endl;
    for(int i = 0; i < nEffBins; i++){
      hEff->SetBinContent(i+1,eff[i]);
      hEff->SetBinError(i+1,effErr[i]);
      cout<<"Trying to measure eff vs "<<cSp[iSpec]<<endl;
      cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      //dataFile<<effErr[i]<<endl;
    }


    outfile->cd();
    hEff->Draw();
    char tmp_histo[512];
    sprintf(tmp_histo,"hEff_%s",cSp[iSpec]);
    hEff->SetName(tmp_histo);
    hEff->Write();
    //dataFile<<""<<endl;
    //dataFile.close();
  }
  outfile->Write();
}
Пример #4
0
void dataLogFV(const char* format, va_list argList)
{
    dataFile().vprintf(format, argList);
}
Visualization::Abstract::DataSet* StructuredGridVTK::load(const std::vector<std::string>& args) const
	{
	/* Create the result data set: */
	Misc::SelfDestructPointer<DataSet> result(new DataSet);
	
	/* Open the input file: */
	Misc::File dataFile(args[0].c_str(),"rb");
	
	/* Read the header line: */
	char line[258];
	dataFile.gets(line,sizeof(line));
	int vtkVersionMajor,vtkVersionMinor;
	if(sscanf(line,"# vtk DataFile Version %d.%d",&vtkVersionMajor,&vtkVersionMinor)!=2)
		Misc::throwStdErr("StructuredGridVTK::load: Input file %s is not a VTK data file",args[0].c_str());
	if(vtkVersionMajor>3||(vtkVersionMajor==3&&vtkVersionMinor>0))
		Misc::throwStdErr("StructuredGridVTK::load: VTK data file %s is unsupported version %d.%d",args[0].c_str(),vtkVersionMajor,vtkVersionMinor);
	
	/* Ignore the comment line: */
	dataFile.gets(line,sizeof(line));
	
	/* Read the file storage format: */
	bool binary=false;
	dataFile.gets(line,sizeof(line));
	if(strncasecmp(line,"BINARY",6)==0&&isspace(line[6]))
		binary=true;
	else if(strncasecmp(line,"ASCII",5)!=0||!isspace(line[5]))
		Misc::throwStdErr("StructuredGridVTK::load: VTK data file %s has unrecognized storage type",args[0].c_str());
	
	/* Read the grid type: */
	dataFile.gets(line,sizeof(line));
	if(strncasecmp(line,"DATASET",7)==0&&isspace(line[7]))
		{
		char* typeStart;
		for(typeStart=line+8;*typeStart!='\0'&&isspace(*typeStart);++typeStart)
			;
		char* typeEnd;
		for(typeEnd=typeStart;*typeEnd!='\0'&&!isspace(*typeEnd);++typeEnd)
			;
		*typeEnd='\0';
		if(strcasecmp(typeStart,"STRUCTURED_GRID")!=0)
			Misc::throwStdErr("StructuredGridVTK::load: VTK data file %s contains wrong grid type %s",args[0].c_str(),typeStart);
		}
	else
		Misc::throwStdErr("StructuredGridVTK::load: invalid grid type in VTK data file %s",args[0].c_str());
	
	/* Read the grid size: */
	DS::Index numVertices;
	dataFile.gets(line,sizeof(line));
	if(sscanf(line,"DIMENSIONS %d %d %d",&numVertices[0],&numVertices[1],&numVertices[2])!=3)
		Misc::throwStdErr("StructuredGridVTK::load: invalid grid dimension in VTK data file %s",args[0].c_str());
	
	/* Initialize the data set: */
	DS& dataSet=result->getDs();
	dataSet.setGrid(numVertices);
	
	/* Read the grid vertices: */
	dataFile.gets(line,sizeof(line));
	int totalNumVertices;
	char vertexScalarType[10];
	if(sscanf(line,"POINTS %d %10s",&totalNumVertices,vertexScalarType)!=2)
		Misc::throwStdErr("StructuredGridVTK::load: invalid grid point definition in VTK data file %s",args[0].c_str());
	if(totalNumVertices!=numVertices.calcIncrement(-1))
		Misc::throwStdErr("StructuredGridVTK::load: mismatching number of grid points in VTK data file %s",args[0].c_str());
	if(strcasecmp(vertexScalarType,"float")!=0&&strcasecmp(vertexScalarType,"double")!=0)
		Misc::throwStdErr("StructuredGridVTK::load: unsupported grid point scalar type %s in VTK data file %s",vertexScalarType,args[0].c_str());
	std::cout<<"Reading grid vertices...   0%"<<std::flush;
	DS::Index index(0);
	while(index[2]<numVertices[2])
		{
		/* Read the next line: */
		dataFile.gets(line,sizeof(line));
		
		/* Parse the line: */
		DS::Point& vertex=dataSet.getVertexPosition(index);
		if(sscanf(line,"%f %f %f",&vertex[0],&vertex[1],&vertex[2])!=3)
			Misc::throwStdErr("StructuredGridVTK::load: Invalid vertex position in VTK data file %s",args[0].c_str());
		
		/* Go to the next vertex: */
		int incDim;
		for(incDim=0;incDim<2&&index[incDim]==numVertices[incDim]-1;++incDim)
			index[incDim]=0;
		++index[incDim];
		if(incDim==2)
			std::cout<<"\b\b\b\b"<<std::setw(3)<<(index[2]*100)/numVertices[2]<<"%"<<std::flush;
		}
	std::cout<<"\b\b\b\bdone"<<std::endl;
	
	/* Finalize the grid structure: */
	std::cout<<"Finalizing grid structure..."<<std::flush;
	dataSet.finalizeGrid();
	std::cout<<" done"<<std::endl;
	
	/* Initialize the result data set's data value: */
	DataValue& dataValue=result->getDataValue();
	dataValue.initialize(&dataSet,0);
	
	/* Read all point attributes stored in the file: */
	while(true)
		{
		/* Read the attribute header line: */
		dataFile.gets(line,sizeof(line));
		
		/* Check if there is another attribute: */
		int totalNumAttributes;
		if(sscanf(line,"POINT_DATA %d",&totalNumAttributes)!=1)
			break;
		if(totalNumAttributes!=numVertices.calcIncrement(-1))
			Misc::throwStdErr("StructuredGridVTK::load: mismatching number of point attributes in VTK data file %s",args[0].c_str());
		
		/* Read the attribute type and name: */
		dataFile.gets(line,sizeof(line));
		char attributeType[40];
		char attributeName[80];
		char attributeScalarType[10];
		if(sscanf(line,"%40s %80s %10s",attributeType,attributeName,attributeScalarType)!=3)
			Misc::throwStdErr("StructuredGridVTK::load: invalid point attribute definition in VTK data file %s",args[0].c_str());
		
		bool vectorAttribute=false;
		if(strcasecmp(attributeType,"VECTORS")==0)
			vectorAttribute=true;
		else if(strcasecmp(attributeType,"SCALARS")!=0)
			Misc::throwStdErr("StructuredGridVTK::load: unsupported point attribute type %s in VTK data file %s",attributeType,args[0].c_str());
		if(strcasecmp(attributeScalarType,"float")!=0&&strcasecmp(attributeScalarType,"double")!=0)
			Misc::throwStdErr("StructuredGridVTK::load: unsupported point attribute scalar type %s in VTK data file %s",attributeScalarType,args[0].c_str());
		
		/* Create the new attribute: */
		int sliceIndex=dataSet.getNumSlices();
		if(vectorAttribute)
			{
			/* Add another vector variable to the data value: */
			int vectorVariableIndex=dataValue.getNumVectorVariables();
			dataValue.addVectorVariable(attributeName);

			/* Add four new slices to the data set (3 components plus magnitude): */
			char variableName[256];
			for(int i=0;i<3;++i)
				{
				dataSet.addSlice();
				snprintf(variableName,sizeof(variableName),"%s %c",attributeName,'X'+i);
				dataValue.addScalarVariable(variableName);
				dataValue.setVectorVariableScalarIndex(vectorVariableIndex,i,sliceIndex+i);
				}
			dataSet.addSlice();
			snprintf(variableName,sizeof(variableName),"%s Magnitude",attributeName);
			dataValue.addScalarVariable(variableName);
			}
		else
			{
			/* Add another slice to the data set: */
			dataSet.addSlice();
			
			/* Add another scalar variable to the data value: */
			dataValue.addScalarVariable(attributeName);
			}
		
		/* Read all vertex attributes: */
		std::cout<<"Reading "<<attributeName<<" point attributes...   0%"<<std::flush;
		DS::Index index(0);
		while(index[2]<numVertices[2])
			{
			/* Read the next line: */
			dataFile.gets(line,sizeof(line));
			
			/* Parse the line: */
			if(vectorAttribute)
				{
				/* Read the vector attribute in Cartesian coordinates: */
				DataValue::VVector vector;
				if(sscanf(line,"%lf %lf %lf",&vector[0],&vector[1],&vector[2])!=3)
					Misc::throwStdErr("StructuredGridVTK::load: Invalid vector attribute in in VTK data file %s",args[0].c_str());
				
				/* Store the vector's components and magnitude: */
				for(int i=0;i<3;++i)
					dataSet.getVertexValue(sliceIndex+i,index)=vector[i];
				dataSet.getVertexValue(sliceIndex+3,index)=DataValue::VScalar(Geometry::mag(vector));
				}
			else
				{
				if(sscanf(line,"%lf",&dataSet.getVertexValue(sliceIndex,index))!=1)
					Misc::throwStdErr("StructuredGridVTK::load: Invalid scalar attribute in in VTK data file %s",args[0].c_str());
				}
			
			/* Go to the next vertex: */
			int incDim;
			for(incDim=0;incDim<2&&index[incDim]==numVertices[incDim]-1;++incDim)
				index[incDim]=0;
			++index[incDim];
			if(incDim==2)
				std::cout<<"\b\b\b\b"<<std::setw(3)<<(index[2]*100)/numVertices[2]<<"%"<<std::flush;
			}
		std::cout<<"\b\b\b\bdone"<<std::endl;
		}
	
	/* Return the result data set: */
	return result.releaseTarget();
	}
Пример #6
0
int main(int argc, char *argv[])
{
    int debugMode = DEBUGMODE;


    if(debugMode)
    {

    } else {
        qInstallMessageHandler(myMessageOutputDisable);

    }

    QDEBUG() << "number of arguments:" << argc;
    QStringList args;
    QDEBUGVAR(RAND_MAX);
    if(argc > 1) {
        QCoreApplication a(argc, argv);
        args = a.arguments();

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();



        QDEBUG() << "Running command line mode.";

        Packet sendPacket;
        sendPacket.init();
        QString outBuilder;

        QTextStream o(&outBuilder);


        QTextStream out(stdout);

        QDate vDate = QDate::fromString(QString(__DATE__).simplified(), "MMM d yyyy");
        QCoreApplication::setApplicationName("Packet Sender");
        QCoreApplication::setApplicationVersion("version " + vDate.toString("yyyy-MM-dd"));

        QCommandLineParser parser;
        parser.setApplicationDescription("Packet Sender is a Network TCP and UDP Test Utility by Dan Nagle\nSee http://PacketSender.com/ for more information.");
        parser.addHelpOption();
        parser.addVersionOption();

        // A boolean option with a single name (-p)
        QCommandLineOption quietOption(QStringList() << "q" << "quiet", "Quiet mode. Only output received data.");
        parser.addOption(quietOption);


        QCommandLineOption hexOption(QStringList() << "x" << "hex", "Parse data as hex (default).");
        parser.addOption(hexOption);

        QCommandLineOption asciiOption(QStringList() << "a" << "ascii", "Parse data as mixed-ascii (like the GUI).");
        parser.addOption(asciiOption);

        QCommandLineOption pureAsciiOption(QStringList() << "A" << "ASCII", "Parse data as pure ascii (no \\xx translation).");
        parser.addOption(pureAsciiOption);

        // An option with a value
        QCommandLineOption waitOption(QStringList() << "w" << "wait",
                "Wait up to <milliseconds> for a response after sending. Zero means do not wait (Default).",
                "milliseconds");
        parser.addOption(waitOption);

        // An option with a value
        QCommandLineOption fileOption(QStringList() << "f" << "file",
                "Send contents of specified path. Max 1024 for UDP, 10 MiB for TCP.",
                "path");
        parser.addOption(fileOption);


        // An option with a value
        QCommandLineOption bindPortOption(QStringList() << "b" << "bind",
                "Bind port. Default is 0 (dynamic).",
                "port");
        parser.addOption(bindPortOption);


        QCommandLineOption tcpOption(QStringList() << "t" << "tcp", "Send TCP (default).");
        parser.addOption(tcpOption);

        // A boolean option with multiple names (-f, --force)
        QCommandLineOption udpOption(QStringList() << "u" << "udp", "Send UDP.");
        parser.addOption(udpOption);

        // An option with a value
        QCommandLineOption nameOption(QStringList() << "n" << "name",
                                      "Send previously saved packet named <name>. Other options overrides saved packet parameters.",
                                      "name");
        parser.addOption(nameOption);


        parser.addPositionalArgument("address", "Destination address. Optional for saved packet.");
        parser.addPositionalArgument("port", "Destination port. Optional for saved packet.");
        parser.addPositionalArgument("data", "Data to send. Optional for saved packet.");


        // Process the actual command line arguments given by the user
        parser.process(a);

        const QStringList args = parser.positionalArguments();

        bool quiet = parser.isSet(quietOption);
        bool hex = parser.isSet(hexOption);
        bool mixedascii = parser.isSet(asciiOption);
        bool ascii = parser.isSet(pureAsciiOption);
        unsigned int wait = parser.value(waitOption).toUInt();
        unsigned int bind = parser.value(bindPortOption).toUInt();
        bool tcp = parser.isSet(tcpOption);
        bool udp = parser.isSet(udpOption);
        bool ipv6  = false;

        QString name = parser.value(nameOption);

        QString filePath = parser.value(fileOption);


        QString address = "";
        unsigned int port = 0;

        int argssize = args.size();
        QString data, dataString;
        data.clear();
        dataString.clear();
        if(argssize >= 1) {
            address = args[0];
        }
        if(argssize >= 2) {
            port = args[1].toUInt();
        }
        if(argssize >= 3) {
            data = (args[2]);
        }

        //check for invalid options..

        if(argssize > 3) {
            OUTIF() << "Warning: Extra parameters detected. Try surrounding your data with quotes.";
        }

        if(hex && mixedascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            mixedascii = false;
        }

        if(hex && ascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            ascii = false;
        }

        if(mixedascii && ascii) {
            OUTIF() << "Warning: both mixed ascii and pure ascii set. Defaulting to pure ascii.";
            mixedascii = false;
        }

        if(tcp && udp) {
            OUTIF() << "Warning: both TCP and UDP set. Defaulting to TCP.";
            udp = false;
        }

        if(!filePath.isEmpty() && !QFile::exists(filePath)) {
            OUTIF() << "Error: specified path "<< filePath <<" does not exist.";
            filePath.clear();
            OUTPUT();
            return -1;
        }

        //bind is now default 0

        if(!bind && parser.isSet(bindPortOption)) {
            OUTIF() << "Warning: Binding to port zero is dynamic.";
        }


        if(!port && name.isEmpty()) {
            OUTIF() << "Warning: Sending to port zero.";
        }

        //set default choices
        if(!hex && !ascii && !mixedascii) {
            hex = true;
        }

        if(!tcp && !udp) {
            tcp = true;
        }

        //Create the packet to send.
        if(!name.isEmpty()) {
            sendPacket = Packet::fetchFromDB(name);
            if(sendPacket.name.isEmpty()) {
                OUTIF() << "Error: Saved packet \""<< name <<"\" not found.";
                OUTPUT();
                return -1;
            } else {
                if(data.isEmpty()) {
                    data  = sendPacket.hexString;
                    hex = true;
                    ascii = false;
                    mixedascii = false;
                }
                if(!port) {
                    port  = sendPacket.port;
                }
                if(address.isEmpty()) {
                    address  = sendPacket.toIP;
                }
                if(!parser.isSet(tcpOption) && !parser.isSet(udpOption)) {

                    if(sendPacket.tcpOrUdp.toUpper() == "TCP") {
                        tcp=true;
                        udp = false;
                    } else {
                        tcp=false;
                        udp = true;
                    }

                }

            }

        }

        if(!parser.isSet(bindPortOption)) {
            bind = 0;
        }

        if(!filePath.isEmpty() && QFile::exists(filePath)) {
            QFile dataFile(filePath);
            if(dataFile.open(QFile::ReadOnly)) {

                if(tcp) {
                    QByteArray dataArray = dataFile.read(1024*1024*10);;
                    dataString = Packet::byteArrayToHex(dataArray);
                } else {

                    QByteArray dataArray = dataFile.read(1024);
                    dataString = Packet::byteArrayToHex(dataArray);
                }

                //data format is raw.
                ascii = 0;
                hex = 0;
                mixedascii = 0;

            }
        }



        QDEBUGVAR(argssize);
        QDEBUGVAR(quiet);
        QDEBUGVAR(hex);
        QDEBUGVAR(mixedascii);
        QDEBUGVAR(ascii);
        QDEBUGVAR(address);
        QDEBUGVAR(port);
        QDEBUGVAR(wait);
        QDEBUGVAR(bind);
        QDEBUGVAR(tcp);
        QDEBUGVAR(udp);
        QDEBUGVAR(name);
        QDEBUGVAR(data);
        QDEBUGVAR(filePath);

        //NOW LETS DO THIS!

        if(ascii) { //pure ascii
            dataString = Packet::byteArrayToHex(data.toLatin1());
        }

        if(hex) { //hex
            dataString = Packet::byteArrayToHex(Packet::HEXtoByteArray(data));
        }
        if(mixedascii) { //mixed ascii
            dataString = Packet::ASCIITohex(data);
        }

        if(dataString.isEmpty()) {
            OUTIF() << "Warning: No data to send. Is your formatting correct?";
        }

        QHostAddress addy;
        if(!addy.setAddress(address)) {
            QHostInfo info = QHostInfo::fromName(address);
            if (info.error() != QHostInfo::NoError)
            {
                OUTIF() << "Error: Could not resolve address:" + address;
                OUTPUT();
                return -1;
            } else {
                addy = info.addresses().at(0);
                address = addy.toString();
            }
        }

        QHostAddress theAddress(address);
        if (QAbstractSocket::IPv6Protocol == theAddress.protocol())
        {
           QDEBUG() << "Valid IPv6 address.";
           ipv6 = true;
        }


        QByteArray sendData = sendPacket.HEXtoByteArray(dataString);
        QByteArray recvData;
        recvData.clear();
        int bytesWriten = 0;
        int bytesRead = 0;


        if(tcp) {
            QTcpSocket sock;


            if(ipv6) {
                sock.bind(QHostAddress::AnyIPv6, bind);
            } else {
                sock.bind(QHostAddress::AnyIPv4, bind);
            }
            sock.connectToHost(addy, port);
            sock.waitForConnected(1000);
            if(sock.state() == QAbstractSocket::ConnectedState)
            {
                OUTIF() << "TCP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;
                bytesWriten = sock.write(sendData);
                sock.waitForBytesWritten(1000);
                //OUTIF() << "Sent:" << Packet::byteArrayToHex(sendData);
                if(wait) {
                    sock.waitForReadyRead(wait);
                    recvData = sock.readAll();
                    bytesRead = recvData.size();
                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
                sock.disconnectFromHost();
                sock.waitForDisconnected(1000);
                sock.close();

                OUTPUT();
                return bytesWriten;


            } else {
                OUTIF() << "Error: Failed to connect to " << address;

                OUTPUT();
                return -1;
            }


        } else {
            QUdpSocket sock;
            if(ipv6) {
                if(!sock.bind(QHostAddress::AnyIPv6, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            } else {
                if(!sock.bind(QHostAddress::AnyIPv4, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            }
            OUTIF() << "UDP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;

            bytesWriten = sock.writeDatagram(sendData, addy, port);
            //OUTIF() << "Wrote " << bytesWriten << " bytes";
            sock.waitForBytesWritten(1000);

            if(wait) {
                sock.waitForReadyRead(wait);

                if(sock.hasPendingDatagrams()) {
                    QHostAddress sender;
                    quint16 senderPort;
                    recvData.resize(sock.pendingDatagramSize());

                    sock.readDatagram(recvData.data(), recvData.size(),
                                            &sender, &senderPort);

                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
            }

            sock.close();

            OUTPUT();
            return bytesWriten;

        }





        OUTPUT();



    } else {
        QApplication a(argc, argv);

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();

        QFile file(":/packetsender.css");
        if(file.open(QFile::ReadOnly)) {
           QString StyleSheet = QLatin1String(file.readAll());
         //  qDebug() << "stylesheet: " << StyleSheet;
           a.setStyleSheet(StyleSheet);
        }

        MainWindow w;


        w.show();

        return a.exec();

    }



    return 0;

}
Пример #7
0
int main( int argc, char * * argv )
{
	// initialize memory managers
	MemoryManager::init();
	NotePlayHandleManager::init();

	// intialize RNG
	srand( getpid() + time( 0 ) );

	disable_denormals();

	bool coreOnly = false;
	bool fullscreen = true;
	bool exitAfterImport = false;
	bool allowRoot = false;
	bool renderLoop = false;
	bool renderTracks = false;
	QString fileToLoad, fileToImport, renderOut, profilerOutputFile;

	// first of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--help"    || arg == "-h" ||
		    arg == "--version" || arg == "-v" ||
		    arg == "--render"  || arg == "-r" )
		{
			coreOnly = true;
		}
		else if( arg == "--rendertracks" )
		{
			coreOnly = true;
			renderTracks = true;
		}
		else if( arg == "--allowroot" )
		{
			allowRoot = true;
		}
		else if( arg == "-geometry" )
		{
			// option -geometry is filtered by Qt later,
			// so we need to check its presence now to
			// determine, if the application should run in
			// fullscreen mode (default, no -geometry given).
			fullscreen = false;
		}
	}

#ifndef LMMS_BUILD_WIN32
	if ( ( getuid() == 0 || geteuid() == 0 ) && !allowRoot )
	{
		printf( "LMMS cannot be run as root.\nUse \"--allowroot\" to override.\n\n" );
		return EXIT_FAILURE;
	}	
#endif

	QCoreApplication * app = coreOnly ?
			new QCoreApplication( argc, argv ) :
					new QApplication( argc, argv ) ;

	Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality );
	ProjectRenderer::OutputSettings os( 44100, false, 160,
						ProjectRenderer::Depth_16Bit );
	ProjectRenderer::ExportFileFormats eff = ProjectRenderer::WaveFile;

	// second of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--version" || arg == "-v" )
		{
			printVersion( argv[0] );
			return EXIT_SUCCESS;
		}
		else if( arg == "--help" || arg  == "-h" )
		{
			printHelp();
			return EXIT_SUCCESS;
		}
		else if( arg == "--upgrade" || arg == "-u" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			DataFile dataFile( QString::fromLocal8Bit( argv[i] ) );

			if( argc > i+1 ) // output file specified
			{
				dataFile.writeFile( QString::fromLocal8Bit( argv[i+1] ) );
			}
			else // no output file specified; use stdout
			{
				QTextStream ts( stdout );
				dataFile.write( ts );
				fflush( stdout );
			}

			return EXIT_SUCCESS;
		}
		else if( arg == "--allowroot" )
		{
			// Ignore, processed earlier
#ifdef LMMS_BUILD_WIN32
			if( allowRoot )
			{
				printf( "\nOption \"--allowroot\" will be ignored on this platform.\n\n" );
			}
#endif
			
		}
		else if( arg == "--dump" || arg == "-d" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			QFile f( QString::fromLocal8Bit( argv[i] ) );
			f.open( QIODevice::ReadOnly );
			QString d = qUncompress( f.readAll() );
			printf( "%s\n", d.toUtf8().constData() );

			return EXIT_SUCCESS;
		}
		else if( arg == "--render" || arg == "-r" || arg == "--rendertracks" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToLoad = QString::fromLocal8Bit( argv[i] );
			renderOut = fileToLoad;
		}
		else if( arg == "--loop" || arg == "-l" )
		{
			renderLoop = true;
		}
		else if( arg == "--output" || arg == "-o" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			renderOut = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--format" || arg == "-f" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output format specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ext = QString( argv[i] );

			if( ext == "wav" )
			{
				eff = ProjectRenderer::WaveFile;
			}
#ifdef LMMS_HAVE_OGGVORBIS
			else if( ext == "ogg" )
			{
				eff = ProjectRenderer::OggFile;
			}
#endif
			else
			{
				printf( "\nInvalid output format %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--samplerate" || arg == "-s" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo samplerate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			sample_rate_t sr = QString( argv[i] ).toUInt();
			if( sr >= 44100 && sr <= 192000 )
			{
				os.samplerate = sr;
			}
			else
			{
				printf( "\nInvalid samplerate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--bitrate" || arg == "-b" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo bitrate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int br = QString( argv[i] ).toUInt();

			if( br >= 64 && br <= 384 )
			{
				os.bitrate = br;
			}
			else
			{
				printf( "\nInvalid bitrate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg =="--float" || arg == "-a" )
		{
			os.depth = ProjectRenderer::Depth_32Bit;
		}
		else if( arg == "--interpolation" || arg == "-i" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo interpolation method specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ip = QString( argv[i] );

			if( ip == "linear" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_Linear;
			}
			else if( ip == "sincfastest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincFastest;
			}
			else if( ip == "sincmedium" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincMedium;
			}
			else if( ip == "sincbest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincBest;
			}
			else
			{
				printf( "\nInvalid interpolation method %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--oversampling" || arg == "-x" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo oversampling specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int o = QString( argv[i] ).toUInt();

			switch( o )
			{
				case 1:
		qs.oversampling = Mixer::qualitySettings::Oversampling_None;
		break;
				case 2:
		qs.oversampling = Mixer::qualitySettings::Oversampling_2x;
		break;
				case 4:
		qs.oversampling = Mixer::qualitySettings::Oversampling_4x;
		break;
				case 8:
		qs.oversampling = Mixer::qualitySettings::Oversampling_8x;
		break;
				default:
				printf( "\nInvalid oversampling %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--import" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo file specified for importing.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToImport = QString::fromLocal8Bit( argv[i] );

			// exit after import? (only for debugging)
			if( QString( argv[i + 1] ) == "-e" )
			{
				exitAfterImport = true;
				++i;
			}
		}
		else if( arg == "--profile" || arg == "-p" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo profile specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			profilerOutputFile = QString::fromLocal8Bit( argv[1] );
		}
		else
		{
			if( argv[i][0] == '-' )
			{
				printf( "\nInvalid option %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
			fileToLoad = QString::fromLocal8Bit( argv[i] );
		}
	}


	ConfigManager::inst()->loadConfigFile();

	// set language
	QString pos = ConfigManager::inst()->value( "app", "language" );
	if( pos.isEmpty() )
	{
		pos = QLocale::system().name().left( 2 );
	}

#ifdef LMMS_BUILD_WIN32
#undef QT_TRANSLATIONS_DIR
#define QT_TRANSLATIONS_DIR ConfigManager::inst()->localeDir()
#endif

#ifdef QT_TRANSLATIONS_DIR
	// load translation for Qt-widgets/-dialogs
	loadTranslation( QString( "qt_" ) + pos,
					QString( QT_TRANSLATIONS_DIR ) );
#endif
	// load actual translation for LMMS
	loadTranslation( pos );


	// try to set realtime priority
#ifdef LMMS_BUILD_LINUX
#ifdef LMMS_HAVE_SCHED_H
#ifndef __OpenBSD__
	struct sched_param sparam;
	sparam.sched_priority = ( sched_get_priority_max( SCHED_FIFO ) +
				sched_get_priority_min( SCHED_FIFO ) ) / 2;
	if( sched_setscheduler( 0, SCHED_FIFO, &sparam ) == -1 )
	{
		printf( "Notice: could not set realtime priority.\n" );
	}
#endif
#endif
#endif

#ifdef LMMS_BUILD_WIN32
	if( !SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
	{
		printf( "Notice: could not set high priority.\n" );
	}
#endif

	// if we have an output file for rendering, just render the song
	// without starting the GUI
	if( !renderOut.isEmpty() )
	{
		Engine::init( true );

		QFileInfo fileInfo( fileToLoad );
		if ( !fileInfo.exists() )
		{
			printf("The file %s does not exist!\n", fileToLoad.toStdString().c_str());
			exit( 1 );
		}

		printf( "Loading project...\n" );
		Engine::getSong()->loadProject( fileToLoad );
		printf( "Done\n" );

		Engine::getSong()->setExportLoop( renderLoop );

		// when rendering multiple tracks, renderOut is a directory
		// otherwise, it is a file, so we need to append the file extension
		if ( !renderTracks )
		{
			renderOut = baseName( renderOut ) +
				ProjectRenderer::getFileExtensionFromFormat(eff);
		}

		// create renderer
		RenderManager * r = new RenderManager( qs, os, eff, renderOut );
		QCoreApplication::instance()->connect( r,
				SIGNAL( finished() ), SLOT( quit() ) );

		// timer for progress-updates
		QTimer * t = new QTimer( r );
		r->connect( t, SIGNAL( timeout() ),
				SLOT( updateConsoleProgress() ) );
		t->start( 200 );

		if( profilerOutputFile.isEmpty() == false )
		{
			Engine::mixer()->profiler().setOutputFile( profilerOutputFile );
		}

		// start now!
		if ( renderTracks )
		{
			r->renderTracks();
		}
		else
		{
			r->renderProject();
		}
	}
	else // otherwise, start the GUI
	{
		new GuiApplication();

		// re-intialize RNG - shared libraries might have srand() or
		// srandom() calls in their init procedure
		srand( getpid() + time( 0 ) );

		// recover a file?
		QString recoveryFile = ConfigManager::inst()->recoveryFile();

		if( QFileInfo(recoveryFile).exists() &&
			QMessageBox::question( gui->mainWindow(), MainWindow::tr( "Project recovery" ),
						MainWindow::tr( "It looks like the last session did not end properly. "
										"Do you want to recover the project of this session?" ),
						QMessageBox::Yes | QMessageBox::No ) == QMessageBox::Yes )
		{
			fileToLoad = recoveryFile;
		}

		// we try to load given file
		if( !fileToLoad.isEmpty() )
		{
			gui->mainWindow()->show();
			if( fullscreen )
			{
				gui->mainWindow()->showMaximized();
			}

			if( fileToLoad == recoveryFile )
			{
				Engine::getSong()->createNewProjectFromTemplate( fileToLoad );
			}
			else
			{
				Engine::getSong()->loadProject( fileToLoad );
			}
		}
		else if( !fileToImport.isEmpty() )
		{
			ImportFilter::import( fileToImport, Engine::getSong() );
			if( exitAfterImport )
			{
				return EXIT_SUCCESS;
			}

			gui->mainWindow()->show();
			if( fullscreen )
			{
				gui->mainWindow()->showMaximized();
			}
		}
		else
		{

		// If enabled, open last project if there is one. Else, create
		// a new one.
		if( ConfigManager::inst()->
				value( "app", "openlastproject" ).toInt() &&
		!ConfigManager::inst()->recentlyOpenedProjects().isEmpty() )
		{
			QString f = ConfigManager::inst()->
						recentlyOpenedProjects().first();
			QFileInfo recentFile( f );

			if ( recentFile.exists() )
			{
				Engine::getSong()->loadProject( f );
			}
			else
			{
				Engine::getSong()->createNewProject();
			}
		}
		else
		{
		Engine::getSong()->createNewProject();
		}

			// [Settel] workaround: showMaximized() doesn't work with
			// FVWM2 unless the window is already visible -> show() first
			gui->mainWindow()->show();
			if( fullscreen )
			{
				gui->mainWindow()->showMaximized();
			}
		}
	}

	const int ret = app->exec();
	delete app;

	// cleanup memory managers
	MemoryManager::cleanup();

	return ret;
}
Пример #8
0
bool CIsoSurfaceBase::save( wxString filename ) const
{
#if 0
    m_dh->printDebug(_T("start saving vtk file"), 1);
    wxFile dataFile;
    wxFileOffset nSize = 0;

    if (dataFile.Open(filename))
    {
        //      nSize = dataFile.Length();
        //      if (nSize == wxInvalidOffset) return false;
    }
    else
    {
        return false;
    }

    m_dh->printDebug(_T("start writing file)"));
    dataFile.write("# vtk DataFile Version 2.0\n");
    dataFile.write("generated using FiberNavigator\n");
    dataFile.write("ASCII\n");

    dataFile.write("POINT_DATA %d float\n", m_tMesh->getNumVertices());
    for(int i=0; i< m_tMesh->getNumVertices(); ++i)
    {
        point = m_tMesh->getVertex(i);
        dataFile.write("%d %d %d\n", point.x, point.y, point.z);
    }

    dataFile.write("CELLS %d %d\n", m_tMesh->getNumTriangles(), m_tMesh->getNumTriangles()*4);
    for(int i=0; i< m_tMesh->getNumTriangles(); ++i)
    {
        triangleEdges = m_tMesh->getTriangle(i);
        dataFile.write("3 %d %d %d\n", triangleEdges.pointID[0],
                triangleEdges.pointID[1], triangleEdges.pointID[2]);
    }
    dataFile.write("CELL_TYPES");
    for(int i=0; i< m_tMesh->getNumTriangles(); ++i)
    {
        dataFile.write("3\n");
    }
    return true;
#else
    char* c_file;
    c_file = (char*) malloc( filename.length() + 1 );
    strcpy( c_file, (const char*) filename.mb_str( wxConvUTF8 ) );

    //m_dh->printDebug(_T("start saving vtk file"), 1);
    std::ofstream dataFile( c_file );

    if ( dataFile )
    {
        std::cout << "opening file" << std::endl;
        //      nSize = dataFile.Length();
        //      if (nSize == wxInvalidOffset) return false;
    }
    else
    {
        std::cout << "open file failed: " << filename.wx_str() << std::endl;
        return false;
    }

    // TODO selection iso use good version
    //m_dh->printDebug( _T("start writing file)"), 1 );
    dataFile << ( "# vtk DataFile Version 2.0\n" );
    dataFile << ( "generated using FiberNavigator\n" );
    dataFile << ( "ASCII\n" );

    Triangle triangleEdges;
    Vector point;
    dataFile << "POINT_DATA " << m_tMesh->getNumVertices() << " float\n";
    for ( int i = 0; i < m_tMesh->getNumVertices(); ++i )
    {
        point = m_tMesh->getVertex( i );
        dataFile << point.x << " " << point.y << " " << point.z << "\n";
    }

    dataFile << "CELLS " << m_tMesh->getNumTriangles() << " " << m_tMesh->getNumTriangles() * 4;
    for ( int i = 0; i < m_tMesh->getNumTriangles(); ++i )
    {
        triangleEdges = m_tMesh->getTriangle( i );
        dataFile << "3 " << triangleEdges.pointID[0] << " " << triangleEdges.pointID[1] << " "
                << triangleEdges.pointID[2] << "\n";
    }
    dataFile << "CELL_TYPES\n";
    for ( int i = 0; i < m_tMesh->getNumTriangles(); ++i )
    {
        dataFile << "3\n";
    }
    std::cout << " saving  done" << std::endl;
    return true;

#endif
}
Пример #9
0
bool WRF::readWRF(const char* filename) {

	// We are writing 4D data, a 2 x 6 x 12 lvl-lat-lon grid, with 2
	// timesteps of data.

	// Return this code to the OS in case of failure.
	static const int NC_ERR = 2;

   // These arrays will hold the data we will read in. We will only
   // need enough space to hold one timestep of data; one record.
   /* float uwind_in[NLVL][NLAT][NLON+1];
   float vwind_in[NLVL][NLAT+1][NLON];
   float wwind_in[NLVL+1][NLAT][NLON];
   float dbz_in[NLVL][NLAT][NLON];
   float ph_in[NLVL+1][NLAT][NLON];
   float phb_in[NLVL+1][NLAT][NLON]; */
   
   // Change the error behavior of the netCDF C++ API by creating an
   // NcError object. Until it is destroyed, this NcError object will
   // ensure that the netCDF C++ API returns error codes on any
   // failure, prints an error message, and leaves any other error
   // handling to the calling program. In the case of this example, we
   // just exit with an NC_ERR error code.
   NcError err(NcError::verbose_nonfatal);

   // Open the file.
   NcFile dataFile(filename, NcFile::ReadOnly);

   // Check to see if the file was opened.
   if(!dataFile.is_valid())
      return NC_ERR;

   // Get pointers to the latitude and longitude variables.
   NcVar *latVar, *lonVar;
   if (!(latVar = dataFile.get_var("XLAT")))
      return NC_ERR;
   if (!(lonVar = dataFile.get_var("XLONG")))
      return NC_ERR;

   // Get pointers to the pressure and temperature variables.
   NcVar *uwindVar, *vwindVar, *wwindVar, *dbzVar, *phVar, *phbVar;
   if (!(uwindVar = dataFile.get_var("U")))
      return NC_ERR;
   if (!(vwindVar  = dataFile.get_var("V")))
      return NC_ERR;
   if (!(wwindVar = dataFile.get_var("W")))
      return NC_ERR;
   if (!(dbzVar  = dataFile.get_var("REFL_10CM")))
      return NC_ERR;
   if (!(phVar  = dataFile.get_var("PH")))
      return NC_ERR;
   if (!(phbVar  = dataFile.get_var("PHB")))
      return NC_ERR;
   
   // Read the data. Since we know the contents of the file we know
   // that the data arrays in this program are the correct size to
   // hold one timestep. 
   for (int rec = 0; rec < NREC; rec++)
   {
      // Read the data one record at a time.
      if (!latVar->set_cur(rec, 0, 0))
 	 return NC_ERR;
      if (!lonVar->set_cur(rec, 0, 0))
 	 return NC_ERR;
      if (!uwindVar->set_cur(rec, 0, 0, 0))
	 return NC_ERR;
      if (!vwindVar->set_cur(rec, 0, 0, 0))
	 return NC_ERR;
      if (!wwindVar->set_cur(rec, 0, 0, 0))
	 return NC_ERR;
      if (!dbzVar->set_cur(rec, 0, 0, 0))
	 return NC_ERR;
      if (!phVar->set_cur(rec, 0, 0, 0))
	 return NC_ERR;
      if (!phbVar->set_cur(rec, 0, 0, 0))
	 return NC_ERR;
	 
      // Get the lat/lon data from the file.
      if (!latVar->get(lats, 1, NLAT, NLON))
	   return NC_ERR;
      if (!lonVar->get(lons, 1, NLAT, NLON))
       return NC_ERR;
	 
      // Get 1 record of NLVL by NLAT by NLON values for each variable.
      if (!uwindVar->get(uwind_in, 1, NLVL, NLAT, NLON+1))
	 return NC_ERR;
      if (!vwindVar->get(vwind_in, 1, NLVL, NLAT+1, NLON))
	 return NC_ERR;
      if (!wwindVar->get(wwind_in, 1, NLVL+1, NLAT, NLON))
	 return NC_ERR;
      if (!dbzVar->get(dbz_in, 1, NLVL, NLAT, NLON))
	 return NC_ERR;
      if (!phVar->get(ph_in, 1, NLVL+1, NLAT, NLON))
	 return NC_ERR;
      if (!phbVar->get(phb_in, 1, NLVL+1, NLAT, NLON))
	 return NC_ERR;
   } // next record 

   for (int i = 0; i < NLON; i++) {
	   for (int j = 0; j < NLAT; j++) {
	      for (int k = 0; k < NLVL; k++) {
			  u[k*NLON*NLAT + j*NLON + i] = (uwind_in[k*(NLON*1)*NLAT + j*(NLON+1)+ i] + uwind_in[k*(NLON+1)*NLAT + j*(NLON+1) + i+1])/2.0;
			  v[k*NLON*NLAT + j*NLON + i] = (vwind_in[k*NLON*(NLAT+1) + j*NLON + i] + vwind_in[k*NLON*(NLAT+1) + (j+1)*NLON + i])/2.0;
			  w[k*NLON*NLAT + j*NLON + i] = (wwind_in[k*NLON*NLAT + j*NLON + i] + wwind_in[(k+1)*NLON*NLAT + j*NLON + i])/2.0;
			  dbz[k*NLON*NLAT + j*NLON + i] = pow(10.0,(dbz_in[k*NLON*NLAT + j*NLON + i]*0.1));
			  z[k*NLON*NLAT + j*NLON + i] = (ph_in[k*NLON*NLAT + j*NLON + i] + ph_in[(k+1)*NLON*NLAT + j*NLON + i]
				  + phb_in[k*NLON*NLAT + j*NLON + i] + phb_in[(k+1)*NLON*NLAT + j*NLON + i])/(2.0*9.81);
		  }
	  }
  }
   // The file is automatically closed by the destructor. This frees
   // up any internal netCDF resources associated with the file, and
   // flushes any buffers.

   std::cout << "*** SUCCESS reading netCDF!" << std::endl;
   return 0;
}
Пример #10
0
bool Loader::loadMEG()
{
    QString fn = m_fileName.path();

    DatasetMeshTimeSeries* dataset = new DatasetMeshTimeSeries( fn, Fn::DatasetType::MESH_TIME_SERIES );

    qDebug() << "loading meg set: " << fn;

    QFile setfile( fn );
    if ( !setfile.open( QIODevice::ReadOnly ) )
    {
        qCritical( "set file unreadable" );
    }
    QTextStream ts( &setfile );
    QString nl;
    //TODO: Will windows have a problem with this?
    QString trunk = QFileInfo( fn ).path();
    while ( !ts.atEnd() )
    {
        nl = ts.readLine();
        //For commenting out stuff in the setfiles
        if ( nl.startsWith( "#meg") )
        {
            QStringList sl = nl.split( " " );
            bool ok;
            int count = sl[1].toInt( &ok );
            if ( ok )
            {
                qDebug() << count << "meg data files in set definition";
                for ( int i = 1; i <= count; ++i )
                {
                    QString numberString = QString::number( i );
                    int nss = numberString.size();
                    for ( int k = 0; k < 3 - nss; ++k )
                    {
                        numberString = "0" + numberString;
                    }
                    QFile dataFile( trunk + QDir::separator() + numberString + ".txt" );
                    if ( !dataFile.open( QIODevice::ReadOnly ) )
                    {
                        qCritical() << "data file unreadable, skipping"  << numberString + ".txt";
                        continue;
                    }
                    std::vector<float>data;
                    QTextStream ds( &dataFile );
                    while( !ds.atEnd() )
                    {
                        nl = ds.readLine();
                        float val = nl.toFloat( &ok );
                        if ( ok )
                        {
                            data.push_back( val );
                        }
                        else
                        {
                            break;
                        }
                    }
                    if ( !ok )
                    {
                        qCritical() << "error while reading data file, skipping" << numberString + ".txt";
                        continue;
                    }
                    else
                    {
                        dataset->addData( data );
                    }
                }
            }
            else
            {
                qCritical() << "can't read count meg data files";
            }
        }
        else if ( !nl.startsWith( "#" ) )
        {
            QStringList sl = nl.split( " " );
            QString fullname = trunk + QDir::separator() + sl.at( 0 );
            float x = 0;
            float y = 0;
            float z = 0;
            if ( sl.length() > 1 )
                x = sl.at( 1 ).toFloat();
            if ( sl.length() > 2 )
                y = sl.at( 2 ).toFloat();
            if ( sl.length() > 3 )
                z = sl.at( 3 ).toFloat();
            QVector3D s( x, y, z );

            TriangleMesh2* mesh;
            std::vector<float>* points;
            std::vector<int> triangles;

            if ( fullname.endsWith( ".asc" ) )
            {
                LoaderFreesurfer lf;

                if ( !lf.loadASC( fullname ) )
                {
                    qCritical() << "unable to load: " << fn;
                    return false;
                }

                points = lf.getPoints();
                triangles = lf.getTriangles();

                int numPoints = points->size() / 3;
                int numTriangles = triangles.size() / 3;


                if ( numPoints > 0 && numTriangles > 0 )
                {
                    mesh = new TriangleMesh2( numPoints, numTriangles );
                    for ( int i = 0; i < numPoints; ++i )
                    {
                        mesh->addVertex( points->at( i * 3 ) + s.x(), points->at( i * 3 + 1 ) + s.y(), points->at( i * 3 + 2 ) + s.z() );
                    }
                    for ( int i = 0; i < numTriangles; ++i )
                    {
                        mesh->addTriangle( triangles[i * 3], triangles[i * 3 + 2], triangles[i * 3 + 1] );
                    }
                    mesh->finalize();

                    dataset->addMesh( mesh, sl.at( 0 ) );
                }
            }

            if ( fullname.endsWith( ".vtk" ) )
            {
                LoaderVTK* lv = new LoaderVTK( fullname );

                if ( !lv->load() )
                {
                    qCritical() << lv->getStatus();
                    return false;
                }

                if ( lv->getPrimitiveType() == 1 )
                {
                    points = lv->getPoints();
                    triangles = lv->getPolys();

                    if ( triangles[0] != 3 )
                    {
                        qCritical() << "*ERROR* " << fn << " can only load triangle polygon data";
                        return false;
                    }

                    int numPoints = lv->getNumPoints();
                    int numTriangles = lv->getNumPolys();

                    if ( numPoints > 0 && numTriangles > 0 )
                    {
                        mesh = new TriangleMesh2( numPoints, numTriangles );
                        for ( int i = 0; i < numPoints; ++i )
                        {
                            mesh->addVertex( points->at( i * 3 ), points->at( i * 3 + 1 ), points->at( i * 3 + 2 ) );
                        }

                        for ( int i = 0; i < numTriangles; ++i )
                        {
                            mesh->addTriangle( triangles[i * 4 + 1], triangles[i * 4 + 2], triangles[i * 4 + 3] );
                        }

                        mesh->finalize();

                        dataset->addMesh( mesh, sl.at( 0 ) );
                    }
                }
            }
        }
    }
    dataset->setProperties();
    m_dataset.push_back( dataset );

    return true;
}
Пример #11
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"); }

}
Пример #12
0
void MCCTRapDep()   
{
  for(int iSpec = 0; iSpec < 3; iSpec++){
    int Prompt =1; int PutWeight = 1;
    bool bDefault = true; // true : cowboy only, false : salior
    bool bCowboy = false; // true : cowboy only, false : salior
    bool bSailor = false; // true : cowboy only, false : salior
    double fake_v2 = 0.3;

    // iSpec : choose the condition for default/cowboy/sailor
    if(iSpec == 0) {bDefault = true;bCowboy = false;bSailor = false;}
    if(iSpec == 1) {bDefault = false;bCowboy = true;bSailor = false;}
    if(iSpec == 2) {bDefault = false;bCowboy = false;bSailor = true;}

    char cCond[512];
    int iCond = 0; // the number of the cases, 1 : default, 2 : cowboy, 3 : sailor
    if(bDefault) {sprintf(cCond, "default"); iCond = 0;}
    if(bCowboy)  {sprintf(cCond, "cowboy"); iCond = 1;}
    if(bSailor)  {sprintf(cCond, "sailor"); iCond = 2;}

    // iCat : decide the categories for Rapidity (1: 0.0 - 1.2, 2: 1.2 - 1.6, 3: 1.6 - 2.4)
    for(int iCat = 0; iCat < 4; iCat++){
      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(0); // at least most of the time
      gStyle->SetOptStat("emri");
      gStyle->SetOptFit(1); // set to 1 only if you want to display fit results
      //==================================== Define Histograms====================================================
      char OutTextFile[100]; 
      if(iCat == 0) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_0012_dPhi_%s.tex", cCond);
      if(iCat == 1) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_1216_dPhi_%s.tex", cCond);
      if(iCat == 2) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_1624H_dPhi_%s.tex", cCond);
      if(iCat == 3) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_1624L_dPhi_%s.tex", cCond);
      ofstream dataFile(Form(OutTextFile));
      TH1D *diMuonsInvMass_Gen = new TH1D("diMuonsInvMass_Gen","diMuonsInvMass_Gen", 100,2.98,3.16);

      TH1D *diMuonsPt_Gen = new TH1D("diMuonsPt_Gen","diMuonsPt_Gen", 100,0,50);
      TH1D *Bin_Gen = new TH1D("Bin_Gen","Bin_Gen", 40,0,40);
      //==============================================Define Acc Eff Stuff here===========================================
      // Pt bin sizes
      // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

      const int nFiles = 6;
      const int ndPhiBins = 4;
      double dphi_bound[100] = {0};

      dphi_bound[0] = 0.0;
      dphi_bound[1] = TMath::Pi()*2/16;
      dphi_bound[2] = TMath::Pi()*4/16;
      dphi_bound[3] = TMath::Pi()*6/16;
      dphi_bound[4] = TMath::Pi()*8/16;

      //X Axis error on Eff graph 
      double xdphi_bound[ndPhiBins] = {0.0};
      for(int i = 0; i < ndPhiBins; i++){
        xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
        cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
        dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      }

      double mom_err[ndPhiBins] = {0.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 2D 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];
      char namePt_1B[500];//for bkg func
      for (int ifile = 0; ifile < nFiles; ifile++) {
        for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {
          sprintf(nameGen[ifile],"DiMuonMassGen_pt_%d_%d_%d",ifile,iCat,idphi);
          sprintf(nameRec[ifile],"DiMuonMassRec_pt_%d_%d_%d",ifile,iCat,idphi);

          sprintf(nameGenPt[ifile],"DiMuonPtGen_pt_%d_%d_%d",ifile,iCat,idphi);
          sprintf(nameRecPt[ifile],"DiMuonPtRec_pt_%d_%d_%d",ifile,iCat,idphi);

          diMuonsInvMass_GenA[ifile][idphi]= new TH1D(nameGen[ifile],nameGen[ifile],  100,2.98,3.16); //for eff Gen;
          diMuonsInvMass_GenA[ifile][idphi]->Sumw2();
          diMuonsInvMass_GenA[ifile][idphi]->SetMarkerStyle(7);
          diMuonsInvMass_GenA[ifile][idphi]->SetMarkerColor(4);
          diMuonsInvMass_GenA[ifile][idphi]->SetLineColor(4);

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

          diMuonsPt_GenA[ifile][idphi]= new TH1D(nameGenPt[ifile],nameGenPt[ifile],  100,0,40); //for eff Gen;
          diMuonsPt_RecA[ifile][idphi]= new TH1D(nameRecPt[ifile],nameRecPt[ifile],  100,0,40); //for eff Rec;
        }
      }

      //===========================================Input Root File============================================================
      char fileName[10][500];
      //scales for different pT bins
      double scale[10]={0};  
      scale[0]=2.35829e-07;
      scale[1]=1.99854e-07;
      scale[2]=4.48263e-08;
      scale[3]=1.01144e-08;
      scale[4]=4.89604e-09;
      scale[5]=2.62102e-09;

      if(PutWeight==0){scale[0]=(1);scale[1]=(1);scale[2]=(1);scale[3]=(1);scale[4]=(1);scale[5]=(1);}

      if(Prompt ==1){
        cout<<"==================Prompt PrJpsi================================================"<<endl;
        sprintf(fileName[0],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0003_total.root");
        sprintf(fileName[1],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0306_total.root");
        sprintf(fileName[2],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0609_total.root");
        sprintf(fileName[3],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0912_total.root");
        sprintf(fileName[4],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt1215_total.root");
        sprintf(fileName[5],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt1530_total.root");

        //sprintf(fileName[6],"../RootFiles/DiMuonTTree_PromptJpsi_Pt30XX_total.root");
      }

      TFile *infile;
      TTree *tree;
      TTree *gentree;

      //======================  File loop Starts ============================
      for(int ifile = 0; ifile < nFiles; 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,JpsiRap, JpsiCharge;
        Double_t JpsiVprob;
        Double_t JpsiPhi;
        Double_t JpsiEta;
        Double_t JpsiPsi[38];
        Double_t JpsiGenPsi;
        //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 PrJpsi Variables
        double GenJpsiMass, GenJpsiPt, GenJpsiRap;
        double GenJpsiPx, GenJpsiPy, GenJpsiPz;
        double GenJpsiPhi;
        double GenJpsiEta;
        double GenJpsiPsi;
        //2.) Gen muon variables 
        double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
        double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;

        // HLTrigger
        int hbit1;

        //Event variables
        tree->SetBranchAddress("eventNb",&eventNb);
        tree->SetBranchAddress("runNb",&runNb);
        tree->SetBranchAddress("lumiBlock",&lumiBlock);
        tree->SetBranchAddress("hbit1",&hbit1);

        //Jpsi Variables
        tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
        tree->SetBranchAddress("JpsiMass",&JpsiMass);
        tree->SetBranchAddress("JpsiPt",&JpsiPt);
        tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
        tree->SetBranchAddress("JpsiEta",&JpsiEta);
        tree->SetBranchAddress("JpsiPsi",&JpsiPsi);
        tree->SetBranchAddress("JpsiGenPsi",&JpsiGenPsi);
        //tree->SetBranchAddress("JpsiPsi",&JpsiPsi[38]);
        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("GenJpsiPhi",    &GenJpsiPhi);
        gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
        gentree->SetBranchAddress("GenJpsiPsi",    &GenJpsiPsi);
        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;

        for(int i=0; i< nGenEntries; i++)  {        
          gentree->GetEntry(i);
          //Only printing 
          if(i%100000==0){
            //cout<<" processing record "<<i<<"/"<<nGenEntries<<endl;
            //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
          }

          //if(GenJpsiPt < 6.5) continue;

          bool GenPosIn=0, GenNegIn=0;
          GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
          GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

          diMuonsInvMass_Gen->Fill(GenJpsiMass);
          diMuonsPt_Gen->Fill(GenJpsiPt);

          if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
          if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

          int AccHighPtJpsi = 0;
          int AccLowPtJpsi = 0;
          if(GenJpsiPt >= 6.5 && fabs(GenJpsiRap) < 2.4 && GenPosIn == 1 && GenNegIn == 1) AccHighPtJpsi = 1;
          if(GenJpsiPt < 6.5 && GenJpsiPt >= 3.0 && fabs(GenJpsiRap) >= 1.6 && fabs(GenJpsiRap) < 2.4 && GenPosIn == 1 && GenNegIn == 1) AccLowPtJpsi = 1;

          double gdPhi2mu = GenmuPosPhi - GenmuNegPhi;
          while (gdPhi2mu > TMath::Pi()) gdPhi2mu -= 2*TMath::Pi();
          while (gdPhi2mu <= -TMath::Pi()) gdPhi2mu += 2*TMath::Pi();
          double gchkCowboy = 1*gdPhi2mu;

          if(bCowboy && !(gchkCowboy > 0.)) continue;
          if(bSailor && (gchkCowboy > 0.)) continue;

          if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

          Bin_Gen->Fill(gbin);

          double GenCenWeight =0, GenWeight =0;
          GenCenWeight=FindCenWeight(gbin);
          
          double gJpsidPhi = TMath::Abs(GenJpsiPsi);
          double gmean_dphi = TMath::Pi()/16;
          if (gJpsidPhi>TMath::Pi()/8) gmean_dphi = 3*TMath::Pi()/16;
          if (gJpsidPhi>TMath::Pi()/4) gmean_dphi = 5*TMath::Pi()/16;
          if (gJpsidPhi>3*TMath::Pi()/8) gmean_dphi = 7*TMath::Pi()/16;
          GenWeight=GenCenWeight*scale[ifile]*(2.0/TMath::Pi()*(1+2*fake_v2*cos(2*gJpsidPhi)*TMath::Gaus(GenJpsiPt,15,4,0)));

          if(PutWeight==0) GenWeight=1; 


          for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {

            //adding pT of all pt bins to see diss is cont

            if(iCat == 0) {
              if(  AccHighPtJpsi == 1 && (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 6.5 && GenJpsiPt < 40.0) &&  
                  (TMath::Abs(GenJpsiRap)<1.2 && TMath::Abs(GenJpsiRap) >= 0.0 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
            if(iCat == 1) {
              if(  AccHighPtJpsi == 1 && (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 6.5 && GenJpsiPt < 40.0) &&  
                  (TMath::Abs(GenJpsiRap)<1.6 && TMath::Abs(GenJpsiRap) >= 1.2 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
            if(iCat == 2) {
              if(  AccHighPtJpsi == 1 &&  (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 6.5 && GenJpsiPt < 40.0) &&  
                  (TMath::Abs(GenJpsiRap)<2.4 && TMath::Abs(GenJpsiRap) >= 1.6 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
            if(iCat == 3) {
              if(  AccLowPtJpsi == 1 && (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 3.0 && GenJpsiPt < 6.5) &&  
                  (TMath::Abs(GenJpsiRap)<2.4 && TMath::Abs(GenJpsiRap) >= 1.6 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
          }
        }//gen loop end



        cout<<" accepted no "<< NAccep<<endl;
        dataFile<<" 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();

        //=============== Rec Tree Loop ==============================================================================

         // start to fill up reco corrected by efficiency
        char tmp_eff_input[512], tmp_input_histo[512];
        if(!(iCat == 3)) sprintf(tmp_eff_input,"../../EffRoots_New/PrJpsi_HighPt_%s.root", cCond);
        if(iCat == 3) sprintf(tmp_eff_input,"../../EffRoots_New/PrJpsi_LowPt_%s.root", cCond);
        sprintf(tmp_input_histo,"eff_%s", cCond);

        TFile *eff_input;
        eff_input=new TFile(tmp_eff_input,"R");

        int nRecEntries=tree->GetEntries();
        cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
        for(int i=0; i<nRecEntries; i++)  {     
          tree->GetEntry(i);
          //if(bCowboy && !(gchkCowboy > 0.)) {cout<<"This is not Cowboy from Gen"<<endl; continue;}
          //if(bSailor && (gchkCowboy > 0.)) {cout<<"This is not Sailor from Gen"<<endl; continue;}
          //Only printing 
          if(i%10000==0){
            //cout<<" processing record "<<i<<"/"<<nRecEntries<<endl;
            //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
            //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<endl; 
          }
          //if(JpsiPt < 6.5) continue;
          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); 

          if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
          if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

          bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
          bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

          double dPhi2mu = muPosPhi - muNegPhi;
          while (dPhi2mu > TMath::Pi()) dPhi2mu -= 2*TMath::Pi();
          while (dPhi2mu <= -TMath::Pi()) dPhi2mu += 2*TMath::Pi();
          double chkCowboy = 1*dPhi2mu;

          if(bCowboy && !(chkCowboy > 0.)) continue;
          if(bSailor && (chkCowboy > 0.)) continue;

          if(muPos_found > 10 && muPos_pixeLayers > 0 && muPos_nchi2In < 4.0 && TMath::Abs(muPos_dxy) < 3 && TMath::Abs(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 && TMath::Abs(muNeg_dxy) < 3 && TMath::Abs(muNeg_dz) < 15 && muNeg_nchi2Gl < 20 &&
              muNeg_arbitrated==1 && muNeg_tracker==1){NegPass=1;}

          //cout<<"Cut checks, muPos_matches : "<<muPos_matches<<", muNeg_matches : "<<muNeg_matches<<", PosIn : "<<PosIn<<", NegIn : "<<NegIn
          //    <<", PosPass : "******", NegPass : "******", mu_Global : "<<mu_Global<<", mu_Tracker : "<<mu_Tracker<<endl;
          //if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
          int AccHighPtJpsi = 0;
          int AccLowPtJpsi = 0;
          if(JpsiPt >= 6.5 && fabs(JpsiRap) < 2.4 && PosIn == 1 && NegIn == 1) AccHighPtJpsi = 1;
          if(JpsiPt < 6.5 && JpsiPt >= 3.0 && fabs(JpsiRap) >= 1.6 && fabs(JpsiRap) < 2.4 && PosIn == 1 && NegIn == 1) AccLowPtJpsi = 1;

          if(hbit1 == 1 && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

          //AllCut = 1;
          //without ID cut
          // if((muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && mu_Global && mu_Tracker){AllCut=1;}

          //without trigger matched
          //if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

          double eff_cor[2];
          double RecCenWeight=0,RecWeight=0;
          RecCenWeight=FindCenWeight(rbin);
          
          double JpsidPhi = 0.0;
          JpsidPhi = TMath::Abs(JpsiGenPsi);

          double rmean_dphi = TMath::Pi()/16;
          if (JpsidPhi>TMath::Pi()/8) rmean_dphi = 3*TMath::Pi()/16;
          if (JpsidPhi>TMath::Pi()/4) rmean_dphi = 5*TMath::Pi()/16;
          if (JpsidPhi>3*TMath::Pi()/8) rmean_dphi = 7*TMath::Pi()/16;
          RecWeight=RecCenWeight*scale[ifile]*(2.0/TMath::Pi()*(1+2*fake_v2*cos(2*JpsidPhi)*TMath::Gaus(JpsiPt,15,4,0)));


          if(PutWeight==0)RecWeight=1;


          //Eff loop for reco
          for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {
            if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {     
                if(iCat == 0) {
                  if(AccHighPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=6.5 && JpsiPt<40.0) && 
                      (TMath::Abs(JpsiRap) < 1.2 && TMath::Abs(JpsiRap) >= 0.0) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
                if(iCat == 1) {
                  if(AccHighPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=6.5 && JpsiPt<40.0) && 
                      (TMath::Abs(JpsiRap) < 1.6 && TMath::Abs(JpsiRap) >= 1.2) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
                if(iCat == 2) {
                  if(AccHighPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=6.5 && JpsiPt<40.0) && 
                      (TMath::Abs(JpsiRap) < 2.4 && TMath::Abs(JpsiRap) >= 1.6) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
                if(iCat == 3) {
                  if(AccLowPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=3.0 && JpsiPt<6.5) && 
                      (TMath::Abs(JpsiRap) < 2.4 && TMath::Abs(JpsiRap) >= 1.6) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
            }
          }
        }//rec tree loop ends
      }  // 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;

      for(Int_t idphi = 0; idphi < ndPhiBins; idphi++){
        diMuonsInvMass_RecA1[idphi] = diMuonsInvMass_RecA[0][idphi];
        diMuonsInvMass_GenA1[idphi] = diMuonsInvMass_GenA[0][idphi];
        diMuonsPt_GenA1[idphi] = diMuonsPt_GenA[0][idphi];
        diMuonsPt_RecA1[idphi] = diMuonsPt_RecA[0][idphi];

        for (int ifile = 1; ifile < nFiles; ifile++) {
          diMuonsInvMass_RecA1[idphi]->Add(diMuonsInvMass_RecA[ifile][idphi]);
          diMuonsInvMass_GenA1[idphi]->Add(diMuonsInvMass_GenA[ifile][idphi]);     
          diMuonsPt_GenA1[idphi]->Add(diMuonsPt_GenA[ifile][idphi]); 
          diMuonsPt_RecA1[idphi]->Add(diMuonsPt_RecA[ifile][idphi]); 
        }
      }
      //===========================Fitting=================================================================================//
      // Fit ranges
      double mass_low, mass_high;
      double MassJpsi, WeidthJpsi;
      // Fit Function crystall ball
      // Jpsi Settings
      MassJpsi = 3.096; 
      WeidthJpsi = 0.028;
      mass_low = 2.945; 
      mass_high = 3.24;  // Fit ranges

      TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,2.4,3.8,6);//2.4,3.8,6);
      GAUSPOL->SetParNames("Yield (J/#psi)","BinWidth","Mean","Sigma","#alpha","n");
      GAUSPOL->SetParameter(2, MassJpsi);
      GAUSPOL->SetParameter(3, WeidthJpsi);
      //GAUSPOL->SetParLimits(3, 0.1*WeidthJpsi,2.0*WeidthJpsi);
      GAUSPOL->SetParameter(4, 1.2);
      GAUSPOL->SetParameter(5, 20.0);
      GAUSPOL->SetLineWidth(2.0);
      GAUSPOL->SetLineColor(2);


      //=====================Loop for eff========================================================================================//
      //define stuff here for error on weighted samples
      double GenNo[100]={0};
      double GenError[100]={0};
      double RecError[100]={0};

      for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {

        gen_pt[idphi] = diMuonsInvMass_GenA1[idphi]->IntegralAndError(1, 100, genError);
        gen_ptError[idphi]= genError;
        cout<<" gen_pt[idphi] "<< gen_pt[idphi] <<" error   "<<  gen_ptError[idphi]<<endl;

        // cout<<" *********************** "<<diMuonsInvMass_RecA1[idphi]->GetMaximum()<<endl;
        //giving inetial value for crystall ball fourth parameter 
        GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[idphi]->Integral(0,50));
        GAUSPOL->FixParameter(1, diMuonsInvMass_RecA1[idphi]->GetBinWidth(1));
        //GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[idphi]->GetMaximum());
        //new TCanvas;
        //diMuonsInvMass_RecA1[idphi]->Draw();

        new TCanvas;
        diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL","EMRQ", "", mass_low, mass_high); // Jpsi
        //diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL","LLMERQ", "", 8.5,10.5); // Jpsi
        //diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL","LLMER", "", mass_low, mass_high); // Jpsi
        diMuonsInvMass_RecA1[idphi]->DrawCopy("EPLsame");

        // new TCanvas;
        //diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL_1","LLMER", "", mass_low, mass_high);
        //diMuonsInvMass_RecA1[idphi]->DrawCopy("EPLsame");
        //gPad->Print(PlotName);
        //gPad->Print(PlotName1);

        //  cout << GAUSPOL_1->GetChisquare()<<endl;
        //for(int i=0;i<=100;i++) {cout<<i<<"  "<<diMuonsInvMass_RecA1[idphi]->GetBinContent(i)<<endl;}
        //return;
        //double JpsiMass = GAUSPOL_1->GetParameter(2);
        //double JpsiWidth = GAUSPOL_1->GetParameter(3);
        //double JpsiYield = GAUSPOL_1->GetParameter(4); 

        double JpsiMass = GAUSPOL->GetParameter(2);
        double JpsiWidth = GAUSPOL->GetParameter(3);

        double JpsiYield = GAUSPOL->GetParameter(0); 
        Double_t JpsiYieldError = GAUSPOL->GetParError(0); 

        //cout<<JpsiYieldError<<"*****************"<<endl;

        //if(TMath::IsNan(JpsiYieldError)=1) {JpsiYieldError=TMath::Sqrt(JpsiYield);}

        double par[20];
        GAUSPOL->GetParameters(par);
        sprintf(namePt_1B,"pt_1B_%d",idphi);

        backfun_1 = new TF1(namePt_1B, Pol2, mass_low, mass_high, 3);
        backfun_1->SetParameters(&par[3]);

        double MassLow=(JpsiMass-3*JpsiWidth);
        double MassHigh=(JpsiMass+3*JpsiWidth);


        int binlow =diMuonsInvMass_RecA1[idphi]->GetXaxis()->FindBin(MassLow);
        int binhi =diMuonsInvMass_RecA1[idphi]->GetXaxis()->FindBin(MassHigh);

        //double binwidth=diMuonsInvMass_RecA1[idphi]->GetBinWidth(1);
        //yield by function 
        //rec_pt[idphi] = JpsiYield;
        //rec_ptError[idphi]= JpsiYieldError;

        //yield by histogram integral
        binlow = 1;
        binhi = 100;
        rec_pt[idphi] = diMuonsInvMass_RecA1[idphi]->IntegralAndError(binlow, binhi,recError);
        rec_ptError[idphi]= recError;
      }

      TFile *outfile;
      char tmp_output[512];
      if(iCat == 0) sprintf(tmp_output,"MCCT_PrJpsi_Raps_0012_dPhi_%s.root",cCond);
      if(iCat == 1) sprintf(tmp_output,"MCCT_PrJpsi_Raps_1216_dPhi_%s.root",cCond);
      if(iCat == 2) sprintf(tmp_output,"MCCT_PrJpsi_Raps_1624H_dPhi_%s.root",cCond);
      if(iCat == 3) sprintf(tmp_output,"MCCT_PrJpsi_Raps_1624L_dPhi_%s.root",cCond);
      outfile =new TFile(tmp_output,"Recreate");

      double gsum = 0.0;
      double gen_pt_Norm[ndPhiBins];
      double gen_ptError_Norm[ndPhiBins];
      for(int i = 0; i < ndPhiBins; i++){
        gsum += gen_pt[i];
      }
      gsum = gsum*(dphi_bound[1]-dphi_bound[0]);

      for(int i = 0; i < ndPhiBins; i++){
        gen_pt_Norm[i] = gen_pt[i]/gsum;
        gen_ptError_Norm[i] = gen_ptError[i]/gsum;
      }

      double sum = 0.0;
      double rec_pt_Norm[ndPhiBins];
      double rec_ptError_Norm[ndPhiBins];
      for(int i = 0; i < ndPhiBins; i++){
        sum += rec_pt[i];
      }
      sum = sum*(dphi_bound[1]-dphi_bound[0]);

      for(int i = 0; i < ndPhiBins; i++){
        rec_pt_Norm[i] = rec_pt[i]/sum;
        rec_ptError_Norm[i] = rec_ptError[i]/sum;
      }

      TH1F *hJpsi_Gen = new TH1F("hJpsi_Gen","hJpsi_Gen",ndPhiBins,0,TMath::Pi()/2);
      TH1F *hJpsi_Reco = new TH1F("hJpsi_Reco","hJpsi_Reco",ndPhiBins,0,TMath::Pi()/2);
      hJpsi_Gen->Sumw2();
      hJpsi_Reco->Sumw2();
      for(int i = 0; i < ndPhiBins; i++){
        hJpsi_Gen->SetBinContent(i+1,gen_pt[i]);
        hJpsi_Gen->SetBinError(i+1,gen_ptError[i]);
        hJpsi_Reco->SetBinContent(i+1,rec_pt[i]);
        hJpsi_Reco->SetBinError(i+1,rec_ptError[i]);
      }

      TGraphErrors *Jpsi_Reco_Norm = new TGraphErrors(ndPhiBins, xdphi_bound, rec_pt_Norm, mom_err, rec_ptError_Norm);
      TGraphErrors *Jpsi_Gen_Norm = new TGraphErrors(ndPhiBins, xdphi_bound, gen_pt_Norm, mom_err, gen_ptError_Norm);
      if(iCat == 0){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_0012");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_0012");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_0012");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_0012");
      }
      if(iCat == 1){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_1216");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_1216");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_1216");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_1216");
      }
      if(iCat == 2){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_1624H");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_1624H");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_1624H");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_1624H");
      }
      if(iCat == 3){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_1624L");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_1624L");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_1624L");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_1624L");
      }
      hJpsi_Gen->Write();
      hJpsi_Reco->Write();
      Jpsi_Reco_Norm->Write();
      Jpsi_Gen_Norm->Write();

      outfile->Write();
      outfile->Close();
    }
  }
}
Пример #13
0
/**
 *@details RFI_Clipper
 */
RFI_Clipper::RFI_Clipper( const ConfigNode& config )
  : AbstractModule( config ), _active(true), _crFactor(10.0),_srFactor(4.0), _current(0), _currentChunk(0),
    _badSpectra(0)
{
    _current = 0;
    if( config.hasAttribute("active") &&
            config.getAttribute("active").toLower() == QString("false") ) {
        _active = false;
    }
    // read in any fixed file data
    QString file = config.getOption("BandPassData", "file", "");
    if( file != "" && _active ) {
        if(! QFile::exists(file))
            throw(QString("RFI_Clipper: File \"" + file + "\" does not exist"));

        QFile dataFile(file);
        if( ! dataFile.open(QIODevice::ReadOnly | QIODevice::Text) )
            throw(QString("RFI_Clipper: Cannot open File \"" + file + "\""));
        BandPassAdapter adapter(config);
        dataFile.waitForReadyRead(-1);
        adapter.config(&_bandPass, dataFile.size());
        adapter.deserialise(&dataFile);
    }
    else {
        if( _active )
            throw(QString("RFI_Clipper: <BandPassData file=?> not defined"));
    }

    if( config.hasAttribute("channelRejectionRMS")  )
        _crFactor = config.getAttribute("channelRejectionRMS").toFloat();
    if( config.hasAttribute("spectrumRejectionRMS")  )
        _srFactor = config.getAttribute("spectrumRejectionRMS").toFloat();

    _maxHistory = config.getOption("History", "maximum", "10" ).toInt();
    _history.resize(_maxHistory);
    _historyMean.resize(_maxHistory);
    _historyRMS.resize(_maxHistory);
    _medianFromFile = _bandPass.median();
    _rmsFromFile = _bandPass.rms();
    _zeroDMing = 0;
    _num = 0; // _num is the number of points in the history
    _numChunks = 0; // _numChunks is the number of chunks in the history
    if( config.getOption("zeroDMing", "active" ) == "true" ) {
      _zeroDMing = 1;
    }
    if( config.getOption("Band", "matching" ) == "true" ) {
        _startFrequency = _bandPass.startFrequency();
        _endFrequency = _bandPass.endFrequency();
    }
    else {
        if( _active ) {
            if( config.getOption("Band", "startFrequency" ) == "" ) {
                throw(QString("RFI_Clipper: <Band startFrequency=?> not defined"));
            }
            _startFrequency = config.getOption("Band","startFrequency" ).toFloat();

            QString efreq = config.getOption("Band", "endFrequency" );
            if( efreq == "" )
                throw(QString("RFI_Clipper: <Band endFrequency=?> not defined"));
            _endFrequency= efreq.toFloat();
        }
    }
}
Пример #14
0
// The validate() method validates the MMFF force field using the MMFF94
// Validation Suite from <http://www.ccl.net/cca/data/MMFF94/>. The suite
// includes 753 molecules and each is check for correct atom typing, atom
// charge assignment, and total energy.
void MmffTest::validate()
{
    // open molecule data file
    chemkit::MoleculeFile dataFile(dataPath + "MMFF94_hypervalent.mol2");
    bool ok = dataFile.read();
    if(!ok)
        qDebug() << dataFile.errorString().c_str();
    QVERIFY(ok);
    QCOMPARE(dataFile.moleculeCount(), size_t(753));

    // open expected results file
    QFile expectedFile("mmff94.expected");
    if(!expectedFile.open(QFile::ReadOnly)){
        qDebug() << expectedFile.errorString();
        QFAIL("Failed to open expected data file.");
    }

    QDomDocument expectedFileDocument;
    expectedFileDocument.setContent(&expectedFile);
    QDomElement expectedMolecule = expectedFileDocument.documentElement().firstChildElement();
    QCOMPARE(expectedMolecule.tagName(), QString("molecule"));

    // validate molecules
    QList<chemkit::ForceField *> failedMolecules;
    foreach(const boost::shared_ptr<chemkit::Molecule> &molecule, dataFile.molecules()){
        bool failed = false;

        // check for correct expected molecule
        QByteArray name = expectedMolecule.attribute("name").toAscii();
        QCOMPARE(name.constData(), molecule->name().c_str());

        // create mmff force field
        chemkit::ForceField *forceField = chemkit::ForceField::create("mmff");
        QVERIFY(forceField);

        // add molecule and setup force field
        forceField->setMolecule(molecule.get());
        bool setup = forceField->setup();
        if(!setup){
            //failed = true;
        }

        // verify atoms
        int atomCount = forceField->atomCount();
        int expectedAtomCount = expectedMolecule.attribute("atomCount").toInt();
        if(atomCount != expectedAtomCount){
            failed = true;
        }

        QDomElement expectedAtom = expectedMolecule.firstChildElement();
        QCOMPARE(expectedAtom.tagName(), QString("atom"));
        foreach(const chemkit::ForceFieldAtom *forceFieldAtom, forceField->atoms()){
            std::string type = forceFieldAtom->type();
            QByteArray expectedType = expectedAtom.attribute("type").toAscii();
            if(type != expectedType.constData()){
                failed = true;
            }

            double charge = forceFieldAtom->charge();
            double expectedCharge = expectedAtom.attribute("charge").toDouble();
            double chargeDifference = std::abs(charge - expectedCharge);
            if(chargeDifference > 0.1){
                failed = true;
            }

            expectedAtom = expectedAtom.nextSiblingElement();
        }

        // verify energy
        double energy = forceField->energy();
        double expectedEnergy = expectedMolecule.attribute("energy").toDouble();
        double energyDifference = std::abs(energy - expectedEnergy);
        if(energyDifference > 1.0){
            failed = true;
        }

        // move expected molecule to next molecule element
        expectedMolecule = expectedMolecule.nextSiblingElement();

        if(failed){
            failedMolecules.append(forceField);
        }
        else{
            delete forceField;
        }
    }

    // write actual results file if any molecules failed
    if(failedMolecules.size() > 0){
        QFile actualFile("mmff94.actual");
        actualFile.open(QFile::WriteOnly);

        actualFile.write("<molecules>\n");

        foreach(chemkit::ForceField *forceField, failedMolecules){
            const chemkit::Molecule *molecule = forceField->molecule();

            actualFile.write(QString("  <molecule name=\"%1\" energy=\"%2\" atomCount=\"%3\">\n")
                                .arg(molecule->name().c_str())
                                .arg(forceField->energy())
                                .arg(forceField->atomCount())
                                .toAscii());

            foreach(const chemkit::ForceFieldAtom *forceFieldAtom, forceField->atoms()){
                actualFile.write(QString("    <atom type=\"%1\" charge=\"%2\"/>\n")
                                    .arg(forceFieldAtom->type().c_str())
                                    .arg(forceFieldAtom->charge())
                                    .toAscii());
            }

            actualFile.write("  </molecule>\n");
            delete forceField;
        }

        actualFile.write("</molecules>\n");
        actualFile.close();
    }
void pbpbEffJpsiSFSysSTA__idx_()   
{
  int Prompt =1; int PutWeight = 1;

  int JpsiCat_ = 1; // 1 : prompt, 2 : non-prompt

  double minRap = 0.0; double maxRap = 1.2;
  double minPt = 6.5; double maxPt = 30.0;
  for(int eCat_ = 1; eCat_ < 6; eCat_++){

    if(eCat_ == 1) {minRap = 0.0; maxRap = 1.2;}
    if(eCat_ == 2) {minRap = 1.2; maxRap = 1.6;}
    if(eCat_ == 3) {minRap = 1.6; maxRap = 2.4;}
    if(eCat_ == 4) {
      minRap = 1.6; maxRap = 2.4;
      minPt = 3.0; maxPt = 6.5;
    }
    if(eCat_ == 5){
      minRap = 0.0; maxRap = 2.4;
      minPt = 6.5; maxPt = 30.0;
    }

    bool bDefault = true; // true : default, false : sailor or cowboy

    char cCd[512];
    if(bDefault) sprintf(cCd, "default");

    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(0); // at least most of the time
    gStyle->SetOptStat(0); // most of the time, sometimes "nemriou" might be useful to display name, 
    //number of entries, mean, rms, integral, overflow and underflow
    gStyle->SetOptFit(0); // set to 1 only if you want to display fit results
    //==================================== Define Histograms====================================================

    //==============================================Define Acc Eff Stuff here===========================================
    // Pt bin sizes
    // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

    const char *cTrg[5] = {"Bit1", "L1DM0HighQ", "L2Mu3NHitQ", "L3Mu3", "L3DMOpen"};
    //int iTrg = 0;
    TFile *outfile;
    char tmp_output[512];
    if(eCat_ == 1) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_y1.root", minRap, maxRap, minPt, maxPt);
    if(eCat_ == 2) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_y2.root", minRap, maxRap, minPt, maxPt);
    if(eCat_ == 3) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_y3.root", minRap, maxRap, minPt, maxPt);
    if(eCat_ == 4) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_lowpt.root", minRap, maxRap, minPt, maxPt);
    if(eCat_ == 5) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_y4.root", minRap, maxRap, minPt, maxPt);
    outfile =new TFile(tmp_output, "Recreate");
    TH1F *hGenCent = new TH1F("hGenCent",";Centrality (%);Weighted Counts",40,0,40);
    TH1F *hRecCent = new TH1F("hRecCent",";Centrality (%);Weighted Counts",40,0,40);
    hGenCent->Sumw2();
    hRecCent->Sumw2();

    for(int iSpec = 0; iSpec < 1; iSpec++){

      const int nCentBins = 6; // Non-prompt (60-100)
      const int nPtBins = 7;
      const int nRapBins = 6;
      const int ndPhiBins = 8;
      //const int ndPhiBins = 4;
      const int ndPhi2Bins = 8;
      const int nPhiBins = 8;
      const int nFiles = 6;
      double ct_bound[nCentBins+1] = {0, 4, 8, 12, 16, 20, 40}; // NonPrompt (60-100)
      double ct_bound2[nCentBins+1] = {0.0};
      for(int ict = 0; ict < nCentBins+1; ict++){
        ct_bound2[ict] = ct_bound[ict]*2.5;
      }
      double xct_bound[nCentBins] = {0.0};
      //double pt_bound[nPtBins+1] = {0.0, 3.0, 6.5};
      // pT bins : 6.5-7.5, 7.5-8.5, 8.5-9.5, 9.5-10.5, 10.5-11.5, 11.5-12.5, 12.5-14.5, 14.5-16.5, 16.5-20.0, 20.0-30.0
      double pt_bound[nPtBins+1] = {6.5, 7.5, 8.5, 9.5, 11.0, 13.0, 16.0, 30.0};
      double xpt_bound[nPtBins] = {0.0};
      // rap bins : 0.0-0.3, 0.3-0.6, 0.6-0.9, 0.9-1.2, 1.2-1.5, 1.5-1.8, 1.8-2.1, 2.1-2.4
      double rap_bound[nRapBins+1] = {0.0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4};
      double xrap_bound[nRapBins] = {0.0};
      double dphi_bound[ndPhiBins+1] = {0.0, TMath::Pi()/16, 2*TMath::Pi()/16, 3*TMath::Pi()/16, 4*TMath::Pi()/16, 5*TMath::Pi()/16, 6*TMath::Pi()/16, 7*TMath::Pi()/16, 8*TMath::Pi()/16};
      double xdphi_bound[ndPhiBins] = {0.0};
      double phi_bound[nPhiBins+1] = {-4*TMath::Pi()/4, -3*TMath::Pi()/4, -2*TMath::Pi()/4, -1*TMath::Pi()/4,0.0, TMath::Pi()/4, 2*TMath::Pi()/4, 3*TMath::Pi()/4, TMath::Pi()};
      double xphi_bound[nPhiBins] = {0.0};
      double dphi2_bound[ndPhi2Bins+1] = {0.0, TMath::Pi()/16, 2*TMath::Pi()/16, 3*TMath::Pi()/16, 4*TMath::Pi()/16, 5*TMath::Pi()/16, 6*TMath::Pi()/16, 7*TMath::Pi()/16, 8*TMath::Pi()/16};
      double xdphi2_bound[ndPhi2Bins] = {0.0};

      const char *cSp[6] = {"Cents","Pts","Raps","Phi","dPhi","gdPhi"};
      char OutTextFile[100];
      if(eCat_ == 1) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_y1.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      if(eCat_ == 2) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_y2.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      if(eCat_ == 3) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_y3.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      if(eCat_ == 4) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_lowpt.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      if(eCat_ == 5) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_y4.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      //sprintf(OutTextFile,"eff_HighPt_%s_%s_%s.tex", cSp[iSpec], cCd, cTrg[iCat]);
      ofstream dataFile(Form(OutTextFile));

      char tmp_start[512];
      sprintf(tmp_start,"%%%% Getting Efficiency starts, Category : %s !!!!! %%%%%", cCd);  
      cout<< tmp_start << endl;
      //dataFile<< tmp_start << endl;

      // x, y, z - axis 
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of Cent"<<endl;
      for(int i = 0; i < nCentBins; i++){
        if(i == (nCentBins-1)){
          xct_bound[i] = ct_bound[i-4] + (ct_bound[i-1]-ct_bound[i-4])/2;
          //cout<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
          //dataFile<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
        }else{
          xct_bound[i] = ct_bound[i] + (ct_bound[i+1]-ct_bound[i])/2;
          //cout<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
          //dataFile<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
        }
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of pT"<<endl;
      for(int i = 0; i < nPtBins; i++){
        xpt_bound[i] = pt_bound[i] + (pt_bound[i+1]-pt_bound[i])/2;
        //cout<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
        //dataFile<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of rap"<<endl;
      for(int i = 0; i < nRapBins; i++){
        xrap_bound[i] = rap_bound[i] + (rap_bound[i+1]-rap_bound[i])/2;
        //cout<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
        //dataFile<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of dphi"<<endl;
      for(int i = 0; i < ndPhiBins; i++){
        xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
        //cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
        //dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of phi"<<endl;
      for(int i = 0; i < nPhiBins; i++){
        xphi_bound[i] = phi_bound[i] + (phi_bound[i+1]-phi_bound[i])/2;
        //cout<<"xphi_bound["<<i<<"] : "<<xphi_bound[i]<<endl;
        //dataFile<<"xphi_bound["<<i<<"] : "<<xphi_bound[i]<<endl;
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of dphi2"<<endl;
      for(int i = 0; i < ndPhi2Bins; i++){
        xdphi2_bound[i] = dphi2_bound[i] + (dphi2_bound[i+1]-dphi2_bound[i])/2;
        //cout<<"xdphi2_bound["<<i<<"] : "<<xdphi2_bound[i]<<endl;
        //dataFile<<"xdphi2_bound["<<i<<"] : "<<xdphi2_bound[i]<<endl;
      }

      int nBins_tmp = 0;
      if(iSpec == 0) { nBins_tmp = nCentBins; }
      if(iSpec == 1) { nBins_tmp = nPtBins; }
      if(iSpec == 2) { nBins_tmp = nRapBins; }
      if(iSpec == 3) { nBins_tmp = nPhiBins; }
      if(iSpec == 4) { nBins_tmp = ndPhiBins; }
      if(iSpec == 5) { nBins_tmp = ndPhi2Bins; }
      const int nBins = nBins_tmp;

      TH1F *hTempMass = new TH1F("hTempMass","",100, 2.0, 4.0);
      TH1F *hGenDiMuonf[nFiles][nBins];
      TH1F *hRecoDiMuonf[nFiles][nBins];
      TH1F *hGenDiMuon[nBins];
      TH1F *hRecoDiMuon[nBins];
      double genNo[nBins];
      double genErr[nBins];
      double recoNo[nBins];
      double recoErr[nBins];
      double eff[nBins];
      double effErr[nBins];
      for(int fl = 0; fl < nFiles; fl++){
        for(int i = 0; i < nBins; i++){
          hGenDiMuonf[fl][i] = (TH1F*)hTempMass->Clone();
          hRecoDiMuonf[fl][i] = (TH1F*)hTempMass->Clone();
          hGenDiMuon[i] = (TH1F*)hTempMass->Clone();
          hRecoDiMuon[i] = (TH1F*)hTempMass->Clone();
          hGenDiMuonf[fl][i]->Sumw2();
          hRecoDiMuonf[fl][i]->Sumw2();
          hGenDiMuon[i]->Sumw2();
          hRecoDiMuon[i]->Sumw2();
        }
      }

      char fileName[10][512];
      //scales for different pT bins

      double scale[6]={5.83233e-06, 8.13987e-06, 3.64971e-06, 1.13816e-06, 3.50384e-07, 2.1568e-07};
      if(PutWeight==0){scale[0]=(1);scale[1]=(1);scale[2]=(1);scale[3]=(1);scale[4]=(1);scale[5]=(1);}

      // loop for pT
      cout<<"================================="<<endl;
      sprintf(fileName[0],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_0003.root");
      sprintf(fileName[1],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_0306.root");
      sprintf(fileName[2],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_0609.root");
      sprintf(fileName[3],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_0912.root");
      sprintf(fileName[4],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_1215.root");
      sprintf(fileName[5],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_1530.root");


      TFile *infile;
      TTree *tree;
      TTree *gentree;

      for(int ifile = 0; ifile < nFiles; 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;
        int hbit1;
        double zVtx;
        //Jpsi Variables
        Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
        Double_t JpsiVprob;
        Double_t JpsiPhi;
        Double_t JpsiEta;
        Double_t JpsiPsi[38];
        Double_t JpsiGenPsi;
        //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,muPos_TMOneST,muPos_trkLayMeas;
        bool muPos_matches,muPos_tracker;
        int muPos_Trigger2, muPos_Trigger10;
        int muPos_Trigger4, muPos_Trigger12, muPos_Trigger13;
        int muPos_Trigger21, muPos_Trigger22;
        //(2).Negative Muon                                     
        double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
        int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated,muNeg_TMOneST,muNeg_trkLayMeas;
        bool muNeg_matches,muNeg_tracker;
        int muNeg_Trigger2, muNeg_Trigger10;
        int muNeg_Trigger4, muNeg_Trigger12, muNeg_Trigger13;
        int muNeg_Trigger21, muNeg_Trigger22;

        //Gen Level variables
        //Gen PrJpsi Variables
        double GenJpsiMass, GenJpsiPt, GenJpsiRap;
        double GenJpsiPx, GenJpsiPy, GenJpsiPz;
        double GenJpsiPhi;
        double GenJpsiEta;
        double GenJpsiPsi;
        //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);
        tree->SetBranchAddress("hbit1",&hbit1);
        tree->SetBranchAddress("zVtx",&zVtx);

        //Jpsi Variables
        tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
        tree->SetBranchAddress("JpsiMass",&JpsiMass);
        tree->SetBranchAddress("JpsiPt",&JpsiPt);
        tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
        tree->SetBranchAddress("JpsiEta",&JpsiEta);
        tree->SetBranchAddress("JpsiPsi",&JpsiPsi);
        tree->SetBranchAddress("JpsiGenPsi",&JpsiGenPsi);
        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);
        tree->SetBranchAddress("muPos_TMOneST", &muPos_TMOneST);
        tree->SetBranchAddress("muPos_trkLayMeas", &muPos_trkLayMeas);
        tree->SetBranchAddress("muPos_Trigger2", &muPos_Trigger2);
        tree->SetBranchAddress("muPos_Trigger21", &muPos_Trigger21);
        tree->SetBranchAddress("muPos_Trigger22", &muPos_Trigger22);
        tree->SetBranchAddress("muPos_Trigger4", &muPos_Trigger4);
        tree->SetBranchAddress("muPos_Trigger10", &muPos_Trigger10);
        tree->SetBranchAddress("muPos_Trigger12", &muPos_Trigger12);
        tree->SetBranchAddress("muPos_Trigger13", &muPos_Trigger13);

        //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);
        tree->SetBranchAddress("muNeg_TMOneST", &muNeg_TMOneST);
        tree->SetBranchAddress("muNeg_trkLayMeas", &muNeg_trkLayMeas);
        tree->SetBranchAddress("muNeg_Trigger2", &muNeg_Trigger2);
        tree->SetBranchAddress("muNeg_Trigger21", &muNeg_Trigger21);
        tree->SetBranchAddress("muNeg_Trigger22", &muNeg_Trigger22);
        tree->SetBranchAddress("muNeg_Trigger4", &muNeg_Trigger4);
        tree->SetBranchAddress("muNeg_Trigger10", &muNeg_Trigger10);
        tree->SetBranchAddress("muNeg_Trigger12", &muNeg_Trigger12);
        tree->SetBranchAddress("muNeg_Trigger13", &muNeg_Trigger13);
        //====================================Gen Variables=========================================================
        //Gen Jpsi Variables
        gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
        gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
        gentree->SetBranchAddress("GenJpsiPhi",    &GenJpsiPhi);
        gentree->SetBranchAddress("GenJpsiPsi",    &GenJpsiPsi);
        gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
        gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
        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;

        for(int iGen=0; iGen< nGenEntries; iGen++)  {        
          //cout<<"i : "<<i<<endl;
          if(!(gentree->GetEntry(iGen))) continue;
          //cout<<" gentree ("<<i<<")"<<endl;
          //Only printing 
          if(iGen%10000==0){
            //cout<<" processing record "<<iGen<<"/"<<nGenEntries<<endl;
            //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
          }

          bool GenPosIn=0, GenNegIn=0;
          GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
          GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

          if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
          if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

          double GenCenWeight =0, GenWeight =0;
          GenCenWeight=FindCenWeight(gbin);   
          GenWeight=GenCenWeight*scale[ifile];

          hGenCent->Fill(gbin,GenWeight);

          int AccJpsi = 0;
          //if(GenJpsiPt < 6.5) continue;
          if((GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && fabs(GenJpsiRap) <= maxRap && 
                GenPosIn == 1 && GenNegIn == 1 && GenJpsiMass > 2.0 && GenJpsiMass < 4.0)) {AccJpsi = 1;}

          if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

          if(PutWeight==0) GenWeight=1; 

          //adding pT of all pt bins to see diss is cont

          //cout<<"1. GenJpsiPt : "<<GenJpsiPt<<", GenJpsiEta : "<<GenJpsiEta<<", GenJpsiRap : "<<GenJpsiRap<<", |GenJpsiPsi| : "<<TMath::Abs(GenJpsiPsi)<<endl;
          //cout<<"1. GenPosIn : "<<GenPosIn<<", GenNegIn : "<<GenNegIn<<endl;
          double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
          if(iSpec == 0) vars = gbin;
          if(iSpec == 1) vars = GenJpsiPt;
          if(iSpec == 2) vars = fabs(GenJpsiRap);
          if(iSpec == 3) vars = GenJpsiPhi;
          if(iSpec == 4) vars = fabs(GenJpsiPsi);
          if(iSpec == 5) vars = fabs(GenJpsiPsi);
          for(int i = 0; i < nBins; i++){
            if(iSpec == 0){
              bin1 = ct_bound[i]; bin2 = ct_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && fabs(GenJpsiRap) < maxRap ) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 1){
              bin1 = pt_bound[i]; bin2 = pt_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && fabs(GenJpsiRap) >= minRap && fabs(GenJpsiRap) < maxRap ) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 2){
              bin1 = rap_bound[i]; bin2 = rap_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 3){
              bin1 = phi_bound[i]; bin2 = phi_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt && fabs(GenJpsiRap) < maxRap) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 4){
              bin1 = dphi_bound[i]; bin2 = dphi_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt && fabs(GenJpsiRap) < maxRap) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 5){
              bin1 = dphi2_bound[i]; bin2 = dphi2_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt && fabs(GenJpsiRap) < maxRap) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
          }
        }//gen loop end

        //cout<<" accepted no "<< NAccep<<endl;

        //=============== Rec Tree Loop ==============================================================================

        int nRecEntries=tree->GetEntries();
        cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
        for(int iRec=0; iRec<nRecEntries; iRec++)  {     
          tree->GetEntry(iRec);
          //Only printing 
          if(iRec%10000==0){
            //cout<<" processing record "<<iRec<<"/"<<nRecEntries<<endl;
            //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
            //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<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); 

          double tnpWgt1 = 0.0, tnpWgt2 = 0.0;
          double staWgt1 = 0.0, staWgt2 = 0.0;

          double x = 0.0;
          if(fabs(muPosEta) < 0.9){
            x = muPosPt;
            tnpWgt1 = tnpSF1->Eval(x);
          }else if(fabs(muPosEta) < 1.6){
            x = muPosPt;
            tnpWgt1 = tnpSF2->Eval(x);
          }else if(fabs(muPosEta) < 2.1){
            x = muPosPt;
            tnpWgt1 = tnpSF3->Eval(x);
          }else{
            x = muPosPt;
            tnpWgt1 = tnpSF4->Eval(x);
          }

          if(fabs(muNegEta) < 0.9){
            x = muNegPt;
            tnpWgt2 = tnpSF1->Eval(x);
          }else if(fabs(muNegEta) < 1.6){
            x = muNegPt;
            tnpWgt2 = tnpSF2->Eval(x);
          }else if(fabs(muNegEta) < 2.1){
            x = muNegPt;
            tnpWgt2 = tnpSF3->Eval(x);
          }else{
            x = muNegPt;
            tnpWgt2 = tnpSF4->Eval(x);
          }

          double xta = 0.0;
          if(fabs(muPosEta) < 1.6){
            xta = muPosPt;
            staWgt1 = fun1->Eval(xta);
          }else{
            xta = muPosPt;
            staWgt1 = fun2->Eval(xta);
          }

          if(fabs(muNegEta) < 1.6){
            xta = muNegPt;
            staWgt2 = fun1->Eval(xta);
          }else{
            xta = muNegPt;
            staWgt2 = fun2->Eval(xta);
          }

          double RecCenWeight=0,RecWeight=0;
          RecCenWeight=FindCenWeight(rbin);   
          RecWeight=RecCenWeight*scale[ifile]*tnpWgt1*tnpWgt2*staWgt1*staWgt2;

          hRecCent->Fill(gbin,RecWeight);

          if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
          if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

          int AccJpsi = 0;
          if((JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && fabs(JpsiRap) <= maxRap && PosIn == 1 && NegIn == 1)) {AccJpsi = 1;}

          /*
             cout<<"muPos_pixeLayers : "<<muPos_pixeLayers<<" muPos_nchi2In : "<<muPos_nchi2In
             <<" TMath::Abs(muPos_dxy) : "<<TMath::Abs(muPos_dxy)<<" TMath::Abs(muPos_dz) : "<<TMath::Abs(muPos_dz)
             <<" muPos_trkLayMeas : "<<muPos_trkLayMeas
             <<" muPos_arbitrated : "<<muPos_arbitrated<<" muPos_TMOneST : "<<muPos_TMOneST<<" muPos_tracker : "<<muPos_tracker<<endl;
             cout<<"muNeg_pixeLayers : "<<muNeg_pixeLayers<<" muNeg_nchi2In : "<<muNeg_nchi2In
             <<" TMath::Abs(muNeg_dxy) : "<<TMath::Abs(muNeg_dxy)<<" TMath::Abs(muNeg_dz) : "<<TMath::Abs(muNeg_dz)
             <<" muNeg_trkLayMeas : "<<muNeg_trkLayMeas
             <<" muNeg_arbitrated : "<<muNeg_arbitrated<<" muNeg_TMOneST : "<<muNeg_TMOneST<<" muNeg_tracker : "<<muNeg_tracker<<endl;
             */
          bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
          bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

          if(muPos_found > 10 &&
              muPos_pixeLayers > 0 &&
              muPos_nchi2In < 4.0 &&
              TMath::Abs(muPos_dxy) < 3 &&
              TMath::Abs(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 &&
              TMath::Abs(muNeg_dxy) < 3 &&
              TMath::Abs(muNeg_dz) < 15 &&
              muNeg_nchi2Gl < 20 &&
              muNeg_arbitrated==1 &&
              muNeg_tracker==1){
            NegPass=1;
          }

          if(hbit1 == 1 && (muPos_Trigger22==1 && muNeg_Trigger22==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1) && mu_Global && mu_Tracker ){AllCut=1;}

          if(PutWeight==0)RecWeight=1;

          double JpsidPhi = JpsiGenPsi;

          //Eff loop for reco
          double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
          if(iSpec == 0) vars = rbin;
          if(iSpec == 1) vars = JpsiPt;
          if(iSpec == 2) vars = fabs(JpsiRap);
          if(iSpec == 3) vars = JpsiPhi;
          if(iSpec == 4) vars = fabs(JpsidPhi);
          if(iSpec == 5) vars = fabs(JpsiGenPsi);
          if((JpsiCharge == 0) && (JpsiVprob > 0.01) && (JpsiMass >= 2.95 && JpsiMass < 3.25)) {     
            for(int i = 0; i < nBins; i++){
              if(iSpec == 0){
                bin1 = ct_bound[i]; bin2 = ct_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && fabs(JpsiRap) <= maxRap ) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 1){
                bin1 = pt_bound[i]; bin2 = pt_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && fabs(JpsiRap) >= minRap && fabs(JpsiRap) <= maxRap ) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 2){ 
                bin1 = rap_bound[i]; bin2 = rap_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 3){ 
                bin1 = phi_bound[i]; bin2 = phi_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) <=maxRap) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 4){ 
                bin1 = dphi_bound[i]; bin2 = dphi_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) <=maxRap) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 5){ 
                bin1 = dphi2_bound[i]; bin2 = dphi2_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) <=maxRap) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
            }
          }
        } //rec tree loop ends
      }  // file loop ends

      //======================  File loop Starts ============================

      ///////////////////////////////////////////////////////////////////
      cout<< " adding "<<endl;
      TCanvas *c1 = new TCanvas();
      char gtmp[512], gtmp1[512];
      char rtmp[512], rtmp1[512];

      for(int i = 0; i < nBins; i++){
        for(int ifile = 0; ifile < nFiles; ifile++){
          hGenDiMuon[i]->Add(hGenDiMuonf[ifile][i],1);
          hRecoDiMuon[i]->Add(hRecoDiMuonf[ifile][i],1);
        }
        if(iSpec == 0) sprintf(gtmp,"hGenDiMuon_Cent_%1.f_%1.f",ct_bound[i],ct_bound[i+1]);
        if(iSpec == 1) sprintf(gtmp,"hGenDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
        if(iSpec == 2) sprintf(gtmp,"hGenDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
        if(iSpec == 0) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Cent_%1.f_%1.f_%s.png",ct_bound[i],ct_bound[i+1],cCd);
        if(iSpec == 1) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Pt_%0.1f_%0.1f_%s.png",pt_bound[i],pt_bound[i+1],cCd);
        if(iSpec == 2) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Rap_%0.1f_%0.1f_%s.png",rap_bound[i],rap_bound[i+1],cCd);
        if(iSpec == 0) sprintf(rtmp,"hRecDiMuon_Cent_%1.f_%1.f",ct_bound[i],ct_bound[i+1]);
        if(iSpec == 1) sprintf(rtmp,"hRecDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
        if(iSpec == 2) sprintf(rtmp,"hRecDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
        if(iSpec == 0) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Cent_%1.f_%1.f_%s.png",ct_bound[i],ct_bound[i+1],cCd);
        if(iSpec == 1) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Pt_%0.1f_%0.1f_%s.png",pt_bound[i],pt_bound[i+1],cCd);
        if(iSpec == 2) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Rap_%0.1f_%0.1f_%s.png",rap_bound[i],rap_bound[i+1],cCd);
        hGenDiMuon[i]->SetName(gtmp);
        //hGenDiMuon[i]->Write();
        //hGenDiMuon[ipt][irap][idphi]->Draw();
        //c1->SaveAs(gtmp1);
        hRecoDiMuon[i]->SetName(rtmp);
        //hRecoDiMuon[i]->Write();
        //hRecoDiMuon[ipt][irap][idphi]->Draw();
        //c1->SaveAs(rtmp1);
      }

      TH1F *hReco = new TH1F();
      TH1F *hGen = new TH1F();
      hReco->Sumw2();
      hGen->Sumw2();
      int nRecoBins;
      int nGenBins;
      if(iSpec == 0) {hReco = new TH1F("hReco","hReco;Centrality (%);Weighted Yields",nCentBins,ct_bound2); nRecoBins = nCentBins;}
      if(iSpec == 1) {hReco = new TH1F("hReco","hReco;p_{T} GeV/c;Weighted Yields",nPtBins,pt_bound); nRecoBins = nPtBins;}
      if(iSpec == 2) {hReco = new TH1F("hReco","hReco;y;Weighted Yields",nRapBins,rap_bound); nRecoBins = nRapBins;}
      if(iSpec == 3) {hReco = new TH1F("hReco","hReco;#phi;Weighted Yields",nPhiBins,phi_bound); nRecoBins = nPhiBins;}
      if(iSpec == 4) {hReco = new TH1F("hReco","hReco;d#phi;Weighted Yields",ndPhiBins,dphi_bound); nRecoBins = ndPhiBins;}
      if(iSpec == 5) {hReco = new TH1F("hReco","hReco;d#phi;Weighted Yields",ndPhi2Bins,dphi2_bound); nRecoBins = ndPhi2Bins;}

      if(iSpec == 0) {hGen = new TH1F("hGen","hGen;Centrality (%);Weighted Yields",nCentBins,ct_bound2); nGenBins = nCentBins;}
      if(iSpec == 1) {hGen = new TH1F("hGen","hGen;p_{T} GeV/c;Weighted Yields",nPtBins,pt_bound); nGenBins = nPtBins;}
      if(iSpec == 2) {hGen = new TH1F("hGen","hGen;y;Weighted Yields",nRapBins,rap_bound); nGenBins = nRapBins;}
      if(iSpec == 3) {hGen = new TH1F("hGen","hGen;#phi;Weighted Yields",nPhiBins,phi_bound); nGenBins = nPhiBins;}
      if(iSpec == 4) {hGen = new TH1F("hGen","hGen;d#phi;Weighted Yields",ndPhiBins,dphi_bound); nGenBins = ndPhiBins;}
      if(iSpec == 5) {hGen = new TH1F("hGen","hGen;d#phi;Weighted Yields",ndPhi2Bins,dphi2_bound); nGenBins = ndPhi2Bins;}

      cout<<"Starts to calculate efficiency"<<endl;
      //dataFile<<""<<endl;
      //=====================Loop for eff========================================================================================//
      //define stuff here for error on weighted samples
      for(int i = 0; i < nBins; i++){
        int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.0);//2.95
        int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(4.0);//2.95
        //int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
        //int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

        int Rbinlow =hRecoDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
        int Rbinhi=hRecoDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

        cout<<"Gbinlow : "<<Gbinlow<<", Gbinhi : "<<Gbinhi<<endl;
        cout<<"Rbinlow : "<<Rbinlow<<", Rbinhi : "<<Rbinhi<<endl;

        genNo[i] = hGenDiMuon[i]->IntegralAndError(Gbinlow, Gbinhi, genErr[i]);
        recoNo[i] = hRecoDiMuon[i]->IntegralAndError(Rbinlow, Rbinhi, recoErr[i]);

        //calculate Eff         
        if(genNo[i] == 0 || recoNo[i] == 0) {
          cout<<"No Gen or Reco, # of Gen : "<<genNo[i] <<", # of Reco : "<<recoNo[i]<<endl;
          eff[i] = 0;
          effErr[i] = 0;
        }else{
          eff[i] = recoNo[i]/genNo[i]; 

          double tmpGenNo = genNo[i];
          double tmpGenErr = genErr[i];
          double tmpRecNo = recoNo[i];
          double tmpRecErr = recoErr[i];
          double tmpEff = eff[i];
          double tmpEffErr = 0.0;

          hReco->SetBinContent(i+1,tmpRecNo);
          hReco->SetBinError(i+1,tmpRecErr);
          hGen->SetBinContent(i+1,tmpGenNo);
          hGen->SetBinError(i+1,tmpGenErr);

          //error    
          double tmp_err_s1_1 = (tmpEff * tmpEff)/(tmpGenNo * tmpGenNo);
          double tmp_err_s1_2 = (tmpRecErr * tmpRecErr);
          double tmp_err_cat_s1 = tmp_err_s1_1 * tmp_err_s1_2;


          double tmp_err_s2_1 = ( (1 - tmpEff)*(1 - tmpEff) ) / (tmpGenNo * tmpGenNo);
          double tmp_err_s2_2 = TMath::Abs(( tmpGenErr*tmpGenErr ) - ( tmpRecErr * tmpRecErr));
          double tmp_err_cat_s2 = tmp_err_s2_1 * tmp_err_s2_2;
          tmpEffErr = sqrt( tmp_err_cat_s1 + tmp_err_cat_s2 );

          effErr[i] = tmpEffErr;

          //error without weight
          //dataFile<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< tmpRecNo  <<", Gen Jpsi : "<< tmpGenNo <<endl;
          //dataFile<<" Eff ["<<i<<"] - "<< tmpEff <<" Error "<< tmpEffErr <<endl;
          cout<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< tmpRecNo  <<", Gen Jpsi : "<< tmpGenNo <<endl;
          cout<<" Eff ["<<i<<"] - "<< tmpEff <<" Error "<< tmpEffErr <<endl;
        }
      }
      TH1F *hEff = new TH1F();
      hEff->Sumw2();
      int nEffBins = 0;
      if(iSpec == 0) {hEff = new TH1F("hEff","hEff;Centrality (%);Efficiency",nCentBins,ct_bound2); nEffBins = nCentBins;}
      if(iSpec == 1) {hEff = new TH1F("hEff","hEff;p_{T} GeV/c;Efficiency",nPtBins,pt_bound); nEffBins = nPtBins;}
      if(iSpec == 2) {hEff = new TH1F("hEff","hEff;y;Efficiency",nRapBins,rap_bound); nEffBins = nRapBins;}
      if(iSpec == 3) {hEff = new TH1F("hEff","hEff;#phi;Efficiency",nPhiBins,phi_bound); nEffBins = nPhiBins;}
      if(iSpec == 4) {hEff = new TH1F("hEff","hEff;d#phi;Efficiency",ndPhiBins,dphi_bound); nEffBins = ndPhiBins;}
      if(iSpec == 5) {hEff = new TH1F("hEff","hEff;d#phi;Efficiency",ndPhi2Bins,dphi2_bound); nEffBins = ndPhi2Bins;}

      for(int i = 0; i < nEffBins; i++){
        hEff->SetBinContent(i+1,eff[i]);
        hEff->SetBinError(i+1,effErr[i]);
        cout<<"Trying to measure Reconstruction eff vs "<<cSp[iSpec]<<endl;
        cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
        dataFile<<eff[i]<<endl;//", err : "<<effErr[i]<<endl;
        //dataFile<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      }

      outfile->cd();
      hEff->Draw();
      char tmp_histo[512];
      sprintf(tmp_histo,"hEff_%s",cSp[iSpec]);
      char tmp_histo_reco[512];
      sprintf(tmp_histo_reco,"hReco_%s",cSp[iSpec]);
      char tmp_histo_gen[512];
      sprintf(tmp_histo_gen,"hGen_%s",cSp[iSpec]);
      hEff->SetName(tmp_histo);
      hEff->Write();
      hReco->SetName(tmp_histo_reco);
      hReco->Write();
      hGen->SetName(tmp_histo_gen);
      hGen->Write();
      //c1->SaveAs("eff_3D_default_etHFm.png");
      //outfile->Close();
      dataFile<<""<<endl;
      dataFile.close();
    }
    hGenCent->Write();
    hRecCent->Write();
    outfile->Write();
  }
}
Пример #16
0
Visualization::Abstract::DataSet* CSConvectionFile::load(const std::vector<std::string>& args) const
	{
	/* Open the data file: */
	Misc::File dataFile(args[0].c_str(),"rt");
	
	/* Read data file's header: */
	char line[256];
	dataFile.gets(line,sizeof(line)); // Skip title field
	if(strncmp(line,"TITLE=",6)!=0)
		Misc::throwStdErr("CSConvectionFile::load: Wrong format in data file header");
	dataFile.gets(line,sizeof(line)); // Skip variable field
	if(strncmp(line,"VARIABLES=",10)!=0)
		Misc::throwStdErr("CSConvectionFile::load: Wrong format in data file header");
	
	/* Determine which zone to read: */
	int zoneIndex=0;
	if(args.size()>1)
		zoneIndex=atoi(args[1].c_str());
	
	/* Read the first zone from the data file: */
	dataFile.gets(line,sizeof(line)); // Read size field
	if(strncmp(line,"ZONE ",5)!=0)
		Misc::throwStdErr("CSConvectionFile::load: Wrong format in data file header");
	DS::Index numZoneVertices=parseZoneSize(line);
	
	/* Skip zones until the correct one: */
	for(int i=0;i<zoneIndex;++i)
		{
		/* Skip all nodes of this zone: */
		size_t numNodes=size_t(numZoneVertices.calcIncrement(-1));
		for(size_t j=0;j<numNodes;++j)
			dataFile.gets(line,sizeof(line));
		
		/* Read the next zone header: */
		dataFile.gets(line,sizeof(line)); // Read size field
		if(strncmp(line,"ZONE ",5)!=0)
			Misc::throwStdErr("CSConvectionFile::load: Wrong format in data file header");
		numZoneVertices=parseZoneSize(line);
		}
	
	/* Create the result data set: */
	DataSet* result=new DataSet;
	result->getDs().setData(numZoneVertices);
	
	/* Read all vertex positions and values: */
	DS::Array& vertices=result->getDs().getVertices();
	for(DS::Array::iterator vIt=vertices.begin();vIt!=vertices.end();++vIt)
		{
		dataFile.gets(line,sizeof(line));
		float pos[3];
		float temp,visc;
		float vel[3];
		if(sscanf(line,"%f %f %f %f %f %f %f %f",&pos[0],&pos[1],&pos[2],&temp,&visc,&vel[0],&vel[1],&vel[2])!=8)
			Misc::throwStdErr("CSConvectionFile::load: Error while reading grid data");
		
		sphericalToCartesian(vIt->pos,pos);
		vIt->value.temperature=temp;
		vIt->value.viscosity=Math::log(visc);
		sphericalToCartesian(vIt->value.velocity,vel);
		}
	
	/* Finalize the grid structure: */
	result->getDs().finalizeGrid();
	
	return result;
	}
Пример #17
0
void mergeEff() {
  TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
  dir.ReplaceAll("mergeEff.C","");
  dir.ReplaceAll("/./","/");
  ifstream in;
  const int nBin = 3; 
  double eff[100][100] = {0.0};
  for(int idir = 1; idir < 101; idir++){
    in.open(Form("%s../Eff_00%d/eff_HighPt_Pts_default_Bit1_y_1.6_2.4_pT_3.0_30.0_pr.tex",dir.Data(),idir));
    Float_t x[300];
    Int_t nlines = 0;
    int nl = 0;
    while (1) {
      in >> x[0] ;
      eff[nl][idir-1] = x[0]; 
      //cout<<"eff : "<<eff[nl][idir-1]<<endl;
      if (!in.good()) break;
      nlines++;
      nl++;
    }
    in.close();
  }

  TH1F *hDis[13]; 

  string eff_tot[100];
  for(int in = 0; in < nBin; in++){
    //hDis[in] = new TH1F(Form("hDis_%d",in),"",20,0.35,0.65); // cent
    hDis[in] = new TH1F(Form("hDis_%d",in),"",150,0.05,0.65); // pT
    hDis[in]->Sumw2();
    hDis[in]->SetMarkerStyle(20);
    hDis[in]->SetMarkerSize(1.2);
    puts("");
    for(int id = 0; id < 100; id++){
      printf("%0.4f ", eff[in][id]);
      hDis[in]->Fill(eff[in][id]);
    }
  }
  puts(""); 

  TLatex *lt = new TLatex();
  lt->SetNDC();
  const int nPtBins = 3;
  double pt_bound[nPtBins+1] = {3.0, 4.5, 5.5, 6.5};
  char OutTextFile[100];
  sprintf(OutTextFile,"pbpb_prompt_lowpt.tex");
  ofstream dataFile(OutTextFile);

  TCanvas *c1 = new TCanvas("c1","",1200,400);
  c1->Divide(3,1);
  for(int ic = 1; ic < nBin+1; ic++){
    c1->cd(ic);
    hDis[ic-1]->GetXaxis()->SetRangeUser(0.0,0.5);
    hDis[ic-1]->GetXaxis()->SetTitle("Efficiency");
    hDis[ic-1]->Draw("E");
    //cout<<"Mean : "<<hDis[ic-1]->GetMean()<<endl;
    //cout<<"RMS : "<<hDis[ic-1]->GetRMS()<<endl;
    cout<<hDis[ic-1]->GetMean()<<" "<<hDis[ic-1]->GetRMS()<<endl;
    dataFile<<"pT : "<<pt_bound[ic-1]<<"-"<<pt_bound[ic]<<endl;
    dataFile<<hDis[ic-1]->GetMean()<<" "<<hDis[ic-1]->GetRMS()<<endl;
    lt->DrawLatex(0.15,0.95,Form("PbPb, p_{T} [%0.1f,%0.1f], y [1.6,2.4]",pt_bound[ic-1],pt_bound[ic]));
    lt->DrawLatex(0.15,0.85,"Cent [0,100]");
  }

  c1->SaveAs("plot_pbpb_eff_STA_pr_dis_lowpt.png");c1->SaveAs("plot_pbpb_eff_STA_pr_dis_lowpt.pdf");

  return;
}
Пример #18
0
void FileBrowserTreeWidget::mousePressEvent(QMouseEvent * me )
{
	QTreeWidget::mousePressEvent( me );
	if( me->button() != Qt::LeftButton )
	{
		return;
	}

	QTreeWidgetItem * i = itemAt( me->pos() );
	if ( i )
	{
		// TODO: Restrict to visible selection
//		if ( _me->x() > header()->cellPos( header()->mapToActual( 0 ) )
//			+ treeStepSize() * ( i->depth() + ( rootIsDecorated() ?
//						1 : 0 ) ) + itemMargin() ||
//				_me->x() < header()->cellPos(
//						header()->mapToActual( 0 ) ) )
//		{
			m_pressPos = me->pos();
			m_mousePressed = true;
//		}
	}

	FileItem * f = dynamic_cast<FileItem *>( i );
	if( f != NULL )
	{
		m_pphMutex.lock();
		if( m_previewPlayHandle != NULL )
		{
			Engine::mixer()->removePlayHandle(
							m_previewPlayHandle );
			m_previewPlayHandle = NULL;
		}

		// in special case of sample-files we do not care about
		// handling() rather than directly creating a SamplePlayHandle
		if( f->type() == FileItem::SampleFile )
		{
			TextFloat * tf = TextFloat::displayMessage(
					tr( "Loading sample" ),
					tr( "Please wait, loading sample for "
								"preview..." ),
					embed::getIconPixmap( "sample_file",
								24, 24 ), 0 );
			qApp->processEvents(
					QEventLoop::ExcludeUserInputEvents );
			SamplePlayHandle * s = new SamplePlayHandle(
								f->fullName() );
			s->setDoneMayReturnTrue( false );
			m_previewPlayHandle = s;
			delete tf;
		}
		else if( ( f->extension ()== "xiz" || f->extension() == "sf2" || f->extension() == "gig" ) && 
			! pluginFactory->pluginSupportingExtension(f->extension()).isNull() )
		{
			m_previewPlayHandle = new PresetPreviewPlayHandle( f->fullName(), f->handling() == FileItem::LoadByPlugin );
		}
		else if( f->type() != FileItem::VstPluginFile &&
				( f->handling() == FileItem::LoadAsPreset ||
				f->handling() == FileItem::LoadByPlugin ) )
		{
			DataFile dataFile( f->fullName() );
			if( !dataFile.validate( f->extension() ) )
			{
				QMessageBox::warning( 0, tr ( "Error" ),
					f->fullName() + " " + tr( "does not appear to be a valid" ) + " " + f->extension() +
									  " " + tr( "file" ),
					QMessageBox::Ok, QMessageBox::NoButton );
				m_pphMutex.unlock();
				return;
			}
			m_previewPlayHandle = new PresetPreviewPlayHandle( f->fullName(), f->handling() == FileItem::LoadByPlugin, &dataFile );
		}
		if( m_previewPlayHandle != NULL )
		{
			if( !Engine::mixer()->addPlayHandle(
							m_previewPlayHandle ) )
			{
				m_previewPlayHandle = NULL;
			}
		}
		m_pphMutex.unlock();
	}
}
Пример #19
0
// load given song
void Song::loadProject( const QString & fileName )
{
	QDomNode node;

	m_loadingProject = true;

	Engine::projectJournal()->setJournalling( false );

	m_fileName = fileName;
	m_oldFileName = fileName;

	DataFile dataFile( m_fileName );
	// if file could not be opened, head-node is null and we create
	// new project
	if( dataFile.validate( fileName.right( fileName.lastIndexOf(".") ) ) )
	{
		return;
	}

	clearProject();

	clearErrors();

	DataFile::LocaleHelper localeHelper( DataFile::LocaleHelper::ModeLoad );

	Engine::mixer()->lock();

	// get the header information from the DOM
	m_tempoModel.loadSettings( dataFile.head(), "bpm" );
	m_timeSigModel.loadSettings( dataFile.head(), "timesig" );
	m_masterVolumeModel.loadSettings( dataFile.head(), "mastervol" );
	m_masterPitchModel.loadSettings( dataFile.head(), "masterpitch" );

	if( m_playPos[Mode_PlaySong].m_timeLine )
	{
		// reset loop-point-state
		m_playPos[Mode_PlaySong].m_timeLine->toggleLoopPoints( 0 );
	}

	if( !dataFile.content().firstChildElement( "track" ).isNull() )
	{
		m_globalAutomationTrack->restoreState( dataFile.content().
						firstChildElement( "track" ) );
	}

	//Backward compatibility for LMMS <= 0.4.15
	PeakController::initGetControllerBySetting();

	// Load mixer first to be able to set the correct range for FX channels
	node = dataFile.content().firstChildElement( Engine::fxMixer()->nodeName() );
	if( !node.isNull() )
	{
		Engine::fxMixer()->restoreState( node.toElement() );
		if( gui )
		{
			// refresh FxMixerView
			gui->fxMixerView()->refreshDisplay();
		}
	}

	node = dataFile.content().firstChild();
	while( !node.isNull() )
	{
		if( node.isElement() )
		{
			if( node.nodeName() == "trackcontainer" )
			{
				( (JournallingObject *)( this ) )->restoreState( node.toElement() );
			}
			else if( node.nodeName() == "controllers" )
			{
				restoreControllerStates( node.toElement() );
			}
			else if( gui )
			{
				if( node.nodeName() == gui->getControllerRackView()->nodeName() )
				{
					gui->getControllerRackView()->restoreState( node.toElement() );
				}
				else if( node.nodeName() == gui->pianoRoll()->nodeName() )
				{
					gui->pianoRoll()->restoreState( node.toElement() );
				}
				else if( node.nodeName() == gui->automationEditor()->m_editor->nodeName() )
				{
					gui->automationEditor()->m_editor->restoreState( node.toElement() );
				}
				else if( node.nodeName() == gui->getProjectNotes()->nodeName() )
				{
					 gui->getProjectNotes()->SerializingObject::restoreState( node.toElement() );
				}
				else if( node.nodeName() == m_playPos[Mode_PlaySong].m_timeLine->nodeName() )
				{
					m_playPos[Mode_PlaySong].m_timeLine->restoreState( node.toElement() );
				}
			}
		}
		node = node.nextSibling();
	}

	// quirk for fixing projects with broken positions of TCOs inside
	// BB-tracks
	Engine::getBBTrackContainer()->fixIncorrectPositions();

	// Connect controller links to their controllers 
	// now that everything is loaded
	ControllerConnection::finalizeConnections();

	// resolve all IDs so that autoModels are automated
	AutomationPattern::resolveAllIDs();


	Engine::mixer()->unlock();

	ConfigManager::inst()->addRecentlyOpenedProject( fileName );

	Engine::projectJournal()->setJournalling( true );

	emit projectLoaded();

	if ( hasErrors())
	{
		if ( gui )
		{
			QMessageBox::warning( NULL, "LMMS Error report", *errorSummary(),
							QMessageBox::Ok );
		}
		else
		{
			QTextStream(stderr) << *Engine::getSong()->errorSummary() << endl;
		}
	}

	m_loadingProject = false;
	m_modified = false;

	if( gui && gui->mainWindow() )
	{
		gui->mainWindow()->resetWindowTitle();
	}
}
Пример #20
0
int main( int argc, char * * argv )
{
	// initialize memory managers
	MemoryManager::init();
	NotePlayHandleManager::init();

	// intialize RNG
	srand( getpid() + time( 0 ) );

	disable_denormals();

	bool coreOnly = false;
	bool fullscreen = true;
	bool exitAfterImport = false;
	bool allowRoot = false;
	bool renderLoop = false;
	bool renderTracks = false;
	QString fileToLoad, fileToImport, renderOut, profilerOutputFile, configFile;

	// first of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--help"    || arg == "-h" ||
		    arg == "--version" || arg == "-v" ||
		    arg == "--render"  || arg == "-r" )
		{
			coreOnly = true;
		}
		else if( arg == "--rendertracks" )
		{
			coreOnly = true;
			renderTracks = true;
		}
		else if( arg == "--allowroot" )
		{
			allowRoot = true;
		}
		else if( arg == "--geometry" || arg == "-geometry")
		{
			if( arg == "--geometry" )
			{
				// Delete the first "-" so Qt recognize the option
				strcpy(argv[i], "-geometry");
			}
			// option -geometry is filtered by Qt later,
			// so we need to check its presence now to
			// determine, if the application should run in
			// fullscreen mode (default, no -geometry given).
			fullscreen = false;
		}
	}

#ifndef LMMS_BUILD_WIN32
	if ( ( getuid() == 0 || geteuid() == 0 ) && !allowRoot )
	{
		printf( "LMMS cannot be run as root.\nUse \"--allowroot\" to override.\n\n" );
		return EXIT_FAILURE;
	}	
#endif

	QCoreApplication * app = coreOnly ?
			new QCoreApplication( argc, argv ) :
					new QApplication( argc, argv ) ;

	Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality );
	ProjectRenderer::OutputSettings os( 44100, false, 160,
						ProjectRenderer::Depth_16Bit );
	ProjectRenderer::ExportFileFormats eff = ProjectRenderer::WaveFile;

	// second of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--version" || arg == "-v" )
		{
			printVersion( argv[0] );
			return EXIT_SUCCESS;
		}
		else if( arg == "--help" || arg  == "-h" )
		{
			printHelp();
			return EXIT_SUCCESS;
		}
		else if( arg == "--upgrade" || arg == "-u" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			DataFile dataFile( QString::fromLocal8Bit( argv[i] ) );

			if( argc > i+1 ) // output file specified
			{
				dataFile.writeFile( QString::fromLocal8Bit( argv[i+1] ) );
			}
			else // no output file specified; use stdout
			{
				QTextStream ts( stdout );
				dataFile.write( ts );
				fflush( stdout );
			}

			return EXIT_SUCCESS;
		}
		else if( arg == "--allowroot" )
		{
			// Ignore, processed earlier
#ifdef LMMS_BUILD_WIN32
			if( allowRoot )
			{
				printf( "\nOption \"--allowroot\" will be ignored on this platform.\n\n" );
			}
#endif
			
		}
		else if( arg == "--dump" || arg == "-d" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			QFile f( QString::fromLocal8Bit( argv[i] ) );
			f.open( QIODevice::ReadOnly );
			QString d = qUncompress( f.readAll() );
			printf( "%s\n", d.toUtf8().constData() );

			return EXIT_SUCCESS;
		}
		else if( arg == "--render" || arg == "-r" || arg == "--rendertracks" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToLoad = QString::fromLocal8Bit( argv[i] );
			renderOut = fileToLoad;
		}
		else if( arg == "--loop" || arg == "-l" )
		{
			renderLoop = true;
		}
		else if( arg == "--output" || arg == "-o" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			renderOut = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--format" || arg == "-f" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output format specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ext = QString( argv[i] );

			if( ext == "wav" )
			{
				eff = ProjectRenderer::WaveFile;
			}
#ifdef LMMS_HAVE_OGGVORBIS
			else if( ext == "ogg" )
			{
				eff = ProjectRenderer::OggFile;
			}
#endif
			else
			{
				printf( "\nInvalid output format %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--samplerate" || arg == "-s" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo samplerate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			sample_rate_t sr = QString( argv[i] ).toUInt();
			if( sr >= 44100 && sr <= 192000 )
			{
				os.samplerate = sr;
			}
			else
			{
				printf( "\nInvalid samplerate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--bitrate" || arg == "-b" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo bitrate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int br = QString( argv[i] ).toUInt();

			if( br >= 64 && br <= 384 )
			{
				os.bitrate = br;
			}
			else
			{
				printf( "\nInvalid bitrate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg =="--float" || arg == "-a" )
		{
			os.depth = ProjectRenderer::Depth_32Bit;
		}
		else if( arg == "--interpolation" || arg == "-i" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo interpolation method specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ip = QString( argv[i] );

			if( ip == "linear" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_Linear;
			}
			else if( ip == "sincfastest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincFastest;
			}
			else if( ip == "sincmedium" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincMedium;
			}
			else if( ip == "sincbest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincBest;
			}
			else
			{
				printf( "\nInvalid interpolation method %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--oversampling" || arg == "-x" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo oversampling specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int o = QString( argv[i] ).toUInt();

			switch( o )
			{
				case 1:
		qs.oversampling = Mixer::qualitySettings::Oversampling_None;
		break;
				case 2:
		qs.oversampling = Mixer::qualitySettings::Oversampling_2x;
		break;
				case 4:
		qs.oversampling = Mixer::qualitySettings::Oversampling_4x;
		break;
				case 8:
		qs.oversampling = Mixer::qualitySettings::Oversampling_8x;
		break;
				default:
				printf( "\nInvalid oversampling %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--import" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo file specified for importing.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToImport = QString::fromLocal8Bit( argv[i] );

			// exit after import? (only for debugging)
			if( QString( argv[i + 1] ) == "-e" )
			{
				exitAfterImport = true;
				++i;
			}
		}
		else if( arg == "--profile" || arg == "-p" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo profile specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			profilerOutputFile = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--config" || arg == "-c" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo configuration file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}

			configFile = QString::fromLocal8Bit( argv[i] );
		}
		else
		{
			if( argv[i][0] == '-' )
			{
				printf( "\nInvalid option %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
			fileToLoad = QString::fromLocal8Bit( argv[i] );
		}
	}

	// Test file argument before continuing
	if( !fileToLoad.isEmpty() )
	{
		fileCheck( fileToLoad );
	}
	else if( !fileToImport.isEmpty() )
	{
		fileCheck( fileToImport );
	}

	ConfigManager::inst()->loadConfigFile(configFile);

	// set language
	QString pos = ConfigManager::inst()->value( "app", "language" );
	if( pos.isEmpty() )
	{
		pos = QLocale::system().name().left( 2 );
	}

#ifdef LMMS_BUILD_WIN32
#undef QT_TRANSLATIONS_DIR
#define QT_TRANSLATIONS_DIR ConfigManager::inst()->localeDir()
#endif

#ifdef QT_TRANSLATIONS_DIR
	// load translation for Qt-widgets/-dialogs
	loadTranslation( QString( "qt_" ) + pos,
					QString( QT_TRANSLATIONS_DIR ) );
#endif
	// load actual translation for LMMS
	loadTranslation( pos );


	// try to set realtime priority
#ifdef LMMS_BUILD_LINUX
#ifdef LMMS_HAVE_SCHED_H
#ifndef __OpenBSD__
	struct sched_param sparam;
	sparam.sched_priority = ( sched_get_priority_max( SCHED_FIFO ) +
				sched_get_priority_min( SCHED_FIFO ) ) / 2;
	if( sched_setscheduler( 0, SCHED_FIFO, &sparam ) == -1 )
	{
		printf( "Notice: could not set realtime priority.\n" );
	}
#endif
#endif
#endif

#ifdef LMMS_BUILD_WIN32
	if( !SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
	{
		printf( "Notice: could not set high priority.\n" );
	}
#endif

#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
	struct sigaction sa;
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = SA_SIGINFO;
	if ( sigemptyset( &sa.sa_mask ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
	if ( sigaction( SIGPIPE, &sa, NULL ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
#endif

	bool destroyEngine = false;

	// if we have an output file for rendering, just render the song
	// without starting the GUI
	if( !renderOut.isEmpty() )
	{
		Engine::init( true );
		destroyEngine = true;

		printf( "Loading project...\n" );
		Engine::getSong()->loadProject( fileToLoad );
		if( Engine::getSong()->isEmpty() )
		{
			printf("The project %s is empty, aborting!\n", fileToLoad.toUtf8().constData() );
			exit( EXIT_FAILURE );
		}
		printf( "Done\n" );

		Engine::getSong()->setExportLoop( renderLoop );

		// when rendering multiple tracks, renderOut is a directory
		// otherwise, it is a file, so we need to append the file extension
		if ( !renderTracks )
		{
			renderOut = baseName( renderOut ) +
				ProjectRenderer::getFileExtensionFromFormat(eff);
		}

		// create renderer
		RenderManager * r = new RenderManager( qs, os, eff, renderOut );
		QCoreApplication::instance()->connect( r,
				SIGNAL( finished() ), SLOT( quit() ) );

		// timer for progress-updates
		QTimer * t = new QTimer( r );
		r->connect( t, SIGNAL( timeout() ),
				SLOT( updateConsoleProgress() ) );
		t->start( 200 );

		if( profilerOutputFile.isEmpty() == false )
		{
			Engine::mixer()->profiler().setOutputFile( profilerOutputFile );
		}

		// start now!
		if ( renderTracks )
		{
			r->renderTracks();
		}
		else
		{
			r->renderProject();
		}
	}
	else // otherwise, start the GUI
	{
		new GuiApplication();

		// re-intialize RNG - shared libraries might have srand() or
		// srandom() calls in their init procedure
		srand( getpid() + time( 0 ) );

		// recover a file?
		QString recoveryFile = ConfigManager::inst()->recoveryFile();

		bool recoveryFilePresent = QFileInfo( recoveryFile ).exists() &&
				QFileInfo( recoveryFile ).isFile();
		bool autoSaveEnabled =
			!ConfigManager::inst()->value( "ui", "disableautosave" ).toInt();
		if( recoveryFilePresent )
		{
			QMessageBox mb;
			mb.setWindowTitle( MainWindow::tr( "Project recovery" ) );
			mb.setText( QString(
				"<html>"
				"<p style=\"margin-left:6\">%1</p>"
				"<table cellpadding=\"3\">"
				"  <tr>"
				"    <td><b>%2</b></td>"
				"    <td>%3</td>"
				"  </tr>"
				"  <tr>"
				"    <td><b>%4</b></td>"
				"    <td>%5</td>"
				"  </tr>"
				"  <tr>"
				"    <td><b>%6</b></td>"
				"    <td>%7</td>"
				"  </tr>"
				"</table>"
				"</html>" ).arg(
				MainWindow::tr( "There is a recovery file present. "
					"It looks like the last session did not end "
					"properly or another instance of LMMS is "
					"already running. Do you want to recover the "
					"project of this session?" ),
				MainWindow::tr( "Recover" ),
				MainWindow::tr( "Recover the file. Please don't run "
					"multiple instances of LMMS when you do this." ),
				MainWindow::tr( "Ignore" ),
				MainWindow::tr( "Launch LMMS as usual but with "
					"automatic backup disabled to prevent the "
					"present recover file from being overwritten." ),
				MainWindow::tr( "Discard" ),
				MainWindow::tr( "Launch a default session and delete "
					"the restored files. This is not reversible." )
							) );

			mb.setIcon( QMessageBox::Warning );
			mb.setWindowIcon( embed::getIconPixmap( "icon" ) );
			mb.setWindowFlags( Qt::WindowCloseButtonHint );

			QPushButton * recover;
			QPushButton * discard;
			QPushButton * ignore;
			QPushButton * exit;
			
			#if QT_VERSION >= 0x050000
				// setting all buttons to the same roles allows us 
				// to have a custom layout
				discard = mb.addButton( MainWindow::tr( "Discard" ),
									QMessageBox::AcceptRole );
				ignore = mb.addButton( MainWindow::tr( "Ignore" ),
									QMessageBox::AcceptRole );
				recover = mb.addButton( MainWindow::tr( "Recover" ),
									QMessageBox::AcceptRole );

			# else 
				// in qt4 the button order is reversed
				recover = mb.addButton( MainWindow::tr( "Recover" ),
									QMessageBox::AcceptRole );
				ignore = mb.addButton( MainWindow::tr( "Ignore" ),
									QMessageBox::AcceptRole );
				discard = mb.addButton( MainWindow::tr( "Discard" ),
									QMessageBox::AcceptRole );

			#endif
			
			// have a hidden exit button
			exit = mb.addButton( "", QMessageBox::RejectRole);
			exit->setVisible(false);
			
			// set icons
			recover->setIcon( embed::getIconPixmap( "recover" ) );
			discard->setIcon( embed::getIconPixmap( "discard" ) );
			ignore->setIcon( embed::getIconPixmap( "ignore" ) );

			mb.setDefaultButton( recover );
			mb.setEscapeButton( exit );

			mb.exec();
			if( mb.clickedButton() == discard )
			{
				gui->mainWindow()->sessionCleanup();
			}
			else if( mb.clickedButton() == recover ) // Recover
			{
				fileToLoad = recoveryFile;
				gui->mainWindow()->setSession( MainWindow::SessionState::Recover );
			}
			else if( mb.clickedButton() == ignore )
			{
				if( autoSaveEnabled )
				{
					gui->mainWindow()->setSession( MainWindow::SessionState::Limited );
				}
			}
			else // Exit
			{
				return 0;
			}
		}

		// first show the Main Window and then try to load given file

		// [Settel] workaround: showMaximized() doesn't work with
		// FVWM2 unless the window is already visible -> show() first
		gui->mainWindow()->show();
		if( fullscreen )
		{
			gui->mainWindow()->showMaximized();
		}

		if( !fileToLoad.isEmpty() )
		{
			if( fileToLoad == recoveryFile )
			{
				Engine::getSong()->createNewProjectFromTemplate( fileToLoad );
			}
			else
			{
				Engine::getSong()->loadProject( fileToLoad );
			}
		}
		else if( !fileToImport.isEmpty() )
		{
			ImportFilter::import( fileToImport, Engine::getSong() );
			if( exitAfterImport )
			{
				return EXIT_SUCCESS;
			}
		}
		// If enabled, open last project if there is one. Else, create
		// a new one. Also skip recently opened file if limited session to
		// lower the chance of opening an already opened file.
		else if( ConfigManager::inst()->
				value( "app", "openlastproject" ).toInt() &&
			!ConfigManager::inst()->
				recentlyOpenedProjects().isEmpty() &&
			gui->mainWindow()->getSession() !=
				MainWindow::SessionState::Limited )
		{
			QString f = ConfigManager::inst()->
					recentlyOpenedProjects().first();
			QFileInfo recentFile( f );

			if ( recentFile.exists() )
			{
				Engine::getSong()->loadProject( f );
			}
			else
			{
				Engine::getSong()->createNewProject();
			}
		}
		else
		{
			Engine::getSong()->createNewProject();
		}

		// Finally we start the auto save timer and also trigger the
		// autosave one time as recover.mmp is a signal to possible other
		// instances of LMMS.
		if( autoSaveEnabled &&
			gui->mainWindow()->getSession() != MainWindow::SessionState::Limited )
		{
			gui->mainWindow()->autoSaveTimerReset();
			gui->mainWindow()->autoSave();
		}
	}

	const int ret = app->exec();
	delete app;

	if( destroyEngine )
	{
		Engine::destroy();
	}

	// cleanup memory managers
	MemoryManager::cleanup();

	// ProjectRenderer::updateConsoleProgress() doesn't return line after render
	if( coreOnly )
	{
		printf( "\n" );
	}

	return ret;
}
Пример #21
0
void IconManager::readIconConfigFiles()
{
	QString baseIconDir(ScPaths::instance().iconDir());
	QStringList locations;
	locations<<baseIconDir;
	QStringList configNames;
	for ( QStringList::Iterator it = locations.begin(); it != locations.end(); ++it )
	{
		QFileInfo iconDir(*it);
		if (!iconDir.exists())
			continue;
		QDir id(*it, "*.xml", QDir::Name, QDir::Dirs | QDir::NoDotAndDotDot | QDir::Files | QDir::NoSymLinks);
		if (!id.exists() || (id.count() == 0))
			continue;
		for (uint i = 0; i < id.count(); ++i)
		{
			QFileInfo file(*it + id[i]);
			//qDebug()<<file.absoluteFilePath();
			QFile dataFile(file.absoluteFilePath());
			if (!dataFile.exists())
				continue;
			dataFile.open(QIODevice::ReadOnly);
			QTextStream ts(&dataFile);
			ts.setCodec(QTextCodec::codecForName("UTF-8"));
			QString errorMsg;
			int eline;
			int ecol;
			QDomDocument xmlData( QString(file.baseName()));
			QString data(ts.readAll());
			dataFile.close();
			if ( !xmlData.setContent( data, &errorMsg, &eline, &ecol ))
			{
				qDebug()<<data<<errorMsg<<eline<<ecol;
				if (data.toLower().contains("404 not found"))
					qDebug()<<"File not found on server";
				else
					qDebug()<<"Could not open file"<<dataFile.fileName();
				continue;
			}
			QDomElement docElem = xmlData.documentElement();
			QDomNode n = docElem.firstChild();
			ScIconSetData isd;
			while( !n.isNull() )
			{
				QDomElement e = n.toElement();
				if( !e.isNull() )
				{
					//qDebug()<<e.tagName()<<e.text();
					if (e.tagName()=="path")
					{
						isd.path=e.text();
					}
					else
					if (e.tagName()=="author")
					{
						isd.author=e.text();
					}
					else
					if (e.tagName()=="license")
					{
						isd.license=e.text();
					}
					else
					if (e.tagName()=="activeversion")
					{
						isd.activeversion=e.text();
					}
					else
					if (e.tagName()=="nametext")
					{
						if (e.hasAttribute("lang"))
						{
							isd.nameTranslations.insert(e.attribute("lang"),e.text());
							if (e.attribute("lang")=="en_US")
								isd.baseName=e.text();
						}
					}
				}
				n = n.nextSibling();
			}
			//just in case there's no en_US basename
			if (!isd.baseName.isEmpty())
			{

				m_iconSets.insert(isd.baseName, isd);
				if(!isd.activeversion.isEmpty())
				{
					int av_major, av_minor, av_patch, curr_major, curr_minor, curr_patch, ver_major, ver_minor, ver_patch;
					av_major=isd.activeversion.section(".",0,0).toInt();
					av_minor=isd.activeversion.section(".",1,1).toInt();
					av_patch=isd.activeversion.section(".",2,2).toInt();
					curr_major=m_activeSetVersion.section(".",0,0).toInt();
					curr_minor=m_activeSetVersion.section(".",1,1).toInt();
					curr_patch=m_activeSetVersion.section(".",2,2).toInt();
					ver_major=QString(VERSION).section(".",0,0).toInt();
					ver_minor=QString(VERSION).section(".",1,1).toInt();
					ver_patch=QString(VERSION).section(".",2,2).toInt();
					//If iconset version <= app version, and iconset version >= current active iconset version
					if (av_major<=ver_major &&
						av_minor<=ver_minor &&
						av_patch<=ver_patch &&
						(
						av_major>=curr_major ||
						(av_major==curr_major && av_minor>=curr_minor) ||
						(av_major==curr_major && av_minor==curr_minor && av_patch>=curr_patch)
						)
						)
					{
						m_backupSetBasename=m_activeSetBasename;
						m_backupSetVersion=m_backupSetVersion;
						m_activeSetBasename=isd.baseName;
						m_activeSetVersion=isd.activeversion;
						//qDebug()<<"backupSetBasename"<<m_backupSetBasename<<"activeSetBasename"<<m_activeSetBasename;
					}
				}
			}
		}
	}
}
Пример #22
0
void ResourceManager::updateAvailableFonts()
{
	QFile dataFile(ScPaths::downloadDir() + dataFiles[RM_FONTS]);
	if (!dataFile.exists())
		return;
	dataFile.open(QIODevice::ReadOnly);
	QTextStream ts(&dataFile);
	ts.setCodec(QTextCodec::codecForName("UTF-8"));
	QString errorMsg;
	int eline;
	int ecol;
	QDomDocument doc( dataFiles[RM_FONTS] );
	QString data(ts.readAll());
	dataFile.close();
	if ( !doc.setContent( data, &errorMsg, &eline, &ecol ))
	{
//		qDebug()<<errorMsg<<eline<<ecol;
		if (data.toLower().contains("404 not found"))
			qDebug()<<"File not found on server";
		else
			qDebug()<<"Could not open file"<<dataFile.fileName();
		return;
	}
	fontList.clear();
	QDomElement docElem = doc.documentElement();
	QDomNode n = docElem.firstChild();
	while( !n.isNull() )
	{
		QDomElement e = n.toElement();
		if( !e.isNull() )
		{
			if (e.tagName()=="font")
			{
				if (e.hasAttribute("type") && e.hasAttribute("filetype"))
				{
					struct DownloadItem d;
					d.desc=e.attribute("description");
					d.download=false;
					d.files=e.attribute("files");
					d.extractfiles=e.attribute("extractfiles");
					d.url=e.attribute("URL");
					d.version=e.attribute("version");
					d.lang=e.attribute("language");
					d.license=e.attribute("license");
					d.filetype=e.attribute("filetype");
					d.movetofile=e.attribute("movetofilename");
					d.type=e.attribute("type").toUpper();
					QUrl url(d.url);
					if (url.isValid() && !url.isEmpty() && !url.host().isEmpty())
						fontList.append(d);
//					else
//						qDebug()<<"rm : availFonts : invalid URL"<<d.url;
				}
			}
		}
		n = n.nextSibling();
	}
	availableTableWidget->clear();
	if(fontList.isEmpty())
	{
		downloadButton->setEnabled(false);
		return;
	}
	availableTableWidget->setRowCount(fontList.count());
	availableTableWidget->setColumnCount(4);
	availableTableWidget->setSortingEnabled(false);
	int row=0;
	foreach(DownloadItem d, fontList)
	{
		int column=0;
//		qDebug()<<d.version<<d.files<<d.url<<d.desc<<d.license;
		QTableWidgetItem *newItem1 = new QTableWidgetItem(d.desc);
		newItem1->setFlags(newItem1->flags() & ~Qt::ItemIsEditable & ~Qt::ItemIsSelectable);
		availableTableWidget->setItem(row, column++, newItem1);
		QTableWidgetItem *newItem2 = new QTableWidgetItem(d.type);
		newItem2->setFlags(newItem1->flags());
		availableTableWidget->setItem(row, column++, newItem2);
		QTableWidgetItem *newItem3 = new QTableWidgetItem();
		newItem3->setCheckState(dictionaryMap.contains(d.lang) ? Qt::Checked : Qt::Unchecked);
		newItem3->setFlags(newItem1->flags() & ~Qt::ItemIsUserCheckable);
		availableTableWidget->setItem(row, column++, newItem3);
		QTableWidgetItem *newItem4 = new QTableWidgetItem();
		newItem4->setFlags(newItem1->flags());
		newItem4->setCheckState(d.download ? Qt::Checked : Qt::Unchecked);
		availableTableWidget->setItem(row, column++, newItem4);
		++row;
	}
Пример #23
0
void dataLogFString(const char* str)
{
    dataFile().printf("%s", str);
}
Пример #24
0
void mergeEff(int iCat_ = 0) {
  TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
  dir.ReplaceAll("mergeEff.C","");
  dir.ReplaceAll("/./","/");
  ifstream in;
  const int nBin = 4; // pT(4), y(3)
  double eff[100][100] = {0.0};
  for(int idir = 1; idir < 101; idir++){
    if(iCat_ == 0) in.open(Form("%s../Eff_00%d/ppPromp_eff_Pts_pT_6.5_30.0_y_0.0_2.4_HighQ.tex",dir.Data(),idir));
    if(iCat_ == 1) in.open(Form("%s../Eff_00%d/ppPromp_eff_Raps_pT_6.5_30.0_y_0.0_2.4_HighQ.tex",dir.Data(),idir));
    Float_t x[300];
    Int_t nlines = 0;
    int nl = 0;
    while (1) {
      in >> x[0] ;
      eff[nl][idir-1] = x[0]; 
      //cout<<"eff : "<<eff[nl][idir-1]<<endl;
      if (!in.good()) break;
      nlines++;
      nl++;
    }
    in.close();
  }

  TH1F *hDis[13]; 

  string eff_tot[100];
  for(int in = 0; in < nBin; in++){
    //hDis[in] = new TH1F(Form("hDis_%d",in),"",20,0.35,0.65); // cent
    hDis[in] = new TH1F(Form("hDis_%d",in),"",180,0.25,0.85); // pT
    hDis[in]->Sumw2();
    hDis[in]->SetMarkerStyle(20);
    hDis[in]->SetMarkerSize(1.2);
    puts("");
    for(int id = 0; id < 100; id++){
      printf("%0.4f ", eff[in][id]);
      hDis[in]->Fill(eff[in][id]);
    }
  }
  puts(""); 

  TLatex *lt = new TLatex();
  lt->SetNDC();
  const int nPtBins = 4;
  const int nRapBins = 3; // 6
  double pt_bound[nPtBins+1] = {6.5, 8.0, 10.0, 13.0, 30.0};
  double rap_bound[nRapBins+1] = {0.0, 1.2, 1.6, 2.4};
  char OutTextFile[100];
  if(iCat_==0) sprintf(OutTextFile,"pp_prompt_old_pt.tex");
  if(iCat_==1) sprintf(OutTextFile,"pp_prompt_old_rap.tex");
  ofstream dataFile(OutTextFile);
  TCanvas *c1 = new TCanvas("c1","",1200,300);
  c1->Divide(4,1);
  for(int ic = 1; ic < nBin+1; ic++){
    c1->cd(ic);
    hDis[ic-1]->GetXaxis()->SetTitle("Efficiency");
    hDis[ic-1]->Draw("E");
    //cout<<"Mean : "<<hDis[ic-1]->GetMean()<<endl;
    //cout<<"RMS : "<<hDis[ic-1]->GetRMS()<<endl;
    cout<<hDis[ic-1]->GetMean()<<" "<<hDis[ic-1]->GetRMS()<<endl;
    if(iCat_==0) dataFile<<"pT : "<<pt_bound[ic-1]<<"-"<<pt_bound[ic]<<endl;
    if(iCat_==1) dataFile<<"rap : "<<rap_bound[ic-1]<<"-"<<rap_bound[ic]<<endl;
    dataFile<<hDis[ic-1]->GetMean()<<" "<<hDis[ic-1]->GetRMS()<<endl;
    if(iCat_==0) lt->DrawLatex(0.2,0.95,Form("pp, p_{T} [%0.1f,%0.1f], y [0.0,2.4]",pt_bound[ic-1],pt_bound[ic]));
    if(iCat_==1) lt->DrawLatex(0.2,0.95,Form("pp, p_{T} [6.5,30.0], y [%0.1f,%0.1f]",pt_bound[ic-1],pt_bound[ic]));
  }

  if(iCat_ == 0) {c1->SaveAs("plot_pp_eff_dis_pt.png");c1->SaveAs("plot_pp_eff_dis_pt.pdf");}
  if(iCat_ == 1) {c1->SaveAs("plot_pp_eff_dis_rap.png");c1->SaveAs("plot_pp_eff_dis_rap.pdf");}

  return;
}
Пример #25
0
int main(int argc, char *argv[])
{
	nn * theNet = NULL;
	string argvI;
	string strArg;
	string strSave;
	int in, out, hidden;
//	float fVal;
	bool unknownFlag = false;
	bool quiet = false;


	int i;

	string nnName = "TestNet";
	cout.precision(12);

	for (i=1; i<argc; i++)
	{
		argvI = argv[i];
		if (argvI == "-n")
		{
				if (theNet != NULL)
				{
					cout << "A network was already loaded and has been deleted.\n";
					delete theNet;
				}

				try
				{
					networkFile netFile(argv[++i]);
					theNet = new nn(&netFile);

					if (!quiet)
						cout << "Done with -n\n";

				}
				catch (format_Error & e)
				{
					cout << e.mesg << "\n";
				}
		}
		else

			if (argvI == "-t")
			{
				if (theNet == NULL)
					cout << "A network must be loaded before it is trained.\n";
				else
					try
					{
						trainingFile trFile(argv[++i]);
						theNet->train(&trFile, &callback_TrainingComplete);

						if (!quiet)
							cout << "Done with -t\n";

					}
					catch (format_Error & e)
					{
						cout << e.mesg << "\n";
					}
			}
			else

				if ((argvI == "-r") || (argvI == "-run"))
				{
					if (theNet == NULL)
						cout << "A network must be loaded before it is run.\n";
					else
						try
						{
							inputFile dataFile(argv[++i]);
							theNet->run(&dataFile, &callback_RunComplete);

							if (!quiet)
								cout << "Done with -r or -run\n";

						}
						catch (format_Error & e)
						{
							cout << e.mesg << "\n";
						}
				}
				else
					if (argvI == "-s")
					{
						if (theNet == NULL)
							cout << "A network must be loaded before it is saved.\n";
						else
							try
							{
								theNet->saveTo(argv[++i]);

								if (!quiet)
									cout << "Done with -s\n";

							}
							catch (format_Error & e)
							{
								cout << e.mesg << "\n";
							}
					}
					else
						if (argvI == "-c")
						{
							if (theNet != NULL)
							{
								cout << "A network was already loaded and has been deleted.\n";
								delete theNet;
							}
							try
							{
							    unsigned int layer, layerCount;
								layerCount = atoi(argv[++i]);

							    vector<unsigned int> layers(layerCount);
								for (layer=0; layer<layerCount; layer++)
                                    layers[layer] = atoi(argv[++i]);
								strArg = argv[++i];
								theNet = new nn(&layers, strArg);

								if (!quiet)
									cout << "Done with -c\n";

							}
							catch (format_Error & e)
							{
								cout << e.mesg << "\n";
							}
						}
						else
							if (argvI == "-rand")
							{
								if (theNet == NULL)
									cout << "A network must be loaded before it is randomised.\n";
								else
									try
									{
										theNet->randomise();

										if (!quiet)
											cout << "Done with -rand\n";

									}
									catch (format_Error & e)
									{
										cout << e.mesg << "\n";
									}

							}
							else
								if (argvI == "-at")
								{
									if (theNet == NULL)
										cout << "A network must be loaded before it is altered.\n";
									else
										try
										{
											in = atoi(argv[++i]);
											hidden = atoi(argv[++i]);
											out = atoi(argv[++i]);
											theNet->alter(in, hidden, out);

											if (!quiet)
												cout << "Done with -at\n";

										}
										catch (format_Error & e)
										{
											cout << e.mesg << "\n";
										}

								}
								else
									if (argvI == "-am")
									{
										if (theNet == NULL)
											cout << "A network must be loaded before it is altered.\n";
										else
											try
											{
												unsigned int layerNo;
												size_t colonPos;
												string modifier;
												string key;
												string value;


												layerNo = atoi(argv[++i]);
												modifier = argv[++i];
												colonPos = modifier.find(":");

												if (layerNo == 0)
												{
													key = modifier.substr(0, colonPos);
													if (key == "biasNode")
													{
														value = modifier.substr(colonPos + 1);
														if (value == "true")
															theNet->alter(layerNo, BIAS_NODE, true);
														else
															if (modifier.substr(colonPos + 1, modifier.size() - colonPos) == "false")
																theNet->alter(layerNo, BIAS_NODE, false);
															else
																cout << "Invalid argument for modifier biasNode: " << value << "\n";
													}
													else
														cout << "Modifer:" << key << " not valid\n";
												}
												else
													cout << "Invalid layer number:" << layerNo << "\n";


												if (!quiet)
													cout << "Done with -am\n";

											}
											catch (format_Error & e)
											{
												cout << e.mesg << "\n";
											}

									}
									else
										if (argvI == "-test")
										{
											if (theNet == NULL)
												cout << "A network must be loaded before it is tested.\n";
											else
												try
												{
													trainingFile testFile(argv[++i]);
													theNet->test(&testFile, callback_TestComplete);

													if (!quiet)
														cout << "Done with -test\n";

												}
												catch (format_Error & e)
												{
													cout << e.mesg << "\n";
												}

										}
										else
											if (argvI == "-q+")
												quiet = true;
											else
												if (argvI == "-q-")
												{
													quiet = false;
													cout << "Done with -q-\n";
												}
												else
												{
													unknownFlag = true;
													cout << "Don't know that one:" << argvI << "\n";
												}

	}

	if (unknownFlag)
	{
		cout << "\n-n %file load a network from %file\n";
		cout << "-t %file training set %file and write the final error vector to standard output\n";
		cout << "(-r | -run) %file run from input set in %file and write each result vector to standard output\n";//and save the results in outPath\n";
		cout << "-rand randomise the network\n";
		cout << "-test %file run the input/output pattern from training file %file and write the final difference vector to standard output\n";
		cout << "-s %path save on %path (with no trailing /) Use . to write to the working directory.\n";
		cout << "-c %i %h %o %n create a new randomised network with %i input nodes %h hidden nodes %o output nodes, called %n (with a learning rate of 0.1)\n";
		cout << "-at %i %h %o alter the topology to be %i input nodes %h hidden nodes %o output nodes\n";
		cout << "-am 1 (biasNode:true OR biasNode:false) add or remove an input bias node to layer one (default is false)\n";
		cout << "-q+ OR -q- Switch quiet mode on (-q+) or off (-q-) +q+ supresses the 'Done with...' after each command line arguement\n";
	}
	if (theNet != NULL)
		delete theNet;

	return 1;
}
Пример #26
0
int main()
{
  std::string line;
  std::ifstream dataFile("heathrow.dat");


  HeathrowRowData heathrowData[MAX_ROWS];
  unsigned int rowsRead = 0;

  if(dataFile.is_open())
  {
    for(unsigned int i = 0; i < MAX_ROWS && dataFile.good(); ++i)
    {
      std::getline(dataFile, line);
      if(!line.empty())
      {
        heathrowData[i].fillFromLine(line);
        ++rowsRead;
      }
    }
    dataFile.close();
  }


  // Initialise to 0
  float totalRainfall[12] = {0.0};
  unsigned int totalMonthsOfData[12] = {0};

  float minTemp = heathrowData[0].getTMin();
  float maxTemp = heathrowData[0].getTMax();
  unsigned int frostiestAugustIndex = INVALID_INT;
  
  for(unsigned int i = 0; i < rowsRead; ++i)
  {
    // Have to subtract 1 in square brackets because months go 1..12
    if(heathrowData[i].getRain() != INVALID_FLOAT)
    {
      const unsigned int monthIndex = heathrowData[i].getMonth() - 1;
      totalRainfall[monthIndex] += heathrowData[i].getRain();
      ++totalMonthsOfData[monthIndex];
    }

    if(heathrowData[i].getTMin() != INVALID_INT)
      minTemp = std::min(minTemp, heathrowData[i].getTMin());

    if(heathrowData[i].getTMax() != INVALID_INT)
      maxTemp = std::max(maxTemp, heathrowData[i].getTMax());
    
    if(heathrowData[i].getMonth() == MONTH_AUGUST)
    {
      if(frostiestAugustIndex == INVALID_INT)
        frostiestAugustIndex = i;
      else if(heathrowData[i].getTMin() < heathrowData[frostiestAugustIndex].getTMin())
        frostiestAugustIndex = i;
    }
  }

  // Go through the months calculating the averages
  unsigned int raniestMonth = 0;
  for(unsigned int i = 0; i < 12; ++i)
  {
    totalRainfall[i] /= static_cast<float>(totalMonthsOfData[i]);
    if(totalRainfall[i] > totalRainfall[raniestMonth])
      raniestMonth = i;
  }
  // Need to add 1 to raniest month to get back to 1..12 range
  std::cout << "Raniest month: " << raniestMonth + 1  << "\n";

  std::cout << "Temperatures - min: " << minTemp << ", max: " << maxTemp <<
    ", mean: " << 0.5 * (maxTemp - minTemp) + minTemp  << "\n";

  std::cout << "Frostiest August: ";
  heathrowData[frostiestAugustIndex].printDate();
  std::cout << " temperature: " << heathrowData[frostiestAugustIndex].getTMin() << "\n";


  return 0;
}
Visualization::Abstract::DataSet* CitcomtVectorFile::load(const std::vector<std::string>& args,Comm::MulticastPipe* pipe) const
	{
	/* Open the data file: */
	Misc::File dataFile(args[0].c_str(),"rt");
	
	/* Check if the user wants to load a specific variable: */
	bool logScale=false;
	const char* varStart=0;
	const char* varEnd=0;
	int varLen=0;
	if(args.size()>2&&args[2][0]!='-')
		{
		/* Parse the search variable name: */
		varStart=args[2].c_str();
		if(strncasecmp(varStart,"log(",4)==0)
			{
			/* Use a logarithmic scale: */
			logScale=true;
			
			/* Take the string in parentheses as search variable name: */
			varStart+=4;
			for(varEnd=varStart;*varEnd!='\0'&&*varEnd!=')';++varEnd)
				;
			}
		else
			{
			/* Take the entire string as search variable name: */
			for(varEnd=varStart;*varEnd!='\0';++varEnd)
				;
			}
		varLen=varEnd-varStart;
		}
	
	/*********************************************************
	Parse any useful information from the CITCOMT file header:
	*********************************************************/
	
	/* Size of data set in C memory / file order: Z varies fastest, then X, then Y: */
	DS::Index numNodes(-1,-1,-1);
	
	/* Ordering of coordinate columns in the file: */
	int coordColumn[3]={-1,-1,-1};
	
	/* Index of data columns: */
	int dataColumn[1]={-1};
	char* dataNames[1]={0};
	
	/* Mapping from coordinate columns to spherical coordinates (lat, long, rad): */
	int sphericalOrder[3]={-1,-1,-1};
	
	/* Read the first line: */
	char line[256];
	dataFile.gets(line,sizeof(line));
	
	/* Parse the entire header: */
	while(line[0]=='#')
		{
		/* Skip hash marks and whitespace: */
		char* cPtr=line;
		while(*cPtr!='\0'&&(*cPtr=='#'||isspace(*cPtr)))
			++cPtr;
		
		/* Check which header line this is: */
		if(strncasecmp(cPtr,"NODES",5)==0)
			{
			/* Parse the number of nodes: */
			do
				{
				/* Check which dimension this is and parse the number of nodes: */
				if(toupper(cPtr[5])=='Y') // Y column varies most slowly
					numNodes[0]=atoi(cPtr+7);
				else if(toupper(cPtr[5])=='X')
					numNodes[1]=atoi(cPtr+7);
				if(toupper(cPtr[5])=='Z') // Z column varies fastest
					numNodes[2]=atoi(cPtr+7);
				
				/* Go to the next field: */
				while(*cPtr!='\0'&&!isspace(*cPtr))
					++cPtr;
				while(*cPtr!='\0'&&isspace(*cPtr))
					++cPtr;
				}
			while(strncasecmp(cPtr,"NODES",5)==0);
			}
		else if((toupper(cPtr[0])=='X'||toupper(cPtr[0])=='Y'||toupper(cPtr[0])=='Z')&&cPtr[1]=='-')
			{
			/* Parse spherical coordinate assignments: */
			do
				{
				/* Remember which coordinate this is: */
				int coordIndex=int(toupper(cPtr[0]))-int('X');
				
				/* Find the end of the spherical component string: */
				char* endPtr;
				for(endPtr=cPtr;*endPtr!='\0'&&*endPtr!=','&&!isspace(*endPtr);++endPtr)
					;
				
				/* Check which component is assigned: */
				if(endPtr-cPtr==5&&strncasecmp(cPtr+2,"LAT",3)==0)
					sphericalOrder[0]=coordIndex;
				else if(endPtr-cPtr==5&&strncasecmp(cPtr+2,"LON",3)==0)
					sphericalOrder[1]=coordIndex;
				if(endPtr-cPtr==8&&strncasecmp(cPtr+2,"RADIUS",3)==0)
					sphericalOrder[2]=coordIndex;
				
				/* Go to the next field: */
				cPtr=endPtr;
				if(*cPtr==',')
					++cPtr;
				while(*cPtr!='\0'&&isspace(*cPtr))
					++cPtr;
				}
			while((toupper(cPtr[0])=='X'||toupper(cPtr[0])=='Y'||toupper(cPtr[0])=='Z')&&cPtr[1]=='-');
			}
		else if(*cPtr=='|')
			{
			/* Parse column assignments: */
			int columnIndex=0;
			do
				{
				/* Skip separator and whitespace: */
				while(*cPtr!='\0'&&(*cPtr=='|'||isspace(*cPtr)))
					++cPtr;
				
				/* Find the end of the column string: */
				char* endPtr;
				for(endPtr=cPtr;*endPtr!='\0'&&!isspace(*endPtr);++endPtr)
					;
				
				/* Check which column this is: */
				if(endPtr-cPtr==1&&strncasecmp(cPtr,"X",1)==0)
					coordColumn[0]=columnIndex;
				else if(endPtr-cPtr==1&&strncasecmp(cPtr,"Y",1)==0)
					coordColumn[1]=columnIndex;
				else if(endPtr-cPtr==1&&strncasecmp(cPtr,"Z",1)==0)
					coordColumn[2]=columnIndex;
				else if(endPtr-cPtr==4&&strncasecmp(cPtr,"NODE",1)==0)
					{
					/* Ignore this column */
					}
				else if(dataColumn[0]<0)
					{
					if(varStart==0||(endPtr-cPtr==varLen&&strncasecmp(varStart,cPtr,varLen)==0))
						{
						/* Treat this column as the data column: */
						dataColumn[0]=columnIndex;

						/* Remember the name of the data value: */
						if(logScale)
							{
							dataNames[0]=new char[varLen+6];
							memcpy(dataNames[0],"Log(",4);
							memcpy(dataNames[0]+4,cPtr,varLen);
							dataNames[0][4+varLen]=')';
							dataNames[0][4+varLen+1]='\0';
							}
						else
							{
							dataNames[0]=new char[varLen+1];
							memcpy(dataNames[0],cPtr,varLen);
							dataNames[0][varLen]='\0';
							}
						}
					}
				
				/* Go to the next column: */
				cPtr=endPtr;
				while(*cPtr!='\0'&&isspace(*cPtr))
					++cPtr;
				++columnIndex;
				}
			while(*cPtr=='|');
			}
		
		/* Go to the next line: */
		dataFile.gets(line,sizeof(line));
		}
	
	/* Check if all required header information has been read: */
	bool headerValid=true;
	for(int i=0;i<3;++i)
		if(numNodes[i]<0)
			headerValid=false;
	for(int i=0;i<3;++i)
		if(coordColumn[i]<0)
			headerValid=false;
	for(int i=0;i<1;++i)
		if(dataColumn[i]<0)
			{
			if(varStart!=0)
				Misc::throwStdErr("CitcomtFile::load: Data variable %s not found in CITCOMT header in input file %s",args[2].c_str(),args[0].c_str());
			headerValid=false;
			}
	if(!headerValid)
		Misc::throwStdErr("CitcomtFile::load: Invalid CITCOMT header in input file %s",args[0].c_str());
	
	/* Create result data set: */
	EarthDataSet<DataSet>* result=new EarthDataSet<DataSet>(args);
	result->getDs().setData(numNodes);
	result->setFlatteningFactor(0.0); // Spherical geoid model to simplify vector transformation
	
	/* Set the data value's name: */
	result->getDataValue().setScalarVariableName(dataNames[0]);
	result->getDataValue().setVectorVariableName("Velocity");
	
	/* Check if the file is stored in spherical coordinates: */
	bool sphericalCoordinates=true;
	for(int i=0;i<3;++i)
		if(sphericalOrder[i]<0)
			sphericalCoordinates=false;
	
	/* Constant parameters for geoid formula: */
	const double a=6378.14e3; // Equatorial radius in m
	// const double f=1.0/298.247; // Geoid flattening factor
	const double scaleFactor=1.0e-3; // Scale factor for Cartesian coordinates
	
	/* Determine the number of significant columns: */
	int numColumns=0;
	for(int i=0;i<3;++i)
		if(numColumns<coordColumn[i])
			numColumns=coordColumn[i];
	for(int i=0;i<1;++i)
		if(numColumns<dataColumn[i])
			numColumns=dataColumn[i];
	++numColumns;
	
	/* Compute a mapping from column indices to coordinate components/data value: */
	int* columnMapping=new int[numColumns];
	for(int i=0;i<numColumns;++i)
		columnMapping[i]=-1;
	for(int i=0;i<3;++i)
		columnMapping[coordColumn[i]]=i;
	for(int i=0;i<1;++i)
		columnMapping[dataColumn[i]]=3+i;
	
	/* Read all vertex positions and values: */
	Misc::File vectorFile(args[1].c_str(),"rt");
	std::cout<<"Reading grid vertex positions and values...   0%"<<std::flush;
	DS::Array& vertices=result->getDs().getVertices();
	DS::Index index;
	for(index[0]=0;index[0]<vertices.getSize(0);++index[0])
		{
		for(index[1]=0;index[1]<vertices.getSize(1);++index[1])
			for(index[2]=0;index[2]<vertices.getSize(2);++index[2])
				{
				/* Parse the coordinate components and the data value from the line: */
				double columns[4];
				char* cPtr=line;
				for(int i=0;i<numColumns;++i)
					{
					/* Read the column value: */
					double val=strtod(cPtr,&cPtr);
					if(columnMapping[i]>=0)
						columns[columnMapping[i]]=val;
					}
				
				/* Read the next line from the vector file and parse the vector components: */
				vectorFile.gets(line,sizeof(line));
				cPtr=line;
				double vector[3];
				
				/* Order in the file is longitude, radius, latitude: */
				vector[1]=strtod(cPtr,&cPtr);
				vector[2]=strtod(cPtr,&cPtr);
				vector[0]=strtod(cPtr,&cPtr);
				
				DS::GridVertex& v=vertices(index);
				if(sphericalCoordinates)
					{
					/* Convert from spherical to Cartesian coordinates: */
					double latitude=columns[sphericalOrder[0]];
					double longitude=columns[sphericalOrder[1]];
					double radius=columns[sphericalOrder[2]];
					double s0=Math::sin(latitude);
					double c0=Math::cos(latitude);
					double s1=Math::sin(longitude);
					double c1=Math::cos(longitude);
					#if 1
					double r=a*radius*scaleFactor; // Use spherical globe model to simplify vector conversion
					#else
					double r=(a*(1.0-f*Math::sqr(s0))*radius)*scaleFactor;
					#endif
					double xy=r*c0;
					v.pos[0]=float(xy*c1);
					v.pos[1]=float(xy*s1);
					v.pos[2]=float(r*s0);
					
					/* Store the scalar value: */
					if(logScale)
						v.value.scalar=float(Math::log10(columns[3]));
					else
						v.value.scalar=float(columns[3]);
					
					/* Convert the vector value from spherical to Cartesian coordinates: */
					v.value.vector[0]=float(c1*(c0*vector[2]-s0*vector[0])-s1*vector[1]);
					v.value.vector[1]=float(s1*(c0*vector[2]-s0*vector[0])+c1*vector[1]);
					v.value.vector[2]=float(c0*vector[0]+s0*vector[2]);
					}
				else
					{
					/* Store the vertex position and value: */
					for(int i=0;i<3;++i)
						v.pos[i]=float(columns[i]);
					if(logScale)
						v.value.scalar=float(Math::log10(columns[3]));
					else
						v.value.scalar=float(columns[3]);
					for(int i=0;i<3;++i)
						v.value.vector[i]=float(vector[i]);
					}
				
				/* Read the next line from the file: */
				dataFile.gets(line,sizeof(line));
				}
		
		std::cout<<"\b\b\b\b"<<std::setw(3)<<((index[0]+1)*100)/vertices.getSize(0)<<"%"<<std::flush;
		}
	std::cout<<"\b\b\b\bdone"<<std::endl;
	
	/* Clean up: */
	delete[] columnMapping;
	
	/* Finalize the grid structure: */
	result->getDs().finalizeGrid();
	
	#if 0
	{
	/* Save the grid to a pair of binary files: */
	Misc::LargeFile gridFile("GridFile.grid","wb",Misc::LargeFile::LittleEndian);
	Misc::LargeFile dataFile("GridFile.dat","wb",Misc::LargeFile::LittleEndian);
	
	/* Write the grid file headers: */
	gridFile.write<int>(result->getDs().getNumVertices().getComponents(),3);
	dataFile.write<int>(result->getDs().getNumVertices().getComponents(),3);
	dataFile.write<int>(2);
	dataFile.write<int>(1);
	dataFile.write<int>(strlen(dataNames[0]));
	dataFile.write<char>(dataNames[0],strlen(dataNames[0]));
	dataFile.write<int>(3);
	dataFile.write<int>(strlen("Velocity"));
	dataFile.write<char>("Velocity",strlen("Velocity"));
	
	/* Write the vertex positions: */
	for(DS::Array::iterator vIt=vertices.begin();vIt!=vertices.end();++vIt)
		{
		gridFile.write<float>(vIt->pos.getComponents(),3);
		dataFile.write<Value>(vIt->value);
		}
	}
	#endif
	
	/* Clean up and return result: */
	delete[] dataNames[0];
	return result;
	}
Пример #28
0
void PendulumTest::startTest()
{
	SimulationEngine engine;
	if (!engine.init())
	{
		return;
	}

	// Get a pointer to the trial number overlay and make it visible.
	Ogre::OverlayManager::getSingleton().getByName("Verve/TrialNumber")->show();

	engine.setUpdateMode(SimulationEngine::SIMULATE_REAL_TIME_MULTIPLE, 1);
	engine.setCameraMoveSpeed(5);

	//// Set to capture frames at 29.97 fps.
	//engine.setUpdateMode(SIMULATE_CONSTANT_CHUNK, 0.0333667);

	engine.getSimulator()->setStepSize(mPhysicsStepSize);
	engine.getSimulator()->setGravity(opal::Vec3r(0, -9.81, 0));

	// Make sure we get notified at the end of each step.
	engine.getSimulator()->addPostStepEventHandler(this);

	// Create a static box for a ground plane.
	opal::Solid* boxSolid = engine.getSimulator()->createSolid();
	boxSolid->setStatic(true);
	boxSolid->setPosition(0, -1.5, 0);
	opal::BoxShapeData data;
	data.dimensions.set(6, 3, 6);
	boxSolid->addShape(data);
	engine.createPhysicalEntity("ground", "Plastic/Gray", boxSolid);

	DataFile dataFile(mNumTrialsPerRun);
	opal::Matrix44r initialTransform;
	initialTransform.translate(0, 1.2, 0);
	assert(NULL == mPendulum);
	mPendulum = new Pendulum(engine, initialTransform);

	mAgentDebugger = new AgentVisualDebugger(engine.getSceneManager());

	for (unsigned int run = 0; run < mNumRuns; ++run)
	{
		mPendulum->resetBodyAndCreateNewAgent();
		mAgentDebugger->setAgent(mPendulum->getAgent());

		for (unsigned int trial = 0; trial < mNumTrialsPerRun; ++trial)
		{
			updateOverlayData(trial);
			mPendulum->resetBodyAndSTM();
			mPendulum->randomizeState();
			mAvgRewardPerStep = 0;
			mCurrentTrialTime = 0;

			while (mCurrentTrialTime < mTrialLength)
			{
				Ogre::Real elapsedSimTime = 0;
				Ogre::Real elapsedRealTime = 0;
				engine.update(elapsedSimTime, elapsedRealTime);
				handleInput(elapsedRealTime, engine);
				if (engine.quitApp())
				{
					return;
				}

				mAgentDebugger->updateVisuals();
			}

			mAvgRewardPerStep = mAvgRewardPerStep * mPhysicsStepSize / 
				mCurrentTrialTime;
			dataFile.storeData("trial", trial, (float)trial);
			dataFile.storeData("avg reward per step", trial, 
				mAvgRewardPerStep);
			printTrialAndRunStatus(run, trial, mAvgRewardPerStep);

			//// Print value function data.
			//if (0 == run && 
			//	(trial == 0 || trial == 4 || trial == 19 || trial == 99))
			//{
			//	char fileStr[1024];
			//	sprintf(fileStr, "./results/pendulum-trial%d-value.dat", trial);
			//	mPendulum->getAgent()->saveValueData(400, fileStr);
			//	sprintf(fileStr, "./results/pendulum-trial%d-RBF.dat", trial);
			//	mPendulum->getAgent()->saveStateRBFData(fileStr);
			//}
		}

		std::cout << "Agent age = " << mPendulum->getAgent()->getAgeString() 
			<< std::endl;
	}

	dataFile.printToFile("./results/pendulum-performance.dat");
}
Пример #29
0
void UpsilonMassFit_All(int iSpec = 3, int PutWeight=1)
{
  //See pT Cut
  double PtCut= 4.0;
  
  //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 = 8;
    
   
    //for plots
    pt_bound[0] = 0.0;
    pt_bound[1] = 2.0;
    pt_bound[2] = 4.0;
    pt_bound[3] = 6.0;
    pt_bound[4] = 8.0;
    pt_bound[5] = 10.0;
    pt_bound[6] = 14.0;
    pt_bound[7] = 20.0;
     pt_bound[8] = 30.0;


    //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;
    
    
   
  }
  
  if(iSpec == 2) { 
    Nptbin = 8;
    
    pt_bound[0] = -2.4; 
    pt_bound[1] = -1.6; 
    pt_bound[2] = -1.2; 
    pt_bound[3] = -0.8; 
    pt_bound[4] = 0.0; 
    pt_bound[5] = 0.8;
    pt_bound[6] = 1.2; 
    pt_bound[7] = 1.6; 
    pt_bound[8] = 2.4; 


    //pt_bound[0] = 0.0; 
    //pt_bound[1] = 1.2; 
    //pt_bound[2] = 2.4; 
    
   
    
  }
  
  
  if(iSpec == 3) {
    Nptbin = 8;
   
    // pt_bound[0] = 0.0;//0
    //pt_bound[1] = 8.0;//20
    //pt_bound[2] = 24.0;//60
    //pt_bound[3] = 40.0;//100



    //for plots
    pt_bound[0] = 0.0;//0
    pt_bound[1] = 4.0;//10
    pt_bound[2] = 8.0;//20
    pt_bound[3] = 12.0;//25
    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;
    
  }
  //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");
  
  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,JpsiRap, JpsiCharge;
    Double_t JpsiVprob;
    //2.) muon variables RECO                                                                       
    double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt,muPosP;
    double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt,muNegP;
    //(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;
    
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt;

    //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("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("muNegPx", &muNegPx);
    tree->SetBranchAddress("muNegPy",    &muNegPy);
    tree->SetBranchAddress("muNegPz",    &muNegPz);
    tree->SetBranchAddress("muNegEta",    &muNegEta);
    //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("GenmuNegPx",    &GenmuNegPx);
    gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
    gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
    gentree->SetBranchAddress("GenmuNegEta",    &GenmuNegEta);
    

    //====================================================== 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); 
            
      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);}
	
	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);}
	//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);}
	

	//for non symetric plots
	if(iSpec == 2)  if((GenPosPass==1 && GenNegPass==1) &&  (GenJpsiPt<20.0) && ((GenJpsiRap) > pt_bound[ih] && (GenJpsiRap) <=pt_bound[ih+1] )){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight);}

	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);}
	
      }
      
    }//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); 
    
      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;}
	 
	 //without muon ID cuts
	 //if((muPosPt > PtCut && muNegPt > PtCut) && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1)){AllCut=1;}
	 
	 //without trigger
	 //if(  (muPosPt > PtCut && muNegPt > PtCut) && (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);}
	     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);}
	    

	     //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);}
	     
	     //for non symetric plots
	     if(iSpec == 2) if( (AllCut==1) &&  (JpsiPt<20.0) && ((JpsiRap) > pt_bound[ih] && (JpsiRap) <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight);}
	     

	     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);}
	     
	   }
	 }
 }
  
    /*
      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.060;
  mass_low = 8.8; mass_high = 10.0;  // Fit ranges
  
  
  // Fit Function crystall ball
  // TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,8.0,12.0,5);
  //GAUSPOL->SetParNames("#alpha","n","Mean","#sigma","N");
  //GAUSPOL->SetLineWidth(2.0);
  //GAUSPOL->SetLineColor(2);
  //GAUSPOL->SetParameter(0, 1.756);
  //GAUSPOL->SetParameter(1, 2.636);
  //GAUSPOL->SetParameter(2, MassUpsilon);
  //GAUSPOL->SetParameter(3, WeidthUpsilon);
  //GAUSPOL->SetParLimits(2, 0.1*MassUpsilon,2.0*MassUpsilon);
  //GAUSPOL->SetParLimits(3, 0.1*WeidthUpsilon,2.0*WeidthUpsilon);


 // 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]->GetMaximum());
    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 CB    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();

   TFile *outfile;
  if(iSpec==1)outfile =new TFile("EffUpsilon_Pt.root","Recreate");
  if(iSpec==2)outfile =new TFile("EffUpsilon_Rap.root","Recreate");
  if(iSpec==3)outfile =new TFile("EffUpsilon_Cent.root","Recreate");

  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");
    
 Eff_Upsilon->Write();

  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"); }
 
  outfile->Write();
  outfile->Close();



}
Пример #30
0
int main(int argc,char**argv)
{
    int length;
    GLOBAL_DATA head;
    INDEX_DATA index;
    std::ifstream is;
    std::string dataFile("DAY.DAT");
    std::string stock;
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "usage message")
        ("config,f", po::value(&dataFile), "data file")
        ("stock,s", po::value(&stock), "data file")
        ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    if (vm.count("help")) {
        std::cout << desc << "\n";
        std::cout << "usage:httpd -f [config file]" << "\n";
        return 0;
    }
    is.open (dataFile.c_str(), std::ios::binary );
    
    // get length of file:
//  is.seekg (0, std::ios::end);
//  length = is.tellg();
//  is.seekg (0, std::ios::beg);
//  std::cout<<length<<std::endl;
    // allocate memory:

    // read data as a block:
    is.read ((char*)&head,sizeof(GLOBAL_DATA));
    std::map<std::string,INDEX_DATA> stockMap;
    for(int i=0;i<head.stocksum;i++)
    {
        is.read ((char*)&index,sizeof(INDEX_DATA));
        stockMap.insert(std::make_pair<std::string,INDEX_DATA>(std::string(index.code),index));
    }
    std::map<std::string,INDEX_DATA>::iterator beg;
    std::map<std::string,INDEX_DATA>::iterator end;
    if(stock.length()>0)
    {
        beg= stockMap.find(stock);
        if(beg!=stockMap.end())
        {
            end=beg;
            ++end;
        }
    }else
    {
        beg= stockMap.begin();
        end= stockMap.end();
    }
    std::cout<<"'Date','Open','High','Low','Close','Volume','Money','Rise','Fall','Ticker'"<<std::endl;
    for(std::map<std::string,INDEX_DATA>::iterator it=beg;it!=end;++it)
    {
        char data[8192*25];
	memset(data,0,sizeof(data));
        for(int i=0;i<25;i++)
        {
            char tmp[8192];
            if(it->second.record[i]<head.startblock)
            {
                is.seekg (0x41000+8192*it->second.record[i], std::ios::beg);
                is.read (tmp,8192);
                memcpy(data+8192*i,tmp,8192);
            }
        }
        int ind=0;
        while(ind<256*25)
        {
            DAY_DATA day;
            memcpy(&day,data+ind*32,32);
            ind++;
            if(day.date==0)
                break;
            boost::posix_time::ptime pdate=boost::posix_time::from_time_t(day.date);
            std::cout<<"'"<<boost::gregorian::to_iso_extended_string(pdate.date())<<"','"<<day.open<<"','"
                     <<day.high<<"','"<<day.low<<"','"<<day.close<<"','"<<day.amount
                     <<"','"<<day.money<<"','"<<day.rise<<"','"<<day.fall<<"','"<<it->first<<"'"<<std::endl;
        }
    }
    is.close();
    return 0;
}