-/**************************************************************************\r
- * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. *\r
- * *\r
- * Author: The ALICE Off-line Project. *\r
- * Contributors are mentioned in the code where appropriate. *\r
- * *\r
- * Permission to use, copy, modify and distribute this software and its *\r
- * documentation strictly for non-commercial purposes is hereby granted *\r
- * without fee, provided that the above copyright notice appears in all *\r
- * copies and that both the copyright notice and this permission notice *\r
- * appear in the supporting documentation. The authors make no claims *\r
- * about the suitability of this software for any purpose. It is *\r
- * provided "as is" without express or implied warranty. *\r
- **************************************************************************/\r
-\r
-/* $Id$ */\r
-\r
-//-----------------------------------------------------------------------------\r
-//\r
-// Interface to AliMillePede2 alignment class for the ALICE ITS detector\r
-// \r
-// ITS specific alignment class which interface to AliMillepede. \r
-// For each track ProcessTrack calculates the local and global derivatives\r
-// at each hit and fill the corresponding local equations. Provide methods for\r
-// fixing or constraining detection elements for best results. \r
-// \r
-// author M. Lunardon (thanks to J. Castillo), ruben.shahoyan@cern.ch\r
-//-----------------------------------------------------------------------------\r
-\r
-#include <TFile.h>\r
-#include <TClonesArray.h>\r
-#include <TMath.h>\r
-#include <TVirtualFitter.h>\r
-#include <TGeoManager.h>\r
-#include <TArrayI.h>\r
-#include <TSystem.h>\r
-#include "AliITSAlignMille2.h"\r
-#include "AliITSgeomTGeo.h"\r
-#include "AliGeomManager.h"\r
-#include "AliMillePede2.h"\r
-#include "AliTrackPointArray.h"\r
-#include "AliAlignObjParams.h"\r
-#include "AliLog.h"\r
-#include "AliTrackFitterRieman.h"\r
-#include "AliITSAlignMille2Constraint.h"\r
-#include "AliITSAlignMille2ConstrArray.h"\r
-#include "AliITSresponseSDD.h"\r
-\r
-ClassImp(AliITSAlignMille2)\r
-\r
-const Char_t* AliITSAlignMille2::kRecKeys[] = {\r
- "GEOMETRY_FILE",\r
- "SUPERMODULE_FILE",\r
- "CONSTRAINTS_REFERENCE_FILE",\r
- "PREALIGNMENT_FILE",\r
- "PRECALIBSDD_FILE",\r
- "INITCALBSDD_FILE",\r
- "SET_GLOBAL_DELTAS",\r
- "CONSTRAINT_LOCAL",\r
- "MODULE_VOLUID",\r
- "MODULE_INDEX",\r
- "SET_PSEUDO_PARENTS",\r
- "SET_TRACK_FIT_METHOD",\r
- "SET_MINPNT_TRA",\r
- "SET_NSTDDEV",\r
- "SET_RESCUT_INIT",\r
- "SET_RESCUT_OTHER",\r
- "SET_LOCALSIGMAFACTOR",\r
- "SET_STARTFAC",\r
- "SET_B_FIELD",\r
- "SET_SPARSE_MATRIX",\r
- "REQUIRE_POINT",\r
- "CONSTRAINT_ORPHANS",\r
- "CONSTRAINT_SUBUNITS",\r
- "APPLY_CONSTRAINT"\r
-};\r
-\r
-\r
-//========================================================================================================\r
-\r
-AliITSAlignMille2* AliITSAlignMille2::fgInstance = 0; \r
-Int_t AliITSAlignMille2::fgInstanceID = 0;\r
-\r
-//________________________________________________________________________________________________________\r
-AliITSAlignMille2::AliITSAlignMille2(const Char_t *configFilename ) \r
-: TObject(),\r
- fMillepede(0),\r
- fStartFac(16.), \r
- fResCutInitial(100.), \r
- fResCut(100.),\r
- fNGlobal(0),\r
- fNLocal(4),\r
- fNStdDev(3),\r
- fIsMilleInit(kFALSE),\r
- fAllowPseudoParents(kFALSE),\r
- //\r
- fCurrentModule(0),\r
- fTrack(0),\r
- fTrackBuff(0),\r
- fCluster(),\r
- fGlobalDerivatives(0), \r
- //\r
- fMinNPtsPerTrack(3),\r
- fInitTrackParamsMeth(1),\r
- fTotBadLocEqPoints(0),\r
- fRieman(0),\r
- //\r
- fConstraints(0),\r
- //\r
- fUseGlobalDelta(kFALSE),\r
- fRequirePoints(kFALSE),\r
- fTempExcludedModule(-1),\r
- //\r
- fGeometryFileName("geometry.root"),\r
- fPreAlignmentFileName(""),\r
- fConstrRefFileName(""),\r
- fGeoManager(0),\r
- fIsConfigured(kFALSE),\r
- fPreAlignQF(0),\r
-//\r
- fCorrectSDD(0),\r
- fInitialRecSDD(0),\r
- fPrealignment(0),\r
- fConstrRef(0),\r
- fMilleModule(2),\r
- fSuperModule(2),\r
- fNModules(0),\r
- fNSuperModules(0),\r
- fUsePreAlignment(kFALSE),\r
- fBOn(kFALSE),\r
- fBField(0.0),\r
- fBug(0),\r
- fMilleVersion(2)\r
-{\r
- /// main constructor that takes input from configuration file\r
- for (int i=3;i--;) fSigmaFactor[i] = 1.0;\r
- //\r
- // new RS\r
- for (Int_t i=0; i<6; i++) {\r
- fNReqLayUp[i]=0;\r
- fNReqLayDown[i]=0;\r
- fNReqLay[i]=0;\r
- }\r
- for (Int_t i=0; i<3; i++) {\r
- fNReqDetUp[i]=0;\r
- fNReqDetDown[i]=0;\r
- fNReqDet[i]=0;\r
- }\r
- //\r
- Int_t lc=LoadConfig(configFilename);\r
- if (lc) {\r
- AliError(Form("Error %d loading configuration from %s",lc,configFilename));\r
- exit(1);\r
- }\r
- //\r
- fMillepede = new AliMillePede2(); \r
- fgInstance = this;\r
- fgInstanceID++;\r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-AliITSAlignMille2::~AliITSAlignMille2()\r
-{\r
- /// Destructor\r
- if (fMillepede) delete fMillepede; fMillepede = 0;\r
- if (fGlobalDerivatives) delete[] fGlobalDerivatives; fGlobalDerivatives = 0;\r
- if (fRieman) delete fRieman; fRieman = 0;\r
- if (fPrealignment) delete fPrealignment; fPrealignment = 0;\r
- if (fConstrRef) delete fConstrRef; fConstrRef = 0;\r
- if (fCorrectSDD) delete fCorrectSDD; fCorrectSDD = 0;\r
- if (fInitialRecSDD) delete fInitialRecSDD; fInitialRecSDD = 0;\r
- fTrackBuff.Delete();\r
- fConstraints.Delete();\r
- fMilleModule.Delete();\r
- fSuperModule.Delete();\r
- if (--fgInstanceID==0) fgInstance = 0;\r
-}\r
-\r
-///////////////////////////////////////////////////////////////////////\r
-\r
-\r
-TObjArray* AliITSAlignMille2::GetConfigRecord(FILE* stream, TString& recTitle, TString& recOpt, Bool_t rew)\r
-{\r
- // read new record from config file\r
- TString record;\r
- static TObjArray* recElems = 0;\r
- if (recElems) {delete recElems; recElems = 0;}\r
- //\r
- TString keyws = recTitle;\r
- if (!keyws.IsNull()) {\r
- keyws.ToUpper();\r
- // keyws += " ";\r
- }\r
- while (record.Gets(stream)) {\r
- int cmt=record.Index("#"); \r
- if (cmt>=0) record.Remove(cmt); // skip comment\r
- record.ReplaceAll("\t"," ");\r
- record.ReplaceAll("\r"," ");\r
- record.Remove(TString::kBoth,' '); \r
- if (record.IsNull()) continue; // nothing to decode \r
- if (!keyws.IsNull() && !record.BeginsWith(keyws.Data())) continue; // specific record was requested\r
- //\r
- recElems = record.Tokenize(" ");\r
- recTitle = recElems->At(0)->GetName();\r
- recTitle.ToUpper();\r
- recOpt = recElems->GetLast()>0 ? recElems->At(1)->GetName() : "";\r
- break;\r
- }\r
- if (rew || !recElems) rewind(stream);\r
- return recElems;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::CheckConfigRecords(FILE* stream)\r
-{ \r
- TString record,recTitle;\r
- int lineCnt = 0;\r
- rewind(stream);\r
- while (record.Gets(stream)) {\r
- int cmt=record.Index("#"); \r
- lineCnt++;\r
- if (cmt>=0) record.Remove(cmt); // skip comment\r
- record.ReplaceAll("\t"," ");\r
- record.ReplaceAll("\r"," ");\r
- record.Remove(TString::kBoth,' ');\r
- if (record.IsNull()) continue; // nothing to decode \r
- // extract keyword\r
- int spc = record.Index(" ");\r
- if (spc>0) recTitle = record(0,spc);\r
- else recTitle = record;\r
- recTitle.ToUpper();\r
- Bool_t strOK = kFALSE;\r
- for (int ik=kNKeyWords;ik--;) if (recTitle == kRecKeys[ik]) {strOK = kTRUE; break;}\r
- if (strOK) continue;\r
- //\r
- AliError(Form("Unknown keyword %s at line %d",\r
- recTitle.Data(),lineCnt));\r
- return -1;\r
- //\r
- }\r
- //\r
- rewind(stream);\r
- return 0;\r
-}\r
-\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::LoadConfig(const Char_t *cfile)\r
-{ \r
- // return 0 if success\r
- // 1 if error in module index or voluid\r
- //\r
- FILE *pfc=fopen(cfile,"r");\r
- if (!pfc) return -1;\r
- //\r
- TString record,recTitle,recOpt,recExt;\r
- Int_t nrecElems,irec;\r
- TObjArray *recArr=0;\r
- //\r
- fNModules = 0;\r
- Bool_t stopped = kFALSE;\r
- //\r
- if (CheckConfigRecords(pfc)<0) return -1;\r
- //\r
- while(1) { \r
- //\r
- // ============= 1: we read some obligatory records in predefined order ================\r
- // \r
- recTitle = kRecKeys[kGeomFile];\r
- if ( !GetConfigRecord(pfc,recTitle,recOpt,1) || \r
- (fGeometryFileName=recOpt).IsNull() || \r
- gSystem->AccessPathName(recOpt.Data()) ||\r
- InitGeometry() )\r
- { AliError("Failed to find/load Geometry"); stopped = kTRUE; break;}\r
- //\r
- recTitle = kRecKeys[kSuperModileFile];\r
- if ( !GetConfigRecord(pfc,recTitle,recOpt,1) || \r
- recOpt.IsNull() || \r
- gSystem->AccessPathName(recOpt.Data()) ||\r
- LoadSuperModuleFile(recOpt.Data()))\r
- { AliError("Failed to find/load SuperModules"); stopped = kTRUE; break;}\r
- //\r
- recTitle = kRecKeys[kConstrRefFile]; // LOCAL_CONSTRAINTS are defined wrt these deltas\r
- if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) {\r
- if (recOpt.IsNull() || recOpt=="IDEAL") SetConstraintWrtRef( "IDEAL" );\r
- else if (gSystem->AccessPathName(recOpt.Data()) || SetConstraintWrtRef(recOpt.Data()) )\r
- { AliError("Failed to load reference deltas for local constraints"); stopped = kTRUE; break;}\r
- }\r
- // \r
- recTitle = kRecKeys[kPrealignFile];\r
- if ( GetConfigRecord(pfc,recTitle,recOpt,1) )\r
- if ( (fPreAlignmentFileName=recOpt).IsNull() || \r
- gSystem->AccessPathName(recOpt.Data()) ||\r
- ApplyToGeometry()) \r
- { AliError(Form("Failed to load Prealignment file %s",recOpt.Data())); stopped = kTRUE; break;}\r
- //\r
- recTitle = kRecKeys[kPreCalSDDFile];\r
- if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) {\r
- if ( recOpt.IsNull() || gSystem->AccessPathName(recOpt.Data()) ) {stopped = kTRUE; break;}\r
- AliInfo(Form("Using %s for SDD precalibration",recOpt.Data()));\r
- TFile* precfi = TFile::Open(recOpt.Data());\r
- if (!precfi->IsOpen()) {stopped = kTRUE; break;}\r
- fCorrectSDD = (AliITSresponseSDD*)precfi->Get("AliITSresponseSDD");\r
- precfi->Close();\r
- delete precfi;\r
- if (!fCorrectSDD) {AliError("Precalibration SDD object is not found"); stopped = kTRUE; break;}\r
- }\r
- //\r
- recTitle = kRecKeys[ kInitCalSDDFile ];\r
- if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) {\r
- if ( recOpt.IsNull() || gSystem->AccessPathName(recOpt.Data()) ) {stopped = kTRUE; break;}\r
- AliInfo(Form("Using %s as SDD calibration used in TrackPoints",recOpt.Data()));\r
- TFile* precf = TFile::Open(recOpt.Data());\r
- if (!precf->IsOpen()) {stopped = kTRUE; break;}\r
- fInitialRecSDD = (AliITSresponseSDD*)precf->Get("AliITSresponseSDD");\r
- precf->Close();\r
- delete precf;\r
- if (!fInitialRecSDD) {AliError("Initial Calibration SDD object is not found"); stopped = kTRUE; break;}\r
- }\r
- //\r
- recTitle = kRecKeys[ kGlobalDeltas ];\r
- if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) SetUseGlobalDelta(kTRUE);\r
- //\r
- // =========== 2: see if there are local gaussian constraints defined =====================\r
- // Note that they should be loaded before the modules declaration\r
- //\r
- recTitle = kRecKeys[ kConstrLocal ];\r
- while( (recArr=GetConfigRecord(pfc,recTitle,recOpt,0)) ) {\r
- nrecElems = recArr->GetLast()+1;\r
- if (recOpt.IsFloat()) {stopped = kTRUE; break;} // wrong name\r
- if (GetConstraint(recOpt.Data())) {\r
- AliError(Form("Existing constraint %s repeated",recOpt.Data()));\r
- stopped = kTRUE; break;\r
- }\r
- recExt = recArr->At(2)->GetName();\r
- if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
- double val = recExt.Atof(); \r
- recExt = recArr->At(3)->GetName();\r
- if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
- double err = recExt.Atof(); \r
- int nwgh = nrecElems - 4;\r
- double *wgh = new double[nwgh];\r
- for (nwgh=0,irec=4;irec<nrecElems;irec++) {\r
- recExt = recArr->At(irec)->GetName();\r
- if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
- wgh[nwgh++] = recExt.Atof();\r
- }\r
- if (stopped) {delete[] wgh; break;}\r
- //\r
- ConstrainLocal(recOpt.Data(),wgh,nwgh,val,err);\r
- delete[] wgh;\r
- //\r
- } // end while for loop over local constraints\r
- if (stopped) break;\r
- //\r
- // =========== 3: now read modules to align ===================================\r
- //\r
- rewind(pfc);\r
- while( (recArr=GetConfigRecord(pfc,recTitle="",recOpt,0)) ) {\r
- if (!(recTitle==kRecKeys[ kModVolID ] || recTitle==kRecKeys[ kModIndex ])) continue;\r
- // Expected format: MODULE id tolX tolY tolZ tolPsi tolTh tolPhi [[sigX sigY sigZ] extra params]\r
- // where tol* is the tolerance (sigma) for given DOF. 0 means fixed\r
- // sig* is the scaling parameters for the errors of the clusters of this module\r
- // extra params are defined for specific modules, e.g. t0 and vdrift corrections of SDD\r
- //\r
- nrecElems = recArr->GetLast()+1;\r
- if (nrecElems<2 || !recOpt.IsDigit()) {stopped = kTRUE; break;}\r
- int idx = recOpt.Atoi(); \r
- UShort_t voluid = (idx<=kMaxITSSensID) ? GetModuleVolumeID(idx) : idx;\r
- AliITSAlignMille2Module* mod = 0;\r
- //\r
- if (voluid>=kMinITSSupeModuleID) { // custom supermodule\r
- for (int j=0; j<fNSuperModules; j++) {\r
- if (voluid==GetSuperModule(j)->GetVolumeID()) {\r
- mod = new AliITSAlignMille2Module(*GetSuperModule(j));\r
- // the matrix might be updated in case some prealignment was applied, check \r
- TGeoHMatrix* mup = AliGeomManager::GetMatrix(mod->GetName());\r
- if (mup) *(mod->GetMatrix()) = *mup;\r
- fMilleModule.AddAtAndExpand(mod,fNModules);\r
- break;\r
- } \r
- }\r
- }\r
- else if (idx<=kMaxITSSensVID) {\r
- mod = new AliITSAlignMille2Module(voluid);\r
- fMilleModule.AddAtAndExpand(mod,fNModules);\r
- }\r
- if (!mod) {stopped = kTRUE; break;} // bad volid\r
- //\r
- // geometry variation settings\r
- for (int i=0;i<AliITSAlignMille2Module::kMaxParGeom;i++) {\r
- irec = i+2;\r
- if (irec >= nrecElems) break;\r
- recExt = recArr->At(irec)->GetName();\r
- if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
- mod->SetFreeDOF(i, recExt.Atof() ); \r
- }\r
- if (stopped) break;\r
- //\r
- // scaling factors for cluster errors\r
- // first set default ones\r
- for (int i=0;i<3;i++) mod->SetSigmaFactor(i, fSigmaFactor[i]); \r
- for (int i=0;i<3;i++) {\r
- irec = i+8;\r
- if (irec >= nrecElems) break;\r
- recExt = recArr->At(irec)->GetName();\r
- if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
- mod->SetSigmaFactor(i, recExt.Atof() ); \r
- } \r
- if (stopped) break;\r
- //\r
- mod->SetGeomParamsGlobal(fUseGlobalDelta);\r
- // now comes special detectors treatment\r
- if (mod->IsSDD()) {\r
- double vl = 0;\r
- if (nrecElems>11) {\r
- recExt = recArr->At(11)->GetName();\r
- if (recExt.IsFloat()) vl = recExt.Atof();\r
- else {stopped = kTRUE; break;}\r
- irec = 11;\r
- }\r
- mod->SetFreeDOF(AliITSAlignMille2Module::kDOFT0,vl);\r
- //\r
- vl = 0;\r
- if (nrecElems>12) {\r
- recExt = recArr->At(12)->GetName();\r
- if (recExt.IsFloat()) vl = recExt.Atof();\r
- else {stopped = kTRUE; break;}\r
- irec = 12;\r
- }\r
- mod->SetFreeDOF(AliITSAlignMille2Module::kDOFDV,vl);\r
- }\r
- //\r
- mod->SetUniqueID(fNModules);\r
- mod->EvaluateDOF();\r
- fNModules++;\r
- //\r
- // now check if there are local constraints on this module\r
- for (++irec;irec<nrecElems;irec++) {\r
- recExt = recArr->At(irec)->GetName();\r
- if (recExt.IsFloat()) {stopped=kTRUE;break;}\r
- AliITSAlignMille2ConstrArray* cstr = (AliITSAlignMille2ConstrArray*)GetConstraint(recExt.Data());\r
- if (!cstr) {\r
- AliInfo(Form("No Local constraint %s was declared",recExt.Data())); \r
- stopped=kTRUE; \r
- break;\r
- }\r
- cstr->AddModule(mod);\r
- }\r
- if (stopped) break;\r
- } // end while for loop over modules\r
- if (stopped) break;\r
- //\r
- if (fNModules==0) {AliError("Failed to find any MODULE"); stopped = kTRUE; break;} \r
- BuildHierarchy(); // preprocess loaded modules\r
- //\r
- // =========== 4: the rest may come in arbitrary order =======================================\r
- rewind(pfc);\r
- while ( (recArr=GetConfigRecord(pfc,recTitle="",recOpt,0))!=0 ) {\r
- //\r
- nrecElems = recArr->GetLast()+1;\r
- //\r
- // some simple flags -----------------------------------------------------------------------\r
- //\r
- if (recTitle == kRecKeys[ kPseudoParents ]) SetAllowPseudoParents(kTRUE);\r
- //\r
- // some optional parameters ----------------------------------------------------------------\r
- else if (recTitle == kRecKeys[ kTrackFitMethod ]) {\r
- if (recOpt.IsNull() || !recOpt.IsDigit() ) {stopped = kTRUE; break;}\r
- SetInitTrackParamsMeth(recOpt.Atoi());\r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kMinPntTrack ]) {\r
- if (recOpt.IsNull() || !recOpt.IsDigit() ) {stopped = kTRUE; break;}\r
- fMinNPtsPerTrack = recOpt.Atoi();\r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kNStDev ]) {\r
- if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
- fNStdDev = (Int_t)recOpt.Atof();\r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kResCutInit ]) {\r
- if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
- fResCutInitial = recOpt.Atof();\r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kResCutOther ]) {\r
- if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
- fResCut = recOpt.Atof();\r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kLocalSigFactor ]) { //-------------------------\r
- for (irec=0;irec<3;irec++) if (nrecElems>irec+1) {\r
- fSigmaFactor[irec] = ((TObjString*)recArr->At(irec+1))->GetString().Atof();\r
- if (fSigmaFactor[irec]<=0.) stopped = kTRUE;\r
- }\r
- if (stopped) break; \r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kStartFactor ]) { //-------------------------\r
- if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
- fStartFac = recOpt.Atof();\r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kBField ]) { //-------------------------\r
- if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}\r
- fBField = recOpt.Atof();\r
- if (fBField>0) {\r
- fBOn = kTRUE;\r
- fNLocal = 5; // helices\r
- fRieman = new AliTrackFitterRieman();\r
- } \r
- else {\r
- fBField = 0.0;\r
- fBOn = kFALSE;\r
- fNLocal = 4;\r
- }\r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kSparseMatrix ]) { // matrix solver type\r
- //\r
- AliMillePede2::SetGlobalMatSparse(kTRUE);\r
- if (recOpt.IsNull()) continue;\r
- // solver type and settings\r
- if (recOpt == "MINRES") AliMillePede2::SetIterSolverType( AliMinResSolve::kSolMinRes );\r
- else if (recOpt == "FGMRES") AliMillePede2::SetIterSolverType( AliMinResSolve::kSolFGMRes );\r
- else {stopped = kTRUE; break;}\r
- //\r
- if (nrecElems>=3) { // preconditioner type\r
- recExt = recArr->At(2)->GetName();\r
- if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
- AliMillePede2::SetMinResPrecondType( recExt.Atoi() );\r
- }\r
- //\r
- if (nrecElems>=4) { // tolerance\r
- recExt = recArr->At(3)->GetName();\r
- if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
- AliMillePede2::SetMinResTol( recExt.Atof() );\r
- }\r
- //\r
- if (nrecElems>=5) { // maxIter\r
- recExt = recArr->At(4)->GetName();\r
- if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
- AliMillePede2::SetMinResMaxIter( recExt.Atoi() );\r
- } \r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kRequirePoint ]) { //-------------------------\r
- // syntax: REQUIRE_POINT where ndet updw nreqpts\r
- // where = LAYER or DETECTOR\r
- // ndet = detector number: 1-6 for LAYER and 1-3 for DETECTOR (SPD=1, SDD=2, SSD=3)\r
- // updw = 1 for Y>0, -1 for Y<0, 0 if not specified\r
- // nreqpts = minimum number of points of that type\r
- if (nrecElems>=5) {\r
- recOpt.ToUpper();\r
- int lr = ((TObjString*)recArr->At(2))->GetString().Atoi() - 1;\r
- int hb = ((TObjString*)recArr->At(3))->GetString().Atoi();\r
- int np = ((TObjString*)recArr->At(4))->GetString().Atoi();\r
- fRequirePoints = kTRUE;\r
- if (recOpt == "LAYER") {\r
- if (lr<0 || lr>5) {stopped = kTRUE; break;}\r
- if (hb>0) fNReqLayUp[lr] = np;\r
- else if (hb<0) fNReqLayDown[lr] = np;\r
- else fNReqLay[lr] = np;\r
- }\r
- else if (recOpt == "DETECTOR") {\r
- if (lr<0 || lr>2) {stopped = kTRUE; break;}\r
- if (hb>0) fNReqDetUp[lr] = np;\r
- else if (hb<0) fNReqDetDown[lr] = np;\r
- else fNReqDet[lr] = np;\r
- }\r
- else {stopped = kTRUE; break;}\r
- }\r
- else {stopped = kTRUE; break;}\r
- }\r
- //\r
- // global constraints on the subunits/orphans \r
- else if (recTitle == kRecKeys[ kConstrOrphans ]) { //------------------------\r
- // expect CONSTRAINT_ORPHANS MEAN/MEDIAN Value parID0 ... parID1 ...\r
- if (nrecElems<4) {stopped = kTRUE; break;}\r
- recExt = recArr->At(2)->GetName();\r
- if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
- double val = recExt.Atof();\r
- UInt_t pattern = 0;\r
- for (irec=3;irec<nrecElems;irec++) { // read params to constraint\r
- recExt = recArr->At(irec)->GetName();\r
- if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
- pattern |= 0x1 << recExt.Atoi();\r
- }\r
- if (stopped) break;\r
- if (recOpt == "MEAN") ConstrainOrphansMean(val,pattern);\r
- else if (recOpt == "MEDIAN") ConstrainOrphansMedian(val,pattern);\r
- else {stopped = kTRUE; break;}\r
- }\r
- //\r
- else if (recTitle == kRecKeys[ kConstrSubunits ]) { //------------------------\r
- // expect ONSTRAINT_SUBUNITS MEAN/MEDIAN Value parID0 ... parID1 ... VolID1 ... VolIDn - VolIDm\r
- if (nrecElems<5) {stopped = kTRUE; break;}\r
- recExt = recArr->At(2)->GetName();\r
- if (!recExt.IsFloat()) {stopped = kTRUE; break;}\r
- double val = recExt.Atof();\r
- UInt_t pattern = 0;\r
- for (irec=3;irec<nrecElems;irec++) { // read params to constraint\r
- recExt = recArr->At(irec)->GetName();\r
- if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
- int parid = recExt.Atoi();\r
- if (parid<kMaxITSSensID) pattern |= 0x1 << recExt.Atoi();\r
- else break; // list of params is over \r
- }\r
- if (stopped) break;\r
- //\r
- Bool_t meanC;\r
- if (recOpt == "MEAN") meanC = kTRUE;\r
- else if (recOpt == "MEDIAN") meanC = kFALSE;\r
- else {stopped = kTRUE; break;}\r
- //\r
- int curID = -1;\r
- int rangeStart = -1;\r
- for (;irec<nrecElems;irec++) { // read modules to apply this constraint\r
- recExt = recArr->At(irec)->GetName();\r
- if (recExt == "-") {rangeStart = curID; continue;} // range is requested\r
- else if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
- else curID = recExt.Atoi();\r
- //\r
- if (curID<=kMaxITSSensID) curID = GetModuleVolumeID(curID);\r
- // this was a range start or single \r
- int start;\r
- if (rangeStart>=0) {start = rangeStart+1; rangeStart=-1;} // continue the range\r
- else start = curID; // create constraint either for single module (or 1st in the range)\r
- for (int id=start;id<=curID;id++) {\r
- int id0 = IsVIDDefined(id);\r
- if (id0<0) {AliDebug(3,Form("Undefined module %d requested in the SubUnits constraint, skipping",id)); continue;}\r
- if (meanC) ConstrainModuleSubUnitsMean(id0,val,pattern);\r
- else ConstrainModuleSubUnitsMedian(id0,val,pattern);\r
- }\r
- }\r
- if (rangeStart>=0) stopped = kTRUE; // unfinished range\r
- if (stopped) break;\r
- } \r
- // \r
- // association of modules with local constraints\r
- else if (recTitle == kRecKeys[ kApplyConstr ]) { //------------------------\r
- // expect APPLY_CONSTRAINT NAME [NAME1...] [VolID1 ... VolIDn - VolIDm]\r
- if (nrecElems<3) {stopped = kTRUE; break;}\r
- int nmID0=-1,nmID1=-1;\r
- for (irec=1;irec<nrecElems;irec++) { // find the range of constraint names\r
- recExt = recArr->At(irec)->GetName();\r
- if (recExt.IsFloat()) break;\r
- // check if such a constraint was declared\r
- if (!GetConstraint(recExt.Data())) {\r
- AliInfo(Form("No Local constraint %s was declared",recExt.Data())); \r
- stopped=kTRUE; \r
- break;\r
- }\r
- if (nmID0<0) nmID0 = irec;\r
- nmID1 = irec;\r
- }\r
- if (stopped) break;\r
- //\r
- if (irec>=nrecElems) {stopped = kTRUE; break;} // no modules provided\r
- //\r
- // now read the list of modules to constrain\r
- int curID = -1;\r
- int rangeStart = -1;\r
- for (;irec<nrecElems;irec++) { // read modules to apply this constraint\r
- recExt = recArr->At(irec)->GetName();\r
- if (recExt == "-") {rangeStart = curID; continue;} // range is requested\r
- else if (!recExt.IsDigit()) {stopped = kTRUE; break;}\r
- else curID = recExt.Atoi();\r
- //\r
- if (curID<=kMaxITSSensID) curID = GetModuleVolumeID(curID);\r
- //\r
- // this was a range start or single \r
- int start;\r
- if (rangeStart>=0) {start = rangeStart+1; rangeStart=-1;} // continue the range\r
- else start = curID; // create constraint either for single module (or 1st in the range)\r
- for (int id=start;id<=curID;id++) {\r
- AliITSAlignMille2Module *md = GetMilleModuleByVID(id);\r
- if (!md) {AliDebug(3,Form("Undefined module %d requested in the Local constraint, skipping",id)); continue;}\r
- for (int nmid=nmID0;nmid<=nmID1;nmid++) \r
- ((AliITSAlignMille2ConstrArray*)GetConstraint(recArr->At(nmid)->GetName()))->AddModule(md);\r
- }\r
- }\r
- if (rangeStart>=0) stopped = kTRUE; // unfinished range\r
- if (stopped) break;\r
- }\r
- //\r
- else continue; // already processed record\r
- //\r
- } // end of while loop 4 over the various params \r
- //\r
- break;\r
- } // end of while(1) loop \r
- //\r
- fclose(pfc);\r
- if (stopped) {\r
- AliError(Form("Failed on record %s %s ...\n",recTitle.Data(),recOpt.Data()));\r
- return -1;\r
- }\r
- //\r
- fIsConfigured = kTRUE;\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::BuildHierarchy()\r
-{\r
- // build the hieararhy of the modules to align\r
- //\r
- if (!GetUseGlobalDelta() && PseudoParentsAllowed()) {\r
- AliInfo("PseudoParents mode is allowed only when the deltas are global\n"\r
- "Since Deltas are local, switching to NoPseudoParents");\r
- SetAllowPseudoParents(kFALSE);\r
- }\r
- // set parent/child relationship for modules to align\r
- AliInfo("Setting parent/child relationships\n");\r
- //\r
- // 1) child -> parent reference\r
- for (int ipar=0;ipar<fNModules;ipar++) {\r
- AliITSAlignMille2Module* parent = GetMilleModule(ipar);\r
- if (parent->IsSensor()) continue; // sensor cannot be a parent\r
- //\r
- for (int icld=0;icld<fNModules;icld++) {\r
- if (icld==ipar) continue;\r
- AliITSAlignMille2Module* child = GetMilleModule(icld);\r
- if (!child->BelongsTo(parent)) continue;\r
- // child cannot have more sensors than the parent\r
- if (child->GetNSensitiveVolumes() > parent->GetNSensitiveVolumes()) continue;\r
- //\r
- AliITSAlignMille2Module* parOld = child->GetParent();\r
- // is this parent candidate closer than the old parent ? \r
- if (parOld && parOld->GetNSensitiveVolumes()<parent->GetNSensitiveVolumes()) continue; // parOld is closer\r
- child->SetParent(parent);\r
- }\r
- //\r
- }\r
- //\r
- // add parent -> children reference\r
- for (int icld=0;icld<fNModules;icld++) {\r
- AliITSAlignMille2Module* child = GetMilleModule(icld);\r
- AliITSAlignMille2Module* parent = child->GetParent();\r
- if (parent) parent->AddChild(child);\r
- } \r
- //\r
- // reorder the modules in such a way that parents come first\r
- for (int icld=0;icld<fNModules;icld++) {\r
- AliITSAlignMille2Module* child = GetMilleModule(icld);\r
- AliITSAlignMille2Module* parent; \r
- while ( (parent=child->GetParent()) && (parent->GetUniqueID()>child->GetUniqueID()) ) {\r
- // swap\r
- fMilleModule[icld] = parent;\r
- fMilleModule[parent->GetUniqueID()] = child;\r
- child->SetUniqueID(parent->GetUniqueID());\r
- parent->SetUniqueID(icld);\r
- child = parent;\r
- }\r
- //\r
- } \r
- //\r
- // Go over the child->parent chain and mark modules with explicitly provided sensors.\r
- // If the sensors of the unit are explicitly declared, all undeclared sensors are \r
- // suppresed in this unit.\r
- for (int icld=fNModules;icld--;) {\r
- AliITSAlignMille2Module* child = GetMilleModule(icld);\r
- AliITSAlignMille2Module* parent = child->GetParent();\r
- if (!parent) continue;\r
- //\r
- // check if this parent was already processed\r
- if (!parent->AreSensorsProvided()) {\r
- parent->DelSensitiveVolumes();\r
- parent->SetSensorsProvided(kTRUE);\r
- }\r
- // reattach sensors to parent\r
- for (int isc=child->GetNSensitiveVolumes();isc--;) {\r
- UShort_t senVID = child->GetSensVolVolumeID(isc);\r
- if (!parent->IsIn(senVID)) parent->AddSensitiveVolume(senVID);\r
- }\r
- }\r
- //\r
-}\r
-\r
-// pepo\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::SetCurrentModule(Int_t id)\r
-{\r
- // set the current supermodule\r
- // new meaning\r
- if (fMilleVersion>=2) {\r
- fCurrentModule = GetMilleModule(id);\r
- return;\r
- }\r
- // old meaning\r
- if (fMilleVersion<=1) {\r
- Int_t index=id;\r
- /// set as current the SuperModule that contains the 'index' sens.vol.\r
- if (index<0 || index>2197) {\r
- AliInfo("index does not correspond to a sensitive volume!");\r
- return;\r
- }\r
- UShort_t voluid=AliITSAlignMille2Module::GetVolumeIDFromIndex(index);\r
- Int_t k=IsContained(voluid);\r
- if (k>=0){\r
- fCluster.SetVolumeID(voluid);\r
- fCluster.SetXYZ(0,0,0);\r
- InitModuleParams();\r
- }\r
- else\r
- AliInfo(Form("module %d not defined\n",index)); \r
- }\r
-}\r
-// endpepo\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::SetRequiredPoint(Char_t* where, Int_t ndet, Int_t updw, Int_t nreqpts) \r
-{\r
- // set minimum number of points in specific detector or layer\r
- // where = LAYER or DETECTOR\r
- // ndet = detector number: 1-6 for LAYER and 1-3 for DETECTOR (SPD=1, SDD=2, SSD=3)\r
- // updw = 1 for Y>0, -1 for Y<0, 0 if not specified\r
- // nreqpts = minimum number of points of that type\r
- ndet--;\r
- if (strstr(where,"LAYER")) {\r
- if (ndet<0 || ndet>5) return;\r
- if (updw>0) fNReqLayUp[ndet]=nreqpts;\r
- else if (updw<0) fNReqLayDown[ndet]=nreqpts;\r
- else fNReqLay[ndet]=nreqpts;\r
- fRequirePoints=kTRUE;\r
- }\r
- else if (strstr(where,"DETECTOR")) {\r
- if (ndet<0 || ndet>2) return;\r
- if (updw>0) fNReqDetUp[ndet]=nreqpts;\r
- else if (updw<0) fNReqDetDown[ndet]=nreqpts;\r
- else fNReqDet[ndet]=nreqpts; \r
- fRequirePoints=kTRUE;\r
- }\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::GetModuleIndex(const Char_t *symname) \r
-{\r
- /// index from symname\r
- if (!symname) return -1;\r
- for (Int_t i=0;i<=kMaxITSSensID; i++) {\r
- if (!strcmp(symname,AliITSgeomTGeo::GetSymName(i))) return i;\r
- }\r
- return -1;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::GetModuleIndex(UShort_t voluid) \r
-{\r
- /// index from volume ID\r
- AliGeomManager::ELayerID lay = AliGeomManager::VolUIDToLayer(voluid);\r
- if (lay<1|| lay>6) return -1;\r
- Int_t idx=Int_t(voluid)-2048*lay;\r
- if (idx>=AliGeomManager::LayerSize(lay)) return -1;\r
- for (Int_t ilay=1; ilay<lay; ilay++) \r
- idx += AliGeomManager::LayerSize(ilay);\r
- return idx;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-UShort_t AliITSAlignMille2::GetModuleVolumeID(const Char_t *symname) \r
-{\r
- /// volume ID from symname\r
- /// works for sensitive volumes only\r
- if (!symname) return 0;\r
-\r
- for (UShort_t voluid=2000; voluid<13300; voluid++) {\r
- Int_t modId;\r
- AliGeomManager::ELayerID layerId = AliGeomManager::VolUIDToLayer(voluid,modId);\r
- if (layerId>0 && layerId<7 && modId>=0 && modId<AliGeomManager::LayerSize(layerId)) {\r
- if (!strcmp(symname,AliGeomManager::SymName(layerId,modId))) return voluid;\r
- }\r
- }\r
-\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-UShort_t AliITSAlignMille2::GetModuleVolumeID(Int_t index) \r
-{\r
- /// volume ID from index\r
- if (index<0) return 0;\r
- if (index<2198)\r
- return GetModuleVolumeID(AliITSgeomTGeo::GetSymName(index));\r
- else {\r
- for (int i=0; i<fNSuperModules; i++) {\r
- if (GetSuperModule(i)->GetIndex()==index) return GetSuperModule(i)->GetVolumeID();\r
- }\r
- }\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::InitGeometry() \r
-{\r
- /// initialize geometry\r
- AliInfo("Loading initial geometry");\r
- AliGeomManager::LoadGeometry(fGeometryFileName.Data());\r
- fGeoManager = AliGeomManager::GetGeometry();\r
- if (!fGeoManager) {\r
- AliInfo("Couldn't initialize geometry");\r
- return -1;\r
- }\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::SetConstraintWrtRef(const char* reffname) \r
-{\r
- // Load the global deltas from this file. The local gaussian constraints on some modules \r
- // will be defined with respect to the deltas from this reference file, converted to local\r
- // delta format. Note: conversion to local format requires reloading the geometry!\r
- //\r
- AliInfo(Form("Loading reference deltas for local constraints from %s",reffname));\r
- if (!fGeoManager) return -1; \r
- fConstrRefFileName = reffname;\r
- if (fConstrRefFileName == "IDEAL") { // the reference is the ideal geometry, just create dummy reference array\r
- fConstrRef = new TClonesArray("AliAlignObjParams",1);\r
- return 0;\r
- }\r
- TFile *pref = TFile::Open(fConstrRefFileName.Data());\r
- if (!pref->IsOpen()) return -2; \r
- fConstrRef = (TClonesArray*)pref->Get("ITSAlignObjs");\r
- pref->Close();\r
- delete pref;\r
- if (!fConstrRef) {\r
- AliError(Form("Did not find reference prealignment deltas in %s",reffname));\r
- return -1;\r
- }\r
- //\r
- // we need ideal geometry to convert global deltas to local ones\r
- if (fUsePreAlignment) {\r
- AliError("The call of SetConstraintWrtRef must be done before application of the prealignment");\r
- return -1;\r
- }\r
- //\r
- AliInfo("Converting global reference deltas to local ones");\r
- Int_t nprea = fConstrRef->GetEntriesFast();\r
- for (int ix=0; ix<nprea; ix++) {\r
- AliAlignObjParams *preo=(AliAlignObjParams*) fConstrRef->At(ix);\r
- if (!preo->ApplyToGeometry()) return -1;\r
- }\r
- //\r
- // now convert the global reference deltas to local ones\r
- for (int i=fConstrRef->GetEntriesFast();i--;) {\r
- AliAlignObjParams *preo = (AliAlignObjParams*)fConstrRef->At(i);\r
- TGeoHMatrix * mupd = AliGeomManager::GetMatrix(preo->GetSymName());\r
- if (!mupd) { // this is not alignable entry, need to look in the supermodules\r
- for (int im=fNSuperModules;im--;) {\r
- AliITSAlignMille2Module* mod = GetSuperModule(im);\r
- if ( strcmp(mod->GetName(), preo->GetSymName()) ) continue;\r
- mupd = mod->GetMatrix();\r
- break;\r
- }\r
- if (!mupd) {\r
- AliError(Form("Failed to find the volume for reference %s",preo->GetSymName()));\r
- return -1;\r
- }\r
- } \r
- TGeoHMatrix preMat;\r
- preo->GetMatrix(preMat); // Delta_Glob\r
- TGeoHMatrix tmpMat = *mupd; // Delta_Glob * Delta_Glob_Par * M\r
- preMat.MultiplyLeft( &tmpMat.Inverse() ); // M^-1 * Delta_Glob_Par^-1 = (Delta_Glob_Par * M)^-1\r
- tmpMat.MultiplyLeft( &preMat ); // (Delta_Glob_Par * M)^-1 * Delta_Glob * Delta_Glob_Par * M = Delta_loc\r
- preo->SetMatrix(tmpMat); // local corrections \r
- }\r
- //\r
- // we need to reload the geometry spoiled by this reference deltas...\r
- delete fGeoManager;\r
- AliInfo("Reloading initial geometry");\r
- AliGeomManager::LoadGeometry(fGeometryFileName.Data());\r
- fGeoManager = AliGeomManager::GetGeometry();\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::Init()\r
-{\r
- // perform global initialization\r
- //\r
- if (fIsMilleInit) {\r
- AliInfo("Millepede has been already initialized!");\r
- return;\r
- }\r
- // range constraints in such a way that the childs are constrained before their parents\r
- // orphan constraints come last\r
- for (int ic=0;ic<GetNConstraints();ic++) {\r
- for (int ic1=ic+1;ic1<GetNConstraints();ic1++) {\r
- AliITSAlignMille2Constraint *cst0 = GetConstraint(ic);\r
- AliITSAlignMille2Constraint *cst1 = GetConstraint(ic1);\r
- if (cst0->GetModuleID()<cst1->GetModuleID()) {\r
- // swap\r
- fConstraints[ic] = cst1;\r
- fConstraints[ic1] = cst0;\r
- }\r
- }\r
- }\r
- //\r
- if (!GetUseGlobalDelta()) {\r
- AliInfo("ATTENTION: The parameters are defined in the local frame, no check for degeneracy will be done");\r
- for (int imd=fNModules;imd--;) {\r
- AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
- int npar = mod->GetNParTot();\r
- // the parameter may have max 1 free instance, otherwise the equations are underdefined\r
- for (int ipar=0;ipar<npar;ipar++) {\r
- if (!mod->IsFreeDOF(ipar)) continue;\r
- mod->SetParOffset(ipar,fNGlobal++);\r
- }\r
- }\r
- }\r
- else {\r
- // init millepede, decide which parameters are to be fitted explicitly\r
- for (int imd=fNModules;imd--;) {\r
- AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
- int npar = mod->GetNParTot();\r
- // the parameter may have max 1 free instance, otherwise the equations are underdefined\r
- for (int ipar=0;ipar<npar;ipar++) {\r
- if (!mod->IsFreeDOF(ipar)) continue; // fixed\r
- //\r
- int nFreeInstances = 0;\r
- //\r
- AliITSAlignMille2Module* parent = mod;\r
- Bool_t cstMeanMed=kFALSE,cstGauss=kFALSE;\r
- //\r
- Bool_t addToFit = kFALSE; \r
- // the parameter may be ommitted from explicit fit (if PseudoParentsAllowed is true) if\r
- // 1) it is not explicitly constrained or its does not participate in Gaussian constraint\r
- // 2) the same applies to all of its parents\r
- // 3) it has at least 1 unconstrained direct child\r
- while(parent) {\r
- if (!parent->IsFreeDOF(ipar)) {parent = parent->GetParent(); continue;}\r
- nFreeInstances++;\r
- if (IsParModConstrained(parent,ipar, cstMeanMed, cstGauss)) nFreeInstances--;\r
- if (cstGauss) addToFit = kTRUE;\r
- parent = parent->GetParent();\r
- }\r
- if (nFreeInstances>1) {\r
- AliError(Form("Parameter#%d of module %s\nhas %d free instances in the "\r
- "unconstrained parents\nSystem is undefined",ipar,mod->GetName(),nFreeInstances));\r
- exit(1);\r
- }\r
- //\r
- // i) Are PseudoParents allowed?\r
- if (!PseudoParentsAllowed()) addToFit = kTRUE;\r
- // ii) check if this module has no child with such a free parameter. Since the order of this check \r
- // goes from child to parent, by this moment such a parameter must have been already added\r
- else if (!IsParModFamilyVaried(mod,ipar)) addToFit = kTRUE; // no varied children at all\r
- else if (!IsParFamilyFree(mod,ipar,1)) addToFit = kTRUE; // no unconstrained direct children\r
- // otherwise the value of this parameter can be extracted from simple contraint and the values of \r
- // the relevant parameters of its children the fit is done. Hence it is not included\r
- if (!addToFit) continue;\r
- //\r
- // shall add this parameter to explicit fit\r
- // printf("Adding %s %d -> %d\n",mod->GetName(), ipar, fNGlobal);\r
- mod->SetParOffset(ipar,fNGlobal++);\r
- }\r
- }\r
- }\r
- //\r
- AliInfo(Form("Initializing Millepede with %d gpar, %d lpar and %d stddev ...",fNGlobal, fNLocal, fNStdDev));\r
- fGlobalDerivatives = new Double_t[fNGlobal];\r
- memset(fGlobalDerivatives,0,fNGlobal*sizeof(Double_t));\r
- //\r
- fMillepede->InitMille(fNGlobal,fNLocal,fNStdDev,fResCut,fResCutInitial);\r
- fIsMilleInit = kTRUE;\r
- //\r
- ResetLocalEquation(); \r
- AliInfo("Parameters initialized to zero");\r
- //\r
- /// Fix non free parameters\r
- for (Int_t i=0; i<fNModules; i++) {\r
- AliITSAlignMille2Module* mod = GetMilleModule(i);\r
- for (Int_t j=0; j<mod->GetNParTot(); j++) {\r
- if (mod->GetParOffset(j)<0) continue; // not varied\r
- FixParameter(mod->GetParOffset(j),mod->GetParConstraint(j));\r
- fMillepede->SetParamGrID(i, mod->GetParOffset(j));\r
- }\r
- }\r
- //\r
- // Set iterations\r
- if (fStartFac>1) fMillepede->SetIterations(fStartFac); \r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::AddConstraint(Double_t *par, Double_t value, Double_t sigma) \r
-{\r
- /// Constrain equation defined by par to value\r
- if (!fIsMilleInit) Init();\r
- fMillepede->SetGlobalConstraint(par, value, sigma);\r
- AliInfo("Adding constraint");\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::InitGlobalParameters(Double_t *par) \r
-{\r
- /// Initialize global parameters with par array\r
- if (!fIsMilleInit) Init();\r
- fMillepede->SetGlobalParameters(par);\r
- AliInfo("Init Global Parameters");\r
-}\r
-\r
-//________________________________________________________________________________________________________ \r
-void AliITSAlignMille2::FixParameter(Int_t iPar, Double_t value) \r
-{\r
- /// Parameter iPar is encourage to vary in [-value;value]. \r
- /// If value == 0, parameter is fixed\r
- if (!fIsMilleInit) {\r
- AliInfo("Millepede has not been initialized!");\r
- return;\r
- }\r
- fMillepede->SetParSigma(iPar, value);\r
- if (value==0) AliInfo(Form("Parameter %i Fixed", iPar));\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ResetLocalEquation()\r
-{\r
- /// Reset the derivative vectors\r
- for(int i=fNLocal;i--;) fLocalDerivatives[i] = 0.0;\r
- memset(fGlobalDerivatives, 0, fNGlobal*sizeof(double) );\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::ApplyToGeometry() \r
-{\r
- // apply starting realignment to ideal geometry\r
- AliInfo(Form("Using %s for prealignment",fPreAlignmentFileName.Data()));\r
- if (!fGeoManager) return -1; \r
- TFile *pref = TFile::Open(fPreAlignmentFileName.Data());\r
- if (!pref->IsOpen()) return -2;\r
- fPrealignment = (TClonesArray*)pref->Get("ITSAlignObjs");\r
- if (!fPrealignment) return -3; \r
- Int_t nprea = fPrealignment->GetEntriesFast();\r
- AliInfo(Form("Array of input misalignments with %d entries",nprea));\r
- //\r
- for (int ix=0; ix<nprea; ix++) {\r
- AliAlignObjParams *preo=(AliAlignObjParams*) fPrealignment->At(ix);\r
- Int_t index=AliITSAlignMille2Module::GetIndexFromVolumeID(preo->GetVolUID());\r
- if (index>=0) {\r
- if (index>=fPreAlignQF.GetSize()) fPreAlignQF.Set(index+10);\r
- fPreAlignQF[index] = (int) preo->GetUniqueID()+1;\r
- }\r
- //TString nms = preo->GetSymName();\r
- //if (!nms.Contains("Ladder")) continue; //RRR\r
- //printf("Applying#%4d %s\n",ix,preo->GetSymName());\r
- if (!preo->ApplyToGeometry()) return -4;\r
- }\r
- //\r
- pref->Close();\r
- delete pref;\r
- //\r
- fUsePreAlignment = kTRUE;\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::GetPreAlignmentQualityFactor(Int_t index) const\r
-{\r
- // quality factors from prealignment\r
- if (!fUsePreAlignment || index<0 || index>=fPreAlignQF.GetSize()) return -1;\r
- return fPreAlignQF[index]-1;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-AliTrackPointArray *AliITSAlignMille2::PrepareTrack(const AliTrackPointArray *atp) \r
-{\r
- /// create a new AliTrackPointArray keeping only defined modules\r
- /// move points according to a given prealignment, if any\r
- /// sort alitrackpoints w.r.t. global Y direction, if selected\r
- const double kTiny = 1E-12;\r
- //\r
- AliTrackPointArray *atps=NULL;\r
- Int_t idx[20];\r
- Int_t npts=atp->GetNPoints();\r
-\r
- /// checks if AliTrackPoints belong to defined modules\r
- Int_t ngoodpts=0;\r
- Int_t intidx[20];\r
- \r
- for (int j=0; j<npts; j++) {\r
- intidx[j] = IsVIDContained(atp->GetVolumeID()[j]);\r
- if (intidx[j]>=0) ngoodpts++;\r
- }\r
- AliDebug(3,Form("Number of points in defined modules: %d out of %d",ngoodpts,npts));\r
-\r
- // reject track if not enough points are left\r
- if (ngoodpts<fMinNPtsPerTrack) {\r
- AliInfo("Track with not enough points!");\r
- return NULL;\r
- }\r
- // >> RS\r
- AliTrackPoint p;\r
- // check points in specific places\r
- if (fRequirePoints) {\r
- Int_t nlayup[6],nlaydown[6],nlay[6];\r
- Int_t ndetup[3],ndetdown[3],ndet[3];\r
- for (Int_t j=0; j<6; j++) {nlayup[j]=0; nlaydown[j]=0; nlay[j]=0;}\r
- for (Int_t j=0; j<3; j++) {ndetup[j]=0; ndetdown[j]=0; ndet[j]=0;}\r
- \r
- for (int i=0; i<npts; i++) {\r
- // skip not defined points\r
- if (intidx[i]<0) continue;\r
- Float_t xx=atp->GetX()[i];\r
- Float_t yy=atp->GetY()[i];\r
- Float_t r=TMath::Sqrt(xx*xx + yy*yy);\r
- int lay=-1;\r
- if (r<5) lay=0;\r
- else if (r>5 && r<10) lay=1;\r
- else if (r>10 && r<18) lay=2;\r
- else if (r>18 && r<30) lay=3;\r
- else if (r>30 && r<40) lay=4;\r
- else if (r>40) lay=5;\r
- if (lay<0) continue;\r
- int det=lay/2;\r
- //printf("Point %d - x=%f y=%f R=%f lay=%d det=%d\n",i,xx,yy,r,lay,det);\r
-\r
- if (yy>=0.0) { // UP point\r
- nlayup[lay]++;\r
- nlay[lay]++;\r
- ndetup[det]++;\r
- ndet[det]++;\r
- }\r
- else {\r
- nlaydown[lay]++;\r
- nlay[lay]++;\r
- ndetdown[det]++;\r
- ndet[det]++;\r
- }\r
- }\r
- \r
- // checks minimum values\r
- Bool_t isok=kTRUE;\r
- for (Int_t j=0; j<6; j++) {\r
- if (nlayup[j]<fNReqLayUp[j]) isok=kFALSE; \r
- if (nlaydown[j]<fNReqLayDown[j]) isok=kFALSE; \r
- if (nlay[j]<fNReqLay[j]) isok=kFALSE; \r
- }\r
- for (Int_t j=0; j<3; j++) {\r
- if (ndetup[j]<fNReqDetUp[j]) isok=kFALSE; \r
- if (ndetdown[j]<fNReqDetDown[j]) isok=kFALSE; \r
- if (ndet[j]<fNReqDet[j]) isok=kFALSE; \r
- }\r
- if (!isok) {\r
- AliDebug(2,Form("Track does not meet all location point requirements!"));\r
- return NULL;\r
- }\r
- }\r
- // build a new track with (sorted) (prealigned) good points\r
- // pepo200709\r
- //atps = (AliTrackPointArray*)fTrackBuff[ngoodpts-fMinNPtsPerTrack];\r
- atps = (AliTrackPointArray*)fTrackBuff[ngoodpts];\r
- if (!atps) {\r
- atps = new AliTrackPointArray(ngoodpts);\r
- // fTrackBuff.AddAtAndExpand(atps,ngoodpts-fMinNPtsPerTrack);\r
- fTrackBuff.AddAtAndExpand(atps,ngoodpts);\r
- } \r
- // atps = new AliTrackPointArray(ngoodpts);\r
- // endpepo200709\r
- //\r
- //\r
- for (int i=0; i<npts; i++) idx[i]=i;\r
- // sort track if required\r
- TMath::Sort(npts,atp->GetY(),idx); // sort descending...\r
- //\r
- Int_t npto=0;\r
- for (int i=0; i<npts; i++) {\r
- // skip not defined points\r
- if (intidx[idx[i]]<0) continue;\r
- atp->GetPoint(p,idx[i]);\r
-\r
- // prealign point if required\r
- // get IDEAL matrix\r
- AliITSAlignMille2Module *mod = GetMilleModule(intidx[idx[i]]);\r
- TGeoHMatrix *svOrigMatrix = mod->GetSensitiveVolumeOrigGlobalMatrix(p.GetVolumeID());\r
- // get back real local coordinates: use OriginalGlobalMatrix because AliTrackPoints were written\r
- // with idel geometry \r
- Double_t pg[3],pl[3];\r
- pg[0]=p.GetX();\r
- pg[1]=p.GetY();\r
- pg[2]=p.GetZ();\r
- // printf("Global coordinates of measured point : X=%f Y=%f Z=%f \n",pg[0],pg[1],pg[2]);\r
- AliDebug(3,Form("Global coordinates of measured point : X=%f Y=%f Z=%f \n",pg[0],pg[1],pg[2]));\r
- svOrigMatrix->MasterToLocal(pg,pl);\r
-\r
- AliDebug(3,Form("Local coordinates of measured point : X=%f Y=%f Z=%f \n",pl[0],pl[1],pl[2]));\r
- //\r
- // this is a temporary code to extract the drift speed used for given point\r
- if (p.GetDriftTime()>0) { // RRR\r
- // calculate the drift speed\r
- int sid = AliITSAlignMille2Module::GetIndexFromVolumeID(p.GetVolumeID());// - kSDDoffsID;\r
- fDriftTime0[npto] = fInitialRecSDD ? fInitialRecSDD->GetTimeZero(sid) : 0.;\r
- /*\r
- AliGeomManager::ELayerID lay = AliGeomManager::VolUIDToLayer(p.GetVolumeID());\r
- if (lay==3) fDriftTime0[npto] = pg[2]<0 ? 169.5 : 140.1;\r
- else if (lay==4) fDriftTime0[npto] = pg[2]<0 ? 158.3 : 139.0;\r
- else {\r
- AliError(Form("Strange layer %d for moduleID %d",lay,p.GetVolumeID()));\r
- exit(1);\r
- }\r
- */\r
- double tdif = p.GetDriftTime() - fDriftTime0[npto];\r
- if (tdif<=0) tdif = 1;\r
- double vdrift = (3.5085-TMath::Abs(pl[0]))/tdif;\r
- if (vdrift<0) vdrift = 0;\r
- //\r
- // TEMPORARY CORRECTION (if provided) -------------->>>\r
- if (fCorrectSDD) {\r
- float t0Upd = fCorrectSDD->GetTimeZero(sid);\r
- vdrift += fCorrectSDD->GetDeltaVDrift(sid);\r
- tdif = p.GetDriftTime() - t0Upd;\r
- // correct Xlocal\r
- pl[0] = TMath::Sign(3.5085 - vdrift*tdif,pl[0]);\r
- fDriftTime0[npto] = t0Upd;\r
- }\r
- // TEMPORARY CORRECTION (if provided) --------------<<<\r
- fDriftSpeed[npto] = TMath::Sign(vdrift,pl[0]);\r
- //\r
- /*\r
- printf("%d %+6.2f %+6.2f %+6.2f %+5.2f %+5.2f %+5.2f %+6.1f %+6.1f %+f %+f\n",\r
- p.GetVolumeID(),pg[0],pg[1],pg[2],pl[0],pl[1],pl[2],p.GetDriftTime(), fDriftTime0[npto], fDriftSpeed[npto],tdif);\r
- */\r
- }\r
-\r
- // update covariance matrix\r
- TGeoHMatrix hcov;\r
- Double_t hcovel[9];\r
- hcovel[0]=double(p.GetCov()[0]);\r
- hcovel[1]=double(p.GetCov()[1]);\r
- hcovel[2]=double(p.GetCov()[2]);\r
- hcovel[3]=double(p.GetCov()[1]);\r
- hcovel[4]=double(p.GetCov()[3]);\r
- hcovel[5]=double(p.GetCov()[4]);\r
- hcovel[6]=double(p.GetCov()[2]);\r
- hcovel[7]=double(p.GetCov()[4]);\r
- hcovel[8]=double(p.GetCov()[5]);\r
- hcov.SetRotation(hcovel);\r
- // now rotate in local system\r
- // printf("\nErrMatGlob: before\n"); hcov.Print(""); //RRR\r
- hcov.Multiply(svOrigMatrix);\r
- hcov.MultiplyLeft(&svOrigMatrix->Inverse());\r
- // now hcov is LOCAL COVARIANCE MATRIX\r
- // apply sigma scaling\r
- // printf("\nErrMatLoc: before\n"); hcov.Print(""); //RRR\r
- Double_t *hcovscl = hcov.GetRotationMatrix(); \r
- // for (int ir=3;ir--;) for (int ic=3;ic--;) hcovscl[ir*3+ic] *= mod->GetSigmaFactor(ir)*mod->GetSigmaFactor(ic); //RRR\r
- // RS TEMPORARY: nullify non-diagonal elements and sigY\r
- hcovscl[5] = 0;\r
- for (int ir=3;ir--;) for (int ic=3;ic--;) {\r
- if (ir==ic) {\r
- if (TMath::Abs(hcovscl[ir*3+ic])<kTiny) hcovscl[ir*3+ic] = 0.;\r
- else hcovscl[ir*3+ic] *= mod->GetSigmaFactor(ir)*mod->GetSigmaFactor(ic); //RRR\r
- }\r
- else hcovscl[ir*3+ic] = 0;\r
- }\r
- //\r
- // printf("\nErrMatLoc: after\n"); hcov.Print(""); //RRR\r
- //\r
- if (fBug==1) {\r
- // correzione bug LAYER 5 SSD temporanea..\r
- int ssdidx=AliITSAlignMille2Module::GetIndexFromVolumeID(p.GetVolumeID());\r
- if (ssdidx>=500 && ssdidx<1248) {\r
- int ladder=(ssdidx-500)%22;\r
- if (ladder==18) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx+1));\r
- if (ladder==19) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx-1));\r
- }\r
- }\r
- /// get (evenctually prealigned) matrix of sens. vol.\r
- TGeoHMatrix *svMatrix = mod->GetSensitiveVolumeMatrix(p.GetVolumeID());\r
- // modify global coordinates according with pre-aligment\r
- svMatrix->LocalToMaster(pl,pg);\r
- // now rotate in local system\r
- hcov.Multiply(&svMatrix->Inverse());\r
- hcov.MultiplyLeft(svMatrix);\r
- // hcov is back in GLOBAL RF\r
- // cure once more\r
- for (int ir=3;ir--;) for (int ic=3;ic--;) if (TMath::Abs(hcovscl[ir*3+ic])<kTiny) hcovscl[ir*3+ic] = 0.;\r
- // printf("\nErrMatGlob: after\n"); hcov.Print(""); //RRR\r
- //\r
- Float_t pcov[6];\r
- pcov[0]=hcovscl[0];\r
- pcov[1]=hcovscl[1];\r
- pcov[2]=hcovscl[2];\r
- pcov[3]=hcovscl[4];\r
- pcov[4]=hcovscl[5];\r
- pcov[5]=hcovscl[8];\r
-\r
- p.SetXYZ(pg[0],pg[1],pg[2],pcov);\r
- // printf("New Gl coordinates of measured point : X=%f Y=%f Z=%f \n",pg[0],pg[1],pg[2]);\r
- AliDebug(3,Form("New global coordinates of measured point : X=%f Y=%f Z=%f \n",pg[0],pg[1],pg[2]));\r
- atps->AddPoint(npto,&p);\r
- AliDebug(2,Form("Adding point[%d] = ( %f , %f , %f ) volid = %d",npto,atps->GetX()[npto],\r
- atps->GetY()[npto],atps->GetZ()[npto],atps->GetVolumeID()[npto] ));\r
- // printf("Adding %d %d %f\n",npto, p.GetVolumeID(), p.GetY()); \r
- npto++;\r
- }\r
-\r
- return atps;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-AliTrackPointArray *AliITSAlignMille2::SortTrack(const AliTrackPointArray *atp) \r
-{\r
- /// sort alitrackpoints w.r.t. global Y direction\r
- AliTrackPointArray *atps=NULL;\r
- Int_t idx[20];\r
- Int_t npts=atp->GetNPoints();\r
- AliTrackPoint p;\r
- atps=new AliTrackPointArray(npts);\r
-\r
- TMath::Sort(npts,atp->GetY(),idx);\r
-\r
- for (int i=0; i<npts; i++) {\r
- atp->GetPoint(p,idx[i]);\r
- atps->AddPoint(i,&p);\r
- AliDebug(2,Form("Point[%d] = ( %f , %f , %f ) volid = %d",i,atps->GetX()[i],atps->GetY()[i],atps->GetZ()[i],atps->GetVolumeID()[i] ));\r
- }\r
- return atps;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::GetCurrentLayer() const \r
-{\r
- // get current layer id\r
- if (!fGeoManager) {\r
- AliInfo("ITS geometry not initialized!");\r
- return -1;\r
- }\r
- return (Int_t)AliGeomManager::VolUIDToLayer(fCluster.GetVolumeID());\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::InitModuleParams() \r
-{\r
- /// initialize geometry parameters for a given detector\r
- /// for current cluster (fCluster)\r
- /// fGlobalInitParam[] is set as:\r
- /// [tx,ty,tz,psi,theta,phi]\r
- /// (old was [tx,ty,tz,theta,psi,phi] ROOT's angles...)\r
- /// *** At the moment: using Raffalele's angles definition ***\r
- ///\r
- /// return 0 if success\r
- /// If module is found but has no parameters to vary, return 1\r
-\r
- if (!fGeoManager) {\r
- AliInfo("ITS geometry not initialized!");\r
- return -1;\r
- }\r
-\r
- // now 'voluid' is the volumeID of a SENSITIVE VOLUME (coming from a cluster)\r
-\r
- // set the internal index (index in module list)\r
- UShort_t voluid=fCluster.GetVolumeID();\r
- //\r
- // IT IS VERY IMPORTANT: start from the end of the list, where the childs are located !!!\r
- Int_t k=fNModules-1;\r
- fCurrentModule = 0;\r
- // VERY IMPORTANT: if the sensors were explicitly provided, don't look in the supermodules \r
- while (k>=0 && ! (fCurrentModule=GetMilleModule(k))->IsIn(voluid)) k--;\r
- if (k<0) return -3;\r
- //\r
- /*\r
- // Check if the module has free params. If not, go over the parents\r
- AliITSAlignMille2Module* mdtmp = fCurrentModule;\r
- while (mdtmp && mdtmp->GetNParFree()==0) mdtmp = mdtmp->GetParent();\r
- if (!mdtmp) return 1; // nothing to vary here\r
- fCurrentModule = mdtmp;\r
- */\r
- //\r
- fModuleInitParam[0] = 0.0;\r
- fModuleInitParam[1] = 0.0;\r
- fModuleInitParam[2] = 0.0;\r
- fModuleInitParam[3] = 0.0; // psi (X)\r
- fModuleInitParam[4] = 0.0; // theta (Y)\r
- fModuleInitParam[5] = 0.0; // phi (Z)\r
- fModuleInitParam[6] = 0.0;\r
- fModuleInitParam[7] = 0.0;\r
- /// get (evenctually prealigned) matrix of sens. vol.\r
- TGeoHMatrix *svMatrix = fCurrentModule->GetSensitiveVolumeMatrix(voluid);\r
- \r
- fMeasGlo[0] = fCluster.GetX();\r
- fMeasGlo[1] = fCluster.GetY();\r
- fMeasGlo[2] = fCluster.GetZ(); \r
- svMatrix->MasterToLocal(fMeasGlo,fMeasLoc); \r
- AliDebug(2,Form("Local coordinates of measured point : X=%f Y=%f Z=%f \n",fMeasLoc[0] ,fMeasLoc[1] ,fMeasLoc[2] ));\r
- \r
- // set stdev from cluster\r
- TGeoHMatrix hcov;\r
- Double_t hcovel[9];\r
- hcovel[0]=double(fCluster.GetCov()[0]);\r
- hcovel[1]=double(fCluster.GetCov()[1]);\r
- hcovel[2]=double(fCluster.GetCov()[2]);\r
- hcovel[3]=double(fCluster.GetCov()[1]);\r
- hcovel[4]=double(fCluster.GetCov()[3]);\r
- hcovel[5]=double(fCluster.GetCov()[4]);\r
- hcovel[6]=double(fCluster.GetCov()[2]);\r
- hcovel[7]=double(fCluster.GetCov()[4]);\r
- hcovel[8]=double(fCluster.GetCov()[5]);\r
- hcov.SetRotation(hcovel);\r
- // now rotate in local system\r
- hcov.Multiply(svMatrix);\r
- hcov.MultiplyLeft(&svMatrix->Inverse());\r
- //\r
- // set local sigmas\r
- fSigmaLoc[0] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[0]));\r
- fSigmaLoc[1] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[4])); // RS\r
- fSigmaLoc[2] = TMath::Sqrt(TMath::Abs(hcov.GetRotationMatrix()[8]));\r
-\r
- // set minimum value for SigmaLoc to 10 micron \r
- if (fSigmaLoc[0]<0.0010) fSigmaLoc[0]=0.0010;\r
- if (fSigmaLoc[2]<0.0010) fSigmaLoc[2]=0.0010;\r
- //\r
- /* RRR the rescaling is moved to PrepareTrack\r
- // multiply local sigmas by global and module specific factor \r
- for (int i=3;i--;) fSigmaLoc[i] *= fSigmaFactor[i]*fCurrentModule->GetSigmaFactor(i);\r
- //\r
- */\r
- AliDebug(2,Form("Setting StDev from CovMat : fSigmaLocX=%g fSigmaLocY=%g fSigmaLocZ=%g \n",fSigmaLoc[0] ,fSigmaLoc[1] ,fSigmaLoc[2] ));\r
- \r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::Print(Option_t*) const \r
-{\r
- // print current status \r
- printf("*** AliMillepede for ITS ***\n");\r
- printf(" Number of defined super modules: %d\n",fNModules);\r
- printf(" Obtained parameters refer to %s Deltas\n",fUseGlobalDelta ? "GLOBAL":"LOCAL");\r
- //\r
- if (fGeoManager)\r
- printf(" geometry loaded from %s\n",fGeometryFileName.Data());\r
- else\r
- printf(" geometry not loaded\n");\r
- // \r
- if (fUsePreAlignment) \r
- printf(" using prealignment from %s \n",fPreAlignmentFileName.Data());\r
- else\r
- printf(" prealignment not used\n"); \r
- //\r
- //\r
- if (fBOn) \r
- printf(" B Field set to %f T - using Riemann's helices\n",fBField);\r
- else\r
- printf(" B Field OFF - using straight lines \n");\r
- //\r
- if (fRequirePoints) printf(" Required points in tracks:\n");\r
- for (Int_t i=0; i<6; i++) {\r
- if (fNReqLayUp[i]>0) printf(" Layer %d : %d points with Y>0\n",i+1,fNReqLayUp[i]);\r
- if (fNReqLayDown[i]>0) printf(" Layer %d : %d points with Y<0\n",i+1,fNReqLayDown[i]);\r
- if (fNReqLay[i]>0) printf(" Layer %d : %d points \n",i+1,fNReqLay[i]);\r
- }\r
- for (Int_t i=0; i<3; i++) {\r
- if (fNReqDetUp[i]>0) printf(" Detector %d : %d points with Y>0\n",i+1,fNReqDetUp[i]);\r
- if (fNReqDetDown[i]>0) printf(" Detector %d : %d points with Y<0\n",i+1,fNReqDetDown[i]);\r
- if (fNReqDet[i]>0) printf(" Detector %d : %d points \n",i+1,fNReqDet[i]);\r
- }\r
- // \r
- printf("\n Millepede configuration parameters:\n");\r
- printf(" init value for chi2 cut : %.4f\n",fStartFac);\r
- printf(" first iteration cut value : %.4f\n",fResCutInitial);\r
- printf(" other iterations cut value : %.4f\n",fResCut);\r
- printf(" number of stddev for chi2 cut : %d\n",fNStdDev);\r
- printf(" def.scaling for local sigmas : %.4f %.4f %.4f\n",fSigmaFactor[0],fSigmaFactor[1],fSigmaFactor[2]);\r
-\r
- printf("List of defined modules:\n");\r
- printf(" intidx\tindex\tvoluid\tname\n");\r
- for (int i=0; i<fNModules; i++) {\r
- AliITSAlignMille2Module* md = GetMilleModule(i); \r
- printf(" %d\t%d\t%d\t%s\n",i,md->GetIndex(),md->GetVolumeID(),md->GetName());\r
- }\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-AliITSAlignMille2Module *AliITSAlignMille2::GetMilleModuleByVID(UShort_t voluid) const\r
-{\r
- // return pointer to a defined supermodule\r
- // return NULL if error\r
- Int_t i=IsVIDDefined(voluid);\r
- if (i<0) return NULL;\r
- return GetMilleModule(i);\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-AliITSAlignMille2Module *AliITSAlignMille2::GetMilleModuleBySymName(const Char_t* symname) const\r
-{\r
- // return pointer to a defined supermodule\r
- // return NULL if error\r
- UShort_t vid = AliITSAlignMille2Module::GetVolumeIDFromSymname(symname);\r
- if (vid>0) return GetMilleModuleByVID(vid);\r
- else { // this is not alignable module, need to look within defined supermodules\r
- int i = IsSymDefined(symname);\r
- if (i>=0) return GetMilleModule(i);\r
- }\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-AliITSAlignMille2Module *AliITSAlignMille2::GetMilleModuleIfContained(const Char_t* symname) const\r
-{\r
- // return pointer to a defined/contained supermodule\r
- // return NULL otherwise\r
- int i = IsSymContained(symname);\r
- return i<0 ? 0 : GetMilleModule(i);\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-AliAlignObjParams* AliITSAlignMille2::GetPrealignedObject(const Char_t* symname) const\r
-{\r
- // get delta from prealignment for given volume\r
- if (!fPrealignment) return 0;\r
- for (int ipre=fPrealignment->GetEntriesFast();ipre--;) { // was the corresponding object prealigned?\r
- AliAlignObjParams* preob = (AliAlignObjParams*)fPrealignment->At(ipre);\r
- if (!strcmp(preob->GetSymName(),symname)) return preob;\r
- }\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-AliAlignObjParams* AliITSAlignMille2::GetConstrRefObject(const Char_t* symname) const\r
-{\r
- // get delta with respect to which the constraint is declared\r
- if (!fConstrRef) return 0;\r
- for (int ipre=fConstrRef->GetEntriesFast();ipre--;) { // was the corresponding object prealigned?\r
- AliAlignObjParams* preob = (AliAlignObjParams*)fConstrRef->At(ipre);\r
- if (!strcmp(preob->GetSymName(),symname)) return preob;\r
- }\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Bool_t AliITSAlignMille2::InitRiemanFit() \r
-{\r
- // Initialize Riemann Fitter for current track\r
- // return kFALSE if error\r
-\r
- if (!fBOn) return kFALSE;\r
-\r
- Int_t npts=0;\r
- AliTrackPoint ap;\r
- npts = fTrack->GetNPoints();\r
- AliDebug(3,Form("Fitting track with %d points",npts));\r
-\r
- fRieman->Reset();\r
- fRieman->SetTrackPointArray(fTrack);\r
-\r
- TArrayI ai(npts);\r
- for (Int_t ipt=0; ipt<npts; ipt++) ai[ipt]=fTrack->GetVolumeID()[ipt];\r
- \r
- // fit track with 5 params in his own tracking-rotated reference system\r
- // xc = -p[1]/p[0];\r
- // yc = 1/p[0];\r
- // R = sqrt( x0*x0 + y0*y0 - y0*p[2]);\r
- if (!fRieman->Fit(&ai,NULL,(AliGeomManager::ELayerID)1,(AliGeomManager::ELayerID)6)) {\r
- return kFALSE;\r
- }\r
-\r
- for (int i=0; i<5; i++)\r
- fLocalInitParam[i] = fRieman->GetParam()[i];\r
- \r
- return kTRUE;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void trackFit2D(Int_t &, Double_t *, double &chi2, double *par, int flag)\r
-{\r
- // local function for minuit\r
- const double kTiny = 1.e-14;\r
- chi2 = 0;\r
- static AliTrackPoint pnt;\r
- static Bool_t fullErr2D;\r
- //\r
- if (flag==1) fullErr2D = kFALSE;//kTRUE;\r
- enum {kAX,kAZ,kBX,kBZ};\r
- enum {kXX=0,kXY=1,kXZ=2,kYX=kXY,kYY=3,kYZ=4,kZX=kXZ,kZY=kYZ,kZZ=5};\r
- //\r
- AliITSAlignMille2* alig = AliITSAlignMille2::GetInstance();\r
- AliTrackPointArray* track = alig->GetCurrentTrack();\r
- //\r
- int npts = track->GetNPoints();\r
- for (int ip=0;ip<npts;ip++) {\r
- track->GetPoint(pnt,ip);\r
- const float *cov = pnt.GetCov();\r
- double y = pnt.GetY();\r
- double dx = pnt.GetX() - (par[kAX]+y*par[kBX]);\r
- double dz = pnt.GetZ() - (par[kAZ]+y*par[kBZ]);\r
- double xxe = cov[kXX];\r
- double zze = cov[kZZ];\r
- double xze = cov[kXZ];\r
- //\r
- if (fullErr2D) {\r
- xxe += par[kBX]*par[kBX]*cov[kYY]-2.*par[kBX]*cov[kXY];\r
- zze += par[kBZ]*par[kBZ]*cov[kYY]-2.*par[kBZ]*cov[kZY];\r
- xze += par[kBX]*par[kBZ]*cov[kYY]-cov[kYZ]*par[kBZ]-cov[kXY]*par[kBX];\r
- }\r
- //\r
- double det = xxe*zze - xze*xze;\r
- if (det<kTiny) {\r
- printf("Negative diag. error (det=%+e) |sxx:%+e szz:%+e sxz:%+e| bx:%+e bz:%+e|\n"\r
- "Discarding correlation term\n",det,xxe,zze,xze,par[kBX],par[kBZ]);\r
- xxe = cov[kXX];\r
- zze = cov[kZZ];\r
- xze = cov[kXZ];\r
- fullErr2D = kFALSE;\r
- }\r
- double xxeI = zze/det;\r
- double zzeI = xxe/det;\r
- double xzeI =-xze/det;\r
- //\r
- chi2 += dx*dx*xxeI + dz*dz*zzeI + 2.*dx*dz*xzeI;\r
- // \r
- // printf("%d | %+e %+e %+e %+e %+e -> %+e\n",ip,dx,dz,xxeI,zzeI,xzeI, chi2);\r
- }\r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::InitTrackParams(int meth) \r
-{\r
- /// initialize local parameters with different methods\r
- /// for current track (fTrack)\r
- Int_t npts=0;\r
- AliTrackPoint ap;\r
- double sX=0,sXY=0,sZ=0,sZY=0,sY=0,sYY=0,det=0;\r
- // simple linear interpolation\r
- // get local starting parameters (to be substituted by ESD track parms)\r
- // local parms (fLocalInitParam[]) are:\r
- // [0] = global x coord. of straight line intersection at y=0 plane\r
- // [1] = global z coord. of straight line intersection at y=0 plane\r
- // [2] = px/py \r
- // [3] = pz/py\r
- // test #1: linear fit in x(y) and z(y)\r
- npts = fTrack->GetNPoints();\r
- AliDebug(3,Form("*** initializing track with %d points ***",npts));\r
- for (int i=npts;i--;) {\r
- sY += fTrack->GetY()[i];\r
- sYY += fTrack->GetY()[i]*fTrack->GetY()[i];\r
- sX += fTrack->GetX()[i];\r
- sXY += fTrack->GetX()[i]*fTrack->GetY()[i];\r
- sZ += fTrack->GetZ()[i];\r
- sZY += fTrack->GetZ()[i]*fTrack->GetY()[i];\r
- }\r
- det = sYY*npts-sY*sY;\r
- if (det==0) det = 1E-20;\r
- fLocalInitParam[0] = (sX*sYY-sY*sXY)/det;\r
- fLocalInitParam[2] = (sXY*npts-sY*sX)/det;\r
- //\r
- fLocalInitParam[1] = (sZ*sYY-sY*sZY)/det;\r
- fLocalInitParam[3] = (sZY*npts-sY*sZ)/det;\r
- // pepo200709\r
- fLocalInitParam[4] = 0.0;\r
- // endpepo200709\r
-\r
- AliDebug(2,Form("X = p0gx + ugx*Y : p0gx = %f ugx = %f\n",fLocalInitParam[0],fLocalInitParam[2]));\r
- //\r
- if (meth==1) return;\r
- //\r
- // perform full fit accounting for cov.matrix\r
- static TVirtualFitter *minuit = 0;\r
- static Double_t step[5] = {1E-3,1E-3,1E-4,1E-4,1E-5};\r
- static Double_t arglist[10];\r
- //\r
- if (!minuit) {\r
- minuit = TVirtualFitter::Fitter(0,4);\r
- minuit->SetFCN(trackFit2D);\r
- arglist[0] = 1;\r
- minuit->ExecuteCommand("SET ERR",arglist, 1);\r
- //\r
- arglist[0] = -1;\r
- minuit->ExecuteCommand("SET PRINT",arglist,1);\r
- //\r
- }\r
- //\r
- minuit->SetParameter(0, "ax", fLocalInitParam[0], step[0], 0,0);\r
- minuit->SetParameter(1, "az", fLocalInitParam[1], step[1], 0,0);\r
- minuit->SetParameter(2, "bx", fLocalInitParam[2], step[2], 0,0);\r
- minuit->SetParameter(3, "bz", fLocalInitParam[3], step[3], 0,0);\r
- //\r
- arglist[0] = 1000; // number of function calls \r
- arglist[1] = 0.001; // tolerance \r
- minuit->ExecuteCommand("MIGRAD",arglist,2);\r
- //\r
- for (int i=0;i<4;i++) fLocalInitParam[i] = minuit->GetParameter(i);\r
- for (int i=0;i<4;i++) for (int j=0;j<4;j++) fLocalInitParEr[i][j] = minuit->GetCovarianceMatrixElement(i,j);\r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::IsSymDefined(const Char_t* symname) const\r
-{\r
- // checks if supermodule with this symname is defined and return the internal index\r
- // return -1 if not.\r
- for (int k=fNModules;k--;) if (!strcmp(symname,GetMilleModule(k)->GetName())) return k;\r
- return -1; \r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::IsSymContained(const Char_t* symname) const\r
-{\r
- // checks if module with this symname is defined and return the internal index\r
- // return -1 if not.\r
- UShort_t vid = AliITSAlignMille2Module::GetVolumeIDFromSymname(symname);\r
- if (vid>0) return IsVIDContained(vid);\r
- // only sensors have real vid, but maybe we have a supermodule with fake vid? \r
- // IMPORTANT: always start from the end to start from the sensors\r
- return IsSymDefined(symname);\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::IsVIDDefined(UShort_t voluid) const\r
-{\r
- // checks if supermodule 'voluid' is defined and return the internal index\r
- // return -1 if not.\r
- for (int k=fNModules;k--;) if (voluid==GetMilleModule(k)->GetVolumeID()) return k;\r
- return -1; \r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::IsVIDContained(UShort_t voluid) const\r
-{\r
- // checks if the sensitive module 'voluid' is contained inside a supermodule \r
- // and return the internal index of the last identified supermodule\r
- // return -1 if error\r
- // IMPORTANT: always start from the end to start from the sensors\r
- if (AliITSAlignMille2Module::GetIndexFromVolumeID(voluid)<0) return -1;\r
- for (int k=fNModules;k--;) if (GetMilleModule(k)->IsIn(voluid)) return k;\r
- return -1; \r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::CheckCurrentTrack() \r
-{\r
- /// checks if AliTrackPoints belongs to defined modules\r
- /// return number of good poins\r
- /// return 0 if not enough points\r
-\r
- Int_t npts = fTrack->GetNPoints();\r
- Int_t ngoodpts=0;\r
- // debug points\r
- for (int j=0; j<npts; j++) if (IsVIDContained(fTrack->GetVolumeID()[j])>=0) ngoodpts++;\r
- //\r
- if (ngoodpts<fMinNPtsPerTrack) return 0;\r
-\r
- return ngoodpts;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::ProcessTrack(const AliTrackPointArray *track) \r
-{\r
- /// Process track; Loop over hits and set local equations\r
- /// here 'track' is a AliTrackPointArray\r
- /// return 0 if success;\r
- \r
- if (!fIsMilleInit) Init();\r
- //\r
- Int_t npts = track->GetNPoints();\r
- AliDebug(2,Form("*** Input track with %d points ***",npts));\r
-\r
- // preprocessing of the input track: keep only points in defined volumes,\r
- // move points if prealignment is set, sort by Yglo if required\r
- \r
- fTrack=PrepareTrack(track);\r
- if (!fTrack) return -1;\r
-\r
- npts = fTrack->GetNPoints();\r
- if (npts>kMaxPoints) {\r
- AliError(Form("Compiled with kMaxPoints=%d, current track has %d points",kMaxPoints,npts));\r
- }\r
- AliDebug(2,Form("*** Processing prepared track with %d points ***",npts));\r
- \r
- if (!fBOn) { // straight lines \r
- // set local starting parameters (to be substituted by ESD track parms)\r
- // local parms (fLocalInitParam[]) are:\r
- // [0] = global x coord. of straight line intersection at y=0 plane\r
- // [1] = global z coord. of straight line intersection at y=0 plane\r
- // [2] = px/py \r
- // [3] = pz/py\r
- InitTrackParams(fInitTrackParamsMeth); \r
- } \r
- else {\r
- // local parms (fLocalInitParam[]) are the Riemann Fitter params\r
- if (!InitRiemanFit()) {\r
- AliInfo("Riemann fit failed! skipping this track...");\r
- fTrack=NULL;\r
- return -5;\r
- }\r
- }\r
- \r
- Int_t nloceq=0;\r
- Int_t ngloeq=0;\r
- static Mille2Data md[kMaxPoints];\r
- //\r
- for (Int_t ipt=0; ipt<npts; ipt++) {\r
- fTrack->GetPoint(fCluster,ipt);\r
- fCluster.SetUniqueID(ipt);\r
- AliDebug(2,Form("\n--- processing point %d --- \n",ipt)); \r
-\r
- // set geometry parameters for the the current module\r
- if (InitModuleParams()) continue;\r
- AliDebug(2,Form(" VolID=%d Index=%d InternalIdx=%d symname=%s\n", \r
- track->GetVolumeID()[ipt], fCurrentModule->GetIndex(),\r
- fCurrentModule->GetUniqueID(), AliGeomManager::SymName(track->GetVolumeID()[ipt]) ));\r
- AliDebug(2,Form(" Preprocessed Point = ( %f , %f , %f ) \n",fCluster.GetX(),fCluster.GetY(),fCluster.GetZ()));\r
- int res = AddLocalEquation(md[nloceq]);\r
- if (res<0) {fTotBadLocEqPoints++; nloceq = 0; break;}\r
- else if (res==0) nloceq++;\r
- else {nloceq++; ngloeq++;}\r
- } // end loop over points\r
- //\r
- fTrack=NULL;\r
- // not enough good points?\r
- if (nloceq<fMinNPtsPerTrack || ngloeq<1) return -1;\r
- //\r
- // finally send local equations to millepede\r
- SetLocalEquations(md,nloceq);\r
- fMillepede->SaveRecordData(); // RRR\r
- //\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::CalcIntersectionPoint(Double_t *lpar, Double_t *gpar) \r
-{\r
- /// calculate track intersection point in local coordinates\r
- /// according with a given set of parameters (local(4) and global(6))\r
- /// and fill fPintLoc/Glo\r
- /// local are: pgx0, pgz0, ugx, ugz OR riemann fitters pars\r
- /// global are: tx,ty,tz,psi,theta,phi (Raff's delta angles in deg.)\r
- /// return 0 if success\r
- \r
- 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
- 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
-\r
- \r
- // prepare the TGeoHMatrix\r
- TGeoHMatrix *tempHMat = fCurrentModule->GetSensitiveVolumeModifiedMatrix(fCluster.GetVolumeID(),gpar,\r
- !fUseGlobalDelta);\r
- if (!tempHMat) return -1;\r
- \r
- Double_t v0g[3]; // vector with straight line direction in global coord.\r
- Double_t p0g[3]; // point of the straight line (glo)\r
- \r
- if (fBOn) { // B FIELD!\r
- AliTrackPoint prf; \r
- for (int ip=0; ip<5; ip++)\r
- fRieman->SetParam(ip,lpar[ip]);\r
-\r
- if (!fRieman->GetPCA(fCluster,prf)) {\r
- AliInfo(Form("error in GetPCA for point %d",fCluster.GetVolumeID()));\r
- return -3;\r
- }\r
- // now determine straight line passing tangent to fit curve at prf\r
- // ugx = dX/dY_glo = DeltaX/DeltaY_glo\r
- // mo' P1=(X,Y,Z)_glo_prf\r
- // => (x,y,Z)_trk_prf ruotando di alpha...\r
- Double_t alpha=fRieman->GetAlpha();\r
- Double_t x1g = prf.GetX();\r
- Double_t y1g = prf.GetY();\r
- Double_t z1g = prf.GetZ();\r
- Double_t x1t = x1g*TMath::Cos(alpha) + y1g*TMath::Sin(alpha);\r
- Double_t y1t = -x1g*TMath::Sin(alpha) + y1g*TMath::Cos(alpha);\r
- Double_t z1t = z1g; \r
-\r
- Double_t x2t = x1t+1.0;\r
- Double_t y2t = y1t+fRieman->GetDYat(x1t);\r
- Double_t z2t = z1t+fRieman->GetDZat(x1t);\r
- Double_t x2g = x2t*TMath::Cos(alpha) - y2t*TMath::Sin(alpha);\r
- Double_t y2g = x2t*TMath::Sin(alpha) + y2t*TMath::Cos(alpha);\r
- Double_t z2g = z2t; \r
-\r
- AliDebug(3,Form("Riemann frame: fAlpha = %f = %f ",alpha,alpha*180./TMath::Pi()));\r
- AliDebug(3,Form(" prf_glo=( %f , %f , %f ) prf_rf=( %f , %f , %f )\n", x1g,y1g,z1g, x1t,y1t,z1t));\r
- AliDebug(3,Form(" mov_glo=( %f , %f , %f ) rf=( %f , %f , %f )\n",x2g,y2g,z2g, x2t,y2t,z2t));\r
- \r
- if (TMath::Abs(y2g-y1g)<1e-15) {\r
- AliInfo("DeltaY=0! Cannot proceed...");\r
- return -1;\r
- }\r
- // ugx,1,ugz\r
- v0g[0] = (x2g-x1g)/(y2g-y1g);\r
- v0g[1]=1.0;\r
- v0g[2] = (z2g-z1g)/(y2g-y1g);\r
- \r
- // point: just keep prf\r
- p0g[0]=x1g;\r
- p0g[1]=y1g;\r
- p0g[2]=z1g;\r
- } \r
- else { // staight line\r
- // vector of initial straight line direction in glob. coord\r
- v0g[0]=lpar[2];\r
- v0g[1]=1.0;\r
- v0g[2]=lpar[3];\r
- \r
- // intercept in yg=0 plane in glob coord\r
- p0g[0]=lpar[0];\r
- p0g[1]=0.0;\r
- p0g[2]=lpar[1];\r
- }\r
- 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
- \r
- // same in local coord.\r
- Double_t p0l[3],v0l[3];\r
- tempHMat->MasterToLocalVect(v0g,v0l);\r
- tempHMat->MasterToLocal(p0g,p0l);\r
- \r
- if (TMath::Abs(v0l[1])<1e-15) {\r
- AliInfo("Track Y direction in local frame is zero! Cannot proceed...");\r
- return -1;\r
- }\r
- \r
- // local intersection point\r
- fPintLoc[0] = p0l[0] - (v0l[0]/v0l[1])*p0l[1];\r
- fPintLoc[1] = 0;\r
- fPintLoc[2] = p0l[2] - (v0l[2]/v0l[1])*p0l[1];\r
- \r
- // global intersection point\r
- tempHMat->LocalToMaster(fPintLoc,fPintGlo);\r
- 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
- \r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::CalcDerivatives(Int_t paridx, Bool_t islpar) \r
-{\r
- /// calculate numerically (ROOT's style) the derivatives for\r
- /// local X intersection and local Z intersection\r
- /// parlist: local (islpar=kTRUE) pgx0, pgz0, ugx0, ugz0 OR riemann's params\r
- /// global (islpar=kFALSE) tx, ty, tz, psi, theta, phi (Raf's angles in deg)\r
- /// return 0 if success\r
- \r
- // copy initial parameters\r
- Double_t lpar[kNLocal];\r
- Double_t gpar[kNParCh];\r
- Double_t *derivative;\r
- for (Int_t i=0; i<kNLocal; i++) lpar[i]=fLocalInitParam[i];\r
- for (Int_t i=0; i<kNParCh; i++) gpar[i]=fModuleInitParam[i];\r
-\r
- // trial with fixed dpar...\r
- Double_t dpar = 0.;\r
-\r
- if (islpar) { // track parameters\r
- //dpar=fLocalInitParam[paridx]*0.001;\r
- // set minimum dpar\r
- derivative = fDerivativeLoc[paridx];\r
- if (!fBOn) {\r
- if (paridx<3) dpar=1.0e-4; // translations\r
- else dpar=1.0e-6; // direction\r
- }\r
- else { // B Field\r
- // pepo: proviamo con 1/1000, poi evenctually 1/100...\r
- Double_t dfrac=0.01;\r
- switch(paridx) {\r
- case 0:\r
- // RMS cosmics: 1e-4\r
- dpar = TMath::Max(1.0e-6,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
- break;\r
- case 1: \r
- // RMS cosmics: 0.2\r
- dpar = TMath::Max(0.002,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
- break;\r
- case 2: \r
- // RMS cosmics: 9\r
- dpar = TMath::Max(0.09,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
- break;\r
- case 3: \r
- // RMS cosmics: 7\r
- dpar = TMath::Max(0.07,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
- break;\r
- case 4: \r
- // RMS cosmics: 0.3\r
- dpar = TMath::Max(0.003,TMath::Abs(fLocalInitParam[paridx]*dfrac)); \r
- break;\r
- }\r
- }\r
- }\r
- else { // alignment global parameters\r
- derivative = fDerivativeGlo[paridx];\r
- //dpar=fModuleInitParam[paridx]*0.001;\r
- if (paridx<3) dpar=1.0e-4; // translations\r
- else dpar=1.0e-2; // angles \r
- }\r
-\r
- AliDebug(3,Form("+++ using dpar=%g",dpar));\r
- \r
- // calculate derivative ROOT's like:\r
- // using f(x+h),f(x-h),f(x+h/2),f(x-h2)...\r
- Double_t pintl1[3]; // f(x-h)\r
- Double_t pintl2[3]; // f(x-h/2)\r
- Double_t pintl3[3]; // f(x+h/2)\r
- Double_t pintl4[3]; // f(x+h)\r
- \r
- // first values\r
- if (islpar) lpar[paridx] -= dpar;\r
- else gpar[paridx] -= dpar;\r
- if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
- for (Int_t i=0; i<3; i++) pintl1[i]=fPintLoc[i];\r
-\r
- // second values\r
- if (islpar) lpar[paridx] += dpar/2;\r
- else gpar[paridx] += dpar/2;\r
- if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
- for (Int_t i=0; i<3; i++) pintl2[i]=fPintLoc[i];\r
-\r
- // third values\r
- if (islpar) lpar[paridx] += dpar;\r
- else gpar[paridx] += dpar;\r
- if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
- for (Int_t i=0; i<3; i++) pintl3[i]=fPintLoc[i];\r
-\r
- // fourth values\r
- if (islpar) lpar[paridx] += dpar/2;\r
- else gpar[paridx] += dpar/2;\r
- if (CalcIntersectionPoint(lpar, gpar)) return -2;\r
- for (Int_t i=0; i<3; i++) pintl4[i]=fPintLoc[i];\r
-\r
- Double_t h2 = 1./(2.*dpar);\r
- Double_t d0 = pintl4[0]-pintl1[0];\r
- Double_t d2 = 2.*(pintl3[0]-pintl2[0]);\r
- derivative[0] = h2*(4*d2 - d0)/3.;\r
- if (TMath::Abs(derivative[0]) < 1.0e-9) derivative[0] = 0.0;\r
-\r
- d0 = pintl4[2]-pintl1[2];\r
- d2 = 2.*(pintl3[2]-pintl2[2]);\r
- derivative[2] = h2*(4*d2 - d0)/3.;\r
- if (TMath::Abs(derivative[2]) < 1.0e-9) derivative[2]=0.0;\r
-\r
- AliDebug(3,Form("\n+++ derivatives +++ \n"));\r
- AliDebug(3,Form("+++ dXLoc/dpar = %g +++\n",derivative[0]));\r
- AliDebug(3,Form("+++ dZLoc/dpar = %g +++\n\n",derivative[2]));\r
- \r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::AddLocalEquation(Mille2Data &m) \r
-{\r
- /// Define local equation for current cluster in X and Z coor.\r
- /// and store them to memory\r
- /// return -1 in case of failure to build some equation\r
- /// 0 if no free global parameters were found but local eq is built\r
- /// 1 if both local and global eqs are built\r
- //\r
- // store first intersection point\r
- if (CalcIntersectionPoint(fLocalInitParam, fModuleInitParam)) return -1; \r
- for (Int_t i=0; i<3; i++) fPintLoc0[i]=fPintLoc[i];\r
- AliDebug(2,Form("Intesect. point: L( %f , %f , %f )",fPintLoc[0],fPintLoc[1],fPintLoc[2]));\r
- \r
- // calculate local derivatives numerically\r
- Bool_t zeroX = kTRUE;\r
- Bool_t zeroZ = kTRUE;\r
- //\r
- for (Int_t i=0; i<fNLocal; i++) {\r
- if (CalcDerivatives(i,kTRUE)) return -1;\r
- m.fDerLocX[i] = fDerivativeLoc[i][0];\r
- m.fDerLocZ[i] = fDerivativeLoc[i][2];\r
- if (zeroX) zeroX = fDerivativeLoc[i][0]==0;\r
- if (zeroZ) zeroZ = fDerivativeLoc[i][2]==0;\r
- }\r
- // 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
- //\r
- if (zeroX) {AliInfo("Skipping: zero local X derivatives!"); return -1;}\r
- if (zeroZ) {AliInfo("Skipping: zero local Z derivatives!"); return -1;}\r
- //\r
- int ifill = 0;\r
- //\r
- AliITSAlignMille2Module* endModule = fCurrentModule;\r
- //\r
- zeroX = zeroZ = kTRUE;\r
- Bool_t dfDone[kNParCh];\r
- for (int i=kNParCh;i--;) dfDone[i] = kFALSE;\r
- m.fNModFilled = 0;\r
- // \r
- // special block for SDD derivatives\r
- Double_t jacobian[kNParChGeom];\r
- Int_t nmodTested = 0;\r
- //\r
- do {\r
- if (fCurrentModule->GetNParFree()==0) continue;\r
- nmodTested++;\r
- for (Int_t i=0; i<kNParChGeom; i++) { // common for all sensors: derivatives over geom params \r
- //\r
- if (!fUseGlobalDelta) dfDone[i] = kFALSE; // for global deltas the derivatives at diff. levels are different\r
- if (fCurrentModule->GetParOffset(i)<0) continue; // this parameter is not explicitly fitted\r
- if (!dfDone[i]) { \r
- if (CalcDerivatives(i,kFALSE)) return -1; \r
- else {\r
- dfDone[i] = kTRUE;\r
- if (zeroX) zeroX = fDerivativeGlo[i][0]==0;\r
- if (zeroZ) zeroZ = fDerivativeGlo[i][2]==0;\r
- }\r
- }\r
- //\r
- m.fDerGloX[ifill] = fDerivativeGlo[i][0];\r
- m.fDerGloZ[ifill] = fDerivativeGlo[i][2];\r
- m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(i);\r
- }\r
- //\r
- // specific for special sensors\r
- if ( fCurrentModule->IsSDD() && \r
- (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0)>=0 ||\r
- fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV)>=0) ) {\r
- //\r
- // assume for sensor local xloc = xloc0 + V0*dT0+dV*(T-T0)\r
- // where V0 and T are the nominal drift velocity, time and time0\r
- // and the dT0 and dV are the corrections:\r
- // dX/dT0 = dX/dxloc * dxloc/dT0 = dX/dxloc * V0\r
- // dX/dV = dX/dxloc * dxloc/dV = dX/dxloc * (T-T0)\r
- // IMPORTANT: the geom derivatives are over the SENSOR LOCAL parameters\r
- //\r
- if (!dfDone[AliITSAlignMille2Module::kDOFT0] || !dfDone[AliITSAlignMille2Module::kDOFDV]) {\r
- //\r
- double dXdxlocsens=0., dZdxlocsens=0.;\r
- //\r
- // if the current module is the sensor itself and we work with local params, then \r
- // we can directly take dX/dxloc_sens dZ/dxloc_sens\r
- if (!fUseGlobalDelta && fCurrentModule->GetVolumeID()==fCluster.GetVolumeID()) {\r
- if (dfDone[AliITSAlignMille2Module::kDOFTX]) {\r
- CalcDerivatives(AliITSAlignMille2Module::kDOFTX,kFALSE); \r
- dfDone[AliITSAlignMille2Module::kDOFTX] = kTRUE;\r
- }\r
- dXdxlocsens = fDerivativeGlo[AliITSAlignMille2Module::kDOFTX][0];\r
- dZdxlocsens = fDerivativeGlo[AliITSAlignMille2Module::kDOFTX][2];\r
- }\r
- //\r
- else { // need to perform some transformations\r
- // fetch the jacobian of the transformation from the sensors local frame to the frame\r
- // where the parameters are defined:\r
- // Global: dX/dxloc_sens = dX/dxgl*dxgl/dxloc_sens + ...dX/dphigl*dphigl/dxloc_sens\r
- if (fUseGlobalDelta) fCurrentModule->CalcDerivGloLoc(fCluster.GetVolumeID(),\r
- AliITSAlignMille2Module::kDOFTX, jacobian);\r
- // Local: dX/dxloc_sens = dX/dxcurr*dxcurr/dxloc_sens +..+dX/dphicurr * dphicurr/dxloc_sens \r
- else fCurrentModule->CalcDerivCurLoc(fCluster.GetVolumeID(),\r
- AliITSAlignMille2Module::kDOFTX, jacobian);\r
- //\r
- for (int j=0;j<kNParChGeom;j++) {\r
- // need global derivative even if the j-th param is locked\r
- if (!dfDone[j]) {CalcDerivatives(j,kFALSE); dfDone[j] = kTRUE;}\r
- dXdxlocsens += fDerivativeGlo[j][0] * jacobian[j];\r
- dZdxlocsens += fDerivativeGlo[j][2] * jacobian[j];\r
- }\r
- }\r
- //\r
- if (zeroX) zeroX = dXdxlocsens == 0;\r
- if (zeroZ) zeroZ = dZdxlocsens == 0;\r
- //\r
- double vdrift = GetVDriftSDD();\r
- double tdrift = GetTDriftSDD();\r
- //\r
- fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][0] = dXdxlocsens*vdrift;\r
- fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][2] = dZdxlocsens*vdrift;\r
- dfDone[AliITSAlignMille2Module::kDOFT0] = kTRUE;\r
- //\r
- fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][0] = -dXdxlocsens*TMath::Sign(tdrift,vdrift);\r
- fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][2] = -dZdxlocsens*TMath::Sign(tdrift,vdrift);\r
- dfDone[AliITSAlignMille2Module::kDOFDV] = kTRUE;\r
- //\r
- }\r
- //\r
- if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0)>=0) {\r
- m.fDerGloX[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][0];\r
- m.fDerGloZ[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][2];\r
- m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0); \r
- }\r
- //\r
- if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV)>=0) {\r
- m.fDerGloX[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][0];\r
- m.fDerGloZ[ifill] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][2];\r
- m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV); \r
- }\r
- }\r
- //\r
- m.fModuleID[m.fNModFilled++] = fCurrentModule->GetUniqueID();\r
- } while( (fCurrentModule=fCurrentModule->GetParent()) );\r
- //\r
- if (nmodTested>0 && zeroX) {AliInfo("Skipping: zero global X derivatives!");return -1;}\r
- if (nmodTested>0 && zeroZ) {AliInfo("Skipping: zero global Z derivatives!");return -1;}\r
- //\r
- // ok, can copy to m\r
- AliDebug(2,Form("Adding local equation X with fMeas=%.6f and fSigma=%.6f",(fMeasLoc[0]-fPintLoc0[0]), fSigmaLoc[0]));\r
- m.fMeasX = fMeasLoc[0]-fPintLoc0[0];\r
- m.fSigmaX = fSigmaLoc[0];\r
- //\r
- AliDebug(2,Form("Adding local equation Z with fMeas=%.6f and fSigma=%.6f",(fMeasLoc[2]-fPintLoc0[2]), fSigmaLoc[2]));\r
- m.fMeasZ = fMeasLoc[2]-fPintLoc0[2];\r
- m.fSigmaZ = fSigmaLoc[2];\r
- //\r
- m.fNGlobFilled = ifill;\r
- fCurrentModule = endModule;\r
- //\r
- return Int_t(!zeroX && !zeroZ);\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::SetLocalEquations(const Mille2Data *marr, Int_t neq) \r
-{\r
- /// Set local equations with data stored in m\r
- /// return 0 if success\r
- //\r
- for (Int_t j=0; j<neq; j++) {\r
- //\r
- const Mille2Data &m = marr[j];\r
- //\r
- // set equation for Xloc coordinate\r
- AliDebug(2,Form("setting local equation X with fMeas=%.6f and fSigma=%.6f",m.fMeasX, m.fSigmaX));\r
- for (int i=fNLocal; i--;) SetLocalDerivative( i, m.fDerLocX[i] );\r
- for (int i=m.fNGlobFilled;i--;) SetGlobalDerivative( m.fParMilleID[i] , m.fDerGloX[i] );\r
- fMillepede->SetLocalEquation(fGlobalDerivatives, fLocalDerivatives, m.fMeasX, m.fSigmaX); \r
- //\r
- // set equation for Zloc coordinate\r
- AliDebug(2,Form("setting local equation Z with fMeas=%.6f and fSigma=%.6f",m.fMeasZ, m.fSigmaZ));\r
- for (int i=fNLocal; i--;) SetLocalDerivative( i, m.fDerLocZ[i] );\r
- for (int i=m.fNGlobFilled;i--;) SetGlobalDerivative( m.fParMilleID[i] , m.fDerGloZ[i] );\r
- fMillepede->SetLocalEquation(fGlobalDerivatives, fLocalDerivatives, m.fMeasZ, m.fSigmaZ); \r
- //\r
- for (int i=m.fNModFilled;i--;) GetMilleModule(m.fModuleID[i])->IncNProcessedPoints();\r
- //\r
- }\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::GlobalFit()\r
-{\r
- /// Call global fit; Global parameters are stored in parameters\r
- if (!fIsMilleInit) Init();\r
- //\r
- ApplyPreConstraints();\r
- int res = fMillepede->GlobalFit();\r
- AliInfo(Form("%s fitting global parameters!",res ? "Done":"Failed"));\r
- if (res) {\r
- // fetch the parameters\r
- for (int imd=fNModules;imd--;) {\r
- AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
- int nprocp = 0;\r
- for (int ip=mod->GetNParTot();ip--;) {\r
- int idp = mod->GetParOffset(ip);\r
- if (idp<0) continue; // was not in the explicit fit\r
- mod->SetParVal(ip,fMillepede->GetFinalParam(idp));\r
- mod->SetParErr(ip,fMillepede->GetFinalError(idp));\r
- int np = fMillepede->GetProcessedPoints(idp);\r
- if (TMath::Abs(np)>TMath::Abs(nprocp)) nprocp = np;\r
- }\r
- if (!mod->GetNProcessedPoints()) mod->SetNProcessedPoints(nprocp);\r
- }\r
-\r
- }\r
- ApplyPostConstraints();\r
- return res;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::PrintGlobalParameters() \r
-{\r
- /// Print global parameters\r
- if (!fIsMilleInit) {\r
- AliInfo("Millepede has not been initialized!");\r
- return;\r
- }\r
- fMillepede->PrintGlobalParameters();\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Int_t AliITSAlignMille2::LoadSuperModuleFile(const Char_t *sfile)\r
-{ \r
- // load definitions of supermodules from a root file\r
- // return 0 if success\r
-\r
- TFile *smf=TFile::Open(sfile);\r
- if (!smf->IsOpen()) {\r
- AliInfo(Form("Cannot open supermodule file %s",sfile));\r
- return -1;\r
- }\r
-\r
- TClonesArray *sma=(TClonesArray*)smf->Get("ITSMilleSuperModules");\r
- if (!sma) {\r
- AliInfo(Form("Cannot find ITSMilleSuperModules array in file"));\r
- return -2; \r
- } \r
- Int_t nsma=sma->GetEntriesFast();\r
- AliInfo(Form("Array of SuperModules with %d entries\n",nsma));\r
- //\r
- // pepo200709\r
- Char_t st[2048];\r
- char symname[250];\r
- // end pepo200709\r
-\r
- UShort_t volid;\r
- TGeoHMatrix m;\r
- //\r
- for (Int_t i=0; i<nsma; i++) {\r
- AliAlignObjParams *a = (AliAlignObjParams*)sma->UncheckedAt(i);\r
- volid=a->GetVolUID();\r
- strcpy(st,a->GetSymName());\r
- a->GetMatrix(m);\r
- //\r
- sscanf(st,"%s",symname);\r
- //\r
- // decode module list\r
- char *stp=strstr(st,"ModuleList:");\r
- if (!stp) return -3;\r
- stp += 11;\r
- int idx[2200];\r
- char spp[200]; int jp=0;\r
- char cl[20];\r
- strcpy(st,stp);\r
- int l=strlen(st);\r
- int j=0;\r
- int n=0;\r
- //\r
- while (j<=l) {\r
- if (st[j]==9 || st[j]==32 || st[j]==10 || st[j]==0) {\r
- spp[jp]=0;\r
- jp=0;\r
- if (strlen(spp)) {\r
- int k=strcspn(spp,"-");\r
- if (k<int(strlen(spp))) { // c'e' il -\r
- strcpy(cl,&(spp[k+1]));\r
- spp[k]=0;\r
- int ifrom=atoi(spp); int ito=atoi(cl);\r
- for (int b=ifrom; b<=ito; b++) {\r
- idx[n]=b;\r
- n++;\r
- }\r
- }\r
- else { // numerillo singolo\r
- idx[n]=atoi(spp);\r
- n++;\r
- }\r
- }\r
- }\r
- else {\r
- spp[jp]=st[j];\r
- jp++;\r
- }\r
- j++;\r
- }\r
- UShort_t volidsv[2198];\r
- for (j=0;j<n;j++) {\r
- volidsv[j]=AliITSAlignMille2Module::GetVolumeIDFromIndex(idx[j]);\r
- if (!volidsv[j]) {\r
- AliInfo(Form("Index %d not valid (range 0->%d)",idx[j],kMaxITSSensID));\r
- return -5;\r
- }\r
- }\r
- Int_t smindex=int(2198+volid-14336); // virtual index\r
- //\r
- fSuperModule.AddAtAndExpand(new AliITSAlignMille2Module(smindex,volid,symname,&m,n,volidsv),fNSuperModules);\r
- //\r
- fNSuperModules++;\r
- }\r
- //\r
- smf->Close();\r
- //\r
- return 0;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ConstrainModuleSubUnitsMean(Int_t idm, Double_t val, UInt_t pattern)\r
-{\r
- // require that sum of modifications for the childs of this module is = val, i.e.\r
- // the internal corrections moves the module as a whole by fixed value (0 by default).\r
- // pattern is the bit pattern for the parameters to constrain\r
- //\r
- if (fIsMilleInit) {\r
- AliInfo("Millepede has been already initialized: no constrain may be added!");\r
- return;\r
- }\r
- if (!GetMilleModule(idm)->GetNChildren()) return;\r
- TString nm = "cstrSUMean";\r
- nm += GetNConstraints();\r
- AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMean,\r
- idm,val,pattern);\r
- cstr->SetConstraintID(GetNConstraints());\r
- fConstraints.Add(cstr);\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ConstrainModuleSubUnitsMedian(Int_t idm, Double_t val, UInt_t pattern)\r
-{\r
- // require that median of the modifications for the childs of this module is = val, i.e.\r
- // the internal corrections moves the module as a whole by fixed value (0 by default) \r
- // module the outliers.\r
- // pattern is the bit pattern for the parameters to constrain\r
- // The difference between the mean and the median will be transfered to the parent\r
- if (fIsMilleInit) {\r
- AliInfo("Millepede has been already initialized: no constrain may be added!");\r
- return;\r
- }\r
- if (!GetMilleModule(idm)->GetNChildren()) return;\r
- TString nm = "cstrSUMed";\r
- nm += GetNConstraints();\r
- AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMedian,\r
- idm,val,pattern);\r
- cstr->SetConstraintID(GetNConstraints());\r
- fConstraints.Add(cstr);\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ConstrainOrphansMean(Double_t val, UInt_t pattern)\r
-{\r
- // require that median of the modifications for the supermodules which have no parents is = val, i.e.\r
- // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.\r
- // pattern is the bit pattern for the parameters to constrain\r
- //\r
- if (fIsMilleInit) {\r
- AliInfo("Millepede has been already initialized: no constrain may be added!");\r
- return;\r
- }\r
- TString nm = "cstrOMean";\r
- nm += GetNConstraints();\r
- AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMean,\r
- -1,val,pattern);\r
- cstr->SetConstraintID(GetNConstraints());\r
- fConstraints.Add(cstr);\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ConstrainOrphansMedian(Double_t val, UInt_t pattern)\r
-{\r
- // require that median of the modifications for the supermodules which have no parents is = val, i.e.\r
- // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.\r
- // pattern is the bit pattern for the parameters to constrain\r
- //\r
- if (fIsMilleInit) {\r
- AliInfo("Millepede has been already initialized: no constrain may be added!");\r
- return;\r
- }\r
- TString nm = "cstrOMed";\r
- nm += GetNConstraints();\r
- AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMedian,\r
- -1,val,pattern);\r
- cstr->SetConstraintID(GetNConstraints());\r
- fConstraints.Add(cstr);\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ConstrainLocal(const Char_t* name,Double_t *parcf,Int_t npar,Double_t val,Double_t err)\r
-{\r
- // apply constraint on parameters in the local frame\r
- if (fIsMilleInit) {\r
- AliInfo("Millepede has been already initialized: no constrain may be added!");\r
- return;\r
- }\r
- AliITSAlignMille2ConstrArray *cstr = new AliITSAlignMille2ConstrArray(name,parcf,npar,val,err);\r
- cstr->SetConstraintID(GetNConstraints());\r
- fConstraints.Add(cstr);\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ApplyGaussianConstraint(const AliITSAlignMille2ConstrArray* cstr)\r
-{\r
- // apply the constraint on the local corrections of a list of modules\r
- int nmod = cstr->GetNModules();\r
- double jacobian[AliITSAlignMille2Module::kMaxParGeom][AliITSAlignMille2Module::kMaxParGeom];\r
- //\r
- for (int imd=nmod;imd--;) {\r
- int modID = cstr->GetModuleID(imd);\r
- AliITSAlignMille2Module* mod = GetMilleModule(modID);\r
- ResetLocalEquation();\r
- int nadded = 0;\r
- double value = cstr->GetValue();\r
- double sigma = cstr->GetError();\r
- //\r
- // in case the reference (survey) deltas were imposed for Gaussian constraints\r
- // already accumulated corrections: they must be subtracted from the constraint value.\r
- if (IsConstraintWrtRef()) {\r
- //\r
- Double_t precal[AliITSAlignMille2Module::kMaxParTot];\r
- Double_t refcal[AliITSAlignMille2Module::kMaxParTot];\r
- for (int ip=AliITSAlignMille2Module::kMaxParTot;ip--;) {precal[ip]=0; refcal[ip] = 0.;}\r
- //\r
- // check if there was a reference delta provided for this module\r
- AliAlignObjParams* parref = GetConstrRefObject(mod->GetName());\r
- if (parref) parref->GetPars(refcal, refcal+3); // found reference delta\r
- //\r
- // extract already applied local corrections for this module\r
- if (fPrealignment) {\r
- //\r
- AliAlignObjParams *preo = GetPrealignedObject(mod->GetName());\r
- if (preo) {\r
- TGeoHMatrix preMat,tmpMat = *mod->GetMatrix(); // Delta_Glob * Delta_Glob_Par * M\r
- preo->GetMatrix(preMat); // Delta_Glob\r
- preMat.MultiplyLeft( &tmpMat.Inverse() ); // M^-1 * Delta_Glob_Par^-1 = (Delta_Glob_Par * M)^-1\r
- tmpMat.MultiplyLeft( &preMat ); // (Delta_Glob_Par * M)^-1 * Delta_Glob * Delta_Glob_Par * M = Delta_loc\r
- AliAlignObjParams algob;\r
- algob.SetMatrix(tmpMat);\r
- algob.GetPars(precal,precal+3); // local corrections for geometry\r
- }\r
- }\r
- //\r
- // subtract the contribution to constraint from precalibration \r
- for (int ipar=cstr->GetNCoeffs();ipar--;) value += (refcal[ipar]-precal[ipar])*cstr->GetCoeff(ipar);\r
- //\r
- } \r
- // \r
- if (fUseGlobalDelta) mod->CalcDerivLocGlo(&jacobian[0][0]);\r
- //\r
- for (int ipar=cstr->GetNCoeffs();ipar--;) {\r
- double coef = cstr->GetCoeff(ipar);\r
- if (coef==0) continue;\r
- //\r
- if (!fUseGlobalDelta || ipar>= AliITSAlignMille2Module::kMaxParGeom) { // \r
- // we are working with local params or if the given param is not related to geometry, \r
- // apply the constraint directly\r
- int parPos = mod->GetParOffset(ipar);\r
- if (parPos<0) continue; // not in the fit\r
- fGlobalDerivatives[parPos] += coef;\r
- nadded++;\r
- }\r
- else { // we are working with global params, while the constraint is on local ones -> jacobian\r
- for (int jpar=AliITSAlignMille2Module::kMaxParGeom;jpar--;) {\r
- int parPos = mod->GetParOffset(jpar);\r
- if (parPos<0) continue;\r
- fGlobalDerivatives[parPos] += coef*jacobian[ipar][jpar];\r
- nadded++;\r
- }\r
- } \r
- }\r
- if (nadded) AddConstraint(fGlobalDerivatives, value, sigma);\r
- }\r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ApplyPreConstraints()\r
-{\r
- // apply constriants which cannot be imposed after the fit\r
- int nconstr = GetNConstraints();\r
- for (int i=0;i<nconstr;i++) {\r
- AliITSAlignMille2Constraint* cstr = GetConstraint(i);\r
- //\r
- if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) {\r
- ApplyGaussianConstraint( (AliITSAlignMille2ConstrArray*)cstr);\r
- continue;\r
- } \r
- //\r
- if (cstr->GetType() == AliITSAlignMille2Constraint::kTypeMedian) continue; // post type constraint\r
- //\r
- if (!fUseGlobalDelta) continue; // mean/med constraints must be applied to global deltas\r
- // apply constraint on the mean's before the fit\r
- int imd = cstr->GetModuleID();\r
- if (imd>=0) {\r
- AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
- UInt_t pattern = 0;\r
- for (int ipar=mod->GetNParTot();ipar--;) {\r
- if (!cstr->IncludesParam(ipar)) continue;\r
- if (mod->GetParOffset(ipar)<0) continue; // parameter is not in the explicit fit -> post constraint\r
- pattern |= 0x1<<ipar;\r
- cstr->SetApplied(ipar);\r
- }\r
- ConstrainModuleSubUnits(imd,cstr->GetValue(),pattern);\r
- //\r
- }\r
- else if (!PseudoParentsAllowed()) {\r
- ConstrainOrphans(cstr->GetValue(),(UInt_t)cstr->GetPattern());\r
- cstr->SetApplied(-1);\r
- }\r
- }\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ApplyPostConstraints()\r
-{\r
- // apply constraints which can be imposed after the fit\r
- int nconstr = GetNConstraints();\r
- Bool_t convGlo = kFALSE;\r
- // check if there is something to do\r
- int ntodo = 0;\r
- for (int i=0;i<nconstr;i++) {\r
- AliITSAlignMille2Constraint* cstr = GetConstraint(i);\r
- if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) continue;\r
- if (cstr->GetRemainingPattern() == 0) continue;\r
- ntodo++;\r
- }\r
- if (!ntodo) return;\r
- //\r
- if (!fUseGlobalDelta) { // need to convert to global params\r
- ConvertParamsToGlobal();\r
- convGlo = kTRUE;\r
- }\r
- //\r
- for (int i=0;i<nconstr;i++) {\r
- AliITSAlignMille2Constraint* cstr = GetConstraint(i);\r
- if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) continue;\r
- //\r
- int imd = cstr->GetModuleID();\r
- //\r
- if (imd>=0) {\r
- AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
- UInt_t pattern = 0;\r
- for (int ipar=mod->GetNParTot();ipar--;) {\r
- if (cstr->IsApplied(ipar)) continue;\r
- if (!cstr->IncludesParam(ipar)) continue;\r
- if (!mod->IsFreeDOF(ipar)) continue; // parameter is fixed, will not apply constraint\r
- pattern |= 0x1<<ipar;\r
- cstr->SetApplied(ipar);\r
- }\r
- if (pattern) PostConstrainModuleSubUnits(cstr->GetType(),cstr->GetModuleID(),cstr->GetValue(),pattern);\r
- //\r
- }\r
- else if (PseudoParentsAllowed()) {\r
- UInt_t pattern = (UInt_t)cstr->GetRemainingPattern();\r
- PostConstrainOrphans(cstr->GetType(),cstr->GetValue(),pattern);\r
- cstr->SetApplied(-1);\r
- }\r
- }\r
- // if there was a conversion, rewind it\r
- if (convGlo) ConvertParamsToLocal();\r
- // \r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ConstrainModuleSubUnits(Int_t idm, Double_t val, UInt_t pattern)\r
-{\r
- // require that sum of modifications for the childs of this module is = val, i.e.\r
- // the internal corrections moves the module as a whole by fixed value (0 by default).\r
- // pattern is the bit pattern for the parameters to constrain\r
- //\r
- //\r
- AliITSAlignMille2Module* mod = GetMilleModule(idm);\r
- //\r
- for (int ip=0;ip<kNParCh;ip++) {\r
- if ( !((pattern>>ip)&0x1) /*|| !parent->IsFreeDOF(ip)*/) continue;\r
- ResetLocalEquation();\r
- int nadd = 0;\r
- for (int ich=mod->GetNChildren();ich--;) {\r
- int idpar = ((AliITSAlignMille2Module*)mod->GetChild(ich))->GetParOffset(ip);\r
- if (idpar<0) continue;\r
- fGlobalDerivatives[idpar] = 1.0;\r
- nadd++;\r
- }\r
- //\r
- if (nadd>0) {\r
- AddConstraint(fGlobalDerivatives,val);\r
- AliInfo(Form("Constrained param %d for %d submodules of module #%d: %s",ip,nadd,idm,mod->GetName()));\r
- }\r
- }\r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ConstrainOrphans(Double_t val, UInt_t pattern)\r
-{\r
- // require that median of the modifications for the supermodules which have no parents is = val, i.e.\r
- // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.\r
- // pattern is the bit pattern for the parameters to constrain\r
- //\r
- for (int ip=0;ip<kNParCh;ip++) {\r
- //\r
- if ( !((pattern>>ip)&0x1) ) continue;\r
- ResetLocalEquation();\r
- int nadd = 0;\r
- for (int imd=fNModules;imd--;) {\r
- AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
- if (mod->GetParent()) continue; // this is not an orphan\r
- int idpar = mod->GetParOffset(ip);\r
- if (idpar<0) continue;\r
- fGlobalDerivatives[idpar] = 1.0;\r
- nadd++;\r
- }\r
- if (nadd>0) {\r
- AddConstraint(fGlobalDerivatives,val);\r
- AliInfo(Form("Constrained param %d for %d orphan modules",ip,nadd));\r
- }\r
- }\r
- //\r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::PostConstrainModuleSubUnits(Int_t type,Int_t idm, Double_t val, UInt_t pattern)\r
-{\r
- // require that median or mean of the modifications for the childs of this module is = val, i.e.\r
- // the internal corrections moves the module as a whole by fixed value (0 by default) \r
- // module the outliers.\r
- // pattern is the bit pattern for the parameters to constrain\r
- // The difference between the mean and the median will be transfered to the parent\r
- //\r
- AliITSAlignMille2Module* parent = GetMilleModule(idm);\r
- int nc = parent->GetNChildren();\r
- //\r
- double *tmpArr = new double[nc]; \r
- //\r
- for (int ip=0;ip<kNParCh;ip++) {\r
- int npc = 0;\r
- if ( !((pattern>>ip)&0x1) || !parent->IsFreeDOF(ip)) continue;\r
- // compute the mean and median of the deltas\r
- int nfree = 0;\r
- for (int ich=nc;ich--;) {\r
- AliITSAlignMille2Module* child = parent->GetChild(ich);\r
- // if (!child->IsFreeDOF(ip)) continue; \r
- tmpArr[nfree++] = child->GetParVal(ip);\r
- }\r
- double median=0,mean=0;\r
- for (int ic0=0;ic0<nfree;ic0++) {// order the deltas \r
- mean += tmpArr[ic0];\r
- for (int ic1=ic0+1;ic1<nfree;ic1++) \r
- if (tmpArr[ic0]>tmpArr[ic1]) {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;}\r
- }\r
- //\r
- int kmed = nfree/2;\r
- median = (tmpArr[kmed]+tmpArr[nfree-kmed-1])/2.;\r
- if (nfree>0) mean /= nfree;\r
- //\r
- double shift = val - (type==AliITSAlignMille2Constraint::kTypeMean ? mean : median);\r
- //\r
- for (int ich=nc;ich--;) {\r
- AliITSAlignMille2Module* child = parent->GetChild(ich);\r
- // if (!child->IsFreeDOF(ip)) continue; \r
- child->SetParVal(ip, child->GetParVal(ip) + shift);\r
- npc++;\r
- }\r
- //\r
- parent->SetParVal(ip, parent->GetParVal(ip) - shift);\r
- AliInfo(Form("%s constraint: added %f shift to param[%d] of %d children of module %d: %s",\r
- type==AliITSAlignMille2Constraint::kTypeMean ? "MEAN" : "MEDIAN",shift,\r
- ip,npc,idm,parent->GetName()));\r
- }\r
- delete[] tmpArr; \r
- //\r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::PostConstrainOrphans(Int_t type,Double_t val, UInt_t pattern)\r
-{\r
- // require that median or mean of modifications for the supermodules which have no parents is = val, i.e.\r
- // the corrections moves the whole setup by fixed value (0 by default).\r
- // pattern is the bit pattern for the parameters to constrain\r
- //\r
- int nc = fNModules;\r
- //\r
- int norph = 0;\r
- for (int ich=nc;ich--;) if (!GetMilleModule(ich)->GetParent()) norph ++;\r
- if (!norph) return;\r
- double *tmpArr = new double[norph]; \r
- //\r
- for (int ip=0;ip<kNParCh;ip++) {\r
- int npc = 0;\r
- if ( !((pattern>>ip)&0x1)) continue;\r
- // compute the mean and median of the deltas\r
- int nfree = 0;\r
- for (int ich=nc;ich--;) {\r
- AliITSAlignMille2Module* child = GetMilleModule(ich);\r
- // if (child->GetParent() || !child->IsFreeDOF(ip)) continue; \r
- if (child->GetParent()) continue; \r
- tmpArr[nfree++] = child->GetParVal(ip);\r
- }\r
- double median=0,mean=0;\r
- for (int ic0=0;ic0<nfree;ic0++) {// order the deltas \r
- mean += tmpArr[ic0];\r
- for (int ic1=ic0+1;ic1<nfree;ic1++) \r
- if (tmpArr[ic0]>tmpArr[ic1]) {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;}\r
- }\r
- //\r
- int kmed = nfree/2;\r
- median = (tmpArr[kmed]+tmpArr[nfree-kmed-1])/2.;\r
- if (nfree>0) mean /= nfree;\r
- //\r
- double shift = val - (type==AliITSAlignMille2Constraint::kTypeMean ? mean : median);\r
- //\r
- for (int ich=nc;ich--;) {\r
- AliITSAlignMille2Module* child = GetMilleModule(ich);\r
- // if (child->GetParent() || !child->IsFreeDOF(ip)) continue; \r
- if (child->GetParent()) continue; \r
- child->SetParVal(ip, child->GetParVal(ip) + shift);\r
- npc++;\r
- }\r
- //\r
- AliInfo(Form("%s constraint: added %f shift to param[%d] of %d orphan modules",\r
- type==AliITSAlignMille2Constraint::kTypeMean ? "MEAN" : "MEDIAN",shift,\r
- ip,npc));\r
- }\r
- delete[] tmpArr; \r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Bool_t AliITSAlignMille2::IsParModConstrained(const AliITSAlignMille2Module* mod,Int_t par, Bool_t &meanmed, Bool_t &gaussian) const\r
-{\r
- // check if par of the module participates in some constraint, and set the flag for their types\r
- meanmed = gaussian = kFALSE;\r
- //\r
- if ( mod->IsParConstrained(par) ) gaussian = kTRUE; // direct constraint on this param\r
- //\r
- for (int icstr=GetNConstraints();icstr--;) {\r
- AliITSAlignMille2Constraint* cstr = GetConstraint(icstr);\r
- //\r
- if (!cstr->IncludesModPar(mod,par)) continue;\r
- if (cstr->GetType()==AliITSAlignMille2ConstrArray::kTypeGaussian) gaussian = kTRUE;\r
- else meanmed = kTRUE;\r
- //\r
- if (meanmed && gaussian) break; // no sense to check further\r
- }\r
- //\r
- return meanmed||gaussian;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Bool_t AliITSAlignMille2::IsParModFamilyVaried(const AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const\r
-{\r
- // check if parameter par is varied for this module or its children up to the level depth\r
- if (depth<0) return kFALSE;\r
- if (mod->GetParOffset(par)>=0) return kTRUE;\r
- for (int icld=mod->GetNChildren();icld--;) {\r
- AliITSAlignMille2Module* child = mod->GetChild(icld);\r
- if (IsParModFamilyVaried(child, par, depth-1)) return kTRUE;\r
- }\r
- return kFALSE;\r
- //\r
-}\r
-\r
-/*\r
-//________________________________________________________________________________________________________\r
-Bool_t AliITSAlignMille2::IsParFamilyFree(AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const\r
-{\r
- // check if parameter par is varied and is not subjected to gaussian constraint for the children up to the level depth\r
- if (depth<0) return kTRUE;\r
- for (int icld=mod->GetNChildren();icld--;) {\r
- AliITSAlignMille2Module* child = mod->GetChild(icld);\r
- //if (child->GetParOffset(par)<0) continue; // fixed\r
- Bool_t cstMM=kFALSE,cstGS=kFALSE;\r
- // does this child have gaussian constraint ?\r
- if (!IsParModConstrained(child,par,cstMM,cstGS) || !cstGS ) return kTRUE;\r
- // check its children\r
- if (!IsParFamilyFree(child,par,depth-1)) return kTRUE;\r
- }\r
- return kFALSE;\r
- //\r
-}\r
-*/\r
-\r
-//________________________________________________________________________________________________________\r
-Bool_t AliITSAlignMille2::IsParFamilyFree(const AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const\r
-{\r
- // check if parameter par is varied and is not subjected to gaussian constraint for the children up to the level depth\r
- if (depth<0) return kFALSE;\r
- for (int icld=mod->GetNChildren();icld--;) {\r
- AliITSAlignMille2Module* child = mod->GetChild(icld);\r
- //if (child->GetParOffset(par)<0) continue; // fixed\r
- Bool_t cstMM=kFALSE,cstGS=kFALSE;\r
- // does this child have gaussian constraint ?\r
- if (!IsParModConstrained(child,par,cstMM,cstGS) || !cstGS ) return kTRUE;\r
- // check its children\r
- if (IsParFamilyFree(child,par,depth-1)) return kTRUE;\r
- }\r
- return kFALSE;\r
- //\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Double_t AliITSAlignMille2::GetTDriftSDD() const \r
-{\r
- // obtain drift time corrected for t0\r
- double t = fCluster.GetDriftTime();\r
- return t - fDriftTime0[ fCluster.GetUniqueID() ];\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Double_t AliITSAlignMille2::GetVDriftSDD() const \r
-{\r
- // obtain corrected drift speed\r
- return fDriftSpeed[ fCluster.GetUniqueID() ];\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-Bool_t AliITSAlignMille2::FixedOrphans() const\r
-{\r
- // are there fixed modules with no parent (normally in such a case \r
- // the constraints on the orphans should not be applied\r
- if (!IsConfigured()) {\r
- AliInfo("Still not configured");\r
- return kFALSE;\r
- }\r
- for (int i=0;i<fNModules;i++) {\r
- AliITSAlignMille2Module* md = GetMilleModule(i);\r
- if (md->GetParent()==0 && md->GetNParFree()==0) return kTRUE;\r
- }\r
- return kFALSE;\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ConvertParamsToGlobal()\r
-{\r
- // convert params in local frame to global one\r
- double pars[AliITSAlignMille2Module::kMaxParGeom];\r
- for (int imd=fNModules;imd--;) {\r
- AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
- if (mod->GeomParamsGlobal()) continue;\r
- mod->GetGeomParamsGlo(pars);\r
- mod->SetParVals(pars,AliITSAlignMille2Module::kMaxParGeom);\r
- mod->SetGeomParamsGlobal(kTRUE);\r
- }\r
-}\r
-\r
-//________________________________________________________________________________________________________\r
-void AliITSAlignMille2::ConvertParamsToLocal()\r
-{\r
- // convert params in global frame to local one\r
- double pars[AliITSAlignMille2Module::kMaxParGeom];\r
- for (int imd=fNModules;imd--;) {\r
- AliITSAlignMille2Module* mod = GetMilleModule(imd);\r
- if (!mod->GeomParamsGlobal()) continue;\r
- mod->GetGeomParamsLoc(pars);\r
- mod->SetParVals(pars,AliITSAlignMille2Module::kMaxParGeom);\r
- mod->SetGeomParamsGlobal(kFALSE);\r
- }\r
-}\r
-\r
+/**************************************************************************
+ * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. *
+ * *
+ * Author: The ALICE Off-line Project. *
+ * Contributors are mentioned in the code where appropriate. *
+ * *
+ * Permission to use, copy, modify and distribute this software and its *
+ * documentation strictly for non-commercial purposes is hereby granted *
+ * without fee, provided that the above copyright notice appears in all *
+ * copies and that both the copyright notice and this permission notice *
+ * appear in the supporting documentation. The authors make no claims *
+ * about the suitability of this software for any purpose. It is *
+ * provided "as is" without express or implied warranty. *
+ **************************************************************************/
+
+/* $Id$ */
+
+//-----------------------------------------------------------------------------
+//
+// Interface to AliMillePede2 alignment class for the ALICE ITS detector
+//
+// ITS specific alignment class which interface to AliMillepede.
+// For each track ProcessTrack calculates the local and global derivatives
+// at each hit and fill the corresponding local equations. Provide methods for
+// fixing or constraining detection elements for best results.
+//
+// author M. Lunardon (thanks to J. Castillo), ruben.shahoyan@cern.ch
+//-----------------------------------------------------------------------------
+
+#include <TFile.h>
+#include <TClonesArray.h>
+#include <TMath.h>
+#include <TVirtualFitter.h>
+#include <TGeoManager.h>
+#include <TSystem.h>
+#include <TRandom.h>
+#include <TCollection.h>
+#include <TGeoPhysicalNode.h>
+#include "AliITSAlignMille2.h"
+#include "AliITSgeomTGeo.h"
+#include "AliGeomManager.h"
+#include "AliMillePede2.h"
+#include "AliTrackPointArray.h"
+#include "AliAlignObjParams.h"
+#include "AliLog.h"
+#include "AliTrackFitterRieman.h"
+#include "AliITSAlignMille2Constraint.h"
+#include "AliITSAlignMille2ConstrArray.h"
+#include "AliITSresponseSDD.h"
+#include "AliITSTPArrayFit.h"
+#include "AliCDBManager.h"
+#include "AliCDBStorage.h"
+#include "AliCDBEntry.h"
+
+
+ClassImp(AliITSAlignMille2)
+
+const Char_t* AliITSAlignMille2::fgkRecKeys[] = {
+ "OCDB_PATH",
+ "GEOMETRY_FILE",
+ "SUPERMODULE_FILE",
+ "CONSTRAINTS_REFERENCE_FILE",
+ "PREALIGNMENT_FILE",
+ "PRECALIBSDD_FILE",
+ "INITCALBSDD_FILE",
+ "INITDELTA_FILE",
+ "SET_GLOBAL_DELTAS",
+ "CONSTRAINT_LOCAL",
+ "MODULE_VOLUID",
+ "MODULE_INDEX",
+ "SET_PSEUDO_PARENTS",
+ "SET_TRACK_FIT_METHOD",
+ "SET_MINPNT_TRA",
+ "SET_NSTDDEV",
+ "SET_RESCUT_INIT",
+ "SET_RESCUT_OTHER",
+ "SET_LOCALSIGMAFACTOR",
+ "SET_STARTFAC",
+ "SET_B_FIELD",
+ "SET_SPARSE_MATRIX",
+ "REQUIRE_POINT",
+ "CONSTRAINT_ORPHANS",
+ "CONSTRAINT_SUBUNITS",
+ "APPLY_CONSTRAINT",
+ "SET_EXTRA_CLUSTERS_MODE",
+ "SET_USE_TPAFITTER",
+ "SET_USE_LOCAL_YERROR",
+ "SET_MIN_POINTS_PER_MODULE"
+
+};
+
+const Char_t AliITSAlignMille2::fgkXYZ[] = "XYZ";
+
+//========================================================================================================
+
+AliITSAlignMille2* AliITSAlignMille2::fgInstance = 0;
+Int_t AliITSAlignMille2::fgInstanceID = 0;
+
+//________________________________________________________________________________________________________
+AliITSAlignMille2::AliITSAlignMille2(const Char_t *configFilename,TList *userInfo )
+: TObject(),
+ fMillepede(0),
+ fStartFac(16.),
+ fResCutInitial(100.),
+ fResCut(100.),
+ fNGlobal(0),
+ fNLocal(4),
+ fNStdDev(3),
+ fIsMilleInit(kFALSE),
+ fAllowPseudoParents(kFALSE),
+ //
+ fTPAFitter(0),
+ fCurrentModule(0),
+ fTrack(0),
+ fTrackBuff(0),
+ fCluster(),
+ fCurrentSensID(-1),
+ fClusLoc(12*3),
+ fClusGlo(12*3),
+ fClusSigLoc(12*3),
+ fGlobalDerivatives(0),
+ fMeasLoc(0),
+ fMeasGlo(0),
+ fSigmaLoc(0),
+ fConstrPT(-1),
+ fConstrPTErr(-1),
+ fConstrCharge(0),
+ //
+ fMinNPtsPerTrack(3),
+ fInitTrackParamsMeth(1),
+ fTotBadLocEqPoints(0),
+ fRieman(0),
+ //
+ fConstraints(0),
+ fCacheMatrixOrig(kMaxITSSensID+1),
+ fCacheMatrixCurr(kMaxITSSensID+1),
+ //
+ fUseGlobalDelta(kFALSE),
+ fRequirePoints(kFALSE),
+ fTempExcludedModule(-1),
+ //
+ fDefCDBpath("local://$ALICE_ROOT/OCDB"),
+ fInitDeltaPath(""),
+ fInitSDDRespPath(""),
+ fPreCalSDDRespPath(""),
+ fGeometryPath("geometry.root"),
+ fPreDeltaPath(""),
+ fConstrRefPath(""),
+ fGeoManager(0),
+ fIsConfigured(kFALSE),
+ fPreAlignQF(0),
+//
+ fCorrectSDD(0),
+ fInitialRecSDD(0),
+ fPrealignment(0),
+ fConstrRef(0),
+ fMilleModule(2),
+ fSuperModule(2),
+ fNModules(0),
+ fNSuperModules(0),
+ fUsePreAlignment(kFALSE),
+ fUseLocalYErr(kFALSE),
+ fBOn(kFALSE),
+ fBField(0.0),
+ fMinPntPerSens(0),
+ fBug(0),
+ fMilleVersion(2),
+ fExtraClustersMode(0)
+{
+ /// main constructor that takes input from configuration file
+ for (int i=3;i--;) fSigmaFactor[i] = 1.0;
+ //
+ // new RS
+ for (Int_t i=0; i<6; i++) {
+ fNReqLayUp[i]=0;
+ fNReqLayDown[i]=0;
+ fNReqLay[i]=0;
+ }
+ for (Int_t i=0; i<3; i++) {
+ fNReqDetUp[i]=0;
+ fNReqDetDown[i]=0;
+ fNReqDet[i]=0;
+ }
+ //
+ if (ProcessUserInfo(userInfo)) exit(1);
+ //
+ Int_t lc=LoadConfig(configFilename);
+ if (lc) {
+ AliError(Form("Error %d loading configuration from %s",lc,configFilename));
+ exit(1);
+ }
+ //
+ fMillepede = new AliMillePede2();
+ fgInstance = this;
+ fgInstanceID++;
+ //
+}
+
+//________________________________________________________________________________________________________
+AliITSAlignMille2::~AliITSAlignMille2()
+{
+ /// Destructor
+ delete fMillepede;
+ delete[] fGlobalDerivatives;
+ delete fRieman;
+ delete fPrealignment;
+ delete fConstrRef;
+ delete fCorrectSDD;
+ delete fInitialRecSDD;
+ delete fTPAFitter;
+ fCacheMatrixOrig.Delete();
+ fCacheMatrixCurr.Delete();
+ fTrackBuff.Delete();
+ fConstraints.Delete();
+ fMilleModule.Delete();
+ fSuperModule.Delete();
+ if (--fgInstanceID==0) fgInstance = 0;
+}
+
+///////////////////////////////////////////////////////////////////////
+
+//________________________________________________________________________________________________________
+TObjArray* AliITSAlignMille2::GetConfigRecord(FILE* stream, TString& recTitle, TString& recOpt, Bool_t rew)
+{
+ // read new record from config file
+ TString record;
+ static TObjArray* recElems = 0;
+ if (recElems) {delete recElems; recElems = 0;}
+ //
+ TString keyws = recTitle;
+ if (!keyws.IsNull()) {
+ keyws.ToUpper();
+ // keyws += " ";
+ }
+ while (record.Gets(stream)) {
+ int cmt=record.Index("#");
+ if (cmt>=0) record.Remove(cmt); // skip comment
+ record.ReplaceAll("\t"," ");
+ record.ReplaceAll("\r"," ");
+ record.Remove(TString::kBoth,' ');
+ if (record.IsNull()) continue; // nothing to decode
+ if (!keyws.IsNull() && !record.BeginsWith(keyws.Data())) continue; // specific record was requested
+ //
+ recElems = record.Tokenize(" ");
+ recTitle = recElems->At(0)->GetName();
+ recTitle.ToUpper();
+ recOpt = recElems->GetLast()>0 ? recElems->At(1)->GetName() : "";
+ break;
+ }
+ if (rew || !recElems) rewind(stream);
+ return recElems;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::CheckConfigRecords(FILE* stream)
+{
+ TString record,recTitle;
+ int lineCnt = 0;
+ rewind(stream);
+ while (record.Gets(stream)) {
+ int cmt=record.Index("#");
+ lineCnt++;
+ if (cmt>=0) record.Remove(cmt); // skip comment
+ record.ReplaceAll("\t"," ");
+ record.ReplaceAll("\r"," ");
+ record.Remove(TString::kBoth,' ');
+ if (record.IsNull()) continue; // nothing to decode
+ // extract keyword
+ int spc = record.Index(" ");
+ if (spc>0) recTitle = record(0,spc);
+ else recTitle = record;
+ recTitle.ToUpper();
+ Bool_t strOK = kFALSE;
+ for (int ik=kNKeyWords;ik--;) if (recTitle == fgkRecKeys[ik]) {strOK = kTRUE; break;}
+ if (strOK) continue;
+ //
+ AliError(Form("Unknown keyword %s at line %d",
+ recTitle.Data(),lineCnt));
+ return -1;
+ //
+ }
+ //
+ rewind(stream);
+ return 0;
+}
+
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::LoadConfig(const Char_t *cfile)
+{
+ // return 0 if success
+ // 1 if error in module index or voluid
+ //
+ FILE *pfc=fopen(cfile,"r");
+ if (!pfc) return -1;
+ //
+ TString record,recTitle,recOpt,recExt;
+ Int_t nrecElems,irec;
+ TObjArray *recArr=0;
+ //
+ fNModules = 0;
+ Bool_t stopped = kFALSE;
+ //
+ if (CheckConfigRecords(pfc)<0) return -1;
+ //
+ while(1) {
+ //
+ // ============= 1: we read some important records in predefined order ================
+ //
+ recTitle = fgkRecKeys[kOCDBPath];
+ if ( GetConfigRecord(pfc,recTitle,recOpt,1) && !(fDefCDBpath=recOpt).IsNull() ) {
+ AliInfo(Form("Configuration sets OCDB Def.Storage to %s",fDefCDBpath.Data()));
+ AliCDBManager::Instance()->SetDefaultStorage( fDefCDBpath.Data() );
+ }
+ //
+ //
+ recTitle = fgkRecKeys[kGeomFile];
+ if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) fGeometryPath = recOpt;
+ if ( InitGeometry() ) { AliError("Failed to find/load Geometry"); stopped = kTRUE; break;}
+ //
+ //
+ recTitle = fgkRecKeys[kSuperModileFile];
+ if ( !GetConfigRecord(pfc,recTitle,recOpt,1) ||
+ recOpt.IsNull() ||
+ gSystem->AccessPathName(recOpt.Data()) ||
+ LoadSuperModuleFile(recOpt.Data()))
+ { AliError("Failed to find/load SuperModules"); stopped = kTRUE; break;}
+ //
+ //
+ recTitle = fgkRecKeys[kConstrRefFile]; // LOCAL_CONSTRAINTS are defined wrt these deltas
+ if ( (recArr = GetConfigRecord(pfc,recTitle,recOpt,1)) ) {
+ if (recOpt.IsNull() || recOpt=="IDEAL") SetConstraintWrtRef( "IDEAL" );
+ else {
+ for (int i=2;i<=recArr->GetLast();i++) {recOpt += " "; recOpt += recArr->At(i)->GetName();} // in case of OCDB string
+ if ( SetConstraintWrtRef(recOpt.Data()) )
+ { AliError("Failed to load reference deltas for local constraints"); stopped = kTRUE; break;}
+ }
+ }
+ //
+ //
+ recTitle = fgkRecKeys[kPreDeltaFile];
+ if ( (recArr = GetConfigRecord(pfc,recTitle,recOpt,1)) && !recOpt.IsNull()) {
+ for (int i=2;i<=recArr->GetLast();i++) {recOpt += " "; recOpt += recArr->At(i)->GetName();} // in case of OCDB string
+ fPreDeltaPath = recOpt;
+ AliInfo(Form("Configuration sets PreAlignment Deltas to %s",fPreDeltaPath.Data()));
+ }
+ if (LoadDeltas(fPreDeltaPath,fPrealignment)) {stopped = kTRUE; break;}
+ if (fPrealignment && ApplyToGeometry()) {stopped = kTRUE; break;}
+ //
+ //
+ recTitle = fgkRecKeys[kInitDeltaFile];
+ if ( (recArr = GetConfigRecord(pfc,recTitle,recOpt,1)) && !recOpt.IsNull()) {
+ for (int i=2;i<=recArr->GetLast();i++) {recOpt += " "; recOpt += recArr->At(i)->GetName();} // in case of OCDB string
+ fInitDeltaPath = recOpt;
+ AliInfo(Form("Configuration sets Production Deltas to %s",fInitDeltaPath.Data()));
+ }
+ //
+ //
+ recTitle = fgkRecKeys[kPreCalSDDFile];
+ if ( (recArr = GetConfigRecord(pfc,recTitle,recOpt,1)) && !recOpt.IsNull() ) {
+ for (int i=2;i<=recArr->GetLast();i++) {recOpt += " "; recOpt += recArr->At(i)->GetName();} // in case of OCDB string
+ fPreCalSDDRespPath = recOpt;
+ AliInfo(Form("Configuration sets PreCalibration SDD Response to %s",fPreCalSDDRespPath.Data()));
+ }
+ if (LoadSDDResponse(fPreCalSDDRespPath, fCorrectSDD) ) {stopped = kTRUE; break;}
+ //
+ recTitle = fgkRecKeys[ kInitCalSDDFile ];
+ if ( (recArr = GetConfigRecord(pfc,recTitle,recOpt,1)) && !recOpt.IsNull()) {
+ for (int i=2;i<=recArr->GetLast();i++) {recOpt += " "; recOpt += recArr->At(i)->GetName();} // in case of OCDB string
+ fInitSDDRespPath = recOpt;
+ AliInfo(Form("Configuration sets Production SDD Response to %s",fInitSDDRespPath.Data()));
+ }
+ if (LoadSDDResponse(fInitSDDRespPath, fInitialRecSDD) ) {stopped = kTRUE; break;}
+ //
+ //
+ recTitle = fgkRecKeys[ kGlobalDeltas ];
+ if ( GetConfigRecord(pfc,recTitle,recOpt,1) ) SetUseGlobalDelta(kTRUE);
+ //
+ // =========== 2: see if there are local gaussian constraints defined =====================
+ // Note that they should be loaded before the modules declaration
+ //
+ recTitle = fgkRecKeys[ kConstrLocal ];
+ while( (recArr=GetConfigRecord(pfc,recTitle,recOpt,0)) ) {
+ nrecElems = recArr->GetLast()+1;
+ if (recOpt.IsFloat()) {stopped = kTRUE; break;} // wrong name
+ if (GetConstraint(recOpt.Data())) {
+ AliError(Form("Existing constraint %s repeated",recOpt.Data()));
+ stopped = kTRUE; break;
+ }
+ recExt = recArr->At(2)->GetName();
+ if (!recExt.IsFloat()) {stopped = kTRUE; break;}
+ double val = recExt.Atof();
+ recExt = recArr->At(3)->GetName();
+ if (!recExt.IsFloat()) {stopped = kTRUE; break;}
+ double err = recExt.Atof();
+ int nwgh = nrecElems - 4;
+ double *wgh = new double[nwgh];
+ for (nwgh=0,irec=4;irec<nrecElems;irec++) {
+ recExt = recArr->At(irec)->GetName();
+ if (!recExt.IsFloat()) {stopped = kTRUE; break;}
+ wgh[nwgh++] = recExt.Atof();
+ }
+ if (stopped) {delete[] wgh; break;}
+ //
+ ConstrainLocal(recOpt.Data(),wgh,nwgh,val,err);
+ delete[] wgh;
+ //
+ } // end while for loop over local constraints
+ if (stopped) break;
+ //
+ // =========== 3: now read modules to align ===================================
+ //
+ rewind(pfc);
+ while( (recArr=GetConfigRecord(pfc,recTitle="",recOpt,0)) ) {
+ if (!(recTitle==fgkRecKeys[ kModVolID ] || recTitle==fgkRecKeys[ kModIndex ])) continue;
+ // Expected format: MODULE id tolX tolY tolZ tolPsi tolTh tolPhi [[sigX sigY sigZ] extra params]
+ // where tol* is the tolerance (sigma) for given DOF. 0 means fixed
+ // sig* is the scaling parameters for the errors of the clusters of this module
+ // extra params are defined for specific modules, e.g. t0 and vdrift corrections of SDD
+ //
+ nrecElems = recArr->GetLast()+1;
+ if (nrecElems<2 || !recOpt.IsDigit()) {stopped = kTRUE; break;}
+ int idx = recOpt.Atoi();
+ UShort_t voluid = (idx<=kMaxITSSensID) ? GetModuleVolumeID(idx) : idx;
+ AliITSAlignMille2Module* mod = 0;
+ //
+ if (voluid>=kMinITSSupeModuleID) { // custom supermodule
+ for (int j=0; j<fNSuperModules; j++) {
+ if (voluid==GetSuperModule(j)->GetVolumeID()) {
+ mod = new AliITSAlignMille2Module(*GetSuperModule(j));
+ // the matrix might be updated in case some prealignment was applied, check
+ TGeoHMatrix* mup = AliGeomManager::GetMatrix(mod->GetName());
+ if (mup) *(mod->GetMatrix()) = *mup;
+ fMilleModule.AddAtAndExpand(mod,fNModules);
+ break;
+ }
+ }
+ }
+ else if (idx<=kMaxITSSensVID) {
+ mod = new AliITSAlignMille2Module(voluid);
+ fMilleModule.AddAtAndExpand(mod,fNModules);
+ }
+ if (!mod) {stopped = kTRUE; break;} // bad volid
+ //
+ // geometry variation settings
+ for (int i=0;i<AliITSAlignMille2Module::kMaxParGeom;i++) {
+ irec = i+2;
+ if (irec >= nrecElems) break;
+ recExt = recArr->At(irec)->GetName();
+ if (!recExt.IsFloat()) {stopped = kTRUE; break;}
+ mod->SetFreeDOF(i, recExt.Atof() );
+ }
+ if (stopped) break;
+ //
+ // scaling factors for cluster errors
+ // first set default ones
+ for (int i=0;i<3;i++) mod->SetSigmaFactor(i, fSigmaFactor[i]);
+ for (int i=0;i<3;i++) {
+ irec = i+8;
+ if (irec >= nrecElems) break;
+ recExt = recArr->At(irec)->GetName();
+ if (!recExt.IsFloat()) {stopped = kTRUE; break;}
+ mod->SetSigmaFactor(i, recExt.Atof() );
+ }
+ if (stopped) break;
+ //
+ mod->SetGeomParamsGlobal(fUseGlobalDelta);
+ // now comes special detectors treatment
+ if (mod->IsSDD()) {
+ double vl = 0;
+ if (nrecElems>11) {
+ recExt = recArr->At(11)->GetName();
+ if (recExt.IsFloat()) vl = recExt.Atof();
+ else {stopped = kTRUE; break;}
+ irec = 11;
+ }
+ mod->SetFreeDOF(AliITSAlignMille2Module::kDOFT0,vl);
+ //
+ vl = 0;
+ if (nrecElems>12) {
+ recExt = recArr->At(12)->GetName();
+ if (recExt.IsFloat()) vl = recExt.Atof();
+ else {stopped = kTRUE; break;}
+ irec = 12;
+ }
+ mod->SetFreeDOF(AliITSAlignMille2Module::kDOFDV,vl);
+ }
+ //
+ mod->SetUniqueID(fNModules);
+ mod->EvaluateDOF();
+ fNModules++;
+ //
+ // now check if there are local constraints on this module
+ for (++irec;irec<nrecElems;irec++) {
+ recExt = recArr->At(irec)->GetName();
+ if (recExt.IsFloat()) {stopped=kTRUE;break;}
+ AliITSAlignMille2ConstrArray* cstr = (AliITSAlignMille2ConstrArray*)GetConstraint(recExt.Data());
+ if (!cstr) {
+ AliInfo(Form("No Local constraint %s was declared",recExt.Data()));
+ stopped=kTRUE;
+ break;
+ }
+ cstr->AddModule(mod);
+ }
+ if (stopped) break;
+ } // end while for loop over modules
+ if (stopped) break;
+ //
+ if (fNModules==0) {AliError("Failed to find any MODULE"); stopped = kTRUE; break;}
+ BuildHierarchy(); // preprocess loaded modules
+ //
+ // =========== 4: the rest may come in arbitrary order =======================================
+ rewind(pfc);
+ while ( (recArr=GetConfigRecord(pfc,recTitle="",recOpt,0))!=0 ) {
+ //
+ nrecElems = recArr->GetLast()+1;
+ //
+ // some simple flags -----------------------------------------------------------------------
+ //
+ if (recTitle == fgkRecKeys[ kPseudoParents ]) SetAllowPseudoParents(kTRUE);
+ //
+ // some optional parameters ----------------------------------------------------------------
+ else if (recTitle == fgkRecKeys[ kTrackFitMethod ]) {
+ if (recOpt.IsNull() || !recOpt.IsDigit() ) {stopped = kTRUE; break;}
+ SetInitTrackParamsMeth(recOpt.Atoi());
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kMinPntTrack ]) {
+ if (recOpt.IsNull() || !recOpt.IsDigit() ) {stopped = kTRUE; break;}
+ fMinNPtsPerTrack = recOpt.Atoi();
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kNStDev ]) {
+ if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}
+ fNStdDev = (Int_t)recOpt.Atof();
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kResCutInit ]) {
+ if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}
+ fResCutInitial = recOpt.Atof();
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kResCutOther ]) {
+ if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}
+ fResCut = recOpt.Atof();
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kLocalSigFactor ]) { //-------------------------
+ for (irec=0;irec<3;irec++) if (nrecElems>irec+1) {
+ fSigmaFactor[irec] = ((TObjString*)recArr->At(irec+1))->GetString().Atof();
+ if (fSigmaFactor[irec]<=0.) stopped = kTRUE;
+ }
+ if (stopped) break;
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kStartFactor ]) { //-------------------------
+ if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}
+ fStartFac = recOpt.Atof();
+ }
+ //
+ // pepo2708909
+ else if (recTitle == fgkRecKeys[ kExtraClustersMode ]) { //-------------------------
+ if (recOpt.IsNull() || !recOpt.IsDigit() ) {stopped = kTRUE; break;}
+ fExtraClustersMode = recOpt.Atoi();
+ }
+ // endpepo270809
+ //
+ else if (recTitle == fgkRecKeys[ kBField ]) { //-------------------------
+ if (recOpt.IsNull() || !recOpt.IsFloat() ) {stopped = kTRUE; break;}
+ SetBField( recOpt.Atof() );
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kSparseMatrix ]) { // matrix solver type
+ //
+ AliMillePede2::SetGlobalMatSparse(kTRUE);
+ if (recOpt.IsNull()) continue;
+ // solver type and settings
+ if (recOpt == "MINRES") AliMillePede2::SetIterSolverType( AliMinResSolve::kSolMinRes );
+ else if (recOpt == "FGMRES") AliMillePede2::SetIterSolverType( AliMinResSolve::kSolFGMRes );
+ else {stopped = kTRUE; break;}
+ //
+ if (nrecElems>=3) { // preconditioner type
+ recExt = recArr->At(2)->GetName();
+ if (!recExt.IsDigit()) {stopped = kTRUE; break;}
+ AliMillePede2::SetMinResPrecondType( recExt.Atoi() );
+ }
+ //
+ if (nrecElems>=4) { // tolerance
+ recExt = recArr->At(3)->GetName();
+ if (!recExt.IsFloat()) {stopped = kTRUE; break;}
+ AliMillePede2::SetMinResTol( recExt.Atof() );
+ }
+ //
+ if (nrecElems>=5) { // maxIter
+ recExt = recArr->At(4)->GetName();
+ if (!recExt.IsDigit()) {stopped = kTRUE; break;}
+ AliMillePede2::SetMinResMaxIter( recExt.Atoi() );
+ }
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kRequirePoint ]) { //-------------------------
+ // syntax: REQUIRE_POINT where ndet updw nreqpts
+ // where = LAYER or DETECTOR
+ // ndet = detector number: 1-6 for LAYER and 1-3 for DETECTOR (SPD=1, SDD=2, SSD=3)
+ // updw = 1 for Y>0, -1 for Y<0, 0 if not specified
+ // nreqpts = minimum number of points of that type
+ if (nrecElems>=5) {
+ recOpt.ToUpper();
+ int lr = ((TObjString*)recArr->At(2))->GetString().Atoi() - 1;
+ int hb = ((TObjString*)recArr->At(3))->GetString().Atoi();
+ int np = ((TObjString*)recArr->At(4))->GetString().Atoi();
+ fRequirePoints = kTRUE;
+ if (recOpt == "LAYER") {
+ if (lr<0 || lr>5) {stopped = kTRUE; break;}
+ if (hb>0) fNReqLayUp[lr] = np;
+ else if (hb<0) fNReqLayDown[lr] = np;
+ else fNReqLay[lr] = np;
+ }
+ else if (recOpt == "DETECTOR") {
+ if (lr<0 || lr>2) {stopped = kTRUE; break;}
+ if (hb>0) fNReqDetUp[lr] = np;
+ else if (hb<0) fNReqDetDown[lr] = np;
+ else fNReqDet[lr] = np;
+ }
+ else {stopped = kTRUE; break;}
+ }
+ else {stopped = kTRUE; break;}
+ }
+ //
+ // global constraints on the subunits/orphans
+ else if (recTitle == fgkRecKeys[ kConstrOrphans ]) { //------------------------
+ // expect CONSTRAINT_ORPHANS MEAN/MEDIAN Value parID0 ... parID1 ...
+ if (nrecElems<4) {stopped = kTRUE; break;}
+ recExt = recArr->At(2)->GetName();
+ if (!recExt.IsFloat()) {stopped = kTRUE; break;}
+ double val = recExt.Atof();
+ UInt_t pattern = 0;
+ for (irec=3;irec<nrecElems;irec++) { // read params to constraint
+ recExt = recArr->At(irec)->GetName();
+ if (!recExt.IsDigit()) {stopped = kTRUE; break;}
+ pattern |= 0x1 << recExt.Atoi();
+ }
+ if (stopped) break;
+ if (recOpt == "MEAN") ConstrainOrphansMean(val,pattern);
+ else if (recOpt == "MEDIAN") ConstrainOrphansMedian(val,pattern);
+ else {stopped = kTRUE; break;}
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kConstrSubunits ]) { //------------------------
+ // expect ONSTRAINT_SUBUNITS MEAN/MEDIAN Value parID0 ... parID1 ... VolID1 ... VolIDn - VolIDm
+ if (nrecElems<5) {stopped = kTRUE; break;}
+ recExt = recArr->At(2)->GetName();
+ if (!recExt.IsFloat()) {stopped = kTRUE; break;}
+ double val = recExt.Atof();
+ UInt_t pattern = 0;
+ for (irec=3;irec<nrecElems;irec++) { // read params to constraint
+ recExt = recArr->At(irec)->GetName();
+ if (!recExt.IsDigit()) {stopped = kTRUE; break;}
+ int parid = recExt.Atoi();
+ if (parid<kMaxITSSensID) pattern |= 0x1 << recExt.Atoi();
+ else break; // list of params is over
+ }
+ if (stopped) break;
+ //
+ Bool_t meanC;
+ if (recOpt == "MEAN") meanC = kTRUE;
+ else if (recOpt == "MEDIAN") meanC = kFALSE;
+ else {stopped = kTRUE; break;}
+ //
+ int curID = -1;
+ int rangeStart = -1;
+ for (;irec<nrecElems;irec++) { // read modules to apply this constraint
+ recExt = recArr->At(irec)->GetName();
+ if (recExt == "-") {rangeStart = curID; continue;} // range is requested
+ else if (!recExt.IsDigit()) {stopped = kTRUE; break;}
+ else curID = recExt.Atoi();
+ //
+ if (curID<=kMaxITSSensID) curID = GetModuleVolumeID(curID);
+ // this was a range start or single
+ int start;
+ if (rangeStart>=0) {start = rangeStart+1; rangeStart=-1;} // continue the range
+ else start = curID; // create constraint either for single module (or 1st in the range)
+ for (int id=start;id<=curID;id++) {
+ int id0 = IsVIDDefined(id);
+ if (id0<0) {AliDebug(3,Form("Undefined module %d requested in the SubUnits constraint, skipping",id)); continue;}
+ if (meanC) ConstrainModuleSubUnitsMean(id0,val,pattern);
+ else ConstrainModuleSubUnitsMedian(id0,val,pattern);
+ }
+ }
+ if (rangeStart>=0) stopped = kTRUE; // unfinished range
+ if (stopped) break;
+ }
+ //
+ // association of modules with local constraints
+ else if (recTitle == fgkRecKeys[ kApplyConstr ]) { //------------------------
+ // expect APPLY_CONSTRAINT NAME [NAME1...] [VolID1 ... VolIDn - VolIDm]
+ if (nrecElems<3) {stopped = kTRUE; break;}
+ int nmID0=-1,nmID1=-1;
+ for (irec=1;irec<nrecElems;irec++) { // find the range of constraint names
+ recExt = recArr->At(irec)->GetName();
+ if (recExt.IsFloat()) break;
+ // check if such a constraint was declared
+ if (!GetConstraint(recExt.Data())) {
+ AliInfo(Form("No Local constraint %s was declared",recExt.Data()));
+ stopped=kTRUE;
+ break;
+ }
+ if (nmID0<0) nmID0 = irec;
+ nmID1 = irec;
+ }
+ if (stopped) break;
+ //
+ if (irec>=nrecElems) {stopped = kTRUE; break;} // no modules provided
+ //
+ // now read the list of modules to constrain
+ int curID = -1;
+ int rangeStart = -1;
+ for (;irec<nrecElems;irec++) { // read modules to apply this constraint
+ recExt = recArr->At(irec)->GetName();
+ if (recExt == "-") {rangeStart = curID; continue;} // range is requested
+ else if (!recExt.IsDigit()) {stopped = kTRUE; break;}
+ else curID = recExt.Atoi();
+ //
+ if (curID<=kMaxITSSensID) curID = GetModuleVolumeID(curID);
+ //
+ // this was a range start or single
+ int start;
+ if (rangeStart>=0) {start = rangeStart+1; rangeStart=-1;} // continue the range
+ else start = curID; // create constraint either for single module (or 1st in the range)
+ for (int id=start;id<=curID;id++) {
+ AliITSAlignMille2Module *md = GetMilleModuleByVID(id);
+ if (!md) {AliDebug(3,Form("Undefined module %d requested in the Local constraint, skipping",id)); continue;}
+ for (int nmid=nmID0;nmid<=nmID1;nmid++)
+ ((AliITSAlignMille2ConstrArray*)GetConstraint(recArr->At(nmid)->GetName()))->AddModule(md);
+ }
+ }
+ if (rangeStart>=0) stopped = kTRUE; // unfinished range
+ if (stopped) break;
+ }
+ // Do we use new TrackPointArray fitter ?
+ else if (recTitle == fgkRecKeys[ kTPAFitter ]) {
+ // expect SET_TPAFITTER
+ fTPAFitter = new AliITSTPArrayFit(kNLocal);
+ }
+ // Do we use new local Y errors?
+ else if (recTitle == fgkRecKeys[ kUseLocalYErr ]) {
+ // expect SET_TPAFITTER
+ fUseLocalYErr = kTRUE;
+ }
+ //
+ else if (recTitle == fgkRecKeys[ kMinPointsSens ]) { //-------------------------
+ if (recOpt.IsNull() || !recOpt.IsDigit() ) {stopped = kTRUE; break;}
+ SetMinPointsPerSensor( recOpt.Atoi() );
+ }
+ //
+ else continue; // already processed record
+ //
+ } // end of while loop 4 over the various params
+ //
+ break;
+ } // end of while(1) loop
+ //
+ fclose(pfc);
+ if (stopped) {
+ AliError(Form("Failed on record %s %s ...\n",recTitle.Data(),recOpt.Data()));
+ return -1;
+ }
+ //
+ if (CacheMatrices()) return -1;
+ SetUseLocalYErrors(fUseLocalYErr); // YErr used only with TPAFitter
+ fIsConfigured = kTRUE;
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::BuildHierarchy()
+{
+ // build the hieararhy of the modules to align
+ //
+ if (!GetUseGlobalDelta() && PseudoParentsAllowed()) {
+ AliInfo("PseudoParents mode is allowed only when the deltas are global\n"
+ "Since Deltas are local, switching to NoPseudoParents");
+ SetAllowPseudoParents(kFALSE);
+ }
+ // set parent/child relationship for modules to align
+ AliInfo("Setting parent/child relationships\n");
+ //
+ // 1) child -> parent reference
+ for (int ipar=0;ipar<fNModules;ipar++) {
+ AliITSAlignMille2Module* parent = GetMilleModule(ipar);
+ if (parent->IsSensor()) continue; // sensor cannot be a parent
+ //
+ for (int icld=0;icld<fNModules;icld++) {
+ if (icld==ipar) continue;
+ AliITSAlignMille2Module* child = GetMilleModule(icld);
+ if (!child->BelongsTo(parent)) continue;
+ // child cannot have more sensors than the parent
+ if (child->GetNSensitiveVolumes() > parent->GetNSensitiveVolumes()) continue;
+ //
+ AliITSAlignMille2Module* parOld = child->GetParent();
+ // is this parent candidate closer than the old parent ?
+ if (parOld && parOld->GetNSensitiveVolumes()<parent->GetNSensitiveVolumes()) continue; // parOld is closer
+ child->SetParent(parent);
+ }
+ //
+ }
+ //
+ // add parent -> children reference
+ for (int icld=0;icld<fNModules;icld++) {
+ AliITSAlignMille2Module* child = GetMilleModule(icld);
+ AliITSAlignMille2Module* parent = child->GetParent();
+ if (parent) parent->AddChild(child);
+ }
+ //
+ // reorder the modules in such a way that parents come first
+ for (int icld=0;icld<fNModules;icld++) {
+ AliITSAlignMille2Module* child = GetMilleModule(icld);
+ AliITSAlignMille2Module* parent;
+ while ( (parent=child->GetParent()) && (parent->GetUniqueID()>child->GetUniqueID()) ) {
+ // swap
+ fMilleModule[icld] = parent;
+ fMilleModule[parent->GetUniqueID()] = child;
+ child->SetUniqueID(parent->GetUniqueID());
+ parent->SetUniqueID(icld);
+ child = parent;
+ }
+ //
+ }
+ //
+ // Go over the child->parent chain and mark modules with explicitly provided sensors.
+ // If the sensors of the unit are explicitly declared, all undeclared sensors are
+ // suppresed in this unit.
+ for (int icld=fNModules;icld--;) {
+ AliITSAlignMille2Module* child = GetMilleModule(icld);
+ AliITSAlignMille2Module* parent = child->GetParent();
+ if (!parent) continue;
+ //
+ // check if this parent was already processed
+ if (!parent->AreSensorsProvided()) {
+ parent->DelSensitiveVolumes();
+ parent->SetSensorsProvided(kTRUE);
+ }
+ // reattach sensors to parent
+ for (int isc=child->GetNSensitiveVolumes();isc--;) {
+ UShort_t senVID = child->GetSensVolVolumeID(isc);
+ if (!parent->IsIn(senVID)) parent->AddSensitiveVolume(senVID);
+ }
+ }
+ //
+}
+
+// pepo
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::SetCurrentModule(Int_t id)
+{
+ // set the current supermodule
+ // new meaning
+ if (fMilleVersion>=2) {
+ fCurrentModule = GetMilleModule(id);
+ return;
+ }
+ // old meaning
+ if (fMilleVersion<=1) {
+ Int_t index=id;
+ /// set as current the SuperModule that contains the 'index' sens.vol.
+ if (index<0 || index>2197) {
+ AliInfo("index does not correspond to a sensitive volume!");
+ return;
+ }
+ UShort_t voluid=AliITSAlignMille2Module::GetVolumeIDFromIndex(index);
+ Int_t k=IsContained(voluid);
+ if (k>=0){
+ fCurrentSensID = index;
+ fCluster.SetVolumeID(voluid);
+ fCluster.SetXYZ(0,0,0);
+ InitModuleParams();
+ }
+ else
+ AliInfo(Form("module %d not defined\n",index));
+ }
+}
+// endpepo
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::SetRequiredPoint(Char_t* where, Int_t ndet, Int_t updw, Int_t nreqpts)
+{
+ // set minimum number of points in specific detector or layer
+ // where = LAYER or DETECTOR
+ // ndet = detector number: 1-6 for LAYER and 1-3 for DETECTOR (SPD=1, SDD=2, SSD=3)
+ // updw = 1 for Y>0, -1 for Y<0, 0 if not specified
+ // nreqpts = minimum number of points of that type
+ ndet--;
+ if (strstr(where,"LAYER")) {
+ if (ndet<0 || ndet>5) return;
+ if (updw>0) fNReqLayUp[ndet]=nreqpts;
+ else if (updw<0) fNReqLayDown[ndet]=nreqpts;
+ else fNReqLay[ndet]=nreqpts;
+ fRequirePoints=kTRUE;
+ }
+ else if (strstr(where,"DETECTOR")) {
+ if (ndet<0 || ndet>2) return;
+ if (updw>0) fNReqDetUp[ndet]=nreqpts;
+ else if (updw<0) fNReqDetDown[ndet]=nreqpts;
+ else fNReqDet[ndet]=nreqpts;
+ fRequirePoints=kTRUE;
+ }
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::GetModuleIndex(const Char_t *symname)
+{
+ /// index from symname
+ if (!symname) return -1;
+ for (Int_t i=0;i<=kMaxITSSensID; i++) {
+ if (!strcmp(symname,AliITSgeomTGeo::GetSymName(i))) return i;
+ }
+ return -1;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::GetModuleIndex(UShort_t voluid)
+{
+ /// index from volume ID
+ AliGeomManager::ELayerID lay = AliGeomManager::VolUIDToLayer(voluid);
+ if (lay<1|| lay>6) return -1;
+ Int_t idx=Int_t(voluid)-2048*lay;
+ if (idx>=AliGeomManager::LayerSize(lay)) return -1;
+ for (Int_t ilay=1; ilay<lay; ilay++)
+ idx += AliGeomManager::LayerSize(ilay);
+ return idx;
+}
+
+//________________________________________________________________________________________________________
+UShort_t AliITSAlignMille2::GetModuleVolumeID(const Char_t *symname)
+{
+ /// volume ID from symname
+ /// works for sensitive volumes only
+ if (!symname) return 0;
+
+ for (UShort_t voluid=2000; voluid<13300; voluid++) {
+ Int_t modId;
+ AliGeomManager::ELayerID layerId = AliGeomManager::VolUIDToLayer(voluid,modId);
+ if (layerId>0 && layerId<7 && modId>=0 && modId<AliGeomManager::LayerSize(layerId)) {
+ if (!strcmp(symname,AliGeomManager::SymName(layerId,modId))) return voluid;
+ }
+ }
+
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+UShort_t AliITSAlignMille2::GetModuleVolumeID(Int_t index)
+{
+ /// volume ID from index
+ if (index<0) return 0;
+ if (index<2198)
+ return GetModuleVolumeID(AliITSgeomTGeo::GetSymName(index));
+ else {
+ for (int i=0; i<fNSuperModules; i++) {
+ if (GetSuperModule(i)->GetIndex()==index) return GetSuperModule(i)->GetVolumeID();
+ }
+ }
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::InitGeometry()
+{
+ /// initialize geometry
+ AliInfo("Loading initial geometry");
+ if (!fGeometryPath.IsNull() && gSystem->AccessPathName(fGeometryPath.Data()) ) {
+ AliError(Form("Explicitly provided geometry file %s is not accessible",fGeometryPath.Data()));
+ return -1;
+ }
+ //
+ AliGeomManager::LoadGeometry(fGeometryPath.Data());
+ fGeoManager = AliGeomManager::GetGeometry();
+ if (!fGeoManager) {
+ AliInfo("Couldn't initialize geometry");
+ return -1;
+ }
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::SetConstraintWrtRef(const char* reffname)
+{
+ // Load the global deltas from this file. The local gaussian constraints on some modules
+ // will be defined with respect to the deltas from this reference file, converted to local
+ // delta format. Note: conversion to local format requires reloading the geometry!
+ //
+ AliInfo(Form("Loading reference deltas for local constraints from %s",reffname));
+ if (!fGeoManager) return -1;
+ fConstrRefPath = reffname;
+ if (fConstrRefPath == "IDEAL") { // the reference is the ideal geometry, just create dummy reference array
+ fConstrRef = new TClonesArray("AliAlignObjParams",1);
+ return 0;
+ }
+ if (LoadDeltas(fConstrRefPath,fConstrRef)) return -1;
+ //
+ // we need ideal geometry to convert global deltas to local ones
+ if (fUsePreAlignment) {
+ AliError("The call of SetConstraintWrtRef must be done before application of the prealignment");
+ return -1;
+ }
+ //
+ AliInfo("Converting global reference deltas to local ones");
+ Int_t nprea = fConstrRef->GetEntriesFast();
+ for (int ix=0; ix<nprea; ix++) {
+ AliAlignObjParams *preo=(AliAlignObjParams*) fConstrRef->At(ix);
+ if (!preo->ApplyToGeometry()) return -1;
+ }
+ //
+ // now convert the global reference deltas to local ones
+ for (int i=fConstrRef->GetEntriesFast();i--;) {
+ AliAlignObjParams *preo = (AliAlignObjParams*)fConstrRef->At(i);
+ TGeoHMatrix * mupd = AliGeomManager::GetMatrix(preo->GetSymName());
+ if (!mupd) { // this is not alignable entry, need to look in the supermodules
+ for (int im=fNSuperModules;im--;) {
+ AliITSAlignMille2Module* mod = GetSuperModule(im);
+ if ( strcmp(mod->GetName(), preo->GetSymName()) ) continue;
+ mupd = mod->GetMatrix();
+ break;
+ }
+ if (!mupd) {
+ AliError(Form("Failed to find the volume for reference %s",preo->GetSymName()));
+ return -1;
+ }
+ }
+ TGeoHMatrix preMat;
+ preo->GetMatrix(preMat); // Delta_Glob
+ TGeoHMatrix tmpMat = *mupd; // Delta_Glob * Delta_Glob_Par * M
+ preMat.MultiplyLeft( &tmpMat.Inverse() ); // M^-1 * Delta_Glob_Par^-1 = (Delta_Glob_Par * M)^-1
+ tmpMat.MultiplyLeft( &preMat ); // (Delta_Glob_Par * M)^-1 * Delta_Glob * Delta_Glob_Par * M = Delta_loc
+ preo->SetMatrix(tmpMat); // local corrections
+ }
+ //
+ // we need to reload the geometry spoiled by this reference deltas...
+ delete fGeoManager;
+ AliInfo("Reloading initial geometry");
+ return InitGeometry();
+ //
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::Init()
+{
+ // perform global initialization
+ //
+ if (fIsMilleInit) {
+ AliInfo("Millepede has been already initialized!");
+ return;
+ }
+ // range constraints in such a way that the childs are constrained before their parents
+ // orphan constraints come last
+ for (int ic=0;ic<GetNConstraints();ic++) {
+ for (int ic1=ic+1;ic1<GetNConstraints();ic1++) {
+ AliITSAlignMille2Constraint *cst0 = GetConstraint(ic);
+ AliITSAlignMille2Constraint *cst1 = GetConstraint(ic1);
+ if (cst0->GetModuleID()<cst1->GetModuleID()) {
+ // swap
+ fConstraints[ic] = cst1;
+ fConstraints[ic1] = cst0;
+ }
+ }
+ }
+ //
+ if (!GetUseGlobalDelta()) {
+ AliInfo("ATTENTION: The parameters are defined in the local frame, no check for degeneracy will be done");
+ for (int imd=fNModules;imd--;) {
+ AliITSAlignMille2Module* mod = GetMilleModule(imd);
+ int npar = mod->GetNParTot();
+ // the parameter may have max 1 free instance, otherwise the equations are underdefined
+ for (int ipar=0;ipar<npar;ipar++) {
+ if (!mod->IsFreeDOF(ipar)) continue;
+ mod->SetParOffset(ipar,fNGlobal++);
+ }
+ }
+ }
+ else {
+ // init millepede, decide which parameters are to be fitted explicitly
+ for (int imd=fNModules;imd--;) {
+ AliITSAlignMille2Module* mod = GetMilleModule(imd);
+ int npar = mod->GetNParTot();
+ // the parameter may have max 1 free instance, otherwise the equations are underdefined
+ for (int ipar=0;ipar<npar;ipar++) {
+ if (!mod->IsFreeDOF(ipar)) continue; // fixed
+ //
+ int nFreeInstances = 0;
+ //
+ AliITSAlignMille2Module* parent = mod;
+ Bool_t cstMeanMed=kFALSE,cstGauss=kFALSE;
+ //
+ Bool_t addToFit = kFALSE;
+ // the parameter may be ommitted from explicit fit (if PseudoParentsAllowed is true) if
+ // 1) it is not explicitly constrained or its does not participate in Gaussian constraint
+ // 2) the same applies to all of its parents
+ // 3) it has at least 1 unconstrained direct child
+ while(parent) {
+ if (!parent->IsFreeDOF(ipar)) {parent = parent->GetParent(); continue;}
+ nFreeInstances++;
+ if (IsParModConstrained(parent,ipar, cstMeanMed, cstGauss)) nFreeInstances--;
+ if (cstGauss) addToFit = kTRUE;
+ parent = parent->GetParent();
+ }
+ if (nFreeInstances>1) {
+ AliError(Form("Parameter#%d of module %s\nhas %d free instances in the "
+ "unconstrained parents\nSystem is undefined",ipar,mod->GetName(),nFreeInstances));
+ exit(1);
+ }
+ //
+ // i) Are PseudoParents allowed?
+ if (!PseudoParentsAllowed()) addToFit = kTRUE;
+ // ii) check if this module has no child with such a free parameter. Since the order of this check
+ // goes from child to parent, by this moment such a parameter must have been already added
+ else if (!IsParModFamilyVaried(mod,ipar)) addToFit = kTRUE; // no varied children at all
+ else if (!IsParFamilyFree(mod,ipar,1)) addToFit = kTRUE; // no unconstrained direct children
+ // otherwise the value of this parameter can be extracted from simple contraint and the values of
+ // the relevant parameters of its children the fit is done. Hence it is not included
+ if (!addToFit) continue;
+ //
+ // shall add this parameter to explicit fit
+ // printf("Adding %s %d -> %d\n",mod->GetName(), ipar, fNGlobal);
+ mod->SetParOffset(ipar,fNGlobal++);
+ }
+ }
+ }
+ //
+ AliInfo(Form("Initializing Millepede with %d gpar, %d lpar and %d stddev ...",fNGlobal, kNLocal, fNStdDev));
+ fGlobalDerivatives = new Double_t[fNGlobal];
+ memset(fGlobalDerivatives,0,fNGlobal*sizeof(Double_t));
+ //
+ fMillepede->InitMille(fNGlobal,kNLocal,fNStdDev,fResCut,fResCutInitial);
+ fMillepede->SetMinPntValid(fMinPntPerSens);
+ fIsMilleInit = kTRUE;
+ //
+ ResetLocalEquation();
+ AliInfo("Parameters initialized to zero");
+ //
+ /// Fix non free parameters
+ for (Int_t i=0; i<fNModules; i++) {
+ AliITSAlignMille2Module* mod = GetMilleModule(i);
+ for (Int_t j=0; j<mod->GetNParTot(); j++) {
+ if (mod->GetParOffset(j)<0) continue; // not varied
+ FixParameter(mod->GetParOffset(j),mod->GetParConstraint(j));
+ fMillepede->SetParamGrID(i, mod->GetParOffset(j));
+ }
+ }
+ //
+ // Set iterations
+ if (fStartFac>1) fMillepede->SetIterations(fStartFac);
+ //
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::AddConstraint(Double_t *par, Double_t value, Double_t sigma)
+{
+ /// Constrain equation defined by par to value
+ if (!fIsMilleInit) Init();
+ fMillepede->SetGlobalConstraint(par, value, sigma);
+ AliInfo("Adding constraint");
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::InitGlobalParameters(Double_t *par)
+{
+ /// Initialize global parameters with par array
+ if (!fIsMilleInit) Init();
+ fMillepede->SetGlobalParameters(par);
+ AliInfo("Init Global Parameters");
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::FixParameter(Int_t iPar, Double_t value)
+{
+ /// Parameter iPar is encourage to vary in [-value;value].
+ /// If value == 0, parameter is fixed
+ if (!fIsMilleInit) {
+ AliInfo("Millepede has not been initialized!");
+ return;
+ }
+ fMillepede->SetParSigma(iPar, value);
+ if (IsZero(value)) AliInfo(Form("Parameter %i Fixed", iPar));
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ResetLocalEquation()
+{
+ /// Reset the derivative vectors
+ for(int i=kNLocal;i--;) fLocalDerivatives[i] = 0.0;
+ memset(fGlobalDerivatives, 0, fNGlobal*sizeof(double) );
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::ApplyToGeometry()
+{
+ // apply prealignment to ideal geometry
+ Int_t nprea = fPrealignment->GetEntriesFast();
+ AliInfo(Form("Array of prealignment deltas: %d entries",nprea));
+ //
+ for (int ix=0; ix<nprea; ix++) {
+ AliAlignObjParams *preo=(AliAlignObjParams*) fPrealignment->At(ix);
+ Int_t index=AliITSAlignMille2Module::GetIndexFromVolumeID(preo->GetVolUID());
+ if (index>=0) {
+ if (index>=fPreAlignQF.GetSize()) fPreAlignQF.Set(index+10);
+ fPreAlignQF[index] = (int) preo->GetUniqueID()+1;
+ }
+ if (!preo->ApplyToGeometry()) {
+ AliError(Form("Failed on ApplyToGeometry at %s",preo->GetSymName()));
+ return -1;
+ }
+ }
+ //
+ fUsePreAlignment = kTRUE;
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::GetPreAlignmentQualityFactor(Int_t index) const
+{
+ // quality factors from prealignment
+ if (!fUsePreAlignment || index<0 || index>=fPreAlignQF.GetSize()) return -1;
+ return fPreAlignQF[index]-1;
+}
+
+//________________________________________________________________________________________________________
+AliTrackPointArray *AliITSAlignMille2::PrepareTrack(const AliTrackPointArray *atp)
+{
+ /// create a new AliTrackPointArray keeping only defined modules
+ /// move points according to a given prealignment, if any
+ /// sort alitrackpoints w.r.t. global Y direction, if selected
+ const Double_t kRad2L[6] = {5*5,10*10,18*18,30*30,40*40,60*60};
+ const Float_t kSensSigY2[6] = {200e-4*200e-4/12, 200e-4*200e-4/12,
+ 300e-4*300e-4/12, 300e-4*300e-4/12,
+ 300e-4*300e-4/12, 300e-4*300e-4/12}; // thickness^2/12
+ //
+ fTrack = NULL;
+ Int_t idx[20];
+ Short_t lrID[20];
+ Int_t npts=atp->GetNPoints();
+ TGeoHMatrix hcov;
+ //
+ /// checks if AliTrackPoints belong to defined modules
+ Int_t ngoodpts=0;
+ Int_t intidx[20];
+ for (int j=0; j<npts; j++) {
+ intidx[j] = IsVIDContained(atp->GetVolumeID()[j]);
+ if (intidx[j]<0) continue;
+ ngoodpts++;
+ Float_t xx=atp->GetX()[j];
+ Float_t yy=atp->GetY()[j];
+ Float_t r=xx*xx + yy*yy;
+ int lay;
+ for (lay=0;lay<6;lay++) if (r<kRad2L[lay]) break;
+ if (lay>5) continue;
+ lrID[j] = lay;
+ }
+ //
+ AliDebug(3,Form("Number of points in defined modules: %d out of %d",ngoodpts,npts));
+
+ // pepo270809
+ Int_t nextra=0;
+ // extra clusters selection mode
+ if (fExtraClustersMode) {
+ // 1 = keep one cluster, remove randomly the extra
+ // 2 = keep one cluster, remove the internal one
+ // 10 = keep tracks only if at least one extra is present
+
+ int iextra1[20],iextra2[20],layovl[20];
+ // extra clusters mapping
+ for (Int_t ipt=0; ipt<npts; ipt++) {
+ if (intidx[ipt]<0) continue; // looks only defined modules...
+ float p1x=atp->GetX()[ipt];
+ float p1y=atp->GetY()[ipt];
+ float p1z=atp->GetZ()[ipt];
+ int lay1=int(AliGeomManager::VolUIDToLayer(atp->GetVolumeID()[ipt]));
+ float r1 = p1x*p1x + p1y*p1y;
+ UShort_t volid1=atp->GetVolumeID()[ipt];
+
+ for (int ik=ipt+1; ik<npts; ik++) {
+ if (intidx[ik]<0) continue;
+ // compare point ipt with next ones
+ int lay2=int(AliGeomManager::VolUIDToLayer(atp->GetVolumeID()[ik]));
+ // check if same layer
+ if (lay2 != lay1) continue;
+ UShort_t volid2=atp->GetVolumeID()[ik];
+ // check if different module
+ if (volid1 == volid2) continue;
+
+ float p2x=atp->GetX()[ik];
+ float p2y=atp->GetY()[ik];
+ float p2z=atp->GetZ()[ik];
+ float r2 = p2x*p2x + p2y*p2y;
+ float dr= (p1x-p2x)*(p1x-p2x) + (p1y-p2y)*(p1y-p2y) + (p1z-p2z)*(p1z-p2z);
+
+ // looks for pairs with dr<1 cm, same layer but different module
+ if (dr<1.0) {
+ // extra1 is the one with smaller radius in rphi plane
+ if (r1<r2) {
+ iextra1[nextra]=ipt;
+ iextra2[nextra]=ik;
+ }
+ else {
+ iextra1[nextra]=ik;
+ iextra2[nextra]=ipt;
+ }
+ layovl[nextra]=lay1;
+ nextra++;
+ }
+ }
+ } // end overlaps mapping
+
+ // mode=1: keep only one clusters and remove the other randomly
+ if (fExtraClustersMode==1 && nextra) {
+ for (int ie=0; ie<nextra; ie++) {
+ if (gRandom->Rndm()<0.5)
+ intidx[iextra1[ie]]=-1;
+ else
+ intidx[iextra2[ie]]=-1;
+ }
+ }
+
+ // mode=2: keep only one clusters and remove the other...
+ if (fExtraClustersMode==2 && nextra) {
+ for (int ie=0; ie<nextra; ie++) {
+ if (layovl[ie]==1) intidx[iextra2[ie]]=-1;
+ else if (layovl[ie]==2) intidx[iextra1[ie]]=-1;
+ else intidx[iextra1[ie]]=-1;
+ }
+ }
+
+ // mode=10: reject track if no overlaps are present
+ if (fExtraClustersMode==10 && nextra==0) {
+ AliInfo("Track with no extra clusters: rejected!");
+ return NULL;
+ }
+
+ // recalculate ngoodpts
+ ngoodpts=0;
+ for (int i=0; i<npts; i++) {
+ if (intidx[i]>=0) ngoodpts++;
+ }
+ }
+ // endpepo270809
+
+ // reject track if not enough points are left
+ if (ngoodpts<fMinNPtsPerTrack) {
+ AliInfo("Track with not enough points!");
+ return NULL;
+ }
+ // >> RS
+ AliTrackPoint p;
+ // check points in specific places
+ if (fRequirePoints) {
+ Int_t nlayup[6],nlaydown[6],nlay[6];
+ Int_t ndetup[3],ndetdown[3],ndet[3];
+ for (Int_t j=0; j<6; j++) {nlayup[j]=0; nlaydown[j]=0; nlay[j]=0;}
+ for (Int_t j=0; j<3; j++) {ndetup[j]=0; ndetdown[j]=0; ndet[j]=0;}
+
+ for (int i=0; i<npts; i++) {
+ // skip not defined points
+ if (intidx[i]<0) continue;
+ //
+ Float_t yy=atp->GetY()[i];
+ int lay = lrID[i];
+ int det=lay/2;
+ //printf("Point %d - x=%f y=%f R=%f lay=%d det=%d\n",i,xx,yy,r,lay,det);
+
+ if (yy>=0.0) { // UP point
+ nlayup[lay]++;
+ nlay[lay]++;
+ ndetup[det]++;
+ ndet[det]++;
+ }
+ else {
+ nlaydown[lay]++;
+ nlay[lay]++;
+ ndetdown[det]++;
+ ndet[det]++;
+ }
+ }
+ //
+ // checks minimum values
+ Bool_t isok=kTRUE;
+ for (Int_t j=0; j<6; j++) {
+ if (nlayup[j]<fNReqLayUp[j]) isok=kFALSE;
+ if (nlaydown[j]<fNReqLayDown[j]) isok=kFALSE;
+ if (nlay[j]<fNReqLay[j]) isok=kFALSE;
+ }
+ for (Int_t j=0; j<3; j++) {
+ if (ndetup[j]<fNReqDetUp[j]) isok=kFALSE;
+ if (ndetdown[j]<fNReqDetDown[j]) isok=kFALSE;
+ if (ndet[j]<fNReqDet[j]) isok=kFALSE;
+ }
+ if (!isok) {
+ AliDebug(2,Form("Track does not meet all location point requirements!"));
+ return NULL;
+ }
+ }
+ // build a new track with (sorted) (prealigned) good points
+ // pepo200709
+ //fTrack = (AliTrackPointArray*)fTrackBuff[ngoodpts-fMinNPtsPerTrack];
+ fTrack = (AliTrackPointArray*)fTrackBuff[ngoodpts];
+ if (!fTrack) {
+ fTrack = new AliTrackPointArray(ngoodpts);
+ // fTrackBuff.AddAtAndExpand(fTrack,ngoodpts-fMinNPtsPerTrack);
+ fTrackBuff.AddAtAndExpand(fTrack,ngoodpts);
+ }
+ // fTrack = new AliTrackPointArray(ngoodpts);
+ // endpepo200709
+ //
+ //
+ for (int i=0; i<npts; i++) idx[i]=i;
+ // sort track if required
+ TMath::Sort(npts,atp->GetY(),idx); // sort descending...
+ //
+ Int_t npto=0;
+ if (fClusLoc.GetSize()<3*npts) fClusLoc.Set(3*npts);
+ if (fClusGlo.GetSize()<3*npts) fClusGlo.Set(3*npts);
+ if (fClusSigLoc.GetSize()<3*npts) fClusSigLoc.Set(3*npts);
+ //
+ for (int i=0; i<npts; i++) {
+ // skip not defined points
+ if (intidx[idx[i]]<0) continue;
+ atp->GetPoint(p,idx[i]);
+ int sid = AliITSAlignMille2Module::GetIndexFromVolumeID(p.GetVolumeID());
+ //
+ // prealign point if required
+ // get matrix used to produce the digits
+ AliITSAlignMille2Module *mod = GetMilleModule(intidx[idx[i]]);
+ TGeoHMatrix *svOrigMatrix = GetSensorOrigMatrixSID(sid); //mod->GetSensitiveVolumeOrigGlobalMatrix(p.GetVolumeID());
+ // get back real local coordinate
+ Double_t *pl = fClusLoc.GetArray() + npto*3;
+ Double_t *pg = fClusGlo.GetArray() + npto*3;
+ Double_t *sgl = fClusSigLoc.GetArray() + npto*3;
+ pg[0]=p.GetX();
+ pg[1]=p.GetY();
+ pg[2]=p.GetZ();
+ AliDebug(3,Form("Global coordinates of measured point : X=%f Y=%f Z=%f \n",pg[0],pg[1],pg[2]));
+ svOrigMatrix->MasterToLocal(pg,pl);
+ AliDebug(3,Form("Local coordinates of measured point : X=%f Y=%f Z=%f \n",pg[0],pg[1],pg[2]));
+ //
+ // this is a temporary code to extract the drift speed used for given point
+ if (p.GetDriftTime()>0) { // RRR
+ // calculate the drift speed
+ fDriftTime0[npto] = fInitialRecSDD ? fInitialRecSDD->GetTimeZero(sid) : 0.;
+ double tdif = p.GetDriftTime() - fDriftTime0[npto];
+ if (tdif<=0) tdif = 1;
+ double vdrift = (3.5085-TMath::Abs(pl[0]))/tdif;
+ if (vdrift<0) vdrift = 0;
+ //
+ // TEMPORARY CORRECTION (if provided) -------------->>>
+ if (fCorrectSDD) {
+ float t0Upd = fCorrectSDD->GetTimeZero(sid);
+ vdrift += fCorrectSDD->GetDeltaVDrift(sid);
+ tdif = p.GetDriftTime() - t0Upd;
+ // correct Xlocal
+ pl[0] = TMath::Sign(3.5085 - vdrift*tdif,pl[0]);
+ fDriftTime0[npto] = t0Upd;
+ }
+ // TEMPORARY CORRECTION (if provided) --------------<<<
+ fDriftSpeed[npto] = TMath::Sign(vdrift,pl[0]);
+ //
+ }
+ // update covariance matrix
+ Double_t hcovel[9];
+ hcovel[0]=double(p.GetCov()[0]);
+ hcovel[1]=double(p.GetCov()[1]);
+ hcovel[2]=double(p.GetCov()[2]);
+ hcovel[3]=double(p.GetCov()[1]);
+ hcovel[4]=double(p.GetCov()[3]);
+ hcovel[5]=double(p.GetCov()[4]);
+ hcovel[6]=double(p.GetCov()[2]);
+ hcovel[7]=double(p.GetCov()[4]);
+ hcovel[8]=double(p.GetCov()[5]);
+ hcov.SetRotation(hcovel);
+ // now rotate in local system
+ hcov.Multiply(svOrigMatrix);
+ hcov.MultiplyLeft(&svOrigMatrix->Inverse());
+ // now hcov is LOCAL COVARIANCE MATRIX
+ // apply sigma scaling
+ Double_t *hcovscl = hcov.GetRotationMatrix();
+ hcovscl[4] = fUseLocalYErr ? kSensSigY2[lrID[idx[i]]] : 1E-10; // error due to the sensor thickness
+ //
+ for (int ir=3;ir--;) for (int ic=3;ic--;) {
+ if (ir==ic) {
+ if ( IsZero(hcovscl[ir*3+ic]) ) hcovscl[ir*3+ic] = 0.;
+ else hcovscl[ir*3+ic] *= mod->GetSigmaFactor(ir)*mod->GetSigmaFactor(ic); //RRR
+ sgl[ir] = TMath::Sqrt(hcovscl[ir*3+ic]);
+ }
+ else hcovscl[ir*3+ic] = 0;
+ }
+ //
+ //
+ if (fBug==1) {
+ // correzione bug LAYER 5 SSD temporanea..
+ int ssdidx=AliITSAlignMille2Module::GetIndexFromVolumeID(p.GetVolumeID());
+ if (ssdidx>=500 && ssdidx<1248) {
+ int ladder=(ssdidx-500)%22;
+ if (ladder==18) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx+1));
+ if (ladder==19) p.SetVolumeID(AliITSAlignMille2Module::GetVolumeIDFromIndex(ssdidx-1));
+ }
+ }
+ /// get (evenctually prealigned) matrix of sens. vol.
+ TGeoHMatrix *svMatrix = GetSensorCurrMatrixSID(sid); //mod->GetSensitiveVolumeMatrix(p.GetVolumeID());
+ // modify global coordinates according with pre-aligment
+ svMatrix->LocalToMaster(pl,pg);
+ // now rotate in local system
+ hcov.Multiply(&svMatrix->Inverse());
+ hcov.MultiplyLeft(svMatrix); // hcov is back in GLOBAL RF
+ // cure once more
+ for (int ir=3;ir--;) for (int ic=3;ic--;) if (IsZero(hcovscl[ir*3+ic])) hcovscl[ir*3+ic] = 0.;
+ // printf("\nErrMatGlob: after\n"); hcov.Print(""); //RRR
+ //
+ Float_t pcov[6];
+ pcov[0]=hcovscl[0];
+ pcov[1]=hcovscl[1];
+ pcov[2]=hcovscl[2];
+ pcov[3]=hcovscl[4];
+ pcov[4]=hcovscl[5];
+ pcov[5]=hcovscl[8];
+ //
+ p.SetXYZ(pg[0],pg[1],pg[2],pcov);
+ // printf("New Gl coordinates of measured point : X=%f Y=%f Z=%f \n",pg[0],pg[1],pg[2]);
+ AliDebug(3,Form("New global coordinates of measured point : X=%f Y=%f Z=%f \n",pg[0],pg[1],pg[2]));
+ fTrack->AddPoint(npto,&p);
+ AliDebug(2,Form("Adding point[%d] = ( %f , %f , %f ) volid = %d",npto,fTrack->GetX()[npto],
+ fTrack->GetY()[npto],fTrack->GetZ()[npto],fTrack->GetVolumeID()[npto] ));
+ // printf("Adding %d %d %f\n",npto, p.GetVolumeID(), p.GetY());
+ npto++;
+ }
+ //
+ return fTrack;
+}
+
+//________________________________________________________________________________________________________
+AliTrackPointArray *AliITSAlignMille2::SortTrack(const AliTrackPointArray *atp)
+{
+ /// sort alitrackpoints w.r.t. global Y direction
+ AliTrackPointArray *atps=NULL;
+ Int_t idx[20];
+ Int_t npts=atp->GetNPoints();
+ AliTrackPoint p;
+ atps=new AliTrackPointArray(npts);
+
+ TMath::Sort(npts,atp->GetY(),idx);
+
+ for (int i=0; i<npts; i++) {
+ atp->GetPoint(p,idx[i]);
+ atps->AddPoint(i,&p);
+ AliDebug(2,Form("Point[%d] = ( %f , %f , %f ) volid = %d",i,atps->GetX()[i],atps->GetY()[i],atps->GetZ()[i],atps->GetVolumeID()[i] ));
+ }
+ return atps;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::GetCurrentLayer() const
+{
+ // get current layer id
+ if (!fGeoManager) {
+ AliInfo("ITS geometry not initialized!");
+ return -1;
+ }
+ return (Int_t)AliGeomManager::VolUIDToLayer(fCluster.GetVolumeID());
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::InitModuleParams()
+{
+ /// initialize geometry parameters for a given detector
+ /// for current cluster (fCluster)
+ /// fGlobalInitParam[] is set as:
+ /// [tx,ty,tz,psi,theta,phi]
+ /// (old was [tx,ty,tz,theta,psi,phi] ROOT's angles...)
+ /// *** At the moment: using Raffalele's angles definition ***
+ ///
+ /// return 0 if success
+ /// If module is found but has no parameters to vary, return 1
+
+ if (!fGeoManager) {
+ AliInfo("ITS geometry not initialized!");
+ return -1;
+ }
+
+ // now 'voluid' is the volumeID of a SENSITIVE VOLUME (coming from a cluster)
+
+ // set the internal index (index in module list)
+ UShort_t voluid=fCluster.GetVolumeID();
+ fCurrentSensID = AliITSAlignMille2Module::GetIndexFromVolumeID(voluid);
+ //
+ // IT IS VERY IMPORTANT: start from the end of the list, where the childs are located !!!
+ Int_t k=fNModules-1;
+ fCurrentModule = 0;
+ // VERY IMPORTANT: if the sensors were explicitly provided, don't look in the supermodules
+ while (k>=0 && ! (fCurrentModule=GetMilleModule(k))->IsIn(voluid)) k--;
+ if (k<0) return -3;
+ //
+ for (int i=AliITSAlignMille2Module::kMaxParTot;i--;) fModuleInitParam[i] = 0.0;
+ //
+ int clID = fCluster.GetUniqueID()-1;
+ if (clID<0) { // external cluster
+ fMeasGlo = &fExtClusterPar[0];
+ fMeasLoc = &fExtClusterPar[3];
+ fSigmaLoc = &fExtClusterPar[6];
+ fExtClusterPar[0] = fCluster.GetX();
+ fExtClusterPar[1] = fCluster.GetY();
+ fExtClusterPar[2] = fCluster.GetZ();
+ //
+ TGeoHMatrix *svMatrix = fCurrentModule->GetSensitiveVolumeMatrix(voluid);
+ svMatrix->MasterToLocal(fMeasGlo,fMeasLoc);
+ TGeoHMatrix hcov;
+ Double_t hcovel[9];
+ hcovel[0]=double(fCluster.GetCov()[0]);
+ hcovel[1]=double(fCluster.GetCov()[1]);
+ hcovel[2]=double(fCluster.GetCov()[2]);
+ hcovel[3]=double(fCluster.GetCov()[1]);
+ hcovel[4]=double(fCluster.GetCov()[3]);
+ hcovel[5]=double(fCluster.GetCov()[4]);
+ hcovel[6]=double(fCluster.GetCov()[2]);
+ hcovel[7]=double(fCluster.GetCov()[4]);
+ hcovel[8]=double(fCluster.GetCov()[5]);
+ hcov.SetRotation(hcovel);
+ // now rotate in local system
+ hcov.Multiply(svMatrix);
+ hcov.MultiplyLeft(&svMatrix->Inverse());
+ if (fSigmaLoc[0]<0.0010) fSigmaLoc[0]=0.0010;
+ if (fSigmaLoc[2]<0.0010) fSigmaLoc[2]=0.0010;
+ //
+ }
+ else {
+ int offs = 3*clID;
+ fMeasGlo = fClusGlo.GetArray() + offs;
+ fMeasLoc = fClusLoc.GetArray() + offs;
+ fSigmaLoc = fClusSigLoc.GetArray() + offs;
+ }
+ //
+ // set minimum value for SigmaLoc to 10 micron
+ if (fSigmaLoc[0]<0.0010) fSigmaLoc[0]=0.0010;
+ if (fSigmaLoc[2]<0.0010) fSigmaLoc[2]=0.0010;
+ //
+ AliDebug(2,Form("Local coordinates of measured point : X=%f Y=%f Z=%f \n",fMeasLoc[0] ,fMeasLoc[1] ,fMeasLoc[2] ));
+ AliDebug(2,Form("Setting StDev from CovMat : fSigmaLocX=%g fSigmaLocY=%g fSigmaLocZ=%g \n",fSigmaLoc[0] ,fSigmaLoc[1] ,fSigmaLoc[2] ));
+ //
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::Print(Option_t*) const
+{
+ // print current status
+ printf("*** AliMillepede for ITS ***\n");
+ printf(" Number of defined super modules: %d\n",fNModules);
+ printf(" Obtained parameters refer to %s Deltas\n",fUseGlobalDelta ? "GLOBAL":"LOCAL");
+ //
+ if (fGeoManager)
+ printf(" geometry loaded from %s\n",fGeometryPath.Data());
+ else
+ printf(" geometry not loaded\n");
+ //
+ if (fUsePreAlignment)
+ printf(" using prealignment from %s \n",fPreDeltaPath.Data());
+ else
+ printf(" prealignment not used\n");
+ //
+ //
+ if (fBOn)
+ printf(" B Field set to %f T - using helices\n",fBField);
+ else
+ printf(" B Field OFF - using straight lines \n");
+ //
+ if (fTPAFitter)
+ printf(" Using AliITSTPArrayFit class for track fitting\n");
+ else
+ printf(" Using StraightLine/Riemann fitter for track fitting\n");
+ //
+ printf("Using local Y error due to the sensor thickness: %s\n",(fUseLocalYErr && fTPAFitter) ? "ON":"OFF");
+ //
+ if (fRequirePoints) printf(" Required points in tracks:\n");
+ for (Int_t i=0; i<6; i++) {
+ if (fNReqLayUp[i]>0) printf(" Layer %d : %d points with Y>0\n",i+1,fNReqLayUp[i]);
+ if (fNReqLayDown[i]>0) printf(" Layer %d : %d points with Y<0\n",i+1,fNReqLayDown[i]);
+ if (fNReqLay[i]>0) printf(" Layer %d : %d points \n",i+1,fNReqLay[i]);
+ }
+ for (Int_t i=0; i<3; i++) {
+ if (fNReqDetUp[i]>0) printf(" Detector %d : %d points with Y>0\n",i+1,fNReqDetUp[i]);
+ if (fNReqDetDown[i]>0) printf(" Detector %d : %d points with Y<0\n",i+1,fNReqDetDown[i]);
+ if (fNReqDet[i]>0) printf(" Detector %d : %d points \n",i+1,fNReqDet[i]);
+ }
+ //
+ printf("\n Millepede configuration parameters:\n");
+ printf(" init value for chi2 cut : %.4f\n",fStartFac);
+ printf(" first iteration cut value : %.4f\n",fResCutInitial);
+ printf(" other iterations cut value : %.4f\n",fResCut);
+ printf(" number of stddev for chi2 cut : %d\n",fNStdDev);
+ printf(" def.scaling for local sigmas : %.4f %.4f %.4f\n",fSigmaFactor[0],fSigmaFactor[1],fSigmaFactor[2]);
+ printf(" min.tracks per module : %d\n",fMinPntPerSens);
+ //
+ printf("List of defined modules:\n");
+ printf(" intidx\tindex\tvoluid\tname\n");
+ for (int i=0; i<fNModules; i++) {
+ AliITSAlignMille2Module* md = GetMilleModule(i);
+ printf(" %d\t%d\t%d\t%s\n",i,md->GetIndex(),md->GetVolumeID(),md->GetName());
+ }
+}
+
+//________________________________________________________________________________________________________
+AliITSAlignMille2Module *AliITSAlignMille2::GetMilleModuleByVID(UShort_t voluid) const
+{
+ // return pointer to a defined supermodule
+ // return NULL if error
+ Int_t i=IsVIDDefined(voluid);
+ if (i<0) return NULL;
+ return GetMilleModule(i);
+}
+
+//________________________________________________________________________________________________________
+AliITSAlignMille2Module *AliITSAlignMille2::GetMilleModuleBySymName(const Char_t* symname) const
+{
+ // return pointer to a defined supermodule
+ // return NULL if error
+ UShort_t vid = AliITSAlignMille2Module::GetVolumeIDFromSymname(symname);
+ if (vid>0) return GetMilleModuleByVID(vid);
+ else { // this is not alignable module, need to look within defined supermodules
+ int i = IsSymDefined(symname);
+ if (i>=0) return GetMilleModule(i);
+ }
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+AliITSAlignMille2Module *AliITSAlignMille2::GetMilleModuleIfContained(const Char_t* symname) const
+{
+ // return pointer to a defined/contained supermodule
+ // return NULL otherwise
+ int i = IsSymContained(symname);
+ return i<0 ? 0 : GetMilleModule(i);
+}
+
+//________________________________________________________________________________________________________
+AliAlignObjParams* AliITSAlignMille2::GetPrealignedObject(const Char_t* symname) const
+{
+ // get delta from prealignment for given volume
+ if (!fPrealignment) return 0;
+ for (int ipre=fPrealignment->GetEntriesFast();ipre--;) { // was the corresponding object prealigned?
+ AliAlignObjParams* preob = (AliAlignObjParams*)fPrealignment->At(ipre);
+ if (!strcmp(preob->GetSymName(),symname)) return preob;
+ }
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+AliAlignObjParams* AliITSAlignMille2::GetConstrRefObject(const Char_t* symname) const
+{
+ // get delta with respect to which the constraint is declared
+ if (!fConstrRef) return 0;
+ for (int ipre=fConstrRef->GetEntriesFast();ipre--;) { // was the corresponding object prealigned?
+ AliAlignObjParams* preob = (AliAlignObjParams*)fConstrRef->At(ipre);
+ if (!strcmp(preob->GetSymName(),symname)) return preob;
+ }
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Bool_t AliITSAlignMille2::InitRiemanFit()
+{
+ // Initialize Riemann Fitter for current track
+ // return kFALSE if error
+
+ if (!fBOn) return kFALSE;
+
+ Int_t npts=0;
+ AliTrackPoint ap;
+ npts = fTrack->GetNPoints();
+ AliDebug(3,Form("Fitting track with %d points",npts));
+ if (!fRieman) fRieman = new AliTrackFitterRieman();
+ fRieman->Reset();
+ fRieman->SetTrackPointArray(fTrack);
+
+ TArrayI ai(npts);
+ for (Int_t ipt=0; ipt<npts; ipt++) ai[ipt]=fTrack->GetVolumeID()[ipt];
+
+ // fit track with 5 params in his own tracking-rotated reference system
+ // xc = -p[1]/p[0];
+ // yc = 1/p[0];
+ // R = sqrt( x0*x0 + y0*y0 - y0*p[2]);
+ if (!fRieman->Fit(&ai,NULL,(AliGeomManager::ELayerID)1,(AliGeomManager::ELayerID)6)) {
+ return kFALSE;
+ }
+
+ for (int i=0; i<5; i++)
+ fLocalInitParam[i] = fRieman->GetParam()[i];
+
+ return kTRUE;
+}
+
+//________________________________________________________________________________________________________
+void trackFit2D(Int_t &, Double_t *, double &chi2, double *par, int flag)
+{
+ // local function for minuit
+ const double kTiny = 1.e-14;
+ chi2 = 0;
+ static AliTrackPoint pnt;
+ static Bool_t fullErr2D;
+ //
+ if (flag==1) fullErr2D = kFALSE;//kTRUE;
+ fullErr2D = kTRUE;
+ enum {kAX,kAZ,kBX,kBZ};
+ enum {kXX=0,kXY=1,kXZ=2,kYX=kXY,kYY=3,kYZ=4,kZX=kXZ,kZY=kYZ,kZZ=5};
+ //
+ AliITSAlignMille2* alig = AliITSAlignMille2::GetInstance();
+ AliTrackPointArray* track = alig->GetCurrentTrack();
+ //
+ int npts = track->GetNPoints();
+ for (int ip=0;ip<npts;ip++) {
+ track->GetPoint(pnt,ip);
+ const float *cov = pnt.GetCov();
+ double y = pnt.GetY();
+ double dx = pnt.GetX() - (par[kAX]+y*par[kBX]);
+ double dz = pnt.GetZ() - (par[kAZ]+y*par[kBZ]);
+ double xxe = cov[kXX];
+ double zze = cov[kZZ];
+ double xze = cov[kXZ];
+ //
+ if (fullErr2D) {
+ xxe += par[kBX]*par[kBX]*cov[kYY]-2.*par[kBX]*cov[kXY];
+ zze += par[kBZ]*par[kBZ]*cov[kYY]-2.*par[kBZ]*cov[kZY];
+ xze += par[kBX]*par[kBZ]*cov[kYY]-cov[kYZ]*par[kBZ]-cov[kXY]*par[kBX];
+ }
+ //
+ double det = xxe*zze - xze*xze;
+ if (det<kTiny) {
+ printf("Negative diag. error (det=%+e) |sxx:%+e szz:%+e sxz:%+e| bx:%+e bz:%+e|\n"
+ "Discarding correlation term\n",det,xxe,zze,xze,par[kBX],par[kBZ]);
+ xxe = cov[kXX];
+ zze = cov[kZZ];
+ xze = cov[kXZ];
+ fullErr2D = kFALSE;
+ }
+ double xxeI = zze/det;
+ double zzeI = xxe/det;
+ double xzeI =-xze/det;
+ //
+ chi2 += dx*dx*xxeI + dz*dz*zzeI + 2.*dx*dz*xzeI;
+ //
+ // printf("%d | %+e %+e %+e %+e %+e -> %+e\n",ip,dx,dz,xxeI,zzeI,xzeI, chi2);
+ }
+ //
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::InitTrackParams(int meth)
+{
+ /// initialize local parameters with different methods
+ /// for current track (fTrack)
+ Int_t npts=0;
+ AliTrackPoint ap;
+ double sX=0,sXY=0,sZ=0,sZY=0,sY=0,sYY=0,det=0;
+ // simple linear interpolation
+ // get local starting parameters (to be substituted by ESD track parms)
+ // local parms (fLocalInitParam[]) are:
+ // [0] = global x coord. of straight line intersection at y=0 plane
+ // [1] = global z coord. of straight line intersection at y=0 plane
+ // [2] = px/py
+ // [3] = pz/py
+ // test #1: linear fit in x(y) and z(y)
+ npts = fTrack->GetNPoints();
+ AliDebug(3,Form("*** initializing track with %d points ***",npts));
+ for (int i=npts;i--;) {
+ sY += fTrack->GetY()[i];
+ sYY += fTrack->GetY()[i]*fTrack->GetY()[i];
+ sX += fTrack->GetX()[i];
+ sXY += fTrack->GetX()[i]*fTrack->GetY()[i];
+ sZ += fTrack->GetZ()[i];
+ sZY += fTrack->GetZ()[i]*fTrack->GetY()[i];
+ }
+ det = sYY*npts-sY*sY;
+ if (IsZero(det)) det = 1E-16;
+ fLocalInitParam[0] = (sX*sYY-sY*sXY)/det;
+ fLocalInitParam[2] = (sXY*npts-sY*sX)/det;
+ //
+ fLocalInitParam[1] = (sZ*sYY-sY*sZY)/det;
+ fLocalInitParam[3] = (sZY*npts-sY*sZ)/det;
+ // pepo200709
+ fLocalInitParam[4] = 0.0;
+ // endpepo200709
+
+ AliDebug(2,Form("X = p0gx + ugx*Y : p0gx = %f ugx = %f\n",fLocalInitParam[0],fLocalInitParam[2]));
+ //
+ if (meth==1) return;
+ //
+ // perform full fit accounting for cov.matrix
+ static TVirtualFitter *minuit = 0;
+ static Double_t step[5] = {1E-3,1E-3,1E-4,1E-4,1E-5};
+ static Double_t arglist[10];
+ //
+ if (!minuit) {
+ minuit = TVirtualFitter::Fitter(0,4);
+ minuit->SetFCN(trackFit2D);
+ arglist[0] = 1;
+ minuit->ExecuteCommand("SET ERR",arglist, 1);
+ //
+ arglist[0] = -1;
+ minuit->ExecuteCommand("SET PRINT",arglist,1);
+ //
+ }
+ //
+ minuit->SetParameter(0, "ax", fLocalInitParam[0], step[0], 0,0);
+ minuit->SetParameter(1, "az", fLocalInitParam[1], step[1], 0,0);
+ minuit->SetParameter(2, "bx", fLocalInitParam[2], step[2], 0,0);
+ minuit->SetParameter(3, "bz", fLocalInitParam[3], step[3], 0,0);
+ //
+ arglist[0] = 1000; // number of function calls
+ arglist[1] = 0.001; // tolerance
+ minuit->ExecuteCommand("MIGRAD",arglist,2);
+ //
+ for (int i=0;i<4;i++) fLocalInitParam[i] = minuit->GetParameter(i);
+ for (int i=0;i<4;i++) for (int j=0;j<4;j++) fLocalInitParEr[i][j] = minuit->GetCovarianceMatrixElement(i,j);
+ /*
+ double amin,edm,errdef;
+ int nvpar,nparx;
+ minuit->GetStats(amin,edm,errdef,nvpar,nparx);
+ amin /= (2*npts - 4);
+ printf("Mchi2: %+e\n",amin);
+ */
+ //
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::IsSymDefined(const Char_t* symname) const
+{
+ // checks if supermodule with this symname is defined and return the internal index
+ // return -1 if not.
+ for (int k=fNModules;k--;) if (!strcmp(symname,GetMilleModule(k)->GetName())) return k;
+ return -1;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::IsSymContained(const Char_t* symname) const
+{
+ // checks if module with this symname is defined and return the internal index
+ // return -1 if not.
+ UShort_t vid = AliITSAlignMille2Module::GetVolumeIDFromSymname(symname);
+ if (vid>0) return IsVIDContained(vid);
+ // only sensors have real vid, but maybe we have a supermodule with fake vid?
+ // IMPORTANT: always start from the end to start from the sensors
+ return IsSymDefined(symname);
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::IsVIDDefined(UShort_t voluid) const
+{
+ // checks if supermodule 'voluid' is defined and return the internal index
+ // return -1 if not.
+ for (int k=fNModules;k--;) if (voluid==GetMilleModule(k)->GetVolumeID()) return k;
+ return -1;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::IsVIDContained(UShort_t voluid) const
+{
+ // checks if the sensitive module 'voluid' is contained inside a supermodule
+ // and return the internal index of the last identified supermodule
+ // return -1 if error
+ // IMPORTANT: always start from the end to start from the sensors
+ if (AliITSAlignMille2Module::GetIndexFromVolumeID(voluid)<0) return -1;
+ for (int k=fNModules;k--;) if (GetMilleModule(k)->IsIn(voluid)) return k;
+ return -1;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::CheckCurrentTrack()
+{
+ /// checks if AliTrackPoints belongs to defined modules
+ /// return number of good poins
+ /// return 0 if not enough points
+
+ Int_t npts = fTrack->GetNPoints();
+ Int_t ngoodpts=0;
+ // debug points
+ for (int j=0; j<npts; j++) if (IsVIDContained(fTrack->GetVolumeID()[j])>=0) ngoodpts++;
+ //
+ if (ngoodpts<fMinNPtsPerTrack) return 0;
+
+ return ngoodpts;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::ProcessTrack(const AliTrackPointArray *track)
+{
+ /// Process track; Loop over hits and set local equations
+ /// here 'track' is a AliTrackPointArray
+ /// return 0 if success;
+
+ if (!fIsMilleInit) Init();
+ //
+ Int_t npts = track->GetNPoints();
+ AliDebug(2,Form("*** Input track with %d points ***",npts));
+
+ // preprocessing of the input track: keep only points in defined volumes,
+ // move points if prealignment is set, sort by Yglo if required
+
+ fTrack=PrepareTrack(track);
+ if (!fTrack) return -1;
+
+ npts = fTrack->GetNPoints();
+ if (npts>kMaxPoints) {
+ AliError(Form("Compiled with kMaxPoints=%d, current track has %d points",kMaxPoints,npts));
+ }
+ AliDebug(2,Form("*** Processing prepared track with %d points ***",npts));
+ //
+ if (fTPAFitter) { // use dediacted fitter
+ //
+ fTPAFitter->AttachPoints(fTrack);
+ if (fBOn) fTPAFitter->SetBz(fBField);
+ if (fInitTrackParamsMeth==1) fTPAFitter->SetIgnoreCov();
+ double chi2 = fTPAFitter->Fit(fConstrCharge,fConstrPT,fConstrPTErr);
+ //
+ // suppress eventual constraints to not affect fit of the next track
+ fConstrCharge = 0;
+ fConstrPT = fConstrPTErr = -1;
+ //
+ if ( chi2<0 || (fTPAFitter->GetNIterations()>=fTPAFitter->GetMaxIterations()) ) {
+ AliInfo("Track fit failed! skipping this track...");
+ fTPAFitter->Reset();
+ fTrack = NULL;
+ return -5;
+ }
+ /*
+ double *pr = fTPAFitter->GetParams();
+ printf("FtPar: %+.5e %+.5e %+.5e %+.5e | chi2:%.3e\n",pr[2],pr[0],pr[3],pr[1],chi2); // RRR
+ */
+ }
+ else {
+ //
+ if (!fBOn) { // straight lines
+ // set local starting parameters (to be substituted by ESD track parms)
+ // local parms (fLocalInitParam[]) are:
+ // [0] = global x coord. of straight line intersection at y=0 plane
+ // [1] = global z coord. of straight line intersection at y=0 plane
+ // [2] = px/py
+ // [3] = pz/py
+ InitTrackParams(fInitTrackParamsMeth);
+ /*
+ double *pr = fLocalInitParam;
+ printf("FtPar: %+.5e %+.5e %+.5e %+.5e |\n",pr[0],pr[1],pr[2],pr[3]); // RRR
+ */
+ }
+ else {
+ // local parms (fLocalInitParam[]) are the Riemann Fitter params
+ if (!InitRiemanFit()) {
+ AliInfo("Riemann fit failed! skipping this track...");
+ fTrack=NULL;
+ return -5;
+ }
+ }
+ }
+ //
+ // printf("Params: "); for (int i=0;i<fNLocal;i++) printf("%+.2e ",fLocalInitParam[i]); printf("\n");//RRR
+ Int_t nloceq=0;
+ Int_t ngloeq=0;
+ static Mille2Data md[kMaxPoints];
+ //
+ for (Int_t ipt=0; ipt<npts; ipt++) {
+ fTrack->GetPoint(fCluster,ipt);
+ fCluster.SetUniqueID(ipt+1);
+ AliDebug(2,Form("\n--- processing point %d --- \n",ipt));
+
+ // set geometry parameters for the the current module
+ if (InitModuleParams()) continue;
+ AliDebug(2,Form(" VolID=%d Index=%d InternalIdx=%d symname=%s\n",
+ track->GetVolumeID()[ipt], fCurrentModule->GetIndex(),
+ fCurrentModule->GetUniqueID(), AliGeomManager::SymName(track->GetVolumeID()[ipt]) ));
+ AliDebug(2,Form(" Preprocessed Point = ( %f , %f , %f ) \n",fCluster.GetX(),fCluster.GetY(),fCluster.GetZ()));
+ int res = fTPAFitter ? AddLocalEquationTPA(md[nloceq]) : AddLocalEquation(md[nloceq]);
+ if (res<0) {fTotBadLocEqPoints++; nloceq = 0; break;}
+ else if (res>0) {nloceq++; ngloeq++;}
+ } // end loop over points
+ //
+ fTrack=NULL;
+ // not enough good points?
+ if (nloceq<fMinNPtsPerTrack || ngloeq<1) return -1;
+ //
+ // finally send local equations to millepede
+ SetLocalEquations(md,nloceq);
+ fMillepede->SaveRecordData(); // RRR
+ //
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::CalcIntersectionPoint(Double_t *lpar, Double_t *gpar)
+{
+ /// calculate track intersection point in local coordinates
+ /// according with a given set of parameters (local(4) and global(6))
+ /// and fill fPintLoc/Glo
+ /// local are: pgx0, pgz0, ugx, ugz OR riemann fitters pars
+ /// global are: tx,ty,tz,psi,theta,phi (Raff's delta angles in deg.)
+ /// return 0 if success
+
+ 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]));
+ 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]));
+
+
+ // prepare the TGeoHMatrix
+ TGeoHMatrix *tempHMat = fCurrentModule->GetSensitiveVolumeModifiedMatrix(fCluster.GetVolumeID(),gpar,
+ !fUseGlobalDelta);
+ if (!tempHMat) return -1;
+
+ Double_t v0g[3]; // vector with straight line direction in global coord.
+ Double_t p0g[3]; // point of the straight line (glo)
+
+ if (fBOn) { // B FIELD!
+ AliTrackPoint prf;
+ for (int ip=0; ip<5; ip++)
+ fRieman->SetParam(ip,lpar[ip]);
+
+ if (!fRieman->GetPCA(fCluster,prf)) {
+ AliInfo(Form("error in GetPCA for point %d",fCluster.GetVolumeID()));
+ return -3;
+ }
+ // now determine straight line passing tangent to fit curve at prf
+ // ugx = dX/dY_glo = DeltaX/DeltaY_glo
+ // mo' P1=(X,Y,Z)_glo_prf
+ // => (x,y,Z)_trk_prf ruotando di alpha...
+ Double_t alpha=fRieman->GetAlpha();
+ Double_t x1g = prf.GetX();
+ Double_t y1g = prf.GetY();
+ Double_t z1g = prf.GetZ();
+ Double_t x1t = x1g*TMath::Cos(alpha) + y1g*TMath::Sin(alpha);
+ Double_t y1t = -x1g*TMath::Sin(alpha) + y1g*TMath::Cos(alpha);
+ Double_t z1t = z1g;
+
+ Double_t x2t = x1t+1.0;
+ Double_t y2t = y1t+fRieman->GetDYat(x1t);
+ Double_t z2t = z1t+fRieman->GetDZat(x1t);
+ Double_t x2g = x2t*TMath::Cos(alpha) - y2t*TMath::Sin(alpha);
+ Double_t y2g = x2t*TMath::Sin(alpha) + y2t*TMath::Cos(alpha);
+ Double_t z2g = z2t;
+
+ AliDebug(3,Form("Riemann frame: fAlpha = %f = %f ",alpha,alpha*180./TMath::Pi()));
+ AliDebug(3,Form(" prf_glo=( %f , %f , %f ) prf_rf=( %f , %f , %f )\n", x1g,y1g,z1g, x1t,y1t,z1t));
+ AliDebug(3,Form(" mov_glo=( %f , %f , %f ) rf=( %f , %f , %f )\n",x2g,y2g,z2g, x2t,y2t,z2t));
+
+ if (TMath::Abs(y2g-y1g)<1e-15) {
+ AliInfo("DeltaY=0! Cannot proceed...");
+ return -1;
+ }
+ // ugx,1,ugz
+ v0g[0] = (x2g-x1g)/(y2g-y1g);
+ v0g[1]=1.0;
+ v0g[2] = (z2g-z1g)/(y2g-y1g);
+
+ // point: just keep prf
+ p0g[0]=x1g;
+ p0g[1]=y1g;
+ p0g[2]=z1g;
+ }
+ else { // staight line
+ // vector of initial straight line direction in glob. coord
+ v0g[0]=lpar[2];
+ v0g[1]=1.0;
+ v0g[2]=lpar[3];
+
+ // intercept in yg=0 plane in glob coord
+ p0g[0]=lpar[0];
+ p0g[1]=0.0;
+ p0g[2]=lpar[1];
+ }
+ 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]));
+
+ // same in local coord.
+ Double_t p0l[3],v0l[3];
+ tempHMat->MasterToLocalVect(v0g,v0l);
+ tempHMat->MasterToLocal(p0g,p0l);
+
+ if (TMath::Abs(v0l[1])<1e-15) {
+ AliInfo("Track Y direction in local frame is zero! Cannot proceed...");
+ return -1;
+ }
+
+ // local intersection point
+ fPintLoc[0] = p0l[0] - (v0l[0]/v0l[1])*p0l[1];
+ fPintLoc[1] = 0;
+ fPintLoc[2] = p0l[2] - (v0l[2]/v0l[1])*p0l[1];
+
+ // global intersection point
+ tempHMat->LocalToMaster(fPintLoc,fPintGlo);
+ 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]));
+
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::CalcDerivatives(Int_t paridx, Bool_t islpar)
+{
+ /// calculate numerically (ROOT's style) the derivatives for
+ /// local X intersection and local Z intersection
+ /// parlist: local (islpar=kTRUE) pgx0, pgz0, ugx0, ugz0 OR riemann's params
+ /// global (islpar=kFALSE) tx, ty, tz, psi, theta, phi (Raf's angles in deg)
+ /// return 0 if success
+
+ // copy initial parameters
+ Double_t lpar[kNLocal];
+ Double_t gpar[kNParCh];
+ Double_t *derivative;
+ for (Int_t i=0; i<kNLocal; i++) lpar[i]=fLocalInitParam[i];
+ for (Int_t i=0; i<kNParCh; i++) gpar[i]=fModuleInitParam[i];
+
+ // trial with fixed dpar...
+ Double_t dpar = 0.;
+
+ if (islpar) { // track parameters
+ //dpar=fLocalInitParam[paridx]*0.001;
+ // set minimum dpar
+ derivative = fDerivativeLoc[paridx];
+ if (!fBOn) {
+ if (paridx<3) dpar=1.0e-4; // translations
+ else dpar=1.0e-6; // direction
+ }
+ else { // B Field
+ // pepo: proviamo con 1/1000, poi evenctually 1/100...
+ Double_t dfrac=0.01;
+ switch(paridx) {
+ case 0:
+ // RMS cosmics: 1e-4
+ dpar = TMath::Max(1.0e-6,TMath::Abs(fLocalInitParam[paridx]*dfrac));
+ break;
+ case 1:
+ // RMS cosmics: 0.2
+ dpar = TMath::Max(0.002,TMath::Abs(fLocalInitParam[paridx]*dfrac));
+ break;
+ case 2:
+ // RMS cosmics: 9
+ dpar = TMath::Max(0.09,TMath::Abs(fLocalInitParam[paridx]*dfrac));
+ break;
+ case 3:
+ // RMS cosmics: 7
+ dpar = TMath::Max(0.07,TMath::Abs(fLocalInitParam[paridx]*dfrac));
+ break;
+ case 4:
+ // RMS cosmics: 0.3
+ dpar = TMath::Max(0.003,TMath::Abs(fLocalInitParam[paridx]*dfrac));
+ break;
+ }
+ }
+ }
+ else { // alignment global parameters
+ derivative = fDerivativeGlo[paridx];
+ //dpar=fModuleInitParam[paridx]*0.001;
+ if (paridx<3) dpar=1.0e-4; // translations
+ else dpar=1.0e-2; // angles
+ }
+
+ AliDebug(3,Form("+++ using dpar=%g",dpar));
+
+ // calculate derivative ROOT's like:
+ // using f(x+h),f(x-h),f(x+h/2),f(x-h2)...
+ Double_t pintl1[3]; // f(x-h)
+ Double_t pintl2[3]; // f(x-h/2)
+ Double_t pintl3[3]; // f(x+h/2)
+ Double_t pintl4[3]; // f(x+h)
+
+ // first values
+ if (islpar) lpar[paridx] -= dpar;
+ else gpar[paridx] -= dpar;
+ if (CalcIntersectionPoint(lpar, gpar)) return -2;
+ for (Int_t i=0; i<3; i++) pintl1[i]=fPintLoc[i];
+
+ // second values
+ if (islpar) lpar[paridx] += dpar/2;
+ else gpar[paridx] += dpar/2;
+ if (CalcIntersectionPoint(lpar, gpar)) return -2;
+ for (Int_t i=0; i<3; i++) pintl2[i]=fPintLoc[i];
+
+ // third values
+ if (islpar) lpar[paridx] += dpar;
+ else gpar[paridx] += dpar;
+ if (CalcIntersectionPoint(lpar, gpar)) return -2;
+ for (Int_t i=0; i<3; i++) pintl3[i]=fPintLoc[i];
+
+ // fourth values
+ if (islpar) lpar[paridx] += dpar/2;
+ else gpar[paridx] += dpar/2;
+ if (CalcIntersectionPoint(lpar, gpar)) return -2;
+ for (Int_t i=0; i<3; i++) pintl4[i]=fPintLoc[i];
+
+ Double_t h2 = 1./(2.*dpar);
+ Double_t d0 = pintl4[0]-pintl1[0];
+ Double_t d2 = 2.*(pintl3[0]-pintl2[0]);
+ derivative[0] = h2*(4*d2 - d0)/3.;
+ if (TMath::Abs(derivative[0]) < 1.0e-9) derivative[0] = 0.0;
+
+ d0 = pintl4[2]-pintl1[2];
+ d2 = 2.*(pintl3[2]-pintl2[2]);
+ derivative[2] = h2*(4*d2 - d0)/3.;
+ if (TMath::Abs(derivative[2]) < 1.0e-9) derivative[2]=0.0;
+
+ AliDebug(3,Form("\n+++ derivatives +++ \n"));
+ AliDebug(3,Form("+++ dXLoc/dpar = %g +++\n",derivative[0]));
+ AliDebug(3,Form("+++ dZLoc/dpar = %g +++\n\n",derivative[2]));
+
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::AddLocalEquation(Mille2Data &m)
+{
+ /// Define local equation for current cluster in X and Z coor.
+ /// and store them to memory
+ /// return -1 in case of failure to build some equation
+ /// 0 if no free global parameters were found but local eq is built
+ /// 1 if both local and global eqs are built
+ //
+ // store first intersection point
+ if (CalcIntersectionPoint(fLocalInitParam, fModuleInitParam)) return -1;
+ for (Int_t i=0; i<3; i++) fPintLoc0[i]=fPintLoc[i];
+
+ AliDebug(2,Form("Intersect. point: L( %f , %f , %f )",fPintLoc[0],fPintLoc[1],fPintLoc[2]));
+
+ // calculate local derivatives numerically
+ Bool_t zeroX = kTRUE;
+ Bool_t zeroZ = kTRUE;
+ //
+ for (Int_t i=0; i<fNLocal; i++) {
+ if (CalcDerivatives(i,kTRUE)) return -1;
+ m.fDerLoc[i][kX] = fDerivativeLoc[i][0];
+ m.fDerLoc[i][kZ] = fDerivativeLoc[i][2];
+ if (zeroX) zeroX = IsZero(fDerivativeLoc[i][0]);
+ if (zeroZ) zeroZ = IsZero(fDerivativeLoc[i][2]);
+ }
+ // for (Int_t i=0; i<fNLocal; i++) AliDebug(2,Form("Local parameter %d - dXdpar = %g - dZdpar = %g\n",i,dXdL[i],dZdL[i]));
+ //
+ if (zeroX) {AliInfo("Skipping: zero local X derivatives!"); return -1;}
+ if (zeroZ) {AliInfo("Skipping: zero local Z derivatives!"); return -1;}
+ //
+ int ifill = 0;
+ //
+ AliITSAlignMille2Module* endModule = fCurrentModule;
+ //
+ zeroX = zeroZ = kTRUE;
+ Bool_t dfDone[kNParCh];
+ for (int i=kNParCh;i--;) dfDone[i] = kFALSE;
+ m.fNModFilled = 0;
+ //
+ // special block for SDD derivatives
+ Double_t jacobian[kNParChGeom];
+ Int_t nmodTested = 0;
+ //
+ do {
+ if (fCurrentModule->GetNParFree()==0) continue;
+ nmodTested++;
+ for (Int_t i=0; i<kNParChGeom; i++) { // common for all sensors: derivatives over geom params
+ //
+ if (!fUseGlobalDelta) dfDone[i] = kFALSE; // for global deltas the derivatives at diff. levels are different
+ if (fCurrentModule->GetParOffset(i)<0) continue; // this parameter is not explicitly fitted
+ if (!dfDone[i]) {
+ if (CalcDerivatives(i,kFALSE)) return -1;
+ else {
+ dfDone[i] = kTRUE;
+ if (zeroX) zeroX = IsZero(fDerivativeGlo[i][0]);
+ if (zeroZ) zeroZ = IsZero(fDerivativeGlo[i][2]);
+ }
+ }
+ //
+ m.fDerGlo[ifill][kX] = fDerivativeGlo[i][0];
+ m.fDerGlo[ifill][kZ] = fDerivativeGlo[i][2];
+ m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(i);
+ }
+ //
+ // specific for special sensors
+ if ( fCurrentModule->IsSDD() &&
+ (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0)>=0 ||
+ fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV)>=0) ) {
+ //
+ // assume for sensor local xloc = xloc0 + V0*dT0+dV*(T-T0)
+ // where V0 and T are the nominal drift velocity, time and time0
+ // and the dT0 and dV are the corrections:
+ // dX/dT0 = dX/dxloc * dxloc/dT0 = dX/dxloc * V0
+ // dX/dV = dX/dxloc * dxloc/dV = dX/dxloc * (T-T0)
+ // IMPORTANT: the geom derivatives are over the SENSOR LOCAL parameters
+ //
+ if (!dfDone[AliITSAlignMille2Module::kDOFT0] || !dfDone[AliITSAlignMille2Module::kDOFDV]) {
+ //
+ double dXdxlocsens=0., dZdxlocsens=0.;
+ //
+ // if the current module is the sensor itself and we work with local params, then
+ // we can directly take dX/dxloc_sens dZ/dxloc_sens
+ if (!fUseGlobalDelta && fCurrentModule->GetVolumeID()==fCluster.GetVolumeID()) {
+ if (!dfDone[AliITSAlignMille2Module::kDOFTX]) {
+ CalcDerivatives(AliITSAlignMille2Module::kDOFTX,kFALSE);
+ dfDone[AliITSAlignMille2Module::kDOFTX] = kTRUE;
+ }
+ dXdxlocsens = fDerivativeGlo[AliITSAlignMille2Module::kDOFTX][0];
+ dZdxlocsens = fDerivativeGlo[AliITSAlignMille2Module::kDOFTX][2];
+ }
+ //
+ else { // need to perform some transformations
+ // fetch the jacobian of the transformation from the sensors local frame to the frame
+ // where the parameters are defined:
+ // Global: dX/dxloc_sens = dX/dxgl*dxgl/dxloc_sens + ...dX/dphigl*dphigl/dxloc_sens
+ if (fUseGlobalDelta) fCurrentModule->CalcDerivGloLoc(fCluster.GetVolumeID(),
+ AliITSAlignMille2Module::kDOFTX, jacobian);
+ // Local: dX/dxloc_sens = dX/dxcurr*dxcurr/dxloc_sens +..+dX/dphicurr * dphicurr/dxloc_sens
+ else fCurrentModule->CalcDerivCurLoc(fCluster.GetVolumeID(),
+ AliITSAlignMille2Module::kDOFTX, jacobian);
+ //
+ for (int j=0;j<kNParChGeom;j++) {
+ // need global derivative even if the j-th param is locked
+ if (!dfDone[j]) {CalcDerivatives(j,kFALSE); dfDone[j] = kTRUE;}
+ dXdxlocsens += fDerivativeGlo[j][0] * jacobian[j];
+ dZdxlocsens += fDerivativeGlo[j][2] * jacobian[j];
+ }
+ }
+ //
+ if (zeroX) zeroX = IsZero(dXdxlocsens);
+ if (zeroZ) zeroZ = IsZero(dZdxlocsens);
+ //
+ double vdrift = GetVDriftSDD();
+ double tdrift = GetTDriftSDD();
+ //
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][0] = dXdxlocsens*vdrift;
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][2] = dZdxlocsens*vdrift;
+ dfDone[AliITSAlignMille2Module::kDOFT0] = kTRUE;
+ //
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][0] = -dXdxlocsens*TMath::Sign(tdrift,vdrift);
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][2] = -dZdxlocsens*TMath::Sign(tdrift,vdrift);
+ dfDone[AliITSAlignMille2Module::kDOFDV] = kTRUE;
+ //
+ }
+ //
+ if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0)>=0) {
+ m.fDerGlo[ifill][kX] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][0];
+ m.fDerGlo[ifill][kZ] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][2];
+ m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0);
+ }
+ //
+ if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV)>=0) {
+ m.fDerGlo[ifill][kX] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][0];
+ m.fDerGlo[ifill][kZ] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][2];
+ m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV);
+ }
+ }
+ //
+ m.fModuleID[m.fNModFilled++] = fCurrentModule->GetUniqueID();
+ } while( (fCurrentModule=fCurrentModule->GetParent()) );
+ //
+ if (nmodTested>0 && zeroX) {AliInfo("Skipping: zero global X derivatives!");return -1;}
+ if (nmodTested>0 && zeroZ) {AliInfo("Skipping: zero global Z derivatives!");return -1;}
+ //
+ // ok, can copy to m
+ AliDebug(2,Form("Adding local equation X with fMeas=%.6f and fSigma=%.6f",(fMeasLoc[0]-fPintLoc0[0]), fSigmaLoc[0]));
+ m.fMeas[kX] = fMeasLoc[0]-fPintLoc0[0];
+ m.fSigma[kX] = fSigmaLoc[0];
+ //
+ AliDebug(2,Form("Adding local equation Z with fMeas=%.6f and fSigma=%.6f",(fMeasLoc[2]-fPintLoc0[2]), fSigmaLoc[2]));
+ m.fMeas[kZ] = fMeasLoc[2]-fPintLoc0[2];
+ m.fSigma[kZ] = fSigmaLoc[2];
+ //
+ m.fNGlobFilled = ifill;
+ fCurrentModule = endModule;
+ //
+ return Int_t(!zeroX && !zeroZ);
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::AddLocalEquationTPA(Mille2Data &m)
+{
+ /// Define local equation for current cluster in X Y and Z coor.
+ /// and store them to memory
+ /// return -1 in case of failure to build some equation
+ /// 0 if no free global parameters were found but local eq is built
+ /// 1 if both local and global eqs are built
+ //
+ int curpoint = fCluster.GetUniqueID()-1;
+ TGeoHMatrix *tempHMat = GetSensorCurrMatrixSID(fCurrentSensID);// fCurrentModule->GetSensitiveVolumeMatrix(fCluster.GetVolumeID());
+ //
+ fTPAFitter->GetDResDParams(&fDerivativeLoc[0][0], curpoint); // resid. derivatives over the track parameters
+ for (Int_t i=fNLocal; i--;) tempHMat->MasterToLocalVect(fDerivativeLoc[i],m.fDerLoc[i]);
+ //
+ // derivatives over the global parameters ---------------------------------------->>>
+ Double_t dRdP[3][3]; // derivative of local residuals vs local position
+ Double_t dPdG[AliITSAlignMille2Module::kMaxParGeom][3]; // derivatives of local position vs global params
+ fTPAFitter->GetDResDPos(&fDerivativeGlo[0][0], curpoint);
+ for (int i=3;i--;) tempHMat->MasterToLocalVect(fDerivativeGlo[i],dRdP[i]);
+ //
+ UInt_t ifill=0, dfDone = 0;
+ m.fNModFilled = 0;
+ //
+ AliITSAlignMille2Module* endModule = fCurrentModule;
+ //
+ do {
+ if (fCurrentModule->GetNParFree()==0) continue;
+ if (!fUseGlobalDelta) dfDone = 0; // for local deltas the derivatives at diff. levels are different
+ Bool_t jacobOK = kFALSE;
+ //
+ for (Int_t i=0; i<kNParChGeom; i++) { // common for all sensors: derivatives over geom params
+ if (fCurrentModule->GetParOffset(i)<0) continue; // this parameter is not explicitly fitted
+ //
+ if (!TestWordBit(dfDone,i)) { // need to calculate new derivative
+ if (!jacobOK) {fCurrentModule->CalcDerivDPosDPar(fCluster.GetVolumeID(),fMeasLoc,&dPdG[0][0]); jacobOK = kTRUE;}
+ // dRes_j/dGlo_i = \sum_{k=1:3} dRes_j/dPos_k * dPos_k/dGlo_i
+ fDerivativeGlo[i][kX] = dRdP[kX][kX]*dPdG[i][kX] + dRdP[kY][kX]*dPdG[i][kY] + dRdP[kZ][kX]*dPdG[i][kZ];
+ fDerivativeGlo[i][kY] = dRdP[kX][kY]*dPdG[i][kX] + dRdP[kY][kY]*dPdG[i][kY] + dRdP[kZ][kY]*dPdG[i][kZ];
+ fDerivativeGlo[i][kZ] = dRdP[kX][kZ]*dPdG[i][kX] + dRdP[kY][kZ]*dPdG[i][kY] + dRdP[kZ][kZ]*dPdG[i][kZ];
+ SetWordBit(dfDone,i);
+ }
+ //
+ m.fDerGlo[ifill][kX] = fDerivativeGlo[i][kX];
+ m.fDerGlo[ifill][kY] = fDerivativeGlo[i][kY];
+ m.fDerGlo[ifill][kZ] = fDerivativeGlo[i][kZ];
+ m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(i);
+ //
+ }
+ //
+ if ( fCurrentModule->IsSDD() ) { // specific for SDD
+ //
+ // assume for sensor local xloc = xloc0 + V0*dT0+dV*(T-T0)
+ // where V0 and T are the nominal drift velocity, time and time0
+ // and the dT0 and dV are the corrections:
+ // dX/dT0 = dX/dxloc * dxloc/dT0 = dX/dxloc * V0
+ // dX/dV = dX/dxloc * dxloc/dV = dX/dxloc * (T-T0)
+ // IMPORTANT: the geom derivatives are over the SENSOR LOCAL parameters
+ //
+ if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0)>=0) {
+ if (!TestWordBit(dfDone, AliITSAlignMille2Module::kDOFT0)) {
+ double vdrift = GetVDriftSDD();
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][kX] = -dRdP[kX][kX]*vdrift;
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][kY] = -dRdP[kX][kY]*vdrift;
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][kZ] = -dRdP[kX][kZ]*vdrift;
+ SetWordBit(dfDone, AliITSAlignMille2Module::kDOFT0);
+ }
+ m.fDerGlo[ifill][kX] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][kX];
+ m.fDerGlo[ifill][kY] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][kY];
+ m.fDerGlo[ifill][kZ] = fDerivativeGlo[AliITSAlignMille2Module::kDOFT0][kZ];
+ m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFT0);
+ }
+ //
+ if (fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV)>=0) {
+ if (!TestWordBit(dfDone, AliITSAlignMille2Module::kDOFDV)) {
+ double tdrift = TMath::Sign(GetTDriftSDD(), GetVDriftSDD());
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][kX] = dRdP[kX][kX]*tdrift;
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][kY] = dRdP[kX][kY]*tdrift;
+ fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][kZ] = dRdP[kX][kZ]*tdrift;
+ SetWordBit(dfDone, AliITSAlignMille2Module::kDOFDV);
+ }
+ m.fDerGlo[ifill][kX] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][kX];
+ m.fDerGlo[ifill][kY] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][kY];
+ m.fDerGlo[ifill][kZ] = fDerivativeGlo[AliITSAlignMille2Module::kDOFDV][kZ];
+ m.fParMilleID[ifill++] = fCurrentModule->GetParOffset(AliITSAlignMille2Module::kDOFDV);
+ }
+ }
+ //
+ m.fModuleID[m.fNModFilled++] = fCurrentModule->GetUniqueID();
+ } while( (fCurrentModule=fCurrentModule->GetParent()) );
+ //
+ // store first local residuals
+ fTPAFitter->GetResiduals(fPintLoc , curpoint); // lab residuals
+ for (int i=3;i--;) fPintLoc[i] = -fPintLoc[i];
+ tempHMat->MasterToLocalVect(fPintLoc,m.fMeas); // local residuals
+ m.fSigma[kX] = fSigmaLoc[kX];
+ m.fSigma[kY] = fSigmaLoc[kY];
+ m.fSigma[kZ] = fSigmaLoc[kZ];
+ //
+ m.fNGlobFilled = ifill;
+ fCurrentModule = endModule;
+ //
+ return 1;
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::SetLocalEquations(const Mille2Data *marr, Int_t neq)
+{
+ /// Set local equations with data stored in m
+ /// return 0 if success
+ //
+ for (Int_t j=0; j<neq; j++) {
+ //
+ const Mille2Data &m = marr[j];
+ //
+ Bool_t filled = kFALSE;
+ for (int ic=3;ic--;) {
+ if (ic==kY && !fUseLocalYErr) continue;
+ AliDebug(2,Form("setting local equation %c with fMeas=%.6f and fSigma=%.6f",fgkXYZ[ic],m.fMeas[ic], m.fSigma[ic]));
+ Bool_t zero = kTRUE;
+ for (int i=fNLocal; i--;) zero &= SetLocalDerivative( i, m.fDerLoc[i][ic] );
+ for (int i=m.fNGlobFilled;i--;) zero &= SetGlobalDerivative( m.fParMilleID[i] , m.fDerGlo[i][ic] );
+ if (zero) { AliInfo(Form("Skipping %c residual due to the zero derivatives!",fgkXYZ[ic])); continue; }
+ fMillepede->SetLocalEquation(fGlobalDerivatives, fLocalDerivatives, m.fMeas[ic], m.fSigma[ic]);
+ filled = kTRUE;
+ //
+ }
+ //
+ if (filled) for (int i=m.fNModFilled;i--;) GetMilleModule(m.fModuleID[i])->IncNProcessedPoints();
+ }
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::GlobalFit()
+{
+ /// Call global fit; Global parameters are stored in parameters
+ if (!fIsMilleInit) Init();
+ //
+ ApplyPreConstraints();
+ int res = fMillepede->GlobalFit();
+ AliInfo(Form("%s fitting global parameters!",res ? "Done":"Failed"));
+ if (res) {
+ // fetch the parameters
+ for (int imd=fNModules;imd--;) {
+ AliITSAlignMille2Module* mod = GetMilleModule(imd);
+ int nprocp = 0;
+ for (int ip=mod->GetNParTot();ip--;) {
+ int idp = mod->GetParOffset(ip);
+ if (idp<0) continue; // was not in the explicit fit
+ mod->SetParVal(ip,fMillepede->GetFinalParam(idp));
+ mod->SetParErr(ip,fMillepede->GetFinalError(idp));
+ int np = fMillepede->GetProcessedPoints(idp);
+ if (TMath::Abs(np)>TMath::Abs(nprocp)) nprocp = np;
+ }
+ if (!mod->GetNProcessedPoints()) mod->SetNProcessedPoints(nprocp);
+ }
+
+ }
+ ApplyPostConstraints();
+ return res;
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::PrintGlobalParameters()
+{
+ /// Print global parameters
+ if (!fIsMilleInit) {
+ AliInfo("Millepede has not been initialized!");
+ return;
+ }
+ fMillepede->PrintGlobalParameters();
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::LoadSuperModuleFile(const Char_t *sfile)
+{
+ // load definitions of supermodules from a root file
+ // return 0 if success
+
+ TFile *smf=TFile::Open(sfile);
+ if (!smf->IsOpen()) {
+ AliInfo(Form("Cannot open supermodule file %s",sfile));
+ return -1;
+ }
+
+ TClonesArray *sma=(TClonesArray*)smf->Get("ITSMilleSuperModules");
+ if (!sma) {
+ AliInfo(Form("Cannot find ITSMilleSuperModules array in file"));
+ return -2;
+ }
+ Int_t nsma=sma->GetEntriesFast();
+ AliInfo(Form("Array of SuperModules with %d entries\n",nsma));
+ //
+ // pepo200709
+ Char_t st[2048];
+ char symname[250];
+ // end pepo200709
+
+ UShort_t volid;
+ TGeoHMatrix m;
+ //
+ for (Int_t i=0; i<nsma; i++) {
+ AliAlignObjParams *a = (AliAlignObjParams*)sma->UncheckedAt(i);
+ volid=a->GetVolUID();
+ strcpy(st,a->GetSymName());
+ a->GetMatrix(m);
+ //
+ sscanf(st,"%s",symname);
+ //
+ // decode module list
+ char *stp=strstr(st,"ModuleList:");
+ if (!stp) return -3;
+ stp += 11;
+ int idx[2200];
+ char spp[200]; int jp=0;
+ char cl[20];
+ strcpy(st,stp);
+ int l=strlen(st);
+ int j=0;
+ int n=0;
+ //
+ while (j<=l) {
+ if (st[j]==9 || st[j]==32 || st[j]==10 || st[j]==0) {
+ spp[jp]=0;
+ jp=0;
+ if (strlen(spp)) {
+ int k=strcspn(spp,"-");
+ if (k<int(strlen(spp))) { // c'e' il -
+ strcpy(cl,&(spp[k+1]));
+ spp[k]=0;
+ int ifrom=atoi(spp); int ito=atoi(cl);
+ for (int b=ifrom; b<=ito; b++) {
+ idx[n]=b;
+ n++;
+ }
+ }
+ else { // numerillo singolo
+ idx[n]=atoi(spp);
+ n++;
+ }
+ }
+ }
+ else {
+ spp[jp]=st[j];
+ jp++;
+ }
+ j++;
+ }
+ UShort_t volidsv[2198];
+ for (j=0;j<n;j++) {
+ volidsv[j]=AliITSAlignMille2Module::GetVolumeIDFromIndex(idx[j]);
+ if (!volidsv[j]) {
+ AliInfo(Form("Index %d not valid (range 0->%d)",idx[j],kMaxITSSensID));
+ return -5;
+ }
+ }
+ Int_t smindex=int(2198+volid-14336); // virtual index
+ //
+ fSuperModule.AddAtAndExpand(new AliITSAlignMille2Module(smindex,volid,symname,&m,n,volidsv),fNSuperModules);
+ //
+ fNSuperModules++;
+ }
+ //
+ smf->Close();
+ //
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConstrainModuleSubUnitsMean(Int_t idm, Double_t val, UInt_t pattern)
+{
+ // require that sum of modifications for the childs of this module is = val, i.e.
+ // the internal corrections moves the module as a whole by fixed value (0 by default).
+ // pattern is the bit pattern for the parameters to constrain
+ //
+ if (fIsMilleInit) {
+ AliInfo("Millepede has been already initialized: no constrain may be added!");
+ return;
+ }
+ if (!GetMilleModule(idm)->GetNChildren()) return;
+ TString nm = "cstrSUMean";
+ nm += GetNConstraints();
+ AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMean,
+ idm,val,pattern);
+ cstr->SetConstraintID(GetNConstraints());
+ fConstraints.Add(cstr);
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConstrainModuleSubUnitsMedian(Int_t idm, Double_t val, UInt_t pattern)
+{
+ // require that median of the modifications for the childs of this module is = val, i.e.
+ // the internal corrections moves the module as a whole by fixed value (0 by default)
+ // module the outliers.
+ // pattern is the bit pattern for the parameters to constrain
+ // The difference between the mean and the median will be transfered to the parent
+ if (fIsMilleInit) {
+ AliInfo("Millepede has been already initialized: no constrain may be added!");
+ return;
+ }
+ if (!GetMilleModule(idm)->GetNChildren()) return;
+ TString nm = "cstrSUMed";
+ nm += GetNConstraints();
+ AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMedian,
+ idm,val,pattern);
+ cstr->SetConstraintID(GetNConstraints());
+ fConstraints.Add(cstr);
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConstrainOrphansMean(Double_t val, UInt_t pattern)
+{
+ // require that median of the modifications for the supermodules which have no parents is = val, i.e.
+ // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.
+ // pattern is the bit pattern for the parameters to constrain
+ //
+ if (fIsMilleInit) {
+ AliInfo("Millepede has been already initialized: no constrain may be added!");
+ return;
+ }
+ TString nm = "cstrOMean";
+ nm += GetNConstraints();
+ AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMean,
+ -1,val,pattern);
+ cstr->SetConstraintID(GetNConstraints());
+ fConstraints.Add(cstr);
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConstrainOrphansMedian(Double_t val, UInt_t pattern)
+{
+ // require that median of the modifications for the supermodules which have no parents is = val, i.e.
+ // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.
+ // pattern is the bit pattern for the parameters to constrain
+ //
+ if (fIsMilleInit) {
+ AliInfo("Millepede has been already initialized: no constrain may be added!");
+ return;
+ }
+ TString nm = "cstrOMed";
+ nm += GetNConstraints();
+ AliITSAlignMille2Constraint *cstr = new AliITSAlignMille2Constraint(nm.Data(),AliITSAlignMille2Constraint::kTypeMedian,
+ -1,val,pattern);
+ cstr->SetConstraintID(GetNConstraints());
+ fConstraints.Add(cstr);
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConstrainLocal(const Char_t* name,Double_t *parcf,Int_t npar,Double_t val,Double_t err)
+{
+ // apply constraint on parameters in the local frame
+ if (fIsMilleInit) {
+ AliInfo("Millepede has been already initialized: no constrain may be added!");
+ return;
+ }
+ AliITSAlignMille2ConstrArray *cstr = new AliITSAlignMille2ConstrArray(name,parcf,npar,val,err);
+ cstr->SetConstraintID(GetNConstraints());
+ fConstraints.Add(cstr);
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ApplyGaussianConstraint(const AliITSAlignMille2ConstrArray* cstr)
+{
+ // apply the constraint on the local corrections of a list of modules
+ int nmod = cstr->GetNModules();
+ double jacobian[AliITSAlignMille2Module::kMaxParGeom][AliITSAlignMille2Module::kMaxParGeom];
+ //
+ for (int imd=nmod;imd--;) {
+ int modID = cstr->GetModuleID(imd);
+ AliITSAlignMille2Module* mod = GetMilleModule(modID);
+ ResetLocalEquation();
+ int nadded = 0;
+ double value = cstr->GetValue();
+ double sigma = cstr->GetError();
+ //
+ // in case the reference (survey) deltas were imposed for Gaussian constraints
+ // already accumulated corrections: they must be subtracted from the constraint value.
+ if (IsConstraintWrtRef()) {
+ //
+ Double_t precal[AliITSAlignMille2Module::kMaxParTot];
+ Double_t refcal[AliITSAlignMille2Module::kMaxParTot];
+ for (int ip=AliITSAlignMille2Module::kMaxParTot;ip--;) {precal[ip]=0; refcal[ip] = 0.;}
+ //
+ // check if there was a reference delta provided for this module
+ AliAlignObjParams* parref = GetConstrRefObject(mod->GetName());
+ if (parref) parref->GetPars(refcal, refcal+3); // found reference delta
+ //
+ // extract already applied local corrections for this module
+ if (fPrealignment) {
+ //
+ AliAlignObjParams *preo = GetPrealignedObject(mod->GetName());
+ if (preo) {
+ TGeoHMatrix preMat,tmpMat = *mod->GetMatrix(); // Delta_Glob * Delta_Glob_Par * M
+ preo->GetMatrix(preMat); // Delta_Glob
+ preMat.MultiplyLeft( &tmpMat.Inverse() ); // M^-1 * Delta_Glob_Par^-1 = (Delta_Glob_Par * M)^-1
+ tmpMat.MultiplyLeft( &preMat ); // (Delta_Glob_Par * M)^-1 * Delta_Glob * Delta_Glob_Par * M = Delta_loc
+ AliAlignObjParams algob;
+ algob.SetMatrix(tmpMat);
+ algob.GetPars(precal,precal+3); // local corrections for geometry
+ }
+ }
+ //
+ // subtract the contribution to constraint from precalibration
+ for (int ipar=cstr->GetNCoeffs();ipar--;) value += (refcal[ipar]-precal[ipar])*cstr->GetCoeff(ipar);
+ //
+ }
+ //
+ if (fUseGlobalDelta) mod->CalcDerivLocGlo(&jacobian[0][0]);
+ //
+ for (int ipar=cstr->GetNCoeffs();ipar--;) {
+ double coef = cstr->GetCoeff(ipar);
+ if (IsZero(coef)) continue;
+ //
+ if (!fUseGlobalDelta || ipar>= AliITSAlignMille2Module::kMaxParGeom) { //
+ // we are working with local params or if the given param is not related to geometry,
+ // apply the constraint directly
+ int parPos = mod->GetParOffset(ipar);
+ if (parPos<0) continue; // not in the fit
+ fGlobalDerivatives[parPos] += coef;
+ nadded++;
+ }
+ else { // we are working with global params, while the constraint is on local ones -> jacobian
+ for (int jpar=AliITSAlignMille2Module::kMaxParGeom;jpar--;) {
+ int parPos = mod->GetParOffset(jpar);
+ if (parPos<0) continue;
+ fGlobalDerivatives[parPos] += coef*jacobian[ipar][jpar];
+ nadded++;
+ }
+ }
+ }
+ if (nadded) AddConstraint(fGlobalDerivatives, value, sigma);
+ }
+ //
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ApplyPreConstraints()
+{
+ // apply constriants which cannot be imposed after the fit
+ int nconstr = GetNConstraints();
+ for (int i=0;i<nconstr;i++) {
+ AliITSAlignMille2Constraint* cstr = GetConstraint(i);
+ //
+ if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) {
+ ApplyGaussianConstraint( (AliITSAlignMille2ConstrArray*)cstr);
+ continue;
+ }
+ //
+ if (cstr->GetType() == AliITSAlignMille2Constraint::kTypeMedian) continue; // post type constraint
+ //
+ if (!fUseGlobalDelta) continue; // mean/med constraints must be applied to global deltas
+ // apply constraint on the mean's before the fit
+ int imd = cstr->GetModuleID();
+ if (imd>=0) {
+ AliITSAlignMille2Module* mod = GetMilleModule(imd);
+ UInt_t pattern = 0;
+ for (int ipar=mod->GetNParTot();ipar--;) {
+ if (!cstr->IncludesParam(ipar)) continue;
+ if (mod->GetParOffset(ipar)<0) continue; // parameter is not in the explicit fit -> post constraint
+ pattern |= 0x1<<ipar;
+ cstr->SetApplied(ipar);
+ }
+ ConstrainModuleSubUnits(imd,cstr->GetValue(),pattern);
+ //
+ }
+ else if (!PseudoParentsAllowed()) {
+ ConstrainOrphans(cstr->GetValue(),(UInt_t)cstr->GetPattern());
+ cstr->SetApplied(-1);
+ }
+ }
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ApplyPostConstraints()
+{
+ // apply constraints which can be imposed after the fit
+ int nconstr = GetNConstraints();
+ Bool_t convGlo = kFALSE;
+ // check if there is something to do
+ int ntodo = 0;
+ for (int i=0;i<nconstr;i++) {
+ AliITSAlignMille2Constraint* cstr = GetConstraint(i);
+ if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) continue;
+ if (cstr->GetRemainingPattern() == 0) continue;
+ ntodo++;
+ }
+ if (!ntodo) return;
+ //
+ if (!fUseGlobalDelta) { // need to convert to global params
+ ConvertParamsToGlobal();
+ convGlo = kTRUE;
+ }
+ //
+ for (int i=0;i<nconstr;i++) {
+ AliITSAlignMille2Constraint* cstr = GetConstraint(i);
+ if (cstr->GetType() == AliITSAlignMille2ConstrArray::kTypeGaussian) continue;
+ //
+ int imd = cstr->GetModuleID();
+ //
+ if (imd>=0) {
+ AliITSAlignMille2Module* mod = GetMilleModule(imd);
+ UInt_t pattern = 0;
+ for (int ipar=mod->GetNParTot();ipar--;) {
+ if (cstr->IsApplied(ipar)) continue;
+ if (!cstr->IncludesParam(ipar)) continue;
+ if (!mod->IsFreeDOF(ipar)) continue; // parameter is fixed, will not apply constraint
+ pattern |= 0x1<<ipar;
+ cstr->SetApplied(ipar);
+ }
+ if (pattern) PostConstrainModuleSubUnits(cstr->GetType(),cstr->GetModuleID(),cstr->GetValue(),pattern);
+ //
+ }
+ else if (PseudoParentsAllowed()) {
+ UInt_t pattern = (UInt_t)cstr->GetRemainingPattern();
+ PostConstrainOrphans(cstr->GetType(),cstr->GetValue(),pattern);
+ cstr->SetApplied(-1);
+ }
+ }
+ // if there was a conversion, rewind it
+ if (convGlo) ConvertParamsToLocal();
+ //
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConstrainModuleSubUnits(Int_t idm, Double_t val, UInt_t pattern)
+{
+ // require that sum of modifications for the childs of this module is = val, i.e.
+ // the internal corrections moves the module as a whole by fixed value (0 by default).
+ // pattern is the bit pattern for the parameters to constrain
+ //
+ //
+ AliITSAlignMille2Module* mod = GetMilleModule(idm);
+ //
+ for (int ip=0;ip<kNParCh;ip++) {
+ if ( !((pattern>>ip)&0x1) /*|| !parent->IsFreeDOF(ip)*/) continue;
+ ResetLocalEquation();
+ int nadd = 0;
+ for (int ich=mod->GetNChildren();ich--;) {
+ int idpar = ((AliITSAlignMille2Module*)mod->GetChild(ich))->GetParOffset(ip);
+ if (idpar<0) continue;
+ fGlobalDerivatives[idpar] = 1.0;
+ nadd++;
+ }
+ //
+ if (nadd>0) {
+ AddConstraint(fGlobalDerivatives,val);
+ AliInfo(Form("Constrained param %d for %d submodules of module #%d: %s",ip,nadd,idm,mod->GetName()));
+ }
+ }
+ //
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConstrainOrphans(Double_t val, UInt_t pattern)
+{
+ // require that median of the modifications for the supermodules which have no parents is = val, i.e.
+ // the corrections moves the whole setup by fixed value (0 by default) modulo the outliers.
+ // pattern is the bit pattern for the parameters to constrain
+ //
+ for (int ip=0;ip<kNParCh;ip++) {
+ //
+ if ( !((pattern>>ip)&0x1) ) continue;
+ ResetLocalEquation();
+ int nadd = 0;
+ for (int imd=fNModules;imd--;) {
+ AliITSAlignMille2Module* mod = GetMilleModule(imd);
+ if (mod->GetParent()) continue; // this is not an orphan
+ int idpar = mod->GetParOffset(ip);
+ if (idpar<0) continue;
+ fGlobalDerivatives[idpar] = 1.0;
+ nadd++;
+ }
+ if (nadd>0) {
+ AddConstraint(fGlobalDerivatives,val);
+ AliInfo(Form("Constrained param %d for %d orphan modules",ip,nadd));
+ }
+ }
+ //
+ //
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::PostConstrainModuleSubUnits(Int_t type,Int_t idm, Double_t val, UInt_t pattern)
+{
+ // require that median or mean of the modifications for the childs of this module is = val, i.e.
+ // the internal corrections moves the module as a whole by fixed value (0 by default)
+ // module the outliers.
+ // pattern is the bit pattern for the parameters to constrain
+ // The difference between the mean and the median will be transfered to the parent
+ //
+ AliITSAlignMille2Module* parent = GetMilleModule(idm);
+ int nc = parent->GetNChildren();
+ //
+ double *tmpArr = new double[nc];
+ //
+ for (int ip=0;ip<kNParCh;ip++) {
+ int npc = 0;
+ if ( !((pattern>>ip)&0x1) || !parent->IsFreeDOF(ip)) continue;
+ // compute the mean and median of the deltas
+ int nfree = 0;
+ for (int ich=nc;ich--;) {
+ AliITSAlignMille2Module* child = parent->GetChild(ich);
+ // if (!child->IsFreeDOF(ip)) continue;
+ tmpArr[nfree++] = child->GetParVal(ip);
+ }
+ double median=0,mean=0;
+ for (int ic0=0;ic0<nfree;ic0++) {// order the deltas
+ mean += tmpArr[ic0];
+ for (int ic1=ic0+1;ic1<nfree;ic1++)
+ if (tmpArr[ic0]>tmpArr[ic1]) {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;}
+ }
+ //
+ int kmed = nfree/2;
+ median = (tmpArr[kmed]+tmpArr[nfree-kmed-1])/2.;
+ if (nfree>0) mean /= nfree;
+ //
+ double shift = val - (type==AliITSAlignMille2Constraint::kTypeMean ? mean : median);
+ //
+ for (int ich=nc;ich--;) {
+ AliITSAlignMille2Module* child = parent->GetChild(ich);
+ // if (!child->IsFreeDOF(ip)) continue;
+ child->SetParVal(ip, child->GetParVal(ip) + shift);
+ npc++;
+ }
+ //
+ parent->SetParVal(ip, parent->GetParVal(ip) - shift);
+ AliInfo(Form("%s constraint: added %f shift to param[%d] of %d children of module %d: %s",
+ type==AliITSAlignMille2Constraint::kTypeMean ? "MEAN" : "MEDIAN",shift,
+ ip,npc,idm,parent->GetName()));
+ }
+ delete[] tmpArr;
+ //
+ //
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::PostConstrainOrphans(Int_t type,Double_t val, UInt_t pattern)
+{
+ // require that median or mean of modifications for the supermodules which have no parents is = val, i.e.
+ // the corrections moves the whole setup by fixed value (0 by default).
+ // pattern is the bit pattern for the parameters to constrain
+ //
+ int nc = fNModules;
+ //
+ int norph = 0;
+ for (int ich=nc;ich--;) if (!GetMilleModule(ich)->GetParent()) norph ++;
+ if (!norph) return;
+ double *tmpArr = new double[norph];
+ //
+ for (int ip=0;ip<kNParCh;ip++) {
+ int npc = 0;
+ if ( !((pattern>>ip)&0x1)) continue;
+ // compute the mean and median of the deltas
+ int nfree = 0;
+ for (int ich=nc;ich--;) {
+ AliITSAlignMille2Module* child = GetMilleModule(ich);
+ // if (child->GetParent() || !child->IsFreeDOF(ip)) continue;
+ if (child->GetParent()) continue;
+ tmpArr[nfree++] = child->GetParVal(ip);
+ }
+ double median=0,mean=0;
+ for (int ic0=0;ic0<nfree;ic0++) {// order the deltas
+ mean += tmpArr[ic0];
+ for (int ic1=ic0+1;ic1<nfree;ic1++)
+ if (tmpArr[ic0]>tmpArr[ic1]) {double tv=tmpArr[ic0]; tmpArr[ic0]=tmpArr[ic1]; tmpArr[ic1]=tv;}
+ }
+ //
+ int kmed = nfree/2;
+ median = (tmpArr[kmed]+tmpArr[nfree-kmed-1])/2.;
+ if (nfree>0) mean /= nfree;
+ //
+ double shift = val - (type==AliITSAlignMille2Constraint::kTypeMean ? mean : median);
+ //
+ for (int ich=nc;ich--;) {
+ AliITSAlignMille2Module* child = GetMilleModule(ich);
+ // if (child->GetParent() || !child->IsFreeDOF(ip)) continue;
+ if (child->GetParent()) continue;
+ child->SetParVal(ip, child->GetParVal(ip) + shift);
+ npc++;
+ }
+ //
+ AliInfo(Form("%s constraint: added %f shift to param[%d] of %d orphan modules",
+ type==AliITSAlignMille2Constraint::kTypeMean ? "MEAN" : "MEDIAN",shift,
+ ip,npc));
+ }
+ delete[] tmpArr;
+ //
+}
+
+//________________________________________________________________________________________________________
+Bool_t AliITSAlignMille2::IsParModConstrained(const AliITSAlignMille2Module* mod,Int_t par, Bool_t &meanmed, Bool_t &gaussian) const
+{
+ // check if par of the module participates in some constraint, and set the flag for their types
+ meanmed = gaussian = kFALSE;
+ //
+ if ( mod->IsParConstrained(par) ) gaussian = kTRUE; // direct constraint on this param
+ //
+ for (int icstr=GetNConstraints();icstr--;) {
+ AliITSAlignMille2Constraint* cstr = GetConstraint(icstr);
+ //
+ if (!cstr->IncludesModPar(mod,par)) continue;
+ if (cstr->GetType()==AliITSAlignMille2ConstrArray::kTypeGaussian) gaussian = kTRUE;
+ else meanmed = kTRUE;
+ //
+ if (meanmed && gaussian) break; // no sense to check further
+ }
+ //
+ return meanmed||gaussian;
+}
+
+//________________________________________________________________________________________________________
+Bool_t AliITSAlignMille2::IsParModFamilyVaried(const AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const
+{
+ // check if parameter par is varied for this module or its children up to the level depth
+ if (depth<0) return kFALSE;
+ if (mod->GetParOffset(par)>=0) return kTRUE;
+ for (int icld=mod->GetNChildren();icld--;) {
+ AliITSAlignMille2Module* child = mod->GetChild(icld);
+ if (IsParModFamilyVaried(child, par, depth-1)) return kTRUE;
+ }
+ return kFALSE;
+ //
+}
+
+/*
+//________________________________________________________________________________________________________
+Bool_t AliITSAlignMille2::IsParFamilyFree(AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const
+{
+ // check if parameter par is varied and is not subjected to gaussian constraint for the children up to the level depth
+ if (depth<0) return kTRUE;
+ for (int icld=mod->GetNChildren();icld--;) {
+ AliITSAlignMille2Module* child = mod->GetChild(icld);
+ //if (child->GetParOffset(par)<0) continue; // fixed
+ Bool_t cstMM=kFALSE,cstGS=kFALSE;
+ // does this child have gaussian constraint ?
+ if (!IsParModConstrained(child,par,cstMM,cstGS) || !cstGS ) return kTRUE;
+ // check its children
+ if (!IsParFamilyFree(child,par,depth-1)) return kTRUE;
+ }
+ return kFALSE;
+ //
+}
+*/
+
+//________________________________________________________________________________________________________
+Bool_t AliITSAlignMille2::IsParFamilyFree(const AliITSAlignMille2Module* mod,Int_t par,Int_t depth) const
+{
+ // check if parameter par is varied and is not subjected to gaussian constraint for the children up to the level depth
+ if (depth<0) return kFALSE;
+ for (int icld=mod->GetNChildren();icld--;) {
+ AliITSAlignMille2Module* child = mod->GetChild(icld);
+ //if (child->GetParOffset(par)<0) continue; // fixed
+ Bool_t cstMM=kFALSE,cstGS=kFALSE;
+ // does this child have gaussian constraint ?
+ if (!IsParModConstrained(child,par,cstMM,cstGS) || !cstGS ) return kTRUE;
+ // check its children
+ if (IsParFamilyFree(child,par,depth-1)) return kTRUE;
+ }
+ return kFALSE;
+ //
+}
+
+//________________________________________________________________________________________________________
+Double_t AliITSAlignMille2::GetTDriftSDD() const
+{
+ // obtain drift time corrected for t0
+ double t = fCluster.GetDriftTime();
+ return t - fDriftTime0[ fCluster.GetUniqueID()-1 ];
+}
+
+//________________________________________________________________________________________________________
+Double_t AliITSAlignMille2::GetVDriftSDD() const
+{
+ // obtain corrected drift speed
+ return fDriftSpeed[ fCluster.GetUniqueID()-1 ];
+}
+
+//________________________________________________________________________________________________________
+Bool_t AliITSAlignMille2::FixedOrphans() const
+{
+ // are there fixed modules with no parent (normally in such a case
+ // the constraints on the orphans should not be applied
+ if (!IsConfigured()) {
+ AliInfo("Still not configured");
+ return kFALSE;
+ }
+ for (int i=0;i<fNModules;i++) {
+ AliITSAlignMille2Module* md = GetMilleModule(i);
+ if (md->GetParent()==0 && md->GetNParFree()==0) return kTRUE;
+ }
+ return kFALSE;
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConvertParamsToGlobal()
+{
+ // convert params in local frame to global one
+ double pars[AliITSAlignMille2Module::kMaxParGeom];
+ for (int imd=fNModules;imd--;) {
+ AliITSAlignMille2Module* mod = GetMilleModule(imd);
+ if (mod->GeomParamsGlobal()) continue;
+ mod->GetGeomParamsGlo(pars);
+ mod->SetParVals(pars,AliITSAlignMille2Module::kMaxParGeom);
+ mod->SetGeomParamsGlobal(kTRUE);
+ }
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConvertParamsToLocal()
+{
+ // convert params in global frame to local one
+ double pars[AliITSAlignMille2Module::kMaxParGeom];
+ for (int imd=fNModules;imd--;) {
+ AliITSAlignMille2Module* mod = GetMilleModule(imd);
+ if (!mod->GeomParamsGlobal()) continue;
+ mod->GetGeomParamsLoc(pars);
+ mod->SetParVals(pars,AliITSAlignMille2Module::kMaxParGeom);
+ mod->SetGeomParamsGlobal(kFALSE);
+ }
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::SetBField(Double_t b)
+{
+ // set Bz value
+ if (IsZero(b,1e-5)) {
+ fBField = 0.0;
+ fBOn = kFALSE;
+ fNLocal = 4;
+ }
+ else {
+ fBField = b;
+ fBOn = kTRUE;
+ fNLocal = 5; // helices
+ }
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::ProcessUserInfo(TList* userInfo)
+{
+ // extract calibration information used for TrackPointArray creation from run info
+ //
+ if (!userInfo) { AliInfo("No UserInfo is provided"); return 0;}
+ //
+ TMap *cdbMap=0;
+ TList* cdbList=0;
+ TObjString *objStr,*keyStr;
+ AliCDBManager* man = AliCDBManager::Instance();
+ //
+ int run = userInfo->GetUniqueID();
+ AliInfo(Form("UserInfo corresponds to run#%d",run));
+ cdbMap = (TMap*)userInfo->FindObject("cdbMap");
+ if (!cdbMap) {AliInfo("No CDB Map found in UserInfo");}
+ else {
+ if ((objStr=(TObjString*)cdbMap->GetValue("default"))) { // first set default CDB path
+ fDefCDBpath = objStr->GetString();
+ if (fDefCDBpath.BeginsWith("raw://")) fDefCDBpath = "raw://";
+ AliInfo(Form("Default CDB Storage from UserInfo: %s",fDefCDBpath.Data()));
+ }
+ man->SetDefaultStorage( fDefCDBpath.Data() ); // this may be overriden later by configuration file
+ man->SetRun(run);
+ //
+ // set specific paths relevant for alignment
+ TIter itMap(cdbMap);
+ while( (keyStr=(TObjString*)itMap.Next()) ) {
+ TString keyS = keyStr->GetString();
+ if ( keyS == "default" ) continue;
+ man->SetSpecificStorage( keyS.Data(), cdbMap->GetValue(keyS)->GetName() );
+ }
+ }
+ //
+ cdbList = (TList*)userInfo->FindObject("cdbList");
+ if (!cdbList) {AliInfo("No CDB List found in UserInfo");}
+ else {
+ // Deltas used for TrackPointArray production
+ TIter itList(cdbList);
+ while( (objStr=(TObjString*)itList.Next()) )
+ if (objStr->GetString().Contains("ITS/Align/Data")) {
+ fInitDeltaPath = objStr->GetString();
+ AliInfo(Form("Production Misalignment from UserInfo: %s",fInitDeltaPath.Data()));
+ break;
+ }
+ // SDD response (time0 and drift speed correction) used for TrackPointArray production
+ itList.Reset();
+ while( (objStr=(TObjString*)itList.Next()) )
+ if (objStr->GetString().Contains("ITS/Calib/RespSDD")) {
+ fInitSDDRespPath = objStr->GetString();
+ AliInfo(Form("Production SDD Response from UserInfo: %s",fInitSDDRespPath.Data()));
+ break;
+ }
+ //
+ }
+ //
+ objStr = (TObjString*)userInfo->FindObject("BzkGauss");
+ if (objStr) {
+ SetBField( objStr->GetString().Atof() );
+ AliInfo(Form("Magentic field from UserInfo: %+.2e",GetBField()));
+ }
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::LoadSDDResponse(TString& path, AliITSresponseSDD *&resp)
+{
+ if (path.IsNull()) return 0;
+ //
+ resp = 0;
+ while(1) {
+ if (path.BeginsWith("path: ")) { // must load from OCDB
+ AliCDBId* cdbId = AliCDBId::MakeFromString( path.Data() );
+ AliCDBEntry *entry = AliCDBManager::Instance()->Get( *cdbId );
+ delete cdbId;
+ if (!entry) break;
+ resp = (AliITSresponseSDD*) entry->GetObject();
+ entry->SetObject(NULL);
+ entry->SetOwner(kTRUE);
+ delete entry;
+ break;
+ }
+ //
+ if (gSystem->AccessPathName(path.Data())) break;
+ TFile* precf = TFile::Open(path.Data());
+ resp = (AliITSresponseSDD*)precf->Get("AliITSresponseSDD");
+ precf->Close();
+ delete precf;
+ break;
+ }
+ //
+ if (!resp) {AliError(Form("Failed to load SDD response from %s",path.Data())); return -1;}
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::LoadDeltas(TString& path, TClonesArray *&arr)
+{
+ if (path.IsNull()) return 0;
+ //
+ arr = 0;
+ while(1) {
+ if (path.BeginsWith("path: ")) { // must load from OCDB
+ AliCDBId *cdbId = AliCDBId::MakeFromString( path.Data() );
+ AliCDBEntry *entry = AliCDBManager::Instance()->Get( *cdbId );
+ delete cdbId;
+ if (!entry) break;
+ arr = (TClonesArray*) entry->GetObject();
+ entry->SetObject(NULL);
+ entry->SetOwner(kTRUE);
+ delete entry;
+ break;
+ }
+ //
+ if (gSystem->AccessPathName(path.Data())) break;
+ TFile* precf = TFile::Open(path.Data());
+ arr = (TClonesArray*)precf->Get("ITSAlignObjs");
+ precf->Close();
+ delete precf;
+ break;
+ }
+ //
+ if (!arr) {AliError(Form("Failed to load Deltas from %s",path.Data())); return -1;}
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+Int_t AliITSAlignMille2::CacheMatrices()
+{
+ // build arrays for the fast access to sensor matrices from their sensor ID
+ //
+ TGeoHMatrix mdel;
+ AliITSAlignMille2Module *mod = GetMilleModule(0); // does not matter which one...
+ AliInfo("Building sensors matrices cache");
+ //
+ fCacheMatrixOrig.Delete();
+ fCacheMatrixCurr.Delete();
+ // in case the reconstruction was done with non-ideal geometry, load relevant deltas
+ TClonesArray *initDeltas = 0;
+ if (!fInitDeltaPath.IsNull()) if (LoadDeltas(fInitDeltaPath,initDeltas)) return -1;
+ //
+ // 1) Original matrices (used to write the global coordinates of the points)
+ for (int idx=0;idx<=kMaxITSSensID;idx++) {
+ int volID = AliITSAlignMille2Module::GetVolumeIDFromIndex(idx);
+ TGeoHMatrix *morig = new TGeoHMatrix();
+ TGeoHMatrix *mcurr = new TGeoHMatrix();
+ *morig = *mod->GetSensitiveVolumeOrigGlobalMatrix(volID);
+ *mcurr = *mod->GetSensitiveVolumeMatrix(volID);
+ //
+ // the reconstruction might be done with particular deltas
+ if (initDeltas) for (int i=initDeltas->GetLast()+1;i--;) {
+ AliAlignObjParams *preo = (AliAlignObjParams*) initDeltas->At(i);
+ if (!preo || (preo->GetVolUID()!=volID)) continue;
+ preo->GetMatrix(mdel);
+ morig->MultiplyLeft(&mdel); // account delta used for reconstruction
+ break;
+ }
+ //
+ fCacheMatrixOrig.AddAtAndExpand(morig,idx);
+ fCacheMatrixCurr.AddAtAndExpand(mcurr,idx);
+ //
+ }
+ //
+ fCacheMatrixOrig.SetOwner(kTRUE);
+ fCacheMatrixCurr.SetOwner(kTRUE);
+ if (initDeltas) {delete initDeltas; initDeltas = 0;}
+ return 0;
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConstrainHelixFitPT(Int_t q,Double_t pt,Double_t pterr)
+{
+ // constrain q and pT of the helical fit of the track (should be set before process.track)
+ //
+ fConstrCharge = q==0 ? q:TMath::Sign(1,q);
+ fConstrPT = pt;
+ fConstrPTErr = pterr;
+}
+
+//________________________________________________________________________________________________________
+void AliITSAlignMille2::ConstrainHelixFitCurv(Int_t q,Double_t crv,Double_t crverr)
+{
+ // constrain charge and curvature of the helical fit of the track (should be set before process.track)
+ //
+ const double kCQConv = 0.299792458e-3;// R = PT/Bz/fgkCQConv with GeV,kGauss,cm
+
+ fConstrCharge = q==0 ? q:TMath::Sign(1,q);
+ if (crv<0 || IsZero(crv)) {
+ fConstrPT = -1;
+ fConstrPTErr = -1;
+ }
+ else {
+ fConstrPT = 1./crv*fBField*kCQConv;
+ fConstrPTErr =fConstrPT/crv*crverr;
+ }
+}
+
+//________________________________________________________________________________________________________
+TClonesArray* AliITSAlignMille2::CreateDeltas()
+{
+ // Create \Deltas for every explicitly or implicitly (via non-alignable volumes) varied
+ // or prealigned module.
+ // If the module has inded J in the hierarchy of alignable volumes (0 - the top, most
+ // coarse level), then its Delta is expressed via MP2 \deltas (in global frame) and
+ // prealignment \DeltaP's as:
+ // \Delta_J = Y X Y^-1
+ // where X = \delta_J * \DeltaP_J
+ // Y = Prod_{K=0,J-1} \delta_K
+ // Note that \delta_L accounts not only for its own correction but also of all non-alignable
+ // modules in the hierarchy chain from L up to the closest alignable:
+ // while (parent && !parent->IsAlignable()) {
+ // \delta_L->MultiplyLeft( \delta_parent );
+ // parent = parent->GetParent();
+ // }
+ //
+ Bool_t convLoc = kFALSE;
+ if (!GetUseGlobalDelta()) {
+ ConvertParamsToGlobal();
+ convLoc = kTRUE;
+ }
+ //
+ AliAlignObjParams tempAlignObj;
+ TGeoHMatrix tempMatX,tempMatY,tempMat1;
+ //
+ TClonesArray *array = new TClonesArray("AliAlignObjParams",10);
+ TClonesArray &alobj = *array;
+ int idx = 0;
+ //
+ TGeoManager* geoManager = AliGeomManager::GetGeometry();
+ int nalgtot = geoManager->GetNAlignable();
+ //
+ for (int ialg=0;ialg<nalgtot;ialg++) { // loop over all alignable entries
+ //
+ const char* algname = geoManager->GetAlignableEntry(ialg)->GetName();
+ //
+ AliITSAlignMille2Module* md = GetMilleModuleBySymName(algname); // explicitly varied?
+ AliITSAlignMille2Module* parent = md ? md->GetParent(): GetMilleModuleIfContained(algname);
+ AliAlignObjParams* preob = GetPrealignedObject(algname); // was it prealigned ?
+ //
+ if (!preob && !md && (!parent || parent->IsAlignable())) continue; // noting to do
+ //
+ // create matrix X (see comment) ------------------------------------------------->>>
+ // start from unity matrix
+ tempMatX.Clear();
+ if (preob) { // account prealigngment
+ preob->GetMatrix(tempMat1);
+ tempMatX.MultiplyLeft(&tempMat1);
+ }
+ //
+ if (md) {
+ tempAlignObj.SetTranslation( md->GetParVal(0),md->GetParVal(1),md->GetParVal(2));
+ tempAlignObj.SetRotation( md->GetParVal(3),md->GetParVal(4),md->GetParVal(5));
+ tempAlignObj.GetMatrix(tempMat1);
+ tempMatX.MultiplyLeft(&tempMat1); // acount correction to varied module
+ }
+ //
+ // the corrections to all non-alignable modules from current on
+ // till first alignable should add up to its matrix
+ while (parent && !parent->IsAlignable()) {
+ tempAlignObj.SetTranslation( parent->GetParVal(0),parent->GetParVal(1),parent->GetParVal(2));
+ tempAlignObj.SetRotation( parent->GetParVal(3),parent->GetParVal(4),parent->GetParVal(5));
+ tempAlignObj.GetMatrix(tempMat1);
+ tempMatX.MultiplyLeft(&tempMat1); // add matrix of non-alignable module
+ parent = parent->GetParent();
+ }
+ // create matrix X (see comment) ------------------------------------------------<<<
+ //
+ // create matrix Y (see comment) ------------------------------------------------>>>
+ // start from unity matrix
+ tempMatY.Clear();
+ while ( parent ) {
+ tempAlignObj.SetTranslation( parent->GetParVal(0),parent->GetParVal(1),parent->GetParVal(2));
+ tempAlignObj.SetRotation( parent->GetParVal(3),parent->GetParVal(4),parent->GetParVal(5));
+ tempAlignObj.GetMatrix(tempMat1);
+ tempMatY.MultiplyLeft(&tempMat1);
+ parent = parent->GetParent();
+ }
+ // create matrix Y (see comment) ------------------------------------------------<<<
+ //
+ tempMatX.MultiplyLeft(&tempMatY);
+ tempMatX.Multiply(&tempMatY.Inverse());
+ //
+ UShort_t vid = AliITSAlignMille2Module::GetVolumeIDFromSymname(algname);
+ new(alobj[idx++]) AliAlignObjParams(algname,vid,tempMatX,kTRUE);
+ //
+ }
+ //
+ if (convLoc) ConvertParamsToLocal();
+ //
+ return array;
+ //
+}
+
+//_______________________________________________________________________________________
+AliITSresponseSDD* AliITSAlignMille2::CreateSDDResponse()
+{
+ // create object with SDD repsonse (t0 and vdrift corrections) accounting for
+ // eventual precalibration
+ //
+ // if there was a precalibration provided, copy it to new arrray
+ AliITSresponseSDD *precal = GetSDDPrecalibration();
+ if (!precal) precal = GetSDDInit();
+ AliITSresponseSDD *calibSDD = new AliITSresponseSDD();
+ //
+ for (int ind=kSDDoffsID;ind<kSDDoffsID+kNSDDmod;ind++) {
+ calibSDD->SetModuleTimeZero(ind, precal? precal->GetTimeZero(ind) : 0.);
+ calibSDD->SetDeltaVDrift(ind, precal? precal->GetDeltaVDrift(ind) : 0.);
+ }
+ //
+ Bool_t save = kFALSE;
+ for (int imd=GetNModules();imd--;) {
+ AliITSAlignMille2Module* md = GetMilleModule(imd);
+ if (!md->IsSDD()) continue;
+ if (md->IsFreeDOF(AliITSAlignMille2Module::kDOFT0) ||
+ md->IsFreeDOF(AliITSAlignMille2Module::kDOFDV)) save = kTRUE;
+ //
+ for (int is=0;is<md->GetNSensitiveVolumes();is++) {
+ int ind = md->GetSensVolIndex(is);
+ float t0 = calibSDD->GetTimeZero(ind) + md->GetParVal(AliITSAlignMille2Module::kDOFT0);
+ float dv = calibSDD->GetDeltaVDrift(ind) + md->GetParVal(AliITSAlignMille2Module::kDOFDV);
+ //
+ calibSDD->SetModuleTimeZero(ind, t0);
+ calibSDD->SetDeltaVDrift(ind, dv);
+ }
+ }
+ //
+ if (!save) {
+ AliInfo("No free parameters for SDD calibration, nothing to save");
+ delete calibSDD;
+ calibSDD = 0;
+ }
+ //
+ return calibSDD;
+}
--- /dev/null
+/**************************************************************************
+ * Copyright(c) 2009-2011, ALICE Experiment at CERN, All rights reserved. *
+ * *
+ * Author: The ALICE Off-line Project. *
+ * Contributors are mentioned in the code where appropriate. *
+ * *
+ * Permission to use, copy, modify and distribute this software and its *
+ * documentation strictly for non-commercial purposes is hereby granted *
+ * without fee, provided that the above copyright notice appears in all *
+ * copies and that both the copyright notice and this permission notice *
+ * appear in the supporting documentation. The authors make no claims *
+ * about the suitability of this software for any purpose. It is *
+ * provided "as is" without express or implied warranty. *
+ **************************************************************************/
+/* $Id$ */
+///////////////////////////////////////////////////////////////////////////////////////////////
+// //
+// The line is defined by equations (1) //
+// a0*z+a1*x-a0*a1=0 and //
+// b0*z+b1*y-b0*b1=0 //
+// where x,y,z are NOT the lab axes but z is the lab axis along which the track //
+// has the largest lever arm and x,y are the remaining 2 axis in //
+// the order of fgkAxisID[z][0], fgkAxisID[z][1] //
+// The parameters are fParams[kA0,kB0,kA1,kB1] and the axis chosen as the independent //
+// var. is fParAxis (i.e. if fParAxis==kZ, then a0=ax,b0=bx, a1=ay,b1=by) //
+// //
+// //
+// The helix is defined by the equations (2) //
+// X(t) = (dr+R)*cos(phi0) - (R+sum{dRi})*cos(t+phi0) + sum{dRi*cos(phi0+ti)} //
+// Y(t) = (dr+R)*sin(phi0) - (R+sum{dRi})*sin(t+phi0) + sum{dRi*sin(phi0+ti)} //
+// Z(t) = dz - (R+sum{dRi})*t*tg(dip) + sum{dRi*ti}*tg(dip) //
+// where dRi is the change of the radius due to the ELoss at parameter ti //
+// //
+// Author: ruben.shahoyan@cern.ch //
+// //
+///////////////////////////////////////////////////////////////////////////////////////////////
+
+#include "AliITSTPArrayFit.h"
+#include "AliExternalTrackParam.h"
+#include "AliSymMatrix.h"
+#include "AliLog.h"
+#include "AliParamSolver.h"
+#include "AliGeomManager.h"
+#include "AliITSgeomTGeo.h"
+#include "AliTracker.h"
+#include <TRandom.h>
+
+ClassImp(AliITSTPArrayFit)
+
+const Int_t AliITSTPArrayFit::fgkAxisID[3][3] = {
+ {AliITSTPArrayFit::kY,AliITSTPArrayFit::kZ,AliITSTPArrayFit::kX},
+ {AliITSTPArrayFit::kZ,AliITSTPArrayFit::kX,AliITSTPArrayFit::kY},
+ {AliITSTPArrayFit::kX,AliITSTPArrayFit::kY,AliITSTPArrayFit::kZ} };
+
+const Int_t AliITSTPArrayFit::fgkAxisCID[3][6] = {
+ {AliITSTPArrayFit::kYY,AliITSTPArrayFit::kYZ,AliITSTPArrayFit::kXY,
+ AliITSTPArrayFit::kZZ,AliITSTPArrayFit::kXZ,AliITSTPArrayFit::kXX},
+ //
+ {AliITSTPArrayFit::kZZ,AliITSTPArrayFit::kXZ,AliITSTPArrayFit::kYZ,
+ AliITSTPArrayFit::kXX,AliITSTPArrayFit::kYX,AliITSTPArrayFit::kYY},
+ //
+ {AliITSTPArrayFit::kXX,AliITSTPArrayFit::kXY,AliITSTPArrayFit::kXZ,
+ AliITSTPArrayFit::kYY,AliITSTPArrayFit::kYZ,AliITSTPArrayFit::kZZ}
+};
+//
+
+const Double_t AliITSTPArrayFit::fgkAlmostZero = 1E-55;
+const Double_t AliITSTPArrayFit::fgkCQConv = 0.299792458e-3;// R = PT/Bz/fgkCQConv with GeV,kGauss,cm
+const Double_t AliITSTPArrayFit::fgkZSpanITS[AliITSTPArrayFit::kMaxLrITS] = {
+ 36. ,14.1,14.1, 38., 22.2,29.7, 51. ,43.1,48.9};
+
+const Double_t AliITSTPArrayFit::fgkRLayITS[AliITSTPArrayFit::kMaxLrITS] = {
+ 2.94, 3.9,7.6, 11.04, 15.0,23.9, 29.44 ,38.0,43.0};
+
+const Int_t AliITSTPArrayFit::fgkPassivLrITS[3] =
+ {AliITSTPArrayFit::kLrBeamPime,AliITSTPArrayFit::kLrShield1,AliITSTPArrayFit::kLrShield2};
+
+const Int_t AliITSTPArrayFit::fgkActiveLrITS[6] =
+ {AliITSTPArrayFit::kLrSPD1,AliITSTPArrayFit::kLrSPD2,
+ AliITSTPArrayFit::kLrSDD1,AliITSTPArrayFit::kLrSDD2,
+ AliITSTPArrayFit::kLrSSD1,AliITSTPArrayFit::kLrSSD2};
+
+Double_t AliITSTPArrayFit::fgRhoLITS[AliITSTPArrayFit::kMaxLrITS] = {
+ 1.48e-01, 2.48e-01,2.57e-01, 1.34e-01, 3.34e-01,3.50e-01, 2.22e-01, 2.38e-01,2.25e-01};
+
+//____________________________________________________
+AliITSTPArrayFit::AliITSTPArrayFit() :
+ fPoints(0),fParSol(0),fBz(0),fCharge(0),fPntFirst(-1),
+ fPntLast(-1),fNPBooked(0),fParAxis(-1),fCovI(0),fChi2NDF(0),
+ fMaxIter(20),fIter(0),fEps(1e-6),fMass(0),fkAxID(0),fkAxCID(0),fCurT(0),
+ fFirstPosT(0),fNElsPnt(0),fElsId(0),fElsDR(0)
+{
+ // default constructor
+ for (int i=kMaxParam;i--;) fParams[i] = 0;
+ for (int i=kMaxParamSq;i--;) fParamsCov[i] = 0;
+ SetMass();
+}
+
+//____________________________________________________
+AliITSTPArrayFit::AliITSTPArrayFit(Int_t np) :
+ fPoints(0),fParSol(0),fBz(0),fCharge(0),fPntFirst(-1),
+ fPntLast(-1),fNPBooked(np),fParAxis(-1),fCovI(0),fChi2NDF(0),
+ fMaxIter(20),fIter(0),fEps(1e-6),fMass(0),fkAxID(0),fkAxCID(0),fCurT(0),
+ fFirstPosT(0),fNElsPnt(0),fElsId(0),fElsDR(0)
+{
+ // constructor with booking of np points
+ for (int i=kMaxParam;i--;) fParams[i] = 0;
+ for (int i=kMaxParamSq;i--;) fParamsCov[i] = 0;
+ InitAux();
+ SetEps();
+ SetMass();
+ SetMaxIterations();
+}
+
+//____________________________________________________
+AliITSTPArrayFit::AliITSTPArrayFit(const AliITSTPArrayFit &src) :
+ TObject(src),fPoints(src.fPoints),fParSol(0),fBz(src.fBz),
+ fCharge(src.fCharge),fPntFirst(src.fPntFirst),fPntLast(src.fPntLast),fNPBooked(src.fNPBooked),
+ fParAxis(src.fParAxis),fCovI(0),fChi2NDF(0),fMaxIter(20),fIter(0),fEps(0),fMass(src.fMass),
+ fkAxID(0),fkAxCID(0),fCurT(0),fFirstPosT(0),fNElsPnt(0),fElsId(0),fElsDR(0)
+{
+ // copy constructor
+ InitAux();
+ memcpy(fCovI,src.fCovI,fNPBooked*6*sizeof(Double_t));
+ for (int i=kMaxParam;i--;) fParams[i] = src.fParams[i];
+ for (int i=kMaxParamSq;i--;) fParamsCov[i] = src.fParamsCov[i];
+ memcpy(fCurT,src.fCurT,fNPBooked*sizeof(Double_t));
+ SetEps(src.fEps);
+ SetMaxIterations(src.fMaxIter);
+ //
+}
+
+//____________________________________________________
+AliITSTPArrayFit &AliITSTPArrayFit::operator =(const AliITSTPArrayFit& src)
+{
+ // assignment operator
+ if (this==&src) return *this;
+ ((TObject*)this)->operator=(src);
+ fPoints = src.fPoints;
+ if (!fParSol) fParSol = new AliParamSolver(*src.fParSol);
+ else *fParSol = *src.fParSol;
+ fBz = src.fBz;
+ fCharge = src.fCharge;
+ fNPBooked = src.fNPBooked;
+ fPntFirst = src.fPntFirst;
+ fPntLast = src.fPntLast;
+ InitAux();
+ memcpy(fCovI,src.fCovI,fNPBooked*6*sizeof(Double_t));
+ for (int i=kMaxParam;i--;) fParams[i] = src.fParams[i];
+ for (int i=kMaxParamSq;i--;) fParamsCov[i] = src.fParamsCov[i];
+ SetParAxis(src.fParAxis);
+ fNElsPnt = src.fNElsPnt;
+ fFirstPosT = src.fFirstPosT;
+ memcpy(fCurT ,src.fCurT ,fNPBooked*sizeof(Double_t));
+ memcpy(fElsId ,src.fElsId ,fNPBooked*sizeof(Int_t));
+ memcpy(fElsDR ,src.fElsDR ,fNPBooked*sizeof(Double_t));
+ memcpy(fCurT ,src.fCurT ,fNPBooked*sizeof(Double_t));
+ SetEps(src.fEps);
+ SetMaxIterations(src.fMaxIter);
+ //
+ return *this;
+ //
+}
+
+//____________________________________________________
+AliITSTPArrayFit::~AliITSTPArrayFit()
+{
+ // destructor
+ delete fParSol;
+ delete[] fCovI;
+ delete[] fCurT;
+ delete[] fElsId;
+ delete[] fElsDR;
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::Reset()
+{
+ // reset to process new track
+ if (fParSol) fParSol->Clear();
+ fPoints=0;
+ fNElsPnt = 0;
+ fFirstPosT = 0;
+ // fBz = 0;
+ fCharge = 0;
+ fIter = 0;
+ fPntFirst=fPntLast=-1;
+ SetParAxis(-1);
+ ResetBit(kFitDoneBit|kCovInvBit);
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::AttachPoints(const AliTrackPointArray* points, Int_t pfirst,Int_t plast)
+{
+ // create from piece of AliTrackPointArray
+ Reset();
+ fPoints = points;
+ int np = points->GetNPoints();
+ if (fNPBooked<np) {
+ fNPBooked = np;
+ InitAux();
+ }
+ fPntFirst = pfirst<0 ? 0 : pfirst;
+ fPntLast = plast<fPntFirst ? np-1 : plast;
+ //
+ for (int i=kMaxParam;i--;) fParams[i] = 0;
+ for (int i=kMaxParamSq;i--;) fParamsCov[i] = 0;
+ //
+ InvertPointsCovMat();
+ //
+}
+
+//____________________________________________________
+Bool_t AliITSTPArrayFit::SetFirstLast(Int_t pfirst,Int_t plast)
+{
+ // set first and last point to fit
+ const AliTrackPointArray* pnts = fPoints;
+ if (!pnts) {AliError("TrackPointArray is not attached yet"); return kFALSE;}
+ AttachPoints(pnts,pfirst,plast);
+ return kTRUE;
+ //
+}
+
+//____________________________________________________
+Bool_t AliITSTPArrayFit::InvertPointsCovMat()
+{
+ // invert the cov.matrices of the points
+ for (int i=fPntFirst;i<=fPntLast;i++) {
+ //
+ const float *cov = fPoints->GetCov() + i*6; // pointer on cov.matrix
+ //
+ Double_t t0 = cov[kYY]*cov[kZZ] - cov[kYZ]*cov[kYZ];
+ Double_t t1 = cov[kXY]*cov[kZZ] - cov[kXZ]*cov[kYZ];
+ Double_t t2 = cov[kXY]*cov[kYZ] - cov[kXZ]*cov[kYY];
+ Double_t det = cov[kXX]*t0 - cov[kXY]*t1 + cov[kXZ]*t2;
+ if (TMath::Abs(det)<fgkAlmostZero) {
+ AliInfo(Form("Cov.Matrix for point %d is singular",i));
+ return kFALSE;
+ }
+ //
+ Double_t *covI = GetCovI(i);
+ covI[kXX] = t0/det;
+ covI[kXY] = -t1/det;
+ covI[kXZ] = t2/det;
+ covI[kYY] = (cov[kXX]*cov[kZZ] - cov[kXZ]*cov[kXZ])/det;
+ covI[kYZ] = (cov[kXY]*cov[kXZ] - cov[kXX]*cov[kYZ])/det;
+ covI[kZZ] = (cov[kXX]*cov[kYY] - cov[kXY]*cov[kXY])/det;
+ //
+ }
+ SetCovInv();
+ return kTRUE;
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::InitAux()
+{
+ // init auxiliary space
+ if (fCovI) delete[] fCovI;
+ if (fCurT) delete[] fCurT;
+ //
+ fCovI = new Double_t[6*fNPBooked];
+ fCurT = new Double_t[fNPBooked+kMaxLrITS];
+ fElsId = new Int_t[fNPBooked+kMaxLrITS];
+ fElsDR = new Double_t[fNPBooked+kMaxLrITS];
+ memset(fElsDR,0,(fNPBooked+kMaxLrITS)*sizeof(Double_t));
+ memset(fCovI,0,fNPBooked*6*sizeof(Double_t));
+ //
+}
+
+//____________________________________________________
+Bool_t AliITSTPArrayFit::FitLineCrude()
+{
+ // perform linear fit w/o accounting the errors
+ // fit is done in the parameterization
+ // x = res[0] + res[1]*z
+ // y = res[2] + res[3]*z
+ // where x,y,z are NOT the lab axes but z is the lab axis along which the track
+ // has the largest lever arm and x,y are the remaining 2 axis in
+ // the order of fgkAxisID[z][0], fgkAxisID[z][1]
+ //
+ int np = fPntLast - fPntFirst + 1;
+ if (np<2) {
+ AliError("At least 2 points are needed for straight line fit");
+ return kFALSE;
+ }
+ //
+ if (fParAxis<0) SetParAxis(ChoseParAxis());
+ Double_t sZ=0,sZZ=0,sY=0,sYZ=0,sX=0,sXZ=0,det=0;
+ //
+ const float *coord[3] = {fPoints->GetX(),fPoints->GetY(),fPoints->GetZ()};
+ const Float_t *varZ = coord[ fParAxis ];
+ const Float_t *varX = coord[ fkAxID[kX] ];
+ const Float_t *varY = coord[ fkAxID[kY] ];
+ //
+ for (int i=fPntFirst;i<=fPntLast;i++) {
+ sZ += varZ[i];
+ sZZ += varZ[i]*varZ[i];
+ //
+ sX += varX[i];
+ sXZ += varX[i]*varZ[i];
+ //
+ sY += varY[i];
+ sYZ += varY[i]*varZ[i];
+ }
+ det = sZZ*np-sZ*sZ;
+ if (TMath::Abs(det)<fgkAlmostZero) return kFALSE;
+ fParams[0] = (sX*sZZ-sZ*sXZ)/det;
+ fParams[1] = (sXZ*np-sZ*sX)/det;
+ //
+ fParams[2] = (sY*sZZ-sZ*sYZ)/det;
+ fParams[3] = (sYZ*np-sZ*sY)/det;
+ //
+ return kTRUE;
+ //
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::SetParAxis(Int_t ax)
+{
+ // select the axis which will be used as a parameter for the line: longest baseline
+ if (ax>kZ) {
+ AliInfo(Form("Wrong axis choice: %d",ax));
+ fParAxis = -1;
+ }
+ fParAxis = ax;
+ if (ax>=0) {
+ fkAxID = fgkAxisID[ax];
+ fkAxCID = fgkAxisCID[ax];
+ }
+ else {
+ fkAxID = fkAxCID = 0;
+ }
+ //
+}
+
+//____________________________________________________
+Int_t AliITSTPArrayFit::ChoseParAxis() const
+{
+ // select the variable with largest base as a parameter
+ Double_t cmn[3]={1.e9,1.e9,1.e9},cmx[3]={-1.e9,-1.e9,-1.e9};
+ //
+ const float *coord[3] = {fPoints->GetX(),fPoints->GetY(),fPoints->GetZ()};
+ for (int i=fPntFirst;i<=fPntLast;i++) {
+ for (int j=3;j--;) {
+ Double_t val = coord[j][i];
+ if (cmn[j]>val) cmn[j] = val;
+ if (cmx[j]<val) cmx[j] = val;
+ }
+ }
+ //
+ int axis = kZ;
+ if (cmx[axis]-cmn[axis] < cmx[kX]-cmn[kX]) axis = kX;
+ if (cmx[axis]-cmn[axis] < cmx[kY]-cmn[kY]) axis = kY;
+ return axis;
+ //
+}
+
+//____________________________________________________
+Double_t AliITSTPArrayFit::GetPosition(Double_t *xyzPCA, const Double_t *xyz, const Double_t *covI) const
+{
+ // calculate the position of the track at PCA to xyz
+ Double_t t = GetParPCA(xyz,covI);
+ GetPosition(xyzPCA,t);
+ return t;
+}
+
+//____________________________________________________
+Double_t AliITSTPArrayFit::GetPosition(Double_t *xyzPCA, const AliTrackPoint *pntCovInv) const
+{
+ // calculate the position of the track at PCA to pntCovInv
+ // NOTE: the covariance matrix of the point must be inverted
+ Double_t covI[6],xyz[3] = {pntCovInv->GetX(),pntCovInv->GetY(),pntCovInv->GetZ()};
+ for (int i=6;i--;) covI[i] = pntCovInv->GetCov()[i];
+ Double_t t = GetParPCA(xyz,covI);
+ GetPosition(xyzPCA,t);
+ return t;
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetResiduals(Double_t *resPCA, const AliTrackPoint *pntCovInv) const
+{
+ // calculate the residuals of the track at PCA to pntCovInv
+ // NOTE: the covariance matrix of the point must be inverted
+ GetPosition(resPCA,pntCovInv);
+ resPCA[0] -= pntCovInv->GetX();
+ resPCA[1] -= pntCovInv->GetY();
+ resPCA[2] -= pntCovInv->GetZ();
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetResiduals(Double_t *resPCA, const Double_t *xyz, const Double_t *covI) const
+{
+ // calculate the residuals of the track at PCA to xyz
+ GetPosition(resPCA,xyz,covI);
+ resPCA[kX] -= xyz[kX];
+ resPCA[kY] -= xyz[kY];
+ resPCA[kZ] -= xyz[kZ];
+}
+
+//____________________________________________________
+Double_t AliITSTPArrayFit::GetParPCALine(const Double_t *xyz, const Double_t *covI) const
+{
+ // get parameter for the point with least weighted distance to the point
+ //
+ Double_t rhs,denom;
+ Double_t dx = fParams[kA0]-xyz[ fkAxID[kX] ];
+ Double_t dy = fParams[kA1]-xyz[ fkAxID[kY] ];
+ Double_t dz = -xyz[ fkAxID[kZ] ];
+ //
+ if (covI) {
+ Double_t tx = fParams[kB0]*covI[ fkAxCID[kXX] ] + fParams[kB1]*covI[ fkAxCID[kXY] ] + covI[ fkAxCID[kXZ] ];
+ Double_t ty = fParams[kB0]*covI[ fkAxCID[kXY] ] + fParams[kB1]*covI[ fkAxCID[kYY] ] + covI[ fkAxCID[kYZ] ];
+ Double_t tz = fParams[kB0]*covI[ fkAxCID[kXZ] ] + fParams[kB1]*covI[ fkAxCID[kYZ] ] + covI[ fkAxCID[kZZ] ];
+ rhs = tx*dx + ty*dy + tz*dz;
+ denom = -(fParams[kB0]*(covI[ fkAxCID[kXZ] ] + tx) + fParams[kB1]*(covI[ fkAxCID[kYZ] ] + ty) + covI[ fkAxCID[kZZ] ]);
+ }
+ else {
+ rhs = fParams[kB0]*dx + fParams[kB1]*dy + dz;
+ denom = -(fParams[kB0]*fParams[kB0] + fParams[kB1]*fParams[kB1] + 1);
+ }
+ //
+ return rhs/denom;
+ //
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetDResDPosLine(Double_t *dXYZdP, /*const Double_t *xyz,*/ const Double_t *covI) const
+{
+ // calculate detivative of the PCA residuals vs point position and fill in user provide
+ // array in the format {dXdXp,dY/dXp,dZdXp, ... dXdZp,dYdZp,dZdZp}
+ //
+ Double_t dTdP[3];
+ GetDtDPosLine(dTdP, /*xyz,*/ covI); // derivative of the t-param over point position
+ //
+ for (int i=3;i--;) {
+ int var = fkAxID[i];
+ Double_t *curd = dXYZdP + var*3; // d/dCoord_i
+ curd[ fkAxID[kX] ] = fParams[kB0]*dTdP[var];
+ curd[ fkAxID[kY] ] = fParams[kB1]*dTdP[var];
+ curd[ fkAxID[kZ] ] = dTdP[var];
+ curd[ var ]-= 1.;
+ }
+ //
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetDResDParamsLine(Double_t *dXYZdP, const Double_t *xyz, const Double_t *covI) const
+{
+ // calculate detivative of the PCA residuals vs line parameters and fill in user provide
+ // array in the format {dXdP0,dYdP0,dZdP0, ... dXdPn,dYdPn,dZdPn}
+ //
+ Double_t dTdP[4];
+ Double_t t = GetDtDParamsLine(dTdP, xyz, covI); // derivative of the t-param over line params
+ //
+ Double_t *curd = dXYZdP + kA0*3; // d/dA0
+ curd[ fkAxID[kX] ] = fParams[kB0]*dTdP[kA0] + 1.;
+ curd[ fkAxID[kY] ] = fParams[kB1]*dTdP[kA0];
+ curd[ fkAxID[kZ] ] = dTdP[kA0];
+ //
+ curd = dXYZdP + kB0*3; // d/dB0
+ curd[ fkAxID[kX] ] = fParams[kB0]*dTdP[kB0] + t;
+ curd[ fkAxID[kY] ] = fParams[kB1]*dTdP[kB0];
+ curd[ fkAxID[kZ] ] = dTdP[kB0];
+ //
+ curd = dXYZdP + kA1*3; // d/dA1
+ curd[ fkAxID[kX] ] = fParams[kB0]*dTdP[kA1];
+ curd[ fkAxID[kY] ] = fParams[kB1]*dTdP[kA1] + 1.;
+ curd[ fkAxID[kZ] ] = dTdP[kA1];
+ //
+ curd = dXYZdP + kB1*3; // d/dB1
+ curd[ fkAxID[kX] ] = fParams[kB0]*dTdP[kB1];
+ curd[ fkAxID[kY] ] = fParams[kB1]*dTdP[kB1] + t;
+ curd[ fkAxID[kZ] ] = dTdP[kB1];
+ //
+}
+
+//____________________________________________________
+Double_t AliITSTPArrayFit::GetDtDParamsLine(Double_t *dtparam,const Double_t *xyz, const Double_t *covI) const
+{
+ // get t-param detivative over the parameters for the point with least weighted distance to the point
+ //
+ Double_t rhs,denom;
+ Double_t dx = fParams[kA0]-xyz[ fkAxID[kX] ];
+ Double_t dy = fParams[kA1]-xyz[ fkAxID[kY] ];
+ Double_t dz = -xyz[ fkAxID[kZ] ];
+ Double_t rhsDA0,rhsDA1,rhsDB0,rhsDB1,denDB0,denDB1;
+ //
+ if (covI) {
+ Double_t tx = fParams[kB0]*covI[ fkAxCID[kXX] ] + fParams[kB1]*covI[ fkAxCID[kXY] ] + covI[ fkAxCID[kXZ] ];
+ Double_t ty = fParams[kB0]*covI[ fkAxCID[kXY] ] + fParams[kB1]*covI[ fkAxCID[kYY] ] + covI[ fkAxCID[kYZ] ];
+ Double_t tz = fParams[kB0]*covI[ fkAxCID[kXZ] ] + fParams[kB1]*covI[ fkAxCID[kYZ] ] + covI[ fkAxCID[kZZ] ];
+ rhs = tx*dx + ty*dy + tz*dz;
+ denom = -(fParams[kB0]*(covI[ fkAxCID[kXZ] ] + tx) + fParams[kB1]*(covI[ fkAxCID[kYZ] ] + ty) + covI[ fkAxCID[kZZ] ]);
+ //
+ rhsDA0 = tx;
+ rhsDA1 = ty;
+ rhsDB0 = covI[ fkAxCID[kXX] ]*dx + covI[ fkAxCID[kXY] ]*dy + covI[ fkAxCID[kXZ] ]*dz;
+ rhsDB1 = covI[ fkAxCID[kXY] ]*dx + covI[ fkAxCID[kYY] ]*dy + covI[ fkAxCID[kYZ] ]*dz;
+ //
+ denDB0 = -(tx + tx);
+ denDB1 = -(ty + ty);
+ }
+ else {
+ rhs = fParams[kB0]*dx + fParams[kB1]*dy + dz;
+ denom = -(fParams[kB0]*fParams[kB0] + fParams[kB1]*fParams[kB1] + 1);
+ //
+ rhsDA0 = fParams[kB0];
+ rhsDB0 = dx;
+ rhsDA1 = fParams[kB1];
+ rhsDB1 = dy;
+ //
+ denDB0 = -(fParams[kB0]+fParams[kB0]);
+ denDB1 = -(fParams[kB1]+fParams[kB1]);
+ //
+ }
+ //
+ Double_t denom2 = denom*denom;
+ dtparam[kA0] = rhsDA0/denom; // denom does not depend on A0,A1
+ dtparam[kA1] = rhsDA1/denom;
+ dtparam[kB0] = rhsDB0/denom - rhs/denom2 * denDB0;
+ dtparam[kB1] = rhsDB1/denom - rhs/denom2 * denDB1;
+ //
+ return rhs/denom;
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetDtDPosLine(Double_t *dtpos,/*const Double_t *xyz,*/ const Double_t *covI) const
+{
+ // get t-param detivative over the parameters for the point with least weighted distance to the point
+ //
+ // Double_t rhs;
+ // Double_t dx = fParams[kA0]-xyz[ fkAxID[kX] ];
+ // Double_t dy = fParams[kA1]-xyz[ fkAxID[kY] ];
+ // Double_t dz = -xyz[ fkAxID[kZ] ];
+ Double_t denom;
+ Double_t rhsDX,rhsDY,rhsDZ;
+ //
+ if (covI) {
+ Double_t tx = fParams[kB0]*covI[ fkAxCID[kXX] ] + fParams[kB1]*covI[ fkAxCID[kXY] ] + covI[ fkAxCID[kXZ] ];
+ Double_t ty = fParams[kB0]*covI[ fkAxCID[kXY] ] + fParams[kB1]*covI[ fkAxCID[kYY] ] + covI[ fkAxCID[kYZ] ];
+ Double_t tz = fParams[kB0]*covI[ fkAxCID[kXZ] ] + fParams[kB1]*covI[ fkAxCID[kYZ] ] + covI[ fkAxCID[kZZ] ];
+ // rhs = tx*dx + ty*dy + tz*dz;
+ denom = -(fParams[kB0]*(covI[ fkAxCID[kXZ] ] + tx) + fParams[kB1]*(covI[ fkAxCID[kYZ] ] + ty) + covI[ fkAxCID[kZZ] ]);
+ //
+ rhsDX = -tx;
+ rhsDY = -ty;
+ rhsDZ = -tz;
+ }
+ else {
+ // rhs = fParams[kB0]*dx + fParams[kB1]*dy + dz;
+ denom = -(fParams[kB0]*fParams[kB0] + fParams[kB1]*fParams[kB1] + 1);
+ //
+ rhsDX = -fParams[kB0];
+ rhsDY = -fParams[kB1];
+ rhsDZ = -1;
+ //
+ }
+ //
+ dtpos[ fkAxID[kX] ] = rhsDX/denom;
+ dtpos[ fkAxID[kY] ] = rhsDY/denom;
+ dtpos[ fkAxID[kZ] ] = rhsDZ/denom;
+ //
+ // return rhs/denom;
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetDResDParamsLine(Double_t *dXYZdP, Int_t ipnt) const
+{
+ // calculate detivative of the PCA residuals vs line parameters and fill in user provide
+ // array in the format {dXdP0,dYdP0,dZdP0, ... dXdPn,dYdPn,dZdPn}
+ //
+ if (ipnt<fPntFirst || ipnt>fPntLast) {
+ AliError(Form("Attempt to access the point %d not in the fitted points [%d:%d]",ipnt,fPntFirst,fPntLast));
+ return;
+ }
+ GetDResDParamsLine(dXYZdP, GetPoint(ipnt) , IsCovIgnored() ? 0 : GetCovI(ipnt));
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetDResDPosLine(Double_t *dXYZdP, Int_t ipnt) const
+{
+ // calculate detivative of the PCA residuals vs point position and fill in user provide
+ // array in the format {dXdXp,dY/dXp,dZdXp, ... dXdZp,dYdZp,dZdZp}
+ //
+ if (ipnt<fPntFirst || ipnt>fPntLast) {
+ AliError(Form("Attempt to access the point %d not in the fitted points [%d:%d]",ipnt,fPntFirst,fPntLast));
+ return;
+ }
+ GetDResDPosLine(dXYZdP,IsCovIgnored() ? 0 : GetCovI(ipnt));
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetDResDParams(Double_t *dXYZdP, Int_t ipnt)
+{
+ // calculate detivative of the PCA residuals vs track parameters and fill in user provide
+ // array in the format {dXdP0,dYdP0,dZdP0, ... dXdPn,dYdPn,dZdPn}
+ //
+ if (ipnt<fPntFirst || ipnt>fPntLast) {
+ AliError(Form("Attempt to access the point %d not in the fitted points [%d:%d]",ipnt,fPntFirst,fPntLast));
+ return;
+ }
+ GetDResDParams(dXYZdP, GetPoint(ipnt) , IsCovIgnored() ? 0 : GetCovI(ipnt));
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetDResDPos(Double_t *dXYZdP, Int_t ipnt)
+{
+ // calculate detivative of the PCA residuals vs point position and fill in user provide
+ // array in the format {dXdXp,dY/dXp,dZdXp, ... dXdZp,dYdZp,dZdZp}
+ //
+ if (ipnt<fPntFirst || ipnt>fPntLast) {
+ AliError(Form("Attempt to access the point %d not in the fitted points [%d:%d]",ipnt,fPntFirst,fPntLast));
+ return;
+ }
+ GetDResDPos(dXYZdP, GetPoint(ipnt), IsCovIgnored() ? 0 : GetCovI(ipnt));
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetDResDParams(Double_t *dXYZdP, const Double_t *xyz, const Double_t *covI)
+{
+ // get residual detivatives over the track parameters for the point with least weighted distance to the point
+ //
+ if (!IsFieldON()) { // for the straight line calculate analytically
+ GetDResDParamsLine(dXYZdP, xyz, covI);
+ return;
+ }
+ //
+ // calculate derivative numerically
+ const Double_t delta = 0.01;
+ Double_t xyzVar[4][3];
+ //
+ for (int ipar = 5;ipar--;) {
+ double sav = fParams[ipar];
+ fParams[ipar] -= delta;
+ GetPosition(xyzVar[0],xyz,covI);
+ fParams[ipar] += delta/2;
+ GetPosition(xyzVar[1],xyz,covI);
+ fParams[ipar] += delta;
+ GetPosition(xyzVar[2],xyz,covI);
+ fParams[ipar] += delta/2;
+ GetPosition(xyzVar[3],xyz,covI);
+ fParams[ipar] = sav; // restore
+ //
+ double *curd = dXYZdP + 3*ipar;
+ for (int i=3;i--;) curd[i] = (8.*(xyzVar[2][i]-xyzVar[1][i]) - (xyzVar[3][i]-xyzVar[0][i]))/6./delta;
+ }
+ //
+}
+
+
+//____________________________________________________
+void AliITSTPArrayFit::GetDResDPos(Double_t *dXYZdP, const Double_t *xyz, const Double_t *covI)
+{
+ // get residuals detivative over the point position for the point with least weighted distance to the point
+ //
+
+ if (!IsFieldON()) { // for the straight line calculate analytically
+ GetDResDPosLine(dXYZdP, /*xyz,*/ covI);
+ return;
+ }
+ //
+ // calculate derivative numerically
+ const Double_t delta = 0.005;
+ Double_t xyzVar[4][3];
+ Double_t xyzv[3] = {xyz[0],xyz[1],xyz[2]};
+ //
+ for (int ipar = 3;ipar--;) {
+ double sav = xyzv[ipar];
+ xyzv[ipar] -= delta;
+ GetPosition(xyzVar[0],xyzv,covI);
+ xyzv[ipar] += delta/2;
+ GetPosition(xyzVar[1],xyzv,covI);
+ xyzv[ipar] += delta;
+ GetPosition(xyzVar[2],xyzv,covI);
+ xyzv[ipar] += delta/2;
+ GetPosition(xyzVar[3],xyzv,covI);
+ xyzv[ipar] = sav; // restore
+ //
+ double *curd = dXYZdP + 3*ipar;
+ for (int i=3;i--;) curd[i] = (8.*(xyzVar[2][i]-xyzVar[1][i]) - (xyzVar[3][i]-xyzVar[0][i]))/6./delta;
+ curd[ipar] -= 1.;
+ }
+ //
+}
+
+//________________________________________________________________________________________________________
+Double_t AliITSTPArrayFit::GetParPCAHelix(const Double_t* xyz, const Double_t* covI) const
+{
+ // find track parameter t (eq.2) corresponding to point of closest approach to xyz
+ //
+ Double_t phi = GetParPCACircle(xyz[kX],xyz[kY]);
+ Double_t cs = TMath::Cos(fParams[kPhi0]);
+ Double_t sn = TMath::Sin(fParams[kPhi0]);
+ Double_t xc = (fParams[kD0]+fParams[kR0])*cs;
+ Double_t yc = (fParams[kD0]+fParams[kR0])*sn;
+ Double_t dchi2,ddchi2;
+ //
+ Double_t dzD = -fParams[kR0]*fParams[kDip];
+ Double_t dphi = 0;
+ //
+ int it=0;
+ do {
+ cs = TMath::Cos(phi + fParams[kPhi0]);
+ sn = TMath::Sin(phi + fParams[kPhi0]);
+ //
+ Double_t dxD = fParams[kR0]*sn;
+ Double_t dyD = -fParams[kR0]*cs;
+ Double_t dxDD = -dyD;
+ Double_t dyDD = dxD;
+ //
+ Double_t dx = xc - fParams[kR0]*cs - xyz[kX];
+ Double_t dy = yc - fParams[kR0]*sn - xyz[kY];
+ Double_t dz = fParams[kDZ] + dzD*phi- xyz[kZ];
+ //
+ if (covI) {
+ Double_t tx = dx*covI[kXX] + dy*covI[kXY] + dz*covI[kXZ];
+ Double_t ty = dx*covI[kXY] + dy*covI[kYY] + dz*covI[kYZ];
+ Double_t tz = dx*covI[kXZ] + dy*covI[kYZ] + dz*covI[kZZ];
+ //
+ Double_t ttx = dxD*covI[kXX] + dyD*covI[kXY] + dzD*covI[kXZ];
+ Double_t tty = dxD*covI[kXY] + dyD*covI[kYY] + dzD*covI[kYZ];
+ Double_t ttz = dxD*covI[kXZ] + dyD*covI[kYZ] + dzD*covI[kZZ];
+ //
+ // chi2 = dx*tx + dy*ty + dz*tz;
+ dchi2 = dxD*tx + dyD*ty + dzD*tz;
+ ddchi2 = dxDD*tx + dyDD*ty + dxD *ttx + dyD *tty + dzD *ttz;
+ //
+ }
+ else {
+ // chi2 = dx*dx + dy*dy + dz*dz;
+ dchi2 = dxD*dx + dyD*dy + dzD*dz;
+ ddchi2 = dxDD*dx + dyDD*dy + + dxD*dxD + dyD*dyD + dzD*dzD;
+ }
+ //
+ if (TMath::Abs(ddchi2)<fgkAlmostZero || TMath::Abs(dphi=dchi2/ddchi2)<fEps) break;
+ phi -= dphi;
+ } while(++it<fMaxIter);
+ //
+ return phi;
+}
+
+//________________________________________________________________________________________________________
+Double_t AliITSTPArrayFit::GetParPCACircle(Double_t x,Double_t y) const
+{
+ // find track parameter t (eq.2) corresponding to point on the circle with closest approach to x,y
+ //
+ Double_t r = fParams[kD0]+fParams[kR0];
+ Double_t t = TMath::ATan2( r*TMath::Sin(fParams[kPhi0])-y, r*TMath::Cos(fParams[kPhi0])-x ) - fParams[kPhi0];
+ if (fParams[kR0] < 0) t += TMath::Pi();
+ if (t > TMath::Pi()) t -= TMath::Pi()*2;
+ if (t <-TMath::Pi()) t += TMath::Pi()*2;
+ return t;
+}
+
+//________________________________________________________________________________________________________
+Double_t AliITSTPArrayFit::GetHelixParAtR(Double_t r) const
+{
+ // find helix parameter t (eq.2) corresponding to point on the circle of radius t
+ //
+ double gam = 1. - (r-fParams[kD0])*(r+fParams[kD0])/fParams[kR0]/(fParams[kD0]+fParams[kR0])/2.;
+ return (TMath::Abs(gam)>1) ? -1e9 : TMath::ACos(gam);
+}
+
+//________________________________________________________________________________________________________
+Double_t AliITSTPArrayFit::CalcChi2NDF() const
+{
+ // calculate fit chi2/ndf
+ Double_t chi2 = 0;
+ Double_t dr[3]; // residuals
+ //if (!IsFitDone()) return -1;
+ for (int ipnt=fPntFirst;ipnt<=fPntLast;ipnt++) {
+ GetResiduals(dr,ipnt);
+ Double_t* covI = GetCovI(ipnt);
+ chi2 += dr[kX]*(dr[kX]*covI[ kXX ]+dr[kY]*covI[ kXY ]+dr[kZ]*covI[ kXZ ])
+ + dr[kY]*(dr[kX]*covI[ kXY ]+dr[kY]*covI[ kYY ]+dr[kZ]*covI[ kYZ ])
+ + dr[kZ]*(dr[kX]*covI[ kXZ ]+dr[kY]*covI[ kYZ ]+dr[kZ]*covI[ kZZ ]);
+ }
+ int ndf = (fPntLast-fPntFirst+1)*3 - GetNParams();
+ chi2 /= ndf;
+ return chi2;
+}
+
+//________________________________________________________________________________________________________
+void AliITSTPArrayFit::GetResiduals(Double_t *res,Int_t ipnt) const
+{
+ // calculate residuals at point
+ if (ipnt<fPntFirst || ipnt>fPntLast) {
+ AliError(Form("Attempt to access the point %d not in the fitted points [%d:%d]",ipnt,fPntFirst,fPntLast));
+ return;
+ }
+ GetPosition(res,fCurT[ipnt]);
+ res[kX] -= fPoints->GetX()[ipnt];
+ res[kY] -= fPoints->GetY()[ipnt];
+ res[kZ] -= fPoints->GetZ()[ipnt];
+}
+
+//________________________________________________________________________________________________________
+void AliITSTPArrayFit::GetPosition(Double_t *xyz, Double_t t) const
+{
+ // calculate track position for parameter value t
+ if (IsFieldON()) {
+ //
+ Double_t rrho = fParams[kD0]+fParams[kR0];
+ Double_t xc = rrho*TMath::Cos(fParams[kPhi0]);
+ Double_t yc = rrho*TMath::Sin(fParams[kPhi0]);
+ Double_t r = fParams[kR0];
+ Double_t ze = 0;
+ //
+ if (IsELossON()) {
+ if (t>0) {
+ for (int i=fFirstPosT;i<fNElsPnt;i++) { // along the track direction
+ int indE = fElsId[i];
+ if ( t<fCurT[indE] ) break; // does not reach this layer on its way to t
+ xc += fElsDR[indE] * TMath::Cos(fParams[kPhi0] + fCurT[indE]);
+ yc += fElsDR[indE] * TMath::Sin(fParams[kPhi0] + fCurT[indE]);
+ ze += fElsDR[indE] * fCurT[indE];
+ r += fElsDR[indE];
+ //printf("ELoss@ %+.2e r:%+.3e got %+.3e\n",fCurT[indE],r,fElsDR[indE]);
+ }
+ } else {
+ for (int i=fFirstPosT;i--;) { // against the track direction
+ int indE = fElsId[i];
+ if ( t>=fCurT[indE] ) break; // does not reach this layer on its way to t
+ xc += fElsDR[indE] * TMath::Cos(fParams[kPhi0] + fCurT[indE]);
+ yc += fElsDR[indE] * TMath::Sin(fParams[kPhi0] + fCurT[indE]);
+ ze += fElsDR[indE] * fCurT[indE];
+ r += fElsDR[indE];
+ //printf("ELoss@ %+.2e r:%+.3e got %+.3e\n",fCurT[indE],r,fElsDR[indE]);
+ }
+ }
+ }
+ //
+ xyz[kZ] = fParams[kDZ] - fParams[kDip]*(t*r - ze);
+ //
+ t += fParams[kPhi0];
+ xyz[kX] = xc - r*TMath::Cos(t);
+ xyz[kY] = yc - r*TMath::Sin(t);
+ // printf("t: %+.3e xyz:%+.2e %+.2e %+.2e | R %+.6e -> %+.6e | sign %d\n",t-fParams[kPhi0],xyz[0],xyz[1],xyz[2],fParams[kR0],r,GetSignQB());
+ }
+ else {
+ xyz[ fkAxID[kX] ] = fParams[kA0] + fParams[kB0]*t;
+ xyz[ fkAxID[kY] ] = fParams[kA1] + fParams[kB1]*t;
+ xyz[ fParAxis ] = t;
+ }
+}
+
+//________________________________________________________________________________________________________
+void AliITSTPArrayFit::GetDirCos(Double_t *dircos, Double_t t) const
+{
+ // calculate track direction cosines for parameter value t
+ if (IsFieldON()) {
+ dircos[kZ] = -fParams[kDip];
+ t += fParams[kPhi0];
+ dircos[kX] = TMath::Sin(t);
+ dircos[kY] =-TMath::Cos(t);
+ double gam = TMath::Sign(1/TMath::Sqrt(dircos[kZ]*dircos[kZ]+dircos[kY]*dircos[kY]+dircos[kX]*dircos[kX]),fParams[kR0]);
+ for (int i=3;i--;) dircos[i] *= gam;
+ }
+ else {
+ double gam = 1/TMath::Sqrt( fParams[kB0]*fParams[kB0] + fParams[kB1]*fParams[kB1] + 1.);
+ dircos[ fkAxID[kX] ] = fParams[kB0]*gam;
+ dircos[ fkAxID[kY] ] = fParams[kB1]*gam;
+ dircos[ fParAxis ] = gam;
+ }
+}
+
+//________________________________________________________________________________________________________
+Double_t AliITSTPArrayFit::GetMachinePrec()
+{
+ // estimate machine precision
+ Double_t eps=1.0,a;
+ do { a = 1. + (eps=eps/2.0); } while(a>1.);
+ return TMath::Abs(2.*eps);
+}
+
+//________________________________________________________________________________________________________
+Bool_t AliITSTPArrayFit::FitHelixCrude(Int_t extQ)
+{
+ // crude estimate of helix parameters, w/o errors and Eloss.
+ // 1st fit the circle (R,xc,yc) by minimizing
+ // chi2 = sum{ (bx*xi + by*yi + xi^2+yi^2 + rho)^2 } vs bx,by,rho
+ // with bx = -2*xc, by = -2*yc , rho = xc^2+yc^2 - R2
+ //
+ // if charge is not imposed (extQ==0) then it will be determined from the collision type
+ //
+ Bool_t eloss = IsELossON();
+ //
+ int np = fPntLast - fPntFirst + 1;
+ if (np<2) { AliError("At least 3 points are needed for helix fit"); return kFALSE; }
+ //
+ const float *x=fPoints->GetX(),*y=fPoints->GetY(),*z=fPoints->GetZ(),*cov=fPoints->GetCov();
+ //
+ // linear circle fit --------------------------------------------------- >>>
+ Double_t sxx=0,sxy=0,syy=0,sx=0,sy=0,rhs0=0,rhs1=0,rhs2=0,minR=1E9;
+ int minRId = 0;
+ for (int i=fPntFirst;i<=fPntLast;i++) {
+ Double_t xx = x[i]*x[i];
+ Double_t yy = y[i]*y[i];
+ Double_t xy = x[i]*y[i];
+ Double_t xxyy = xx + yy;
+ //
+ sxx += xx;
+ sxy += xy;
+ syy += yy;
+ sx += x[i];
+ sy += y[i];
+ //
+ rhs0 -= xxyy*x[i];
+ rhs1 -= xxyy*y[i];
+ rhs2 -= xxyy;
+ //
+ // remember Id of the point closest to origin, to determine the charge
+ if (xxyy<minR) { minR = xxyy; minRId = i; }
+ //
+ if (eloss) { // find layer id
+ int lrid,volid = fPoints->GetVolumeID()[i];
+ if (volid>0) lrid = fgkActiveLrITS[AliGeomManager::VolUIDToLayer(fPoints->GetVolumeID()[i])-1];
+ else { // missing layer info, find from radius
+ double r = TMath::Sqrt(xxyy);
+ for (lrid=kMaxLrITS;lrid--;) if ( IsZero(r-fgkRLayITS[ lrid ],1.) ) break;
+ }
+ fElsDR[i] = (lrid>=0 && lrid<kMaxLrITS) ? fgRhoLITS[ lrid ] : 0; // eloss for normal track
+ }
+ //
+ }
+ //
+ Double_t mn00 = syy*np-sy*sy;
+ Double_t mn01 = sxy*np-sy*sx;
+ Double_t mn02 = sxy*sy-syy*sx;
+ Double_t det = sxx*mn00 - sxy*mn01 + sx*mn02;
+ if (TMath::Abs(det)<fgkAlmostZero) return kFALSE;
+ //
+ Double_t mn11 = sxx*np-sx*sx;
+ Double_t mn12 = sxx*sy-sxy*sx;
+ Double_t mn22 = sxx*syy-sxy*sxy;
+ //
+ Double_t mi00 = mn00/det;
+ Double_t mi01 = -mn01/det;
+ Double_t mi02 = mn02/det;
+ Double_t mi11 = mn11/det;
+ Double_t mi12 = -mn12/det;
+ Double_t mi22 = mn22/det;
+ //
+ Double_t xc = -(rhs0*mi00 + rhs1*mi01 + rhs2*mi02)/2;
+ Double_t yc = -(rhs0*mi01 + rhs1*mi11 + rhs2*mi12)/2;
+ Double_t rho2 = (rhs0*mi02 + rhs1*mi12 + rhs2*mi22);
+ //
+ Double_t dcen = xc*xc + yc*yc;
+ Double_t rad = dcen - rho2;
+ rad = (rad>fgkAlmostZero) ? (TMath::Sqrt(rad)):fgkAlmostZero;
+ //
+ // printf("Rad: %+e xc: %+e yc: %+e\n",rad,xc,yc);
+ // linear circle fit --------------------------------------------------- <<<
+ //
+ // decide sign(Q*B) and fill cicrle parameters ------------------------- >>>
+ int sqb;
+ if (extQ) {
+ SetCharge(extQ);
+ sqb = fBz<0 ? -GetCharge():GetCharge();
+ }
+ else {
+ // determine the charge from the collision type and field sign
+ // the negative Q*B will have positive Vc x V0 product Z component
+ // with Vc={-xc,-yc} : vector from circle center to the origin
+ // and V0 - track direction vector (take {0,-1,1} for cosmics)
+ // If Bz is not provided, assume positive Bz
+ sqb = ( IsTypeCosmics() ? xc:(yc*x[minRId]-xc*y[minRId]) ) > 0 ? -1:1;
+ SetCharge( fBz<0 ? -sqb : sqb);
+ }
+ //
+ dcen = TMath::Sqrt(dcen);
+ fParams[kD0] = dcen-rad;
+ Double_t phi = TMath::ATan2(yc,xc);
+ if (sqb<0) phi += TMath::Pi();
+ if (phi > TMath::Pi()) phi -= 2.*TMath::Pi();
+ else if (phi <-TMath::Pi()) phi += 2.*TMath::Pi();
+ fParams[kPhi0] = phi;
+ fParams[kR0] = sqb<0 ? -rad:rad;
+ //
+ // decide sign(Q*B) and fill cicrle parameters ------------------------- <<<
+ //
+ // find z-offset and dip + the parameter t of closest approach to hits - >>>
+ //
+ UInt_t hitLrPos=0; // pattern of hit layers at pos
+ UInt_t hitLrNeg=0; // and negative t's
+
+ Double_t ss=0,st=0,sz=0,stt=0,szt=0;
+ for (int i=fPntFirst;i<=fPntLast;i++) {
+ //
+ Double_t ze2 = cov[i*6 + kZZ];
+ Double_t t = TMath::ATan2(yc-y[i],xc-x[i]) - fParams[kPhi0]; // angle at measured z
+ if (fParams[kR0]<0) t += TMath::Pi();
+ if (t > TMath::Pi()) t -= TMath::Pi()*2;
+ else if (t <-TMath::Pi()) t += TMath::Pi()*2;
+ if (ze2<fgkAlmostZero) ze2 = 1E-8;
+ ze2 = 1./ze2;
+ ss += ze2;
+ st += t*ze2;
+ stt+= t*t*ze2;
+ sz += z[i]*ze2;
+ szt+= z[i]*t*ze2;
+ //
+ fCurT[i] = t; // parameter of the closest approach to the point
+ // printf("%d %+e %+e %+e %+e\n",i,x[i],y[i],z[i],t);
+ if (eloss) {
+ double r = TMath::Sqrt(x[i]*x[i]+y[i]*y[i]);
+ int lr;
+ for (lr=kMaxLrITS;lr--;) if ( IsZero(r-fgkRLayITS[ lr ],1.) ) break;
+ if (lr<kMaxLrITS) {
+ if (t>0) hitLrPos |= (1<<lr); // set bit of the layer
+ else hitLrNeg |= (1<<lr); // set bit of the layer
+ }
+ }
+ }
+ det = ss*stt - st*st;
+ if (TMath::Abs(det)<fgkAlmostZero) { // no Z dependence
+ fParams[kDZ] = sz/ss;
+ fParams[kDip] = 0;
+ }
+ else {
+ fParams[kDZ] = (sz*stt-st*szt)/det;
+ fParams[kDip] = -(ss*szt-st*sz)/det/fParams[kR0];
+ }
+ //
+ // find z-offset and dip + the parameter t of closest approach to hits - <<<
+ //
+ // fill info needed to account for ELoss ------------------------------- >>>
+ if (eloss) {
+ fNElsPnt = fPntLast - fPntFirst + 1;
+ //
+ // to account for the energy loss in the passive volumes, calculate the relevant t-parameters
+ double* tcur = fCurT + fPntFirst;
+ double* ecur = fElsDR+ fPntFirst;
+ //
+ for (int ilp=3;ilp--;) {
+ int id = fgkPassivLrITS[ilp];
+ double tp = GetHelixParAtR( fgkRLayITS[ id ] );
+ if (tp<0) continue; // does not hit this radius
+ //
+ tcur[fNElsPnt] = GetSignQB()>0 ? -tp : tp;
+ ecur[fNElsPnt] = fgRhoLITS[ id ];
+ fNElsPnt++;
+ // printf("Passive on lr %d %+e\n",ilp,tcur[fNElsPnt-1]);
+ //
+ if (IsTypeCosmics() && !IsZero(tp)) { // 2 crossings for cosmics
+ tcur[fNElsPnt] = -tcur[fNElsPnt-1];
+ ecur[fNElsPnt] = ecur[fNElsPnt-1];
+ fNElsPnt++;
+ //printf("Passive* on lr %d %+e\n",ilp,-tcur[fNElsPnt-1]);
+ }
+ //
+ }
+ // check if some active layers did not miss the hit, treat them as passive
+ for (int ilp=6;ilp--;) {
+ int id = fgkActiveLrITS[ilp];
+ double tp = GetHelixParAtR( fgkRLayITS[ id ] );
+ if (tp<0) continue; // does not hit this radius
+ //
+ if ( (GetSignQB()>0||IsTypeCosmics()) && !(hitLrNeg & (1<<id)) ) {
+ tcur[fNElsPnt] = -tp;
+ ecur[fNElsPnt] = fgRhoLITS[ id ];
+ fNElsPnt++;
+ //printf("Missed on lr %d %+e\n",ilp,-tp);
+ }
+ //
+ if ( (GetSignQB()<0||IsTypeCosmics()) && !(hitLrPos & (1<<id)) ) {
+ tcur[fNElsPnt] = tp;
+ ecur[fNElsPnt] = fgRhoLITS[ id ];
+ fNElsPnt++;
+ //printf("Missed* on lr %d %e\n",ilp,tp);
+ }
+ }
+ //
+ TMath::Sort(fNElsPnt,fCurT+fPntFirst,fElsId,kFALSE); // index e-loss points in increasing order
+ // find the position of smallest positive t-param
+ for (fFirstPosT=0;fFirstPosT<fNElsPnt;fFirstPosT++) if (fCurT[ fElsId[ fFirstPosT ] ]>0) break;
+ //
+ Double_t cdip = 1./TMath::Sqrt(1.+fParams[kDip]*fParams[kDip]);
+ Double_t ptot = TMath::Abs(fParams[kR0]*fgkCQConv*fBz/cdip); // momentum and energy
+ Double_t etot = TMath::Sqrt(ptot*ptot + fMass*fMass); // in the point of closest approach to beam
+ Double_t normS[3];
+ //
+ // Positive t-params: along the track direction for negative track, against for positive
+ Double_t pcur = ptot, ecurr = etot;
+ for (int ip=fFirstPosT;ip<fNElsPnt;ip++) {
+ int tID = fElsId[ip];
+ Double_t t = fCurT[ tID ];
+ //
+ if (tID>fPntLast) { // this is not a hit layer but passive layer
+ double php = TMath::ATan2(yc-fParams[kR0]*TMath::Cos(fParams[kPhi0]+t),
+ xc-fParams[kR0]*TMath::Cos(fParams[kPhi0]+t));
+ normS[0] = -TMath::Cos(php); // normal to the cylinder at intersection point
+ normS[1] = -TMath::Sin(php);
+ normS[2] = 0;
+ }
+ else GetNormal(normS,fPoints->GetCov()+tID*6); // vector normal to hit module
+ fElsDR[tID] = GetDRofELoss(t,cdip,fElsDR[tID],normS,ptot,etot);
+ }
+ //
+ // negaive t-params: against the track direction for negative track, along for positive
+ pcur = ptot;
+ ecurr = etot;
+ for (int ip=fFirstPosT;ip--;) {
+ int tID = fElsId[ip];
+ Double_t t = fCurT[ tID ];
+ //
+ if (tID>fPntLast) { // this is not a hit layer but passive layer
+ double php = TMath::ATan2(yc-fParams[kR0]*TMath::Cos(fParams[kPhi0]+t),
+ xc-fParams[kR0]*TMath::Cos(fParams[kPhi0]+t));
+ normS[0] = -TMath::Cos(php); // normal to the cylinder at intersection point
+ normS[1] = -TMath::Sin(php);
+ normS[2] = 0;
+ }
+ else GetNormal(normS,fPoints->GetCov()+tID*6); // vector normal to hit module
+ //
+ fElsDR[tID] = GetDRofELoss(t,cdip,fElsDR[tID],normS,ptot,etot);
+ }
+ }
+ // fill info needed to account for ELoss ------------------------------- <<<
+ //
+ return kTRUE;
+}
+
+//____________________________________________________
+Double_t AliITSTPArrayFit::FitHelix(Int_t extQ, Double_t extPT,Double_t extPTerr)
+{
+ // fit by helix accounting for the errors of all coordinates (and energy loss if requested)
+ //
+ // If extQ is non-0, its sign is imposed as a charge of the track
+ // If extPT>0 and extPTerr>=0, constrain to measured tr.momentum PT
+ // with corresponding error (err=0 -> rel.err=1e-6)
+ //
+ double chiprev=1e99;
+ //const Double_t kMaxTEffect = 1E-6;
+ Double_t dXYZdGlo[3*5],dXYZdLoc[3],xyzRes[3];
+ //
+ SetFitDone(kFALSE);
+ fChi2NDF = -1;
+ //
+ if (!FitHelixCrude(extQ)) return -1; // get initial estimate, ignoring the errors
+ //
+ if (!IsCovInv()) InvertPointsCovMat(); // prepare inverted errors
+ if (!fParSol) fParSol = new AliParamSolver(5);
+ fParSol->SetNGlobal(5);
+ //
+ // printf("-1 | %+.2e %+.2e %+.2e %+.2e %+.2e | chi2: %+.4e\n",fParams[0],fParams[1],fParams[2],fParams[3],fParams[4],CalcChi2NDF());
+ int iter = 0;
+ fChi2NDF = 1e99;
+ Bool_t converged = kFALSE;
+ while(iter<fMaxIter) {
+ chiprev = fChi2NDF;
+ fParSol->Clear();
+ for (int ip=fPntFirst;ip<=fPntLast;ip++) {
+ //
+ GetResiduals(xyzRes, ip); // current residuals at point ip
+ Double_t rrho = fParams[kR0]+fParams[kD0];
+ Double_t cs0 = TMath::Cos(fParams[kPhi0]);
+ Double_t sn0 = TMath::Sin(fParams[kPhi0]);
+ Double_t cst = TMath::Cos(fCurT[ip]+fParams[kPhi0]);
+ Double_t snt = TMath::Sin(fCurT[ip]+fParams[kPhi0]);
+ //
+ int offs = kD0; // dXYZ/dD0
+ dXYZdGlo[offs + kX] = cs0;
+ dXYZdGlo[offs + kY] = sn0;
+ dXYZdGlo[offs + kZ] = 0;
+ //
+ offs = kPhi0*3; // dXYZ/dPhi0
+ dXYZdGlo[offs + kX] = -rrho*sn0;
+ dXYZdGlo[offs + kY] = rrho*cs0;
+ dXYZdGlo[offs + kZ] = 0;
+ //
+ offs = kR0*3; // dXYZ/dR0
+ dXYZdGlo[offs + kX] = cs0 - cst;
+ dXYZdGlo[offs + kY] = sn0 - snt;
+ dXYZdGlo[offs + kZ] = -fParams[kDip]*fCurT[ip];
+ //
+ offs = kDZ*3; // dXYZ/dDZ
+ dXYZdGlo[offs + kX] = 0;
+ dXYZdGlo[offs + kY] = 0;
+ dXYZdGlo[offs + kZ] = 1.;
+ //
+ offs = kDip*3; // dXYZ/dDip
+ dXYZdGlo[offs + kX] = 0;
+ dXYZdGlo[offs + kY] = 0;
+ dXYZdGlo[offs + kZ] = -fParams[kR0]*fCurT[ip];
+ //
+ dXYZdLoc[kX] = fParams[kR0]*snt;
+ dXYZdLoc[kY] = -fParams[kR0]*cst;
+ dXYZdLoc[kZ] = -fParams[kR0]*fParams[kDip];
+ //
+ fParSol->AddEquation(dXYZdGlo,dXYZdLoc,xyzRes,GetCovI(ip));
+ }
+ //
+ if (extPT>0) { // add constraint on pt
+ if (extPTerr<fgkAlmostZero) extPTerr = 1e-6*extPT;
+ Double_t cf = fBz*GetCharge()*fgkCQConv;
+ Double_t err2i = extPTerr/cf;
+ err2i = 1./err2i/err2i;
+ // printf("Constrain R to %+e\n",extPT/cf);
+ fParSol->AddConstraint(kR0,-extPT/cf+fParams[kR0],err2i);
+ }
+ if (!fParSol->Solve()) { AliError("Failed to fit helix"); return -1; }
+ Double_t *deltaG = fParSol->GetGlobals();
+ Double_t *deltaT = fParSol->GetLocals();
+ for (int ipar=5;ipar--;) fParams[ipar] -= deltaG[ipar];
+ for (int ip=fPntFirst;ip<=fPntLast;ip++) fCurT[ip] -= deltaT[ip-fPntFirst];
+ iter++;
+ //
+ fChi2NDF = CalcChi2NDF();
+ // printf("%d | %+.2e %+.2e %+.2e %+.2e %+.2e | chi2: %+.4e %+.4e\n",iter,deltaG[0],deltaG[1],deltaG[2],deltaG[3],deltaG[4],fChi2NDF,fChi2NDF-chiprev);
+ // printf("->> %+.2e %+.2e %+.2e %+.2e %+.2e | Chi2: %+.6e %+.6e\n",fParams[0],fParams[1],fParams[2],fParams[3],fParams[4],fChi2NDF,fChi2NDF-chiprev);
+ double difchi2 = chiprev - fChi2NDF;
+ if ( difchi2<fEps && TMath::Abs(difchi2)<1e-4) {converged = kTRUE; break;}
+ // if (errT*TMath::Abs(fParams[kR0])<kMaxTEffect && errP<fEps) {converged = kTRUE; break;}
+ }
+ //
+ if (!converged) {
+ AliDebug(2,Form("Max number of %d iteration reached, Current chi2:%.3e, chi2 change %+.3e",iter,
+ fChi2NDF,chiprev-fChi2NDF));
+ for (int ip=fPntFirst;ip<=fPntLast;ip++)
+ AliDebug(2,Form("P%2d| %+.3e %+.3e %+.3e\n",ip,fPoints->GetX()[ip],fPoints->GetY()[ip],fPoints->GetZ()[ip]));
+
+ }
+ fIter = iter;
+ SetCharge( fParams[kR0]>0 ? (fBz<0?-1:1):(fBz>0?-1:1) );
+ SetFitDone();
+ // printf("F1>> %+.7e %+.7e %+.7e %+.7e %.7e\n",fParams[0],fParams[1],fParams[2],fParams[3],fParams[4]);
+ //
+ return fChi2NDF;
+}
+
+//____________________________________________________
+Double_t AliITSTPArrayFit::FitLine()
+{
+ // fit by helix accounting for the errors of all coordinates (and energy loss if requested)
+ //
+ double chiprev=1e99;
+ // const Double_t kMaxTEffect = 1.e-6;
+ Double_t dXYZdGlo[3*4],dXYZdLoc[3],xyzRes[3];
+ SetFitDone(kFALSE);
+ fChi2NDF = -1;
+ //
+ if (fParAxis<0) SetParAxis(ChoseParAxis());
+ //
+ const float *xyzp[3]={fPoints->GetX(),fPoints->GetY(),fPoints->GetZ()};
+ if (!IsCovInv()) InvertPointsCovMat();
+ if (!FitLineCrude()) return -1; // get initial estimate, ignoring the errors
+ //
+ if (!fParSol) fParSol = new AliParamSolver(5);
+ fParSol->SetNGlobal(4);
+ // initial set of parameters
+ for (int ip=fPntFirst;ip<=fPntLast;ip++) fCurT[ip] = xyzp[fParAxis][ip]; // use measured param-coordinate
+ //
+ int iter = 0;
+ Bool_t converged = kFALSE;
+ fChi2NDF = 1e99;
+ while(iter<fMaxIter) {
+ chiprev = fChi2NDF;
+ fParSol->Clear();
+ for (int ip=fPntFirst;ip<=fPntLast;ip++) {
+ //
+ int offs;
+ GetResiduals(xyzRes, ip); // current residuals at point ip
+ //
+ offs = kA0*3; // dXYZ/dA0
+ dXYZdGlo[offs + fkAxID[kX]] = 1;
+ dXYZdGlo[offs + fkAxID[kY]] = 0;
+ dXYZdGlo[offs + fParAxis ] = 0;
+ //
+ offs = kB0*3; // dXYZ/dB0
+ dXYZdGlo[offs + fkAxID[kX]] = fCurT[ip];
+ dXYZdGlo[offs + fkAxID[kY]] = 0;
+ dXYZdGlo[offs + fParAxis ] = 0;
+ //
+ offs = kA1*3; // dXYZ/dA1
+ dXYZdGlo[offs + fkAxID[kX]] = 0;
+ dXYZdGlo[offs + fkAxID[kY]] = 1;
+ dXYZdGlo[offs + fParAxis ] = 0;
+ //
+ offs = kB1*3; // dXYZ/dB1
+ dXYZdGlo[offs + fkAxID[kX]] = 0;
+ dXYZdGlo[offs + fkAxID[kY]] = fCurT[ip];
+ dXYZdGlo[offs + fParAxis ] = 0;
+ //
+ dXYZdLoc[ fkAxID[kX] ] = fParams[kB0]; // dX/dt
+ dXYZdLoc[ fkAxID[kY] ] = fParams[kB1]; // dY/dt
+ dXYZdLoc[ fParAxis ] = 1;
+ //
+ fParSol->AddEquation(dXYZdGlo,dXYZdLoc,xyzRes,GetCovI(ip));
+ }
+ //
+ if (!fParSol->Solve()) { AliError("Failed to fit line"); return -1; }
+ Double_t *deltaG = fParSol->GetGlobals();
+ Double_t *deltaT = fParSol->GetLocals();
+ for (int ipar=4;ipar--;) fParams[ipar] -= deltaG[ipar];
+ for (int ip=fPntFirst;ip<=fPntLast;ip++) fCurT[ip] -= deltaT[ip-fPntFirst];
+ iter++;
+ fChi2NDF = CalcChi2NDF();
+ // printf("%d %+e %+e | %+.2e %+.2e %+.2e %+.2e | chi2: %+.4e %+.4e\n",iter,errP,errT, deltaG[0],deltaG[1],deltaG[2],deltaG[3],fChi2NDF,fChi2NDF-chiprev);
+ // printf("->> %+.2e %+.2e %+.2e %+.2e %+.2e | Chi2: %+.6e %+.6e\n",fParams[0],fParams[1],fParams[2],fParams[3],fParams[4],fChi2NDF,fChi2NDF-chiprev);
+ double difchi2 = chiprev - fChi2NDF;
+ if ( difchi2<fEps && TMath::Abs(difchi2)<1e-4) {converged = kTRUE; break;}
+ chiprev = fChi2NDF;
+ // if (errT<kMaxTEffect && errP<fEps) {converged = kTRUE; break;}
+ }
+ //
+ if (!converged) {
+ AliDebug(2,Form("Max number of %d iteration reached, Current chi2:%.3e, chi2 change %+.3e",iter,
+ fChi2NDF,chiprev-fChi2NDF));
+ for (int ip=fPntFirst;ip<=fPntLast;ip++)
+ AliDebug(2,Form("P%2d| %+.3e %+.3e %+.3e\n",ip,fPoints->GetX()[ip],fPoints->GetY()[ip],fPoints->GetZ()[ip]));
+ }
+ fIter = iter;
+ SetFitDone();
+ //printf("F1>> %+.2e %+.2e %+.2e %+.2e\n",fParams[0],fParams[1],fParams[2],fParams[3]);
+ return fChi2NDF;
+ //
+}
+
+//____________________________________________________
+void AliITSTPArrayFit::GetNormal(Double_t *norm, const Float_t *covMat)
+{
+ // obtain the lab normal vector to the sensor from the covariance matrix
+ // in such a way that when the local frame of the sensor coincides with
+ // the lab frame, the vector {0,1,0} is obtained
+ Double_t tgxy = TMath::Tan(0.5*TMath::ATan2(2.*covMat[kXY],covMat[kYY]-covMat[kXX]));
+ Double_t tgyz = TMath::Tan(0.5*TMath::ATan2(2.*covMat[kYZ],covMat[kZZ]-covMat[kYY]));
+ norm[kY] = 1./TMath::Sqrt(1 + tgxy*tgxy + tgyz*tgyz);
+ norm[kX] = norm[kY]*tgxy;
+ norm[kZ] = norm[kY]*tgyz;
+ //
+}
+
+//____________________________________________________
+Double_t AliITSTPArrayFit::GetDRofELoss(Double_t t,Double_t cdip,Double_t rhoL,const Double_t *normS,
+ Double_t &p,Double_t &e) const
+{
+ // Calculate energy loss of the particle at given t-param on the layer with rhoL (thickness*density) with
+ // normal vector normS in the lab. The particle before eloss has energy "e" and momentum "p"
+ // cdip = cosine of the dip angle = 1/sqrt(1+tgL^2)
+ // Return the change DR of the radius due to the ELoss
+ //
+ // NOTE: with B>0 the negative particles propagate along increasing t-param and positive
+ // particles - against.
+ // t-param = 0 corresponds to the point of closest approach of the track to the beam.
+ // Since the fitted helix parameters of the track are defined in this PCA point, when the correction
+ // is applied upstream of the PCS, the energy must be increased (DR>0) rather than decreased (DR<0)
+ //
+ Double_t dirTr[3];
+ dirTr[0] = -TMath::Sin(fParams[kPhi0]+t);
+ dirTr[1] = TMath::Cos(fParams[kPhi0]+t);
+ dirTr[2] = fParams[kDip];
+ // cosine of the impact angle
+ Double_t cosImp = cdip*TMath::Abs(dirTr[0]*normS[0]+dirTr[1]*normS[1]+dirTr[2]*normS[2]);
+ //
+ if (cosImp<0.3) cosImp = 0.3; //?
+ Double_t dE = AliExternalTrackParam::BetheBlochSolid(p/fMass)*rhoL/cosImp;
+ Double_t dP = e/p*dE;
+ //
+ if (t*GetSignQB() < 0) {
+ dP = -dP;
+ dE = -dE;
+ }
+ //
+ if (p+dP<0) {
+ AliInfo(Form("Estimated PLoss %.3f is larger than particle momentum %.3f. Skipping",dP,p));
+ return 0;
+ }
+ //
+ p += dP;
+ e += dE;
+ //
+ return fCharge*dP*cdip/fBz/fgkCQConv;
+}
+
+//_____________________________________________________________
+Double_t AliITSTPArrayFit::GetLineOffset(Int_t axis) const
+{
+ // return intercept of the parameterization coord = intercept + slope*t for given axis
+ if (fParAxis<0) return -1E6; // no line fit
+ if (axis==fParAxis) return 0;
+ if (fParAxis==kX) return fParams[axis==kY ? kA0 : kA1 ];
+ if (fParAxis==kY) return fParams[axis==kZ ? kA0 : kA1 ];
+ return fParams[axis==kX ? kA0 : kA1 ];
+}
+
+//_____________________________________________________________
+Double_t AliITSTPArrayFit::GetLineSlope(Int_t axis) const
+{
+ // return intercept of the parameterization coord = intercept + slope*t for given axis
+ if (fParAxis<0) return -1E6; // no line fit
+ if (axis==fParAxis) return 1.;
+ if (fParAxis==kX) return fParams[axis==kY ? kB0 : kB1 ];
+ if (fParAxis==kY) return fParams[axis==kZ ? kB0 : kB1 ];
+ return fParams[axis==kX ? kB0 : kB1 ];
+}
+
+//_____________________________________________________________
+void AliITSTPArrayFit::Print(Option_t *) const
+{
+ const char kCxyz[] = "XYZ";
+ if (!fPoints) return;
+ //
+ printf("Track of %3d points in Bz=%+.1f |Fit ",fPntLast-fPntFirst+1,fBz);
+ if ( IsFitDone() ) {
+ if (IsFieldON())
+ printf("Helix: Chi2: %5.1f | %+.2e %+.2e %+.2e %+.2e %+.2e\n",
+ fChi2NDF,fParams[kD0],fParams[kPhi0],fParams[kR0],fParams[kDZ],fParams[kDip]);
+ else
+ printf("Line%c: Chi2: %5.1f | %+.2e %+.2e %+.2e %+.2e\n",
+ kCxyz[fParAxis],fChi2NDF,fParams[kA0],fParams[kB0],fParams[kA1],fParams[kB1]);
+ }
+ else printf("N/A\n");
+}
+
+
+
+
+//____________________________________________________
+void AliITSTPArrayFit::BuildMaterialLUT(Int_t ntri)
+{
+ // Fill a look-up table with mean material a la AliITSTrackerMI
+ //
+ if (!AliGeomManager::GetGeometry()) AliFatal("Geometry is not loaded");
+ //
+ // detector layer to check: dX,dZ,Ymin,Ymax
+ const double kLayr[9][4] = {{0. ,60. , 2.80,3.00}, // beam pipe
+ {1.28,7.07,-0.20,0.22}, // SPD1
+ {1.28,7.07,-0.20,0.22}, // SPD2
+ {0. ,76.0, 10.4,11.8}, // Shield1
+ {7.02,7.53,-1.00,4.50}, // SDD1
+ {7.02,7.53,-1.00,4.50}, // SDD2
+ {0. ,102., 29.0,30.0}, // Shield2
+ {7.50,4.20,-0.15,4.50}, // SSD1
+ {7.50,4.20,-0.15,4.50}}; // SSD2
+ //
+ //
+ // build <dens*L> for detectors (track hitting the sensor in normal direction)
+ double pg1[3],pg2[3],res[7];
+ //
+ int sID = 0;
+ int actLrID = 0;
+ for (int lr=0;lr<9;lr++) {
+ //
+ Bool_t active = kFALSE;
+ const double* tpars = kLayr[lr];
+ //
+ if (IsZero(tpars[0])) { // passive layer
+ active = kFALSE;
+ AliInfo(Form("Probing passive layer (total layer #%d)",lr));
+ }
+ else {
+ active = kTRUE;
+ sID += AliGeomManager::LayerSize(++actLrID);
+ AliInfo(Form("Probing sensors of active layer #%d (total layers #%d)",actLrID,lr));
+ }
+ double shift = TMath::Abs(tpars[2]-tpars[3])*1E-4;
+ double rhol = 0;
+ for (int i=ntri;i--;) {
+ //
+ if (active) {
+ int ssID = sID -1 - AliGeomManager::LayerSize(actLrID)*gRandom->Rndm();
+ pg1[0] = pg2[0] = (gRandom->Rndm()-0.5)*tpars[0] + shift; // local X
+ pg2[0] -= 2*shift;
+ pg1[1] = tpars[2];
+ pg2[1] = tpars[3];
+ pg1[2] = pg2[2] = (gRandom->Rndm()-0.5)*tpars[1] + shift; // local Z
+ pg2[2] -= 2*shift;
+ AliITSgeomTGeo::LocalToGlobal(ssID,pg1,pg1);
+ AliITSgeomTGeo::LocalToGlobal(ssID,pg2,pg2);
+ }
+ else {
+ double ang = gRandom->Rndm()*TMath::Pi()*2;
+ pg1[0] = tpars[2]*TMath::Cos(ang)+shift;
+ pg2[0] = tpars[3]*TMath::Cos(ang)-shift;
+ pg1[1] = tpars[2]*TMath::Sin(ang);
+ pg2[1] = tpars[3]*TMath::Sin(ang);
+ pg1[2] = pg2[2] = (gRandom->Rndm()-0.5)*tpars[1]+shift; // local Z
+ pg2[2] -= 2*shift;
+ }
+
+ //
+ AliTracker::MeanMaterialBudget(pg1,pg2,res);
+ rhol += res[0]*res[4]; // rho*L
+ }
+ fgRhoLITS[lr] = rhol/ntri;
+ AliInfo(Form("Obtained <rho*L> = %e\n",fgRhoLITS[lr]));
+ }
+ //
+ return;
+}
+
+
+//____________________________________________________
+Double_t AliITSTPArrayFit::GetPCA2PlaneInfo(Double_t *xyz, Double_t *dir, Int_t axis, Double_t axval) const
+{
+ // calculate the PCA to plane normal ti axis and crossing it at axval
+ // fill the position and direction cosines at this point
+ //
+ double xyzp[3] = {0,0,0}; // create fake point
+ xyzp[axis] = axval;
+ double covI[6] = {1e-4,0,0,1e-4,0,1e-4}; // fake cov.matrix loose in all directions
+ covI[4*axis - axis*(axis+1)/2] = 1e8; // except axis
+ //
+ double t = GetPosition(xyz, xyzp, covI); // got pca
+ //
+ if (dir) GetDirCos(dir,t);
+ return t;
+}
+