]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ITS/AliITSAlignMille2.cxx
Added ITS Alignment interface to MillePede2 and related supermodule class
[u/mrichter/AliRoot.git] / ITS / AliITSAlignMille2.cxx
1 /**************************************************************************
2  * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id: AliITSAlignMille.cxx 25025 2008-04-09 20:50:08Z masera $ */
17
18 //-----------------------------------------------------------------------------
19 /// \class AliITSAlignMille
20 /// Alignment class fro the ALICE ITS detector
21 ///
22 /// ITS specific alignment class which interface to AliMillepede.   
23 /// For each track ProcessTrack calculates the local and global derivatives
24 /// at each hit and fill the corresponding local equations. Provide methods for
25 /// fixing or constraining detection elements for best results. 
26 ///
27 /// \author M. Lunardon (thanks to J. Castillo)
28 //-----------------------------------------------------------------------------
29
30 #include <TF1.h>
31 #include <TFile.h>
32 #include <TClonesArray.h>
33 #include <TGraph.h>
34 #include <TGeoMatrix.h>
35 #include <TMath.h>
36 #include <TGraphErrors.h>
37 #include <TVirtualFitter.h>
38
39 #include "AliITSAlignMille2.h"
40 #include "AliITSgeomTGeo.h"
41 #include "AliGeomManager.h"
42 #include "AliMillePede2.h"
43 #include "AliTrackPointArray.h"
44 #include "AliAlignObjParams.h"
45 #include "AliLog.h"
46 #include "TSystem.h"  // come si fa?
47 #include "AliTrackFitterRieman.h"
48
49 /// \cond CLASSIMP
50 ClassImp(AliITSAlignMille2)
51 /// \endcond
52
53 AliITSAlignMille2* AliITSAlignMille2::fgInstance = 0;  
54 Int_t              AliITSAlignMille2::fgInstanceID = 0;
55
56 AliITSAlignMille2::AliITSAlignMille2(const Char_t *configFilename, Bool_t initmille) 
57 : TObject(),
58   fMillepede(0),
59   fStartFac(16.), 
60   fResCutInitial(100.), 
61   fResCut(100.),
62   fNGlobal(0),
63   fNLocal(4),
64   fNStdDev(3),
65   fIsMilleInit(kFALSE),
66   fSensorsIn(kFALSE),
67   fParSigTranslations(0.0100),
68   fParSigRotations(0.1),
69 //
70   fCurrentModule(0),
71   fTrack(0),
72   fCluster(),
73   fGlobalDerivatives(0), 
74 //
75   fMinNPtsPerTrack(3),
76   fInitTrackParamsMeth(1),
77   fTotBadLocEqPoints(0),
78   fRieman(0),
79   //
80   fUseGlobalDelta(kFALSE),
81   fRequirePoints(kFALSE),
82   fTempExcludedModule(-1),
83   //
84   fGeometryFileName("geometry.root"),
85   fPreAlignmentFileName(""),
86   fGeoManager(0),
87   fIsConfigured(kFALSE),
88   fPreAlignQF(0),
89 //
90   fPrealignment(0),
91   fMilleModule(2),
92   fSuperModule(2),
93   fNModules(0),
94   fNSuperModules(0),
95   fUsePreAlignment(kFALSE),
96   fUseSortedTracks(kTRUE),
97   fBOn(kFALSE),
98   fBField(0.0),
99   fBug(0)
100 {
101   /// main constructor that takes input from configuration file
102   //  
103   fMillepede = new AliMillePede2();
104   for (int i=3;i--;) fSigmaFactor[i] = 1.0;
105   //
106   // new RS
107   for (Int_t i=0; i<6; i++) {
108     fNReqLayUp[i]=0;
109     fNReqLayDown[i]=0;
110     fNReqLay[i]=0;
111   }
112   for (Int_t i=0; i<3; i++) {
113     fNReqDetUp[i]=0;
114     fNReqDetDown[i]=0;
115     fNReqDet[i]=0;
116   }
117   //
118   Int_t lc=LoadConfig(configFilename);
119   if (lc) {
120     AliInfo(Form("Error %d loading configuration from %s",lc,configFilename));
121   }
122   else {    
123     fIsConfigured=kTRUE;
124     if (initmille) {
125       AliInfo(Form("Initializing Millepede with %d gpar, %d lpar and %d stddev ...",fNGlobal, fNLocal, fNStdDev));
126       Init(fNGlobal, fNLocal, fNStdDev);      
127       ResetLocalEquation();    
128       AliInfo("Parameters initialized to zero");
129     }
130     else {
131       AliInfo("Millepede has not been initialized ... ");
132     }
133   }
134   //
135   fgInstance = this;
136   fgInstanceID++;
137   //
138 }
139
140 AliITSAlignMille2::~AliITSAlignMille2() {
141   /// Destructor
142   if (fMillepede)         delete fMillepede;
143   if (fGlobalDerivatives) delete[] fGlobalDerivatives;
144   if (fRieman)            delete fRieman;
145   if (fPrealignment)      delete fPrealignment;
146   fMilleModule.Delete();
147   fSuperModule.Delete();
148   if (--fgInstanceID==0) fgInstance = 0;
149 }
150
151 ///////////////////////////////////////////////////////////////////////
152
153 Int_t AliITSAlignMille2::LoadConfig(const Char_t *cfile) {
154   /// return 0 if success
155   ///        1 if error in module index or voluid
156   
157   FILE *pfc=fopen(cfile,"r");
158   if (!pfc) return -1;
159   
160   Char_t st[200],st2[200];
161   Char_t tmp[100];
162   Int_t idx,itx,ity,itz,ith,ips,iph;
163   Float_t f1,f2,f3;
164   UShort_t voluid;
165   Int_t nmod=0;
166   //
167   while (fgets(st,200,pfc)) {
168     //
169     for (int i=0; i<int(strlen(st)); i++) if (st[i]=='#') st[i]=0; // skip comments
170     //
171     if (strstr(st,"GEOMETRY_FILE")) {
172       sscanf(st,"%s %s",tmp,st2);
173       if (gSystem->AccessPathName(st2)) { AliInfo("*** WARNING! *** geometry file not found! "); return -1;}  
174       fGeometryFileName=st2;
175       InitGeometry();
176     }
177     //
178     if (strstr(st,"PREALIGNMENT_FILE")) {
179       sscanf(st,"%s %s",tmp,st2);
180       if (gSystem->AccessPathName(st2)) { AliInfo("*** WARNING! *** prealignment file not found! "); return -1;}  
181       fPreAlignmentFileName=st2;
182       itx=ApplyToGeometry();
183       if (itx) { AliInfo(Form("*** WARNING! *** error %d reading prealignment file! ",itx)); return -6;}
184     }
185     //
186     if (strstr(st,"SUPERMODULE_FILE")) {
187       sscanf(st,"%s %s",tmp,st2);
188       if (gSystem->AccessPathName(st2)) { AliInfo("*** WARNING! *** supermodule file not found! "); return -1;}  
189       if (LoadSuperModuleFile(st2)) return -1;
190     }
191     //
192     if (strstr(st,"SET_B_FIELD")) {
193       sscanf(st,"%s %f",tmp,&f1);
194       if (f1>0) {
195         fBField = f1;
196         fBOn = kTRUE;
197         fNLocal = 5; // helices
198         fRieman = new AliTrackFitterRieman();
199       }  
200       else {
201         fBField = 0.0;
202         fBOn = kFALSE;
203         fNLocal = 4;
204       }
205     }
206     //
207     if (strstr(st,"SET_MINPNT_TRA")) {
208       sscanf(st,"%s %d",tmp,&idx);
209       fMinNPtsPerTrack=idx;
210     }
211     //
212     if (strstr(st,"SET_PARSIG_TRA")) {
213       sscanf(st,"%s %f",tmp,&f1);
214       fParSigTranslations=f1;
215     }
216     //
217     if (strstr(st,"SET_PARSIG_ROT")) {
218       sscanf(st,"%s %f",tmp,&f1);
219       fParSigRotations=f1;
220     }
221     //
222     if (strstr(st,"SET_NSTDDEV")) {
223       sscanf(st,"%s %d",tmp,&idx);
224       fNStdDev=idx;
225     }
226     //
227     if (strstr(st,"SET_RESCUT_INIT")) {
228       sscanf(st,"%s %f",tmp,&f1);
229       fResCutInitial=f1;
230     }
231     //
232     if (strstr(st,"SET_RESCUT_OTHER")) {
233       sscanf(st,"%s %f",tmp,&f1);
234       fResCut=f1;
235     }
236     //
237     if (strstr(st,"SET_LOCALSIGMAFACTOR")) {
238       f1=f2=f3=0;
239       sscanf(st,"%s %f %f %f",tmp,&f1,&f2,&f3);
240       if (f1>0) fSigmaFactor[0] = f1;
241       if (f2>0) fSigmaFactor[1] = f2; else fSigmaFactor[1]=fSigmaFactor[0];
242       if (f3>0) fSigmaFactor[2] = f3; else fSigmaFactor[2]=fSigmaFactor[1];
243     }
244     //
245     if (strstr(st,"SET_STARTFAC")) {
246       sscanf(st,"%s %f",tmp,&f1);
247       fStartFac=f1;
248     }
249     //
250     // >> RS
251     if (strstr(st,"REQUIRE_POINT")) {
252       // syntax:   REQUIRE_POINT where ndet updw nreqpts
253       //    where = LAYER or DETECTOR
254       //    ndet = detector number: 1-6 for LAYER and 1-3 for DETECTOR (SPD=1, SDD=2, SSD=3)
255       //    updw = 1 for Y>0, -1 for Y<0, 0 if not specified
256       //    nreqpts = minimum number of points of that type
257       sscanf(st,"%s %s %d %d %d",tmp,st2,&itx,&ity,&itz);
258       itx--;
259       if (strstr(st2,"LAYER")) {
260         if (itx<0 || itx>5) return -7;
261         if (ity>0) fNReqLayUp[itx]=itz;
262         else if (ity<0) fNReqLayDown[itx]=itz;
263         else fNReqLay[itx]=itz;
264         fRequirePoints=kTRUE;
265       }
266       else if (strstr(st2,"DETECTOR")) { // DETECTOR
267         if (itx<0 || itx>2) return -7;
268         if (ity>0) fNReqDetUp[itx]=itz;
269         else if (ity<0) fNReqDetDown[itx]=itz;
270         else fNReqDet[itx]=itz; 
271         fRequirePoints=kTRUE;
272       }
273     }
274     // << RS
275     
276     //
277     if (strstr(st,"MODULE_INDEX") || strstr(st,"MODULE_VOLUID")) { 
278       f1=f2=f3=0;
279       sscanf(st,"%s %d %d %d %d %d %d %d %f %f %f",tmp,&idx,&itx,&ity,&itz,&iph,&ith,&ips,&f1,&f2,&f3);
280       //
281       if (idx<=kMaxITSSensID) voluid=GetModuleVolumeID(idx);
282       else voluid = UShort_t(idx);
283       //
284       if (voluid>=kMinITSSupeModuleID) { // custom supermodule
285         int ism=-1;
286         for (int j=0; j<fNSuperModules; j++) if (voluid==GetSuperModule(j)->GetVolumeID()) ism=j;
287         if (ism<0) return -1; // bad volid
288         fMilleModule.AddAtAndExpand(new AliITSAlignMille2Module(*GetSuperModule(ism)),nmod);
289         // >> RS
290 //      if (f1>0) {
291 //        for (int kk=0; kk<GetMilleModule(nmod)->GetNSensitiveVolumes(); kk++) {
292 //          idx=AliITSAlignMille2Module::GetIndexFromVolumeID(GetMilleModule(nmod)->GetSensitiveVolumeVolumeID()[kk]);
293 //          if (idx>=0) fSensVolSigmaXfactor[idx]=f1;
294 //        }
295 //      }
296 //      if (f2>0) {
297 //        for (int kk=0; kk<GetMilleModule(nmod)->GetNSensitiveVolumes(); kk++) {
298 //          idx=AliITSAlignMille2Module::GetIndexFromVolumeID(GetMilleModule(nmod)->GetSensitiveVolumeVolumeID()[kk]);
299 //          if (idx>=0) fSensVolSigmaZfactor[idx]=f2;
300 //        }
301 //      }
302         // << RS
303       }
304       else if (idx<=kMaxITSSensVID) {
305         fMilleModule.AddAtAndExpand(new AliITSAlignMille2Module(voluid),nmod);
306         AliITSAlignMille2Module* md = (AliITSAlignMille2Module*) fMilleModule[nmod];
307         fSensorsIn = kTRUE;
308         md->SetSensorsProvided();
309       }
310       else return -1;  // bad volid
311       //
312       AliITSAlignMille2Module* mod = GetMilleModule(nmod);
313       mod->SetFreeDOF(kDOFTX,itx!=0);
314       mod->SetFreeDOF(kDOFTY,ity!=0);
315       mod->SetFreeDOF(kDOFTZ,itz!=0);
316       mod->SetFreeDOF(kDOFPH,iph!=0);
317       mod->SetFreeDOF(kDOFTH,ith!=0);
318       mod->SetFreeDOF(kDOFPS,ips!=0);
319       //
320       mod->SetUniqueID(nmod);
321       if (f1>0) mod->SetSigmaXFactor(f1);
322       if (f2>0) mod->SetSigmaYFactor(f2); else mod->SetSigmaYFactor(mod->GetSigmaXFactor());
323       if (f3>0) mod->SetSigmaZFactor(f3); else mod->SetSigmaZFactor(mod->GetSigmaYFactor());
324       nmod++;
325     }
326     //
327   } // end while
328   //
329   fNModules = nmod;
330   fNGlobal = fNModules*kNParCh;
331   //
332   fclose(pfc);
333   //
334   // set parent/child relationship for modules to align
335   printf("Setting parent/child relationships\n");
336   //
337   for (int ipar=0;ipar<nmod;ipar++) {
338     AliITSAlignMille2Module* parent = GetMilleModule(ipar);
339     if (parent->GetIndex()<=kMaxITSSensID) continue; // sensor cannot be a parent
340     //
341     for (int icld=0;icld<nmod;icld++) {
342       if (icld==ipar) continue;
343       AliITSAlignMille2Module* child = GetMilleModule(icld);
344       if (!child->BelongsTo(parent)) continue;
345       //
346       AliITSAlignMille2Module* parOld = child->GetParent();
347       if (parOld && parOld->GetNSensitiveVolumes()<parent->GetNSensitiveVolumes()) continue; // parOld is closer
348       child->SetParent(parent);
349     }
350     //
351   }
352   //
353   // reorder the modules in such a way that parents come first
354   for (int icld=0;icld<nmod;icld++) {
355     AliITSAlignMille2Module* child = GetMilleModule(icld);
356     if (!child->GetParent()) continue;
357     //
358     for (int icld=0;icld<nmod;icld++) {
359       AliITSAlignMille2Module* child = GetMilleModule(icld);
360       AliITSAlignMille2Module* parent = child->GetParent();
361       if (!parent || parent->GetUniqueID()<child->GetUniqueID()) continue;
362       // swap
363       fMilleModule[icld] = parent;
364       fMilleModule[parent->GetUniqueID()] = child;
365       child->SetUniqueID(parent->GetUniqueID());
366       parent->SetUniqueID(icld);
367     }
368   }
369   //
370   // go over the child->parent chain and mark modules with explicitly provided sensors
371   for (int icld=nmod;icld--;) {
372     AliITSAlignMille2Module* child = GetMilleModule(icld);
373     AliITSAlignMille2Module* parent = child->GetParent();
374     if (!parent) continue;
375     parent->SetSensorsProvided( child->AreSensorsProvided() );
376     if (!parent->AreSensorsProvided()) continue;
377     // suppress unused sensors
378     for (int isn=0;isn<parent->GetNSensitiveVolumes();isn++) {
379       int snVID = parent->GetSensVolVolumeID(isn);
380       // check if this sensor is explicitly requested
381       for (int imd=nmod;imd--;) if (GetMilleModule(imd)->GetVolumeID() == snVID) {snVID = -1; break;}
382       //
383       if (snVID==-1) continue; // found this sensor, do nothing
384       //
385       // otherwise, remove this sensor from the module list
386       AliInfo(Form("Removing sensor %d from %s",snVID,parent->GetName()));
387       parent->DelSensitiveVolume(isn--);
388     }
389   }
390   //
391   fGlobalDerivatives = new Double_t[fNGlobal];
392   memset(fGlobalDerivatives,0,fNGlobal*sizeof(Double_t));
393   //
394   return 0;
395 }
396
397
398 void AliITSAlignMille2::SetRequiredPoint(Char_t* where, Int_t ndet, Int_t updw, Int_t nreqpts) 
399 {
400   // set minimum number of points in specific detector or layer
401   // where = LAYER or DETECTOR
402   // ndet = detector number: 1-6 for LAYER and 1-3 for DETECTOR (SPD=1, SDD=2, SSD=3)
403   // updw = 1 for Y>0, -1 for Y<0, 0 if not specified
404   // nreqpts = minimum number of points of that type
405   ndet--;
406   if (strstr(where,"LAYER")) {
407     if (ndet<0 || ndet>5) return;
408     if (updw>0) fNReqLayUp[ndet]=nreqpts;
409     else if (updw<0) fNReqLayDown[ndet]=nreqpts;
410     else fNReqLay[ndet]=nreqpts;
411     fRequirePoints=kTRUE;
412   }
413   else if (strstr(where,"DETECTOR")) {
414     if (ndet<0 || ndet>2) return;
415     if (updw>0) fNReqDetUp[ndet]=nreqpts;
416     else if (updw<0) fNReqDetDown[ndet]=nreqpts;
417     else fNReqDet[ndet]=nreqpts;        
418     fRequirePoints=kTRUE;
419   }
420 }
421
422
423 Int_t AliITSAlignMille2::GetModuleIndex(const Char_t *symname) {
424   /// index from symname
425   if (!symname) return -1;
426   for (Int_t i=0;i<=kMaxITSSensID; i++) {
427     if (!strcmp(symname,AliITSgeomTGeo::GetSymName(i))) return i;
428   }
429   return -1;
430 }
431
432 Int_t AliITSAlignMille2::GetModuleIndex(UShort_t voluid) {
433   /// index from volume ID
434   AliGeomManager::ELayerID lay = AliGeomManager::VolUIDToLayer(voluid);
435   if (lay<1|| lay>6) return -1;
436   Int_t idx=Int_t(voluid)-2048*lay;
437   if (idx>=AliGeomManager::LayerSize(lay)) return -1;
438   for (Int_t ilay=1; ilay<lay; ilay++) 
439     idx += AliGeomManager::LayerSize(ilay);
440   return idx;
441 }
442
443 UShort_t AliITSAlignMille2::GetModuleVolumeID(const Char_t *symname) {
444   /// volume ID from symname
445   /// works for sensitive volumes only
446   if (!symname) return 0;
447
448   for (UShort_t voluid=2000; voluid<13300; voluid++) {
449     Int_t modId;
450     AliGeomManager::ELayerID layerId = AliGeomManager::VolUIDToLayer(voluid,modId);
451     if (layerId>0 && layerId<7 && modId>=0 && modId<AliGeomManager::LayerSize(layerId)) {
452       if (!strcmp(symname,AliGeomManager::SymName(layerId,modId))) return voluid;
453     }
454   }
455
456   return 0;
457 }
458
459 UShort_t AliITSAlignMille2::GetModuleVolumeID(Int_t index) {
460   /// volume ID from index
461   if (index<0) return 0;
462   if (index<2198)
463     return GetModuleVolumeID(AliITSgeomTGeo::GetSymName(index));
464   else {
465     for (int i=0; i<fNSuperModules; i++) {
466       if (GetSuperModule(i)->GetIndex()==index) return GetSuperModule(i)->GetVolumeID();
467     }
468   }
469   return 0;
470 }
471
472 void AliITSAlignMille2::InitGeometry() {
473   /// initialize geometry
474   AliGeomManager::LoadGeometry(fGeometryFileName.Data());
475   fGeoManager = AliGeomManager::GetGeometry();
476   if (!fGeoManager) {
477     AliInfo("Couldn't initialize geometry");
478     return;
479   }
480 }
481
482 void AliITSAlignMille2::Init(Int_t nGlobal,  /* number of global paramers */
483                            Int_t nLocal,   /* number of local parameters */
484                            Int_t nStdDev   /* std dev cut */ )
485 {
486   /// Initialization of AliMillepede. Fix parameters, define constraints ...
487   fMillepede->InitMille(nGlobal,nLocal,nStdDev,fResCut,fResCutInitial);
488   fIsMilleInit = kTRUE;
489   
490   /// Fix non free parameters
491   for (Int_t i=0; i<fNModules; i++) {
492     for (Int_t j=0; j<kNParCh; j++) {
493       if (!GetMilleModule(i)->IsFreeDOF(j)) FixParameter(i*kNParCh+j,0.0);
494       else {
495         // pepopepo: da verificare il settaggio delle sigma, ma forse va bene...
496         Double_t parsig=0;
497         if (j<3) parsig = fParSigTranslations; // translations (0.0100 cm)
498         else     parsig = fParSigRotations; // rotations (1/10 deg)
499         FixParameter(i*kNParCh+j,parsig);
500       }
501     }    
502   }
503   //
504   // Set iterations
505   if (fStartFac>1) fMillepede->SetIterations(fStartFac);          
506 }
507
508
509 void AliITSAlignMille2::AddConstraint(Double_t *par, Double_t value) {
510   /// Constrain equation defined by par to value
511   if (!fIsMilleInit) {
512     AliInfo("Millepede has not been initialized!");
513     return;
514   }
515   fMillepede->SetGlobalConstraint(par, value);
516   AliInfo("Adding constraint");
517 }
518
519 void AliITSAlignMille2::InitGlobalParameters(Double_t *par) {
520   /// Initialize global parameters with par array
521   if (!fIsMilleInit) {
522     AliInfo("Millepede has not been initialized!");
523     return;
524   }
525   fMillepede->SetGlobalParameters(par);
526   AliInfo("Init Global Parameters");
527 }
528  
529 void AliITSAlignMille2::FixParameter(Int_t iPar, Double_t value) {
530   /// Parameter iPar is encourage to vary in [-value;value]. 
531   /// If value == 0, parameter is fixed
532   if (!fIsMilleInit) {
533     AliInfo("Millepede has not been initialized!");
534     return;
535   }
536   fMillepede->SetParSigma(iPar, value);
537   if (value==0) AliInfo(Form("Parameter %i Fixed", iPar));
538 }
539
540 void AliITSAlignMille2::ResetLocalEquation()
541 {
542   /// Reset the derivative vectors
543   for(int i=fNLocal;i--;)  fLocalDerivatives[i] = 0.0;
544   for(int i=fNGlobal;i--;) fGlobalDerivatives[i] = 0.0;
545 }
546
547 Int_t AliITSAlignMille2::ApplyToGeometry() 
548 {
549   // apply starting realignment to ideal geometry
550   //
551   if (!fGeoManager) return -1; 
552   TFile *pref = new TFile(fPreAlignmentFileName.Data());
553   if (!pref->IsOpen()) return -2;
554   fPrealignment = (TClonesArray*)pref->Get("ITSAlignObjs");
555   if (!fPrealignment) return -3;  
556   Int_t nprea = fPrealignment->GetEntriesFast();
557   AliInfo(Form("Array of input misalignments with %d entries",nprea));
558   //
559   for (int ix=0; ix<nprea; ix++) {
560     AliAlignObjParams *preo=(AliAlignObjParams*) fPrealignment->At(ix);
561     Int_t index=AliITSAlignMille2Module::GetIndexFromVolumeID(preo->GetVolUID());
562     if (index>=0) {
563       if (index>=fPreAlignQF.GetSize()) fPreAlignQF.Set(index+10);
564       fPreAlignQF[index] = (int) preo->GetUniqueID()+1;
565     }
566     //TString nms = preo->GetSymName();
567     //if (!nms.Contains("Ladder")) continue; //RRR
568     if (!preo->ApplyToGeometry()) return -4;
569   }
570   //
571   pref->Close();
572   delete pref;
573   //
574   fUsePreAlignment = kTRUE;
575   return 0;
576 }
577
578 Int_t AliITSAlignMille2::GetPreAlignmentQualityFactor(Int_t index) const
579 {
580   if (!fUsePreAlignment || index<0 || index>=fPreAlignQF.GetSize()) return -1;
581   return fPreAlignQF[index]-1;
582 }
583
584 AliTrackPointArray *AliITSAlignMille2::PrepareTrack(const AliTrackPointArray *atp) {
585   /// create a new AliTrackPointArray keeping only defined modules
586   /// move points according to a given prealignment, if any
587   /// sort alitrackpoints w.r.t. global Y direction, if selected
588
589   AliTrackPointArray *atps=NULL;
590   Int_t idx[20];
591   Int_t npts=atp->GetNPoints();
592
593   /// checks if AliTrackPoints belong to defined modules
594   Int_t ngoodpts=0;
595   Int_t intidx[20];
596   
597   for (int j=0; j<npts; j++) {
598     intidx[j] = IsContained(atp->GetVolumeID()[j]);
599     if (intidx[j]>=0) ngoodpts++;
600   }
601   AliDebug(3,Form("Number of points in defined modules: %d",ngoodpts));
602
603   // reject track if not enough points are left
604   if (ngoodpts<fMinNPtsPerTrack) {
605     AliInfo("Track with not enough points!");
606     return NULL;
607   }
608   // >> RS
609   AliTrackPoint p;
610   // check points in specific places
611   if (fRequirePoints) {
612     Int_t nlayup[6],nlaydown[6],nlay[6];
613     Int_t ndetup[3],ndetdown[3],ndet[3];
614     for (Int_t j=0; j<6; j++) {nlayup[j]=0; nlaydown[j]=0; nlay[j]=0;}
615     for (Int_t j=0; j<3; j++) {ndetup[j]=0; ndetdown[j]=0; ndet[j]=0;}
616     
617     for (int i=0; i<npts; i++) {
618       // skip not defined points
619       if (intidx[i]<0) continue;
620       Float_t xx=atp->GetX()[i];
621       Float_t yy=atp->GetY()[i];
622       Float_t r=TMath::Sqrt(xx*xx + yy*yy);
623       int lay=-1;
624       if (r<5) lay=0;
625       else if (r>5 && r<10) lay=1;
626       else if (r>10 && r<18) lay=2;
627       else if (r>18 && r<30) lay=3;
628       else if (r>30 && r<40) lay=4;
629       else if (r>40) lay=5;
630       if (lay<0) continue;
631       int det=lay/2;
632       //printf("Point %d - x=%f  y=%f  R=%f  lay=%d  det=%d\n",i,xx,yy,r,lay,det);
633
634       if (yy>=0.0) { // UP point
635         nlayup[lay]++;
636         nlay[lay]++;
637         ndetup[det]++;
638         ndet[det]++;
639       }
640       else {
641         nlaydown[lay]++;
642         nlay[lay]++;
643         ndetdown[det]++;
644         ndet[det]++;
645       }
646     }
647     
648     // checks minimum values
649     Bool_t isok=kTRUE;
650     for (Int_t j=0; j<6; j++) {
651       if (nlayup[j]<fNReqLayUp[j]) isok=kFALSE; 
652       if (nlaydown[j]<fNReqLayDown[j]) isok=kFALSE; 
653       if (nlay[j]<fNReqLay[j]) isok=kFALSE; 
654     }
655     for (Int_t j=0; j<3; j++) {
656       if (ndetup[j]<fNReqDetUp[j]) isok=kFALSE; 
657       if (ndetdown[j]<fNReqDetDown[j]) isok=kFALSE; 
658       if (ndet[j]<fNReqDet[j]) isok=kFALSE; 
659     }
660     if (!isok) {
661       AliDebug(2,Form("Track does not meet all location point requirements!"));
662       return NULL;
663     }
664   }
665   
666   // << RS
667   // build a new track with (sorted) (prealigned) good points
668   atps=new AliTrackPointArray(ngoodpts);
669
670   for (int i=0; i<npts; i++) idx[i]=i;
671   // sort track if required
672   if (fUseSortedTracks) TMath::Sort(npts,atp->GetY(),idx); // sort descending...
673
674   Int_t npto=0;
675   for (int i=0; i<npts; i++) {
676     // skip not defined points
677     if (intidx[idx[i]]<0) continue;
678     atp->GetPoint(p,idx[i]);
679
680     // prealign point if required
681     // get IDEAL matrix
682     TGeoHMatrix *svOrigMatrix = GetMilleModule(intidx[idx[i]])->GetSensitiveVolumeOrigGlobalMatrix(p.GetVolumeID());
683     // get back real local coordinates: use OriginalGlobalMatrix because AliTrackPoints were written
684     // with idel geometry  
685     Double_t pg[3],pl[3];
686     pg[0]=p.GetX();
687     pg[1]=p.GetY();
688     pg[2]=p.GetZ();
689     //    printf("Global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]);
690     AliDebug(3,Form("Global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]));
691     svOrigMatrix->MasterToLocal(pg,pl);
692
693     AliDebug(3,Form("Local coordinates of measured point : X=%f  Y=%f  Z=%f \n",pl[0],pl[1],pl[2]));
694
695     // update covariance matrix
696     TGeoHMatrix hcov;
697     Double_t hcovel[9];
698     hcovel[0]=double(p.GetCov()[0]);
699     hcovel[1]=double(p.GetCov()[1]);
700     hcovel[2]=double(p.GetCov()[2]);
701     hcovel[3]=double(p.GetCov()[1]);
702     hcovel[4]=double(p.GetCov()[3]);
703     hcovel[5]=double(p.GetCov()[4]);
704     hcovel[6]=double(p.GetCov()[2]);
705     hcovel[7]=double(p.GetCov()[4]);
706     hcovel[8]=double(p.GetCov()[5]);
707     hcov.SetRotation(hcovel);
708     // now rotate in local system
709     hcov.Multiply(svOrigMatrix);
710     hcov.MultiplyLeft(&svOrigMatrix->Inverse());
711     // now hcov is LOCAL COVARIANCE MATRIX
712
713     // >> RS
714     if (fBug==1) {
715       // correzione bug LAYER 5  SSD temporanea..
716       int ssdidx=AliITSAlignMille2Module::GetIndexFromVolumeID(p.GetVolumeID());
717       if (ssdidx>=500 && ssdidx<1248) {
718         int ladder=(ssdidx-500)%22;
719         if (ladder==18) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx+1));
720         if (ladder==19) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx-1));
721       }
722     }
723     
724     // << RS
725
726     /// get (evenctually prealigned) matrix of sens. vol.
727     TGeoHMatrix *svMatrix = GetMilleModule(intidx[idx[i]])->GetSensitiveVolumeMatrix(p.GetVolumeID());
728     // modify global coordinates according with pre-aligment
729     svMatrix->LocalToMaster(pl,pg);
730     // now rotate in local system
731     hcov.Multiply(&svMatrix->Inverse());
732     hcov.MultiplyLeft(svMatrix);
733     // hcov is back in GLOBAL RF
734     Float_t pcov[6];
735     pcov[0]=hcov.GetRotationMatrix()[0];
736     pcov[1]=hcov.GetRotationMatrix()[1];
737     pcov[2]=hcov.GetRotationMatrix()[2];
738     pcov[3]=hcov.GetRotationMatrix()[4];
739     pcov[4]=hcov.GetRotationMatrix()[5];
740     pcov[5]=hcov.GetRotationMatrix()[8];
741
742     p.SetXYZ(pg[0],pg[1],pg[2],pcov);
743     //    printf("New Gl coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]);
744     AliDebug(3,Form("New global coordinates of measured point : X=%f  Y=%f  Z=%f \n",pg[0],pg[1],pg[2]));
745     atps->AddPoint(npto,&p);
746     AliDebug(2,Form("Adding point[%d] = ( %f , %f , %f )     volid = %d",npto,atps->GetX()[npto],atps->GetY()[npto],atps->GetZ()[npto],atps->GetVolumeID()[npto] ));
747
748     npto++;
749   }
750
751   return atps;
752 }
753
754
755
756 AliTrackPointArray *AliITSAlignMille2::SortTrack(const AliTrackPointArray *atp) {
757   /// sort alitrackpoints w.r.t. global Y direction
758   AliTrackPointArray *atps=NULL;
759   Int_t idx[20];
760   Int_t npts=atp->GetNPoints();
761   AliTrackPoint p;
762   atps=new AliTrackPointArray(npts);
763
764   TMath::Sort(npts,atp->GetY(),idx);
765
766   for (int i=0; i<npts; i++) {
767     atp->GetPoint(p,idx[i]);
768     atps->AddPoint(i,&p);
769     AliDebug(2,Form("Point[%d] = ( %f , %f , %f )     volid = %d",i,atps->GetX()[i],atps->GetY()[i],atps->GetZ()[i],atps->GetVolumeID()[i] ));
770   }
771   return atps;
772 }
773
774
775 Int_t AliITSAlignMille2::InitModuleParams() {
776   /// initialize geometry parameters for a given detector
777   /// for current cluster (fCluster)
778   /// fGlobalInitParam[] is set as:
779   ///    [tx,ty,tz,psi,theta,phi]
780   ///    (old was [tx,ty,tz,theta,psi,phi] ROOT's angles...)
781   /// *** At the moment: using Raffalele's angles definition ***
782   ///
783   /// return 0 if success
784
785   if (!fGeoManager) {
786     AliInfo("ITS geometry not initialized!");
787     return -1;
788   }
789
790   // now 'voluid' is the volumeID of a SENSITIVE VOLUME (coming from a cluster)
791
792   // set the internal index (index in module list)
793   UShort_t voluid=fCluster.GetVolumeID();
794   //
795   // IT IS VERY IMPORTANT: start from the end of the list, where the childs are located !!!
796   Int_t k=fNModules-1;
797   fCurrentModule = 0;
798   while (k>=0 && ! (fCurrentModule=GetMilleModule(k))->IsIn(voluid)) {
799      // VERY IMPORTANT: if the sensors were explicitly provided, don't look in the supermodules  
800     if (fSensorsIn && fCurrentModule->GetVolumeID() > kMaxITSSensVID) {k=-1; break;} 
801     k--; 
802   }
803   if (k<0) return -3;
804   //  fCurrentModule = GetMilleModule(k);
805   //
806   fModuleInitParam[0] = 0.0;
807   fModuleInitParam[1] = 0.0;
808   fModuleInitParam[2] = 0.0;
809   fModuleInitParam[3] = 0.0; // psi   (X)
810   fModuleInitParam[4] = 0.0; // theta (Y)
811   fModuleInitParam[5] = 0.0; // phi   (Z)
812   
813   /// get (evenctually prealigned) matrix of sens. vol.
814   TGeoHMatrix *svMatrix = fCurrentModule->GetSensitiveVolumeMatrix(voluid);
815   
816   fMeasGlo[0] = fCluster.GetX();
817   fMeasGlo[1] = fCluster.GetY();
818   fMeasGlo[2] = fCluster.GetZ(); 
819   svMatrix->MasterToLocal(fMeasGlo,fMeasLoc);  
820   AliDebug(2,Form("Local coordinates of measured point : X=%f  Y=%f  Z=%f \n",fMeasLoc[0] ,fMeasLoc[1] ,fMeasLoc[2] ));
821   
822   // set stdev from cluster
823   TGeoHMatrix hcov;
824   Double_t hcovel[9];
825   hcovel[0]=double(fCluster.GetCov()[0]);
826   hcovel[1]=double(fCluster.GetCov()[1]);
827   hcovel[2]=double(fCluster.GetCov()[2]);
828   hcovel[3]=double(fCluster.GetCov()[1]);
829   hcovel[4]=double(fCluster.GetCov()[3]);
830   hcovel[5]=double(fCluster.GetCov()[4]);
831   hcovel[6]=double(fCluster.GetCov()[2]);
832   hcovel[7]=double(fCluster.GetCov()[4]);
833   hcovel[8]=double(fCluster.GetCov()[5]);
834   hcov.SetRotation(hcovel);
835   // now rotate in local system
836   hcov.Multiply(svMatrix);
837   hcov.MultiplyLeft(&svMatrix->Inverse());
838
839   // set local sigmas
840   fSigmaLoc[0] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[0]));
841   fSigmaLoc[1] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[4])); // RS
842   fSigmaLoc[2] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[8]));
843
844   // set minimum value for SigmaLoc to 10 micron 
845   if (fSigmaLoc[0]<0.0010) fSigmaLoc[0]=0.0010;
846   if (fSigmaLoc[2]<0.0010) fSigmaLoc[2]=0.0010;
847
848   // multiply local sigmas by global and module specific factor 
849   for (int i=3;i--;) fSigmaLoc[i] *= fSigmaFactor[i]*fCurrentModule->GetSigmaFactor(i);
850   //
851   AliDebug(2,Form("Setting StDev from CovMat : fSigmaLocX=%g  fSigmaLocY=%g fSigmaLocZ=%g \n",fSigmaLoc[0] ,fSigmaLoc[1] ,fSigmaLoc[2] ));
852    
853   return 0;
854 }
855
856 void AliITSAlignMille2::Print(Option_t*) const 
857 {
858   ///
859   printf("*** AliMillepede for ITS ***\n");
860   printf("    Number of defined super modules: %d\n",fNModules);
861   printf("    Obtained parameters refer to %s Deltas\n",fUseGlobalDelta ? "GLOBAL":"LOCAL");
862   //
863   if (fGeoManager)
864     printf("    geometry loaded from %s\n",fGeometryFileName.Data());
865   else
866     printf("    geometry not loaded\n");
867   //  
868   if (fUsePreAlignment) 
869     printf("    using prealignment from %s \n",fPreAlignmentFileName.Data());
870   else
871     printf("    prealignment not used\n");    
872   //
873   //
874   if (fBOn) 
875     printf("    B Field set to %f T - using Riemann's helices\n",fBField);
876   else
877     printf("    B Field OFF - using straight lines \n");
878   //
879   if (fRequirePoints) printf("    Required points in tracks:\n");
880   for (Int_t i=0; i<6; i++) {
881     if (fNReqLayUp[i]>0) printf("        Layer %d : %d points with Y>0\n",i+1,fNReqLayUp[i]);
882     if (fNReqLayDown[i]>0) printf("        Layer %d : %d points with Y<0\n",i+1,fNReqLayDown[i]);
883     if (fNReqLay[i]>0) printf("        Layer %d : %d points \n",i+1,fNReqLay[i]);
884   }
885   for (Int_t i=0; i<3; i++) {
886     if (fNReqDetUp[i]>0) printf("        Detector %d : %d points with Y>0\n",i+1,fNReqDetUp[i]);
887     if (fNReqDetDown[i]>0) printf("        Detector %d : %d points with Y<0\n",i+1,fNReqDetDown[i]);
888     if (fNReqDet[i]>0) printf("        Detector %d : %d points \n",i+1,fNReqDet[i]);
889   }
890   //  
891   printf("\n    Millepede configuration parameters:\n");
892   printf("        init parsig for translations  : %.4f\n",fParSigTranslations);
893   printf("        init parsig for rotations     : %.4f\n",fParSigRotations);
894   printf("        init value for chi2 cut       : %.4f\n",fStartFac);
895   printf("        first iteration cut value     : %.4f\n",fResCutInitial);
896   printf("        other iterations cut value    : %.4f\n",fResCut);
897   printf("        number of stddev for chi2 cut : %d\n",fNStdDev);
898   printf("        mult. fact. for local sigmas  : %.4f %.4f %.4f\n",fSigmaFactor[0],fSigmaFactor[1],fSigmaFactor[2]);
899
900   printf("List of defined modules:\n");
901   printf("  intidx\tindex\tvoluid\tname\n");
902   for (int i=0; i<fNModules; i++) {
903     AliITSAlignMille2Module* md = GetMilleModule(i); 
904     printf("  %d\t%d\t%d\t%s\n",i,md->GetIndex(),md->GetVolumeID(),md->GetName());
905   }
906 }
907
908 AliITSAlignMille2Module  *AliITSAlignMille2::GetMilleModuleByVID(UShort_t voluid) const
909 {
910   // return pointer to a define supermodule
911   // return NULL if error
912   Int_t i=IsDefined(voluid);
913   if (i<0) return NULL;
914   return GetMilleModule(i);
915 }
916
917 Bool_t AliITSAlignMille2::InitRiemanFit() 
918 {
919   // Initialize Riemann Fitter for current track
920   // return kFALSE if error
921
922   if (!fBOn) return kFALSE;
923
924   Int_t npts=0;
925   AliTrackPoint ap;
926   npts = fTrack->GetNPoints();
927   AliDebug(3,Form("Fitting track with %d points",npts));
928
929   fRieman->Reset();
930   fRieman->SetTrackPointArray(fTrack);
931
932   TArrayI ai(npts);
933   for (Int_t ipt=0; ipt<npts; ipt++) ai[ipt]=fTrack->GetVolumeID()[ipt];
934   
935   // fit track with 5 params in his own tracking-rotated reference system
936   // xc = -p[1]/p[0];
937   // yc = 1/p[0];
938   // R  = sqrt( x0*x0 + y0*y0 - y0*p[2]);
939   if (!fRieman->Fit(&ai,NULL,(AliGeomManager::ELayerID)1,(AliGeomManager::ELayerID)6)) {
940     return kFALSE;
941   }
942
943   for (int i=0; i<5; i++)
944     fLocalInitParam[i] = fRieman->GetParam()[i];
945   
946   return kTRUE;
947 }
948
949 Bool_t fullErr2D = kTRUE;
950
951 void trackFit2D(Int_t &, Double_t *, double &chi2, double *par, int)
952 {
953   const double kTiny = 1.e-14;
954   chi2 = 0;
955   static AliTrackPoint pnt;
956   //
957   enum {kAX,kAZ,kBX,kBZ};
958   enum {kXX=0,kXY=1,kXZ=2,kYX=kXY,kYY=3,kYZ=4,kZX=kXZ,kZY=kYZ,kZZ=5};
959   //
960   AliITSAlignMille2* alig = AliITSAlignMille2::GetInstance();
961   AliTrackPointArray* track = alig->GetCurrentTrack();
962   //
963   int npts = track->GetNPoints();
964   for (int ip=0;ip<npts;ip++) {
965     track->GetPoint(pnt,ip);
966     const float *cov = pnt.GetCov();
967     double y  = pnt.GetY();
968     double dx = pnt.GetX() - (par[kAX]+y*par[kBX]);
969     double dz = pnt.GetZ() - (par[kAZ]+y*par[kBZ]);
970     double xxe = cov[kXX];
971     double zze = cov[kZZ];
972     double xze = cov[kXZ];
973     //
974     if (fullErr2D) {
975       xxe += par[kBX]*par[kBX]*cov[kYY]-2.*par[kBX]*cov[kXY];
976       zze += par[kBZ]*par[kBZ]*cov[kYY]-2.*par[kBZ]*cov[kZY];
977       xze += par[kBX]*par[kBZ]*cov[kYY]-cov[kYZ]*par[kBZ]-cov[kXY]*par[kBX];
978     }
979     //
980     double det = xxe*zze - xze*xze;
981     if (det<kTiny) {
982       printf("Negative diag. error (det=%+e) |sxx:%+e szz:%+e sxz:%+e| bx:%+e bz:%+e|\n"
983              "Discarding correlation term\n",det,xxe,zze,xze,par[kBX],par[kBZ]);
984       xxe = cov[kXX];
985       zze = cov[kZZ];
986       xze = cov[kXZ];
987       fullErr2D = kFALSE;
988     }
989     double xxeI = zze/det;
990     double zzeI = xxe/det;
991     double xzeI =-xze/det;
992     //
993     chi2 += dx*dx*xxeI + dz*dz*zzeI + 2.*dx*dz*xzeI;
994     // 
995     //    printf("%d | %+e %+e %+e %+e %+e -> %+e\n",ip,dx,dz,xxeI,zzeI,xzeI,  chi2);
996   }
997   //
998 }
999
1000 void AliITSAlignMille2::InitTrackParams(int meth) 
1001 {
1002   /// initialize local parameters with different methods
1003   /// for current track (fTrack)
1004   Int_t npts=0;
1005   AliTrackPoint ap;
1006   double sX=0,sXY=0,sZ=0,sZY=0,sY=0,sYY=0,det=0;
1007   // simple linear interpolation
1008   // get local starting parameters (to be substituted by ESD track parms)
1009   // local parms (fLocalInitParam[]) are:
1010   //      [0] = global x coord. of straight line intersection at y=0 plane
1011   //      [1] = global z coord. of straight line intersection at y=0 plane
1012   //      [2] = px/py  
1013   //      [3] = pz/py
1014   // test #1: linear fit in x(y) and z(y)
1015   npts = fTrack->GetNPoints();
1016   AliDebug(3,Form("*** initializing track with %d points ***",npts));
1017   for (int i=npts;i--;) {
1018     sY  += fTrack->GetY()[i];
1019     sYY += fTrack->GetY()[i]*fTrack->GetY()[i];
1020     sX  += fTrack->GetX()[i];
1021     sXY += fTrack->GetX()[i]*fTrack->GetY()[i];
1022     sZ  += fTrack->GetZ()[i];
1023     sZY += fTrack->GetZ()[i]*fTrack->GetY()[i];
1024   }
1025   det = sYY*npts-sY*sY;
1026   if (det==0) det = 1E-20;
1027   fLocalInitParam[0] = (sX*sYY-sY*sXY)/det;
1028   fLocalInitParam[2] = (sXY*npts-sY*sX)/det;
1029   //
1030   fLocalInitParam[1] = (sZ*sYY-sY*sZY)/det;
1031   fLocalInitParam[3] = (sZY*npts-sY*sZ)/det;
1032   //AliDebug(2,Form("X = p0gx + ugx*Y : p0gx = %f +- %f    ugx = %f +- %f\n",fLocalInitParam[0],f1->GetParError(0),fLocalInitParam[2],f1->GetParError(1)));
1033   AliDebug(2,Form("X = p0gx + ugx*Y : p0gx = %f    ugx = %f\n",fLocalInitParam[0],fLocalInitParam[2]));
1034   //
1035   if (meth==1) return;
1036   //
1037   // perform full fit accounting for cov.matrix
1038   static TVirtualFitter *minuit = 0;
1039   static Double_t step[5]   = {1E-3,1E-3,1E-4,1E-4,1E-5};
1040   static Double_t arglist[10];
1041   //
1042   if (!minuit) {
1043     minuit = TVirtualFitter::Fitter(0,4);
1044     minuit->SetFCN(trackFit2D);
1045     arglist[0] = 1;
1046     minuit->ExecuteCommand("SET ERR",arglist, 1);
1047     //
1048     arglist[0] = -1;
1049     minuit->ExecuteCommand("SET PRINT",arglist,1);
1050     //
1051   }
1052   //
1053   minuit->SetParameter(0, "ax",   fLocalInitParam[0], step[0], 0,0);
1054   minuit->SetParameter(1, "az",   fLocalInitParam[1], step[1], 0,0);
1055   minuit->SetParameter(2, "bx",   fLocalInitParam[2], step[2], 0,0);
1056   minuit->SetParameter(3, "bz",   fLocalInitParam[3], step[3], 0,0);
1057   //
1058   arglist[0] = 1000; // number of function calls 
1059   arglist[1] = 0.001; // tolerance 
1060   fullErr2D = kTRUE;
1061   minuit->ExecuteCommand("MIGRAD",arglist,2);
1062   //
1063   for (int i=0;i<4;i++) fLocalInitParam[i] = minuit->GetParameter(i);
1064   for (int i=0;i<4;i++) for (int j=0;j<4;j++) fLocalInitParEr[i][j] = minuit->GetCovarianceMatrixElement(i,j);
1065   //
1066 }
1067
1068
1069 Int_t AliITSAlignMille2::IsDefined(UShort_t voluid) const
1070 {
1071   // checks if supermodule 'voluid' is defined and return the internal index
1072   // return -1 if error
1073   Int_t k = fNModules-1;
1074   while ( k>=0 && !(voluid==GetMilleModule(k)->GetVolumeID()) ) k--;  
1075   if (k<0) return -1; 
1076   return k;
1077 }
1078
1079 Int_t AliITSAlignMille2::IsContained(UShort_t voluid) const
1080 {
1081   // checks if the sensitive module 'voluid' is contained inside a supermodule and return the internal index of the last identified supermodule
1082   // return -1 if error
1083   if (AliITSAlignMille2Module::GetIndexFromVolumeID(voluid)<0) return -1;
1084   Int_t k=fNModules-1;
1085   while (k>=0 && !(GetMilleModule(k)->IsIn(voluid)) ) k--;  
1086   if (k<0) return -1; 
1087   return k;
1088 }
1089
1090 Bool_t AliITSAlignMille2::CheckVolumeID(UShort_t voluid) const 
1091 {
1092   /// check if a sensitive volume is contained inside one of the defined supermodules
1093   Int_t k=fNModules-1;
1094   while (k>=0 && !(GetMilleModule(k)->IsIn(voluid)) ) k--;  
1095   if (k>=0) return kTRUE;
1096   return kFALSE;
1097 }
1098
1099 Int_t AliITSAlignMille2::CheckCurrentTrack() {
1100   /// checks if AliTrackPoints belongs to defined modules
1101   /// return number of good poins
1102   /// return 0 if not enough points
1103
1104   Int_t npts = fTrack->GetNPoints();
1105   Int_t ngoodpts=0;
1106   // debug points
1107   for (int j=0; j<npts; j++) {
1108     UShort_t voluid = fTrack->GetVolumeID()[j];    
1109     if (CheckVolumeID(voluid)) {
1110       ngoodpts++;
1111     }
1112   }
1113
1114   if (ngoodpts<fMinNPtsPerTrack) return 0;
1115
1116   return ngoodpts;
1117 }
1118
1119 Int_t AliITSAlignMille2::ProcessTrack(const AliTrackPointArray *track) {
1120   /// Process track; Loop over hits and set local equations
1121   /// here 'track' is a AliTrackPointArray
1122   /// return 0 if success;
1123   
1124   if (!fIsMilleInit) {
1125     AliInfo("Millepede has not been initialized!");
1126     return -1;
1127   }
1128
1129   Int_t npts = track->GetNPoints();
1130   AliDebug(2,Form("*** Input track with %d points ***",npts));
1131
1132   // preprocessing of the input track: keep only points in defined volumes,
1133   // move points if prealignment is set, sort by Yglo if required
1134   
1135   fTrack=PrepareTrack(track);
1136   if (!fTrack) return -1;
1137
1138   npts = fTrack->GetNPoints();
1139   AliDebug(2,Form("*** Processing prepared track with %d points ***",npts));
1140   
1141   if (!fBOn) { // straight lines  
1142     // set local starting parameters (to be substituted by ESD track parms)
1143     // local parms (fLocalInitParam[]) are:
1144     //      [0] = global x coord. of straight line intersection at y=0 plane
1145     //      [1] = global z coord. of straight line intersection at y=0 plane
1146     //      [2] = px/py  
1147     //      [3] = pz/py
1148     InitTrackParams(fInitTrackParamsMeth);  
1149   } 
1150   else {
1151     // local parms (fLocalInitParam[]) are the Riemann Fitter params
1152     if (!InitRiemanFit()) {
1153       AliInfo("Riemann fit failed! skipping this track...");
1154       delete fTrack;
1155       fTrack=NULL;
1156       return -5;
1157     }
1158   }
1159   
1160   Int_t nloceq=0;
1161   static Mille2Data md[100];
1162   
1163   for (Int_t ipt=0; ipt<npts; ipt++) {
1164     fTrack->GetPoint(fCluster,ipt);
1165     AliDebug(2,Form("\n--- processing point %d --- \n",ipt));    
1166
1167     // set geometry parameters for the the current module
1168     if (InitModuleParams()) continue;
1169     AliDebug(2,Form("    VolID=%d  Index=%d  InternalIdx=%d  symname=%s\n", 
1170                     track->GetVolumeID()[ipt], fCurrentModule->GetIndex(),
1171                     fCurrentModule->GetUniqueID(), AliGeomManager::SymName(track->GetVolumeID()[ipt]) ));
1172     AliDebug(2,Form("    Preprocessed Point = ( %f , %f , %f ) \n",fCluster.GetX(),fCluster.GetY(),fCluster.GetZ()));
1173     
1174     if (!AddLocalEquation(md[nloceq])) nloceq++;    
1175     else fTotBadLocEqPoints++;
1176   } // end loop over points
1177   //
1178   delete fTrack;
1179   fTrack=NULL;
1180   // not enough good points!
1181   if (nloceq<fMinNPtsPerTrack) return -1;
1182   //
1183   // finally send local equations to millepede
1184   SetLocalEquations(md,nloceq);
1185   fMillepede->SaveRecordData(); // RRR
1186   //
1187   return 0;
1188 }
1189
1190 Int_t AliITSAlignMille2::CalcIntersectionPoint(Double_t *lpar, Double_t *gpar) {
1191   /// calculate track intersection point in local coordinates
1192   /// according with a given set of parameters (local(4) and global(6))
1193   /// and fill fPintLoc/Glo
1194   ///    local are:   pgx0, pgz0, ugx, ugz   OR   riemann fitters pars
1195   ///    global are:  tx,ty,tz,psi,theta,phi (Raff's delta angles in deg.)
1196   /// return 0 if success
1197   
1198   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]));
1199   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]));
1200
1201   
1202   // prepare the TGeoHMatrix
1203   TGeoHMatrix *fTempHMat = fCurrentModule->GetSensitiveVolumeModifiedMatrix(fCluster.GetVolumeID(),gpar,
1204                                                                             !fUseGlobalDelta);
1205   if (!fTempHMat) return -1;
1206   
1207   Double_t v0g[3]; // vector with straight line direction in global coord.
1208   Double_t p0g[3]; // point of the straight line (glo)
1209   
1210   if (fBOn) { // B FIELD!
1211     AliTrackPoint prf; 
1212     for (int ip=0; ip<5; ip++)
1213       fRieman->SetParam(ip,lpar[ip]);
1214
1215     if (!fRieman->GetPCA(fCluster,prf))  {
1216       AliInfo(Form("error in GetPCA for point %d",fCluster.GetVolumeID()));
1217       return -3;
1218     }
1219     // now determine straight line passing tangent to fit curve at prf
1220     // ugx = dX/dY_glo = DeltaX/DeltaY_glo
1221     // mo' P1=(X,Y,Z)_glo_prf
1222     //       => (x,y,Z)_trk_prf ruotando di alpha...
1223     Double_t alpha=fRieman->GetAlpha();
1224     Double_t x1g = prf.GetX();
1225     Double_t y1g = prf.GetY();
1226     Double_t z1g = prf.GetZ();
1227     Double_t x1t =  x1g*TMath::Cos(alpha) + y1g*TMath::Sin(alpha);
1228     Double_t y1t = -x1g*TMath::Sin(alpha) + y1g*TMath::Cos(alpha);
1229     Double_t z1t =  z1g;    
1230
1231     Double_t x2t = x1t+1.0;
1232     Double_t y2t = y1t+fRieman->GetDYat(x1t);
1233     Double_t z2t = z1t+fRieman->GetDZat(x1t);
1234     Double_t x2g =  x2t*TMath::Cos(alpha) - y2t*TMath::Sin(alpha);
1235     Double_t y2g =  x2t*TMath::Sin(alpha) + y2t*TMath::Cos(alpha);
1236     Double_t z2g =  z2t;  
1237
1238     AliDebug(3,Form("Riemann frame:  fAlpha = %f  =  %f  ",alpha,alpha*180./TMath::Pi()));
1239     AliDebug(3,Form("   prf_glo=( %f , %f , %f )  prf_rf=( %f , %f , %f )\n", x1g,y1g,z1g, x1t,y1t,z1t));
1240     AliDebug(3,Form("   mov_glo=( %f , %f , %f )      rf=( %f , %f , %f )\n",x2g,y2g,z2g, x2t,y2t,z2t));
1241         
1242     if (TMath::Abs(y2g-y1g)<1e-15) {
1243       AliInfo("DeltaY=0! Cannot proceed...");
1244       return -1;
1245     }
1246     // ugx,1,ugz
1247     v0g[0] = (x2g-x1g)/(y2g-y1g);
1248     v0g[1]=1.0;
1249     v0g[2] = (z2g-z1g)/(y2g-y1g);
1250     
1251     // point: just keep prf
1252     p0g[0]=x1g;
1253     p0g[1]=y1g;
1254     p0g[2]=z1g;
1255   }  
1256   else { // staight line
1257     // vector of initial straight line direction in glob. coord
1258     v0g[0]=lpar[2];
1259     v0g[1]=1.0;
1260     v0g[2]=lpar[3];
1261     
1262     // intercept in yg=0 plane in glob coord
1263     p0g[0]=lpar[0];
1264     p0g[1]=0.0;
1265     p0g[2]=lpar[1];
1266   }
1267   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]));
1268   
1269   // same in local coord.
1270   Double_t p0l[3],v0l[3];
1271   fTempHMat->MasterToLocalVect(v0g,v0l);
1272   fTempHMat->MasterToLocal(p0g,p0l);
1273   
1274   if (TMath::Abs(v0l[1])<1e-15) {
1275     AliInfo("Track Y direction in local frame is zero! Cannot proceed...");
1276     return -1;
1277   }
1278   
1279   // local intersection point
1280   fPintLoc[0] = p0l[0] - (v0l[0]/v0l[1])*p0l[1];
1281   fPintLoc[1] = 0;
1282   fPintLoc[2] = p0l[2] - (v0l[2]/v0l[1])*p0l[1];
1283   
1284   // global intersection point
1285   fTempHMat->LocalToMaster(fPintLoc,fPintGlo);
1286   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]));
1287   
1288   return 0;
1289 }
1290
1291 Int_t AliITSAlignMille2::CalcDerivatives(Int_t paridx, Bool_t islpar) {
1292   /// calculate numerically (ROOT's style) the derivatives for
1293   /// local X intersection  and local Z intersection
1294   /// parlist: local  (islpar=kTRUE)  pgx0, pgz0, ugx0, ugz0  OR riemann's params
1295   ///          global (islpar=kFALSE) tx, ty, tz, psi, theta, phi (Raf's angles in deg)
1296   /// return 0 if success
1297   
1298   // copy initial parameters
1299   Double_t lpar[ITSMILLE2_NLOCAL];
1300   Double_t gpar[ITSMILLE2_NPARCH];
1301   for (Int_t i=0; i<ITSMILLE2_NLOCAL; i++) lpar[i]=fLocalInitParam[i];
1302   for (Int_t i=0; i<ITSMILLE2_NPARCH; i++) gpar[i]=fModuleInitParam[i];
1303
1304   // trial with fixed dpar...
1305   Double_t dpar=0.0;
1306
1307   if (islpar) { // track parameters
1308     //dpar=fLocalInitParam[paridx]*0.001;
1309     // set minimum dpar
1310     if (!fBOn) {
1311       if (paridx<2) dpar=1.0e-4; // translations
1312       else dpar=1.0e-6; // direction
1313     }
1314     else { // B Field
1315       // pepo: proviamo con 1/1000, poi evenctually 1/100...
1316       Double_t dfrac=0.01;
1317       switch(paridx) {
1318       case 0:
1319         // RMS cosmics: 1e-4
1320         dpar = TMath::Max(1.0e-6,TMath::Abs(fLocalInitParam[paridx]*dfrac)); 
1321         break;
1322       case 1: 
1323         // RMS cosmics: 0.2
1324         dpar = TMath::Max(0.002,TMath::Abs(fLocalInitParam[paridx]*dfrac)); 
1325         break;
1326       case 2: 
1327         // RMS cosmics: 9
1328         dpar = TMath::Max(0.09,TMath::Abs(fLocalInitParam[paridx]*dfrac)); 
1329         break;
1330       case 3: 
1331         // RMS cosmics: 7
1332         dpar = TMath::Max(0.07,TMath::Abs(fLocalInitParam[paridx]*dfrac)); 
1333         break;
1334       case 4: 
1335         // RMS cosmics: 0.3
1336         dpar = TMath::Max(0.003,TMath::Abs(fLocalInitParam[paridx]*dfrac)); 
1337         break;
1338       }
1339     }
1340   }
1341   else { // alignment global parameters
1342     //dpar=fModuleInitParam[paridx]*0.001;
1343     if (paridx<3) dpar=1.0e-4; // translations
1344     else dpar=1.0e-2; // angles    
1345   }
1346
1347   AliDebug(3,Form("+++ using dpar=%g",dpar));
1348   
1349   // calculate derivative ROOT's like:
1350   //  using f(x+h),f(x-h),f(x+h/2),f(x-h2)...
1351   Double_t pintl1[3]; // f(x-h)
1352   Double_t pintl2[3]; // f(x-h/2)
1353   Double_t pintl3[3]; // f(x+h/2)
1354   Double_t pintl4[3]; // f(x+h)
1355     
1356   // first values
1357   if (islpar) lpar[paridx] -= dpar;
1358   else gpar[paridx] -= dpar;
1359   if (CalcIntersectionPoint(lpar, gpar)) return -2;
1360   for (Int_t i=0; i<3; i++) pintl1[i]=fPintLoc[i];
1361
1362   // second values
1363   if (islpar) lpar[paridx] += dpar/2;
1364   else gpar[paridx] += dpar/2;
1365   if (CalcIntersectionPoint(lpar, gpar)) return -2;
1366   for (Int_t i=0; i<3; i++) pintl2[i]=fPintLoc[i];
1367
1368   // third values
1369   if (islpar) lpar[paridx] += dpar;
1370   else gpar[paridx] += dpar;
1371   if (CalcIntersectionPoint(lpar, gpar)) return -2;
1372   for (Int_t i=0; i<3; i++) pintl3[i]=fPintLoc[i];
1373
1374   // fourth values
1375   if (islpar) lpar[paridx] += dpar/2;
1376   else gpar[paridx] += dpar/2;
1377   if (CalcIntersectionPoint(lpar, gpar)) return -2;
1378   for (Int_t i=0; i<3; i++) pintl4[i]=fPintLoc[i];
1379
1380   Double_t h2 = 1./(2.*dpar);
1381   Double_t d0 = pintl4[0]-pintl1[0];
1382   Double_t d2 = 2.*(pintl3[0]-pintl2[0]);
1383   fDerivativeLoc[0] = h2*(4*d2 - d0)/3.;
1384   if (TMath::Abs(fDerivativeLoc[0]) < 1.0e-9) fDerivativeLoc[0] = 0.0;
1385
1386   d0 = pintl4[2]-pintl1[2];
1387   d2 = 2.*(pintl3[2]-pintl2[2]);
1388   fDerivativeLoc[2] = h2*(4*d2 - d0)/3.;
1389   if (TMath::Abs(fDerivativeLoc[2]) < 1.0e-9) fDerivativeLoc[2]=0.0;
1390
1391   AliDebug(3,Form("\n+++ derivatives +++ \n"));
1392   AliDebug(3,Form("+++ dXLoc/dpar = %g +++\n",fDerivativeLoc[0]));
1393   AliDebug(3,Form("+++ dZLoc/dpar = %g +++\n\n",fDerivativeLoc[0]));
1394   
1395   return 0;
1396 }
1397
1398
1399 Int_t AliITSAlignMille2::AddLocalEquation(Mille2Data &m) {
1400   /// Define local equation for current cluster in X and Z coor.
1401   /// and store them to memory
1402   /// return 0 if success
1403   int nLev = 0; 
1404   // store first interaction point
1405   if (CalcIntersectionPoint(fLocalInitParam, fModuleInitParam)) return -4;  
1406   for (Int_t i=0; i<3; i++) fPintLoc0[i]=fPintLoc[i];
1407   AliDebug(2,Form("Intesect. point: L( %f , %f , %f )",fPintLoc[0],fPintLoc[1],fPintLoc[2]));
1408   
1409   // calculate local derivatives numerically
1410   Bool_t zeroX = kTRUE;
1411   Bool_t zeroZ = kTRUE;
1412   //
1413   for (Int_t i=0; i<fNLocal; i++) {
1414     if (CalcDerivatives(i,kTRUE)) return -1;
1415     m.derlocX[i] = fDerivativeLoc[0];
1416     m.derlocZ[i] = fDerivativeLoc[2];
1417     if (zeroX) zeroX = fDerivativeLoc[0]==0;
1418     if (zeroZ) zeroZ = fDerivativeLoc[2]==0;
1419   }
1420   //  for (Int_t i=0; i<fNLocal; i++) AliDebug(2,Form("Local parameter %d - dXdpar = %g  - dZdpar = %g\n",i,dXdL[i],dZdL[i]));
1421   if (zeroX) {AliInfo("Aborting: zero local X derivatives!"); return -2;}
1422   if (zeroZ) {AliInfo("Aborting: zero local Z derivatives!"); return -2;}
1423   //
1424   //
1425   AliITSAlignMille2Module* endModule = fCurrentModule;
1426   //
1427   do {
1428     if (nLev==0 || !fUseGlobalDelta) zeroX = zeroZ = kTRUE;
1429     int shiftL = nLev*ITSMILLE2_NPARCH;
1430     for (Int_t i=0; i<ITSMILLE2_NPARCH; i++) {
1431       if (nLev==0 || !fUseGlobalDelta) {
1432         if (CalcDerivatives(i,kFALSE)) return -1;
1433         m.dergloX[shiftL + i] = fDerivativeLoc[0];
1434         m.dergloZ[shiftL + i] = fDerivativeLoc[2];
1435         if (zeroX) zeroX = fDerivativeLoc[0]==0;
1436         if (zeroZ) zeroZ = fDerivativeLoc[2]==0;      
1437       } 
1438       else { // for the global delta the deravites of different levels are the same
1439         m.dergloX[shiftL + i] = m.dergloX[shiftL + i - ITSMILLE2_NPARCH];
1440         m.dergloZ[shiftL + i] = m.dergloZ[shiftL + i - ITSMILLE2_NPARCH];
1441       }
1442     }
1443     //  for (Int_t i=0; i<ITSMILLE2_NPARCH; i++) AliDebug(2,Form("Global parameter %d - dXdpar = %g  - dZdpar = %g\n",i,dXdG[i],dZdG[i]));
1444     if (zeroX) {AliInfo("Aborting: zero global X derivatives!");return -2;}
1445     if (zeroZ) {AliInfo("Aborting: zero global Z derivatives!");return -2;}
1446     // set equation for Xloc coordinate
1447     m.moduleIDX[nLev] = fCurrentModule->GetUniqueID();
1448     nLev++;
1449     //
1450   } while( (fCurrentModule=fCurrentModule->GetParent()) );
1451   //
1452   // ok, can copy to m
1453   AliDebug(2,Form("Adding local equation X with fMeas=%.6f  and fSigma=%.6f",(fMeasLoc[0]-fPintLoc0[0]), fSigmaLoc[0]));
1454   m.measX = fMeasLoc[0]-fPintLoc0[0];
1455   m.sigmaX = fSigmaLoc[0];
1456   //
1457   AliDebug(2,Form("Adding local equation Z with fMeas=%.6f  and fSigma=%.6f",(fMeasLoc[2]-fPintLoc0[2]), fSigmaLoc[2]));
1458   m.measZ = fMeasLoc[2]-fPintLoc0[2];
1459   m.sigmaZ = fSigmaLoc[2];
1460   //
1461   m.levFilled = nLev;
1462   fCurrentModule = endModule;
1463   //
1464   return 0;
1465 }
1466
1467 void AliITSAlignMille2::SetLocalEquations(const Mille2Data *marr, Int_t neq) {
1468   /// Set local equations with data stored in m
1469   /// return 0 if success
1470   //
1471   for (Int_t j=0; j<neq; j++) {
1472     //
1473     const Mille2Data &m = marr[j];
1474     //
1475     // set equation for Xloc coordinate
1476     AliDebug(2,Form("setting local equation X with fMeas=%.6f  and fSigma=%.6f",m.measX, m.sigmaX));
1477     for (int i=fNLocal; i--;) SetLocalDerivative( i, m.derlocX[i] );
1478     for (int il=m.levFilled;il--;) {
1479       GetMilleModule(m.moduleIDX[il])->IncNProcessedPoints();
1480       int hlev = m.moduleIDX[il]*ITSMILLE2_NPARCH;       // id of the supermodule 
1481       int llev = il*ITSMILLE2_NPARCH;
1482       for (int i=ITSMILLE2_NPARCH; i--;) SetGlobalDerivative( hlev+i, m.dergloX[llev+i] );
1483     }
1484     //
1485     fMillepede->SetLocalEquation(fGlobalDerivatives, fLocalDerivatives, m.measX, m.sigmaX);  
1486     //
1487     // set equation for Zloc coordinate
1488     AliDebug(2,Form("setting local equation Z with fMeas=%.6f  and fSigma=%.6f",m.measZ, m.sigmaZ));
1489     for (int i=fNLocal; i--;) SetLocalDerivative( i, m.derlocZ[i] );
1490     for (int il=m.levFilled;il--;) {
1491       int hlev = m.moduleIDX[il]*ITSMILLE2_NPARCH;       // id of the supermodule 
1492       int llev = il*ITSMILLE2_NPARCH;
1493       for (int i=ITSMILLE2_NPARCH; i--;) SetGlobalDerivative(hlev+i, m.dergloZ[llev+i] );
1494     }
1495     fMillepede->SetLocalEquation(fGlobalDerivatives, fLocalDerivatives, m.measZ, m.sigmaZ);  
1496   }
1497 }
1498
1499 Int_t AliITSAlignMille2::GlobalFit(Double_t *parameters,Double_t *errors,Double_t *pulls) {
1500   /// Call global fit; Global parameters are stored in parameters
1501   if (!fIsMilleInit) {
1502     AliInfo("Millepede has not been initialized!");
1503     return 0;
1504   }
1505   int res = fMillepede->GlobalFit(parameters,errors,pulls);
1506   AliInfo(Form("%s fitting global parameters!",res ? "Done":"Failed"));
1507   return res;
1508 }
1509
1510 Double_t AliITSAlignMille2::GetParError(Int_t iPar) {
1511   /// Get error of parameter iPar
1512   if (!fIsMilleInit) {
1513     AliInfo("Millepede has not been initialized!");
1514     return 0;
1515   }
1516   Double_t lErr = fMillepede->GetParError(iPar);
1517   return lErr;
1518 }
1519
1520 void AliITSAlignMille2::PrintGlobalParameters() {
1521   /// Print global parameters
1522   if (!fIsMilleInit) {
1523     AliInfo("Millepede has not been initialized!");
1524     return;
1525   }
1526   fMillepede->PrintGlobalParameters();
1527 }
1528
1529 // //_________________________________________________________________________
1530 Int_t AliITSAlignMille2::LoadSuperModuleFile(const Char_t *sfile)
1531
1532   // load definitions of supermodules from a root file
1533   // return 0 if success
1534
1535   TFile *smf=TFile::Open(sfile);
1536   if (!smf->IsOpen()) {
1537     AliInfo(Form("Cannot open supermodule file %s",sfile));
1538     return -1;
1539   }
1540
1541   TClonesArray *sma=(TClonesArray*)smf->Get("ITSMilleSuperModules");
1542   if (!sma) {
1543     AliInfo(Form("Cannot find ITSMilleSuperModules array in file"));
1544     return -2;  
1545   }  
1546   Int_t nsma=sma->GetEntriesFast();
1547   AliInfo(Form("Array of SuperModules with %d entries\n",nsma));
1548   //
1549   Char_t st[250];
1550   char symname[150];
1551   UShort_t volid;
1552   TGeoHMatrix m;
1553   //
1554   for (Int_t i=0; i<nsma; i++) {
1555     AliAlignObjParams *a = (AliAlignObjParams*)sma->UncheckedAt(i);
1556     volid=a->GetVolUID();
1557     strcpy(st,a->GetSymName());
1558     a->GetMatrix(m);
1559     //
1560     sscanf(st,"%s",symname);
1561     // decode module list
1562     char *stp=strstr(st,"ModuleList:");
1563     if (!stp) return -3;
1564     stp += 11;
1565     int idx[2200];
1566     char spp[200]; int jp=0;
1567     char cl[20];
1568     strcpy(st,stp);
1569     int l=strlen(st);
1570     int j=0;
1571     int n=0;
1572     //
1573     while (j<=l) {
1574       if (st[j]==9 || st[j]==32 || st[j]==10 || st[j]==0) {
1575         spp[jp]=0;
1576         jp=0;
1577         if (strlen(spp)) {
1578           int k=strcspn(spp,"-");
1579           if (k<int(strlen(spp))) { // c'e' il -
1580             strcpy(cl,&(spp[k+1]));
1581             spp[k]=0;
1582             int ifrom=atoi(spp); int ito=atoi(cl);
1583             for (int b=ifrom; b<=ito; b++) {
1584               idx[n]=b;
1585               n++;
1586             }
1587           }
1588           else { // numerillo singolo
1589             idx[n]=atoi(spp);
1590             n++;
1591           }
1592         }
1593       }
1594       else {
1595         spp[jp]=st[j];
1596         jp++;
1597       }
1598       j++;
1599     }
1600     UShort_t volidsv[2198];
1601     for (j=0;j<n;j++) {
1602       volidsv[j]=AliITSAlignMille2Module::GetVolumeIDFromIndex(idx[j]);
1603       if (!volidsv[j]) {
1604         AliInfo(Form("Index %d not valid (range 0->%d)",idx[j],kMaxITSSensID));
1605         return -5;
1606       }
1607     }
1608     Int_t smindex=int(2198+volid-14336); // virtual index
1609     fSuperModule.AddAtAndExpand(new AliITSAlignMille2Module(smindex,volid,symname,&m,n,volidsv),fNSuperModules);
1610     //
1611     fNSuperModules++;
1612   }
1613
1614   smf->Close();
1615   //
1616   return 0;
1617 }
1618
1619 //_________________________________________________________________________
1620 void AliITSAlignMille2::ConstrainModuleSubUnits(Int_t idm, Double_t val, UInt_t pattern)
1621 {
1622   // require that sum of modifications for the childs of this module is = val, i.e.
1623   // the internal corrections moves the module as a whole by fixed value (0 by default).
1624   // pattern is the bit pattern for the parameters to constrain
1625   //
1626   static TObjArray childs;
1627   childs.Clear();
1628   //
1629   // build list of childs for this module
1630   int nChilds = 0;
1631   AliITSAlignMille2Module* parent = GetMilleModule(idm);
1632   if (!parent) return;
1633   //
1634   for (int i=fNModules;i--;) {
1635     AliITSAlignMille2Module* child = GetMilleModule(i);
1636     if (child->GetParent() == parent) childs.AddAtAndExpand(child,nChilds++);
1637   }
1638   if (nChilds<1) return;
1639   //
1640   int npc = 0;
1641   for (int ip=0;ip<kNParCh;ip++) {
1642     if ( !((pattern>>ip)&0x1) /*|| !parent->IsFreeDOF(ip)*/) continue;
1643     ResetLocalEquation();
1644     for (int ich=nChilds;ich--;) fGlobalDerivatives[childs[ich]->GetUniqueID()*kNParCh+ip] = 1.0;
1645     AddConstraint(fGlobalDerivatives,val);
1646     npc++;
1647   }
1648   //
1649   AliInfo(Form("Constrained %d params for %d submodules of module #%d: %s",npc,nChilds,idm,parent->GetName()));
1650   //
1651 }
1652
1653 //_________________________________________________________________________
1654 void AliITSAlignMille2::PostConstrainModuleSubUnitsMedian(Int_t idm, Double_t val, UInt_t pattern)
1655 {
1656   // require that median of the modifications for the childs of this module is = val, i.e.
1657   // the internal corrections moves the module as a whole by fixed value (0 by default) 
1658   // module the outliers.
1659   // pattern is the bit pattern for the parameters to constrain
1660   // The difference between the mean and the median will be transfered to the parent
1661   //
1662   static TObjArray childs;
1663   childs.Clear();
1664   //
1665   // build list of childs for this module
1666   int nChilds = 0;
1667   AliITSAlignMille2Module* parent = GetMilleModule(idm);
1668   if (!parent) return;
1669   //
1670   for (int i=fNModules;i--;) {
1671     AliITSAlignMille2Module* child = GetMilleModule(i);
1672     if (child->GetParent() == parent) childs.AddAtAndExpand(child,nChilds++);
1673   }
1674   if (nChilds<1) return;
1675   //
1676   int npc = 0;
1677   double *deltas = fMillepede->GetDeltaPars();
1678   double *tmpArr = new double[nChilds]; 
1679   //
1680   for (int ip=0;ip<kNParCh;ip++) {
1681     if ( !((pattern>>ip)&0x1) /*|| !parent->IsFreeDOF(ip)*/) continue;
1682     // compute the median of the deltas
1683     for (int ich=nChilds;ich--;) tmpArr[ich] = deltas[childs[ich]->GetUniqueID()*kNParCh+ip];
1684     for (int ic0=0;ic0<nChilds;ic0++) // order the deltas 
1685       for (int ic1=ic0+1;ic1<nChilds;ic1++) 
1686         if (tmpArr[ic0]>tmpArr[ic1]) {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;}
1687     //
1688     int kmed = nChilds/2;
1689     double median = (tmpArr[kmed]+tmpArr[nChilds-kmed-1])/2.;
1690     //
1691     for (int ich=nChilds;ich--;) deltas[childs[ich]->GetUniqueID()*kNParCh+ip] -= median - val;
1692     deltas[parent->GetUniqueID()*kNParCh+ip] += median - val;
1693     npc++;
1694   }
1695   delete[] tmpArr;  
1696   //
1697   AliInfo(Form("Applied median constraint to %d params for %d submodules of module #%d: %s",npc,nChilds,idm,parent->GetName()));
1698   //
1699 }
1700
1701 //_________________________________________________________________________
1702 void AliITSAlignMille2::ConstrainOrphans(Double_t val, UInt_t pattern)
1703 {
1704   // require that median of the modifications for the supermodules which have no parents is = val, i.e.
1705   // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.
1706   // pattern is the bit pattern for the parameters to constrain
1707   //
1708   static TObjArray modSet;
1709   modSet.Clear();
1710   //
1711   // build list of childs for this module
1712   int nModules = 0;
1713   int *nFree = new int[kNParCh];
1714   for (int i=0;i<kNParCh;i++) nFree[i] = 0;
1715   //
1716   for (int i=fNModules;i--;) {
1717     AliITSAlignMille2Module* module = GetMilleModule(i);
1718     if (module->GetParent()) continue;   // skip this    
1719     for (int ip=0;ip<kNParCh;ip++) if ( ((pattern>>ip)&0x1) && module->IsFreeDOF(ip)) nFree[ip]++;
1720     modSet.AddAtAndExpand(module,nModules++);
1721   }
1722   if (nModules<1) return;
1723   //
1724   int npc = 0;
1725   for (int ip=0;ip<kNParCh;ip++) {
1726     if (nFree[ip]<1) continue; // nothing to do
1727     ResetLocalEquation();
1728     for (int ich=nModules;ich--;) {
1729       AliITSAlignMille2Module* module = (AliITSAlignMille2Module*) modSet[ich];
1730       if ( !((pattern>>ip)&0x1) || !module->IsFreeDOF(ip)) continue;
1731       fGlobalDerivatives[module->GetUniqueID()*kNParCh+ip] = 1.0;
1732     }
1733     AddConstraint(fGlobalDerivatives,val);
1734     npc++;
1735   }
1736   //
1737   delete[] nFree;
1738   AliInfo(Form("Constrained %d params for %d orphan modules",npc,nModules));
1739   //
1740 }
1741 //_________________________________________________________________________
1742 void AliITSAlignMille2::PostConstrainOrphansMedian(Double_t val, UInt_t pattern)
1743 {
1744   // require that sum of modifications for the supermodules which have no parents is = val, i.e.
1745   // the corrections moves the whole setup by fixed value (0 by default).
1746   // pattern is the bit pattern for the parameters to constrain
1747   //
1748   static TObjArray modSet;
1749   modSet.Clear();
1750   //
1751   // build list of childs for this module
1752   int nModules = 0;
1753   int *nFree = new int[kNParCh];
1754   for (int i=0;i<kNParCh;i++) nFree[i] = 0;
1755   //
1756   for (int i=fNModules;i--;) {
1757     AliITSAlignMille2Module* module = GetMilleModule(i);
1758     if (module->GetParent()) continue;   // skip this    
1759     for (int ip=0;ip<kNParCh;ip++) if ( ((pattern>>ip)&0x1) && module->IsFreeDOF(ip)) nFree[ip]++;
1760     modSet.AddAtAndExpand(module,nModules++);
1761   }
1762   if (nModules<1) return;
1763   //
1764   int npc = 0;
1765   double *deltas = fMillepede->GetDeltaPars();
1766   double *tmpArr = new double[nModules]; 
1767   //
1768   for (int ip=0;ip<kNParCh;ip++) {
1769     if (nFree[ip]<1) continue; // nothing to do
1770     // compute the median of the deltas
1771     for (int ich=nModules;ich--;) tmpArr[ich] = deltas[modSet[ich]->GetUniqueID()*kNParCh+ip];
1772     for (int ic0=0;ic0<nModules;ic0++) // order the deltas 
1773       for (int ic1=ic0+1;ic1<nModules;ic1++) 
1774         if (tmpArr[ic0]>tmpArr[ic1])  {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;};
1775     //
1776     int kmed = nModules/2;
1777     double median = (tmpArr[kmed]+tmpArr[nModules-kmed-1])/2.;
1778     //    
1779     for (int ich=nModules;ich--;) {
1780       AliITSAlignMille2Module* module = (AliITSAlignMille2Module*) modSet[ich];
1781       if ( !((pattern>>ip)&0x1) || !module->IsFreeDOF(ip)) continue;
1782       deltas[module->GetUniqueID()*kNParCh+ip] -= median - val;
1783     }
1784     npc++;
1785   }
1786   //
1787   delete[] nFree;
1788   delete[] tmpArr;
1789   AliInfo(Form("Applied median constraint to %d params for %d orphan modules",npc,nModules));
1790   //
1791 }
1792
1793 //_________________________________________________________________________
1794 void AliITSAlignMille2::ConstrainLinComb(const Int_t *vidLst, const Float_t *wghLst, Int_t nmd, Double_t val, UInt_t pattern)
1795 {
1796   // require that the linear combinations of the nmd modules (refered by their volume ID) from the 
1797   // modList with the coefficients wghLst adds up to val.
1798   // pattern is the bit pattern for the parameters to constrain.
1799   //
1800   static TObjArray modSet;
1801   modSet.Clear();
1802   //
1803   // build list of childs for this module
1804   int nModules = 0;
1805   int *nFree = new int[kNParCh];
1806   for (int i=0;i<kNParCh;i++) nFree[i] = 0;
1807   //
1808   for (int imd=nmd;imd--;) {
1809     UShort_t vid = (UShort_t)vidLst[imd];
1810     for (int i=fNModules;i--;) {
1811       AliITSAlignMille2Module* module = GetMilleModule(i);
1812       if (module->GetVolumeID() == vid) {
1813         modSet.AddAtAndExpand(module,nModules++);
1814         for (int ip=0;ip<kNParCh;ip++) if ( ((pattern>>ip)&0x1) && module->IsFreeDOF(ip)) nFree[ip]++;
1815         break;
1816       }
1817     }
1818   }
1819   //
1820   if (nModules != nmd) {
1821     AliInfo(Form("Error: constraint for %d modules requested but %d are found",nmd,nModules));
1822     delete[] nFree;
1823     return;
1824   }
1825   int npc = 0;
1826   for (int ip=0;ip<kNParCh;ip++) {
1827     if (nFree[ip]<1) continue; // nothing to do
1828     ResetLocalEquation();
1829     for (int ich=nModules;ich--;) {
1830       AliITSAlignMille2Module* module = (AliITSAlignMille2Module*) modSet[ich];
1831       if ( !((pattern>>ip)&0x1) || !module->IsFreeDOF(ip)) continue;
1832       fGlobalDerivatives[module->GetUniqueID()*kNParCh+ip] = wghLst[ich];
1833     }
1834     AddConstraint(fGlobalDerivatives,val);
1835     npc++;
1836   }
1837   //
1838   delete[] nFree;
1839   AliInfo(Form("Constrained %d params for linerar combination of %d  modules",npc,nModules));
1840   //
1841 }
1842