]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliCheb3D.cxx
Setting the class name meta-data field in the constructor
[u/mrichter/AliRoot.git] / STEER / AliCheb3D.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 #include <TString.h>
17 #include <TSystem.h>
18 #include <TROOT.h>
19 #include <TRandom.h>
20 #include <stdio.h>
21 #include <TMethodCall.h>
22 #include <TMath.h>
23 #include <TH1.h>
24 #include "AliCheb3D.h"
25 #include "AliCheb3DCalc.h"
26
27 ClassImp(AliCheb3D)
28
29 //__________________________________________________________________________________________
30 AliCheb3D::AliCheb3D() : 
31   fDimOut(0), 
32   fPrec(0), 
33   fChebCalc(1), 
34   fMaxCoefs(0), 
35   fResTmp(0), 
36   fGrid(0), 
37   fUsrFunName(""), 
38   fUsrMacro(0) 
39 {
40   for (int i=3;i--;) fBMin[i] = fBMax[i] = fBScale[i] = fBOffset[i] = 0;
41 }
42
43 //__________________________________________________________________________________________
44 AliCheb3D::AliCheb3D(const AliCheb3D& src) : 
45   TNamed(src),
46   fDimOut(src.fDimOut), 
47   fPrec(src.fPrec), 
48   fChebCalc(1), 
49   fMaxCoefs(src.fMaxCoefs), 
50   fResTmp(0),
51   fGrid(0), 
52   fUsrFunName(src.fUsrFunName), 
53   fUsrMacro(0)
54 {
55   // read coefs from text file
56   for (int i=3;i--;) {
57     fBMin[i]    = src.fBMin[i];
58     fBMax[i]    = src.fBMax[i];
59     fBScale[i]  = src.fBScale[i];
60     fBOffset[i] = src.fBOffset[i];
61     fNPoints[i] = src.fNPoints[i];
62   }
63   for (int i=0;i<fDimOut;i++) {
64     AliCheb3DCalc* cbc = src.GetChebCalc(i);
65     if (cbc) fChebCalc.AddAtAndExpand(new AliCheb3DCalc(*cbc),i);
66   }
67 }
68
69 //__________________________________________________________________________________________
70 AliCheb3D::AliCheb3D(const char* inpFile) : 
71   fDimOut(0), 
72   fPrec(0),  
73   fChebCalc(1),
74   fMaxCoefs(0),  
75   fResTmp(0),
76   fGrid(0), 
77   fUsrFunName(""), 
78   fUsrMacro(0)
79 {
80   // read coefs from text file
81   for (int i=3;i--;) fBMin[i] = fBMax[i] = fBScale[i] = fBOffset[i] = 0;
82   LoadData(inpFile);
83 }
84
85 //__________________________________________________________________________________________
86 AliCheb3D::AliCheb3D(FILE* stream) : 
87   fDimOut(0), 
88   fPrec(0), 
89   fChebCalc(1), 
90   fMaxCoefs(0),
91   fResTmp(0),
92   fGrid(0),
93   fUsrFunName(""),
94   fUsrMacro(0)
95 {
96   // read coefs from stream
97   for (int i=3;i--;) fBMin[i] = fBMax[i] = fBScale[i] = fBOffset[i] = 0;
98   LoadData(stream);
99 }
100
101 //__________________________________________________________________________________________
102 #ifdef _INC_CREATION_ALICHEB3D_
103 AliCheb3D::AliCheb3D(const char* funName, int DimOut, Float_t  *bmin,Float_t  *bmax, Int_t *npoints, Float_t prec) : 
104   TNamed(funName,funName), 
105   fDimOut(0), 
106   fPrec(TMath::Max(1.E-12f,prec)), 
107   fChebCalc(1), 
108   fMaxCoefs(0), 
109   fResTmp(0), 
110   fGrid(0), 
111   fUsrFunName("") ,
112   fUsrMacro(0)
113 {
114   // Construct the parameterization for the function
115   // funName : name of the file containing the function: void funName(Float_t * inp,Float_t * out)
116   // DimOut  : dimension of the vector computed by the user function
117   // bmin    : array of 3 elements with the lower boundaries of the region where the function is defined
118   // bmax    : array of 3 elements with the upper boundaries of the region where the function is defined
119   // npoints : array of 3 elements with the number of points to compute in each of 3 dimension
120   // prec    : max allowed absolute difference between the user function and computed parameterization on the requested grid
121   //
122   if (DimOut<1) {Error("AliCheb3D","Requested output dimension is %d\nStop\n",fDimOut); exit(1);}
123   SetDimOut(DimOut);
124   PrepareBoundaries(bmin,bmax);
125   DefineGrid(npoints);
126   SetUsrFunction(funName);
127   ChebFit();
128   //
129 }
130 #endif
131
132 //__________________________________________________________________________________________
133 #ifdef _INC_CREATION_ALICHEB3D_
134 AliCheb3D::AliCheb3D(void (*ptr)(float*,float*), int DimOut, Float_t  *bmin,Float_t  *bmax, Int_t *npoints, Float_t prec) : 
135   fDimOut(0), 
136   fPrec(TMath::Max(1.E-12f,prec)), 
137   fChebCalc(1), 
138   fMaxCoefs(0), 
139   fResTmp(0), 
140   fGrid(0), 
141   fUsrFunName(""),
142   fUsrMacro(0)
143 {
144   // Construct the parameterization for the function
145   // ptr     : pointer on the function: void fun(Float_t * inp,Float_t * out)
146   // DimOut  : dimension of the vector computed by the user function
147   // bmin    : array of 3 elements with the lower boundaries of the region where the function is defined
148   // bmax    : array of 3 elements with the upper boundaries of the region where the function is defined
149   // npoints : array of 3 elements with the number of points to compute in each of 3 dimension
150   // prec    : max allowed absolute difference between the user function and computed parameterization on the requested grid
151   //
152   if (DimOut<1) {Error("AliCheb3D","Requested output dimension is %d\nStop\n",fDimOut); exit(1);}
153   SetDimOut(DimOut);
154   PrepareBoundaries(bmin,bmax);
155   DefineGrid(npoints);
156   SetUsrFunction(ptr);
157   ChebFit();
158   //
159 }
160 #endif
161
162 //__________________________________________________________________________________________
163 #ifdef _INC_CREATION_ALICHEB3D_
164 AliCheb3D::AliCheb3D(void (*ptr)(float*,float*), int DimOut, Float_t  *bmin,Float_t  *bmax, Int_t *npX,Int_t *npY,Int_t *npZ, Float_t prec) : 
165   fDimOut(0), 
166   fPrec(TMath::Max(1.E-12f,prec)), 
167   fChebCalc(1), 
168   fMaxCoefs(0), 
169   fResTmp(0), 
170   fGrid(0), 
171   fUsrFunName(""),
172   fUsrMacro(0)
173 {
174   // Construct very economic  parameterization for the function
175   // ptr     : pointer on the function: void fun(Float_t * inp,Float_t * out)
176   // DimOut  : dimension of the vector computed by the user function
177   // bmin    : array of 3 elements with the lower boundaries of the region where the function is defined
178   // bmax    : array of 3 elements with the upper boundaries of the region where the function is defined
179   // npX     : array of 3 elements with the number of points to compute in each dimension for 1st component 
180   // npY     : array of 3 elements with the number of points to compute in each dimension for 2nd component 
181   // npZ     : array of 3 elements with the number of points to compute in each dimension for 3d  component 
182   // prec    : max allowed absolute difference between the user function and computed parameterization on the requested grid
183   //
184   if (DimOut<1) {Error("AliCheb3D","Requested output dimension is %d\nStop\n",fDimOut); exit(1);}
185   SetDimOut(DimOut);
186   PrepareBoundaries(bmin,bmax);
187   SetUsrFunction(ptr);
188   //
189   DefineGrid(npX);
190   ChebFit(0);
191   DefineGrid(npY);
192   ChebFit(1);
193   DefineGrid(npZ);
194   ChebFit(2);
195   //
196 }
197 #endif
198
199
200 //__________________________________________________________________________________________
201 #ifdef _INC_CREATION_ALICHEB3D_
202 AliCheb3D::AliCheb3D(void (*ptr)(float*,float*), int DimOut, Float_t  *bmin,Float_t  *bmax, Float_t prec, Bool_t run) : 
203   fDimOut(0), 
204   fPrec(TMath::Max(1.E-12f,prec)), 
205   fChebCalc(1), 
206   fMaxCoefs(0), 
207   fResTmp(0), 
208   fGrid(0), 
209   fUsrFunName(""),
210   fUsrMacro(0)
211 {
212   // Construct very economic  parameterization for the function with automatic calculation of the root's grid
213   // ptr     : pointer on the function: void fun(Float_t * inp,Float_t * out)
214   // DimOut  : dimension of the vector computed by the user function
215   // bmin    : array of 3 elements with the lower boundaries of the region where the function is defined
216   // bmax    : array of 3 elements with the upper boundaries of the region where the function is defined
217   // prec    : max allowed absolute difference between the user function and computed parameterization on the requested grid
218   //
219   if (DimOut!=3) {Error("AliCheb3D","This constructor works only for 3D fits, %dD fit was requested\n",fDimOut); exit(1);}
220   SetDimOut(DimOut);
221   PrepareBoundaries(bmin,bmax);
222   SetUsrFunction(ptr);
223   //
224   if (run) {
225     int gridNC[3][3];
226     EstimateNPoints(prec,gridNC);
227     DefineGrid(gridNC[0]);
228     ChebFit(0);
229     DefineGrid(gridNC[1]);
230     ChebFit(1);
231     DefineGrid(gridNC[2]);
232     ChebFit(2);
233   }
234   //
235 }
236 #endif
237
238
239 //__________________________________________________________________________________________
240 AliCheb3D& AliCheb3D::operator=(const AliCheb3D& rhs)
241 {
242   // assignment operator
243   //
244   if (this != &rhs) {
245     Clear();
246     fDimOut   = rhs.fDimOut;
247     fPrec     = rhs.fPrec;
248     fMaxCoefs = rhs.fMaxCoefs;
249     fUsrFunName = rhs.fUsrFunName;
250     fUsrMacro   = 0;
251     for (int i=3;i--;) {
252       fBMin[i]    = rhs.fBMin[i];
253       fBMax[i]    = rhs.fBMax[i];
254       fBScale[i]  = rhs.fBScale[i];
255       fBOffset[i] = rhs.fBOffset[i];
256       fNPoints[i] = rhs.fNPoints[i];
257     } 
258     for (int i=0;i<fDimOut;i++) {
259       AliCheb3DCalc* cbc = rhs.GetChebCalc(i);
260       if (cbc) fChebCalc.AddAtAndExpand(new AliCheb3DCalc(*cbc),i);
261     }    
262   }
263   return *this;
264   //
265 }
266
267 //__________________________________________________________________________________________
268 void AliCheb3D::Clear(const Option_t*)
269 {
270   // clear all dynamic structures
271   //
272   if (fResTmp)        { delete[] fResTmp; fResTmp = 0; }
273   if (fGrid)          { delete[] fGrid;   fGrid   = 0; }
274   if (fUsrMacro)      { delete fUsrMacro; fUsrMacro = 0;}
275   fChebCalc.Delete();
276   //
277 }
278
279 //__________________________________________________________________________________________
280 void AliCheb3D::Print(const Option_t* opt) const
281 {
282   // print info
283   //
284   printf("%s: Chebyshev parameterization for 3D->%dD function. Precision: %e\n",GetName(),fDimOut,fPrec);
285   printf("Region of validity: [%+.5e:%+.5e] [%+.5e:%+.5e] [%+.5e:%+.5e]\n",fBMin[0],fBMax[0],fBMin[1],fBMax[1],fBMin[2],fBMax[2]);
286   TString opts = opt; opts.ToLower();
287   if (opts.Contains("l")) for (int i=0;i<fDimOut;i++) {printf("Output dimension %d:\n",i+1); GetChebCalc(i)->Print();}
288   //
289 }
290
291 //__________________________________________________________________________________________
292 void AliCheb3D::PrepareBoundaries(const Float_t  *bmin, const Float_t  *bmax)
293 {
294   // Set and check boundaries defined by user, prepare coefficients for their conversion to [-1:1] interval
295   //
296   for (int i=3;i--;) {
297     fBMin[i]   = bmin[i];
298     fBMax[i]   = bmax[i];
299     fBScale[i] = bmax[i]-bmin[i];
300     if (fBScale[i]<=0) { 
301       Error("PrepareBoundaries","Boundaries for %d-th dimension are not increasing: %+.4e %+.4e\nStop\n",i,fBMin[i],fBMax[i]);
302       exit(1);
303     }
304     fBOffset[i] = bmin[i] + fBScale[i]/2.0;
305     fBScale[i] = 2./fBScale[i];
306   }
307   //
308 }
309
310
311 //__________________________________________________________________________________________
312 #ifdef _INC_CREATION_ALICHEB3D_
313
314 // Pointer on user function (faster altrnative to TMethodCall)
315 void (*gUsrFunAliCheb3D) (float* ,float* );
316
317 void AliCheb3D::EvalUsrFunction() 
318 {
319   // call user supplied function
320   if   (gUsrFunAliCheb3D) gUsrFunAliCheb3D(fArgsTmp,fResTmp);
321   else fUsrMacro->Execute(); 
322 }
323
324 void AliCheb3D::SetUsrFunction(const char* name)
325 {
326   // load user macro with function definition and compile it
327   gUsrFunAliCheb3D = 0; 
328   fUsrFunName = name;
329   gSystem->ExpandPathName(fUsrFunName);
330   if (fUsrMacro) delete fUsrMacro;
331   TString tmpst = fUsrFunName;
332   tmpst += "+"; // prepare filename to compile
333   if (gROOT->LoadMacro(tmpst.Data())) {Error("SetUsrFunction","Failed to load user function from %s\nStop\n",name); exit(1);}
334   fUsrMacro = new TMethodCall();        
335   tmpst = tmpst.Data() + tmpst.Last('/')+1; //Strip away any path preceding the macro file name
336   int dot = tmpst.Last('.');
337   if (dot>0) tmpst.Resize(dot);
338   fUsrMacro->InitWithPrototype(tmpst.Data(),"Float_t *,Float_t *");
339   long args[2];
340   args[0] = (long)fArgsTmp;
341   args[1] = (long)fResTmp;
342   fUsrMacro->SetParamPtrs(args); 
343   //
344 }
345 #endif
346
347 //__________________________________________________________________________________________
348 #ifdef _INC_CREATION_ALICHEB3D_
349 void AliCheb3D::SetUsrFunction(void (*ptr)(float*,float*))
350 {
351   // assign user training function
352   //
353   if (fUsrMacro) delete fUsrMacro;
354   fUsrMacro = 0;
355   fUsrFunName = "";
356   gUsrFunAliCheb3D = ptr;
357 }
358 #endif
359
360 //__________________________________________________________________________________________
361 #ifdef _INC_CREATION_ALICHEB3D_
362 void AliCheb3D::EvalUsrFunction(const Float_t  *x, Float_t  *res) 
363 {
364   // evaluate user function value
365   //
366   for (int i=3;i--;) fArgsTmp[i] = x[i];
367   if   (gUsrFunAliCheb3D) gUsrFunAliCheb3D(fArgsTmp,fResTmp);
368   else fUsrMacro->Execute(); 
369   for (int i=fDimOut;i--;) res[i] = fResTmp[i];
370 }
371 #endif
372
373 //__________________________________________________________________________________________
374 #ifdef _INC_CREATION_ALICHEB3D_
375 Int_t AliCheb3D::CalcChebCoefs(const Float_t  *funval,int np, Float_t  *outCoefs, Float_t  prec)
376 {
377   // Calculate Chebyshev coeffs using precomputed function values at np roots.
378   // If prec>0, estimate the highest coeff number providing the needed precision
379   //
380   double sm;                 // do summations in double to minimize the roundoff error
381   for (int ic=0;ic<np;ic++) { // compute coeffs
382     sm = 0;          
383     for (int ir=0;ir<np;ir++) {
384       float  rt = TMath::Cos( ic*(ir+0.5)*TMath::Pi()/np);
385       sm += funval[ir]*rt;
386     }
387     outCoefs[ic] = Float_t( sm * ((ic==0) ? 1./np : 2./np) );
388   }
389   //
390   if (prec<=0) return np;
391   //
392   sm = 0;
393   int cfMax = 0;
394   for (cfMax=np;cfMax--;) {
395     sm += TMath::Abs(outCoefs[cfMax]);
396     if (sm>=prec) break;
397   }
398   if (++cfMax==0) cfMax=1;
399   return cfMax;
400   //
401 }
402 #endif
403
404 //__________________________________________________________________________________________
405 #ifdef _INC_CREATION_ALICHEB3D_
406 void AliCheb3D::DefineGrid(Int_t* npoints)
407 {
408   // prepare the grid of Chebyshev roots in each dimension
409   const int kMinPoints = 1;
410   int ntot = 0;
411   fMaxCoefs = 1;
412   for (int id=3;id--;) { 
413     fNPoints[id] = npoints[id];
414     if (fNPoints[id]<kMinPoints) {
415       Error("DefineGrid","at %d-th dimension %d point is requested, at least %d is needed\nStop\n",id,fNPoints[id],kMinPoints);
416       exit(1);
417     }
418     ntot += fNPoints[id];
419     fMaxCoefs *= fNPoints[id];
420   }
421   printf("Computing Chebyshev nodes on [%2d/%2d/%2d] grid\n",npoints[0],npoints[1],npoints[2]);
422   if (fGrid) delete[] fGrid;
423   fGrid = new Float_t [ntot];
424   //
425   int curp = 0;
426   for (int id=3;id--;) { 
427     int np = fNPoints[id];
428     fGridOffs[id] = curp;
429     for (int ip=0;ip<np;ip++) {
430       Float_t x = TMath::Cos( TMath::Pi()*(ip+0.5)/np );
431       fGrid[curp++] = MapToExternal(x,id);
432     }
433   }
434   //
435 }
436 #endif
437
438 //__________________________________________________________________________________________
439 #ifdef _INC_CREATION_ALICHEB3D_
440 Int_t AliCheb3D::ChebFit()
441 {
442   // prepare parameterization for all output dimensions
443   int ir=0; 
444   for (int i=fDimOut;i--;) ir+=ChebFit(i); 
445   return ir;
446 }
447 #endif
448
449 //__________________________________________________________________________________________
450 #ifdef _INC_CREATION_ALICHEB3D_
451 Int_t AliCheb3D::ChebFit(int dmOut)
452 {
453   // prepare paramaterization of 3D function for dmOut-th dimension 
454   int maxDim = 0;
455   for (int i=0;i<3;i++) if (maxDim<fNPoints[i]) maxDim = fNPoints[i];
456   Float_t  *fvals      = new Float_t [ fNPoints[0] ];
457   Float_t  *tmpCoef3D  = new Float_t [ fNPoints[0]*fNPoints[1]*fNPoints[2] ]; 
458   Float_t  *tmpCoef2D  = new Float_t [ fNPoints[0]*fNPoints[1] ]; 
459   Float_t  *tmpCoef1D  = new Float_t [ maxDim ];
460   //
461   Float_t rTiny = 0.1*fPrec/Float_t(maxDim); // neglect coefficient below this threshold
462   //
463   // 1D Cheb.fit for 0-th dimension at current steps of remaining dimensions
464   int ncmax = 0;
465   //
466   printf("Dim%d : 00.00%% Done",dmOut);fflush(stdout);
467   AliCheb3DCalc* cheb =  GetChebCalc(dmOut);
468   //
469   float ncals2count = fNPoints[2]*fNPoints[1]*fNPoints[0];
470   float ncals = 0;
471   float frac = 0;
472   float fracStep = 0.001;
473   //
474   for (int id2=fNPoints[2];id2--;) {
475     fArgsTmp[2] = fGrid[ fGridOffs[2]+id2 ];
476     //
477     for (int id1=fNPoints[1];id1--;) {
478       fArgsTmp[1] = fGrid[ fGridOffs[1]+id1 ];
479       //
480       for (int id0=fNPoints[0];id0--;) {
481         fArgsTmp[0] = fGrid[ fGridOffs[0]+id0 ];
482         EvalUsrFunction();     // compute function values at Chebyshev roots of 0-th dimension
483         fvals[id0] =  fResTmp[dmOut];
484         float fr = (++ncals)/ncals2count;
485         if (fr-frac>=fracStep) {
486           frac = fr;
487           printf("\b\b\b\b\b\b\b\b\b\b\b");
488           printf("%05.2f%% Done",fr*100);
489           fflush(stdout);
490         }
491         //
492       }
493       int nc = CalcChebCoefs(fvals,fNPoints[0], tmpCoef1D, fPrec);
494       for (int id0=fNPoints[0];id0--;) tmpCoef2D[id1 + id0*fNPoints[1]] = tmpCoef1D[id0];
495       if (ncmax<nc) ncmax = nc;              // max coefs to be kept in dim0 to guarantee needed precision
496     }
497     //
498     // once each 1d slice of given 2d slice is parametrized, parametrize the Cheb.coeffs
499     for (int id0=fNPoints[0];id0--;) {
500       CalcChebCoefs( tmpCoef2D+id0*fNPoints[1], fNPoints[1], tmpCoef1D, -1);
501       for (int id1=fNPoints[1];id1--;) tmpCoef3D[id2 + fNPoints[2]*(id1+id0*fNPoints[1])] = tmpCoef1D[id1];
502     }
503   }
504   //
505   // now fit the last dimensions Cheb.coefs
506   for (int id0=fNPoints[0];id0--;) {
507     for (int id1=fNPoints[1];id1--;) {
508       CalcChebCoefs( tmpCoef3D+ fNPoints[2]*(id1+id0*fNPoints[1]), fNPoints[2], tmpCoef1D, -1);
509       for (int id2=fNPoints[2];id2--;) tmpCoef3D[id2+ fNPoints[2]*(id1+id0*fNPoints[1])] = tmpCoef1D[id2]; // store on place
510     }
511   }
512   //
513   // now find 2D surface which separates significant coefficients of 3D matrix from nonsignificant ones (up to fPrec)
514   UShort_t *tmpCoefSurf = new UShort_t[ fNPoints[0]*fNPoints[1] ];
515   for (int id0=fNPoints[0];id0--;) for (int id1=fNPoints[1];id1--;) tmpCoefSurf[id1+id0*fNPoints[1]]=0;  
516   Double_t resid = 0;
517   for (int id0=fNPoints[0];id0--;) {
518     for (int id1=fNPoints[1];id1--;) {
519       for (int id2=fNPoints[2];id2--;) {
520         int id = id2 + fNPoints[2]*(id1+id0*fNPoints[1]);
521         Float_t  cfa = TMath::Abs(tmpCoef3D[id]);
522         if (cfa < rTiny) {tmpCoef3D[id] = 0; continue;} // neglect coefs below the threshold
523         resid += cfa;
524         if (resid<fPrec) continue; // this coeff is negligible
525         // otherwise go back 1 step
526         resid -= cfa;
527         tmpCoefSurf[id1+id0*fNPoints[1]] = id2+1; // how many coefs to keep
528         break;
529       }
530     }
531   }
532   /*
533   printf("\n\nCoeffs\n");  
534   int cnt = 0;
535   for (int id0=0;id0<fNPoints[0];id0++) {
536     for (int id1=0;id1<fNPoints[1];id1++) {
537       for (int id2=0;id2<fNPoints[2];id2++) {
538         printf("%2d%2d%2d %+.4e |",id0,id1,id2,tmpCoef3D[cnt++]);
539       }
540       printf("\n");
541     }
542     printf("\n");
543   }
544   */
545   // see if there are rows to reject, find max.significant column at each row
546   int nRows = fNPoints[0];
547   UShort_t *tmpCols = new UShort_t[nRows]; 
548   for (int id0=fNPoints[0];id0--;) {
549     int id1 = fNPoints[1];
550     while (id1>0 && tmpCoefSurf[(id1-1)+id0*fNPoints[1]]==0) id1--;
551     tmpCols[id0] = id1;
552   }
553   // find max significant row
554   for (int id0=nRows;id0--;) {if (tmpCols[id0]>0) break; nRows--;}
555   // find max significant column and fill the permanent storage for the max sigificant column of each row
556   cheb->InitRows(nRows);                  // create needed arrays;
557   UShort_t *nColsAtRow = cheb->GetNColsAtRow();
558   UShort_t *colAtRowBg = cheb->GetColAtRowBg();
559   int nCols = 0;
560   int NElemBound2D = 0;
561   for (int id0=0;id0<nRows;id0++) {
562     nColsAtRow[id0] = tmpCols[id0];     // number of columns to store for this row
563     colAtRowBg[id0] = NElemBound2D;     // begining of this row in 2D boundary surface
564     NElemBound2D += tmpCols[id0];
565     if (nCols<nColsAtRow[id0]) nCols = nColsAtRow[id0];
566   }
567   cheb->InitCols(nCols);
568   delete[] tmpCols;
569   //  
570   // create the 2D matrix defining the boundary of significance for 3D coeffs.matrix 
571   // and count the number of siginifacnt coefficients
572   //
573   cheb->InitElemBound2D(NElemBound2D);
574   UShort_t *coefBound2D0 = cheb->GetCoefBound2D0();
575   UShort_t *coefBound2D1 = cheb->GetCoefBound2D1();
576   fMaxCoefs = 0; // redefine number of coeffs
577   for (int id0=0;id0<nRows;id0++) {
578     int nCLoc = nColsAtRow[id0];
579     int col0  = colAtRowBg[id0];
580     for (int id1=0;id1<nCLoc;id1++) {
581       coefBound2D0[col0 + id1] = tmpCoefSurf[id1+id0*fNPoints[1]];  // number of coefs to store for 3-d dimension
582       coefBound2D1[col0 + id1] = fMaxCoefs;
583       fMaxCoefs += coefBound2D0[col0 + id1];
584     }
585   }
586   //
587   // create final compressed 3D matrix for significant coeffs
588   cheb->InitCoefs(fMaxCoefs);
589   Float_t  *coefs = cheb->GetCoefs();
590   int count = 0;
591   for (int id0=0;id0<nRows;id0++) {
592     int ncLoc = nColsAtRow[id0];
593     int col0  = colAtRowBg[id0];
594     for (int id1=0;id1<ncLoc;id1++) {
595       int ncf2 = coefBound2D0[col0 + id1];
596       for (int id2=0;id2<ncf2;id2++) {
597         coefs[count++] = tmpCoef3D[id2 + fNPoints[2]*(id1+id0*fNPoints[1])];
598       }
599     }
600   }
601   /*
602   printf("\n\nNewSurf\n");
603   for (int id0=0;id0<fNPoints[0];id0++) {
604     for (int id1=0;id1<fNPoints[1];id1++) {
605       printf("(%2d %2d) %2d |",id0,id1,tmpCoefSurf[id1+id0*fNPoints[1]]);  
606     }
607     printf("\n");
608   }
609   */
610   //
611   delete[] tmpCoefSurf;
612   delete[] tmpCoef1D;
613   delete[] tmpCoef2D;
614   delete[] tmpCoef3D;
615   delete[] fvals;
616   //
617   printf("\b\b\b\b\b\b\b\b\b\b\b\b");
618   printf("100.00%% Done\n");
619   return 1;
620 }
621 #endif
622
623 //_______________________________________________
624 #ifdef _INC_CREATION_ALICHEB3D_
625 void AliCheb3D::SaveData(const char* outfile,Bool_t append) const
626 {
627   // writes coefficients data to output text file, optionallt appending on the end of existing file
628   TString strf = outfile;
629   gSystem->ExpandPathName(strf);
630   FILE* stream = fopen(strf,append ? "a":"w");
631   SaveData(stream);
632   fclose(stream);
633   //
634 }
635 #endif
636
637 //_______________________________________________
638 #ifdef _INC_CREATION_ALICHEB3D_
639 void AliCheb3D::SaveData(FILE* stream) const
640 {
641   // writes coefficients data to existing output stream
642   //
643   fprintf(stream,"\n# These are automatically generated data for the Chebyshev interpolation of 3D->%dD function\n",fDimOut); 
644   fprintf(stream,"#\nSTART %s\n",GetName());
645   fprintf(stream,"# Dimensionality of the output\n%d\n",fDimOut);
646   fprintf(stream,"# Interpolation abs. precision\n%+.8e\n",fPrec);
647   //
648   fprintf(stream,"# Lower boundaries of interpolation region\n");
649   for (int i=0;i<3;i++) fprintf(stream,"%+.8e\n",fBMin[i]);
650   fprintf(stream,"# Upper boundaries of interpolation region\n");
651   for (int i=0;i<3;i++) fprintf(stream,"%+.8e\n",fBMax[i]);
652   fprintf(stream,"# Parameterization for each output dimension follows:\n");
653   //
654   for (int i=0;i<fDimOut;i++) GetChebCalc(i)->SaveData(stream);
655   fprintf(stream,"#\nEND %s\n#\n",GetName());
656   //
657 }
658 #endif
659
660 //_______________________________________________
661 void AliCheb3D::LoadData(const char* inpFile)
662 {
663   // load coefficients data from txt file
664   //
665   TString strf = inpFile;
666   gSystem->ExpandPathName(strf);
667   FILE* stream = fopen(strf.Data(),"r");
668   LoadData(stream);
669   fclose(stream);
670   //
671 }
672
673 //_______________________________________________
674 void AliCheb3D::LoadData(FILE* stream)
675 {
676   // load coefficients data from stream
677   //
678   if (!stream) {Error("LoadData","No stream provided.\nStop"); exit(1);}
679   TString buffs;
680   Clear();
681   AliCheb3DCalc::ReadLine(buffs,stream);
682   if (!buffs.BeginsWith("START")) {Error("LoadData","Expected: \"START <fit_name>\", found \"%s\"\nStop\n",buffs.Data());exit(1);}
683   SetName(buffs.Data()+buffs.First(' ')+1);
684   //
685   AliCheb3DCalc::ReadLine(buffs,stream); // N output dimensions
686   fDimOut = buffs.Atoi(); 
687   if (fDimOut<1) {Error("LoadData","Expected: '<number_of_output_dimensions>', found \"%s\"\nStop\n",buffs.Data());exit(1);}
688   //
689   SetDimOut(fDimOut);
690   //
691   AliCheb3DCalc::ReadLine(buffs,stream); // Interpolation abs. precision
692   fPrec = buffs.Atof();
693   if (fPrec<=0) {Error("LoadData","Expected: '<abs.precision>', found \"%s\"\nStop\n",buffs.Data());exit(1);}
694   //
695   for (int i=0;i<3;i++) { // Lower boundaries of interpolation region
696     AliCheb3DCalc::ReadLine(buffs,stream);
697     fBMin[i] = buffs.Atof(); 
698   }
699   for (int i=0;i<3;i++) { // Upper boundaries of interpolation region
700     AliCheb3DCalc::ReadLine(buffs,stream);
701     fBMax[i] = buffs.Atof(); 
702   }
703   PrepareBoundaries(fBMin,fBMax);
704   //
705   // data for each output dimension
706   for (int i=0;i<fDimOut;i++) GetChebCalc(i)->LoadData(stream);
707   //
708   // check end_of_data record
709   AliCheb3DCalc::ReadLine(buffs,stream);
710   if (!buffs.BeginsWith("END") || !buffs.Contains(GetName())) {
711     Error("LoadData","Expected \"END %s\", found \"%s\".\nStop\n",GetName(),buffs.Data());
712     exit(1);
713   }
714   //
715 }
716
717 //_______________________________________________
718 void AliCheb3D::SetDimOut(const int d)
719 {
720   // init output dimensions
721   fDimOut = d;
722   if (fResTmp) delete fResTmp;
723   fResTmp = new Float_t[fDimOut];
724   fChebCalc.Delete();
725   for (int i=0;i<d;i++) fChebCalc.AddAtAndExpand(new AliCheb3DCalc(),i);
726 }
727
728 //_______________________________________________
729 void AliCheb3D::ShiftBound(int id,float dif)
730 {
731   // modify the bounds of the grid
732   //
733   if (id<0||id>2) {printf("Maximum 3 dimensions are supported\n"); return;}
734   fBMin[id] += dif;
735   fBMax[id] += dif;
736   fBOffset[id] += dif;
737 }
738
739 //_______________________________________________
740 #ifdef _INC_CREATION_ALICHEB3D_
741 TH1* AliCheb3D::TestRMS(int idim,int npoints,TH1* histo)
742 {
743   // fills the difference between the original function and parameterization (for idim-th component of the output)
744   // to supplied histogram. Calculations are done in npoints random points. 
745   // If the hostgram was not supplied, it will be created. It is up to the user to delete it! 
746   if (!fUsrMacro) {
747     printf("No user function is set\n");
748     return 0;
749   }
750   if (!histo) histo = new TH1D(GetName(),"Control: Function - Parametrization",100,-2*fPrec,2*fPrec);
751   for (int ip=npoints;ip--;) {
752     gRandom->RndmArray(3,(Float_t *)fArgsTmp);
753     for (int i=3;i--;) fArgsTmp[i] = fBMin[i] + fArgsTmp[i]*(fBMax[i]-fBMin[i]);
754     EvalUsrFunction();
755     Float_t valFun = fResTmp[idim];
756     Eval(fArgsTmp,fResTmp);
757     Float_t valPar = fResTmp[idim];
758     histo->Fill(valFun - valPar);
759   }
760   return histo;
761   //
762 }
763 #endif
764
765 //_______________________________________________
766 #ifdef _INC_CREATION_ALICHEB3D_
767
768 void AliCheb3D::EstimateNPoints(float Prec, int gridBC[3][3],Int_t npd1,Int_t npd2,Int_t npd3)
769 {
770   // Estimate number of points to generate a training data
771   //
772   const int kScp = 9;
773   const float kScl[9] = {0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9};
774   //
775   const float sclDim[2] = {0.001,0.999};
776   const int   compDim[3][2] = { {1,2}, {2,0}, {0,1} };
777   static float xyz[3];
778   Int_t npdTst[3] = {npd1,npd2,npd3};
779   //
780
781   for (int i=3;i--;)for (int j=3;j--;) gridBC[i][j] = -1;
782   //
783   for (int idim=0;idim<3;idim++) {
784     float dimMN = fBMin[idim] + sclDim[0]*(fBMax[idim]-fBMin[idim]);
785     float dimMX = fBMin[idim] + sclDim[1]*(fBMax[idim]-fBMin[idim]);
786     //
787     int id1 = compDim[idim][0]; // 1st fixed dim
788     int id2 = compDim[idim][1]; // 2nd fixed dim
789     for (int i1=0;i1<kScp;i1++) {
790       xyz[ id1 ] = fBMin[id1] + kScl[i1]*( fBMax[id1]-fBMin[id1] );
791       for (int i2=0;i2<kScp;i2++) {
792         xyz[ id2 ] = fBMin[id2] + kScl[i2]*( fBMax[id2]-fBMin[id2] );
793         int* npt = GetNCNeeded(xyz,idim, dimMN,dimMX, Prec, npdTst[idim]); // npoints for Bx,By,Bz
794         for (int ib=0;ib<3;ib++) if (npt[ib]>gridBC[ib][idim]) gridBC[ib][idim] = npt[ib];
795       }
796     }
797   }
798 }
799
800 /*
801 void AliCheb3D::EstimateNPoints(float Prec, int gridBC[3][3])
802 {
803   // Estimate number of points to generate a training data
804   //
805   const float sclA[9] = {0.1, 0.5, 0.9, 0.1, 0.5, 0.9, 0.1, 0.5, 0.9} ;
806   const float sclB[9] = {0.1, 0.1, 0.1, 0.5, 0.5, 0.5, 0.9, 0.9, 0.9} ;
807   const float sclDim[2] = {0.01,0.99};
808   const int   compDim[3][2] = { {1,2}, {2,0}, {0,1} };
809   static float xyz[3];
810   //
811   for (int i=3;i--;)for (int j=3;j--;) gridBC[i][j] = -1;
812   //
813   for (int idim=0;idim<3;idim++) {
814     float dimMN = fBMin[idim] + sclDim[0]*(fBMax[idim]-fBMin[idim]);
815     float dimMX = fBMin[idim] + sclDim[1]*(fBMax[idim]-fBMin[idim]);
816     //
817     for (int it=0;it<9;it++) { // test in 9 points
818       int id1 = compDim[idim][0]; // 1st fixed dim
819       int id2 = compDim[idim][1]; // 2nd fixed dim
820       xyz[ id1 ] = fBMin[id1] + sclA[it]*( fBMax[id1]-fBMin[id1] );
821       xyz[ id2 ] = fBMin[id2] + sclB[it]*( fBMax[id2]-fBMin[id2] );
822       //
823       int* npt = GetNCNeeded(xyz,idim, dimMN,dimMX, Prec); // npoints for Bx,By,Bz
824       for (int ib=0;ib<3;ib++) if (npt[ib]>gridBC[ib][idim]) gridBC[ib][idim] = npt[ib];//+2;
825       //
826     }
827   }
828 }
829
830
831 int* AliCheb3D::GetNCNeeded(float xyz[3],int DimVar, float mn,float mx, float prec)
832 {
833   // estimate needed number of chebyshev coefs for given function description in DimVar dimension
834   // The values for two other dimensions must be set beforehand
835   //
836   static int curNC[3];
837   static int retNC[3];
838   const int kMaxPoint = 400;
839   float* gridVal = new float[3*kMaxPoint];
840   float* coefs   = new float[3*kMaxPoint];
841   //
842   float scale = mx-mn;
843   float offs  = mn + scale/2.0;
844   scale = 2./scale;
845   // 
846   int curNP;
847   int maxNC=-1;
848   int maxNCPrev=-1;
849   for (int i=0;i<3;i++) retNC[i] = -1;
850   for (int i=0;i<3;i++) fArgsTmp[i] = xyz[i];
851   //
852   for (curNP=3; curNP<kMaxPoint; curNP+=3) { 
853     maxNCPrev = maxNC;
854     //
855     for (int i=0;i<curNP;i++) { // get function values on Cheb. nodes
856       float x = TMath::Cos( TMath::Pi()*(i+0.5)/curNP );
857       fArgsTmp[DimVar] =  x/scale+offs; // map to requested interval
858       EvalUsrFunction();
859       for (int ib=3;ib--;) gridVal[ib*kMaxPoint + i] = fResTmp[ib];
860     }
861     //
862     for (int ib=0;ib<3;ib++) {
863       curNC[ib] = AliCheb3D::CalcChebCoefs(&gridVal[ib*kMaxPoint], curNP, &coefs[ib*kMaxPoint],prec);
864       if (maxNC < curNC[ib]) maxNC = curNC[ib];
865       if (retNC[ib] < curNC[ib]) retNC[ib] = curNC[ib];
866     }
867     if ( (curNP-maxNC)>3 &&  (maxNC-maxNCPrev)<1 ) break;
868     maxNCPrev = maxNC;
869     //
870   }
871   delete[] gridVal;
872   delete[] coefs;
873   return retNC;
874   //
875 }
876 */
877
878
879 int* AliCheb3D::GetNCNeeded(float xyz[3],int DimVar, float mn,float mx, float prec, Int_t npCheck)
880 {
881   // estimate needed number of chebyshev coefs for given function description in DimVar dimension
882   // The values for two other dimensions must be set beforehand
883   //
884   static int retNC[3];
885   static int npChLast = 0;
886   static float *gridVal=0,*coefs=0;
887   if (npCheck<3) npCheck = 3;
888   if (npChLast<npCheck) {
889     if (gridVal) delete[] gridVal;
890     if (coefs)   delete[] coefs;
891     gridVal = new float[3*npCheck];
892     coefs   = new float[3*npCheck];
893     npChLast = npCheck;
894   }
895   //
896   float scale = mx-mn;
897   float offs  = mn + scale/2.0;
898   scale = 2./scale;
899   //
900   for (int i=0;i<3;i++) fArgsTmp[i] = xyz[i];
901   for (int i=0;i<npCheck;i++) {
902     fArgsTmp[DimVar] =  TMath::Cos( TMath::Pi()*(i+0.5)/npCheck)/scale+offs; // map to requested interval
903     EvalUsrFunction();
904     for (int ib=3;ib--;) gridVal[ib*npCheck + i] = fResTmp[ib];
905   } 
906   //
907   for (int ib=0;ib<3;ib++) retNC[ib] = AliCheb3D::CalcChebCoefs(&gridVal[ib*npCheck], npCheck, &coefs[ib*npCheck],prec);
908   return retNC;
909   //
910 }
911
912
913 #endif