-
Notifications
You must be signed in to change notification settings - Fork 2
/
cleanir.py
executable file
·1084 lines (862 loc) · 43.3 KB
/
cleanir.py
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
#!/usr/bin/env python3
"""
TBD
----
- ToDo:
- Update help
- Simpler to pass the four quadrants as a list, e.g. [q0,q1,q2,q3] ?
- Do we really need to save the variables qxsize and qysize ?
- Add more regression tests
- Whenever there is intermittent noise, it seems to always be in coherent bands across the detector.
- This indicates that the pattern is actually across the *entire* detector, but with some offset or
- scaling between the quadrants. If we could use all 4 quadrants (at the same time) for pattern
- determination that may give better results, especially for GNIRS spectroscopy where only the
- unilluminated edges are available.
- -> either median combine the quadrants or the pattern, or filter the whole detector at once.
- support FITS files that have been compressed with bzip2
Changelog
-----------
- 20220105: update to add arg option for output path
- 20220113: rearranged parser, and added 'cleanFits' as a hook for python calls
"""
import argparse
from astropy.io import fits
from astropy import stats
import datetime
from functools import partial
import glob
import logging
from matplotlib import pyplot
import multiprocessing
import numpy
from numpy import ma
import os
from scipy import optimize
from scipy.stats import norm
__version__ = '2022-Jan-12'
__author__ = 'astephens,cfigura'
# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------q------------
def main(args):
if args.debug:
logger = ConfigureLogging('DEBUG')
else:
logger = ConfigureLogging()
inputlist = glob.glob(args.fits)
if len(inputlist) < 1:
logger.error('No files found')
logger.debug('inputlist = %s', inputlist)
filelist = expand(inputlist)
for f in filelist:
cleanir = CleanIR(args)
cleanir.clean(f)
return
# --------------------------------------------------------------------------------------------------
class CleanIR():
def __init__(self, args):
self.clip = args.clip
self.debug = args.debug
self.force = args.force
self.graph = args.graph
self.manual_q0_offset = args.TL
self.manual_q1_offset = args.TR
self.manual_q2_offset = args.BL
self.manual_q3_offset = args.BR
self.pshift = args.pshift
self.pxsize = 16
self.pysize = 4
self.quadlevel = args.quadlevel
self.roi = args.roi
self.roimirror = True # mirror ROIs in the bottom quads to the top quads (and vice-versa?)
self.rowfilter = args.rowfilter
self.rowmedian = args.rowmedian
self.clip_sigma = args.sigma
self.save = args.save
self.src = args.src
self.sub = args.sub
self.use_dq = not args.nodq
self.usermask = args.mask # user-supplied pixel mask
self.outputpath = args.outputpath
# ----------------------------------------------------------------------------------------------
def clean(self, fitsfile):
self.fitsfile = fitsfile
self.read()
self.mask_rois()
self.mask_dq()
self.subtract()
self.mask_sources()
self.calculate_pattern()
self.subtract_pattern()
if self.rowfilter:
self.row_filter()
if self.rowmedian:
self.row_median_filter()
self.level_quadrants()
self.write_output()
return
# ----------------------------------------------------------------------------------------------
def read(self):
logger = logging.getLogger('read')
logger.info('Reading %s', self.fitsfile)
self.hdulist = fits.open(self.fitsfile)
numext = len(self.hdulist)
logger.debug('Numext: %d', numext)
self.sciext = None
for i in range(len(self.hdulist)):
try:
extname = self.hdulist[i].header['EXTNAME']
except:
extname = None
logger.debug('Extension %d name: %s', i, extname)
if extname == 'SCI':
self.sciext = i
if self.sciext is None:
if numext == 1:
self.sciext = 0
else:
self.sciext = 1
logger.debug('Science extension: %s', self.sciext)
self.data = self.hdulist[self.sciext].data
self.instrument = self.hdulist[0].header['INSTRUME']
logger.debug('Instrument: %s', self.instrument)
self.naxis1 = self.hdulist[self.sciext].header['naxis1'] # X
self.naxis2 = self.hdulist[self.sciext].header['naxis2'] # Y
logger.debug('Image size: %s x %s', self.naxis1, self.naxis2)
if self.instrument == 'NIRI':
self.config = self.hdulist[0].header['FPMASK']
elif self.instrument == 'GNIRS':
self.config = self.hdulist[0].header['CAMERA'] + self.hdulist[0].header['DECKER']
logger.debug('Padding GNIRS SCI y-axis by 2 rows') # ydim must be a multiple of 4
self.data = numpy.append(self.data, numpy.zeros((2, self.naxis1)), axis=0)
self.naxis2 += 2
logger.debug('New image size: %s x %s', self.naxis1, self.naxis2)
else:
logger.error('Unsupported instrument: %s', self.instrument)
raise SystemExit
# Check that the image is the proper size:
if self.naxis1 % self.pxsize or self.naxis2 % self.pysize:
logger.info('Padded image size: %d x %d', self.naxis1, self.naxis2)
logger.error('Image size is not a multiple of %d x %d', self.pxsize, self.pysize)
raise SystemExit
logger.info('Config: %s', self.config)
self.qxsize = int(self.naxis1 / 2) # quadrant x size
self.qysize = int(self.naxis2 / 2) # quadrant y size
self.mdata = ma.array(self.data, copy=True) # masked science data
if self.instrument == 'GNIRS': # mask the padding
self.mdata[-2:,] = ma.masked
return
# ----------------------------------------------------------------------------------------------
def mask_rois(self):
"""
Mask all pixels that are NOT in the user-supplied ROIs.
These masked pixels will not be used in the pattern determination or be pattern subtracted.
Expect ROI strings will have the format y1:y2
If roimirror == True then apply ROIs to the opposite (top/bottom) half of the detector.
"""
logger = logging.getLogger('mask_rois')
if self.roi:
logger.info('Masking around ROIs: %s', self.roi)
self.roimask = ma.ones((self.naxis2, self.naxis1))
self.roimask.mask = True
for roi in self.roi:
r = roi.split(':')
if len(r) != 2:
logger.error('ROI must have 2 values: y1:y2: %s', roi)
raise SystemExit
y1 = int(r[0]) - 1 # convert to zero-index
y2 = int(r[1]) # zero index +1 because slicing does not include upper limit
logger.debug('...%d-%d', y1,y2)
# Unmask the ROI: mask[y1:y2,x1:x2] = False
self.roimask.mask[y1:y2, ] = False
if self.roimirror:
y3 = 1024-y2
y4 = 1024-y1
logger.debug('...%d-%d', y3,y4)
self.roimask.mask[y3:y4, ] = False
# Apply the ROI mask to the science data:
self.mdata *= self.roimask
return
# ----------------------------------------------------------------------------------------------
def mask_dq(self):
"""Mask pixels flagged in the DQ extension."""
logger = logging.getLogger('mask_dq')
if self.use_dq:
try:
dq = self.hdulist['DQ'].data
except:
dq = None
logger.debug('No DQ extension found')
else:
dq = None
if dq is not None:
numpix = len(dq[dq>0])
if numpix > 0:
logger.info('Masking %d pixels flagged in DQ extension', numpix)
if self.instrument == 'GNIRS':
logger.debug('Padding GNIRS DQ y-axis by 2 rows')
dq = numpy.append(dq, numpy.ones((2, self.naxis1)), axis=0)
self.dqmask = ma.masked_where(dq > 0, numpy.ones((self.naxis2, self.naxis1)))
self.mdata *= self.dqmask
else:
self.dqmask = 1.0
else:
self.dqmask = 1.0
if self.usermask is not None: # user-supplied pixel mask
logger.info('Masking pixels from %s', self.usermask)
with fits.open(self.usermask) as hdulist:
numext = len(hdulist)
logger.debug('...numext: %d', numext)
if numext != 1:
raise SystemExit('User supplied mask has multiple extensions. Not sure which is the mask.')
data_ext = 0
usermask = ma.masked_where(hdulist[data_ext].data > 0, numpy.ones((self.naxis2, self.naxis1)))
self.mdata *= usermask
return
# ----------------------------------------------------------------------------------------------
def subtract(self):
logger = logging.getLogger('subtract')
if self.sub:
logger.info('Subtracting %s', self.sub)
hdulist = fits.open(self.sub)
numext = len(hdulist)
logger.debug('...numext: %d', numext)
if numext == 1:
data_ext = 0
else:
data_ext = 1
self.sub = hdulist[data_ext].data
if self.instrument == 'GNIRS':
logger.debug('Padding frame to subtract')
self.sub = numpy.append(self.sub, numpy.zeros((2,self.naxis1)), axis=0)
self.mdata -= self.sub
else:
self.sub = 0.0
return
# ----------------------------------------------------------------------------------------------
def mask_sources(self):
"""
Mask sources in the image by:
1. Predefined NIRI and GNIRS spectroscopic ROIs
2. User-supplied ROIs with the format x1:x2,y1:y2
3. Iterative sigma clipping
Masked regions will be ignored during pattern determination but still cleaned
"""
logger = logging.getLogger('mask_sources')
self.srcmask = ma.ones((self.naxis2, self.naxis1))
if self.src is None: # The default, which is interpreted as "use the default mask"
if self.instrument == 'NIRI' and self.config in \
('f6-2pixBl_G5214', 'f6-4pixBl_G5215', 'f6-6pixBl_G5216', 'f6-2pix_G5211'):
logger.info('Using Y<=270 and Y>=728 for pattern determination')
self.src = ['1:1024,271:727']
elif self.instrument == 'GNIRS' and self.sub is not None and \
'Short' in self.config and not 'XD' in self.config:
logger.info('Using X<=160 and X>=864 for pattern determination')
self.src = ['161:863,1:1024']
else:
self.src = None
if self.instrument == 'NIRI' and self.config in \
('f6-4pix_G5212', 'f6-6pix_G5213', 'f32-6pix_G5229', 'f32-9pix_G5230'):
logger.warning('Sky lines may be altered by pattern removal')
logger.debug('Source mask: %s', self.src)
if self.src is not None:
if self.src[0] != 'None': # "None" is interpreted as do NOT use the default mask
logger.info('Masking source ROI(s)...')
for roi in self.src: # 'X1:X2,Y1:Y2'
r = roi.split(',')
x = r[0].split(':')
y = r[1].split(':')
x1 = int(x[0]) - 1 # convert to zero-index
x2 = int(x[1])
y1 = int(y[0]) - 1 # convert to zero-index
y2 = int(y[1])
logger.debug('%s -> %s %s %s %s', roi, x1, x2, y1, y2)
self.srcmask[y1:y2,x1:x2] = ma.masked
if self.clip:
logger.info('Sigma-clipping to remove sources...')
q0,q1,q2,q3 = disassemble(self.data - self.sub)
pool = multiprocessing.Pool(processes=4)
mapfunc = partial(stats.sigma_clip,sigma_lower=3,sigma_upper=self.clip_sigma,maxiters=None)
p0,p1,p2,p3 = pool.map(mapfunc, [q0,q1,q2,q3])
pool.close()
pool.join()
nosrc = assemble(p0,p1,p2,p3) # the image with all sources masked
sigmask = ma.ones((self.naxis2, self.naxis1))
sigmask.mask = nosrc.mask
self.srcmask *= sigmask
self.mdata *= self.srcmask
return
# -----------------------------------------------------------------------------------------------
def calculate_pattern(self):
"""
Calculate the pattern for all four quadrants.
"""
logger = logging.getLogger('calculate_pattern')
logger.info('Calculating patterns...')
# Create arrays of indices which correspond to the pattern tiled over the image
indx = numpy.tile(numpy.arange(0, self.qxsize, self.pxsize), int(self.qysize/self.pysize))
indy = numpy.arange(0, self.qysize, self.pysize).repeat(self.qxsize/self.pxsize)
logger.debug('...indx: %s', indx)
logger.debug('...indy: %s', indy)
if self.graph is None:
graph = False
else:
graph = True if 'pattern' in self.graph else False
mapfunc = partial(cpq, pxsize=self.pxsize, pysize=self.pysize, qxsize=self.qxsize,
qysize=self.qysize, indx=indx, indy=indy, graph=graph, pshift=self.pshift)
q0,q1,q2,q3 = disassemble(self.mdata)
pool = multiprocessing.Pool(processes=4)
(k0,p0),(k1,p1),(k2,p2),(k3,p3) = pool.map(mapfunc, [q0,q1,q2,q3])
pool.close()
pool.join()
self.kernel = assemble(k0,k1,k2,k3)
self.pattern = assemble(p0,p1,p2,p3)
if self.roi: # Zero regions not in the user-supplied ROIs
self.pattern *= self.roimask.filled(fill_value=0)
return
# ----------------------------------------------------------------------------------------------
def subtract_pattern(self):
"""
Check and subtract the pattern from the original science image.
"""
logger = logging.getLogger('subtract_pattern')
logger.info('Checking pattern subtraction...')
if self.force:
logger.info('Forcing pattern subtraction on all quadrants')
else:
#d0,d1,d2,d3 = disassemble(self.data) # raw data
d0,d1,d2,d3 = disassemble(self.mdata - self.sub) # masked subtracted data
p0,p1,p2,p3 = disassemble(self.pattern)
data = [(d0,p0), (d1,p1), (d2,p2), (d3,p3)] # pool.map only supports one input list
pool = multiprocessing.Pool(processes=4)
q0,q1,q2,q3 = pool.map(checksub, data)
pool.close()
pool.join()
self.pattern = assemble(q0,q1,q2,q3)
self.cleaned = self.data - self.pattern
return
# ----------------------------------------------------------------------------------------------
def level_quadrants(self):
"""
When full-frame (i.e. no user-supplied ROIs) compare each quadrant with the others.
If there are user-supplied ROIs the region *outside* the ROIs is good and defines the
reference bias level, so shift the bad regions to that level.
"""
logger = logging.getLogger('level_quadrants')
if self.quadlevel:
logger.info('Leveling quadrants...')
logger.debug('Fitting pixel distribution of each quadrant...')
# Use the masked data to avoid bad pixels and objects.
# Pattern subtract to minimize the dispersion.
if self.graph is None:
graph = False
else:
graph = True if 'offsets' in self.graph else False
q0,q1,q2,q3 = disassemble(self.mdata - self.pattern)
data = [ma.compressed(q0), ma.compressed(q1), ma.compressed(q2), ma.compressed(q3)]
pool = multiprocessing.Pool(processes=4)
mapfunc = partial(fitpixdist, graph=graph)
g0,g1,g2,g3 = pool.map(mapfunc, data)
pool.close()
pool.join()
logger.debug('Peaks: %5.1f %5.1f %5.1f %5.1f', g0, g1, g2, g3)
if self.roi:
# Create a "not-ROI" mask which is the inverse of the ROI mask:
notroi = ma.masked_array(self.roimask.data, ~self.roimask.mask)
# The "good" background level is defined by the entire array excluding
# pixels in the ROI, the DQ extension, and pixels with sources (stars, etc):
# good = self.data * goodmask * self.dqmask * self.srcmask - self.sub
# good = self.data * notroi - self.sub
good = stats.sigma_clip(self.data * notroi - self.sub,
sigma_lower=3, sigma_upper=3.0, maxiters=1)
middle = fitpixdist(ma.compressed(good), graph=self.graph)
logger.debug('Good level: %.2f', middle)
else: # full-frame
# Should this be the *original* median of the entire image,
# or the median after fixing the pattern noise?
# Using the median after fixing pattern noise will give different
# results for the different pattern shifting methods (min, mean, max).
middle = numpy.median([g0,g1,g2,g3])
logger.debug('Median of all quadrants: %.1f', middle)
logger.debug('Calculating offsets...')
o0 = middle - g0
o1 = middle - g1
o2 = middle - g2
o3 = middle - g3
logger.info('Quadrant offsets: %.1f %.1f %.1f %.1f', o0, o1, o2, o3)
else:
o0 = o1 = o2 = o3 = 0.0
offsets = offset(numpy.zeros(self.naxis2*self.naxis1).reshape(self.naxis2,self.naxis1),
o0 + self.manual_q0_offset, o1 + self.manual_q1_offset,
o2 + self.manual_q2_offset, o3 + self.manual_q3_offset)
if self.roi: # only apply offsets to the user-supplied ROI:
offsets *= self.roimask.filled(fill_value=0)
logger.debug('Applying offsets...')
self.cleaned += offsets
self.pattern -= offsets # the pattern is meant to be subtracted, so apply negative offsets
self.kernel = offset(self.kernel,
-o0 - self.manual_q0_offset, -o1 - self.manual_q1_offset,
-o2 - self.manual_q2_offset, -o3 - self.manual_q3_offset)
return
# ----------------------------------------------------------------------------------------------
def row_filter(self):
"""
Generate an independent 8x1 pixel pattern for each row in each quadrant.
"""
logger = logging.getLogger('row_filter')
logger.info('Row filtering...')
# quadrant AND/OR row filtering?
# I'll have to find some examples to test, but IMHO we should try to remove as much of the
# pattern noise on the full quadrant before trying to row filter, as the row filtering
# will be affected by sky lines. Alternatively we do quad filtering OR row filtering.
q0,q1,q2,q3 = disassemble(self.mdata - self.pattern)
pool = multiprocessing.Pool(processes=4)
p0,p1,p2,p3 = pool.map(rf, [q0,q1,q2,q3])
pool.close()
pool.join()
self.rowpattern = assemble(p0,p1,p2,p3)
self.cleaned -= self.rowpattern
return
# ----------------------------------------------------------------------------------------------
def row_median_filter(self):
"""
Subtract the median of each row in each quadrant.
"""
logger = logging.getLogger('row_median')
logger.info('Median filtering each row...')
q0,q1,q2,q3 = disassemble(self.mdata - self.pattern)
pool = multiprocessing.Pool(processes=4)
p0,p1,p2,p3 = pool.map(rowmed, [q0,q1,q2,q3])
pool.close()
pool.join()
self.rowmedianimage = assemble(p0,p1,p2,p3)
self.cleaned -= self.rowmedianimage
return
# ----------------------------------------------------------------------------------------------
def write_output(self):
if not os.path.exists(self.outputpath):
os.makedirs(self.outputpath)
logger = logging.getLogger('write_output')
path, filename = os.path.split(self.fitsfile)
cleanfile = 'c' + filename[:filename.rfind('.fits')]
logger.debug('cleanfile: %s', cleanfile)
if self.save is not None:
for s in self.save:
f = cleanfile + '_' + s + '.fits'
logger.info('Writing %s', f)
delete ([f])
if s == 'kernel':
data = self.kernel
elif s == 'masked':
data = self.mdata.filled(fill_value=0)
elif s == 'pattern':
data = self.pattern
elif s == 'rowpattern':
data = self.rowpattern
elif s == 'rowmedian':
data = self.rowmedianimage
fits.PrimaryHDU(data).writeto(f)
if self.instrument == 'GNIRS':
logger.debug('Removing padding')
self.cleaned = numpy.delete(self.cleaned, [self.naxis2-1,self.naxis2-2], axis=0)
cleanfile += '.fits'
cleanfile = os.path.join(self.outputpath,cleanfile)
logger.info('Writing %s', cleanfile)
delete ([cleanfile])
self.hdulist[self.sciext].data = self.cleaned
self.hdulist[0].header['CLEANIR'] = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
self.hdulist[0].header.comments['CLEANIR'] = 'UT time stamp for cleanir.py'
self.hdulist.writeto(cleanfile, output_verify='warn')
self.hdulist.close()
return
# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
def disassemble(image):
logger = logging.getLogger('disassemble')
"""
Split an image into quadrants:
+-------+
| 0 | 1 |
+---+---+
| 2 | 3 |
+---+---+
"""
xsize = int(image.shape[1])
ysize = int(image.shape[0])
q0 = image[int(ysize/2):ysize, 0:int(xsize/2)]
q1 = image[int(ysize/2):ysize, int(xsize/2):xsize]
q2 = image[ 0:int(ysize/2), 0:int(xsize/2)]
q3 = image[ 0:int(ysize/2), int(xsize/2):xsize]
return q0, q1, q2, q3
# ----------------------------------------------------------------------------------------------
def assemble(q0, q1, q2, q3):
"""
Assemble quadrants into an image.
"""
logger = logging.getLogger('assemble')
xsize = 2 * q0.shape[1]
ysize = 2 * q0.shape[0]
if ma.is_masked(q0):
image = ma.zeros(ysize*xsize).reshape(ysize,xsize)
else:
image = numpy.zeros(ysize*xsize).reshape(ysize,xsize)
image[int(ysize/2):ysize, 0:int(xsize/2)] = q0
image[int(ysize/2):ysize, int(xsize/2):xsize] = q1
image[ 0:int(ysize/2), 0:int(xsize/2)] = q2
image[ 0:int(ysize/2), int(xsize/2):xsize] = q3
return image
# ----------------------------------------------------------------------------------------------
def offset(image, o0, o1, o2, o3):
"""
Apply offsets to quadrants of an image.
"""
logger = logging.getLogger('offset')
logger.debug('Offsetting quadrant levels...')
xsize = image.shape[1]
ysize = image.shape[0]
image[int(ysize/2):ysize, 0:int(xsize/2)] += o0
image[int(ysize/2):ysize, int(xsize/2):xsize] += o1
image[ 0:int(ysize/2), 0:int(xsize/2)] += o2
image[ 0:int(ysize/2), int(xsize/2):xsize] += o3
return image
# --------------------------------------------------------------------------------------------------
def checksub(data_and_pattern):
"""
Calculate the 3-sigma clipped standard deviation of a quadrant before and after pattern
subtraction and decide if there is improvement
"""
logger = logging.getLogger('checksub')
# The data and pattern arrays have been combined for pool.map; split them out here:
data = data_and_pattern[0]
pattern = data_and_pattern[1]
ostd = numpy.std(stats.sigma_clip(data, sigma_lower=3.0, sigma_upper=3.0, maxiters=None))
cstd = numpy.std(stats.sigma_clip(data-pattern, sigma_lower=3.0, sigma_upper=3.0, maxiters=None))
if ostd - cstd > 0.01:
logger.info('stddev %6.2f -> %6.2f Improvement!', ostd, cstd)
else:
logger.info('stddev %6.2f -> %6.2f', ostd, cstd)
pattern *= 0 # reset to zeros
return pattern
# --------------------------------------------------------------------------------------------------
def cpq(quad, pxsize=None, pysize=None, qxsize=None, qysize=None, indx=None, indy=None,
graph=False, pshift='mean'):
"""
Calculate the pattern for the supplied quadrant.
"""
logger = logging.getLogger('cpq')
# Create blank pattern array:
p = numpy.zeros(pysize*pxsize).reshape(pysize,pxsize)
median = ma.median(quad)
stddev = ma.std(quad)
logger.debug('...median: %.3f +/- %.3f', median, stddev)
if graph:
binwidth = 1
binmin = median - 5. * stddev
binmax = median + 5. * stddev
bins = numpy.arange( binmin, binmax, binwidth )
bincenters = bins[1:bins.size] - binwidth/2.
iplot = 0
for iy in range(0, pysize):
for ix in range(0, pxsize):
data = quad[indy+iy, indx+ix]
p[iy,ix] = ma.median(data)
if graph:
iplot += 1
plot = pyplot.subplot(pysize, pxsize, iplot)
hist,bins = numpy.histogram(data, bins=bins)
pyplot.plot(bincenters, hist, linestyle='-', marker='', markersize=1)
pyplot.axvline(x=p[iy,ix], ls='--', color='red')
if ix != 0:
plot.set_yticklabels([])
if graph:
logger.debug('...graphing results...')
pyplot.subplots_adjust(left=0.05,bottom=0.05,right=0.95,top=0.95,wspace=0.,hspace=0.2)
pyplot.show()
# Decide how to shift the pattern:
# For situations where the S/N is very low it is usually best to shift the pattern so that
# it's mean is zero, and then subtracting the pattern has no net effect. However, other
# times this will consistently over-subtract the pattern, leaving dark quadrants.
# In these situations it works better to shift the pattern so that it has a maximum of zero.
# What is the best way to characterize the amplitude of the pattern?
logger.debug('Pattern Amplitude: %.2f', numpy.amax(p) - numpy.amin(p))
logger.debug('Pattern Sigma: %.2f', numpy.std(p))
if pshift == 'mean':
logger.debug('Shifting the pattern to have a mean of zero')
p -= numpy.mean(p)
elif pshift == 'min':
logger.debug('Shifting the pattern to have a minimum of zero')
p -= numpy.amin(p)
elif pshift == 'max':
logger.debug('Shifting the pattern to have a maximum of zero')
p -= numpy.amax(p)
else:
raise SystemExit('Invalid pshift')
quadpattern = numpy.tile(p, (int(qysize/pysize), int(qxsize/pxsize))) # Tile pattern over quadrant
return p, quadpattern
# --------------------------------------------------------------------------------------------------
def rf(quad): # Row filter a quadrant
logger = logging.getLogger('rf')
#display(quad, title='Input')
xsize = quad.shape[1]
ysize = quad.shape[0]
indx = numpy.arange(0, xsize, 8)
pattern = ma.zeros((ysize,xsize))
for iy in range(0, ysize):
p = ma.zeros(8)
for ix in range(0, 8):
p[ix] = ma.median(quad[iy,indx+ix])
pattern[iy] = numpy.tile(p, int(xsize/8))
#display(pattern, title='Pattern Pre-Normalization')
mean = ma.mean(pattern)
logger.debug('Row pattern mean: %s', mean)
pattern -= mean # set the pattern mean to zero
return pattern.filled(fill_value=0) # set masked values to zero
# --------------------------------------------------------------------------------------------------
def rowmed(quad):
median = ma.median(quad, axis=1) # calculate median along the x-axis
ysize, xsize = quad.shape
medimg = numpy.tile(median, xsize).reshape(xsize, ysize).transpose()
medimg -= numpy.mean(medimg) # set the mean to zero
return medimg.filled(fill_value=0) # set masked values to zero
# --------------------------------------------------------------------------------------------------
def display(image, title=None, cmap='viridis'): # cmap='gray'
logger = logging.getLogger('display')
fig = pyplot.figure(figsize=(8,8))
pyplot.imshow(image, cmap=cmap, origin='lower')
if title is not None:
pyplot.title(title)
pyplot.show()
return
# --------------------------------------------------------------------------------------------------
def expand(listoflists):
"""Expand a list of file lists and return a list of files"""
logger = logging.getLogger('expand')
filelist = []
for l in listoflists:
if l.endswith('.fits'):
filelist.append(l)
else:
logger.debug('Trying to expand %s', l)
try:
with open(l) as f:
for line in f:
filelist.append(line.strip())
except:
logger.error('Can\'t read %s', l)
raise SystemExit
filelist.sort()
logger.debug('filelist = %s', filelist)
return filelist
# --------------------------------------------------------------------------------------------------
def fitpixdist(array, graph=False):
"""
Fit the pixel distribution of the passed array and return the center and width.
Input:
array = numpy masked array
Output:
center
NOTE: This works with v.1.14.5 but silently fails with numpy versions 1.15.0 and 1.15.1.
"""
logger = logging.getLogger('fitpixdist')
#logger.debug('array = %s', array)
mu, sigma = norm.fit(array)
logger.debug('mu = %.2f sigma = %.2f', mu, sigma)
mincts = numpy.amin(array)
maxcts = numpy.amax(array)
logger.debug('mincts = %.2f maxcts = %.2f', mincts, maxcts)
#bins = numpy.linspace(mincts, maxcts, 100)
#logger.debug('bins = %s', bins)
hist,bins = numpy.histogram(array, bins=int(maxcts-mincts))
#logger.debug('Bins: %s', bins)
bincenters = bins[1:bins.size] - (bins[1] - bins[0])/2.
#logger.debug('Bin Centers: %s', bincenters)
mode = bins[ hist.argmax() ]
logger.debug('Mode = %.2f', mode)
peak = hist.max()
logger.debug('Peak = %.2f', peak)
#fitsigma = 1.0 # how much to fit around the peak (+/- this sigma)
#mincts = mode - fitsigma * inputstddev
#maxcts = mode + fitsigma * inputstddev
#t = bincenters[ (bincenters>mincts) & (bincenters<maxcts) ]
#data = hist[ (bincenters>mincts) & (bincenters<maxcts) ]
#p0 = [mode, sigma, peak]
#logger.debug('Initial parameter guesses: %.3f %.3f %.3f', p0[0], p0[1], p0[2])
p0 = [mode, sigma, peak, 0.01, 0.00]
logger.debug('Initial parameters: %.3f %.3f %.3f %.3f %.3f', p0[0], p0[1], p0[2], p0[3], p0[4])
xdata = bincenters
ydata = hist
#p, pcov = curve_fit(gaussian, xdata, ydata, p0=p0)
p, pcov = optimize.curve_fit(gaussian_plus_slope, xdata, ydata, p0=p0)
#print 'p =', p
#logger.debug('Best fit parameters: %.3f %.3f %.3f', p[0], p[1], p[2])
logger.debug('Best fit parameters: %.3f %.3f %.3f %.3f %.3f', p[0], p[1], p[2], p[3], p[4])
xfit = xdata
#yfit = gaussian(xfit, p[0], p[1], p[2])
yfit = gaussian_plus_slope(xfit, p[0], p[1], p[2], p[3], p[4])
if graph:
pyplot.figure()
pyplot.plot(xfit, yfit, linestyle='-', marker='', color='green')
pyplot.plot(xdata, ydata, linestyle='', marker='.', markersize=3, color='red')
pyplot.show()
return p[0]
# --------------------------------------------------------------------------------------------------
def gaussian(t,p0,p1,p2): # p[0] = mu p[1] = sigma p[2] = peak
return(p2 * numpy.exp( -(t - p0)**2 / (2 * p1**2) ))
# --------------------------------------------------------------------------------------------------
def gaussian_plus_slope(t,p0,p1,p2,p3,p4): # p0=mu, p1=sigma, p2=peak, p3=slope, p4=offset
return p2 * numpy.exp(-(t - p0)**2 / (2 * p1**2)) + p3 * t + p4
# --------------------------------------------------------------------------------------------------
def delete(filelist):
for f in filelist:
if os.path.isfile(f):
os.remove(f)
return
# --------------------------------------------------------------------------------------------------
def ConfigureLogging(level='INFO'):
"""Set up a console logger"""
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # set minimum threshold level for logger
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
consoleloghandler = logging.StreamHandler()
if level.upper() == 'DEBUG':
consoleloghandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(name)-20s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
elif level.upper() == 'INFO':
consoleloghandler.setLevel(logging.INFO)
elif level.upper() == 'WARNING':
consoleloghandler.setLevel(logging.WARNING)
elif level.upper() == 'ERROR':
consoleloghandler.setLevel(logging.ERROR)
elif level.upper() == 'CRITICAL':
consoleloghandler.setLevel(logging.CRITICAL)
else:
print ('ERROR: Unknown log error level')
consoleloghandler.setLevel(logging.INFO)
consoleloghandler.setFormatter(formatter)
## check for other handlers, otherwise we'll get multiple log entries
if (logger.hasHandlers()):
logger.handlers.clear()
logger.addHandler(consoleloghandler)
return logger
# --------------------------------------------------------------------------------------------------
def cleanFits(fits,**kwargs):
## cleanFits serves as the python hook for the cleanir command.
## run the parser on the fits name, and then loop through kwargs.
## NB: this does not check to ensure that kwargs are correct!
parser = create_parser()
args = parser.parse_args([fits])
for key,value in kwargs.items():
exec(f'args.{key}=value')
main(args)
# --------------------------------------------------------------------------------------------------
def create_parser():
parser = argparse.ArgumentParser(
description='This script assumes that the NIRI/GNIRS pattern noise can be represented by a\
16x4 pixel additive pattern which is repeated over the entire quadrant. The pattern is\
determined for each quadrant by taking the mode of the pixel value distribution at each\
position in the pattern. Once the pattern has been determined for a\
quadrant it is replicated to cover the entire quadrant and subtracted, and the mean of the\
pattern is added back to preserve flux. The standard deviation of all the pixels in the\
quadrant is compared to that before the pattern subtraction, and if no reduction was\
achieved the subtraction is undone (the pattern subtraction may be forced with --force).\
This process is repeated for all four quadrants and the cleaned frame is written to\
c<infile>. The pattern derived for each quadrant may be saved with --save pattern.\
\n\
If the pattern only affect part of an image, which may appear as one or more bands of\
noise across the image, these regions may be specified with --roi.\
\n\
Pattern noise is often accompanied by an offset in the bias values between the four\
quadrants. One may want to use --quadlevel to try to remove this offset. This attempts to\
match the iteratively determined median value of each quadrant. This method works best with\
sky subtraction (i.e. with --sub), and does not work well if there are large extended\
objects in the frame. Note that the derived quadrant offsets will be applied to the output\
pattern file.\
\n\
Row noise (description here) will not be removed by the regular algorithm that works on the entirety of each\
quadrant at a time.\
\n\
Removing the pattern from spectroscopy is more difficult because of many vertical sky\
lines. By default NIRI f/6 spectroscopy with the 2-pixel or blue slits (which do not fill\
the detector) use the empty regions at the bottom (1-272) and top (720-1024) of the array\
for measuring the pattern. This is not possible for other modes of spectroscopy where the\
spectrum fills the detector. For these modes it is best to do sky subtraction before pattern\
removal. The quickest method is to pass a sky frame (or an offset frame) via the -s flag.\
The manual method is to generate and subtract the sky, determine and save the pattern via\
the -p flag, then subtract the pattern from the original image. One may use the -a flag to\
force using all of the pixels for the pattern determination. If the SKYIMAGE FITS header\
keyword is present it is assumed that the sky has already been subtracted and all pixels\
will be used for the pattern determination.\
\n\
Note that you may use glob expansion in infile, however, the entire string must then be\
quoted or any pattern matching characters (*,?) must be escaped with a backslash.',
epilog='Version: ' + __version__)
# Add comment about the pshift parameter.
# Use "min" if the stripes are positive, and "max" if the stripes are negative,
# and use "mean" if you don't want to change mean level of the image.
parser.add_argument('fits', help='Fits file(s) or a list of FITS files')
#parser.add_argument('-b', '--bpm', action='store', type=str, default=None,
# help='Specify a bad pixel mask (overrides DQ plane)')
parser.add_argument('--clip', action='store_true', default=False,