-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcube_tools.py
More file actions
1463 lines (944 loc) · 49.3 KB
/
cube_tools.py
File metadata and controls
1463 lines (944 loc) · 49.3 KB
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
from astropy.io import fits
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt
from astropy.wcs import WCS
import warnings
from astropy.coordinates import SkyCoord
import astropy.units as u
import astropy.stats as S
import os
import lmfit as LM
import scipy.constants as const
from stellarpops.tools import fspTools as FT
#import plotting as P
def twoD_Gaussian_list(position, amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
(x, y) = position
xo = float(xo)
yo = float(yo)
a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
g = offset + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo)
+ c*((y-yo)**2)))
return g.ravel()
def twoD_Gaussian_with_slope(params, X, Y):
"""
Adapted from https://stackoverflow.com/questions/21566379/fitting-a-2d-gaussian-function-using-scipy-optimize-curve-fit-valueerror-and-m/21566831
"""
xo = params['X']
yo = params['Y']
theta = params['ROTATION']
sigma_x = params['XWIDTH']
sigma_y = params['YWIDTH']
offset = params['OFFSET']
amplitude = params['Amp']
slope_X = params['X_GRAD']
slope_Y = params['Y_GRAD']
a = (np.cos(theta)**2)/(2*sigma_y**2) + (np.sin(theta)**2)/(2*sigma_x**2)
b = -(np.sin(2*theta))/(4*sigma_y**2) + (np.sin(2*theta))/(4*sigma_x**2)
c = (np.sin(theta)**2)/(2*sigma_y**2) + (np.cos(theta)**2)/(2*sigma_x**2)
g = offset + slope_X*X +slope_Y*Y + amplitude*np.exp( - (a*((X-xo)**2) + 2*b*(X-xo)*(Y-yo)
+ c*((Y-yo)**2)))
return g
def twoD_Gaussian(params, X, Y):
xo = params['X']
yo = params['Y']
theta = params['ROTATION']
sigma_x = params['XWIDTH']
sigma_y = params['YWIDTH']
offset = params['OFFSET']
amplitude = params['Amp']
a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
g = offset + amplitude*np.exp( - (a*((X-xo)**2) + 2*b*(X-xo)*(Y-yo)
+ c*((Y-yo)**2)))
return g
def moments(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution by calculating its
moments """
total = np.nansum(np.abs(data))
Y, X = np.indices(data.shape)
x = np.nansum((X*np.abs(data)))/total
y = np.nansum((Y*np.abs(data)))/total
# col = data[:, int(y)]
# width_x = np.sqrt(np.nansum(np.abs((np.arange(col.size)-y)**2*col))/np.nansum(col))
# row = data[int(x), :]
# width_y = np.sqrt(np.nansum(np.abs((np.arange(row.size)-x)**2*row))/np.nansum(row))
height = np.nanmax(data)
theta=np.pi/2.0
offset=np.nanmedian(data[data!=0.0])
width_x=2.0
width_y=2.0
slope_X=0.0
slope_Y=0.0
return height, x, y, width_x, width_y, theta, offset
class Cube(object):
def __init__(self, cube_filename, extension=1, object_name=None, noise_cube=None, is_sim=False):
"""
A Cube class for working with (primarily) KMOS cubes.
Arguments:
cube_filename: string. Filename of a 3D data cube.
extension. Int. Which extension is the cube data in? Default is 1, since all KMOS cubes have their data in the 1 extension (not the first, 0th extension).
object_name. String. Name of the object in the cube, used for plotting. Default is None, in which case we try and get it from the header.
noise_cube. 3D numpy array. Array containing the noise cube. If None, assume we're dealing with a KMOS cube and use the cube in the (extension+1)th hdu extension
is_sim. Bool. Is the cube a simulated cube rather than a real observation? If so, don't try and look up things which aren't in the data tables
Notes:
Assumes the noise cube is a separate extension of
"""
self.filename=cube_filename
self.hdu=fits.open(cube_filename)
self.data=self.hdu[extension].data
self.pri_header=self.hdu[0].header
self.header=self.hdu[extension].header
#WCS information
if not is_sim:
self.wcs=WCS(self.header)
self.wcs2d=self.wcs.celestial
#Noise Cube
if noise_cube is None:
self.noise=self.hdu[extension+1].data
else:
self.noise=noise_cube
#Try getting the units of the cube. If that fails, just use counts
try:
self.flux_unit=self.header['HIERARCH ESO QC CUBE_UNIT']
except:
self.flux_unit='Counts'
if not is_sim:
if object_name is None:
self.object_name=self.pri_header['HIERARCH ESO PRO REFLEX SUFFIX']
if is_sim:
self.Ha_flag=True
self.continuum_flag=True
self.z=self.header['specz']
self.Ha_lam=(1+self.z)*0.656281
elif not 'ARMSTAR' in self.object_name.upper():
data=self.get_KMOS_fits_data(self.object_name)
if data is not None:
self.Ha_flag=bool(data['line_detection'])
self.continuum_flag=bool(data['detected'])
self.cluster=data['cluster']
#self.quadrant=data['Quadrant']
#self.skysub_method=data['SkySub']
#self.cubecomments=data['Comment']
self.table=data
if self.Ha_flag:
self.z=float(data['specz'])
self.Ha_lam=(1+self.z)*0.65628
else:
warnings.warn("No emission found to get an accurate z. Setting z=0.0")
self.z=0.0
else:
raise NameError("No data found for {}".format(self.object_name))
else:
self.z=0.0
warnings.warn("No spectroscopic data for an arm star. Setting z=0.0")
# #Get the IFU arm, if we have it:
# try:
# self.arm=get_KMOS_arm_number(self.object_name)
# except KeyError:
# warnings.warn("No Arm data found for {}".format(self.object_name))
#Get the number of dimensions. Should be 3
self.ndims=self.header['NAXIS']
assert self.ndims == 3, 'This Class is for dealing with cubes! Check we have 3 dimensions (or maybe the header is wrong)'
#Get the wavelength axis
if self.header['CTYPE1'] == 'WAVE':
self.lam_axis=2
self.nlam=self.header['NAXIS1']
self.nx=self.header['NAXIS2']
self.ny=self.header['NAXIS3']
self.lamdas=self.header['CRVAL1']+(np.arange(self.header['NAXIS1'])-self.header['CRPIX1'])*self.header['CDELT1']
self.lam_unit=self.header['CUNIT1']
#Rotate the cube so the wavelength axis is first.
self.lam_axis=0
print('Rolling the cube so the wavelength axis is first')
self.data=np.rollaxis(self.data, 2, 0)
elif self.header['CTYPE2'] == 'WAVE':
self.nlam=self.header['NAXIS2']
self.nx=self.header['NAXIS1']
self.ny=self.header['NAXIS3']
self.lamdas=self.header['CRVAL2']+(np.arange(self.header['NAXIS2'])-self.header['CRPIX2'])*self.header['CDELT2']
self.lam_unit=self.header['CUNIT2']
#Rotate the cube so the wavelength axis is first.
self.lam_axis=0
print('Rolling the cube so the wavelength axis is first')
self.data=np.rollaxis(self.data, 1, 0)
elif self.header['CTYPE3'] == 'WAVE':
self.lam_axis=0
self.nlam=self.header['NAXIS3']
self.nx=self.header['NAXIS1']
self.ny=self.header['NAXIS2']
self.lamdas=self.header['CRVAL3']+(np.arange(self.header['NAXIS3'])-self.header['CRPIX3'])*self.header['CDELT3']
self.lam_unit=self.header['CUNIT3']
else:
raise NameError("Can't find Wavelength axis")
#make a quick spectrum by median-combining the whole cube
self.quick_spec=np.nanmedian(np.nanmedian(self.data, axis=2), axis=1)
#Set the pixel scale
self.pix_scale=float(self.pri_header['HIERARCH ESO PRO REC1 PARAM8 VALUE'])
#The cube hasn't been collapsed yet
self.collapsed=None
self.has_been_collapsed=False
# @staticmethod
# def get_KMOS_csv_data(object_name):
# data=np.genfromtxt(os.path.expanduser('~/z/Data/KCLASH/KCLASH_cube_data.csv'), delimiter=',', dtype=str, skip_header=1, autostrip=True)
# galaxies=list(data[:, 0])
# obj_index=galaxies.index(object_name)
# return data[obj_index, :]
@staticmethod
def get_KMOS_fits_data(object_name):
from astropy.table import Table
import pandas as pd
dat=Table.read(os.path.expanduser('~/z/Data/KCLASH/KCLASH_data_V4.4_GalacticRedenning.fits'), format='fits')
df=dat.to_pandas()
if isinstance(df.name.iloc[0], bytes):
names=df['name'].str.decode("utf-8")
names=names.str.strip()
elif isinstance(df.name.iloc[0], str):
names=df.name.values
names=names.str.strip().iloc[0]
else:
raise TypeError('What type is names? Neither bytes nor string!')
#names = df.apply(lambda x: x.str.decode("utf-8") if x.dtype == "object" else x)['name'].values
index=pd.Index(names)
df=df.set_index(index)
return df.loc[object_name]
# mask=data['Galaxy Name']==object_name
# n_results=len(np.where(mask==True)[0])
# if n_results==1:
# return data[mask]
# else:
# warnings.warn('Found {} entries for {}'.format(n_results, object_name))
# return None
@staticmethod
def get_all_KMOS_fits_data(fname=os.path.expanduser('~/z/Data/KCLASH/KCLASH_data_V4.4_GalacticRedenning.fits')):
from astropy.table import Table
import pandas as pd
dat=Table.read(fname, format='fits')
df=dat.to_pandas()
names = df.apply(lambda x: x.str.strip() if x.dtype == "object" else x)['name'].values
index=pd.Index(names)
df=df.set_index(index)
return df
@staticmethod
def get_KMOS_arm_number(object_name):
arm_dict={
'MACS1931_bluefield_50044' : 1 ,
'MACS1931_bluefield_41168' : 10,
'MACS1931_blueclust_42661' : 11,
'MACS1931_blueclust_36441' : 12,
'ARMSTAR401' : 13,
'MACS1931_redclust_43187' : 14,
'MACS1931_bluefield_44837' : 15,
'MACS1931_bluefield_45168' : 16,
'MACS1931_redclust_40753' : 17,
'ARMSTAR423' : 18,
'MACS1931_blueclust_40782' : 19,
'MACS1931_redclust_58042' : 2 ,
'MACS1931_bluefield_43122' : 20,
'MACS1931_blueclust_46452' : 21,
'MACS_1931_ARM22_SCI' : 22,
'MACS_1931_ARM23_SCI' : 23,
'MACS1931_redclust_55075' : 24,
'MACS1931_bluefield_53332' : 3 ,
'MACS1931_blueclust_52577' : 4 ,
'MACS1931_BCG_59407' : 5 ,
'MACS1931_blueclust_48927' : 6 ,
'MACS1931_bluefield_51071' : 7 ,
'ARMSTAR382' : 8 ,
'MACS1931_bluefield_46041' : 9
}
return arm_dict[object_name]
def collapse(self, wavelength_mask=None, collapse_func=np.nansum, plot=False, plot_args={}, savename=None, save_args={}):
"""
Collapse a cube along the wavelength axis, according to the function collapse_func.
Arguments:
collapse_func: function. Function to use to do the collapsing. Normally np.nanmedian or np.nansum.
plot: Bool. If true, plot the resulting collapsed cube.
plot_args: Dict. Extra arguments to pass to plot_collapsed_cube
savename: String or None. If string, pass to save_collapsed_cube with that filename. If None, don't save
save_args: Dict. Extra args to pass to save_collapsed_cube.
"""
if wavelength_mask is not None:
im=collapse_func(self.data[wavelength_mask, :, :], axis=self.lam_axis)
else:
im=collapse_func(self.data, axis=self.lam_axis)
if plot:
fig, ax=self.plot_collapsed_cube(savename=savename, **plot_args)
return fig, ax
if savename is not None:
raise ValueError('Code not yet written!!')
self.has_been_collapsed=True
self.collapsed=im
return im
def plot_collapsed_cube(self, fig=None, ax=None, savename=None, **kwargs):
if ax is None or ax is None:
fig, ax=plt.subplots(figsize=(10, 10))
#vmin = kwargs.pop('vmin', 0.0)
vmax = kwargs.pop('vmax', 0.98*np.nanmax(self.collapsed))
im=ax.imshow(self.collapsed, aspect='auto', origin='lower',vmax=vmax, **kwargs)
fig.colorbar(im, ax=ax, label='{}'.format(self.flux_unit))
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('{}'.format(self.object_name))
if savename is not None:
fig.savefig(savename)
return fig, ax
def get_emission_lines(self, z):
###
#Get all emission lines within the cube
#Taken and modified from ppxf_utils.py (Thanks Michele!)
# Balmer Series: Hdelta Hgamma Hbeta Halpha
line_wave = np.array([4101.76, 4340.47, 4861.33, 6562.80])/(10.0**4) # air wavelengths
line_names = np.array(['Hdelta', 'Hgamma', 'Hbeta', 'Halpha'])
# -----[OII]----- -----[SII]-----
lines = np.array([3726.03, 3728.82, 6716.47, 6730.85])/(10.0**4) # air wavelengths
names = np.array(['[OII]3726', '[OII]3729', '[SII]6716', '[SII]6731'])
line_names = np.append(line_names, names)
line_wave = np.append(line_wave, lines)
# To keep the flux ratio of a doublet fixed, we place the two lines in a single template
# -----[OIII]-----
lines = np.array([4958.92, 5006.84])/(10.0**4) # air wavelengths
line_names = np.append(line_names, '[OIII]5007d') # single template for this doublet
line_wave = np.append(line_wave, lines[1])
# To keep the flux ratio of a doublet fixed, we place the two lines in a single template
# -----[OI]-----
lines = np.array([6300.30, 6363.67])/(10.0**4) # air wavelengths
line_names = np.append(line_names, ['[OI]6300d', '[OI]6300d']) # single template for this doublet
line_wave = np.append(line_wave, lines)
# To keep the flux ratio of a doublet fixed, we place the two lines in a single template
# -----[NII]-----
lines = np.array([6548.03, 6583.41])/(10.0**4) # air wavelengths
line_names = np.append(line_names, ['[NII]6583d', '[NII]6583d']) # single template for this doublet
line_wave = np.append(line_wave, lines)
# Only include lines falling within the cube wavelength range.
line_wave*=(1+z)
w = (line_wave > self.lamdas[0]) & (line_wave < self.lamdas[-1])
line_names = line_names[w]
line_wave = line_wave[w]
return line_names, line_wave
def get_continuum_mask(self, z, line_width=50.0/(10**4), mask_skylines=False):
"""
Get a wavelength mask which avoids all emission lines and the worst skylines
"""
line_names, line_wave=self.get_emission_lines(z)
mask=np.ones_like(self.lamdas, dtype=bool)
for line in line_wave:
m=~((self.lamdas > (line-line_width/2.0)) & (self.lamdas < (line+line_width/2.0)))
mask=mask & m
#Avoid the last pixels which are often bad
mask[1950:]=False
if mask_skylines:
#Avoid skylines. Needs work
#At a skyline, the gradient sharply changs from positive to negative
#If we sigma_clip the gradient and keep the outliers, we find where the worse skylines are
clipped=S.sigma_clip(np.gradient(self.quick_spec), sigma=5, iters=3)
mask=mask & ~ clipped.mask
return mask
def plot_continuum_map(self, z, plot_args={}, savename=None, line_width=50.0/(10**4)):
"""
Make a map of the Continuum Emission in a cube. This collapses the cube along the wavelength axis, but masks strong skylines and emission lines
Arguments:
self
z: float. The redshift of the cube (for masking emission lines)
linewidth: float. *Total* width around the line centre to mask out (i.e we mask out centre-(width/2) to centre+(width/2) ). Note this is in the same units as the cube (so usually microns for KMOS cubes).
plot_args: Dictionary. Passes to plot_collapsed_cube
"""
mask=self.get_continuum_mask(z, line_width)
fig, ax=self.collapse(wavelength_mask=mask, plot=True, plot_args=plot_args, savename=savename)
title=ax.get_title()
ax.set_title('{}: Continuum Map'.format(title))
return fig, ax
def get_spec_mask_around_wave(self, wave, width):
"""
Mask a spectrum around a certain OBSERVED wavelength. Length of mask is defined by width. Width is in microns
"""
m=((self.lamdas > (wave-width/2.0)) & (self.lamdas < (wave+width/2.0)))
return m
def get_cube_mask_around_wave(self, wave, width):
"""
Mask an entire cube around a certain wavelength
"""
m=self.get_spec_mask_around_wave(wave, width)
cube_mask=np.repeat(m, self.nx*self.ny).reshape(-1, self.nx, self.ny)
return cube_mask
def mask_cube_around_wave(self, wave, width):
"""
Apply get_cube_mask_around_wave to a cube and noise cube
"""
cube_mask=self.get_cube_mask_around_wave(wave, width)
return self.data*cube_mask, self.noise*cube_mask
def plot_line_map(self, z, line_name, line_width=50.0/(10**4), plot_args={}, savename=None, show_spec=False):
line_names, line_wave=self.get_emission_lines(z)
assert line_name in line_names, 'Pick a line from here: {}'.format(line_names)
#Select the desired line from the names
#If we have a doublet then we'll get two wavelengths back
wavelengths=line_wave[line_names==line_name]
mask=np.zeros_like(self.lamdas, dtype=bool)
for line in wavelengths:
m=self.get_spec_mask_around_wave(line, line_width)
mask=mask | m
#Plot the quick spectrum, showing the lines we're mapping
if show_spec == True:
fig=plt.figure(figsize=(12, 10))
#Make a gridspec. Want the height ratios such that the main image is larger than the spectrum
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1])
#Add the axes.
ax_linemap = plt.subplot(gs[0, 0])
ax_spec = plt.subplot(gs[1, 0])
plot_args['fig']=fig
plot_args['ax']=ax_linemap
fig, ax_linemap=self.collapse(wavelength_mask=mask, plot=True, plot_args=plot_args, savename=None)
#Plot the whole spectrum in grey, then just the linemap region in red
ax_spec.plot(self.lamdas, self.quick_spec, c='k', alpha=0.5, linewidth=2)
ax_spec.plot(self.lamdas[mask], self.quick_spec[mask], c='r', alpha=1.0, linewidth=2)
ax_spec.set_title('Median spec')
ax_spec.set_xlabel(r'$\lambda$ ($\mu$m)')
if savename is not None:
fig.savefig(savename)
return fig, [ax_linemap, ax_spec]
else:
fig, ax=self.collapse(wavelength_mask=mask, plot=True, plot_args=plot_args, savename=savename)
title=ax.get_title()
ax.set_title('{}: Line map around {}'.format(title, line_name))
return fig, ax
def plot_all_lines(self, z, line_width=50.0/(10**4), plot_args={}, savename=None):
"""
Plot all the lines within the wavelength range of the cube, and a continuum map. Just calls plot_line_map many times, with
plot_continuum_line at the end. Assumes that we have less than 5 lines! Otherwise we'd need to think of a better way to set up the axes
"""
line_names, line_wave=self.get_emission_lines(z)
#Get rid of duplicate names (i.e of the line doublets) but preserve the order of the labels
from collections import OrderedDict
names=list(OrderedDict.fromkeys(line_names))
assert len(names) <=7, 'Change the code to include more than 5 emission lines!'
if len(names) <=5:
fig, axs=plt.subplots(nrows=2, ncols=3, figsize=(24, 12))
for name, ax in zip(names, axs.flatten()):
fig, ax=self.plot_line_map(z, name, line_width=50.0/(10**4), plot_args={'fig':fig, 'ax':ax}, show_spec=False)
ax.set_title('{}'.format(name))
ax.axis('off')
elif 5 < len(names) <=7:
fig, axs=plt.subplots(nrows=2, ncols=4, figsize=(24, 12))
for name, ax in zip(names, axs.flatten()):
fig, ax=self.plot_line_map(z, name, line_width=50.0/(10**4), plot_args={'fig':fig, 'ax':ax}, show_spec=False)
ax.set_title('{}'.format(name))
ax.axis('off')
#Fill the last cube with a continuum map
fig, ax=self.plot_continuum_map(z, line_width=50.0/(10**4), plot_args={'fig':fig, 'ax':axs.flatten()[-1]})
ax.set_title('Continuum Map')
ax.axis('off')
fig.suptitle('{}'.format(self.object_name), fontsize=24)
if savename is not None:
fig.savefig(savename)
return fig, axs
def unwrap(self, plot=False, plot_args={}, savename=None, save_args={}):
"""
Unwrap a cube to make a 2D representation, to easily find emission lines.
Arguments:
self
plot: Bool. If true, plot the resulting unwrapped cube.
plot_args: Dict. Extra arguments to pass to plot_unwrapped_cube
savename: String or None. If string, pass to save_unwrapped_cube with that filename. If None, don't save
save_args: Dict. Extra args to pass to save_unwrapped_cube.
"""
self.unwrapped=self.data.reshape(self.nlam, -1).T
if plot:
self.plot_unwrapped_cube(**plot_args)
if savename is not None:
self.save_unwrapped_cube(savename, **save_args)
def plot_unwrapped_cube(self, fig=None, ax=None, savename=None, n_median=5.0, show_plot=True, **kwargs):
"""
Plot an unwrapped cube, with vmin and vmax being 0.0 and 5.0 times the median value of the cube. I find that this gives nice results for the resulting image.
Arguments:
fig: a matplotlib figure. Default is none, in which case we plot on a new figure.
ax: a matplotlib axes. Default is none, in which case we plot on a new axis
save: string or None. If string, save the image to that filename. If None, don't save.
n_median: float. Vmax is n_median*median value of the array.
**kwargs: extra args to pass to imshow
"""
if ax is None or ax is None:
fig, ax=plt.subplots(figsize=(18, 4))
zero_mask=self.unwrapped!=0.0
median_value=np.abs(np.nanmedian(self.unwrapped[zero_mask]))
im=ax.imshow(self.unwrapped, vmin=-1.0*median_value, vmax=n_median*median_value, extent=[self.lamdas[0], self.lamdas[-1], self.unwrapped.shape[0], 0], aspect='auto', **kwargs)
fig.colorbar(im, ax=ax, label='{}'.format(self.flux_unit))
ax.set_xlabel(r'$\lambda$ ({})'.format(self.lam_unit))
ax.set_ylabel('Spectrum Number')
ax.set_title('{}'.format(self.object_name))
import matplotlib.ticker as ticker
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.01))
ax.tick_params(which='major', length=7)
ax.tick_params(which='minor', length=4)
#ax.set_xticks(np.linspace())
if savename is not None:
fig.savefig(savename)
return fig, ax
def save_unwrapped_cube(self, savename, **kwargs):
"""
Save an unwrapped cube to a filename, with an updated header.
Args:
self
savename: the filename to save the cube to.
**kwargs: extra args to pass to hdu.writeto (e.g clobber)
"""
save_hdr=self.pri_header.copy()
save_hdr.set("CRVAL1",self.lamdas[0])
save_hdr.set("CRPIX1",1)
save_hdr.set("CDELT1",self.lamdas[1]-self.lamdas[0])
save_hdr.set("CTYPE1","LINEAR")
save_hdr.set("DC-FLAG",0)
save_hdr.set("OBJECT", self.object_name)
hdu=fits.PrimaryHDU(self.unwrapped)
hdu.header=save_hdr
hdu.writeto(savename, **kwargs)
def fit_gaussian(self, fit_funct=twoD_Gaussian, im=None, method='leastsq', clip=False):
"""
Fit a Gaussian to a 2D collapsed cube using lmfit
"""
if im is None:
if self.collapsed is not None:
im=self.collapsed
else:
self.collapse()
im=self.collapsed
xmin=2
xmax=-2
ymin=2
ymax=-2
image=im.copy()[xmin:xmax, ymin:ymax]
errors=np.sqrt(np.nansum(self.noise[:, xmin:xmax, ymin:ymax]**2, axis=0))
errors[errors<=0.0]=100
Y, X = np.indices(image.shape)
#Tidy up the image so we have no infs or nans
image[~np.isfinite(image)]=0.0
#FIXME
#Not sure this is going to work properly...
#errors[image<=0.0]=100
#image[image<0.0]=0.0
if clip:
clipped_img=S.sigma_clip(image, sigma_lower=2.0, sigma_upper=3.0, iters=3)
image=clipped_img.filled(0.0)
#Initial Guess. Use the maxval of the image for the Gaussian height. Maybe use mean instead?
#Best guess is centre, with sigma of 2 in each direction. Theta is 0.0 and so is the overall y offset
#Normalise things to avoid having some parameters at 1e-20 and others at 1
median=np.abs(np.median(image[image!=0.0]))
medianed_image=image/median
medianed_errors=errors/median
initial_guess=moments(image)
params=LM.Parameters()
params.add('Amp', value=initial_guess[0]/median, min=1e-3)
params.add('X', value=initial_guess[2], min=0.5, max=image.shape[1]-0.5)
params.add('Y', value=initial_guess[1], min=0.5, max=image.shape[0]-0.5)
params.add('XWIDTH', value=initial_guess[3], min=0.1, max=6.0)
params.add('YWIDTH', value=initial_guess[4], min=0.1, max=6.0)
params.add('ROTATION', value=initial_guess[5], min=0.0, max=2*np.pi)
params.add('OFFSET', value=initial_guess[6]/median)
params.add('X_GRAD', value=0.0)
params.add('Y_GRAD', value=0.0)
def lmfitfun(p, data, err, X, Y):
return (data.ravel()-twoD_Gaussian_with_slope(p, X, Y).ravel())/err.ravel()
minimiser = LM.Minimizer(lmfitfun, params, fcn_args=(medianed_image, medianed_errors, X, Y))
result = minimiser.minimize(method=method)
# try:
# popt, pcov = opt.curve_fit(fit_funct, (X, Y), image.ravel(), sigma=errors.ravel(), p0=initial_guess)
# except:
# popt=None
#Deal with the amount of the cube we clipped off:
result.params['X'].set(value=result.params['X']+xmin, min=0.0, max=image.shape[1])
result.params['Y'].set(value=result.params['Y']+ymin, min=0.0, max=image.shape[0])
return image, errors, minimiser, result
def get_continuum_centre(self, fit_funct=twoD_Gaussian, plot=True, savename=None, verbose=False, fig=None, ax=None, clip=False, return_full=False, fit_args={}, plot_collapsed_cube_args={}, contour_args={}):
"""
Fit a guassian to a collapsed cube and get the x, y coordinates of the centre.
"""
image, errors, minimiser, result=self.fit_gaussian(fit_funct=fit_funct, clip=clip)
ret=[result]
if plot:
if fig is None or ax is None:
fig, ax=plt.subplots(figsize=(10, 10))
fig, ax=self.plot_collapsed_cube(fig=fig, ax=ax, **plot_collapsed_cube_args)
Y, X = np.indices(self.collapsed.shape)
best_gaussian=twoD_Gaussian(result.params, X, Y)
ax.contour(X, Y, best_gaussian, linewidth=1.0, colors='r', **contour_args)
ax.set_title(r"{}: $X={:.2f}$, $Y={:.2f}$".format(ax.get_title(), result.params['X'].value, result.params['Y'].value))
if savename is not None:
fig.savefig(savename)
ret.append((fig, ax))
if verbose:
print("\nObject: {}".format(self.object_name))
print("Best Fitting Gaussian:")
print("\t(x, y)={:.2f}, {:.2f}".format(result.params['X'].value, result.params['Y'].value))
LM.report_fit(result)
if return_full:
ret.append((image, errors, minimiser))
if len(ret)>1:
ret=tuple(ret)
else:
ret=ret[0]
return ret
def get_PSF(self, fit_funct=twoD_Gaussian, plot=True, savename=None, verbose=True, fig=None, ax=None, clip=False, plot_collapsed_cube_args={}, contour_args={}):
"""
Get the PSF of a cube containing an arm star. Use cube.fit_gaussian to fit a 2D gaussian, then use that to get the average seeing (from get_av_seeing)
and return the average seeing and the optimal gaussian parameters.
Can plot if necessary and print results.
"""
if not self.has_been_collapsed:
self.collapse()
image, errors, minimiser, result=self.fit_gaussian(fit_funct=fit_funct, clip=clip)
Y, X = np.indices(self.collapsed.shape)
best_gaussian=twoD_Gaussian_with_slope(result.params, X, Y)
average_seeing=self.get_av_seeing(result)
if verbose:
print("\nObject: {}".format(self.object_name))
print("Best Fitting Gaussian:")
print("\t(x, y)={:.2f}, {:.2f}".format(result.params['X'].value, result.params['Y'].value))
print("\tsigma_x={:.3f}, sigma_y={:.3f}".format(result.params['XWIDTH'].value, result.params['YWIDTH'].value))
print('\ttheta={:.3f}, amplitude={:.3f}'.format(result.params['ROTATION'].value, result.params['Amp'].value))
print('\toffset={:.3f}, x_gradient={:.3f}, y_gradient={:.3f}'.format(result.params['OFFSET'].value, result.params['X_GRAD'].value, result.params['Y_GRAD'].value))
print('\tReconstructed seeing: {:.3f}"'.format(average_seeing))
if plot:
if fig is None or ax is None:
fig, ax=plt.subplots(figsize=(10, 10))
fig, ax=self.plot_collapsed_cube(fig=fig, ax=ax, **plot_collapsed_cube_args)
levels=np.array([0.2, 0.4, 0.6, 0.8, 0.95])*np.max(best_gaussian)
ax.contour(X, Y, best_gaussian.reshape(self.ny, self.nx), levels=levels, linewidth=2.0, colors='w', origin='lower', **contour_args)
ax.set_title(r"{}: Seeing={:.3f}$^{{{{\prime\prime}}}}$, $\sigma_{{x}}={:.2f}$, $\sigma_{{y}}={:.2f}$".format(ax.get_title(), average_seeing, result.params['XWIDTH'].value, result.params['YWIDTH'].value))
ax.set_aspect('equal')
if savename is not None:
fig.savefig(savename)
return average_seeing, result, (fig, ax)
return average_seeing, result
def get_av_seeing(self, result, pix_scale=None):
"""
Get average seeing in x and y directions from fitting a gaussian to a point source.
Take sqrt(sigma_x**2+sigma_y**2) of the best fitting Gaussian and multiply by the pixel scale.
"""
pix_scale=self.pix_scale
return pix_scale*np.sqrt(result.params['XWIDTH'].value**2+result.params['YWIDTH'].value**2)
def interpolate_point_1_arcsec_sampling(self):
"""
Interpolate a cube to go from 0.2" spaxels to 0.1" spaxels, ensuring the flux in each wavelength slice is the same.
This assumes the spatial sampling is already 0.2"! And we just want to halve that.
This works IN PLACE! So it overwrites cube.data, cube.noise and cube.nx, cube.ny.
"""
if self.pix_scale == 0.2:
import scipy.interpolate as si
x=np.arange(self.nx)
y=np.arange(self.ny)
x_new=np.arange(0, self.nx, 0.5)
y_new=np.arange(0, self.ny, 0.5)
interp=si.RegularGridInterpolator((self.lamdas, y, x), self.data, bounds_error=False, fill_value=np.nan)
noise_interp=si.RegularGridInterpolator((self.lamdas, y, x), self.noise, bounds_error=False, fill_value=np.nan)
new_points = np.meshgrid(self.lamdas, y_new, x_new, indexing='ij')
flat = np.array([m.flatten() for m in new_points])
out_array = interp(flat.T)
new_cube = out_array.reshape(*new_points[0].shape)
out_noise = noise_interp(flat.T)
new_noise = out_noise.reshape(*new_points[0].shape)
"""This does terrible things to the spectra!"""
#Ensure the flux in each wavelength slice is the same
# old_flux=np.nanmedian(np.nanmedian(self.data, axis=2), axis=1)
# new_flux=np.nanmedian(np.nanmedian(new_cube, axis=2), axis=1)
# old_noise_values=np.nanmedian(np.nanmedian(self.noise, axis=2), axis=1)
# new_noise_values=np.nanmedian(np.nanmedian(new_noise, axis=2), axis=1)
# flux_ratio=old_flux/new_flux
# noise_ratio=old_noise_values/new_noise_values
# flux_ratio[~np.isfinite(flux_ratio)]=1.0
# noise_ratio[~np.isfinite(noise_ratio)]=1.0
# flux_ratio_cube=np.repeat(flux_ratio, x_new.shape[0]*y_new.shape[0]).reshape(-1, y_new.shape[0], x_new.shape[0])
# noise_ratio_cube=np.repeat(noise_ratio, x_new.shape[0]*y_new.shape[0]).reshape(-1, y_new.shape[0], x_new.shape[0])
flux_ratio_cube=np.ones_like(new_cube)
noise_ratio_cube=np.ones_like(new_noise)
self.data=new_cube*flux_ratio_cube
self.noise=new_noise*noise_ratio_cube
self.nx=x_new.shape[0]
self.ny=y_new.shape[0]
self.pix_scale=0.1
return new_cube*flux_ratio_cube, new_noise*noise_ratio_cube
else:
warnings.warn('Pixel scale is {}, so cannot interpolate!'.format(self.pix_scale))
def get_north_east_arrow(wcs):
"""
Returns the (unit vectors) dx and dy of an arrow pointing North, as defined from a WCS instance
"""
#Check the wcs we pass is celestial
if not wcs.is_celestial:
raise TypeError("Must pass a celestial WCS instance")
cd11=wcs.wcs.cd[0, 0]
cd12=wcs.wcs.cd[0, 1]
cd21=wcs.wcs.cd[1, 0]
cd22=wcs.wcs.cd[1, 1]