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