-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathiris_snr_sim.py
executable file
·1806 lines (1448 loc) · 71.7 KB
/
iris_snr_sim.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 python
# SNR equation:
# S/N = S*sqrt(T)/sqrt(S + npix(B + D + R^2/t))
# t = itime per frame
# T = sqrt(Nframes*itime)
# S, B, D -> electrons per second
# R -> read noise (electrons)
import argparse, os, sys
from math import log10,ceil,sqrt,log
import ConfigParser # Python 2.7?
#import configparser
import json
from collections import OrderedDict
import numpy as np
from scipy import integrate,interpolate
from astropy.io import fits
from astropy.modeling import models
from photutils import aperture_photometry
from photutils import CircularAperture, SkyCircularAperture
from photutils.background import Background2D
from astropy.convolution import Tophat2DKernel
from scipy.signal import convolve2d
from scipy.signal import fftconvolve
import scipy
import photutils
#print photutils.__version__
import matplotlib.pyplot as plt
# constants
c_km = 2.9979E5 # km/s
c = 2.9979E10 # cm/s
h = 6.626068E-27 # cm^2*g/s
k = 1.3806503E-16 # cm^2*g/(s^2*K)
Ang = 1E-8 # cm
mu = 1E-4 # cm
# IRIS interal packages
from get_filterdat import get_filterdat
#from background_specs import background_specs2
from background_specs import background_specs3
from get_psf import get_psf
def extrap1d(interpolator):
xs = interpolator.x
ys = interpolator.y
def pointwise(x):
if x < xs[0]:
return ys[0]+(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0])
elif x > xs[-1]:
return ys[-1]+(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2])
else:
return interpolator(x)
def ufunclike(xs):
return np.array(map(pointwise, np.array(xs)))
return ufunclike
def binnd(ndarray, new_shape, operation='sum'):
"""
Bins an ndarray in all axes based on the target shape, by summing or
averaging.
Number of output dimensions must match number of input dimensions and
new axes must divide old ones.
Example
-------
>>> m = np.arange(0,100,1).reshape((10,10))
>>> n = bin_ndarray(m, new_shape=(5,5), operation='sum')
>>> print(n)
[[ 22 30 38 46 54]
[102 110 118 126 134]
[182 190 198 206 214]
[262 270 278 286 294]
[342 350 358 366 374]]
"""
if not operation in ['sum', 'mean']:
raise ValueError("Operation not supported.")
if ndarray.ndim != len(new_shape):
raise ValueError("Shape mismatch: {} -> {}".format(ndarray.shape,
new_shape))
compression_pairs = [(d, c//d) for d,c in zip(new_shape,
ndarray.shape)]
flattened = [l for p in compression_pairs for l in p]
ndarray = ndarray.reshape(flattened)
for i in range(len(new_shape)):
op = getattr(ndarray, operation)
ndarray = op(-1*(i+1))
return ndarray
def IRIS_ETC(filter = "K", mag = 21.0, flambda=1.62e-19, fint=4e-17, itime = 1.0,
nframes = 1, snr = 10.0, radius = 0.024, gain = 3.04,
readnoise = 5., darkcurrent = 0.002, scale = 0.004,
resolution = 4000, collarea = 630.0, positions = [0, 0],
bgmag = None, efftot = None, mode = "imager", calc = "snr",
spectrum = "Vega", lam_obs = 2.22, line_width = 200.,
png_output = None, zenith_angle = 30. , atm_cond = 50.,source='point_source',source_size=0.2,csv_output=None,
psf_loc = [8.8, 8.8], psf_time = 1.4, verb = 1, psf_old = 0,
simdir='~/data/iris/sim/', psfdir='~/data/iris/sim/', test = 0):
#print flambda
#print mag
# KEYWORDS: filter - broadband filter to use (default: 'K')
# mag - magnitude of the point source
# itime - integration time per frame (default: 900 s)
# nframes - number of observations (default: 1)
# snr - signal-to-noise of source
# radius - aperture radius in arcsec
# gain - gain in e-/DN
# readnoise - read noise in e-
# darkcurrent - dark current noise in e-/s
# scale - pixel scale (default: 0.004"), sets the IFS mode: slicer or lenslet
# imager - calculate the SNR if it's the imager
# collarea - collecting area (m^2) (TMT 630, Keck 76)
# positions - position of point source
# bgmag - the background magnitude (default: sky
# background corresponding to input filter)
# efftot - total throughput
# verb - verbosity level
# mode - either "imager" or "ifs"
# calc - either "snr" or "exptime"
#fixed radius 0.2 arc sec
radius=0.2
radius /= scale
## Saturation Limit
sat_limit=90000
if spectrum.lower() == "vega":
spectrum = "vega_all.fits"
#spectrum = "spec_vega.fits"
##### READ IN FILTER INFORMATION
filterdat = get_filterdat(filter, simdir)
lambdamin = filterdat["lambdamin"]
lambdamax = filterdat["lambdamax"]
lambdac = filterdat["lambdac"]
bw = filterdat["bw"]
filterfile = os.path.expanduser(simdir + filterdat["filterfiles"][0])
#print filterfile
#print lambdamin
#print lambdamax
#print lambdac
#print bw
#various scales of lambda/D radius according to scale
if scale==0.004:
radiusl=1*lambdac[0]*206265/3.e11
elif scale==0.009 :
radiusl=1.5*lambdac[0]*206265/3.e11
elif scale==0.025 :
radiusl=20*lambdac[0]*206265/3.e11
else:
radiusl=40*lambdac[0]*206265/3.e11
sizel=2*radiusl
radiusl /= scale
## Determine the length of the cube, dependent on filter
## (supporting only BB for now)
dxspectrum = 0
wi = lambdamin # Ang
wf = lambdamax # Ang
#resolution = resolution*2.
dxspectrum = int(ceil( log10(wf/wi)/log10(1.0+1.0/(resolution*2.0)) ))
## resolution times 2 to get nyquist sampled
crval1 = wi/10. # nm
cdelt1 = ((wf-wi) / dxspectrum)/10. # nm/channel
#print dxspectrum
# Throughput calculation
if efftot is None:
# Throughput number from Ryuji (is there wavelength dependence?)
#teltot = 0.91 # TMT total throughput
#aotot = 0.80 # NFIRAOS AO total throughput
teltot = 0.91
aotot = 0.80
wav = [830,900,2000,2200,2300,2412] # nm
if mode == "imager":
tput = [0.631,0.772,0.772,0.813,0.763,0.728] # imager
if verb > 1: print 'IRIS imager selected!!!'
else:
if (scale == 0.004) or (scale == 0.009):
tput = [0.340,0.420,0.420,0.490,0.440,0.400] # IFS lenslet
if verb > 1: print 'IRIS lenslet selected!!!'
else:
tput = [0.343,0.465,0.465,0.514,0.482,0.451] # IFS slicer
if verb > 1: print 'IRIS slicer selected!!!'
#print tput
w = (np.arange(dxspectrum)+1)*cdelt1 + crval1 # compute wavelength
#print,lambda
#####################################################################
# Interpolating the IRIS throughputs from the PDR-1 Design Description
# Document (Table 7, page 54)
#####################################################################
R = interpolate.interp1d(wav,tput,fill_value='extrapolate')
eff_lambda = [R(w) for w0 in w]
#print eff_lambda
###############################################################
# MEAN OF THE INSTRUMENT THROUGHPUT BETWEEN THE FILTER BANDPASS
###############################################################
instot = np.mean(eff_lambda)
#efftot = instot
efftot = instot*teltot*aotot
if verb > 1: print ' '
#print 'IRIS efficiency ', efftot
if verb > 1: print 'Total throughput (TMT+NFIRAOS+IRIS) = %.3f' % efftot
if bgmag:
backmag = bgmag
else:
backmag = filterdat["backmag"] #background between OH lines
imagmag = filterdat["imagmag"] #integrated BB background
if mode == "imager": backmag = imagmag ## use the integrated background if specified
zp = filterdat["zp"]
#print 'zp',zp
#print 'backmag',backmag
# test case
# PSFs
#print lambdac
if psf_old:
psf_dict = { 928:"psf_x0_y0_wvl928nm_implKOLMO117nm_bin4mas_sm.fits",
1092:"psf_x0_y0_wvl1092nm_implKOLMO117nm_bin4mas_sm.fits",
1270:"psf_x0_y0_wvl1270nm_implKOLMO117nm_bin4mas_sm.fits",
1629:"psf_x0_y0_wvl1629nm_implKOLMO117nm_bin4mas_sm.fits",
2182:"psf_x0_y0_wvl2182nm_implKOLMO117nm_bin4mas_sm.fits"}
psf_wvls = psf_dict.keys()
psf_ind = np.argmin(np.abs(lambdac/10. - psf_wvls))
psf_wvl = psf_wvls[psf_ind]
#psf_file = os.path.expanduser(simdir + "/psfs/" + psf_dict[psf_wvl])
psf_file = os.path.expanduser(psfdir + "/psfs/results_central/" + psf_dict[psf_wvl])
ext = 0
#print psf_ind
#print psf_wvl
#print psf_file
else:
if mode.lower() == "ifs":
psf_wvls = [840, 928, 1026, 988, 1092, 1206, 1149, 1270, 1403, 1474,
1629, 1810, 1975, 2182, 2412] # nm
if mode.lower() == "imager":
psf_wvls = [830, 876, 925, 970, 1019, 1070, 1166, 1245, 1330, 1485,
1626, 1781, 2000, 2191, 2400] # nm
#print psf_loc
#print zenith_angle
#print atm_cond
psf_time=itime
psf_file = get_psf(zenith_angle, atm_cond, mode, psf_time, psf_loc, scale)
#print psf_file
psf_file = os.path.expanduser(psfdir + "/psfs/" + psf_file)
#print 'psf_file',psf_file
#print os.path.isfile(psf_file)
psf_ind = np.argmin(np.abs(lambdac/10. - psf_wvls))
psf_wvl = psf_wvls[psf_ind]
ext = psf_ind
#print lambdac
#print psf_ind
#print psf_wvl
# FITS header comments contain wavelength information
# for i in xrange(len(pf)): print pf[i].header["COMMENT"]
# truncate PSF with iamge size goes down to 1e-6
# check in log scale
# 350 - 1150
pf = fits.open(psf_file)
#print len(pf)
image = pf[ext].data
head = pf[ext].header
#print head['COMMENT']
if mode == "imager":
image=binnd(image,[750,750],'sum')
image /= image.sum()
psf_extend=np.array(image)
#print 'imagemax',image.max()
if source=='extended':
window=300
obj=np.ones([1500,1500])
centerx=psf_extend.shape[0]/2
centery=psf_extend.shape[1]/2
psf_extend=psf_extend[centerx-(window/2):centerx+(window/2),centery-(window/2):centery+(window/2)]
#image=fftconvolve(obj,psf_extend,mode='same')
image=np.ones([1500,1500])
# position of center of PSF
x_im_size,y_im_size = image.shape
hw_x = x_im_size/2
hw_y = y_im_size/2
#print hw_x,hw_y
#sys.exit()
#print image.sum()
#image /= image.sum()
# mag = ABmag - 0.91 ; Vega magnitude
##########################################
# convert AB to Vega and vice versa
# band eff mAB - mVega
ABconv = [["i", 0.7472, 0.37 ],
["z", 0.8917, 0.54 ],
["Y", 1.0305, 0.634],
["J", 1.2355, 0.91 ],
["H", 1.6458, 1.39 ],
["Ks", 2.1603, 1.85 ]]
ABwave = [i[1] for i in ABconv]
ABdelta = [i[2] for i in ABconv]
#print
#print filter
if verb > 1:
fig = plt.figure()
p = fig.add_subplot(111)
p.plot(ABwave, ABdelta)
p.set_xlabel("Wavelength ($\mu$m)")
p.set_ylabel("m$_{\\rm AB}$ - m$_{\\rm Vega}$")
plt.show()
R_i = interpolate.interp1d(ABwave,ABdelta)
R_x = extrap1d(R_i)
delta = R_x(lambdac/1e4)
#print delta
# delta = mAB - mVega
##########################################
if mag is not None:
# convert to flux density (flambda)
ABmag = mag + delta
fnu = 10**(-0.4*(ABmag + 48.60)) # erg/s/cm^2/Hz
#print "Calculated from magnitude"
#print fnu,"erg/s/cm^2/Hz"
#flambda = fnu*Ang/((lam_obs*mu)**2/c)
flambda = fnu*Ang/((lambdac*Ang)**2/c)
flambda=flambda[0]
flux_phot = zp*10**(-0.4*mag) # photons/s/m^2
if source=='extended':
flux_phot= flux_phot*(scale**2)
elif flambda is not None:
# convert to Vega mag
fnu = flambda/(Ang/((lambdac*Ang)**2/c))
#print "Calculated from magnitude"
#print fnu,"erg/s/cm^2/Hz"
ABmag = -2.5* log10(fnu) - 48.60
mag = ABmag - delta
flux_phot = zp*10**(-0.4*mag) # photons/s/m^2
if source=='extended':
flux_phot= flux_phot*(scale**2)
elif fint is not None:
# Compute flux_phot from flux
E_phot = (h*c)/(lambdac*Ang)
flux_phot=1e4*fint/E_phot
if source=='extended':
flux_phot= flux_phot*(scale**2)
#print flambda
#print mag
#########################################################################
#########################################################################
# comparison:
#########################################################################
# http://ssc.spitzer.caltech.edu/warmmission/propkit/pet/magtojy/
# input: Johnson
# 20 K-banda
# 2.22 micron
# output:
# 6.67e-29 erg/s/cm^2/Hz
# 4.06e-19 erg/s/cm^2/Ang
#########################################################################
#################################################################
# tests
#################################################################
if test:
fnu = 10**(-0.4*(ABmag + 48.60)) # erg/s/cm^2/Hz
#print "Calculated from magnitude"
#print fnu,"erg/s/cm^2/Hz"
#flambda = fnu*Ang/((lam_obs*mu)**2/c)
flambda = fnu*Ang/((lambdac*Ang)**2/c)
#print flambda,"erg/s/cm^2/Ang"
#nu = c/(lam_obs*mu)
#print nu,"Hz"
#dnu = nu/(2*resolution)
#dlambda = lam_obs*1e4/(2*resolution)
#dlambda = (wf-wi) # Ang
#print dlambda, "Ang"
#print dnu, "Hz"
#print fnu*dnu,"erg/s/cm^2"
#print flambda*lambdac,"erg/s/cm^2"
E_phot = (h*c)/(lambdac*Ang) # erg
#print flambda*lambdac/E_phot,"photons/s/cm^2"
#print flambda/E_phot,"photons/s/cm^2/Ang"
# above is correct!!
########################################################################
if verb > 1:
# Vega test spectrum
if spectrum == "vega_all.fits":
ext = 0
spec_file = os.path.expanduser(simdir + "/model_spectra/" + spectrum)
pf = fits.open(spec_file)
spec = pf[ext].data
head = pf[ext].header
cdelt1 = head["cdelt1"]
crval1 = head["crval1"]
nelem = spec.shape[0]
specwave = (np.arange(nelem))*cdelt1 + crval1 # Angstrom
#spec /= 206265.**2
elif spectrum == "spec_vega.fits":
ext = 0
spec_file = os.path.expanduser(simdir + "/model_spectra/" + spectrum)
pf = fits.open(spec_file)
specwave = pf[ext].data[0,:] # Angstrom
spec = pf[ext].data[1,:] # erg/s/cm^2/Ang
nelem = spec.shape[0]
E_phot = (h*c)/(specwave*Ang) # erg
#print specwave
#print E_phot
fig = plt.figure()
p = fig.add_subplot(111)
p.plot(specwave, spec/E_phot) # photons/s/cm^2/Ang
p.set_xlim(3000,11000)
#p.set_xlim(20000,24000)
#p.set_ylim(0,2000)
p.set_xlabel("Wavelength ($\AA$)")
p.set_ylabel("Flux (photons cm$^{-2}$ s$^{-1}$ $\AA^{-1}$)")
p.set_title("Vega photon spectrum")
# ABnu = STlamb @ 5492.9 Ang
STlamb = 3.63E-9*np.ones((nelem)) # erg/cm^2/s/Ang STlamb = 0
ABnu = 3.63E-20*np.ones((nelem)) # erg/cm^2/s/Hz ABnu = 0
p.plot(specwave,STlamb/E_phot)
p.plot(specwave,ABnu/E_phot*(c/(specwave*Ang)**2)*Ang)
plt.show()
#print
#print
#print "Calculated from IRIS zeropoints"
E_phot = (h*c)/(lambdac*Ang) # erg
flux = flux_phot*E_phot*(1./(100*100)) # erg/s/cm^2
# convert from m**2 to cm**2
#print flux,"erg/s/cm^2"
#print flux_phot*(1./(100*100)),"photons/s/cm^2"
##print flux_phot/dnu,"photons/s/cm^2/Hz"
#print flux_phot*(1./(100*100))/lambdac,"photons/s/cm^2/Ang"
#print flux_phot,"photons/s/m^2"
#print flux_phot*collarea,"photons/s"
#print flux_phot*collarea*efftot,"photons/s"
#print flux/dnu,"erg/s/cm^2/Hz"
#print flux/dlambda,"erg/s/cm^2/Ang"
if verb > 1: print
#########################################################################
#########################################################################
#ymax,xmax = image.shape
#print xmax,ymax
if mode.lower() == "ifs":
#hwbox = 25
hwbox = 10
elif mode == "imager":
#hwbox = 239
hwbox = 100
# write check for hwbox boundary
if verb > 1: print image.shape
if 0:
# original code
xc,yc = [hw_x,hw_y]
xs = xc
ys = yc
subimage = image
else:
# center coordinates
#xp,yp = positions
xc,yc = positions
# image coordinates
xp = xc + hw_x
yp = yc + hw_y
# 239 x 239 is the shape of the PSF image
# subimage coordinates
xs = xc + hwbox
ys = yc + hwbox
subimage = image[yp-hwbox:yp+hwbox+1,xp-hwbox:xp+hwbox+1]
#print xc,yc
#print xp,yp
#print xs,ys
# normalize by the full PSF image
#subimage /= image.sum()
# to define apertures used throughout the calculations
radii = np.arange(1,50,1) # pixels
apertures = [CircularAperture([xs,ys], r=r) for r in radii]
aperture = CircularAperture([xs,ys], r=radius)
masks = aperture.to_mask(method='center')
mask = masks[0]
#Second Aperture lambda dependent
aperturel = CircularAperture([xs,ys], r=radiusl)
#print radius
#print radiusl
masksl = aperturel.to_mask(method='center')
maskl = masksl[0]
###########################################################################
###########################################################################
# IFS MODE
###########################################################################
###########################################################################
if mode.lower() == "ifs":
#bkgd = background_specs2(resolution*2.0, filter, convolve=True, simdir = simdir)
bkgd = background_specs3(resolution*2.0, filter, convolve=True, simdir = simdir,
filteronly=True)
ohspec = bkgd.backspecs[0,:]
cospec = bkgd.backspecs[1,:]
bbspec = bkgd.backspecs[2,:]
ohspectrum = ohspec*scale**2.0 ## photons/um/s/m^2
contspectrum = cospec*scale**2.0
bbspectrum = bbspec*scale**2.0
backtot = ohspectrum + contspectrum + bbspectrum
if verb >1:
print 'mean OH: ', np.mean(ohspectrum)
print 'mean continuum: ', np.mean(contspectrum)
print 'mean bb: ', np.mean(bbspectrum)
print 'mean background: ', np.mean(backtot)
backwave = bkgd.waves/1e4
wave = np.linspace(wi/1e4,wf/1e4,dxspectrum)
#print dxspectrum
#print len(wave)
#print len(backwave)
#print wave
#print backwave
backtot_func = interpolate.interp1d(backwave,backtot,fill_value='extrapolate')
backtot = backtot_func(wave)
#print
#print "Flux = %.2e photons/s/m^2" % flux_phot
#print "Image sum = %.1f" % subimage.sum()
#print subimage.shape
#print subimage.size
if spectrum.lower() == "flat":
spec_temp = np.ones(dxspectrum)
intFlux = integrate.trapz(spec_temp,wave)
intNorm = flux_phot/intFlux
#print "Spec integration = %.1f" % intFlux
#print "Spec normalization = %.4e" % intNorm
elif spectrum.lower() == "emission":
specwave = wave
lam_width=lam_obs/c_km*line_width
instwidth = (lam_obs/resolution)
width = np.sqrt(instwidth**2+lam_width**2)
A = flux_phot/(width*np.sqrt(2*np.pi)) # photons/s/m^2/micron
#print flux_phot
#print width*1e4
#print A
spec_temp = A*np.exp(-0.5*((specwave - lam_obs)/width)**2.)
intFlux = integrate.trapz(spec_temp,specwave)
intNorm = flux_phot/intFlux
#print "Spec integration = %.1f" % intFlux
#print "Spec normalization = %.4e" % intNorm
else:
if spectrum == "vega_all.fits":
ext = 0
spec_file = os.path.expanduser(simdir + "/model_spectra/" + spectrum)
pf = fits.open(spec_file)
spec = pf[ext].data
head = pf[ext].header
cdelt1 = head["cdelt1"]
crval1 = head["crval1"]
nelem = spec.shape[0]
specwave = (np.arange(nelem))*cdelt1 + crval1 # Angstrom
specwave /= 1e4 # -> microns
elif spectrum == "spec_vega.fits":
ext = 0
spec_file = os.path.expanduser(simdir + "/model_spectra/" + spectrum)
pf = fits.open(spec_file)
specwave = pf[ext].data[0,:] # Angstrom
spec = pf[ext].data[1,:] # erg/s/cm^2/Ang
nelem = spec.shape[0]
E_phot = (h*c)/(specwave*Ang) # erg
spec *= 100*100*1e4/E_phot # -> photons/s/m^2/um
specwave /= 1e4 # -> microns
#intFlux = integrate.trapz(spec,specwave,dx=dx)
#intFlux = integrate.simps(spec,specwave)
#intNorm = flux_phot/intFlux
#print
#print "Spec integration = %.2e" % intFlux
#print "Spec normalization = %.4e" % intNorm
#print
if verb > 1:
fig = plt.figure()
p = fig.add_subplot(111)
p.plot(specwave, spec)
#p.set_xscale("log")
#p.set_yscale("log")
plt.show()
################################################
# convolve with the resolution of the instrument
################################################
delt = 2.0*(wave[1]-wave[0])/(specwave[1]-specwave[0])
#delt = 0
if delt > 1:
stddev = delt/2*sqrt(2*log(2))
psf_func = models.Gaussian1D(amplitude=1.0, stddev=stddev)
x = np.arange(4*int(delt)+1)-2*int(delt)
psf = psf_func(x)
psf /= psf.sum() # normalize
spec = np.convolve(spec, psf,mode='same')
spec_func = interpolate.interp1d(specwave,spec)
spec_temp = spec_func(wave)
intFlux = integrate.trapz(spec_temp,wave)
#intFlux = integrate.simps(spec_temp,wave)
intNorm = flux_phot/intFlux
#print
#print "Spec integration = %.2e" % intFlux
#print "Spec normalization = %.4e" % intNorm
#print
#spec_norm = np.mean(spec_temp)
#spec_temp /= spec_norm
# essentially the output of mkpointsourcecube
cube = (subimage[np.newaxis]*spec_temp[:,np.newaxis,np.newaxis]).astype(np.float32)
# photons/s/m^2/um
cube = intNorm*cube
#print "Cube sum = %.2e photons/s/m^2/um" % cube.sum()
#print "Cube mean = %.2e photons/s/m^2/um" % cube.mean()
if verb > 1: print
newcube = np.ones(cube.shape)
#print newcube.sum()
#print cube.shape
#print cube.size
if verb > 2:
# [electrons]
hdu = fits.PrimaryHDU(cube)
hdul = fits.HDUList([hdu])
hdul.writeto('cube.fits',clobber=True)
# convert the signal and the background into photons/s observed
# with TMT
observedCube = cube*collarea*efftot # photons/s/um
backtot = backtot*collarea*efftot # photons/s/um
# get photons/s per spectral channel, since each spectral
# channel has the same bandwidth
if verb > 1: print "Observed cube sum = %.2e photons/s/um" % observedCube.sum()
if verb > 1: print "Background cube sum = %.2e photons/s/um" % backtot.sum()
#print "Observed cube mean = %.2e photons/s/um" % observedCube.mean()
if verb > 1: print
observedCube = observedCube*(wave[1]-wave[0])
backtot = backtot*(wave[1]-wave[0])
if verb > 1: print "dL = %f micron" % (wave[1]-wave[0])
if verb > 1: print "Observed cube sum = %.2e photons/s" % observedCube.sum()
if verb > 1: print "Background cube sum = %.2e photons/s" % backtot.sum()
#print "Observed cube mean = %.2e photons/s" % observedCube.mean()
if verb > 1: print
##############
# filter curve
##############
# not needed until actual filters are known
#filterdata = np.loadtxt(filterfile)
#filterwav = filterdata[:,0] # micron
#filtertran = filterdata[:,1] # transmission [fraction]
#filter_norm = np.max(filtertran)
#print filter_norm
#filtertran /= filter_norm
#filter_func = interpolate.interp1d(filterwav,filtertran)
#filter_tput = filter_func(wave)
if verb > 1:
fig = plt.figure()
p = fig.add_subplot(111)
#p.plot(wave, filter_tput*cube[:,ys,xs])
p.plot(wave, cube[:,ys,xs],c="k")
p.plot(wave, np.sum(cube,axis=(1,2)),c="b")
plt.show()
if verb > 1:
print 'n wavelength channels: ', len(wave)
print 'channel width (micron): ', wave[1]-wave[0]
print 'mean flux input cube center (phot/s/m^2/micron): %.2e' % np.mean(cube[:, ys, xs])
print 'mean counts/spectral channel input cube center (phot/s): %.2e' % np.mean(observedCube[:, ys, xs])
print 'mean background (phot/s): ', np.mean(backtot)
#print "CORRECT ABOVE"
backgroundCube = np.broadcast_to(backtot[:,np.newaxis,np.newaxis],cube.shape)
#print backgroundCube
if verb > 1: print backgroundCube.shape
### Calculate total noise number of photons from detector
#darknoise = (sqrt(darkcurrent*itime)) * (1/sqrt(coadds))
#readnoise = sqrt(coadds)*readnoise
#darknoise = (sqrt(darkcurrent*itime))
darknoise = darkcurrent ## electrons/s
readnoise = readnoise**2.0/itime ## scale read noise
# total noise per pixel
# noisetot = sqrt((readnoise*readnoise) + (darknoise*darknoise))
noisetot = darknoise + readnoise
noise = noisetot
### Combine detector noise and background (sky+tel+AO)
#noisetotal = SQRT(noise*noise + background*background)
noisetotal = noise + backgroundCube
####################################################
# Case 1: find s/n for a given exposure time and mag
####################################################
if calc == "snr":
if verb > 1: print "Case 1: find S/N for a given exposure time and mag"
signal = observedCube*np.sqrt(itime*nframes) # photons/s
# make a background cube and add noise
# noise = sqrt(S + B + R^2/t)
#noiseCube = np.sqrt(observedCube+backgroundCube+darkcurrent+readnoise**2.0/itime)
noiseCube = np.sqrt(observedCube+noisetotal)
# SNR cube = S*sqrt(itime*nframes)/sqrt(S + B+ R^2/t)
##snrCube = observedCube*nframes*itime/rmsNoiseCube
#snrCube = observedCube*sqrt(itime*nframes)/noiseCube
#snrCube = float(snrCube)
snrCube = signal/noiseCube
if verb > 2:
hdu = fits.PrimaryHDU(snrCube)
hdul = fits.HDUList([hdu])
hdul.writeto('snrCube.fits',clobber=True)
peakSNR=""
medianSNR=""
meanSNR=""
medianSNRl=""
meanSNRl=""
minexptime=""
medianexptime=""
meanexptime=""
medianexptimel=""
meanexptimel=""
totalSNRl = "" # integrated aperture SNR at pre-defined fixed aperture
totalexptimel = "" # integrated aperture exptime at pre-defined fixed aperture
flatarray=np.ones(snrCube[0,:,:].shape)
if photutils.__version__ == "0.4":
maskimg= mask.multiply(flatarray)
masklimg= maskl.multiply(flatarray)
else:
maskimg= mask.apply(flatarray)
masklimg= maskl.apply(flatarray)
snr_cutout = []
snr_cutout_aper = []
snr_cutout_aperselect = []
snr_cutoutl = []
snr_cutout_aperl = []
snr_cutout_aperlselect = []
for n in xrange(dxspectrum):
snr_cutout.append(mask.cutout(snrCube[n,:,:]))
if photutils.__version__ == "0.4":
snr_cutout_tmp = mask.multiply(snrCube[n,:,:]) # in version 0.4 of photutils
snr_cutout_tmp_select=snr_cutout_tmp[np.where(maskimg>0)]
else:
snr_cutout_tmp = mask.apply(snrCube[n,:,:])
snr_cutout_tmp_select=snr_cutout_tmp[np.where(maskimg>0)]
snr_cutout_aper.append(snr_cutout_tmp)
snr_cutout_aperselect.append(snr_cutout_tmp_select)
for n in xrange(dxspectrum):
snr_cutoutl.append(maskl.cutout(snrCube[n,:,:]))
if photutils.__version__ == "0.4":
snr_cutout_tmp = maskl.multiply(snrCube[n,:,:]) # in version 0.4 of photutils
snr_cutout_tmp_select=snr_cutout_tmp[np.where(masklimg>0)]
else:
snr_cutout_tmp = maskl.apply(snrCube[n,:,:])
snr_cutout_tmp_select=snr_cutout_tmp[np.where(masklimg>0)]
snr_cutout_aperl.append(snr_cutout_tmp)
snr_cutout_aperlselect.append(snr_cutout_tmp_select)
#if verb > 0 and n == 0:
# fig = plt.figure()
# p = fig.add_subplot(111)
# p.imshow(snrCube[n,:,:],interpolation='none')
# plt.show()
snr_cutout = np.array(snr_cutout)
snr_cutout_aper = np.array(snr_cutout_aper)
snr_cutoutl = np.array(snr_cutoutl)
snr_cutout_aperl = np.array(snr_cutout_aperl)
snr_cutout_aperselect = np.array(snr_cutout_aperselect)
snr_cutout_aperlselect = np.array(snr_cutout_aperlselect)
if verb > 1: print snr_cutout.shape
if verb > 1: print snr_cutout_aper.shape
###########################
# summation of the aperture
###########################
data_cutout_aperl = []
noise_cutout_aperl = []
for n in xrange(dxspectrum):
if photutils.__version__ == "0.4":
data_cutout_tmp = maskl.multiply(signal[n,:,:]) # in version 0.4 of photutils
noise_cutout_tmp = maskl.multiply(noiseCube[n,:,:])
else:
data_cutout_tmp = maskl.apply(signal[n,:,:])
noise_cutout_tmp = maskl.apply(noiseCube[n,:,:])
data_cutout_aperl.append(data_cutout_tmp)
noise_cutout_aperl.append(noise_cutout_tmp)
data_cutout_aperl = np.array(data_cutout_aperl)
noise_cutout_aperl = np.array(noise_cutout_aperl)
###########################
# summation of the aperture
###########################
#aper_suml = data_cutout_aperl.sum()
#noise_suml = np.sqrt((noise_cutout_aperl**2).sum())
aper_sum_chl = np.sum(data_cutout_aperl,axis=(1,2)) # per channel
noise_sum_chl = np.sqrt(np.sum(noise_cutout_aperl**2,axis=(1,2))) # per channel
snr_chl = aper_sum_chl/noise_sum_chl
aper_suml = aper_sum_chl.sum()
noise_suml = np.sqrt((noise_sum_chl**2).sum())
snr_int = aper_suml/noise_suml
if verb > 1: print 'S/N (aperture = %.4f") = %.4f' % (sizel, snr_int)
#totalSNRl = str("%0.4f" % snr_int) # integrated aperture SNR at pre-defined fixed aperture
###############
# Main S/N plot
###############
if verb > 0:
fig = plt.figure()
p = fig.add_subplot(111)
#p.plot(wave, filter_tput*cube[:,ys,xs])
l1, = p.plot(wave, snr_chl, c="k", label="Total Flux [Aperture : "+"{:.3f}".format(sizel)+'"]')
############
# inset plot
############
#p2 = plt.axes([0.2, 0.6, 0.25, 0.25])
p2 = plt.axes([0.17, 0.2, 0.25, 0.25]) #0.625, 0.55
l2, = p2.plot(wave, snrCube[:,ys,xs],label="Peak Flux")
#p2.plot(wave, np.mean(snr_cutout_aper,axis=(1,2)),label='Mean Flux [Aperture : 0.2"]')
#p2.plot(wave, np.median(snr_cutout_aper,axis=(1,2)),label='Median Flux [Aperture : 0.2"]')
l3, = p2.plot(wave, np.mean(snr_cutout_aperlselect,axis=1),label="Mean Flux [Aperture : "+"{:.3f}".format(sizel)+'"]')
l4, = p2.plot(wave, np.median(snr_cutout_aperlselect,axis=1),label="Median Flux [Aperture : "+"{:.3f}".format(sizel)+'"]')
#leg = p.legend(loc=1,numpoints=1,prop={'size': 6})
leg = p.legend([l1,l2,l3,l4], ["Total Flux [Aperture : "+"{:.3f}".format(sizel)+'"]', "Peak Flux",
"Mean Flux [Aperture : "+"{:.3f}".format(sizel)+'"]',"Median Flux [Aperture : "+"{:.3f}".format(sizel)+'"]'],
loc=1,numpoints=1,prop={'size': 6})
p.set_xlabel("Wavelength ($\mu$m)")
p.set_ylabel("S/N")
#leg = p.legend(loc=1,numpoints=1,prop={'size': 6})
if png_output:
plt.tight_layout()
fig.savefig(png_output,dpi=200)
else:
plt.tight_layout()
plt.show()
if csv_output:
csvarr=np.array([wave,snrCube[:,ys,xs],np.median(snr_cutout_aperlselect,axis=1),np.mean(snr_cutout_aperlselect,axis=1),snr_chl]).T
np.savetxt(csv_output, csvarr, delimiter=',', header="Wavelength(microns),SNR_Peak,SNR_Median,SNR_Mean,SNR_Aperture_Total", comments="",fmt='%.4f')
#print data_cutout.shape
#print data_cutout_aper.shape
#;; save the SNR cube if given
#if n_elements(outcube) ne 0 then begin
# mkosiriscube, wave, transpose(snrCube, [2, 1, 0]), outcube, /micron, scale = scale, units = 'SNR', params = fitsParams, values = fitsValues
#endif
#return, snrCube
## total noise in photons
## rmsNoiseCube = sqrt(observedCube*itime*nframes + noiseCube*itime*nframes + darkcurrent*itime*nframes + readnoise^2.0*nframes)
### original code from Tuan, probably not correct
#rmsNoiseCube = (observedCube*itime*nframes + backgroundCube*itime*nframes + darkcurrent*itime*nframes + readnoise**2.0*nframes)
#simNoiseCube = np.random.poisson(lam=rmsNoiseCube, size=rmsNoiseCube.shape).astype("float64")
#totalObservedCube = observedCube*nframes*itime + simNoiseCube
#for ii = 0, s[3] - 1 do begin
# for jj = 0, s[2]-1 do begin
# for kk = 0, s[1]-1 do begin
# simNoiseCube[kk, jj, ii] = randomu(seed2, poisson = rmsNoiseCube[kk, jj, ii], /double)
# endfor
# endfor