int main(int argc, char* argv[]) {
    
    
    // initialize globalArgs
    globalArgs.data_folder = " ";
    globalArgs.arg_pathToSetupFile = " ";
    globalArgs.results_folder = " ";
    globalArgs.save_all = 0;
    
    // Get paremeter from the command
    int opt =0;
    opt = getopt(argc, argv, optString);
    if(opt == -1){
        std::cerr <<  "There is no opption in the command! Type \"output -h\" for help." << std::endl;
        exit(EXIT_FAILURE);
    }
    
    while(opt != -1){
        switch(opt){
            case 'd':
                globalArgs.data_folder= optarg;
                //std::cout<<"-p option path= "<<globalArgs.arg_pathToData<<std::endl;
                break;
            case 'S':
                globalArgs.arg_pathToSetupFile = optarg;
                break;
            case 'o':
                globalArgs.results_folder = optarg;
                break;
            case 'a':
                globalArgs.save_all = 1;
                break;
            case 'h':
            case '?':
                std::cerr << "Usage: output -d pathToData -S pathToSetupFile -o pathToResultsFolder [-a]" << std::endl;
                std::cerr << "----------------------------------------------------------------------------------------------------"<<std::endl;
                std::cerr << " '-d'+'-S'+'-o' options are necessary!"<<std::endl;
                std::cerr << "-----------------------------------------------------------------------------------------------------"<<std::endl;
                std::cerr << " use '-a' option afterwards to save all the plots of the analysis to further check."<<std::endl;
                std::cerr << "-----------------------------------------------------------------------------------------------------"<<std::endl;
                std::cerr << "Example: ./output -d /Users/Analysis_waveforms/ov_scan_pde_H2014/ -S /Users/Analysis_waveforms/config_file.txt -o /Users/Analysis_waveforms/Plots/ [-a]"<<std::endl;
                exit(EXIT_FAILURE);
                break;
            default:
                break;
        }
        opt = getopt(argc, argv, optString);
    }
    
    
    if((strncmp(globalArgs.data_folder," ",1) == 0|| strncmp(globalArgs.arg_pathToSetupFile," ",1) == 0)){
        std::cerr << "ERROR: -d or -S option is not set! Both of them has to be set correctly!"<<std::endl;
        exit(EXIT_FAILURE);
    }
    
    if(strncmp(globalArgs.results_folder," ",1) == 0){
        std::cerr << "ERROR: -o option is not set! It has to be set up correctly!"<<std::endl;
        exit(EXIT_FAILURE);
    }
            
    ifstream setupFile(globalArgs.arg_pathToSetupFile);
    if(!setupFile){
        std::cerr << "Failure: could not open file: \"" << globalArgs.arg_pathToSetupFile << "\"." << std::endl;
        std::cerr << "Please check if the path is correct or not!" << std::endl;
        exit(EXIT_FAILURE);
    }
    
    ////////////////
    //Define thresholds
    ////////////////
    
    //in  nanoseconds
    const double reject_time = 4;
    vector <Double_t> reject_time_v;
    //used for AP, delayed x-talk and long tau fit
    
    
    //in percentage of pe
    const double after_pulse_th = 0.38;
    vector <Double_t> after_pulse_th_v;
    const double direct_xtalk_th = 1.17;
    vector <Double_t> direct_xtalk_th_v;
    const double xtalk_th = 0.85;
    vector <Double_t> xtalk_th_v;
    const double time_dist_th = 0.4;
    vector <Double_t> time_dist_th_v;
    
    ////////////////
    ////////////////
    
    //Read setup file:
    string s;
    vector <TString> vol_folders;
    Int_t data_size;

    while (true) {
        
        Double_t rt;
        Double_t ap;
        Double_t delay;
        Double_t imme;
        
        getline(setupFile, s);
        if (setupFile.eof()) break;
        
        const char* searchString = s.c_str();
        char volt [20];
        Int_t numfiles;
        
        if (s.find("#") == 0 || s=="") {
            continue; // Skip commented  or empty lines
        }
        
        //Find the voltages
        if(sscanf(searchString, "V || %s ||", volt)==1){
            vol_folders.push_back(volt);
            reject_time_v.push_back(reject_time);
            after_pulse_th_v.push_back(after_pulse_th);
            direct_xtalk_th_v.push_back(direct_xtalk_th);
            xtalk_th_v.push_back(xtalk_th);
            time_dist_th_v.push_back(time_dist_th);
        }
        
        if(sscanf(searchString, "V/th || %s ||", volt)==1){
            vol_folders.push_back(volt);
            getline(setupFile, s);
            const char* thresholds_string = s.c_str();
            sscanf(thresholds_string, "Rej_t: %lf, AP_th: %lf, Delay_th: %lf, Imm_th: %lf", &rt,&ap,&delay,&imme);
            reject_time_v.push_back(rt);
            after_pulse_th_v.push_back(ap);
            direct_xtalk_th_v.push_back(imme);
            xtalk_th_v.push_back(delay);
            time_dist_th_v.push_back(time_dist_th);
        }
        
        //Find data size
        if(sscanf(searchString, "Files at each voltage || %d ||", &numfiles)==1){
            data_size = numfiles;
        }
    }
    
    
    
    //Initialize variables
    const Int_t vol_size = vol_folders.size();
    
    int singleplot=0;
    Int_t Event=0;
    Char_t Category[15];
    TGraph* waveform = 0;
    Double_t Amp;
    Double_t V_meas;
    
    double pe = 0.07;
    int row = 0;
    int full_n_file = 0;
    int ap_n_file = 0;
    int xtalk_n_file = 0;
    int dxtalk_n_file = 0;
    int time_dist_n_file = 0;
    
    int direct_xtalk_pulse;
    Double_t direct_xtalk_pulse_cnt=0;
    int xtalk_pulse;
    Double_t xtalk_pulse_cnt = 0;
    int after_pulse;
    Double_t after_pulse_cnt=0;
    Double_t event_cnt = 0;
    double sig_max = 0;
    double time_of_max = 0;
    double sig_max_first = 0;
    double time_of_max_first = 0;
    int max_cnt = 0;
    int max_noise_cnt = 0;
    int max_found = 0;
    
    
    
    /*const char * Voltage="56.5V";
    int event=0;
    if (singleplot) {
        single_plot(Voltage,event);
    }*/
    
    
    //Create a root tree with the graph of the waveform of each event and
    //classify them
    TString filename = globalArgs.results_folder;
    filename.Append("noiseanalysis.root");
    
    TFile *hfile = 0;
    hfile = TFile::Open(filename,"RECREATE");
    
    
    TTree *tree = new TTree("T","Noise Analysis");
    tree->Branch("Event",&Event,"Event/I");
    tree->Branch("Category",Category,"Category/C");
    //Uncomment if every single waveform is desired to be saved by its own on the root file
    //tree->Branch("waveform","TGraph",&waveform);
    tree->Branch("V_meas",&V_meas,"V_meas/D"); //OV of the measurement
    
   
    TGraph* Correl_noise[4];
    Correl_noise[0] = new TGraph();
    Correl_noise[1] = new TGraph();
    Correl_noise[2] = new TGraph();
    Correl_noise[3] = new TGraph();
    TGraph *Expfit_longtau[vol_size];
    TGraph *Expfit_AP[vol_size];
    
    //Fiting functions of long tau and AP recharge
    TF1 *exp_longtau= new TF1("exptau","[0]*exp(-x/[1])",0,180 * ns);
    TF1 *exp= new TF1("exp","[0]*(1-exp(-x/[1]))+[2]*exp(-x/[3])",0,180 * ns);
    
    TCanvas* c1[vol_size];
    TCanvas* c2[vol_size];
    TCanvas* c3[vol_size];
    TCanvas* c4[vol_size];
    
    TMultiGraph *Cleanwaves[vol_size];
    TCanvas* expfit_longtau_c[vol_size];
    TCanvas* expfit_AP_c[vol_size];
    
    cout<<"////////////"<< endl;
    cout<<"****----->Voltage Breakdown calculation ***"<< endl;
    
   
    vector <Double_t> pe_volt;
    TGraph *Vbias_ver= new TGraph();
    
    
        //Change to not recalculate the pe
        //pe_volt.push_back(6.87435e-02);
        /*pe_volt.push_back( 1.20426e-01);
        pe_volt.push_back(1.75262e-01);
        pe_volt.push_back(2.30936e-01);
        pe_volt.push_back(2.87958e-01);*/
        //pe_volt.push_back( 3.44156e-01);
        //Double_t VBD=55.9006;
    
    //Calculate Voltage breakdown and value of pe
    for (int i=0; i<vol_size; i++) {
        pe_volt.push_back(Amplitude_calc(vol_folders.at(i).Data(), data_size));
        V_meas = vol_folders.at(i).Atof();
        Vbias_ver->SetPoint(i, pe_volt.at(i), V_meas);
    }
    
    TCanvas* ca= new TCanvas("Voltage Breakdown calculation","Voltage Breakdown calculation",100,100,900,700);
    Vbias_ver->SetTitle("Voltage Breakdown calculation");
    Vbias_ver->GetYaxis()->SetTitle("Bias Volatge [V]");
    Vbias_ver->GetYaxis()->SetTitleOffset(1.2);
    Vbias_ver->GetXaxis()->SetTitle("Mean peak amplitude [V]");
    Vbias_ver->Draw("AP*");
    ca->SetGrid();
    
    TPaveText * pv = new TPaveText(0.2,0.65,0.35,0.74,"brNDC");
    
    cout<<"////////////"<< endl;
    cout<<"****----->Voltage Breakdown fit ***"<< endl;
    
    TFitResultPtr fit = Vbias_ver->Fit("pol1","S");
    Double_t VBD= fit->Value(0);
    
    Char_t VBD_text[20];
    sprintf(VBD_text,"V_{BD} = %2.2f",VBD);
    pv->AddText(VBD_text);
    pv->Draw();
    
    if (globalArgs.save_all==1) ca->Write();
    
    cout<<"////////////"<< endl;
    cout<<"****----->Noise analysis ***"<< endl;
    cout<<"////////////"<< endl;
    
    /////////////////
    // Loop over all Voltages measured
    /////////////////
    for (int i=0; i<vol_size; i++) {
        
        //Important to reinitialize, the value color* = kOrange-11 is used to plot axis of TGraph()
        
        int color1 = kOrange-11;
        int color2 = kOrange-11;
        int color3 = kOrange-11;
        int color4 = kOrange-11;
        
        direct_xtalk_pulse_cnt = 0;
        xtalk_pulse_cnt = 0;
        after_pulse_cnt = 0;
        event_cnt = 0; //Events on the Voltage measured
        
        cout<<"****----->Voltage analyzed: "<< vol_folders.at(i) << endl;
        
        
        //Define amplitude measured at which OV
        
        Double_t pe = pe_volt.at(i);
        
        V_meas = vol_folders.at(i).Atof()-VBD;
        
        //Define canvases to save and check results
        
        Char_t canvas_title[40];
        sprintf(canvas_title,"Direct CrossTalk OV = %2.2f V",V_meas);
        c1[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700);
        sprintf(canvas_title,"Delayed CrossTalk OV = %2.2f V",V_meas);
        c2[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700);
        sprintf(canvas_title,"After Pulse OV = %2.2f V",V_meas);
        c3[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700);
        sprintf(canvas_title,"Clean OV = %2.2f V",V_meas);
        c4[i] = new TCanvas(canvas_title,canvas_title,100,100,900,700);
        
        Cleanwaves[i]=new TMultiGraph();
        
        sprintf(canvas_title,"Exponential fit, #tau_l OV = %2.2f V",V_meas);
        expfit_longtau_c[i] = new TCanvas(canvas_title,canvas_title,300,100,900,500);
        sprintf(canvas_title,"Exponential fit OV = %2.2f V",V_meas);
        expfit_AP_c[i] = new TCanvas(canvas_title,canvas_title,300,100,900,500);
        
        Expfit_longtau[i]= new TGraph();
        Expfit_AP[i]= new TGraph();
        
        //loop over every measurement on a folder
        for (int j=0; j<data_size; j++) {
            
            Char_t datafilename[200];
            Char_t datashortfilename[100];
            
            sprintf(datafilename,"%s%s/C1H%05i.csv",globalArgs.data_folder,vol_folders.at(i).Data(),j);
            sprintf(datashortfilename,"%s_C1H%05i",vol_folders.at(i).Data(),j);
            //Get the data of a single file:
            waveform = new TGraph(datafilename,"%lg %lg","/t;,");
            if (waveform->IsZombie()) continue;
            
            waveform->SetName(datashortfilename);
            waveform->SetTitle("");
            
            Int_t ROWS_DATA = waveform->GetN();
            Double_t *time = waveform->GetX();
            Double_t *volts = waveform->GetY();
            
            Amp = waveform->GetY()[0];
            
            
            /////////////////////////////////////////////////////
            // Data filtering into the different type of events
            // direct x-talk  AP   delayed x-talk
            /////////////////////////////////////////////////////
            after_pulse = 0;
            xtalk_pulse = 0;
            direct_xtalk_pulse = 0;
            sig_max = 0;
            max_cnt = 0;
            max_found = 0;
            
            /////////////////////////////////////////////////////
            // direct x-talk
            for (row = 0; row < ROWS_DATA; row++) {
                if ((time[row]>0 * ns)&(volts[row] > direct_xtalk_th_v.at(i) * pe)) {// time larger 0ns
                    direct_xtalk_pulse++;
                }
            }
            
            /////////////////////////////////////////////////////
            // after-pulse threshold
            for (row = 0; row < ROWS_DATA; row++) {
                if ((time[row]>reject_time_v.at(i)*ns)&(volts[row] > after_pulse_th_v.at(i) * pe)) {// time larger 4ns and ap_th
                    after_pulse++;
                }
            }
            
            /////////////////////////////////////////////////////
            // delayed x-talk
            for (row = 0; row < ROWS_DATA; row++) {
                if ((time[row]>reject_time_v.at(i)*ns)&(volts[row] > xtalk_th_v.at(i) * pe)) {// time larger 4ns and larger xtalk_th
                    xtalk_pulse++;
                }
            }
            
            
            /////////////////////////////////////////////////////////////////////
            // Detect peaks in data after 4ns, count the number of maxima and
            // measure the time of arrival of first maxima, used later for AP exp fit
            /////////////////////////////////////////////////////////////////////
            max_noise_cnt = 0;
            for (row = 0; row < ROWS_DATA; row++) {
                if (time[row] > reject_time_v.at(i)*ns) {// time larger 4ns
                    if (volts[row] > sig_max) {
                        sig_max = volts[row];        // set the max
                        time_of_max = time[row];    // time max
                        max_noise_cnt++;                   // set the histeresis cnt
                    }else if (max_noise_cnt > 0) max_noise_cnt--;  //  count down if no new max is reached
                    // decide if real max or only noise, threshold has to be reached in case of a real max
                    if (max_noise_cnt>2 && sig_max > time_dist_th_v.at(i) * pe) {
                        max_cnt++;
                        if (max_cnt == 1) {
                            sig_max_first = sig_max;  // sig max
                            time_of_max_first = time_of_max; // time max
                            max_found = 1;
                            //printf("First max found: sig=%f  time=%f ns max_noise_cnt=%d\n", sig_max, time_of_max / ns, max_noise_cnt);
                        }
                        
                        //printf("Max number is: %d   cnt=%d\n", max_cnt, max_noise_cnt);
                    }
                } // 4ns
            } //loop over time
            
            bool clean = true; //The pulse is clean until the contrary can be demonstrated
            char graph_title[50];
            
            //Check for imm x-talk and plot
            if (direct_xtalk_pulse > 0){
                direct_xtalk_pulse_cnt++;
                sprintf(Category,"ImmCrosstalk");
                c1[i]->cd();
                
                //Set graph color, and counting to draw axis and title
                color1=color1+2;
                if (color1>kOrange+110) {
                    color1=kOrange-8;
                }else if (color1>kOrange+109){
                    color1=kOrange-7;
                }
                waveform->SetLineColor(color1);
                waveform->SetMarkerColor(color1);
                
                //Format the graph
                sprintf(graph_title,"Direct CrossTalk OV = %2.2f V",V_meas);
                waveform = format_graph(waveform,graph_title,2.5*pe);
                
                if (color1>kOrange-8) {
                    waveform->Draw("SAME");
                }else{
                    waveform->Draw("AL");
                    c1[i]->SetGrid();
                }
                clean = false;
            }
            
            // only delayed x-talk
            if (xtalk_pulse > 0 && direct_xtalk_pulse == 0){
                xtalk_pulse_cnt++;
                sprintf(Category,"DelCrosstalk");
                c2[i]->cd();
                
                //Set graph color, and counting to draw axis and title
                color2=color2+2;
                if (color2>kOrange+110) {
                    color2=kOrange-8;
                }else if (color2>kOrange+109){
                    color2=kOrange-7;
                }
                waveform->SetLineColor(color2);
                waveform->SetMarkerColor(color2);
                
                //Format the graph
                sprintf(graph_title,"Delayed cross-talk OV = %2.2f V",V_meas);
                waveform = format_graph(waveform,graph_title,1.2*pe);

                if (color2>kOrange-8) {
                    waveform->Draw("SAME");
                }else{
                    waveform->Draw("AL");
                    c2[i]->SetGrid();
                }
                clean = false;
            }
            
            //  Only after pulse
            if (after_pulse > 0 && xtalk_pulse == 0 && direct_xtalk_pulse == 0){
                after_pulse_cnt++;
                sprintf(Category,"AfterPulse");
                c3[i]->cd();
                
                //Set graph color, and counting to draw axis and title
                color3=color3+2;
                if (color3>kOrange+110) {
                    color3=kOrange-8;
                }else if (color3>kOrange+109){
                    color3=kOrange-7;
                }
                waveform->SetLineColor(color3);
                waveform->SetMarkerColor(color3);
                
                //Format the graph
                sprintf(graph_title,"After pulse OV = %2.2f V",V_meas);
                waveform = format_graph(waveform,graph_title,1.2*pe);
                
                if (color3>kOrange-8) {
                    waveform->Draw("SAME");
                }else{
                    waveform->Draw("AL");
                    c3[i]->SetGrid();
                }
                
                clean = false;
                
                //Fill for the exponential fit
                Expfit_AP[i]->SetPoint(after_pulse_cnt-1,time_of_max,sig_max);
            }
            
            // Only clean graphs for the sample
            if (clean){
                sprintf(Category,"Clean");
                
                if (color4 < 860 && j <100) { //Max 100 clean graphs on the plot
                    Cleanwaves[i]->Add(waveform);
                    c4[i]->cd();
                    
                    //Set graph color, and counting to draw axis and title
                    color4=color4+2;
                    if (color4>kOrange+110) {
                        color4=kOrange-8;
                    }else if (color4>kOrange+109){
                        color4=kOrange-7;
                    }
                    waveform->SetLineColor(color4);
                    waveform->SetMarkerColor(color4);
                    
                    //Format the graph
                    sprintf(graph_title,"Clean pulse OV = %2.2f V",V_meas);
                    waveform = format_graph(waveform,graph_title,1.2*pe);
                    
                    if (color4>kOrange-8) {
                        waveform->Draw("SAME");
                    }else{
                        waveform->Draw("AL");
                        c4[i]->SetGrid();
                    }
                }
                
                
            }
            
            tree->Fill();
            
            Event ++;//Total number of events analyzed on the run
            if (Event%500==0) {
                cout<<"****----->Events analyzed:"<< Event << endl;
            }
            
            event_cnt++;
            
            
        }
        
        cout<<"////////////"<< endl;
        cout<<"****----->Long tau fit ***"<< endl;
        expfit_longtau_c[i]->cd();
        Cleanwaves[i]->Draw("AP*");
        // Fit parameters and limits to calculate slow component of the pulse
        exp_longtau->SetParameter(0,pe*0.2);
        exp_longtau->SetParLimits(0,0.05*pe,0.5*pe);
        exp_longtau->SetParameter(1,80*ns);
        exp_longtau->SetParLimits(1,4*ns,200*ns);
        Cleanwaves[i]->Fit("exptau","","",reject_time_v.at(i)*ns,60*ns); // Fit boundaries for the slow component of the pulse
        Double_t amp0 = exp_longtau->GetParameter(0);
        Double_t tau = exp_longtau->GetParameter(1);
        if (globalArgs.save_all==1) expfit_longtau_c[i]->Write();
        
        c4[i]->cd();
        TF1* exp_tau_plot =(TF1*) exp_longtau->Clone();
        exp_tau_plot->Draw("SAME");//Draw fit-line over clean waveforms
        
        cout<<"////////////"<< endl;
        cout<<"****----->After pulse fit ***"<< endl;
        expfit_AP_c[i]->cd();
        Expfit_AP[i]->Draw("AP*");
        // Fit parameters and limits to calculate AP recharge
        exp->SetParameter(0,pe);
        exp->SetParLimits(0,0.5*pe,1.5*pe);
        exp->SetParameter(1,30*ns);
        exp->SetParLimits(1,4*ns,500*ns);
        exp->SetParameter(2,amp0);
        exp->FixParameter(2,amp0);
        exp->SetParameter(3,tau);
        exp->FixParameter(3,tau);
        Expfit_AP[i]->Fit("exp");
        if (globalArgs.save_all==1) expfit_AP_c[i]->Write();
        
        c3[i]->cd();
        TF1* exp_plot =(TF1*) exp->Clone();
        exp_plot->Draw("SAME"); //Draw fit-line over AP waveforms
        
        
        //Final result: Correlated noise
        Correl_noise[0]->SetPoint(i,V_meas,direct_xtalk_pulse_cnt/event_cnt*100);
        Correl_noise[1]->SetPoint(i,V_meas,after_pulse_cnt/event_cnt*100);
        Correl_noise[2]->SetPoint(i,V_meas,xtalk_pulse_cnt/event_cnt*100);
        Correl_noise[3]->SetPoint(i,V_meas,
                                  Correl_noise[0]->GetY()[i]+Correl_noise[1]->GetY()[i]+Correl_noise[2]->GetY()[i]);
        
        
        //Save/print reults:
        if (globalArgs.save_all==1){
            c1[i]->Write();
            c2[i]->Write();
            c3[i]->Write();
            c4[i]->Write();
        }
        
        sprintf(canvas_title,"%sImmcrosstalk_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data());
        c1[i]->Print(canvas_title,"pdf");
        sprintf(canvas_title,"%sDelcrosstalk_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data());
        c2[i]->Print(canvas_title,"pdf");
        sprintf(canvas_title,"%sAfterpulse_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data());
        c3[i]->Print(canvas_title,"pdf");
        sprintf(canvas_title,"%sClean_%s.pdf",globalArgs.results_folder,vol_folders.at(i).Data());
        c4[i]->Print(canvas_title,"pdf");
        
        
    }
    //Save TTree with hist of noise
    //Save each event with its OV and the noise classification
    tree->Write();
    
    //Create final plot of total correlated noise
    TCanvas* c5 = new TCanvas("Correlated Noise","Correlated Noise",100,100,900,700);
    
    Double_t tot_max_noise = TMath::MaxElement(Correl_noise[3]->GetN(),Correl_noise[3]->GetY());
    
    Correl_noise[3]->SetTitle("Correlated Noise");
    Correl_noise[3]->SetMarkerColor(kRed);
    Correl_noise[3]->SetLineColor(kRed);
    Correl_noise[3]->GetYaxis()->SetRangeUser(0,tot_max_noise+2);
    Correl_noise[3]->GetYaxis()->SetTitle("Noise [%]");
    Correl_noise[3]->GetXaxis()->SetTitle("OverVoltage [V]");
    Correl_noise[3]->Draw("ALP*");
    
    Correl_noise[0]->SetTitle("Direct Cross-Talk");
    Correl_noise[1]->SetTitle("After Pulse");
    Correl_noise[2]->SetTitle("Delayed Cross-Talk");
    Correl_noise[0]->SetLineColor(kBlue);
    Correl_noise[1]->SetLineColor(kOrange+7);
    Correl_noise[2]->SetLineColor(kGreen+2);
    Correl_noise[0]->SetMarkerColor(kBlue);
    Correl_noise[1]->SetMarkerColor(kOrange+7);
    Correl_noise[2]->SetMarkerColor(kGreen+2);
    Correl_noise[0]->Draw("LP*");
    Correl_noise[1]->Draw("LP*");
    Correl_noise[2]->Draw("LP*");
    
    TLegend* leg = new TLegend(0.15,0.65,0.47,0.87);
    leg->AddEntry(Correl_noise[3],"Total","lp");
    leg->AddEntry(Correl_noise[0],"Direct Cross-Talk","lp");
    leg->AddEntry(Correl_noise[1],"After Pulse","lp");
    leg->AddEntry(Correl_noise[2],"Delayed Cross-Talk","lp");
    leg->Draw();
    
    
    c5->SetGrid();
    TString final_plot_name = globalArgs.results_folder;
    final_plot_name.Append("Correlated Noise.pdf");
    c5->Print(final_plot_name,"pdf");
    c5->Write();
    
    delete hfile;
    
    return 0;

}
Beispiel #2
0
void AnalysisSparse(Bool_t save_output = kFALSE)
{
  gStyle->SetGridColor(kGray);
  //  TString tmpstr(fname);
  //  if (tmpstr.Contains("data")) {
  //    Printf("!!! Real Data !!!");
  //    mc = kFALSE;
  //  }
  TString gtitle = Form("Monte Carlo, %s", graph_name.Data());
  grapht = graph_name.Data();
  Double_t grx[999], gry[999], gry2[999], gry3[999], gry4[999],
    gry_eff[999], gry_fix[999], grxE[999];
  Double_t gry22[999], gry22E[999], grx22E[999];
  Double_t gry_true[999], gry_true_eff[999], gry_true_effE[999];
  TH1::AddDirectory(kFALSE);
  TFile::SetCacheFileDir(gSystem->HomeDirectory());
  TFile *f = TFile::Open(fname.Data(), "CACHEREAD");
  if (!f) return;
  TList *l; f->GetObject(lname.Data(), l);
  if (!l) return;
  Int_t bf[999], bl[999];
  Int_t nn = FindExactRange(((THnSparse *)(l->FindObject(s1name.Data())))->
                            Projection(1), del_step, bf, bl);
  //  Int_t nn = FindRange5(bf, bl);
  Bool_t binhaluska = kFALSE;
  if (binAnders) {
    nn = 8;
    bf[0] = 6;bf[1] =  9;bf[2] = 11;bf[3] = 16;bf[4] = 21;bf[5] = 26;
    bl[0] = 8;bl[1] = 10;bl[2] = 15;bl[3] = 20;bl[4] = 25;bl[5] = 30;

    bf[6] = 31;bf[7] = 41;
    bl[6] = 40;bl[7] = 50;
  }
  Printf("number of intervals = %d =>", nn);

  Int_t count = 0;
  Double_t ptmean = 0, value = 0;
  Int_t fitStatus = -1;
  gStyle->SetOptStat(0);
  TCanvas *c = new TCanvas("c", "Signal & Background");
  c->Divide(5, 5); c->Modified(); c->Draw();
  TCanvas *c2 = (TCanvas *)c->DrawClone("c2");
  c2->SetTitle("Phi mesons (raw)"); c2->Modified(); c2->Draw();
  TCanvas *c3, *c4;
  if (mc) {
    c3 = (TCanvas *)c->DrawClone("c3");
    c3->SetTitle("Phi mesons (gen)"); c3->Modified(); c3->Draw();
    c4 = (TCanvas *)c->DrawClone("c4");
    c4->SetTitle("Phi mesons (true)"); c4->Modified(); c4->Draw();
  }

  for (Int_t i = 0; i < nn; i++) {
    c->cd(count + 1)->SetGrid();
    h1 = (TH1D *)PullHisto(l, s1name.Data(), bf[i], bl[i], ptmean);
    h1->SetLineColor(kRed);
    h1->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
    h1->Draw("hist");

    h3_p = (TH1D *)PullHisto(l, s3name_p.Data(), bf[i], bl[i], ptmean);
    h3_m = (TH1D *)PullHisto(l, s3name_m.Data(), bf[i], bl[i], ptmean);
    // !!!!!!!!!!!!!!!!!!!!!!!!
    if (count==0) h3_p = h1;
    // !!!!!!!!!!!!!!!!!!!!!!!!
    else {
      h3_p->Add(h3_m);
      //      h3_p->Add((TH1D *)PullHisto(l, smix.Data(), bf[i], bl[i], ptmean));
      //      h3_p->Add((TH1D *)PullHisto(l, smixpp.Data(), bf[i], bl[i], ptmean));
      //      h3_p->Add((TH1D *)PullHisto(l, smixmm.Data(), bf[i], bl[i], ptmean));
      Norm(h1, h3_p, norm[0], norm[1]);
    }
    h3_p->SetLineColor(kBlue);
    h3_p->Draw("hist, same");

    if (mc) {
      c3->cd(count + 1)->SetGrid();
      Printf("%s", s1namegen.Data());
      hg = (TH1D *)PullHisto(l, s1namegen.Data(), bf[i], bl[i], ptmean);
      hg->SetLineColor(kMagenta);
      hg->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
      hg->Draw("hist");
      c4->cd(count + 1)->SetGrid();
      ht = (TH1D *)PullHisto(l, s1nametrue.Data(), bf[i], bl[i], ptmean);
      ht->SetLineColor(kMagenta-5);
      ht->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
      ht->Draw("hist");
    }
    c2->cd(count + 1)->SetGrid();
    TH1 *hh = (TH1 *)h1->Clone("hh");
    hh->SetLineColor(kRed+1);
    hh->Add(h3_p, -1);
    /// !!!!!!!!!!!!!!!!!!!!!!
    //////////    if ((ilist == 3) && (count < 2)) hh->Reset();
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    hh->Draw("hist");

    // !!!!!!!!!!!!!!!!!!
    ff->SetParameters(0.1, 1.02, 0.004, -25000., 0., 0., 0.);
    ff->SetLineColor(hh->GetLineColor());
    ff->SetLineWidth(1);
    //    ff->SetLineStyle(kDashed);
    // where fit
    Double_t fmin = 1.02-2*0.004;
    Double_t fmax = 1.02+2*0.004;
    //    Double_t fmin = 0.995;
    //    Double_t fmax = 1.185;
    // !!!!!!!!!!!!!!!!!!
    Bool_t hisfun = kFALSE; // kFALSE = integral from function
    Double_t   hisfun_k = 1.0/hh->GetBinWidth(10);
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    if (binhaluska)
      if (i > 9) hisfun_k = 0.5/hh->GetBinWidth(10);
    Printf("======= %f", hisfun_k);
    // !!!!!!!!!!!!!!!!!!
    // wehere integral (his or fun)
    Double_t fmini = 1.02-2*0.004;
    Double_t fmaxi = 1.02+2*0.004;
    hh->Fit(ff, "Q", "", fmin, fmax);
    hh->Fit(ff, "Q", "", fmin, fmax);
    fitStatus = hh->Fit(ff, "Q", "", fmin, fmax);
    TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
    pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
                       ff->GetParameter(5), ff->GetParameter(6));
    pp3->SetLineWidth(1);
    pp3->SetLineColor(h3_p->GetLineColor());
    pp3->Draw("same");
    // ff->SetRange(fmin, fmax);
    // ff->DrawCopy("same");

    value              = hh->Integral(hh->FindBin(fmini), hh->FindBin(fmaxi));
    if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k -
                   pp3->Integral(fmini, fmaxi)*hisfun_k;
    if (value < 0) value = 0;

    if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
      printf(" SKIP Data");
      value = 0;
    }
    grx[count] = ptmean;
    if (binhaluska) {
      if (count < 10) grxE[count] = 0.25; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      else            grxE[count] = 0.50; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    }
    else
      //      grxE[count] = (1.30-1.10)/2.0; // !!!!!!!!!!!!!!!!!!!!!!!!!!
      grxE[count] = 0.05;
    gry[count] = value;

    Double_t tmp1 = h1->Integral(h1->FindBin(fmini), h1->FindBin(fmaxi));
    Double_t tmp2 = h3_p->Integral(h3_p->FindBin(fmini), h3_p->FindBin(fmaxi));
    Double_t tmp_sg = tmp1 - tmp2;
    Double_t tmp_bg = tmp2;

    // if ((tmp_sg <= -tmp_bg) || (tmp_bg < 33.0)) {
    //   gry3[count] = 0.0;
    //   gry4[count] = 0.0;
    // }
    // else {
    gry3[count] = tmp_sg/tmp_bg;
    gry4[count] = tmp_sg/TMath::Sqrt(tmp_sg + tmp_bg);
    // }

    //    Printf("%4.2f, %10f, %10f, %10f", ptmean, tmp1, tmp2, gry3[count]);


    if (mc) {
      c3->cd(count + 1);
      // !!!!!!!!!!!!!!!!
      ff->SetParameters(1, 1.02, 0.004, 0., 0., 0., 0.);
      hg->Fit(ff, "Q", "", fmin, fmax);
      hg->Fit(ff, "Q", "", fmin, fmax);
      fitStatus = hg->Fit(ff, "Q", "", fmin, fmax);
      /*      TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
              pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
              ff->GetParameter(5), ff->GetParameter(6));
              pp3->SetLineWidth(1);
              pp3->SetLineColor(h3_p->GetLineColor());
              pp3->Draw("same");
      */

      value              = hg->Integral(hg->FindBin(fmini), hg->FindBin(fmaxi));
      if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k;
      //!!!!!!!!!!!!!!!!!!!pp3->Integral(fmini, fmaxi)*hisfun_k;
      if (value <= 0) value = -1;

      if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
        printf(" SKIP MC");
        value = -1;
      }
      gry2[count]    = value;
      Double_t superfactor = CalculateFactor(l, 0.1);
      if (useCF) {
        gry22E[i] = TMath::Sqrt(gry2[i])*superfactor;
        //        gry22E[i] = 0.0001;
        gry22[i]  = gry2[i]*superfactor;
        grx22E[i] = 0.05;
      }
      gry_eff[count] = gry[count]/gry2[count];

      c4->cd(count + 1);
      // !!!!!!!!!!!!!!!!
      ff->SetParameters(1, 1.02, 0.004, 0., 0., 0., 0.);
      ht->Fit(ff, "Q", "", fmin, fmax);
      ht->Fit(ff, "Q", "", fmin, fmax);
      fitStatus = ht->Fit(ff, "Q", "", fmin, fmax);
      /*      TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
              pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
              ff->GetParameter(5), ff->GetParameter(6));
              pp3->SetLineWidth(1);
              pp3->SetLineColor(h3_p->GetLineColor());
              pp3->Draw("same");
      */

      value              = ht->Integral(ht->FindBin(fmini), ht->FindBin(fmaxi));
      if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k;
      //!!!!!!!!!!!!!!!!!!!pp3->Integral(fmini, fmaxi)*hisfun_k;
      if (value <= 0) value = -1;

      if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
        printf(" SKIP true");
        value = -1;
      }
      gry_true[count]     = value;
      gry_true_eff[count] = gry_true[count]/gry2[count];
      // Propagation of uncertainty (A/B)
      Double_t AAA  = gry_true[count];
      Double_t AAAE = TMath::Sqrt(AAA);
      Double_t BBB  = gry2[count];
      Double_t BBBE = TMath::Sqrt(BBB);
      Double_t EEE  = TMath::Sqrt((AAAE/AAA)*(AAAE/AAA)+(BBBE/BBB)*(BBBE/BBB));
      EEE = EEE*gry_true_eff[count];
      gry_true_effE[count] = EEE;
    }

    Printf("=> %6.4f", ptmean);
    count++;
  }

  new TCanvas();
  TGraph *gr = new TGraph(count, grx, gry);
  gr->SetMarkerStyle(8);
  gr->SetMarkerColor(hh->GetLineColor());
  gr->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr->SetTitle(Form("raw phi, %s", gtitle.Data()));
  gr->Draw("AP");

  cc3 = new TCanvas();
  TGraph *gr3 = new TGraph(count, grx, gry3);
  gr3->SetMarkerStyle(22);
  gr3->SetMarkerColor(kBlue+1);
  gr3->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr3->SetTitle(Form("SIG / BKG, %s", gtitle.Data()));
  gr3->SetMinimum(0);
  gr3->Draw("AP");

  cc4 = new TCanvas();
  TGraph *gr4 = new TGraph(count, grx, gry4);
  gr4->SetMarkerStyle(23);
  gr4->SetMarkerColor(kBlue-1);
  gr4->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr4->SetTitle(Form("Significance, %s", gtitle.Data()));
  gr4->SetMinimum(0);
  gr4->Draw("AP");

  ccc = new TCanvas("ccc","ccc",0,0,900,300);
  ccc->Divide(2, 1, 0.001, 0.001);
  ccc->cd(1); gr3->Draw("AP");
  ccc->cd(2); gr4->Draw("AP");

  TString blabla = "mc";
  if (!mc) blabla = "data";
  // gr3->SaveAs(Form("SB_%s_%s.C", blabla.Data(), grapht.Data()));
  // gr4->SaveAs(Form("Sig_%s_%s.C", blabla.Data(), grapht.Data()));
  // ccc->SaveAs(Form("%s_%s_2.eps", blabla.Data(), grapht.Data()));
  // c->SaveAs(Form("%s_%s_0.eps", blabla.Data(), grapht.Data()));
  // c2->SaveAs(Form("%s_%s_1.eps", blabla.Data(), grapht.Data()));

  //  cc3->SaveAs(Form("%s_%s_2.eps", blabla.Data(), grapht.Data()));
  //  gr3->SaveAs(Form("sig_bck_%s_%s.C", blabla.Data(), grapht.Data()));

  if (mc) {
    new TCanvas();
    TGraph *gr2 = new TGraph(count, grx, gry2);
    gr2->SetMarkerStyle(8);
    gr2->SetMarkerColor(hg->GetLineColor());
    gr2->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr2->SetTitle(Form("gen phi, %s", gtitle.Data()));
    gr2->Draw("AP");

    new TCanvas();
    TGraphErrors *gr22 = new TGraphErrors(count, grx, gry22, grx22E, gry22E);
    gr22->SetMarkerStyle(8);
    gr22->SetMarkerColor(kCyan);
    gr22->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr22->SetTitle(Form("gen phi, %s", gtitle.Data()));
    gr22->Draw("AP");


    c = new TCanvas();
    c->SetGrid();
    TGraph *gr_e = new TGraph(count, grx, gry_eff);
    gr_e->SetMarkerStyle(22);
    gr_e->SetMarkerColor(kBlack);
    gr_e->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_e->SetTitle(Form("efficiency (raw), %s", grapht.Data()));
    gr_e->Draw("AP");
    Printf("Save as '\033[1meffi_raw_%s\033[0m' file", grapht.Data());
    for (Int_t i = 0; i < gr_e->GetN(); i++)
      Printf("%f %f", gr_e->GetX()[i], gr_e->GetY()[i]);

    cvb = new TCanvas();
    cvb->cd();
    TGraph *gr_true = new TGraph(count, grx, gry_true);
    gr_true->SetMarkerStyle(8);
    gr_true->SetMarkerColor(ht->GetLineColor());
    gr_true->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_true->SetTitle(Form("true phi, %s", gtitle.Data()));
    gr_true->Draw("AP");
    c = new TCanvas();
    c->cd();
    c->SetGrid();
    TGraphErrors *gr_true_eff = new TGraphErrors(count, grx, gry_true_eff,
                                                 grxE, gry_true_effE);
    gr_true_eff->SetMarkerStyle(20);
    //    gr_true_eff->SetMarkerSize(0.75);
    gr_true_eff->SetMarkerColor(kBlack);
    gr_true_eff->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_true_eff->SetTitle(Form("efficiency (true), %s", grapht.Data()));
    gr_true_eff->Draw("AEP");
    m_gr->Add(gr_true_eff);
    Printf("Save as '\033[1meffi_true_%s\033[0m' file", grapht.Data());
    TString tout;
    Double_t oux, ouy, ouxe, ouye;
    for (Int_t i = 0; i < gr_true_eff->GetN(); i++) {
      oux = gr_true_eff->GetX()[i];
      ouy = gr_true_eff->GetY()[i];
      ouy = MinusCheck(ouy);
      ouxe = gr_true_eff->GetErrorX(i);
      ouye = gr_true_eff->GetErrorY(i);
      ouye = NanCheck(ouye);
      Printf("%f %f %f %f", gr_true_eff->GetX()[i], gr_true_eff->GetY()[i],
             gr_true_eff->GetErrorX(i), gr_true_eff->GetErrorY(i));
      if (!save_output) continue;
      gSystem->mkdir(dir_prefix.Data());
      tout = Form("%f %f %f %f", oux, ouy, ouxe, ouye);
      if (i == 0)
        tout = Form("Printf(\"%s\"); > %s/effi_%s", tout.Data(),
                    dir_prefix.Data(), grapht.Data());
      else
        tout = Form("Printf(\"%s\"); >> %s/effi_%s", tout.Data(),
                    dir_prefix.Data(), grapht.Data());
      //      Printf(":::::: %s", tout.Data());
      gROOT->ProcessLine(tout.Data());
    }
    // ------------------
    c = new TCanvas("cfinal", "mc_effi", 1200, 450);
    c->Divide(2, 1, 0.001, 0.001); c->Modified(); c->Draw();
    c->cd(1);
    gr_true->SetMinimum(0);
    gr_true->SetTitle(Form("phi (true & raw), %s", gtitle.Data()));
    gr_true->SetMarkerColor(kGreen+1);
    gr_true->Draw("AP");
    gr->SetMarkerColor(kRed+1);
    gr->Draw("P");
    c->cd(2)->SetGrid();
    gr_true_eff->SetMinimum(0);
    gr_true_eff->SetTitle(Form("efficiency, %s", grapht.Data()));
    gr_true_eff->SetMarkerColor(kGreen+1);
    gr_true_eff->Draw("AP");
    gr_e->SetMarkerColor(kRed+1);
    gr_e->Draw("P");
    //    c->SaveAs(Form("%s_%s.eps", blabla.Data(), grapht.Data()));
    return;
  }

  //  TGraph *geff = new TGraph(Form("effi_raw_%s", grapht.Data()));
  //  TGraph *geff = new TGraph(Form("effi_true_%s", grapht.Data()));
  //  TGraph *geff = new TGraph("effi_true_Phi2010_qualityonly");
  TGraph *geff = new TGraph("effi_true_PhiNsigma_qualityonly");
  if (geff->IsZombie()) return;
  geff->SetMarkerStyle(22);
  geff->SetMarkerColor(kBlack);
  geff->GetXaxis()->SetTitle("p_{t}, GeV/c");
  geff->SetTitle(Form("efficiency, %s", grapht.Data()));
  c = new TCanvas();
  c->SetGrid();
  geff->Draw("AP");
  Double_t tpcsigma = 9999.9;
  if (ilist == 1) tpcsigma = 1.0;
  if (ilist == 2) tpcsigma = 1.5;
  if (ilist == 3) tpcsigma = 2.0;
  if (ilist == 4) tpcsigma = 2.5;
  if (ilist == 5) tpcsigma = 3.0;
  Double_t sss = TMath::Erf(tpcsigma/TMath::Sqrt(2.0));
  if (noSigma) sss = 1.0;
  Printf("sigma = %10f", sss);

  // for (Int_t i = 0; i < count; i++)
  //   geff->GetY()[i] = (sss*sss)/(geff->GetY()[i]);
  // geff->SetMaximum(1.0);
  // geff->Draw("AP");

  for (Int_t i = 0; i < count; i++) {
    Double_t deno = geff->Eval(grx[i])*sss*sss;
    if (deno < 0.00001) deno = 1;
    gry_fix[i] = gry[i]/deno;
  }
  new TCanvas;
  TGraph *gr_fix = new TGraph(count, grx, gry_fix);
  gr_fix->SetMarkerStyle(21);
  gr_fix->SetMarkerColor(hh->GetLineColor());
  gr_fix->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr_fix->SetTitle(Form("corrected phi * #sigma^{2}, %s", gtitle.Data()));
  if (noSigma)
    gr_fix->SetTitle(Form("corrected phi (no #sigma), %s", gtitle.Data()));
  gr_fix->Draw("AP");

  //---------------------
  c = new TCanvas("cfinald", "data_correct", 1200, 450);
  c->Divide(2, 1, 0.001, 0.001); c->Modified(); c->Draw();
  c->cd(1);
  gr->SetMinimum(0);
  gr->SetMarkerColor(kBlack);
  gr->Draw("AP");
  c->cd(2);
  gr_fix->SetMinimum(0);
  gr_fix->SetMarkerColor(kGreen+3);
  gr_fix->Draw("AP");
  TString bla9 = Form("qualityonly_PID2_%s", grapht.Data());
  if (noSigma) bla9 = Form("%s_noSig.C", bla9.Data());
  else         bla9 = Form("%s.C", bla9.Data());
  //  gr_fix->SaveAs(bla9.Data());
  //  TPad *cp = new TPad("cpf", "", 0.45,0.45,0.99,0.92);
  TPad *cp = new TPad("cpf", "", 0.60,0.55,0.99,0.93);
  cp->SetLogy(); cp->Draw(); cp->cd();
  TGraph *cloneg = ((TGraph *)gr_fix->Clone());
  cloneg->SetTitle(); cloneg->SetMarkerSize(0.8);
  cloneg->Draw("AP");
  //  c->SaveAs(Form("%s_%s.eps", blabla.Data(), grapht.Data()));
  f->Close();
}