makeit.c 21.6 KB
Newer Older
Emmanuel Bertin's avatar
Emmanuel Bertin committed
1
/*
2
*				makeit.c
Emmanuel Bertin's avatar
Emmanuel Bertin committed
3
*
4
* Main program.
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) 1993-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:		23/09/2020
26
27
*
*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
Emmanuel Bertin's avatar
Emmanuel Bertin committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

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

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

#include	"define.h"
#include	"globals.h"
#include	"prefs.h"
#include	"fits/fitscat.h"
#include	"assoc.h"
#include	"back.h"
#include	"check.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
46
#include	"fft.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
47
48
49
50
#include	"field.h"
#include	"filter.h"
#include	"growth.h"
#include	"interpolate.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
51
#include	"pattern.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
52
#include	"psf.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
53
#include	"profit.h"
Emmanuel Bertin's avatar
Emmanuel Bertin committed
54
55
56
57
#include	"som.h"
#include	"weight.h"
#include	"xml.h"

Emmanuel Bertin's avatar
Emmanuel Bertin committed
58
static int		selectext(char *filename);
59

Emmanuel Bertin's avatar
Emmanuel Bertin committed
60
time_t			thetimet, thetimet2;
61
#ifdef USE_MODEL
62
extern profitstruct	*theprofit,*thedprofit, *thepprofit,*theqprofit;
63
#else
64
profitstruct		*theprofit,*thedprofit, *thepprofit,*theqprofit;
65
#endif
Emmanuel Bertin's avatar
Emmanuel Bertin committed
66
extern char		profname[][32];
67
68
69
70
71
72
extern float		ctg[37], stg[37];

sexcatstruct		thecat;
picstruct		thefield1,thefield2, thewfield1,thewfield2;
char			gstr[MAXCHAR];

Emmanuel Bertin's avatar
Emmanuel Bertin committed
73
74
75
76
77
78
79
80
81

/******************************** makeit *************************************/
/*
Manage the whole stuff.
*/
void	makeit()

  {
   checkstruct		*check;
82
83
   picstruct		*dfield, *field,*pffield[MAXFLAG], *wfield,*dwfield,
			*dgeofield;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
84
85
   catstruct		*imacat;
   tabstruct		*imatab;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
86
   patternstruct	*pattern;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
87
88
   static time_t        thetime1, thetime2;
   struct tm		*tm;
89
   double		dtime;
90
   unsigned int		modeltype;
91
   int			nflag[MAXFLAG], nparam2[2],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
92
			i, nok, ntab, next, ntabmax, forcextflag,
93
94
			nima0,nima1, nweight0,nweight1, npsf0,npsf1, npat,npat0,
			ndgeo;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
95
96
97
98
99

/* Install error logging */
  error_installfunc(write_error);

/* Processing start date and time */
100
  dtime = counter_seconds();
Emmanuel Bertin's avatar
Emmanuel Bertin committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
  thetimet = time(NULL);
  tm = localtime(&thetimet);
  sprintf(prefs.sdate_start,"%04d-%02d-%02d",
        tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
  sprintf(prefs.stime_start,"%02d:%02d:%02d",
        tm->tm_hour, tm->tm_min, tm->tm_sec);

  NFPRINTF(OUTPUT, "");
  QPRINTF(OUTPUT, "----- %s %s started on %s at %s with %d thread%s\n\n",
		BANNER,
		MYVERSION,
		prefs.sdate_start,
		prefs.stime_start,
		prefs.nthreads,
		prefs.nthreads>1? "s":"");

/* Initialize globals variables */
  initglob();

  NFPRINTF(OUTPUT, "Setting catalog parameters");
  readcatparams(prefs.param_name);
  useprefs();			/* update things accor. to prefs parameters */

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/* Check if a specific extension should be loaded */
  if ((nima0=selectext(prefs.image_name[0])) != RETURN_ERROR)
    {
    forcextflag = 1;
    ntabmax = next = 1;
    }
  else
    forcextflag = 0;

/* Do the same for other data (but do not force single extension mode) */
  nima1 = selectext(prefs.image_name[1]);
  nweight0 = selectext(prefs.wimage_name[0]);
  nweight1 = selectext(prefs.wimage_name[1]);
  if (prefs.dpsf_flag)
    {
    npsf0 = selectext(prefs.psf_name[0]);
    npsf1 = selectext(prefs.psf_name[1]);
    }
  else
    npsf0 = selectext(prefs.psf_name[0]);
  for (i=0; i<prefs.nfimage_name; i++)
    nflag[i] = selectext(prefs.fimage_name[i]);
146
  ndgeo = selectext(prefs.dgeoimage_name);
147

148
  if (prefs.psf_flag)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
149
    {
150
/*-- Read the first PSF extension to set up stuff such as context parameters */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
151
152
    NFPRINTF(OUTPUT, "Reading PSF information");
    if (prefs.dpsf_flag)
153
      {
154
155
      thedpsf = psf_load(prefs.psf_name[0],nima0<0? 1 :(npsf0<0? 1:npsf0)); 
      thepsf = psf_load(prefs.psf_name[1], nima1<0? 1 :(npsf1<0? 1:npsf1));
156
157
      }
    else
158
      thepsf = psf_load(prefs.psf_name[0], nima0<0? 1 :(npsf0<0? 1:npsf0)); 
Emmanuel Bertin's avatar
Emmanuel Bertin committed
159
160
161
162
163
 /*-- Need to check things up because of PSF context parameters */
    updateparamflags();
    useprefs();
    }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
164
165
  if (prefs.prof_flag)
    {
166
#ifdef USE_MODEL
167
    fft_init(prefs.nthreads);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
168
169
/* Create profiles at full resolution */
    NFPRINTF(OUTPUT, "Preparing profile models");
170
    modeltype = (FLAG(obj2.prof_offset_flux)? MODEL_BACK : MODEL_NONE)
171
172
173
174
175
176
	|(FLAG(obj2.prof_dirac_flux)? MODEL_DIRAC : MODEL_NONE)
	|(FLAG(obj2.prof_spheroid_flux)?
		(FLAG(obj2.prof_spheroid_sersicn)?
			MODEL_SERSIC : MODEL_DEVAUCOULEURS) : MODEL_NONE)
	|(FLAG(obj2.prof_disk_flux)? MODEL_EXPONENTIAL : MODEL_NONE)
	|(FLAG(obj2.prof_bar_flux)? MODEL_BAR : MODEL_NONE)
177
178
	|(FLAG(obj2.prof_arms_flux)? MODEL_ARMS : MODEL_NONE);
    theprofit = profit_init(thepsf, modeltype);
179
180
181
    changecatparamarrays("VECTOR_MODEL", &theprofit->nparam, 1);
    changecatparamarrays("VECTOR_MODELERR", &theprofit->nparam, 1);
    nparam2[0] = nparam2[1] = theprofit->nparam;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
182
    changecatparamarrays("MATRIX_MODELERR", nparam2, 2);
183
184
    if (prefs.dprof_flag)
      thedprofit = profit_init(thedpsf, modeltype);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
185
186
    if (prefs.pattern_flag)
      {
187
188
189
190
191
      npat0 = prefs.prof_disk_patternvectorsize;
      if (npat0<prefs.prof_disk_patternmodvectorsize)
        npat0 = prefs.prof_disk_patternmodvectorsize;
      if (npat0<prefs.prof_disk_patternargvectorsize)
        npat0 = prefs.prof_disk_patternargvectorsize;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
192
/*---- Do a copy of the original number of pattern components */
193
194
      prefs.prof_disk_patternncomp = npat0;
      pattern = pattern_init(theprofit, prefs.pattern_type, npat0);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
      if (FLAG(obj2.prof_disk_patternvector))
        {
        npat = pattern->size[2];
        changecatparamarrays("DISK_PATTERN_VECTOR", &npat, 1);
        }
      if (FLAG(obj2.prof_disk_patternmodvector))
        {
        npat = pattern->ncomp*pattern->nfreq;
        changecatparamarrays("DISK_PATTERNMOD_VECTOR", &npat, 1);
        }
      if (FLAG(obj2.prof_disk_patternargvector))
        {
        npat = pattern->ncomp*pattern->nfreq;
        changecatparamarrays("DISK_PATTERNARG_VECTOR", &npat, 1);
        }
      pattern_end(pattern);
      }
    QPRINTF(OUTPUT, "Fitting model: ");
    for (i=0; i<theprofit->nprof; i++)
      {
      if (i)
        QPRINTF(OUTPUT, "+");
217
      QPRINTF(OUTPUT, "%s", theprofit->prof[i]->name);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
218
219
      }
    QPRINTF(OUTPUT, "\n");
220
    if (FLAG(obj2.prof_concentration)|FLAG(obj2.prof_concentration))
221
      {
222
223
      thepprofit = profit_init(thepsf, MODEL_DIRAC);
      theqprofit = profit_init(thepsf, MODEL_EXPONENTIAL);
224
      }
225
226
227
228
229
#else
    error(EXIT_FAILURE,
		"*Error*: model-fitting is not supported in this build.\n",
			" Please check your configure options");
#endif
Emmanuel Bertin's avatar
Emmanuel Bertin committed
230
231
    }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
  if (prefs.filter_flag)
    {
    NFPRINTF(OUTPUT, "Reading detection filter");
    getfilter(prefs.filter_name);	/* get the detection filter */
    }

  if (FLAG(obj2.sprob))
    {
    NFPRINTF(OUTPUT, "Initializing Neural Network");
    neurinit();
    NFPRINTF(OUTPUT, "Reading Neural Network Weights");
    getnnw(); 
    }

  if (prefs.somfit_flag)
    {
     int	margin;

    thesom = som_load(prefs.som_name);
    if ((margin=(thesom->inputsize[1]+1)/2) > prefs.cleanmargin)
      prefs.cleanmargin = margin;
    if (prefs.somfit_vectorsize>thesom->neurdim)
      {
      prefs.somfit_vectorsize = thesom->neurdim;
      sprintf(gstr,"%d", prefs.somfit_vectorsize);
      warning("Dimensionality of the SOM-fit vector limited to ", gstr);
      }
    }

/* Prepare growth-curve buffer */
  if (prefs.growth_flag)
    initgrowth();

Emmanuel Bertin's avatar
Emmanuel Bertin committed
265
266
267
268
/* Allocate memory for multidimensional catalog parameter arrays */
  alloccatparams();
  useprefs();

Emmanuel Bertin's avatar
Emmanuel Bertin committed
269
270
271
272
  if (!(imacat = read_cat(prefs.image_name[0])))
    error(EXIT_FAILURE, "*Error*: cannot open ", prefs.image_name[0]);
  close_cat(imacat);
  imatab = imacat->tab;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
273
274

  if (!forcextflag)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
275
    {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
276
277
278
279
280
281
282
    ntabmax = imacat->ntab;
/*-- Compute the number of valid input extensions */
    next = 0;
    for (ntab = 0 ; ntab<imacat->ntab; ntab++, imatab = imatab->nexttab)
      {
/*---- Check for the next valid image extension */
      if ((imatab->naxis < 2)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
283
284
	|| !strncmp(imatab->xtension, "BINTABLE", 8)
	|| !strncmp(imatab->xtension, "ASCTABLE", 8))
285
286
287
288
#ifdef HAVE_CFITSIO
        if (!imatab->isTileCompressed)
#endif
          continue;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
289
290
      next++;
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
291
    }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
292

Emmanuel Bertin's avatar
Emmanuel Bertin committed
293
294
295
296
297
298
299
300
301
  thecat.next = next;

/*-- Init the CHECK-images */
  if (prefs.check_flag)
    {
     checkenum	c;

    NFPRINTF(OUTPUT, "Initializing check-image(s)");
    for (i=0; i<prefs.ncheck_type; i++)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
302
303
304
305
      if ((c=prefs.check_type[i]) != CHECK_NONE)
        {
        if (prefs.check[c])
           error(EXIT_FAILURE,"*Error*: 2 CHECK_IMAGEs cannot have the same ",
Emmanuel Bertin's avatar
Emmanuel Bertin committed
306
			" CHECK_IMAGE_TYPE");
Emmanuel Bertin's avatar
Emmanuel Bertin committed
307
        prefs.check[c] = initcheck(prefs.check_name[i], prefs.check_type[i],
Emmanuel Bertin's avatar
Emmanuel Bertin committed
308
			next);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
309
        }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
310
311
312
313
314
315
316
317
318
319
    }

  NFPRINTF(OUTPUT, "Initializing catalog");
  initcat();

/* Initialize XML data */
  if (prefs.xml_flag || prefs.cat_type==ASCII_VO)
    init_xml(next);

/* Go through all images */
320
  nok = 0;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
321
  for (ntab = 0 ; ntab<ntabmax; ntab++, imatab = imatab->nexttab)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
322
323
    {
/*--  Check for the next valid image extension */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
324
    if (!forcextflag && ((imatab->naxis < 2)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
325
	|| !strncmp(imatab->xtension, "BINTABLE", 8)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
326
	|| !strncmp(imatab->xtension, "ASCTABLE", 8)))
327
328
329
#ifdef HAVE_CFITSIO
        if (!imatab->isTileCompressed)
#endif
Emmanuel Bertin's avatar
Emmanuel Bertin committed
330
331
332
333
334
      continue;
    nok++;

/*-- Initial time measurement*/
    time(&thetime1);
335
    thecat.currext = nok;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
336

337
    dfield = field = wfield = dwfield = dgeofield = NULL;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
338
339
340
341

    if (prefs.dimage_flag)
      {
/*---- Init the Detection and Measurement-images */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
342
      dfield = newfield(prefs.image_name[0], DETECT_FIELD,
343
	nima0<0? ntab:nima0);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
344
      field = newfield(prefs.image_name[1], MEASURE_FIELD,
345
	nima1<0? ntab:nima1);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
346
      if ((field->width!=dfield->width) || (field->height!=dfield->height))
Emmanuel Bertin's avatar
Emmanuel Bertin committed
347
        error(EXIT_FAILURE, "*Error*: Frames have different sizes","");
Emmanuel Bertin's avatar
Emmanuel Bertin committed
348
349
350
351
352
353
354
355
/*---- Prepare interpolation */
      if (prefs.dweight_flag && prefs.interp_type[0] == INTERP_ALL)
        init_interpolate(dfield, -1, -1);
      if (prefs.interp_type[1] == INTERP_ALL)
        init_interpolate(field, -1, -1);
      }
    else
      {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
356
      field = newfield(prefs.image_name[0], DETECT_FIELD | MEASURE_FIELD,
357
		nima0<0? ntab:nima0);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
358

359
/*---- Prepare interpolation */
Emmanuel Bertin's avatar
Emmanuel Bertin committed
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
      if ((prefs.dweight_flag || prefs.weight_flag)
	&& prefs.interp_type[0] == INTERP_ALL)
      init_interpolate(field, -1, -1);       /* 0.0 or anything else */
      }

/*-- Init the WEIGHT-images */
    if (prefs.dweight_flag || prefs.weight_flag) 
      {
       weightenum	wtype;
       PIXTYPE	interpthresh;

      if (prefs.nweight_type>1)
        {
/*------ Double-weight-map mode */
        if (prefs.weight_type[1] != WEIGHT_NONE)
          {
/*-------- First: the "measurement" weights */
          wfield = newweight(prefs.wimage_name[1],field,prefs.weight_type[1],
378
379
		(nima1<0 && prefs.image_name[1])?
			ntab : (nweight1<0?1:nweight1));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
          wtype = prefs.weight_type[1];
          interpthresh = prefs.weight_thresh[1];
/*-------- Convert the interpolation threshold to variance units */
          weight_to_var(wfield, &interpthresh, 1);
          wfield->weight_thresh = interpthresh;
          if (prefs.interp_type[1] != INTERP_NONE)
            init_interpolate(wfield,
		prefs.interp_xtimeout[1], prefs.interp_ytimeout[1]);
          }
/*------ The "detection" weights */
        if (prefs.weight_type[0] != WEIGHT_NONE)
          {
          interpthresh = prefs.weight_thresh[0];
          if (prefs.weight_type[0] == WEIGHT_FROMINTERP)
            {
            dwfield=newweight(prefs.wimage_name[0],wfield,prefs.weight_type[0],
396
		nima0<0? ntab : (nweight0<0? 1 :nweight0));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
397
398
399
400
401
            weight_to_var(wfield, &interpthresh, 1);
            }
          else
            {
            dwfield = newweight(prefs.wimage_name[0], dfield?dfield:field,
402
		prefs.weight_type[0], nima0<0? ntab : (nweight0<0?1:nweight0));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
403
404
405
406
407
408
409
410
411
412
413
414
            weight_to_var(dwfield, &interpthresh, 1);
            }
          dwfield->weight_thresh = interpthresh;
          if (prefs.interp_type[0] != INTERP_NONE)
            init_interpolate(dwfield,
		prefs.interp_xtimeout[0], prefs.interp_ytimeout[0]);
          }
        }
      else
        {
/*------ Single-weight-map mode */
        wfield = newweight(prefs.wimage_name[0], dfield?dfield:field,
415
		prefs.weight_type[0], nima0<0? ntab : (nweight0<0?1:nweight0));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
        wtype = prefs.weight_type[0];
        interpthresh = prefs.weight_thresh[0];
/*------ Convert the interpolation threshold to variance units */
        weight_to_var(wfield, &interpthresh, 1);
        wfield->weight_thresh = interpthresh;
        if (prefs.interp_type[0] != INTERP_NONE)
          init_interpolate(wfield,
		prefs.interp_xtimeout[0], prefs.interp_ytimeout[0]);
        }
      }

/*-- Init the FLAG-images */
    for (i=0; i<prefs.nimaflag; i++)
      {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
430
      pffield[i] = newfield(prefs.fimage_name[i], FLAG_FIELD,
431
		nima0<0? ntab : (nflag[i]<0?1:nflag[i]));
Emmanuel Bertin's avatar
Emmanuel Bertin committed
432
433
434
435
436
437
      if ((pffield[i]->width!=field->width)
	|| (pffield[i]->height!=field->height))
        error(EXIT_FAILURE,
	"*Error*: Incompatible FLAG-map size in ", prefs.fimage_name[i]);
      }

438
439
440
441
442
443
444
445
446
447
448
449
/*-- Init the differential geometry images */
    if (prefs.dgeo_type != DGEO_NONE) {
      dgeofield = newfield(prefs.dgeoimage_name, DGEO_FIELD,
		nima0<0? ntab : (ndgeo<0?1:ndgeo));
      if ((dgeofield->width != field->width)
		|| (dgeofield->height != field->height))
        error(EXIT_FAILURE,
		"*Error*: Incompatible differential geometry map size in ",
		prefs.dgeoimage_name);
    }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
450
451
452
/*-- Compute background maps for `standard' fields */
    QPRINTF(OUTPUT, dfield? "Measurement image:"
			: "Detection+Measurement image: ");
453
    makeback(field, wfield, prefs.wscale_flag[1]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
454
455
456
457
458
459
460
    QPRINTF(OUTPUT, (dfield || (dwfield&&dwfield->flags^INTERP_FIELD))? "(M)   "
		"Background: %-10g RMS: %-10g / Threshold: %-10g \n"
		: "(M+D) "
		"Background: %-10g RMS: %-10g / Threshold: %-10g \n",
	field->backmean, field->backsig, (field->flags & DETECT_FIELD)?
	field->dthresh: field->thresh);
    if (dfield)
461
      {
Emmanuel Bertin's avatar
Emmanuel Bertin committed
462
463
      QPRINTF(OUTPUT, "Detection image: ");
      makeback(dfield, dwfield? dwfield
464
465
			: (prefs.weight_type[0] == WEIGHT_NONE?NULL:wfield),
		prefs.wscale_flag[0]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
466
467
468
469
470
471
      QPRINTF(OUTPUT, "(D)   "
		"Background: %-10g RMS: %-10g / Threshold: %-10g \n",
	dfield->backmean, dfield->backsig, dfield->dthresh);
      }
    else if (dwfield && dwfield->flags^INTERP_FIELD)
      {
472
      makeback(field, dwfield, prefs.wscale_flag[0]);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
      QPRINTF(OUTPUT, "(D)   "
		"Background: %-10g RMS: %-10g / Threshold: %-10g \n",
	field->backmean, field->backsig, field->dthresh);
      }

/*-- For interpolated weight-maps, copy the background structure */
    if (dwfield && dwfield->flags&(INTERP_FIELD|BACKRMS_FIELD))
      copyback(dwfield->reffield, dwfield);
    if (wfield && wfield->flags&(INTERP_FIELD|BACKRMS_FIELD))
      copyback(wfield->reffield, wfield);

/*-- Prepare learn and/or associations */
    if (prefs.assoc_flag)
      init_assoc(field);                  /* initialize assoc tasks */

/*-- Update the CHECK-images */
    if (prefs.check_flag)
      for (i=0; i<MAXCHECK; i++)
        if ((check=prefs.check[i]))
          reinitcheck(field, check);

494
    if (!forcextflag && nok>1)
495
496
497
498
499
500
501
502
503
      {
      if (prefs.psf_flag)
        {
/*------ Read other PSF extensions */
        NFPRINTF(OUTPUT, "Reading PSF information");
        psf_end(thepsf, thepsfit);
        if (prefs.dpsf_flag)
          {
          psf_end(thedpsf, thedpsfit);
504
505
          thedpsf = psf_load(prefs.psf_name[0], nok);
          thepsf = psf_load(prefs.psf_name[1], nok);
506
507
          }
        else
508
          thepsf = psf_load(prefs.psf_name[0], nok); 
509
510
        }

511
#ifdef USE_MODEL
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
      if (prefs.prof_flag)
        {
/*------ Create profiles at full resolution */
        profit_end(theprofit);
        theprofit = profit_init(thepsf, modeltype);
        if (prefs.dprof_flag)
          {
          profit_end(thedprofit);
          thedprofit = profit_init(thedpsf, modeltype);
          }
        if (prefs.pattern_flag)
          {
          pattern = pattern_init(theprofit, prefs.pattern_type, npat0);
          pattern_end(pattern);
          }
        if (FLAG(obj2.prof_concentration)|FLAG(obj2.prof_concentration))
          {
          profit_end(thepprofit);
          profit_end(theqprofit);
          thepprofit = profit_init(thepsf, MODEL_DIRAC);
          theqprofit = profit_init(thepsf, MODEL_EXPONENTIAL);
          }
        }
535
#endif
536
537
      }

Emmanuel Bertin's avatar
Emmanuel Bertin committed
538
539
540
541
/*-- Initialize PSF contexts and workspace */
    if (prefs.psf_flag)
      {
      psf_readcontext(thepsf, field);
542
      psf_init();
Emmanuel Bertin's avatar
Emmanuel Bertin committed
543
544
545
      if (prefs.dpsf_flag)
        {
        psf_readcontext(thepsf, dfield);
546
        psf_init();
Emmanuel Bertin's avatar
Emmanuel Bertin committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
        }
      }

/*-- Copy field structures to static ones (for catalog info) */
    if (dfield)
      {
      thefield1 = *field;
      thefield2 = *dfield;
      }
    else
      thefield1 = thefield2 = *field;

    if (wfield)
      {
      thewfield1 = *wfield;
      thewfield2 = dwfield? *dwfield: *wfield;
      }
    else if (dwfield)
      thewfield2 = *dwfield;

    reinitcat(field);

/*-- Start the extraction pipeline */
    NFPRINTF(OUTPUT, "Scanning image");
571
572
    scanimage(field, dfield, pffield, prefs.nimaflag, wfield, dwfield,
		dgeofield);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592

/*-- Finish the current CHECK-image processing */
    if (prefs.check_flag)
      for (i=0; i<MAXCHECK; i++)
        if ((check=prefs.check[i]))
          reendcheck(field, check);

/*-- Final time measurements*/
    if (time(&thetime2)!=-1)
      {
      if (!strftime(thecat.ext_date, 12, "%d/%m/%Y", localtime(&thetime2)))
        error(EXIT_FAILURE, "*Internal Error*: Date string too long ","");
      if (!strftime(thecat.ext_time, 10, "%H:%M:%S", localtime(&thetime2)))
        error(EXIT_FAILURE, "*Internal Error*: Time/date string too long ","");
      thecat.ext_elapsed = difftime(thetime2, thetime1);
      }

    reendcat();

/* Update XML data */
593
594
    if (prefs.xml_flag || prefs.cat_type==ASCII_VO)
      update_xml(&thecat, dfield? dfield:field, field,
Emmanuel Bertin's avatar
Emmanuel Bertin committed
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
	dwfield? dwfield:wfield, wfield);


/*-- Close ASSOC routines */
    end_assoc(field);

    for (i=0; i<prefs.nimaflag; i++)
      endfield(pffield[i]);
    endfield(field);
    if (dfield)
      endfield(dfield);
    if (wfield)
      endfield(wfield);
    if (dwfield)
      endfield(dwfield);
610
611
    if (dgeofield)
      endfield(dgeofield);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
612

613
    QPRINTF(OUTPUT, "      Objects: detected %-8d / sextracted %-8d        \n\n",
Emmanuel Bertin's avatar
Emmanuel Bertin committed
614
615
616
	thecat.ndetect, thecat.ntotal);
    }

617
  if (nok<=0)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
    error(EXIT_FAILURE, "Not enough valid FITS image extensions in ",
	prefs.image_name[0]);
  free_cat(&imacat, 1);

  NFPRINTF(OUTPUT, "Closing files");

/* End CHECK-image processing */
  if (prefs.check_flag)
    for (i=0; i<MAXCHECK; i++)
      {
      if ((check=prefs.check[i]))
        endcheck(check);
      prefs.check[i] = NULL;
      }

  if (prefs.filter_flag)
    endfilter();

  if (prefs.somfit_flag)
    som_end(thesom);

  if (prefs.growth_flag)
    endgrowth();

642
#ifdef USE_MODEL
Emmanuel Bertin's avatar
Emmanuel Bertin committed
643
644
645
  if (prefs.prof_flag)
    {
    profit_end(theprofit);
646
647
    if (prefs.dprof_flag)
      profit_end(thedprofit);
648
649
650
651
652
    if (FLAG(obj2.prof_concentration)|FLAG(obj2.prof_concentration))
      {
      profit_end(thepprofit);
      profit_end(theqprofit);
      }
Emmanuel Bertin's avatar
Emmanuel Bertin committed
653
654
    fft_end();
    }
655
#endif
Emmanuel Bertin's avatar
Emmanuel Bertin committed
656

657
  if (prefs.psf_flag)
658
    psf_end(thepsf, thepsfit);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
659
660

  if (prefs.dpsf_flag)
661
    psf_end(thedpsf, thedpsfit);
Emmanuel Bertin's avatar
Emmanuel Bertin committed
662
663
664
665
666
667
668
669
670
671
672

  if (FLAG(obj2.sprob))
    neurclose();

/* Processing end date and time */
  thetimet2 = time(NULL);
  tm = localtime(&thetimet2);
  sprintf(prefs.sdate_end,"%04d-%02d-%02d",
	tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
  sprintf(prefs.stime_end,"%02d:%02d:%02d",
	tm->tm_hour, tm->tm_min, tm->tm_sec);
673
  prefs.time_diff = counter_seconds() - dtime;
Emmanuel Bertin's avatar
Emmanuel Bertin committed
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706

/* Write XML */
  if (prefs.xml_flag)
    write_xml(prefs.xml_name);

  endcat((char *)NULL);

  if (prefs.xml_flag || prefs.cat_type==ASCII_VO)
    end_xml();

  return;
  }


/******************************** initglob ***********************************/
/*
Initialize a few global variables
*/
void	initglob()
  {
   int	i;

  for (i=0; i<37; i++)
    {
    ctg[i] = cos(i*PI/18);
    stg[i] = sin(i*PI/18);
    }


  return;
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
707
708
709
710
711
712
713
714
/****** selectext ************************************************************
PROTO	int selectext(char *filename)
PURPOSE	Return the user-selected extension number [%d] from the file name.
INPUT	Filename character string.
OUTPUT	Extension number, or RETURN_ERROR if nos extension specified.
NOTES	The bracket and its extension number are removed from the filename if
	found.
AUTHOR  E. Bertin (IAP)
715
VERSION 23/09/2020
Emmanuel Bertin's avatar
Emmanuel Bertin committed
716
717
718
719
720
721
722
723
724
725
726
727
 ***/
static int	selectext(char *filename)
  {
   char	*bracl,*bracr;
   int	next;

  if (filename && (bracl=strrchr(filename, '[')))
    {
    *bracl = '\0';
    if ((bracr=strrchr(bracl+1, ']')))
      *bracr = '\0';
    next = strtol(bracl+1, NULL, 0);
728
729

    // VERY BAD HACK to check if this is tile-compressed, if so, add +1 to extension number requested
730
731
    if (strstr(filename, ".fits.fz") != NULL)
      next++;
732

Emmanuel Bertin's avatar
Emmanuel Bertin committed
733
734
735
736
737
738
739
    return next;
    }

  return RETURN_ERROR;
  }


Emmanuel Bertin's avatar
Emmanuel Bertin committed
740
741
742
743
744
745
746
747
/****** write_error ********************************************************
PROTO	int	write_error(char *msg1, char *msg2)
PURPOSE	Manage files in case of a catched error
INPUT	a character string,
	another character string
OUTPUT	RETURN_OK if everything went fine, RETURN_ERROR otherwise.
NOTES	-.
AUTHOR	E. Bertin (IAP)
748
VERSION	23/09/2020
Emmanuel Bertin's avatar
Emmanuel Bertin committed
749
 ***/
750
void	write_error(const char *msg1, const char *msg2)
Emmanuel Bertin's avatar
Emmanuel Bertin committed
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
  {
   char			error[MAXCHAR];

  sprintf(error, "%s%s", msg1,msg2);
  if (prefs.xml_flag)
    write_xmlerror(prefs.xml_name, error);

/* Also close existing catalog */
  endcat(error);

  end_xml();

  return;
  }

766