6.3. Example 3 - K-band R3K Longslit Point Source - Using the “reduce” command

We will reduce a F2 R3K 2.2 {\mu}m longslit observation the superluminal microquasar GRS 1915+105 using the Python programmatic interface.

This observation uses the 2-pixel slit. The original observation is a bit long. For expediency, we will reduced only the last eight frames of the sequence. The dither pattern is AABB-AABB.

Note

We will see later that for both the science observations and the telluric observations, the source was going out of the slit when the telescope was moved to the B position. The signal in the B beam can be as low as 15% the signal in the A beam. We do not know what happened on that night to cause that. The consequence is a lower signal-to-noise ratio in the final stack than requested.

6.3.1. The dataset

If you have not already, download and unpack the tutorial’s data package. Refer to Downloading tutorial datasets for the links and simple instructions.

The dataset specific to this example is described in:

Here is a copy of the table for quick reference.

Science

S20230606S0083-090

Science darks (120s)

S20230610S0434-440

Science flat

S20230606S0091

Science flat darks (16s)

S20230610S0217,220,223,225,227,230,232,235

Science arc

S20230606S0093

Science arc darks (180s) |

S20230610S0343-349

Telluric

S20230606S0097-100

Telluric darks (15s)

S20230610S0200,203,205,208,211,213

Telluric flat

S20230606S0101

Telluric flat darks (16s)

Same as science flat darks

Telluric arc

S20230606S0103

Telluric arc darks

Same as science arc darks

6.3.2. Setting up

First navigate to your work directory in the unpacked data package.

cd <path>/f2ls_tutorial/playground

The first steps are to import libraries, set up the calibration manager, and set the logger.

6.3.2.1. Configuring the interactive interface

In ~/.dragons/, add the following to the configuration file dragonsrc:

[interactive]
browser = your_preferred_browser

The [interactive] section defines your preferred browser. DRAGONS will open the interactive tools using that browser. The allowed strings are “safari”, “chrome”, and “firefox”.

6.3.2.2. Importing libraries

1import glob
2
3import astrodata
4import gemini_instruments
5from recipe_system.reduction.coreReduce import Reduce
6from gempy.adlibrary import dataselect

The dataselect module will be used to create file lists for the biases, the flats, the arcs, the telluric star, and the science observations. The Reduce class is used to set up and run the data reduction.

6.3.2.3. Setting up the logger

We recommend using the DRAGONS logger. (See also Double messaging issue.)

7from gempy.utils import logutils
8logutils.config(file_name='f2ls_tutorial.log')

6.3.2.4. Set up the Calibration Service

Important

Remember to set up the calibration service.

Instructions to configure and use the calibration service are found in Setting up the Calibration Service, specifically the these sections: The Configuration File and Usage from the API.

We recommend that you clean up your working directory (playground) and delete the old calibration database before you start. Create a fresh one.

Start a fresh calibration database (caldb.init(wipe=True)) when you start a new example.

6.3.3. Inspect and fix headers

It is unfortunately too common that the last frame of a science or telluric sequence gets some, not all, of its header values from the next (yes, future) frame which is normally, in the case of F2, a flat. The key headers to pay attention too are EXPTIME and LNRS. They are both associate with descriptors.

Let’s inspect the exposure_time and the read_mode for the science and the telluric data. For a given sequence, all the values should match.

First, we create is a list of all the files in the playdata directory.

 9all_files = glob.glob('../playdata/example3/*.fits')
10all_files.sort()

We will select the telluric and science frames and display the values for the exposure_time and read_mode descriptors.

11sciframes = dataselect.select_data(
12    all_files,
13    [],
14    ['CAL'],
15    dataselect.expr_parser('observation_class=="science"')
16)
17tellurics = dataselect.select_data(
18    all_files,
19    [],
20    ['CAL'],
21    dataselect.expr_parser('observation_class!="science"')
22)
23
24for f in sciframes:
25    ad = astrodata.open(f)
26    print(f"{f}:\t{ad.exposure_time()}\t{ad.read_mode()}")
27
28for f in tellurics:
29    ad = astrodata.open(f)
30    print(f"{f}:\t{ad.exposure_time()}\t{ad.read_mode()}")

The science sequence:

../playdata/example3/S20230606S0083.fits           120.0           4
../playdata/example3/S20230606S0084.fits           120.0           4
../playdata/example3/S20230606S0085.fits           120.0           4
../playdata/example3/S20230606S0086.fits           120.0           4
../playdata/example3/S20230606S0087.fits           120.0           4
../playdata/example3/S20230606S0088.fits           120.0           4
../playdata/example3/S20230606S0089.fits           120.0           4
../playdata/example3/S20230606S0090.fits           120.0           4

The telluric sequence:

../playdata/example3/S20230606S0097.fits            15.0           1
../playdata/example3/S20230606S0098.fits            15.0           1
../playdata/example3/S20230606S0099.fits            15.0           1
../playdata/example3/S20230606S0100.fits            16.0           1

As you can see, the exposure time of the last file of the telluric sequence is 16 instead of 15, like the others. The “16” is from the next file, the flat. The data was taken with the correct exposure time, but the header is wrong.

Let’s fix that. So that you can rerun these same commands before, we first make a copy of the problematic file and give it a new name, leaving the original untouched. Obviously, with your own data, you would just fix the downloaded file once and for all, skipping the copy.

31import shutil
32shutil.copy('../playdata/example3/S20230606S0100.fits', '../playdata/example3/S20230606S0100_fixed.fits')
33
34ad = astrodata.open('../playdata/example3/S20230606S0100_fixed.fits')
35ad.phu['EXPTIME'] = 15.0
36ad.write(overwrite=True)

6.3.4. Create file lists

This data set contains science and calibration frames. For some programs, it could contain different observed targets and different exposure times depending on how you like to organize your raw data.

The DRAGONS data reduction pipeline does not organize the data for you. You have to do it. However, DRAGONS provides tools to help you.

The first step is to create input file lists. The tool “dataselect” helps with that. It uses Astrodata tags and “descriptors” to select the files and send the filenames to a text file that can then be fed to the Reduce class. (See the Astrodata User Manual for information about Astrodata and for a list of descriptors.)

Let’s get a fresh list of all the files in the playdata directory.

37all_files = glob.glob('../playdata/example3/*.fits')
38all_files.sort()

We will search that list for files with specific characteristics. We use the all_files list as an input to the function dataselect.select_data() . The function’s signature is:

select_data(inputs, tags=[], xtags=[], expression='True')

6.3.4.1. Several lists for the darks

The flats, the arcs, the telluric, and the science observations need a master dark matching their exposure time. We need a list of darks for each set. The exposure times are 16s for the flats, 180s for the arcs, 15s for the telluric frames, and 120s for the science frames.

A dark correction is unfortunately necessary for Flamingos 2 data due to strong and bright patterns that can interfere with the reduction if left present in the data.

39exposure_times = [15, 16, 120, 180]
40darks = {}
41for exptime in exposure_times:
42    darks[exptime] = dataselect.select_data(
43            all_files,
44            ['DARK'],
45            [],
46            dataselect.expr_parser(f'exposure_time=={exptime}')
47    )

6.3.4.2. Two lists for the flats

Two lamp-on flats were taken for this observation. One after the telluric sequence and one after the science sequence. The recipe to make the master flats will combine the flats if more than one is passed. We need each flat to be processed independently as they were taken at a slightly different telescope orientation. Therefore we need to separate them into two lists.

There are various ways to do that with dataselect. Here we show how to use a range of UT times. Note that we use the tag LAMPON in case the arc LAMPOFF was downloaded. As explained in the “Note” at the bottom of Example 3 - Datasets description, we do not use that lamp-off flat.

We first check the times at which the flats were taken. Then use that information to set our selection criteria to separate them.

48for f in dataselect.select_data(all_files, ['FLAT', 'LAMPON']):
49    ad = astrodata.open(f)
50    print(f"{f}\t{ad.ut_time()}\t{ad.disperser()}")
../playdata/example3/S20230606S0091.fits   2023-06-06 07:29:51
../playdata/example3/S20230606S0101.fits   2023-06-06 07:50:35
51flatsci = dataselect.select_data(
52    all_files,
53    ['FLAT', 'LAMPON'],
54    [],
55    dataselect.expr_parser('ut_time>="07:29:00" and ut_time<="07:30:00"')
56)
57flattel = dataselect.select_data(
58    all_files,
59    ['FLAT', 'LAMPON'],
60    [],
61    dataselect.expr_parser('ut_time>="07:50:00" and ut_time<="07:51:00"')
62)

6.3.4.3. A list for the arcs

There are two arcs. One for the telluric sequence, one for the science sequence. The recipe to measure the wavelength solution will not stack the arcs. Therefore, we can conveniently create just one list with all the raw arc observations in it and they will be processed independently.

63arcs = dataselect.select_data(all_files, ['ARC'])

6.3.4.4. A list for the telluric

DRAGONS does not recognize the telluric star as such. This is because, at Gemini, the observations are taken like science data and the Flamingos 2 headers do not explicitly state that the observation is a telluric standard. In most cases, the observation_class descriptor can be used to differentiate the telluric from the science observations, along with the rejection of the CAL tag to reject flats and arcs.

Also, since we had to fix the exposure time for one of the files and we created a copy instead of changing the original, we need to make sure only the telluric with the correct exposure time of 15 seconds get picked up. If you had fixed the original, mostly likely what you will do with your data, you wouldn’t need to select on the exposure time.

64tellurics = dataselect.select_data(
65    all_files,
66    [],
67    ['CAL'],
68    dataselect.expr_parser('observation_class!="science" and exposure_time==15')
69)

6.3.4.5. A list for the science observations

The science observations can be selected from the observation class, science, that is how they are differentiated from the telluric standards which are partnerCal.

If we had multiple targets, we would need to split them into separate lists. To inspect what we have we can use dataselect.

70all_science = dataselect.select_data(
71    all_files,
72    [],
73    ['CAL'],
74    dataselect.expr_parser('observation_class=="science"')
75)
76for sci in all_science:
77    ad = astrodata.open(sci)
78    print(sci, '  ', ad.object())
../playdata/example3/S20230606S0083.fits   Granat 1915+105
../playdata/example3/S20230606S0084.fits   Granat 1915+105
...
../playdata/example3/S20230606S0089.fits   Granat 1915+105
../playdata/example3/S20230606S0090.fits   Granat 1915+105

Here we only have one object from the same sequence. If we had multiple objects we could add the object name in the expression.

79sciframes = dataselect.select_data(
80    all_files,
81    [],
82    ['CAL'],
83    dataselect.expr_parser('observation_class=="science" and object=="Granat 1915+105"')
84)

6.3.5. Master Darks

Now that the lists are created, we just need to run Reduce on each list.

85for exptime in darks.keys():
86    reduce_darks = Reduce()
87    reduce_darks.files.extend(darks[exptime])
88    reduce_darks.runr()

6.3.6. Master Flat Fields

Flamingos 2 longslit flat fields are normally obtained at night along with the observation sequence to match the telescope and instrument flexure.

Flamingos 2 longslit master flat fields are created from the lamp-on flat(s) and a master dark matching the flats exposure times. Lamp-off flats are not used.

In Flamingos 2 spectroscopic observations a blocking filter is used. The sharp drops in signal at both end makes fitting a function difficult. Our recommendation is to set the region to be between the sharp drops and then fit a low-order cubic spline. This is a departure from what is being recommended for the other Gemini spectrographs where a high-order is recommended to fit all the wiggles.

For F2, only the overall shape should be fit. The detailed fitting will be taken care of when the sensitivity function is calculated using the telluric standard star.

We have defined appropriate defaults for the order and the region to use to normalize the flat for each grism and filter combinations. You should not have to modify them.

89reduce_flatsci = Reduce()
90reduce_flatsci.files.extend(flatsci)
91reduce_flatsci.runr()
92
93reduce_flattel = Reduce()
94reduce_flattel.files.extend(flattel)
95reduce_flattel.runr()

If you wish to see the fit, you can add reduce_flats.uparms = dict([('interactive', True)]) before the runr() call. For example, this is how HK flat fit looks like.

R3K-K flat normalization fit

6.3.7. Processed Arc - Wavelength Solution

Obtaining the wavelength solution for Flamingos 2 is fairly straightforward from the user’s perspective. There are usually a sufficient number of lines in the lamp. Note, however, that the lines becomes asymmetric as they move away from the center. There are provisions in the algorithm to account of that effect but the precision of the solution is limited.

The recipe for the arc requires a flat as it contains a map of the unilluminated areas. The master dark is required because of the strong pattern that is often horizontal and that could be interpreted as an emission line if not removed.

The solution is normally found automatically, but it does not hurt to visually inspect it in interactive mode.

96reduce_arcs = Reduce()
97reduce_arcs.files.extend(arcs)
98reduce_arcs.uparms = dict([('interactive', True),])
99reduce_arcs.runr()

The interactive tools are introduced in section Interactive tools.

6.3.8. Telluric Standard

The telluric standard observed after the science observation is “hip 98805”. The spectral type of the star is A2V.

To properly calculate and fit a telluric model to the star, we need to know its effective temperature. To properly scale the sensitivity function (to use the star as a spectrophotometric standard), we need to know the star’s magnitude. Those are inputs to the fitTelluric primitive.

In Eric Mamajek’s list “A Modern Mean Dwarf Stellar Color and Effective Temperature Sequence” (https://www.pas.rochester.edu/~emamajek/EEM_dwarf_UBVIJHK_colors_Teff.txt) the effective temperature of an A2V star as 8800 K. The precise value has only a small effect on the derived sensitivity and even less effect on the telluric correction, so the temperature from any reliable source can be used. Using Simbad, we find that the star has a magnitude of K=7.778, which is the closest waveband to our observation.

Note that the data are recognized by Astrodata as normal F2 longslit science spectra. To calculate the telluric correction, we need to specify the telluric recipe (reduceTelluric), otherwise the default science reduction will be run.

100reduce_telluric = Reduce()
101reduce_telluric.files.extend(tellurics)
102reduce_telluric.recipename = 'reduceTelluric'
103reduce_telluric.uparms = dict([
104            ('fitTelluric:bbtemp', 8800),
105            ('fitTelluric:magnitude', 'K=7.778'),
106            ('fitTelluric:interactive', True),
107            ('prepare:bad_wcs', 'new')
108            ])
109reduce_telluric.runr()

The prepare:bad_wcs=new is needed because the WCS in the raw data is not quite right and that leads to an incorrect sky subtraction and alignment. See Recognizing and fixing bad WCS for more information.

At the findApertures step, you will notice that the two negative beams are not the same depth. This indicates that the A and B beams do not have similar flux from the source. While clouds could explain some variations, in this case the two A positions have equal flux and the two B have equal flux, but the flux at the B position is a fraction of the flux at the A position.

The explanation is that the telescope movement, when supposedly moving along the slit to the B position, was not “along the slit”. Somehow the slit was misaligned. It is not understood why.

The consequence is that the final signal-to-noise is lower than expected. That slit misalignment is observed in the science sequence too.

Using the defaults, the fit and model spectrum look like this:

R3K-K telluric fit R3K-K sensitivity function fit

6.3.9. Science Observations

The science target is a superluminal microquasar. We are using only the last eight frames of the program’s sequence. The dither pattern is AABB-AABB. DRAGONS will subtract the dark current, flatfield the data, apply the wavelength calibration, subtract the sky, stack the aligned spectra. Then the source will be extracted to a 1D spectrum, the telluric features removed, and the spectrum flux calibrated.

Following the wavelength calibration, the default recipe has an optional step to adjust the wavelength zero point using the sky lines. By default, this step will NOT make any adjustment. We found that in general, the adjustment is so small as being in the noise. If you wish to make an adjustment, or try it out, see Adjusting the Wavelength Zeropoint to learn how.

Note

When the algorithm detects multiple sources, all of them will be extracted. Each extracted spectrum is stored in an individual extension in the output multi-extension FITS file.

This is what one raw image looks like.

Raw R3K-K image

To run the reduction, call the Reduce class on the science list. The calibrations will be automatically associated. It is recommended to run the reduction in interactive mode to allow inspection of and control over the critical steps.

There are many sources along the slit. We know that we are interested only in the brightest one. Therefore, we set the maximum number of sources to find to 1 in findApertures.

110reduce_science = Reduce()
111reduce_science.files.extend(sciframes)
112reduce_science.uparms = dict([
113        ('interactive', True),
114        ('findApertures:max_apertures', 1)
115        ])
116reduce_science.runr()

As explained above in the telluric section, the slit was misaligned during the observation resulting in the source slipping out of the slit when the telescope was dithered to the B position. The flux in the B position is a fraction of the flux in the A position. This can be seen in the uneven negative beams in the findApertures profile.

In telluricCorrect, applying a shift of -0.1 helps better remove the telluric features in the spectrum.

The 2D spectrum before extraction looks like this, with blue wavelengths at the bottom and the red-end at the top.

R3K-K 2D spectrum

The 1D extracted spectrum before telluric correction or flux calibration, obtained by adding ('extractSpectra:write_outputs', True) to the uparms dictionary, looks like this.

R3K-K 1D extracted spectrum before telluric correction or flux calibration

The 1D extracted spectrum after telluric correction but before flux calibration, obtained by adding ('telluricCorrect:write_outputs', True) to the uparms dictionary, looks like this.

R3K-K 1D extracted spectrum after telluric correction and before flux calibration

And the final spectrum, corrected for telluric features and flux calibrated.

from gempy.adlibrary import plotting
ad = astrodata.open(reduce_science.output_filenames[0])
plotting.dgsplot_matplotlib(ad, 1, kwargs={})
R3K-K 1D extracted spectrum after telluric correction and flux calibration