poly.c 23.7 KB
Newer Older
1
2
/*
*				poly.c
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3
*
4
* Polynomial functions.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
5
*
6
*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Emmanuel Bertin's avatar
Emmanuel Bertin committed
7
*
8
*	This file part of:	AstrOmatic software
Emmanuel Bertin's avatar
Emmanuel Bertin committed
9
*
10
*	Copyright:		(C) 1998-2012 IAP/CNRS/UPMC
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
*
*	License:		GNU General Public License
*
*	AstrOmatic software is free software: you can redistribute it and/or
*	modify it under the terms of the GNU General Public License as
*	published by the Free Software Foundation, either version 3 of the
*	License, or (at your option) any later version.
*	AstrOmatic software is distributed in the hope that it will be useful,
*	but WITHOUT ANY WARRANTY; without even the implied warranty of
*	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*	GNU General Public License for more details.
*	You should have received a copy of the GNU General Public License
*	along with AstrOmatic software.
*	If not, see <http://www.gnu.org/licenses/>.
*
26
*	Last modified:		20/11/2012
27
28
*
*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
Emmanuel Bertin's avatar
Emmanuel Bertin committed
29
30
31
32
33
34
35
36
37
38

#ifdef HAVE_CONFIG_H
#include	"config.h"
#endif

#include	<math.h>
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>

39
40
#include	"poly.h"

41
#ifdef HAVE_ATLAS
42
43
44
45
46
#include ATLAS_LAPACK_H
#endif

#ifdef HAVE_LAPACKE
#include LAPACKE_H
47
//#define MATSTORAGE_PACKED 1
48
#endif
Emmanuel Bertin's avatar
Emmanuel Bertin committed
49
50
51
52
53
54
55
56
57
58
59

#define	QCALLOC(ptr, typ, nel) \
		{if (!(ptr = (typ *)calloc((size_t)(nel),sizeof(typ)))) \
		  qerror("Not enough memory for ", \
			#ptr " (" #nel " elements) !");;}

#define	QMALLOC(ptr, typ, nel) \
		{if (!(ptr = (typ *)malloc((size_t)(nel)*sizeof(typ)))) \
		  qerror("Not enough memory for ", \
			#ptr " (" #nel " elements) !");;}

60
61
62
63
64
65
66
#define QMEMCPY(ptrin, ptrout, typ, nel) \
		{if (ptrin) \
		  {if (!(ptrout = (typ *)malloc((size_t)(nel)*sizeof(typ)))) \
		    qerror("Not enough memory for ", \
			#ptrout " (" #nel " elements) !"); \
		memcpy(ptrout, ptrin, (size_t)(nel)*sizeof(typ));};;}

Emmanuel Bertin's avatar
Emmanuel Bertin committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/********************************* qerror ************************************/
/*
I hope it will never be used!
*/
void	qerror(char *msg1, char *msg2)
  {
  fprintf(stderr, "\n> %s%s\n\n",msg1,msg2);
  exit(-1);
  }


/****** poly_init ************************************************************
PROTO   polystruct *poly_init(int *group, int ndim, int *degree, int ngroup)
PURPOSE Allocate and initialize a polynom structure.
INPUT   1D array containing the group for each parameter,
        number of dimensions (parameters),
        1D array with the polynomial degree for each group,
        number of groups.
OUTPUT  polystruct pointer.
NOTES   -.
AUTHOR  E. Bertin (IAP)
88
VERSION 30/08/2011
Emmanuel Bertin's avatar
Emmanuel Bertin committed
89
90
91
92
93
94
95
96
 ***/
polystruct	*poly_init(int *group, int ndim, int *degree, int ngroup)
  {
   void	qerror(char *msg1, char *msg2);
   polystruct	*poly;
   char		str[512];
   int		nd[POLY_MAXDIM];
   int		*groupt,
97
		d,g,n, num,den, dmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132

  QCALLOC(poly, polystruct, 1);
  if ((poly->ndim=ndim) > POLY_MAXDIM)
    {
    sprintf(str, "The dimensionality of the polynom (%d) exceeds the maximum\n"
		"allowed one (%d)", ndim, POLY_MAXDIM);
    qerror("*Error*: ", str);
    }

  if (ndim)
    QMALLOC(poly->group, int, poly->ndim);
    for (groupt=poly->group, d=ndim; d--;)
      *(groupt++) = *(group++)-1;

  poly->ngroup = ngroup;
  if (ngroup)
    {
    group = poly->group;	/* Forget the original *group */

    QMALLOC(poly->degree, int, poly->ngroup);

/*-- Compute the number of context parameters for each group */
    memset(nd, 0, ngroup*sizeof(int));
    for (d=0; d<ndim; d++)
      {
      if ((g=group[d])>=ngroup)
        qerror("*Error*: polynomial GROUP out of range", "");
      nd[g]++;
      }
    }

/* Compute the total number of coefficients */
  poly->ncoeff = 1;
  for (g=0; g<ngroup; g++)
    {
133
    if ((dmax=poly->degree[g]=*(degree++))>POLY_MAXDEGREE)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
134
135
136
137
138
139
      {
      sprintf(str, "The degree of the polynom (%d) exceeds the maximum\n"
		"allowed one (%d)", poly->degree[g], POLY_MAXDEGREE);
      qerror("*Error*: ", str);
      }

140
141
142
143
/*-- There are (n+d)!/(n!d!) coeffs per group = Prod_(i<=d)(n+i)/Prod_(i<=d)i */
    n = nd[g];
    d = dmax>n? n: dmax;
    for (num=den=1; d; num*=(n+dmax--), den*=d--);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
    poly->ncoeff *= num/den;
    }

  QMALLOC(poly->basis, double, poly->ncoeff);
  QCALLOC(poly->coeff, double, poly->ncoeff);

  return poly;
  }


/****** poly_end *************************************************************
PROTO   void poly_end(polystruct *poly)
PURPOSE Free a polynom structure and everything it contains.
INPUT   polystruct pointer.
OUTPUT  -.
NOTES   -.
160
161
AUTHOR  E. Bertin (IAP)
VERSION 04/11/2008
Emmanuel Bertin's avatar
Emmanuel Bertin committed
162
163
164
165
166
167
168
 ***/
void	poly_end(polystruct *poly)
  {
  if (poly)
    {
    free(poly->coeff);
    free(poly->basis);
169
    free(poly->orthobasis);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
170
171
    free(poly->degree);
    free(poly->group);
172
173
    free(poly->orthomat);
    free(poly->deorthomat);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
174
175
    free(poly);
    }
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219

  return;
  }


/****** poly_copy *************************************************************
PROTO   polystruct *poly_copy(polystruct *poly)
PURPOSE Copy a polynom structure and everything it contains.
INPUT   polystruct pointer.
OUTPUT  -.
NOTES   -.
AUTHOR  E. Bertin (IAP)
VERSION 04/11/2008
 ***/
polystruct *poly_copy(polystruct *poly)
  {
   polystruct	*newpoly;

  if (poly)
    {
    QMALLOC(newpoly, polystruct, 1);
    *newpoly = *poly;
    if (poly->ncoeff)
      {
      QMEMCPY(poly->coeff, newpoly->coeff, double, poly->ncoeff);
      QMEMCPY(poly->basis, newpoly->basis, double, poly->ncoeff);
      }
    if (poly->ndim)
      QMEMCPY(poly->group, newpoly->group, int, poly->ndim);
    if (poly->ngroup)
      QMEMCPY(poly->degree, newpoly->degree, int, poly->ngroup);
    if (poly->orthomat)
      {
      QMEMCPY(poly->orthomat, newpoly->orthomat, double,
		poly->ncoeff*poly->ncoeff);
      QMEMCPY(poly->deorthomat, newpoly->deorthomat, double,
		poly->ncoeff*poly->ncoeff);
      QMEMCPY(poly->orthobasis, newpoly->orthobasis, double, poly->ncoeff);
      }

    return newpoly;
    }
  else
    return NULL;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
220
221
222
223
224
  }


/****** poly_func ************************************************************
PROTO   double poly_func(polystruct *poly, double *pos)
225
PURPOSE Evaluate a multidimensional polynomial.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
INPUT   polystruct pointer,
        pointer to the 1D array of input vector data.
OUTPUT  Polynom value.
NOTES   Values of the basis functions are updated in poly->basis.
AUTHOR  E. Bertin (IAP)
VERSION 03/03/2004
 ***/
double	poly_func(polystruct *poly, double *pos)
  {
   double	xpol[POLY_MAXDIM+1];
   double      	*post, *xpolt, *basis, *coeff, xval;
   long double	val;
   int		expo[POLY_MAXDIM+1], gexpo[POLY_MAXDIM+1];
   int	       	*expot, *degree,*degreet, *group,*groupt, *gexpot,
			d,g,t, ndim;

/* Prepare the vectors and counters */
  ndim = poly->ndim;
  basis = poly->basis;
  coeff = poly->coeff;
  group = poly->group;
  degree = poly->degree;
  if (ndim)
    {
    for (xpolt=xpol, expot=expo, post=pos, d=ndim; --d;)
      {
      *(++xpolt) = 1.0;
      *(++expot) = 0;
      }
    for (gexpot=gexpo, degreet=degree, g=poly->ngroup; g--;)
      *(gexpot++) = *(degreet++);
    if (gexpo[*group])
      gexpo[*group]--;
    }

/* The constant term is handled separately */
  val = *(coeff++);
  *(basis++) = 1.0;
  *expo = 1;
  *xpol = *pos;

/* Compute the rest of the polynom */
  for (t=poly->ncoeff; --t; )
    {
/*-- xpol[0] contains the current product of the x^n's */
    val += (*(basis++)=*xpol)**(coeff++);
/*-- A complex recursion between terms of the polynom speeds up computations */
/*-- Not too good for roundoff errors (prefer Horner's), but much easier for */
/*-- multivariate polynomials: this is why we use a long double accumulator */
    post = pos;
    groupt = group;
    expot = expo;
    xpolt = xpol;
    for (d=0; d<ndim; d++, groupt++)
      if (gexpo[*groupt]--)
        {
        ++*(expot++);
        xval = (*(xpolt--) *= *post);
        while (d--)
          *(xpolt--) = xval;
        break;
        }
      else
        {
        gexpo[*groupt] = *expot;
        *(expot++) = 0;
        *(xpolt++) = 1.0;
        post++;
        }
    }

  return (double)val;
  }


301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/****** poly_cfunc ************************************************************
PROTO   double poly_cfunc(polystruct *poly, double *pos)
PURPOSE Evaluate a multidimensional Chebyshev polynomial.
INPUT   polystruct pointer,
        pointer to the 1D array of input vector data.
OUTPUT  Polynom value.
NOTES   Values of the basis functions are updated in poly->basis.
AUTHOR  E. Bertin (IAP)
VERSION 29/01/2013
 ***/
double	poly_cfunc(polystruct *poly, double *pos)
  {
   double	pol[POLY_MAXDIM*(POLY_MAXDEGREE+1)],
	      	*polt, *post, *basis, *coeff, xval;
   long double	val;
   int		expo[POLY_MAXDIM+1], gexpo[POLY_MAXDIM+1];
   int	       	*expot, *degree,*degreet, *group,*groupt, *gexpot,
			d,d2,g,t, ndim;

/* Prepare the vectors and counters */
  ndim = poly->ndim;
  basis = poly->basis;
  coeff = poly->coeff;
  group = poly->group;
  degree = poly->degree;
  if (ndim)
    {
    for (groupt=group, expot=expo, post=pos, d=0; d<ndim; d++)
      {
      *(expot++) = 0;
      polt = pol + d*(POLY_MAXDEGREE+1);
      *(polt++) = 1.0;
      *(polt++) = xval = *(post++);
      for (d2 = degree[*(groupt++)]; --d2 > 0; polt++)
        *polt = 2.0*xval**(polt-1) - *(polt-2);
      }
    for (gexpot=gexpo, degreet=degree, g=poly->ngroup; g--;)
      *(gexpot++) = *(degreet++);
    if (gexpo[*group])
      gexpo[*group]--;
    }

/* The constant term is handled separately */
  val = *(coeff++);
  *(basis++) = 1.0;
  *expo = 1;

/* Compute the rest of the polynom */
  for (t=poly->ncoeff; --t; )
    {
    polt = pol;
    expot = expo;
/*-- xval contains the current product of the polynomials */
    xval = 1.0;
    for (d=ndim; d--; polt += POLY_MAXDEGREE+1)
      xval *= polt[*(expot++)];
    val += (*(basis++)=xval)**(coeff++);
/*-- A complex recursion between terms of the polynom speeds up computations */
/*-- Not too good for roundoff errors (prefer Horner's), but much easier for */
/*-- multivariate polynomials: this is why we use a long double accumulator */
    expot = expo;
    groupt = group;
    for (d=0; d<ndim; d++, groupt++)
      if (gexpo[*groupt]--)
        {
        ++*(expot++);
        break;
        }
      else
        {
        gexpo[*groupt] = *expot;
        *(expot++) = 0;
        }
    }

  return (double)val;
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
380
/****** poly_fit *************************************************************
381
382
PROTO   int poly_fit(polystruct *poly, double *x, double *y, double *w,
        int ndata, double *extbasis, double regul)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
383
384
385
386
387
388
389
PURPOSE Least-Square fit of a multidimensional polynom to weighted data.
INPUT   polystruct pointer,
        pointer to the (pseudo)2D array of inputs to basis functions,
        pointer to the 1D array of data values,
        pointer to the 1D array of data weights,
        number of data points,
        pointer to a (pseudo)2D array of computed basis function values.
390
	Tikhonov regularization parameter (0 = no regularization).
Emmanuel Bertin's avatar
Emmanuel Bertin committed
391
392
393
394
395
OUTPUT  Chi2 of the fit.
NOTES   If different from NULL, extbasis can be provided to store the
        values of the basis functions. If x==NULL and extbasis!=NULL, the
        precomputed basis functions stored in extbasis are used (which saves
        CPU). If w is NULL, all points are given identical weight.
396
397
AUTHOR  E. Bertin (IAP)
VERSION 20/11/2012
Emmanuel Bertin's avatar
Emmanuel Bertin committed
398
 ***/
399
400
int	poly_fit(polystruct *poly, double *x, double *y, double *w, int ndata,
		double *extbasis, double regul)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
401
402
403
404
405
406
  {
   void	qerror(char *msg1, char *msg2);
   double	/*offset[POLY_MAXDIM],*/x2[POLY_MAXDIM],
		*alpha,*alphat, *beta,*betat, *basis,*basis1,*basis2, *coeff,
		*extbasist,*xt,
		val,wval,yval;
407
   int		ncoeff, ndim, matsize, info,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
		d,i,j,n;

  if (!x && !extbasis)
    qerror("*Internal Error*: One of x or extbasis should be "
	"different from NULL\nin ", "poly_func()");
  ncoeff = poly->ncoeff;
  ndim = poly->ndim;
  matsize = ncoeff*ncoeff;
  basis = poly->basis;
  extbasist = extbasis;
  QCALLOC(alpha, double, matsize);
  QCALLOC(beta, double, ncoeff);

/* Subtract an average offset to maintain precision (droped for now ) */
/*
  if (x)
    {
    for (d=0; d<ndim; d++)
      offset[d] = 0.0;
    xt = x;
    for (n=ndata; n--;)
      for (d=0; d<ndim; d++)
        offset[d] += *(xt++);
    for (d=0; d<ndim; d++)
      offset[d] /= (double)ndata;    
    }
*/ 
/* Build the covariance matrix */
  xt = x;
  for (n=ndata; n--;)
    {
    if (x)
      {
/*---- If x!=NULL, compute the basis functions */
      for (d=0; d<ndim; d++)
        x2[d] = *(xt++)/* - offset[d]*/;     
      poly_func(poly, x2);
/*---- If, in addition, extbasis is provided, then fill it */
      if (extbasis)
        for (basis1=basis,j=ncoeff; j--;)
          *(extbasist++) = *(basis1++);
      }
    else
/*---- If x==NULL, then rely on pre-computed basis functions */
      for (basis1=basis,j=ncoeff; j--;)
        *(basis1++) = *(extbasist++);

    basis1 = basis;
    wval = w? *(w++) : 1.0;
    yval = *(y++);
    betat = beta;
    alphat = alpha;
    for (j=ncoeff; j--;)
      {
      val = *(basis1++)*wval;
      *(betat++) += val*yval;
      for (basis2=basis,i=ncoeff; i--;)
        *(alphat++) += val**(basis2++);
      }
    }

469
470
471
472
473
  if (regul>POLY_TINY)
/*-- Simple Tikhonov regularization */
    for (i=0; i<ncoeff; i++)
      alpha[i*(ncoeff+1)] += regul;

Emmanuel Bertin's avatar
Emmanuel Bertin committed
474
/* Solve the system */
475
  info = poly_solve(alpha,beta,ncoeff);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
476
477
478
479
480
481
482
483
484
485
486
487
488

  free(alpha);

/* Now fill the coeff array with the result of the fit */
  betat = beta;
  coeff = poly->coeff;
  for (j=ncoeff; j--;)
    *(coeff++) = *(betat++);
/*
  poly_addcste(poly, offset);
*/
  free(beta);

489
  return info;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
490
491
492
493
494
495
496
497
498
499
500
501
502
  }


/****** poly_addcste *********************************************************
PROTO   void poly_addcste(polystruct *poly, double *cste)
PURPOSE Modify matrix coefficients to mimick the effect of adding a cst to
	the input of a polynomial.
INPUT   Pointer to the polynomial structure,
        Pointer to the vector of cst.
OUTPUT  -.
NOTES   Requires quadruple-precision. **For the time beeing, this function
	returns completely wrong results!!**
AUTHOR  E. Bertin (IAP)
503
VERSION 05/10/2010
Emmanuel Bertin's avatar
Emmanuel Bertin committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
 ***/
void	poly_addcste(polystruct *poly, double *cste)
  {
   long double	*acoeff;
   double	*coeff,*mcoeff,*mcoefft,
		val;
   int		*mpowers,*powers,*powerst,*powerst2,
		i,j,n,p, denum, flag, maxdegree, ncoeff, ndim;

  ncoeff = poly->ncoeff;
  ndim = poly->ndim;
  maxdegree = 0;
  for (j=0; j<poly->ngroup; j++)
    if (maxdegree < poly->degree[j])
      maxdegree = poly->degree[j];
  maxdegree++;		/* Actually we need maxdegree+1 terms */
  QCALLOC(acoeff, long double, ncoeff);
  QCALLOC(mcoeff, double, ndim*maxdegree);
  QCALLOC(mpowers, int, ndim);
  mcoefft = mcoeff;		/* To avoid gcc -Wall warnings */
  powerst = powers = poly_powers(poly);
  coeff = poly->coeff;
  for (i=0; i<ncoeff; i++)
    {
    for (j=0; j<ndim; j++)
      {
      mpowers[j] = n = *(powerst++);
      mcoefft = mcoeff+j*maxdegree+n;
      denum = 1;
      val = 1.0;
      for (p=n+1; p--;)
        {
        *(mcoefft--) = val;
        val *= (cste[j]*(n--))/(denum++);	/* This is C_n^p X^(n-p) */
        }
      }
/*-- Update all valid coefficients */
    powerst2 = powers;
    for (p=0; p<ncoeff; p++)
      {
/*---- Check that this combination of powers is included in the series above */
      flag = 0;
      for (j=0; j<ndim; j++)
        if (mpowers[j] < powerst2[j])
	  {
          flag = 1;
          powerst2 += ndim;
          break;
          }
      if (flag == 1)
        continue;
      val = 1.0;
      mcoefft = mcoeff;
      for (j=ndim; j--; mcoefft += maxdegree)
        val *= mcoefft[*(powerst2++)];
      acoeff[i] += val*coeff[p];
      }
    }

/* Add the new coefficients to the previous ones */

  for (i=0; i<ncoeff; i++)
    coeff[i] = (double)acoeff[i];

  free(acoeff);
  free(mcoeff);
  free(mpowers);
  free(powers);

  return;
  }

576

Emmanuel Bertin's avatar
Emmanuel Bertin committed
577
/****** poly_solve ************************************************************
578
PROTO   int poly_solve(double *a, double *b, int n)
579
PURPOSE Solve a system of linear equations, using Cholesky decomposition.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
580
581
582
INPUT   Pointer to the (pseudo 2D) matrix of coefficients,
        pointer to the 1D column vector,
        matrix size.
583
OUTPUT  0 if solution OK, !=0 otherwise (e.g., singular matrix).
Emmanuel Bertin's avatar
Emmanuel Bertin committed
584
NOTES   -.
585
586
AUTHOR  E. Bertin (IAP)
VERSION 20/11/2012
Emmanuel Bertin's avatar
Emmanuel Bertin committed
587
 ***/
588
int	poly_solve(double *a, double *b, int n)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
589
  {
590
#if defined(HAVE_LAPACKE)
591
  return LAPACKE_dposv(LAPACK_COL_MAJOR, 'L', n, 1, a, n, b, n);
592
#elif defined(HAVE_ATLAS)
593
  return clapack_dposv(CblasRowMajor, CblasUpper, n, 1, a, n, b, n);
594
#else
595
  return cholsolve(a,b,n);
596
#endif
Emmanuel Bertin's avatar
Emmanuel Bertin committed
597
598
  }

599

Emmanuel Bertin's avatar
Emmanuel Bertin committed
600
/****** cholsolve *************************************************************
601
PROTO	void cholsolve(double *a, double *b, int n)
602
603
604
605
606
607
608
609
610
PURPOSE	Solve a system of linear equations, using Cholesky decomposition.
INPUT	Pointer to the (pseudo 2D) matrix of coefficients,
	pointer to the 1D column vector,
 	matrix size.
OUTPUT	-1 if the matrix is not positive-definite, 0 otherwise.
NOTES	Based on algorithm described in Numerical Recipes, 2nd ed. (Chap 2.9).
	The matrix of coefficients must be symmetric and positive definite.
AUTHOR	E. Bertin (IAP)
VERSION	10/10/2010
Emmanuel Bertin's avatar
Emmanuel Bertin committed
611
612
613
614
615
616
617
618
619
620
621
622
623
 ***/
int	cholsolve(double *a, double *b, int n)
  {
   double	*p, *x, sum;
   int		i,j,k;

/* Allocate memory to store the diagonal elements */
  QMALLOC(p, double, n);

/* Cholesky decomposition */
  for (i=0; i<n; i++)
    for (j=i; j<n; j++)
      {
624
625
      sum = a[i*n+j];
      for (k=i; k--;)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
        sum -= a[i*n+k]*a[j*n+k];
      if (i==j)
        {
        if (sum <= 0.0)
	  {
          free(p);
          return -1;
          }
        p[i] = sqrt(sum);
        }
      else
        a[j*n+i] = sum/p[i];
      }

/* Solve the system */
  x = b;		/* Just to save memory:  the solution replaces b */
  for (i=0; i<n; i++)
    {
644
    for (sum=b[i],k=i; k--;)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
645
646
647
648
      sum -= a[i*n+k]*x[k];
    x[i] = sum/p[i];
    }

649
  for (i=n; i--;)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
650
    {
651
652
    sum = x[i];
    for (k=i; ++k<n;)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
      sum -= a[k*n+i]*x[k];
    x[i] = sum/p[i];
    }

  free(p);

  return 0;
  }


/****** poly_powers ***********************************************************
PROTO   int *poly_powers(polystruct *poly)
PURPOSE	Return an array of powers of polynom terms
INPUT   polystruct pointer,
OUTPUT  Pointer to an array of polynom powers (int *), (ncoeff*ndim numbers).
NOTES   The returned pointer is mallocated.
AUTHOR  E. Bertin (IAP)
VERSION 23/10/2003
 ***/
int	*poly_powers(polystruct *poly)
  {
   int		expo[POLY_MAXDIM+1], gexpo[POLY_MAXDIM+1];
   int	       	*expot, *degree,*degreet, *group,*groupt, *gexpot,
		*powers, *powerst,
		d,g,t, ndim;

/* Prepare the vectors and counters */
  ndim = poly->ndim;
  group = poly->group;
  degree = poly->degree;
  QMALLOC(powers, int, ndim*poly->ncoeff);
  if (ndim)
    {
    for (expot=expo, d=ndim; --d;)
      *(++expot) = 0;
    for (gexpot=gexpo, degreet=degree, g=poly->ngroup; g--;)
      *(gexpot++) = *(degreet++);
    if (gexpo[*group])
      gexpo[*group]--;
    }

/* The constant term is handled separately */
  powerst = powers;
  for (d=0; d<ndim; d++)
    *(powerst++) = 0;
  *expo = 1;

/* Compute the rest of the polynom */
  for (t=poly->ncoeff; --t; )
    {
    for (d=0; d<ndim; d++)
      *(powerst++) = expo[d];
/*-- A complex recursion between terms of the polynom speeds up computations */
    groupt = group;
    expot = expo;
    for (d=0; d<ndim; d++, groupt++)
      if (gexpo[*groupt]--)
        {
        ++*(expot++);
        break;
        }
      else
        {
        gexpo[*groupt] = *expot;
        *(expot++) = 0;
        }
    }

  return powers;
  }

724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901

/****** poly_initortho ********************************************************
PROTO   void poly_initortho(polystruct *poly, double *data, int ndata)
PURPOSE Compute orthonormalization and de-orthonormalization matrices for a
	polynomial basis on a data set.
INPUT   polystruct pointer,
        pointer to the 1D array of input vector data,
	number of data vectors.
OUTPUT  -.
NOTES   -.
AUTHOR  E. Bertin (IAP)
VERSION 10/07/2012
 ***/
void	poly_initortho(polystruct *poly, double *data, int ndata)
  {
   double	*basis, *coeff, *invec,*invect0,*invect,*invect02,*invect2,
		*rdiag, *deortho,
		scale,s, dval;
   int		c,i,j,m,n, ndmc, ndim,ncoeff;

/* Prepare the vectors and counters */
  ndim = poly->ndim;
  ncoeff = poly->ncoeff;
  basis = poly->basis;
  coeff = poly->coeff;

/* Allocate memory for orthonormalization matrix and vector */
  QCALLOC(poly->deorthomat, double, ncoeff*ncoeff);
  QMALLOC(poly->orthobasis, double, poly->ncoeff);
  QMALLOC(rdiag, double, ncoeff);

/* Do a QR decomposition of input vector set */
/* Vectors are stored as rows to speed up the Householder transformation */
  n = ncoeff;
  m = ndata;
  invec = data;
  for (c=0; c<ncoeff; c++)
    {
    ndmc = ndata - c;
    scale = 0.0;
    invect = invect0 = data + c*(ndata+1);
    for (i=ndmc; i--; invect++)
      scale = sqrt(scale*scale + *invect**invect);
    if (scale > POLY_TINY)
      {
      if (*invect0 < 0.0)
        scale = -scale;
      invect = invect0;
      for (i=ndmc; i--;)
        *(invect++) /= scale;
      *invect0 += 1.0;
      invect02 = invect0 + ndata;
      for (j=ncoeff-c; --j; invect02+=ndata)
        {
        s = 0.0;
        invect = invect0;
        invect2 = invect02;
        for (i=ndmc; i--;)
          s += *(invect++)**(invect2++);
        s /= -*invect0;
        invect = invect0;
        invect2 = invect02;
        for (i=ndmc; i--;)
          *(invect2++) += s**(invect++);
        }
      }
    rdiag[c] = -scale;
    }

/* Convert to deorthonormalization matrix */
  deortho = poly->deorthomat;
  for (j=0; j<ncoeff; j++)
    for (i=0; i<ncoeff; i++)
      deortho[j*ncoeff+i] = i<j? data[j*ndata+i] : (i==j?rdiag[i] : 0.0);

  free(rdiag);

/* Compute the "unorthonormalization" matrix */
  QMEMCPY(poly->deorthomat, poly->orthomat, double, ncoeff*ncoeff);
#if defined(HAVE_LAPACKE)
  LAPACKE_dtrtri(LAPACK_ROW_MAJOR, 'L', 'N', ncoeff,poly->orthomat,ncoeff);
#elif defined(HAVE_ATLAS)
  clapack_dtrtri(CblasRowMajor, CblasLower, CblasNonUnit, ncoeff,
	poly->orthomat, ncoeff);
#else
  qerror("*Internal Error*: no routine available", " for triangular inverse");
#endif

/* Transpose orthonormalization matrix to speed up later use */
  deortho = poly->deorthomat;
  for (j=0; j<ncoeff; j++)
    for (i=j; i<ncoeff; i++)
      {
      dval = deortho[j*ncoeff+i];
      deortho[j*ncoeff+i] = deortho[i*ncoeff+j];
      deortho[i*ncoeff+j] = dval;
      }

  return;
  }


/****** poly_ortho ************************************************************
PROTO   double *poly_ortho(polystruct *poly, double *datain, double *dataout)
PURPOSE Apply orthonormalization to the poly basis vector ("ket>").
INPUT   polystruct pointer,
	pointer to the input vector,
	pointer to the output vector.
OUTPUT  Pointer to poly->orthobasis, or poly->basis if no ortho. matrix exists.
NOTES   The poly->basis vector must have been updated with poly_func() first.
AUTHOR  E. Bertin (IAP)
VERSION 04/11/2008
 ***/
double	*poly_ortho(polystruct *poly, double *datain, double *dataout)
  {
   double	*omat,*basis,*obasis,
		dval;
   int		i,j, ncoeff;

  if (!poly->orthomat)
    return datain;

  ncoeff = poly->ncoeff;

/* Compute matrix product */
  omat = poly->orthomat;
  obasis = dataout;
  for (j=ncoeff; j--;)
    {
    basis = datain;
    dval = 0.0;
    for (i=ncoeff; i--;)
      dval += *(omat++)**(basis++);
    *(obasis++) = dval;
    }

  return dataout;
  }


/****** poly_deortho **********************************************************
PROTO   void poly_deortho(polystruct *poly, double *datain, double *dataout)
PURPOSE Apply deorthonormalization to the poly basis component vector("<bra|").
INPUT   polystruct pointer,
	pointer to the input vector,
	pointer to the output vector.
OUTPUT  Pointer to poly->basis.
NOTES   -.
AUTHOR  E. Bertin (IAP)
VERSION 04/11/2008
 ***/
double	*poly_deortho(polystruct *poly, double *datain, double *dataout)
  {
   double	*omat,*basis,*obasis,
		dval;
   int		i,j, ncoeff;

  if (!poly->deorthomat)
    return datain;

  ncoeff = poly->ncoeff;

/* Compute matrix product */
  omat = poly->deorthomat;
  basis = dataout;
  for (j=ncoeff; j--;)
    {
    obasis = datain;
    dval = 0.0;
    for (i=ncoeff; i--;)
      dval += *(omat++)**(obasis++);
    *(basis++) = dval;
    }

  return dataout;
  }