def fit_res(x, res): fitter = fitting.LevMarLSQFitter() p1_init = powerlaws.PowerLaw1D(res[:, 0].max(), 1, 0.5) p2_init = powerlaws.PowerLaw1D(res[:, 1].max(), 1, 0.5) p3_init = powerlaws.PowerLaw1D(res[:, 2].max(), 1, 0.5) p1_init.alpha.fixed = True p2_init.alpha.fixed = True p3_init.alpha.fixed = True p1_fit = fitter(p1_init, x, res[:, 0]) p2_fit = fitter(p2_init, x, res[:, 1]) p3_fit = fitter(p3_init, x, res[:, 2]) return p1_fit, p2_fit, p3_fit
def test_powerlaw(scale=5., alpha=2.): x = np.linspace(10, 100) y = scale * (x)**(-alpha) plm = powerlaws.PowerLaw1D(1, 1, 1) fitter = fitting.LevMarLSQFitter() result = fitter(plm, x, y) print("Result: ", result) print("plm.params: ", plm) return plm
def from_tree_transform(self, node): return powerlaws.PowerLaw1D(amplitude=node['amplitude'], x_0=node['x_0'], alpha=node['alpha'])
def getAlpha(spec, wave_center, plot=False, plotname=None): """ spec = {'Wavelength(um)': wave, 'Flux_Density(Jy)': flux, 'Uncertainty(Jy)': unc} """ from astropy.modeling import models, fitting, powerlaws from scipy.interpolate import interp1d import astropy.constants as const import numpy as np c = const.c.cgs.value # initial guess x_ref = c / 1e5 / wave_center f_flux = interp1d(c / 1e5 / spec['Wavelength(um)'], spec['Flux_Density(Jy)']) amp = f_flux(x_ref) alpha = 0 # unit conversions freq_dum = (c/1e5/spec['Wavelength(um)'])\ [(c/1e5/spec['Wavelength(um)']>= x_ref-100) & (c/1e5/spec['Wavelength(um)']<= x_ref+100)] flux_dum = spec['Flux_Density(Jy)']\ [(c/1e5/spec['Wavelength(um)']>= x_ref-100) & (c/1e5/spec['Wavelength(um)']<= x_ref+100)] pow_model = powerlaws.PowerLaw1D(amp, x_ref, alpha) fitter = fitting.LevMarLSQFitter() fit = fitter(pow_model, freq_dum, flux_dum) alpha = -fit.alpha.value if fitter.fit_info['param_cov'] is None: alpha_err = np.nan else: alpha_err = fitter.fit_info['param_cov'][2, 2]**0.5 if plot: # to avoid X server error import matplotlib as mpl mpl.use('Agg') # import matplotlib.pyplot as plt fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) ax.plot(freq_dum, flux_dum, 'o') ax.plot(freq_dum, fit(freq_dum), '-', color='k') ax.text(0.6, 0.05, r'$\alpha_{500} = %3.2f \pm %3.2f$' % (alpha, alpha_err), transform=ax.transAxes, fontsize=18) [ ax.spines[axis].set_linewidth(1.5) for axis in ['top', 'bottom', 'left', 'right'] ] ax.minorticks_on() ax.tick_params('both', labelsize=18, width=1.5, which='major', pad=10, length=5) ax.tick_params('both', labelsize=18, width=1.5, which='minor', pad=10, length=2.5) ax.set_xlabel('Frequency [GHz]', fontsize=18) ax.set_ylabel('Flux Density [Jy]', fontsize=18) ax.set_xlim([400, 2000]) fig.savefig(plotname + 'Alpha500Hyperion.pdf', format='pdf', dpi=300, bbox_inches='tight') fig.clf() return (alpha, alpha_err)
def spire_spectral_index(outdir, obsid, obj): # to avoid X server error import matplotlib as mpl mpl.use('Agg') # # Note that the spectral index works in frequency import matplotlib.pyplot as plt from astropy.modeling import models, fitting, powerlaws from scipy.interpolate import interp1d import astropy.constants as const from astropy.io import ascii import numpy as np c = const.c.cgs.value # Read in spectra spire_sect = ascii.read(outdir + obsid + '_spire_sect.txt', data_start=4) fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) spire, = ax.plot(c / 1e5 / spire_sect['wave_segm1_0'], spire_sect['flux_segm1_0'], linewidth=1, color='b') ax.plot(c / 1e5 / spire_sect['wave_segm2_0'], spire_sect['flux_segm2_0'], linewidth=1, color='r') f_ssw = interp1d(c / 1e5 / spire_sect['wave_segm2_0'], spire_sect['flux_segm2_0']) f_slw = interp1d(c / 1e5 / spire_sect['wave_segm1_0'], spire_sect['flux_segm1_0']) fitted_alpha = [] fitted_alpha_err = [] for band in [250, 350, 500]: x_ref = c / 1e5 / band if band != 250: amp = f_slw(x_ref) freq_dum = (c/1e5/spire_sect['wave_segm1_0'])\ [(c/1e5/spire_sect['wave_segm1_0'] >= x_ref-100) & (c/1e5/spire_sect['wave_segm1_0'] <= x_ref+100)] flux_dum = spire_sect['flux_segm1_0']\ [(c/1e5/spire_sect['wave_segm1_0'] >= x_ref-100) & (c/1e5/spire_sect['wave_segm1_0'] <= x_ref+100)] else: amp = f_ssw(x_ref) freq_dum = (c/1e5/spire_sect['wave_segm2_0'])\ [(c/1e5/spire_sect['wave_segm2_0'] >= x_ref-100) & (c/1e5/spire_sect['wave_segm2_0'] <= x_ref+100)] flux_dum = spire_sect['flux_segm2_0']\ [(c/1e5/spire_sect['wave_segm2_0'] >= x_ref-100) & (c/1e5/spire_sect['wave_segm2_0'] <= x_ref+100)] alpha = 0 pow_model = powerlaws.PowerLaw1D(amp, x_ref, alpha) fitter = fitting.LevMarLSQFitter() fit = fitter(pow_model, freq_dum, flux_dum) ax.plot(freq_dum, fit(freq_dum), '-', color='k') # take negative sign because the frequency array is reversed fitted_alpha.append(-fit.alpha.value) # the uncertainty part somehow does work on bettyjo. # probably something wrong with the python config if 'bettyjo' not in archive_dir: fitted_alpha_err.append(fitter.fit_info['param_cov'][2, 2]**0.5) print - fit.alpha.value, '+/-', fitter.fit_info['param_cov'][ 2, 2]**0.5 else: fitted_alpha_err.append(0) print - fit.alpha.value ax.text(0.35, 0.15, r'$\alpha_{250,350,500} = %3.2f, %3.2f, %3.2f$' % (fitted_alpha[0], fitted_alpha[1], fitted_alpha[2]), transform=ax.transAxes, fontsize=18) ax.text(0.35, 0.05, r'$\sigma_{\alpha}\,(250,350,500) = %5.3f, %5.3f, %5.3f$' % (fitted_alpha_err[0], fitted_alpha_err[1], fitted_alpha_err[2]), transform=ax.transAxes, fontsize=18) [ ax.spines[axis].set_linewidth(1.5) for axis in ['top', 'bottom', 'left', 'right'] ] ax.minorticks_on() ax.tick_params('both', labelsize=18, width=1.5, which='major', pad=10, length=5) ax.tick_params('both', labelsize=18, width=1.5, which='minor', pad=10, length=2.5) ax.set_xlabel('Frequency [GHz]', fontsize=18) ax.set_ylabel('Flux Density [Jy]', fontsize=18) ax.set_xlim([400, 2000]) fig.savefig(outdir + obj + '_spire_alpha.pdf', format='pdf', dpi=300, bbox_inches='tight') fig.clf() # write out the alpha index foo = open(outdir + obj + '_alpha.txt', 'w') foo.write('250um \t 350um \t 500um \n') foo.write('%8.6f \t %8.6f \t %8.6f \n' % (fitted_alpha[0], fitted_alpha[1], fitted_alpha[2])) foo.write('%8.6f \t %8.6f \t %8.6f \n' % (fitted_alpha_err[0], fitted_alpha_err[1], fitted_alpha_err[2])) foo.close()