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