Exemple #1
0
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
 
    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);
    


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    const int NnewBins = 80;
    double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);


    int NDepth = 2; //number of depths
    int MinDepth = 1;
    int MaxDepth = 2;
    int MinEta = 29; 
    int MaxEta = 41;
    int MinPhi = 41;
    int MaxPhi = 53;
   
 
    TCanvas *Carray[NDepth+1][MaxPhi+1];
    bool drawflag[NDepth+1][MaxPhi+1];  
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

	bool nonNull = false;

	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
	  if(LED[iDepth][iEta][iPhi]) nonNull = true;
      
	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);
	}

	drawflag[iDepth][iPhi] = false;
	char canvname[16];
	sprintf(canvname, "c_%d_%d", iDepth,iPhi);
	if(nonNull){ //only create canvas if distributions exist
	  Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700);
	  Carray[iDepth][iPhi]->Divide(5,3);
	}

      }
    }



    int HV=0;

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;

	  if(!LED[iDepth][iEta][iPhi]) continue;

	  sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
	  sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
	  hspe->Reset();
	  sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  hspe->SetTitle(spehistname);

	  //combine bins of original SPE histogram
	  for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	    double bin_center = hspe_temp->GetBinCenter(ib);
	    if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	    int newbin = hspe->FindBin(bin_center);
	    double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	    double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	    hspe->SetBinContent(newbin,new_content);
	    hspe->SetBinError(newbin,new_error);
	  }
	  TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");
	  //renormalize bins of new SPE histogram
	  for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	    double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    hspe->SetBinContent(ib,new_content);
	    hspe->SetBinError(ib,new_error);
	  }
	  
	  if(hspe_temp->Integral()==0) continue;
	  else drawflag[iDepth][iPhi] = true;	  

	  Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	  TF1 *fped = new TF1("fped","gaus",0, 80);
	  hped->Fit(fped,"NQR");
	  double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	  hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
	  
	  //estimate SPE peak location
	  int max_SPE_bin, maxbin, Nbins;
	  double max_SPE_height=0, minheight, max_SPE_location;
	  bool minflag = false;
	  maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	  minheight=hspe->GetBinContent(maxbin); //initialize minheight
	  Nbins = hspe->GetNbinsX();
	  for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	    if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	    if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	    if(minflag && hspe->GetBinContent(j) > max_SPE_height){
	      max_SPE_bin = j;
	      max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
	      max_SPE_height = hspe->GetBinContent(j);
	    }
	  } //start from pedestal peak and loop through bins
	  //find minimum bin between pedestal and SPE peaks
	  hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	  int minbin = hspe->GetMinimumBin(); 
	  double minbin_location = hspe->GetBinCenter(minbin);
	  hspe->GetXaxis()->SetRange(1,Nbins);	    
	  
	  TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	  double mu = - log(fped->Integral(0,100)/Nev);
	  if(mu<0) mu=0.01;
	  double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	  if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
	  else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	  fit->SetParLimits(0, 0, 10);
	  fit->FixParameter(1, fped->GetParameter(1));
	  fit->FixParameter(2, fped->GetParameter(2));
	  fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	  fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);
	  

	  double maxfitrange = 500.;    
	  double minfitrange = 0.;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	  maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4);
	  if(500<maxfitrange) maxfitrange = 500;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	  //calculate NDOF of fit excluding bins with 0 entries
	  int myNDOF=-3; //three free parameters
	  for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	    if(hspe->GetBinContent(j)) myNDOF++;
	  } //loop through fitted spe bins


	  //calculate means and integrals of the fit and data
	  double fint, fint_error, hint, favg, havg;
	  int temp_lowbin, temp_highbin;
	  temp_lowbin = hspe->FindBin(minfitrange);
	  temp_highbin = hspe->FindBin(maxfitrange);
	  hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	  havg = hspe_unscaled->GetMean();
	  hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	  double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	  favg = fit->Mean(min_frange, maxfitrange);
	  fint = fit->Integral(min_frange, maxfitrange);
	  //fint_error = fit->IntegralError(min_frange, maxfitrange);
	  
	  double PE5int = 0; //integral of events with >=5 PE
	  double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	  if(PE5loc>500) PE5int = 0;
	  else {
	    int PE5bin =  hspe_temp->FindBin(PE5loc);
	    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	  }
	  int PE5flag = 0;
	  if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
	//=========================================    
	  //for(int i1=1;i1<hspe->GetNbinsX();i1++){
	    //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
          //}
        //=========================================    

	  //printf("%d\n",myNDOF);
	  //output calibrations constants
	  //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	  constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	    

	  /*
	  if(iDepth==2 && iPhi==53 && iEta==36){
	    cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
	    cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  }
	  */

	  Carray[iDepth][iPhi]->cd(iEta-MinEta+1);
	  gPad->SetBorderMode(0);
	  gPad->SetBorderSize(0);
	  gPad->SetRightMargin(0.01);
	  gPad->SetBottomMargin(0.1);
	  gPad->SetLogy(true);
	  hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/);
	  hspe->SetLineColor(kBlue);
	  hspe->DrawClone("hist");
	  fit->SetLineWidth(2);
	  fit->Draw("same");

	}
    
	if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present
	  stringstream plot_name;
	  plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf";
	  Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str());
	  plot_name.str( std::string() );
	}

      }
    }

    constants_file.close();
    //constants_file1.close();
}
void SPEFit(char * fname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc);
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
    constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag Polya_shape Polya_shape_err Polya_mode"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";


    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 

    //extra_file<<endl<<"LED_amplitude HV Spigot Channel PedSubtracted_mean Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
    bool drawflag;   
 
    TFile *tf = new TFile(fname);
    
    TCanvas *c1 = new TCanvas("c1","c1",1200,700);
    c1->Divide(6,4);
    c1->SetBorderMode(0);
    c1->SetBorderSize(0);
    TCanvas *c2 = new TCanvas("c2","c2",1200,700);
    c2->Divide(6,4);
    c2->SetBorderMode(0);
    c2->SetBorderSize(0);  
    TCanvas *c3 = new TCanvas("c3","c3",1200,700);
    c3->Divide(6,4);
    c3->SetBorderMode(0);
    c3->SetBorderSize(0);

    const int NnewBins = 106;
    double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);

    int Npoints;
    TH2D *tmp;
    for(Npoints=0;Npoints<10;Npoints++){
      sprintf(spename,"spetest/spigot_%d/bb_%d/LED_HVset_%d_sp_%d_BB_%d",0,1,Npoints,0,1);
      tmp=(TH2D *)tf->Get(spename);
      if(tmp==0) break;
    }
    TH2D *LED[3][3][20];
    TH2D *PED[3][3];
    for(int iSpig = 0; iSpig < 3; iSpig++)for(int bb = 1; bb < 4; bb++){
        for(int ii=0; ii<Npoints; ii++){
           sprintf(spename,"spetest/spigot_%d/bb_%d/LED_HVset_%d_sp_%d_BB_%d",iSpig,bb,ii,iSpig,bb);
           LED[iSpig][bb-1][ii]=(TH2D *)tf->Get(spename);
        }
        sprintf(spename,"spetest/spigot_%d/bb_%d/PED_sp_%d_BB_%d",iSpig,bb,iSpig,bb);
        PED[iSpig][bb-1]=(TH2D *)tf->Get(spename);
    }


    for(int ii=0; ii<Npoints; ii++) {
      drawflag=false;
      int HV=0;
      for (int iSpig = 0; iSpig < 3; iSpig++) {
	for(int i = 0; i < 24; i++) {
            int bb=BB_MAP[i];
            int pmt=PMT_MAP[i];
            sprintf(spehistname,"led %d %d %d",ii,iSpig,i);
            TH1D *hspe_temp = (TH1D *)LED[iSpig][bb-1][ii]->ProjectionX(spehistname,pmt,pmt,"")->Clone();
            sprintf(spehistname,"ped %d %d %d",ii,iSpig,i);
            TH1D *hped = (TH1D *)PED[iSpig][bb-1]->ProjectionX(spehistname,pmt,pmt,"")->Clone();
            sscanf(&hspe_temp->GetTitle()[7],"%d",&HV);
	    hspe->Reset();
            sprintf (spehistname, "SumLED%d_sp_%d_ch_%d", HV, iSpig, i);
	    hspe->SetTitle(spehistname);

	    //combine bins of original SPE histogram
	    for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	      double bin_center = hspe_temp->GetBinCenter(ib);
	      if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	      int newbin = hspe->FindBin(bin_center);
	      double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	      double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	      hspe->SetBinContent(newbin,new_content);
	      hspe->SetBinError(newbin,new_error);
	    }
	    TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");

	    //renormalize bins of new SPE histogram
	    for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	      double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	      double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	      hspe->SetBinContent(ib,new_content);
	      hspe->SetBinError(ib,new_error);
	    }
	    
	    if(hspe_temp->Integral()==0) continue;
	    else drawflag=true;	  
    
            Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	    
	    TF1 *fped = new TF1("fped","gaus",0, 80);
	    hped->Fit(fped,"NQR");
	    double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	    //cout<<"Ped only: ped mean "<<fped->GetParameter(1)<<", ped width "<<fped->GetParameter(2)<<" normalization "<<fped->GetParameter(0)<<endl;
	    hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);
	    //cout<<"SPE distribution: ped mean "<<fped->GetParameter(1)<<", ped width "<<fped->GetParameter(2)<<" normalization "<<fped->GetParameter(0)<<endl;
	    
	    
	    //estimate SPE peak location
	    int max_SPE_bin, maxbin, Nbins;
	    double max_SPE_height=0, minheight, max_SPE_location;
	    bool minflag = false;
	    maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	    minheight=hspe->GetBinContent(maxbin); //initialize minheight
	    /*
	    int maxped_bin = hspe->GetMaximumBin();
	    int maxped_binheight = hspe->GetBinContent(maxped_bin);
	    minheight = maxped_binheight;
	    */
	    Nbins = hspe->GetNbinsX();
	    for(int j=/*maxped_bin*/maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	      if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	      if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	      if(minflag && hspe->GetBinContent(j) > max_SPE_height){
		max_SPE_bin = j;
		max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
		max_SPE_height = hspe->GetBinContent(j);
	      }
	    } //start from pedestal peak and loop through bins
	    //find minimum bin between pedestal and SPE peaks
	    hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	    int minbin = hspe->GetMinimumBin(); 
	    double minbin_location = hspe->GetBinCenter(minbin);
	    hspe->GetXaxis()->SetRange(1,Nbins);
	    
	    
	    TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	    double mu = - log(fped->Integral(0,100)/Nev);
	    if(mu<0) mu=0.01;
	    double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	    if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, 3.0);
	    else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 3.0); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	    fit->SetParLimits(0, 0, 10);
	    fit->FixParameter(1, fped->GetParameter(1));
	    fit->FixParameter(2, fped->GetParameter(2));
	    fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	    fit->SetParLimits(4, 1.01, 100.);


	    double maxfitrange = 500.;    
	    double minfitrange = 0.;
	    hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	    double rms_estimate = fit->GetParameter(3)/sqrt(fit->GetParameter(4));
            maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+rms_estimate;

 //  cout<<"estimate of gain "<<gain_est<<", fit "<<fit->GetParameter(3)<<endl;
 //  cout<<"Shape Parameter "<<fit->GetParameter(4)<<endl;
 //  cout<<"SPE width "<<rms_estimate<<endl;
 //  cout<<"maxfitrange "<<maxfitrange<<endl;

            if(500<maxfitrange) maxfitrange = 500;
	    hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	    //calculate NDOF of fit excluding bins with 0 entries
	    int myNDOF=-3; //three free parameters
	    for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	      if(hspe->GetBinContent(j)) myNDOF++;
            } //loop through fitted spe bins


//	    cout<<"estimate of gain "<<gain_est<<", fit "<<fit->GetParameter(3)<<endl;
//	    cout<<"Shape Parameter "<<fit->GetParameter(4)<<endl;
//	    double SPE_rms = fit->GetParameter(3)/sqrt(fit->GetParameter(4));
//	    cout<<"SPE width "<<SPE_rms<<endl;

	    //cout<<"SPE width "<<fit->GetParameter(4)<<endl;
	    //cout<<"Fit normalization constant: estimate "<<mu<<" fit "<<fit->GetParameter(0)<<endl;
	    //cout<<spename<<endl;


	    //calculate means and integrals of the fit and data
	    double fint, fint_error, hint, favg, havg;
	    int temp_lowbin, temp_highbin;
	    temp_lowbin = hspe->FindBin(minfitrange);
	    temp_highbin = hspe->FindBin(maxfitrange);
	    hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	    havg = hspe_unscaled->GetMean();
	    hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	    double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	    favg = fit->Mean(min_frange, maxfitrange);
	    fint = fit->Integral(min_frange, maxfitrange);
	    //fint_error = fit->IntegralError(min_frange, maxfitrange);
	    
	    double PE5int = 0; //integral of events with >=5 PE
	    double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	    if(PE5loc>500) PE5int = 0;
	    else {
	      int PE5bin =  hspe_temp->FindBin(PE5loc);
	      temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	      PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	    }
	    int PE5flag = 0;
	    if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
        //=========================================    
            for(int i1=1;i1<hspe->GetNbinsX();i1++){
constants_file1<<HV<<"\t"<<iSpig<<"\t"<<i<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
            }
        //=========================================    


	    //output calibrations constants
	    //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag Polya_shape Polya_shape_err Polya_mode"<<endl;
	    constants_file<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<(bb-1)*8+pmt<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(3)/sqrt(fit->GetParameter(4))<<" "<<0<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<scale*(fit->GetParameter(4)-1.0)/fit->GetParameter(4)*fit->GetParameter(3)*fC2electrons<<endl;



//	    cout<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<QIECh[i]<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/fit->GetNDF()<<" "<<fit->GetChisquare()<<" "<<fit->GetNDF()<<" "<<myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<endl;
	   
	    //extra_file<<endl<<"LED_amplitude HV Spigot Channel SignalAvg_inFitRange FitAvg_inFitRange SignalInt_inFitRange FitInt_inFitRange PEge5Int Gain(fC) Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	    //extra_file<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<QIECh[i]<<" "<<scale*havg<<" "<<scale*favg<<" "<<hint<<" "<<fint<<" "<<PE5int<<" "<<scale*fit->GetParameter(3)<<" "<<scale*fit->GetParError(3)<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;


	    //cout<<"# Spigot Channel Ped_mean Ped_RMS SPE_PeakRMS Gain Normalized_Chi2 Avg_PE"<<endl;
	    //cout<<iSpig<<" "<<i<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<fit->GetChisquare()/fit->GetNDF()<<" "<<fit->GetParameter(0)<<endl<<endl;
	    
	    
	  
	    if(iSpig==0) c1->cd(i+1);
	    else if(iSpig==1) c2->cd(i+1);
            else if(iSpig==2) c3->cd(i+1);
	    gPad->SetBorderMode(0);
	    gPad->SetBorderSize(0);
	    gPad->SetRightMargin(0.01);
	    gPad->SetBottomMargin(0.1);
	    gPad->SetLogy(true);
	    hspe->GetXaxis()->SetRangeUser(0, /*300*/508);
	    hspe->SetLineColor(kBlue);
	    hspe->DrawClone("hist");
	    fit->SetLineWidth(2);
	    fit->Draw("same");
	   
	  }
      }

      if(drawflag) { //draw plots of fit if data for the HV is present
        stringstream plot_name;
        //plot_name<<"Plots/SPEFits_Spigot0_Run_"<<run<<"_HV"<<HV<<".pdf";
        plot_name<<"Plots/SPEFits_Spigot0_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf";
        c1->SaveAs(plot_name.str().c_str());
        plot_name.str( std::string() );
        //plot_name<<"Plots/SPEFits_Spigot1_Run_"<<run<<"_HV"<<HV<<".pdf";
        plot_name<<"Plots/SPEFits_Spigot1_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf";
        c2->SaveAs(plot_name.str().c_str());
        plot_name.str( std::string() );
        //plot_name<<"Plots/SPEFits_Spigot2_Run_"<<run<<"_HV"<<HV<<".pdf";
        plot_name<<"Plots/SPEFits_Spigot2_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf";
        c3->SaveAs(plot_name.str().c_str());
      }

    } //HV loop

    constants_file.close();
    constants_file1.close();
}
Exemple #3
0
void checkflat(int icent = 0, int ihar=0){
    int color[nsub]={1,2,3,4,5,6,7,8};
    float pi = acos(-1.0);
    TString str;
    TFile *fin;
        TH1::SetDefaultSumw2();
        gStyle->SetOptStat(kFALSE);
        int iharE=0;
     if(nhar==1||nhar==2) iharE=1;
        int n = ihar+1.0+iharE;
    int nrun = GetTotalRun();
    float FitGood[nsub][1000];
    float FitGooderr[nsub][1000];
    float runlist[1000];
        TH1F* hpsi = new TH1F("psi","psi",100,-pi,pi);
        TH1F* hunpsi = new TH1F("unpsi","unpsi",100,-pi,pi);
        TH1F* h = new TH1F("h","",100,-4,4);
        for(int irun=0;irun<nrun;irun++){
        std::ifstream corrs("run15pAl200MBPro104.Lst");
        int index=0; int run=0;
        for(int jrun=0;jrun<irun+1;jrun++){
        corrs>>index>>run;
        }
        runlist[irun] = run;
       // system(Form("hadd -f /phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d.root /phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d_*.root",run,run));
        fin = TFile::Open(Form("/phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d.root",run));
        for(int isub=0;isub<nsub;isub++){
        str = choosesub(isub);
        if(str=="ABORT") continue;
        hpsi->Reset();
        hunpsi->Reset();
        for(int ibbcz=0;ibbcz<nbbcz;ibbcz++){
          TH1F* hunpsitemp = (TH1F*)fin->Get(Form("psi_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          TH1F* hpsitemp = (TH1F*)fin->Get(Form("psiFla_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          hpsi->Add(hpsitemp);
          hunpsi->Add(hunpsitemp);
        }
        TF1 *fun = new TF1("fun","pol0",-pi,pi);
        TCanvas *c1 = new TCanvas("c1","c1",600,450);
        h->GetXaxis()->SetTitle(Form("#Psi_{%d}",n));
        h->GetYaxis()->SetTitle(Form("# of events"));
        h->GetYaxis()->SetRangeUser(hunpsi->GetBinContent(hunpsi->GetMinimumBin())*0.9,hunpsi->GetBinContent(hunpsi->GetMaximumBin())*1.1);
        h->Draw("C");
       // h->GetYaxis()->SetRangeUser(0,hunpsi->GetBinContent(hunpsi->GetMaximumBin())*1.2);
      if(hpsi->GetEntries()>1000){
	hpsi->Fit("fun","QR0");
	float par=fun->GetParameter(0);
	float parerr=fun->GetParError(0);
        FitGood[isub][irun]=fun->GetChisquare()/fun->GetNDF();
        FitGooderr[isub][irun]=0;
        fun->SetLineColor(4);
        fun->Draw("same");
      }
        else{
        FitGood[isub][irun]=0;
        FitGooderr[isub][irun]=0;
        }
        if(irun!=104) continue;
	hpsi->SetMarkerStyle(20);
	hpsi->SetMarkerSize(0.8);
	hpsi->SetMarkerColor(2);
	hpsi->SetLineColor(2);
	hunpsi->SetMarkerStyle(20);
	hunpsi->SetMarkerSize(0.8);
	hunpsi->SetMarkerColor(1);
	hunpsi->SetLineColor(1);
        TLegend *leg = new TLegend(0.4,0.7,0.8,0.85);
        leg->SetTextSize(0.04);
        leg->SetFillColor(0);
        leg->SetBorderSize(0);
        leg->AddEntry(hunpsi,Form("Run%d %s",run,str.Data()));
        leg->AddEntry(hunpsi,"before flattening","L");
        leg->AddEntry(hpsi,"After flattening","L");
        hpsi->Draw("Csame");
        hunpsi->Draw("Csame");
        leg->Draw("same");
        c1->Print(Form("run-by-run/checkflat_%d_%d_%d_%d.png",icent,ihar,isub,irun));
        delete c1;
        }
        fin->Close();
    }  
        TGraphErrors *grRun[nsub];
    TCanvas *c1 = new TCanvas("c1","c1",600,450);
    TCanvas *c2 = new TCanvas("c2","c2",600,450);
    TH1F* h1 = new TH1F("h1","",4000,436000,439000);
    h1->GetXaxis()->SetTitle(Form("Run Number"));
    h1->GetYaxis()->SetTitle("Fit #chi^{2}/Ndf");
    h1->GetXaxis()->SetRangeUser(runlist[0]-15,runlist[nrun-1]+15);
    h1->GetYaxis()->SetRangeUser(0,4);
    TLegend *leg = new TLegend(0.65,0.75,0.88,0.85);
    leg->SetTextSize(0.035);
    leg->SetBorderSize(0);
    leg->SetFillColor(0);
    c1->cd();
    h1->Draw("0");
        for(int isub=0;isub<nsub;isub++){
            if(isub!=4 && isub!=5) continue;
            grRun[isub] = new TGraphErrors(nrun,runlist,FitGood[isub],0,FitGooderr[isub]);
            grRun[isub] -> SetMarkerColor(isub-3);
            grRun[isub] -> SetMarkerSize(1.);
            grRun[isub] -> SetMarkerStyle(16+isub);
            grRun[isub] -> SetLineColor(isub-3);
            grRun[isub] -> Draw("Psame");
            leg->AddEntry(grRun[isub],choosesub(isub).Data(),"P");
        leg->Draw("same");
        }
      c1->Print(Form("run-by-run/fitsum%d.png",n));
}
Exemple #4
0
void PlotField1D( const TString &sim, Int_t time, Int_t Nbins=1, const TString &options="") { 
  
#ifdef __CINT__  
  gSystem->Load("libplasma.so");
#endif

  PlasmaGlob::Initialize();
    
  TString opt = options;

  gStyle->SetPadLeftMargin(0.10);  // Margin left axis  
  gStyle->SetPadRightMargin(0.12); // Margin right axis 
  if(opt.Contains("grid")) {
    gStyle->SetPadGridX(1);
    gStyle->SetPadGridY(1);
  }

  // Load PData
  PData *pData = PData::Get(sim.Data());
  pData->LoadFileNames(time);
  if(!pData->IsInit()) return;

  Bool_t CYL = kFALSE;
  if(sim.Contains("cyl")) { CYL = kTRUE; opt += "cyl"; } 
    
  Bool_t ThreeD = kFALSE;
  if(sim.Contains("3D")) ThreeD = kTRUE; 

  // Some plasma constants
  Double_t n0 = pData->GetPlasmaDensity();
  Double_t kp = pData->GetPlasmaK();
  Double_t skindepth = 1/kp;
  Double_t E0 = pData->GetPlasmaE0();

  // Some beam properties:
  Float_t Ebeam = pData->GetBeamEnergy() * PUnits::MeV;
  Float_t gamma = Ebeam / PConst::ElectronMassE;
  Float_t vbeam = TMath::Sqrt(1 - 1/(gamma*gamma));
  // cout << Form(" - Bunch gamma      = %8.4f", gamma ) << endl;
  // cout << Form(" - Bunch velocity   = %8.4f c", vbeam ) << endl;

  Float_t Time = pData->GetRealTime();
  // z start of the plasma in normalized units.
  Float_t zStartPlasma = pData->GetPlasmaStart()*kp;
  // z start of the beam in normalized units.
  Float_t zStartBeam = pData->GetBeamStart()*kp;
  Time -= zStartPlasma - zStartBeam;

  // 1D histograms
  TString opth1 = opt;
  opth1 += "avg";
  // Get electric fields
  const Int_t Nfields = 1;
  TH1F **hE1D = new TH1F*[Nfields];
  for(Int_t i=0;i<Nfields;i++) {
    hE1D[i] = NULL;
    if(!pData->GetEfieldFileName(i))
      continue;
    
    char nam[3]; sprintf(nam,"e%i",i+1);
    if(ThreeD) {
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,-1,Nbins,opth1.Data());
      else  
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,-Nbins,Nbins,opth1.Data());
    } else if(CYL) { // Cylindrical: The firt bin with r>0 is actually the number 1 (not the 0).
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data());
      else
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data());
    } else { // 2D cartesian
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,opth1.Data());
      else 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,opth1.Data());
    }
    
    char hName[24];
    sprintf(hName,"hE_%i",i);
    hE1D[i]->SetName(hName);
    if(opt.Contains("comov"))
      hE1D[i]->GetXaxis()->SetTitle("#zeta [c/#omega_{p}]");
    else
      hE1D[i]->GetXaxis()->SetTitle("z [c/#omega_{p}]");
   
    if(i==0)
      hE1D[i]->GetYaxis()->SetTitle("E_{z} [E_{0}]");
    else if(i==1)
      hE1D[i]->GetYaxis()->SetTitle("E_{y} [E_{0}}]");
    else if(i==2)
      hE1D[i]->GetYaxis()->SetTitle("E_{x} [E_{0}}]");
    
    
  }  
  
  // Chaning to user units: 
  if(opt.Contains("units") && n0) {
    for(Int_t i=0;i<Nfields;i++) {
      Int_t NbinsX = hE1D[i]->GetNbinsX();
      Float_t xMin = (skindepth/PUnits::mm) * hE1D[i]->GetXaxis()->GetXmin();
      Float_t xMax = (skindepth/PUnits::mm) * hE1D[i]->GetXaxis()->GetXmax();
      
      hE1D[i]->SetBins(NbinsX,xMin,xMax);
      
      for(Int_t j=0;j<NbinsX;j++) {
	hE1D[i]->SetBinContent(j, hE1D[i]->GetBinContent(j) * ( E0 / (PUnits::GV/PUnits::m) ) );
      }
      
      if(opt.Contains("comov"))
	hE1D[i]->GetXaxis()->SetTitle("#zeta [mm]");
      else
	hE1D[i]->GetXaxis()->SetTitle("z [mm]");
      
      if(i==0)
	hE1D[i]->GetYaxis()->SetTitle("E_{z} [GV/m]");
      else if(i==1)
	hE1D[i]->GetYaxis()->SetTitle("E_{y} [GV/m]");
      else if(i==2)
	hE1D[i]->GetYaxis()->SetTitle("E_{x} [GV/m]");
    }
  }
  
  // Calculate wave positions:
  // ----------------------------------------------------------------
  
  // Retrieve the previous time TGraph if any;
  // Open TGraph
  TString filename = Form("./%s/Plots/Field1D/Field1D-%s.root",sim.Data(),sim.Data());
  TFile * ifile = (TFile*) gROOT->GetListOfFiles()->FindObject(filename);
  // if doesn't exist the directory should be created
  if (!ifile) {
    TString f = filename;
    TString dir2 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) );
    TString dir1 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) );
    gSystem->mkdir( dir1 );
    gSystem->mkdir( dir2 );
    ifile = new TFile(filename,"UPDATE");
  }  
  
  
  
  Float_t *EMaxPos = new Float_t[Nfields];
  Float_t *EMaxValue = new Float_t[Nfields];
  
  // Get the Graph with the x1 positions of the maximum E_1
  TGraph **graph = new TGraph*[Nfields];
  char gName[24];
  for(Int_t i=0;i<Nfields;i++) {
    if(!hE1D[i]) continue;
    
    EMaxPos[i] = EMaxValue[i] = -999;
    
    // Initial time search window:
    Float_t xCenter = (hE1D[i]->GetXaxis()->GetXmin()+hE1D[i]->GetXaxis()->GetXmax())/2.; 
    Float_t xs1min = 0.5*(hE1D[i]->GetXaxis()->GetXmin()+xCenter);
    Float_t xs1max = xCenter;

    // For focusing fields i==1,2 we use a narrower window based on the previosly found 
    // minimum for the accelerating fields i==0.
    if(i>0) {
      xCenter = EMaxPos[0];
      if(opt.Contains("units") && n0) {
	xs1min = xCenter - (0.25*TMath::Pi() * 1e3 * skindepth);
	xs1max = xCenter + (0.25*TMath::Pi() * 1e3 * skindepth);
      } else {
	xs1min = xCenter - 0.25*TMath::Pi();
	xs1max = xCenter + 0.25*TMath::Pi();
      }
    }

    sprintf(gName,"gEMaxPos_%i",i);
    graph[i] =  (TGraph*) ifile->Get(gName);
    if(graph[i]) {
      Double_t *y = graph[i]->GetY();
      
      // Setup the searching windows to +/- pi/2 respect the last found minimum.
      if(opt.Contains("units") && n0) {
	xs1min = y[graph[i]->GetN()-1] - (0.5*TMath::Pi() * 1e3 * skindepth);
	xs1max = y[graph[i]->GetN()-1] + (0.5*TMath::Pi() * 1e3 * skindepth);
      } else {
	xs1min = y[graph[i]->GetN()-1] - 0.5*TMath::Pi();
	xs1max = y[graph[i]->GetN()-1] + 0.5*TMath::Pi();
      }
      
      delete graph[i];
    }
    
    TH1F *htemp = (TH1F*) hE1D[i]->Clone("htemp");
    htemp->GetXaxis()->SetRangeUser(xs1min,xs1max);
    
    //htemp->Smooth(1,"R");
    Int_t binMax = htemp->GetMinimumBin();
    EMaxPos[i] = (Float_t) htemp->GetBinCenter(binMax);
    EMaxValue[i] = (Float_t) htemp->GetBinContent(binMax);
    delete htemp;
    
  }
  
  
  // Tunning the Histograms
  // ---------------------
  
  
  // Plotting
  // -----------------------------------------------
  
  // Output file
  TString fOutName = Form("./%s/Plots/Field1D/Field1D",sim.Data());
  fOutName += Form("-%s_%i",sim.Data(),time);
  
  // Canvas setup
  TCanvas *C = new TCanvas("C","Electric wakefield on axis",850,1000);
  C->Divide(1,2);

  // Draw objects
  TPaveText *textTime = new TPaveText(0.70,0.87,0.85,0.92,"NDC");
  PlasmaGlob::SetPaveTextStyle(textTime); 
  char ctext[128];
  if(opt.Contains("units") && n0) 
    sprintf(ctext,"Z = %5.1f mm", 1e3 * skindepth * Time);
  else
    sprintf(ctext,"T = %5.1f 1/#omega_{p}",Time);
  textTime->AddText(ctext);
  
  // Colors
  Int_t fieldC  = PlasmaGlob::fieldLine;
  Int_t phaseC  = kGray+1;
 
  // Actual Plotting!
  // ------------------------------------------------------------

  // More makeup
  C->cd(1);
  gPad->SetGridy(0);
  gPad->SetGridx(0);
  gPad->SetFrameLineWidth(2);  

  hE1D[0]->SetLineWidth(1);
  hE1D[0]->GetYaxis()->CenterTitle();
  hE1D[0]->GetXaxis()->CenterTitle();
  hE1D[0]->SetLineStyle(1);
  hE1D[0]->SetLineWidth(3);
  hE1D[0]->SetLineColor(fieldC);
  hE1D[0]->SetMarkerStyle(20);

  if(Nfields>1) {
    hE1D[1]->GetYaxis()->CenterTitle();
    hE1D[1]->GetXaxis()->CenterTitle();
    hE1D[1]->SetLineStyle(1);
    hE1D[1]->SetLineWidth(1);  
    hE1D[1]->SetLineColor(fieldC);
    hE1D[1]->SetMarkerStyle(24);
  }

  Float_t factor = 1.5;
  Float_t minimum = factor * hE1D[0]->GetMinimum();
  Float_t maximum = factor * hE1D[0]->GetMaximum();
    
  if(Nfields>1) {
    if(hE1D[1]->GetMaximum() > hE1D[0]->GetMaximum()) {
      maximum = factor * hE1D[1]->GetMaximum();
    } 
    
    if(hE1D[1]->GetMinimum() < hE1D[0]->GetMinimum()) {
    minimum = factor * hE1D[1]->GetMinimum();
    } 
  }
  
  if( maximum >= TMath::Abs(minimum)) minimum = -maximum;
  else maximum = - minimum;
  
  hE1D[0]->GetYaxis()->SetRangeUser(minimum,maximum);
  hE1D[0]->Draw("C");
  
  if(Nfields>1)
    hE1D[1]->Draw("C same");
  
  C->Update();
  
  TLine *line0 = new TLine(hE1D[0]->GetXaxis()->GetXmin(),
			   (gPad->GetUymin()+gPad->GetUymax())/2.,
			   hE1D[0]->GetXaxis()->GetXmax(),
			   (gPad->GetUymin()+gPad->GetUymax())/2.);
  line0->SetLineColor(kGray+1);
  line0->SetLineStyle(2);
  line0->Draw();
  
  TMarker *markEMax0 = new TMarker(EMaxPos[0],EMaxValue[0], 24);
  markEMax0->SetMarkerColor(fieldC);
  markEMax0->SetMarkerSize(1.6);
  markEMax0->Draw();

  if(Nfields>1) {
    TMarker *markEMax1 = new TMarker(EMaxPos[1],EMaxValue[1], 24);
    markEMax1->SetMarkerColor(fieldC);
    markEMax1->SetMarkerSize(1.4);
    markEMax1->Draw();
  }
  
  textTime->Draw();

  // ----
  
  // Define the TGraphs
  Int_t nPoints = 0;  
  TGraph **gEMaxPos = new TGraph*[Nfields];
  TGraph **gEMaxValue = new TGraph*[Nfields];
  for(Int_t i=0;i<Nfields;i++) {
    if(!hE1D[i]) continue;

    sprintf(gName,"gEMaxPos_%i",i);
    gEMaxPos[i] = (TGraph*) ifile->Get(gName);
    if(gEMaxPos[i]==NULL) {
      gEMaxPos[i] = new TGraph();
      gEMaxPos[i]->SetName(gName);
    } else {
      nPoints = gEMaxPos[i]->GetN(); 
    }  
    gEMaxPos[i]->Set(nPoints+1);
    if(opt.Contains("units") && n0) 
      gEMaxPos[i]->SetPoint(nPoints, 1e3 * skindepth * Time,EMaxPos[i]);
    else
      gEMaxPos[i]->SetPoint(nPoints,Time,EMaxPos[i]);
    
    if(opt.Contains("units") && n0) {
      gEMaxPos[i]->GetYaxis()->SetTitle("#zeta_{min} [mm]");
      gEMaxPos[i]->GetXaxis()->SetTitle("Z [mm]");
    } else {
      gEMaxPos[i]->GetYaxis()->SetTitle("#zeta_{min} [c/#omega_{p}]");
      gEMaxPos[i]->GetXaxis()->SetTitle("T [c/#omega_{p}]");
    }

    gEMaxPos[i]->Write(gEMaxPos[i]->GetName(),TObject::kOverwrite);

    sprintf(gName,"gEMaxValue_%i",i);
    gEMaxValue[i] = (TGraph*) ifile->Get(gName);
    if(gEMaxValue[i]==NULL) {
      gEMaxValue[i] = new TGraph();  
      gEMaxValue[i]->SetName(gName);
    } else {
      nPoints = gEMaxValue[i]->GetN(); 
    }  
    gEMaxValue[i]->Set(nPoints+1);
    if(opt.Contains("units") && n0) 
      gEMaxValue[i]->SetPoint(nPoints, 1e3 * skindepth * Time,EMaxValue[i]);
    else
      gEMaxValue[i]->SetPoint(nPoints,Time,EMaxValue[i]);
    
    if(opt.Contains("units") && n0) {
      gEMaxValue[i]->GetYaxis()->SetTitle("E_{min} [GV/m]");
      gEMaxValue[i]->GetXaxis()->SetTitle("Z [mm]");
    } else {
      gEMaxValue[i]->GetYaxis()->SetTitle("E_{min} [E_{0}]");
      gEMaxValue[i]->GetXaxis()->SetTitle("T [c/#omega_{p}]");
    }
    
    gEMaxValue[i]->Write(gEMaxValue[i]->GetName(),TObject::kOverwrite);    
  }


  C->cd(2);
  gPad->SetGridy(1);
  gPad->SetGridx(0);
  gPad->SetFrameLineWidth(2);  

  Float_t minPhase = 99.;
  Float_t maxPhase = -99.;
  Float_t minField = 99.;
  Float_t maxField = -99.;

  Double_t *yEMaxPos[Nfields];
  Double_t *yEMaxValue[Nfields];

  for(Int_t i=0;i<Nfields;i++) {
    yEMaxPos[i]   = gEMaxPos[i]->GetY();
    yEMaxValue[i] = gEMaxValue[i]->GetY();
    
    for(Int_t j=0;j<gEMaxPos[0]->GetN();j++) {
      if(yEMaxPos[i][j]>maxPhase)
	maxPhase = yEMaxPos[i][j];
      if(yEMaxPos[i][j]<minPhase)
	minPhase = yEMaxPos[i][j];
 
      if(yEMaxValue[i][j]>maxField)
	maxField = yEMaxValue[i][j];
      if(yEMaxValue[i][j]<minField)
	minField = yEMaxValue[i][j];
    }
  }

  Float_t margin = (maxPhase - minPhase)/10;
  gEMaxPos[0]->GetYaxis()->SetRangeUser(minPhase-margin,maxPhase+margin);
  gEMaxPos[0]->GetYaxis()->CenterTitle();
  gEMaxPos[0]->GetXaxis()->CenterTitle();
  gEMaxPos[0]->SetLineColor(phaseC);
  gEMaxPos[0]->SetMarkerColor(phaseC);
  gEMaxPos[0]->SetLineWidth(3);
  gEMaxPos[0]->SetMarkerStyle(20);
  gEMaxPos[0]->SetMarkerSize(1.4);
  gEMaxPos[0]->Draw("APC");

  if(Nfields>1) {
    gEMaxPos[1]->SetLineStyle(1);
    gEMaxPos[1]->SetLineColor(phaseC);
    gEMaxPos[1]->SetMarkerColor(phaseC);
    gEMaxPos[1]->SetLineWidth(1);
    gEMaxPos[1]->SetMarkerStyle(24);
    gEMaxPos[1]->SetMarkerSize(1.4);
    gEMaxPos[1]->Draw("PC");
  }

  // Emax value
  // New axis first:
  C->Update();  // Needed for the axis!

  margin = (maxField - minField)/10;
  if (margin==0) margin = 1; 
  Float_t rightmin = minField-margin;
  Float_t rightmax = maxField+margin;
  Float_t slope = (gPad->GetUymax() - gPad->GetUymin())/(rightmax-rightmin);
  TGaxis *axisEmax = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),gPad->GetUxmax(),
				gPad->GetUymax(),rightmin,rightmax,505,"+L");
  axisEmax->SetLineWidth(1);
  axisEmax->SetLineColor(fieldC);
  axisEmax->SetLabelColor(fieldC);
  axisEmax->SetTitleColor(fieldC);
  if(opt.Contains("units") && n0) 
    axisEmax->SetTitle("E_{min} [GV/m]");
  else
    axisEmax->SetTitle("E_{min} [E_{0}]");
  axisEmax->CenterTitle();
  axisEmax->SetTitleSize(0.05);
  axisEmax->SetTitleOffset(1.2);
  axisEmax->SetLabelSize(0.05);
  axisEmax->SetLabelOffset(0.006);
  
  axisEmax->Draw();
  
  // Adjust the TGraph
  Double_t *x = gEMaxValue[0]->GetX();
  Double_t *y = gEMaxValue[0]->GetY();
  for(Int_t i=0;i<gEMaxValue[0]->GetN();i++) {
    gEMaxValue[0]->SetPoint(i,x[i],(y[i]-rightmin)*slope + gPad->GetUymin());
  }  
  gEMaxValue[0]->SetLineColor(fieldC);
  gEMaxValue[0]->SetMarkerColor(fieldC);
  gEMaxValue[0]->SetLineWidth(3);
  gEMaxValue[0]->SetMarkerStyle(20);
  gEMaxValue[0]->SetMarkerSize(1.4);
  gEMaxValue[0]->Draw("PC");

   if(Nfields>1) {
    x = gEMaxValue[1]->GetX();
    y = gEMaxValue[1]->GetY();
    for(Int_t i=0;i<gEMaxValue[1]->GetN();i++) {
      gEMaxValue[1]->SetPoint(i,x[i],(y[i]-rightmin)*slope + gPad->GetUymin());
    }  
    gEMaxValue[1]->SetLineColor(fieldC);
    gEMaxValue[1]->SetMarkerColor(fieldC);
    gEMaxValue[1]->SetLineWidth(1);
    gEMaxValue[1]->SetMarkerStyle(24);
    gEMaxValue[1]->SetMarkerSize(1.4);
    gEMaxValue[1]->Draw("PC");
  }

  // Emax value
  // New axis first:
  C->Update();  // Needed for the axis!

  C->cd();

  ifile->Close();
  
  // Print to a file
  PlasmaGlob::imgconv(C,fOutName,opt);
  // ---------------------------------------------------------
  
  }