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

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

33
34
35
36
#ifndef HAVE_MATHIMF_H
#define _GNU_SOURCE
#endif

37
#include	<math.h>
Emmanuel Bertin's avatar
Emmanuel Bertin committed
38
39
40
41
42
43
44
45
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>

#include	"define.h"
#include	"globals.h"
#include	"prefs.h"
#include	"fits/fitscat.h"
46
#include	"levmar/levmar.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
47
48
49
50
51
52
53
#include	"fft.h"
#include	"fitswcs.h"
#include	"check.h"
#include	"pattern.h"
#include	"psf.h"
#include	"profit.h"

54
55
static double	prof_gammainc(double x, double a),
		prof_gamma(double x);
56
57
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
58
59
		interpenum interptype);

60
static void	make_kernel(float pos, float *kernel, interpenum interptype);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
61
62
63

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

Emmanuel Bertin's avatar
Emmanuel Bertin committed
64
65
const int	interp_kernwidth[5]={1,2,4,6,8};

66
67
const int	flux_flag[PARAM_NPARAM] = {0,
					1,0,0,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
68
69
70
71
72
73
74
75
					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
76
/* "Local" global variables for debugging purposes */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
77
78
int theniter, the_gal;
static picstruct	*the_field, *the_wfield;
79
profitstruct		*theprofit,*thedprofit, *thepprofit, *theqprofit;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
80
81

/****** profit_init ***********************************************************
82
PROTO	profitstruct profit_init(psfstruct *psf, unsigned int modeltype)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
83
PURPOSE	Allocate and initialize a new profile-fitting structure.
84
85
INPUT	Pointer to PSF structure,
	Model type.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
86
87
88
OUTPUT	A pointer to an allocated profit structure.
NOTES	-.
AUTHOR	E. Bertin (IAP)
89
VERSION	17/02/2015
Emmanuel Bertin's avatar
Emmanuel Bertin committed
90
 ***/
91
profitstruct	*profit_init(psfstruct *psf, unsigned int modeltype)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
92
93
  {
   profitstruct		*profit;
94
   int			t, nmodels;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
95
96
97

  QCALLOC(profit, profitstruct, 1);
  profit->psf = psf;
98
99
100
101
102
  QMALLOC(profit->prof, profstruct *, MODEL_NMAX);
  nmodels = 0;
  for (t=1; t<(1<<MODEL_NMAX); t<<=1)
    if (modeltype&t)
      profit->prof[nmodels++] = prof_init(profit, t);
103
104
105
106
107
108
109
/* Allocate memory for the complete model */
  QMALLOC16(profit->modpix, float, PROFIT_MAXMODSIZE*PROFIT_MAXMODSIZE);
  QMALLOC16(profit->modpix2, float, PROFIT_MAXMODSIZE*PROFIT_MAXMODSIZE);
  QMALLOC16(profit->cmodpix, float, PROFIT_MAXMODSIZE*PROFIT_MAXMODSIZE);
  QMALLOC16(profit->psfpix, float, PROFIT_MAXMODSIZE*PROFIT_MAXMODSIZE);
  QMALLOC16(profit->objpix, PIXTYPE, PROFIT_MAXOBJSIZE*PROFIT_MAXOBJSIZE);
  QMALLOC16(profit->objweight, PIXTYPE, PROFIT_MAXOBJSIZE*PROFIT_MAXOBJSIZE);
110
111
  QMALLOC16(profit->dgeopix[0], PIXTYPE, PROFIT_MAXOBJSIZE*PROFIT_MAXOBJSIZE);
  QMALLOC16(profit->dgeopix[1], PIXTYPE, PROFIT_MAXOBJSIZE*PROFIT_MAXOBJSIZE);
112
113
114
  QMALLOC16(profit->lmodpix, PIXTYPE, PROFIT_MAXOBJSIZE*PROFIT_MAXOBJSIZE);
  QMALLOC16(profit->lmodpix2, PIXTYPE, PROFIT_MAXOBJSIZE*PROFIT_MAXOBJSIZE);
  QMALLOC16(profit->resi, float, PROFIT_MAXOBJSIZE*PROFIT_MAXOBJSIZE);
115
  QMALLOC16(profit->presi, float, profit->nparam);
116
  QMALLOC16(profit->covar, float, profit->nparam*profit->nparam);
117
  profit->nprof = nmodels;
118
  profit->fluxfac = 1.0;	/* Default */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
119
120
121
122
123
124
125
126
127
128
129
130

  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)
131
VERSION	17/02/2015
Emmanuel Bertin's avatar
Emmanuel Bertin committed
132
133
134
135
136
137
138
 ***/
void	profit_end(profitstruct *profit)
  {
   int	p;

  for (p=0; p<profit->nprof; p++)
    prof_end(profit->prof[p]);
139
140
141
142
143
144
145
146
  free(profit->modpix);
  free(profit->modpix2);
  free(profit->cmodpix);
  free(profit->psfpix);
  free(profit->lmodpix);
  free(profit->lmodpix2);
  free(profit->objpix);
  free(profit->objweight);
147
148
  free(profit->dgeopix[0]);
  free(profit->dgeopix[1]);
149
  free(profit->resi);
150
  free(profit->presi);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
151
152
  free(profit->prof);
  free(profit->covar);
153
  QFFTWF_FREE(profit->psfdft);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
154
155
156
157
158
159
160
161
  free(profit);

  return;
  }


/****** profit_fit ************************************************************
PROTO	void profit_fit(profitstruct *profit, picstruct *field,
162
163
		picstruct *wfield, picstruct *dgeofield,
		objstruct *obj, obj2struct *obj2)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
164
165
166
167
168
169
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,
170
	Pointer to the differential geometry field,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
171
172
173
174
175
	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/09/2015
Emmanuel Bertin's avatar
Emmanuel Bertin committed
177
178
 ***/
void	profit_fit(profitstruct *profit,
179
		picstruct *field, picstruct *wfield, picstruct *dgeofield,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
180
181
		objstruct *obj, obj2struct *obj2)
  {
182
    profitstruct	*pprofit, *qprofit;
183
    patternstruct	*pattern;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
184
185
    psfstruct		*psf;
    checkstruct		*check;
186
187
188
    double		emx2,emy2,emxy, a , cp,sp, cn, bn, n, rho,
			sum, sump,sumq, sumpw2,sumqw2,sumpqw, sump0,sumq0,
			fluxerr, err;
189
    PIXTYPE		valp,valq,sig2;
190
191
192
    float		param0[PARAM_NPARAM], param1[PARAM_NPARAM],
			param[PARAM_NPARAM],
			**list,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
193
			*cov,
194
			psf_fwhm, dchi2, aspect, chi2;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
195
    int			*index,
196
			c,i,j,p, nparam, nparam2, ncomp, nprof;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
197
198

  nparam = profit->nparam;
199
  nparam2 = nparam*nparam;
200
  nprof = profit->nprof;
201

Emmanuel Bertin's avatar
Emmanuel Bertin committed
202
  if (profit->psfdft)
203
204
    QFFTWF_FREE(profit->psfdft);

Emmanuel Bertin's avatar
Emmanuel Bertin committed
205
206
207

  psf = profit->psf;
  profit->pixstep = psf->pixstep;
208
  obj2->prof_flag = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
209

210
211
  profit->dgeoflag = (dgeofield != NULL);

Emmanuel Bertin's avatar
Emmanuel Bertin committed
212
/* Create pixmaps at image resolution */
213
214
  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
215
  psf_fwhm = psf->masksize[0]*psf->pixstep;
216
  profit->objnaxisn[0] = (((int)((obj->xmax-obj->xmin+1) + psf_fwhm + 0.499)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
217
		*1.2)/2)*2 + 1;
218
  profit->objnaxisn[1] = (((int)((obj->ymax-obj->ymin+1) + psf_fwhm + 0.499)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
219
220
221
222
223
		*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];
224
225
  if (profit->objnaxisn[0]>PROFIT_MAXOBJSIZE)
    {
226
227
    profit->subsamp = ceil((float)profit->objnaxisn[0]/PROFIT_MAXOBJSIZE);
    profit->objnaxisn[1] = (profit->objnaxisn[0] /= (int)profit->subsamp);
228
229
230
    obj2->prof_flag |= PROFLAG_OBJSUB;
    }
  else
231
    profit->subsamp = 1.0;
232
  profit->nobjpix = profit->objnaxisn[0]*profit->objnaxisn[1];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
233

234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/* Create pixmap at model resolution */
  profit->modnaxisn[0] =
	((int)(profit->objnaxisn[0]*profit->subsamp/profit->pixstep
		+0.4999)/2+1)*2; 
  profit->modnaxisn[1] =
	((int)(profit->objnaxisn[1]*profit->subsamp/profit->pixstep
		+0.4999)/2+1)*2; 
  if (profit->modnaxisn[1] < profit->modnaxisn[0])
    profit->modnaxisn[1] = profit->modnaxisn[0];
  else
    profit->modnaxisn[0] = profit->modnaxisn[1];
  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;
    }
  profit->nmodpix = profit->modnaxisn[0]*profit->modnaxisn[1];

Emmanuel Bertin's avatar
Emmanuel Bertin committed
253
254
255
256
257
258
259
/* Use (dirty) global variables to interface with lmfit */
  the_field = field;
  the_wfield = wfield;
  theprofit = profit;
  profit->obj = obj;
  profit->obj2 = obj2;

260
261
262
/* Compute the local PSF */
  profit_psf(profit);

263
  profit->nresi = profit_copyobjpix(profit, field, wfield, dgeofield);
264
  profit->npresi = 0;
265
/* Check if the number of constraints exceeds the number of free parameters */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
266
267
  if (profit->nresi < nparam)
    {
268
269
270
    if (FLAG(obj2.prof_vector))
      for (p=0; p<nparam; p++)
        obj2->prof_vector[p] = 0.0;
271
272
273
274
275
276
    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
277
    obj2->prof_niter = 0;
278
    obj2->prof_flag |= PROFLAG_NOTCONST;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
279
280
281
282
    return;
    }

/* Set initial guesses and boundaries */
283
284
285
  profit->guesssigbkg = profit->sigma = obj->sigbkg;
  profit->guessdx = obj->mx - (int)(obj->mx+0.49999);
  profit->guessdy = obj->my - (int)(obj->my+0.49999);
286
287
288
289
290
291
  if ((profit->guessflux = obj2->flux_auto) <= 0.0)
    profit->guessflux = 0.0;
  if ((profit->guessfluxmax = 10.0*obj2->fluxerr_auto) <= profit->guessflux)
    profit->guessfluxmax = profit->guessflux;
  if (profit->guessfluxmax <= 0.0)
    profit->guessfluxmax = 1.0;
292
293
294
295
  if ((profit->guessradius = 0.5*psf->fwhm) < obj2->hl_radius)
    profit->guessradius = obj2->hl_radius;
  profit->guessaspect = obj->b/obj->a;
  profit->guessposang = obj->theta;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
296
297
298
299

  profit_resetparams(profit);

/* Actual minimisation */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
300
  fft_reset();
301
the_gal++;
302

Emmanuel Bertin's avatar
Emmanuel Bertin committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/*
char str[1024];
sprintf(str, "obj_%04d.fits", the_gal);
catstruct *bcat;
float *bpix, *opix,*lmodpix,*objpix;
bcat=read_cat("base.fits");
QMALLOC(bpix, float, field->npix);
QFSEEK(bcat->file, bcat->tab->bodypos, SEEK_SET, bcat->filename);
read_body(bcat->tab, bpix, field->npix); 
free_cat(&bcat,1);
bcat=read_cat(str);
QMALLOC(opix, float, profit->nobjpix);
QFSEEK(bcat->file, bcat->tab->bodypos, SEEK_SET, bcat->filename);
read_body(bcat->tab, opix, profit->nobjpix); 
free_cat(&bcat,1);
addfrombig(bpix, field->width, field->height,
		profit->objpix, profit->objnaxisn[0],profit->objnaxisn[1],
		profit->ix,profit->iy, -1.0);
objpix = profit->objpix;
lmodpix = opix;
for (i=profit->nobjpix; i--;)
*(objpix++) += *(lmodpix++);
free(bpix);
free(opix);
*/
Emmanuel Bertin's avatar
Emmanuel Bertin committed
328
  profit->niter = profit_minimize(profit, PROFIT_MAXITER);
329
/*
Emmanuel Bertin's avatar
Emmanuel Bertin committed
330
331
332
333
334
335
336
337
338
profit_residuals(profit,field,wfield, 0.0, profit->paraminit, NULL);
check=initcheck(str, CHECK_OTHER,1);
check->width = profit->objnaxisn[0];
check->height = profit->objnaxisn[1];
reinitcheck(field,check);
memcpy(check->pix, profit->lmodpix, profit->nobjpix*sizeof(float));
reendcheck(field,check);
endcheck(check);

339
340
341
342
343
344
345
  chi2 = profit->chi2;
  for (p=0; p<nparam; p++)
    param1[p] = profit->paraminit[p];
  profit_resetparams(profit);
  for (p=0; p<nparam; p++)
    profit->paraminit[p] = param1[p] + (profit->paraminit[p]<param1[p]?1.0:-1.0)
			* sqrt(profit->covar[p*(nparam+1)]);
346

347
348
349
350
351
352
353
354
355
356
357
358
  profit->niter = profit_minimize(profit, PROFIT_MAXITER);
  if (chi2<profit->chi2)
    for (p=0; p<nparam; p++)
      profit->paraminit[p] = param1[p];

list = profit->paramlist;
index = profit->paramindex;
for (i=0; i<PARAM_NPARAM; i++)
if (list[i] && i!= PARAM_SPHEROID_ASPECT && i!=PARAM_SPHEROID_POSANG)
profit->freeparam_flag[index[i]] = 0;
profit->niter = profit_minimize(profit, PROFIT_MAXITER);
*/
359

360
361
362
363
364
  if (profit->nlimmin)
    obj2->prof_flag |= PROFLAG_MINLIM;
  if (profit->nlimmax)
    obj2->prof_flag |= PROFLAG_MAXLIM;

Emmanuel Bertin's avatar
Emmanuel Bertin committed
365
366
367
368
  for (p=0; p<nparam; p++)
    profit->paramerr[p]= sqrt(profit->covar[p*(nparam+1)]);

/* CHECK-Images */
369
370
371
  if ((check = prefs.check[CHECK_PROFILES]))
    {
    profit_residuals(profit,field,wfield, 0.0, profit->paraminit, NULL);
372
373
374
    if (profit->subsamp>1.0)
      addcheck_resample(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
375
		profit->ix,profit->iy, profit->subsamp,
376
377
378
379
		1.0/(profit->subsamp*profit->subsamp));
    else
      addcheck(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
380
381
		profit->ix,profit->iy, 1.0);
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
382

Emmanuel Bertin's avatar
Emmanuel Bertin committed
383
384
  if ((check = prefs.check[CHECK_SUBPROFILES]))
    {
385
    profit_residuals(profit,field,wfield, 0.0, profit->paraminit, NULL);
386
387
388
    if (profit->subsamp>1.0)
      addcheck_resample(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
389
		profit->ix,profit->iy, profit->subsamp,
390
391
392
393
		-1.0/(profit->subsamp*profit->subsamp));
    else
      addcheck(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
394
395
		profit->ix,profit->iy, -1.0);
    }
396
397
398
399
400
401
402
403
404
405
406
  if ((check = prefs.check[CHECK_SPHEROIDS]))
    {
/*-- Set to 0 flux components that do not belong to spheroids */
    for (p=0; p<profit->nparam; p++)
      param[p] = profit->paraminit[p];
    list = profit->paramlist;
    index = profit->paramindex;
    for (i=0; i<PARAM_NPARAM; i++)
      if (list[i] && flux_flag[i] && i!= PARAM_SPHEROID_FLUX)
        param[index[i]] = 0.0;
    profit_residuals(profit,field,wfield, 0.0, param, NULL);
407
408
409
    if (profit->subsamp>1.0)
      addcheck_resample(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
410
		profit->ix,profit->iy, profit->subsamp,
411
412
413
414
		1.0/(profit->subsamp*profit->subsamp));
    else
      addcheck(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
415
416
417
418
419
420
421
422
423
424
425
426
427
		profit->ix,profit->iy, 1.0);
    }
  if ((check = prefs.check[CHECK_SUBSPHEROIDS]))
    {
/*-- Set to 0 flux components that do not belong to spheroids */
    for (p=0; p<profit->nparam; p++)
      param[p] = profit->paraminit[p];
    list = profit->paramlist;
    index = profit->paramindex;
    for (i=0; i<PARAM_NPARAM; i++)
      if (list[i] && flux_flag[i] && i!= PARAM_SPHEROID_FLUX)
        param[index[i]] = 0.0;
    profit_residuals(profit,field,wfield, 0.0, param, NULL);
428
429
430
    if (profit->subsamp>1.0)
      addcheck_resample(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
431
		profit->ix,profit->iy, profit->subsamp,
432
433
434
435
		-1.0/(profit->subsamp*profit->subsamp));
    else
      addcheck(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
436
437
438
		profit->ix,profit->iy, -1.0);
    }
  if ((check = prefs.check[CHECK_DISKS]))
Emmanuel Bertin's avatar
Emmanuel Bertin committed
439
    {
440
441
442
443
444
445
446
447
448
/*-- Set to 0 flux components that do not belong to disks */
    for (p=0; p<profit->nparam; p++)
      param[p] = profit->paraminit[p];
    list = profit->paramlist;
    index = profit->paramindex;
    for (i=0; i<PARAM_NPARAM; i++)
      if (list[i] && flux_flag[i] && i!= PARAM_DISK_FLUX)
        param[index[i]] = 0.0;
    profit_residuals(profit,field,wfield, 0.0, param, NULL);
449
450
451
    if (profit->subsamp>1.0)
      addcheck_resample(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
452
		profit->ix,profit->iy, profit->subsamp,
453
454
455
456
		1.0/(profit->subsamp*profit->subsamp));
    else
      addcheck(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
457
458
		profit->ix,profit->iy, 1.0);
    }
459
460
461
462
463
464
465
466
467
468
469
  if ((check = prefs.check[CHECK_SUBDISKS]))
    {
/*-- Set to 0 flux components that do not belong to disks */
    for (p=0; p<profit->nparam; p++)
      param[p] = profit->paraminit[p];
    list = profit->paramlist;
    index = profit->paramindex;
    for (i=0; i<PARAM_NPARAM; i++)
      if (list[i] && flux_flag[i] && i!= PARAM_DISK_FLUX)
        param[index[i]] = 0.0;
    profit_residuals(profit,field,wfield, 0.0, param, NULL);
470
471
472
    if (profit->subsamp>1.0)
      addcheck_resample(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
473
		profit->ix,profit->iy, profit->subsamp,
474
475
476
477
		-1.0/(profit->subsamp*profit->subsamp));
    else
      addcheck(check, profit->lmodpix,
		profit->objnaxisn[0],profit->objnaxisn[1],
478
479
		profit->ix,profit->iy, -1.0);
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
480
 
481
482
/* Compute compressed residuals */
  profit_residuals(profit,field,wfield, 10.0, profit->paraminit,profit->resi);
483

Emmanuel Bertin's avatar
Emmanuel Bertin committed
484
485
486
487
/* Fill measurement parameters */
  if (FLAG(obj2.prof_vector))
    {
    for (p=0; p<nparam; p++)
488
      obj2->prof_vector[p]= profit->paraminit[p];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
489
490
491
492
493
494
    }
  if (FLAG(obj2.prof_errvector))
    {
    for (p=0; p<nparam; p++)
      obj2->prof_errvector[p]= profit->paramerr[p];
    }
495
496
497
498
499
  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
500
501
502

  obj2->prof_niter = profit->niter;
  obj2->flux_prof = profit->flux;
503
504
  if (FLAG(obj2.fluxerr_prof))
    {
505
    fluxerr = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
506
507
508
509
510
511
512
513
514
    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])
515
            fluxerr += cov[index[j]];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
516
        }
517
    obj2->fluxerr_prof = fluxerr>0.0? sqrt(fluxerr): 0.0;
518
519
    }

520
521
522
  obj2->prof_chi2 = (profit->nresi > profit->nparam)?
		profit->chi2 / (profit->nresi - profit->nparam) : 0.0;

523
/* Position */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
524
525
526
527
528
  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) */
529
530
    if (profit->paramlist[PARAM_X])
      {
531
      obj2->x_prof = (double)profit->ix + *profit->paramlist[PARAM_X] + 1.0;
532
533
534
535
536
537
      obj2->poserrmx2_prof = emx2 = profit->covar[i*(nparam+1)];
      }
    else
      emx2 = 0.0;
    if (profit->paramlist[PARAM_Y])
      {
538
      obj2->y_prof = (double)profit->iy + *profit->paramlist[PARAM_Y] + 1.0;
539
540
541
542
543
544
545
546
      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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562

/*-- 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;

563
564
      obj2->poserra_prof = (float)sqrt(pmx2>0.0? pmx2 : 0.0);
      obj2->poserrb_prof = (float)sqrt(pmy2>0.0? pmy2 : 0.0);
565
      obj2->poserrtheta_prof = (float)(theta/DEG);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
566
567
568
569
570
571
572
573
574
575
576
577
      }

    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);
      }
    }

578
579
580
581
582
583
584
585
586
587
588
589
590
/* Equivalent noise area */
  if (FLAG(obj2.prof_noisearea))
    obj2->prof_noisearea = profit_noisearea(profit);

/* Second order moments and ellipticities */
  if (FLAG(obj2.prof_mx2))
    profit_moments(profit, obj2);

/* Second order moments of the convolved model (used by other parameters) */
  if (FLAG(obj2.prof_convmx2))
    profit_convmoments(profit, obj2);

/* "Hybrid" magnitudes */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
591
592
593
594
595
596
  if (FLAG(obj2.fluxcor_prof))
    {
    profit_residuals(profit,field,wfield, 0.0, profit->paraminit, NULL);
    profit_fluxcor(profit, obj, obj2);
    }

597
/* Do measurements on the rasterised model (surface brightnesses) */
598
  if (FLAG(obj2.fluxeff_prof))
599
    profit_surface(profit, obj2); 
Emmanuel Bertin's avatar
Emmanuel Bertin committed
600

601
602
603
604
605
606
607
608
609
610
611
612
613
/* Background offset */
  if (FLAG(obj2.prof_offset_flux))
    {
    obj2->prof_offset_flux = *profit->paramlist[PARAM_BACK];
    obj2->prof_offset_fluxerr=profit->paramerr[profit->paramindex[PARAM_BACK]];
    }

/* Point source */
  if (FLAG(obj2.prof_dirac_flux))
    {
    obj2->prof_dirac_flux = *profit->paramlist[PARAM_DIRAC_FLUX];
    obj2->prof_dirac_fluxerr =
		profit->paramerr[profit->paramindex[PARAM_DIRAC_FLUX]];
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
    if (FLAG(obj2.prof_dirac_fluxratio))
      {
      obj2->prof_dirac_fluxratio = (rho = obj2->flux_prof>(1.0/BIG)?
				obj2->prof_dirac_flux / obj2->flux_prof
				: 0.0);
      index = profit->paramindex;
      c = index[PARAM_DIRAC_FLUX];
      list = profit->paramlist;
      cov = profit->covar + c*nparam;
      err = 0.0;
      for (i=0; i<PARAM_NPARAM; i++)
        if (flux_flag[i] && list[i])
          err += cov[index[i]];
      err = cov[c] + rho*rho*fluxerr - 2.0*rho*err;
      obj2->prof_dirac_fluxratioerr = (err>(1.0/BIG) && profit->flux>(1.0/BIG))?
					sqrt(err)/profit->flux : 0.0;
      }
631
632
    }

633
/* Spheroid */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
  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]];
649
650
651
652
653
654
655
656
    if ((aspect = obj2->prof_spheroid_aspect) > 1.0)
      {
      obj2->prof_spheroid_aspect = 1.0 / aspect;
      obj2->prof_spheroid_aspecterr /= (aspect*aspect);
      obj2->prof_spheroid_reff *= aspect;
      obj2->prof_spheroid_refferr *= aspect;
      obj2->prof_spheroid_theta = fmod_m90_p90(obj2->prof_spheroid_theta+90.0);
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
657
658
659
660
661
662
    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]];
      }
663
664
665
666
667
    else
      obj2->prof_spheroid_sersicn = 4.0;
    if (FLAG(obj2.prof_spheroid_peak))
      {
      n = obj2->prof_spheroid_sersicn;
668
      bn = 2.0*n - 1.0/3.0 + 4.0/(405.0*n) + 46.0/(25515.0*n*n)
669
		+ 131.0/(1148175*n*n*n);	/* Ciotti & Bertin 1999 */
670
      cn = n * prof_gamma(2.0*n) * pow(bn, -2.0*n);
671
      obj2->prof_spheroid_peak = obj2->prof_spheroid_reff>0.0?
672
	obj2->prof_spheroid_flux
673
		/ (2.0 * PI * cn
674
		* obj2->prof_spheroid_reff*obj2->prof_spheroid_reff
675
		* obj2->prof_spheroid_aspect)
676
677
	: 0.0;
      if (FLAG(obj2.prof_spheroid_fluxeff))
678
679
680
        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;
681
      }
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
    if (FLAG(obj2.prof_spheroid_fluxratio))
      {
      obj2->prof_spheroid_fluxratio = (rho = obj2->flux_prof>(1.0/BIG)?
				obj2->prof_spheroid_flux / obj2->flux_prof
				: 0.0);
      index = profit->paramindex;
      c = index[PARAM_SPHEROID_FLUX];
      list = profit->paramlist;
      cov = profit->covar + c*nparam;
      err = 0.0;
      for (i=0; i<PARAM_NPARAM; i++)
        if (flux_flag[i] && list[i])
          err += cov[index[i]];
      err = cov[c] + rho*rho*fluxerr - 2.0*rho*err;
      obj2->prof_spheroid_fluxratioerr
				= (err>(1.0/BIG) && profit->flux>(1.0/BIG))?
					sqrt(err)/profit->flux : 0.0;
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
    }

/* 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]];
717
718
719
720
721
722
723
724
    if ((aspect = obj2->prof_disk_aspect) > 1.0)
      {
      obj2->prof_disk_aspect = 1.0 / aspect;
      obj2->prof_disk_aspecterr /= (aspect*aspect);
      obj2->prof_disk_scale *= aspect;
      obj2->prof_disk_scaleerr *= aspect;
      obj2->prof_disk_theta = fmod_m90_p90(obj2->prof_spheroid_theta+90.0);
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
725
726
727
728
729
730
731
732
733
734
735
    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;
        }
      }

736
737
738
    if (FLAG(obj2.prof_disk_peak))
      {
      obj2->prof_disk_peak = obj2->prof_disk_scale>0.0?
739
	obj2->prof_disk_flux
740
741
742
743
	/ (2.0 * PI * obj2->prof_disk_scale*obj2->prof_disk_scale
		* obj2->prof_disk_aspect)
	: 0.0;
      if (FLAG(obj2.prof_disk_fluxeff))
744
745
746
        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)*/
747
748
      }

749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
    if (FLAG(obj2.prof_disk_fluxratio))
      {
      obj2->prof_disk_fluxratio = (rho = obj2->flux_prof>(1.0/BIG)?
					obj2->prof_disk_flux / obj2->flux_prof
					: 0.0);
      index = profit->paramindex;
      c = index[PARAM_DISK_FLUX];
      list = profit->paramlist;
      cov = profit->covar + c*nparam;
      err = 0.0;
      for (i=0; i<PARAM_NPARAM; i++)
        if (flux_flag[i] && list[i])
          err += cov[index[i]];
      err = cov[c] + rho*rho*fluxerr - 2.0*rho*err;
      obj2->prof_disk_fluxratioerr = (err>(1.0/BIG) && profit->flux>(1.0/BIG))?
					sqrt(err)/profit->flux : 0.0;
      }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
767
768
769
/* Disk pattern */
    if (prefs.pattern_flag)
      {
770
      profit_residuals(profit,field,wfield, PROFIT_DYNPARAM,
771
			profit->paraminit,profit->resi);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
      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);
        }
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
      if (FLAG(obj2.prof_bar_fluxratio))
        {
        obj2->prof_bar_fluxratio = (rho = obj2->flux_prof>(1.0/BIG)?
					obj2->prof_bar_flux / obj2->flux_prof
					: 0.0);
        index = profit->paramindex;
        c = index[PARAM_BAR_FLUX];
        list = profit->paramlist;
        cov = profit->covar + c*nparam;
        err = 0.0;
        for (i=0; i<PARAM_NPARAM; i++)
          if (flux_flag[i] && list[i])
            err += cov[index[i]];
        err = cov[c] + rho*rho*fluxerr - 2.0*rho*err;
        obj2->prof_bar_fluxratioerr = (err>(1.0/BIG) && profit->flux>(1.0/BIG))?
					sqrt(err)/profit->flux : 0.0;
        }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866

/* 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]];
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
        if (FLAG(obj2.prof_arms_fluxratio))
          {
          obj2->prof_arms_fluxratio = (rho = obj2->flux_prof>(1.0/BIG)?
					obj2->prof_arms_flux / obj2->flux_prof
					: 0.0);
          index = profit->paramindex;
          c = index[PARAM_ARMS_FLUX];
          list = profit->paramlist;
          cov = profit->covar + c*nparam;
          err = 0.0;
          for (i=0; i<PARAM_NPARAM; i++)
            if (flux_flag[i] && list[i])
              err += cov[index[i]];
          err = cov[c] + rho*rho*fluxerr - 2.0*rho*err;
          obj2->prof_arms_fluxratioerr
				= (err>(1.0/BIG) && profit->flux>(1.0/BIG))?
					sqrt(err)/profit->flux : 0.0;
          }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
885
886
887
888
        }
      }
    }

889
/* Star/galaxy classification */
890
  if (FLAG(obj2.prof_class_star) || FLAG(obj2.prof_concentration))
891
    {
892
893
    profit_residuals(profit,field,wfield, PROFIT_DYNPARAM, profit->paraminit,
	FLAG(obj2.prof_class_star) ? profit->resi : NULL);
894
895
896
    pprofit = thepprofit;
    nparam = pprofit->nparam;
    if (pprofit->psfdft)
897
      QFFTWF_FREE(pprofit->psfdft);
898
899
    psf = pprofit->psf;
    pprofit->pixstep = profit->pixstep;
900
901
902
    pprofit->guesssigbkg = profit->guesssigbkg;
    pprofit->guessdx = profit->guessdx;
    pprofit->guessdy = profit->guessdy;
903
904
    pprofit->guessflux = profit->guessflux;
    pprofit->guessfluxmax = profit->guessfluxmax;
905
906
907
    pprofit->guessradius = profit->guessradius;
    pprofit->guessaspect = profit->guessaspect;
    pprofit->guessposang = profit->guessposang;
908
909
910
911
912
913
914
915
    pprofit->ix = profit->ix;
    pprofit->iy = profit->iy;
    pprofit->objnaxisn[0] = profit->objnaxisn[0];
    pprofit->objnaxisn[1] = profit->objnaxisn[1];
    pprofit->subsamp = profit->subsamp;
    pprofit->nobjpix = profit->nobjpix;
    pprofit->obj = obj;
    pprofit->obj2 = obj2;
916
    pprofit->nresi = profit_copyobjpix(pprofit, field, wfield, dgeofield);
917
918
919
920
921
922
    pprofit->modnaxisn[0] = profit->modnaxisn[0];
    pprofit->modnaxisn[1] = profit->modnaxisn[1];
    pprofit->nmodpix = profit->nmodpix;
    profit_psf(pprofit);
    pprofit->sigma = obj->sigbkg;
    profit_resetparams(pprofit);
923
924
    if (profit->paramlist[PARAM_X] && profit->paramlist[PARAM_Y])
      {
925
926
927
928
929
930
      pprofit->paraminit[pprofit->paramindex[PARAM_X]] = *profit->paramlist[PARAM_X];
      pprofit->paraminit[pprofit->paramindex[PARAM_Y]] = *profit->paramlist[PARAM_Y];
      }
    fft_reset();
    pprofit->paraminit[pprofit->paramindex[PARAM_DIRAC_FLUX]] = profit->flux;
    pprofit->niter = profit_minimize(pprofit, PROFIT_MAXITER);
931
    profit_residuals(pprofit,field,wfield, 0.0, pprofit->paraminit,
932
			FLAG(obj2.prof_class_star)? pprofit->resi : NULL);
933
934
935
    qprofit = theqprofit;
    nparam = qprofit->nparam;
    if (qprofit->psfdft)
936
      QFFTWF_FREE(qprofit->psfdft);
937
    qprofit->pixstep = profit->pixstep;
938
939
940
    qprofit->guesssigbkg = profit->guesssigbkg;
    qprofit->guessdx = profit->guessdx;
    qprofit->guessdy = profit->guessdy;
941
942
    qprofit->guessflux = profit->guessflux;
    qprofit->guessfluxmax = profit->guessfluxmax;
943
944
945
    qprofit->guessradius = profit->guessradius;
    qprofit->guessaspect = profit->guessaspect;
    qprofit->guessposang = profit->guessposang;
946
947
948
949
950
951
952
953
    qprofit->ix = profit->ix;
    qprofit->iy = profit->iy;
    qprofit->objnaxisn[0] = profit->objnaxisn[0];
    qprofit->objnaxisn[1] = profit->objnaxisn[1];
    qprofit->subsamp = profit->subsamp;
    qprofit->nobjpix = profit->nobjpix;
    qprofit->obj = obj;
    qprofit->obj2 = obj2;
954
    qprofit->nresi = profit_copyobjpix(qprofit, field, wfield, dgeofield);
955
956
957
958
959
960
961
    qprofit->modnaxisn[0] = profit->modnaxisn[0];
    qprofit->modnaxisn[1] = profit->modnaxisn[1];
    qprofit->nmodpix = profit->nmodpix;
    profit_psf(qprofit);
    qprofit->sigma = obj->sigbkg;
    profit_resetparams(qprofit);
    fft_reset();
962
963
964
965
966
967
    qprofit->paraminit[qprofit->paramindex[PARAM_X]]
		= pprofit->paraminit[pprofit->paramindex[PARAM_X]];
    qprofit->paraminit[qprofit->paramindex[PARAM_Y]]
		= pprofit->paraminit[pprofit->paramindex[PARAM_Y]];
    qprofit->paraminit[qprofit->paramindex[PARAM_DISK_FLUX]]
		= pprofit->paraminit[pprofit->paramindex[PARAM_DIRAC_FLUX]];
968
969
970
    qprofit->paraminit[qprofit->paramindex[PARAM_DISK_SCALE]] = psf->fwhm/16.0;
    qprofit->paraminit[qprofit->paramindex[PARAM_DISK_ASPECT]] = 1.0;
    qprofit->paraminit[qprofit->paramindex[PARAM_DISK_POSANG]] = 0.0;
971
    profit_residuals(qprofit,field,wfield, 0.0, qprofit->paraminit,
972
			FLAG(obj2.prof_class_star)? qprofit->resi : NULL);
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
    sump = sumq = sumpw2 = sumqw2 = sumpqw = sump0 = sumq0 = 0.0;
    for (p=0; p<pprofit->nobjpix; p++)
      if (pprofit->objweight[p]>0 && pprofit->objpix[p]>-BIG)
        {
        valp = pprofit->lmodpix[p];
        sump += (double)(valp*pprofit->objpix[p]);
	valq = qprofit->lmodpix[p];
        sumq += (double)(valq*pprofit->objpix[p]);
	sump0 += (double)(valp*valp);
	sumq0 += (double)(valp*valq);
        sig2 = 1.0f/(pprofit->objweight[p]*pprofit->objweight[p]);
        sumpw2 += valp*valp*sig2;
        sumqw2 += valq*valq*sig2;
        sumpqw += valp*valq*sig2;
        }

989
990
    if (FLAG(obj2.prof_class_star))
      {
991
      dchi2 = 0.5*(pprofit->chi2 - profit->chi2);
992
      obj2->prof_class_star = dchi2 < 50.0?
993
	(dchi2 > -50.0? 2.0/(1.0+expf(dchi2)) : 2.0) : 0.0;
994
995
996
      }
    if (FLAG(obj2.prof_concentration))
      {
997
      obj2->prof_concentration = sump>0.0? (sumq/sump - sumq0/sump0) : 1.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
998
      if (FLAG(obj2.prof_concentrationerr))
999
1000
1001
        obj2->prof_concentrationerr = (sump>0.0 && (err = sumqw2*sump*sump
		+sumpw2*sumq*sumq-2.0*sumpqw*sump*sumq)>0.0)?
			sqrt(err) / (sump*sump) : 1.0;
1002
      }
1003
1004
    }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1005
/* clean up. */
1006
  fft_reset();
1007

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1008
1009
1010
  return;
  }

1011

1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
/****** profit_dfit ***********************************************************
PROTO	void profit_dfit(profitstruct *profit, profitstruct *dprofit,
		picstruct *field, picstruct *dfield,
		picstruct *wfield, picstruct *dwfield,
		objstruct *obj, obj2struct *obj2)
PURPOSE	Fit profile(s) convolved with the PSF to a detected object on the
	detection image, and use the measurement image to scale the flux.
INPUT	Pointer to the measurement profile-fitting structure,
	pointer to the detection profile-fitting structure,
	pointer to the measurement field,
	pointer to the detection field,
	pointer to the measurement field weight,
	pointer to the detection 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)
1030
VERSION	16/02/2013
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
 ***/
void	profit_dfit(profitstruct *profit, profitstruct *dprofit,
		picstruct *field, picstruct *dfield,
		picstruct *wfield, picstruct *dwfield,
		objstruct *obj, obj2struct *obj2)
  {
    psfstruct		*dpsf;
    double		emx2,emy2,emxy, a , cp,sp, cn, bn, n,
			sumn,sumd;
    PIXTYPE		valn,vald,w2;
    float		param0[PARAM_NPARAM], param1[PARAM_NPARAM],
			param[PARAM_NPARAM],
			**list,
			*cov, *pix,
			psf_fwhm, dchi2, err, aspect, chi2, ffac;
    int			*index,
			i,j,p, nparam, nparam2, ncomp, nprof;

  nparam = dprofit->nparam;
  nparam2 = nparam*nparam;
  nprof = dprofit->nprof;
  if (dprofit->psfdft)
1053
    QFFTWF_FREE(dprofit->psfdft);
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086

  dpsf = dprofit->psf;
  dprofit->pixstep = dpsf->pixstep;
  obj2->dprof_flag = 0;

/* Create pixmaps at image resolution */
  dprofit->ix = (int)(obj->mx + 0.49999);/* internal convention: 1st pix = 0 */
  dprofit->iy = (int)(obj->my + 0.49999);/* internal convention: 1st pix = 0 */
  psf_fwhm = dpsf->masksize[0]*dpsf->pixstep;
  dprofit->objnaxisn[0] = (((int)((obj->xmax-obj->xmin+1) + psf_fwhm + 0.499)
		*1.2)/2)*2 + 1;
  dprofit->objnaxisn[1] = (((int)((obj->ymax-obj->ymin+1) + psf_fwhm + 0.499)
		*1.2)/2)*2 + 1;
  if (dprofit->objnaxisn[1]<dprofit->objnaxisn[0])
    dprofit->objnaxisn[1] = dprofit->objnaxisn[0];
  else
    dprofit->objnaxisn[0] = dprofit->objnaxisn[1];
  if (dprofit->objnaxisn[0]>PROFIT_MAXOBJSIZE)
    {
    dprofit->subsamp = ceil((float)dprofit->objnaxisn[0]/PROFIT_MAXOBJSIZE);
    dprofit->objnaxisn[1] = (dprofit->objnaxisn[0] /= (int)dprofit->subsamp);
    obj2->dprof_flag |= PROFLAG_OBJSUB;
    }
  else
    dprofit->subsamp = 1.0;
  dprofit->nobjpix = dprofit->objnaxisn[0]*dprofit->objnaxisn[1];

/* Use (dirty) global variables to interface with lmfit */
  the_field = dfield;
  the_wfield = dwfield;
  dprofit->obj = obj;
  dprofit->obj2 = obj2;

1087
  dprofit->nresi = profit_copyobjpix(dprofit, dfield, dwfield, NULL);
1088

1089
/* Check if the number of constraints exceeds the number of free parameters */
1090
  if (dprofit->nresi < nparam || profit->nresi < 1)
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
    {
    obj2->dprof_flag |= PROFLAG_NOTCONST;
    return;
    }

/* Create pixmap at PSF resolution */
  dprofit->modnaxisn[0] =
	((int)(dprofit->objnaxisn[0]*dprofit->subsamp/dprofit->pixstep
		+0.4999)/2+1)*2; 
  dprofit->modnaxisn[1] =
	((int)(dprofit->objnaxisn[1]*dprofit->subsamp/dprofit->pixstep
		+0.4999)/2+1)*2; 
  if (dprofit->modnaxisn[1] < dprofit->modnaxisn[0])
    dprofit->modnaxisn[1] = dprofit->modnaxisn[0];
  else
    dprofit->modnaxisn[0] = dprofit->modnaxisn[1];
  if (dprofit->modnaxisn[0]>PROFIT_MAXMODSIZE)
    {
    dprofit->pixstep = (double)dprofit->modnaxisn[0] / PROFIT_MAXMODSIZE;
    dprofit->modnaxisn[0] = dprofit->modnaxisn[1] = PROFIT_MAXMODSIZE;
    obj2->dprof_flag |= PROFLAG_MODSUB;
    }
  dprofit->nmodpix = dprofit->modnaxisn[0]*dprofit->modnaxisn[1];

/* Compute the local PSF */
  profit_psf(dprofit);

/* Set initial guesses and boundaries */
  dprofit->guesssigbkg = dprofit->sigma = obj->dsigbkg;
  dprofit->guessdx = obj->mx - (int)(obj->mx+0.49999);
  dprofit->guessdy = obj->my - (int)(obj->my+0.49999);
  if ((dprofit->guessflux = obj->dflux) <= 0.0)
    dprofit->guessflux = 0.0;
  if ((dprofit->guessfluxmax = 10.0*obj->dnpix*obj->dsigbkg*obj->dsigbkg)
			 <= dprofit->guessflux)
    dprofit->guessfluxmax = dprofit->guessflux;
  if (dprofit->guessfluxmax <= 0.0)
    dprofit->guessfluxmax = 1.0;
1129
1130
  if ((dprofit->guessradius = sqrtf(obj->a*obj->b)*1.17)<0.5*dpsf->fwhm)
    dprofit->guessradius = 0.5*dpsf->fwhm;
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
  dprofit->guessaspect = obj->b/obj->a;
  dprofit->guessposang = obj->theta;

  profit_resetparams(dprofit);

/* Actual minimisation */
  fft_reset();

  dprofit->niter = profit_minimize(dprofit, PROFIT_MAXITER);

  if (dprofit->nlimmin)
    obj2->dprof_flag |= PROFLAG_MINLIM;
  if (dprofit->nlimmax)
    obj2->dprof_flag |= PROFLAG_MAXLIM;

  for (p=0; p<nparam; p++)
    dprofit->paramerr[p]= sqrt(dprofit->covar[p*(nparam+1)]);
 
  obj2->dprof_niter = dprofit->niter;

/* Now inject fitted parameters into the measurement model */
  fft_reset();
  profit_residuals(profit,field,wfield, 0.0, dprofit->paraminit, NULL);

/* Compute flux correction */
  sumn = sumd = 0.0;
  for (p=0; p<profit->nobjpix; p++)
    if (profit->objweight[p]>0 && profit->objpix[p]>-BIG)
      {
      w2 = profit->objweight[p]*profit->objweight[p] * profit->lmodpix[p];
      sumn += (double)(w2*profit->objpix[p]);
      sumd += (double)(w2*profit->lmodpix[p]);
      }

  ffac = (float)(sumn/sumd);
  obj2->flux_dprof = sumd!=0.0? dprofit->flux*ffac: 0.0f;
1167
  obj2->fluxerr_dprof = sumd!=0.0? dprofit->flux/sqrtf((float)sumd): 0.0f;
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186

  if (FLAG(obj2.dprof_chi2))
    {
/*-- Compute reduced chi2 on measurement image */
    pix = profit->lmodpix;
    for (p=profit->nobjpix; p--;)
      *(pix++) *= ffac;
    profit_compresi(profit, 0.0, profit->resi);
    obj2->dprof_chi2 = (profit->nresi > dprofit->nparam)?
		profit->chi2 / (profit->nresi - dprofit->nparam) : 0.0;
    }

/* clean up. */
  fft_reset();

  return;
  }


1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
/****** profit_noisearea ******************************************************
PROTO	float profit_noisearea(profitstruct *profit)
PURPOSE	Return the equivalent noise area (see King 1983) of a model.
INPUT	Profile-fitting structure,
OUTPUT	Equivalent noise area, in pixels.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	19/10/2010
 ***/
float	profit_noisearea(profitstruct *profit)
  {
   double	dval, flux,flux2;
   PIXTYPE	*pix;
   int		p;

  flux = flux2 = 0.0;
  pix = profit->lmodpix;
  for (p=profit->nobjpix; p--;)
    {
    dval = (double)*(pix++);
    flux += dval;
    flux2 += dval*dval;
    }

  return (float)(flux2>0.0? flux*flux / flux2 : 0.0);
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
1215
/****** profit_fluxcor ******************************************************
1216
PROTO	void profit_fluxcor(profitstruct *profit, objstruct *obj,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1217
1218
1219
1220
1221
1222
1223
1224
1225
			obj2struct *obj2)
PURPOSE	Integrate the flux within an ellipse and complete it with the wings of
		the fitted model.
INPUT		Profile-fitting structure,
		pointer to the obj structure,
		pointer to the obj2 structure.
OUTPUT	Model-corrected flux.
NOTES	-.
AUTHOR	E. Bertin (IAP)
1226
VERSION	12/04/2011
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1227
1228
1229
 ***/
void	profit_fluxcor(profitstruct *profit, objstruct *obj, obj2struct *obj2)
  {
1230
1231
1232
1233
    checkstruct		*check;
    double		mx,my, dx,dy, cx2,cy2,cxy, klim,klim2, tvobj,sigtvobj,
			tvm,tvmin,tvmout, r1,v1;
    PIXTYPE		*objpix,*objpixt,*objweight,*objweightt, *lmodpix,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1234
			pix, weight,var;
1235
1236
    int			x,y, x2,y2, pos, w,h, area, corrflag;

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249

  corrflag = (prefs.mask_type==MASK_CORRECT);
  w = profit->objnaxisn[0];
  h = profit->objnaxisn[1];
  mx = (float)(w/2);
  my = (float)(h/2);
  if (FLAG(obj2.x_prof))
    {
    if (profit->paramlist[PARAM_X])
      mx += *profit->paramlist[PARAM_X];
    if (profit->paramlist[PARAM_Y])
      my += *profit->paramlist[PARAM_Y];
    }
1250

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1251
1252
1253
1254
1255
  if (obj2->kronfactor>0.0)
    {
    cx2 = obj->cxx;
    cy2 = obj->cyy;
    cxy = obj->cxy;
1256
    klim2 = 0.64*obj2->kronfactor*obj2->kronfactor;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1257
1258
1259
1260
1261
1262
1263
1264
    }
  else
/*-- ...if not, use the circular aperture provided by the user */
    {
    cx2 = cy2 = 1.0;
    cxy = 0.0;
    klim2 = (prefs.autoaper[1]/2.0)*(prefs.autoaper[1]/2.0);
    }
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
/*
  cx2 = obj2->prof_convcxx;
  cy2 = obj2->prof_convcyy;
  cxy = obj2->prof_convcxy;

  lmodpix = profit->lmodpix;
  r1 = v1 = 0.0;
  for (y=0; y<h; y++)
    {
    dy = y - my;
    for (x=0; x<w; x++)
      {
      dx = x - mx;
      pix = *(lmodpix++);
      r1 += sqrt(cx2*dx*dx + cy2*dy*dy + cxy*dx*dy)*pix;
      v1 += pix;
      }
    }

  klim = r1/v1*2.0;
  klim2 = klim*klim;

if ((check = prefs.check[CHECK_APERTURES]))
sexellips(check->pix, check->width, check->height,
obj2->x_prof-1.0, obj2->y_prof-1.0, klim*obj2->prof_conva,klim*obj2->prof_convb,
obj2->prof_convtheta, check->overlay, 0);
*/
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329

  area = 0;
  tvmin = tvmout = tvobj = sigtvobj = 0.0;
  lmodpix = profit->lmodpix;
  objpixt = objpix = profit->objpix;
  objweightt = objweight = profit->objweight;
  for (y=0; y<h; y++)
    {
    for (x=0; x<w; x++, objpixt++,objweightt++)
      {
      dx = x - mx;
      dy = y - my;
      if ((cx2*dx*dx + cy2*dy*dy + cxy*dx*dy) <= klim2)
        {
        area++;
/*------ Here begin tests for pixel and/or weight overflows. Things are a */
/*------ bit intricated to have it running as fast as possible in the most */
/*------ common cases */
        if ((weight=*objweightt)<=0.0)
          {
          if (corrflag
		&& (x2=(int)(2*mx+0.49999-x))>=0 && x2<w
		&& (y2=(int)(2*my+0.49999-y))>=0 && y2<h
		&& (weight=objweight[pos = y2*w + x2])>0.0)
            {
            pix = objpix[pos];
            var = 1.0/(weight*weight);
            }
          else
            pix = var = 0.0;
          }
        else
          {
          pix = *objpixt;
          var = 1.0/(weight*weight);
          }
        tvobj += pix;
        sigtvobj += var;
1330
1331
        tvmin += *(lmodpix++);
//        *(lmodpix++) = pix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
        }
      else
        tvmout += *(lmodpix++);
      }
    }

//  tv -= area*bkg;

  tvm = tvmin + tvmout;
  if (tvm != 0.0)
    {
    obj2->fluxcor_prof = tvobj+obj2->flux_prof*tvmout/tvm;
    obj2->fluxcorerr_prof = sqrt(sigtvobj
			+obj2->fluxerr_prof*obj2->fluxerr_prof*tvmout/tvm);
    }
  else
    {
    obj2->fluxcor_prof = tvobj;
    obj2->fluxcorerr_prof = sqrt(sigtvobj);
    }

1353
1354
1355
1356
/*
  if ((check = prefs.check[CHECK_OTHER]))
    addcheck(check, profit->lmodpix, w, h, profit->ix,profit->iy, 1.0);
*/
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1357
1358
1359
1360
  return;
  }


1361
1362
/****i* prof_gammainc *********************************************************
PROTO	double prof_gammainc(double x, double a)
1363
1364
PURPOSE	Returns the incomplete Gamma function (based on algorithm described in
	Numerical Recipes in C, chap. 6.1).
1365
1366
1367
1368
1369
INPUT	A double,
	upper integration limit.
OUTPUT	Incomplete Gamma function.
NOTES	-.
AUTHOR	E. Bertin (IAP)
1370
VERSION	08/10/2010
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
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
1415
1416
1417
1418
*/
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;
  }


1419
/****i* prof_gamma ************************************************************
1420
PROTO	double prof_gamma(double xx)
1421
1422
PURPOSE	Returns the Gamma function (based on algorithm described in Numerical
	Recipes in C, chap 6.1).
1423
1424
1425
1426
INPUT	A double.
OUTPUT	Gamma function.
NOTES	-.
AUTHOR	E. Bertin (IAP)
1427
VERSION	11/09/2009
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
*/
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
1446

1447
1448
1449
1450
1451
1452
1453
1454
1455
/****** 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)
1456
VERSION	08/10/2010
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
*/
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)
      {
1469
1470
      case MODEL_BACK:
      case MODEL_DIRAC:
1471
1472
        reff = 0.0;
      break;
1473
      case MODEL_SERSIC:
1474
        reff = *profit->paramlist[PARAM_SPHEROID_REFF];
1475
        break;
1476
      case MODEL_DEVAUCOULEURS:
1477
        reff = *profit->paramlist[PARAM_SPHEROID_REFF];
1478
        break;
1479
      case MODEL_EXPONENTIAL:
1480
        reff = *profit->paramlist[PARAM_DISK_SCALE]*1.67835;
1481
        break;
1482
1483
1484
      default:
        error(EXIT_FAILURE, "*Internal Error*: Unknown profile parameter in ",
		"profit_minradius()");
1485
        break;
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
      }
    r = reff*(double)refffac;
    if (r>rmax)
      rmax = r;
    }

  return (float)rmax;
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
1496
1497
1498
1499
1500
1501
1502
/****** 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)
1503
VERSION	13/02/2013
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1504
1505
1506
 ***/
void	profit_psf(profitstruct *profit)
  {
1507
1508
   double	flux;
   float	posin[2], posout[2], dnaxisn[2],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1509
		*pixout,
1510
		xcout,ycout, xcin,ycin, invpixstep, norm;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1511
1512
1513
1514
1515
   int		d,i;

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

1516
1517
  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
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
  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...) */
1546
  flux *= profit->pixstep*profit->pixstep / (profit->subsamp*profit->subsamp);
1547
1548
1549
1550
1551
1552
1553
  if (fabs(flux) <= 0.0)
    error(EXIT_FAILURE, "*Error*: PSF model is empty or negative: ", psf->name);

  norm = 1.0/flux;
  pixout = profit->psfpix;
  for (i=profit->modnaxisn[0]*profit->modnaxisn[1]; i--;)
    *(pixout++) *= norm;  
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566

  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)
1567
VERSION	15/01/2013
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1568
1569
1570
 ***/
int	profit_minimize(profitstruct *profit, int niter)
  {
1571
1572
1573
   double	lm_opts[5], info[LM_INFO_SZ],
		dcovar[PARAM_NPARAM*PARAM_NPARAM], dparam[PARAM_NPARAM];
   int		nfree;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1574

1575
1576
  profit->iter = 0;
  memset(dcovar, 0, profit->nparam*profit->nparam*sizeof(double));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1577
1578

/* Perform fit */
1579
  lm_opts[0] = 1.0e-3;		/* Initial mu */
1580
1581
1582
  lm_opts[1] = 1.0e-6;		/* ||J^T e||_inf stopping factor */
  lm_opts[2] = 1.0e-6;		/* |Dp||_2 stopping factor */
  lm_opts[3] = 1.0e-6;		/* ||e||_2 stopping factor */
1583
  lm_opts[4] = 1.0e-4;		/* Jacobian step */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1584

1585
1586
  nfree = profit_boundtounbound(profit, profit->paraminit, dparam,
				PARAM_ALLPARAMS);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1587

1588
1589
  niter = dlevmar_dif(profit_evaluate, dparam, NULL, nfree,
			profit->nresi + profit->npresi,
1590
			niter, lm_opts, info, NULL, dcovar, profit);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1591

1592
1593
1594
1595
  profit_unboundtobound(profit, dparam, profit->paraminit, PARAM_ALLPARAMS);

/* Convert covariance matrix to bounded space */
  profit_covarunboundtobound(profit, dcovar, profit->covar);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1596
1597
1598
1599
1600
1601

  return niter;
  }


/****** profit_printout *******************************************************
1602
PROTO	void profit_printout(int n_par, float* par, int m_dat, float* fvec,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
		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
 ***/
1618
void	profit_printout(int n_par, float* par, int m_dat, float* fvec,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
		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 ******************************************************
1649
1650
PROTO	void profit_evaluate(double *par, double *fvec, int m, int n,
			void *adata)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1651
1652
1653
1654
1655
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,
1656
	pointer to a data structure (we use it for the profit structure here).
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1657
OUTPUT	-.
1658
NOTES	-.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1659
AUTHOR	E. Bertin (IAP)
1660
VERSION	16/01/2013
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1661
 ***/
1662
void	profit_evaluate(double *dpar, double *fvec, int m, int n, void *adata)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1663
  {
1664
1665
   profitstruct		*profit;
   profstruct		**prof;
1666
   double		*dpar0, *dresi, *fvect;
1667
1668
1669
1670
1671
   float		*modpixt, *profpixt, *resi,
			tparam, val;
   PIXTYPE		*lmodpixt,*lmodpix2t, *objpix,*weight,
			wval;
   int			c,f,i,p,q, fd,pd, jflag,sflag, nprof;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1672
1673

  profit = (profitstruct *)adata;
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688

/* Detect "Jacobian-related" calls */
  jflag = pd = fd = 0;
  dpar0 = profit->dparam;
  if (profit->iter)
    {
    f = q = 0;
    for (p=0; p<profit->nparam; p++)
      {
      if (dpar[f] - dpar0[f] != 0.0)
        {
        pd = p;
        fd = f;
        q++;
        }
1689
      if (profit->parfittype[p]!=PARFIT_FIXED)
1690
1691
1692
1693
1694
        f++;
      }
    if (f>0 && q==1)
      jflag = 1;
    }
1695
jflag = 0;	/* Temporarily deactivated (until problems are fixed) */
1696
  if (jflag && !(profit->nprof==1 && profit->prof[0]->code == MODEL_DIRAC))
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
    {
    prof = profit->prof;
    nprof = profit->nprof;

/*-- "Jacobian call" */
    tparam = profit->param[pd];
    profit_unboundtobound(profit, &dpar[fd], &profit->param[pd], pd);
    sflag = 1;
    switch(profit->paramrevindex[pd])
      {
1707
1708
1709
1710
1711
1712
1713
      case PARAM_BACK:
        lmodpixt = profit->lmodpix;
        lmodpix2t = profit->lmodpix2;
        val = (profit->param[pd] - tparam);
        for (i=profit->nobjpix;i--;)
          *(lmodpix2t++) = val;
        break;
1714
1715
1716
1717
1718
1719
1720
1721
      case PARAM_X:
      case PARAM_Y:
        profit_resample(profit, profit->cmodpix, profit->lmodpix2, 1.0);
        lmodpixt = profit->lmodpix;
        lmodpix2t = profit->lmodpix2;
        for (i=profit->nobjpix;i--;)
          *(lmodpix2t++) -= *(lmodpixt++);
        break;
1722
      case PARAM_DIRAC_FLUX:
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
      case PARAM_SPHEROID_FLUX:
      case PARAM_DISK_FLUX:
      case PARAM_ARMS_FLUX:
      case PARAM_BAR_FLUX:
        if (nprof==1 && tparam != 0.0)
          {
          lmodpixt = profit->lmodpix;
          lmodpix2t = profit->lmodpix2;
          val = (profit->param[pd] - tparam) / tparam;
          for (i=profit->nobjpix;i--;)
            *(lmodpix2t++) = val**(lmodpixt++);
          }
        else
          {
          for (c=0; c<nprof; c++)
            if (prof[c]->flux == &profit->param[pd])
              break;
          memcpy(profit->modpix, prof[c]->pix, profit->nmodpix*sizeof(float));
          profit_convolve(profit, profit->modpix);
          profit_resample(profit, profit->modpix, profit->lmodpix2,
		profit->param[pd] - tparam);
          }
        break;
      case PARAM_SPHEROID_REFF:
      case PARAM_SPHEROID_ASPECT:
      case PARAM_SPHEROID_POSANG:
      case PARAM_SPHEROID_SERSICN:
        sflag = 0;			/* We are in the same switch */
        for (c=0; c<nprof; c++)
1752
1753
          if (prof[c]->code == MODEL_SERSIC
		|| prof[c]->code == MODEL_DEVAUCOULEURS)
1754
1755
1756
1757
1758
1759
            break; 
      case PARAM_DISK_SCALE:
      case PARAM_DISK_ASPECT:
      case PARAM_DISK_POSANG:
        if (sflag)
          for (c=0; c<nprof; c++)
1760
            if (prof[c]->code == MODEL_EXPONENTIAL)
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
              break; 
        sflag = 0;
      case PARAM_ARMS_QUADFRAC:
      case PARAM_ARMS_SCALE:
      case PARAM_ARMS_START:
      case PARAM_ARMS_POSANG:
      case PARAM_ARMS_PITCH:
      case PARAM_ARMS_PITCHVAR:
      case PARAM_ARMS_WIDTH:
        if (sflag)
          for (c=0; c<nprof; c++)
1772
            if (prof[c]->code == MODEL_ARMS)
1773
1774
1775
1776
1777
1778
              break; 
        sflag = 0;
      case PARAM_BAR_ASPECT:
      case PARAM_BAR_POSANG:
        if (sflag)
          for (c=0; c<nprof; c++)
1779
            if (prof[c]->code == MODEL_ARMS)
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
              break; 
        modpixt = profit->modpix;
        profpixt = prof[c]->pix;
        val = -*prof[c]->flux;
        for (i=profit->nmodpix;i--;)
          *(modpixt++) = val**(profpixt++);
        memcpy(profit->modpix2, prof[c]->pix, profit->nmodpix*sizeof(float));
        prof_add(profit, prof[c], 0);
        memcpy(prof[c]->pix, profit->modpix2, profit->nmodpix*sizeof(float));
        profit_convolve(profit, profit->modpix);
        profit_resample(profit, profit->modpix, profit->lmodpix2, 1.0);
        break;
      default:
        error(EXIT_FAILURE, "*Internal Error*: ",
			"unknown parameter index in profit_jacobian()");
        break;
      }
    objpix = profit->objpix;
    weight = profit->objweight;
    lmodpixt = profit->lmodpix;
    lmodpix2t = profit->lmodpix2;
    resi = profit->resi;
    dresi = fvec;
    if (PROFIT_DYNPARAM > 0.0)
      for (i=profit->nobjpix;i--; lmodpixt++, lmodpix2t++)
        {
        val = *(objpix++);
        if ((wval=*(weight++))>0.0)
          *(dresi++) = *(resi++) + *lmodpix2t
		* wval/(1.0+wval*fabs(*lmodpixt - val)/PROFIT_DYNPARAM);
        }
    else
      for (i=profit->nobjpix;i--; lmodpix2t++)
        if ((wval=*(weight++))>0.0)
          *(dresi++) = *(resi++) + *lmodpix2t * wval;
    }
  else
    {
/*-- "Regular call" */
    for (p=0; p<profit->nparam; p++)
      dpar0[p] = dpar[p];
    profit_unboundtobound(profit, dpar, profit->param, PARAM_ALLPARAMS);

    profit_residuals(profit, the_field, the_wfield, PROFIT_DYNPARAM,
	profit->param, profit->resi);

1826
1827
1828
    profit_presiduals(profit, dpar, profit->presi);

    fvect = fvec;
1829
    for (p=0; p<profit->nresi; p++)
1830
1831
1832
1833
      *(fvect++) = profit->resi[p];
    for (p=0; p<profit->npresi; p++)
      *(fvect++) = profit->presi[p];

1834
1835
1836
1837
1838
    }

//  profit_printout(m, par, n, fvec, adata, 0, -1, 0 );
  profit->iter++;

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1839
1840
1841
1842
1843
  return;
  }


/****** profit_residuals ******************************************************
1844
PROTO	float *profit_residuals(profitstruct *profit, picstruct *field,
1845
		picstruct *wfield, float dynparam, float *param, float *resi)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1846
1847
1848
1849
1850
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,
1851
	dynamic compression parameter (0=no compression),
1852
	pointer to the model parameters
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1853
1854
1855
1856
	pointer to the computed residuals (output).
OUTPUT	Vector of residuals.
NOTES	-.
AUTHOR	E. Bertin (IAP)
1857
VERSION	08/07/2010
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1858
 ***/
1859
1860
float	*profit_residuals(profitstruct *profit, picstruct *field,
		picstruct *wfield, float dynparam, float *param, float *resi)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1861
  {
1862
   int		p, nmodpix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1863

1864
1865
  nmodpix = profit->modnaxisn[0]*profit->modnaxisn[1]*sizeof(float);
  memset(profit->modpix, 0, nmodpix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1866
1867
  for (p=0; p<profit->nparam; p++)
    profit->param[p] = param[p];
1868
/* Simple PSF shortcut */
1869
  if (profit->nprof == 1 && profit->prof[0]->code == MODEL_DIRAC)
1870
    {
1871
1872
    profit_resample(profit, profit->psfpix, profit->lmodpix,
		*profit->prof[0]->flux);
1873
1874
    profit->flux = *profit->prof[0]->flux;
    }
1875
1876
  else
    {
1877
    profit->flux = 0.0;
1878
    for (p=0; p<profit->nprof; p++)
1879
1880
1881
1882
      profit->flux += prof_add(profit, profit->prof[p], 0);
    memcpy(profit->cmodpix, profit->modpix, profit->nmodpix*sizeof(float));
    profit_convolve(profit, profit->cmodpix);
    profit_resample(profit, profit->cmodpix, profit->lmodpix, 1.0);
1883
    }
1884
1885
1886

  if (resi)
    profit_compresi(profit, dynparam, resi);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1887
1888
1889
1890
1891

  return resi;
  }


1892
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
/****** profit_presiduals *****************************************************
PROTO	float *profit_presiduals(profitstruct *profit, float *param,
		float *presi)
PURPOSE	Compute the vector of prior "residuals" for the model parameters.
INPUT	Profile-fitting structure,
	pointer to the (unbound) model parameters,
	pointer to the computed prior "residuals" (output).
OUTPUT	Vector of residuals.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	15/01/2013
 ***/
float	*profit_presiduals(profitstruct *profit, double *dparam, float *presi)
  {
   float	*presit;  
   int		p;

  presit = presi;
  for (p=0; p<profit->nparam; p++)
    if (profit->dparampsig[p]>0.0)
      *(presit++) = (float)((dparam[p] - profit->dparampcen[p])
				/ profit->dparampsig[p]);

  return presi;
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
1919
/****** profit_compresi ******************************************************
1920
PROTO	float *profit_compresi(profitstruct *profit, float dynparam,
1921
			float *resi)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1922
1923
1924
PURPOSE	Compute the vector of residuals between the data and the galaxy
	profile model.
INPUT	Profile-fitting structure,
1925
	dynamic-compression parameter (0=no compression),
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1926
1927
1928
1929
	vector of residuals (output).
OUTPUT	Vector of residuals.
NOTES	-.
AUTHOR	E. Bertin (IAP)
1930
VERSION	07/09/2009
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1931
 ***/
1932
float	*profit_compresi(profitstruct *profit, float dynparam, float *resi)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1933
  {
1934
1935
   double	error;
   float	*resit;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1936
1937
   PIXTYPE	*objpix, *objweight, *lmodpix,
		val,val2,wval, invsig;
1938
   int		npix, i;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1939
1940
1941
1942
1943
1944
1945
  
/* Compute vector of residuals */
  resit = resi;
  objpix = profit->objpix;
  objweight = profit->objweight;
  lmodpix = profit->lmodpix;
  error = 0.0;
1946
1947
  npix = profit->objnaxisn[0]*profit->objnaxisn[1];
  if (dynparam > 0.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1948
    {
1949
1950
    invsig = (PIXTYPE)(1.0/dynparam);
    for (i=npix; i--; lmodpix++)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1951
1952
1953
1954
      {
      val = *(objpix++);
      if ((wval=*(objweight++))>0.0)
        {
1955
        val2 = (*lmodpix - val)*wval*invsig;
1956
        val2 = val2>0.0? logf(1.0+val2) : -logf(1.0-val2);
1957
        *(resit++) = val2*dynparam;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1958
1959
1960
        error += val2*val2;
        }
      }
1961
1962
1963
1964
1965
1966
1967
1968
1969
    profit->chi2 = dynparam*dynparam*error;
    }
  else
    {
    for (i=npix; i--; lmodpix++)
      {
      val = *(objpix++);
      if ((wval=*(objweight++))>0.0)
        {
1970
        val2 = (*lmodpix - val)*wval;
1971
1972
1973
1974
1975
        *(resit++) = val2;
        error += val2*val2;
        }
      }
    profit->chi2 = error;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1976
1977
1978
1979
1980
1981
1982
    }

  return resi;
  }


/****** profit_resample ******************************************************
1983
PROTO	int	profit_resample(profitstruct *profit, float *inpix,
1984
		PIXTYPE *outpix, float factor)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1985
PURPOSE	Resample the current full resolution model to image resolution.
1986
1987
1988
1989
1990
INPUT	Profile-fitting structure,
	pointer to input raster,
	pointer to output raster,
	multiplicating factor.
OUTPUT	RETURN_ERROR if the rasters don't overlap, RETURN_OK otherwise.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1991
1992
NOTES	-.
AUTHOR	E. Bertin (IAP)
1993
VERSION	17/02/2015
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1994
 ***/
1995
int	profit_resample(profitstruct *profit, float *inpix, PIXTYPE *outpix,
1996
	float factor)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1997
  {
1998
   interpenum	interptype;
1999
   PIXTYPE	*pixout,*pixout0;
2000
2001
2002
2003
2004
2005
2006
2007
   float	kernel[INTERP_MAXKERNELWIDTH], pos[2],
		*kernelt, *pixin,*pixin0, *mask,*maskt, *pixinout,
		*dpixin,*dpixin0, *dpixout,*dpixout0, *dx,*dy,
		*dgeoxpix0,*dgeoypix0, *dgeoxpix,*dgeoypix,
		xcin,xcout,ycin,ycout, xsin,ysin, xin,yin, x,y, val,
		invpixstep;
   int		*start,*startt, *nmask,*nmaskt, *modnaxisn,
		i,j,k,n,t,w,
2008
		ixsout,iysout, ixout,iyout, dixout,diyout, nxout,nyout,
2009
		iysina, nyin, hmw,hmh, ix,iy, ixin,iyin, interpw, offout;
2010

2011
2012
2013
  modnaxisn = profit->modnaxisn;
  interptype = INTERP_LANCZOS4;
  interpw = interp_kernwidth[interptype];
2014
  invpixstep = profit->subsamp/profit->pixstep;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2015

2016
  xcin = (float)(modnaxisn[0]/2);
2017
2018
2019
  xcout = ((int)(profit->subsamp*profit->objnaxisn[0])/2 + 0.5)
		/ profit->subsamp - 0.5;
  if ((dx=profit->paramlist[PARAM_X]))
2020
    xcout += *dx/profit->subsamp;
2021
2022

  xsin = xcin - xcout*invpixstep;			/* Input start x-coord*/
2023

2024
  if ((int)xsin >= modnaxisn[0]
2025
2026
2027
2028
#if defined(HAVE_ISNAN) && defined(HAVE_ISINF)
	|| isnan(xsin) || isinf(xsin)
#endif
	)
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
    return RETURN_ERROR;
  ixsout = 0;				/* Int. part of output start x-coord */
  if (xsin<0.0)
    {
    dixout = (int)(1.0-xsin/invpixstep);
/*-- Simply leave here if the images do not overlap in x */
    if (dixout >= profit->objnaxisn[0])
      return RETURN_ERROR;
    ixsout += dixout;
    xsin += dixout*invpixstep;
    }
2040
  nxout = (int)((modnaxisn[0]-xsin)/invpixstep);	/* nb of interpolated
2041
2042
2043
2044
2045
2046
							input pixels along x */
  if (nxout>(ixout=profit->objnaxisn[0]-ixsout))
    nxout = ixout;
  if (!nxout)
    return RETURN_ERROR;

2047
  ycin = (float)(modnaxisn[1]/2);
2048
2049
2050
  ycout = ((int)(profit->subsamp*profit->objnaxisn[1])/2 + 0.5)
		/ profit->subsamp - 0.5;
  if ((dy=profit->paramlist[PARAM_Y]))
2051
    ycout += *dy/profit->subsamp;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2052

2053
  ysin = ycin - ycout*invpixstep;		/* Input start y-coord*/
2054
  if ((int)ysin >= modnaxisn[1]
2055
2056
2057
2058
#if defined(HAVE_ISNAN) && defined(HAVE_ISINF)
	|| isnan(ysin) || isinf(ysin)
#endif
	)
2059
2060
2061
    return RETURN_ERROR;
  iysout = 0;				/* Int. part of output start y-coord */
  if (ysin<0.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2062
    {
2063
2064
2065
2066
2067
2068
    diyout = (int)(1.0-ysin/invpixstep);
/*-- Simply leave here if the images do not overlap in y */
    if (diyout >= profit->objnaxisn[1])
      return RETURN_ERROR;
    iysout += diyout;
    ysin += diyout*invpixstep;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2069
    }
2070
  nyout = (int)((modnaxisn[1]-ysin)/invpixstep);/* nb of interpolated
2071
2072
2073
2074
2075
							input pixels along y */
  if (nyout>(iyout=profit->objnaxisn[1]-iysout))
    nyout = iyout;
  if (!nyout)
    return RETURN_ERROR;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2076

2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
  w = profit->objnaxisn[0];

/* Initialize destination buffer to zero */
  memset(outpix, 0, (size_t)profit->nobjpix*sizeof(PIXTYPE));

  if (profit->dgeoflag) {
/*-- Resample taking into account differential geometry maps */
    offout = iysout*w + ixsout;
    pixout0 = outpix + offout;
    dgeoxpix0 = profit->dgeopix[0] + offout;
    dgeoypix0 = profit->dgeopix[1] + offout;
    yin = ysin + 1.0;    
    for (j = nyout; j--; yin += invpixstep) {
      pixout = pixout0;
      dgeoxpix = dgeoxpix0;
      dgeoypix = dgeoypix0;
      dgeoxpix0 += w;
      dgeoypix0 += w;
      pixout0 += w;
      xin = xsin + 1.0;
      for (i=nxout; i--; xin += invpixstep) {
        pos[0] = xin - *(dgeoxpix++)*invpixstep;
        pos[1] = yin - *(dgeoypix++)*invpixstep;
        *(pixout++) = (PIXTYPE)(factor*interpolate_pix(pos, inpix, modnaxisn,
			interptype));
      }
    }
  return RETURN_OK;
  }

2107
2108
/* Set the yrange for the x-resampling with some margin for interpolation */
  iysina = (int)ysin;	/* Int. part of Input start y-coord with margin */
2109
  hmh = interpw/2 - 1;	/* Interpolant start */
2110
2111
  if (iysina<0 || ((iysina -= hmh)< 0))
    iysina = 0;
2112
2113
2114
  nyin = (int)(ysin+nyout*invpixstep)+interpw-hmh;/* Interpolated Input y size*/
  if (nyin > modnaxisn[1])			/* with margin */
    nyin = modnaxisn[1];
2115
2116
2117
2118
2119
/* Express everything relative to the effective Input start (with margin) */
  nyin -= iysina;
  ysin -= (float)iysina;

/* Allocate interpolant stuff for the x direction */
2120
  QMALLOC(mask, float, nxout*interpw);	/* Interpolation masks */
2121
2122
  QMALLOC(nmask, int, nxout);		/* Interpolation mask sizes */
  QMALLOC(start, int, nxout);		/* Int. part of Input conv starts */
2123

2124
/* Compute the local interpolant and data starting points in x */
2125
  hmw = interpw/2 - 1;
2126
2127
2128
2129
2130
2131
2132
  xin = xsin;
  maskt = mask;
  nmaskt = nmask;
  startt = start;
  for (j=nxout; j--; xin+=invpixstep)
    {
    ix = (ixin=(int)xin) - hmw;
2133
2134
    make_kernel(xin - ixin, kernel, interptype);
    kernelt = kernel;
2135
    if (ix < 0)
2136
      {
2137
      n = interpw + ix;
2138
      ix = 0;
2139
      kernelt -= ix;
2140
      }
2141
    else
2142
2143
      n = interpw;
    if (n>(t=modnaxisn[0]-ix))
2144
2145
2146
      n=t;
    *(startt++) = ix;
    *(nmaskt++) = n;
2147
    for (i=n; i--;)
2148
      *(maskt++) = *(kernelt++);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2149
    }
2150
2151
2152
2153

  QCALLOC(pixinout, float, nxout*nyin);	/* Intermediary frame-buffer */

/* Make the interpolation in x (this includes transposition) */
2154
  pixin0 = inpix + iysina*modnaxisn[0];
2155
  dpixout0 = pixinout;
2156
  for (k=nyin; k--; pixin0+=modnaxisn[0], dpixout0++)
2157
2158
2159
2160
2161
2162
    {
    maskt = mask;
    nmaskt = nmask;
    startt = start;
    dpixout = dpixout0;
    for (j=nxout; j--; dpixout+=nyin)
2163
      {
2164
2165
2166
2167
2168
      pixin = pixin0+*(startt++);
      val = 0.0; 
      for (i=*(nmaskt++); i--;)
        val += *(maskt++)**(pixin++);
      *dpixout = val;
2169
      }
2170
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2171

2172
/* Reallocate interpolant stuff for the y direction */
2173
  QREALLOC(mask, float, nyout*interpw);	/* Interpolation masks */
2174
2175
2176
2177
  QREALLOC(nmask, int, nyout);			/* Interpolation mask sizes */
  QREALLOC(start, int, nyout);		/* Int. part of Input conv starts */

/* Compute the local interpolant and data starting points in y */
2178
  hmh = interpw/2 - 1;
2179
2180
2181
2182
2183
2184
2185
  yin = ysin;
  maskt = mask;
  nmaskt = nmask;
  startt = start;
  for (j=nyout; j--; yin+=invpixstep)
    {
    iy = (iyin=(int)yin) - hmh;
2186
2187
    make_kernel(yin - iyin, kernel, interptype);
    kernelt = kernel;
2188
2189
    if (iy < 0)
      {
2190
2191
      n = interpw + iy;
      kernelt -= iy;
2192
2193
2194
      iy = 0;
      }
    else
2195
      n = interpw;
2196
2197
2198
2199
    if (n>(t=nyin-iy))
      n=t;
    *(startt++) = iy;
    *(nmaskt++) = n;
2200
    for (i=n; i--;)
2201
      *(maskt++) = *(kernelt++);
2202
2203
2204
2205
    }

/* Make the interpolation in y and transpose once again */
  dpixin0 = pixinout;
2206
  pixout0 = outpix+ixsout+iysout*w;
2207
2208
2209
2210
2211
2212
  for (k=nxout; k--; dpixin0+=nyin, pixout0++)
    {
    maskt = mask;
    nmaskt = nmask;
    startt = start;
    pixout = pixout0;
2213
    for (j=nyout; j--; pixout+=w)
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
      {
      dpixin = dpixin0+*(startt++);
      val = 0.0; 
      for (i=*(nmaskt++); i--;)
        val += *(maskt++)**(dpixin++);
       *pixout = (PIXTYPE)(factor*val);
      }
    }

/* Free memory */
  free(pixinout);
  free(mask);
  free(nmask);
  free(start);

  return RETURN_OK;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2230
2231
2232
2233
  }


/****** profit_convolve *******************************************************
2234
PROTO	void profit_convolve(profitstruct *profit, float *modpix)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2235
2236
2237
2238
2239
2240
2241
2242
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
 ***/
2243
void	profit_convolve(profitstruct *profit, float *modpix)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
  {
  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;
2266
2267
   float      *mask,*maskt, *ppix;
   float       dx,dy, r,r2,rmin,rmin2,rmax,rmax2,rsig,invrsig2;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
   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;
2280
  QCALLOC(mask, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
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
2330
2331
2332
2333
2334
2335
2336
  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)
2337
        *maskt *= (r2>rmax2)?0.0:expf((2*rmin*sqrtf(r2)-r2-rmin2)*invrsig2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2338
2339
2340
2341
    dx = -hcpwidth;
    maskt += offset;
    for (x=hcpwidth; x--; dx+=1.0, maskt++)
      if ((r2=dx*dx+dy*dy)>rmin2)
2342
        *maskt *= (r2>rmax2)?0.0:expf((2*rmin*sqrtf(r2)-r2-rmin2)*invrsig2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2343
2344
2345
2346
2347
2348
2349
2350
    }
  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)
2351
        *maskt *= (r2>rmax2)?0.0:expf((2*rmin*sqrtf(r2)-r2-rmin2)*invrsig2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2352
2353
2354
2355
    dx = -hcpwidth;
    maskt += offset;
    for (x=hcpwidth; x--; dx+=1.0, maskt++)
      if ((r2=dx*dx+dy*dy)>rmin2)
2356
        *maskt *= (r2>rmax2)?0.0:expf((2*rmin*sqrtf(r2)-r2-rmin2)*invrsig2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
    }

/* 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,
2370
			picstruct *wfield, picstruct *dgeofield)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2371
2372
2373
PURPOSE	Copy a piece of the input field image to a profit structure.
INPUT	Pointer to the profit structure,
	Pointer to the field structure,
2374
2375
	Pointer to the field weight structure,
	Pointer to the differential geometry field structure
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2376
2377
2378
OUTPUT	The number of valid pixels copied.
NOTES	Global preferences are used.
AUTHOR	E. Bertin (IAP)
2379
VERSION	17/02/2015
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2380
2381
 ***/
int	profit_copyobjpix(profitstruct *profit, picstruct *field,
2382
			picstruct *wfield, picstruct *dgeofield)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2383
  {
2384
   float	dx, dy2, dr2, rad2;
2385
2386
2387
2388
   PIXTYPE	*pixin,*wpixin,*dgeoxpixin,*dgeoypixin, *pixout,*wpixout,
		*dgeoxpixout, *dgeoypixout,
		backnoise2, invgain, satlevel, wthresh, pix,spix, wpix,swpix,
		dgeoxpix,dgeoypix,sdgeoxpix,sdgeoypix;
2389
   int		i,x,y, xmin,xmax,ymin,ymax, w,h,dw, npix, off, gainflag,
2390
		badflag, sflag, sx,sy,sn,sw, ix,iy;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2391
2392
2393
2394

/* First put the image background to -BIG */
  pixout = profit->objpix;
  wpixout = profit->objweight;
2395
2396
  dgeoxpixout = profit->dgeopix[0];
  dgeoypixout = profit->dgeopix[1];
2397
  for (i=profit->objnaxisn[0]*profit->objnaxisn[1]; i--;)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2398
2399
    {
    *(pixout++) = -BIG;
2400
    *(wpixout++) = *(dgeoxpixout++) = *(dgeoypixout++) = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2401
2402
2403
2404
2405
2406
2407
2408
2409
    }

/* 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;
2410
  sn = (int)profit->subsamp;
2411
2412
2413
  sflag = (sn>1);
  w = profit->objnaxisn[0]*sn;
  h = profit->objnaxisn[1]*sn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
  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;
2424
2425
  dgeoxpixout = profit->dgeopix[0];
  dgeoypixout = profit->dgeopix[1];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2426
2427
2428
2429
  ymin = iy-h/2;
  ymax = ymin + h;
  if (ymin<field->ymin)
    {
2430
2431
2432
    off = (field->ymin-ymin-1)/sn + 1;
    pixout += off*profit->objnaxisn[0];
    wpixout += off*profit->objnaxisn[0];
2433
2434
    dgeoxpixout += off*profit->objnaxisn[0];
    dgeoypixout += off*profit->objnaxisn[0];
2435
    ymin += off*sn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2436
2437
    }
  if (ymax>field->ymax)
2438
    ymax -= ((ymax-field->ymax-1)/sn + 1)*sn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2439
2440
2441

  xmin = ix-w/2;
  xmax = xmin + w;
2442
  dw = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2443
2444
  if (xmax>field->width)
    {
2445
2446
2447
    off = (xmax-field->width-1)/sn + 1;
    dw += off;
    xmax -= off*sn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2448
2449
2450
    }
  if (xmin<0)
    {
2451
2452
2453
    off = (-xmin-1)/sn + 1;
    pixout += off;
    wpixout += off;
2454
2455
    dgeoxpixout += off;
    dgeoypixout += off;
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
    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
2478
2479
2480
2481
    }

/* Copy the right pixels to the destination */
  npix = 0;
2482
  if (wfield) {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2483
    gainflag = prefs.weightgain_flag;
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
    wthresh = wfield->weight_thresh;
  } else {
    gainflag = 0;
    wthresh = BIG;
  }
  if (sflag)
    {
    swpix = backnoise2 / (double)(sn*sn);
    sdgeoxpix = sdgeoypix = 0.0;
/*-- Sub-sampling case */
    for (y=ymin; y<ymax; y+=sn)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2495
      {
2496
      for (x=xmin; x<xmax; x+=sn)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2497
        {
2498
2499
2500
        pix = wpix = 0.0;
        badflag = 0;
        for (sy=0; sy<sn; sy++)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2501
          {
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
          dy2 = (y+sy-iy);
          dy2 *= dy2;
          dx = (x-ix);
          pixin = &PIX(field, x, y+sy);
          if (wfield)
            wpixin = &PIX(wfield, x, y+sy);
          if (dgeofield) {
            dgeoxpixin = &DGEOPIXX(dgeofield, x, y+sy);
            dgeoypixin = &DGEOPIXY(dgeofield, x, y+sy);
          }
          for (sx=sn; sx--;)
2513
            {
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
            dr2 = dy2 + dx*dx;
            dx++;
            spix = *(pixin++);
            if (wfield)
              swpix = *(wpixin++);
            if (dgeofield) {
                sdgeoxpix = *(dgeoxpixin++);
                sdgeoypix = *(dgeoypixin++);
            }
            if (dr2<rad2 && spix>-BIG && spix<satlevel && swpix<wthresh)
2524
              {
2525
2526
2527
2528
              pix += spix;
              wpix += swpix;
              dgeoxpix += sdgeoxpix;
              dgeoypix += sdgeoypix;
2529
              }
2530
2531
            else
              badflag=1;
2532
            }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2533
          }
2534
2535
2536
2537
        *(pixout++) = pix;
        *(dgeoxpixout++) = dgeoxpix;
        *(dgeoypixout++) = dgeoypix;
        if (!badflag)	/* A single bad pixel ruins is all (saturation, etc.)*/
2538
          {
2539
          *(wpixout++) = 1.0 / sqrt(wpix+(pix>0.0?
2540
		(gainflag? pix*wpix/backnoise2:pix)*invgain : 0.0));
2541
          npix++;
2542
          }
2543
2544
        else
          *(wpixout++) = 0.0;
2545
        }
2546
2547
2548
2549
2550
      pixout += dw;
      wpixout += dw;
      dgeoxpixout += dw;
      dgeoypixout += dw;
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2551
2552
    }
  else
2553
    {
2554
2555
2556
    wpix = backnoise2;
    dgeoxpix = dgeoypix = 0.0;
    for (y=ymin; y<ymax; y++)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2557
      {
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
      dy2 = y-iy;
      dy2 *= dy2;
      pixin = &PIX(field, xmin, y);
      if (wfield)
        wpixin = &PIX(wfield, xmin, y);
      if (dgeofield) {
        dgeoxpixin = &DGEOPIXX(dgeofield, xmin, y);
        dgeoypixin = &DGEOPIXY(dgeofield, xmin, y);
      }
      for (x=xmin; x<xmax; x++)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2568
        {
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
        dx = x-ix;
        dr2 = dy2 + dx*dx;
        pix = *(pixin++);
        if (wfield)
          wpix = *(wpixin++);
        if (dgeofield) {
          dgeoxpix = *(dgeoxpixin++);
          dgeoypix = *(dgeoypixin++);
        }
        if (dr2<rad2 && pix>-BIG && pix<satlevel && wpix<wthresh)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2579
          {
2580
          *(pixout++) = pix;
2581
2582
2583
2584
2585
          *(wpixout++) = 1.0 / sqrt(wpix+(pix>0.0?
		(gainflag? pix*wpix/backnoise2:pix)*invgain : 0.0));
          npix++;
          *(dgeoxpixout++) = dgeoxpix;
          *(dgeoypixout++) = dgeoypix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2586
          }
2587
2588
        else
          *(pixout++) = *(wpixout++) = *(dgeoxpixout++) = *(dgeoypixout++) = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2589
        }
2590
2591
2592
2593
      pixout += dw;
      wpixout += dw;
      dgeoxpixout += dw;
      dgeoypixout += dw;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2594
      }
2595
    }
2596

Emmanuel Bertin's avatar
Emmanuel Bertin committed
2597
2598
2599
2600
2601
  return npix;
  }


/****** profit_spiralindex ****************************************************
2602
PROTO	float profit_spiralindex(profitstruct *profit)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2603
2604
2605
2606
2607
2608
2609
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)
2610
VERSION	12/07/2012
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2611
 ***/
2612
float profit_spiralindex(profitstruct *profit)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2613
2614
2615
  {
   objstruct	*obj;
   obj2struct	*obj2;
2616
   float	*dx,*dy, *fdx,*fdy, *gdx,*gdy, *gdxt,*gdyt, *pix,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
		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 */
2627
  fwhm = profit->guessradius * 2.0 / 4.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2628
2629
2630
2631
2632
  if (fwhm < 2.0)
    fwhm = 2.0;
  sep = 2.0;

  invtwosigma2 = -(2.35*2.35/(2.0*fwhm*fwhm));
2633
  hw = (float)(profit->objnaxisn[0]/2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2634
  ohw = profit->objnaxisn[0] - hw;
2635
  hh = (float)(profit->objnaxisn[1]/2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2636
2637
2638
  ohh = profit->objnaxisn[1] - hh;
  txstart = -hw;
  ty = -hh;
2639
  QMALLOC(dx, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
  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));
      }
    }
2652
  QMALLOC(dy, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
  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)));
      }
    }

2667
  QMALLOC(gdx, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2668
2669
2670
2671
2672
2673
2674
2675
2676
  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 */
2677
  QMEMCPY(gdx, gdy, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2678
2679
2680
2681
2682
2683
  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 */
2684
  invtwosigma2 = -1.18*1.18 / (2.0*profit->guessradius*profit->guessradius);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
  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);
2705
2706
  QFFTWF_FREE(fdx);
  QFFTWF_FREE(fdy);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2707
2708
2709
2710
2711
2712
2713
2714
  free(gdx);
  free(gdy);

  return spirindex;
  }


/****** profit_moments ****************************************************
2715
PROTO	void profit_moments(profitstruct *profit, obj2struct *obj2)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2716
PURPOSE	Compute the 2nd order moments from the unconvolved object model.
2717
2718
INPUT	Profile-fitting structure,
	Pointer to obj2 structure.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2719
2720
2721
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
2722
VERSION	22/04/2011
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2723
 ***/
2724
void	 profit_moments(profitstruct *profit, obj2struct *obj2)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2725
  {
2726
   profstruct	*prof;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2727
2728
2729
2730
2731
2732
   double	dpdmx2[6], cov[4],
		*jac,*jact, *pjac,*pjact, *dcovar,*dcovart,
		*dmx2,*dmy2,*dmxy,
		m0,invm0, mx2,my2,mxy, den,invden,
		temp, temp2,invtemp2,invstemp2,
		pmx2,theta, flux, dval;
2733
   float	 *covart;
2734
   int		findex[MODEL_NMAX],
2735
		i,j,p, nparam;
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769

/*  hw = (float)(profit->modnaxisn[0]/2);*/
/*  hh = (float)(profit->modnaxisn[1]/2);*/
/*  r2max = hw<hh? hw*hw : hh*hh;*/
/*  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)*/
/*      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++;*/
/*    }*/

/*  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;*/

2770
  nparam = profit->nparam;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2771
  if (FLAG(obj2.prof_e1err) || FLAG(obj2.prof_pol1err))
2772
2773
2774
    {
/*-- Set up Jacobian matrices */
    QCALLOC(jac, double, nparam*3);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2775
2776
2777
2778
2779
2780
    QMALLOC(pjac, double, (nparam<2? 6 : nparam*3));
    QMALLOC(dcovar, double, nparam*nparam);
    dcovart = dcovar;
    covart = profit->covar;
    for (i=nparam*nparam; i--;)
      *(dcovart++) = (double)(*(covart++));
2781
2782
2783
2784
2785
    dmx2 = jac;
    dmy2 = jac+nparam;
    dmxy = jac+2*nparam;
    }
  else
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2786
    jac = pjac = dcovar = dmx2 = dmy2 = dmxy = NULL;
2787

2788
2789
  m0 = mx2 = my2 = mxy = 0.0;
  for (p=0; p<profit->nprof; p++)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2790
    {
2791
    prof = profit->prof[p];
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
    findex[p] = prof_moments(profit, prof, pjac);
    flux = *prof->flux;
    m0 += flux;
    mx2 += prof->mx2*flux;
    my2 += prof->my2*flux;
    mxy += prof->mxy*flux;
    if (jac)
      {
      jact = jac;
      pjact = pjac;
      for (j=nparam*3; j--;)
        *(jact++) += flux * *(pjact++);
      }
    }
  invm0 = 1.0 / m0;
  obj2->prof_mx2 = (mx2 *= invm0);
  obj2->prof_my2 = (my2 *= invm0);
  obj2->prof_mxy = (mxy *= invm0);
/* Complete the flux derivative of moments */
  if (jac)
    {
    for (p=0; p<profit->nprof; p++)
      {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2815
2816
2817
2818
      prof = profit->prof[p];
      dmx2[findex[p]] = prof->mx2 - mx2;
      dmy2[findex[p]] = prof->my2 - my2;
      dmxy[findex[p]] = prof->mxy - mxy;
2819
2820
2821
2822
      }
    jact = jac;
    for (j=nparam*3; j--;)
      *(jact++) *= invm0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2823
    }
2824
2825
2826

/* Handle fully correlated profiles (which cause a singularity...) */
  if ((temp2=mx2*my2-mxy*mxy)<0.00694)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2827
    {
2828
2829
2830
2831
2832
    mx2 += 0.0833333;
    my2 += 0.0833333;
    temp2 = mx2*my2-mxy*mxy;
    }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
2833
2834
2835
2836
2837
/* Use the Jacobians to compute the moment covariance matrix */
  if (jac)
    propagate_covar(dcovar, jac, obj2->prof_mx2cov, nparam, 3,
						pjac);	/* We re-use pjac */

2838
  if (FLAG(obj2.prof_pol1))
2839
    {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2840
/*--- "Polarisation", i.e. module = (a^2-b^2)/(a^2+b^2) */
2841
2842
2843
2844
    if (mx2+my2 > 1.0/BIG)
      {
      obj2->prof_pol1 = (mx2 - my2) / (mx2+my2);
      obj2->prof_pol2 = 2.0*mxy / (mx2 + my2);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2845
      if (FLAG(obj2.prof_pol1err))
2846
        {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
/*------ Compute the Jacobian of polarisation */
        invden = 1.0/(mx2+my2);
        dpdmx2[0] =  2.0*my2*invden*invden;
        dpdmx2[1] = -2.0*mx2*invden*invden;
        dpdmx2[2] =  0.0;
        dpdmx2[3] = -2.0*mxy*invden*invden;
        dpdmx2[4] = -2.0*mxy*invden*invden;
        dpdmx2[5] =  2.0*invden;

/*------ Use the Jacobian to compute the polarisation covariance matrix */
        propagate_covar(obj2->prof_mx2cov, dpdmx2, cov, 3, 2,
						pjac);	/* We re-use pjac */
        obj2->prof_pol1err = (float)sqrt(cov[0]<0.0? 0.0: cov[0]);
        obj2->prof_pol2err = (float)sqrt(cov[3]<0.0? 0.0: cov[3]);
        obj2->prof_pol12corr = (dval=cov[0]*cov[3]) > 0.0?
					(float)(cov[1]/sqrt(dval)) : 0.0;
2863
2864
2865
2866
        }
      }
    else
      obj2->prof_pol1 = obj2->prof_pol2
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2867
	= obj2->prof_pol1err = obj2->prof_pol2err = obj2->prof_pol12corr = 0.0;
2868
2869
2870
2871
    }

  if (FLAG(obj2.prof_e1))
    {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2872
/*--- "Ellipticity", i.e. module = (a-b)/(a+b) */
2873
2874
    if (mx2+my2 > 1.0/BIG)
      {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2875
2876
      den = (temp2>=0.0) ? mx2+my2+2.0*sqrt(temp2) : mx2+my2;
      invden = 1.0/den;
2877
2878
      obj2->prof_e1 = (float)(invden * (mx2 - my2));
      obj2->prof_e2 = (float)(2.0 * invden * mxy);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2879
      if (FLAG(obj2.prof_e1err))
2880
        {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2881
/*------ Compute the Jacobian of ellipticity */
2882
        invstemp2 = (temp2>=0.0) ? 1.0/sqrt(temp2) : 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
        dpdmx2[0] = ( den - (1.0+my2*invstemp2)*(mx2-my2))*invden*invden;
        dpdmx2[1] = (-den - (1.0+mx2*invstemp2)*(mx2-my2))*invden*invden;
        dpdmx2[2] = 2.0*mxy*invstemp2*(mx2-my2)*invden*invden;
        dpdmx2[3] = -2.0*mxy*(1.0+my2*invstemp2)*invden*invden;
        dpdmx2[4] = -2.0*mxy*(1.0+mx2*invstemp2)*invden*invden;
        dpdmx2[5] =  (2.0*den+4.0*mxy*mxy*invstemp2)*invden*invden;

/*------ Use the Jacobian to compute the ellipticity covariance matrix */
        propagate_covar(obj2->prof_mx2cov, dpdmx2, cov, 3, 2,
					pjac);	/* We re-use pjac */
        obj2->prof_e1err = (float)sqrt(cov[0]<0.0? 0.0: cov[0]);
        obj2->prof_e2err = (float)sqrt(cov[3]<0.0? 0.0: cov[3]);
        obj2->prof_e12corr = (dval=cov[0]*cov[3]) > 0.0?
					(float)(cov[1]/sqrt(dval)) : 0.0;
2897
        }
2898
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2899
    else
2900
      obj2->prof_e1 = obj2->prof_e2
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2901
	= obj2->prof_e1err = obj2->prof_e2err = obj2->prof_e12corr = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2902
    }
2903
2904
2905

  if (FLAG(obj2.prof_cxx))
    {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2906
2907
2908
2909
    invtemp2 = (temp2>=0.0) ? 1.0/temp2 : 0.0;
    obj2->prof_cxx = (float)(my2*invtemp2);
    obj2->prof_cyy = (float)(mx2*invtemp2);
    obj2->prof_cxy = (float)(-2*mxy*invtemp2);
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
    }

  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;
    }

2926
2927
2928
/* Free memory used by Jacobians */
  free(jac);
  free(pjac);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
2929
  free(dcovar);
2930

Emmanuel Bertin's avatar
Emmanuel Bertin committed
2931
2932
2933
2934
  return;
  }


2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
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
/****** profit_convmoments ****************************************************
PROTO	void profit_convmoments(profitstruct *profit, obj2struct *obj2)
PURPOSE	Compute the 2nd order moments of the convolved object model.
INPUT	Profile-fitting structure,
	Pointer to obj2 structure.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
VERSION	12/04/2011
 ***/
void	 profit_convmoments(profitstruct *profit, obj2struct *obj2)
  {
   double	hw,hh, r2max, x,xstart,y, mx2,my2,mxy,mx,my,sum, dval,
		temp,temp2,invtemp2, pmx2, theta;
   PIXTYPE	*pix;
   int		ix,iy, w,h;

  w = profit->modnaxisn[0];
  h = profit->modnaxisn[1];
  hw = (double)(w/2);
  hh = (double)(h/2);

  r2max = hw<hh? hw*hw : hh*hh;
  xstart = -hw;
  y = -hh;
  pix = profit->cmodpix;
  mx2 = my2 = mxy = mx = my = sum = 0.0;
  for (iy=h; iy--; y+=1.0)
    {
    x = xstart;
    for (ix=w; ix--; x+=1.0)
      if (y*y+x*x <= r2max)
        {
        dval = *(pix++);
        sum += dval;
        mx  += dval*x;
        my  += dval*y;
        mx2 += dval*x*x;
        mxy += dval*x*y;
        my2 += dval*y*y;
        }
      else
        pix++;
    }

  if (sum <= 1.0/BIG)
    sum = 1.0;
  mx /= sum;
  my /= sum;
  obj2->prof_convmx2 = (mx2 = mx2/sum - mx*mx)*profit->pixstep*profit->pixstep;
  obj2->prof_convmy2 = (my2 = my2/sum - my*my)*profit->pixstep*profit->pixstep;
  obj2->prof_convmxy = (mxy = mxy/sum - mx*my)*profit->pixstep*profit->pixstep;

/* Handle fully correlated profiles (which cause a singularity...) */
  if ((temp2=mx2*my2-mxy*mxy)<0.00694)
    {
    mx2 += 0.0833333;
    my2 += 0.0833333;
    temp2 = mx2*my2-mxy*mxy;
    }

  temp2 *= profit->pixstep*profit->pixstep;

  if (FLAG(obj2.prof_convcxx))
    {
    invtemp2 = (temp2>=0.0) ? 1.0/temp2 : 0.0;
    obj2->prof_convcxx = (float)(my2*invtemp2);
    obj2->prof_convcyy = (float)(mx2*invtemp2);
    obj2->prof_convcxy = (float)(-2*mxy*invtemp2);
    }

  if (1 /*FLAG(obj2.prof_conva)*/)
    {
    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_conva = (float)sqrt(pmx2 + temp)*profit->pixstep;
    obj2->prof_convb = (float)sqrt(pmx2 - temp)*profit->pixstep;
    obj2->prof_convtheta = theta/DEG;
    }

  return;
  }


3024
/****** profit_surface ****************************************************
3025
PROTO	void profit_surface(profitstruct *profit, obj2struct *obj2)
3026
3027
PURPOSE	Compute surface brightnesses from the unconvolved object model.
INPUT	Pointer to the profile-fitting structure,
3028
	Pointer to obj2 structure.
3029
3030
3031
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
3032
VERSION	06/09/2011
3033
 ***/
3034
void	 profit_surface(profitstruct *profit, obj2struct *obj2)
3035
  {
3036
   profitstruct	hdprofit;
3037
   double	dsum,dhsum,dsumoff, dhval, frac, seff;
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
   float	*spix, *spixt,
		val,vmax,
		scalefac, imsizefac, flux, lost, sum, lostfluxfrac;
   int		i,p, imax, npix, neff;

/* Allocate "high-definition" raster only to make measurements */
  hdprofit.modnaxisn[0] = hdprofit.modnaxisn[1] = PROFIT_HIDEFRES;
  npix = hdprofit.nmodpix = hdprofit.modnaxisn[0]*hdprofit.modnaxisn[1];
/* 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;
3056
  hdprofit.fluxfac = 1.0/(hdprofit.pixstep*hdprofit.pixstep);
3057
3058
3059
3060
3061
  QCALLOC(hdprofit.modpix, float,npix*sizeof(float));

  for (p=0; p<profit->nparam; p++)
    profit->param[p] = profit->paraminit[p];
  lost = sum = 0.0;
3062

3063
3064
3065
3066
3067
3068
3069
3070
  for (p=0; p<profit->nprof; p++)
    {
    sum += (flux = prof_add(&hdprofit, profit->prof[p],0));
    lost += flux*profit->prof[p]->lostfluxfrac;
    }
  lostfluxfrac = sum > 0.0? lost / sum : 0.0;
/*
char filename[256];
3071
checkstruct *check;
3072
3073
3074
3075
3076
3077
3078
3079
3080
sprintf(filename, "raster_%02d.fits", the_gal);
check=initcheck(filename, CHECK_OTHER, 0);
check->width = hdprofit.modnaxisn[0];
check->height = hdprofit.modnaxisn[1];
reinitcheck(the_field, check);
memcpy(check->pix,hdprofit.modpix,check->npix*sizeof(float));
reendcheck(the_field, check);
endcheck(check);
*/
3081
3082
  if (FLAG(obj2.fluxeff_prof))
    {
3083
3084
3085
/*-- Sort model pixel values */
    spix = NULL;			/* to avoid gcc -Wall warnings */
    QMEMCPY(hdprofit.modpix, spix, float, npix);
3086
    fqmedian(spix, npix);
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
/*-- 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;
      }
3123
3124
3125
    free(spix);
    }

3126
/* Compute model peak */
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
  if (FLAG(obj2.peak_prof))
    {
/*-- Find position of maximum pixel in current hi-def raster */
    imax = 0;
    vmax = -BIG;
    spixt = hdprofit.modpix;
    for (i=npix; i--;)
      if ((val=*(spixt++))>vmax)
        {
        vmax = val;
        imax = i;
        }
    imax = npix-1 - imax;
    obj2->peak_prof = hdprofit.modpix[imax];
3141
3142
    }

3143
3144
/* Free hi-def model raster */
  free(hdprofit.modpix);
3145
3146
3147
3148
3149

  return;
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
3150
3151
/****** profit_addparam *******************************************************
PROTO	void profit_addparam(profitstruct *profit, paramenum paramindex,
3152
		float **param)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3153
3154
3155
3156
3157
3158
3159
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)
3160
VERSION	29/03/2010
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3161
3162
 ***/
void	profit_addparam(profitstruct *profit, paramenum paramindex,
3163
		float **param)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3164
3165
3166
3167
3168
3169
3170
3171
3172
  {
/* 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];
3173
3174
    profit->paramindex[paramindex] = profit->nparam;
    profit->paramrevindex[profit->nparam++] = paramindex;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
    }

  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.
3186
OUTPUT	.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3187
3188
NOTES	-.
AUTHOR	E. Bertin (IAP)
3189
VERSION	16/03/2016
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3190
3191
3192
3193
 ***/
void	profit_resetparam(profitstruct *profit, paramenum paramtype)
  {
   obj2struct	*obj2;
3194
   float	param, parammin,parammax, range, priorcen,priorsig;
3195
   parfitenum	fittype;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3196
3197

  obj2 = profit->obj2;
3198
  param = parammin = parammax = priorcen = priorsig = 0.0;
3199

Emmanuel Bertin's avatar
Emmanuel Bertin committed
3200
3201
3202
  switch(paramtype)
    {
    case PARAM_BACK:
3203
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3204
      param = 0.0;
3205
3206
      parammin = -6.0*profit->guesssigbkg;
      parammax =  6.0*profit->guesssigbkg;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3207
3208
      break;
    case PARAM_X:
3209
      fittype = PARFIT_LINBOUND;
3210
      param = profit->guessdx;
3211
      range = profit->guessradius*4.0;
3212
3213
      if (range>profit->objnaxisn[0]*profit->subsamp*2.0)
        range = profit->objnaxisn[0]*profit->subsamp*2.0;
3214
3215
      parammin = -range;
      parammax =  range;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3216
3217
      break;
    case PARAM_Y:
3218
      fittype = PARFIT_LINBOUND;
3219
      param = profit->guessdy;
3220
      range = profit->guessradius*4.0;
3221
3222
      if (range>profit->objnaxisn[1]*profit->subsamp*2.0)
        range = profit->objnaxisn[1]*profit->subsamp*2.0;
3223
3224
      parammin = -range;
      parammax =  range;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3225
      break;
3226
    case PARAM_DIRAC_FLUX:
3227
3228
3229
3230
      fittype = PARFIT_LOGBOUND;
      param = profit->guessflux/profit->nprof;
      parammin = 0.00001*profit->guessfluxmax;
      parammax = 10.0*profit->guessfluxmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3231
      break;
3232
    case PARAM_SPHEROID_FLUX:
3233
3234
3235
3236
      fittype = PARFIT_LOGBOUND;
      param = profit->guessflux/profit->nprof;
      parammin = 0.00001*profit->guessfluxmax;
      parammax = 10.0*profit->guessfluxmax;
3237
      break;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3238
    case PARAM_SPHEROID_REFF:
3239
3240
      fittype = PARFIT_LOGBOUND;
      param = FLAG(obj2.prof_disk_flux)? profit->guessradius
3241
			: profit->guessradius/sqrtf(profit->guessaspect);
3242
      parammin = 0.01;
3243
      parammax = param * 10.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3244
3245
      break;
    case PARAM_SPHEROID_ASPECT:
3246
      fittype = PARFIT_LOGBOUND;
3247
      param = FLAG(obj2.prof_disk_flux)? 1.0 : profit->guessaspect;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3248
      parammin = FLAG(obj2.prof_disk_flux)? 0.5 : 0.01;
3249
      parammax = FLAG(obj2.prof_disk_flux)? 2.0 : 100.0;
3250
      priorcen = 0.0;
3251
      priorsig = 1.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3252
3253
      break;
    case PARAM_SPHEROID_POSANG:
3254
      fittype = PARFIT_UNBOUND;
3255
      param = profit->guessposang;
3256
3257
      parammin = 90.0;
      parammax =  90.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3258
3259
      break;
    case PARAM_SPHEROID_SERSICN:
3260
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3261
      param = 4.0;
3262
      parammin = FLAG(obj2.prof_disk_flux)? 1.0 : 0.3;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3263
3264
3265
      parammax = 10.0;
      break;
    case PARAM_DISK_FLUX:
3266
3267
3268
3269
      fittype = PARFIT_LOGBOUND;
      param = profit->guessflux/profit->nprof;
      parammin = 0.00001*profit->guessfluxmax;
      parammax = 10.0*profit->guessfluxmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3270
3271
      break;
    case PARAM_DISK_SCALE:	/* From scalelength to Re */
3272
      fittype = PARFIT_LOGBOUND;
3273
      param = profit->guessradius/(1.67835*sqrtf(profit->guessaspect));
3274
3275
      parammin = 0.01/1.67835;
      parammax = param * 10.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3276
3277
      break;
    case PARAM_DISK_ASPECT:
3278
      fittype = PARFIT_LOGBOUND;
3279
      param = profit->guessaspect;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3280
      parammin = 0.01;
3281
      parammax = 100.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3282
3283
      break;
    case PARAM_DISK_POSANG:
3284
      fittype = PARFIT_UNBOUND;
3285
      param = profit->guessposang;
3286
3287
      parammin = 90.0;
      parammax =  90.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3288
3289
      break;
    case PARAM_ARMS_FLUX:
3290
3291
3292
3293
      fittype = PARFIT_LOGBOUND;
      param = profit->guessflux/profit->nprof;
      parammin = 0.00001*profit->guessfluxmax;
      parammax = 10.0*profit->guessfluxmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3294
3295
      break;
    case PARAM_ARMS_QUADFRAC:
3296
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3297
3298
3299
3300
3301
      param = 0.5;
      parammin = 0.0;
      parammax = 1.0;
      break;
    case PARAM_ARMS_SCALE:
3302
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3303
3304
3305
3306
3307
      param = 1.0;
      parammin = 0.5;
      parammax = 10.0;
      break;
    case PARAM_ARMS_START:
3308
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3309
3310
3311
3312
3313
      param = 0.5;
      parammin = 0.0;
      parammax = 3.0;
      break;
    case PARAM_ARMS_PITCH:
3314
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3315
3316
3317
3318
3319
      param = 20.0;
      parammin = 5.0;
      parammax = 50.0;
      break;
    case PARAM_ARMS_PITCHVAR:
3320
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
      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:
3334
      fittype = PARFIT_UNBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3335
3336
3337
3338
3339
      param = 0.0;
      parammin = 0.0;
      parammax = 0.0;
      break;
    case PARAM_ARMS_WIDTH:
3340
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3341
3342
3343
3344
3345
      param = 3.0;
      parammin = 1.5;
      parammax = 11.0;
      break;
    case PARAM_BAR_FLUX:
3346
3347
3348
3349
      fittype = PARFIT_LOGBOUND;
      param = profit->guessflux/profit->nprof;
      parammin = 0.00001*profit->guessfluxmax;
      parammax = 4.0*profit->guessfluxmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3350
3351
      break;
    case PARAM_BAR_ASPECT:
3352
      fittype = PARFIT_LOGBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3353
3354
3355
3356
3357
      param = 0.3;
      parammin = 0.2;
      parammax = 0.5;
      break;
    case PARAM_BAR_POSANG:
3358
      fittype = PARFIT_UNBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3359
      param = 0.0;
3360
3361
      parammin = 90.0;
      parammax = 90.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3362
3363
      break;
    case PARAM_INRING_FLUX:
3364
3365
3366
3367
      fittype = PARFIT_LOGBOUND;
      param = profit->guessflux/profit->nprof;
      parammin = 0.00001*profit->guessfluxmax;
      parammax = 4.0*profit->guessfluxmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3368
3369
      break;
    case PARAM_INRING_WIDTH:
3370
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3371
3372
3373
3374
3375
      param = 0.3;
      parammin = 0.0;
      parammax = 0.5;
      break;
    case PARAM_INRING_ASPECT:
3376
      fittype = PARFIT_LOGBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3377
3378
3379
3380
3381
      param = 0.8;
      parammin = 0.4;
      parammax = 1.0;
      break;
    case PARAM_OUTRING_FLUX:
3382
3383
3384
3385
      fittype = PARFIT_LOGBOUND;
      param = profit->guessflux/profit->nprof;
      parammin = 0.00001*profit->guessfluxmax;
      parammax = 4.0*profit->guessfluxmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3386
3387
      break;
    case PARAM_OUTRING_START:
3388
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3389
3390
3391
3392
3393
      param = 4.0;
      parammin = 3.5;
      parammax = 6.0;
      break;
    case PARAM_OUTRING_WIDTH:
3394
      fittype = PARFIT_LINBOUND;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
      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;
3407
3408
  else if (parammin==0.0 && parammax==0.0)
    parammax = 1.0;
3409
3410
  profit_setparam(profit, paramtype, param, parammin, parammax, fittype,
	priorcen, priorsig);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422

  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)
3423
VERSION	18/03/2014
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3424
3425
3426
 ***/
void	profit_resetparams(profitstruct *profit)
  {
3427
   int		p, npresi;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3428
3429
3430
3431
3432


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

3433
3434
3435
3436
3437
3438
3439
  npresi = 0;
  for (p=0; p<profit->nparam; p++)
    if (profit->dparampsig[p]>0.0)
      npresi++;

  profit->npresi = npresi;

Emmanuel Bertin's avatar
Emmanuel Bertin committed
3440
3441
3442
3443
3444
3445
  return;
  }


/****** profit_setparam ****************************************************
PROTO	void profit_setparam(profitstruct *profit, paramenum paramtype,
3446
		float param, float parammin, float parammax,
3447
3448
		parfitenum parfittype,
		float priorcen, float priorsig)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3449
3450
PURPOSE	Set the actual, lower and upper boundary values of a profile parameter.
INPUT	Pointer to the profit structure,
3451
3452
3453
3454
3455
	parameter index,
	actual value,
	lower boundary to the parameter,
	upper boundary to the parameter,
	parameter fitting type.
3456
3457
	prior central value,
	prior standard deviation.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3458
3459
OUTPUT	RETURN_OK if the parameter is registered, RETURN_ERROR otherwise.
AUTHOR	E. Bertin (IAP)
3460
VERSION	16/01/2013
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3461
3462
 ***/
int	profit_setparam(profitstruct *profit, paramenum paramtype,
3463
		float param, float parammin,float parammax,
3464
3465
		parfitenum parfittype,
		float priorcen, float priorsig)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3466
  {
3467
   double	dtemp;
3468
   float	*paramptr;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3469
3470
3471
3472
3473
   int		index;

/* Check whether the parameter has already be registered */
  if ((paramptr=profit->paramlist[(int)paramtype]))
    {
3474
    index = profit->paramindex[(int)paramtype];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3475
3476
3477
    profit->paraminit[index] = param;
    profit->parammin[index] = parammin;
    profit->parammax[index] = parammax;
3478
    profit->parfittype[index] = parfittype;
3479
3480
3481
// Does not make much sense to express Gaussian prior center in model space
//  profit_boundtounbound(profit, &priorcen, &profit->dparampcen[index], index);
    profit->dparampcen[index] = priorcen;
3482
    profit->dparampsig[index] = priorsig;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3483
3484
3485
3486
3487
3488
3489
3490
    return RETURN_OK;
    }
  else
    return RETURN_ERROR;
  }

  
/****** profit_boundtounbound *************************************************
3491
PROTO	int profit_boundtounbound(profitstruct *profit,
3492
				float *param, double *dparam, int index)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3493
PURPOSE	Convert parameters from bounded to unbounded space.
3494
3495
3496
3497
INPUT	Pointer to the profit structure,
	input array of single precision parameters,
	output (incomplete) array of double precision parameters,
	parameter selection index (<0 = all parameters)
3498
OUTPUT	Number of free parameters.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3499
3500
NOTES	-.
AUTHOR	E. Bertin (IAP)
3501
VERSION	20/05/2011
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3502
 ***/
3503
int	profit_boundtounbound(profitstruct *profit,
3504
				float *param, double *dparam, int index)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3505
  {
3506
   double	num,den, tparam;
3507
   int		f,p, pstart,np;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3508

3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
  if (index<0)
    {
    pstart = 0;
    np = profit->nparam;
    }
  else
    {
    pstart = index;
    np = pstart+1;
    }

  f = 0;
  for (p=pstart ; p<np; p++)
3522
    switch(profit->parfittype[p])
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3523
      {
3524
3525
3526
3527
3528
3529
3530
3531
3532
      case PARFIT_FIXED:
        break;
      case PARFIT_UNBOUND:
        if (profit->parammax[p] > 0.0 || profit->parammax[p] < 0.0)
          dparam[f] = param[p-pstart] / profit->parammax[p];
        f++;
        break;
      case PARFIT_LINBOUND:
        tparam = param[p-pstart];
3533
3534
3535
        num = tparam - profit->parammin[p];
        den = profit->parammax[p] - tparam;
        dparam[f] = num>1e-50? (den>1e-50? log(num/den): 50.0) : -50.0;
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
        f++;
        break;
      case PARFIT_LOGBOUND:
        tparam = log(param[p-pstart]);
        num = tparam - log(profit->parammin[p]);
        den = log(profit->parammax[p]) - tparam;
        dparam[f] = num>1e-50? (den>1e-50? log(num/den): 50.0) : -50.0;
        f++;
        break;
      default:
        error(EXIT_FAILURE,
		"*Internal Error*: Unknown parameter fitting type in ",
		"profit_boundtounbound()");
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3549
3550
      }

3551
  return f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3552
3553
3554
3555
  }


/****** profit_unboundtobound *************************************************
3556
PROTO	int profit_unboundtobound(profitstruct *profit,
3557
				double *dparam, float *param, int index)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3558
PURPOSE	Convert parameters from unbounded to bounded space.
3559
3560
3561
3562
INPUT	Pointer to the profit structure,
	input (incomplete) array of double precision parameters,
	output array of single precision parameters.
	parameter selection index (<0 = all parameters)
3563
OUTPUT	Number of free parameters.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3564
3565
NOTES	-.
AUTHOR	E. Bertin (IAP)
3566
VERSION	20/05/2011
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3567
 ***/
3568
int	profit_unboundtobound(profitstruct *profit,
3569
				double *dparam, float *param, int index)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3570
  {
3571
   int		f,p, pstart,np;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3572

3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
  if (index<0)
    {
    pstart = 0;
    np = profit->nparam;
    }
  else
    {
    pstart = index;
    np = pstart+1;
    }

  f = 0;
  for (p=pstart; p<np; p++)
3586
    switch(profit->parfittype[p])
3587
      {
3588
3589
3590
3591
3592
3593
3594
3595
3596
      case PARFIT_FIXED:
        param[p-pstart] = profit->paraminit[p];
        break;
      case PARFIT_UNBOUND:
        param[p-pstart] = dparam[f]*profit->parammax[p];
        f++;
        break;
      case PARFIT_LINBOUND:
        param[p-pstart] = (profit->parammax[p] - profit->parammin[p])
3597
3598
		/ (1.0 + exp(-(dparam[f]>50.0? 50.0
				: (dparam[f]<-50.0? -50.0: dparam[f]))))
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
		+ profit->parammin[p];
        f++;
        break;
      case PARFIT_LOGBOUND:
        param[p-pstart] = exp(log(profit->parammax[p]/profit->parammin[p])
		/ (1.0 + exp(-(dparam[f]>50.0? 50.0
				: (dparam[f]<-50.0? -50.0: dparam[f])))))
		*profit->parammin[p];
        f++;
        break;
      default:
        error(EXIT_FAILURE,
		"*Internal Error*: Unknown parameter fitting type in ",
		"profit_unboundtobound()");
3613
      }
3614
3615
 
  return f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3616
3617
3618
3619
  }


/****** profit_covarunboundtobound ********************************************
3620
PROTO	int profit_covarunboundtobound(profitstruct *profit,
3621
				double *dcovar, float *covar)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3622
PURPOSE	Convert covariance matrix from unbounded to bounded space.
3623
3624
3625
INPUT	Pointer to the profit structure,
	input (incomplete) matrix of double precision covariances,
	output matrix of single precision covariances.
3626
OUTPUT	Number of parameters that hit a boundary.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3627
3628
NOTES	-.
AUTHOR	E. Bertin (IAP)
3629
VERSION	20/05/2011
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3630
 ***/
3631
int	profit_covarunboundtobound(profitstruct *profit,
3632
				double *dcovar, float *covar)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3633
  {
3634
3635
   double	*dxdy,
		xmmin,maxmx, maxmmin;
3636
   float	*x,*xmin,*xmax;
3637
   parfitenum	*fittype;
3638
   int		*fflag,
3639
		f,f1,f2, p,p1,p2, nfree, nparam, nmin,nmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3640
3641

  nparam = profit->nparam;
3642
3643
  fittype = profit->parfittype;
  QMALLOC16(dxdy, double, PARAM_NPARAM);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3644
3645
3646
  x = profit->paraminit;
  xmin = profit->parammin;
  xmax = profit->parammax;
3647
  nmin = nmax = 0;
3648
  f = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3649
  for (p=0; p<profit->nparam; p++)
3650
    switch(fittype[p])
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3651
      {
3652
3653
3654
      case PARFIT_FIXED:
        break;
      case PARFIT_UNBOUND:
3655
        dxdy[f++] = xmax[p];
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
        break;
      case PARFIT_LINBOUND:
        xmmin   = x[p] - xmin[p];
        maxmx   = xmax[p] - x[p];
        maxmmin = xmax[p] - xmin[p];
        dxdy[f++] = xmmin * maxmx / maxmmin;
        if (xmmin<0.001*maxmmin)
          nmin++;
        else if (maxmx<0.001*maxmmin)
          nmax++;
        break;
      case PARFIT_LOGBOUND:
        xmmin   = log(x[p]/xmin[p]);
        maxmx   = log(xmax[p]/x[p]);
        maxmmin = log(xmax[p]/xmin[p]);
        dxdy[f++] = x[p] * xmmin * maxmx / maxmmin;
        if (xmmin<0.001*maxmmin)
          nmin++;
        else if (maxmx<0.001*maxmmin)
          nmax++;
        break;
      default:
        error(EXIT_FAILURE,
		"*Internal Error*: Unknown parameter fitting type in ",
		"profit_boundtounbound()");
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3681
3682
      }

3683
3684
  nfree = f;

3685
3686
  memset(profit->covar, 0, nparam*nparam*sizeof(float));
  f2 = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3687
  for (p2=0; p2<nparam; p2++)
3688
    {
3689
    if (fittype[p2]!=PARFIT_FIXED)
3690
3691
3692
      {
      f1 = 0;
      for (p1=0; p1<nparam; p1++)
3693
        if (fittype[p1]!=PARFIT_FIXED)
3694
3695
3696
3697
3698
3699
3700
          {
          covar[p2*nparam+p1] = (float)(dcovar[f2*nfree+f1]*dxdy[f1]*dxdy[f2]);
          f1++;
          }
      f2++;
      }
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3701
3702
3703

  free(dxdy);

3704
3705
3706
3707
  profit->nlimmin = nmin;
  profit->nlimmax = nmax;

  return nmin+nmax;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3708
3709
3710
3711
  }


/****** prof_init *************************************************************
3712
PROTO	profstruct prof_init(profitstruct *profit, unsigned int modeltype)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3713
3714
PURPOSE	Allocate and initialize a new profile structure.
INPUT	Pointer to the profile-fitting structure,
3715
	model type.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3716
3717
3718
OUTPUT	A pointer to an allocated prof structure.
NOTES	-.
AUTHOR	E. Bertin (IAP)
3719
VERSION	08/12/2011
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3720
 ***/
3721
profstruct	*prof_init(profitstruct *profit, unsigned int modeltype)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3722
3723
  {
   profstruct	*prof;
3724
   float	*pix,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3725
3726
3727
3728
3729
		rmax2, re2, dy2,r2, scale, zero, k,n, hinvn;
   int		width,height, ixc,iyc, ix,iy, nsub,
		d,s;

  QCALLOC(prof, profstruct, 1);
3730
3731
  prof->code = modeltype;
  switch(modeltype)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3732
    {
3733
3734
    case MODEL_BACK:
      prof->name = "background offset";
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3735
3736
3737
3738
3739
      prof->naxis = 2;
      prof->pix = NULL;
      profit_addparam(profit, PARAM_BACK, &prof->flux);
      prof->typscale = 1.0;
      break;
3740
3741
    case MODEL_DIRAC:
      prof->name = "point source";
3742
3743
3744
3745
3746
      prof->naxis = 2;
      prof->naxisn[0] = PROFIT_MAXMODSIZE;
      prof->naxisn[1] = PROFIT_MAXMODSIZE;
      prof->naxisn[2] = 1;
      prof->npix = prof->naxisn[0]*prof->naxisn[1]*prof->naxisn[2];
3747
      QMALLOC(prof->pix, float, prof->npix);
3748
3749
3750
3751
3752
      prof->typscale = 1.0;
      profit_addparam(profit, PARAM_X, &prof->x[0]);
      profit_addparam(profit, PARAM_Y, &prof->x[1]);
      profit_addparam(profit, PARAM_DIRAC_FLUX, &prof->flux);
      break;
3753
3754
    case MODEL_SERSIC:
      prof->name = "Sersic spheroid";
3755
3756
3757
3758
3759
3760
      prof->naxis = 2;
      prof->naxisn[0] = PROFIT_MAXMODSIZE;
      prof->naxisn[1] = PROFIT_MAXMODSIZE;
      prof->naxisn[2] = 1;
      prof->npix = prof->naxisn[0]*prof->naxisn[1]*prof->naxisn[2];
      QMALLOC(prof->pix, float, prof->npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3761
3762
3763
3764
3765
3766
3767
3768
3769
      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;
3770
3771
    case MODEL_DEVAUCOULEURS:
      prof->name = "de Vaucouleurs spheroid";
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3772
      prof->naxis = 2;
3773
3774
3775
3776
      prof->naxisn[0] = PROFIT_MAXMODSIZE;
      prof->naxisn[1] = PROFIT_MAXMODSIZE;
      prof->naxisn[2] = 1;
      prof->npix = prof->naxisn[0]*prof->naxisn[1]*prof->naxisn[2];
3777
      QMALLOC(prof->pix, float, prof->npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3778
3779
3780
3781
3782
3783
3784
3785
      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;
3786
3787
    case MODEL_EXPONENTIAL:
      prof->name = "exponential disk";
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3788
      prof->naxis = 2;
3789
3790
3791
3792
      prof->naxisn[0] = PROFIT_MAXMODSIZE;
      prof->naxisn[1] = PROFIT_MAXMODSIZE;
      prof->naxisn[2] = 1;
      prof->npix = prof->naxisn[0]*prof->naxisn[1]*prof->naxisn[2];
3793
      QMALLOC(prof->pix, float, prof->npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3794
3795
3796
3797
3798
3799
3800
3801
      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;
3802
3803
    case MODEL_ARMS:
      prof->name = "spiral arms";
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3804
      prof->naxis = 2;
3805
3806
3807
3808
      prof->naxisn[0] = PROFIT_MAXMODSIZE;
      prof->naxisn[1] = PROFIT_MAXMODSIZE;
      prof->naxisn[2] = 1;
      prof->npix = prof->naxisn[0]*prof->naxisn[1]*prof->naxisn[2];
3809
      QMALLOC(prof->pix, float, prof->npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
      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;
3825
3826
    case MODEL_BAR:
      prof->name = "bar";
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3827
      prof->naxis = 2;
3828
3829
3830
3831
      prof->naxisn[0] = PROFIT_MAXMODSIZE;
      prof->naxisn[1] = PROFIT_MAXMODSIZE;
      prof->naxisn[2] = 1;
      prof->npix = prof->naxisn[0]*prof->naxisn[1]*prof->naxisn[2];
3832
      QMALLOC(prof->pix, float, prof->npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
      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;
3844
3845
    case MODEL_INRING:
      prof->name = "inner ring";
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3846
      prof->naxis = 2;
3847
3848
3849
3850
      prof->naxisn[0] = PROFIT_MAXMODSIZE;
      prof->naxisn[1] = PROFIT_MAXMODSIZE;
      prof->naxisn[2] = 1;
      prof->npix = prof->naxisn[0]*prof->naxisn[1]*prof->naxisn[2];
3851
      QMALLOC(prof->pix, float, prof->npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
      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;
3863
3864
    case MODEL_OUTRING:
      prof->name = "outer ring";
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3865
      prof->naxis = 2;
3866
3867
3868
3869
      prof->naxisn[0] = PROFIT_MAXMODSIZE;
      prof->naxisn[1] = PROFIT_MAXMODSIZE;
      prof->naxisn[2] = 1;
      prof->npix = prof->naxisn[0]*prof->naxisn[1]*prof->naxisn[2];
3870
      QMALLOC(prof->pix, float, prof->npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
      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;
3881
3882
    case MODEL_TABULATED:	/* An example of tabulated profile */
      prof->name = "tabulated model";
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3883
      prof->naxis = 3;
3884
3885
3886
3887
3888
      width =  prof->naxisn[0] = PROFIT_MAXMODSIZE;
      height = prof->naxisn[1] = PROFIT_MAXMODSIZE;
      nsub = prof->naxisn[2] = PROFIT_MAXSMODSIZE;
      prof->npix = prof->naxisn[0]*prof->naxisn[1]*prof->naxisn[2];
      QMALLOC(prof->pix, float, prof->npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3889
3890
3891
3892
3893
3894
3895
      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;
3896
      scale = prof->extrascale[0]= 8.0/PROFIT_MAXSMODSIZE;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
      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;
    }

3928
  if (prof->naxis>2)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3929
3930
3931
3932
3933
3934
3935
3936
3937
    {
    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];
3938
    QMALLOC16(prof->kernelbuf, float, prof->kernelnlines);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
    }

  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 **************************************************************
3968
3969
PROTO	float prof_add(profitstruct *profit, profstruct *prof,
		int extfluxfac_flag)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3970
PURPOSE	Add a model profile to an image.
3971
3972
3973
3974
INPUT	Profile-fitting structure,
	profile structure,
	flag (0 if flux correction factor is to be computed internally) 
OUTPUT	Total (asymptotic) flux contribution.
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3975
3976
NOTES	-.
AUTHOR	E. Bertin (IAP)
3977
VERSION	13/02/2013
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3978
 ***/
3979
float	prof_add(profitstruct *profit, profstruct *prof, int extfluxfac_flag)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3980
  {
3981
3982
   double	xscale, yscale, saspect, ctheta,stheta, flux, scaling, bn, n,
		dx1cout,dx2cout, ddx1[36],ddx2[36];
3983
   float	posin[PROFIT_MAXEXTRA], posout[2], dnaxisn[2],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3984
		*pixin, *pixin2, *pixout,
3985
3986
		fluxfac, amp,cd11,cd12,cd21,cd22, dx1,dx2,
		x1,x10,x2, x1cin,x2cin, x1cout,x2cout, x1max,x2max, x1in,x2in,
3987
		k, hinvn, x1t,x2t, ca,sa, u,umin,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3988
3989
		armamp,arm2amp, armrdphidr, armrdphidrvar, posang,
		width, invwidth2,
3990
3991
		r,r2,rmin, r2minxin,r2minxout, rmax, r2max,
		r2max1, r2max2, r2min, invr2xdif,
3992
3993
		val, theta, thresh, ra,rb, num,num2,den, ang,angstep,
		invn, dr, krpinvn,dkrpinvn, rs,rs2,
3994
3995
3996
		a11,a12,a21,a22, invdet, dca,dsa, a0,a2,a3, p1,p2,
		krspinvn, ekrspinvn, selem;
   int		npix, threshflag,
3997
		a,d,e,i, ix1,ix2, ix1max,ix2max, nang, nx2,
3998
		npix2;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3999

4000
  npix = profit->nmodpix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4001

4002
  if (prof->code==MODEL_BACK)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4003
4004
4005
4006
4007
    {
    amp = fabs(*prof->flux);
    pixout = profit->modpix;
    for (i=npix; i--;)
      *(pixout++) += amp;
4008
4009
    prof->lostfluxfrac = 0.0;
    return 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4010
4011
4012
4013
    }

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

4014
  if (prof->code!=MODEL_DIRAC)
4015
4016
4017
4018
4019
4020
    {
/*-- 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
4021
		0.0 : fabs(scaling / (*prof->scale*prof->typscale));
4022
    yscale = (*prof->scale*saspect == 0.0)?
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4023
		0.0 : fabs(scaling / (*prof->scale*prof->typscale*saspect));
4024
4025
4026
4027
    cd11 = (float)(xscale*ctheta);
    cd12 = (float)(xscale*stheta);
    cd21 = (float)(-yscale*stheta);
    cd22 = (float)(yscale*ctheta);
4028
4029
4030
4031
4032
    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
4033
    nx2 = profit->modnaxisn[1]/2 + 1;
4034
4035
4036

/*-- Compute the largest r^2 that fits in the frame */
    num = cd11*cd22-cd12*cd21;
4037
    num *= num;
4038
4039
    x1max = x1cout - 1.0;
    x2max = x2cout - 1.0;
4040
4041
4042
4043
4044
4045
4046
    den = fabs(cd12*cd12+cd22*cd22);
    num2 = x1max*x1max*num;
    r2max1 = num2<PROFIT_MAXR2MAX*den? num2 / den : PROFIT_MAXR2MAX;
    den = fabs(cd11*cd11+cd21*cd21);
    num2 = x2max*x2max*num;
    r2max2 = num2<PROFIT_MAXR2MAX*den? num2 / den : PROFIT_MAXR2MAX;
    r2max = (r2max1 < r2max2? r2max1 : r2max2);
4047
    rmax = sqrtf(r2max);
4048
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4049
4050
4051

  switch(prof->code)
    {
4052
    case MODEL_DIRAC:
4053
      memset(prof->pix, 0, profit->nmodpix);
4054
4055
4056
4057
4058
      prof->pix[profit->modnaxisn[0]/2
		+ (profit->modnaxisn[1]/2)*profit->modnaxisn[0]] = 1.0;
      prof->lostfluxfrac = 0.0;
      threshflag = 0;
      break;
4059
4060
4061
    case MODEL_SERSIC:
    case MODEL_DEVAUCOULEURS:
    case MODEL_EXPONENTIAL:
4062
4063
4064
4065
4066
4067
/*---- Compute sharp/smooth transition radius */
      rs = PROFIT_SMOOTHR*(xscale>yscale?xscale:yscale);
      if (rs<=0)
        rs = 1.0;
      rs2 = rs*rs;
/*---- The consequence of sampling on flux is compensated by PSF normalisation*/
4068
      if (prof->code==MODEL_EXPONENTIAL)
4069
        bn = n = 1.0;
4070
      else if (prof->code==MODEL_DEVAUCOULEURS)
4071
4072
4073
4074
4075
4076
4077
4078
        {
        n = 4.0;
        bn = 7.66924944;
        }
      else
        {
        n = fabs(*prof->extra[0]);
        bn = 2.0*n - 1.0/3.0 + 4.0/(405.0*n) + 46.0/(25515.0*n*n)
4079
		+ 131.0/(1148175*n*n*n);	/* Ciotti & Bertin 1999 */
4080
4081
        }
      invn = 1.0/n;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4082
      hinvn = 0.5/n;
4083
4084
      k = -bn;
/*---- Compute central polynomial terms */
4085
      krspinvn = prof->code==MODEL_EXPONENTIAL? -rs : k*expf(logf(rs)*invn);
4086
4087
4088
4089
4090
4091
4092
      ekrspinvn = expf(krspinvn);
      p2 = krspinvn*invn*invn;
      p1 = krspinvn*p2;
      a0 = (1+(1.0/6.0)*(p1+(1.0-5.0*n)*p2))*ekrspinvn;
      a2 = (-1.0/2.0)*(p1+(1.0-3.0*n)*p2)/rs2*ekrspinvn;
      a3 = (1.0/3.0)*(p1+(1.0-2.0*n)*p2)/(rs2*rs)*ekrspinvn;
/*---- Compute the smooth part of the profile */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4093
4094
      x10 = -x1cout - dx1;
      x2 = -x2cout - dx2;
4095
      pixin = prof->pix;
4096
      if (prof->code==MODEL_EXPONENTIAL)
4097
        for (ix2=nx2; ix2--; x2+=1.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4098
          {
4099
4100
          x1 = x10;
          for (ix1=profit->modnaxisn[0]; ix1--; x1+=1.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4101
            {
4102
4103
4104
4105
            x1in = cd12*x2 + cd11*x1;
            x2in = cd22*x2 + cd21*x1;
            ra = x1in*x1in+x2in*x2in;
            if (ra>r2max)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4106
              {
4107
4108
              *(pixin++) = 0.0;
              continue;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4109
              }
4110
4111
            val = ra<rs2? a0+ra*(a2+a3*sqrtf(ra)) : expf(-sqrtf(ra));
            *(pixin++) = val;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4112
4113
            }
          }
4114
4115
      else
        for (ix2=nx2; ix2--; x2+=1.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4116
          {
4117
4118
          x1 = x10;
          for (ix1=profit->modnaxisn[0]; ix1--; x1+=1.0)
4119
            {
4120
4121
4122
4123
            x1in = cd12*x2 + cd11*x1;
            x2in = cd22*x2 + cd21*x1;
            ra = x1in*x1in+x2in*x2in;
            if (ra>r2max)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4124
              {
4125
4126
              *(pixin++) = 0.0;
              continue;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4127
              }
4128
4129
            val = ra<rs2? a0+ra*(a2+a3*sqrtf(ra)) : expf(k*expf(logf(ra)*hinvn));
            *(pixin++) = val;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4130
4131
            }
          }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4132
4133
4134
/*---- Copy the symmetric part */
      if ((npix2=(profit->modnaxisn[1]-nx2)*profit->modnaxisn[0]) > 0)
        {
4135
4136
4137
4138
4139
4140
        pixin2 = pixin - profit->modnaxisn[0] - 1;
        if (!(profit->modnaxisn[0]&1))
          {
          *(pixin++) = 0.0;
          npix2--;
          }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4141
4142
4143
        for (i=npix2; i--;)
          *(pixin++) = *(pixin2--);
        }
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158

/*---- Compute the sharp part of the profile */
      ix1max = profit->modnaxisn[0];
      ix2max = profit->modnaxisn[1];
      dx1cout = x1cout + 0.4999999;
      dx2cout = x2cout + 0.4999999;
      invdet = 1.0/fabsf(cd11*cd22 - cd12*cd21);
      a11 = cd22*invdet;
      a12 = -cd12*invdet;
      a21 = -cd21*invdet;
      a22 = cd11*invdet;
      nang = 72 / 2;		/* 36 angles; only half of them are computed*/
      angstep = PI/nang;
      ang = 0.0;
      for (a=0; a<nang; a++)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4159
        {
4160
#ifdef HAVE_SINCOSF
4161
4162
4163
4164
4165
4166
4167
        sincosf(ang, &dsa, &dca);
#else
        dsa = sinf(ang);
        dca = cosf(ang);
#endif
        ddx1[a] = a11*dsa+a12*dca;
        ddx2[a] = a21*dsa+a22*dca;
4168
        ang += angstep;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4169
        }
4170
4171
4172
4173
4174
4175
4176
      r = DEXPF(-4.0);
      dr = DEXPF(0.05);
      selem = 0.5*angstep*(dr - 1.0/dr)/(xscale*yscale);
      krpinvn = k*DEXPF(-4.0*invn);
      dkrpinvn = DEXPF(0.05*invn);
      pixin = prof->pix;
      for (; r<rs; r *= dr)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4177
        {
4178
4179
4180
        r2 = r*r;
        val = (expf(krpinvn) - (a0 + r2*(a2+a3*r)))*r2*selem;
        for (a=0; a<nang; a++)
4181
          {
4182
4183
4184
4185
4186
4187
4188
4189
          ix1 = (int)(dx1cout + r*ddx1[a]);
          ix2 = (int)(dx2cout + r*ddx2[a]);
          if (ix1>=0 && ix1<ix1max && ix2>=0 && ix2<ix2max)
            pixin[ix2*ix1max+ix1] += val;
          ix1 = (int)(dx1cout - r*ddx1[a]);
          ix2 = (int)(dx2cout - r*ddx2[a]);
          if (ix1>=0 && ix1<ix1max && ix2>=0 && ix2<ix2max)
            pixin[ix2*ix1max+ix1] += val;
4190
          }
4191
        krpinvn *= dkrpinvn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4192
        }
4193

4194
      prof->lostfluxfrac = prof->code==MODEL_EXPONENTIAL?
4195
4196
		(1.0 + rmax)*exp(-rmax)
		:1.0 - prof_gammainc(2.0*n, bn*pow(r2max, hinvn));
4197
      threshflag = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4198
      break;
4199
    case MODEL_ARMS:
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
      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;
4217
      pixin = prof->pix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
      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; 
         }
        }
4247
4248
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4249
      break;
4250
    case MODEL_BAR:
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
      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;
4264
      pixin = prof->pix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
      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;
          }
        }
4286
4287
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4288
      break;
4289
    case MODEL_INRING:
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
      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;
4302
      pixin = prof->pix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
      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;
          }
        }
4321
4322
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4323
      break;
4324
    case MODEL_OUTRING:
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
      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;
4335
      pixin = prof->pix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
      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;
          }
        }
4354
4355
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
      break;
    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])
4375
            posin[d] += (float)prof->naxisn[d];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4376
4377
4378
          else
            posin[d] = 1.0;
          }
4379
        else if (posin[d] > (float)prof->naxisn[d])
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4380
4381
4382
          {
          if (prof->extracycleflag[e])
          posin[d] = (prof->extracycleflag[e])?
4383
4384
		  fmod(posin[d], (float)prof->naxisn[d])
		: (float)prof->naxisn[d];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4385
4386
          }
        }
4387
4388
      x1cin = (float)(prof->naxisn[0]/2);
      x2cin = (float)(prof->naxisn[1]/2);
4389
      pixin = prof->pix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
      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;
        }
4403
4404
      prof->lostfluxfrac = 0.0;
      threshflag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4405
4406
4407
    break;
    }

4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
/* 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;
4425
    pixin = prof->pix;
4426
4427
4428
4429
4430
4431
4432
4433
    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
4434

4435
4436
/*-- Threshold and measure the flux */
    flux = 0.0;
4437
    pixin = prof->pix;
4438
4439
4440
4441
4442
4443
4444
    for (i=npix; i--; pixin++)
      if (*pixin >= thresh)
        flux += (double)*pixin;
      else
        *pixin = 0.0;
    }
  else
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4445
    {
4446
    flux = 0.0;
4447
    pixin = prof->pix;
4448
4449
    for (i=npix; i--;)
      flux += (double)*(pixin++);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4450
4451
    }

4452
4453
4454
4455
4456
4457
4458
  if (extfluxfac_flag)
    fluxfac = prof->fluxfac;
  else
    {
    if (prof->lostfluxfrac < 1.0)
      flux /= (1.0 - prof->lostfluxfrac);

4459
    prof->fluxfac = fluxfac = fabs(flux)>0.0? profit->fluxfac/fabs(flux) : 0.0;
4460
4461
4462
4463
4464
    }

  pixin = prof->pix;
  for (i=npix; i--;)
    *(pixin++) *= fluxfac;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4465
4466

/* Correct final flux */
4467
4468
  fluxfac = *prof->flux;
  pixin = prof->pix;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4469
  pixout = profit->modpix;
4470
  for (i=npix; i--;)
4471
    *(pixout++) += fluxfac**(pixin++);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4472

4473
  return *prof->flux;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4474
4475
4476
  }


4477
/****** prof_moments **********************************************************
4478
4479
PROTO	int	prof_moments(profitstruct *profit, profstruct *prof)
PURPOSE	Computes (analytically or numerically) the 2nd moments of a profile.
4480
INPUT	Profile-fitting structure,
4481
4482
4483
4484
	profile structure,
	optional pointer to 3xnparam Jacobian matrix.
OUTPUT	Index to the profile flux for further processing.
NOTES	.
4485
AUTHOR	E. Bertin (IAP)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4486
VERSION	20/08/2010
4487
 ***/
4488
int	prof_moments(profitstruct *profit, profstruct *prof, double *jac)
4489
  {
4490
4491
4492
4493
   double	*dmx2,*dmy2,*dmxy,
		m20, a2, ct,st, mx2fac, my2fac,mxyfac, dc2,ds2,dcs,
		bn,bn2, n,n2, nfac,nfac2, hscale2, dmdn;
   int		nparam, index;
4494

4495
4496
4497
4498
4499
4500
4501
4502
4503
  if (jac)
/*-- Clear output Jacobian */
    {
    nparam = profit->nparam;
    memset(jac, 0, nparam*3*sizeof(double));
    dmx2 = jac;
    dmy2 = jac + nparam;
    dmxy = jac + 2*nparam;
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4504
4505
4506
4507
4508
4509
4510
  else
    dmx2 = dmy2 = dmxy = NULL;		/* To avoid gcc -Wall warnings */

  m20 = 0.0;				/* to avoid gcc -Wall warnings */
  index = 0;				/* to avoid gcc -Wall warnings */


4511
4512
  if (prof->posangle)
    {
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
    a2 = *prof->aspect**prof->aspect;
    ct = cos(*prof->posangle*DEG);
    st = sin(*prof->posangle*DEG);
    mx2fac = ct*ct + st*st*a2;
    my2fac = st*st + ct*ct*a2;
    mxyfac = ct*st * (1.0 - a2);
    if (jac)
      {
      dc2 = -2.0*ct*st*DEG;
      ds2 =  2.0*ct*st*DEG;
      dcs = (ct*ct - st*st)*DEG;
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4525
4526
    else
      dc2 = ds2 = dcs = 0.0;		/* To avoid gcc -Wall warnings */
4527
4528
    switch(prof->code)
      {
4529
      case MODEL_SERSIC:
4530
4531
4532
        n = fabs(*prof->extra[0]);
        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 */
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
        nfac  = prof_gamma(4.0*n) / (prof_gamma(2.0*n)*pow(bn, 2.0*n));
        hscale2 = 0.5 * *prof->scale**prof->scale;
        m20 = hscale2 * nfac;
        if (jac)
          {
          dmx2[profit->paramindex[PARAM_SPHEROID_REFF]]
			= *prof->scale * nfac * mx2fac;
          dmy2[profit->paramindex[PARAM_SPHEROID_REFF]]
			= *prof->scale * nfac * my2fac;
          dmxy[profit->paramindex[PARAM_SPHEROID_REFF]]
			= *prof->scale * nfac * mxyfac;
          n2 = n+0.01;
          bn2 = 2.0*n2 - 1.0/3.0 + 4.0/(405.0*n2) + 46.0/(25515.0*n2*n2)
		+ 131.0/(1148175*n2*n2*n2);	/* Ciotti & Bertin 1999 */
          nfac2 = prof_gamma(4.0*n2) / (prof_gamma(2.0*n2)*pow(bn2, 2.0*n2));
          dmdn = 100.0 * hscale2 * (nfac2-nfac);
          dmx2[profit->paramindex[PARAM_SPHEROID_SERSICN]] = dmdn * mx2fac;
          dmy2[profit->paramindex[PARAM_SPHEROID_SERSICN]] = dmdn * my2fac;
          dmxy[profit->paramindex[PARAM_SPHEROID_SERSICN]] = dmdn * mxyfac;
          dmx2[profit->paramindex[PARAM_SPHEROID_ASPECT]]
			= 2.0 * m20 * st*st * *prof->aspect;
          dmy2[profit->paramindex[PARAM_SPHEROID_ASPECT]]
			= 2.0 * m20 * ct*ct * *prof->aspect;
          dmxy[profit->paramindex[PARAM_SPHEROID_ASPECT]]
			= -2.0 * m20 * ct*st * *prof->aspect;
          dmx2[profit->paramindex[PARAM_SPHEROID_POSANG]] = m20 * (dc2+ds2*a2);
          dmy2[profit->paramindex[PARAM_SPHEROID_POSANG]] = m20 * (ds2+dc2*a2);
          dmxy[profit->paramindex[PARAM_SPHEROID_POSANG]] = m20 * (1.0-a2)*dcs;
          }
        index = profit->paramindex[PARAM_SPHEROID_FLUX];
4563
        break; 
4564
      case MODEL_DEVAUCOULEURS:
4565
        m20 = 10.83995 * *prof->scale**prof->scale;
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
        if (jac)
          {
          dmx2[profit->paramindex[PARAM_SPHEROID_REFF]]
			= 21.680 * *prof->scale * mx2fac;
          dmy2[profit->paramindex[PARAM_SPHEROID_REFF]]
			= 21.680 * *prof->scale * my2fac;
          dmxy[profit->paramindex[PARAM_SPHEROID_REFF]]
			= 21.680 * *prof->scale * mxyfac;
          dmx2[profit->paramindex[PARAM_SPHEROID_ASPECT]]
			= 2.0 * m20 * st*st * *prof->aspect;
          dmy2[profit->paramindex[PARAM_SPHEROID_ASPECT]]
			= 2.0 * m20 * ct*ct * *prof->aspect;
          dmxy[profit->paramindex[PARAM_SPHEROID_ASPECT]]
			= -2.0 * m20 * ct*st * *prof->aspect;
          dmx2[profit->paramindex[PARAM_SPHEROID_POSANG]] = m20 * (dc2+ds2*a2);
          dmy2[profit->paramindex[PARAM_SPHEROID_POSANG]] = m20 * (ds2+dc2*a2);
          dmxy[profit->paramindex[PARAM_SPHEROID_POSANG]] = m20 * (1.0-a2)*dcs;
          }
        index = profit->paramindex[PARAM_SPHEROID_FLUX];
4585
        break;
4586
      case MODEL_EXPONENTIAL:
4587
        m20 = 3.0 * *prof->scale**prof->scale;
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
        if (jac)
          {
          dmx2[profit->paramindex[PARAM_DISK_SCALE]]
			= 6.0 * *prof->scale * mx2fac;
          dmy2[profit->paramindex[PARAM_DISK_SCALE]]
			= 6.0 * *prof->scale * my2fac;
          dmxy[profit->paramindex[PARAM_DISK_SCALE]]
			= 6.0 * *prof->scale * mxyfac;
          dmx2[profit->paramindex[PARAM_DISK_ASPECT]]
			= 2.0 * m20 * st*st * *prof->aspect;
          dmy2[profit->paramindex[PARAM_DISK_ASPECT]]
			= 2.0 * m20 * ct*ct * *prof->aspect;
          dmxy[profit->paramindex[PARAM_DISK_ASPECT]]
			= -2.0 * m20 * ct*st * *prof->aspect;
          dmx2[profit->paramindex[PARAM_DISK_POSANG]] = m20 * (dc2 + ds2*a2);
          dmy2[profit->paramindex[PARAM_DISK_POSANG]] = m20 * (ds2 + dc2*a2);
          dmxy[profit->paramindex[PARAM_DISK_POSANG]] = m20 * (1.0 - a2) * dcs;
          }
        index = profit->paramindex[PARAM_DISK_FLUX];
4607
        break;
4608
      case MODEL_ARMS:
4609
4610
4611
        m20 = 1.0;
        index = profit->paramindex[PARAM_ARMS_FLUX];
        break;
4612
      case MODEL_BAR:
4613
4614
4615
        m20 = 1.0;
        index = profit->paramindex[PARAM_BAR_FLUX];
        break;
4616
      case MODEL_INRING:
4617
4618
4619
        m20 = 1.0;
        index = profit->paramindex[PARAM_INRING_FLUX];
        break;
4620
      case MODEL_OUTRING:
4621
4622
        m20 = 1.0;
        index = profit->paramindex[PARAM_OUTRING_FLUX];
4623
4624
4625
4626
4627
4628
4629
        break;
      default:
        error(EXIT_FAILURE, "*Internal Error*: Unknown oriented model in ",
		"prof_moments()");
      break;
      }

4630
4631
4632
4633
    prof->mx2 = m20*mx2fac;
    prof->my2 = m20*my2fac;
    prof->mxy = m20*mxyfac;
    
4634
4635
4636
4637
    }
  else
    prof->mx2 = prof->my2 = prof->mxy = 0.0;

4638
  return index;
4639
4640
4641
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
4642
/****** prof_interpolate ******************************************************
4643
PROTO	float	prof_interpolate(profstruct *prof, float *posin)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4644
4645
4646
4647
4648
4649
4650
4651
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
 ***/
4652
static float	prof_interpolate(profstruct *prof, float *posin)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4653
  {
4654
   float		dpos[2+PROFIT_MAXEXTRA],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
			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 ******************************************************
4737
PROTO	void interpolate_pix(float *posin, float *pix, int naxisn,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
		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
 ***/
4749
static float	interpolate_pix(float *posin, float *pix, int *naxisn,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4750
4751
			interpenum interptype)
  {
4752
   float	buffer[INTERP_MAXKERNELWIDTH],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
		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 **********************************************************
4808
PROTO	void make_kernel(float pos, float *kernel, interpenum interptype)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4809
4810
4811
4812
4813
4814
4815
PURPOSE	Conpute interpolation-kernel data
INPUT	Position,
	Pointer to the output kernel data,
	Interpolation method.
OUTPUT	-.
NOTES	-.
AUTHOR	E. Bertin (IAP)
4816
VERSION	25/07/2011
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4817
 ***/
4818
void	make_kernel(float pos, float *kernel, interpenum interptype)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4819
  {
4820
   float	x, val, sinx1,sinx2,sinx3,cosx1;
4821

Emmanuel Bertin's avatar
Emmanuel Bertin committed
4822
4823
4824
4825
  if (interptype == INTERP_NEARESTNEIGHBOUR)
    *kernel = 1;
  else if (interptype == INTERP_BILINEAR)
    {
4826
    *(kernel++) = 1.0f-pos;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4827
4828
4829
4830
    *kernel = pos;
    }
  else if (interptype == INTERP_LANCZOS2)
    {
4831
    if (pos<1e-5f && pos>-1e-5f)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4832
      {
4833
4834
4835
4836
      *(kernel++) = 0.0f;
      *(kernel++) = 1.0f;
      *(kernel++) = 0.0f;
      *kernel = 0.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4837
4838
4839
      }
    else
      {
4840
      x = -PI/2.0f*(pos+1.0f);
4841
#ifdef HAVE_SINCOSF
4842
      sincosf(x, &sinx1, &cosx1);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4843
#else
4844
4845
      sinx1 = sinf(x);
      cosx1 = cosf(x);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4846
4847
#endif
      val = (*(kernel++) = sinx1/(x*x));
4848
      x += PI/2.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4849
      val += (*(kernel++) = -cosx1/(x*x));
4850
      x += PI/2.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4851
      val += (*(kernel++) = -sinx1/(x*x));
4852
      x += PI/2.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4853
      val += (*kernel = cosx1/(x*x));
4854
      val = 1.0f/val;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4855
4856
4857
4858
4859
4860
4861
4862
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *kernel *= val;
      }
    }
  else if (interptype == INTERP_LANCZOS3)
    {
4863
    if (pos<1e-5f && pos>-1e-5f)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4864
      {
4865
4866
4867
4868
4869
4870
      *(kernel++) = 0.0f;
      *(kernel++) = 0.0f;
      *(kernel++) = 1.0f;
      *(kernel++) = 0.0f;
      *(kernel++) = 0.0f;
      *kernel = 0.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4871
4872
4873
      }
    else
      {
4874
      x = -PI/3.0f*(pos+2.0f);
4875
#ifdef HAVE_SINCOSF
4876
      sincosf(x, &sinx1, &cosx1);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4877
#else
4878
4879
      sinx1 = sinf(x);
      cosx1 = cosf(x);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4880
4881
#endif
      val = (*(kernel++) = sinx1/(x*x));
4882
4883
      x += PI/3.0f;
      val += (*(kernel++) = (sinx2=-0.5f*sinx1-0.866025403785f*cosx1)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4884
				/ (x*x));
4885
4886
      x += PI/3.0f;
      val += (*(kernel++) = (sinx3=-0.5f*sinx1+0.866025403785f*cosx1)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4887
				/(x*x));
4888
      x += PI/3.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4889
      val += (*(kernel++) = sinx1/(x*x));
4890
      x += PI/3.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4891
      val += (*(kernel++) = sinx2/(x*x));
4892
      x += PI/3.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4893
      val += (*kernel = sinx3/(x*x));
4894
      val = 1.0f/val;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *(kernel--) *= val;
      *kernel *= val;
      }
    }
  else if (interptype == INTERP_LANCZOS4)
    {
4905
    if (pos<1e-5f && pos>-1e-5f)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4906
      {
4907
4908
4909
4910
4911
4912
4913
4914
      *(kernel++) = 0.0f;
      *(kernel++) = 0.0f;
      *(kernel++) = 0.0f;
      *(kernel++) = 1.0f;
      *(kernel++) = 0.0f;
      *(kernel++) = 0.0f;
      *(kernel++) = 0.0f;
      *kernel = 0.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4915
4916
4917
      }
    else
      {
4918
      x = -PI/4.0f*(pos+3.0f);
4919
#ifdef HAVE_SINCOSF
4920
      sincosf(x, &sinx1, &cosx1);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4921
#else
4922
4923
      sinx1 = sinf(x);
      cosx1 = cosf(x);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4924
4925
#endif
      val = (*(kernel++) = sinx1/(x*x));
4926
4927
      x += PI/4.0f;
      val +=(*(kernel++) = -(sinx2=0.707106781186f*(sinx1+cosx1))
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4928
				/(x*x));
4929
      x += PI/4.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4930
      val += (*(kernel++) = cosx1/(x*x));
4931
4932
4933
      x += PI/4.0f;
      val += (*(kernel++) = -(sinx3=0.707106781186f*(cosx1-sinx1))/(x*x));
      x += PI/4.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4934
      val += (*(kernel++) = -sinx1/(x*x));
4935
      x += PI/4.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4936
      val += (*(kernel++) = sinx2/(x*x));
4937
      x += PI/4.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4938
      val += (*(kernel++) = -cosx1/(x*x));
4939
      x += PI/4.0f;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4940
      val += (*kernel = sinx3/(x*x));
4941
      val = 1.0f/val;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
      *(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;
  }