-
Notifications
You must be signed in to change notification settings - Fork 2
/
bmep.pro
6093 lines (5193 loc) · 221 KB
/
bmep.pro
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
;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
;+ +
;+ BMEP +
;+ +
;+ Written by William R. Freeman +
;+ +
;+ +
;+ Version 1.3: Jan 25 2017 +
;+ +
;+ Info: https://github.com/billfreeman44/bmep +
;+ Freeman, William R., et al. in prep +
;+ +
;+ If you use BMEP in your publication, please cite +
;+ this paper! +
;+ +
;+ Contact: [email protected] +
;+ +
;+ This software was written as part +
;+ of the MOSDEF collaboration: +
;+ http://mosdef.astro.berkeley.edu/Home.html +
;+ +
;+ Much thanks to Alice Shapley for helping me +
;+ iron out many of the issues and greatly +
;+ improving features of this software. +
;+ +
;+ +
;+ +
;+ +
;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
;
;
;
;
;
;
;Copyright (c) 2014 William R. Freeman
;
;Permission is hereby granted, free of charge, to any person obtaining a copy
;of this software and associated documentation files (the "Software"), to deal
;in the Software without restriction, including without limitation the rights
;to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;copies of the Software, and to permit persons to whom the Software is
;furnished to do so, subject to the following conditions:
;
;The above copyright notice and this permission notice shall be included in
;all copies or substantial portions of the Software.
;
;THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;THE SOFTWARE.
;
;
;
;
;
;
;
;
;
;;git commit -a -m ''
;;git push
;
;subroutines listed alphabetically. check bmep or bmep_mosdef subroutines for how to start
;things. check bmep_KeyboardHandler() for how everything works after that.
;
;
;
;
;
;
;
;
;
;extract data multiple times using different widths to find the best SNR
;"slides" the width from 1.5 to 4.0 and outputs the results in a table and also
;saves a .ps file in your savepath folder. Filename is:
;'profile_'+fitsfilenm+'.ps'
pro bmep_auto_width_calculator,j,centerarr,state,order,bkgndl,bkgndr,$
printp,fitgaussp,plotp,slidep,pwindowsize,singlep,cosmic_sigma,$
n_iterate_cosmic,bkgnd_naverage,max_rays_per_col,gwidth,gcenter,$
$;OUTPUTS
F,ferr,Fopt,fopterr,img2d_nobkgnd,parr,sky_reslut_arr,sky_residuals,$
widtharr,leftstatspos,rightstatspos
FORWARD_FUNCTION bmep_blind_hdr, bmep_dir_exist, bmep_fit_sky,bmep_find_p_slide, $
bmep_find_p, bmep_get_slitname, bmep_make_hdr,bmep_sigma_clip, bmep_percent_cut
; print,'\begin{tabular}{| l | l | l | l | l | l |}'
; print,' \hline'
; print,'Width & SNR boxcar & SNR optimal & mean box & mean opt & total flux \\ \hline'
print,'Width & SNR optimal & SNR optimal old & mean opt & mean opt old & total flux & total flux old'
sigmaarr=[]
snroptarr=[]
snrboxarr=[]
avgoptarr=[]
avgboxarr=[]
snroptarr_old=[]
avgoptarr_old=[]
;loop throught widths to see which is best SNR
for test_width=1.5,5.0,0.075 do begin
test_width_arr=replicate(test_width,n_elements(widtharr))
;extract new profile
;note: using test_width_arr rather than widtharr
bmep_extraction_subpixel,j,centerarr,state,order,test_width_arr,bkgndl,bkgndr,$
printp,fitgaussp,plotp,slidep,pwindowsize,singlep,$
cosmic_sigma,n_iterate_cosmic,bkgnd_naverage,max_rays_per_col,$
gwidth,gcenter,$
$;OUTPUTS
F,ferr,Fopt,fopterr,img2d_nobkgnd,sky_reslut_arr,sky_residuals,$
revisevar=state.revisevar,quiet=1
bmep_extraction,j,centerarr,state,order,test_width_arr,bkgndl,bkgndr,$
printp,fitgaussp,plotp,slidep,pwindowsize,singlep,cosmic_sigma,$
n_iterate_cosmic,bkgnd_naverage,max_rays_per_col,gwidth,gcenter,$
$;OUTPUTS
F_old,ferr_old,Fopt_old,fopterr_old,img2d_nobkgnd,parr,sky_reslut_arr,sky_residuals,$
revisevar=state.revisevar,quiet=1
index=where(state.wavel ge leftstatspos and state.wavel le rightstatspos,ct)
momentresult=moment(f[index],sdev=std_dev)
momentresultopt=moment(fopt[index],sdev=std_devopt)
momentresult_old=moment(f_old[index],sdev=std_dev_old)
momentresultopt_old=moment(fopt_old[index],sdev=std_devopt_old)
; ;print info in style of LaTeX
; print,test_width,$ ;width
; ' & ',momentresult[0]/std_dev,$ ; snr box
; ' & ',momentresultopt[0]/std_devopt,$ ; snr optimal
; $;' & ',(momentresultopt[0]/std_devopt)*(momentresult[0]/std_dev),$ ; snr optimal * snr box
; ' & ',momentresult[0],$
; ' & ',momentresultopt[0],$
; ' & ',total(fopt[index]),' \\ \hline' ; mean val
; ;print info in style of NOT LaTeX
; print,test_width,$ ;width
; ' ',momentresult[0]/std_dev,$ ; snr box
; ' ',momentresultopt[0]/std_devopt,$ ; snr optimal
; $;' & ',(momentresultopt[0]/std_devopt)*(momentresult[0]/std_dev),$ ; snr optimal * snr box
; ' ',momentresult[0],$
; ' ',momentresultopt[0],$
; ' ',total(fopt[index]),' ' ; mean val
;print info comparing sub-pixel and not sub-pixel
print,test_width,$ ;width
' ',momentresultopt[0]/std_devopt,$ ; snr optimal
' ',momentresultopt_old[0]/std_devopt_old,$ ; snr optimal _old
' ',momentresultopt[0],$
' ',momentresultopt_old[0],$
' ',total(fopt[index]) ,$
' ',total(fopt_old[index])
if gwidth[j] gt 0 then sigmaarr=[sigmaarr,test_width/gwidth[j]] $
else sigmaarr=[sigmaarr,test_width]
snroptarr=[snroptarr,momentresultopt[0]/avg(fopterr[index])]
snrboxarr=[snrboxarr,momentresult[0]/avg(ferr[index])]
avgoptarr=[avgoptarr,momentresultopt[0]]
avgboxarr=[avgboxarr,momentresult[0]]
snroptarr_old=[snroptarr_old,momentresultopt_old[0]/avg(fopterr_old[index])]
avgoptarr_old=[avgoptarr_old,momentresultopt_old[0]]
endfor ; test_width
;get name of plot.
extrainfo1=state.extrainfo1
extrainfo2=state.extrainfo2
extrainfo3=state.extrainfo3
if j eq 0 then suffix='' else suffix='-'+ssi(j)
;extract original name from fits header.
index=WHERE(extrainfo1 eq 'MSKNM',ct)
if ct eq 0 then message,'ERROR: MASKNAME (MSKNM) IS NOT DEFINED IN EXTRAINFO1'
fitsfilenm=extrainfo2[index]+'.'
index=WHERE(extrainfo1 eq 'FILTNM',ct)
if ct eq 0 then message,'ERROR: FILTERNAME (FILTNM) IS NOT DEFINED IN EXTRAINFO1'
fitsfilenm=fitsfilenm+extrainfo2[index]+'.'
index=WHERE(extrainfo1 eq 'SLITNM',ct)
if ct eq 0 then message,'ERROR: SLITNAME (SLITNM) IS NOT DEFINED IN EXTRAINFO1'
fitsfilenm=fitsfilenm+extrainfo2[index]+suffix
fitsfilenm=fitsfilenm[0]
print,'saving ',state.savepath+'profile_'+fitsfilenm+'.eps'
ps_start,state.savepath+'profile_'+fitsfilenm+'_plot1.eps',xsize=7,ysize=7,/encapsulated
pmsave=!p.multi
!p.multi=[0,1,2]
cgplot,sigmaarr,snroptarr,ytitle='Average Signal to Noise',/ynozero,xtitle='',$
xtickname=replicate(' ',10),ymargin=[0, 2],ytickname=' '
cgplot,sigmaarr,snroptarr_old,/overplot,linestyle=2
norm_ind=where(abs(sigmaarr-2.3548) eq min(abs(abs(sigmaarr-2.3548))))
norm_val=min(avgoptarr[norm_ind])
cgplot,sigmaarr,avgoptarr/norm_val,ytitle='Normalized Flux',/ynozero,xtitle='width (sigma)',ymargin=[4, 0]
cgplot,sigmaarr,avgoptarr_old/norm_val,/overplot,linestyle=2
ps_end
ps_start,state.savepath+'profile_'+fitsfilenm+'_plot2.eps',xsize=7,ysize=7,/encapsulated
cgplot,sigmaarr,snroptarr,ytitle='Average Signal to Noise',/ynozero,$
xtitle='',xtickname=replicate(' ',10),ymargin=[0, 2],xr=[1.5,2.75],ytickname=' '
cgplot,sigmaarr,snroptarr_old,/overplot,linestyle=2
norm_ind=where(abs(sigmaarr-2.3548) eq min(abs(abs(sigmaarr-2.3548))))
norm_val=min(avgoptarr[norm_ind])
cgplot,sigmaarr,avgoptarr/norm_val,ytitle='Normalized Flux',/ynozero,xr=[1.5,2.75],$
xtitle='width (sigma)',ymargin=[4, 0]
cgplot,sigmaarr,avgoptarr_old/norm_val,/overplot,linestyle=2
; cgplot,sigmaarr,snroptarr,psym=-6,$
; title='SNR vs width',xtitle=' total width (sigma)',$
; ytitle='square=optimal, diamond=boxcar',$
; /ynozero,yr=[minmax([snroptarr,snrboxarr])]
; cgplot,sigmaarr,snrboxarr,psym=-4,/overplot
; cgplot,[widtharr[j],widtharr[j]]/gwidth[j],[-1000,10000],/overplot
; cgtext,0.13,1.0,ssi(leftstatspos),/normal
; cgtext,0.13,0.95,ssi(rightstatspos),/normal
;
; cgplot,sigmaarr,avgoptarr,psym=-6,$
; title='average flux vs width',xtitle=' total width (sigma)',$
; ytitle='square=optimal, diamond=boxcar',$
; /ynozero,yr=[minmax([avgoptarr,avgboxarr])]
; cgplot,sigmaarr,avgboxarr,psym=-4,/overplot
; cgplot,[widtharr[j],widtharr[j]]/gwidth[j],[-1000,10000],/overplot
;
;
; if gwidth[j] gt 0 then sigmaarr=sigmaarr*gwidth[j]
;
;
; cgplot,sigmaarr,snroptarr,psym=-6,$
; title='SNR vs width',xtitle=' half width (pixels)',$
; ytitle='square=optimal, diamond=boxcar',$
; /ynozero,yr=[minmax([snroptarr,snrboxarr])]
; cgplot,sigmaarr,snrboxarr,psym=-4,/overplot
; cgplot,[widtharr[j],widtharr[j]],[-1000,10000],/overplot
; cgtext,0.13,1.0,ssi(leftstatspos),/normal
; cgtext,0.13,0.95,ssi(rightstatspos),/normal
;
; cgplot,sigmaarr,avgoptarr,psym=-6,$
; title='average flux vs width',xtitle=' half width (pixels)',$
; ytitle='square=optimal, diamond=boxcar',$
; /ynozero,yr=[minmax([avgoptarr,avgboxarr])]
; cgplot,sigmaarr,avgboxarr,psym=-4,/overplot
; cgplot,[widtharr[j],widtharr[j]],[-1000,10000],/overplot
;
; if gwidth[j] gt 0 then sigmaarr=sigmaarr/gwidth[j]
; cgplot,sigmaarr,snroptarr,psym=-6,$
; title='SNR vs width',xtitle=' total width (sigma)',$
; ytitle='optimal snr',$
; /ynozero
; cgplot,[widtharr[j],widtharr[j]]/gwidth[j],[-1000,10000],/overplot
ps_end
;;;
;;;
;;;Begin center shift test...
;;;
;;;
offset_arr=[]
snroptarr=[]
snrboxarr=[]
avgoptarr=[]
avgboxarr=[]
snroptarr_old=[]
avgoptarr_old=[]
print,'test_offset & SNR optimal & mean opt & total flux'
;loop throught widths to see which is best SNR
for test_offset=0.0,4.0,0.1 do begin
test_center_arr=centerarr+test_offset
test_gcenter_arr=gcenter+test_offset
;extract new profile
;note: using test_width_arr rather than widtharr
bmep_extraction_subpixel,j,test_center_arr,state,order,widtharr,bkgndl,bkgndr,$
printp,fitgaussp,plotp,slidep,pwindowsize,singlep,$
cosmic_sigma,n_iterate_cosmic,bkgnd_naverage,max_rays_per_col,$
gwidth,test_gcenter_arr,$
$;OUTPUTS
F,ferr,Fopt,fopterr,img2d_nobkgnd,sky_reslut_arr,sky_residuals,$
revisevar=state.revisevar,quiet=1
index=where(state.wavel ge leftstatspos and state.wavel le rightstatspos,ct)
momentresult=moment(f[index],sdev=std_dev)
momentresultopt=moment(fopt[index],sdev=std_devopt)
;print info comparing sub-pixel and not sub-pixel
print,test_offset,$ ;width
' ',widtharr[0],$ ; snr optimal
' ',momentresultopt[0]/std_devopt,$ ; snr optimal
' ',momentresultopt[0],$
' ',total(fopt[index])
offset_arr=[offset_arr,test_offset]
snroptarr=[snroptarr,momentresultopt[0]/avg(fopterr[index])]
snrboxarr=[snrboxarr,momentresult[0]/avg(ferr[index])]
avgoptarr=[avgoptarr,momentresultopt[0]]
avgboxarr=[avgboxarr,momentresult[0]]
snroptarr_old=[snroptarr_old,momentresultopt_old[0]/avg(fopterr_old[index])]
avgoptarr_old=[avgoptarr_old,momentresultopt_old[0]]
endfor ; test_offset
!p.multi=[0,1,1]
ps_end
ps_start,state.savepath+'profile_'+fitsfilenm+'_plot3.eps'
!p.multi=[0,1,1]
cgplot,offset_arr,snroptarr,title='optimal snr vs center offset',/ynozero,xtitle='distance offset from center (pixels)'
cgplot,[widtharr[0],widtharr[0]],[-10000,10000],linestyle=2,/overplot
ps_end
ps_start,state.savepath+'profile_'+fitsfilenm+'_plot4.eps'
cgplot,offset_arr,avgoptarr,title='optimal flux vs center offset',/ynozero,xtitle='distance offset from center (pixels)'
cgplot,[widtharr[0],widtharr[0]],[-10000,10000],linestyle=2,/overplot
ps_end
ps_start,state.savepath+'profile_'+fitsfilenm+'_plot5.eps'
cgplot,offset_arr,snrboxarr,title='boxcar snr vs center offset',/ynozero,xtitle='distance offset from center (pixels)'
cgplot,[widtharr[0],widtharr[0]],[-10000,10000],linestyle=2,/overplot
ps_end
ps_start,state.savepath+'profile_'+fitsfilenm+'_plot6.eps'
cgplot,offset_arr,avgboxarr,title='boxcar flux vs center offset',/ynozero,xtitle='distance offset from center (pixels)'
cgplot,[widtharr[0],widtharr[0]],[-10000,10000],linestyle=2,/overplot
ps_end
;rerun extraction to fix damage.
bmep_extraction_subpixel,j,centerarr,state,order,widtharr,bkgndl,bkgndr,$
printp,fitgaussp,plotp,slidep,pwindowsize,singlep,$
cosmic_sigma,n_iterate_cosmic,bkgnd_naverage,max_rays_per_col,$
gwidth,gcenter,$
$;OUTPUTS
F,ferr,Fopt,fopterr,img2d_nobkgnd,sky_reslut_arr,sky_residuals,revisevar=state.revisevar,/quiet
;print,'\end{tabular}'
!p.multi = pmsave
end
;follows horne 86 method of flagging cosmic rays. it also flags anything
;with a variance of 0 as a bad pixel.
;i is column number.
pro bmep_calc_cosmic_rays,i,bkgndl,bkgndr,bottomint,topint,state,totalpixflagged,$
xarr_big,sky_reslut_arr,p,f,cosmic_sigma,badPixelMask,sky_residuals,n_iterate_cosmic,$
order,xarr_small,bkgnd_naverage,max_rays_per_col,variance,ferr
;variables all the same as in main extraction program.
FORWARD_FUNCTION bmep_blind_hdr, bmep_dir_exist, bmep_fit_sky,bmep_find_p_slide, $
bmep_find_p, bmep_get_slitname, bmep_make_hdr,bmep_sigma_clip, bmep_percent_cut
;all pixels start as good
badPixelMask=replicate(1.0,n_elements(state.data[0,*]))
n_flagged=0
if cosmic_sigma gt 0 then begin
;calculate range that you care about.
if n_elements(bkgndl) ge 1 then begin
bottom_cosmic_range=fix(min(bkgndl))
top_cosmic_range=fix(max(bkgndr))
endif else begin
bottom_cosmic_range=bottomint
top_cosmic_range=topint
endelse
;check that range is OK
if bottom_cosmic_range lt 0 then bottom_cosmic_range=0
if top_cosmic_range gt n_elements(state.data[0,*])-1 then top_cosmic_range=n_elements(state.data[0,*])-1
if bottom_cosmic_range gt n_elements(state.data[0,*])-1 then bottom_cosmic_range=0
if top_cosmic_range lt 0 then top_cosmic_range=n_elements(state.data[0,*])-1
;make names easier...
bot=bottom_cosmic_range
top=top_cosmic_range
;remove zeroes without messing with the removed count
index=where(variance[i,bot:top] eq 0,ct)
index=index+bot
if ct gt 0 then badPixelMask[index]=0.0
;data - sky - f*p
residual_arr=(state.data[i,bot:top] - $
poly(findgen(top-bot+1)+bot,sky_reslut_arr[i,*]) - $
f[i]*p[bot:top])
index=where(residual_arr*residual_arr GT $
cosmic_sigma*cosmic_sigma*variance[i,bot:top],ct)
index=index+bot
;actually do the masking if not too many flagged.
if ct gt 0 and ct lt max_rays_per_col then badPixelMask[index]=0.0 ; mark bad pixels as 0
nflagged=ct
;if cosmic rays, iterate things...
if ct ne 0 and ct ne n_elements(badPixelMask) and ct lt max_rays_per_col then begin
totalpixflagged=totalpixflagged+ct
for cosmic_counter=0, n_iterate_cosmic-1 do begin
;recalculate sky
newresult=bmep_fit_sky(badPixelMask*state.data[i,*],bkgndl,bkgndr,order,bkgnd_naverage)
;recalculate boxcar flux
f[i]=total(badPixelMask*(state.data[i,bottomint:topint] - poly(xarr_small,newresult)))
ferr[i]=sqrt(total(badPixelMask*(variance[i,bottomint:topint])))
;recalculate residual array (note new sky, not old)
residual_arr=badPixelMask[bot:top]*(state.data[i,bot:top] - $
poly(findgen(top-bot+1)+bot,newresult) - $
f[i]*p[bot:top])
;find more bad pixels
index=where(residual_arr*residual_arr GT cosmic_sigma*cosmic_sigma*variance[i,bot:top],ct) ;flag bad pixels
;mask pixels
if ct gt 0 and ct lt max_rays_per_col - nflagged then begin
badPixelMask[index]=0.0
totalpixflagged=totalpixflagged+ct
nflagged=nflagged+ct
endif
;bail out of for loop if no moar cosmic rays.
if ct eq 0 or ct ge max_rays_per_col - nflagged then break
endfor
sky_reslut_arr[i,*]=newresult ; update sky array.
endif
sky_residuals[i]=total(abs(residual_arr))
endif;cosmic sigma gt 0
end
;attempt to calculate where the bad skylines are based on variance image
pro bmep_calc_skyline_mask,varimg,percent,rval
FORWARD_FUNCTION bmep_blind_hdr, bmep_dir_exist, bmep_fit_sky,bmep_find_p_slide, $
bmep_find_p, bmep_get_slitname, bmep_make_hdr,bmep_sigma_clip, bmep_percent_cut
tempvarimg=varimg
;only consider finite values (remove nans)
index=where(finite(tempvarimg) eq 0,ct)
tempvarimg[index]=0.0
;define default return value of 1 for each wavelength
rval=replicate(1.0,n_elements(varimg[*,0]))
mask=[]
;calculate the total noise in one column.
for i=0,n_elements(varimg[*,0])-1 do mask=[mask,total(varimg[i,*])]
;calculate bad arrays based on the total noise
indexbad=where(mask gt bmep_percent_cut(mask,100-percent),maskedct)
indexgood=where(mask le bmep_percent_cut(mask,100-percent),goodct)
;0 has unacceptable noise, 1 has good value
rval[indexbad]=0.0
rval[indexgood]=1.0
end
;attempt to calculate where the bad skylines are based on noise in extracted spectrum
;so it masks out the noisest lines
pro bmep_calc_skyline_mask_v2,var_opt,percent,rval
FORWARD_FUNCTION bmep_blind_hdr, bmep_dir_exist, bmep_fit_sky,bmep_find_p_slide, $
bmep_find_p, bmep_get_slitname, bmep_make_hdr,bmep_sigma_clip, bmep_percent_cut
tempvarimg=var_opt
index=where(finite(tempvarimg) eq 0,ct)
tempvarimg[index]=0.0
rval=replicate(1.0,n_elements(var_opt))
mask=var_opt
indexbad=where(mask gt bmep_percent_cut(mask,100-percent),maskedct)
indexgood=where(mask le bmep_percent_cut(mask,100-percent),goodct)
rval[indexbad]=0.0
rval[indexgood]=1.0
end
;input: gauss_sigma. sigma of the gaussian fit to the y-profile.
function bmep_calc_slitloss,gauss_sigma
pixscale=0.1799 ;pixelscale in arcsec/pixel
slitwidth=0.7 ; slitwidth in arcseconds
return,erf((slitwidth/pixscale/2)/(gauss_sigma)/sqrt(2.0))
end
pro bmep_clean_imgs,sci,var,silent=silent
index=where(finite(var) eq 0 or finite(sci) eq 0,ct,/null)
if ~keyword_set(silent) then print,'there are ',ct,' nan vals'
sci[index]=0.0
var[index]=0.0
var=double(var)
sci=double(sci)
end
;check if a directory exists.
;stolen from somewhere....
function bmep_dir_exist, dir
CD, CUR=cur
CATCH, error_status
if (error_status NE 0) then begin
return, 0
endif
CD, dir
CD, cur
return, 1
end
; Anyone can run BMEP on any normal fits image by calling this function
; This program calls the actual program, bmep and bmep_lris are instrument
; specific wrappers. BMEP is for mosfire, bmep_lris is for LRIS data.
;
; Inputs
;big_img - image to be displayed. can be different than science image if you
; wanted to show the variance image as well. The X SIZE of this image
; should be the same as the science image
;
;sciimg - science image in number of electrons.
;
;var_img - variance of the above image. If assuming poisson noise, this input would
; be exactly the same as the science image
;
;highval - Sometimes there are cosmic rays that mess up the scale of the images and
; make it impossible to see the image properly. If there is one spike at,
; say, a value of 60000 but the majority of your image is between 3000 and
; 5000, you would want to set this value to something like 5500. This is because
; there is basically no data between 5000 and 60000 but this eats up all
; the dynamic range of the image display. to exclude the top 10 percent of
; the pixels (set them to white...) make this bmep_percent_cut(sciimg,90).
; To include the full range of the image set this to max(sciimg).
;
;lowval - Same thing as highval but this sets the lower limit. To exclude
;
;slitname - name of object in slit for saving purposes.
;
;filtername - name of filter for slit for saving purposes.
;
;wavel - wavelength array of the data. Should have same number of elements as x direction
; of science image.
;
;savepath - output will be saved in savepath+slitname+'.sav'
; to save in current directory (not advisable) use set savepathe to ''
; if multiple objects are in slit and they are extracted, the path will be
; savepath+slitname+suffix+'.sav' where "suffix" is "--N" where N is the
; object number.
;
;revisevar - set keyword to revise variance estimate. no default, please set this. (essential keyword)
;
;extrainfo1 - fits keywords to be added to fits header ()
;extrainfo2 - values of the fits keywords to be added ()
;extrainfo2 - comments of the fits keywords to be added ()
;savetext - flag as to weather or not to save a text file. (optional)
;
;
;NOTES: this will only work on idl 8.1 or higher.
; The majority of the program is housed in the bmep_keyboardhandler() function.
;
pro bmep_display_image,big_img,sciimg,var_img,highval,lowval,slitname,filtername,wavel,savepath,$
revisevar=revisevar,extrainfo1=extrainfo1,extrainfo2=extrainfo2,extrainfo3=extrainfo3,savetext=savetext,$
monitorfix=monitorfix,vacuum=vacuum,serendips=serendips
FORWARD_FUNCTION bmep_blind_hdr, bmep_dir_exist, bmep_fit_sky,bmep_find_p_slide, $
bmep_find_p, bmep_get_slitname, bmep_make_hdr,bmep_sigma_clip, bmep_percent_cut
if ~keyword_set(extrainfo1) then message,'must have ex info 1'
if ~keyword_set(extrainfo2) then message,'must have ex info 2'
if ~keyword_set(extrainfo3) then message,'must have ex info 3'
if ~keyword_set(savetext) then savetext=0
if ~keyword_set(monitorfix) then monitorfix=0
if ~keyword_set(vacuum) then vacuum=0
if ~keyword_set(serendips) then serendips=[-1]
!except=2
dimensions = GET_SCREEN_SIZE()
monitor_width=dimensions[0]-10
;check version number
IF (Float(!Version.Release) lt 8.1) THEN message,'idl ver must be 8.1 or greater'
index=where(var_img eq 0,ct)
;print,'there are ',ct,' pixels with 0 variance '
index=where(finite(var_img) eq 0,ct)
;print,'there are ',ct,' pixels with nan value for variance '
sciimg[index]=0.0
var_img[index]=0.0
index=where(var_img lt 0,ct)
var_img[INDEX]=ABS(var_img[INDEX])
;print,'there are ',ct,' pixels with NEGATIVE value for variance '
dimensions = GET_SCREEN_SIZE()
monitor_width=dimensions[0]-10
if n_elements(big_img[*,0]) gt monitor_width then begin
xdim=monitor_width
width_scale_factor=float(n_elements(big_img[*,0]))/float(monitor_width)
endif else begin
xdim=n_elements(big_img[*,0])
width_scale_factor=1.0
endelse
; print,'monitor width scale factor is: ',width_scale_factor
im1=image(big_img,dimensions=[xdim,n_elements(big_img[0,*])],$ ;n_elements(big_img[0,*])
window_title=slitname+'-'+filtername,max_value=highval,min_value=lowval,margin=[0,0,0,0],$
location=[0,0],/xstyle,/ystyle,/widget);title=slitname,
im1.window.UVALUE={x0:0, y0:0, buttonDown:0L,$
ydata:replicate(0.D,n_elements(sciimg[0,*])),ydataerr:replicate(0.D,n_elements(sciimg[0,*])),data:sciimg,$
slitname:slitname+'_'+filtername,wavel:wavel,savepath:savepath,var_img:var_img,revisevar:revisevar,$
raw_slitname:slitname,extrainfo1:extrainfo1,extrainfo2:extrainfo2,extrainfo3:extrainfo3,$
savetext:savetext,cont_mode:0,monitorfix:monitorfix,vacuum:vacuum,$
stats_mode:0,n_bins:0,l_bins:[0,0,0,0,0,0,0,0,0,0,0],r_bins:[0,0,0,0,0,0,0,0,0,0,0],$
cmode_arr:[0,0,0,0,0,0,0,0,0,0,0],width_scale_factor:width_scale_factor,serendips:serendips}
im1.window.MOUSE_DOWN_HANDLER='bmep_MouseDown'
im1.window.MOUSE_UP_HANDLER='bmep_MouseUp'
im1.window.Keyboard_Handler='bmep_KeyboardHandler'
end
;extract the spectra!! algorithm from horne 1986
pro bmep_extraction_simple,sciimg,var_img,ydata,ypos,width,f,ferr,fopt,fopterr,p
FORWARD_FUNCTION bmep_blind_hdr, bmep_dir_exist, bmep_fit_sky,bmep_find_p_slide, $
bmep_find_p, bmep_get_slitname, bmep_make_hdr,bmep_sigma_clip, bmep_percent_cut
cosmic_sigma=4.5
max_rays_per_col=0
f=[]
ferr=[]
fopt=[]
fopterr=[]
bottomint=round(ypos-width)
if bottomint lt 0 then bottomint=0
topint=round(ypos+width)
if topint gt n_elements(sciimg[0,*])-1 then topint=n_elements(sciimg[0,*])-1
xarr_small=findgen(topint-bottomint+1)+bottomint
xarr_big=findgen(n_elements(ydata))
;double check that the extraction ranges are actually the same.
if min(xarr_small) ne bottomint then print,'WARNING, THE EXTRACTION RANGES ARE DIFFERENT.'
variance=var_img
for i=0,n_elements(sciimg[*,0])-1 do begin
f=[f,total(sciimg[i,bottomint:topint])]
ferr=[ferr,sqrt(total(variance[i,bottomint:topint]))]
endfor
;===OPTIMAL===================================================
p=ydata
index=where(xarr_big lt bottomint or xarr_big gt topint,/null)
p[index]=0.0
index=where(p lt 0,/null)
p[index]=0.0
if total(p) ne 0 then p=p/total(p)
gresult=MPFITPEAK(double(xarr_big),double(p),$
coeff,nterms=3,/gaussian)
p=gresult
index=where(xarr_big lt bottomint or xarr_big gt topint,ct)
if ct ne 0 then p[index]=0.0
index=where(p lt 0,ct)
if ct gt 0 then p[index]=0.0
if total(p) ne 0 then p=p/total(p)
for i=0,n_elements(sciimg[*,0])-1 do begin
badPixelMask=replicate(1.0,n_elements(p))
residual_arr=(sciimg[i,xarr_small] - f[i]*p[xarr_small])
index=where(residual_arr*residual_arr GT $
cosmic_sigma*cosmic_sigma*variance[i,xarr_small],ct)
if ct lt max_rays_per_col and ct gt 0 then badPixelMask[xarr_small[index]]=0.0
var_opt=variance[i,*]
index=where(var_opt[xarr_small] eq 0.0 or var_opt[xarr_small] eq 99.00 or var_opt[xarr_small] eq 99.0*99.0,count)
if count gt 0 then begin
badPixelMask[xarr_small[index]]=0.0
var_opt[xarr_small[index]]=1.0
endif ;else begin
;calc optimal flux as in horne
numerator=total(badPixelMask[xarr_small]*p[xarr_small]*$
(sciimg[i,xarr_small])/var_opt[xarr_small])
denominator=total(badPixelMask[xarr_small]*p[xarr_small]*p[xarr_small]/var_opt[xarr_small])
if denominator ne 0 then flux_opt=numerator/denominator else flux_opt=0.0
;calc optimal flux error as in horne.
numerator=total(badPixelMask[xarr_small]*p[xarr_small]) ;
denominator=total(badPixelMask[xarr_small]*p[xarr_small]*p[xarr_small]/var_opt[xarr_small])
if denominator ne 0 then err_opt=sqrt(abs(numerator/denominator)) else err_opt=0.0
;undo the damage from setting pixels with zero variance to one
if count gt 0 then var_opt[xarr_small[index]]=0.0
fopt=[fopt,flux_opt] ;!!!!!!!!!!!!
fopterr=[fopterr,err_opt]
endfor ; cols of data! - end of the optimal section of extraction.
end ; end of extraction
;extract the spectra!! algorithm from horne 1986
pro bmep_extraction_simple_subpixel,sciimg,var_img,ydata,ypos,width,gcenter,gwidth,f,ferr,fopt,fopterr,p,fitgaussp
FORWARD_FUNCTION bmep_blind_hdr, bmep_dir_exist, bmep_fit_sky,bmep_find_p_slide, $
bmep_find_p, bmep_get_slitname, bmep_make_hdr,bmep_sigma_clip, bmep_percent_cut,bmep_find_p_simple
f=[]
ferr=[]
fopt=[]
fopterr=[]
bottomint=fix(ypos-width+1.0)>1
bottomremainder=1.0 - ( ( (ypos-width+1.0)-bottomint) < 1.0)
topint=fix(ypos+width)<(n_elements(sciimg[0,*])-2)
topremainder=((ypos+width)-topint) < 1.0
xarr_small=indgen(topint-bottomint+1)+bottomint
xarr_small_wider=findgen(topint-bottomint+3)+bottomint-1
xarr_big=findgen(n_elements(ydata))
;STEP2 (steps from horne 1986 extraction paper... step 1 was flatfielding)
for i=0,n_elements(sciimg[*,0])-1 do begin
;STEP3 (calculate sky)
;step4 (extract spectrum and error)
;remainder is OUTWARDS from the center...
botadd= sciimg[i,bottomint-1] * bottomremainder
botadderr= var_img[i,bottomint-1] * bottomremainder
topadd= sciimg[i,topint+1] * topremainder
topadderr= var_img[i,topint+1] * topremainder
f=[f,total(sciimg[i,bottomint:topint])+topadd+botadd]
ferr=[ferr,sqrt(total(var_img[i,bottomint:topint])+botadderr+topadderr)]
endfor ; looping through i, the number of columns...
;optimal extraction based on horne 1989
;step 5 (calculate p)
if gcenter lt -1 then BEGIN
p=bmep_find_p_simple(ydata,bottomint,topint,fitgaussp)
endif else begin
xarr_fit=[min(xarr_small)-bottomremainder,float(xarr_small),max(xarr_small)+topremainder]
p_small_wider=gaussian(xarr_fit,[1.0,gcenter,gwidth])
p_small_wider[0]=p_small_wider[0] * bottomremainder
p_small_wider[-1]=p_small_wider[-1] * topremainder
p=replicate(0.0,n_elements(xarr_big))
p[xarr_small_wider]=p_small_wider
endelse
p=double(p)
if total(p) ne 0 then p=p/total(p)
;set up vars
;loop through columns
for i=0,n_elements(sciimg[*,0])-1 do begin
;recalculate fractions to add to top/bottom of extractions.
botadd= sciimg[i,bottomint-1] * bottomremainder
botadderr= var_img[i,bottomint-1] * bottomremainder
topadd= sciimg[i,topint+1] * topremainder
topadderr= var_img[i,topint+1] * topremainder
;step 7 (mask cosmic rays)
;calculate range over which we care about cosmic rays
badPixelMask=replicate(1.0,n_elements(xarr_big))
;swapped steps 6 and 7 to use better flux estimation after removing cosmic spikes.
;step 6 (Revise errors) (dont revise for MOSFIRE)
var_opt=var_img[i,*]
;step 8
col_data=[botadd,reform(sciimg[i,xarr_small]),topadd]
var_data=[botadderr,var_opt[xarr_small],topadderr]
bp_data=badPixelMask[xarr_small_wider]
p_data=p[xarr_small_wider]
p_data=p_data/total(p_data)
;try to not divide by 0.
index=where(var_data eq 0.0 or var_data eq 99.00,count)
if count gt 0 then begin
bp_data[index]=0.0
var_data[index]=1.0
endif ;else begin
;calc optimal flux as in horne
numerator=total(bp_data*p_data*col_data/var_data)
denominator=total(bp_data*p_data*p_data/var_data)
if denominator ne 0 then flux_opt=numerator/denominator else flux_opt=0.0
;calc optimal flux error as in horne.
numerator=total(bp_data*p_data) ;
denominator=total(bp_data*p_data*p_data/var_data)
if denominator ne 0 then err_opt=sqrt(abs(numerator/denominator)) else err_opt=0.0
fopt=[fopt,flux_opt] ;!!!!!!!!!!!!
fopterr=[fopterr,err_opt]
endfor ; cols of data! - end of the optimal section of extraction.
end ; end of extraction
;extract the spectra!! algorithm from horne 1986
pro bmep_extraction,j,centerarr,state,order,widtharr,bkgndl,bkgndr,$
printp,fitgaussp,plotp,slidep,pwindowsize,singlep,cosmic_sigma,$
n_iterate_cosmic,bkgnd_naverage,max_rays_per_col,gwidth,gcenter,$
$;OUTPUTS
F,ferr,Fopt,fopterr,img2d_nobkgnd,parr,sky_reslut_arr,sky_residuals,$
revisevar=revisevar,quiet=quiet
FORWARD_FUNCTION bmep_blind_hdr, bmep_dir_exist, bmep_fit_sky,bmep_find_p_slide, $
bmep_find_p, bmep_get_slitname, bmep_make_hdr,bmep_sigma_clip, bmep_percent_cut
if ~keyword_set(quiet) then quiet = 0
f=[]
ferr=[]
fopt=[]
fopterr=[]
sky_reslut_arr=findgen(n_elements(state.data[*,0]),order+1)
if ~quiet then print,'center, width',centerarr[j],widtharr[j]
;lower extraction limit
bottomint=round(centerarr[j]-widtharr[j])>0
;upper extraction limit
topint=round(centerarr[j]+widtharr[j])<(n_elements(state.data[0,*])-1)
;calculate array to extract
xarr_small=findgen(topint-bottomint+1)+bottomint
;calculate array for whole column
xarr_big=findgen(n_elements(state.ydata))
;double check that the extraction ranges are actually the same.
if min(xarr_small) ne bottomint then print,'WARNING, THE EXTRACTION RANGES ARE DIFFERENT.'
if max(xarr_small) ne topint then print,'WARNING, THE EXTRACTION RANGES ARE DIFFERENT.'
if ~quiet then PRINT,'Extracting from ',bottomint,' to ',topint,' ',n_elements(xarr_small),' elements'
;STEP2 (steps from horne 1986 extraction paper... step 1 was flatfielding)
variance=state.var_img
for i=0,n_elements(state.data[*,0])-1 do begin
;STEP3 (calculate sky)
result=bmep_fit_sky(state.data[i,*],bkgndl,bkgndr,order,bkgnd_naverage)
SKY=poly(xarr_small,result)
sky_reslut_arr[i,*]=result
;step4 (extract spectrum and error)
f=[f,total(state.data[i,bottomint:topint] - sky)]
ferr=[ferr,sqrt(total(variance[i,bottomint:topint]))]
endfor ; looping through i, the number of columns...
;===OPTIMAL===================================================
;optimal extraction based on horne 1989
;step 5 (calculate p)
;figure out p from cross section and use only that.
if singlep then begin
if slidep then message,'insanity occured. only single p or slide p allowed'
FORWARD_FUNCTION bmep_find_p
;calculate p
if gcenter[j] gt 0 then begin
p=replicate(0.0,n_elements(xarr_big))
p[xarr_small]=gaussian(float(xarr_small),[1.0,gcenter[j],gwidth[j]])
if fitgaussp eq 0 then p=bmep_find_p(state,bkgndl,bkgndr,$
order,bottomint,topint,printp,fitgaussp,$
plotp,xarr_big,bkgnd_naverage)
p=double(p)
if total(p) ne 0 then p=p/total(p)
endif else begin
p=bmep_find_p(state,bkgndl,bkgndr,$
order,bottomint,topint,printp,fitgaussp,$
plotp,xarr_big,bkgnd_naverage)
endelse
;plot p on the plot
plotshift=poly(centerarr[j],bmep_fit_sky(state.ydata,bkgndl,bkgndr,order,bkgnd_naverage))
pscale=(state.ydata[centerarr[j]]-plotshift)/max(p)
; pmulti_save=!p.multi
; if j gt 1 then !p.multi[0]=1
oplot,(p*pscale + plotshift),color=255,linestyle=3
; !p.multi[0]=1+j*2
endif
;set up vars
parr=replicate(0.0,n_elements(state.data[*,0]),n_elements(state.data[0,*]))
img2d_nobkgnd=replicate(0.0,n_elements(state.data[*,0]),n_elements(state.data[0,*]))
sky_residuals=replicate(0.0,n_elements(state.data[*,0]))
totalpixflagged=0
;loop through columns
for i=0,n_elements(state.data[*,0])-1 do begin
;if spectrum is UNDERSAMPLED in the spatial direction,
;p (the fraction of light in each pixel) could change as
;a function of wavelength. If this is true, p should be
;reevaluated as a function of position. The way I do this
;pretty much only works for anything bright.
;(step 5) Alternate version of step 5...
if slidep then begin
if singlep then message,'insanity occured. only single p or slide p allowed'
p=bmep_find_p_slide(state,pwindowsize,i,f,xarr_small)
endif
;step 7 (mask cosmic rays)
;calculate range over which we care about cosmic rays
if keyword_set(revisevar) then bmep_calc_cosmic_rays,i,bkgndl,bkgndr,bottomint,topint,state,totalpixflagged,$
xarr_big,sky_reslut_arr,p,f,cosmic_sigma,badPixelMask,sky_residuals,n_iterate_cosmic,$
order,xarr_small,bkgnd_naverage,max_rays_per_col,variance,ferr $
else badPixelMask=replicate(1.0,n_elements(xarr_big))
;swapped steps 6 and 7 to use better flux estimation after removing cosmic spikes.
;step 6 (Revise errors) (dont revise for MOSFIRE)
if keyword_set(revisevar) then var_opt=poly(xarr_big,sky_reslut_arr[i,*]) + f[i]*p $
else var_opt=variance[i,*]
;step 8
;try to not divide by 0.
index=where(var_opt[xarr_small] eq 0.0 or var_opt[xarr_small] eq 99.00,count)
if count gt 0 then begin
; print,i,count,' number of var_opt bade '
; print,index
;places with 0 variance are considered bad
badPixelMask[xarr_small[index]]=0.0
;though they are still in the denominator, so set
;their value to 1.0 temporarily.
;these points are masked, so their value doesn't matter
var_opt[xarr_small[index]]=1.0
endif ;else begin
;calc optimal flux as in horne
numerator=total(badPixelMask[xarr_small]*p[xarr_small]*$
(state.data[i,xarr_small] - poly(xarr_small,sky_reslut_arr[i,*]))/var_opt[xarr_small])
denominator=total(badPixelMask[xarr_small]*p[xarr_small]*p[xarr_small]/var_opt[xarr_small])
if denominator ne 0 then flux_opt=numerator/denominator else flux_opt=0.0
;calc optimal flux error as in horne.
numerator=total(badPixelMask[xarr_small]*p[xarr_small]) ;
denominator=total(badPixelMask[xarr_small]*p[xarr_small]*p[xarr_small]/var_opt[xarr_small])
if denominator ne 0 then err_opt=sqrt(abs(numerator/denominator)) else err_opt=0.0
;undo the damage from setting pixels with zero variance to one
if count gt 0 then var_opt[xarr_small[index]]=0.0
fopt=[fopt,flux_opt] ;!!!!!!!!!!!!
fopterr=[fopterr,err_opt]
img2d_nobkgnd[i,*]=state.data[i,*] - poly(findgen(n_elements(state.data[i,*])),sky_reslut_arr[i,*])
parr[i,*]=p
; if i gt 405 and flux_opt eq 0 then stop
endfor ; cols of data! - end of the optimal section of extraction.
if not quiet then print,'eliminated cosmic rays: ',totalpixflagged
end ; end of extraction
;extract the spectra!! algorithm from horne 1986. Modified to do sub-pixel extractions
pro bmep_extraction_subpixel,j,centerarr,state,order,widtharr,bkgndl,bkgndr,$
printp,fitgaussp,plotp,slidep,pwindowsize,singlep,cosmic_sigma,$
n_iterate_cosmic,bkgnd_naverage,max_rays_per_col,gwidth,gcenter,$
$;OUTPUTS
F,ferr,Fopt,fopterr,img2d_nobkgnd,sky_reslut_arr,sky_residuals,$
revisevar=revisevar,quiet=quiet
FORWARD_FUNCTION bmep_blind_hdr, bmep_dir_exist, bmep_fit_sky,bmep_find_p_slide, $
bmep_find_p, bmep_get_slitname, bmep_make_hdr,bmep_sigma_clip, bmep_percent_cut
if ~ keyword_set(quiet) then quiet = 0
;print,'doing center number ',j
f=[]
ferr=[]
fopt=[]
fopterr=[]
sky_reslut_arr=findgen(n_elements(state.data[*,0]),order+1)
;lower extraction limit
bottomint=fix(centerarr[j]-widtharr[j]+1.0)>1
bottomremainder=1.0 - ( ( (centerarr[j]-widtharr[j]+1.0)-bottomint) < 1.0)
;upper extraction limit
topint=fix(centerarr[j]+widtharr[j])<(n_elements(state.data[0,*])-2)
topremainder=((centerarr[j]+widtharr[j])-topint) < 1.0
;check for insanity
if topremainder lt 0 or bottomremainder lt 0 then message,'insanity'
;calculate array to extract
xarr_small=indgen(topint-bottomint+1)+bottomint