Debian Codegraph @

doc/source/tutorials.rst

raw
1 .. _pysynphot-tutorials:
2
3 *********
4 Tutorials
5 *********
6
7 These tutorials are for those who prefer to jump right in. There are also some
8 simple :ref:`exercises <pysynphot_tutorial_exercises>` for practice. You can
9 skip the parts involving plotting if you do not have ``matplotlib`` installed.
10
11 Before starting the tutorials, see :ref:`pysynphot-installation-setup`.
12
13
14 .. _pysynphot_tutorial_1:
15
16 Tutorial 1: The Basics
17 ======================
18
19 In this tutorial, you will be introduced to the **pysynphot** software and
20 practice the following basic functionalities:
21
22 * Read spectra from files and display them using ``matplotlib``
23 * Create analytic source spectra
24 * Create a bandpass from observation mode string expression
25 * Manipulate spectrum objects
26 * Create an observation and compute its count rate and effective wavelength
27 * Write out spectra as FITS tables
28
29
30 Source Spectrum from File
31 -------------------------
32
33 Read a Vega spectrum (not the built-in version) from FITS table and
34 convert its flux unit to ``flam``:
35
36 >>> vega_file = os.path.join(
37 ... os.environ['PYSYN_CDBS'], 'calspec', 'alpha_lyr_stis_005.fits')
38 >>> vega = S.FileSpectrum(vega_file)
39 >>> vega.convert('flam')
40
41 Evaluate flux at 5000 Angstroms:
42
43 >>> vega(5000) # photlam (internal unit)
44 1190.0510381121621
45 >>> vega.sample(5000) # flam (user unit)
46 4.7280365616415988e-09
47
48 Plot the Vega spectrum:
49
50 >>> plt.plot(vega.wave, vega.flux)
51 >>> plt.xlim(0, 12000)
52 >>> plt.xlabel(vega.waveunits)
53 >>> plt.ylabel(vega.fluxunits)
54 >>> plt.title(os.path.basename(vega.name))
55
56 .. image:: _static/vega_spec.png
57 :width: 600px
58 :alt: Vega spectrum.
59
60
61 .. _pysynphot_tutorial_1_analytic:
62
63 Analytic Source Spectra
64 -----------------------
65
66 Create a blackbody source with a temperature of 40000 Kelvin:
67
68 >>> bb = S.BlackBody(40000)
69
70 Create a power-law source with reference wavelength of 10000 Angstrom and index
71 of -2:
72
73 >>> plaw = S.PowerLaw(10000, -2)
74
75 Create a Gaussian source with total flux of :math:`8.3 \times 10^{-9}` ``flam``
76 under the curve, central wavelength of 18000 Angstroms,
77 and FWHM of 20 Angstroms:
78
79 >>> gss = S.GaussianSource(8.3e-9, 18000, 20, fluxunits='flam')
80
81 Create a source that emits 1 count across all wavelengths:
82
83 >>> onecount = S.FlatSpectrum(1, fluxunits='counts')
84
85 Add Gaussian and power-law source spectra together to create a new source:
86
87 >>> sp = plaw + gss
88
89 Plot the combined spectrum and its individual components:
90
91 >>> plt.semilogy(sp.wave, sp.flux, 'k', label='plaw+gss')
92 >>> plt.semilogy(plaw.wave, plaw.flux, 'b:', label='plaw')
93 >>> plt.semilogy(gss.wave, gss.flux, 'r--', label='gss')
94 >>> plt.xlim(17900, 18100)
95 >>> plt.xlabel(sp.waveunits)
96 >>> plt.ylabel(sp.fluxunits)
97 >>> plt.legend(loc='center')
98
99 .. image:: _static/added_spec_tutorial_1.png
100 :width: 600px
101 :alt: Spectrum addition from Tutorial 1.
102
103
104 Bandpass from Observation Mode
105 ------------------------------
106
107 Create a bandpass for HST/ACS instrument using its WFC1 detector and F555W
108 filter:
109
110 >>> bp1 = S.ObsBandpass('acs,wfc1,f555w')
111
112 Show all the components in the light path used to create the bandpass:
113
114 >>> bp1.showfiles()
115 /my/local/dir/trds/comp/ota/hst_ota_007_syn.fits
116 /my/local/dir/trds/comp/acs/acs_wfc_im123_004_syn.fits
117 /my/local/dir/trds/comp/acs/acs_f555w_wfc_005_syn.fits
118 /my/local/dir/trds/comp/acs/acs_wfc_ebe_win12f_005_syn.fits
119 /my/local/dir/trds/comp/acs/acs_wfc_ccd1_mjd_021_syn.fits
120
121 Read the OTA and CCD transmissions from files, then multiply them:
122
123 >>> ota = S.FileBandpass('/my/local/dir/trds/comp/ota/hst_ota_007_syn.fits')
124 >>> ccd = S.FileBandpass(
125 ... '/my/local/dir/trds/comp/acs/acs_wfc_ccd1_mjd_021_syn.fits')
126 >>> bp2 = ota * ccd
127
128 Plot the bandpass and overlay its two components from above:
129
130 >>> plt.plot(bp1.wave, bp1.throughput, 'k', label='acs,wfc1,f555w')
131 >>> plt.plot(ota.wave, ota.throughput, 'b--', label='ota')
132 >>> plt.plot(ccd.wave, ccd.throughput, 'r--', label='ccd')
133 >>> plt.plot(bp2.wave, bp2.throughput, 'g', label='ota*ccd')
134 >>> plt.xlabel(bp1.waveunits)
135 >>> plt.legend(loc='best')
136
137 .. image:: _static/acs_wfc1_f555w_bandpass_tutorial_1.png
138 :width: 600px
139 :alt: Bandpass for ACS WFC1 F555W from Tutorial 1.
140
141
142 Spectrum Manipulation
143 ---------------------
144
145 Get extinction curve for Milky Way (diffuse) with :math:`E(B-V) = 0.7` and apply
146 it to Vega spectrum from above. Then, check that the flux is indeed reduced
147 by the extinction curve:
148
149 >>> extinct = S.Extinction(0.7, 'mwavg')
150 >>> extinct.citation
151 ' Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.'
152 >>> sp1 = vega * extinct
153 >>> max(vega.flux)
154 8.7730995298612719e-09
155 >>> max(sp1.flux)
156 5.06749522597244e-10
157
158 Redshift the reddened spectrum above by :math:`z = 0.23`. Then, check that the
159 peak wavelength is indeed redder:
160
161 >>> sp2 = sp1.redshift(0.23) # sp2 is in PHOTLAM
162 >>> sp2.convert('flam')
163 >>> sp1.wave[sp1.flux == max(sp1.flux)][0]
164 5026.7534
165 >>> sp2.wave[sp2.flux == max(sp2.flux)][0]
166 6182.9067
167
168 Normalize the redshifted spectrum to a total flux of :math:`1.8 \times 10^{-13}`
169 ``flam`` over HST/ACS WFC1 F555W bandpass from above:
170
171 >>> sp3 = sp2.renorm(1.8e-13, 'flam', bp1)
172
173 Plot the resultant spectrum and compare to the original Vega:
174
175 >>> plt.semilogy(vega.wave, vega.flux, 'b', label='vega')
176 >>> plt.semilogy(sp3.wave, sp3.flux, 'r', label='sp3')
177 >>> plt.xlim(1100, 10000)
178 >>> plt.xlabel(vega.waveunits)
179 >>> plt.ylabel(vega.fluxunits)
180 >>> plt.legend(loc='lower right')
181
182 .. image:: _static/vega_manip_tutorial_1.png
183 :width: 600px
184 :alt: Manipulated Vega spectrum from Tutorial 1.
185
186
187 .. _pysynphot_tutorial_1_obs:
188
189 Observation
190 -----------
191
192 Create an observation using modified Vega spectrum and HST/ACS WFC1 F555W
193 bandpass from above:
194
195 >>> obs = S.Observation(sp3, bp1)
196
197 Calculate count rate of this observation in the unit of counts/s over the HST
198 collecting area (i.e., the primary mirror) that is defined in
199 :math:`\mathrm{cm}^{2}`:
200
201 >>> obs.primary_area
202 45238.93416
203 >>> obs.countrate()
204 909477.56364769232
205
206 Calculate the count rate in
207 :math:`\mathrm{counts} \; \mathrm{s}^{-1} \; \mathrm{cm}^{-2}`:
208
209 >>> obs.countrate() / obs.primary_area
210 20.103868062653145
211
212 Calculate the effective stimulus in ``flam``:
213
214 >>> obs.effstim('flam')
215 1.7999999531057673e-13
216
217 Calculate effective wavelength in Angstroms:
218
219 >>> obs.efflam()
220 5425.0867727745972
221
222 Convert the flux unit to counts:
223
224 >>> obs.convert('counts')
225
226 Plot observation data in both native and binned wavelength sets. Note that
227 counts per wavelength bin depends on the size of the bin because it is not
228 a flux density:
229
230 >>> plt.plot(obs.wave, obs.flux, marker='x', label='native')
231 >>> plt.plot(obs.binwave, obs.binflux, drawstyle='steps-mid', label='binned')
232 >>> plt.xlim(5030, 5050)
233 >>> plt.xlabel(obs.waveunits)
234 >>> plt.ylabel(obs.fluxunits)
235 >>> plt.legend(loc='best')
236
237 .. image:: _static/obs_counts_tutorial_1.png
238 :width: 600px
239 :alt: Observation in counts from Tutorial 1.
240
241 Write the observation out to two FITS tables, one with native dataset and the
242 other binned:
243
244 >>> obs.writefits('myobs_native.fits', binned=False)
245 >>> obs.writefits('myobs_binned.fits')
246
247
248 .. _pysynphot_tutorial_2:
249
250 Tutorial 2: Adding Emission Line
251 ================================
252
253 This tutorial is adapted from
254 `Exposure Time Calculator User's Guide on a similar topic <http://etc.stsci.edu/etcstatic/users_guide/1_ref_8.5_emlines.html#using-pysynphot-to-modify-emission-lines>`_.
255 In this tutorial, you will learn how to manipulate and superimpose
256 an emission line to a continuum spectrum.
257
258 Create a continuum spectrum of a 5500 K blackbody with :math:`z = 0.6`:
259
260 >>> bb = S.BlackBody(5500).redshift(0.6)
261
262 Create a Gaussian emission line with :math:`8 \times 10^{-14}` ``flam``
263 total flux under the curve and FWHM of 100 Angstroms centered at 7000 Angstroms:
264
265 >>> em = S.GaussianSource(8e-14, 7000, 100, fluxunits='flam')
266
267 Add emission line to continuum spectrum:
268
269 >>> sp = bb + em
270
271 Apply extinction curve for LMC (average) with :math:`E(B-V) = 1.3` to the
272 composite spectrum:
273
274 >>> my_spec = sp * S.Extinction(1.3, 'lmcavg')
275
276 Plot the result:
277
278 >>> plt.plot(my_spec.wave, my_spec.flux)
279 >>> plt.xlabel(my_spec.waveunits)
280 >>> plt.ylabel(my_spec.fluxunits)
281
282 .. image:: _static/bb_em_tutorial_2.png
283 :width: 600px
284 :alt: Blackbody with emission line from Tutorial 2.
285
286
287 .. _pysynphot_tutorial_3:
288
289 Tutorial 3: FWHM
290 ================
291
292 This tutorial is adapted from an example in the documentation of
293 IRAF STSDAS SYNPHOT ``bandpar`` task. In this tutorial, you will learn
294 how to calculate the full-width at half-maximum (FWHM) of the
295 HST/WFPC instrument with F555W filter.
296
297 Create the bandpass:
298
299 >>> bp = S.ObsBandpass('wfpc,f555w')
300
301 Compute FWHM in Angstroms:
302
303 >>> np.sqrt(8 * np.log(2)) * bp.photbw()
304 1200.923243227332
305
306
307 .. _pysynphot-tutorial-color-index:
308
309 Tutorial 4: Color Difference
310 ============================
311
312 This tutorial is adapted from an example in the documentation of
313 IRAF STSDAS SYNPHOT ``calcphot`` task. In this tutorial, you will learn
314 how to find the color difference of a 2500 K blackbody in Cousins *I* and
315 HST/WFC3 UVIS1 F814W bandpasses.
316
317 Create the blackbody:
318
319 >>> bb = S.BlackBody(2500)
320
321 Create an observation for each of the two bandpasses. Cousins *I* bandpass does
322 not have pre-defined ``binset``, so for consistency with the other bandpass,
323 it is to use the binning of HST/WFC3 UVIS1 detector:
324
325 >>> obs_wfc3 = S.Observation(bb, S.ObsBandpass('wfc3,uvis1,f814w'))
326 >>> obs_i = S.Observation(bb, S.ObsBandpass('i'), binset=obs_wfc3.binwave)
327
328 The color difference in magnitude is computed by subtracting the effective
329 stimuli of the two observations. In instrumental magnitude, this is:
330
331 >>> obs_i.effstim('obmag') - obs_wfc3.effstim('obmag')
332 -1.2585631331417577
333
334 The color difference in linear flux unit is computed by dividing the effective
335 stimuli of the two observations. In ``flam``, this is:
336
337 >>> obs_i.effstim('flam') / obs_wfc3.effstim('flam')
338 0.95505705250139461
339
340
341 .. _pysynphot_tutorial_5:
342
343 Tutorial 5: Continuum-Normalized Spectrum
344 =========================================
345
346 In this tutorial, you will learn how to create a composite spectrum with a noisy
347 blackbody continuum, an emission line, and an absorption line. Then, you will
348 divide it by a smooth continuum and plot the resultant continuum-normalized
349 spectrum.
350
351 Create the smooth continuum that is a 5000 K blackbody:
352
353 >>> bb = S.BlackBody(5000)
354
355 Add random noise to the continuum. Since **pysynphot** object cannot be
356 multiplied with Numpy array, this has to be done indirectly by applying the
357 noise to sampled flux array, and then use the results to build a new source
358 spectrum:
359
360 >>> w = bb.wave
361 >>> nse = 1 + np.random.normal(size=w.size, scale=0.02)
362 >>> bb_noisy = S.ArraySpectrum(wave=w, flux=bb(w)*nse)
363
364 Apply emission and absorption lines to the noisy continuum. How to construct a
365 Gaussian source is explained in
366 :ref:`Tutorial 1: Analytic Source Spectra <pysynphot_tutorial_1_analytic>`:
367
368 >>> g_em = S.GaussianSource(0.02, 15000, 500, fluxunits='photlam')
369 >>> g_ab = S.GaussianSource(0.015, 4500, 100, fluxunits='photlam')
370 >>> sp = bb_noisy + g_em - g_ab
371
372 Divide the spectrum above with the smooth continuum to obtain flux ratio.
373 Since **pysynphot** object cannot do division, this has to be calculated
374 indirectly using sampled flux arrays, which happen to be in ``photlam`` in
375 this example:
376
377 >>> fratio = sp(w) / bb(w)
378
379 Plot the continuum-normalized spectrum:
380
381 >>> plt.plot(w, fratio)
382 >>> plt.xlabel(sp.waveunits)
383 >>> plt.ylabel('flux ratio')
384
385 .. image:: _static/cont_norm_spec_tutorial_5.png
386 :width: 600px
387 :alt: Continuum-normalized spectrum from Tutorial 5.
388
389
390 .. _pysynphot_tutorial_6:
391
392 Tutorial 6: Custom Wavelength Table
393 ===================================
394
395 In this tutorial, you will learn how to create a custom wavelength array and
396 save it to a FITS table using `astropy.io.fits`. Then, you will read the array
397 back in from file, and use it to define binned dataset in an observation.
398
399 Suppose we want a wavelength set that ranges from 2000 to 8000 Angstroms, with
400 1 Angstrom spacing over most of the range, but 0.1 Angstrom spacing
401 around the [O III] forbidden lines at 4959 and 5007 Angstroms.
402
403 Create the 3 regions separately, concatenate them, and display the result:
404
405 >>> lowwave = np.arange(2000, 4950)
406 >>> midrange = np.arange(4950, 5010, 0.1) # [O III]
407 >>> hiwave = np.arange(5010, 8000)
408 >>> wave = np.concatenate([lowwave, midrange, hiwave])
409 >>> wave
410 array([ 2000., 2001., 2002., ..., 7997., 7998., 7999.], dtype=float32)
411
412 Create a FITS table column from the concatenated array above, insert it
413 into a new FITS table, and write the table out to file:
414
415 >>> from astropy.io import fits
416 >>> col = fits.Column(
417 ... name='wavelength', unit='angstroms', format='E', array=wave)
418 >>> tabhdu = fits.BinTableHDU.from_columns([col])
419 >>> tabhdu.writeto('mywaveset.fits', clobber=True)
420
421 Read the custom wavelength set back in from file:
422
423 >>> with fits.open('mywaveset.fits') as pf:
424 ... wave = pf[1].data.field('wavelength')
425
426 Create an observation of Vega with HST/ACS WFC1 F555W bandpass, using the
427 custom wavelength set for binned data, and then check that the binned wavelength
428 set is indeed the given one:
429
430 >>> obs = S.Observation(S.Vega, S.ObsBandpass('acs,wfc1,f555w'), binset=wave)
431 >>> obs.binwave
432 array([ 2000., 2001., 2002., ..., 7997., 7998., 7999.], dtype=float32)
433
434
435 .. _pysynphot_tutorial_7:
436
437 Tutorial 7: Count Rates for Multiple Apertures
438 ==============================================
439
440 In this tutorial, you will learn how to calculate count rates for observations
441 of the same source and bandpass, but with different apertures. Note that this
442 feature is only available for observing modes that allow encircled energy (EE)
443 radius specification (see :ref:`pysynphot-appendixb`).
444
445 Create two observations of Vega (renormalized to 20 ``stmag`` in Johnson *V*)
446 with HST/ACS WFC1 F555W bandpass, with 0.3 and 1.0 arcsec EE radii,
447 respectively:
448
449 >>> sp = S.Vega.renorm(20, 'stmag', S.ObsBandpass('johnson,v'))
450 >>> obs03 = S.Observation(sp, S.ObsBandpass('acs,wfc1,f555w,aper#0.3'))
451 >>> obs10 = S.Observation(sp, S.ObsBandpass('acs,wfc1,f555w,aper#1.0'))
452
453 Calculate the count rates for both and display the results:
454
455 >>> c03 = obs03.countrate()
456 >>> c10 = obs10.countrate()
457 >>> print('Count rate for 0.3" is {0}\n'
458 ... 'Count rate for 1.0" is {1}'.format(c03, c10))
459 Count rate for 0.3" is 174.063405183
460 Count rate for 1.0" is 185.733901828
461
462
463 .. _pysynphot_tutorial_8:
464
465 Tutorial 8: Blueshift
466 =====================
467
468 In this tutorial, you will learn how to blueshift an observed spectrum back to
469 its rest frame. The blueshift value, :math:`z_{\mathrm{blue}}`, can be
470 calculated from the redshift, :math:`z`, as follows:
471
472 .. math::
473
474 z_{\mathrm{blue}} = \frac{1}{1 + z} - 1
475
476 Create an observed blackbody spectrum at :math:`z = 0.1` (this is similar to the
477 example in :ref:`pysynphot-redshift`):
478
479 >>> z = 0.1
480 >>> bb = S.BlackBody(5000)
481 >>> sp_obs = bb.redshift(z)
482
483 Calculate and apply the blueshift, and then compare the result to the expected
484 values at rest frame (i.e., the original blackbody spectrum):
485
486 >>> z_blue = 1.0 / (1 + z) - 1
487 >>> sp_rest = sp_obs.redshift(z_blue)
488 >>> np.testing.assert_allclose(sp_rest.wave, bb.wave)
489 >>> np.testing.assert_allclose(sp_rest.flux, bb.flux)
490
491
492 .. _pysynphot_tutorial_9:
493
494 Tutorial 9: Bandpass ``stmag`` Zeropoint
495 ========================================
496
497 HST bandpasses store their :ref:`pysynphot-formula-uresp` values under the
498 ``PHOTFLAM`` keyword in image headers. This keyword is then used to compute
499 ``stmag`` zeropoint for the respective bandpass (e.g.,
500 `ACS <http://www.stsci.edu/hst/instrumentation/acs/data-analysis/zeropoints.html>`_ and
501 `WFC3 <http://www.stsci.edu/hst/instrumentation/wfc3/data-analysis/photometric-calibration.html#section-14525acb-c4ec-4fe8-9d25-c9606f1ea62e>`_).
502
503 In this tutorial, you will learn how to calculate the ``stmag`` zeropoint for
504 the F555W filter in HST/ACS WFC1 detector:
505
506 >>> bp = S.ObsBandpass('acs,wfc1,f555w')
507 >>> st_zpt = -2.5 * np.log10(bp.unit_response()) - 21.1
508 >>> print('STmag zeropoint for {0} is {1:.5f}'.format(bp.name, st_zpt))
509 STmag zeropoint for acs,wfc1,f555w is 25.65880
510
511
512 .. _pysynphot_tutorial_10:
513
514 Tutorial 10: Spectrum from Custom Text File
515 ===========================================
516
517 In this tutorial, you will learn how to load a source spectrum from an ASCII
518 table that does not conform to the expected format stated in
519 :ref:`pysynphot-io`. Since `~pysynphot.spectrum.FileSourceSpectrum` does not
520 allow explicit setting of units, if your table data have non-default wavelength
521 or flux units, you have to first load them into Numpy arrays and then use
522 `~pysynphot.spectrum.ArraySourceSpectrum` to obtain the spectrum object
523 correctly. Similar workflow applies to bandpass for non-default
524 wavelength units, using `~pysynphot.spectrum.ArraySpectralElement` (not shown).
525
526 Let's say your ASCII table looks like this::
527
528 # My source spectrum
529 # ROW WAVELENGTH(NM) FLUX(PHOTLAM)
530 1 400.0 0.1
531 2 401.0 0.1234
532 3 405.0 0.4556
533 ... ... ...
534
535 There are many ways you can read the ASCII table into Numpy arrays. The example
536 below uses Astropy:
537
538 >>> from astropy.io import ascii
539 >>> tab = ascii.read('myfile.txt', names=['row', 'wave', 'flux'])
540 >>> wave = tab['wave'] # Second column
541 >>> flux = tab['flux'] # Third column
542
543 Construct the source spectrum from the arrays above:
544
545 >>> sp = S.ArraySpectrum(
546 ... wave=wave, flux=flux, waveunits='nm', fluxunits='photlam')
547
548
549 .. _pysynphot_tutorial_exercises:
550
551 Exercises
552 =========
553
554 Here are the exercises for those who wish to apply what they learned from
555 some of the tutorials above. Answers are not provided, but should be obvious
556 based on the available tutorials and documentation.
557
558 :ref:`pysynphot_tutorial_1`
559
560 1. Convert the blackbody source created in Tutorial 1 to ``flam`` flux unit.
561 Plot it.
562
563 2. Create a bandpass for HST/WFC3 instrument using its UVIS1 detector and F475W
564 filter. Plot it.
565
566 3. Create an observation using the blackbody source and the HST/WFC3 UVIS1
567 F475W bandpass. Compute its count rate. Plot it.
568
569 :ref:`pysynphot_tutorial_2`
570
571 1. Create a Gaussian emission line with :math:`10^{-13}` ``flam``
572 total flux under the curve and FWHM of 50 Angstroms centered at
573 5000 Angstroms. Redshift it by :math:`z=0.01`.
574
575 2. Add this new emission line to the composite spectrum from Tutorial 2.
576 Don't forget to account for the foreground LMC extinction.
577
578 3. Plot your result. You should see the same composite spectrum as in the
579 tutorial but with an extra emission line that you created.
580
581 :ref:`pysynphot_tutorial_3`
582
583 1. Find the FWHM for HST/ACS WFC1 F555W bandpass.
584
585 2. Find the FWHM for a :ref:`box-shaped bandpass <pysynphot-box-bandpass>`
586 centered at 3500 Angstroms with the width of 100 Angstroms.
587
588 :ref:`pysynphot-tutorial-color-index`
589
590 1. Find the color difference for the observations in Tutorial 4 in ``stmag``.
591
592 2. Find the color difference for the observations in Tutorial 4 in counts/s.
593
594 :ref:`pysynphot_tutorial_5`
595
596 1. Repeat the steps in Tutorial 5 but using blackbody temperature of 10000
597 Kelvin.
598
599 2. Add a new absorption line of your choice to the spectrum that you just
600 created. Recalculate and replot its flux ratio.