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