/
smf_fit_profile.c
2091 lines (1774 loc) · 66.7 KB
/
smf_fit_profile.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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
503
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SMF_fit_profile
* Purpose:
* Low-level 1-D profile fitter
* Language:
* Starlink ANSI C
* Type of Module:
* Subroutine
* Invocation:
* smf_fit_profile( smfData *data, int axis, int *range, int ncomp,
* smfArray *pardata, void *pfcntrl, int *status );
* Arguments:
* data = smfData* (Given and Returned)
* Pointer to input data struct
* axis = int (Given)
* Axis to fit along
* range = int * (Given & Returned)
* Range of pixels to use in fit (default all: 1..ndim)
* ncomp = int (Given)
* Number of functions to fit along each profile
* pardata = smfArray* (Given and returned)
* Array with data structs to parameter ndfs
* pfcntrl = fitStruct* (Given)
* Pointer to struct with fit control parameters
* status = int* (Given and Returned)
* Pointer to global status.
* Description:
* This routine performs a 1-D fit to the data along one axis
* of a NDF cube. It replaces the values in the data array with
* the fitted profile.
*
* Currently Gaussian, Gaussian-hermite 1 (skewed gaussian),
* Gaussian-Hermite 2 (skewed and peaky gaussian), and Voigt
* (Gaussian+Lorentzian) are supported (see smf_math_functions).
*
* A smfData struct is expected for each component as pardata
* indices 1..ncomp. The values and errors of the fitted functions
* are stored in the data structs of each parameter ndfs along the same
* axis as is being fitted, pixels 1..NPAR. The definition of the
* pixels depends on the function that is being fitted:
* pixel 1 - amplitude, a
* 2 - centre, b
* 3 - FWHM, c
* 4 - h3 (skewness) or lorentzian width
* 5 - h4 (peakyness)
* The first ndf data struct in pardata (index 0) is used for diagnostics
* and an optional fit of a common baseline.
* pixel 1 - number of gaussians fitted
* 2 - number of iterations for fit (>=0) or error (<0): see
* smf_lsqfit).
* 3 - <not used>
* 4 - parameter z0 of 2nd order baseline z0 + z1*x + z2*x*x
* 5 - parameter z1 of 2nd order baseline z0 + z1*x + z2*x*x
* 6 - parameter z2 of 2nd order baseline z0 + z1*x + z2*x*x
* If external initial guesses are used, the smfData structs at pardata
* 1..ncomp need to have been populated with those values upon entry,
* as well as any user-defined fixed values that are not to be fitted.
*
* Notes:
* Getting the initial estimates right, especially for the dispersions,
* is essential for a successful fit. This is more difficult than
* the fit itself. The routine has 'wrappers' around the low level
* routines smf_gauest and smf_lsqfit for the initial estimates and
* fitting. Major portions of the code are derived (by permission)
* from the xgaufit routine of the GIPSY software package of the
* Kapteyn Institute, Groningen, The Netherlands.
*
* Authors:
* Remo Tilanus (JAC, Hawaii)
* TIMJ: Tim Jenness (JAC, Hawaii)
* Kor Begeman, Hans Terlouw, Martin Vogelaar (Kapteyn Institute, Groningen)
* {enter_new_authors_here}
* History:
* 2010-09-27 (RPT):
* Starlink version
* 2012-04-10 (TIMJ):
* Use const and stop using unnecessary pointers.
* {enter_further_changes_here}
* Copyright:
* Copyright (C) 2010,2012 Science and Technology Facilities Council.
* Copyright (C) Kapteyn Laboratorium Groningen 2001
* All Rights Reserved.
* Licence:
* This program 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.
*
* This program 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 this program; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307, USA
* Bugs:
* {note_any_bugs_here}
*-
*/
/* Standard includes */
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <math.h>
/* Starlink includes */
#include "sae_par.h"
#include "mers.h"
#include "msg_par.h"
#include "prm_par.h"
#include "star/kaplibs.h"
#include "star/util.h"
#include "star/thr.h"
/* SMURF includes */
#include "smf.h"
#include "smurf_par.h"
#include "smurf_typ.h"
/* FIT1D includes */
#include "libsmf/smf_fit1d.h"
/* Simple default string for errRep */
#define FUNC_NAME "smf_fit_profile"
/*
** Switch this on for additional debug with information on individual
** fits. I.e. run like this on single or very few spectra to investigate
** an issue.
*/
#define MAXDEBUGINFO 0
/*
** Direct printout debug info on details fitting program for development
** only. Use on single spectra!
*/
#define PRINTFOUT 0
/*
** Switch off MULTITHREADING. This may help troubleshoot issues.
*/
#define MULTITHREADED 1
/* Structure containing information about blocks of profiles that each
thread will process */
typedef struct {
int ijob; /* Job identifier */
int threads; /* Number of jobs/threads */
smfData *data; /* Pointer to SMF data struct */
size_t istart; /* Start index into data for thread */
size_t dstride; /* Data stride: 1 unless single thread */
size_t nprofiles; /* Number of profiles to process */
size_t firstid; /* Id number for first profile */
size_t npts; /* Number of data points in profile */
int range[2]; /* Range of pixels to use for fit */
int ncomp; /* Number of functions in each profile */
fitStruct *fcntrl; /* Pointer fit control struct */
smfArray *pardata; /* Array with parameter ndf data structs */
} fitProfileData;
typedef struct /* 'qsort' struct for comparisons */
{
double par[MAXPAR];
double err[MAXPAR];
double refpix;
}
qsortstruct;
static void FitProfileThread( void *job_data_ptr, int *status );
static void generalize_gauss_fit( void *pfcntrl, int *status );
static int getestimates( const double fdata[], const float weight[], int ndat,
double *parlist, int npar, int ncomp, void *pfcntrl,
const int smoothingpar[], int numq );
static int dolsqfit( smf_math_function fid, const double pcoord[],
const double fdata[], float *weight, int npts,
double *parlist, double *errlist, const int fixmask[],
int npar, int *ncomp, void *pfcntrl, int *fitopt );
static void adjustestimates( smf_math_function fid, int nfound,
double *parlist, int npar );
static int fillfromparndf( void *pfcntrl, const smfArray *pardata, int pbase,
int dstride, int nfound,
double *parlist, double *errlist, int npar );
static double amp2area( double aD, double aL );
static void mysort( int sortopt, double refpix, double *parlist,
double *errlist, int npar, int ncomp );
int comp0( const void *s1, const void *s2 );
int comp11( const void *s1, const void *s2 );
int comp2( const void *s1, const void *s2 );
int comp21( const void *s1, const void *s2 );
static double getresidual( const double fdata[], int ndat,
int gaussiansfound, double *Destimates,
double zerolev );
void smf_fit_profile( smfData *data, smfArray *pardata, void *pfcntrl,
int *status )
/* Top-level subroutine to fite profiles in a data cube along the specified
** axis. The routine will slice up the data into chucks to be process
** by each thread.
*/
{
/* Local variables */
size_t i, k; /* Loop counters */
size_t iaxis; /* Index nr axis to fit */
size_t ndata = 1; /* Length data array */
smfData *cdata; /* Pointer to data struct in par ndf */
size_t pdata = 1; /* Length parameter ndf data array */
size_t dstride = 1; /* Data stride */
size_t nprofiles = 0; /* Number of profiles */
size_t npts; /* Number of data points */
size_t didRotate = 0; /* Rotated to fast axis or not */
fitStruct *fcntrl=NULL; /* Pointer to fit control struct */
/* Threads related processing */
ThrWorkForce *wf = NULL; /* Pointer to a pool of worker threads */
size_t nw = 1; /* Number of threads */
size_t njobs = 0; /* Number of jobs to be processed */
size_t njobprofs; /* Number of profiles for each job */
fitProfileData *job_data=NULL; /* Pointer to job data array*/
fitProfileData *jdata=NULL; /* Pointer to job data */
size_t step; /* step size for dividing up work */
size_t perm[NDF__MXDIM]; /* Axes permutation array */
dim_t pdims[NDF__MXDIM]; /* Dimensions permutated data */
dim_t cdims[NDF__MXDIM]; /* Dimensions permutated param data */
/* Check status */
if (*status != SAI__OK) return;
fcntrl = (fitStruct *) pfcntrl;
/* Copy some variables to local ones */
int axis = fcntrl->axis;
int ncomp = fcntrl->ncomp;
/*
** Let's start: Find the number of cores/processors available and
** create a pool of threads of the same size.
*/
#if (MULTITHREADED)
nw = thrGetNThread( SMF__THREADS, status );
#endif
wf = thrGetWorkforce( nw, status );
if ( *status != SAI__OK ) {
errRep( FUNC_NAME,
"Failed to create workforce of threads", status );
}
msgOutif(MSG__DEBUG, " ", "SMF_FIT_PROFILE:", status);
/*
** Determine axis to fit and nr of points in profile
*/
/* Which axis */
iaxis = axis-1;
npts = (data->dims)[ (int) (iaxis) ];
int range[2] = { 1, npts };
if ( fcntrl->lolimit[1] != 0 && fcntrl->lolimit[1] != VAL__BADI ) {
range[0] = NINT(fcntrl->lolimit[1]);
}
if ( fcntrl->hilimit[1] != 0 && fcntrl->hilimit[1] != VAL__BADI ) {
range[1] = NINT(fcntrl->hilimit[1]);
}
/* Sanity check: make sure the axis has any extent */
if ( (abs(range[1]-range[0])+1) < 2 ) {
*status = SAI__ERROR;
errRep( FUNC_NAME,
"Number of points to fit along 1 or less", status );
}
/* Tell user what we're fitting */
msgOutf(" ", "Fitting data using %d %s(s) over pixel range [%d,%d]",
status, ncomp, smf_mathfunc_str(fcntrl->fid, status),
range[0],range[1]);
/*
** Determine cube layout: if the fit axis is not the fastest axis
** dstride calculates how many elements its adjacent pixels are
** apart. The code in FitProfileThread can fit along any axis.
**
** For multi-threading, the fit axis needs to be the first (fastest)
** axis. I.e. with multiple threads, reorder the cube if necessary
** otherwise just fit along the requested axis. Dstride will be 1
** since points in a profile will be adjacent.
*/
/* Pointer to first parameter NDF data struct */
cdata = pardata->sdata[0];
for( i = 0; i < data->ndims; i++ ) {
ndata *= data->dims[i];
pdata *= cdata->dims[i];
if ( i < iaxis ) {
dstride *= data->dims[i];
}
}
/* Rotate cube if necessary. Set up axis permutation array */
if ( nw > 1 && iaxis > 0 ) {
perm[0] = axis;
pdims[0] = data->dims[iaxis];
cdims[0] = cdata->dims[iaxis];
k = 1;
for( i = 0; i < data->ndims; i++ ) {
if ( i != iaxis ) {
perm[k] = i+1;
pdims[k] = data->dims[i];
cdims[k] = cdata->dims[i];
k++;
}
}
/* Loop over elements of data->ptr and re-form arrays */
msgOutif( MSG__DEBUG," ", "Reorder input data and var cube", status );
for( i = 0; i < 2; i++ ) {
data->pntr[i] = smf_dataOrder_ndims( data->pntr[i], data->dtype,
ndata, data->ndims, data->dims,
perm, 1, 1, status );
}
/* Loop over parameter ndfs as well to rotate them similarly */
msgOutiff(MSG__DEBUG," ", "Reorder parameter and error cubes 1..%d",
status, (int) ncomp+1);
for( int icomp = 0; (int) icomp < ncomp+1; icomp++ ) {
cdata = pardata->sdata[icomp];
for( int j = 0; j < 2; j++ ) {
cdata->pntr[j] = smf_dataOrder_ndims( cdata->pntr[j], cdata->dtype,
pdata, cdata->ndims, cdata->dims,
perm, 1, 0, status );
}
}
/* The profile now is fastest dimension, i.e. the stride becomes 1 */
dstride = 1;
didRotate = 1;
}
/* Return if error at this point */
if (*status != SAI__OK) return;
/*
** Change gaussian and gausshermite1 fits to gausshermite2 fits
** with h3 and/or h4 fixed to 0. This means that components can
** be of mixed type within the gausshermite family since the
** actual fit is always a gh2, possibly with fixed values.
*/
if ( fcntrl->fid == SMF__MATH_GAUSS ||
fcntrl->fid == SMF__MATH_GAUSSHERMITE1 ) {
generalize_gauss_fit( pfcntrl, status );
}
/*
** Each of the thread carried out. Set up the job struct for each
** with pointers to the part of data to be handled.
*/
/* Total number of profiles to fit */
nprofiles = (ndata/npts+0.5);
msgOutiff(MSG__VERB," ", "Total number of %d profiles to fit",
status, (int) nprofiles);
/* Number of profiles for each thread: the last thread will do
whatever is left */
step = 1;
if( nprofiles > nw ) {
step = ((int) (nprofiles/nw+0.5));
}
if( step < 1 ) step = 1;
/* Allocate array of parameter structs for each thread */
job_data = astCalloc( nw, sizeof(*job_data) );
/* Set up each parameter struct */
for ( i = 0; (*status==SAI__OK) && i < nw; i++ ) {
jdata = job_data + i;
if ( i*step >= nprofiles ) {
/* Already done all profiles available */
break;
} else if ( (i+1)*step >= nprofiles ) {
/* Ensure that a thread does not exceed the number of profiles */
njobprofs = nprofiles - i*step;
} else if ( (i == (nw-1) ) && ((i+1)*step < nprofiles) ) {
/* Ensure that the last thread picks up any left-over profiles */
njobprofs = nprofiles - i*step;
} else {
/* Can process default batch */
njobprofs = step;
}
/* increase the jobs counter */
njobs++;
jdata->ijob = njobs;
jdata->threads = (int) nw;
jdata->data = data;
jdata->istart = i*step*npts;
jdata->dstride = dstride;
jdata->nprofiles = njobprofs;
jdata->firstid = (i*step)+1;
jdata->npts = npts;
jdata->range[0] = range[0];
jdata->range[1] = range[1];
jdata->ncomp = ncomp;
jdata->fcntrl = fcntrl;
jdata->pardata = pardata;
msgOutiff(MSG__DEBUG," ",
"...thread %d will handle %d profiles (from index %d)", status,
(int) jdata->ijob, (int) jdata->nprofiles, (int) jdata->istart );
}
/* Hand each job to a thread */
msgOutf(" ", "...Will use %d threads to fit %d profiles.",
status, (int) njobs, (int) nprofiles );
thrBeginJobContext( wf, status );
for( i = 0; (*status == SAI__OK) && (i < njobs); i++ ) {
jdata = job_data + i;
(void) thrAddJob( wf, 0, jdata, FitProfileThread, 0, NULL, status );
}
/* Wait until all of the submitted jobs have completed */
thrWait( wf, status );
thrEndJobContext( wf, status );
astFree( job_data );
/*
** If the data cubes were rotated, rotate them and the parameter cubes
** back again.
*/
/* Permutate array back */
msgOut(" ", "...Writing parameter cubes and finishing up.", status );
if ( *status == SAI__OK && didRotate ) {
for( i = 0; i < iaxis; i++ ) {
perm[i] = i+2;
}
perm[iaxis] = 1;
/* Loop over elements of data->ptr and re-form arrays */
msgOutif( MSG__DEBUG," ", "Reorder input data and var cube back", status );
for( i = 0; i < 2; i++ ) {
data->pntr[i] = smf_dataOrder_ndims( data->pntr[i], data->dtype,
ndata, data->ndims, pdims,
perm, 1, 1, status );
}
/* Loop over parameter ndfs as well to rotate them back as well */
msgOutiff(MSG__DEBUG," ", "Reorder parameter and error cubes 1..%d back",
status, (int) ncomp+1);
for( int icomp = 0; (int) icomp < ncomp+1; icomp++ ) {
cdata = pardata->sdata[icomp];
for( int j = 0; j < 2; j++ ) {
cdata->pntr[j] = smf_dataOrder_ndims( cdata->pntr[j], cdata->dtype,
pdata, cdata->ndims, cdims,
perm, 1, 0, status );
}
}
}
/*
** Finish up: Write history entry
*/
if ( *status == SAI__OK ) {
smf_history_add( data, FUNC_NAME, status);
} else {
errRep(FUNC_NAME, "Error: status set bad. Possible programming error.",
status);
return;
}
}
static void FitProfileThread ( void *job_data_ptr, int *status ) {
/*
** This routine marches through the data stream, collecting the points
** of each profile in an array, fits the profile, and replaces the data
** with the fitted profile. It can fit along any axis:
** job_data_prt->dstride gives the number of elements that seperate
** adjacent spectral points. Logically this splits the hypercube into
** nprofiles/dstride subcubes each with dstride profiles. Thus we can
** cycle through the profiles by cycling over the subcubes and each
** profile in the subcube.
**
** If the fit axis is the fastest dimension, dstride=1. In that case
** the number of subcubes will be equal to the number of profiles
** and only 1 spectrum will be handled per subcube, which will make
** the routine suitable for multithreading: simply set the number
** of profiles and the data pointer appropriate for the job (and
** have dstride=1 of course since the data must have been reordered
** with the fit axis being the first).
**
** The routine will exit with an error if job_data_prt->ijob > 1 and
** dstride != 1. I.e. it assumes that a multi-threaded operation is
** intended if ijob is being actively used.
*/
fitProfileData *jdata=NULL; /* Pointer to job data */
size_t i, j, k, l; /* Loop counters */
int ijob; /* Job identifier */
int threads; /* Number of threads (jobs) */
size_t profid; /* ID number Profile */
size_t iprof = 0; /* Profile counter */
smfData *data; /* SMF data struct to be fitted */
void *indata; /* Pointer to sdata array */
int istart = 0; /* Index number into data for thread */
int range[2]; /* Pixel range to fit over */
smf_math_function fid; /* Integer id for function */
int ncomp = 1; /* Number of functions in each profile */
smfArray *pardata = NULL; /* Array with parameter data pointers */
double *fitval, *fiterr; /* Pointers into parameter data */
size_t base = 0; /* Starting point for index into arrays */
size_t pbase = 0; /* Same for parameter data arrays */
size_t index; /* Current index into array */
size_t dstride; /* Data stride: 1 unless single thread */
size_t nsubcubes = 1; /* Number of strides subcubes */
size_t nprofiles = 0; /* Number of profiles */
size_t npts; /* Number of data points */
fitStruct *fcntrl=NULL; /* Pointer to fit control struct */
/* Moments and initial estimates parameters */
double value; /* Local variable for data value */
size_t zeronum = 0; /* Number of points in zerolevel rim */
double zerolev = 0.0; /* Zero level */
/* Initial estimates */
int smoothingpar[6] = { 1, 2, 3, 5, 10, 20 };
int numq = sizeof((int *)smoothingpar)/sizeof(smoothingpar[0]);
double maxval = VAL__BADD;
int posmax = -1;
/* LSQFIT etc. parameters: see also smf_lsqfit */
int fitopt[10]; /* Options for 'smf_math_... */
double *fdata = NULL; /* Data array to be fitted */
double *pcoord = NULL; /* Coordinate array e.g. pixel value */
float *weight = NULL; /* Weights */
double coord; /* Coordinate */
int npar = 3; /* Number of parameters in the fit */
double parlist[MAXPAR]; /* Fitted parameters */
double errlist[MAXPAR]; /* Errors fit */
int iters = 0; /* Return status smf_lsqfit */
int estimate_only = 0;
int model_only = 0;
if ( *status != SAI__OK ) return;
/* Retrieve job data */
jdata = job_data_ptr;
ijob = jdata->ijob;
threads = jdata->threads;
data = jdata->data;
istart = jdata->istart;
dstride = jdata->dstride;
nprofiles = jdata->nprofiles;
profid = jdata->firstid-1; /* Routine below increments upfront */
npts = jdata->npts;
if (jdata->range[0] < jdata->range[1] ) { /* Order range low to high */
range[0] = jdata->range[0];
range[1] = jdata->range[1];
} else {
range[0] = jdata->range[1];
range[1] = jdata->range[0];
}
ncomp = jdata->ncomp;
fcntrl = jdata->fcntrl;
pardata = jdata->pardata;
fid = fcntrl->fid;
estimate_only = fcntrl->estimate_only;
model_only = fcntrl->model_only;
indata = data->pntr[0];
/* If no fit required pipe the model through the fit routine
with fitopts = -1 so that it skips the fit, but still filters
the results */
if ( estimate_only == YES || model_only == YES ) fitopt[0] = -1;
/* Get nr parameters associated with function */
npar = smf_math_fnpar ( fid );
msgOutiff(MSG__DEBUG, " ",
"(FitProfileThread %d) ...Function %s (fid %d) npar = %d",
status, ijob, smf_mathfunc_str(fid,status), (int) fid, (int) npar );
/* Check the job nr and dstride */
if ( (ijob > 1) && (dstride != 1 ) ) {
msgOutiff(MSG__DEBUG, " ",
"ERROR (FitProfileThread %d) stride=%d instead of 1 for multi-threading",
status, ijob, (int) dstride );
*status = SAI__ERROR;
return;
}
/* Allocate some workspace */
fdata = astMalloc( sizeof(*fdata) * npts );
pcoord = astMalloc( sizeof(*pcoord) * npts );
weight = astMalloc( sizeof(*weight) * npts );
#if (MAXDEBUGINFO)
msgOutiff(MSG__DEBUG, " ",
"(FitProfileThread %d) ...istart=%d, dstart=%d, nprof=%d, npts=%d",
status,
ijob, (int) istart, (int) dstride, (int) nprofiles, (int) npts );
#endif
/* Loop over subcubes */
istart /= npts;
nsubcubes = (int) (nprofiles/dstride+0.5);
for ( l = 0; l < nsubcubes; l++ ) {
/*
** Loop over profiles in subcube: since the spectral points are
** dstride apart, there are dstride profiles in the subcube:
** yes, think this one over: there are dstride adjacent points
** that start a profile before point 2 of the first one.
*/
/* Loop over profiles */
for ( k = 0; k < dstride; k++) {
iprof++;
profid++;
/* Reset/initialize fit error condition */
iters = 0;
/* Offset into current data and parameter array */
base = (istart + l*dstride) * npts + k;
pbase = (istart + l*dstride) * NPAR + k;
/* Inform user about progress every 1000 profiles: by default
for the first and last thread only, unless debug output is
requested */
if ( profid % 1000 == 0) {
if ( ijob == 1 || ijob == threads )
msgOutf(" ",
"(FitProfileThread %3d) ...at profile %6d - %6d of %6d (i=%8d)",
status, ijob, (int) profid, (int) iprof,
(int) nprofiles, (int) base );
else
msgOutiff(MSG__DEBUG, " ",
"(FitProfileThread %d) ...At profile %6d - %6d of %6d (i=%8d)",
status, ijob, (int) profid, (int) iprof,
(int) nprofiles, (int) base );
}
#if (MAXDEBUGINFO)
msgOutiff(MSG__DEBUG, " ", "(FitProfileThread %d):\n", status, ijob);
#endif
/* First loop over points: clip, zerolevel etc. */
maxval = VAL__BADD;
posmax = 0;
zerolev = 0.0;
zeronum = 0;
size_t nbad = 0;
for ( i = 0; i < npts && model_only != YES; i++ ) {
/*----------------------------------------------------------------*/
/* Put all data in arrays with positions, values and weights */
/* suitable for the LSQFIT function. */
/*----------------------------------------------------------------*/
fdata[i] = VAL__BADD;
weight[i] = 1.0;
pcoord[i] = (double) (i+1); /* pixel dimensions 1..n */
/* Accumulate profile points in fdata */
index = base+i*dstride;
if ( data->dtype == SMF__DOUBLE ) {
if ( ((double *)indata)[index] != VAL__BADD ) {
fdata[i] = ((double *)indata)[index];
}
} else if ( data->dtype == SMF__FLOAT ) {
if ( ((float *)indata)[index] != VAL__BADR ) {
fdata[i] = (double) ((float *)indata)[index];
}
} else if ( data->dtype == SMF__INTEGER ) {
if ( ((int *)indata)[index] != VAL__BADI ) {
fdata[i] = (double) ((int *)indata)[index];
}
} else if ( data->dtype == SMF__USHORT ) {
if ( ((unsigned short *)indata)[index] != VAL__BADUW ) {
fdata[i] = (double) ((unsigned short *)indata)[index];
}
} else if ( data->dtype == SMF__UBYTE ) {
if ( ((unsigned char *)indata)[index] != VAL__BADUB )
fdata[i] = (double) ((unsigned char *)indata)[index];
} else {
msgSeti("IJOB", (int) ijob);
msgSeti("PROFID", (int) profid);
msgSetc("DTYPE",smf_dtype_str(data->dtype, status));
*status = SAI__ERROR;
errRep( FUNC_NAME,
"(FitProfileThread ^IJOB prof PROFID): Don't know how to handle ^DTYPE type.",
status);
}
if ( *status != SAI__OK ) goto CLEANUP;
value = fdata[i];
if (value != VAL__BADD) {
/* Clip data as required */
if ( fcntrl->clip[0] != VAL__BADD &&
fcntrl->clip[1] != VAL__BADD &&
( value > fcntrl->clip[1] || value < fcntrl->clip[0] ) ) {
/* value must be between cliplo and cliphi (included) */
value = VAL__BADD;
} else if ( fcntrl->clip[0] != VAL__BADD &&
value < fcntrl->clip[0] ) {
/* value must be greater(equal) than cliplo */
value = VAL__BADD;
} else if (fcntrl->clip[1] != VAL__BADD &&
value > fcntrl->clip[1] ) {
/* value must be smaller(equal) than cliphi */
value = VAL__BADD;
/* else: no clip */
}
if ( value != VAL__BADD ) {
/* find maximum */
if ( maxval == VAL__BADD || value > maxval ) {
maxval = value;
posmax = pcoord[i];
};
/* Use outer 15% for initial estimate zero level */
if ( (i < 0.15*npts ) || (i > 0.85*npts) ) {
zerolev += value;
zeronum++;
}
} else {
weight[i] = 0.0;
}
} else {
nbad++;
weight[i] = 0.0;
}
/* Now that we got the zerolevel disable points outside range */
if ( i < (size_t) (range[0]-1) || i > (size_t) (range[1]-1) ) {
weight[i] = 0.0;
}
} /* End loop over profile points */
#if (FITZEROLEVEL)
if (zeronum > 0) {
zerolev /= zeronum; /* Mean of all border pixels */
} else {
#if (MAXDEBUGINFO)
msgOutiff(MSG__DEBUG," ",
"(FitProfileThread %d) Profile %d edge of fit box filled with blanks\n0.0 substituded for zero level",
status, ijob, (int) profid);
#endif
zerolev = 0.0;
}
#else
/* Do not fit and fix zerolevel at 0 */
zerolev = 0.0;
#endif
/*
** Setup for the fit.
*/
int nfound = 0; /* Number of components found */
int nestim = 0; /* Number of initial estimates */
/* Initialize parameters */
for ( i = 0; (int) i < MAXPAR; i++ ) {
parlist[i] = 0.0;
errlist[i] = 0.0;
}
/* If no fit errors and enough points */
if ( iters >= 0 && (npts-nbad) > NPAR ) {
/*
** This is a bit tricky: the estimate can deliver a larger
** number of components than the fit later finds. On occasion
** that causes problems. For best results make sure that the
** estimate and fit are asked an equal number of components.
** Hence if the fit delivers less components than estimated
** retry with less and less demanded components until the
** estimate and fit are balanced
*/
int mcomp = ncomp+1; /* add 1: loop below decrements at start */
while ( nfound < mcomp && mcomp > 1 ) {
mcomp -= 1;
#if (MAXDEBUGINFO)
msgOutiff(MSG__DEBUG, " ",
"(FitProfileThread %d) ...profile %d trying to find %d components",
status, ijob, (int) profid, mcomp);
#endif
/* Can skip the initial estimate altogether of model_only. */
if ( model_only != YES ) {
/* For the fit store the zerolevel at the end of the parlist */
parlist[MAXPAR-3] = zerolev;
/*----------------------------------------*/
/* Get initial Estimates */
/*----------------------------------------*/
nestim = getestimates( fdata, weight, npts, parlist, npar,
mcomp, fcntrl, smoothingpar, numq );
#if (MAXDEBUGINFO)
msgOutiff(MSG__DEBUG, " ",
"(FitProfileThread %d) ...profile %d getestimates found %d comps",
status, ijob, (int) profid, nestim);
#endif
/* No estimates? Try a fit anyway */
if (nestim == 0) {
parlist[0] = maxval;
parlist[1] = posmax;
if ( fcntrl->lolimit[2] != VAL__BADD ) {
parlist[2] = 1.5*fcntrl->lolimit[2];
} else {
parlist[2] = 1.2;
}
nfound = 1;
} else {
nfound = nestim;
}
/* Adjust gaussian estimates for actual function being fitted */
adjustestimates( fid, nfound, parlist, npar );
/* Replace estimates with values from any external parameter
ndf or with user supplied values */
nfound = fillfromparndf( fcntrl, pardata, pbase, dstride,
nfound, parlist, errlist, npar );
#define PREFITGAUSSIAN 0
#if (PREFITGAUSSIAN)
/* Prefit gaussian to non-gaussian fits. Does not appear to
lead to overall better results */
if ( fid != SMF__MATH_GAUSS ) {
/* Do an initial fit with a gaussian */
double parlist2[MAXPAR];
double errlist2[MAXPAR];
int fixmask2[MAXPAR];
int npar2 = smf_math_fnpar ( SMF__MATH_GAUSS );
int nfound2 = nfound;
for ( i = 0; (int) i < nfound-1; i++ ) {
int offset = i*npar;
int offset2 = i*npar2;
parlist2[offset2] = parlist[offset];
parlist2[offset2+1] = parlist[offset+1];
parlist2[offset2+2] = parlist[offset+2];
fixmask2[offset2] = fcntrl->fixmask[offset];
fixmask2[offset2+1] = fcntrl->fixmask[offset+1];
fixmask2[offset2+2] = fcntrl->fixmask[offset+2];
}
#if (MAXDEBUGINFO)
msgOutiff(MSG__DEBUG, " ",
"(FitProfileThread %d) ...profile %d gaussian prefit %d comps",
status, ijob, (int) profid, nfound);
#endif
iters = dolsqfit( SMF__MATH_GAUSS, pcoord, fdata, weight, npts,
parlist2, errlist2, fixmask2, npar2,
&nfound2, fcntrl, fitopt );
if ( iters >= 0 && nfound2 > 0 ) {
for ( i = 0; (int) i < nfound2-1; i++ ) {
int offset = i*npar;
int offset2 = i*npar2;
nfound = nfound2;
parlist[offset] = parlist2[offset2];
parlist[offset+1] = parlist2[offset2+1];
parlist[offset+2] = parlist2[offset2+2];
}
}
}
#endif
} else {
/* Fill parameters from model with values from external parameter
ndf and user supplied values */
nfound = ncomp;
nfound = fillfromparndf( fcntrl, pardata, pbase, dstride,
nfound, parlist, errlist, npar );
}
/*----------------------------------------*/
/* Do the actual fit */
/*----------------------------------------*/
#if (MAXDEBUGINFO)
msgOutiff(MSG__DEBUG, " ",
"(FitProfileThread %d) ...profile %d fitting %d comps",
status, ijob, (int) profid, nfound);
#endif
int *fixmask = fcntrl->fixmask;
iters = dolsqfit( fid, pcoord, fdata, weight, npts, parlist, errlist,
fixmask, npar, &nfound, fcntrl, fitopt );
if ( iters < 0 ) {
nfound = 0;
}
if ( model_only == YES ) mcomp = 0; /* Terminate loop */
}
}
#if (MAXDEBUGINFO)
msgOutiff(MSG__DEBUG, " ",
"(FitProfileThread %d) ...profile %d dolsqfit fitted %d (ier = %d)",
status, ijob, (int) profid, nfound, iters);
for ( j = 0; (int) j < nfound; j++ ) {
int offset = j*npar;
for ( i = 0; (int) i < npar; i++ ) {
if ( i == 0 )
msgOutiff(MSG__DEBUG," ", "%1d..par[%d] = %.6f",
status, (int) j+1, (int) i, (float) parlist[offset+i] );
else
msgOutiff(MSG__DEBUG," ", "...par[%d] = %.6f",
status, (int) i, (float) parlist[offset+i] );
}
}
#endif
/* Store fitted profile parameters */
/* Diagnostics and baselines in COMP_0 */
fitval = (pardata->sdata[0]->pntr)[0];
fiterr = (pardata->sdata[0]->pntr)[1];
for ( i = 0; i < NPAR; i++ ) {
index = pbase + i*dstride;
fitval[index] = VAL__BADD;
fiterr[index] = VAL__BADD;
if (i == 0) {
fitval[index] = (double) nfound;
} else if (i == 1) {
fitval[index] = (double) iters;
} else if ( i >= NPAR-3 ) {
if (iters >= 0) {
fitval[index] = parlist[npar*nfound+i-3];
fiterr[index] = errlist[npar*nfound+i-3];
}
}
}