1 /**********************************************************************************************/
2 /* General class for alignment with large number of degrees of freedom */
3 /* Based on the original milliped2 by Volker Blobel */
4 /* and AliMillepede class by Javier */
5 /* Allows operations with large sparse matrices */
6 /* http://www.desy.de/~blobel/mptalks.html */
8 /* Author: ruben.shahoyan@cern.ch */
10 /**********************************************************************************************/
12 #include "AliMillePede2.h"
14 #include <TStopwatch.h>
21 #include "AliMatrixSq.h"
22 #include "AliSymMatrix.h"
23 #include "AliRectMatrix.h"
24 #include "AliMatrixSparse.h"
28 #include <sys/types.h>
36 ClassImp(AliMillePede2)
38 Bool_t AliMillePede2::fgInvChol = kTRUE; // Invert global matrix with Cholesky solver
39 Bool_t AliMillePede2::fgWeightSigma = kTRUE; // weight local constraint by module statistics
40 Bool_t AliMillePede2::fgIsMatGloSparse = kFALSE; // use faster dense matrix by default
41 Int_t AliMillePede2::fgMinResCondType = 1; // Jacoby preconditioner by default
42 Double_t AliMillePede2::fgMinResTol = 1.e-11; // default tolerance
43 Int_t AliMillePede2::fgMinResMaxIter = 10000; // default max number of iterations
44 Int_t AliMillePede2::fgIterSol = AliMinResSolve::kSolMinRes; // default iterative solver
45 Int_t AliMillePede2::fgNKrylovV = 240; // default number of Krylov vectors to keep
47 //_____________________________________________________________________________________________
48 AliMillePede2::AliMillePede2()
58 fNLagrangeConstraints(0),
62 fGloSolveStatus(kFailed),
92 fDataRecFName("/tmp/mp2_data_records.root"),
98 fConstrRecFName("/tmp/mp2_constraints_records.root"),
110 //_____________________________________________________________________________________________
111 AliMillePede2::AliMillePede2(const AliMillePede2& src) :
112 TObject(src),fNLocPar(0),fNGloPar(0),fNGloSize(0),fNLocEquations(0),fIter(0),
113 fMaxIter(10),fNStdDev(3),fNGloConstraints(0),fNLagrangeConstraints(0),
114 fNLocFits(0),fNLocFitsRejected(0),
115 fNGloFix(0),fGloSolveStatus(0),fChi2CutFactor(0),fChi2CutRef(0),fResCutInit(0),
116 fResCut(0),fMinPntValid(1),fNGroupsSet(0),fParamGrID(0),fProcPnt(0),fVecBLoc(0),fDiagCGlo(0),fVecBGlo(0),
117 fInitPar(0),fDeltaPar(0),fSigmaPar(0),fIsLinear(0),fConstrUsed(0),fGlo2CGlo(0),fCGlo2Glo(0),
118 fMatCLoc(0),fMatCGlo(0),fMatCGloLoc(0),fFillIndex(0),fFillValue(0),
119 fDataRecFName(0),fRecord(0),fDataRecFile(0),
120 fTreeData(0),fRecFileStatus(0),fConstrRecFName(0),fTreeConstr(0),fConsRecFile(0),fCurrRecDataID(0),
121 fCurrRecConstrID(0),fLocFitAdd(kTRUE),
128 //_____________________________________________________________________________________________
129 AliMillePede2::~AliMillePede2()
132 CloseDataRecStorage();
133 CloseConsRecStorage();
146 delete[] fConstrUsed;
158 //_____________________________________________________________________________________________
159 Int_t AliMillePede2::InitMille(int nGlo, int nLoc, int lNStdDev,double lResCut, double lResCutInit)
162 if (nLoc>0) fNLocPar = nLoc;
163 if (nGlo>0) fNGloPar = nGlo;
164 if (lResCutInit>0) fResCutInit = lResCutInit;
165 if (lResCut>0) fResCut = lResCut;
166 if (lNStdDev>0) fNStdDev = lNStdDev;
168 fNGloSize = fNGloPar;
170 if (fgIsMatGloSparse) {fMatCGlo = new AliMatrixSparse(fNGloPar); fMatCGlo->SetSymmetric(kTRUE);}
171 else fMatCGlo = new AliSymMatrix(fNGloPar);
173 fFillIndex = new Int_t[fNGloPar];
174 fFillValue = new Double_t[fNGloPar];
176 fMatCLoc = new AliSymMatrix(fNLocPar);
177 fMatCGloLoc = new AliRectMatrix(fNGloPar,fNLocPar);
179 fParamGrID = new Int_t[fNGloPar];
180 fProcPnt = new Int_t[fNGloPar];
181 fVecBLoc = new Double_t[fNLocPar];
182 fDiagCGlo = new Double_t[fNGloPar];
184 fInitPar = new Double_t[fNGloPar];
185 fDeltaPar = new Double_t[fNGloPar];
186 fSigmaPar = new Double_t[fNGloPar];
187 fIsLinear = new Bool_t[fNGloPar];
189 fGlo2CGlo = new Int_t[fNGloPar];
190 fCGlo2Glo = new Int_t[fNGloPar];
192 memset(fVecBLoc ,0,fNLocPar*sizeof(Double_t));
193 memset(fDiagCGlo ,0,fNGloPar*sizeof(Double_t));
194 memset(fInitPar ,0,fNGloPar*sizeof(Double_t));
195 memset(fDeltaPar ,0,fNGloPar*sizeof(Double_t));
196 memset(fSigmaPar ,0,fNGloPar*sizeof(Double_t));
197 memset(fProcPnt ,0,fNGloPar*sizeof(Int_t));
199 for (int i=fNGloPar;i--;) {
200 fGlo2CGlo[i] = fCGlo2Glo[i] = -1;
201 fIsLinear[i] = kTRUE;
208 //_____________________________________________________________________________________________
209 Bool_t AliMillePede2::ImposeDataRecFile(const char* fname)
211 // set filename for records
212 CloseDataRecStorage();
213 SetDataRecFName(fname);
214 return InitDataRecStorage(kTRUE); // open in read mode
217 //_____________________________________________________________________________________________
218 Bool_t AliMillePede2::ImposeConsRecFile(const char* fname)
220 // set filename for constraints
221 CloseConsRecStorage();
222 SetConsRecFName(fname);
223 return InitConsRecStorage(kTRUE); // open in read mode
226 //_____________________________________________________________________________________________
227 Bool_t AliMillePede2::InitDataRecStorage(Bool_t read)
229 // initialize the buffer for processed measurements records
231 if (fTreeData) {AliInfo("Data Records File is already initialized"); return kFALSE;}
233 if (!fRecord) fRecord = new AliMillePedeRecord();
235 if (!read) { // write mode: cannot use chain
236 fDataRecFile = TFile::Open(GetDataRecFName(),"recreate");
237 if (!fDataRecFile) {AliFatal(Form("Failed to initialize data records file %s",GetDataRecFName())); return kFALSE;}
238 AliInfo(Form("File %s used for derivatives records",GetDataRecFName()));
239 fTreeData = new TTree("AliMillePedeRecords_Data","Data Records for AliMillePede2");
240 fTreeData->Branch("Record_Data","AliMillePedeRecord",&fRecord,32000,99);
243 TChain* ch = new TChain("AliMillePedeRecords_Data");
245 if (fDataRecFName.EndsWith(".root")) ch->AddFile(fDataRecFName);
246 else { // assume text file with list of filenames
248 ifstream inpf(fDataRecFName.Data());
249 if (!inpf.good()) {AliInfo(Form("Failed on input records list %s\n",fDataRecFName.Data())); return kFALSE;}
252 while ( !(recfName.ReadLine(inpf)).eof() ) {
253 recfName = recfName.Strip(TString::kBoth,' ');
254 if (recfName.BeginsWith("//") || recfName.BeginsWith("#") || !recfName.EndsWith(".root")) { // comment
255 AliInfo(Form("Skip %s\n",recfName.Data()));
259 recfName = recfName.Strip(TString::kBoth,',');
260 recfName = recfName.Strip(TString::kBoth,'"');
261 gSystem->ExpandPathName(recfName);
262 printf("Adding %s\n",recfName.Data());
263 ch->AddFile(recfName.Data());
267 Long64_t nent = ch->GetEntries();
268 if (nent<1) { AliInfo("Obtained chain is empty"); return kFALSE;}
270 fTreeData->SetBranchAddress("Record_Data",&fRecord);
271 AliInfo(Form("Found %lld derivatives records",nent));
274 fRecFileStatus = read ? 1:2;
279 //_____________________________________________________________________________________________
280 Bool_t AliMillePede2::InitConsRecStorage(Bool_t read)
282 // initialize the buffer for processed measurements records
284 if (fConsRecFile) {AliInfo("Constraints Records File is already initialized"); return kFALSE;}
286 if (!fRecord) fRecord = new AliMillePedeRecord();
288 fConsRecFile = TFile::Open(GetConsRecFName(),read ? "":"recreate");
289 if (!fConsRecFile) {AliInfo(Form("Failed to initialize constraints records file %s",GetConsRecFName())); return kFALSE;}
291 AliInfo(Form("File %s used for constraints records",GetConsRecFName()));
293 fTreeConstr = (TTree*)fConsRecFile->Get("AliMillePedeRecords_Constraints");
294 if (!fTreeConstr) {AliInfo(Form("Did not find constraints records tree in %s",GetConsRecFName())); return kFALSE;}
295 fTreeConstr->SetBranchAddress("Record_Constraints",&fRecord);
296 AliInfo(Form("Found %lld constraints records",fTreeConstr->GetEntries()));
301 fTreeConstr = new TTree("AliMillePedeRecords_Constraints","Constraints Records for AliMillePede2");
302 fTreeConstr->Branch("Record_Constraints","AliMillePedeRecord",&fRecord,32000,99);
304 fCurrRecConstrID = -1;
309 //_____________________________________________________________________________________________
310 void AliMillePede2::CloseDataRecStorage()
312 // close records file
314 if (fDataRecFile && fDataRecFile->IsWritable()) {
321 fDataRecFile->Close();
330 //_____________________________________________________________________________________________
331 void AliMillePede2::CloseConsRecStorage()
333 // close constraints file
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)
370 if (fRecFileStatus<2) InitDataRecStorage(); // create a buffer to store the data
371 fRecord->SetWeight(wgh);
374 //_____________________________________________________________________________________________
375 void AliMillePede2::SetRecordRun(Int_t run)
378 if (fRecFileStatus<2) InitDataRecStorage(); // create a buffer to store the data
379 fRecord->SetRunID(run);
382 //_____________________________________________________________________________________________
383 void AliMillePede2::SetLocalEquation(double *dergb, double *derlc, double lMeas, double lSigma)
385 // assing derivs of loc.eq.
386 if (fRecFileStatus<2) InitDataRecStorage(); // create a buffer to store the data
388 // write data of single measurement
389 if (lSigma<=0.0) { // If parameter is fixed, then no equation
390 for (int i=fNLocPar; i--;) derlc[i] = 0.0;
391 for (int i=fNGloPar; i--;) dergb[i] = 0.0;
395 fRecord->AddResidual(lMeas);
397 // Retrieve local param interesting indices
398 for (int i=0;i<fNLocPar;i++) if (!IsZero(derlc[i])) {fRecord->AddIndexValue(i,derlc[i]); derlc[i] = 0.0;}
400 fRecord->AddWeight( 1.0/lSigma/lSigma );
402 // Idem for global parameters
403 for (int i=0;i<fNGloPar;i++) if (!IsZero(dergb[i])) {
404 fRecord->AddIndexValue(i,dergb[i]); dergb[i] = 0.0;
405 fRecord->MarkGroup(fParamGrID[i]);
410 //_____________________________________________________________________________________________
411 void AliMillePede2::SetLocalEquation(int *indgb, double *dergb, int ngb, int *indlc,
412 double *derlc,int nlc,double lMeas,double lSigma)
414 // write data of single measurement
415 if (lSigma<=0.0) { // If parameter is fixed, then no equation
416 for (int i=nlc;i--;) derlc[i] = 0.0;
417 for (int i=ngb;i--;) dergb[i] = 0.0;
421 if (fRecFileStatus<2) InitDataRecStorage(); // create a buffer to store the data
423 fRecord->AddResidual(lMeas);
425 // Retrieve local param interesting indices
426 for (int i=0;i<nlc;i++) if (!IsZero(derlc[i])) {fRecord->AddIndexValue(indlc[i],derlc[i]); derlc[i]=0.; indlc[i]=0;}
428 fRecord->AddWeight( 1./lSigma/lSigma );
430 // Idem for global parameters
431 for (int i=0;i<ngb;i++) if (!IsZero(dergb[i])) {fRecord->AddIndexValue(indgb[i],dergb[i]); dergb[i]=0.; indgb[i]=0;}
436 //_____________________________________________________________________________________________
437 void AliMillePede2::SetGlobalConstraint(const double *dergb, double val, double sigma)
439 // Define a constraint equation.
440 if (!fConsRecFile || !fConsRecFile->IsWritable()) InitConsRecStorage(); // create a buffer to store the data
443 fRecord->AddResidual(val);
444 fRecord->AddWeight(sigma);
445 for (int i=0; i<fNGloPar; i++) if (!IsZero(dergb[i])) fRecord->AddIndexValue(i,dergb[i]);
447 if (IsZero(sigma)) fNLagrangeConstraints++;
448 // printf("NewConstraint:\n"); fRecord->Print(); //RRR
449 SaveRecordConstraint();
453 //_____________________________________________________________________________________________
454 void AliMillePede2::SetGlobalConstraint(const int *indgb, const double *dergb, int ngb, double val,double sigma)
456 // Define a constraint equation.
457 if (!fConsRecFile || !fConsRecFile->IsWritable()) InitConsRecStorage(); // create a buffer to store the data
459 fRecord->AddResidual(val);
460 fRecord->AddWeight(sigma); // dummy
461 for (int i=0; i<ngb; i++) if (!IsZero(dergb[i])) fRecord->AddIndexValue(indgb[i],dergb[i]);
463 if (IsZero(sigma)) fNLagrangeConstraints++;
464 SaveRecordConstraint();
468 //_____________________________________________________________________________________________
469 Int_t AliMillePede2::LocalFit(double *localParams)
472 Perform local parameters fit once all the local equations have been set
473 -----------------------------------------------------------
474 localParams = (if !=0) will contain the fitted track parameters and
477 static int nrefSize = 0;
478 // static TArrayI refLoc,refGlo,nrefLoc,nrefGlo;
479 static Int_t *refLoc=0,*refGlo=0,*nrefLoc=0,*nrefGlo=0;
482 AliSymMatrix &matCLoc = *fMatCLoc;
483 AliMatrixSq &matCGlo = *fMatCGlo;
484 AliRectMatrix &matCGloLoc = *fMatCGloLoc;
486 memset(fVecBLoc,0,fNLocPar*sizeof(double));
490 int recSz = fRecord->GetSize();
492 while(cnt<recSz) { // Transfer the measurement records to matrices
494 // extract addresses of residual, weight and pointers on local and global derivatives for each point
495 if (nrefSize<=nPoints) {
497 nrefSize = 2*(nPoints+1);
498 tmpA = refLoc; refLoc = new Int_t[nrefSize]; if (tmpA) memcpy(refLoc,tmpA,nPoints*sizeof(int));
499 tmpA = refGlo; refGlo = new Int_t[nrefSize]; if (tmpA) memcpy(refGlo,tmpA,nPoints*sizeof(int));
500 tmpA = nrefLoc; nrefLoc = new Int_t[nrefSize]; if (tmpA) memcpy(nrefLoc,tmpA,nPoints*sizeof(int));
501 tmpA = nrefGlo; nrefGlo = new Int_t[nrefSize]; if (tmpA) memcpy(nrefGlo,tmpA,nPoints*sizeof(int));
504 refLoc[nPoints] = ++cnt;
506 while(!fRecord->IsWeight(cnt)) {nLoc++; cnt++;}
507 nrefLoc[nPoints] = nLoc;
509 refGlo[nPoints] = ++cnt;
511 while(!fRecord->IsResidual(cnt) && cnt<recSz) {nGlo++; cnt++;}
512 nrefGlo[nPoints] = nGlo;
518 double gloWgh = fRecord->GetWeight(); // global weight for this set
519 Int_t maxLocUsed = 0;
521 for (int ip=nPoints;ip--;) { // Transfer the measurement records to matrices
522 double resid = fRecord->GetValue( refLoc[ip]-1 );
523 double weight = fRecord->GetValue( refGlo[ip]-1 )*gloWgh;
524 double *derLoc = fRecord->GetValue()+refLoc[ip];
525 double *derGlo = fRecord->GetValue()+refGlo[ip];
526 int *indLoc = fRecord->GetIndex()+refLoc[ip];
527 int *indGlo = fRecord->GetIndex()+refGlo[ip];
529 for (int i=nrefGlo[ip];i--;) { // suppress the global part (only relevant with iterations)
530 int iID = indGlo[i]; // Global param indice
531 if (fSigmaPar[iID]<=0.) continue; // fixed parameter RRRCheck
532 if (fIsLinear[iID]) resid -= derGlo[i]*(fInitPar[iID]+fDeltaPar[iID]); // linear parameter
533 else resid -= derGlo[i]*fDeltaPar[iID]; // nonlinear parameter
536 // Symmetric matrix, don't bother j>i coeffs
537 for (int i=nrefLoc[ip];i--;) { // Fill local matrix and vector
538 fVecBLoc[ indLoc[i] ] += weight*resid*derLoc[i];
539 if (indLoc[i]>maxLocUsed) maxLocUsed = indLoc[i];
540 for (int j=i+1;j--;) matCLoc(indLoc[i] ,indLoc[j]) += weight*derLoc[i]*derLoc[j];
543 } // end of the transfer of the measurement record to matrices
545 matCLoc.SetSizeUsed(++maxLocUsed); // data with B=0 may use less than declared nLocals
549 printf("\nBefore\nLocalMatrix: "); matCLoc.Print("l");
550 printf("RHSLoc: "); for (int i=0;i<fNLocPar;i++) printf("%+e |",fVecBLoc[i]); printf("\n");
552 // first try to solve by faster Cholesky decomposition, then by Gaussian elimination
553 if (!matCLoc.SolveChol(fVecBLoc,kTRUE)) {
554 AliInfo("Failed to solve locals by Cholesky, trying Gaussian Elimination");
555 if (!matCLoc.SolveSpmInv(fVecBLoc,kTRUE)) {
556 AliInfo("Failed to solve locals by Gaussian Elimination, skip...");
558 return 0; // failed to solve
562 // If requested, store the track params and errors
563 //RRR printf("locfit: "); for (int i=0;i<fNLocPar;i++) printf("%+e |",fVecBLoc[i]); printf("\n");
565 if (localParams) for (int i=maxLocUsed; i--;) {
566 localParams[2*i] = fVecBLoc[i];
567 localParams[2*i+1] = TMath::Sqrt(TMath::Abs(matCLoc.QueryDiag(i)));
573 for (int ip=nPoints;ip--;) { // Calculate residuals
574 double resid = fRecord->GetValue( refLoc[ip]-1 );
575 double weight = fRecord->GetValue( refGlo[ip]-1 )*gloWgh;
576 double *derLoc = fRecord->GetValue()+refLoc[ip];
577 double *derGlo = fRecord->GetValue()+refGlo[ip];
578 int *indLoc = fRecord->GetIndex()+refLoc[ip];
579 int *indGlo = fRecord->GetIndex()+refGlo[ip];
581 // Suppress local and global contribution in residuals;
582 for (int i=nrefLoc[ip];i--;) resid -= derLoc[i]*fVecBLoc[ indLoc[i] ]; // local part
584 for (int i=nrefGlo[ip];i--;) { // global part
586 if ( fSigmaPar[iID] <= 0.) continue; // fixed parameter RRRCheck
587 if (fIsLinear[iID]) resid -= derGlo[i]*(fInitPar[iID]+fDeltaPar[iID]); // linear parameter
588 else resid -= derGlo[i]*fDeltaPar[iID]; // nonlinear parameter
591 // reject the track if the residual is too large (outlier)
592 double absres = TMath::Abs(resid);
593 if ( (absres >= fResCutInit && fIter ==1 ) ||
594 (absres >= fResCut && fIter > 1)) {
595 if (fLocFitAdd) fNLocFitsRejected++;
596 // printf("reject res %5ld %+e\n",fCurrRecDataID,resid);
600 lChi2 += weight*resid*resid ; // total chi^2
601 nEq++; // number of equations
602 } // end of Calculate residuals
605 int nDoF = nEq-maxLocUsed;
606 lChi2 = (nDoF>0) ? lChi2/nDoF : 0; // Chi^2/dof
608 if (fNStdDev != 0 && nDoF>0 && lChi2 > Chi2DoFLim(fNStdDev,nDoF)*fChi2CutFactor) { // check final chi2
609 if (fLocFitAdd) fNLocFitsRejected++;
610 // printf("reject chi2 %5ld: %+e\n",fCurrRecDataID, lChi2);
616 fNLocEquations += nEq;
620 fNLocEquations -= nEq;
623 // local operations are finished, track is accepted
624 // We now update the global parameters (other matrices)
628 for (int ip=nPoints;ip--;) { // Update matrices
629 double resid = fRecord->GetValue( refLoc[ip]-1 );
630 double weight = fRecord->GetValue( refGlo[ip]-1 )*gloWgh;
631 double *derLoc = fRecord->GetValue()+refLoc[ip];
632 double *derGlo = fRecord->GetValue()+refGlo[ip];
633 int *indLoc = fRecord->GetIndex()+refLoc[ip];
634 int *indGlo = fRecord->GetIndex()+refGlo[ip];
636 for (int i=nrefGlo[ip];i--;) { // suppress the global part
637 int iID = indGlo[i]; // Global param indice
638 if ( fSigmaPar[iID] <= 0.) continue; // fixed parameter RRRCheck
639 if (fIsLinear[iID]) resid -= derGlo[i]*(fInitPar[iID]+fDeltaPar[iID]); // linear parameter
640 else resid -= derGlo[i]*fDeltaPar[iID]; // nonlinear parameter
643 for (int ig=nrefGlo[ip];ig--;) {
644 int iIDg = indGlo[ig]; // Global param indice (the matrix line)
645 if ( fSigmaPar[iIDg] <= 0.) continue; // fixed parameter RRRCheck
646 if (fLocFitAdd) fVecBGlo[ iIDg ] += weight*resid*derGlo[ig]; //!!!
647 else fVecBGlo[ iIDg ] -= weight*resid*derGlo[ig]; //!!!
649 // First of all, the global/global terms (exactly like local matrix)
651 for (int jg=ig+1;jg--;) { // matCGlo is symmetric by construction
652 int jIDg = indGlo[jg];
653 if ( fSigmaPar[jIDg] <= 0.) continue; // fixed parameter RRRCheck
654 if ( !IsZero(vl = weight*derGlo[ig]*derGlo[jg]) ) {
655 fFillIndex[nfill] = jIDg;
656 fFillValue[nfill++] = fLocFitAdd ? vl:-vl;
659 if (nfill) matCGlo.AddToRow(iIDg,fFillValue,fFillIndex,nfill);
661 // Now we have also rectangular matrices containing global/local terms.
662 int iCIDg = fGlo2CGlo[iIDg]; // compressed Index of index
664 Double_t *rowGL = matCGloLoc(nGloInFit);
665 for (int k=maxLocUsed;k--;) rowGL[k] = 0.0; // reset the row
666 iCIDg = fGlo2CGlo[iIDg] = nGloInFit;
667 fCGlo2Glo[nGloInFit++] = iIDg;
670 Double_t *rowGLIDg = matCGloLoc(iCIDg);
671 for (int il=nrefLoc[ip];il--;) rowGLIDg[ indLoc[il] ] += weight*derGlo[ig]*derLoc[il];
672 fProcPnt[iIDg] += fLocFitAdd ? 1:-1; // update counter
675 } // end of Update matrices
678 printf("After GLO\n");
679 printf("MatCLoc: "); fMatCLoc->Print("l");
680 printf("MatCGlo: "); fMatCGlo->Print("l");
681 printf("MatCGlLc:"); fMatCGloLoc->Print("l");
682 printf("BGlo: "); for (int i=0; i<fNGloPar; i++) printf("%+e |",fVecBGlo[i]); printf("\n");
684 // calculate fMatCGlo -= fMatCGloLoc * fMatCLoc * fMatCGloLoc^T
685 // and fVecBGlo -= fMatCGloLoc * fVecBLoc
687 //-------------------------------------------------------------- >>>
689 for (int iCIDg=0; iCIDg<nGloInFit; iCIDg++) {
690 int iIDg = fCGlo2Glo[iCIDg];
693 Double_t *rowGLIDg = matCGloLoc(iCIDg);
694 for (int kl=0;kl<maxLocUsed;kl++) if (rowGLIDg[kl]) vl += rowGLIDg[kl]*fVecBLoc[kl];
695 if (!IsZero(vl)) fVecBGlo[iIDg] -= fLocFitAdd ? vl : -vl;
698 for (int jCIDg=0;jCIDg<=iCIDg; jCIDg++) {
699 int jIDg = fCGlo2Glo[jCIDg];
702 Double_t *rowGLJDg = matCGloLoc(jCIDg);
703 for (int kl=0;kl<maxLocUsed;kl++) {
705 if ( (!IsZero(vll=rowGLIDg[kl]*rowGLJDg[kl])) ) vl += matCLoc.QueryDiag(kl)*vll;
708 for (int ll=0;ll<kl;ll++) {
709 if ( !IsZero(vll=rowGLIDg[kl]*rowGLJDg[ll]) ) vl += matCLoc(kl,ll)*vll;
710 if ( !IsZero(vll=rowGLIDg[ll]*rowGLJDg[kl]) ) vl += matCLoc(kl,ll)*vll;
714 fFillIndex[nfill] = jIDg;
715 fFillValue[nfill++] = fLocFitAdd ? -vl : vl;
718 if (nfill) matCGlo.AddToRow(iIDg,fFillValue,fFillIndex,nfill);
721 // reset compressed index array
724 printf("After GLOLoc\n");
725 printf("MatCGlo: "); fMatCGlo->Print("");
726 printf("BGlo: "); for (int i=0; i<fNGloPar; i++) printf("%+e |",fVecBGlo[i]); printf("\n");
728 for (int i=nGloInFit;i--;) {
729 fGlo2CGlo[ fCGlo2Glo[i] ] = -1;
733 //---------------------------------------------------- <<<
737 //_____________________________________________________________________________________________
738 Int_t AliMillePede2::GlobalFit(Double_t *par, Double_t *error, Double_t *pull)
740 // performs a requested number of global iterations
743 TStopwatch sw; sw.Start();
746 AliInfo("Starting Global fit.");
747 while (fIter<=fMaxIter) {
749 res = GlobalFitIteration();
752 if (!IsZero(fChi2CutFactor-fChi2CutRef)) {
753 fChi2CutFactor = TMath::Sqrt(fChi2CutFactor);
754 if (fChi2CutFactor < 1.2*fChi2CutRef) {
755 fChi2CutFactor = fChi2CutRef;
756 //RRR fIter = fMaxIter - 1; // Last iteration
763 AliInfo(Form("Global fit %s, CPU time: %.1f",res ? "Converged":"Failed",sw.CpuTime()));
766 if (par) for (int i=fNGloPar;i--;) par[i] = fInitPar[i]+fDeltaPar[i];
768 if (fGloSolveStatus==kInvert) { // errors on params are available
769 if (error) for (int i=fNGloPar;i--;) error[i] = fProcPnt[i]>0 ? TMath::Sqrt(TMath::Abs(fMatCGlo->QueryDiag(i))) : 0.;
770 if (pull) for (int i=fNGloPar;i--;) pull[i] = fProcPnt[i]>0 && (fSigmaPar[i]*fSigmaPar[i]-fMatCGlo->QueryDiag(i))>0. && fSigmaPar[i]>0
771 ? fDeltaPar[i]/TMath::Sqrt(fSigmaPar[i]*fSigmaPar[i]-fMatCGlo->QueryDiag(i)) : 0;
777 //_____________________________________________________________________________________________
778 Int_t AliMillePede2::GlobalFitIteration()
780 // perform global parameters fit once all the local equations have been fitted
782 AliInfo(Form("Global Fit Iteration#%2d (Local Fit Chi^2 cut factor: %.2f)",fIter,fChi2CutFactor));
784 if (!fNGloPar || !fTreeData) {
785 AliInfo("No data was stored, stopping iteration");
793 fConstrUsed = new Bool_t[fNGloConstraints];
794 memset(fConstrUsed,0,fNGloConstraints*sizeof(Bool_t));
796 // Reset all info specific for this step
797 AliMatrixSq& matCGlo = *fMatCGlo;
799 memset(fProcPnt,0,fNGloPar*sizeof(Int_t));
801 fNGloConstraints = fTreeConstr ? fTreeConstr->GetEntries() : 0;
803 // count number of Lagrange constraints: they need new row/cols to be added
804 fNLagrangeConstraints = 0;
805 for (int i=0; i<fNGloConstraints; i++) {
806 ReadRecordConstraint(i);
807 if ( IsZero(fRecord->GetValue(1)) ) fNLagrangeConstraints++; // exact constraint (no error) -> Lagrange multiplier
810 // if needed, readjust the size of the global vector (for matrices this is done automatically)
811 if (!fVecBGlo || fNGloSize!=fNGloPar+fNLagrangeConstraints) {
812 delete[] fVecBGlo; // in case some constraint was added between the two manual iterations
813 fNGloSize = fNGloPar+fNLagrangeConstraints;
814 fVecBGlo = new Double_t[fNGloSize];
816 memset(fVecBGlo,0,fNGloSize*sizeof(double));
819 fNLocFitsRejected = 0;
822 // Process data records and build the matrices
823 Long_t ndr = fTreeData->GetEntries();
824 Long_t first = fSelFirst>0 ? fSelFirst : 0;
825 Long_t last = fSelLast<1 ? ndr : (fSelLast>=ndr ? ndr : fSelLast+Long_t(1));
828 AliInfo(Form("Building the Global matrix from data records %ld : %ld",first,last));
831 TStopwatch swt; swt.Start();
832 fLocFitAdd = kTRUE; // add contributions of matching tracks
833 for (Long_t i=0;i<ndr;i++) {
834 Long_t iev = i+first;
836 if (!IsRecordAcceptable()) continue;
838 if ( (i%int(0.2*ndr)) == 0) printf("%.1f%% of local fits done\n", double(100.*i)/ndr);
841 printf("%ld local fits done: ", ndr);
843 printf("MatCGlo: "); fMatCGlo->Print("l");
844 printf("BGlo: "); for (int i=0; i<fNGloPar; i++) printf("%+e |",fVecBGlo[i]); printf("\n");
850 // ---------------------- Reject parameters with low statistics ------------>>
852 if (fMinPntValid>1 && fNGroupsSet) {
854 printf("Checking parameters with statistics < %d\n",fMinPntValid);
857 // 1) build the list of parameters to fix
858 Int_t fixArrSize = 10;
859 Int_t nFixedGroups = 0;
860 TArrayI fixGroups(fixArrSize);
864 double oldMin = 1.e20;
865 double oldMax =-1.e20;
867 for (int i=fNGloPar;i--;) { // // Reset row and column of fixed params and add 1/sig^2 to free ones
868 int grID = fParamGrID[i];
869 if (grID<0) continue; // not in the group
871 if (grID!=grIDold) { // starting new group
872 if (grIDold>=0) { // decide if the group has enough statistics
873 if (oldMin<fMinPntValid && oldMax<2*fMinPntValid) { // suppress group
874 for (int iold=oldStart;iold>i;iold--) fProcPnt[iold] = 0;
875 Bool_t fnd = kFALSE; // check if the group is already accounted
876 for (int j=nFixedGroups;j--;) if (fixGroups[j]==grIDold) {fnd=kTRUE; break;}
878 if (nFixedGroups>=fixArrSize) {fixArrSize*=2; fixGroups.Set(fixArrSize);}
879 fixGroups[nFixedGroups++] = grIDold; // add group to fix
883 grIDold = grID; // mark the start of the new group
888 if (oldMin>fProcPnt[i]) oldMin = fProcPnt[i];
889 if (oldMax<fProcPnt[i]) oldMax = fProcPnt[i];
892 // extra check for the last group
893 if (grIDold>=0 && oldMin<fMinPntValid && oldMax<2*fMinPntValid) { // suppress group
894 for (int iold=oldStart;iold--;) fProcPnt[iold] = 0;
895 Bool_t fnd = kFALSE; // check if the group is already accounted
896 for (int j=nFixedGroups;j--;) if (fixGroups[j]==grIDold) {fnd=kTRUE; break;}
898 if (nFixedGroups>=fixArrSize) {fixArrSize*=2; fixGroups.Set(fixArrSize);}
899 fixGroups[nFixedGroups++] = grIDold; // add group to fix
903 // 2) loop over records and add contributions of fixed groups with negative sign
906 for (Long_t i=0;i<ndr;i++) {
907 Long_t iev = i+first;
909 if (!IsRecordAcceptable()) continue;
910 Bool_t suppr = kFALSE;
911 for (int ifx=nFixedGroups;ifx--;)if (fRecord->IsGroupPresent(fixGroups[ifx])) suppr = kTRUE;
912 if (suppr) LocalFit();
917 printf("Suppressed contributions of groups with NPoints<%d :\n",fMinPntValid);
918 for (int i=0;i<nFixedGroups;i++) printf("%d ",fixGroups[i]); printf("\n");
923 // ---------------------- Reject parameters with low statistics ------------<<
925 // add large number to diagonal of fixed params
927 for (int i=fNGloPar;i--;) { // // Reset row and column of fixed params and add 1/sig^2 to free ones
928 // printf("#%3d : Nproc : %5d grp: %d\n",i,fProcPnt[i],fParamGrID[i]);
932 matCGlo.DiagElem(i) = 1.;//float(fNLocEquations*fNLocEquations);
933 // matCGlo.DiagElem(i) = float(fNLocEquations*fNLocEquations);
935 else matCGlo.DiagElem(i) += (fgWeightSigma ? fProcPnt[i] : 1.)/(fSigmaPar[i]*fSigmaPar[i]);
938 for (int i=fNGloPar;i--;) fDiagCGlo[i] = matCGlo.QueryDiag(i); // save the diagonal elements
940 // add constraint equations
941 int nVar = fNGloPar; // Current size of global matrix
942 for (int i=0; i<fNGloConstraints; i++) {
943 ReadRecordConstraint(i);
944 double val = fRecord->GetValue(0);
945 double sig = fRecord->GetValue(1);
946 int *indV = fRecord->GetIndex()+2;
947 double *der = fRecord->GetValue()+2;
948 int csize = fRecord->GetSize()-2;
950 // check if after suppression of fixed variables there are non-0 derivatives
951 // and determine the max statistics of involved params
954 for (int j=csize;j--;) {
955 if (fProcPnt[indV[j]]<1) nSuppressed++;
957 maxStat = TMath::Max(maxStat,fProcPnt[indV[j]]);
961 if (nSuppressed==csize) {
962 // AliInfo(Form("Neglecting constraint %d of %d derivatives since no free parameters left",i,csize));
964 // was this constraint ever created ?
965 if ( sig==0 && fConstrUsed[i] ) { // this is needed only for constraints with Lagrange multiplier
966 // to avoid empty row impose dummy constraint on "Lagrange multiplier"
967 matCGlo.DiagElem(nVar) = 1.;
968 fVecBGlo[nVar++] = 0;
973 // account for already accumulated corrections
974 for (int j=csize; j--;) val -= der[j]*(fInitPar[ indV[j] ]+fDeltaPar[ indV[j] ]);
976 if (sig > 0) { // this is a gaussian constriant: no Lagrange multipliers are added
978 double sig2i = (fgWeightSigma ? TMath::Sqrt(maxStat) : 1.)/sig/sig;
979 for (int ir=0;ir<csize;ir++) {
981 for (int ic=0;ic<=ir;ic++) { // matrix is symmetric
983 double vl = der[ir]*der[ic]*sig2i;
984 if (!IsZero(vl)) matCGlo(iID,jID) += vl;
986 fVecBGlo[iID] += val*der[ir]*sig2i;
989 else { // this is exact constriant: Lagrange multipliers must be added
990 for (int j=csize; j--;) {
992 if (fProcPnt[jID]<1) continue; // this parameter was fixed, don't put it into constraint
993 matCGlo(nVar,jID) = float(fNLocEquations)*der[j]; // fMatCGlo is symmetric, only lower triangle is filled
996 if (matCGlo.QueryDiag(nVar)) matCGlo.DiagElem(nVar) = 0.0;
997 fVecBGlo[nVar++] = float(fNLocEquations)*val; //RS ? should we use here fNLocFits ?
998 fConstrUsed[i] = kTRUE;
1002 AliInfo(Form("Obtained %-7ld equations from %-7ld records (%-7ld rejected). Fixed %-4d globals",
1003 fNLocEquations,fNLocFits,fNLocFitsRejected,fNGloFix));
1009 printf("Solving:\n");
1011 for (int i=0;i<fNGloSize;i++) printf("b%2d : %+e\n",i,fVecBGlo[i]);
1013 fGloSolveStatus = SolveGlobalMatEq(); // obtain solution for this step
1015 printf("Solve %d |",fIter); sws.Print();
1018 AliInfo(Form("Iteration#%2d %s. CPU time: %.1f",fIter,fGloSolveStatus==kFailed ? "Failed":"Converged",sw.CpuTime()));
1019 if (fGloSolveStatus==kFailed) return 0;
1021 for (int i=fNGloPar;i--;) fDeltaPar[i] += fVecBGlo[i]; // Update global parameters values (for iterations)
1023 // PrintGlobalParameters();
1027 //_____________________________________________________________________________________________
1028 Int_t AliMillePede2::SolveGlobalMatEq()
1031 // solve global matrix equation MatCGlob*X=VecBGlo and store the result in the VecBGlo
1034 printf("GlobalMatrix\n");
1037 for (int i=0;i<fNGloPar;i++) printf("%d %+e\n",i,fVecBGlo[i]);
1040 if (!fgIsMatGloSparse) {
1042 if (fNLagrangeConstraints==0) { // pos-def systems are faster to solve by Cholesky
1043 if ( ((AliSymMatrix*)fMatCGlo)->SolveChol(fVecBGlo, fgInvChol) ) return fgInvChol ? kInvert:kNoInversion;
1044 else AliInfo("Solution of Global Dense System by Cholesky failed, trying Gaussian Elimiation");
1047 if (((AliSymMatrix*)fMatCGlo)->SolveSpmInv(fVecBGlo, kTRUE)) return kInvert;
1048 else AliInfo("Solution of Global Dense System by Gaussian Elimination failed, trying iterative methods");
1050 // try to solve by minres
1051 TVectorD sol(fNGloSize);
1053 AliMinResSolve *slv = new AliMinResSolve(fMatCGlo,fVecBGlo);
1054 if (!slv) return kFailed;
1056 Bool_t res = kFALSE;
1057 if (fgIterSol == AliMinResSolve::kSolMinRes)
1058 res = slv->SolveMinRes(sol,fgMinResCondType,fgMinResMaxIter,fgMinResTol);
1059 else if (fgIterSol == AliMinResSolve::kSolFGMRes)
1060 res = slv->SolveFGMRES(sol,fgMinResCondType,fgMinResMaxIter,fgMinResTol,fgNKrylovV);
1062 AliInfo(Form("Undefined Iteritive Solver ID=%d, only %d are defined",fgIterSol,AliMinResSolve::kNSolvers));
1065 const char* faildump = "fgmr_failed.dat";
1066 int defout = dup(1);
1068 AliInfo("Failed on dup");
1071 int slvDump = open(faildump, O_RDWR|O_CREAT, 0666);
1075 printf("#Failed to solve using solver %d with PreCond: %d MaxIter: %d Tol: %e NKrylov: %d\n",
1076 fgIterSol,fgMinResCondType,fgMinResMaxIter,fgMinResTol,fgNKrylovV);
1077 printf("#Dump of matrix:\n");
1078 fMatCGlo->Print("10");
1079 printf("#Dump of RHS:\n");
1080 for (int i=0;i<fNGloSize;i++) printf("%d %+.10f\n",i,fVecBGlo[i]);
1084 printf("#Dumped failed matrix and RHS to %s\n",faildump);
1086 else AliInfo("Failed on file open for matrix dumping");
1090 for (int i=fNGloSize;i--;) fVecBGlo[i] = sol[i];
1091 return kNoInversion;
1095 //_____________________________________________________________________________________________
1096 Float_t AliMillePede2::Chi2DoFLim(int nSig, int nDoF) const
1098 /// return the limit in chi^2/nd for n sigmas stdev authorized
1099 // Only n=1, 2, and 3 are expected in input
1101 float sn[3] = {0.47523, 1.690140, 2.782170};
1102 float table[3][30] = {{1.0000, 1.1479, 1.1753, 1.1798, 1.1775, 1.1730, 1.1680, 1.1630,
1103 1.1581, 1.1536, 1.1493, 1.1454, 1.1417, 1.1383, 1.1351, 1.1321,
1104 1.1293, 1.1266, 1.1242, 1.1218, 1.1196, 1.1175, 1.1155, 1.1136,
1105 1.1119, 1.1101, 1.1085, 1.1070, 1.1055, 1.1040},
1106 {4.0000, 3.0900, 2.6750, 2.4290, 2.2628, 2.1415, 2.0481, 1.9736,
1107 1.9124, 1.8610, 1.8171, 1.7791, 1.7457, 1.7161, 1.6897, 1.6658,
1108 1.6442, 1.6246, 1.6065, 1.5899, 1.5745, 1.5603, 1.5470, 1.5346,
1109 1.5230, 1.5120, 1.5017, 1.4920, 1.4829, 1.4742},
1110 {9.0000, 5.9146, 4.7184, 4.0628, 3.6410, 3.3436, 3.1209, 2.9468,
1111 2.8063, 2.6902, 2.5922, 2.5082, 2.4352, 2.3711, 2.3143, 2.2635,
1112 2.2178, 2.1764, 2.1386, 2.1040, 2.0722, 2.0428, 2.0155, 1.9901,
1113 1.9665, 1.9443, 1.9235, 1.9040, 1.8855, 1.8681}};
1119 lNSig = TMath::Max(1,TMath::Min(nSig,3));
1122 return table[lNSig-1][nDoF-1];
1124 else { // approximation
1125 return ((sn[lNSig-1]+TMath::Sqrt(float(2*nDoF-3)))*
1126 (sn[lNSig-1]+TMath::Sqrt(float(2*nDoF-3))))/float(2*nDoF-2);
1131 //_____________________________________________________________________________________________
1132 Int_t AliMillePede2::SetIterations(double lChi2CutFac)
1134 // Number of iterations is calculated from lChi2CutFac
1135 fChi2CutFactor = TMath::Max(1.0, lChi2CutFac);
1137 AliInfo(Form("Initial cut factor is %f",fChi2CutFactor));
1138 fIter = 1; // Initializes the iteration process
1142 //_____________________________________________________________________________________________
1143 Double_t AliMillePede2::GetParError(int iPar) const
1145 // return error for parameter iPar
1146 if (fGloSolveStatus==kInvert) {
1147 double res = fMatCGlo->QueryDiag(iPar);
1148 if (res>=0) return TMath::Sqrt(res);
1154 //_____________________________________________________________________________________________
1155 Int_t AliMillePede2::PrintGlobalParameters() const
1157 /// Print the final results into the logfile
1159 double lGlobalCor =0.;
1162 AliInfo(" Result of fit for global parameters");
1163 AliInfo(" ===================================");
1164 AliInfo(" I initial final differ lastcor error gcor Npnt");
1165 AliInfo("----------------------------------------------------------------------------------------------");
1167 for (int i=0; i<fNGloPar; i++) {
1168 lError = GetParError(i);
1172 if (fGloSolveStatus==kInvert && TMath::Abs( (dg=fMatCGlo->QueryDiag(i)) *fDiagCGlo[i]) > 0) {
1173 lGlobalCor = TMath::Sqrt(TMath::Abs(1.0-1.0/(dg*fDiagCGlo[i])));
1174 AliInfo(Form("%d\t %.6f\t %.6f\t %.6f\t %.6f\t %.6f\t %.6f\t %6d",
1175 i,fInitPar[i],fInitPar[i]+fDeltaPar[i],fDeltaPar[i],fVecBGlo[i],lError,lGlobalCor,fProcPnt[i]));
1178 AliInfo(Form("%d\t %.6f\t %.6f\t %.6f\t %.6f\t OFF\t OFF\t %6d",i,fInitPar[i],fInitPar[i]+fDeltaPar[i],
1179 fDeltaPar[i],fVecBGlo[i],fProcPnt[i]));
1185 //_____________________________________________________________________________________________
1186 Bool_t AliMillePede2::IsRecordAcceptable() const
1188 // validate record according run lists set by the user
1189 static Long_t prevRunID = kMaxInt;
1190 static Bool_t prevAns = kTRUE;
1191 Long_t runID = fRecord->GetRunID();
1192 if (runID!=prevRunID) {
1195 // is run to be rejected?
1196 if (fRejRunList && (n=fRejRunList->GetSize())) {
1198 for (int i=n;i--;) if (runID == (*fRejRunList)[i]) {
1200 printf("New Run to reject: %ld -> %d\n",runID,prevAns);
1204 else if (fAccRunList && (n=fAccRunList->GetSize())) { // is run specifically selected
1206 for (int i=n;i--;) if (runID == (*fAccRunList)[i]) {prevAns = kTRUE; break;}
1214 //_____________________________________________________________________________________________
1215 void AliMillePede2::SetRejRunList(const UInt_t *runs, Int_t nruns)
1217 // set the list of runs to be rejected
1218 if (fRejRunList) delete fRejRunList;
1220 if (nruns<1 || !runs) return;
1221 fRejRunList = new TArrayL(nruns);
1222 for (int i=0;i<nruns;i++) (*fRejRunList)[i] = runs[i];
1225 //_____________________________________________________________________________________________
1226 void AliMillePede2::SetAccRunList(const UInt_t *runs, Int_t nruns)
1228 // set the list of runs to be selected
1229 if (fAccRunList) delete fAccRunList;
1231 if (nruns<1 || !runs) return;
1232 fAccRunList = new TArrayL(nruns);
1233 for (int i=0;i<nruns;i++) (*fAccRunList)[i] = runs[i];