Example #1
0
/**
 ****************************************************************************
 * \fn static uint16_t MDIO_Read(uint8_t phy_addr,uint8_t regAddr)
 * Read 16 Bit from MDIO
 * This is not the standard Read command as used for PHY Registers.
 * Use this command after setting the Address with a separate address 
 * command with no other commands between.
 ****************************************************************************
 */
uint16_t 
MDIO_Read(uint8_t phy_addr,uint8_t regAddr)
{
	uint8_t i;
	uint16_t outval,inval;
	SetMDO(1);
	SetDirection(DIR_OUT);
	mdio_delay();
	/* Preamble */
	for(i = 0; i < 32; i++) {
		SetMDC(1);
		mdio_delay();
		SetMDC(0);
		mdio_delay();
	}
	//outval = 0x1800;
	outval = 0x0c00;
	outval |= (phy_addr << 5);
	outval |= (regAddr & 0x1f);
	for(i = 0; i < 14; i++,  outval <<= 1) {
		uint8_t mdo = (outval & 0x2000) ? 1 : 0; 
		SetMDO(mdo);
		SetMDC(1);
		mdio_delay();
		SetMDC(0);
		mdio_delay();
	}
	/* Bus release with one clock cycle */
	SetDirection(DIR_IN);
	SetMDC(1);
	mdio_delay();
	SetMDC(0);
	mdio_delay();

	inval = 0;
	for(i = 0; i < 16; i++) {
		SetMDC(1);
		mdio_delay();
		SetMDC(0);
		mdio_delay();
		/* 
		 ******************************************************
		 * delay of data is up to 300ns from rising edge so 
		 * better sample behind falling edge 
		 ******************************************************
		 */
		inval <<= 1;
		if(GetMDI()) {
			inval |= 1;
		}
	}
	/* Let the device release the bus ? */
	SetMDC(1);
	mdio_delay();
	SetMDC(0);
	mdio_delay();
	return inval;
}
TGraphErrors *MD68Point(TH1 *hp, double y)
{
  double ymin = hp->GetMinimum();
  double ymax = hp->GetMaximum();
  double yDraw = y>0? y : ymin + 0.25*(ymax-ymin);
  TGraphErrors *g = new TGraphErrors();
  MaxDensityInterval mdi = GetMDI(hp, 0.68);
  g->SetPoint(0, mdi.u, yDraw);
  g->SetPointError(0, mdi.du, 0);
  SetGraphProps(g, kAzure, kAzure, kAzure, kOpenSquare, 1.5);
  return g;
}
TGraphAsymmErrors *ReducedSamplingVolume(TH1D **hmp, TGraphAsymmErrors *old)
{
  TGraphAsymmErrors *g = (TGraphAsymmErrors *)old->Clone();

  for (int t=0; t<g->GetN(); t++)
  {

    if (!hmp[t])
      Error("","!hmp[%d]",t);

    MaxDensityInterval mdi = GetMDI(hmp[t], 0.99);
    g->SetPoint(t, g->GetX()[t], mdi.u);
    g->SetPointEYlow(t, mdi.du);
    g->SetPointEYhigh(t, mdi.du);
  }
  return g;
}
void BayesUnfoldingExample641()
{

#ifdef __CINT__ // Avoid CINT badness
  Printf("Please compile this script (root BayesUnfoldingExample641.C+) "
         "or use ROOT 6.");
  gSystem->Exit(0);
#endif

  if (!gROOT->IsBatch())
  {
    Printf("Several canvases coming...adding -b flag.");
    gROOT->SetBatch();
  }

  gStyle->SetOptStat(0);
  gStyle->SetPaintTextFormat(".2f");

  if (gSystem->Getenv("TMPDIR"))
    gSystem->SetBuildDir(gSystem->Getenv("TMPDIR"));

  TRandom3 ran;
  TStopwatch watch; // Watch starts here. A call to Start() would reset it.

  TObjArray *cList = new TObjArray(); // List of drawn canvases --> PDF file

  // Set up the problem
  double bins[Nt+1] = {0};
  for (int j=0; j<=Nt; j++)
    bins[j] = 500*TMath::Exp(0.15*j);

  TestProblem testprob = AtlasDiJetMass(Nt, Nr, bins, bins,
                                        apar, bpar, nevts, evtWeight);
  TH2D *hM   = testprob.Response;
  TH1D *hT   = testprob.xTruth;
  TH1D *hTmc = testprob.xTruthEst;
  TH1D *hMt  = testprob.xIni;
  TH1D *hD   = testprob.bNoisy;
  TH1D *heff = testprob.eff;
  SetHistProps(hT,kRed+2,kNone,kRed+2);
  SetHistProps(hTmc,kRed,kNone,kRed);
  SetHistProps(hD,kBlack,kNone,kBlack,kFullCircle,1.5);

  TMatrixD M   = MatrixUtils::Hist2Matrix(hM);
  TVectorD T   = MatrixUtils::Hist2Vec(hT);   // \hat{T}
  TVectorD Tmc = MatrixUtils::Hist2Vec(hTmc); // \tilde{T}
  TVectorD D   = MatrixUtils::Hist2Vec(hD);
  TVectorD eff = MatrixUtils::Hist2Vec(heff);
  TVectorD Pt  = MatrixUtils::ElemDiv(MatrixUtils::Hist2Vec(hMt), eff); // P(t)
  TMatrixD Prt = MatrixUtils::DivRowsByVector(M, Pt);  // P(r|t)

  // Compute initial sampling volume and do MCMC sampling
  TGraphAsymmErrors *box = HyperBox(hTmc);
  SetGraphProps(box, kGreen+2, kNone, kSpring, kFullSquare, 1.0);

  // Likelihood functor
  LogPoissonLikeFn llfunc(Prt, D);

  // Curvature regularization.
  // Note that this is not directly penalizing curvature of the solution.
  // Instead it smooths the solution divided by the trial spectrum.
  std::vector<double> regpars;
  regpars.push_back(alpha);  // Regularization strength
  for (int i=0; i<box->GetN(); i++)
    regpars.push_back(box->GetY()[i]);

  CurvatureRegFn regfunc(regpars);

  TTree *tmcmc = SampleMH(nMcmcSamples, 1e4, 0.01, box, llfunc, regfunc);

  // Create marginal prob. distributions from MCMC
  std::cout << Form("Marginalizing parameters from Markov chain...")
            << std::flush;

  TH1D *hMCMC[Nt];
  for (int t=0; t<Nt; t++)
  {
    double tlo = box->GetY()[t] - box->GetEYlow()[t];
    double thi = box->GetY()[t] + box->GetEYhigh()[t];
    hMCMC[t] = new TH1D(Form("hMCMC%d",t),"",nMcmcBins, tlo, thi);
    hMCMC[t]->SetTitle(Form("MCMC - point %d;"
                            "entries;"
                            "Marginal posterior probability",t));

    // Marginalize with unit weight when using MCMC, weight by
    // likelihood if sampling was uniform.
    tmcmc->Draw(Form("T%d >> hMCMC%d",t,t), "", "goff");
    hMCMC[t]->Scale(1./hMCMC[t]->Integral(1, nMcmcBins));
    SetHistProps(hMCMC[t], kBlack, kYellow, kBlack, kFullCircle, 1.0);
    hMCMC[t]->GetYaxis()->SetTitleOffset(1.5);
  }
  Printf("Done marginalizing MCMC.");

  // Now compute reduced sampling volume, and do uniform sampling
  TGraphAsymmErrors *rbox = ReducedSamplingVolume(hMCMC, box);
  SetGraphProps(rbox, kBlack, kNone, kNone, kFullSquare, 1.0);
  TH1D *hFlat[Nt];
  if (doUniformSampling)
  {
    TTree *tflat = SampleUniform(nFlatSamples, D, Prt, rbox);
    std::cout << Form("Marginalizing parameters from uniform volume...")
              << std::flush;

    for (int t=0; t<Nt; t++)
    {
      double tlo = rbox->GetY()[t] - rbox->GetEYlow()[t];
      double thi = rbox->GetY()[t] + rbox->GetEYhigh()[t];
      hFlat[t] = new TH1D(Form("hFlat%d",t),"",nFlatBins, tlo, thi);
      hFlat[t]->SetTitle(Form("Uniform sampling - point %d;"
                              "dijet mass (GeV/c^{2});"
                              "Marginal posterior probability",t));

      tflat->Draw(Form("T%d >> hFlat%d",t,t), "L", "goff");
      hFlat[t]->Scale(1./hFlat[t]->Integral(1,nFlatBins));
      SetHistProps(hFlat[t], kBlack, kOrange, kBlack, kFullCircle, 1.0);
    }
    Printf("Done marginalizing uniform volume.");
  }

  // Unfolded spectrum from MCMC
  TGraphErrors *unf1 = new TGraphErrors();
  SetGraphProps(unf1, kBlue, kNone, kBlue, kOpenSquare, 1.5);
  unf1->SetLineWidth(2);
  for (int t=0; t<Nt; t++)
  {
    MaxDensityInterval mdi = GetMDI(hMCMC[t], 0.68);
    unf1->SetPoint(t, hD->GetBinCenter(t+1), mdi.u);
    unf1->SetPointError(t, 0.48*hD->GetBinWidth(t+1), mdi.du);
  }

  // Unfolded spectrum from uniform sampling after volume reduction
  TGraphErrors *unf2 = 0;
  if (doUniformSampling)
  {
    unf2 = new TGraphErrors();
    SetGraphProps(unf2, kRed, kNone, kRed, kOpenSquare, 1.5);
    unf2->SetLineWidth(2);

    for (int t=0; t<Nt; t++)
    {
      MaxDensityInterval mdi = GetMDI(hFlat[t], 0.68);
      unf2->SetPoint(t, hD->GetBinCenter(t+1), mdi.u);
      unf2->SetPointError(t, 0.47*hD->GetBinWidth(t+1), mdi.du);
    }
  }

  Printf("Drawing results...");
  DrawObject(hM, "colz", "matrix", cList, 550, 500);
  gPad->SetLogx();  gPad->SetLogy();  gPad->SetLogz();
  gPad->SetRightMargin(0.15);

  DrawObject(heff, "", "efficiency", cList);

  // Draw marginal dists. from MCMC
  for (int t=0; t<Nt; t++)
  {
    DrawObject(hMCMC[t], "", Form("post_%d", t), cList);
    gPad->SetLeftMargin(0.15);

    if (doUniformSampling)
    {
      hFlat[t]->Scale(1./hFlat[t]->Integral(1, nFlatBins,"width"));
      hFlat[t]->Draw("same");
    }

    double ymin = hMCMC[t]->GetMinimum();
    double ymax = hMCMC[t]->GetMaximum();
    double yDraw = 0.25*(ymax-ymin);
    DataPoint(hD, hMCMC[t], t, 0.75*yDraw)->Draw("ep same");
    TruePoint(hT, hMCMC[t], t, yDraw)->Draw("p same");
    MD68Point(hMCMC[t], yDraw)->Draw("ep same");
  }

  // Result!
  hT->GetYaxis()->SetRangeUser(0.002, 101*nevts*evtWeight);
  DrawObject(hT, "ep", "result", cList);
  gPad->SetLogy();
  box->Draw("e5 same");
  if (doUniformSampling || drawReducedVolume)
    rbox->Draw("e5 same");
  hT->Draw("same");
  hD->Draw("ep same");
  unf1->Draw("ep same");
  if (unf2)
    unf2->Draw("ep same");

  if (printPDFs)
  {
    PrintPDFs(cList, "pdfs"); // Print individuals into ./pdfs dir
    PrintPDF(cList, "pdfs/mcmc_unfold_example"); // Multipage PDF
  }

  Printf("All done.");
  watch.Stop();
  watch.Print();

  return;
}