profit.c 92.8 KB
Newer Older
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1
2
3
4
5
6
7
8
9
10
11
 /*
 				profit.c

*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
*	Part of:	SExtractor
*
*	Authors:	E.BERTIN (IAP)
*
*	Contents:	Fit an arbitrary profile combination to a detection.
*
12
*	Last modify:	09/10/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
13
14
15
16
17
18
19
20
*
*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/

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

21
22
23
24
#ifndef HAVE_MATHIMF_H
#define _GNU_SOURCE
#endif

25
#include	<math.h>
Emmanuel Bertin's avatar
Emmanuel Bertin committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>

#include	"define.h"
#include	"globals.h"
#include	"prefs.h"
#include	"fits/fitscat.h"
#include	"levmar/lm.h"
#include	"fft.h"
#include	"fitswcs.h"
#include	"check.h"
#include	"pattern.h"
#include	"psf.h"
#include	"profit.h"

42
43
static double	prof_gammainc(double x, double a),
		prof_gamma(double x);
44
45
static float	prof_interpolate(profstruct *prof, float *posin);
static float	interpolate_pix(float *posin, float *pix, int *naxisn,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
46
47
		interpenum interptype);

48
static void	make_kernel(float pos, float *kernel, interpenum interptype);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
49
50
51

/*------------------------------- variables ---------------------------------*/

Emmanuel Bertin's avatar
Emmanuel Bertin committed
52
const char	profname[][32]={"background offset", "Sersic spheroid",
Emmanuel Bertin's avatar
Emmanuel Bertin committed
53
54
55
56
		"De Vaucouleurs spheroid", "exponential disk", "spiral arms",
		"bar", "inner ring", "outer ring", "tabulated model",
		""};

Emmanuel Bertin's avatar
Emmanuel Bertin committed
57
58
59
60
61
62
63
64
65
66
67
const int	interp_kernwidth[5]={1,2,4,6,8};

const int	flux_flag[PARAM_NPARAM] = {0,0,0,
					1,0,0,0,0,
					1,0,0,0,
					1,0,0,0,0,0,0,0,
					1,0,0,
					1,0,0,
					1,0,0
					};

Emmanuel Bertin's avatar
Emmanuel Bertin committed
68
69
70
71
72
73
74
75
76
77
78
79
80
int theniter, the_gal;
/* "Local" global variables; it seems dirty but it simplifies a lot */
/* interfacing to the LM routines */
static picstruct	*the_field, *the_wfield;
profitstruct		*theprofit;

/****** profit_init ***********************************************************
PROTO	profitstruct profit_init(psfstruct *psf)
PURPOSE	Allocate and initialize a new profile-fitting structure.
INPUT	Pointer to PSF structure.
OUTPUT	A pointer to an allocated profit structure.
NOTES	-.
AUTHOR	E. Bertin (IAP)
81
VERSION	07/09/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
 ***/
profitstruct	*profit_init(psfstruct *psf)
  {
   profitstruct		*profit;
   int			p, nprof,
			backflag, spheroidflag, diskflag, barflag, armsflag;

  QCALLOC(profit, profitstruct, 1);
  profit->psf = psf;
  profit->psfdft = NULL;

  profit->nparam = 0;
  QMALLOC(profit->prof, profstruct *, PROF_NPROF);
  backflag = spheroidflag = diskflag = barflag = armsflag = 0;
  nprof = 0;
  for (p=0; p<PROF_NPROF; p++)
    if (!backflag && FLAG(obj2.prof_offset_flux))
      {
      profit->prof[p] = prof_init(profit, PROF_BACK);
      backflag = 1;
      nprof++;
      }
    else if (!spheroidflag && FLAG(obj2.prof_spheroid_flux))
      {
      profit->prof[p] = prof_init(profit,
	FLAG(obj2.prof_spheroid_sersicn)? PROF_SERSIC : PROF_DEVAUCOULEURS);
      spheroidflag = 1;
      nprof++;
      }
    else if (!diskflag && FLAG(obj2.prof_disk_flux))
      {
      profit->prof[p] = prof_init(profit, PROF_EXPONENTIAL);
      diskflag = 1;
      nprof++;
      }
    else if (diskflag && !barflag && FLAG(obj2.prof_bar_flux))
      {
      profit->prof[p] = prof_init(profit, PROF_BAR);
      barflag = 1;
      nprof++;
      }
    else if (barflag && !armsflag && FLAG(obj2.prof_arms_flux))
      {
      profit->prof[p] = prof_init(profit, PROF_ARMS);
      armsflag = 1;
      nprof++;
      }

130
  QMALLOC16(profit->covar, float, profit->nparam*profit->nparam);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
131
  profit->nprof = nprof;
132
  profit->fluxfac = 1.0;	/* Default */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

  return profit;
  }  


/****** profit_end ************************************************************
PROTO	void prof_end(profstruct *prof)
PURPOSE	End (deallocate) a profile-fitting structure.
INPUT	Prof structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	26/04/2008
 ***/
void	profit_end(profitstruct *profit)
  {
   int	p;

  for (p=0; p<profit->nprof; p++)
    prof_end(profit->prof[p]);
  free(profit->prof);
  free(profit->covar);
  free(profit->psfdft);
  free(profit);

  return;
  }


/****** profit_fit ************************************************************
PROTO	void profit_fit(profitstruct *profit, picstruct *field,
		picstruct *wfield, objstruct *obj, obj2struct *obj2)
PURPOSE	Fit profile(s) convolved with the PSF to a detected object.
INPUT	Array of profile structures,
	Number of profiles,
	Pointer to the profile-fitting structure,
	Pointer to the field,
	Pointer to the field weight,
	Pointer to the obj.
OUTPUT	Pointer to an allocated fit structure (containing details about the
	fit).
NOTES	It is a modified version of the lm_minimize() of lmfit.
AUTHOR	E. Bertin (IAP)
176
VERSION	09/10/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
177
178
179
180
181
 ***/
void	profit_fit(profitstruct *profit,
		picstruct *field, picstruct *wfield,
		objstruct *obj, obj2struct *obj2)
  {
182
    profitstruct	pprofit;
183
    profitstruct	hdprofit;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
184
185
186
    patternstruct *pattern;
    psfstruct		*psf;
    checkstruct		*check;
187
    double		emx2,emy2,emxy, a , cp,sp, cn, bn, n;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
188
189
190
191
192
    float		**list,
			*cov,
			psf_fwhm, dchi2, err;
    int			*index,
			i,j,p, nparam, nparam2, ncomp, nprof;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
193
194

  nparam = profit->nparam;
195
  nparam2 = nparam*nparam;
196
  nprof = profit->nprof;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
197
198
199
200
201
202
203
  if (profit->psfdft)
    {
    QFREE(profit->psfdft);
    }

  psf = profit->psf;
  profit->pixstep = psf->pixstep;
204
  obj2->prof_flag = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
205
206

/* Create pixmaps at image resolution */
207
208
  profit->ix = (int)(obj->mx + 0.49999);/* internal convention: 1st pix = 0 */
  profit->iy = (int)(obj->my + 0.49999);/* internal convention: 1st pix = 0 */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
209
210
211
212
213
214
215
216
217
  psf_fwhm = psf->masksize[0]*psf->pixstep;
  profit->objnaxisn[0] = (((int)((obj->xmax-obj->xmin+1) + psf_fwhm + 0.499)
		*1.2)/2)*2 + 1;
  profit->objnaxisn[1] = (((int)((obj->ymax-obj->ymin+1) + psf_fwhm + 0.499)
		*1.2)/2)*2 + 1;
  if (profit->objnaxisn[1]<profit->objnaxisn[0])
    profit->objnaxisn[1] = profit->objnaxisn[0];
  else
    profit->objnaxisn[0] = profit->objnaxisn[1];
218
219
  if (profit->objnaxisn[0]>PROFIT_MAXOBJSIZE)
    {
220
221
222
223
    profit->subsamp = ceil((float)profit->objnaxisn[0]/PROFIT_MAXOBJSIZE);
//    profit->fluxfac *= profit->subsamp*profit->subsamp;
    profit->objnaxisn[1] = (profit->objnaxisn[0] /= (int)profit->subsamp);
//    profit->pixstep *= profit->subsamp;
224
225
226
    obj2->prof_flag |= PROFLAG_OBJSUB;
    }
  else
227
    profit->subsamp = 1.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
228
229
230
231
232
233
234
235

/* Use (dirty) global variables to interface with lmfit */
  the_field = field;
  the_wfield = wfield;
  theprofit = profit;
  profit->obj = obj;
  profit->obj2 = obj2;

236
237
238
  QMALLOC16(profit->objpix, PIXTYPE, profit->objnaxisn[0]*profit->objnaxisn[1]);
  QMALLOC16(profit->objweight, PIXTYPE,profit->objnaxisn[0]*profit->objnaxisn[1]);
  QMALLOC16(profit->lmodpix, PIXTYPE, profit->objnaxisn[0]*profit->objnaxisn[1]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
239
  profit->nresi = profit_copyobjpix(profit, field, wfield);
240
/* Check if the number of constraints exceeds the number of free parameters */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
241
242
  if (profit->nresi < nparam)
    {
243
244
245
    if (FLAG(obj2.prof_vector))
      for (p=0; p<nparam; p++)
        obj2->prof_vector[p] = 0.0;
246
247
248
249
250
251
    if (FLAG(obj2.prof_errvector))
      for (p=0; p<nparam; p++)
        obj2->prof_errvector[p] = 0.0;
    if (FLAG(obj2.prof_errmatrix))
      for (p=0; p<nparam2; p++)
        obj2->prof_errmatrix[p] = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
252
    obj2->prof_niter = 0;
253
    obj2->prof_flag |= PROFLAG_NOTCONST;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
254
255
256
    return;
    }

257
  QMALLOC16(profit->resi, float, profit->nresi);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
258
259
260

/* Create pixmap at PSF resolution */
  profit->modnaxisn[0] =
261
262
	((int)(profit->objnaxisn[0]*profit->subsamp/profit->pixstep
		+0.4999)/2+1)*2; 
Emmanuel Bertin's avatar
Emmanuel Bertin committed
263
  profit->modnaxisn[1] =
264
265
	((int)(profit->objnaxisn[1]*profit->subsamp/profit->pixstep
		+0.4999)/2+1)*2; 
Emmanuel Bertin's avatar
Emmanuel Bertin committed
266
267
268
269
  if (profit->modnaxisn[1] < profit->modnaxisn[0])
    profit->modnaxisn[1] = profit->modnaxisn[0];
  else
    profit->modnaxisn[0] = profit->modnaxisn[1];
270
271
272
273
274
275
  if (profit->modnaxisn[0]>PROFIT_MAXMODSIZE)
    {
    profit->pixstep = (double)profit->modnaxisn[0] / PROFIT_MAXMODSIZE;
    profit->modnaxisn[0] = profit->modnaxisn[1] = PROFIT_MAXMODSIZE;
    obj2->prof_flag |= PROFLAG_MODSUB;
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
276
277

/* Allocate memory for the complete model */
278
  QMALLOC16(profit->modpix, float, profit->modnaxisn[0]*profit->modnaxisn[1]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
279
  memset(profit->modpix, 0, profit->modnaxisn[0]*profit->modnaxisn[1]*sizeof(float));
280
  QMALLOC16(profit->psfpix, float, profit->modnaxisn[0]*profit->modnaxisn[1]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
281
/* Allocate memory for the partial model */
282
  QMALLOC16(profit->pmodpix, float, profit->modnaxisn[0]*profit->modnaxisn[1]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
283
284
285
286
287
288
289
290
/* Compute the local PSF */
  profit_psf(profit);

/* Set initial guesses and boundaries */
  profit->sigma = obj->sigbkg;

  profit_resetparams(profit);

291
//the_gal++;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
292
293

/* Actual minimisation */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
294
  fft_reset();
295
the_gal++;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
296
  profit->niter = profit_minimize(profit, PROFIT_MAXITER);
297
  profit_residuals(profit,field,wfield, 10.0, profit->param,profit->resi);
298

Emmanuel Bertin's avatar
Emmanuel Bertin committed
299
300
301
302
303
304
305
306
307
308
309
310
/* Convert covariance matrix to bound space */
  profit_covarunboundtobound(profit);
  for (p=0; p<nparam; p++)
    profit->paramerr[p]= sqrt(profit->covar[p*(nparam+1)]);

/* Equate param and paraminit vectors to avoid confusion later on */
  for (p=0; p<profit->nparam; p++)
    profit->param[p] = profit->paraminit[p];

/* CHECK-Images */
  if ((check = prefs.check[CHECK_SUBPROFILES]))
    {
311
    profit_residuals(profit,field,wfield, 0.0, profit->param,profit->resi);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
312
313
314
315
316
    addcheck(check, profit->lmodpix, profit->objnaxisn[0],profit->objnaxisn[1],
		profit->ix,profit->iy, -1.0);
    }
  if ((check = prefs.check[CHECK_PROFILES]))
    {
317
    profit_residuals(profit,field,wfield, 0.0, profit->param,profit->resi);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
318
319
320
    addcheck(check, profit->lmodpix, profit->objnaxisn[0],profit->objnaxisn[1],
		profit->ix,profit->iy, 1.0);
    }
321

Emmanuel Bertin's avatar
Emmanuel Bertin committed
322
323
324
325
326
327
328
329
330
331
332
/* Fill measurement parameters */
  if (FLAG(obj2.prof_vector))
    {
    for (p=0; p<nparam; p++)
      obj2->prof_vector[p]= profit->param[p];
    }
  if (FLAG(obj2.prof_errvector))
    {
    for (p=0; p<nparam; p++)
      obj2->prof_errvector[p]= profit->paramerr[p];
    }
333
334
335
336
337
  if (FLAG(obj2.prof_errmatrix))
    {
    for (p=0; p<nparam2; p++)
      obj2->prof_errmatrix[p]= profit->covar[p];
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
338
339
340

  obj2->prof_niter = profit->niter;
  obj2->flux_prof = profit->flux;
341
342
343
  if (FLAG(obj2.fluxerr_prof))
    {
    err = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
344
345
346
347
348
349
350
351
352
353
354
    cov = profit->covar;
    index = profit->paramindex;
    list = profit->paramlist;
    for (i=0; i<PARAM_NPARAM; i++)
      if (flux_flag[i] && list[i])
        {
        cov = profit->covar + nparam*index[i];
        for (j=0; j<PARAM_NPARAM; j++)
          if (flux_flag[j] && list[j])
            err += cov[index[j]];
        }
355
356
357
    obj2->fluxerr_prof = err>0.0? sqrt(err): 0.0;
    }

358
359
360
  obj2->prof_chi2 = (profit->nresi > profit->nparam)?
		profit->chi2 / (profit->nresi - profit->nparam) : 0.0;

Emmanuel Bertin's avatar
Emmanuel Bertin committed
361
362
363
364
365
  if (FLAG(obj2.x_prof))
    {
    i = profit->paramindex[PARAM_X];
    j = profit->paramindex[PARAM_Y];
/*-- Model coordinates follow the FITS convention (first pixel at 1,1) */
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
    if (profit->paramlist[PARAM_X])
      {
      obj2->x_prof = profit->ix + *profit->paramlist[PARAM_X] + 1.0;
      obj2->poserrmx2_prof = emx2 = profit->covar[i*(nparam+1)];
      }
    else
      emx2 = 0.0;
    if (profit->paramlist[PARAM_Y])
      {
      obj2->y_prof = profit->iy + *profit->paramlist[PARAM_Y] + 1.0;
      obj2->poserrmy2_prof = emy2 = profit->covar[j*(nparam+1)];
      }
    else
      emy2 = 0.0;
    if (profit->paramlist[PARAM_X] && profit->paramlist[PARAM_Y])
      obj2->poserrmxy_prof = emxy = profit->covar[i+j*nparam];
    else
      emxy = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401

/*-- Error ellipse parameters */
    if (FLAG(obj2.poserra_prof))
      {
       double	pmx2,pmy2,temp,theta;

      if (fabs(temp=emx2-emy2) > 0.0)
        theta = atan2(2.0 * emxy,temp) / 2.0;
      else
        theta = PI/4.0;

      temp = sqrt(0.25*temp*temp+ emxy*emxy);
      pmy2 = pmx2 = 0.5*(emx2+emy2);
      pmx2+=temp;
      pmy2-=temp;

      obj2->poserra_prof = (float)sqrt(pmx2);
      obj2->poserrb_prof = (float)sqrt(pmy2);
402
      obj2->poserrtheta_prof = (float)(theta/DEG);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
403
404
405
406
407
408
409
410
411
412
413
414
      }

    if (FLAG(obj2.poserrcxx_prof))
      {
       double	temp;

      obj2->poserrcxx_prof = (float)(emy2/(temp=emx2*emy2-emxy*emxy));
      obj2->poserrcyy_prof = (float)(emx2/temp);
      obj2->poserrcxy_prof = (float)(-2*emxy/temp);
      }
    }

415
416
/* Do measurements on the rasterised model (shear and surface brightnesses) */
  if (FLAG(obj2.prof_mx2) || FLAG(obj2.peak_prof))
Emmanuel Bertin's avatar
Emmanuel Bertin committed
417
    {
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
     float	scalefac, imsizefac, flux, lost, sum, lostfluxfrac;

/*-- Allocate "high-definition" rasters only to make measurements */
    hdprofit.modnaxisn[0] = hdprofit.modnaxisn[1] = PROFIT_HIDEFRES;
/*-- Find best image size factor from fitting results */
    imsizefac = 2.0*profit_minradius(profit, PROFIT_REFFFAC)/profit->pixstep
	/ (float)profit->modnaxisn[0];
    if (imsizefac<0.01)
      imsizefac = 0.01;
    else if (imsizefac>100.0)
      imsizefac = 100.0;
    scalefac = (float)hdprofit.modnaxisn[0] / (float)profit->modnaxisn[0]
		/ imsizefac;
    hdprofit.pixstep = profit->pixstep / scalefac;
    hdprofit.fluxfac = scalefac*scalefac;
    QCALLOC(hdprofit.modpix, float,
	hdprofit.modnaxisn[0]*hdprofit.modnaxisn[1]*sizeof(float));
    QCALLOC(hdprofit.pmodpix, float,
	hdprofit.modnaxisn[0]*hdprofit.modnaxisn[1]*sizeof(float));

    lost = sum = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
439
    for (p=0; p<profit->nprof; p++)
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
      {
      sum += (flux = prof_add(profit->prof[p], &hdprofit));
      lost += flux*profit->prof[p]->lostfluxfrac;
      }
    lostfluxfrac = sum > 0.0? lost / sum : 0.0;

    if (FLAG(obj2.prof_mx2))
      profit_moments(&hdprofit, obj2);

    if (FLAG(obj2.peak_prof))
      profit_surface(&hdprofit, obj2, lostfluxfrac);

/*-- Free rasters */
    free(hdprofit.modpix);
    free(hdprofit.pmodpix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
455
456
    }

457
/* Spheroid */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
  if (FLAG(obj2.prof_spheroid_flux))
    {
    obj2->prof_spheroid_flux = *profit->paramlist[PARAM_SPHEROID_FLUX];
    obj2->prof_spheroid_fluxerr =
		profit->paramerr[profit->paramindex[PARAM_SPHEROID_FLUX]];
    obj2->prof_spheroid_reff = *profit->paramlist[PARAM_SPHEROID_REFF];
    obj2->prof_spheroid_refferr = 
		profit->paramerr[profit->paramindex[PARAM_SPHEROID_REFF]];
    obj2->prof_spheroid_aspect = *profit->paramlist[PARAM_SPHEROID_ASPECT];
    obj2->prof_spheroid_aspecterr = 
		profit->paramerr[profit->paramindex[PARAM_SPHEROID_ASPECT]];
    obj2->prof_spheroid_theta =
			fmod_m90_p90(*profit->paramlist[PARAM_SPHEROID_POSANG]);
    obj2->prof_spheroid_thetaerr = 
		profit->paramerr[profit->paramindex[PARAM_SPHEROID_POSANG]];
    if (FLAG(obj2.prof_spheroid_sersicn))
      {
      obj2->prof_spheroid_sersicn = *profit->paramlist[PARAM_SPHEROID_SERSICN];
      obj2->prof_spheroid_sersicnerr = 
		profit->paramerr[profit->paramindex[PARAM_SPHEROID_SERSICN]];
      }
479
480
481
482
483
    else
      obj2->prof_spheroid_sersicn = 4.0;
    if (FLAG(obj2.prof_spheroid_peak))
      {
      n = obj2->prof_spheroid_sersicn;
484
      bn = 2.0*n - 1.0/3.0 + 4.0/(405.0*n) + 46.0/(25515.0*n*n)
485
		+ 131.0/(1148175*n*n*n);	/* Ciotti & Bertin 1999 */
486
      cn = n * prof_gamma(2.0*n) * pow(bn, -2.0*n);
487
      obj2->prof_spheroid_peak = obj2->prof_spheroid_reff>0.0?
488
489
	obj2->prof_spheroid_flux * profit->pixstep*profit->pixstep
		/ (2.0 * PI * cn
490
		* obj2->prof_spheroid_reff*obj2->prof_spheroid_reff
491
		* obj2->prof_spheroid_aspect)
492
493
	: 0.0;
      if (FLAG(obj2.prof_spheroid_fluxeff))
494
495
496
        obj2->prof_spheroid_fluxeff = obj2->prof_spheroid_peak * exp(-bn);
      if (FLAG(obj2.prof_spheroid_fluxmean))
        obj2->prof_spheroid_fluxmean = obj2->prof_spheroid_peak * cn;
497
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    }

/* Disk */
  if (FLAG(obj2.prof_disk_flux))
    {
    obj2->prof_disk_flux = *profit->paramlist[PARAM_DISK_FLUX];
    obj2->prof_disk_fluxerr =
		profit->paramerr[profit->paramindex[PARAM_DISK_FLUX]];
    obj2->prof_disk_scale = *profit->paramlist[PARAM_DISK_SCALE];
    obj2->prof_disk_scaleerr =
		profit->paramerr[profit->paramindex[PARAM_DISK_SCALE]];
    obj2->prof_disk_aspect = *profit->paramlist[PARAM_DISK_ASPECT];
    obj2->prof_disk_aspecterr =
		profit->paramerr[profit->paramindex[PARAM_DISK_ASPECT]];
    obj2->prof_disk_theta = fmod_m90_p90(*profit->paramlist[PARAM_DISK_POSANG]);
    obj2->prof_disk_thetaerr =
		profit->paramerr[profit->paramindex[PARAM_DISK_POSANG]];
    if (FLAG(obj2.prof_disk_inclination))
      {
      obj2->prof_disk_inclination = acos(obj2->prof_disk_aspect) / DEG;
      if (FLAG(obj2.prof_disk_inclinationerr))
        {
        a = sqrt(1.0-obj2->prof_disk_aspect*obj2->prof_disk_aspect);
        obj2->prof_disk_inclinationerr = obj2->prof_disk_aspecterr
					/(a>0.1? a : 0.1)/DEG;
        }
      }

526
527
528
    if (FLAG(obj2.prof_disk_peak))
      {
      obj2->prof_disk_peak = obj2->prof_disk_scale>0.0?
529
	obj2->prof_disk_flux * profit->pixstep*profit->pixstep
530
531
532
533
	/ (2.0 * PI * obj2->prof_disk_scale*obj2->prof_disk_scale
		* obj2->prof_disk_aspect)
	: 0.0;
      if (FLAG(obj2.prof_disk_fluxeff))
534
535
536
        obj2->prof_disk_fluxeff = obj2->prof_disk_peak * 0.186682; /* e^-(b_n)*/
      if (FLAG(obj2.prof_disk_fluxmean))
        obj2->prof_disk_fluxmean = obj2->prof_disk_peak * 0.355007;/* b_n^(-2)*/
537
538
      }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
539
540
541
/* Disk pattern */
    if (prefs.pattern_flag)
      {
542
543
      profit_residuals(profit,field,wfield, PROFIT_DYNPARAM,
			profit->param,profit->resi);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
      pattern = pattern_init(profit, prefs.pattern_type,
		prefs.prof_disk_patternncomp);
      pattern_fit(pattern, profit);
      if (FLAG(obj2.prof_disk_patternspiral))
        obj2->prof_disk_patternspiral = pattern_spiral(pattern);
      if (FLAG(obj2.prof_disk_patternvector))
        {
        ncomp = pattern->size[2];
        for (p=0; p<ncomp; p++)
          obj2->prof_disk_patternvector[p] = (float)pattern->coeff[p];
        }
      if (FLAG(obj2.prof_disk_patternmodvector))
        {
        ncomp = pattern->ncomp*pattern->nfreq;
        for (p=0; p<ncomp; p++)
          obj2->prof_disk_patternmodvector[p] = (float)pattern->mcoeff[p];
        }
      if (FLAG(obj2.prof_disk_patternargvector))
        {
        ncomp = pattern->ncomp*pattern->nfreq;
        for (p=0; p<ncomp; p++)
          obj2->prof_disk_patternargvector[p] = (float)pattern->acoeff[p];
        }
      pattern_end(pattern);
      }

/* Bar */
    if (FLAG(obj2.prof_bar_flux))
      {
      obj2->prof_bar_flux = *profit->paramlist[PARAM_BAR_FLUX];
      obj2->prof_bar_fluxerr =
		profit->paramerr[profit->paramindex[PARAM_BAR_FLUX]];
      obj2->prof_bar_length = *profit->paramlist[PARAM_ARMS_START]
				**profit->paramlist[PARAM_DISK_SCALE];
      obj2->prof_bar_lengtherr = *profit->paramlist[PARAM_ARMS_START]
		  * profit->paramerr[profit->paramindex[PARAM_DISK_SCALE]]
		+ *profit->paramlist[PARAM_DISK_SCALE]
		  * profit->paramerr[profit->paramindex[PARAM_ARMS_START]];
      obj2->prof_bar_aspect = *profit->paramlist[PARAM_BAR_ASPECT];
      obj2->prof_bar_aspecterr =
		profit->paramerr[profit->paramindex[PARAM_BAR_ASPECT]];
      obj2->prof_bar_posang = 
			fmod_m90_p90(*profit->paramlist[PARAM_ARMS_POSANG]);
      obj2->prof_bar_posangerr =
		profit->paramerr[profit->paramindex[PARAM_ARMS_POSANG]];
      if (FLAG(obj2.prof_bar_theta))
        {
        cp = cos(obj2->prof_bar_posang*DEG);
        sp = sin(obj2->prof_bar_posang*DEG);
        a = obj2->prof_disk_aspect;
        obj2->prof_bar_theta = fmod_m90_p90(atan2(a*sp,cp)/DEG
				+ obj2->prof_disk_theta);
        obj2->prof_bar_thetaerr = obj2->prof_bar_posangerr*a/(cp*cp+a*a*sp*sp);
        }

/* Arms */
      if (FLAG(obj2.prof_arms_flux))
        {
        obj2->prof_arms_flux = *profit->paramlist[PARAM_ARMS_FLUX];
        obj2->prof_arms_fluxerr =
		profit->paramerr[profit->paramindex[PARAM_ARMS_FLUX]];
        obj2->prof_arms_pitch =
		fmod_m90_p90(*profit->paramlist[PARAM_ARMS_PITCH]);
        obj2->prof_arms_pitcherr =
		profit->paramerr[profit->paramindex[PARAM_ARMS_PITCH]];
        obj2->prof_arms_start = *profit->paramlist[PARAM_ARMS_START]
				**profit->paramlist[PARAM_DISK_SCALE];
        obj2->prof_arms_starterr = *profit->paramlist[PARAM_ARMS_START]
		  * profit->paramerr[profit->paramindex[PARAM_DISK_SCALE]]
		+ *profit->paramlist[PARAM_DISK_SCALE]
		  * profit->paramerr[profit->paramindex[PARAM_ARMS_START]];
        obj2->prof_arms_quadfrac = *profit->paramlist[PARAM_ARMS_QUADFRAC];
        obj2->prof_arms_quadfracerr =
		profit->paramerr[profit->paramindex[PARAM_ARMS_QUADFRAC]];
        obj2->prof_arms_posang =
			fmod_m90_p90(*profit->paramlist[PARAM_ARMS_POSANG]);
        obj2->prof_arms_posangerr =
		profit->paramerr[profit->paramindex[PARAM_ARMS_POSANG]];
        }
      }
    }

626
/* Star/galaxy classification */
627
  if (FLAG(obj2.prof_class_star) || FLAG(obj2.prof_concentration))
628
629
630
    {
    pprofit = *profit;
    memset(pprofit.paramindex, 0, PARAM_NPARAM*sizeof(int));
631
    memset(pprofit.paramlist, 0, PARAM_NPARAM*sizeof(float *));
632
633
634
    pprofit.nparam = 0;
    QMALLOC(pprofit.prof, profstruct *, 1);
    pprofit.prof[0] = prof_init(&pprofit, PROF_DIRAC);
635
    QMALLOC16(pprofit.covar, float, pprofit.nparam*pprofit.nparam);
636
637
638
639
640
641
642
643
644
    pprofit.nprof = 1;
    profit_resetparams(&pprofit);
    if (profit->paramlist[PARAM_X] && profit->paramlist[PARAM_Y])
      {
      pprofit.paraminit[pprofit.paramindex[PARAM_X]] = *profit->paramlist[PARAM_X];
      pprofit.paraminit[pprofit.paramindex[PARAM_Y]] = *profit->paramlist[PARAM_Y];
      }
    pprofit.paraminit[pprofit.paramindex[PARAM_DISK_FLUX]] = profit->flux;
    pprofit.niter = profit_minimize(&pprofit, PROFIT_MAXITER);
645
    profit_residuals(&pprofit,field,wfield, 10.0, pprofit.param,pprofit.resi);
646
647
648
649
    if (FLAG(obj2.prof_class_star))
      {
      dchi2 = 0.5*(pprofit.chi2 - profit->chi2);
      obj2->prof_class_star = dchi2 < 50.0?
650
	(dchi2 > -50.0? 2.0/(1.0+expf(dchi2)) : 2.0) : 0.0;
651
652
653
654
655
656
657
658
659
      }
    if (FLAG(obj2.prof_concentration))
      {
      if (profit->flux > 0.0 && pprofit.flux > 0.0)
        obj2->prof_concentration = -2.5*log10(pprofit.flux / profit->flux);
      else  if (profit->flux > 0.0)
        obj2->prof_concentration = 99.0;
      else  if (pprofit.flux > 0.0)
        obj2->prof_concentration = -99.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
660
661
662
      if (FLAG(obj2.prof_concentrationerr))
        obj2->prof_concentrationerr = (obj2->flux_prof > 0.0?
		1.086*(obj2->fluxerr_prof / obj2->flux_prof) : 99.0);
663
      }
664
665
666
667
668
    prof_end(pprofit.prof[0]);
    free(pprofit.prof);
    free(pprofit.covar);
    }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
669
/* clean up. */
670
  fft_reset();
Emmanuel Bertin's avatar
Emmanuel Bertin committed
671
672
673
674
675
676
677
  free(profit->modpix);
  free(profit->psfpix);
  free(profit->pmodpix);
  free(profit->lmodpix);
  free(profit->objpix);
  free(profit->objweight);
  free(profit->resi);
678

Emmanuel Bertin's avatar
Emmanuel Bertin committed
679
680
681
  return;
  }

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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739

/****i* prof_gammainc *********************************************************
PROTO	double prof_gammainc(double x, double a)
PURPOSE	Returns the incomplete Gamma function (from Num. Recipes in C, p.216).
INPUT	A double,
	upper integration limit.
OUTPUT	Incomplete Gamma function.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	18/09/009
*/
static double	prof_gammainc (double x, double a)

  {
   double	b,c,d,h, xn,xp, del,sum;
   int		i;

  if (a < 0.0 || x <= 0.0)
    return 0.0;

  if (a < (x+1.0))
    {
/*-- Use the series representation */
    xp = x;
    del = sum = 1.0/x;
    for (i=100;i--;)	/* Iterate to convergence */
      {
      sum += (del *= a/(++xp));
      if (fabs(del) < fabs(sum)*3e-7)
        return sum*exp(-a+x*log(a)) / prof_gamma(x);
      }
    }
  else
    {
/*-- Use the continued fraction representation and take its complement */
    b = a + 1.0 - x;
    c = 1e30;
    h = d = 1.0/b;
    for (i=1; i<=100; i++)	/* Iterate to convergence */
      {
      xn = -i*(i-x);
      b += 2.0;
      if (fabs(d=xn*d+b) < 1e-30)
        d = 1e-30;
      if (fabs(c=b+xn/c) < 1e-30)
        c = 1e-30;
      del= c * (d = 1.0/d);
      h *= del;
      if (fabs(del-1.0) < 3e-7)
        return 1.0 - exp(-a+x*log(a))*h / prof_gamma(x);
      }
    }
  error(EXIT_FAILURE, "*Error*: out of bounds in ",
		"prof_gammainc()");
  return 0.0;
  }


740
/****i* prof_gamma ************************************************************
741
742
PROTO	double prof_gamma(double xx)
PURPOSE	Returns the Gamma function (from Num. Recipes in C, p.213).
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
INPUT	A double.
OUTPUT	Gamma function.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	11/09/009
*/
static double	prof_gamma(double xx)

  {
   double		x,tmp,ser;
   static double	cof[6]={76.18009173,-86.50532033,24.01409822,
			-1.231739516,0.120858003e-2,-0.536382e-5};
   int			j;

  tmp=(x=xx-1.0)+5.5;
  tmp -= (x+0.5)*log(tmp);
  ser=1.0;
  for (j=0;j<6;j++)
    ser += cof[j]/(x+=1.0);

  return 2.50662827465*ser*exp(-tmp);
  }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
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
/****** profit_minradius ******************************************************
PROTO	float profit_minradius(profitstruct *profit, float refffac)
PURPOSE	Returns the minimum disk radius that guarantees that each and
	every model component fits within some margin in that disk.
INPUT	Profit structure pointer,
	margin in units of (r/r_eff)^(1/n)).
OUTPUT	Radius (in pixels).
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	21/09/009
*/
float	profit_minradius(profitstruct *profit, float refffac)

  {
   double	r,reff,rmax;
   int		p;

  rmax = reff = 0.0;
  for (p=0; p<profit->nprof; p++)
    {
    switch (profit->prof[p]->code)
      {
      case PROF_SERSIC:
        reff = *profit->paramlist[PARAM_SPHEROID_REFF];
      break;
      case PROF_DEVAUCOULEURS:
        reff = *profit->paramlist[PARAM_SPHEROID_REFF];
       break;
      case PROF_EXPONENTIAL:
        reff = *profit->paramlist[PARAM_DISK_SCALE]*1.67835;
      break;
      default:
        error(EXIT_FAILURE, "*Internal Error*: Unknown profile parameter in ",
		"profit_minradius()");
      break;
      }
    r = reff*(double)refffac;
    if (r>rmax)
      rmax = r;
    }

  return (float)rmax;
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
812
813
814
815
816
817
818
/****** profit_psf ************************************************************
PROTO	void	profit_psf(profitstruct *profit)
PURPOSE	Build the local PSF at a given resolution.
INPUT	Profile-fitting structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
819
VERSION	05/10/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
820
821
822
 ***/
void	profit_psf(profitstruct *profit)
  {
823
824
   double	flux;
   float	posin[2], posout[2], dnaxisn[2],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
825
		*pixout,
826
		xcout,ycout, xcin,ycin, invpixstep, norm;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
827
828
829
830
831
   int		d,i;

  psf = profit->psf;
  psf_build(psf);

832
833
  xcout = (float)(profit->modnaxisn[0]/2) + 1.0;	/* FITS convention */
  ycout = (float)(profit->modnaxisn[1]/2) + 1.0;	/* FITS convention */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
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
  xcin = (psf->masksize[0]/2) + 1.0;			/* FITS convention */
  ycin = (psf->masksize[1]/2) + 1.0;			/* FITS convention */
  invpixstep = profit->pixstep / psf->pixstep;

/* Initialize multi-dimensional counters */
  for (d=0; d<2; d++)
    {
    posout[d] = 1.0;					/* FITS convention */
    dnaxisn[d] = profit->modnaxisn[d]+0.5;
    }

/* Remap each pixel */
  pixout = profit->psfpix;
  flux = 0.0;
  for (i=profit->modnaxisn[0]*profit->modnaxisn[1]; i--;)
    {
    posin[0] = (posout[0] - xcout)*invpixstep + xcin;
    posin[1] = (posout[1] - ycout)*invpixstep + ycin;
    flux += ((*(pixout++) = interpolate_pix(posin, psf->maskloc,
		psf->masksize, INTERP_LANCZOS3)));
    for (d=0; d<2; d++)
      if ((posout[d]+=1.0) < dnaxisn[d])
        break;
      else
        posout[d] = 1.0;
    }

/* Normalize PSF flux (just in case...) */
862
  flux *= profit->pixstep*profit->pixstep;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
  if (fabs(flux) > 0.0)
    {
    norm = 1.0/flux;
    pixout = profit->psfpix;
    for (i=profit->modnaxisn[0]*profit->modnaxisn[1]; i--;)
      *(pixout++) *= norm;
    }

  return;
  }


/****** profit_minimize *******************************************************
PROTO	void profit_minimize(profitstruct *profit)
PURPOSE	Provide a function returning residuals to lmfit.
INPUT	Pointer to the profit structure involved in the fit,
	maximum number of iterations.
OUTPUT	Number of iterations used.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	23/05/2008
 ***/
int	profit_minimize(profitstruct *profit, int niter)
  {
887
   float		lm_opts[5], info[LM_INFO_SZ];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
888
889
890
891
892
893
   int			m,n;

/* Allocate work space */
  n = profit->nparam;
  m = profit->nresi;

894
895
  memset(profit->resi, 0, profit->nresi*sizeof(float));
  memset(profit->covar, 0, profit->nparam*profit->nparam*sizeof(float));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
896
897
898
  profit_boundtounbound(profit, profit->paraminit);

/* Perform fit */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
899
900
901
902
903
  lm_opts[0] = 1.0e-3;
  lm_opts[1] = 1.0e-17;
  lm_opts[2] = 1.0e-17;
  lm_opts[3] = 1.0e-17;
  lm_opts[4] = 1.0e-6;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
904

905
  niter = slevmar_dif(profit_evaluate, profit->paraminit, profit->resi,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
906
907
908
909
910
911
912
913
914
915
	n, m, niter, lm_opts, info, NULL, profit->covar, profit);

  profit_unboundtobound(profit, profit->paraminit);


  return niter;
  }


/****** profit_printout *******************************************************
916
PROTO	void profit_printout(int n_par, float* par, int m_dat, float* fvec,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
		void *data, int iflag, int iter, int nfev )
PURPOSE	Provide a function to print out results to lmfit.
INPUT	Number of fitted parameters,
	pointer to the vector of parameters,
	number of data points,
	pointer to the vector of residuals (output),
	pointer to the data structure (unused),
	0 (init) 1 (outer loop) 2(inner loop) -1(terminated),
	outer loop counter,
	number of calls to evaluate().
OUTPUT	-.
NOTES	Input arguments are there only for compatibility purposes (unused)
AUTHOR	E. Bertin (IAP)
VERSION	17/09/2008
 ***/
932
void	profit_printout(int n_par, float* par, int m_dat, float* fvec,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
		void *data, int iflag, int iter, int nfev )
  {
   checkstruct	*check;
   profitstruct	*profit;
   char		filename[256];
   static int	itero;

  profit = (profitstruct *)data;

  if (0 && (iter!=itero || iter<0))
    {
    if (iter<0)
      itero++;
    else
      itero = iter;
    sprintf(filename, "check_%d_%04d.fits", the_gal, itero);
    check=initcheck(filename, CHECK_PROFILES, 0);
    reinitcheck(the_field, check);
    addcheck(check, profit->lmodpix, profit->objnaxisn[0],profit->objnaxisn[1],
		profit->ix,profit->iy, 1.0);

    reendcheck(the_field, check);
    endcheck(check);
    }

  return;
  }


/****** profit_evaluate ******************************************************
963
PROTO	void profit_evaluate(float *par, float *fvec, int m, int n,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
964
965
966
967
968
969
970
971
972
973
974
975
		void *adata)
PURPOSE	Provide a function returning residuals to levmar.
INPUT	Pointer to the vector of parameters,
	pointer to the vector of residuals (output),
	number of model parameters,
	number of data points,
	pointer to a data structure (unused).
OUTPUT	-.
NOTES	Input arguments are there only for compatibility purposes (unused)
AUTHOR	E. Bertin (IAP)
VERSION	18/09/2008
 ***/
976
void	profit_evaluate(float *par, float *fvec, int m, int n,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
977
978
979
980
981
982
			void *adata)
  {
   profitstruct	*profit;

  profit = (profitstruct *)adata;
  profit_unboundtobound(profit, par);
983
  profit_residuals(profit, the_field, the_wfield, PROFIT_DYNPARAM, par, fvec);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
984
985
986
987
988
989
990
  profit_boundtounbound(profit, par);
  profit_printout(m, par, n, fvec, adata, 0, -1, 0 );
  return;
  }


/****** profit_residuals ******************************************************
991
992
PROTO	float *prof_residuals(profitstruct *profit, picstruct *field,
		picstruct *wfield, float dynparam, float *param, float *resi)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
993
994
995
996
997
PURPOSE	Compute the vector of residuals between the data and the galaxy
	profile model.
INPUT	Profile-fitting structure,
	pointer to the field,
	pointer to the field weight,
998
	dynamic compression parameter (0=no compression),
Emmanuel Bertin's avatar
Emmanuel Bertin committed
999
1000
1001
1002
1003
	pointer to the model parameters (output),
	pointer to the computed residuals (output).
OUTPUT	Vector of residuals.
NOTES	-.
AUTHOR	E. Bertin (IAP)
1004
VERSION	24/03/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1005
 ***/
1006
1007
float	*profit_residuals(profitstruct *profit, picstruct *field,
		picstruct *wfield, float dynparam, float *param, float *resi)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1008
1009
1010
1011
  {
   int		p;

  memset(profit->modpix, 0,
1012
	profit->modnaxisn[0]*profit->modnaxisn[1]*sizeof(float));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1013
1014
  for (p=0; p<profit->nparam; p++)
    profit->param[p] = param[p];
1015
1016
/* Simple PSF shortcut */
  if (profit->nprof == 1 && profit->prof[0]->code == PROF_DIRAC)
1017
    {
1018
1019
    profit_resample(profit, profit->psfpix, profit->lmodpix,
		*profit->prof[0]->flux);
1020
1021
    profit->flux = *profit->prof[0]->flux;
    }
1022
1023
  else
    {
1024
    profit->flux = 0.0;
1025
    for (p=0; p<profit->nprof; p++)
1026
      profit->flux += prof_add(profit->prof[p], profit);
1027
1028
1029
    profit_convolve(profit, profit->modpix);
    profit_resample(profit, profit->modpix, profit->lmodpix, 1.0);
    }
1030
  profit_compresi(profit, dynparam, resi);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1031
1032
1033
1034
1035
1036

  return resi;
  }


/****** profit_compresi ******************************************************
1037
1038
PROTO	float *prof_compresi(profitstruct *profit, float dynparam,
			float *resi)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1039
1040
1041
PURPOSE	Compute the vector of residuals between the data and the galaxy
	profile model.
INPUT	Profile-fitting structure,
1042
	dynamic-compression parameter (0=no compression),
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1043
1044
1045
1046
	vector of residuals (output).
OUTPUT	Vector of residuals.
NOTES	-.
AUTHOR	E. Bertin (IAP)
1047
VERSION	07/09/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1048
 ***/
1049
float	*profit_compresi(profitstruct *profit, float dynparam, float *resi)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1050
  {
1051
1052
   double	error;
   float	*resit;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1053
1054
   PIXTYPE	*objpix, *objweight, *lmodpix,
		val,val2,wval, invsig;
1055
   int		npix, i;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1056
1057
1058
1059
1060
1061
1062
  
/* Compute vector of residuals */
  resit = resi;
  objpix = profit->objpix;
  objweight = profit->objweight;
  lmodpix = profit->lmodpix;
  error = 0.0;
1063
1064
  npix = profit->objnaxisn[0]*profit->objnaxisn[1];
  if (dynparam > 0.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1065
    {
1066
1067
    invsig = (PIXTYPE)(1.0/dynparam);
    for (i=npix; i--; lmodpix++)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1068
1069
1070
1071
      {
      val = *(objpix++);
      if ((wval=*(objweight++))>0.0)
        {
1072
        val2 = (val - *lmodpix)*wval*invsig;
1073
        val2 = val2>0.0? logf(1.0+val2) : -logf(1.0-val2);
1074
        *(resit++) = val2*dynparam;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1075
1076
1077
        error += val2*val2;
        }
      }
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
    profit->chi2 = dynparam*dynparam*error;
    }
  else
    {
    for (i=npix; i--; lmodpix++)
      {
      val = *(objpix++);
      if ((wval=*(objweight++))>0.0)
        {
        val2 = (val - *lmodpix)*wval;
        *(resit++) = val2;
        error += val2*val2;
        }
      }
    profit->chi2 = error;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1093
1094
1095
1096
1097
1098
1099
    }

  return resi;
  }


/****** profit_resample ******************************************************
1100
PROTO	void	prof_resample(profitstruct *profit, float *inpix,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1101
1102
1103
1104
1105
1106
		PIXTYPE *outpix)
PURPOSE	Resample the current full resolution model to image resolution.
INPUT	Profile-fitting structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
1107
VERSION	09/10/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1108
 ***/
1109
1110
void	profit_resample(profitstruct *profit, float *inpix, PIXTYPE *outpix,
	float factor)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1111
  {
1112
1113
   double	flux;
   float	posin[2], posout[2], dnaxisn[2],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1114
		*dx,*dy,
1115
1116
		xcout,ycout, xcin,ycin, invpixstep, pix, off,step;
   int		d,i, ix,iy,ns;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1117

1118
  xcout = (float)(profit->objnaxisn[0]/2) + 1.0;	/* FITS convention */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1119
1120
  if ((dx=(profit->paramlist[PARAM_X])))
    xcout += *dx;
1121
  ycout = (float)(profit->objnaxisn[1]/2) + 1.0;	/* FITS convention */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1122
1123
1124
1125
  if ((dy=(profit->paramlist[PARAM_Y])))
    ycout += *dy;
  xcin = (profit->modnaxisn[0]/2) + 1.0;		/* FITS convention */
  ycin = (profit->modnaxisn[1]/2) + 1.0;		/* FITS convention */
1126
  invpixstep = profit->subsamp/profit->pixstep;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1127
1128
1129
1130
1131
1132
1133
1134

/* Initialize multi-dimensional counters */
  for (d=0; d<2; d++)
    {
    posout[d] = 1.0;					/* FITS convention */
    dnaxisn[d] = profit->objnaxisn[d]+0.5;
    }

1135
/* Remap each pixel (and rebin if necessary) */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1136
  flux = 0.0;
1137
1138
  ns=(int)profit->subsamp;
  if (ns>1)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1139
    {
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
    step = 1.0/profit->subsamp;
    off = 0.5*(step - 1.0);
    xcin += off;
    ycin += off;
    for (i=profit->objnaxisn[0]*profit->objnaxisn[1]; i--;)
      {
      posin[0] = (posout[0] - xcout)*invpixstep + xcin;
      posin[1] = (posout[1] - ycout)*invpixstep + ycin;
      pix = 0.0;
      for (iy=ns; iy--; posin[1] += step)
        for (ix=ns; ix--; posin[0] += step)
          pix += (PIXTYPE)(factor*interpolate_pix(posin, inpix,
		profit->modnaxisn, INTERP_LANCZOS3));
      flux += (*(outpix++) = pix);
      for (d=0; d<2; d++)
        if ((posout[d]+=1.0) < dnaxisn[d])
          break;
        else
          posout[d] = 1.0;
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1160
    }
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
  else
    for (i=profit->objnaxisn[0]*profit->objnaxisn[1]; i--;)
      {
      posin[0] = (posout[0] - xcout)*invpixstep + xcin;
      posin[1] = (posout[1] - ycout)*invpixstep + ycin;
      flux += ((*(outpix++) = (PIXTYPE)(factor*interpolate_pix(posin, inpix,
		profit->modnaxisn, INTERP_LANCZOS3))));
      for (d=0; d<2; d++)
        if ((posout[d]+=1.0) < dnaxisn[d])
          break;
        else
          posout[d] = 1.0;
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1174
1175
1176
1177
1178
1179

  return;
  }


/****** profit_convolve *******************************************************
1180
PROTO	void profit_convolve(profitstruct *profit, float *modpix)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1181
1182
1183
1184
1185
1186
1187
1188
PURPOSE	Convolve a model image with the local PSF.
INPUT	Pointer to the profit structure,
	Pointer to the image raster.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	15/09/2008
 ***/
1189
void	profit_convolve(profitstruct *profit, float *modpix)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
  {
  if (!profit->psfdft)
    profit_makedft(profit);

  fft_conv(modpix, profit->psfdft, profit->modnaxisn);

  return;
  }


/****** profit_makedft *******************************************************
PROTO	void profit_makedft(profitstruct *profit)
PURPOSE	Create the Fourier transform of the descrambled PSF component.
INPUT	Pointer to the profit structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	22/04/2008
 ***/
void	profit_makedft(profitstruct *profit)
  {
   psfstruct	*psf;
1212
1213
   float      *mask,*maskt, *ppix;
   float       dx,dy, r,r2,rmin,rmin2,rmax,rmax2,rsig,invrsig2;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
   int          width,height,npix,offset, psfwidth,psfheight,psfnpix,
                cpwidth, cpheight,hcpwidth,hcpheight, i,j,x,y;

  if (!(psf=profit->psf))
    return;

  psfwidth = profit->modnaxisn[0];
  psfheight = profit->modnaxisn[1];
  psfnpix = psfwidth*psfheight;
  width = profit->modnaxisn[0];
  height = profit->modnaxisn[1];
  npix = width*height;
1226
  QCALLOC(mask, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
  cpwidth = (width>psfwidth)?psfwidth:width;
  hcpwidth = cpwidth>>1;
  cpwidth = hcpwidth<<1;
  offset = width - cpwidth;
  cpheight = (height>psfheight)?psfheight:height;
  hcpheight = cpheight>>1;
  cpheight = hcpheight<<1;

/* Frame and descramble the PSF data */
  ppix = profit->psfpix + (psfheight/2)*psfwidth + psfwidth/2;
  maskt = mask;
  for (j=hcpheight; j--; ppix+=psfwidth)
    {
    for (i=hcpwidth; i--;)
      *(maskt++) = *(ppix++);      
    ppix -= cpwidth;
    maskt += offset;
    for (i=hcpwidth; i--;)
      *(maskt++) = *(ppix++);      
    }

  ppix = profit->psfpix + ((psfheight/2)-hcpheight)*psfwidth + psfwidth/2;
  maskt += width*(height-cpheight);
  for (j=hcpheight; j--; ppix+=psfwidth)
    {
    for (i=hcpwidth; i--;)
      *(maskt++) = *(ppix++);      
    ppix -= cpwidth;
    maskt += offset;
    for (i=hcpwidth; i--;)
      *(maskt++) = *(ppix++);      
    }

/* Truncate to a disk that has diameter = (box width) */
  rmax = cpwidth - 1.0 - hcpwidth;
  if (rmax > (r=hcpwidth))
    rmax = r;
  if (rmax > (r=cpheight-1.0-hcpheight))
    rmax = r;
  if (rmax > (r=hcpheight))
    rmax = r;
  if (rmax<1.0)
    rmax = 1.0;
  rmax2 = rmax*rmax;
  rsig = psf->fwhm/profit->pixstep;
  invrsig2 = 1/(2*rsig*rsig);
  rmin = rmax - (3*rsig);     /* 3 sigma annulus (almost no aliasing) */
  rmin2 = rmin*rmin;

  maskt = mask;
  dy = 0.0;
  for (y=hcpheight; y--; dy+=1.0)
    {
    dx = 0.0;
    for (x=hcpwidth; x--; dx+=1.0, maskt++)
      if ((r2=dx*dx+dy*dy)>rmin2)
1283
        *maskt *= (r2>rmax2)?0.0:expf((2*rmin*sqrtf(r2)-r2-rmin2)*invrsig2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1284
1285
1286
1287
    dx = -hcpwidth;
    maskt += offset;
    for (x=hcpwidth; x--; dx+=1.0, maskt++)
      if ((r2=dx*dx+dy*dy)>rmin2)
1288
        *maskt *= (r2>rmax2)?0.0:expf((2*rmin*sqrtf(r2)-r2-rmin2)*invrsig2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1289
1290
1291
1292
1293
1294
1295
1296
    }
  dy = -hcpheight;
  maskt += width*(height-cpheight);
  for (y=hcpheight; y--; dy+=1.0)
    {
    dx = 0.0;
    for (x=hcpwidth; x--; dx+=1.0, maskt++)
      if ((r2=dx*dx+dy*dy)>rmin2)
1297
        *maskt *= (r2>rmax2)?0.0:expf((2*rmin*sqrtf(r2)-r2-rmin2)*invrsig2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1298
1299
1300
1301
    dx = -hcpwidth;
    maskt += offset;
    for (x=hcpwidth; x--; dx+=1.0, maskt++)
      if ((r2=dx*dx+dy*dy)>rmin2)
1302
        *maskt *= (r2>rmax2)?0.0:expf((2*rmin*sqrtf(r2)-r2-rmin2)*invrsig2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
    }

/* Finally move to Fourier space */
  profit->psfdft = fft_rtf(mask, profit->modnaxisn);

  free(mask);

  return;
  }


/****** profit_copyobjpix *****************************************************
PROTO	int profit_copyobjpix(profitstruct *profit, picstruct *field,
			picstruct *wfield)
PURPOSE	Copy a piece of the input field image to a profit structure.
INPUT	Pointer to the profit structure,
	Pointer to the field structure,
	Pointer to the field weight structure.
OUTPUT	The number of valid pixels copied.
NOTES	Global preferences are used.
AUTHOR	E. Bertin (IAP)
1324
VERSION	07/10/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1325
1326
1327
1328
 ***/
int	profit_copyobjpix(profitstruct *profit, picstruct *field,
			picstruct *wfield)
  {
1329
1330
1331
1332
1333
   float	dx, dy2, dr2, rad2;
   PIXTYPE	*pixin,*spixin, *wpixin,*swpixin, *pixout,*wpixout,
		backnoise2, invgain, satlevel, wthresh, pix,spix, wpix,swpix;
   int		i,x,y, xmin,xmax,ymin,ymax, w,h,dw, npix, off, gainflag,
		badflag, sflag, sx,sy,sn,sw, rem, ix,iy;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1334
1335
1336
1337

/* First put the image background to -BIG */
  pixout = profit->objpix;
  wpixout = profit->objweight;
1338
  for (i=profit->objnaxisn[0]*profit->objnaxisn[1]; i--;)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
    {
    *(pixout++) = -BIG;
    *(wpixout++) = 0.0;
    }

/* Don't go further if out of frame!! */
  ix = profit->ix;
  iy = profit->iy;
  if (ix<0 || ix>=field->width || iy<field->ymin || iy>=field->ymax)
    return 0;

  backnoise2 = field->backsig*field->backsig;
1351
  sn = (int)profit->subsamp;
1352
1353
1354
1355
1356
  sflag = (sn>1);
  w = profit->objnaxisn[0]*sn;
  h = profit->objnaxisn[1]*sn;
  if (sflag)
    backnoise2 *= (PIXTYPE)sn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
  invgain = (field->gain > 0.0) ? 1.0/field->gain : 0.0;
  satlevel = field->satur_level - profit->obj->bkg;
  rad2 = h/2.0;
  if (rad2 > w/2.0)
    rad2 = w/2.0;
  rad2 *= rad2;

/* Set the image boundaries */
  pixout = profit->objpix;
  wpixout = profit->objweight;
  ymin = iy-h/2;
  ymax = ymin + h;
  if (ymin<field->ymin)
    {
1371
1372
1373
1374
    off = (field->ymin-ymin-1)/sn + 1;
    pixout += off*profit->objnaxisn[0];
    wpixout += off*profit->objnaxisn[0];
    ymin += off*sn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1375
1376
    }
  if (ymax>field->ymax)
1377
    ymax -= ((ymax-field->ymax-1)/sn + 1)*sn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1378
1379
1380

  xmin = ix-w/2;
  xmax = xmin + w;
1381
  dw = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1382
1383
  if (xmax>field->width)
    {
1384
1385
1386
    off = (xmax-field->width-1)/sn + 1;
    dw += off;
    xmax -= off*sn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1387
1388
1389
    }
  if (xmin<0)
    {
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
    off = (-xmin-1)/sn + 1;
    pixout += off;
    wpixout += off;
    dw += off;
    xmin += off*sn;
    }
/* Make sure the input frame size is a multiple of the subsampling step */
  if (sflag)
    {
/*
    if (((rem=ymax-ymin)%sn))
      {
      ymin += rem/2;
      ymax -= (rem-rem/2);
      }
    if (((rem=xmax-xmin)%sn))
      {
      xmin += rem/2;
      pixout += rem/2;
      wpixout += rem/2;
      dw += rem;
      xmax -= (rem-rem/2);
      }
*/
    sw = field->width;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1415
1416
1417
1418
1419
1420
1421
1422
    }

/* Copy the right pixels to the destination */
  npix = 0;
  if (wfield)
    {
    wthresh = wfield->weight_thresh;
    gainflag = prefs.weightgain_flag;
1423
    if (sflag)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1424
      {
1425
1426
/*---- Sub-sampling case */
      for (y=ymin; y<ymax; y+=sn, pixout+=dw,wpixout+=dw)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1427
        {
1428
        for (x=xmin; x<xmax; x+=sn)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1429
          {
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
          pix = wpix = 0.0;
          badflag = 0;
          for (sy=0; sy<sn; sy++)
            {
            dy2 = (y+sy-iy);
            dy2 *= dy2;
            dx = (x-ix);
            spixin = &PIX(field, x, y+sy);
            swpixin = &PIX(wfield, x, y+sy);
            for (sx=sn; sx--;)
              {
              dr2 = dy2 + dx*dx;
              dx++;
              spix = *(spixin++);
              swpix = *(swpixin++);
              if (dr2<rad2 && spix>-BIG && spix<satlevel && swpix<wthresh)
                {
                pix += spix;
                wpix += swpix;
                }
              else
                badflag=1;
              }
            }
          *(pixout++) = pix;
          if (!badflag)	/* A single bad pixel ruins is all (saturation, etc.)*/
            {
            *(wpixout++) = 1.0 / sqrt(wpix+(pix>0.0?
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1458
		(gainflag? pix*wpix/backnoise2:pix)*invgain : 0.0));
1459
1460
1461
1462
            npix++;
            }
          else
            *(wpixout++) = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1463
1464
1465
          }
        }
      }
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
    else
      for (y=ymin; y<ymax; y++, pixout+=dw,wpixout+=dw)
        {
        dy2 = y-iy;
        dy2 *= dy2;
        pixin = &PIX(field, xmin, y);
        wpixin = &PIX(wfield, xmin, y);
        for (x=xmin; x<xmax; x++)
          {
          dx = x-ix;
          dr2 = dy2 + dx*dx;
          pix = *(pixin++);
          wpix = *(wpixin++);
          if (dr2<rad2 && pix>-BIG && pix<satlevel && wpix<wthresh)
            {
            *(pixout++) = pix;
            *(wpixout++) = 1.0 / sqrt(wpix+(pix>0.0?
		(gainflag? pix*wpix/backnoise2:pix)*invgain : 0.0));
            npix++;
            }
          else
            *(pixout++) = *(wpixout++) = 0.0;
          }
        }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1490
1491
    }
  else
1492
1493
    {
    if (sflag)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1494
      {
1495
1496
/*---- Sub-sampling case */
      for (y=ymin; y<ymax; y+=sn, pixout+=dw, wpixout+=dw)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1497
        {
1498
        for (x=xmin; x<xmax; x+=sn)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1499
          {
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
          pix = 0.0;
          badflag = 0;
          for (sy=0; sy<sn; sy++)
            {
            dy2 = y+sy-iy;
            dy2 *= dy2;
            dx = x-ix;
            spixin = &PIX(field, x, y+sy);
            for (sx=sn; sx--;)
              {
              dr2 = dy2 + dx*dx;
              dx++;
              spix = *(spixin++);
              if (dr2<rad2 && spix>-BIG && spix<satlevel)
                pix += spix;
              else
                badflag=1;
              }
            }
          *(pixout++) = pix;
          if (!badflag)	/* A single bad pixel ruins is all (saturation, etc.)*/
            {
            *(wpixout++) = 1.0 / sqrt(backnoise2 + (pix>0.0?pix*invgain:0.0));
            npix++;
            }
          else
            *(wpixout++) = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1527
1528
1529
          }
        }
      }
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
    else
      for (y=ymin; y<ymax; y++, pixout+=dw,wpixout+=dw)
        {
        dy2 = y-iy;
        dy2 *= dy2;
        pixin = &PIX(field, xmin, y);
        for (x=xmin; x<xmax; x++)
          {
          dx = x-ix;
          dr2 = dy2 + dx*dx;
          pix = *(pixin++);
          if (dr2<rad2 && pix>-BIG && pix<satlevel)
            {
            *(pixout++) = pix;
            *(wpixout++) = 1.0 / sqrt(backnoise2 + (pix>0.0?pix*invgain : 0.0));
            npix++;
            }
          else
            *(pixout++) = *(wpixout++) = 0.0;
          }
        }
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1552
1553
1554
1555
1556
1557
 
  return npix;
  }


/****** profit_spiralindex ****************************************************
1558
PROTO	float profit_spiralindex(profitstruct *profit)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1559
1560
1561
1562
1563
1564
1565
1566
1567
PURPOSE	Compute the spiral index of a galaxy image (positive for arms
	extending counter-clockwise and negative for arms extending CW, 0 for
	no spiral pattern).
INPUT	Profile-fitting structure.
OUTPUT	Vector of residuals.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	18/09/2008
 ***/
1568
float profit_spiralindex(profitstruct *profit)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1569
1570
1571
  {
   objstruct	*obj;
   obj2struct	*obj2;
1572
   float	*dx,*dy, *fdx,*fdy, *gdx,*gdy, *gdxt,*gdyt, *pix,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
		fwhm, invtwosigma2, hw,hh, ohw,ohh, x,y,xstart, tx,ty,txstart,
		gx,gy, r2, spirindex, invsig, val, sep;
   PIXTYPE	*fpix;
   int		i,j, npix;

  npix = profit->objnaxisn[0]*profit->objnaxisn[1];

  obj = profit->obj;
  obj2 = profit->obj2;
/* Compute simple derivative vectors at a fraction of the object scale */
  fwhm = obj2->hl_radius * 2.0 / 4.0;
  if (fwhm < 2.0)
    fwhm = 2.0;
  sep = 2.0;

  invtwosigma2 = -(2.35*2.35/(2.0*fwhm*fwhm));
1589
  hw = (float)(profit->objnaxisn[0]/2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1590
  ohw = profit->objnaxisn[0] - hw;
1591
  hh = (float)(profit->objnaxisn[1]/2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1592
1593
1594
  ohh = profit->objnaxisn[1] - hh;
  txstart = -hw;
  ty = -hh;
1595
  QMALLOC(dx, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
  pix = dx;
  for (j=profit->objnaxisn[1]; j--; ty+=1.0)
    {
    tx = txstart;
    y = ty < -0.5? ty + hh : ty - ohh;
    for (i=profit->objnaxisn[0]; i--; tx+=1.0)
      {
      x = tx < -0.5? tx + hw : tx - ohw;
      *(pix++) = exp(invtwosigma2*((x+sep)*(x+sep)+y*y))
		- exp(invtwosigma2*((x-sep)*(x-sep)+y*y));
      }
    }
1608
  QMALLOC(dy, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
  pix = dy;
  ty = -hh;
  for (j=profit->objnaxisn[1]; j--; ty+=1.0)
    {
    tx = txstart;
    y = ty < -0.5? ty + hh : ty - ohh;
    for (i=profit->objnaxisn[0]; i--; tx+=1.0)
      {
      x = tx < -0.5? tx + hw : tx - ohw;
      *(pix++) = exp(invtwosigma2*(x*x+(y+sep)*(y+sep)))
		- exp(invtwosigma2*(x*x+(y-sep)*(y-sep)));
      }
    }

1623
  QMALLOC(gdx, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1624
1625
1626
1627
1628
1629
1630
1631
1632
  gdxt = gdx;
  fpix = profit->objpix;
  invsig = npix/profit->sigma;
  for (i=npix; i--; fpix++)
    {
    val = *fpix > -1e29? *fpix*invsig : 0.0;
    *(gdxt++) = (val>0.0? log(1.0+val) : -log(1.0-val));
    }
  gdy = NULL;			/* to avoid gcc -Wall warnings */
1633
  QMEMCPY(gdx, gdy, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
  fdx = fft_rtf(dx, profit->objnaxisn);
  fft_conv(gdx, fdx, profit->objnaxisn);
  fdy = fft_rtf(dy, profit->objnaxisn);
  fft_conv(gdy, fdy, profit->objnaxisn);

/* Compute estimator */
  invtwosigma2 = -1.18*1.18 / (2.0*obj2->hl_radius*obj2->hl_radius);
  xstart = -hw - obj->mx + (int)(obj->mx+0.49999);
  y = -hh -  obj->my + (int)(obj->my+0.49999);;
  spirindex = 0.0;
  gdxt = gdx;
  gdyt = gdy;
  for (j=profit->objnaxisn[1]; j--; y+=1.0)
    {
    x = xstart;
    for (i=profit->objnaxisn[0]; i--; x+=1.0)
      {
      gx = *(gdxt++);
      gy = *(gdyt++);
      if ((r2=x*x+y*y)>0.0)
        spirindex += (x*y*(gx*gx-gy*gy)+gx*gy*(y*y-x*x))/r2
			* exp(invtwosigma2*r2);
      }
    }

  free(dx);
  free(dy);
  free(fdx);
  free(fdy);
  free(gdx);
  free(gdy);

  return spirindex;
  }


/****** profit_moments ****************************************************
1671
PROTO	void profit_moments(profitstruct *profit, obj2struct *obj2)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1672
PURPOSE	Compute the 2nd order moments from the unconvolved object model.
1673
1674
INPUT	Profile-fitting structure,
	Pointer to obj2 structure.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1675
1676
1677
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
1678
VERSION	17/09/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1679
 ***/
1680
void	 profit_moments(profitstruct *profit, obj2struct *obj2)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1681
  {
1682
   double	mx,my, sum, mx2,my2,mxy, den, temp,temp2,pmx2,theta;
1683
1684
   float	*pix,
		hw,hh, x,y, xstart, val, r2max;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1685
1686
   int		ix,iy;

1687
1688
  hw = (float)(profit->modnaxisn[0]/2);
  hh = (float)(profit->modnaxisn[1]/2);
1689
  r2max = hw<hh? hw*hw : hh*hh;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1690
1691
1692
1693
1694
1695
1696
1697
  xstart = -hw;
  y = -hh;
  pix = profit->modpix;
  mx2 = my2 = mxy = mx = my = sum = 0.0;
  for (iy=profit->modnaxisn[1]; iy--; y+=1.0)
    {
    x = xstart;
    for (ix=profit->modnaxisn[0]; ix--; x+=1.0)
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
      if (y*y+x*x <= r2max)
        {
        val = *(pix++);
        sum += val;
        mx  += val*x;
        my  += val*y;
        mx2 += val*x*x;
        mxy += val*x*y;
        my2 += val*y*y;
        }
      else
        pix++;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1710
1711
1712
1713
1714
1715
1716
1717
1718
    }

  if (sum <= 1.0/BIG)
    sum = 1.0;
  mx /= sum;
  my /= sum;
  obj2->prof_mx2 = mx2 = mx2/sum - mx*mx;
  obj2->prof_my2 = my2 = my2/sum - my*my;
  obj2->prof_mxy = mxy = mxy/sum - mx*my;
1719
1720
1721

/* Handle fully correlated profiles (which cause a singularity...) */
  if ((temp2=mx2*my2-mxy*mxy)<0.00694)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1722
    {
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
    mx2 += 0.0833333;
    my2 += 0.0833333;
    temp2 = mx2*my2-mxy*mxy;
    }

  if (FLAG(obj2.prof_e1))
    {
    if (mx2+my2 > 1.0/BIG)
      {
      obj2->prof_pol1 = (mx2 - my2) / (mx2+my2);
      obj2->prof_pol2 = 2.0*mxy / (mx2 + my2);
      if (temp2>=0.0)
        den = mx2+my2+2.0*sqrt(temp2);
      else
        den = mx2+my2;
      obj2->prof_e1 = (mx2 - my2) / den;
      obj2->prof_e2 = 2.0*mxy / den;
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1741
    else
1742
      obj2->prof_pol1 = obj2->prof_pol2 = obj2->prof_e1 = obj2->prof_e2 = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1743
    }
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765

  if (FLAG(obj2.prof_cxx))
    {
    obj2->prof_cxx = (float)(my2/temp2);
    obj2->prof_cyy = (float)(mx2/temp2);
    obj2->prof_cxy = (float)(-2*mxy/temp2);
    }

  if (FLAG(obj2.prof_a))
    {
    if ((fabs(temp=mx2-my2)) > 0.0)
      theta = atan2(2.0 * mxy,temp) / 2.0;
    else
      theta = PI/4.0;

    temp = sqrt(0.25*temp*temp+mxy*mxy);
    pmx2 = 0.5*(mx2+my2);
    obj2->prof_a = (float)sqrt(pmx2 + temp);
    obj2->prof_b = (float)sqrt(pmx2 - temp);
    obj2->prof_theta = theta*180.0/PI;
    }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1766
1767
1768
1769
1770

  return;
  }


1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
/****** profit_surface ****************************************************
PROTO	void profit_surface(profitstruct *profit, obj2struct *obj2,
			double lostfluxfrac)
PURPOSE	Compute surface brightnesses from the unconvolved object model.
INPUT	Pointer to the profile-fitting structure,
	Pointer to obj2 structure,
	Fraction of total flux lost in model.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	21/09/2009
 ***/
void	 profit_surface(profitstruct *profit, obj2struct *obj2,
			double lostfluxfrac)
  {
   double	dsum,dhsum,dsumoff, dhval, frac, seff;
   float	*spix, *spixt;
   int		i, npix, neff;

  npix = profit->modnaxisn[0]*profit->modnaxisn[1];
/* Sort model pixel values */
  spix = NULL;				/* to avoid gcc -Wall warnings */
  QMEMCPY(profit->modpix, spix, float, npix);
  hmedian(spix, npix);
  obj2->peak_prof = spix[npix-1];

  if (FLAG(obj2.fluxeff_prof))
    {
/*-- Build a cumulative distribution */
    dsum = 0.0;
    spixt = spix;
    for (i=npix; i--;)
      dsum += (double)*(spixt++);
/*-- Find matching surface brightness */
    if (lostfluxfrac > 1.0)
      lostfluxfrac = 0.0;
    dhsum = 0.5 * dsum / (1.0-lostfluxfrac);
    dsum = lostfluxfrac * dsum / (1.0-lostfluxfrac);
    neff = 0;
    spixt = spix;
    for (i=npix; i--;)
      if ((dsum += (double)*(spixt++)) >= dhsum)
        {
        neff = i;
        break;
        }
    dhval = (double)*(spixt-1);
    seff = neff;
    dsumoff = 0.0;
    if (spixt>=spix+2)
      if (dhval > 0.0 && (frac = (dsum - dhsum) / dhval) < 1.0)
        {
        seff += frac;
        dsumoff = frac*dhval;
        dhval = dsumoff + (1.0 - frac)*(double)*(spixt-2);
        }
    obj2->fluxeff_prof = dhval;
    if (FLAG(obj2.fluxmean_prof))
      {
      dsum = dsumoff;
      for (i=neff; i--;)
        dsum += (double)*(spixt++);
      obj2->fluxmean_prof = seff > 0.0? dsum / seff : 0.0;
      }
    }

  free(spix);

  return;
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
1843
1844
/****** profit_addparam *******************************************************
PROTO	void profit_addparam(profitstruct *profit, paramenum paramindex,
1845
		float **param)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
PURPOSE	Add a profile parameter to the list of fitted items.
INPUT	Pointer to the profit structure,
	Parameter index,
	Pointer to the parameter pointer.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	29/03/2007
 ***/
void	profit_addparam(profitstruct *profit, paramenum paramindex,
1856
		float **param)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
  {
/* Check whether the parameter has already be registered */
  if (profit->paramlist[paramindex])
/*-- Yes */
    *param = profit->paramlist[paramindex];
  else
/*-- No */
    {
    *param = profit->paramlist[paramindex] = &profit->param[profit->nparam];
    profit->paramindex[paramindex] = profit->nparam++;
    }

  return;
  }


/****** profit_resetparam ****************************************************
PROTO	void profit_resetparam(profitstruct *profit, paramenum paramtype)
PURPOSE	Set the initial, lower and upper boundary values of a profile parameter.
INPUT	Pointer to the profit structure,
	Parameter index.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	25/09/2008
 ***/
void	profit_resetparam(profitstruct *profit, paramenum paramtype)
  {
   objstruct	*obj;
   obj2struct	*obj2;
1887
   float	param, parammin,parammax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1888
1889
1890
1891

  obj = profit->obj;
  obj2 = profit->obj2;
  param = parammin = parammax = 0.0;	/* Avoid gcc -Wall warnings*/
1892

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
  switch(paramtype)
    {
    case PARAM_BACK:
      param = 0.0;
      parammin = -6.0*obj->sigbkg;
      parammax =  6.0*obj->sigbkg;
      break;
    case PARAM_X:
      param = obj->mx - (int)(obj->mx+0.49999);
      parammin = -obj2->hl_radius*4;
      parammax =  obj2->hl_radius*4;
      break;
    case PARAM_Y:
      param = obj->my - (int)(obj->my+0.49999);
      parammin = -obj2->hl_radius*4;
      parammax =  obj2->hl_radius*4;
      break;
    case PARAM_SPHEROID_FLUX:
      param = obj2->flux_auto/2.0;
      parammin = -obj2->flux_auto/1000.0;
      parammax = 2*obj2->flux_auto;
      break;
    case PARAM_SPHEROID_REFF:
      param = obj2->hl_radius;
      parammin = 0.1;
      parammax = param * 4.0;
      break;
    case PARAM_SPHEROID_ASPECT:
      param = FLAG(obj2.prof_disk_flux)? 1.0 : obj->b/obj->a;
      parammin = FLAG(obj2.prof_disk_flux)? 0.5 : 0.01;
      parammax = 1.0;
      break;
    case PARAM_SPHEROID_POSANG:
      param = obj->theta;
      parammin = 0.0;
      parammax =  0.0;
      break;
    case PARAM_SPHEROID_SERSICN:
      param = 4.0;
      parammin = 1.0;
      parammax = 10.0;
      break;
    case PARAM_DISK_FLUX:
      param = obj2->flux_auto/2.0;
      parammin = -obj2->flux_auto/1000.0;
      parammax = 2*obj2->flux_auto;
      break;
    case PARAM_DISK_SCALE:	/* From scalelength to Re */
      param = obj2->hl_radius/1.67835*sqrt(obj->a/obj->b);
1942
      parammin = param/4.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
      parammax = param * 4.0;
      break;
    case PARAM_DISK_ASPECT:
      param = obj->b/obj->a;
      parammin = 0.01;
      parammax = 1.0;
      break;
    case PARAM_DISK_POSANG:
      param = obj->theta;
      parammin = 0.0;
      parammax =  0.0;
      break;
    case PARAM_ARMS_FLUX:
      param = obj2->flux_auto/2.0;
      parammin = 0.0;
      parammax = obj2->flux_auto*2.0;
      break;
    case PARAM_ARMS_QUADFRAC:
      param = 0.5;
      parammin = 0.0;
      parammax = 1.0;
      break;
    case PARAM_ARMS_SCALE:
      param = 1.0;
      parammin = 0.5;
      parammax = 10.0;
      break;
    case PARAM_ARMS_START:
      param = 0.5;
      parammin = 0.0;
      parammax = 3.0;
      break;
    case PARAM_ARMS_PITCH:
      param = 20.0;
      parammin = 5.0;
      parammax = 50.0;
      break;
    case PARAM_ARMS_PITCHVAR:
      param = 0.0;
      parammin = -1.0;
      parammax = 1.0;
      break;
//      if ((profit->spirindex=profit_spiralindex(profit, obj, obj2)) > 0.0)
//        {
//        param = -param;
//        parammin = -parammax;
//        parammax = -parammin;
//        }
//      printf("spiral index: %g  \n", profit->spirindex);
//      break;
    case PARAM_ARMS_POSANG:
      param = 0.0;
      parammin = 0.0;
      parammax = 0.0;
      break;
    case PARAM_ARMS_WIDTH:
      param = 3.0;
      parammin = 1.5;
      parammax = 11.0;
      break;
    case PARAM_BAR_FLUX:
      param = obj2->flux_auto/10.0;
      parammin = 0.0;
      parammax = 2.0*obj2->flux_auto;
      break;
    case PARAM_BAR_ASPECT:
      param = 0.3;
      parammin = 0.2;
      parammax = 0.5;
      break;
    case PARAM_BAR_POSANG:
      param = 0.0;
      parammin = 0.0;
      parammax = 0.0;
      break;
    case PARAM_INRING_FLUX:
      param = obj2->flux_auto/10.0;
      parammin = 0.0;
      parammax = 2.0*obj2->flux_auto;
      break;
    case PARAM_INRING_WIDTH:
      param = 0.3;
      parammin = 0.0;
      parammax = 0.5;
      break;
    case PARAM_INRING_ASPECT:
      param = 0.8;
      parammin = 0.4;
      parammax = 1.0;
      break;
    case PARAM_OUTRING_FLUX:
      param = obj2->flux_auto/10.0;
      parammin = 0.0;
      parammax = 2.0*obj2->flux_auto;
      break;
    case PARAM_OUTRING_START:
      param = 4.0;
      parammin = 3.5;
      parammax = 6.0;
      break;
    case PARAM_OUTRING_WIDTH:
      param = 0.3;
      parammin = 0.0;
      parammax = 0.5;
      break;
    default:
      error(EXIT_FAILURE, "*Internal Error*: Unknown profile parameter in ",
		"profit_resetparam()");
      break;
   }

  if (parammin!=parammax && (param<=parammin || param>=parammax))
    param = (parammin+parammax)/2.0;
  profit_setparam(profit, paramtype, param, parammin, parammax);

  return;
  }


/****** profit_resetparams ****************************************************
PROTO	void profit_resetparams(profitstruct *profit)
PURPOSE	Set the initial, lower and upper boundary values of profile parameters.
INPUT	Pointer to the profit structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	18/09/2008
 ***/
void	profit_resetparams(profitstruct *profit)
  {
   int		p;


  for (p=0; p<PARAM_NPARAM; p++)
    profit_resetparam(profit, (paramenum)p);

  return;
  }


/****** profit_setparam ****************************************************
PROTO	void profit_setparam(profitstruct *profit, paramenum paramtype,
2085
		float param, float parammin, float parammax)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2086
2087
2088
2089
2090
2091
2092
2093
PURPOSE	Set the actual, lower and upper boundary values of a profile parameter.
INPUT	Pointer to the profit structure,
	Parameter index,
	Actual value,
	Lower boundary to the parameter,
	Upper boundary to the parameter.
OUTPUT	RETURN_OK if the parameter is registered, RETURN_ERROR otherwise.
AUTHOR	E. Bertin (IAP)
2094
VERSION	15/03/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2095
2096
 ***/
int	profit_setparam(profitstruct *profit, paramenum paramtype,
2097
		float param, float parammin, float parammax)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2098
  {
2099
   float	*paramptr;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2100
2101
2102
2103
2104
   int		index;

/* Check whether the parameter has already be registered */
  if ((paramptr=profit->paramlist[(int)paramtype]))
    {
2105
    index = profit->paramindex[(int)paramtype];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
    profit->paraminit[index] = param;
    profit->parammin[index] = parammin;
    profit->parammax[index] = parammax;
    return RETURN_OK;
    }
  else
    return RETURN_ERROR;
  }

  
/****** profit_boundtounbound *************************************************
2117
PROTO	void profit_boundtounbound(profitstruct *profit, float *param)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2118
2119
2120
2121
2122
PURPOSE	Convert parameters from bounded to unbounded space.
INPUT	Pointer to the profit structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
2123
VERSION	07/09/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2124
 ***/
2125
void	profit_boundtounbound(profitstruct *profit, float *param)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2126
2127
2128
2129
2130
2131
2132
2133
2134
  {
   double	num,den;
   int		p;

  for (p=0; p<profit->nparam; p++)
    if (profit->parammin[p]!=profit->parammax[p])
      {
      num = param[p] - profit->parammin[p];
      den = profit->parammax[p] - param[p];
2135
      param[p] = num>1e-50? (den>1e-50? log(num/den): 50.0) : -50.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2136
2137
2138
2139
2140
2141
2142
2143
      }

  return;

  }


/****** profit_unboundtobound *************************************************
2144
PROTO	void profit_unboundtobound(profitstruct *profit, float *param)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2145
2146
2147
2148
2149
PURPOSE	Convert parameters from unbounded to bounded space.
INPUT	Pointer to the profit structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
2150
VERSION	18/05/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2151
 ***/
2152
void	profit_unboundtobound(profitstruct *profit, float *param)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2153
2154
2155
2156
2157
2158
  {
   int		p;

  for (p=0; p<profit->nparam; p++)
    if (profit->parammin[p]!=profit->parammax[p])
      param[p] = (profit->parammax[p] - profit->parammin[p])
2159
		/ (1.0 + exp(-(param[p]>50.0? 50.0 : param[p])))
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
		+ profit->parammin[p];

  return;
  }


/****** profit_covarunboundtobound ********************************************
PROTO	void profit_covarunboundtobound(profitstruct *profit)
PURPOSE	Convert covariance matrix from unbounded to bounded space.
INPUT	Pointer to the profit structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
2173
VERSION	02/10/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2174
2175
2176
 ***/
void	profit_covarunboundtobound(profitstruct *profit)
  {
2177
2178
2179
   double	*dxdy,
		dxmin,dxmax;
   float	*covar, *x,*xmin,*xmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2180
2181
2182
   int		p,p1,p2, nparam;

  nparam = profit->nparam;
2183
  QMALLOC16(dxdy, double, nparam);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
  x = profit->paraminit;
  xmin = profit->parammin;
  xmax = profit->parammax;
  for (p=0; p<profit->nparam; p++)
    if (xmin[p]!=xmax[p])
      {
      dxmin = x[p] - xmin[p];
      dxmax= xmax[p] - x[p];
      dxdy[p] = (fabs(dxmin) < 1.0/BIG && fabs(dxmax) < 1.0/BIG) ?
		0.0 : dxmin*dxmax/(dxmin+dxmax);
      }
    else
      dxdy[p] = 1.0;

  covar = profit->covar;
  for (p2=0; p2<nparam; p2++)
    for (p1=0; p1<nparam; p1++)
2201
      *(covar++) *= (float)(dxdy[p1]*dxdy[p2]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221

  free(dxdy);

  return;
  }


/****** prof_init *************************************************************
PROTO	profstruct prof_init(profitstruct *profit, proftypenum profcode)
PURPOSE	Allocate and initialize a new profile structure.
INPUT	Pointer to the profile-fitting structure,
	profile type.
OUTPUT	A pointer to an allocated prof structure.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	22/04/2008
 ***/
profstruct	*prof_init(profitstruct *profit, proftypenum profcode)
  {
   profstruct	*prof;
2222
   float	*pix,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
		rmax2, re2, dy2,r2, scale, zero, k,n, hinvn;
   int		width,height, ixc,iyc, ix,iy, nsub,
		d,s;

  QCALLOC(prof, profstruct, 1);
  prof->code = profcode;
  switch(profcode)
    {
    case PROF_BACK:
      prof->naxis = 2;
      prof->pix = NULL;
      profit_addparam(profit, PARAM_BACK, &prof->flux);
      prof->typscale = 1.0;
      break;
    case PROF_SERSIC:
      prof->naxis = 3;
      prof->pix = NULL;
      prof->typscale = 1.0;
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_SPHEROID_FLUX, &prof->flux);
      profit_addparam(profit, PARAM_SPHEROID_REFF, &prof->scale);
      profit_addparam(profit, PARAM_SPHEROID_ASPECT, &prof->aspect);
      profit_addparam(profit, PARAM_SPHEROID_POSANG, &prof->posangle);
      profit_addparam(profit, PARAM_SPHEROID_SERSICN, &prof->extra[0]);
      break;
    case PROF_DEVAUCOULEURS:
      prof->naxis = 2;
      prof->pix = NULL;
      prof->typscale = 1.0;
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_SPHEROID_FLUX, &prof->flux);
      profit_addparam(profit, PARAM_SPHEROID_REFF, &prof->scale);
      profit_addparam(profit, PARAM_SPHEROID_ASPECT, &prof->aspect);
      profit_addparam(profit, PARAM_SPHEROID_POSANG, &prof->posangle);
      break;
    case PROF_EXPONENTIAL:
      prof->naxis = 2;
      prof->pix = NULL;
      prof->typscale = 1.0;
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_DISK_FLUX, &prof->flux);
      profit_addparam(profit, PARAM_DISK_SCALE, &prof->scale);
      profit_addparam(profit, PARAM_DISK_ASPECT, &prof->aspect);
      profit_addparam(profit, PARAM_DISK_POSANG, &prof->posangle);
      break;
    case PROF_ARMS:
      prof->naxis = 2;
      prof->pix = NULL;
      prof->typscale = 1.0;
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_DISK_SCALE, &prof->scale);
      profit_addparam(profit, PARAM_DISK_ASPECT, &prof->aspect);
      profit_addparam(profit, PARAM_DISK_POSANG, &prof->posangle);
      profit_addparam(profit, PARAM_ARMS_FLUX, &prof->flux);
      profit_addparam(profit, PARAM_ARMS_QUADFRAC, &prof->featfrac);
//      profit_addparam(profit, PARAM_ARMS_SCALE, &prof->featscale);
      profit_addparam(profit, PARAM_ARMS_START, &prof->featstart);
      profit_addparam(profit, PARAM_ARMS_PITCH, &prof->featpitch);
//      profit_addparam(profit, PARAM_ARMS_PITCHVAR, &prof->featpitchvar);
      profit_addparam(profit, PARAM_ARMS_POSANG, &prof->featposang);
//      profit_addparam(profit, PARAM_ARMS_WIDTH, &prof->featwidth);
      break;
    case PROF_BAR:
      prof->naxis = 2;
      prof->pix = NULL;
      prof->typscale = 1.0;
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_DISK_SCALE, &prof->scale);
      profit_addparam(profit, PARAM_DISK_ASPECT, &prof->aspect);
      profit_addparam(profit, PARAM_DISK_POSANG, &prof->posangle);
      profit_addparam(profit, PARAM_ARMS_START, &prof->featstart);
      profit_addparam(profit, PARAM_BAR_FLUX, &prof->flux);
      profit_addparam(profit, PARAM_BAR_ASPECT, &prof->feataspect);
      profit_addparam(profit, PARAM_ARMS_POSANG, &prof->featposang);
      break;
    case PROF_INRING:
      prof->naxis = 2;
      prof->pix = NULL;
      prof->typscale = 1.0;
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_DISK_SCALE, &prof->scale);
      profit_addparam(profit, PARAM_DISK_ASPECT, &prof->aspect);
      profit_addparam(profit, PARAM_DISK_POSANG, &prof->posangle);
      profit_addparam(profit, PARAM_ARMS_START, &prof->featstart);
      profit_addparam(profit, PARAM_INRING_FLUX, &prof->flux);
      profit_addparam(profit, PARAM_INRING_WIDTH, &prof->featwidth);
      profit_addparam(profit, PARAM_INRING_ASPECT, &prof->feataspect);
      break;
    case PROF_OUTRING:
      prof->naxis = 2;
      prof->pix = NULL;
      prof->typscale = 1.0;
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_DISK_SCALE, &prof->scale);
      profit_addparam(profit, PARAM_DISK_ASPECT, &prof->aspect);
      profit_addparam(profit, PARAM_DISK_POSANG, &prof->posangle);
      profit_addparam(profit, PARAM_OUTRING_START, &prof->featstart);
      profit_addparam(profit, PARAM_OUTRING_FLUX, &prof->flux);
      profit_addparam(profit, PARAM_OUTRING_WIDTH, &prof->featwidth);
      break;
2330
2331
2332
2333
2334
2335
2336
2337
    case PROF_DIRAC:
      prof->naxis = 2;
      prof->pix = NULL;
      prof->typscale = 1.0;
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_DISK_FLUX, &prof->flux);
      break;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2338
2339
2340
2341
2342
    case PROF_SERSIC_TABEX:	/* An example of tabulated profile */
      prof->naxis = 3;
      width =  prof->naxisn[0] = PROFIT_PROFRES;
      height = prof->naxisn[1] = PROFIT_PROFRES;
      nsub = prof->naxisn[2] = PROFIT_PROFSRES;
2343
      QCALLOC(prof->pix, float, width*height*nsub);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
      ixc = width/2;
      iyc = height/2;
      rmax2 = (ixc - 1.0)*(ixc - 1.0);
      re2 = width/64.0;
      prof->typscale = re2;
      re2 *= re2;
      zero = prof->extrazero[0] = 0.2;
      scale = prof->extrascale[0]= 8.0/PROFIT_PROFSRES;
      pix = prof->pix;
      for (s=0; s<nsub; s++)
        {
        n = s*scale + zero;
        hinvn = 0.5/n;
        k = -1.0/3.0 + 2.0*n + 4.0/(405.0*n) + 46.0/(25515.0*n*n)
		+ 131.0/(1148175*n*n*n);
        for (iy=0; iy<height; iy++)
          {
          dy2 = (iy-iyc)*(iy-iyc);
          for (ix=0; ix<width; ix++)
            {
            r2 = dy2 + (ix-ixc)*(ix-ixc);
            *(pix++) = (r2<rmax2)? exp(-k*pow(r2/re2,hinvn)) : 0.0;
            }
          }
        }
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_SPHEROID_FLUX, &prof->flux);
      profit_addparam(profit, PARAM_SPHEROID_REFF, &prof->scale);
      profit_addparam(profit, PARAM_SPHEROID_ASPECT, &prof->aspect);
      profit_addparam(profit, PARAM_SPHEROID_POSANG, &prof->posangle);
      profit_addparam(profit, PARAM_SPHEROID_SERSICN, &prof->extra[0]);
      break;
    default:
      error(EXIT_FAILURE, "*Internal Error*: Unknown profile in ",
		"prof_init()");
      break;
    }

  if (prof->pix)
    {
    prof->kernelnlines = 1;
    for (d=0; d<prof->naxis; d++)
      {
      prof->interptype[d] = INTERP_BILINEAR;
      prof->kernelnlines *= 
	(prof->kernelwidth[d] = interp_kernwidth[prof->interptype[d]]);
      }
    prof->kernelnlines /= prof->kernelwidth[0];
2393
    QMALLOC16(prof->kernelbuf, float, prof->kernelnlines);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
    }

  return prof;
  }  


/****** prof_end **************************************************************
PROTO	void prof_end(profstruct *prof)
PURPOSE	End (deallocate) a profile structure.
INPUT	Prof structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	09/04/2007
 ***/
void	prof_end(profstruct *prof)
  {
  if (prof->pix)
    {
    free(prof->pix);
    free(prof->kernelbuf);
    }
  free(prof);

  return;
  }


/****** prof_add **************************************************************
2423
PROTO	float prof_add(profstruct *prof, profitstruct *profit)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2424
2425
2426
PURPOSE	Add a model profile to an image.
INPUT	Profile structure,
	profile-fitting structure.
2427
OUTPUT	Corrected flux contribution.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2428
2429
NOTES	-.
AUTHOR	E. Bertin (IAP)
2430
VERSION	09/10/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2431
 ***/
2432
float	prof_add(profstruct *prof, profitstruct *profit)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2433
  {
2434
   double	xscale, yscale, saspect, ctheta,stheta, flux, scaling, bn, n;
2435
   float	posin[PROFIT_MAXEXTRA], posout[2], dnaxisn[2],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2436
		*pixin, *pixin2, *pixout,
2437
		fluxfac, amp,cd11,cd12,cd21,cd22, dcd11,dcd21, dx1,dx2,
2438
		x1,x10,x2, x1cin,x2cin, x1cout,x2cout, x1max,x2max,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2439
		x1in,x2in, odx, ostep,
2440
		k, hinvn, x1t,x2t, ca,sa, u,umin,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2441
2442
		armamp,arm2amp, armrdphidr, armrdphidrvar, posang,
		width, invwidth2,
2443
2444
2445
2446
		r,r2,rmin, r2minxin,r2minxout, rmax, r2max,
		r2max1, r2max2, r2min, invr2xdif,
		val, theta, thresh, ra,rb,rao, num;
   int		npix, noversamp, threshflag,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2447
		d,e,i, ix1,ix2, idx1,idx2, nx2, npix2;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2448
2449
2450
2451
2452
2453
2454
2455
2456

  npix = profit->modnaxisn[0]*profit->modnaxisn[1];

  if (prof->code==PROF_BACK)
    {
    amp = fabs(*prof->flux);
    pixout = profit->modpix;
    for (i=npix; i--;)
      *(pixout++) += amp;
2457
2458
    prof->lostfluxfrac = 0.0;
    return 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2459
2460
2461
2462
    }

  scaling = profit->pixstep / prof->typscale;

2463
2464
2465
2466
2467
2468
2469
  if (prof->code!=PROF_DIRAC)
    {
/*-- Compute Profile CD matrix */
    ctheta = cos(*prof->posangle*DEG);
    stheta = sin(*prof->posangle*DEG);
    saspect = fabs(*prof->aspect);
    xscale = (*prof->scale==0.0)?
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2470
		0.0 : fabs(scaling / (*prof->scale*prof->typscale));
2471
    yscale = (*prof->scale*saspect == 0.0)?
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2472
		0.0 : fabs(scaling / (*prof->scale*prof->typscale*saspect));
2473
2474
2475
2476
    cd11 = (float)(xscale*ctheta);
    cd12 = (float)(xscale*stheta);
    cd21 = (float)(-yscale*stheta);
    cd22 = (float)(yscale*ctheta);
2477
2478
2479
2480
2481
    dx1 = 0.0;	/* Shifting operations have been moved to profit_resample() */
    dx2 = 0.0;	/* Shifting operations have been moved to profit_resample() */

    x1cout = (float)(profit->modnaxisn[0]/2);
    x2cout = (float)(profit->modnaxisn[1]/2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2482
    nx2 = profit->modnaxisn[1]/2 + 1;
2483
2484
2485
2486
2487
2488
2489
2490

/*-- Compute the largest r^2 that fits in the frame */
    num = cd11*cd22-cd12*cd21;
    x1max = x1cout - 1.0;
    x2max = x2cout - 1.0;
    r2max1 = x1max*x1max*fabs(num*num / (cd12*cd12+cd22*cd22));
    r2max2 = x2max*x2max*fabs(num*num / (cd11*cd11+cd21*cd21));
    r2max = r2max1 < r2max2? r2max1 : r2max2;
2491
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2492
2493
2494
2495
2496

  switch(prof->code)
    {
    case PROF_SERSIC:
      n = fabs(*prof->extra[0]);
2497
2498
2499
      bn = 2.0*n - 1.0/3.0 + 4.0/(405.0*n) + 46.0/(25515.0*n*n)
		+ 131.0/(1148175*n*n*n);	/* Ciotti & Bertin 1999 */
      k = -bn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2500
2501
2502
2503
2504
      hinvn = 0.5/n;
/*---- The consequence of sampling on flux is compensated by PSF normalisation*/
      x10 = -x1cout - dx1;
      x2 = -x2cout - dx2;
      pixin = profit->pmodpix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2505
      for (ix2=nx2; ix2--; x2+=1.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2506
2507
2508
2509
2510
2511
2512
        {
        x1 = x10;
        for (ix1=profit->modnaxisn[0]; ix1--; x1+=1.0)
          {
          x1in = cd12*x2 + cd11*x1;
          x2in = cd22*x2 + cd21*x1;
          ra = x1in*x1in+x2in*x2in;
2513
2514
2515
2516
2517
          if (ra>r2max)
            {
            *(pixin++) = 0.0;
            continue;
            }
2518
          val = expf(k*expf(logf(ra)*hinvn));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
          noversamp  = (int)(val*PROFIT_OVERSAMP+0.1);
          if (noversamp < 2)
            *(pixin++) = val;
          else
            {
            ostep = 1.0/noversamp;
            dcd11 = cd11*ostep;
            dcd21 = cd21*ostep;
            odx = 0.5*(ostep-1.0);
            x1t = x1+odx;
            val = 0.0;
            for (idx2=noversamp; idx2--; odx+=ostep)
              {
              x1in = cd12*(x2+odx) + cd11*x1t;
              x2in = cd22*(x2+odx) + cd21*x1t;
              for (idx1=noversamp; idx1--;)
                {
2536
2537
                rao = x1in*x1in+x2in*x2in;
                val += expf(k*PROFIT_POWF(rao,hinvn));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2538
2539
2540
2541
2542
2543
2544
2545
                x1in += dcd11;
                x2in += dcd21;
                }
              }
            *(pixin++) = val*ostep*ostep;
            }
          }
        }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2546
2547
2548
/*---- Copy the symmetric part */
      if ((npix2=(profit->modnaxisn[1]-nx2)*profit->modnaxisn[0]) > 0)
        {
2549
        pixin2 = pixin - profit->modnaxisn[0];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2550
2551
2552
        for (i=npix2; i--;)
          *(pixin++) = *(pixin2--);
        }
2553
2554
      prof->lostfluxfrac = 1.0 - prof_gammainc(2.0*n, bn*pow(r2max, hinvn));
      threshflag = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2555
2556
2557
2558
2559
2560
      break;
    case PROF_DEVAUCOULEURS:
/*---- The consequence of sampling on flux is compensated by PSF normalisation*/
      x10 = -x1cout - dx1;
      x2 = -x2cout - dx2;
      pixin = profit->pmodpix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2561
      for (ix2=nx2; ix2--; x2+=1.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2562
2563
2564
2565
2566
2567
2568
        {
        x1 = x10;
        for (ix1=profit->modnaxisn[0]; ix1--; x1+=1.0)
          {
          x1in = cd12*x2 + cd11*x1;
          x2in = cd22*x2 + cd21*x1;
          ra = x1in*x1in+x2in*x2in;
2569
2570
2571
2572
2573
2574
          if (ra>r2max)
            {
            *(pixin++) = 0.0;
            continue;
            }
          val = expf(-7.66924944f*PROFIT_POWF(ra,0.125));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
          noversamp  = (int)(sqrt(val)*PROFIT_OVERSAMP+0.1);
          if (noversamp < 2)
            *(pixin++) = val;
          else
            {
            ostep = 1.0/noversamp;
            dcd11 = cd11*ostep;
            dcd21 = cd21*ostep;
            odx = 0.5*(ostep-1.0);
            x1t = x1+odx;
            val = 0.0;
            for (idx2=noversamp; idx2--; odx+=ostep)
              {
              x1in = cd12*(x2+odx) + cd11*x1t;
              x2in = cd22*(x2+odx) + cd21*x1t;
              for (idx1=noversamp; idx1--;)
                {
                ra = x1in*x1in+x2in*x2in;
2593
                val += expf(-7.66924944f*PROFIT_POWF(ra,0.125));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2594
2595
2596
2597
2598
2599
2600
2601
                x1in += dcd11;
                x2in += dcd21;
                }
              }
            *(pixin++) = val*ostep*ostep;
            }
          }
        }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2602
2603
2604
/*---- Copy the symmetric part */
      if ((npix2=(profit->modnaxisn[1]-nx2)*profit->modnaxisn[0]) > 0)
        {
2605
        pixin2 = pixin - profit->modnaxisn[0];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2606
2607
2608
        for (i=npix2; i--;)
          *(pixin++) = *(pixin2--);
        }
2609
2610
      prof->lostfluxfrac = 1.0-prof_gammainc(8.0, 7.66924944*pow(r2max, 0.125));
      threshflag = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2611
2612
      break;
    case PROF_EXPONENTIAL:
2613
      x10 = -x1cout - dx1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2614
2615
      x2 = -x2cout - dx2;
      pixin = profit->pmodpix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2616
      for (ix2=nx2; ix2--; x2+=1.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2617
        {
2618
2619
        x1 = x10;
        for (ix1=profit->modnaxisn[0]; ix1--; x1+=1.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2620
          {
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
          x1in = cd12*x2 + cd11*x1;
          x2in = cd22*x2 + cd21*x1;
          ra = x1in*x1in+x2in*x2in;
          if (ra>r2max)
            {
            *(pixin++) = 0.0;
            continue;
            }
          val = expf(-sqrtf(ra));
          noversamp  = (int)(val*sqrt(PROFIT_OVERSAMP)+0.1);
          if (noversamp < 2)
            *(pixin++) = val;
          else
            {
            ostep = 1.0/noversamp;
            dcd11 = cd11*ostep;
            dcd21 = cd21*ostep;
            odx = 0.5*(ostep-1.0);
            x1t = x1+odx;
            val = 0.0;
            for (idx2=noversamp; idx2--; odx+=ostep)
              {
              x1in = cd12*(x2+odx) + cd11*x1t;
              x2in = cd22*(x2+odx) + cd21*x1t;
              for (idx1=noversamp; idx1--;)
                {
                ra = x1in*x1in+x2in*x2in;
                val += expf(-sqrtf(ra));
                x1in += dcd11;
                x2in += dcd21;
                }
              }
            *(pixin++) = val*ostep*ostep;
            }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2655
2656
          }
        }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2657
2658
2659
/*---- Copy the symmetric part */
      if ((npix2=(profit->modnaxisn[1]-nx2)*profit->modnaxisn[0]) > 0)
        {
2660
        pixin2 = pixin - profit->modnaxisn[0];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2661
2662
2663
        for (i=npix2; i--;)
          *(pixin++) = *(pixin2--);
        }
2664
2665
2666
      rmax = sqrt(r2max);
      prof->lostfluxfrac = (1.0 + rmax)*exp(-rmax);
      threshflag = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
      break;
    case PROF_ARMS:
      r2min = *prof->featstart**prof->featstart;
      r2minxin = r2min * (1.0 - PROFIT_BARXFADE) * (1.0 - PROFIT_BARXFADE);
      r2minxout = r2min * (1.0 + PROFIT_BARXFADE) * (1.0 + PROFIT_BARXFADE);
      if ((invr2xdif = (r2minxout - r2minxin)) > 0.0)
        invr2xdif = 1.0 / invr2xdif;
      else
        invr2xdif = 1.0;
      umin = 0.5*logf(r2minxin + 0.00001);
      arm2amp = *prof->featfrac;
      armamp = 1.0 - arm2amp;
      armrdphidr = 1.0/tan(*prof->featpitch*DEG);
      armrdphidrvar = 0.0 /**prof->featpitchvar*/;
      posang = *prof->featposang*DEG;
      width = fabs(*prof->featwidth);
width = 3.0;
      x1 = -x1cout - dx1;
      x2 = -x2cout - dx2;
      pixin = profit->pmodpix;
      for (ix2=profit->modnaxisn[1]; ix2--; x2+=1.0)
        {
        x1t = cd12*x2 + cd11*x1;
        x2t = cd22*x2 + cd21*x1;
        for (ix1=profit->modnaxisn[0]; ix1--;)
          {
          r2 = x1t*x1t+x2t*x2t;
          if (r2>r2minxin)
            {
            u = 0.5*logf(r2 + 0.00001);
            theta = (armrdphidr+armrdphidrvar*(u-umin))*u+posang;
            ca = cosf(theta);
            sa = sinf(theta);
            x1in = (x1t*ca - x2t*sa);
            x2in = (x1t*sa + x2t*ca);
            amp = expf(-sqrtf(x1t*x1t+x2t*x2t));
            if (r2<r2minxout)
              amp *= (r2 - r2minxin)*invr2xdif;
            ra = x1in*x1in/r2;
            rb = x2in*x2in/r2;
            *(pixin++) = amp * (armamp*PROFIT_POWF(ra,width)
				+ arm2amp*PROFIT_POWF(rb,width));
            }
          else
            *(pixin++) = 0.0;
          x1t += cd11;
          x2t += cd21; 
         }
        }
2716
2717
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
      break;
    case PROF_BAR:
      r2min = *prof->featstart**prof->featstart;
      r2minxin = r2min * (1.0 - PROFIT_BARXFADE) * (1.0 - PROFIT_BARXFADE);
      r2minxout = r2min * (1.0 + PROFIT_BARXFADE) * (1.0 + PROFIT_BARXFADE);
      if ((invr2xdif = (r2minxout - r2minxin)) > 0.0)
        invr2xdif = 1.0 / invr2xdif;
      else
        invr2xdif = 1.0;
      invwidth2 = fabs(1.0 / (*prof->featstart**prof->feataspect));
      posang = *prof->featposang*DEG;
      ca = cosf(posang);
      sa = sinf(posang);
      x1 = -x1cout - dx1;
      x2 = -x2cout - dx2;
      pixin = profit->pmodpix;
      for (ix2=profit->modnaxisn[1]; ix2--; x2+=1.0)
        {
        x1t = cd12*x2 + cd11*x1;
        x2t = cd22*x2 + cd21*x1;
        for (ix1=profit->modnaxisn[0]; ix1--;)
          {
          r2 = x1t*x1t+x2t*x2t;
          if (r2<r2minxout)
            {
            x1in = x1t*ca - x2t*sa;
            x2in = invwidth2*(x1t*sa + x2t*ca);
            *(pixin++) = (r2>r2minxin) ?
				(r2minxout - r2)*invr2xdif*expf(-x2in*x2in)
				: expf(-x2in*x2in);
            }
          else
            *(pixin++) = 0.0;
          x1t += cd11;
          x2t += cd21;
          }
        }
2755
2756
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
      break;
    case PROF_INRING:
      rmin = *prof->featstart;
      r2minxin = *prof->featstart-4.0**prof->featwidth;
      if (r2minxin < 0.0)
        r2minxin = 0.0;
      r2minxin *= r2minxin;
      r2minxout = *prof->featstart+4.0**prof->featwidth;
      r2minxout *= r2minxout;
      invwidth2 = 0.5 / (*prof->featwidth**prof->featwidth);
      cd22 /= *prof->feataspect;
      cd21 /= *prof->feataspect;
      x1 = -x1cout - dx1;
      x2 = -x2cout - dx2;
      pixin = profit->pmodpix;
      for (ix2=profit->modnaxisn[1]; ix2--; x2+=1.0)
        {
        x1t = cd12*x2 + cd11*x1;
        x2t = cd22*x2 + cd21*x1;
        for (ix1=profit->modnaxisn[0]; ix1--;)
          {
          r2 = x1t*x1t+x2t*x2t;
          if (r2>r2minxin && r2<r2minxout)
            {
            r = sqrt(r2) - rmin;
            *(pixin++) = expf(-invwidth2*r*r);
            }
          else
            *(pixin++) = 0.0;
          x1t += cd11;
          x2t += cd21;
          }
        }
2790
2791
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
      break;
    case PROF_OUTRING:
      rmin = *prof->featstart;
      r2minxin = *prof->featstart-4.0**prof->featwidth;
      if (r2minxin < 0.0)
        r2minxin = 0.0;
      r2minxin *= r2minxin;
      r2minxout = *prof->featstart+4.0**prof->featwidth;
      r2minxout *= r2minxout;
      invwidth2 = 0.5 / (*prof->featwidth**prof->featwidth);
      x1 = -x1cout - dx1;
      x2 = -x2cout - dx2;
      pixin = profit->pmodpix;
      for (ix2=profit->modnaxisn[1]; ix2--; x2+=1.0)
        {
        x1t = cd12*x2 + cd11*x1;
        x2t = cd22*x2 + cd21*x1;
        for (ix1=profit->modnaxisn[0]; ix1--;)
          {
          r2 = x1t*x1t+x2t*x2t;
          if (r2>r2minxin && r2<r2minxout)
            {
            r = sqrt(r2) - rmin;
            *(pixin++) = expf(-invwidth2*r*r);
            }
          else
            *(pixin++) = 0.0;
          x1t += cd11;
          x2t += cd21;
          }
        }
2823
2824
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2825
      break;
2826
2827
2828
2829
2830
    case PROF_DIRAC:
      memset(profit->pmodpix, 0,
	profit->modnaxisn[0]*profit->modnaxisn[1]*sizeof(float));
      profit->pmodpix[profit->modnaxisn[0]/2
		+ (profit->modnaxisn[1]/2)*profit->modnaxisn[0]] = 1.0;
2831
2832
      prof->lostfluxfrac = 0.0;
      threshflag = 0;
2833
      break;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
    default:
/*---- Tabulated profile: remap each pixel */
/*---- Initialize multi-dimensional counters */
     for (d=0; d<2; d++)
        {
        posout[d] = 1.0;	/* FITS convention */
        dnaxisn[d] = profit->modnaxisn[d] + 0.99999;
        }

      for (e=0; e<prof->naxis - 2; e++)
        {
        d = 2+e;
/*------ Compute position along axis */
        posin[d] = (*prof->extra[e]-prof->extrazero[e])/prof->extrascale[e]+1.0;
/*------ Keep position within boundaries and let interpolation do the rest */
        if (posin[d] < 0.99999)
          {
          if (prof->extracycleflag[e])
2852
            posin[d] += (float)prof->naxisn[d];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2853
2854
2855
          else
            posin[d] = 1.0;
          }
2856
        else if (posin[d] > (float)prof->naxisn[d])
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2857
2858
2859
          {
          if (prof->extracycleflag[e])
          posin[d] = (prof->extracycleflag[e])?
2860
2861
		  fmod(posin[d], (float)prof->naxisn[d])
		: (float)prof->naxisn[d];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2862
2863
          }
        }
2864
2865
      x1cin = (float)(prof->naxisn[0]/2);
      x2cin = (float)(prof->naxisn[1]/2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
      pixin = profit->pmodpix;
      for (i=npix; i--;)
        {
        x1 = posout[0] - x1cout - 1.0 - dx1;
        x2 = posout[1] - x2cout - 1.0 - dx2;
        posin[0] = cd11*x1 + cd12*x2 + x1cin + 1.0;
        posin[1] = cd21*x1 + cd22*x2 + x2cin + 1.0;
        *(pixin++) = prof_interpolate(prof, posin);
        for (d=0; d<2; d++)
          if ((posout[d]+=1.0) < dnaxisn[d])
            break;
          else
            posout[d] = 1.0;
        }
2880
2881
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2882
2883
2884
    break;
    }

2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
/* For complex profiles, threshold to the brightest pixel value at border */
  if (threshflag)
    {
/*-- Now find truncation threshold */
/*-- Find the shortest distance to a vignet border */
    rmax = x1cout;
    if (rmax > (r = x2cout))
      rmax = r;
    rmax += 0.01;
    if (rmax<1.0)
      rmax = 1.0;
    r2max = rmax*rmax;
    rmin = rmax - 1.0;
    r2min = rmin*rmin;

/*-- Find best threshold (the max around the circle with radius rmax */
    dx2 = -x2cout;
    pixin = profit->pmodpix;
    thresh = -BIG;
    for (ix2=profit->modnaxisn[1]; ix2--; dx2 += 1.0)
      {
      dx1 = -x1cout;
      for (ix1=profit->modnaxisn[0]; ix1--; dx1 += 1.0)
        if ((val=*(pixin++))>thresh && (r2=dx1*dx1+dx2*dx2)>r2min && r2<r2max)
          thresh = val;
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2911

2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
/*-- Threshold and measure the flux */
    flux = 0.0;
    pixin = profit->pmodpix;
    for (i=npix; i--; pixin++)
      if (*pixin >= thresh)
        flux += (double)*pixin;
      else
        *pixin = 0.0;
    }
  else
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2922
    {
2923
2924
2925
2926
    flux = 0.0;
    pixin = profit->pmodpix;
    for (i=npix; i--;)
      flux += (double)*(pixin++);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2927
2928
    }

2929
2930
  if (prof->lostfluxfrac < 1.0)
    flux /= (1.0 - prof->lostfluxfrac);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2931
2932

/* Correct final flux */
2933
2934
2935
  fluxfac = profit->fluxfac ;
  fluxfac *= fabs(flux)>0.0? *prof->flux / flux : 1.0;
//  prof->fluxfac = fluxfac;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2936
2937
  pixin = profit->pmodpix;
  pixout = profit->modpix;
2938
  for (i=npix; i--;)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2939
2940
    *(pixout++) += fluxfac * *(pixin++);

2941
  return *prof->flux;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2942
2943
2944
2945
  }


/****** prof_interpolate ******************************************************
2946
PROTO	float	prof_interpolate(profstruct *prof, float *posin)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2947
2948
2949
2950
2951
2952
2953
2954
PURPOSE	Interpolate a multidimensional model profile at a given position.
INPUT	Profile structure,
	input position vector.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	10/12/2006
 ***/
2955
static float	prof_interpolate(profstruct *prof, float *posin)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2956
  {
2957
   float		dpos[2+PROFIT_MAXEXTRA],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
			kernel_vector[INTERP_MAXKERNELWIDTH],
			*kvector, *pixin,*pixout,
			val;
   long			step[2+PROFIT_MAXEXTRA],
			start, fac;
   int			linecount[2+PROFIT_MAXEXTRA],
			*naxisn,
			i,j,n, ival, nlines, kwidth,width, badpixflag, naxis;

  naxis = prof->naxis;
  naxisn = prof->naxisn;
  start = 0;
  fac = 1;
  for (n=0; n<naxis; n++)
    {
    val = *(posin++);
    width = *(naxisn++);
/*-- Get the integer part of the current coordinate or nearest neighbour */
    ival = (prof->interptype[n]==INTERP_NEARESTNEIGHBOUR)?
                                        (int)(val-0.50001):(int)val;
/*-- Store the fractional part of the current coordinate */
    dpos[n] = val - ival;
/*-- Check if interpolation start/end exceed image boundary... */
    kwidth = prof->kernelwidth[n];
    ival-=kwidth/2;
    if (ival<0 || ival+kwidth<=0 || ival+kwidth>width)
      return 0.0;

/*-- Update starting pointer */
    start += ival*fac;
/*-- Update step between interpolated regions */
    step[n] = fac*(width-kwidth);
    linecount[n] = 0.0;
    fac *= width;
    }

/* Update Interpolation kernel vectors */
  make_kernel(*dpos, kernel_vector, prof->interptype[0]);
  kwidth = prof->kernelwidth[0];
  nlines = prof->kernelnlines;
/* First step: interpolate along NAXIS1 from the data themselves */
  badpixflag = 0;
  pixin = prof->pix+start;
  pixout = prof->kernelbuf;
  for (j=nlines; j--;)
    {
    val = 0.0;
    kvector = kernel_vector;
    for (i=kwidth; i--;)
       val += *(kvector++)**(pixin++);
    *(pixout++) = val;
    for (n=1; n<naxis; n++)
      {
      pixin+=step[n-1];
      if (++linecount[n]<prof->kernelwidth[n])
        break;
      else
        linecount[n] = 0;       /* No need to initialize it to 0! */
      }
    }

/* Second step: interpolate along other axes from the interpolation buffer */
  for (n=1; n<naxis; n++)
    {
    make_kernel(dpos[n], kernel_vector, prof->interptype[n]);
    kwidth = prof->kernelwidth[n];
    pixout = pixin = prof->kernelbuf;
    for (j = (nlines/=kwidth); j--;)
      {
      val = 0.0;
      kvector = kernel_vector;
      for (i=kwidth; i--;)
        val += *(kvector++)**(pixin++);
      *(pixout++) = val;
     }
    }

  return prof->kernelbuf[0];
  }


/****** interpolate_pix ******************************************************
3040
PROTO	void interpolate_pix(float *posin, float *pix, int naxisn,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
		interpenum interptype)
PURPOSE	Interpolate a model profile at a given position.
INPUT	Profile structure,
	input position vector,
	input pixmap dimension vector,
	interpolation type.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	07/12/2006
 ***/
3052
static float	interpolate_pix(float *posin, float *pix, int *naxisn,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3053
3054
			interpenum interptype)
  {
3055
   float	buffer[INTERP_MAXKERNELWIDTH],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
		kernel[INTERP_MAXKERNELWIDTH], dpos[2],
		*kvector, *pixin, *pixout,
		val;
   int		fac, ival, kwidth, start, width, step,
		i,j, n;

  kwidth = interp_kernwidth[interptype];
  start = 0;
  fac = 1;
  for (n=0; n<2; n++)
    {
    val = *(posin++);
    width = naxisn[n];
/*-- Get the integer part of the current coordinate or nearest neighbour */
    ival = (interptype==INTERP_NEARESTNEIGHBOUR)? (int)(val-0.50001):(int)val;
/*-- Store the fractional part of the current coordinate */
    dpos[n] = val - ival;
/*-- Check if interpolation start/end exceed image boundary... */
    ival-=kwidth/2;
    if (ival<0 || ival+kwidth<=0 || ival+kwidth>width)
      return 0.0;
/*-- Update starting pointer */
    start += ival*fac;
/*-- Update step between interpolated regions */
    fac *= width;
    }

/* First step: interpolate along NAXIS1 from the data themselves */
  make_kernel(dpos[0], kernel, interptype);
  step = naxisn[0]-kwidth;
  pixin = pix+start;
  pixout = buffer;
  for (j=kwidth; j--;)
    {
    val = 0.0;
    kvector = kernel;
    for (i=kwidth; i--;)
      val += *(kvector++)**(pixin++);
    *(pixout++) = val;
    pixin += step;
    }

/* Second step: interpolate along NAXIS2 from the interpolation buffer */
  make_kernel(dpos[1], kernel, interptype);
  pixin = buffer;
  val = 0.0;
  kvector = kernel;
  for (i=kwidth; i--;)
    val += *(kvector++)**(pixin++);

  return val;
  }


/****** make_kernel **********************************************************
3111
PROTO	void make_kernel(float pos, float *kernel, interpenum interptype)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3112
3113
3114
3115
3116
3117
3118
PURPOSE	Conpute interpolation-kernel data
INPUT	Position,
	Pointer to the output kernel data,
	Interpolation method.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
3119
VERSION	07/09/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3120
 ***/
3121
void	make_kernel(float pos, float *kernel, interpenum interptype)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3122
  {
3123
   float	x, val, sinx1,sinx2,sinx3,cosx1;
3124

Emmanuel Bertin's avatar
Emmanuel Bertin committed
3125
3126
3127
3128
3129
3130
3131
3132
3133
  if (interptype == INTERP_NEARESTNEIGHBOUR)
    *kernel = 1;
  else if (interptype == INTERP_BILINEAR)
    {
    *(kernel++) = 1.0-pos;
    *kernel = pos;
    }
  else if (interptype == INTERP_LANCZOS2)
    {
3134
    if (pos<1e-5 && pos>-1e-5)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3135
3136
3137
3138
3139
3140
3141
3142
3143
      {
      *(kernel++) = 0.0;
      *(kernel++) = 1.0;
      *(kernel++) = 0.0;
      *kernel = 0.0;
      }
    else
      {
      x = -PI/2.0*(pos+1.0);
3144
#ifdef HAVE_SINCOSF
3145
      sincosf(x, &sinx1, &cosx1);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3146
#else
3147
3148
      sinx1 = sinf(x);
      cosx1 = cosf(x);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
#endif
      val = (*(kernel++) = sinx1/(x*x));
      x += PI/2.0;
      val += (*(kernel++) = -cosx1/(x*x));
      x += PI/2.0;
      val += (*(kernel++) = -sinx1/(x*x));
      x += PI/2.0;
      val += (*kernel = cosx1/(x*x));
      val = 1.0/val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *kernel *= val;
      }
    }
  else if (interptype == INTERP_LANCZOS3)
    {
3166
    if (pos<1e-5 && pos>-1e-5)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
      {
      *(kernel++) = 0.0;
      *(kernel++) = 0.0;
      *(kernel++) = 1.0;
      *(kernel++) = 0.0;
      *(kernel++) = 0.0;
      *kernel = 0.0;
      }
    else
      {
      x = -PI/3.0*(pos+2.0);
#ifdef HAVE_SINCOS
3179
      sincosf(x, &sinx1, &cosx1);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3180
#else
3181
3182
      sinx1 = sinf(x);
      cosx1 = cosf(x);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
#endif
      val = (*(kernel++) = sinx1/(x*x));
      x += PI/3.0;
      val += (*(kernel++) = (sinx2=-0.5*sinx1-0.866025403785*cosx1)
				/ (x*x));
      x += PI/3.0;
      val += (*(kernel++) = (sinx3=-0.5*sinx1+0.866025403785*cosx1)
				/(x*x));
      x += PI/3.0;
      val += (*(kernel++) = sinx1/(x*x));
      x += PI/3.0;
      val += (*(kernel++) = sinx2/(x*x));
      x += PI/3.0;
      val += (*kernel = sinx3/(x*x));
      val = 1.0/val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *kernel *= val;
      }
    }
  else if (interptype == INTERP_LANCZOS4)
    {
3208
    if (pos<1e-5 && pos>-1e-5)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
      {
      *(kernel++) = 0.0;
      *(kernel++) = 0.0;
      *(kernel++) = 0.0;
      *(kernel++) = 1.0;
      *(kernel++) = 0.0;
      *(kernel++) = 0.0;
      *(kernel++) = 0.0;
      *kernel = 0.0;
      }
    else
      {
      x = -PI/4.0*(pos+3.0);
#ifdef HAVE_SINCOS
3223
      sincosf(x, &sinx1, &cosx1);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3224
#else
3225
3226
      sinx1 = sinf(x);
      cosx1 = cosf(x);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
#endif
      val = (*(kernel++) = sinx1/(x*x));
      x += PI/4.0;
      val +=(*(kernel++) = -(sinx2=0.707106781186*(sinx1+cosx1))
				/(x*x));
      x += PI/4.0;
      val += (*(kernel++) = cosx1/(x*x));
      x += PI/4.0;
      val += (*(kernel++) = -(sinx3=0.707106781186*(cosx1-sinx1))/(x*x));
      x += PI/4.0;
      val += (*(kernel++) = -sinx1/(x*x));
      x += PI/4.0;
      val += (*(kernel++) = sinx2/(x*x));
      x += PI/4.0;
      val += (*(kernel++) = -cosx1/(x*x));
      x += PI/4.0;
      val += (*kernel = sinx3/(x*x));
      val = 1.0/val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *kernel *= val;
      }
    }
  else
    error(EXIT_FAILURE, "*Internal Error*: Unknown interpolation type in ",
		"make_kernel()");

  return;
  }