Copy, clone or save

Copy

Spectrum, Image and Cube objects provide a copy method that returns a deep copy of these objects. For example:

In [1]: from mpdaf.obj import Spectrum

In [2]: import numpy as np

In [3]: specline = Spectrum('obj/Spectrum_lines.fits')

In [4]: specline.info()
[INFO] 2048 Spectrum (obj/Spectrum_lines.fits)
[INFO] .data(2048) (no unit), .var(2048)
[INFO] wavelength: min:6550.00 max:9120.00 step:1.26 Angstrom

In [5]: specline.data[42]
Out[5]: 3.7648298740386963

In [6]: spe = specline.copy()

In [7]: specline.data = np.ones(specline.shape)

In [8]: spe.info()
[INFO] 2048 Spectrum (obj/Spectrum_lines.fits)
[INFO] .data(2048) (no unit), .var(2048)
[INFO] wavelength: min:6550.00 max:9120.00 step:1.26 Angstrom

In [9]: spe.data[42]
Out[9]: 3.7648298740386963

Clone

The clone method returns a new object of the same shape and coordinates as the original object. However the .data and .var attributes of the cloned object are set to None by default. After cloning an object, new numpy data and/or variance arrays can be assigned to the .data and .var properties of the clone. In the following example, an existing spectrum is cloned, and then the clone is assigned a zero-filled data array.

In [10]: spe2 = spe.clone()

In [11]: spe2.info()
[INFO] 2048 Spectrum (no name)
[INFO] no data (no unit), no noise
[INFO] wavelength: min:6550.00 max:9120.00 step:1.26 Angstrom

In [12]: spe2.data = np.zeros(spe.shape)

In [13]: spe2.info()
[INFO] 2048 Spectrum (no name)
[INFO] .data(2048) (no unit), no noise
[INFO] wavelength: min:6550.00 max:9120.00 step:1.26 Angstrom

In [14]: spe2.data[42]
Out[14]: 0.0

Alternatively, the clone method can be passed functions that generate the data and variances arrays of the cloned object. The clone method passes these functions the shape of the required data or variance array, and the functions are expected to return an array of that shape. For example, numpy provides functions like np.zeros and np.ones that can be used for this purpose. In the following demonstration, an existing spectrum, spe, is cloned and the cloning method is passed np.zeros, to create a zero-filled data array.

In [15]: spe3 = spe.clone(data_init=np.zeros)

In [16]: spe3.info()
[INFO] 2048 Spectrum (no name)
[INFO] .data(2048) (no unit), no noise
[INFO] wavelength: min:6550.00 max:9120.00 step:1.26 Angstrom

In [17]: spe3.data[42]
Out[17]: 0.0

Save

The Spectrum.write, Image.write and Cube.write methods save the contents of a Spectrum, Image or Cube to a FITS file. The data are saved in a DATA extension, and any variances are saved in a STAT extension. Depending on the value of the savemask option, the mask array is either saved as a DQ extension (the default) or masked data elements are replaced by NaN in the DATA extension and the mask array is not saved.

The intermediate methods get_data_hdu and get_stat_hdu can also be used to generate astropy.io.fits.ImageHDU objects that correspond to the DATA and STAT extensions.