This repository contains a Python script to convert the data units in a FITS file from MJy/sr to erg/cm²/sr/s/Hz reading the unit information in the FITS header. The script also updates the BUNIT header in the FITS file to reflect the new units.
- Python 3.x
- Astropy
- Numpy
- Matplotlib
You can install the necessary Python packages using:
pip install astropy numpy matplotlib
The script convert_to_erg.py
performs the following steps:
- Import Libraries: Imports necessary libraries for file handling, data manipulation, and FITS file operations.
- Set Up Variables: Defines the source name and file names for input and output FITS files.
- Open FITS File: Reads the FITS file and extracts the data and header from the first extension.
- Update Header and Data: Changes the BUNIT header to 'erg/cm2/sr/s/Hz' and converts the data units from MJy/sr to erg/cm²/sr/s/Hz.
- Write New FITS File: Writes the updated data and header to a new FITS file.
- Check New File Units: Opens the new FITS file to verify the updated units and data.
- Print Execution Time: Prints the time taken to execute the script.
import os
import math
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from datetime import datetime
Define the source name and file names for the input and output FITS files.
source_name = "ngc7538_160micron"
original_fits = source_name + '.fits'
fits_image_filename = original_fits
new_fits = source_name + '_erg.fits'
Reads the FITS file and extracts the data and header from the first extension.
hdul = fits.open(fits_image_filename)
data = hdul[1].data # assume the first extension is an image
header = hdul[1].header
Changes the BUNIT header to 'erg/cm2/sr/s/Hz' and converts the data units from MJy/sr to erg/cm²/sr/s/Hz.
# change BUNIT
header['BUNIT'] = 'erg/cm2/sr/s/Hz'
# multiply the data with 1e-23 for erg/cm2/sr/s/Hz conversion from MJy/sr
hdul[1].data = (data[:] * 1e-23)/(((header['CDELT2'] * 3600)**2)*2.35e-11)
print('old = ', data[:])
Writes the updated data and header to a new FITS file.
# Write our the new file
hdul.writeto(new_fits)
hdul.close()
Opens the new FITS file to verify the updated units and data.
#checking the new file units
hdu2 = fits.open(new_fits)
data_erg = hdu2[1].data # assume the first extension is an image
header2 = hdu2[1].header
print('NEW = ', data_erg[:])
Prints the time taken to execute the script.
print('The time you spent (h:mm:ss.s) is :', datetime.now() - startTime)
print("Good job! At least, you code has worked without any interruption.")
Ensure that the FITS file ngc7538_160micron.fits
is in the same directory as the script. Run the script using:
python convert_to_erg.py