psf.c 43.9 KB
Newer Older
1
2
/*
*				psf.c
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3
*
4
* Fit a PSF model 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) 1998-2020 IAP/CNRS/SorbonneU
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:		15/07/2020
26
27
*
*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
Emmanuel Bertin's avatar
Emmanuel Bertin committed
28
29
30
31
32
33
34
35
36
37
38
39

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

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

#include	"define.h"
#include	"globals.h"
40
#include	"key.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
41
42
43
44
45
#include	"prefs.h"
#include	"fits/fitscat.h"
#include	"check.h"
#include	"filter.h"
#include	"image.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
46
#include	"wcs/poly.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
47
48
49
50
51
52
#include	"psf.h"

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


extern keystruct	objkey[];
53
54
55
56

psfstruct	*psf,*thedpsf,*thepsf;
psfitstruct	*thepsfit,*thedpsfit;
PIXTYPE		*checkmask;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
57
58
59
60
61

/********************************* psf_init **********************************/
/*
Allocate memory and stuff for the PSF-fitting.
*/
62
void	psf_init(void)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
63
64
  {
  QMALLOC(thepsfit, psfitstruct, 1);
65
66
  QMALLOC(thepsfit->x, double, prefs.psf_npsfmax);
  QMALLOC(thepsfit->y, double, prefs.psf_npsfmax);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
67
  QMALLOC(thepsfit->flux, float, prefs.psf_npsfmax);
68
  QMALLOC(thepsfit->fluxerr, float, prefs.psf_npsfmax);
69
70
71
72
73
74
75
76
  if (prefs.dpsf_flag)
    {
    QMALLOC(thedpsfit, psfitstruct, 1);
    QMALLOC(thedpsfit->x, double, prefs.psf_npsfmax);
    QMALLOC(thedpsfit->y, double, prefs.psf_npsfmax);
    QMALLOC(thedpsfit->flux, float, prefs.psf_npsfmax);
    QMALLOC(thedpsfit->fluxerr, float, prefs.psf_npsfmax);
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
  return;
  }  


/********************************* psf_end ***********************************/
/*
Free memory occupied by the PSF-fitting stuff.
*/
void	psf_end(psfstruct *psf, psfitstruct *psfit)
  {
   int	d, ndim;

  if (psf->pc)
    pc_end(psf->pc);

  ndim = psf->poly->ndim;
  for (d=0; d<ndim; d++)
    free(psf->contextname[d]);
  free(psf->context);
96
  free(psf->contextindex);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
97
98
99
100
101
102
103
104
105
106
  free(psf->contextname);
  free(psf->contextoffset);
  free(psf->contextscale);
  free(psf->contexttyp);
  poly_end(psf->poly);
  free(psf->maskcomp);
  free(psf->maskloc);
  free(psf->masksize);
  free(psf);

Emmanuel Bertin's avatar
Emmanuel Bertin committed
107
108
109
110
111
  if (psfit)
    {
    free(psfit->x);
    free(psfit->y);
    free(psfit->flux);
112
    free(psfit->fluxerr);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
113
114
    free(psfit);
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
115
116
117
118
119
120
121
122
123

  return;
  }


/********************************* psf_load *********************************/
/*
Read the PSF data from a FITS file.
*/
124
psfstruct	*psf_load(char *filename, int ext)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
125
  {
126
   extern tabstruct	*objtab;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
127
128
129
130
131
132
   static objstruct	saveobj;
   static obj2struct	saveobj2;
   psfstruct		*psf;
   catstruct		*cat;
   tabstruct		*tab;
   keystruct		*key;
133
134
   char			rkeyname[80],
			*head, *ci,*co, *pstr, *pstrbuf;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
135
   int			deg[POLY_MAXDIM], group[POLY_MAXDIM], ndim, ngroup,
136
			d,e,i,k,p,n, keyn;
137

Emmanuel Bertin's avatar
Emmanuel Bertin committed
138
139
140
141
142
143
144
145
146
147
148
149
150
/* Open the cat (well it is not a "cat", but simply a FITS file */
  if (!(cat = read_cat(filename)))
    error(EXIT_FAILURE, "*Error*: PSF file not found: ", filename);

/* OK, we now allocate memory for the PSF structure itself */
  QCALLOC(psf, psfstruct, 1);

/* Store a short copy of the PSF filename */
  if ((ci=strrchr(filename, '/')))
    strcpy(psf->name, ci+1);
  else
    strcpy(psf->name, filename);

151
  tab = cat->tab;
152
153
  for (i=cat->ntab, e=ext?ext-1 : 0;
	i-- && (strcmp("PSF_DATA",tab->extname) || e--);
154
155
	tab = tab->nexttab);
  if (i<0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
156
157
158
159
160
161
    error(EXIT_FAILURE, "*Error*: PSF_DATA table not found in catalog ",
	filename);

  head = tab->headbuf;

/*-- Dimension of the polynomial */
162
  if (fitsread(head, "POLNAXIS", &ndim, H_INT,T_LONG) == RETURN_OK && ndim)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
163
164
165
166
167
168
169
170
171
172
173
    {
/*-- So we have a polynomial description of the PSF variations */
    if (ndim > POLY_MAXDIM)
        {
        sprintf(gstr, "*Error*: The POLNAXIS parameter in %s exceeds %d",
		psf->name, POLY_MAXDIM);
        error(EXIT_FAILURE, gstr, "");
        }

    QMALLOC(psf->contextname, char *, ndim);
    QMALLOC(psf->context, double *, ndim);
174
    QMALLOC(psf->contextindex, int, ndim);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    QMALLOC(psf->contexttyp, t_type, ndim);
    QMALLOC(psf->contextoffset, double, ndim);
    QMALLOC(psf->contextscale, double, ndim);

/*-- We will have to use the outobj structs, so we first save their content */
    saveobj = outobj;
    saveobj2 = outobj2;
/*-- outobj's are used as FLAG arrays, so we initialize them to 0 */
    memset(&outobj, 0, sizeof(outobj));
    memset(&outobj2, 0, sizeof(outobj2));
    for (i=0; i<ndim; i++)
      {
/*---- Polynomial groups */
      sprintf(gstr, "POLGRP%1d", i+1);
      if (fitsread(head, gstr, &group[i], H_INT,T_LONG) != RETURN_OK)
        goto headerror;

/*---- Contexts */
      QMALLOC(psf->contextname[i], char, 80);
      sprintf(gstr, "POLNAME%1d", i+1);
      if (fitsread(head,gstr,psf->contextname[i],H_STRING,T_STRING)!=RETURN_OK)
        goto headerror;
      if (*psf->contextname[i]==(char)':')
/*------ It seems we're facing a FITS header parameter */
        psf->context[i] = NULL;	/* This is to tell we'll have to load */
				/* a FITS header context later on */
      else
/*------ The context element is a dynamic object parameter */
        {
204
205
206
        strncpy(rkeyname, psf->contextname[i],40);
        strtok_r(rkeyname, "([{}])", &pstrbuf);
        if ((k = findkey(rkeyname, (char *)objkey,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
207
208
209
		sizeof(keystruct)))==RETURN_ERROR)
          {
          sprintf(gstr, "*Error*: %s CONTEXT parameter in %s unknown",
210
		rkeyname, psf->name);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
211
212
          error(EXIT_FAILURE, gstr, "");
          }
213
        keyn = (pstr = strtok_r(NULL,"([{}])", &pstrbuf))? atoi(pstr) - 1 : 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
214
        key = objkey+k;
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        if (key->naxis)
          {
          n = 1;
          for (d=0; d<key->naxis; d++)
            n *= key->naxisn[d];
          if (keyn >= n)
            {
/*---------- Increase vector size: we restrict ourselves to vectors (1D) */
            key->nbytes = key->naxisn[0] = keyn+1;
            key->naxis = 1;
            changecatparamarrays(rkeyname, key->naxisn, key->naxis);
            }
          }
        else
          keyn = -1;
        psf->context[i] = (double *)((char *)key->ptr);
        psf->contextindex[i] = keyn;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
232
233
234
        psf->contexttyp[i] = key->ttype;
/*------ Declare the parameter "active" to trigger computation by SExtractor */
        *((char *)key->ptr) = (char)'\1';
235
236
237
238
239
/*------ Add the key to the catalog */
        if (add_key(key, objtab, 0) != RETURN_ERROR)
          thecat.nparam++;
        if (!cistrcmp("MAG", rkeyname, FIND_NOSTRICT))
          psf->mag_flag = 1;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
        }
/*---- Scaling of the context parameter */
      sprintf(gstr, "POLZERO%1d", i+1);
      if (fitsread(head, gstr, &psf->contextoffset[i], H_EXPO, T_DOUBLE)
		!=RETURN_OK)
        goto headerror;
      sprintf(gstr, "POLSCAL%1d", i+1);
      if (fitsread(head, gstr, &psf->contextscale[i], H_EXPO, T_DOUBLE)
		!=RETURN_OK)
        goto headerror;
      }

/*-- Number of groups */
    if (fitsread(head, "POLNGRP ", &ngroup, H_INT, T_LONG) != RETURN_OK)
      goto headerror;

    for (i=0; i<ngroup; i++)
      {
/*---- Polynomial degree for each group */
      sprintf(gstr, "POLDEG%1d", i+1);
      if (fitsread(head, gstr, &deg[i], H_INT,T_LONG) != RETURN_OK)
        goto headerror;
      }

    psf->poly = poly_init(group, ndim, deg, ngroup);

/*-- Update the permanent FLAG arrays (that is, perform an "OR" on them) */
    for (ci=(char *)&outobj,co=(char *)&flagobj,i=sizeof(objstruct); i--;)
      *(co++) |= *(ci++);
    for (ci=(char *)&outobj2,co=(char *)&flagobj2,i=sizeof(obj2struct); i--;)
      *(co++) |= *(ci++);

/*-- Restore previous outobj contents */
    outobj = saveobj;
    outobj2 = saveobj2;
    }
  else
    {
/*-- This is a simple, constant PSF */
    psf->poly = poly_init(group, 0, deg, 0);
    psf->context = NULL;
    }

/* Dimensionality of the PSF mask */
  if (fitsread(head, "PSFNAXIS", &psf->maskdim, H_INT, T_LONG) != RETURN_OK)
    goto headerror;
  if (psf->maskdim<2 || psf->maskdim>3)
    error(EXIT_FAILURE, "*Error*: wrong dimensionality for the PSF "
	"mask in ", filename);
  QMALLOC(psf->masksize, int, psf->maskdim);
  for (i=0; i<psf->maskdim; i++)
    psf->masksize[i] = 1;
  psf->masknpix = 1;
  for (i=0; i<psf->maskdim; i++)
    {
    sprintf(gstr, "PSFAXIS%1d", i+1);
    if (fitsread(head, gstr, &psf->masksize[i], H_INT,T_LONG) != RETURN_OK)
      goto headerror;
    psf->masknpix *= psf->masksize[i];
    }

/* PSF FWHM: defaulted to 3 pixels */
 if (fitsread(head, "PSF_FWHM", &psf->fwhm, H_FLOAT,T_DOUBLE) != RETURN_OK)
    psf->fwhm = 3.0;

/* PSF oversampling: defaulted to 1 */
306
307
  if (fitsread(head, "PSF_SAMP", &psf->pixstep,H_FLOAT,T_FLOAT) != RETURN_OK
	|| psf->pixstep <= 0.0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
308
309
310
311
312
313
314
315
    psf->pixstep = 1.0;

/* Load the PSF mask data */
  key = read_key(tab, "PSF_MASK");
  psf->maskcomp = key->ptr;

  psf->pc = pc_load(cat);

316
  QMALLOC(psf->maskloc, float, psf->masksize[0]*psf->masksize[1]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

/* But don't touch my arrays!! */
  blank_keys(tab);

  free_cat(&cat, 1);

  return psf;

headerror:
  error(EXIT_FAILURE, "*Error*: Incorrect or obsolete PSF data in ", filename);
  return NULL;
  }


/***************************** psf_readcontext *******************************/
/*
Read the PSF context parameters in the FITS header.
*/
void	psf_readcontext(psfstruct *psf, picstruct *field)
  {
   static double	contextval[POLY_MAXDIM];
   int			i, ndim;

  ndim = psf->poly->ndim;
  for (i=0; i<ndim; i++)
    if (!psf->context[i])
      {
      psf->context[i] = &contextval[i];
      psf->contexttyp[i] = T_DOUBLE;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
346
      if (fitsread(field->tab->headbuf, psf->contextname[i]+1, &contextval[i],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
347
348
349
350
351
352
353
354
355
356
357
358
359
		H_FLOAT,T_DOUBLE) == RETURN_ERROR)
        {
        sprintf(gstr, "*Error*: %s parameter not found in the header of ",
		psf->contextname[i]+1);
        error(EXIT_FAILURE, gstr, field->rfilename);
        }
      }

  return;
  }


/******************************** psf_fit ***********************************/
360
/*                   standard PSF fit for one component                     */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
361
362
363
364
365
366
367
368
369
/****************************************************************************/

void	psf_fit(psfstruct *psf, picstruct *field, picstruct *wfield,
		objstruct *obj)
{
  checkstruct		*check;
  static obj2struct     *obj2 = &outobj2;
  static double		x2[PSF_NPSFMAX],y2[PSF_NPSFMAX],xy[PSF_NPSFMAX],
			deltax[PSF_NPSFMAX],
370
371
			deltay[PSF_NPSFMAX],
			flux[PSF_NPSFMAX],fluxerr[PSF_NPSFMAX],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
372
			deltaxb[PSF_NPSFMAX],deltayb[PSF_NPSFMAX],
373
			fluxb[PSF_NPSFMAX],fluxerrb[PSF_NPSFMAX],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
374
375
			sol[PSF_NTOT], covmat[PSF_NTOT*PSF_NTOT], 
			vmat[PSF_NTOT*PSF_NTOT], wmat[PSF_NTOT];
376
377
378
  float			*data, *data2, *data3, *weight, *d, *w;
  double		*mat,
			*m, *var,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
379
380
381
382
			dx,dy,
			pix,pix2, wthresh,val,
			backnoise2, gain, radmin2,radmax2,satlevel,chi2,
			r2, valmax, psf_fwhm;
383
  float			**psfmasks, **psfmaskx,**psfmasky,
384
			*ps, *dh, *wh, pixstep;
385
  PIXTYPE		*datah, *weighth;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
386
387
388
389
390
391
392
393
394
  int			i,j,p, npsf,npsfmax, npix, nppix, ix,iy,niter,
			width, height, pwidth,pheight, x,y,
			xmax,ymax, wbad, gainflag, convflag, npsfflag,
			ival,kill=0;
  
  dx = dy = 0.0;
  niter = 0;
  npsfmax = prefs.psf_npsfmax;
  pixstep = 1.0/psf->pixstep;
395
  gain = (field->gain >0.0? field->gain: 1e30);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
396
  backnoise2 = field->backsig*field->backsig;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
397
  satlevel = field->satur_level - obj->bkg;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
398
399
400
401
402
403
404
405
406
407
408
409
410
  wthresh = wfield?wfield->weight_thresh:BIG;
  gainflag = prefs.weightgain_flag;
  psf_fwhm = psf->fwhm*psf->pixstep;

 
  /* Initialize outputs */
  thepsfit->niter = 0;
  thepsfit->npsf = 0;
  for (j=0; j<npsfmax; j++) 
    {
      thepsfit->x[j] = obj2->posx;
      thepsfit->y[j] = obj2->posy;
      thepsfit->flux[j] = 0.0;
411
      thepsfit->fluxerr[j] = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    }

  /* Scale data area with object "size" */
  ix = (obj->xmax+obj->xmin+1)/2;
  iy = (obj->ymax+obj->ymin+1)/2;
  width = obj->xmax-obj->xmin+1+psf_fwhm;
  if (width < (ival=(int)(psf_fwhm*2)))
    width = ival;
  height = obj->ymax-obj->ymin+1+psf_fwhm;
  if (height < (ival=(int)(psf_fwhm*2)))
    height = ival;
  npix = width*height;
  radmin2 = PSF_MINSHIFT*PSF_MINSHIFT;
  radmax2 = npix/2.0;

  /* Scale total area with PSF FWHM */
  pwidth = (int)(psf->masksize[0]*psf->pixstep)+width;;
  pheight = (int)(psf->masksize[1]*psf->pixstep)+height;
  nppix = pwidth*pheight;

  QMALLOC(weighth, PIXTYPE, npix);
433
  QMALLOC(weight, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
434
  QMALLOC(datah, PIXTYPE, npix);
435
436
437
  QMALLOC(data, float, npix);
  QMALLOC(data2, float, npix);
  QMALLOC(data3, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
438
439
440
441
442
443
444
445
  QMALLOC(mat, double, npix*PSF_NTOT);
  if (prefs.check[CHECK_SUBPSFPROTOS] || prefs.check[CHECK_PSFPROTOS]
      || prefs.check[CHECK_SUBPCPROTOS] || prefs.check[CHECK_PCPROTOS]
      || prefs.check[CHECK_PCOPROTOS])
    {
      QMALLOC(checkmask, PIXTYPE, nppix);
    }

446
447
448
  QMALLOC(psfmasks, float *, npsfmax);
  QMALLOC(psfmaskx, float *, npsfmax);
  QMALLOC(psfmasky, float *, npsfmax);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
449
450
  for (i=0; i<npsfmax; i++)
    {
451
452
453
      QMALLOC(psfmasks[i], float, npix);
      QMALLOC(psfmaskx[i], float, npix);
      QMALLOC(psfmasky[i], float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    }

  copyimage(field, datah, width, height, ix, iy);

  /* Compute weights */
  wbad = 0;
  if (wfield)
    {
      copyimage(wfield, weighth, width, height, ix, iy);
      for (wh=weighth, w=weight, dh=datah,p=npix; p--;)
        if ((pix=*(wh++)) < wthresh && pix>0
            && (pix2=*(dh++))>-BIG
            && pix2<satlevel)
          *(w++) = 1/sqrt(pix+(pix2>0.0?
                               (gainflag? pix2*pix/backnoise2:pix2)/gain
                               :0.0));
        else
          {
            *(w++) = 0.0;
            wbad++;
          }
    }
  else
    for (w=weight, dh=datah, p=npix; p--;)
      if ((pix=*(dh++))>-BIG && pix<satlevel)
        *(w++) = 1.0/sqrt(backnoise2+(pix>0.0?pix/gain:0.0));
      else
        {
          *(w++) = 0.0;
          wbad++;
        }

  /* Special action if most of the weights are zero!! */
  if (wbad>=npix-3)
    return;

  /* Weight the data */
  dh = datah;
  val = obj->dbkg;      /* Take into account a local background change */
  d = data;
  w = weight;
  for (p=npix; p--;)
    *(d++) = (*(dh++)-val)**(w++);

  /* Get the local PSF */
  psf_build(psf);

  npsfflag = 1;
  r2 = psf_fwhm*psf_fwhm/2.0;
503
  fluxb[0] = fluxerrb[0] = deltaxb[0] = deltayb[0] = 0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583

  for (npsf=1; npsf<=npsfmax && npsfflag; npsf++)
    {
      kill=0;
/*-- First compute an optimum initial guess for the positions of components */
      if (npsf>1)
        {
/*---- Subtract previously fitted components */
          d = data2;
          dh = datah;
          for (p=npix; p--;)
            *(d++) = (double)*(dh++);
          for (j=0; j<npsf-1; j++)
            {
              d = data2;
              ps = psfmasks[j];
              for (p=npix; p--;)
                *(d++) -= flux[j]**(ps++);
            }
          convolve_image(field, data2, data3, width,height);
/*---- Ignore regions too close to stellar cores */
          for (j=0; j<npsf-1; j++)
            {
              d = data3;
              dy = -((double)(height/2)+deltay[j]);
              for (y=height; y--; dy += 1.0)
                {
                  dx = -((double)(width/2)+deltax[j]);
                  for (x=width; x--; dx+= 1.0, d++)
                    if (dx*dx+dy*dy<r2)
                      *d = -BIG;
                }
            }
/*---- Now find the brightest pixel (poor man's guess, to be refined later) */
          d = data3;
          valmax = -BIG;
          xmax = width/2;
          ymax = height/2;
          for (y=0; y<height; y++)
            for (x=0; x<width; x++)
              {
                if ((val = *(d++))>valmax)
                  {
                    valmax = val;
                    xmax = x;
                    ymax = y;
                  }
              }
          deltax[npsf-1] = (double)(xmax - width/2);
          deltay[npsf-1] = (double)(ymax - height/2);
        }
      else
        {
/*---- Only one component to fit: simply use the barycenter as a guess */
          deltax[npsf-1] = obj->mx - ix;
          deltay[npsf-1] = obj->my - iy;
        }

      niter = 0;
      convflag = 1;
      for (i=0; i<PSF_NITER && convflag; i++)
        {
          convflag = 0,niter++,m=mat;
          for (j=0; j<npsf; j++)
            {
/*------ Resample the PSFs here for the 1st iteration */
              vignet_resample(psf->maskloc, psf->masksize[0], psf->masksize[1],
                              psfmasks[j], width, height,
                              -deltax[j]*pixstep, -deltay[j]*pixstep,
                              pixstep);       
              m=compute_gradient(weight,width,height,
                                 psfmasks[j],psfmaskx[j],psfmasky[j],m);
            }
          
          
          svdfit(mat, data, npix, npsf*PSF_NA, sol, vmat, wmat);
          
          compute_pos( &npsf, &convflag, &npsfflag,radmin2,radmax2,
                       r2, sol,flux, deltax, deltay,&dx,&dy);
        }
584

Emmanuel Bertin's avatar
Emmanuel Bertin committed
585
/*-- Compute variances and covariances */
586
587
588
589
      svdvar(vmat, wmat, npsf*PSF_NA, covmat);
      var = covmat;
      for (j=0; j<npsf; j++, var += (npsf*PSF_NA+1)*PSF_NA)
        {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
590
/*---- First, the error on the flux estimate */      
591
          fluxerr[j] = sqrt(*var)>0.0?  sqrt(*var):999999.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
592
593
          //if (flux[j]<12*fluxerr && j>0)
          //  npsfmax--,flux[j]=0;
594
          if (flux[j]<12*fluxerr[j] && j>0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
595
596
597
598
599
600
601
602
603
604
605
606
607
608
                 {
                   flux[j]=0,kill++,npsfmax--;
                   //if(j==npsfmax-1)
                   //  kill++;             
                 } 
        }
      if (npsfflag)
        {
/*--- If we reach this point we know the data are worth backuping */
          for (j=0; j<npsf; j++)
            {
              deltaxb[j] = deltax[j];
              deltayb[j] = deltay[j];
              fluxb[j] = flux[j];
609
              fluxerrb[j]=fluxerr[j];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
            }
        }
    }
  npsf=npsf-1-kill;

/* Now keep only fitted stars that fall within the current detection area */
  i = 0;
  for (j=0; j<npsf; j++)
    {      
      x = (int)(deltaxb[j]+0.4999)+width/2;
      y = (int)(deltayb[j]+0.4999)+height/2;
      if (x<0 || x>=width || y<0 || y>=height)
        continue;
      if (weight[y*width+x] < 1/BIG)
        continue;
      if (10*fluxb[j]<fluxb[0] )
        continue;
      if (fluxb[j]<=0 )
        continue; 

      if (FLAG(obj2.poserrmx2_psf))
631
        compute_poserr(j,covmat,sol,obj2,x2,y2,xy, npsf);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
632
633
634
      
      deltax[i] = deltaxb[j];
      deltay[i] = deltayb[j];
635
636
      flux[i] = fluxb[j];
      fluxerr[i++] = fluxerrb[j];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
637
    }
638

Emmanuel Bertin's avatar
Emmanuel Bertin committed
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
  npsf = i;

  /* Compute chi2 if asked to 
  if (FLAG(obj2.chi2_psf))
    {
      for (j=0; j<npsf; j++)
        {
          chi2 = 0.0;
          for (d=data,w=weight,p=0; p<npix; w++,p++)
            {
              pix = *(d++);
              pix -=  psfmasks[j][p]*flux[j]**w;
              chi2 += pix*pix;
              if (chi2>1E29) chi2=1E28;
            }
          obj2->chi2_psf = obj->sigbkg>0.?
            chi2/((npix - 3*npsf)*obj->sigbkg*obj->sigbkg):999999;

        }
      
    }*/
 /* Compute relative chi2 if asked to */
    if (FLAG(obj2.chi2_psf))
    {
      for (j=0; j<npsf; j++)
        {
          chi2 = 0.0;
          for (d=data,w=weight,p=0; p<npix; w++,p++)
            {
              pix = *(d++)/flux[j];
              pix -=  psfmasks[j][p]**w;
              chi2 += pix*pix;
              if (chi2>1E29) chi2=1E28;
            }
          obj2->chi2_psf = flux[j]>0?
		chi2/((npix - 3*npsf)*obj->sigbkg*obj->sigbkg):999999;

        }
      
    }
  /* CHECK images */
  if (prefs.check[CHECK_SUBPSFPROTOS] || prefs.check[CHECK_PSFPROTOS])
    for (j=0; j<npsf; j++)
      {
        vignet_resample(psf->maskloc, psf->masksize[0], psf->masksize[1],
684
                        checkmask, pwidth, pheight,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
685
686
687
688
689
690
691
692
693
694
695
696
697
698
                        -deltax[j]*pixstep, -deltay[j]*pixstep, pixstep);
        if ((check = prefs.check[CHECK_SUBPSFPROTOS]))
          addcheck(check, checkmask, pwidth,pheight, ix,iy,-flux[j]);
        if ((check = prefs.check[CHECK_PSFPROTOS]))
          addcheck(check, checkmask, pwidth,pheight, ix,iy,flux[j]);
      }

  thepsfit->niter = niter;
  thepsfit->npsf = npsf;
  for (j=0; j<npsf; j++)
    {
      thepsfit->x[j] = ix+deltax[j]+1.0;
      thepsfit->y[j] = iy+deltay[j]+1.0;
      thepsfit->flux[j] = flux[j];
699
      thepsfit->fluxerr[j] = fluxerr[j];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
    }




  /* Now the morphology stuff */
  if (prefs.pc_flag)
    {
      width = pwidth-1;
      height = pheight-1;
      npix = width*height;
      copyimage(field, datah, width, height, ix, iy);

      /*-- Re-compute weights */
      if (wfield)
        {
          copyimage(wfield, weighth, width, height, ix, iy);
          for (wh=weighth ,w=weight, p=npix; p--;)
            *(w++) = (pix=*(wh++))<wthresh? sqrt(pix): 0.0;
        }
      else
        for (w=weight, dh=datah, p=npix; p--;)
          *(w++) = ((pix = *(dh++))>-BIG && pix<satlevel)?
            1.0/sqrt(backnoise2+(pix>0.0?pix/gain:0.0))
            :0.0;

      /*-- Weight the data */
      dh = datah;
      d = data;
      w = weight;
      for (p=npix; p--;)
        *(d++) = *(dh++)*(*(w++));

      pc_fit(psf, data, weight, width, height, ix,iy, dx,dy, npix,
             field->backsig);
    }
  
  
  for (i=0; i<prefs.psf_npsfmax; i++)
    {
      QFREE(psfmasks[i]);
      QFREE(psfmaskx[i]);
      QFREE(psfmasky[i]);
    }

  QFREE(psfmasks);
  QFREE(psfmaskx);
  QFREE(psfmasky);
  QFREE(datah);
  QFREE(data);
  QFREE(data2);
  QFREE(data3);
  QFREE(weighth);
  QFREE(weight);
  QFREE(data);
  QFREE(mat);

  if (prefs.check[CHECK_SUBPSFPROTOS] || prefs.check[CHECK_PSFPROTOS]
      || prefs.check[CHECK_SUBPCPROTOS] || prefs.check[CHECK_PCPROTOS]
      || prefs.check[CHECK_PCOPROTOS])
    {
      QFREE(checkmask);
    }

  return;
}


/******************************** double_psf_fit *******************************
****/
/* double fit to make the psf detection on one image and the photometry on anoth
er */
/*******************************************************************************
****/

775
776
777
void    double_psf_fit(psfstruct *psf, picstruct *field, picstruct *wfield,
                       objstruct *obj, psfstruct *dpsf, picstruct *dfield, 
                       picstruct *dwfield)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
778
779
780
{
  static double      /* sum[PSF_NPSFMAX]*/ pdeltax[PSF_NPSFMAX],
    pdeltay[PSF_NPSFMAX],psol[PSF_NPSFMAX], pcovmat[PSF_NPSFMAX*PSF_NPSFMAX], 
781
782
    pvmat[PSF_NPSFMAX*PSF_NPSFMAX], pwmat[PSF_NPSFMAX],pflux[PSF_NPSFMAX],
    pfluxerr[PSF_NPSFMAX];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
783

784
785
    double *pmat,
     *pm, /* *pps,  *px, *py,*/
Emmanuel Bertin's avatar
Emmanuel Bertin committed
786
787
788
789
    dx,dy,pdx,pdy, /* x1,y1, mx,my,mflux, */
    val, ppix,ppix2, /* dflux, */
    gain, radmin2,radmax2,satlevel
    ,chi2,pwthresh,pbacknoise2, /* mr, */
790
791
    r2=0, dpsf_fwhm,psf_fwhm ;
  float         **psfmasks, **psfmaskx,**psfmasky, *pps;
792
793
  float         *pdata, *pdata2, *pdata3, *pweight, *pd, *pw, 
		*pdh, *pwh, pixstep,ppixstep;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
794
795
796
797
798
799
800
801
802
  PIXTYPE       *pdatah, *pweighth;
  int                   i,j,k,p, npsf, npix,ix,iy,
    width, height, /* hw,hh, */
    x,y, /* yb, */
    wbad, gainflag,
    ival,npsfmax;
  double *pvar;
  
    static obj2struct   *obj2 = &outobj2;
803

Emmanuel Bertin's avatar
Emmanuel Bertin committed
804
  pdx = pdy =dx = dy = 0.0;
805
806
807
  ppixstep = 1.0/psf->pixstep;
  pixstep = 1.0/dpsf->pixstep;
  gain = (dfield->gain >0.0? dfield->gain: 1e30);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
808
  npsfmax=prefs.psf_npsfmax;
809
810
  pbacknoise2 = field->backsig*field->backsig;
  satlevel = dfield->satur_level - obj->bkg;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
811
  gainflag = prefs.weightgain_flag;
812
  dpsf_fwhm = dpsf->fwhm*dpsf->pixstep;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
813
  psf_fwhm = psf->fwhm*psf->pixstep;
814
  pwthresh = wfield?wfield->weight_thresh:BIG;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
815
816

  /* Initialize outputs */
817
818
  thepsfit->niter = 0;
  thepsfit->npsf = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
819
820
  for (j=0; j<npsfmax; j++) 
    {
821
822
823
824
      thepsfit->x[j] = 999999.0;
      thepsfit->y[j] = 999999.0;
      thepsfit->flux[j] = 0.0;
      thepsfit->fluxerr[j] = 0.0;
825
      pdeltax[j]= pdeltay[j]=psol[j]= pwmat[j]=pflux[j]=pfluxerr[j]=0.0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
826
827
828
829
830
   
    }

  ix = (obj->xmax+obj->xmin+1)/2;
  iy = (obj->ymax+obj->ymin+1)/2;
831
832
  width = obj->xmax-obj->xmin+1+dpsf_fwhm;
  if (width < (ival=(int)(dpsf_fwhm*2)))
Emmanuel Bertin's avatar
Emmanuel Bertin committed
833
    width = ival;
834
835
  height = obj->ymax-obj->ymin+1+dpsf_fwhm;
  if (height < (ival=(int)(dpsf_fwhm*2)))
Emmanuel Bertin's avatar
Emmanuel Bertin committed
836
837
838
839
    height = ival;
  npix = width*height;
  radmin2 = PSF_MINSHIFT*PSF_MINSHIFT;
  radmax2 = npix/2.0;
840
841
  psf_fit(dpsf,dfield, dwfield,obj);
  npsf=thedpsfit->npsf;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
842
  
843
844
845
  QMALLOC(psfmasks,float *,npsfmax);
  QMALLOC(psfmaskx,float *,npsfmax);
  QMALLOC(psfmasky,float *,npsfmax);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
846
847
848

  for (i=0; i<npsfmax; i++)
    {
849
850
851
      QMALLOC(psfmasks[i],float,npix);
      QMALLOC(psfmaskx[i],float,npix);
      QMALLOC(psfmasky[i],float,npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
852
853
854
    }

  QMALLOC(pweighth, PIXTYPE, npix);
855
  QMALLOC(pweight, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
856
  QMALLOC(pdatah, PIXTYPE, npix);
857
858
859
  QMALLOC(pdata, float, npix);
  QMALLOC(pdata2, float, npix);
  QMALLOC(pdata3, float, npix);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
860
861
862
863
  QMALLOC(pmat, double, npix*npsfmax);
  
   for (j=0; j<npsf; j++)
    {
864
865
866
867
      pdeltax[j] =thedpsfit->x[j]-ix-1 ;
      pdeltay[j] =thedpsfit->y[j]-iy-1 ;
      thepsfit->flux[j] = 0;
      thepsfit->fluxerr[j] = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
868
869
870
    }

/*-------------------  Now the photometry fit ---------------------*/
871
  copyimage(field, pdatah, width, height, ix, iy);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
872
873
   /* Compute photometry weights */
  wbad = 0;
874
  if (wfield)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
875
    {
876
       copyimage(wfield, pweighth, width, height, ix, iy);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
      for (pwh=pweighth, pw=pweight, pdh=pdatah,p=npix; p--;)
        {
        if ((ppix=*(pwh++)) < pwthresh && ppix>0
            && (ppix2=*(pdh++))>-BIG  && ppix2<satlevel)
          {
            *(pw++) = 1/sqrt(ppix+(ppix2>0.0?
			(gainflag? ppix2*ppix/pbacknoise2:ppix2)/gain : 0.0));
          }
      else
          {
            *(pw++) = 0.0;          
            wbad++;
          }
        }
    }
  else
    for (pw=pweight, pdh=pdatah, p=npix; p--;)
      if ((ppix=*(pdh++))>-BIG && ppix<satlevel)
          {
            *(pw++) = 1.0/sqrt(pbacknoise2+(ppix>0.0?ppix/gain:0.0));
          }
      else
        {
          *(pw++) = 0.0;
          wbad++;
        }
  /* Special action if most of the weights are zero!! */
  if (wbad>=npix-3)
    return;

  /* Weight the data */
  pdh = pdatah;
  pd = pdata;
  pw = pweight;
  val = obj->dbkg;
  for (p=npix; p--;)
    *(pd++) = (*(pdh++)-val)**(pw++);

 
  /* Get the photmetry PSF */
917
  psf_build(psf);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
918
919
920
921
922
923
924
925
926
927
928
929
  for (j=1; j<=npsf; j++)
    {
      if (j>1)
        {
          /*---- Subtract //previously fitted components in photometry image */
          pd = pdata2;
          pdh = pdatah;
          for (p=npix; p--;)
            *(pd++) = (double)*(pdh++);
          for (k=0; k<j-1; k++)
            {
              pd = pdata2;
930
              pps = psfmasks[k];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
931
932
933
              for (p=npix; p--;)
                *(pd++) -= pflux[k]**(pps++);
            }
934
          convolve_image(field, pdata2, pdata3, width,height);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
         /*---- Ignore regions too close to stellar cores */
          for (k=0; k<j-1; k++)
            {
              pd = pdata3;
              dy = -((double)(height/2)+pdeltay[k]);
              for (y=height; y--; dy += 1.0)
                {
                  dx = -((double)(width/2)+pdeltax[k]);
                  for (x=width; x--; dx+= 1.0, pd++)
                    if (dx*dx+dy*dy<r2) /*?*/
                      *pd = -BIG;
                }
            } 
        }
   
      pm=pmat;
      for (k=0; k<j; k++)
            {
              /*------ Resample the PSFs here for the 1st iteration */
954
955
956
              vignet_resample(psf->maskloc,
			psf->masksize[0], psf->masksize[1],
			psfmasks[k], width, height,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
957
958
			-pdeltax[k]*ppixstep, -pdeltay[k]*ppixstep,
			ppixstep);              
959
              pm=compute_gradient_phot(pweight,width,height, psfmasks[k],pm);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
960
961
962
963
964
965
966
967
968
            }
      
      svdfit(pmat, pdata, npix, j, psol, pvmat, pwmat);  
      compute_pos_phot( &j, psol,pflux);
   
  for (k=0; k<j; k++)
        {
          svdvar(pvmat, pwmat, j, pcovmat);
          pvar = pcovmat;
969
          pfluxerr[k]= sqrt(*pvar)>0.0 && sqrt(*pvar)<99? 
Emmanuel Bertin's avatar
Emmanuel Bertin committed
970
971
972
973
974
975
976
977
978
979
980
981
            sqrt(*pvar):99;
        }
    }
  /* Compute chi2 if asked to 
  if (FLAG(obj2.chi2_psf))
    {
      for (j=0; j<npsf; j++)
        {
          chi2 = 0.0;
          for (pd=pdata,pw=pweight,p=0; p<npix; pw++,p++)
            {
              ppix = *(pd++);
982
              ppix -=  psfmasks[j][p]*pflux[j]**pw;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
              chi2 += ppix*ppix;
              if (chi2>1E29) chi2=1E28;
            }
          obj2->chi2_psf = obj->sigbkg>0.?
            chi2/((npix - 3*npsf)*obj->sigbkg*obj->sigbkg):999999;

        }
      
    }
 */
 /* Compute relative error if asked to */
  if (FLAG(obj2.chi2_psf))
  {
      for (j=0; j<npsf; j++)
        {
          chi2 = 0.0;
          for (pd=pdata,pw=pweight,p=0; p<npix; pw++,p++)
            {
              ppix = *(pd++)/pflux[j];
1002
              ppix -=  psfmasks[j][p]**pw;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1003
1004
1005
1006
1007
1008
1009
1010
1011
              chi2 += ppix*ppix;
              if (chi2>1E29) chi2=1E28;
            }
          obj2->chi2_psf = pflux[j]>0?
		chi2/((npix - 3*npsf)*obj->sigbkg*obj->sigbkg):999999;

        }
      
    }
1012
1013
  thepsfit->niter = thedpsfit->niter;
  thepsfit->npsf = npsf;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1014
1015
1016

  for (j=0; j<npsf; j++)
    {
1017
1018
1019
1020
      thedpsfit->x[j] = ix+pdeltax[j]+1.0;
      thedpsfit->y[j] = iy+pdeltay[j]+1.0;
      thedpsfit->flux[j] = pflux[j];
      thedpsfit->fluxerr[j] = pfluxerr[j];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1021
1022
1023
      thepsfit->x[j] = ix+pdeltax[j]+1.0;
      thepsfit->y[j] = iy+pdeltay[j]+1.0;
      thepsfit->flux[j] = pflux[j];
1024
      thepsfit->fluxerr[j] = pfluxerr[j];
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1025
1026
1027
1028
1029
    }
    
  
  for (i=0; i<npsfmax; i++)
    {
1030
1031
1032
      QFREE(psfmasks[i]);
      QFREE(psfmaskx[i]);
      QFREE(psfmasky[i]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1033
1034
1035
    }

  
1036
1037
1038
  QFREE(psfmasks);
  QFREE(psfmaskx);
  QFREE(psfmasky);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
  QFREE(pdatah);
  QFREE(pdata);
  QFREE(pdata2);
  QFREE(pdata3);
  QFREE(pweighth);
  QFREE(pweight);
  QFREE(pdata);
  QFREE(pmat);
   
  if (prefs.check[CHECK_SUBPSFPROTOS] || prefs.check[CHECK_PSFPROTOS]
      || prefs.check[CHECK_SUBPCPROTOS] || prefs.check[CHECK_PCPROTOS]
      || prefs.check[CHECK_PCOPROTOS])
    {
      QFREE(checkmask);
    }
  return;
}

/******************************* psf_build **********************************/
/*
Build the local PSF (function of "context").
*/
void	psf_build(psfstruct *psf)
  {
   static double	pos[POLY_MAXDIM];
1064
1065
   double	*basis, fac;
   float	*ppc, *pl;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1066
1067
   int		i,n,p, ndim, npix;

1068
1069
1070
  if (psf->build_flag)
    return;

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1071
1072
1073
  npix = psf->masksize[0]*psf->masksize[1];

/* Reset the Local PSF mask */
1074
  memset(psf->maskloc, 0, npix*sizeof(float));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1075
1076
1077
1078
1079

/* Grab the context vector */
  ndim = psf->poly->ndim;
  for (i=0; i<ndim; i++)
    {
1080
1081
1082
1083
    ttypeconv(psf->contextindex[i]<0? (char *)psf->context[i]
		: *((char **)psf->context[i])
			+ psf->contextindex[i]*t_size[psf->contexttyp[i]],
		&pos[i], psf->contexttyp[i],T_DOUBLE);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
    pos[i] = (pos[i] - psf->contextoffset[i]) / psf->contextscale[i];
    }
  poly_func(psf->poly, pos);

  basis = psf->poly->basis;

  ppc = psf->maskcomp;
/* Sum each component */
  for (n = (psf->maskdim>2?psf->masksize[2]:1); n--;)
    {
    pl = psf->maskloc;
    fac = *(basis++);
    for (p=npix; p--;)
      *(pl++) +=  fac**(ppc++);
    }

1100
1101
  psf->build_flag = 1;

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1102
1103
1104
1105
  return;
  }


1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
/******************************** psf_fwhm **********************************/
/*
Return the local PSF FWHM.
*/
double	psf_fwhm(psfstruct *psf)
  {
   float	*pl,
		val, max;
   int		n,p, npix;

  if (!psf->build_flag)
    psf_build(psf);

  npix = psf->masksize[0]*psf->masksize[1];
  max = -BIG;
  pl = psf->maskloc;
  for (p=npix; p--;)
    if ((val=*(pl++)) > max)
      max = val;
  pl = psf->maskloc;
  max /= 2.0;
  n = 0;
  for (p=npix; p--;)
    if (*(pl++) >= max)
      n++;

  return 2.0*sqrt(n/PI)*psf->pixstep;
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
1136
1137
/*****************************compute_gradient*********************************/

1138
1139
double *compute_gradient(float *weight,int width, int height,
                         float *masks,float *maskx,float *masky
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1140
1141
1142
                        ,double *m)
{
  int x,y;
1143
  float	*w, *ps,*px,*py;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
    
  /*------ copy of the (weighted) PSF, with outer ring set to zero */
      ps = masks;
      w = weight;
      for (y=0; y<height; y++)
        for (x=0; x<width; x++, ps++, w++)
          *(m++) = y?(y>=(height-1)?0:(x?(x>=(width-1)?0:*ps**w):0)):0;
      /*------ (weighted) PSF gradient in x (kernel for first moment in x) */
      ps = masks;
      px = maskx;
      w = weight;
      for (y=0; y<height; y++)
        for (x=0; x<width; x++, ps++, w++)
          *(m++) = ((*px++) = (x?(x>=(width-1)?0:*(ps+1)-*(ps-1)):0))**w/2;
      /*------ (weighted) PSF gradient in y (kernel for first moment in y) */
      ps = masks; 
      py = masky;
      w = weight;
      for (y=0; y<height; y++)
        for (x=0; x<width; x++, ps++, w++)
          *(m++) = (*(py++)=(y?(y>=(height-1)?0:*(ps+width)-*(ps-width)):0))
            **w/2;
  return m;
}

/*****************************compute_gradient_phot*****************************
****/

1172
1173
double *compute_gradient_phot(float  *pweight,int width, int height,
                         float *pmasks,double *pm)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1174
1175
1176

{
  int x,y;
1177
  float  *pw, *pps;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1178
1179
1180
1181
1182
1183
1184
1185
1186
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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
    
  /*------ copy of the (weighted) PSF, with outer ring set to zero */
      pps = pmasks;
      pw = pweight;
      for (y=0; y<height; y++)
        for (x=0; x<width; x++, pps++, pw++)
          *(pm++) = y?(y>=(height-1)?0:(x?(x>=(width-1)?0:*pps**pw):0)):0;

  return pm;
}

/**************************compute_pos********************************/

void compute_pos(int *pnpsf,int *pconvflag,int *pnpsfflag,double radmin2,
                         double radmax2,double r2,double *sol,double *flux 
                        ,double *deltax,double *deltay,double *pdx,double *pdy)
{
  int j,k,convflag,npsfflag,npsf; 
  double dx,dy;

  dx=*pdx;
  dy=*pdy;
  convflag=*pconvflag;
  npsfflag=*pnpsfflag;
  npsf=*pnpsf;
  for (j=0; j<npsf; j++)
    {
      flux[j] = sol[j*PSF_NA];
      /*------ Update the PSF shifts */
      if (fabs(flux[j])>0.0)
        {
          dx = -sol[j*PSF_NA+1]/((npsf>1?2:1)*flux[j]);
          dy = -sol[j*PSF_NA+2]/((npsf>1?2:1)*flux[j]);
        }
      
      deltax[j] += dx;
      deltay[j] += dy;
      /*------ Continue until all PSFs have come to a complete stop */
      if ((dx*dx+dy*dy) > radmin2)
        convflag = 1;
    }
  for (j=0; j<npsf; j++)
    {
      /*------ Exit if too much decentering or negative flux */
      for (k=j+1; k<npsf; k++)
        {
          dx = deltax[j]-deltax[k];
          dy = deltay[j]-deltay[k];
          if (dx*dx+dy*dy<r2/4.0)
            {
              flux[j] = -BIG;
              break;
            }
        }
      if (flux[j]<0.0
          || (deltax[j]*deltax[j] + deltay[j]*deltay[j]) > radmax2)
        {
          npsfflag = 0;
          convflag = 0;
          npsf--;
          break;
        }
    }
  *pdx=dx;
  *pdy=dy;
  *pconvflag=convflag;
  *pnpsfflag= npsfflag;
  *pnpsf=npsf;
  return;
}

/**************************compute_pos_phot********************************/

void compute_pos_phot(int *pnpsf,double *sol,double *flux)
{
  int j,npsf;   
  npsf=*pnpsf;
  for (j=0; j<npsf; j++)
    {
      flux[j] = sol[j];     
    }
  *pnpsf=npsf;
  return;
}


/************************************compute_poserr*****************************
*********/

void compute_poserr( int j,double *var,double *sol,obj2struct *obj2,double *x2,
1268
                    double *y2,double *xy, int npsf)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1269
{
1270
  double vara,covab,varb, f2;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1271
1272

  /*------ Variances and covariance along x and y */
1273
  vara = *(var += (PSF_NA*npsf+1)*(j*PSF_NA+1));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1274
  covab = *(++var);
1275
1276
1277
1278
1279
1280
1281
  varb = *(var += PSF_NA*npsf);
  f2 = sol[PSF_NA*j];
  f2 *= f2;
  obj2->poserrmx2_psf = vara/f2;
  obj2->poserrmy2_psf = varb/f2;
  obj2->poserrmxy_psf = covab/f2;

Emmanuel Bertin's avatar
Emmanuel Bertin committed
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
  /*------ If requested, translate variances to major and minor error axes... */
  if (FLAG(obj2.poserra_psf))
    {
      double    pmx2,pmy2,temp,theta;
      
      if (fabs(temp=obj2->poserrmx2_psf-obj2->poserrmy2_psf) > 0.0)
        theta = atan2(2.0 * obj2->poserrmxy_psf,temp) / 2.0;
      else
        theta = PI/4.0;
      
      temp = sqrt(0.25*temp*temp+obj2->poserrmxy_psf*obj2->poserrmxy_psf);
      pmy2 = pmx2 = 0.5*(obj2->poserrmx2_psf+obj2->poserrmy2_psf);
      pmx2+=temp;
      pmy2-=temp;
1296

Emmanuel Bertin's avatar
Emmanuel Bertin committed
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
      obj2->poserra_psf = (float)sqrt(pmx2);
      obj2->poserrb_psf = (float)sqrt(pmy2);
      obj2->poserrtheta_psf = theta*180.0/PI;
    }
  
  /*------ ...Or ellipse parameters */
  if (FLAG(obj2.poserr_cxx))
    {
      double    xm2,ym2, xym, temp;
      
      xm2 = obj2->poserrmx2_psf;
      ym2 = obj2->poserrmy2_psf;
      xym = obj2->poserrmxy_psf;
      obj2->poserrcxx_psf = (float)(ym2/(temp=xm2*ym2-xym*xym));
      obj2->poserrcyy_psf = (float)(xm2/temp);
      obj2->poserrcxy_psf = (float)(-2*xym/temp);
    }
  return;
}


/******************************** svdfit ************************************/
/*
General least-square fit A.x = b, based on Singular Value Decomposition (SVD).
Loosely adapted from Numerical Recipes in C, 2nd Ed. (p. 671).
Note: the a and v matrices are transposed with respect to the N.R. convention.
*/
1324
void svdfit(double *a, float *b, int m, int n, double *sol,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
	double *vmat, double *wmat)
  {
#define MAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ?\
        (maxarg1) : (maxarg2))
#define	PYTHAG(a,b)	((at=fabs(a)) > (bt=fabs(b)) ? \
				  (ct=bt/at,at*sqrt(1.0+ct*ct)) \
				: (bt ? (ct=at/bt,bt*sqrt(1.0+ct*ct)): 0.0))
#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
#define	TOL		1.0e-11

   int			flag,i,its,j,jj,k,l,nm,mmi,nml;
   double		c,f,h,s,x,y,z,
			anorm, g, scale,
			at,bt,ct,maxarg1,maxarg2,
			thresh, wmax,
			*w,*ap,*ap0,*ap1,*ap10,*rv1p,*vp,*vp0,*vp1,*vp10,
1341
1342
			*tmpp, *rv1,*tmp;
   float		*bp;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
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
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
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
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674

  anorm = g = scale = 0.0;
  if (m < n)
    error(EXIT_FAILURE, "*Error*: Not enough rows for solving the system ",
	"in svdfit()");
  
  QMALLOC(rv1, double, n);
  QMALLOC(tmp, double, n);
  l = nm = nml = 0;			/* To avoid gcc -Wall warnings */
  for (i=0;i<n;i++)
    {
    l = i+1;
    nml = n-l;
    rv1[i] = scale*g;
    g = s = scale = 0.0;
    if ((mmi = m - i) > 0)
      {
      ap = ap0 = a+i*(m+1);
      for (k=mmi;k--;)
        scale += fabs(*(ap++));
      if (scale)
        {
        for (ap=ap0,k=mmi; k--; ap++)
          {
          *ap /= scale;
          s += *ap**ap;
          }
        f = *ap0;
        g = -SIGN(sqrt(s),f);
        h = f*g-s;
        *ap0 = f-g;
        ap10 = a+l*m+i;
        for (j=nml;j--; ap10+=m)
          {
          for (s=0.0,ap=ap0,ap1=ap10,k=mmi; k--;)
            s += *(ap1++)**(ap++);
          f = s/h;
          for (ap=ap0,ap1=ap10,k=mmi; k--;)
            *(ap1++) += f**(ap++);
          }
        for (ap=ap0,k=mmi; k--;)
          *(ap++) *= scale;
        }
      }
    wmat[i] = scale*g;
    g = s = scale = 0.0;
    if (i < m && i+1 != n)
      {
      ap = ap0 = a+i+m*l;
      for (k=nml;k--; ap+=m)
        scale += fabs(*ap);
      if (scale)
        {
        for (ap=ap0,k=nml;k--; ap+=m)
          {
          *ap /= scale;
          s += *ap**ap;
          }
        f=*ap0;
        g = -SIGN(sqrt(s),f);
        h=f*g-s;
        *ap0=f-g;
        rv1p = rv1+l;
        for (ap=ap0,k=nml;k--; ap+=m)
          *(rv1p++) = *ap/h;
        ap10 = a+l+m*l;
        for (j=m-l; j--; ap10++)
          {
          for (s=0.0,ap=ap0,ap1=ap10,k=nml; k--; ap+=m,ap1+=m)
            s += *ap1**ap;
          rv1p = rv1+l;
          for (ap1=ap10,k=nml;k--; ap1+=m)
            *ap1 += s**(rv1p++);
          }
        for (ap=ap0,k=nml;k--; ap+=m)
          *ap *= scale;
        }
      }
    anorm=MAX(anorm,(fabs(wmat[i])+fabs(rv1[i])));
    }

  for (i=n-1;i>=0;i--)
    {
    if (i < n-1)
      {
      if (g)
        {
        ap0 = a+l*m+i;
        vp0 = vmat+i*n+l;
        vp10 = vmat+l*n+l;
        g *= *ap0;
        for (ap=ap0,vp=vp0,j=nml; j--; ap+=m)
          *(vp++) = *ap/g;
        for (j=nml; j--; vp10+=n)
          {
          for (s=0.0,ap=ap0,vp1=vp10,k=nml; k--; ap+=m)
            s += *ap**(vp1++);
          for (vp=vp0,vp1=vp10,k=nml; k--;)
            *(vp1++) += s**(vp++);
          }
        }
      vp = vmat+l*n+i;
      vp1 = vmat+i*n+l;
      for (j=nml; j--; vp+=n)
        *vp = *(vp1++) = 0.0;
      }
    vmat[i*n+i]=1.0;
    g=rv1[i];
    l=i;
    nml = n-l;
    }

  for (i=(m<n?m:n); --i>=0;)
    {
    l=i+1;
    nml = n-l;
    mmi=m-i;
    g=wmat[i];
    ap0 = a+i*m+i;
    ap10 = ap0 + m;
    for (ap=ap10,j=nml;j--;ap+=m)
      *ap=0.0;
    if (g)
      {
      g=1.0/g;
      for (j=nml;j--; ap10+=m)
        {
        for (s=0.0,ap=ap0,ap1=ap10,k=mmi; --k;)
              s += *(++ap)**(++ap1);
        f = (s/(*ap0))*g;
        for (ap=ap0,ap1=ap10,k=mmi;k--;)
          *(ap1++) += f**(ap++);
        }
      for (ap=ap0,j=mmi;j--;)
        *(ap++) *= g;
      }
    else
      for (ap=ap0,j=mmi;j--;)
        *(ap++)=0.0;
    ++(*ap0);
    }

  for (k=n; --k>=0;)
      {
      for (its=0;its<100;its++)
        {
        flag=1;
        for (l=k;l>=0;l--)
          {
          nm=l-1;
          if (fabs(rv1[l])+anorm == anorm)
            {
            flag=0;
            break;
            }
          if (fabs(wmat[nm])+anorm == anorm)
            break;
          }
        if (flag)
          {
          c=0.0;
          s=1.0;
          ap0 = a+nm*m;
          ap10 = a+l*m;
          for (i=l; i<=k; i++,ap10+=m)
            {
            f=s*rv1[i];
            if (fabs(f)+anorm == anorm)
              break;
            g=wmat[i];
            h=PYTHAG(f,g);
            wmat[i]=h;
            h=1.0/h;
            c=g*h;
            s=(-f*h);
            for (ap=ap0,ap1=ap10,j=m; j--;)
              {
              z = *ap1;
              y = *ap;
              *(ap++) = y*c+z*s;
              *(ap1++) = z*c-y*s;
              }
            }
          }
        z=wmat[k];
        if (l == k)
          {
          if (z < 0.0)
            {
            wmat[k] = -z;
            vp = vmat+k*n;
            for (j=n; j--; vp++)
              *vp = (-*vp);
            }
          break;
          }
        if (its == 99)
          error(EXIT_FAILURE, "*Error*: No convergence in 100 SVD iterations ",
		"in svdfit()");
        x=wmat[l];
        nm=k-1;
        y=wmat[nm];
        g=rv1[nm];
        h=rv1[k];
        f=((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y);
        g=PYTHAG(f,1.0);
        f=((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x;
        c=s=1.0;
        ap10 = a+l*m;
        vp10 = vmat+l*n;
        for (j=l;j<=nm;j++,ap10+=m,vp10+=n)
          {
          i=j+1;
          g=rv1[i];
          y=wmat[i];
          h=s*g;
          g=c*g;
          z=PYTHAG(f,h);
          rv1[j]=z;
          c=f/z;
          s=h/z;
          f=x*c+g*s;
          g=g*c-x*s;
          h=y*s;
          y=y*c;
          for (vp=(vp1=vp10)+n,jj=n; jj--;)
            {
            z = *vp;
            x = *vp1;
            *(vp1++) = x*c+z*s;
            *(vp++) = z*c-x*s;
            }
          z=PYTHAG(f,h);
          wmat[j]=z;
          if (z)
            {
            z=1.0/z;
            c=f*z;
            s=h*z;
            }
          f=c*g+s*y;
          x=c*y-s*g;
          for (ap=(ap1=ap10)+m,jj=m; jj--;)
            {
            z = *ap;
            y = *ap1;
            *(ap1++) = y*c+z*s;
            *(ap++) = z*c-y*s;
            }
          }
        rv1[l]=0.0;
        rv1[k]=f;
        wmat[k]=x;
        }
      }

  wmax=0.0;
  w = wmat;
  for (j=n;j--; w++)
    if (*w > wmax)
      wmax=*w;
  thresh=TOL*wmax;
  w = wmat;
  for (j=n;j--; w++)
    if (*w < thresh)
      *w = 0.0;

  w = wmat;
  ap = a;
  tmpp = tmp;
  for (j=n; j--; w++)
    {
    s=0.0;
    if (*w)
      {
      bp = b;
      for (i=m; i--;)
        s += *(ap++)**(bp++);
      s /= *w;
      }
    else
      ap += m;
    *(tmpp++) = s;
    }

  vp0 = vmat;
  for (j=0; j<n; j++,vp0++)
    {
    s=0.0;
    tmpp = tmp;
    for (vp=vp0,jj=n; jj--; vp+=n)
      s += *vp**(tmpp++);
    sol[j]=s;
    }

/* Free temporary arrays */
  free(tmp);
  free(rv1);

  return;
  }

#undef SIGN
#undef MAX
#undef PYTHAG
#undef TOL

/******************************** svdvar ************************************/
/*
Computation of the covariance matrix from the SVD vmat and wmat matrices.A
dapted from Numerical Recipes in C, 2nd Ed. (p. 679).
*/
void svdvar(double *v, double *w, int n, double *cov)
  {
   static double	wti[PSF_NTOT];
   double		sum;
   int			i,j,k;

  for (i=0; i<n; i++)
    wti[i] = w[i]? 1.0/(w[i]*w[i]) : 0.0;

  for (i=0; i<n; i++)
    for (j=0; j<=i; j++)
      {
      for (sum=0.0,k=0; k<n; k++)
        sum += v[k*n+i]*v[k*n+j]*wti[k];
      cov[j*n+i] = cov[i*n+j] = sum;
      }

  return;
  }