def trimmed_query(self, *args, **kwargs): S = Splatalogue(energy_max=500, energy_type='eu_k', energy_levels=['el4'], line_strengths=['ls4'], only_NRAO_recommended=True, show_upper_degeneracy=True) columns = [ 'Species', 'Chemical Name', 'Resolved QNs', 'Freq-GHz', 'Log<sub>10</sub> (A<sub>ij</sub>)', 'E_U (K)', 'Upper State Degeneracy' ] table = S.query_lines(*args, **kwargs) table.rename_column('Log<sub>10</sub> (A<sub>ij</sub>)', 'log10(Aij)') table['Aij'] = pow(10, table['log10(Aij)']) #table.remove_column('log10(Aij)') table.rename_column('E_U (K)', 'EU_K') table.rename_column('Resolved QNs', 'QNs') table.rename_column('Upper State Degeneracy', 'g_u') table['Freq-MHz'] = table['Freq-GHz'] * 1000. table.remove_column('Freq-GHz') table.sort('Freq-MHz') self.remove_hfs(table) if self.idx_obs: table = table[self.idx_obs] return table
def query(low_freq, high_freq, chemical_name=None, line_list=[LineList.JPL, LineList.CDMS]): """ Class method for querying splatalogue. Wraps the query_lines function from astroquery. """ columns = [ 'Species', 'Chemical Name', 'Freq-GHz(rest frame,redshifted)', 'Meas Freq-GHz(rest frame,redshifted)', 'CDMS/JPL Intensity', 'Lovas/AST Intensity', 'Linelist' ] try: # TODO-Dynamic Frequency Units # Query splatalogue and convert into pandas dataframes if chemical_name: df = Splatalogue.query_lines( low_freq * u.MHz, high_freq * u.MHz, chemical_name=chemical_name).to_pandas() else: df = Splatalogue.query_lines(low_freq * u.MHz, high_freq * u.MHz, line_lists=line_list).to_pandas() df = df[columns] except TimeoutError: return [] return df
def __init__( self, chemical_name, energy_max=2500, nu_min=216 * u.GHz, nu_max=235 * u.GHz, line_lists=['SLAIM'], freq_type='Freq-GHz', linelimit=100000, ): Splatalogue.LINES_LIMIT = linelimit line_ids = Splatalogue.get_species_ids().find(chemical_name) if len(line_ids) > 1: mwts = [int(lid[:3]) for lid in line_ids] if len(set(mwts)) != 1: raise ValueError("Chemical name {0} matches too many " "different lines: {1}".format( chemical_name, line_ids)) self.molwt = mwts[0] elif len(line_ids) == 1: self.molwt = int(list(line_ids.keys())[0][:3]) else: raise ValueError("No matching molecules") linecat = Splatalogue.query_lines( nu_min, nu_max, chemical_name=chemical_name, energy_max=energy_max, energy_type='eu_k', line_strengths=['ls1', 'ls2', 'ls3', 'ls4', 'ls5'], line_lists=line_lists, show_upper_degeneracy=True) self.linecat = linecat self.freqs = np.array(linecat[freq_type]) * u.GHz self.aij = linecat['Log<sub>10</sub> (A<sub>ij</sub>)'] self.deg = [ x if x > 0 else 1 for x in linecat['Upper State Degeneracy'] ] self.SijMu2 = linecat[ 'S<sub>ij</sub>μ<sup>2</sup> (D<sup>2</sup>)'] self.EU = (np.array(linecat['E_U (K)']) * u.K * constants.k_B).to( u.erg).value ## crappy debug hack #if 'OSU' in line_lists: # self.EU = (np.array(linecat['E_L (K)'])*u.K*constants.k_B).to(u.erg).value slaim_query = Splatalogue.query_lines(1 * u.Hz, 10000 * u.GHz, chemical_name=chemical_name, energy_max=energy_max, energy_type='eu_k', line_lists=['SLAIM'], show_upper_degeneracy=True) self.slaim = slaim_query self.all_EU = (slaim_query['E_U (K)'] * u.K * constants.k_B).to( u.erg).value self.all_freq = slaim_query['Freq-GHz'] self.all_deg = slaim_query['Upper State Degeneracy']
def findSpeciesSource(self, sourceName, redshift, DV, flag = False): """ Try to identify the lines for a given source with redshift using the splatalogue DB. If flag = True search only for lines w/o flagging (EDGE, TELURIC, ...) DV : uncertainty on the velocity in km/s """ lines = self.findSource(sourceName, flag) if len(lines) == 0: print("## Species - No lines found for source %s"%(sourceName)) return(0) for li in lines: freq1 = li[4] * (1. + redshift) freq2 = li[5] * (1. + redshift) df = freq1 * u.GHz * DV * 1e3 * u.m / u.s / const.c print df columns = ('Species','Chemical Name','Resolved QNs','Freq-GHz','Meas Freq-GHz','Log<sub>10</sub> (A<sub>ij</sub>)','E_U (K)','Linelist') transitions = spla.query_lines(freq1*u.GHz-df,freq2*u.GHz+df)[columns] transitions.rename_column('Log<sub>10</sub> (A<sub>ij</sub>)','log10(Aij)') transitions.rename_column('E_U (K)','EU_K') transitions.rename_column('Resolved QNs','QNs') transitions.sort('EU_K') transitions.pprint(100)
def get_composition(self, full_name): columns = ('Species') rows = Splatalogue.query_lines_async(chemical_name=full_name)[columns] row = rows[0] name = row[0] return name
def query_splatalogue(spikes): # from a spike to the splatalogue (linelist, tag, moleculename) # verify this is right spacing = (spikes.data[1:, 0] - spikes.data[:-1, 0]).mean() bounds = ( np.column_stack([spikes.frequency - spacing, spikes.frequency + spacing]) * u.GHz ) out = [] for i in range(spikes.frequency.shape[0]): res = Splatalogue.query_lines( *bounds[i, :].T, show_molecule_tag=True, line_lists=["CDMS", "JPL"], exclude=None, line_strengths="ls1", ) if "Molecule<br>Tag" in res.keys(): tag = list( map(lambda x: str(x).zfill(6).replace("-", "0"), res["Molecule<br>Tag"]) ) db = list(res["Linelist"]) mname = list(res["Chemical Name"]) species = list(res["Species"]) molecule = [f"{m} ({s})" for m, s in zip(mname, species)] if res: out.append(splat_query(db, tag, molecule)) # tuple transpositions! return set(zip(*[sum(o, []) for o in zip(*out)]))
def search_center_frequency(frequency: float, width=0.5): """ Function for wrapping the astroquery Splatalogue API for looking up a frequency and finding candidate molecules for assignment. The width parameter adjusts the +/- range to include in the search: for high frequency surveys, it's probably preferable to use a percentage to accommodate for the typically larger uncertainties (sub-mm experiments). Parameters ---------- frequency: float Frequency in MHz to search Splatalogue for. width: float, optional Absolute frequency offset in MHz to include in the search. Returns ------- dataframe or None Pandas dataframe containing frequency matches, or None if no matches are found. """ min_freq = frequency - width max_freq = frequency + width try: splat_df = Splatalogue.query_lines( min_freq*u.MHz, max_freq*u.MHz, line_lists=["CDMS", "JPL"] ).to_pandas() # These are the columns wanted columns = [ "Species", "Chemical Name", "Meas Freq-GHz(rest frame,redshifted)", "Freq-GHz(rest frame,redshifted)", "Resolved QNs", "CDMS/JPL Intensity", "E_U (K)", "E_L (K)" ] # Take only what we want splat_df = splat_df[columns] splat_df.columns = [ "Species", "Chemical Name", "Meas Freq-GHz", "Freq-GHz", "Resolved QNs", "CDMS/JPL Intensity", "E_U (K)", "E_L (K)" ] # Now we combine the frequency measurements splat_df["Frequency"] = splat_df["Meas Freq-GHz"].values # Replace missing experimental data with calculated splat_df["Frequency"].fillna(splat_df["Freq-GHz"], inplace=True) # Convert to MHz splat_df["Frequency"] *= 1000. return splat_df except IndexError: print("Could not parse Splatalogue table at {:,.4f}".format(frequency)) return None
def query(low_freq, high_freq, chemical_name=None, line_list=[LineList.JPL, LineList.CDMS]): columns = ('Species', 'Chemical Name', 'Freq-GHz', 'Meas Freq-GHz', 'CDMS/JPL Intensity', 'Lovas/AST Intensity', 'Linelist') try: # TODO-Dynamic Frequency Units if chemical_name is not None: lines = Splatalogue.query_lines(low_freq * u.MHz, high_freq * u.MHz, chemical_name=chemical_name)[columns] else: lines = Splatalogue.query_lines(low_freq * u.MHz, high_freq * u.MHz, line_lists=line_list)[columns] except TimeoutError: return [] return lines
def __init__(self, chemical_name, energy_max=2500, nu_min=216*u.GHz, nu_max=235*u.GHz, line_lists=['SLAIM'], freq_type='Freq-GHz', linelimit=100000, ): Splatalogue.LINES_LIMIT=linelimit line_ids = Splatalogue.get_species_ids().find(chemical_name) if len(line_ids) > 1: mwts = [int(lid[:3]) for lid in line_ids] if len(set(mwts)) != 1: raise ValueError("Chemical name {0} matches too many " "different lines: {1}".format(chemical_name, line_ids)) self.molwt = mwts[0] elif len(line_ids) == 1: self.molwt = int(list(line_ids.keys())[0][:3]) else: raise ValueError("No matching molecules") linecat = Splatalogue.query_lines(nu_min, nu_max, chemical_name=chemical_name, energy_max=energy_max, energy_type='eu_k', line_strengths=['ls1','ls2','ls3','ls4','ls5'], line_lists=line_lists, show_upper_degeneracy=True) self.linecat = linecat self.freqs = np.array(linecat[freq_type])*u.GHz self.aij = linecat['Log<sub>10</sub> (A<sub>ij</sub>)'] self.deg = [x if x > 0 else 1 for x in linecat['Upper State Degeneracy']] self.SijMu2 = linecat['S<sub>ij</sub>μ<sup>2</sup> (D<sup>2</sup>)'] self.EU = (np.array(linecat['E_U (K)'])*u.K*constants.k_B).to(u.erg).value ## crappy debug hack #if 'OSU' in line_lists: # self.EU = (np.array(linecat['E_L (K)'])*u.K*constants.k_B).to(u.erg).value slaim_query = Splatalogue.query_lines(1*u.Hz, 10000*u.GHz, chemical_name=chemical_name, energy_max=energy_max, energy_type='eu_k', line_lists=['SLAIM'], show_upper_degeneracy=True) self.slaim = slaim_query self.all_EU = (slaim_query['E_U (K)']*u.K*constants.k_B).to(u.erg).value self.all_freq = slaim_query['Freq-GHz'] self.all_deg = slaim_query['Upper State Degeneracy']
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 lines(species, min_frequency, max_frequency, show_upper_degeneracy=True, transition=None): query = Splatalogue.query_lines( min_frequency=min_frequency, max_frequency=max_frequency, chemical_name=str(" " + species + " "), transition=str(transition), show_upper_degeneracy=show_upper_degeneracy) return query
def query(low_freq, high_freq, chemical_name=None, line_list=[LineList.JPL, LineList.CDMS]): columns = ('Species', 'Chemical Name', 'Freq-GHz', 'Meas Freq-GHz', 'CDMS/JPL Intensity', 'Lovas/AST Intensity', 'Linelist') try: # TODO-Dynamic Frequency Units if chemical_name is not None: lines = Splatalogue.query_lines( low_freq * u.MHz, high_freq * u.MHz, chemical_name=chemical_name)[columns] else: lines = Splatalogue.query_lines(low_freq * u.MHz, high_freq * u.MHz, line_lists=line_list)[columns] except TimeoutError: return [] return lines
def trimmed_query(self, *args,**kwargs): S = Splatalogue(energy_max=500, energy_type='eu_k',energy_levels=['el4'], line_strengths=['ls4'], only_NRAO_recommended=True, show_upper_degeneracy=True) columns = ['Species','Chemical Name','Resolved QNs','Freq-GHz', 'Log<sub>10</sub> (A<sub>ij</sub>)', 'E_U (K)','Upper State Degeneracy' ] table = S.query_lines(*args, **kwargs) table.rename_column('Log<sub>10</sub> (A<sub>ij</sub>)','log10(Aij)') table['Aij'] = pow(10,table['log10(Aij)']) #table.remove_column('log10(Aij)') table.rename_column('E_U (K)','EU_K') table.rename_column('Resolved QNs','QNs') table.rename_column('Upper State Degeneracy','g_u') table['Freq-MHz'] = table['Freq-GHz']*1000. table.remove_column('Freq-GHz') table.sort('Freq-MHz') self.remove_hfs(table) if self.idx_obs: table = table[self.idx_obs] return table
def get_all_lines(self, min_freq, max_freq, line_list=[LineList.JPL, LineList.CDMS]): columns = ('Species', 'Chemical Name', 'Freq-GHz', 'Meas Freq-GHz', 'CDMS/JPL Intensity', 'Lovas/AST Intensity', 'Linelist') rows = Splatalogue.query_lines(min_freq * u.MHz, max_freq * u.MHz, chemical_name=self.full_name, line_lists=line_list)[columns] lines = [] for row in rows: name, full_name, frequency, intensity, line_list = SplatalogueAnalysis.get_row_data(row) if min_freq < frequency < max_freq: line = Line(frequency, line_list, intensity) lines.append(line) return lines
def get_full_frequency_intensity_list(full_name, min_freq, max_freq, line_list=[LineList.JPL, LineList.CDMS]): columns = ('Species', 'Chemical Name', 'Freq-GHz', 'Meas Freq-GHz', 'CDMS/JPL Intensity', 'Lovas/AST Intensity', 'Linelist') rows = Splatalogue.query_lines(min_freq * u.MHz, max_freq * u.MHz, chemical_name=full_name, line_lists=line_list)[columns] frequencies = [] intensities = [] for row in rows: name, full_name, frequency, intensity, line_list = SplatalogueAnalysis.get_row_data(row) if min_freq < frequency < max_freq: frequencies.append(frequency * 1000) # convert to MHz intensities.append(intensity) return frequencies, intensities
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
def get_all_lines(self, min_freq, max_freq, line_list=[LineList.JPL, LineList.CDMS]): columns = ('Species', 'Chemical Name', 'Freq-GHz', 'Meas Freq-GHz', 'CDMS/JPL Intensity', 'Lovas/AST Intensity', 'Linelist') rows = Splatalogue.query_lines(min_freq * u.MHz, max_freq * u.MHz, chemical_name=self.full_name, line_lists=line_list)[columns] lines = [] for row in rows: name, full_name, frequency, intensity, line_list = SplatalogueAnalysis.get_row_data( row) if min_freq < frequency < max_freq: line = Line(frequency, line_list, intensity) lines.append(line) return lines
def find_molecules(): """ Classify the molecules from their frequency for each dataset """ for id, dataset in enumerate(data): # Locate the indices where the flux is greater than 3 standard deviations # There are 4 datasets. Column 0 is the frequency, column 1 is the flux # Splatalogue appears to be accurate up to 5 decimal places molecules = {} # An empty dictionary to store the results of each detected molecule and rest frequency delta = 0.00005 # +/- when searching frequencies frequencies = np.round(dataset[np.where( dataset[:, 1] >= 3 * np.std(dataset[:, 1])), 0], 5)[0] for freq in frequencies: results = Splatalogue.query_lines( (freq - delta)*u.GHz, (freq + delta)*u.GHz, show_molecule_tag = True, top20 = 'planet', line_lists = ['CDMS', 'JPL'], line_strengths = 'ls1') # Append the chemical names corresponding to the searched frequency. if len(results) > 0: molecules[freq] = {"Chemical Name": results["Chemical Name"].tolist(), "Molecule Tag": results["Molecule<br>Tag"].tolist()} else: molecules[freq] = {"Chemical Name": "Unknown", "Molecule Tag": None} # Append the chemical name and frequency to the dictionary of all molecules found if len(results) > 0: for i, molecule in enumerate(results["Chemical Name"].tolist()): if molecule in all_molecules.keys(): all_molecules[molecule]["Occurances"].append(freq) else: molecule_tag = "0" + str(results["Molecule<br>Tag"][i]) if len(str(results["Molecule<br>Tag"][i])) < 6 else str(results["Molecule<br>Tag"][i]) all_molecules[molecule] = {"Molecule Tag": molecule_tag, "Linelist": results["Linelist"][i], "Occurances": [freq]} else: if "Unknown" in all_molecules.keys(): all_molecules["Unknown"]["Occurances"].append(freq) else: all_molecules["Unknown"] = {"Molecule Tag": "None", "Linelist": "None", "Occurances": [freq]} add_lines(id, molecules)
def getLines(self,lower, upper, location): print("Downloading From "+ str(lower) + " to " + str(upper)) lines = Splatalogue.query_lines_async( lower, upper, export=True, export_limit=999999999, line_strengths=('ls1', 'ls2', 'ls3', 'ls4', 'ls5'), displayHFS=True, show_unres_qn=True, show_upper_degeneracy=True, show_molecule_tag=True, show_qn_code=True, show_lovas_labref=True, show_lovas_obsref=True, show_orderedfreq_only=None, show_nrao_recommended=True ) print("Downloadg From " + str(lower) + " to " + str(upper) + " Completed | ") + lines.content.split("\n")[1] Container[location] = lines.content return lines
def get_full_frequency_intensity_list(full_name, min_freq, max_freq, line_list=[ LineList.JPL, LineList.CDMS ]): columns = ('Species', 'Chemical Name', 'Freq-GHz', 'Meas Freq-GHz', 'CDMS/JPL Intensity', 'Lovas/AST Intensity', 'Linelist') rows = Splatalogue.query_lines(min_freq * u.MHz, max_freq * u.MHz, chemical_name=full_name, line_lists=line_list)[columns] frequencies = [] intensities = [] for row in rows: name, full_name, frequency, intensity, line_list = SplatalogueAnalysis.get_row_data( row) if min_freq < frequency < max_freq: frequencies.append(frequency * 1000) # convert to MHz intensities.append(intensity) return frequencies, intensities
limits=[(0, 1), (xmin.value, xmax.value), (0, 15)], limited=[(True, True)] * 3, ) if doplot: slc.plotter.savefig( paths.fpath( 'spectral_fits/{linename}_{band}_{spw}_{freq}.png'. format(linename=linename, band=band, freq=freq, spw=spw))) frq = u.Quantity(slc.specfit.parinfo['SHIFT0'], u.GHz) result = Splatalogue.query_lines( freq - (dv_linesearch) / constants.c * freq, freq + (dv_linesearch) / constants.c * freq, chemical_name=chem_re) for tbl in salt_tables: match = ((tbl['Freq'].quantity > freq - (dv_linesearch) / constants.c * freq) & (tbl['Freq'].quantity < freq + (dv_linesearch) / constants.c * freq)) result = tbl[match] #print(match.any()) if match.any(): #print("Matched {0}".format(linename)) break #if len(result) > 0: # result = mt(result) if len(result) >= 1:
import numpy as np import line_to_image_list from astropy import units as u from astropy import constants from astropy import log import pylab as pl from ch3oh_rotational_diagram_maps import nupper_of_kkms, fit_tex from ch3oh_model import show_modelfit from astroquery.splatalogue import Splatalogue, utils slaim = Splatalogue.query_lines(218*u.GHz, 235*u.GHz, chemical_name=' CH3OH vt = 0 ', energy_max=3500, energy_type='eu_k', line_lists=['SLAIM'], show_upper_degeneracy=True) slaimfreqs = np.array(slaim['Freq-GHz'])*u.GHz def fit_each_line_with_a_gaussian(spectra, ampguess, vguess_kms, widthguess, fixed_velo=False, fixed_width=False, wrange_GHz=(0,0.01), plot=False, separation_tolerance=0.005*u.GHz, fignum_start=1): assert spectra.unit == 'K' sp = spectra sp.plotter.plotkwargs = {} sp.xarr.convert_to_unit(u.GHz) # assume baselined already # sp.data -= np.nanpercentile(sp.data, 10) #sp.data *= beam.jtok(sp.xarr)
def search_molecule(species: str, freq_range=[0., 40e3], **kwargs): """ Function to search Splatalogue for a specific molecule. Technically I'd prefer to download entries from CDMS instead, but this is probably the most straight forward way. The main use for this function is to verify line identifications - if a line is tentatively assigned to a U-line, then other transitions for the molecule that are stronger or comparatively strong should be visible. Parameters ---------- species: str Chemical name of the molecule freq_range: list The frequency range to perform the lookup Returns ------- DataFrame or None Pandas dataframe containing transitions for the given molecule. If no matches are found, returns None. """ default_param = { "line_lists": ["CDMS", "JPL"], "export_limit": 20000 } default_param.update(**kwargs) splat_df = Splatalogue.query_lines( min(freq_range) * u.MHz, max(freq_range) * u.MHz, chemical_name=species, **default_param ).to_pandas() if len(splat_df)> 0: # These are the columns wanted columns = [ "Species", "Chemical Name", "Meas Freq-GHz(rest frame,redshifted)", "Freq-GHz(rest frame,redshifted)", "Resolved QNs", "CDMS/JPL Intensity", "E_U (K)" ] # Take only what we want splat_df = splat_df[columns] splat_df.columns = [ "Species", "Chemical Name", "Meas Freq-GHz", "Freq-GHz", "Resolved QNs", "CDMS/JPL Intensity", "E_U (K)" ] # Now we combine the frequency measurements splat_df["Frequency"] = splat_df["Meas Freq-GHz"].values # Replace missing experimental data with calculated splat_df["Frequency"].fillna(splat_df["Freq-GHz"], inplace=True) # Convert to MHz splat_df["Frequency"] *= 1000. return splat_df else: return None
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
print('Corrected decreasing frequency axis') else: pass 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 / 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
import line_to_image_list from astropy import table from astroquery.splatalogue import Splatalogue from astropy import units as u tbl_list = [] tbl_dict = {} for linename, freq, _, _ in line_to_image_list.line_to_image_list: frq = float(freq.strip("GHz"))*u.GHz tbl = Splatalogue.query_lines(frq*(1-0.25/3e5), frq*(1+0.25/3e5), line_lists=['SLAIM'], noHFS=True) if len(tbl) > 0: if len(tbl) > 1: print("Contaminants for {0}: ".format(linename)) print(tbl) selected = tbl['E_U (K)'].argmin() tbl = tbl[selected:selected+1] print("Selected: ",tbl) col = tbl['Lovas/AST Intensity'] if col.dtype.kind != 'U': col = col.astype(str) tbl.replace_column(col.name, col) tbl_list.append(tbl) tbl_dict[linename] = tbl final_tbl = table.vstack(tbl_list) final_tbl.write("full_line_table.csv", overwrite=True)
from astropy import units as u from astroquery.splatalogue import Splatalogue from config import conn from tables import peaks_table line_ids = Splatalogue.get_species_ids() # --- Find species that have CO --- # # CO_containing_species = Splatalogue.get_species_ids('CHS') # print CO_containing_species # -- Find Species within lines -- # # CO1to0 = Splatalogue.query_lines(115.271 * u.GHz, 115.273 * u.GHz, top20='top20') # CO1to0.pprint() # row = CO1to0[0] # print row[1] mid = 142 threshold = 0.02 frequencies, intensities = peaks_table.get_frequency_intensity_list(conn, mid) class Chemical: def __init__(self, name): self.name = name self.lines = [] self.matched_lines = [] self.N = 0 def add_line(self, line, match):
} pl.figure(1).clf() for target, species_list in spectra_to_species.items(): spectra = pyspeckit.Spectra(glob.glob(paths.spath("*{0}*fits".format(target)))) for species_tuple in species_list: species_name, chemid, tmax = species_tuple for ii in range(4): cat = Splatalogue.query_lines( spectra[ii].xarr.min(), spectra[ii].xarr.max(), chemical_name=chemid, energy_max=tmax, energy_type="eu_k", noHFS=True, line_lists=["SLAIM"], ) spectra[ii].plotter(figure=pl.figure(1)) spectra[ii].plotter.axis.set_ylim(snu_min[target], spectra[ii].plotter.axis.get_ylim()[1]) spectra[ii].plotter.line_ids( cat["Resolved QNs"], cat["Freq-GHz"] * u.GHz, velocity_offset=velo[target], plot_kwargs=plot_kwargs, annotate_kwargs=annotate_kwargs, ) spectra[ii].plotter.savefig( paths.fpath(
for target in velo: files = glob.glob( paths.dpath("longbaseline/spectra/{0}*.fits".format(target))) for fn in files: 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))
import re import numpy as np from astropy import units as u from astropy import constants from astroquery.splatalogue import Splatalogue, utils # Query splatalogue, keeping all of the line strength columns # Both Lovas and CDMS/JPL can be used nh3 = Splatalogue.query_lines(20 * u.GHz, 40 * u.GHz, chemical_name=' NH3 ', show_upper_degeneracy=True, line_strengths=['ls1', 'ls2', 'ls3', 'ls4']) numbers = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 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))
def get_molecular_parameters(molecule_name, molecule_name_vamdc=None, tex=50, fmin=1 * u.GHz, fmax=1 * u.THz, line_lists=['SLAIM'], chem_re_flags=0, **kwargs): """ Get the molecular parameters for a molecule from the CDMS database using vamdclib Parameters ---------- molecule_name : string The string name of the molecule (normal name, like CH3OH or CH3CH2OH) molecule_name_vamdc : string or None If specified, gives this name to vamdc instead of the normal name. Needed for some molecules, like CH3CH2OH -> C2H5OH. tex : float Optional excitation temperature (basically checks if the partition function calculator works) fmin : quantity with frequency units fmax : quantity with frequency units The minimum and maximum frequency to search over line_lists : list A list of Splatalogue line list catalogs to search. Valid options include SLAIM, CDMS, JPL. Only a single catalog should be used to avoid repetition of transitions and species chem_re_flags : int An integer flag to be passed to splatalogue's chemical name matching tool Examples -------- >>> freqs, aij, deg, EU, partfunc = get_molecular_parameters(molecule_name='CH2CHCN', ... fmin=220*u.GHz, ... fmax=222*u.GHz, ... molecule_name_vamdc='C2H3CN') >>> freqs, aij, deg, EU, partfunc = get_molecular_parameters('CH3OH', ... fmin=90*u.GHz, ... fmax=100*u.GHz) """ from astroquery.vamdc import load_species_table from astroquery.splatalogue import Splatalogue from vamdclib import nodes from vamdclib import request from vamdclib import specmodel lut = load_species_table.species_lookuptable() species_id_dict = lut.find(molecule_name_vamdc or molecule_name, flags=chem_re_flags) if len(species_id_dict) == 1: species_id = list(species_id_dict.values())[0] elif len(species_id_dict) == 0: raise ValueError("No matches for {0}".format(molecule_name)) else: raise ValueError( "Too many species matched: {0}".format(species_id_dict)) # do this here, before trying to compute the partition function, because # this query could fail tbl = Splatalogue.query_lines(fmin, fmax, chemical_name=molecule_name, line_lists=line_lists, show_upper_degeneracy=True, **kwargs) nl = nodes.Nodelist() nl.findnode('cdms') cdms = nl.findnode('cdms') request = request.Request(node=cdms) query_string = "SELECT ALL WHERE VAMDCSpeciesID='%s'" % species_id request.setquery(query_string) result = request.dorequest() Q = list( specmodel.calculate_partitionfunction(result.data['States'], temperature=tex).values())[0] def partfunc(tem): Q = list( specmodel.calculate_partitionfunction(result.data['States'], temperature=tem).values())[0] return Q freqs = np.array(tbl['Freq-GHz']) * u.GHz aij = tbl['Log<sub>10</sub> (A<sub>ij</sub>)'] deg = tbl['Upper State Degeneracy'] EU = (np.array(tbl['E_U (K)']) * u.K * constants.k_B).to(u.erg).value return freqs, aij, deg, EU, partfunc
} pl.figure(1).clf() for target, species_list in spectra_to_species.items(): spectra = pyspeckit.Spectra( glob.glob(paths.spath("*{0}*fits".format(target)))) for species_tuple in species_list: species_name, chemid, tmax = species_tuple for ii in range(4): cat = Splatalogue.query_lines(spectra[ii].xarr.min(), spectra[ii].xarr.max(), chemical_name=chemid, energy_max=tmax, energy_type='eu_k', noHFS=True, line_lists=['SLAIM']) spectra[ii].plotter(figure=pl.figure(1)) spectra[ii].plotter.axis.set_ylim( snu_min[target], spectra[ii].plotter.axis.get_ylim()[1]) spectra[ii].plotter.line_ids(cat['Resolved QNs'], cat['Freq-GHz'] * u.GHz, velocity_offset=velo[target], plot_kwargs=plot_kwargs, annotate_kwargs=annotate_kwargs) spectra[ii].plotter.savefig(paths.fpath( 'line_id_spectra/{target}_{species_name}_{chemid}_spw{0}.png'. format( ii,
} eupper = {'66': 409, '77': 539, '99': 853, '1010': 1037, '1313': 1693, } degeneracy = {'66': 2*(2*6+1), '77': 1*(2*7+1), '99': 2*(2*9+1), '1010': 1*(2*10+1), '1313': 1*(2*13+1), } nh3tables = {line:Splatalogue.query_lines(freqs[line]*0.99999, freqs[line]*1.00001, line_strengths=['ls1','ls2','ls3','ls4','ls5'], chemical_name=' NH3 ') for line in freqs} linestrengths = {'66':float(nh3tables['66'][nh3tables['66']['Linelist']=='JPL']['S<sub>ij</sub>μ<sup>2</sup> (D<sup>2</sup>)'])*1e-18*u.esu*u.cm, '77':float(nh3tables['77'][nh3tables['77']['Linelist']=='JPL']['S<sub>ij</sub>μ<sup>2</sup> (D<sup>2</sup>)'])*1e-18*u.esu*u.cm, '99':float(nh3tables['99'][nh3tables['99']['Linelist']=='JPL']['S<sub>ij</sub>μ<sup>2</sup> (D<sup>2</sup>)'])*1e-18*u.esu*u.cm, '1010':float(nh3tables['1010'][nh3tables['1010']['Linelist']=='JPL']['S<sub>ij</sub>μ<sup>2</sup> (D<sup>2</sup>)'])*1e-18*u.esu*u.cm, '1313':float(nh3tables['1313'][nh3tables['1313']['Linelist']=='JPL']['S<sub>ij</sub>μ<sup>2</sup> (D<sup>2</sup>)'])*1e-18*u.esu*u.cm, } FWHM = np.sqrt(8*np.log(2)) def tbl_vals(pi): """ Compute the average amplitude, average width, and respective errors from the hyperfine fits """
def get_molecular_parameters(molecule_name, molecule_name_vamdc=None, tex=50, fmin=1*u.GHz, fmax=1*u.THz, line_lists=['SLAIM'], chem_re_flags=0, **kwargs): """ Get the molecular parameters for a molecule from the CDMS database using vamdclib Parameters ---------- molecule_name : string The string name of the molecule (normal name, like CH3OH or CH3CH2OH) molecule_name_vamdc : string or None If specified, gives this name to vamdc instead of the normal name. Needed for some molecules, like CH3CH2OH -> C2H5OH. tex : float Optional excitation temperature (basically checks if the partition function calculator works) fmin : quantity with frequency units fmax : quantity with frequency units The minimum and maximum frequency to search over line_lists : list A list of Splatalogue line list catalogs to search. Valid options include SLAIM, CDMS, JPL. Only a single catalog should be used to avoid repetition of transitions and species chem_re_flags : int An integer flag to be passed to splatalogue's chemical name matching tool Examples -------- >>> freqs, aij, deg, EU, partfunc = get_molecular_parameters(molecule_name='CH2CHCN', ... fmin=220*u.GHz, ... fmax=222*u.GHz, ... molecule_name_vamdc='C2H3CN') >>> freqs, aij, deg, EU, partfunc = get_molecular_parameters('CH3OH', ... fmin=90*u.GHz, ... fmax=100*u.GHz) """ from astroquery.vamdc import load_species_table from astroquery.splatalogue import Splatalogue from vamdclib import nodes from vamdclib import request from vamdclib import specmodel lut = load_species_table.species_lookuptable() species_id_dict = lut.find(molecule_name_vamdc or molecule_name, flags=chem_re_flags) if len(species_id_dict) == 1: species_id = list(species_id_dict.values())[0] elif len(species_id_dict) == 0: raise ValueError("No matches for {0}".format(molecule_name)) else: raise ValueError("Too many species matched: {0}" .format(species_id_dict)) # do this here, before trying to compute the partition function, because # this query could fail tbl = Splatalogue.query_lines(fmin, fmax, chemical_name=molecule_name, line_lists=line_lists, show_upper_degeneracy=True, **kwargs) nl = nodes.Nodelist() nl.findnode('cdms') cdms = nl.findnode('cdms') request = request.Request(node=cdms) query_string = "SELECT ALL WHERE VAMDCSpeciesID='%s'" % species_id request.setquery(query_string) result = request.dorequest() # run it once to test that it works Q = list(specmodel.calculate_partitionfunction(result.data['States'], temperature=tex).values())[0] def partfunc(tem): Q = list(specmodel.calculate_partitionfunction(result.data['States'], temperature=tem).values())[0] return Q freqs = (np.array(tbl['Freq-GHz'])*u.GHz if 'Freq-GHz' in tbl else np.array(tbl['Freq-GHz(rest frame,redshifted)'])*u.GHz) aij = tbl['Log<sub>10</sub> (A<sub>ij</sub>)'] deg = tbl['Upper State Degeneracy'] EU = (np.array(tbl['E_U (K)'])*u.K*constants.k_B).to(u.erg).value return freqs, aij, deg, EU, partfunc
from __future__ import print_function import re import numpy as np from astropy import units as u from astropy import constants from astroquery.splatalogue import Splatalogue, utils # Query splatalogue, keeping all of the line strength columns # Both Lovas and CDMS/JPL can be used nh3 = Splatalogue.query_lines(20*u.GHz, 40*u.GHz, chemical_name=' NH3 ', show_upper_degeneracy=True, line_strengths=['ls1','ls2','ls3','ls4']) numbers = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 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))
from astropy import units as u from astroquery.splatalogue import Splatalogue name = "2,4-Pentadiynylidyne" columns = ('Species', 'Chemical Name') freq = 11935.48 # freq *= 1000 max_freq = 11936.0 min_freq = 11935.0 rows = Splatalogue.query_lines(min_freq * u.GHz, max_freq * u.GHz, chemical_name=name) rows.pprint() for row in rows: print str(row[0]) + " " + str(row[2])
from astropy import units as u from latex_info import latexdict from astroquery.splatalogue import Splatalogue from line_to_image_list import line_to_image_list, labeldict for spwid in (0,1,2,3): label_col = Column(data=[labeldict[name] for name,_,_,spw in line_to_image_list if spw==spwid], name='Line Name') freq_col = Column(data=[float(freq.strip('GHz')) for _,freq,_,spw in line_to_image_list if spw==spwid], name='Frequency', unit=u.GHz,) EU = [set(Splatalogue.query_lines(freq*(1-0.001/3e5), freq*(1+0.001/3e5))['E_U (K)']) for freq in u.Quantity(freq_col)] #spw_col = Column(data=[spw for _,_,_,spw in line_to_image_list # if spw==spwid], # name='Spectral Window',) tbl = Table([label_col, freq_col,])# spw_col]) latexdict['header_start'] = '\label{{tab:linesspw{0}}}'.format(spwid) latexdict['caption'] = 'Spectral Lines in SPW {0}'.format(spwid) latexdict['tablefoot'] = '' #latexdict['tablefoot'] = ('\par\nJy-Kelvin gives the conversion factor from Jy ' # 'to Kelvin given the synthesized beam size and ' # 'observation frequency.')
slc = sp.slice(xmin, xmax) if len(slc) == 0: continue guesses = [ slc.data.max(), (freq * (1 + v / constants.c)).to(u.GHz).value, (2 * u.km / u.s / constants.c * freq).to(u.GHz).value ] #print(guesses) slc.specfit(guesses=guesses) #print(slc.specfit.parinfo) frq = u.Quantity(slc.specfit.parinfo['SHIFT0'], u.GHz) result = Splatalogue.query_lines( frq + (v - dv_linesearch) / constants.c * frq, frq + (v + dv_linesearch) / constants.c * frq) ref = np.array(result['Freq-GHz']) * u.GHz result.add_column( table.Column(name='velocity', data=-((frq - ref) / (ref) * constants.c).to(u.km / u.s))) linesearch = result['Species', 'Chemical Name', 'Resolved QNs', 'Freq-GHz', 'Meas Freq-GHz', 'velocity', 'E_U (K)'] fits[linename] = { 'pars': slc.specfit.parinfo, 'vel': ((u.Quantity(slc.specfit.parinfo['SHIFT0'].value, u.GHz) - freq) / freq * constants.c.to(u.km / u.s)),
from pyspeckit.spectrum.models import model from pyspeckit.spectrum.models import lte_molecule from spectral_cube import SpectralCube from astropy import units as u from astropy import constants from astropy import log from astropy.io import fits from astroquery.splatalogue import Splatalogue from astropy import modeling from vamdclib import nodes from vamdclib import request as r from vamdclib import specmodel as m from vamdclib import specmodel tbl = Splatalogue.query_lines(210*u.GHz, 235*u.GHz, chemical_name='CH3CN', energy_max=1840, energy_type='eu_k') freqs = np.unique(tbl['Freq-GHz']) vdiff = (np.array((freqs-freqs[0])/freqs[0])*constants.c).to(u.km/u.s) slaim = Splatalogue.query_lines(210*u.GHz, 235*u.GHz, chemical_name='CH3CN', energy_max=1840, 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 ref_freq = 220.74726*u.GHz vdiff = (np.array(-(freqs-ref_freq)/ref_freq)*constants.c).to(u.km/u.s).value
""" import numpy as np import pyspeckit from pyspeckit.spectrum.models import model from pyspeckit.spectrum.models import lte_molecule from spectral_cube import SpectralCube from astropy import units as u from astropy import constants from astropy.io import fits from astroquery.splatalogue import Splatalogue, utils from vamdclib import nodes from vamdclib import request from vamdclib import specmodel tbl = Splatalogue.query_lines(210*u.GHz, 235*u.GHz, chemical_name=' HNCO ', energy_max=2500, energy_type='eu_k') freqs = np.unique(tbl['Freq-GHz']) #vdiff = (np.array((freqs-freqs[0])/freqs[0])*constants.c).to(u.km/u.s) # 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',
from astroquery.splatalogue import Splatalogue line_ids = Splatalogue.get_species_ids() print line_ids
""" import numpy as np import pyspeckit from pyspeckit.spectrum.models import model from pyspeckit.spectrum.models import lte_molecule from spectral_cube import SpectralCube from astropy import units as u from astropy import constants from astropy.io import fits from astroquery.splatalogue import Splatalogue, utils from vamdclib import nodes from vamdclib import request from vamdclib import specmodel tbl = Splatalogue.query_lines(210 * u.GHz, 235 * u.GHz, chemical_name=" HNCO ", energy_max=2500, energy_type="eu_k") freqs = np.unique(tbl["Freq-GHz"]) # vdiff = (np.array((freqs-freqs[0])/freqs[0])*constants.c).to(u.km/u.s) # 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>)"]
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:
pl.rcParams['font.size'] = 10 pl.rcParams['axes.labelsize'] = 12 pl.rcParams['axes.titlesize'] = 14 major_labelsize = 10 minor_labelsize = 8 elif filetype == 'pdf': annotation_fontsize = 8 pl.rcParams['font.size'] = 14 pl.rcParams['axes.labelsize'] = 14 pl.rcParams['axes.titlesize'] = 14 major_labelsize = 10 minor_labelsize = 8 tbl = Splatalogue.query_lines(210 * u.GHz, 235 * u.GHz, chemical_name=' CH3OH', energy_max=1840, energy_type='eu_k') freqs = np.unique(tbl['Freq-GHz']) #vdiff = (np.array((freqs-freqs[0])/freqs[0])*constants.c).to(u.km/u.s) slaim = Splatalogue.query_lines(210 * u.GHz, 235 * u.GHz, chemical_name=' CH3OH', energy_max=1840, 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
else: pass 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 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(
sp.data *= beam.jtok(sp.xarr) sp.unit='K' plot_whole_spectrum(speclist, title=row['source'], figname='fullspectra/{0}.png'.format(row['source']), velocity=row['velocity']*u.km/u.s, ) # Methanol lines (for identification purposes - similar to ch3oh spectral # fit overlays...) from astroquery.splatalogue import Splatalogue Splatalogue.LINES_LIMIT=50000 methanol_lines = Splatalogue.query_lines(218*u.GHz, 235*u.GHz, energy_max=3000, energy_type='eu_k', chemical_name='032.*Methanol') from generic_lte_molecule_model import LTEModel methanolmodel = LTEModel(chemical_name='032.*Methanol') # REQUIRES USING INTENSITY, not Aij methanolmodel_osu = LTEModel(chemical_name='032.*Methanol', line_lists=['OSU'], freq_type='Meas Freq-GHz', energy_max=500000) for row in myvtbl: speclist = [pyspeckit.Spectrum(fn) for fn in glob.glob(paths.spath("{0}_spw*_peak.fits".format(row['source'])))] if len(speclist) == 0: continue
def get_molecular_parameters(molecule_name, molecule_name_jpl=None, tex=50, fmin=1 * u.GHz, fmax=1 * u.THz, line_lists=['SLAIM'], chem_re_flags=0, **kwargs): """ Get the molecular parameters for a molecule from the CDMS database using vamdclib Parameters ---------- molecule_name : string The string name of the molecule (normal name, like CH3OH or CH3CH2OH) molecule_name_jpl : string or None Default to molecule_name, but if jplspec doesn't have your molecule by the right name, specify it here tex : float Optional excitation temperature (basically checks if the partition function calculator works) fmin : quantity with frequency units fmax : quantity with frequency units The minimum and maximum frequency to search over line_lists : list A list of Splatalogue line list catalogs to search. Valid options include SLAIM, CDMS, JPL. Only a single catalog should be used to avoid repetition of transitions and species chem_re_flags : int An integer flag to be passed to splatalogue's chemical name matching tool Examples -------- >>> freqs, aij, deg, EU, partfunc = get_molecular_parameters(molecule_name='CH2CHCN', ... fmin=220*u.GHz, ... fmax=222*u.GHz, ) >>> freqs, aij, deg, EU, partfunc = get_molecular_parameters('CH3OH', ... fmin=90*u.GHz, ... fmax=100*u.GHz) """ from astroquery.splatalogue import Splatalogue from astroquery.jplspec import JPLSpec # do this here, before trying to compute the partition function, because # this query could fail tbl = Splatalogue.query_lines(fmin, fmax, chemical_name=molecule_name, line_lists=line_lists, show_upper_degeneracy=True, **kwargs) if molecule_name_jpl is None: molecule_name_jpl = molecule_name jpltable = JPLSpec.get_species_table()[JPLSpec.get_species_table()['NAME'] == molecule_name_jpl] if len(jpltable) != 1: raise ValueError(f"Too many or too few matches to {molecule_name_jpl}") def partfunc(tem): """ interpolate the partition function WARNING: this can be very wrong """ tem = u.Quantity(tem, u.K).value tems = np.array(jpltable.meta['Temperature (K)']) logQs = jpltable['QLOG1 QLOG2 QLOG3 QLOG4 QLOG5 QLOG6 QLOG7'.split()] logQs = np.array(list(logQs[0])) inds = np.argsort(tems) logQ = np.interp(tem, tems[inds], logQs[inds]) return 10**logQ freqs = (np.array(tbl['Freq-GHz']) * u.GHz if 'Freq-GHz' in tbl.colnames else np.array(tbl['Freq-GHz(rest frame,redshifted)']) * u.GHz) aij = tbl['Log<sub>10</sub> (A<sub>ij</sub>)'] deg = tbl['Upper State Degeneracy'] EU = (np.array(tbl['E_U (K)']) * u.K * constants.k_B).to(u.erg).value return freqs, aij, deg, EU, partfunc
outfile = open('sio_column_estimate_results.txt', 'w') sys.stdout = outfile dw51 = 5.4 * u.kpc warnings.filterwarnings( 'ignore', message='This function (.*) requires loading the entire cube', append=True) warnings.filterwarnings('ignore', message='All-NaN slice encountered') warnings.filterwarnings('ignore', message='invalid value encountered in true_divide') tbl = Splatalogue.query_lines(210 * u.GHz, 235 * u.GHz, chemical_name='SiO', energy_max=1840, energy_type='eu_k') freqs = np.unique(tbl['Freq-GHz']) vdiff = (np.array((freqs - freqs[0]) / freqs[0]) * constants.c).to(u.km / u.s) slaim = Splatalogue.query_lines( 210 * u.GHz, 235 * u.GHz, chemical_name='SiO', energy_max=1840, energy_type='eu_k', line_lists=['SLAIM'], noHFS=True, # there seems to be a problem where HFS # for K >= 6 is included *incorrectly* show_upper_degeneracy=True) freqs = np.array(slaim['Freq-GHz']) * u.GHz
Simbad.add_votable_fields('rv_value') m83simbad = Simbad.query_object('M83') rvel = m83simbad['RV_VALUE'][0]*u.Unit(m83simbad['RV_VALUE'].unit) for fn in m83files: if 'line' in fn: cube = SpectralCube.read(fn) # Convert frequencies to their rest frequencies frange = u.Quantity([cube.spectral_axis.min(), cube.spectral_axis.max()]) * (1+rvel/constants.c) # Query the top 20 most common species in the frequency range of the # cube with an upper energy state <= 50K lines = Splatalogue.query_lines(frange[0], frange[1], top20='top20', energy_max=50, energy_type='eu_k', only_NRAO_recommended=True) lines.pprint() # Change the cube coordinate system to be in velocity with respect # to the rest frequency (in the M83 rest frame) rest_frequency = lines['Freq-GHz'][0]*u.GHz / (1+rvel/constants.c) vcube = cube.with_spectral_unit(u.km/u.s, rest_value=rest_frequency, velocity_convention='radio') # Write the cube with the specified line name fmt = "{Species}{Resolved QNs}" row = lines[0] linename = fmt.format(**dict(zip(row.colnames, row.data))) vcube.write('M83_ALMA_{linename}.fits'.format(linename=linename))