ReplayCore()

From Hall A Wiki
Jump to: navigation, search

Introduction

ReplayCore() is the core part of replay scripts system for experiment e08007 and Transversity. It is included ReplayCore.C and collaborate closely with definition file def.h

Major function of ReplayCore() is to

  1. prepare analyzer for replay
  2. Search for proper raw datafile
  3. Set path for output root file with overwritten protection
  4. loop through all data file sections and do analysis
  5. clean up

A complete replay script using ReplayCore() should do:

  1. Load detector and Apparatus
  2. Call ReplayCore()

HowTo

What are the interface of ReplayCore()

void ReplayCore(
		Int_t runnumber=0,            //run #
		Int_t all=0,                  //-1=replay all;0=ask for a number
		Int_t DefReplayNum=-1,        //defaut replay event num
		char* OutFileFormat="%s/e06010_test_%d.root", //output file format
		char* OutDefineFile="replay_test.odef",       //out define
		char* CutDefineFile="replay_test.cdef",       //cut define
		Bool_t EnableScalar=false,                    //Enable Scalar?
		Int_t FirstEventNum=0         //First Event To Replay
		)

HowTo enable scalar analysis?

set the 7th parameter from false to true.

What to do if I need special setting on analyzer?

Add following code to your script before calling ReplayCore()

THaAnalyzer* analyzer = THaAnalyzer::GetInstance();
if( !analyzer ) {
	analyzer = new THaAnalyzer;
}
analyzer->DO_YOUR_SETTING(...);

What I want to replay an arbitary section of the run?

set the 8th parameter to the first event number of the section you want to replay. The second parameter is still the number of event to replay.


An simple replay code

#include "def.h"

using namespace std;

void replay_BB(Int_t runnumber=0,Int_t all=0)
{

  //Add BigBite 
  THaBigBite* pB=new THaBigBite("BB","BigBite"); 
  THaBBTotalShower* ts=new THaBBTotalShower("ts","BigBite total shower");
  pB->AddDetector(ts);
  gHaApps->Add(pB);


  ReplayCore(
	    runnumber,            //run #
	    all,                  //-1=replay all;0=ask for a number
	    -1,                   //defaut replay event num
	    "%s/e06010_BB_%d.root", //output file format
	    "replay_BB.odef",       //out define
	    "replay_test.cdef"        //cut define
	    );
}

Source Code (Oct 13, 2008 version)

def.h


#ifndef ROOT_REPLAY_DEF
#define ROOT_REPLAY_DEF

static const char* PATHS[] = {
  "./raw",
    "/adaqfs/home/adaq/rawdata_links",
    "/cache/mss/halla/e06010/raw/",
    "/adaql2/data1",
    "/adaql2/data2",
    "/adaql2/data3",
    "/adaql2/data4",
    "/adaql1/data1",
    "/adaql1/data2",
    "/adaql1/data3",
    "/adaql1/data4",
    "/local/scratch/home/jinhuang/BigBite/RawData",
    ".",
    "/agen4/data1/raw/hadron/",
    "/agen4/data2/raw/hadron/hadron",
    0
};

static const char* RAW_DATA_FORMAT="%s/e06010_%d.dat.%d";

static const char* STD_REPLAY_OUTPUT_DIR="./ROOTfiles";
static const char* CUSTOM_REPLAY_OUTPUT_DIR="./ScratchROOTfiles";

static const char* SUMMARY_PHYSICS_FORMAT="./summaryfiles/summaryphy_%d.log";

static const Int_t ANA_MARK_INTERVAL=1000;

#include "ReplayCore.C"
// DO NOT DELETE!

ReplayCore.C

//////////////////////////////////////////////////////////////////////////
//
// Hall A analyzer replay script core
//
// Call this script after loading all the detectors to run replay
//
// if there is no rootlogon.C, execute following command in analyzer first
//   gSystem->Load("<your lib name>.so");
//  if you want to compile this script then you will also need
//   gSystem->AddIncludePath("-I<your include path>");
//   gInterpreter->AddIncludePath("<your include path>");
//
//////////////////////////////////////////////////////////////////////////
//	
//	Author : Jin Huang (jinhuang@jlab.org)    Aug 2007
//
//	Modify History:
//      Mar 2008    Jin Huang
//          add physics module support
//      Mar 2008    Jin Huang
//          separate two modes: physics replay and detector replay
//          also make it smarter
//      Apr 2008    Jin Huang
//          rootfile overwrite proof
//      May 2008    Jin Huang    
//          Separate core code of replay script to ReplayCore.C
//      May 2008    Jin Huang
//          Support Start Analyzing from an arbitary event number
//          Support Exit when getting an invalid answer.
//          Fix Bugs
//      Oct 2008    Jin Huang
//          Support raw data file name which do not have an endfix index
//
//////////////////////////////////////////////////////////////////////////


#ifndef ROOT_REPLAY_CORE
#define ROOT_REPLAY_CORE


//#include "def.h"

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>



#ifndef __CINT__
//header file for compile

#include "TSystem.h"
#include "TROOT.h"
#include "THaEvent.h"
#include "THaRun.h"
#include "THaAnalyzer.h"

#include "TTree.h"
#include "TFile.h"
#include "TString.h"

#endif//#ifdef __CINT__



using namespace std;

void ReplayCore(
				Int_t runnumber=0,            //run #
				Int_t all=0,                  //-1=replay all;0=ask for a number
				Int_t DefReplayNum=-1,        //defaut replay event num
				char* OutFileFormat="%s/e06010_test_%d.root", //output file format
				char* OutDefineFile="replay_test.odef",       //out define
				char* CutDefineFile="replay_test.cdef",       //cut define
				Bool_t EnableScalar=false,                    //Enable Scalar?
				Int_t FirstEventNum=0         //First Event To Replay
				)
{
	//general replay script core
	//
	// to do replay, use a script to load detectors then call this function
	//
	// it's also convenient to load detector manually in analyzer 
	// command line then call me

	// step 1: Init analyzer
	cout<<"replay: Init analyzer ..."<<endl;
	THaAnalyzer* analyzer = THaAnalyzer::GetInstance();
	if( analyzer ) {
		analyzer->Close();
	} else {
		analyzer = new THaAnalyzer;
	}

	//Enable scalers
	if (EnableScalar)
	{
		cout<<"replay: Enabling Scalars"<<endl;
		analyzer->EnableScalers();
	}

	// step 2: setup run information
	cout<<"replay: configuring analyzer ..."<<endl;
	int nrun, nev;
	int found = 0;
	const char** path = 0;
	char filename[300],buf[300];  
	FILE *fd;

	while( found==0 ) {
		if (runnumber<=0)
		{
			cout << "\nreplay: Please enter a Run Number (-1 to exit):";
			cin >> nrun;
			fgets(buf,300,stdin);//get the extra '\n' from stdin
			if( nrun<=0 ) break;
		}
		else 
			nrun=runnumber;

		path=PATHS;

		while ( path && *path ) {
			sprintf(filename,RAW_DATA_FORMAT,*path,nrun,0);
			cout<<"replay: Try file "<<filename<<endl;
			fd = fopen(filename,"r");
			if (fd != NULL) {
				found = 1;
				cout << "replay: Will analyze file "<<filename<<endl;
				fclose(fd);
				break;
			}
			path++;
		}
		if ( (!path || !*path) && !found ) {
			cout << "replay: File not found. \n";
			if (runnumber>0) runnumber=0;
		}
	}
	if(nrun<=0) {
		gHaApps->Delete();
		gHaPhysics->Delete();
		analyzer->Close();
		return;
	}


	if (all==0)
	{
		cout << "\nreplay: Number of Events to analyze "
			<<" (default=";
		if (DefReplayNum>0)
			cout<<DefReplayNum<<"):";
		else 
			cout<<"replay all):";


		//trick to support blank inputs
		fgets(buf,300,stdin);
		if (sscanf(buf,"%d\n",&nev)<1)
			nev=DefReplayNum;
	}
	else 
		nev=all;


	char outname[300];
	sprintf(outname,OutFileFormat,STD_REPLAY_OUTPUT_DIR,nrun);
	found=0;    

	//rootfile overwrite proof
	while (found==0)
	{
		cout << "replay: Testing file "<<outname<<" for overwrite proof."<<endl;
		fd = fopen(outname,"r");

		if (fd == NULL) {found=1;break;}
		else
		{
			fclose(fd);
			Long64_t NEnt=0;
			TFile *f=new TFile(outname);
			if (f)
			{
				TTree *t=(TTree *)f->Get("T");
				if (t!=0)  NEnt = (t->GetEntries());
			}
			delete f;
			TString DefOverWriting;
			if (NEnt==DefReplayNum || DefReplayNum<0 || NEnt==0)
				DefOverWriting="no";
			else DefOverWriting="yes";

			if (NEnt<=0) {
				cout <<endl << "replay: "<<outname
					<<" is an invalid root file, "
					<<"or other people is replaying it. ";
			}
			else{
				cout << "replay: "<<outname<<", which contains "<<NEnt
					<<" events, already exists. ";
			}

			cout<<"Do you want to overwrite it? "
				<<"(default="<<DefOverWriting.Data()<<"; enter \"c\" means exit):";

			//trick to support blank inputs
			fgets(buf,300,stdin);
			TString s(buf);
			s.Chop();
			s.ToLower();
			if (s.IsNull()) s=DefOverWriting;

			if (s=="y" || s=="yes") {found=1;break;}
			else if (s=="n" || s=="no"){
				sprintf(outname,OutFileFormat,
					CUSTOM_REPLAY_OUTPUT_DIR,nrun);
				cout<<endl
					<<"replay: please enter the output root file name. "<<endl
					<<"        leave blank = "<<outname<<endl
					<<"Root File:";

				//trick to support blank inputs
				fgets(buf,300,stdin);
				if (buf[0]!='\n' and buf[0]!=0){
					strcpy(outname,buf);
				}

				//clear the last char if it's '\n'
				if (outname[strlen(outname)-1]=='\n') outname[strlen(outname)-1]=0;
			}
			else {
				cout<<"replay: " 
					<<s.Data()
					<<"is not a valid input; Exiting."
					<<endl;
				gHaApps->Delete();
				gHaPhysics->Delete();
				analyzer->Close();
				return;
			}
		}
	}

	cout<<endl<<"----------------------------------------------"<<endl;
	cout<<"replay: Inputs Summary:"<<endl;
	cout<<"        Raw data: "<<filename<<endl;
	cout<<"        Event   : ";
	if (nev<0) cout <<"all events";
	else cout << nev <<" events";
	cout<<", starting from Event # "<<FirstEventNum<<endl;
	cout<<"        Outputs : "<<outname<<endl;
	cout<<"----------------------------------------------"<<endl<<endl;

	cout<<"replay: Setup run inputs/outputs ..."<<endl;

	analyzer->SetOutFile( outname );
	analyzer->SetOdefFile(OutDefineFile);
	analyzer->SetCutFile(CutDefineFile);  
	char sumname[300];
	sprintf(sumname,SUMMARY_PHYSICS_FORMAT,nrun);
	analyzer->SetSummaryFile(sumname); // optional
	analyzer->SetEvent( new THaEvent );
	analyzer->SetMarkInterval(ANA_MARK_INTERVAL);

	//correct the offset on the last event if first event is above 0
	if (nev>=0) nev+=FirstEventNum;

	// step 3: run it
	cout<<"replay: Start Process ..."<<endl;

	TString oldfilename="";
	THaRun *oldrun=0, *run, *runlist[30]={0};Int_t runidx=0;
	Bool_t exit=false;
	//UInt_t  NeveAna=0;
	for (Int_t nsplit=0;!exit;nsplit++)
	{

		sprintf(filename,RAW_DATA_FORMAT,"raw data paths",nrun,nsplit);
		cout<<"replay: trying file "<<filename<<endl;

		path=PATHS;found=0;
		while ( path && *path ) {
			sprintf(filename,RAW_DATA_FORMAT,*path,nrun,nsplit);
			//cout<<"replay: Try file "<<filename<<endl;
			fd = fopen(filename,"r");
			if (fd != NULL) {
				found = 1;
				cout << "replay: Will analyze file "<<filename<<endl;
				fclose(fd);
				break;
			}
			path++;
		}

		//cout<<"======================\n"<<oldfilename<<endl<<filename<<endl;
		if ( ((!path || !*path) && !found) || oldfilename==filename) {
			cout << "replay: no more raw data file to analyze"<<endl;
			exit=true;
		}
		else{
			oldfilename=filename;
			//do the analysis
			if( oldrun ) {
				run = new THaRun(*oldrun);
				run->SetFilename(filename);
			} else {
				run = new THaRun(filename);
			}
			runlist[runidx]=run; runidx++;

			if(nev>=0) run->SetLastEvent(nev);
			run->SetFirstEvent(FirstEventNum);

			//run->Print();
			analyzer->Process(run); 
			//NeveAna=run->GetNumAnalyzed();
			//cout << "replay: "<<NeveAna<<"events were analyzed."<<endl;

			//if (NeveAna-1>=(UInt_t)nev) exit=true;
			run->Close();
			if (!oldrun) oldrun = run;
			//else delete run;
		}
	}



	// step 3: clean up
	cout<<"replay: Cleaning up ... "<<endl;
	for (runidx--;runidx>=0;runidx--){
		assert(runlist[runidx]);
		delete runlist[runidx];
	}
	gHaApps->Delete();
	gHaPhysics->Delete();
	analyzer->Close();

	cout<<"replay: YOU JUST ANALYZED RUN number "<<nrun<<"."<<endl;
}

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



// DO NOT DELETE!
#endif//#define ROOT_REPLAY_CORE