Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
fitCircle.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_fit
3 /// \notebook
4 /// Generate points distributed with some errors around a circle
5 /// Fit a circle through the points and draw
6 /// To run the script, do, eg
7 ///
8 /// ~~~{.cpp}
9 /// root > .x fitCircle.C (10000 points by default)
10 /// root > .x fitCircle.C(100); (with only 100 points
11 /// root > .x fitCircle.C++(100000); with ACLIC
12 /// ~~~
13 ///
14 /// \macro_image
15 /// \macro_output
16 /// \macro_code
17 ///
18 /// \author Rene Brun
19 
20 #include "TCanvas.h"
21 #include "TRandom3.h"
22 #include "TGraph.h"
23 #include "TMath.h"
24 #include "TArc.h"
25 #include "Fit/Fitter.h"
26 #include <Math/Functor.h>
27 
28 //____________________________________________________________________
29 void fitCircle(Int_t n=10000) {
30  //generates n points around a circle and fit them
31  TCanvas *c1 = new TCanvas("c1","c1",600,600);
32  c1->SetGrid();
33  TGraph* gr = new TGraph(n);
34  if (n> 999) gr->SetMarkerStyle(1);
35  else gr->SetMarkerStyle(3);
36  TRandom3 r;
37  Double_t x,y;
38  for (Int_t i=0;i<n;i++) {
39  r.Circle(x,y,r.Gaus(4,0.3));
40  gr->SetPoint(i,x,y);
41  }
42  c1->DrawFrame(-5,-5,5,5);
43  gr->Draw("p");
44 
45 
46  auto chi2Function = [&](const Double_t *par) {
47  //minimisation function computing the sum of squares of residuals
48  // looping at the graph points
49  Int_t np = gr->GetN();
50  Double_t f = 0;
51  Double_t *x = gr->GetX();
52  Double_t *y = gr->GetY();
53  for (Int_t i=0;i<np;i++) {
54  Double_t u = x[i] - par[0];
55  Double_t v = y[i] - par[1];
56  Double_t dr = par[2] - std::sqrt(u*u+v*v);
57  f += dr*dr;
58  }
59  return f;
60  };
61 
62  // wrap chi2 function in a function object for the fit
63  // 3 is the number of fit parameters (size of array par)
64  ROOT::Math::Functor fcn(chi2Function,3);
65  ROOT::Fit::Fitter fitter;
66 
67 
68  double pStart[3] = {0,0,1};
69  fitter.SetFCN(fcn, pStart);
70  fitter.Config().ParSettings(0).SetName("x0");
71  fitter.Config().ParSettings(1).SetName("y0");
72  fitter.Config().ParSettings(2).SetName("R");
73 
74  // do the fit
75  bool ok = fitter.FitFCN();
76  if (!ok) {
77  Error("line3Dfit","Line3D Fit failed");
78  }
79 
80  const ROOT::Fit::FitResult & result = fitter.Result();
81  result.Print(std::cout);
82 
83  //Draw the circle on top of the points
84  TArc *arc = new TArc(result.Parameter(0),result.Parameter(1),result.Parameter(2));
85  arc->SetLineColor(kRed);
86  arc->SetLineWidth(4);
87  arc->SetFillStyle(0);
88  arc->Draw();
89 }