]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliCheb3D.cxx
41246b2efd90580259b250508c4550b396d6d8ea
[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 /* $Id$ */
17
18 // Author: ruben.shahoyan@cern.ch   09/09/2006
19 //
20 ////////////////////////////////////////////////////////////////////////////////
21 //                                                                            //
22 // AliCheb3D produces the interpolation of the user 3D->NDimOut arbitrary     //
23 // function supplied in "void (*fcn)(float* inp,float* out)" format           //
24 // either in a separate macro file or as a function pointer.                  //
25 // Only coefficients needed to guarantee the requested precision are kept.    //
26 //                                                                            //
27 // The user-callable methods are:                                             //
28 // To create the interpolation use:                                           //
29 // AliCheb3D(const char* funName,  // name of the file with user function     //
30 //          or                                                                //
31 // AliCheb3D(void (*ptr)(float*,float*),// pointer on the  user function      //
32 //        Int_t     DimOut,     // dimensionality of the function's output    // 
33 //        Float_t  *bmin,       // lower 3D bounds of interpolation domain    // 
34 //        Float_t  *bmax,       // upper 3D bounds of interpolation domain    // 
35 //        Int_t    *npoints,    // number of points in each of 3 input        //
36 //                              // dimension, defining the interpolation grid //
37 //        Float_t   prec=1E-6); // requested max.absolute difference between  //
38 //                              // the interpolation and any point on grid    //
39 //                                                                            //
40 // To test obtained parameterization use the method                           //
41 // TH1* TestRMS(int idim,int npoints = 1000,TH1* histo=0);                    // 
42 // it will compare the user output of the user function and interpolation     //
43 // for idim-th output dimension and fill the difference in the supplied       //
44 // histogram. If no histogram is supplied, it will be created.                //
45 //                                                                            //
46 // To save the interpolation data:                                            //
47 // SaveData(const char* filename, Bool_t append )                             //
48 // write text file with data. If append is kTRUE and the output file already  //
49 // exists, data will be added in the end of the file.                         //
50 // Alternatively, SaveData(FILE* stream) will write the data to               //
51 // already existing stream.                                                   //
52 //                                                                            //
53 // To read back already stored interpolation use either the constructor       // 
54 // AliCheb3D(const char* inpFile);                                            //
55 // or the default constructor AliCheb3D() followed by                         //
56 // AliCheb3D::LoadData(const char* inpFile);                                  //
57 //                                                                            //
58 // To compute the interpolation use Eval(float* par,float *res) method, with  //
59 // par being 3D vector of arguments (inside the validity region) and res is   //
60 // the array of DimOut elements for the output.                               //
61 //                                                                            //
62 // If only one component (say, idim-th) of the output is needed, use faster   //
63 // Float_t Eval(Float_t *par,int idim) method.                                //
64 //                                                                            //
65 // void Print(option="") will print the name, the ranges of validity and      //
66 // the absolute precision of the parameterization. Option "l" will also print //
67 // the information about the number of coefficients for each output           //
68 // dimension.                                                                 //
69 //                                                                            //
70 // NOTE: during the evaluation no check is done for parameter vector being    //
71 // outside the interpolation region. If there is such a risk, use             //
72 // Bool_t IsInside(float *par) method. Chebyshev parameterization is not      //
73 // good for extrapolation!                                                    //
74 //                                                                            //
75 // For the properties of Chebyshev parameterization see:                      //
76 // H.Wind, CERN EP Internal Report, 81-12/Rev.                                //
77 //                                                                            //
78 ////////////////////////////////////////////////////////////////////////////////
79
80 #include <TString.h>
81 #include <TSystem.h>
82 #include <TRandom.h>
83 #include <TROOT.h>
84 #include "AliCheb3D.h"
85 #include "AliLog.h"
86
87
88
89 ClassImp(AliCheb3DCalc)
90
91
92 AliCheb3DCalc::AliCheb3DCalc():
93     TNamed("", ""),
94     fNCoefs(0),  
95     fNRows(0),
96     fNCols(0),
97     fNElemBound2D(0),
98     fNColsAtRow(0),
99     fColAtRowBg(0),
100     fCoefBound2D0(0),
101     fCoefBound2D1(0),
102     fCoefs(0),
103     fTmpCf1(0),
104     fTmpCf0(0)
105 {
106     // Default constructor
107     Init0();
108 }
109
110 AliCheb3DCalc::AliCheb3DCalc(FILE* stream):
111     TNamed("", ""),
112     fNCoefs(0),  
113     fNRows(0),
114     fNCols(0),
115     fNElemBound2D(0),
116     fNColsAtRow(0),
117     fColAtRowBg(0),
118     fCoefBound2D0(0),
119     fCoefBound2D1(0),
120     fCoefs(0),
121     fTmpCf1(0),
122     fTmpCf0(0)
123 {
124     // Default constructor
125     Init0();
126     LoadData(stream);
127 }
128
129 AliCheb3DCalc::AliCheb3DCalc(const AliCheb3DCalc& cheb):
130     TNamed("", ""),
131     fNCoefs(0),  
132     fNRows(0),
133     fNCols(0),
134     fNElemBound2D(0),
135     fNColsAtRow(0),
136     fColAtRowBg(0),
137     fCoefBound2D0(0),
138     fCoefBound2D1(0),
139     fCoefs(0),
140     fTmpCf1(0),
141     fTmpCf0(0)
142 {
143     // Copy constructor
144     cheb.Copy(*this);
145 }
146
147 void AliCheb3DCalc::Copy(TObject &) const
148 {
149   //dummy Copy function
150   AliFatal("Not implemented!");
151 }
152
153 //__________________________________________________________________________________________
154 void AliCheb3DCalc::Clear(Option_t*)
155 {
156   // delete all dynamycally allocated structures
157   if (fTmpCf1)       { delete[] fTmpCf1;  fTmpCf1 = 0;}
158   if (fTmpCf0)       { delete[] fTmpCf0;  fTmpCf0 = 0;}
159   if (fCoefs)        { delete[] fCoefs;   fCoefs  = 0;}
160   if (fCoefBound2D0) { delete[] fCoefBound2D0; fCoefBound2D0 = 0; }
161   if (fCoefBound2D1) { delete[] fCoefBound2D1; fCoefBound2D1 = 0; }
162   if (fNColsAtRow)   { delete[] fNColsAtRow;   fNColsAtRow = 0; }
163   if (fColAtRowBg)   { delete[] fColAtRowBg;   fColAtRowBg = 0; }
164   //
165 }
166
167 //__________________________________________________________________________________________
168 void AliCheb3DCalc::Init0()
169 {
170   // reset everything to 0
171   fNCoefs = fNRows = fNCols = fNElemBound2D = 0;
172   fCoefs = 0;
173   fCoefBound2D0 = fCoefBound2D1 = 0;
174   fNColsAtRow = fColAtRowBg = 0;
175   fTmpCf0 = fTmpCf1 = 0;
176 }
177
178 //__________________________________________________________________________________________
179 void AliCheb3DCalc::Print(Option_t* ) const
180 {
181   printf("Chebyshev parameterization data %s for 3D->1 function.\n",GetName());
182   int nmax3d = 0; 
183   for (int i=fNElemBound2D;i--;) if (fCoefBound2D0[i]>nmax3d) nmax3d = fCoefBound2D0[i];
184   printf("%d coefficients in %dx%dx%d matrix\n",fNCoefs,fNRows,fNCols,nmax3d);
185   //
186 }
187
188 //__________________________________________________________________________________________
189 Float_t  AliCheb3DCalc::Eval(Float_t  *par) const
190 {
191   // evaluate Chebyshev parameterization for 3D function.
192   // VERY IMPORTANT: par must contain the function arguments ALREADY MAPPED to [-1:1] interval
193   Float_t  &z = par[2];
194   Float_t  &y = par[1];
195   Float_t  &x = par[0];
196   //
197   int ncfRC;
198   for (int id0=fNRows;id0--;) {
199     int nCLoc = fNColsAtRow[id0];                   // number of significant coefs on this row
200     int Col0  = fColAtRowBg[id0];                   // beginning of local column in the 2D boundary matrix
201     for (int id1=nCLoc;id1--;) {
202       int id = id1+Col0;
203       fTmpCf1[id1] = (ncfRC=fCoefBound2D0[id]) ? ChebEval1D(z,fCoefs + fCoefBound2D1[id], ncfRC) : 0.0;
204     }
205     fTmpCf0[id0] = nCLoc>0 ? ChebEval1D(y,fTmpCf1,nCLoc):0.0;
206   }
207   return ChebEval1D(x,fTmpCf0,fNRows);
208   //
209 }
210
211 //_______________________________________________
212 #ifdef _INC_CREATION_ALICHEB3D_
213 void AliCheb3DCalc::SaveData(const char* outfile,Bool_t append) const
214 {
215   // writes coefficients data to output text file, optionallt appending on the end of existing file
216   TString strf = outfile;
217   gSystem->ExpandPathName(strf);
218   FILE* stream = fopen(strf,append ? "a":"w");
219   SaveData(stream);
220   fclose(stream);
221   //
222 }
223 #endif
224
225 //_______________________________________________
226 #ifdef _INC_CREATION_ALICHEB3D_
227 void AliCheb3DCalc::SaveData(FILE* stream) const
228 {
229   // writes coefficients data to existing output stream
230   // Note: fNCols, fNElemBound2D and fColAtRowBg is not stored, will be computed on fly during the loading of this file
231   fprintf(stream,"#\nSTART %s\n",GetName());
232   fprintf(stream,"# Number of rows\n%d\n",fNRows);
233   //
234   fprintf(stream,"# Number of columns per row\n");
235   for (int i=0;i<fNRows;i++) fprintf(stream,"%d\n",fNColsAtRow[i]);
236   //
237   fprintf(stream,"# Number of Coefs in each significant block of third dimension\n");
238   for (int i=0;i<fNElemBound2D;i++) fprintf(stream,"%d\n",fCoefBound2D0[i]);
239   //
240   fprintf(stream,"# Coefficients\n");
241   for (int i=0;i<fNCoefs;i++) fprintf(stream,"%+.8e\n",fCoefs[i]);
242   fprintf(stream,"END %s\n",GetName());
243   //
244 }
245 #endif
246
247 //_______________________________________________
248 void AliCheb3DCalc::LoadData(FILE* stream)
249 {
250   // Load coefs. from the stream 
251   if (!stream) {Error("LoadData","No stream provided.\nStop"); exit(1);}
252   TString buffs;
253   Clear();
254   ReadLine(buffs,stream);
255   if (!buffs.BeginsWith("START")) {Error("LoadData","Expected: \"START <fit_name>\", found \"%s\"\nStop\n",buffs.Data());exit(1);}
256   if (buffs.First(' ')>0) SetName(buffs.Data()+buffs.First(' ')+1);
257   //
258   ReadLine(buffs,stream); // NRows
259   fNRows = buffs.Atoi(); 
260   if (fNRows<1) {Error("LoadData","Expected: '<number_of_rows>', found \"%s\"\nStop\n",buffs.Data());exit(1);}
261   //
262   fNCols = 0;
263   fNElemBound2D = 0;
264   InitRows(fNRows);
265   //
266   for (int id0=0;id0<fNRows;id0++) {
267     ReadLine(buffs,stream);               // n.cols at this row
268     fNColsAtRow[id0] = buffs.Atoi();
269     fColAtRowBg[id0] = fNElemBound2D;     // begining of this row in 2D boundary surface
270     fNElemBound2D   += fNColsAtRow[id0];
271     if (fNCols<fNColsAtRow[id0]) fNCols = fNColsAtRow[id0];
272   }
273   InitCols(fNCols);
274   //  
275   fNCoefs = 0; 
276   InitElemBound2D(fNElemBound2D);
277   //
278   for (int i=0;i<fNElemBound2D;i++) {
279     ReadLine(buffs,stream);               // n.coeffs at 3-d dimension for the given column/row
280     fCoefBound2D0[i] = buffs.Atoi();
281     fCoefBound2D1[i] = fNCoefs;
282     fNCoefs += fCoefBound2D0[i];
283   }
284   //
285   if (fNCoefs<=0) {Error("LoadData","Negtive (%d) number of Chebychef coeffs. is obtained.\nStop\n",fNCoefs);exit(1);}
286   //
287   InitCoefs(fNCoefs);
288   for (int i=0;i<fNCoefs;i++) {
289     ReadLine(buffs,stream);
290     fCoefs[i] = buffs.Atof();
291   }
292   // check end_of_data record
293   ReadLine(buffs,stream);
294   if (!buffs.BeginsWith("END") || !buffs.Contains(GetName())) {
295     Error("LoadData","Expected \"END %s\", found \"%s\".\nStop\n",GetName(),buffs.Data());
296     exit(1);
297   }
298   //
299 }
300
301 //_______________________________________________
302 void AliCheb3DCalc::ReadLine(TString& str,FILE* stream) 
303 {
304   // read single line from the stream, skipping empty and commented lines. EOF is not expected
305   while (str.Gets(stream)) {
306     str = str.Strip(TString::kBoth,' ');
307     if (str.IsNull()||str.BeginsWith("#")) continue;
308     return;
309   }
310   fprintf(stderr,"AliCheb3D::ReadLine: Failed to read from stream.\nStop");exit(1); // normally, should not reach here
311 }
312
313 //_______________________________________________
314 void AliCheb3DCalc::InitCols(int nc)
315 {
316   // Set max.number of significant columns in the coefs matrix
317   fNCols = nc;
318   if (fTmpCf1) delete[] fTmpCf1;
319   fTmpCf1 = new Float_t [fNCols];
320 }
321
322 //_______________________________________________
323 void AliCheb3DCalc::InitRows(int nr)
324 {
325   // Set max.number of significant rows in the coefs matrix
326   if (fNColsAtRow) delete[] fNColsAtRow;
327   if (fColAtRowBg) delete[] fColAtRowBg;
328   if (fTmpCf0)     delete[] fTmpCf0;
329   fNRows = nr;
330   fNColsAtRow = new Int_t[fNRows];
331   fTmpCf0     = new Float_t [fNRows];
332   fColAtRowBg = new Int_t[fNRows];
333   for (int i=fNRows;i--;) fNColsAtRow[i] = fColAtRowBg[i] = 0;
334 }
335
336 //_______________________________________________
337 void AliCheb3DCalc::InitElemBound2D(int ne)
338 {
339   // Set max number of significant coefs for given row/column of coefs 3D matrix
340   if (fCoefBound2D0) delete[] fCoefBound2D0; 
341   if (fCoefBound2D1) delete[] fCoefBound2D1; 
342   fNElemBound2D = ne;
343   fCoefBound2D0 = new Int_t[fNElemBound2D];
344   fCoefBound2D1 = new Int_t[fNElemBound2D];
345   for (int i=fNElemBound2D;i--;) fCoefBound2D0[i] = fCoefBound2D1[i] = 0;
346 }
347
348 //_______________________________________________
349 void AliCheb3DCalc::InitCoefs(int nc)
350 {
351   // Set total number of significant coefs
352   if (fCoefs) delete[] fCoefs; 
353   fNCoefs = nc;
354   fCoefs = new Float_t [fNCoefs];
355   for (int i=fNCoefs;i--;) fCoefs[i] = 0.0;
356 }
357
358
359
360
361 ClassImp(AliCheb3D)
362
363 AliCheb3D::AliCheb3D():
364     TNamed("", ""),
365     fDimOut(0),
366     fPrec(0.),
367     fChebCalc(),
368     fMaxCoefs(0),
369     fResTmp(0),
370     fGrid(0),
371     fUsrFunName(),
372     fUsrMacro(0)             
373 {
374     // Default constructor
375     Init0();
376 }
377
378 AliCheb3D::AliCheb3D(const char* inputFile):
379     TNamed("", ""),
380     fDimOut(0),
381     fPrec(0.),
382     fChebCalc(),
383     fMaxCoefs(0),
384     fResTmp(0),
385     fGrid(0),
386     fUsrFunName(),
387     fUsrMacro(0)             
388 {
389     // Default constructor
390     Init0();
391     LoadData(inputFile);
392 }
393
394
395
396 AliCheb3D::AliCheb3D(FILE* stream):
397     TNamed("", ""),
398     fDimOut(0),
399     fPrec(0.),
400     fChebCalc(),
401     fMaxCoefs(0),
402     fResTmp(0),
403     fGrid(0),
404     fUsrFunName(),
405     fUsrMacro(0)             
406 {
407     // Default constructor
408     Init0();
409     LoadData(stream);
410 }
411
412 AliCheb3D::AliCheb3D(const AliCheb3D& cheb):
413     TNamed("", ""),
414     fDimOut(0),
415     fPrec(0.),
416     fChebCalc(),
417     fMaxCoefs(0),
418     fResTmp(0),
419     fGrid(0),
420     fUsrFunName(),
421     fUsrMacro(0)             
422 {
423     // Copy constructor
424     cheb.Copy(*this);
425 }
426
427 //__________________________________________________________________________________________
428 #ifdef _INC_CREATION_ALICHEB3D_
429 AliCheb3D::AliCheb3D(const char* funName, int DimOut, Float_t  *bmin,Float_t  *bmax, Int_t *npoints, Float_t prec) : TNamed(funName,funName)
430 {
431   // Construct the parameterization for the function
432   // funName : name of the file containing the function: void funName(Float_t * inp,Float_t * out)
433   // DimOut  : dimension of the vector computed by the user function
434   // bmin    : array of 3 elements with the lower boundaries of the region where the function is defined
435   // bmax    : array of 3 elements with the upper boundaries of the region where the function is defined
436   // npoints : array of 3 elements with the number of points to compute in each of 3 dimension
437   // prec    : max allowed absolute difference between the user function and computed parameterization on the requested grid
438   //
439   Init0();
440   fPrec = TMath::Max(1.E-12f,prec);
441   if (DimOut<1) {Error("AliCheb3D","Requested output dimension is %d\nStop\n",fDimOut); exit(1);}
442   SetDimOut(DimOut);
443   PrepareBoundaries(bmin,bmax);
444   DefineGrid(npoints);
445   SetUsrFunction(funName);
446   ChebFit();
447   //
448 }
449 #endif
450
451 //__________________________________________________________________________________________
452 #ifdef _INC_CREATION_ALICHEB3D_
453 AliCheb3D::AliCheb3D(void (*ptr)(float*,float*), int DimOut, Float_t  *bmin,Float_t  *bmax, Int_t *npoints, Float_t prec) : TNamed("AliCheb3D","AliCheb3D")
454 {
455   // Construct the parameterization for the function
456   // ptr     : pointer on the function: void fun(Float_t * inp,Float_t * out)
457   // DimOut  : dimension of the vector computed by the user function
458   // bmin    : array of 3 elements with the lower boundaries of the region where the function is defined
459   // bmax    : array of 3 elements with the upper boundaries of the region where the function is defined
460   // npoints : array of 3 elements with the number of points to compute in each of 3 dimension
461   // prec    : max allowed absolute difference between the user function and computed parameterization on the requested grid
462   //
463   Init0();
464   fPrec = TMath::Max(1.E-12f,prec);
465   if (DimOut<1) {Error("AliCheb3D","Requested output dimension is %d\nStop\n",fDimOut); exit(1);}
466   SetDimOut(DimOut);
467   PrepareBoundaries(bmin,bmax);
468   DefineGrid(npoints);
469   SetUsrFunction(ptr);
470   ChebFit();
471   //
472 }
473 #endif
474
475
476 void AliCheb3D::Copy(TObject &) const
477 {
478   //dummy Copy function
479   AliFatal("Not implemented!");
480 }
481
482 //__________________________________________________________________________________________
483 void AliCheb3D::Clear(Option_t*)
484 {
485   if (fResTmp)        { delete[] fResTmp; fResTmp = 0; }
486   if (fGrid)          { delete[] fGrid;   fGrid   = 0; }
487   if (fUsrMacro)      { delete fUsrMacro; fUsrMacro = 0;}
488   fChebCalc.Delete();
489   //
490 }
491
492 //__________________________________________________________________________________________
493 void AliCheb3D::Print(Option_t* opt) const
494 {
495   printf("%s: Chebyshev parameterization for 3D->%dD function. Precision: %e\n",GetName(),fDimOut,fPrec);
496   printf("Region of validity: [%+.5e:%+.5e] [%+.5e:%+.5e] [%+.5e:%+.5e]\n",fBMin[0],fBMax[0],fBMin[1],fBMax[1],fBMin[2],fBMax[2]);
497   TString opts = opt; opts.ToLower();
498   if (opts.Contains("l")) for (int i=0;i<fDimOut;i++) {printf("Output dimension %d:\n",i+1); GetChebCalc(i)->Print();}
499   //
500 }
501
502 //__________________________________________________________________________________________
503 void AliCheb3D::Init0()
504 {
505   for (int i=3;i--;) fBMin[i] = fBMax[i] = fBScale[i] = fBOffset[i] = 0;
506   fMaxCoefs = 0;
507   fGrid = 0;
508   fResTmp = 0;
509   fUsrFunName = "";
510   fUsrMacro = 0;
511 #ifdef _INC_CREATION_ALICHEB3D_
512   gUsrFunAliCheb3D = 0;
513 #endif
514 }
515
516 //__________________________________________________________________________________________
517 void AliCheb3D::PrepareBoundaries(Float_t  *bmin,Float_t  *bmax)
518 {
519   // Set and check boundaries defined by user, prepare coefficients for their conversion to [-1:1] interval
520   //
521   for (int i=3;i--;) {
522     fBMin[i]   = bmin[i];
523     fBMax[i]   = bmax[i];
524     fBScale[i] = bmax[i]-bmin[i];
525     if (fBScale[i]<=0) { 
526       Error("PrepareBoundaries","Boundaries for %d-th dimension are not increasing: %+.4e %+.4e\nStop\n",i,fBMin[i],fBMax[i]);
527       exit(1);
528     }
529     fBOffset[i] = bmin[i] + fBScale[i]/2.0;
530     fBScale[i] = 2./fBScale[i];
531   }
532   //
533 }
534
535 //__________________________________________________________________________________________
536 #ifdef _INC_CREATION_ALICHEB3D_
537 void AliCheb3D::SetUsrFunction(const char* name)
538 {
539   // load user macro with function definition and compile it
540   gUsrFunAliCheb3D = 0; 
541   fUsrFunName = name;
542   gSystem->ExpandPathName(fUsrFunName);
543   if (fUsrMacro) delete fUsrMacro;
544   TString tmpst = fUsrFunName;
545   tmpst += "+"; // prepare filename to compile
546   if (gROOT->LoadMacro(tmpst.Data())) {Error("SetUsrFunction","Failed to load user function from %s\nStop\n",name); exit(1);}
547   fUsrMacro = new TMethodCall();        
548   tmpst = tmpst.Data() + tmpst.Last('/')+1; //Strip away any path preceding the macro file name
549   int dot = tmpst.Last('.');
550   if (dot>0) tmpst.Resize(dot);
551   fUsrMacro->InitWithPrototype(tmpst.Data(),"Float_t *,Float_t *");
552   long args[2];
553   args[0] = (long)fArgsTmp;
554   args[1] = (long)fResTmp;
555   fUsrMacro->SetParamPtrs(args); 
556   //
557 }
558 #endif
559
560 //__________________________________________________________________________________________
561 #ifdef _INC_CREATION_ALICHEB3D_
562 void AliCheb3D::SetUsrFunction(void (*ptr)(float*,float*))
563 {
564   if (fUsrMacro) delete fUsrMacro;
565   fUsrMacro = 0;
566   fUsrFunName = "";
567   gUsrFunAliCheb3D = ptr;
568 }
569 #endif
570
571 //__________________________________________________________________________________________
572 #ifdef _INC_CREATION_ALICHEB3D_
573 void AliCheb3D::EvalUsrFunction(Float_t  *x, Float_t  *res) {
574   for (int i=3;i--;) fArgsTmp[i] = x[i];
575   if   (gUsrFunAliCheb3D) gUsrFunAliCheb3D(fArgsTmp,fResTmp);
576   else fUsrMacro->Execute(); 
577   for (int i=fDimOut;i--;) res[i] = fResTmp[i];
578 }
579 #endif
580
581 //__________________________________________________________________________________________
582 #ifdef _INC_CREATION_ALICHEB3D_
583 Int_t AliCheb3D::CalcChebCoefs(Float_t  *funval,int np, Float_t  *outCoefs, Float_t  prec)
584 {
585   // Calculate Chebyshev coeffs using precomputed function values at np roots.
586   // If prec>0, estimate the highest coeff number providing the needed precision
587   //
588   double sm;                 // do summations in double to minimize the roundoff error
589   for (int ic=0;ic<np;ic++) { // compute coeffs
590     sm = 0;          
591     for (int ir=0;ir<np;ir++) {
592       float  rt = TMath::Cos( ic*(ir+0.5)*TMath::Pi()/np);
593       sm += funval[ir]*rt;
594     }
595     outCoefs[ic] = Float_t( sm * ((ic==0) ? 1./np : 2./np) );
596   }
597   //
598   if (prec<=0) return np;
599   //
600   sm = 0;
601   int cfMax = 0;
602   for (cfMax=np;cfMax--;) {
603     sm += TMath::Abs(outCoefs[cfMax]);
604     if (sm>=prec) break;
605   }
606   if (++cfMax==0) cfMax=1;
607   return cfMax;
608   //
609 }
610 #endif
611
612 //__________________________________________________________________________________________
613 #ifdef _INC_CREATION_ALICHEB3D_
614 void AliCheb3D::DefineGrid(Int_t* npoints)
615 {
616   // prepare the grid of Chebyshev roots in each dimension
617   const int kMinPoints = 1;
618   int ntot = 0;
619   fMaxCoefs = 1;
620   for (int id=3;id--;) { 
621     fNPoints[id] = npoints[id];
622     if (fNPoints[id]<kMinPoints) {
623       Error("DefineGrid","at %d-th dimension %d point is requested, at least %d is needed\nStop\n",fNPoints[id],kMinPoints);
624       exit(1);
625     }
626     ntot += fNPoints[id];
627     fMaxCoefs *= fNPoints[id];
628   }
629   fGrid = new Float_t [ntot];
630   //
631   int curp = 0;
632   for (int id=3;id--;) { 
633     int np = fNPoints[id];
634     fGridOffs[id] = curp;
635     for (int ip=0;ip<np;ip++) {
636       Float_t x = TMath::Cos( TMath::Pi()*(ip+0.5)/np );
637       fGrid[curp++] = MapToExternal(x,id);
638     }
639   }
640   //
641 }
642 #endif
643
644 //__________________________________________________________________________________________
645 #ifdef _INC_CREATION_ALICHEB3D_
646 Int_t AliCheb3D::ChebFit()
647 {
648   // prepare parameterization for all output dimensions
649   int ir=0; 
650   for (int i=fDimOut;i--;) ir+=ChebFit(i); 
651   return ir;
652 }
653 #endif
654
655 //__________________________________________________________________________________________
656 #ifdef _INC_CREATION_ALICHEB3D_
657 Int_t AliCheb3D::ChebFit(int dmOut)
658 {
659   // prepare paramaterization of 3D function for dmOut-th dimension 
660   int maxDim = 0;
661   for (int i=0;i<3;i++) if (maxDim<fNPoints[i]) maxDim = fNPoints[i];
662   Float_t  *fvals      = new Float_t [ fNPoints[0] ];
663   Float_t  *tmpCoef3D  = new Float_t [ fNPoints[0]*fNPoints[1]*fNPoints[2] ]; 
664   Float_t  *tmpCoef2D  = new Float_t [ fNPoints[0]*fNPoints[1] ]; 
665   Float_t  *tmpCoef1D  = new Float_t [ maxDim ];
666   //
667   Float_t RTiny = fPrec/Float_t(maxDim); // neglect coefficient below this threshold
668   //
669   // 1D Cheb.fit for 0-th dimension at current steps of remaining dimensions
670   int ncmax = 0;
671   //
672   AliCheb3DCalc* cheb =  GetChebCalc(dmOut);
673   //
674   for (int id2=fNPoints[2];id2--;) {
675     fArgsTmp[2] = fGrid[ fGridOffs[2]+id2 ];
676     //
677     for (int id1=fNPoints[1];id1--;) {
678       fArgsTmp[1] = fGrid[ fGridOffs[1]+id1 ];
679       //
680       for (int id0=fNPoints[0];id0--;) {
681         fArgsTmp[0] = fGrid[ fGridOffs[0]+id0 ];
682         EvalUsrFunction();     // compute function values at Chebyshev roots of 0-th dimension
683         fvals[id0] =  fResTmp[dmOut];
684       }
685       int nc = CalcChebCoefs(fvals,fNPoints[0], tmpCoef1D, fPrec);
686       for (int id0=fNPoints[0];id0--;) tmpCoef2D[id1 + id0*fNPoints[1]] = tmpCoef1D[id0];
687       if (ncmax<nc) ncmax = nc;              // max coefs to be kept in dim0 to guarantee needed precision
688     }
689     //
690     // once each 1d slice of given 2d slice is parametrized, parametrize the Cheb.coeffs
691     for (int id0=fNPoints[0];id0--;) {
692       CalcChebCoefs( tmpCoef2D+id0*fNPoints[1], fNPoints[1], tmpCoef1D, -1);
693       for (int id1=fNPoints[1];id1--;) tmpCoef3D[id2 + fNPoints[2]*(id1+id0*fNPoints[1])] = tmpCoef1D[id1];
694     }
695   }
696   //
697   // now fit the last dimensions Cheb.coefs
698   for (int id0=fNPoints[0];id0--;) {
699     for (int id1=fNPoints[1];id1--;) {
700       CalcChebCoefs( tmpCoef3D+ fNPoints[2]*(id1+id0*fNPoints[1]), fNPoints[2], tmpCoef1D, -1);
701       for (int id2=fNPoints[2];id2--;) tmpCoef3D[id2+ fNPoints[2]*(id1+id0*fNPoints[1])] = tmpCoef1D[id2]; // store on place
702     }
703   }
704   //
705   // now find 2D surface which separates significant coefficients of 3D matrix from nonsignificant ones (up to fPrec)
706   int *tmpCoefSurf = new Int_t[ fNPoints[0]*fNPoints[1] ];
707   for (int id0=fNPoints[0];id0--;) for (int id1=fNPoints[1];id1--;) tmpCoefSurf[id1+id0*fNPoints[1]]=0;  
708   Double_t resid = 0;
709   for (int id0=fNPoints[0];id0--;) {
710     for (int id1=fNPoints[1];id1--;) {
711       for (int id2=fNPoints[2];id2--;) {
712         int id = id2 + fNPoints[2]*(id1+id0*fNPoints[1]);
713         Float_t  cfa = TMath::Abs(tmpCoef3D[id]);
714         if (cfa < RTiny) {tmpCoef3D[id] = 0; continue;} // neglect coeefs below the threshold
715
716         resid += cfa;
717         if (resid<fPrec) continue; // this coeff is negligible
718         // otherwise go back 1 step
719         resid -= cfa;
720         tmpCoefSurf[id1+id0*fNPoints[1]] = id2+1; // how many coefs to keep
721         break;
722       }
723     }
724   }
725   /*
726   printf("\n\nCoeffs\n");  
727   int cnt = 0;
728   for (int id0=0;id0<fNPoints[0];id0++) {
729     for (int id1=0;id1<fNPoints[1];id1++) {
730       for (int id2=0;id2<fNPoints[2];id2++) {
731         printf("%2d%2d%2d %+.4e |",id0,id1,id2,tmpCoef3D[cnt++]);
732       }
733       printf("\n");
734     }
735     printf("\n");
736   }
737   */
738   // see if there are rows to reject, find max.significant column at each row
739   int NRows = fNPoints[0];
740   int *tmpCols = new int[NRows]; 
741   for (int id0=fNPoints[0];id0--;) {
742     int id1 = fNPoints[1];
743     while (id1>0 && tmpCoefSurf[(id1-1)+id0*fNPoints[1]]==0) id1--;
744     tmpCols[id0] = id1;
745   }
746   // find max significant row
747   for (int id0=NRows;id0--;) {if (tmpCols[id0]>0) break; NRows--;}
748   // find max significant column and fill the permanent storage for the max sigificant column of each row
749   cheb->InitRows(NRows);                  // create needed arrays;
750   int *NColsAtRow = cheb->GetNColsAtRow();
751   int *ColAtRowBg = cheb->GetColAtRowBg();
752   int NCols = 0;
753   int NElemBound2D = 0;
754   for (int id0=0;id0<NRows;id0++) {
755     NColsAtRow[id0] = tmpCols[id0];     // number of columns to store for this row
756     ColAtRowBg[id0] = NElemBound2D;     // begining of this row in 2D boundary surface
757     NElemBound2D += tmpCols[id0];
758     if (NCols<NColsAtRow[id0]) NCols = NColsAtRow[id0];
759   }
760   cheb->InitCols(NCols);
761   delete[] tmpCols;
762   //  
763   // create the 2D matrix defining the boundary of significance for 3D coeffs.matrix 
764   // and count the number of siginifacnt coefficients
765   //
766   cheb->InitElemBound2D(NElemBound2D);
767   int *CoefBound2D0 = cheb->GetCoefBound2D0();
768   int *CoefBound2D1 = cheb->GetCoefBound2D1();
769   fMaxCoefs = 0; // redefine number of coeffs
770   for (int id0=0;id0<NRows;id0++) {
771     int nCLoc = NColsAtRow[id0];
772     int Col0  = ColAtRowBg[id0];
773     for (int id1=0;id1<nCLoc;id1++) {
774       CoefBound2D0[Col0 + id1] = tmpCoefSurf[id1+id0*fNPoints[1]];  // number of coefs to store for 3-d dimension
775       CoefBound2D1[Col0 + id1] = fMaxCoefs;
776       fMaxCoefs += CoefBound2D0[Col0 + id1];
777     }
778   }
779   //
780   // create final compressed 3D matrix for significant coeffs
781   cheb->InitCoefs(fMaxCoefs);
782   Float_t  *Coefs = cheb->GetCoefs();
783   int count = 0;
784   for (int id0=0;id0<NRows;id0++) {
785     int ncLoc = NColsAtRow[id0];
786     int Col0  = ColAtRowBg[id0];
787     for (int id1=0;id1<ncLoc;id1++) {
788       int ncf2 = CoefBound2D0[Col0 + id1];
789       for (int id2=0;id2<ncf2;id2++) {
790         Coefs[count++] = tmpCoef3D[id2 + fNPoints[2]*(id1+id0*fNPoints[1])];
791       }
792     }
793   }
794   /*
795   printf("\n\nNewSurf\n");
796   for (int id0=0;id0<fNPoints[0];id0++) {
797     for (int id1=0;id1<fNPoints[1];id1++) {
798       printf("(%2d %2d) %2d |",id0,id1,tmpCoefSurf[id1+id0*fNPoints[1]]);  
799     }
800     printf("\n");
801   }
802   */
803   //
804   delete[] tmpCoefSurf;
805   delete[] tmpCoef1D;
806   delete[] tmpCoef2D;
807   delete[] tmpCoef3D;
808   delete[] fvals;
809   //
810   return 1;
811 }
812 #endif
813
814 //_______________________________________________
815 #ifdef _INC_CREATION_ALICHEB3D_
816 void AliCheb3D::SaveData(const char* outfile,Bool_t append) const
817 {
818   // writes coefficients data to output text file, optionallt appending on the end of existing file
819   TString strf = outfile;
820   gSystem->ExpandPathName(strf);
821   FILE* stream = fopen(strf,append ? "a":"w");
822   SaveData(stream);
823   fclose(stream);
824   //
825 }
826 #endif
827
828 //_______________________________________________
829 #ifdef _INC_CREATION_ALICHEB3D_
830 void AliCheb3D::SaveData(FILE* stream) const
831 {
832   // writes coefficients data to existing output stream
833   //
834   fprintf(stream,"\n# These are automatically generated data for the Chebyshev interpolation of 3D->%dD function\n",fDimOut); 
835   fprintf(stream,"#\nSTART %s\n",GetName());
836   fprintf(stream,"# Dimensionality of the output\n%d\n",fDimOut);
837   fprintf(stream,"# Interpolation abs. precision\n%+.8e\n",fPrec);
838   //
839   fprintf(stream,"# Lower boundaries of interpolation region\n");
840   for (int i=0;i<3;i++) fprintf(stream,"%+.8e\n",fBMin[i]);
841   fprintf(stream,"# Upper boundaries of interpolation region\n");
842   for (int i=0;i<3;i++) fprintf(stream,"%+.8e\n",fBMax[i]);
843   fprintf(stream,"# Parameterization for each output dimension follows:\n",GetName());
844   //
845   for (int i=0;i<fDimOut;i++) GetChebCalc(i)->SaveData(stream);
846   fprintf(stream,"#\nEND %s\n#\n",GetName());
847   //
848 }
849 #endif
850
851 //_______________________________________________
852 void AliCheb3D::LoadData(const char* inpFile)
853 {
854   TString strf = inpFile;
855   gSystem->ExpandPathName(strf);
856   FILE* stream = fopen(strf.Data(),"r");
857   LoadData(stream);
858   fclose(stream);
859   //
860 }
861
862 //_______________________________________________
863 void AliCheb3D::LoadData(FILE* stream)
864 {
865   if (!stream) {Error("LoadData","No stream provided.\nStop"); exit(1);}
866   TString buffs;
867   Clear();
868   AliCheb3DCalc::ReadLine(buffs,stream);
869   if (!buffs.BeginsWith("START")) {Error("LoadData","Expected: \"START <fit_name>\", found \"%s\"\nStop\n",buffs.Data());exit(1);}
870   SetName(buffs.Data()+buffs.First(' ')+1);
871   //
872   AliCheb3DCalc::ReadLine(buffs,stream); // N output dimensions
873   fDimOut = buffs.Atoi(); 
874   if (fDimOut<1) {Error("LoadData","Expected: '<number_of_output_dimensions>', found \"%s\"\nStop\n",buffs.Data());exit(1);}
875   //
876   SetDimOut(fDimOut);
877   //
878   AliCheb3DCalc::ReadLine(buffs,stream); // Interpolation abs. precision
879   fPrec = buffs.Atof();
880   if (fPrec<=0) {Error("LoadData","Expected: '<abs.precision>', found \"%s\"\nStop\n",buffs.Data());exit(1);}
881   //
882   for (int i=0;i<3;i++) { // Lower boundaries of interpolation region
883     AliCheb3DCalc::ReadLine(buffs,stream);
884     fBMin[i] = buffs.Atof(); 
885   }
886   for (int i=0;i<3;i++) { // Upper boundaries of interpolation region
887     AliCheb3DCalc::ReadLine(buffs,stream);
888     fBMax[i] = buffs.Atof(); 
889   }
890   PrepareBoundaries(fBMin,fBMax);
891   //
892   // data for each output dimension
893   for (int i=0;i<fDimOut;i++) GetChebCalc(i)->LoadData(stream);
894   //
895   // check end_of_data record
896   AliCheb3DCalc::ReadLine(buffs,stream);
897   if (!buffs.BeginsWith("END") || !buffs.Contains(GetName())) {
898     Error("LoadData","Expected \"END %s\", found \"%s\".\nStop\n",GetName(),buffs.Data());
899     exit(1);
900   }
901   //
902 }
903
904 //_______________________________________________
905 void AliCheb3D::SetDimOut(int d)
906 {
907   fDimOut = d;
908   if (fResTmp) delete fResTmp;
909   fResTmp = new Float_t[fDimOut]; // RRR
910   fChebCalc.Delete();
911   for (int i=0;i<d;i++) fChebCalc.AddAtAndExpand(new AliCheb3DCalc(),i);
912 }
913
914 //_______________________________________________
915 void AliCheb3D::ShiftBound(int id,float dif)
916 {
917   if (id<0||id>2) {printf("Maximum 3 dimensions are supported\n"); return;}
918   fBMin[id] += dif;
919   fBMax[id] += dif;
920   fBOffset[id] += dif;
921 }
922
923 //_______________________________________________
924 #ifdef _INC_CREATION_ALICHEB3D_
925 TH1* AliCheb3D::TestRMS(int idim,int npoints,TH1* histo)
926 {
927   // fills the difference between the original function and parameterization (for idim-th component of the output)
928   // to supplied histogram. Calculations are done in npoints random points. 
929   // If the hostgram was not supplied, it will be created. It is up to the user to delete it! 
930   if (!fUsrMacro) {
931     printf("No user function is set\n");
932     return 0;
933   }
934   if (!histo) histo = new TH1D(GetName(),"Control: Function - Parametrization",100,-2*fPrec,2*fPrec);
935   for (int ip=npoints;ip--;) {
936     gRandom->RndmArray(3,(Float_t *)fArgsTmp);
937     for (int i=3;i--;) fArgsTmp[i] = fBMin[i] + fArgsTmp[i]*(fBMax[i]-fBMin[i]);
938     EvalUsrFunction();
939     Float_t valFun = fResTmp[idim];
940     Eval(fArgsTmp,fResTmp);
941     Float_t valPar = fResTmp[idim];
942     histo->Fill(valFun - valPar);
943   }
944   return histo;
945   //
946 }
947 #endif