]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ITS/AliITSAlignMille2.cxx
New EMCAL cosmic trigger as defined by Federico A.
[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   // pepo200709\r
1254   //atps = (AliTrackPointArray*)fTrackBuff[ngoodpts-fMinNPtsPerTrack];\r
1255   atps = (AliTrackPointArray*)fTrackBuff[ngoodpts];\r
1256   if (!atps) {\r
1257     atps = new AliTrackPointArray(ngoodpts);\r
1258     //    fTrackBuff.AddAtAndExpand(atps,ngoodpts-fMinNPtsPerTrack);\r
1259     fTrackBuff.AddAtAndExpand(atps,ngoodpts);\r
1260   }  \r
1261   //  atps = new AliTrackPointArray(ngoodpts);\r
1262   // endpepo200709\r
1263   //\r
1264   //\r
1265   for (int i=0; i<npts; i++) idx[i]=i;\r
1266   // sort track if required\r
1267   TMath::Sort(npts,atp->GetY(),idx); // sort descending...\r
1268   //\r
1269   Int_t npto=0;\r
1270   for (int i=0; i<npts; i++) {\r
1271     // skip not defined points\r
1272     if (intidx[idx[i]]<0) continue;\r
1273     atp->GetPoint(p,idx[i]);\r
1274 \r
1275     // prealign point if required\r
1276     // get IDEAL matrix\r
1277     AliITSAlignMille2Module *mod = GetMilleModule(intidx[idx[i]]);\r
1278     TGeoHMatrix *svOrigMatrix = mod->GetSensitiveVolumeOrigGlobalMatrix(p.GetVolumeID());\r
1279     // get back real local coordinates: use OriginalGlobalMatrix because AliTrackPoints were written\r
1280     // with idel geometry  \r
1281     Double_t pg[3],pl[3];\r
1282     pg[0]=p.GetX();\r
1283     pg[1]=p.GetY();\r
1284     pg[2]=p.GetZ();\r
1285     //    printf("Global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]);\r
1286     AliDebug(3,Form("Global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]));\r
1287     svOrigMatrix->MasterToLocal(pg,pl);\r
1288 \r
1289     AliDebug(3,Form("Local coordinates of measured point : X=%f  Y=%f  Z=%f \n",pl[0],pl[1],pl[2]));\r
1290     //\r
1291     // this is a temporary code to extract the drift speed used for given point\r
1292     if (p.GetDriftTime()>0) { // RRR\r
1293       // calculate the drift speed\r
1294       int sid = AliITSAlignMille2Module::GetIndexFromVolumeID(p.GetVolumeID());// - kSDDoffsID;\r
1295       fDriftTime0[npto] = fInitialRecSDD ? fInitialRecSDD->GetTimeZero(sid) : 0.;\r
1296       /*\r
1297       AliGeomManager::ELayerID lay = AliGeomManager::VolUIDToLayer(p.GetVolumeID());\r
1298       if      (lay==3) fDriftTime0[npto] = pg[2]<0 ? 169.5 : 140.1;\r
1299       else if (lay==4) fDriftTime0[npto] = pg[2]<0 ? 158.3 : 139.0;\r
1300       else {\r
1301         AliError(Form("Strange layer %d for moduleID %d",lay,p.GetVolumeID()));\r
1302         exit(1);\r
1303       }\r
1304       */\r
1305       double tdif = p.GetDriftTime() - fDriftTime0[npto];\r
1306       if (tdif<=0) tdif = 1;\r
1307       double vdrift = (3.5085-TMath::Abs(pl[0]))/tdif;\r
1308       if (vdrift<0) vdrift = 0;\r
1309       //\r
1310       // TEMPORARY CORRECTION (if provided) -------------->>>\r
1311       if (fCorrectSDD) {\r
1312         float t0Upd = fCorrectSDD->GetTimeZero(sid);\r
1313         vdrift += fCorrectSDD->GetDeltaVDrift(sid);\r
1314         tdif    = p.GetDriftTime() - t0Upd;\r
1315         // correct Xlocal\r
1316         pl[0] = TMath::Sign(3.5085 - vdrift*tdif,pl[0]);\r
1317         fDriftTime0[npto] =  t0Upd;\r
1318       }\r
1319       // TEMPORARY CORRECTION (if provided) --------------<<<\r
1320       fDriftSpeed[npto] = TMath::Sign(vdrift,pl[0]);\r
1321       //\r
1322       /*\r
1323       printf("%d  %+6.2f %+6.2f %+6.2f  %+5.2f %+5.2f %+5.2f  %+6.1f  %+6.1f %+f %+f\n",\r
1324              p.GetVolumeID(),pg[0],pg[1],pg[2],pl[0],pl[1],pl[2],p.GetDriftTime(), fDriftTime0[npto], fDriftSpeed[npto],tdif);\r
1325       */\r
1326     }\r
1327 \r
1328     // update covariance matrix\r
1329     TGeoHMatrix hcov;\r
1330     Double_t hcovel[9];\r
1331     hcovel[0]=double(p.GetCov()[0]);\r
1332     hcovel[1]=double(p.GetCov()[1]);\r
1333     hcovel[2]=double(p.GetCov()[2]);\r
1334     hcovel[3]=double(p.GetCov()[1]);\r
1335     hcovel[4]=double(p.GetCov()[3]);\r
1336     hcovel[5]=double(p.GetCov()[4]);\r
1337     hcovel[6]=double(p.GetCov()[2]);\r
1338     hcovel[7]=double(p.GetCov()[4]);\r
1339     hcovel[8]=double(p.GetCov()[5]);\r
1340     hcov.SetRotation(hcovel);\r
1341     // now rotate in local system\r
1342     //    printf("\nErrMatGlob: before\n"); hcov.Print(""); //RRR\r
1343     hcov.Multiply(svOrigMatrix);\r
1344     hcov.MultiplyLeft(&svOrigMatrix->Inverse());\r
1345     // now hcov is LOCAL COVARIANCE MATRIX\r
1346     // apply sigma scaling\r
1347     //    printf("\nErrMatLoc: before\n"); hcov.Print(""); //RRR\r
1348     Double_t *hcovscl = hcov.GetRotationMatrix(); \r
1349     //    for (int ir=3;ir--;) for (int ic=3;ic--;) hcovscl[ir*3+ic] *= mod->GetSigmaFactor(ir)*mod->GetSigmaFactor(ic); //RRR\r
1350     // RS TEMPORARY: nullify non-diagonal elements and sigY\r
1351     hcovscl[5] = 0;\r
1352     for (int ir=3;ir--;) for (int ic=3;ic--;) {\r
1353         if (ir==ic) {\r
1354           if (TMath::Abs(hcovscl[ir*3+ic])<kTiny) hcovscl[ir*3+ic] = 0.;\r
1355           else hcovscl[ir*3+ic] *= mod->GetSigmaFactor(ir)*mod->GetSigmaFactor(ic); //RRR\r
1356         }\r
1357         else hcovscl[ir*3+ic]  = 0;\r
1358       }\r
1359     //\r
1360     //    printf("\nErrMatLoc: after\n"); hcov.Print(""); //RRR\r
1361     //\r
1362     if (fBug==1) {\r
1363       // correzione bug LAYER 5  SSD temporanea..\r
1364       int ssdidx=AliITSAlignMille2Module::GetIndexFromVolumeID(p.GetVolumeID());\r
1365       if (ssdidx>=500 && ssdidx<1248) {\r
1366         int ladder=(ssdidx-500)%22;\r
1367         if (ladder==18) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx+1));\r
1368         if (ladder==19) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx-1));\r
1369       }\r
1370     }\r
1371     /// get (evenctually prealigned) matrix of sens. vol.\r
1372     TGeoHMatrix *svMatrix = mod->GetSensitiveVolumeMatrix(p.GetVolumeID());\r
1373     // modify global coordinates according with pre-aligment\r
1374     svMatrix->LocalToMaster(pl,pg);\r
1375     // now rotate in local system\r
1376     hcov.Multiply(&svMatrix->Inverse());\r
1377     hcov.MultiplyLeft(svMatrix);\r
1378     // hcov is back in GLOBAL RF\r
1379     // cure once more\r
1380     for (int ir=3;ir--;) for (int ic=3;ic--;) if (TMath::Abs(hcovscl[ir*3+ic])<kTiny) hcovscl[ir*3+ic] = 0.;\r
1381     //    printf("\nErrMatGlob: after\n"); hcov.Print(""); //RRR\r
1382     //\r
1383     Float_t pcov[6];\r
1384     pcov[0]=hcovscl[0];\r
1385     pcov[1]=hcovscl[1];\r
1386     pcov[2]=hcovscl[2];\r
1387     pcov[3]=hcovscl[4];\r
1388     pcov[4]=hcovscl[5];\r
1389     pcov[5]=hcovscl[8];\r
1390 \r
1391     p.SetXYZ(pg[0],pg[1],pg[2],pcov);\r
1392     //    printf("New Gl coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]);\r
1393     AliDebug(3,Form("New global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]));\r
1394     atps->AddPoint(npto,&p);\r
1395     AliDebug(2,Form("Adding point[%d] = ( %f , %f , %f )     volid = %d",npto,atps->GetX()[npto],\r
1396                     atps->GetY()[npto],atps->GetZ()[npto],atps->GetVolumeID()[npto] ));\r
1397     //    printf("Adding %d %d %f\n",npto, p.GetVolumeID(), p.GetY()); \r
1398     npto++;\r
1399   }\r
1400 \r
1401   return atps;\r
1402 }\r
1403 \r
1404 //________________________________________________________________________________________________________\r
1405 AliTrackPointArray *AliITSAlignMille2::SortTrack(const AliTrackPointArray *atp) \r
1406 {\r
1407   /// sort alitrackpoints w.r.t. global Y direction\r
1408   AliTrackPointArray *atps=NULL;\r
1409   Int_t idx[20];\r
1410   Int_t npts=atp->GetNPoints();\r
1411   AliTrackPoint p;\r
1412   atps=new AliTrackPointArray(npts);\r
1413 \r
1414   TMath::Sort(npts,atp->GetY(),idx);\r
1415 \r
1416   for (int i=0; i<npts; i++) {\r
1417     atp->GetPoint(p,idx[i]);\r
1418     atps->AddPoint(i,&p);\r
1419     AliDebug(2,Form("Point[%d] = ( %f , %f , %f )     volid = %d",i,atps->GetX()[i],atps->GetY()[i],atps->GetZ()[i],atps->GetVolumeID()[i] ));\r
1420   }\r
1421   return atps;\r
1422 }\r
1423 \r
1424 //________________________________________________________________________________________________________\r
1425 Int_t AliITSAlignMille2::GetCurrentLayer() const \r
1426 {\r
1427   // get current layer id\r
1428   if (!fGeoManager) {\r
1429     AliInfo("ITS geometry not initialized!");\r
1430     return -1;\r
1431   }\r
1432   return (Int_t)AliGeomManager::VolUIDToLayer(fCluster.GetVolumeID());\r
1433 }\r
1434 \r
1435 //________________________________________________________________________________________________________\r
1436 Int_t AliITSAlignMille2::InitModuleParams() \r
1437 {\r
1438   /// initialize geometry parameters for a given detector\r
1439   /// for current cluster (fCluster)\r
1440   /// fGlobalInitParam[] is set as:\r
1441   ///    [tx,ty,tz,psi,theta,phi]\r
1442   ///    (old was [tx,ty,tz,theta,psi,phi] ROOT's angles...)\r
1443   /// *** At the moment: using Raffalele's angles definition ***\r
1444   ///\r
1445   /// return 0 if success\r
1446   /// If module is found but has no parameters to vary, return 1\r
1447 \r
1448   if (!fGeoManager) {\r
1449     AliInfo("ITS geometry not initialized!");\r
1450     return -1;\r
1451   }\r
1452 \r
1453   // now 'voluid' is the volumeID of a SENSITIVE VOLUME (coming from a cluster)\r
1454 \r
1455   // set the internal index (index in module list)\r
1456   UShort_t voluid=fCluster.GetVolumeID();\r
1457   //\r
1458   // IT IS VERY IMPORTANT: start from the end of the list, where the childs are located !!!\r
1459   Int_t k=fNModules-1;\r
1460   fCurrentModule = 0;\r
1461   // VERY IMPORTANT: if the sensors were explicitly provided, don't look in the supermodules  \r
1462   while (k>=0 && ! (fCurrentModule=GetMilleModule(k))->IsIn(voluid)) k--;\r
1463   if (k<0) return -3;\r
1464   //\r
1465   /*\r
1466   // Check if the module has free params. If not, go over the parents\r
1467   AliITSAlignMille2Module* mdtmp = fCurrentModule;\r
1468   while (mdtmp && mdtmp->GetNParFree()==0) mdtmp = mdtmp->GetParent();\r
1469   if (!mdtmp) return 1; // nothing to vary here\r
1470   fCurrentModule = mdtmp;\r
1471   */\r
1472   //\r
1473   fModuleInitParam[0] = 0.0;\r
1474   fModuleInitParam[1] = 0.0;\r
1475   fModuleInitParam[2] = 0.0;\r
1476   fModuleInitParam[3] = 0.0; // psi   (X)\r
1477   fModuleInitParam[4] = 0.0; // theta (Y)\r
1478   fModuleInitParam[5] = 0.0; // phi   (Z)\r
1479   fModuleInitParam[6] = 0.0;\r
1480   fModuleInitParam[7] = 0.0;\r
1481   /// get (evenctually prealigned) matrix of sens. vol.\r
1482   TGeoHMatrix *svMatrix = fCurrentModule->GetSensitiveVolumeMatrix(voluid);\r
1483   \r
1484   fMeasGlo[0] = fCluster.GetX();\r
1485   fMeasGlo[1] = fCluster.GetY();\r
1486   fMeasGlo[2] = fCluster.GetZ(); \r
1487   svMatrix->MasterToLocal(fMeasGlo,fMeasLoc);  \r
1488   AliDebug(2,Form("Local coordinates of measured point : X=%f  Y=%f  Z=%f \n",fMeasLoc[0] ,fMeasLoc[1] ,fMeasLoc[2] ));\r
1489   \r
1490   // set stdev from cluster\r
1491   TGeoHMatrix hcov;\r
1492   Double_t hcovel[9];\r
1493   hcovel[0]=double(fCluster.GetCov()[0]);\r
1494   hcovel[1]=double(fCluster.GetCov()[1]);\r
1495   hcovel[2]=double(fCluster.GetCov()[2]);\r
1496   hcovel[3]=double(fCluster.GetCov()[1]);\r
1497   hcovel[4]=double(fCluster.GetCov()[3]);\r
1498   hcovel[5]=double(fCluster.GetCov()[4]);\r
1499   hcovel[6]=double(fCluster.GetCov()[2]);\r
1500   hcovel[7]=double(fCluster.GetCov()[4]);\r
1501   hcovel[8]=double(fCluster.GetCov()[5]);\r
1502   hcov.SetRotation(hcovel);\r
1503   // now rotate in local system\r
1504   hcov.Multiply(svMatrix);\r
1505   hcov.MultiplyLeft(&svMatrix->Inverse());\r
1506   //\r
1507   // set local sigmas\r
1508   fSigmaLoc[0] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[0]));\r
1509   fSigmaLoc[1] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[4])); // RS\r
1510   fSigmaLoc[2] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[8]));\r
1511 \r
1512   // set minimum value for SigmaLoc to 10 micron \r
1513   if (fSigmaLoc[0]<0.0010) fSigmaLoc[0]=0.0010;\r
1514   if (fSigmaLoc[2]<0.0010) fSigmaLoc[2]=0.0010;\r
1515   //\r
1516   /* RRR the rescaling is moved to PrepareTrack\r
1517   // multiply local sigmas by global and module specific factor \r
1518   for (int i=3;i--;) fSigmaLoc[i] *= fSigmaFactor[i]*fCurrentModule->GetSigmaFactor(i);\r
1519   //\r
1520   */\r
1521   AliDebug(2,Form("Setting StDev from CovMat : fSigmaLocX=%g  fSigmaLocY=%g fSigmaLocZ=%g \n",fSigmaLoc[0] ,fSigmaLoc[1] ,fSigmaLoc[2] ));\r
1522    \r
1523   return 0;\r
1524 }\r
1525 \r
1526 //________________________________________________________________________________________________________\r
1527 void AliITSAlignMille2::Print(Option_t*) const \r
1528 {\r
1529   // print current status \r
1530   printf("*** AliMillepede for ITS ***\n");\r
1531   printf("    Number of defined super modules: %d\n",fNModules);\r
1532   printf("    Obtained parameters refer to %s Deltas\n",fUseGlobalDelta ? "GLOBAL":"LOCAL");\r
1533   //\r
1534   if (fGeoManager)\r
1535     printf("    geometry loaded from %s\n",fGeometryFileName.Data());\r
1536   else\r
1537     printf("    geometry not loaded\n");\r
1538   //  \r
1539   if (fUsePreAlignment) \r
1540     printf("    using prealignment from %s \n",fPreAlignmentFileName.Data());\r
1541   else\r
1542     printf("    prealignment not used\n");    \r
1543   //\r
1544   //\r
1545   if (fBOn) \r
1546     printf("    B Field set to %f T - using Riemann's helices\n",fBField);\r
1547   else\r
1548     printf("    B Field OFF - using straight lines \n");\r
1549   //\r
1550   if (fRequirePoints) printf("    Required points in tracks:\n");\r
1551   for (Int_t i=0; i<6; i++) {\r
1552     if (fNReqLayUp[i]>0) printf("        Layer %d : %d points with Y>0\n",i+1,fNReqLayUp[i]);\r
1553     if (fNReqLayDown[i]>0) printf("        Layer %d : %d points with Y<0\n",i+1,fNReqLayDown[i]);\r
1554     if (fNReqLay[i]>0) printf("        Layer %d : %d points \n",i+1,fNReqLay[i]);\r
1555   }\r
1556   for (Int_t i=0; i<3; i++) {\r
1557     if (fNReqDetUp[i]>0) printf("        Detector %d : %d points with Y>0\n",i+1,fNReqDetUp[i]);\r
1558     if (fNReqDetDown[i]>0) printf("        Detector %d : %d points with Y<0\n",i+1,fNReqDetDown[i]);\r
1559     if (fNReqDet[i]>0) printf("        Detector %d : %d points \n",i+1,fNReqDet[i]);\r
1560   }\r
1561   //  \r
1562   printf("\n    Millepede configuration parameters:\n");\r
1563   printf("        init value for chi2 cut       : %.4f\n",fStartFac);\r
1564   printf("        first iteration cut value     : %.4f\n",fResCutInitial);\r
1565   printf("        other iterations cut value    : %.4f\n",fResCut);\r
1566   printf("        number of stddev for chi2 cut : %d\n",fNStdDev);\r
1567   printf("        def.scaling for local sigmas  : %.4f %.4f %.4f\n",fSigmaFactor[0],fSigmaFactor[1],fSigmaFactor[2]);\r
1568 \r
1569   printf("List of defined modules:\n");\r
1570   printf("  intidx\tindex\tvoluid\tname\n");\r
1571   for (int i=0; i<fNModules; i++) {\r
1572     AliITSAlignMille2Module* md = GetMilleModule(i); \r
1573     printf("  %d\t%d\t%d\t%s\n",i,md->GetIndex(),md->GetVolumeID(),md->GetName());\r
1574   }\r
1575 }\r
1576 \r
1577 //________________________________________________________________________________________________________\r
1578 AliITSAlignMille2Module  *AliITSAlignMille2::GetMilleModuleByVID(UShort_t voluid) const\r
1579 {\r
1580   // return pointer to a defined supermodule\r
1581   // return NULL if error\r
1582   Int_t i=IsVIDDefined(voluid);\r
1583   if (i<0) return NULL;\r
1584   return GetMilleModule(i);\r
1585 }\r
1586 \r
1587 //________________________________________________________________________________________________________\r
1588 AliITSAlignMille2Module  *AliITSAlignMille2::GetMilleModuleBySymName(const Char_t* symname) const\r
1589 {\r
1590   // return pointer to a defined supermodule\r
1591   // return NULL if error\r
1592   UShort_t vid = AliITSAlignMille2Module::GetVolumeIDFromSymname(symname);\r
1593   if (vid>0) return GetMilleModuleByVID(vid);\r
1594   else {    // this is not alignable module, need to look within defined supermodules\r
1595     int i = IsSymDefined(symname);\r
1596     if (i>=0) return  GetMilleModule(i);\r
1597   }\r
1598   return 0;\r
1599 }\r
1600 \r
1601 //________________________________________________________________________________________________________\r
1602 AliITSAlignMille2Module  *AliITSAlignMille2::GetMilleModuleIfContained(const Char_t* symname) const\r
1603 {\r
1604   // return pointer to a defined/contained supermodule\r
1605   // return NULL otherwise\r
1606   int i = IsSymContained(symname);\r
1607   return i<0 ? 0 : GetMilleModule(i);\r
1608 }\r
1609 \r
1610 //________________________________________________________________________________________________________\r
1611 AliAlignObjParams* AliITSAlignMille2::GetPrealignedObject(const Char_t* symname) const\r
1612 {\r
1613   // get delta from prealignment for given volume\r
1614   if (!fPrealignment) return 0;\r
1615   for (int ipre=fPrealignment->GetEntriesFast();ipre--;) { // was the corresponding object prealigned?\r
1616     AliAlignObjParams* preob = (AliAlignObjParams*)fPrealignment->At(ipre);\r
1617     if (!strcmp(preob->GetSymName(),symname)) return preob;\r
1618   }\r
1619   return 0;\r
1620 }\r
1621 \r
1622 //________________________________________________________________________________________________________\r
1623 AliAlignObjParams* AliITSAlignMille2::GetConstrRefObject(const Char_t* symname) const\r
1624 {\r
1625   // get delta with respect to which the constraint is declared\r
1626   if (!fConstrRef) return 0;\r
1627   for (int ipre=fConstrRef->GetEntriesFast();ipre--;) { // was the corresponding object prealigned?\r
1628     AliAlignObjParams* preob = (AliAlignObjParams*)fConstrRef->At(ipre);\r
1629     if (!strcmp(preob->GetSymName(),symname)) return preob;\r
1630   }\r
1631   return 0;\r
1632 }\r
1633 \r
1634 //________________________________________________________________________________________________________\r
1635 Bool_t AliITSAlignMille2::InitRiemanFit() \r
1636 {\r
1637   // Initialize Riemann Fitter for current track\r
1638   // return kFALSE if error\r
1639 \r
1640   if (!fBOn) return kFALSE;\r
1641 \r
1642   Int_t npts=0;\r
1643   AliTrackPoint ap;\r
1644   npts = fTrack->GetNPoints();\r
1645   AliDebug(3,Form("Fitting track with %d points",npts));\r
1646 \r
1647   fRieman->Reset();\r
1648   fRieman->SetTrackPointArray(fTrack);\r
1649 \r
1650   TArrayI ai(npts);\r
1651   for (Int_t ipt=0; ipt<npts; ipt++) ai[ipt]=fTrack->GetVolumeID()[ipt];\r
1652   \r
1653   // fit track with 5 params in his own tracking-rotated reference system\r
1654   // xc = -p[1]/p[0];\r
1655   // yc = 1/p[0];\r
1656   // R  = sqrt( x0*x0 + y0*y0 - y0*p[2]);\r
1657   if (!fRieman->Fit(&ai,NULL,(AliGeomManager::ELayerID)1,(AliGeomManager::ELayerID)6)) {\r
1658     return kFALSE;\r
1659   }\r
1660 \r
1661   for (int i=0; i<5; i++)\r
1662     fLocalInitParam[i] = fRieman->GetParam()[i];\r
1663   \r
1664   return kTRUE;\r
1665 }\r
1666 \r
1667 //________________________________________________________________________________________________________\r
1668 void trackFit2D(Int_t &, Double_t *, double &chi2, double *par, int flag)\r
1669 {\r
1670   // local function for minuit\r
1671   const double kTiny = 1.e-14;\r
1672   chi2 = 0;\r
1673   static AliTrackPoint pnt;\r
1674   static Bool_t fullErr2D;\r
1675   //\r
1676   if (flag==1) fullErr2D = kFALSE;//kTRUE;\r
1677   enum {kAX,kAZ,kBX,kBZ};\r
1678   enum {kXX=0,kXY=1,kXZ=2,kYX=kXY,kYY=3,kYZ=4,kZX=kXZ,kZY=kYZ,kZZ=5};\r
1679   //\r
1680   AliITSAlignMille2* alig = AliITSAlignMille2::GetInstance();\r
1681   AliTrackPointArray* track = alig->GetCurrentTrack();\r
1682   //\r
1683   int npts = track->GetNPoints();\r
1684   for (int ip=0;ip<npts;ip++) {\r
1685     track->GetPoint(pnt,ip);\r
1686     const float *cov = pnt.GetCov();\r
1687     double y  = pnt.GetY();\r
1688     double dx = pnt.GetX() - (par[kAX]+y*par[kBX]);\r
1689     double dz = pnt.GetZ() - (par[kAZ]+y*par[kBZ]);\r
1690     double xxe = cov[kXX];\r
1691     double zze = cov[kZZ];\r
1692     double xze = cov[kXZ];\r
1693     //\r
1694     if (fullErr2D) {\r
1695       xxe += par[kBX]*par[kBX]*cov[kYY]-2.*par[kBX]*cov[kXY];\r
1696       zze += par[kBZ]*par[kBZ]*cov[kYY]-2.*par[kBZ]*cov[kZY];\r
1697       xze += par[kBX]*par[kBZ]*cov[kYY]-cov[kYZ]*par[kBZ]-cov[kXY]*par[kBX];\r
1698     }\r
1699     //\r
1700     double det = xxe*zze - xze*xze;\r
1701     if (det<kTiny) {\r
1702       printf("Negative diag. error (det=%+e) |sxx:%+e szz:%+e sxz:%+e| bx:%+e bz:%+e|\n"\r
1703              "Discarding correlation term\n",det,xxe,zze,xze,par[kBX],par[kBZ]);\r
1704       xxe = cov[kXX];\r
1705       zze = cov[kZZ];\r
1706       xze = cov[kXZ];\r
1707       fullErr2D = kFALSE;\r
1708     }\r
1709     double xxeI = zze/det;\r
1710     double zzeI = xxe/det;\r
1711     double xzeI =-xze/det;\r
1712     //\r
1713     chi2 += dx*dx*xxeI + dz*dz*zzeI + 2.*dx*dz*xzeI;\r
1714     // \r
1715     //    printf("%d | %+e %+e %+e %+e %+e -> %+e\n",ip,dx,dz,xxeI,zzeI,xzeI,  chi2);\r
1716   }\r
1717   //\r
1718 }\r
1719 \r
1720 //________________________________________________________________________________________________________\r
1721 void AliITSAlignMille2::InitTrackParams(int meth) \r
1722 {\r
1723   /// initialize local parameters with different methods\r
1724   /// for current track (fTrack)\r
1725   Int_t npts=0;\r
1726   AliTrackPoint ap;\r
1727   double sX=0,sXY=0,sZ=0,sZY=0,sY=0,sYY=0,det=0;\r
1728   // simple linear interpolation\r
1729   // get local starting parameters (to be substituted by ESD track parms)\r
1730   // local parms (fLocalInitParam[]) are:\r
1731   //      [0] = global x coord. of straight line intersection at y=0 plane\r
1732   //      [1] = global z coord. of straight line intersection at y=0 plane\r
1733   //      [2] = px/py  \r
1734   //      [3] = pz/py\r
1735   // test #1: linear fit in x(y) and z(y)\r
1736   npts = fTrack->GetNPoints();\r
1737   AliDebug(3,Form("*** initializing track with %d points ***",npts));\r
1738   for (int i=npts;i--;) {\r
1739     sY  += fTrack->GetY()[i];\r
1740     sYY += fTrack->GetY()[i]*fTrack->GetY()[i];\r
1741     sX  += fTrack->GetX()[i];\r
1742     sXY += fTrack->GetX()[i]*fTrack->GetY()[i];\r
1743     sZ  += fTrack->GetZ()[i];\r
1744     sZY += fTrack->GetZ()[i]*fTrack->GetY()[i];\r
1745   }\r
1746   det = sYY*npts-sY*sY;\r
1747   if (det==0) det = 1E-20;\r
1748   fLocalInitParam[0] = (sX*sYY-sY*sXY)/det;\r
1749   fLocalInitParam[2] = (sXY*npts-sY*sX)/det;\r
1750   //\r
1751   fLocalInitParam[1] = (sZ*sYY-sY*sZY)/det;\r
1752   fLocalInitParam[3] = (sZY*npts-sY*sZ)/det;\r
1753   // pepo200709\r
1754   fLocalInitParam[4] = 0.0;\r
1755   // endpepo200709\r
1756 \r
1757   AliDebug(2,Form("X = p0gx + ugx*Y : p0gx = %f    ugx = %f\n",fLocalInitParam[0],fLocalInitParam[2]));\r
1758   //\r
1759   if (meth==1) return;\r
1760   //\r
1761   // perform full fit accounting for cov.matrix\r
1762   static TVirtualFitter *minuit = 0;\r
1763   static Double_t step[5]   = {1E-3,1E-3,1E-4,1E-4,1E-5};\r
1764   static Double_t arglist[10];\r
1765   //\r
1766   if (!minuit) {\r
1767     minuit = TVirtualFitter::Fitter(0,4);\r
1768     minuit->SetFCN(trackFit2D);\r
1769     arglist[0] = 1;\r
1770     minuit->ExecuteCommand("SET ERR",arglist, 1);\r
1771     //\r
1772     arglist[0] = -1;\r
1773     minuit->ExecuteCommand("SET PRINT",arglist,1);\r
1774     //\r
1775   }\r
1776   //\r
1777   minuit->SetParameter(0, "ax",   fLocalInitParam[0], step[0], 0,0);\r
1778   minuit->SetParameter(1, "az",   fLocalInitParam[1], step[1], 0,0);\r
1779   minuit->SetParameter(2, "bx",   fLocalInitParam[2], step[2], 0,0);\r
1780   minuit->SetParameter(3, "bz",   fLocalInitParam[3], step[3], 0,0);\r
1781   //\r
1782   arglist[0] = 1000; // number of function calls \r
1783   arglist[1] = 0.001; // tolerance \r
1784   minuit->ExecuteCommand("MIGRAD",arglist,2);\r
1785   //\r
1786   for (int i=0;i<4;i++) fLocalInitParam[i] = minuit->GetParameter(i);\r
1787   for (int i=0;i<4;i++) for (int j=0;j<4;j++) fLocalInitParEr[i][j] = minuit->GetCovarianceMatrixElement(i,j);\r
1788   //\r
1789 }\r
1790 \r
1791 //________________________________________________________________________________________________________\r
1792 Int_t AliITSAlignMille2::IsSymDefined(const Char_t* symname) const\r
1793 {\r
1794   // checks if supermodule with this symname is defined and return the internal index\r
1795   // return -1 if not.\r
1796   for (int k=fNModules;k--;) if (!strcmp(symname,GetMilleModule(k)->GetName())) return k;\r
1797   return -1; \r
1798 }\r
1799 \r
1800 //________________________________________________________________________________________________________\r
1801 Int_t AliITSAlignMille2::IsSymContained(const Char_t* symname) const\r
1802 {\r
1803   // checks if module with this symname is defined and return the internal index\r
1804   // return -1 if not.\r
1805   UShort_t vid = AliITSAlignMille2Module::GetVolumeIDFromSymname(symname);\r
1806   if (vid>0) return IsVIDContained(vid);\r
1807   // only sensors have real vid, but maybe we have a supermodule with fake vid? \r
1808   // IMPORTANT: always start from the end to start from the sensors\r
1809   return IsSymDefined(symname);\r
1810 }\r
1811 \r
1812 //________________________________________________________________________________________________________\r
1813 Int_t AliITSAlignMille2::IsVIDDefined(UShort_t voluid) const\r
1814 {\r
1815   // checks if supermodule 'voluid' is defined and return the internal index\r
1816   // return -1 if not.\r
1817   for (int k=fNModules;k--;) if (voluid==GetMilleModule(k)->GetVolumeID()) return k;\r
1818   return -1; \r
1819 }\r
1820 \r
1821 //________________________________________________________________________________________________________\r
1822 Int_t AliITSAlignMille2::IsVIDContained(UShort_t voluid) const\r
1823 {\r
1824   // checks if the sensitive module 'voluid' is contained inside a supermodule \r
1825   // and return the internal index of the last identified supermodule\r
1826   // return -1 if error\r
1827   // IMPORTANT: always start from the end to start from the sensors\r
1828   if (AliITSAlignMille2Module::GetIndexFromVolumeID(voluid)<0) return -1;\r
1829   for (int k=fNModules;k--;) if (GetMilleModule(k)->IsIn(voluid)) return k;\r
1830   return -1; \r
1831 }\r
1832 \r
1833 //________________________________________________________________________________________________________\r
1834 Int_t AliITSAlignMille2::CheckCurrentTrack() \r
1835 {\r
1836   /// checks if AliTrackPoints belongs to defined modules\r
1837   /// return number of good poins\r
1838   /// return 0 if not enough points\r
1839 \r
1840   Int_t npts = fTrack->GetNPoints();\r
1841   Int_t ngoodpts=0;\r
1842   // debug points\r
1843   for (int j=0; j<npts; j++) if (IsVIDContained(fTrack->GetVolumeID()[j])>=0) ngoodpts++;\r
1844   //\r
1845   if (ngoodpts<fMinNPtsPerTrack) return 0;\r
1846 \r
1847   return ngoodpts;\r
1848 }\r
1849 \r
1850 //________________________________________________________________________________________________________\r
1851 Int_t AliITSAlignMille2::ProcessTrack(const AliTrackPointArray *track) \r
1852 {\r
1853   /// Process track; Loop over hits and set local equations\r
1854   /// here 'track' is a AliTrackPointArray\r
1855   /// return 0 if success;\r
1856   \r
1857   if (!fIsMilleInit) Init();\r
1858   //\r
1859   Int_t npts = track->GetNPoints();\r
1860   AliDebug(2,Form("*** Input track with %d points ***",npts));\r
1861 \r
1862   // preprocessing of the input track: keep only points in defined volumes,\r
1863   // move points if prealignment is set, sort by Yglo if required\r
1864   \r
1865   fTrack=PrepareTrack(track);\r
1866   if (!fTrack) return -1;\r
1867 \r
1868   npts = fTrack->GetNPoints();\r
1869   if (npts>kMaxPoints) {\r
1870     AliError(Form("Compiled with kMaxPoints=%d, current track has %d points",kMaxPoints,npts));\r
1871   }\r
1872   AliDebug(2,Form("*** Processing prepared track with %d points ***",npts));\r
1873   \r
1874   if (!fBOn) { // straight lines  \r
1875     // set local starting parameters (to be substituted by ESD track parms)\r
1876     // local parms (fLocalInitParam[]) are:\r
1877     //      [0] = global x coord. of straight line intersection at y=0 plane\r
1878     //      [1] = global z coord. of straight line intersection at y=0 plane\r
1879     //      [2] = px/py  \r
1880     //      [3] = pz/py\r
1881     InitTrackParams(fInitTrackParamsMeth);  \r
1882   } \r
1883   else {\r
1884     // local parms (fLocalInitParam[]) are the Riemann Fitter params\r
1885     if (!InitRiemanFit()) {\r
1886       AliInfo("Riemann fit failed! skipping this track...");\r
1887       fTrack=NULL;\r
1888       return -5;\r
1889     }\r
1890   }\r
1891   \r
1892   Int_t nloceq=0;\r
1893   Int_t ngloeq=0;\r
1894   static Mille2Data md[kMaxPoints];\r
1895   //\r
1896   for (Int_t ipt=0; ipt<npts; ipt++) {\r
1897     fTrack->GetPoint(fCluster,ipt);\r
1898     fCluster.SetUniqueID(ipt);\r
1899     AliDebug(2,Form("\n--- processing point %d --- \n",ipt));    \r
1900 \r
1901     // set geometry parameters for the the current module\r
1902     if (InitModuleParams()) continue;\r
1903     AliDebug(2,Form("    VolID=%d  Index=%d  InternalIdx=%d  symname=%s\n", \r
1904                     track->GetVolumeID()[ipt], fCurrentModule->GetIndex(),\r
1905                     fCurrentModule->GetUniqueID(), AliGeomManager::SymName(track->GetVolumeID()[ipt]) ));\r
1906     AliDebug(2,Form("    Preprocessed Point = ( %f , %f , %f ) \n",fCluster.GetX(),fCluster.GetY(),fCluster.GetZ()));\r
1907     int res = AddLocalEquation(md[nloceq]);\r
1908     if (res<0) {fTotBadLocEqPoints++; nloceq = 0; break;}\r
1909     else if (res==0) nloceq++;\r
1910     else {nloceq++; ngloeq++;}\r
1911   } // end loop over points\r
1912   //\r
1913   fTrack=NULL;\r
1914   // not enough good points?\r
1915   if (nloceq<fMinNPtsPerTrack || ngloeq<1) return -1;\r
1916   //\r
1917   // finally send local equations to millepede\r
1918   SetLocalEquations(md,nloceq);\r
1919   fMillepede->SaveRecordData(); // RRR\r
1920   //\r
1921   return 0;\r
1922 }\r
1923 \r
1924 //________________________________________________________________________________________________________\r
1925 Int_t AliITSAlignMille2::CalcIntersectionPoint(Double_t *lpar, Double_t *gpar) \r
1926 {\r
1927   /// calculate track intersection point in local coordinates\r
1928   /// according with a given set of parameters (local(4) and global(6))\r
1929   /// and fill fPintLoc/Glo\r
1930   ///    local are:   pgx0, pgz0, ugx, ugz   OR   riemann fitters pars\r
1931   ///    global are:  tx,ty,tz,psi,theta,phi (Raff's delta angles in deg.)\r
1932   /// return 0 if success\r
1933   \r
1934   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
1935   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
1936 \r
1937   \r
1938   // prepare the TGeoHMatrix\r
1939   TGeoHMatrix *tempHMat = fCurrentModule->GetSensitiveVolumeModifiedMatrix(fCluster.GetVolumeID(),gpar,\r
1940                                                                            !fUseGlobalDelta);\r
1941   if (!tempHMat) return -1;\r
1942   \r
1943   Double_t v0g[3]; // vector with straight line direction in global coord.\r
1944   Double_t p0g[3]; // point of the straight line (glo)\r
1945   \r
1946   if (fBOn) { // B FIELD!\r
1947     AliTrackPoint prf; \r
1948     for (int ip=0; ip<5; ip++)\r
1949       fRieman->SetParam(ip,lpar[ip]);\r
1950 \r
1951     if (!fRieman->GetPCA(fCluster,prf))  {\r
1952       AliInfo(Form("error in GetPCA for point %d",fCluster.GetVolumeID()));\r
1953       return -3;\r
1954     }\r
1955     // now determine straight line passing tangent to fit curve at prf\r
1956     // ugx = dX/dY_glo = DeltaX/DeltaY_glo\r
1957     // mo' P1=(X,Y,Z)_glo_prf\r
1958     //       => (x,y,Z)_trk_prf ruotando di alpha...\r
1959     Double_t alpha=fRieman->GetAlpha();\r
1960     Double_t x1g = prf.GetX();\r
1961     Double_t y1g = prf.GetY();\r
1962     Double_t z1g = prf.GetZ();\r
1963     Double_t x1t =  x1g*TMath::Cos(alpha) + y1g*TMath::Sin(alpha);\r
1964     Double_t y1t = -x1g*TMath::Sin(alpha) + y1g*TMath::Cos(alpha);\r
1965     Double_t z1t =  z1g;    \r
1966 \r
1967     Double_t x2t = x1t+1.0;\r
1968     Double_t y2t = y1t+fRieman->GetDYat(x1t);\r
1969     Double_t z2t = z1t+fRieman->GetDZat(x1t);\r
1970     Double_t x2g =  x2t*TMath::Cos(alpha) - y2t*TMath::Sin(alpha);\r
1971     Double_t y2g =  x2t*TMath::Sin(alpha) + y2t*TMath::Cos(alpha);\r
1972     Double_t z2g =  z2t;  \r
1973 \r
1974     AliDebug(3,Form("Riemann frame:  fAlpha = %f  =  %f  ",alpha,alpha*180./TMath::Pi()));\r
1975     AliDebug(3,Form("   prf_glo=( %f , %f , %f )  prf_rf=( %f , %f , %f )\n", x1g,y1g,z1g, x1t,y1t,z1t));\r
1976     AliDebug(3,Form("   mov_glo=( %f , %f , %f )      rf=( %f , %f , %f )\n",x2g,y2g,z2g, x2t,y2t,z2t));\r
1977         \r
1978     if (TMath::Abs(y2g-y1g)<1e-15) {\r
1979       AliInfo("DeltaY=0! Cannot proceed...");\r
1980       return -1;\r
1981     }\r
1982     // ugx,1,ugz\r
1983     v0g[0] = (x2g-x1g)/(y2g-y1g);\r
1984     v0g[1]=1.0;\r
1985     v0g[2] = (z2g-z1g)/(y2g-y1g);\r
1986     \r
1987     // point: just keep prf\r
1988     p0g[0]=x1g;\r
1989     p0g[1]=y1g;\r
1990     p0g[2]=z1g;\r
1991   }  \r
1992   else { // staight line\r
1993     // vector of initial straight line direction in glob. coord\r
1994     v0g[0]=lpar[2];\r
1995     v0g[1]=1.0;\r
1996     v0g[2]=lpar[3];\r
1997     \r
1998     // intercept in yg=0 plane in glob coord\r
1999     p0g[0]=lpar[0];\r
2000     p0g[1]=0.0;\r
2001     p0g[2]=lpar[1];\r
2002   }\r
2003   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
2004   \r
2005   // same in local coord.\r
2006   Double_t p0l[3],v0l[3];\r
2007   tempHMat->MasterToLocalVect(v0g,v0l);\r
2008   tempHMat->MasterToLocal(p0g,p0l);\r
2009   \r
2010   if (TMath::Abs(v0l[1])<1e-15) {\r
2011     AliInfo("Track Y direction in local frame is zero! Cannot proceed...");\r
2012     return -1;\r
2013   }\r
2014   \r
2015   // local intersection point\r
2016   fPintLoc[0] = p0l[0] - (v0l[0]/v0l[1])*p0l[1];\r
2017   fPintLoc[1] = 0;\r
2018   fPintLoc[2] = p0l[2] - (v0l[2]/v0l[1])*p0l[1];\r
2019   \r
2020   // global intersection point\r
2021   tempHMat->LocalToMaster(fPintLoc,fPintGlo);\r
2022   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
2023   \r
2024   return 0;\r
2025 }\r
2026 \r
2027 //________________________________________________________________________________________________________\r
2028 Int_t AliITSAlignMille2::CalcDerivatives(Int_t paridx, Bool_t islpar) \r
2029 {\r
2030   /// calculate numerically (ROOT's style) the derivatives for\r
2031   /// local X intersection  and local Z intersection\r
2032   /// parlist: local  (islpar=kTRUE)  pgx0, pgz0, ugx0, ugz0  OR riemann's params\r
2033   ///          global (islpar=kFALSE) tx, ty, tz, psi, theta, phi (Raf's angles in deg)\r
2034   /// return 0 if success\r
2035   \r
2036   // copy initial parameters\r
2037   Double_t lpar[kNLocal];\r
2038   Double_t gpar[kNParCh];\r
2039   Double_t *derivative;\r
2040   for (Int_t i=0; i<kNLocal; i++) lpar[i]=fLocalInitParam[i];\r
2041   for (Int_t i=0; i<kNParCh; i++) gpar[i]=fModuleInitParam[i];\r
2042 \r
2043   // trial with fixed dpar...\r
2044   Double_t dpar = 0.;\r
2045 \r
2046   if (islpar) { // track parameters\r
2047     //dpar=fLocalInitParam[paridx]*0.001;\r
2048     // set minimum dpar\r
2049     derivative = fDerivativeLoc[paridx];\r
2050     if (!fBOn) {\r
2051       if (paridx<3) dpar=1.0e-4; // translations\r
2052       else dpar=1.0e-6; // direction\r
2053     }\r
2054     else { // B Field\r
2055       // pepo: proviamo con 1/1000, poi evenctually 1/100...\r
2056       Double_t dfrac=0.01;\r
2057       switch(paridx) {\r
2058       case 0:\r
2059         // RMS cosmics: 1e-4\r
2060         dpar = TMath::Max(1.0e-6,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2061         break;\r
2062       case 1: \r
2063         // RMS cosmics: 0.2\r
2064         dpar = TMath::Max(0.002,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2065         break;\r
2066       case 2: \r
2067         // RMS cosmics: 9\r
2068         dpar = TMath::Max(0.09,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2069         break;\r
2070       case 3: \r
2071         // RMS cosmics: 7\r
2072         dpar = TMath::Max(0.07,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2073         break;\r
2074       case 4: \r
2075         // RMS cosmics: 0.3\r
2076         dpar = TMath::Max(0.003,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
2077         break;\r
2078       }\r
2079     }\r
2080   }\r
2081   else { // alignment global parameters\r
2082     derivative = fDerivativeGlo[paridx];\r
2083     //dpar=fModuleInitParam[paridx]*0.001;\r
2084     if (paridx<3) dpar=1.0e-4; // translations\r
2085     else dpar=1.0e-2; // angles    \r
2086   }\r
2087 \r
2088   AliDebug(3,Form("+++ using dpar=%g",dpar));\r
2089   \r
2090   // calculate derivative ROOT's like:\r
2091   //  using f(x+h),f(x-h),f(x+h/2),f(x-h2)...\r
2092   Double_t pintl1[3]; // f(x-h)\r
2093   Double_t pintl2[3]; // f(x-h/2)\r
2094   Double_t pintl3[3]; // f(x+h/2)\r
2095   Double_t pintl4[3]; // f(x+h)\r
2096     \r
2097   // first values\r
2098   if (islpar) lpar[paridx] -= dpar;\r
2099   else gpar[paridx] -= dpar;\r
2100   if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
2101   for (Int_t i=0; i<3; i++) pintl1[i]=fPintLoc[i];\r
2102 \r
2103   // second values\r
2104   if (islpar) lpar[paridx] += dpar/2;\r
2105   else gpar[paridx] += dpar/2;\r
2106   if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
2107   for (Int_t i=0; i<3; i++) pintl2[i]=fPintLoc[i];\r
2108 \r
2109   // third values\r
2110   if (islpar) lpar[paridx] += dpar;\r
2111   else gpar[paridx] += dpar;\r
2112   if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
2113   for (Int_t i=0; i<3; i++) pintl3[i]=fPintLoc[i];\r
2114 \r
2115   // fourth values\r
2116   if (islpar) lpar[paridx] += dpar/2;\r
2117   else gpar[paridx] += dpar/2;\r
2118   if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
2119   for (Int_t i=0; i<3; i++) pintl4[i]=fPintLoc[i];\r
2120 \r
2121   Double_t h2 = 1./(2.*dpar);\r
2122   Double_t d0 = pintl4[0]-pintl1[0];\r
2123   Double_t d2 = 2.*(pintl3[0]-pintl2[0]);\r
2124   derivative[0] = h2*(4*d2 - d0)/3.;\r
2125   if (TMath::Abs(derivative[0]) < 1.0e-9) derivative[0] = 0.0;\r
2126 \r
2127   d0 = pintl4[2]-pintl1[2];\r
2128   d2 = 2.*(pintl3[2]-pintl2[2]);\r
2129   derivative[2] = h2*(4*d2 - d0)/3.;\r
2130   if (TMath::Abs(derivative[2]) < 1.0e-9) derivative[2]=0.0;\r
2131 \r
2132   AliDebug(3,Form("\n+++ derivatives +++ \n"));\r
2133   AliDebug(3,Form("+++ dXLoc/dpar = %g +++\n",derivative[0]));\r
2134   AliDebug(3,Form("+++ dZLoc/dpar = %g +++\n\n",derivative[2]));\r
2135   \r
2136   return 0;\r
2137 }\r
2138 \r
2139 //________________________________________________________________________________________________________\r
2140 Int_t AliITSAlignMille2::AddLocalEquation(Mille2Data &m) \r
2141 {\r
2142   /// Define local equation for current cluster in X and Z coor.\r
2143   /// and store them to memory\r
2144   /// return -1 in case of failure to build some equation\r
2145   ///         0 if no free global parameters were found but local eq is built\r
2146   ///         1 if both local and global eqs are built\r
2147   //\r
2148   // store first intersection point\r
2149   if (CalcIntersectionPoint(fLocalInitParam, fModuleInitParam)) return -1;  \r
2150   for (Int_t i=0; i<3; i++) fPintLoc0[i]=fPintLoc[i];\r
2151   AliDebug(2,Form("Intesect. point: L( %f , %f , %f )",fPintLoc[0],fPintLoc[1],fPintLoc[2]));\r
2152   \r
2153   // calculate local derivatives numerically\r
2154   Bool_t zeroX = kTRUE;\r
2155   Bool_t zeroZ = kTRUE;\r
2156   //\r
2157   for (Int_t i=0; i<fNLocal; i++) {\r
2158     if (CalcDerivatives(i,kTRUE)) return -1;\r
2159     m.fDerLocX[i] = fDerivativeLoc[i][0];\r
2160     m.fDerLocZ[i] = fDerivativeLoc[i][2];\r
2161     if (zeroX) zeroX = fDerivativeLoc[i][0]==0;\r
2162     if (zeroZ) zeroZ = fDerivativeLoc[i][2]==0;\r
2163   }\r
2164   //  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
2165   //\r
2166   if (zeroX) {AliInfo("Skipping: zero local X derivatives!"); return -1;}\r
2167   if (zeroZ) {AliInfo("Skipping: zero local Z derivatives!"); return -1;}\r
2168   //\r
2169   int ifill = 0;\r
2170   //\r
2171   AliITSAlignMille2Module* endModule = fCurrentModule;\r
2172   //\r
2173   zeroX = zeroZ = kTRUE;\r
2174   Bool_t dfDone[kNParCh];\r
2175   for (int i=kNParCh;i--;) dfDone[i] = kFALSE;\r
2176   m.fNModFilled = 0;\r
2177   // \r
2178   // special block for SDD derivatives\r
2179   Double_t jacobian[kNParChGeom];\r
2180   Int_t nmodTested = 0;\r
2181   //\r
2182   do {\r
2183     if (fCurrentModule->GetNParFree()==0) continue;\r
2184     nmodTested++;\r
2185     for (Int_t i=0; i<kNParChGeom; i++) {   // common for all sensors: derivatives over geom params \r
2186       //\r
2187       if (!fUseGlobalDelta) dfDone[i] = kFALSE; // for global deltas the derivatives at diff. levels are different\r
2188       if (fCurrentModule->GetParOffset(i)<0) continue; // this parameter is not explicitly fitted\r
2189       if (!dfDone[i]) { \r
2190         if (CalcDerivatives(i,kFALSE)) return -1; \r
2191         else {\r
2192           dfDone[i] = kTRUE;\r
2193           if (zeroX) zeroX = fDerivativeGlo[i][0]==0;\r
2194           if (zeroZ) zeroZ = fDerivativeGlo[i][2]==0;\r
2195         }\r
2196       }\r
2197       //\r
2198       m.fDerGloX[ifill] = fDerivativeGlo[i][0];\r
2199       m.fDerGloZ[ifill] = fDerivativeGlo[i][2];\r
2200       m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(i);\r
2201     }\r
2202     //\r
2203     // specific for special sensors\r
2204     if ( fCurrentModule->IsSDD() && \r
2205          (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0)>=0 ||\r
2206           fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV)>=0) ) {\r
2207       //\r
2208       // assume for sensor local xloc = xloc0 + V0*dT0+dV*(T-T0)\r
2209       // where V0 and T are the nominal drift velocity, time and time0\r
2210       // and the dT0 and dV are the corrections:\r
2211       // dX/dT0 = dX/dxloc * dxloc/dT0 = dX/dxloc * V0\r
2212       // dX/dV  = dX/dxloc * dxloc/dV =  dX/dxloc * (T-T0)\r
2213       // IMPORTANT: the geom derivatives are over the SENSOR LOCAL parameters\r
2214       //\r
2215       if (!dfDone[AliITSAlignMille2Module::kDOFT0] || !dfDone[AliITSAlignMille2Module::kDOFDV]) {\r
2216         //\r
2217         double dXdxlocsens=0., dZdxlocsens=0.;\r
2218         //\r
2219         // if the current module is the sensor itself and we work with local params, then \r
2220         // we can directly take dX/dxloc_sens dZ/dxloc_sens\r
2221         if (!fUseGlobalDelta && fCurrentModule->GetVolumeID()==fCluster.GetVolumeID()) {\r
2222           if (dfDone[AliITSAlignMille2Module::kDOFTX]) {\r
2223             CalcDerivatives(AliITSAlignMille2Module::kDOFTX,kFALSE); \r
2224             dfDone[AliITSAlignMille2Module::kDOFTX] = kTRUE;\r
2225           }\r
2226           dXdxlocsens = fDerivativeGlo[AliITSAlignMille2Module::kDOFTX][0];\r
2227           dZdxlocsens = fDerivativeGlo[AliITSAlignMille2Module::kDOFTX][2];\r
2228         }\r
2229         //\r
2230         else { // need to perform some transformations\r
2231           // fetch the jacobian of the transformation from the sensors local frame to the frame\r
2232           // where the parameters are defined:\r
2233           // Global: dX/dxloc_sens = dX/dxgl*dxgl/dxloc_sens + ...dX/dphigl*dphigl/dxloc_sens\r
2234           if (fUseGlobalDelta) fCurrentModule->CalcDerivGloLoc(fCluster.GetVolumeID(),\r
2235                                                                AliITSAlignMille2Module::kDOFTX, jacobian);\r
2236           // Local:  dX/dxloc_sens = dX/dxcurr*dxcurr/dxloc_sens +..+dX/dphicurr * dphicurr/dxloc_sens \r
2237           else                 fCurrentModule->CalcDerivCurLoc(fCluster.GetVolumeID(),\r
2238                                                                AliITSAlignMille2Module::kDOFTX, jacobian);\r
2239           //\r
2240           for (int j=0;j<kNParChGeom;j++) {\r
2241             // need global derivative even if the j-th param is locked\r
2242             if (!dfDone[j]) {CalcDerivatives(j,kFALSE); dfDone[j] = kTRUE;}\r
2243             dXdxlocsens += fDerivativeGlo[j][0] * jacobian[j];\r
2244             dZdxlocsens += fDerivativeGlo[j][2] * jacobian[j];\r
2245           }\r
2246         }\r
2247         //\r
2248         if (zeroX) zeroX = dXdxlocsens == 0;\r
2249         if (zeroZ) zeroZ = dZdxlocsens == 0;\r
2250         //\r
2251         double vdrift = GetVDriftSDD();\r
2252         double tdrift = GetTDriftSDD();\r
2253         //\r
2254         fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][0] = dXdxlocsens*vdrift;\r
2255         fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][2] = dZdxlocsens*vdrift;\r
2256         dfDone[AliITSAlignMille2Module::kDOFT0] = kTRUE;\r
2257         //\r
2258         fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][0] = -dXdxlocsens*TMath::Sign(tdrift,vdrift);\r
2259         fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][2] = -dZdxlocsens*TMath::Sign(tdrift,vdrift);\r
2260         dfDone[AliITSAlignMille2Module::kDOFDV] = kTRUE;\r
2261         //\r
2262       }\r
2263       //\r
2264       if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0)>=0) {\r
2265         m.fDerGloX[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][0];\r
2266         m.fDerGloZ[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][2];\r
2267         m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0);      \r
2268       }\r
2269       //\r
2270       if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV)>=0) {\r
2271         m.fDerGloX[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][0];\r
2272         m.fDerGloZ[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][2];\r
2273         m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV);      \r
2274       }\r
2275     }\r
2276     //\r
2277     m.fModuleID[m.fNModFilled++] = fCurrentModule->GetUniqueID();\r
2278   } while( (fCurrentModule=fCurrentModule->GetParent()) );\r
2279   //\r
2280   if (nmodTested>0 && zeroX) {AliInfo("Skipping: zero global X derivatives!");return -1;}\r
2281   if (nmodTested>0 && zeroZ) {AliInfo("Skipping: zero global Z derivatives!");return -1;}\r
2282   //\r
2283   // ok, can copy to m\r
2284   AliDebug(2,Form("Adding local equation X with fMeas=%.6f  and fSigma=%.6f",(fMeasLoc[0]-fPintLoc0[0]), fSigmaLoc[0]));\r
2285   m.fMeasX = fMeasLoc[0]-fPintLoc0[0];\r
2286   m.fSigmaX = fSigmaLoc[0];\r
2287   //\r
2288   AliDebug(2,Form("Adding local equation Z with fMeas=%.6f  and fSigma=%.6f",(fMeasLoc[2]-fPintLoc0[2]), fSigmaLoc[2]));\r
2289   m.fMeasZ = fMeasLoc[2]-fPintLoc0[2];\r
2290   m.fSigmaZ = fSigmaLoc[2];\r
2291   //\r
2292   m.fNGlobFilled = ifill;\r
2293   fCurrentModule = endModule;\r
2294   //\r
2295   return Int_t(!zeroX && !zeroZ);\r
2296 }\r
2297 \r
2298 //________________________________________________________________________________________________________\r
2299 void AliITSAlignMille2::SetLocalEquations(const Mille2Data *marr, Int_t neq) \r
2300 {\r
2301   /// Set local equations with data stored in m\r
2302   /// return 0 if success\r
2303   //\r
2304   for (Int_t j=0; j<neq; j++) {\r
2305     //\r
2306     const Mille2Data &m = marr[j];\r
2307     //\r
2308     // set equation for Xloc coordinate\r
2309     AliDebug(2,Form("setting local equation X with fMeas=%.6f  and fSigma=%.6f",m.fMeasX, m.fSigmaX));\r
2310     for (int i=fNLocal; i--;) SetLocalDerivative( i, m.fDerLocX[i] );\r
2311     for (int i=m.fNGlobFilled;i--;) SetGlobalDerivative( m.fParMilleID[i] , m.fDerGloX[i] );\r
2312     fMillepede->SetLocalEquation(fGlobalDerivatives, fLocalDerivatives, m.fMeasX, m.fSigmaX);  \r
2313     //\r
2314     // set equation for Zloc coordinate\r
2315     AliDebug(2,Form("setting local equation Z with fMeas=%.6f  and fSigma=%.6f",m.fMeasZ, m.fSigmaZ));\r
2316     for (int i=fNLocal; i--;) SetLocalDerivative( i, m.fDerLocZ[i] );\r
2317     for (int i=m.fNGlobFilled;i--;) SetGlobalDerivative( m.fParMilleID[i] , m.fDerGloZ[i] );\r
2318     fMillepede->SetLocalEquation(fGlobalDerivatives, fLocalDerivatives, m.fMeasZ, m.fSigmaZ);  \r
2319     //\r
2320     for (int i=m.fNModFilled;i--;) GetMilleModule(m.fModuleID[i])->IncNProcessedPoints();\r
2321     //\r
2322   }\r
2323 }\r
2324 \r
2325 //________________________________________________________________________________________________________\r
2326 Int_t AliITSAlignMille2::GlobalFit()\r
2327 {\r
2328   /// Call global fit; Global parameters are stored in parameters\r
2329   if (!fIsMilleInit) Init();\r
2330   //\r
2331   ApplyPreConstraints();\r
2332   int res = fMillepede->GlobalFit();\r
2333   AliInfo(Form("%s fitting global parameters!",res ? "Done":"Failed"));\r
2334   if (res) {\r
2335     // fetch the parameters\r
2336     for (int imd=fNModules;imd--;) {\r
2337       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2338       int nprocp = 0;\r
2339       for (int ip=mod->GetNParTot();ip--;) {\r
2340         int idp = mod->GetParOffset(ip);\r
2341         if (idp<0) continue;    // was not in the explicit fit\r
2342         mod->SetParVal(ip,fMillepede->GetFinalParam(idp));\r
2343         mod->SetParErr(ip,fMillepede->GetFinalError(idp));\r
2344         int np = fMillepede->GetProcessedPoints(idp);\r
2345         if (TMath::Abs(np)>TMath::Abs(nprocp)) nprocp = np;\r
2346       }\r
2347       if (!mod->GetNProcessedPoints()) mod->SetNProcessedPoints(nprocp);\r
2348     }\r
2349 \r
2350   }\r
2351   ApplyPostConstraints();\r
2352   return res;\r
2353 }\r
2354 \r
2355 //________________________________________________________________________________________________________\r
2356 void AliITSAlignMille2::PrintGlobalParameters() \r
2357 {\r
2358   /// Print global parameters\r
2359   if (!fIsMilleInit) {\r
2360     AliInfo("Millepede has not been initialized!");\r
2361     return;\r
2362   }\r
2363   fMillepede->PrintGlobalParameters();\r
2364 }\r
2365 \r
2366 //________________________________________________________________________________________________________\r
2367 Int_t AliITSAlignMille2::LoadSuperModuleFile(const Char_t *sfile)\r
2368\r
2369   // load definitions of supermodules from a root file\r
2370   // return 0 if success\r
2371 \r
2372   TFile *smf=TFile::Open(sfile);\r
2373   if (!smf->IsOpen()) {\r
2374     AliInfo(Form("Cannot open supermodule file %s",sfile));\r
2375     return -1;\r
2376   }\r
2377 \r
2378   TClonesArray *sma=(TClonesArray*)smf->Get("ITSMilleSuperModules");\r
2379   if (!sma) {\r
2380     AliInfo(Form("Cannot find ITSMilleSuperModules array in file"));\r
2381     return -2;  \r
2382   }  \r
2383   Int_t nsma=sma->GetEntriesFast();\r
2384   AliInfo(Form("Array of SuperModules with %d entries\n",nsma));\r
2385   //\r
2386   // pepo200709\r
2387   Char_t st[2048];\r
2388   char symname[250];\r
2389   // end pepo200709\r
2390 \r
2391   UShort_t volid;\r
2392   TGeoHMatrix m;\r
2393   //\r
2394   for (Int_t i=0; i<nsma; i++) {\r
2395     AliAlignObjParams *a = (AliAlignObjParams*)sma->UncheckedAt(i);\r
2396     volid=a->GetVolUID();\r
2397     strcpy(st,a->GetSymName());\r
2398     a->GetMatrix(m);\r
2399     //\r
2400     sscanf(st,"%s",symname);\r
2401     //\r
2402     // decode module list\r
2403     char *stp=strstr(st,"ModuleList:");\r
2404     if (!stp) return -3;\r
2405     stp += 11;\r
2406     int idx[2200];\r
2407     char spp[200]; int jp=0;\r
2408     char cl[20];\r
2409     strcpy(st,stp);\r
2410     int l=strlen(st);\r
2411     int j=0;\r
2412     int n=0;\r
2413     //\r
2414     while (j<=l) {\r
2415       if (st[j]==9 || st[j]==32 || st[j]==10 || st[j]==0) {\r
2416         spp[jp]=0;\r
2417         jp=0;\r
2418         if (strlen(spp)) {\r
2419           int k=strcspn(spp,"-");\r
2420           if (k<int(strlen(spp))) { // c'e' il -\r
2421             strcpy(cl,&(spp[k+1]));\r
2422             spp[k]=0;\r
2423             int ifrom=atoi(spp); int ito=atoi(cl);\r
2424             for (int b=ifrom; b<=ito; b++) {\r
2425               idx[n]=b;\r
2426               n++;\r
2427             }\r
2428           }\r
2429           else { // numerillo singolo\r
2430             idx[n]=atoi(spp);\r
2431             n++;\r
2432           }\r
2433         }\r
2434       }\r
2435       else {\r
2436         spp[jp]=st[j];\r
2437         jp++;\r
2438       }\r
2439       j++;\r
2440     }\r
2441     UShort_t volidsv[2198];\r
2442     for (j=0;j<n;j++) {\r
2443       volidsv[j]=AliITSAlignMille2Module::GetVolumeIDFromIndex(idx[j]);\r
2444       if (!volidsv[j]) {\r
2445         AliInfo(Form("Index %d not valid (range 0->%d)",idx[j],kMaxITSSensID));\r
2446         return -5;\r
2447       }\r
2448     }\r
2449     Int_t smindex=int(2198+volid-14336); // virtual index\r
2450     //\r
2451     fSuperModule.AddAtAndExpand(new AliITSAlignMille2Module(smindex,volid,symname,&m,n,volidsv),fNSuperModules);\r
2452     //\r
2453     fNSuperModules++;\r
2454   }\r
2455   //\r
2456   smf->Close();\r
2457   //\r
2458   return 0;\r
2459 }\r
2460 \r
2461 //________________________________________________________________________________________________________\r
2462 void AliITSAlignMille2::ConstrainModuleSubUnitsMean(Int_t idm, Double_t val, UInt_t pattern)\r
2463 {\r
2464   // require that sum of modifications for the childs of this module is = val, i.e.\r
2465   // the internal corrections moves the module as a whole by fixed value (0 by default).\r
2466   // pattern is the bit pattern for the parameters to constrain\r
2467   //\r
2468   if (fIsMilleInit) {\r
2469     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2470     return;\r
2471   }\r
2472   if (!GetMilleModule(idm)->GetNChildren()) return;\r
2473   TString nm = "cstrSUMean";\r
2474   nm += GetNConstraints();\r
2475   AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMean,\r
2476                                                                       idm,val,pattern);\r
2477   cstr->SetConstraintID(GetNConstraints());\r
2478   fConstraints.Add(cstr);\r
2479 }\r
2480 \r
2481 //________________________________________________________________________________________________________\r
2482 void AliITSAlignMille2::ConstrainModuleSubUnitsMedian(Int_t idm, Double_t val, UInt_t pattern)\r
2483 {\r
2484   // require that median of the modifications for the childs of this module is = val, i.e.\r
2485   // the internal corrections moves the module as a whole by fixed value (0 by default) \r
2486   // module the outliers.\r
2487   // pattern is the bit pattern for the parameters to constrain\r
2488   // The difference between the mean and the median will be transfered to the parent\r
2489   if (fIsMilleInit) {\r
2490     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2491     return;\r
2492   }\r
2493   if (!GetMilleModule(idm)->GetNChildren()) return;\r
2494   TString nm = "cstrSUMed";\r
2495   nm += GetNConstraints();\r
2496   AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMedian,\r
2497                                                                       idm,val,pattern);\r
2498   cstr->SetConstraintID(GetNConstraints());\r
2499   fConstraints.Add(cstr);\r
2500 }\r
2501 \r
2502 //________________________________________________________________________________________________________\r
2503 void AliITSAlignMille2::ConstrainOrphansMean(Double_t val, UInt_t pattern)\r
2504 {\r
2505   // require that median of the modifications for the supermodules which have no parents is = val, i.e.\r
2506   // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.\r
2507   // pattern is the bit pattern for the parameters to constrain\r
2508   //\r
2509   if (fIsMilleInit) {\r
2510     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2511     return;\r
2512   }\r
2513   TString nm = "cstrOMean";\r
2514   nm += GetNConstraints();\r
2515   AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMean,\r
2516                                                                       -1,val,pattern);\r
2517   cstr->SetConstraintID(GetNConstraints());\r
2518   fConstraints.Add(cstr);\r
2519 }\r
2520 \r
2521 //________________________________________________________________________________________________________\r
2522 void AliITSAlignMille2::ConstrainOrphansMedian(Double_t val, UInt_t pattern)\r
2523 {\r
2524   // require that median of the modifications for the supermodules which have no parents is = val, i.e.\r
2525   // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.\r
2526   // pattern is the bit pattern for the parameters to constrain\r
2527   //\r
2528   if (fIsMilleInit) {\r
2529     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2530     return;\r
2531   }\r
2532   TString nm = "cstrOMed";\r
2533   nm += GetNConstraints();\r
2534   AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMedian,\r
2535                                                                       -1,val,pattern);\r
2536   cstr->SetConstraintID(GetNConstraints());\r
2537   fConstraints.Add(cstr);\r
2538 }\r
2539 \r
2540 //________________________________________________________________________________________________________\r
2541 void AliITSAlignMille2::ConstrainLocal(const Char_t* name,Double_t *parcf,Int_t npar,Double_t val,Double_t err)\r
2542 {\r
2543   // apply constraint on parameters in the local frame\r
2544   if (fIsMilleInit) {\r
2545     AliInfo("Millepede has been already initialized: no constrain may be added!");\r
2546     return;\r
2547   }\r
2548   AliITSAlignMille2ConstrArray *cstr = new AliITSAlignMille2ConstrArray(name,parcf,npar,val,err);\r
2549   cstr->SetConstraintID(GetNConstraints());\r
2550   fConstraints.Add(cstr);\r
2551 }\r
2552 \r
2553 //________________________________________________________________________________________________________\r
2554 void AliITSAlignMille2::ApplyGaussianConstraint(const AliITSAlignMille2ConstrArray* cstr)\r
2555 {\r
2556   // apply the constraint on the local corrections of a list of modules\r
2557   int nmod = cstr->GetNModules();\r
2558   double jacobian[AliITSAlignMille2Module::kMaxParGeom][AliITSAlignMille2Module::kMaxParGeom];\r
2559   //\r
2560   for (int imd=nmod;imd--;) {\r
2561     int modID = cstr->GetModuleID(imd);\r
2562     AliITSAlignMille2Module* mod = GetMilleModule(modID);\r
2563     ResetLocalEquation();\r
2564     int nadded = 0;\r
2565     double value = cstr->GetValue();\r
2566     double sigma = cstr->GetError();\r
2567     //\r
2568     // in case the reference (survey) deltas were imposed for Gaussian constraints\r
2569     // already accumulated corrections: they must be subtracted from the constraint value.\r
2570     if (IsConstraintWrtRef()) {\r
2571       //\r
2572       Double_t precal[AliITSAlignMille2Module::kMaxParTot];\r
2573       Double_t refcal[AliITSAlignMille2Module::kMaxParTot];\r
2574       for (int ip=AliITSAlignMille2Module::kMaxParTot;ip--;) {precal[ip]=0; refcal[ip] = 0.;}\r
2575       //\r
2576       // check if there was a reference delta provided for this module\r
2577       AliAlignObjParams* parref = GetConstrRefObject(mod->GetName());\r
2578       if (parref) parref->GetPars(refcal, refcal+3);    // found reference delta\r
2579       //\r
2580       // extract already applied local corrections for this module\r
2581       if (fPrealignment) {\r
2582         //\r
2583         AliAlignObjParams *preo = GetPrealignedObject(mod->GetName());\r
2584         if (preo) {\r
2585           TGeoHMatrix preMat,tmpMat = *mod->GetMatrix(); //  Delta_Glob * Delta_Glob_Par * M\r
2586           preo->GetMatrix(preMat);                       //  Delta_Glob\r
2587           preMat.MultiplyLeft( &tmpMat.Inverse() );      //  M^-1 * Delta_Glob_Par^-1 = (Delta_Glob_Par * M)^-1\r
2588           tmpMat.MultiplyLeft( &preMat );                //  (Delta_Glob_Par * M)^-1 * Delta_Glob * Delta_Glob_Par * M = Delta_loc\r
2589           AliAlignObjParams algob;\r
2590           algob.SetMatrix(tmpMat);\r
2591           algob.GetPars(precal,precal+3); // local corrections for geometry\r
2592         }\r
2593       }\r
2594       //\r
2595       // subtract the contribution to constraint from precalibration \r
2596       for (int ipar=cstr->GetNCoeffs();ipar--;) value += (refcal[ipar]-precal[ipar])*cstr->GetCoeff(ipar);\r
2597       //\r
2598     } \r
2599     //    \r
2600     if (fUseGlobalDelta) mod->CalcDerivLocGlo(&jacobian[0][0]);\r
2601     //\r
2602     for (int ipar=cstr->GetNCoeffs();ipar--;) {\r
2603       double coef = cstr->GetCoeff(ipar);\r
2604       if (coef==0) continue;\r
2605       //\r
2606       if (!fUseGlobalDelta || ipar>= AliITSAlignMille2Module::kMaxParGeom) { // \r
2607         // we are working with local params or if the given param is not related to geometry, \r
2608         // apply the constraint directly\r
2609         int parPos = mod->GetParOffset(ipar);\r
2610         if (parPos<0) continue; // not in the fit\r
2611         fGlobalDerivatives[parPos] += coef;\r
2612         nadded++;\r
2613       }\r
2614       else { // we are working with global params, while the constraint is on local ones -> jacobian\r
2615         for (int jpar=AliITSAlignMille2Module::kMaxParGeom;jpar--;) {\r
2616           int parPos = mod->GetParOffset(jpar);\r
2617           if (parPos<0) continue;\r
2618           fGlobalDerivatives[parPos] += coef*jacobian[ipar][jpar];\r
2619           nadded++;\r
2620         }\r
2621       }      \r
2622     }\r
2623     if (nadded) AddConstraint(fGlobalDerivatives, value, sigma);\r
2624   }\r
2625   //\r
2626 }\r
2627 \r
2628 //________________________________________________________________________________________________________\r
2629 void AliITSAlignMille2::ApplyPreConstraints()\r
2630 {\r
2631   // apply constriants which cannot be imposed after the fit\r
2632   int nconstr = GetNConstraints();\r
2633   for (int i=0;i<nconstr;i++) {\r
2634     AliITSAlignMille2Constraint* cstr = GetConstraint(i);\r
2635     //\r
2636     if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) {\r
2637       ApplyGaussianConstraint( (AliITSAlignMille2ConstrArray*)cstr);\r
2638       continue;\r
2639     } \r
2640     //\r
2641     if (cstr->GetType() == AliITSAlignMille2Constraint::kTypeMedian) continue; // post type constraint\r
2642     //\r
2643     if (!fUseGlobalDelta) continue; // mean/med constraints must be applied to global deltas\r
2644     // apply constraint on the mean's before the fit\r
2645     int imd = cstr->GetModuleID();\r
2646     if (imd>=0) {\r
2647       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2648       UInt_t pattern = 0;\r
2649       for (int ipar=mod->GetNParTot();ipar--;) {\r
2650         if (!cstr->IncludesParam(ipar)) continue;\r
2651         if (mod->GetParOffset(ipar)<0) continue; // parameter is not in the explicit fit -> post constraint\r
2652         pattern |= 0x1<<ipar;\r
2653         cstr->SetApplied(ipar);\r
2654       }\r
2655       ConstrainModuleSubUnits(imd,cstr->GetValue(),pattern);\r
2656       //\r
2657     }\r
2658     else if (!PseudoParentsAllowed()) {\r
2659       ConstrainOrphans(cstr->GetValue(),(UInt_t)cstr->GetPattern());\r
2660       cstr->SetApplied(-1);\r
2661     }\r
2662   }\r
2663 }\r
2664 \r
2665 //________________________________________________________________________________________________________\r
2666 void AliITSAlignMille2::ApplyPostConstraints()\r
2667 {\r
2668   // apply constraints which can be imposed after the fit\r
2669   int nconstr = GetNConstraints();\r
2670   Bool_t convGlo      = kFALSE;\r
2671   // check if there is something to do\r
2672   int ntodo = 0;\r
2673   for (int i=0;i<nconstr;i++) {\r
2674     AliITSAlignMille2Constraint* cstr = GetConstraint(i);\r
2675     if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) continue;\r
2676     if (cstr->GetRemainingPattern() == 0) continue;\r
2677     ntodo++;\r
2678   }\r
2679   if (!ntodo) return;\r
2680   //\r
2681   if (!fUseGlobalDelta) { // need to convert to global params\r
2682     ConvertParamsToGlobal();\r
2683     convGlo = kTRUE;\r
2684   }\r
2685   //\r
2686   for (int i=0;i<nconstr;i++) {\r
2687     AliITSAlignMille2Constraint* cstr = GetConstraint(i);\r
2688     if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) continue;\r
2689     //\r
2690     int imd = cstr->GetModuleID();\r
2691     //\r
2692     if (imd>=0) {\r
2693       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2694       UInt_t pattern = 0;\r
2695       for (int ipar=mod->GetNParTot();ipar--;) {\r
2696         if (cstr->IsApplied(ipar))      continue;\r
2697         if (!cstr->IncludesParam(ipar)) continue;\r
2698         if (!mod->IsFreeDOF(ipar))      continue; // parameter is fixed, will not apply constraint\r
2699         pattern |= 0x1<<ipar;\r
2700         cstr->SetApplied(ipar);\r
2701       }\r
2702       if (pattern) PostConstrainModuleSubUnits(cstr->GetType(),cstr->GetModuleID(),cstr->GetValue(),pattern);\r
2703       //\r
2704     }\r
2705     else if (PseudoParentsAllowed()) {\r
2706       UInt_t pattern = (UInt_t)cstr->GetRemainingPattern();\r
2707       PostConstrainOrphans(cstr->GetType(),cstr->GetValue(),pattern);\r
2708       cstr->SetApplied(-1);\r
2709     }\r
2710   }\r
2711   // if there was a conversion, rewind it\r
2712   if (convGlo) ConvertParamsToLocal();\r
2713   // \r
2714 }\r
2715 \r
2716 //________________________________________________________________________________________________________\r
2717 void AliITSAlignMille2::ConstrainModuleSubUnits(Int_t idm, Double_t val, UInt_t pattern)\r
2718 {\r
2719   // require that sum of modifications for the childs of this module is = val, i.e.\r
2720   // the internal corrections moves the module as a whole by fixed value (0 by default).\r
2721   // pattern is the bit pattern for the parameters to constrain\r
2722   //\r
2723   //\r
2724   AliITSAlignMille2Module* mod = GetMilleModule(idm);\r
2725   //\r
2726   for (int ip=0;ip<kNParCh;ip++) {\r
2727     if ( !((pattern>>ip)&0x1) /*|| !parent->IsFreeDOF(ip)*/) continue;\r
2728     ResetLocalEquation();\r
2729     int nadd = 0;\r
2730     for (int ich=mod->GetNChildren();ich--;) {\r
2731       int idpar = ((AliITSAlignMille2Module*)mod->GetChild(ich))->GetParOffset(ip);\r
2732       if (idpar<0) continue;\r
2733       fGlobalDerivatives[idpar] = 1.0;\r
2734       nadd++;\r
2735     }\r
2736     //\r
2737     if (nadd>0) {\r
2738       AddConstraint(fGlobalDerivatives,val);\r
2739       AliInfo(Form("Constrained param %d for %d submodules of module #%d: %s",ip,nadd,idm,mod->GetName()));\r
2740     }\r
2741   }\r
2742   //\r
2743 }\r
2744 \r
2745 //________________________________________________________________________________________________________\r
2746 void AliITSAlignMille2::ConstrainOrphans(Double_t val, UInt_t pattern)\r
2747 {\r
2748   // require that median of the modifications for the supermodules which have no parents is = val, i.e.\r
2749   // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.\r
2750   // pattern is the bit pattern for the parameters to constrain\r
2751   //\r
2752   for (int ip=0;ip<kNParCh;ip++) {\r
2753     //\r
2754     if ( !((pattern>>ip)&0x1) ) continue;\r
2755     ResetLocalEquation();\r
2756     int nadd = 0;\r
2757     for (int imd=fNModules;imd--;) {\r
2758       AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2759       if (mod->GetParent()) continue; // this is not an orphan\r
2760       int idpar = mod->GetParOffset(ip);\r
2761       if (idpar<0) continue;\r
2762       fGlobalDerivatives[idpar] = 1.0;\r
2763       nadd++;\r
2764     }\r
2765     if (nadd>0) {\r
2766       AddConstraint(fGlobalDerivatives,val);\r
2767       AliInfo(Form("Constrained param %d for %d orphan modules",ip,nadd));\r
2768     }\r
2769   }\r
2770   //\r
2771   //\r
2772 }\r
2773 \r
2774 //________________________________________________________________________________________________________\r
2775 void AliITSAlignMille2::PostConstrainModuleSubUnits(Int_t type,Int_t idm, Double_t val, UInt_t pattern)\r
2776 {\r
2777   // require that median or mean of the modifications for the childs of this module is = val, i.e.\r
2778   // the internal corrections moves the module as a whole by fixed value (0 by default) \r
2779   // module the outliers.\r
2780   // pattern is the bit pattern for the parameters to constrain\r
2781   // The difference between the mean and the median will be transfered to the parent\r
2782   //\r
2783   AliITSAlignMille2Module* parent = GetMilleModule(idm);\r
2784   int nc = parent->GetNChildren();\r
2785   //\r
2786   double *tmpArr = new double[nc]; \r
2787   //\r
2788   for (int ip=0;ip<kNParCh;ip++) {\r
2789     int npc = 0;\r
2790     if ( !((pattern>>ip)&0x1) || !parent->IsFreeDOF(ip)) continue;\r
2791     // compute the mean and median of the deltas\r
2792     int nfree = 0;\r
2793     for (int ich=nc;ich--;) {\r
2794       AliITSAlignMille2Module* child = parent->GetChild(ich);\r
2795       //      if (!child->IsFreeDOF(ip)) continue; \r
2796       tmpArr[nfree++] = child->GetParVal(ip);\r
2797     }\r
2798     double median=0,mean=0;\r
2799     for (int ic0=0;ic0<nfree;ic0++) {// order the deltas \r
2800       mean += tmpArr[ic0];\r
2801       for (int ic1=ic0+1;ic1<nfree;ic1++) \r
2802         if (tmpArr[ic0]>tmpArr[ic1]) {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;}\r
2803     }\r
2804     //\r
2805     int kmed = nfree/2;\r
2806     median = (tmpArr[kmed]+tmpArr[nfree-kmed-1])/2.;\r
2807     if (nfree>0) mean /= nfree;\r
2808     //\r
2809     double shift = val - (type==AliITSAlignMille2Constraint::kTypeMean ? mean : median);\r
2810     //\r
2811     for (int ich=nc;ich--;) {\r
2812       AliITSAlignMille2Module* child = parent->GetChild(ich);\r
2813       //    if (!child->IsFreeDOF(ip)) continue; \r
2814       child->SetParVal(ip, child->GetParVal(ip) + shift);\r
2815       npc++;\r
2816     }\r
2817     //\r
2818     parent->SetParVal(ip, parent->GetParVal(ip) - shift);\r
2819     AliInfo(Form("%s constraint: added %f shift to param[%d] of %d children of module %d: %s",\r
2820                  type==AliITSAlignMille2Constraint::kTypeMean ? "MEAN" : "MEDIAN",shift,\r
2821                  ip,npc,idm,parent->GetName()));\r
2822   }\r
2823   delete[] tmpArr;  \r
2824   //\r
2825   //\r
2826 }\r
2827 \r
2828 //________________________________________________________________________________________________________\r
2829 void AliITSAlignMille2::PostConstrainOrphans(Int_t type,Double_t val, UInt_t pattern)\r
2830 {\r
2831   // require that median or mean of modifications for the supermodules which have no parents is = val, i.e.\r
2832   // the corrections moves the whole setup by fixed value (0 by default).\r
2833   // pattern is the bit pattern for the parameters to constrain\r
2834   //\r
2835   int nc = fNModules;\r
2836   //\r
2837   int norph = 0;\r
2838   for (int ich=nc;ich--;) if (!GetMilleModule(ich)->GetParent()) norph ++;\r
2839   if (!norph) return;\r
2840   double *tmpArr = new double[norph]; \r
2841   //\r
2842   for (int ip=0;ip<kNParCh;ip++) {\r
2843     int npc = 0;\r
2844     if ( !((pattern>>ip)&0x1)) continue;\r
2845     // compute the mean and median of the deltas\r
2846     int nfree = 0;\r
2847     for (int ich=nc;ich--;) {\r
2848       AliITSAlignMille2Module* child = GetMilleModule(ich);\r
2849       //      if (child->GetParent() || !child->IsFreeDOF(ip)) continue; \r
2850       if (child->GetParent()) continue; \r
2851       tmpArr[nfree++] = child->GetParVal(ip);\r
2852     }\r
2853     double median=0,mean=0;\r
2854     for (int ic0=0;ic0<nfree;ic0++) {// order the deltas \r
2855       mean += tmpArr[ic0];\r
2856       for (int ic1=ic0+1;ic1<nfree;ic1++) \r
2857         if (tmpArr[ic0]>tmpArr[ic1]) {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;}\r
2858     }\r
2859     //\r
2860     int kmed = nfree/2;\r
2861     median = (tmpArr[kmed]+tmpArr[nfree-kmed-1])/2.;\r
2862     if (nfree>0) mean /= nfree;\r
2863     //\r
2864     double shift = val - (type==AliITSAlignMille2Constraint::kTypeMean ? mean : median);\r
2865     //\r
2866     for (int ich=nc;ich--;) {\r
2867       AliITSAlignMille2Module* child = GetMilleModule(ich);\r
2868       //      if (child->GetParent() || !child->IsFreeDOF(ip)) continue; \r
2869       if (child->GetParent()) continue; \r
2870       child->SetParVal(ip, child->GetParVal(ip) + shift);\r
2871       npc++;\r
2872     }\r
2873     //\r
2874     AliInfo(Form("%s constraint: added %f shift to param[%d] of %d orphan modules",\r
2875                  type==AliITSAlignMille2Constraint::kTypeMean ? "MEAN" : "MEDIAN",shift,\r
2876                  ip,npc));\r
2877   }\r
2878   delete[] tmpArr;  \r
2879   //\r
2880 }\r
2881 \r
2882 //________________________________________________________________________________________________________\r
2883 Bool_t AliITSAlignMille2::IsParModConstrained(const AliITSAlignMille2Module* mod,Int_t par, Bool_t &meanmed, Bool_t &gaussian) const\r
2884 {\r
2885   // check if par of the module participates in some constraint, and set the flag for their types\r
2886   meanmed = gaussian = kFALSE;\r
2887   //\r
2888   if ( mod->IsParConstrained(par) ) gaussian = kTRUE;     // direct constraint on this param\r
2889   //\r
2890   for (int icstr=GetNConstraints();icstr--;) {\r
2891     AliITSAlignMille2Constraint* cstr = GetConstraint(icstr);\r
2892     //\r
2893     if (!cstr->IncludesModPar(mod,par)) continue;\r
2894     if (cstr->GetType()==AliITSAlignMille2ConstrArray::kTypeGaussian) gaussian = kTRUE;\r
2895     else meanmed = kTRUE;\r
2896     //\r
2897     if (meanmed && gaussian) break; // no sense to check further\r
2898   }\r
2899   //\r
2900   return meanmed||gaussian;\r
2901 }\r
2902 \r
2903 //________________________________________________________________________________________________________\r
2904 Bool_t AliITSAlignMille2::IsParModFamilyVaried(const AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const\r
2905 {\r
2906   // check if parameter par is varied for this module or its children up to the level depth\r
2907   if (depth<0) return kFALSE;\r
2908   if (mod->GetParOffset(par)>=0) return kTRUE;\r
2909   for (int icld=mod->GetNChildren();icld--;) {\r
2910     AliITSAlignMille2Module* child = mod->GetChild(icld);\r
2911     if (IsParModFamilyVaried(child, par, depth-1)) return kTRUE;\r
2912   }\r
2913   return kFALSE;\r
2914   //\r
2915 }\r
2916 \r
2917 /*\r
2918 //________________________________________________________________________________________________________\r
2919 Bool_t AliITSAlignMille2::IsParFamilyFree(AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const\r
2920 {\r
2921   // check if parameter par is varied and is not subjected to gaussian constraint for the children up to the level depth\r
2922   if (depth<0) return kTRUE;\r
2923   for (int icld=mod->GetNChildren();icld--;) {\r
2924     AliITSAlignMille2Module* child = mod->GetChild(icld);\r
2925     //if (child->GetParOffset(par)<0) continue;                  // fixed\r
2926     Bool_t cstMM=kFALSE,cstGS=kFALSE;\r
2927     // does this child have gaussian constraint ?\r
2928     if (!IsParModConstrained(child,par,cstMM,cstGS) || !cstGS ) return kTRUE;\r
2929     // check its children\r
2930     if (!IsParFamilyFree(child,par,depth-1)) return kTRUE;\r
2931   }\r
2932   return kFALSE;\r
2933   //\r
2934 }\r
2935 */\r
2936 \r
2937 //________________________________________________________________________________________________________\r
2938 Bool_t AliITSAlignMille2::IsParFamilyFree(const AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const\r
2939 {\r
2940   // check if parameter par is varied and is not subjected to gaussian constraint for the children up to the level depth\r
2941   if (depth<0) return kFALSE;\r
2942   for (int icld=mod->GetNChildren();icld--;) {\r
2943     AliITSAlignMille2Module* child = mod->GetChild(icld);\r
2944     //if (child->GetParOffset(par)<0) continue;                  // fixed\r
2945     Bool_t cstMM=kFALSE,cstGS=kFALSE;\r
2946     // does this child have gaussian constraint ?\r
2947     if (!IsParModConstrained(child,par,cstMM,cstGS) || !cstGS ) return kTRUE;\r
2948     // check its children\r
2949     if (IsParFamilyFree(child,par,depth-1)) return kTRUE;\r
2950   }\r
2951   return kFALSE;\r
2952   //\r
2953 }\r
2954 \r
2955 //________________________________________________________________________________________________________\r
2956 Double_t AliITSAlignMille2::GetTDriftSDD() const \r
2957 {\r
2958   // obtain drift time corrected for t0\r
2959   double t = fCluster.GetDriftTime();\r
2960   return t - fDriftTime0[ fCluster.GetUniqueID() ];\r
2961 }\r
2962 \r
2963 //________________________________________________________________________________________________________\r
2964 Double_t AliITSAlignMille2::GetVDriftSDD() const \r
2965 {\r
2966   // obtain corrected drift speed\r
2967   return fDriftSpeed[ fCluster.GetUniqueID() ];\r
2968 }\r
2969 \r
2970 //________________________________________________________________________________________________________\r
2971 Bool_t AliITSAlignMille2::FixedOrphans() const\r
2972 {\r
2973   // are there fixed modules with no parent (normally in such a case \r
2974   // the constraints on the orphans should not be applied\r
2975   if (!IsConfigured()) {\r
2976     AliInfo("Still not configured");\r
2977     return kFALSE;\r
2978   }\r
2979   for (int i=0;i<fNModules;i++) {\r
2980     AliITSAlignMille2Module* md = GetMilleModule(i);\r
2981     if (md->GetParent()==0 && md->GetNParFree()==0) return kTRUE;\r
2982   }\r
2983   return kFALSE;\r
2984 }\r
2985 \r
2986 //________________________________________________________________________________________________________\r
2987 void AliITSAlignMille2::ConvertParamsToGlobal()\r
2988 {\r
2989   // convert params in local frame to global one\r
2990   double pars[AliITSAlignMille2Module::kMaxParGeom];\r
2991   for (int imd=fNModules;imd--;) {\r
2992     AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
2993     if (mod->GeomParamsGlobal()) continue;\r
2994     mod->GetGeomParamsGlo(pars);\r
2995     mod->SetParVals(pars,AliITSAlignMille2Module::kMaxParGeom);\r
2996     mod->SetGeomParamsGlobal(kTRUE);\r
2997   }\r
2998 }\r
2999 \r
3000 //________________________________________________________________________________________________________\r
3001 void AliITSAlignMille2::ConvertParamsToLocal()\r
3002 {\r
3003   // convert params in global frame to local one\r
3004   double pars[AliITSAlignMille2Module::kMaxParGeom];\r
3005   for (int imd=fNModules;imd--;) {\r
3006     AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
3007     if (!mod->GeomParamsGlobal()) continue;\r
3008     mod->GetGeomParamsLoc(pars);\r
3009     mod->SetParVals(pars,AliITSAlignMille2Module::kMaxParGeom);\r
3010     mod->SetGeomParamsGlobal(kFALSE);\r
3011   }\r
3012 }\r
3013 \r