-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpsp2d.py
executable file
·215 lines (181 loc) · 6.33 KB
/
psp2d.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
#!/usr/bin/python
# -*- coding: latin-1 -*-
"""
Description
-----------
`pysynphot` has the `ArraySpectrum` and `Observation` classes to handle 1D spectra.
This class accepts 2D flux arrays (thus the names `ArraySpectra` and `Observations`)
and vectorizes all `ArraySpectrum` and `Observation` attribute calls.
Authors
-------
Joe Filippazzo, 2017-12-21
"""
import numpy as np
import pysynphot as ps
import matplotlib.pyplot as plt
class ArraySpectra(object):
"""
This is a wrapper class for pysynphot.ArraySpectrum() so it can handle ND spectra
"""
def __init__(self, wave, flux, **kwargs):
"""
Initialize the object
Parameters
----------
wave: sequence
The wavelength array
flux:
The flux cube
Example
-------
import os
import ExoCTK
import pysynphot2d
grid = ExoCTK.core.ModelGrid(os.environ['MODELGRID_DIR'], resolution=100, Teff_rng=(3400,3500), logg_rng=(4.5,5.5), FeH_rng=(0,0), wave_rng=(0.8,2.5))
model = grid.get(3500, 5, 0)
model['wave'] *= 10000
spec2D = pysynphot2d.psp2d.ArraySpectra(**model)
"""
# Create object for each 1D spectrum
self.spectra = [ps.ArraySpectrum(wave, f, name=n) for n,f in enumerate(flux)]
# Store other inputs as attributes
for key, value in kwargs.items():
setattr(self, key, value)
def __getattribute__(self, attr):
"""
Redefining the getattribute call to iterate over the list of 1D spectra
Parameters
----------
attr: str
The attribute to call
Returns
-------
np.ndarray
An array of the results
"""
# Try to get the attribute from the parent object
try:
return super().__getattribute__(attr)
# If that fails, check the child object
except AttributeError:
# If it is a method...
if callable(getattr(self.spectra[0], attr)):
results = lambda *args, **kwargs: self._vec_attr(attr, *args, **kwargs)
# ... or just an attribute
else:
results = np.array([getattr(data1D, attr) for data1D in self.spectra])
return results
def _vec_attr(self, attr, *args, **kwargs):
"""
Iterate over the 1D spectra
Parameters
----------
attr: str
The attribute to call
Returns
-------
np.ndarray
The vectorized results
"""
return np.array([getattr(data1D, attr)(*args, **kwargs) for data1D in self.spectra])
def plot(self, idx, param=''):
"""
Plot the spectrum
Parameters
----------
idx: int
The index of the spectrum to plot
param: str
The name of the parameter to print
"""
obs = self.spectra[idx]
if param:
p = getattr(self, param)
plt.plot(obs.wave, obs.flux, label='{} @ {} = {}'.format(obs.name,param,p[idx]))
else:
plt.plot(obs.wave, obs.flux, label=obs.name)
plt.xlabel(obs.waveunits)
plt.ylabel(obs.fluxunits)
plt.legend(loc=0)
class Observations(object):
"""
This is a wrapper class for pysynphot.Observtion() so it can handle ND spectra
"""
def __init__(self, spec2D, band, **kwargs):
"""
Initialize the object
Parameters
----------
spec2D: ArraySpectra
The 2D spectra
band: ps.spectrum.SpectralElement
The bandpass
Example
-------
import os
import ExoCTK
import pysynphot
import pysynphot2d
grid = ExoCTK.core.ModelGrid(os.environ['MODELGRID_DIR'], resolution=100, Teff_rng=(3400,3500), logg_rng=(4.5,5.5), FeH_rng=(0,0),wave_rng=(0.8,2.5))
model = grid.get(3500, 5, 0)
model['wave'] *= 10000
spec2D = pysynphot2d.psp2d.ArraySpectra(**model)
bp = pysynphot.ObsBandpass('wfc3,ir,g141')
obs = pysynphot2d.psp2d.Observations(spec2D, bp)
"""
# Create object for each 1D spectrum
self.spectra = [ps.Observation(spec, band) for spec in spec2D.spectra]
# Store other inputs as attributes
for key, value in kwargs.items():
setattr(self, key, value)
def __getattribute__(self, attr):
"""
Redefining the getattribute call to iterate over the list of 1D spectra
Parameters
----------
attr: str
The attribute to call
Returns
-------
np.ndarray
An array of the results
"""
# Try to get the attribute from the parent object
try:
return super().__getattribute__(attr)
# If that fails, check the child object
except AttributeError:
# If it is a method...
if callable(getattr(self.spectra[0], attr)):
results = lambda *args, **kwargs: self._vec_attr(attr, *args, **kwargs)
# ... or just an attribute
else:
results = np.array([getattr(data1D, attr) for data1D in self.spectra])
return results
def _vec_attr(self, attr, *args, **kwargs):
"""
Iterate over the 1D spectra
Parameters
----------
attr: str
The attribute to call
Returns
-------
np.ndarray
The vectorized results
"""
return np.array([getattr(data1D, attr)(*args, **kwargs) for data1D in self.spectra])
def plot(self, idx):
"""
Plot the observation
Parameters
----------
idx: int
The index of the spectrum to plot
"""
obs = self.spectra[idx]
plt.plot(obs.wave, obs.flux, label='native, {}'.format(obs.name))
plt.step(obs.binwave, obs.binflux, label='binned, {}'.format(obs.name))
plt.xlabel(obs.waveunits)
plt.ylabel(obs.fluxunits)
plt.legend(loc=0)