]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONTrack.cxx
TrackChi2MCS function: covariance matrix better calculated,
[u/mrichter/AliRoot.git] / MUON / AliMUONTrack.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /*
17 $Log$
18 Revision 1.6  2000/07/20 12:45:27  gosset
19 New "EventReconstructor..." structure,
20         hopefully more adapted to tree/streamer.
21 "AliMUONEventReconstructor::RemoveDoubleTracks"
22         to keep only one track among similar ones.
23
24 Revision 1.5  2000/07/18 16:04:06  gosset
25 AliMUONEventReconstructor package:
26 * a few minor modifications and more comments
27 * a few corrections
28   * right sign for Z of raw clusters
29   * right loop over chambers inside station
30   * symmetrized covariance matrix for measurements (TrackChi2MCS)
31   * right sign of charge in extrapolation (ExtrapToZ)
32   * right zEndAbsorber for Branson correction below 3 degrees
33 * use of TVirtualFitter instead of TMinuit for AliMUONTrack::Fit
34 * no parameter for AliMUONTrack::Fit() but more fit parameters in Track object
35
36 Revision 1.4  2000/06/30 10:15:48  gosset
37 Changes to EventReconstructor...:
38 precision fit with multiple Coulomb scattering;
39 extrapolation to vertex with Branson correction in absorber (JPC)
40
41 Revision 1.3  2000/06/25 13:23:28  hristov
42 stdlib.h needed for non-Linux compilation
43
44 Revision 1.2  2000/06/15 07:58:48  morsch
45 Code from MUON-dev joined
46
47 Revision 1.1.2.3  2000/06/12 10:11:34  morsch
48 Dummy copy constructor and assignment operator added
49
50 Revision 1.1.2.2  2000/06/09 12:58:05  gosset
51 Removed comment beginnings in Log sections of .cxx files
52 Suppressed most violations of coding rules
53
54 Revision 1.1.2.1  2000/06/07 14:44:53  gosset
55 Addition of files for track reconstruction in C++
56 */
57
58 //__________________________________________________________________________
59 //
60 // Reconstructed track in ALICE dimuon spectrometer
61 //__________________________________________________________________________
62
63 #include "AliMUONTrack.h"
64
65 #include <iostream.h>
66
67 #include <TClonesArray.h>
68 #include <TMath.h>
69 #include <TMatrix.h>
70 #include <TObjArray.h>
71 #include <TVirtualFitter.h>
72
73 #include "AliMUONEventReconstructor.h" 
74 #include "AliMUONHitForRec.h" 
75 #include "AliMUONSegment.h" 
76 #include "AliMUONTrackHit.h"
77
78 #include <stdlib.h>
79
80 // Functions to be minimized with Minuit
81 void TrackChi2(Int_t &NParam, Double_t *Gradient, Double_t &Chi2, Double_t *Param, Int_t Flag);
82 void TrackChi2MCS(Int_t &NParam, Double_t *Gradient, Double_t &Chi2, Double_t *Param, Int_t Flag);
83
84 Double_t MultipleScatteringAngle2(AliMUONTrackHit *TrackHit);
85
86 ClassImp(AliMUONTrack) // Class implementation in ROOT context
87
88 TVirtualFitter* AliMUONTrack::fgFitter = NULL; 
89
90   //__________________________________________________________________________
91 AliMUONTrack::AliMUONTrack(AliMUONSegment* BegSegment, AliMUONSegment* EndSegment, AliMUONEventReconstructor* EventReconstructor)
92 {
93   // Constructor from two Segment's
94   fEventReconstructor = EventReconstructor; // link back to EventReconstructor
95   // memory allocation for the TObjArray of pointers to reconstructed TrackHit's
96   fTrackHitsPtr = new TObjArray(10);
97   fNTrackHits = 0;
98   AddSegment(BegSegment); // add hits from BegSegment
99   AddSegment(EndSegment); // add hits from EndSegment
100   fTrackHitsPtr->Sort(); // sort TrackHits according to increasing Z
101   SetTrackParamAtVertex(); // set track parameters at vertex
102   // set fit conditions...
103   fFitMCS = 0;
104   fFitNParam = 3;
105   fFitStart = 1;
106   fFitFMin = -1.0;
107   return;
108 }
109
110   //__________________________________________________________________________
111 AliMUONTrack::AliMUONTrack(AliMUONSegment* Segment, AliMUONHitForRec* HitForRec, AliMUONEventReconstructor* EventReconstructor)
112 {
113   // Constructor from one Segment and one HitForRec
114   fEventReconstructor = EventReconstructor; // link back to EventReconstructor
115   // memory allocation for the TObjArray of pointers to reconstructed TrackHit's
116   fTrackHitsPtr = new TObjArray(10);
117   fNTrackHits = 0;
118   AddSegment(Segment); // add hits from Segment
119   AddHitForRec(HitForRec); // add HitForRec
120   fTrackHitsPtr->Sort(); // sort TrackHits according to increasing Z
121   SetTrackParamAtVertex(); // set track parameters at vertex
122   // set fit conditions...
123   fFitMCS = 0;
124   fFitNParam = 3;
125   fFitStart = 1;
126   fFitFMin = -1.0;
127   return;
128 }
129
130   //__________________________________________________________________________
131 AliMUONTrack::~AliMUONTrack()
132 {
133   // Destructor
134   if (fTrackHitsPtr) {
135     delete fTrackHitsPtr; // delete the TObjArray of pointers to TrackHit's
136     fTrackHitsPtr = NULL;
137   }
138 }
139
140   //__________________________________________________________________________
141 AliMUONTrack::AliMUONTrack (const AliMUONTrack& MUONTrack)
142 {
143 // Dummy copy constructor
144 }
145
146   //__________________________________________________________________________
147 AliMUONTrack & AliMUONTrack::operator=(const AliMUONTrack& MUONTrack)
148 {
149 // Dummy assignment operator
150     return *this;
151 }
152
153   //__________________________________________________________________________
154 void AliMUONTrack::Remove()
155 {
156   // Remove current track from array of tracks,
157   // and corresponding track hits from array of track hits.
158   // Compress the TClonesArray it belongs to.
159   AliMUONTrackHit *nextTrackHit;
160   AliMUONEventReconstructor *eventRec = this->fEventReconstructor;
161   TClonesArray *trackHitsPtr = eventRec->GetRecTrackHitsPtr();
162   // Loop over all track hits of track
163   AliMUONTrackHit *trackHit = (AliMUONTrackHit*) fTrackHitsPtr->First();
164   while (trackHit) {
165     nextTrackHit = (AliMUONTrackHit*) fTrackHitsPtr->After(trackHit);
166     // Remove TrackHit from event TClonesArray.
167     // Destructor is called,
168     // hence links between HitForRec's and TrackHit's are updated
169     trackHitsPtr->Remove(trackHit);
170     trackHit = nextTrackHit;
171   }
172   // Remove the track from event TClonesArray
173   // Destructor is called,
174   // hence space for TObjArray of pointers to TrackHit's is freed
175   eventRec->GetRecTracksPtr()->Remove(this);
176   // Number of tracks decreased by 1
177   eventRec->SetNRecTracks(eventRec->GetNRecTracks() - 1);
178   // Compress event TClonesArray of Track's:
179   // this is essential to retrieve the TClonesArray afterwards
180   eventRec->GetRecTracksPtr()->Compress();
181   // Compress event TClonesArray of TrackHit's:
182   // this is probably also essential to retrieve the TClonesArray afterwards
183   trackHitsPtr->Compress();
184 }
185
186   //__________________________________________________________________________
187 void AliMUONTrack::SetFitMCS(Int_t FitMCS)
188 {
189   // Set multiple Coulomb scattering option for track fit "fFitMCS"
190   // from "FitMCS" argument: 0 without, 1 with
191   if ((FitMCS == 0) || (FitMCS == 1)) fFitMCS = FitMCS;
192   // better implementation with enum(with, without) ????
193   else {
194     cout << "ERROR in AliMUONTrack::SetFitMCS(FitMCS)" << endl;
195     cout << "FitMCS = " << FitMCS << " is neither 0 nor 1" << endl;
196     exit(0);
197   }
198   return;
199 }
200
201   //__________________________________________________________________________
202 void AliMUONTrack::SetFitNParam(Int_t FitNParam)
203 {
204   // Set number of parameters for track fit "fFitNParam" from "FitNParam":
205   // 3 for momentum, 5 for momentum and position
206   if ((FitNParam == 3) || (FitNParam == 5)) fFitNParam = FitNParam;
207   else {
208     cout << "ERROR in AliMUONTrack::SetFitNParam(FitNParam)" << endl;
209     cout << "FitNParam = " << FitNParam << " is neither 3 nor 5" << endl;
210     exit(0);
211   }
212   return;
213 }
214
215   //__________________________________________________________________________
216 void AliMUONTrack::SetFitStart(Int_t FitStart)
217 {
218   // Set multiple Coulomb scattering option for track fit "fFitStart"
219   // from "FitStart" argument: 0 without, 1 with
220   if ((FitStart == 0) || (FitStart == 1)) fFitStart = FitStart;
221   // better implementation with enum(vertex, firstHit) ????
222   else {
223     cout << "ERROR in AliMUONTrack::SetFitStart(FitStart)" << endl;
224     cout << "FitStart = " << FitStart << " is neither 0 nor 1" << endl;
225     exit(0);
226   }
227   return;
228 }
229
230   //__________________________________________________________________________
231 AliMUONTrackParam* AliMUONTrack::GetTrackParamAtFirstHit(void) {
232   // Get pointer to TrackParamAtFirstHit
233   return ((AliMUONTrackHit*) (fTrackHitsPtr->First()))->GetTrackParam();}
234
235   //__________________________________________________________________________
236 void AliMUONTrack::RecursiveDump(void)
237 {
238   // Recursive dump of AliMUONTrack, i.e. with dump of TrackHit's and HitForRec's
239   AliMUONTrackHit *trackHit;
240   AliMUONHitForRec *hitForRec;
241   cout << "Recursive dump of Track: " << this << endl;
242   // Track
243   this->Dump();
244   for (Int_t trackHitIndex = 0; trackHitIndex < fNTrackHits; trackHitIndex++) {
245     trackHit = (AliMUONTrackHit*) ((*fTrackHitsPtr)[trackHitIndex]);
246     // TrackHit
247     cout << "TrackHit: " << trackHit << " (index: " << trackHitIndex << ")" << endl;
248     trackHit->Dump();
249     hitForRec = trackHit->GetHitForRecPtr();
250     // HitForRec
251     cout << "HitForRec: " << hitForRec << endl;
252     hitForRec->Dump();
253   }
254   return;
255 }
256
257   //__________________________________________________________________________
258 Int_t AliMUONTrack::HitsInCommon(AliMUONTrack* Track)
259 {
260   // Returns the number of hits in common
261   // between the current track ("this")
262   // and the track pointed to by "Track".
263   Int_t hitsInCommon = 0;
264   AliMUONTrackHit *trackHit1, *trackHit2;
265   // Loop over hits of first track
266   trackHit1 = (AliMUONTrackHit*) this->GetTrackHitsPtr()->First();
267   while (trackHit1) {
268     // Loop over hits of second track
269     trackHit2 = (AliMUONTrackHit*) Track->GetTrackHitsPtr()->First();
270     while (trackHit2) {
271       // Increment "hitsInCommon" if both TrackHits point to the same HitForRec
272       if ( (trackHit1->GetHitForRecPtr()) ==
273            (trackHit2->GetHitForRecPtr())    ) hitsInCommon++;
274       trackHit2 = (AliMUONTrackHit*) Track->GetTrackHitsPtr()->After(trackHit2);
275     } // trackHit2
276     trackHit1 = (AliMUONTrackHit*) this->GetTrackHitsPtr()->After(trackHit1);
277   } // trackHit1
278   return hitsInCommon;
279 }
280
281   //__________________________________________________________________________
282 void AliMUONTrack::Fit()
283 {
284   // Fit the current track ("this"),
285   // with or without multiple Coulomb scattering according to "fFitMCS",
286   // with the number of parameters given by "fFitNParam"
287   // (3 if one keeps X and Y fixed in "TrackParam", 5 if one lets them vary),
288   // starting, according to "fFitStart",
289   // with track parameters at vertex or at the first TrackHit.
290   // "fFitMCS", "fFitNParam" and "fFitStart" have to be set before
291   // by calling the corresponding Set methods.
292   Double_t arg[1], benC, errorParam, invBenP, lower, nonBenC, upper, x, y;
293   char parName[50];
294   AliMUONTrackParam *trackParam;
295   // Check if Minuit is initialized...
296   fgFitter = TVirtualFitter::Fitter(this); // add 3 or 5 for the maximum number of parameters ???
297   fgFitter->Clear(); // necessary ???? probably yes
298   // how to reset the printout number at every fit ????
299   // is there any risk to leave it like that ????
300   // how to go faster ???? choice of Minuit parameters like EDM ????
301   // choice of function to be minimized according to fFitMCS
302   if (fFitMCS == 0) fgFitter->SetFCN(TrackChi2);
303   else fgFitter->SetFCN(TrackChi2MCS);
304   arg[0] = 1;
305   fgFitter->ExecuteCommand("SET PRINT", arg, 1); // More printing !!!!
306   // Parameters according to "fFitStart"
307   // (should be a function to be used at every place where needed ????)
308   if (fFitStart == 0) trackParam = &fTrackParamAtVertex;
309   else trackParam = this->GetTrackParamAtFirstHit();
310   // set first 3 Minuit parameters
311   // could be tried with no limits for the search (min=max=0) ????
312   fgFitter->SetParameter(0, "InvBenP",
313                          trackParam->GetInverseBendingMomentum(),
314                          0.003, -0.4, 0.4);
315   fgFitter->SetParameter(1, "BenS",
316                          trackParam->GetBendingSlope(),
317                          0.001, -0.5, 0.5);
318   fgFitter->SetParameter(2, "NonBenS",
319                          trackParam->GetNonBendingSlope(),
320                          0.001, -0.5, 0.5);
321   if (fFitNParam == 5) {
322     // set last 2 Minuit parameters (no limits for the search: min=max=0)
323     fgFitter->SetParameter(3, "X",
324                            trackParam->GetNonBendingCoor(),
325                            0.03, 0.0, 0.0);
326     fgFitter->SetParameter(4, "Y",
327                            trackParam->GetBendingCoor(),
328                            0.10, 0.0, 0.0);
329   }
330   // search without gradient calculation in the function
331   fgFitter->ExecuteCommand("SET NOGRADIENT", arg, 0);
332   // minimization
333   fgFitter->ExecuteCommand("MINIMIZE", arg, 0);
334   // exit from Minuit
335   fgFitter->ExecuteCommand("EXIT", arg, 0); // necessary ????
336   // get results into "invBenP", "benC", "nonBenC" ("x", "y")
337   fgFitter->GetParameter(0, parName, invBenP, errorParam, lower, upper);
338   fgFitter->GetParameter(1, parName, benC, errorParam, lower, upper);
339   fgFitter->GetParameter(2, parName, nonBenC, errorParam, lower, upper);
340   if (fFitNParam == 5) {
341     fgFitter->GetParameter(3, parName, x, errorParam, lower, upper);
342     fgFitter->GetParameter(4, parName, y, errorParam, lower, upper);
343   }
344   // result of the fit into track parameters
345   trackParam->SetInverseBendingMomentum(invBenP);
346   trackParam->SetBendingSlope(benC);
347   trackParam->SetNonBendingSlope(nonBenC);
348   if (fFitNParam == 5) {
349     trackParam->SetNonBendingCoor(x);
350     trackParam->SetBendingCoor(y);
351   }
352   // global result of the fit
353   Double_t fedm, errdef;
354   Int_t npari, nparx;
355   fgFitter->GetStats(fFitFMin, fedm, errdef, npari, nparx);
356 }
357
358   //__________________________________________________________________________
359 void AliMUONTrack::AddSegment(AliMUONSegment* Segment)
360 {
361   // Add Segment to the track
362   AddHitForRec(Segment->GetHitForRec1()); // 1st hit
363   AddHitForRec(Segment->GetHitForRec2()); // 2nd hit
364 }
365
366   //__________________________________________________________________________
367 void AliMUONTrack::AddHitForRec(AliMUONHitForRec* HitForRec)
368 {
369   // Add HitForRec to the track:
370   // actual TrackHit into TClonesArray of TrackHit's for the event;
371   // pointer to actual TrackHit in TObjArray of pointers to TrackHit's for the track
372   TClonesArray *recTrackHitsPtr = this->fEventReconstructor->GetRecTrackHitsPtr();
373   Int_t eventTrackHits = this->fEventReconstructor->GetNRecTrackHits();
374   // event
375   AliMUONTrackHit* trackHit =
376     new ((*recTrackHitsPtr)[eventTrackHits]) AliMUONTrackHit(HitForRec);
377   this->fEventReconstructor->SetNRecTrackHits(eventTrackHits + 1);
378   // track
379   fTrackHitsPtr->Add(trackHit);
380   fNTrackHits++;
381 }
382
383   //__________________________________________________________________________
384 void AliMUONTrack::SetTrackParamAtHit(Int_t indexHit, AliMUONTrackParam *TrackParam)
385 {
386   // Set track parameters at TrackHit with index "indexHit"
387   // from the track parameters pointed to by "TrackParam".
388   AliMUONTrackHit* trackHit = (AliMUONTrackHit*) ((*fTrackHitsPtr)[indexHit]);
389   trackHit->SetTrackParam(TrackParam);
390 }
391
392   //__________________________________________________________________________
393 void AliMUONTrack::SetTrackParamAtVertex()
394 {
395   // Set track parameters at vertex.
396   // TrackHit's are assumed to be only in stations(1..) 4 and 5,
397   // and sorted according to increasing Z..
398   // Parameters are calculated from information in HitForRec's
399   // of first and last TrackHit's.
400   AliMUONTrackParam *trackParam =
401     &fTrackParamAtVertex; // pointer to track parameters
402   // Pointer to HitForRec of first TrackHit
403   AliMUONHitForRec *firstHit =
404     ((AliMUONTrackHit*) (fTrackHitsPtr->First()))->GetHitForRecPtr();
405   // Pointer to HitForRec of last TrackHit
406   AliMUONHitForRec *lastHit =
407     ((AliMUONTrackHit*) (fTrackHitsPtr->Last()))->GetHitForRecPtr();
408   // Z difference between first and last hits
409   Double_t deltaZ = firstHit->GetZ() - lastHit->GetZ();
410   // bending slope in stations(1..) 4 and 5
411   Double_t bendingSlope =
412     (firstHit->GetBendingCoor() - lastHit->GetBendingCoor()) / deltaZ;
413   trackParam->SetBendingSlope(bendingSlope);
414   // impact parameter
415   Double_t impactParam =
416     firstHit->GetBendingCoor() - bendingSlope * firstHit->GetZ(); // same if from firstHit and  lastHit ????
417   // signed bending momentum
418   Double_t signedBendingMomentum =
419     fEventReconstructor->GetBendingMomentumFromImpactParam(impactParam);
420   trackParam->SetInverseBendingMomentum(1.0 / signedBendingMomentum);
421   // bending slope at vertex
422   trackParam->
423     SetBendingSlope(bendingSlope +
424                     impactParam / fEventReconstructor->GetSimpleBPosition());
425   // non bending slope
426   Double_t nonBendingSlope =
427     (firstHit->GetNonBendingCoor() - lastHit->GetNonBendingCoor()) / deltaZ;
428   trackParam->SetNonBendingSlope(nonBendingSlope);
429   // vertex coordinates at (0,0,0)
430   trackParam->SetZ(0.0);
431   trackParam->SetBendingCoor(0.0);
432   trackParam->SetNonBendingCoor(0.0);
433 }
434
435   //__________________________________________________________________________
436 void TrackChi2(Int_t &NParam, Double_t *Gradient, Double_t &Chi2, Double_t *Param, Int_t Flag)
437 {
438   // Return the "Chi2" to be minimized with Minuit for track fitting,
439   // with "NParam" parameters
440   // and their current values in array pointed to by "Param".
441   // Assumes that the track hits are sorted according to increasing Z.
442   // Track parameters at each TrackHit are updated accordingly.
443   // Multiple Coulomb scattering is not taken into account
444   AliMUONTrack *trackBeingFitted;
445   AliMUONTrackHit* hit;
446   AliMUONTrackParam param1;
447   Int_t hitNumber;
448   Double_t zHit;
449   Chi2 = 0.0; // initialize Chi2
450   // copy of track parameters to be fitted
451   trackBeingFitted = (AliMUONTrack*) AliMUONTrack::Fitter()->GetObjectFit();
452   if (trackBeingFitted->GetFitStart() == 0)
453     param1 = *(trackBeingFitted->GetTrackParamAtVertex());
454   else param1 = *(trackBeingFitted->GetTrackParamAtFirstHit());
455   // Minuit parameters to be fitted into this copy
456   param1.SetInverseBendingMomentum(Param[0]);
457   param1.SetBendingSlope(Param[1]);
458   param1.SetNonBendingSlope(Param[2]);
459   if (NParam == 5) {
460     param1.SetNonBendingCoor(Param[3]);
461     param1.SetBendingCoor(Param[4]);
462   }
463   // Follow track through all planes of track hits
464   for (hitNumber = 0; hitNumber < trackBeingFitted->GetNTrackHits(); hitNumber++) {
465     hit = (AliMUONTrackHit*) (*(trackBeingFitted->GetTrackHitsPtr()))[hitNumber];
466     zHit = hit->GetHitForRecPtr()->GetZ();
467     // do something special if 2 hits with same Z ????
468     // security against infinite loop ????
469     (&param1)->ExtrapToZ(zHit); // extrapolation
470     hit->SetTrackParam(&param1);
471     // Increment Chi2
472     // done hit per hit, with hit resolution,
473     // and not with point and angle like in "reco_muon.F" !!!!
474     // Needs to add multiple scattering contribution ????
475     Double_t dX =
476       hit->GetHitForRecPtr()->GetNonBendingCoor() - (&param1)->GetNonBendingCoor();
477     Double_t dY =
478       hit->GetHitForRecPtr()->GetBendingCoor() - (&param1)->GetBendingCoor();
479     Chi2 =
480       Chi2 +
481       dX * dX / hit->GetHitForRecPtr()->GetNonBendingReso2() +
482       dY * dY / hit->GetHitForRecPtr()->GetBendingReso2();
483   }
484 }
485
486   //__________________________________________________________________________
487 void TrackChi2MCS(Int_t &NParam, Double_t *Gradient, Double_t &Chi2, Double_t *Param, Int_t Flag)
488 {
489   // Return the "Chi2" to be minimized with Minuit for track fitting,
490   // with "NParam" parameters
491   // and their current values in array pointed to by "Param".
492   // Assumes that the track hits are sorted according to increasing Z.
493   // Track parameters at each TrackHit are updated accordingly.
494   // Multiple Coulomb scattering is taken into account with covariance matrix.
495   AliMUONTrack *trackBeingFitted;
496   AliMUONTrackParam param1;
497   Chi2 = 0.0; // initialize Chi2
498   // copy of track parameters to be fitted
499   trackBeingFitted = (AliMUONTrack*) AliMUONTrack::Fitter()->GetObjectFit();
500   if (trackBeingFitted->GetFitStart() == 0)
501     param1 = *(trackBeingFitted->GetTrackParamAtVertex());
502   else param1 = *(trackBeingFitted->GetTrackParamAtFirstHit());
503   // Minuit parameters to be fitted into this copy
504   param1.SetInverseBendingMomentum(Param[0]);
505   param1.SetBendingSlope(Param[1]);
506   param1.SetNonBendingSlope(Param[2]);
507   if (NParam == 5) {
508     param1.SetNonBendingCoor(Param[3]);
509     param1.SetBendingCoor(Param[4]);
510   }
511
512   AliMUONTrackHit *hit;
513   Bool_t goodDeterminant;
514   Int_t chCurrent, chPrev, hitNumber, hitNumber1, hitNumber2, hitNumber3;
515   Double_t z, z1, z2, z3;
516   AliMUONTrackHit *hit1, *hit2, *hit3;
517   Double_t hbc1, hbc2, pbc1, pbc2;
518   Double_t hnbc1, hnbc2, pnbc1, pnbc2;
519   Int_t numberOfHit = trackBeingFitted->GetNTrackHits();
520   TMatrix *covBending = new TMatrix(numberOfHit, numberOfHit);
521   TMatrix *covNonBending = new TMatrix(numberOfHit, numberOfHit);
522   Double_t *msa2 = new Double_t[numberOfHit];
523
524   // Predicted coordinates and  multiple scattering angles are first calculated
525   for (hitNumber = 0; hitNumber < numberOfHit; hitNumber++) {
526     hit = (AliMUONTrackHit*) (*(trackBeingFitted->GetTrackHitsPtr()))[hitNumber];
527     z = hit->GetHitForRecPtr()->GetZ();
528     // do something special if 2 hits with same Z ????
529     // security against infinite loop ????
530     (&param1)->ExtrapToZ(z); // extrapolation
531     hit->SetTrackParam(&param1);
532     // square of multiple scattering angle at current hit, with one chamber
533     msa2[hitNumber] = MultipleScatteringAngle2(hit);
534     // correction for eventual missing hits or multiple hits in a chamber,
535     // according to the number of chambers
536     // between the current hit and the previous one
537     chCurrent = hit->GetHitForRecPtr()->GetChamberNumber();
538     if (hitNumber > 0) msa2[hitNumber] = msa2[hitNumber] * (chCurrent - chPrev);
539     chPrev = chCurrent;
540   }
541
542   // Calculates the covariance matrix
543   for (hitNumber1 = 0; hitNumber1 < numberOfHit; hitNumber1++) { 
544     hit1 = (AliMUONTrackHit*) (*(trackBeingFitted->GetTrackHitsPtr()))[hitNumber1];
545     z1 = hit1->GetHitForRecPtr()->GetZ();
546     for (hitNumber2 = hitNumber1; hitNumber2 < numberOfHit; hitNumber2++) {
547       hit2 = (AliMUONTrackHit*) (*(trackBeingFitted->GetTrackHitsPtr()))[hitNumber2];
548       z2 = hit2->GetHitForRecPtr()->GetZ();
549       // initialization to 0 (diagonal plus upper triangular part)
550       (*covBending)(hitNumber2, hitNumber1) = 0.0;
551       // contribution from multiple scattering in bending plane:
552       // loop over upstream hits
553       for (hitNumber3 = 0; hitNumber3 < hitNumber1; hitNumber3++) {     
554         hit3 = (AliMUONTrackHit*)
555           (*(trackBeingFitted->GetTrackHitsPtr()))[hitNumber3];
556         z3 = hit3->GetHitForRecPtr()->GetZ();
557         (*covBending)(hitNumber2, hitNumber1) =
558           (*covBending)(hitNumber2, hitNumber1) +
559           ((z1 - z3) * (z2 - z3) * msa2[hitNumber3]); 
560       }
561       // equal contribution from multiple scattering in non bending plane
562       (*covNonBending)(hitNumber2, hitNumber1) =
563         (*covBending)(hitNumber2, hitNumber1);
564       if (hitNumber1 == hitNumber2) {
565         // Diagonal elements: add contribution from position measurements
566         // in bending plane
567         (*covBending)(hitNumber2, hitNumber1) =
568           (*covBending)(hitNumber2, hitNumber1) +
569           hit1->GetHitForRecPtr()->GetBendingReso2();
570         // and in non bending plane
571         (*covNonBending)(hitNumber2, hitNumber1) =
572           (*covNonBending)(hitNumber2, hitNumber1) +
573           hit1->GetHitForRecPtr()->GetNonBendingReso2();
574       }
575       else {
576         // Non diagonal elements: symmetrization
577         // for bending plane
578         (*covBending)(hitNumber1, hitNumber2) =
579           (*covBending)(hitNumber2, hitNumber1);
580         // and non bending plane
581         (*covNonBending)(hitNumber1, hitNumber2) =
582           (*covNonBending)(hitNumber2, hitNumber1);
583       }
584     } // for (hitNumber2 = hitNumber1;...
585   } // for (hitNumber1 = 0;...
586
587   // Inverts covariance matrix 
588   goodDeterminant = kTRUE;
589   // check whether the Invert method returns flag if matrix cannot be inverted,
590   // and do not calculate the Determinant in that case !!!!
591   if (covBending->Determinant() != 0) {
592     covBending->Invert();
593   } else {
594     goodDeterminant = kFALSE;
595     cout << "Warning in ChiMCS  Determinant Bending=0: " << endl;  
596   }
597   if (covNonBending->Determinant() != 0) {
598     covNonBending->Invert();
599   } else {
600     goodDeterminant = kFALSE;
601     cout << "Warning in ChiMCS  Determinant non Bending=0: " << endl;  
602   }
603
604   // It would be worth trying to calculate the inverse of the covariance matrix
605   // only once per fit, since it cannot change much in principle,
606   // and it would save a lot of computing time !!!!
607   
608   // Calculates Chi2
609   if (goodDeterminant) {
610     // with Multiple Scattering if inversion correct
611     for (hitNumber1 = 0; hitNumber1 < numberOfHit ; hitNumber1++) { 
612       hit1 = (AliMUONTrackHit*) (*(trackBeingFitted->GetTrackHitsPtr()))[hitNumber1];
613       hbc1 = hit1->GetHitForRecPtr()->GetBendingCoor();
614       pbc1 = hit1->GetTrackParam()->GetBendingCoor();
615       hnbc1 = hit1->GetHitForRecPtr()->GetNonBendingCoor();
616       pnbc1 = hit1->GetTrackParam()->GetNonBendingCoor();
617       for (hitNumber2 = 0; hitNumber2 < numberOfHit; hitNumber2++) {
618         hit2 = (AliMUONTrackHit*)
619           (*(trackBeingFitted->GetTrackHitsPtr()))[hitNumber2];
620         hbc2 = hit2->GetHitForRecPtr()->GetBendingCoor();
621         pbc2 = hit2->GetTrackParam()->GetBendingCoor();
622         hnbc2 = hit2->GetHitForRecPtr()->GetNonBendingCoor();
623         pnbc2 = hit2->GetTrackParam()->GetNonBendingCoor();
624         Chi2 = Chi2 +
625           ((*covBending)(hitNumber2, hitNumber1) *
626            (hbc1 - pbc1) * (hbc2 - pbc2)) +
627           ((*covNonBending)(hitNumber2, hitNumber1) *
628            (hnbc1 - pnbc1) * (hnbc2 - pnbc2));
629       }
630     }
631   } else {
632     // without Multiple Scattering if inversion impossible
633     for (hitNumber1 = 0; hitNumber1 < numberOfHit ; hitNumber1++) { 
634       hit1 = (AliMUONTrackHit*) (*(trackBeingFitted->GetTrackHitsPtr()))[hitNumber1];
635       hbc1 = hit1->GetHitForRecPtr()->GetBendingCoor();
636       pbc1 = hit1->GetTrackParam()->GetBendingCoor();
637       hnbc1 = hit1->GetHitForRecPtr()->GetNonBendingCoor();
638       pnbc1 = hit1->GetTrackParam()->GetNonBendingCoor();
639       Chi2 = Chi2 + 
640         ((hbc1 - pbc1) * (hbc1 - pbc1) /
641          hit1->GetHitForRecPtr()->GetBendingReso2()) +
642         ((hnbc1 - pnbc1) * (hnbc1 - pnbc1) /
643          hit1->GetHitForRecPtr()->GetNonBendingReso2());
644     }
645   }
646   
647   delete covBending;
648   delete covNonBending;
649   delete [] msa2;
650 }
651
652 Double_t MultipleScatteringAngle2(AliMUONTrackHit *TrackHit)
653 {
654   // Returns square of multiple Coulomb scattering angle
655   // at TrackHit pointed to by "TrackHit"
656   Double_t slopeBending, slopeNonBending, radiationLength, inverseBendingMomentum2, inverseTotalMomentum2;
657   Double_t varMultipleScatteringAngle;
658   AliMUONTrack *trackBeingFitted = (AliMUONTrack*) AliMUONTrack::Fitter()->GetObjectFit();
659   AliMUONTrackParam *param = TrackHit->GetTrackParam();
660   // Better implementation in AliMUONTrack class ????
661   slopeBending = param->GetBendingSlope();
662   slopeNonBending = param->GetNonBendingSlope();
663   // thickness in radiation length for the current track,
664   // taking local angle into account
665   radiationLength =
666     trackBeingFitted->GetEventReconstructor()->GetChamberThicknessInX0() *
667     TMath::Sqrt(1.0 +
668                 slopeBending * slopeBending + slopeNonBending * slopeNonBending);
669   inverseBendingMomentum2 = 
670     param->GetInverseBendingMomentum() * param->GetInverseBendingMomentum();
671   inverseTotalMomentum2 =
672     inverseBendingMomentum2 * (1.0 + slopeBending * slopeBending) /
673     (1.0 + slopeBending *slopeBending + slopeNonBending * slopeNonBending); 
674   varMultipleScatteringAngle = 0.0136 * (1.0 + 0.038 * TMath::Log(radiationLength));
675   // The velocity is assumed to be 1 !!!!
676   varMultipleScatteringAngle = inverseTotalMomentum2 * radiationLength *
677     varMultipleScatteringAngle * varMultipleScatteringAngle;
678   return varMultipleScatteringAngle;
679 }