]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ITS/AliITSAlignMille2.cxx
Minor updates in macros to check the SDD calibration files (F. Prino)
[u/mrichter/AliRoot.git] / ITS / AliITSAlignMille2.cxx
1 /**************************************************************************\r
2  * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. *\r
3  *                                                                        *\r
4  * Author: The ALICE Off-line Project.                                    *\r
5  * Contributors are mentioned in the code where appropriate.              *\r
6  *                                                                        *\r
7  * Permission to use, copy, modify and distribute this software and its   *\r
8  * documentation strictly for non-commercial purposes is hereby granted   *\r
9  * without fee, provided that the above copyright notice appears in all   *\r
10  * copies and that both the copyright notice and this permission notice   *\r
11  * appear in the supporting documentation. The authors make no claims     *\r
12  * about the suitability of this software for any purpose. It is          *\r
13  * provided "as is" without express or implied warranty.                  *\r
14  **************************************************************************/\r
15 \r
16 /* $Id$ */\r
17 \r
18 //-----------------------------------------------------------------------------\r
19 //\r
20 //  Interface to AliMillePede2 alignment class for the ALICE ITS detector\r
21 // \r
22 //  ITS specific alignment class which interface to AliMillepede.   \r
23 //  For each track ProcessTrack calculates the local and global derivatives\r
24 //  at each hit and fill the corresponding local equations. Provide methods for\r
25 //  fixing or constraining detection elements for best results. \r
26 // \r
27 //  author M. Lunardon (thanks to J. Castillo), ruben.shahoyan@cern.ch\r
28 //-----------------------------------------------------------------------------\r
29 \r
30 #include <TFile.h>\r
31 #include <TClonesArray.h>\r
32 #include <TMath.h>\r
33 #include <TVirtualFitter.h>\r
34 #include <TGeoManager.h>\r
35 #include <TArrayI.h>\r
36 #include <TSystem.h>\r
37 #include "AliITSAlignMille2.h"\r
38 #include "AliITSgeomTGeo.h"\r
39 #include "AliGeomManager.h"\r
40 #include "AliMillePede2.h"\r
41 #include "AliTrackPointArray.h"\r
42 #include "AliAlignObjParams.h"\r
43 #include "AliLog.h"\r
44 #include "AliTrackFitterRieman.h"\r
45 #include "AliITSAlignMille2Constraint.h"\r
46 #include "AliITSAlignMille2ConstrArray.h"\r
47 #include "AliITSresponseSDD.h"\r
48 \r
49 ClassImp(AliITSAlignMille2)\r
50 \r
51 const Char_t* AliITSAlignMille2::kRecKeys[] = {\r
52   "GEOMETRY_FILE",\r
53   "SUPERMODULE_FILE",\r
54   "CONSTRAINTS_REFERENCE_FILE",\r
55   "PREALIGNMENT_FILE",\r
56   "PRECALIBSDD_FILE",\r
57   "INITCALBSDD_FILE",\r
58   "SET_GLOBAL_DELTAS",\r
59   "CONSTRAINT_LOCAL",\r
60   "MODULE_VOLUID",\r
61   "MODULE_INDEX",\r
62   "SET_PSEUDO_PARENTS",\r
63   "SET_TRACK_FIT_METHOD",\r
64   "SET_MINPNT_TRA",\r
65   "SET_NSTDDEV",\r
66   "SET_RESCUT_INIT",\r
67   "SET_RESCUT_OTHER",\r
68   "SET_LOCALSIGMAFACTOR",\r
69   "SET_STARTFAC",\r
70   "SET_B_FIELD",\r
71   "SET_SPARSE_MATRIX",\r
72   "REQUIRE_POINT",\r
73   "CONSTRAINT_ORPHANS",\r
74   "CONSTRAINT_SUBUNITS",\r
75   "APPLY_CONSTRAINT"\r
76 };\r
77 \r
78 \r
79 //========================================================================================================\r
80 \r
81 AliITSAlignMille2* AliITSAlignMille2::fgInstance = 0;  \r
82 Int_t              AliITSAlignMille2::fgInstanceID = 0;\r
83 \r
84 //________________________________________________________________________________________________________\r
85 AliITSAlignMille2::AliITSAlignMille2(const Char_t *configFilename  ) \r
86 : TObject(),\r
87   fMillepede(0),\r
88   fStartFac(16.), \r
89   fResCutInitial(100.), \r
90   fResCut(100.),\r
91   fNGlobal(0),\r
92   fNLocal(4),\r
93   fNStdDev(3),\r
94   fIsMilleInit(kFALSE),\r
95   fAllowPseudoParents(kFALSE),\r
96   //\r
97   fCurrentModule(0),\r
98   fTrack(0),\r
99   fTrackBuff(0),\r
100   fCluster(),\r
101   fGlobalDerivatives(0), \r
102   //\r
103   fMinNPtsPerTrack(3),\r
104   fInitTrackParamsMeth(1),\r
105   fTotBadLocEqPoints(0),\r
106   fRieman(0),\r
107   //\r
108   fConstraints(0),\r
109   //\r
110   fUseGlobalDelta(kFALSE),\r
111   fRequirePoints(kFALSE),\r
112   fTempExcludedModule(-1),\r
113   //\r
114   fGeometryFileName("geometry.root"),\r
115   fPreAlignmentFileName(""),\r
116   fConstrRefFileName(""),\r
117   fGeoManager(0),\r
118   fIsConfigured(kFALSE),\r
119   fPreAlignQF(0),\r
120 //\r
121   fCorrectSDD(0),\r
122   fInitialRecSDD(0),\r
123   fPrealignment(0),\r
124   fConstrRef(0),\r
125   fMilleModule(2),\r
126   fSuperModule(2),\r
127   fNModules(0),\r
128   fNSuperModules(0),\r
129   fUsePreAlignment(kFALSE),\r
130   fBOn(kFALSE),\r
131   fBField(0.0),\r
132   fBug(0),\r
133   fMilleVersion(2)\r
134 {\r
135   /// main constructor that takes input from configuration file\r
136   for (int i=3;i--;) fSigmaFactor[i] = 1.0;\r
137   //\r
138   // new RS\r
139   for (Int_t i=0; i<6; i++) {\r
140     fNReqLayUp[i]=0;\r
141     fNReqLayDown[i]=0;\r
142     fNReqLay[i]=0;\r
143   }\r
144   for (Int_t i=0; i<3; i++) {\r
145     fNReqDetUp[i]=0;\r
146     fNReqDetDown[i]=0;\r
147     fNReqDet[i]=0;\r
148   }\r
149   //\r
150   Int_t lc=LoadConfig(configFilename);\r
151   if (lc) {\r
152     AliError(Form("Error %d loading configuration from %s",lc,configFilename));\r
153     exit(1);\r
154   }\r
155   //\r
156   fMillepede = new AliMillePede2();  \r
157   fgInstance = this;\r
158   fgInstanceID++;\r
159   //\r
160 }\r
161 \r
162 //________________________________________________________________________________________________________\r
163 AliITSAlignMille2::~AliITSAlignMille2()\r
164 {\r
165   /// Destructor\r
166   if (fMillepede)         delete fMillepede;            fMillepede = 0;\r
167   if (fGlobalDerivatives) delete[] fGlobalDerivatives;  fGlobalDerivatives = 0;\r
168   if (fRieman)            delete fRieman;               fRieman = 0;\r
169   if (fPrealignment)      delete fPrealignment;         fPrealignment = 0;\r
170   if (fConstrRef)         delete fConstrRef;            fConstrRef = 0;\r
171   if (fCorrectSDD)        delete fCorrectSDD;           fCorrectSDD = 0;\r
172   if (fInitialRecSDD)     delete fInitialRecSDD;        fInitialRecSDD = 0;\r
173   fTrackBuff.Delete();\r
174   fConstraints.Delete();\r
175   fMilleModule.Delete();\r
176   fSuperModule.Delete();\r
177   if (--fgInstanceID==0) fgInstance = 0;\r
178 }\r
179 \r
180 ///////////////////////////////////////////////////////////////////////\r
181 \r
182 \r
183 TObjArray* AliITSAlignMille2::GetConfigRecord(FILE* stream, TString& recTitle, TString& recOpt, Bool_t rew)\r
184 {\r
185   // read new record from config file\r
186   TString record;\r
187   static TObjArray* recElems = 0;\r
188   if (recElems) {delete recElems; recElems = 0;}\r
189   //\r
190   TString keyws = recTitle;\r
191   if (!keyws.IsNull()) {\r
192     keyws.ToUpper();\r
193     //    keyws += " ";\r
194   }\r
195   while (record.Gets(stream)) {\r
196     int cmt=record.Index("#"); \r
197     if (cmt>=0) record.Remove(cmt);  // skip comment\r
198     record.ReplaceAll("\t"," ");\r
199     record.ReplaceAll("\r"," ");\r
200     record.Remove(TString::kBoth,' '); \r
201     if (record.IsNull()) continue;      // nothing to decode \r
202     if (!keyws.IsNull() && !record.BeginsWith(keyws.Data())) continue; // specific record was requested\r
203     //\r
204     recElems = record.Tokenize(" ");\r
205     recTitle = recElems->At(0)->GetName();\r
206     recTitle.ToUpper();\r
207     recOpt = recElems->GetLast()>0 ? recElems->At(1)->GetName() : "";\r
208     break;\r
209   }\r
210   if (rew || !recElems) rewind(stream);\r
211   return recElems;\r
212 }\r
213 \r
214 //________________________________________________________________________________________________________\r
215 Int_t AliITSAlignMille2::CheckConfigRecords(FILE* stream)\r
216 {  \r
217   TString record,recTitle;\r
218   int lineCnt = 0;\r
219   rewind(stream);\r
220   while (record.Gets(stream)) {\r
221     int cmt=record.Index("#"); \r
222     lineCnt++;\r
223     if (cmt>=0) record.Remove(cmt);  // skip comment\r
224     record.ReplaceAll("\t"," ");\r
225     record.ReplaceAll("\r"," ");\r
226     record.Remove(TString::kBoth,' ');\r
227     if (record.IsNull()) continue;   // nothing to decode  \r
228     // extract keyword\r
229     int spc = record.Index(" ");\r
230     if (spc>0) recTitle = record(0,spc);\r
231     else     recTitle = record;\r
232     recTitle.ToUpper();\r
233     Bool_t strOK = kFALSE;\r
234     for (int ik=kNKeyWords;ik--;) if (recTitle == kRecKeys[ik]) {strOK = kTRUE; break;}\r
235     if (strOK) continue;\r
236     //\r
237     AliError(Form("Unknown keyword %s at line %d",\r
238                   recTitle.Data(),lineCnt));\r
239     return -1;\r
240     //\r
241   }\r
242   //\r
243   rewind(stream);\r
244   return 0;\r
245 }\r
246 \r
247 \r
248 //________________________________________________________________________________________________________\r
249 Int_t AliITSAlignMille2::LoadConfig(const Char_t *cfile)\r
250 {  \r
251   // return 0 if success\r
252   //        1 if error in module index or voluid\r
253   //\r
254   FILE *pfc=fopen(cfile,"r");\r
255   if (!pfc) return -1;\r
256   //\r
257   TString record,recTitle,recOpt,recExt;\r
258   Int_t nrecElems,irec;\r
259   TObjArray *recArr=0;\r
260   //\r
261   fNModules = 0;\r
262   Bool_t stopped = kFALSE;\r
263   //\r
264   if (CheckConfigRecords(pfc)<0) return -1;\r
265   //\r
266   while(1) { \r
267     //\r
268     // ============= 1: we read some obligatory records in predefined order ================\r
269     //  \r
270     recTitle = kRecKeys[kGeomFile];\r
271     if ( !GetConfigRecord(pfc,recTitle,recOpt,1) || \r
272          (fGeometryFileName=recOpt).IsNull()     || \r
273          gSystem->AccessPathName(recOpt.Data())  ||\r
274          InitGeometry() )\r
275       { AliError("Failed to find/load Geometry"); stopped = kTRUE; break;}\r
276     //\r
277     recTitle = kRecKeys[kSuperModileFile];\r
278     if ( !GetConfigRecord(pfc,recTitle,recOpt,1) || \r
279          recOpt.IsNull()                         || \r
280          gSystem->AccessPathName(recOpt.Data())  ||\r
281          LoadSuperModuleFile(recOpt.Data()))\r
282       { AliError("Failed to find/load SuperModules"); stopped = kTRUE; break;}\r
283     //\r
284     recTitle = kRecKeys[kConstrRefFile];      // LOCAL_CONSTRAINTS are defined wrt these deltas\r
285     if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) {\r
286       if (recOpt.IsNull() || recOpt=="IDEAL") SetConstraintWrtRef( "IDEAL" );\r
287       else if (gSystem->AccessPathName(recOpt.Data()) || SetConstraintWrtRef(recOpt.Data()) )\r
288         { AliError("Failed to load reference deltas for local constraints"); stopped = kTRUE; break;}\r
289     }\r
290     //   \r
291     recTitle = kRecKeys[kPrealignFile];\r
292     if ( GetConfigRecord(pfc,recTitle,recOpt,1) )\r
293       if ( (fPreAlignmentFileName=recOpt).IsNull() || \r
294            gSystem->AccessPathName(recOpt.Data())   ||\r
295            ApplyToGeometry()) \r
296         { AliError(Form("Failed to load Prealignment file %s",recOpt.Data())); stopped = kTRUE; break;}\r
297     //\r
298     recTitle = kRecKeys[kPreCalSDDFile];\r
299     if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) {\r
300       if ( recOpt.IsNull() || gSystem->AccessPathName(recOpt.Data()) ) {stopped = kTRUE; break;}\r
301       AliInfo(Form("Using %s for SDD precalibration",recOpt.Data()));\r
302       TFile* precfi = TFile::Open(recOpt.Data());\r
303       if (!precfi->IsOpen()) {stopped = kTRUE; break;}\r
304       fCorrectSDD = (AliITSresponseSDD*)precfi->Get("AliITSresponseSDD");\r
305       precfi->Close();\r
306       delete precfi;\r
307       if (!fCorrectSDD) {AliError("Precalibration SDD object is not found"); stopped = kTRUE; break;}\r
308     }\r
309     //\r
310     recTitle = kRecKeys[ kInitCalSDDFile ];\r
311     if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) {\r
312       if ( recOpt.IsNull() || gSystem->AccessPathName(recOpt.Data()) ) {stopped = kTRUE; break;}\r
313       AliInfo(Form("Using %s as SDD calibration used in TrackPoints",recOpt.Data()));\r
314       TFile* precf = TFile::Open(recOpt.Data());\r
315       if (!precf->IsOpen()) {stopped = kTRUE; break;}\r
316       fInitialRecSDD = (AliITSresponseSDD*)precf->Get("AliITSresponseSDD");\r
317       precf->Close();\r
318       delete precf;\r
319       if (!fInitialRecSDD) {AliError("Initial Calibration SDD object is not found"); stopped = kTRUE; break;}\r
320     }\r
321     //\r
322     recTitle = kRecKeys[ kGlobalDeltas ];\r
323     if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) SetUseGlobalDelta(kTRUE);\r
324     //\r
325     // =========== 2: see if there are local gaussian constraints defined =====================\r
326     //            Note that they should be loaded before the modules declaration\r
327     //\r
328     recTitle = kRecKeys[ kConstrLocal ];\r
329     while( (recArr=GetConfigRecord(pfc,recTitle,recOpt,0)) ) {\r
330       nrecElems = recArr->GetLast()+1;\r
331       if (recOpt.IsFloat()) {stopped = kTRUE; break;} // wrong name\r
332       if (GetConstraint(recOpt.Data())) {\r
333         AliError(Form("Existing constraint %s repeated",recOpt.Data()));\r
334         stopped = kTRUE; break;\r
335       }\r
336       recExt = recArr->At(2)->GetName();\r
337       if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
338       double val = recExt.Atof();      \r
339       recExt = recArr->At(3)->GetName();\r
340       if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
341       double err = recExt.Atof();      \r
342       int nwgh = nrecElems - 4;\r
343       double *wgh = new double[nwgh];\r
344       for (nwgh=0,irec=4;irec<nrecElems;irec++) {\r
345         recExt = recArr->At(irec)->GetName();\r
346         if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
347         wgh[nwgh++] = recExt.Atof();\r
348       }\r
349       if (stopped) {delete[] wgh; break;}\r
350       //\r
351       ConstrainLocal(recOpt.Data(),wgh,nwgh,val,err);\r
352       delete[] wgh;\r
353       //\r
354     } // end while for loop over local constraints\r
355     if (stopped) break;\r
356     //\r
357     // =========== 3: now read modules to align ===================================\r
358     //\r
359     rewind(pfc);\r
360     while( (recArr=GetConfigRecord(pfc,recTitle="",recOpt,0)) ) {\r
361       if (!(recTitle==kRecKeys[ kModVolID ] || recTitle==kRecKeys[ kModIndex ])) continue;\r
362       // Expected format: MODULE id tolX tolY tolZ tolPsi tolTh tolPhi [[sigX sigY sigZ]  extra params]\r
363       // where tol* is the tolerance (sigma) for given DOF. 0 means fixed\r
364       // sig* is the scaling parameters for the errors of the clusters of this module\r
365       // extra params are defined for specific modules, e.g. t0 and vdrift corrections of SDD\r
366       //\r
367       nrecElems = recArr->GetLast()+1;\r
368       if (nrecElems<2 || !recOpt.IsDigit()) {stopped = kTRUE; break;}\r
369       int idx = recOpt.Atoi(); \r
370       UShort_t voluid =  (idx<=kMaxITSSensID) ? GetModuleVolumeID(idx) : idx;\r
371       AliITSAlignMille2Module* mod = 0;\r
372       //\r
373       if (voluid>=kMinITSSupeModuleID) { // custom supermodule\r
374         for (int j=0; j<fNSuperModules; j++) {\r
375           if (voluid==GetSuperModule(j)->GetVolumeID()) {\r
376             mod = new AliITSAlignMille2Module(*GetSuperModule(j));\r
377             // the matrix might be updated in case some prealignment was applied, check \r
378             TGeoHMatrix* mup = AliGeomManager::GetMatrix(mod->GetName());\r
379             if (mup) *(mod->GetMatrix()) = *mup;\r
380             fMilleModule.AddAtAndExpand(mod,fNModules);\r
381             break;\r
382           }     \r
383         }\r
384       }\r
385       else if (idx<=kMaxITSSensVID) {\r
386         mod = new AliITSAlignMille2Module(voluid);\r
387         fMilleModule.AddAtAndExpand(mod,fNModules);\r
388       }\r
389       if (!mod) {stopped = kTRUE; break;}  // bad volid\r
390       //\r
391       // geometry variation settings\r
392       for (int i=0;i<AliITSAlignMille2Module::kMaxParGeom;i++) {\r
393         irec = i+2;\r
394         if (irec >= nrecElems) break;\r
395         recExt = recArr->At(irec)->GetName();\r
396         if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
397         mod->SetFreeDOF(i, recExt.Atof() );     \r
398       }\r
399       if (stopped) break;\r
400       //\r
401       // scaling factors for cluster errors\r
402       // first set default ones\r
403       for (int i=0;i<3;i++) mod->SetSigmaFactor(i, fSigmaFactor[i]);    \r
404       for (int i=0;i<3;i++) {\r
405         irec = i+8;\r
406         if (irec >= nrecElems) break;\r
407         recExt = recArr->At(irec)->GetName();\r
408         if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
409         mod->SetSigmaFactor(i, recExt.Atof() ); \r
410       }     \r
411       if (stopped) break;\r
412       //\r
413       mod->SetGeomParamsGlobal(fUseGlobalDelta);\r
414       // now comes special detectors treatment\r
415       if (mod->IsSDD()) {\r
416         double vl = 0;\r
417         if (nrecElems>11) {\r
418           recExt = recArr->At(11)->GetName();\r
419           if (recExt.IsFloat()) vl = recExt.Atof();\r
420           else {stopped = kTRUE; break;}\r
421           irec = 11;\r
422         }\r
423         mod->SetFreeDOF(AliITSAlignMille2Module::kDOFT0,vl);\r
424         //\r
425         vl = 0;\r
426         if (nrecElems>12) {\r
427           recExt = recArr->At(12)->GetName();\r
428           if (recExt.IsFloat()) vl = recExt.Atof();\r
429           else {stopped = kTRUE; break;}\r
430           irec = 12;\r
431         }\r
432         mod->SetFreeDOF(AliITSAlignMille2Module::kDOFDV,vl);\r
433       }\r
434       //\r
435       mod->SetUniqueID(fNModules);\r
436       mod->EvaluateDOF();\r
437       fNModules++;\r
438       //\r
439       // now check if there are local constraints on this module\r
440       for (++irec;irec<nrecElems;irec++) {\r
441         recExt = recArr->At(irec)->GetName();\r
442         if (recExt.IsFloat()) {stopped=kTRUE;break;}\r
443         AliITSAlignMille2ConstrArray* cstr = (AliITSAlignMille2ConstrArray*)GetConstraint(recExt.Data());\r
444         if (!cstr) {\r
445           AliInfo(Form("No Local constraint %s was declared",recExt.Data())); \r
446           stopped=kTRUE; \r
447           break;\r
448         }\r
449         cstr->AddModule(mod);\r
450       }\r
451       if (stopped) break;\r
452     } // end while for loop over modules\r
453     if (stopped) break;\r
454     //\r
455     if (fNModules==0) {AliError("Failed to find any MODULE"); stopped = kTRUE; break;}  \r
456     BuildHierarchy();  // preprocess loaded modules\r
457     //\r
458     // =========== 4: the rest may come in arbitrary order =======================================\r
459     rewind(pfc);\r
460     while ( (recArr=GetConfigRecord(pfc,recTitle="",recOpt,0))!=0 ) {\r
461       //\r
462       nrecElems = recArr->GetLast()+1;\r
463       //\r
464       // some simple flags -----------------------------------------------------------------------\r
465       //\r
466       if      (recTitle == kRecKeys[ kPseudoParents ])  SetAllowPseudoParents(kTRUE);\r
467       //\r
468       // some optional parameters ----------------------------------------------------------------\r
469       else if (recTitle == kRecKeys[ kTrackFitMethod ]) {\r
470         if (recOpt.IsNull() || !recOpt.IsDigit() ) {stopped = kTRUE; break;}\r
471         SetInitTrackParamsMeth(recOpt.Atoi());\r
472       }\r
473       //\r
474       else if (recTitle == kRecKeys[ kMinPntTrack ]) {\r
475         if (recOpt.IsNull() || !recOpt.IsDigit() ) {stopped = kTRUE; break;}\r
476         fMinNPtsPerTrack = recOpt.Atoi();\r
477       }\r
478       //\r
479       else if (recTitle == kRecKeys[ kNStDev ]) {\r
480         if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
481         fNStdDev = (Int_t)recOpt.Atof();\r
482       }\r
483       //\r
484       else if (recTitle == kRecKeys[ kResCutInit  ]) {\r
485         if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
486         fResCutInitial = recOpt.Atof();\r
487       }\r
488       //\r
489       else if (recTitle == kRecKeys[ kResCutOther ]) {\r
490         if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
491         fResCut = recOpt.Atof();\r
492       }\r
493       //\r
494       else if (recTitle == kRecKeys[ kLocalSigFactor ]) { //-------------------------\r
495         for (irec=0;irec<3;irec++) if (nrecElems>irec+1) {\r
496             fSigmaFactor[irec] = ((TObjString*)recArr->At(irec+1))->GetString().Atof();\r
497             if (fSigmaFactor[irec]<=0.) stopped = kTRUE;\r
498           }\r
499         if (stopped) break; \r
500       }\r
501       //\r
502       else if (recTitle == kRecKeys[ kStartFactor ]) {        //-------------------------\r
503         if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
504         fStartFac = recOpt.Atof();\r
505       }\r
506       //\r
507       else if (recTitle == kRecKeys[ kBField ]) {         //-------------------------\r
508         if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
509         fBField = recOpt.Atof();\r
510         if (fBField>0) {\r
511           fBOn = kTRUE;\r
512           fNLocal = 5; // helices\r
513           fRieman = new AliTrackFitterRieman();\r
514         }  \r
515         else {\r
516           fBField = 0.0;\r
517           fBOn = kFALSE;\r
518           fNLocal = 4;\r
519         }\r
520       }\r
521       //\r
522       else if (recTitle == kRecKeys[ kSparseMatrix ]) {   // matrix solver type\r
523         //\r
524         AliMillePede2::SetGlobalMatSparse(kTRUE);\r
525         if (recOpt.IsNull()) continue;\r
526         // solver type and settings\r
527         if      (recOpt == "MINRES") AliMillePede2::SetIterSolverType( AliMinResSolve::kSolMinRes );\r
528         else if (recOpt == "FGMRES") AliMillePede2::SetIterSolverType( AliMinResSolve::kSolFGMRes );\r
529         else {stopped = kTRUE; break;}\r
530         //\r
531         if (nrecElems>=3) { // preconditioner type\r
532           recExt = recArr->At(2)->GetName();\r
533           if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
534           AliMillePede2::SetMinResPrecondType( recExt.Atoi() );\r
535         }\r
536         //\r
537         if (nrecElems>=4) { // tolerance\r
538           recExt = recArr->At(3)->GetName();\r
539           if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
540           AliMillePede2::SetMinResTol( recExt.Atof() );\r
541         }\r
542         //\r
543         if (nrecElems>=5) { // maxIter\r
544           recExt = recArr->At(4)->GetName();\r
545           if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
546           AliMillePede2::SetMinResMaxIter( recExt.Atoi() );\r
547         }       \r
548       }\r
549       //\r
550       else if (recTitle == kRecKeys[ kRequirePoint ]) {       //-------------------------\r
551         // syntax:   REQUIRE_POINT where ndet updw nreqpts\r
552         //    where = LAYER or DETECTOR\r
553         //    ndet = detector number: 1-6 for LAYER and 1-3 for DETECTOR (SPD=1, SDD=2, SSD=3)\r
554         //    updw = 1 for Y>0, -1 for Y<0, 0 if not specified\r
555         //    nreqpts = minimum number of points of that type\r
556         if (nrecElems>=5) {\r
557           recOpt.ToUpper();\r
558           int lr = ((TObjString*)recArr->At(2))->GetString().Atoi() - 1;\r
559           int hb = ((TObjString*)recArr->At(3))->GetString().Atoi();\r
560           int np = ((TObjString*)recArr->At(4))->GetString().Atoi();\r
561           fRequirePoints = kTRUE;\r
562           if (recOpt == "LAYER") {\r
563             if (lr<0 || lr>5) {stopped = kTRUE; break;}\r
564             if (hb>0) fNReqLayUp[lr] = np;\r
565             else if (hb<0) fNReqLayDown[lr] = np;\r
566             else fNReqLay[lr] = np;\r
567           }\r
568           else if (recOpt == "DETECTOR") {\r
569             if (lr<0 || lr>2) {stopped = kTRUE; break;}\r
570             if (hb>0) fNReqDetUp[lr] = np;\r
571             else if (hb<0) fNReqDetDown[lr] = np;\r
572             else fNReqDet[lr] = np;\r
573           }\r
574           else {stopped = kTRUE; break;}\r
575         }\r
576         else {stopped = kTRUE; break;}\r
577       }\r
578       //\r
579       // global constraints on the subunits/orphans \r
580       else if (recTitle == kRecKeys[ kConstrOrphans ]) {    //------------------------\r
581         // expect CONSTRAINT_ORPHANS MEAN/MEDIAN Value parID0 ... parID1 ...\r
582         if (nrecElems<4) {stopped = kTRUE; break;}\r
583         recExt = recArr->At(2)->GetName();\r
584         if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
585         double val = recExt.Atof();\r
586         UInt_t pattern = 0;\r
587         for (irec=3;irec<nrecElems;irec++) { // read params to constraint\r
588           recExt = recArr->At(irec)->GetName();\r
589           if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
590           pattern |= 0x1 << recExt.Atoi();\r
591         }\r
592         if (stopped) break;\r
593         if      (recOpt == "MEAN")   ConstrainOrphansMean(val,pattern);\r
594         else if (recOpt == "MEDIAN") ConstrainOrphansMedian(val,pattern);\r
595         else {stopped = kTRUE; break;}\r
596       }\r
597       //\r
598       else if (recTitle == kRecKeys[ kConstrSubunits ]) {    //------------------------\r
599         // expect ONSTRAINT_SUBUNITS MEAN/MEDIAN Value parID0 ... parID1 ... VolID1 ... VolIDn - VolIDm\r
600         if (nrecElems<5) {stopped = kTRUE; break;}\r
601         recExt = recArr->At(2)->GetName();\r
602         if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
603         double val = recExt.Atof();\r
604         UInt_t pattern = 0;\r
605         for (irec=3;irec<nrecElems;irec++) { // read params to constraint\r
606           recExt = recArr->At(irec)->GetName();\r
607           if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
608           int parid = recExt.Atoi();\r
609           if (parid<kMaxITSSensID) pattern |= 0x1 << recExt.Atoi();\r
610           else break;           // list of params is over \r
611         }\r
612         if (stopped) break;\r
613         //\r
614         Bool_t meanC;\r
615         if      (recOpt == "MEAN")   meanC = kTRUE;\r
616         else if (recOpt == "MEDIAN") meanC = kFALSE;\r
617         else    {stopped = kTRUE; break;}\r
618         //\r
619         int curID = -1;\r
620         int rangeStart = -1;\r
621         for (;irec<nrecElems;irec++) { // read modules to apply this constraint\r
622           recExt = recArr->At(irec)->GetName();\r
623           if (recExt == "-") {rangeStart = curID; continue;}  // range is requested\r
624           else if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
625           else curID = recExt.Atoi();\r
626           //\r
627           if (curID<=kMaxITSSensID) curID = GetModuleVolumeID(curID);\r
628           // this was a range start or single \r
629           int start;\r
630           if (rangeStart>=0) {start = rangeStart+1; rangeStart=-1;} // continue the range\r
631           else start = curID;  // create constraint either for single module (or 1st in the range)\r
632           for (int id=start;id<=curID;id++) {\r
633             int id0 = IsVIDDefined(id);\r
634             if (id0<0) {AliDebug(3,Form("Undefined module %d requested in the SubUnits constraint, skipping",id)); continue;}\r
635             if (meanC) ConstrainModuleSubUnitsMean(id0,val,pattern);\r
636             else       ConstrainModuleSubUnitsMedian(id0,val,pattern);\r
637           }\r
638         }\r
639         if (rangeStart>=0) stopped = kTRUE; // unfinished range\r
640         if (stopped) break;\r
641       } \r
642       // \r
643       // association of modules with local constraints\r
644       else if (recTitle == kRecKeys[ kApplyConstr ]) {            //------------------------\r
645         // expect APPLY_CONSTRAINT NAME [NAME1...] [VolID1 ... VolIDn - VolIDm]\r
646         if (nrecElems<3) {stopped = kTRUE; break;}\r
647         int nmID0=-1,nmID1=-1;\r
648         for (irec=1;irec<nrecElems;irec++) { // find the range of constraint names\r
649           recExt = recArr->At(irec)->GetName();\r
650           if (recExt.IsFloat()) break;\r
651           // check if such a constraint was declared\r
652           if (!GetConstraint(recExt.Data())) {\r
653             AliInfo(Form("No Local constraint %s was declared",recExt.Data())); \r
654             stopped=kTRUE; \r
655             break;\r
656           }\r
657           if (nmID0<0) nmID0 = irec;\r
658           nmID1 = irec;\r
659         }\r
660         if (stopped) break;\r
661         //\r
662         if (irec>=nrecElems) {stopped = kTRUE; break;} // no modules provided\r
663         //\r
664         // now read the list of modules to constrain\r
665         int curID = -1;\r
666         int rangeStart = -1;\r
667         for (;irec<nrecElems;irec++) { // read modules to apply this constraint\r
668           recExt = recArr->At(irec)->GetName();\r
669           if (recExt == "-") {rangeStart = curID; continue;}  // range is requested\r
670           else if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
671           else curID = recExt.Atoi();\r
672           //\r
673           if (curID<=kMaxITSSensID) curID = GetModuleVolumeID(curID);\r
674           //\r
675           // this was a range start or single \r
676           int start;\r
677           if (rangeStart>=0) {start = rangeStart+1; rangeStart=-1;} // continue the range\r
678           else start = curID;  // create constraint either for single module (or 1st in the range)\r
679           for (int id=start;id<=curID;id++) {\r
680             AliITSAlignMille2Module *md = GetMilleModuleByVID(id);\r
681             if (!md) {AliDebug(3,Form("Undefined module %d requested in the Local constraint, skipping",id)); continue;}\r
682             for (int nmid=nmID0;nmid<=nmID1;nmid++) \r
683               ((AliITSAlignMille2ConstrArray*)GetConstraint(recArr->At(nmid)->GetName()))->AddModule(md);\r
684           }\r
685         }\r
686         if (rangeStart>=0) stopped = kTRUE; // unfinished range\r
687         if (stopped) break;\r
688       }\r
689       //\r
690       else continue; // already processed record\r
691       //\r
692     } // end of while loop 4 over the various params \r
693     //\r
694     break;\r
695   } // end of while(1) loop \r
696   //\r
697   fclose(pfc);\r
698   if (stopped) {\r
699     AliError(Form("Failed on record %s %s ...\n",recTitle.Data(),recOpt.Data()));\r
700     return -1;\r
701   }\r
702   //\r
703   fIsConfigured = kTRUE;\r
704   return 0;\r
705 }\r
706 \r
707 //________________________________________________________________________________________________________\r
708 void AliITSAlignMille2::BuildHierarchy()\r
709 {\r
710   // build the hieararhy of the modules to align\r
711   //\r
712   if (!GetUseGlobalDelta() && PseudoParentsAllowed()) {\r
713     AliInfo("PseudoParents mode is allowed only when the deltas are global\n"\r
714             "Since Deltas are local, switching to NoPseudoParents");\r
715     SetAllowPseudoParents(kFALSE);\r
716   }\r
717   // set parent/child relationship for modules to align\r
718   AliInfo("Setting parent/child relationships\n");\r
719   //\r
720   // 1) child -> parent reference\r
721   for (int ipar=0;ipar<fNModules;ipar++) {\r
722     AliITSAlignMille2Module* parent = GetMilleModule(ipar);\r
723     if (parent->IsSensor()) continue; // sensor cannot be a parent\r
724     //\r
725     for (int icld=0;icld<fNModules;icld++) {\r
726       if (icld==ipar) continue;\r
727       AliITSAlignMille2Module* child = GetMilleModule(icld);\r
728       if (!child->BelongsTo(parent)) continue;\r
729       // child cannot have more sensors than the parent\r
730       if (child->GetNSensitiveVolumes() > parent->GetNSensitiveVolumes()) continue;\r
731       //\r
732       AliITSAlignMille2Module* parOld = child->GetParent();\r
733       // is this parent candidate closer than the old parent ? \r
734       if (parOld && parOld->GetNSensitiveVolumes()<parent->GetNSensitiveVolumes()) continue; // parOld is closer\r
735       child->SetParent(parent);\r
736     }\r
737     //\r
738   }\r
739   //\r
740   // add parent -> children reference\r
741   for (int icld=0;icld<fNModules;icld++) {\r
742     AliITSAlignMille2Module* child = GetMilleModule(icld);\r
743     AliITSAlignMille2Module* parent = child->GetParent();\r
744     if (parent) parent->AddChild(child);\r
745   }  \r
746   //\r
747   // reorder the modules in such a way that parents come first\r
748   for (int icld=0;icld<fNModules;icld++) {\r
749     AliITSAlignMille2Module* child  = GetMilleModule(icld);\r
750     AliITSAlignMille2Module* parent; \r
751     while ( (parent=child->GetParent()) &&  (parent->GetUniqueID()>child->GetUniqueID()) ) {\r
752       // swap\r
753       fMilleModule[icld] = parent;\r
754       fMilleModule[parent->GetUniqueID()] = child;\r
755       child->SetUniqueID(parent->GetUniqueID());\r
756       parent->SetUniqueID(icld);\r
757       child = parent;\r
758     }\r
759     //\r
760   }  \r
761   //\r
762   // Go over the child->parent chain and mark modules with explicitly provided sensors.\r
763   // If the sensors of the unit are explicitly declared, all undeclared sensors are \r
764   // suppresed in this unit.\r
765   for (int icld=fNModules;icld--;) {\r
766     AliITSAlignMille2Module* child = GetMilleModule(icld);\r
767     AliITSAlignMille2Module* parent = child->GetParent();\r
768     if (!parent) continue;\r
769     //\r
770     // check if this parent was already processed\r
771     if (!parent->AreSensorsProvided()) {\r
772       parent->DelSensitiveVolumes();\r
773       parent->SetSensorsProvided(kTRUE);\r
774     }\r
775     // reattach sensors to parent\r
776     for (int isc=child->GetNSensitiveVolumes();isc--;) {\r
777       UShort_t senVID = child->GetSensVolVolumeID(isc);\r
778       if (!parent->IsIn(senVID)) parent->AddSensitiveVolume(senVID);\r
779     }\r
780   }\r
781   //\r
782 }\r
783 \r
784 // pepo\r
785 //________________________________________________________________________________________________________\r
786 void AliITSAlignMille2::SetCurrentModule(Int_t id)\r
787 {\r
788   // set the current supermodule\r
789   // new meaning\r
790   if (fMilleVersion>=2) {\r
791     fCurrentModule = GetMilleModule(id);\r
792     return;\r
793   }\r
794   // old meaning\r
795   if (fMilleVersion<=1) {\r
796     Int_t index=id;\r
797     /// set as current the SuperModule that contains the 'index' sens.vol.\r
798     if (index<0 || index>2197) {\r
799       AliInfo("index does not correspond to a sensitive volume!");\r
800       return;\r
801     }\r
802     UShort_t voluid=AliITSAlignMille2Module::GetVolumeIDFromIndex(index);\r
803     Int_t k=IsContained(voluid);\r
804     if (k>=0){\r
805       fCluster.SetVolumeID(voluid);\r
806       fCluster.SetXYZ(0,0,0);\r
807       InitModuleParams();\r
808     }\r
809     else\r
810       AliInfo(Form("module %d not defined\n",index));    \r
811   }\r
812 }\r
813 // endpepo\r
814 //________________________________________________________________________________________________________\r
815 void AliITSAlignMille2::SetRequiredPoint(Char_t* where, Int_t ndet, Int_t updw, Int_t nreqpts) \r
816 {\r
817   // set minimum number of points in specific detector or layer\r
818   // where = LAYER or DETECTOR\r
819   // ndet = detector number: 1-6 for LAYER and 1-3 for DETECTOR (SPD=1, SDD=2, SSD=3)\r
820   // updw = 1 for Y>0, -1 for Y<0, 0 if not specified\r
821   // nreqpts = minimum number of points of that type\r
822   ndet--;\r
823   if (strstr(where,"LAYER")) {\r
824     if (ndet<0 || ndet>5) return;\r
825     if (updw>0) fNReqLayUp[ndet]=nreqpts;\r
826     else if (updw<0) fNReqLayDown[ndet]=nreqpts;\r
827     else fNReqLay[ndet]=nreqpts;\r
828     fRequirePoints=kTRUE;\r
829   }\r
830   else if (strstr(where,"DETECTOR")) {\r
831     if (ndet<0 || ndet>2) return;\r
832     if (updw>0) fNReqDetUp[ndet]=nreqpts;\r
833     else if (updw<0) fNReqDetDown[ndet]=nreqpts;\r
834     else fNReqDet[ndet]=nreqpts;        \r
835     fRequirePoints=kTRUE;\r
836   }\r
837 }\r
838 \r
839 //________________________________________________________________________________________________________\r
840 Int_t AliITSAlignMille2::GetModuleIndex(const Char_t *symname) \r
841 {\r
842   /// index from symname\r
843   if (!symname) return -1;\r
844   for (Int_t i=0;i<=kMaxITSSensID; i++) {\r
845     if (!strcmp(symname,AliITSgeomTGeo::GetSymName(i))) return i;\r
846   }\r
847   return -1;\r
848 }\r
849 \r
850 //________________________________________________________________________________________________________\r
851 Int_t AliITSAlignMille2::GetModuleIndex(UShort_t voluid) \r
852 {\r
853   /// index from volume ID\r
854   AliGeomManager::ELayerID lay = AliGeomManager::VolUIDToLayer(voluid);\r
855   if (lay<1|| lay>6) return -1;\r
856   Int_t idx=Int_t(voluid)-2048*lay;\r
857   if (idx>=AliGeomManager::LayerSize(lay)) return -1;\r
858   for (Int_t ilay=1; ilay<lay; ilay++) \r
859     idx += AliGeomManager::LayerSize(ilay);\r
860   return idx;\r
861 }\r
862 \r
863 //________________________________________________________________________________________________________\r
864 UShort_t AliITSAlignMille2::GetModuleVolumeID(const Char_t *symname) \r
865 {\r
866   /// volume ID from symname\r
867   /// works for sensitive volumes only\r
868   if (!symname) return 0;\r
869 \r
870   for (UShort_t voluid=2000; voluid<13300; voluid++) {\r
871     Int_t modId;\r
872     AliGeomManager::ELayerID layerId = AliGeomManager::VolUIDToLayer(voluid,modId);\r
873     if (layerId>0 && layerId<7 && modId>=0 && modId<AliGeomManager::LayerSize(layerId)) {\r
874       if (!strcmp(symname,AliGeomManager::SymName(layerId,modId))) return voluid;\r
875     }\r
876   }\r
877 \r
878   return 0;\r
879 }\r
880 \r
881 //________________________________________________________________________________________________________\r
882 UShort_t AliITSAlignMille2::GetModuleVolumeID(Int_t index) \r
883 {\r
884   /// volume ID from index\r
885   if (index<0) return 0;\r
886   if (index<2198)\r
887     return GetModuleVolumeID(AliITSgeomTGeo::GetSymName(index));\r
888   else {\r
889     for (int i=0; i<fNSuperModules; i++) {\r
890       if (GetSuperModule(i)->GetIndex()==index) return GetSuperModule(i)->GetVolumeID();\r
891     }\r
892   }\r
893   return 0;\r
894 }\r
895 \r
896 //________________________________________________________________________________________________________\r
897 Int_t AliITSAlignMille2::InitGeometry() \r
898 {\r
899   /// initialize geometry\r
900   AliInfo("Loading initial geometry");\r
901   AliGeomManager::LoadGeometry(fGeometryFileName.Data());\r
902   fGeoManager = AliGeomManager::GetGeometry();\r
903   if (!fGeoManager) {\r
904     AliInfo("Couldn't initialize geometry");\r
905     return -1;\r
906   }\r
907   return 0;\r
908 }\r
909 \r
910 //________________________________________________________________________________________________________\r
911 Int_t AliITSAlignMille2::SetConstraintWrtRef(const char* reffname) \r
912 {\r
913   // Load the global deltas from this file. The local gaussian constraints on some modules \r
914   // will be defined with respect to the deltas from this reference file, converted to local\r
915   // delta format. Note: conversion to local format requires reloading the geometry!\r
916   //\r
917   AliInfo(Form("Loading reference deltas for local constraints from %s",reffname));\r
918   if (!fGeoManager) return -1; \r
919   fConstrRefFileName = reffname;\r
920   if (fConstrRefFileName == "IDEAL") { // the reference is the ideal geometry, just create dummy reference array\r
921     fConstrRef = new TClonesArray("AliAlignObjParams",1);\r
922     return 0;\r
923   }\r
924   TFile *pref = TFile::Open(fConstrRefFileName.Data());\r
925   if (!pref->IsOpen()) return -2;   \r
926   fConstrRef = (TClonesArray*)pref->Get("ITSAlignObjs");\r
927   pref->Close();\r
928   delete pref;\r
929   if (!fConstrRef) {\r
930     AliError(Form("Did not find reference prealignment deltas in %s",reffname));\r
931     return -1;\r
932   }\r
933   //\r
934   // we need ideal geometry to convert global deltas to local ones\r
935   if (fUsePreAlignment) {\r
936     AliError("The call of SetConstraintWrtRef must be done before application of the prealignment");\r
937     return -1;\r
938   }\r
939   //\r
940   AliInfo("Converting global reference deltas to local ones");\r
941   Int_t nprea = fConstrRef->GetEntriesFast();\r
942   for (int ix=0; ix<nprea; ix++) {\r
943     AliAlignObjParams *preo=(AliAlignObjParams*) fConstrRef->At(ix);\r
944     if (!preo->ApplyToGeometry()) return -1;\r
945   }\r
946   //\r
947   // now convert the global reference deltas to local ones\r
948   for (int i=fConstrRef->GetEntriesFast();i--;) {\r
949     AliAlignObjParams *preo = (AliAlignObjParams*)fConstrRef->At(i);\r
950     TGeoHMatrix * mupd = AliGeomManager::GetMatrix(preo->GetSymName());\r
951     if (!mupd) {  // this is not alignable entry, need to look in the supermodules\r
952       for (int im=fNSuperModules;im--;) {\r
953         AliITSAlignMille2Module* mod = GetSuperModule(im);\r
954         if ( strcmp(mod->GetName(), preo->GetSymName()) ) continue;\r
955         mupd = mod->GetMatrix();\r
956         break;\r
957       }\r
958       if (!mupd) {\r
959         AliError(Form("Failed to find the volume for reference %s",preo->GetSymName()));\r
960         return -1;\r
961       }\r
962     } \r
963     TGeoHMatrix preMat;\r
964     preo->GetMatrix(preMat);                     //  Delta_Glob\r
965     TGeoHMatrix tmpMat    = *mupd;               //  Delta_Glob * Delta_Glob_Par * M\r
966     preMat.MultiplyLeft( &tmpMat.Inverse() );    //  M^-1 * Delta_Glob_Par^-1 = (Delta_Glob_Par * M)^-1\r
967     tmpMat.MultiplyLeft( &preMat );              //  (Delta_Glob_Par * M)^-1 * Delta_Glob * Delta_Glob_Par * M = Delta_loc\r
968     preo->SetMatrix(tmpMat);     // local corrections \r
969   }\r
970   //\r
971   // we need to reload the geometry spoiled by this reference deltas...\r
972   delete fGeoManager;\r
973   AliInfo("Reloading initial geometry");\r
974   AliGeomManager::LoadGeometry(fGeometryFileName.Data());\r
975   fGeoManager = AliGeomManager::GetGeometry();\r
976   return 0;\r
977 }\r
978 \r
979 //________________________________________________________________________________________________________\r
980 void AliITSAlignMille2::Init()\r
981 {\r
982   // perform global initialization\r
983   //\r
984   if (fIsMilleInit) {\r
985     AliInfo("Millepede has been already initialized!");\r
986     return;\r
987   }\r
988   // range constraints in such a way that the childs are constrained before their parents\r
989   // orphan constraints come last\r
990   for (int ic=0;ic<GetNConstraints();ic++) {\r
991     for (int ic1=ic+1;ic1<GetNConstraints();ic1++) {\r
992       AliITSAlignMille2Constraint *cst0 = GetConstraint(ic);\r
993       AliITSAlignMille2Constraint *cst1 = GetConstraint(ic1);\r
994       if (cst0->GetModuleID()<cst1->GetModuleID()) {\r
995         // swap\r
996         fConstraints[ic] = cst1;\r
997         fConstraints[ic1] = cst0;\r
998       }\r
999     }\r
1000   }\r
1001   //\r
1002   if (!GetUseGlobalDelta()) {\r
1003     AliInfo("ATTENTION: The parameters are defined in the local frame, no check for degeneracy will be done");\r
1004     for (int imd=fNModules;imd--;) {\r
1005       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
1006       int npar = mod->GetNParTot();\r
1007       // the parameter may have max 1 free instance, otherwise the equations are underdefined\r
1008       for (int ipar=0;ipar<npar;ipar++) {\r
1009         if (!mod->IsFreeDOF(ipar)) continue;\r
1010         mod->SetParOffset(ipar,fNGlobal++);\r
1011       }\r
1012     }\r
1013   }\r
1014   else {\r
1015     // init millepede, decide which parameters are to be fitted explicitly\r
1016     for (int imd=fNModules;imd--;) {\r
1017       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
1018       int npar = mod->GetNParTot();\r
1019       // the parameter may have max 1 free instance, otherwise the equations are underdefined\r
1020       for (int ipar=0;ipar<npar;ipar++) {\r
1021         if (!mod->IsFreeDOF(ipar)) continue;  // fixed\r
1022         //\r
1023         int nFreeInstances = 0;\r
1024         //\r
1025         AliITSAlignMille2Module* parent = mod;\r
1026         Bool_t cstMeanMed=kFALSE,cstGauss=kFALSE;\r
1027         //\r
1028         Bool_t addToFit = kFALSE;       \r
1029         // the parameter may be ommitted from explicit fit (if PseudoParentsAllowed is true) if\r
1030         // 1) it is not explicitly constrained or its does not participate in Gaussian constraint\r
1031         // 2) the same applies to all of its parents\r
1032         // 3) it has at least 1 unconstrained direct child\r
1033         while(parent) {\r
1034           if (!parent->IsFreeDOF(ipar)) {parent = parent->GetParent(); continue;}\r
1035           nFreeInstances++;\r
1036           if (IsParModConstrained(parent,ipar, cstMeanMed, cstGauss)) nFreeInstances--;\r
1037           if (cstGauss) addToFit = kTRUE;\r
1038           parent = parent->GetParent();\r
1039         }\r
1040         if (nFreeInstances>1) {\r
1041           AliError(Form("Parameter#%d of module %s\nhas %d free instances in the "\r
1042                         "unconstrained parents\nSystem is undefined",ipar,mod->GetName(),nFreeInstances));\r
1043           exit(1);\r
1044         }\r
1045         //\r
1046         // i) Are PseudoParents allowed?\r
1047         if (!PseudoParentsAllowed()) addToFit = kTRUE;\r
1048         // ii) check if this module has no child with such a free parameter. Since the order of this check \r
1049         // goes from child to parent, by this moment such a parameter must have been already added\r
1050         else if (!IsParModFamilyVaried(mod,ipar))  addToFit = kTRUE;  // no varied children at all\r
1051         else if (!IsParFamilyFree(mod,ipar,1))     addToFit = kTRUE;  // no unconstrained direct children\r
1052         // otherwise the value of this parameter can be extracted from simple contraint and the values of \r
1053         // the relevant parameters of its children the fit is done. Hence it is not included\r
1054         if (!addToFit) continue;\r
1055         //\r
1056         // shall add this parameter to explicit fit\r
1057         //      printf("Adding %s %d -> %d\n",mod->GetName(), ipar, fNGlobal);\r
1058         mod->SetParOffset(ipar,fNGlobal++);\r
1059       }\r
1060     }\r
1061   }\r
1062   //\r
1063   AliInfo(Form("Initializing Millepede with %d gpar, %d lpar and %d stddev ...",fNGlobal, fNLocal, fNStdDev));\r
1064   fGlobalDerivatives = new Double_t[fNGlobal];\r
1065   memset(fGlobalDerivatives,0,fNGlobal*sizeof(Double_t));\r
1066   //\r
1067   fMillepede->InitMille(fNGlobal,fNLocal,fNStdDev,fResCut,fResCutInitial);\r
1068   fIsMilleInit = kTRUE;\r
1069   //\r
1070   ResetLocalEquation();    \r
1071   AliInfo("Parameters initialized to zero");\r
1072   //\r
1073   /// Fix non free parameters\r
1074   for (Int_t i=0; i<fNModules; i++) {\r
1075     AliITSAlignMille2Module* mod = GetMilleModule(i);\r
1076     for (Int_t j=0; j<mod->GetNParTot(); j++) {\r
1077       if (mod->GetParOffset(j)<0) continue; // not varied\r
1078       FixParameter(mod->GetParOffset(j),mod->GetParConstraint(j));\r
1079       fMillepede->SetParamGrID(i, mod->GetParOffset(j));\r
1080     }\r
1081   }\r
1082   //\r
1083   // Set iterations\r
1084   if (fStartFac>1) fMillepede->SetIterations(fStartFac);    \r
1085   //\r
1086 }\r
1087 \r
1088 //________________________________________________________________________________________________________\r
1089 void AliITSAlignMille2::AddConstraint(Double_t *par, Double_t value, Double_t sigma) \r
1090 {\r
1091   /// Constrain equation defined by par to value\r
1092   if (!fIsMilleInit) Init();\r
1093   fMillepede->SetGlobalConstraint(par, value, sigma);\r
1094   AliInfo("Adding constraint");\r
1095 }\r
1096 \r
1097 //________________________________________________________________________________________________________\r
1098 void AliITSAlignMille2::InitGlobalParameters(Double_t *par) \r
1099 {\r
1100   /// Initialize global parameters with par array\r
1101   if (!fIsMilleInit) Init();\r
1102   fMillepede->SetGlobalParameters(par);\r
1103   AliInfo("Init Global Parameters");\r
1104 }\r
1105 \r
1106 //________________________________________________________________________________________________________ \r
1107 void AliITSAlignMille2::FixParameter(Int_t iPar, Double_t value) \r
1108 {\r
1109   /// Parameter iPar is encourage to vary in [-value;value]. \r
1110   /// If value == 0, parameter is fixed\r
1111   if (!fIsMilleInit) {\r
1112     AliInfo("Millepede has not been initialized!");\r
1113     return;\r
1114   }\r
1115   fMillepede->SetParSigma(iPar, value);\r
1116   if (value==0) AliInfo(Form("Parameter %i Fixed", iPar));\r
1117 }\r
1118 \r
1119 //________________________________________________________________________________________________________\r
1120 void AliITSAlignMille2::ResetLocalEquation()\r
1121 {\r
1122   /// Reset the derivative vectors\r
1123   for(int i=fNLocal;i--;)  fLocalDerivatives[i] = 0.0;\r
1124   memset(fGlobalDerivatives, 0, fNGlobal*sizeof(double) );\r
1125 }\r
1126 \r
1127 //________________________________________________________________________________________________________\r
1128 Int_t AliITSAlignMille2::ApplyToGeometry() \r
1129 {\r
1130   // apply starting realignment to ideal geometry\r
1131   AliInfo(Form("Using %s for prealignment",fPreAlignmentFileName.Data()));\r
1132   if (!fGeoManager) return -1; \r
1133   TFile *pref = TFile::Open(fPreAlignmentFileName.Data());\r
1134   if (!pref->IsOpen()) return -2;\r
1135   fPrealignment = (TClonesArray*)pref->Get("ITSAlignObjs");\r
1136   if (!fPrealignment) return -3;  \r
1137   Int_t nprea = fPrealignment->GetEntriesFast();\r
1138   AliInfo(Form("Array of input misalignments with %d entries",nprea));\r
1139   //\r
1140   for (int ix=0; ix<nprea; ix++) {\r
1141     AliAlignObjParams *preo=(AliAlignObjParams*) fPrealignment->At(ix);\r
1142     Int_t index=AliITSAlignMille2Module::GetIndexFromVolumeID(preo->GetVolUID());\r
1143     if (index>=0) {\r
1144       if (index>=fPreAlignQF.GetSize()) fPreAlignQF.Set(index+10);\r
1145       fPreAlignQF[index] = (int) preo->GetUniqueID()+1;\r
1146     }\r
1147     //TString nms = preo->GetSymName();\r
1148     //if (!nms.Contains("Ladder")) continue; //RRR\r
1149     //printf("Applying#%4d %s\n",ix,preo->GetSymName());\r
1150     if (!preo->ApplyToGeometry()) return -4;\r
1151   }\r
1152   //\r
1153   pref->Close();\r
1154   delete pref;\r
1155   //\r
1156   fUsePreAlignment = kTRUE;\r
1157   return 0;\r
1158 }\r
1159 \r
1160 //________________________________________________________________________________________________________\r
1161 Int_t AliITSAlignMille2::GetPreAlignmentQualityFactor(Int_t index) const\r
1162 {\r
1163   // quality factors from prealignment\r
1164   if (!fUsePreAlignment || index<0 || index>=fPreAlignQF.GetSize()) return -1;\r
1165   return fPreAlignQF[index]-1;\r
1166 }\r
1167 \r
1168 //________________________________________________________________________________________________________\r
1169 AliTrackPointArray *AliITSAlignMille2::PrepareTrack(const AliTrackPointArray *atp) \r
1170 {\r
1171   /// create a new AliTrackPointArray keeping only defined modules\r
1172   /// move points according to a given prealignment, if any\r
1173   /// sort alitrackpoints w.r.t. global Y direction, if selected\r
1174   const double kTiny = 1E-12;\r
1175   //\r
1176   AliTrackPointArray *atps=NULL;\r
1177   Int_t idx[20];\r
1178   Int_t npts=atp->GetNPoints();\r
1179 \r
1180   /// checks if AliTrackPoints belong to defined modules\r
1181   Int_t ngoodpts=0;\r
1182   Int_t intidx[20];\r
1183   \r
1184   for (int j=0; j<npts; j++) {\r
1185     intidx[j] = IsVIDContained(atp->GetVolumeID()[j]);\r
1186     if (intidx[j]>=0) ngoodpts++;\r
1187   }\r
1188   AliDebug(3,Form("Number of points in defined modules: %d out of %d",ngoodpts,npts));\r
1189 \r
1190   // reject track if not enough points are left\r
1191   if (ngoodpts<fMinNPtsPerTrack) {\r
1192     AliInfo("Track with not enough points!");\r
1193     return NULL;\r
1194   }\r
1195   // >> RS\r
1196   AliTrackPoint p;\r
1197   // check points in specific places\r
1198   if (fRequirePoints) {\r
1199     Int_t nlayup[6],nlaydown[6],nlay[6];\r
1200     Int_t ndetup[3],ndetdown[3],ndet[3];\r
1201     for (Int_t j=0; j<6; j++) {nlayup[j]=0; nlaydown[j]=0; nlay[j]=0;}\r
1202     for (Int_t j=0; j<3; j++) {ndetup[j]=0; ndetdown[j]=0; ndet[j]=0;}\r
1203     \r
1204     for (int i=0; i<npts; i++) {\r
1205       // skip not defined points\r
1206       if (intidx[i]<0) continue;\r
1207       Float_t xx=atp->GetX()[i];\r
1208       Float_t yy=atp->GetY()[i];\r
1209       Float_t r=TMath::Sqrt(xx*xx + yy*yy);\r
1210       int lay=-1;\r
1211       if (r<5) lay=0;\r
1212       else if (r>5 && r<10) lay=1;\r
1213       else if (r>10 && r<18) lay=2;\r
1214       else if (r>18 && r<30) lay=3;\r
1215       else if (r>30 && r<40) lay=4;\r
1216       else if (r>40) lay=5;\r
1217       if (lay<0) continue;\r
1218       int det=lay/2;\r
1219       //printf("Point %d - x=%f  y=%f  R=%f  lay=%d  det=%d\n",i,xx,yy,r,lay,det);\r
1220 \r
1221       if (yy>=0.0) { // UP point\r
1222         nlayup[lay]++;\r
1223         nlay[lay]++;\r
1224         ndetup[det]++;\r
1225         ndet[det]++;\r
1226       }\r
1227       else {\r
1228         nlaydown[lay]++;\r
1229         nlay[lay]++;\r
1230         ndetdown[det]++;\r
1231         ndet[det]++;\r
1232       }\r
1233     }\r
1234     \r
1235     // checks minimum values\r
1236     Bool_t isok=kTRUE;\r
1237     for (Int_t j=0; j<6; j++) {\r
1238       if (nlayup[j]<fNReqLayUp[j]) isok=kFALSE; \r
1239       if (nlaydown[j]<fNReqLayDown[j]) isok=kFALSE; \r
1240       if (nlay[j]<fNReqLay[j]) isok=kFALSE; \r
1241     }\r
1242     for (Int_t j=0; j<3; j++) {\r
1243       if (ndetup[j]<fNReqDetUp[j]) isok=kFALSE; \r
1244       if (ndetdown[j]<fNReqDetDown[j]) isok=kFALSE; \r
1245       if (ndet[j]<fNReqDet[j]) isok=kFALSE; \r
1246     }\r
1247     if (!isok) {\r
1248       AliDebug(2,Form("Track does not meet all location point requirements!"));\r
1249       return NULL;\r
1250     }\r
1251   }\r
1252   // build a new track with (sorted) (prealigned) good points\r
1253   // pepo 200709\r
1254 //   atps = (AliTrackPointArray*)fTrackBuff[ngoodpts-fMinNPtsPerTrack];\r
1255 //   if (!atps) {\r
1256 //     atps = new AliTrackPointArray(ngoodpts);\r
1257 //     fTrackBuff.AddAtAndExpand(atps,ngoodpts-fMinNPtsPerTrack);\r
1258 //   }  \r
1259   atps = new AliTrackPointArray(ngoodpts);\r
1260   // endpepo200709\r
1261   //\r
1262   //\r
1263   for (int i=0; i<npts; i++) idx[i]=i;\r
1264   // sort track if required\r
1265   TMath::Sort(npts,atp->GetY(),idx); // sort descending...\r
1266   //\r
1267   Int_t npto=0;\r
1268   for (int i=0; i<npts; i++) {\r
1269     // skip not defined points\r
1270     if (intidx[idx[i]]<0) continue;\r
1271     atp->GetPoint(p,idx[i]);\r
1272 \r
1273     // prealign point if required\r
1274     // get IDEAL matrix\r
1275     AliITSAlignMille2Module *mod = GetMilleModule(intidx[idx[i]]);\r
1276     TGeoHMatrix *svOrigMatrix = mod->GetSensitiveVolumeOrigGlobalMatrix(p.GetVolumeID());\r
1277     // get back real local coordinates: use OriginalGlobalMatrix because AliTrackPoints were written\r
1278     // with idel geometry  \r
1279     Double_t pg[3],pl[3];\r
1280     pg[0]=p.GetX();\r
1281     pg[1]=p.GetY();\r
1282     pg[2]=p.GetZ();\r
1283     //    printf("Global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]);\r
1284     AliDebug(3,Form("Global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]));\r
1285     svOrigMatrix->MasterToLocal(pg,pl);\r
1286 \r
1287     AliDebug(3,Form("Local coordinates of measured point : X=%f  Y=%f  Z=%f \n",pl[0],pl[1],pl[2]));\r
1288     //\r
1289     // this is a temporary code to extract the drift speed used for given point\r
1290     if (p.GetDriftTime()>0) { // RRR\r
1291       // calculate the drift speed\r
1292       int sid = AliITSAlignMille2Module::GetIndexFromVolumeID(p.GetVolumeID());// - kSDDoffsID;\r
1293       fDriftTime0[npto] = fInitialRecSDD ? fInitialRecSDD->GetTimeZero(sid) : 0.;\r
1294       /*\r
1295       AliGeomManager::ELayerID lay = AliGeomManager::VolUIDToLayer(p.GetVolumeID());\r
1296       if      (lay==3) fDriftTime0[npto] = pg[2]<0 ? 169.5 : 140.1;\r
1297       else if (lay==4) fDriftTime0[npto] = pg[2]<0 ? 158.3 : 139.0;\r
1298       else {\r
1299         AliError(Form("Strange layer %d for moduleID %d",lay,p.GetVolumeID()));\r
1300         exit(1);\r
1301       }\r
1302       */\r
1303       double tdif = p.GetDriftTime() - fDriftTime0[npto];\r
1304       if (tdif<=0) tdif = 1;\r
1305       double vdrift = (3.5085-TMath::Abs(pl[0]))/tdif;\r
1306       if (vdrift<0) vdrift = 0;\r
1307       //\r
1308       // TEMPORARY CORRECTION (if provided) -------------->>>\r
1309       if (fCorrectSDD) {\r
1310         float t0Upd = fCorrectSDD->GetTimeZero(sid);\r
1311         vdrift += fCorrectSDD->GetDeltaVDrift(sid);\r
1312         tdif    = p.GetDriftTime() - t0Upd;\r
1313         // correct Xlocal\r
1314         pl[0] = TMath::Sign(3.5085 - vdrift*tdif,pl[0]);\r
1315         fDriftTime0[npto] =  t0Upd;\r
1316       }\r
1317       // TEMPORARY CORRECTION (if provided) --------------<<<\r
1318       fDriftSpeed[npto] = TMath::Sign(vdrift,pl[0]);\r
1319       //\r
1320       /*\r
1321       printf("%d  %+6.2f %+6.2f %+6.2f  %+5.2f %+5.2f %+5.2f  %+6.1f  %+6.1f %+f %+f\n",\r
1322              p.GetVolumeID(),pg[0],pg[1],pg[2],pl[0],pl[1],pl[2],p.GetDriftTime(), fDriftTime0[npto], fDriftSpeed[npto],tdif);\r
1323       */\r
1324     }\r
1325 \r
1326     // update covariance matrix\r
1327     TGeoHMatrix hcov;\r
1328     Double_t hcovel[9];\r
1329     hcovel[0]=double(p.GetCov()[0]);\r
1330     hcovel[1]=double(p.GetCov()[1]);\r
1331     hcovel[2]=double(p.GetCov()[2]);\r
1332     hcovel[3]=double(p.GetCov()[1]);\r
1333     hcovel[4]=double(p.GetCov()[3]);\r
1334     hcovel[5]=double(p.GetCov()[4]);\r
1335     hcovel[6]=double(p.GetCov()[2]);\r
1336     hcovel[7]=double(p.GetCov()[4]);\r
1337     hcovel[8]=double(p.GetCov()[5]);\r
1338     hcov.SetRotation(hcovel);\r
1339     // now rotate in local system\r
1340     //    printf("\nErrMatGlob: before\n"); hcov.Print(""); //RRR\r
1341     hcov.Multiply(svOrigMatrix);\r
1342     hcov.MultiplyLeft(&svOrigMatrix->Inverse());\r
1343     // now hcov is LOCAL COVARIANCE MATRIX\r
1344     // apply sigma scaling\r
1345     //    printf("\nErrMatLoc: before\n"); hcov.Print(""); //RRR\r
1346     Double_t *hcovscl = hcov.GetRotationMatrix(); \r
1347     //    for (int ir=3;ir--;) for (int ic=3;ic--;) hcovscl[ir*3+ic] *= mod->GetSigmaFactor(ir)*mod->GetSigmaFactor(ic); //RRR\r
1348     // RS TEMPORARY: nullify non-diagonal elements and sigY\r
1349     hcovscl[5] = 0;\r
1350     for (int ir=3;ir--;) for (int ic=3;ic--;) {\r
1351         if (ir==ic) {\r
1352           if (TMath::Abs(hcovscl[ir*3+ic])<kTiny) hcovscl[ir*3+ic] = 0.;\r
1353           else hcovscl[ir*3+ic] *= mod->GetSigmaFactor(ir)*mod->GetSigmaFactor(ic); //RRR\r
1354         }\r
1355         else hcovscl[ir*3+ic]  = 0;\r
1356       }\r
1357     //\r
1358     //    printf("\nErrMatLoc: after\n"); hcov.Print(""); //RRR\r
1359     //\r
1360     if (fBug==1) {\r
1361       // correzione bug LAYER 5  SSD temporanea..\r
1362       int ssdidx=AliITSAlignMille2Module::GetIndexFromVolumeID(p.GetVolumeID());\r
1363       if (ssdidx>=500 && ssdidx<1248) {\r
1364         int ladder=(ssdidx-500)%22;\r
1365         if (ladder==18) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx+1));\r
1366         if (ladder==19) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx-1));\r
1367       }\r
1368     }\r
1369     /// get (evenctually prealigned) matrix of sens. vol.\r
1370     TGeoHMatrix *svMatrix = mod->GetSensitiveVolumeMatrix(p.GetVolumeID());\r
1371     // modify global coordinates according with pre-aligment\r
1372     svMatrix->LocalToMaster(pl,pg);\r
1373     // now rotate in local system\r
1374     hcov.Multiply(&svMatrix->Inverse());\r
1375     hcov.MultiplyLeft(svMatrix);\r
1376     // hcov is back in GLOBAL RF\r
1377     // cure once more\r
1378     for (int ir=3;ir--;) for (int ic=3;ic--;) if (TMath::Abs(hcovscl[ir*3+ic])<kTiny) hcovscl[ir*3+ic] = 0.;\r
1379     //    printf("\nErrMatGlob: after\n"); hcov.Print(""); //RRR\r
1380     //\r
1381     Float_t pcov[6];\r
1382     pcov[0]=hcovscl[0];\r
1383     pcov[1]=hcovscl[1];\r
1384     pcov[2]=hcovscl[2];\r
1385     pcov[3]=hcovscl[4];\r
1386     pcov[4]=hcovscl[5];\r
1387     pcov[5]=hcovscl[8];\r
1388 \r
1389     p.SetXYZ(pg[0],pg[1],pg[2],pcov);\r
1390     //    printf("New Gl coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]);\r
1391     AliDebug(3,Form("New global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]));\r
1392     atps->AddPoint(npto,&p);\r
1393     AliDebug(2,Form("Adding point[%d] = ( %f , %f , %f )     volid = %d",npto,atps->GetX()[npto],\r
1394                     atps->GetY()[npto],atps->GetZ()[npto],atps->GetVolumeID()[npto] ));\r
1395     //    printf("Adding %d %d %f\n",npto, p.GetVolumeID(), p.GetY()); \r
1396     npto++;\r
1397   }\r
1398 \r
1399   return atps;\r
1400 }\r
1401 \r
1402 //________________________________________________________________________________________________________\r
1403 AliTrackPointArray *AliITSAlignMille2::SortTrack(const AliTrackPointArray *atp) \r
1404 {\r
1405   /// sort alitrackpoints w.r.t. global Y direction\r
1406   AliTrackPointArray *atps=NULL;\r
1407   Int_t idx[20];\r
1408   Int_t npts=atp->GetNPoints();\r
1409   AliTrackPoint p;\r
1410   atps=new AliTrackPointArray(npts);\r
1411 \r
1412   TMath::Sort(npts,atp->GetY(),idx);\r
1413 \r
1414   for (int i=0; i<npts; i++) {\r
1415     atp->GetPoint(p,idx[i]);\r
1416     atps->AddPoint(i,&p);\r
1417     AliDebug(2,Form("Point[%d] = ( %f , %f , %f )     volid = %d",i,atps->GetX()[i],atps->GetY()[i],atps->GetZ()[i],atps->GetVolumeID()[i] ));\r
1418   }\r
1419   return atps;\r
1420 }\r
1421 \r
1422 //________________________________________________________________________________________________________\r
1423 Int_t AliITSAlignMille2::GetCurrentLayer() const \r
1424 {\r
1425   // get current layer id\r
1426   if (!fGeoManager) {\r
1427     AliInfo("ITS geometry not initialized!");\r
1428     return -1;\r
1429   }\r
1430   return (Int_t)AliGeomManager::VolUIDToLayer(fCluster.GetVolumeID());\r
1431 }\r
1432 \r
1433 //________________________________________________________________________________________________________\r
1434 Int_t AliITSAlignMille2::InitModuleParams() \r
1435 {\r
1436   /// initialize geometry parameters for a given detector\r
1437   /// for current cluster (fCluster)\r
1438   /// fGlobalInitParam[] is set as:\r
1439   ///    [tx,ty,tz,psi,theta,phi]\r
1440   ///    (old was [tx,ty,tz,theta,psi,phi] ROOT's angles...)\r
1441   /// *** At the moment: using Raffalele's angles definition ***\r
1442   ///\r
1443   /// return 0 if success\r
1444   /// If module is found but has no parameters to vary, return 1\r
1445 \r
1446   if (!fGeoManager) {\r
1447     AliInfo("ITS geometry not initialized!");\r
1448     return -1;\r
1449   }\r
1450 \r
1451   // now 'voluid' is the volumeID of a SENSITIVE VOLUME (coming from a cluster)\r
1452 \r
1453   // set the internal index (index in module list)\r
1454   UShort_t voluid=fCluster.GetVolumeID();\r
1455   //\r
1456   // IT IS VERY IMPORTANT: start from the end of the list, where the childs are located !!!\r
1457   Int_t k=fNModules-1;\r
1458   fCurrentModule = 0;\r
1459   // VERY IMPORTANT: if the sensors were explicitly provided, don't look in the supermodules  \r
1460   while (k>=0 && ! (fCurrentModule=GetMilleModule(k))->IsIn(voluid)) k--;\r
1461   if (k<0) return -3;\r
1462   //\r
1463   /*\r
1464   // Check if the module has free params. If not, go over the parents\r
1465   AliITSAlignMille2Module* mdtmp = fCurrentModule;\r
1466   while (mdtmp && mdtmp->GetNParFree()==0) mdtmp = mdtmp->GetParent();\r
1467   if (!mdtmp) return 1; // nothing to vary here\r
1468   fCurrentModule = mdtmp;\r
1469   */\r
1470   //\r
1471   fModuleInitParam[0] = 0.0;\r
1472   fModuleInitParam[1] = 0.0;\r
1473   fModuleInitParam[2] = 0.0;\r
1474   fModuleInitParam[3] = 0.0; // psi   (X)\r
1475   fModuleInitParam[4] = 0.0; // theta (Y)\r
1476   fModuleInitParam[5] = 0.0; // phi   (Z)\r
1477   fModuleInitParam[6] = 0.0;\r
1478   fModuleInitParam[7] = 0.0;\r
1479   /// get (evenctually prealigned) matrix of sens. vol.\r
1480   TGeoHMatrix *svMatrix = fCurrentModule->GetSensitiveVolumeMatrix(voluid);\r
1481   \r
1482   fMeasGlo[0] = fCluster.GetX();\r
1483   fMeasGlo[1] = fCluster.GetY();\r
1484   fMeasGlo[2] = fCluster.GetZ(); \r
1485   svMatrix->MasterToLocal(fMeasGlo,fMeasLoc);  \r
1486   AliDebug(2,Form("Local coordinates of measured point : X=%f  Y=%f  Z=%f \n",fMeasLoc[0] ,fMeasLoc[1] ,fMeasLoc[2] ));\r
1487   \r
1488   // set stdev from cluster\r
1489   TGeoHMatrix hcov;\r
1490   Double_t hcovel[9];\r
1491   hcovel[0]=double(fCluster.GetCov()[0]);\r
1492   hcovel[1]=double(fCluster.GetCov()[1]);\r
1493   hcovel[2]=double(fCluster.GetCov()[2]);\r
1494   hcovel[3]=double(fCluster.GetCov()[1]);\r
1495   hcovel[4]=double(fCluster.GetCov()[3]);\r
1496   hcovel[5]=double(fCluster.GetCov()[4]);\r
1497   hcovel[6]=double(fCluster.GetCov()[2]);\r
1498   hcovel[7]=double(fCluster.GetCov()[4]);\r
1499   hcovel[8]=double(fCluster.GetCov()[5]);\r
1500   hcov.SetRotation(hcovel);\r
1501   // now rotate in local system\r
1502   hcov.Multiply(svMatrix);\r
1503   hcov.MultiplyLeft(&svMatrix->Inverse());\r
1504   //\r
1505   // set local sigmas\r
1506   fSigmaLoc[0] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[0]));\r
1507   fSigmaLoc[1] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[4])); // RS\r
1508   fSigmaLoc[2] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[8]));\r
1509 \r
1510   // set minimum value for SigmaLoc to 10 micron \r
1511   if (fSigmaLoc[0]<0.0010) fSigmaLoc[0]=0.0010;\r
1512   if (fSigmaLoc[2]<0.0010) fSigmaLoc[2]=0.0010;\r
1513   //\r
1514   /* RRR the rescaling is moved to PrepareTrack\r
1515   // multiply local sigmas by global and module specific factor \r
1516   for (int i=3;i--;) fSigmaLoc[i] *= fSigmaFactor[i]*fCurrentModule->GetSigmaFactor(i);\r
1517   //\r
1518   */\r
1519   AliDebug(2,Form("Setting StDev from CovMat : fSigmaLocX=%g  fSigmaLocY=%g fSigmaLocZ=%g \n",fSigmaLoc[0] ,fSigmaLoc[1] ,fSigmaLoc[2] ));\r
1520    \r
1521   return 0;\r
1522 }\r
1523 \r
1524 //________________________________________________________________________________________________________\r
1525 void AliITSAlignMille2::Print(Option_t*) const \r
1526 {\r
1527   // print current status \r
1528   printf("*** AliMillepede for ITS ***\n");\r
1529   printf("    Number of defined super modules: %d\n",fNModules);\r
1530   printf("    Obtained parameters refer to %s Deltas\n",fUseGlobalDelta ? "GLOBAL":"LOCAL");\r
1531   //\r
1532   if (fGeoManager)\r
1533     printf("    geometry loaded from %s\n",fGeometryFileName.Data());\r
1534   else\r
1535     printf("    geometry not loaded\n");\r
1536   //  \r
1537   if (fUsePreAlignment) \r
1538     printf("    using prealignment from %s \n",fPreAlignmentFileName.Data());\r
1539   else\r
1540     printf("    prealignment not used\n");    \r
1541   //\r
1542   //\r
1543   if (fBOn) \r
1544     printf("    B Field set to %f T - using Riemann's helices\n",fBField);\r
1545   else\r
1546     printf("    B Field OFF - using straight lines \n");\r
1547   //\r
1548   if (fRequirePoints) printf("    Required points in tracks:\n");\r
1549   for (Int_t i=0; i<6; i++) {\r
1550     if (fNReqLayUp[i]>0) printf("        Layer %d : %d points with Y>0\n",i+1,fNReqLayUp[i]);\r
1551     if (fNReqLayDown[i]>0) printf("        Layer %d : %d points with Y<0\n",i+1,fNReqLayDown[i]);\r
1552     if (fNReqLay[i]>0) printf("        Layer %d : %d points \n",i+1,fNReqLay[i]);\r
1553   }\r
1554   for (Int_t i=0; i<3; i++) {\r
1555     if (fNReqDetUp[i]>0) printf("        Detector %d : %d points with Y>0\n",i+1,fNReqDetUp[i]);\r
1556     if (fNReqDetDown[i]>0) printf("        Detector %d : %d points with Y<0\n",i+1,fNReqDetDown[i]);\r
1557     if (fNReqDet[i]>0) printf("        Detector %d : %d points \n",i+1,fNReqDet[i]);\r
1558   }\r
1559   //  \r
1560   printf("\n    Millepede configuration parameters:\n");\r
1561   printf("        init value for chi2 cut       : %.4f\n",fStartFac);\r
1562   printf("        first iteration cut value     : %.4f\n",fResCutInitial);\r
1563   printf("        other iterations cut value    : %.4f\n",fResCut);\r
1564   printf("        number of stddev for chi2 cut : %d\n",fNStdDev);\r
1565   printf("        def.scaling for local sigmas  : %.4f %.4f %.4f\n",fSigmaFactor[0],fSigmaFactor[1],fSigmaFactor[2]);\r
1566 \r
1567   printf("List of defined modules:\n");\r
1568   printf("  intidx\tindex\tvoluid\tname\n");\r
1569   for (int i=0; i<fNModules; i++) {\r
1570     AliITSAlignMille2Module* md = GetMilleModule(i); \r
1571     printf("  %d\t%d\t%d\t%s\n",i,md->GetIndex(),md->GetVolumeID(),md->GetName());\r
1572   }\r
1573 }\r
1574 \r
1575 //________________________________________________________________________________________________________\r
1576 AliITSAlignMille2Module  *AliITSAlignMille2::GetMilleModuleByVID(UShort_t voluid) const\r
1577 {\r
1578   // return pointer to a defined supermodule\r
1579   // return NULL if error\r
1580   Int_t i=IsVIDDefined(voluid);\r
1581   if (i<0) return NULL;\r
1582   return GetMilleModule(i);\r
1583 }\r
1584 \r
1585 //________________________________________________________________________________________________________\r
1586 AliITSAlignMille2Module  *AliITSAlignMille2::GetMilleModuleBySymName(const Char_t* symname) const\r
1587 {\r
1588   // return pointer to a defined supermodule\r
1589   // return NULL if error\r
1590   UShort_t vid = AliITSAlignMille2Module::GetVolumeIDFromSymname(symname);\r
1591   if (vid>0) return GetMilleModuleByVID(vid);\r
1592   else {    // this is not alignable module, need to look within defined supermodules\r
1593     int i = IsSymDefined(symname);\r
1594     if (i>=0) return  GetMilleModule(i);\r
1595   }\r
1596   return 0;\r
1597 }\r
1598 \r
1599 //________________________________________________________________________________________________________\r
1600 AliITSAlignMille2Module  *AliITSAlignMille2::GetMilleModuleIfContained(const Char_t* symname) const\r
1601 {\r
1602   // return pointer to a defined/contained supermodule\r
1603   // return NULL otherwise\r
1604   int i = IsSymContained(symname);\r
1605   return i<0 ? 0 : GetMilleModule(i);\r
1606 }\r
1607 \r
1608 //________________________________________________________________________________________________________\r
1609 AliAlignObjParams* AliITSAlignMille2::GetPrealignedObject(const Char_t* symname) const\r
1610 {\r
1611   // get delta from prealignment for given volume\r
1612   if (!fPrealignment) return 0;\r
1613   for (int ipre=fPrealignment->GetEntriesFast();ipre--;) { // was the corresponding object prealigned?\r
1614     AliAlignObjParams* preob = (AliAlignObjParams*)fPrealignment->At(ipre);\r
1615     if (!strcmp(preob->GetSymName(),symname)) return preob;\r
1616   }\r
1617   return 0;\r
1618 }\r
1619 \r
1620 //________________________________________________________________________________________________________\r
1621 AliAlignObjParams* AliITSAlignMille2::GetConstrRefObject(const Char_t* symname) const\r
1622 {\r
1623   // get delta with respect to which the constraint is declared\r
1624   if (!fConstrRef) return 0;\r
1625   for (int ipre=fConstrRef->GetEntriesFast();ipre--;) { // was the corresponding object prealigned?\r
1626     AliAlignObjParams* preob = (AliAlignObjParams*)fConstrRef->At(ipre);\r
1627     if (!strcmp(preob->GetSymName(),symname)) return preob;\r
1628   }\r
1629   return 0;\r
1630 }\r
1631 \r
1632 //________________________________________________________________________________________________________\r
1633 Bool_t AliITSAlignMille2::InitRiemanFit() \r
1634 {\r
1635   // Initialize Riemann Fitter for current track\r
1636   // return kFALSE if error\r
1637 \r
1638   if (!fBOn) return kFALSE;\r
1639 \r
1640   Int_t npts=0;\r
1641   AliTrackPoint ap;\r
1642   npts = fTrack->GetNPoints();\r
1643   AliDebug(3,Form("Fitting track with %d points",npts));\r
1644 \r
1645   fRieman->Reset();\r
1646   fRieman->SetTrackPointArray(fTrack);\r
1647 \r
1648   TArrayI ai(npts);\r
1649   for (Int_t ipt=0; ipt<npts; ipt++) ai[ipt]=fTrack->GetVolumeID()[ipt];\r
1650   \r
1651   // fit track with 5 params in his own tracking-rotated reference system\r
1652   // xc = -p[1]/p[0];\r
1653   // yc = 1/p[0];\r
1654   // R  = sqrt( x0*x0 + y0*y0 - y0*p[2]);\r
1655   if (!fRieman->Fit(&ai,NULL,(AliGeomManager::ELayerID)1,(AliGeomManager::ELayerID)6)) {\r
1656     return kFALSE;\r
1657   }\r
1658 \r
1659   for (int i=0; i<5; i++)\r
1660     fLocalInitParam[i] = fRieman->GetParam()[i];\r
1661   \r
1662   return kTRUE;\r
1663 }\r
1664 \r
1665 //________________________________________________________________________________________________________\r
1666 void trackFit2D(Int_t &, Double_t *, double &chi2, double *par, int flag)\r
1667 {\r
1668   // local function for minuit\r
1669   const double kTiny = 1.e-14;\r
1670   chi2 = 0;\r
1671   static AliTrackPoint pnt;\r
1672   static Bool_t fullErr2D;\r
1673   //\r
1674   if (flag==1) fullErr2D = kFALSE;//kTRUE;\r
1675   enum {kAX,kAZ,kBX,kBZ};\r
1676   enum {kXX=0,kXY=1,kXZ=2,kYX=kXY,kYY=3,kYZ=4,kZX=kXZ,kZY=kYZ,kZZ=5};\r
1677   //\r
1678   AliITSAlignMille2* alig = AliITSAlignMille2::GetInstance();\r
1679   AliTrackPointArray* track = alig->GetCurrentTrack();\r
1680   //\r
1681   int npts = track->GetNPoints();\r
1682   for (int ip=0;ip<npts;ip++) {\r
1683     track->GetPoint(pnt,ip);\r
1684     const float *cov = pnt.GetCov();\r
1685     double y  = pnt.GetY();\r
1686     double dx = pnt.GetX() - (par[kAX]+y*par[kBX]);\r
1687     double dz = pnt.GetZ() - (par[kAZ]+y*par[kBZ]);\r
1688     double xxe = cov[kXX];\r
1689     double zze = cov[kZZ];\r
1690     double xze = cov[kXZ];\r
1691     //\r
1692     if (fullErr2D) {\r
1693       xxe += par[kBX]*par[kBX]*cov[kYY]-2.*par[kBX]*cov[kXY];\r
1694       zze += par[kBZ]*par[kBZ]*cov[kYY]-2.*par[kBZ]*cov[kZY];\r
1695       xze += par[kBX]*par[kBZ]*cov[kYY]-cov[kYZ]*par[kBZ]-cov[kXY]*par[kBX];\r
1696     }\r
1697     //\r
1698     double det = xxe*zze - xze*xze;\r
1699     if (det<kTiny) {\r
1700       printf("Negative diag. error (det=%+e) |sxx:%+e szz:%+e sxz:%+e| bx:%+e bz:%+e|\n"\r
1701              "Discarding correlation term\n",det,xxe,zze,xze,par[kBX],par[kBZ]);\r
1702       xxe = cov[kXX];\r
1703       zze = cov[kZZ];\r
1704       xze = cov[kXZ];\r
1705       fullErr2D = kFALSE;\r
1706     }\r
1707     double xxeI = zze/det;\r
1708     double zzeI = xxe/det;\r
1709     double xzeI =-xze/det;\r
1710     //\r
1711     chi2 += dx*dx*xxeI + dz*dz*zzeI + 2.*dx*dz*xzeI;\r
1712     // \r
1713     //    printf("%d | %+e %+e %+e %+e %+e -> %+e\n",ip,dx,dz,xxeI,zzeI,xzeI,  chi2);\r
1714   }\r
1715   //\r
1716 }\r
1717 \r
1718 //________________________________________________________________________________________________________\r
1719 void AliITSAlignMille2::InitTrackParams(int meth) \r
1720 {\r
1721   /// initialize local parameters with different methods\r
1722   /// for current track (fTrack)\r
1723   Int_t npts=0;\r
1724   AliTrackPoint ap;\r
1725   double sX=0,sXY=0,sZ=0,sZY=0,sY=0,sYY=0,det=0;\r
1726   // simple linear interpolation\r
1727   // get local starting parameters (to be substituted by ESD track parms)\r
1728   // local parms (fLocalInitParam[]) are:\r
1729   //      [0] = global x coord. of straight line intersection at y=0 plane\r
1730   //      [1] = global z coord. of straight line intersection at y=0 plane\r
1731   //      [2] = px/py  \r
1732   //      [3] = pz/py\r
1733   // test #1: linear fit in x(y) and z(y)\r
1734   npts = fTrack->GetNPoints();\r
1735   AliDebug(3,Form("*** initializing track with %d points ***",npts));\r
1736   for (int i=npts;i--;) {\r
1737     sY  += fTrack->GetY()[i];\r
1738     sYY += fTrack->GetY()[i]*fTrack->GetY()[i];\r
1739     sX  += fTrack->GetX()[i];\r
1740     sXY += fTrack->GetX()[i]*fTrack->GetY()[i];\r
1741     sZ  += fTrack->GetZ()[i];\r
1742     sZY += fTrack->GetZ()[i]*fTrack->GetY()[i];\r
1743   }\r
1744   det = sYY*npts-sY*sY;\r
1745   if (det==0) det = 1E-20;\r
1746   fLocalInitParam[0] = (sX*sYY-sY*sXY)/det;\r
1747   fLocalInitParam[2] = (sXY*npts-sY*sX)/det;\r
1748   //\r
1749   fLocalInitParam[1] = (sZ*sYY-sY*sZY)/det;\r
1750   fLocalInitParam[3] = (sZY*npts-sY*sZ)/det;\r
1751   // pepo200709\r
1752   fLocalInitParam[4] = 0.0;\r
1753   // endpepo200709\r
1754 \r
1755   AliDebug(2,Form("X = p0gx + ugx*Y : p0gx = %f    ugx = %f\n",fLocalInitParam[0],fLocalInitParam[2]));\r
1756   //\r
1757   if (meth==1) return;\r
1758   //\r
1759   // perform full fit accounting for cov.matrix\r
1760   static TVirtualFitter *minuit = 0;\r
1761   static Double_t step[5]   = {1E-3,1E-3,1E-4,1E-4,1E-5};\r
1762   static Double_t arglist[10];\r
1763   //\r
1764   if (!minuit) {\r
1765     minuit = TVirtualFitter::Fitter(0,4);\r
1766     minuit->SetFCN(trackFit2D);\r
1767     arglist[0] = 1;\r
1768     minuit->ExecuteCommand("SET ERR",arglist, 1);\r
1769     //\r
1770     arglist[0] = -1;\r
1771     minuit->ExecuteCommand("SET PRINT",arglist,1);\r
1772     //\r
1773   }\r
1774   //\r
1775   minuit->SetParameter(0, "ax",   fLocalInitParam[0], step[0], 0,0);\r
1776   minuit->SetParameter(1, "az",   fLocalInitParam[1], step[1], 0,0);\r
1777   minuit->SetParameter(2, "bx",   fLocalInitParam[2], step[2], 0,0);\r
1778   minuit->SetParameter(3, "bz",   fLocalInitParam[3], step[3], 0,0);\r
1779   //\r
1780   arglist[0] = 1000; // number of function calls \r
1781   arglist[1] = 0.001; // tolerance \r
1782   minuit->ExecuteCommand("MIGRAD",arglist,2);\r
1783   //\r
1784   for (int i=0;i<4;i++) fLocalInitParam[i] = minuit->GetParameter(i);\r
1785   for (int i=0;i<4;i++) for (int j=0;j<4;j++) fLocalInitParEr[i][j] = minuit->GetCovarianceMatrixElement(i,j);\r
1786   //\r
1787 }\r
1788 \r
1789 //________________________________________________________________________________________________________\r
1790 Int_t AliITSAlignMille2::IsSymDefined(const Char_t* symname) const\r
1791 {\r
1792   // checks if supermodule with this symname is defined and return the internal index\r
1793   // return -1 if not.\r
1794   for (int k=fNModules;k--;) if (!strcmp(symname,GetMilleModule(k)->GetName())) return k;\r
1795   return -1; \r
1796 }\r
1797 \r
1798 //________________________________________________________________________________________________________\r
1799 Int_t AliITSAlignMille2::IsSymContained(const Char_t* symname) const\r
1800 {\r
1801   // checks if module with this symname is defined and return the internal index\r
1802   // return -1 if not.\r
1803   UShort_t vid = AliITSAlignMille2Module::GetVolumeIDFromSymname(symname);\r
1804   if (vid>0) return IsVIDContained(vid);\r
1805   // only sensors have real vid, but maybe we have a supermodule with fake vid? \r
1806   // IMPORTANT: always start from the end to start from the sensors\r
1807   return IsSymDefined(symname);\r
1808 }\r
1809 \r
1810 //________________________________________________________________________________________________________\r
1811 Int_t AliITSAlignMille2::IsVIDDefined(UShort_t voluid) const\r
1812 {\r
1813   // checks if supermodule 'voluid' is defined and return the internal index\r
1814   // return -1 if not.\r
1815   for (int k=fNModules;k--;) if (voluid==GetMilleModule(k)->GetVolumeID()) return k;\r
1816   return -1; \r
1817 }\r
1818 \r
1819 //________________________________________________________________________________________________________\r
1820 Int_t AliITSAlignMille2::IsVIDContained(UShort_t voluid) const\r
1821 {\r
1822   // checks if the sensitive module 'voluid' is contained inside a supermodule \r
1823   // and return the internal index of the last identified supermodule\r
1824   // return -1 if error\r
1825   // IMPORTANT: always start from the end to start from the sensors\r
1826   if (AliITSAlignMille2Module::GetIndexFromVolumeID(voluid)<0) return -1;\r
1827   for (int k=fNModules;k--;) if (GetMilleModule(k)->IsIn(voluid)) return k;\r
1828   return -1; \r
1829 }\r
1830 \r
1831 //________________________________________________________________________________________________________\r
1832 Int_t AliITSAlignMille2::CheckCurrentTrack() \r
1833 {\r
1834   /// checks if AliTrackPoints belongs to defined modules\r
1835   /// return number of good poins\r
1836   /// return 0 if not enough points\r
1837 \r
1838   Int_t npts = fTrack->GetNPoints();\r
1839   Int_t ngoodpts=0;\r
1840   // debug points\r
1841   for (int j=0; j<npts; j++) if (IsVIDContained(fTrack->GetVolumeID()[j])>=0) ngoodpts++;\r
1842   //\r
1843   if (ngoodpts<fMinNPtsPerTrack) return 0;\r
1844 \r
1845   return ngoodpts;\r
1846 }\r
1847 \r
1848 //________________________________________________________________________________________________________\r
1849 Int_t AliITSAlignMille2::ProcessTrack(const AliTrackPointArray *track) \r
1850 {\r
1851   /// Process track; Loop over hits and set local equations\r
1852   /// here 'track' is a AliTrackPointArray\r
1853   /// return 0 if success;\r
1854   \r
1855   if (!fIsMilleInit) Init();\r
1856   //\r
1857   Int_t npts = track->GetNPoints();\r
1858   AliDebug(2,Form("*** Input track with %d points ***",npts));\r
1859 \r
1860   // preprocessing of the input track: keep only points in defined volumes,\r
1861   // move points if prealignment is set, sort by Yglo if required\r
1862   \r
1863   fTrack=PrepareTrack(track);\r
1864   if (!fTrack) return -1;\r
1865 \r
1866   npts = fTrack->GetNPoints();\r
1867   if (npts>kMaxPoints) {\r
1868     AliError(Form("Compiled with kMaxPoints=%d, current track has %d points",kMaxPoints,npts));\r
1869   }\r
1870   AliDebug(2,Form("*** Processing prepared track with %d points ***",npts));\r
1871   \r
1872   if (!fBOn) { // straight lines  \r
1873     // set local starting parameters (to be substituted by ESD track parms)\r
1874     // local parms (fLocalInitParam[]) are:\r
1875     //      [0] = global x coord. of straight line intersection at y=0 plane\r
1876     //      [1] = global z coord. of straight line intersection at y=0 plane\r
1877     //      [2] = px/py  \r
1878     //      [3] = pz/py\r
1879     InitTrackParams(fInitTrackParamsMeth);  \r
1880   } \r
1881   else {\r
1882     // local parms (fLocalInitParam[]) are the Riemann Fitter params\r
1883     if (!InitRiemanFit()) {\r
1884       AliInfo("Riemann fit failed! skipping this track...");\r
1885       fTrack=NULL;\r
1886       return -5;\r
1887     }\r
1888   }\r
1889   \r
1890   Int_t nloceq=0;\r
1891   Int_t ngloeq=0;\r
1892   static Mille2Data md[kMaxPoints];\r
1893   //\r
1894   for (Int_t ipt=0; ipt<npts; ipt++) {\r
1895     fTrack->GetPoint(fCluster,ipt);\r
1896     fCluster.SetUniqueID(ipt);\r
1897     AliDebug(2,Form("\n--- processing point %d --- \n",ipt));    \r
1898 \r
1899     // set geometry parameters for the the current module\r
1900     if (InitModuleParams()) continue;\r
1901     AliDebug(2,Form("    VolID=%d  Index=%d  InternalIdx=%d  symname=%s\n", \r
1902                     track->GetVolumeID()[ipt], fCurrentModule->GetIndex(),\r
1903                     fCurrentModule->GetUniqueID(), AliGeomManager::SymName(track->GetVolumeID()[ipt]) ));\r
1904     AliDebug(2,Form("    Preprocessed Point = ( %f , %f , %f ) \n",fCluster.GetX(),fCluster.GetY(),fCluster.GetZ()));\r
1905     int res = AddLocalEquation(md[nloceq]);\r
1906     if (res<0) {fTotBadLocEqPoints++; nloceq = 0; break;}\r
1907     else if (res==0) nloceq++;\r
1908     else {nloceq++; ngloeq++;}\r
1909   } // end loop over points\r
1910   //\r
1911   fTrack=NULL;\r
1912   // not enough good points?\r
1913   if (nloceq<fMinNPtsPerTrack || ngloeq<1) return -1;\r
1914   //\r
1915   // finally send local equations to millepede\r
1916   SetLocalEquations(md,nloceq);\r
1917   fMillepede->SaveRecordData(); // RRR\r
1918   //\r
1919   return 0;\r
1920 }\r
1921 \r
1922 //________________________________________________________________________________________________________\r
1923 Int_t AliITSAlignMille2::CalcIntersectionPoint(Double_t *lpar, Double_t *gpar) \r
1924 {\r
1925   /// calculate track intersection point in local coordinates\r
1926   /// according with a given set of parameters (local(4) and global(6))\r
1927   /// and fill fPintLoc/Glo\r
1928   ///    local are:   pgx0, pgz0, ugx, ugz   OR   riemann fitters pars\r
1929   ///    global are:  tx,ty,tz,psi,theta,phi (Raff's delta angles in deg.)\r
1930   /// return 0 if success\r
1931   \r
1932   AliDebug(3,Form("lpar = %g %g %g %g %g\ngpar= %g %g %g %g %g %g\n",lpar[0],lpar[1],lpar[2],lpar[3],lpar[4],gpar[0],gpar[1],gpar[2],gpar[3],gpar[4],gpar[5]));\r
1933   AliDebug(3,Form("deltalpar = %g %g %g %g %g\n",lpar[0]-fLocalInitParam[0],lpar[1]-fLocalInitParam[1],lpar[2]-fLocalInitParam[2],lpar[3]-fLocalInitParam[3],lpar[4]-fLocalInitParam[4]));\r
1934 \r
1935   \r
1936   // prepare the TGeoHMatrix\r
1937   TGeoHMatrix *tempHMat = fCurrentModule->GetSensitiveVolumeModifiedMatrix(fCluster.GetVolumeID(),gpar,\r
1938                                                                            !fUseGlobalDelta);\r
1939   if (!tempHMat) return -1;\r
1940   \r
1941   Double_t v0g[3]; // vector with straight line direction in global coord.\r
1942   Double_t p0g[3]; // point of the straight line (glo)\r
1943   \r
1944   if (fBOn) { // B FIELD!\r
1945     AliTrackPoint prf; \r
1946     for (int ip=0; ip<5; ip++)\r
1947       fRieman->SetParam(ip,lpar[ip]);\r
1948 \r
1949     if (!fRieman->GetPCA(fCluster,prf))  {\r
1950       AliInfo(Form("error in GetPCA for point %d",fCluster.GetVolumeID()));\r
1951       return -3;\r
1952     }\r
1953     // now determine straight line passing tangent to fit curve at prf\r
1954     // ugx = dX/dY_glo = DeltaX/DeltaY_glo\r
1955     // mo' P1=(X,Y,Z)_glo_prf\r
1956     //       => (x,y,Z)_trk_prf ruotando di alpha...\r
1957     Double_t alpha=fRieman->GetAlpha();\r
1958     Double_t x1g = prf.GetX();\r
1959     Double_t y1g = prf.GetY();\r
1960     Double_t z1g = prf.GetZ();\r
1961     Double_t x1t =  x1g*TMath::Cos(alpha) + y1g*TMath::Sin(alpha);\r
1962     Double_t y1t = -x1g*TMath::Sin(alpha) + y1g*TMath::Cos(alpha);\r
1963     Double_t z1t =  z1g;    \r
1964 \r
1965     Double_t x2t = x1t+1.0;\r
1966     Double_t y2t = y1t+fRieman->GetDYat(x1t);\r
1967     Double_t z2t = z1t+fRieman->GetDZat(x1t);\r
1968     Double_t x2g =  x2t*TMath::Cos(alpha) - y2t*TMath::Sin(alpha);\r
1969     Double_t y2g =  x2t*TMath::Sin(alpha) + y2t*TMath::Cos(alpha);\r
1970     Double_t z2g =  z2t;  \r
1971 \r
1972     AliDebug(3,Form("Riemann frame:  fAlpha = %f  =  %f  ",alpha,alpha*180./TMath::Pi()));\r
1973     AliDebug(3,Form("   prf_glo=( %f , %f , %f )  prf_rf=( %f , %f , %f )\n", x1g,y1g,z1g, x1t,y1t,z1t));\r
1974     AliDebug(3,Form("   mov_glo=( %f , %f , %f )      rf=( %f , %f , %f )\n",x2g,y2g,z2g, x2t,y2t,z2t));\r
1975         \r
1976     if (TMath::Abs(y2g-y1g)<1e-15) {\r
1977       AliInfo("DeltaY=0! Cannot proceed...");\r
1978       return -1;\r
1979     }\r
1980     // ugx,1,ugz\r
1981     v0g[0] = (x2g-x1g)/(y2g-y1g);\r
1982     v0g[1]=1.0;\r
1983     v0g[2] = (z2g-z1g)/(y2g-y1g);\r
1984     \r
1985     // point: just keep prf\r
1986     p0g[0]=x1g;\r
1987     p0g[1]=y1g;\r
1988     p0g[2]=z1g;\r
1989   }  \r
1990   else { // staight line\r
1991     // vector of initial straight line direction in glob. coord\r
1992     v0g[0]=lpar[2];\r
1993     v0g[1]=1.0;\r
1994     v0g[2]=lpar[3];\r
1995     \r
1996     // intercept in yg=0 plane in glob coord\r
1997     p0g[0]=lpar[0];\r
1998     p0g[1]=0.0;\r
1999     p0g[2]=lpar[1];\r
2000   }\r
2001   AliDebug(3,Form("Line vector: ( %f , %f , %f )  point:( %f , %f , %f )\n",v0g[0],v0g[1],v0g[2],p0g[0],p0g[1],p0g[2]));\r
2002   \r
2003   // same in local coord.\r
2004   Double_t p0l[3],v0l[3];\r
2005   tempHMat->MasterToLocalVect(v0g,v0l);\r
2006   tempHMat->MasterToLocal(p0g,p0l);\r
2007   \r
2008   if (TMath::Abs(v0l[1])<1e-15) {\r
2009     AliInfo("Track Y direction in local frame is zero! Cannot proceed...");\r
2010     return -1;\r
2011   }\r
2012   \r
2013   // local intersection point\r
2014   fPintLoc[0] = p0l[0] - (v0l[0]/v0l[1])*p0l[1];\r
2015   fPintLoc[1] = 0;\r
2016   fPintLoc[2] = p0l[2] - (v0l[2]/v0l[1])*p0l[1];\r
2017   \r
2018   // global intersection point\r
2019   tempHMat->LocalToMaster(fPintLoc,fPintGlo);\r
2020   AliDebug(3,Form("Intesect. point: L( %f , %f , %f )  G( %f , %f , %f )\n",fPintLoc[0],fPintLoc[1],fPintLoc[2],fPintGlo[0],fPintGlo[1],fPintGlo[2]));\r
2021   \r
2022   return 0;\r
2023 }\r
2024 \r
2025 //________________________________________________________________________________________________________\r
2026 Int_t AliITSAlignMille2::CalcDerivatives(Int_t paridx, Bool_t islpar) \r
2027 {\r
2028   /// calculate numerically (ROOT's style) the derivatives for\r
2029   /// local X intersection  and local Z intersection\r
2030   /// parlist: local  (islpar=kTRUE)  pgx0, pgz0, ugx0, ugz0  OR riemann's params\r
2031   ///          global (islpar=kFALSE) tx, ty, tz, psi, theta, phi (Raf's angles in deg)\r
2032   /// return 0 if success\r
2033   \r
2034   // copy initial parameters\r
2035   Double_t lpar[kNLocal];\r
2036   Double_t gpar[kNParCh];\r
2037   Double_t *derivative;\r
2038   for (Int_t i=0; i<kNLocal; i++) lpar[i]=fLocalInitParam[i];\r
2039   for (Int_t i=0; i<kNParCh; i++) gpar[i]=fModuleInitParam[i];\r
2040 \r
2041   // trial with fixed dpar...\r
2042   Double_t dpar = 0.;\r
2043 \r
2044   if (islpar) { // track parameters\r
2045     //dpar=fLocalInitParam[paridx]*0.001;\r
2046     // set minimum dpar\r
2047     derivative = fDerivativeLoc[paridx];\r
2048     if (!fBOn) {\r
2049       if (paridx<3) dpar=1.0e-4; // translations\r
2050       else dpar=1.0e-6; // direction\r
2051     }\r
2052     else { // B Field\r
2053       // pepo: proviamo con 1/1000, poi evenctually 1/100...\r
2054       Double_t dfrac=0.01;\r
2055       switch(paridx) {\r
2056       case 0:\r
2057         // RMS cosmics: 1e-4\r
2058         dpar = TMath::Max(1.0e-6,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2059         break;\r
2060       case 1: \r
2061         // RMS cosmics: 0.2\r
2062         dpar = TMath::Max(0.002,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2063         break;\r
2064       case 2: \r
2065         // RMS cosmics: 9\r
2066         dpar = TMath::Max(0.09,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2067         break;\r
2068       case 3: \r
2069         // RMS cosmics: 7\r
2070         dpar = TMath::Max(0.07,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2071         break;\r
2072       case 4: \r
2073         // RMS cosmics: 0.3\r
2074         dpar = TMath::Max(0.003,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2075         break;\r
2076       }\r
2077     }\r
2078   }\r
2079   else { // alignment global parameters\r
2080     derivative = fDerivativeGlo[paridx];\r
2081     //dpar=fModuleInitParam[paridx]*0.001;\r
2082     if (paridx<3) dpar=1.0e-4; // translations\r
2083     else dpar=1.0e-2; // angles    \r
2084   }\r
2085 \r
2086   AliDebug(3,Form("+++ using dpar=%g",dpar));\r
2087   \r
2088   // calculate derivative ROOT's like:\r
2089   //  using f(x+h),f(x-h),f(x+h/2),f(x-h2)...\r
2090   Double_t pintl1[3]; // f(x-h)\r
2091   Double_t pintl2[3]; // f(x-h/2)\r
2092   Double_t pintl3[3]; // f(x+h/2)\r
2093   Double_t pintl4[3]; // f(x+h)\r
2094     \r
2095   // first values\r
2096   if (islpar) lpar[paridx] -= dpar;\r
2097   else gpar[paridx] -= dpar;\r
2098   if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
2099   for (Int_t i=0; i<3; i++) pintl1[i]=fPintLoc[i];\r
2100 \r
2101   // second values\r
2102   if (islpar) lpar[paridx] += dpar/2;\r
2103   else gpar[paridx] += dpar/2;\r
2104   if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
2105   for (Int_t i=0; i<3; i++) pintl2[i]=fPintLoc[i];\r
2106 \r
2107   // third values\r
2108   if (islpar) lpar[paridx] += dpar;\r
2109   else gpar[paridx] += dpar;\r
2110   if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
2111   for (Int_t i=0; i<3; i++) pintl3[i]=fPintLoc[i];\r
2112 \r
2113   // fourth values\r
2114   if (islpar) lpar[paridx] += dpar/2;\r
2115   else gpar[paridx] += dpar/2;\r
2116   if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
2117   for (Int_t i=0; i<3; i++) pintl4[i]=fPintLoc[i];\r
2118 \r
2119   Double_t h2 = 1./(2.*dpar);\r
2120   Double_t d0 = pintl4[0]-pintl1[0];\r
2121   Double_t d2 = 2.*(pintl3[0]-pintl2[0]);\r
2122   derivative[0] = h2*(4*d2 - d0)/3.;\r
2123   if (TMath::Abs(derivative[0]) < 1.0e-9) derivative[0] = 0.0;\r
2124 \r
2125   d0 = pintl4[2]-pintl1[2];\r
2126   d2 = 2.*(pintl3[2]-pintl2[2]);\r
2127   derivative[2] = h2*(4*d2 - d0)/3.;\r
2128   if (TMath::Abs(derivative[2]) < 1.0e-9) derivative[2]=0.0;\r
2129 \r
2130   AliDebug(3,Form("\n+++ derivatives +++ \n"));\r
2131   AliDebug(3,Form("+++ dXLoc/dpar = %g +++\n",derivative[0]));\r
2132   AliDebug(3,Form("+++ dZLoc/dpar = %g +++\n\n",derivative[2]));\r
2133   \r
2134   return 0;\r
2135 }\r
2136 \r
2137 //________________________________________________________________________________________________________\r
2138 Int_t AliITSAlignMille2::AddLocalEquation(Mille2Data &m) \r
2139 {\r
2140   /// Define local equation for current cluster in X and Z coor.\r
2141   /// and store them to memory\r
2142   /// return -1 in case of failure to build some equation\r
2143   ///         0 if no free global parameters were found but local eq is built\r
2144   ///         1 if both local and global eqs are built\r
2145   //\r
2146   // store first intersection point\r
2147   if (CalcIntersectionPoint(fLocalInitParam, fModuleInitParam)) return -1;  \r
2148   for (Int_t i=0; i<3; i++) fPintLoc0[i]=fPintLoc[i];\r
2149   AliDebug(2,Form("Intesect. point: L( %f , %f , %f )",fPintLoc[0],fPintLoc[1],fPintLoc[2]));\r
2150   \r
2151   // calculate local derivatives numerically\r
2152   Bool_t zeroX = kTRUE;\r
2153   Bool_t zeroZ = kTRUE;\r
2154   //\r
2155   for (Int_t i=0; i<fNLocal; i++) {\r
2156     if (CalcDerivatives(i,kTRUE)) return -1;\r
2157     m.fDerLocX[i] = fDerivativeLoc[i][0];\r
2158     m.fDerLocZ[i] = fDerivativeLoc[i][2];\r
2159     if (zeroX) zeroX = fDerivativeLoc[i][0]==0;\r
2160     if (zeroZ) zeroZ = fDerivativeLoc[i][2]==0;\r
2161   }\r
2162   //  for (Int_t i=0; i<fNLocal; i++) AliDebug(2,Form("Local parameter %d - dXdpar = %g  - dZdpar = %g\n",i,dXdL[i],dZdL[i]));\r
2163   //\r
2164   if (zeroX) {AliInfo("Skipping: zero local X derivatives!"); return -1;}\r
2165   if (zeroZ) {AliInfo("Skipping: zero local Z derivatives!"); return -1;}\r
2166   //\r
2167   int ifill = 0;\r
2168   //\r
2169   AliITSAlignMille2Module* endModule = fCurrentModule;\r
2170   //\r
2171   zeroX = zeroZ = kTRUE;\r
2172   Bool_t dfDone[kNParCh];\r
2173   for (int i=kNParCh;i--;) dfDone[i] = kFALSE;\r
2174   m.fNModFilled = 0;\r
2175   // \r
2176   // special block for SDD derivatives\r
2177   Double_t jacobian[kNParChGeom];\r
2178   Int_t nmodTested = 0;\r
2179   //\r
2180   do {\r
2181     if (fCurrentModule->GetNParFree()==0) continue;\r
2182     nmodTested++;\r
2183     for (Int_t i=0; i<kNParChGeom; i++) {   // common for all sensors: derivatives over geom params \r
2184       //\r
2185       if (!fUseGlobalDelta) dfDone[i] = kFALSE; // for global deltas the derivatives at diff. levels are different\r
2186       if (fCurrentModule->GetParOffset(i)<0) continue; // this parameter is not explicitly fitted\r
2187       if (!dfDone[i]) { \r
2188         if (CalcDerivatives(i,kFALSE)) return -1; \r
2189         else {\r
2190           dfDone[i] = kTRUE;\r
2191           if (zeroX) zeroX = fDerivativeGlo[i][0]==0;\r
2192           if (zeroZ) zeroZ = fDerivativeGlo[i][2]==0;\r
2193         }\r
2194       }\r
2195       //\r
2196       m.fDerGloX[ifill] = fDerivativeGlo[i][0];\r
2197       m.fDerGloZ[ifill] = fDerivativeGlo[i][2];\r
2198       m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(i);\r
2199     }\r
2200     //\r
2201     // specific for special sensors\r
2202     if ( fCurrentModule->IsSDD() && \r
2203          (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0)>=0 ||\r
2204           fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV)>=0) ) {\r
2205       //\r
2206       // assume for sensor local xloc = xloc0 + V0*dT0+dV*(T-T0)\r
2207       // where V0 and T are the nominal drift velocity, time and time0\r
2208       // and the dT0 and dV are the corrections:\r
2209       // dX/dT0 = dX/dxloc * dxloc/dT0 = dX/dxloc * V0\r
2210       // dX/dV  = dX/dxloc * dxloc/dV =  dX/dxloc * (T-T0)\r
2211       // IMPORTANT: the geom derivatives are over the SENSOR LOCAL parameters\r
2212       //\r
2213       if (!dfDone[AliITSAlignMille2Module::kDOFT0] || !dfDone[AliITSAlignMille2Module::kDOFDV]) {\r
2214         //\r
2215         double dXdxlocsens=0., dZdxlocsens=0.;\r
2216         //\r
2217         // if the current module is the sensor itself and we work with local params, then \r
2218         // we can directly take dX/dxloc_sens dZ/dxloc_sens\r
2219         if (!fUseGlobalDelta && fCurrentModule->GetVolumeID()==fCluster.GetVolumeID()) {\r
2220           if (dfDone[AliITSAlignMille2Module::kDOFTX]) {\r
2221             CalcDerivatives(AliITSAlignMille2Module::kDOFTX,kFALSE); \r
2222             dfDone[AliITSAlignMille2Module::kDOFTX] = kTRUE;\r
2223           }\r
2224           dXdxlocsens = fDerivativeGlo[AliITSAlignMille2Module::kDOFTX][0];\r
2225           dZdxlocsens = fDerivativeGlo[AliITSAlignMille2Module::kDOFTX][2];\r
2226         }\r
2227         //\r
2228         else { // need to perform some transformations\r
2229           // fetch the jacobian of the transformation from the sensors local frame to the frame\r
2230           // where the parameters are defined:\r
2231           // Global: dX/dxloc_sens = dX/dxgl*dxgl/dxloc_sens + ...dX/dphigl*dphigl/dxloc_sens\r
2232           if (fUseGlobalDelta) fCurrentModule->CalcDerivGloLoc(fCluster.GetVolumeID(),\r
2233                                                                AliITSAlignMille2Module::kDOFTX, jacobian);\r
2234           // Local:  dX/dxloc_sens = dX/dxcurr*dxcurr/dxloc_sens +..+dX/dphicurr * dphicurr/dxloc_sens \r
2235           else                 fCurrentModule->CalcDerivCurLoc(fCluster.GetVolumeID(),\r
2236                                                                AliITSAlignMille2Module::kDOFTX, jacobian);\r
2237           //\r
2238           for (int j=0;j<kNParChGeom;j++) {\r
2239             // need global derivative even if the j-th param is locked\r
2240             if (!dfDone[j]) {CalcDerivatives(j,kFALSE); dfDone[j] = kTRUE;}\r
2241             dXdxlocsens += fDerivativeGlo[j][0] * jacobian[j];\r
2242             dZdxlocsens += fDerivativeGlo[j][2] * jacobian[j];\r
2243           }\r
2244         }\r
2245         //\r
2246         if (zeroX) zeroX = dXdxlocsens == 0;\r
2247         if (zeroZ) zeroZ = dZdxlocsens == 0;\r
2248         //\r
2249         double vdrift = GetVDriftSDD();\r
2250         double tdrift = GetTDriftSDD();\r
2251         //\r
2252         fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][0] = dXdxlocsens*vdrift;\r
2253         fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][2] = dZdxlocsens*vdrift;\r
2254         dfDone[AliITSAlignMille2Module::kDOFT0] = kTRUE;\r
2255         //\r
2256         fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][0] = -dXdxlocsens*TMath::Sign(tdrift,vdrift);\r
2257         fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][2] = -dZdxlocsens*TMath::Sign(tdrift,vdrift);\r
2258         dfDone[AliITSAlignMille2Module::kDOFDV] = kTRUE;\r
2259         //\r
2260       }\r
2261       //\r
2262       if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0)>=0) {\r
2263         m.fDerGloX[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][0];\r
2264         m.fDerGloZ[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][2];\r
2265         m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0);      \r
2266       }\r
2267       //\r
2268       if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV)>=0) {\r
2269         m.fDerGloX[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][0];\r
2270         m.fDerGloZ[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][2];\r
2271         m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV);      \r
2272       }\r
2273     }\r
2274     //\r
2275     m.fModuleID[m.fNModFilled++] = fCurrentModule->GetUniqueID();\r
2276   } while( (fCurrentModule=fCurrentModule->GetParent()) );\r
2277   //\r
2278   if (nmodTested>0 && zeroX) {AliInfo("Skipping: zero global X derivatives!");return -1;}\r
2279   if (nmodTested>0 && zeroZ) {AliInfo("Skipping: zero global Z derivatives!");return -1;}\r
2280   //\r
2281   // ok, can copy to m\r
2282   AliDebug(2,Form("Adding local equation X with fMeas=%.6f  and fSigma=%.6f",(fMeasLoc[0]-fPintLoc0[0]), fSigmaLoc[0]));\r
2283   m.fMeasX = fMeasLoc[0]-fPintLoc0[0];\r
2284   m.fSigmaX = fSigmaLoc[0];\r
2285   //\r
2286   AliDebug(2,Form("Adding local equation Z with fMeas=%.6f  and fSigma=%.6f",(fMeasLoc[2]-fPintLoc0[2]), fSigmaLoc[2]));\r
2287   m.fMeasZ = fMeasLoc[2]-fPintLoc0[2];\r
2288   m.fSigmaZ = fSigmaLoc[2];\r
2289   //\r
2290   m.fNGlobFilled = ifill;\r
2291   fCurrentModule = endModule;\r
2292   //\r
2293   return Int_t(!zeroX && !zeroZ);\r
2294 }\r
2295 \r
2296 //________________________________________________________________________________________________________\r
2297 void AliITSAlignMille2::SetLocalEquations(const Mille2Data *marr, Int_t neq) \r
2298 {\r
2299   /// Set local equations with data stored in m\r
2300   /// return 0 if success\r
2301   //\r
2302   for (Int_t j=0; j<neq; j++) {\r
2303     //\r
2304     const Mille2Data &m = marr[j];\r
2305     //\r
2306     // set equation for Xloc coordinate\r
2307     AliDebug(2,Form("setting local equation X with fMeas=%.6f  and fSigma=%.6f",m.fMeasX, m.fSigmaX));\r
2308     for (int i=fNLocal; i--;) SetLocalDerivative( i, m.fDerLocX[i] );\r
2309     for (int i=m.fNGlobFilled;i--;) SetGlobalDerivative( m.fParMilleID[i] , m.fDerGloX[i] );\r
2310     fMillepede->SetLocalEquation(fGlobalDerivatives, fLocalDerivatives, m.fMeasX, m.fSigmaX);  \r
2311     //\r
2312     // set equation for Zloc coordinate\r
2313     AliDebug(2,Form("setting local equation Z with fMeas=%.6f  and fSigma=%.6f",m.fMeasZ, m.fSigmaZ));\r
2314     for (int i=fNLocal; i--;) SetLocalDerivative( i, m.fDerLocZ[i] );\r
2315     for (int i=m.fNGlobFilled;i--;) SetGlobalDerivative( m.fParMilleID[i] , m.fDerGloZ[i] );\r
2316     fMillepede->SetLocalEquation(fGlobalDerivatives, fLocalDerivatives, m.fMeasZ, m.fSigmaZ);  \r
2317     //\r
2318     for (int i=m.fNModFilled;i--;) GetMilleModule(m.fModuleID[i])->IncNProcessedPoints();\r
2319     //\r
2320   }\r
2321 }\r
2322 \r
2323 //________________________________________________________________________________________________________\r
2324 Int_t AliITSAlignMille2::GlobalFit()\r
2325 {\r
2326   /// Call global fit; Global parameters are stored in parameters\r
2327   if (!fIsMilleInit) Init();\r
2328   //\r
2329   ApplyPreConstraints();\r
2330   int res = fMillepede->GlobalFit();\r
2331   AliInfo(Form("%s fitting global parameters!",res ? "Done":"Failed"));\r
2332   if (res) {\r
2333     // fetch the parameters\r
2334     for (int imd=fNModules;imd--;) {\r
2335       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2336       int nprocp = 0;\r
2337       for (int ip=mod->GetNParTot();ip--;) {\r
2338         int idp = mod->GetParOffset(ip);\r
2339         if (idp<0) continue;    // was not in the explicit fit\r
2340         mod->SetParVal(ip,fMillepede->GetFinalParam(idp));\r
2341         mod->SetParErr(ip,fMillepede->GetFinalError(idp));\r
2342         int np = fMillepede->GetProcessedPoints(idp);\r
2343         if (TMath::Abs(np)>TMath::Abs(nprocp)) nprocp = np;\r
2344       }\r
2345       if (!mod->GetNProcessedPoints()) mod->SetNProcessedPoints(nprocp);\r
2346     }\r
2347 \r
2348   }\r
2349   ApplyPostConstraints();\r
2350   return res;\r
2351 }\r
2352 \r
2353 //________________________________________________________________________________________________________\r
2354 void AliITSAlignMille2::PrintGlobalParameters() \r
2355 {\r
2356   /// Print global parameters\r
2357   if (!fIsMilleInit) {\r
2358     AliInfo("Millepede has not been initialized!");\r
2359     return;\r
2360   }\r
2361   fMillepede->PrintGlobalParameters();\r
2362 }\r
2363 \r
2364 //________________________________________________________________________________________________________\r
2365 Int_t AliITSAlignMille2::LoadSuperModuleFile(const Char_t *sfile)\r
2366\r
2367   // load definitions of supermodules from a root file\r
2368   // return 0 if success\r
2369 \r
2370   TFile *smf=TFile::Open(sfile);\r
2371   if (!smf->IsOpen()) {\r
2372     AliInfo(Form("Cannot open supermodule file %s",sfile));\r
2373     return -1;\r
2374   }\r
2375 \r
2376   TClonesArray *sma=(TClonesArray*)smf->Get("ITSMilleSuperModules");\r
2377   if (!sma) {\r
2378     AliInfo(Form("Cannot find ITSMilleSuperModules array in file"));\r
2379     return -2;  \r
2380   }  \r
2381   Int_t nsma=sma->GetEntriesFast();\r
2382   AliInfo(Form("Array of SuperModules with %d entries\n",nsma));\r
2383   //\r
2384   // pepo200709\r
2385   Char_t st[2048];\r
2386   char symname[250];\r
2387   // end pepo200709\r
2388 \r
2389   UShort_t volid;\r
2390   TGeoHMatrix m;\r
2391   //\r
2392   for (Int_t i=0; i<nsma; i++) {\r
2393     AliAlignObjParams *a = (AliAlignObjParams*)sma->UncheckedAt(i);\r
2394     volid=a->GetVolUID();\r
2395     strcpy(st,a->GetSymName());\r
2396     a->GetMatrix(m);\r
2397     //\r
2398     sscanf(st,"%s",symname);\r
2399     //\r
2400     // decode module list\r
2401     char *stp=strstr(st,"ModuleList:");\r
2402     if (!stp) return -3;\r
2403     stp += 11;\r
2404     int idx[2200];\r
2405     char spp[200]; int jp=0;\r
2406     char cl[20];\r
2407     strcpy(st,stp);\r
2408     int l=strlen(st);\r
2409     int j=0;\r
2410     int n=0;\r
2411     //\r
2412     while (j<=l) {\r
2413       if (st[j]==9 || st[j]==32 || st[j]==10 || st[j]==0) {\r
2414         spp[jp]=0;\r
2415         jp=0;\r
2416         if (strlen(spp)) {\r
2417           int k=strcspn(spp,"-");\r
2418           if (k<int(strlen(spp))) { // c'e' il -\r
2419             strcpy(cl,&(spp[k+1]));\r
2420             spp[k]=0;\r
2421             int ifrom=atoi(spp); int ito=atoi(cl);\r
2422             for (int b=ifrom; b<=ito; b++) {\r
2423               idx[n]=b;\r
2424               n++;\r
2425             }\r
2426           }\r
2427           else { // numerillo singolo\r
2428             idx[n]=atoi(spp);\r
2429             n++;\r
2430           }\r
2431         }\r
2432       }\r
2433       else {\r
2434         spp[jp]=st[j];\r
2435         jp++;\r
2436       }\r
2437       j++;\r
2438     }\r
2439     UShort_t volidsv[2198];\r
2440     for (j=0;j<n;j++) {\r
2441       volidsv[j]=AliITSAlignMille2Module::GetVolumeIDFromIndex(idx[j]);\r
2442       if (!volidsv[j]) {\r
2443         AliInfo(Form("Index %d not valid (range 0->%d)",idx[j],kMaxITSSensID));\r
2444         return -5;\r
2445       }\r
2446     }\r
2447     Int_t smindex=int(2198+volid-14336); // virtual index\r
2448     //\r
2449     fSuperModule.AddAtAndExpand(new AliITSAlignMille2Module(smindex,volid,symname,&m,n,volidsv),fNSuperModules);\r
2450     //\r
2451     fNSuperModules++;\r
2452   }\r
2453   //\r
2454   smf->Close();\r
2455   //\r
2456   return 0;\r
2457 }\r
2458 \r
2459 //________________________________________________________________________________________________________\r
2460 void AliITSAlignMille2::ConstrainModuleSubUnitsMean(Int_t idm, Double_t val, UInt_t pattern)\r
2461 {\r
2462   // require that sum of modifications for the childs of this module is = val, i.e.\r
2463   // the internal corrections moves the module as a whole by fixed value (0 by default).\r
2464   // pattern is the bit pattern for the parameters to constrain\r
2465   //\r
2466   if (fIsMilleInit) {\r
2467     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2468     return;\r
2469   }\r
2470   if (!GetMilleModule(idm)->GetNChildren()) return;\r
2471   TString nm = "cstrSUMean";\r
2472   nm += GetNConstraints();\r
2473   AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMean,\r
2474                                                                       idm,val,pattern);\r
2475   cstr->SetConstraintID(GetNConstraints());\r
2476   fConstraints.Add(cstr);\r
2477 }\r
2478 \r
2479 //________________________________________________________________________________________________________\r
2480 void AliITSAlignMille2::ConstrainModuleSubUnitsMedian(Int_t idm, Double_t val, UInt_t pattern)\r
2481 {\r
2482   // require that median of the modifications for the childs of this module is = val, i.e.\r
2483   // the internal corrections moves the module as a whole by fixed value (0 by default) \r
2484   // module the outliers.\r
2485   // pattern is the bit pattern for the parameters to constrain\r
2486   // The difference between the mean and the median will be transfered to the parent\r
2487   if (fIsMilleInit) {\r
2488     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2489     return;\r
2490   }\r
2491   if (!GetMilleModule(idm)->GetNChildren()) return;\r
2492   TString nm = "cstrSUMed";\r
2493   nm += GetNConstraints();\r
2494   AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMedian,\r
2495                                                                       idm,val,pattern);\r
2496   cstr->SetConstraintID(GetNConstraints());\r
2497   fConstraints.Add(cstr);\r
2498 }\r
2499 \r
2500 //________________________________________________________________________________________________________\r
2501 void AliITSAlignMille2::ConstrainOrphansMean(Double_t val, UInt_t pattern)\r
2502 {\r
2503   // require that median of the modifications for the supermodules which have no parents is = val, i.e.\r
2504   // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.\r
2505   // pattern is the bit pattern for the parameters to constrain\r
2506   //\r
2507   if (fIsMilleInit) {\r
2508     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2509     return;\r
2510   }\r
2511   TString nm = "cstrOMean";\r
2512   nm += GetNConstraints();\r
2513   AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMean,\r
2514                                                                       -1,val,pattern);\r
2515   cstr->SetConstraintID(GetNConstraints());\r
2516   fConstraints.Add(cstr);\r
2517 }\r
2518 \r
2519 //________________________________________________________________________________________________________\r
2520 void AliITSAlignMille2::ConstrainOrphansMedian(Double_t val, UInt_t pattern)\r
2521 {\r
2522   // require that median of the modifications for the supermodules which have no parents is = val, i.e.\r
2523   // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.\r
2524   // pattern is the bit pattern for the parameters to constrain\r
2525   //\r
2526   if (fIsMilleInit) {\r
2527     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2528     return;\r
2529   }\r
2530   TString nm = "cstrOMed";\r
2531   nm += GetNConstraints();\r
2532   AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMedian,\r
2533                                                                       -1,val,pattern);\r
2534   cstr->SetConstraintID(GetNConstraints());\r
2535   fConstraints.Add(cstr);\r
2536 }\r
2537 \r
2538 //________________________________________________________________________________________________________\r
2539 void AliITSAlignMille2::ConstrainLocal(const Char_t* name,Double_t *parcf,Int_t npar,Double_t val,Double_t err)\r
2540 {\r
2541   // apply constraint on parameters in the local frame\r
2542   if (fIsMilleInit) {\r
2543     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2544     return;\r
2545   }\r
2546   AliITSAlignMille2ConstrArray *cstr = new AliITSAlignMille2ConstrArray(name,parcf,npar,val,err);\r
2547   cstr->SetConstraintID(GetNConstraints());\r
2548   fConstraints.Add(cstr);\r
2549 }\r
2550 \r
2551 //________________________________________________________________________________________________________\r
2552 void AliITSAlignMille2::ApplyGaussianConstraint(const AliITSAlignMille2ConstrArray* cstr)\r
2553 {\r
2554   // apply the constraint on the local corrections of a list of modules\r
2555   int nmod = cstr->GetNModules();\r
2556   double jacobian[AliITSAlignMille2Module::kMaxParGeom][AliITSAlignMille2Module::kMaxParGeom];\r
2557   //\r
2558   for (int imd=nmod;imd--;) {\r
2559     int modID = cstr->GetModuleID(imd);\r
2560     AliITSAlignMille2Module* mod = GetMilleModule(modID);\r
2561     ResetLocalEquation();\r
2562     int nadded = 0;\r
2563     double value = cstr->GetValue();\r
2564     double sigma = cstr->GetError();\r
2565     //\r
2566     // in case the reference (survey) deltas were imposed for Gaussian constraints\r
2567     // already accumulated corrections: they must be subtracted from the constraint value.\r
2568     if (IsConstraintWrtRef()) {\r
2569       //\r
2570       Double_t precal[AliITSAlignMille2Module::kMaxParTot];\r
2571       Double_t refcal[AliITSAlignMille2Module::kMaxParTot];\r
2572       for (int ip=AliITSAlignMille2Module::kMaxParTot;ip--;) {precal[ip]=0; refcal[ip] = 0.;}\r
2573       //\r
2574       // check if there was a reference delta provided for this module\r
2575       AliAlignObjParams* parref = GetConstrRefObject(mod->GetName());\r
2576       if (parref) parref->GetPars(refcal, refcal+3);    // found reference delta\r
2577       //\r
2578       // extract already applied local corrections for this module\r
2579       if (fPrealignment) {\r
2580         //\r
2581         AliAlignObjParams *preo = GetPrealignedObject(mod->GetName());\r
2582         if (preo) {\r
2583           TGeoHMatrix preMat,tmpMat = *mod->GetMatrix(); //  Delta_Glob * Delta_Glob_Par * M\r
2584           preo->GetMatrix(preMat);                       //  Delta_Glob\r
2585           preMat.MultiplyLeft( &tmpMat.Inverse() );      //  M^-1 * Delta_Glob_Par^-1 = (Delta_Glob_Par * M)^-1\r
2586           tmpMat.MultiplyLeft( &preMat );                //  (Delta_Glob_Par * M)^-1 * Delta_Glob * Delta_Glob_Par * M = Delta_loc\r
2587           AliAlignObjParams algob;\r
2588           algob.SetMatrix(tmpMat);\r
2589           algob.GetPars(precal,precal+3); // local corrections for geometry\r
2590         }\r
2591       }\r
2592       //\r
2593       // subtract the contribution to constraint from precalibration \r
2594       for (int ipar=cstr->GetNCoeffs();ipar--;) value += (refcal[ipar]-precal[ipar])*cstr->GetCoeff(ipar);\r
2595       //\r
2596     } \r
2597     //    \r
2598     if (fUseGlobalDelta) mod->CalcDerivLocGlo(&jacobian[0][0]);\r
2599     //\r
2600     for (int ipar=cstr->GetNCoeffs();ipar--;) {\r
2601       double coef = cstr->GetCoeff(ipar);\r
2602       if (coef==0) continue;\r
2603       //\r
2604       if (!fUseGlobalDelta || ipar>= AliITSAlignMille2Module::kMaxParGeom) { // \r
2605         // we are working with local params or if the given param is not related to geometry, \r
2606         // apply the constraint directly\r
2607         int parPos = mod->GetParOffset(ipar);\r
2608         if (parPos<0) continue; // not in the fit\r
2609         fGlobalDerivatives[parPos] += coef;\r
2610         nadded++;\r
2611       }\r
2612       else { // we are working with global params, while the constraint is on local ones -> jacobian\r
2613         for (int jpar=AliITSAlignMille2Module::kMaxParGeom;jpar--;) {\r
2614           int parPos = mod->GetParOffset(jpar);\r
2615           if (parPos<0) continue;\r
2616           fGlobalDerivatives[parPos] += coef*jacobian[ipar][jpar];\r
2617           nadded++;\r
2618         }\r
2619       }      \r
2620     }\r
2621     if (nadded) AddConstraint(fGlobalDerivatives, value, sigma);\r
2622   }\r
2623   //\r
2624 }\r
2625 \r
2626 //________________________________________________________________________________________________________\r
2627 void AliITSAlignMille2::ApplyPreConstraints()\r
2628 {\r
2629   // apply constriants which cannot be imposed after the fit\r
2630   int nconstr = GetNConstraints();\r
2631   for (int i=0;i<nconstr;i++) {\r
2632     AliITSAlignMille2Constraint* cstr = GetConstraint(i);\r
2633     //\r
2634     if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) {\r
2635       ApplyGaussianConstraint( (AliITSAlignMille2ConstrArray*)cstr);\r
2636       continue;\r
2637     } \r
2638     //\r
2639     if (cstr->GetType() == AliITSAlignMille2Constraint::kTypeMedian) continue; // post type constraint\r
2640     //\r
2641     if (!fUseGlobalDelta) continue; // mean/med constraints must be applied to global deltas\r
2642     // apply constraint on the mean's before the fit\r
2643     int imd = cstr->GetModuleID();\r
2644     if (imd>=0) {\r
2645       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2646       UInt_t pattern = 0;\r
2647       for (int ipar=mod->GetNParTot();ipar--;) {\r
2648         if (!cstr->IncludesParam(ipar)) continue;\r
2649         if (mod->GetParOffset(ipar)<0) continue; // parameter is not in the explicit fit -> post constraint\r
2650         pattern |= 0x1<<ipar;\r
2651         cstr->SetApplied(ipar);\r
2652       }\r
2653       ConstrainModuleSubUnits(imd,cstr->GetValue(),pattern);\r
2654       //\r
2655     }\r
2656     else if (!PseudoParentsAllowed()) {\r
2657       ConstrainOrphans(cstr->GetValue(),(UInt_t)cstr->GetPattern());\r
2658       cstr->SetApplied(-1);\r
2659     }\r
2660   }\r
2661 }\r
2662 \r
2663 //________________________________________________________________________________________________________\r
2664 void AliITSAlignMille2::ApplyPostConstraints()\r
2665 {\r
2666   // apply constraints which can be imposed after the fit\r
2667   int nconstr = GetNConstraints();\r
2668   Bool_t convGlo      = kFALSE;\r
2669   // check if there is something to do\r
2670   int ntodo = 0;\r
2671   for (int i=0;i<nconstr;i++) {\r
2672     AliITSAlignMille2Constraint* cstr = GetConstraint(i);\r
2673     if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) continue;\r
2674     if (cstr->GetRemainingPattern() == 0) continue;\r
2675     ntodo++;\r
2676   }\r
2677   if (!ntodo) return;\r
2678   //\r
2679   if (!fUseGlobalDelta) { // need to convert to global params\r
2680     ConvertParamsToGlobal();\r
2681     convGlo = kTRUE;\r
2682   }\r
2683   //\r
2684   for (int i=0;i<nconstr;i++) {\r
2685     AliITSAlignMille2Constraint* cstr = GetConstraint(i);\r
2686     if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) continue;\r
2687     //\r
2688     int imd = cstr->GetModuleID();\r
2689     //\r
2690     if (imd>=0) {\r
2691       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2692       UInt_t pattern = 0;\r
2693       for (int ipar=mod->GetNParTot();ipar--;) {\r
2694         if (cstr->IsApplied(ipar))      continue;\r
2695         if (!cstr->IncludesParam(ipar)) continue;\r
2696         if (!mod->IsFreeDOF(ipar))      continue; // parameter is fixed, will not apply constraint\r
2697         pattern |= 0x1<<ipar;\r
2698         cstr->SetApplied(ipar);\r
2699       }\r
2700       if (pattern) PostConstrainModuleSubUnits(cstr->GetType(),cstr->GetModuleID(),cstr->GetValue(),pattern);\r
2701       //\r
2702     }\r
2703     else if (PseudoParentsAllowed()) {\r
2704       UInt_t pattern = (UInt_t)cstr->GetRemainingPattern();\r
2705       PostConstrainOrphans(cstr->GetType(),cstr->GetValue(),pattern);\r
2706       cstr->SetApplied(-1);\r
2707     }\r
2708   }\r
2709   // if there was a conversion, rewind it\r
2710   if (convGlo) ConvertParamsToLocal();\r
2711   // \r
2712 }\r
2713 \r
2714 //________________________________________________________________________________________________________\r
2715 void AliITSAlignMille2::ConstrainModuleSubUnits(Int_t idm, Double_t val, UInt_t pattern)\r
2716 {\r
2717   // require that sum of modifications for the childs of this module is = val, i.e.\r
2718   // the internal corrections moves the module as a whole by fixed value (0 by default).\r
2719   // pattern is the bit pattern for the parameters to constrain\r
2720   //\r
2721   //\r
2722   AliITSAlignMille2Module* mod = GetMilleModule(idm);\r
2723   //\r
2724   for (int ip=0;ip<kNParCh;ip++) {\r
2725     if ( !((pattern>>ip)&0x1) /*|| !parent->IsFreeDOF(ip)*/) continue;\r
2726     ResetLocalEquation();\r
2727     int nadd = 0;\r
2728     for (int ich=mod->GetNChildren();ich--;) {\r
2729       int idpar = ((AliITSAlignMille2Module*)mod->GetChild(ich))->GetParOffset(ip);\r
2730       if (idpar<0) continue;\r
2731       fGlobalDerivatives[idpar] = 1.0;\r
2732       nadd++;\r
2733     }\r
2734     //\r
2735     if (nadd>0) {\r
2736       AddConstraint(fGlobalDerivatives,val);\r
2737       AliInfo(Form("Constrained param %d for %d submodules of module #%d: %s",ip,nadd,idm,mod->GetName()));\r
2738     }\r
2739   }\r
2740   //\r
2741 }\r
2742 \r
2743 //________________________________________________________________________________________________________\r
2744 void AliITSAlignMille2::ConstrainOrphans(Double_t val, UInt_t pattern)\r
2745 {\r
2746   // require that median of the modifications for the supermodules which have no parents is = val, i.e.\r
2747   // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.\r
2748   // pattern is the bit pattern for the parameters to constrain\r
2749   //\r
2750   for (int ip=0;ip<kNParCh;ip++) {\r
2751     //\r
2752     if ( !((pattern>>ip)&0x1) ) continue;\r
2753     ResetLocalEquation();\r
2754     int nadd = 0;\r
2755     for (int imd=fNModules;imd--;) {\r
2756       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2757       if (mod->GetParent()) continue; // this is not an orphan\r
2758       int idpar = mod->GetParOffset(ip);\r
2759       if (idpar<0) continue;\r
2760       fGlobalDerivatives[idpar] = 1.0;\r
2761       nadd++;\r
2762     }\r
2763     if (nadd>0) {\r
2764       AddConstraint(fGlobalDerivatives,val);\r
2765       AliInfo(Form("Constrained param %d for %d orphan modules",ip,nadd));\r
2766     }\r
2767   }\r
2768   //\r
2769   //\r
2770 }\r
2771 \r
2772 //________________________________________________________________________________________________________\r
2773 void AliITSAlignMille2::PostConstrainModuleSubUnits(Int_t type,Int_t idm, Double_t val, UInt_t pattern)\r
2774 {\r
2775   // require that median or mean of the modifications for the childs of this module is = val, i.e.\r
2776   // the internal corrections moves the module as a whole by fixed value (0 by default) \r
2777   // module the outliers.\r
2778   // pattern is the bit pattern for the parameters to constrain\r
2779   // The difference between the mean and the median will be transfered to the parent\r
2780   //\r
2781   AliITSAlignMille2Module* parent = GetMilleModule(idm);\r
2782   int nc = parent->GetNChildren();\r
2783   //\r
2784   double *tmpArr = new double[nc]; \r
2785   //\r
2786   for (int ip=0;ip<kNParCh;ip++) {\r
2787     int npc = 0;\r
2788     if ( !((pattern>>ip)&0x1) || !parent->IsFreeDOF(ip)) continue;\r
2789     // compute the mean and median of the deltas\r
2790     int nfree = 0;\r
2791     for (int ich=nc;ich--;) {\r
2792       AliITSAlignMille2Module* child = parent->GetChild(ich);\r
2793       //      if (!child->IsFreeDOF(ip)) continue; \r
2794       tmpArr[nfree++] = child->GetParVal(ip);\r
2795     }\r
2796     double median=0,mean=0;\r
2797     for (int ic0=0;ic0<nfree;ic0++) {// order the deltas \r
2798       mean += tmpArr[ic0];\r
2799       for (int ic1=ic0+1;ic1<nfree;ic1++) \r
2800         if (tmpArr[ic0]>tmpArr[ic1]) {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;}\r
2801     }\r
2802     //\r
2803     int kmed = nfree/2;\r
2804     median = (tmpArr[kmed]+tmpArr[nfree-kmed-1])/2.;\r
2805     if (nfree>0) mean /= nfree;\r
2806     //\r
2807     double shift = val - (type==AliITSAlignMille2Constraint::kTypeMean ? mean : median);\r
2808     //\r
2809     for (int ich=nc;ich--;) {\r
2810       AliITSAlignMille2Module* child = parent->GetChild(ich);\r
2811       //    if (!child->IsFreeDOF(ip)) continue; \r
2812       child->SetParVal(ip, child->GetParVal(ip) + shift);\r
2813       npc++;\r
2814     }\r
2815     //\r
2816     parent->SetParVal(ip, parent->GetParVal(ip) - shift);\r
2817     AliInfo(Form("%s constraint: added %f shift to param[%d] of %d children of module %d: %s",\r
2818                  type==AliITSAlignMille2Constraint::kTypeMean ? "MEAN" : "MEDIAN",shift,\r
2819                  ip,npc,idm,parent->GetName()));\r
2820   }\r
2821   delete[] tmpArr;  \r
2822   //\r
2823   //\r
2824 }\r
2825 \r
2826 //________________________________________________________________________________________________________\r
2827 void AliITSAlignMille2::PostConstrainOrphans(Int_t type,Double_t val, UInt_t pattern)\r
2828 {\r
2829   // require that median or mean of modifications for the supermodules which have no parents is = val, i.e.\r
2830   // the corrections moves the whole setup by fixed value (0 by default).\r
2831   // pattern is the bit pattern for the parameters to constrain\r
2832   //\r
2833   int nc = fNModules;\r
2834   //\r
2835   int norph = 0;\r
2836   for (int ich=nc;ich--;) if (!GetMilleModule(ich)->GetParent()) norph ++;\r
2837   if (!norph) return;\r
2838   double *tmpArr = new double[norph]; \r
2839   //\r
2840   for (int ip=0;ip<kNParCh;ip++) {\r
2841     int npc = 0;\r
2842     if ( !((pattern>>ip)&0x1)) continue;\r
2843     // compute the mean and median of the deltas\r
2844     int nfree = 0;\r
2845     for (int ich=nc;ich--;) {\r
2846       AliITSAlignMille2Module* child = GetMilleModule(ich);\r
2847       //      if (child->GetParent() || !child->IsFreeDOF(ip)) continue; \r
2848       if (child->GetParent()) continue; \r
2849       tmpArr[nfree++] = child->GetParVal(ip);\r
2850     }\r
2851     double median=0,mean=0;\r
2852     for (int ic0=0;ic0<nfree;ic0++) {// order the deltas \r
2853       mean += tmpArr[ic0];\r
2854       for (int ic1=ic0+1;ic1<nfree;ic1++) \r
2855         if (tmpArr[ic0]>tmpArr[ic1]) {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;}\r
2856     }\r
2857     //\r
2858     int kmed = nfree/2;\r
2859     median = (tmpArr[kmed]+tmpArr[nfree-kmed-1])/2.;\r
2860     if (nfree>0) mean /= nfree;\r
2861     //\r
2862     double shift = val - (type==AliITSAlignMille2Constraint::kTypeMean ? mean : median);\r
2863     //\r
2864     for (int ich=nc;ich--;) {\r
2865       AliITSAlignMille2Module* child = GetMilleModule(ich);\r
2866       //      if (child->GetParent() || !child->IsFreeDOF(ip)) continue; \r
2867       if (child->GetParent()) continue; \r
2868       child->SetParVal(ip, child->GetParVal(ip) + shift);\r
2869       npc++;\r
2870     }\r
2871     //\r
2872     AliInfo(Form("%s constraint: added %f shift to param[%d] of %d orphan modules",\r
2873                  type==AliITSAlignMille2Constraint::kTypeMean ? "MEAN" : "MEDIAN",shift,\r
2874                  ip,npc));\r
2875   }\r
2876   delete[] tmpArr;  \r
2877   //\r
2878 }\r
2879 \r
2880 //________________________________________________________________________________________________________\r
2881 Bool_t AliITSAlignMille2::IsParModConstrained(const AliITSAlignMille2Module* mod,Int_t par, Bool_t &meanmed, Bool_t &gaussian) const\r
2882 {\r
2883   // check if par of the module participates in some constraint, and set the flag for their types\r
2884   meanmed = gaussian = kFALSE;\r
2885   //\r
2886   if ( mod->IsParConstrained(par) ) gaussian = kTRUE;     // direct constraint on this param\r
2887   //\r
2888   for (int icstr=GetNConstraints();icstr--;) {\r
2889     AliITSAlignMille2Constraint* cstr = GetConstraint(icstr);\r
2890     //\r
2891     if (!cstr->IncludesModPar(mod,par)) continue;\r
2892     if (cstr->GetType()==AliITSAlignMille2ConstrArray::kTypeGaussian) gaussian = kTRUE;\r
2893     else meanmed = kTRUE;\r
2894     //\r
2895     if (meanmed && gaussian) break; // no sense to check further\r
2896   }\r
2897   //\r
2898   return meanmed||gaussian;\r
2899 }\r
2900 \r
2901 //________________________________________________________________________________________________________\r
2902 Bool_t AliITSAlignMille2::IsParModFamilyVaried(const AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const\r
2903 {\r
2904   // check if parameter par is varied for this module or its children up to the level depth\r
2905   if (depth<0) return kFALSE;\r
2906   if (mod->GetParOffset(par)>=0) return kTRUE;\r
2907   for (int icld=mod->GetNChildren();icld--;) {\r
2908     AliITSAlignMille2Module* child = mod->GetChild(icld);\r
2909     if (IsParModFamilyVaried(child, par, depth-1)) return kTRUE;\r
2910   }\r
2911   return kFALSE;\r
2912   //\r
2913 }\r
2914 \r
2915 /*\r
2916 //________________________________________________________________________________________________________\r
2917 Bool_t AliITSAlignMille2::IsParFamilyFree(AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const\r
2918 {\r
2919   // check if parameter par is varied and is not subjected to gaussian constraint for the children up to the level depth\r
2920   if (depth<0) return kTRUE;\r
2921   for (int icld=mod->GetNChildren();icld--;) {\r
2922     AliITSAlignMille2Module* child = mod->GetChild(icld);\r
2923     //if (child->GetParOffset(par)<0) continue;                  // fixed\r
2924     Bool_t cstMM=kFALSE,cstGS=kFALSE;\r
2925     // does this child have gaussian constraint ?\r
2926     if (!IsParModConstrained(child,par,cstMM,cstGS) || !cstGS ) return kTRUE;\r
2927     // check its children\r
2928     if (!IsParFamilyFree(child,par,depth-1)) return kTRUE;\r
2929   }\r
2930   return kFALSE;\r
2931   //\r
2932 }\r
2933 */\r
2934 \r
2935 //________________________________________________________________________________________________________\r
2936 Bool_t AliITSAlignMille2::IsParFamilyFree(const AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const\r
2937 {\r
2938   // check if parameter par is varied and is not subjected to gaussian constraint for the children up to the level depth\r
2939   if (depth<0) return kFALSE;\r
2940   for (int icld=mod->GetNChildren();icld--;) {\r
2941     AliITSAlignMille2Module* child = mod->GetChild(icld);\r
2942     //if (child->GetParOffset(par)<0) continue;                  // fixed\r
2943     Bool_t cstMM=kFALSE,cstGS=kFALSE;\r
2944     // does this child have gaussian constraint ?\r
2945     if (!IsParModConstrained(child,par,cstMM,cstGS) || !cstGS ) return kTRUE;\r
2946     // check its children\r
2947     if (IsParFamilyFree(child,par,depth-1)) return kTRUE;\r
2948   }\r
2949   return kFALSE;\r
2950   //\r
2951 }\r
2952 \r
2953 //________________________________________________________________________________________________________\r
2954 Double_t AliITSAlignMille2::GetTDriftSDD() const \r
2955 {\r
2956   // obtain drift time corrected for t0\r
2957   double t = fCluster.GetDriftTime();\r
2958   return t - fDriftTime0[ fCluster.GetUniqueID() ];\r
2959 }\r
2960 \r
2961 //________________________________________________________________________________________________________\r
2962 Double_t AliITSAlignMille2::GetVDriftSDD() const \r
2963 {\r
2964   // obtain corrected drift speed\r
2965   return fDriftSpeed[ fCluster.GetUniqueID() ];\r
2966 }\r
2967 \r
2968 //________________________________________________________________________________________________________\r
2969 Bool_t AliITSAlignMille2::FixedOrphans() const\r
2970 {\r
2971   // are there fixed modules with no parent (normally in such a case \r
2972   // the constraints on the orphans should not be applied\r
2973   if (!IsConfigured()) {\r
2974     AliInfo("Still not configured");\r
2975     return kFALSE;\r
2976   }\r
2977   for (int i=0;i<fNModules;i++) {\r
2978     AliITSAlignMille2Module* md = GetMilleModule(i);\r
2979     if (md->GetParent()==0 && md->GetNParFree()==0) return kTRUE;\r
2980   }\r
2981   return kFALSE;\r
2982 }\r
2983 \r
2984 //________________________________________________________________________________________________________\r
2985 void AliITSAlignMille2::ConvertParamsToGlobal()\r
2986 {\r
2987   // convert params in local frame to global one\r
2988   double pars[AliITSAlignMille2Module::kMaxParGeom];\r
2989   for (int imd=fNModules;imd--;) {\r
2990     AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2991     if (mod->GeomParamsGlobal()) continue;\r
2992     mod->GetGeomParamsGlo(pars);\r
2993     mod->SetParVals(pars,AliITSAlignMille2Module::kMaxParGeom);\r
2994     mod->SetGeomParamsGlobal(kTRUE);\r
2995   }\r
2996 }\r
2997 \r
2998 //________________________________________________________________________________________________________\r
2999 void AliITSAlignMille2::ConvertParamsToLocal()\r
3000 {\r
3001   // convert params in global frame to local one\r
3002   double pars[AliITSAlignMille2Module::kMaxParGeom];\r
3003   for (int imd=fNModules;imd--;) {\r
3004     AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
3005     if (!mod->GeomParamsGlobal()) continue;\r
3006     mod->GetGeomParamsLoc(pars);\r
3007     mod->SetParVals(pars,AliITSAlignMille2Module::kMaxParGeom);\r
3008     mod->SetGeomParamsGlobal(kFALSE);\r
3009   }\r
3010 }\r
3011 \r