コード例 #1
0
ファイル: runGridpPb.C プロジェクト: ktf/AliPhysics
bool CreateTrainDir(AliAnalysisAlien *plugin, const TMap &lookup){
        //
        // Make train data dir name and JDL, C and sh file names
        //
        TObjArray infos;
        bool found = FindDataSample(lookup, infos);
        if(!found){
                printf("sample %s not found\n", g_sample.Data());
                return false;
        }
        TString type; GetData(infos, type, 2);

        // check whether the train dir is already provided or needs to be specified
        if(!g_train_dir.Length()){
                // Query number of train runs before
                const char *gridhome = gGrid->GetHomeDirectory();
                const char gridoutdir[256];
                sprintf(gridoutdir, "%sAnalysis_pPb/%s", gridhome, type.Data());
                TGridResult *trainruns = gGrid->Ls(gridoutdir);
                int nruns = trainruns->GetEntries();
                // Get Date and time
                TDatime time;
                g_train_dir = Form("%d_%d%02d%02d_%02d%02d", nruns, time.GetYear(), time.GetMonth(), time.GetDay(), time.GetHour(), time.GetMinute());
        }
        
        plugin->SetGridWorkingDir(Form("Analysis_pPb/%s/%s", type.Data(), g_train_dir.Data()));
        plugin->SetJDLName(Form("TPCTOFanalysispPb_%s_%s.jdl", type.Data(), g_train_dir.Data()));
        plugin->SetExecutable(Form("TPCTOFanalysispPb_%s_%s.sh", type.Data(), g_train_dir.Data()));
        plugin->SetAnalysisMacro(Form("TPCTOFanalysispPb_%s_%s.C", type.Data(), g_train_dir.Data()));
        return true;
}
コード例 #2
0
ファイル: TExpenser.C プロジェクト: libov/expenser
void TExpenser::calculate_balance() {

    fBalanceXMLParser -> selectMainNode();
    fBalanceXMLParser -> selectNode("entry");
    TString balance = fBalanceXMLParser -> getNodeContent("amount");
    fBalanceXMLParser -> selectNode("date");
    TString balance_year = fBalanceXMLParser -> getNodeContent("year");
    TString balance_month = fBalanceXMLParser -> getNodeContent("month");

    fLastStatusLabel -> SetText(balance_month+"/"+balance_year+": " + balance + " eur");

    // now calculate the current balance (last - expenses since the last)
    TDatime time;

    fXMLParser->selectMainNode();
    fXMLParser->selectNode("expense");
    Double_t expenses_since_last_status = 0;
    while (fXMLParser->getCurrentNode() != 0) {
        XMLNodePointer_t current_node = fXMLParser->getCurrentNode();

        fXMLParser -> selectNode("date");
        TString year = fXMLParser -> getNodeContent("year");
        TString month = fXMLParser -> getNodeContent("month");
        fXMLParser -> setCurrentNode(current_node);

        bool year_more_recent = (year.Atoi() > balance_year.Atoi());
        bool year_same = (year.Atoi() == balance_year.Atoi());
        bool month_more_recent = (month.Atoi()>=balance_month.Atoi());
        bool expense_more_recent_than_balance = (year_more_recent || (year_same && month_more_recent));
        if (  expense_more_recent_than_balance && fXMLParser -> getNodeContent("withdrawn") == "Yes" ) {
            expenses_since_last_status += fXMLParser -> getNodeContent("amount").Atof();
        }

        fXMLParser->selectNextNode("expense");
    }

    // calculate total income since last balance
    fIncomeXMLParser->selectMainNode();
    fIncomeXMLParser->selectNode("entry");
    Double_t income_since_last_status = 0;
    while (fIncomeXMLParser->getCurrentNode() != 0) {
        XMLNodePointer_t current_node = fIncomeXMLParser->getCurrentNode();

        fIncomeXMLParser -> selectNode("date");
        TString year = fIncomeXMLParser -> getNodeContent("year");
        TString month = fIncomeXMLParser -> getNodeContent("month");
        fIncomeXMLParser -> setCurrentNode(current_node);

        if ( ( (month.Atoi()>=balance_month.Atoi()) && (year.Atoi()==balance_year.Atoi()) ) || (year.Atoi()>balance_year.Atoi()) ) {
            income_since_last_status += fIncomeXMLParser -> getNodeContent("amount").Atof();
        }

        fIncomeXMLParser->selectNextNode("entry");
    }

    Double_t new_balance = balance.Atof() - expenses_since_last_status + income_since_last_status;
    fCurrentStatusLabel -> SetText(toStr(time.GetDay())+"/"+toStr(time.GetMonth())+"/"+toStr(time.GetYear())+": " + toStr(new_balance,2) + " eur");
}
コード例 #3
0
ファイル: TExpenser.C プロジェクト: libov/expenser
void TExpenser::drawStatisticsMonthTab() {

    fStatisticsTab = fTab->AddTab("Statistics (Month)");
    fStatisticsTab -> SetLayoutManager(new TGHorizontalLayout(fStatisticsTab));

    TRootEmbeddedCanvas * fEcanvas = new TRootEmbeddedCanvas("Ecanvas",fStatisticsTab, CANVAS_WIDTH, CANVAS_HEIGHT);
    fStatisticsTab -> AddFrame(fEcanvas, new TGLayoutHints(kLHintsCenterX, 10,10,10,1));
    fCanvas = fEcanvas->GetCanvas();
    fCategoriesHistogram = new TH1F("fCategoriesHistogram", "Expenses for each category for a given month", NCATEGORIES, 0, NCATEGORIES);
    fCategoriesHistogram -> SetStats(0);

    TGVerticalFrame *vframe = new TGVerticalFrame(fStatisticsTab, 60, 40);
    fStatisticsTab -> AddFrame(vframe, new TGLayoutHints(kLHintsCenterX,2,2,2,2));

    // month selector
    fStatisticsMonth = new TGComboBox(vframe);
    for (unsigned i = 0; i < 12; i++) {
        fStatisticsMonth->AddEntry(MONTHS[i], i+1);
    }
    fStatisticsMonth->Resize(DROPDOWN_MENU_WIDTH, DROPDOWN_MENU_HEIGHT);
    TDatime time;
    fStatisticsMonth->Select(time.GetMonth());
    vframe->AddFrame(fStatisticsMonth, new TGLayoutHints(kLHintsLeft,5,10,5,5));

    // year selector
    fStatisticsYear = new TGComboBox(vframe);
    for (unsigned i = FIRST_YEAR; i <= LAST_YEAR; i++) {
        fStatisticsYear->AddEntry(toStr(i), i+1-FIRST_YEAR);
    }
    fStatisticsYear->Resize(DROPDOWN_MENU_WIDTH, DROPDOWN_MENU_HEIGHT);
    fStatisticsYear->Select(time.GetYear()-FIRST_YEAR+1);
    vframe->AddFrame(fStatisticsYear, new TGLayoutHints(kLHintsLeft,5,10,5,5));

    // update-button
    TGTextButton * update_button = new TGTextButton(vframe,"&Apply");
    update_button -> SetFont("-*-times-bold-r-*-*-28-*-*-*-*-*-*-*");
    update_button -> Connect("Clicked()", "TExpenser", this, "calculate_monthly()");
    vframe -> AddFrame(update_button, new TGLayoutHints(kLHintsLeft,5,5,3,4));

    // monthly sum
    TColor *color = gROOT->GetColor(kBlue);
    TGFont *font = gClient->GetFont("-*-times-bold-r-*-*-22-*-*-*-*-*-*-*");
    fTotalMonthlyExpenses = new TGLabel(vframe, "");
    vframe->AddFrame(fTotalMonthlyExpenses, new TGLayoutHints(kLHintsNormal, 5, 5, 3, 4));
    fTotalMonthlyExpenses->SetTextColor(color);
    fTotalMonthlyExpenses -> SetTextFont(font);

    calculate_monthly();
}
コード例 #4
0
ファイル: checkPullTree.C プロジェクト: ktf/AliPhysics
//_________________________________________________________________________________________
Int_t checkPullTree(TString pathTree,  TString pathNameThetaMap, TString pathNameSigmaMap,
                    TString mapSuffix, const Int_t collType /*0: pp, 1: pPb, 2: PbPb*/, const Bool_t plotPull = kTRUE,
                    const Double_t downScaleFactor = 1,
                    TString pathNameSplinesFile = "", TString prSplinesName = "",
                    TString fileNameTree = "bhess_PIDetaTree.root", TString treeName = "fTree")
{
  const Bool_t isNonPP = collType != 0;
  const Double_t massProton = AliPID::ParticleMass(AliPID::kProton);
  
  Bool_t recalculateExpecteddEdx = pathNameSplinesFile != "";
  
  TFile* f = 0x0;
	
  f = TFile::Open(Form("%s/%s", pathTree.Data(), fileNameTree.Data()));
  if (!f)  {
    std::cout << "Failed to open tree file \"" << Form("%s/%s", pathTree.Data(), fileNameTree.Data()) << "\"!" << std::endl;
    return -1;
  }
      
  // Extract the data Tree
  TTree* tree = dynamic_cast<TTree*>(f->Get(treeName.Data()));
  if (!tree) {
    std::cout << "Failed to load data tree!" << std::endl;
    return -1;
  }
  
  // Extract the splines, if desired
  TSpline3* splPr = 0x0;
  if (recalculateExpecteddEdx) {
    std::cout << "Loading splines to recalculate expected dEdx!" << std::endl << std::endl;
    
    TFile* fSpl = TFile::Open(pathNameSplinesFile.Data());
    if (!fSpl) {
      std::cout << "Failed to open spline file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
      return 0x0;
    }
    
    TObjArray* TPCPIDResponse = (TObjArray*)fSpl->Get("TPCPIDResponse");
    if (!TPCPIDResponse) {
      splPr = (TSpline3*)fSpl->Get(prSplinesName.Data());
      
      // If splines are in file directly, without TPCPIDResponse object, try to load them
      if (!splPr) {
        std::cout << "Failed to load object array from spline file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
        return 0x0;
      }
    }
    else {
      splPr = (TSpline3*)TPCPIDResponse->FindObject(prSplinesName.Data());
      
      if (!splPr) {
        std::cout << "Failed to load splines from file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
        return 0x0;
      }
    }
  }
  else
    std::cout << "Taking dEdxExpected from Tree..." << std::endl << std::endl;

  // Extract the correction maps
  TFile* fMap = TFile::Open(pathNameThetaMap.Data());
  if (!fMap)  {
    std::cout << "Failed to open thetaMap file \"" << pathNameThetaMap.Data() << "\"! Will not additionally correct data...." << std::endl;
  }

  TH2D* hMap = 0x0;
  
  if (fMap) {
    hMap = dynamic_cast<TH2D*>(fMap->Get(Form("hRefined%s", mapSuffix.Data())));
    if (!hMap) {
      std::cout << "Failed to load theta map!" << std::endl;
      return -1;
    }
  }

  TFile* fSigmaMap = TFile::Open(pathNameSigmaMap.Data());
  if (!fSigmaMap)  {
    std::cout << "Failed to open simgaMap file \"" << pathNameSigmaMap.Data() << "\"!" << std::endl;
    return -1;
  }

  TH2D* hThetaMapSigmaPar1 = dynamic_cast<TH2D*>(fSigmaMap->Get("hThetaMapSigmaPar1"));
  if (!hThetaMapSigmaPar1) {
    std::cout << "Failed to load sigma map for par 1!" << std::endl;
    return -1;
  }

  Double_t c0 = -1;
  TNamed* c0Info = dynamic_cast<TNamed*>(fSigmaMap->Get("c0"));
  if (!c0Info) {
    std::cout << "Failed to extract c0 from file with sigma map!" << std::endl;
    return -1;
  }

  TString c0String = c0Info->GetTitle();
  c0 = c0String.Atof();
  printf("Loaded parameter 0 for sigma: %f\n\n", c0);

  if (plotPull)
    std::cout << "Plotting pull..." << std::endl << std::endl;
  else
    std::cout << "Plotting delta'..." << std::endl << std::endl;

  Long64_t nTreeEntries = tree->GetEntriesFast();

  Double_t dEdx = 0.; // Measured dE/dx
  Double_t dEdxExpected = 0.; // Expected dE/dx according to parametrisation
  Double_t tanTheta = 0.; // Tangens of (local) theta at TPC inner wall
  Double_t pTPC = 0.; // Momentum at TPC inner wall
  UShort_t tpcSignalN = 0; // Number of clusters used for dEdx
  UChar_t  pidType = 0;
  Int_t    fMultiplicity = 0;
  //Double_t phiPrime = 0;

  // Only activate the branches of interest to save processing time
  tree->SetBranchStatus("*", 0); // Disable all branches
  tree->SetBranchStatus("pTPC", 1);
  tree->SetBranchStatus("dEdx", 1);
  tree->SetBranchStatus("dEdxExpected", 1);
  tree->SetBranchStatus("tanTheta", 1);
  tree->SetBranchStatus("tpcSignalN", 1);
  tree->SetBranchStatus("pidType", 1);
  //tree->SetBranchStatus("phiPrime", 1);
  if (isNonPP)
    tree->SetBranchStatus("fMultiplicity", 1);

  
  tree->SetBranchAddress("dEdx", &dEdx);
  tree->SetBranchAddress("dEdxExpected", &dEdxExpected);
  tree->SetBranchAddress("tanTheta", &tanTheta);
  tree->SetBranchAddress("tpcSignalN", &tpcSignalN);
  tree->SetBranchAddress("pTPC", &pTPC);
  tree->SetBranchAddress("pidType", &pidType);
  //tree->SetBranchAddress("phiPrime", &phiPrime);
  if (isNonPP)
    tree->SetBranchAddress("fMultiplicity", &fMultiplicity);

  
  // Output file
  TDatime daTime;
  TString savefileName = Form("%s%s_checkPullSigma_%04d_%02d_%02d__%02d_%02d.root", fileNameTree.ReplaceAll(".root", "").Data(),
                              recalculateExpecteddEdx ? "_recalcdEdx" : "",
                              daTime.GetYear(), daTime.GetMonth(), daTime.GetDay(), daTime.GetHour(), daTime.GetMinute());

  TFile* fSave = TFile::Open(Form("%s/%s", pathTree.Data(), savefileName.Data()), "recreate");
  if (!fSave) {
    std::cout << "Failed to open save file \"" << Form("%s/%s", pathTree.Data(), savefileName.Data()) << "\"!" << std::endl;
    return -1;
  }
  
  const Double_t pBoundLow = 0.1;
  const Double_t pBoundUp = 5;

  const Int_t nBins1 = TMath::Ceil(180 / downScaleFactor);
  const Int_t nBins2 = TMath::Ceil(100 / downScaleFactor);
  const Int_t nBins3 = TMath::Ceil(60 / downScaleFactor);
  
  const Int_t nPbinsForMap = nBins1 + nBins2 + nBins3;
  Double_t binsPforMap[nPbinsForMap + 1];
  
  Double_t binWidth1 = (1.0 - pBoundLow) / nBins1;
  Double_t binWidth2 = (2.0 - 1.0 ) / nBins2;
  Double_t binWidth3 = (pBoundUp - 2.0) / nBins3;
  
  for (Int_t i = 0; i < nBins1; i++)  {
    binsPforMap[i] = pBoundLow + i * binWidth1;
  }
  for (Int_t i = nBins1, j = 0; i < nBins1 + nBins2; i++, j++)  {
    binsPforMap[i] = 1.0 + j * binWidth2;
  }
  for (Int_t i = nBins1 + nBins2, j = 0; i < nBins1 + nBins2 + nBins3; i++, j++)  {
    binsPforMap[i] = 2.0 + j * binWidth3;
  }
  binsPforMap[nPbinsForMap] = pBoundUp;

  TH2D* hPull = new TH2D("hPull", "Pull vs. p_{TPC} integrated over tan(#Theta);p_{TPC} (GeV/c);Pull", nPbinsForMap, binsPforMap, 
                         plotPull ? 120 : 240, plotPull ? -6 : -0.6, plotPull ? 6 : 0.6);
  TH2D* hPullAdditionalCorr = (TH2D*)hPull->Clone("hPullAdditionalCorr");
  hPullAdditionalCorr->SetTitle("Pull vs. p_{TPC} integrated over tan(#Theta) with additional dEdx correction w.r.t. tan(#Theta)");
  /*
  const Int_t nThetaHistos = 3;
  TH2D* hPullTheta[nThetaHistos];
  TH2D* hPullAdditionalCorrTheta[nThetaHistos];
  Double_t tThetaLow[nThetaHistos] = { 0.0, 0.4, 0.9 };
  Double_t tThetaHigh[nThetaHistos] = { 0.1, 0.5, 1.0 };
  */
  const Int_t nThetaHistos = 10;
  TH2D* hPullTheta[nThetaHistos];
  TH2D* hPullAdditionalCorrTheta[nThetaHistos];
  Double_t tThetaLow[nThetaHistos] = { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 };
  Double_t tThetaHigh[nThetaHistos] = { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
  

  for (Int_t i = 0; i < nThetaHistos; i++)    {
    hPullTheta[i] = new TH2D(Form("hPullTheta_%d", i),
                             Form("Pull vs. p_{TPC} for %.2f <= |tan(#Theta)| < %.2f;p_{TPC} (GeV/c);Pull", tThetaLow[i], tThetaHigh[i]),
                             nPbinsForMap, binsPforMap, plotPull ? 120 : 240, plotPull ? -6 : -0.6, plotPull ? 6 : 0.6);

    hPullAdditionalCorrTheta[i] =
      new TH2D(Form("hPullAdditionalCorrTheta_%d", i),
               Form("Pull vs. p_{TPC} for %.2f <= |tan(#Theta)| < %.2f with additional dEdx correction w.r.t. tan(#Theta);p_{TPC} (GeV/c);Pull",
                    tThetaLow[i], tThetaHigh[i]),
               nPbinsForMap, binsPforMap, plotPull ? 120 : 240, plotPull ? -6 : -0.6, plotPull ? 6 : 0.6);
  }

  
  
  
  
  
  TF1 corrFuncMult("corrFuncMult", "[0] + [1]*TMath::Max([4], TMath::Min(x, [3])) + [2] * TMath::Power(TMath::Max([4], TMath::Min(x, [3])), 2)",
                   0., 0.2);
  TF1 corrFuncMultTanTheta("corrFuncMultTanTheta", "[0] * (x -[2]) + [1] * (x * x - [2] * [2])", -1.5, 1.5);
  TF1 corrFuncSigmaMult("corrFuncSigmaMul", "TMath::Max(0, [0] + [1]*TMath::Min(x, [3]) + [2] * TMath::Power(TMath::Min(x, [3]), 2))", 0., 0.2);
  
  
  // LHC13b.pass2
  if (isNonPP)
    printf("Using corr Parameters for 13b.pass2\n!");
  
  corrFuncMult.SetParameter(0, -5.906e-06);
  corrFuncMult.SetParameter(1, -5.064e-04);
  corrFuncMult.SetParameter(2, -3.521e-02);
  corrFuncMult.SetParameter(3,  2.469e-02);
  corrFuncMult.SetParameter(4, 0);
  
  corrFuncMultTanTheta.SetParameter(0, -5.32e-06);
  corrFuncMultTanTheta.SetParameter(1,  1.177e-05);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, 0.);
  corrFuncSigmaMult.SetParameter(1, 0.);
  corrFuncSigmaMult.SetParameter(2, 0.);
  corrFuncSigmaMult.SetParameter(3, 0.);
  
  
  /* OK, but PID task was not very satisfying
  corrFuncMult.SetParameter(0, -6.27187e-06);
  corrFuncMult.SetParameter(1, -4.60649e-04);
  corrFuncMult.SetParameter(2, -4.26450e-02);
  corrFuncMult.SetParameter(3, 2.40590e-02);
  corrFuncMult.SetParameter(4, 0);
  
  corrFuncMultTanTheta.SetParameter(0, -5.338e-06);
  corrFuncMultTanTheta.SetParameter(1,  1.220e-05);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, 7.89237e-05);
  corrFuncSigmaMult.SetParameter(1, -1.30662e-02);
  corrFuncSigmaMult.SetParameter(2, 8.91548e-01);
  corrFuncSigmaMult.SetParameter(3, 1.47931e-02);
  */
  
  
  /*
  // LHC11a10a
  if (isNonPP)
    printf("Using corr Parameters for 11a10a\n!");
  
  corrFuncMult.SetParameter(0, 6.90133e-06);
  corrFuncMult.SetParameter(1, -1.22123e-03);
  corrFuncMult.SetParameter(2, 1.80220e-02);
  corrFuncMult.SetParameter(3, 0.1);
  corrFuncMult.SetParameter(4, 6.45306e-03);
  
  corrFuncMultTanTheta.SetParameter(0, -2.85505e-07);
  corrFuncMultTanTheta.SetParameter(1, -1.31911e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -4.29665e-05);
  corrFuncSigmaMult.SetParameter(1, 1.37023e-02);
  corrFuncSigmaMult.SetParameter(2, -6.36337e-01);
  corrFuncSigmaMult.SetParameter(3, 1.13479e-02);
  */
  
  /* OLD without saturation and large error for negative slopes
  corrFuncSigmaMult.SetParameter(0, -4.79684e-05);
  corrFuncSigmaMult.SetParameter(1, 1.49938e-02);
  corrFuncSigmaMult.SetParameter(2, -7.15269e-01);
  corrFuncSigmaMult.SetParameter(3, 1.06855e-02);
  */
  
  /* OLD very good try, but with fewer pBins for the fitting
  corrFuncMult.SetParameter(0, 6.88365e-06);
  corrFuncMult.SetParameter(1, -1.22324e-03);
  corrFuncMult.SetParameter(2, 1.81625e-02);
  corrFuncMult.SetParameter(3, 0.1);
  corrFuncMult.SetParameter(4, 6.36890e-03);
  
  corrFuncMultTanTheta.SetParameter(0, -2.85505e-07);
  corrFuncMultTanTheta.SetParameter(1, -1.31911e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -4.28401e-05);
  corrFuncSigmaMult.SetParameter(1, 1.24812e-02);
  corrFuncSigmaMult.SetParameter(2, -5.28531e-01);
  corrFuncSigmaMult.SetParameter(3, 1.25147e-02);
  */
  /*OLD good try
  corrFuncMult.SetParameter(0, 7.50321e-06);
  corrFuncMult.SetParameter(1, -1.25250e-03);
  corrFuncMult.SetParameter(2, 1.85437e-02);
  corrFuncMult.SetParameter(3, 0.1);
  corrFuncMult.SetParameter(4, 6.21192e-03);
  
  corrFuncMultTanTheta.SetParameter(0, -1.43112e-07);
  corrFuncMultTanTheta.SetParameter(1, -1.53e-06);
  corrFuncMultTanTheta.SetParameter(2, 0.3);
  
  corrFuncSigmaMult.SetParameter(0, -2.54019e-05);
  corrFuncSigmaMult.SetParameter(1, 8.68883e-03);
  corrFuncSigmaMult.SetParameter(2, -3.36176e-01);
  corrFuncSigmaMult.SetParameter(3, 1.29230e-02);
  */
  
  /*
  // LHC10h.pass2
  if (isNonPP)
    printf("Using corr Parameters for 10h.pass2\n!");
  
  corrFuncMult.SetParameter(0, 3.21636e-07);
  corrFuncMult.SetParameter(1, -6.65876e-04);
  corrFuncMult.SetParameter(2, 1.28786e-03);
  corrFuncMult.SetParameter(3, 1.47677e-02);
  corrFuncMult.SetParameter(4, 0.);
  
  corrFuncMultTanTheta.SetParameter(0, 7.23591e-08);
  corrFuncMultTanTheta.SetParameter(1, 2.7469e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -1.22590e-05);
  corrFuncSigmaMult.SetParameter(1, 6.88888e-03);
  corrFuncSigmaMult.SetParameter(2, -3.20788e-01);
  corrFuncSigmaMult.SetParameter(3, 1.07345e-02);
  */
  
  /*OLD bad try
  corrFuncMult.SetParameter(0, 2.71514e-07);
  corrFuncMult.SetParameter(1, -6.92031e-04);
  corrFuncMult.SetParameter(2, 3.56042e-03);
  corrFuncMult.SetParameter(3, 1.47497e-02);
  corrFuncMult.SetParameter(4, 0.);
  
  corrFuncMultTanTheta.SetParameter(0, 8.53204e-08);
  corrFuncMultTanTheta.SetParameter(1, 2.85591e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -6.82477e-06);
  corrFuncSigmaMult.SetParameter(1, 4.97051e-03);
  corrFuncSigmaMult.SetParameter(2, -1.64954e-01);
  corrFuncSigmaMult.SetParameter(3, 9.21061e-03);
  */
  

  //TODO NOW
  TF1* fShapeSmallP = new TF1("fShapeSmallP", "pol5", -0.4, 0.4);
  fShapeSmallP->SetParameters(1.01712, -0.0202725, -0.260692, 0.261623, 0.671854, -1.14014);
    
  for (Long64_t i = 0; i < nTreeEntries; i++) {
    tree->GetEntry(i);

    if (dEdx <= 0 || dEdxExpected <= 0 || tpcSignalN <= 10)
      continue;
    /*
    Double_t pT = pTPC*TMath::Sin(-TMath::ATan(tanTheta)+TMath::Pi()/2.0);
    if ((phiPrime > 0.072/pT+TMath::Pi()/18.0-0.035 && phiPrime < 0.07/pT/pT+0.1/pT+TMath::Pi()/18.0+0.035)) 
      continue;
    */
      
    if (pidType != kMCid) {
      if (pidType == kTPCid && pTPC > 0.6)
        continue;
      if (pidType == kTPCandTOFid && (pTPC < 0.6 || pTPC > 2.0))
        continue;
      if ((collType == 2) && pidType == kTPCandTOFid && pTPC > 1.0)
        continue;// Only V0's in case of PbPb above 1.0 GeV/c
      if (pidType == kV0idPlusTOFrejected) //TODO NOW NEW
        continue;
    }
    
    if (recalculateExpecteddEdx) {
      dEdxExpected = 50. * splPr->Eval(pTPC / massProton); //WARNING: What, if MIP is different from 50.? Seems not to be used (tested for pp, MC_pp, PbPb and MC_PbPb), but can in principle happen
    }
      
    //TODO NOW
    /*
    if (TMath::Abs(tanTheta) <= 0.4) {
      Double_t p0 = fShapeSmallP->Eval(tanTheta) - 1.0; // Strength of the correction
      Double_t p1 = -9.0; // How fast the correction is turned off
      Double_t p2 = -0.209; // Turn off correction around 0.2 GeV/c
      Double_t p3 = 1.0; // Delta' for large p should be 1

      Double_t corrFactor = TMath::Erf((pTPC + p2) * p1) * p0 + p3 + p0; // Add p0 to have 1 for p3 = 1 and large pTPC
      dEdxExpected *= corrFactor;
    }*/
    
     /*TODO old unsuccessful try 
    Double_t thetaGlobalTPC = -TMath::ATan(tanTheta) + TMath::Pi() / 2.;
    Double_t pTtpc = pTPC * TMath::Sin(thetaGlobalTPC);
    Double_t pTtpcInv = (pTtpc > 0) ? 1. / pTtpc : 0;
    Double_t p0 = 1.0;
    Double_t p1 = 1./ 0.5;//TODO 2.0;
    Double_t p2 = -0.2;//TODO 0.1
    Double_t pTcorrFactor = p0 + (pTtpcInv > p1) * p2 * (pTtpcInv - p1);
    
    dEdxExpected *= pTcorrFactor;
    */
    
      
    // From the momentum (via dEdxExpected) and the tanTheta of the track, the expected dEdx can be calculated (correctedDeDxExpected).
    // If the splines are correct, this should give in average the same value as dEdx. 
    // Now valid: Maps created from corrected data with splines adopted to corrected data, so lookup should be for dEdxExpected=dEdxSplines (no further
    // eta correction) or the corrected dEdx from the track (which should ideally be = dEdxSplines)
    
    // Tested with corrected data for LHC10d.pass2: using dEdx for the lookup (which is the corrected value and should ideally be = dEdxSplines):
    // Results almost the same. Maybe slightly better for dEdxExpected.
    
    // No longer valid: Note that the maps take always the uncorrected dEdx w.r.t.
    // tanTheta, so that correctedDeDxExpected is needed here normally. However, the information for the correction will be lost at some point.
    // Therefore, dEdxExpected can be used instead and should provide a good approximation.
    Double_t c1FromSigmaMap = hThetaMapSigmaPar1->GetBinContent(getBinX(hThetaMapSigmaPar1, tanTheta), getBinY(hThetaMapSigmaPar1, 1./dEdxExpected));
    
    Double_t expectedSigma = dEdxExpected * TMath::Sqrt( c0 * c0 + (c1FromSigmaMap * c1FromSigmaMap) / tpcSignalN);
    Double_t pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);

    // Fill pull histo
    hPull->Fill(pTPC, pull);

    Double_t tanThetaAbs = TMath::Abs(tanTheta);
    
    for (Int_t j = 0; j < nThetaHistos; j++)    {
      if (tanThetaAbs  >= tThetaLow[j] && tanThetaAbs < tThetaHigh[j])  {
        hPullTheta[j]->Fill(pTPC, pull);
      }
    }

    if (!hMap)
      continue;

    Double_t correctionFactor = 1.;
    
    if (isNonPP) {
      // 1. Correct eta dependence
      correctionFactor = hMap->GetBinContent(getBinX(hMap, tanTheta), getBinY(hMap, 1./dEdxExpected));
      
      // 2. Correct for multiplicity dependence:
      Double_t multCorrectionFactor = 1.;
      
      if (fMultiplicity > 0) {
        Double_t relSlope = corrFuncMult.Eval(1. / (dEdxExpected * correctionFactor));
        relSlope += corrFuncMultTanTheta.Eval(tanTheta);

        multCorrectionFactor = 1. + relSlope * fMultiplicity;
      }

      c1FromSigmaMap = hThetaMapSigmaPar1->GetBinContent(getBinX(hThetaMapSigmaPar1, tanTheta), getBinY(hThetaMapSigmaPar1, 1./dEdxExpected));
      
      // Multiplicity dependence of sigma depends on the real dEdx at zero multiplicity, i.e. the eta (only) corrected dEdxExpected value has to be used
      // since all maps etc. have been created for ~zero multiplicity
      Double_t relSigmaSlope = corrFuncSigmaMult.Eval(1. / (dEdxExpected * correctionFactor));
      Double_t multSigmaCorrectionFactor = 1. + relSigmaSlope * fMultiplicity;
      
      dEdxExpected *= correctionFactor * multCorrectionFactor; 
      
      expectedSigma = dEdxExpected * TMath::Sqrt( c0 * c0 + (c1FromSigmaMap * c1FromSigmaMap) / tpcSignalN);
      expectedSigma *= multSigmaCorrectionFactor;
      
      pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);
    }
    else {
      correctionFactor = hMap->GetBinContent(getBinX(hMap, tanTheta), getBinY(hMap, 1./dEdxExpected));
      
      c1FromSigmaMap = hThetaMapSigmaPar1->GetBinContent(getBinX(hThetaMapSigmaPar1, tanTheta), getBinY(hThetaMapSigmaPar1, 1./dEdxExpected));
   
      dEdxExpected *= correctionFactor; // If data is not corrected, but the sigma map is for corrected data, re-do analysis with corrected dEdx
      
      expectedSigma = dEdxExpected * TMath::Sqrt( c0 * c0 + (c1FromSigmaMap * c1FromSigmaMap) / tpcSignalN);
      pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);
    }

    pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);

    hPullAdditionalCorr->Fill(pTPC, pull);

    for (Int_t j = 0; j < nThetaHistos; j++)    {
      if (tanThetaAbs  >= tThetaLow[j] && tanThetaAbs < tThetaHigh[j])  {
        hPullAdditionalCorrTheta[j]->Fill(pTPC, pull);
      }
    }
  }
/*
  // Mean, Sigma, chi^2/NDF of pull of different theta bins and all in one plot
  TCanvas* canvPullMean = new TCanvas("canvPullMean", "canvPullMean", 100,10,1380,800);
  canvPullMean->SetLogx(kTRUE);
  canvPullMean->SetGridx(kTRUE);
  canvPullMean->SetGridy(kTRUE);
  TCanvas* canvPullSigma = new TCanvas("canvPullSigma", "canvPullSigma", 100,10,1380,800);
  canvPullSigma->SetLogx(kTRUE);
  canvPullSigma->SetGridx(kTRUE);
  canvPullSigma->SetGridy(kTRUE);
  TCanvas* canvPullChi2 = new TCanvas("canvPullChi2", "canvPullChi2", 100,10,1380,800);
  canvPullChi2->SetLogx(kTRUE);
  canvPullChi2->SetGridx(kTRUE);
  canvPullChi2->SetGridy(kTRUE);
  

  TCanvas* canvPull[nThetaHistos + 1];
  for (Int_t i = 0, j = nThetaHistos; i < nThetaHistos + 1; i++, j--)  {
    canvPull[i] = new TCanvas(Form("canvPull_%d", i), "canvPull", 100,10,1380,800);
    canvPull[i]->cd();
    canvPull[i]->SetLogx(kTRUE);
    canvPull[i]->SetLogz(kTRUE);
    canvPull[i]->SetGrid(kTRUE, kTRUE);

    TH2D* hTemp = 0x0;
    TString thetaString = "";
    if (i == nThetaHistos)  {
      hTemp = hPull;
      thetaString = "tan(#Theta) integrated";
    }
    else {
      hTemp = hPullTheta[i];
      thetaString = Form("%.2f #leq |tan(#Theta)| < %.2f", tThetaLow[i], tThetaHigh[i]);
    }
    
    normaliseHisto(hTemp);
    hTemp->FitSlicesY();
    hTemp->GetYaxis()->SetNdivisions(12);
    hTemp->GetXaxis()->SetMoreLogLabels(kTRUE);
    TH1D* hTempMean = (TH1D*)gDirectory->Get(Form("%s_1", hTemp->GetName()));
    hTempMean->SetTitle(Form("mean(pull), %s", thetaString.Data()));
    hTempMean->GetXaxis()->SetMoreLogLabels(kTRUE);
    hTempMean->SetLineWidth(2);
    hTempMean->SetMarkerStyle(20);
    TH1D* hTempSigma = (TH1D*)gDirectory->Get(Form("%s_2", hTemp->GetName()));
    hTempSigma->SetTitle(Form("#sigma(pull), %s", thetaString.Data()));
    hTempSigma->GetXaxis()->SetMoreLogLabels(kTRUE);
    hTempSigma->SetLineColor(kMagenta);
    hTempSigma->SetMarkerStyle(20);
    hTempSigma->SetMarkerColor(kMagenta);
    hTempSigma->SetLineWidth(2);
    TH1D* hTempChi2 = (TH1D*)gDirectory->Get(Form("%s_chi2", hTemp->GetName()));
    hTempChi2->SetTitle(Form("#chi^{2} / NDF (pull), %s", thetaString.Data()));
    hTempChi2->GetXaxis()->SetMoreLogLabels(kTRUE);
    hTempChi2->SetLineColor(kMagenta + 2);
    hTempChi2->SetMarkerStyle(20);
    hTempChi2->SetMarkerColor(kMagenta + 2);
    hTempChi2->SetLineWidth(2);

    hTemp->DrawCopy("colz");
    hTempMean->DrawCopy("same");
    hTempSigma->DrawCopy("same");
    hTempChi2->Scale(-1./10.);
    hTempChi2->DrawCopy("same");
    hTempChi2->Scale(-10.);

    canvPullMean->cd();
    hTempMean->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempMean->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempMean->DrawCopy((i == 0 ? "" : "same"));

    canvPullSigma->cd();
    hTempSigma->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempSigma->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempSigma->DrawCopy((i == 0 ? "" : "same"));

    canvPullChi2->cd();
    hTempChi2->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempChi2->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempChi2->DrawCopy((i == 0 ? "" : "same"));
  }

  canvPullMean->BuildLegend();
  canvPullSigma->BuildLegend();
  canvPullChi2->BuildLegend();
*/
  // Histograms with additional correction
  TCanvas* canvPullMeanCorr = 0x0;
  TCanvas* canvPullSigmaCorr = 0x0;
  TCanvas* canvPullChi2Corr = 0x0;
  TCanvas* canvPullCorr[nThetaHistos + 1];
  for (Int_t i = 0; i < nThetaHistos + 1; i++) 
    canvPullCorr[i] = 0x0;
  
  if (hMap) {
    // Mean, Sigma, chi^2/NDF of pull of different theta bins and all in one plot
    canvPullMeanCorr = new TCanvas("canvPullMeanCorr", "canvPullMeanCorr", 100,10,1380,800);
    canvPullMeanCorr->SetLogx(kTRUE);
    canvPullMeanCorr->SetGridx(kTRUE);
    canvPullMeanCorr->SetGridy(kTRUE);
    canvPullSigmaCorr = new TCanvas("canvPullSigmaCorr", "canvPullSigmaCorr", 100,10,1380,800);
    canvPullSigmaCorr->SetLogx(kTRUE);
    canvPullSigmaCorr->SetGridx(kTRUE);
    canvPullSigmaCorr->SetGridy(kTRUE);
    canvPullChi2Corr = new TCanvas("canvPullChi2Corr", "canvPullChi2Corr", 100,10,1380,800);
    canvPullChi2Corr->SetLogx(kTRUE);
    canvPullChi2Corr->SetGridx(kTRUE);
    canvPullChi2Corr->SetGridy(kTRUE);
    
    for (Int_t i = 0, j = nThetaHistos; i < nThetaHistos + 1; i++, j--)  {
      canvPullCorr[i] = new TCanvas(Form("canvPullCorr_%d", i), "canvPullCorr", 100,10,1380,800);
      canvPullCorr[i]->cd();
      canvPullCorr[i]->SetLogx(kTRUE);
      canvPullCorr[i]->SetLogz(kTRUE);
      canvPullCorr[i]->SetGrid(kTRUE, kTRUE);

      TH2D* hTemp = 0x0;
      TString thetaString = "";
      
      if (i == nThetaHistos)  {
        hTemp = hPullAdditionalCorr;
        thetaString = "tan(#Theta) integrated";
      }
      else    {
        hTemp = hPullAdditionalCorrTheta[i];
        thetaString = Form("%.2f #leq |tan(#Theta)| < %.2f", tThetaLow[i], tThetaHigh[i]);
      }

      normaliseHisto(hTemp);
      hTemp->FitSlicesY();
      hTemp->GetYaxis()->SetNdivisions(12);
      hTemp->GetXaxis()->SetMoreLogLabels(kTRUE);
      TH1D* hTempMean = (TH1D*)gDirectory->Get(Form("%s_1", hTemp->GetName()));
      hTempMean->SetTitle(Form("mean(pull), %s", thetaString.Data()));
      hTempMean->GetXaxis()->SetMoreLogLabels(kTRUE);
      hTempMean->SetLineWidth(2);
      hTempMean->SetMarkerStyle(20);
      TH1D* hTempSigma = (TH1D*)gDirectory->Get(Form("%s_2", hTemp->GetName()));
      hTempSigma->SetTitle(Form("#sigma(pull), %s", thetaString.Data()));
      hTempSigma->GetXaxis()->SetMoreLogLabels(kTRUE);
      hTempSigma->SetLineColor(kMagenta);
      hTempSigma->SetMarkerStyle(20);
      hTempSigma->SetMarkerColor(kMagenta);
      hTempSigma->SetLineWidth(2);
      TH1D* hTempChi2 = (TH1D*)gDirectory->Get(Form("%s_chi2", hTemp->GetName()));
      hTempChi2->SetTitle(Form("#chi^{2} / NDF (pull), %s", thetaString.Data()));
      hTempChi2->GetXaxis()->SetMoreLogLabels(kTRUE);
      hTempChi2->SetLineColor(kMagenta + 2);
      hTempChi2->SetMarkerStyle(20);
      hTempChi2->SetMarkerColor(kMagenta + 2);
      hTempChi2->SetLineWidth(2);

      hTemp->DrawCopy("colz");
      hTempMean->DrawCopy("same");
      hTempSigma->DrawCopy("same");
      hTempChi2->Scale(-1./10.);
      hTempChi2->DrawCopy("same");
      hTempChi2->Scale(-10.);
  
      canvPullMeanCorr->cd();
      hTempMean->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempMean->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempMean->DrawCopy((i == 0 ? "" : "same"));
      
      canvPullSigmaCorr->cd();
      hTempSigma->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempSigma->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempSigma->DrawCopy((i == 0 ? "" : "same"));
      
      canvPullChi2Corr->cd();
      hTempChi2->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempChi2->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempChi2->DrawCopy((i == 0 ? "" : "same"));
    }
    
    canvPullMeanCorr->BuildLegend();
    canvPullSigmaCorr->BuildLegend();
    canvPullChi2Corr->BuildLegend();
  }
  
  
  
  
  
  fSave->cd();
  /*canvPullMean->Write();
  canvPullSigma->Write();
  canvPullChi2->Write();
  
  for (Int_t  i = 0; i < nThetaHistos + 1; i++) {
    canvPull[i]->Write();
  }*/
  
  canvPullMeanCorr->Write();
  canvPullSigmaCorr->Write();
  canvPullChi2Corr->Write();
  
  for (Int_t  i = 0; i < nThetaHistos + 1; i++) {
    canvPullCorr[i]->Write();
  }

  TNamed* info = new TNamed(Form("Theta map: %s\n\nSigma map: %s\n\nSplines file: %s\n\nSplines name: %s", pathNameThetaMap.Data(), 
                                 pathNameSigmaMap.Data(), pathNameSplinesFile.Data(), prSplinesName.Data()),
                            "info");
  info->Write();
  fSave->Close();
  
  return 0;
}
コード例 #5
0
ファイル: AverageDmesonRaa.C プロジェクト: ktf/AliPhysics
//____________________________________________________________
void AverageDmesonRaa( const char* fD0Raa="",    const char* fD0ppRef="",
                      const char* fDplusRaa="", const char* fDplusppRef="",
                      const char* fDstarRaa="", const char* fDstarppRef="",
                      const char* outfile="", Int_t averageOption=kRelativeStatUnc, Int_t cc=kpPb0100, Int_t ccestimator=kV0M,
                      Bool_t isReadAllPPUnc=false, Bool_t isPPRefExtrapD0=false, Bool_t isPPRefExtrapDplus=false, Bool_t isPPRefExtrapDstar=false)
{
    
    FILE *resultFile;
    TString foutname = "Average";
    if(fD0Raa) foutname += "Dzero";
    if(fDplusRaa) foutname += "Dplus";
    if(fDstarRaa) foutname += "Dstar";
    if(averageOption==kRelativeStatUnc)  foutname+= "_RelStatUncWeight";
    else if(averageOption==kAbsoluteStatUnc)  foutname+= "_AbsStatUncWeight";
    else if(averageOption==kRelativeStatUncorrWoPidSyst) foutname+= "_RelStatUncorrWeight";
    else if(averageOption==kRelativeStatRawYieldSyst) foutname+= "_RelStatRawYieldSystWeight";
    if(!useExtrapPPref) foutname+= "_NoExtrapBins";
    TDatime d;
    TString ndate = Form("%02d%02d%04d",d.GetDay(),d.GetMonth(),d.GetYear());
    resultFile = fopen( Form("%s_result_%s.txt",foutname.Data(),ndate.Data()),"w");
    fprintf(resultFile,"Ptmin (GeV/c)   Ptmax (GeV/c)   Raa(Daverage)   +-(stat)    +(syst)  - (syst) \n\n");
    
    
    // Define here all needed histograms/graphs to be retrieved
    TH1D *hDmesonRaa[3];
    TH1I *hCombinedReferenceFlag[3];
    TGraphAsymmErrors *gDataSystematicsPP[3], *gDataSystematicsAB[3];
    TGraphAsymmErrors *gScalingUncPP[3];
    TGraphAsymmErrors *gRABFeedDownSystematicsElossHypothesis[3];
    TGraphAsymmErrors *gRAB_GlobalSystematics[3];
    TH1D *hDmesonPPRef[3], *hDmesonPPYieldExtrUnc[3], *hDmesonPPCutVarUnc[3], *hDmesonPPIDPUnc[3], *hDmesonPPMCPtUnc[3];
    
    // Define here all output histograms/graphs
    TH1D *hDmesonAverageRAB = new TH1D("hDmesonAverageRAB","D meson average Raa ; p_{T} (GeV/c)",nbins,ptbinlimits);
    TGraphAsymmErrors *gRABNorm;
    TGraphAsymmErrors *gRAB_DmesonAverage_GlobalSystematics = new TGraphAsymmErrors(0);
    TGraphAsymmErrors *gRAB_DmesonAverage_FeedDownSystematicsElossHypothesis = new TGraphAsymmErrors(0);
    TGraphAsymmErrors *gRAB_DmesonAverage_ScalingSystematicsPP = new TGraphAsymmErrors(0);
    TGraphAsymmErrors *gRAB_DmesonAverage_DataSystematicsPP = new TGraphAsymmErrors(0);
    TGraphAsymmErrors *gRAB_DmesonAverage_DataSystematicsAB = new TGraphAsymmErrors(0);
    TGraphAsymmErrors *gRAB_DmesonAverage_TrackingSystematicsPP = new TGraphAsymmErrors(0);
    TGraphAsymmErrors *gRAB_DmesonAverage_TrackingSystematicsAB = new TGraphAsymmErrors(0);
    gRAB_DmesonAverage_GlobalSystematics->SetNameTitle("gRAB_DmesonAverage_GlobalSystematics","DmesonAverage GlobalSystematics");
    gRAB_DmesonAverage_FeedDownSystematicsElossHypothesis->SetNameTitle("gRAB_DmesonAverage_FeedDownSystematicsElossHypothesis","DmesonAverage FeedDownSystematicsElossHypothesis");
    gRAB_DmesonAverage_ScalingSystematicsPP->SetNameTitle("gRAB_DmesonAverage_ScalingSystematicsPP","DmesonAverage Scaling uncertainty PP");
    gRAB_DmesonAverage_DataSystematicsPP->SetNameTitle("gRAB_DmesonAverage_DataSystematicsPP","DmesonRaaAverage DataSystematicsPP - tracking uncertainty PP");
    gRAB_DmesonAverage_DataSystematicsAB->SetNameTitle("gRAB_DmesonAverage_DataSystematicsAB","DmesonRaaAverage DataSystematicsAB - tracking uncertainty AB");
    gRAB_DmesonAverage_TrackingSystematicsPP->SetNameTitle("gRAB_DmesonAverage_TrackingSystematicsPP","DmesonRaaAverage tracking uncertainty PP");
    gRAB_DmesonAverage_TrackingSystematicsAB->SetNameTitle("gRAB_DmesonAverage_TrackingSystematicsAB","DmesonRaaAverage tracking uncertainty AB");
    
    
    const char *filenamesRaa[3] = { fD0Raa, fDplusRaa, fDstarRaa };
    const char *filenamesReference[3] = { fD0ppRef, fDplusppRef, fDstarppRef };
    const char *filenamesSuffixes[3] = { "Dzero", "Dplus", "Dstar" };
    Bool_t isDmeson[3] = { true, true, true };
    
    if(strcmp(filenamesRaa[0],"")==0) { cout<<" Dzero not set, error"<<endl; return; }
    
    //
    // Get Raa file histos and graphs
    //
    AliHFSystErr *ppSyst[3];
    AliHFSystErr *ABSyst[3];
    Double_t ppTracking[3][nbins], ppSystRawYield[3][nbins], ppSystCutVar[3][nbins], ppSystPid[3][nbins];
    Double_t ABTracking[3][nbins], ABSystRawYield[3][nbins], ABSystCutVar[3][nbins], ABSystPid[3][nbins];
    for(Int_t j=0; j<3; j++) {
        if(strcmp(filenamesRaa[j],"")==0)  { isDmeson[j]=false; continue; }
        cout<<" Reading file "<<filenamesRaa[j]<<"..."<<endl;
        TFile *fDRaa = TFile::Open(filenamesRaa[j],"read");
        if(!fDRaa){ cout<<" Error on file !!!!!"<<filenamesRaa[j]<<endl; return; }
        hDmesonRaa[j] = (TH1D*)fDRaa->Get("hRABvsPt");
        hDmesonRaa[j]->SetName(Form("%s_%s",hDmesonRaa[j]->GetName(),filenamesSuffixes[j]));
        
        //    cout<< hDmesonRaa[j]<< " bins="<< hDmesonRaa[j]->GetNbinsX()<<", value bin 1 ="<<hDmesonRaa[j]->GetBinContent(1)<<endl;
        
        if(j==0) gRABNorm = (TGraphAsymmErrors*)fDRaa->Get("gRAB_Norm");
        //
        gDataSystematicsPP[j] = (TGraphAsymmErrors*)fDRaa->Get("gRAB_DataSystematicsPP");
        gDataSystematicsPP[j]->SetName(Form("%s_%s",gDataSystematicsPP[j]->GetName(),filenamesSuffixes[j]));
        gDataSystematicsAB[j] = (TGraphAsymmErrors*)fDRaa->Get("gRAB_DataSystematicsAB");
        gDataSystematicsAB[j]->SetName(Form("%s_%s",gDataSystematicsAB[j]->GetName(),filenamesSuffixes[j]));
        gRABFeedDownSystematicsElossHypothesis[j] = (TGraphAsymmErrors*)fDRaa->Get("gRAB_FeedDownSystematicsElossHypothesis");
        gRABFeedDownSystematicsElossHypothesis[j]->SetName(Form("%s_%s",gRABFeedDownSystematicsElossHypothesis[j]->GetName(),filenamesSuffixes[j]));
        gRAB_GlobalSystematics[j] = (TGraphAsymmErrors*)fDRaa->Get("gRAB_GlobalSystematics");
        gRAB_GlobalSystematics[j]->SetName(Form("%s_%s",gRAB_GlobalSystematics[j]->GetName(),filenamesSuffixes[j]));
	Bool_t shouldDelete=kFALSE;
	if(fDRaa->Get("AliHFSystErrPP")){
	  ppSyst[j]=(AliHFSystErr*)fDRaa->Get("AliHFSystErrPP");
	  printf("AliHFSystErr object for meson %d in pp (%s) read from HFPtSpectrumRaa output file\n",j,ppSyst[j]->GetTitle());
	}else{   
	  printf("Create instance of AliHFSystErr for meson %d in pp \n",j);
	  ppSyst[j] = new AliHFSystErr(Form("ppSyst_%d",j),Form("ppSyst_%d",j));
	  ppSyst[j]->SetIsPass4Analysis(kTRUE);
	  ppSyst[j]->Init(j+1);
	  shouldDelete=kTRUE;
	}
        for(Int_t ipt=0; ipt<nbins; ipt++) {
	  Double_t ptval = ptbinlimits[ipt] + (ptbinlimits[ipt+1]-ptbinlimits[ipt])/2.;
	  ppTracking[j][ipt]=0.; ppSystRawYield[j][ipt]=0; ppSystCutVar[j][ipt]=0; ppSystPid[j][ipt]=0.;
	  ppTracking[j][ipt]    =ppSyst[j]->GetTrackingEffErr(ptval);
	  ppSystRawYield[j][ipt]=ppSyst[j]->GetRawYieldErr(ptval);
	  ppSystCutVar[j][ipt]  =ppSyst[j]->GetCutsEffErr(ptval);
	  ppSystPid[j][ipt]     =ppSyst[j]->GetPIDEffErr(ptval);
        }
	if(shouldDelete)  delete ppSyst[j];
	shouldDelete=kFALSE;
	if(fDRaa->Get("AliHFSystErrAA")){
	  ABSyst[j]=(AliHFSystErr*)fDRaa->Get("AliHFSystErrAA");
	  printf("AliHFSystErr object for meson %d in AA (%s) read from HFPtSpectrumRaa output file\n",j,ppSyst[j]->GetTitle());
	}else{
	  printf("Create instance of AliHFSystErr for meson %d in AA \n",j);
	  ABSyst[j] = new AliHFSystErr(Form("ABSyst_%d",j),Form("ABSyst_%d",j));
	  ABSyst[j]->SetCollisionType(1); // PbPb by default
	  if ( cc == k010 ) ABSyst[j]->SetCentrality("010");
	  else if ( cc == k1020 ) ABSyst[j]->SetCentrality("1020");
	  else if ( cc == k2040 || cc == k2030 || cc == k3040 ) {
            ABSyst[j]->SetCentrality("2040");
            ABSyst[j]->SetIsPbPb2010EnergyScan(true);
	  }
	  else if ( cc == k3050 ) ABSyst[j]->SetCentrality("3050");
	  else if ( cc == k4060 || cc == k4050 || cc == k5060 ) ABSyst[j]->SetCentrality("4060");
	  else if ( cc == k6080 || cc == k5080 ) ABSyst[j]->SetCentrality("6080");
	  else if ( cc == k4080 ) ABSyst[j]->SetCentrality("4080");
	  // Going to pPb systematics
	  else if ( cc == kpPb0100 || cc == kpPb020 || cc == kpPb2040 || cc == kpPb4060 || cc == kpPb60100 ) {
            ABSyst[j]->SetCollisionType(2);
            ABSyst[j]->SetRunNumber(16);
	    if(ccestimator==kV0A) {
	      if(cc == kpPb020) ABSyst[j]->SetCentrality("020V0A");
	      else if(cc == kpPb2040) ABSyst[j]->SetCentrality("2040V0A");
	      else if(cc == kpPb4060) ABSyst[j]->SetCentrality("4060V0A");
	      else if(cc == kpPb60100) ABSyst[j]->SetCentrality("60100V0A");
            } else if (ccestimator==kZNA) {
	      if(cc == kpPb020) ABSyst[j]->SetCentrality("020ZNA");
	      else if(cc == kpPb2040) ABSyst[j]->SetCentrality("2040ZNA");
	      else if(cc == kpPb4060) ABSyst[j]->SetCentrality("4060ZNA");
	      else if(cc == kpPb60100) ABSyst[j]->SetCentrality("60100ZNA");
            } else if (ccestimator==kCL1) {
	      if(cc == kpPb020) ABSyst[j]->SetCentrality("020CL1");
	      else if(cc == kpPb2040) ABSyst[j]->SetCentrality("2040CL1");
	      else if(cc == kpPb4060) ABSyst[j]->SetCentrality("4060CL1");
	      else if(cc == kpPb60100) ABSyst[j]->SetCentrality("60100CL1");
            } else {
	      if(!(cc == kpPb0100)) {
		cout <<" Error on the pPb options"<<endl;
		return;
	      }
            }
	  }
	  ABSyst[j]->Init(j+1);
 	  shouldDelete=kTRUE;
	}
	for(Int_t ipt=0; ipt<nbins; ipt++) {
	  Double_t ptval = ptbinlimits[ipt] + (ptbinlimits[ipt+1]-ptbinlimits[ipt])/2.;
	  ABTracking[j][ipt]=0.; ABSystRawYield[j][ipt]=0; ABSystCutVar[j][ipt]=0; ABSystPid[j][ipt]=0.;
	  ABTracking[j][ipt]    =ABSyst[j]->GetTrackingEffErr(ptval);
	  ABSystRawYield[j][ipt]=ABSyst[j]->GetRawYieldErr(ptval);
	  ABSystCutVar[j][ipt]  =ABSyst[j]->GetCutsEffErr(ptval);
	  ABSystPid[j][ipt]     =ABSyst[j]->GetPIDEffErr(ptval);
        }
        if(shouldDelete)  delete ABSyst[j];    
    }

    //
    // Get pp-reference file histos and graphs
    //
    const char *pprefhgnames[6] = { "fhScaledData","gScaledDataSystExtrap",
        "fhScaledSystRebinYieldExtraction","fhScaledSystRebinCutVariation","fhScaledSystRebinPIDUnc","fhScaledSystRebinMCPt"};
    Bool_t isPPRefExtrap[3] = { isPPRefExtrapD0, isPPRefExtrapDplus, isPPRefExtrapDstar };
    for(Int_t j=0; j<3; j++) {
        if(strcmp(filenamesReference[j],"")==0)  { isDmeson[j]=false; continue; }
        cout<<" Reading file "<<filenamesReference[j]<<"..."<<endl;
        TFile *fRef = TFile::Open(filenamesReference[j],"read");
        gScalingUncPP[j] = (TGraphAsymmErrors*)fRef->Get(pprefhgnames[1]);
        gScalingUncPP[j]->SetName(Form("%s_%s",gScalingUncPP[j]->GetName(),filenamesSuffixes[j]));
        if(isPPRefExtrap[j]) {
            hCombinedReferenceFlag[j] = (TH1I*)fRef->Get("hCombinedReferenceFlag");
            hCombinedReferenceFlag[j]->SetName(Form("%s_%s",hCombinedReferenceFlag[j]->GetName(),filenamesSuffixes[j]));
        }
        if(isReadAllPPUnc){
            const char*hname="fhScaledData";
            if(isPPRefExtrap[j]) hname="hReference";
            hDmesonPPRef[j] = (TH1D*)fRef->Get(hname);
            hDmesonPPRef[j]->SetName(Form("%s_%s",hDmesonPPRef[j]->GetName(),filenamesSuffixes[j]));
            hDmesonPPYieldExtrUnc[j] = (TH1D*)fRef->Get(pprefhgnames[2]);
            hDmesonPPYieldExtrUnc[j]->SetName(Form("%s_%s",hDmesonPPYieldExtrUnc[j]->GetName(),filenamesSuffixes[j]));
            hDmesonPPCutVarUnc[j] = (TH1D*)fRef->Get(pprefhgnames[3]);
            hDmesonPPCutVarUnc[j]->SetName(Form("%s_%s",hDmesonPPCutVarUnc[j]->GetName(),filenamesSuffixes[j]));
            hDmesonPPIDPUnc[j] = (TH1D*)fRef->Get(pprefhgnames[4]);
            hDmesonPPIDPUnc[j]->SetName(Form("%s_%s",hDmesonPPIDPUnc[j]->GetName(),filenamesSuffixes[j]));
            hDmesonPPMCPtUnc[j] = (TH1D*)fRef->Get(pprefhgnames[5]);
            hDmesonPPMCPtUnc[j]->SetName(Form("%s_%s",hDmesonPPMCPtUnc[j]->GetName(),filenamesSuffixes[j]));
        }
    }
    
    
    //
    // Loop per pt bin
    //
    for(Int_t ipt=0; ipt<nbins; ipt++) {
        
        cout<<" Calculation for pt bin ("<<ptbinlimits[ipt]<<","<<ptbinlimits[ipt+1]<<")"<<endl;
        
        Double_t ptval = ptbinlimits[ipt] + (ptbinlimits[ipt+1]-ptbinlimits[ipt])/2.;
        Double_t RaaDmeson[3]={0.,0.,0.};
        Double_t RaaDmesonStat[3]={0.,0.,0.};
        Double_t RaaDmesonSystLow[3]={0.,0.,0.};
        Double_t RaaDmesonSystHigh[3]={0.,0.,0.};
        Double_t weight[3]={0.,0.,0.};
        Double_t ppSystLow[3]={0.,0.,0.};
        Double_t ppSystHigh[3]={0.,0.,0.};
        Double_t ppSystUncorrLow[3]={0.,0.,0.};
        Double_t ppSystUncorrHigh[3]={0.,0.,0.};
        //    Double_t ppTracking[3]={0.,0.,0.};
        Double_t ScalingLow[3]={0.,0.,0.};
        Double_t ScalingHigh[3]={0.,0.,0.};
	Double_t ppSystRawYieldOnly[3]={0.,0.,0.};
	Double_t ppSystRawYieldCutVar[3]={0.,0.,0.};
        Double_t ppSystRawYieldCutVarPid[3]={0.,0.,0.};
        Double_t ABSystLow[3]={0.,0.,0.};
        Double_t ABSystHigh[3]={0.,0.,0.};
        Double_t ABSystUncorrLow[3]={0.,0.,0.};
        Double_t ABSystUncorrHigh[3]={0.,0.,0.};
        Double_t ABSystRawYieldOnly[3]={0.,0.,0.};
        Double_t ABSystRawYieldCutVar[3]={0.,0.,0.};
        Double_t ABSystRawYieldCutVarPid[3]={0.,0.,0.};
        //    Double_t ABTracking[3]={0.,0.,0.};
        Double_t RabFdElossLow[3]={0.,0.,0.};
        Double_t RabFdElossHigh[3]={0.,0.,0.};
        Double_t RabGlobalLow[3]={0.,0.,0.};
        Double_t RabGlobalHigh[3]={0.,0.,0.};
        
        Double_t average=0., averageStat=0.;
        Double_t weightTot=0.;
        Double_t ppTrackingAv=0., ABTrackingAv=0.;
        Double_t ppDataSystAvLow=0., ppDataSystAvHigh=0.;
        Double_t ABDataSystAvLow=0., ABDataSystAvHigh=0.;
        Double_t scalingLowAv=0., scalingHighAv=0.;
        Double_t raaSystUncorrLow=0., raaSystUncorrHigh=0.;
        Double_t raabeautyLow=0., raabeautyHigh=0.;
        
        Int_t histoBin=-1;
        
        // Get tracking uncertainties and raw yield and cut-variation and pid-systematics
        if(isDebug) cout<<" Retrieving tracking + rawyield systematics"<<endl;
        for(Int_t j=0; j<3; j++) {
            if(!isDmeson[j]) continue;
	    ppSystRawYieldOnly[j] = ppSystRawYield[j][ipt];
            ppSystRawYieldCutVar[j] = TMath::Sqrt( ppSystRawYield[j][ipt]*ppSystRawYield[j][ipt]
                                                  + ppSystCutVar[j][ipt]*ppSystCutVar[j][ipt] );
            ppSystRawYieldCutVarPid[j] = TMath::Sqrt( ppSystRawYield[j][ipt]*ppSystRawYield[j][ipt]
                                                     + ppSystCutVar[j][ipt]*ppSystCutVar[j][ipt]
                                                     + ppSystPid[j][ipt]*ppSystPid[j][ipt] );
	    ABSystRawYieldOnly[j] = ABSystRawYield[j][ipt];
            ABSystRawYieldCutVar[j] = TMath::Sqrt( ABSystRawYield[j][ipt]*ABSystRawYield[j][ipt]
                                                  + ABSystCutVar[j][ipt]*ABSystCutVar[j][ipt] );
            ABSystRawYieldCutVarPid[j] = TMath::Sqrt( ABSystRawYield[j][ipt]*ABSystRawYield[j][ipt]
                                                     + ABSystCutVar[j][ipt]*ABSystCutVar[j][ipt]
                                                     + ABSystPid[j][ipt]*ABSystPid[j][ipt] );
            if(isDebug) cout<<" j="<<j<<" pt="<< ptval<<" ppref unc RY+CV="<<ppSystRawYieldCutVar[j]<<" RY+CV+PID="<<ppSystRawYieldCutVarPid[j]<<endl;
            if(isDebug) cout<<" j="<<j<<" pt="<< ptval<<" AB unc RY+CV="<<ABSystRawYieldCutVar[j]<<" RY+CV+PID="<<ABSystRawYieldCutVarPid[j]<<endl;
        }
        
        if(isReadAllPPUnc){
            if(isDebug) cout<<" Retrieving all pp reference systematics from the rebinned file"<<endl;
            for(Int_t j=0; j<3; j++) {
                if(!isDmeson[j]) continue;
                Int_t ibin = hDmesonPPRef[j]->FindBin(ptval);
                Double_t ppval = hDmesonPPRef[j]->GetBinContent(ibin);
                Double_t rawyield = hDmesonPPYieldExtrUnc[j]->GetBinContent( hDmesonPPYieldExtrUnc[j]->FindBin(ptval) )/ppval;
                Double_t cutvar = hDmesonPPCutVarUnc[j]->GetBinContent( hDmesonPPCutVarUnc[j]->FindBin(ptval) )/ppval;
                Double_t pid = hDmesonPPIDPUnc[j]->GetBinContent(  hDmesonPPIDPUnc[j]->FindBin(ptval) )/ppval;
                ppSystRawYieldCutVar[j] = TMath::Sqrt( rawyield*rawyield + cutvar*cutvar );
                ppSystRawYieldCutVarPid[j] = TMath::Sqrt( rawyield*rawyield + cutvar*cutvar + pid*pid );
                if(isDebug) cout<<"redo j="<<j<<" pt="<< ptval<<" ppref unc RY+CV="<<ppSystRawYieldCutVar[j]<<" RY+CV+PID="<<ppSystRawYieldCutVarPid[j]<<endl;
            }
        }
        // Check for the pp reference systematics for extrapolated pt bins
        for(Int_t j=0; j<3; j++) {
            if(isPPRefExtrap[j]){
                //      if(ptval>ptmaxPPRefData[j]) {
                Int_t ippbin = hCombinedReferenceFlag[j]->FindBin(ptval);
                Bool_t flag = hCombinedReferenceFlag[j]->GetBinContent(ippbin);
                if(!flag) continue;
                //	cout<<" pp ref flag="<<flag<<" >>> ";
                // Get pp reference relative systematics
                Double_t ppSystTotLow=0., ppSystTotHigh=0.;
                FindGraphRelativeUnc(gDataSystematicsPP[j],ptval,ppSystTotLow,ppSystTotHigh);
                ppSystRawYieldCutVar[j] = ppSystTotLow > ppSystTotHigh ? ppSystTotLow : ppSystTotHigh ;
                ppSystRawYieldCutVarPid[j] = ppSystRawYieldCutVar[j];
		ppSystRawYieldOnly[j] = ppSystRawYieldCutVar[j];
	    }
        }
        //
        // Loop per meson to get the Raa values and uncertainties for the given pt bin
        //
        if(isDebug) cout<<" Retrieving all Raa values and uncertainties"<<endl;
        for(Int_t j=0; j<3; j++) {
            // Get value, stat unc and weight
            if(!isDmeson[j]) continue;
            if(!hDmesonRaa[j]) continue;
            histoBin = hDmesonRaa[j]->FindBin(ptval);
            RaaDmeson[j] = hDmesonRaa[j]->GetBinContent( histoBin );
            if (RaaDmeson[j]<=0) continue;
            RaaDmesonStat[j] = hDmesonRaa[j]->GetBinError( histoBin );
            // Get global systematics
            FindGraphRelativeUnc(gRAB_GlobalSystematics[j],ptval,RaaDmesonSystLow[j],RaaDmesonSystHigh[j]);
            // Evaluate the weight
            weight[j] = GetWeight(averageOption,ptval,hDmesonRaa[j],
                                  RaaDmesonSystLow[j],RaaDmesonSystHigh[j],
                                  ppSystRawYieldOnly[j],ppSystRawYieldCutVar[j],ppSystRawYieldCutVarPid[j],
				  ABSystRawYieldOnly[j],ABSystRawYieldCutVar[j],ABSystRawYieldCutVarPid[j]);
            cout<<" raa "<<filenamesSuffixes[j]<<" meson  = "<<RaaDmeson[j]<<" +-"<<RaaDmesonStat[j]<<"(stat) -> (weight="<<weight[j]<<") ,";
            // Get pp reference relative systematics
            FindGraphRelativeUnc(gDataSystematicsPP[j],ptval,ppSystLow[j],ppSystHigh[j]);
            // Get pp-extrapolation relative uncertainty
            FindGraphRelativeUnc(gScalingUncPP[j],ptval,ScalingHigh[j],ScalingLow[j]); // exchanging low-high bc has oposite influence on Raa
            if(isPPRefExtrap[j]){
                Int_t ippbin = hCombinedReferenceFlag[j]->FindBin(ptval);
                Bool_t flag = hCombinedReferenceFlag[j]->GetBinContent(ippbin);
                if(isDebug) cout<< " bin="<<j<<" pp ref flag on? "<<flag;
                if(flag){ ScalingHigh[j]=0.; ScalingLow[j]=0.; ppTracking[j][ipt]=0.; }
		if(flag && !useExtrapPPref){ 
		  weight[j] =0;
		  cout<<"weight set to 0";
		}
            }
            // Get pp reference systematics minus tracking systematics minus extrapolation uncertainties
            ppSystUncorrLow[j] = TMath::Sqrt( ppSystLow[j]*ppSystLow[j]
                                             - ScalingLow[j]*ScalingLow[j]
                                             - ppTracking[j][ipt]*ppTracking[j][ipt] );
            ppSystUncorrHigh[j] = TMath::Sqrt( ppSystHigh[j]*ppSystHigh[j]
                                              - ScalingHigh[j]*ScalingHigh[j]
                                              - ppTracking[j][ipt]*ppTracking[j][ipt] );
            // Get AB relative systematics
            FindGraphRelativeUnc(gDataSystematicsAB[j],ptval,ABSystLow[j],ABSystHigh[j]);
            // Get AB relative systematics minus tracking systematics
            ABSystUncorrLow[j] = TMath::Sqrt( ABSystLow[j]*ABSystLow[j]
                                             - ABTracking[j][ipt]*ABTracking[j][ipt] );
            ABSystUncorrHigh[j] = TMath::Sqrt( ABSystHigh[j]*ABSystHigh[j]
                                              - ABTracking[j][ipt]*ABTracking[j][ipt] );
            // Get Feed-Down and Eloss relative uncertainties on the Raa
            FindGraphRelativeUnc(gRABFeedDownSystematicsElossHypothesis[j],ptval,RabFdElossLow[j],RabFdElossHigh[j]);
            //
            // Check with global Raa uncertainties
            FindGraphRelativeUnc(gRAB_GlobalSystematics[j],ptval,RabGlobalLow[j],RabGlobalHigh[j]);
            Double_t testLow = TMath::Sqrt( RabFdElossLow[j]*RabFdElossLow[j] + ABSystLow[j]*ABSystLow[j]
                                           + ppSystLow[j]*ppSystLow[j] + ScalingLow[j]*ScalingLow[j] );
            Double_t testHigh = TMath::Sqrt( RabFdElossHigh[j]*RabFdElossHigh[j] + ABSystHigh[j]*ABSystHigh[j]
                                            + ppSystHigh[j]*ppSystHigh[j] + ScalingHigh[j]*ScalingHigh[j] );
            if (TMath::Abs( testLow - RabGlobalLow[j] ) > 0.015) {
                cout << endl<<" >>>> Error on the global Raa uncertainties low : test-sum = "<< testLow<<", global = "<< RabGlobalLow[j]<<" ppref="<<ppSystLow[j]<<endl;
            }
            if (TMath::Abs( testHigh - RabGlobalHigh[j] ) > 0.015) {
                cout << endl<<" >>>> Error on the global Raa uncertainties high : test-sum = "<< testHigh<<", global = "<< RabGlobalHigh[j]<<" ppref="<<ppSystHigh[j]<<endl<<endl;
            }
            //
            histoBin = -1;
	    cout<<endl;
        }
        cout<<endl;
        
        //
        // Evaluate Dmeson average
        //
        if(isDebug) cout<<" Evaluating the average"<<endl;
        for(Int_t j=0; j<3; j++){
            if(!isDmeson[j]) continue;
            if( !(RaaDmeson[j]>0.) ) continue;
            weightTot += weight[j];
            // weighted average
            average += RaaDmeson[j]*weight[j];
            // stat absolute uncertainty (uncorrelated) : sum in quadrature
            averageStat += (RaaDmesonStat[j]*weight[j])*(RaaDmesonStat[j]*weight[j]);
            // pp tracking relative uncertainty (correlated) : linear sum
            ppTrackingAv += ppTracking[j][ipt]*RaaDmeson[j]*weight[j];
            // AB tracking relative uncertainty (correlated) : linear sum
            ABTrackingAv += ABTracking[j][ipt]*RaaDmeson[j]*weight[j];
            // pp scaling relative uncertainty (correlated) : linear sum
            scalingLowAv += ScalingLow[j]*RaaDmeson[j]*weight[j];
            scalingHighAv += ScalingHigh[j]*RaaDmeson[j]*weight[j];
            // Get pp and AB relative uncorrelated systematics : sum in quadrature
            raaSystUncorrLow += (ppSystUncorrLow[j]*RaaDmeson[j]*weight[j])*(ppSystUncorrLow[j]*RaaDmeson[j]*weight[j])
            + (ABSystUncorrLow[j]*RaaDmeson[j]*weight[j])*(ABSystUncorrLow[j]*RaaDmeson[j]*weight[j]);
            raaSystUncorrHigh += (ppSystUncorrHigh[j]*RaaDmeson[j]*weight[j])*(ppSystUncorrHigh[j]*RaaDmeson[j]*weight[j])
            + (ABSystUncorrHigh[j]*RaaDmeson[j]*weight[j])*(ABSystUncorrHigh[j]*RaaDmeson[j]*weight[j]);
            ppDataSystAvLow += (ppSystUncorrLow[j]*RaaDmeson[j]*weight[j])*(ppSystUncorrLow[j]*RaaDmeson[j]*weight[j]);
            ABDataSystAvLow += (ABSystUncorrLow[j]*RaaDmeson[j]*weight[j])*(ABSystUncorrLow[j]*RaaDmeson[j]*weight[j]);
            ppDataSystAvHigh += (ppSystUncorrHigh[j]*RaaDmeson[j]*weight[j])*(ppSystUncorrHigh[j]*RaaDmeson[j]*weight[j]);
            ABDataSystAvHigh += (ABSystUncorrHigh[j]*RaaDmeson[j]*weight[j])*(ABSystUncorrHigh[j]*RaaDmeson[j]*weight[j]);
            // Beauty uncertainties: evaluate Raa average for the upper / lower bands
            raabeautyLow += (1-RabFdElossLow[j])*RaaDmeson[j]*weight[j];
            raabeautyHigh += (1+RabFdElossHigh[j])*RaaDmeson[j]*weight[j];
        }
        average /= weightTot;
        averageStat = TMath::Sqrt(averageStat)/weightTot;
        ppTrackingAv /= weightTot;
        ABTrackingAv /= weightTot;
        scalingLowAv /= weightTot;
        scalingHighAv /= weightTot;
        raaSystUncorrLow = TMath::Sqrt(raaSystUncorrLow)/weightTot;
        raaSystUncorrHigh = TMath::Sqrt(raaSystUncorrHigh)/weightTot;
        ppDataSystAvLow = TMath::Sqrt(ppDataSystAvLow)/weightTot;
        ppDataSystAvHigh = TMath::Sqrt(ppDataSystAvHigh)/weightTot;
        ABDataSystAvLow = TMath::Sqrt(ABDataSystAvLow)/weightTot;
        ABDataSystAvHigh = TMath::Sqrt(ABDataSystAvHigh)/weightTot;
        
        // finalization beauty uncertainties
        raabeautyLow /= weightTot;
        raabeautyHigh /= weightTot;
        Double_t RaaBeauty[3] = { average, raabeautyLow, raabeautyHigh };
        Double_t beautyUncLow = average-TMath::MinElement(3,RaaBeauty);
        Double_t beautyUncHigh = TMath::MaxElement(3,RaaBeauty)-average;
        
        // finalization global uncertainties
        Double_t totalUncLow = TMath::Sqrt( raaSystUncorrLow*raaSystUncorrLow
                                           + ppTrackingAv*ppTrackingAv + ABTrackingAv*ABTrackingAv
                                           + scalingLowAv*scalingLowAv
                                           + beautyUncLow*beautyUncLow );
        Double_t totalUncHigh = TMath::Sqrt( raaSystUncorrHigh*raaSystUncorrHigh
                                            + ppTrackingAv*ppTrackingAv + ABTrackingAv*ABTrackingAv
                                            + scalingHighAv*scalingHighAv
                                            + beautyUncHigh*beautyUncHigh );
        if(isDebug) cout<<" Raa="<<average<<" +-"<<averageStat<<"(stat) +"<<ppDataSystAvHigh<<" -"<<ppDataSystAvLow<<" (pp-data) +-"<<ppTrackingAv<<" (pp-track) +"<<ABDataSystAvHigh<<" -"<<ABDataSystAvLow<<" (ab-data) +-"<<ABTrackingAv<<" (ab-track) +"<<scalingHighAv<<" -"<<scalingLowAv<<" (scal) +"<<beautyUncHigh<<" -"<<beautyUncLow<<" (fd)"<<endl;
        //
        // Fill output histos/graphs
        //
        histoBin = hDmesonAverageRAB->FindBin(ptval);
        hDmesonAverageRAB->SetBinContent(histoBin,average);
        hDmesonAverageRAB->SetBinError(histoBin,averageStat);
        Double_t ept = hDmesonAverageRAB->GetBinWidth(histoBin)/2.;
        ept=0.3;
        gRAB_DmesonAverage_GlobalSystematics->SetPoint(ipt,ptval,average);
        gRAB_DmesonAverage_GlobalSystematics->SetPointError(ipt,ept,ept,totalUncLow,totalUncHigh);
        ept=0.2;
        gRAB_DmesonAverage_FeedDownSystematicsElossHypothesis->SetPoint(ipt,ptval,average);
        gRAB_DmesonAverage_FeedDownSystematicsElossHypothesis->SetPointError(ipt,ept,ept,beautyUncLow,beautyUncHigh);
        //
        ept=0.1;
        gRAB_DmesonAverage_TrackingSystematicsPP->SetPoint(ipt,ptval,average);
        gRAB_DmesonAverage_TrackingSystematicsPP->SetPointError(ipt,ept,ept,ppTrackingAv,ppTrackingAv);
        gRAB_DmesonAverage_TrackingSystematicsAB->SetPoint(ipt,ptval,average);
        gRAB_DmesonAverage_TrackingSystematicsAB->SetPointError(ipt,ept,ept,ABTrackingAv,ABTrackingAv);
        gRAB_DmesonAverage_ScalingSystematicsPP->SetPoint(ipt,ptval,average);
        gRAB_DmesonAverage_ScalingSystematicsPP->SetPointError(ipt,ept,ept,scalingLowAv,scalingHighAv);
        gRAB_DmesonAverage_DataSystematicsPP->SetPoint(ipt,ptval,average);
        gRAB_DmesonAverage_DataSystematicsPP->SetPointError(ipt,ept,ept,ppDataSystAvLow,ppDataSystAvHigh);
        gRAB_DmesonAverage_DataSystematicsAB->SetPoint(ipt,ptval,average);
        gRAB_DmesonAverage_DataSystematicsAB->SetPointError(ipt,ept,ept,ABDataSystAvLow,ABDataSystAvHigh);
        histoBin = -1;
        //
        // Printout
        cout<< " pt min (GeV/c),  pt max (GeV/c), Raa(Daverage), +- (stat), + (syst) , - (syst) "<<endl;
        cout<< ptbinlimits[ipt] <<"  "<< ptbinlimits[ipt+1]<< "  "<< average<< "  "<< averageStat<< "  "<< totalUncHigh<<"  "<<totalUncLow<<endl;
        fprintf(resultFile,"%02.0f   %02.0f   %5.3f   %5.3f   %5.3f   %5.3f\n",ptbinlimits[ipt],ptbinlimits[ipt+1],average,averageStat,totalUncHigh,totalUncLow);
    } // end loop on pt bins
    
    fclose(resultFile);
    
    //
    // Now can start drawing
    //
    TH2F* hempty=new TH2F("hempty"," ; p_{T} (GeV/c} ; Nucl. modif. fact.",100,0.,ptbinlimits[nbins],100,0.,2.);
    hempty->SetStats(0);

    TCanvas *cAvCheck = new TCanvas("cAvCheck","Average Dmeson check");
    hempty->Draw();
    hDmesonAverageRAB->SetLineColor(kBlack);
    hDmesonAverageRAB->SetMarkerStyle(20);
    hDmesonAverageRAB->SetMarkerColor(kBlack);
    hDmesonAverageRAB->Draw("esame");
    for(Int_t j=0; j<3; j++) {
        if(!isDmeson[j]) continue;
        hDmesonRaa[j]->SetLineColor(kBlack);
        hDmesonRaa[j]->SetMarkerColor(2+j);
        hDmesonRaa[j]->SetMarkerStyle(21+j);
        gRAB_GlobalSystematics[j]->SetFillStyle(0);
        gRAB_GlobalSystematics[j]->SetLineColor(2+j);
        gRAB_GlobalSystematics[j]->Draw("2");
        hDmesonRaa[j]->Draw("esame");
    }
    gRAB_DmesonAverage_GlobalSystematics->SetFillStyle(0);
    gRAB_DmesonAverage_GlobalSystematics->SetLineColor(kBlack);
    gRAB_DmesonAverage_GlobalSystematics->Draw("2");
    hDmesonAverageRAB->Draw("esame");
    cAvCheck->Update();
    cAvCheck->SaveAs(Form("%s_result_%s.gif",foutname.Data(),ndate.Data()));

    TCanvas *cAv = new TCanvas("cAv","Average Dmeson");
    hDmesonAverageRAB->Draw("e");
    gRAB_DmesonAverage_FeedDownSystematicsElossHypothesis->SetFillStyle(1001);
    gRAB_DmesonAverage_FeedDownSystematicsElossHypothesis->SetFillColor(kMagenta-7);
    gRAB_DmesonAverage_FeedDownSystematicsElossHypothesis->Draw("2");
    gRAB_DmesonAverage_GlobalSystematics->Draw("2");
    hDmesonAverageRAB->Draw("esame");
    cAv->Update();
    
    //
    // Now can start saving the output
    //
    TFile *fout = new TFile(Form("HFPtSpectrumRaa_%s_%s.root",foutname.Data(),ndate.Data()),"recreate");
    hDmesonAverageRAB->Write();
    gRABNorm->Write();
    gRAB_DmesonAverage_GlobalSystematics->Write();
    gRAB_DmesonAverage_FeedDownSystematicsElossHypothesis->Write();
    gRAB_DmesonAverage_TrackingSystematicsPP->Write();
    gRAB_DmesonAverage_TrackingSystematicsAB->Write();
    gRAB_DmesonAverage_ScalingSystematicsPP->Write();
    gRAB_DmesonAverage_DataSystematicsPP->Write();
    gRAB_DmesonAverage_DataSystematicsAB->Write();
    fout->Write();
    
}