1 /**********************************************************************************************/
2 /* General class for alignment with large number of degrees of freedom */
3 /* Based on the original milliped2 by Volker Blobel */
4 /* http://www.desy.de/~blobel/mptalks.html */
6 /* Author: ruben.shahoyan@cern.ch */
8 /**********************************************************************************************/
10 #include "AliMillePede2.h"
12 #include <TStopwatch.h>
19 #include "AliMatrixSq.h"
20 #include "AliSymMatrix.h"
21 #include "AliRectMatrix.h"
22 #include "AliMatrixSparse.h"
26 #include <sys/types.h>
34 ClassImp(AliMillePede2)
36 Bool_t AliMillePede2::fgInvChol = kTRUE; // Invert global matrix with Cholesky solver
37 Bool_t AliMillePede2::fgWeightSigma = kTRUE; // weight local constraint by module statistics
38 Bool_t AliMillePede2::fgIsMatGloSparse = kFALSE; // use faster dense matrix by default
39 Int_t AliMillePede2::fgMinResCondType = 1; // Jacoby preconditioner by default
40 Double_t AliMillePede2::fgMinResTol = 1.e-11; // default tolerance
41 Int_t AliMillePede2::fgMinResMaxIter = 10000; // default max number of iterations
42 Int_t AliMillePede2::fgIterSol = AliMinResSolve::kSolMinRes; // default iterative solver
43 Int_t AliMillePede2::fgNKrylovV = 240; // default number of Krylov vectors to keep
45 //_____________________________________________________________________________________________
46 AliMillePede2::AliMillePede2()
56 fNLagrangeConstraints(0),
60 fGloSolveStatus(gkFailed),
90 fDataRecFName("/tmp/mp2_data_records.root"),
96 fConstrRecFName("/tmp/mp2_constraints_records.root"),
108 //_____________________________________________________________________________________________
109 AliMillePede2::AliMillePede2(const AliMillePede2& src) :
110 TObject(src),fNLocPar(0),fNGloPar(0),fNGloSize(0),fNLocEquations(0),fIter(0),
111 fMaxIter(10),fNStdDev(3),fNGloConstraints(0),fNLagrangeConstraints(0),
112 fNLocFits(0),fNLocFitsRejected(0),
113 fNGloFix(0),fGloSolveStatus(0),fChi2CutFactor(0),fChi2CutRef(0),fResCutInit(0),
114 fResCut(0),fMinPntValid(1),fNGroupsSet(0),fParamGrID(0),fProcPnt(0),fVecBLoc(0),fDiagCGlo(0),fVecBGlo(0),
115 fInitPar(0),fDeltaPar(0),fSigmaPar(0),fIsLinear(0),fConstrUsed(0),fGlo2CGlo(0),fCGlo2Glo(0),
116 fMatCLoc(0),fMatCGlo(0),fMatCGloLoc(0),fFillIndex(0),fFillValue(0),
117 fDataRecFName(0),fRecord(0),fDataRecFile(0),
118 fTreeData(0),fRecFileStatus(0),fConstrRecFName(0),fTreeConstr(0),fConsRecFile(0),fCurrRecDataID(0),
119 fCurrRecConstrID(0),fLocFitAdd(kTRUE),
126 //_____________________________________________________________________________________________
127 AliMillePede2::~AliMillePede2()
129 CloseDataRecStorage();
130 CloseConsRecStorage();
143 delete[] fConstrUsed;
155 //_____________________________________________________________________________________________
156 Int_t AliMillePede2::InitMille(int nGlo, int nLoc, int lNStdDev,double lResCut, double lResCutInit)
159 if (nLoc>0) fNLocPar = nLoc;
160 if (nGlo>0) fNGloPar = nGlo;
161 if (lResCutInit>0) fResCutInit = lResCutInit;
162 if (lResCut>0) fResCut = lResCut;
163 if (lNStdDev>0) fNStdDev = lNStdDev;
165 fNGloSize = fNGloPar;
169 if (fgIsMatGloSparse) {fMatCGlo = new AliMatrixSparse(fNGloPar); fMatCGlo->SetSymmetric(kTRUE);}
170 else fMatCGlo = new AliSymMatrix(fNGloPar);
172 fFillIndex = new Int_t[fNGloPar];
173 fFillValue = new Double_t[fNGloPar];
175 fMatCLoc = new AliSymMatrix(fNLocPar);
176 fMatCGloLoc = new AliRectMatrix(fNGloPar,fNLocPar);
178 fParamGrID = new Int_t[fNGloPar];
179 fProcPnt = new Int_t[fNGloPar];
180 fVecBLoc = new Double_t[fNLocPar];
181 fDiagCGlo = new Double_t[fNGloPar];
183 fInitPar = new Double_t[fNGloPar];
184 fDeltaPar = new Double_t[fNGloPar];
185 fSigmaPar = new Double_t[fNGloPar];
186 fIsLinear = new Bool_t[fNGloPar];
188 fGlo2CGlo = new Int_t[fNGloPar];
189 fCGlo2Glo = new Int_t[fNGloPar];
192 AliInfo(Form("Failed to allocate the memory for %d global and %d local parameters",fNGloPar,fNLocPar));
196 memset(fVecBLoc ,0,fNLocPar*sizeof(Double_t));
197 memset(fDiagCGlo ,0,fNGloPar*sizeof(Double_t));
198 memset(fInitPar ,0,fNGloPar*sizeof(Double_t));
199 memset(fDeltaPar ,0,fNGloPar*sizeof(Double_t));
200 memset(fSigmaPar ,0,fNGloPar*sizeof(Double_t));
201 memset(fProcPnt ,0,fNGloPar*sizeof(Int_t));
203 for (int i=fNGloPar;i--;) {
204 fGlo2CGlo[i] = fCGlo2Glo[i] = -1;
205 fIsLinear[i] = kTRUE;
212 //_____________________________________________________________________________________________
213 Bool_t AliMillePede2::ImposeDataRecFile(const char* fname)
215 CloseDataRecStorage();
216 SetDataRecFName(fname);
217 return InitDataRecStorage(kTRUE); // open in read mode
220 //_____________________________________________________________________________________________
221 Bool_t AliMillePede2::ImposeConsRecFile(const char* fname)
223 CloseConsRecStorage();
224 SetConsRecFName(fname);
225 return InitConsRecStorage(kTRUE); // open in read mode
228 //_____________________________________________________________________________________________
229 Bool_t AliMillePede2::InitDataRecStorage(Bool_t read)
231 // initialize the buffer for processed measurements records
233 if (fTreeData) {AliInfo("Data Records File is already initialized"); return kFALSE;}
235 if (!fRecord) fRecord = new AliMillePedeRecord();
237 if (!read) { // write mode: cannot use chain
238 fDataRecFile = TFile::Open(GetDataRecFName(),"recreate");
239 if (!fDataRecFile) {AliFatal(Form("Failed to initialize data records file %s",GetDataRecFName())); return kFALSE;}
240 AliInfo(Form("File %s used for derivatives records",GetDataRecFName()));
241 fTreeData = new TTree("AliMillePedeRecords_Data","Data Records for AliMillePede2");
242 fTreeData->Branch("Record_Data","AliMillePedeRecord",&fRecord,32000,99);
245 TChain* ch = new TChain("AliMillePedeRecords_Data");
247 if (fDataRecFName.EndsWith(".root")) ch->AddFile(fDataRecFName);
248 else { // assume text file with list of filenames
250 ifstream inpf(fDataRecFName.Data());
251 if (!inpf.good()) {AliInfo(Form("Failed on input records list %s\n",fDataRecFName.Data())); return kFALSE;}
254 while ( !(recfName.ReadLine(inpf)).eof() ) {
255 recfName = recfName.Strip(TString::kBoth,' ');
256 if (recfName.BeginsWith("//") || recfName.BeginsWith("#") || !recfName.EndsWith(".root")) { // comment
257 AliInfo(Form("Skip %s\n",recfName.Data()));
261 recfName = recfName.Strip(TString::kBoth,',');
262 recfName = recfName.Strip(TString::kBoth,'"');
263 gSystem->ExpandPathName(recfName);
264 printf("Adding %s\n",recfName.Data());
265 ch->AddFile(recfName.Data());
269 Long64_t nent = ch->GetEntries();
270 if (nent<1) { AliInfo("Obtained chain is empty"); return kFALSE;}
272 fTreeData->SetBranchAddress("Record_Data",&fRecord);
273 AliInfo(Form("Found %lld derivatives records",nent));
276 fRecFileStatus = read ? 1:2;
281 //_____________________________________________________________________________________________
282 Bool_t AliMillePede2::InitConsRecStorage(Bool_t read)
284 // initialize the buffer for processed measurements records
286 if (fConsRecFile) {AliInfo("Constraints Records File is already initialized"); return kFALSE;}
288 if (!fRecord) fRecord = new AliMillePedeRecord();
290 fConsRecFile = TFile::Open(GetConsRecFName(),read ? "":"recreate");
291 if (!fConsRecFile) {AliInfo(Form("Failed to initialize constraints records file %s",GetConsRecFName())); return kFALSE;}
293 AliInfo(Form("File %s used for constraints records",GetConsRecFName()));
295 fTreeConstr = (TTree*)fConsRecFile->Get("AliMillePedeRecords_Constraints");
296 if (!fTreeConstr) {AliInfo(Form("Did not find constraints records tree in %s",GetConsRecFName())); return kFALSE;}
297 fTreeConstr->SetBranchAddress("Record_Constraints",&fRecord);
298 AliInfo(Form("Found %lld constraints records",fTreeConstr->GetEntries()));
303 fTreeConstr = new TTree("AliMillePedeRecords_Constraints","Constraints Records for AliMillePede2");
304 fTreeConstr->Branch("Record_Constraints","AliMillePedeRecord",&fRecord,32000,99);
306 fCurrRecConstrID = -1;
311 //_____________________________________________________________________________________________
312 void AliMillePede2::CloseDataRecStorage()
315 if (fDataRecFile && fDataRecFile->IsWritable()) {
322 fDataRecFile->Close();
331 //_____________________________________________________________________________________________
332 void AliMillePede2::CloseConsRecStorage()
335 if (fConsRecFile->IsWritable()) {
337 fTreeConstr->Write();
341 fConsRecFile->Close();
348 //_____________________________________________________________________________________________
349 Bool_t AliMillePede2::ReadNextRecordData()
351 // read next data record (if any)
352 if (!fTreeData || ++fCurrRecDataID >= fTreeData->GetEntries()) { fCurrRecDataID--; return kFALSE;}
353 fTreeData->GetEntry(fCurrRecDataID);
357 //_____________________________________________________________________________________________
358 Bool_t AliMillePede2::ReadNextRecordConstraint()
360 // read next constraint record (if any)
361 if (!fTreeConstr || ++fCurrRecConstrID >= fTreeConstr->GetEntries()) { fCurrRecConstrID--; return kFALSE;}
362 fTreeConstr->GetEntry(fCurrRecConstrID);
366 //_____________________________________________________________________________________________
367 void AliMillePede2::SetRecordWeight(double wgh)
369 if (fRecFileStatus<2) InitDataRecStorage(); // create a buffer to store the data
370 fRecord->SetWeight(wgh);
373 //_____________________________________________________________________________________________
374 void AliMillePede2::SetRecordRun(Int_t run)
376 if (fRecFileStatus<2) InitDataRecStorage(); // create a buffer to store the data
377 fRecord->SetRunID(run);
380 //_____________________________________________________________________________________________
381 void AliMillePede2::SetLocalEquation(double *dergb, double *derlc, double lMeas, double lSigma)
383 if (fRecFileStatus<2) InitDataRecStorage(); // create a buffer to store the data
385 // write data of single measurement
386 if (lSigma<=0.0) { // If parameter is fixed, then no equation
387 for (int i=fNLocPar; i--;) derlc[i] = 0.0;
388 for (int i=fNGloPar; i--;) dergb[i] = 0.0;
392 fRecord->AddResidual(lMeas);
394 // Retrieve local param interesting indices
395 for (int i=0;i<fNLocPar;i++) if (!IsZero(derlc[i])) {fRecord->AddIndexValue(i,derlc[i]); derlc[i] = 0.0;}
397 fRecord->AddWeight( 1.0/lSigma/lSigma );
399 // Idem for global parameters
400 for (int i=0;i<fNGloPar;i++) if (!IsZero(dergb[i])) {
401 fRecord->AddIndexValue(i,dergb[i]); dergb[i] = 0.0;
402 fRecord->MarkGroup(fParamGrID[i]);
407 //_____________________________________________________________________________________________
408 void AliMillePede2::SetLocalEquation(int *indgb, double *dergb, int ngb, int *indlc,
409 double *derlc,int nlc,double lMeas,double lSigma)
411 // write data of single measurement
412 if (lSigma<=0.0) { // If parameter is fixed, then no equation
413 for (int i=nlc;i--;) derlc[i] = 0.0;
414 for (int i=ngb;i--;) dergb[i] = 0.0;
418 if (fRecFileStatus<2) InitDataRecStorage(); // create a buffer to store the data
420 fRecord->AddResidual(lMeas);
422 // Retrieve local param interesting indices
423 for (int i=0;i<nlc;i++) if (!IsZero(derlc[i])) {fRecord->AddIndexValue(indlc[i],derlc[i]); derlc[i]=0.; indlc[i]=0;}
425 fRecord->AddWeight( 1./lSigma/lSigma );
427 // Idem for global parameters
428 for (int i=0;i<ngb;i++) if (!IsZero(dergb[i])) {fRecord->AddIndexValue(indgb[i],dergb[i]); dergb[i]=0.; indgb[i]=0;}
433 //_____________________________________________________________________________________________
434 void AliMillePede2::SetGlobalConstraint(double *dergb, double val, double sigma)
436 // Define a constraint equation.
437 if (!fConsRecFile || !fConsRecFile->IsWritable()) InitConsRecStorage(); // create a buffer to store the data
440 fRecord->AddResidual(val);
441 fRecord->AddWeight(sigma);
442 for (int i=0; i<fNGloPar; i++) if (!IsZero(dergb[i])) fRecord->AddIndexValue(i,dergb[i]);
444 if (IsZero(sigma)) fNLagrangeConstraints++;
445 // printf("NewConstraint:\n"); fRecord->Print(); //RRR
446 SaveRecordConstraint();
450 //_____________________________________________________________________________________________
451 void AliMillePede2::SetGlobalConstraint(const int *indgb, double *dergb, int ngb, double val,double sigma)
453 // Define a constraint equation.
454 if (!fConsRecFile || !fConsRecFile->IsWritable()) InitConsRecStorage(); // create a buffer to store the data
456 fRecord->AddResidual(val);
457 fRecord->AddWeight(sigma); // dummy
458 for (int i=0; i<ngb; i++) if (!IsZero(dergb[i])) fRecord->AddIndexValue(indgb[i],dergb[i]);
460 if (IsZero(sigma)) fNLagrangeConstraints++;
461 SaveRecordConstraint();
465 //_____________________________________________________________________________________________
466 Int_t AliMillePede2::LocalFit(double *localParams)
469 Perform local parameters fit once all the local equations have been set
470 -----------------------------------------------------------
471 localParams = (if !=0) will contain the fitted track parameters and
474 static int nrefSize = 0;
475 // static TArrayI refLoc,refGlo,nrefLoc,nrefGlo;
476 static Int_t *refLoc=0,*refGlo=0,*nrefLoc=0,*nrefGlo=0;
479 AliSymMatrix &matCLoc = *fMatCLoc;
480 AliMatrixSq &matCGlo = *fMatCGlo;
481 AliRectMatrix &matCGloLoc = *fMatCGloLoc;
483 memset(fVecBLoc,0,fNLocPar*sizeof(double));
487 int recSz = fRecord->GetSize();
489 while(cnt<recSz) { // Transfer the measurement records to matrices
491 // extract addresses of residual, weight and pointers on local and global derivatives for each point
492 if (nrefSize<=nPoints) {
494 nrefSize = 2*(nPoints+1);
495 tmpA = refLoc; refLoc = new Int_t[nrefSize]; if (tmpA) memcpy(refLoc,tmpA,nPoints*sizeof(int));
496 tmpA = refGlo; refGlo = new Int_t[nrefSize]; if (tmpA) memcpy(refGlo,tmpA,nPoints*sizeof(int));
497 tmpA = nrefLoc; nrefLoc = new Int_t[nrefSize]; if (tmpA) memcpy(nrefLoc,tmpA,nPoints*sizeof(int));
498 tmpA = nrefGlo; nrefGlo = new Int_t[nrefSize]; if (tmpA) memcpy(nrefGlo,tmpA,nPoints*sizeof(int));
501 refLoc[nPoints] = ++cnt;
503 while(!fRecord->IsWeight(cnt)) {nLoc++; cnt++;}
504 nrefLoc[nPoints] = nLoc;
506 refGlo[nPoints] = ++cnt;
508 while(!fRecord->IsResidual(cnt) && cnt<recSz) {nGlo++; cnt++;}
509 nrefGlo[nPoints] = nGlo;
515 double gloWgh = fRecord->GetWeight(); // global weight for this set
516 Int_t maxLocUsed = 0;
518 for (int ip=nPoints;ip--;) { // Transfer the measurement records to matrices
519 double resid = fRecord->GetValue( refLoc[ip]-1 );
520 double weight = fRecord->GetValue( refGlo[ip]-1 )*gloWgh;
521 double *derLoc = fRecord->GetValue()+refLoc[ip];
522 double *derGlo = fRecord->GetValue()+refGlo[ip];
523 int *indLoc = fRecord->GetIndex()+refLoc[ip];
524 int *indGlo = fRecord->GetIndex()+refGlo[ip];
526 for (int i=nrefGlo[ip];i--;) { // suppress the global part (only relevant with iterations)
527 int iID = indGlo[i]; // Global param indice
528 if (fSigmaPar[iID]<=0.) continue; // fixed parameter RRRCheck
529 if (fIsLinear[iID]) resid -= derGlo[i]*(fInitPar[iID]+fDeltaPar[iID]); // linear parameter
530 else resid -= derGlo[i]*fDeltaPar[iID]; // nonlinear parameter
533 // Symmetric matrix, don't bother j>i coeffs
534 for (int i=nrefLoc[ip];i--;) { // Fill local matrix and vector
535 fVecBLoc[ indLoc[i] ] += weight*resid*derLoc[i];
536 if (indLoc[i]>maxLocUsed) maxLocUsed = indLoc[i];
537 for (int j=i+1;j--;) matCLoc(indLoc[i] ,indLoc[j]) += weight*derLoc[i]*derLoc[j];
540 } // end of the transfer of the measurement record to matrices
542 matCLoc.SetSizeUsed(++maxLocUsed); // data with B=0 may use less than declared nLocals
546 printf("\nBefore\nLocalMatrix: "); matCLoc.Print("l");
547 printf("RHSLoc: "); for (int i=0;i<fNLocPar;i++) printf("%+e |",fVecBLoc[i]); printf("\n");
549 // first try to solve by faster Cholesky decomposition, then by Gaussian elimination
550 if (!matCLoc.SolveChol(fVecBLoc,kTRUE)) {
551 AliInfo("Failed to solve locals by Cholesky, trying Gaussian Elimination");
552 if (!matCLoc.SolveSpmInv(fVecBLoc,kTRUE)) {
553 AliInfo("Failed to solve locals by Gaussian Elimination, skip...");
555 return 0; // failed to solve
559 // If requested, store the track params and errors
560 //RRR printf("locfit: "); for (int i=0;i<fNLocPar;i++) printf("%+e |",fVecBLoc[i]); printf("\n");
562 if (localParams) for (int i=maxLocUsed; i--;) {
563 localParams[2*i] = fVecBLoc[i];
564 localParams[2*i+1] = TMath::Sqrt(TMath::Abs(matCLoc.QueryDiag(i)));
570 for (int ip=nPoints;ip--;) { // Calculate residuals
571 double resid = fRecord->GetValue( refLoc[ip]-1 );
572 double weight = fRecord->GetValue( refGlo[ip]-1 )*gloWgh;
573 double *derLoc = fRecord->GetValue()+refLoc[ip];
574 double *derGlo = fRecord->GetValue()+refGlo[ip];
575 int *indLoc = fRecord->GetIndex()+refLoc[ip];
576 int *indGlo = fRecord->GetIndex()+refGlo[ip];
578 // Suppress local and global contribution in residuals;
579 for (int i=nrefLoc[ip];i--;) resid -= derLoc[i]*fVecBLoc[ indLoc[i] ]; // local part
581 for (int i=nrefGlo[ip];i--;) { // global part
583 if ( fSigmaPar[iID] <= 0.) continue; // fixed parameter RRRCheck
584 if (fIsLinear[iID]) resid -= derGlo[i]*(fInitPar[iID]+fDeltaPar[iID]); // linear parameter
585 else resid -= derGlo[i]*fDeltaPar[iID]; // nonlinear parameter
588 // reject the track if the residual is too large (outlier)
589 double absres = TMath::Abs(resid);
590 if ( (absres >= fResCutInit && fIter ==1 ) ||
591 (absres >= fResCut && fIter > 1)) {
592 if (fLocFitAdd) fNLocFitsRejected++;
593 // printf("reject res %5ld %+e\n",fCurrRecDataID,resid);
597 lChi2 += weight*resid*resid ; // total chi^2
598 nEq++; // number of equations
599 } // end of Calculate residuals
602 int nDoF = nEq-maxLocUsed;
603 lChi2 = (nDoF>0) ? lChi2/nDoF : 0; // Chi^2/dof
605 if (fNStdDev != 0 && nDoF>0 && lChi2 > Chi2DoFLim(fNStdDev,nDoF)*fChi2CutFactor) { // check final chi2
606 if (fLocFitAdd) fNLocFitsRejected++;
607 // printf("reject chi2 %5ld: %+e\n",fCurrRecDataID, lChi2);
613 fNLocEquations += nEq;
617 fNLocEquations -= nEq;
620 // local operations are finished, track is accepted
621 // We now update the global parameters (other matrices)
625 for (int ip=nPoints;ip--;) { // Update matrices
626 double resid = fRecord->GetValue( refLoc[ip]-1 );
627 double weight = fRecord->GetValue( refGlo[ip]-1 )*gloWgh;
628 double *derLoc = fRecord->GetValue()+refLoc[ip];
629 double *derGlo = fRecord->GetValue()+refGlo[ip];
630 int *indLoc = fRecord->GetIndex()+refLoc[ip];
631 int *indGlo = fRecord->GetIndex()+refGlo[ip];
633 for (int i=nrefGlo[ip];i--;) { // suppress the global part
634 int iID = indGlo[i]; // Global param indice
635 if ( fSigmaPar[iID] <= 0.) continue; // fixed parameter RRRCheck
636 if (fIsLinear[iID]) resid -= derGlo[i]*(fInitPar[iID]+fDeltaPar[iID]); // linear parameter
637 else resid -= derGlo[i]*fDeltaPar[iID]; // nonlinear parameter
640 for (int ig=nrefGlo[ip];ig--;) {
641 int iIDg = indGlo[ig]; // Global param indice (the matrix line)
642 if ( fSigmaPar[iIDg] <= 0.) continue; // fixed parameter RRRCheck
643 if (fLocFitAdd) fVecBGlo[ iIDg ] += weight*resid*derGlo[ig]; //!!!
644 else fVecBGlo[ iIDg ] -= weight*resid*derGlo[ig]; //!!!
646 // First of all, the global/global terms (exactly like local matrix)
648 for (int jg=ig+1;jg--;) { // matCGlo is symmetric by construction
649 int jIDg = indGlo[jg];
650 if ( fSigmaPar[jIDg] <= 0.) continue; // fixed parameter RRRCheck
651 if ( !IsZero(vl = weight*derGlo[ig]*derGlo[jg]) ) {
652 fFillIndex[nfill] = jIDg;
653 fFillValue[nfill++] = fLocFitAdd ? vl:-vl;
656 if (nfill) matCGlo.AddToRow(iIDg,fFillValue,fFillIndex,nfill);
658 // Now we have also rectangular matrices containing global/local terms.
659 int iCIDg = fGlo2CGlo[iIDg]; // compressed Index of index
661 Double_t *rowGL = matCGloLoc(nGloInFit);
662 for (int k=maxLocUsed;k--;) rowGL[k] = 0.0; // reset the row
663 iCIDg = fGlo2CGlo[iIDg] = nGloInFit;
664 fCGlo2Glo[nGloInFit++] = iIDg;
667 Double_t *rowGLIDg = matCGloLoc(iCIDg);
668 for (int il=nrefLoc[ip];il--;) rowGLIDg[ indLoc[il] ] += weight*derGlo[ig]*derLoc[il];
669 fProcPnt[iIDg] += fLocFitAdd ? 1:-1; // update counter
672 } // end of Update matrices
675 printf("After GLO\n");
676 printf("MatCLoc: "); fMatCLoc->Print("l");
677 printf("MatCGlo: "); fMatCGlo->Print("l");
678 printf("MatCGlLc:"); fMatCGloLoc->Print("l");
679 printf("BGlo: "); for (int i=0; i<fNGloPar; i++) printf("%+e |",fVecBGlo[i]); printf("\n");
681 // calculate fMatCGlo -= fMatCGloLoc * fMatCLoc * fMatCGloLoc^T
682 // and fVecBGlo -= fMatCGloLoc * fVecBLoc
684 //-------------------------------------------------------------- >>>
686 for (int iCIDg=0; iCIDg<nGloInFit; iCIDg++) {
687 int iIDg = fCGlo2Glo[iCIDg];
690 Double_t *rowGLIDg = matCGloLoc(iCIDg);
691 for (int kl=0;kl<maxLocUsed;kl++) if (rowGLIDg[kl]) vl += rowGLIDg[kl]*fVecBLoc[kl];
692 if (!IsZero(vl)) fVecBGlo[iIDg] -= fLocFitAdd ? vl : -vl;
695 for (int jCIDg=0;jCIDg<=iCIDg; jCIDg++) {
696 int jIDg = fCGlo2Glo[jCIDg];
699 Double_t *rowGLJDg = matCGloLoc(jCIDg);
700 for (int kl=0;kl<maxLocUsed;kl++) {
702 if ( (!IsZero(vll=rowGLIDg[kl]*rowGLJDg[kl])) ) vl += matCLoc.QueryDiag(kl)*vll;
705 for (int ll=0;ll<kl;ll++) {
706 if ( !IsZero(vll=rowGLIDg[kl]*rowGLJDg[ll]) ) vl += matCLoc(kl,ll)*vll;
707 if ( !IsZero(vll=rowGLIDg[ll]*rowGLJDg[kl]) ) vl += matCLoc(kl,ll)*vll;
711 fFillIndex[nfill] = jIDg;
712 fFillValue[nfill++] = fLocFitAdd ? -vl : vl;
715 if (nfill) matCGlo.AddToRow(iIDg,fFillValue,fFillIndex,nfill);
718 // reset compressed index array
721 printf("After GLOLoc\n");
722 printf("MatCGlo: "); fMatCGlo->Print("");
723 printf("BGlo: "); for (int i=0; i<fNGloPar; i++) printf("%+e |",fVecBGlo[i]); printf("\n");
725 for (int i=nGloInFit;i--;) {
726 fGlo2CGlo[ fCGlo2Glo[i] ] = -1;
730 //---------------------------------------------------- <<<
734 //_____________________________________________________________________________________________
735 Int_t AliMillePede2::GlobalFit(Double_t *par, Double_t *error, Double_t *pull)
737 // performs a requested number of global iterations
740 TStopwatch sw; sw.Start();
743 AliInfo("Starting Global fit.");
744 while (fIter<=fMaxIter) {
746 res = GlobalFitIteration();
749 if (!IsZero(fChi2CutFactor-fChi2CutRef)) {
750 fChi2CutFactor = TMath::Sqrt(fChi2CutFactor);
751 if (fChi2CutFactor < 1.2*fChi2CutRef) {
752 fChi2CutFactor = fChi2CutRef;
753 //RRR fIter = fMaxIter - 1; // Last iteration
760 AliInfo(Form("Global fit %s, CPU time: %.1f",res ? "Converged":"Failed",sw.CpuTime()));
763 if (par) for (int i=fNGloPar;i--;) par[i] = fInitPar[i]+fDeltaPar[i];
765 if (fGloSolveStatus==gkInvert) { // errors on params are available
766 if (error) for (int i=fNGloPar;i--;) error[i] = fProcPnt[i]>0 ? TMath::Sqrt(TMath::Abs(fMatCGlo->QueryDiag(i))) : 0.;
767 if (pull) for (int i=fNGloPar;i--;) pull[i] = fProcPnt[i]>0 && (fSigmaPar[i]*fSigmaPar[i]-fMatCGlo->QueryDiag(i))>0. && fSigmaPar[i]>0
768 ? fDeltaPar[i]/TMath::Sqrt(fSigmaPar[i]*fSigmaPar[i]-fMatCGlo->QueryDiag(i)) : 0;
774 //_____________________________________________________________________________________________
775 Int_t AliMillePede2::GlobalFitIteration()
777 // perform global parameters fit once all the local equations have been fitted
779 AliInfo(Form("Global Fit Iteration#%2d (Local Fit Chi^2 cut factor: %.2f)",fIter,fChi2CutFactor));
781 if (!fNGloPar || !fTreeData) {
782 AliInfo("No data was stored, aborting iteration");
790 fConstrUsed = new Bool_t[fNGloConstraints];
791 memset(fConstrUsed,0,fNGloConstraints*sizeof(Bool_t));
793 // Reset all info specific for this step
794 AliMatrixSq& matCGlo = *fMatCGlo;
796 memset(fProcPnt,0,fNGloPar*sizeof(Int_t));
798 fNGloConstraints = fTreeConstr ? fTreeConstr->GetEntries() : 0;
800 // count number of Lagrange constraints: they need new row/cols to be added
801 fNLagrangeConstraints = 0;
802 for (int i=0; i<fNGloConstraints; i++) {
803 ReadRecordConstraint(i);
804 if ( IsZero(fRecord->GetValue(1)) ) fNLagrangeConstraints++; // exact constraint (no error) -> Lagrange multiplier
807 // if needed, readjust the size of the global vector (for matrices this is done automatically)
808 if (!fVecBGlo || fNGloSize!=fNGloPar+fNLagrangeConstraints) {
809 delete[] fVecBGlo; // in case some constraint was added between the two manual iterations
810 fNGloSize = fNGloPar+fNLagrangeConstraints;
811 fVecBGlo = new Double_t[fNGloSize];
813 memset(fVecBGlo,0,fNGloSize*sizeof(double));
816 fNLocFitsRejected = 0;
819 // Process data records and build the matrices
820 Long_t ndr = fTreeData->GetEntries();
821 Long_t first = fSelFirst>0 ? fSelFirst : 0;
822 Long_t last = fSelLast<1 ? ndr : (fSelLast>=ndr ? ndr : fSelLast+Long_t(1));
825 AliInfo(Form("Building the Global matrix from data records %ld : %ld",first,last));
828 TStopwatch swt; swt.Start();
829 fLocFitAdd = kTRUE; // add contributions of matching tracks
830 for (Long_t i=0;i<ndr;i++) {
831 Long_t iev = i+first;
833 if (!IsRecordAcceptable()) continue;
835 if ( (i%int(0.2*ndr)) == 0) printf("%.1f%% of local fits done\n", double(100.*i)/ndr);
838 printf("%ld local fits done: ", ndr);
840 printf("MatCGlo: "); fMatCGlo->Print("l");
841 printf("BGlo: "); for (int i=0; i<fNGloPar; i++) printf("%+e |",fVecBGlo[i]); printf("\n");
847 // ---------------------- Reject parameters with low statistics ------------>>
849 if (fMinPntValid>1 && fNGroupsSet) {
851 printf("Checking parameters with statistics < %d\n",fMinPntValid);
854 // 1) build the list of parameters to fix
855 Int_t fixArrSize = 10;
856 Int_t nFixedGroups = 0;
857 TArrayI fixGroups(fixArrSize);
861 double oldMin = 1.e20;
862 double oldMax =-1.e20;
864 for (int i=fNGloPar;i--;) { // // Reset row and column of fixed params and add 1/sig^2 to free ones
865 int grID = fParamGrID[i];
866 if (grID<0) continue; // not in the group
868 if (grID!=grIDold) { // starting new group
869 if (grIDold>=0) { // decide if the group has enough statistics
870 if (oldMin<fMinPntValid && oldMax<2*fMinPntValid) { // suppress group
871 for (int iold=oldStart;iold>i;iold--) fProcPnt[iold] = 0;
872 Bool_t fnd = kFALSE; // check if the group is already accounted
873 for (int j=nFixedGroups;j--;) if (fixGroups[j]==grIDold) {fnd=kTRUE; break;}
875 if (nFixedGroups>=fixArrSize) {fixArrSize*=2; fixGroups.Set(fixArrSize);}
876 fixGroups[nFixedGroups++] = grIDold; // add group to fix
880 grIDold = grID; // mark the start of the new group
885 if (oldMin>fProcPnt[i]) oldMin = fProcPnt[i];
886 if (oldMax<fProcPnt[i]) oldMax = fProcPnt[i];
889 // extra check for the last group
890 if (grIDold>=0 && oldMin<fMinPntValid && oldMax<2*fMinPntValid) { // suppress group
891 for (int iold=oldStart;iold--;) fProcPnt[iold] = 0;
892 Bool_t fnd = kFALSE; // check if the group is already accounted
893 for (int j=nFixedGroups;j--;) if (fixGroups[j]==grIDold) {fnd=kTRUE; break;}
895 if (nFixedGroups>=fixArrSize) {fixArrSize*=2; fixGroups.Set(fixArrSize);}
896 fixGroups[nFixedGroups++] = grIDold; // add group to fix
900 // 2) loop over records and add contributions of fixed groups with negative sign
903 for (Long_t i=0;i<ndr;i++) {
904 Long_t iev = i+first;
906 if (!IsRecordAcceptable()) continue;
907 Bool_t suppr = kFALSE;
908 for (int ifx=nFixedGroups;ifx--;)if (fRecord->IsGroupPresent(fixGroups[ifx])) suppr = kTRUE;
909 if (suppr) LocalFit();
914 printf("Suppressed contributions of groups with NPoints<%d :\n",fMinPntValid);
915 for (int i=0;i<nFixedGroups;i++) printf("%d ",fixGroups[i]); printf("\n");
920 // ---------------------- Reject parameters with low statistics ------------<<
922 // add large number to diagonal of fixed params
924 for (int i=fNGloPar;i--;) { // // Reset row and column of fixed params and add 1/sig^2 to free ones
925 // printf("#%3d : Nproc : %5d grp: %d\n",i,fProcPnt[i],fParamGrID[i]);
929 matCGlo.DiagElem(i) = 1.;//float(fNLocEquations*fNLocEquations);
930 // matCGlo.DiagElem(i) = float(fNLocEquations*fNLocEquations);
932 else matCGlo.DiagElem(i) += (fgWeightSigma ? fProcPnt[i] : 1.)/(fSigmaPar[i]*fSigmaPar[i]);
935 for (int i=fNGloPar;i--;) fDiagCGlo[i] = matCGlo.QueryDiag(i); // save the diagonal elements
937 // add constraint equations
938 int nVar = fNGloPar; // Current size of global matrix
939 for (int i=0; i<fNGloConstraints; i++) {
940 ReadRecordConstraint(i);
941 double val = fRecord->GetValue(0);
942 double sig = fRecord->GetValue(1);
943 int *indV = fRecord->GetIndex()+2;
944 double *der = fRecord->GetValue()+2;
945 int csize = fRecord->GetSize()-2;
947 // check if after suppression of fixed variables there are non-0 derivatives
948 // and determine the max statistics of involved params
951 for (int j=csize;j--;) {
952 if (fProcPnt[indV[j]]<1) nSuppressed++;
954 maxStat = TMath::Max(maxStat,fProcPnt[indV[j]]);
958 if (nSuppressed==csize) {
959 // AliInfo(Form("Neglecting constraint %d of %d derivatives since no free parameters left",i,csize));
961 // was this constraint ever created ?
962 if ( sig==0 && fConstrUsed[i] ) { // this is needed only for constraints with Lagrange multiplier
963 // to avoid empty row impose dummy constraint on "Lagrange multiplier"
964 matCGlo.DiagElem(nVar) = 1.;
965 fVecBGlo[nVar++] = 0;
970 // account for already accumulated corrections
971 for (int j=csize; j--;) val -= der[j]*(fInitPar[ indV[j] ]+fDeltaPar[ indV[j] ]);
973 if (sig > 0) { // this is a gaussian constriant: no Lagrange multipliers are added
975 double sig2i = (fgWeightSigma ? TMath::Sqrt(maxStat) : 1.)/sig/sig;
976 for (int ir=0;ir<csize;ir++) {
978 for (int ic=0;ic<=ir;ic++) { // matrix is symmetric
980 double vl = der[ir]*der[ic]*sig2i;
981 if (!IsZero(vl)) matCGlo(iID,jID) += vl;
983 fVecBGlo[iID] += val*der[ir]*sig2i;
986 else { // this is exact constriant: Lagrange multipliers must be added
987 for (int j=csize; j--;) {
989 if (fProcPnt[jID]<1) continue; // this parameter was fixed, don't put it into constraint
990 matCGlo(nVar,jID) = float(fNLocEquations)*der[j]; // fMatCGlo is symmetric, only lower triangle is filled
993 if (matCGlo.QueryDiag(nVar)) matCGlo.DiagElem(nVar) = 0.0;
994 fVecBGlo[nVar++] = float(fNLocEquations)*val; //RS ? should we use here fNLocFits ?
995 fConstrUsed[i] = kTRUE;
999 AliInfo(Form("Obtained %-7ld equations from %-7ld records (%-7ld rejected). Fixed %-4d globals",
1000 fNLocEquations,fNLocFits,fNLocFitsRejected,fNGloFix));
1006 printf("Solving:\n");
1008 for (int i=0;i<fNGloSize;i++) printf("b%2d : %+e\n",i,fVecBGlo[i]);
1010 fGloSolveStatus = SolveGlobalMatEq(); // obtain solution for this step
1012 printf("Solve %d |",fIter); sws.Print();
1015 AliInfo(Form("Iteration#%2d %s. CPU time: %.1f",fIter,fGloSolveStatus==gkFailed ? "Failed":"Converged",sw.CpuTime()));
1016 if (fGloSolveStatus==gkFailed) return 0;
1018 for (int i=fNGloPar;i--;) fDeltaPar[i] += fVecBGlo[i]; // Update global parameters values (for iterations)
1020 // PrintGlobalParameters();
1024 //_____________________________________________________________________________________________
1025 Int_t AliMillePede2::SolveGlobalMatEq()
1028 // solve global matrix equation MatCGlob*X=VecBGlo and store the result in the VecBGlo
1031 printf("GlobalMatrix\n");
1034 for (int i=0;i<fNGloPar;i++) printf("%d %+e\n",i,fVecBGlo[i]);
1037 if (!fgIsMatGloSparse) {
1039 if (fNLagrangeConstraints==0) { // pos-def systems are faster to solve by Cholesky
1040 if ( ((AliSymMatrix*)fMatCGlo)->SolveChol(fVecBGlo, fgInvChol) ) return fgInvChol ? gkInvert:gkNoInversion;
1041 else AliInfo("Solution of Global Dense System by Cholesky failed, trying Gaussian Elimiation");
1044 if (((AliSymMatrix*)fMatCGlo)->SolveSpmInv(fVecBGlo, kTRUE)) return gkInvert;
1045 else AliInfo("Solution of Global Dense System by Gaussian Elimination failed, trying iterative methods");
1047 // try to solve by minres
1048 TVectorD sol(fNGloSize);
1050 AliMinResSolve *slv = new AliMinResSolve(fMatCGlo,fVecBGlo);
1051 if (!slv) return gkFailed;
1053 Bool_t res = kFALSE;
1054 if (fgIterSol == AliMinResSolve::kSolMinRes)
1055 res = slv->SolveMinRes(sol,fgMinResCondType,fgMinResMaxIter,fgMinResTol);
1056 else if (fgIterSol == AliMinResSolve::kSolFGMRes)
1057 res = slv->SolveFGMRES(sol,fgMinResCondType,fgMinResMaxIter,fgMinResTol,fgNKrylovV);
1059 AliInfo(Form("Undefined Iteritive Solver ID=%d, only %d are defined",fgIterSol,AliMinResSolve::kNSolvers));
1062 const char* faildump = "fgmr_failed.dat";
1063 int defout = dup(1);
1065 AliInfo("Failed on dup");
1068 int slvDump = open(faildump, O_RDWR|O_CREAT, 0666);
1072 printf("#Failed to solve using solver %d with PreCond: %d MaxIter: %d Tol: %e NKrylov: %d\n",
1073 fgIterSol,fgMinResCondType,fgMinResMaxIter,fgMinResTol,fgNKrylovV);
1074 printf("#Dump of matrix:\n");
1075 fMatCGlo->Print("10");
1076 printf("#Dump of RHS:\n");
1077 for (int i=0;i<fNGloSize;i++) printf("%d %+.10f\n",i,fVecBGlo[i]);
1082 printf("#Dumped failed matrix and RHS to %s\n",faildump);
1084 else AliInfo("Failed on file open for matrix dumping");
1087 for (int i=fNGloSize;i--;) fVecBGlo[i] = sol[i];
1088 return gkNoInversion;
1092 //_____________________________________________________________________________________________
1093 Float_t AliMillePede2::Chi2DoFLim(int nSig, int nDoF) const
1095 /// return the limit in chi^2/nd for n sigmas stdev authorized
1096 // Only n=1, 2, and 3 are expected in input
1098 float sn[3] = {0.47523, 1.690140, 2.782170};
1099 float table[3][30] = {{1.0000, 1.1479, 1.1753, 1.1798, 1.1775, 1.1730, 1.1680, 1.1630,
1100 1.1581, 1.1536, 1.1493, 1.1454, 1.1417, 1.1383, 1.1351, 1.1321,
1101 1.1293, 1.1266, 1.1242, 1.1218, 1.1196, 1.1175, 1.1155, 1.1136,
1102 1.1119, 1.1101, 1.1085, 1.1070, 1.1055, 1.1040},
1103 {4.0000, 3.0900, 2.6750, 2.4290, 2.2628, 2.1415, 2.0481, 1.9736,
1104 1.9124, 1.8610, 1.8171, 1.7791, 1.7457, 1.7161, 1.6897, 1.6658,
1105 1.6442, 1.6246, 1.6065, 1.5899, 1.5745, 1.5603, 1.5470, 1.5346,
1106 1.5230, 1.5120, 1.5017, 1.4920, 1.4829, 1.4742},
1107 {9.0000, 5.9146, 4.7184, 4.0628, 3.6410, 3.3436, 3.1209, 2.9468,
1108 2.8063, 2.6902, 2.5922, 2.5082, 2.4352, 2.3711, 2.3143, 2.2635,
1109 2.2178, 2.1764, 2.1386, 2.1040, 2.0722, 2.0428, 2.0155, 1.9901,
1110 1.9665, 1.9443, 1.9235, 1.9040, 1.8855, 1.8681}};
1116 lNSig = TMath::Max(1,TMath::Min(nSig,3));
1119 return table[lNSig-1][nDoF-1];
1121 else { // approximation
1122 return ((sn[lNSig-1]+TMath::Sqrt(float(2*nDoF-3)))*
1123 (sn[lNSig-1]+TMath::Sqrt(float(2*nDoF-3))))/float(2*nDoF-2);
1128 //_____________________________________________________________________________________________
1129 Int_t AliMillePede2::SetIterations(double lChi2CutFac)
1131 // Number of iterations is calculated from lChi2CutFac
1132 fChi2CutFactor = TMath::Max(1.0, lChi2CutFac);
1134 AliInfo(Form("Initial cut factor is %f",fChi2CutFactor));
1135 fIter = 1; // Initializes the iteration process
1139 //_____________________________________________________________________________________________
1140 Double_t AliMillePede2::GetParError(int iPar) const
1142 // return error for parameter iPar
1143 if (fGloSolveStatus==gkInvert) {
1144 double res = fMatCGlo->QueryDiag(iPar);
1145 if (res>=0) return TMath::Sqrt(res);
1151 //_____________________________________________________________________________________________
1152 Int_t AliMillePede2::PrintGlobalParameters() const
1154 /// Print the final results into the logfile
1156 double lGlobalCor =0.;
1159 AliInfo(" Result of fit for global parameters");
1160 AliInfo(" ===================================");
1161 AliInfo(" I initial final differ lastcor error gcor Npnt");
1162 AliInfo("----------------------------------------------------------------------------------------------");
1164 for (int i=0; i<fNGloPar; i++) {
1165 lError = GetParError(i);
1169 if (fGloSolveStatus==gkInvert && TMath::Abs( (dg=fMatCGlo->QueryDiag(i)) *fDiagCGlo[i]) > 0) {
1170 lGlobalCor = TMath::Sqrt(TMath::Abs(1.0-1.0/(dg*fDiagCGlo[i])));
1171 AliInfo(Form("%d\t %.6f\t %.6f\t %.6f\t %.6f\t %.6f\t %.6f\t %6d",
1172 i,fInitPar[i],fInitPar[i]+fDeltaPar[i],fDeltaPar[i],fVecBGlo[i],lError,lGlobalCor,fProcPnt[i]));
1175 AliInfo(Form("%d\t %.6f\t %.6f\t %.6f\t %.6f\t OFF\t OFF\t %6d",i,fInitPar[i],fInitPar[i]+fDeltaPar[i],
1176 fDeltaPar[i],fVecBGlo[i],fProcPnt[i]));
1182 //_____________________________________________________________________________________________
1183 Bool_t AliMillePede2::IsRecordAcceptable() const
1185 // validate record according run lists set by the user
1186 static Long_t prevRunID = kMaxInt;
1187 static Bool_t prevAns = kTRUE;
1188 Long_t runID = fRecord->GetRunID();
1189 if (runID!=prevRunID) {
1192 // is run to be rejected?
1193 if (fRejRunList && (n=fRejRunList->GetSize())) {
1195 for (int i=n;i--;) if (runID == (*fRejRunList)[i]) {
1197 printf("New Run to reject: %ld -> %d\n",runID,prevAns);
1201 else if (fAccRunList && (n=fAccRunList->GetSize())) { // is run specifically selected
1203 for (int i=n;i--;) if (runID == (*fAccRunList)[i]) {prevAns = kTRUE; break;}
1211 //_____________________________________________________________________________________________
1212 void AliMillePede2::SetRejRunList(const UInt_t *runs, Int_t nruns)
1214 // set the list of runs to be rejected
1215 if (fRejRunList) delete fRejRunList;
1217 if (nruns<1 || !runs) return;
1218 fRejRunList = new TArrayL(nruns);
1219 for (int i=0;i<nruns;i++) (*fRejRunList)[i] = runs[i];
1222 //_____________________________________________________________________________________________
1223 void AliMillePede2::SetAccRunList(const UInt_t *runs, Int_t nruns)
1225 // set the list of runs to be selected
1226 if (fAccRunList) delete fAccRunList;
1228 if (nruns<1 || !runs) return;
1229 fAccRunList = new TArrayL(nruns);
1230 for (int i=0;i<nruns;i++) (*fAccRunList)[i] = runs[i];