Debian Codegraph @

pysynphot/obsbandpass.py

raw symbols SCIP
1 """This module handle bandpass of observation modes."""
2 from __future__ import division, print_function
3 import numpy as np
4
5 from .observationmode import ObservationMode
6 from .spectrum import CompositeSpectralElement, TabularSpectralElement
7 from . import units
8 from . import exceptions
9
10
11 def ObsBandpass(obstring, graphtable=None, comptable=None, component_dict={}):
12 """Generate a bandpass object from observation mode.
13
14 If the bandpass consists of multiple throughput files
15 (e.g., "acs,hrc,f555w"), then `ObsModeBandpass` is returned.
16 Otherwise, if it consists of a single throughput file
17 (e.g., "johnson,v"), then `~pysynphot.spectrum.TabularSpectralElement`
18 is returned.
19
20 See :ref:`pysynphot-obsmode-bandpass` and :ref:`pysynphot-appendixb`
21 for more details.
22
23 Parameters
24 ----------
25 obstring : str
26 Observation mode.
27
28 graphtable, comptable, component_dict
29 See `~pysynphot.observationmode.ObservationMode`.
30
31 Returns
32 -------
33 bp : `~pysynphot.spectrum.TabularSpectralElement` or `ObsModeBandpass`
34
35 Examples
36 --------
37 >>> bp1 = S.ObsBandpass('acs,hrc,f555w')
38 >>> bp2 = S.ObsBandpass('johnson,v')
39
40 """
41 ##Temporarily create an Obsmode to determine whether an
42 ##ObsModeBandpass or a TabularSpectralElement will be returned.
43 ob=ObservationMode(obstring,graphtable=graphtable,
44 comptable=comptable,component_dict=component_dict)
45 if len(ob) > 1:
46 return ObsModeBandpass(ob)
47 else:
48 return TabularSpectralElement(ob.components[0].throughput_name)
49
50
51 class ObsModeBandpass(CompositeSpectralElement):
52 """Bandpass instantiated from an ``obsmode`` string.
53 Also see :ref:`pysynphot-obsmode-bandpass`, :ref:`pysynphot-appendixb`,
54 and :ref:`pysynphot-appendixc`.
55
56 Parameters
57 ----------
58 ob : str
59 Observation mode.
60
61 Attributes
62 ----------
63 obsmode, name
64 Same as input ``ob``.
65
66 component1, component2 : `CompositeSpectralElement` or `SpectralElement`
67 Components and sub-components that belong to the observation mode.
68
69 isAnalytic : bool
70 This is always `False`.
71
72 warnings : dict
73 To store warnings, which are inherited from all inputs. If they have the same warning keyword, the one from most recently read component is used.
74
75 primary_area : float
76 See :ref:`pysynphot-area` for how this is set.
77
78 binset : array_like
79 This is set with :meth:`~pysynphot.observationmode.BaseObservationMode.bandWave`, as described in :ref:`pysynphot-refdata`.
80
81 waveunits : `~pysynphot.units.Units`
82 User unit inherited from inputs, where all inputs are required to have the same unit or an exception will be raised.
83
84 throughputunits : `None`
85 This is only to inform user that throughput is unitless.
86
87 wave, throughput : array_like
88 Wavelength set in user unit and associated unitless throughput.
89
90 Raises
91 ------
92 NotImplementedError
93 Inputs have different wavelength units.
94
95 TypeError
96 Both input spectra must be bandpasses.
97
98 pysynphot.exceptions.IncompatibleSources
99 Input spectra have different telescope areas defined.
100
101 """
102 # Instantiate a COmpositeSpectralElement by means of an
103 # ObservationMode (which the caller must have already created from
104 # an obstring
105 def __init__(self,ob):
106 #Chain the individual components
107 chain=ob.components[0].throughput*ob.components[1].throughput
108
109 for i in range(2,len(ob)-1):
110 chain = chain*ob.components[i].throughput
111
112 CompositeSpectralElement.__init__(self,chain,
113 ob.components[-1].throughput)
114
115
116 self.obsmode = ob
117 self.name = self.obsmode._obsmode #str(self.obsmode)
118 self.primary_area = ob.primary_area
119
120 #Check for valid bounds
121 self._checkbounds()
122
123 try:
124 self.binset = self.obsmode.bandWave()
125 except AttributeError:
126 # this is to catch an error raised when the self.obsmode object does not
127 # have a binset attribute because of some problem with the obsmode
128 # used to instatiate it.
129 pass
130
131 def __str__(self):
132 """Defer to ObservationMode component """
133 return self.name #self.obsmode._obsmode
134
135 def __len__(self):
136 """Defer to ObservationMode component """
137 return len(self.obsmode)
138
139 def showfiles(self):
140 """Same as
141 :meth:`pysynphot.observationmode.BaseObservationMode.showfiles`.
142
143 """
144 return self.obsmode.showfiles()
145
146 def _checkbounds(self):
147 thru=self.throughput
148 if thru[0] != 0 or thru[-1] != 0:
149 print("Warning: throughput for this obsmode is not bounded by zeros. Endpoints: thru[0]=%g, thru[-1]=%g"%(thru[0],thru[-1]))
150
151 def thermback(self):
152 """Calculate thermal background count rate for ``self.obsmode``.
153
154 Calculation uses
155 :func:`~pysynphot.observationmode.ObservationMode.ThermalSpectrum`
156 to extract thermal component source spectrum in
157 ``photlam`` per square arcsec. Then this spectrum is
158 integrated and multiplied by detector pixel scale
159 and telescope collecting area to produce a count rate
160 in count/s/pix. This unit is non-standard but used widely
161 by STScI Exposure Time Calculator.
162
163 .. note::
164
165 Similar to IRAF STSDAS SYNPHOT ``thermback`` task.
166
167 Returns
168 -------
169 ans : float
170 Thermal background count rate.
171
172 Raises
173 ------
174 NotImplementedError
175 Bandpass has no thermal information in graph table.
176
177 """
178 #The obsmode.ThermalSpectrum method will raise an exception if there is
179 #no thermal information, and that will just propagate up.
180 sp=self.obsmode.ThermalSpectrum()
181
182 #Thermback is always provided in this non-standard set of units.
183 #This code was copied from etc.py.
184 ans = sp.integrate() * (self.obsmode.pixscale**2 *
185 self.obsmode.primary_area)
186 return ans
187
188 def pixel_range(self, waverange, waveunits=None, round='round'):
189 """Returns the number of wavelength bins within ``waverange``.
190
191 .. note::
192
193 This calls :func:`pixel_range` with ``self.binset`` as
194 the first argument.
195
196 Parameters
197 ----------
198 waverange, round
199 See :func:`pixel_range`.
200
201 waveunits : str, optional
202 The units of the wavelengths given in ``waverange``.
203 If `None` (default), the wavelengths are assumed to be
204 in the units of ``self.waveunits``.
205
206 Returns
207 -------
208 num : int or float
209 Number of wavelength bins within ``waverange``.
210
211 Raises
212 ------
213 pysynphot.exceptions.UndefinedBinset
214 If ``self.binset`` is `None`.
215
216 """
217 # make sure we have a binset to work with
218 if self.binset is None:
219 raise exceptions.UndefinedBinset('No binset specified for this bandpass.')
220
221 # start by converting waverange to self.waveunits, if necessary
222 if waveunits is not None:
223 waveunits = units.Units(waveunits)
224
225 if not isinstance(waverange,np.ndarray):
226 waverange = np.array(waverange)
227
228 # convert to angstroms and then whatever self.waveunits is
229 waverange = waveunits.ToAngstrom(waverange)
230
231 waverange = units.Angstrom().Convert(waverange, self.waveunits.name)
232
233 return pixel_range(self.binset, waverange, round=round)
234
235 def wave_range(self, cenwave, npix, waveunits=None, round='round'):
236 """Get the wavelength range covered by the given number of pixels
237 centered on the given wavelength.
238
239 .. note::
240
241 This calls :func:`wave_range` with ``self.binset``
242 as the first argument.
243
244 Parameters
245 ----------
246 cenwave, npix, round
247 See :func:`wave_range`.
248
249 waveunits : str, optional
250 Wavelength units of ``cenwave`` and the returned wavelength range.
251 If `None` (default), the wavelengths are assumed to be in
252 the units of ``self.waveunits``.
253
254 Returns
255 -------
256 waverange : tuple of floats
257 The range of wavelengths spanned by ``npix`` centered on
258 ``cenwave``.
259
260 Raises
261 ------
262 pysynphot.exceptions.UndefinedBinset
263 If ``self.binset`` is None.
264
265 """
266 # make sure we have a binset to work with
267 if self.binset is None:
268 raise exceptions.UndefinedBinset('No binset specified for this bandpass.')
269
270 # convert cenwave from waveunits to self.waveunits, if necessary
271 if waveunits is not None:
272 waveunits = units.Units(waveunits)
273
274 # convert to angstroms and then whatever self.waveunits is
275 cenwave = waveunits.ToAngstrom(cenwave)
276 cenwave = units.Angstrom().Convert(cenwave, self.waveunits.name)
277
278 wave1, wave2 = wave_range(self.binset, cenwave, npix, round=round)
279
280 # translate ends to waveunits, if necessary
281 if waveunits is not None:
282 # convert to angstroms
283 wave1 = self.waveunits.ToAngstrom(wave1)
284 wave2 = self.waveunits.ToAngstrom(wave2)
285
286 # then to waveunits
287 wave1 = units.Angstrom().Convert(wave1, waveunits.name)
288 wave2 = units.Angstrom().Convert(wave2, waveunits.name)
289
290 return wave1, wave2
291
292
293 def pixel_range(bins, waverange, round='round'):
294 """Returns the number of wavelength bins within ``waverange``.
295
296 Parameters
297 ----------
298 bins : ndarray
299 Wavelengths of pixel centers.
300 Must be in the same units as ``waverange``.
301
302 waverange : array_like
303 A sequence containing the wavelength range of interest. Only the
304 first and last elements are used. Assumed to be in increasing order.
305 Must be in the same units as ``bins``.
306
307 round : {'round', 'min', 'max', `None`}, optional
308 How to deal with pixels at the edges of the wavelength range. All
309 of the options, except `None`, will return an integer number of pixels.
310 Defaults to ``'round'``.
311
312 * ``'round'`` - Wavelength ends that fall in the middle of a
313 pixel are counted if more than half of the pixel is within
314 ``waverange``. Ends that fall in the center of a pixel are
315 rounded up to the nearest pixel edge.
316 * ``'min'`` - Only pixels wholly within ``waverange`` are counted.
317 * ``'max'`` - End pixels that are within ``waverange`` by any
318 margin are counted.
319 * `None` - The exact number of encompassed pixels, including
320 fractional pixels, is returned.
321
322 Returns
323 -------
324 num : int or float
325 Number of wavelength bins within ``waverange``.
326
327 Raises
328 ------
329 ValueError
330 If ``round`` is not an allowed value.
331
332 pysynphot.exceptions.OverlapError
333 If ``waverange`` exceeds the bounds of ``bins``.
334
335 """
336 # make sure that the round keyword is valid
337 if round not in ('round','min','max',None):
338 raise ValueError("round keyword must be one of ('round','ciel','floor',None)")
339
340 wave1 = waverange[0]
341 wave2 = waverange[-1]
342
343 # make sure the specified waverange is within our .binset
344 minwave = bins[0] - (bins[0:2].mean() - bins[0])
345 if wave1 < minwave:
346 raise exceptions.OverlapError("Lower bound of waverange is outside of binset. Min = %f" % minwave)
347
348 maxwave = bins[-1] + (bins[-1] - bins[-2:].mean())
349 if wave2 > maxwave:
350 raise exceptions.OverlapError("Upper bound of waverange is outside of binset. Max = %f" % maxwave)
351
352 # if the wavelength ends are the same return 0
353 if wave1 == wave2:
354 return 0
355
356 # find where the wavelength endpoints fall.
357 if round == 'round':
358 ind1 = bins.searchsorted(wave1, side='right')
359 ind2 = bins.searchsorted(wave2, side='right')
360
361 num = ind2 - ind1
362
363 elif round == 'min':
364 ind1 = bins.searchsorted(wave1, side='left')
365 ind2 = bins.searchsorted(wave2, side='left')
366
367 # for ind1, figure out if pixel ind1 is wholly included or not.
368 # do this by figuring out where wave1 is between ind1 and ind1-1.
369 frac = (bins[ind1] - wave1) / (bins[ind1] - bins[ind1-1])
370
371 if frac < 0.5:
372 # ind1 is only partially included
373 ind1 += 1
374
375 # similar but reversed procedure for ind2
376 frac = (wave2 - bins[ind2-1]) / (bins[ind2] - bins[ind2-1])
377
378 if frac < 0.5:
379 # ind2 is only partially included
380 ind2 -= 1
381
382 num = ind2 - ind1
383
384 elif round == 'max':
385 ind1 = bins.searchsorted(wave1, side='left')
386 ind2 = bins.searchsorted(wave2, side='left')
387
388 # for ind1, figure out if pixel ind1-1 is partially included or not.
389 # do this by figuring out where wave1 is between ind1 and ind1-1.
390 frac = (wave1 - bins[ind1-1]) / (bins[ind1] - bins[ind1-1])
391
392 if frac < 0.5:
393 # ind1 is partially included
394 ind1 -= 1
395
396 # similar but reversed procedure for ind2
397 frac = (bins[ind2] - wave2) / (bins[ind2] - bins[ind2-1])
398
399 if frac < 0.5:
400 # ind2 is partially included
401 ind2 += 1
402
403 num = ind2 - ind1
404
405 elif round is None:
406 ind1 = bins.searchsorted(wave1, side='left')
407 ind2 = bins.searchsorted(wave2, side='left')
408
409 # calculate fractional indices
410 frac1 = ind1 - (bins[ind1] - wave1) / (bins[ind1] - bins[ind1-1])
411
412 frac2 = ind2 - (bins[ind2] - wave2) / (bins[ind2] - bins[ind2-1])
413
414 num = frac2 - frac1
415
416 return num
417
418
419 def wave_range(bins, cenwave, npix, round='round'):
420 """Get the wavelength range covered by the given number of pixels
421 centered on the given wavelength.
422
423 Parameters
424 ----------
425 bins : ndarray
426 Wavelengths of pixel centers. Must be in the same units as
427 ``cenwave``.
428
429 cenwave : float
430 Central wavelength of range. Must be in the same units as ``bins``.
431
432 npix : int
433 Number of pixels in range, centered on ``cenwave``.
434
435 round : {'round', 'min', 'max', `None`}, optional
436 How to deal with pixels at the edges of the wavelength range. All
437 of the options, except `None`, will return wavelength ends that
438 correpsonds to pixel edges. Defaults to ``'round'``.
439
440 * ``'round'`` - A wavelength range is returned such that the
441 ends are pixel edges and the range spans exactly ``npix`` pixels.
442 Ends that fall in the center of bins are rounded up to the nearest
443 pixel edge.
444 * ``'min'`` - The returned wavelength range is shrunk so that
445 it includes an integer number of pixels and the ends fall on pixel
446 edges. May not span exactly ``npix`` pixels.
447 * ``'max'`` - The returned wavelength range is expanded so that
448 it includes an integer number of pixels and the ends fall on pixel
449 edges. May not span exactly ``npix`` pixels.
450 * `None` - An exact wavelength range is returned.
451 The wavelength ends returned may not correspond to pixel edges,
452 but will cover exactly ``npix`` pixels.
453
454 Returns
455 -------
456 waverange : tuple of floats
457 The range of wavelengths spanned by ``npix`` centered on ``cenwave``.
458
459 Raises
460 ------
461 ValueError
462 If ``round`` is not an allowed value.
463
464 pysynphot.exceptions.OverlapError
465 If ``cenwave`` is not within ``bins``, or the returned ``waverange``
466 would exceed the limits of ``bins``.
467
468 """
469 # make sure that the round keyword is valid
470 if round not in (None,'round','min','max'):
471 raise ValueError("round keyword must be one of (None,'round','min','max')")
472
473 # make sure cenwave is within binset
474 if cenwave < bins[0]:
475 raise exceptions.OverlapError("cenwave is not within binset. Min = %f" % bins[0])
476 elif cenwave > bins[-1]:
477 raise exceptions.OverlapError("cenwave is not within binset. Max = %f" % bins[-1])
478
479 # first figure out what index the central wavelength falls at
480 diff = cenwave - bins
481 ind = np.where(np.abs(diff) == np.abs(diff).min())[0][0]
482
483 # now figure out the fractional index
484 if diff[ind] < 0:
485 frac_ind = float(ind) + diff[ind] / (bins[ind] - bins[ind-1])
486 elif diff[ind] > 0:
487 frac_ind = float(ind) + diff[ind] / (bins[ind+1] - bins[ind])
488 else:
489 frac_ind = float(ind)
490
491 # then figure out the fractional indices of the ends
492 frac_ind1 = frac_ind - npix/2.
493 frac_ind2 = frac_ind + npix/2.
494
495 # check ends
496 if frac_ind1 < -0.5:
497 raise exceptions.OverlapError("Lower wavelength range is below allowed binset.")
498
499 if frac_ind2 > bins.shape[0] - 0.5:
500 raise exceptions.OverlapError("Upper wavelength range is above allowed binset.")
501
502 frac1, int1 = np.modf(frac_ind1)
503 frac2, int2 = np.modf(frac_ind2)
504
505 # translate ends to wavelength
506 if round is None:
507 # translate ends directly to wavelength without regard to bin edges
508 f, i = frac1, int(int1)
509
510 wave1 = bins[i] + frac1 * (bins[i+1] - bins[i])
511
512 f, i = frac2, int(int2)
513
514 wave2 = bins[i] + frac2 * (bins[i+1] - bins[i])
515
516 elif round == 'round':
517 # calculate lower end of wavelength range
518 f, i = frac1, int(int1)
519
520 if f >= 0:
521 # end is somewhere greater than binset[0] so we can just
522 # interpolate between two neighboring values going with upper edge
523 wave1 = bins[i:i+2].mean()
524 else:
525 # end is below the lowest binset value, but not by enough to
526 # trigger an exception
527 wave1 = bins[0] - (bins[0:2].mean() - bins[0])
528
529 # calculate upper end of wavelength range
530 f, i = frac2, int(int2)
531
532 if i < bins.shape[0] - 1:
533 # end is somewhere below binset[-1] so we can just interpolate
534 # between two neighboring values, going with the upper edge.
535 wave2 = bins[i:i+2].mean()
536 else:
537 # end is above highest binset value but not by enough to
538 # trigger an exception
539 wave2 = bins[-1] + (bins[-1] - bins[-2:].mean())
540
541 elif round == 'min':
542 # calculate lower end of wavelength range
543 f, i = frac1, int(int1)
544
545 if f <= 0.5 and i < bins.shape[0] - 1:
546 # not at the lowest possible edge and pixel i included
547 wave1 = bins[i:i+2].mean()
548 elif f > 0.5 and i < bins.shape[0] - 2:
549 # not at the lowest possible edge and pixel i not included
550 wave1 = bins[i+1:i+3].mean()
551 elif f == -0.5:
552 # at the lowest possible edge
553 wave1 = bins[0] - (bins[0:2].mean() - bins[0])
554
555 # calculate upper end of wavelength range
556 f, i = frac2, int(int2)
557
558 if f >= 0.5 and i < bins.shape[0] - 1:
559 # not out at the end and pixel i included
560 wave2 = bins[i:i+2].mean()
561 elif f < 0.5 and i < bins.shape[0]:
562 # not out at end and pixel i not included
563 wave2 = bins[i-1:i+1].mean()
564 elif f == 0.5 and i == bins.shape[0] - 1:
565 # at the very end
566 wave2 = bins[-1] + (bins[-1] - bins[-2:].mean())
567
568 elif round == 'max':
569 # calculate lower end of wavelength range
570 f, i = frac1, int(int1)
571
572 if f < 0.5 and i < bins.shape[0]:
573 # not at the lowest possible edge and pixel i included
574 wave1 = bins[i-1:i+1].mean()
575 elif f >= 0.5 and i < bins.shape[0] - 1:
576 # not at the lowest possible edge and pixel i not included
577 wave1 = bins[i:i+2].mean()
578 elif f == -0.5:
579 # at the lowest possible edge
580 wave1 = bins[0] - (bins[0:2].mean() - bins[0])
581
582 # calculate upper end of wavelength range
583 f, i = frac2, int(int2)
584
585 if f > 0.5 and i < bins.shape[0] - 2:
586 # not out at the end and pixel i included
587 wave2 = bins[i+1:i+3].mean()
588 elif f <= 0.5 and i < bins.shape[0] - 1:
589 # not out at end and pixel i not included
590 wave2 = bins[i:i+2].mean()
591 elif f == 0.5 and i == bins.shape[0] - 1:
592 # at the very end
593 wave2 = bins[-1] + (bins[-1] - bins[-2:].mean())
594
595 return wave1, wave2