def specmaker(plot, x, y, xmin, xmax, center, trans, ymax, ymin, moddata, thickmoddata): plot.set_xlim(xmin.value, xmax.value) plot.axvline(x=center, color='green', linestyle='--', linewidth=2.0, label='CH3OH') plot.set_ylim(ymin, ymax) plot.plot(x, y, drawstyle='steps') plot.plot(x, moddata, color='brown', label=(r'$\tau<<1$')) plot.plot(x, thickmoddata, color='cyan', label=(r'$\tau>1')) plot.set_title(trans) for mols in range(len(contaminants)): contamlabel = 0 linelistcheck = 0 for lis in linelistlist: if linelistcheck > 0: #print(contaminants[mols]+' already plotted.') break else: contamtable = Splatalogue.query_lines( (mins[col + rowoffset] * (1 + z)), (maxs[col + rowoffset] * (1 + z)), energy_max=1840, energy_type='eu_k', chemical_name=contaminants[mols], line_lists=[lis], show_upper_degeneracy=True) if len(contamtable) == 0: print('No ' + contaminants[mols] + ' lines in ' + lis + ' frequency range ' + str(mins[col + rowoffset]) + '-' + str(maxs[col + rowoffset]) + '.') continue else: linelistcheck += 1 print('(' + lis + ') ' + contaminants[mols] + ' contaminants identified for CH3OH ' + mqns[col + rowoffset] + ' at ' + str(mins[col + rowoffset] + linewidth) + ' GHz.') table = utils.minimize_table(contamtable) line = (table['Freq'] * 10**9) / (1 + z) #Redshifted qns = table['QNs'] for g in range(len(table)): if g == 0 and contamlabel == 0: contamline = ax[row, col].axvline( x=line[g], color=colors[mols], label=contaminants[mols]) print(contaminants[mols]) contamlabel += 1 else: ax[row, col].axvline(x=line[g], color=colors[mols]) '''
def mt(x): return minimize_table( x, columns=[ 'Species', 'Chemical Name', 'Resolved QNs', 'Freq-GHz(rest frame,redshifted)', 'Meas Freq-GHz(rest frame,redshifted)', 'Log<sub>10</sub> (A<sub>ij</sub>)', 'E_U (K)', 'Upper State Degeneracy', ], )
def find_lines_in_header(header, return_pixels=False, **kwargs): """ Create a dictionary of line name: line position (in pixel units or frequency) for later extraction Parameters ---------- header: astropy.io.fits.Header return_pixels: bool Return the line dictionary with pixel units in the header? Otherwises, returns frequency (in GHz) Examples -------- >>> from astropy.io import fits >>> header = fits.getheader('cubefile.fits') >>> linedict = find_lines_in_header(header, energy_max=50, ... energy_type='eu_k') """ naxis3 = header["NAXIS3"] wcs = WCS(header) xarr = np.arange(naxis3) r, d = wcs.wcs.crval[:2] frequencies = wcs.wcs_pix2world([(r, d, z) for z in xarr], 0)[:, 2] unit = u.Unit(header["CUNIT3"]) lines = splatutils.minimize_table( Splatalogue.query_lines(frequencies.min() * unit, frequencies.max() * unit, **kwargs) ) if return_pixels: def nearest(x): return np.argmin(np.abs(frequencies - x)) linedict = {row["Species"]: nearest(row["Freq"] * 1e9) for row in lines} else: linedict = {row["Species"]: row["Freq"] for row in lines} return linedict
header = fits.getheader(fname) freqs = cube.spectral_axis numchans = int( round( np.abs((linewidth.to('Hz')).value / (freqs[1].value - freqs[0].value)))) freq_max = freqs[np.argmin(freqs)] * (1 + z) #215*u.GHz freq_min = freqs[np.argmax(freqs)] * (1 + z) #235*u.GHz methanol_table = utils.minimize_table( Splatalogue.query_lines(freq_min, freq_max, chemical_name=' CH3OH ', energy_max=1840, energy_type='eu_k', line_lists=[linelist], show_upper_degeneracy=True)) mlines = (methanol_table['Freq'] * 10**9) / (1 + z) mqns = methanol_table['QNs'] temptable = Splatalogue.query_lines(freq_min, freq_max, chemical_name=chem, energy_max=1840, energy_type='eu_k', line_lists=[linelist], show_upper_degeneracy=True) if len(temptable) == 0:
freq_max = freqs[(len(freqs) - 1)] * (1 + z) #235*u.GHz assert freq_max > freq_min, 'Decreasing frequency axis' linewidth = 0.00485 * u.GHz #Half of original 0.0097GHz lw2 = linewidth / 4 '''Generate methanol table for contaminant search''' methanol_table = Splatalogue.query_lines(freq_min, freq_max, chemical_name=' CH3OH ', energy_max=1840, energy_type='eu_k', line_lists=['JPL'], show_upper_degeneracy=True) minmethtable = utils.minimize_table(methanol_table) mlines = (minmethtable['Freq'] * 10**9) / (1 + z) * u.Hz mqns = minmethtable['QNs'] meuks = minmethtable['EU_K'] * u.K meujs = [] for euk in meuks: meujs.append(KtoJ(euk)) mdegs = methanol_table['Upper State Degeneracy'] testline = 8 plotwidth = linewidth * 1.5 lwvel = vradio(lw2, mlines[testline]) print(f'Transition: {mqns[testline]}\nEU_K: {meuks[testline]}') spwwindow = cube.spectral_slab((mlines[testline] - plotwidth),
def line_ids(fn): results = [] Ulines = [] sp = pyspeckit.Spectrum(fn) # this is a bit hackier than I like # we'll do all our measurements in Kelvin! beams = Beams.from_fits_bintable(fits.open(fn)[1]) factors = jtok_factors(beams, sp.xarr.to(u.GHz)) sp.data = sp.data * factors sp.unit = u.K # want km/s - reference will be ~middle of SPW sp.xarr.convert_to_unit(u.km / u.s) med = np.nanmedian(sp.data) mad = stats.mad_std(sp.data - med) detections = (sp.data - med) > 5 * mad labels, ct = label(detections) for labelid in range(1, ct + 1): ssp = sp[labels == labelid] try: ssp.xarr.convert_to_unit(u.GHz) ssp.specfit() ssp.specfit.parinfo frq = ssp.specfit.parinfo['SHIFT0'].value * ssp.xarr.unit except Exception as ex: print(ex) frq = ssp.xarr.to(u.GHz).mean() sq = Splatalogue.query_lines( frq * (1 + 0 / 3e5), frq * (1 + 75 / 3e5), # 30/3e5 original lower bound only_astronomically_observed=True) if len(sq) > 0: tbl = utils.minimize_table(sq) try: total_intensity = ssp.data.sum() * np.abs( ssp.xarr.to(u.km / u.s).cdelt()) except ValueError: total_intensity = ssp.data.sum() * np.abs( sp.xarr.to(u.km / u.s).cdelt()) peak_intensity = ssp.data.max() tbl.add_column(Column(data=total_intensity, name='TotalIntensity')) tbl.add_column(Column(data=peak_intensity, name='PeakIntensity')) tbl.add_column(Column(data=mad, name='RMS')) tbl.add_column( Column(data=u.Quantity((-(frq.to(u.GHz).value - tbl['Freq']) / tbl['Freq'] * constants.c), u.km / u.s), name='Velocity')) # print(tbl.pprint(max_width=200)) results.append(tbl) else: log.warning(f"Frequency {frq.to(u.GHz)} had no hits") Ulines.append(frq) try: match_table = table.vstack(results) except ValueError: pass else: # match_table.remove_column('QNs') match_table = table.unique(match_table, keys='Species') match_table.sort('Freq') print(match_table.pprint(max_width=200)) print(match_table['Species', 'Freq', 'Velocity']) # match_table.write(f"line_fit_table_{suffix}.ipac", format='ascii.ipac', overwrite=True) return match_table
8:'eight', 9:'nine',} tbls = {} for line in (1,2,3,4,5,6,7,8,9): reline = re.compile('^{n}\({n}\).*-{n}'.format(n=line)) tbl = utils.minimize_table(nh3[np.array([bool(reline.search(x)) if bool(x) else False for x in nh3['Resolved QNs']], dtype='bool')], columns=['Species', 'Chemical Name', 'Resolved QNs', 'Freq-GHz', 'Meas Freq-GHz', 'Log<sub>10</sub> (A<sub>ij</sub>)', 'CDMS/JPL Intensity', 'Linelist', 'E_U (K)', 'Upper State Degeneracy']) if len(tbl) == 0: pass # Select only TopModel lines from CDMS/JPL tbls[line] = tbl[tbl['Linelist'] == 'TopModel'] for par in ('tau_wts','voff_lines','aval','freq'): print(par) for line in (1,2,3,4,5,6,7,8): # 9 not available
assert freq_max > freq_min, 'Decreasing frequency axis' #linewidth=0.00485*u.GHz#Half of original 0.0097GHz #lw2=linewidth/8 originallinewidth = (11231152.36688232 * u.Hz / 2) '''Generate methanol table for use during contaminant search''' methanol_table = Splatalogue.query_lines( freq_min, freq_max, chemical_name=' CH3OH ', energy_max=1840, energy_type='eu_k', line_lists=['JPL', 'CDMS', 'SLAIM', 'ToyoMA', 'OSU', 'RFI', 'Lisa'], show_upper_degeneracy=True) minmethtable = utils.minimize_table(methanol_table) mlines = ((minmethtable['Freq'] * 10**9) / (1 + z) * u.Hz).to('MHz') mqns = minmethtable['QNs'] meuks = minmethtable['EU_K'] * u.K meujs = [] for euk in meuks: meujs.append(KtoJ(euk)) mdegs = methanol_table['Upper State Degeneracy'] mlog10aijs = minmethtable['log10_Aij'] maijs = 10**mlog10aijs * u.s**-1 '''Generate species table for contaminant search''' species_table = Splatalogue.query_lines( freq_min, freq_max, chemical_name=specieslist[molnum], energy_max=1840,
f'Line {detections[row,1]} at {(line*u.Hz).to("GHz")} skipped; out of frequency range' ) for mol, molname, linecolor in zip(otherspecies, specplotnames, colors): firstline = True temptable = Splatalogue.query_lines(emitxlims[0] * u.Hz, emitxlims[1] * u.Hz, energy_max=1840, energy_type='eu_k', chemical_name=mol, line_lists=['CDMS', 'JPL', 'SLAIM'], show_upper_degeneracy=True, only_NRAO_recommended=True) if len(temptable) != 0: print(f'{mol} lines available in range.') table = utils.minimize_table(temptable) otherlines = (table['Freq'] * 10**9 * u.Hz) / (1 + z) #Redshifted euks = table['EU_K'] qns = table['QNs'] for line, euk, qn in zip(otherlines, euks, qns): if euk < 1000: closest_channel = cube.closest_spectral_channel(line) if spw[closest_channel] >= 3 * stdvalue: if firstline: print('Begin plotting') plt.axvline(x=line.value, linestyle='--', color=linecolor, label=molname) print(f'{qn}; {euk} K; {line} Hz') firstline = False
# SLAIM is missing an important (10,5) transition slaim = Splatalogue.query_lines(210*u.GHz, 235*u.GHz, chemical_name=' HNCO ', energy_max=2500, energy_type='eu_k', line_lists=['SLAIM'], show_upper_degeneracy=True) freqs = np.array(slaim['Freq-GHz'])*u.GHz aij = slaim['Log<sub>10</sub> (A<sub>ij</sub>)'] deg = slaim['Upper State Degeneracy'] EU = (np.array(slaim['E_U (K)'])*u.K*constants.k_B).to(u.erg).value cdmsplat_ = Splatalogue.query_lines(210*u.GHz, 235*u.GHz, chemical_name=' HNCO ', energy_max=2500, energy_type='eu_k', line_lists=['CDMS'], show_upper_degeneracy=True) cdmsplat = utils.minimize_table(cdmsplat_) freqs = np.array(cdmsplat['Freq'])*u.GHz aij = cdmsplat['log10_Aij'] deg = cdmsplat_['Upper State Degeneracy'] EU = (np.array(cdmsplat['EU_K'])*u.K*constants.k_B).to(u.erg).value #ref_freq = 220.74726*u.GHz #vdiff = (np.array(-(freqs-ref_freq)/ref_freq)*constants.c).to(u.km/u.s).value nl = nodes.Nodelist() nl.findnode('cdms') cdms = nl.findnode('cdms') request = request.Request(node=cdms)
import scipy.constants as cnst from astropy.io import fits import glob import radio_beam import os from astropy.modeling import models, fitting import time import pdb import pickle Splatalogue.QUERY_URL = 'https://splatalogue.online/c_export.php' sanitytable1 = utils.minimize_table( Splatalogue.query_lines(200 * u.GHz, 300 * u.GHz, chemical_name=' HCN ', energy_max=1840, energy_type='eu_k', line_lists=['JPL'], show_upper_degeneracy=True)) '''Collect constants and CH3OH-specific quantum parameters''' print('Setting constants') c = cnst.c * u.m / u.s k = cnst.k * u.J / u.K h = cnst.h * u.J * u.s sigma_sb = cnst.sigma * u.W / ((u.m)**(2) * (u.K)**(4)) b_0 = 24679.98 * u.MHz a_0 = 127484 * u.MHz c_0 = 23769.70 * u.MHz m = b_0**2 / (a_0 * c_0) mu_a = (0.896e-18 * u.statC * u.cm).to('cm(3/2) g(1/2) s-1 cm') R_i = 1
freq_min = freqs[0] * (1 + z) #215*u.GHz freq_max = freqs[(len(freqs) - 1)] * (1 + z) #235*u.GHz assert freq_max > freq_min, 'Decreasing frequency axis' linewidth = 0.00485 * u.GHz #Half of original 0.0097GHz lw2 = linewidth / 8 '''Generate methanol table for contaminant search''' mtable1 = Splatalogue.query_lines(freq_min, freq_max, chemical_name=' CH3OH ', energy_max=1840, energy_type='eu_k', line_lists=[linelist], show_upper_degeneracy=True) methanol_table = utils.minimize_table(mtable1) mdict[i] = {datacubes[i]: methanol_table} mlines = (methanol_table['Freq'] * 10**9) / (1 + z) mqns = methanol_table['QNs'] meuks = methanol_table['EU_K'] * u.K mlog10aijs = np.array(methanol_table['log10_Aij']) maijs = 10**mlog10aijs * u.s**-1 meujs = [] for euk in meuks: meujs.append(KtoJ(euk)) mdegs = mtable1['Upper State Degeneracy'] mins = [] maxs = []
freq_min = freqs[0] * (1 + z) #215*u.GHz freq_max = freqs[(len(freqs) - 1)] * (1 + z) #235*u.GHz assert freq_max > freq_min, 'Decreasing frequency axis' linewidth = 0.00485 * u.GHz #Half of original 0.0097GHz lw2 = linewidth / 8 '''Generate methanol table for contaminant search''' mtable1 = Splatalogue.query_lines(freq_min, freq_max, chemical_name=' CH3OH ', energy_max=1840, energy_type='eu_k', line_lists=[linelist], show_upper_degeneracy=True) methanol_table = utils.minimize_table(mtable1) mdict[i] = {imgnames[i]: methanol_table} mlines = (methanol_table['Freq'] * 10**9) / (1 + z) mqns = methanol_table['QNs'] meuks = methanol_table['EU_K'] * u.K mlog10aijs = np.array(methanol_table['log10_Aij']) maijs = 10**mlog10aijs * u.s**-1 meujs = [] for euk in meuks: meujs.append(KtoJ(euk)) mdegs = mtable1['Upper State Degeneracy'] mins = [] maxs = []
for labelid in range(1, ct + 1): ssp = sp[labels == labelid] try: ssp.xarr.convert_to_unit(u.GHz) ssp.specfit() ssp.specfit.parinfo frq = ssp.specfit.parinfo['SHIFT0'].value * ssp.xarr.unit except Exception as ex: print(ex) frq = ssp.xarr.to(u.GHz).mean() sq = Splatalogue.query_lines(frq * (1 + 30 / 3e5), frq * (1 + 75 / 3e5), only_astronomically_observed=True) if len(sq) > 0: tbl = utils.minimize_table(sq) try: total_intensity = ssp.data.sum() * np.abs( ssp.xarr.to(u.km / u.s).cdelt()) except ValueError: total_intensity = ssp.data.sum() * np.abs( sp.xarr.to(u.km / u.s).cdelt()) peak_intensity = ssp.data.max() tbl.add_column( Column(data=total_intensity, name='TotalIntensity')) tbl.add_column( Column(data=peak_intensity, name='PeakIntensity')) tbl.add_column(Column(data=mad, name='RMS')) tbl.add_column( Column(data=u.Quantity( (-(frq.to(u.GHz).value - tbl['Freq']) / tbl['Freq'] *
8: 'eight', 9: 'nine', } tbls = {} for line in (1, 2, 3, 4, 5, 6, 7, 8, 9): reline = re.compile('^{n}\({n}\).*-{n}'.format(n=line)) tbl = utils.minimize_table(nh3[np.array([ bool(reline.search(x)) if bool(x) else False for x in nh3['Resolved QNs'] ], dtype='bool')], columns=[ 'Species', 'Chemical Name', 'Resolved QNs', 'Freq-GHz', 'Meas Freq-GHz', 'Log<sub>10</sub> (A<sub>ij</sub>)', 'CDMS/JPL Intensity', 'Linelist', 'E_U (K)', 'Upper State Degeneracy' ]) if len(tbl) == 0: pass # Select only TopModel lines from CDMS/JPL tbls[line] = tbl[tbl['Linelist'] == 'TopModel'] for par in ('tau_wts', 'voff_lines', 'aval', 'freq'): print par for line in (1, 2, 3, 4, 5, 6, 7, 8): # 9 not available
sp = pyspeckit.Spectrum(fn) sp.xarr.convert_to_unit(u.GHz) print(fn, sp.xarr.min(), sp.xarr.max()) fpre = os.path.splitext(os.path.split(fn)[-1])[0] species_names = [x[0] for x in line_to_image_list] frequencies = u.Quantity( [float(x[1].strip("GHz")) for x in line_to_image_list], unit=u.GHz) splat = Splatalogue.query_lines(sp.xarr.min(), sp.xarr.max(), chemical_name='NaCl|KCl', line_lists=['CDMS']) if len(splat) > 0: splat = utils.minimize_table(splat) species_names = [row['Species'] + row['QNs'] for row in splat] frequencies = u.Quantity(splat['Freq'], u.GHz) else: species_names = [] frequencies = [] sp.plotter(figure=pl.figure(1)) sp.plotter(figure=pl.figure(1)) outname = paths.dpath( 'longbaseline/spectra/pngs/{target}_{0}.png'.format(fpre, target=target)) sp.plotter.savefig(outname, bbox_extra_artists=[]) okfreqs = (frequencies > sp.xarr.min()) & (frequencies < sp.xarr.max())
) freqs = np.array(slaim["Freq-GHz"]) * u.GHz aij = slaim["Log<sub>10</sub> (A<sub>ij</sub>)"] deg = slaim["Upper State Degeneracy"] EU = (np.array(slaim["E_U (K)"]) * u.K * constants.k_B).to(u.erg).value cdmsplat_ = Splatalogue.query_lines( 210 * u.GHz, 235 * u.GHz, chemical_name=" HNCO ", energy_max=2500, energy_type="eu_k", line_lists=["CDMS"], show_upper_degeneracy=True, ) cdmsplat = utils.minimize_table(cdmsplat_) freqs = np.array(cdmsplat["Freq"]) * u.GHz aij = cdmsplat["log10_Aij"] deg = cdmsplat_["Upper State Degeneracy"] EU = (np.array(cdmsplat["EU_K"]) * u.K * constants.k_B).to(u.erg).value # ref_freq = 220.74726*u.GHz # vdiff = (np.array(-(freqs-ref_freq)/ref_freq)*constants.c).to(u.km/u.s).value nl = nodes.Nodelist() nl.findnode("cdms") cdms = nl.findnode("cdms") request = request.Request(node=cdms)