import matplotlib
matplotlib.use('Agg')
from astropy.io import fits as pyfits
import numpy as np
from importlib import import_module
from extinction import fitzpatrick99 as f99
from extinction import remove
from lmfit import Model
from lmfit.models import GaussianModel, LorentzianModel
from astropy.convolution import convolve, Box1DKernel
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.ndimage import gaussian_filter
import sys, os, time, datetime
import signal, gc
sys.path.insert(0, './params_alt')
Define the fitting functions used for lmfit (continuum and Fe-template); adapted/copied from other code
def powerLaw(x, amp, exp):
"""Model for powerlaw"""
return amp * (x / 5100.0) ** exp
Fe_in = np.genfromtxt('Vestergaard.txt').T
Fe_temp = interp1d(Fe_in[0], Fe_in[1], fill_value='extrapolate')
del Fe_in
def FeUV(x, redshift, amp, sigma, limit=(2000, 3089)):
"""Final output for FeII template, smoothed with gaussian filter"""
x = np.array([xi for xi in x if limit[0] < xi / (1. + redshift) < limit[1]])
Fez = amp * Fe_temp(x / (1. + redshift))
return gaussian_filter(Fez, sigma)
SpectrumError class
class SpectrumError(Exception):
"""Used to control flow in loops that call functions from the Spectrum class, as well as in the Spectrum method 'choose_model'. Necessary due to possible error in lmfit chi2 fitting, called in the Spectrum method 'run_fit' """
pass
Spectrum class
class Spectrum:
"""Spectral data for a single epoch, which will be adjusted according to airmass for BOSS spectra and according to OIII scaling for WHT/MMT/Magellan scaling. The adjusted spectrum will subsequently be fitted using the lmfit routine"""
def init(self, full_name, data=None, airmass=0, correction=1, output='./output', z=1, A_v=0, lower=None, upper=None, fe_yn='no', Fe_template='Vestergaard.txt', path=None, fitspath=None, Spath=None, failed_runs='failedrunslist'):
self.full_name = full_name
self.obs_date = self.full_name[8:]
self.obj = self.full_name[:7]
self.data = data
self.data_fit = None
self.airmass = airmass
self.correction = correction
self.output = output # Ensure output is set to a valid directory
self.z = z
self.A_v = A_v
self.lower = lower
self.upper = upper
self.fe_yn = fe_yn
self.cmod = None
self.pars = None
self.fit_out = None
self.mod = None
self.survey = None
self.path = path
self.Spath = Spath
self.fitspath = fitspath
self.failed_runs = failed_runs
self.final_pars = {}
self.final_fits = {}
self.line = 'UV' # this definition is for labeling only
def del(self):
gc.collect()
print(f'Finished with spectrum for {self.full_name}')
def load(self):
"""Load the spectral data into a numpy array. The input data can be either a text file (format = wavelength, flux, flux_err), or an SDSS formatted fits file"""
if self.full_name.endswith('.fits'):
hdu_in = pyfits.open(os.path.join(self.Spath, self.full_name))
tb = hdu_in[1].data
hdu_in.close()
lam = tb.field('loglam')
base = np.full(len(lam), 10)
lam = np.power(base, lam)
flux = tb.field(0) * 1e-17
flux_err = tb.field('ivar')
id_z = np.where(flux_err == 0)
lam = np.delete(lam, id_z)
flux = np.delete(flux, id_z)
flux_err = np.delete(flux_err, id_z)
flux_err = (1 / np.sqrt(flux_err)) * 1e-17
self.data = np.array([lam, flux, flux_err]).T
self.obs_date = str(self.full_name[10:15])
else:
if os.path.isfile(os.path.join(self.Spath, 'sdss_' + self.full_name)):
self.mod = import_module('sdss_' + self.obj)
self.data = np.loadtxt(os.path.join(self.Spath, 'sdss_' + self.full_name))
self.survey = 'sdss'
else:
try:
self.data = np.loadtxt(os.path.join(self.Spath, self.full_name))
self.mod = import_module(self.obj)
except Exception:
print(f'Error: could not load data for {self.full_name}')
self.z = self.mod.z_est
self.A_v = self.mod.A_v
self.lower = self.mod.lower
self.upper = self.mod.upper
self.fe_yn = self.mod.fev
def load_corrected_redshift(self):
"""In case a clearly erroneous redshift is loaded as an initial estimate, try to solve the issue by loading the redshift from the SDSS spectrum file itself"""
hdu_in = pyfits.open(os.path.join(self.Spath, self.full_name))
try:
if hdu_in[2].data['z'] > 0:
self.z = hdu_in[2].data['z']
else:
self.z = np.average(hdu_in[3].data['linez'][np.where(hdu_in[3].data['linez'] > 0)])
except Exception:
self.z = 0
def adjust_boss_spectra(self, airmass=None):
"""Apply the correction from Harris et al. to the BOSS spectra. Use the preloaded correction function, and interpolate for the bins if necessary. The airmass used for the correction function is the average airmass over the period of observation, calculated by taking the mean of the airmasses indicated for the individual exposures in the SDSS spectrum files, weighted by the exposure times. The spectrum is trimmed to match the BOSS correction function limits, if necessary"""
if self.survey == 'sdss' and int(self.obs_date) > 55000: # The MJD is selected to be in between the SDSS I/II and SDSS III epochs
self.data = self.data[(self.data[:, 0] >= self.corr_min) & (self.data[:, 0] <= self.corr_max)]
if airmass:
self.airmass = airmass
else:
airmass_list = []
exposure_times = []
hdu_list = pyfits.open(os.path.join(self.fitspath, self.obj, 'sdss_' + self.obj + '_' + self.obs_date + '.fits'))
for ii in range(4, len(hdu_list)):
if hdu_list[ii].header['EXTNAME'][0] == 'B':
airmass_list.append(hdu_list[ii].header['AIRMASS'])
exposure_times.append(hdu_list[ii].header['EXPTIME'])
hdu_list.close()
airmass_list = np.array(airmass_list)
exposure_times = np.array(exposure_times)
self.airmass = np.average(airmass_list, weights=exposure_times)
self.data[:, 1] = self.data[:, 1] * (self.corr_slope(self.data[:, 0]) * self.airmass + self.corr_intercept(self.data[:, 0]))
self.data[:, 2] = self.data[:, 2] * abs(self.corr_slope(self.data[:, 0]) * self.airmass)
def adjust_non_boss_spectra(self):
"""Apply the correction function to the non-BOSS spectra, which are manually determined for each spectrum. The correction will only be applied if the initial wavelength solution is within 1% of the true wavelength solution, otherwise the correction will be deemed inapplicable"""
try:
wlen_corr = self.corr_fun(self.data[:, 0])
except Exception:
print(f'Could not load wavelength correction for {self.full_name}')
return
if np.isclose(wlen_corr, self.data[:, 0], atol=0.01).all():
self.data[:, 1] = self.data[:, 1] * wlen_corr
self.data[:, 2] = self.data[:, 2] * wlen_corr
else:
print(f'Wavelength correction failed for {self.full_name}')
def trim(self):
"""Trim the spectrum to the given bounds, if they exist"""
if self.lower and self.upper:
self.data_fit = self.data[(self.data[:, 0] >= self.lower) & (self.data[:, 0] <= self.upper)]
else:
self.data_fit = self.data
def plot_spec(self, title, fit):
"""Plot the spectrum"""
fig, ax = plt.subplots()
ax.plot(self.data[:, 0], self.data[:, 1], 'k-', label='Data')
if fit is not None:
ax.plot(self.data[:, 0], fit, 'r-', label='Fit')
ax.set_xlabel('Wavelength [Angstrom]')
ax.set_ylabel('Flux')
ax.set_title(title)
ax.legend()
plt.savefig(f'{self.full_name}fit.png')
plt.close(fig)
def run_fit(self):
"""Run the fitting procedure. This involves trimming the spectrum, creating the model, setting the initial parameters, and performing the fit"""
self.trim()
# Create the initial model
self.cmod = Model(powerLaw)
self.pars = self.cmod.make_params()
self.pars['amp'].set(value=1.0)
self.pars['exp'].set(value=-1.5)
# Add FeII template if necessary
if self.fe_yn == 'yes':
self.cmod += Model(FeUV, prefix='Fe')
self.pars.update(self.cmod.make_params())
self.pars['Fe_amp'].set(value=0.1)
self.pars['Fe_sigma'].set(value=2.0)
self.pars['Fe_redshift'].set(value=self.z)
# Run the fit
self.fit_out = self.cmod.fit(self.data_fit[:, 1], x=self.data_fit[:, 0], params=self.pars)
self.final_pars = self.fit_out.params
self.final_fits = self.fit_out.best_fit
def save_output(self):
"""Save the output to a file"""
if not os.path.exists(self.output):
os.makedirs(self.output)
with open(os.path.join(self.output, f'{self.full_name}_fit.txt'), 'w') as f:
for key, val in self.final_pars.items():
f.write(f'{key}: {val.value}\n')
np.savetxt(os.path.join(self.output, f'{self.full_name}_fit.dat'), self.final_fits)
Execute the fitting procedure for the sample spectrum
def main():
spec_list = ['trial.fits']
for spec in spec_list:
sp = Spectrum(full_name=spec, Spath='.') # ‘.’ indicates current directory
sp.load()
sp.adjust_boss_spectra()
sp.run_fit()
sp.save_output()
sp.plot_spec(title=f'Spectrum fit for {spec}', fit=sp.final_fits)
print(f'Finished processing {spec}')
if name == 'main':
main()
here;s the whole code, remember to put the apostophes as ' not the curly ones