laserrun.cc

00001 #include "FitOverROI.hh"
00002 #include "FitTH1F.hh"
00003 #include "TNamed.h"
00004 #include "TString.h"
00005 #include "TCanvas.h"
00006 #include "EventData.hh"
00007 #include "TRint.h"
00008 #include "ConfigHandler.hh"
00009 #include "CommandSwitchFunctions.hh"
00010 #include "utilities.hh"
00011 #include "RootGraphix.hh"
00012 #include "ChanFitSettings.hh"
00013 #include <sstream>
00014 #include <fstream>
00015 #include <map>
00016 #include <vector>
00017 #include <iostream>
00018 #include <iomanip>
00019 #include <cstdlib>
00020 #include "ParameterList.hh"
00021 #include "TTree.h"
00022 #include "TFile.h"
00023 #include "TF1.h"
00024 
00025 #define mNCHANS 14
00026 
00027 using namespace std;
00028 using namespace FitOverROI;
00029 
00030 
00031 class tab{
00032 public:
00033   int n;
00034   char f;
00035   tab(int nspaces, char fill=' ') : n(nspaces),f(fill) {}
00036 };
00037 
00038 ostream& operator<<(ostream& out, tab t)
00039 { return out<<left<<setfill(t.f)<<setw(t.n); }
00040 
00041 void PrintResults(std::map<int, FitTH1F*>* spectra)
00042 {
00043         
00044   cout<<"\n"<<tab(55,'*')<<""<<endl;
00045   cout<<"Current results are: "<<endl;
00046   cout<<tab(10)<<"Channel"<<tab(11)<<"spe_mean"<<tab(12)<<"spe_sigma";
00047   cout<<tab(11)<<"lambda"<<tab(11)<<"amp_E"<<tab(12)<<"p_E"<<tab(12)<<"Chi2/NDF";
00048   cout<<tab(6)<<"|||"<<tab(10)<<"pdfmean"<<tab(11)<<"pdfsigma"<<"pdfmean_err";
00049   cout<<endl;
00050   cout<<tab(104,'-')<<""<<endl;
00051   map<int, FitTH1F*>::iterator it = spectra->begin();
00052   for( ; it != spectra->end(); it++){
00053     cout<<tab(10)<<it->first;
00054     TF1* fit = (it->second)->GetFunction("spefunc");
00055     if(!fit){
00056       cout<<endl;
00057       continue;
00058     }
00059         
00060         
00061         double* params=fit->GetParameters();
00062         //double sigma_1=sqrt(params[FitOverROI::SHOTNOISE]*params[SHOTNOISE] + params[SIGMA]*params[SIGMA]);
00063         //double pdfmean=(1-params[FitOverROI::P_E])*(params[MEAN]+ sigma_1/(sqrt(2 * TMath::Pi()) * 0.5 *(1- TMath::Erf(-params[MEAN]/(sigma_1*sqrt(2))))) *TMath::Power(TMath::E(),-0.5 *params[MEAN]*params[MEAN]/(sigma_1 * sigma_1))) + params[P_E] * params[AMP_E];
00064     cout<<tab(11)<<params[MEAN]<<tab(12)<<params[SIGMA];
00065     cout<<tab(11)<<params[LAMBDA];
00066         cout<<tab(11)<<params[AMP_E];
00067         cout<<tab(12)<<params[P_E];
00068     stringstream s;
00069     s<<fit->GetChisquare()<<"/"<<fit->GetNDF();
00070     cout<<tab(12)<<s.str();
00071     cout<<tab(6)<<"|||";
00072         cout<<tab(10)<<m_n(params);
00073     //afan------------
00074     //double pdfmean_approx = params[P_E]*params[AMP_E]+(1-params[P_E])*params[MEAN];
00075     cout<<tab(11)<<sigma_n(params);
00076     double pdfmean_error = FitOverROI::pdfmean_error_corr((it->second)->fitResult);
00077     cout <<tab(10)<<pdfmean_error;
00078     
00079     //----------------
00080         
00081         
00082         //cout<<tab(10);
00083     if(fit->GetProb() < 0.01)
00084       cout<<"!";
00085     if(fit->GetProb() < 0.001)
00086       cout<<"!";
00087     cout<<endl;
00088   }
00089   cout<<tab(55,'*')<<""<<endl;
00090 }
00091 
00092 void DrawSpectra(map<int, FitTH1F*>* spectra, TCanvas* c)
00093 {
00094   c->Clear();
00095   DividePad(c,spectra->size());
00096   int padn=1;
00097   for( std::map<int,FitTH1F*>::iterator it = spectra->begin();
00098        it != spectra->end(); it++){
00099     //RootGraphix::Lock lock = root.AcquireLock();
00100     c->cd(padn++);
00101     gPad->SetLogy();
00102     TH1* hist = (it->second);
00103     hist->Draw();
00104   }
00105   c->cd(0);    
00106   c->Draw();
00107   c->Update();
00108 }
00109 
00110 /*
00111 void UpdateDatabase(map<int,FitTH1F*>* spectra, TTree* Events, ChanFitSettings ChannelSettings[])
00112 {
00113   const string table="laserruns";
00114   //find the runid
00115   EventData* ev = 0;
00116   Events->SetBranchAddress("event",&ev);
00117   Events->GetEntry(0);
00118   
00119 
00120   
00121   if(ev->run_id < 0){
00122     std::cerr<<"Unable to read runid from rootfile! Aborting."<<std::endl;
00123     return;
00124   }
00125   
00126   cout<<"How many filters were used in this run? "<<endl;
00127   int nfilters;
00128   cin>>nfilters;
00129   std::vector<RunDB::laserinfo> vec;
00130 for( map<int,FitTH1F*>::iterator it = spectra->begin();
00131 it != spectra->end(); it++){
00132         Events->GetEntry(0);
00133         for(int i =1;(ev->GetChannelByID(it->first)->regions.size() < 1) && (i<Events->GetEntries());i++)
00134         {  
00135                 Events->GetEntry(i);
00136         }
00137         if(ev->GetChannelByID(it->first)->regions.size() < 1){
00138                 std::cout<<"no regions found anywhere in tree!"<<endl;
00139                 throw std::runtime_error("No regions found in tree");
00140         }
00141         
00142         TF1* spefunc = (it->second)->GetFunction("spefunc");
00143         if(!spefunc){
00144                 cerr<<"Unable to get spefunc from channel "<<it->first<<endl;
00145                 continue;
00146         }
00147         std::stringstream CFSss;
00148         ChannelSettings[it->first].WriteTo(CFSss);
00149         std::string CFSstring = CFSss.str();
00150         FitTH1F* hist = it->second;
00151         
00152         int Runid = ev->run_id;
00153         int Channel = it->first;
00154         time_t Runtime=ev->timestamp;
00155         
00156         double Roi_start = ev->GetChannelByID(it->first)->regions[0].start_time;
00157                 //          double Roi_start, double Roi_end, FitTH1F* h, std::string Fitsettings
00158         
00159     vec.push_back(RunDB::laserinfo(Runid, 
00160                                    Channel,  
00161                                    Runtime,
00162                                    nfilters,
00163                                    Roi_start,
00164                                    ev->GetChannelByID(it->first)
00165                                      ->regions[0].end_time,
00166                                    hist, CFSstring) )
00167                                    ; 
00168     
00169   }
00170   int rows = InsertLaserInfo(vec);
00171   std::cout<<rows<<" entries were successfully inserted into the database."
00172            <<std::endl;
00173 }
00174 */
00175 
00176 void RefitChannel(FitTH1F* h, int entries, TCanvas* c, ChanFitSettings& CFS)
00177 {
00178   c->Clear();
00179   h->Draw();
00180   string response="";
00181 
00182 /*   TNamed* options = (TNamed*)h->FindObject("options");
00183   if(!options){
00184     options = new TNamed("options","");
00185     options->SetBit(TObject::kCanDelete, true);
00186     h->GetListOfFunctions()->Add(options); 
00187   }*/
00188   while( response[0] != 'r' && response[0] != 'f'
00189          && response[0] != 's' &&response[0] != 'd'){
00190     if(response != "")
00191       cerr<<response<<" is not a valid option!"<<endl;
00192     cout<<"Would you like to \n"
00193         <<" r) Rebin the histogram\n"
00194         <<" s) Suppress the background exponential in the fit\n"
00195         <<" f) fix the fit by altering the config\n"
00196         <<" d) refit with the default method\n"
00197         <<endl;
00198     cin >> response;
00199   }
00200 /*   std::string optstring = options->GetTitle();
00201   optstring += response;
00202   options->SetTitle(optstring.c_str()); */
00203   
00204 
00205   bool allow_bg = true;
00206   bool force_old = false;
00207   if(response.find('d') != string::npos){}
00208   if(response.find('r') != string::npos){
00209     int lastbin = h->GetXaxis()->GetLast();
00210     h->Rebin();
00211     h->GetXaxis()->SetRange(0,lastbin/2);
00212   }
00213  
00214   if(response.find('s') != string::npos){
00215     allow_bg = false;
00216   }
00217   if(response.find('f') != string::npos){
00218 
00219         char temppath[]="/tmp/fileXXXXXX";
00220         int test = mkstemp(temppath);
00221         if(test == -1){
00222           Message(ERROR)<<"Unable to open temp file!\n";
00223           return;
00224         }
00225         fstream tempfile(temppath, fstream::in | fstream::out | fstream::app);
00226         CFS.WriteTo(tempfile);
00227         tempfile<<endl<<"# Parameter meanings:"<<endl;
00228         tempfile<<"# amp_E: Decay constant of SPE exponential"<<endl;
00229         tempfile<<"# constant: Normalization to number of events"<<endl;
00230         tempfile<<"# lambda: Occupancy"<<endl;
00231         tempfile<<"# mean: SPE gaussian center"<<endl;
00232         tempfile<<"# p_E: Proportion of total SPE distribution in the exponential"<<endl;
00233         tempfile<<"# pedmean: Pedestal gaussian center"<<endl;
00234         tempfile<<"# pedrange: Range looked at to find pedestal center."<<endl;
00235         tempfile<<"# range: Histogram x-axis range"<<endl;
00236         tempfile<<"# shotnoise: Pedestal width"<<endl;
00237         tempfile<<"# sigma: SPE gaussian width"<<endl;
00238         tempfile.clear();
00239         tempfile.close();
00240         std::stringstream command;
00241     command << "emacs "<<temppath;
00242     if( system(command.str().c_str()) ){
00243       std::cerr<<"Unable to open config for editing."<<std::endl;
00244     }
00245         else{
00246                 
00247                 tempfile.open(temppath, fstream::in);
00248                 CFS.ReadFrom(tempfile);
00249                 cout<<"Config File read back."<<endl;
00250                 CFS.WriteTo(cout);
00251                 cout<<endl;
00252         }
00253         tempfile.close();
00254         remove(temppath);
00255   }
00256   FitSPE(h, CFS,entries,allow_bg, force_old);
00257   //FitSPE(h,entries,min,max,allow_bg);
00258 }    
00259   
00260 
00261 void QueryUser(map<int, FitTH1F*>* spectra, TTree* Events, RootGraphix* root, ChanFitSettings ChannelSettings[], 
00262                TCanvas* c = 0)
00263 {
00264   if(!c)
00265     c = new TCanvas;
00266   bool showresults=true;
00267   string response = "";
00268   while(response != "q"){
00269     if(showresults){
00270       RootGraphix::Lock lock = root->AcquireLock();
00271       DrawSpectra(spectra, c);
00272       PrintResults(spectra);
00273     }
00274     showresults=false;
00275     cout<<"Enter \n q) to quit, \n"
00276         <<" #) to retry fitting channel # \n"
00277         <<" r#) to remove channel # from the list\n"
00278         <<" w) to write the results to the database."<<endl;
00279     cin >> response;
00280     if(response == "q"){
00281       cout<<"Aborting without saving results."<<endl;
00282       break;
00283     }
00284     if(response == "w"){
00285       //UpdateDatabase(spectra, Events, ChannelSettings);
00286       break;
00287     }
00288     bool remove = false;
00289     if( response[0] == 'r'){
00290       remove = true;
00291       response.erase(0,1);
00292     }
00293     int chan = atoi(response.c_str());
00294     if( chan == 0 && response != "0"){
00295       //user entered something weird
00296       cout<<"'"<<response<<"' is not a valid response!"<<endl;
00297       continue;
00298     }
00299     //ok, we should have a number in there
00300     //find the relevant channel
00301     map<int, FitTH1F*>::iterator it = spectra->find(chan);
00302     if( it == spectra->end()){
00303       cout<<chan<<" is not a valid channel!"<<endl;
00304       continue;
00305     }
00306     showresults = true;
00307     if(remove){
00308       (it->second)->Delete();
00309       spectra->erase(it);
00310       continue;
00311     }
00312     else{
00313       RootGraphix::Lock lock = root->AcquireLock();
00314       FitTH1F* h = (it->second);
00315       RefitChannel(h,Events->GetEntries(),c,ChannelSettings[it->first]);
00316       showresults=true;
00317       c->Update();
00318       continue;
00319     }
00320   } 
00321   if(c) delete c;
00322 }
00323 
00324 int ProcessLaserRun(const char* fname, unsigned region=0,bool rehist=false,bool min=false)
00325 {
00326         ParameterList* ChanSettingsHandler = new ParameterList("ChannelsSettings","Stores 8 channels of fit settings");
00327         ChanFitSettings ChannelsSettings[ mNCHANS ];
00328         
00329         
00330         for(int j=0; j< mNCHANS; j++){
00331                 stringstream name;
00332                 stringstream help;
00333                 name<<"chan"<<j;
00334                 help<<"Fit settings for channel "<<j;
00335                 ChanSettingsHandler->RegisterParameter(name.str(),ChannelsSettings[j], help.str());
00336                 }
00337         ifstream CFSConfig("cfg/LaserCFSConfig.cfg");
00338         ChanSettingsHandler->ReadFrom(CFSConfig);
00339         CFSConfig.close();
00340         
00341   const int nbins=315;
00342   const double start=-30, end=600; 
00343   std::map<int,FitTH1F*> spectra;
00344   std::map<int,FitTH1F*> spectra2; //historgram of amplitude (min)
00345   RootGraphix root;
00346   root.Initialize();
00347   TFile *f= OpenFile(fname,"UPDATE");
00348   if(!f){cout<<"File not opened!"<<endl;}
00349   TTree* Events = GetEventsTree(fname);
00350   if(!Events) {cout<< "!Events"<<endl; return -1;}
00351 
00352         
00353   EventData* event=0;
00354   Events->SetBranchAddress("event",&event);
00355   Events->GetEntry(0);
00356   cout<<"There are "<<Events->GetEntries()<<" entries in this tree."<<endl;
00357 
00358    //check for cached histograms
00359         bool found_all=true;
00360 
00361         //if(event->channels.size() > 10){cout<< "channels.size() >10"<<endl;    return -2;}
00362         if(!rehist){
00363                 for(size_t j=0; j < event->channels.size(); j++){
00364                         TString name = "channel";
00365                         ChannelData* channel = &(event->channels.at(j));
00366                         name += channel->channel_id;
00367                         FitTH1F *histo= new FitTH1F();
00368                         int read= histo->Read(name);
00369                         cout<<"readvar" << read<<endl;
00370                         if (read==0) { found_all = false; delete histo; break; }
00371 
00372                         if(found_all){
00373                                 cout<<"Loaded cached histogram "<<name<<endl;
00374                                 std::map<int,FitTH1F*>::iterator mapit = spectra.find(channel->channel_id);
00375 
00376                                 if(mapit == spectra.end()){
00377                                         spectra.insert( std::make_pair(channel->channel_id, histo) );     }
00378                                   else{
00379                                         histo = (mapit->second);
00380                                   }
00381                                 }
00382                 }
00383         }
00384   //Create histograms of amplitude (min) (by Xiaoyang)
00385         if(min){
00386      for(int i=0; i < Events->GetEntries(); i++){
00387                 if(i%5000 == 0) cout<<"Processing Entry "<<i<<endl;
00388                 
00389                         Events->GetEntry(i);
00390                         //iterate over all channels
00391                         
00392                         
00393                         for(size_t j=0; j < event->channels.size(); j++){
00394                           ChannelData* channel = &(event->channels.at(j));
00395                           if(channel->channel_id < 0){
00396                                 cout<<"channel->channel_id < 0"<<endl;
00397                                 continue;
00398                                 }
00399                           std::map<int,FitTH1F*>::iterator mapit = spectra2.find(channel->channel_id);
00400                           FitTH1F* histo=0;
00401                           if(mapit == spectra2.end()){
00402                                 TString name = "channel";
00403                                 name += channel->channel_id;
00404                                 cout<<"Creating new histogram with name "<<name<<endl;
00405                                 histo = new FitTH1F(name,name,nbins,start,end);
00406                                 spectra2.insert( std::make_pair(channel->channel_id, histo) );
00407                           }
00408                           else{
00409                                 histo = (mapit->second);
00410                           }
00411                 
00412                           //fill the histogram
00413                           if(!histo){
00414                         cerr<<"Null pointer passed!\n";
00415                         return -2;
00416                           }
00417 
00418                         if( channel->regions.size() > region){  
00419                                 histo->Fill( -channel->regions.at(region).min);
00420                         }
00421                 }
00422         }
00423 
00424         
00425   //Draw all the histograms
00426   TCanvas* cmin = new TCanvas("cmin",fname);
00427   cmin->SetLogy();
00428   for( std::map<int,FitTH1F*>::iterator it = spectra2.begin();
00429        it != spectra2.end(); it++){
00430     RootGraphix::Lock lock = root.AcquireLock();
00431     FitTH1F* hist = (it->second);
00432     hist->Draw();
00433         if(rehist||!found_all){ hist->Write(hist->GetName(),TObject::kOverwrite);}
00434         cout<<"about to fit"<<endl;
00435         //FitSPE(hist, ChannelsSettings[it->first], Events->GetEntries());
00436         cout<<"done fitting"<<endl;
00437          cmin->Update();
00438   }
00439  DrawSpectra(&spectra2,cmin);
00440         }
00441 
00442         //create historgams of integrals
00443   if(!found_all||rehist){
00444           //process the tree line by line, and create histograms for each channel
00445           for(int i=0; i < Events->GetEntries(); i++){
00446                 if(i%5000 == 0) cout<<"Processing Entry "<<i<<endl;
00447                 
00448                         Events->GetEntry(i);
00449                         //iterate over all channels
00450                         /*
00451                           if(event->channels.size() > 10){    
00452                                 cout<<"channels.size()>10"<<endl;
00453                                 return -2;}
00454                         */
00455                         for(size_t j=0; j < event->channels.size(); j++){
00456                           ChannelData* channel = &(event->channels.at(j));
00457                           if(channel->channel_id < 0){
00458                                 cout<<"channel->channel_id < 0"<<endl;
00459                                 continue;
00460                                 }
00461         if(!channel->baseline.found_baseline){
00462                                 if (i==0){cout<<"channel "<<channel->channel_id<<": no baseline found, skipping"<<endl;}
00463                                 continue;
00464                                 }
00465                           std::map<int,FitTH1F*>::iterator mapit = spectra.find(channel->channel_id);
00466                           FitTH1F* histo=0;
00467                           if(mapit == spectra.end()){
00468                                 TString name = "channel";
00469                                 name += channel->channel_id;
00470                                 cout<<"Creating new histogram with name "<<name<<endl;
00471                                 histo = new FitTH1F(name,name,nbins,start,end);
00472                                 spectra.insert( std::make_pair(channel->channel_id, histo) );
00473                           }
00474                           else{
00475                                 histo = (mapit->second);
00476                           }
00477                 
00478                           //fill the histogram
00479                           if(!histo){
00480                         cerr<<"Null pointer passed!\n";
00481                         return -2;
00482                           }
00483                         //if(channel->pulses.size() > region)   histo->Fill( -channel->pulses.at(region).integral);
00484                         if( channel->regions.size() > region){  
00485                             histo->Fill( -channel->regions.at(region).integral);
00486                         }
00487                 }
00488         }
00489   }
00490         
00491   //Draw all the histograms
00492   TCanvas* c = new TCanvas("c",fname);
00493   c->SetLogy();
00494   for( std::map<int,FitTH1F*>::iterator it = spectra.begin();
00495        it != spectra.end(); it++){
00496     RootGraphix::Lock lock = root.AcquireLock();
00497     FitTH1F* hist = (it->second);
00498     hist->Draw();
00499         if(rehist||!found_all){ hist->Write(hist->GetName(),TObject::kOverwrite);}
00500         cout<<endl<<"About to fit channel: "<<it->first<<endl<<endl;
00501         FitSPE(hist, ChannelsSettings[it->first], Events->GetEntries());
00502         cout<<endl<<"Done fitting channel: "<<it->first<<endl<<endl;
00503     c->Update();
00504   } 
00505   
00506   
00507   QueryUser(&spectra, Events, &root, ChannelsSettings, c);
00508   f->Close();
00509   return spectra.size();
00510   
00511 }
00512 
00513 int main(int argc, char** argv)
00514 {
00515   bool rehist=false; 
00516   bool reprocess=false;
00517   bool min = false; //amplitude switch
00518   bool mc=false;
00519 
00520   ConfigHandler* config = ConfigHandler::GetInstance();
00521   config->AddCommandSwitch('m',"amplitude","generate histogram of amplitude",
00522                            CommandSwitch::Toggle(min));
00523   config->AddCommandSwitch('r',"rehist","re-histogram data",
00524                            CommandSwitch::Toggle(rehist));
00525   config->AddCommandSwitch('p',"reprocess",
00526                            "Force (re)processing of genroot output",
00527                            CommandSwitch::SetValue<bool>(reprocess,true)); 
00528   config->AddCommandSwitch('s',"mc",
00529                            "Data is MC simulation",
00530                            CommandSwitch::SetValue<bool>(mc,true));
00531 
00532   config->SetProgramUsageString("laserrun [options] <run number>");
00533   if(config->ProcessCommandLine(argc,argv))
00534     return -1;
00535   
00536   if(argc != 2){
00537     config->PrintSwitches(true);
00538   }
00539   //generate the run filename
00540   int run = atoi(argv[1]);
00541   std::stringstream rootfile, rawfile;
00542   if(!mc){
00543     rootfile << "/data/singlepe/Run";
00544     rawfile  << "/data/rawdata/Run";
00545     rootfile<<std::setw(6)<<std::setfill('0')<<run<<".root";
00546     rawfile<<std::setw(6)<<std::setfill('0')<<run<<"/Run"<<std::setw(6)<<std::setfill('0')<<run<<".out";
00547   } else {
00548     rootfile << "/data/test_processing/mc_singlepe/Run";
00549     rawfile  << "/data/test_processing/mc_singlepe_raw/Run";
00550     rootfile<<std::setw(6)<<std::setfill('0')<<run<<".root";
00551     rawfile<<std::setw(6)<<std::setfill('0')<<run<<"/Run"<<std::setw(6)<<std::setfill('0')<<run<<".out";
00552   }
00553 
00554   std::ifstream fin(rootfile.str().c_str());
00555   if(reprocess || !fin.is_open()){
00556     if(!reprocess){
00557       std::cout<<"The processed rootifle "<<rootfile.str()<<" is not present."
00558                <<"\nWould you like to create it now? (y/n)"<<std::endl;
00559       char answer;
00560       std::cin>>answer;
00561       if(answer != 'y' && answer != 'Y'){
00562         std::cout<<"OK, aborting"<<endl;
00563         return 1;
00564       }
00565     }
00566     std::stringstream command;
00567     if(!mc){
00568       command << "./genroot --cfg cfg/laserrun_analysis.cfg "<<rawfile.str();
00569     } else {
00570       command << "./genroot --cfg cfg/laserrun_mc_analysis.cfg "<<rawfile.str();
00571     }
00572 
00573     if( system(command.str().c_str()) ){
00574       std::cerr<<"Unable to generate rootfile; aborting."<<std::endl;
00575       return 1;
00576     }
00577   }
00578   fin.close();
00579   return ProcessLaserRun(rootfile.str().c_str(),0,rehist,min);
00580 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines

Generated on 20 Jun 2014 for daqman by  doxygen 1.6.1