LArSoft  v07_13_02
Liquid Argon Software toolkit - http://larsoft.org/
LinFitAlg.cxx
Go to the documentation of this file.
1 
11 extern "C" {
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 }
15 
17 
18 
19 namespace trkf{
20 
22 
24 
25 
26  void LinFitAlg::LinFit(std::vector<float>& x, std::vector<float>& y,
27  std::vector<float>& ey2, float& Intercept, float& Slope,
28  float& InterceptError, float& SlopeError, float& ChiDOF)
29  {
30  // fit a line ala Bevington linfit.F. The number of points fit is defined by
31  // the size of the y vector.
32 
33  ChiDOF = 999.;
34 
35  if(y.size() < 2) return;
36  if(x.size() < y.size() || ey2.size() < y.size()) return;
37 
38  double sum = 0.;
39  double sumx = 0.;
40  double sumy = 0.;
41  double sumxy = 0.;
42  double sumx2 = 0.;
43  double sumy2 = 0.;
44  double weight, arg;
45  unsigned short ii;
46 
47  for(ii = 0; ii < y.size(); ++ii) {
48  weight = 1. / ey2[ii];
49  sum += weight;
50  sumx += weight * x[ii];
51  sumy += weight * y[ii];
52  sumx2 += weight * x[ii] * x[ii];
53  sumxy += weight * x[ii] * y[ii];
54  sumy2 += weight * y[ii] * y[ii];
55  }
56  // calculate coefficients and std dev
57  double delta = sum * sumx2 - sumx * sumx;
58  if(delta == 0.) return;
59  double A = (sumx2 * sumy - sumx * sumxy) / delta;
60  double B = (sumxy * sum - sumx * sumy) / delta;
61  Intercept = A;
62  Slope = B;
63  if(x.size() == 2) {
64  ChiDOF = 0.;
65  return;
66  }
67  double ndof = x.size() - 2;
68  double varnce = (sumy2 + A*A*sum + B*B*sumx2 - 2 * (A*sumy + B*sumxy - A*B*sumx)) / ndof;
69  if(varnce > 0.) {
70  InterceptError = sqrt(varnce * sumx2 / delta);
71  SlopeError = sqrt(varnce * sum / delta);
72  } else {
73  InterceptError = 0.;
74  SlopeError = 0.;
75  }
76  sum = 0.;
77  // calculate chisq
78  for(ii = 0; ii < y.size(); ++ii) {
79  arg = y[ii] - A - B * x[ii];
80  sum += arg * arg / ey2[ii];
81  }
82  ChiDOF = sum / ndof;
83  } // LinFit
84 
85 } // namespace trkf
Float_t x
Definition: compare.C:6
Float_t y
Definition: compare.C:6
Int_t B
Definition: plot.C:25
virtual ~LinFitAlg()
Definition: LinFitAlg.cxx:23
double weight
Definition: plottest35.C:25
void LinFit(std::vector< float > &x, std::vector< float > &y, std::vector< float > &ey2, float &Intercept, float &Slope, float &InterceptError, float &SlopeError, float &ChiDOF)
Definition: LinFitAlg.cxx:26