aboutsummaryrefslogtreecommitdiff
path: root/noao/twodspec/apextract/apvariance.x
blob: 015eed7432b4bd7bc301958216f5f3264e486f8c (plain) (blame)
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
include	<gset.h>
include	"apertures.h"


# AP_VARIANCE -- Variance weighted extraction based on profile and CCD noise.
# If desired reject deviant pixels.  In addition to the variance weighted
# spectrum, the unweighted and uncleaned "raw" spectrum is extracted and
# a sigma spectrum is returned.  Wavelengths with saturated pixels are
# flagged with 0 value and negative sigma if cleaning.

procedure ap_variance (im, ap, dbuf, nc, nl, c1, l1, sbuf, svar, profile,
	nx, ny, xs, ys, spec, raw, specsig, nsubaps, asi)

pointer	im			# IMIO pointer
pointer	ap			# Aperture structure
pointer	dbuf			# Data buffer
int	nc, nl			# Size of data buffer
int	c1, l1			# Origin of data buffer
pointer	sbuf			# Sky values (NULL if none)
pointer	svar			# Sky variance
real	profile[ny,nx]		# Profile (returned)
int	nx, ny			# Size of profile array
int	xs[ny], ys		# Origin of profile array
real	spec[ny,nsubaps]	# Spectrum
real	raw[ny,nsubaps]		# Raw spectrum
real	specsig[ny,nsubaps]	# Sky variance in, spectrum sigma out
int	nsubaps			# Number of subapertures
pointer	asi			# Image interpolator for edge pixel weighting

real	rdnoise			# Readout noise in RMS data numbers.
real	gain			# Gain in photons per data number.
real	saturation		# Maximum value for an unsaturated pixel.
bool	clean			# Clean cosmic rays?
real	nclean			# Number of pixels to clean
real	lsigma, usigma		# Rejection sigmas.

bool	sat
int	fd, iterate, niterate, nrej, irej, nreject
int	i, ix, iy, ix1, ix2
real	low, high, step, shift, x1, x2, wt1, wt2, s, w, dat, sk, var, var0
real	sum, wsum, wvsum, sum1, sum2, total1, total2
real	vmin, resid, rrej
pointer	cv, gp
pointer	sp, str, work, wt, xplot, yplot, eplot, fplot, data, sky, data1

real	apgetr(), apgimr(), ap_cveval()
bool	apgetb()
errchk	apgimr, ap_asifit

begin
	# Get task parameters.
	gain = apgimr ("gain", im)
	rdnoise = apgimr ("readnoise", im) ** 2
	saturation = apgetr ("saturation")
	if (!IS_INDEF(saturation))
	    saturation = saturation * gain
	clean = apgetb ("clean")
	lsigma = apgetr ("lsigma")
	usigma = apgetr ("usigma")
	call ap_popen (gp, fd, "clean")

	# Allocate memory and one index.
	call smark (sp)
	call salloc (str, SZ_LINE, TY_CHAR)
	call salloc (work, 6*nx, TY_REAL)
	wt = work - 1
	xplot = wt + nx
	yplot = xplot + nx
	eplot = yplot + nx
	fplot = eplot + nx
	data1 = fplot + nx
	if (sbuf == NULL) {
	    call salloc (sky, nx, TY_REAL)
	    call aclrr (Memr[sky], nx)
	    sky = sky - 1
	    var0 = rdnoise
	}

	# Initialize
	if (rdnoise == 0.)
	    vmin = 1.
	else
	    vmin = rdnoise
	if (clean) {
	    nclean = apgetr ("nclean")
	    if (nclean < 1.)
	        niterate = max (1., nclean * nx)
	    else
		niterate = max (1., min (real (nx), nclean))
	} else
	    niterate = 0

	call aclrr (spec, ny * nsubaps)
	call aclrr (raw, ny * nsubaps)
	call amovkr (-1., specsig, ny * nsubaps)

	i = AP_AXIS(ap)
	low = AP_CEN(ap,i) + AP_LOW(ap,i)
	high = AP_CEN(ap,i) + AP_HIGH(ap,i)
	step = (high - low) / nsubaps
	cv = AP_CV(ap)

	# For each line compute the weighted spectrum and then iterate
	# to reject deviant pixels.  Rejected pixels are flagged by negative
	# variance.

	nreject = 0
	total1 = 0.
	total2 = 0.
	do iy = 1, ny {
	    shift = ap_cveval (cv, real (iy + ys - 1)) - c1 + 1
	    x1 = max (0.5, low + shift) + c1 - xs[iy]
	    x2 = min (nc + 0.49, high + shift) + c1 - xs[iy]
	    if (x1 >= x2)
		next
	    ix1 = nint (x1)
	    ix2 = nint (x2)

	    call ap_asifit (dbuf+(iy+ys-1-l1)*nc, nc, xs[iy]-c1+1,
		low+shift, high+shift, data, asi)
#	    data = dbuf + (iy + ys - 1 - l1) * nc + xs[iy] - c1 - 1
	    if (sbuf != NULL) {
		sky = sbuf + (iy - 1) * nx - 1
		var0 = rdnoise + Memr[svar+iy-1]
	    }

	    # Set pixel weights for summing.
#	    if (asi != NULL)
#		call asifit (asi, Memr[data], nc-xs[iy]+c1)
	    call ap_edge (asi, x1+1, x2+1, wt1, wt2)

	    # First estimate spectrum by summing across the aperture.
	    # Accumulate the raw spectrum and set up various arrays for
	    # plotting and later access.

	    sat = false
	    sum = 0.
	    wsum = 0.
	    wvsum = 0.
	    do ix = ix1, ix2 {
		if (ix1 == ix2)
		    w = wt1
		else if (ix == ix1)
		    w = wt1
		else if (ix == ix2)
		    w = wt2
		else
		    w = 1.
		dat = Memr[data+ix]
		if (!IS_INDEF(saturation))
		    if (dat > saturation)
			sat = true
		sk = Memr[sky+ix]
		raw[iy,1] = raw[iy,1] + w * (dat - sk)

	        Memr[xplot+ix] = ix + xs[iy] - 1
	        Memr[yplot+ix] = dat - sk
		Memr[data1+ix] = dat - sk
		Memr[wt+ix] = w
		var = max (vmin, var0 + max (0., dat))
		w = profile[iy,ix] / var
		var = sqrt (var)
		Memr[eplot+ix] = var
		sum = sum + w * (dat - sk)
		wsum = wsum + w * profile[iy,ix]
		wvsum = wvsum + (w * var) ** 2
	    }
	    if (wsum > 0.) {
	        spec[iy,1] = sum / wsum
	        specsig[iy,1] = sqrt (wvsum) / abs (wsum)
	    } else {
	        spec[iy,1] = 0.
	        specsig[iy,1] = -1.
	    }

	    sum = 0.
	    wsum = 0.
	    wvsum = 0.
	    sum1 = 0.
	    sum2 = 0.
	    do ix = ix1, ix2 {
		sum1 = sum1 + Memr[wt+ix] * Memr[data1+ix]
		if (Memr[eplot+ix] <= 0.)
		    next
		sk = Memr[sky+ix]
	        s = max (0., spec[iy,1]) * profile[iy,ix]
	        var = max (vmin, var0 + (s + sk))
	        w = profile[iy,ix] / var
		var = sqrt (var)
	        Memr[eplot+ix] = var
	        Memr[fplot+ix] = s
	        sum = sum + w * Memr[data1+ix]
	        wsum = wsum + w * profile[iy,ix]
	        wvsum = wvsum + (w * var) ** 2
	    }
	    if (wsum > 0.) {
	        spec[iy,1] = sum / wsum
	        specsig[iy,1] = sqrt (wvsum) / abs (wsum)
		sum2 = sum2 + spec[iy,1]
	    } else {
	         spec[iy,1] = 0.
	         specsig[iy,1] = -1.
		 sum1 = 0.
		 sum2 = 0.
	    }

	    # Reject cosmic rays one at a time.
	    nrej = 0
	    do iterate = 1, niterate {
	        irej = 0
	        rrej = 0.

		# Compute revised variance estimate using profile model 
		# skip rejected pixels, find worst pixel.

	        do ix = ix1, ix2 {
	            if (Memr[eplot+ix] <= 0.)
			next
	            s = max (0., spec[iy,1]) * profile[iy,ix]
		    sk = Memr[sky+ix]
	            var = sqrt (max (vmin, var0 + max (0., s + sk)))
	            Memr[fplot+ix] = s
	            Memr[eplot+ix] = var

		    resid = (Memr[data1+ix] - Memr[fplot+ix]) / var
		    if (abs (resid) > abs (rrej)) {
			rrej = resid
			irej = ix
	            }
	        }

		# Reject worst outlier.

	        if (rrej <= -lsigma || rrej >= usigma) {
	            Memr[eplot+irej] = -Memr[eplot+irej]
		    Memr[data1+irej] = Memr[fplot+irej]
	            nrej = nrej + 1
	        } else
		    break

		# Update spectrum estimate excluding rejected pixels.
	        sum = 0.
	        wsum = 0.
	        wvsum = 0.
		sum1 = 0.
		sum2 = 0.
	        do ix = ix1, ix2 {
		    sum1 = sum1 + Memr[wt+ix] * Memr[data1+ix]
	            if (Memr[eplot+ix] <= 0.)
			next
	            w = profile[iy,ix] / Memr[eplot+ix]**2
	            sum = sum + w * Memr[data1+ix]
	            wsum = wsum + w * profile[iy,ix]
	            wvsum = wvsum + (w * Memr[eplot+ix]) ** 2
	        }

	        if (wsum > 0.) {
	            spec[iy,1] = sum / wsum
	            specsig[iy,1] = sqrt (wvsum) / abs (wsum)
		    sum2 = sum2 + spec[iy,1]
	        } else {
	            spec[iy,1] = 0.
	            specsig[iy,1] = -1.
		    sum1 = 0.
		    sum2 = 0.
	        }
	    }

	    nreject = nreject + nrej
	    total1 = total1 + sum1
	    total2 = total2 + sum2

	    # Calculate subapertures if desired.
	    if (nsubaps > 1) {
		do i = 1, nsubaps {
		    x1 = max (0.5, low + (i - 1) * step + shift) + c1 - xs[iy]
		    x2 = min (nc + 0.49, low + i * step + shift) + c1 - xs[iy]
		    if (x1 >= x2) {
			spec[iy,i] = 0.
			raw[iy,i] = 0.
			specsig[iy,i] = -1.
			next
		    }
		    ix1 = nint (x1)
		    ix2 = nint (x2)
		    call ap_edge (asi, x1+1, x2+1, wt1, wt2)

	            sum = 0.
	            wvsum = 0.
		    raw[iy,i] = 0.
	            do ix = ix1, ix2 {
			if (ix1 == ix2)
			    w = wt1
			else if (ix == ix1)
			    w = wt1
			else if (ix == ix2)
			    w = wt2
			else
			    w = 1.
			raw[iy,i] = raw[iy,i] + w * Memr[yplot+ix]
	                if (Memr[eplot+ix] <= 0.)
			    next
	                w = profile[iy,ix] / Memr[eplot+ix]**2
	                sum = sum + w * Memr[data1+ix]
	                wvsum = wvsum + (w * Memr[eplot+ix]) ** 2
	            }

	            if (wsum > 0.) {
	                spec[iy,i] = sum / wsum
	                specsig[iy,i] = sqrt (wvsum) / abs (wsum)
	            } else {
	                spec[iy,i] = 0.
	                specsig[iy,i] = -1.
	            }
		}
	    }

	    # Flag points with saturated pixels.
	    if (sat)
	        do i = 1, nsubaps
		    specsig[iy,i] = -specsig[iy,i]

	    # Plot profile with cosmic rays if desired.
	    if (gp != NULL && nrej > 0 && spec[iy,1] > 0.) {
		call sprintf (Memc[str], SZ_LINE, "Profile %4d")
		    call pargi (iy)
		s = Memr[yplot+ix1] - abs (Memr[eplot+ix1])
		w = Memr[yplot+ix1] + abs (Memr[eplot+ix1])
		do ix = ix1+1, ix2 {
		    s = min (s, Memr[yplot+ix] - abs (Memr[eplot+ix]))
		    w = max (w, Memr[yplot+ix] + abs (Memr[eplot+ix]))
		}
		sum = w - s
		x1 = ix1 + xs[iy] - 2
		x2 = ix2 + xs[iy]
		s = s - 0.1 * sum
		w = w + 0.1 * sum
		call gclear (gp)
		call gswind (gp, x1, x2, s, w)
		call glabax (gp, Memc[str], "", "")

	        do ix = ix1, ix2 {
	            if (Memr[eplot+ix] > 0.) {
			call gmark (gp, Memr[xplot+ix], Memr[yplot+ix],
			    GM_PLUS, 2., 2.)
			call gmark (gp, Memr[xplot+ix], Memr[yplot+ix],
			    GM_VEBAR, 2., -6.*Memr[eplot+ix])
	            } else {
			call gmark (gp, Memr[xplot+ix], Memr[yplot+ix],
			    GM_CROSS, 2., 2.)
			call gmark (gp, Memr[xplot+ix], Memr[yplot+ix],
			    GM_VEBAR, 1., 6.*Memr[eplot+ix])
	            }
	        }
		call gpline (gp, Memr[xplot+ix1], Memr[fplot+ix1], ix2-ix1+1)
	    }
	}

	# To avoid any bias, scale weighted extraction to same total flux
	# as raw spectrum (with rejected pixels replaced by fit).

	if (total1 * total2 <= 0.) {
	    call sprintf (Memc[str], SZ_LINE,
		"EXTRACT: WARNING - Aperture %d:")
		call pargi (AP_ID(ap))
	    call ap_log (Memc[str], YES, NO, YES)
	    call sprintf (Memc[str], SZ_LINE,
		"   Total variance weighted spectrum flux is %g")
		call pargr (total2)
	    call ap_log (Memc[str], YES, NO, YES)
	    call sprintf (Memc[str], SZ_LINE,
		"   Total unweighted spectrum flux is %g")
		call pargr (total1)
	    call ap_log (Memc[str], YES, NO, YES)
	    call sprintf (Memc[str], SZ_LINE,
		"   Variance spectrum bias factor ignored")
	    call ap_log (Memc[str], YES, NO, YES)
	} else {
	    sum = total1 / total2
	    call amulkr (spec, sum, spec, ny * nsubaps)
	    call amulkr (specsig, sum, specsig, ny * nsubaps)
	    if (sum < .5 || sum > 2) {
		call sprintf (Memc[str], SZ_LINE,
		    "EXTRACT: WARNING - Aperture %d:")
		    call pargi (AP_ID(ap))
		call ap_log (Memc[str], YES, NO, YES)
		call sprintf (Memc[str], SZ_LINE,
		    "   Total variance weighted spectrum flux is %g")
		    call pargr (total2)
		call ap_log (Memc[str], YES, NO, YES)
		call sprintf (Memc[str], SZ_LINE,
		    "   Total unweighted spectrum flux is %g")
		    call pargr (total1)
		call ap_log (Memc[str], YES, NO, YES)
		call sprintf (Memc[str], SZ_LINE,
		    "EXTRACT: Aperture %d variance spectrum bias factor is %g")
		    call pargi (AP_ID(ap))
		    call pargr (total1 / total2)
		call ap_log (Memc[str], YES, NO, YES)
	    } else {
		call sprintf (Memc[str], SZ_LINE,
		    "EXTRACT: Aperture %d variance spectrum bias factor is %g")
		    call pargi (AP_ID(ap))
		    call pargr (total1 / total2)
		call ap_log (Memc[str], YES, NO, NO)
	    }
	}

	# Log the number of rejected pixels.
	if (clean) {
	    call sprintf (Memc[str], SZ_LINE,
		"EXTRACT: %d pixels rejected from aperture %d")
		call pargi (nreject)
		call pargi (AP_ID(ap))
	    call ap_log (Memc[str], YES, NO, NO)
	}

	call ap_pclose (gp, fd)
	call sfree (sp)
end