1 /**********************************************************************************************/
2 /* Fast symmetric matrix with dynamically expandable size. */
3 /* Only part can be used for matrix operations. It is defined as: */
4 /* fNCols: rows built by constructor (GetSizeBooked) */
5 /* fNRows: number of rows added dynamically (automatically added on assignment to row) */
7 /* fNRowIndex: total size (fNCols+fNRows), GetSize */
8 /* fRowLwb : actual size to used for given operation, by default = total size, GetSizeUsed */
10 /* Author: ruben.shahoyan@cern.ch */
12 /**********************************************************************************************/
21 #include "AliSymMatrix.h"
25 ClassImp(AliSymMatrix)
28 AliSymMatrix* AliSymMatrix::fgBuffer = 0;
29 Int_t AliSymMatrix::fgCopyCnt = 0;
30 //___________________________________________________________
31 AliSymMatrix::AliSymMatrix()
32 : fElems(0),fElemsAdd(0)
34 // default constructor
39 //___________________________________________________________
40 AliSymMatrix::AliSymMatrix(Int_t size)
41 : AliMatrixSq(),fElems(0),fElemsAdd(0)
43 //constructor for matrix with defined size
45 fNrowIndex = fNcols = fRowLwb = size;
46 fElems = new Double_t[fNcols*(fNcols+1)/2];
53 //___________________________________________________________
54 AliSymMatrix::AliSymMatrix(const AliSymMatrix &src)
55 : AliMatrixSq(src),fElems(0),fElemsAdd(0)
58 fNrowIndex = fNcols = src.GetSize();
60 fRowLwb = src.GetSizeUsed();
62 int nmainel = fNcols*(fNcols+1)/2;
63 fElems = new Double_t[nmainel];
64 nmainel = src.fNcols*(src.fNcols+1)/2;
65 memcpy(fElems,src.fElems,nmainel*sizeof(Double_t));
66 if (src.GetSizeAdded()) { // transfer extra rows to main matrix
67 Double_t *pnt = fElems + nmainel;
68 int ncl = src.GetSizeBooked() + 1;
69 for (int ir=0;ir<src.GetSizeAdded();ir++) {
70 memcpy(pnt,src.fElemsAdd[ir],ncl*sizeof(Double_t));
82 //___________________________________________________________
83 AliSymMatrix::~AliSymMatrix()
86 if (--fgCopyCnt < 1 && fgBuffer) {delete fgBuffer; fgBuffer = 0;}
89 //___________________________________________________________
90 AliSymMatrix& AliSymMatrix::operator=(const AliSymMatrix& src)
92 // assignment operator
94 TObject::operator=(src);
95 if (GetSizeBooked()!=src.GetSizeBooked() && GetSizeAdded()!=src.GetSizeAdded()) {
96 // recreate the matrix
97 if (fElems) delete[] fElems;
98 for (int i=0;i<GetSizeAdded();i++) delete[] fElemsAdd[i];
101 fNrowIndex = src.GetSize();
102 fNcols = src.GetSize();
104 fRowLwb = src.GetSizeUsed();
105 fElems = new Double_t[GetSize()*(GetSize()+1)/2];
106 int nmainel = src.GetSizeBooked()*(src.GetSizeBooked()+1);
107 memcpy(fElems,src.fElems,nmainel*sizeof(Double_t));
108 if (src.GetSizeAdded()) { // transfer extra rows to main matrix
109 Double_t *pnt = fElems + nmainel;//*sizeof(Double_t);
110 int ncl = src.GetSizeBooked() + 1;
111 for (int ir=0;ir<src.GetSizeAdded();ir++) {
113 memcpy(pnt,src.fElemsAdd[ir],ncl*sizeof(Double_t));
114 pnt += ncl;//*sizeof(Double_t);
120 memcpy(fElems,src.fElems,GetSizeBooked()*(GetSizeBooked()+1)/2*sizeof(Double_t));
121 int ncl = GetSizeBooked() + 1;
122 for (int ir=0;ir<GetSizeAdded();ir++) { // dynamic rows
124 memcpy(fElemsAdd[ir],src.fElemsAdd[ir],ncl*sizeof(Double_t));
132 //___________________________________________________________
133 AliSymMatrix& AliSymMatrix::operator+=(const AliSymMatrix& src)
136 if (GetSizeUsed() != src.GetSizeUsed()) {
137 AliError("Matrix sizes are different");
140 for (int i=0;i<GetSizeUsed();i++) for (int j=i;j<GetSizeUsed();j++) (*this)(j,i) += src(j,i);
144 //___________________________________________________________
145 void AliSymMatrix::Clear(Option_t*)
147 // clear dynamic part
148 if (fElems) {delete[] fElems; fElems = 0;}
151 for (int i=0;i<GetSizeAdded();i++) delete[] fElemsAdd[i];
155 fNrowIndex = fNcols = fNrows = fRowLwb = 0;
159 //___________________________________________________________
160 Float_t AliSymMatrix::GetDensity() const
162 // get fraction of non-zero elements
164 for (int i=GetSizeUsed();i--;) for (int j=i+1;j--;) if (!IsZero(GetEl(i,j))) nel++;
165 return 2.*nel/( (GetSizeUsed()+1)*GetSizeUsed() );
168 //___________________________________________________________
169 void AliSymMatrix::Print(Option_t* option) const
172 printf("Symmetric Matrix: Size = %d (%d rows added dynamically), %d used\n",GetSize(),GetSizeAdded(),GetSizeUsed());
173 TString opt = option; opt.ToLower();
174 if (opt.IsNull()) return;
175 opt = "%"; opt += 1+int(TMath::Log10(double(GetSize()))); opt+="d|";
176 for (Int_t i=0;i<GetSizeUsed();i++) {
178 for (Int_t j=0;j<=i;j++) printf("%+.3e|",GetEl(i,j));
183 //___________________________________________________________
184 void AliSymMatrix::MultiplyByVec(const Double_t *vecIn,Double_t *vecOut) const
186 // fill vecOut by matrix*vecIn
187 // vector should be of the same size as the matrix
188 for (int i=GetSizeUsed();i--;) {
190 for (int j=GetSizeUsed();j--;) vecOut[i] += vecIn[j]*GetEl(i,j);
195 //___________________________________________________________
196 AliSymMatrix* AliSymMatrix::DecomposeChol()
198 // Return a matrix with Choleski decomposition
199 // Adopted from Numerical Recipes in C, ch.2-9, http://www.nr.com
200 // consturcts Cholesky decomposition of SYMMETRIC and
201 // POSITIVELY-DEFINED matrix a (a=L*Lt)
202 // Only upper triangle of the matrix has to be filled.
203 // In opposite to function from the book, the matrix is modified:
204 // lower triangle and diagonal are refilled.
206 if (!fgBuffer || fgBuffer->GetSizeUsed()!=GetSizeUsed()) {
208 fgBuffer = new AliSymMatrix(*this);
210 else (*fgBuffer) = *this;
212 AliSymMatrix& mchol = *fgBuffer;
214 for (int i=0;i<GetSizeUsed();i++) {
215 Double_t *rowi = mchol.GetRow(i);
216 for (int j=i;j<GetSizeUsed();j++) {
217 Double_t *rowj = mchol.GetRow(j);
218 double sum = rowj[i];
219 for (int k=i-1;k>=0;k--) if (rowi[k]&&rowj[k]) sum -= rowi[k]*rowj[k];
221 if (sum <= 0.0) { // not positive-definite
222 AliInfo(Form("The matrix is not positive definite [%e]\n"
223 "Choleski decomposition is not possible",sum));
227 rowi[i] = TMath::Sqrt(sum);
229 } else rowj[i] = sum/rowi[i];
235 //___________________________________________________________
236 Bool_t AliSymMatrix::InvertChol()
238 // Invert matrix using Choleski decomposition
240 AliSymMatrix* mchol = DecomposeChol();
242 AliInfo("Failed to invert the matrix");
251 //___________________________________________________________
252 void AliSymMatrix::InvertChol(AliSymMatrix* pmchol)
254 // Invert matrix using Choleski decomposition, provided the Cholseki's L matrix
257 AliSymMatrix& mchol = *pmchol;
259 // Invert decomposed triangular L matrix (Lower triangle is filled)
260 for (int i=0;i<GetSizeUsed();i++) {
261 mchol(i,i) = 1.0/mchol(i,i);
262 for (int j=i+1;j<GetSizeUsed();j++) {
263 Double_t *rowj = mchol.GetRow(j);
265 for (int k=i;k<j;k++) if (rowj[k]) {
266 double &mki = mchol(k,i); if (mki) sum -= rowj[k]*mki;
268 rowj[i] = sum/rowj[j];
272 // take product of the inverted Choleski L matrix with its transposed
273 for (int i=GetSizeUsed();i--;) {
274 for (int j=i+1;j--;) {
276 for (int k=i;k<GetSizeUsed();k++) {
277 double &mik = mchol(i,k);
279 double &mjk = mchol(j,k);
280 if (mjk) sum += mik*mjk;
290 //___________________________________________________________
291 Bool_t AliSymMatrix::SolveChol(Double_t *b, Bool_t invert)
293 // Adopted from Numerical Recipes in C, ch.2-9, http://www.nr.com
294 // Solves the set of n linear equations A x = b,
295 // where a is a positive-definite symmetric matrix.
296 // a[1..n][1..n] is the output of the routine CholDecomposw.
297 // Only the lower triangle of a is accessed. b[1..n] is input as the
298 // right-hand side vector. The solution vector is returned in b[1..n].
303 AliSymMatrix *pmchol = DecomposeChol();
305 AliInfo("SolveChol failed");
309 AliSymMatrix& mchol = *pmchol;
311 for (i=0;i<GetSizeUsed();i++) {
312 Double_t *rowi = mchol.GetRow(i);
313 for (sum=b[i],k=i-1;k>=0;k--) if (rowi[k]&&b[k]) sum -= rowi[k]*b[k];
317 for (i=GetSizeUsed()-1;i>=0;i--) {
318 for (sum=b[i],k=i+1;k<GetSizeUsed();k++) if (b[k]) {
319 double &mki=mchol(k,i); if (mki) sum -= mki*b[k];
324 if (invert) InvertChol(pmchol);
329 //___________________________________________________________
330 Bool_t AliSymMatrix::SolveChol(TVectorD &b, Bool_t invert)
332 return SolveChol((Double_t*)b.GetMatrixArray(),invert);
336 //___________________________________________________________
337 Bool_t AliSymMatrix::SolveChol(Double_t *brhs, Double_t *bsol,Bool_t invert)
339 memcpy(bsol,brhs,GetSizeUsed()*sizeof(Double_t));
340 return SolveChol(bsol,invert);
343 //___________________________________________________________
344 Bool_t AliSymMatrix::SolveChol(const TVectorD &brhs, TVectorD &bsol,Bool_t invert)
347 return SolveChol(bsol,invert);
350 //___________________________________________________________
351 void AliSymMatrix::AddRows(int nrows)
355 Double_t **pnew = new Double_t*[nrows+fNrows];
356 for (int ir=0;ir<fNrows;ir++) pnew[ir] = fElemsAdd[ir]; // copy old extra rows
357 for (int ir=0;ir<nrows;ir++) {
358 int ncl = GetSize()+1;
359 pnew[fNrows] = new Double_t[ncl];
360 memset(pnew[fNrows],0,ncl*sizeof(Double_t));
370 //___________________________________________________________
371 void AliSymMatrix::Reset()
373 // if additional rows exist, regularize it
376 for (int i=0;i<fNrows;i++) delete[] fElemsAdd[i];
377 delete[] fElemsAdd; fElemsAdd = 0;
378 fNcols = fRowLwb = fNrowIndex;
379 fElems = new Double_t[GetSize()*(GetSize()+1)/2];
382 if (fElems) memset(fElems,0,GetSize()*(GetSize()+1)/2*sizeof(Double_t));
386 //___________________________________________________________
388 void AliSymMatrix::AddToRow(Int_t r, Double_t *valc,Int_t *indc,Int_t n)
390 // for (int i=n;i--;) {
391 // (*this)(indc[i],r) += valc[i];
397 AddRows(r-fNrowIndex+1);
398 row = &((fElemsAdd[r-fNcols])[0]);
400 else row = &fElems[GetIndex(r,0)];
404 if (indc[i]>r) continue;
405 row[indc[i]] += valc[i];
408 if (nadd == n) return;
412 if (indc[i]>r) (*this)(indc[i],r) += valc[i];
418 //___________________________________________________________
419 Double_t* AliSymMatrix::GetRow(Int_t r)
421 // get pointer on the row
424 AddRows(r-GetSize()+1);
425 AliDebug(2,Form("create %d of %d\n",r, nn));
426 return &((fElemsAdd[r-GetSizeBooked()])[0]);
428 else return &fElems[GetIndex(r,0)];
432 //___________________________________________________________
433 int AliSymMatrix::SolveSpmInv(double *vecB, Bool_t stabilize)
435 // Solution a la MP1: gaussian eliminations
436 /// Obtain solution of a system of linear equations with symmetric matrix
437 /// and the inverse (using 'singular-value friendly' GAUSS pivot)
444 int nGlo = GetSizeUsed();
445 bool *bUnUsed = new bool[nGlo];
446 double *rowMax,*colMax=0;
447 rowMax = new double[nGlo];
450 colMax = new double[nGlo];
451 for (Int_t i=nGlo; i--;) rowMax[i] = colMax[i] = 0.0;
452 for (Int_t i=nGlo; i--;) for (Int_t j=i+1;j--;) {
453 double vl = TMath::Abs(Query(i,j));
454 if (IsZero(vl)) continue;
455 if (vl > rowMax[i]) rowMax[i] = vl; // Max elemt of row i
456 if (vl > colMax[j]) colMax[j] = vl; // Max elemt of column j
458 if (vl > rowMax[j]) rowMax[j] = vl; // Max elemt of row j
459 if (vl > colMax[i]) colMax[i] = vl; // Max elemt of column i
462 for (Int_t i=nGlo; i--;) {
463 if (!IsZero(rowMax[i])) rowMax[i] = 1./rowMax[i]; // Max elemt of row i
464 if (!IsZero(colMax[i])) colMax[i] = 1./colMax[i]; // Max elemt of column i
469 for (Int_t i=nGlo; i--;) bUnUsed[i] = true;
471 if (!fgBuffer || fgBuffer->GetSizeUsed()!=GetSizeUsed()) {
473 fgBuffer = new AliSymMatrix(*this);
475 else (*fgBuffer) = *this;
477 if (stabilize) for (int i=0;i<nGlo; i++) { // Small loop for matrix equilibration (gives a better conditioning)
478 for (int j=0;j<=i; j++) {
479 double vl = Query(i,j);
480 if (!IsZero(vl)) SetEl(i,j, TMath::Sqrt(rowMax[i])*vl*TMath::Sqrt(colMax[j]) ); // Equilibrate the V matrix
482 for (int j=i+1;j<nGlo;j++) {
483 double vl = Query(j,i);
484 if (!IsZero(vl)) fgBuffer->SetEl(j,i,TMath::Sqrt(rowMax[i])*vl*TMath::Sqrt(colMax[j]) ); // Equilibrate the V matrix
488 for (Int_t j=nGlo; j--;) fgBuffer->DiagElem(j) = TMath::Abs(QueryDiag(j)); // save diagonal elem absolute values
490 for (Int_t i=0; i<nGlo; i++) {
494 for (Int_t j=0; j<nGlo; j++) { // First look for the pivot, ie max unused diagonal element
496 if (bUnUsed[j] && (TMath::Abs(vl=QueryDiag(j))>TMath::Max(TMath::Abs(vPivot),eps*fgBuffer->QueryDiag(j)))) {
502 if (iPivot >= 0) { // pivot found
504 bUnUsed[iPivot] = false; // This value is used
506 DiagElem(iPivot) = -vPivot; // Replace pivot by its inverse
508 for (Int_t j=0; j<nGlo; j++) {
509 for (Int_t jj=0; jj<nGlo; jj++) {
510 if (j != iPivot && jj != iPivot) {// Other elements (!!! do them first as you use old matV[k][j]'s !!!)
511 double &r = j>=jj ? (*this)(j,jj) : (*fgBuffer)(jj,j);
512 r -= vPivot* ( j>iPivot ? Query(j,iPivot) : fgBuffer->Query(iPivot,j) )
513 * ( iPivot>jj ? Query(iPivot,jj) : fgBuffer->Query(jj,iPivot));
518 for (Int_t j=0; j<nGlo; j++) if (j != iPivot) { // Pivot row or column elements
519 (*this)(j,iPivot) *= vPivot;
520 (*fgBuffer)(iPivot,j) *= vPivot;
524 else { // No more pivot value (clear those elements)
525 for (Int_t j=0; j<nGlo; j++) {
528 for (Int_t k=0; k<nGlo; k++) {
530 if (j!=k) (*fgBuffer)(j,k) = 0;
534 break; // No more pivots anyway, stop here
538 if (stabilize) for (Int_t i=0; i<nGlo; i++) for (Int_t j=0; j<nGlo; j++) {
539 double vl = TMath::Sqrt(colMax[i])*TMath::Sqrt(rowMax[j]); // Correct matrix V
540 if (i>=j) (*this)(i,j) *= vl;
541 else (*fgBuffer)(j,i) *= vl;
544 for (Int_t j=0; j<nGlo; j++) {
546 for (Int_t jj=0; jj<nGlo; jj++) { // Reverse matrix elements
548 if (j>=jj) vl = (*this)(j,jj) = -Query(j,jj);
549 else vl = (*fgBuffer)(j,jj) = -fgBuffer->Query(j,jj);
550 rowMax[j] += vl*vecB[jj];
554 for (Int_t j=0; j<nGlo; j++) {
555 vecB[j] = rowMax[j]; // The final result
560 if (stabilize) delete [] colMax;